hash
stringlengths
64
64
content
stringlengths
0
1.51M
6dc525e2d67975e58307bf6fdd57e914412b64777265256a4fd8899c5a0de4eb
from sympy.core import S, Integer from sympy.core.function import Function from sympy.core.logic import fuzzy_not from sympy.core.mul import prod from sympy.core.relational import Ne from sympy.core.sorting import default_sort_key from sympy.external.gmpy import SYMPY_INTS from sympy.utilities.iterables import has_dups ############################################################################### ###################### Kronecker Delta, Levi-Civita etc. ###################### ############################################################################### def Eijk(*args, **kwargs): """ Represent the Levi-Civita symbol. This is a compatibility wrapper to ``LeviCivita()``. See Also ======== LeviCivita """ return LeviCivita(*args, **kwargs) def eval_levicivita(*args): """Evaluate Levi-Civita symbol.""" from sympy.functions.combinatorial.factorials import factorial n = len(args) return prod( prod(args[j] - args[i] for j in range(i + 1, n)) / factorial(i) for i in range(n)) # converting factorial(i) to int is slightly faster class LeviCivita(Function): """ Represent the Levi-Civita symbol. Explanation =========== For even permutations of indices it returns 1, for odd permutations -1, and for everything else (a repeated index) it returns 0. Thus it represents an alternating pseudotensor. Examples ======== >>> from sympy import LeviCivita >>> from sympy.abc import i, j, k >>> LeviCivita(1, 2, 3) 1 >>> LeviCivita(1, 3, 2) -1 >>> LeviCivita(1, 2, 2) 0 >>> LeviCivita(i, j, k) LeviCivita(i, j, k) >>> LeviCivita(i, j, i) 0 See Also ======== Eijk """ is_integer = True @classmethod def eval(cls, *args): if all(isinstance(a, (SYMPY_INTS, Integer)) for a in args): return eval_levicivita(*args) if has_dups(args): return S.Zero def doit(self): return eval_levicivita(*self.args) class KroneckerDelta(Function): """ The discrete, or Kronecker, delta function. Explanation =========== A function that takes in two integers $i$ and $j$. It returns $0$ if $i$ and $j$ are not equal, or it returns $1$ if $i$ and $j$ are equal. Examples ======== An example with integer indices: >>> from sympy import KroneckerDelta >>> KroneckerDelta(1, 2) 0 >>> KroneckerDelta(3, 3) 1 Symbolic indices: >>> from sympy.abc import i, j, k >>> KroneckerDelta(i, j) KroneckerDelta(i, j) >>> KroneckerDelta(i, i) 1 >>> KroneckerDelta(i, i + 1) 0 >>> KroneckerDelta(i, i + 1 + k) KroneckerDelta(i, i + k + 1) Parameters ========== i : Number, Symbol The first index of the delta function. j : Number, Symbol The second index of the delta function. See Also ======== eval DiracDelta References ========== .. [1] https://en.wikipedia.org/wiki/Kronecker_delta """ is_integer = True @classmethod def eval(cls, i, j, delta_range=None): """ Evaluates the discrete delta function. Examples ======== >>> from sympy import KroneckerDelta >>> from sympy.abc import i, j, k >>> KroneckerDelta(i, j) KroneckerDelta(i, j) >>> KroneckerDelta(i, i) 1 >>> KroneckerDelta(i, i + 1) 0 >>> KroneckerDelta(i, i + 1 + k) KroneckerDelta(i, i + k + 1) # indirect doctest """ if delta_range is not None: dinf, dsup = delta_range if (dinf - i > 0) == True: return S.Zero if (dinf - j > 0) == True: return S.Zero if (dsup - i < 0) == True: return S.Zero if (dsup - j < 0) == True: return S.Zero diff = i - j if diff.is_zero: return S.One elif fuzzy_not(diff.is_zero): return S.Zero if i.assumptions0.get("below_fermi") and \ j.assumptions0.get("above_fermi"): return S.Zero if j.assumptions0.get("below_fermi") and \ i.assumptions0.get("above_fermi"): return S.Zero # to make KroneckerDelta canonical # following lines will check if inputs are in order # if not, will return KroneckerDelta with correct order if i != min(i, j, key=default_sort_key): if delta_range: return cls(j, i, delta_range) else: return cls(j, i) @property def delta_range(self): if len(self.args) > 2: return self.args[2] def _eval_power(self, expt): if expt.is_positive: return self if expt.is_negative and not -expt is S.One: return 1/self @property def is_above_fermi(self): """ True if Delta can be non-zero above fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, a).is_above_fermi True >>> KroneckerDelta(p, i).is_above_fermi False >>> KroneckerDelta(p, q).is_above_fermi True See Also ======== is_below_fermi, is_only_below_fermi, is_only_above_fermi """ if self.args[0].assumptions0.get("below_fermi"): return False if self.args[1].assumptions0.get("below_fermi"): return False return True @property def is_below_fermi(self): """ True if Delta can be non-zero below fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, a).is_below_fermi False >>> KroneckerDelta(p, i).is_below_fermi True >>> KroneckerDelta(p, q).is_below_fermi True See Also ======== is_above_fermi, is_only_above_fermi, is_only_below_fermi """ if self.args[0].assumptions0.get("above_fermi"): return False if self.args[1].assumptions0.get("above_fermi"): return False return True @property def is_only_above_fermi(self): """ True if Delta is restricted to above fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, a).is_only_above_fermi True >>> KroneckerDelta(p, q).is_only_above_fermi False >>> KroneckerDelta(p, i).is_only_above_fermi False See Also ======== is_above_fermi, is_below_fermi, is_only_below_fermi """ return ( self.args[0].assumptions0.get("above_fermi") or self.args[1].assumptions0.get("above_fermi") ) or False @property def is_only_below_fermi(self): """ True if Delta is restricted to below fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, i).is_only_below_fermi True >>> KroneckerDelta(p, q).is_only_below_fermi False >>> KroneckerDelta(p, a).is_only_below_fermi False See Also ======== is_above_fermi, is_below_fermi, is_only_above_fermi """ return ( self.args[0].assumptions0.get("below_fermi") or self.args[1].assumptions0.get("below_fermi") ) or False @property def indices_contain_equal_information(self): """ Returns True if indices are either both above or below fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, q).indices_contain_equal_information True >>> KroneckerDelta(p, q+1).indices_contain_equal_information True >>> KroneckerDelta(i, p).indices_contain_equal_information False """ if (self.args[0].assumptions0.get("below_fermi") and self.args[1].assumptions0.get("below_fermi")): return True if (self.args[0].assumptions0.get("above_fermi") and self.args[1].assumptions0.get("above_fermi")): return True # if both indices are general we are True, else false return self.is_below_fermi and self.is_above_fermi @property def preferred_index(self): """ Returns the index which is preferred to keep in the final expression. Explanation =========== The preferred index is the index with more information regarding fermi level. If indices contain the same information, 'a' is preferred before 'b'. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> j = Symbol('j', below_fermi=True) >>> p = Symbol('p') >>> KroneckerDelta(p, i).preferred_index i >>> KroneckerDelta(p, a).preferred_index a >>> KroneckerDelta(i, j).preferred_index i See Also ======== killable_index """ if self._get_preferred_index(): return self.args[1] else: return self.args[0] @property def killable_index(self): """ Returns the index which is preferred to substitute in the final expression. Explanation =========== The index to substitute is the index with less information regarding fermi level. If indices contain the same information, 'a' is preferred before 'b'. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> j = Symbol('j', below_fermi=True) >>> p = Symbol('p') >>> KroneckerDelta(p, i).killable_index p >>> KroneckerDelta(p, a).killable_index p >>> KroneckerDelta(i, j).killable_index j See Also ======== preferred_index """ if self._get_preferred_index(): return self.args[0] else: return self.args[1] def _get_preferred_index(self): """ Returns the index which is preferred to keep in the final expression. The preferred index is the index with more information regarding fermi level. If indices contain the same information, index 0 is returned. """ if not self.is_above_fermi: if self.args[0].assumptions0.get("below_fermi"): return 0 else: return 1 elif not self.is_below_fermi: if self.args[0].assumptions0.get("above_fermi"): return 0 else: return 1 else: return 0 @property def indices(self): return self.args[0:2] def _eval_rewrite_as_Piecewise(self, *args, **kwargs): from sympy.functions.elementary.piecewise import Piecewise i, j = args return Piecewise((0, Ne(i, j)), (1, True))
e990edf97fa0072151e784e9497b365f3f7f7baa17c246948721d1920561a085
""" Elliptic Integrals. """ from sympy.core import S, pi, I, Rational from sympy.core.function import Function, ArgumentIndexError from sympy.core.symbol import Dummy from sympy.functions.elementary.complexes import sign from sympy.functions.elementary.hyperbolic import atanh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin, tan from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import hyper, meijerg class elliptic_k(Function): r""" The complete elliptic integral of the first kind, defined by .. math:: K(m) = F\left(\tfrac{\pi}{2}\middle| m\right) where $F\left(z\middle| m\right)$ is the Legendre incomplete elliptic integral of the first kind. Explanation =========== The function $K(m)$ is a single-valued function on the complex plane with branch cut along the interval $(1, \infty)$. Note that our notation defines the incomplete elliptic integral in terms of the parameter $m$ instead of the elliptic modulus (eccentricity) $k$. In this case, the parameter $m$ is defined as $m=k^2$. Examples ======== >>> from sympy import elliptic_k, I >>> from sympy.abc import m >>> elliptic_k(0) pi/2 >>> elliptic_k(1.0 + I) 1.50923695405127 + 0.625146415202697*I >>> elliptic_k(m).series(n=3) pi/2 + pi*m/8 + 9*pi*m**2/128 + O(m**3) See Also ======== elliptic_f References ========== .. [1] https://en.wikipedia.org/wiki/Elliptic_integrals .. [2] http://functions.wolfram.com/EllipticIntegrals/EllipticK """ @classmethod def eval(cls, m): if m.is_zero: return pi*S.Half elif m is S.Half: return 8*pi**Rational(3, 2)/gamma(Rational(-1, 4))**2 elif m is S.One: return S.ComplexInfinity elif m is S.NegativeOne: return gamma(Rational(1, 4))**2/(4*sqrt(2*pi)) elif m in (S.Infinity, S.NegativeInfinity, I*S.Infinity, I*S.NegativeInfinity, S.ComplexInfinity): return S.Zero def fdiff(self, argindex=1): m = self.args[0] return (elliptic_e(m) - (1 - m)*elliptic_k(m))/(2*m*(1 - m)) def _eval_conjugate(self): m = self.args[0] if (m.is_real and (m - 1).is_positive) is False: return self.func(m.conjugate()) def _eval_nseries(self, x, n, logx, cdir=0): from sympy.simplify import hyperexpand return hyperexpand(self.rewrite(hyper)._eval_nseries(x, n=n, logx=logx)) def _eval_rewrite_as_hyper(self, m, **kwargs): return pi*S.Half*hyper((S.Half, S.Half), (S.One,), m) def _eval_rewrite_as_meijerg(self, m, **kwargs): return meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -m)/2 def _eval_is_zero(self): m = self.args[0] if m.is_infinite: return True def _eval_rewrite_as_Integral(self, *args): from sympy.integrals.integrals import Integral t = Dummy('t') m = self.args[0] return Integral(1/sqrt(1 - m*sin(t)**2), (t, 0, pi/2)) class elliptic_f(Function): r""" The Legendre incomplete elliptic integral of the first kind, defined by .. math:: F\left(z\middle| m\right) = \int_0^z \frac{dt}{\sqrt{1 - m \sin^2 t}} Explanation =========== This function reduces to a complete elliptic integral of the first kind, $K(m)$, when $z = \pi/2$. Note that our notation defines the incomplete elliptic integral in terms of the parameter $m$ instead of the elliptic modulus (eccentricity) $k$. In this case, the parameter $m$ is defined as $m=k^2$. Examples ======== >>> from sympy import elliptic_f, I >>> from sympy.abc import z, m >>> elliptic_f(z, m).series(z) z + z**5*(3*m**2/40 - m/30) + m*z**3/6 + O(z**6) >>> elliptic_f(3.0 + I/2, 1.0 + I) 2.909449841483 + 1.74720545502474*I See Also ======== elliptic_k References ========== .. [1] https://en.wikipedia.org/wiki/Elliptic_integrals .. [2] http://functions.wolfram.com/EllipticIntegrals/EllipticF """ @classmethod def eval(cls, z, m): if z.is_zero: return S.Zero if m.is_zero: return z k = 2*z/pi if k.is_integer: return k*elliptic_k(m) elif m in (S.Infinity, S.NegativeInfinity): return S.Zero elif z.could_extract_minus_sign(): return -elliptic_f(-z, m) def fdiff(self, argindex=1): z, m = self.args fm = sqrt(1 - m*sin(z)**2) if argindex == 1: return 1/fm elif argindex == 2: return (elliptic_e(z, m)/(2*m*(1 - m)) - elliptic_f(z, m)/(2*m) - sin(2*z)/(4*(1 - m)*fm)) raise ArgumentIndexError(self, argindex) def _eval_conjugate(self): z, m = self.args if (m.is_real and (m - 1).is_positive) is False: return self.func(z.conjugate(), m.conjugate()) def _eval_rewrite_as_Integral(self, *args): from sympy.integrals.integrals import Integral t = Dummy('t') z, m = self.args[0], self.args[1] return Integral(1/(sqrt(1 - m*sin(t)**2)), (t, 0, z)) def _eval_is_zero(self): z, m = self.args if z.is_zero: return True if m.is_extended_real and m.is_infinite: return True class elliptic_e(Function): r""" Called with two arguments $z$ and $m$, evaluates the incomplete elliptic integral of the second kind, defined by .. math:: E\left(z\middle| m\right) = \int_0^z \sqrt{1 - m \sin^2 t} dt Called with a single argument $m$, evaluates the Legendre complete elliptic integral of the second kind .. math:: E(m) = E\left(\tfrac{\pi}{2}\middle| m\right) Explanation =========== The function $E(m)$ is a single-valued function on the complex plane with branch cut along the interval $(1, \infty)$. Note that our notation defines the incomplete elliptic integral in terms of the parameter $m$ instead of the elliptic modulus (eccentricity) $k$. In this case, the parameter $m$ is defined as $m=k^2$. Examples ======== >>> from sympy import elliptic_e, I >>> from sympy.abc import z, m >>> elliptic_e(z, m).series(z) z + z**5*(-m**2/40 + m/30) - m*z**3/6 + O(z**6) >>> elliptic_e(m).series(n=4) pi/2 - pi*m/8 - 3*pi*m**2/128 - 5*pi*m**3/512 + O(m**4) >>> elliptic_e(1 + I, 2 - I/2).n() 1.55203744279187 + 0.290764986058437*I >>> elliptic_e(0) pi/2 >>> elliptic_e(2.0 - I) 0.991052601328069 + 0.81879421395609*I References ========== .. [1] https://en.wikipedia.org/wiki/Elliptic_integrals .. [2] http://functions.wolfram.com/EllipticIntegrals/EllipticE2 .. [3] http://functions.wolfram.com/EllipticIntegrals/EllipticE """ @classmethod def eval(cls, m, z=None): if z is not None: z, m = m, z k = 2*z/pi if m.is_zero: return z if z.is_zero: return S.Zero elif k.is_integer: return k*elliptic_e(m) elif m in (S.Infinity, S.NegativeInfinity): return S.ComplexInfinity elif z.could_extract_minus_sign(): return -elliptic_e(-z, m) else: if m.is_zero: return pi/2 elif m is S.One: return S.One elif m is S.Infinity: return I*S.Infinity elif m is S.NegativeInfinity: return S.Infinity elif m is S.ComplexInfinity: return S.ComplexInfinity def fdiff(self, argindex=1): if len(self.args) == 2: z, m = self.args if argindex == 1: return sqrt(1 - m*sin(z)**2) elif argindex == 2: return (elliptic_e(z, m) - elliptic_f(z, m))/(2*m) else: m = self.args[0] if argindex == 1: return (elliptic_e(m) - elliptic_k(m))/(2*m) raise ArgumentIndexError(self, argindex) def _eval_conjugate(self): if len(self.args) == 2: z, m = self.args if (m.is_real and (m - 1).is_positive) is False: return self.func(z.conjugate(), m.conjugate()) else: m = self.args[0] if (m.is_real and (m - 1).is_positive) is False: return self.func(m.conjugate()) def _eval_nseries(self, x, n, logx, cdir=0): from sympy.simplify import hyperexpand if len(self.args) == 1: return hyperexpand(self.rewrite(hyper)._eval_nseries(x, n=n, logx=logx)) return super()._eval_nseries(x, n=n, logx=logx) def _eval_rewrite_as_hyper(self, *args, **kwargs): if len(args) == 1: m = args[0] return (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), m) def _eval_rewrite_as_meijerg(self, *args, **kwargs): if len(args) == 1: m = args[0] return -meijerg(((S.Half, Rational(3, 2)), []), \ ((S.Zero,), (S.Zero,)), -m)/4 def _eval_rewrite_as_Integral(self, *args): from sympy.integrals.integrals import Integral z, m = (pi/2, self.args[0]) if len(self.args) == 1 else self.args t = Dummy('t') return Integral(sqrt(1 - m*sin(t)**2), (t, 0, z)) class elliptic_pi(Function): r""" Called with three arguments $n$, $z$ and $m$, evaluates the Legendre incomplete elliptic integral of the third kind, defined by .. math:: \Pi\left(n; z\middle| m\right) = \int_0^z \frac{dt} {\left(1 - n \sin^2 t\right) \sqrt{1 - m \sin^2 t}} Called with two arguments $n$ and $m$, evaluates the complete elliptic integral of the third kind: .. math:: \Pi\left(n\middle| m\right) = \Pi\left(n; \tfrac{\pi}{2}\middle| m\right) Explanation =========== Note that our notation defines the incomplete elliptic integral in terms of the parameter $m$ instead of the elliptic modulus (eccentricity) $k$. In this case, the parameter $m$ is defined as $m=k^2$. Examples ======== >>> from sympy import elliptic_pi, I >>> from sympy.abc import z, n, m >>> elliptic_pi(n, z, m).series(z, n=4) z + z**3*(m/6 + n/3) + O(z**4) >>> elliptic_pi(0.5 + I, 1.0 - I, 1.2) 2.50232379629182 - 0.760939574180767*I >>> elliptic_pi(0, 0) pi/2 >>> elliptic_pi(1.0 - I/3, 2.0 + I) 3.29136443417283 + 0.32555634906645*I References ========== .. [1] https://en.wikipedia.org/wiki/Elliptic_integrals .. [2] http://functions.wolfram.com/EllipticIntegrals/EllipticPi3 .. [3] http://functions.wolfram.com/EllipticIntegrals/EllipticPi """ @classmethod def eval(cls, n, m, z=None): if z is not None: n, z, m = n, m, z if n.is_zero: return elliptic_f(z, m) elif n is S.One: return (elliptic_f(z, m) + (sqrt(1 - m*sin(z)**2)*tan(z) - elliptic_e(z, m))/(1 - m)) k = 2*z/pi if k.is_integer: return k*elliptic_pi(n, m) elif m.is_zero: return atanh(sqrt(n - 1)*tan(z))/sqrt(n - 1) elif n == m: return (elliptic_f(z, n) - elliptic_pi(1, z, n) + tan(z)/sqrt(1 - n*sin(z)**2)) elif n in (S.Infinity, S.NegativeInfinity): return S.Zero elif m in (S.Infinity, S.NegativeInfinity): return S.Zero elif z.could_extract_minus_sign(): return -elliptic_pi(n, -z, m) if n.is_zero: return elliptic_f(z, m) if m.is_extended_real and m.is_infinite or \ n.is_extended_real and n.is_infinite: return S.Zero else: if n.is_zero: return elliptic_k(m) elif n is S.One: return S.ComplexInfinity elif m.is_zero: return pi/(2*sqrt(1 - n)) elif m == S.One: return S.NegativeInfinity/sign(n - 1) elif n == m: return elliptic_e(n)/(1 - n) elif n in (S.Infinity, S.NegativeInfinity): return S.Zero elif m in (S.Infinity, S.NegativeInfinity): return S.Zero if n.is_zero: return elliptic_k(m) if m.is_extended_real and m.is_infinite or \ n.is_extended_real and n.is_infinite: return S.Zero def _eval_conjugate(self): if len(self.args) == 3: n, z, m = self.args if (n.is_real and (n - 1).is_positive) is False and \ (m.is_real and (m - 1).is_positive) is False: return self.func(n.conjugate(), z.conjugate(), m.conjugate()) else: n, m = self.args return self.func(n.conjugate(), m.conjugate()) def fdiff(self, argindex=1): if len(self.args) == 3: n, z, m = self.args fm, fn = sqrt(1 - m*sin(z)**2), 1 - n*sin(z)**2 if argindex == 1: return (elliptic_e(z, m) + (m - n)*elliptic_f(z, m)/n + (n**2 - m)*elliptic_pi(n, z, m)/n - n*fm*sin(2*z)/(2*fn))/(2*(m - n)*(n - 1)) elif argindex == 2: return 1/(fm*fn) elif argindex == 3: return (elliptic_e(z, m)/(m - 1) + elliptic_pi(n, z, m) - m*sin(2*z)/(2*(m - 1)*fm))/(2*(n - m)) else: n, m = self.args if argindex == 1: return (elliptic_e(m) + (m - n)*elliptic_k(m)/n + (n**2 - m)*elliptic_pi(n, m)/n)/(2*(m - n)*(n - 1)) elif argindex == 2: return (elliptic_e(m)/(m - 1) + elliptic_pi(n, m))/(2*(n - m)) raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_Integral(self, *args): from sympy.integrals.integrals import Integral if len(self.args) == 2: n, m, z = self.args[0], self.args[1], pi/2 else: n, z, m = self.args t = Dummy('t') return Integral(1/((1 - n*sin(t)**2)*sqrt(1 - m*sin(t)**2)), (t, 0, z))
cd3143634bc11627cd065576420a3c7a3d120c4169755e7e1dc77a99df1cb4dd
""" This module contains various functions that are special cases of incomplete gamma functions. It should probably be renamed. """ from sympy.core import Add, S, sympify, cacheit, pi, I, Rational, EulerGamma from sympy.core.function import Function, ArgumentIndexError, expand_mul from sympy.core.relational import is_eq from sympy.core.power import Pow from sympy.core.symbol import Symbol from sympy.functions.combinatorial.factorials import factorial, factorial2, RisingFactorial from sympy.functions.elementary.complexes import re from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt, root from sympy.functions.elementary.exponential import exp, log, exp_polar from sympy.functions.elementary.complexes import polar_lift, unpolarify from sympy.functions.elementary.hyperbolic import cosh, sinh from sympy.functions.elementary.trigonometric import cos, sin, sinc from sympy.functions.special.hyper import hyper, meijerg # TODO series expansions # TODO see the "Note:" in Ei # Helper function def real_to_real_as_real_imag(self, deep=True, **hints): if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: x, y = self.args[0].expand(deep, **hints).as_real_imag() else: x, y = self.args[0].as_real_imag() re = (self.func(x + I*y) + self.func(x - I*y))/2 im = (self.func(x + I*y) - self.func(x - I*y))/(2*I) return (re, im) ############################################################################### ################################ ERROR FUNCTION ############################### ############################################################################### class erf(Function): r""" The Gauss error function. Explanation =========== This function is defined as: .. math :: \mathrm{erf}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{-t^2} \mathrm{d}t. Examples ======== >>> from sympy import I, oo, erf >>> from sympy.abc import z Several special values are known: >>> erf(0) 0 >>> erf(oo) 1 >>> erf(-oo) -1 >>> erf(I*oo) oo*I >>> erf(-I*oo) -oo*I In general one can pull out factors of -1 and $I$ from the argument: >>> erf(-z) -erf(z) The error function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(erf(z)) erf(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(erf(z), z) 2*exp(-z**2)/sqrt(pi) We can numerically evaluate the error function to arbitrary precision on the whole complex plane: >>> erf(4).evalf(30) 0.999999984582742099719981147840 >>> erf(-4*I).evalf(30) -1296959.73071763923152794095062*I See Also ======== erfc: Complementary error function. erfi: Imaginary error function. erf2: Two-argument error function. erfinv: Inverse error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function .. [2] http://dlmf.nist.gov/7 .. [3] http://mathworld.wolfram.com/Erf.html .. [4] http://functions.wolfram.com/GammaBetaErf/Erf """ unbranched = True def fdiff(self, argindex=1): if argindex == 1: return 2*exp(-self.args[0]**2)/sqrt(S.Pi) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return erfinv @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.One elif arg is S.NegativeInfinity: return S.NegativeOne elif arg.is_zero: return S.Zero if isinstance(arg, erfinv): return arg.args[0] if isinstance(arg, erfcinv): return S.One - arg.args[0] if arg.is_zero: return S.Zero # Only happens with unevaluated erf2inv if isinstance(arg, erf2inv) and arg.args[0].is_zero: return arg.args[1] # Try to pull out factors of I t = arg.extract_multiplicatively(S.ImaginaryUnit) if t in (S.Infinity, S.NegativeInfinity): return arg # Try to pull out factors of -1 if arg.could_extract_minus_sign(): return -cls(-arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) k = floor((n - 1)/S(2)) if len(previous_terms) > 2: return -previous_terms[-2] * x**2 * (n - 2)/(n*k) else: return 2*S.NegativeOne**k * x**n/(n*factorial(k)*sqrt(S.Pi)) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_real(self): return self.args[0].is_extended_real def _eval_is_finite(self): if self.args[0].is_finite: return True else: return self.args[0].is_extended_real def _eval_is_zero(self): return self.args[0].is_zero def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return sqrt(z**2)/z*(S.One - uppergamma(S.Half, z**2)/sqrt(S.Pi)) def _eval_rewrite_as_fresnels(self, z, **kwargs): arg = (S.One - S.ImaginaryUnit)*z/sqrt(pi) return (S.One + S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_fresnelc(self, z, **kwargs): arg = (S.One - S.ImaginaryUnit)*z/sqrt(pi) return (S.One + S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_meijerg(self, z, **kwargs): return z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2) def _eval_rewrite_as_hyper(self, z, **kwargs): return 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], -z**2) def _eval_rewrite_as_expint(self, z, **kwargs): return sqrt(z**2)/z - z*expint(S.Half, z**2)/sqrt(S.Pi) def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): from sympy.series.limits import limit if limitvar: lim = limit(z, limitvar, S.Infinity) if lim is S.NegativeInfinity: return S.NegativeOne + _erfs(-z)*exp(-z**2) return S.One - _erfs(z)*exp(-z**2) def _eval_rewrite_as_erfc(self, z, **kwargs): return S.One - erfc(z) def _eval_rewrite_as_erfi(self, z, **kwargs): return -I*erfi(I*z) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.ComplexInfinity: arg0 = arg.limit(x, 0, dir='-' if cdir == -1 else '+') if x in arg.free_symbols and arg0.is_zero: return 2*arg/sqrt(pi) else: return self.func(arg0) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order from sympy.functions.elementary.integers import ceiling point = args0[0] if point in [S.Infinity, S.NegativeInfinity]: z = self.args[0] try: _, ex = z.leadterm(x) except (ValueError, NotImplementedError): return self ex = -ex # as x->1/x for aseries if ex.is_positive: newn = ceiling(n/ex) s = [S.NegativeOne**k * factorial2(2*k - 1) / (z**(2*k + 1) * 2**k) for k in range(0, newn)] + [Order(1/z**newn, x)] return S.One - (exp(-z**2)/sqrt(pi)) * Add(*s) return super(erf, self)._eval_aseries(n, args0, x, logx) as_real_imag = real_to_real_as_real_imag class erfc(Function): r""" Complementary Error Function. Explanation =========== The function is defined as: .. math :: \mathrm{erfc}(x) = \frac{2}{\sqrt{\pi}} \int_x^\infty e^{-t^2} \mathrm{d}t Examples ======== >>> from sympy import I, oo, erfc >>> from sympy.abc import z Several special values are known: >>> erfc(0) 1 >>> erfc(oo) 0 >>> erfc(-oo) 2 >>> erfc(I*oo) -oo*I >>> erfc(-I*oo) oo*I The error function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(erfc(z)) erfc(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(erfc(z), z) -2*exp(-z**2)/sqrt(pi) It also follows >>> erfc(-z) 2 - erfc(z) We can numerically evaluate the complementary error function to arbitrary precision on the whole complex plane: >>> erfc(4).evalf(30) 0.0000000154172579002800188521596734869 >>> erfc(4*I).evalf(30) 1.0 - 1296959.73071763923152794095062*I See Also ======== erf: Gaussian error function. erfi: Imaginary error function. erf2: Two-argument error function. erfinv: Inverse error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function .. [2] http://dlmf.nist.gov/7 .. [3] http://mathworld.wolfram.com/Erfc.html .. [4] http://functions.wolfram.com/GammaBetaErf/Erfc """ unbranched = True def fdiff(self, argindex=1): if argindex == 1: return -2*exp(-self.args[0]**2)/sqrt(S.Pi) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return erfcinv @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg.is_zero: return S.One if isinstance(arg, erfinv): return S.One - arg.args[0] if isinstance(arg, erfcinv): return arg.args[0] if arg.is_zero: return S.One # Try to pull out factors of I t = arg.extract_multiplicatively(S.ImaginaryUnit) if t in (S.Infinity, S.NegativeInfinity): return -arg # Try to pull out factors of -1 if arg.could_extract_minus_sign(): return 2 - cls(-arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.One elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) k = floor((n - 1)/S(2)) if len(previous_terms) > 2: return -previous_terms[-2] * x**2 * (n - 2)/(n*k) else: return -2*S.NegativeOne**k * x**n/(n*factorial(k)*sqrt(S.Pi)) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_real(self): return self.args[0].is_extended_real def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return self.rewrite(erf).rewrite("tractable", deep=True, limitvar=limitvar) def _eval_rewrite_as_erf(self, z, **kwargs): return S.One - erf(z) def _eval_rewrite_as_erfi(self, z, **kwargs): return S.One + I*erfi(I*z) def _eval_rewrite_as_fresnels(self, z, **kwargs): arg = (S.One - S.ImaginaryUnit)*z/sqrt(pi) return S.One - (S.One + S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_fresnelc(self, z, **kwargs): arg = (S.One-S.ImaginaryUnit)*z/sqrt(pi) return S.One - (S.One + S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_meijerg(self, z, **kwargs): return S.One - z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2) def _eval_rewrite_as_hyper(self, z, **kwargs): return S.One - 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], -z**2) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return S.One - sqrt(z**2)/z*(S.One - uppergamma(S.Half, z**2)/sqrt(S.Pi)) def _eval_rewrite_as_expint(self, z, **kwargs): return S.One - sqrt(z**2)/z + z*expint(S.Half, z**2)/sqrt(S.Pi) def _eval_expand_func(self, **hints): return self.rewrite(erf) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.ComplexInfinity: arg0 = arg.limit(x, 0, dir='-' if cdir == -1 else '+') if arg0.is_zero: return S.One else: return self.func(arg0) as_real_imag = real_to_real_as_real_imag def _eval_aseries(self, n, args0, x, logx): return S.One - erf(*self.args)._eval_aseries(n, args0, x, logx) class erfi(Function): r""" Imaginary error function. Explanation =========== The function erfi is defined as: .. math :: \mathrm{erfi}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{t^2} \mathrm{d}t Examples ======== >>> from sympy import I, oo, erfi >>> from sympy.abc import z Several special values are known: >>> erfi(0) 0 >>> erfi(oo) oo >>> erfi(-oo) -oo >>> erfi(I*oo) I >>> erfi(-I*oo) -I In general one can pull out factors of -1 and $I$ from the argument: >>> erfi(-z) -erfi(z) >>> from sympy import conjugate >>> conjugate(erfi(z)) erfi(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(erfi(z), z) 2*exp(z**2)/sqrt(pi) We can numerically evaluate the imaginary error function to arbitrary precision on the whole complex plane: >>> erfi(2).evalf(30) 18.5648024145755525987042919132 >>> erfi(-2*I).evalf(30) -0.995322265018952734162069256367*I See Also ======== erf: Gaussian error function. erfc: Complementary error function. erf2: Two-argument error function. erfinv: Inverse error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function .. [2] http://mathworld.wolfram.com/Erfi.html .. [3] http://functions.wolfram.com/GammaBetaErf/Erfi """ unbranched = True def fdiff(self, argindex=1): if argindex == 1: return 2*exp(self.args[0]**2)/sqrt(S.Pi) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, z): if z.is_Number: if z is S.NaN: return S.NaN elif z.is_zero: return S.Zero elif z is S.Infinity: return S.Infinity if z.is_zero: return S.Zero # Try to pull out factors of -1 if z.could_extract_minus_sign(): return -cls(-z) # Try to pull out factors of I nz = z.extract_multiplicatively(I) if nz is not None: if nz is S.Infinity: return I if isinstance(nz, erfinv): return I*nz.args[0] if isinstance(nz, erfcinv): return I*(S.One - nz.args[0]) # Only happens with unevaluated erf2inv if isinstance(nz, erf2inv) and nz.args[0].is_zero: return I*nz.args[1] @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) k = floor((n - 1)/S(2)) if len(previous_terms) > 2: return previous_terms[-2] * x**2 * (n - 2)/(n*k) else: return 2 * x**n/(n*factorial(k)*sqrt(S.Pi)) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_extended_real(self): return self.args[0].is_extended_real def _eval_is_zero(self): return self.args[0].is_zero def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return self.rewrite(erf).rewrite("tractable", deep=True, limitvar=limitvar) def _eval_rewrite_as_erf(self, z, **kwargs): return -I*erf(I*z) def _eval_rewrite_as_erfc(self, z, **kwargs): return I*erfc(I*z) - I def _eval_rewrite_as_fresnels(self, z, **kwargs): arg = (S.One + S.ImaginaryUnit)*z/sqrt(pi) return (S.One - S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_fresnelc(self, z, **kwargs): arg = (S.One + S.ImaginaryUnit)*z/sqrt(pi) return (S.One - S.ImaginaryUnit)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_meijerg(self, z, **kwargs): return z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], -z**2) def _eval_rewrite_as_hyper(self, z, **kwargs): return 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], z**2) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return sqrt(-z**2)/z*(uppergamma(S.Half, -z**2)/sqrt(S.Pi) - S.One) def _eval_rewrite_as_expint(self, z, **kwargs): return sqrt(-z**2)/z - z*expint(S.Half, -z**2)/sqrt(S.Pi) def _eval_expand_func(self, **hints): return self.rewrite(erf) as_real_imag = real_to_real_as_real_imag def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if x in arg.free_symbols and arg0.is_zero: return 2*arg/sqrt(pi) elif arg0.is_finite: return self.func(arg0) return self.func(arg) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] if point is S.Infinity: z = self.args[0] s = [factorial2(2*k - 1) / (2**k * z**(2*k + 1)) for k in range(0, n)] + [Order(1/z**n, x)] return -S.ImaginaryUnit + (exp(z**2)/sqrt(pi)) * Add(*s) return super(erfi, self)._eval_aseries(n, args0, x, logx) class erf2(Function): r""" Two-argument error function. Explanation =========== This function is defined as: .. math :: \mathrm{erf2}(x, y) = \frac{2}{\sqrt{\pi}} \int_x^y e^{-t^2} \mathrm{d}t Examples ======== >>> from sympy import oo, erf2 >>> from sympy.abc import x, y Several special values are known: >>> erf2(0, 0) 0 >>> erf2(x, x) 0 >>> erf2(x, oo) 1 - erf(x) >>> erf2(x, -oo) -erf(x) - 1 >>> erf2(oo, y) erf(y) - 1 >>> erf2(-oo, y) erf(y) + 1 In general one can pull out factors of -1: >>> erf2(-x, -y) -erf2(x, y) The error function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(erf2(x, y)) erf2(conjugate(x), conjugate(y)) Differentiation with respect to $x$, $y$ is supported: >>> from sympy import diff >>> diff(erf2(x, y), x) -2*exp(-x**2)/sqrt(pi) >>> diff(erf2(x, y), y) 2*exp(-y**2)/sqrt(pi) See Also ======== erf: Gaussian error function. erfc: Complementary error function. erfi: Imaginary error function. erfinv: Inverse error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] http://functions.wolfram.com/GammaBetaErf/Erf2/ """ def fdiff(self, argindex): x, y = self.args if argindex == 1: return -2*exp(-x**2)/sqrt(S.Pi) elif argindex == 2: return 2*exp(-y**2)/sqrt(S.Pi) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, x, y): chk = (S.Infinity, S.NegativeInfinity, S.Zero) if x is S.NaN or y is S.NaN: return S.NaN elif x == y: return S.Zero elif x in chk or y in chk: return erf(y) - erf(x) if isinstance(y, erf2inv) and y.args[0] == x: return y.args[1] if x.is_zero or y.is_zero or x.is_extended_real and x.is_infinite or \ y.is_extended_real and y.is_infinite: return erf(y) - erf(x) #Try to pull out -1 factor sign_x = x.could_extract_minus_sign() sign_y = y.could_extract_minus_sign() if (sign_x and sign_y): return -cls(-x, -y) elif (sign_x or sign_y): return erf(y)-erf(x) def _eval_conjugate(self): return self.func(self.args[0].conjugate(), self.args[1].conjugate()) def _eval_is_extended_real(self): return self.args[0].is_extended_real and self.args[1].is_extended_real def _eval_rewrite_as_erf(self, x, y, **kwargs): return erf(y) - erf(x) def _eval_rewrite_as_erfc(self, x, y, **kwargs): return erfc(x) - erfc(y) def _eval_rewrite_as_erfi(self, x, y, **kwargs): return I*(erfi(I*x)-erfi(I*y)) def _eval_rewrite_as_fresnels(self, x, y, **kwargs): return erf(y).rewrite(fresnels) - erf(x).rewrite(fresnels) def _eval_rewrite_as_fresnelc(self, x, y, **kwargs): return erf(y).rewrite(fresnelc) - erf(x).rewrite(fresnelc) def _eval_rewrite_as_meijerg(self, x, y, **kwargs): return erf(y).rewrite(meijerg) - erf(x).rewrite(meijerg) def _eval_rewrite_as_hyper(self, x, y, **kwargs): return erf(y).rewrite(hyper) - erf(x).rewrite(hyper) def _eval_rewrite_as_uppergamma(self, x, y, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return (sqrt(y**2)/y*(S.One - uppergamma(S.Half, y**2)/sqrt(S.Pi)) - sqrt(x**2)/x*(S.One - uppergamma(S.Half, x**2)/sqrt(S.Pi))) def _eval_rewrite_as_expint(self, x, y, **kwargs): return erf(y).rewrite(expint) - erf(x).rewrite(expint) def _eval_expand_func(self, **hints): return self.rewrite(erf) def _eval_is_zero(self): return is_eq(*self.args) class erfinv(Function): r""" Inverse Error Function. The erfinv function is defined as: .. math :: \mathrm{erf}(x) = y \quad \Rightarrow \quad \mathrm{erfinv}(y) = x Examples ======== >>> from sympy import erfinv >>> from sympy.abc import x Several special values are known: >>> erfinv(0) 0 >>> erfinv(1) oo Differentiation with respect to $x$ is supported: >>> from sympy import diff >>> diff(erfinv(x), x) sqrt(pi)*exp(erfinv(x)**2)/2 We can numerically evaluate the inverse error function to arbitrary precision on [-1, 1]: >>> erfinv(0.2).evalf(30) 0.179143454621291692285822705344 See Also ======== erf: Gaussian error function. erfc: Complementary error function. erfi: Imaginary error function. erf2: Two-argument error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function#Inverse_functions .. [2] http://functions.wolfram.com/GammaBetaErf/InverseErf/ """ def fdiff(self, argindex =1): if argindex == 1: return sqrt(S.Pi)*exp(self.func(self.args[0])**2)*S.Half else : raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return erf @classmethod def eval(cls, z): if z is S.NaN: return S.NaN elif z is S.NegativeOne: return S.NegativeInfinity elif z.is_zero: return S.Zero elif z is S.One: return S.Infinity if isinstance(z, erf) and z.args[0].is_extended_real: return z.args[0] if z.is_zero: return S.Zero # Try to pull out factors of -1 nz = z.extract_multiplicatively(-1) if nz is not None and (isinstance(nz, erf) and (nz.args[0]).is_extended_real): return -nz.args[0] def _eval_rewrite_as_erfcinv(self, z, **kwargs): return erfcinv(1-z) def _eval_is_zero(self): return self.args[0].is_zero class erfcinv (Function): r""" Inverse Complementary Error Function. The erfcinv function is defined as: .. math :: \mathrm{erfc}(x) = y \quad \Rightarrow \quad \mathrm{erfcinv}(y) = x Examples ======== >>> from sympy import erfcinv >>> from sympy.abc import x Several special values are known: >>> erfcinv(1) 0 >>> erfcinv(0) oo Differentiation with respect to $x$ is supported: >>> from sympy import diff >>> diff(erfcinv(x), x) -sqrt(pi)*exp(erfcinv(x)**2)/2 See Also ======== erf: Gaussian error function. erfc: Complementary error function. erfi: Imaginary error function. erf2: Two-argument error function. erfinv: Inverse error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function#Inverse_functions .. [2] http://functions.wolfram.com/GammaBetaErf/InverseErfc/ """ def fdiff(self, argindex =1): if argindex == 1: return -sqrt(S.Pi)*exp(self.func(self.args[0])**2)*S.Half else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return erfc @classmethod def eval(cls, z): if z is S.NaN: return S.NaN elif z.is_zero: return S.Infinity elif z is S.One: return S.Zero elif z == 2: return S.NegativeInfinity if z.is_zero: return S.Infinity def _eval_rewrite_as_erfinv(self, z, **kwargs): return erfinv(1-z) def _eval_is_zero(self): return (self.args[0] - 1).is_zero def _eval_is_infinite(self): return self.args[0].is_zero class erf2inv(Function): r""" Two-argument Inverse error function. The erf2inv function is defined as: .. math :: \mathrm{erf2}(x, w) = y \quad \Rightarrow \quad \mathrm{erf2inv}(x, y) = w Examples ======== >>> from sympy import erf2inv, oo >>> from sympy.abc import x, y Several special values are known: >>> erf2inv(0, 0) 0 >>> erf2inv(1, 0) 1 >>> erf2inv(0, 1) oo >>> erf2inv(0, y) erfinv(y) >>> erf2inv(oo, y) erfcinv(-y) Differentiation with respect to $x$ and $y$ is supported: >>> from sympy import diff >>> diff(erf2inv(x, y), x) exp(-x**2 + erf2inv(x, y)**2) >>> diff(erf2inv(x, y), y) sqrt(pi)*exp(erf2inv(x, y)**2)/2 See Also ======== erf: Gaussian error function. erfc: Complementary error function. erfi: Imaginary error function. erf2: Two-argument error function. erfinv: Inverse error function. erfcinv: Inverse complementary error function. References ========== .. [1] http://functions.wolfram.com/GammaBetaErf/InverseErf2/ """ def fdiff(self, argindex): x, y = self.args if argindex == 1: return exp(self.func(x,y)**2-x**2) elif argindex == 2: return sqrt(S.Pi)*S.Half*exp(self.func(x,y)**2) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, x, y): if x is S.NaN or y is S.NaN: return S.NaN elif x.is_zero and y.is_zero: return S.Zero elif x.is_zero and y is S.One: return S.Infinity elif x is S.One and y.is_zero: return S.One elif x.is_zero: return erfinv(y) elif x is S.Infinity: return erfcinv(-y) elif y.is_zero: return x elif y is S.Infinity: return erfinv(x) if x.is_zero: if y.is_zero: return S.Zero else: return erfinv(y) if y.is_zero: return x def _eval_is_zero(self): x, y = self.args if x.is_zero and y.is_zero: return True ############################################################################### #################### EXPONENTIAL INTEGRALS #################################### ############################################################################### class Ei(Function): r""" The classical exponential integral. Explanation =========== For use in SymPy, this function is defined as .. math:: \operatorname{Ei}(x) = \sum_{n=1}^\infty \frac{x^n}{n\, n!} + \log(x) + \gamma, where $\gamma$ is the Euler-Mascheroni constant. If $x$ is a polar number, this defines an analytic function on the Riemann surface of the logarithm. Otherwise this defines an analytic function in the cut plane $\mathbb{C} \setminus (-\infty, 0]$. **Background** The name exponential integral comes from the following statement: .. math:: \operatorname{Ei}(x) = \int_{-\infty}^x \frac{e^t}{t} \mathrm{d}t If the integral is interpreted as a Cauchy principal value, this statement holds for $x > 0$ and $\operatorname{Ei}(x)$ as defined above. Examples ======== >>> from sympy import Ei, polar_lift, exp_polar, I, pi >>> from sympy.abc import x >>> Ei(-1) Ei(-1) This yields a real value: >>> Ei(-1).n(chop=True) -0.219383934395520 On the other hand the analytic continuation is not real: >>> Ei(polar_lift(-1)).n(chop=True) -0.21938393439552 + 3.14159265358979*I The exponential integral has a logarithmic branch point at the origin: >>> Ei(x*exp_polar(2*I*pi)) Ei(x) + 2*I*pi Differentiation is supported: >>> Ei(x).diff(x) exp(x)/x The exponential integral is related to many other special functions. For example: >>> from sympy import expint, Shi >>> Ei(x).rewrite(expint) -expint(1, x*exp_polar(I*pi)) - I*pi >>> Ei(x).rewrite(Shi) Chi(x) + Shi(x) See Also ======== expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. uppergamma: Upper incomplete gamma function. References ========== .. [1] http://dlmf.nist.gov/6.6 .. [2] https://en.wikipedia.org/wiki/Exponential_integral .. [3] Abramowitz & Stegun, section 5: http://people.math.sfu.ca/~cbm/aands/page_228.htm """ @classmethod def eval(cls, z): if z.is_zero: return S.NegativeInfinity elif z is S.Infinity: return S.Infinity elif z is S.NegativeInfinity: return S.Zero if z.is_zero: return S.NegativeInfinity nz, n = z.extract_branch_factor() if n: return Ei(nz) + 2*I*pi*n def fdiff(self, argindex=1): arg = unpolarify(self.args[0]) if argindex == 1: return exp(arg)/arg else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): if (self.args[0]/polar_lift(-1)).is_positive: return Function._eval_evalf(self, prec) + (I*pi)._eval_evalf(prec) return Function._eval_evalf(self, prec) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma # XXX this does not currently work usefully because uppergamma # immediately turns into expint return -uppergamma(0, polar_lift(-1)*z) - I*pi def _eval_rewrite_as_expint(self, z, **kwargs): return -expint(1, polar_lift(-1)*z) - I*pi def _eval_rewrite_as_li(self, z, **kwargs): if isinstance(z, log): return li(z.args[0]) # TODO: # Actually it only holds that: # Ei(z) = li(exp(z)) # for -pi < imag(z) <= pi return li(exp(z)) def _eval_rewrite_as_Si(self, z, **kwargs): if z.is_negative: return Shi(z) + Chi(z) - I*pi else: return Shi(z) + Chi(z) _eval_rewrite_as_Ci = _eval_rewrite_as_Si _eval_rewrite_as_Chi = _eval_rewrite_as_Si _eval_rewrite_as_Shi = _eval_rewrite_as_Si def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return exp(z) * _eis(z) def _eval_as_leading_term(self, x, logx=None, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_Si(*self.args) return f._eval_as_leading_term(x, logx=logx, cdir=cdir) return super()._eval_as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_Si(*self.args) return f._eval_nseries(x, n, logx) return super()._eval_nseries(x, n, logx) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] if point is S.Infinity: z = self.args[0] s = [factorial(k) / (z)**k for k in range(0, n)] + \ [Order(1/z**n, x)] return (exp(z)/z) * Add(*s) return super(Ei, self)._eval_aseries(n, args0, x, logx) class expint(Function): r""" Generalized exponential integral. Explanation =========== This function is defined as .. math:: \operatorname{E}_\nu(z) = z^{\nu - 1} \Gamma(1 - \nu, z), where $\Gamma(1 - \nu, z)$ is the upper incomplete gamma function (``uppergamma``). Hence for $z$ with positive real part we have .. math:: \operatorname{E}_\nu(z) = \int_1^\infty \frac{e^{-zt}}{t^\nu} \mathrm{d}t, which explains the name. The representation as an incomplete gamma function provides an analytic continuation for $\operatorname{E}_\nu(z)$. If $\nu$ is a non-positive integer, the exponential integral is thus an unbranched function of $z$, otherwise there is a branch point at the origin. Refer to the incomplete gamma function documentation for details of the branching behavior. Examples ======== >>> from sympy import expint, S >>> from sympy.abc import nu, z Differentiation is supported. Differentiation with respect to $z$ further explains the name: for integral orders, the exponential integral is an iterated integral of the exponential function. >>> expint(nu, z).diff(z) -expint(nu - 1, z) Differentiation with respect to $\nu$ has no classical expression: >>> expint(nu, z).diff(nu) -z**(nu - 1)*meijerg(((), (1, 1)), ((0, 0, 1 - nu), ()), z) At non-postive integer orders, the exponential integral reduces to the exponential function: >>> expint(0, z) exp(-z)/z >>> expint(-1, z) exp(-z)/z + exp(-z)/z**2 At half-integers it reduces to error functions: >>> expint(S(1)/2, z) sqrt(pi)*erfc(sqrt(z))/sqrt(z) At positive integer orders it can be rewritten in terms of exponentials and ``expint(1, z)``. Use ``expand_func()`` to do this: >>> from sympy import expand_func >>> expand_func(expint(5, z)) z**4*expint(1, z)/24 + (-z**3 + z**2 - 2*z + 6)*exp(-z)/24 The generalised exponential integral is essentially equivalent to the incomplete gamma function: >>> from sympy import uppergamma >>> expint(nu, z).rewrite(uppergamma) z**(nu - 1)*uppergamma(1 - nu, z) As such it is branched at the origin: >>> from sympy import exp_polar, pi, I >>> expint(4, z*exp_polar(2*pi*I)) I*pi*z**3/3 + expint(4, z) >>> expint(nu, z*exp_polar(2*pi*I)) z**(nu - 1)*(exp(2*I*pi*nu) - 1)*gamma(1 - nu) + expint(nu, z) See Also ======== Ei: Another related function called exponential integral. E1: The classical case, returns expint(1, z). li: Logarithmic integral. Li: Offset logarithmic integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. uppergamma References ========== .. [1] http://dlmf.nist.gov/8.19 .. [2] http://functions.wolfram.com/GammaBetaErf/ExpIntegralE/ .. [3] https://en.wikipedia.org/wiki/Exponential_integral """ @classmethod def eval(cls, nu, z): from sympy.functions.special.gamma_functions import (gamma, uppergamma) nu2 = unpolarify(nu) if nu != nu2: return expint(nu2, z) if nu.is_Integer and nu <= 0 or (not nu.is_Integer and (2*nu).is_Integer): return unpolarify(expand_mul(z**(nu - 1)*uppergamma(1 - nu, z))) # Extract branching information. This can be deduced from what is # explained in lowergamma.eval(). z, n = z.extract_branch_factor() if n is S.Zero: return if nu.is_integer: if not nu > 0: return return expint(nu, z) \ - 2*pi*I*n*S.NegativeOne**(nu - 1)/factorial(nu - 1)*unpolarify(z)**(nu - 1) else: return (exp(2*I*pi*nu*n) - 1)*z**(nu - 1)*gamma(1 - nu) + expint(nu, z) def fdiff(self, argindex): nu, z = self.args if argindex == 1: return -z**(nu - 1)*meijerg([], [1, 1], [0, 0, 1 - nu], [], z) elif argindex == 2: return -expint(nu - 1, z) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_uppergamma(self, nu, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return z**(nu - 1)*uppergamma(1 - nu, z) def _eval_rewrite_as_Ei(self, nu, z, **kwargs): if nu == 1: return -Ei(z*exp_polar(-I*pi)) - I*pi elif nu.is_Integer and nu > 1: # DLMF, 8.19.7 x = -unpolarify(z) return x**(nu - 1)/factorial(nu - 1)*E1(z).rewrite(Ei) + \ exp(x)/factorial(nu - 1) * \ Add(*[factorial(nu - k - 2)*x**k for k in range(nu - 1)]) else: return self def _eval_expand_func(self, **hints): return self.rewrite(Ei).rewrite(expint, **hints) def _eval_rewrite_as_Si(self, nu, z, **kwargs): if nu != 1: return self return Shi(z) - Chi(z) _eval_rewrite_as_Ci = _eval_rewrite_as_Si _eval_rewrite_as_Chi = _eval_rewrite_as_Si _eval_rewrite_as_Shi = _eval_rewrite_as_Si def _eval_nseries(self, x, n, logx, cdir=0): if not self.args[0].has(x): nu = self.args[0] if nu == 1: f = self._eval_rewrite_as_Si(*self.args) return f._eval_nseries(x, n, logx) elif nu.is_Integer and nu > 1: f = self._eval_rewrite_as_Ei(*self.args) return f._eval_nseries(x, n, logx) return super()._eval_nseries(x, n, logx) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[1] nu = self.args[0] if point is S.Infinity: z = self.args[1] s = [S.NegativeOne**k * RisingFactorial(nu, k) / z**k for k in range(0, n)] + [Order(1/z**n, x)] return (exp(-z)/z) * Add(*s) return super(expint, self)._eval_aseries(n, args0, x, logx) def E1(z): """ Classical case of the generalized exponential integral. Explanation =========== This is equivalent to ``expint(1, z)``. Examples ======== >>> from sympy import E1 >>> E1(0) expint(1, 0) >>> E1(5) expint(1, 5) See Also ======== Ei: Exponential integral. expint: Generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. """ return expint(1, z) class li(Function): r""" The classical logarithmic integral. Explanation =========== For use in SymPy, this function is defined as .. math:: \operatorname{li}(x) = \int_0^x \frac{1}{\log(t)} \mathrm{d}t \,. Examples ======== >>> from sympy import I, oo, li >>> from sympy.abc import z Several special values are known: >>> li(0) 0 >>> li(1) -oo >>> li(oo) oo Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(li(z), z) 1/log(z) Defining the ``li`` function via an integral: >>> from sympy import integrate >>> integrate(li(z)) z*li(z) - Ei(2*log(z)) >>> integrate(li(z),z) z*li(z) - Ei(2*log(z)) The logarithmic integral can also be defined in terms of ``Ei``: >>> from sympy import Ei >>> li(z).rewrite(Ei) Ei(log(z)) >>> diff(li(z).rewrite(Ei), z) 1/log(z) We can numerically evaluate the logarithmic integral to arbitrary precision on the whole complex plane (except the singular points): >>> li(2).evalf(30) 1.04516378011749278484458888919 >>> li(2*I).evalf(30) 1.0652795784357498247001125598 + 3.08346052231061726610939702133*I We can even compute Soldner's constant by the help of mpmath: >>> from mpmath import findroot >>> findroot(li, 2) 1.45136923488338 Further transformations include rewriting ``li`` in terms of the trigonometric integrals ``Si``, ``Ci``, ``Shi`` and ``Chi``: >>> from sympy import Si, Ci, Shi, Chi >>> li(z).rewrite(Si) -log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z)) >>> li(z).rewrite(Ci) -log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z)) >>> li(z).rewrite(Shi) -log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z)) >>> li(z).rewrite(Chi) -log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z)) See Also ======== Li: Offset logarithmic integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. References ========== .. [1] https://en.wikipedia.org/wiki/Logarithmic_integral .. [2] http://mathworld.wolfram.com/LogarithmicIntegral.html .. [3] http://dlmf.nist.gov/6 .. [4] http://mathworld.wolfram.com/SoldnersConstant.html """ @classmethod def eval(cls, z): if z.is_zero: return S.Zero elif z is S.One: return S.NegativeInfinity elif z is S.Infinity: return S.Infinity if z.is_zero: return S.Zero def fdiff(self, argindex=1): arg = self.args[0] if argindex == 1: return S.One / log(arg) else: raise ArgumentIndexError(self, argindex) def _eval_conjugate(self): z = self.args[0] # Exclude values on the branch cut (-oo, 0) if not z.is_extended_negative: return self.func(z.conjugate()) def _eval_rewrite_as_Li(self, z, **kwargs): return Li(z) + li(2) def _eval_rewrite_as_Ei(self, z, **kwargs): return Ei(log(z)) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return (-uppergamma(0, -log(z)) + S.Half*(log(log(z)) - log(S.One/log(z))) - log(-log(z))) def _eval_rewrite_as_Si(self, z, **kwargs): return (Ci(I*log(z)) - I*Si(I*log(z)) - S.Half*(log(S.One/log(z)) - log(log(z))) - log(I*log(z))) _eval_rewrite_as_Ci = _eval_rewrite_as_Si def _eval_rewrite_as_Shi(self, z, **kwargs): return (Chi(log(z)) - Shi(log(z)) - S.Half*(log(S.One/log(z)) - log(log(z)))) _eval_rewrite_as_Chi = _eval_rewrite_as_Shi def _eval_rewrite_as_hyper(self, z, **kwargs): return (log(z)*hyper((1, 1), (2, 2), log(z)) + S.Half*(log(log(z)) - log(S.One/log(z))) + S.EulerGamma) def _eval_rewrite_as_meijerg(self, z, **kwargs): return (-log(-log(z)) - S.Half*(log(S.One/log(z)) - log(log(z))) - meijerg(((), (1,)), ((0, 0), ()), -log(z))) def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return z * _eis(log(z)) def _eval_nseries(self, x, n, logx, cdir=0): z = self.args[0] s = [(log(z))**k / (factorial(k) * k) for k in range(1, n)] return S.EulerGamma + log(log(z)) + Add(*s) def _eval_is_zero(self): z = self.args[0] if z.is_zero: return True class Li(Function): r""" The offset logarithmic integral. Explanation =========== For use in SymPy, this function is defined as .. math:: \operatorname{Li}(x) = \operatorname{li}(x) - \operatorname{li}(2) Examples ======== >>> from sympy import Li >>> from sympy.abc import z The following special value is known: >>> Li(2) 0 Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(Li(z), z) 1/log(z) The shifted logarithmic integral can be written in terms of $li(z)$: >>> from sympy import li >>> Li(z).rewrite(li) li(z) - li(2) We can numerically evaluate the logarithmic integral to arbitrary precision on the whole complex plane (except the singular points): >>> Li(2).evalf(30) 0 >>> Li(4).evalf(30) 1.92242131492155809316615998938 See Also ======== li: Logarithmic integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. References ========== .. [1] https://en.wikipedia.org/wiki/Logarithmic_integral .. [2] http://mathworld.wolfram.com/LogarithmicIntegral.html .. [3] http://dlmf.nist.gov/6 """ @classmethod def eval(cls, z): if z is S.Infinity: return S.Infinity elif z == S(2): return S.Zero def fdiff(self, argindex=1): arg = self.args[0] if argindex == 1: return S.One / log(arg) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): return self.rewrite(li).evalf(prec) def _eval_rewrite_as_li(self, z, **kwargs): return li(z) - li(2) def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return self.rewrite(li).rewrite("tractable", deep=True) def _eval_nseries(self, x, n, logx, cdir=0): f = self._eval_rewrite_as_li(*self.args) return f._eval_nseries(x, n, logx) ############################################################################### #################### TRIGONOMETRIC INTEGRALS ################################## ############################################################################### class TrigonometricIntegral(Function): """ Base class for trigonometric integrals. """ @classmethod def eval(cls, z): if z is S.Zero: return cls._atzero elif z is S.Infinity: return cls._atinf() elif z is S.NegativeInfinity: return cls._atneginf() if z.is_zero: return cls._atzero nz = z.extract_multiplicatively(polar_lift(I)) if nz is None and cls._trigfunc(0) == 0: nz = z.extract_multiplicatively(I) if nz is not None: return cls._Ifactor(nz, 1) nz = z.extract_multiplicatively(polar_lift(-I)) if nz is not None: return cls._Ifactor(nz, -1) nz = z.extract_multiplicatively(polar_lift(-1)) if nz is None and cls._trigfunc(0) == 0: nz = z.extract_multiplicatively(-1) if nz is not None: return cls._minusfactor(nz) nz, n = z.extract_branch_factor() if n == 0 and nz == z: return return 2*pi*I*n*cls._trigfunc(0) + cls(nz) def fdiff(self, argindex=1): arg = unpolarify(self.args[0]) if argindex == 1: return self._trigfunc(arg)/arg else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_Ei(self, z, **kwargs): return self._eval_rewrite_as_expint(z).rewrite(Ei) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return self._eval_rewrite_as_expint(z).rewrite(uppergamma) def _eval_nseries(self, x, n, logx, cdir=0): # NOTE this is fairly inefficient n += 1 if self.args[0].subs(x, 0) != 0: return super()._eval_nseries(x, n, logx) baseseries = self._trigfunc(x)._eval_nseries(x, n, logx) if self._trigfunc(0) != 0: baseseries -= 1 baseseries = baseseries.replace(Pow, lambda t, n: t**n/n, simultaneous=False) if self._trigfunc(0) != 0: baseseries += EulerGamma + log(x) return baseseries.subs(x, self.args[0])._eval_nseries(x, n, logx) class Si(TrigonometricIntegral): r""" Sine integral. Explanation =========== This function is defined by .. math:: \operatorname{Si}(z) = \int_0^z \frac{\sin{t}}{t} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import Si >>> from sympy.abc import z The sine integral is an antiderivative of $sin(z)/z$: >>> Si(z).diff(z) sin(z)/z It is unbranched: >>> from sympy import exp_polar, I, pi >>> Si(z*exp_polar(2*I*pi)) Si(z) Sine integral behaves much like ordinary sine under multiplication by ``I``: >>> Si(I*z) I*Shi(z) >>> Si(-z) -Si(z) It can also be expressed in terms of exponential integrals, but beware that the latter is branched: >>> from sympy import expint >>> Si(z).rewrite(expint) -I*(-expint(1, z*exp_polar(-I*pi/2))/2 + expint(1, z*exp_polar(I*pi/2))/2) + pi/2 It can be rewritten in the form of sinc function (by definition): >>> from sympy import sinc >>> Si(z).rewrite(sinc) Integral(sinc(t), (t, 0, z)) See Also ======== Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. Ei: Exponential integral. expint: Generalised exponential integral. sinc: unnormalized sinc function E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral """ _trigfunc = sin _atzero = S.Zero @classmethod def _atinf(cls): return pi*S.Half @classmethod def _atneginf(cls): return -pi*S.Half @classmethod def _minusfactor(cls, z): return -Si(z) @classmethod def _Ifactor(cls, z, sign): return I*Shi(z)*sign def _eval_rewrite_as_expint(self, z, **kwargs): # XXX should we polarify z? return pi/2 + (E1(polar_lift(I)*z) - E1(polar_lift(-I)*z))/2/I def _eval_rewrite_as_sinc(self, z, **kwargs): from sympy.integrals.integrals import Integral t = Symbol('t', Dummy=True) return Integral(sinc(t), (t, 0, z)) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo if point is S.Infinity: z = self.args[0] p = [S.NegativeOne**k * factorial(2*k) / z**(2*k) for k in range(0, int((n - 1)/2))] + [Order(1/z**n, x)] q = [S.NegativeOne**k * factorial(2*k + 1) / z**(2*k + 1) for k in range(0, int(n/2) - 1)] + [Order(1/z**n, x)] return pi/2 - (cos(z)/z)*Add(*p) - (sin(z)/z)*Add(*q) # All other points are not handled return super(Si, self)._eval_aseries(n, args0, x, logx) def _eval_is_zero(self): z = self.args[0] if z.is_zero: return True class Ci(TrigonometricIntegral): r""" Cosine integral. Explanation =========== This function is defined for positive $x$ by .. math:: \operatorname{Ci}(x) = \gamma + \log{x} + \int_0^x \frac{\cos{t} - 1}{t} \mathrm{d}t = -\int_x^\infty \frac{\cos{t}}{t} \mathrm{d}t, where $\gamma$ is the Euler-Mascheroni constant. We have .. math:: \operatorname{Ci}(z) = -\frac{\operatorname{E}_1\left(e^{i\pi/2} z\right) + \operatorname{E}_1\left(e^{-i \pi/2} z\right)}{2} which holds for all polar $z$ and thus provides an analytic continuation to the Riemann surface of the logarithm. The formula also holds as stated for $z \in \mathbb{C}$ with $\Re(z) > 0$. By lifting to the principal branch, we obtain an analytic function on the cut complex plane. Examples ======== >>> from sympy import Ci >>> from sympy.abc import z The cosine integral is a primitive of $\cos(z)/z$: >>> Ci(z).diff(z) cos(z)/z It has a logarithmic branch point at the origin: >>> from sympy import exp_polar, I, pi >>> Ci(z*exp_polar(2*I*pi)) Ci(z) + 2*I*pi The cosine integral behaves somewhat like ordinary $\cos$ under multiplication by $i$: >>> from sympy import polar_lift >>> Ci(polar_lift(I)*z) Chi(z) + I*pi/2 >>> Ci(polar_lift(-1)*z) Ci(z) + I*pi It can also be expressed in terms of exponential integrals: >>> from sympy import expint >>> Ci(z).rewrite(expint) -expint(1, z*exp_polar(-I*pi/2))/2 - expint(1, z*exp_polar(I*pi/2))/2 See Also ======== Si: Sine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral """ _trigfunc = cos _atzero = S.ComplexInfinity @classmethod def _atinf(cls): return S.Zero @classmethod def _atneginf(cls): return I*pi @classmethod def _minusfactor(cls, z): return Ci(z) + I*pi @classmethod def _Ifactor(cls, z, sign): return Chi(z) + I*pi/2*sign def _eval_rewrite_as_expint(self, z, **kwargs): return -(E1(polar_lift(I)*z) + E1(polar_lift(-I)*z))/2 def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return S.EulerGamma elif arg0.is_finite: return self.func(arg0) else: return self def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo if point is S.Infinity: z = self.args[0] p = [S.NegativeOne**k * factorial(2*k) / z**(2*k) for k in range(0, int((n - 1)/2))] + [Order(1/z**n, x)] q = [S.NegativeOne**k * factorial(2*k + 1) / z**(2*k + 1) for k in range(0, int(n/2) - 1)] + [Order(1/z**n, x)] return (sin(z)/z)*Add(*p) - (cos(z)/z)*Add(*q) # All other points are not handled return super(Ci, self)._eval_aseries(n, args0, x, logx) class Shi(TrigonometricIntegral): r""" Sinh integral. Explanation =========== This function is defined by .. math:: \operatorname{Shi}(z) = \int_0^z \frac{\sinh{t}}{t} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import Shi >>> from sympy.abc import z The Sinh integral is a primitive of $\sinh(z)/z$: >>> Shi(z).diff(z) sinh(z)/z It is unbranched: >>> from sympy import exp_polar, I, pi >>> Shi(z*exp_polar(2*I*pi)) Shi(z) The $\sinh$ integral behaves much like ordinary $\sinh$ under multiplication by $i$: >>> Shi(I*z) I*Si(z) >>> Shi(-z) -Shi(z) It can also be expressed in terms of exponential integrals, but beware that the latter is branched: >>> from sympy import expint >>> Shi(z).rewrite(expint) expint(1, z)/2 - expint(1, z*exp_polar(I*pi))/2 - I*pi/2 See Also ======== Si: Sine integral. Ci: Cosine integral. Chi: Hyperbolic cosine integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral """ _trigfunc = sinh _atzero = S.Zero @classmethod def _atinf(cls): return S.Infinity @classmethod def _atneginf(cls): return S.NegativeInfinity @classmethod def _minusfactor(cls, z): return -Shi(z) @classmethod def _Ifactor(cls, z, sign): return I*Si(z)*sign def _eval_rewrite_as_expint(self, z, **kwargs): # XXX should we polarify z? return (E1(z) - E1(exp_polar(I*pi)*z))/2 - I*pi/2 def _eval_is_zero(self): z = self.args[0] if z.is_zero: return True def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return arg elif not arg0.is_infinite: return self.func(arg0) elif arg0.is_infinite: return -pi*S.ImaginaryUnit/2 else: return self class Chi(TrigonometricIntegral): r""" Cosh integral. Explanation =========== This function is defined for positive $x$ by .. math:: \operatorname{Chi}(x) = \gamma + \log{x} + \int_0^x \frac{\cosh{t} - 1}{t} \mathrm{d}t, where $\gamma$ is the Euler-Mascheroni constant. We have .. math:: \operatorname{Chi}(z) = \operatorname{Ci}\left(e^{i \pi/2}z\right) - i\frac{\pi}{2}, which holds for all polar $z$ and thus provides an analytic continuation to the Riemann surface of the logarithm. By lifting to the principal branch we obtain an analytic function on the cut complex plane. Examples ======== >>> from sympy import Chi >>> from sympy.abc import z The $\cosh$ integral is a primitive of $\cosh(z)/z$: >>> Chi(z).diff(z) cosh(z)/z It has a logarithmic branch point at the origin: >>> from sympy import exp_polar, I, pi >>> Chi(z*exp_polar(2*I*pi)) Chi(z) + 2*I*pi The $\cosh$ integral behaves somewhat like ordinary $\cosh$ under multiplication by $i$: >>> from sympy import polar_lift >>> Chi(polar_lift(I)*z) Ci(z) + I*pi/2 >>> Chi(polar_lift(-1)*z) Chi(z) + I*pi It can also be expressed in terms of exponential integrals: >>> from sympy import expint >>> Chi(z).rewrite(expint) -expint(1, z)/2 - expint(1, z*exp_polar(I*pi))/2 - I*pi/2 See Also ======== Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral """ _trigfunc = cosh _atzero = S.ComplexInfinity @classmethod def _atinf(cls): return S.Infinity @classmethod def _atneginf(cls): return S.Infinity @classmethod def _minusfactor(cls, z): return Chi(z) + I*pi @classmethod def _Ifactor(cls, z, sign): return Ci(z) + I*pi/2*sign def _eval_rewrite_as_expint(self, z, **kwargs): return -I*pi/2 - (E1(z) + E1(exp_polar(I*pi)*z))/2 def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return S.EulerGamma elif arg0.is_finite: return self.func(arg0) else: return self ############################################################################### #################### FRESNEL INTEGRALS ######################################## ############################################################################### class FresnelIntegral(Function): """ Base class for the Fresnel integrals.""" unbranched = True @classmethod def eval(cls, z): # Values at positive infinities signs # if any were extracted automatically if z is S.Infinity: return S.Half # Value at zero if z.is_zero: return S.Zero # Try to pull out factors of -1 and I prefact = S.One newarg = z changed = False nz = newarg.extract_multiplicatively(-1) if nz is not None: prefact = -prefact newarg = nz changed = True nz = newarg.extract_multiplicatively(I) if nz is not None: prefact = cls._sign*I*prefact newarg = nz changed = True if changed: return prefact*cls(newarg) def fdiff(self, argindex=1): if argindex == 1: return self._trigfunc(S.Half*pi*self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_extended_real(self): return self.args[0].is_extended_real _eval_is_finite = _eval_is_extended_real def _eval_is_zero(self): return self.args[0].is_zero def _eval_conjugate(self): return self.func(self.args[0].conjugate()) as_real_imag = real_to_real_as_real_imag class fresnels(FresnelIntegral): r""" Fresnel integral S. Explanation =========== This function is defined by .. math:: \operatorname{S}(z) = \int_0^z \sin{\frac{\pi}{2} t^2} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import I, oo, fresnels >>> from sympy.abc import z Several special values are known: >>> fresnels(0) 0 >>> fresnels(oo) 1/2 >>> fresnels(-oo) -1/2 >>> fresnels(I*oo) -I/2 >>> fresnels(-I*oo) I/2 In general one can pull out factors of -1 and $i$ from the argument: >>> fresnels(-z) -fresnels(z) >>> fresnels(I*z) -I*fresnels(z) The Fresnel S integral obeys the mirror symmetry $\overline{S(z)} = S(\bar{z})$: >>> from sympy import conjugate >>> conjugate(fresnels(z)) fresnels(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(fresnels(z), z) sin(pi*z**2/2) Defining the Fresnel functions via an integral: >>> from sympy import integrate, pi, sin, expand_func >>> integrate(sin(pi*z**2/2), z) 3*fresnels(z)*gamma(3/4)/(4*gamma(7/4)) >>> expand_func(integrate(sin(pi*z**2/2), z)) fresnels(z) We can numerically evaluate the Fresnel integral to arbitrary precision on the whole complex plane: >>> fresnels(2).evalf(30) 0.343415678363698242195300815958 >>> fresnels(-2*I).evalf(30) 0.343415678363698242195300815958*I See Also ======== fresnelc: Fresnel cosine integral. References ========== .. [1] https://en.wikipedia.org/wiki/Fresnel_integral .. [2] http://dlmf.nist.gov/7 .. [3] http://mathworld.wolfram.com/FresnelIntegrals.html .. [4] http://functions.wolfram.com/GammaBetaErf/FresnelS .. [5] The converging factors for the fresnel integrals by John W. Wrench Jr. and Vicki Alley """ _trigfunc = sin _sign = -S.One @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 1: p = previous_terms[-1] return (-pi**2*x**4*(4*n - 1)/(8*n*(2*n + 1)*(4*n + 3))) * p else: return x**3 * (-x**4)**n * (S(2)**(-2*n - 1)*pi**(2*n + 1)) / ((4*n + 3)*factorial(2*n + 1)) def _eval_rewrite_as_erf(self, z, **kwargs): return (S.One + I)/4 * (erf((S.One + I)/2*sqrt(pi)*z) - I*erf((S.One - I)/2*sqrt(pi)*z)) def _eval_rewrite_as_hyper(self, z, **kwargs): return pi*z**3/6 * hyper([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)], -pi**2*z**4/16) def _eval_rewrite_as_meijerg(self, z, **kwargs): return (pi*z**Rational(9, 4) / (sqrt(2)*(z**2)**Rational(3, 4)*(-z)**Rational(3, 4)) * meijerg([], [1], [Rational(3, 4)], [Rational(1, 4), 0], -pi**2*z**4/16)) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.ComplexInfinity: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return pi*arg**3/6 elif arg0 in [S.Infinity, S.NegativeInfinity]: s = 1 if arg0 is S.Infinity else -1 return s*S.Half + Order(x, x) else: return self.func(arg0) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo and -oo if point in [S.Infinity, -S.Infinity]: z = self.args[0] # expansion of S(x) = S1(x*sqrt(pi/2)), see reference[5] page 1-8 # as only real infinities are dealt with, sin and cos are O(1) p = [S.NegativeOne**k * factorial(4*k + 1) / (2**(2*k + 2) * z**(4*k + 3) * 2**(2*k)*factorial(2*k)) for k in range(0, n) if 4*k + 3 < n] q = [1/(2*z)] + [S.NegativeOne**k * factorial(4*k - 1) / (2**(2*k + 1) * z**(4*k + 1) * 2**(2*k - 1)*factorial(2*k - 1)) for k in range(1, n) if 4*k + 1 < n] p = [-sqrt(2/pi)*t for t in p] q = [-sqrt(2/pi)*t for t in q] s = 1 if point is S.Infinity else -1 # The expansion at oo is 1/2 + some odd powers of z # To get the expansion at -oo, replace z by -z and flip the sign # The result -1/2 + the same odd powers of z as before. return s*S.Half + (sin(z**2)*Add(*p) + cos(z**2)*Add(*q) ).subs(x, sqrt(2/pi)*x) + Order(1/z**n, x) # All other points are not handled return super()._eval_aseries(n, args0, x, logx) class fresnelc(FresnelIntegral): r""" Fresnel integral C. Explanation =========== This function is defined by .. math:: \operatorname{C}(z) = \int_0^z \cos{\frac{\pi}{2} t^2} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import I, oo, fresnelc >>> from sympy.abc import z Several special values are known: >>> fresnelc(0) 0 >>> fresnelc(oo) 1/2 >>> fresnelc(-oo) -1/2 >>> fresnelc(I*oo) I/2 >>> fresnelc(-I*oo) -I/2 In general one can pull out factors of -1 and $i$ from the argument: >>> fresnelc(-z) -fresnelc(z) >>> fresnelc(I*z) I*fresnelc(z) The Fresnel C integral obeys the mirror symmetry $\overline{C(z)} = C(\bar{z})$: >>> from sympy import conjugate >>> conjugate(fresnelc(z)) fresnelc(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(fresnelc(z), z) cos(pi*z**2/2) Defining the Fresnel functions via an integral: >>> from sympy import integrate, pi, cos, expand_func >>> integrate(cos(pi*z**2/2), z) fresnelc(z)*gamma(1/4)/(4*gamma(5/4)) >>> expand_func(integrate(cos(pi*z**2/2), z)) fresnelc(z) We can numerically evaluate the Fresnel integral to arbitrary precision on the whole complex plane: >>> fresnelc(2).evalf(30) 0.488253406075340754500223503357 >>> fresnelc(-2*I).evalf(30) -0.488253406075340754500223503357*I See Also ======== fresnels: Fresnel sine integral. References ========== .. [1] https://en.wikipedia.org/wiki/Fresnel_integral .. [2] http://dlmf.nist.gov/7 .. [3] http://mathworld.wolfram.com/FresnelIntegrals.html .. [4] http://functions.wolfram.com/GammaBetaErf/FresnelC .. [5] The converging factors for the fresnel integrals by John W. Wrench Jr. and Vicki Alley """ _trigfunc = cos _sign = S.One @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 1: p = previous_terms[-1] return (-pi**2*x**4*(4*n - 3)/(8*n*(2*n - 1)*(4*n + 1))) * p else: return x * (-x**4)**n * (S(2)**(-2*n)*pi**(2*n)) / ((4*n + 1)*factorial(2*n)) def _eval_rewrite_as_erf(self, z, **kwargs): return (S.One - I)/4 * (erf((S.One + I)/2*sqrt(pi)*z) + I*erf((S.One - I)/2*sqrt(pi)*z)) def _eval_rewrite_as_hyper(self, z, **kwargs): return z * hyper([Rational(1, 4)], [S.Half, Rational(5, 4)], -pi**2*z**4/16) def _eval_rewrite_as_meijerg(self, z, **kwargs): return (pi*z**Rational(3, 4) / (sqrt(2)*root(z**2, 4)*root(-z, 4)) * meijerg([], [1], [Rational(1, 4)], [Rational(3, 4), 0], -pi**2*z**4/16)) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.ComplexInfinity: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return arg elif arg0 in [S.Infinity, S.NegativeInfinity]: s = 1 if arg0 is S.Infinity else -1 return s*S.Half + Order(x, x) else: return self.func(arg0) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo if point in [S.Infinity, -S.Infinity]: z = self.args[0] # expansion of C(x) = C1(x*sqrt(pi/2)), see reference[5] page 1-8 # as only real infinities are dealt with, sin and cos are O(1) p = [S.NegativeOne**k * factorial(4*k + 1) / (2**(2*k + 2) * z**(4*k + 3) * 2**(2*k)*factorial(2*k)) for k in range(0, n) if 4*k + 3 < n] q = [1/(2*z)] + [S.NegativeOne**k * factorial(4*k - 1) / (2**(2*k + 1) * z**(4*k + 1) * 2**(2*k - 1)*factorial(2*k - 1)) for k in range(1, n) if 4*k + 1 < n] p = [-sqrt(2/pi)*t for t in p] q = [ sqrt(2/pi)*t for t in q] s = 1 if point is S.Infinity else -1 # The expansion at oo is 1/2 + some odd powers of z # To get the expansion at -oo, replace z by -z and flip the sign # The result -1/2 + the same odd powers of z as before. return s*S.Half + (cos(z**2)*Add(*p) + sin(z**2)*Add(*q) ).subs(x, sqrt(2/pi)*x) + Order(1/z**n, x) # All other points are not handled return super()._eval_aseries(n, args0, x, logx) ############################################################################### #################### HELPER FUNCTIONS ######################################### ############################################################################### class _erfs(Function): """ Helper function to make the $\\mathrm{erf}(z)$ function tractable for the Gruntz algorithm. """ @classmethod def eval(cls, arg): if arg.is_zero: return S.One def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo if point is S.Infinity: z = self.args[0] l = [ 1/sqrt(S.Pi) * factorial(2*k)*(-S( 4))**(-k)/factorial(k) * (1/z)**(2*k + 1) for k in range(0, n) ] o = Order(1/z**(2*n + 1), x) # It is very inefficient to first add the order and then do the nseries return (Add(*l))._eval_nseries(x, n, logx) + o # Expansion at I*oo t = point.extract_multiplicatively(S.ImaginaryUnit) if t is S.Infinity: z = self.args[0] # TODO: is the series really correct? l = [ 1/sqrt(S.Pi) * factorial(2*k)*(-S( 4))**(-k)/factorial(k) * (1/z)**(2*k + 1) for k in range(0, n) ] o = Order(1/z**(2*n + 1), x) # It is very inefficient to first add the order and then do the nseries return (Add(*l))._eval_nseries(x, n, logx) + o # All other points are not handled return super()._eval_aseries(n, args0, x, logx) def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] return -2/sqrt(S.Pi) + 2*z*_erfs(z) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_intractable(self, z, **kwargs): return (S.One - erf(z))*exp(z**2) class _eis(Function): """ Helper function to make the $\\mathrm{Ei}(z)$ and $\\mathrm{li}(z)$ functions tractable for the Gruntz algorithm. """ def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order if args0[0] != S.Infinity: return super(_erfs, self)._eval_aseries(n, args0, x, logx) z = self.args[0] l = [ factorial(k) * (1/z)**(k + 1) for k in range(0, n) ] o = Order(1/z**(n + 1), x) # It is very inefficient to first add the order and then do the nseries return (Add(*l))._eval_nseries(x, n, logx) + o def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] return S.One / z - _eis(z) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_intractable(self, z, **kwargs): return exp(-z)*Ei(z) def _eval_as_leading_term(self, x, logx=None, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_intractable(*self.args) return f._eval_as_leading_term(x, logx=logx, cdir=cdir) return super()._eval_as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_intractable(*self.args) return f._eval_nseries(x, n, logx) return super()._eval_nseries(x, n, logx)
be2df708965cb39047c6a7c7edd38e7bd2c260e102c1f726e85ebd364cee30d9
""" 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 ( jacobi_poly, gegenbauer_poly, chebyshevt_poly, chebyshevu_poly, laguerre_poly, hermite_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 nth 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 nth 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 nth 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 nth 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 nth 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 kth root (indexed from zero) of the nth Chebyshev polynomial of the first kind; that is, if 0 <= 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 kth root (indexed from zero) of the nth Chebyshev polynomial of the second kind; that is, if 0 <= 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 nth 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 = 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 nth 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 nth 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 >= 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 nth 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 >= 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())
278e8bbd1c533ff5d88353af128bf62cb8eab63823b12a7ccdc57f006b6865d4
from sympy.concrete.products import Product from sympy.core.function import expand_func from sympy.core.mod import Mod from sympy.core.mul import Mul from sympy.core import EulerGamma from sympy.core.numbers import (Float, I, Rational, nan, oo, pi, zoo) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.combinatorial.factorials import (ff, rf, binomial, factorial, factorial2) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.gamma_functions import (gamma, polygamma) from sympy.polys.polytools import Poly from sympy.series.order import O from sympy.simplify.simplify import simplify from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.functions.combinatorial.factorials import subfactorial from sympy.functions.special.gamma_functions import uppergamma from sympy.testing.pytest import XFAIL, raises, slow #Solves and Fixes Issue #10388 - This is the updated test for the same solved issue def test_rf_eval_apply(): x, y = symbols('x,y') n, k = symbols('n k', integer=True) m = Symbol('m', integer=True, nonnegative=True) assert rf(nan, y) is nan assert rf(x, nan) is nan assert unchanged(rf, x, y) assert rf(oo, 0) == 1 assert rf(-oo, 0) == 1 assert rf(oo, 6) is oo assert rf(-oo, 7) is -oo assert rf(-oo, 6) is oo assert rf(oo, -6) is oo assert rf(-oo, -7) is oo assert rf(-1, pi) == 0 assert rf(-5, 1 + I) == 0 assert unchanged(rf, -3, k) assert unchanged(rf, x, Symbol('k', integer=False)) assert rf(-3, Symbol('k', integer=False)) == 0 assert rf(Symbol('x', negative=True, integer=True), Symbol('k', integer=False)) == 0 assert rf(x, 0) == 1 assert rf(x, 1) == x assert rf(x, 2) == x*(x + 1) assert rf(x, 3) == x*(x + 1)*(x + 2) assert rf(x, 5) == x*(x + 1)*(x + 2)*(x + 3)*(x + 4) assert rf(x, -1) == 1/(x - 1) assert rf(x, -2) == 1/((x - 1)*(x - 2)) assert rf(x, -3) == 1/((x - 1)*(x - 2)*(x - 3)) assert rf(1, 100) == factorial(100) assert rf(x**2 + 3*x, 2) == (x**2 + 3*x)*(x**2 + 3*x + 1) assert isinstance(rf(x**2 + 3*x, 2), Mul) assert rf(x**3 + x, -2) == 1/((x**3 + x - 1)*(x**3 + x - 2)) assert rf(Poly(x**2 + 3*x, x), 2) == Poly(x**4 + 8*x**3 + 19*x**2 + 12*x, x) assert isinstance(rf(Poly(x**2 + 3*x, x), 2), Poly) raises(ValueError, lambda: rf(Poly(x**2 + 3*x, x, y), 2)) assert rf(Poly(x**3 + x, x), -2) == 1/(x**6 - 9*x**5 + 35*x**4 - 75*x**3 + 94*x**2 - 66*x + 20) raises(ValueError, lambda: rf(Poly(x**3 + x, x, y), -2)) assert rf(x, m).is_integer is None assert rf(n, k).is_integer is None assert rf(n, m).is_integer is True assert rf(n, k + pi).is_integer is False assert rf(n, m + pi).is_integer is False assert rf(pi, m).is_integer is False def check(x, k, o, n): a, b = Dummy(), Dummy() r = lambda x, k: o(a, b).rewrite(n).subs({a:x,b:k}) for i in range(-5,5): for j in range(-5,5): assert o(i, j) == r(i, j), (o, n, i, j) check(x, k, rf, ff) check(x, k, rf, binomial) check(n, k, rf, factorial) check(x, y, rf, factorial) check(x, y, rf, binomial) assert rf(x, k).rewrite(ff) == ff(x + k - 1, k) assert rf(x, k).rewrite(gamma) == Piecewise( (gamma(k + x)/gamma(x), x > 0), ((-1)**k*gamma(1 - x)/gamma(-k - x + 1), True)) assert rf(5, k).rewrite(gamma) == gamma(k + 5)/24 assert rf(x, k).rewrite(binomial) == factorial(k)*binomial(x + k - 1, k) assert rf(n, k).rewrite(factorial) == Piecewise( (factorial(k + n - 1)/factorial(n - 1), n > 0), ((-1)**k*factorial(-n)/factorial(-k - n), True)) assert rf(5, k).rewrite(factorial) == factorial(k + 4)/24 assert rf(x, y).rewrite(factorial) == rf(x, y) assert rf(x, y).rewrite(binomial) == rf(x, y) import random from mpmath import rf as mpmath_rf for i in range(100): x = -500 + 500 * random.random() k = -500 + 500 * random.random() assert (abs(mpmath_rf(x, k) - rf(x, k)) < 10**(-15)) def test_ff_eval_apply(): x, y = symbols('x,y') n, k = symbols('n k', integer=True) m = Symbol('m', integer=True, nonnegative=True) assert ff(nan, y) is nan assert ff(x, nan) is nan assert unchanged(ff, x, y) assert ff(oo, 0) == 1 assert ff(-oo, 0) == 1 assert ff(oo, 6) is oo assert ff(-oo, 7) is -oo assert ff(-oo, 6) is oo assert ff(oo, -6) is oo assert ff(-oo, -7) is oo assert ff(x, 0) == 1 assert ff(x, 1) == x assert ff(x, 2) == x*(x - 1) assert ff(x, 3) == x*(x - 1)*(x - 2) assert ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4) assert ff(x, -1) == 1/(x + 1) assert ff(x, -2) == 1/((x + 1)*(x + 2)) assert ff(x, -3) == 1/((x + 1)*(x + 2)*(x + 3)) assert ff(100, 100) == factorial(100) assert ff(2*x**2 - 5*x, 2) == (2*x**2 - 5*x)*(2*x**2 - 5*x - 1) assert isinstance(ff(2*x**2 - 5*x, 2), Mul) assert ff(x**2 + 3*x, -2) == 1/((x**2 + 3*x + 1)*(x**2 + 3*x + 2)) assert ff(Poly(2*x**2 - 5*x, x), 2) == Poly(4*x**4 - 28*x**3 + 59*x**2 - 35*x, x) assert isinstance(ff(Poly(2*x**2 - 5*x, x), 2), Poly) raises(ValueError, lambda: ff(Poly(2*x**2 - 5*x, x, y), 2)) assert ff(Poly(x**2 + 3*x, x), -2) == 1/(x**4 + 12*x**3 + 49*x**2 + 78*x + 40) raises(ValueError, lambda: ff(Poly(x**2 + 3*x, x, y), -2)) assert ff(x, m).is_integer is None assert ff(n, k).is_integer is None assert ff(n, m).is_integer is True assert ff(n, k + pi).is_integer is False assert ff(n, m + pi).is_integer is False assert ff(pi, m).is_integer is False assert isinstance(ff(x, x), ff) assert ff(n, n) == factorial(n) def check(x, k, o, n): a, b = Dummy(), Dummy() r = lambda x, k: o(a, b).rewrite(n).subs({a:x,b:k}) for i in range(-5,5): for j in range(-5,5): assert o(i, j) == r(i, j), (o, n) check(x, k, ff, rf) check(x, k, ff, gamma) check(n, k, ff, factorial) check(x, k, ff, binomial) check(x, y, ff, factorial) check(x, y, ff, binomial) assert ff(x, k).rewrite(rf) == rf(x - k + 1, k) assert ff(x, k).rewrite(gamma) == Piecewise( (gamma(x + 1)/gamma(-k + x + 1), x >= 0), ((-1)**k*gamma(k - x)/gamma(-x), True)) assert ff(5, k).rewrite(gamma) == 120/gamma(6 - k) assert ff(n, k).rewrite(factorial) == Piecewise( (factorial(n)/factorial(-k + n), n >= 0), ((-1)**k*factorial(k - n - 1)/factorial(-n - 1), True)) assert ff(5, k).rewrite(factorial) == 120/factorial(5 - k) assert ff(x, k).rewrite(binomial) == factorial(k) * binomial(x, k) assert ff(x, y).rewrite(factorial) == ff(x, y) assert ff(x, y).rewrite(binomial) == ff(x, y) import random from mpmath import ff as mpmath_ff for i in range(100): x = -500 + 500 * random.random() k = -500 + 500 * random.random() a = mpmath_ff(x, k) b = ff(x, k) assert (abs(a - b) < abs(a) * 10**(-15)) def test_rf_ff_eval_hiprec(): maple = Float('6.9109401292234329956525265438452') us = ff(18, Rational(2, 3)).evalf(32) assert abs(us - maple)/us < 1e-31 maple = Float('6.8261540131125511557924466355367') us = rf(18, Rational(2, 3)).evalf(32) assert abs(us - maple)/us < 1e-31 maple = Float('34.007346127440197150854651814225') us = rf(Float('4.4', 32), Float('2.2', 32)); assert abs(us - maple)/us < 1e-31 def test_rf_lambdify_mpmath(): from sympy.utilities.lambdify import lambdify x, y = symbols('x,y') f = lambdify((x,y), rf(x, y), 'mpmath') maple = Float('34.007346127440197') us = f(4.4, 2.2) assert abs(us - maple)/us < 1e-15 def test_factorial(): x = Symbol('x') n = Symbol('n', integer=True) k = Symbol('k', integer=True, nonnegative=True) r = Symbol('r', integer=False) s = Symbol('s', integer=False, negative=True) t = Symbol('t', nonnegative=True) u = Symbol('u', noninteger=True) assert factorial(-2) is zoo assert factorial(0) == 1 assert factorial(7) == 5040 assert factorial(19) == 121645100408832000 assert factorial(31) == 8222838654177922817725562880000000 assert factorial(n).func == factorial assert factorial(2*n).func == factorial assert factorial(x).is_integer is None assert factorial(n).is_integer is None assert factorial(k).is_integer assert factorial(r).is_integer is None assert factorial(n).is_positive is None assert factorial(k).is_positive assert factorial(x).is_real is None assert factorial(n).is_real is None assert factorial(k).is_real is True assert factorial(r).is_real is None assert factorial(s).is_real is True assert factorial(t).is_real is True assert factorial(u).is_real is True assert factorial(x).is_composite is None assert factorial(n).is_composite is None assert factorial(k).is_composite is None assert factorial(k + 3).is_composite is True assert factorial(r).is_composite is None assert factorial(s).is_composite is None assert factorial(t).is_composite is None assert factorial(u).is_composite is None assert factorial(oo) is oo def test_factorial_Mod(): pr = Symbol('pr', prime=True) p, q = 10**9 + 9, 10**9 + 33 # prime modulo r, s = 10**7 + 5, 33333333 # composite modulo assert Mod(factorial(pr - 1), pr) == pr - 1 assert Mod(factorial(pr - 1), -pr) == -1 assert Mod(factorial(r - 1, evaluate=False), r) == 0 assert Mod(factorial(s - 1, evaluate=False), s) == 0 assert Mod(factorial(p - 1, evaluate=False), p) == p - 1 assert Mod(factorial(q - 1, evaluate=False), q) == q - 1 assert Mod(factorial(p - 50, evaluate=False), p) == 854928834 assert Mod(factorial(q - 1800, evaluate=False), q) == 905504050 assert Mod(factorial(153, evaluate=False), r) == Mod(factorial(153), r) assert Mod(factorial(255, evaluate=False), s) == Mod(factorial(255), s) assert Mod(factorial(4, evaluate=False), 3) == S.Zero assert Mod(factorial(5, evaluate=False), 6) == S.Zero def test_factorial_diff(): n = Symbol('n', integer=True) assert factorial(n).diff(n) == \ gamma(1 + n)*polygamma(0, 1 + n) assert factorial(n**2).diff(n) == \ 2*n*gamma(1 + n**2)*polygamma(0, 1 + n**2) raises(ArgumentIndexError, lambda: factorial(n**2).fdiff(2)) def test_factorial_series(): n = Symbol('n', integer=True) assert factorial(n).series(n, 0, 3) == \ 1 - n*EulerGamma + n**2*(EulerGamma**2/2 + pi**2/12) + O(n**3) def test_factorial_rewrite(): n = Symbol('n', integer=True) k = Symbol('k', integer=True, nonnegative=True) assert factorial(n).rewrite(gamma) == gamma(n + 1) _i = Dummy('i') assert factorial(k).rewrite(Product).dummy_eq(Product(_i, (_i, 1, k))) assert factorial(n).rewrite(Product) == factorial(n) def test_factorial2(): n = Symbol('n', integer=True) assert factorial2(-1) == 1 assert factorial2(0) == 1 assert factorial2(7) == 105 assert factorial2(8) == 384 # The following is exhaustive tt = Symbol('tt', integer=True, nonnegative=True) tte = Symbol('tte', even=True, nonnegative=True) tpe = Symbol('tpe', even=True, positive=True) tto = Symbol('tto', odd=True, nonnegative=True) tf = Symbol('tf', integer=True, nonnegative=False) tfe = Symbol('tfe', even=True, nonnegative=False) tfo = Symbol('tfo', odd=True, nonnegative=False) ft = Symbol('ft', integer=False, nonnegative=True) ff = Symbol('ff', integer=False, nonnegative=False) fn = Symbol('fn', integer=False) nt = Symbol('nt', nonnegative=True) nf = Symbol('nf', nonnegative=False) nn = Symbol('nn') z = Symbol('z', zero=True) #Solves and Fixes Issue #10388 - This is the updated test for the same solved issue raises(ValueError, lambda: factorial2(oo)) raises(ValueError, lambda: factorial2(Rational(5, 2))) raises(ValueError, lambda: factorial2(-4)) assert factorial2(n).is_integer is None assert factorial2(tt - 1).is_integer assert factorial2(tte - 1).is_integer assert factorial2(tpe - 3).is_integer assert factorial2(tto - 4).is_integer assert factorial2(tto - 2).is_integer assert factorial2(tf).is_integer is None assert factorial2(tfe).is_integer is None assert factorial2(tfo).is_integer is None assert factorial2(ft).is_integer is None assert factorial2(ff).is_integer is None assert factorial2(fn).is_integer is None assert factorial2(nt).is_integer is None assert factorial2(nf).is_integer is None assert factorial2(nn).is_integer is None assert factorial2(n).is_positive is None assert factorial2(tt - 1).is_positive is True assert factorial2(tte - 1).is_positive is True assert factorial2(tpe - 3).is_positive is True assert factorial2(tpe - 1).is_positive is True assert factorial2(tto - 2).is_positive is True assert factorial2(tto - 1).is_positive is True assert factorial2(tf).is_positive is None assert factorial2(tfe).is_positive is None assert factorial2(tfo).is_positive is None assert factorial2(ft).is_positive is None assert factorial2(ff).is_positive is None assert factorial2(fn).is_positive is None assert factorial2(nt).is_positive is None assert factorial2(nf).is_positive is None assert factorial2(nn).is_positive is None assert factorial2(tt).is_even is None assert factorial2(tt).is_odd is None assert factorial2(tte).is_even is None assert factorial2(tte).is_odd is None assert factorial2(tte + 2).is_even is True assert factorial2(tpe).is_even is True assert factorial2(tpe).is_odd is False assert factorial2(tto).is_odd is True assert factorial2(tf).is_even is None assert factorial2(tf).is_odd is None assert factorial2(tfe).is_even is None assert factorial2(tfe).is_odd is None assert factorial2(tfo).is_even is False assert factorial2(tfo).is_odd is None assert factorial2(z).is_even is False assert factorial2(z).is_odd is True def test_factorial2_rewrite(): n = Symbol('n', integer=True) assert factorial2(n).rewrite(gamma) == \ 2**(n/2)*Piecewise((1, Eq(Mod(n, 2), 0)), (sqrt(2)/sqrt(pi), Eq(Mod(n, 2), 1)))*gamma(n/2 + 1) assert factorial2(2*n).rewrite(gamma) == 2**n*gamma(n + 1) assert factorial2(2*n + 1).rewrite(gamma) == \ sqrt(2)*2**(n + S.Half)*gamma(n + Rational(3, 2))/sqrt(pi) def test_binomial(): x = Symbol('x') n = Symbol('n', integer=True) nz = Symbol('nz', integer=True, nonzero=True) k = Symbol('k', integer=True) kp = Symbol('kp', integer=True, positive=True) kn = Symbol('kn', integer=True, negative=True) u = Symbol('u', negative=True) v = Symbol('v', nonnegative=True) p = Symbol('p', positive=True) z = Symbol('z', zero=True) nt = Symbol('nt', integer=False) kt = Symbol('kt', integer=False) a = Symbol('a', integer=True, nonnegative=True) b = Symbol('b', integer=True, nonnegative=True) assert binomial(0, 0) == 1 assert binomial(1, 1) == 1 assert binomial(10, 10) == 1 assert binomial(n, z) == 1 assert binomial(1, 2) == 0 assert binomial(-1, 2) == 1 assert binomial(1, -1) == 0 assert binomial(-1, 1) == -1 assert binomial(-1, -1) == 0 assert binomial(S.Half, S.Half) == 1 assert binomial(-10, 1) == -10 assert binomial(-10, 7) == -11440 assert binomial(n, -1) == 0 # holds for all integers (negative, zero, positive) assert binomial(kp, -1) == 0 assert binomial(nz, 0) == 1 assert expand_func(binomial(n, 1)) == n assert expand_func(binomial(n, 2)) == n*(n - 1)/2 assert expand_func(binomial(n, n - 2)) == n*(n - 1)/2 assert expand_func(binomial(n, n - 1)) == n assert binomial(n, 3).func == binomial assert binomial(n, 3).expand(func=True) == n**3/6 - n**2/2 + n/3 assert expand_func(binomial(n, 3)) == n*(n - 2)*(n - 1)/6 assert binomial(n, n).func == binomial # e.g. (-1, -1) == 0, (2, 2) == 1 assert binomial(n, n + 1).func == binomial # e.g. (-1, 0) == 1 assert binomial(kp, kp + 1) == 0 assert binomial(kn, kn) == 0 # issue #14529 assert binomial(n, u).func == binomial assert binomial(kp, u).func == binomial assert binomial(n, p).func == binomial assert binomial(n, k).func == binomial assert binomial(n, n + p).func == binomial assert binomial(kp, kp + p).func == binomial assert expand_func(binomial(n, n - 3)) == n*(n - 2)*(n - 1)/6 assert binomial(n, k).is_integer assert binomial(nt, k).is_integer is None assert binomial(x, nt).is_integer is False assert binomial(gamma(25), 6) == 79232165267303928292058750056084441948572511312165380965440075720159859792344339983120618959044048198214221915637090855535036339620413440000 assert binomial(1324, 47) == 906266255662694632984994480774946083064699457235920708992926525848438478406790323869952 assert binomial(1735, 43) == 190910140420204130794758005450919715396159959034348676124678207874195064798202216379800 assert binomial(2512, 53) == 213894469313832631145798303740098720367984955243020898718979538096223399813295457822575338958939834177325304000 assert binomial(3383, 52) == 27922807788818096863529701501764372757272890613101645521813434902890007725667814813832027795881839396839287659777235 assert binomial(4321, 51) == 124595639629264868916081001263541480185227731958274383287107643816863897851139048158022599533438936036467601690983780576 assert binomial(a, b).is_nonnegative is True assert binomial(-1, 2, evaluate=False).is_nonnegative is True assert binomial(10, 5, evaluate=False).is_nonnegative is True assert binomial(10, -3, evaluate=False).is_nonnegative is True assert binomial(-10, -3, evaluate=False).is_nonnegative is True assert binomial(-10, 2, evaluate=False).is_nonnegative is True assert binomial(-10, 1, evaluate=False).is_nonnegative is False assert binomial(-10, 7, evaluate=False).is_nonnegative is False # issue #14625 for _ in (pi, -pi, nt, v, a): assert binomial(_, _) == 1 assert binomial(_, _ - 1) == _ assert isinstance(binomial(u, u), binomial) assert isinstance(binomial(u, u - 1), binomial) assert isinstance(binomial(x, x), binomial) assert isinstance(binomial(x, x - 1), binomial) #issue #18802 assert expand_func(binomial(x + 1, x)) == x + 1 assert expand_func(binomial(x, x - 1)) == x assert expand_func(binomial(x + 1, x - 1)) == x*(x + 1)/2 assert expand_func(binomial(x**2 + 1, x**2)) == x**2 + 1 # issue #13980 and #13981 assert binomial(-7, -5) == 0 assert binomial(-23, -12) == 0 assert binomial(Rational(13, 2), -10) == 0 assert binomial(-49, -51) == 0 assert binomial(19, Rational(-7, 2)) == S(-68719476736)/(911337863661225*pi) assert binomial(0, Rational(3, 2)) == S(-2)/(3*pi) assert binomial(-3, Rational(-7, 2)) is zoo assert binomial(kn, kt) is zoo assert binomial(nt, kt).func == binomial assert binomial(nt, Rational(15, 6)) == 8*gamma(nt + 1)/(15*sqrt(pi)*gamma(nt - Rational(3, 2))) assert binomial(Rational(20, 3), Rational(-10, 8)) == gamma(Rational(23, 3))/(gamma(Rational(-1, 4))*gamma(Rational(107, 12))) assert binomial(Rational(19, 2), Rational(-7, 2)) == Rational(-1615, 8388608) assert binomial(Rational(-13, 5), Rational(-7, 8)) == gamma(Rational(-8, 5))/(gamma(Rational(-29, 40))*gamma(Rational(1, 8))) assert binomial(Rational(-19, 8), Rational(-13, 5)) == gamma(Rational(-11, 8))/(gamma(Rational(-8, 5))*gamma(Rational(49, 40))) # binomial for complexes assert binomial(I, Rational(-89, 8)) == gamma(1 + I)/(gamma(Rational(-81, 8))*gamma(Rational(97, 8) + I)) assert binomial(I, 2*I) == gamma(1 + I)/(gamma(1 - I)*gamma(1 + 2*I)) assert binomial(-7, I) is zoo assert binomial(Rational(-7, 6), I) == gamma(Rational(-1, 6))/(gamma(Rational(-1, 6) - I)*gamma(1 + I)) assert binomial((1+2*I), (1+3*I)) == gamma(2 + 2*I)/(gamma(1 - I)*gamma(2 + 3*I)) assert binomial(I, 5) == Rational(1, 3) - I/S(12) assert binomial((2*I + 3), 7) == -13*I/S(63) assert isinstance(binomial(I, n), binomial) assert expand_func(binomial(3, 2, evaluate=False)) == 3 assert expand_func(binomial(n, 0, evaluate=False)) == 1 assert expand_func(binomial(n, -2, evaluate=False)) == 0 assert expand_func(binomial(n, k)) == binomial(n, k) def test_binomial_Mod(): p, q = 10**5 + 3, 10**9 + 33 # prime modulo r = 10**7 + 5 # composite modulo # A few tests to get coverage # Lucas Theorem assert Mod(binomial(156675, 4433, evaluate=False), p) == Mod(binomial(156675, 4433), p) # factorial Mod assert Mod(binomial(1234, 432, evaluate=False), q) == Mod(binomial(1234, 432), q) # binomial factorize assert Mod(binomial(253, 113, evaluate=False), r) == Mod(binomial(253, 113), r) @slow def test_binomial_Mod_slow(): p, q = 10**5 + 3, 10**9 + 33 # prime modulo r, s = 10**7 + 5, 33333333 # composite modulo n, k, m = symbols('n k m') assert (binomial(n, k) % q).subs({n: s, k: p}) == Mod(binomial(s, p), q) assert (binomial(n, k) % m).subs({n: 8, k: 5, m: 13}) == 4 assert (binomial(9, k) % 7).subs(k, 2) == 1 # Lucas Theorem assert Mod(binomial(123456, 43253, evaluate=False), p) == Mod(binomial(123456, 43253), p) assert Mod(binomial(-178911, 237, evaluate=False), p) == Mod(-binomial(178911 + 237 - 1, 237), p) assert Mod(binomial(-178911, 238, evaluate=False), p) == Mod(binomial(178911 + 238 - 1, 238), p) # factorial Mod assert Mod(binomial(9734, 451, evaluate=False), q) == Mod(binomial(9734, 451), q) assert Mod(binomial(-10733, 4459, evaluate=False), q) == Mod(binomial(-10733, 4459), q) assert Mod(binomial(-15733, 4458, evaluate=False), q) == Mod(binomial(-15733, 4458), q) assert Mod(binomial(23, -38, evaluate=False), q) is S.Zero assert Mod(binomial(23, 38, evaluate=False), q) is S.Zero # binomial factorize assert Mod(binomial(753, 119, evaluate=False), r) == Mod(binomial(753, 119), r) assert Mod(binomial(3781, 948, evaluate=False), s) == Mod(binomial(3781, 948), s) assert Mod(binomial(25773, 1793, evaluate=False), s) == Mod(binomial(25773, 1793), s) assert Mod(binomial(-753, 118, evaluate=False), r) == Mod(binomial(-753, 118), r) assert Mod(binomial(-25773, 1793, evaluate=False), s) == Mod(binomial(-25773, 1793), s) def test_binomial_diff(): n = Symbol('n', integer=True) k = Symbol('k', integer=True) assert binomial(n, k).diff(n) == \ (-polygamma(0, 1 + n - k) + polygamma(0, 1 + n))*binomial(n, k) assert binomial(n**2, k**3).diff(n) == \ 2*n*(-polygamma( 0, 1 + n**2 - k**3) + polygamma(0, 1 + n**2))*binomial(n**2, k**3) assert binomial(n, k).diff(k) == \ (-polygamma(0, 1 + k) + polygamma(0, 1 + n - k))*binomial(n, k) assert binomial(n**2, k**3).diff(k) == \ 3*k**2*(-polygamma( 0, 1 + k**3) + polygamma(0, 1 + n**2 - k**3))*binomial(n**2, k**3) raises(ArgumentIndexError, lambda: binomial(n, k).fdiff(3)) def test_binomial_rewrite(): n = Symbol('n', integer=True) k = Symbol('k', integer=True) x = Symbol('x') assert binomial(n, k).rewrite( factorial) == factorial(n)/(factorial(k)*factorial(n - k)) assert binomial( n, k).rewrite(gamma) == gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1)) assert binomial(n, k).rewrite(ff) == ff(n, k) / factorial(k) assert binomial(n, x).rewrite(ff) == binomial(n, x) @XFAIL def test_factorial_simplify_fail(): # simplify(factorial(x + 1).diff(x) - ((x + 1)*factorial(x)).diff(x))) == 0 from sympy.abc import x assert simplify(x*polygamma(0, x + 1) - x*polygamma(0, x + 2) + polygamma(0, x + 1) - polygamma(0, x + 2) + 1) == 0 def test_subfactorial(): assert all(subfactorial(i) == ans for i, ans in enumerate( [1, 0, 1, 2, 9, 44, 265, 1854, 14833, 133496])) assert subfactorial(oo) is oo assert subfactorial(nan) is nan assert subfactorial(23) == 9510425471055777937262 assert unchanged(subfactorial, 2.2) x = Symbol('x') assert subfactorial(x).rewrite(uppergamma) == uppergamma(x + 1, -1)/S.Exp1 tt = Symbol('tt', integer=True, nonnegative=True) tf = Symbol('tf', integer=True, nonnegative=False) tn = Symbol('tf', integer=True) ft = Symbol('ft', integer=False, nonnegative=True) ff = Symbol('ff', integer=False, nonnegative=False) fn = Symbol('ff', integer=False) nt = Symbol('nt', nonnegative=True) nf = Symbol('nf', nonnegative=False) nn = Symbol('nf') te = Symbol('te', even=True, nonnegative=True) to = Symbol('to', odd=True, nonnegative=True) assert subfactorial(tt).is_integer assert subfactorial(tf).is_integer is None assert subfactorial(tn).is_integer is None assert subfactorial(ft).is_integer is None assert subfactorial(ff).is_integer is None assert subfactorial(fn).is_integer is None assert subfactorial(nt).is_integer is None assert subfactorial(nf).is_integer is None assert subfactorial(nn).is_integer is None assert subfactorial(tt).is_nonnegative assert subfactorial(tf).is_nonnegative is None assert subfactorial(tn).is_nonnegative is None assert subfactorial(ft).is_nonnegative is None assert subfactorial(ff).is_nonnegative is None assert subfactorial(fn).is_nonnegative is None assert subfactorial(nt).is_nonnegative is None assert subfactorial(nf).is_nonnegative is None assert subfactorial(nn).is_nonnegative is None assert subfactorial(tt).is_even is None assert subfactorial(tt).is_odd is None assert subfactorial(te).is_odd is True assert subfactorial(to).is_even is True
81cf27d196a70ac6dc4ce515c4c9499b4fd8650a75006f910469b84a7ec79636
import string from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.core.function import (diff, expand_func) from sympy.core import (EulerGamma, TribonacciConstant) from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.combinatorial.numbers import carmichael from sympy.functions.elementary.complexes import (im, re) from sympy.functions.elementary.integers import floor from sympy.polys.polytools import cancel from sympy.series.limits import limit from sympy.functions import ( bernoulli, harmonic, bell, fibonacci, tribonacci, lucas, euler, catalan, genocchi, partition, motzkin, binomial, gamma, sqrt, cbrt, hyper, log, digamma, trigamma, polygamma, factorial, sin, cos, cot, zeta) from sympy.functions.combinatorial.numbers import _nT from sympy.core.expr import unchanged from sympy.core.numbers import GoldenRatio, Integer from sympy.testing.pytest import XFAIL, raises, nocache_fail from sympy.abc import x def test_carmichael(): assert carmichael.find_carmichael_numbers_in_range(0, 561) == [] assert carmichael.find_carmichael_numbers_in_range(561, 562) == [561] assert carmichael.find_carmichael_numbers_in_range(561, 1105) == carmichael.find_carmichael_numbers_in_range(561, 562) assert carmichael.find_first_n_carmichaels(5) == [561, 1105, 1729, 2465, 2821] assert carmichael.is_prime(2821) == False assert carmichael.is_prime(2465) == False assert carmichael.is_prime(1729) == False assert carmichael.is_prime(1105) == False assert carmichael.is_prime(561) == False raises(ValueError, lambda: carmichael.is_carmichael(-2)) raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(-2, 2)) raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(22, 2)) def test_bernoulli(): assert bernoulli(0) == 1 assert bernoulli(1) == Rational(-1, 2) assert bernoulli(2) == Rational(1, 6) assert bernoulli(3) == 0 assert bernoulli(4) == Rational(-1, 30) assert bernoulli(5) == 0 assert bernoulli(6) == Rational(1, 42) assert bernoulli(7) == 0 assert bernoulli(8) == Rational(-1, 30) assert bernoulli(10) == Rational(5, 66) assert bernoulli(1000001) == 0 assert bernoulli(0, x) == 1 assert bernoulli(1, x) == x - S.Half assert bernoulli(2, x) == x**2 - x + Rational(1, 6) assert bernoulli(3, x) == x**3 - (3*x**2)/2 + x/2 # Should be fast; computed with mpmath b = bernoulli(1000) assert b.p % 10**10 == 7950421099 assert b.q == 342999030 b = bernoulli(10**6, evaluate=False).evalf() assert str(b) == '-2.23799235765713e+4767529' # Issue #8527 l = Symbol('l', integer=True) m = Symbol('m', integer=True, nonnegative=True) n = Symbol('n', integer=True, positive=True) assert isinstance(bernoulli(2 * l + 1), bernoulli) assert isinstance(bernoulli(2 * m + 1), bernoulli) assert bernoulli(2 * n + 1) == 0 raises(ValueError, lambda: bernoulli(-2)) def test_fibonacci(): assert [fibonacci(n) for n in range(-3, 5)] == [2, -1, 1, 0, 1, 1, 2, 3] assert fibonacci(100) == 354224848179261915075 assert [lucas(n) for n in range(-3, 5)] == [-4, 3, -1, 2, 1, 3, 4, 7] assert lucas(100) == 792070839848372253127 assert fibonacci(1, x) == 1 assert fibonacci(2, x) == x assert fibonacci(3, x) == x**2 + 1 assert fibonacci(4, x) == x**3 + 2*x # issue #8800 n = Dummy('n') assert fibonacci(n).limit(n, S.Infinity) is S.Infinity assert lucas(n).limit(n, S.Infinity) is S.Infinity assert fibonacci(n).rewrite(sqrt) == \ 2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5 assert fibonacci(n).rewrite(sqrt).subs(n, 10).expand() == fibonacci(10) assert fibonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \ fibonacci(10) assert lucas(n).rewrite(sqrt) == \ (fibonacci(n-1).rewrite(sqrt) + fibonacci(n+1).rewrite(sqrt)).simplify() assert lucas(n).rewrite(sqrt).subs(n, 10).expand() == lucas(10) raises(ValueError, lambda: fibonacci(-3, x)) def test_tribonacci(): assert [tribonacci(n) for n in range(8)] == [0, 1, 1, 2, 4, 7, 13, 24] assert tribonacci(100) == 98079530178586034536500564 assert tribonacci(0, x) == 0 assert tribonacci(1, x) == 1 assert tribonacci(2, x) == x**2 assert tribonacci(3, x) == x**4 + x assert tribonacci(4, x) == x**6 + 2*x**3 + 1 assert tribonacci(5, x) == x**8 + 3*x**5 + 3*x**2 n = Dummy('n') assert tribonacci(n).limit(n, S.Infinity) is S.Infinity w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2 a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3 b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3 c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3 assert tribonacci(n).rewrite(sqrt) == \ (a**(n + 1)/((a - b)*(a - c)) + b**(n + 1)/((b - a)*(b - c)) + c**(n + 1)/((c - a)*(c - b))) assert tribonacci(n).rewrite(sqrt).subs(n, 4).simplify() == tribonacci(4) assert tribonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \ tribonacci(10) assert tribonacci(n).rewrite(TribonacciConstant) == floor( 3*TribonacciConstant**n*(102*sqrt(33) + 586)**Rational(1, 3)/ (-2*(102*sqrt(33) + 586)**Rational(1, 3) + 4 + (102*sqrt(33) + 586)**Rational(2, 3)) + S.Half) raises(ValueError, lambda: tribonacci(-1, x)) @nocache_fail def test_bell(): assert [bell(n) for n in range(8)] == [1, 1, 2, 5, 15, 52, 203, 877] assert bell(0, x) == 1 assert bell(1, x) == x assert bell(2, x) == x**2 + x assert bell(5, x) == x**5 + 10*x**4 + 25*x**3 + 15*x**2 + x assert bell(oo) is S.Infinity raises(ValueError, lambda: bell(oo, x)) raises(ValueError, lambda: bell(-1)) raises(ValueError, lambda: bell(S.Half)) X = symbols('x:6') # X = (x0, x1, .. x5) # at the same time: X[1] = x1, X[2] = x2 for standard readablity. # but we must supply zero-based indexed object X[1:] = (x1, .. x5) assert bell(6, 2, X[1:]) == 6*X[5]*X[1] + 15*X[4]*X[2] + 10*X[3]**2 assert bell( 6, 3, X[1:]) == 15*X[4]*X[1]**2 + 60*X[3]*X[2]*X[1] + 15*X[2]**3 X = (1, 10, 100, 1000, 10000) assert bell(6, 2, X) == (6 + 15 + 10)*10000 X = (1, 2, 3, 3, 5) assert bell(6, 2, X) == 6*5 + 15*3*2 + 10*3**2 X = (1, 2, 3, 5) assert bell(6, 3, X) == 15*5 + 60*3*2 + 15*2**3 # Dobinski's formula n = Symbol('n', integer=True, nonnegative=True) # For large numbers, this is too slow # For nonintegers, there are significant precision errors for i in [0, 2, 3, 7, 13, 42, 55]: # Running without the cache this is either very slow or goes into an # infinite loop. assert bell(i).evalf() == bell(n).rewrite(Sum).evalf(subs={n: i}) m = Symbol("m") assert bell(m).rewrite(Sum) == bell(m) assert bell(n, m).rewrite(Sum) == bell(n, m) # issue 9184 n = Dummy('n') assert bell(n).limit(n, S.Infinity) is S.Infinity def test_harmonic(): n = Symbol("n") m = Symbol("m") assert harmonic(n, 0) == n assert harmonic(n).evalf() == harmonic(n) assert harmonic(n, 1) == harmonic(n) assert harmonic(1, n).evalf() == harmonic(1, n) assert harmonic(0, 1) == 0 assert harmonic(1, 1) == 1 assert harmonic(2, 1) == Rational(3, 2) assert harmonic(3, 1) == Rational(11, 6) assert harmonic(4, 1) == Rational(25, 12) assert harmonic(0, 2) == 0 assert harmonic(1, 2) == 1 assert harmonic(2, 2) == Rational(5, 4) assert harmonic(3, 2) == Rational(49, 36) assert harmonic(4, 2) == Rational(205, 144) assert harmonic(0, 3) == 0 assert harmonic(1, 3) == 1 assert harmonic(2, 3) == Rational(9, 8) assert harmonic(3, 3) == Rational(251, 216) assert harmonic(4, 3) == Rational(2035, 1728) assert harmonic(oo, -1) is S.NaN assert harmonic(oo, 0) is oo assert harmonic(oo, S.Half) is oo assert harmonic(oo, 1) is oo assert harmonic(oo, 2) == (pi**2)/6 assert harmonic(oo, 3) == zeta(3) assert harmonic(oo, Dummy(negative=True)) is S.NaN ip = Dummy(integer=True, positive=True) if (1/ip <= 1) is True: #---------------------------------+ assert None, 'delete this if-block and the next line' #| ip = Dummy(even=True, positive=True) #--------------------+ assert harmonic(oo, 1/ip) is oo assert harmonic(oo, 1 + ip) is zeta(1 + ip) assert harmonic(0, m) == 0 def test_harmonic_rational(): ne = S(6) no = S(5) pe = S(8) po = S(9) qe = S(10) qo = S(13) Heee = harmonic(ne + pe/qe) Aeee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8))) + 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8))) + pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(13944145, 4720968)) Heeo = harmonic(ne + pe/qo) Aeeo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(4, 13)) + 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(32, 13)) + 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13)) - 2*log(sin(pi*Rational(4, 13)))*cos(pi/13) + pi*cot(pi*Rational(5, 13))/2 - 2*log(sin(pi/13))*cos(pi*Rational(3, 13)) + Rational(2422020029, 702257080)) Heoe = harmonic(ne + po/qe) Aeoe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8))) + 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8))) + 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4) + Rational(11818877030, 4286604231) + pi*sqrt(2*sqrt(5) + 5)/2) Heoo = harmonic(ne + po/qo) Aeoo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(54, 13)) + 2*log(sin(pi*Rational(4, 13)))*cos(pi*Rational(6, 13)) + 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13) - 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2 - 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(3, 13)) + Rational(11669332571, 3628714320)) Hoee = harmonic(no + pe/qe) Aoee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8))) + 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8))) + pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(779405, 277704)) Hoeo = harmonic(no + pe/qo) Aoeo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(4, 13)) + 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(32, 13)) + 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13)) - 2*log(sin(pi*Rational(4, 13)))*cos(pi/13) + pi*cot(pi*Rational(5, 13))/2 - 2*log(sin(pi/13))*cos(pi*Rational(3, 13)) + Rational(53857323, 16331560)) Hooe = harmonic(no + po/qe) Aooe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8))) + 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8))) + 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4) + Rational(486853480, 186374097) + pi*sqrt(2*sqrt(5) + 5)/2) Hooo = harmonic(no + po/qo) Aooo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(54, 13)) + 2*log(sin(pi*Rational(4, 13)))*cos(pi*Rational(6, 13)) + 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13) - 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2 - 2*log(sin(pi*Rational(2, 13)))*cos(3*pi/13) + Rational(383693479, 125128080)) H = [Heee, Heeo, Heoe, Heoo, Hoee, Hoeo, Hooe, Hooo] A = [Aeee, Aeeo, Aeoe, Aeoo, Aoee, Aoeo, Aooe, Aooo] for h, a in zip(H, A): e = expand_func(h).doit() assert cancel(e/a) == 1 assert abs(h.n() - a.n()) < 1e-12 def test_harmonic_evalf(): assert str(harmonic(1.5).evalf(n=10)) == '1.280372306' assert str(harmonic(1.5, 2).evalf(n=10)) == '1.154576311' # issue 7443 def test_harmonic_rewrite(): n = Symbol("n") m = Symbol("m") assert harmonic(n).rewrite(digamma) == polygamma(0, n + 1) + EulerGamma assert harmonic(n).rewrite(trigamma) == polygamma(0, n + 1) + EulerGamma assert harmonic(n).rewrite(polygamma) == polygamma(0, n + 1) + EulerGamma assert harmonic(n,3).rewrite(polygamma) == polygamma(2, n + 1)/2 - polygamma(2, 1)/2 assert harmonic(n,m).rewrite(polygamma) == (-1)**m*(polygamma(m - 1, 1) - polygamma(m - 1, n + 1))/factorial(m - 1) assert expand_func(harmonic(n+4)) == harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1) assert expand_func(harmonic(n-4)) == harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n assert harmonic(n, m).rewrite("tractable") == harmonic(n, m).rewrite(polygamma) _k = Dummy("k") assert harmonic(n).rewrite(Sum).dummy_eq(Sum(1/_k, (_k, 1, n))) assert harmonic(n, m).rewrite(Sum).dummy_eq(Sum(_k**(-m), (_k, 1, n))) @XFAIL def test_harmonic_limit_fail(): n = Symbol("n") m = Symbol("m") # For m > 1: assert limit(harmonic(n, m), n, oo) == zeta(m) def test_euler(): assert euler(0) == 1 assert euler(1) == 0 assert euler(2) == -1 assert euler(3) == 0 assert euler(4) == 5 assert euler(6) == -61 assert euler(8) == 1385 assert euler(20, evaluate=False) != 370371188237525 n = Symbol('n', integer=True) assert euler(n) != -1 assert euler(n).subs(n, 2) == -1 raises(ValueError, lambda: euler(-2)) raises(ValueError, lambda: euler(-3)) raises(ValueError, lambda: euler(2.3)) assert euler(20).evalf() == 370371188237525.0 assert euler(20, evaluate=False).evalf() == 370371188237525.0 assert euler(n).rewrite(Sum) == euler(n) n = Symbol('n', integer=True, nonnegative=True) assert euler(2*n + 1).rewrite(Sum) == 0 _j = Dummy('j') _k = Dummy('k') assert euler(2*n).rewrite(Sum).dummy_eq( I*Sum((-1)**_j*2**(-_k)*I**(-_k)*(-2*_j + _k)**(2*n + 1)* binomial(_k, _j)/_k, (_j, 0, _k), (_k, 1, 2*n + 1))) def test_euler_odd(): n = Symbol('n', odd=True, positive=True) assert euler(n) == 0 n = Symbol('n', odd=True) assert euler(n) != 0 def test_euler_polynomials(): assert euler(0, x) == 1 assert euler(1, x) == x - S.Half assert euler(2, x) == x**2 - x assert euler(3, x) == x**3 - (3*x**2)/2 + Rational(1, 4) m = Symbol('m') assert isinstance(euler(m, x), euler) from sympy.core.numbers import Float A = Float('-0.46237208575048694923364757452876131e8') # from Maple B = euler(19, S.Pi.evalf(32)) assert abs((A - B)/A) < 1e-31 # expect low relative error C = euler(19, S.Pi, evaluate=False).evalf(32) assert abs((A - C)/A) < 1e-31 def test_euler_polynomial_rewrite(): m = Symbol('m') A = euler(m, x).rewrite('Sum'); assert A.subs({m:3, x:5}).doit() == euler(3, 5) def test_catalan(): n = Symbol('n', integer=True) m = Symbol('m', integer=True, positive=True) k = Symbol('k', integer=True, nonnegative=True) p = Symbol('p', nonnegative=True) catalans = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786] for i, c in enumerate(catalans): assert catalan(i) == c assert catalan(n).rewrite(factorial).subs(n, i) == c assert catalan(n).rewrite(Product).subs(n, i).doit() == c assert unchanged(catalan, x) assert catalan(2*x).rewrite(binomial) == binomial(4*x, 2*x)/(2*x + 1) assert catalan(S.Half).rewrite(gamma) == 8/(3*pi) assert catalan(S.Half).rewrite(factorial).rewrite(gamma) ==\ 8 / (3 * pi) assert catalan(3*x).rewrite(gamma) == 4**( 3*x)*gamma(3*x + S.Half)/(sqrt(pi)*gamma(3*x + 2)) assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2,), 1) assert catalan(n).rewrite(factorial) == factorial(2*n) / (factorial(n + 1) * factorial(n)) assert isinstance(catalan(n).rewrite(Product), catalan) assert isinstance(catalan(m).rewrite(Product), Product) assert diff(catalan(x), x) == (polygamma( 0, x + S.Half) - polygamma(0, x + 2) + log(4))*catalan(x) assert catalan(x).evalf() == catalan(x) c = catalan(S.Half).evalf() assert str(c) == '0.848826363156775' c = catalan(I).evalf(3) assert str((re(c), im(c))) == '(0.398, -0.0209)' # Assumptions assert catalan(p).is_positive is True assert catalan(k).is_integer is True assert catalan(m+3).is_composite is True def test_genocchi(): genocchis = [1, -1, 0, 1, 0, -3, 0, 17] for n, g in enumerate(genocchis): assert genocchi(n + 1) == g m = Symbol('m', integer=True) n = Symbol('n', integer=True, positive=True) assert unchanged(genocchi, m) assert genocchi(2*n + 1) == 0 assert genocchi(n).rewrite(bernoulli) == (1 - 2 ** n) * bernoulli(n) * 2 assert genocchi(2 * n).is_odd assert genocchi(2 * n).is_even is False assert genocchi(2 * n + 1).is_even assert genocchi(n).is_integer assert genocchi(4 * n).is_positive # these are the only 2 prime Genocchi numbers assert genocchi(6, evaluate=False).is_prime == S(-3).is_prime assert genocchi(8, evaluate=False).is_prime assert genocchi(4 * n + 2).is_negative assert genocchi(4 * n + 1).is_negative is False assert genocchi(4 * n - 2).is_negative raises(ValueError, lambda: genocchi(Rational(5, 4))) raises(ValueError, lambda: genocchi(-2)) @nocache_fail def test_partition(): partition_nums = [1, 1, 2, 3, 5, 7, 11, 15, 22] for n, p in enumerate(partition_nums): assert partition(n) == p x = Symbol('x') y = Symbol('y', real=True) m = Symbol('m', integer=True) n = Symbol('n', integer=True, negative=True) p = Symbol('p', integer=True, nonnegative=True) assert partition(m).is_integer assert not partition(m).is_negative assert partition(m).is_nonnegative assert partition(n).is_zero assert partition(p).is_positive assert partition(x).subs(x, 7) == 15 assert partition(y).subs(y, 8) == 22 raises(ValueError, lambda: partition(Rational(5, 4))) def test__nT(): assert [_nT(i, j) for i in range(5) for j in range(i + 2)] == [ 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 2, 1, 1, 0] check = [_nT(10, i) for i in range(11)] assert check == [0, 1, 5, 8, 9, 7, 5, 3, 2, 1, 1] assert all(type(i) is int for i in check) assert _nT(10, 5) == 7 assert _nT(100, 98) == 2 assert _nT(100, 100) == 1 assert _nT(10, 3) == 8 def test_nC_nP_nT(): from sympy.utilities.iterables import ( multiset_permutations, multiset_combinations, multiset_partitions, partitions, subsets, permutations) from sympy.functions.combinatorial.numbers import ( nP, nC, nT, stirling, _stirling1, _stirling2, _multiset_histogram, _AOP_product) from sympy.combinatorics.permutations import Permutation from random import choice c = string.ascii_lowercase for i in range(100): s = ''.join(choice(c) for i in range(7)) u = len(s) == len(set(s)) try: tot = 0 for i in range(8): check = nP(s, i) tot += check assert len(list(multiset_permutations(s, i))) == check if u: assert nP(len(s), i) == check assert nP(s) == tot except AssertionError: print(s, i, 'failed perm test') raise ValueError() for i in range(100): s = ''.join(choice(c) for i in range(7)) u = len(s) == len(set(s)) try: tot = 0 for i in range(8): check = nC(s, i) tot += check assert len(list(multiset_combinations(s, i))) == check if u: assert nC(len(s), i) == check assert nC(s) == tot if u: assert nC(len(s)) == tot except AssertionError: print(s, i, 'failed combo test') raise ValueError() for i in range(1, 10): tot = 0 for j in range(1, i + 2): check = nT(i, j) assert check.is_Integer tot += check assert sum(1 for p in partitions(i, j, size=True) if p[0] == j) == check assert nT(i) == tot for i in range(1, 10): tot = 0 for j in range(1, i + 2): check = nT(range(i), j) tot += check assert len(list(multiset_partitions(list(range(i)), j))) == check assert nT(range(i)) == tot for i in range(100): s = ''.join(choice(c) for i in range(7)) u = len(s) == len(set(s)) try: tot = 0 for i in range(1, 8): check = nT(s, i) tot += check assert len(list(multiset_partitions(s, i))) == check if u: assert nT(range(len(s)), i) == check if u: assert nT(range(len(s))) == tot assert nT(s) == tot except AssertionError: print(s, i, 'failed partition test') raise ValueError() # tests for Stirling numbers of the first kind that are not tested in the # above assert [stirling(9, i, kind=1) for i in range(11)] == [ 0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1, 0] perms = list(permutations(range(4))) assert [sum(1 for p in perms if Permutation(p).cycles == i) for i in range(5)] == [0, 6, 11, 6, 1] == [ stirling(4, i, kind=1) for i in range(5)] # http://oeis.org/A008275 assert [stirling(n, k, signed=1) for n in range(10) for k in range(1, n + 1)] == [ 1, -1, 1, 2, -3, 1, -6, 11, -6, 1, 24, -50, 35, -10, 1, -120, 274, -225, 85, -15, 1, 720, -1764, 1624, -735, 175, -21, 1, -5040, 13068, -13132, 6769, -1960, 322, -28, 1, 40320, -109584, 118124, -67284, 22449, -4536, 546, -36, 1] # https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind assert [stirling(n, k, kind=1) for n in range(10) for k in range(n+1)] == [ 1, 0, 1, 0, 1, 1, 0, 2, 3, 1, 0, 6, 11, 6, 1, 0, 24, 50, 35, 10, 1, 0, 120, 274, 225, 85, 15, 1, 0, 720, 1764, 1624, 735, 175, 21, 1, 0, 5040, 13068, 13132, 6769, 1960, 322, 28, 1, 0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1] # https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind assert [stirling(n, k, kind=2) for n in range(10) for k in range(n+1)] == [ 1, 0, 1, 0, 1, 1, 0, 1, 3, 1, 0, 1, 7, 6, 1, 0, 1, 15, 25, 10, 1, 0, 1, 31, 90, 65, 15, 1, 0, 1, 63, 301, 350, 140, 21, 1, 0, 1, 127, 966, 1701, 1050, 266, 28, 1, 0, 1, 255, 3025, 7770, 6951, 2646, 462, 36, 1] assert stirling(3, 4, kind=1) == stirling(3, 4, kind=1) == 0 raises(ValueError, lambda: stirling(-2, 2)) # Assertion that the return type is SymPy Integer. assert isinstance(_stirling1(6, 3), Integer) assert isinstance(_stirling2(6, 3), Integer) def delta(p): if len(p) == 1: return oo return min(abs(i[0] - i[1]) for i in subsets(p, 2)) parts = multiset_partitions(range(5), 3) d = 2 assert (sum(1 for p in parts if all(delta(i) >= d for i in p)) == stirling(5, 3, d=d) == 7) # other coverage tests assert nC('abb', 2) == nC('aab', 2) == 2 assert nP(3, 3, replacement=True) == nP('aabc', 3, replacement=True) == 27 assert nP(3, 4) == 0 assert nP('aabc', 5) == 0 assert nC(4, 2, replacement=True) == nC('abcdd', 2, replacement=True) == \ len(list(multiset_combinations('aabbccdd', 2))) == 10 assert nC('abcdd') == sum(nC('abcdd', i) for i in range(6)) == 24 assert nC(list('abcdd'), 4) == 4 assert nT('aaaa') == nT(4) == len(list(partitions(4))) == 5 assert nT('aaab') == len(list(multiset_partitions('aaab'))) == 7 assert nC('aabb'*3, 3) == 4 # aaa, bbb, abb, baa assert dict(_AOP_product((4,1,1,1))) == { 0: 1, 1: 4, 2: 7, 3: 8, 4: 8, 5: 7, 6: 4, 7: 1} # the following was the first t that showed a problem in a previous form of # the function, so it's not as random as it may appear t = (3, 9, 4, 6, 6, 5, 5, 2, 10, 4) assert sum(_AOP_product(t)[i] for i in range(55)) == 58212000 raises(ValueError, lambda: _multiset_histogram({1:'a'})) def test_PR_14617(): from sympy.functions.combinatorial.numbers import nT for n in (0, []): for k in (-1, 0, 1): if k == 0: assert nT(n, k) == 1 else: assert nT(n, k) == 0 def test_issue_8496(): n = Symbol("n") k = Symbol("k") raises(TypeError, lambda: catalan(n, k)) def test_issue_8601(): n = Symbol('n', integer=True, negative=True) assert catalan(n - 1) is S.Zero assert catalan(Rational(-1, 2)) is S.ComplexInfinity assert catalan(-S.One) == Rational(-1, 2) c1 = catalan(-5.6).evalf() assert str(c1) == '6.93334070531408e-5' c2 = catalan(-35.4).evalf() assert str(c2) == '-4.14189164517449e-24' def test_motzkin(): assert motzkin.is_motzkin(4) == True assert motzkin.is_motzkin(9) == True assert motzkin.is_motzkin(10) == False assert motzkin.find_motzkin_numbers_in_range(10,200) == [21, 51, 127] assert motzkin.find_motzkin_numbers_in_range(10,400) == [21, 51, 127, 323] assert motzkin.find_motzkin_numbers_in_range(10,1600) == [21, 51, 127, 323, 835] assert motzkin.find_first_n_motzkins(5) == [1, 1, 2, 4, 9] assert motzkin.find_first_n_motzkins(7) == [1, 1, 2, 4, 9, 21, 51] assert motzkin.find_first_n_motzkins(10) == [1, 1, 2, 4, 9, 21, 51, 127, 323, 835] raises(ValueError, lambda: motzkin.eval(77.58)) raises(ValueError, lambda: motzkin.eval(-8)) raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(-2,7)) raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(13,7)) raises(ValueError, lambda: motzkin.find_first_n_motzkins(112.8)) def test_nD_derangements(): from sympy.utilities.iterables import (partitions, multiset, multiset_derangements, multiset_permutations) from sympy.functions.combinatorial.numbers import nD got = [] for i in partitions(8, k=4): s = [] it = 0 for k, v in i.items(): for i in range(v): s.extend([it]*k) it += 1 ms = multiset(s) c1 = sum(1 for i in multiset_permutations(s) if all(i != j for i, j in zip(i, s))) assert c1 == nD(ms) == nD(ms, 0) == nD(ms, 1) v = [tuple(i) for i in multiset_derangements(s)] c2 = len(v) assert c2 == len(set(v)) assert c1 == c2 got.append(c1) assert got == [1, 4, 6, 12, 24, 24, 61, 126, 315, 780, 297, 772, 2033, 5430, 14833] assert nD('1112233456', brute=True) == nD('1112233456') == 16356 assert nD('') == nD([]) == nD({}) == 0 assert nD({1: 0}) == 0 raises(ValueError, lambda: nD({1: -1})) assert nD('112') == 0 assert nD(i='112') == 0 assert [nD(n=i) for i in range(6)] == [0, 0, 1, 2, 9, 44] assert nD((i for i in range(4))) == nD('0123') == 9 assert nD(m=(i for i in range(4))) == 3 assert nD(m={0: 1, 1: 1, 2: 1, 3: 1}) == 3 assert nD(m=[0, 1, 2, 3]) == 3 raises(TypeError, lambda: nD(m=0)) raises(TypeError, lambda: nD(-1)) assert nD({-1: 1, -2: 1}) == 1 assert nD(m={0: 3}) == 0 raises(ValueError, lambda: nD(i='123', n=3)) raises(ValueError, lambda: nD(i='123', m=(1,2))) raises(ValueError, lambda: nD(n=0, m=(1,2))) raises(ValueError, lambda: nD({1: -1})) raises(ValueError, lambda: nD(m={-1: 1, 2: 1})) raises(ValueError, lambda: nD(m={1: -1, 2: 1})) raises(ValueError, lambda: nD(m=[-1, 2])) raises(TypeError, lambda: nD({1: x})) raises(TypeError, lambda: nD(m={1: x})) raises(TypeError, lambda: nD(m={x: 1}))
3c50586bd78ca2f1f95ce14de574f15abd550e3d440682b09f8980b63fbf0dd3
from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import exp x, y = symbols('x,y') e = exp(2*x) q = exp(3*x) def timeit_exp_subs(): e.subs(q, y)
483d2ac38aea8c8db3f5a7ea52682e7fd77e0d0329281b3cacd6b8070d93fa7a
from sympy.assumptions.refine import refine from sympy.calculus.util 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) 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*Rational(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 not x.func is 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) @_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
190c653a75774eda5e314bd4f054e65b7b8365152d56358bcefabadc1c0ba8f5
from sympy.calculus.util import AccumBounds from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo) 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.combinatorial.factorials import factorial from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.integers import (ceiling, floor, frac) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.core.expr import unchanged from sympy.testing.pytest import XFAIL x = Symbol('x') i = Symbol('i', imaginary=True) y = Symbol('y', real=True) k, n = symbols('k,n', integer=True) def test_floor(): assert floor(nan) is nan assert floor(oo) is oo assert floor(-oo) is -oo assert floor(zoo) is zoo assert floor(0) == 0 assert floor(1) == 1 assert floor(-1) == -1 assert floor(E) == 2 assert floor(-E) == -3 assert floor(2*E) == 5 assert floor(-2*E) == -6 assert floor(pi) == 3 assert floor(-pi) == -4 assert floor(S.Half) == 0 assert floor(Rational(-1, 2)) == -1 assert floor(Rational(7, 3)) == 2 assert floor(Rational(-7, 3)) == -3 assert floor(-Rational(7, 3)) == -3 assert floor(Float(17.0)) == 17 assert floor(-Float(17.0)) == -17 assert floor(Float(7.69)) == 7 assert floor(-Float(7.69)) == -8 assert floor(I) == I assert floor(-I) == -I e = floor(i) assert e.func is floor and e.args[0] == i assert floor(oo*I) == oo*I assert floor(-oo*I) == -oo*I assert floor(exp(I*pi/4)*oo) == exp(I*pi/4)*oo assert floor(2*I) == 2*I assert floor(-2*I) == -2*I assert floor(I/2) == 0 assert floor(-I/2) == -I assert floor(E + 17) == 19 assert floor(pi + 2) == 5 assert floor(E + pi) == 5 assert floor(I + pi) == 3 + I assert floor(floor(pi)) == 3 assert floor(floor(y)) == floor(y) assert floor(floor(x)) == floor(x) assert unchanged(floor, x) assert unchanged(floor, 2*x) assert unchanged(floor, k*x) assert floor(k) == k assert floor(2*k) == 2*k assert floor(k*n) == k*n assert unchanged(floor, k/2) assert unchanged(floor, x + y) assert floor(x + 3) == floor(x) + 3 assert floor(x + k) == floor(x) + k assert floor(y + 3) == floor(y) + 3 assert floor(y + k) == floor(y) + k assert floor(3 + I*y + pi) == 6 + floor(y)*I assert floor(k + n) == k + n assert unchanged(floor, x*I) assert floor(k*I) == k*I assert floor(Rational(23, 10) - E*I) == 2 - 3*I assert floor(sin(1)) == 0 assert floor(sin(-1)) == -1 assert floor(exp(2)) == 7 assert floor(log(8)/log(2)) != 2 assert int(floor(log(8)/log(2)).evalf(chop=True)) == 3 assert floor(factorial(50)/exp(1)) == \ 11188719610782480504630258070757734324011354208865721592720336800 assert (floor(y) < y) == False assert (floor(y) <= y) == True assert (floor(y) > y) == False assert (floor(y) >= y) == False assert (floor(x) <= x).is_Relational # x could be non-real assert (floor(x) > x).is_Relational assert (floor(x) <= y).is_Relational # arg is not same as rhs assert (floor(x) > y).is_Relational assert (floor(y) <= oo) == True assert (floor(y) < oo) == True assert (floor(y) >= -oo) == True assert (floor(y) > -oo) == True assert floor(y).rewrite(frac) == y - frac(y) assert floor(y).rewrite(ceiling) == -ceiling(-y) assert floor(y).rewrite(frac).subs(y, -pi) == floor(-pi) assert floor(y).rewrite(frac).subs(y, E) == floor(E) assert floor(y).rewrite(ceiling).subs(y, E) == -ceiling(-E) assert floor(y).rewrite(ceiling).subs(y, -pi) == -ceiling(pi) assert Eq(floor(y), y - frac(y)) assert Eq(floor(y), -ceiling(-y)) neg = Symbol('neg', negative=True) nn = Symbol('nn', nonnegative=True) pos = Symbol('pos', positive=True) np = Symbol('np', nonpositive=True) assert (floor(neg) < 0) == True assert (floor(neg) <= 0) == True assert (floor(neg) > 0) == False assert (floor(neg) >= 0) == False assert (floor(neg) <= -1) == True assert (floor(neg) >= -3) == (neg >= -3) assert (floor(neg) < 5) == (neg < 5) assert (floor(nn) < 0) == False assert (floor(nn) >= 0) == True assert (floor(pos) < 0) == False assert (floor(pos) <= 0) == (pos < 1) assert (floor(pos) > 0) == (pos >= 1) assert (floor(pos) >= 0) == True assert (floor(pos) >= 3) == (pos >= 3) assert (floor(np) <= 0) == True assert (floor(np) > 0) == False assert floor(neg).is_negative == True assert floor(neg).is_nonnegative == False assert floor(nn).is_negative == False assert floor(nn).is_nonnegative == True assert floor(pos).is_negative == False assert floor(pos).is_nonnegative == True assert floor(np).is_negative is None assert floor(np).is_nonnegative is None assert (floor(7, evaluate=False) >= 7) == True assert (floor(7, evaluate=False) > 7) == False assert (floor(7, evaluate=False) <= 7) == True assert (floor(7, evaluate=False) < 7) == False assert (floor(7, evaluate=False) >= 6) == True assert (floor(7, evaluate=False) > 6) == True assert (floor(7, evaluate=False) <= 6) == False assert (floor(7, evaluate=False) < 6) == False assert (floor(7, evaluate=False) >= 8) == False assert (floor(7, evaluate=False) > 8) == False assert (floor(7, evaluate=False) <= 8) == True assert (floor(7, evaluate=False) < 8) == True assert (floor(x) <= 5.5) == Le(floor(x), 5.5, evaluate=False) assert (floor(x) >= -3.2) == Ge(floor(x), -3.2, evaluate=False) assert (floor(x) < 2.9) == Lt(floor(x), 2.9, evaluate=False) assert (floor(x) > -1.7) == Gt(floor(x), -1.7, evaluate=False) assert (floor(y) <= 5.5) == (y < 6) assert (floor(y) >= -3.2) == (y >= -3) assert (floor(y) < 2.9) == (y < 3) assert (floor(y) > -1.7) == (y >= -1) assert (floor(y) <= n) == (y < n + 1) assert (floor(y) >= n) == (y >= n) assert (floor(y) < n) == (y < n) assert (floor(y) > n) == (y >= n + 1) def test_ceiling(): assert ceiling(nan) is nan assert ceiling(oo) is oo assert ceiling(-oo) is -oo assert ceiling(zoo) is zoo assert ceiling(0) == 0 assert ceiling(1) == 1 assert ceiling(-1) == -1 assert ceiling(E) == 3 assert ceiling(-E) == -2 assert ceiling(2*E) == 6 assert ceiling(-2*E) == -5 assert ceiling(pi) == 4 assert ceiling(-pi) == -3 assert ceiling(S.Half) == 1 assert ceiling(Rational(-1, 2)) == 0 assert ceiling(Rational(7, 3)) == 3 assert ceiling(-Rational(7, 3)) == -2 assert ceiling(Float(17.0)) == 17 assert ceiling(-Float(17.0)) == -17 assert ceiling(Float(7.69)) == 8 assert ceiling(-Float(7.69)) == -7 assert ceiling(I) == I assert ceiling(-I) == -I e = ceiling(i) assert e.func is ceiling and e.args[0] == i assert ceiling(oo*I) == oo*I assert ceiling(-oo*I) == -oo*I assert ceiling(exp(I*pi/4)*oo) == exp(I*pi/4)*oo assert ceiling(2*I) == 2*I assert ceiling(-2*I) == -2*I assert ceiling(I/2) == I assert ceiling(-I/2) == 0 assert ceiling(E + 17) == 20 assert ceiling(pi + 2) == 6 assert ceiling(E + pi) == 6 assert ceiling(I + pi) == I + 4 assert ceiling(ceiling(pi)) == 4 assert ceiling(ceiling(y)) == ceiling(y) assert ceiling(ceiling(x)) == ceiling(x) assert unchanged(ceiling, x) assert unchanged(ceiling, 2*x) assert unchanged(ceiling, k*x) assert ceiling(k) == k assert ceiling(2*k) == 2*k assert ceiling(k*n) == k*n assert unchanged(ceiling, k/2) assert unchanged(ceiling, x + y) assert ceiling(x + 3) == ceiling(x) + 3 assert ceiling(x + k) == ceiling(x) + k assert ceiling(y + 3) == ceiling(y) + 3 assert ceiling(y + k) == ceiling(y) + k assert ceiling(3 + pi + y*I) == 7 + ceiling(y)*I assert ceiling(k + n) == k + n assert unchanged(ceiling, x*I) assert ceiling(k*I) == k*I assert ceiling(Rational(23, 10) - E*I) == 3 - 2*I assert ceiling(sin(1)) == 1 assert ceiling(sin(-1)) == 0 assert ceiling(exp(2)) == 8 assert ceiling(-log(8)/log(2)) != -2 assert int(ceiling(-log(8)/log(2)).evalf(chop=True)) == -3 assert ceiling(factorial(50)/exp(1)) == \ 11188719610782480504630258070757734324011354208865721592720336801 assert (ceiling(y) >= y) == True assert (ceiling(y) > y) == False assert (ceiling(y) < y) == False assert (ceiling(y) <= y) == False assert (ceiling(x) >= x).is_Relational # x could be non-real assert (ceiling(x) < x).is_Relational assert (ceiling(x) >= y).is_Relational # arg is not same as rhs assert (ceiling(x) < y).is_Relational assert (ceiling(y) >= -oo) == True assert (ceiling(y) > -oo) == True assert (ceiling(y) <= oo) == True assert (ceiling(y) < oo) == True assert ceiling(y).rewrite(floor) == -floor(-y) assert ceiling(y).rewrite(frac) == y + frac(-y) assert ceiling(y).rewrite(floor).subs(y, -pi) == -floor(pi) assert ceiling(y).rewrite(floor).subs(y, E) == -floor(-E) assert ceiling(y).rewrite(frac).subs(y, pi) == ceiling(pi) assert ceiling(y).rewrite(frac).subs(y, -E) == ceiling(-E) assert Eq(ceiling(y), y + frac(-y)) assert Eq(ceiling(y), -floor(-y)) neg = Symbol('neg', negative=True) nn = Symbol('nn', nonnegative=True) pos = Symbol('pos', positive=True) np = Symbol('np', nonpositive=True) assert (ceiling(neg) <= 0) == True assert (ceiling(neg) < 0) == (neg <= -1) assert (ceiling(neg) > 0) == False assert (ceiling(neg) >= 0) == (neg > -1) assert (ceiling(neg) > -3) == (neg > -3) assert (ceiling(neg) <= 10) == (neg <= 10) assert (ceiling(nn) < 0) == False assert (ceiling(nn) >= 0) == True assert (ceiling(pos) < 0) == False assert (ceiling(pos) <= 0) == False assert (ceiling(pos) > 0) == True assert (ceiling(pos) >= 0) == True assert (ceiling(pos) >= 1) == True assert (ceiling(pos) > 5) == (pos > 5) assert (ceiling(np) <= 0) == True assert (ceiling(np) > 0) == False assert ceiling(neg).is_positive == False assert ceiling(neg).is_nonpositive == True assert ceiling(nn).is_positive is None assert ceiling(nn).is_nonpositive is None assert ceiling(pos).is_positive == True assert ceiling(pos).is_nonpositive == False assert ceiling(np).is_positive == False assert ceiling(np).is_nonpositive == True assert (ceiling(7, evaluate=False) >= 7) == True assert (ceiling(7, evaluate=False) > 7) == False assert (ceiling(7, evaluate=False) <= 7) == True assert (ceiling(7, evaluate=False) < 7) == False assert (ceiling(7, evaluate=False) >= 6) == True assert (ceiling(7, evaluate=False) > 6) == True assert (ceiling(7, evaluate=False) <= 6) == False assert (ceiling(7, evaluate=False) < 6) == False assert (ceiling(7, evaluate=False) >= 8) == False assert (ceiling(7, evaluate=False) > 8) == False assert (ceiling(7, evaluate=False) <= 8) == True assert (ceiling(7, evaluate=False) < 8) == True assert (ceiling(x) <= 5.5) == Le(ceiling(x), 5.5, evaluate=False) assert (ceiling(x) >= -3.2) == Ge(ceiling(x), -3.2, evaluate=False) assert (ceiling(x) < 2.9) == Lt(ceiling(x), 2.9, evaluate=False) assert (ceiling(x) > -1.7) == Gt(ceiling(x), -1.7, evaluate=False) assert (ceiling(y) <= 5.5) == (y <= 5) assert (ceiling(y) >= -3.2) == (y > -4) assert (ceiling(y) < 2.9) == (y <= 2) assert (ceiling(y) > -1.7) == (y > -2) assert (ceiling(y) <= n) == (y <= n) assert (ceiling(y) >= n) == (y > n - 1) assert (ceiling(y) < n) == (y <= n - 1) assert (ceiling(y) > n) == (y > n) def test_frac(): assert isinstance(frac(x), frac) assert frac(oo) == AccumBounds(0, 1) assert frac(-oo) == AccumBounds(0, 1) assert frac(zoo) is nan assert frac(n) == 0 assert frac(nan) is nan assert frac(Rational(4, 3)) == Rational(1, 3) assert frac(-Rational(4, 3)) == Rational(2, 3) assert frac(Rational(-4, 3)) == Rational(2, 3) r = Symbol('r', real=True) assert frac(I*r) == I*frac(r) assert frac(1 + I*r) == I*frac(r) assert frac(0.5 + I*r) == 0.5 + I*frac(r) assert frac(n + I*r) == I*frac(r) assert frac(n + I*k) == 0 assert unchanged(frac, x + I*x) assert frac(x + I*n) == frac(x) assert frac(x).rewrite(floor) == x - floor(x) assert frac(x).rewrite(ceiling) == x + ceiling(-x) assert frac(y).rewrite(floor).subs(y, pi) == frac(pi) assert frac(y).rewrite(floor).subs(y, -E) == frac(-E) assert frac(y).rewrite(ceiling).subs(y, -pi) == frac(-pi) assert frac(y).rewrite(ceiling).subs(y, E) == frac(E) assert Eq(frac(y), y - floor(y)) assert Eq(frac(y), y + ceiling(-y)) r = Symbol('r', real=True) p_i = Symbol('p_i', integer=True, positive=True) n_i = Symbol('p_i', integer=True, negative=True) np_i = Symbol('np_i', integer=True, nonpositive=True) nn_i = Symbol('nn_i', integer=True, nonnegative=True) p_r = Symbol('p_r', real=True, positive=True) n_r = Symbol('n_r', real=True, negative=True) np_r = Symbol('np_r', real=True, nonpositive=True) nn_r = Symbol('nn_r', real=True, nonnegative=True) # Real frac argument, integer rhs assert frac(r) <= p_i assert not frac(r) <= n_i assert (frac(r) <= np_i).has(Le) assert (frac(r) <= nn_i).has(Le) assert frac(r) < p_i assert not frac(r) < n_i assert not frac(r) < np_i assert (frac(r) < nn_i).has(Lt) assert not frac(r) >= p_i assert frac(r) >= n_i assert frac(r) >= np_i assert (frac(r) >= nn_i).has(Ge) assert not frac(r) > p_i assert frac(r) > n_i assert (frac(r) > np_i).has(Gt) assert (frac(r) > nn_i).has(Gt) assert not Eq(frac(r), p_i) assert not Eq(frac(r), n_i) assert Eq(frac(r), np_i).has(Eq) assert Eq(frac(r), nn_i).has(Eq) assert Ne(frac(r), p_i) assert Ne(frac(r), n_i) assert Ne(frac(r), np_i).has(Ne) assert Ne(frac(r), nn_i).has(Ne) # Real frac argument, real rhs assert (frac(r) <= p_r).has(Le) assert not frac(r) <= n_r assert (frac(r) <= np_r).has(Le) assert (frac(r) <= nn_r).has(Le) assert (frac(r) < p_r).has(Lt) assert not frac(r) < n_r assert not frac(r) < np_r assert (frac(r) < nn_r).has(Lt) assert (frac(r) >= p_r).has(Ge) assert frac(r) >= n_r assert frac(r) >= np_r assert (frac(r) >= nn_r).has(Ge) assert (frac(r) > p_r).has(Gt) assert frac(r) > n_r assert (frac(r) > np_r).has(Gt) assert (frac(r) > nn_r).has(Gt) assert not Eq(frac(r), n_r) assert Eq(frac(r), p_r).has(Eq) assert Eq(frac(r), np_r).has(Eq) assert Eq(frac(r), nn_r).has(Eq) assert Ne(frac(r), p_r).has(Ne) assert Ne(frac(r), n_r) assert Ne(frac(r), np_r).has(Ne) assert Ne(frac(r), nn_r).has(Ne) # Real frac argument, +/- oo rhs assert frac(r) < oo assert frac(r) <= oo assert not frac(r) > oo assert not frac(r) >= oo assert not frac(r) < -oo assert not frac(r) <= -oo assert frac(r) > -oo assert frac(r) >= -oo assert frac(r) < 1 assert frac(r) <= 1 assert not frac(r) > 1 assert not frac(r) >= 1 assert not frac(r) < 0 assert (frac(r) <= 0).has(Le) assert (frac(r) > 0).has(Gt) assert frac(r) >= 0 # Some test for numbers assert frac(r) <= sqrt(2) assert (frac(r) <= sqrt(3) - sqrt(2)).has(Le) assert not frac(r) <= sqrt(2) - sqrt(3) assert not frac(r) >= sqrt(2) assert (frac(r) >= sqrt(3) - sqrt(2)).has(Ge) assert frac(r) >= sqrt(2) - sqrt(3) assert not Eq(frac(r), sqrt(2)) assert Eq(frac(r), sqrt(3) - sqrt(2)).has(Eq) assert not Eq(frac(r), sqrt(2) - sqrt(3)) assert Ne(frac(r), sqrt(2)) assert Ne(frac(r), sqrt(3) - sqrt(2)).has(Ne) assert Ne(frac(r), sqrt(2) - sqrt(3)) assert frac(p_i, evaluate=False).is_zero assert frac(p_i, evaluate=False).is_finite assert frac(p_i, evaluate=False).is_integer assert frac(p_i, evaluate=False).is_real assert frac(r).is_finite assert frac(r).is_real assert frac(r).is_zero is None assert frac(r).is_integer is None assert frac(oo).is_finite assert frac(oo).is_real def test_series(): x, y = symbols('x,y') assert floor(x).nseries(x, y, 100) == floor(y) assert ceiling(x).nseries(x, y, 100) == ceiling(y) assert floor(x).nseries(x, pi, 100) == 3 assert ceiling(x).nseries(x, pi, 100) == 4 assert floor(x).nseries(x, 0, 100) == 0 assert ceiling(x).nseries(x, 0, 100) == 1 assert floor(-x).nseries(x, 0, 100) == -1 assert ceiling(-x).nseries(x, 0, 100) == 0 @XFAIL def test_issue_4149(): assert floor(3 + pi*I + y*I) == 3 + floor(pi + y)*I assert floor(3*I + pi*I + y*I) == floor(3 + pi + y)*I assert floor(3 + E + pi*I + y*I) == 5 + floor(pi + y)*I def test_issue_21651(): k = Symbol('k', positive=True, integer=True) exp = 2*2**(-k) assert isinstance(floor(exp), floor) def test_issue_11207(): assert floor(floor(x)) == floor(x) assert floor(ceiling(x)) == ceiling(x) assert ceiling(floor(x)) == floor(x) assert ceiling(ceiling(x)) == ceiling(x) def test_nested_floor_ceiling(): assert floor(-floor(ceiling(x**3)/y)) == -floor(ceiling(x**3)/y) assert ceiling(-floor(ceiling(x**3)/y)) == -floor(ceiling(x**3)/y) assert floor(ceiling(-floor(x**Rational(7, 2)/y))) == -floor(x**Rational(7, 2)/y) assert -ceiling(-ceiling(floor(x)/y)) == ceiling(floor(x)/y) def test_issue_18689(): assert floor(floor(floor(x)) + 3) == floor(x) + 3 assert ceiling(ceiling(ceiling(x)) + 1) == ceiling(x) + 1 assert ceiling(ceiling(floor(x)) + 3) == floor(x) + 3 def test_issue_18421(): assert floor(float(0)) is S.Zero assert ceiling(float(0)) is S.Zero
3d7813ba7e908a7a7b8a40cb4caaafe5448fdc6d31f9975f3c7e18be945d253f
from sympy.calculus.util 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) for func in [tan, cot]: for a in (1/x, S.Half): eq = func(a) assert eq.as_leading_term(x) == eq # 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
41ee78b42dc4180c33e3491d3e7f13c3b659903ecad513301925871a9e2f0a17
from sympy.core.expr import Expr from sympy.core.function import (Derivative, Function, Lambda, expand) from sympy.core.numbers import (E, I, Rational, comp, nan, oo, pi, zoo) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (Abs, adjoint, arg, conjugate, im, re, sign, transpose) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, atan, atan2, cos, sin) from sympy.functions.special.delta_functions import (DiracDelta, Heaviside) from sympy.integrals.integrals import Integral from sympy.matrices.dense import Matrix from sympy.matrices.expressions.funcmatrix import FunctionMatrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.immutable import (ImmutableMatrix, ImmutableSparseMatrix) from sympy.matrices import SparseMatrix from sympy.sets.sets import Interval from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import XFAIL, raises, _both_exp_pow def N_equals(a, b): """Check whether two complex numbers are numerically close""" return comp(a.n(), b.n(), 1.e-6) def test_re(): x, y = symbols('x,y') a, b = symbols('a,b', real=True) r = Symbol('r', real=True) i = Symbol('i', imaginary=True) assert re(nan) is nan assert re(oo) is oo assert re(-oo) is -oo assert re(0) == 0 assert re(1) == 1 assert re(-1) == -1 assert re(E) == E assert re(-E) == -E assert unchanged(re, x) assert re(x*I) == -im(x) assert re(r*I) == 0 assert re(r) == r assert re(i*I) == I * i assert re(i) == 0 assert re(x + y) == re(x) + re(y) assert re(x + r) == re(x) + r assert re(re(x)) == re(x) assert re(2 + I) == 2 assert re(x + I) == re(x) assert re(x + y*I) == re(x) - im(y) assert re(x + r*I) == re(x) assert re(log(2*I)) == log(2) assert re((2 + I)**2).expand(complex=True) == 3 assert re(conjugate(x)) == re(x) assert conjugate(re(x)) == re(x) assert re(x).as_real_imag() == (re(x), 0) assert re(i*r*x).diff(r) == re(i*x) assert re(i*r*x).diff(i) == I*r*im(x) assert re( sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2) assert re(a * (2 + b*I)) == 2*a assert re((1 + sqrt(a + b*I))/2) == \ (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)/2 + S.Half assert re(x).rewrite(im) == x - S.ImaginaryUnit*im(x) assert (x + re(y)).rewrite(re, im) == x + y - S.ImaginaryUnit*im(y) a = Symbol('a', algebraic=True) t = Symbol('t', transcendental=True) x = Symbol('x') assert re(a).is_algebraic assert re(x).is_algebraic is None assert re(t).is_algebraic is False assert re(S.ComplexInfinity) is S.NaN n, m, l = symbols('n m l') A = MatrixSymbol('A',n,m) assert re(A) == (S.Half) * (A + conjugate(A)) A = Matrix([[1 + 4*I,2],[0, -3*I]]) assert re(A) == Matrix([[1, 2],[0, 0]]) A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]]) assert re(A) == ImmutableMatrix([[1, 3],[0, 0]]) X = SparseMatrix([[2*j + i*I for i in range(5)] for j in range(5)]) assert re(X) - Matrix([[0, 0, 0, 0, 0], [2, 2, 2, 2, 2], [4, 4, 4, 4, 4], [6, 6, 6, 6, 6], [8, 8, 8, 8, 8]]) == Matrix.zeros(5) assert im(X) - Matrix([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]) == Matrix.zeros(5) X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I)) assert re(X) == Matrix([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) def test_im(): x, y = symbols('x,y') a, b = symbols('a,b', real=True) r = Symbol('r', real=True) i = Symbol('i', imaginary=True) assert im(nan) is nan assert im(oo*I) is oo assert im(-oo*I) is -oo assert im(0) == 0 assert im(1) == 0 assert im(-1) == 0 assert im(E*I) == E assert im(-E*I) == -E assert unchanged(im, x) assert im(x*I) == re(x) assert im(r*I) == r assert im(r) == 0 assert im(i*I) == 0 assert im(i) == -I * i assert im(x + y) == im(x) + im(y) assert im(x + r) == im(x) assert im(x + r*I) == im(x) + r assert im(im(x)*I) == im(x) assert im(2 + I) == 1 assert im(x + I) == im(x) + 1 assert im(x + y*I) == im(x) + re(y) assert im(x + r*I) == im(x) + r assert im(log(2*I)) == pi/2 assert im((2 + I)**2).expand(complex=True) == 4 assert im(conjugate(x)) == -im(x) assert conjugate(im(x)) == im(x) assert im(x).as_real_imag() == (im(x), 0) assert im(i*r*x).diff(r) == im(i*x) assert im(i*r*x).diff(i) == -I * re(r*x) assert im( sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2) assert im(a * (2 + b*I)) == a*b assert im((1 + sqrt(a + b*I))/2) == \ (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2 assert im(x).rewrite(re) == -S.ImaginaryUnit * (x - re(x)) assert (x + im(y)).rewrite(im, re) == x - S.ImaginaryUnit * (y - re(y)) a = Symbol('a', algebraic=True) t = Symbol('t', transcendental=True) x = Symbol('x') assert re(a).is_algebraic assert re(x).is_algebraic is None assert re(t).is_algebraic is False assert im(S.ComplexInfinity) is S.NaN n, m, l = symbols('n m l') A = MatrixSymbol('A',n,m) assert im(A) == (S.One/(2*I)) * (A - conjugate(A)) A = Matrix([[1 + 4*I, 2],[0, -3*I]]) assert im(A) == Matrix([[4, 0],[0, -3]]) A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]]) assert im(A) == ImmutableMatrix([[3, -2],[0, 2]]) X = ImmutableSparseMatrix( [[i*I + i for i in range(5)] for i in range(5)]) Y = SparseMatrix([[i for i in range(5)] for i in range(5)]) assert im(X).as_immutable() == Y X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I)) assert im(X) == Matrix([[0, 1, 2], [0, 1, 2], [0, 1, 2]]) def test_sign(): assert sign(1.2) == 1 assert sign(-1.2) == -1 assert sign(3*I) == I assert sign(-3*I) == -I assert sign(0) == 0 assert sign(0, evaluate=False).doit() == 0 assert sign(oo, evaluate=False).doit() == 1 assert sign(nan) is nan assert sign(2 + 2*I).doit() == sqrt(2)*(2 + 2*I)/4 assert sign(2 + 3*I).simplify() == sign(2 + 3*I) assert sign(2 + 2*I).simplify() == sign(1 + I) assert sign(im(sqrt(1 - sqrt(3)))) == 1 assert sign(sqrt(1 - sqrt(3))) == I x = Symbol('x') assert sign(x).is_finite is True assert sign(x).is_complex is True assert sign(x).is_imaginary is None assert sign(x).is_integer is None assert sign(x).is_real is None assert sign(x).is_zero is None assert sign(x).doit() == sign(x) assert sign(1.2*x) == sign(x) assert sign(2*x) == sign(x) assert sign(I*x) == I*sign(x) assert sign(-2*I*x) == -I*sign(x) assert sign(conjugate(x)) == conjugate(sign(x)) p = Symbol('p', positive=True) n = Symbol('n', negative=True) m = Symbol('m', negative=True) assert sign(2*p*x) == sign(x) assert sign(n*x) == -sign(x) assert sign(n*m*x) == sign(x) x = Symbol('x', imaginary=True) assert sign(x).is_imaginary is True assert sign(x).is_integer is False assert sign(x).is_real is False assert sign(x).is_zero is False assert sign(x).diff(x) == 2*DiracDelta(-I*x) assert sign(x).doit() == x / Abs(x) assert conjugate(sign(x)) == -sign(x) x = Symbol('x', real=True) assert sign(x).is_imaginary is False assert sign(x).is_integer is True assert sign(x).is_real is True assert sign(x).is_zero is None assert sign(x).diff(x) == 2*DiracDelta(x) assert sign(x).doit() == sign(x) assert conjugate(sign(x)) == sign(x) x = Symbol('x', nonzero=True) assert sign(x).is_imaginary is False assert sign(x).is_integer is True assert sign(x).is_real is True assert sign(x).is_zero is False assert sign(x).doit() == x / Abs(x) assert sign(Abs(x)) == 1 assert Abs(sign(x)) == 1 x = Symbol('x', positive=True) assert sign(x).is_imaginary is False assert sign(x).is_integer is True assert sign(x).is_real is True assert sign(x).is_zero is False assert sign(x).doit() == x / Abs(x) assert sign(Abs(x)) == 1 assert Abs(sign(x)) == 1 x = 0 assert sign(x).is_imaginary is False assert sign(x).is_integer is True assert sign(x).is_real is True assert sign(x).is_zero is True assert sign(x).doit() == 0 assert sign(Abs(x)) == 0 assert Abs(sign(x)) == 0 nz = Symbol('nz', nonzero=True, integer=True) assert sign(nz).is_imaginary is False assert sign(nz).is_integer is True assert sign(nz).is_real is True assert sign(nz).is_zero is False assert sign(nz)**2 == 1 assert (sign(nz)**3).args == (sign(nz), 3) assert sign(Symbol('x', nonnegative=True)).is_nonnegative assert sign(Symbol('x', nonnegative=True)).is_nonpositive is None assert sign(Symbol('x', nonpositive=True)).is_nonnegative is None assert sign(Symbol('x', nonpositive=True)).is_nonpositive assert sign(Symbol('x', real=True)).is_nonnegative is None assert sign(Symbol('x', real=True)).is_nonpositive is None assert sign(Symbol('x', real=True, zero=False)).is_nonpositive is None x, y = Symbol('x', real=True), Symbol('y') f = Function('f') assert sign(x).rewrite(Piecewise) == \ Piecewise((1, x > 0), (-1, x < 0), (0, True)) assert sign(y).rewrite(Piecewise) == sign(y) assert sign(x).rewrite(Heaviside) == 2*Heaviside(x, H0=S(1)/2) - 1 assert sign(y).rewrite(Heaviside) == sign(y) assert sign(y).rewrite(Abs) == Piecewise((0, Eq(y, 0)), (y/Abs(y), True)) assert sign(f(y)).rewrite(Abs) == Piecewise((0, Eq(f(y), 0)), (f(y)/Abs(f(y)), True)) # evaluate what can be evaluated assert sign(exp_polar(I*pi)*pi) is S.NegativeOne eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) # if there is a fast way to know when and when you cannot prove an # expression like this is zero then the equality to zero is ok assert sign(eq).func is sign or sign(eq) == 0 # but sometimes it's hard to do this so it's better not to load # abs down with tests that will be very slow q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6) p = expand(q**3)**Rational(1, 3) d = p - q assert sign(d).func is sign or sign(d) == 0 def test_as_real_imag(): n = pi**1000 # the special code for working out the real # and complex parts of a power with Integer exponent # should not run if there is no imaginary part, hence # this should not hang assert n.as_real_imag() == (n, 0) # issue 6261 x = Symbol('x') assert sqrt(x).as_real_imag() == \ ((re(x)**2 + im(x)**2)**Rational(1, 4)*cos(atan2(im(x), re(x))/2), (re(x)**2 + im(x)**2)**Rational(1, 4)*sin(atan2(im(x), re(x))/2)) # issue 3853 a, b = symbols('a,b', real=True) assert ((1 + sqrt(a + b*I))/2).as_real_imag() == \ ( (a**2 + b**2)**Rational( 1, 4)*cos(atan2(b, a)/2)/2 + S.Half, (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2) assert sqrt(a**2).as_real_imag() == (sqrt(a**2), 0) i = symbols('i', imaginary=True) assert sqrt(i**2).as_real_imag() == (0, abs(i)) assert ((1 + I)/(1 - I)).as_real_imag() == (0, 1) assert ((1 + I)**3/(1 - I)).as_real_imag() == (-2, 0) @XFAIL def test_sign_issue_3068(): n = pi**1000 i = int(n) x = Symbol('x') assert (n - i).round() == 1 # doesn't hang assert sign(n - i) == 1 # perhaps it's not possible to get the sign right when # only 1 digit is being requested for this situation; # 2 digits works assert (n - x).n(1, subs={x: i}) > 0 assert (n - x).n(2, subs={x: i}) > 0 def test_Abs(): raises(TypeError, lambda: Abs(Interval(2, 3))) # issue 8717 x, y = symbols('x,y') assert sign(sign(x)) == sign(x) assert sign(x*y).func is sign assert Abs(0) == 0 assert Abs(1) == 1 assert Abs(-1) == 1 assert Abs(I) == 1 assert Abs(-I) == 1 assert Abs(nan) is nan assert Abs(zoo) is oo assert Abs(I * pi) == pi assert Abs(-I * pi) == pi assert Abs(I * x) == Abs(x) assert Abs(-I * x) == Abs(x) assert Abs(-2*x) == 2*Abs(x) assert Abs(-2.0*x) == 2.0*Abs(x) assert Abs(2*pi*x*y) == 2*pi*Abs(x*y) assert Abs(conjugate(x)) == Abs(x) assert conjugate(Abs(x)) == Abs(x) assert Abs(x).expand(complex=True) == sqrt(re(x)**2 + im(x)**2) a = Symbol('a', positive=True) assert Abs(2*pi*x*a) == 2*pi*a*Abs(x) assert Abs(2*pi*I*x*a) == 2*pi*a*Abs(x) x = Symbol('x', real=True) n = Symbol('n', integer=True) assert Abs((-1)**n) == 1 assert x**(2*n) == Abs(x)**(2*n) assert Abs(x).diff(x) == sign(x) assert abs(x) == Abs(x) # Python built-in assert Abs(x)**3 == x**2*Abs(x) assert Abs(x)**4 == x**4 assert ( Abs(x)**(3*n)).args == (Abs(x), 3*n) # leave symbolic odd unchanged assert (1/Abs(x)).args == (Abs(x), -1) assert 1/Abs(x)**3 == 1/(x**2*Abs(x)) assert Abs(x)**-3 == Abs(x)/(x**4) assert Abs(x**3) == x**2*Abs(x) assert Abs(I**I) == exp(-pi/2) assert Abs((4 + 5*I)**(6 + 7*I)) == 68921*exp(-7*atan(Rational(5, 4))) y = Symbol('y', real=True) assert Abs(I**y) == 1 y = Symbol('y') assert Abs(I**y) == exp(-pi*im(y)/2) x = Symbol('x', imaginary=True) assert Abs(x).diff(x) == -sign(x) eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) # if there is a fast way to know when you can and when you cannot prove an # expression like this is zero then the equality to zero is ok assert abs(eq).func is Abs or abs(eq) == 0 # but sometimes it's hard to do this so it's better not to load # abs down with tests that will be very slow q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6) p = expand(q**3)**Rational(1, 3) d = p - q assert abs(d).func is Abs or abs(d) == 0 assert Abs(4*exp(pi*I/4)) == 4 assert Abs(3**(2 + I)) == 9 assert Abs((-3)**(1 - I)) == 3*exp(pi) assert Abs(oo) is oo assert Abs(-oo) is oo assert Abs(oo + I) is oo assert Abs(oo + I*oo) is oo a = Symbol('a', algebraic=True) t = Symbol('t', transcendental=True) x = Symbol('x') assert re(a).is_algebraic assert re(x).is_algebraic is None assert re(t).is_algebraic is False assert Abs(x).fdiff() == sign(x) raises(ArgumentIndexError, lambda: Abs(x).fdiff(2)) # doesn't have recursion error arg = sqrt(acos(1 - I)*acos(1 + I)) assert abs(arg) == arg # special handling to put Abs in denom assert abs(1/x) == 1/Abs(x) e = abs(2/x**2) assert e.is_Mul and e == 2/Abs(x**2) assert unchanged(Abs, y/x) assert unchanged(Abs, x/(x + 1)) assert unchanged(Abs, x*y) p = Symbol('p', positive=True) assert abs(x/p) == abs(x)/p # coverage assert unchanged(Abs, Symbol('x', real=True)**y) # issue 19627 f = Function('f', positive=True) assert sqrt(f(x)**2) == f(x) # issue 21625 assert unchanged(Abs, S("im(acos(-i + acosh(-g + i)))")) def test_Abs_rewrite(): x = Symbol('x', real=True) a = Abs(x).rewrite(Heaviside).expand() assert a == x*Heaviside(x) - x*Heaviside(-x) for i in [-2, -1, 0, 1, 2]: assert a.subs(x, i) == abs(i) y = Symbol('y') assert Abs(y).rewrite(Heaviside) == Abs(y) x, y = Symbol('x', real=True), Symbol('y') assert Abs(x).rewrite(Piecewise) == Piecewise((x, x >= 0), (-x, True)) assert Abs(y).rewrite(Piecewise) == Abs(y) assert Abs(y).rewrite(sign) == y/sign(y) i = Symbol('i', imaginary=True) assert abs(i).rewrite(Piecewise) == Piecewise((I*i, I*i >= 0), (-I*i, True)) assert Abs(y).rewrite(conjugate) == sqrt(y*conjugate(y)) assert Abs(i).rewrite(conjugate) == sqrt(-i**2) # == -I*i y = Symbol('y', extended_real=True) assert (Abs(exp(-I*x)-exp(-I*y))**2).rewrite(conjugate) == \ -exp(I*x)*exp(-I*y) + 2 - exp(-I*x)*exp(I*y) def test_Abs_real(): # test some properties of abs that only apply # to real numbers x = Symbol('x', complex=True) assert sqrt(x**2) != Abs(x) assert Abs(x**2) != x**2 x = Symbol('x', real=True) assert sqrt(x**2) == Abs(x) assert Abs(x**2) == x**2 # if the symbol is zero, the following will still apply nn = Symbol('nn', nonnegative=True, real=True) np = Symbol('np', nonpositive=True, real=True) assert Abs(nn) == nn assert Abs(np) == -np def test_Abs_properties(): x = Symbol('x') assert Abs(x).is_real is None assert Abs(x).is_extended_real is True assert Abs(x).is_rational is None assert Abs(x).is_positive is None assert Abs(x).is_nonnegative is None assert Abs(x).is_extended_positive is None assert Abs(x).is_extended_nonnegative is True f = Symbol('x', finite=True) assert Abs(f).is_real is True assert Abs(f).is_extended_real is True assert Abs(f).is_rational is None assert Abs(f).is_positive is None assert Abs(f).is_nonnegative is True assert Abs(f).is_extended_positive is None assert Abs(f).is_extended_nonnegative is True z = Symbol('z', complex=True, zero=False) assert Abs(z).is_real is True # since complex implies finite assert Abs(z).is_extended_real is True assert Abs(z).is_rational is None assert Abs(z).is_positive is True assert Abs(z).is_extended_positive is True assert Abs(z).is_zero is False p = Symbol('p', positive=True) assert Abs(p).is_real is True assert Abs(p).is_extended_real is True assert Abs(p).is_rational is None assert Abs(p).is_positive is True assert Abs(p).is_zero is False q = Symbol('q', rational=True) assert Abs(q).is_real is True assert Abs(q).is_rational is True assert Abs(q).is_integer is None assert Abs(q).is_positive is None assert Abs(q).is_nonnegative is True i = Symbol('i', integer=True) assert Abs(i).is_real is True assert Abs(i).is_integer is True assert Abs(i).is_positive is None assert Abs(i).is_nonnegative is True e = Symbol('n', even=True) ne = Symbol('ne', real=True, even=False) assert Abs(e).is_even is True assert Abs(ne).is_even is False assert Abs(i).is_even is None o = Symbol('n', odd=True) no = Symbol('no', real=True, odd=False) assert Abs(o).is_odd is True assert Abs(no).is_odd is False assert Abs(i).is_odd is None def test_abs(): # this tests that abs calls Abs; don't rename to # test_Abs since that test is already above a = Symbol('a', positive=True) assert abs(I*(1 + a)**2) == (1 + a)**2 def test_arg(): assert arg(0) is nan assert arg(1) == 0 assert arg(-1) == pi assert arg(I) == pi/2 assert arg(-I) == -pi/2 assert arg(1 + I) == pi/4 assert arg(-1 + I) == pi*Rational(3, 4) assert arg(1 - I) == -pi/4 assert arg(exp_polar(4*pi*I)) == 4*pi assert arg(exp_polar(-7*pi*I)) == -7*pi assert arg(exp_polar(5 - 3*pi*I/4)) == pi*Rational(-3, 4) f = Function('f') assert not arg(f(0) + I*f(1)).atoms(re) # check nesting x = Symbol('x') assert arg(arg(arg(x))) is not S.NaN assert arg(arg(arg(arg(x)))) is S.NaN r = Symbol('r', extended_real=True) assert arg(arg(r)) is not S.NaN assert arg(arg(arg(r))) is S.NaN p = Function('p', extended_positive=True) assert arg(p(x)) == 0 assert arg((3 + I)*p(x)) == arg(3 + I) p = Symbol('p', positive=True) assert arg(p) == 0 assert arg(p*I) == pi/2 n = Symbol('n', negative=True) assert arg(n) == pi assert arg(n*I) == -pi/2 x = Symbol('x') assert conjugate(arg(x)) == arg(x) e = p + I*p**2 assert arg(e) == arg(1 + p*I) # make sure sign doesn't swap e = -2*p + 4*I*p**2 assert arg(e) == arg(-1 + 2*p*I) # make sure sign isn't lost x = symbols('x', real=True) # could be zero e = x + I*x assert arg(e) == arg(x*(1 + I)) assert arg(e/p) == arg(x*(1 + I)) e = p*cos(p) + I*log(p)*exp(p) assert arg(e).args[0] == e # keep it simple -- let the user do more advanced cancellation e = (p + 1) + I*(p**2 - 1) assert arg(e).args[0] == e f = Function('f') e = 2*x*(f(0) - 1) - 2*x*f(0) assert arg(e) == arg(-2*x) assert arg(f(0)).func == arg and arg(f(0)).args == (f(0),) def test_arg_rewrite(): assert arg(1 + I) == atan2(1, 1) x = Symbol('x', real=True) y = Symbol('y', real=True) assert arg(x + I*y).rewrite(atan2) == atan2(y, x) def test_adjoint(): a = Symbol('a', antihermitian=True) b = Symbol('b', hermitian=True) assert adjoint(a) == -a assert adjoint(I*a) == I*a assert adjoint(b) == b assert adjoint(I*b) == -I*b assert adjoint(a*b) == -b*a assert adjoint(I*a*b) == I*b*a x, y = symbols('x y') assert adjoint(adjoint(x)) == x assert adjoint(x + y) == adjoint(x) + adjoint(y) assert adjoint(x - y) == adjoint(x) - adjoint(y) assert adjoint(x * y) == adjoint(x) * adjoint(y) assert adjoint(x / y) == adjoint(x) / adjoint(y) assert adjoint(-x) == -adjoint(x) x, y = symbols('x y', commutative=False) assert adjoint(adjoint(x)) == x assert adjoint(x + y) == adjoint(x) + adjoint(y) assert adjoint(x - y) == adjoint(x) - adjoint(y) assert adjoint(x * y) == adjoint(y) * adjoint(x) assert adjoint(x / y) == 1 / adjoint(y) * adjoint(x) assert adjoint(-x) == -adjoint(x) def test_conjugate(): a = Symbol('a', real=True) b = Symbol('b', imaginary=True) assert conjugate(a) == a assert conjugate(I*a) == -I*a assert conjugate(b) == -b assert conjugate(I*b) == I*b assert conjugate(a*b) == -a*b assert conjugate(I*a*b) == I*a*b x, y = symbols('x y') assert conjugate(conjugate(x)) == x assert conjugate(x).inverse() == conjugate assert conjugate(x + y) == conjugate(x) + conjugate(y) assert conjugate(x - y) == conjugate(x) - conjugate(y) assert conjugate(x * y) == conjugate(x) * conjugate(y) assert conjugate(x / y) == conjugate(x) / conjugate(y) assert conjugate(-x) == -conjugate(x) a = Symbol('a', algebraic=True) t = Symbol('t', transcendental=True) assert re(a).is_algebraic assert re(x).is_algebraic is None assert re(t).is_algebraic is False def test_conjugate_transpose(): x = Symbol('x') assert conjugate(transpose(x)) == adjoint(x) assert transpose(conjugate(x)) == adjoint(x) assert adjoint(transpose(x)) == conjugate(x) assert transpose(adjoint(x)) == conjugate(x) assert adjoint(conjugate(x)) == transpose(x) assert conjugate(adjoint(x)) == transpose(x) class Symmetric(Expr): def _eval_adjoint(self): return None def _eval_conjugate(self): return None def _eval_transpose(self): return self x = Symmetric() assert conjugate(x) == adjoint(x) assert transpose(x) == x def test_transpose(): a = Symbol('a', complex=True) assert transpose(a) == a assert transpose(I*a) == I*a x, y = symbols('x y') assert transpose(transpose(x)) == x assert transpose(x + y) == transpose(x) + transpose(y) assert transpose(x - y) == transpose(x) - transpose(y) assert transpose(x * y) == transpose(x) * transpose(y) assert transpose(x / y) == transpose(x) / transpose(y) assert transpose(-x) == -transpose(x) x, y = symbols('x y', commutative=False) assert transpose(transpose(x)) == x assert transpose(x + y) == transpose(x) + transpose(y) assert transpose(x - y) == transpose(x) - transpose(y) assert transpose(x * y) == transpose(y) * transpose(x) assert transpose(x / y) == 1 / transpose(y) * transpose(x) assert transpose(-x) == -transpose(x) @_both_exp_pow def test_polarify(): from sympy.functions.elementary.complexes import (polar_lift, polarify) x = Symbol('x') z = Symbol('z', polar=True) f = Function('f') ES = {} assert polarify(-1) == (polar_lift(-1), ES) assert polarify(1 + I) == (polar_lift(1 + I), ES) assert polarify(exp(x), subs=False) == exp(x) assert polarify(1 + x, subs=False) == 1 + x assert polarify(f(I) + x, subs=False) == f(polar_lift(I)) + x assert polarify(x, lift=True) == polar_lift(x) assert polarify(z, lift=True) == z assert polarify(f(x), lift=True) == f(polar_lift(x)) assert polarify(1 + x, lift=True) == polar_lift(1 + x) assert polarify(1 + f(x), lift=True) == polar_lift(1 + f(polar_lift(x))) newex, subs = polarify(f(x) + z) assert newex.subs(subs) == f(x) + z mu = Symbol("mu") sigma = Symbol("sigma", positive=True) # Make sure polarify(lift=True) doesn't try to lift the integration # variable assert polarify( Integral(sqrt(2)*x*exp(-(-mu + x)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (x, -oo, oo)), lift=True) == Integral(sqrt(2)*(sigma*exp_polar(0))**exp_polar(I*pi)* exp((sigma*exp_polar(0))**(2*exp_polar(I*pi))*exp_polar(I*pi)*polar_lift(-mu + x)** (2*exp_polar(0))/2)*exp_polar(0)*polar_lift(x)/(2*sqrt(pi)), (x, -oo, oo)) def test_unpolarify(): from sympy.functions.elementary.complexes import (polar_lift, principal_branch, unpolarify) from sympy.core.relational import Ne from sympy.functions.elementary.hyperbolic import tanh from sympy.functions.special.error_functions import erf from sympy.functions.special.gamma_functions import (gamma, uppergamma) from sympy.abc import x p = exp_polar(7*I) + 1 u = exp(7*I) + 1 assert unpolarify(1) == 1 assert unpolarify(p) == u assert unpolarify(p**2) == u**2 assert unpolarify(p**x) == p**x assert unpolarify(p*x) == u*x assert unpolarify(p + x) == u + x assert unpolarify(sqrt(sin(p))) == sqrt(sin(u)) # Test reduction to principal branch 2*pi. t = principal_branch(x, 2*pi) assert unpolarify(t) == x assert unpolarify(sqrt(t)) == sqrt(t) # Test exponents_only. assert unpolarify(p**p, exponents_only=True) == p**u assert unpolarify(uppergamma(x, p**p)) == uppergamma(x, p**u) # Test functions. assert unpolarify(sin(p)) == sin(u) assert unpolarify(tanh(p)) == tanh(u) assert unpolarify(gamma(p)) == gamma(u) assert unpolarify(erf(p)) == erf(u) assert unpolarify(uppergamma(x, p)) == uppergamma(x, p) assert unpolarify(uppergamma(sin(p), sin(p + exp_polar(0)))) == \ uppergamma(sin(u), sin(u + 1)) assert unpolarify(uppergamma(polar_lift(0), 2*exp_polar(0))) == \ uppergamma(0, 2) assert unpolarify(Eq(p, 0)) == Eq(u, 0) assert unpolarify(Ne(p, 0)) == Ne(u, 0) assert unpolarify(polar_lift(x) > 0) == (x > 0) # Test bools assert unpolarify(True) is True def test_issue_4035(): x = Symbol('x') assert Abs(x).expand(trig=True) == Abs(x) assert sign(x).expand(trig=True) == sign(x) assert arg(x).expand(trig=True) == arg(x) def test_issue_3206(): x = Symbol('x') assert Abs(Abs(x)) == Abs(x) def test_issue_4754_derivative_conjugate(): x = Symbol('x', real=True) y = Symbol('y', imaginary=True) f = Function('f') assert (f(x).conjugate()).diff(x) == (f(x).diff(x)).conjugate() assert (f(y).conjugate()).diff(y) == -(f(y).diff(y)).conjugate() def test_derivatives_issue_4757(): x = Symbol('x', real=True) y = Symbol('y', imaginary=True) f = Function('f') assert re(f(x)).diff(x) == re(f(x).diff(x)) assert im(f(x)).diff(x) == im(f(x).diff(x)) assert re(f(y)).diff(y) == -I*im(f(y).diff(y)) assert im(f(y)).diff(y) == -I*re(f(y).diff(y)) assert Abs(f(x)).diff(x).subs(f(x), 1 + I*x).doit() == x/sqrt(1 + x**2) assert arg(f(x)).diff(x).subs(f(x), 1 + I*x**2).doit() == 2*x/(1 + x**4) assert Abs(f(y)).diff(y).subs(f(y), 1 + y).doit() == -y/sqrt(1 - y**2) assert arg(f(y)).diff(y).subs(f(y), I + y**2).doit() == 2*y/(1 + y**4) def test_issue_11413(): from sympy.simplify.simplify import simplify v0 = Symbol('v0') v1 = Symbol('v1') v2 = Symbol('v2') V = Matrix([[v0],[v1],[v2]]) U = V.normalized() assert U == Matrix([ [v0/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)], [v1/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)], [v2/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)]]) U.norm = sqrt(v0**2/(v0**2 + v1**2 + v2**2) + v1**2/(v0**2 + v1**2 + v2**2) + v2**2/(v0**2 + v1**2 + v2**2)) assert simplify(U.norm) == 1 def test_periodic_argument(): from sympy.functions.elementary.complexes import (periodic_argument, polar_lift, principal_branch, unbranched_argument) x = Symbol('x') p = Symbol('p', positive=True) assert unbranched_argument(2 + I) == periodic_argument(2 + I, oo) assert unbranched_argument(1 + x) == periodic_argument(1 + x, oo) assert N_equals(unbranched_argument((1 + I)**2), pi/2) assert N_equals(unbranched_argument((1 - I)**2), -pi/2) assert N_equals(periodic_argument((1 + I)**2, 3*pi), pi/2) assert N_equals(periodic_argument((1 - I)**2, 3*pi), -pi/2) assert unbranched_argument(principal_branch(x, pi)) == \ periodic_argument(x, pi) assert unbranched_argument(polar_lift(2 + I)) == unbranched_argument(2 + I) assert periodic_argument(polar_lift(2 + I), 2*pi) == \ periodic_argument(2 + I, 2*pi) assert periodic_argument(polar_lift(2 + I), 3*pi) == \ periodic_argument(2 + I, 3*pi) assert periodic_argument(polar_lift(2 + I), pi) == \ periodic_argument(polar_lift(2 + I), pi) assert unbranched_argument(polar_lift(1 + I)) == pi/4 assert periodic_argument(2*p, p) == periodic_argument(p, p) assert periodic_argument(pi*p, p) == periodic_argument(p, p) assert Abs(polar_lift(1 + I)) == Abs(1 + I) @XFAIL def test_principal_branch_fail(): # TODO XXX why does abs(x)._eval_evalf() not fall back to global evalf? from sympy.functions.elementary.complexes import principal_branch assert N_equals(principal_branch((1 + I)**2, pi/2), 0) def test_principal_branch(): from sympy.functions.elementary.complexes import (polar_lift, principal_branch) p = Symbol('p', positive=True) x = Symbol('x') neg = Symbol('x', negative=True) assert principal_branch(polar_lift(x), p) == principal_branch(x, p) assert principal_branch(polar_lift(2 + I), p) == principal_branch(2 + I, p) assert principal_branch(2*x, p) == 2*principal_branch(x, p) assert principal_branch(1, pi) == exp_polar(0) assert principal_branch(-1, 2*pi) == exp_polar(I*pi) assert principal_branch(-1, pi) == exp_polar(0) assert principal_branch(exp_polar(3*pi*I)*x, 2*pi) == \ principal_branch(exp_polar(I*pi)*x, 2*pi) assert principal_branch(neg*exp_polar(pi*I), 2*pi) == neg*exp_polar(-I*pi) # related to issue #14692 assert principal_branch(exp_polar(-I*pi/2)/polar_lift(neg), 2*pi) == \ exp_polar(-I*pi/2)/neg assert N_equals(principal_branch((1 + I)**2, 2*pi), 2*I) assert N_equals(principal_branch((1 + I)**2, 3*pi), 2*I) assert N_equals(principal_branch((1 + I)**2, 1*pi), 2*I) # test argument sanitization assert principal_branch(x, I).func is principal_branch assert principal_branch(x, -4).func is principal_branch assert principal_branch(x, -oo).func is principal_branch assert principal_branch(x, zoo).func is principal_branch @XFAIL def test_issue_6167_6151(): n = pi**1000 i = int(n) assert sign(n - i) == 1 assert abs(n - i) == n - i x = Symbol('x') eps = pi**-1500 big = pi**1000 one = cos(x)**2 + sin(x)**2 e = big*one - big + eps from sympy.simplify.simplify import simplify assert sign(simplify(e)) == 1 for xi in (111, 11, 1, Rational(1, 10)): assert sign(e.subs(x, xi)) == 1 def test_issue_14216(): from sympy.functions.elementary.complexes import unpolarify A = MatrixSymbol("A", 2, 2) assert unpolarify(A[0, 0]) == A[0, 0] assert unpolarify(A[0, 0]*A[1, 0]) == A[0, 0]*A[1, 0] def test_issue_14238(): # doesn't cause recursion error r = Symbol('r', real=True) assert Abs(r + Piecewise((0, r > 0), (1 - r, True))) def test_issue_22189(): x = Symbol('x') for a in (sqrt(7 - 2*x) - 2, 1 - x): assert Abs(a) - Abs(-a) == 0, a def test_zero_assumptions(): nr = Symbol('nonreal', real=False, finite=True) ni = Symbol('nonimaginary', imaginary=False) # imaginary implies not zero nzni = Symbol('nonzerononimaginary', zero=False, imaginary=False) assert re(nr).is_zero is None assert im(nr).is_zero is False assert re(ni).is_zero is None assert im(ni).is_zero is None assert re(nzni).is_zero is False assert im(nzni).is_zero is None @_both_exp_pow def test_issue_15893(): f = Function('f', real=True) x = Symbol('x', real=True) eq = Derivative(Abs(f(x)), f(x)) assert eq.doit() == sign(f(x))
a7ee40628aac318b165fe35258f32ae17b18c49967176876a45bff3c1582d5d5
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.function import (Function, diff, expand) from sympy.core.mul import Mul from sympy.core.numbers import (Float, I, Rational, oo, pi, zoo) from sympy.core.relational import (Eq, Ge, Gt, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (Abs, adjoint, arg, conjugate, im, re, transpose) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt) from sympy.functions.elementary.piecewise import (Piecewise, piecewise_fold) from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.delta_functions import (DiracDelta, Heaviside) from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.integrals.integrals import (Integral, integrate) from sympy.logic.boolalg import (And, ITE, Not, Or) from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.sets.contains import Contains from sympy.sets.sets import Interval from sympy.solvers.solvers import solve from sympy.utilities.lambdify import lambdify from sympy.core.expr import unchanged from sympy.functions.elementary.piecewise import Undefined, ExprCondPair from sympy.printing import srepr from sympy.testing.pytest import raises, slow from sympy.simplify import simplify a, b, c, d, x, y = symbols('a:d, x, y') z = symbols('z', nonzero=True) def test_piecewise1(): # Test canonicalization assert unchanged(Piecewise, ExprCondPair(x, x < 1), ExprCondPair(0, True)) assert Piecewise((x, x < 1), (0, True)) == Piecewise(ExprCondPair(x, x < 1), ExprCondPair(0, True)) assert Piecewise((x, x < 1), (0, True), (1, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (0, False), (-1, 1 > 2)) == \ Piecewise((x, x < 1)) assert Piecewise((x, x < 1), (0, x < 1), (0, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (0, x < 2), (0, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (x, x < 2), (0, True)) == \ Piecewise((x, Or(x < 1, x < 2)), (0, True)) assert Piecewise((x, x < 1), (x, x < 2), (x, True)) == x assert Piecewise((x, True)) == x # Explicitly constructed empty Piecewise not accepted raises(TypeError, lambda: Piecewise()) # False condition is never retained assert Piecewise((2*x, x < 0), (x, False)) == \ Piecewise((2*x, x < 0), (x, False), evaluate=False) == \ Piecewise((2*x, x < 0)) assert Piecewise((x, False)) == Undefined raises(TypeError, lambda: Piecewise(x)) assert Piecewise((x, 1)) == x # 1 and 0 are accepted as True/False raises(TypeError, lambda: Piecewise((x, 2))) raises(TypeError, lambda: Piecewise((x, x**2))) raises(TypeError, lambda: Piecewise(([1], True))) assert Piecewise(((1, 2), True)) == Tuple(1, 2) cond = (Piecewise((1, x < 0), (2, True)) < y) assert Piecewise((1, cond) ) == Piecewise((1, ITE(x < 0, y > 1, y > 2))) assert Piecewise((1, x > 0), (2, And(x <= 0, x > -1)) ) == Piecewise((1, x > 0), (2, x > -1)) assert Piecewise((1, x <= 0), (2, (x < 0) & (x > -1)) ) == Piecewise((1, x <= 0)) # test for supporting Contains in Piecewise pwise = Piecewise( (1, And(x <= 6, x > 1, Contains(x, S.Integers))), (0, True)) assert pwise.subs(x, pi) == 0 assert pwise.subs(x, 2) == 1 assert pwise.subs(x, 7) == 0 # Test subs p = Piecewise((-1, x < -1), (x**2, x < 0), (log(x), x >= 0)) p_x2 = Piecewise((-1, x**2 < -1), (x**4, x**2 < 0), (log(x**2), x**2 >= 0)) assert p.subs(x, x**2) == p_x2 assert p.subs(x, -5) == -1 assert p.subs(x, -1) == 1 assert p.subs(x, 1) == log(1) # More subs tests p2 = Piecewise((1, x < pi), (-1, x < 2*pi), (0, x > 2*pi)) p3 = Piecewise((1, Eq(x, 0)), (1/x, True)) p4 = Piecewise((1, Eq(x, 0)), (2, 1/x>2)) assert p2.subs(x, 2) == 1 assert p2.subs(x, 4) == -1 assert p2.subs(x, 10) == 0 assert p3.subs(x, 0.0) == 1 assert p4.subs(x, 0.0) == 1 f, g, h = symbols('f,g,h', cls=Function) pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1)) pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1)) assert pg.subs(g, f) == pf assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 0) == 1 assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 1) == 0 assert Piecewise((1, Eq(x, y)), (0, True)).subs(x, y) == 1 assert Piecewise((1, Eq(x, z)), (0, True)).subs(x, z) == 1 assert Piecewise((1, Eq(exp(x), cos(z))), (0, True)).subs(x, z) == \ Piecewise((1, Eq(exp(z), cos(z))), (0, True)) p5 = Piecewise( (0, Eq(cos(x) + y, 0)), (1, True)) assert p5.subs(y, 0) == Piecewise( (0, Eq(cos(x), 0)), (1, True)) assert Piecewise((-1, y < 1), (0, x < 0), (1, Eq(x, 0)), (2, True) ).subs(x, 1) == Piecewise((-1, y < 1), (2, True)) assert Piecewise((1, Eq(x**2, -1)), (2, x < 0)).subs(x, I) == 1 p6 = Piecewise((x, x > 0)) n = symbols('n', negative=True) assert p6.subs(x, n) == Undefined # Test evalf assert p.evalf() == p assert p.evalf(subs={x: -2}) == -1 assert p.evalf(subs={x: -1}) == 1 assert p.evalf(subs={x: 1}) == log(1) assert p6.evalf(subs={x: -5}) == Undefined # Test doit f_int = Piecewise((Integral(x, (x, 0, 1)), x < 1)) assert f_int.doit() == Piecewise( (S.Half, x < 1) ) # Test differentiation f = x fp = x*p dp = Piecewise((0, x < -1), (2*x, x < 0), (1/x, x >= 0)) fp_dx = x*dp + p assert diff(p, x) == dp assert diff(f*p, x) == fp_dx # Test simple arithmetic assert x*p == fp assert x*p + p == p + x*p assert p + f == f + p assert p + dp == dp + p assert p - dp == -(dp - p) # Test power dp2 = Piecewise((0, x < -1), (4*x**2, x < 0), (1/x**2, x >= 0)) assert dp**2 == dp2 # Test _eval_interval f1 = x*y + 2 f2 = x*y**2 + 3 peval = Piecewise((f1, x < 0), (f2, x > 0)) peval_interval = f1.subs( x, 0) - f1.subs(x, -1) + f2.subs(x, 1) - f2.subs(x, 0) assert peval._eval_interval(x, 0, 0) == 0 assert peval._eval_interval(x, -1, 1) == peval_interval peval2 = Piecewise((f1, x < 0), (f2, True)) assert peval2._eval_interval(x, 0, 0) == 0 assert peval2._eval_interval(x, 1, -1) == -peval_interval assert peval2._eval_interval(x, -1, -2) == f1.subs(x, -2) - f1.subs(x, -1) assert peval2._eval_interval(x, -1, 1) == peval_interval assert peval2._eval_interval(x, None, 0) == peval2.subs(x, 0) assert peval2._eval_interval(x, -1, None) == -peval2.subs(x, -1) # Test integration assert p.integrate() == Piecewise( (-x, x < -1), (x**3/3 + Rational(4, 3), x < 0), (x*log(x) - x + Rational(4, 3), True)) p = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x)) assert integrate(p, (x, -2, 2)) == Rational(5, 6) assert integrate(p, (x, 2, -2)) == Rational(-5, 6) p = Piecewise((0, x < 0), (1, x < 1), (0, x < 2), (1, x < 3), (0, True)) assert integrate(p, (x, -oo, oo)) == 2 p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x)) assert integrate(p, (x, -2, 2)) == Undefined # Test commutativity assert isinstance(p, Piecewise) and p.is_commutative is True def test_piecewise_free_symbols(): f = Piecewise((x, a < 0), (y, True)) assert f.free_symbols == {x, y, a} def test_piecewise_integrate1(): x, y = symbols('x y', real=True, finite=True) f = Piecewise(((x - 2)**2, x >= 0), (1, True)) assert integrate(f, (x, -2, 2)) == Rational(14, 3) g = Piecewise(((x - 5)**5, x >= 4), (f, True)) assert integrate(g, (x, -2, 2)) == Rational(14, 3) assert integrate(g, (x, -2, 5)) == Rational(43, 6) assert g == Piecewise(((x - 5)**5, x >= 4), (f, x < 4)) g = Piecewise(((x - 5)**5, 2 <= x), (f, x < 2)) assert integrate(g, (x, -2, 2)) == Rational(14, 3) assert integrate(g, (x, -2, 5)) == Rational(-701, 6) assert g == Piecewise(((x - 5)**5, 2 <= x), (f, True)) g = Piecewise(((x - 5)**5, 2 <= x), (2*f, True)) assert integrate(g, (x, -2, 2)) == Rational(28, 3) assert integrate(g, (x, -2, 5)) == Rational(-673, 6) def test_piecewise_integrate1b(): g = Piecewise((1, x > 0), (0, Eq(x, 0)), (-1, x < 0)) assert integrate(g, (x, -1, 1)) == 0 g = Piecewise((1, x - y < 0), (0, True)) assert integrate(g, (y, -oo, 0)) == -Min(0, x) assert g.subs(x, -3).integrate((y, -oo, 0)) == 3 assert integrate(g, (y, 0, -oo)) == Min(0, x) assert integrate(g, (y, 0, oo)) == -Max(0, x) + oo assert integrate(g, (y, -oo, 42)) == -Min(42, x) + 42 assert integrate(g, (y, -oo, oo)) == -x + oo g = Piecewise((0, x < 0), (x, x <= 1), (1, True)) gy1 = g.integrate((x, y, 1)) g1y = g.integrate((x, 1, y)) for yy in (-1, S.Half, 2): assert g.integrate((x, yy, 1)) == gy1.subs(y, yy) assert g.integrate((x, 1, yy)) == g1y.subs(y, yy) assert gy1 == Piecewise( (-Min(1, Max(0, y))**2/2 + S.Half, y < 1), (-y + 1, True)) assert g1y == Piecewise( (Min(1, Max(0, y))**2/2 - S.Half, y < 1), (y - 1, True)) @slow def test_piecewise_integrate1ca(): y = symbols('y', real=True) g = Piecewise( (1 - x, Interval(0, 1).contains(x)), (1 + x, Interval(-1, 0).contains(x)), (0, True) ) gy1 = g.integrate((x, y, 1)) g1y = g.integrate((x, 1, y)) assert g.integrate((x, -2, 1)) == gy1.subs(y, -2) assert g.integrate((x, 1, -2)) == g1y.subs(y, -2) assert g.integrate((x, 0, 1)) == gy1.subs(y, 0) assert g.integrate((x, 1, 0)) == g1y.subs(y, 0) assert g.integrate((x, 2, 1)) == gy1.subs(y, 2) assert g.integrate((x, 1, 2)) == g1y.subs(y, 2) assert piecewise_fold(gy1.rewrite(Piecewise) ).simplify() == Piecewise( (1, y <= -1), (-y**2/2 - y + S.Half, y <= 0), (y**2/2 - y + S.Half, y < 1), (0, True)) assert piecewise_fold(g1y.rewrite(Piecewise) ).simplify() == Piecewise( (-1, y <= -1), (y**2/2 + y - S.Half, y <= 0), (-y**2/2 + y - S.Half, y < 1), (0, True)) assert gy1 == Piecewise( ( -Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) + Min(1, Max(0, y))**2 + S.Half, y < 1), (0, True) ) assert g1y == Piecewise( ( Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) - Min(1, Max(0, y))**2 - S.Half, y < 1), (0, True)) @slow def test_piecewise_integrate1cb(): y = symbols('y', real=True) g = Piecewise( (0, Or(x <= -1, x >= 1)), (1 - x, x > 0), (1 + x, True) ) gy1 = g.integrate((x, y, 1)) g1y = g.integrate((x, 1, y)) assert g.integrate((x, -2, 1)) == gy1.subs(y, -2) assert g.integrate((x, 1, -2)) == g1y.subs(y, -2) assert g.integrate((x, 0, 1)) == gy1.subs(y, 0) assert g.integrate((x, 1, 0)) == g1y.subs(y, 0) assert g.integrate((x, 2, 1)) == gy1.subs(y, 2) assert g.integrate((x, 1, 2)) == g1y.subs(y, 2) assert piecewise_fold(gy1.rewrite(Piecewise) ).simplify() == Piecewise( (1, y <= -1), (-y**2/2 - y + S.Half, y <= 0), (y**2/2 - y + S.Half, y < 1), (0, True)) assert piecewise_fold(g1y.rewrite(Piecewise) ).simplify() == Piecewise( (-1, y <= -1), (y**2/2 + y - S.Half, y <= 0), (-y**2/2 + y - S.Half, y < 1), (0, True)) # g1y and gy1 should simplify if the condition that y < 1 # is applied, e.g. Min(1, Max(-1, y)) --> Max(-1, y) assert gy1 == Piecewise( ( -Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) + Min(1, Max(0, y))**2 + S.Half, y < 1), (0, True) ) assert g1y == Piecewise( ( Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) - Min(1, Max(0, y))**2 - S.Half, y < 1), (0, True)) def test_piecewise_integrate2(): from itertools import permutations lim = Tuple(x, c, d) p = Piecewise((1, x < a), (2, x > b), (3, True)) q = p.integrate(lim) assert q == Piecewise( (-c + 2*d - 2*Min(d, Max(a, c)) + Min(d, Max(a, b, c)), c < d), (-2*c + d + 2*Min(c, Max(a, d)) - Min(c, Max(a, b, d)), True)) for v in permutations((1, 2, 3, 4)): r = dict(zip((a, b, c, d), v)) assert p.subs(r).integrate(lim.subs(r)) == q.subs(r) def test_meijer_bypass(): # totally bypass meijerg machinery when dealing # with Piecewise in integrate assert Piecewise((1, x < 4), (0, True)).integrate((x, oo, 1)) == -3 def test_piecewise_integrate3_inequality_conditions(): from sympy.utilities.iterables import cartes lim = (x, 0, 5) # set below includes two pts below range, 2 pts in range, # 2 pts above range, and the boundaries N = (-2, -1, 0, 1, 2, 5, 6, 7) p = Piecewise((1, x > a), (2, x > b), (0, True)) ans = p.integrate(lim) for i, j in cartes(N, repeat=2): reps = dict(zip((a, b), (i, j))) assert ans.subs(reps) == p.subs(reps).integrate(lim) assert ans.subs(a, 4).subs(b, 1) == 0 + 2*3 + 1 p = Piecewise((1, x > a), (2, x < b), (0, True)) ans = p.integrate(lim) for i, j in cartes(N, repeat=2): reps = dict(zip((a, b), (i, j))) assert ans.subs(reps) == p.subs(reps).integrate(lim) # delete old tests that involved c1 and c2 since those # reduce to the above except that a value of 0 was used # for two expressions whereas the above uses 3 different # values @slow def test_piecewise_integrate4_symbolic_conditions(): a = Symbol('a', real=True, finite=True) b = Symbol('b', real=True, finite=True) x = Symbol('x', real=True, finite=True) y = Symbol('y', real=True, finite=True) p0 = Piecewise((0, Or(x < a, x > b)), (1, True)) p1 = Piecewise((0, x < a), (0, x > b), (1, True)) p2 = Piecewise((0, x > b), (0, x < a), (1, True)) p3 = Piecewise((0, x < a), (1, x < b), (0, True)) p4 = Piecewise((0, x > b), (1, x > a), (0, True)) p5 = Piecewise((1, And(a < x, x < b)), (0, True)) # check values of a=1, b=3 (and reversed) with values # of y of 0, 1, 2, 3, 4 lim = Tuple(x, -oo, y) for p in (p0, p1, p2, p3, p4, p5): ans = p.integrate(lim) for i in range(5): reps = {a:1, b:3, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) reps = {a: 3, b:1, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) lim = Tuple(x, y, oo) for p in (p0, p1, p2, p3, p4, p5): ans = p.integrate(lim) for i in range(5): reps = {a:1, b:3, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) reps = {a:3, b:1, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) ans = Piecewise( (0, x <= Min(a, b)), (x - Min(a, b), x <= b), (b - Min(a, b), True)) for i in (p0, p1, p2, p4): assert i.integrate(x) == ans assert p3.integrate(x) == Piecewise( (0, x < a), (-a + x, x <= Max(a, b)), (-a + Max(a, b), True)) assert p5.integrate(x) == Piecewise( (0, x <= a), (-a + x, x <= Max(a, b)), (-a + Max(a, b), True)) p1 = Piecewise((0, x < a), (0.5, x > b), (1, True)) p2 = Piecewise((0.5, x > b), (0, x < a), (1, True)) p3 = Piecewise((0, x < a), (1, x < b), (0.5, True)) p4 = Piecewise((0.5, x > b), (1, x > a), (0, True)) p5 = Piecewise((1, And(a < x, x < b)), (0.5, x > b), (0, True)) # check values of a=1, b=3 (and reversed) with values # of y of 0, 1, 2, 3, 4 lim = Tuple(x, -oo, y) for p in (p1, p2, p3, p4, p5): ans = p.integrate(lim) for i in range(5): reps = {a:1, b:3, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) reps = {a: 3, b:1, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) def test_piecewise_integrate5_independent_conditions(): p = Piecewise((0, Eq(y, 0)), (x*y, True)) assert integrate(p, (x, 1, 3)) == Piecewise((0, Eq(y, 0)), (4*y, True)) def test_piecewise_simplify(): p = Piecewise(((x**2 + 1)/x**2, Eq(x*(1 + x) - x**2, 0)), ((-1)**x*(-1), True)) assert p.simplify() == \ Piecewise((zoo, Eq(x, 0)), ((-1)**(x + 1), True)) # simplify when there are Eq in conditions assert Piecewise( (a, And(Eq(a, 0), Eq(a + b, 0))), (1, True)).simplify( ) == Piecewise( (0, And(Eq(a, 0), Eq(b, 0))), (1, True)) assert Piecewise((2*x*factorial(a)/(factorial(y)*factorial(-y + a)), Eq(y, 0) & Eq(-y + a, 0)), (2*factorial(a)/(factorial(y)*factorial(-y + a)), Eq(y, 0) & Eq(-y + a, 1)), (0, True)).simplify( ) == Piecewise( (2*x, And(Eq(a, 0), Eq(y, 0))), (2, And(Eq(a, 1), Eq(y, 0))), (0, True)) args = (2, And(Eq(x, 2), Ge(y, 0))), (x, True) assert Piecewise(*args).simplify() == Piecewise(*args) args = (1, Eq(x, 0)), (sin(x)/x, True) assert Piecewise(*args).simplify() == Piecewise(*args) assert Piecewise((2 + y, And(Eq(x, 2), Eq(y, 0))), (x, True) ).simplify() == x # check that x or f(x) are recognized as being Symbol-like for lhs args = Tuple((1, Eq(x, 0)), (sin(x) + 1 + x, True)) ans = x + sin(x) + 1 f = Function('f') assert Piecewise(*args).simplify() == ans assert Piecewise(*args.subs(x, f(x))).simplify() == ans.subs(x, f(x)) # issue 18634 d = Symbol("d", integer=True) n = Symbol("n", integer=True) t = Symbol("t", real=True, positive=True) expr = Piecewise((-d + 2*n, Eq(1/t, 1)), (t**(1 - 4*n)*t**(4*n - 1)*(-d + 2*n), True)) assert expr.simplify() == -d + 2*n def test_piecewise_solve(): abs2 = Piecewise((-x, x <= 0), (x, x > 0)) f = abs2.subs(x, x - 2) assert solve(f, x) == [2] assert solve(f - 1, x) == [1, 3] f = Piecewise(((x - 2)**2, x >= 0), (1, True)) assert solve(f, x) == [2] g = Piecewise(((x - 5)**5, x >= 4), (f, True)) assert solve(g, x) == [2, 5] g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4)) assert solve(g, x) == [2, 5] g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2)) assert solve(g, x) == [5] g = Piecewise(((x - 5)**5, x >= 2), (f, True)) assert solve(g, x) == [5] g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False)) assert solve(g, x) == [5] g = Piecewise(((x - 5)**5, x >= 2), (-x + 2, x - 2 <= 0), (x - 2, x - 2 > 0)) assert solve(g, x) == [5] # if no symbol is given the piecewise detection must still work assert solve(Piecewise((x - 2, x > 2), (2 - x, True)) - 3) == [-1, 5] f = Piecewise(((x - 2)**2, x >= 0), (0, True)) raises(NotImplementedError, lambda: solve(f, x)) def nona(ans): return list(filter(lambda x: x is not S.NaN, ans)) p = Piecewise((x**2 - 4, x < y), (x - 2, True)) ans = solve(p, x) assert nona([i.subs(y, -2) for i in ans]) == [2] assert nona([i.subs(y, 2) for i in ans]) == [-2, 2] assert nona([i.subs(y, 3) for i in ans]) == [-2, 2] assert ans == [ Piecewise((-2, y > -2), (S.NaN, True)), Piecewise((2, y <= 2), (S.NaN, True)), Piecewise((2, y > 2), (S.NaN, True))] # issue 6060 absxm3 = Piecewise( (x - 3, 0 <= x - 3), (3 - x, 0 > x - 3) ) assert solve(absxm3 - y, x) == [ Piecewise((-y + 3, -y < 0), (S.NaN, True)), Piecewise((y + 3, y >= 0), (S.NaN, True))] p = Symbol('p', positive=True) assert solve(absxm3 - p, x) == [-p + 3, p + 3] # issue 6989 f = Function('f') assert solve(Eq(-f(x), Piecewise((1, x > 0), (0, True))), f(x)) == \ [Piecewise((-1, x > 0), (0, True))] # issue 8587 f = Piecewise((2*x**2, And(0 < x, x < 1)), (2, True)) assert solve(f - 1) == [1/sqrt(2)] def test_piecewise_fold(): p = Piecewise((x, x < 1), (1, 1 <= x)) assert piecewise_fold(x*p) == Piecewise((x**2, x < 1), (x, 1 <= x)) assert piecewise_fold(p + p) == Piecewise((2*x, x < 1), (2, 1 <= x)) assert piecewise_fold(Piecewise((1, x < 0), (2, True)) + Piecewise((10, x < 0), (-10, True))) == \ Piecewise((11, x < 0), (-8, True)) p1 = Piecewise((0, x < 0), (x, x <= 1), (0, True)) p2 = Piecewise((0, x < 0), (1 - x, x <= 1), (0, True)) p = 4*p1 + 2*p2 assert integrate( piecewise_fold(p), (x, -oo, oo)) == integrate(2*x + 2, (x, 0, 1)) assert piecewise_fold( Piecewise((1, y <= 0), (-Piecewise((2, y >= 0)), True) )) == Piecewise((1, y <= 0), (-2, y >= 0)) assert piecewise_fold(Piecewise((x, ITE(x > 0, y < 1, y > 1))) ) == Piecewise((x, ((x <= 0) | (y < 1)) & ((x > 0) | (y > 1)))) a, b = (Piecewise((2, Eq(x, 0)), (0, True)), Piecewise((x, Eq(-x + y, 0)), (1, Eq(-x + y, 1)), (0, True))) assert piecewise_fold(Mul(a, b, evaluate=False) ) == piecewise_fold(Mul(b, a, evaluate=False)) def test_piecewise_fold_piecewise_in_cond(): p1 = Piecewise((cos(x), x < 0), (0, True)) p2 = Piecewise((0, Eq(p1, 0)), (p1 / Abs(p1), True)) assert p2.subs(x, -pi/2) == 0 assert p2.subs(x, 1) == 0 assert p2.subs(x, -pi/4) == 1 p4 = Piecewise((0, Eq(p1, 0)), (1,True)) ans = piecewise_fold(p4) for i in range(-1, 1): assert ans.subs(x, i) == p4.subs(x, i) r1 = 1 < Piecewise((1, x < 1), (3, True)) ans = piecewise_fold(r1) for i in range(2): assert ans.subs(x, i) == r1.subs(x, i) p5 = Piecewise((1, x < 0), (3, True)) p6 = Piecewise((1, x < 1), (3, True)) p7 = Piecewise((1, p5 < p6), (0, True)) ans = piecewise_fold(p7) for i in range(-1, 2): assert ans.subs(x, i) == p7.subs(x, i) def test_piecewise_fold_piecewise_in_cond_2(): p1 = Piecewise((cos(x), x < 0), (0, True)) p2 = Piecewise((0, Eq(p1, 0)), (1 / p1, True)) p3 = Piecewise( (0, (x >= 0) | Eq(cos(x), 0)), (1/cos(x), x < 0), (zoo, True)) # redundant b/c all x are already covered assert(piecewise_fold(p2) == p3) def test_piecewise_fold_expand(): p1 = Piecewise((1, Interval(0, 1, False, True).contains(x)), (0, True)) p2 = piecewise_fold(expand((1 - x)*p1)) cond = ((x >= 0) & (x < 1)) assert piecewise_fold(expand((1 - x)*p1), evaluate=False ) == Piecewise((1 - x, cond), (-x, cond), (1, cond), (0, True), evaluate=False) assert piecewise_fold(expand((1 - x)*p1), evaluate=None ) == Piecewise((1 - x, cond), (0, True)) assert p2 == Piecewise((1 - x, cond), (0, True)) assert p2 == expand(piecewise_fold((1 - x)*p1)) def test_piecewise_duplicate(): p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x)) assert p == Piecewise(*p.args) def test_doit(): p1 = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x)) p2 = Piecewise((x, x < 1), (Integral(2 * x), -1 <= x), (x, 3 < x)) assert p2.doit() == p1 assert p2.doit(deep=False) == p2 # issue 17165 p1 = Sum(y**x, (x, -1, oo)).doit() assert p1.doit() == p1 def test_piecewise_interval(): p1 = Piecewise((x, Interval(0, 1).contains(x)), (0, True)) assert p1.subs(x, -0.5) == 0 assert p1.subs(x, 0.5) == 0.5 assert p1.diff(x) == Piecewise((1, Interval(0, 1).contains(x)), (0, True)) assert integrate(p1, x) == Piecewise( (0, x <= 0), (x**2/2, x <= 1), (S.Half, True)) def test_piecewise_collapse(): assert Piecewise((x, True)) == x a = x < 1 assert Piecewise((x, a), (x + 1, a)) == Piecewise((x, a)) assert Piecewise((x, a), (x + 1, a.reversed)) == Piecewise((x, a)) b = x < 5 def canonical(i): if isinstance(i, Piecewise): return Piecewise(*i.args) return i for args in [ ((1, a), (Piecewise((2, a), (3, b)), b)), ((1, a), (Piecewise((2, a), (3, b.reversed)), b)), ((1, a), (Piecewise((2, a), (3, b)), b), (4, True)), ((1, a), (Piecewise((2, a), (3, b), (4, True)), b)), ((1, a), (Piecewise((2, a), (3, b), (4, True)), b), (5, True))]: for i in (0, 2, 10): assert canonical( Piecewise(*args, evaluate=False).subs(x, i) ) == canonical(Piecewise(*args).subs(x, i)) r1, r2, r3, r4 = symbols('r1:5') a = x < r1 b = x < r2 c = x < r3 d = x < r4 assert Piecewise((1, a), (Piecewise( (2, a), (3, b), (4, c)), b), (5, c) ) == Piecewise((1, a), (3, b), (5, c)) assert Piecewise((1, a), (Piecewise( (2, a), (3, b), (4, c), (6, True)), c), (5, d) ) == Piecewise((1, a), (Piecewise( (3, b), (4, c)), c), (5, d)) assert Piecewise((1, Or(a, d)), (Piecewise( (2, d), (3, b), (4, c)), b), (5, c) ) == Piecewise((1, Or(a, d)), (Piecewise( (2, d), (3, b)), b), (5, c)) assert Piecewise((1, c), (2, ~c), (3, S.true) ) == Piecewise((1, c), (2, S.true)) assert Piecewise((1, c), (2, And(~c, b)), (3,True) ) == Piecewise((1, c), (2, b), (3, True)) assert Piecewise((1, c), (2, Or(~c, b)), (3,True) ).subs(dict(zip((r1, r2, r3, r4, x), (1, 2, 3, 4, 3.5)))) == 2 assert Piecewise((1, c), (2, ~c)) == Piecewise((1, c), (2, True)) def test_piecewise_lambdify(): p = Piecewise( (x**2, x < 0), (x, Interval(0, 1, False, True).contains(x)), (2 - x, x >= 1), (0, True) ) f = lambdify(x, p) assert f(-2.0) == 4.0 assert f(0.0) == 0.0 assert f(0.5) == 0.5 assert f(2.0) == 0.0 def test_piecewise_series(): from sympy.series.order import O p1 = Piecewise((sin(x), x < 0), (cos(x), x > 0)) p2 = Piecewise((x + O(x**2), x < 0), (1 + O(x**2), x > 0)) assert p1.nseries(x, n=2) == p2 def test_piecewise_as_leading_term(): p1 = Piecewise((1/x, x > 1), (0, True)) p2 = Piecewise((x, x > 1), (0, True)) p3 = Piecewise((1/x, x > 1), (x, True)) p4 = Piecewise((x, x > 1), (1/x, True)) p5 = Piecewise((1/x, x > 1), (x, True)) p6 = Piecewise((1/x, x < 1), (x, True)) p7 = Piecewise((x, x < 1), (1/x, True)) p8 = Piecewise((x, x > 1), (1/x, True)) assert p1.as_leading_term(x) == 0 assert p2.as_leading_term(x) == 0 assert p3.as_leading_term(x) == x assert p4.as_leading_term(x) == 1/x assert p5.as_leading_term(x) == x assert p6.as_leading_term(x) == 1/x assert p7.as_leading_term(x) == x assert p8.as_leading_term(x) == 1/x def test_piecewise_complex(): p1 = Piecewise((2, x < 0), (1, 0 <= x)) p2 = Piecewise((2*I, x < 0), (I, 0 <= x)) p3 = Piecewise((I*x, x > 1), (1 + I, True)) p4 = Piecewise((-I*conjugate(x), x > 1), (1 - I, True)) assert conjugate(p1) == p1 assert conjugate(p2) == piecewise_fold(-p2) assert conjugate(p3) == p4 assert p1.is_imaginary is False assert p1.is_real is True assert p2.is_imaginary is True assert p2.is_real is False assert p3.is_imaginary is None assert p3.is_real is None assert p1.as_real_imag() == (p1, 0) assert p2.as_real_imag() == (0, -I*p2) def test_conjugate_transpose(): A, B = symbols("A B", commutative=False) p = Piecewise((A*B**2, x > 0), (A**2*B, True)) assert p.adjoint() == \ Piecewise((adjoint(A*B**2), x > 0), (adjoint(A**2*B), True)) assert p.conjugate() == \ Piecewise((conjugate(A*B**2), x > 0), (conjugate(A**2*B), True)) assert p.transpose() == \ Piecewise((transpose(A*B**2), x > 0), (transpose(A**2*B), True)) def test_piecewise_evaluate(): assert Piecewise((x, True)) == x assert Piecewise((x, True), evaluate=True) == x assert Piecewise((1, Eq(1, x))).args == ((1, Eq(x, 1)),) assert Piecewise((1, Eq(1, x)), evaluate=False).args == ( (1, Eq(1, x)),) # like the additive and multiplicative identities that # cannot be kept in Add/Mul, we also do not keep a single True p = Piecewise((x, True), evaluate=False) assert p == x def test_as_expr_set_pairs(): assert Piecewise((x, x > 0), (-x, x <= 0)).as_expr_set_pairs() == \ [(x, Interval(0, oo, True, True)), (-x, Interval(-oo, 0))] assert Piecewise(((x - 2)**2, x >= 0), (0, True)).as_expr_set_pairs() == \ [((x - 2)**2, Interval(0, oo)), (0, Interval(-oo, 0, True, True))] def test_S_srepr_is_identity(): p = Piecewise((10, Eq(x, 0)), (12, True)) q = S(srepr(p)) assert p == q def test_issue_12587(): # sort holes into intervals p = Piecewise((1, x > 4), (2, Not((x <= 3) & (x > -1))), (3, True)) assert p.integrate((x, -5, 5)) == 23 p = Piecewise((1, x > 1), (2, x < y), (3, True)) lim = x, -3, 3 ans = p.integrate(lim) for i in range(-1, 3): assert ans.subs(y, i) == p.subs(y, i).integrate(lim) def test_issue_11045(): assert integrate(1/(x*sqrt(x**2 - 1)), (x, 1, 2)) == pi/3 # handle And with Or arguments assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True) ).integrate((x, 0, 3)) == 1 # hidden false assert Piecewise((1, x > 1), (2, x > x + 1), (3, True) ).integrate((x, 0, 3)) == 5 # targetcond is Eq assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True) ).integrate((x, 0, 4)) == 6 # And has Relational needing to be solved assert Piecewise((1, And(2*x > x + 1, x < 2)), (0, True) ).integrate((x, 0, 3)) == 1 # Or has Relational needing to be solved assert Piecewise((1, Or(2*x > x + 2, x < 1)), (0, True) ).integrate((x, 0, 3)) == 2 # ignore hidden false (handled in canonicalization) assert Piecewise((1, x > 1), (2, x > x + 1), (3, True) ).integrate((x, 0, 3)) == 5 # watch for hidden True Piecewise assert Piecewise((2, Eq(1 - x, x*(1/x - 1))), (0, True) ).integrate((x, 0, 3)) == 6 # overlapping conditions of targetcond are recognized and ignored; # the condition x > 3 will be pre-empted by the first condition assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True) ).integrate((x, 0, 4)) == 6 # convert Ne to Or assert Piecewise((1, Ne(x, 0)), (2, True) ).integrate((x, -1, 1)) == 2 # no default but well defined assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4)) ).integrate((x, 1, 4)) == 5 p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))) nan = Undefined i = p.integrate((x, 1, y)) assert i == Piecewise( (y - 1, y < 1), (Min(3, y)**2/2 - Min(3, y) + Min(4, y) - S.Half, y <= Min(4, y)), (nan, True)) assert p.integrate((x, 1, -1)) == i.subs(y, -1) assert p.integrate((x, 1, 4)) == 5 assert p.integrate((x, 1, 5)) is nan # handle Not p = Piecewise((1, x > 1), (2, Not(And(x > 1, x< 3))), (3, True)) assert p.integrate((x, 0, 3)) == 4 # handle updating of int_expr when there is overlap p = Piecewise( (1, And(5 > x, x > 1)), (2, Or(x < 3, x > 7)), (4, x < 8)) assert p.integrate((x, 0, 10)) == 20 # And with Eq arg handling assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)) ).integrate((x, 0, 3)) is S.NaN assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)), (3, True) ).integrate((x, 0, 3)) == 7 assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)), (3, True) ).integrate((x, -1, 1)) == 4 # middle condition doesn't matter: it's a zero width interval assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True) ).integrate((x, 0, 3)) == 7 def test_holes(): nan = Undefined assert Piecewise((1, x < 2)).integrate(x) == Piecewise( (x, x < 2), (nan, True)) assert Piecewise((1, And(x > 1, x < 2))).integrate(x) == Piecewise( (nan, x < 1), (x - 1, x < 2), (nan, True)) assert Piecewise((1, And(x > 1, x < 2))).integrate((x, 0, 3)) is nan assert Piecewise((1, And(x > 0, x < 4))).integrate((x, 1, 3)) == 2 # this also tests that the integrate method is used on non-Piecwise # arguments in _eval_integral A, B = symbols("A B") a, b = symbols('a b', real=True) assert Piecewise((A, And(x < 0, a < 1)), (B, Or(x < 1, a > 2)) ).integrate(x) == Piecewise( (B*x, (a > 2)), (Piecewise((A*x, x < 0), (B*x, x < 1), (nan, True)), a < 1), (Piecewise((B*x, x < 1), (nan, True)), True)) def test_issue_11922(): def f(x): return Piecewise((0, x < -1), (1 - x**2, x < 1), (0, True)) autocorr = lambda k: ( f(x) * f(x + k)).integrate((x, -1, 1)) assert autocorr(1.9) > 0 k = symbols('k') good_autocorr = lambda k: ( (1 - x**2) * f(x + k)).integrate((x, -1, 1)) a = good_autocorr(k) assert a.subs(k, 3) == 0 k = symbols('k', positive=True) a = good_autocorr(k) assert a.subs(k, 3) == 0 assert Piecewise((0, x < 1), (10, (x >= 1)) ).integrate() == Piecewise((0, x < 1), (10*x - 10, True)) def test_issue_5227(): f = 0.0032513612725229*Piecewise((0, x < -80.8461538461539), (-0.0160799238820171*x + 1.33215984776403, x < 2), (Piecewise((0.3, x > 123), (0.7, True)) + Piecewise((0.4, x > 2), (0.6, True)), x <= 123), (-0.00817409766454352*x + 2.10541401273885, x < 380.571428571429), (0, True)) i = integrate(f, (x, -oo, oo)) assert i == Integral(f, (x, -oo, oo)).doit() assert str(i) == '1.00195081676351' assert Piecewise((1, x - y < 0), (0, True) ).integrate(y) == Piecewise((0, y <= x), (-x + y, True)) def test_issue_10137(): a = Symbol('a', real=True, finite=True) b = Symbol('b', real=True, finite=True) x = Symbol('x', real=True, finite=True) y = Symbol('y', real=True, finite=True) p0 = Piecewise((0, Or(x < a, x > b)), (1, True)) p1 = Piecewise((0, Or(a > x, b < x)), (1, True)) assert integrate(p0, (x, y, oo)) == integrate(p1, (x, y, oo)) p3 = Piecewise((1, And(0 < x, x < a)), (0, True)) p4 = Piecewise((1, And(a > x, x > 0)), (0, True)) ip3 = integrate(p3, x) assert ip3 == Piecewise( (0, x <= 0), (x, x <= Max(0, a)), (Max(0, a), True)) ip4 = integrate(p4, x) assert ip4 == ip3 assert p3.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2 assert p4.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2 def test_stackoverflow_43852159(): f = lambda x: Piecewise((1, (x >= -1) & (x <= 1)), (0, True)) Conv = lambda x: integrate(f(x - y)*f(y), (y, -oo, +oo)) cx = Conv(x) assert cx.subs(x, -1.5) == cx.subs(x, 1.5) assert cx.subs(x, 3) == 0 assert piecewise_fold(f(x - y)*f(y)) == Piecewise( (1, (y >= -1) & (y <= 1) & (x - y >= -1) & (x - y <= 1)), (0, True)) def test_issue_12557(): ''' # 3200 seconds to compute the fourier part of issue import sympy as sym x,y,z,t = sym.symbols('x y z t') k = sym.symbols("k", integer=True) fourier = sym.fourier_series(sym.cos(k*x)*sym.sqrt(x**2), (x, -sym.pi, sym.pi)) assert fourier == FourierSeries( sqrt(x**2)*cos(k*x), (x, -pi, pi), (Piecewise((pi**2, Eq(k, 0)), (2*(-1)**k/k**2 - 2/k**2, True))/(2*pi), SeqFormula(Piecewise((pi**2, (Eq(_n, 0) & Eq(k, 0)) | (Eq(_n, 0) & Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(k, 0) & Eq(_n, -k)) | (Eq(_n, 0) & Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), (pi**2/2, Eq(_n, k) | Eq(_n, -k) | (Eq(_n, 0) & Eq(_n, k)) | (Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(_n, -k)) | (Eq(_n, k) & Eq(_n, -k)) | (Eq(k, 0) & Eq(_n, -k)) | (Eq(_n, 0) & Eq(_n, k) & Eq(_n, -k)) | (Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), ((-1)**k*pi**2*_n**3*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + pi*k**4) - (-1)**k*pi**2*_n**3*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - pi*k**4) + (-1)**k*pi*_n**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + pi*k**4) - (-1)**k*pi*_n**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - pi*k**4) - (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + pi*k**4) + (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - pi*k**4) + (-1)**k*pi*k**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + pi*k**4) - (-1)**k*pi*k**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - pi*k**4) - (2*_n**2 + 2*k**2)/(_n**4 - 2*_n**2*k**2 + k**4), True))*cos(_n*x)/pi, (_n, 1, oo)), SeqFormula(0, (_k, 1, oo)))) ''' x = symbols("x", real=True) k = symbols('k', integer=True, finite=True) abs2 = lambda x: Piecewise((-x, x <= 0), (x, x > 0)) assert integrate(abs2(x), (x, -pi, pi)) == pi**2 func = cos(k*x)*sqrt(x**2) assert integrate(func, (x, -pi, pi)) == Piecewise( (2*(-1)**k/k**2 - 2/k**2, Ne(k, 0)), (pi**2, True)) def test_issue_6900(): from itertools import permutations t0, t1, T, t = symbols('t0, t1 T t') f = Piecewise((0, t < t0), (x, And(t0 <= t, t < t1)), (0, t >= t1)) g = f.integrate(t) assert g == Piecewise( (0, t <= t0), (t*x - t0*x, t <= Max(t0, t1)), (-t0*x + x*Max(t0, t1), True)) for i in permutations(range(2)): reps = dict(zip((t0,t1), i)) for tt in range(-1,3): assert (g.xreplace(reps).subs(t,tt) == f.xreplace(reps).integrate(t).subs(t,tt)) lim = Tuple(t, t0, T) g = f.integrate(lim) ans = Piecewise( (-t0*x + x*Min(T, Max(t0, t1)), T > t0), (0, True)) for i in permutations(range(3)): reps = dict(zip((t0,t1,T), i)) tru = f.xreplace(reps).integrate(lim.xreplace(reps)) assert tru == ans.xreplace(reps) assert g == ans def test_issue_10122(): assert solve(abs(x) + abs(x - 1) - 1 > 0, x ) == Or(And(-oo < x, x < S.Zero), And(S.One < x, x < oo)) def test_issue_4313(): u = Piecewise((0, x <= 0), (1, x >= a), (x/a, True)) e = (u - u.subs(x, y))**2/(x - y)**2 M = Max(0, a) assert integrate(e, x).expand() == Piecewise( (Piecewise( (0, x <= 0), (-y**2/(a**2*x - a**2*y) + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 - y/a**2, x <= M), (-y**2/(-a**2*y + a**2*M) + 1/(-y + M) - 1/(x - y) - 2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 - y/a**2 + M/a**2, True)), ((a <= y) & (y <= 0)) | ((y <= 0) & (y > -oo))), (Piecewise( (-1/(x - y), x <= 0), (-a**2/(a**2*x - a**2*y) + 2*a*y/(a**2*x - a**2*y) - y**2/(a**2*x - a**2*y) + 2*log(-y)/a - 2*log(x - y)/a + 2/a + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 - y/a**2, x <= M), (-a**2/(-a**2*y + a**2*M) + 2*a*y/(-a**2*y + a**2*M) - y**2/(-a**2*y + a**2*M) + 2*log(-y)/a - 2*log(-y + M)/a + 2/a - 2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 - y/a**2 + M/a**2, True)), a <= y), (Piecewise( (-y**2/(a**2*x - a**2*y), x <= 0), (x/a**2 + y/a**2, x <= M), (a**2/(-a**2*y + a**2*M) - a**2/(a**2*x - a**2*y) - 2*a*y/(-a**2*y + a**2*M) + 2*a*y/(a**2*x - a**2*y) + y**2/(-a**2*y + a**2*M) - y**2/(a**2*x - a**2*y) + y/a**2 + M/a**2, True)), True)) def test__intervals(): assert Piecewise((x + 2, Eq(x, 3)))._intervals(x) == (True, []) assert Piecewise( (1, x > x + 1), (Piecewise((1, x < x + 1)), 2*x < 2*x + 1), (1, True))._intervals(x) == (True, [(-oo, oo, 1, 1)]) assert Piecewise((1, Ne(x, I)), (0, True))._intervals(x) == (True, [(-oo, oo, 1, 0)]) assert Piecewise((-cos(x), sin(x) >= 0), (cos(x), True) )._intervals(x) == (True, [(0, pi, -cos(x), 0), (-oo, oo, cos(x), 1)]) # the following tests that duplicates are removed and that non-Eq # generated zero-width intervals are removed assert Piecewise((1, Abs(x**(-2)) > 1), (0, True) )._intervals(x) == (True, [(-1, 0, 1, 0), (0, 1, 1, 0), (-oo, oo, 0, 1)]) def test_containment(): a, b, c, d, e = [1, 2, 3, 4, 5] p = (Piecewise((d, x > 1), (e, True))* Piecewise((a, Abs(x - 1) < 1), (b, Abs(x - 2) < 2), (c, True))) assert p.integrate(x).diff(x) == Piecewise( (c*e, x <= 0), (a*e, x <= 1), (a*d, x < 2), # this is what we want to get right (b*d, x < 4), (c*d, True)) def test_piecewise_with_DiracDelta(): d1 = DiracDelta(x - 1) assert integrate(d1, (x, -oo, oo)) == 1 assert integrate(d1, (x, 0, 2)) == 1 assert Piecewise((d1, Eq(x, 2)), (0, True)).integrate(x) == 0 assert Piecewise((d1, x < 2), (0, True)).integrate(x) == Piecewise( (Heaviside(x - 1), x < 2), (1, True)) # TODO raise error if function is discontinuous at limit of # integration, e.g. integrate(d1, (x, -2, 1)) or Piecewise( # (d1, Eq(x, 1) def test_issue_10258(): assert Piecewise((0, x < 1), (1, True)).is_zero is None assert Piecewise((-1, x < 1), (1, True)).is_zero is False a = Symbol('a', zero=True) assert Piecewise((0, x < 1), (a, True)).is_zero assert Piecewise((1, x < 1), (a, x < 3)).is_zero is None a = Symbol('a') assert Piecewise((0, x < 1), (a, True)).is_zero is None assert Piecewise((0, x < 1), (1, True)).is_nonzero is None assert Piecewise((1, x < 1), (2, True)).is_nonzero assert Piecewise((0, x < 1), (oo, True)).is_finite is None assert Piecewise((0, x < 1), (1, True)).is_finite b = Basic() assert Piecewise((b, x < 1)).is_finite is None # 10258 c = Piecewise((1, x < 0), (2, True)) < 3 assert c != True assert piecewise_fold(c) == True def test_issue_10087(): a, b = Piecewise((x, x > 1), (2, True)), Piecewise((x, x > 3), (3, True)) m = a*b f = piecewise_fold(m) for i in (0, 2, 4): assert m.subs(x, i) == f.subs(x, i) m = a + b f = piecewise_fold(m) for i in (0, 2, 4): assert m.subs(x, i) == f.subs(x, i) def test_issue_8919(): c = symbols('c:5') x = symbols("x") f1 = Piecewise((c[1], x < 1), (c[2], True)) f2 = Piecewise((c[3], x < Rational(1, 3)), (c[4], True)) assert integrate(f1*f2, (x, 0, 2) ) == c[1]*c[3]/3 + 2*c[1]*c[4]/3 + c[2]*c[4] f1 = Piecewise((0, x < 1), (2, True)) f2 = Piecewise((3, x < 2), (0, True)) assert integrate(f1*f2, (x, 0, 3)) == 6 y = symbols("y", positive=True) a, b, c, x, z = symbols("a,b,c,x,z", real=True) I = Integral(Piecewise( (0, (x >= y) | (x < 0) | (b > c)), (a, True)), (x, 0, z)) ans = I.doit() assert ans == Piecewise((0, b > c), (a*Min(y, z) - a*Min(0, z), True)) for cond in (True, False): for yy in range(1, 3): for zz in range(-yy, 0, yy): reps = [(b > c, cond), (y, yy), (z, zz)] assert ans.subs(reps) == I.subs(reps).doit() def test_unevaluated_integrals(): f = Function('f') p = Piecewise((1, Eq(f(x) - 1, 0)), (2, x - 10 < 0), (0, True)) assert p.integrate(x) == Integral(p, x) assert p.integrate((x, 0, 5)) == Integral(p, (x, 0, 5)) # test it by replacing f(x) with x%2 which will not # affect the answer: the integrand is essentially 2 over # the domain of integration assert Integral(p, (x, 0, 5)).subs(f(x), x%2).n() == 10 # this is a test of using _solve_inequality when # solve_univariate_inequality fails assert p.integrate(y) == Piecewise( (y, Eq(f(x), 1) | ((x < 10) & Eq(f(x), 1))), (2*y, (x > -oo) & (x < 10)), (0, True)) def test_conditions_as_alternate_booleans(): a, b, c = symbols('a:c') assert Piecewise((x, Piecewise((y < 1, x > 0), (y > 1, True))) ) == Piecewise((x, ITE(x > 0, y < 1, y > 1))) def test_Piecewise_rewrite_as_ITE(): a, b, c, d = symbols('a:d') def _ITE(*args): return Piecewise(*args).rewrite(ITE) assert _ITE((a, x < 1), (b, x >= 1)) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (b, x < oo)) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (b, Or(y < 1, x < oo)), (c, y > 0) ) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (b, True)) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (b, x < 2), (c, True) ) == ITE(x < 1, a, ITE(x < 2, b, c)) assert _ITE((a, x < 1), (b, y < 2), (c, True) ) == ITE(x < 1, a, ITE(y < 2, b, c)) assert _ITE((a, x < 1), (b, x < oo), (c, y < 1) ) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (c, y < 1), (b, x < oo), (d, True) ) == ITE(x < 1, a, ITE(y < 1, c, b)) assert _ITE((a, x < 0), (b, Or(x < oo, y < 1)) ) == ITE(x < 0, a, b) raises(TypeError, lambda: _ITE((x + 1, x < 1), (x, True))) # if `a` in the following were replaced with y then the coverage # is complete but something other than as_set would need to be # used to detect this raises(NotImplementedError, lambda: _ITE((x, x < y), (y, x >= a))) raises(ValueError, lambda: _ITE((a, x < 2), (b, x > 3))) def test_issue_14052(): assert integrate(abs(sin(x)), (x, 0, 2*pi)) == 4 def test_issue_14240(): assert piecewise_fold( Piecewise((1, a), (2, b), (4, True)) + Piecewise((8, a), (16, True)) ) == Piecewise((9, a), (18, b), (20, True)) assert piecewise_fold( Piecewise((2, a), (3, b), (5, True)) * Piecewise((7, a), (11, True)) ) == Piecewise((14, a), (33, b), (55, True)) # these will hang if naive folding is used assert piecewise_fold(Add(*[ Piecewise((i, a), (0, True)) for i in range(40)]) ) == Piecewise((780, a), (0, True)) assert piecewise_fold(Mul(*[ Piecewise((i, a), (0, True)) for i in range(1, 41)]) ) == Piecewise((factorial(40), a), (0, True)) def test_issue_14787(): x = Symbol('x') f = Piecewise((x, x < 1), ((S(58) / 7), True)) assert str(f.evalf()) == "Piecewise((x, x < 1), (8.28571428571429, True))" def test_issue_8458(): x, y = symbols('x y') # Original issue p1 = Piecewise((0, Eq(x, 0)), (sin(x), True)) assert p1.simplify() == sin(x) # Slightly larger variant p2 = Piecewise((x, Eq(x, 0)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True)) assert p2.simplify() == sin(x) # Test for problem highlighted during review p3 = Piecewise((x+1, Eq(x, -1)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True)) assert p3.simplify() == Piecewise((0, Eq(x, -1)), (sin(x), True)) def test_issue_16417(): z = Symbol('z') assert unchanged(Piecewise, (1, Or(Eq(im(z), 0), Gt(re(z), 0))), (2, True)) x = Symbol('x') assert unchanged(Piecewise, (S.Pi, re(x) < 0), (0, Or(re(x) > 0, Ne(im(x), 0))), (S.NaN, True)) r = Symbol('r', real=True) p = Piecewise((S.Pi, re(r) < 0), (0, Or(re(r) > 0, Ne(im(r), 0))), (S.NaN, True)) assert p == Piecewise((S.Pi, r < 0), (0, r > 0), (S.NaN, True), evaluate=False) # Does not work since imaginary != 0... #i = Symbol('i', imaginary=True) #p = Piecewise((S.Pi, re(i) < 0), # (0, Or(re(i) > 0, Ne(im(i), 0))), # (S.NaN, True)) #assert p == Piecewise((0, Ne(im(i), 0)), # (S.NaN, True), evaluate=False) i = I*r p = Piecewise((S.Pi, re(i) < 0), (0, Or(re(i) > 0, Ne(im(i), 0))), (S.NaN, True)) assert p == Piecewise((0, Ne(im(i), 0)), (S.NaN, True), evaluate=False) assert p == Piecewise((0, Ne(r, 0)), (S.NaN, True), evaluate=False) def test_eval_rewrite_as_KroneckerDelta(): x, y, z, n, t, m = symbols('x y z n t m') K = KroneckerDelta f = lambda p: expand(p.rewrite(K)) p1 = Piecewise((0, Eq(x, y)), (1, True)) assert f(p1) == 1 - K(x, y) p2 = Piecewise((x, Eq(y,0)), (z, Eq(t,0)), (n, True)) assert f(p2) == n*K(0, t)*K(0, y) - n*K(0, t) - n*K(0, y) + n + \ x*K(0, y) - z*K(0, t)*K(0, y) + z*K(0, t) p3 = Piecewise((1, Ne(x, y)), (0, True)) assert f(p3) == 1 - K(x, y) p4 = Piecewise((1, Eq(x, 3)), (4, True), (5, True)) assert f(p4) == 4 - 3*K(3, x) p5 = Piecewise((3, Ne(x, 2)), (4, Eq(y, 2)), (5, True)) assert f(p5) == -K(2, x)*K(2, y) + 2*K(2, x) + 3 p6 = Piecewise((0, Ne(x, 1) & Ne(y, 4)), (1, True)) assert f(p6) == -K(1, x)*K(4, y) + K(1, x) + K(4, y) p7 = Piecewise((2, Eq(y, 3) & Ne(x, 2)), (1, True)) assert f(p7) == -K(2, x)*K(3, y) + K(3, y) + 1 p8 = Piecewise((4, Eq(x, 3) & Ne(y, 2)), (1, True)) assert f(p8) == -3*K(2, y)*K(3, x) + 3*K(3, x) + 1 p9 = Piecewise((6, Eq(x, 4) & Eq(y, 1)), (1, True)) assert f(p9) == 5 * K(1, y) * K(4, x) + 1 p10 = Piecewise((4, Ne(x, -4) | Ne(y, 1)), (1, True)) assert f(p10) == -3 * K(-4, x) * K(1, y) + 4 p11 = Piecewise((1, Eq(y, 2) | Ne(x, -3)), (2, True)) assert f(p11) == -K(-3, x)*K(2, y) + K(-3, x) + 1 p12 = Piecewise((-1, Eq(x, 1) | Ne(y, 3)), (1, True)) assert f(p12) == -2*K(1, x)*K(3, y) + 2*K(3, y) - 1 p13 = Piecewise((3, Eq(x, 2) | Eq(y, 4)), (1, True)) assert f(p13) == -2*K(2, x)*K(4, y) + 2*K(2, x) + 2*K(4, y) + 1 p14 = Piecewise((1, Ne(x, 0) | Ne(y, 1)), (3, True)) assert f(p14) == 2 * K(0, x) * K(1, y) + 1 p15 = Piecewise((2, Eq(x, 3) | Ne(y, 2)), (3, Eq(x, 4) & Eq(y, 5)), (1, True)) assert f(p15) == -2*K(2, y)*K(3, x)*K(4, x)*K(5, y) + K(2, y)*K(3, x) + \ 2*K(2, y)*K(4, x)*K(5, y) - K(2, y) + 2 p16 = Piecewise((0, Ne(m, n)), (1, True))*Piecewise((0, Ne(n, t)), (1, True))\ *Piecewise((0, Ne(n, x)), (1, True)) - Piecewise((0, Ne(t, x)), (1, True)) assert f(p16) == K(m, n)*K(n, t)*K(n, x) - K(t, x) p17 = Piecewise((0, Ne(t, x) & (Ne(m, n) | Ne(n, t) | Ne(n, x))), (1, Ne(t, x)), (-1, Ne(m, n) | Ne(n, t) | Ne(n, x)), (0, True)) assert f(p17) == K(m, n)*K(n, t)*K(n, x) - K(t, x) p18 = Piecewise((-4, Eq(y, 1) | (Eq(x, -5) & Eq(x, z))), (4, True)) assert f(p18) == 8*K(-5, x)*K(1, y)*K(x, z) - 8*K(-5, x)*K(x, z) - 8*K(1, y) + 4 p19 = Piecewise((0, x > 2), (1, True)) assert f(p19) == p19 p20 = Piecewise((0, And(x < 2, x > -5)), (1, True)) assert f(p20) == p20 p21 = Piecewise((0, Or(x > 1, x < 0)), (1, True)) assert f(p21) == p21 p22 = Piecewise((0, ~((Eq(y, -1) | Ne(x, 0)) & (Ne(x, 1) | Ne(y, -1)))), (1, True)) assert f(p22) == K(-1, y)*K(0, x) - K(-1, y)*K(1, x) - K(0, x) + 1 @slow def test_identical_conds_issue(): from sympy.stats import Uniform, density u1 = Uniform('u1', 0, 1) u2 = Uniform('u2', 0, 1) # Result is quite big, so not really important here (and should ideally be # simpler). Should not give an exception though. density(u1 + u2) def test_issue_7370(): f = Piecewise((1, x <= 2400)) v = integrate(f, (x, 0, Float("252.4", 30))) assert str(v) == '252.400000000000000000000000000' def test_issue_14933(): x = Symbol('x') y = Symbol('y') inp = MatrixSymbol('inp', 1, 1) rep_dict = {y: inp[0, 0], x: inp[0, 0]} p = Piecewise((1, ITE(y > 0, x < 0, True))) assert p.xreplace(rep_dict) == Piecewise((1, ITE(inp[0, 0] > 0, inp[0, 0] < 0, True))) def test_issue_16715(): raises(NotImplementedError, lambda: Piecewise((x, x<0), (0, y>1)).as_expr_set_pairs()) def test_issue_20360(): t, tau = symbols("t tau", real=True) n = symbols("n", integer=True) lam = pi * (n - S.Half) eq = integrate(exp(lam * tau), (tau, 0, t)) assert simplify(eq) == (2*exp(pi*t*(2*n - 1)/2) - 2)/(pi*(2*n - 1)) def test_piecewise_eval(): # XXX these tests might need modification if this # simplification is moved out of eval and into # boolalg or Piecewise simplification functions f = lambda x: x.args[0].cond # unsimplified assert f(Piecewise((x, (x > -oo) & (x < 3))) ) == ((x > -oo) & (x < 3)) assert f(Piecewise((x, (x > -oo) & (x < oo))) ) == ((x > -oo) & (x < oo)) assert f(Piecewise((x, (x > -3) & (x < 3))) ) == ((x > -3) & (x < 3)) assert f(Piecewise((x, (x > -3) & (x < oo))) ) == ((x > -3) & (x < oo)) assert f(Piecewise((x, (x <= 3) & (x > -oo))) ) == ((x <= 3) & (x > -oo)) assert f(Piecewise((x, (x <= 3) & (x > -3))) ) == ((x <= 3) & (x > -3)) assert f(Piecewise((x, (x >= -3) & (x < 3))) ) == ((x >= -3) & (x < 3)) assert f(Piecewise((x, (x >= -3) & (x < oo))) ) == ((x >= -3) & (x < oo)) assert f(Piecewise((x, (x >= -3) & (x <= 3))) ) == ((x >= -3) & (x <= 3)) # could simplify by keeping only the first # arg of result assert f(Piecewise((x, (x <= oo) & (x > -oo))) ) == (x > -oo) & (x <= oo) assert f(Piecewise((x, (x <= oo) & (x > -3))) ) == (x > -3) & (x <= oo) assert f(Piecewise((x, (x >= -oo) & (x < 3))) ) == (x < 3) & (x >= -oo) assert f(Piecewise((x, (x >= -oo) & (x < oo))) ) == (x < oo) & (x >= -oo) assert f(Piecewise((x, (x >= -oo) & (x <= 3))) ) == (x <= 3) & (x >= -oo) assert f(Piecewise((x, (x >= -oo) & (x <= oo))) ) == (x <= oo) & (x >= -oo) # but cannot be True unless x is real assert f(Piecewise((x, (x >= -3) & (x <= oo))) ) == (x >= -3) & (x <= oo) assert f(Piecewise((x, (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1))) ) == (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1)
cb073b70826122bb1a1425031fe6eefed2eedd3ff815aa91de8bfb0187f7547b
import itertools as it from sympy.core.expr import unchanged from sympy.core.function import Function from sympy.core.numbers import I, oo, Rational from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.external import import_module from sympy.functions.elementary.exponential import log from sympy.functions.elementary.integers import floor, ceiling from sympy.functions.elementary.miscellaneous import (sqrt, cbrt, root, Min, Max, real_root, Rem) from sympy.functions.elementary.trigonometric import cos, sin from sympy.functions.special.delta_functions import Heaviside from sympy.utilities.lambdify import lambdify from sympy.testing.pytest import raises, skip, ignore_warnings def test_Min(): from sympy.abc import x, y, z n = Symbol('n', negative=True) n_ = Symbol('n_', negative=True) nn = Symbol('nn', nonnegative=True) nn_ = Symbol('nn_', nonnegative=True) p = Symbol('p', positive=True) p_ = Symbol('p_', positive=True) np = Symbol('np', nonpositive=True) np_ = Symbol('np_', nonpositive=True) r = Symbol('r', real=True) assert Min(5, 4) == 4 assert Min(-oo, -oo) is -oo assert Min(-oo, n) is -oo assert Min(n, -oo) is -oo assert Min(-oo, np) is -oo assert Min(np, -oo) is -oo assert Min(-oo, 0) is -oo assert Min(0, -oo) is -oo assert Min(-oo, nn) is -oo assert Min(nn, -oo) is -oo assert Min(-oo, p) is -oo assert Min(p, -oo) is -oo assert Min(-oo, oo) is -oo assert Min(oo, -oo) is -oo assert Min(n, n) == n assert unchanged(Min, n, np) assert Min(np, n) == Min(n, np) assert Min(n, 0) == n assert Min(0, n) == n assert Min(n, nn) == n assert Min(nn, n) == n assert Min(n, p) == n assert Min(p, n) == n assert Min(n, oo) == n assert Min(oo, n) == n assert Min(np, np) == np assert Min(np, 0) == np assert Min(0, np) == np assert Min(np, nn) == np assert Min(nn, np) == np assert Min(np, p) == np assert Min(p, np) == np assert Min(np, oo) == np assert Min(oo, np) == np assert Min(0, 0) == 0 assert Min(0, nn) == 0 assert Min(nn, 0) == 0 assert Min(0, p) == 0 assert Min(p, 0) == 0 assert Min(0, oo) == 0 assert Min(oo, 0) == 0 assert Min(nn, nn) == nn assert unchanged(Min, nn, p) assert Min(p, nn) == Min(nn, p) assert Min(nn, oo) == nn assert Min(oo, nn) == nn assert Min(p, p) == p assert Min(p, oo) == p assert Min(oo, p) == p assert Min(oo, oo) is oo assert Min(n, n_).func is Min assert Min(nn, nn_).func is Min assert Min(np, np_).func is Min assert Min(p, p_).func is Min # lists assert Min() is S.Infinity assert Min(x) == x assert Min(x, y) == Min(y, x) assert Min(x, y, z) == Min(z, y, x) assert Min(x, Min(y, z)) == Min(z, y, x) assert Min(x, Max(y, -oo)) == Min(x, y) assert Min(p, oo, n, p, p, p_) == n assert Min(p_, n_, p) == n_ assert Min(n, oo, -7, p, p, 2) == Min(n, -7) assert Min(2, x, p, n, oo, n_, p, 2, -2, -2) == Min(-2, x, n, n_) assert Min(0, x, 1, y) == Min(0, x, y) assert Min(1000, 100, -100, x, p, n) == Min(n, x, -100) assert unchanged(Min, sin(x), cos(x)) assert Min(sin(x), cos(x)) == Min(cos(x), sin(x)) assert Min(cos(x), sin(x)).subs(x, 1) == cos(1) assert Min(cos(x), sin(x)).subs(x, S.Half) == sin(S.Half) raises(ValueError, lambda: Min(cos(x), sin(x)).subs(x, I)) raises(ValueError, lambda: Min(I)) raises(ValueError, lambda: Min(I, x)) raises(ValueError, lambda: Min(S.ComplexInfinity, x)) assert Min(1, x).diff(x) == Heaviside(1 - x) assert Min(x, 1).diff(x) == Heaviside(1 - x) assert Min(0, -x, 1 - 2*x).diff(x) == -Heaviside(x + Min(0, -2*x + 1)) \ - 2*Heaviside(2*x + Min(0, -x) - 1) # issue 7619 f = Function('f') assert Min(1, 2*Min(f(1), 2)) # doesn't fail # issue 7233 e = Min(0, x) assert e.n().args == (0, x) # issue 8643 m = Min(n, p_, n_, r) assert m.is_positive is False assert m.is_nonnegative is False assert m.is_negative is True m = Min(p, p_) assert m.is_positive is True assert m.is_nonnegative is True assert m.is_negative is False m = Min(p, nn_, p_) assert m.is_positive is None assert m.is_nonnegative is True assert m.is_negative is False m = Min(nn, p, r) assert m.is_positive is None assert m.is_nonnegative is None assert m.is_negative is None def test_Max(): from sympy.abc import x, y, z n = Symbol('n', negative=True) n_ = Symbol('n_', negative=True) nn = Symbol('nn', nonnegative=True) p = Symbol('p', positive=True) p_ = Symbol('p_', positive=True) r = Symbol('r', real=True) assert Max(5, 4) == 5 # lists assert Max() is S.NegativeInfinity assert Max(x) == x assert Max(x, y) == Max(y, x) assert Max(x, y, z) == Max(z, y, x) assert Max(x, Max(y, z)) == Max(z, y, x) assert Max(x, Min(y, oo)) == Max(x, y) assert Max(n, -oo, n_, p, 2) == Max(p, 2) assert Max(n, -oo, n_, p) == p assert Max(2, x, p, n, -oo, S.NegativeInfinity, n_, p, 2) == Max(2, x, p) assert Max(0, x, 1, y) == Max(1, x, y) assert Max(r, r + 1, r - 1) == 1 + r assert Max(1000, 100, -100, x, p, n) == Max(p, x, 1000) assert Max(cos(x), sin(x)) == Max(sin(x), cos(x)) assert Max(cos(x), sin(x)).subs(x, 1) == sin(1) assert Max(cos(x), sin(x)).subs(x, S.Half) == cos(S.Half) raises(ValueError, lambda: Max(cos(x), sin(x)).subs(x, I)) raises(ValueError, lambda: Max(I)) raises(ValueError, lambda: Max(I, x)) raises(ValueError, lambda: Max(S.ComplexInfinity, 1)) assert Max(n, -oo, n_, p, 2) == Max(p, 2) assert Max(n, -oo, n_, p, 1000) == Max(p, 1000) assert Max(1, x).diff(x) == Heaviside(x - 1) assert Max(x, 1).diff(x) == Heaviside(x - 1) assert Max(x**2, 1 + x, 1).diff(x) == \ 2*x*Heaviside(x**2 - Max(1, x + 1)) \ + Heaviside(x - Max(1, x**2) + 1) e = Max(0, x) assert e.n().args == (0, x) # issue 8643 m = Max(p, p_, n, r) assert m.is_positive is True assert m.is_nonnegative is True assert m.is_negative is False m = Max(n, n_) assert m.is_positive is False assert m.is_nonnegative is False assert m.is_negative is True m = Max(n, n_, r) assert m.is_positive is None assert m.is_nonnegative is None assert m.is_negative is None m = Max(n, nn, r) assert m.is_positive is None assert m.is_nonnegative is True assert m.is_negative is False def test_minmax_assumptions(): r = Symbol('r', real=True) a = Symbol('a', real=True, algebraic=True) t = Symbol('t', real=True, transcendental=True) q = Symbol('q', rational=True) p = Symbol('p', irrational=True) n = Symbol('n', rational=True, integer=False) i = Symbol('i', integer=True) o = Symbol('o', odd=True) e = Symbol('e', even=True) k = Symbol('k', prime=True) reals = [r, a, t, q, p, n, i, o, e, k] for ext in (Max, Min): for x, y in it.product(reals, repeat=2): # Must be real assert ext(x, y).is_real # Algebraic? if x.is_algebraic and y.is_algebraic: assert ext(x, y).is_algebraic elif x.is_transcendental and y.is_transcendental: assert ext(x, y).is_transcendental else: assert ext(x, y).is_algebraic is None # Rational? if x.is_rational and y.is_rational: assert ext(x, y).is_rational elif x.is_irrational and y.is_irrational: assert ext(x, y).is_irrational else: assert ext(x, y).is_rational is None # Integer? if x.is_integer and y.is_integer: assert ext(x, y).is_integer elif x.is_noninteger and y.is_noninteger: assert ext(x, y).is_noninteger else: assert ext(x, y).is_integer is None # Odd? if x.is_odd and y.is_odd: assert ext(x, y).is_odd elif x.is_odd is False and y.is_odd is False: assert ext(x, y).is_odd is False else: assert ext(x, y).is_odd is None # Even? if x.is_even and y.is_even: assert ext(x, y).is_even elif x.is_even is False and y.is_even is False: assert ext(x, y).is_even is False else: assert ext(x, y).is_even is None # Prime? if x.is_prime and y.is_prime: assert ext(x, y).is_prime elif x.is_prime is False and y.is_prime is False: assert ext(x, y).is_prime is False else: assert ext(x, y).is_prime is None def test_issue_8413(): x = Symbol('x', real=True) # we can't evaluate in general because non-reals are not # comparable: Min(floor(3.2 + I), 3.2 + I) -> ValueError assert Min(floor(x), x) == floor(x) assert Min(ceiling(x), x) == x assert Max(floor(x), x) == x assert Max(ceiling(x), x) == ceiling(x) def test_root(): from sympy.abc import x n = Symbol('n', integer=True) k = Symbol('k', integer=True) assert root(2, 2) == sqrt(2) assert root(2, 1) == 2 assert root(2, 3) == 2**Rational(1, 3) assert root(2, 3) == cbrt(2) assert root(2, -5) == 2**Rational(4, 5)/2 assert root(-2, 1) == -2 assert root(-2, 2) == sqrt(2)*I assert root(-2, 1) == -2 assert root(x, 2) == sqrt(x) assert root(x, 1) == x assert root(x, 3) == x**Rational(1, 3) assert root(x, 3) == cbrt(x) assert root(x, -5) == x**Rational(-1, 5) assert root(x, n) == x**(1/n) assert root(x, -n) == x**(-1/n) assert root(x, n, k) == (-1)**(2*k/n)*x**(1/n) def test_real_root(): assert real_root(-8, 3) == -2 assert real_root(-16, 4) == root(-16, 4) r = root(-7, 4) assert real_root(r) == r r1 = root(-1, 3) r2 = r1**2 r3 = root(-1, 4) assert real_root(r1 + r2 + r3) == -1 + r2 + r3 assert real_root(root(-2, 3)) == -root(2, 3) assert real_root(-8., 3) == -2 x = Symbol('x') n = Symbol('n') g = real_root(x, n) assert g.subs(dict(x=-8, n=3)) == -2 assert g.subs(dict(x=8, n=3)) == 2 # give principle root if there is no real root -- if this is not desired # then maybe a Root class is needed to raise an error instead assert g.subs(dict(x=I, n=3)) == cbrt(I) assert g.subs(dict(x=-8, n=2)) == sqrt(-8) assert g.subs(dict(x=I, n=2)) == sqrt(I) def test_issue_11463(): numpy = import_module('numpy') if not numpy: skip("numpy not installed.") x = Symbol('x') f = lambdify(x, real_root((log(x/(x-2))), 3), 'numpy') # numpy.select evaluates all options before considering conditions, # so it raises a warning about root of negative number which does # not affect the outcome. This warning is suppressed here with ignore_warnings(RuntimeWarning): assert f(numpy.array(-1)) < -1 def test_rewrite_MaxMin_as_Heaviside(): from sympy.abc import x assert Max(0, x).rewrite(Heaviside) == x*Heaviside(x) assert Max(3, x).rewrite(Heaviside) == x*Heaviside(x - 3) + \ 3*Heaviside(-x + 3) assert Max(0, x+2, 2*x).rewrite(Heaviside) == \ 2*x*Heaviside(2*x)*Heaviside(x - 2) + \ (x + 2)*Heaviside(-x + 2)*Heaviside(x + 2) assert Min(0, x).rewrite(Heaviside) == x*Heaviside(-x) assert Min(3, x).rewrite(Heaviside) == x*Heaviside(-x + 3) + \ 3*Heaviside(x - 3) assert Min(x, -x, -2).rewrite(Heaviside) == \ x*Heaviside(-2*x)*Heaviside(-x - 2) - \ x*Heaviside(2*x)*Heaviside(x - 2) \ - 2*Heaviside(-x + 2)*Heaviside(x + 2) def test_rewrite_MaxMin_as_Piecewise(): from sympy.core.symbol import symbols from sympy.functions.elementary.piecewise import Piecewise x, y, z, a, b = symbols('x y z a b', real=True) vx, vy, va = symbols('vx vy va') assert Max(a, b).rewrite(Piecewise) == Piecewise((a, a >= b), (b, True)) assert Max(x, y, z).rewrite(Piecewise) == Piecewise((x, (x >= y) & (x >= z)), (y, y >= z), (z, True)) assert Max(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a >= b) & (a >= x) & (a >= y)), (b, (b >= x) & (b >= y)), (x, x >= y), (y, True)) assert Min(a, b).rewrite(Piecewise) == Piecewise((a, a <= b), (b, True)) assert Min(x, y, z).rewrite(Piecewise) == Piecewise((x, (x <= y) & (x <= z)), (y, y <= z), (z, True)) assert Min(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a <= b) & (a <= x) & (a <= y)), (b, (b <= x) & (b <= y)), (x, x <= y), (y, True)) # Piecewise rewriting of Min/Max does also takes place for not explicitly real arguments assert Max(vx, vy).rewrite(Piecewise) == Piecewise((vx, vx >= vy), (vy, True)) assert Min(va, vx, vy).rewrite(Piecewise) == Piecewise((va, (va <= vx) & (va <= vy)), (vx, vx <= vy), (vy, True)) def test_issue_11099(): from sympy.abc import x, y # some fixed value tests fixed_test_data = {x: -2, y: 3} assert Min(x, y).evalf(subs=fixed_test_data) == \ Min(x, y).subs(fixed_test_data).evalf() assert Max(x, y).evalf(subs=fixed_test_data) == \ Max(x, y).subs(fixed_test_data).evalf() # randomly generate some test data from random import randint for i in range(20): random_test_data = {x: randint(-100, 100), y: randint(-100, 100)} assert Min(x, y).evalf(subs=random_test_data) == \ Min(x, y).subs(random_test_data).evalf() assert Max(x, y).evalf(subs=random_test_data) == \ Max(x, y).subs(random_test_data).evalf() def test_issue_12638(): from sympy.abc import a, b, c assert Min(a, b, c, Max(a, b)) == Min(a, b, c) assert Min(a, b, Max(a, b, c)) == Min(a, b) assert Min(a, b, Max(a, c)) == Min(a, b) def test_issue_21399(): from sympy.abc import a, b, c assert Max(Min(a, b), Min(a, b, c)) == Min(a, b) def test_instantiation_evaluation(): from sympy.abc import v, w, x, y, z assert Min(1, Max(2, x)) == 1 assert Max(3, Min(2, x)) == 3 assert Min(Max(x, y), Max(x, z)) == Max(x, Min(y, z)) assert set(Min(Max(w, x), Max(y, z)).args) == { Max(w, x), Max(y, z)} assert Min(Max(x, y), Max(x, z), w) == Min( w, Max(x, Min(y, z))) A, B = Min, Max for i in range(2): assert A(x, B(x, y)) == x assert A(x, B(y, A(x, w, z))) == A(x, B(y, A(w, z))) A, B = B, A assert Min(w, Max(x, y), Max(v, x, z)) == Min( w, Max(x, Min(y, Max(v, z)))) def test_rewrite_as_Abs(): from itertools import permutations from sympy.functions.elementary.complexes import Abs from sympy.abc import x, y, z, w def test(e): free = e.free_symbols a = e.rewrite(Abs) assert not a.has(Min, Max) for i in permutations(range(len(free))): reps = dict(zip(free, i)) assert a.xreplace(reps) == e.xreplace(reps) test(Min(x, y)) test(Max(x, y)) test(Min(x, y, z)) test(Min(Max(w, x), Max(y, z))) def test_issue_14000(): assert isinstance(sqrt(4, evaluate=False), Pow) == True assert isinstance(cbrt(3.5, evaluate=False), Pow) == True assert isinstance(root(16, 4, evaluate=False), Pow) == True assert sqrt(4, evaluate=False) == Pow(4, S.Half, evaluate=False) assert cbrt(3.5, evaluate=False) == Pow(3.5, Rational(1, 3), evaluate=False) assert root(4, 2, evaluate=False) == Pow(4, S.Half, evaluate=False) assert root(16, 4, 2, evaluate=False).has(Pow) == True assert real_root(-8, 3, evaluate=False).has(Pow) == True def test_issue_6899(): from sympy.core.function import Lambda x = Symbol('x') eqn = Lambda(x, x) assert eqn.func(*eqn.args) == eqn def test_Rem(): from sympy.abc import x, y assert Rem(5, 3) == 2 assert Rem(-5, 3) == -2 assert Rem(5, -3) == 2 assert Rem(-5, -3) == -2 assert Rem(x**3, y) == Rem(x**3, y) assert Rem(Rem(-5, 3) + 3, 3) == 1
dd209f706cd7c6522f0d4ecf1c7180703baa85aa93ae3564f41979a6a1b876b0
from sympy.calculus.util import AccumBounds from sympy.core.function import (expand_mul, expand_trig) from sympy.core.numbers import (E, I, Integer, Rational, nan, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (im, re) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (acosh, acoth, acsch, asech, asinh, atanh, cosh, coth, csch, sech, sinh, tanh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, asin, cos, cot, sec, sin, tan) from sympy.series.order import O from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises def test_sinh(): x, y = symbols('x,y') k = Symbol('k', integer=True) assert sinh(nan) is nan assert sinh(zoo) is nan assert sinh(oo) is oo assert sinh(-oo) is -oo assert sinh(0) == 0 assert unchanged(sinh, 1) assert sinh(-1) == -sinh(1) assert unchanged(sinh, x) assert sinh(-x) == -sinh(x) assert unchanged(sinh, pi) assert sinh(-pi) == -sinh(pi) assert unchanged(sinh, 2**1024 * E) assert sinh(-2**1024 * E) == -sinh(2**1024 * E) assert sinh(pi*I) == 0 assert sinh(-pi*I) == 0 assert sinh(2*pi*I) == 0 assert sinh(-2*pi*I) == 0 assert sinh(-3*10**73*pi*I) == 0 assert sinh(7*10**103*pi*I) == 0 assert sinh(pi*I/2) == I assert sinh(-pi*I/2) == -I assert sinh(pi*I*Rational(5, 2)) == I assert sinh(pi*I*Rational(7, 2)) == -I assert sinh(pi*I/3) == S.Half*sqrt(3)*I assert sinh(pi*I*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)*I assert sinh(pi*I/4) == S.Half*sqrt(2)*I assert sinh(-pi*I/4) == Rational(-1, 2)*sqrt(2)*I assert sinh(pi*I*Rational(17, 4)) == S.Half*sqrt(2)*I assert sinh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)*I assert sinh(pi*I/6) == S.Half*I assert sinh(-pi*I/6) == Rational(-1, 2)*I assert sinh(pi*I*Rational(7, 6)) == Rational(-1, 2)*I assert sinh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*I assert sinh(pi*I/105) == sin(pi/105)*I assert sinh(-pi*I/105) == -sin(pi/105)*I assert unchanged(sinh, 2 + 3*I) assert sinh(x*I) == sin(x)*I assert sinh(k*pi*I) == 0 assert sinh(17*k*pi*I) == 0 assert sinh(k*pi*I/2) == sin(k*pi/2)*I assert sinh(x).as_real_imag(deep=False) == (cos(im(x))*sinh(re(x)), sin(im(x))*cosh(re(x))) x = Symbol('x', extended_real=True) assert sinh(x).as_real_imag(deep=False) == (sinh(x), 0) x = Symbol('x', real=True) assert sinh(I*x).is_finite is True assert sinh(x).is_real is True assert sinh(I).is_real is False p = Symbol('p', positive=True) assert sinh(p).is_zero is False assert sinh(0, evaluate=False).is_zero is True assert sinh(2*pi*I, evaluate=False).is_zero is True def test_sinh_series(): x = Symbol('x') assert sinh(x).series(x, 0, 10) == \ x + x**3/6 + x**5/120 + x**7/5040 + x**9/362880 + O(x**10) def test_sinh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: sinh(x).fdiff(2)) def test_cosh(): x, y = symbols('x,y') k = Symbol('k', integer=True) assert cosh(nan) is nan assert cosh(zoo) is nan assert cosh(oo) is oo assert cosh(-oo) is oo assert cosh(0) == 1 assert unchanged(cosh, 1) assert cosh(-1) == cosh(1) assert unchanged(cosh, x) assert cosh(-x) == cosh(x) assert cosh(pi*I) == cos(pi) assert cosh(-pi*I) == cos(pi) assert unchanged(cosh, 2**1024 * E) assert cosh(-2**1024 * E) == cosh(2**1024 * E) assert cosh(pi*I/2) == 0 assert cosh(-pi*I/2) == 0 assert cosh((-3*10**73 + 1)*pi*I/2) == 0 assert cosh((7*10**103 + 1)*pi*I/2) == 0 assert cosh(pi*I) == -1 assert cosh(-pi*I) == -1 assert cosh(5*pi*I) == -1 assert cosh(8*pi*I) == 1 assert cosh(pi*I/3) == S.Half assert cosh(pi*I*Rational(-2, 3)) == Rational(-1, 2) assert cosh(pi*I/4) == S.Half*sqrt(2) assert cosh(-pi*I/4) == S.Half*sqrt(2) assert cosh(pi*I*Rational(11, 4)) == Rational(-1, 2)*sqrt(2) assert cosh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2) assert cosh(pi*I/6) == S.Half*sqrt(3) assert cosh(-pi*I/6) == S.Half*sqrt(3) assert cosh(pi*I*Rational(7, 6)) == Rational(-1, 2)*sqrt(3) assert cosh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3) assert cosh(pi*I/105) == cos(pi/105) assert cosh(-pi*I/105) == cos(pi/105) assert unchanged(cosh, 2 + 3*I) assert cosh(x*I) == cos(x) assert cosh(k*pi*I) == cos(k*pi) assert cosh(17*k*pi*I) == cos(17*k*pi) assert unchanged(cosh, k*pi) assert cosh(x).as_real_imag(deep=False) == (cos(im(x))*cosh(re(x)), sin(im(x))*sinh(re(x))) x = Symbol('x', extended_real=True) assert cosh(x).as_real_imag(deep=False) == (cosh(x), 0) x = Symbol('x', real=True) assert cosh(I*x).is_finite is True assert cosh(I*x).is_real is True assert cosh(I*2 + 1).is_real is False assert cosh(5*I*S.Pi/2, evaluate=False).is_zero is True assert cosh(x).is_zero is False def test_cosh_series(): x = Symbol('x') assert cosh(x).series(x, 0, 10) == \ 1 + x**2/2 + x**4/24 + x**6/720 + x**8/40320 + O(x**10) def test_cosh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: cosh(x).fdiff(2)) def test_tanh(): x, y = symbols('x,y') k = Symbol('k', integer=True) assert tanh(nan) is nan assert tanh(zoo) is nan assert tanh(oo) == 1 assert tanh(-oo) == -1 assert tanh(0) == 0 assert unchanged(tanh, 1) assert tanh(-1) == -tanh(1) assert unchanged(tanh, x) assert tanh(-x) == -tanh(x) assert unchanged(tanh, pi) assert tanh(-pi) == -tanh(pi) assert unchanged(tanh, 2**1024 * E) assert tanh(-2**1024 * E) == -tanh(2**1024 * E) assert tanh(pi*I) == 0 assert tanh(-pi*I) == 0 assert tanh(2*pi*I) == 0 assert tanh(-2*pi*I) == 0 assert tanh(-3*10**73*pi*I) == 0 assert tanh(7*10**103*pi*I) == 0 assert tanh(pi*I/2) is zoo assert tanh(-pi*I/2) is zoo assert tanh(pi*I*Rational(5, 2)) is zoo assert tanh(pi*I*Rational(7, 2)) is zoo assert tanh(pi*I/3) == sqrt(3)*I assert tanh(pi*I*Rational(-2, 3)) == sqrt(3)*I assert tanh(pi*I/4) == I assert tanh(-pi*I/4) == -I assert tanh(pi*I*Rational(17, 4)) == I assert tanh(pi*I*Rational(-3, 4)) == I assert tanh(pi*I/6) == I/sqrt(3) assert tanh(-pi*I/6) == -I/sqrt(3) assert tanh(pi*I*Rational(7, 6)) == I/sqrt(3) assert tanh(pi*I*Rational(-5, 6)) == I/sqrt(3) assert tanh(pi*I/105) == tan(pi/105)*I assert tanh(-pi*I/105) == -tan(pi/105)*I assert unchanged(tanh, 2 + 3*I) assert tanh(x*I) == tan(x)*I assert tanh(k*pi*I) == 0 assert tanh(17*k*pi*I) == 0 assert tanh(k*pi*I/2) == tan(k*pi/2)*I assert tanh(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(cos(im(x))**2 + sinh(re(x))**2), sin(im(x))*cos(im(x))/(cos(im(x))**2 + sinh(re(x))**2)) x = Symbol('x', extended_real=True) assert tanh(x).as_real_imag(deep=False) == (tanh(x), 0) assert tanh(I*pi/3 + 1).is_real is False assert tanh(x).is_real is True assert tanh(I*pi*x/2).is_real is None def test_tanh_series(): x = Symbol('x') assert tanh(x).series(x, 0, 10) == \ x - x**3/3 + 2*x**5/15 - 17*x**7/315 + 62*x**9/2835 + O(x**10) def test_tanh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: tanh(x).fdiff(2)) def test_coth(): x, y = symbols('x,y') k = Symbol('k', integer=True) assert coth(nan) is nan assert coth(zoo) is nan assert coth(oo) == 1 assert coth(-oo) == -1 assert coth(0) is zoo assert unchanged(coth, 1) assert coth(-1) == -coth(1) assert unchanged(coth, x) assert coth(-x) == -coth(x) assert coth(pi*I) == -I*cot(pi) assert coth(-pi*I) == cot(pi)*I assert unchanged(coth, 2**1024 * E) assert coth(-2**1024 * E) == -coth(2**1024 * E) assert coth(pi*I) == -I*cot(pi) assert coth(-pi*I) == I*cot(pi) assert coth(2*pi*I) == -I*cot(2*pi) assert coth(-2*pi*I) == I*cot(2*pi) assert coth(-3*10**73*pi*I) == I*cot(3*10**73*pi) assert coth(7*10**103*pi*I) == -I*cot(7*10**103*pi) assert coth(pi*I/2) == 0 assert coth(-pi*I/2) == 0 assert coth(pi*I*Rational(5, 2)) == 0 assert coth(pi*I*Rational(7, 2)) == 0 assert coth(pi*I/3) == -I/sqrt(3) assert coth(pi*I*Rational(-2, 3)) == -I/sqrt(3) assert coth(pi*I/4) == -I assert coth(-pi*I/4) == I assert coth(pi*I*Rational(17, 4)) == -I assert coth(pi*I*Rational(-3, 4)) == -I assert coth(pi*I/6) == -sqrt(3)*I assert coth(-pi*I/6) == sqrt(3)*I assert coth(pi*I*Rational(7, 6)) == -sqrt(3)*I assert coth(pi*I*Rational(-5, 6)) == -sqrt(3)*I assert coth(pi*I/105) == -cot(pi/105)*I assert coth(-pi*I/105) == cot(pi/105)*I assert unchanged(coth, 2 + 3*I) assert coth(x*I) == -cot(x)*I assert coth(k*pi*I) == -cot(k*pi)*I assert coth(17*k*pi*I) == -cot(17*k*pi)*I assert coth(k*pi*I) == -cot(k*pi)*I assert coth(log(tan(2))) == coth(log(-tan(2))) assert coth(1 + I*pi/2) == tanh(1) assert coth(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(sin(im(x))**2 + sinh(re(x))**2), -sin(im(x))*cos(im(x))/(sin(im(x))**2 + sinh(re(x))**2)) x = Symbol('x', extended_real=True) assert coth(x).as_real_imag(deep=False) == (coth(x), 0) assert expand_trig(coth(2*x)) == (coth(x)**2 + 1)/(2*coth(x)) assert expand_trig(coth(3*x)) == (coth(x)**3 + 3*coth(x))/(1 + 3*coth(x)**2) assert expand_trig(coth(x + y)) == (1 + coth(x)*coth(y))/(coth(x) + coth(y)) def test_coth_series(): x = Symbol('x') assert coth(x).series(x, 0, 8) == \ 1/x + x/3 - x**3/45 + 2*x**5/945 - x**7/4725 + O(x**8) def test_coth_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: coth(x).fdiff(2)) def test_csch(): x, y = symbols('x,y') k = Symbol('k', integer=True) n = Symbol('n', positive=True) assert csch(nan) is nan assert csch(zoo) is nan assert csch(oo) == 0 assert csch(-oo) == 0 assert csch(0) is zoo assert csch(-1) == -csch(1) assert csch(-x) == -csch(x) assert csch(-pi) == -csch(pi) assert csch(-2**1024 * E) == -csch(2**1024 * E) assert csch(pi*I) is zoo assert csch(-pi*I) is zoo assert csch(2*pi*I) is zoo assert csch(-2*pi*I) is zoo assert csch(-3*10**73*pi*I) is zoo assert csch(7*10**103*pi*I) is zoo assert csch(pi*I/2) == -I assert csch(-pi*I/2) == I assert csch(pi*I*Rational(5, 2)) == -I assert csch(pi*I*Rational(7, 2)) == I assert csch(pi*I/3) == -2/sqrt(3)*I assert csch(pi*I*Rational(-2, 3)) == 2/sqrt(3)*I assert csch(pi*I/4) == -sqrt(2)*I assert csch(-pi*I/4) == sqrt(2)*I assert csch(pi*I*Rational(7, 4)) == sqrt(2)*I assert csch(pi*I*Rational(-3, 4)) == sqrt(2)*I assert csch(pi*I/6) == -2*I assert csch(-pi*I/6) == 2*I assert csch(pi*I*Rational(7, 6)) == 2*I assert csch(pi*I*Rational(-7, 6)) == -2*I assert csch(pi*I*Rational(-5, 6)) == 2*I assert csch(pi*I/105) == -1/sin(pi/105)*I assert csch(-pi*I/105) == 1/sin(pi/105)*I assert csch(x*I) == -1/sin(x)*I assert csch(k*pi*I) is zoo assert csch(17*k*pi*I) is zoo assert csch(k*pi*I/2) == -1/sin(k*pi/2)*I assert csch(n).is_real is True assert expand_trig(csch(x + y)) == 1/(sinh(x)*cosh(y) + cosh(x)*sinh(y)) def test_csch_series(): x = Symbol('x') assert csch(x).series(x, 0, 10) == \ 1/ x - x/6 + 7*x**3/360 - 31*x**5/15120 + 127*x**7/604800 \ - 73*x**9/3421440 + O(x**10) def test_csch_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: csch(x).fdiff(2)) def test_sech(): x, y = symbols('x, y') k = Symbol('k', integer=True) n = Symbol('n', positive=True) assert sech(nan) is nan assert sech(zoo) is nan assert sech(oo) == 0 assert sech(-oo) == 0 assert sech(0) == 1 assert sech(-1) == sech(1) assert sech(-x) == sech(x) assert sech(pi*I) == sec(pi) assert sech(-pi*I) == sec(pi) assert sech(-2**1024 * E) == sech(2**1024 * E) assert sech(pi*I/2) is zoo assert sech(-pi*I/2) is zoo assert sech((-3*10**73 + 1)*pi*I/2) is zoo assert sech((7*10**103 + 1)*pi*I/2) is zoo assert sech(pi*I) == -1 assert sech(-pi*I) == -1 assert sech(5*pi*I) == -1 assert sech(8*pi*I) == 1 assert sech(pi*I/3) == 2 assert sech(pi*I*Rational(-2, 3)) == -2 assert sech(pi*I/4) == sqrt(2) assert sech(-pi*I/4) == sqrt(2) assert sech(pi*I*Rational(5, 4)) == -sqrt(2) assert sech(pi*I*Rational(-5, 4)) == -sqrt(2) assert sech(pi*I/6) == 2/sqrt(3) assert sech(-pi*I/6) == 2/sqrt(3) assert sech(pi*I*Rational(7, 6)) == -2/sqrt(3) assert sech(pi*I*Rational(-5, 6)) == -2/sqrt(3) assert sech(pi*I/105) == 1/cos(pi/105) assert sech(-pi*I/105) == 1/cos(pi/105) assert sech(x*I) == 1/cos(x) assert sech(k*pi*I) == 1/cos(k*pi) assert sech(17*k*pi*I) == 1/cos(17*k*pi) assert sech(n).is_real is True assert expand_trig(sech(x + y)) == 1/(cosh(x)*cosh(y) + sinh(x)*sinh(y)) def test_sech_series(): x = Symbol('x') assert sech(x).series(x, 0, 10) == \ 1 - x**2/2 + 5*x**4/24 - 61*x**6/720 + 277*x**8/8064 + O(x**10) def test_sech_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: sech(x).fdiff(2)) def test_asinh(): x, y = symbols('x,y') assert unchanged(asinh, x) assert asinh(-x) == -asinh(x) #at specific points assert asinh(nan) is nan assert asinh( 0) == 0 assert asinh(+1) == log(sqrt(2) + 1) assert asinh(-1) == log(sqrt(2) - 1) assert asinh(I) == pi*I/2 assert asinh(-I) == -pi*I/2 assert asinh(I/2) == pi*I/6 assert asinh(-I/2) == -pi*I/6 # at infinites assert asinh(oo) is oo assert asinh(-oo) is -oo assert asinh(I*oo) is oo assert asinh(-I *oo) is -oo assert asinh(zoo) is zoo #properties assert asinh(I *(sqrt(3) - 1)/(2**Rational(3, 2))) == pi*I/12 assert asinh(-I *(sqrt(3) - 1)/(2**Rational(3, 2))) == -pi*I/12 assert asinh(I*(sqrt(5) - 1)/4) == pi*I/10 assert asinh(-I*(sqrt(5) - 1)/4) == -pi*I/10 assert asinh(I*(sqrt(5) + 1)/4) == pi*I*Rational(3, 10) assert asinh(-I*(sqrt(5) + 1)/4) == pi*I*Rational(-3, 10) # Symmetry assert asinh(Rational(-1, 2)) == -asinh(S.Half) # inverse composition assert unchanged(asinh, sinh(Symbol('v1'))) assert asinh(sinh(0, evaluate=False)) == 0 assert asinh(sinh(-3, evaluate=False)) == -3 assert asinh(sinh(2, evaluate=False)) == 2 assert asinh(sinh(I, evaluate=False)) == I assert asinh(sinh(-I, evaluate=False)) == -I assert asinh(sinh(5*I, evaluate=False)) == -2*I*pi + 5*I assert asinh(sinh(15 + 11*I)) == 15 - 4*I*pi + 11*I assert asinh(sinh(-73 + 97*I)) == 73 - 97*I + 31*I*pi assert asinh(sinh(-7 - 23*I)) == 7 - 7*I*pi + 23*I assert asinh(sinh(13 - 3*I)) == -13 - I*pi + 3*I p = Symbol('p', positive=True) assert asinh(p).is_zero is False assert asinh(sinh(0, evaluate=False), evaluate=False).is_zero is True def test_asinh_rewrite(): x = Symbol('x') assert asinh(x).rewrite(log) == log(x + sqrt(x**2 + 1)) def test_asinh_series(): x = Symbol('x') assert asinh(x).series(x, 0, 8) == \ x - x**3/6 + 3*x**5/40 - 5*x**7/112 + O(x**8) t5 = asinh(x).taylor_term(5, x) assert t5 == 3*x**5/40 assert asinh(x).taylor_term(7, x, t5, 0) == -5*x**7/112 def test_asinh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: asinh(x).fdiff(2)) def test_acosh(): x = Symbol('x') assert unchanged(acosh, -x) #at specific points assert acosh(1) == 0 assert acosh(-1) == pi*I assert acosh(0) == I*pi/2 assert acosh(S.Half) == I*pi/3 assert acosh(Rational(-1, 2)) == pi*I*Rational(2, 3) assert acosh(nan) is nan # at infinites assert acosh(oo) is oo assert acosh(-oo) is oo assert acosh(I*oo) == oo + I*pi/2 assert acosh(-I*oo) == oo - I*pi/2 assert acosh(zoo) is zoo assert acosh(I) == log(I*(1 + sqrt(2))) assert acosh(-I) == log(-I*(1 + sqrt(2))) assert acosh((sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(5, 12) assert acosh(-(sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(7, 12) assert acosh(sqrt(2)/2) == I*pi/4 assert acosh(-sqrt(2)/2) == I*pi*Rational(3, 4) assert acosh(sqrt(3)/2) == I*pi/6 assert acosh(-sqrt(3)/2) == I*pi*Rational(5, 6) assert acosh(sqrt(2 + sqrt(2))/2) == I*pi/8 assert acosh(-sqrt(2 + sqrt(2))/2) == I*pi*Rational(7, 8) assert acosh(sqrt(2 - sqrt(2))/2) == I*pi*Rational(3, 8) assert acosh(-sqrt(2 - sqrt(2))/2) == I*pi*Rational(5, 8) assert acosh((1 + sqrt(3))/(2*sqrt(2))) == I*pi/12 assert acosh(-(1 + sqrt(3))/(2*sqrt(2))) == I*pi*Rational(11, 12) assert acosh((sqrt(5) + 1)/4) == I*pi/5 assert acosh(-(sqrt(5) + 1)/4) == I*pi*Rational(4, 5) assert str(acosh(5*I).n(6)) == '2.31244 + 1.5708*I' assert str(acosh(-5*I).n(6)) == '2.31244 - 1.5708*I' # inverse composition assert unchanged(acosh, Symbol('v1')) assert acosh(cosh(-3, evaluate=False)) == 3 assert acosh(cosh(3, evaluate=False)) == 3 assert acosh(cosh(0, evaluate=False)) == 0 assert acosh(cosh(I, evaluate=False)) == I assert acosh(cosh(-I, evaluate=False)) == I assert acosh(cosh(7*I, evaluate=False)) == -2*I*pi + 7*I assert acosh(cosh(1 + I)) == 1 + I assert acosh(cosh(3 - 3*I)) == 3 - 3*I assert acosh(cosh(-3 + 2*I)) == 3 - 2*I assert acosh(cosh(-5 - 17*I)) == 5 - 6*I*pi + 17*I assert acosh(cosh(-21 + 11*I)) == 21 - 11*I + 4*I*pi assert acosh(cosh(cosh(1) + I)) == cosh(1) + I assert acosh(1, evaluate=False).is_zero is True def test_acosh_rewrite(): x = Symbol('x') assert acosh(x).rewrite(log) == log(x + sqrt(x - 1)*sqrt(x + 1)) def test_acosh_series(): x = Symbol('x') assert acosh(x).series(x, 0, 8) == \ -I*x + pi*I/2 - I*x**3/6 - 3*I*x**5/40 - 5*I*x**7/112 + O(x**8) t5 = acosh(x).taylor_term(5, x) assert t5 == - 3*I*x**5/40 assert acosh(x).taylor_term(7, x, t5, 0) == - 5*I*x**7/112 def test_acosh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: acosh(x).fdiff(2)) def test_asech(): x = Symbol('x') assert unchanged(asech, -x) # values at fixed points assert asech(1) == 0 assert asech(-1) == pi*I assert asech(0) is oo assert asech(2) == I*pi/3 assert asech(-2) == 2*I*pi / 3 assert asech(nan) is nan # at infinites assert asech(oo) == I*pi/2 assert asech(-oo) == I*pi/2 assert asech(zoo) == I*AccumBounds(-pi/2, pi/2) assert asech(I) == log(1 + sqrt(2)) - I*pi/2 assert asech(-I) == log(1 + sqrt(2)) + I*pi/2 assert asech(sqrt(2) - sqrt(6)) == 11*I*pi / 12 assert asech(sqrt(2 - 2/sqrt(5))) == I*pi / 10 assert asech(-sqrt(2 - 2/sqrt(5))) == 9*I*pi / 10 assert asech(2 / sqrt(2 + sqrt(2))) == I*pi / 8 assert asech(-2 / sqrt(2 + sqrt(2))) == 7*I*pi / 8 assert asech(sqrt(5) - 1) == I*pi / 5 assert asech(1 - sqrt(5)) == 4*I*pi / 5 assert asech(-sqrt(2*(2 + sqrt(2)))) == 5*I*pi / 8 # properties # asech(x) == acosh(1/x) assert asech(sqrt(2)) == acosh(1/sqrt(2)) assert asech(2/sqrt(3)) == acosh(sqrt(3)/2) assert asech(2/sqrt(2 + sqrt(2))) == acosh(sqrt(2 + sqrt(2))/2) assert asech(2) == acosh(S.Half) # asech(x) == I*acos(1/x) # (Note: the exact formula is asech(x) == +/- I*acos(1/x)) assert asech(-sqrt(2)) == I*acos(-1/sqrt(2)) assert asech(-2/sqrt(3)) == I*acos(-sqrt(3)/2) assert asech(-S(2)) == I*acos(Rational(-1, 2)) assert asech(-2/sqrt(2)) == I*acos(-sqrt(2)/2) # sech(asech(x)) / x == 1 assert expand_mul(sech(asech(sqrt(6) - sqrt(2))) / (sqrt(6) - sqrt(2))) == 1 assert expand_mul(sech(asech(sqrt(6) + sqrt(2))) / (sqrt(6) + sqrt(2))) == 1 assert (sech(asech(sqrt(2 + 2/sqrt(5)))) / (sqrt(2 + 2/sqrt(5)))).simplify() == 1 assert (sech(asech(-sqrt(2 + 2/sqrt(5)))) / (-sqrt(2 + 2/sqrt(5)))).simplify() == 1 assert (sech(asech(sqrt(2*(2 + sqrt(2))))) / (sqrt(2*(2 + sqrt(2))))).simplify() == 1 assert expand_mul(sech(asech(1 + sqrt(5))) / (1 + sqrt(5))) == 1 assert expand_mul(sech(asech(-1 - sqrt(5))) / (-1 - sqrt(5))) == 1 assert expand_mul(sech(asech(-sqrt(6) - sqrt(2))) / (-sqrt(6) - sqrt(2))) == 1 # numerical evaluation assert str(asech(5*I).n(6)) == '0.19869 - 1.5708*I' assert str(asech(-5*I).n(6)) == '0.19869 + 1.5708*I' def test_asech_series(): x = Symbol('x') t6 = asech(x).expansion_term(6, x) assert t6 == -5*x**6/96 assert asech(x).expansion_term(8, x, t6, 0) == -35*x**8/1024 def test_asech_rewrite(): x = Symbol('x') assert asech(x).rewrite(log) == log(1/x + sqrt(1/x - 1) * sqrt(1/x + 1)) def test_asech_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: asech(x).fdiff(2)) def test_acsch(): x = Symbol('x') assert unchanged(acsch, x) assert acsch(-x) == -acsch(x) # values at fixed points assert acsch(1) == log(1 + sqrt(2)) assert acsch(-1) == - log(1 + sqrt(2)) assert acsch(0) is zoo assert acsch(2) == log((1+sqrt(5))/2) assert acsch(-2) == - log((1+sqrt(5))/2) assert acsch(I) == - I*pi/2 assert acsch(-I) == I*pi/2 assert acsch(-I*(sqrt(6) + sqrt(2))) == I*pi / 12 assert acsch(I*(sqrt(2) + sqrt(6))) == -I*pi / 12 assert acsch(-I*(1 + sqrt(5))) == I*pi / 10 assert acsch(I*(1 + sqrt(5))) == -I*pi / 10 assert acsch(-I*2 / sqrt(2 - sqrt(2))) == I*pi / 8 assert acsch(I*2 / sqrt(2 - sqrt(2))) == -I*pi / 8 assert acsch(-I*2) == I*pi / 6 assert acsch(I*2) == -I*pi / 6 assert acsch(-I*sqrt(2 + 2/sqrt(5))) == I*pi / 5 assert acsch(I*sqrt(2 + 2/sqrt(5))) == -I*pi / 5 assert acsch(-I*sqrt(2)) == I*pi / 4 assert acsch(I*sqrt(2)) == -I*pi / 4 assert acsch(-I*(sqrt(5)-1)) == 3*I*pi / 10 assert acsch(I*(sqrt(5)-1)) == -3*I*pi / 10 assert acsch(-I*2 / sqrt(3)) == I*pi / 3 assert acsch(I*2 / sqrt(3)) == -I*pi / 3 assert acsch(-I*2 / sqrt(2 + sqrt(2))) == 3*I*pi / 8 assert acsch(I*2 / sqrt(2 + sqrt(2))) == -3*I*pi / 8 assert acsch(-I*sqrt(2 - 2/sqrt(5))) == 2*I*pi / 5 assert acsch(I*sqrt(2 - 2/sqrt(5))) == -2*I*pi / 5 assert acsch(-I*(sqrt(6) - sqrt(2))) == 5*I*pi / 12 assert acsch(I*(sqrt(6) - sqrt(2))) == -5*I*pi / 12 assert acsch(nan) is nan # properties # acsch(x) == asinh(1/x) assert acsch(-I*sqrt(2)) == asinh(I/sqrt(2)) assert acsch(-I*2 / sqrt(3)) == asinh(I*sqrt(3) / 2) # acsch(x) == -I*asin(I/x) assert acsch(-I*sqrt(2)) == -I*asin(-1/sqrt(2)) assert acsch(-I*2 / sqrt(3)) == -I*asin(-sqrt(3)/2) # csch(acsch(x)) / x == 1 assert expand_mul(csch(acsch(-I*(sqrt(6) + sqrt(2)))) / (-I*(sqrt(6) + sqrt(2)))) == 1 assert expand_mul(csch(acsch(I*(1 + sqrt(5)))) / (I*(1 + sqrt(5)))) == 1 assert (csch(acsch(I*sqrt(2 - 2/sqrt(5)))) / (I*sqrt(2 - 2/sqrt(5)))).simplify() == 1 assert (csch(acsch(-I*sqrt(2 - 2/sqrt(5)))) / (-I*sqrt(2 - 2/sqrt(5)))).simplify() == 1 # numerical evaluation assert str(acsch(5*I+1).n(6)) == '0.0391819 - 0.193363*I' assert str(acsch(-5*I+1).n(6)) == '0.0391819 + 0.193363*I' def test_acsch_infinities(): assert acsch(oo) == 0 assert acsch(-oo) == 0 assert acsch(zoo) == 0 def test_acsch_rewrite(): x = Symbol('x') assert acsch(x).rewrite(log) == log(1/x + sqrt(1/x**2 + 1)) def test_acsch_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: acsch(x).fdiff(2)) def test_atanh(): x = Symbol('x') #at specific points assert atanh(0) == 0 assert atanh(I) == I*pi/4 assert atanh(-I) == -I*pi/4 assert atanh(1) is oo assert atanh(-1) is -oo assert atanh(nan) is nan # at infinites assert atanh(oo) == -I*pi/2 assert atanh(-oo) == I*pi/2 assert atanh(I*oo) == I*pi/2 assert atanh(-I*oo) == -I*pi/2 assert atanh(zoo) == I*AccumBounds(-pi/2, pi/2) #properties assert atanh(-x) == -atanh(x) assert atanh(I/sqrt(3)) == I*pi/6 assert atanh(-I/sqrt(3)) == -I*pi/6 assert atanh(I*sqrt(3)) == I*pi/3 assert atanh(-I*sqrt(3)) == -I*pi/3 assert atanh(I*(1 + sqrt(2))) == pi*I*Rational(3, 8) assert atanh(I*(sqrt(2) - 1)) == pi*I/8 assert atanh(I*(1 - sqrt(2))) == -pi*I/8 assert atanh(-I*(1 + sqrt(2))) == pi*I*Rational(-3, 8) assert atanh(I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(2, 5) assert atanh(-I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(-2, 5) assert atanh(I*(2 - sqrt(3))) == pi*I/12 assert atanh(I*(sqrt(3) - 2)) == -pi*I/12 assert atanh(oo) == -I*pi/2 # Symmetry assert atanh(Rational(-1, 2)) == -atanh(S.Half) # inverse composition assert unchanged(atanh, tanh(Symbol('v1'))) assert atanh(tanh(-5, evaluate=False)) == -5 assert atanh(tanh(0, evaluate=False)) == 0 assert atanh(tanh(7, evaluate=False)) == 7 assert atanh(tanh(I, evaluate=False)) == I assert atanh(tanh(-I, evaluate=False)) == -I assert atanh(tanh(-11*I, evaluate=False)) == -11*I + 4*I*pi assert atanh(tanh(3 + I)) == 3 + I assert atanh(tanh(4 + 5*I)) == 4 - 2*I*pi + 5*I assert atanh(tanh(pi/2)) == pi/2 assert atanh(tanh(pi)) == pi assert atanh(tanh(-3 + 7*I)) == -3 - 2*I*pi + 7*I assert atanh(tanh(9 - I*Rational(2, 3))) == 9 - I*Rational(2, 3) assert atanh(tanh(-32 - 123*I)) == -32 - 123*I + 39*I*pi def test_atanh_rewrite(): x = Symbol('x') assert atanh(x).rewrite(log) == (log(1 + x) - log(1 - x)) / 2 def test_atanh_series(): x = Symbol('x') assert atanh(x).series(x, 0, 10) == \ x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10) def test_atanh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: atanh(x).fdiff(2)) def test_acoth(): x = Symbol('x') #at specific points assert acoth(0) == I*pi/2 assert acoth(I) == -I*pi/4 assert acoth(-I) == I*pi/4 assert acoth(1) is oo assert acoth(-1) is -oo assert acoth(nan) is nan # at infinites assert acoth(oo) == 0 assert acoth(-oo) == 0 assert acoth(I*oo) == 0 assert acoth(-I*oo) == 0 assert acoth(zoo) == 0 #properties assert acoth(-x) == -acoth(x) assert acoth(I/sqrt(3)) == -I*pi/3 assert acoth(-I/sqrt(3)) == I*pi/3 assert acoth(I*sqrt(3)) == -I*pi/6 assert acoth(-I*sqrt(3)) == I*pi/6 assert acoth(I*(1 + sqrt(2))) == -pi*I/8 assert acoth(-I*(sqrt(2) + 1)) == pi*I/8 assert acoth(I*(1 - sqrt(2))) == pi*I*Rational(3, 8) assert acoth(I*(sqrt(2) - 1)) == pi*I*Rational(-3, 8) assert acoth(I*sqrt(5 + 2*sqrt(5))) == -I*pi/10 assert acoth(-I*sqrt(5 + 2*sqrt(5))) == I*pi/10 assert acoth(I*(2 + sqrt(3))) == -pi*I/12 assert acoth(-I*(2 + sqrt(3))) == pi*I/12 assert acoth(I*(2 - sqrt(3))) == pi*I*Rational(-5, 12) assert acoth(I*(sqrt(3) - 2)) == pi*I*Rational(5, 12) # Symmetry assert acoth(Rational(-1, 2)) == -acoth(S.Half) def test_acoth_rewrite(): x = Symbol('x') assert acoth(x).rewrite(log) == (log(1 + 1/x) - log(1 - 1/x)) / 2 def test_acoth_series(): x = Symbol('x') assert acoth(x).series(x, 0, 10) == \ I*pi/2 + x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10) def test_acoth_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: acoth(x).fdiff(2)) def test_inverses(): x = Symbol('x') assert sinh(x).inverse() == asinh raises(AttributeError, lambda: cosh(x).inverse()) assert tanh(x).inverse() == atanh assert coth(x).inverse() == acoth assert asinh(x).inverse() == sinh assert acosh(x).inverse() == cosh assert atanh(x).inverse() == tanh assert acoth(x).inverse() == coth assert asech(x).inverse() == sech assert acsch(x).inverse() == csch def test_leading_term(): x = Symbol('x') assert cosh(x).as_leading_term(x) == 1 assert coth(x).as_leading_term(x) == 1/x assert acosh(x).as_leading_term(x) == I*pi/2 assert acoth(x).as_leading_term(x) == I*pi/2 for func in [sinh, tanh, asinh, atanh]: assert func(x).as_leading_term(x) == x for func in [sinh, cosh, tanh, coth, asinh, acosh, atanh, acoth]: for arg in (1/x, S.Half): eq = func(arg) assert eq.as_leading_term(x) == eq for func in [csch, sech]: eq = func(S.Half) assert eq.as_leading_term(x) == eq def test_complex(): a, b = symbols('a,b', real=True) z = a + b*I for func in [sinh, cosh, tanh, coth, sech, csch]: assert func(z).conjugate() == func(a - b*I) for deep in [True, False]: assert sinh(z).expand( complex=True, deep=deep) == sinh(a)*cos(b) + I*cosh(a)*sin(b) assert cosh(z).expand( complex=True, deep=deep) == cosh(a)*cos(b) + I*sinh(a)*sin(b) assert tanh(z).expand(complex=True, deep=deep) == sinh(a)*cosh( a)/(cos(b)**2 + sinh(a)**2) + I*sin(b)*cos(b)/(cos(b)**2 + sinh(a)**2) assert coth(z).expand(complex=True, deep=deep) == sinh(a)*cosh( a)/(sin(b)**2 + sinh(a)**2) - I*sin(b)*cos(b)/(sin(b)**2 + sinh(a)**2) assert csch(z).expand(complex=True, deep=deep) == cos(b) * sinh(a) / (sin(b)**2\ *cosh(a)**2 + cos(b)**2 * sinh(a)**2) - I*sin(b) * cosh(a) / (sin(b)**2\ *cosh(a)**2 + cos(b)**2 * sinh(a)**2) assert sech(z).expand(complex=True, deep=deep) == cos(b) * cosh(a) / (sin(b)**2\ *sinh(a)**2 + cos(b)**2 * cosh(a)**2) - I*sin(b) * sinh(a) / (sin(b)**2\ *sinh(a)**2 + cos(b)**2 * cosh(a)**2) def test_complex_2899(): a, b = symbols('a,b', real=True) for deep in [True, False]: for func in [sinh, cosh, tanh, coth]: assert func(a).expand(complex=True, deep=deep) == func(a) def test_simplifications(): x = Symbol('x') assert sinh(asinh(x)) == x assert sinh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1) assert sinh(atanh(x)) == x/sqrt(1 - x**2) assert sinh(acoth(x)) == 1/(sqrt(x - 1) * sqrt(x + 1)) assert cosh(asinh(x)) == sqrt(1 + x**2) assert cosh(acosh(x)) == x assert cosh(atanh(x)) == 1/sqrt(1 - x**2) assert cosh(acoth(x)) == x/(sqrt(x - 1) * sqrt(x + 1)) assert tanh(asinh(x)) == x/sqrt(1 + x**2) assert tanh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1) / x assert tanh(atanh(x)) == x assert tanh(acoth(x)) == 1/x assert coth(asinh(x)) == sqrt(1 + x**2)/x assert coth(acosh(x)) == x/(sqrt(x - 1) * sqrt(x + 1)) assert coth(atanh(x)) == 1/x assert coth(acoth(x)) == x assert csch(asinh(x)) == 1/x assert csch(acosh(x)) == 1/(sqrt(x - 1) * sqrt(x + 1)) assert csch(atanh(x)) == sqrt(1 - x**2)/x assert csch(acoth(x)) == sqrt(x - 1) * sqrt(x + 1) assert sech(asinh(x)) == 1/sqrt(1 + x**2) assert sech(acosh(x)) == 1/x assert sech(atanh(x)) == sqrt(1 - x**2) assert sech(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)/x def test_issue_4136(): assert cosh(asinh(Integer(3)/2)) == sqrt(Integer(13)/4) def test_sinh_rewrite(): x = Symbol('x') assert sinh(x).rewrite(exp) == (exp(x) - exp(-x))/2 \ == sinh(x).rewrite('tractable') assert sinh(x).rewrite(cosh) == -I*cosh(x + I*pi/2) tanh_half = tanh(S.Half*x) assert sinh(x).rewrite(tanh) == 2*tanh_half/(1 - tanh_half**2) coth_half = coth(S.Half*x) assert sinh(x).rewrite(coth) == 2*coth_half/(coth_half**2 - 1) def test_cosh_rewrite(): x = Symbol('x') assert cosh(x).rewrite(exp) == (exp(x) + exp(-x))/2 \ == cosh(x).rewrite('tractable') assert cosh(x).rewrite(sinh) == -I*sinh(x + I*pi/2) tanh_half = tanh(S.Half*x)**2 assert cosh(x).rewrite(tanh) == (1 + tanh_half)/(1 - tanh_half) coth_half = coth(S.Half*x)**2 assert cosh(x).rewrite(coth) == (coth_half + 1)/(coth_half - 1) def test_tanh_rewrite(): x = Symbol('x') assert tanh(x).rewrite(exp) == (exp(x) - exp(-x))/(exp(x) + exp(-x)) \ == tanh(x).rewrite('tractable') assert tanh(x).rewrite(sinh) == I*sinh(x)/sinh(I*pi/2 - x) assert tanh(x).rewrite(cosh) == I*cosh(I*pi/2 - x)/cosh(x) assert tanh(x).rewrite(coth) == 1/coth(x) def test_coth_rewrite(): x = Symbol('x') assert coth(x).rewrite(exp) == (exp(x) + exp(-x))/(exp(x) - exp(-x)) \ == coth(x).rewrite('tractable') assert coth(x).rewrite(sinh) == -I*sinh(I*pi/2 - x)/sinh(x) assert coth(x).rewrite(cosh) == -I*cosh(x)/cosh(I*pi/2 - x) assert coth(x).rewrite(tanh) == 1/tanh(x) def test_csch_rewrite(): x = Symbol('x') assert csch(x).rewrite(exp) == 1 / (exp(x)/2 - exp(-x)/2) \ == csch(x).rewrite('tractable') assert csch(x).rewrite(cosh) == I/cosh(x + I*pi/2) tanh_half = tanh(S.Half*x) assert csch(x).rewrite(tanh) == (1 - tanh_half**2)/(2*tanh_half) coth_half = coth(S.Half*x) assert csch(x).rewrite(coth) == (coth_half**2 - 1)/(2*coth_half) def test_sech_rewrite(): x = Symbol('x') assert sech(x).rewrite(exp) == 1 / (exp(x)/2 + exp(-x)/2) \ == sech(x).rewrite('tractable') assert sech(x).rewrite(sinh) == I/sinh(x + I*pi/2) tanh_half = tanh(S.Half*x)**2 assert sech(x).rewrite(tanh) == (1 - tanh_half)/(1 + tanh_half) coth_half = coth(S.Half*x)**2 assert sech(x).rewrite(coth) == (coth_half - 1)/(coth_half + 1) def test_derivs(): x = Symbol('x') assert coth(x).diff(x) == -sinh(x)**(-2) assert sinh(x).diff(x) == cosh(x) assert cosh(x).diff(x) == sinh(x) assert tanh(x).diff(x) == -tanh(x)**2 + 1 assert csch(x).diff(x) == -coth(x)*csch(x) assert sech(x).diff(x) == -tanh(x)*sech(x) assert acoth(x).diff(x) == 1/(-x**2 + 1) assert asinh(x).diff(x) == 1/sqrt(x**2 + 1) assert acosh(x).diff(x) == 1/sqrt(x**2 - 1) assert atanh(x).diff(x) == 1/(-x**2 + 1) assert asech(x).diff(x) == -1/(x*sqrt(1 - x**2)) assert acsch(x).diff(x) == -1/(x**2*sqrt(1 + x**(-2))) def test_sinh_expansion(): x, y = symbols('x,y') assert sinh(x+y).expand(trig=True) == sinh(x)*cosh(y) + cosh(x)*sinh(y) assert sinh(2*x).expand(trig=True) == 2*sinh(x)*cosh(x) assert sinh(3*x).expand(trig=True).expand() == \ sinh(x)**3 + 3*sinh(x)*cosh(x)**2 def test_cosh_expansion(): x, y = symbols('x,y') assert cosh(x+y).expand(trig=True) == cosh(x)*cosh(y) + sinh(x)*sinh(y) assert cosh(2*x).expand(trig=True) == cosh(x)**2 + sinh(x)**2 assert cosh(3*x).expand(trig=True).expand() == \ 3*sinh(x)**2*cosh(x) + cosh(x)**3 def test_cosh_positive(): # See issue 11721 # cosh(x) is positive for real values of x k = symbols('k', real=True) n = symbols('n', integer=True) assert cosh(k, evaluate=False).is_positive is True assert cosh(k + 2*n*pi*I, evaluate=False).is_positive is True assert cosh(I*pi/4, evaluate=False).is_positive is True assert cosh(3*I*pi/4, evaluate=False).is_positive is False def test_cosh_nonnegative(): k = symbols('k', real=True) n = symbols('n', integer=True) assert cosh(k, evaluate=False).is_nonnegative is True assert cosh(k + 2*n*pi*I, evaluate=False).is_nonnegative is True assert cosh(I*pi/4, evaluate=False).is_nonnegative is True assert cosh(3*I*pi/4, evaluate=False).is_nonnegative is False assert cosh(S.Zero, evaluate=False).is_nonnegative is True def test_real_assumptions(): z = Symbol('z', real=False) assert sinh(z).is_real is None assert cosh(z).is_real is None assert tanh(z).is_real is None assert sech(z).is_real is None assert csch(z).is_real is None assert coth(z).is_real is None def test_sign_assumptions(): p = Symbol('p', positive=True) n = Symbol('n', negative=True) assert sinh(n).is_negative is True assert sinh(p).is_positive is True assert cosh(n).is_positive is True assert cosh(p).is_positive is True assert tanh(n).is_negative is True assert tanh(p).is_positive is True assert csch(n).is_negative is True assert csch(p).is_positive is True assert sech(n).is_positive is True assert sech(p).is_positive is True assert coth(n).is_negative is True assert coth(p).is_positive is True
7411e76a0c9f0c45ec4169715735a9aa008176224cd28508bf640e35b118a3db
# This test file tests the SymPy function interface, that people use to create # their own new functions. It should be as easy as possible. from sympy.core.function import Function from sympy.core.sympify import sympify from sympy.functions.elementary.hyperbolic import tanh from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.series.limits import limit from sympy.abc import x def test_function_series1(): """Create our new "sin" function.""" class my_function(Function): def fdiff(self, argindex=1): return cos(self.args[0]) @classmethod def eval(cls, arg): arg = sympify(arg) if arg == 0: return sympify(0) #Test that the taylor series is correct assert my_function(x).series(x, 0, 10) == sin(x).series(x, 0, 10) assert limit(my_function(x)/x, x, 0) == 1 def test_function_series2(): """Create our new "cos" function.""" class my_function2(Function): def fdiff(self, argindex=1): return -sin(self.args[0]) @classmethod def eval(cls, arg): arg = sympify(arg) if arg == 0: return sympify(1) #Test that the taylor series is correct assert my_function2(x).series(x, 0, 10) == cos(x).series(x, 0, 10) def test_function_series3(): """ Test our easy "tanh" function. This test tests two things: * that the Function interface works as expected and it's easy to use * that the general algorithm for the series expansion works even when the derivative is defined recursively in terms of the original function, since tanh(x).diff(x) == 1-tanh(x)**2 """ class mytanh(Function): def fdiff(self, argindex=1): return 1 - mytanh(self.args[0])**2 @classmethod def eval(cls, arg): arg = sympify(arg) if arg == 0: return sympify(0) e = tanh(x) f = mytanh(x) assert e.series(x, 0, 6) == f.series(x, 0, 6)
c3302829371cb84686e31ac46139587c826e2e2de4513313109f62035d775a88
from sympy.core.symbol import symbols from sympy.functions.special.spherical_harmonics import Ynm x, y = symbols('x,y') def timeit_Ynm_xy(): Ynm(1, 1, x, y)
d03d92233453dbf2a4b8e834499ca8d7f490ef62df11d94e5e46b189e1543a6f
from sympy.core.relational import Ne from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.elementary.complexes import (adjoint, conjugate, transpose) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.tensor_functions import (Eijk, KroneckerDelta, LeviCivita) from sympy.physics.secondquant import evaluate_deltas, F x, y = symbols('x y') def test_levicivita(): assert Eijk(1, 2, 3) == LeviCivita(1, 2, 3) assert LeviCivita(1, 2, 3) == 1 assert LeviCivita(int(1), int(2), int(3)) == 1 assert LeviCivita(1, 3, 2) == -1 assert LeviCivita(1, 2, 2) == 0 i, j, k = symbols('i j k') assert LeviCivita(i, j, k) == LeviCivita(i, j, k, evaluate=False) assert LeviCivita(i, j, i) == 0 assert LeviCivita(1, i, i) == 0 assert LeviCivita(i, j, k).doit() == (j - i)*(k - i)*(k - j)/2 assert LeviCivita(1, 2, 3, 1) == 0 assert LeviCivita(4, 5, 1, 2, 3) == 1 assert LeviCivita(4, 5, 2, 1, 3) == -1 assert LeviCivita(i, j, k).is_integer is True assert adjoint(LeviCivita(i, j, k)) == LeviCivita(i, j, k) assert conjugate(LeviCivita(i, j, k)) == LeviCivita(i, j, k) assert transpose(LeviCivita(i, j, k)) == LeviCivita(i, j, k) def test_kronecker_delta(): i, j = symbols('i j') k = Symbol('k', nonzero=True) assert KroneckerDelta(1, 1) == 1 assert KroneckerDelta(1, 2) == 0 assert KroneckerDelta(k, 0) == 0 assert KroneckerDelta(x, x) == 1 assert KroneckerDelta(x**2 - y**2, x**2 - y**2) == 1 assert KroneckerDelta(i, i) == 1 assert KroneckerDelta(i, i + 1) == 0 assert KroneckerDelta(0, 0) == 1 assert KroneckerDelta(0, 1) == 0 assert KroneckerDelta(i + k, i) == 0 assert KroneckerDelta(i + k, i + k) == 1 assert KroneckerDelta(i + k, i + 1 + k) == 0 assert KroneckerDelta(i, j).subs(dict(i=1, j=0)) == 0 assert KroneckerDelta(i, j).subs(dict(i=3, j=3)) == 1 assert KroneckerDelta(i, j)**0 == 1 for n in range(1, 10): assert KroneckerDelta(i, j)**n == KroneckerDelta(i, j) assert KroneckerDelta(i, j)**-n == 1/KroneckerDelta(i, j) assert KroneckerDelta(i, j).is_integer is True assert adjoint(KroneckerDelta(i, j)) == KroneckerDelta(i, j) assert conjugate(KroneckerDelta(i, j)) == KroneckerDelta(i, j) assert transpose(KroneckerDelta(i, j)) == KroneckerDelta(i, j) # to test if canonical assert (KroneckerDelta(i, j) == KroneckerDelta(j, i)) == True assert KroneckerDelta(i, j).rewrite(Piecewise) == Piecewise((0, Ne(i, j)), (1, True)) # Tests with range: assert KroneckerDelta(i, j, (0, i)).args == (i, j, (0, i)) assert KroneckerDelta(i, j, (-j, i)).delta_range == (-j, i) # If index is out of range, return zero: assert KroneckerDelta(i, j, (0, i-1)) == 0 assert KroneckerDelta(-1, j, (0, i-1)) == 0 assert KroneckerDelta(j, -1, (0, i-1)) == 0 assert KroneckerDelta(j, i, (0, i-1)) == 0 def test_kronecker_delta_secondquant(): """secondquant-specific methods""" D = KroneckerDelta i, j, v, w = symbols('i j v w', below_fermi=True, cls=Dummy) a, b, t, u = symbols('a b t u', above_fermi=True, cls=Dummy) p, q, r, s = symbols('p q r s', cls=Dummy) assert D(i, a) == 0 assert D(i, t) == 0 assert D(i, j).is_above_fermi is False assert D(a, b).is_above_fermi is True assert D(p, q).is_above_fermi is True assert D(i, q).is_above_fermi is False assert D(q, i).is_above_fermi is False assert D(q, v).is_above_fermi is False assert D(a, q).is_above_fermi is True assert D(i, j).is_below_fermi is True assert D(a, b).is_below_fermi is False assert D(p, q).is_below_fermi is True assert D(p, j).is_below_fermi is True assert D(q, b).is_below_fermi is False assert D(i, j).is_only_above_fermi is False assert D(a, b).is_only_above_fermi is True assert D(p, q).is_only_above_fermi is False assert D(i, q).is_only_above_fermi is False assert D(q, i).is_only_above_fermi is False assert D(a, q).is_only_above_fermi is True assert D(i, j).is_only_below_fermi is True assert D(a, b).is_only_below_fermi is False assert D(p, q).is_only_below_fermi is False assert D(p, j).is_only_below_fermi is True assert D(q, b).is_only_below_fermi is False assert not D(i, q).indices_contain_equal_information assert not D(a, q).indices_contain_equal_information assert D(p, q).indices_contain_equal_information assert D(a, b).indices_contain_equal_information assert D(i, j).indices_contain_equal_information assert D(q, b).preferred_index == b assert D(q, b).killable_index == q assert D(q, t).preferred_index == t assert D(q, t).killable_index == q assert D(q, i).preferred_index == i assert D(q, i).killable_index == q assert D(q, v).preferred_index == v assert D(q, v).killable_index == q assert D(q, p).preferred_index == p assert D(q, p).killable_index == q EV = evaluate_deltas assert EV(D(a, q)*F(q)) == F(a) assert EV(D(i, q)*F(q)) == F(i) assert EV(D(a, q)*F(a)) == D(a, q)*F(a) assert EV(D(i, q)*F(i)) == D(i, q)*F(i) assert EV(D(a, b)*F(a)) == F(b) assert EV(D(a, b)*F(b)) == F(a) assert EV(D(i, j)*F(i)) == F(j) assert EV(D(i, j)*F(j)) == F(i) assert EV(D(p, q)*F(q)) == F(p) assert EV(D(p, q)*F(p)) == F(q) assert EV(D(p, j)*D(p, i)*F(i)) == F(j) assert EV(D(p, j)*D(p, i)*F(j)) == F(i) assert EV(D(p, q)*D(p, i))*F(i) == D(q, i)*F(i)
e94620ec8a974e2f1f7123aeb7c4c4ccd564c480387dff82c86db6a899db2180
from sympy.functions import bspline_basis_set, interpolating_spline from sympy.core.numbers import Rational from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.piecewise import Piecewise from sympy.logic.boolalg import And from sympy.sets.sets import Interval from sympy.testing.pytest import slow x, y = symbols('x,y') def test_basic_degree_0(): d = 0 knots = range(5) splines = bspline_basis_set(d, knots, x) for i in range(len(splines)): assert splines[i] == Piecewise((1, Interval(i, i + 1).contains(x)), (0, True)) def test_basic_degree_1(): d = 1 knots = range(5) splines = bspline_basis_set(d, knots, x) assert splines[0] == Piecewise((x, Interval(0, 1).contains(x)), (2 - x, Interval(1, 2).contains(x)), (0, True)) assert splines[1] == Piecewise((-1 + x, Interval(1, 2).contains(x)), (3 - x, Interval(2, 3).contains(x)), (0, True)) assert splines[2] == Piecewise((-2 + x, Interval(2, 3).contains(x)), (4 - x, Interval(3, 4).contains(x)), (0, True)) def test_basic_degree_2(): d = 2 knots = range(5) splines = bspline_basis_set(d, knots, x) b0 = Piecewise((x**2/2, Interval(0, 1).contains(x)), (Rational(-3, 2) + 3*x - x**2, Interval(1, 2).contains(x)), (Rational(9, 2) - 3*x + x**2/2, Interval(2, 3).contains(x)), (0, True)) b1 = Piecewise((S.Half - x + x**2/2, Interval(1, 2).contains(x)), (Rational(-11, 2) + 5*x - x**2, Interval(2, 3).contains(x)), (8 - 4*x + x**2/2, Interval(3, 4).contains(x)), (0, True)) assert splines[0] == b0 assert splines[1] == b1 def test_basic_degree_3(): d = 3 knots = range(5) splines = bspline_basis_set(d, knots, x) b0 = Piecewise( (x**3/6, Interval(0, 1).contains(x)), (Rational(2, 3) - 2*x + 2*x**2 - x**3/2, Interval(1, 2).contains(x)), (Rational(-22, 3) + 10*x - 4*x**2 + x**3/2, Interval(2, 3).contains(x)), (Rational(32, 3) - 8*x + 2*x**2 - x**3/6, Interval(3, 4).contains(x)), (0, True) ) assert splines[0] == b0 def test_repeated_degree_1(): d = 1 knots = [0, 0, 1, 2, 2, 3, 4, 4] splines = bspline_basis_set(d, knots, x) assert splines[0] == Piecewise((1 - x, Interval(0, 1).contains(x)), (0, True)) assert splines[1] == Piecewise((x, Interval(0, 1).contains(x)), (2 - x, Interval(1, 2).contains(x)), (0, True)) assert splines[2] == Piecewise((-1 + x, Interval(1, 2).contains(x)), (0, True)) assert splines[3] == Piecewise((3 - x, Interval(2, 3).contains(x)), (0, True)) assert splines[4] == Piecewise((-2 + x, Interval(2, 3).contains(x)), (4 - x, Interval(3, 4).contains(x)), (0, True)) assert splines[5] == Piecewise((-3 + x, Interval(3, 4).contains(x)), (0, True)) def test_repeated_degree_2(): d = 2 knots = [0, 0, 1, 2, 2, 3, 4, 4] splines = bspline_basis_set(d, knots, x) assert splines[0] == Piecewise(((-3*x**2/2 + 2*x), And(x <= 1, x >= 0)), (x**2/2 - 2*x + 2, And(x <= 2, x >= 1)), (0, True)) assert splines[1] == Piecewise((x**2/2, And(x <= 1, x >= 0)), (-3*x**2/2 + 4*x - 2, And(x <= 2, x >= 1)), (0, True)) assert splines[2] == Piecewise((x**2 - 2*x + 1, And(x <= 2, x >= 1)), (x**2 - 6*x + 9, And(x <= 3, x >= 2)), (0, True)) assert splines[3] == Piecewise((-3*x**2/2 + 8*x - 10, And(x <= 3, x >= 2)), (x**2/2 - 4*x + 8, And(x <= 4, x >= 3)), (0, True)) assert splines[4] == Piecewise((x**2/2 - 2*x + 2, And(x <= 3, x >= 2)), (-3*x**2/2 + 10*x - 16, And(x <= 4, x >= 3)), (0, True)) # Tests for interpolating_spline def test_10_points_degree_1(): d = 1 X = [-5, 2, 3, 4, 7, 9, 10, 30, 31, 34] Y = [-10, -2, 2, 4, 7, 6, 20, 45, 19, 25] spline = interpolating_spline(d, x, X, Y) assert spline == Piecewise((x*Rational(8, 7) - Rational(30, 7), (x >= -5) & (x <= 2)), (4*x - 10, (x >= 2) & (x <= 3)), (2*x - 4, (x >= 3) & (x <= 4)), (x, (x >= 4) & (x <= 7)), (-x/2 + Rational(21, 2), (x >= 7) & (x <= 9)), (14*x - 120, (x >= 9) & (x <= 10)), (x*Rational(5, 4) + Rational(15, 2), (x >= 10) & (x <= 30)), (-26*x + 825, (x >= 30) & (x <= 31)), (2*x - 43, (x >= 31) & (x <= 34))) def test_3_points_degree_2(): d = 2 X = [-3, 10, 19] Y = [3, -4, 30] spline = interpolating_spline(d, x, X, Y) assert spline == Piecewise((505*x**2/2574 - x*Rational(4921, 2574) - Rational(1931, 429), (x >= -3) & (x <= 19))) def test_5_points_degree_2(): d = 2 X = [-3, 2, 4, 5, 10] Y = [-1, 2, 5, 10, 14] spline = interpolating_spline(d, x, X, Y) assert spline == Piecewise((4*x**2/329 + x*Rational(1007, 1645) + Rational(1196, 1645), (x >= -3) & (x <= 3)), (2701*x**2/1645 - x*Rational(15079, 1645) + Rational(5065, 329), (x >= 3) & (x <= Rational(9, 2))), (-1319*x**2/1645 + x*Rational(21101, 1645) - Rational(11216, 329), (x >= Rational(9, 2)) & (x <= 10))) @slow def test_6_points_degree_3(): d = 3 X = [-1, 0, 2, 3, 9, 12] Y = [-4, 3, 3, 7, 9, 20] spline = interpolating_spline(d, x, X, Y) assert spline == Piecewise((6058*x**3/5301 - 18427*x**2/5301 + x*Rational(12622, 5301) + 3, (x >= -1) & (x <= 2)), (-8327*x**3/5301 + 67883*x**2/5301 - x*Rational(159998, 5301) + Rational(43661, 1767), (x >= 2) & (x <= 3)), (5414*x**3/47709 - 1386*x**2/589 + x*Rational(4267, 279) - Rational(12232, 589), (x >= 3) & (x <= 12))) def test_issue_19262(): Delta = symbols('Delta', positive=True) knots = [i*Delta for i in range(4)] basis = bspline_basis_set(1, knots, x) y = symbols('y', nonnegative=True) basis2 = bspline_basis_set(1, knots, y) assert basis[0].subs(x, y) == basis2[0] assert interpolating_spline(1, x, [Delta*i for i in [1, 2, 4, 7]], [3, 6, 5, 7] ) == Piecewise((3*x/Delta, (Delta <= x) & (x <= 2*Delta)), (7 - x/(2*Delta), (x >= 2*Delta) & (x <= 4*Delta)), (Rational(7, 3) + 2*x/(3*Delta), (x >= 4*Delta) & (x <= 7*Delta)))
73408b1e14d8e18728619f0e0d7bd4cd5fc861ba160a64a61252916d22998bcc
from sympy.core.containers import Tuple from sympy.core.function import Derivative from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import cos from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import (appellf1, hyper, meijerg) from sympy.series.order import O from sympy.abc import x, z, k from sympy.series.limits import limit from sympy.testing.pytest import raises, slow from sympy.testing.randtest import ( random_complex_number as randcplx, verify_numerically as tn, test_derivative_numerically as td) def test_TupleParametersBase(): # test that our implementation of the chain rule works p = hyper((), (), z**2) assert p.diff(z) == p*2*z def test_hyper(): raises(TypeError, lambda: hyper(1, 2, z)) assert hyper((1, 2), (1,), z) == hyper(Tuple(1, 2), Tuple(1), z) h = hyper((1, 2), (3, 4, 5), z) assert h.ap == Tuple(1, 2) assert h.bq == Tuple(3, 4, 5) assert h.argument == z assert h.is_commutative is True # just a few checks to make sure that all arguments go where they should assert tn(hyper(Tuple(), Tuple(), z), exp(z), z) assert tn(z*hyper((1, 1), Tuple(2), -z), log(1 + z), z) # differentiation h = hyper( (randcplx(), randcplx(), randcplx()), (randcplx(), randcplx()), z) assert td(h, z) a1, a2, b1, b2, b3 = symbols('a1:3, b1:4') assert hyper((a1, a2), (b1, b2, b3), z).diff(z) == \ a1*a2/(b1*b2*b3) * hyper((a1 + 1, a2 + 1), (b1 + 1, b2 + 1, b3 + 1), z) # differentiation wrt parameters is not supported assert hyper([z], [], z).diff(z) == Derivative(hyper([z], [], z), z) # hyper is unbranched wrt parameters from sympy.functions.elementary.complexes import polar_lift assert hyper([polar_lift(z)], [polar_lift(k)], polar_lift(x)) == \ hyper([z], [k], polar_lift(x)) # hyper does not automatically evaluate anyway, but the test is to make # sure that the evaluate keyword is accepted assert hyper((1, 2), (1,), z, evaluate=False).func is hyper def test_expand_func(): # evaluation at 1 of Gauss' hypergeometric function: from sympy.abc import a, b, c from sympy.core.function import expand_func a1, b1, c1 = randcplx(), randcplx(), randcplx() + 5 assert expand_func(hyper([a, b], [c], 1)) == \ gamma(c)*gamma(-a - b + c)/(gamma(-a + c)*gamma(-b + c)) assert abs(expand_func(hyper([a1, b1], [c1], 1)).n() - hyper([a1, b1], [c1], 1).n()) < 1e-10 # hyperexpand wrapper for hyper: assert expand_func(hyper([], [], z)) == exp(z) assert expand_func(hyper([1, 2, 3], [], z)) == hyper([1, 2, 3], [], z) assert expand_func(meijerg([[1, 1], []], [[1], [0]], z)) == log(z + 1) assert expand_func(meijerg([[1, 1], []], [[], []], z)) == \ meijerg([[1, 1], []], [[], []], z) def replace_dummy(expr, sym): from sympy.core.symbol import Dummy dum = expr.atoms(Dummy) if not dum: return expr assert len(dum) == 1 return expr.xreplace({dum.pop(): sym}) def test_hyper_rewrite_sum(): from sympy.concrete.summations import Sum from sympy.core.symbol import Dummy from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial) _k = Dummy("k") assert replace_dummy(hyper((1, 2), (1, 3), x).rewrite(Sum), _k) == \ Sum(x**_k / factorial(_k) * RisingFactorial(2, _k) / RisingFactorial(3, _k), (_k, 0, oo)) assert hyper((1, 2, 3), (-1, 3), z).rewrite(Sum) == \ hyper((1, 2, 3), (-1, 3), z) def test_radius_of_convergence(): assert hyper((1, 2), [3], z).radius_of_convergence == 1 assert hyper((1, 2), [3, 4], z).radius_of_convergence is oo assert hyper((1, 2, 3), [4], z).radius_of_convergence == 0 assert hyper((0, 1, 2), [4], z).radius_of_convergence is oo assert hyper((-1, 1, 2), [-4], z).radius_of_convergence == 0 assert hyper((-1, -2, 2), [-1], z).radius_of_convergence is oo assert hyper((-1, 2), [-1, -2], z).radius_of_convergence == 0 assert hyper([-1, 1, 3], [-2, 2], z).radius_of_convergence == 1 assert hyper([-1, 1], [-2, 2], z).radius_of_convergence is oo assert hyper([-1, 1, 3], [-2], z).radius_of_convergence == 0 assert hyper((-1, 2, 3, 4), [], z).radius_of_convergence is oo assert hyper([1, 1], [3], 1).convergence_statement == True assert hyper([1, 1], [2], 1).convergence_statement == False assert hyper([1, 1], [2], -1).convergence_statement == True assert hyper([1, 1], [1], -1).convergence_statement == False def test_meijer(): raises(TypeError, lambda: meijerg(1, z)) raises(TypeError, lambda: meijerg(((1,), (2,)), (3,), (4,), z)) assert meijerg(((1, 2), (3,)), ((4,), (5,)), z) == \ meijerg(Tuple(1, 2), Tuple(3), Tuple(4), Tuple(5), z) g = meijerg((1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11, 12, 13, 14), z) assert g.an == Tuple(1, 2) assert g.ap == Tuple(1, 2, 3, 4, 5) assert g.aother == Tuple(3, 4, 5) assert g.bm == Tuple(6, 7, 8, 9) assert g.bq == Tuple(6, 7, 8, 9, 10, 11, 12, 13, 14) assert g.bother == Tuple(10, 11, 12, 13, 14) assert g.argument == z assert g.nu == 75 assert g.delta == -1 assert g.is_commutative is True assert g.is_number is False #issue 13071 assert meijerg([[],[]], [[S.Half],[0]], 1).is_number is True assert meijerg([1, 2], [3], [4], [5], z).delta == S.Half # just a few checks to make sure that all arguments go where they should assert tn(meijerg(Tuple(), Tuple(), Tuple(0), Tuple(), -z), exp(z), z) assert tn(sqrt(pi)*meijerg(Tuple(), Tuple(), Tuple(0), Tuple(S.Half), z**2/4), cos(z), z) assert tn(meijerg(Tuple(1, 1), Tuple(), Tuple(1), Tuple(0), z), log(1 + z), z) # test exceptions raises(ValueError, lambda: meijerg(((3, 1), (2,)), ((oo,), (2, 0)), x)) raises(ValueError, lambda: meijerg(((3, 1), (2,)), ((1,), (2, 0)), x)) # differentiation g = meijerg((randcplx(),), (randcplx() + 2*I,), Tuple(), (randcplx(), randcplx()), z) assert td(g, z) g = meijerg(Tuple(), (randcplx(),), Tuple(), (randcplx(), randcplx()), z) assert td(g, z) g = meijerg(Tuple(), Tuple(), Tuple(randcplx()), Tuple(randcplx(), randcplx()), z) assert td(g, z) a1, a2, b1, b2, c1, c2, d1, d2 = symbols('a1:3, b1:3, c1:3, d1:3') assert meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z).diff(z) == \ (meijerg((a1 - 1, a2), (b1, b2), (c1, c2), (d1, d2), z) + (a1 - 1)*meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z))/z assert meijerg([z, z], [], [], [], z).diff(z) == \ Derivative(meijerg([z, z], [], [], [], z), z) # meijerg is unbranched wrt parameters from sympy.functions.elementary.complexes import polar_lift as pl assert meijerg([pl(a1)], [pl(a2)], [pl(b1)], [pl(b2)], pl(z)) == \ meijerg([a1], [a2], [b1], [b2], pl(z)) # integrand from sympy.abc import a, b, c, d, s assert meijerg([a], [b], [c], [d], z).integrand(s) == \ z**s*gamma(c - s)*gamma(-a + s + 1)/(gamma(b - s)*gamma(-d + s + 1)) def test_meijerg_derivative(): assert meijerg([], [1, 1], [0, 0, x], [], z).diff(x) == \ log(z)*meijerg([], [1, 1], [0, 0, x], [], z) \ + 2*meijerg([], [1, 1, 1], [0, 0, x, 0], [], z) y = randcplx() a = 5 # mpmath chokes with non-real numbers, and Mod1 with floats assert td(meijerg([x], [], [], [], y), x) assert td(meijerg([x**2], [], [], [], y), x) assert td(meijerg([], [x], [], [], y), x) assert td(meijerg([], [], [x], [], y), x) assert td(meijerg([], [], [], [x], y), x) assert td(meijerg([x], [a], [a + 1], [], y), x) assert td(meijerg([x], [a + 1], [a], [], y), x) assert td(meijerg([x, a], [], [], [a + 1], y), x) assert td(meijerg([x, a + 1], [], [], [a], y), x) b = Rational(3, 2) assert td(meijerg([a + 2], [b], [b - 3, x], [a], y), x) def test_meijerg_period(): assert meijerg([], [1], [0], [], x).get_period() == 2*pi assert meijerg([1], [], [], [0], x).get_period() == 2*pi assert meijerg([], [], [0], [], x).get_period() == 2*pi # exp(x) assert meijerg( [], [], [0], [S.Half], x).get_period() == 2*pi # cos(sqrt(x)) assert meijerg( [], [], [S.Half], [0], x).get_period() == 4*pi # sin(sqrt(x)) assert meijerg([1, 1], [], [1], [0], x).get_period() is oo # log(1 + x) def test_hyper_unpolarify(): from sympy.functions.elementary.exponential import exp_polar a = exp_polar(2*pi*I)*x b = x assert hyper([], [], a).argument == b assert hyper([0], [], a).argument == a assert hyper([0], [0], a).argument == b assert hyper([0, 1], [0], a).argument == a assert hyper([0, 1], [0], exp_polar(2*pi*I)).argument == 1 @slow def test_hyperrep(): from sympy.functions.special.hyper import (HyperRep, HyperRep_atanh, HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1, HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2, HyperRep_cosasin, HyperRep_sinasin) # First test the base class works. from sympy.functions.elementary.exponential import exp_polar from sympy.functions.elementary.piecewise import Piecewise a, b, c, d, z = symbols('a b c d z') class myrep(HyperRep): @classmethod def _expr_small(cls, x): return a @classmethod def _expr_small_minus(cls, x): return b @classmethod def _expr_big(cls, x, n): return c*n @classmethod def _expr_big_minus(cls, x, n): return d*n assert myrep(z).rewrite('nonrep') == Piecewise((0, abs(z) > 1), (a, True)) assert myrep(exp_polar(I*pi)*z).rewrite('nonrep') == \ Piecewise((0, abs(z) > 1), (b, True)) assert myrep(exp_polar(2*I*pi)*z).rewrite('nonrep') == \ Piecewise((c, abs(z) > 1), (a, True)) assert myrep(exp_polar(3*I*pi)*z).rewrite('nonrep') == \ Piecewise((d, abs(z) > 1), (b, True)) assert myrep(exp_polar(4*I*pi)*z).rewrite('nonrep') == \ Piecewise((2*c, abs(z) > 1), (a, True)) assert myrep(exp_polar(5*I*pi)*z).rewrite('nonrep') == \ Piecewise((2*d, abs(z) > 1), (b, True)) assert myrep(z).rewrite('nonrepsmall') == a assert myrep(exp_polar(I*pi)*z).rewrite('nonrepsmall') == b def t(func, hyp, z): """ Test that func is a valid representation of hyp. """ # First test that func agrees with hyp for small z if not tn(func.rewrite('nonrepsmall'), hyp, z, a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half): return False # Next check that the two small representations agree. if not tn( func.rewrite('nonrepsmall').subs( z, exp_polar(I*pi)*z).replace(exp_polar, exp), func.subs(z, exp_polar(I*pi)*z).rewrite('nonrepsmall'), z, a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half): return False # Next check continuity along exp_polar(I*pi)*t expr = func.subs(z, exp_polar(I*pi)*z).rewrite('nonrep') if abs(expr.subs(z, 1 + 1e-15).n() - expr.subs(z, 1 - 1e-15).n()) > 1e-10: return False # Finally check continuity of the big reps. def dosubs(func, a, b): rv = func.subs(z, exp_polar(a)*z).rewrite('nonrep') return rv.subs(z, exp_polar(b)*z).replace(exp_polar, exp) for n in [0, 1, 2, 3, 4, -1, -2, -3, -4]: expr1 = dosubs(func, 2*I*pi*n, I*pi/2) expr2 = dosubs(func, 2*I*pi*n + I*pi, -I*pi/2) if not tn(expr1, expr2, z): return False expr1 = dosubs(func, 2*I*pi*(n + 1), -I*pi/2) expr2 = dosubs(func, 2*I*pi*n + I*pi, I*pi/2) if not tn(expr1, expr2, z): return False return True # Now test the various representatives. a = Rational(1, 3) assert t(HyperRep_atanh(z), hyper([S.Half, 1], [Rational(3, 2)], z), z) assert t(HyperRep_power1(a, z), hyper([-a], [], z), z) assert t(HyperRep_power2(a, z), hyper([a, a - S.Half], [2*a], z), z) assert t(HyperRep_log1(z), -z*hyper([1, 1], [2], z), z) assert t(HyperRep_asin1(z), hyper([S.Half, S.Half], [Rational(3, 2)], z), z) assert t(HyperRep_asin2(z), hyper([1, 1], [Rational(3, 2)], z), z) assert t(HyperRep_sqrts1(a, z), hyper([-a, S.Half - a], [S.Half], z), z) assert t(HyperRep_sqrts2(a, z), -2*z/(2*a + 1)*hyper([-a - S.Half, -a], [S.Half], z).diff(z), z) assert t(HyperRep_log2(z), -z/4*hyper([Rational(3, 2), 1, 1], [2, 2], z), z) assert t(HyperRep_cosasin(a, z), hyper([-a, a], [S.Half], z), z) assert t(HyperRep_sinasin(a, z), 2*a*z*hyper([1 - a, 1 + a], [Rational(3, 2)], z), z) @slow def test_meijerg_eval(): from sympy.functions.elementary.exponential import exp_polar from sympy.functions.special.bessel import besseli from sympy.abc import l a = randcplx() arg = x*exp_polar(k*pi*I) expr1 = pi*meijerg([[], [(a + 1)/2]], [[a/2], [-a/2, (a + 1)/2]], arg**2/4) expr2 = besseli(a, arg) # Test that the two expressions agree for all arguments. for x_ in [0.5, 1.5]: for k_ in [0.0, 0.1, 0.3, 0.5, 0.8, 1, 5.751, 15.3]: assert abs((expr1 - expr2).n(subs={x: x_, k: k_})) < 1e-10 assert abs((expr1 - expr2).n(subs={x: x_, k: -k_})) < 1e-10 # Test continuity independently eps = 1e-13 expr2 = expr1.subs(k, l) for x_ in [0.5, 1.5]: for k_ in [0.5, Rational(1, 3), 0.25, 0.75, Rational(2, 3), 1.0, 1.5]: assert abs((expr1 - expr2).n( subs={x: x_, k: k_ + eps, l: k_ - eps})) < 1e-10 assert abs((expr1 - expr2).n( subs={x: x_, k: -k_ + eps, l: -k_ - eps})) < 1e-10 expr = (meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(-I*pi)/4) + meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(I*pi)/4)) \ /(2*sqrt(pi)) assert (expr - pi/exp(1)).n(chop=True) == 0 def test_limits(): k, x = symbols('k, x') assert hyper((1,), (Rational(4, 3), Rational(5, 3)), k**2).series(k) == \ 1 + 9*k**2/20 + 81*k**4/1120 + O(k**6) # issue 6350 assert limit(meijerg((), (), (1,), (0,), -x), x, 0) == \ meijerg(((), ()), ((1,), (0,)), 0) # issue 6052 # https://github.com/sympy/sympy/issues/11465 assert limit(1/hyper((1, ), (1, ), x), x, 0) == 1 def test_appellf1(): a, b1, b2, c, x, y = symbols('a b1 b2 c x y') assert appellf1(a, b2, b1, c, y, x) == appellf1(a, b1, b2, c, x, y) assert appellf1(a, b1, b1, c, y, x) == appellf1(a, b1, b1, c, x, y) assert appellf1(a, b1, b2, c, S.Zero, S.Zero) is S.One f = appellf1(a, b1, b2, c, S.Zero, S.Zero, evaluate=False) assert f.func is appellf1 assert f.doit() is S.One def test_derivative_appellf1(): from sympy.core.function import diff a, b1, b2, c, x, y, z = symbols('a b1 b2 c x y z') assert diff(appellf1(a, b1, b2, c, x, y), x) == a*b1*appellf1(a + 1, b2, b1 + 1, c + 1, y, x)/c assert diff(appellf1(a, b1, b2, c, x, y), y) == a*b2*appellf1(a + 1, b1, b2 + 1, c + 1, x, y)/c assert diff(appellf1(a, b1, b2, c, x, y), z) == 0 assert diff(appellf1(a, b1, b2, c, x, y), a) == Derivative(appellf1(a, b1, b2, c, x, y), a) def test_eval_nseries(): a1, b1, a2, b2 = symbols('a1 b1 a2 b2') assert hyper((1,2), (1,2,3), x**2)._eval_nseries(x, 7, None) == 1 + x**2/3 + x**4/24 + x**6/360 + O(x**7) assert exp(x)._eval_nseries(x,7,None) == hyper((a1, b1), (a1, b1), x)._eval_nseries(x, 7, None) assert hyper((a1, a2), (b1, b2), x)._eval_nseries(z, 7, None) == hyper((a1, a2), (b1, b2), x) + O(z**7)
a6aa056e70bce0d0cbe844248a016dc79390d51158a697244e3cec9bd5d3d0f6
from sympy.core.function import diff from sympy.functions.elementary.complexes import conjugate from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.mathieu_functions import (mathieuc, mathieucprime, mathieus, mathieusprime) from sympy.abc import a, q, z def test_mathieus(): assert isinstance(mathieus(a, q, z), mathieus) assert mathieus(a, 0, z) == sin(sqrt(a)*z) assert conjugate(mathieus(a, q, z)) == mathieus(conjugate(a), conjugate(q), conjugate(z)) assert diff(mathieus(a, q, z), z) == mathieusprime(a, q, z) def test_mathieuc(): assert isinstance(mathieuc(a, q, z), mathieuc) assert mathieuc(a, 0, z) == cos(sqrt(a)*z) assert diff(mathieuc(a, q, z), z) == mathieucprime(a, q, z) def test_mathieusprime(): assert isinstance(mathieusprime(a, q, z), mathieusprime) assert mathieusprime(a, 0, z) == sqrt(a)*cos(sqrt(a)*z) assert diff(mathieusprime(a, q, z), z) == (-a + 2*q*cos(2*z))*mathieus(a, q, z) def test_mathieucprime(): assert isinstance(mathieucprime(a, q, z), mathieucprime) assert mathieucprime(a, 0, z) == -sqrt(a)*sin(sqrt(a)*z) assert diff(mathieucprime(a, q, z), z) == (-a + 2*q*cos(2*z))*mathieuc(a, q, z)
b88b143a206fcc913782f028cee104caf405c4b2f01edd992ed30281b6359fd4
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, warns_deprecated_sympy 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 with warns_deprecated_sympy(): assert DiracDelta(x*y).simplify(x) == DiracDelta(x)/abs(y) with warns_deprecated_sympy(): assert DiracDelta(x*y).simplify(y) == DiracDelta(y)/abs(x) with warns_deprecated_sympy(): assert DiracDelta(x**2*y).simplify(x) == DiracDelta(x**2*y) with warns_deprecated_sympy(): assert DiracDelta(y).simplify(x) == DiracDelta(y) with warns_deprecated_sympy(): assert DiracDelta((x - 1)*(x - 2)*(x - 3)).simplify(x) == ( DiracDelta(x - 3)/2 + DiracDelta(x - 2) + DiracDelta(x - 1)/2) raises(ArgumentIndexError, lambda: DiracDelta(x).fdiff(2)) raises(ValueError, lambda: DiracDelta(x, -1)) raises(ValueError, lambda: DiracDelta(I)) raises(ValueError, lambda: DiracDelta(2 + 3*I)) def test_heaviside(): assert Heaviside(-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
e79ffe5e666c306d7ef0e089067dceb57f9527d91524db2b5817a9f6bbd567b9
from sympy.core.function import (diff, expand_func) from sympy.core.numbers import I from sympy.core.symbol import (Dummy, symbols) from sympy.functions.elementary.complexes import conjugate from sympy.functions.special.beta_functions import (beta, betainc, betainc_regularized) from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import hyper from sympy.integrals.integrals import Integral from sympy.functions.special.gamma_functions import polygamma from sympy.core.function import ArgumentIndexError from sympy.core.expr import unchanged from sympy.testing.pytest import raises def test_beta(): x, y = symbols('x y') t = Dummy('t') assert unchanged(beta, x, y) assert beta(5, -3).is_real == True assert beta(3, y).is_real is None assert expand_func(beta(x, y)) == gamma(x)*gamma(y)/gamma(x + y) assert expand_func(beta(x, y) - beta(y, x)) == 0 # Symmetric assert expand_func(beta(x, y)) == expand_func(beta(x, y + 1) + beta(x + 1, y)).simplify() assert diff(beta(x, y), x) == beta(x, y)*(polygamma(0, x) - polygamma(0, x + y)) assert diff(beta(x, y), y) == beta(x, y)*(polygamma(0, y) - polygamma(0, x + y)) assert conjugate(beta(x, y)) == beta(conjugate(x), conjugate(y)) raises(ArgumentIndexError, lambda: beta(x, y).fdiff(3)) assert beta(x, y).rewrite(gamma) == gamma(x)*gamma(y)/gamma(x + y) assert beta(x).rewrite(gamma) == gamma(x)**2/gamma(2*x) assert beta(x, y).rewrite(Integral).dummy_eq(Integral(t**(x - 1) * (1 - t)**(y - 1), (t, 0, 1))) def test_betainc(): a, b, x1, x2 = symbols('a b x1 x2') assert unchanged(betainc, a, b, x1, x2) assert unchanged(betainc, a, b, 0, x1) assert betainc(1, 2, 0, -5).is_real == True assert betainc(1, 2, 0, x2).is_real is None assert conjugate(betainc(I, 2, 3 - I, 1 + 4*I)) == betainc(-I, 2, 3 + I, 1 - 4*I) assert betainc(a, b, 0, 1).rewrite(Integral).dummy_eq(beta(a, b).rewrite(Integral)) assert betainc(1, 2, 0, x2).rewrite(hyper) == x2*hyper((1, -1), (2,), x2) assert betainc(1, 2, 3, 3).evalf() == 0 def test_betainc_regularized(): a, b, x1, x2 = symbols('a b x1 x2') assert unchanged(betainc_regularized, a, b, x1, x2) assert unchanged(betainc_regularized, a, b, 0, x1) assert betainc_regularized(3, 5, 0, -1).is_real == True assert betainc_regularized(3, 5, 0, x2).is_real is None assert conjugate(betainc_regularized(3*I, 1, 2 + I, 1 + 2*I)) == betainc_regularized(-3*I, 1, 2 - I, 1 - 2*I) assert betainc_regularized(a, b, 0, 1).rewrite(Integral) == 1 assert betainc_regularized(1, 2, x1, x2).rewrite(hyper) == 2*x2*hyper((1, -1), (2,), x2) - 2*x1*hyper((1, -1), (2,), x1) assert betainc_regularized(4, 1, 5, 5).evalf() == 0
a5416d16934f067253767aa8bb48e78927218a3ca1d6b7732aff07db8453f455
from sympy.core.function import diff from sympy.core.numbers import (I, pi) from sympy.core.symbol import Symbol from sympy.functions.elementary.complexes import conjugate from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, cot, sin) from sympy.functions.special.spherical_harmonics import Ynm, Znm, Ynm_c def test_Ynm(): # https://en.wikipedia.org/wiki/Spherical_harmonics th, ph = Symbol("theta", real=True), Symbol("phi", real=True) from sympy.abc import n,m assert Ynm(0, 0, th, ph).expand(func=True) == 1/(2*sqrt(pi)) assert Ynm(1, -1, th, ph) == -exp(-2*I*ph)*Ynm(1, 1, th, ph) assert Ynm(1, -1, th, ph).expand(func=True) == sqrt(6)*sin(th)*exp(-I*ph)/(4*sqrt(pi)) assert Ynm(1, 0, th, ph).expand(func=True) == sqrt(3)*cos(th)/(2*sqrt(pi)) assert Ynm(1, 1, th, ph).expand(func=True) == -sqrt(6)*sin(th)*exp(I*ph)/(4*sqrt(pi)) assert Ynm(2, 0, th, ph).expand(func=True) == 3*sqrt(5)*cos(th)**2/(4*sqrt(pi)) - sqrt(5)/(4*sqrt(pi)) assert Ynm(2, 1, th, ph).expand(func=True) == -sqrt(30)*sin(th)*exp(I*ph)*cos(th)/(4*sqrt(pi)) assert Ynm(2, -2, th, ph).expand(func=True) == (-sqrt(30)*exp(-2*I*ph)*cos(th)**2/(8*sqrt(pi)) + sqrt(30)*exp(-2*I*ph)/(8*sqrt(pi))) assert Ynm(2, 2, th, ph).expand(func=True) == (-sqrt(30)*exp(2*I*ph)*cos(th)**2/(8*sqrt(pi)) + sqrt(30)*exp(2*I*ph)/(8*sqrt(pi))) assert diff(Ynm(n, m, th, ph), th) == (m*cot(th)*Ynm(n, m, th, ph) + sqrt((-m + n)*(m + n + 1))*exp(-I*ph)*Ynm(n, m + 1, th, ph)) assert diff(Ynm(n, m, th, ph), ph) == I*m*Ynm(n, m, th, ph) assert conjugate(Ynm(n, m, th, ph)) == (-1)**(2*m)*exp(-2*I*m*ph)*Ynm(n, m, th, ph) assert Ynm(n, m, -th, ph) == Ynm(n, m, th, ph) assert Ynm(n, m, th, -ph) == exp(-2*I*m*ph)*Ynm(n, m, th, ph) assert Ynm(n, -m, th, ph) == (-1)**m*exp(-2*I*m*ph)*Ynm(n, m, th, ph) def test_Ynm_c(): th, ph = Symbol("theta", real=True), Symbol("phi", real=True) from sympy.abc import n,m assert Ynm_c(n, m, th, ph) == (-1)**(2*m)*exp(-2*I*m*ph)*Ynm(n, m, th, ph) def test_Znm(): # https://en.wikipedia.org/wiki/Solid_harmonics#List_of_lowest_functions th, ph = Symbol("theta", real=True), Symbol("phi", real=True) assert Znm(0, 0, th, ph) == Ynm(0, 0, th, ph) assert Znm(1, -1, th, ph) == (-sqrt(2)*I*(Ynm(1, 1, th, ph) - exp(-2*I*ph)*Ynm(1, 1, th, ph))/2) assert Znm(1, 0, th, ph) == Ynm(1, 0, th, ph) assert Znm(1, 1, th, ph) == (sqrt(2)*(Ynm(1, 1, th, ph) + exp(-2*I*ph)*Ynm(1, 1, th, ph))/2) assert Znm(0, 0, th, ph).expand(func=True) == 1/(2*sqrt(pi)) assert Znm(1, -1, th, ph).expand(func=True) == (sqrt(3)*I*sin(th)*exp(I*ph)/(4*sqrt(pi)) - sqrt(3)*I*sin(th)*exp(-I*ph)/(4*sqrt(pi))) assert Znm(1, 0, th, ph).expand(func=True) == sqrt(3)*cos(th)/(2*sqrt(pi)) assert Znm(1, 1, th, ph).expand(func=True) == (-sqrt(3)*sin(th)*exp(I*ph)/(4*sqrt(pi)) - sqrt(3)*sin(th)*exp(-I*ph)/(4*sqrt(pi))) assert Znm(2, -1, th, ph).expand(func=True) == (sqrt(15)*I*sin(th)*exp(I*ph)*cos(th)/(4*sqrt(pi)) - sqrt(15)*I*sin(th)*exp(-I*ph)*cos(th)/(4*sqrt(pi))) assert Znm(2, 0, th, ph).expand(func=True) == 3*sqrt(5)*cos(th)**2/(4*sqrt(pi)) - sqrt(5)/(4*sqrt(pi)) assert Znm(2, 1, th, ph).expand(func=True) == (-sqrt(15)*sin(th)*exp(I*ph)*cos(th)/(4*sqrt(pi)) - sqrt(15)*sin(th)*exp(-I*ph)*cos(th)/(4*sqrt(pi)))
f41dee4fc8d1923a18f332453195fef0c2f90251b319fdb1b3c18ad02df2bb2e
from sympy.concrete.summations import Sum from sympy.core.function import expand_func from sympy.core.numbers import (Float, I, Rational, nan, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.complexes import (Abs, polar_lift) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.special.zeta_functions import (dirichlet_eta, lerchphi, polylog, riemann_xi, stieltjes, zeta) from sympy.series.order import O from sympy.core.function import ArgumentIndexError from sympy.functions.combinatorial.numbers import bernoulli, factorial from sympy.testing.pytest import raises from sympy.testing.randtest import (test_derivative_numerically as td, random_complex_number as randcplx, verify_numerically) x = Symbol('x') a = Symbol('a') b = Symbol('b', negative=True) z = Symbol('z') s = Symbol('s') def test_zeta_eval(): assert zeta(nan) is nan assert zeta(x, nan) is nan assert zeta(0) == Rational(-1, 2) assert zeta(0, x) == S.Half - x assert zeta(0, b) == S.Half - b assert zeta(1) is zoo assert zeta(1, 2) is zoo assert zeta(1, -7) is zoo assert zeta(1, x) is zoo assert zeta(2, 1) == pi**2/6 assert zeta(2) == pi**2/6 assert zeta(4) == pi**4/90 assert zeta(6) == pi**6/945 assert zeta(2, 2) == pi**2/6 - 1 assert zeta(4, 3) == pi**4/90 - Rational(17, 16) assert zeta(6, 4) == pi**6/945 - Rational(47449, 46656) assert zeta(2, -2) == pi**2/6 + Rational(5, 4) assert zeta(4, -3) == pi**4/90 + Rational(1393, 1296) assert zeta(6, -4) == pi**6/945 + Rational(3037465, 2985984) assert zeta(oo) == 1 assert zeta(-1) == Rational(-1, 12) assert zeta(-2) == 0 assert zeta(-3) == Rational(1, 120) assert zeta(-4) == 0 assert zeta(-5) == Rational(-1, 252) assert zeta(-1, 3) == Rational(-37, 12) assert zeta(-1, 7) == Rational(-253, 12) assert zeta(-1, -4) == Rational(119, 12) assert zeta(-1, -9) == Rational(539, 12) assert zeta(-4, 3) == -17 assert zeta(-4, -8) == 8772 assert zeta(0, 1) == Rational(-1, 2) assert zeta(0, -1) == Rational(3, 2) assert zeta(0, 2) == Rational(-3, 2) assert zeta(0, -2) == Rational(5, 2) assert zeta( 3).evalf(20).epsilon_eq(Float("1.2020569031595942854", 20), 1e-19) def test_zeta_series(): assert zeta(x, a).series(a, 0, 2) == \ zeta(x, 0) - x*a*zeta(x + 1, 0) + O(a**2) def test_dirichlet_eta_eval(): assert dirichlet_eta(0) == S.Half assert dirichlet_eta(-1) == Rational(1, 4) assert dirichlet_eta(1) == log(2) assert dirichlet_eta(2) == pi**2/12 assert dirichlet_eta(4) == pi**4*Rational(7, 720) def test_riemann_xi_eval(): assert riemann_xi(2) == pi/6 assert riemann_xi(0) == Rational(1, 2) assert riemann_xi(1) == Rational(1, 2) assert riemann_xi(3).rewrite(zeta) == 3*zeta(3)/(2*pi) assert riemann_xi(4) == pi**2/15 def test_rewriting(): assert dirichlet_eta(x).rewrite(zeta) == (1 - 2**(1 - x))*zeta(x) assert zeta(x).rewrite(dirichlet_eta) == dirichlet_eta(x)/(1 - 2**(1 - x)) assert zeta(x).rewrite(dirichlet_eta, a=2) == zeta(x) assert verify_numerically(dirichlet_eta(x), dirichlet_eta(x).rewrite(zeta), x) assert verify_numerically(zeta(x), zeta(x).rewrite(dirichlet_eta), x) assert zeta(x, a).rewrite(lerchphi) == lerchphi(1, x, a) assert polylog(s, z).rewrite(lerchphi) == lerchphi(z, s, 1)*z assert lerchphi(1, x, a).rewrite(zeta) == zeta(x, a) assert z*lerchphi(z, s, 1).rewrite(polylog) == polylog(s, z) def test_derivatives(): from sympy.core.function import Derivative assert zeta(x, a).diff(x) == Derivative(zeta(x, a), x) assert zeta(x, a).diff(a) == -x*zeta(x + 1, a) assert lerchphi( z, s, a).diff(z) == (lerchphi(z, s - 1, a) - a*lerchphi(z, s, a))/z assert lerchphi(z, s, a).diff(a) == -s*lerchphi(z, s + 1, a) assert polylog(s, z).diff(z) == polylog(s - 1, z)/z b = randcplx() c = randcplx() assert td(zeta(b, x), x) assert td(polylog(b, z), z) assert td(lerchphi(c, b, x), x) assert td(lerchphi(x, b, c), x) raises(ArgumentIndexError, lambda: lerchphi(c, b, x).fdiff(2)) raises(ArgumentIndexError, lambda: lerchphi(c, b, x).fdiff(4)) raises(ArgumentIndexError, lambda: polylog(b, z).fdiff(1)) raises(ArgumentIndexError, lambda: polylog(b, z).fdiff(3)) def myexpand(func, target): expanded = expand_func(func) if target is not None: return expanded == target if expanded == func: # it didn't expand return False # check to see that the expanded and original evaluate to the same value subs = {} for a in func.free_symbols: subs[a] = randcplx() return abs(func.subs(subs).n() - expanded.replace(exp_polar, exp).subs(subs).n()) < 1e-10 def test_polylog_expansion(): assert polylog(s, 0) == 0 assert polylog(s, 1) == zeta(s) assert polylog(s, -1) == -dirichlet_eta(s) assert polylog(s, exp_polar(I*pi*Rational(4, 3))) == polylog(s, exp(I*pi*Rational(4, 3))) assert polylog(s, exp_polar(I*pi)/3) == polylog(s, exp(I*pi)/3) assert myexpand(polylog(1, z), -log(1 - z)) assert myexpand(polylog(0, z), z/(1 - z)) assert myexpand(polylog(-1, z), z/(1 - z)**2) assert ((1-z)**3 * expand_func(polylog(-2, z))).simplify() == z*(1 + z) assert myexpand(polylog(-5, z), None) def test_polylog_series(): assert polylog(1, z).series(z, n=5) == z + z**2/2 + z**3/3 + z**4/4 + O(z**5) assert polylog(1, sqrt(z)).series(z, n=3) == z/2 + z**2/4 + sqrt(z)\ + z**(S(3)/2)/3 + z**(S(5)/2)/5 + O(z**3) # https://github.com/sympy/sympy/issues/9497 assert polylog(S(3)/2, -z).series(z, 0, 5) == -z + sqrt(2)*z**2/4\ - sqrt(3)*z**3/9 + z**4/8 + O(z**5) def test_issue_8404(): i = Symbol('i', integer=True) assert Abs(Sum(1/(3*i + 1)**2, (i, 0, S.Infinity)).doit().n(4) - 1.122) < 0.001 def test_polylog_values(): assert polylog(2, 2) == pi**2/4 - I*pi*log(2) assert polylog(2, S.Half) == pi**2/12 - log(2)**2/2 for z in [S.Half, 2, (sqrt(5)-1)/2, -(sqrt(5)-1)/2, -(sqrt(5)+1)/2, (3-sqrt(5))/2]: assert Abs(polylog(2, z).evalf() - polylog(2, z, evaluate=False).evalf()) < 1e-15 z = Symbol("z") for s in [-1, 0]: for _ in range(10): assert verify_numerically(polylog(s, z), polylog(s, z, evaluate=False), z, a=-3, b=-2, c=S.Half, d=2) assert verify_numerically(polylog(s, z), polylog(s, z, evaluate=False), z, a=2, b=-2, c=5, d=2) from sympy.integrals.integrals import Integral assert polylog(0, Integral(1, (x, 0, 1))) == -S.Half def test_lerchphi_expansion(): assert myexpand(lerchphi(1, s, a), zeta(s, a)) assert myexpand(lerchphi(z, s, 1), polylog(s, z)/z) # direct summation assert myexpand(lerchphi(z, -1, a), a/(1 - z) + z/(1 - z)**2) assert myexpand(lerchphi(z, -3, a), None) # polylog reduction assert myexpand(lerchphi(z, s, S.Half), 2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) - polylog(s, polar_lift(-1)*sqrt(z))/sqrt(z))) assert myexpand(lerchphi(z, s, 2), -1/z + polylog(s, z)/z**2) assert myexpand(lerchphi(z, s, Rational(3, 2)), None) assert myexpand(lerchphi(z, s, Rational(7, 3)), None) assert myexpand(lerchphi(z, s, Rational(-1, 3)), None) assert myexpand(lerchphi(z, s, Rational(-5, 2)), None) # hurwitz zeta reduction assert myexpand(lerchphi(-1, s, a), 2**(-s)*zeta(s, a/2) - 2**(-s)*zeta(s, (a + 1)/2)) assert myexpand(lerchphi(I, s, a), None) assert myexpand(lerchphi(-I, s, a), None) assert myexpand(lerchphi(exp(I*pi*Rational(2, 5)), s, a), None) def test_stieltjes(): assert isinstance(stieltjes(x), stieltjes) assert isinstance(stieltjes(x, a), stieltjes) # Zero'th constant EulerGamma assert stieltjes(0) == S.EulerGamma assert stieltjes(0, 1) == S.EulerGamma # Not defined assert stieltjes(nan) is nan assert stieltjes(0, nan) is nan assert stieltjes(-1) is S.ComplexInfinity assert stieltjes(1.5) is S.ComplexInfinity assert stieltjes(z, 0) is S.ComplexInfinity assert stieltjes(z, -1) is S.ComplexInfinity def test_stieltjes_evalf(): assert abs(stieltjes(0).evalf() - 0.577215664) < 1E-9 assert abs(stieltjes(0, 0.5).evalf() - 1.963510026) < 1E-9 assert abs(stieltjes(1, 2).evalf() + 0.072815845 ) < 1E-9 def test_issue_10475(): a = Symbol('a', extended_real=True) b = Symbol('b', extended_positive=True) s = Symbol('s', zero=False) assert zeta(2 + I).is_finite assert zeta(1).is_finite is False assert zeta(x).is_finite is None assert zeta(x + I).is_finite is None assert zeta(a).is_finite is None assert zeta(b).is_finite is None assert zeta(-b).is_finite is True assert zeta(b**2 - 2*b + 1).is_finite is None assert zeta(a + I).is_finite is True assert zeta(b + 1).is_finite is True assert zeta(s + 1).is_finite is True def test_issue_14177(): n = Symbol('n', positive=True, integer=True) assert zeta(2*n) == (-1)**(n + 1)*2**(2*n - 1)*pi**(2*n)*bernoulli(2*n)/factorial(2*n) assert zeta(-n) == (-1)**(-n)*bernoulli(n + 1)/(n + 1) n = Symbol('n') assert zeta(2*n) == zeta(2*n) # As sign of z (= 2*n) is not determined
5f48ccda3773797d162a2ef04d4552a75a88906bd22dff3260ffc68c8e086433
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.testing.randtest 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 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) 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', real=True, positive=True) t = Symbol('t', negative=True) for f in [besseli, besselj, besselk, bessely, hankel1, hankel2]: assert f(n, -1).conjugate() != f(conjugate(n), -1) assert f(n, x).conjugate() != f(conjugate(n), x) assert f(n, t).conjugate() != f(conjugate(n), t) rz = randcplx(b=0.5) for f in [besseli, besselj, besselk, bessely]: assert f(n, 1 + I).conjugate() == f(conjugate(n), 1 - I) assert f(n, 0).conjugate() == f(conjugate(n), 0) assert f(n, 1).conjugate() == f(conjugate(n), 1) assert f(n, z).conjugate() == f(conjugate(n), conjugate(z)) assert f(n, y).conjugate() == f(conjugate(n), y) assert tn(f(n, rz).conjugate(), f(conjugate(n), conjugate(rz))) assert hankel1(n, 1 + I).conjugate() == hankel2(conjugate(n), 1 - I) assert hankel1(n, 0).conjugate() == hankel2(conjugate(n), 0) assert hankel1(n, 1).conjugate() == hankel2(conjugate(n), 1) assert hankel1(n, y).conjugate() == hankel2(conjugate(n), y) assert hankel1(n, z).conjugate() == hankel2(conjugate(n), conjugate(z)) assert tn(hankel1(n, rz).conjugate(), hankel2(conjugate(n), conjugate(rz))) assert hankel2(n, 1 + I).conjugate() == hankel1(conjugate(n), 1 - I) assert hankel2(n, 0).conjugate() == hankel1(conjugate(n), 0) assert hankel2(n, 1).conjugate() == hankel1(conjugate(n), 1) assert hankel2(n, y).conjugate() == hankel1(conjugate(n), y) assert hankel2(n, z).conjugate() == hankel1(conjugate(n), conjugate(z)) assert tn(hankel2(n, rz).conjugate(), hankel1(conjugate(n), conjugate(rz))) def test_branching(): assert besselj(polar_lift(k), x) == besselj(k, x) assert besseli(polar_lift(k), x) == besseli(k, x) n = Symbol('n', integer=True) assert besselj(n, exp_polar(2*pi*I)*x) == besselj(n, x) assert besselj(n, polar_lift(x)) == besselj(n, x) assert besseli(n, exp_polar(2*pi*I)*x) == besseli(n, x) assert besseli(n, polar_lift(x)) == besseli(n, x) def tn(func, s): from random import uniform c = uniform(1, 5) expr = func(s, c*exp_polar(I*pi)) - func(s, c*exp_polar(-I*pi)) eps = 1e-15 expr2 = func(s + eps, -c + eps*I) - func(s + eps, -c - eps*I) return abs(expr.n() - expr2.n()).n() < 1e-10 nu = Symbol('nu') assert besselj(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besselj(nu, x) assert besseli(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besseli(nu, x) assert tn(besselj, 2) assert tn(besselj, pi) assert tn(besselj, I) assert tn(besseli, 2) assert tn(besseli, pi) assert tn(besseli, I) def test_airy_base(): z = Symbol('z') x = Symbol('x', real=True) y = Symbol('y', real=True) assert conjugate(airyai(z)) == airyai(conjugate(z)) assert airyai(x).is_extended_real assert airyai(x+I*y).as_real_imag() == ( airyai(x - I*y)/2 + airyai(x + I*y)/2, I*(airyai(x - I*y) - airyai(x + I*y))/2) def test_airyai(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airyai(z), airyai) assert airyai(0) == 3**Rational(1, 3)/(3*gamma(Rational(2, 3))) assert airyai(oo) == 0 assert airyai(-oo) == 0 assert diff(airyai(z), z) == airyaiprime(z) assert series(airyai(z), z, 0, 3) == ( 3**Rational(5, 6)*gamma(Rational(1, 3))/(6*pi) - 3**Rational(1, 6)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3)) assert airyai(z).rewrite(hyper) == ( -3**Rational(2, 3)*z*hyper((), (Rational(4, 3),), z**3/9)/(3*gamma(Rational(1, 3))) + 3**Rational(1, 3)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3)))) assert isinstance(airyai(z).rewrite(besselj), airyai) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airyai(z).rewrite(besseli) == ( -z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(1, 3)) + (z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3) assert airyai(p).rewrite(besseli) == ( sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) - besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airyai(2*(3*z**5)**Rational(1, 3))) == ( -sqrt(3)*(-1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/6 + (1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_airybi(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airybi(z), airybi) assert airybi(0) == 3**Rational(5, 6)/(3*gamma(Rational(2, 3))) assert airybi(oo) is oo assert airybi(-oo) == 0 assert diff(airybi(z), z) == airybiprime(z) assert series(airybi(z), z, 0, 3) == ( 3**Rational(1, 3)*gamma(Rational(1, 3))/(2*pi) + 3**Rational(2, 3)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3)) assert airybi(z).rewrite(hyper) == ( 3**Rational(1, 6)*z*hyper((), (Rational(4, 3),), z**3/9)/gamma(Rational(1, 3)) + 3**Rational(5, 6)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3)))) assert isinstance(airybi(z).rewrite(besselj), airybi) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airybi(z).rewrite(besseli) == ( sqrt(3)*(z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(1, 3) + (z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3))/3) assert airybi(p).rewrite(besseli) == ( sqrt(3)*sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airybi(2*(3*z**5)**Rational(1, 3))) == ( sqrt(3)*(1 - (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2 + (1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_airyaiprime(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airyaiprime(z), airyaiprime) assert airyaiprime(0) == -3**Rational(2, 3)/(3*gamma(Rational(1, 3))) assert airyaiprime(oo) == 0 assert diff(airyaiprime(z), z) == z*airyai(z) assert series(airyaiprime(z), z, 0, 3) == ( -3**Rational(2, 3)/(3*gamma(Rational(1, 3))) + 3**Rational(1, 3)*z**2/(6*gamma(Rational(2, 3))) + O(z**3)) assert airyaiprime(z).rewrite(hyper) == ( 3**Rational(1, 3)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) - 3**Rational(2, 3)*hyper((), (Rational(1, 3),), z**3/9)/(3*gamma(Rational(1, 3)))) assert isinstance(airyaiprime(z).rewrite(besselj), airyaiprime) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airyaiprime(z).rewrite(besseli) == ( z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(2, 3)) - (z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3) assert airyaiprime(p).rewrite(besseli) == ( p*(-besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airyaiprime(2*(3*z**5)**Rational(1, 3))) == ( sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/6 + (z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_airybiprime(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airybiprime(z), airybiprime) assert airybiprime(0) == 3**Rational(1, 6)/gamma(Rational(1, 3)) assert airybiprime(oo) is oo assert airybiprime(-oo) == 0 assert diff(airybiprime(z), z) == z*airybi(z) assert series(airybiprime(z), z, 0, 3) == ( 3**Rational(1, 6)/gamma(Rational(1, 3)) + 3**Rational(5, 6)*z**2/(6*gamma(Rational(2, 3))) + O(z**3)) assert airybiprime(z).rewrite(hyper) == ( 3**Rational(5, 6)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) + 3**Rational(1, 6)*hyper((), (Rational(1, 3),), z**3/9)/gamma(Rational(1, 3))) assert isinstance(airybiprime(z).rewrite(besselj), airybiprime) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airybiprime(z).rewrite(besseli) == ( sqrt(3)*(z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(2, 3) + (z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-2, 3), 2*z**Rational(3, 2)/3))/3) assert airybiprime(p).rewrite(besseli) == ( sqrt(3)*p*(besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airybiprime(2*(3*z**5)**Rational(1, 3))) == ( sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2 + (z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_marcumq(): m = Symbol('m') a = Symbol('a') b = Symbol('b') assert marcumq(0, 0, 0) == 0 assert marcumq(m, 0, b) == uppergamma(m, b**2/2)/gamma(m) assert marcumq(2, 0, 5) == 27*exp(Rational(-25, 2))/2 assert marcumq(0, a, 0) == 1 - exp(-a**2/2) assert marcumq(0, pi, 0) == 1 - exp(-pi**2/2) assert marcumq(1, a, a) == S.Half + exp(-a**2)*besseli(0, a**2)/2 assert marcumq(2, a, a) == S.Half + exp(-a**2)*besseli(0, a**2)/2 + exp(-a**2)*besseli(1, a**2) assert diff(marcumq(1, a, 3), a) == a*(-marcumq(1, a, 3) + marcumq(2, a, 3)) assert diff(marcumq(2, 3, b), b) == -b**2*exp(-b**2/2 - Rational(9, 2))*besseli(1, 3*b)/3 x = Symbol('x') assert marcumq(2, 3, 4).rewrite(Integral, x=x) == \ Integral(x**2*exp(-x**2/2 - Rational(9, 2))*besseli(1, 3*x), (x, 4, oo))/3 assert eq([marcumq(5, -2, 3).rewrite(Integral).evalf(10)], [0.7905769565]) k = Symbol('k') assert marcumq(-3, -5, -7).rewrite(Sum, k=k) == \ exp(-37)*Sum((Rational(5, 7))**k*besseli(k, 35), (k, 4, oo)) assert eq([marcumq(1, 3, 1).rewrite(Sum).evalf(10)], [0.9891705502]) assert marcumq(1, a, a, evaluate=False).rewrite(besseli) == S.Half + exp(-a**2)*besseli(0, a**2)/2 assert marcumq(2, a, a, evaluate=False).rewrite(besseli) == S.Half + exp(-a**2)*besseli(0, a**2)/2 + \ exp(-a**2)*besseli(1, a**2) assert marcumq(3, a, a).rewrite(besseli) == (besseli(1, a**2) + besseli(2, a**2))*exp(-a**2) + \ S.Half + exp(-a**2)*besseli(0, a**2)/2 assert marcumq(5, 8, 8).rewrite(besseli) == exp(-64)*besseli(0, 64)/2 + \ (besseli(4, 64) + besseli(3, 64) + besseli(2, 64) + besseli(1, 64))*exp(-64) + S.Half assert marcumq(m, a, a).rewrite(besseli) == marcumq(m, a, a) x = Symbol('x', integer=True) assert marcumq(x, a, a).rewrite(besseli) == marcumq(x, a, a)
b6a30940838eb01aef79772d5cf90f14861d4e11bec302ac8df7511ec844a5fc
from sympy.core.function import (Derivative, diff) from sympy.core.numbers import (Float, I, nan, oo, pi) from sympy.core.relational import Eq from sympy.core.symbol import (Symbol, symbols) 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.series.order import O from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises x, y, a, n = symbols('x y a n') def test_fdiff(): assert SingularityFunction(x, 4, 5).fdiff() == 5*SingularityFunction(x, 4, 4) assert SingularityFunction(x, 4, -1).fdiff() == SingularityFunction(x, 4, -2) assert SingularityFunction(x, 4, 0).fdiff() == SingularityFunction(x, 4, -1) assert SingularityFunction(y, 6, 2).diff(y) == 2*SingularityFunction(y, 6, 1) assert SingularityFunction(y, -4, -1).diff(y) == SingularityFunction(y, -4, -2) assert SingularityFunction(y, 4, 0).diff(y) == SingularityFunction(y, 4, -1) assert SingularityFunction(y, 4, 0).diff(y, 2) == SingularityFunction(y, 4, -2) n = Symbol('n', positive=True) assert SingularityFunction(x, a, n).fdiff() == n*SingularityFunction(x, a, n - 1) assert SingularityFunction(y, a, n).diff(y) == n*SingularityFunction(y, a, n - 1) expr_in = 4*SingularityFunction(x, a, n) + 3*SingularityFunction(x, a, -1) + -10*SingularityFunction(x, a, 0) expr_out = n*4*SingularityFunction(x, a, n - 1) + 3*SingularityFunction(x, a, -2) - 10*SingularityFunction(x, a, -1) assert diff(expr_in, x) == expr_out assert SingularityFunction(x, -10, 5).diff(evaluate=False) == ( Derivative(SingularityFunction(x, -10, 5), x)) raises(ArgumentIndexError, lambda: SingularityFunction(x, 4, 5).fdiff(2)) def test_eval(): assert SingularityFunction(x, a, n).func == SingularityFunction assert unchanged(SingularityFunction, x, 5, n) assert SingularityFunction(5, 3, 2) == 4 assert SingularityFunction(3, 5, 1) == 0 assert SingularityFunction(3, 3, 0) == 1 assert SingularityFunction(4, 4, -1) is oo assert SingularityFunction(4, 2, -1) == 0 assert SingularityFunction(4, 7, -1) == 0 assert SingularityFunction(5, 6, -2) == 0 assert SingularityFunction(4, 2, -2) == 0 assert SingularityFunction(4, 4, -2) is oo assert (SingularityFunction(6.1, 4, 5)).evalf(5) == Float('40.841', '5') assert SingularityFunction(6.1, pi, 2) == (-pi + 6.1)**2 assert SingularityFunction(x, a, nan) is nan assert SingularityFunction(x, nan, 1) is nan assert SingularityFunction(nan, a, n) is nan raises(ValueError, lambda: SingularityFunction(x, a, I)) raises(ValueError, lambda: SingularityFunction(2*I, I, n)) raises(ValueError, lambda: SingularityFunction(x, a, -3)) def test_leading_term(): l = Symbol('l', positive=True) assert SingularityFunction(x, 3, 2).as_leading_term(x) == 0 assert SingularityFunction(x, -2, 1).as_leading_term(x) == 2 assert SingularityFunction(x, 0, 0).as_leading_term(x) == 1 assert SingularityFunction(x, 0, 0).as_leading_term(x, cdir=-1) == 0 assert SingularityFunction(x, 0, -1).as_leading_term(x) == 0 assert SingularityFunction(x, 0, -2).as_leading_term(x) == 0 assert (SingularityFunction(x + l, 0, 1)/2\ - SingularityFunction(x + l, l/2, 1)\ + SingularityFunction(x + l, l, 1)/2).as_leading_term(x) == -x/2 def test_series(): l = Symbol('l', positive=True) assert SingularityFunction(x, -3, 2).series(x) == x**2 + 6*x + 9 assert SingularityFunction(x, -2, 1).series(x) == x + 2 assert SingularityFunction(x, 0, 0).series(x) == 1 assert SingularityFunction(x, 0, 0).series(x, dir='-') == 0 assert SingularityFunction(x, 0, -1).series(x) == 0 assert SingularityFunction(x, 0, -2).series(x) == 0 assert (SingularityFunction(x + l, 0, 1)/2\ - SingularityFunction(x + l, l/2, 1)\ + SingularityFunction(x + l, l, 1)/2).nseries(x) == -x/2 + O(x**6) def test_rewrite(): assert SingularityFunction(x, 4, 5).rewrite(Piecewise) == ( Piecewise(((x - 4)**5, x - 4 > 0), (0, True))) assert SingularityFunction(x, -10, 0).rewrite(Piecewise) == ( Piecewise((1, x + 10 > 0), (0, True))) assert SingularityFunction(x, 2, -1).rewrite(Piecewise) == ( Piecewise((oo, Eq(x - 2, 0)), (0, True))) assert SingularityFunction(x, 0, -2).rewrite(Piecewise) == ( Piecewise((oo, Eq(x, 0)), (0, True))) n = Symbol('n', nonnegative=True) assert SingularityFunction(x, a, n).rewrite(Piecewise) == ( Piecewise(((x - a)**n, x - a > 0), (0, True))) expr_in = SingularityFunction(x, 4, 5) + SingularityFunction(x, -3, -1) - SingularityFunction(x, 0, -2) expr_out = (x - 4)**5*Heaviside(x - 4) + DiracDelta(x + 3) - DiracDelta(x, 1) assert expr_in.rewrite(Heaviside) == expr_out assert expr_in.rewrite(DiracDelta) == expr_out assert expr_in.rewrite('HeavisideDiracDelta') == expr_out expr_in = SingularityFunction(x, a, n) + SingularityFunction(x, a, -1) - SingularityFunction(x, a, -2) expr_out = (x - a)**n*Heaviside(x - a) + DiracDelta(x - a) + DiracDelta(a - x, 1) assert expr_in.rewrite(Heaviside) == expr_out assert expr_in.rewrite(DiracDelta) == expr_out assert expr_in.rewrite('HeavisideDiracDelta') == expr_out
73b778e3735fb1c38b2b1e5fae177b2e8e405de132c94270b6791394d016ea00
from sympy.core.numbers import (I, Rational, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol) from sympy.functions.elementary.hyperbolic import atanh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (sin, tan) from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import (hyper, meijerg) from sympy.integrals.integrals import Integral from sympy.series.order import O from sympy.functions.special.elliptic_integrals import (elliptic_k as K, elliptic_f as F, elliptic_e as E, elliptic_pi as P) from sympy.testing.randtest import (test_derivative_numerically as td, random_complex_number as randcplx, verify_numerically as tn) from sympy.abc import z, m, n i = Symbol('i', integer=True) j = Symbol('k', integer=True, positive=True) t = Dummy('t') def test_K(): assert K(0) == pi/2 assert K(S.Half) == 8*pi**Rational(3, 2)/gamma(Rational(-1, 4))**2 assert K(1) is zoo assert K(-1) == gamma(Rational(1, 4))**2/(4*sqrt(2*pi)) assert K(oo) == 0 assert K(-oo) == 0 assert K(I*oo) == 0 assert K(-I*oo) == 0 assert K(zoo) == 0 assert K(z).diff(z) == (E(z) - (1 - z)*K(z))/(2*z*(1 - z)) assert td(K(z), z) zi = Symbol('z', real=False) assert K(zi).conjugate() == K(zi.conjugate()) zr = Symbol('z', real=True, negative=True) assert K(zr).conjugate() == K(zr) assert K(z).rewrite(hyper) == \ (pi/2)*hyper((S.Half, S.Half), (S.One,), z) assert tn(K(z), (pi/2)*hyper((S.Half, S.Half), (S.One,), z)) assert K(z).rewrite(meijerg) == \ meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z)/2 assert tn(K(z), meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z)/2) assert K(z).series(z) == pi/2 + pi*z/8 + 9*pi*z**2/128 + \ 25*pi*z**3/512 + 1225*pi*z**4/32768 + 3969*pi*z**5/131072 + O(z**6) assert K(m).rewrite(Integral).dummy_eq( Integral(1/sqrt(1 - m*sin(t)**2), (t, 0, pi/2))) def test_F(): assert F(z, 0) == z assert F(0, m) == 0 assert F(pi*i/2, m) == i*K(m) assert F(z, oo) == 0 assert F(z, -oo) == 0 assert F(-z, m) == -F(z, m) assert F(z, m).diff(z) == 1/sqrt(1 - m*sin(z)**2) assert F(z, m).diff(m) == E(z, m)/(2*m*(1 - m)) - F(z, m)/(2*m) - \ sin(2*z)/(4*(1 - m)*sqrt(1 - m*sin(z)**2)) r = randcplx() assert td(F(z, r), z) assert td(F(r, m), m) mi = Symbol('m', real=False) assert F(z, mi).conjugate() == F(z.conjugate(), mi.conjugate()) mr = Symbol('m', real=True, negative=True) assert F(z, mr).conjugate() == F(z.conjugate(), mr) assert F(z, m).series(z) == \ z + z**5*(3*m**2/40 - m/30) + m*z**3/6 + O(z**6) assert F(z, m).rewrite(Integral).dummy_eq( Integral(1/sqrt(1 - m*sin(t)**2), (t, 0, z))) def test_E(): assert E(z, 0) == z assert E(0, m) == 0 assert E(i*pi/2, m) == i*E(m) assert E(z, oo) is zoo assert E(z, -oo) is zoo assert E(0) == pi/2 assert E(1) == 1 assert E(oo) == I*oo assert E(-oo) is oo assert E(zoo) is zoo assert E(-z, m) == -E(z, m) assert E(z, m).diff(z) == sqrt(1 - m*sin(z)**2) assert E(z, m).diff(m) == (E(z, m) - F(z, m))/(2*m) assert E(z).diff(z) == (E(z) - K(z))/(2*z) r = randcplx() assert td(E(r, m), m) assert td(E(z, r), z) assert td(E(z), z) mi = Symbol('m', real=False) assert E(z, mi).conjugate() == E(z.conjugate(), mi.conjugate()) assert E(mi).conjugate() == E(mi.conjugate()) mr = Symbol('m', real=True, negative=True) assert E(z, mr).conjugate() == E(z.conjugate(), mr) assert E(mr).conjugate() == E(mr) assert E(z).rewrite(hyper) == (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), z) assert tn(E(z), (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), z)) assert E(z).rewrite(meijerg) == \ -meijerg(((S.Half, Rational(3, 2)), []), ((S.Zero,), (S.Zero,)), -z)/4 assert tn(E(z), -meijerg(((S.Half, Rational(3, 2)), []), ((S.Zero,), (S.Zero,)), -z)/4) assert E(z, m).series(z) == \ z + z**5*(-m**2/40 + m/30) - m*z**3/6 + O(z**6) assert E(z).series(z) == pi/2 - pi*z/8 - 3*pi*z**2/128 - \ 5*pi*z**3/512 - 175*pi*z**4/32768 - 441*pi*z**5/131072 + O(z**6) assert E(z, m).rewrite(Integral).dummy_eq( Integral(sqrt(1 - m*sin(t)**2), (t, 0, z))) assert E(m).rewrite(Integral).dummy_eq( Integral(sqrt(1 - m*sin(t)**2), (t, 0, pi/2))) def test_P(): assert P(0, z, m) == F(z, m) assert P(1, z, m) == F(z, m) + \ (sqrt(1 - m*sin(z)**2)*tan(z) - E(z, m))/(1 - m) assert P(n, i*pi/2, m) == i*P(n, m) assert P(n, z, 0) == atanh(sqrt(n - 1)*tan(z))/sqrt(n - 1) assert P(n, z, n) == F(z, n) - P(1, z, n) + tan(z)/sqrt(1 - n*sin(z)**2) assert P(oo, z, m) == 0 assert P(-oo, z, m) == 0 assert P(n, z, oo) == 0 assert P(n, z, -oo) == 0 assert P(0, m) == K(m) assert P(1, m) is zoo assert P(n, 0) == pi/(2*sqrt(1 - n)) assert P(2, 1) is -oo assert P(-1, 1) is oo assert P(n, n) == E(n)/(1 - n) assert P(n, -z, m) == -P(n, z, m) ni, mi = Symbol('n', real=False), Symbol('m', real=False) assert P(ni, z, mi).conjugate() == \ P(ni.conjugate(), z.conjugate(), mi.conjugate()) nr, mr = Symbol('n', real=True, negative=True), \ Symbol('m', real=True, negative=True) assert P(nr, z, mr).conjugate() == P(nr, z.conjugate(), mr) assert P(n, m).conjugate() == P(n.conjugate(), m.conjugate()) assert P(n, z, m).diff(n) == (E(z, m) + (m - n)*F(z, m)/n + (n**2 - m)*P(n, z, m)/n - n*sqrt(1 - m*sin(z)**2)*sin(2*z)/(2*(1 - n*sin(z)**2)))/(2*(m - n)*(n - 1)) assert P(n, z, m).diff(z) == 1/(sqrt(1 - m*sin(z)**2)*(1 - n*sin(z)**2)) assert P(n, z, m).diff(m) == (E(z, m)/(m - 1) + P(n, z, m) - m*sin(2*z)/(2*(m - 1)*sqrt(1 - m*sin(z)**2)))/(2*(n - m)) assert P(n, m).diff(n) == (E(m) + (m - n)*K(m)/n + (n**2 - m)*P(n, m)/n)/(2*(m - n)*(n - 1)) assert P(n, m).diff(m) == (E(m)/(m - 1) + P(n, m))/(2*(n - m)) # These tests fail due to # https://github.com/fredrik-johansson/mpmath/issues/571#issuecomment-777201962 # https://github.com/sympy/sympy/issues/20933#issuecomment-777080385 # # rx, ry = randcplx(), randcplx() # assert td(P(n, rx, ry), n) # assert td(P(rx, z, ry), z) # assert td(P(rx, ry, m), m) assert P(n, z, m).series(z) == z + z**3*(m/6 + n/3) + \ z**5*(3*m**2/40 + m*n/10 - m/30 + n**2/5 - n/15) + O(z**6) assert P(n, z, m).rewrite(Integral).dummy_eq( Integral(1/((1 - n*sin(t)**2)*sqrt(1 - m*sin(t)**2)), (t, 0, z))) assert P(n, m).rewrite(Integral).dummy_eq( Integral(1/((1 - n*sin(t)**2)*sqrt(1 - m*sin(t)**2)), (t, 0, pi/2)))
d3e42eefce3a82357506e5695e9fdf59a859aca7bb9d01f0e4feff4b8ba633db
from sympy.concrete.summations import Sum from sympy.core.function import (Derivative, diff) from sympy.core.numbers import (Rational, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol) from sympy.functions.combinatorial.factorials import (RisingFactorial, binomial, factorial) from sympy.functions.elementary.complexes import conjugate 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 from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import hyper from sympy.functions.special.polynomials import (assoc_laguerre, assoc_legendre, chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, gegenbauer, hermite, jacobi, jacobi_normalized, laguerre, legendre) from sympy.polys.orthopolys import laguerre_poly from sympy.polys.polyroots import roots from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises x = Symbol('x') def test_jacobi(): n = Symbol("n") a = Symbol("a") b = Symbol("b") assert jacobi(0, a, b, x) == 1 assert jacobi(1, a, b, x) == a/2 - b/2 + x*(a/2 + b/2 + 1) assert jacobi(n, a, a, x) == RisingFactorial( a + 1, n)*gegenbauer(n, a + S.Half, x)/RisingFactorial(2*a + 1, n) assert jacobi(n, a, -a, x) == ((-1)**a*(-x + 1)**(-a/2)*(x + 1)**(a/2)*assoc_legendre(n, a, x)* factorial(-a + n)*gamma(a + n + 1)/(factorial(a + n)*gamma(n + 1))) assert jacobi(n, -b, b, x) == ((-x + 1)**(b/2)*(x + 1)**(-b/2)*assoc_legendre(n, b, x)* gamma(-b + n + 1)/gamma(n + 1)) assert jacobi(n, 0, 0, x) == legendre(n, x) assert jacobi(n, S.Half, S.Half, x) == RisingFactorial( Rational(3, 2), n)*chebyshevu(n, x)/factorial(n + 1) assert jacobi(n, Rational(-1, 2), Rational(-1, 2), x) == RisingFactorial( S.Half, n)*chebyshevt(n, x)/factorial(n) X = jacobi(n, a, b, x) assert isinstance(X, jacobi) assert jacobi(n, a, b, -x) == (-1)**n*jacobi(n, b, a, x) assert jacobi(n, a, b, 0) == 2**(-n)*gamma(a + n + 1)*hyper( (-b - n, -n), (a + 1,), -1)/(factorial(n)*gamma(a + 1)) assert jacobi(n, a, b, 1) == RisingFactorial(a + 1, n)/factorial(n) m = Symbol("m", positive=True) assert jacobi(m, a, b, oo) == oo*RisingFactorial(a + b + m + 1, m) assert unchanged(jacobi, n, a, b, oo) assert conjugate(jacobi(m, a, b, x)) == \ jacobi(m, conjugate(a), conjugate(b), conjugate(x)) _k = Dummy('k') assert diff(jacobi(n, a, b, x), n) == Derivative(jacobi(n, a, b, x), n) assert diff(jacobi(n, a, b, x), a).dummy_eq(Sum((jacobi(n, a, b, x) + (2*_k + a + b + 1)*RisingFactorial(_k + b + 1, -_k + n)*jacobi(_k, a, b, x)/((-_k + n)*RisingFactorial(_k + a + b + 1, -_k + n)))/(_k + a + b + n + 1), (_k, 0, n - 1))) assert diff(jacobi(n, a, b, x), b).dummy_eq(Sum(((-1)**(-_k + n)*(2*_k + a + b + 1)*RisingFactorial(_k + a + 1, -_k + n)*jacobi(_k, a, b, x)/ ((-_k + n)*RisingFactorial(_k + a + b + 1, -_k + n)) + jacobi(n, a, b, x))/(_k + a + b + n + 1), (_k, 0, n - 1))) assert diff(jacobi(n, a, b, x), x) == \ (a/2 + b/2 + n/2 + S.Half)*jacobi(n - 1, a + 1, b + 1, x) assert jacobi_normalized(n, a, b, x) == \ (jacobi(n, a, b, x)/sqrt(2**(a + b + 1)*gamma(a + n + 1)*gamma(b + n + 1) /((a + b + 2*n + 1)*factorial(n)*gamma(a + b + n + 1)))) raises(ValueError, lambda: jacobi(-2.1, a, b, x)) raises(ValueError, lambda: jacobi(Dummy(positive=True, integer=True), 1, 2, oo)) assert jacobi(n, a, b, x).rewrite("polynomial").dummy_eq(Sum((S.Half - x/2) **_k*RisingFactorial(-n, _k)*RisingFactorial(_k + a + 1, -_k + n)* RisingFactorial(a + b + n + 1, _k)/factorial(_k), (_k, 0, n))/factorial(n)) raises(ArgumentIndexError, lambda: jacobi(n, a, b, x).fdiff(5)) def test_gegenbauer(): n = Symbol("n") a = Symbol("a") assert gegenbauer(0, a, x) == 1 assert gegenbauer(1, a, x) == 2*a*x assert gegenbauer(2, a, x) == -a + x**2*(2*a**2 + 2*a) assert gegenbauer(3, a, x) == \ x**3*(4*a**3/3 + 4*a**2 + a*Rational(8, 3)) + x*(-2*a**2 - 2*a) assert gegenbauer(-1, a, x) == 0 assert gegenbauer(n, S.Half, x) == legendre(n, x) assert gegenbauer(n, 1, x) == chebyshevu(n, x) assert gegenbauer(n, -1, x) == 0 X = gegenbauer(n, a, x) assert isinstance(X, gegenbauer) assert gegenbauer(n, a, -x) == (-1)**n*gegenbauer(n, a, x) assert gegenbauer(n, a, 0) == 2**n*sqrt(pi) * \ gamma(a + n/2)/(gamma(a)*gamma(-n/2 + S.Half)*gamma(n + 1)) assert gegenbauer(n, a, 1) == gamma(2*a + n)/(gamma(2*a)*gamma(n + 1)) assert gegenbauer(n, Rational(3, 4), -1) is zoo assert gegenbauer(n, Rational(1, 4), -1) == (sqrt(2)*cos(pi*(n + S.One/4))* gamma(n + S.Half)/(sqrt(pi)*gamma(n + 1))) m = Symbol("m", positive=True) assert gegenbauer(m, a, oo) == oo*RisingFactorial(a, m) assert unchanged(gegenbauer, n, a, oo) assert conjugate(gegenbauer(n, a, x)) == gegenbauer(n, conjugate(a), conjugate(x)) _k = Dummy('k') assert diff(gegenbauer(n, a, x), n) == Derivative(gegenbauer(n, a, x), n) assert diff(gegenbauer(n, a, x), a).dummy_eq(Sum((2*(-1)**(-_k + n) + 2)* (_k + a)*gegenbauer(_k, a, x)/((-_k + n)*(_k + 2*a + n)) + ((2*_k + 2)/((_k + 2*a)*(2*_k + 2*a + 1)) + 2/(_k + 2*a + n))*gegenbauer(n, a , x), (_k, 0, n - 1))) assert diff(gegenbauer(n, a, x), x) == 2*a*gegenbauer(n - 1, a + 1, x) assert gegenbauer(n, a, x).rewrite('polynomial').dummy_eq( Sum((-1)**_k*(2*x)**(-2*_k + n)*RisingFactorial(a, -_k + n) /(factorial(_k)*factorial(-2*_k + n)), (_k, 0, floor(n/2)))) raises(ArgumentIndexError, lambda: gegenbauer(n, a, x).fdiff(4)) def test_legendre(): assert legendre(0, x) == 1 assert legendre(1, x) == x assert legendre(2, x) == ((3*x**2 - 1)/2).expand() assert legendre(3, x) == ((5*x**3 - 3*x)/2).expand() assert legendre(4, x) == ((35*x**4 - 30*x**2 + 3)/8).expand() assert legendre(5, x) == ((63*x**5 - 70*x**3 + 15*x)/8).expand() assert legendre(6, x) == ((231*x**6 - 315*x**4 + 105*x**2 - 5)/16).expand() assert legendre(10, -1) == 1 assert legendre(11, -1) == -1 assert legendre(10, 1) == 1 assert legendre(11, 1) == 1 assert legendre(10, 0) != 0 assert legendre(11, 0) == 0 assert legendre(-1, x) == 1 k = Symbol('k') assert legendre(5 - k, x).subs(k, 2) == ((5*x**3 - 3*x)/2).expand() assert roots(legendre(4, x), x) == { sqrt(Rational(3, 7) - Rational(2, 35)*sqrt(30)): 1, -sqrt(Rational(3, 7) - Rational(2, 35)*sqrt(30)): 1, sqrt(Rational(3, 7) + Rational(2, 35)*sqrt(30)): 1, -sqrt(Rational(3, 7) + Rational(2, 35)*sqrt(30)): 1, } n = Symbol("n") X = legendre(n, x) assert isinstance(X, legendre) assert unchanged(legendre, n, x) assert legendre(n, 0) == sqrt(pi)/(gamma(S.Half - n/2)*gamma(n/2 + 1)) assert legendre(n, 1) == 1 assert legendre(n, oo) is oo assert legendre(-n, x) == legendre(n - 1, x) assert legendre(n, -x) == (-1)**n*legendre(n, x) assert unchanged(legendre, -n + k, x) assert conjugate(legendre(n, x)) == legendre(n, conjugate(x)) assert diff(legendre(n, x), x) == \ n*(x*legendre(n, x) - legendre(n - 1, x))/(x**2 - 1) assert diff(legendre(n, x), n) == Derivative(legendre(n, x), n) _k = Dummy('k') assert legendre(n, x).rewrite("polynomial").dummy_eq(Sum((-1)**_k*(S.Half - x/2)**_k*(x/2 + S.Half)**(-_k + n)*binomial(n, _k)**2, (_k, 0, n))) raises(ArgumentIndexError, lambda: legendre(n, x).fdiff(1)) raises(ArgumentIndexError, lambda: legendre(n, x).fdiff(3)) def test_assoc_legendre(): Plm = assoc_legendre Q = sqrt(1 - x**2) assert Plm(0, 0, x) == 1 assert Plm(1, 0, x) == x assert Plm(1, 1, x) == -Q assert Plm(2, 0, x) == (3*x**2 - 1)/2 assert Plm(2, 1, x) == -3*x*Q assert Plm(2, 2, x) == 3*Q**2 assert Plm(3, 0, x) == (5*x**3 - 3*x)/2 assert Plm(3, 1, x).expand() == (( 3*(1 - 5*x**2)/2 ).expand() * Q).expand() assert Plm(3, 2, x) == 15*x * Q**2 assert Plm(3, 3, x) == -15 * Q**3 # negative m assert Plm(1, -1, x) == -Plm(1, 1, x)/2 assert Plm(2, -2, x) == Plm(2, 2, x)/24 assert Plm(2, -1, x) == -Plm(2, 1, x)/6 assert Plm(3, -3, x) == -Plm(3, 3, x)/720 assert Plm(3, -2, x) == Plm(3, 2, x)/120 assert Plm(3, -1, x) == -Plm(3, 1, x)/12 n = Symbol("n") m = Symbol("m") X = Plm(n, m, x) assert isinstance(X, assoc_legendre) assert Plm(n, 0, x) == legendre(n, x) assert Plm(n, m, 0) == 2**m*sqrt(pi)/(gamma(-m/2 - n/2 + S.Half)*gamma(-m/2 + n/2 + 1)) assert diff(Plm(m, n, x), x) == (m*x*assoc_legendre(m, n, x) - (m + n)*assoc_legendre(m - 1, n, x))/(x**2 - 1) _k = Dummy('k') assert Plm(m, n, x).rewrite("polynomial").dummy_eq( (1 - x**2)**(n/2)*Sum((-1)**_k*2**(-m)*x**(-2*_k + m - n)*factorial (-2*_k + 2*m)/(factorial(_k)*factorial(-_k + m)*factorial(-2*_k + m - n)), (_k, 0, floor(m/2 - n/2)))) assert conjugate(assoc_legendre(n, m, x)) == \ assoc_legendre(n, conjugate(m), conjugate(x)) raises(ValueError, lambda: Plm(0, 1, x)) raises(ValueError, lambda: Plm(-1, 1, x)) raises(ArgumentIndexError, lambda: Plm(n, m, x).fdiff(1)) raises(ArgumentIndexError, lambda: Plm(n, m, x).fdiff(2)) raises(ArgumentIndexError, lambda: Plm(n, m, x).fdiff(4)) def test_chebyshev(): assert chebyshevt(0, x) == 1 assert chebyshevt(1, x) == x assert chebyshevt(2, x) == 2*x**2 - 1 assert chebyshevt(3, x) == 4*x**3 - 3*x for n in range(1, 4): for k in range(n): z = chebyshevt_root(n, k) assert chebyshevt(n, z) == 0 raises(ValueError, lambda: chebyshevt_root(n, n)) for n in range(1, 4): for k in range(n): z = chebyshevu_root(n, k) assert chebyshevu(n, z) == 0 raises(ValueError, lambda: chebyshevu_root(n, n)) n = Symbol("n") X = chebyshevt(n, x) assert isinstance(X, chebyshevt) assert unchanged(chebyshevt, n, x) assert chebyshevt(n, -x) == (-1)**n*chebyshevt(n, x) assert chebyshevt(-n, x) == chebyshevt(n, x) assert chebyshevt(n, 0) == cos(pi*n/2) assert chebyshevt(n, 1) == 1 assert chebyshevt(n, oo) is oo assert conjugate(chebyshevt(n, x)) == chebyshevt(n, conjugate(x)) assert diff(chebyshevt(n, x), x) == n*chebyshevu(n - 1, x) X = chebyshevu(n, x) assert isinstance(X, chebyshevu) y = Symbol('y') assert chebyshevu(n, -x) == (-1)**n*chebyshevu(n, x) assert chebyshevu(-n, x) == -chebyshevu(n - 2, x) assert unchanged(chebyshevu, -n + y, x) assert chebyshevu(n, 0) == cos(pi*n/2) assert chebyshevu(n, 1) == n + 1 assert chebyshevu(n, oo) is oo assert conjugate(chebyshevu(n, x)) == chebyshevu(n, conjugate(x)) assert diff(chebyshevu(n, x), x) == \ (-x*chebyshevu(n, x) + (n + 1)*chebyshevt(n + 1, x))/(x**2 - 1) _k = Dummy('k') assert chebyshevt(n, x).rewrite("polynomial").dummy_eq(Sum(x**(-2*_k + n) *(x**2 - 1)**_k*binomial(n, 2*_k), (_k, 0, floor(n/2)))) assert chebyshevu(n, x).rewrite("polynomial").dummy_eq(Sum((-1)**_k*(2*x) **(-2*_k + n)*factorial(-_k + n)/(factorial(_k)* factorial(-2*_k + n)), (_k, 0, floor(n/2)))) raises(ArgumentIndexError, lambda: chebyshevt(n, x).fdiff(1)) raises(ArgumentIndexError, lambda: chebyshevt(n, x).fdiff(3)) raises(ArgumentIndexError, lambda: chebyshevu(n, x).fdiff(1)) raises(ArgumentIndexError, lambda: chebyshevu(n, x).fdiff(3)) def test_hermite(): assert hermite(0, x) == 1 assert hermite(1, x) == 2*x assert hermite(2, x) == 4*x**2 - 2 assert hermite(3, x) == 8*x**3 - 12*x assert hermite(4, x) == 16*x**4 - 48*x**2 + 12 assert hermite(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120 n = Symbol("n") assert unchanged(hermite, n, x) assert hermite(n, -x) == (-1)**n*hermite(n, x) assert unchanged(hermite, -n, x) assert hermite(n, 0) == 2**n*sqrt(pi)/gamma(S.Half - n/2) assert hermite(n, oo) is oo assert conjugate(hermite(n, x)) == hermite(n, conjugate(x)) _k = Dummy('k') assert hermite(n, x).rewrite("polynomial").dummy_eq(factorial(n)*Sum((-1) **_k*(2*x)**(-2*_k + n)/(factorial(_k)*factorial(-2*_k + n)), (_k, 0, floor(n/2)))) assert diff(hermite(n, x), x) == 2*n*hermite(n - 1, x) assert diff(hermite(n, x), n) == Derivative(hermite(n, x), n) raises(ArgumentIndexError, lambda: hermite(n, x).fdiff(3)) def test_laguerre(): n = Symbol("n") m = Symbol("m", negative=True) # Laguerre polynomials: assert laguerre(0, x) == 1 assert laguerre(1, x) == -x + 1 assert laguerre(2, x) == x**2/2 - 2*x + 1 assert laguerre(3, x) == -x**3/6 + 3*x**2/2 - 3*x + 1 assert laguerre(-2, x) == (x + 1)*exp(x) X = laguerre(n, x) assert isinstance(X, laguerre) assert laguerre(n, 0) == 1 assert laguerre(n, oo) == (-1)**n*oo assert laguerre(n, -oo) is oo assert conjugate(laguerre(n, x)) == laguerre(n, conjugate(x)) _k = Dummy('k') assert laguerre(n, x).rewrite("polynomial").dummy_eq( Sum(x**_k*RisingFactorial(-n, _k)/factorial(_k)**2, (_k, 0, n))) assert laguerre(m, x).rewrite("polynomial").dummy_eq( exp(x)*Sum((-x)**_k*RisingFactorial(m + 1, _k)/factorial(_k)**2, (_k, 0, -m - 1))) assert diff(laguerre(n, x), x) == -assoc_laguerre(n - 1, 1, x) k = Symbol('k') assert laguerre(-n, x) == exp(x)*laguerre(n - 1, -x) assert laguerre(-3, x) == exp(x)*laguerre(2, -x) assert unchanged(laguerre, -n + k, x) raises(ValueError, lambda: laguerre(-2.1, x)) raises(ValueError, lambda: laguerre(Rational(5, 2), x)) raises(ArgumentIndexError, lambda: laguerre(n, x).fdiff(1)) raises(ArgumentIndexError, lambda: laguerre(n, x).fdiff(3)) def test_assoc_laguerre(): n = Symbol("n") m = Symbol("m") alpha = Symbol("alpha") # generalized Laguerre polynomials: assert assoc_laguerre(0, alpha, x) == 1 assert assoc_laguerre(1, alpha, x) == -x + alpha + 1 assert assoc_laguerre(2, alpha, x).expand() == \ (x**2/2 - (alpha + 2)*x + (alpha + 2)*(alpha + 1)/2).expand() assert assoc_laguerre(3, alpha, x).expand() == \ (-x**3/6 + (alpha + 3)*x**2/2 - (alpha + 2)*(alpha + 3)*x/2 + (alpha + 1)*(alpha + 2)*(alpha + 3)/6).expand() # Test the lowest 10 polynomials with laguerre_poly, to make sure it works: for i in range(10): assert assoc_laguerre(i, 0, x).expand() == laguerre_poly(i, x) X = assoc_laguerre(n, m, x) assert isinstance(X, assoc_laguerre) assert assoc_laguerre(n, 0, x) == laguerre(n, x) assert assoc_laguerre(n, alpha, 0) == binomial(alpha + n, alpha) p = Symbol("p", positive=True) assert assoc_laguerre(p, alpha, oo) == (-1)**p*oo assert assoc_laguerre(p, alpha, -oo) is oo assert diff(assoc_laguerre(n, alpha, x), x) == \ -assoc_laguerre(n - 1, alpha + 1, x) _k = Dummy('k') assert diff(assoc_laguerre(n, alpha, x), alpha).dummy_eq( Sum(assoc_laguerre(_k, alpha, x)/(-alpha + n), (_k, 0, n - 1))) assert conjugate(assoc_laguerre(n, alpha, x)) == \ assoc_laguerre(n, conjugate(alpha), conjugate(x)) assert assoc_laguerre(n, alpha, x).rewrite('polynomial').dummy_eq( gamma(alpha + n + 1)*Sum(x**_k*RisingFactorial(-n, _k)/ (factorial(_k)*gamma(_k + alpha + 1)), (_k, 0, n))/factorial(n)) raises(ValueError, lambda: assoc_laguerre(-2.1, alpha, x)) raises(ArgumentIndexError, lambda: assoc_laguerre(n, alpha, x).fdiff(1)) raises(ArgumentIndexError, lambda: assoc_laguerre(n, alpha, x).fdiff(4))
a51dd60bf85893c5189644d02c25c5c91802770aac486fc40789ba6b680133f0
from sympy.core.function import expand_func from sympy.core import EulerGamma from sympy.core.numbers import (I, Rational, nan, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol) from sympy.functions.combinatorial.factorials import factorial from sympy.functions.combinatorial.numbers import harmonic from sympy.functions.elementary.complexes import (Abs, conjugate, im, re) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import tanh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.error_functions import (Ei, erf, erfc) from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma, lowergamma, multigamma, polygamma, trigamma, uppergamma) from sympy.functions.special.zeta_functions import zeta from sympy.series.order import O from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises from sympy.testing.randtest import (test_derivative_numerically as td, random_complex_number as randcplx, verify_numerically as tn) x = Symbol('x') y = Symbol('y') n = Symbol('n', integer=True) w = Symbol('w', real=True) def test_gamma(): assert gamma(nan) is nan assert gamma(oo) is oo assert gamma(-100) is zoo assert gamma(0) is zoo assert gamma(-100.0) is zoo assert gamma(1) == 1 assert gamma(2) == 1 assert gamma(3) == 2 assert gamma(102) == factorial(101) assert gamma(S.Half) == sqrt(pi) assert gamma(Rational(3, 2)) == sqrt(pi)*S.Half assert gamma(Rational(5, 2)) == sqrt(pi)*Rational(3, 4) assert gamma(Rational(7, 2)) == sqrt(pi)*Rational(15, 8) assert gamma(Rational(-1, 2)) == -2*sqrt(pi) assert gamma(Rational(-3, 2)) == sqrt(pi)*Rational(4, 3) assert gamma(Rational(-5, 2)) == sqrt(pi)*Rational(-8, 15) assert gamma(Rational(-15, 2)) == sqrt(pi)*Rational(256, 2027025) assert gamma(Rational( -11, 8)).expand(func=True) == Rational(64, 33)*gamma(Rational(5, 8)) assert gamma(Rational( -10, 3)).expand(func=True) == Rational(81, 280)*gamma(Rational(2, 3)) assert gamma(Rational( 14, 3)).expand(func=True) == Rational(880, 81)*gamma(Rational(2, 3)) assert gamma(Rational( 17, 7)).expand(func=True) == Rational(30, 49)*gamma(Rational(3, 7)) assert gamma(Rational( 19, 8)).expand(func=True) == Rational(33, 64)*gamma(Rational(3, 8)) assert gamma(x).diff(x) == gamma(x)*polygamma(0, x) assert gamma(x - 1).expand(func=True) == gamma(x)/(x - 1) assert gamma(x + 2).expand(func=True, mul=False) == x*(x + 1)*gamma(x) assert conjugate(gamma(x)) == gamma(conjugate(x)) assert expand_func(gamma(x + Rational(3, 2))) == \ (x + S.Half)*gamma(x + S.Half) assert expand_func(gamma(x - S.Half)) == \ gamma(S.Half + x)/(x - S.Half) # Test a bug: assert expand_func(gamma(x + Rational(3, 4))) == gamma(x + Rational(3, 4)) # XXX: Not sure about these tests. I can fix them by defining e.g. # exp_polar.is_integer but I'm not sure if that makes sense. assert gamma(3*exp_polar(I*pi)/4).is_nonnegative is False assert gamma(3*exp_polar(I*pi)/4).is_extended_nonpositive is True y = Symbol('y', nonpositive=True, integer=True) assert gamma(y).is_real == False y = Symbol('y', positive=True, noninteger=True) assert gamma(y).is_real == True assert gamma(-1.0, evaluate=False).is_real == False assert gamma(0, evaluate=False).is_real == False assert gamma(-2, evaluate=False).is_real == False def test_gamma_rewrite(): assert gamma(n).rewrite(factorial) == factorial(n - 1) def test_gamma_series(): assert gamma(x + 1).series(x, 0, 3) == \ 1 - EulerGamma*x + x**2*(EulerGamma**2/2 + pi**2/12) + O(x**3) assert gamma(x).series(x, -1, 3) == \ -1/(x + 1) + EulerGamma - 1 + (x + 1)*(-1 - pi**2/12 - EulerGamma**2/2 + \ EulerGamma) + (x + 1)**2*(-1 - pi**2/12 - EulerGamma**2/2 + EulerGamma**3/6 - \ polygamma(2, 1)/6 + EulerGamma*pi**2/12 + EulerGamma) + O((x + 1)**3, (x, -1)) def tn_branch(s, func): from random import uniform c = uniform(1, 5) expr = func(s, c*exp_polar(I*pi)) - func(s, c*exp_polar(-I*pi)) eps = 1e-15 expr2 = func(s + eps, -c + eps*I) - func(s + eps, -c - eps*I) return abs(expr.n() - expr2.n()).n() < 1e-10 def test_lowergamma(): from sympy.functions.special.error_functions import expint from sympy.functions.special.hyper import meijerg assert lowergamma(x, 0) == 0 assert lowergamma(x, y).diff(y) == y**(x - 1)*exp(-y) assert td(lowergamma(randcplx(), y), y) assert td(lowergamma(x, randcplx()), x) assert lowergamma(x, y).diff(x) == \ gamma(x)*digamma(x) - uppergamma(x, y)*log(y) \ - meijerg([], [1, 1], [0, 0, x], [], y) assert lowergamma(S.Half, x) == sqrt(pi)*erf(sqrt(x)) assert not lowergamma(S.Half - 3, x).has(lowergamma) assert not lowergamma(S.Half + 3, x).has(lowergamma) assert lowergamma(S.Half, x, evaluate=False).has(lowergamma) assert tn(lowergamma(S.Half + 3, x, evaluate=False), lowergamma(S.Half + 3, x), x) assert tn(lowergamma(S.Half - 3, x, evaluate=False), lowergamma(S.Half - 3, x), x) assert tn_branch(-3, lowergamma) assert tn_branch(-4, lowergamma) assert tn_branch(Rational(1, 3), lowergamma) assert tn_branch(pi, lowergamma) assert lowergamma(3, exp_polar(4*pi*I)*x) == lowergamma(3, x) assert lowergamma(y, exp_polar(5*pi*I)*x) == \ exp(4*I*pi*y)*lowergamma(y, x*exp_polar(pi*I)) assert lowergamma(-2, exp_polar(5*pi*I)*x) == \ lowergamma(-2, x*exp_polar(I*pi)) + 2*pi*I assert conjugate(lowergamma(x, y)) == lowergamma(conjugate(x), conjugate(y)) assert conjugate(lowergamma(x, 0)) == 0 assert unchanged(conjugate, lowergamma(x, -oo)) assert lowergamma(0, x)._eval_is_meromorphic(x, 0) == False assert lowergamma(S(1)/3, x)._eval_is_meromorphic(x, 0) == False assert lowergamma(1, x, evaluate=False)._eval_is_meromorphic(x, 0) == True assert lowergamma(x, x)._eval_is_meromorphic(x, 0) == False assert lowergamma(x + 1, x)._eval_is_meromorphic(x, 0) == False assert lowergamma(1/x, x)._eval_is_meromorphic(x, 0) == False assert lowergamma(0, x + 1)._eval_is_meromorphic(x, 0) == False assert lowergamma(S(1)/3, x + 1)._eval_is_meromorphic(x, 0) == True assert lowergamma(1, x + 1, evaluate=False)._eval_is_meromorphic(x, 0) == True assert lowergamma(x, x + 1)._eval_is_meromorphic(x, 0) == True assert lowergamma(x + 1, x + 1)._eval_is_meromorphic(x, 0) == True assert lowergamma(1/x, x + 1)._eval_is_meromorphic(x, 0) == False assert lowergamma(0, 1/x)._eval_is_meromorphic(x, 0) == False assert lowergamma(S(1)/3, 1/x)._eval_is_meromorphic(x, 0) == False assert lowergamma(1, 1/x, evaluate=False)._eval_is_meromorphic(x, 0) == False assert lowergamma(x, 1/x)._eval_is_meromorphic(x, 0) == False assert lowergamma(x + 1, 1/x)._eval_is_meromorphic(x, 0) == False assert lowergamma(1/x, 1/x)._eval_is_meromorphic(x, 0) == False assert lowergamma(x, 2).series(x, oo, 3) == \ 2**x*(1 + 2/(x + 1))*exp(-2)/x + O(exp(x*log(2))/x**3, (x, oo)) assert lowergamma( x, y).rewrite(expint) == -y**x*expint(-x + 1, y) + gamma(x) k = Symbol('k', integer=True) assert lowergamma( k, y).rewrite(expint) == -y**k*expint(-k + 1, y) + gamma(k) k = Symbol('k', integer=True, positive=False) assert lowergamma(k, y).rewrite(expint) == lowergamma(k, y) assert lowergamma(x, y).rewrite(uppergamma) == gamma(x) - uppergamma(x, y) assert lowergamma(70, 6) == factorial(69) - 69035724522603011058660187038367026272747334489677105069435923032634389419656200387949342530805432320 * exp(-6) assert (lowergamma(S(77) / 2, 6) - lowergamma(S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 assert (lowergamma(-S(77) / 2, 6) - lowergamma(-S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 def test_uppergamma(): from sympy.functions.special.error_functions import expint from sympy.functions.special.hyper import meijerg assert uppergamma(4, 0) == 6 assert uppergamma(x, y).diff(y) == -y**(x - 1)*exp(-y) assert td(uppergamma(randcplx(), y), y) assert uppergamma(x, y).diff(x) == \ uppergamma(x, y)*log(y) + meijerg([], [1, 1], [0, 0, x], [], y) assert td(uppergamma(x, randcplx()), x) p = Symbol('p', positive=True) assert uppergamma(0, p) == -Ei(-p) assert uppergamma(p, 0) == gamma(p) assert uppergamma(S.Half, x) == sqrt(pi)*erfc(sqrt(x)) assert not uppergamma(S.Half - 3, x).has(uppergamma) assert not uppergamma(S.Half + 3, x).has(uppergamma) assert uppergamma(S.Half, x, evaluate=False).has(uppergamma) assert tn(uppergamma(S.Half + 3, x, evaluate=False), uppergamma(S.Half + 3, x), x) assert tn(uppergamma(S.Half - 3, x, evaluate=False), uppergamma(S.Half - 3, x), x) assert unchanged(uppergamma, x, -oo) assert unchanged(uppergamma, x, 0) assert tn_branch(-3, uppergamma) assert tn_branch(-4, uppergamma) assert tn_branch(Rational(1, 3), uppergamma) assert tn_branch(pi, uppergamma) assert uppergamma(3, exp_polar(4*pi*I)*x) == uppergamma(3, x) assert uppergamma(y, exp_polar(5*pi*I)*x) == \ exp(4*I*pi*y)*uppergamma(y, x*exp_polar(pi*I)) + \ gamma(y)*(1 - exp(4*pi*I*y)) assert uppergamma(-2, exp_polar(5*pi*I)*x) == \ uppergamma(-2, x*exp_polar(I*pi)) - 2*pi*I assert uppergamma(-2, x) == expint(3, x)/x**2 assert conjugate(uppergamma(x, y)) == uppergamma(conjugate(x), conjugate(y)) assert unchanged(conjugate, uppergamma(x, -oo)) assert uppergamma(x, y).rewrite(expint) == y**x*expint(-x + 1, y) assert uppergamma(x, y).rewrite(lowergamma) == gamma(x) - lowergamma(x, y) assert uppergamma(70, 6) == 69035724522603011058660187038367026272747334489677105069435923032634389419656200387949342530805432320*exp(-6) assert (uppergamma(S(77) / 2, 6) - uppergamma(S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 assert (uppergamma(-S(77) / 2, 6) - uppergamma(-S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 def test_polygamma(): assert polygamma(n, nan) is nan assert polygamma(0, oo) is oo assert polygamma(0, -oo) is oo assert polygamma(0, I*oo) is oo assert polygamma(0, -I*oo) is oo assert polygamma(1, oo) == 0 assert polygamma(5, oo) == 0 assert polygamma(0, -9) is zoo assert polygamma(0, -9) is zoo assert polygamma(0, -1) is zoo assert polygamma(0, 0) is zoo assert polygamma(0, 1) == -EulerGamma assert polygamma(0, 7) == Rational(49, 20) - EulerGamma assert polygamma(1, 1) == pi**2/6 assert polygamma(1, 2) == pi**2/6 - 1 assert polygamma(1, 3) == pi**2/6 - Rational(5, 4) assert polygamma(3, 1) == pi**4 / 15 assert polygamma(3, 5) == 6*(Rational(-22369, 20736) + pi**4/90) assert polygamma(5, 1) == 8 * pi**6 / 63 assert polygamma(1, S.Half) == pi**2 / 2 assert polygamma(2, S.Half) == -14*zeta(3) assert polygamma(11, S.Half) == 176896*pi**12 def t(m, n): x = S(m)/n r = polygamma(0, x) if r.has(polygamma): return False return abs(polygamma(0, x.n()).n() - r.n()).n() < 1e-10 assert t(1, 2) assert t(3, 2) assert t(-1, 2) assert t(1, 4) assert t(-3, 4) assert t(1, 3) assert t(4, 3) assert t(3, 4) assert t(2, 3) assert t(123, 5) assert polygamma(0, x).rewrite(zeta) == polygamma(0, x) assert polygamma(1, x).rewrite(zeta) == zeta(2, x) assert polygamma(2, x).rewrite(zeta) == -2*zeta(3, x) assert polygamma(I, 2).rewrite(zeta) == polygamma(I, 2) n1 = Symbol('n1') n2 = Symbol('n2', real=True) n3 = Symbol('n3', integer=True) n4 = Symbol('n4', positive=True) n5 = Symbol('n5', positive=True, integer=True) assert polygamma(n1, x).rewrite(zeta) == polygamma(n1, x) assert polygamma(n2, x).rewrite(zeta) == polygamma(n2, x) assert polygamma(n3, x).rewrite(zeta) == polygamma(n3, x) assert polygamma(n4, x).rewrite(zeta) == polygamma(n4, x) assert polygamma(n5, x).rewrite(zeta) == (-1)**(n5 + 1) * factorial(n5) * zeta(n5 + 1, x) assert polygamma(3, 7*x).diff(x) == 7*polygamma(4, 7*x) assert polygamma(0, x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma assert polygamma(2, x).rewrite(harmonic) == 2*harmonic(x - 1, 3) - 2*zeta(3) ni = Symbol("n", integer=True) assert polygamma(ni, x).rewrite(harmonic) == (-1)**(ni + 1)*(-harmonic(x - 1, ni + 1) + zeta(ni + 1))*factorial(ni) # Polygamma of non-negative integer order is unbranched: k = Symbol('n', integer=True, nonnegative=True) assert polygamma(k, exp_polar(2*I*pi)*x) == polygamma(k, x) # but negative integers are branched! k = Symbol('n', integer=True) assert polygamma(k, exp_polar(2*I*pi)*x).args == (k, exp_polar(2*I*pi)*x) # Polygamma of order -1 is loggamma: assert polygamma(-1, x) == loggamma(x) # But smaller orders are iterated integrals and don't have a special name assert polygamma(-2, x).func is polygamma # Test a bug assert polygamma(0, -x).expand(func=True) == polygamma(0, -x) assert polygamma(2, 2.5).is_positive == False assert polygamma(2, -2.5).is_positive == False assert polygamma(3, 2.5).is_positive == True assert polygamma(3, -2.5).is_positive is True assert polygamma(-2, -2.5).is_positive is None assert polygamma(-3, -2.5).is_positive is None assert polygamma(2, 2.5).is_negative == True assert polygamma(3, 2.5).is_negative == False assert polygamma(3, -2.5).is_negative == False assert polygamma(2, -2.5).is_negative is True assert polygamma(-2, -2.5).is_negative is None assert polygamma(-3, -2.5).is_negative is None assert polygamma(I, 2).is_positive is None assert polygamma(I, 3).is_negative is None # issue 17350 assert polygamma(pi, 3).evalf() == polygamma(pi, 3) assert (I*polygamma(I, pi)).as_real_imag() == \ (-im(polygamma(I, pi)), re(polygamma(I, pi))) assert (tanh(polygamma(I, 1))).rewrite(exp) == \ (exp(polygamma(I, 1)) - exp(-polygamma(I, 1)))/(exp(polygamma(I, 1)) + exp(-polygamma(I, 1))) assert (I / polygamma(I, 4)).rewrite(exp) == \ I*sqrt(re(polygamma(I, 4))**2 + im(polygamma(I, 4))**2)\ /((re(polygamma(I, 4)) + I*im(polygamma(I, 4)))*Abs(polygamma(I, 4))) assert unchanged(polygamma, 2.3, 1.0) # issue 12569 assert unchanged(im, polygamma(0, I)) assert polygamma(Symbol('a', positive=True), Symbol('b', positive=True)).is_real is True assert polygamma(0, I).is_real is None def test_polygamma_expand_func(): assert polygamma(0, x).expand(func=True) == polygamma(0, x) assert polygamma(0, 2*x).expand(func=True) == \ polygamma(0, x)/2 + polygamma(0, S.Half + x)/2 + log(2) assert polygamma(1, 2*x).expand(func=True) == \ polygamma(1, x)/4 + polygamma(1, S.Half + x)/4 assert polygamma(2, x).expand(func=True) == \ polygamma(2, x) assert polygamma(0, -1 + x).expand(func=True) == \ polygamma(0, x) - 1/(x - 1) assert polygamma(0, 1 + x).expand(func=True) == \ 1/x + polygamma(0, x ) assert polygamma(0, 2 + x).expand(func=True) == \ 1/x + 1/(1 + x) + polygamma(0, x) assert polygamma(0, 3 + x).expand(func=True) == \ polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) assert polygamma(0, 4 + x).expand(func=True) == \ polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) + 1/(3 + x) assert polygamma(1, 1 + x).expand(func=True) == \ polygamma(1, x) - 1/x**2 assert polygamma(1, 2 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 assert polygamma(1, 3 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - 1/(2 + x)**2 assert polygamma(1, 4 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - \ 1/(2 + x)**2 - 1/(3 + x)**2 assert polygamma(0, x + y).expand(func=True) == \ polygamma(0, x + y) assert polygamma(1, x + y).expand(func=True) == \ polygamma(1, x + y) assert polygamma(1, 3 + 4*x + y).expand(func=True, multinomial=False) == \ polygamma(1, y + 4*x) - 1/(y + 4*x)**2 - \ 1/(1 + y + 4*x)**2 - 1/(2 + y + 4*x)**2 assert polygamma(3, 3 + 4*x + y).expand(func=True, multinomial=False) == \ polygamma(3, y + 4*x) - 6/(y + 4*x)**4 - \ 6/(1 + y + 4*x)**4 - 6/(2 + y + 4*x)**4 assert polygamma(3, 4*x + y + 1).expand(func=True, multinomial=False) == \ polygamma(3, y + 4*x) - 6/(y + 4*x)**4 e = polygamma(3, 4*x + y + Rational(3, 2)) assert e.expand(func=True) == e e = polygamma(3, x + y + Rational(3, 4)) assert e.expand(func=True, basic=False) == e def test_digamma(): assert digamma(nan) == nan assert digamma(oo) == oo assert digamma(-oo) == oo assert digamma(I*oo) == oo assert digamma(-I*oo) == oo assert digamma(-9) == zoo assert digamma(-9) == zoo assert digamma(-1) == zoo assert digamma(0) == zoo assert digamma(1) == -EulerGamma assert digamma(7) == Rational(49, 20) - EulerGamma def t(m, n): x = S(m)/n r = digamma(x) if r.has(digamma): return False return abs(digamma(x.n()).n() - r.n()).n() < 1e-10 assert t(1, 2) assert t(3, 2) assert t(-1, 2) assert t(1, 4) assert t(-3, 4) assert t(1, 3) assert t(4, 3) assert t(3, 4) assert t(2, 3) assert t(123, 5) assert digamma(x).rewrite(zeta) == polygamma(0, x) assert digamma(x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma assert digamma(I).is_real is None assert digamma(x,evaluate=False).fdiff() == polygamma(1, x) assert digamma(x,evaluate=False).is_real is None assert digamma(x,evaluate=False).is_positive is None assert digamma(x,evaluate=False).is_negative is None assert digamma(x,evaluate=False).rewrite(polygamma) == polygamma(0, x) def test_digamma_expand_func(): assert digamma(x).expand(func=True) == polygamma(0, x) assert digamma(2*x).expand(func=True) == \ polygamma(0, x)/2 + polygamma(0, Rational(1, 2) + x)/2 + log(2) assert digamma(-1 + x).expand(func=True) == \ polygamma(0, x) - 1/(x - 1) assert digamma(1 + x).expand(func=True) == \ 1/x + polygamma(0, x ) assert digamma(2 + x).expand(func=True) == \ 1/x + 1/(1 + x) + polygamma(0, x) assert digamma(3 + x).expand(func=True) == \ polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) assert digamma(4 + x).expand(func=True) == \ polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) + 1/(3 + x) assert digamma(x + y).expand(func=True) == \ polygamma(0, x + y) def test_trigamma(): assert trigamma(nan) == nan assert trigamma(oo) == 0 assert trigamma(1) == pi**2/6 assert trigamma(2) == pi**2/6 - 1 assert trigamma(3) == pi**2/6 - Rational(5, 4) assert trigamma(x, evaluate=False).rewrite(zeta) == zeta(2, x) assert trigamma(x, evaluate=False).rewrite(harmonic) == \ trigamma(x).rewrite(polygamma).rewrite(harmonic) assert trigamma(x,evaluate=False).fdiff() == polygamma(2, x) assert trigamma(x,evaluate=False).is_real is None assert trigamma(x,evaluate=False).is_positive is None assert trigamma(x,evaluate=False).is_negative is None assert trigamma(x,evaluate=False).rewrite(polygamma) == polygamma(1, x) def test_trigamma_expand_func(): assert trigamma(2*x).expand(func=True) == \ polygamma(1, x)/4 + polygamma(1, Rational(1, 2) + x)/4 assert trigamma(1 + x).expand(func=True) == \ polygamma(1, x) - 1/x**2 assert trigamma(2 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 assert trigamma(3 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - 1/(2 + x)**2 assert trigamma(4 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - \ 1/(2 + x)**2 - 1/(3 + x)**2 assert trigamma(x + y).expand(func=True) == \ polygamma(1, x + y) assert trigamma(3 + 4*x + y).expand(func=True, multinomial=False) == \ polygamma(1, y + 4*x) - 1/(y + 4*x)**2 - \ 1/(1 + y + 4*x)**2 - 1/(2 + y + 4*x)**2 def test_loggamma(): raises(TypeError, lambda: loggamma(2, 3)) raises(ArgumentIndexError, lambda: loggamma(x).fdiff(2)) assert loggamma(-1) is oo assert loggamma(-2) is oo assert loggamma(0) is oo assert loggamma(1) == 0 assert loggamma(2) == 0 assert loggamma(3) == log(2) assert loggamma(4) == log(6) n = Symbol("n", integer=True, positive=True) assert loggamma(n) == log(gamma(n)) assert loggamma(-n) is oo assert loggamma(n/2) == log(2**(-n + 1)*sqrt(pi)*gamma(n)/gamma(n/2 + S.Half)) assert loggamma(oo) is oo assert loggamma(-oo) is zoo assert loggamma(I*oo) is zoo assert loggamma(-I*oo) is zoo assert loggamma(zoo) is zoo assert loggamma(nan) is nan L = loggamma(Rational(16, 3)) E = -5*log(3) + loggamma(Rational(1, 3)) + log(4) + log(7) + log(10) + log(13) assert expand_func(L).doit() == E assert L.n() == E.n() L = loggamma(Rational(19, 4)) E = -4*log(4) + loggamma(Rational(3, 4)) + log(3) + log(7) + log(11) + log(15) assert expand_func(L).doit() == E assert L.n() == E.n() L = loggamma(Rational(23, 7)) E = -3*log(7) + log(2) + loggamma(Rational(2, 7)) + log(9) + log(16) assert expand_func(L).doit() == E assert L.n() == E.n() L = loggamma(Rational(19, 4) - 7) E = -log(9) - log(5) + loggamma(Rational(3, 4)) + 3*log(4) - 3*I*pi assert expand_func(L).doit() == E assert L.n() == E.n() L = loggamma(Rational(23, 7) - 6) E = -log(19) - log(12) - log(5) + loggamma(Rational(2, 7)) + 3*log(7) - 3*I*pi assert expand_func(L).doit() == E assert L.n() == E.n() assert loggamma(x).diff(x) == polygamma(0, x) s1 = loggamma(1/(x + sin(x)) + cos(x)).nseries(x, n=4) s2 = (-log(2*x) - 1)/(2*x) - log(x/pi)/2 + (4 - log(2*x))*x/24 + O(x**2) + \ log(x)*x**2/2 assert (s1 - s2).expand(force=True).removeO() == 0 s1 = loggamma(1/x).series(x) s2 = (1/x - S.Half)*log(1/x) - 1/x + log(2*pi)/2 + \ x/12 - x**3/360 + x**5/1260 + O(x**7) assert ((s1 - s2).expand(force=True)).removeO() == 0 assert loggamma(x).rewrite('intractable') == log(gamma(x)) s1 = loggamma(x).series(x).cancel() assert s1 == -log(x) - EulerGamma*x + pi**2*x**2/12 + x**3*polygamma(2, 1)/6 + \ pi**4*x**4/360 + x**5*polygamma(4, 1)/120 + O(x**6) assert s1 == loggamma(x).rewrite('intractable').series(x).cancel() assert conjugate(loggamma(x)) == loggamma(conjugate(x)) assert conjugate(loggamma(0)) is oo assert conjugate(loggamma(1)) == loggamma(conjugate(1)) assert conjugate(loggamma(-oo)) == conjugate(zoo) assert loggamma(Symbol('v', positive=True)).is_real is True assert loggamma(Symbol('v', zero=True)).is_real is False assert loggamma(Symbol('v', negative=True)).is_real is False assert loggamma(Symbol('v', nonpositive=True)).is_real is False assert loggamma(Symbol('v', nonnegative=True)).is_real is None assert loggamma(Symbol('v', imaginary=True)).is_real is None assert loggamma(Symbol('v', real=True)).is_real is None assert loggamma(Symbol('v')).is_real is None assert loggamma(S.Half).is_real is True assert loggamma(0).is_real is False assert loggamma(Rational(-1, 2)).is_real is False assert loggamma(I).is_real is None assert loggamma(2 + 3*I).is_real is None def tN(N, M): assert loggamma(1/x)._eval_nseries(x, n=N).getn() == M tN(0, 0) tN(1, 1) tN(2, 2) tN(3, 3) tN(4, 4) tN(5, 5) def test_polygamma_expansion(): # A. & S., pa. 259 and 260 assert polygamma(0, 1/x).nseries(x, n=3) == \ -log(x) - x/2 - x**2/12 + O(x**3) assert polygamma(1, 1/x).series(x, n=5) == \ x + x**2/2 + x**3/6 + O(x**5) assert polygamma(3, 1/x).nseries(x, n=11) == \ 2*x**3 + 3*x**4 + 2*x**5 - x**7 + 4*x**9/3 + O(x**11) def test_issue_8657(): n = Symbol('n', negative=True, integer=True) m = Symbol('m', integer=True) o = Symbol('o', positive=True) p = Symbol('p', negative=True, integer=False) assert gamma(n).is_real is False assert gamma(m).is_real is None assert gamma(o).is_real is True assert gamma(p).is_real is True assert gamma(w).is_real is None def test_issue_8524(): x = Symbol('x', positive=True) y = Symbol('y', negative=True) z = Symbol('z', positive=False) p = Symbol('p', negative=False) q = Symbol('q', integer=True) r = Symbol('r', integer=False) e = Symbol('e', even=True, negative=True) assert gamma(x).is_positive is True assert gamma(y).is_positive is None assert gamma(z).is_positive is None assert gamma(p).is_positive is None assert gamma(q).is_positive is None assert gamma(r).is_positive is None assert gamma(e + S.Half).is_positive is True assert gamma(e - S.Half).is_positive is False def test_issue_14450(): assert uppergamma(Rational(3, 8), x).evalf() == uppergamma(Rational(3, 8), x) assert lowergamma(x, Rational(3, 8)).evalf() == lowergamma(x, Rational(3, 8)) # some values from Wolfram Alpha for comparison assert abs(uppergamma(Rational(3, 8), 2).evalf() - 0.07105675881) < 1e-9 assert abs(lowergamma(Rational(3, 8), 2).evalf() - 2.2993794256) < 1e-9 def test_issue_14528(): k = Symbol('k', integer=True, nonpositive=True) assert isinstance(gamma(k), gamma) def test_multigamma(): from sympy.concrete.products import Product p = Symbol('p') _k = Dummy('_k') assert multigamma(x, p).dummy_eq(pi**(p*(p - 1)/4)*\ Product(gamma(x + (1 - _k)/2), (_k, 1, p))) assert conjugate(multigamma(x, p)).dummy_eq(pi**((conjugate(p) - 1)*\ conjugate(p)/4)*Product(gamma(conjugate(x) + (1-conjugate(_k))/2), (_k, 1, p))) assert conjugate(multigamma(x, 1)) == gamma(conjugate(x)) p = Symbol('p', positive=True) assert conjugate(multigamma(x, p)).dummy_eq(pi**((p - 1)*p/4)*\ Product(gamma(conjugate(x) + (1-conjugate(_k))/2), (_k, 1, p))) assert multigamma(nan, 1) is nan assert multigamma(oo, 1).doit() is oo assert multigamma(1, 1) == 1 assert multigamma(2, 1) == 1 assert multigamma(3, 1) == 2 assert multigamma(102, 1) == factorial(101) assert multigamma(S.Half, 1) == sqrt(pi) assert multigamma(1, 2) == pi assert multigamma(2, 2) == pi/2 assert multigamma(1, 3) is zoo assert multigamma(2, 3) == pi**2/2 assert multigamma(3, 3) == 3*pi**2/2 assert multigamma(x, 1).diff(x) == gamma(x)*polygamma(0, x) assert multigamma(x, 2).diff(x) == sqrt(pi)*gamma(x)*gamma(x - S.Half)*\ polygamma(0, x) + sqrt(pi)*gamma(x)*gamma(x - S.Half)*polygamma(0, x - S.Half) assert multigamma(x - 1, 1).expand(func=True) == gamma(x)/(x - 1) assert multigamma(x + 2, 1).expand(func=True, mul=False) == x*(x + 1)*\ gamma(x) assert multigamma(x - 1, 2).expand(func=True) == sqrt(pi)*gamma(x)*\ gamma(x + S.Half)/(x**3 - 3*x**2 + x*Rational(11, 4) - Rational(3, 4)) assert multigamma(x - 1, 3).expand(func=True) == pi**Rational(3, 2)*gamma(x)**2*\ gamma(x + S.Half)/(x**5 - 6*x**4 + 55*x**3/4 - 15*x**2 + x*Rational(31, 4) - Rational(3, 2)) assert multigamma(n, 1).rewrite(factorial) == factorial(n - 1) assert multigamma(n, 2).rewrite(factorial) == sqrt(pi)*\ factorial(n - Rational(3, 2))*factorial(n - 1) assert multigamma(n, 3).rewrite(factorial) == pi**Rational(3, 2)*\ factorial(n - 2)*factorial(n - Rational(3, 2))*factorial(n - 1) assert multigamma(Rational(-1, 2), 3, evaluate=False).is_real == False assert multigamma(S.Half, 3, evaluate=False).is_real == False assert multigamma(0, 1, evaluate=False).is_real == False assert multigamma(1, 3, evaluate=False).is_real == False assert multigamma(-1.0, 3, evaluate=False).is_real == False assert multigamma(0.7, 3, evaluate=False).is_real == True assert multigamma(3, 3, evaluate=False).is_real == True def test_gamma_as_leading_term(): assert gamma(x).as_leading_term(x) == 1/x assert gamma(2 + x).as_leading_term(x) == S(1) assert gamma(cos(x)).as_leading_term(x) == S(1) assert gamma(sin(x)).as_leading_term(x) == 1/x
1249a281d4016a849f808e24a2cc3cb0cc6ede94ae29bb5f82f2826536859587
from sympy.core.function import (diff, expand, expand_func) from sympy.core import EulerGamma from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (conjugate, im, polar_lift, re) 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, sinc) from sympy.functions.special.error_functions import (Chi, Ci, E1, Ei, Li, Shi, Si, erf, erf2, erf2inv, erfc, erfcinv, erfi, erfinv, expint, fresnelc, fresnels, li) from sympy.functions.special.gamma_functions import (gamma, uppergamma) from sympy.functions.special.hyper import (hyper, meijerg) from sympy.integrals.integrals import (Integral, integrate) from sympy.series.gruntz import gruntz from sympy.series.limits import limit from sympy.series.order import O from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.functions.special.error_functions import _erfs, _eis from sympy.testing.pytest import raises x, y, z = symbols('x,y,z') w = Symbol("w", real=True) n = Symbol("n", integer=True) def test_erf(): assert erf(nan) is nan assert erf(oo) == 1 assert erf(-oo) == -1 assert erf(0) is S.Zero assert erf(I*oo) == oo*I assert erf(-I*oo) == -oo*I assert erf(-2) == -erf(2) assert erf(-x*y) == -erf(x*y) assert erf(-x - y) == -erf(x + y) assert erf(erfinv(x)) == x assert erf(erfcinv(x)) == 1 - x assert erf(erf2inv(0, x)) == x assert erf(erf2inv(0, x, evaluate=False)) == x # To cover code in erf assert erf(erf2inv(0, erf(erfcinv(1 - erf(erfinv(x)))))) == x assert erf(I).is_real is False assert erf(0, evaluate=False).is_real assert erf(0, evaluate=False).is_zero assert conjugate(erf(z)) == erf(conjugate(z)) assert erf(x).as_leading_term(x) == 2*x/sqrt(pi) assert erf(x*y).as_leading_term(y) == 2*x*y/sqrt(pi) assert (erf(x*y)/erf(y)).as_leading_term(y) == x assert erf(1/x).as_leading_term(x) == S.One assert erf(z).rewrite('uppergamma') == sqrt(z**2)*(1 - erfc(sqrt(z**2)))/z assert erf(z).rewrite('erfc') == S.One - erfc(z) assert erf(z).rewrite('erfi') == -I*erfi(I*z) assert erf(z).rewrite('fresnels') == (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - I*fresnels(z*(1 - I)/sqrt(pi))) assert erf(z).rewrite('fresnelc') == (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - I*fresnels(z*(1 - I)/sqrt(pi))) assert erf(z).rewrite('hyper') == 2*z*hyper([S.Half], [3*S.Half], -z**2)/sqrt(pi) assert erf(z).rewrite('meijerg') == z*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)/sqrt(pi) assert erf(z).rewrite('expint') == sqrt(z**2)/z - z*expint(S.Half, z**2)/sqrt(S.Pi) assert limit(exp(x)*exp(x**2)*(erf(x + 1/exp(x)) - erf(x)), x, oo) == \ 2/sqrt(pi) assert limit((1 - erf(z))*exp(z**2)*z, z, oo) == 1/sqrt(pi) assert limit((1 - erf(x))*exp(x**2)*sqrt(pi)*x, x, oo) == 1 assert limit(((1 - erf(x))*exp(x**2)*sqrt(pi)*x - 1)*2*x**2, x, oo) == -1 assert limit(erf(x)/x, x, 0) == 2/sqrt(pi) assert limit(x**(-4) - sqrt(pi)*erf(x**2) / (2*x**6), x, 0) == S(1)/3 assert erf(x).as_real_imag() == \ (erf(re(x) - I*im(x))/2 + erf(re(x) + I*im(x))/2, -I*(-erf(re(x) - I*im(x)) + erf(re(x) + I*im(x)))/2) assert erf(x).as_real_imag(deep=False) == \ (erf(re(x) - I*im(x))/2 + erf(re(x) + I*im(x))/2, -I*(-erf(re(x) - I*im(x)) + erf(re(x) + I*im(x)))/2) assert erf(w).as_real_imag() == (erf(w), 0) assert erf(w).as_real_imag(deep=False) == (erf(w), 0) # issue 13575 assert erf(I).as_real_imag() == (0, -I*erf(I)) raises(ArgumentIndexError, lambda: erf(x).fdiff(2)) assert erf(x).inverse() == erfinv def test_erf_series(): assert erf(x).series(x, 0, 7) == 2*x/sqrt(pi) - \ 2*x**3/3/sqrt(pi) + x**5/5/sqrt(pi) + O(x**7) assert erf(x).series(x, oo) == \ -exp(-x**2)*(3/(4*x**5) - 1/(2*x**3) + 1/x + O(x**(-6), (x, oo)))/sqrt(pi) + 1 assert erf(x**2).series(x, oo, n=8) == \ (-1/(2*x**6) + x**(-2) + O(x**(-8), (x, oo)))*exp(-x**4)/sqrt(pi)*-1 + 1 assert erf(sqrt(x)).series(x, oo, n=3) == (sqrt(1/x) - (1/x)**(S(3)/2)/2\ + 3*(1/x)**(S(5)/2)/4 + O(x**(-3), (x, oo)))*exp(-x)/sqrt(pi)*-1 + 1 def test_erf_evalf(): assert abs( erf(Float(2.0)) - 0.995322265 ) < 1E-8 # XXX def test__erfs(): assert _erfs(z).diff(z) == -2/sqrt(S.Pi) + 2*z*_erfs(z) assert _erfs(1/z).series(z) == \ z/sqrt(pi) - z**3/(2*sqrt(pi)) + 3*z**5/(4*sqrt(pi)) + O(z**6) assert expand(erf(z).rewrite('tractable').diff(z).rewrite('intractable')) \ == erf(z).diff(z) assert _erfs(z).rewrite("intractable") == (-erf(z) + 1)*exp(z**2) raises(ArgumentIndexError, lambda: _erfs(z).fdiff(2)) def test_erfc(): assert erfc(nan) is nan assert erfc(oo) is S.Zero assert erfc(-oo) == 2 assert erfc(0) == 1 assert erfc(I*oo) == -oo*I assert erfc(-I*oo) == oo*I assert erfc(-x) == S(2) - erfc(x) assert erfc(erfcinv(x)) == x assert erfc(I).is_real is False assert erfc(0, evaluate=False).is_real assert erfc(0, evaluate=False).is_zero is False assert erfc(erfinv(x)) == 1 - x assert conjugate(erfc(z)) == erfc(conjugate(z)) assert erfc(x).as_leading_term(x) is S.One assert erfc(1/x).as_leading_term(x) == S.Zero assert erfc(z).rewrite('erf') == 1 - erf(z) assert erfc(z).rewrite('erfi') == 1 + I*erfi(I*z) assert erfc(z).rewrite('fresnels') == 1 - (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - I*fresnels(z*(1 - I)/sqrt(pi))) assert erfc(z).rewrite('fresnelc') == 1 - (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - I*fresnels(z*(1 - I)/sqrt(pi))) assert erfc(z).rewrite('hyper') == 1 - 2*z*hyper([S.Half], [3*S.Half], -z**2)/sqrt(pi) assert erfc(z).rewrite('meijerg') == 1 - z*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)/sqrt(pi) assert erfc(z).rewrite('uppergamma') == 1 - sqrt(z**2)*(1 - erfc(sqrt(z**2)))/z assert erfc(z).rewrite('expint') == S.One - sqrt(z**2)/z + z*expint(S.Half, z**2)/sqrt(S.Pi) assert erfc(z).rewrite('tractable') == _erfs(z)*exp(-z**2) assert expand_func(erf(x) + erfc(x)) is S.One assert erfc(x).as_real_imag() == \ (erfc(re(x) - I*im(x))/2 + erfc(re(x) + I*im(x))/2, -I*(-erfc(re(x) - I*im(x)) + erfc(re(x) + I*im(x)))/2) assert erfc(x).as_real_imag(deep=False) == \ (erfc(re(x) - I*im(x))/2 + erfc(re(x) + I*im(x))/2, -I*(-erfc(re(x) - I*im(x)) + erfc(re(x) + I*im(x)))/2) assert erfc(w).as_real_imag() == (erfc(w), 0) assert erfc(w).as_real_imag(deep=False) == (erfc(w), 0) raises(ArgumentIndexError, lambda: erfc(x).fdiff(2)) assert erfc(x).inverse() == erfcinv def test_erfc_series(): assert erfc(x).series(x, 0, 7) == 1 - 2*x/sqrt(pi) + \ 2*x**3/3/sqrt(pi) - x**5/5/sqrt(pi) + O(x**7) assert erfc(x).series(x, oo) == \ (3/(4*x**5) - 1/(2*x**3) + 1/x + O(x**(-6), (x, oo)))*exp(-x**2)/sqrt(pi) def test_erfc_evalf(): assert abs( erfc(Float(2.0)) - 0.00467773 ) < 1E-8 # XXX def test_erfi(): assert erfi(nan) is nan assert erfi(oo) is S.Infinity assert erfi(-oo) is S.NegativeInfinity assert erfi(0) is S.Zero assert erfi(I*oo) == I assert erfi(-I*oo) == -I assert erfi(-x) == -erfi(x) assert erfi(I*erfinv(x)) == I*x assert erfi(I*erfcinv(x)) == I*(1 - x) assert erfi(I*erf2inv(0, x)) == I*x assert erfi(I*erf2inv(0, x, evaluate=False)) == I*x # To cover code in erfi assert erfi(I).is_real is False assert erfi(0, evaluate=False).is_real assert erfi(0, evaluate=False).is_zero assert conjugate(erfi(z)) == erfi(conjugate(z)) assert erfi(x).as_leading_term(x) == 2*x/sqrt(pi) assert erfi(x*y).as_leading_term(y) == 2*x*y/sqrt(pi) assert (erfi(x*y)/erfi(y)).as_leading_term(y) == x assert erfi(1/x).as_leading_term(x) == erfi(1/x) assert erfi(z).rewrite('erf') == -I*erf(I*z) assert erfi(z).rewrite('erfc') == I*erfc(I*z) - I assert erfi(z).rewrite('fresnels') == (1 - I)*(fresnelc(z*(1 + I)/sqrt(pi)) - I*fresnels(z*(1 + I)/sqrt(pi))) assert erfi(z).rewrite('fresnelc') == (1 - I)*(fresnelc(z*(1 + I)/sqrt(pi)) - I*fresnels(z*(1 + I)/sqrt(pi))) assert erfi(z).rewrite('hyper') == 2*z*hyper([S.Half], [3*S.Half], z**2)/sqrt(pi) assert erfi(z).rewrite('meijerg') == z*meijerg([S.Half], [], [0], [Rational(-1, 2)], -z**2)/sqrt(pi) assert erfi(z).rewrite('uppergamma') == (sqrt(-z**2)/z*(uppergamma(S.Half, -z**2)/sqrt(S.Pi) - S.One)) assert erfi(z).rewrite('expint') == sqrt(-z**2)/z - z*expint(S.Half, -z**2)/sqrt(S.Pi) assert erfi(z).rewrite('tractable') == -I*(-_erfs(I*z)*exp(z**2) + 1) assert expand_func(erfi(I*z)) == I*erf(z) assert erfi(x).as_real_imag() == \ (erfi(re(x) - I*im(x))/2 + erfi(re(x) + I*im(x))/2, -I*(-erfi(re(x) - I*im(x)) + erfi(re(x) + I*im(x)))/2) assert erfi(x).as_real_imag(deep=False) == \ (erfi(re(x) - I*im(x))/2 + erfi(re(x) + I*im(x))/2, -I*(-erfi(re(x) - I*im(x)) + erfi(re(x) + I*im(x)))/2) assert erfi(w).as_real_imag() == (erfi(w), 0) assert erfi(w).as_real_imag(deep=False) == (erfi(w), 0) raises(ArgumentIndexError, lambda: erfi(x).fdiff(2)) def test_erfi_series(): assert erfi(x).series(x, 0, 7) == 2*x/sqrt(pi) + \ 2*x**3/3/sqrt(pi) + x**5/5/sqrt(pi) + O(x**7) assert erfi(x).series(x, oo) == \ (3/(4*x**5) + 1/(2*x**3) + 1/x + O(x**(-6), (x, oo)))*exp(x**2)/sqrt(pi) - I def test_erfi_evalf(): assert abs( erfi(Float(2.0)) - 18.5648024145756 ) < 1E-13 # XXX def test_erf2(): assert erf2(0, 0) is S.Zero assert erf2(x, x) is S.Zero assert erf2(nan, 0) is nan assert erf2(-oo, y) == erf(y) + 1 assert erf2( oo, y) == erf(y) - 1 assert erf2( x, oo) == 1 - erf(x) assert erf2( x,-oo) == -1 - erf(x) assert erf2(x, erf2inv(x, y)) == y assert erf2(-x, -y) == -erf2(x,y) assert erf2(-x, y) == erf(y) + erf(x) assert erf2( x, -y) == -erf(y) - erf(x) assert erf2(x, y).rewrite('fresnels') == erf(y).rewrite(fresnels)-erf(x).rewrite(fresnels) assert erf2(x, y).rewrite('fresnelc') == erf(y).rewrite(fresnelc)-erf(x).rewrite(fresnelc) assert erf2(x, y).rewrite('hyper') == erf(y).rewrite(hyper)-erf(x).rewrite(hyper) assert erf2(x, y).rewrite('meijerg') == erf(y).rewrite(meijerg)-erf(x).rewrite(meijerg) assert erf2(x, y).rewrite('uppergamma') == erf(y).rewrite(uppergamma) - erf(x).rewrite(uppergamma) assert erf2(x, y).rewrite('expint') == erf(y).rewrite(expint)-erf(x).rewrite(expint) assert erf2(I, 0).is_real is False assert erf2(0, 0, evaluate=False).is_real assert erf2(0, 0, evaluate=False).is_zero assert erf2(x, x, evaluate=False).is_zero assert erf2(x, y).is_zero is None assert expand_func(erf(x) + erf2(x, y)) == erf(y) assert conjugate(erf2(x, y)) == erf2(conjugate(x), conjugate(y)) assert erf2(x, y).rewrite('erf') == erf(y) - erf(x) assert erf2(x, y).rewrite('erfc') == erfc(x) - erfc(y) assert erf2(x, y).rewrite('erfi') == I*(erfi(I*x) - erfi(I*y)) assert erf2(x, y).diff(x) == erf2(x, y).fdiff(1) assert erf2(x, y).diff(y) == erf2(x, y).fdiff(2) assert erf2(x, y).diff(x) == -2*exp(-x**2)/sqrt(pi) assert erf2(x, y).diff(y) == 2*exp(-y**2)/sqrt(pi) raises(ArgumentIndexError, lambda: erf2(x, y).fdiff(3)) assert erf2(x, y).is_extended_real is None xr, yr = symbols('xr yr', extended_real=True) assert erf2(xr, yr).is_extended_real is True def test_erfinv(): assert erfinv(0) is S.Zero assert erfinv(1) is S.Infinity assert erfinv(nan) is S.NaN assert erfinv(-1) is S.NegativeInfinity assert erfinv(erf(w)) == w assert erfinv(erf(-w)) == -w assert erfinv(x).diff() == sqrt(pi)*exp(erfinv(x)**2)/2 raises(ArgumentIndexError, lambda: erfinv(x).fdiff(2)) assert erfinv(z).rewrite('erfcinv') == erfcinv(1-z) assert erfinv(z).inverse() == erf def test_erfinv_evalf(): assert abs( erfinv(Float(0.2)) - 0.179143454621292 ) < 1E-13 def test_erfcinv(): assert erfcinv(1) is S.Zero assert erfcinv(0) is S.Infinity assert erfcinv(nan) is S.NaN assert erfcinv(x).diff() == -sqrt(pi)*exp(erfcinv(x)**2)/2 raises(ArgumentIndexError, lambda: erfcinv(x).fdiff(2)) assert erfcinv(z).rewrite('erfinv') == erfinv(1-z) assert erfcinv(z).inverse() == erfc def test_erf2inv(): assert erf2inv(0, 0) is S.Zero assert erf2inv(0, 1) is S.Infinity assert erf2inv(1, 0) is S.One assert erf2inv(0, y) == erfinv(y) assert erf2inv(oo, y) == erfcinv(-y) assert erf2inv(x, 0) == x assert erf2inv(x, oo) == erfinv(x) assert erf2inv(nan, 0) is nan assert erf2inv(0, nan) is nan assert erf2inv(x, y).diff(x) == exp(-x**2 + erf2inv(x, y)**2) assert erf2inv(x, y).diff(y) == sqrt(pi)*exp(erf2inv(x, y)**2)/2 raises(ArgumentIndexError, lambda: erf2inv(x, y).fdiff(3)) # NOTE we multiply by exp_polar(I*pi) and need this to be on the principal # branch, hence take x in the lower half plane (d=0). def mytn(expr1, expr2, expr3, x, d=0): from sympy.testing.randtest import verify_numerically, random_complex_number subs = {} for a in expr1.free_symbols: if a != x: subs[a] = random_complex_number() return expr2 == expr3 and verify_numerically(expr1.subs(subs), expr2.subs(subs), x, d=d) def mytd(expr1, expr2, x): from sympy.testing.randtest import test_derivative_numerically, \ random_complex_number subs = {} for a in expr1.free_symbols: if a != x: subs[a] = random_complex_number() return expr1.diff(x) == expr2 and test_derivative_numerically(expr1.subs(subs), x) def tn_branch(func, s=None): from random import uniform def fn(x): if s is None: return func(x) return func(s, x) c = uniform(1, 5) expr = fn(c*exp_polar(I*pi)) - fn(c*exp_polar(-I*pi)) eps = 1e-15 expr2 = fn(-c + eps*I) - fn(-c - eps*I) return abs(expr.n() - expr2.n()).n() < 1e-10 def test_ei(): assert Ei(0) is S.NegativeInfinity assert Ei(oo) is S.Infinity assert Ei(-oo) is S.Zero assert tn_branch(Ei) assert mytd(Ei(x), exp(x)/x, x) assert mytn(Ei(x), Ei(x).rewrite(uppergamma), -uppergamma(0, x*polar_lift(-1)) - I*pi, x) assert mytn(Ei(x), Ei(x).rewrite(expint), -expint(1, x*polar_lift(-1)) - I*pi, x) assert Ei(x).rewrite(expint).rewrite(Ei) == Ei(x) assert Ei(x*exp_polar(2*I*pi)) == Ei(x) + 2*I*pi assert Ei(x*exp_polar(-2*I*pi)) == Ei(x) - 2*I*pi assert mytn(Ei(x), Ei(x).rewrite(Shi), Chi(x) + Shi(x), x) assert mytn(Ei(x*polar_lift(I)), Ei(x*polar_lift(I)).rewrite(Si), Ci(x) + I*Si(x) + I*pi/2, x) assert Ei(log(x)).rewrite(li) == li(x) assert Ei(2*log(x)).rewrite(li) == li(x**2) assert gruntz(Ei(x+exp(-x))*exp(-x)*x, x, oo) == 1 assert Ei(x).series(x) == EulerGamma + log(x) + x + x**2/4 + \ x**3/18 + x**4/96 + x**5/600 + O(x**6) assert Ei(x).series(x, 1, 3) == Ei(1) + E*(x - 1) + O((x - 1)**3, (x, 1)) assert Ei(x).series(x, oo) == \ (120/x**5 + 24/x**4 + 6/x**3 + 2/x**2 + 1/x + 1 + O(x**(-6), (x, oo)))*exp(x)/x assert str(Ei(cos(2)).evalf(n=10)) == '-0.6760647401' raises(ArgumentIndexError, lambda: Ei(x).fdiff(2)) def test_expint(): assert mytn(expint(x, y), expint(x, y).rewrite(uppergamma), y**(x - 1)*uppergamma(1 - x, y), x) assert mytd( expint(x, y), -y**(x - 1)*meijerg([], [1, 1], [0, 0, 1 - x], [], y), x) assert mytd(expint(x, y), -expint(x - 1, y), y) assert mytn(expint(1, x), expint(1, x).rewrite(Ei), -Ei(x*polar_lift(-1)) + I*pi, x) assert expint(-4, x) == exp(-x)/x + 4*exp(-x)/x**2 + 12*exp(-x)/x**3 \ + 24*exp(-x)/x**4 + 24*exp(-x)/x**5 assert expint(Rational(-3, 2), x) == \ exp(-x)/x + 3*exp(-x)/(2*x**2) + 3*sqrt(pi)*erfc(sqrt(x))/(4*x**S('5/2')) assert tn_branch(expint, 1) assert tn_branch(expint, 2) assert tn_branch(expint, 3) assert tn_branch(expint, 1.7) assert tn_branch(expint, pi) assert expint(y, x*exp_polar(2*I*pi)) == \ x**(y - 1)*(exp(2*I*pi*y) - 1)*gamma(-y + 1) + expint(y, x) assert expint(y, x*exp_polar(-2*I*pi)) == \ x**(y - 1)*(exp(-2*I*pi*y) - 1)*gamma(-y + 1) + expint(y, x) assert expint(2, x*exp_polar(2*I*pi)) == 2*I*pi*x + expint(2, x) assert expint(2, x*exp_polar(-2*I*pi)) == -2*I*pi*x + expint(2, x) assert expint(1, x).rewrite(Ei).rewrite(expint) == expint(1, x) assert expint(x, y).rewrite(Ei) == expint(x, y) assert expint(x, y).rewrite(Ci) == expint(x, y) assert mytn(E1(x), E1(x).rewrite(Shi), Shi(x) - Chi(x), x) assert mytn(E1(polar_lift(I)*x), E1(polar_lift(I)*x).rewrite(Si), -Ci(x) + I*Si(x) - I*pi/2, x) assert mytn(expint(2, x), expint(2, x).rewrite(Ei).rewrite(expint), -x*E1(x) + exp(-x), x) assert mytn(expint(3, x), expint(3, x).rewrite(Ei).rewrite(expint), x**2*E1(x)/2 + (1 - x)*exp(-x)/2, x) assert expint(Rational(3, 2), z).nseries(z) == \ 2 + 2*z - z**2/3 + z**3/15 - z**4/84 + z**5/540 - \ 2*sqrt(pi)*sqrt(z) + O(z**6) assert E1(z).series(z) == -EulerGamma - log(z) + z - \ z**2/4 + z**3/18 - z**4/96 + z**5/600 + O(z**6) assert expint(4, z).series(z) == Rational(1, 3) - z/2 + z**2/2 + \ z**3*(log(z)/6 - Rational(11, 36) + EulerGamma/6 - I*pi/6) - z**4/24 + \ z**5/240 + O(z**6) assert expint(n, x).series(x, oo, n=3) == \ (n*(n + 1)/x**2 - n/x + 1 + O(x**(-3), (x, oo)))*exp(-x)/x assert expint(z, y).series(z, 0, 2) == exp(-y)/y - z*meijerg(((), (1, 1)), ((0, 0, 1), ()), y)/y + O(z**2) raises(ArgumentIndexError, lambda: expint(x, y).fdiff(3)) neg = Symbol('neg', negative=True) assert Ei(neg).rewrite(Si) == Shi(neg) + Chi(neg) - I*pi def test__eis(): assert _eis(z).diff(z) == -_eis(z) + 1/z assert _eis(1/z).series(z) == \ z + z**2 + 2*z**3 + 6*z**4 + 24*z**5 + O(z**6) assert Ei(z).rewrite('tractable') == exp(z)*_eis(z) assert li(z).rewrite('tractable') == z*_eis(log(z)) assert _eis(z).rewrite('intractable') == exp(-z)*Ei(z) assert expand(li(z).rewrite('tractable').diff(z).rewrite('intractable')) \ == li(z).diff(z) assert expand(Ei(z).rewrite('tractable').diff(z).rewrite('intractable')) \ == Ei(z).diff(z) assert _eis(z).series(z, n=3) == EulerGamma + log(z) + z*(-log(z) - \ EulerGamma + 1) + z**2*(log(z)/2 - Rational(3, 4) + EulerGamma/2)\ + O(z**3*log(z)) raises(ArgumentIndexError, lambda: _eis(z).fdiff(2)) def tn_arg(func): def test(arg, e1, e2): from random import uniform v = uniform(1, 5) v1 = func(arg*x).subs(x, v).n() v2 = func(e1*v + e2*1e-15).n() return abs(v1 - v2).n() < 1e-10 return test(exp_polar(I*pi/2), I, 1) and \ test(exp_polar(-I*pi/2), -I, 1) and \ test(exp_polar(I*pi), -1, I) and \ test(exp_polar(-I*pi), -1, -I) def test_li(): z = Symbol("z") zr = Symbol("z", real=True) zp = Symbol("z", positive=True) zn = Symbol("z", negative=True) assert li(0) is S.Zero assert li(1) is -oo assert li(oo) is oo assert isinstance(li(z), li) assert unchanged(li, -zp) assert unchanged(li, zn) assert diff(li(z), z) == 1/log(z) assert conjugate(li(z)) == li(conjugate(z)) assert conjugate(li(-zr)) == li(-zr) assert unchanged(conjugate, li(-zp)) assert unchanged(conjugate, li(zn)) assert li(z).rewrite(Li) == Li(z) + li(2) assert li(z).rewrite(Ei) == Ei(log(z)) assert li(z).rewrite(uppergamma) == (-log(1/log(z))/2 - log(-log(z)) + log(log(z))/2 - expint(1, -log(z))) assert li(z).rewrite(Si) == (-log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z))) assert li(z).rewrite(Ci) == (-log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z))) assert li(z).rewrite(Shi) == (-log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z))) assert li(z).rewrite(Chi) == (-log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z))) assert li(z).rewrite(hyper) ==(log(z)*hyper((1, 1), (2, 2), log(z)) - log(1/log(z))/2 + log(log(z))/2 + EulerGamma) assert li(z).rewrite(meijerg) == (-log(1/log(z))/2 - log(-log(z)) + log(log(z))/2 - meijerg(((), (1,)), ((0, 0), ()), -log(z))) assert gruntz(1/li(z), z, oo) is S.Zero assert li(z).series(z) == log(z)**5/600 + log(z)**4/96 + log(z)**3/18 + log(z)**2/4 + \ log(z) + log(log(z)) + EulerGamma raises(ArgumentIndexError, lambda: li(z).fdiff(2)) def test_Li(): assert Li(2) is S.Zero assert Li(oo) is oo assert isinstance(Li(z), Li) assert diff(Li(z), z) == 1/log(z) assert gruntz(1/Li(z), z, oo) is S.Zero assert Li(z).rewrite(li) == li(z) - li(2) assert Li(z).series(z) == \ log(z)**5/600 + log(z)**4/96 + log(z)**3/18 + log(z)**2/4 + log(z) + log(log(z)) - li(2) + EulerGamma raises(ArgumentIndexError, lambda: Li(z).fdiff(2)) def test_si(): assert Si(I*x) == I*Shi(x) assert Shi(I*x) == I*Si(x) assert Si(-I*x) == -I*Shi(x) assert Shi(-I*x) == -I*Si(x) assert Si(-x) == -Si(x) assert Shi(-x) == -Shi(x) assert Si(exp_polar(2*pi*I)*x) == Si(x) assert Si(exp_polar(-2*pi*I)*x) == Si(x) assert Shi(exp_polar(2*pi*I)*x) == Shi(x) assert Shi(exp_polar(-2*pi*I)*x) == Shi(x) assert Si(oo) == pi/2 assert Si(-oo) == -pi/2 assert Shi(oo) is oo assert Shi(-oo) is -oo assert mytd(Si(x), sin(x)/x, x) assert mytd(Shi(x), sinh(x)/x, x) assert mytn(Si(x), Si(x).rewrite(Ei), -I*(-Ei(x*exp_polar(-I*pi/2))/2 + Ei(x*exp_polar(I*pi/2))/2 - I*pi) + pi/2, x) assert mytn(Si(x), Si(x).rewrite(expint), -I*(-expint(1, x*exp_polar(-I*pi/2))/2 + expint(1, x*exp_polar(I*pi/2))/2) + pi/2, x) assert mytn(Shi(x), Shi(x).rewrite(Ei), Ei(x)/2 - Ei(x*exp_polar(I*pi))/2 + I*pi/2, x) assert mytn(Shi(x), Shi(x).rewrite(expint), expint(1, x)/2 - expint(1, x*exp_polar(I*pi))/2 - I*pi/2, x) assert tn_arg(Si) assert tn_arg(Shi) assert Si(x).nseries(x, n=8) == \ x - x**3/18 + x**5/600 - x**7/35280 + O(x**9) assert Shi(x).nseries(x, n=8) == \ x + x**3/18 + x**5/600 + x**7/35280 + O(x**9) assert Si(sin(x)).nseries(x, n=5) == x - 2*x**3/9 + 17*x**5/450 + O(x**6) assert Si(x).nseries(x, 1, n=3) == \ Si(1) + (x - 1)*sin(1) + (x - 1)**2*(-sin(1)/2 + cos(1)/2) + O((x - 1)**3, (x, 1)) assert Si(x).series(x, oo) == pi/2 - (- 6/x**3 + 1/x \ + O(x**(-7), (x, oo)))*sin(x)/x - (24/x**4 - 2/x**2 + 1 \ + O(x**(-7), (x, oo)))*cos(x)/x t = Symbol('t', Dummy=True) assert Si(x).rewrite(sinc) == Integral(sinc(t), (t, 0, x)) assert limit(Shi(x), x, S.NegativeInfinity) == -I*pi/2 def test_ci(): m1 = exp_polar(I*pi) m1_ = exp_polar(-I*pi) pI = exp_polar(I*pi/2) mI = exp_polar(-I*pi/2) assert Ci(m1*x) == Ci(x) + I*pi assert Ci(m1_*x) == Ci(x) - I*pi assert Ci(pI*x) == Chi(x) + I*pi/2 assert Ci(mI*x) == Chi(x) - I*pi/2 assert Chi(m1*x) == Chi(x) + I*pi assert Chi(m1_*x) == Chi(x) - I*pi assert Chi(pI*x) == Ci(x) + I*pi/2 assert Chi(mI*x) == Ci(x) - I*pi/2 assert Ci(exp_polar(2*I*pi)*x) == Ci(x) + 2*I*pi assert Chi(exp_polar(-2*I*pi)*x) == Chi(x) - 2*I*pi assert Chi(exp_polar(2*I*pi)*x) == Chi(x) + 2*I*pi assert Ci(exp_polar(-2*I*pi)*x) == Ci(x) - 2*I*pi assert Ci(oo) is S.Zero assert Ci(-oo) == I*pi assert Chi(oo) is oo assert Chi(-oo) is oo assert mytd(Ci(x), cos(x)/x, x) assert mytd(Chi(x), cosh(x)/x, x) assert mytn(Ci(x), Ci(x).rewrite(Ei), Ei(x*exp_polar(-I*pi/2))/2 + Ei(x*exp_polar(I*pi/2))/2, x) assert mytn(Chi(x), Chi(x).rewrite(Ei), Ei(x)/2 + Ei(x*exp_polar(I*pi))/2 - I*pi/2, x) assert tn_arg(Ci) assert tn_arg(Chi) assert Ci(x).nseries(x, n=4) == \ EulerGamma + log(x) - x**2/4 + x**4/96 + O(x**5) assert Chi(x).nseries(x, n=4) == \ EulerGamma + log(x) + x**2/4 + x**4/96 + O(x**5) assert Ci(x).series(x, oo) == -cos(x)*(-6/x**3 + 1/x \ + O(x**(-7), (x, oo)))/x + (24/x**4 - 2/x**2 + 1 \ + O(x**(-7), (x, oo)))*sin(x)/x assert limit(log(x) - Ci(2*x), x, 0) == -log(2) - EulerGamma assert Ci(x).rewrite(uppergamma) == -expint(1, x*exp_polar(-I*pi/2))/2 -\ expint(1, x*exp_polar(I*pi/2))/2 assert Ci(x).rewrite(expint) == -expint(1, x*exp_polar(-I*pi/2))/2 -\ expint(1, x*exp_polar(I*pi/2))/2 raises(ArgumentIndexError, lambda: Ci(x).fdiff(2)) def test_fresnel(): assert fresnels(0) is S.Zero assert fresnels(oo) is S.Half assert fresnels(-oo) == Rational(-1, 2) assert fresnels(I*oo) == -I*S.Half assert unchanged(fresnels, z) assert fresnels(-z) == -fresnels(z) assert fresnels(I*z) == -I*fresnels(z) assert fresnels(-I*z) == I*fresnels(z) assert conjugate(fresnels(z)) == fresnels(conjugate(z)) assert fresnels(z).diff(z) == sin(pi*z**2/2) assert fresnels(z).rewrite(erf) == (S.One + I)/4 * ( erf((S.One + I)/2*sqrt(pi)*z) - I*erf((S.One - I)/2*sqrt(pi)*z)) assert fresnels(z).rewrite(hyper) == \ pi*z**3/6 * hyper([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)], -pi**2*z**4/16) assert fresnels(z).series(z, n=15) == \ pi*z**3/6 - pi**3*z**7/336 + pi**5*z**11/42240 + O(z**15) assert fresnels(w).is_extended_real is True assert fresnels(w).is_finite is True assert fresnels(z).is_extended_real is None assert fresnels(z).is_finite is None assert fresnels(z).as_real_imag() == (fresnels(re(z) - I*im(z))/2 + fresnels(re(z) + I*im(z))/2, -I*(-fresnels(re(z) - I*im(z)) + fresnels(re(z) + I*im(z)))/2) assert fresnels(z).as_real_imag(deep=False) == (fresnels(re(z) - I*im(z))/2 + fresnels(re(z) + I*im(z))/2, -I*(-fresnels(re(z) - I*im(z)) + fresnels(re(z) + I*im(z)))/2) assert fresnels(w).as_real_imag() == (fresnels(w), 0) assert fresnels(w).as_real_imag(deep=True) == (fresnels(w), 0) assert fresnels(2 + 3*I).as_real_imag() == ( fresnels(2 + 3*I)/2 + fresnels(2 - 3*I)/2, -I*(fresnels(2 + 3*I) - fresnels(2 - 3*I))/2 ) assert expand_func(integrate(fresnels(z), z)) == \ z*fresnels(z) + cos(pi*z**2/2)/pi assert fresnels(z).rewrite(meijerg) == sqrt(2)*pi*z**Rational(9, 4) * \ meijerg(((), (1,)), ((Rational(3, 4),), (Rational(1, 4), 0)), -pi**2*z**4/16)/(2*(-z)**Rational(3, 4)*(z**2)**Rational(3, 4)) assert fresnelc(0) is S.Zero assert fresnelc(oo) == S.Half assert fresnelc(-oo) == Rational(-1, 2) assert fresnelc(I*oo) == I*S.Half assert unchanged(fresnelc, z) assert fresnelc(-z) == -fresnelc(z) assert fresnelc(I*z) == I*fresnelc(z) assert fresnelc(-I*z) == -I*fresnelc(z) assert conjugate(fresnelc(z)) == fresnelc(conjugate(z)) assert fresnelc(z).diff(z) == cos(pi*z**2/2) assert fresnelc(z).rewrite(erf) == (S.One - I)/4 * ( erf((S.One + I)/2*sqrt(pi)*z) + I*erf((S.One - I)/2*sqrt(pi)*z)) assert fresnelc(z).rewrite(hyper) == \ z * hyper([Rational(1, 4)], [S.Half, Rational(5, 4)], -pi**2*z**4/16) assert fresnelc(w).is_extended_real is True assert fresnelc(z).as_real_imag() == \ (fresnelc(re(z) - I*im(z))/2 + fresnelc(re(z) + I*im(z))/2, -I*(-fresnelc(re(z) - I*im(z)) + fresnelc(re(z) + I*im(z)))/2) assert fresnelc(z).as_real_imag(deep=False) == \ (fresnelc(re(z) - I*im(z))/2 + fresnelc(re(z) + I*im(z))/2, -I*(-fresnelc(re(z) - I*im(z)) + fresnelc(re(z) + I*im(z)))/2) assert fresnelc(2 + 3*I).as_real_imag() == ( fresnelc(2 - 3*I)/2 + fresnelc(2 + 3*I)/2, -I*(fresnelc(2 + 3*I) - fresnelc(2 - 3*I))/2 ) assert expand_func(integrate(fresnelc(z), z)) == \ z*fresnelc(z) - sin(pi*z**2/2)/pi assert fresnelc(z).rewrite(meijerg) == sqrt(2)*pi*z**Rational(3, 4) * \ meijerg(((), (1,)), ((Rational(1, 4),), (Rational(3, 4), 0)), -pi**2*z**4/16)/(2*(-z)**Rational(1, 4)*(z**2)**Rational(1, 4)) from sympy.testing.randtest import verify_numerically verify_numerically(re(fresnels(z)), fresnels(z).as_real_imag()[0], z) verify_numerically(im(fresnels(z)), fresnels(z).as_real_imag()[1], z) verify_numerically(fresnels(z), fresnels(z).rewrite(hyper), z) verify_numerically(fresnels(z), fresnels(z).rewrite(meijerg), z) verify_numerically(re(fresnelc(z)), fresnelc(z).as_real_imag()[0], z) verify_numerically(im(fresnelc(z)), fresnelc(z).as_real_imag()[1], z) verify_numerically(fresnelc(z), fresnelc(z).rewrite(hyper), z) verify_numerically(fresnelc(z), fresnelc(z).rewrite(meijerg), z) raises(ArgumentIndexError, lambda: fresnels(z).fdiff(2)) raises(ArgumentIndexError, lambda: fresnelc(z).fdiff(2)) assert fresnels(x).taylor_term(-1, x) is S.Zero assert fresnelc(x).taylor_term(-1, x) is S.Zero assert fresnelc(x).taylor_term(1, x) == -pi**2*x**5/40 def test_fresnel_series(): assert fresnelc(z).series(z, n=15) == \ z - pi**2*z**5/40 + pi**4*z**9/3456 - pi**6*z**13/599040 + O(z**15) # issues 6510, 10102 fs = (S.Half - sin(pi*z**2/2)/(pi**2*z**3) + (-1/(pi*z) + 3/(pi**3*z**5))*cos(pi*z**2/2)) fc = (S.Half - cos(pi*z**2/2)/(pi**2*z**3) + (1/(pi*z) - 3/(pi**3*z**5))*sin(pi*z**2/2)) assert fresnels(z).series(z, oo) == fs + O(z**(-6), (z, oo)) assert fresnelc(z).series(z, oo) == fc + O(z**(-6), (z, oo)) assert (fresnels(z).series(z, -oo) + fs.subs(z, -z)).expand().is_Order assert (fresnelc(z).series(z, -oo) + fc.subs(z, -z)).expand().is_Order assert (fresnels(1/z).series(z) - fs.subs(z, 1/z)).expand().is_Order assert (fresnelc(1/z).series(z) - fc.subs(z, 1/z)).expand().is_Order assert ((2*fresnels(3*z)).series(z, oo) - 2*fs.subs(z, 3*z)).expand().is_Order assert ((3*fresnelc(2*z)).series(z, oo) - 3*fc.subs(z, 2*z)).expand().is_Order
6552b64c85b45e35910c17b1d39e329a6565481430f912018442f5c12d990265
from sympy.core.symbol import Symbol from sympy.matrices.dense import (eye, zeros) from sympy.solvers.solvers import solve_linear_system N = 8 M = zeros(N, N + 1) M[:, :N] = eye(N) S = [Symbol('A%i' % i) for i in range(N)] def timeit_linsolve_trivial(): solve_linear_system(M, *S)
c5602c5fa050b78760cca31a895844fc53bac6c877b6b563a82f63127a6e582a
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.solvers.diophantine import diophantine >>> from sympy.abc import a, b >>> eq = a**4 + b**4 - (2**4 + 3**4) >>> diophantine(eq) {(2, 3)} >>> diophantine(eq, permute=True) {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)} Details ======= ``eq`` should be an expression which is assumed to be zero. ``t`` is the parameter to be used in the solution. Examples ======== >>> from sympy.abc import x, y, z >>> diophantine(x**2 - y**2) {(t_0, -t_0), (t_0, t_0)} >>> diophantine(x*(2*x + 3*y - z)) {(0, n1, n2), (t_0, t_1, 2*t_0 + 3*t_1)} >>> diophantine(x**2 + 3*x*y + 4*x) {(0, n1), (3*t_0 - 4, -t_0)} See Also ======== diop_solve() sympy.utilities.iterables.permute_signs sympy.utilities.iterables.signed_permutations """ 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 type(v[-1]) is list: rpt = len(v[-1]) nonrpt = len(v) - 1 else: rpt = 0 nonrpt = len(v) return rpt + nonrpt def transformation_to_DN(eq): """ This function transforms general quadratic, `ax^2 + bxy + cy^2 + dx + ey + f = 0` to more easy to deal with `X^2 - DY^2 = N` form. Explanation =========== This is used to solve the general quadratic equation by transforming it to the latter form. Refer [1]_ for more detailed information on the transformation. This function returns a tuple (A, B) where A is a 2 X 2 matrix and B is a 2 X 1 matrix such that, Transpose([x y]) = A * Transpose([X Y]) + B Usage ===== ``transformation_to_DN(eq)``: where ``eq`` is the quadratic to be transformed. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import transformation_to_DN >>> 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 [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 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
ff40f4717257a05f2cc34f61c1a7a67a2b1f164811454eb02fb91b7d7835f200
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 doesn't have an ``_Integral`` counterpart (such as a best hint that would defeat the purpose of ``all_Integral``), you will need to remove it manually in the :py:meth:`~sympy.solvers.ode.dsolve` code. See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for guidelines on writing a hint name. Determine *in general* how the solutions returned by your method compare with other methods that can potentially solve the same ODEs. Then, put your hints in the :py:data:`~sympy.solvers.ode.allhints` tuple in the order that they should be called. The ordering of this tuple determines which hints are default. Note that exceptions are ok, because it is easy for the user to choose individual hints with :py:meth:`~sympy.solvers.ode.dsolve`. In general, ``_Integral`` variants should go at the end of the list, and ``_best`` variants should go before the various hints they apply to. For example, the ``undetermined_coefficients`` hint comes before the ``variation_of_parameters`` hint because, even though variation of parameters is more general than undetermined coefficients, undetermined coefficients generally returns cleaner results for the ODEs that it can solve than variation of parameters does, and it does not require integration, so it is much faster. Next, you need to have a match expression or a function that matches the type of the ODE, which you should put in :py:meth:`~sympy.solvers.ode.classify_ode` (if the match function is more than just a few lines. It should match the ODE without solving for it as much as possible, so that :py:meth:`~sympy.solvers.ode.classify_ode` remains fast and is not hindered by bugs in solving code. Be sure to consider corner cases. For example, if your solution method involves dividing by something, make sure you exclude the case where that division will be 0. In most cases, the matching of the ODE will also give you the various parts that you need to solve it. You should put that in a dictionary (``.match()`` will do this for you), and add that as ``matching_hints['hint'] = matchdict`` in the relevant part of :py:meth:`~sympy.solvers.ode.classify_ode`. :py:meth:`~sympy.solvers.ode.classify_ode` will then send this to :py:meth:`~sympy.solvers.ode.dsolve`, which will send it to your function as the ``match`` argument. Your function should be named ``ode_<hint>(eq, func, order, match)`. If you need to send more information, put it in the ``match`` dictionary. For example, if you had to substitute in a dummy variable in :py:meth:`~sympy.solvers.ode.classify_ode` to match the ODE, you will need to pass it to your function using the `match` dict to access it. You can access the independent variable using ``func.args[0]``, and the dependent variable (the function you are trying to solve for) as ``func.func``. If, while trying to solve the ODE, you find that you cannot, raise ``NotImplementedError``. :py:meth:`~sympy.solvers.ode.dsolve` will catch this error with the ``all`` meta-hint, rather than causing the whole routine to fail. Add a docstring to your function that describes the method employed. Like with anything else in SymPy, you will need to add a doctest to the docstring, in addition to real tests in ``test_ode.py``. Try to maintain consistency with the other hint functions' docstrings. Add your method to the list at the top of this docstring. Also, add your method to ``ode.rst`` in the ``docs/src`` directory, so that the Sphinx docs will pull its docstring into the main SymPy documentation. Be sure to make the Sphinx documentation by running ``make html`` from within the doc directory to verify that the docstring formats correctly. If your solution method involves integrating, use :py:obj:`~.Integral` instead of :py:meth:`~sympy.core.expr.Expr.integrate`. This allows the user to bypass hard/slow integration by using the ``_Integral`` variant of your hint. In most cases, calling :py:meth:`sympy.core.basic.Basic.doit` will integrate your solution. If this is not the case, you will need to write special code in :py:meth:`~sympy.solvers.ode.ode._handle_Integral`. Arbitrary constants should be symbols named ``C1``, ``C2``, and so on. All solution methods should return an equality instance. If you need an arbitrary number of arbitrary constants, you can use ``constants = numbered_symbols(prefix='C', cls=Symbol, start=1)``. If it is possible to solve for the dependent function in a general way, do so. Otherwise, do as best as you can, but do not call solve in your ``ode_<hint>()`` function. :py:meth:`~sympy.solvers.ode.ode.odesimp` will attempt to solve the solution for you, so you do not need to do that. Lastly, if your ODE has a common simplification that can be applied to your solutions, you can add a special case in :py:meth:`~sympy.solvers.ode.ode.odesimp` for it. For example, solutions returned from the ``1st_homogeneous_coeff`` hints often have many :obj:`~sympy.functions.elementary.exponential.log` terms, so :py:meth:`~sympy.solvers.ode.ode.odesimp` calls :py:meth:`~sympy.simplify.simplify.logcombine` on them (it also helps to write the arbitrary constant as ``log(C1)`` instead of ``C1`` in this case). Also consider common ways that you can rearrange your solution to have :py:meth:`~sympy.solvers.ode.constantsimp` take better advantage of it. It is better to put simplification in :py:meth:`~sympy.solvers.ode.ode.odesimp` than in your method, because it can then be turned off with the simplify flag in :py:meth:`~sympy.solvers.ode.dsolve`. If you have any extraneous simplification in your function, be sure to only run it using ``if match.get('simplify', True):``, especially if it can be slow or if it can reduce the domain of the solution. Finally, as with every contribution to SymPy, your method will need to be tested. Add a test for each method in ``test_ode.py``. Follow the conventions there, i.e., test the solver using ``dsolve(eq, f(x), hint=your_hint)``, and also test the solution using :py:meth:`~sympy.solvers.ode.checkodesol` (you can put these in a separate tests and skip/XFAIL if it runs too slow/doesn't work). Be sure to call your hint specifically in :py:meth:`~sympy.solvers.ode.dsolve`, that way the test 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 couldn't be detected). ``hint`` is the solving method that you want dsolve to use. Use ``classify_ode(eq, f(x))`` to get all of the possible hints for an ODE. The default hint, ``default``, will use whatever hint is returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. See Hints below for more options that you can use for hint. ``simplify`` enables simplification by :py:meth:`~sympy.solvers.ode.ode.odesimp`. See its docstring for more information. Turn this off, for example, to disable solving of solutions for ``func`` or simplification of arbitrary constants. It will still integrate with this hint. Note that the solution may contain more arbitrary constants than the order of the ODE with this option enabled. ``xi`` and ``eta`` are the infinitesimal functions of an ordinary differential equation. They are the infinitesimals of the Lie group of point transformations for which the differential equation is invariant. The user can specify values for the infinitesimals. If nothing is specified, ``xi`` and ``eta`` are calculated using :py:meth:`~sympy.solvers.ode.infinitesimals` with the help of various heuristics. ``ics`` is the set of initial/boundary conditions for the differential equation. It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2): x3}`` and so on. For power series solutions, if no initial conditions are specified ``f(0)`` is assumed to be ``C0`` and the power series solution is calculated about 0. ``x0`` is the point about which the power series solution of a differential equation is to be evaluated. ``n`` gives the exponent of the dependent variable up to which the power series solution of a differential equation is to be evaluated. **Hints** Aside from the various solving methods, there are also some meta-hints that you can pass to :py:meth:`~sympy.solvers.ode.dsolve`: ``default``: This uses whatever hint is returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. This is the default argument to :py:meth:`~sympy.solvers.ode.dsolve`. ``all``: To make :py:meth:`~sympy.solvers.ode.dsolve` apply all relevant classification hints, use ``dsolve(ODE, func, hint="all")``. This will return a dictionary of ``hint:solution`` terms. If a hint causes dsolve to raise the ``NotImplementedError``, value of that hint's key will be the exception object raised. The dictionary will also include some special keys: - ``order``: The order of the ODE. See also :py:meth:`~sympy.solvers.deutils.ode_order` in ``deutils.py``. - ``best``: The simplest hint; what would be returned by ``best`` below. - ``best_hint``: The hint that would produce the solution given by ``best``. If more than one hint produces the best solution, the first one in the tuple returned by :py:meth:`~sympy.solvers.ode.classify_ode` is chosen. - ``default``: The solution that would be returned by default. This is the one produced by the hint that appears first in the tuple returned by :py:meth:`~sympy.solvers.ode.classify_ode`. ``all_Integral``: This is the same as ``all``, except if a hint also has a corresponding ``_Integral`` hint, it only returns the ``_Integral`` hint. This is useful if ``all`` causes :py:meth:`~sympy.solvers.ode.dsolve` to hang because of a difficult or impossible integral. This meta-hint will also be much faster than ``all``, because :py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine. ``best``: To have :py:meth:`~sympy.solvers.ode.dsolve` try all methods and return the simplest one. This takes into account whether the solution is solvable in the function, whether it contains any Integral classes (i.e. unevaluatable integrals), and which one is the shortest in size. See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for more info on hints, and the :py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints. **Tips** - You can declare the derivative of an unknown function this way: >>> from sympy import Function, Derivative >>> from sympy.abc import x # x is the independent variable >>> f = Function("f")(x) # f is a function of x >>> # f_ will be the derivative of f with respect to x >>> f_ = Derivative(f, x) - See ``test_ode.py`` for many tests, which serves also as a set of examples for how to use :py:meth:`~sympy.solvers.ode.dsolve`. - :py:meth:`~sympy.solvers.ode.dsolve` always returns an :py:class:`~sympy.core.relational.Equality` class (except for the case when the hint is ``all`` or ``all_Integral``). If possible, it solves the solution explicitly for the function being solved for. Otherwise, it returns an implicit solution. - Arbitrary constants are symbols named ``C1``, ``C2``, and so on. - Because all solutions should be mathematically equivalent, some hints may return the exact same result for an ODE. Often, though, two different hints will return the same solution formatted differently. The two should be equivalent. Also note that sometimes the values of the arbitrary constants in two different solutions may not be the same, because one constant may have "absorbed" other constants into it. - Do ``help(ode.ode_<hintname>)`` to get help more information on a specific hint, where ``<hintname>`` is the name of a hint without ``_Integral``. For system of ordinary differential equations ============================================= **Usage** ``dsolve(eq, func)`` -> Solve a system of ordinary differential equations ``eq`` for ``func`` being list of functions including `x(t)`, `y(t)`, `z(t)` where number of functions in the list depends upon the number of equations provided in ``eq``. **Details** ``eq`` can be any supported system of ordinary differential equations This can either be an :py:class:`~sympy.core.relational.Equality`, or an expression, which is assumed to be equal to ``0``. ``func`` holds ``x(t)`` and ``y(t)`` being functions of one variable which together with some of their derivatives make up the system of ordinary differential equation ``eq``. It is not necessary to provide this; it will be autodetected (and an error raised if it couldn't be detected). **Hints** The hints are formed by parameters returned by classify_sysode, combining them give hints name used later for forming method name. Examples ======== >>> from sympy import Function, dsolve, Eq, Derivative, sin, cos, symbols >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(Derivative(f(x), x, x) + 9*f(x), f(x)) Eq(f(x), C1*sin(3*x) + C2*cos(3*x)) >>> eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x) >>> dsolve(eq, hint='1st_exact') [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] >>> dsolve(eq, hint='almost_linear') [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] >>> t = symbols('t') >>> x, y = symbols('x, y', cls=Function) >>> eq = (Eq(Derivative(x(t),t), 12*t*x(t) + 8*y(t)), Eq(Derivative(y(t),t), 21*x(t) + 7*t*y(t))) >>> dsolve(eq) [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t)), Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t) + exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)))] >>> eq = (Eq(Derivative(x(t),t),x(t)*y(t)*sin(t)), Eq(Derivative(y(t),t),y(t)**2*sin(t))) >>> dsolve(eq) {Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t))), Eq(y(t), -1/(C1 - cos(t)))} """ if iterable(eq): 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 not 'power_series' in hint: if isinstance(rv, (Expr, Eq)): solved_constants = solve_ics([rv], [r['func']], cons(rv), ics) rv = rv.subs(solved_constants) else: rv1 = [] for s in rv: try: solved_constants = solve_ics([s], [r['func']], cons(s), ics) except ValueError: continue rv1.append(s.subs(solved_constants)) if len(rv1) == 1: return rv1[0] rv = rv1 return rv def solve_ics(sols, funcs, constants, ics): """ Solve for the constants given initial conditions ``sols`` is a list of solutions. ``funcs`` is a list of functions. ``constants`` is a list of constants. ``ics`` is the set of initial/boundary conditions for the differential equation. It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2): x3}`` and so on. Returns a dictionary mapping constants to values. ``solution.subs(constants)`` will replace the constants in ``solution``. Example ======= >>> # From dsolve(f(x).diff(x) - f(x), f(x)) >>> from sympy import symbols, Eq, exp, Function >>> from sympy.solvers.ode.ode import solve_ics >>> f = Function('f') >>> x, C1 = symbols('x C1') >>> sols = [Eq(f(x), C1*exp(x))] >>> funcs = [f(x)] >>> constants = [C1] >>> ics = {f(0): 2} >>> solved_constants = solve_ics(sols, funcs, constants, ics) >>> solved_constants {C1: 2} >>> sols[0].subs(solved_constants) Eq(f(x), 2*exp(x)) """ # Assume ics are of the form f(x0): value or Subs(diff(f(x), x, n), (x, # x0)): value (currently checked by classify_ode). To solve, replace x # with x0, f(x0) with value, then solve for constants. For f^(n)(x0), # differentiate the solution n times, so that f^(n)(x) appears. x = funcs[0].args[0] diff_sols = [] subs_sols = [] diff_variables = set() for funcarg, value in ics.items(): if isinstance(funcarg, AppliedUndef): x0 = funcarg.args[0] matching_func = [f for f in funcs if f.func == funcarg.func][0] S = sols elif isinstance(funcarg, (Subs, Derivative)): if isinstance(funcarg, Subs): # Make sure it stays a subs. Otherwise subs below will produce # a different looking term. funcarg = funcarg.doit() if isinstance(funcarg, Subs): deriv = funcarg.expr x0 = funcarg.point[0] variables = funcarg.expr.variables matching_func = deriv elif isinstance(funcarg, Derivative): deriv = funcarg x0 = funcarg.variables[0] variables = (x,)*len(funcarg.variables) matching_func = deriv.subs(x0, x) if variables not in diff_variables: for sol in sols: if sol.has(deriv.expr.func): diff_sols.append(Eq(sol.lhs.diff(*variables), sol.rhs.diff(*variables))) diff_variables.add(variables) S = diff_sols else: raise NotImplementedError("Unrecognized initial condition") for sol in S: if sol.has(matching_func): sol2 = sol sol2 = sol2.subs(x, x0) sol2 = sol2.subs(funcarg, value) # This check is necessary because of issue #15724 if not isinstance(sol2, BooleanAtom) or not subs_sols: subs_sols = [s for s in subs_sols if not isinstance(s, BooleanAtom)] subs_sols.append(sol2) # TODO: Use solveset here try: solved_constants = solve(subs_sols, constants, dict=True) except NotImplementedError: solved_constants = [] # XXX: We can't differentiate between the solution not existing because of # invalid initial conditions, and not existing because solve is not smart # enough. If we could use solveset, this might be improvable, but for now, # we use NotImplementedError in this case. if not solved_constants: raise ValueError("Couldn't solve for initial conditions") if solved_constants == True: raise ValueError("Initial conditions did not produce any solutions for constants. Perhaps they are degenerate.") if len(solved_constants) > 1: raise NotImplementedError("Initial conditions produced too many solutions for constants") return solved_constants[0] def classify_ode(eq, func=None, dict=False, ics=None, *, 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 = 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 doesn't 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 doesn't 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) = 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.get('x0') terms = match.get('terms', 5) p = match[match['a3']] q = match[match['b3']] r = match[match['c3']] seriesdict = {} recurr = Function("r") # Generating the recurrence relation which works this way: # for the second order term the summation begins at n = 2. The coefficients # p is multiplied with an*(n - 1)*(n - 2)*x**n-2 and a substitution is made such that # the exponent of x becomes n. # For example, if p is x, then the second degree recurrence term is # an*(n - 1)*(n - 2)*x**n-1, substituting (n - 1) as n, it transforms to # an+1*n*(n - 1)*x**n. # A similar process is done with the first order and zeroth order term. coefflist = [(recurr(n), r), (n*recurr(n), q), (n*(n - 1)*recurr(n), p)] for index, coeff in enumerate(coefflist): if coeff[1]: f2 = powsimp(expand((coeff[1]*(x - x0)**(n - index)).subs(x, x + x0))) if f2.is_Add: addargs = f2.args else: addargs = [f2] for arg in addargs: powm = arg.match(s*x**k) term = coeff[0]*powm[s] if not powm[k].is_Symbol: term = term.subs(n, n - powm[k].as_independent(n)[0]) startind = powm[k].subs(n, index) # Seeing if the startterm can be reduced further. # If it vanishes for n lesser than startind, it is # equal to summation from n. if startind: for i in reversed(range(startind)): if not term.subs(n, i): seriesdict[term] = i else: seriesdict[term] = i + 1 break else: seriesdict[term] = S.Zero # Stripping of terms so that the sum starts with the same number. teq = S.Zero suminit = seriesdict.values() rkeys = seriesdict.keys() req = Add(*rkeys) if any(suminit): maxval = max(suminit) for term in seriesdict: val = seriesdict[term] if val != maxval: for i in range(val, maxval): teq += term.subs(n, val) finaldict = {} if teq: fargs = teq.atoms(AppliedUndef) if len(fargs) == 1: finaldict[fargs.pop()] = 0 else: maxf = max(fargs, key = lambda x: x.args[0]) sol = solve(teq, maxf) if isinstance(sol, list): sol = sol[0] finaldict[maxf] = sol # Finding the recurrence relation in terms of the largest term. fargs = req.atoms(AppliedUndef) maxf = max(fargs, key = lambda x: x.args[0]) minf = min(fargs, key = lambda x: x.args[0]) if minf.args[0].is_Symbol: startiter = 0 else: startiter = -minf.args[0].as_independent(n)[0] lhs = maxf rhs = solve(req, maxf) if isinstance(rhs, list): rhs = rhs[0] # Checking how many values are already present tcounter = len([t for t in finaldict.values() if t]) for _ in range(tcounter, terms - 3): # Assuming c0 and c1 to be arbitrary check = rhs.subs(n, startiter) nlhs = lhs.subs(n, startiter) nrhs = check.subs(finaldict) finaldict[nlhs] = nrhs startiter += 1 # Post processing series = C0 + C1*(x - x0) for term in finaldict: if finaldict[term]: fact = term.args[0] series += (finaldict[term].subs([(recurr(0), C0), (recurr(1), C1)])*( x - x0)**fact) series = collect(expand_mul(series), [C0, C1]) + Order(x**terms) return Eq(f(x), series) def ode_2nd_power_series_regular(eq, func, order, match): r""" Gives a power series solution to a second order homogeneous differential equation with polynomial coefficients at a regular point. A second order homogeneous differential equation is of the form .. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0 A point is said to regular singular at `x0` if `x - x0\frac{Q(x)}{P(x)}` and `(x - x0)^{2}\frac{R(x)}{P(x)}` are analytic at `x0`. For simplicity `P(x)`, `Q(x)` and `R(x)` are assumed to be polynomials. The algorithm for finding the power series solutions is: 1. Try expressing `(x - x0)P(x)` and `((x - x0)^{2})Q(x)` as power series solutions about x0. Find `p0` and `q0` which are the constants of the power series expansions. 2. Solve the indicial equation `f(m) = m(m - 1) + m*p0 + q0`, to obtain the roots `m1` and `m2` of the indicial equation. 3. If `m1 - m2` is a non integer there exists two series solutions. If `m1 = m2`, there exists only one solution. If `m1 - m2` is an integer, then the existence of one solution is confirmed. The other solution may or may not exist. The power series solution is of the form `x^{m}\sum_{n=0}^\infty a_{n}x^{n}`. The coefficients are determined by the following recurrence relation. `a_{n} = -\frac{\sum_{k=0}^{n-1} q_{n-k} + (m + k)p_{n-k}}{f(m + n)}`. For the case in which `m1 - m2` is an integer, it can be seen from the recurrence relation that for the lower root `m`, when `n` equals the difference of both the roots, the denominator becomes zero. So if the numerator is not equal to zero, a second series solution exists. Examples ======== >>> from sympy import dsolve, Function, pprint >>> from sympy.abc import x >>> f = Function("f") >>> eq = x*(f(x).diff(x, 2)) + 2*(f(x).diff(x)) + x*f(x) >>> pprint(dsolve(eq, hint='2nd_power_series_regular')) / 6 4 2 \ | x x x | / 4 2 \ C1*|- --- + -- - -- + 1| | x x | \ 720 24 2 / / 6\ f(x) = C2*|--- - -- + 1| + ------------------------ + O\x / \120 6 / x References ========== - George E. Simmons, "Differential Equations with Applications and Historical Notes", p.p 176 - 184 """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) m = Dummy("m") # for solving the indicial equation x0 = match.get('x0') terms = match.get('terms', 5) p = match['p'] q = match['q'] # Generating the indicial equation indicial = [] for term in [p, q]: if not term.has(x): indicial.append(term) else: term = series(term, 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 doesn't depend on x then it # means that some value of the constants in sol1 is a special case of # sol2 corresponding to a particular choice of the integration constants. # In case the solution is in implicit form we subtract the sides soln1 = soln1.rhs - soln1.lhs soln2 = soln2.rhs - soln2.lhs # Work for the series solution if soln1.has(Order) and soln2.has(Order): if soln1.getO() == soln2.getO(): soln1 = soln1.removeO() soln2 = soln2.removeO() else: return False elif soln1.has(Order) or soln2.has(Order): return False constants1 = soln1.free_symbols.difference(eq.free_symbols) constants2 = soln2.free_symbols.difference(eq.free_symbols) constants1_new = get_numbered_constants(Tuple(soln1, soln2), len(constants1)) if len(constants1) == 1: constants1_new = {constants1_new} for c_old, c_new in zip(constants1, constants1_new): soln1 = soln1.subs(c_old, c_new) # n equations for sol1 = sol2, sol1'=sol2', ... lhs = soln1 rhs = soln2 eqns = [Eq(lhs, rhs)] for n in range(1, order): lhs = lhs.diff(var) rhs = rhs.diff(var) eq = Eq(lhs, rhs) eqns.append(eq) # BooleanTrue/False awkwardly show up for trivial equations if any(isinstance(eq, BooleanFalse) for eq in eqns): return False eqns = [eq for eq in eqns if not isinstance(eq, BooleanTrue)] try: constant_solns = solve(eqns, constants2) except NotImplementedError: return False # Sometimes returns a dict and sometimes a list of dicts if isinstance(constant_solns, dict): constant_solns = [constant_solns] # after solving the issue 17418, maybe we don't need the following checksol code. for constant_soln in constant_solns: for eq in eqns: eq=eq.rhs-eq.lhs if checksol(eq, constant_soln) is not True: return False # If any solution gives all constants as expressions that don't depend on # x then there exists constants for soln2 that give soln1 for constant_soln in constant_solns: if not any(c.has(var) for c in constant_soln.values()): return True return False def 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 >>> from sympy.solvers.ode.ode import dsolve >>> from sympy.abc import x >>> f = Function('f') >>> eq = exp(x)*(f(x).diff(x)) - f(x) >>> pprint(dsolve(eq, hint='1st_power_series')) 3 4 5 C1*x C1*x C1*x / 6\ f(x) = C1 + C1*x - ----- + ----- + ----- + O\x / 6 24 60 References ========== - Travis W. Walker, Analytic power series technique for solving first-order differential equations, p.p 17, 18 """ x = func.args[0] y = match['y'] f = func.func h = -match[match['d']]/match[match['e']] point = match.get('f0') value = match.get('f0val') terms = match.get('terms') # First term F = h if not h: return Eq(f(x), value) # Initialization series = value if terms > 1: hc = h.subs({x: point, y: value}) if hc.has(oo) or hc.has(nan) or hc.has(zoo): # Derivative does not exist, not analytic return Eq(f(x), oo) elif hc: series += hc*(x - point) for factcount in range(2, terms): Fnew = F.diff(x) + F.diff(y)*h Fnewc = Fnew.subs({x: point, y: value}) # Same logic as above if Fnewc.has(oo) or Fnewc.has(nan) or Fnewc.has(-oo) or Fnewc.has(zoo): return Eq(f(x), oo) series += Fnewc*((x - point)**factcount)/factorial(factcount) F = Fnew series += Order(x**terms) return Eq(f(x), series) def 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
be63588d7d1be0627cd7598bbf9837effa63af8f98676d7ca4516bfeda57048b
# # 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 Function, pprint, sin, cos >>> from sympy.solvers.ode import dsolve >>> 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.solvers.ode import dsolve, checkodesol >>> from sympy import pprint, Function >>> f = Function('f') >>> y = f(x) >>> genform = a*y.diff(x) - (b*y**2 + c*y/x + d/x**2) >>> sol = dsolve(genform, y, 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 Function, pprint >>> from sympy.solvers.ode.ode import dsolve >>> 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 Function, pprint >>> from sympy.solvers.ode.ode import dsolve >>> 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 >>> from sympy.abc import x >>> from sympy.solvers.ode.single import LinearCoefficients >>> from sympy.functions.elementary.trigonometric import sin >>> 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 doesn't use integration, making it faster and more reliable. Warning, using simplify=False with 'nth_linear_constant_coeff_variation_of_parameters' in :py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will not attempt to simplify the Wronskian before integrating. It is recommended that you only use simplify=False with 'nth_linear_constant_coeff_variation_of_parameters_Integral' for this method, especially if the solution to the homogeneous equation has trigonometric functions in it. Examples ======== >>> from sympy import Function, dsolve, pprint, exp, log >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x, 3) - 3*f(x).diff(x, 2) + ... 3*f(x).diff(x) - f(x) - exp(x)*log(x), f(x), ... hint='nth_linear_constant_coeff_variation_of_parameters')) / / / 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 doesn't use integration, making it faster and more reliable. Warning, using simplify=False with 'nth_linear_constant_coeff_variation_of_parameters' in :py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will not attempt to simplify the Wronskian before integrating. It is recommended that you only use simplify=False with 'nth_linear_constant_coeff_variation_of_parameters_Integral' for this method, especially if the solution to the homogeneous equation has trigonometric functions in it. Examples ======== >>> from sympy import Function, dsolve, Derivative >>> from sympy.abc import x >>> f = Function('f') >>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - x**4 >>> dsolve(eq, f(x), ... hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters').expand() Eq(f(x), C1*x + C2*x**2 + x**4/6) """ 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.solvers.ode import dsolve >>> from sympy import 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
f727f60ae6edc949ffe5a0111007e1772a0cf66946134442903020dc59fd207a
r""" This module contains :py:meth:`~sympy.solvers.ode.riccati.solve_riccati`, a function which gives all rational particular solutions to first order Riccati ODEs. A general first order Riccati ODE is given by - .. math:: y' = b_0(x) + b_1(x)w + b_2(x)w^2 where `b_0, b_1` and `b_2` can be arbitrary rational functions of `x` with `b_2 \ne 0`. When `b_2 = 0`, the equation is not a Riccati ODE anymore and becomes a Linear ODE. Similarly, when `b_0 = 0`, the equation is a Bernoulli ODE. The algorithm presented below can find rational solution(s) to all ODEs with `b_2 \ne 0` that have a rational solution, or prove that no rational solution exists for the equation. Background ========== A Riccati equation can be transformed to its normal form .. math:: y' + y^2 = a(x) using the transformation .. math:: y = -b_2(x) - \frac{b'_2(x)}{2 b_2(x)} - \frac{b_1(x)}{2} where `a(x)` is given by .. math:: a(x) = \frac{1}{4}\left(\frac{b_2'}{b_2} + b_1\right)^2 - \frac{1}{2}\left(\frac{b_2'}{b_2} + b_1\right)' - b_0 b_2 Thus, we can develop an algorithm to solve for the Riccati equation in its normal form, which would in turn give us the solution for the original Riccati equation. Algorithm ========= The algorithm implemented here is presented in the Ph.D thesis "Rational and Algebraic Solutions of First-Order Algebraic ODEs" by N. Thieu Vo. The entire thesis can be found here - https://www3.risc.jku.at/publications/download/risc_5387/PhDThesisThieu.pdf We have only implemented the Rational Riccati solver (Algorithm 11, Pg 78-82 in Thesis). Before we proceed towards the implementation of the algorithm, a few definitions to understand are - 1. Valuation of a Rational Function at `\infty`: The valuation of a rational function `p(x)` at `\infty` is equal to the difference between the degree of the denominator and the numerator of `p(x)`. NOTE: A general definition of valuation of a rational function at any value of `x` can be found in Pg 63 of the thesis, but is not of any interest for this algorithm. 2. Zeros and Poles of a Rational Function: Let `a(x) = \frac{S(x)}{T(x)}, T \ne 0` be a rational function of `x`. Then - a. The Zeros of `a(x)` are the roots of `S(x)`. b. The Poles of `a(x)` are the roots of `T(x)`. However, `\infty` can also be a pole of a(x). We say that `a(x)` has a pole at `\infty` if `a(\frac{1}{x})` has a pole at 0. Every pole is associated with an order that is equal to the multiplicity of its appearence as a root of `T(x)`. A pole is called a simple pole if it has an order 1. Similarly, a pole is called a multiple pole if it has an order `\ge` 2. Necessary Conditions ==================== For a Riccati equation in its normal form, .. math:: y' + y^2 = a(x) we can define a. A pole is called a movable pole if it is a pole of `y(x)` and is not a pole of `a(x)`. b. Similarly, a pole is called a non-movable pole if it is a pole of both `y(x)` and `a(x)`. Then, the algorithm states that a rational solution exists only if - a. Every pole of `a(x)` must be either a simple pole or a multiple pole of even order. b. The valuation of `a(x)` at `\infty` must be even or be `\ge` 2. This algorithm finds all possible rational solutions for the Riccati ODE. If no rational solutions are found, it means that no rational solutions exist. The algorithm works for Riccati ODEs where the coefficients are rational functions in the independent variable `x` with rational number coefficients i.e. in `Q(x)`. The coefficients in the rational function cannot be floats, irrational numbers, symbols or any other kind of expression. The reasons for this are - 1. When using symbols, different symbols could take the same value and this would affect the multiplicity of poles if symbols are present here. 2. An integer degree bound is required to calculate a polynomial solution to an auxiliary differential equation, which in turn gives the particular solution for the original ODE. If symbols/floats/irrational numbers are present, we cannot determine if the expression for the degree bound is an integer or not. Solution ======== With these definitions, we can state a general form for the solution of the equation. `y(x)` must have the form - .. math:: y(x) = \sum_{i=1}^{n} \sum_{j=1}^{r_i} \frac{c_{ij}}{(x - x_i)^j} + \sum_{i=1}^{m} \frac{1}{x - \chi_i} + \sum_{i=0}^{N} d_i x^i where `x_1, x_2, \dots, x_n` are non-movable poles of `a(x)`, `\chi_1, \chi_2, \dots, \chi_m` are movable poles of `a(x)`, and the values of `N, n, r_1, r_2, \dots, r_n` can be determined from `a(x)`. The coefficient vectors `(d_0, d_1, \dots, d_N)` and `(c_{i1}, c_{i2}, \dots, c_{i r_i})` can be determined from `a(x)`. We will have 2 choices each of these vectors and part of the procedure is figuring out which of the 2 should be used to get the solution correctly. Implementation ============== In this implementatin, we use ``Poly`` to represent a rational function rather than using ``Expr`` since ``Poly`` is much faster. Since we cannot represent rational functions directly using ``Poly``, we instead represent a rational function with 2 ``Poly`` objects - one for its numerator and the other for its denominator. The code is written to match the steps given in the thesis (Pg 82) Step 0 : Match the equation - Find `b_0, b_1` and `b_2`. If `b_2 = 0` or no such functions exist, raise an error Step 1 : Transform the equation to its normal form as explained in the theory section. Step 2 : Initialize an empty set of solutions, ``sol``. Step 3 : If `a(x) = 0`, append `\frac{1}/{(x - C1)}` to ``sol``. Step 4 : If `a(x)` is a rational non-zero number, append `\pm \sqrt{a}` to ``sol``. Step 5 : Find the poles and their multiplicities of `a(x)`. Let the number of poles be `n`. Also find the valuation of `a(x)` at `\infty` using ``val_at_inf``. NOTE: Although the algorithm considers `\infty` as a pole, it is not mentioned if it a part of the set of finite poles. `\infty` is NOT a part of the set of finite poles. If a pole exists at `\infty`, we use its multiplicty to find the laurent series of `a(x)` about `\infty`. Step 6 : Find `n` c-vectors (one for each pole) and 1 d-vector using ``construct_c`` and ``construct_d``. Now, determine all the ``2**(n + 1)`` combinations of choosing between 2 choices for each of the `n` c-vectors and 1 d-vector. NOTE: The equation for `d_{-1}` in Case 4 (Pg 80) has a printinig mistake. The term `- d_N` must be replaced with `-N d_N`. The same has been explained in the code as well. For each of these above combinations, do Step 8 : Compute `m` in ``compute_m_ybar``. `m` is the degree bound of the polynomial solution we must find for the auxiliary equation. Step 9 : In ``compute_m_ybar``, compute ybar as well where ``ybar`` is one part of y(x) - .. math:: \overline{y}(x) = \sum_{i=1}^{n} \sum_{j=1}^{r_i} \frac{c_{ij}}{(x - x_i)^j} + \sum_{i=0}^{N} d_i x^i Step 10 : If `m` is a non-negative integer - Step 11: Find a polynomial solution of degree `m` for the auxiliary equation. There are 2 cases possible - a. `m` is a non-negative integer: We can solve for the coefficients in `p(x)` using Undetermined Coefficients. b. `m` is not a non-negative integer: In this case, we cannot find a polynomial solution to the auxiliary equation, and hence, we ignore this value of `m`. Step 12 : For each `p(x)` that exists, append `ybar + \frac{p'(x)}{p(x)}` to ``sol``. Step 13 : For each solution in ``sol``, apply an inverse transformation, so that the solutions of the original equation are found using the solutions of the equation in its normal form. """ from itertools import product from sympy.core import S from sympy.core.add import Add from sympy.core.numbers import oo, Float from sympy.core.function import count_ops from sympy.core.relational import Eq from sympy.core.symbol import symbols, Symbol, Dummy from sympy.functions import sqrt, exp from sympy.functions.elementary.complexes import sign from sympy.integrals.integrals import Integral from sympy.polys.domains import ZZ from sympy.polys.polytools import Poly from sympy.polys.polyroots import roots from sympy.solvers.solveset import linsolve def riccati_normal(w, x, b1, b2): """ Given a solution `w(x)` to the equation .. math:: w'(x) = b_0(x) + b_1(x)*w(x) + b_2(x)*w(x)^2 and rational function coefficients `b_1(x)` and `b_2(x)`, this function transforms the solution to give a solution `y(x)` for its corresponding normal Riccati ODE .. math:: y'(x) + y(x)^2 = a(x) using the transformation .. math:: y(x) = -b_2(x)*w(x) - b'_2(x)/(2*b_2(x)) - b_1(x)/2 """ return -b2*w - b2.diff(x)/(2*b2) - b1/2 def riccati_inverse_normal(y, x, b1, b2, bp=None): """ Inverse transforming the solution to the normal Riccati ODE to get the solution to the Riccati ODE. """ # bp is the expression which is independent of the solution # and hence, it need not be computed again if bp is None: bp = -b2.diff(x)/(2*b2**2) - b1/(2*b2) # w(x) = -y(x)/b2(x) - b2'(x)/(2*b2(x)^2) - b1(x)/(2*b2(x)) return -y/b2 + bp def riccati_reduced(eq, f, x): """ Convert a Riccati ODE into its corresponding normal Riccati ODE. """ match, funcs = match_riccati(eq, f, x) # If equation is not a Riccati ODE, exit if not match: return False # Using the rational functions, find the expression for a(x) b0, b1, b2 = funcs a = -b0*b2 + b1**2/4 - b1.diff(x)/2 + 3*b2.diff(x)**2/(4*b2**2) + b1*b2.diff(x)/(2*b2) - \ b2.diff(x, 2)/(2*b2) # Normal form of Riccati ODE is f'(x) + f(x)^2 = a(x) return f(x).diff(x) + f(x)**2 - a def linsolve_dict(eq, syms): """ Get the output of linsolve as a dict """ # Convert tuple type return value of linsolve # to a dictionary for ease of use sol = linsolve(eq, syms) if not sol: return {} return {k:v for k, v in zip(syms, list(sol)[0])} def match_riccati(eq, f, x): """ A function that matches and returns the coefficients if an equation is a Riccati ODE Parameters ========== eq: Equation to be matched f: Dependent variable x: Independent variable Returns ======= match: True if equation is a Riccati ODE, False otherwise funcs: [b0, b1, b2] if match is True, [] otherwise. Here, b0, b1 and b2 are rational functions which match the equation. """ # Group terms based on f(x) if isinstance(eq, Eq): eq = eq.lhs - eq.rhs eq = eq.expand().collect(f(x)) cf = eq.coeff(f(x).diff(x)) # There must be an f(x).diff(x) term. # eq must be an Add object since we are using the expanded # equation and it must have atleast 2 terms (b2 != 0) if cf != 0 and isinstance(eq, Add): # Divide all coefficients by the coefficient of f(x).diff(x) # and add the terms again to get the same equation eq = Add(*((x/cf).cancel() for x in eq.args)).collect(f(x)) # Match the equation with the pattern b1 = -eq.coeff(f(x)) b2 = -eq.coeff(f(x)**2) b0 = (f(x).diff(x) - b1*f(x) - b2*f(x)**2 - eq).expand() funcs = [b0, b1, b2] # Check if coefficients are not symbols and floats if any(len(x.atoms(Symbol)) > 1 or len(x.atoms(Float)) for x in funcs): return False, [] # If b_0(x) contains f(x), it is not a Riccati ODE if len(b0.atoms(f)) or not all((b2 != 0, b0.is_rational_function(x), b1.is_rational_function(x), b2.is_rational_function(x))): return False, [] return True, funcs return False, [] def val_at_inf(num, den, x): # Valuation of a rational function at oo = deg(denom) - deg(numer) return den.degree(x) - num.degree(x) def check_necessary_conds(val_inf, muls): """ The necessary conditions for a rational solution to exist are as follows - i) Every pole of a(x) must be either a simple pole or a multiple pole of even order. ii) The valuation of a(x) at infinity must be even or be greater than or equal to 2. Here, a simple pole is a pole with multiplicity 1 and a multiple pole is a pole with multiplicity greater than 1. """ return (val_inf >= 2 or (val_inf <= 0 and val_inf%2 == 0)) and \ all(mul == 1 or (mul%2 == 0 and mul >= 2) for mul in muls) def inverse_transform_poly(num, den, x): """ A function to make the substitution x -> 1/x in a rational function that is represented using Poly objects for numerator and denominator. """ # Declare for reuse one = Poly(1, x) xpoly = Poly(x, x) # Check if degree of numerator is same as denominator pwr = val_at_inf(num, den, x) if pwr >= 0: # Denominator has greater degree. Substituting x with # 1/x would make the extra power go to the numerator if num.expr != 0: num = num.transform(one, xpoly) * x**pwr den = den.transform(one, xpoly) else: # Numerator has greater degree. Substituting x with # 1/x would make the extra power go to the denominator num = num.transform(one, xpoly) den = den.transform(one, xpoly) * x**(-pwr) return num.cancel(den, include=True) def limit_at_inf(num, den, x): """ Find the limit of a rational function at oo """ # pwr = degree(num) - degree(den) pwr = -val_at_inf(num, den, x) # Numerator has a greater degree than denominator # Limit at infinity would depend on the sign of the # leading coefficients of numerator and denominator if pwr > 0: return oo*sign(num.LC()/den.LC()) # Degree of numerator is equal to that of denominator # Limit at infinity is just the ratio of leading coeffs elif pwr == 0: return num.LC()/den.LC() # Degree of numerator is less than that of denominator # Limit at infinity is just 0 else: return 0 def construct_c_case_1(num, den, x, pole): # Find the coefficient of 1/(x - pole)**2 in the # Laurent series expansion of a(x) about pole. num1, den1 = (num*Poly((x - pole)**2, x, extension=True)).cancel(den, include=True) r = (num1.subs(x, pole))/(den1.subs(x, pole)) # If multiplicity is 2, the coefficient to be added # in the c-vector is c = (1 +- sqrt(1 + 4*r))/2 if r != -S(1)/4: return [[(1 + sqrt(1 + 4*r))/2], [(1 - sqrt(1 + 4*r))/2]] return [[S.Half]] def construct_c_case_2(num, den, x, pole, mul): # Generate the coefficients using the recurrence # relation mentioned in (5.14) in the thesis (Pg 80) # r_i = mul/2 ri = mul//2 # Find the Laurent series coefficients about the pole ser = rational_laurent_series(num, den, x, pole, mul, 6) # Start with an empty memo to store the coefficients # This is for the plus case cplus = [0 for i in range(ri)] # Base Case cplus[ri-1] = sqrt(ser[2*ri]) # Iterate backwards to find all coefficients s = ri - 1 sm = 0 for s in range(ri-1, 0, -1): sm = 0 for j in range(s+1, ri): sm += cplus[j-1]*cplus[ri+s-j-1] if s!= 1: cplus[s-1] = (ser[ri+s] - sm)/(2*cplus[ri-1]) # Memo for the minus case cminus = [-x for x in cplus] # Find the 0th coefficient in the recurrence cplus[0] = (ser[ri+s] - sm - ri*cplus[ri-1])/(2*cplus[ri-1]) cminus[0] = (ser[ri+s] - sm - ri*cminus[ri-1])/(2*cminus[ri-1]) # Add both the plus and minus cases' coefficients if cplus != cminus: return [cplus, cminus] return cplus def construct_c_case_3(): # If multiplicity is 1, the coefficient to be added # in the c-vector is 1 (no choice) return [[1]] def construct_c(num, den, x, poles, muls): """ Helper function to calculate the coefficients in the c-vector for each pole. """ c = [] for pole, mul in zip(poles, muls): c.append([]) # Case 3 if mul == 1: # Add the coefficients from Case 3 c[-1].extend(construct_c_case_3()) # Case 1 elif mul == 2: # Add the coefficients from Case 1 c[-1].extend(construct_c_case_1(num, den, x, pole)) # Case 2 else: # Add the coefficients from Case 2 c[-1].extend(construct_c_case_2(num, den, x, pole, mul)) return c def construct_d_case_4(ser, N): # Initialize an empty vector dplus = [0 for i in range(N+2)] # d_N = sqrt(a_{2*N}) dplus[N] = sqrt(ser[2*N]) # Use the recurrence relations to find # the value of d_s for s in range(N-1, -2, -1): sm = 0 for j in range(s+1, N): sm += dplus[j]*dplus[N+s-j] if s != -1: dplus[s] = (ser[N+s] - sm)/(2*dplus[N]) # Coefficients for the case of d_N = -sqrt(a_{2*N}) dminus = [-x for x in dplus] # The third equation in Eq 5.15 of the thesis is WRONG! # d_N must be replaced with N*d_N in that equation. dplus[-1] = (ser[N+s] - N*dplus[N] - sm)/(2*dplus[N]) dminus[-1] = (ser[N+s] - N*dminus[N] - sm)/(2*dminus[N]) if dplus != dminus: return [dplus, dminus] return dplus def construct_d_case_5(ser): # List to store coefficients for plus case dplus = [0, 0] # d_0 = sqrt(a_0) dplus[0] = sqrt(ser[0]) # d_(-1) = a_(-1)/(2*d_0) dplus[-1] = ser[-1]/(2*dplus[0]) # Coefficients for the minus case are just the negative # of the coefficients for the positive case. dminus = [-x for x in dplus] if dplus != dminus: return [dplus, dminus] return dplus def construct_d_case_6(num, den, x): # s_oo = lim x->0 1/x**2 * a(1/x) which is equivalent to # s_oo = lim x->oo x**2 * a(x) s_inf = limit_at_inf(Poly(x**2, x)*num, den, x) # d_(-1) = (1 +- sqrt(1 + 4*s_oo))/2 if s_inf != -S(1)/4: return [[(1 + sqrt(1 + 4*s_inf))/2], [(1 - sqrt(1 + 4*s_inf))/2]] return [[S.Half]] def construct_d(num, den, x, val_inf): """ Helper function to calculate the coefficients in the d-vector based on the valuation of the function at oo. """ N = -val_inf//2 # Multiplicity of oo as a pole mul = -val_inf if val_inf < 0 else 0 ser = rational_laurent_series(num, den, x, oo, mul, 1) # Case 4 if val_inf < 0: d = construct_d_case_4(ser, N) # Case 5 elif val_inf == 0: d = construct_d_case_5(ser) # Case 6 else: d = construct_d_case_6(num, den, x) return d def rational_laurent_series(num, den, x, r, m, n): r""" The function computes the Laurent series coefficients of a rational function. Parameters ========== num: A Poly object that is the numerator of `f(x)`. den: A Poly object that is the denominator of `f(x)`. x: The variable of expansion of the series. r: The point of expansion of the series. m: Multiplicity of r if r is a pole of `f(x)`. Should be zero otherwise. n: Order of the term upto which the series is expanded. Returns ======= series: A dictionary that has power of the term as key and coefficient of that term as value. Below is a basic outline of how the Laurent series of a rational function `f(x)` about `x_0` is being calculated - 1. Substitute `x + x_0` in place of `x`. If `x_0` is a pole of `f(x)`, multiply the expression by `x^m` where `m` is the multiplicity of `x_0`. Denote the the resulting expression as g(x). We do this substitution so that we can now find the Laurent series of g(x) about `x = 0`. 2. We can then assume that the Laurent series of `g(x)` takes the following form - .. math:: g(x) = \frac{num(x)}{den(x)} = \sum_{m = 0}^{\infty} a_m x^m where `a_m` denotes the Laurent series coefficients. 3. Multiply the denominator to the RHS of the equation and form a recurrence relation for the coefficients `a_m`. """ one = Poly(1, x, extension=True) if r == oo: # Series at x = oo is equal to first transforming # the function from x -> 1/x and finding the # series at x = 0 num, den = inverse_transform_poly(num, den, x) r = S(0) if r: # For an expansion about a non-zero point, a # transformation from x -> x + r must be made num = num.transform(Poly(x + r, x, extension=True), one) den = den.transform(Poly(x + r, x, extension=True), one) # Remove the pole from the denominator if the series # expansion is about one of the poles num, den = (num*x**m).cancel(den, include=True) # Equate coefficients for the first terms (base case) maxdegree = 1 + max(num.degree(), den.degree()) syms = symbols(f'a:{maxdegree}', cls=Dummy) diff = num - den * Poly(syms[::-1], x) coeff_diffs = diff.all_coeffs()[::-1][:maxdegree] (coeffs, ) = linsolve(coeff_diffs, syms) # Use the recursion relation for the rest recursion = den.all_coeffs()[::-1] div, rec_rhs = recursion[0], recursion[1:] series = list(coeffs) while len(series) < n: next_coeff = Add(*(c*series[-1-n] for n, c in enumerate(rec_rhs))) / div series.append(-next_coeff) series = {m - i: val for i, val in enumerate(series)} return series def compute_m_ybar(x, poles, choice, N): """ Helper function to calculate - 1. m - The degree bound for the polynomial solution that must be found for the auxiliary differential equation. 2. ybar - Part of the solution which can be computed using the poles, c and d vectors. """ ybar = 0 m = Poly(choice[-1][-1], x, extension=True) # Calculate the first (nested) summation for ybar # as given in Step 9 of the Thesis (Pg 82) for i in range(len(poles)): for j in range(len(choice[i])): ybar += choice[i][j]/(x - poles[i])**(j+1) m -= Poly(choice[i][0], x, extension=True) # Calculate the second summation for ybar for i in range(N+1): ybar += choice[-1][i]*x**i return (m.expr, ybar) def solve_aux_eq(numa, dena, numy, deny, x, m): """ Helper function to find a polynomial solution of degree m for the auxiliary differential equation. """ # Assume that the solution is of the type # p(x) = C_0 + C_1*x + ... + C_{m-1}*x**(m-1) + x**m psyms = symbols(f'C0:{m}', cls=Dummy) K = ZZ[psyms] psol = Poly(K.gens, x, domain=K) + Poly(x**m, x, domain=K) # Eq (5.16) in Thesis - Pg 81 auxeq = (dena*(numy.diff(x)*deny - numy*deny.diff(x) + numy**2) - numa*deny**2)*psol if m >= 1: px = psol.diff(x) auxeq += px*(2*numy*deny*dena) if m >= 2: auxeq += px.diff(x)*(deny**2*dena) if m != 0: # m is a non-zero integer. Find the constant terms using undetermined coefficients return psol, linsolve_dict(auxeq.all_coeffs(), psyms), True else: # m == 0 . Check if 1 (x**0) is a solution to the auxiliary equation return S.One, auxeq, auxeq == 0 def remove_redundant_sols(sol1, sol2, x): """ Helper function to remove redundant solutions to the differential equation. """ # If y1 and y2 are redundant solutions, there is # some value of the arbitrary constant for which # they will be equal syms1 = sol1.atoms(Symbol, Dummy) syms2 = sol2.atoms(Symbol, Dummy) num1, den1 = [Poly(e, x, extension=True) for e in sol1.together().as_numer_denom()] num2, den2 = [Poly(e, x, extension=True) for e in sol2.together().as_numer_denom()] # Cross multiply e = num1*den2 - den1*num2 # Check if there are any constants syms = list(e.atoms(Symbol, Dummy)) if len(syms): # Find values of constants for which solutions are equal redn = linsolve(e.all_coeffs(), syms) if len(redn): # Return the general solution over a particular solution if len(syms1) > len(syms2): return sol2 # If both have constants, return the lesser complex solution elif len(syms1) == len(syms2): return sol1 if count_ops(syms1) >= count_ops(syms2) else sol2 else: return sol1 def get_gen_sol_from_part_sol(part_sols, a, x): """" Helper function which computes the general solution for a Riccati ODE from its particular solutions. There are 3 cases to find the general solution from the particular solutions for a Riccati ODE depending on the number of particular solution(s) we have - 1, 2 or 3. For more information, see Section 6 of "Methods of Solution of the Riccati Differential Equation" by D. R. Haaheim and F. M. Stein """ # If no particular solutions are found, a general # solution cannot be found if len(part_sols) == 0: return [] # In case of a single particular solution, the general # solution can be found by using the substitution # y = y1 + 1/z and solving a Bernoulli ODE to find z. elif len(part_sols) == 1: y1 = part_sols[0] i = exp(Integral(2*y1, x)) z = i * Integral(a/i, x) z = z.doit() if a == 0 or z == 0: return y1 return y1 + 1/z # In case of 2 particular solutions, the general solution # can be found by solving a separable equation. This is # the most common case, i.e. most Riccati ODEs have 2 # rational particular solutions. elif len(part_sols) == 2: y1, y2 = part_sols # One of them already has a constant if len(y1.atoms(Dummy)) + len(y2.atoms(Dummy)) > 0: u = exp(Integral(y2 - y1, x)).doit() # Introduce a constant else: C1 = Dummy('C1') u = C1*exp(Integral(y2 - y1, x)).doit() if u == 1: return y2 return (y2*u - y1)/(u - 1) # In case of 3 particular solutions, a closed form # of the general solution can be obtained directly else: y1, y2, y3 = part_sols[:3] C1 = Dummy('C1') return (C1 + 1)*y2*(y1 - y3)/(C1*y1 + y2 - (C1 + 1)*y3) def solve_riccati(fx, x, b0, b1, b2, gensol=False): """ The main function that gives particular/general solutions to Riccati ODEs that have atleast 1 rational particular solution. """ # Step 1 : Convert to Normal Form a = -b0*b2 + b1**2/4 - b1.diff(x)/2 + 3*b2.diff(x)**2/(4*b2**2) + b1*b2.diff(x)/(2*b2) - \ b2.diff(x, 2)/(2*b2) a_t = a.together() num, den = [Poly(e, x, extension=True) for e in a_t.as_numer_denom()] num, den = num.cancel(den, include=True) # Step 2 presol = [] # Step 3 : a(x) is 0 if num == 0: presol.append(1/(x + Dummy('C1'))) # Step 4 : a(x) is a non-zero constant elif x not in num.free_symbols.union(den.free_symbols): presol.extend([sqrt(a), -sqrt(a)]) # Step 5 : Find poles and valuation at infinity poles = roots(den, x) poles, muls = list(poles.keys()), list(poles.values()) val_inf = val_at_inf(num, den, x) if len(poles): # Check necessary conditions (outlined in the module docstring) if not check_necessary_conds(val_inf, muls): raise ValueError("Rational Solution doesn't exist") # Step 6 # Construct c-vectors for each singular point c = construct_c(num, den, x, poles, muls) # Construct d vectors for each singular point d = construct_d(num, den, x, val_inf) # Step 7 : Iterate over all possible combinations and return solutions # For each possible combination, generate an array of 0's and 1's # where 0 means pick 1st choice and 1 means pick the second choice. # NOTE: We could exit from the loop if we find 3 particular solutions, # but it is not implemented here as - # a. Finding 3 particular solutions is very rare. Most of the time, # only 2 particular solutions are found. # b. In case we exit after finding 3 particular solutions, it might # happen that 1 or 2 of them are redundant solutions. So, instead of # spending some more time in computing the particular solutions, # we will end up computing the general solution from a single # particular solution which is usually slower than computing the # general solution from 2 or 3 particular solutions. c.append(d) choices = product(*c) for choice in choices: m, ybar = compute_m_ybar(x, poles, choice, -val_inf//2) numy, deny = [Poly(e, x, extension=True) for e in ybar.together().as_numer_denom()] # Step 10 : Check if a valid solution exists. If yes, also check # if m is a non-negative integer if m.is_nonnegative == True and m.is_integer == True: # Step 11 : Find polynomial solutions of degree m for the auxiliary equation psol, coeffs, exists = solve_aux_eq(num, den, numy, deny, x, m) # Step 12 : If valid polynomial solution exists, append solution. if exists: # m == 0 case if psol == 1 and coeffs == 0: # p(x) = 1, so p'(x)/p(x) term need not be added presol.append(ybar) # m is a positive integer and there are valid coefficients elif len(coeffs): # Substitute the valid coefficients to get p(x) psol = psol.xreplace(coeffs) # y(x) = ybar(x) + p'(x)/p(x) presol.append(ybar + psol.diff(x)/psol) # Remove redundant solutions from the list of existing solutions remove = set() for i in range(len(presol)): for j in range(i+1, len(presol)): rem = remove_redundant_sols(presol[i], presol[j], x) if rem is not None: remove.add(rem) sols = [x for x in presol if x not in remove] # Step 15 : Inverse transform the solutions of the equation in normal form bp = -b2.diff(x)/(2*b2**2) - b1/(2*b2) # If general solution is required, compute it from the particular solutions if gensol: sols = [get_gen_sol_from_part_sol(sols, a, x)] # Inverse transform the particular solutions presol = [Eq(fx, riccati_inverse_normal(y, x, b1, b2, bp).cancel(extension=True)) for y in sols] return presol
a39e9c346933d4b0ac15718b78d2a632882b84887177029a951ad6628d48008a
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 type(coeff) is 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 doesn't 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' = A0 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, aren't a matrix or do not have correct dimensions NonSquareMatrixError When the coefficient matrix or its antiderivative, if passed isn't a square matrix NotImplementedError If the coefficient matrix doesn't 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: sol_vector = P * J * ((J.inv() * 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` isn't 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 aren't 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 isn't 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 isn't 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 aren't 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
4dcb8c8f228686dd73f7278bd4a417577bd76bec46b865fe1a4e2c430443601d
r""" This File contains helper functions for nth_linear_constant_coeff_undetermined_coefficients, nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients, nth_linear_constant_coeff_variation_of_parameters, and nth_linear_euler_eq_nonhomogeneous_variation_of_parameters. All the functions in this file are used by more than one solvers so, instead of creating instances in other classes for using them it is better to keep it here as separate helpers. """ from collections import defaultdict from sympy.core import Add, S from sympy.core.function import diff, expand, _mexpand, expand_mul from sympy.core.relational import Eq from sympy.core.sorting import default_sort_key from sympy.core.symbol import Dummy, Wild from sympy.functions import exp, cos, cosh, im, log, re, sin, sinh, \ atan2, conjugate from sympy.integrals import Integral from sympy.polys import (Poly, RootOf, rootof, roots) from sympy.simplify import collect, simplify, separatevars, powsimp, trigsimp # type: ignore from sympy.utilities import numbered_symbols from sympy.solvers.solvers import solve from sympy.matrices import wronskian from .subscheck import sub_func_doit from sympy.solvers.ode.ode import get_numbered_constants def _test_term(coeff, func, order): r""" Linear Euler ODEs have the form K*x**order*diff(y(x), x, order) = F(x), where K is independent of x and y(x), order>= 0. So we need to check that for each term, coeff == K*x**order from some K. We have a few cases, since coeff may have several different types. """ x = func.args[0] f = func.func if order < 0: raise ValueError("order should be greater than 0") if coeff == 0: return True if order == 0: if x in coeff.free_symbols: return False return True if coeff.is_Mul: if coeff.has(f(x)): return False return x**order in coeff.args elif coeff.is_Pow: return coeff.as_base_exp() == (x, order) elif order == 1: return x == coeff return False def _get_euler_characteristic_eq_sols(eq, func, match_obj): r""" Returns the solution of homogeneous part of the linear euler ODE and the list of roots of characteristic equation. The parameter ``match_obj`` is 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. """ x = func.args[0] f = func.func # First, set up characteristic equation. chareq, symbol = S.Zero, Dummy('x') for i in match_obj: if i >= 0: chareq += (match_obj[i]*diff(x**symbol, x, i)*x**-symbol).expand() chareq = Poly(chareq, symbol) chareqroots = [rootof(chareq, k) for k in range(chareq.degree())] collectterms = [] # A generator of constants constants = list(get_numbered_constants(eq, num=chareq.degree()*2)) constants.reverse() # Create a dict root: multiplicity or charroots charroots = defaultdict(int) for root in chareqroots: charroots[root] += 1 gsol = S.Zero ln = log for root, multiplicity in charroots.items(): for i in range(multiplicity): if isinstance(root, RootOf): gsol += (x**root) * constants.pop() if multiplicity != 1: raise ValueError("Value should be 1") collectterms = [(0, root, 0)] + collectterms elif root.is_real: gsol += ln(x)**i*(x**root) * constants.pop() collectterms = [(i, root, 0)] + collectterms else: reroot = re(root) imroot = im(root) gsol += ln(x)**i * (x**reroot) * ( constants.pop() * sin(abs(imroot)*ln(x)) + constants.pop() * cos(imroot*ln(x))) collectterms = [(i, reroot, imroot)] + collectterms gsol = Eq(f(x), gsol) gensols = [] # Keep track of when to use sin or cos for nonzero imroot for i, reroot, imroot in collectterms: if imroot == 0: gensols.append(ln(x)**i*x**reroot) else: sin_form = ln(x)**i*x**reroot*sin(abs(imroot)*ln(x)) if sin_form in gensols: cos_form = ln(x)**i*x**reroot*cos(imroot*ln(x)) gensols.append(cos_form) else: gensols.append(sin_form) return gsol, gensols def _solve_variation_of_parameters(eq, func, roots, homogen_sol, order, match_obj, simplify_flag=True): r""" Helper function for the method of variation of parameters and nonhomogeneous euler eq. See the :py:meth:`~sympy.solvers.ode.single.NthLinearConstantCoeffVariationOfParameters` docstring for more information on this method. The parameter are ``match_obj`` should be a dictionary that has the following keys: ``list`` A list of solutions to the homogeneous equation. ``sol`` The general solution. """ f = func.func x = func.args[0] r = match_obj psol = 0 wr = wronskian(roots, x) if simplify_flag: wr = simplify(wr) # We need much better simplification for # some ODEs. See issue 4662, for example. # To reduce commonly occurring sin(x)**2 + cos(x)**2 to 1 wr = trigsimp(wr, deep=True, recursive=True) if not wr: # The wronskian will be 0 iff the solutions are not linearly # independent. raise NotImplementedError("Cannot find " + str(order) + " solutions to the homogeneous equation necessary to apply " + "variation of parameters to " + str(eq) + " (Wronskian == 0)") if len(roots) != order: raise NotImplementedError("Cannot find " + str(order) + " solutions to the homogeneous equation necessary to apply " + "variation of parameters to " + str(eq) + " (number of terms != order)") negoneterm = S.NegativeOne**(order) for i in roots: psol += negoneterm*Integral(wronskian([sol for sol in roots if sol != i], x)*r[-1]/wr, x)*i/r[order] negoneterm *= -1 if simplify_flag: psol = simplify(psol) psol = trigsimp(psol, deep=True) return Eq(f(x), homogen_sol.rhs + psol) def _get_const_characteristic_eq_sols(r, func, order): r""" Returns the roots of characteristic equation of constant coefficient linear ODE and list of collectterms which is later on used by simplification to use collect on solution. The parameter `r` is 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. """ x = func.args[0] # First, set up characteristic equation. chareq, symbol = S.Zero, Dummy('x') for i in r.keys(): if isinstance(i, str) or i < 0: pass else: chareq += r[i]*symbol**i chareq = Poly(chareq, symbol) # Can't just call roots because it doesn't return rootof for unsolveable # polynomials. chareqroots = roots(chareq, multiple=True) if len(chareqroots) != order: chareqroots = [rootof(chareq, k) for k in range(chareq.degree())] chareq_is_complex = not all(i.is_real for i in chareq.all_coeffs()) # Create a dict root: multiplicity or charroots charroots = defaultdict(int) for root in chareqroots: charroots[root] += 1 # We need to keep track of terms so we can run collect() at the end. # This is necessary for constantsimp to work properly. collectterms = [] gensols = [] conjugate_roots = [] # used to prevent double-use of conjugate roots # Loop over roots in theorder provided by roots/rootof... for root in chareqroots: # but don't repoeat multiple roots. if root not in charroots: continue multiplicity = charroots.pop(root) for i in range(multiplicity): if chareq_is_complex: gensols.append(x**i*exp(root*x)) collectterms = [(i, root, 0)] + collectterms continue reroot = re(root) imroot = im(root) if imroot.has(atan2) and reroot.has(atan2): # Remove this condition when re and im stop returning # circular atan2 usages. gensols.append(x**i*exp(root*x)) collectterms = [(i, root, 0)] + collectterms else: if root in conjugate_roots: collectterms = [(i, reroot, imroot)] + collectterms continue if imroot == 0: gensols.append(x**i*exp(reroot*x)) collectterms = [(i, reroot, 0)] + collectterms continue conjugate_roots.append(conjugate(root)) gensols.append(x**i*exp(reroot*x) * sin(abs(imroot) * x)) gensols.append(x**i*exp(reroot*x) * cos( imroot * x)) # This ordering is important collectterms = [(i, reroot, imroot)] + collectterms return gensols, collectterms # Ideally these kind of simplification functions shouldn't be part of solvers. # odesimp should be improved to handle these kind of specific simplifications. def _get_simplified_sol(sol, func, collectterms): r""" Helper function which collects the solution on collectterms. Ideally this should be handled by odesimp.It is used only when the simplify is set to True in dsolve. The parameter ``collectterms`` is a list of tuple (i, reroot, imroot) where `i` is the multiplicity of the root, reroot is real part and imroot being the imaginary part. """ f = func.func x = func.args[0] collectterms.sort(key=default_sort_key) collectterms.reverse() assert len(sol) == 1 and sol[0].lhs == f(x) sol = sol[0].rhs sol = expand_mul(sol) for i, reroot, imroot in collectterms: sol = collect(sol, x**i*exp(reroot*x)*sin(abs(imroot)*x)) sol = collect(sol, x**i*exp(reroot*x)*cos(imroot*x)) for i, reroot, imroot in collectterms: sol = collect(sol, x**i*exp(reroot*x)) sol = powsimp(sol) return Eq(f(x), sol) def _undetermined_coefficients_match(expr, x, func=None, eq_homogeneous=S.Zero): r""" Returns a trial function match if undetermined coefficients can be applied to ``expr``, and ``None`` otherwise. A trial expression can be found for an expression for use with the method of undetermined coefficients if the expression is an additive/multiplicative combination of constants, polynomials in `x` (the independent variable of expr), `\sin(a x + b)`, `\cos(a x + b)`, and `e^{a x}` terms (in other words, it has a finite number of linearly independent derivatives). Note that you may still need to multiply each term returned here by sufficient `x` to make it linearly independent with the solutions to the homogeneous equation. This is intended for internal use by ``undetermined_coefficients`` hints. SymPy currently has no way to convert `\sin^n(x) \cos^m(y)` into a sum of only `\sin(a x)` and `\cos(b x)` terms, so these are not implemented. So, for example, you will need to manually convert `\sin^2(x)` into `[1 + \cos(2 x)]/2` to properly apply the method of undetermined coefficients on it. Examples ======== >>> from sympy import log, exp >>> from sympy.solvers.ode.nonhomogeneous import _undetermined_coefficients_match >>> from sympy.abc import x >>> _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) {'test': True, 'trialset': {x*exp(x), exp(-x), exp(x)}} >>> _undetermined_coefficients_match(log(x), x) {'test': False} """ a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1) retdict = {} def _test_term(expr, x): r""" Test if ``expr`` fits the proper form for undetermined coefficients. """ if not expr.has(x): return True elif expr.is_Add: return all(_test_term(i, x) for i in expr.args) elif expr.is_Mul: if expr.has(sin, cos): foundtrig = False # Make sure that there is only one trig function in the args. # See the docstring. for i in expr.args: if i.has(sin, cos): if foundtrig: return False else: foundtrig = True return all(_test_term(i, x) for i in expr.args) elif expr.is_Function: if expr.func in (sin, cos, exp, sinh, cosh): if expr.args[0].match(a*x + b): return True else: return False else: return False elif expr.is_Pow and expr.base.is_Symbol and expr.exp.is_Integer and \ expr.exp >= 0: return True elif expr.is_Pow and expr.base.is_number: if expr.exp.match(a*x + b): return True else: return False elif expr.is_Symbol or expr.is_number: return True else: return False def _get_trial_set(expr, x, exprs=set()): r""" Returns a set of trial terms for undetermined coefficients. The idea behind undetermined coefficients is that the terms expression repeat themselves after a finite number of derivatives, except for the coefficients (they are linearly dependent). So if we collect these, we should have the terms of our trial function. """ def _remove_coefficient(expr, x): r""" Returns the expression without a coefficient. Similar to expr.as_independent(x)[1], except it only works multiplicatively. """ term = S.One if expr.is_Mul: for i in expr.args: if i.has(x): term *= i elif expr.has(x): term = expr return term expr = expand_mul(expr) if expr.is_Add: for term in expr.args: if _remove_coefficient(term, x) in exprs: pass else: exprs.add(_remove_coefficient(term, x)) exprs = exprs.union(_get_trial_set(term, x, exprs)) else: term = _remove_coefficient(expr, x) tmpset = exprs.union({term}) oldset = set() while tmpset != oldset: # If you get stuck in this loop, then _test_term is probably # broken oldset = tmpset.copy() expr = expr.diff(x) term = _remove_coefficient(expr, x) if term.is_Add: tmpset = tmpset.union(_get_trial_set(term, x, tmpset)) else: tmpset.add(term) exprs = tmpset return exprs def is_homogeneous_solution(term): r""" This function checks whether the given trialset contains any root of homogenous equation""" return expand(sub_func_doit(eq_homogeneous, func, term)).is_zero retdict['test'] = _test_term(expr, x) if retdict['test']: # Try to generate a list of trial solutions that will have the # undetermined coefficients. Note that if any of these are not linearly # independent with any of the solutions to the homogeneous equation, # then they will need to be multiplied by sufficient x to make them so. # This function DOES NOT do that (it doesn't even look at the # homogeneous equation). temp_set = set() for i in Add.make_args(expr): act = _get_trial_set(i, x) if eq_homogeneous is not S.Zero: while any(is_homogeneous_solution(ts) for ts in act): act = {x*ts for ts in act} temp_set = temp_set.union(act) retdict['trialset'] = temp_set return retdict def _solve_undetermined_coefficients(eq, func, order, match, trialset): r""" Helper function for the method of undetermined coefficients. See the :py:meth:`~sympy.solvers.ode.single.NthLinearConstantCoeffUndeterminedCoefficients` docstring for more information on this method. The parameter ``trialset`` is the set of trial functions as returned by ``_undetermined_coefficients_match()['trialset']``. The parameter ``match`` should be a dictionary that has the following keys: ``list`` A list of solutions to the homogeneous equation. ``sol`` The general solution. """ r = match coeffs = numbered_symbols('a', cls=Dummy) coefflist = [] gensols = r['list'] gsol = r['sol'] f = func.func x = func.args[0] if len(gensols) != order: raise NotImplementedError("Cannot find " + str(order) + " solutions to the homogeneous equation necessary to apply" + " undetermined coefficients to " + str(eq) + " (number of terms != order)") trialfunc = 0 for i in trialset: c = next(coeffs) coefflist.append(c) trialfunc += c*i eqs = sub_func_doit(eq, f(x), trialfunc) coeffsdict = dict(list(zip(trialset, [0]*(len(trialset) + 1)))) eqs = _mexpand(eqs) for i in Add.make_args(eqs): s = separatevars(i, dict=True, symbols=[x]) if coeffsdict.get(s[x]): coeffsdict[s[x]] += s['coeff'] else: coeffsdict[s[x]] = s['coeff'] coeffvals = solve(list(coeffsdict.values()), coefflist) if not coeffvals: raise NotImplementedError( "Could not solve `%s` using the " "method of undetermined coefficients " "(unable to solve for coefficients)." % eq) psol = trialfunc.subs(coeffvals) return Eq(f(x), gsol.rhs + psol)
458f53b3a51acc939fd5e30772c228a6a2b7fb4735c0ae3c79945f7a27bd8e29
from sympy.core import S, Pow from sympy.core.function import (Derivative, AppliedUndef, diff) from sympy.core.relational import Equality, Eq from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.logic.boolalg import BooleanAtom from sympy.functions import exp from sympy.series import Order from sympy.simplify.simplify import simplify, posify, besselsimp from sympy.simplify.trigsimp import trigsimp from sympy.simplify.sqrtdenest import sqrtdenest from sympy.solvers import solve from sympy.solvers.deutils import _preprocess, ode_order from sympy.utilities.iterables import iterable, is_sequence def sub_func_doit(eq, func, new): r""" When replacing the func with something else, we usually want the derivative evaluated, so this function helps in making that happen. Examples ======== >>> from sympy import Derivative, symbols, Function >>> from sympy.solvers.ode.subscheck import sub_func_doit >>> x, z = symbols('x, z') >>> y = Function('y') >>> sub_func_doit(3*Derivative(y(x), x) - 1, y(x), x) 2 >>> sub_func_doit(x*Derivative(y(x), x) - y(x)**2 + y(x), y(x), ... 1/(x*(z + 1/x))) x*(-1/(x**2*(z + 1/x)) + 1/(x**3*(z + 1/x)**2)) + 1/(x*(z + 1/x)) ...- 1/(x**2*(z + 1/x)**2) """ reps= {func: new} for d in eq.atoms(Derivative): if d.expr == func: reps[d] = new.diff(*d.variable_count) else: reps[d] = d.xreplace({func: new}).doit(deep=False) return eq.xreplace(reps) def checkodesol(ode, sol, func=None, order='auto', solve_for_func=True): r""" Substitutes ``sol`` into ``ode`` and checks that the result is ``0``. This works when ``func`` is one function, like `f(x)` or a list of functions like `[f(x), g(x)]` when `ode` is a system of ODEs. ``sol`` can be a single solution or a list of solutions. Each solution may be an :py:class:`~sympy.core.relational.Equality` that the solution satisfies, e.g. ``Eq(f(x), C1), Eq(f(x) + C1, 0)``; or simply an :py:class:`~sympy.core.expr.Expr`, e.g. ``f(x) - C1``. In most cases it will not be necessary to explicitly identify the function, but if the function cannot be inferred from the original equation it can be supplied through the ``func`` argument. If a sequence of solutions is passed, the same sort of container will be used to return the result for each solution. It tries the following methods, in order, until it finds zero equivalence: 1. Substitute the solution for `f` in the original equation. This only works if ``ode`` is solved for `f`. It will attempt to solve it first unless ``solve_for_func == False``. 2. Take `n` derivatives of the solution, where `n` is the order of ``ode``, and check to see if that is equal to the solution. This only works on exact ODEs. 3. Take the 1st, 2nd, ..., `n`\th derivatives of the solution, each time solving for the derivative of `f` of that order (this will always be possible because `f` is a linear operator). Then back substitute each derivative into ``ode`` in reverse order. This function returns a tuple. The first item in the tuple is ``True`` if the substitution results in ``0``, and ``False`` otherwise. The second item in the tuple is what the substitution results in. It should always be ``0`` if the first item is ``True``. Sometimes this function will return ``False`` even when an expression is identically equal to ``0``. This happens when :py:meth:`~sympy.simplify.simplify.simplify` does not reduce the expression to ``0``. If an expression returned by this function vanishes identically, then ``sol`` really is a solution to the ``ode``. If this function seems to hang, it is probably because of a hard simplification. To use this function to test, test the first item of the tuple. Examples ======== >>> from sympy import (Eq, Function, checkodesol, symbols, ... Derivative, exp) >>> x, C1, C2 = symbols('x,C1,C2') >>> f, g = symbols('f g', cls=Function) >>> checkodesol(f(x).diff(x), Eq(f(x), C1)) (True, 0) >>> assert checkodesol(f(x).diff(x), C1)[0] >>> assert not checkodesol(f(x).diff(x), x)[0] >>> checkodesol(f(x).diff(x, 2), x**2) (False, 2) >>> eqs = [Eq(Derivative(f(x), x), f(x)), Eq(Derivative(g(x), x), g(x))] >>> sol = [Eq(f(x), C1*exp(x)), Eq(g(x), C2*exp(x))] >>> checkodesol(eqs, sol) (True, [0, 0]) """ if iterable(ode): return checksysodesol(ode, sol, func=func) if not isinstance(ode, Equality): ode = Eq(ode, 0) if func is None: try: _, func = _preprocess(ode.lhs) except ValueError: funcs = [s.atoms(AppliedUndef) for s in ( sol if is_sequence(sol, set) else [sol])] funcs = set().union(*funcs) if len(funcs) != 1: raise ValueError( 'must pass func arg to checkodesol for this case.') func = funcs.pop() if not isinstance(func, AppliedUndef) or len(func.args) != 1: raise ValueError( "func must be a function of one variable, not %s" % func) if is_sequence(sol, set): return type(sol)([checkodesol(ode, i, order=order, solve_for_func=solve_for_func) for i in sol]) if not isinstance(sol, Equality): sol = Eq(func, sol) elif sol.rhs == func: sol = sol.reversed if order == 'auto': order = ode_order(ode, func) solved = sol.lhs == func and not sol.rhs.has(func) if solve_for_func and not solved: rhs = solve(sol, func) if rhs: eqs = [Eq(func, t) for t in rhs] if len(rhs) == 1: eqs = eqs[0] return checkodesol(ode, eqs, order=order, solve_for_func=False) x = func.args[0] # Handle series solutions here if sol.has(Order): assert sol.lhs == func Oterm = sol.rhs.getO() solrhs = sol.rhs.removeO() Oexpr = Oterm.expr assert isinstance(Oexpr, Pow) sorder = Oexpr.exp assert Oterm == Order(x**sorder) odesubs = (ode.lhs-ode.rhs).subs(func, solrhs).doit().expand() neworder = Order(x**(sorder - order)) odesubs = odesubs + neworder assert odesubs.getO() == neworder residual = odesubs.removeO() return (residual == 0, residual) s = True testnum = 0 while s: if testnum == 0: # First pass, try substituting a solved solution directly into the # ODE. This has the highest chance of succeeding. ode_diff = ode.lhs - ode.rhs if sol.lhs == func: s = sub_func_doit(ode_diff, func, sol.rhs) s = besselsimp(s) else: testnum += 1 continue ss = simplify(s.rewrite(exp)) if ss: # with the new numer_denom in power.py, if we do a simple # expansion then testnum == 0 verifies all solutions. s = ss.expand(force=True) else: s = 0 testnum += 1 elif testnum == 1: # Second pass. If we cannot substitute f, try seeing if the nth # derivative is equal, this will only work for odes that are exact, # by definition. s = simplify( trigsimp(diff(sol.lhs, x, order) - diff(sol.rhs, x, order)) - trigsimp(ode.lhs) + trigsimp(ode.rhs)) # s2 = simplify( # diff(sol.lhs, x, order) - diff(sol.rhs, x, order) - \ # ode.lhs + ode.rhs) testnum += 1 elif testnum == 2: # Third pass. Try solving for df/dx and substituting that into the # ODE. Thanks to Chris Smith for suggesting this method. Many of # the comments below are his, too. # The method: # - Take each of 1..n derivatives of the solution. # - Solve each nth derivative for d^(n)f/dx^(n) # (the differential of that order) # - Back substitute into the ODE in decreasing order # (i.e., n, n-1, ...) # - Check the result for zero equivalence if sol.lhs == func and not sol.rhs.has(func): diffsols = {0: sol.rhs} elif sol.rhs == func and not sol.lhs.has(func): diffsols = {0: sol.lhs} else: diffsols = {} sol = sol.lhs - sol.rhs for i in range(1, order + 1): # Differentiation is a linear operator, so there should always # be 1 solution. Nonetheless, we test just to make sure. # We only need to solve once. After that, we automatically # have the solution to the differential in the order we want. if i == 1: ds = sol.diff(x) try: sdf = solve(ds, func.diff(x, i)) if not sdf: raise NotImplementedError except NotImplementedError: testnum += 1 break else: diffsols[i] = sdf[0] else: # This is what the solution says df/dx should be. diffsols[i] = diffsols[i - 1].diff(x) # Make sure the above didn't fail. if testnum > 2: continue else: # Substitute it into ODE to check for self consistency. lhs, rhs = ode.lhs, ode.rhs for i in range(order, -1, -1): if i == 0 and 0 not in diffsols: # We can only substitute f(x) if the solution was # solved for f(x). break lhs = sub_func_doit(lhs, func.diff(x, i), diffsols[i]) rhs = sub_func_doit(rhs, func.diff(x, i), diffsols[i]) ode_or_bool = Eq(lhs, rhs) ode_or_bool = simplify(ode_or_bool) if isinstance(ode_or_bool, (bool, BooleanAtom)): if ode_or_bool: lhs = rhs = S.Zero else: lhs = ode_or_bool.lhs rhs = ode_or_bool.rhs # No sense in overworking simplify -- just prove that the # numerator goes to zero num = trigsimp((lhs - rhs).as_numer_denom()[0]) # since solutions are obtained using force=True we test # using the same level of assumptions ## replace function with dummy so assumptions will work _func = Dummy('func') num = num.subs(func, _func) ## posify the expression num, reps = posify(num) s = simplify(num).xreplace(reps).xreplace({_func: func}) testnum += 1 else: break if not s: return (True, s) elif s is True: # The code above never was able to change s raise NotImplementedError("Unable to test if " + str(sol) + " is a solution to " + str(ode) + ".") else: return (False, s) def checksysodesol(eqs, sols, func=None): r""" Substitutes corresponding ``sols`` for each functions into each ``eqs`` and checks that the result of substitutions for each equation is ``0``. The equations and solutions passed can be any iterable. This only works when each ``sols`` have one function only, like `x(t)` or `y(t)`. For each function, ``sols`` can have a single solution or a list of solutions. In most cases it will not be necessary to explicitly identify the function, but if the function cannot be inferred from the original equation it can be supplied through the ``func`` argument. When a sequence of equations is passed, the same sequence is used to return the result for each equation with each function substituted with corresponding solutions. It tries the following method to find zero equivalence for each equation: Substitute the solutions for functions, like `x(t)` and `y(t)` into the original equations containing those functions. This function returns a tuple. The first item in the tuple is ``True`` if the substitution results for each equation is ``0``, and ``False`` otherwise. The second item in the tuple is what the substitution results in. Each element of the ``list`` should always be ``0`` corresponding to each equation if the first item is ``True``. Note that sometimes this function may return ``False``, but with an expression that is identically equal to ``0``, instead of returning ``True``. This is because :py:meth:`~sympy.simplify.simplify.simplify` cannot reduce the expression to ``0``. If an expression returned by each function vanishes identically, then ``sols`` really is a solution to ``eqs``. If this function seems to hang, it is probably because of a difficult simplification. Examples ======== >>> from sympy import Eq, diff, symbols, sin, cos, exp, sqrt, S, Function >>> from sympy.solvers.ode.subscheck import checksysodesol >>> C1, C2 = symbols('C1:3') >>> t = symbols('t') >>> x, y = symbols('x, y', cls=Function) >>> eq = (Eq(diff(x(t),t), x(t) + y(t) + 17), Eq(diff(y(t),t), -2*x(t) + y(t) + 12)) >>> sol = [Eq(x(t), (C1*sin(sqrt(2)*t) + C2*cos(sqrt(2)*t))*exp(t) - S(5)/3), ... Eq(y(t), (sqrt(2)*C1*cos(sqrt(2)*t) - sqrt(2)*C2*sin(sqrt(2)*t))*exp(t) - S(46)/3)] >>> checksysodesol(eq, sol) (True, [0, 0]) >>> eq = (Eq(diff(x(t),t),x(t)*y(t)**4), Eq(diff(y(t),t),y(t)**3)) >>> sol = [Eq(x(t), C1*exp(-1/(4*(C2 + t)))), Eq(y(t), -sqrt(2)*sqrt(-1/(C2 + t))/2), ... Eq(x(t), C1*exp(-1/(4*(C2 + t)))), Eq(y(t), sqrt(2)*sqrt(-1/(C2 + t))/2)] >>> checksysodesol(eq, sol) (True, [0, 0]) """ def _sympify(eq): return list(map(sympify, eq if iterable(eq) else [eq])) eqs = _sympify(eqs) for i in range(len(eqs)): if isinstance(eqs[i], Equality): eqs[i] = eqs[i].lhs - eqs[i].rhs if func is None: funcs = [] for eq in eqs: derivs = eq.atoms(Derivative) func = set().union(*[d.atoms(AppliedUndef) for d in derivs]) for func_ in func: funcs.append(func_) funcs = list(set(funcs)) if not all(isinstance(func, AppliedUndef) and len(func.args) == 1 for func in funcs)\ and len({func.args for func in funcs})!=1: raise ValueError("func must be a function of one variable, not %s" % func) for sol in sols: if len(sol.atoms(AppliedUndef)) != 1: raise ValueError("solutions should have one function only") if len(funcs) != len({sol.lhs for sol in sols}): raise ValueError("number of solutions provided does not match the number of equations") dictsol = dict() for sol in sols: func = list(sol.atoms(AppliedUndef))[0] if sol.rhs == func: sol = sol.reversed solved = sol.lhs == func and not sol.rhs.has(func) if not solved: rhs = solve(sol, func) if not rhs: raise NotImplementedError else: rhs = sol.rhs dictsol[func] = rhs checkeq = [] for eq in eqs: for func in funcs: eq = sub_func_doit(eq, func, dictsol[func]) ss = simplify(eq) if ss != 0: eq = ss.expand(force=True) if eq != 0: eq = sqrtdenest(eq).simplify() else: eq = 0 checkeq.append(eq) if len(set(checkeq)) == 1 and list(set(checkeq))[0] == 0: return (True, checkeq) else: return (False, checkeq)
51fb10cd2426e82c1fbe7ce479f890998494546773cdd329c98b3aefed4a44dc
r''' This module contains the implementation of the 2nd_hypergeometric hint for dsolve. This is an incomplete implementation of the algorithm described in [1]. The algorithm solves 2nd order linear ODEs of the form .. math:: y'' + A(x) y' + B(x) y = 0\text{,} where `A` and `B` are rational functions. 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!). References ========== .. [1] L. Chan, E.S. Cheb-Terrab, Non-Liouvillian solutions for second order linear ODEs, (2004). https://arxiv.org/abs/math-ph/0402063 ''' from sympy.core import S, Pow from sympy.core.function import expand from sympy.core.relational import Eq from sympy.core.symbol import Symbol, Wild from sympy.functions import exp, sqrt, hyper from sympy.integrals import Integral from sympy.polys import roots, gcd from sympy.polys.polytools import cancel, factor from sympy.simplify import collect, simplify, logcombine # type: ignore from sympy.simplify.powsimp import powdenest from sympy.solvers.ode.ode import get_numbered_constants def match_2nd_hypergeometric(eq, func): x = func.args[0] df = func.diff(x) a3 = Wild('a3', exclude=[func, func.diff(x), func.diff(x, 2)]) b3 = Wild('b3', exclude=[func, func.diff(x), func.diff(x, 2)]) c3 = Wild('c3', exclude=[func, func.diff(x), func.diff(x, 2)]) deq = a3*(func.diff(x, 2)) + b3*df + c3*func r = collect(eq, [func.diff(x, 2), func.diff(x), func]).match(deq) if r: if not all(val.is_polynomial() for val in r.values()): n, d = eq.as_numer_denom() eq = expand(n) r = collect(eq, [func.diff(x, 2), func.diff(x), func]).match(deq) if r and r[a3]!=0: A = cancel(r[b3]/r[a3]) B = cancel(r[c3]/r[a3]) return [A, B] else: return [] def equivalence_hypergeometric(A, B, func): # This method for finding the equivalence is only for 2F1 type. # We can extend it for 1F1 and 0F1 type also. x = func.args[0] # making given equation in normal form I1 = factor(cancel(A.diff(x)/2 + A**2/4 - B)) # computing shifted invariant(J1) of the equation J1 = factor(cancel(x**2*I1 + S(1)/4)) num, dem = J1.as_numer_denom() num = powdenest(expand(num)) dem = powdenest(expand(dem)) # this function will compute the different powers of variable(x) in J1. # then it will help in finding value of k. k is power of x such that we can express # J1 = x**k * J0(x**k) then all the powers in J0 become integers. def _power_counting(num): _pow = {0} for val in num: if val.has(x): if isinstance(val, Pow) and val.as_base_exp()[0] == x: _pow.add(val.as_base_exp()[1]) elif val == x: _pow.add(val.as_base_exp()[1]) else: _pow.update(_power_counting(val.args)) return _pow pow_num = _power_counting((num, )) pow_dem = _power_counting((dem, )) pow_dem.update(pow_num) _pow = pow_dem k = gcd(_pow) # computing I0 of the given equation I0 = powdenest(simplify(factor(((J1/k**2) - S(1)/4)/((x**k)**2))), force=True) I0 = factor(cancel(powdenest(I0.subs(x, x**(S(1)/k)), force=True))) num, dem = I0.as_numer_denom() max_num_pow = max(_power_counting((num, ))) dem_args = dem.args sing_point = [] dem_pow = [] # calculating singular point of I0. for arg in dem_args: if arg.has(x): if isinstance(arg, Pow): # (x-a)**n dem_pow.append(arg.as_base_exp()[1]) sing_point.append(list(roots(arg.as_base_exp()[0], x).keys())[0]) else: # (x-a) type dem_pow.append(arg.as_base_exp()[1]) sing_point.append(list(roots(arg, x).keys())[0]) dem_pow.sort() # checking if equivalence is exists or not. if equivalence(max_num_pow, dem_pow) == "2F1": return {'I0':I0, 'k':k, 'sing_point':sing_point, 'type':"2F1"} else: return None def match_2nd_2F1_hypergeometric(I, k, sing_point, func): x = func.args[0] a = Wild("a") b = Wild("b") c = Wild("c") t = Wild("t") s = Wild("s") r = Wild("r") alpha = Wild("alpha") beta = Wild("beta") gamma = Wild("gamma") delta = Wild("delta") # I0 of the standerd 2F1 equation. I0 = ((a-b+1)*(a-b-1)*x**2 + 2*((1-a-b)*c + 2*a*b)*x + c*(c-2))/(4*x**2*(x-1)**2) if sing_point != [0, 1]: # If singular point is [0, 1] then we have standerd equation. eqs = [] sing_eqs = [-beta/alpha, -delta/gamma, (delta-beta)/(alpha-gamma)] # making equations for the finding the mobius transformation for i in range(3): if i<len(sing_point): eqs.append(Eq(sing_eqs[i], sing_point[i])) else: eqs.append(Eq(1/sing_eqs[i], 0)) # solving above equations for the mobius transformation _beta = -alpha*sing_point[0] _delta = -gamma*sing_point[1] _gamma = alpha if len(sing_point) == 3: _gamma = (_beta + sing_point[2]*alpha)/(sing_point[2] - sing_point[1]) mob = (alpha*x + beta)/(gamma*x + delta) mob = mob.subs(beta, _beta) mob = mob.subs(delta, _delta) mob = mob.subs(gamma, _gamma) mob = cancel(mob) t = (beta - delta*x)/(gamma*x - alpha) t = cancel(((t.subs(beta, _beta)).subs(delta, _delta)).subs(gamma, _gamma)) else: mob = x t = x # applying mobius transformation in I to make it into I0. I = I.subs(x, t) I = I*(t.diff(x))**2 I = factor(I) dict_I = {x**2:0, x:0, 1:0} I0_num, I0_dem = I0.as_numer_denom() # collecting coeff of (x**2, x), of the standerd equation. # substituting (a-b) = s, (a+b) = r dict_I0 = {x**2:s**2 - 1, x:(2*(1-r)*c + (r+s)*(r-s)), 1:c*(c-2)} # collecting coeff of (x**2, x) from I0 of the given equation. dict_I.update(collect(expand(cancel(I*I0_dem)), [x**2, x], evaluate=False)) eqs = [] # We are comparing the coeff of powers of different x, for finding the values of # parameters of standerd equation. for key in [x**2, x, 1]: eqs.append(Eq(dict_I[key], dict_I0[key])) # We can have many possible roots for the equation. # I am selecting the root on the basis that when we have # standard equation eq = x*(x-1)*f(x).diff(x, 2) + ((a+b+1)*x-c)*f(x).diff(x) + a*b*f(x) # then root should be a, b, c. _c = 1 - factor(sqrt(1+eqs[2].lhs)) if not _c.has(Symbol): _c = min(list(roots(eqs[2], c))) _s = factor(sqrt(eqs[0].lhs + 1)) _r = _c - factor(sqrt(_c**2 + _s**2 + eqs[1].lhs - 2*_c)) _a = (_r + _s)/2 _b = (_r - _s)/2 rn = {'a':simplify(_a), 'b':simplify(_b), 'c':simplify(_c), 'k':k, 'mobius':mob, 'type':"2F1"} return rn def equivalence(max_num_pow, dem_pow): # this function is made for checking the equivalence with 2F1 type of equation. # max_num_pow is the value of maximum power of x in numerator # and dem_pow is list of powers of different factor of form (a*x b). # reference from table 1 in paper - "Non-Liouvillian solutions for second order # linear ODEs" by L. Chan, E.S. Cheb-Terrab. # We can extend it for 1F1 and 0F1 type also. if max_num_pow == 2: if dem_pow in [[2, 2], [2, 2, 2]]: return "2F1" elif max_num_pow == 1: if dem_pow in [[1, 2, 2], [2, 2, 2], [1, 2], [2, 2]]: return "2F1" elif max_num_pow == 0: if dem_pow in [[1, 1, 2], [2, 2], [1, 2, 2], [1, 1], [2], [1, 2], [2, 2]]: return "2F1" return None def get_sol_2F1_hypergeometric(eq, func, match_object): x = func.args[0] from sympy.simplify.hyperexpand import hyperexpand from sympy.polys.polytools import factor C0, C1 = get_numbered_constants(eq, num=2) a = match_object['a'] b = match_object['b'] c = match_object['c'] A = match_object['A'] sol = None if c.is_integer == False: sol = C0*hyper([a, b], [c], x) + C1*hyper([a-c+1, b-c+1], [2-c], x)*x**(1-c) elif c == 1: y2 = Integral(exp(Integral((-(a+b+1)*x + c)/(x**2-x), x))/(hyperexpand(hyper([a, b], [c], x))**2), x)*hyper([a, b], [c], x) sol = C0*hyper([a, b], [c], x) + C1*y2 elif (c-a-b).is_integer == False: sol = C0*hyper([a, b], [1+a+b-c], 1-x) + C1*hyper([c-a, c-b], [1+c-a-b], 1-x)*(1-x)**(c-a-b) if sol: # applying transformation in the solution subs = match_object['mobius'] dtdx = simplify(1/(subs.diff(x))) _B = ((a + b + 1)*x - c).subs(x, subs)*dtdx _B = factor(_B + ((x**2 -x).subs(x, subs))*(dtdx.diff(x)*dtdx)) _A = factor((x**2 - x).subs(x, subs)*(dtdx**2)) e = exp(logcombine(Integral(cancel(_B/(2*_A)), x), force=True)) sol = sol.subs(x, match_object['mobius']) sol = sol.subs(x, x**match_object['k']) e = e.subs(x, x**match_object['k']) if not A.is_zero: e1 = Integral(A/2, x) e1 = exp(logcombine(e1, force=True)) sol = cancel((e/e1)*x**((-match_object['k']+1)/2))*sol sol = Eq(func, sol) return sol sol = cancel((e)*x**((-match_object['k']+1)/2))*sol sol = Eq(func, sol) return sol
023c15f418c06058bae85888bf0d3b53f3dc8891c697c2485203e687f8b907b0
from sympy.core.containers import Tuple from sympy.core.function import (Function, Lambda, nfloat, diff) from sympy.core.mod import Mod from sympy.core.numbers import (E, I, Rational, oo, pi, Integer) from sympy.core.relational import (Eq, Gt, Ne, Ge) from sympy.core.singleton import S from sympy.core.sorting import ordered from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.elementary.complexes import (Abs, arg, im, re, sign, conjugate) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.hyperbolic import (HyperbolicFunction, sinh, tanh, cosh, sech, coth) from sympy.functions.elementary.miscellaneous import sqrt, Min, Max from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import ( TrigonometricFunction, acos, acot, acsc, asec, asin, atan, atan2, cos, cot, csc, sec, sin, tan) from sympy.functions.special.error_functions import (erf, erfc, erfcinv, erfinv) from sympy.logic.boolalg import And from sympy.matrices.dense import MutableDenseMatrix as Matrix from sympy.matrices.immutable import ImmutableDenseMatrix from sympy.polys.polytools import Poly from sympy.polys.rootoftools import CRootOf from sympy.sets.contains import Contains from sympy.sets.conditionset import ConditionSet from sympy.sets.fancysets import ImageSet, Range from sympy.sets.sets import (Complement, FiniteSet, Intersection, Interval, Union, imageset, ProductSet) from sympy.simplify import simplify from sympy.tensor.indexed import Indexed from sympy.utilities.iterables import numbered_symbols from sympy.testing.pytest import (XFAIL, raises, skip, slow, SKIP, _both_exp_pow) from sympy.testing.randtest import verify_numerically as tn from sympy.physics.units import cm from sympy.solvers import solve from sympy.solvers.solveset import ( solveset_real, domain_check, solveset_complex, linear_eq_to_matrix, linsolve, _is_function_class_equation, invert_real, invert_complex, solveset, solve_decomposition, substitution, nonlinsolve, solvify, _is_finite_with_finite_vars, _transolve, _is_exponential, _solve_exponential, _is_logarithmic, _is_lambert, _solve_logarithm, _term_factors, _is_modular, NonlinearError) from sympy.abc import (a, b, c, d, e, f, g, h, i, j, k, l, m, n, q, r, t, w, x, y, z) def dumeq(i, j): if type(i) in (list, tuple): return all(dumeq(i, j) for i, j in zip(i, j)) return i == j or i.dummy_eq(j) @_both_exp_pow def test_invert_real(): x = Symbol('x', real=True) def ireal(x, s=S.Reals): return Intersection(s, x) assert invert_real(exp(x), z, x) == (x, ireal(FiniteSet(log(z)))) y = Symbol('y', positive=True) n = Symbol('n', real=True) assert invert_real(x + 3, y, x) == (x, FiniteSet(y - 3)) assert invert_real(x*3, y, x) == (x, FiniteSet(y / 3)) assert invert_real(exp(x), y, x) == (x, FiniteSet(log(y))) assert invert_real(exp(3*x), y, x) == (x, FiniteSet(log(y) / 3)) assert invert_real(exp(x + 3), y, x) == (x, FiniteSet(log(y) - 3)) assert invert_real(exp(x) + 3, y, x) == (x, ireal(FiniteSet(log(y - 3)))) assert invert_real(exp(x)*3, y, x) == (x, FiniteSet(log(y / 3))) assert invert_real(log(x), y, x) == (x, FiniteSet(exp(y))) assert invert_real(log(3*x), y, x) == (x, FiniteSet(exp(y) / 3)) assert invert_real(log(x + 3), y, x) == (x, FiniteSet(exp(y) - 3)) assert invert_real(Abs(x), y, x) == (x, FiniteSet(y, -y)) assert invert_real(2**x, y, x) == (x, FiniteSet(log(y)/log(2))) assert invert_real(2**exp(x), y, x) == (x, ireal(FiniteSet(log(log(y)/log(2))))) assert invert_real(x**2, y, x) == (x, FiniteSet(sqrt(y), -sqrt(y))) assert invert_real(x**S.Half, y, x) == (x, FiniteSet(y**2)) raises(ValueError, lambda: invert_real(x, x, x)) # issue 21236 assert invert_real(x**pi, y, x) == (x, FiniteSet(y**(1/pi))) assert invert_real(x**pi, -E, x) == (x, S.EmptySet) assert invert_real(x**Rational(3/2), 1000, x) == (x, FiniteSet(100)) assert invert_real(x**1.0, 1, x) == (x**1.0, FiniteSet(1)) raises(ValueError, lambda: invert_real(S.One, y, x)) assert invert_real(x**31 + x, y, x) == (x**31 + x, FiniteSet(y)) lhs = x**31 + x base_values = FiniteSet(y - 1, -y - 1) assert invert_real(Abs(x**31 + x + 1), y, x) == (lhs, base_values) assert dumeq(invert_real(sin(x), y, x), (x, imageset(Lambda(n, n*pi + (-1)**n*asin(y)), S.Integers))) assert dumeq(invert_real(sin(exp(x)), y, x), (x, imageset(Lambda(n, log((-1)**n*asin(y) + n*pi)), S.Integers))) assert dumeq(invert_real(csc(x), y, x), (x, imageset(Lambda(n, n*pi + (-1)**n*acsc(y)), S.Integers))) assert dumeq(invert_real(csc(exp(x)), y, x), (x, imageset(Lambda(n, log((-1)**n*acsc(y) + n*pi)), S.Integers))) assert dumeq(invert_real(cos(x), y, x), (x, Union(imageset(Lambda(n, 2*n*pi + acos(y)), S.Integers), \ imageset(Lambda(n, 2*n*pi - acos(y)), S.Integers)))) assert dumeq(invert_real(cos(exp(x)), y, x), (x, Union(imageset(Lambda(n, log(2*n*pi + acos(y))), S.Integers), \ imageset(Lambda(n, log(2*n*pi - acos(y))), S.Integers)))) assert dumeq(invert_real(sec(x), y, x), (x, Union(imageset(Lambda(n, 2*n*pi + asec(y)), S.Integers), \ imageset(Lambda(n, 2*n*pi - asec(y)), S.Integers)))) assert dumeq(invert_real(sec(exp(x)), y, x), (x, Union(imageset(Lambda(n, log(2*n*pi + asec(y))), S.Integers), \ imageset(Lambda(n, log(2*n*pi - asec(y))), S.Integers)))) assert dumeq(invert_real(tan(x), y, x), (x, imageset(Lambda(n, n*pi + atan(y)), S.Integers))) assert dumeq(invert_real(tan(exp(x)), y, x), (x, imageset(Lambda(n, log(n*pi + atan(y))), S.Integers))) assert dumeq(invert_real(cot(x), y, x), (x, imageset(Lambda(n, n*pi + acot(y)), S.Integers))) assert dumeq(invert_real(cot(exp(x)), y, x), (x, imageset(Lambda(n, log(n*pi + acot(y))), S.Integers))) assert dumeq(invert_real(tan(tan(x)), y, x), (tan(x), imageset(Lambda(n, n*pi + atan(y)), S.Integers))) x = Symbol('x', positive=True) assert invert_real(x**pi, y, x) == (x, FiniteSet(y**(1/pi))) def test_invert_complex(): assert invert_complex(x + 3, y, x) == (x, FiniteSet(y - 3)) assert invert_complex(x*3, y, x) == (x, FiniteSet(y / 3)) assert invert_complex((x - 1)**3, 0, x) == (x, FiniteSet(1)) assert dumeq(invert_complex(exp(x), y, x), (x, imageset(Lambda(n, I*(2*pi*n + arg(y)) + log(Abs(y))), S.Integers))) assert invert_complex(log(x), y, x) == (x, FiniteSet(exp(y))) raises(ValueError, lambda: invert_real(1, y, x)) raises(ValueError, lambda: invert_complex(x, x, x)) raises(ValueError, lambda: invert_complex(x, x, 1)) # https://github.com/skirpichev/omg/issues/16 assert invert_complex(sinh(x), 0, x) != (x, FiniteSet(0)) def test_domain_check(): assert domain_check(1/(1 + (1/(x+1))**2), x, -1) is False assert domain_check(x**2, x, 0) is True assert domain_check(x, x, oo) is False assert domain_check(0, x, oo) is False def test_issue_11536(): assert solveset(0**x - 100, x, S.Reals) == S.EmptySet assert solveset(0**x - 1, x, S.Reals) == FiniteSet(0) def test_issue_17479(): f = (x**2 + y**2)**2 + (x**2 + z**2)**2 - 2*(2*x**2 + y**2 + z**2) fx = f.diff(x) fy = f.diff(y) fz = f.diff(z) sol = nonlinsolve([fx, fy, fz], [x, y, z]) assert len(sol) >= 4 and len(sol) <= 20 # nonlinsolve has been giving a varying number of solutions # (originally 18, then 20, now 19) due to various internal changes. # Unfortunately not all the solutions are actually valid and some are # redundant. Since the original issue was that an exception was raised, # this first test only checks that nonlinsolve returns a "plausible" # solution set. The next test checks the result for correctness. @XFAIL def test_issue_18449(): x, y, z = symbols("x, y, z") f = (x**2 + y**2)**2 + (x**2 + z**2)**2 - 2*(2*x**2 + y**2 + z**2) fx = diff(f, x) fy = diff(f, y) fz = diff(f, z) sol = nonlinsolve([fx, fy, fz], [x, y, z]) for (xs, ys, zs) in sol: d = {x: xs, y: ys, z: zs} assert tuple(_.subs(d).simplify() for _ in (fx, fy, fz)) == (0, 0, 0) # After simplification and removal of duplicate elements, there should # only be 4 parametric solutions left: # simplifiedsolutions = FiniteSet((sqrt(1 - z**2), z, z), # (-sqrt(1 - z**2), z, z), # (sqrt(1 - z**2), -z, z), # (-sqrt(1 - z**2), -z, z)) # TODO: Is the above solution set definitely complete? def test_issue_21047(): f = (2 - x)**2 + (sqrt(x - 1) - 1)**6 assert solveset(f, x, S.Reals) == FiniteSet(2) f = (sqrt(x)-1)**2 + (sqrt(x)+1)**2 -2*x**2 + sqrt(2) assert solveset(f, x, S.Reals) == FiniteSet( S.Half - sqrt(2*sqrt(2) + 5)/2, S.Half + sqrt(2*sqrt(2) + 5)/2) def test_is_function_class_equation(): assert _is_function_class_equation(TrigonometricFunction, tan(x), x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x) - 1, x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x), x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x) - a, x) is True assert _is_function_class_equation(TrigonometricFunction, sin(x)*tan(x) + sin(x), x) is True assert _is_function_class_equation(TrigonometricFunction, sin(x)*tan(x + a) + sin(x), x) is True assert _is_function_class_equation(TrigonometricFunction, sin(x)*tan(x*a) + sin(x), x) is True assert _is_function_class_equation(TrigonometricFunction, a*tan(x) - 1, x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x)**2 + sin(x) - 1, x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x) + x, x) is False assert _is_function_class_equation(TrigonometricFunction, tan(x**2), x) is False assert _is_function_class_equation(TrigonometricFunction, tan(x**2) + sin(x), x) is False assert _is_function_class_equation(TrigonometricFunction, tan(x)**sin(x), x) is False assert _is_function_class_equation(TrigonometricFunction, tan(sin(x)) + sin(x), x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x) - 1, x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x) - a, x) is True assert _is_function_class_equation(HyperbolicFunction, sinh(x)*tanh(x) + sinh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, sinh(x)*tanh(x + a) + sinh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, sinh(x)*tanh(x*a) + sinh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, a*tanh(x) - 1, x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x)**2 + sinh(x) - 1, x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x) + x, x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(x**2), x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(x**2) + sinh(x), x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(x)**sinh(x), x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(sinh(x)) + sinh(x), x) is False def test_garbage_input(): raises(ValueError, lambda: solveset_real([y], y)) x = Symbol('x', real=True) assert solveset_real(x, 1) == S.EmptySet assert solveset_real(x - 1, 1) == FiniteSet(x) assert solveset_real(x, pi) == S.EmptySet assert solveset_real(x, x**2) == S.EmptySet raises(ValueError, lambda: solveset_complex([x], x)) assert solveset_complex(x, pi) == S.EmptySet raises(ValueError, lambda: solveset((x, y), x)) raises(ValueError, lambda: solveset(x + 1, S.Reals)) raises(ValueError, lambda: solveset(x + 1, x, 2)) def test_solve_mul(): assert solveset_real((a*x + b)*(exp(x) - 3), x) == \ Union({log(3)}, Intersection({-b/a}, S.Reals)) anz = Symbol('anz', nonzero=True) bb = Symbol('bb', real=True) assert solveset_real((anz*x + bb)*(exp(x) - 3), x) == \ FiniteSet(-bb/anz, log(3)) assert solveset_real((2*x + 8)*(8 + exp(x)), x) == FiniteSet(S(-4)) assert solveset_real(x/log(x), x) is S.EmptySet def test_solve_invert(): assert solveset_real(exp(x) - 3, x) == FiniteSet(log(3)) assert solveset_real(log(x) - 3, x) == FiniteSet(exp(3)) assert solveset_real(3**(x + 2), x) == FiniteSet() assert solveset_real(3**(2 - x), x) == FiniteSet() assert solveset_real(y - b*exp(a/x), x) == Intersection( S.Reals, FiniteSet(a/log(y/b))) # issue 4504 assert solveset_real(2**x - 10, x) == FiniteSet(1 + log(5)/log(2)) def test_errorinverses(): assert solveset_real(erf(x) - S.Half, x) == \ FiniteSet(erfinv(S.Half)) assert solveset_real(erfinv(x) - 2, x) == \ FiniteSet(erf(2)) assert solveset_real(erfc(x) - S.One, x) == \ FiniteSet(erfcinv(S.One)) assert solveset_real(erfcinv(x) - 2, x) == FiniteSet(erfc(2)) def test_solve_polynomial(): x = Symbol('x', real=True) y = Symbol('y', real=True) assert solveset_real(3*x - 2, x) == FiniteSet(Rational(2, 3)) assert solveset_real(x**2 - 1, x) == FiniteSet(-S.One, S.One) assert solveset_real(x - y**3, x) == FiniteSet(y ** 3) assert solveset_real(x**3 - 15*x - 4, x) == FiniteSet( -2 + 3 ** S.Half, S(4), -2 - 3 ** S.Half) assert solveset_real(sqrt(x) - 1, x) == FiniteSet(1) assert solveset_real(sqrt(x) - 2, x) == FiniteSet(4) assert solveset_real(x**Rational(1, 4) - 2, x) == FiniteSet(16) assert solveset_real(x**Rational(1, 3) - 3, x) == FiniteSet(27) assert len(solveset_real(x**5 + x**3 + 1, x)) == 1 assert len(solveset_real(-2*x**3 + 4*x**2 - 2*x + 6, x)) > 0 assert solveset_real(x**6 + x**4 + I, x) is S.EmptySet def test_return_root_of(): f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20 s = list(solveset_complex(f, x)) for root in s: assert root.func == CRootOf # if one uses solve to get the roots of a polynomial that has a CRootOf # solution, make sure that the use of nfloat during the solve process # doesn't fail. Note: if you want numerical solutions to a polynomial # it is *much* faster to use nroots to get them than to solve the # equation only to get CRootOf solutions which are then numerically # evaluated. So for eq = x**5 + 3*x + 7 do Poly(eq).nroots() rather # than [i.n() for i in solve(eq)] to get the numerical roots of eq. assert nfloat(list(solveset_complex(x**5 + 3*x**3 + 7, x))[0], exponent=False) == CRootOf(x**5 + 3*x**3 + 7, 0).n() sol = list(solveset_complex(x**6 - 2*x + 2, x)) assert all(isinstance(i, CRootOf) for i in sol) and len(sol) == 6 f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20 s = list(solveset_complex(f, x)) for root in s: assert root.func == CRootOf s = x**5 + 4*x**3 + 3*x**2 + Rational(7, 4) assert solveset_complex(s, x) == \ FiniteSet(*Poly(s*4, domain='ZZ').all_roots()) # Refer issue #7876 eq = x*(x - 1)**2*(x + 1)*(x**6 - x + 1) assert solveset_complex(eq, x) == \ FiniteSet(-1, 0, 1, CRootOf(x**6 - x + 1, 0), CRootOf(x**6 - x + 1, 1), CRootOf(x**6 - x + 1, 2), CRootOf(x**6 - x + 1, 3), CRootOf(x**6 - x + 1, 4), CRootOf(x**6 - x + 1, 5)) def test_solveset_sqrt_1(): assert solveset_real(sqrt(5*x + 6) - 2 - x, x) == \ FiniteSet(-S.One, S(2)) assert solveset_real(sqrt(x - 1) - x + 7, x) == FiniteSet(10) assert solveset_real(sqrt(x - 2) - 5, x) == FiniteSet(27) assert solveset_real(sqrt(x) - 2 - 5, x) == FiniteSet(49) assert solveset_real(sqrt(x**3), x) == FiniteSet(0) assert solveset_real(sqrt(x - 1), x) == FiniteSet(1) def test_solveset_sqrt_2(): x = Symbol('x', real=True) y = Symbol('y', real=True) # http://tutorial.math.lamar.edu/Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a assert solveset_real(sqrt(2*x - 1) - sqrt(x - 4) - 2, x) == \ FiniteSet(S(5), S(13)) assert solveset_real(sqrt(x + 7) + 2 - sqrt(3 - x), x) == \ FiniteSet(-6) # http://www.purplemath.com/modules/solverad.htm assert solveset_real(sqrt(17*x - sqrt(x**2 - 5)) - 7, x) == \ FiniteSet(3) eq = x + 1 - (x**4 + 4*x**3 - x)**Rational(1, 4) assert solveset_real(eq, x) == FiniteSet(Rational(-1, 2), Rational(-1, 3)) eq = sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4) assert solveset_real(eq, x) == FiniteSet(0) eq = sqrt(x + 4) + sqrt(2*x - 1) - 3*sqrt(x - 1) assert solveset_real(eq, x) == FiniteSet(5) eq = sqrt(x)*sqrt(x - 7) - 12 assert solveset_real(eq, x) == FiniteSet(16) eq = sqrt(x - 3) + sqrt(x) - 3 assert solveset_real(eq, x) == FiniteSet(4) eq = sqrt(2*x**2 - 7) - (3 - x) assert solveset_real(eq, x) == FiniteSet(-S(8), S(2)) # others eq = sqrt(9*x**2 + 4) - (3*x + 2) assert solveset_real(eq, x) == FiniteSet(0) assert solveset_real(sqrt(x - 3) - sqrt(x) - 3, x) == FiniteSet() eq = (2*x - 5)**Rational(1, 3) - 3 assert solveset_real(eq, x) == FiniteSet(16) assert solveset_real(sqrt(x) + sqrt(sqrt(x)) - 4, x) == \ FiniteSet((Rational(-1, 2) + sqrt(17)/2)**4) eq = sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x)) assert solveset_real(eq, x) == FiniteSet() eq = (x - 4)**2 + (sqrt(x) - 2)**4 assert solveset_real(eq, x) == FiniteSet(-4, 4) eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5) ans = solveset_real(eq, x) ra = S('''-1484/375 - 4*(-1/2 + sqrt(3)*I/2)*(-12459439/52734375 + 114*sqrt(12657)/78125)**(1/3) - 172564/(140625*(-1/2 + sqrt(3)*I/2)*(-12459439/52734375 + 114*sqrt(12657)/78125)**(1/3))''') rb = Rational(4, 5) assert all(abs(eq.subs(x, i).n()) < 1e-10 for i in (ra, rb)) and \ len(ans) == 2 and \ {i.n(chop=True) for i in ans} == \ {i.n(chop=True) for i in (ra, rb)} assert solveset_real(sqrt(x) + x**Rational(1, 3) + x**Rational(1, 4), x) == FiniteSet(0) assert solveset_real(x/sqrt(x**2 + 1), x) == FiniteSet(0) eq = (x - y**3)/((y**2)*sqrt(1 - y**2)) assert solveset_real(eq, x) == FiniteSet(y**3) # issue 4497 assert solveset_real(1/(5 + x)**Rational(1, 5) - 9, x) == \ FiniteSet(Rational(-295244, 59049)) @XFAIL def test_solve_sqrt_fail(): # this only works if we check real_root(eq.subs(x, Rational(1, 3))) # but checksol doesn't work like that eq = (x**3 - 3*x**2)**Rational(1, 3) + 1 - x assert solveset_real(eq, x) == FiniteSet(Rational(1, 3)) @slow def test_solve_sqrt_3(): R = Symbol('R') eq = sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1) sol = solveset_complex(eq, R) fset = [Rational(5, 3) + 4*sqrt(10)*cos(atan(3*sqrt(111)/251)/3)/3, -sqrt(10)*cos(atan(3*sqrt(111)/251)/3)/3 + 40*re(1/((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9 + sqrt(30)*sin(atan(3*sqrt(111)/251)/3)/3 + Rational(5, 3) + I*(-sqrt(30)*cos(atan(3*sqrt(111)/251)/3)/3 - sqrt(10)*sin(atan(3*sqrt(111)/251)/3)/3 + 40*im(1/((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9)] cset = [40*re(1/((Rational(-1, 2) + sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9 - sqrt(10)*cos(atan(3*sqrt(111)/251)/3)/3 - sqrt(30)*sin(atan(3*sqrt(111)/251)/3)/3 + Rational(5, 3) + I*(40*im(1/((Rational(-1, 2) + sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9 - sqrt(10)*sin(atan(3*sqrt(111)/251)/3)/3 + sqrt(30)*cos(atan(3*sqrt(111)/251)/3)/3)] assert sol._args[0] == FiniteSet(*fset) assert sol._args[1] == ConditionSet( R, Eq(sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1), 0), FiniteSet(*cset)) # the number of real roots will depend on the value of m: for m=1 there are 4 # and for m=-1 there are none. eq = -sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) + sqrt((-m**2/2 - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2) unsolved_object = ConditionSet(q, Eq(sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) - sqrt((-m**2/2 - sqrt(4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt(4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2), 0), S.Reals) assert solveset_real(eq, q) == unsolved_object def test_solve_polynomial_symbolic_param(): assert solveset_complex((x**2 - 1)**2 - a, x) == \ FiniteSet(sqrt(1 + sqrt(a)), -sqrt(1 + sqrt(a)), sqrt(1 - sqrt(a)), -sqrt(1 - sqrt(a))) # issue 4507 assert solveset_complex(y - b/(1 + a*x), x) == \ FiniteSet((b/y - 1)/a) - FiniteSet(-1/a) # issue 4508 assert solveset_complex(y - b*x/(a + x), x) == \ FiniteSet(-a*y/(y - b)) - FiniteSet(-a) def test_solve_rational(): assert solveset_real(1/x + 1, x) == FiniteSet(-S.One) assert solveset_real(1/exp(x) - 1, x) == FiniteSet(0) assert solveset_real(x*(1 - 5/x), x) == FiniteSet(5) assert solveset_real(2*x/(x + 2) - 1, x) == FiniteSet(2) assert solveset_real((x**2/(7 - x)).diff(x), x) == \ FiniteSet(S.Zero, S(14)) def test_solveset_real_gen_is_pow(): assert solveset_real(sqrt(1) + 1, x) is S.EmptySet def test_no_sol(): assert solveset(1 - oo*x) is S.EmptySet assert solveset(oo*x, x) is S.EmptySet assert solveset(oo*x - oo, x) is S.EmptySet assert solveset_real(4, x) is S.EmptySet assert solveset_real(exp(x), x) is S.EmptySet assert solveset_real(x**2 + 1, x) is S.EmptySet assert solveset_real(-3*a/sqrt(x), x) is S.EmptySet assert solveset_real(1/x, x) is S.EmptySet assert solveset_real(-(1 + x)/(2 + x)**2 + 1/(2 + x), x ) is S.EmptySet def test_sol_zero_real(): assert solveset_real(0, x) == S.Reals assert solveset(0, x, Interval(1, 2)) == Interval(1, 2) assert solveset_real(-x**2 - 2*x + (x + 1)**2 - 1, x) == S.Reals def test_no_sol_rational_extragenous(): assert solveset_real((x/(x + 1) + 3)**(-2), x) is S.EmptySet assert solveset_real((x - 1)/(1 + 1/(x - 1)), x) is S.EmptySet def test_solve_polynomial_cv_1a(): """ Test for solving on equations that can be converted to a polynomial equation using the change of variable y -> x**Rational(p, q) """ assert solveset_real(sqrt(x) - 1, x) == FiniteSet(1) assert solveset_real(sqrt(x) - 2, x) == FiniteSet(4) assert solveset_real(x**Rational(1, 4) - 2, x) == FiniteSet(16) assert solveset_real(x**Rational(1, 3) - 3, x) == FiniteSet(27) assert solveset_real(x*(x**(S.One / 3) - 3), x) == \ FiniteSet(S.Zero, S(27)) def test_solveset_real_rational(): """Test solveset_real for rational functions""" x = Symbol('x', real=True) y = Symbol('y', real=True) assert solveset_real((x - y**3) / ((y**2)*sqrt(1 - y**2)), x) \ == FiniteSet(y**3) # issue 4486 assert solveset_real(2*x/(x + 2) - 1, x) == FiniteSet(2) def test_solveset_real_log(): assert solveset_real(log((x-1)*(x+1)), x) == \ FiniteSet(sqrt(2), -sqrt(2)) def test_poly_gens(): assert solveset_real(4**(2*(x**2) + 2*x) - 8, x) == \ FiniteSet(Rational(-3, 2), S.Half) def test_solve_abs(): n = Dummy('n') raises(ValueError, lambda: solveset(Abs(x) - 1, x)) assert solveset(Abs(x) - n, x, S.Reals).dummy_eq( ConditionSet(x, Contains(n, Interval(0, oo)), {-n, n})) assert solveset_real(Abs(x) - 2, x) == FiniteSet(-2, 2) assert solveset_real(Abs(x) + 2, x) is S.EmptySet assert solveset_real(Abs(x + 3) - 2*Abs(x - 3), x) == \ FiniteSet(1, 9) assert solveset_real(2*Abs(x) - Abs(x - 1), x) == \ FiniteSet(-1, Rational(1, 3)) sol = ConditionSet( x, And( Contains(b, Interval(0, oo)), Contains(a + b, Interval(0, oo)), Contains(a - b, Interval(0, oo))), FiniteSet(-a - b - 3, -a + b - 3, a - b - 3, a + b - 3)) eq = Abs(Abs(x + 3) - a) - b assert invert_real(eq, 0, x)[1] == sol reps = {a: 3, b: 1} eqab = eq.subs(reps) for si in sol.subs(reps): assert not eqab.subs(x, si) assert dumeq(solveset(Eq(sin(Abs(x)), 1), x, domain=S.Reals), Union( Intersection(Interval(0, oo), ImageSet(Lambda(n, (-1)**n*pi/2 + n*pi), S.Integers)), Intersection(Interval(-oo, 0), ImageSet(Lambda(n, n*pi - (-1)**(-n)*pi/2), S.Integers)))) def test_issue_9824(): assert dumeq(solveset(sin(x)**2 - 2*sin(x) + 1, x), ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers)) assert dumeq(solveset(cos(x)**2 - 2*cos(x) + 1, x), ImageSet(Lambda(n, 2*n*pi), S.Integers)) def test_issue_9565(): assert solveset_real(Abs((x - 1)/(x - 5)) <= Rational(1, 3), x) == Interval(-1, 2) def test_issue_10069(): eq = abs(1/(x - 1)) - 1 > 0 assert solveset_real(eq, x) == Union( Interval.open(0, 1), Interval.open(1, 2)) def test_real_imag_splitting(): a, b = symbols('a b', real=True) assert solveset_real(sqrt(a**2 - b**2) - 3, a) == \ FiniteSet(-sqrt(b**2 + 9), sqrt(b**2 + 9)) assert solveset_real(sqrt(a**2 + b**2) - 3, a) != \ S.EmptySet def test_units(): assert solveset_real(1/x - 1/(2*cm), x) == FiniteSet(2*cm) def test_solve_only_exp_1(): y = Symbol('y', positive=True) assert solveset_real(exp(x) - y, x) == FiniteSet(log(y)) assert solveset_real(exp(x) + exp(-x) - 4, x) == \ FiniteSet(log(-sqrt(3) + 2), log(sqrt(3) + 2)) assert solveset_real(exp(x) + exp(-x) - y, x) != S.EmptySet def test_atan2(): # The .inverse() method on atan2 works only if x.is_real is True and the # second argument is a real constant assert solveset_real(atan2(x, 2) - pi/3, x) == FiniteSet(2*sqrt(3)) def test_piecewise_solveset(): eq = Piecewise((x - 2, Gt(x, 2)), (2 - x, True)) - 3 assert set(solveset_real(eq, x)) == set(FiniteSet(-1, 5)) absxm3 = Piecewise( (x - 3, 0 <= x - 3), (3 - x, 0 > x - 3)) y = Symbol('y', positive=True) assert solveset_real(absxm3 - y, x) == FiniteSet(-y + 3, y + 3) f = Piecewise(((x - 2)**2, x >= 0), (0, True)) assert solveset(f, x, domain=S.Reals) == Union(FiniteSet(2), Interval(-oo, 0, True, True)) assert solveset( Piecewise((x + 1, x > 0), (I, True)) - I, x, S.Reals ) == Interval(-oo, 0) assert solveset(Piecewise((x - 1, Ne(x, I)), (x, True)), x) == FiniteSet(1) # issue 19718 g = Piecewise((1, x > 10), (0, True)) assert solveset(g > 0, x, S.Reals) == Interval.open(10, oo) from sympy.logic.boolalg import BooleanTrue f = BooleanTrue() assert solveset(f, x, domain=Interval(-3, 10)) == Interval(-3, 10) # issue 20552 f = Piecewise((0, Eq(x, 0)), (x**2/Abs(x), True)) g = Piecewise((0, Eq(x, pi)), ((x - pi)/sin(x), True)) assert solveset(f, x, domain=S.Reals) == FiniteSet(0) assert solveset(g) == FiniteSet(pi) def test_solveset_complex_polynomial(): assert solveset_complex(a*x**2 + b*x + c, x) == \ FiniteSet(-b/(2*a) - sqrt(-4*a*c + b**2)/(2*a), -b/(2*a) + sqrt(-4*a*c + b**2)/(2*a)) assert solveset_complex(x - y**3, y) == FiniteSet( (-x**Rational(1, 3))/2 + I*sqrt(3)*x**Rational(1, 3)/2, x**Rational(1, 3), (-x**Rational(1, 3))/2 - I*sqrt(3)*x**Rational(1, 3)/2) assert solveset_complex(x + 1/x - 1, x) == \ FiniteSet(S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2) def test_sol_zero_complex(): assert solveset_complex(0, x) is S.Complexes def test_solveset_complex_rational(): assert solveset_complex((x - 1)*(x - I)/(x - 3), x) == \ FiniteSet(1, I) assert solveset_complex((x - y**3)/((y**2)*sqrt(1 - y**2)), x) == \ FiniteSet(y**3) assert solveset_complex(-x**2 - I, x) == \ FiniteSet(-sqrt(2)/2 + sqrt(2)*I/2, sqrt(2)/2 - sqrt(2)*I/2) def test_solve_quintics(): skip("This test is too slow") f = x**5 - 110*x**3 - 55*x**2 + 2310*x + 979 s = solveset_complex(f, x) for root in s: res = f.subs(x, root.n()).n() assert tn(res, 0) f = x**5 + 15*x + 12 s = solveset_complex(f, x) for root in s: res = f.subs(x, root.n()).n() assert tn(res, 0) def test_solveset_complex_exp(): assert dumeq(solveset_complex(exp(x) - 1, x), imageset(Lambda(n, I*2*n*pi), S.Integers)) assert dumeq(solveset_complex(exp(x) - I, x), imageset(Lambda(n, I*(2*n*pi + pi/2)), S.Integers)) assert solveset_complex(1/exp(x), x) == S.EmptySet assert dumeq(solveset_complex(sinh(x).rewrite(exp), x), imageset(Lambda(n, n*pi*I), S.Integers)) def test_solveset_real_exp(): assert solveset(Eq((-2)**x, 4), x, S.Reals) == FiniteSet(2) assert solveset(Eq(-2**x, 4), x, S.Reals) == S.EmptySet assert solveset(Eq((-3)**x, 27), x, S.Reals) == S.EmptySet assert solveset(Eq((-5)**(x+1), 625), x, S.Reals) == FiniteSet(3) assert solveset(Eq(2**(x-3), -16), x, S.Reals) == S.EmptySet assert solveset(Eq((-3)**(x - 3), -3**39), x, S.Reals) == FiniteSet(42) assert solveset(Eq(2**x, y), x, S.Reals) == Intersection(S.Reals, FiniteSet(log(y)/log(2))) assert invert_real((-2)**(2*x) - 16, 0, x) == (x, FiniteSet(2)) def test_solve_complex_log(): assert solveset_complex(log(x), x) == FiniteSet(1) assert solveset_complex(1 - log(a + 4*x**2), x) == \ FiniteSet(-sqrt(-a + E)/2, sqrt(-a + E)/2) def test_solve_complex_sqrt(): assert solveset_complex(sqrt(5*x + 6) - 2 - x, x) == \ FiniteSet(-S.One, S(2)) assert solveset_complex(sqrt(5*x + 6) - (2 + 2*I) - x, x) == \ FiniteSet(-S(2), 3 - 4*I) assert solveset_complex(4*x*(1 - a * sqrt(x)), x) == \ FiniteSet(S.Zero, 1 / a ** 2) def test_solveset_complex_tan(): s = solveset_complex(tan(x).rewrite(exp), x) assert dumeq(s, imageset(Lambda(n, pi*n), S.Integers) - \ imageset(Lambda(n, pi*n + pi/2), S.Integers)) @_both_exp_pow def test_solve_trig(): assert dumeq(solveset_real(sin(x), x), Union(imageset(Lambda(n, 2*pi*n), S.Integers), imageset(Lambda(n, 2*pi*n + pi), S.Integers))) assert dumeq(solveset_real(sin(x) - 1, x), imageset(Lambda(n, 2*pi*n + pi/2), S.Integers)) assert dumeq(solveset_real(cos(x), x), Union(imageset(Lambda(n, 2*pi*n + pi/2), S.Integers), imageset(Lambda(n, 2*pi*n + pi*Rational(3, 2)), S.Integers))) assert dumeq(solveset_real(sin(x) + cos(x), x), Union(imageset(Lambda(n, 2*n*pi + pi*Rational(3, 4)), S.Integers), imageset(Lambda(n, 2*n*pi + pi*Rational(7, 4)), S.Integers))) assert solveset_real(sin(x)**2 + cos(x)**2, x) == S.EmptySet assert dumeq(solveset_complex(cos(x) - S.Half, x), Union(imageset(Lambda(n, 2*n*pi + pi*Rational(5, 3)), S.Integers), imageset(Lambda(n, 2*n*pi + pi/3), S.Integers))) assert dumeq(solveset(sin(y + a) - sin(y), a, domain=S.Reals), Union(ImageSet(Lambda(n, 2*n*pi), S.Integers), Intersection(ImageSet(Lambda(n, -I*(I*( 2*n*pi + arg(-exp(-2*I*y))) + 2*im(y))), S.Integers), S.Reals))) assert dumeq(solveset_real(sin(2*x)*cos(x) + cos(2*x)*sin(x)-1, x), ImageSet(Lambda(n, n*pi*Rational(2, 3) + pi/6), S.Integers)) assert dumeq(solveset_real(2*tan(x)*sin(x) + 1, x), Union( ImageSet(Lambda(n, 2*n*pi + atan(sqrt(2)*sqrt(-1 + sqrt(17))/ (1 - sqrt(17))) + pi), S.Integers), ImageSet(Lambda(n, 2*n*pi - atan(sqrt(2)*sqrt(-1 + sqrt(17))/ (1 - sqrt(17))) + pi), S.Integers))) assert dumeq(solveset_real(cos(2*x)*cos(4*x) - 1, x), ImageSet(Lambda(n, n*pi), S.Integers)) assert dumeq(solveset(sin(x/10) + Rational(3, 4)), Union( ImageSet(Lambda(n, 20*n*pi + 10*atan(3*sqrt(7)/7) + 10*pi), S.Integers), ImageSet(Lambda(n, 20*n*pi - 10*atan(3*sqrt(7)/7) + 20*pi), S.Integers))) assert dumeq(solveset(cos(x/15) + cos(x/5)), Union( ImageSet(Lambda(n, 30*n*pi + 15*pi/2), S.Integers), ImageSet(Lambda(n, 30*n*pi + 45*pi/2), S.Integers), ImageSet(Lambda(n, 30*n*pi + 75*pi/4), S.Integers), ImageSet(Lambda(n, 30*n*pi + 45*pi/4), S.Integers), ImageSet(Lambda(n, 30*n*pi + 105*pi/4), S.Integers), ImageSet(Lambda(n, 30*n*pi + 15*pi/4), S.Integers))) assert dumeq(solveset(sec(sqrt(2)*x/3) + 5), Union( ImageSet(Lambda(n, 3*sqrt(2)*(2*n*pi - pi + atan(2*sqrt(6)))/2), S.Integers), ImageSet(Lambda(n, 3*sqrt(2)*(2*n*pi - atan(2*sqrt(6)) + pi)/2), S.Integers))) assert dumeq(simplify(solveset(tan(pi*x) - cot(pi/2*x))), Union( ImageSet(Lambda(n, 4*n + 1), S.Integers), ImageSet(Lambda(n, 4*n + 3), S.Integers), ImageSet(Lambda(n, 4*n + Rational(7, 3)), S.Integers), ImageSet(Lambda(n, 4*n + Rational(5, 3)), S.Integers), ImageSet(Lambda(n, 4*n + Rational(11, 3)), S.Integers), ImageSet(Lambda(n, 4*n + Rational(1, 3)), S.Integers))) assert dumeq(solveset(cos(9*x)), Union( ImageSet(Lambda(n, 2*n*pi/9 + pi/18), S.Integers), ImageSet(Lambda(n, 2*n*pi/9 + pi/6), S.Integers))) assert dumeq(solveset(sin(8*x) + cot(12*x), x, S.Reals), Union( ImageSet(Lambda(n, n*pi/2 + pi/8), S.Integers), ImageSet(Lambda(n, n*pi/2 + 3*pi/8), S.Integers), ImageSet(Lambda(n, n*pi/2 + 5*pi/16), S.Integers), ImageSet(Lambda(n, n*pi/2 + 3*pi/16), S.Integers), ImageSet(Lambda(n, n*pi/2 + 7*pi/16), S.Integers), ImageSet(Lambda(n, n*pi/2 + pi/16), S.Integers))) # This is the only remaining solveset test that actually ends up being solved # by _solve_trig2(). All others are handled by the improved _solve_trig1. assert dumeq(solveset_real(2*cos(x)*cos(2*x) - 1, x), Union(ImageSet(Lambda(n, 2*n*pi + 2*atan(sqrt(-2*2**Rational(1, 3)*(67 + 9*sqrt(57))**Rational(2, 3) + 8*2**Rational(2, 3) + 11*(67 + 9*sqrt(57))**Rational(1, 3))/(3*(67 + 9*sqrt(57))**Rational(1, 6)))), S.Integers), ImageSet(Lambda(n, 2*n*pi - 2*atan(sqrt(-2*2**Rational(1, 3)*(67 + 9*sqrt(57))**Rational(2, 3) + 8*2**Rational(2, 3) + 11*(67 + 9*sqrt(57))**Rational(1, 3))/(3*(67 + 9*sqrt(57))**Rational(1, 6))) + 2*pi), S.Integers))) # issue #16870 assert dumeq(simplify(solveset(sin(x/180*pi) - S.Half, x, S.Reals)), Union( ImageSet(Lambda(n, 360*n + 150), S.Integers), ImageSet(Lambda(n, 360*n + 30), S.Integers))) def test_solve_hyperbolic(): # actual solver: _solve_trig1 n = Dummy('n') assert solveset(sinh(x) + cosh(x), x) == S.EmptySet assert solveset(sinh(x) + cos(x), x) == ConditionSet(x, Eq(cos(x) + sinh(x), 0), S.Complexes) assert solveset_real(sinh(x) + sech(x), x) == FiniteSet( log(sqrt(sqrt(5) - 2))) assert solveset_real(3*cosh(2*x) - 5, x) == FiniteSet( -log(3)/2, log(3)/2) assert solveset_real(sinh(x - 3) - 2, x) == FiniteSet( log((2 + sqrt(5))*exp(3))) assert solveset_real(cosh(2*x) + 2*sinh(x) - 5, x) == FiniteSet( log(-2 + sqrt(5)), log(1 + sqrt(2))) assert solveset_real((coth(x) + sinh(2*x))/cosh(x) - 3, x) == FiniteSet( log(S.Half + sqrt(5)/2), log(1 + sqrt(2))) assert solveset_real(cosh(x)*sinh(x) - 2, x) == FiniteSet( log(4 + sqrt(17))/2) assert solveset_real(sinh(x) + tanh(x) - 1, x) == FiniteSet( log(sqrt(2)/2 + sqrt(-S(1)/2 + sqrt(2)))) assert dumeq(solveset_complex(sinh(x) - I/2, x), Union( ImageSet(Lambda(n, I*(2*n*pi + 5*pi/6)), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi/6)), S.Integers))) assert dumeq(solveset_complex(sinh(x) + sech(x), x), Union( ImageSet(Lambda(n, 2*n*I*pi + log(sqrt(-2 + sqrt(5)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi/2) + log(sqrt(2 + sqrt(5)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi) + log(sqrt(-2 + sqrt(5)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi - pi/2) + log(sqrt(2 + sqrt(5)))), S.Integers))) assert dumeq(solveset(sinh(x/10) + Rational(3, 4)), Union( ImageSet(Lambda(n, 10*I*(2*n*pi + pi) + 10*log(2)), S.Integers), ImageSet(Lambda(n, 20*n*I*pi - 10*log(2)), S.Integers))) assert dumeq(solveset(cosh(x/15) + cosh(x/5)), Union( ImageSet(Lambda(n, 15*I*(2*n*pi + pi/2)), S.Integers), ImageSet(Lambda(n, 15*I*(2*n*pi - pi/2)), S.Integers), ImageSet(Lambda(n, 15*I*(2*n*pi - 3*pi/4)), S.Integers), ImageSet(Lambda(n, 15*I*(2*n*pi + 3*pi/4)), S.Integers), ImageSet(Lambda(n, 15*I*(2*n*pi - pi/4)), S.Integers), ImageSet(Lambda(n, 15*I*(2*n*pi + pi/4)), S.Integers))) assert dumeq(solveset(sech(sqrt(2)*x/3) + 5), Union( ImageSet(Lambda(n, 3*sqrt(2)*I*(2*n*pi - pi + atan(2*sqrt(6)))/2), S.Integers), ImageSet(Lambda(n, 3*sqrt(2)*I*(2*n*pi - atan(2*sqrt(6)) + pi)/2), S.Integers))) assert dumeq(solveset(tanh(pi*x) - coth(pi/2*x)), Union( ImageSet(Lambda(n, 2*I*(2*n*pi + pi/2)/pi), S.Integers), ImageSet(Lambda(n, 2*I*(2*n*pi - pi/2)/pi), S.Integers))) assert dumeq(solveset(cosh(9*x)), Union( ImageSet(Lambda(n, I*(2*n*pi + pi/2)/9), S.Integers), ImageSet(Lambda(n, I*(2*n*pi - pi/2)/9), S.Integers))) # issues #9606 / #9531: assert solveset(sinh(x), x, S.Reals) == FiniteSet(0) assert dumeq(solveset(sinh(x), x, S.Complexes), Union( ImageSet(Lambda(n, I*(2*n*pi + pi)), S.Integers), ImageSet(Lambda(n, 2*n*I*pi), S.Integers))) # issues #11218 / #18427 assert dumeq(solveset(sin(pi*x), x, S.Reals), Union( ImageSet(Lambda(n, (2*n*pi + pi)/pi), S.Integers), ImageSet(Lambda(n, 2*n), S.Integers))) assert dumeq(solveset(sin(pi*x), x), Union( ImageSet(Lambda(n, (2*n*pi + pi)/pi), S.Integers), ImageSet(Lambda(n, 2*n), S.Integers))) # issue #17543 assert dumeq(simplify(solveset(I*cot(8*x - 8*E), x)), Union( ImageSet(Lambda(n, n*pi/4 - 13*pi/16 + E), S.Integers), ImageSet(Lambda(n, n*pi/4 - 11*pi/16 + E), S.Integers))) # issues #18490 / #19489 assert solveset(cosh(x) + cosh(3*x) - cosh(5*x), x, S.Reals ).dummy_eq(ConditionSet(x, Eq(cosh(x) + cosh(3*x) - cosh(5*x), 0), S.Reals)) assert solveset(sinh(8*x) + coth(12*x)).dummy_eq( ConditionSet(x, Eq(sinh(8*x) + coth(12*x), 0), S.Complexes)) def test_solve_trig_hyp_symbolic(): # actual solver: _solve_trig1 assert dumeq(solveset(sin(a*x), x), ConditionSet(x, Ne(a, 0), Union( ImageSet(Lambda(n, (2*n*pi + pi)/a), S.Integers), ImageSet(Lambda(n, 2*n*pi/a), S.Integers)))) assert dumeq(solveset(cosh(x/a), x), ConditionSet(x, Ne(a, 0), Union( ImageSet(Lambda(n, I*a*(2*n*pi + pi/2)), S.Integers), ImageSet(Lambda(n, I*a*(2*n*pi - pi/2)), S.Integers)))) assert dumeq(solveset(sin(2*sqrt(3)/3*a**2/(b*pi)*x) + cos(4*sqrt(3)/3*a**2/(b*pi)*x), x), ConditionSet(x, Ne(b, 0) & Ne(a**2, 0), Union( ImageSet(Lambda(n, sqrt(3)*pi*b*(2*n*pi + pi/2)/(2*a**2)), S.Integers), ImageSet(Lambda(n, sqrt(3)*pi*b*(2*n*pi - 5*pi/6)/(2*a**2)), S.Integers), ImageSet(Lambda(n, sqrt(3)*pi*b*(2*n*pi - pi/6)/(2*a**2)), S.Integers)))) assert dumeq(simplify(solveset(cot((1 + I)*x) - cot((3 + 3*I)*x), x)), Union( ImageSet(Lambda(n, pi*(1 - I)*(4*n + 1)/4), S.Integers), ImageSet(Lambda(n, pi*(1 - I)*(4*n - 1)/4), S.Integers))) assert dumeq(solveset(cosh((a**2 + 1)*x) - 3, x), ConditionSet(x, Ne(a**2 + 1, 0), Union( ImageSet(Lambda(n, (2*n*I*pi + log(3 - 2*sqrt(2)))/(a**2 + 1)), S.Integers), ImageSet(Lambda(n, (2*n*I*pi + log(2*sqrt(2) + 3))/(a**2 + 1)), S.Integers)))) ar = Symbol('ar', real=True) assert solveset(cosh((ar**2 + 1)*x) - 2, x, S.Reals) == FiniteSet( log(sqrt(3) + 2)/(ar**2 + 1), log(2 - sqrt(3))/(ar**2 + 1)) def test_issue_9616(): assert dumeq(solveset(sinh(x) + tanh(x) - 1, x), Union( ImageSet(Lambda(n, 2*n*I*pi + log(sqrt(2)/2 + sqrt(-S.Half + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi - atan(sqrt(2)*sqrt(S.Half + sqrt(2))) + pi) + log(sqrt(1 + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi) + log(-sqrt(2)/2 + sqrt(-S.Half + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi - pi + atan(sqrt(2)*sqrt(S.Half + sqrt(2)))) + log(sqrt(1 + sqrt(2)))), S.Integers))) f1 = (sinh(x)).rewrite(exp) f2 = (tanh(x)).rewrite(exp) assert dumeq(solveset(f1 + f2 - 1, x), Union( Complement(ImageSet( Lambda(n, I*(2*n*pi + pi) + log(-sqrt(2)/2 + sqrt(-S.Half + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi)/2), S.Integers)), Complement(ImageSet(Lambda(n, I*(2*n*pi - pi + atan(sqrt(2)*sqrt(S.Half + sqrt(2)))) + log(sqrt(1 + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi)/2), S.Integers)), Complement(ImageSet(Lambda(n, I*(2*n*pi - atan(sqrt(2)*sqrt(S.Half + sqrt(2))) + pi) + log(sqrt(1 + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi)/2), S.Integers)), Complement( ImageSet(Lambda(n, 2*n*I*pi + log(sqrt(2)/2 + sqrt(-S.Half + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi)/2), S.Integers)))) def test_solve_invalid_sol(): assert 0 not in solveset_real(sin(x)/x, x) assert 0 not in solveset_complex((exp(x) - 1)/x, x) @XFAIL def test_solve_trig_simplified(): n = Dummy('n') assert dumeq(solveset_real(sin(x), x), imageset(Lambda(n, n*pi), S.Integers)) assert dumeq(solveset_real(cos(x), x), imageset(Lambda(n, n*pi + pi/2), S.Integers)) assert dumeq(solveset_real(cos(x) + sin(x), x), imageset(Lambda(n, n*pi - pi/4), S.Integers)) @XFAIL def test_solve_lambert(): assert solveset_real(x*exp(x) - 1, x) == FiniteSet(LambertW(1)) assert solveset_real(exp(x) + x, x) == FiniteSet(-LambertW(1)) assert solveset_real(x + 2**x, x) == \ FiniteSet(-LambertW(log(2))/log(2)) # issue 4739 ans = solveset_real(3*x + 5 + 2**(-5*x + 3), x) assert ans == FiniteSet(Rational(-5, 3) + LambertW(-10240*2**Rational(1, 3)*log(2)/3)/(5*log(2))) eq = 2*(3*x + 4)**5 - 6*7**(3*x + 9) result = solveset_real(eq, x) ans = FiniteSet((log(2401) + 5*LambertW(-log(7**(7*3**Rational(1, 5)/5))))/(3*log(7))/-1) assert result == ans assert solveset_real(eq.expand(), x) == result assert solveset_real(5*x - 1 + 3*exp(2 - 7*x), x) == \ FiniteSet(Rational(1, 5) + LambertW(-21*exp(Rational(3, 5))/5)/7) assert solveset_real(2*x + 5 + log(3*x - 2), x) == \ FiniteSet(Rational(2, 3) + LambertW(2*exp(Rational(-19, 3))/3)/2) assert solveset_real(3*x + log(4*x), x) == \ FiniteSet(LambertW(Rational(3, 4))/3) assert solveset_real(x**x - 2) == FiniteSet(exp(LambertW(log(2)))) a = Symbol('a') assert solveset_real(-a*x + 2*x*log(x), x) == FiniteSet(exp(a/2)) a = Symbol('a', real=True) assert solveset_real(a/x + exp(x/2), x) == \ FiniteSet(2*LambertW(-a/2)) assert solveset_real((a/x + exp(x/2)).diff(x), x) == \ FiniteSet(4*LambertW(sqrt(2)*sqrt(a)/4)) # coverage test assert solveset_real(tanh(x + 3)*tanh(x - 3) - 1, x) is S.EmptySet assert solveset_real((x**2 - 2*x + 1).subs(x, log(x) + 3*x), x) == \ FiniteSet(LambertW(3*S.Exp1)/3) assert solveset_real((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x) == \ FiniteSet(LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3) assert solveset_real((x**2 - 2*x - 2).subs(x, log(x) + 3*x), x) == \ FiniteSet(LambertW(3*exp(1 + sqrt(3)))/3, LambertW(3*exp(-sqrt(3) + 1))/3) assert solveset_real(x*log(x) + 3*x + 1, x) == \ FiniteSet(exp(-3 + LambertW(-exp(3)))) eq = (x*exp(x) - 3).subs(x, x*exp(x)) assert solveset_real(eq, x) == \ FiniteSet(LambertW(3*exp(-LambertW(3)))) assert solveset_real(3*log(a**(3*x + 5)) + a**(3*x + 5), x) == \ FiniteSet(-((log(a**5) + LambertW(Rational(1, 3)))/(3*log(a)))) p = symbols('p', positive=True) assert solveset_real(3*log(p**(3*x + 5)) + p**(3*x + 5), x) == \ FiniteSet( log((-3**Rational(1, 3) - 3**Rational(5, 6)*I)*LambertW(Rational(1, 3))**Rational(1, 3)/(2*p**Rational(5, 3)))/log(p), log((-3**Rational(1, 3) + 3**Rational(5, 6)*I)*LambertW(Rational(1, 3))**Rational(1, 3)/(2*p**Rational(5, 3)))/log(p), log((3*LambertW(Rational(1, 3))/p**5)**(1/(3*log(p)))),) # checked numerically # check collection b = Symbol('b') eq = 3*log(a**(3*x + 5)) + b*log(a**(3*x + 5)) + a**(3*x + 5) assert solveset_real(eq, x) == FiniteSet( -((log(a**5) + LambertW(1/(b + 3)))/(3*log(a)))) # issue 4271 assert solveset_real((a/x + exp(x/2)).diff(x, 2), x) == FiniteSet( 6*LambertW((-1)**Rational(1, 3)*a**Rational(1, 3)/3)) assert solveset_real(x**3 - 3**x, x) == \ FiniteSet(-3/log(3)*LambertW(-log(3)/3)) assert solveset_real(3**cos(x) - cos(x)**3) == FiniteSet( acos(-3*LambertW(-log(3)/3)/log(3))) assert solveset_real(x**2 - 2**x, x) == \ solveset_real(-x**2 + 2**x, x) assert solveset_real(3*log(x) - x*log(3)) == FiniteSet( -3*LambertW(-log(3)/3)/log(3), -3*LambertW(-log(3)/3, -1)/log(3)) assert solveset_real(LambertW(2*x) - y) == FiniteSet( y*exp(y)/2) @XFAIL def test_other_lambert(): a = Rational(6, 5) assert solveset_real(x**a - a**x, x) == FiniteSet( a, -a*LambertW(-log(a)/a)/log(a)) @_both_exp_pow def test_solveset(): f = Function('f') raises(ValueError, lambda: solveset(x + y)) assert solveset(x, 1) == S.EmptySet assert solveset(f(1)**2 + y + 1, f(1) ) == FiniteSet(-sqrt(-y - 1), sqrt(-y - 1)) assert solveset(f(1)**2 - 1, f(1), S.Reals) == FiniteSet(-1, 1) assert solveset(f(1)**2 + 1, f(1)) == FiniteSet(-I, I) assert solveset(x - 1, 1) == FiniteSet(x) assert solveset(sin(x) - cos(x), sin(x)) == FiniteSet(cos(x)) assert solveset(0, domain=S.Reals) == S.Reals assert solveset(1) == S.EmptySet assert solveset(True, domain=S.Reals) == S.Reals # issue 10197 assert solveset(False, domain=S.Reals) == S.EmptySet assert solveset(exp(x) - 1, domain=S.Reals) == FiniteSet(0) assert solveset(exp(x) - 1, x, S.Reals) == FiniteSet(0) assert solveset(Eq(exp(x), 1), x, S.Reals) == FiniteSet(0) assert solveset(exp(x) - 1, exp(x), S.Reals) == FiniteSet(1) A = Indexed('A', x) assert solveset(A - 1, A, S.Reals) == FiniteSet(1) assert solveset(x - 1 >= 0, x, S.Reals) == Interval(1, oo) assert solveset(exp(x) - 1 >= 0, x, S.Reals) == Interval(0, oo) assert dumeq(solveset(exp(x) - 1, x), imageset(Lambda(n, 2*I*pi*n), S.Integers)) assert dumeq(solveset(Eq(exp(x), 1), x), imageset(Lambda(n, 2*I*pi*n), S.Integers)) # issue 13825 assert solveset(x**2 + f(0) + 1, x) == {-sqrt(-f(0) - 1), sqrt(-f(0) - 1)} # issue 19977 assert solveset(atan(log(x)) > 0, x, domain=Interval.open(0, oo)) == Interval.open(1, oo) @_both_exp_pow def test_multi_exp(): k1, k2, k3 = symbols('k1, k2, k3') assert dumeq(solveset(exp(exp(x)) - 5, x),\ imageset(Lambda(((k1, n),), I*(2*k1*pi + arg(2*n*I*pi + log(5))) + log(Abs(2*n*I*pi + log(5)))),\ ProductSet(S.Integers, S.Integers))) assert dumeq(solveset((d*exp(exp(a*x + b)) + c), x),\ imageset(Lambda(x, (-b + x)/a), ImageSet(Lambda(((k1, n),), \ I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d))))), \ ProductSet(S.Integers, S.Integers)))) assert dumeq(solveset((d*exp(exp(exp(a*x + b))) + c), x),\ imageset(Lambda(x, (-b + x)/a), ImageSet(Lambda(((k2, k1, n),), \ I*(2*k2*pi + arg(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + \ log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))))) + log(Abs(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + \ log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d))))))), \ ProductSet(S.Integers, S.Integers, S.Integers)))) assert dumeq(solveset((d*exp(exp(exp(exp(a*x + b)))) + c), x),\ ImageSet(Lambda(x, (-b + x)/a), ImageSet(Lambda(((k3, k2, k1, n),), \ I*(2*k3*pi + arg(I*(2*k2*pi + arg(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + \ log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))))) + log(Abs(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + \ log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))))))) + log(Abs(I*(2*k2*pi + \ arg(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))))) + \ log(Abs(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d))))))))), \ ProductSet(S.Integers, S.Integers, S.Integers, S.Integers)))) def test__solveset_multi(): from sympy.solvers.solveset import _solveset_multi from sympy.sets import Reals # Basic univariate case: assert _solveset_multi([x**2-1], [x], [S.Reals]) == FiniteSet((1,), (-1,)) # Linear systems of two equations assert _solveset_multi([x+y, x+1], [x, y], [Reals, Reals]) == FiniteSet((-1, 1)) assert _solveset_multi([x+y, x+1], [y, x], [Reals, Reals]) == FiniteSet((1, -1)) assert _solveset_multi([x+y, x-y-1], [x, y], [Reals, Reals]) == FiniteSet((S(1)/2, -S(1)/2)) assert _solveset_multi([x-1, y-2], [x, y], [Reals, Reals]) == FiniteSet((1, 2)) # assert dumeq(_solveset_multi([x+y], [x, y], [Reals, Reals]), ImageSet(Lambda(x, (x, -x)), Reals)) assert dumeq(_solveset_multi([x+y], [x, y], [Reals, Reals]), Union( ImageSet(Lambda(((x,),), (x, -x)), ProductSet(Reals)), ImageSet(Lambda(((y,),), (-y, y)), ProductSet(Reals)))) assert _solveset_multi([x+y, x+y+1], [x, y], [Reals, Reals]) == S.EmptySet assert _solveset_multi([x+y, x-y, x-1], [x, y], [Reals, Reals]) == S.EmptySet assert _solveset_multi([x+y, x-y, x-1], [y, x], [Reals, Reals]) == S.EmptySet # Systems of three equations: assert _solveset_multi([x+y+z-1, x+y-z-2, x-y-z-3], [x, y, z], [Reals, Reals, Reals]) == FiniteSet((2, -S.Half, -S.Half)) # Nonlinear systems: from sympy.abc import theta assert _solveset_multi([x**2+y**2-2, x+y], [x, y], [Reals, Reals]) == FiniteSet((-1, 1), (1, -1)) assert _solveset_multi([x**2-1, y], [x, y], [Reals, Reals]) == FiniteSet((1, 0), (-1, 0)) #assert _solveset_multi([x**2-y**2], [x, y], [Reals, Reals]) == Union( # ImageSet(Lambda(x, (x, -x)), Reals), ImageSet(Lambda(x, (x, x)), Reals)) assert dumeq(_solveset_multi([x**2-y**2], [x, y], [Reals, Reals]), Union( ImageSet(Lambda(((x,),), (x, -Abs(x))), ProductSet(Reals)), ImageSet(Lambda(((x,),), (x, Abs(x))), ProductSet(Reals)), ImageSet(Lambda(((y,),), (-Abs(y), y)), ProductSet(Reals)), ImageSet(Lambda(((y,),), (Abs(y), y)), ProductSet(Reals)))) assert _solveset_multi([r*cos(theta)-1, r*sin(theta)], [theta, r], [Interval(0, pi), Interval(-1, 1)]) == FiniteSet((0, 1), (pi, -1)) assert _solveset_multi([r*cos(theta)-1, r*sin(theta)], [r, theta], [Interval(0, 1), Interval(0, pi)]) == FiniteSet((1, 0)) #assert _solveset_multi([r*cos(theta)-r, r*sin(theta)], [r, theta], # [Interval(0, 1), Interval(0, pi)]) == ? assert dumeq(_solveset_multi([r*cos(theta)-r, r*sin(theta)], [r, theta], [Interval(0, 1), Interval(0, pi)]), Union( ImageSet(Lambda(((r,),), (r, 0)), ImageSet(Lambda(r, (r,)), Interval(0, 1))), ImageSet(Lambda(((theta,),), (0, theta)), ImageSet(Lambda(theta, (theta,)), Interval(0, pi))))) def test_conditionset(): assert solveset(Eq(sin(x)**2 + cos(x)**2, 1), x, domain=S.Reals ) is S.Reals assert solveset(Eq(x**2 + x*sin(x), 1), x, domain=S.Reals ).dummy_eq(ConditionSet(x, Eq(x**2 + x*sin(x) - 1, 0), S.Reals)) assert dumeq(solveset(Eq(-I*(exp(I*x) - exp(-I*x))/2, 1), x ), imageset(Lambda(n, 2*n*pi + pi/2), S.Integers)) assert solveset(x + sin(x) > 1, x, domain=S.Reals ).dummy_eq(ConditionSet(x, x + sin(x) > 1, S.Reals)) assert solveset(Eq(sin(Abs(x)), x), x, domain=S.Reals ).dummy_eq(ConditionSet(x, Eq(-x + sin(Abs(x)), 0), S.Reals)) assert solveset(y**x-z, x, S.Reals ).dummy_eq(ConditionSet(x, Eq(y**x - z, 0), S.Reals)) @XFAIL def test_conditionset_equality(): ''' Checking equality of different representations of ConditionSet''' assert solveset(Eq(tan(x), y), x) == ConditionSet(x, Eq(tan(x), y), S.Complexes) def test_solveset_domain(): assert solveset(x**2 - x - 6, x, Interval(0, oo)) == FiniteSet(3) assert solveset(x**2 - 1, x, Interval(0, oo)) == FiniteSet(1) assert solveset(x**4 - 16, x, Interval(0, 10)) == FiniteSet(2) def test_improve_coverage(): solution = solveset(exp(x) + sin(x), x, S.Reals) unsolved_object = ConditionSet(x, Eq(exp(x) + sin(x), 0), S.Reals) assert solution.dummy_eq(unsolved_object) def test_issue_9522(): expr1 = Eq(1/(x**2 - 4) + x, 1/(x**2 - 4) + 2) expr2 = Eq(1/x + x, 1/x) assert solveset(expr1, x, S.Reals) is S.EmptySet assert solveset(expr2, x, S.Reals) is S.EmptySet def test_solvify(): assert solvify(x**2 + 10, x, S.Reals) == [] assert solvify(x**3 + 1, x, S.Complexes) == [-1, S.Half - sqrt(3)*I/2, S.Half + sqrt(3)*I/2] assert solvify(log(x), x, S.Reals) == [1] assert solvify(cos(x), x, S.Reals) == [pi/2, pi*Rational(3, 2)] assert solvify(sin(x) + 1, x, S.Reals) == [pi*Rational(3, 2)] raises(NotImplementedError, lambda: solvify(sin(exp(x)), x, S.Complexes)) def test_solvify_piecewise(): p1 = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True)) p2 = Piecewise((0, x < -10), (x**2 + 5*x - 6, x >= -9)) p3 = Piecewise((0, Eq(x, 0)), (x**2/Abs(x), True)) p4 = Piecewise((0, Eq(x, pi)), ((x - pi)/sin(x), True)) # issue 21079 assert solvify(p1, x, S.Reals) == [0] assert solvify(p2, x, S.Reals) == [-6, 1] assert solvify(p3, x, S.Reals) == [0] assert solvify(p4, x, S.Reals) == [pi] def test_abs_invert_solvify(): x = Symbol('x',positive=True) assert solvify(sin(Abs(x)), x, S.Reals) == [0, pi] x = Symbol('x') assert solvify(sin(Abs(x)), x, S.Reals) is None def test_linear_eq_to_matrix(): eqns1 = [2*x + y - 2*z - 3, x - y - z, x + y + 3*z - 12] eqns2 = [Eq(3*x + 2*y - z, 1), Eq(2*x - 2*y + 4*z, -2), -2*x + y - 2*z] A, B = linear_eq_to_matrix(eqns1, x, y, z) assert A == Matrix([[2, 1, -2], [1, -1, -1], [1, 1, 3]]) assert B == Matrix([[3], [0], [12]]) A, B = linear_eq_to_matrix(eqns2, x, y, z) assert A == Matrix([[3, 2, -1], [2, -2, 4], [-2, 1, -2]]) assert B == Matrix([[1], [-2], [0]]) # Pure symbolic coefficients eqns3 = [a*b*x + b*y + c*z - d, e*x + d*x + f*y + g*z - h, i*x + j*y + k*z - l] A, B = linear_eq_to_matrix(eqns3, x, y, z) assert A == Matrix([[a*b, b, c], [d + e, f, g], [i, j, k]]) assert B == Matrix([[d], [h], [l]]) # raise ValueError if # 1) no symbols are given raises(ValueError, lambda: linear_eq_to_matrix(eqns3)) # 2) there are duplicates raises(ValueError, lambda: linear_eq_to_matrix(eqns3, [x, x, y])) # 3) there are non-symbols raises(ValueError, lambda: linear_eq_to_matrix(eqns3, [x, 1/a, y])) # 4) a nonlinear term is detected in the original expression raises(NonlinearError, lambda: linear_eq_to_matrix(Eq(1/x + x, 1/x), [x])) assert linear_eq_to_matrix(1, x) == (Matrix([[0]]), Matrix([[-1]])) # issue 15195 assert linear_eq_to_matrix(x + y*(z*(3*x + 2) + 3), x) == ( Matrix([[3*y*z + 1]]), Matrix([[-y*(2*z + 3)]])) assert linear_eq_to_matrix(Matrix( [[a*x + b*y - 7], [5*x + 6*y - c]]), x, y) == ( Matrix([[a, b], [5, 6]]), Matrix([[7], [c]])) # issue 15312 assert linear_eq_to_matrix(Eq(x + 2, 1), x) == ( Matrix([[1]]), Matrix([[-1]])) def test_issue_16577(): assert linear_eq_to_matrix(Eq(a*(2*x + 3*y) + 4*y, 5), x, y) == ( Matrix([[2*a, 3*a + 4]]), Matrix([[5]])) def test_issue_10085(): assert invert_real(exp(x),0,x) == (x, S.EmptySet) def test_linsolve(): x1, x2, x3, x4 = symbols('x1, x2, x3, x4') # Test for different input forms M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]]) system1 = A, B = M[:, :-1], M[:, -1] Eqns = [x1 + 2*x2 + x3 + x4 - 7, x1 + 2*x2 + 2*x3 - x4 - 12, 2*x1 + 4*x2 + 6*x4 - 4] sol = FiniteSet((-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4)) assert linsolve(Eqns, (x1, x2, x3, x4)) == sol assert linsolve(Eqns, *(x1, x2, x3, x4)) == sol assert linsolve(system1, (x1, x2, x3, x4)) == sol assert linsolve(system1, *(x1, x2, x3, x4)) == sol # issue 9667 - symbols can be Dummy symbols x1, x2, x3, x4 = symbols('x:4', cls=Dummy) assert linsolve(system1, x1, x2, x3, x4) == FiniteSet( (-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4)) # raise ValueError for garbage value raises(ValueError, lambda: linsolve(Eqns)) raises(ValueError, lambda: linsolve(x1)) raises(ValueError, lambda: linsolve(x1, x2)) raises(ValueError, lambda: linsolve((A,), x1, x2)) raises(ValueError, lambda: linsolve(A, B, x1, x2)) #raise ValueError if equations are non-linear in given variables raises(NonlinearError, lambda: linsolve([x + y - 1, x ** 2 + y - 3], [x, y])) raises(NonlinearError, lambda: linsolve([cos(x) + y, x + y], [x, y])) assert linsolve([x + z - 1, x ** 2 + y - 3], [z, y]) == {(-x + 1, -x**2 + 3)} # Fully symbolic test A = Matrix([[a, b], [c, d]]) B = Matrix([[e], [g]]) system2 = (A, B) sol = FiniteSet(((-b*g + d*e)/(a*d - b*c), (a*g - c*e)/(a*d - b*c))) assert linsolve(system2, [x, y]) == sol # No solution A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]]) B = Matrix([0, 0, 1]) assert linsolve((A, B), (x, y, z)) is S.EmptySet # Issue #10056 A, B, J1, J2 = symbols('A B J1 J2') Augmatrix = Matrix([ [2*I*J1, 2*I*J2, -2/J1], [-2*I*J2, -2*I*J1, 2/J2], [0, 2, 2*I/(J1*J2)], [2, 0, 0], ]) assert linsolve(Augmatrix, A, B) == FiniteSet((0, I/(J1*J2))) # Issue #10121 - Assignment of free variables Augmatrix = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]]) assert linsolve(Augmatrix, a, b, c, d, e) == FiniteSet((a, 0, c, 0, e)) #raises(IndexError, lambda: linsolve(Augmatrix, a, b, c)) x0, x1, x2, _x0 = symbols('tau0 tau1 tau2 _tau0') assert linsolve(Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]]) ) == FiniteSet((x0, 0, x1, _x0, x2)) x0, x1, x2, _x0 = symbols('tau00 tau01 tau02 tau0') assert linsolve(Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]]) ) == FiniteSet((x0, 0, x1, _x0, x2)) x0, x1, x2, _x0 = symbols('tau00 tau01 tau02 tau1') assert linsolve(Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]]) ) == FiniteSet((x0, 0, x1, _x0, x2)) # symbols can be given as generators x0, x2, x4 = symbols('x0, x2, x4') assert linsolve(Augmatrix, numbered_symbols('x') ) == FiniteSet((x0, 0, x2, 0, x4)) Augmatrix[-1, -1] = x0 # use Dummy to avoid clash; the names may clash but the symbols # will not Augmatrix[-1, -1] = symbols('_x0') assert len(linsolve( Augmatrix, numbered_symbols('x', cls=Dummy)).free_symbols) == 4 # Issue #12604 f = Function('f') assert linsolve([f(x) - 5], f(x)) == FiniteSet((5,)) # Issue #14860 from sympy.physics.units import meter, newton, kilo kN = kilo*newton Eqns = [8*kN + x + y, 28*kN*meter + 3*x*meter] assert linsolve(Eqns, x, y) == { (kilo*newton*Rational(-28, 3), kN*Rational(4, 3))} # linsolve fully expands expressions, so removable singularities # and other nonlinearity does not raise an error assert linsolve([Eq(x, x + y)], [x, y]) == {(x, 0)} assert linsolve([Eq(1/x, 1/x + y)], [x, y]) == {(x, 0)} assert linsolve([Eq(y/x, y/x + y)], [x, y]) == {(x, 0)} assert linsolve([Eq(x*(x + 1), x**2 + y)], [x, y]) == {(y, y)} # corner cases # # XXX: The case below should give the same as for [0] # assert linsolve([], [x]) == {(x,)} assert linsolve([], [x]) is S.EmptySet assert linsolve([0], [x]) == {(x,)} assert linsolve([x], [x, y]) == {(0, y)} assert linsolve([x, 0], [x, y]) == {(0, y)} def test_linsolve_large_sparse(): # # This is mainly a performance test # def _mk_eqs_sol(n): xs = symbols('x:{}'.format(n)) ys = symbols('y:{}'.format(n)) syms = xs + ys eqs = [] sol = (-S.Half,) * n + (S.Half,) * n for xi, yi in zip(xs, ys): eqs.extend([xi + yi, xi - yi + 1]) return eqs, syms, FiniteSet(sol) n = 500 eqs, syms, sol = _mk_eqs_sol(n) assert linsolve(eqs, syms) == sol def test_linsolve_immutable(): A = ImmutableDenseMatrix([[1, 1, 2], [0, 1, 2], [0, 0, 1]]) B = ImmutableDenseMatrix([2, 1, -1]) assert linsolve([A, B], (x, y, z)) == FiniteSet((1, 3, -1)) A = ImmutableDenseMatrix([[1, 1, 7], [1, -1, 3]]) assert linsolve(A) == FiniteSet((5, 2)) def test_solve_decomposition(): n = Dummy('n') f1 = exp(3*x) - 6*exp(2*x) + 11*exp(x) - 6 f2 = sin(x)**2 - 2*sin(x) + 1 f3 = sin(x)**2 - sin(x) f4 = sin(x + 1) f5 = exp(x + 2) - 1 f6 = 1/log(x) f7 = 1/x s1 = ImageSet(Lambda(n, 2*n*pi), S.Integers) s2 = ImageSet(Lambda(n, 2*n*pi + pi), S.Integers) s3 = ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers) s4 = ImageSet(Lambda(n, 2*n*pi - 1), S.Integers) s5 = ImageSet(Lambda(n, 2*n*pi - 1 + pi), S.Integers) assert solve_decomposition(f1, x, S.Reals) == FiniteSet(0, log(2), log(3)) assert dumeq(solve_decomposition(f2, x, S.Reals), s3) assert dumeq(solve_decomposition(f3, x, S.Reals), Union(s1, s2, s3)) assert dumeq(solve_decomposition(f4, x, S.Reals), Union(s4, s5)) assert solve_decomposition(f5, x, S.Reals) == FiniteSet(-2) assert solve_decomposition(f6, x, S.Reals) == S.EmptySet assert solve_decomposition(f7, x, S.Reals) == S.EmptySet assert solve_decomposition(x, x, Interval(1, 2)) == S.EmptySet # nonlinsolve testcases def test_nonlinsolve_basic(): assert nonlinsolve([],[]) == S.EmptySet assert nonlinsolve([],[x, y]) == S.EmptySet system = [x, y - x - 5] assert nonlinsolve([x],[x, y]) == FiniteSet((0, y)) assert nonlinsolve(system, [y]) == FiniteSet((x + 5,)) soln = (ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers),) assert dumeq(nonlinsolve([sin(x) - 1], [x]), FiniteSet(tuple(soln))) assert nonlinsolve([x**2 - 1], [x]) == FiniteSet((-1,), (1,)) soln = FiniteSet((y, y)) assert nonlinsolve([x - y, 0], x, y) == soln assert nonlinsolve([0, x - y], x, y) == soln assert nonlinsolve([x - y, x - y], x, y) == soln assert nonlinsolve([x, 0], x, y) == FiniteSet((0, y)) f = Function('f') assert nonlinsolve([f(x), 0], f(x), y) == FiniteSet((0, y)) assert nonlinsolve([f(x), 0], f(x), f(y)) == FiniteSet((0, f(y))) A = Indexed('A', x) assert nonlinsolve([A, 0], A, y) == FiniteSet((0, y)) assert nonlinsolve([x**2 -1], [sin(x)]) == FiniteSet((S.EmptySet,)) assert nonlinsolve([x**2 -1], sin(x)) == FiniteSet((S.EmptySet,)) assert nonlinsolve([x**2 -1], 1) == FiniteSet((x**2,)) assert nonlinsolve([x**2 -1], x + y) == FiniteSet((S.EmptySet,)) assert nonlinsolve([Eq(1, x + y), Eq(1, -x + y - 1), Eq(1, -x + y - 1)], x, y) == FiniteSet( (-S.Half, 3*S.Half)) def test_nonlinsolve_abs(): soln = FiniteSet((y, y), (-y, y)) assert nonlinsolve([Abs(x) - y], x, y) == soln def test_raise_exception_nonlinsolve(): raises(IndexError, lambda: nonlinsolve([x**2 -1], [])) raises(ValueError, lambda: nonlinsolve([x**2 -1])) raises(NotImplementedError, lambda: nonlinsolve([(x+y)**2 - 9, x**2 - y**2 - 0.75], (x, y))) def test_trig_system(): # TODO: add more simple testcases when solveset returns # simplified soln for Trig eq assert nonlinsolve([sin(x) - 1, cos(x) -1 ], x) == S.EmptySet soln1 = (ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers),) soln = FiniteSet(soln1) assert dumeq(nonlinsolve([sin(x) - 1, cos(x)], x), soln) @XFAIL def test_trig_system_fail(): # fails because solveset trig solver is not much smart. sys = [x + y - pi/2, sin(x) + sin(y) - 1] # solveset returns conditionset for sin(x) + sin(y) - 1 soln_1 = (ImageSet(Lambda(n, n*pi + pi/2), S.Integers), ImageSet(Lambda(n, n*pi), S.Integers)) soln_1 = FiniteSet(soln_1) soln_2 = (ImageSet(Lambda(n, n*pi), S.Integers), ImageSet(Lambda(n, n*pi+ pi/2), S.Integers)) soln_2 = FiniteSet(soln_2) soln = soln_1 + soln_2 assert dumeq(nonlinsolve(sys, [x, y]), soln) # Add more cases from here # http://www.vitutor.com/geometry/trigonometry/equations_systems.html#uno sys = [sin(x) + sin(y) - (sqrt(3)+1)/2, sin(x) - sin(y) - (sqrt(3) - 1)/2] soln_x = Union(ImageSet(Lambda(n, 2*n*pi + pi/3), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi*Rational(2, 3)), S.Integers)) soln_y = Union(ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi*Rational(5, 6)), S.Integers)) assert dumeq(nonlinsolve(sys, [x, y]), FiniteSet((soln_x, soln_y))) def test_nonlinsolve_positive_dimensional(): x, y, a, b, c, d = symbols('x, y, a, b, c, d', extended_real=True) assert nonlinsolve([x*y, x*y - x], [x, y]) == FiniteSet((0, y)) system = [a**2 + a*c, a - b] assert nonlinsolve(system, [a, b]) == FiniteSet((0, 0), (-c, -c)) # here (a= 0, b = 0) is independent soln so both is printed. # if symbols = [a, b, c] then only {a : -c ,b : -c} eq1 = a + b + c + d eq2 = a*b + b*c + c*d + d*a eq3 = a*b*c + b*c*d + c*d*a + d*a*b eq4 = a*b*c*d - 1 system = [eq1, eq2, eq3, eq4] sol1 = (-1/d, -d, 1/d, FiniteSet(d) - FiniteSet(0)) sol2 = (1/d, -d, -1/d, FiniteSet(d) - FiniteSet(0)) soln = FiniteSet(sol1, sol2) assert nonlinsolve(system, [a, b, c, d]) == soln def test_nonlinsolve_polysys(): x, y = symbols('x, y', real=True) assert nonlinsolve([x**2 + y - 2, x**2 + y], [x, y]) == S.EmptySet s = (-y + 2, y) assert nonlinsolve([(x + y)**2 - 4, x + y - 2], [x, y]) == FiniteSet(s) system = [x**2 - y**2] soln_real = FiniteSet((-y, y), (y, y)) soln_complex = FiniteSet((-Abs(y), y), (Abs(y), y)) soln =soln_real + soln_complex assert nonlinsolve(system, [x, y]) == soln system = [x**2 - y**2] soln_real= FiniteSet((y, -y), (y, y)) soln_complex = FiniteSet((y, -Abs(y)), (y, Abs(y))) soln = soln_real + soln_complex assert nonlinsolve(system, [y, x]) == soln system = [x**2 + y - 3, x - y - 4] assert nonlinsolve(system, (x, y)) != nonlinsolve(system, (y, x)) def test_nonlinsolve_using_substitution(): x, y, z, n = symbols('x, y, z, n', real = True) system = [(x + y)*n - y**2 + 2] s_x = (n*y - y**2 + 2)/n soln = (-s_x, y) assert nonlinsolve(system, [x, y]) == FiniteSet(soln) system = [z**2*x**2 - z**2*y**2/exp(x)] soln_real_1 = (y, x, 0) soln_real_2 = (-exp(x/2)*Abs(x), x, z) soln_real_3 = (exp(x/2)*Abs(x), x, z) soln_complex_1 = (-x*exp(x/2), x, z) soln_complex_2 = (x*exp(x/2), x, z) syms = [y, x, z] soln = FiniteSet(soln_real_1, soln_complex_1, soln_complex_2,\ soln_real_2, soln_real_3) assert nonlinsolve(system,syms) == soln def test_nonlinsolve_complex(): n = Dummy('n') assert dumeq(nonlinsolve([exp(x) - sin(y), 1/y - 3], [x, y]), { (ImageSet(Lambda(n, 2*n*I*pi + log(sin(Rational(1, 3)))), S.Integers), Rational(1, 3))}) system = [exp(x) - sin(y), 1/exp(y) - 3] assert dumeq(nonlinsolve(system, [x, y]), { (ImageSet(Lambda(n, I*(2*n*pi + pi) + log(sin(log(3)))), S.Integers), -log(3)), (ImageSet(Lambda(n, I*(2*n*pi + arg(sin(2*n*I*pi - log(3)))) + log(Abs(sin(2*n*I*pi - log(3))))), S.Integers), ImageSet(Lambda(n, 2*n*I*pi - log(3)), S.Integers))}) system = [exp(x) - sin(y), y**2 - 4] assert dumeq(nonlinsolve(system, [x, y]), { (ImageSet(Lambda(n, I*(2*n*pi + pi) + log(sin(2))), S.Integers), -2), (ImageSet(Lambda(n, 2*n*I*pi + log(sin(2))), S.Integers), 2)}) @XFAIL def test_solve_nonlinear_trans(): # After the transcendental equation solver these will work x, y = symbols('x, y', real=True) soln1 = FiniteSet((2*LambertW(y/2), y)) soln2 = FiniteSet((-x*sqrt(exp(x)), y), (x*sqrt(exp(x)), y)) soln3 = FiniteSet((x*exp(x/2), x)) soln4 = FiniteSet(2*LambertW(y/2), y) assert nonlinsolve([x**2 - y**2/exp(x)], [x, y]) == soln1 assert nonlinsolve([x**2 - y**2/exp(x)], [y, x]) == soln2 assert nonlinsolve([x**2 - y**2/exp(x)], [y, x]) == soln3 assert nonlinsolve([x**2 - y**2/exp(x)], [x, y]) == soln4 def test_issue_14642(): x = Symbol('x') n1 = 0.5*x**3+x**2+0.5+I #add I in the Polynomials solution = solveset(n1, x) assert abs(solution.args[0] - (-2.28267560928153 - 0.312325580497716*I)) <= 1e-9 assert abs(solution.args[1] - (-0.297354141679308 + 1.01904778618762*I)) <= 1e-9 assert abs(solution.args[2] - (0.580029750960839 - 0.706722205689907*I)) <= 1e-9 # Symbolic n1 = S.Half*x**3+x**2+S.Half+I res = FiniteSet(-((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49) /2)/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*31985**(S(1)/4)* cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan( S(172)/49)/2)/2 + S(43)/2))/3)/3 - S(2)/3 - 4*cos(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)* 31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2))/3)/(3*((3* sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)/2)**2)**(S(1)/ 6)) + I*(-((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/ 2)/2)**2)**(S(1)/6)*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos( atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49) /2)/2 + S(43)/2))/3)/3 + 4*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)* cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172) /49)/2)/2 + S(43)/2))/3)/(3*((3*sqrt(3)*31985**(S(1)/4)*sin(atan( S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)* cos(atan(S(172)/49)/2)/2)**2)**(S(1)/6))), -S(2)/3 - sqrt(3)*((3* sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)/2)**2)**(S(1) /6)*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2) /2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)) /3)/6 - 4*re(1/((-S(1)/2 - sqrt(3)*I/2)*(S(43)/2 + 27*I + sqrt(-256 + (43 + 54*I)**2)/2)**(S(1)/3)))/3 + ((3*sqrt(3)*31985**(S(1)/4)*sin( atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)* cos(atan(S(172)/49)/2)/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)* 31985**(S(1)/4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)* sin(atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 + I*(-4*im(1/((-S(1)/2 - sqrt(3)*I/2)*(S(43)/2 + 27*I + sqrt(-256 + (43 + 54*I)**2)/2)**(S(1)/ 3)))/3 + ((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2) /2)**2)**(S(1)/6)*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan( S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 + sqrt(3)*((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/ 49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan( S(172)/49)/2)/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*31985**(S(1)/ 4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan( S(172)/49)/2)/2 + S(43)/2))/3)/6), -S(2)/3 - 4*re(1/((-S(1)/2 + sqrt(3)*I/2)*(S(43)/2 + 27*I + sqrt(-256 + (43 + 54*I)**2)/2)**(S(1) /3)))/3 + sqrt(3)*((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2) /2)**2)**(S(1)/6)*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan( S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 + ((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2) /2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan( S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 + I*(-sqrt(3)*((3*sqrt(3)*31985**(S(1)/4)*sin(atan( S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos( atan(S(172)/49)/2)/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*31985**( S(1)/4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin( atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 + ((3*sqrt(3)*31985**(S(1)/4)* sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)* cos(atan(S(172)/49)/2)/2)**2)**(S(1)/6)*sin(atan((27 + 3*sqrt(3)*31985**( S(1)/4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin( atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 - 4*im(1/((-S(1)/2 + sqrt(3)*I/2)* (S(43)/2 + 27*I + sqrt(-256 + (43 + 54*I)**2)/2)**(S(1)/3)))/3)) assert solveset(n1, x) == res def test_issue_13961(): V = (ax, bx, cx, gx, jx, lx, mx, nx, q) = symbols('ax bx cx gx jx lx mx nx q') S = (ax*q - lx*q - mx, ax - gx*q - lx, bx*q**2 + cx*q - jx*q - nx, q*(-ax*q + lx*q + mx), q*(-ax + gx*q + lx)) sol = FiniteSet((lx + mx/q, (-cx*q + jx*q + nx)/q**2, cx, mx/q**2, jx, lx, mx, nx, q), (lx + mx/q, (cx*q - jx*q - nx)/q**2*-1, cx, mx/q**2, jx, lx, mx, nx, q)) assert nonlinsolve(S, *V) == sol # The two solutions are in fact identical, so even better if only one is returned def test_issue_14541(): solutions = solveset(sqrt(-x**2 - 2.0), x) assert abs(solutions.args[0]+1.4142135623731*I) <= 1e-9 assert abs(solutions.args[1]-1.4142135623731*I) <= 1e-9 def test_issue_13396(): expr = -2*y*exp(-x**2 - y**2)*Abs(x) sol = FiniteSet(0) assert solveset(expr, y, domain=S.Reals) == sol # Related type of equation also solved here assert solveset(atan(x**2 - y**2)-pi/2, y, S.Reals) is S.EmptySet def test_issue_12032(): sol = FiniteSet(-sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))/2 + sqrt(Abs(-2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)) + 2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2/sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))))/2, -sqrt(Abs(-2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)) + 2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2/sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))))/2 - sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))/2, sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))/2 - I*sqrt(Abs(-2/sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) - 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)) + 2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))))/2, sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))/2 + I*sqrt(Abs(-2/sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) - 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)) + 2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1,3)))))/2) assert solveset(x**4 + x - 1, x) == sol def test_issue_10876(): assert solveset(1/sqrt(x), x) == S.EmptySet def test_issue_19050(): # test_issue_19050 --> TypeError removed assert dumeq(nonlinsolve([x + y, sin(y)], [x, y]), FiniteSet((ImageSet(Lambda(n, -2*n*pi), S.Integers), ImageSet(Lambda(n, 2*n*pi), S.Integers)),\ (ImageSet(Lambda(n, -2*n*pi - pi), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi), S.Integers)))) assert dumeq(nonlinsolve([x + y, sin(y) + cos(y)], [x, y]), FiniteSet((ImageSet(Lambda(n, -2*n*pi - 3*pi/4), S.Integers), ImageSet(Lambda(n, 2*n*pi + 3*pi/4), S.Integers)), \ (ImageSet(Lambda(n, -2*n*pi - 7*pi/4), S.Integers), ImageSet(Lambda(n, 2*n*pi + 7*pi/4), S.Integers)))) def test_issue_16618(): # AttributeError is removed ! eqn = [sin(x)*sin(y), cos(x)*cos(y) - 1] ans = FiniteSet((x, 2*n*pi), (2*n*pi, y), (x, 2*n*pi + pi), (2*n*pi + pi, y)) sol = nonlinsolve(eqn, [x, y]) for i0, j0 in zip(ordered(sol), ordered(ans)): assert len(i0) == len(j0) == 2 assert all(a.dummy_eq(b) for a, b in zip(i0, j0)) assert len(sol) == len(ans) def test_issue_17566(): assert nonlinsolve([32*(2**x)/2**(-y) - 4**y, 27*(3**x) - 1/3**y], x, y) ==\ FiniteSet((-log(81)/log(3), 1)) def test_issue_16643(): n = Dummy('n') assert solveset(x**2*sin(x), x).dummy_eq(Union(ImageSet(Lambda(n, 2*n*pi + pi), S.Integers), ImageSet(Lambda(n, 2*n*pi), S.Integers))) def test_issue_19587(): n,m = symbols('n m') assert nonlinsolve([32*2**m*2**n - 4**n, 27*3**m - 3**(-n)], m, n) ==\ FiniteSet((-log(81)/log(3), 1)) def test_issue_5132_1(): system = [sqrt(x**2 + y**2) - sqrt(10), x + y - 4] assert nonlinsolve(system, [x, y]) == FiniteSet((1, 3), (3, 1)) n = Dummy('n') eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3] s_real_y = -log(3) s_real_z = sqrt(-exp(2*x) - sin(log(3))) soln_real = FiniteSet((s_real_y, s_real_z), (s_real_y, -s_real_z)) lam = Lambda(n, 2*n*I*pi + -log(3)) s_complex_y = ImageSet(lam, S.Integers) lam = Lambda(n, sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3)))) s_complex_z_1 = ImageSet(lam, S.Integers) lam = Lambda(n, -sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3)))) s_complex_z_2 = ImageSet(lam, S.Integers) soln_complex = FiniteSet( (s_complex_y, s_complex_z_1), (s_complex_y, s_complex_z_2) ) soln = soln_real + soln_complex assert dumeq(nonlinsolve(eqs, [y, z]), soln) def test_issue_5132_2(): x, y = symbols('x, y', real=True) eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3] n = Dummy('n') soln_real = (log(-z**2 + sin(y))/2, z) lam = Lambda( n, I*(2*n*pi + arg(-z**2 + sin(y)))/2 + log(Abs(z**2 - sin(y)))/2) img = ImageSet(lam, S.Integers) # not sure about the complex soln. But it looks correct. soln_complex = (img, z) soln = FiniteSet(soln_real, soln_complex) assert dumeq(nonlinsolve(eqs, [x, z]), soln) system = [r - x**2 - y**2, tan(t) - y/x] s_x = sqrt(r/(tan(t)**2 + 1)) s_y = sqrt(r/(tan(t)**2 + 1))*tan(t) soln = FiniteSet((s_x, s_y), (-s_x, -s_y)) assert nonlinsolve(system, [x, y]) == soln def test_issue_6752(): a, b = symbols('a, b', real=True) assert nonlinsolve([a**2 + a, a - b], [a, b]) == {(-1, -1), (0, 0)} @SKIP("slow") def test_issue_5114_solveset(): # slow testcase from sympy.abc import o, p # there is no 'a' in the equation set but this is how the # problem was originally posed syms = [a, b, c, f, h, k, n] eqs = [b + r/d - c/d, c*(1/d + 1/e + 1/g) - f/g - r/d, f*(1/g + 1/i + 1/j) - c/g - h/i, h*(1/i + 1/l + 1/m) - f/i - k/m, k*(1/m + 1/o + 1/p) - h/m - n/p, n*(1/p + 1/q) - k/p] assert len(nonlinsolve(eqs, syms)) == 1 @SKIP("Hangs") def _test_issue_5335(): # Not able to check zero dimensional system. # is_zero_dimensional Hangs lam, a0, conc = symbols('lam a0 conc') eqs = [lam + 2*y - a0*(1 - x/2)*x - 0.005*x/2*x, a0*(1 - x/2)*x - 1*y - 0.743436700916726*y, x + y - conc] sym = [x, y, a0] # there are 4 solutions but only two are valid assert len(nonlinsolve(eqs, sym)) == 2 # float eqs = [lam + 2*y - a0*(1 - x/2)*x - 0.005*x/2*x, a0*(1 - x/2)*x - 1*y - 0.743436700916726*y, x + y - conc] sym = [x, y, a0] assert len(nonlinsolve(eqs, sym)) == 2 def test_issue_2777(): # the equations represent two circles x, y = symbols('x y', real=True) e1, e2 = sqrt(x**2 + y**2) - 10, sqrt(y**2 + (-x + 10)**2) - 3 a, b = Rational(191, 20), 3*sqrt(391)/20 ans = {(a, -b), (a, b)} assert nonlinsolve((e1, e2), (x, y)) == ans assert nonlinsolve((e1, e2/(x - a)), (x, y)) == S.EmptySet # make the 2nd circle's radius be -3 e2 += 6 assert nonlinsolve((e1, e2), (x, y)) == S.EmptySet def test_issue_8828(): x1 = 0 y1 = -620 r1 = 920 x2 = 126 y2 = 276 x3 = 51 y3 = 205 r3 = 104 v = [x, y, z] f1 = (x - x1)**2 + (y - y1)**2 - (r1 - z)**2 f2 = (x2 - x)**2 + (y2 - y)**2 - z**2 f3 = (x - x3)**2 + (y - y3)**2 - (r3 - z)**2 F = [f1, f2, f3] g1 = sqrt((x - x1)**2 + (y - y1)**2) + z - r1 g2 = f2 g3 = sqrt((x - x3)**2 + (y - y3)**2) + z - r3 G = [g1, g2, g3] # both soln same A = nonlinsolve(F, v) B = nonlinsolve(G, v) assert A == B def test_nonlinsolve_conditionset(): # when solveset failed to solve all the eq # return conditionset f = Function('f') f1 = f(x) - pi/2 f2 = f(y) - pi*Rational(3, 2) intermediate_system = Eq(2*f(x) - pi, 0) & Eq(2*f(y) - 3*pi, 0) syms = Tuple(x, y) soln = ConditionSet( syms, intermediate_system, S.Complexes**2) assert nonlinsolve([f1, f2], [x, y]) == soln def test_substitution_basic(): assert substitution([], [x, y]) == S.EmptySet assert substitution([], []) == S.EmptySet system = [2*x**2 + 3*y**2 - 30, 3*x**2 - 2*y**2 - 19] soln = FiniteSet((-3, -2), (-3, 2), (3, -2), (3, 2)) assert substitution(system, [x, y]) == soln soln = FiniteSet((-1, 1)) assert substitution([x + y], [x], [{y: 1}], [y], set(), [x, y]) == soln assert substitution( [x + y], [x], [{y: 1}], [y], {x + 1}, [y, x]) == S.EmptySet def test_issue_5132_substitution(): x, y, z, r, t = symbols('x, y, z, r, t', real=True) system = [r - x**2 - y**2, tan(t) - y/x] s_x_1 = Complement(FiniteSet(-sqrt(r/(tan(t)**2 + 1))), FiniteSet(0)) s_x_2 = Complement(FiniteSet(sqrt(r/(tan(t)**2 + 1))), FiniteSet(0)) s_y = sqrt(r/(tan(t)**2 + 1))*tan(t) soln = FiniteSet((s_x_2, s_y)) + FiniteSet((s_x_1, -s_y)) assert substitution(system, [x, y]) == soln n = Dummy('n') eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3] s_real_y = -log(3) s_real_z = sqrt(-exp(2*x) - sin(log(3))) soln_real = FiniteSet((s_real_y, s_real_z), (s_real_y, -s_real_z)) lam = Lambda(n, 2*n*I*pi + -log(3)) s_complex_y = ImageSet(lam, S.Integers) lam = Lambda(n, sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3)))) s_complex_z_1 = ImageSet(lam, S.Integers) lam = Lambda(n, -sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3)))) s_complex_z_2 = ImageSet(lam, S.Integers) soln_complex = FiniteSet( (s_complex_y, s_complex_z_1), (s_complex_y, s_complex_z_2)) soln = soln_real + soln_complex assert dumeq(substitution(eqs, [y, z]), soln) def test_raises_substitution(): raises(ValueError, lambda: substitution([x**2 -1], [])) raises(TypeError, lambda: substitution([x**2 -1])) raises(ValueError, lambda: substitution([x**2 -1], [sin(x)])) raises(TypeError, lambda: substitution([x**2 -1], x)) raises(TypeError, lambda: substitution([x**2 -1], 1)) def test_issue_21022(): from sympy.core.sympify import sympify eqs = [ 'k-16', 'p-8', 'y*y+z*z-x*x', 'd - x + p', 'd*d+k*k-y*y', 'z*z-p*p-k*k', 'abc-efg', ] efg = Symbol('efg') eqs = [sympify(x) for x in eqs] syb = list(ordered(set.union(*[x.free_symbols for x in eqs]))) res = nonlinsolve(eqs, syb) ans = FiniteSet( (efg, sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16), efg, 16, 8, 8 + sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16), sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16, -8*sqrt(5)), (efg, sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16), efg, 16, 8, 8 + sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16), sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16, 8*sqrt(5)), (efg, -sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16), efg, 16, 8, -sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16) + 8, sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16, -8*sqrt(5)), (efg, -sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16), efg, 16, 8, -sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16) + 8, sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16, 8*sqrt(5)) ) assert len(res) == len(ans) == 4 assert res == ans for result in res.args: assert len(result) == 8 def test_issue_17940(): n = Dummy('n') k1 = Dummy('k1') sol = ImageSet(Lambda(((k1, n),), I*(2*k1*pi + arg(2*n*I*pi + log(5))) + log(Abs(2*n*I*pi + log(5)))), ProductSet(S.Integers, S.Integers)) assert solveset(exp(exp(x)) - 5, x).dummy_eq(sol) def test_issue_17906(): assert solveset(7**(x**2 - 80) - 49**x, x) == FiniteSet(-8, 10) def test_issue_17933(): eq1 = x*sin(45) - y*cos(q) eq2 = x*cos(45) - y*sin(q) eq3 = 9*x*sin(45)/10 + y*cos(q) eq4 = 9*x*cos(45)/10 + y*sin(z) - z assert nonlinsolve([eq1, eq2, eq3, eq4], x, y, z, q) ==\ FiniteSet((0, 0, 0, q)) def test_issue_14565(): # removed redundancy assert dumeq(nonlinsolve([k + m, k + m*exp(-2*pi*k)], [k, m]) , FiniteSet((-n*I, ImageSet(Lambda(n, n*I), S.Integers)))) # end of tests for nonlinsolve def test_issue_9556(): b = Symbol('b', positive=True) assert solveset(Abs(x) + 1, x, S.Reals) is S.EmptySet assert solveset(Abs(x) + b, x, S.Reals) is S.EmptySet assert solveset(Eq(b, -1), b, S.Reals) is S.EmptySet def test_issue_9611(): assert solveset(Eq(x - x + a, a), x, S.Reals) == S.Reals assert solveset(Eq(y - y + a, a), y) == S.Complexes def test_issue_9557(): assert solveset(x**2 + a, x, S.Reals) == Intersection(S.Reals, FiniteSet(-sqrt(-a), sqrt(-a))) def test_issue_9778(): x = Symbol('x', real=True) y = Symbol('y', real=True) assert solveset(x**3 + 1, x, S.Reals) == FiniteSet(-1) assert solveset(x**Rational(3, 5) + 1, x, S.Reals) == S.EmptySet assert solveset(x**3 + y, x, S.Reals) == \ FiniteSet(-Abs(y)**Rational(1, 3)*sign(y)) def test_issue_10214(): assert solveset(x**Rational(3, 2) + 4, x, S.Reals) == S.EmptySet assert solveset(x**(Rational(-3, 2)) + 4, x, S.Reals) == S.EmptySet ans = FiniteSet(-2**Rational(2, 3)) assert solveset(x**(S(3)) + 4, x, S.Reals) == ans assert (x**(S(3)) + 4).subs(x,list(ans)[0]) == 0 # substituting ans and verifying the result. assert (x**(S(3)) + 4).subs(x,-(-2)**Rational(2, 3)) == 0 def test_issue_9849(): assert solveset(Abs(sin(x)) + 1, x, S.Reals) == S.EmptySet def test_issue_9953(): assert linsolve([ ], x) == S.EmptySet def test_issue_9913(): assert solveset(2*x + 1/(x - 10)**2, x, S.Reals) == \ FiniteSet(-(3*sqrt(24081)/4 + Rational(4027, 4))**Rational(1, 3)/3 - 100/ (3*(3*sqrt(24081)/4 + Rational(4027, 4))**Rational(1, 3)) + Rational(20, 3)) def test_issue_10397(): assert solveset(sqrt(x), x, S.Complexes) == FiniteSet(0) def test_issue_14987(): raises(ValueError, lambda: linear_eq_to_matrix( [x**2], x)) raises(ValueError, lambda: linear_eq_to_matrix( [x*(-3/x + 1) + 2*y - a], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [(x**2 - 3*x)/(x - 3) - 3], x)) raises(ValueError, lambda: linear_eq_to_matrix( [(x + 1)**3 - x**3 - 3*x**2 + 7], x)) raises(ValueError, lambda: linear_eq_to_matrix( [x*(1/x + 1) + y], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [(x + 1)*y], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [Eq(1/x, 1/x + y)], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [Eq(y/x, y/x + y)], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [Eq(x*(x + 1), x**2 + y)], [x, y])) def test_simplification(): eq = x + (a - b)/(-2*a + 2*b) assert solveset(eq, x) == FiniteSet(S.Half) assert solveset(eq, x, S.Reals) == Intersection({-((a - b)/(-2*a + 2*b))}, S.Reals) # So that ap - bn is not zero: ap = Symbol('ap', positive=True) bn = Symbol('bn', negative=True) eq = x + (ap - bn)/(-2*ap + 2*bn) assert solveset(eq, x) == FiniteSet(S.Half) assert solveset(eq, x, S.Reals) == FiniteSet(S.Half) def test_integer_domain_relational(): eq1 = 2*x + 3 > 0 eq2 = x**2 + 3*x - 2 >= 0 eq3 = x + 1/x > -2 + 1/x eq4 = x + sqrt(x**2 - 5) > 0 eq = x + 1/x > -2 + 1/x eq5 = eq.subs(x,log(x)) eq6 = log(x)/x <= 0 eq7 = log(x)/x < 0 eq8 = x/(x-3) < 3 eq9 = x/(x**2-3) < 3 assert solveset(eq1, x, S.Integers) == Range(-1, oo, 1) assert solveset(eq2, x, S.Integers) == Union(Range(-oo, -3, 1), Range(1, oo, 1)) assert solveset(eq3, x, S.Integers) == Union(Range(-1, 0, 1), Range(1, oo, 1)) assert solveset(eq4, x, S.Integers) == Range(3, oo, 1) assert solveset(eq5, x, S.Integers) == Range(2, oo, 1) assert solveset(eq6, x, S.Integers) == Range(1, 2, 1) assert solveset(eq7, x, S.Integers) == S.EmptySet assert solveset(eq8, x, domain=Range(0,5)) == Range(0, 3, 1) assert solveset(eq9, x, domain=Range(0,5)) == Union(Range(0, 2, 1), Range(2, 5, 1)) # test_issue_19794 assert solveset(x + 2 < 0, x, S.Integers) == Range(-oo, -2, 1) def test_issue_10555(): f = Function('f') g = Function('g') assert solveset(f(x) - pi/2, x, S.Reals).dummy_eq( ConditionSet(x, Eq(f(x) - pi/2, 0), S.Reals)) assert solveset(f(g(x)) - pi/2, g(x), S.Reals).dummy_eq( ConditionSet(g(x), Eq(f(g(x)) - pi/2, 0), S.Reals)) def test_issue_8715(): eq = x + 1/x > -2 + 1/x assert solveset(eq, x, S.Reals) == \ (Interval.open(-2, oo) - FiniteSet(0)) assert solveset(eq.subs(x,log(x)), x, S.Reals) == \ Interval.open(exp(-2), oo) - FiniteSet(1) def test_issue_11174(): eq = z**2 + exp(2*x) - sin(y) soln = Intersection(S.Reals, FiniteSet(log(-z**2 + sin(y))/2)) assert solveset(eq, x, S.Reals) == soln eq = sqrt(r)*Abs(tan(t))/sqrt(tan(t)**2 + 1) + x*tan(t) s = -sqrt(r)*Abs(tan(t))/(sqrt(tan(t)**2 + 1)*tan(t)) soln = Intersection(S.Reals, FiniteSet(s)) assert solveset(eq, x, S.Reals) == soln def test_issue_11534(): # eq and eq2 should give the same solution as a Complement x = Symbol('x', real=True) y = Symbol('y', real=True) eq = -y + x/sqrt(-x**2 + 1) eq2 = -y**2 + x**2/(-x**2 + 1) soln = Complement(FiniteSet(-y/sqrt(y**2 + 1), y/sqrt(y**2 + 1)), FiniteSet(-1, 1)) assert solveset(eq, x, S.Reals) == soln assert solveset(eq2, x, S.Reals) == soln def test_issue_10477(): assert solveset((x**2 + 4*x - 3)/x < 2, x, S.Reals) == \ Union(Interval.open(-oo, -3), Interval.open(0, 1)) def test_issue_10671(): assert solveset(sin(y), y, Interval(0, pi)) == FiniteSet(0, pi) i = Interval(1, 10) assert solveset((1/x).diff(x) < 0, x, i) == i def test_issue_11064(): eq = x + sqrt(x**2 - 5) assert solveset(eq > 0, x, S.Reals) == \ Interval(sqrt(5), oo) assert solveset(eq < 0, x, S.Reals) == \ Interval(-oo, -sqrt(5)) assert solveset(eq > sqrt(5), x, S.Reals) == \ Interval.Lopen(sqrt(5), oo) def test_issue_12478(): eq = sqrt(x - 2) + 2 soln = solveset_real(eq, x) assert soln is S.EmptySet assert solveset(eq < 0, x, S.Reals) is S.EmptySet assert solveset(eq > 0, x, S.Reals) == Interval(2, oo) def test_issue_12429(): eq = solveset(log(x)/x <= 0, x, S.Reals) sol = Interval.Lopen(0, 1) assert eq == sol def test_issue_19506(): eq = arg(x + I) C = Dummy('C') assert solveset(eq).dummy_eq(Intersection(ConditionSet(C, Eq(im(C) + 1, 0), S.Complexes), ConditionSet(C, re(C) > 0, S.Complexes))) def test_solveset_arg(): assert solveset(arg(x), x, S.Reals) == Interval.open(0, oo) assert solveset(arg(4*x -3), x, S.Reals) == Interval.open(Rational(3, 4), oo) def test__is_finite_with_finite_vars(): f = _is_finite_with_finite_vars # issue 12482 assert all(f(1/x) is None for x in ( Dummy(), Dummy(real=True), Dummy(complex=True))) assert f(1/Dummy(real=False)) is True # b/c it's finite but not 0 def test_issue_13550(): assert solveset(x**2 - 2*x - 15, symbol = x, domain = Interval(-oo, 0)) == FiniteSet(-3) def test_issue_13849(): assert nonlinsolve((t*(sqrt(5) + sqrt(2)) - sqrt(2), t), t) is S.EmptySet def test_issue_14223(): assert solveset((Abs(x + Min(x, 2)) - 2).rewrite(Piecewise), x, S.Reals) == FiniteSet(-1, 1) assert solveset((Abs(x + Min(x, 2)) - 2).rewrite(Piecewise), x, Interval(0, 2)) == FiniteSet(1) assert solveset(x, x, FiniteSet(1, 2)) is S.EmptySet def test_issue_10158(): dom = S.Reals assert solveset(x*Max(x, 15) - 10, x, dom) == FiniteSet(Rational(2, 3)) assert solveset(x*Min(x, 15) - 10, x, dom) == FiniteSet(-sqrt(10), sqrt(10)) assert solveset(Max(Abs(x - 3) - 1, x + 2) - 3, x, dom) == FiniteSet(-1, 1) assert solveset(Abs(x - 1) - Abs(y), x, dom) == FiniteSet(-Abs(y) + 1, Abs(y) + 1) assert solveset(Abs(x + 4*Abs(x + 1)), x, dom) == FiniteSet(Rational(-4, 3), Rational(-4, 5)) assert solveset(2*Abs(x + Abs(x + Max(3, x))) - 2, x, S.Reals) == FiniteSet(-1, -2) dom = S.Complexes raises(ValueError, lambda: solveset(x*Max(x, 15) - 10, x, dom)) raises(ValueError, lambda: solveset(x*Min(x, 15) - 10, x, dom)) raises(ValueError, lambda: solveset(Max(Abs(x - 3) - 1, x + 2) - 3, x, dom)) raises(ValueError, lambda: solveset(Abs(x - 1) - Abs(y), x, dom)) raises(ValueError, lambda: solveset(Abs(x + 4*Abs(x + 1)), x, dom)) def test_issue_14300(): f = 1 - exp(-18000000*x) - y a1 = FiniteSet(-log(-y + 1)/18000000) assert solveset(f, x, S.Reals) == \ Intersection(S.Reals, a1) assert dumeq(solveset(f, x), ImageSet(Lambda(n, -I*(2*n*pi + arg(-y + 1))/18000000 - log(Abs(y - 1))/18000000), S.Integers)) def test_issue_14454(): number = CRootOf(x**4 + x - 1, 2) raises(ValueError, lambda: invert_real(number, 0, x)) assert invert_real(x**2, number, x) # no error def test_issue_17882(): assert solveset(-8*x**2/(9*(x**2 - 1)**(S(4)/3)) + 4/(3*(x**2 - 1)**(S(1)/3)), x, S.Complexes) == \ FiniteSet(sqrt(3), -sqrt(3)) def test_term_factors(): assert list(_term_factors(3**x - 2)) == [-2, 3**x] expr = 4**(x + 1) + 4**(x + 2) + 4**(x - 1) - 3**(x + 2) - 3**(x + 3) assert set(_term_factors(expr)) == { 3**(x + 2), 4**(x + 2), 3**(x + 3), 4**(x - 1), -1, 4**(x + 1)} #################### tests for transolve and its helpers ############### def test_transolve(): assert _transolve(3**x, x, S.Reals) == S.EmptySet assert _transolve(3**x - 9**(x + 5), x, S.Reals) == FiniteSet(-10) def test_issue_21276(): eq = (2*x*(y - z) - y*erf(y - z) - y + z*erf(y - z) + z)**2 assert solveset(eq.expand(), y) == FiniteSet(z, z + erfinv(2*x - 1)) # exponential tests def test_exponential_real(): from sympy.abc import y e1 = 3**(2*x) - 2**(x + 3) e2 = 4**(5 - 9*x) - 8**(2 - x) e3 = 2**x + 4**x e4 = exp(log(5)*x) - 2**x e5 = exp(x/y)*exp(-z/y) - 2 e6 = 5**(x/2) - 2**(x/3) e7 = 4**(x + 1) + 4**(x + 2) + 4**(x - 1) - 3**(x + 2) - 3**(x + 3) e8 = -9*exp(-2*x + 5) + 4*exp(3*x + 1) e9 = 2**x + 4**x + 8**x - 84 e10 = 29*2**(x + 1)*615**(x) - 123*2726**(x) assert solveset(e1, x, S.Reals) == FiniteSet( -3*log(2)/(-2*log(3) + log(2))) assert solveset(e2, x, S.Reals) == FiniteSet(Rational(4, 15)) assert solveset(e3, x, S.Reals) == S.EmptySet assert solveset(e4, x, S.Reals) == FiniteSet(0) assert solveset(e5, x, S.Reals) == Intersection( S.Reals, FiniteSet(y*log(2*exp(z/y)))) assert solveset(e6, x, S.Reals) == FiniteSet(0) assert solveset(e7, x, S.Reals) == FiniteSet(2) assert solveset(e8, x, S.Reals) == FiniteSet(-2*log(2)/5 + 2*log(3)/5 + Rational(4, 5)) assert solveset(e9, x, S.Reals) == FiniteSet(2) assert solveset(e10,x, S.Reals) == FiniteSet((-log(29) - log(2) + log(123))/(-log(2726) + log(2) + log(615))) assert solveset_real(-9*exp(-2*x + 5) + 2**(x + 1), x) == FiniteSet( -((-5 - 2*log(3) + log(2))/(log(2) + 2))) assert solveset_real(4**(x/2) - 2**(x/3), x) == FiniteSet(0) b = sqrt(6)*sqrt(log(2))/sqrt(log(5)) assert solveset_real(5**(x/2) - 2**(3/x), x) == FiniteSet(-b, b) # coverage test C1, C2 = symbols('C1 C2') f = Function('f') assert solveset_real(C1 + C2/x**2 - exp(-f(x)), f(x)) == Intersection( S.Reals, FiniteSet(-log(C1 + C2/x**2))) y = symbols('y', positive=True) assert solveset_real(x**2 - y**2/exp(x), y) == Intersection( S.Reals, FiniteSet(-sqrt(x**2*exp(x)), sqrt(x**2*exp(x)))) p = Symbol('p', positive=True) assert solveset_real((1/p + 1)**(p + 1), p).dummy_eq( ConditionSet(x, Eq((1 + 1/x)**(x + 1), 0), S.Reals)) @XFAIL def test_exponential_complex(): n = Dummy('n') assert dumeq(solveset_complex(2**x + 4**x, x),imageset( Lambda(n, I*(2*n*pi + pi)/log(2)), S.Integers)) assert solveset_complex(x**z*y**z - 2, z) == FiniteSet( log(2)/(log(x) + log(y))) assert dumeq(solveset_complex(4**(x/2) - 2**(x/3), x), imageset( Lambda(n, 3*n*I*pi/log(2)), S.Integers)) assert dumeq(solveset(2**x + 32, x), imageset( Lambda(n, (I*(2*n*pi + pi) + 5*log(2))/log(2)), S.Integers)) eq = (2**exp(y**2/x) + 2)/(x**2 + 15) a = sqrt(x)*sqrt(-log(log(2)) + log(log(2) + 2*n*I*pi)) assert solveset_complex(eq, y) == FiniteSet(-a, a) union1 = imageset(Lambda(n, I*(2*n*pi - pi*Rational(2, 3))/log(2)), S.Integers) union2 = imageset(Lambda(n, I*(2*n*pi + pi*Rational(2, 3))/log(2)), S.Integers) assert dumeq(solveset(2**x + 4**x + 8**x, x), Union(union1, union2)) eq = 4**(x + 1) + 4**(x + 2) + 4**(x - 1) - 3**(x + 2) - 3**(x + 3) res = solveset(eq, x) num = 2*n*I*pi - 4*log(2) + 2*log(3) den = -2*log(2) + log(3) ans = imageset(Lambda(n, num/den), S.Integers) assert dumeq(res, ans) def test_expo_conditionset(): f1 = (exp(x) + 1)**x - 2 f2 = (x + 2)**y*x - 3 f3 = 2**x - exp(x) - 3 f4 = log(x) - exp(x) f5 = 2**x + 3**x - 5**x assert solveset(f1, x, S.Reals).dummy_eq(ConditionSet( x, Eq((exp(x) + 1)**x - 2, 0), S.Reals)) assert solveset(f2, x, S.Reals).dummy_eq(ConditionSet( x, Eq(x*(x + 2)**y - 3, 0), S.Reals)) assert solveset(f3, x, S.Reals).dummy_eq(ConditionSet( x, Eq(2**x - exp(x) - 3, 0), S.Reals)) assert solveset(f4, x, S.Reals).dummy_eq(ConditionSet( x, Eq(-exp(x) + log(x), 0), S.Reals)) assert solveset(f5, x, S.Reals).dummy_eq(ConditionSet( x, Eq(2**x + 3**x - 5**x, 0), S.Reals)) def test_exponential_symbols(): x, y, z = symbols('x y z', positive=True) xr, zr = symbols('xr, zr', real=True) assert solveset(z**x - y, x, S.Reals) == Intersection( S.Reals, FiniteSet(log(y)/log(z))) f1 = 2*x**w - 4*y**w f2 = (x/y)**w - 2 sol1 = Intersection({log(2)/(log(x) - log(y))}, S.Reals) sol2 = Intersection({log(2)/log(x/y)}, S.Reals) assert solveset(f1, w, S.Reals) == sol1, solveset(f1, w, S.Reals) assert solveset(f2, w, S.Reals) == sol2, solveset(f2, w, S.Reals) assert solveset(x**x, x, Interval.Lopen(0,oo)).dummy_eq( ConditionSet(w, Eq(w**w, 0), Interval.open(0, oo))) assert solveset(x**y - 1, y, S.Reals) == FiniteSet(0) assert solveset(exp(x/y)*exp(-z/y) - 2, y, S.Reals) == \ Complement(ConditionSet(y, Eq(im(x)/y, 0) & Eq(im(z)/y, 0), \ Complement(Intersection(FiniteSet((x - z)/log(2)), S.Reals), FiniteSet(0))), FiniteSet(0)) assert solveset(exp(xr/y)*exp(-zr/y) - 2, y, S.Reals) == \ Complement(FiniteSet((xr - zr)/log(2)), FiniteSet(0)) assert solveset(a**x - b**x, x).dummy_eq(ConditionSet( w, Ne(a, 0) & Ne(b, 0), FiniteSet(0))) def test_ignore_assumptions(): # make sure assumptions are ignored xpos = symbols('x', positive=True) x = symbols('x') assert solveset_complex(xpos**2 - 4, xpos ) == solveset_complex(x**2 - 4, x) @XFAIL def test_issue_10864(): assert solveset(x**(y*z) - x, x, S.Reals) == FiniteSet(1) @XFAIL def test_solve_only_exp_2(): assert solveset_real(sqrt(exp(x)) + sqrt(exp(-x)) - 4, x) == \ FiniteSet(2*log(-sqrt(3) + 2), 2*log(sqrt(3) + 2)) def test_is_exponential(): assert _is_exponential(y, x) is False assert _is_exponential(3**x - 2, x) is True assert _is_exponential(5**x - 7**(2 - x), x) is True assert _is_exponential(sin(2**x) - 4*x, x) is False assert _is_exponential(x**y - z, y) is True assert _is_exponential(x**y - z, x) is False assert _is_exponential(2**x + 4**x - 1, x) is True assert _is_exponential(x**(y*z) - x, x) is False assert _is_exponential(x**(2*x) - 3**x, x) is False assert _is_exponential(x**y - y*z, y) is False assert _is_exponential(x**y - x*z, y) is True def test_solve_exponential(): assert _solve_exponential(3**(2*x) - 2**(x + 3), 0, x, S.Reals) == \ FiniteSet(-3*log(2)/(-2*log(3) + log(2))) assert _solve_exponential(2**y + 4**y, 1, y, S.Reals) == \ FiniteSet(log(Rational(-1, 2) + sqrt(5)/2)/log(2)) assert _solve_exponential(2**y + 4**y, 0, y, S.Reals) == \ S.EmptySet assert _solve_exponential(2**x + 3**x - 5**x, 0, x, S.Reals) == \ ConditionSet(x, Eq(2**x + 3**x - 5**x, 0), S.Reals) # end of exponential tests # logarithmic tests def test_logarithmic(): assert solveset_real(log(x - 3) + log(x + 3), x) == FiniteSet( -sqrt(10), sqrt(10)) assert solveset_real(log(x + 1) - log(2*x - 1), x) == FiniteSet(2) assert solveset_real(log(x + 3) + log(1 + 3/x) - 3, x) == FiniteSet( -3 + sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 + exp(3)/2, -sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 - 3 + exp(3)/2) eq = z - log(x) + log(y/(x*(-1 + y**2/x**2))) assert solveset_real(eq, x) == \ Intersection(S.Reals, FiniteSet(-sqrt(y**2 - y*exp(z)), sqrt(y**2 - y*exp(z)))) - \ Intersection(S.Reals, FiniteSet(-sqrt(y**2), sqrt(y**2))) assert solveset_real( log(3*x) - log(-x + 1) - log(4*x + 1), x) == FiniteSet(Rational(-1, 2), S.Half) assert solveset(log(x**y) - y*log(x), x, S.Reals) == S.Reals @XFAIL def test_uselogcombine_2(): eq = log(exp(2*x) + 1) + log(-tanh(x) + 1) - log(2) assert solveset_real(eq, x) is S.EmptySet eq = log(8*x) - log(sqrt(x) + 1) - 2 assert solveset_real(eq, x) is S.EmptySet def test_is_logarithmic(): assert _is_logarithmic(y, x) is False assert _is_logarithmic(log(x), x) is True assert _is_logarithmic(log(x) - 3, x) is True assert _is_logarithmic(log(x)*log(y), x) is True assert _is_logarithmic(log(x)**2, x) is False assert _is_logarithmic(log(x - 3) + log(x + 3), x) is True assert _is_logarithmic(log(x**y) - y*log(x), x) is True assert _is_logarithmic(sin(log(x)), x) is False assert _is_logarithmic(x + y, x) is False assert _is_logarithmic(log(3*x) - log(1 - x) + 4, x) is True assert _is_logarithmic(log(x) + log(y) + x, x) is False assert _is_logarithmic(log(log(x - 3)) + log(x - 3), x) is True assert _is_logarithmic(log(log(3) + x) + log(x), x) is True assert _is_logarithmic(log(x)*(y + 3) + log(x), y) is False def test_solve_logarithm(): y = Symbol('y') assert _solve_logarithm(log(x**y) - y*log(x), 0, x, S.Reals) == S.Reals y = Symbol('y', positive=True) assert _solve_logarithm(log(x)*log(y), 0, x, S.Reals) == FiniteSet(1) # end of logarithmic tests # lambert tests def test_is_lambert(): a, b, c = symbols('a,b,c') assert _is_lambert(x**2, x) is False assert _is_lambert(a**x**2+b*x+c, x) is True assert _is_lambert(E**2, x) is False assert _is_lambert(x*E**2, x) is False assert _is_lambert(3*log(x) - x*log(3), x) is True assert _is_lambert(log(log(x - 3)) + log(x-3), x) is True assert _is_lambert(5*x - 1 + 3*exp(2 - 7*x), x) is True assert _is_lambert((a/x + exp(x/2)).diff(x, 2), x) is True assert _is_lambert((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x) is True assert _is_lambert(x*sinh(x) - 1, x) is True assert _is_lambert(x*cos(x) - 5, x) is True assert _is_lambert(tanh(x) - 5*x, x) is True assert _is_lambert(cosh(x) - sinh(x), x) is False # end of lambert tests def test_linear_coeffs(): from sympy.solvers.solveset import linear_coeffs assert linear_coeffs(0, x) == [0, 0] assert all(i is S.Zero for i in linear_coeffs(0, x)) assert linear_coeffs(x + 2*y + 3, x, y) == [1, 2, 3] assert linear_coeffs(x + 2*y + 3, y, x) == [2, 1, 3] assert linear_coeffs(x + 2*x**2 + 3, x, x**2) == [1, 2, 3] raises(ValueError, lambda: linear_coeffs(x + 2*x**2 + x**3, x, x**2)) raises(ValueError, lambda: linear_coeffs(1/x*(x - 1) + 1/x, x)) assert linear_coeffs(a*(x + y), x, y) == [a, a, 0] assert linear_coeffs(1.0, x, y) == [0, 0, 1.0] # modular tests def test_is_modular(): assert _is_modular(y, x) is False assert _is_modular(Mod(x, 3) - 1, x) is True assert _is_modular(Mod(x**3 - 3*x**2 - x + 1, 3) - 1, x) is True assert _is_modular(Mod(exp(x + y), 3) - 2, x) is True assert _is_modular(Mod(exp(x + y), 3) - log(x), x) is True assert _is_modular(Mod(x, 3) - 1, y) is False assert _is_modular(Mod(x, 3)**2 - 5, x) is False assert _is_modular(Mod(x, 3)**2 - y, x) is False assert _is_modular(exp(Mod(x, 3)) - 1, x) is False assert _is_modular(Mod(3, y) - 1, y) is False def test_invert_modular(): n = Dummy('n', integer=True) from sympy.solvers.solveset import _invert_modular as invert_modular # non invertible cases assert invert_modular(Mod(sin(x), 7), S(5), n, x) == (Mod(sin(x), 7), 5) assert invert_modular(Mod(exp(x), 7), S(5), n, x) == (Mod(exp(x), 7), 5) assert invert_modular(Mod(log(x), 7), S(5), n, x) == (Mod(log(x), 7), 5) # a is symbol assert dumeq(invert_modular(Mod(x, 7), S(5), n, x), (x, ImageSet(Lambda(n, 7*n + 5), S.Integers))) # a.is_Add assert dumeq(invert_modular(Mod(x + 8, 7), S(5), n, x), (x, ImageSet(Lambda(n, 7*n + 4), S.Integers))) assert invert_modular(Mod(x**2 + x, 7), S(5), n, x) == \ (Mod(x**2 + x, 7), 5) # a.is_Mul assert dumeq(invert_modular(Mod(3*x, 7), S(5), n, x), (x, ImageSet(Lambda(n, 7*n + 4), S.Integers))) assert invert_modular(Mod((x + 1)*(x + 2), 7), S(5), n, x) == \ (Mod((x + 1)*(x + 2), 7), 5) # a.is_Pow assert invert_modular(Mod(x**4, 7), S(5), n, x) == \ (x, S.EmptySet) assert dumeq(invert_modular(Mod(3**x, 4), S(3), n, x), (x, ImageSet(Lambda(n, 2*n + 1), S.Naturals0))) assert dumeq(invert_modular(Mod(2**(x**2 + x + 1), 7), S(2), n, x), (x**2 + x + 1, ImageSet(Lambda(n, 3*n + 1), S.Naturals0))) assert invert_modular(Mod(sin(x)**4, 7), S(5), n, x) == (x, S.EmptySet) def test_solve_modular(): n = Dummy('n', integer=True) # if rhs has symbol (need to be implemented in future). assert solveset(Mod(x, 4) - x, x, S.Integers ).dummy_eq( ConditionSet(x, Eq(-x + Mod(x, 4), 0), S.Integers)) # when _invert_modular fails to invert assert solveset(3 - Mod(sin(x), 7), x, S.Integers ).dummy_eq( ConditionSet(x, Eq(Mod(sin(x), 7) - 3, 0), S.Integers)) assert solveset(3 - Mod(log(x), 7), x, S.Integers ).dummy_eq( ConditionSet(x, Eq(Mod(log(x), 7) - 3, 0), S.Integers)) assert solveset(3 - Mod(exp(x), 7), x, S.Integers ).dummy_eq(ConditionSet(x, Eq(Mod(exp(x), 7) - 3, 0), S.Integers)) # EmptySet solution definitely assert solveset(7 - Mod(x, 5), x, S.Integers) is S.EmptySet assert solveset(5 - Mod(x, 5), x, S.Integers) is S.EmptySet # Negative m assert dumeq(solveset(2 + Mod(x, -3), x, S.Integers), ImageSet(Lambda(n, -3*n - 2), S.Integers)) assert solveset(4 + Mod(x, -3), x, S.Integers) is S.EmptySet # linear expression in Mod assert dumeq(solveset(3 - Mod(x, 5), x, S.Integers), ImageSet(Lambda(n, 5*n + 3), S.Integers)) assert dumeq(solveset(3 - Mod(5*x - 8, 7), x, S.Integers), ImageSet(Lambda(n, 7*n + 5), S.Integers)) assert dumeq(solveset(3 - Mod(5*x, 7), x, S.Integers), ImageSet(Lambda(n, 7*n + 2), S.Integers)) # higher degree expression in Mod assert dumeq(solveset(Mod(x**2, 160) - 9, x, S.Integers), Union(ImageSet(Lambda(n, 160*n + 3), S.Integers), ImageSet(Lambda(n, 160*n + 13), S.Integers), ImageSet(Lambda(n, 160*n + 67), S.Integers), ImageSet(Lambda(n, 160*n + 77), S.Integers), ImageSet(Lambda(n, 160*n + 83), S.Integers), ImageSet(Lambda(n, 160*n + 93), S.Integers), ImageSet(Lambda(n, 160*n + 147), S.Integers), ImageSet(Lambda(n, 160*n + 157), S.Integers))) assert solveset(3 - Mod(x**4, 7), x, S.Integers) is S.EmptySet assert dumeq(solveset(Mod(x**4, 17) - 13, x, S.Integers), Union(ImageSet(Lambda(n, 17*n + 3), S.Integers), ImageSet(Lambda(n, 17*n + 5), S.Integers), ImageSet(Lambda(n, 17*n + 12), S.Integers), ImageSet(Lambda(n, 17*n + 14), S.Integers))) # a.is_Pow tests assert dumeq(solveset(Mod(7**x, 41) - 15, x, S.Integers), ImageSet(Lambda(n, 40*n + 3), S.Naturals0)) assert dumeq(solveset(Mod(12**x, 21) - 18, x, S.Integers), ImageSet(Lambda(n, 6*n + 2), S.Naturals0)) assert dumeq(solveset(Mod(3**x, 4) - 3, x, S.Integers), ImageSet(Lambda(n, 2*n + 1), S.Naturals0)) assert dumeq(solveset(Mod(2**x, 7) - 2 , x, S.Integers), ImageSet(Lambda(n, 3*n + 1), S.Naturals0)) assert dumeq(solveset(Mod(3**(3**x), 4) - 3, x, S.Integers), Intersection(ImageSet(Lambda(n, Intersection({log(2*n + 1)/log(3)}, S.Integers)), S.Naturals0), S.Integers)) # Implemented for m without primitive root assert solveset(Mod(x**3, 7) - 2, x, S.Integers) is S.EmptySet assert dumeq(solveset(Mod(x**3, 8) - 1, x, S.Integers), ImageSet(Lambda(n, 8*n + 1), S.Integers)) assert dumeq(solveset(Mod(x**4, 9) - 4, x, S.Integers), Union(ImageSet(Lambda(n, 9*n + 4), S.Integers), ImageSet(Lambda(n, 9*n + 5), S.Integers))) # domain intersection assert dumeq(solveset(3 - Mod(5*x - 8, 7), x, S.Naturals0), Intersection(ImageSet(Lambda(n, 7*n + 5), S.Integers), S.Naturals0)) # Complex args assert solveset(Mod(x, 3) - I, x, S.Integers) == \ S.EmptySet assert solveset(Mod(I*x, 3) - 2, x, S.Integers ).dummy_eq( ConditionSet(x, Eq(Mod(I*x, 3) - 2, 0), S.Integers)) assert solveset(Mod(I + x, 3) - 2, x, S.Integers ).dummy_eq( ConditionSet(x, Eq(Mod(x + I, 3) - 2, 0), S.Integers)) # issue 17373 (https://github.com/sympy/sympy/issues/17373) assert dumeq(solveset(Mod(x**4, 14) - 11, x, S.Integers), Union(ImageSet(Lambda(n, 14*n + 3), S.Integers), ImageSet(Lambda(n, 14*n + 11), S.Integers))) assert dumeq(solveset(Mod(x**31, 74) - 43, x, S.Integers), ImageSet(Lambda(n, 74*n + 31), S.Integers)) # issue 13178 n = symbols('n', integer=True) a = 742938285 b = 1898888478 m = 2**31 - 1 c = 20170816 assert dumeq(solveset(c - Mod(a**n*b, m), n, S.Integers), ImageSet(Lambda(n, 2147483646*n + 100), S.Naturals0)) assert dumeq(solveset(c - Mod(a**n*b, m), n, S.Naturals0), Intersection(ImageSet(Lambda(n, 2147483646*n + 100), S.Naturals0), S.Naturals0)) assert dumeq(solveset(c - Mod(a**(2*n)*b, m), n, S.Integers), Intersection(ImageSet(Lambda(n, 1073741823*n + 50), S.Naturals0), S.Integers)) assert solveset(c - Mod(a**(2*n + 7)*b, m), n, S.Integers) is S.EmptySet assert dumeq(solveset(c - Mod(a**(n - 4)*b, m), n, S.Integers), Intersection(ImageSet(Lambda(n, 2147483646*n + 104), S.Naturals0), S.Integers)) # end of modular tests def test_issue_17276(): assert nonlinsolve([Eq(x, 5**(S(1)/5)), Eq(x*y, 25*sqrt(5))], x, y) == \ FiniteSet((5**(S(1)/5), 25*5**(S(3)/10))) def test_issue_10426(): x = Dummy('x') a = Symbol('a') n = Dummy('n') assert (solveset(sin(x + a) - sin(x), a)).dummy_eq(Dummy('x')) == (Union( ImageSet(Lambda(n, 2*n*pi), S.Integers), Intersection(S.Complexes, ImageSet(Lambda(n, -I*(I*(2*n*pi + arg(-exp(-2*I*x))) + 2*im(x))), S.Integers)))).dummy_eq(Dummy('x,n')) def test_solveset_conjugate(): """Test solveset for simple conjugate functions""" assert solveset(conjugate(x) -3 + I) == FiniteSet(3 + I) def test_issue_18208(): variables = symbols('x0:16') + symbols('y0:12') x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15,\ y0, y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11 = variables eqs = [x0 + x1 + x2 + x3 - 51, x0 + x1 + x4 + x5 - 46, x2 + x3 + x6 + x7 - 39, x0 + x3 + x4 + x7 - 50, x1 + x2 + x5 + x6 - 35, x4 + x5 + x6 + x7 - 34, x4 + x5 + x8 + x9 - 46, x10 + x11 + x6 + x7 - 23, x11 + x4 + x7 + x8 - 25, x10 + x5 + x6 + x9 - 44, x10 + x11 + x8 + x9 - 35, x12 + x13 + x8 + x9 - 35, x10 + x11 + x14 + x15 - 29, x11 + x12 + x15 + x8 - 35, x10 + x13 + x14 + x9 - 29, x12 + x13 + x14 + x15 - 29, y0 + y1 + y2 + y3 - 55, y0 + y1 + y4 + y5 - 53, y2 + y3 + y6 + y7 - 56, y0 + y3 + y4 + y7 - 57, y1 + y2 + y5 + y6 - 52, y4 + y5 + y6 + y7 - 54, y4 + y5 + y8 + y9 - 48, y10 + y11 + y6 + y7 - 60, y11 + y4 + y7 + y8 - 51, y10 + y5 + y6 + y9 - 57, y10 + y11 + y8 + y9 - 54, x10 - 2, x11 - 5, x12 - 1, x13 - 6, x14 - 1, x15 - 21, y0 - 12, y1 - 20] expected = [38 - x3, x3 - 10, 23 - x3, x3, 12 - x7, x7 + 6, 16 - x7, x7, 8, 20, 2, 5, 1, 6, 1, 21, 12, 20, -y11 + y9 + 2, y11 - y9 + 21, -y11 - y7 + y9 + 24, y11 + y7 - y9 - 3, 33 - y7, y7, 27 - y9, y9, 27 - y11, y11] A, b = linear_eq_to_matrix(eqs, variables) # solve solve_expected = {v:eq for v, eq in zip(variables, expected) if v != eq} assert solve(eqs, variables) == solve_expected # linsolve linsolve_expected = FiniteSet(Tuple(*expected)) assert linsolve(eqs, variables) == linsolve_expected assert linsolve((A, b), variables) == linsolve_expected # gauss_jordan_solve gj_solve, new_vars = A.gauss_jordan_solve(b) gj_solve = [i for i in gj_solve] gj_expected = linsolve_expected.subs(zip([x3, x7, y7, y9, y11], new_vars)) assert FiniteSet(Tuple(*gj_solve)) == gj_expected # nonlinsolve # The solution set of nonlinsolve is currently equivalent to linsolve and is # also correct. However, we would prefer to use the same symbols as parameters # for the solution to the underdetermined system in all cases if possible. # We want a solution that is not just equivalent but also given in the same form. # This test may be changed should nonlinsolve be modified in this way. nonlinsolve_expected = FiniteSet((38 - x3, x3 - 10, 23 - x3, x3, 12 - x7, x7 + 6, 16 - x7, x7, 8, 20, 2, 5, 1, 6, 1, 21, 12, 20, -y5 + y7 - 1, y5 - y7 + 24, 21 - y5, y5, 33 - y7, y7, 27 - y9, y9, -y5 + y7 - y9 + 24, y5 - y7 + y9 + 3)) assert nonlinsolve(eqs, variables) == nonlinsolve_expected @XFAIL def test_substitution_with_infeasible_solution(): a00, a01, a10, a11, l0, l1, l2, l3, m0, m1, m2, m3, m4, m5, m6, m7, c00, c01, c10, c11, p00, p01, p10, p11 = symbols( 'a00, a01, a10, a11, l0, l1, l2, l3, m0, m1, m2, m3, m4, m5, m6, m7, c00, c01, c10, c11, p00, p01, p10, p11' ) solvefor = [p00, p01, p10, p11, c00, c01, c10, c11, m0, m1, m3, l0, l1, l2, l3] system = [ -l0 * c00 - l1 * c01 + m0 + c00 + c01, -l0 * c10 - l1 * c11 + m1, -l2 * c00 - l3 * c01 + c00 + c01, -l2 * c10 - l3 * c11 + m3, -l0 * p00 - l2 * p10 + p00 + p10, -l1 * p00 - l3 * p10 + p00 + p10, -l0 * p01 - l2 * p11, -l1 * p01 - l3 * p11, -a00 + c00 * p00 + c10 * p01, -a01 + c01 * p00 + c11 * p01, -a10 + c00 * p10 + c10 * p11, -a11 + c01 * p10 + c11 * p11, -m0 * p00, -m1 * p01, -m2 * p10, -m3 * p11, -m4 * c00, -m5 * c01, -m6 * c10, -m7 * c11, m2, m4, m5, m6, m7 ] sol = FiniteSet( (0, Complement(FiniteSet(p01), FiniteSet(0)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, l2, l3), (p00, Complement(FiniteSet(p01), FiniteSet(0)), 0, p11, 0, 0, 0, 0, 0, 0, 0, 1, 1, -p01/p11, -p01/p11), (0, Complement(FiniteSet(p01), FiniteSet(0)), 0, p11, 0, 0, 0, 0, 0, 0, 0, 1, -l3*p11/p01, -p01/p11, l3), (0, Complement(FiniteSet(p01), FiniteSet(0)), 0, p11, 0, 0, 0, 0, 0, 0, 0, -l2*p11/p01, -l3*p11/p01, l2, l3), ) assert sol != nonlinsolve(system, solvefor) def test_issue_20097(): assert solveset(1/sqrt(x)) is S.EmptySet def test_issue_15350(): assert solveset(diff(sqrt(1/x+x))) == FiniteSet(-1, 1) def test_issue_18359(): c1 = Piecewise((0, x < 0), (Min(1, x)/2 - Min(2, x)/2 + Min(3, x)/2, True)) c2 = Piecewise((Piecewise((0, x < 0), (Min(1, x)/2 - Min(2, x)/2 + Min(3, x)/2, True)), x >= 0), (0, True)) correct_result = Interval(1, 2) result1 = solveset(c1 - Rational(1, 2), x, Interval(0, 3)) result2 = solveset(c2 - Rational(1, 2), x, Interval(0, 3)) assert result1 == correct_result assert result2 == correct_result def test_issue_17604(): lhs = -2**(3*x/11)*exp(x/11) + pi**(x/11) assert _is_exponential(lhs, x) assert _solve_exponential(lhs, 0, x, S.Complexes) == FiniteSet(0) def test_issue_17580(): assert solveset(1/(1 - x**3)**2, x, S.Reals) is S.EmptySet def test_issue_17566_actual(): sys = [2**x + 2**y - 3, 4**x + 9**y - 5] # Not clear this is the correct result, but at least no recursion error assert nonlinsolve(sys, x, y) == FiniteSet((log(3 - 2**y)/log(2), y)) def test_issue_17565(): eq = Ge(2*(x - 2)**2/(3*(x + 1)**(Integer(1)/3)) + 2*(x - 2)*(x + 1)**(Integer(2)/3), 0) res = Union(Interval.Lopen(-1, -Rational(1, 4)), Interval(2, oo)) assert solveset(eq, x, S.Reals) == res def test_issue_15024(): function = (x + 5)/sqrt(-x**2 - 10*x) assert solveset(function, x, S.Reals) == FiniteSet(Integer(-5)) def test_issue_16877(): assert dumeq(nonlinsolve([x - 1, sin(y)], x, y), FiniteSet((FiniteSet(1), ImageSet(Lambda(n, 2*n*pi), S.Integers)), (FiniteSet(1), ImageSet(Lambda(n, 2*n*pi + pi), S.Integers)))) # Even better if (FiniteSet(1), ImageSet(Lambda(n, n*pi), S.Integers)) is obtained def test_issue_16876(): assert dumeq(nonlinsolve([sin(x), 2*x - 4*y], x, y), FiniteSet((ImageSet(Lambda(n, 2*n*pi), S.Integers), ImageSet(Lambda(n, n*pi), S.Integers)), (ImageSet(Lambda(n, 2*n*pi + pi), S.Integers), ImageSet(Lambda(n, n*pi + pi/2), S.Integers)))) # Even better if (ImageSet(Lambda(n, n*pi), S.Integers), # ImageSet(Lambda(n, n*pi/2), S.Integers)) is obtained def test_issue_21236(): x, z = symbols("x z") y = symbols('y', rational=True) assert solveset(x**y - z, x, S.Reals) == ConditionSet(x, Eq(x**y - z, 0), S.Reals) e1, e2 = symbols('e1 e2', even=True) y = e1/e2 # don't know if num or den will be odd and the other even assert solveset(x**y - z, x, S.Reals) == ConditionSet(x, Eq(x**y - z, 0), S.Reals) def test_issue_21908(): assert nonlinsolve([(x**2 + 2*x - y**2)*exp(x), -2*y*exp(x)], x, y ) == {(-2, 0), (0, 0)} def test_issue_19144(): # test case 1 expr1 = [x + y - 1, y**2 + 1] eq1 = [Eq(i, 0) for i in expr1] soln1 = {(1 - I, I), (1 + I, -I)} soln_expr1 = nonlinsolve(expr1, [x, y]) soln_eq1 = nonlinsolve(eq1, [x, y]) assert soln_eq1 == soln_expr1 == soln1 # test case 2 - with denoms expr2 = [x/y - 1, y**2 + 1] eq2 = [Eq(i, 0) for i in expr2] soln2 = {(-I, -I), (I, I)} soln_expr2 = nonlinsolve(expr2, [x, y]) soln_eq2 = nonlinsolve(eq2, [x, y]) assert soln_eq2 == soln_expr2 == soln2 # denominators that cancel in expression assert nonlinsolve([Eq(x + 1/x, 1/x)], [x]) == FiniteSet((S.EmptySet,)) def test_issue_22413(): res = nonlinsolve((4*y*(2*x + 2*exp(y) + 1)*exp(2*x), 4*x*exp(2*x) + 4*y*exp(2*x + y) + 4*exp(2*x + y) + 1), x, y) # First solution is not correct, but the issue was an exception sols = FiniteSet((x, S.Zero), (-exp(y) - S.Half, y)) assert res == sols def test_issue_19814(): assert nonlinsolve([ 2**m - 2**(2*n), 4*2**m - 2**(4*n)], m, n ) == FiniteSet((log(2**(2*n))/log(2), S.Complexes)) def test_issue_22058(): sol = solveset(-sqrt(t)*x**2 + 2*x + sqrt(t), x, S.Reals) # doesn't fail (and following numerical check) assert sol.xreplace({t: 1}) == {1 - sqrt(2), 1 + sqrt(2)}, sol.xreplace({t: 1}) def test_issue_11184(): assert solveset(20*sqrt(y**2 + (sqrt(-(y - 10)*(y + 10)) + 10)**2) - 60, y, S.Reals) is S.EmptySet def test_issue_21890(): e = S(2)/3 assert nonlinsolve([4*x**3*y**4 - 2*y, 4*x**4*y**3 - 2*x], x, y) == { (2**e/(2*y), y), ((-2**e/4 - 2**e*sqrt(3)*I/4)/y, y), ((-2**e/4 + 2**e*sqrt(3)*I/4)/y, y)} assert nonlinsolve([(1 - 4*x**2)*exp(-2*x**2 - 2*y**2), -4*x*y*exp(-2*x**2)*exp(-2*y**2)], x, y) == {(-S(1)/2, 0), (S(1)/2, 0)} rx, ry = symbols('x y', real=True) sol = nonlinsolve([4*rx**3*ry**4 - 2*ry, 4*rx**4*ry**3 - 2*rx], rx, ry) ans = {(2**(S(2)/3)/(2*ry), ry), ((-2**(S(2)/3)/4 - 2**(S(2)/3)*sqrt(3)*I/4)/ry, ry), ((-2**(S(2)/3)/4 + 2**(S(2)/3)*sqrt(3)*I/4)/ry, ry)} assert sol == ans
c564d4c0a05509a35a268f7e88cd5593ab9e5d4fdcc58e3ca2e457085a9abf41
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.testing.randtest 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 solve([y, exp(x) + x], x, y) == [(-LambertW(1), 0)] # symbol is a number assert solve(x**2 - pi, pi) == [x**2] # no equations assert solve([], [x]) == [] # overdetermined system # - nonlinear assert solve([(x + y)**2 - 4, x + y - 2]) == [{x: -y + 2}] # - linear assert solve((x + y - 2, 2*x + 2*y - 4)) == {x: -y + 2} # When one or more args are Boolean assert solve(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()) 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 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(): def count(dic): return len([x for x in dic.values() if x == 0]) assert count(solve([x + y + z, y + z + a + t], particular=True, quick=True)) \ == 3 assert count(solve([x + y + z, y + z + a + t], particular=True, quick=False)) \ == 3 assert count(solve([x + y + z, y + z + a], particular=True, quick=True)) == 1 assert count(solve([x + y + z, y + z + a], particular=True, quick=False)) == 2 def test_real_roots(): # cf. issue 6650 x = Symbol('x', real=True) assert len(solve(x**5 + x**3 + 1)) == 1 def test_issue_6528(): eqs = [ 327600995*x**2 - 37869137*x + 1809975124*y**2 - 9998905626, 895613949*x**2 - 273830224*x*y + 530506983*y**2 - 10000000000] # two expressions encountered are > 1400 ops long so if this hangs # it is likely because simplification is being done assert len(solve(eqs, y, x, check=False)) == 4 def test_overdetermined(): x = symbols('x', real=True) eqs = [Abs(4*x - 7) - 5, Abs(3 - 8*x) - 1] assert solve(eqs, x) == [(S.Half,)] assert solve(eqs, x, manual=True) == [(S.Half,)] assert solve(eqs, x, manual=True, check=False) == [(S.Half,), (S(3),)] def test_issue_6605(): x = symbols('x') assert solve(4**(x/2) - 2**(x/3)) == [0, 3*I*pi/log(2)] # while the first one passed, this one failed x = symbols('x', real=True) assert solve(5**(x/2) - 2**(x/3)) == [0] b = sqrt(6)*sqrt(log(2))/sqrt(log(5)) assert solve(5**(x/2) - 2**(3/x)) == [-b, b] def test__ispow(): assert _ispow(x**2) assert not _ispow(x) assert not _ispow(True) def test_issue_6644(): eq = -sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) + sqrt((-m**2/2 - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2) sol = solve(eq, q, simplify=False, check=False) assert len(sol) == 5 def test_issue_6752(): assert solve([a**2 + a, a - b], [a, b]) == [(-1, -1), (0, 0)] assert solve([a**2 + a*c, a - b], [a, b]) == [(0, 0), (-c, -c)] def test_issue_6792(): assert solve(x*(x - 1)**2*(x + 1)*(x**6 - x + 1)) == [ -1, 0, 1, CRootOf(x**6 - x + 1, 0), CRootOf(x**6 - x + 1, 1), CRootOf(x**6 - x + 1, 2), CRootOf(x**6 - x + 1, 3), CRootOf(x**6 - x + 1, 4), CRootOf(x**6 - x + 1, 5)] def test_issues_6819_6820_6821_6248_8692(): # issue 6821 x, y = symbols('x y', real=True) assert solve(abs(x + 3) - 2*abs(x - 3)) == [1, 9] assert solve([abs(x) - 2, arg(x) - pi], x) == [(-2,)] 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))]
87d86d97d6adb236aad034ab639b3d2ead4e32d14d26baff1c56dcb270fddf2b
"""Tests for solvers of systems of polynomial equations. """ from sympy.core.numbers import (I, Integer, Rational) from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.miscellaneous import sqrt from sympy.polys.domains.rationalfield import QQ from sympy.polys.polytools import Poly from sympy.solvers.solvers import solve from sympy.utilities.iterables import flatten from sympy.abc import x, y, z from sympy.polys import PolynomialError from sympy.solvers.polysys import (solve_poly_system, solve_triangulated, solve_biquadratic, SolveFailed) from sympy.polys.polytools import parallel_poly_from_expr from sympy.testing.pytest import raises def test_solve_poly_system(): assert solve_poly_system([x - 1], x) == [(S.One,)] assert solve_poly_system([y - x, y - x - 1], x, y) is None assert solve_poly_system([y - x**2, y + x**2], x, y) == [(S.Zero, S.Zero)] assert solve_poly_system([2*x - 3, y*Rational(3, 2) - 2*x, z - 5*y], x, y, z) == \ [(Rational(3, 2), Integer(2), Integer(10))] assert solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y) == \ [(0, 0), (2, -sqrt(2)), (2, sqrt(2))] assert solve_poly_system([y - x**2, y + x**2 + 1], x, y) == \ [(-I*sqrt(S.Half), Rational(-1, 2)), (I*sqrt(S.Half), Rational(-1, 2))] f_1 = x**2 + y + z - 1 f_2 = x + y**2 + z - 1 f_3 = x + y + z**2 - 1 a, b = sqrt(2) - 1, -sqrt(2) - 1 assert solve_poly_system([f_1, f_2, f_3], x, y, z) == \ [(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)] solution = [(1, -1), (1, 1)] assert solve_poly_system([Poly(x**2 - y**2), Poly(x - 1)]) == solution assert solve_poly_system([x**2 - y**2, x - 1], x, y) == solution assert solve_poly_system([x**2 - y**2, x - 1]) == solution assert solve_poly_system( [x + x*y - 3, y + x*y - 4], x, y) == [(-3, -2), (1, 2)] raises(NotImplementedError, lambda: solve_poly_system([x**3 - y**3], x, y)) raises(NotImplementedError, lambda: solve_poly_system( [z, -2*x*y**2 + x + y**2*z, y**2*(-z - 4) + 2])) raises(PolynomialError, lambda: solve_poly_system([1/x], x)) raises(NotImplementedError, lambda: solve_poly_system( [x-1,], (x, y))) raises(NotImplementedError, lambda: solve_poly_system( [y-1,], (x, y))) def test_solve_biquadratic(): x0, y0, x1, y1, r = symbols('x0 y0 x1 y1 r') f_1 = (x - 1)**2 + (y - 1)**2 - r**2 f_2 = (x - 2)**2 + (y - 2)**2 - r**2 s = sqrt(2*r**2 - 1) a = (3 - s)/2 b = (3 + s)/2 assert solve_poly_system([f_1, f_2], x, y) == [(a, b), (b, a)] f_1 = (x - 1)**2 + (y - 2)**2 - r**2 f_2 = (x - 1)**2 + (y - 1)**2 - r**2 assert solve_poly_system([f_1, f_2], x, y) == \ [(1 - sqrt((2*r - 1)*(2*r + 1))/2, Rational(3, 2)), (1 + sqrt((2*r - 1)*(2*r + 1))/2, Rational(3, 2))] query = lambda expr: expr.is_Pow and expr.exp is S.Half f_1 = (x - 1 )**2 + (y - 2)**2 - r**2 f_2 = (x - x1)**2 + (y - 1)**2 - r**2 result = solve_poly_system([f_1, f_2], x, y) assert len(result) == 2 and all(len(r) == 2 for r in result) assert all(r.count(query) == 1 for r in flatten(result)) f_1 = (x - x0)**2 + (y - y0)**2 - r**2 f_2 = (x - x1)**2 + (y - y1)**2 - r**2 result = solve_poly_system([f_1, f_2], x, y) assert len(result) == 2 and all(len(r) == 2 for r in result) assert all(len(r.find(query)) == 1 for r in flatten(result)) s1 = (x*y - y, x**2 - x) assert solve(s1) == [{x: 1}, {x: 0, y: 0}] s2 = (x*y - x, y**2 - y) assert solve(s2) == [{y: 1}, {x: 0, y: 0}] gens = (x, y) for seq in (s1, s2): (f, g), opt = parallel_poly_from_expr(seq, *gens) raises(SolveFailed, lambda: solve_biquadratic(f, g, opt)) seq = (x**2 + y**2 - 2, y**2 - 1) (f, g), opt = parallel_poly_from_expr(seq, *gens) assert solve_biquadratic(f, g, opt) == [ (-1, -1), (-1, 1), (1, -1), (1, 1)] ans = [(0, -1), (0, 1)] seq = (x**2 + y**2 - 1, y**2 - 1) (f, g), opt = parallel_poly_from_expr(seq, *gens) assert solve_biquadratic(f, g, opt) == ans seq = (x**2 + y**2 - 1, x**2 - x + y**2 - 1) (f, g), opt = parallel_poly_from_expr(seq, *gens) assert solve_biquadratic(f, g, opt) == ans def test_solve_triangulated(): f_1 = x**2 + y + z - 1 f_2 = x + y**2 + z - 1 f_3 = x + y + z**2 - 1 a, b = sqrt(2) - 1, -sqrt(2) - 1 assert solve_triangulated([f_1, f_2, f_3], x, y, z) == \ [(0, 0, 1), (0, 1, 0), (1, 0, 0)] dom = QQ.algebraic_field(sqrt(2)) assert solve_triangulated([f_1, f_2, f_3], x, y, z, domain=dom) == \ [(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)] def test_solve_issue_3686(): roots = solve_poly_system([((x - 5)**2/250000 + (y - Rational(5, 10))**2/250000) - 1, x], x, y) assert roots == [(0, S.Half - 15*sqrt(1111)), (0, S.Half + 15*sqrt(1111))] roots = solve_poly_system([((x - 5)**2/250000 + (y - 5.0/10)**2/250000) - 1, x], x, y) # TODO: does this really have to be so complicated?! assert len(roots) == 2 assert roots[0][0] == 0 assert roots[0][1].epsilon_eq(-499.474999374969, 1e12) assert roots[1][0] == 0 assert roots[1][1].epsilon_eq(500.474999374969, 1e12)
3fd3a8b8a88213a0c903b90059397f3b4ff80b48037705e7bae925e2ac482321
"""Tests for tools for solving inequalities and systems of inequalities. """ from sympy.concrete.summations import Sum from sympy.core.function import Function from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol) from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import (root, sqrt) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (cos, sin, tan) from sympy.integrals.integrals import Integral from sympy.logic.boolalg import (And, Or) from sympy.polys.polytools import (Poly, PurePoly) from sympy.sets.sets import (FiniteSet, Interval, Union) from sympy.solvers.inequalities import (reduce_inequalities, solve_poly_inequality as psolve, reduce_rational_inequalities, solve_univariate_inequality as isolve, reduce_abs_inequality, _solve_inequality) from sympy.polys.rootoftools import rootof from sympy.solvers.solvers import solve from sympy.solvers.solveset import solveset from sympy.abc import x, y from sympy.core.mod import Mod from sympy.testing.pytest import raises, XFAIL inf = oo.evalf() def test_solve_poly_inequality(): assert psolve(Poly(0, x), '==') == [S.Reals] assert psolve(Poly(1, x), '==') == [S.EmptySet] assert psolve(PurePoly(x + 1, x), ">") == [Interval(-1, oo, True, False)] def test_reduce_poly_inequalities_real_interval(): assert reduce_rational_inequalities( [[Eq(x**2, 0)]], x, relational=False) == FiniteSet(0) assert reduce_rational_inequalities( [[Le(x**2, 0)]], x, relational=False) == FiniteSet(0) assert reduce_rational_inequalities( [[Lt(x**2, 0)]], x, relational=False) == S.EmptySet assert reduce_rational_inequalities( [[Ge(x**2, 0)]], x, relational=False) == \ S.Reals if x.is_real else Interval(-oo, oo) assert reduce_rational_inequalities( [[Gt(x**2, 0)]], x, relational=False) == \ FiniteSet(0).complement(S.Reals) assert reduce_rational_inequalities( [[Ne(x**2, 0)]], x, relational=False) == \ FiniteSet(0).complement(S.Reals) assert reduce_rational_inequalities( [[Eq(x**2, 1)]], x, relational=False) == FiniteSet(-1, 1) assert reduce_rational_inequalities( [[Le(x**2, 1)]], x, relational=False) == Interval(-1, 1) assert reduce_rational_inequalities( [[Lt(x**2, 1)]], x, relational=False) == Interval(-1, 1, True, True) assert reduce_rational_inequalities( [[Ge(x**2, 1)]], x, relational=False) == \ Union(Interval(-oo, -1), Interval(1, oo)) assert reduce_rational_inequalities( [[Gt(x**2, 1)]], x, relational=False) == \ Interval(-1, 1).complement(S.Reals) assert reduce_rational_inequalities( [[Ne(x**2, 1)]], x, relational=False) == \ FiniteSet(-1, 1).complement(S.Reals) assert reduce_rational_inequalities([[Eq( x**2, 1.0)]], x, relational=False) == FiniteSet(-1.0, 1.0).evalf() assert reduce_rational_inequalities( [[Le(x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0) assert reduce_rational_inequalities([[Lt( x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0, True, True) assert reduce_rational_inequalities( [[Ge(x**2, 1.0)]], x, relational=False) == \ Union(Interval(-inf, -1.0), Interval(1.0, inf)) assert reduce_rational_inequalities( [[Gt(x**2, 1.0)]], x, relational=False) == \ Union(Interval(-inf, -1.0, right_open=True), Interval(1.0, inf, left_open=True)) assert reduce_rational_inequalities([[Ne( x**2, 1.0)]], x, relational=False) == \ FiniteSet(-1.0, 1.0).complement(S.Reals) s = sqrt(2) assert reduce_rational_inequalities([[Lt( x**2 - 1, 0), Gt(x**2 - 1, 0)]], x, relational=False) == S.EmptySet assert reduce_rational_inequalities([[Le(x**2 - 1, 0), Ge( x**2 - 1, 0)]], x, relational=False) == FiniteSet(-1, 1) assert reduce_rational_inequalities( [[Le(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False ) == Union(Interval(-s, -1, False, False), Interval(1, s, False, False)) assert reduce_rational_inequalities( [[Le(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False ) == Union(Interval(-s, -1, False, True), Interval(1, s, True, False)) assert reduce_rational_inequalities( [[Lt(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False ) == Union(Interval(-s, -1, True, False), Interval(1, s, False, True)) assert reduce_rational_inequalities( [[Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False ) == Union(Interval(-s, -1, True, True), Interval(1, s, True, True)) assert reduce_rational_inequalities( [[Lt(x**2 - 2, 0), Ne(x**2 - 1, 0)]], x, relational=False ) == Union(Interval(-s, -1, True, True), Interval(-1, 1, True, True), Interval(1, s, True, True)) assert reduce_rational_inequalities([[Lt(x**2, -1.)]], x) is S.false def test_reduce_poly_inequalities_complex_relational(): assert reduce_rational_inequalities( [[Eq(x**2, 0)]], x, relational=True) == Eq(x, 0) assert reduce_rational_inequalities( [[Le(x**2, 0)]], x, relational=True) == Eq(x, 0) assert reduce_rational_inequalities( [[Lt(x**2, 0)]], x, relational=True) == False assert reduce_rational_inequalities( [[Ge(x**2, 0)]], x, relational=True) == And(Lt(-oo, x), Lt(x, oo)) assert reduce_rational_inequalities( [[Gt(x**2, 0)]], x, relational=True) == \ And(Gt(x, -oo), Lt(x, oo), Ne(x, 0)) assert reduce_rational_inequalities( [[Ne(x**2, 0)]], x, relational=True) == \ And(Gt(x, -oo), Lt(x, oo), Ne(x, 0)) for one in (S.One, S(1.0)): inf = one*oo assert reduce_rational_inequalities( [[Eq(x**2, one)]], x, relational=True) == \ Or(Eq(x, -one), Eq(x, one)) assert reduce_rational_inequalities( [[Le(x**2, one)]], x, relational=True) == \ And(And(Le(-one, x), Le(x, one))) assert reduce_rational_inequalities( [[Lt(x**2, one)]], x, relational=True) == \ And(And(Lt(-one, x), Lt(x, one))) assert reduce_rational_inequalities( [[Ge(x**2, one)]], x, relational=True) == \ And(Or(And(Le(one, x), Lt(x, inf)), And(Le(x, -one), Lt(-inf, x)))) assert reduce_rational_inequalities( [[Gt(x**2, one)]], x, relational=True) == \ And(Or(And(Lt(-inf, x), Lt(x, -one)), And(Lt(one, x), Lt(x, inf)))) assert reduce_rational_inequalities( [[Ne(x**2, one)]], x, relational=True) == \ Or(And(Lt(-inf, x), Lt(x, -one)), And(Lt(-one, x), Lt(x, one)), And(Lt(one, x), Lt(x, inf))) def test_reduce_rational_inequalities_real_relational(): assert reduce_rational_inequalities([], x) == False assert reduce_rational_inequalities( [[(x**2 + 3*x + 2)/(x**2 - 16) >= 0]], x, relational=False) == \ Union(Interval.open(-oo, -4), Interval(-2, -1), Interval.open(4, oo)) assert reduce_rational_inequalities( [[((-2*x - 10)*(3 - x))/((x**2 + 5)*(x - 2)**2) < 0]], x, relational=False) == \ Union(Interval.open(-5, 2), Interval.open(2, 3)) assert reduce_rational_inequalities([[(x + 1)/(x - 5) <= 0]], x, relational=False) == \ Interval.Ropen(-1, 5) assert reduce_rational_inequalities([[(x**2 + 4*x + 3)/(x - 1) > 0]], x, relational=False) == \ Union(Interval.open(-3, -1), Interval.open(1, oo)) assert reduce_rational_inequalities([[(x**2 - 16)/(x - 1)**2 < 0]], x, relational=False) == \ Union(Interval.open(-4, 1), Interval.open(1, 4)) assert reduce_rational_inequalities([[(3*x + 1)/(x + 4) >= 1]], x, relational=False) == \ Union(Interval.open(-oo, -4), Interval.Ropen(Rational(3, 2), oo)) assert reduce_rational_inequalities([[(x - 8)/x <= 3 - x]], x, relational=False) == \ Union(Interval.Lopen(-oo, -2), Interval.Lopen(0, 4)) # issue sympy/sympy#10237 assert reduce_rational_inequalities( [[x < oo, x >= 0, -oo < x]], x, relational=False) == Interval(0, oo) def test_reduce_abs_inequalities(): e = abs(x - 5) < 3 ans = And(Lt(2, x), Lt(x, 8)) assert reduce_inequalities(e) == ans assert reduce_inequalities(e, x) == ans assert reduce_inequalities(abs(x - 5)) == Eq(x, 5) assert reduce_inequalities( abs(2*x + 3) >= 8) == Or(And(Le(Rational(5, 2), x), Lt(x, oo)), And(Le(x, Rational(-11, 2)), Lt(-oo, x))) assert reduce_inequalities(abs(x - 4) + abs( 3*x - 5) < 7) == And(Lt(S.Half, x), Lt(x, 4)) assert reduce_inequalities(abs(x - 4) + abs(3*abs(x) - 5) < 7) == \ Or(And(S(-2) < x, x < -1), And(S.Half < x, x < 4)) nr = Symbol('nr', extended_real=False) raises(TypeError, lambda: reduce_inequalities(abs(nr - 5) < 3)) assert reduce_inequalities(x < 3, symbols=[x, nr]) == And(-oo < x, x < 3) def test_reduce_inequalities_general(): assert reduce_inequalities(Ge(sqrt(2)*x, 1)) == And(sqrt(2)/2 <= x, x < oo) assert reduce_inequalities(x + 1 > 0) == And(S.NegativeOne < x, x < oo) def test_reduce_inequalities_boolean(): assert reduce_inequalities( [Eq(x**2, 0), True]) == Eq(x, 0) assert reduce_inequalities([Eq(x**2, 0), False]) == False assert reduce_inequalities(x**2 >= 0) is S.true # issue 10196 def test_reduce_inequalities_multivariate(): assert reduce_inequalities([Ge(x**2, 1), Ge(y**2, 1)]) == And( Or(And(Le(S.One, x), Lt(x, oo)), And(Le(x, -1), Lt(-oo, x))), Or(And(Le(S.One, y), Lt(y, oo)), And(Le(y, -1), Lt(-oo, y)))) def test_reduce_inequalities_errors(): raises(NotImplementedError, lambda: reduce_inequalities(Ge(sin(x) + x, 1))) raises(NotImplementedError, lambda: reduce_inequalities(Ge(x**2*y + y, 1))) def test__solve_inequalities(): assert reduce_inequalities(x + y < 1, symbols=[x]) == (x < 1 - y) assert reduce_inequalities(x + y >= 1, symbols=[x]) == (x < oo) & (x >= -y + 1) assert reduce_inequalities(Eq(0, x - y), symbols=[x]) == Eq(x, y) assert reduce_inequalities(Ne(0, x - y), symbols=[x]) == Ne(x, y) def test_issue_6343(): eq = -3*x**2/2 - x*Rational(45, 4) + Rational(33, 2) > 0 assert reduce_inequalities(eq) == \ And(x < Rational(-15, 4) + sqrt(401)/4, -sqrt(401)/4 - Rational(15, 4) < x) def test_issue_8235(): assert reduce_inequalities(x**2 - 1 < 0) == \ And(S.NegativeOne < x, x < 1) assert reduce_inequalities(x**2 - 1 <= 0) == \ And(S.NegativeOne <= x, x <= 1) assert reduce_inequalities(x**2 - 1 > 0) == \ Or(And(-oo < x, x < -1), And(x < oo, S.One < x)) assert reduce_inequalities(x**2 - 1 >= 0) == \ Or(And(-oo < x, x <= -1), And(S.One <= x, x < oo)) eq = x**8 + x - 9 # we want CRootOf solns here sol = solve(eq >= 0) tru = Or(And(rootof(eq, 1) <= x, x < oo), And(-oo < x, x <= rootof(eq, 0))) assert sol == tru # recast vanilla as real assert solve(sqrt((-x + 1)**2) < 1) == And(S.Zero < x, x < 2) def test_issue_5526(): assert reduce_inequalities(0 <= x + Integral(y**2, (y, 1, 3)) - 1, [x]) == \ (x >= -Integral(y**2, (y, 1, 3)) + 1) f = Function('f') e = Sum(f(x), (x, 1, 3)) assert reduce_inequalities(0 <= x + e + y**2, [x]) == \ (x >= -y**2 - Sum(f(x), (x, 1, 3))) def test_solve_univariate_inequality(): assert isolve(x**2 >= 4, x, relational=False) == Union(Interval(-oo, -2), Interval(2, oo)) assert isolve(x**2 >= 4, x) == Or(And(Le(2, x), Lt(x, oo)), And(Le(x, -2), Lt(-oo, x))) assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x, relational=False) == \ Union(Interval(1, 2), Interval(3, oo)) assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x) == \ Or(And(Le(1, x), Le(x, 2)), And(Le(3, x), Lt(x, oo))) assert isolve((x - 1)*(x - 2)*(x - 4) < 0, x, domain = FiniteSet(0, 3)) == \ Or(Eq(x, 0), Eq(x, 3)) # issue 2785: assert isolve(x**3 - 2*x - 1 > 0, x, relational=False) == \ Union(Interval(-1, -sqrt(5)/2 + S.Half, True, True), Interval(S.Half + sqrt(5)/2, oo, True, True)) # issue 2794: assert isolve(x**3 - x**2 + x - 1 > 0, x, relational=False) == \ Interval(1, oo, True) #issue 13105 assert isolve((x + I)*(x + 2*I) < 0, x) == Eq(x, 0) assert isolve(((x - 1)*(x - 2) + I)*((x - 1)*(x - 2) + 2*I) < 0, x) == Or(Eq(x, 1), Eq(x, 2)) assert isolve((((x - 1)*(x - 2) + I)*((x - 1)*(x - 2) + 2*I))/(x - 2) > 0, x) == Eq(x, 1) raises (ValueError, lambda: isolve((x**2 - 3*x*I + 2)/x < 0, x)) # numerical testing in valid() is needed assert isolve(x**7 - x - 2 > 0, x) == \ And(rootof(x**7 - x - 2, 0) < x, x < oo) # handle numerator and denominator; although these would be handled as # rational inequalities, these test confirm that the right thing is done # when the domain is EX (e.g. when 2 is replaced with sqrt(2)) assert isolve(1/(x - 2) > 0, x) == And(S(2) < x, x < oo) den = ((x - 1)*(x - 2)).expand() assert isolve((x - 1)/den <= 0, x) == \ (x > -oo) & (x < 2) & Ne(x, 1) n = Dummy('n') raises(NotImplementedError, lambda: isolve(Abs(x) <= n, x, relational=False)) c1 = Dummy("c1", positive=True) raises(NotImplementedError, lambda: isolve(n/c1 < 0, c1)) n = Dummy('n', negative=True) assert isolve(n/c1 > -2, c1) == (-n/2 < c1) assert isolve(n/c1 < 0, c1) == True assert isolve(n/c1 > 0, c1) == False zero = cos(1)**2 + sin(1)**2 - 1 raises(NotImplementedError, lambda: isolve(x**2 < zero, x)) raises(NotImplementedError, lambda: isolve( x**2 < zero*I, x)) raises(NotImplementedError, lambda: isolve(1/(x - y) < 2, x)) raises(NotImplementedError, lambda: isolve(1/(x - y) < 0, x)) raises(TypeError, lambda: isolve(x - I < 0, x)) zero = x**2 + x - x*(x + 1) assert isolve(zero < 0, x, relational=False) is S.EmptySet assert isolve(zero <= 0, x, relational=False) is S.Reals # make sure iter_solutions gets a default value raises(NotImplementedError, lambda: isolve( Eq(cos(x)**2 + sin(x)**2, 1), x)) def test_trig_inequalities(): # all the inequalities are solved in a periodic interval. assert isolve(sin(x) < S.Half, x, relational=False) == \ Union(Interval(0, pi/6, False, True), Interval.open(pi*Rational(5, 6), 2*pi)) assert isolve(sin(x) > S.Half, x, relational=False) == \ Interval(pi/6, pi*Rational(5, 6), True, True) assert isolve(cos(x) < S.Zero, x, relational=False) == \ Interval(pi/2, pi*Rational(3, 2), True, True) assert isolve(cos(x) >= S.Zero, x, relational=False) == \ Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi)) assert isolve(tan(x) < S.One, x, relational=False) == \ Union(Interval.Ropen(0, pi/4), Interval.open(pi/2, pi)) assert isolve(sin(x) <= S.Zero, x, relational=False) == \ Union(FiniteSet(S.Zero), Interval.Ropen(pi, 2*pi)) assert isolve(sin(x) <= S.One, x, relational=False) == S.Reals assert isolve(cos(x) < S(-2), x, relational=False) == S.EmptySet assert isolve(sin(x) >= S.NegativeOne, x, relational=False) == S.Reals assert isolve(cos(x) > S.One, x, relational=False) == S.EmptySet def test_issue_9954(): assert isolve(x**2 >= 0, x, relational=False) == S.Reals assert isolve(x**2 >= 0, x, relational=True) == S.Reals.as_relational(x) assert isolve(x**2 < 0, x, relational=False) == S.EmptySet assert isolve(x**2 < 0, x, relational=True) == S.EmptySet.as_relational(x) @XFAIL def test_slow_general_univariate(): r = rootof(x**5 - x**2 + 1, 0) assert solve(sqrt(x) + 1/root(x, 3) > 1) == \ Or(And(0 < x, x < r**6), And(r**6 < x, x < oo)) def test_issue_8545(): eq = 1 - x - abs(1 - x) ans = And(Lt(1, x), Lt(x, oo)) assert reduce_abs_inequality(eq, '<', x) == ans eq = 1 - x - sqrt((1 - x)**2) assert reduce_inequalities(eq < 0) == ans def test_issue_8974(): assert isolve(-oo < x, x) == And(-oo < x, x < oo) assert isolve(oo > x, x) == And(-oo < x, x < oo) def test_issue_10198(): assert reduce_inequalities( -1 + 1/abs(1/x - 1) < 0) == (x > -oo) & (x < 1/2) & Ne(x, 0) assert reduce_inequalities(abs(1/sqrt(x)) - 1, x) == Eq(x, 1) assert reduce_abs_inequality(-3 + 1/abs(1 - 1/x), '<', x) == \ Or(And(-oo < x, x < 0), And(S.Zero < x, x < Rational(3, 4)), And(Rational(3, 2) < x, x < oo)) raises(ValueError,lambda: reduce_abs_inequality(-3 + 1/abs( 1 - 1/sqrt(x)), '<', x)) def test_issue_10047(): # issue 10047: this must remain an inequality, not True, since if x # is not real the inequality is invalid # assert solve(sin(x) < 2) == (x <= oo) # with PR 16956, (x <= oo) autoevaluates when x is extended_real # which is assumed in the current implementation of inequality solvers assert solve(sin(x) < 2) == True assert solveset(sin(x) < 2, domain=S.Reals) == S.Reals def test_issue_10268(): assert solve(log(x) < 1000) == And(S.Zero < x, x < exp(1000)) @XFAIL def test_isolve_Sets(): n = Dummy('n') assert isolve(Abs(x) <= n, x, relational=False) == \ Piecewise((S.EmptySet, n < 0), (Interval(-n, n), True)) def test_integer_domain_relational_isolve(): dom = FiniteSet(0, 3) x = Symbol('x',zero=False) assert isolve((x - 1)*(x - 2)*(x - 4) < 0, x, domain=dom) == Eq(x, 3) x = Symbol('x') assert isolve(x + 2 < 0, x, domain=S.Integers) == \ (x <= -3) & (x > -oo) & Eq(Mod(x, 1), 0) assert isolve(2 * x + 3 > 0, x, domain=S.Integers) == \ (x >= -1) & (x < oo) & Eq(Mod(x, 1), 0) assert isolve((x ** 2 + 3 * x - 2) < 0, x, domain=S.Integers) == \ (x >= -3) & (x <= 0) & Eq(Mod(x, 1), 0) assert isolve((x ** 2 + 3 * x - 2) > 0, x, domain=S.Integers) == \ ((x >= 1) & (x < oo) & Eq(Mod(x, 1), 0)) | ( (x <= -4) & (x > -oo) & Eq(Mod(x, 1), 0)) def test_issue_10671_12466(): assert solveset(sin(y), y, Interval(0, pi)) == FiniteSet(0, pi) i = Interval(1, 10) assert solveset((1/x).diff(x) < 0, x, i) == i assert solveset((log(x - 6)/x) <= 0, x, S.Reals) == \ Interval.Lopen(6, 7) def test__solve_inequality(): for op in (Gt, Lt, Le, Ge, Eq, Ne): assert _solve_inequality(op(x, 1), x).lhs == x assert _solve_inequality(op(S.One, x), x).lhs == x # don't get tricked by symbol on right: solve it assert _solve_inequality(Eq(2*x - 1, x), x) == Eq(x, 1) ie = Eq(S.One, y) assert _solve_inequality(ie, x) == ie for fx in (x**2, exp(x), sin(x) + cos(x), x*(1 + x)): for c in (0, 1): e = 2*fx - c > 0 assert _solve_inequality(e, x, linear=True) == ( fx > c/S(2)) assert _solve_inequality(2*x**2 + 2*x - 1 < 0, x, linear=True) == ( x*(x + 1) < S.Half) assert _solve_inequality(Eq(x*y, 1), x) == Eq(x*y, 1) nz = Symbol('nz', nonzero=True) assert _solve_inequality(Eq(x*nz, 1), x) == Eq(x, 1/nz) assert _solve_inequality(x*nz < 1, x) == (x*nz < 1) a = Symbol('a', positive=True) assert _solve_inequality(a/x > 1, x) == (S.Zero < x) & (x < a) assert _solve_inequality(a/x > 1, x, linear=True) == (1/x > 1/a) # make sure to include conditions under which solution is valid e = Eq(1 - x, x*(1/x - 1)) assert _solve_inequality(e, x) == Ne(x, 0) assert _solve_inequality(x < x*(1/x - 1), x) == (x < S.Half) & Ne(x, 0) def test__pt(): from sympy.solvers.inequalities import _pt assert _pt(-oo, oo) == 0 assert _pt(S.One, S(3)) == 2 assert _pt(S.One, oo) == _pt(oo, S.One) == 2 assert _pt(S.One, -oo) == _pt(-oo, S.One) == S.Half assert _pt(S.NegativeOne, oo) == _pt(oo, S.NegativeOne) == Rational(-1, 2) assert _pt(S.NegativeOne, -oo) == _pt(-oo, S.NegativeOne) == -2 assert _pt(x, oo) == _pt(oo, x) == x + 1 assert _pt(x, -oo) == _pt(-oo, x) == x - 1 raises(ValueError, lambda: _pt(Dummy('i', infinite=True), S.One))
5a9da18efd4deae98dec85445ed0368bad547376fecbd40496583711c5224bdf
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 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] raises(TypeError, lambda: decompogen(x < 5, x)) def test_decompogen_poly(): assert decompogen(x**4 + 2*x**2 + 1, x) == [x**2 + 2*x + 1, x**2] assert decompogen(x**4 + 2*x**3 - x - 1, x) == [x**2 - x - 1, x**2 + x] @XFAIL def test_decompogen_fails(): A = lambda x: x**2 + 2*x + 3 B = lambda x: 4*x**2 + 5*x + 6 assert decompogen(A(x*exp(x)), x) == [x**2 + 2*x + 3, x*exp(x)] assert decompogen(A(B(x)), x) == [x**2 + 2*x + 3, 4*x**2 + 5*x + 6] assert decompogen(A(1/x + 1/x**2), x) == [x**2 + 2*x + 3, 1/x + 1/x**2] assert decompogen(A(1/x + 2/(x + 1)), x) == [x**2 + 2*x + 3, 1/x + 2/(x + 1)] def test_compogen(): assert compogen([sin(x), cos(x)], x) == sin(cos(x)) assert compogen([x**2 + x + 1, sin(x)], x) == sin(x)**2 + sin(x) + 1 assert compogen([sqrt(x), 6*x**2 - 5], x) == sqrt(6*x**2 - 5) assert compogen([sin(x), sqrt(x), cos(x), x**2 + 1], x) == sin(sqrt( cos(x**2 + 1))) assert compogen([Abs(x), x**2 + 3*x - 4, cos(x)], x) == Abs(cos(x)**2 + 3*cos(x) - 4) assert compogen([x**2 + x - sqrt(3)/2, sin(x)], x) == (sin(x)**2 + sin(x) - sqrt(3)/2) assert compogen([Abs(x), 3*x + cos(y)**2 - 4, cos(x)], x) == \ Abs(3*cos(x) + cos(y)**2 - 4) assert compogen([x**2 + 2*x + 1, x**2], x) == x**4 + 2*x**2 + 1 # the result is in unsimplified form assert compogen([x**2 - x - 1, x**2 + x], x) == -x**2 - x + (x**2 + x)**2 - 1
224df761c6bc05a5e99c0efad7b20842e1189cce50a46613e2aac3f5085c2ef9
from sympy.core.numbers import (Float, I, Rational, pi) from sympy.core.relational import Eq from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import sin from sympy.integrals.integrals import Integral from sympy.matrices.dense import Matrix from mpmath import mnorm, mpf from sympy.solvers import nsolve from sympy.utilities.lambdify import lambdify from sympy.testing.pytest import raises, XFAIL from sympy.utilities.decorator import conserve_mpmath_dps @XFAIL def test_nsolve_fail(): x = symbols('x') # Sometimes it is better to use the numerator (issue 4829) # but sometimes it is not (issue 11768) so leave this to # the discretion of the user ans = nsolve(x**2/(1 - x)/(1 - 2*x)**2 - 100, x, 0) assert ans > 0.46 and ans < 0.47 def test_nsolve_denominator(): x = symbols('x') # Test that nsolve uses the full expression (numerator and denominator). ans = nsolve((x**2 + 3*x + 2)/(x + 2), -2.1) # The root -2 was divided out, so make sure we don't find it. assert ans == -1.0 def test_nsolve(): # onedimensional x = Symbol('x') assert nsolve(sin(x), 2) - pi.evalf() < 1e-15 assert nsolve(Eq(2*x, 2), x, -10) == nsolve(2*x - 2, -10) # Testing checks on number of inputs raises(TypeError, lambda: nsolve(Eq(2*x, 2))) raises(TypeError, lambda: nsolve(Eq(2*x, 2), x, 1, 2)) # multidimensional x1 = Symbol('x1') x2 = Symbol('x2') f1 = 3 * x1**2 - 2 * x2**2 - 1 f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8 f = Matrix((f1, f2)).T F = lambdify((x1, x2), f.T, modules='mpmath') for x0 in [(-1, 1), (1, -2), (4, 4), (-4, -4)]: x = nsolve(f, (x1, x2), x0, tol=1.e-8) assert mnorm(F(*x), 1) <= 1.e-10 # The Chinese mathematician Zhu Shijie was the very first to solve this # nonlinear system 700 years ago (z was added to make it 3-dimensional) x = Symbol('x') y = Symbol('y') z = Symbol('z') f1 = -x + 2*y f2 = (x**2 + x*(y**2 - 2) - 4*y) / (x + 4) f3 = sqrt(x**2 + y**2)*z f = Matrix((f1, f2, f3)).T F = lambdify((x, y, z), f.T, modules='mpmath') def getroot(x0): root = nsolve(f, (x, y, z), x0) assert mnorm(F(*root), 1) <= 1.e-8 return root assert list(map(round, getroot((1, 1, 1)))) == [2.0, 1.0, 0.0] assert nsolve([Eq( f1, 0), Eq(f2, 0), Eq(f3, 0)], [x, y, z], (1, 1, 1)) # just see that it works a = Symbol('a') assert abs(nsolve(1/(0.001 + a)**3 - 6/(0.9 - a)**3, a, 0.3) - mpf('0.31883011387318591')) < 1e-15 def test_issue_6408(): x = Symbol('x') assert nsolve(Piecewise((x, x < 1), (x**2, True)), x, 2) == 0.0 def test_issue_6408_integral(): x, y = symbols('x y') assert nsolve(Integral(x*y, (x, 0, 5)), y, 2) == 0.0 @conserve_mpmath_dps def test_increased_dps(): # Issue 8564 import mpmath mpmath.mp.dps = 128 x = Symbol('x') e1 = x**2 - pi q = nsolve(e1, x, 3.0) assert abs(sqrt(pi).evalf(128) - q) < 1e-128 def test_nsolve_precision(): x, y = symbols('x y') sol = nsolve(x**2 - pi, x, 3, prec=128) assert abs(sqrt(pi).evalf(128) - sol) < 1e-128 assert isinstance(sol, Float) sols = nsolve((y**2 - x, x**2 - pi), (x, y), (3, 3), prec=128) assert isinstance(sols, Matrix) assert sols.shape == (2, 1) assert abs(sqrt(pi).evalf(128) - sols[0]) < 1e-128 assert abs(sqrt(sqrt(pi)).evalf(128) - sols[1]) < 1e-128 assert all(isinstance(i, Float) for i in sols) def test_nsolve_complex(): x, y = symbols('x y') assert nsolve(x**2 + 2, 1j) == sqrt(2.)*I assert nsolve(x**2 + 2, I) == sqrt(2.)*I assert nsolve([x**2 + 2, y**2 + 2], [x, y], [I, I]) == Matrix([sqrt(2.)*I, sqrt(2.)*I]) assert nsolve([x**2 + 2, y**2 + 2], [x, y], [I, I]) == Matrix([sqrt(2.)*I, sqrt(2.)*I]) def test_nsolve_dict_kwarg(): x, y = symbols('x y') # one variable assert nsolve(x**2 - 2, 1, dict = True) == \ [{x: sqrt(2.)}] # one variable with complex solution assert nsolve(x**2 + 2, I, dict = True) == \ [{x: sqrt(2.)*I}] # two variables assert nsolve([x**2 + y**2 - 5, x**2 - y**2 + 1], [x, y], [1, 1], dict = True) == \ [{x: sqrt(2.), y: sqrt(3.)}] def test_nsolve_rational(): x = symbols('x') assert nsolve(x - Rational(1, 3), 0, prec=100) == Rational(1, 3).evalf(100) def test_issue_14950(): x = Matrix(symbols('t s')) x0 = Matrix([17, 23]) eqn = x + x0 assert nsolve(eqn, x, x0) == -x0 assert nsolve(eqn.T, x.T, x0.T) == -x0
5063f7b968c5f2929081f3e27e675fbd2e544559b34a0ea6d8d912ecb1b39a2a
from sympy.core.function import (Derivative as D, Function) from sympy.core.relational import Eq from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.core import S from sympy.solvers.pde import (pde_separate, pde_separate_add, pde_separate_mul, pdsolve, classify_pde, checkpdesol) from sympy.testing.pytest import raises a, b, c, x, y = symbols('a b c x y') def test_pde_separate_add(): x, y, z, t = symbols("x,y,z,t") F, T, X, Y, Z, u = map(Function, 'FTXYZu') eq = Eq(D(u(x, t), x), D(u(x, t), t)*exp(u(x, t))) res = pde_separate_add(eq, u(x, t), [X(x), T(t)]) assert res == [D(X(x), x)*exp(-X(x)), D(T(t), t)*exp(T(t))] def test_pde_separate(): x, y, z, t = symbols("x,y,z,t") F, T, X, Y, Z, u = map(Function, 'FTXYZu') eq = Eq(D(u(x, t), x), D(u(x, t), t)*exp(u(x, t))) raises(ValueError, lambda: pde_separate(eq, u(x, t), [X(x), T(t)], 'div')) def test_pde_separate_mul(): x, y, z, t = symbols("x,y,z,t") c = Symbol("C", real=True) Phi = Function('Phi') F, R, T, X, Y, Z, u = map(Function, 'FRTXYZu') r, theta, z = symbols('r,theta,z') # Something simple :) eq = Eq(D(F(x, y, z), x) + D(F(x, y, z), y) + D(F(x, y, z), z), 0) # Duplicate arguments in functions raises( ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(x), u(z, z)])) # Wrong number of arguments raises(ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(x), Y(y)])) # Wrong variables: [x, y] -> [x, z] raises( ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(t), Y(x, y)])) assert pde_separate_mul(eq, F(x, y, z), [Y(y), u(x, z)]) == \ [D(Y(y), y)/Y(y), -D(u(x, z), x)/u(x, z) - D(u(x, z), z)/u(x, z)] assert pde_separate_mul(eq, F(x, y, z), [X(x), Y(y), Z(z)]) == \ [D(X(x), x)/X(x), -D(Z(z), z)/Z(z) - D(Y(y), y)/Y(y)] # wave equation wave = Eq(D(u(x, t), t, t), c**2*D(u(x, t), x, x)) res = pde_separate_mul(wave, u(x, t), [X(x), T(t)]) assert res == [D(X(x), x, x)/X(x), D(T(t), t, t)/(c**2*T(t))] # Laplace equation in cylindrical coords eq = Eq(1/r * D(Phi(r, theta, z), r) + D(Phi(r, theta, z), r, 2) + 1/r**2 * D(Phi(r, theta, z), theta, 2) + D(Phi(r, theta, z), z, 2), 0) # Separate z res = pde_separate_mul(eq, Phi(r, theta, z), [Z(z), u(theta, r)]) assert res == [D(Z(z), z, z)/Z(z), -D(u(theta, r), r, r)/u(theta, r) - D(u(theta, r), r)/(r*u(theta, r)) - D(u(theta, r), theta, theta)/(r**2*u(theta, r))] # Lets use the result to create a new equation... eq = Eq(res[1], c) # ...and separate theta... res = pde_separate_mul(eq, u(theta, r), [T(theta), R(r)]) assert res == [D(T(theta), theta, theta)/T(theta), -r*D(R(r), r)/R(r) - r**2*D(R(r), r, r)/R(r) - c*r**2] # ...or r... res = pde_separate_mul(eq, u(theta, r), [R(r), T(theta)]) assert res == [r*D(R(r), r)/R(r) + r**2*D(R(r), r, r)/R(r) + c*r**2, -D(T(theta), theta, theta)/T(theta)] def test_issue_11726(): x, t = symbols("x t") f = symbols("f", cls=Function) X, T = symbols("X T", cls=Function) u = f(x, t) eq = u.diff(x, 2) - u.diff(t, 2) res = pde_separate(eq, u, [T(x), X(t)]) assert res == [D(T(x), x, x)/T(x),D(X(t), t, t)/X(t)] def test_pde_classify(): # When more number of hints are added, add tests for classifying here. f = Function('f') eq1 = a*f(x,y) + b*f(x,y).diff(x) + c*f(x,y).diff(y) eq2 = 3*f(x,y) + 2*f(x,y).diff(x) + f(x,y).diff(y) eq3 = a*f(x,y) + b*f(x,y).diff(x) + 2*f(x,y).diff(y) eq4 = x*f(x,y) + f(x,y).diff(x) + 3*f(x,y).diff(y) eq5 = x**2*f(x,y) + x*f(x,y).diff(x) + x*y*f(x,y).diff(y) eq6 = y*x**2*f(x,y) + y*f(x,y).diff(x) + f(x,y).diff(y) for eq in [eq1, eq2, eq3]: assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',) for eq in [eq4, eq5, eq6]: assert classify_pde(eq) == ('1st_linear_variable_coeff',) def test_checkpdesol(): f, F = map(Function, ['f', 'F']) eq1 = a*f(x,y) + b*f(x,y).diff(x) + c*f(x,y).diff(y) eq2 = 3*f(x,y) + 2*f(x,y).diff(x) + f(x,y).diff(y) eq3 = a*f(x,y) + b*f(x,y).diff(x) + 2*f(x,y).diff(y) for eq in [eq1, eq2, eq3]: assert checkpdesol(eq, pdsolve(eq))[0] eq4 = x*f(x,y) + f(x,y).diff(x) + 3*f(x,y).diff(y) eq5 = 2*f(x,y) + 1*f(x,y).diff(x) + 3*f(x,y).diff(y) eq6 = f(x,y) + 1*f(x,y).diff(x) + 3*f(x,y).diff(y) assert checkpdesol(eq4, [pdsolve(eq5), pdsolve(eq6)]) == [ (False, (x - 2)*F(3*x - y)*exp(-x/S(5) - 3*y/S(5))), (False, (x - 1)*F(3*x - y)*exp(-x/S(10) - 3*y/S(10)))] for eq in [eq4, eq5, eq6]: assert checkpdesol(eq, pdsolve(eq))[0] sol = pdsolve(eq4) sol4 = Eq(sol.lhs - sol.rhs, 0) raises(NotImplementedError, lambda: checkpdesol(eq4, sol4, solve_for_func=False)) def test_solvefun(): f, F, G, H = map(Function, ['f', 'F', 'G', 'H']) eq1 = f(x,y) + f(x,y).diff(x) + f(x,y).diff(y) assert pdsolve(eq1) == Eq(f(x, y), F(x - y)*exp(-x/2 - y/2)) assert pdsolve(eq1, solvefun=G) == Eq(f(x, y), G(x - y)*exp(-x/2 - y/2)) assert pdsolve(eq1, solvefun=H) == Eq(f(x, y), H(x - y)*exp(-x/2 - y/2)) def test_pde_1st_linear_constant_coeff_homogeneous(): f, F = map(Function, ['f', 'F']) u = f(x, y) eq = 2*u + u.diff(x) + u.diff(y) assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',) sol = pdsolve(eq) assert sol == Eq(u, F(x - y)*exp(-x - y)) assert checkpdesol(eq, sol)[0] eq = 4 + (3*u.diff(x)/u) + (2*u.diff(y)/u) assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',) sol = pdsolve(eq) assert sol == Eq(u, F(2*x - 3*y)*exp(-S(12)*x/13 - S(8)*y/13)) assert checkpdesol(eq, sol)[0] eq = u + (6*u.diff(x)) + (7*u.diff(y)) assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',) sol = pdsolve(eq) assert sol == Eq(u, F(7*x - 6*y)*exp(-6*x/S(85) - 7*y/S(85))) assert checkpdesol(eq, sol)[0] eq = a*u + b*u.diff(x) + c*u.diff(y) sol = pdsolve(eq) assert checkpdesol(eq, sol)[0] def test_pde_1st_linear_constant_coeff(): f, F = map(Function, ['f', 'F']) u = f(x,y) eq = -2*u.diff(x) + 4*u.diff(y) + 5*u - exp(x + 3*y) sol = pdsolve(eq) assert sol == Eq(f(x,y), (F(4*x + 2*y)*exp(x/2) + exp(x + 4*y)/15)*exp(-y)) assert classify_pde(eq) == ('1st_linear_constant_coeff', '1st_linear_constant_coeff_Integral') assert checkpdesol(eq, sol)[0] eq = (u.diff(x)/u) + (u.diff(y)/u) + 1 - (exp(x + y)/u) sol = pdsolve(eq) assert sol == Eq(f(x, y), F(x - y)*exp(-x/2 - y/2) + exp(x + y)/3) assert classify_pde(eq) == ('1st_linear_constant_coeff', '1st_linear_constant_coeff_Integral') assert checkpdesol(eq, sol)[0] eq = 2*u + -u.diff(x) + 3*u.diff(y) + sin(x) sol = pdsolve(eq) assert sol == Eq(f(x, y), F(3*x + y)*exp(x/5 - 3*y/5) - 2*sin(x)/5 - cos(x)/5) assert classify_pde(eq) == ('1st_linear_constant_coeff', '1st_linear_constant_coeff_Integral') assert checkpdesol(eq, sol)[0] eq = u + u.diff(x) + u.diff(y) + x*y sol = pdsolve(eq) assert sol.expand() == Eq(f(x, y), x + y + (x - y)**2/4 - (x + y)**2/4 + F(x - y)*exp(-x/2 - y/2) - 2).expand() assert classify_pde(eq) == ('1st_linear_constant_coeff', '1st_linear_constant_coeff_Integral') assert checkpdesol(eq, sol)[0] eq = u + u.diff(x) + u.diff(y) + log(x) assert classify_pde(eq) == ('1st_linear_constant_coeff', '1st_linear_constant_coeff_Integral') def test_pdsolve_all(): f, F = map(Function, ['f', 'F']) u = f(x,y) eq = u + u.diff(x) + u.diff(y) + x**2*y sol = pdsolve(eq, hint = 'all') keys = ['1st_linear_constant_coeff', '1st_linear_constant_coeff_Integral', 'default', 'order'] assert sorted(sol.keys()) == keys assert sol['order'] == 1 assert sol['default'] == '1st_linear_constant_coeff' assert sol['1st_linear_constant_coeff'].expand() == Eq(f(x, y), -x**2*y + x**2 + 2*x*y - 4*x - 2*y + F(x - y)*exp(-x/2 - y/2) + 6).expand() def test_pdsolve_variable_coeff(): f, F = map(Function, ['f', 'F']) u = f(x, y) eq = x*(u.diff(x)) - y*(u.diff(y)) + y**2*u - y**2 sol = pdsolve(eq, hint="1st_linear_variable_coeff") assert sol == Eq(u, F(x*y)*exp(y**2/2) + 1) assert checkpdesol(eq, sol)[0] eq = x**2*u + x*u.diff(x) + x*y*u.diff(y) sol = pdsolve(eq, hint='1st_linear_variable_coeff') assert sol == Eq(u, F(y*exp(-x))*exp(-x**2/2)) assert checkpdesol(eq, sol)[0] eq = y*x**2*u + y*u.diff(x) + u.diff(y) sol = pdsolve(eq, hint='1st_linear_variable_coeff') assert sol == Eq(u, F(-2*x + y**2)*exp(-x**3/3)) assert checkpdesol(eq, sol)[0] eq = exp(x)**2*(u.diff(x)) + y sol = pdsolve(eq, hint='1st_linear_variable_coeff') assert sol == Eq(u, y*exp(-2*x)/2 + F(y)) assert checkpdesol(eq, sol)[0] eq = exp(2*x)*(u.diff(y)) + y*u - u sol = pdsolve(eq, hint='1st_linear_variable_coeff') assert sol == Eq(u, F(x)*exp(-y*(y - 2)*exp(-2*x)/2))
4db8e05c856bbb6d13c4e5eca9c78744049c6c254e26f3ef3d447ca5758501fd
from sympy.core.function import (Function, Lambda, expand) from sympy.core.numbers import (I, Rational) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import (rf, binomial, factorial) from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.polys.polytools import factor from sympy.solvers.recurr import rsolve, rsolve_hyper, rsolve_poly, rsolve_ratio from sympy.testing.pytest import raises, slow from sympy.abc import a, b y = Function('y') n, k = symbols('n,k', integer=True) C0, C1, C2 = symbols('C0,C1,C2') def test_rsolve_poly(): assert rsolve_poly([-1, -1, 1], 0, n) == 0 assert rsolve_poly([-1, -1, 1], 1, n) == -1 assert rsolve_poly([-1, n + 1], n, n) == 1 assert rsolve_poly([-1, 1], n, n) == C0 + (n**2 - n)/2 assert rsolve_poly([-n - 1, n], 1, n) == C1*n - 1 assert rsolve_poly([-4*n - 2, 1], 4*n + 1, n) == -1 assert rsolve_poly([-1, 1], n**5 + n**3, n) == \ C0 - n**3 / 2 - n**5 / 2 + n**2 / 6 + n**6 / 6 + 2*n**4 / 3 def test_rsolve_ratio(): solution = rsolve_ratio([-2*n**3 + n**2 + 2*n - 1, 2*n**3 + n**2 - 6*n, -2*n**3 - 11*n**2 - 18*n - 9, 2*n**3 + 13*n**2 + 22*n + 8], 0, n) assert solution in [ C1*((-2*n + 3)/(n**2 - 1))/3, (S.Half)*(C1*(-3 + 2*n)/(-1 + n**2)), (S.Half)*(C1*( 3 - 2*n)/( 1 - n**2)), (S.Half)*(C2*(-3 + 2*n)/(-1 + n**2)), (S.Half)*(C2*( 3 - 2*n)/( 1 - n**2)), ] def test_rsolve_hyper(): assert rsolve_hyper([-1, -1, 1], 0, n) in [ C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n, C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n, ] assert rsolve_hyper([n**2 - 2, -2*n - 1, 1], 0, n) in [ C0*rf(sqrt(2), n) + C1*rf(-sqrt(2), n), C1*rf(sqrt(2), n) + C0*rf(-sqrt(2), n), ] assert rsolve_hyper([n**2 - k, -2*n - 1, 1], 0, n) in [ C0*rf(sqrt(k), n) + C1*rf(-sqrt(k), n), C1*rf(sqrt(k), n) + C0*rf(-sqrt(k), n), ] assert rsolve_hyper( [2*n*(n + 1), -n**2 - 3*n + 2, n - 1], 0, n) == C1*factorial(n) + C0*2**n assert rsolve_hyper( [n + 2, -(2*n + 3)*(17*n**2 + 51*n + 39), n + 1], 0, n) == None assert rsolve_hyper([-n - 1, -1, 1], 0, n) == None assert rsolve_hyper([-1, 1], n, n).expand() == C0 + n**2/2 - n/2 assert rsolve_hyper([-1, 1], 1 + n, n).expand() == C0 + n**2/2 + n/2 assert rsolve_hyper([-1, 1], 3*(n + n**2), n).expand() == C0 + n**3 - n assert rsolve_hyper([-a, 1],0,n).expand() == C0*a**n assert rsolve_hyper([-a, 0, 1], 0, n).expand() == (-1)**n*C1*a**(n/2) + C0*a**(n/2) assert rsolve_hyper([1, 1, 1], 0, n).expand() == \ C0*(Rational(-1, 2) - sqrt(3)*I/2)**n + C1*(Rational(-1, 2) + sqrt(3)*I/2)**n assert rsolve_hyper([1, -2*n/a - 2/a, 1], 0, n) is None def recurrence_term(c, f): """Compute RHS of recurrence in f(n) with coefficients in c.""" return sum(c[i]*f.subs(n, n + i) for i in range(len(c))) def test_rsolve_bulk(): """Some bulk-generated tests.""" funcs = [ n, n + 1, n**2, n**3, n**4, n + n**2, 27*n + 52*n**2 - 3* n**3 + 12*n**4 - 52*n**5 ] coeffs = [ [-2, 1], [-2, -1, 1], [-1, 1, 1, -1, 1], [-n, 1], [n**2 - n + 12, 1] ] for p in funcs: # compute difference for c in coeffs: q = recurrence_term(c, p) if p.is_polynomial(n): assert rsolve_poly(c, q, n) == p # See issue 3956: #if p.is_hypergeometric(n): # assert rsolve_hyper(c, q, n) == p def test_rsolve(): f = y(n + 2) - y(n + 1) - y(n) h = sqrt(5)*(S.Half + S.Half*sqrt(5))**n \ - sqrt(5)*(S.Half - S.Half*sqrt(5))**n assert rsolve(f, y(n)) in [ C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n, C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n, ] assert rsolve(f, y(n), [0, 5]) == h assert rsolve(f, y(n), {0: 0, 1: 5}) == h assert rsolve(f, y(n), {y(0): 0, y(1): 5}) == h assert rsolve(y(n) - y(n - 1) - y(n - 2), y(n), [0, 5]) == h assert rsolve(Eq(y(n), y(n - 1) + y(n - 2)), y(n), [0, 5]) == h assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = (n - 1)*y(n + 2) - (n**2 + 3*n - 2)*y(n + 1) + 2*n*(n + 1)*y(n) g = C1*factorial(n) + C0*2**n h = -3*factorial(n) + 3*2**n assert rsolve(f, y(n)) == g assert rsolve(f, y(n), []) == g assert rsolve(f, y(n), {}) == g assert rsolve(f, y(n), [0, 3]) == h assert rsolve(f, y(n), {0: 0, 1: 3}) == h assert rsolve(f, y(n), {y(0): 0, y(1): 3}) == h assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = y(n) - y(n - 1) - 2 assert rsolve(f, y(n), {y(0): 0}) == 2*n assert rsolve(f, y(n), {y(0): 1}) == 2*n + 1 assert rsolve(f, y(n), {y(0): 0, y(1): 1}) is None assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = 3*y(n - 1) - y(n) - 1 assert rsolve(f, y(n), {y(0): 0}) == -3**n/2 + S.Half assert rsolve(f, y(n), {y(0): 1}) == 3**n/2 + S.Half assert rsolve(f, y(n), {y(0): 2}) == 3*3**n/2 + S.Half assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = y(n) - 1/n*y(n - 1) assert rsolve(f, y(n)) == C0/factorial(n) assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = y(n) - 1/n*y(n - 1) - 1 assert rsolve(f, y(n)) is None f = 2*y(n - 1) + (1 - n)*y(n)/n assert rsolve(f, y(n), {y(1): 1}) == 2**(n - 1)*n assert rsolve(f, y(n), {y(1): 2}) == 2**(n - 1)*n*2 assert rsolve(f, y(n), {y(1): 3}) == 2**(n - 1)*n*3 assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = (n - 1)*(n - 2)*y(n + 2) - (n + 1)*(n + 2)*y(n) assert rsolve(f, y(n), {y(3): 6, y(4): 24}) == n*(n - 1)*(n - 2) assert rsolve( f, y(n), {y(3): 6, y(4): -24}) == -n*(n - 1)*(n - 2)*(-1)**(n) assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 assert rsolve(Eq(y(n + 1), a*y(n)), y(n), {y(1): a}).simplify() == a**n assert rsolve(y(n) - a*y(n-2),y(n), \ {y(1): sqrt(a)*(a + b), y(2): a*(a - b)}).simplify() == \ a**(n/2)*(-(-1)**n*b + a) f = (-16*n**2 + 32*n - 12)*y(n - 1) + (4*n**2 - 12*n + 9)*y(n) yn = rsolve(f, y(n), {y(1): binomial(2*n + 1, 3)}) sol = 2**(2*n)*n*(2*n - 1)**2*(2*n + 1)/12 assert factor(expand(yn, func=True)) == sol sol = rsolve(y(n) + a*(y(n + 1) + y(n - 1))/2, y(n)) Y = lambda i: sol.subs(n, i) assert (Y(n) + a*(Y(n + 1) + Y(n - 1))/2).expand().cancel() == 0 assert rsolve((k + 1)*y(k), y(k)) is None assert (rsolve((k + 1)*y(k) + (k + 3)*y(k + 1) + (k + 5)*y(k + 2), y(k)) is None) assert rsolve(y(n) + y(n + 1) + 2**n + 3**n, y(n)) == (-1)**n*C0 - 2**n/3 - 3**n/4 def test_rsolve_raises(): x = Function('x') raises(ValueError, lambda: rsolve(y(n) - y(k + 1), y(n))) raises(ValueError, lambda: rsolve(y(n) - y(n + 1), x(n))) raises(ValueError, lambda: rsolve(y(n) - x(n + 1), y(n))) raises(ValueError, lambda: rsolve(y(n) - sqrt(n)*y(n + 1), y(n))) raises(ValueError, lambda: rsolve(y(n) - y(n + 1), y(n), {x(0): 0})) raises(ValueError, lambda: rsolve(y(n) + y(n + 1) + 2**n + cos(n), y(n))) def test_issue_6844(): f = y(n + 2) - y(n + 1) + y(n)/4 assert rsolve(f, y(n)) == 2**(-n)*(C0 + C1*n) assert rsolve(f, y(n), {y(0): 0, y(1): 1}) == 2*2**(-n)*n def test_issue_18751(): r = Symbol('r', real=True, positive=True) theta = Symbol('theta', real=True) f = y(n) - 2 * r * cos(theta) * y(n - 1) + r**2 * y(n - 2) assert rsolve(f, y(n)) == \ C0*(r*(cos(theta) - I*Abs(sin(theta))))**n + C1*(r*(cos(theta) + I*Abs(sin(theta))))**n def test_constant_naming(): #issue 8697 assert rsolve(y(n+3) - y(n+2) - y(n+1) + y(n), y(n)) == (-1)**n*C0+C1+C2*n assert rsolve(y(n+3)+3*y(n+2)+3*y(n+1)+y(n), y(n)).expand() == C0*(-1)**n + (-1)**n*C1*n + (-1)**n*C2*n**2 assert rsolve(y(n) - 2*y(n - 3) + 5*y(n - 2) - 4*y(n - 1),y(n),[1,3,8]) == 3*2**n - n - 2 #issue 19630 assert rsolve(y(n+3) - 3*y(n+1) + 2*y(n), y(n), {y(1):0, y(2):8, y(3):-2}) == (-2)**n + 2*n @slow def test_issue_15751(): f = y(n) + 21*y(n + 1) - 273*y(n + 2) - 1092*y(n + 3) + 1820*y(n + 4) + 1092*y(n + 5) - 273*y(n + 6) - 21*y(n + 7) + y(n + 8) assert rsolve(f, y(n)) is not None def test_issue_17990(): f = -10*y(n) + 4*y(n + 1) + 6*y(n + 2) + 46*y(n + 3) sol = rsolve(f, y(n)) expected = C0*((86*18**(S(1)/3)/69 + (-12 + (-1 + sqrt(3)*I)*(290412 + 3036*sqrt(9165))**(S(1)/3))*(1 - sqrt(3)*I)*(24201 + 253*sqrt(9165))** (S(1)/3)/276)/((1 - sqrt(3)*I)*(24201 + 253*sqrt(9165))**(S(1)/3)) )**n + C1*((86*18**(S(1)/3)/69 + (-12 + (-1 - sqrt(3)*I)*(290412 + 3036 *sqrt(9165))**(S(1)/3))*(1 + sqrt(3)*I)*(24201 + 253*sqrt(9165))** (S(1)/3)/276)/((1 + sqrt(3)*I)*(24201 + 253*sqrt(9165))**(S(1)/3)) )**n + C2*(-43*18**(S(1)/3)/(69*(24201 + 253*sqrt(9165))**(S(1)/3)) - S(1)/23 + (290412 + 3036*sqrt(9165))**(S(1)/3)/138)**n assert sol == expected e = sol.subs({C0: 1, C1: 1, C2: 1, n: 1}).evalf() assert abs(e + 0.130434782608696) < 1e-13
f457ae82c83d8c3d81c10886e041696fd7ce472b2de89741999aaad8668e807f
""" If the arbitrary constant class from issue 4435 is ever implemented, this should serve as a set of test cases. """ from sympy.core.function import Function from sympy.core.numbers import I 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.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (cosh, sinh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, cos, sin) from sympy.integrals.integrals import Integral from sympy.solvers.ode.ode import constantsimp, constant_renumber from sympy.testing.pytest import XFAIL x = Symbol('x') y = Symbol('y') z = Symbol('z') u2 = Symbol('u2') _a = Symbol('_a') C1 = Symbol('C1') C2 = Symbol('C2') C3 = Symbol('C3') f = Function('f') def test_constant_mul(): # We want C1 (Constant) below to absorb the y's, but not the x's assert constant_renumber(constantsimp(y*C1, [C1])) == C1*y assert constant_renumber(constantsimp(C1*y, [C1])) == C1*y assert constant_renumber(constantsimp(x*C1, [C1])) == x*C1 assert constant_renumber(constantsimp(C1*x, [C1])) == x*C1 assert constant_renumber(constantsimp(2*C1, [C1])) == C1 assert constant_renumber(constantsimp(C1*2, [C1])) == C1 assert constant_renumber(constantsimp(y*C1*x, [C1, y])) == C1*x assert constant_renumber(constantsimp(x*y*C1, [C1, y])) == x*C1 assert constant_renumber(constantsimp(y*x*C1, [C1, y])) == x*C1 assert constant_renumber(constantsimp(C1*x*y, [C1, y])) == C1*x assert constant_renumber(constantsimp(x*C1*y, [C1, y])) == x*C1 assert constant_renumber(constantsimp(C1*y*(y + 1), [C1])) == C1*y*(y+1) assert constant_renumber(constantsimp(y*C1*(y + 1), [C1])) == C1*y*(y+1) assert constant_renumber(constantsimp(x*(y*C1), [C1])) == x*y*C1 assert constant_renumber(constantsimp(x*(C1*y), [C1])) == x*y*C1 assert constant_renumber(constantsimp(C1*(x*y), [C1, y])) == C1*x assert constant_renumber(constantsimp((x*y)*C1, [C1, y])) == x*C1 assert constant_renumber(constantsimp((y*x)*C1, [C1, y])) == x*C1 assert constant_renumber(constantsimp(y*(y + 1)*C1, [C1, y])) == C1 assert constant_renumber(constantsimp((C1*x)*y, [C1, y])) == C1*x assert constant_renumber(constantsimp(y*(x*C1), [C1, y])) == x*C1 assert constant_renumber(constantsimp((x*C1)*y, [C1, y])) == x*C1 assert constant_renumber(constantsimp(C1*x*y*x*y*2, [C1, y])) == C1*x**2 assert constant_renumber(constantsimp(C1*x*y*z, [C1, y, z])) == C1*x assert constant_renumber(constantsimp(C1*x*y**2*sin(z), [C1, y, z])) == C1*x assert constant_renumber(constantsimp(C1*C1, [C1])) == C1 assert constant_renumber(constantsimp(C1*C2, [C1, C2])) == C1 assert constant_renumber(constantsimp(C2*C2, [C1, C2])) == C1 assert constant_renumber(constantsimp(C1*C1*C2, [C1, C2])) == C1 assert constant_renumber(constantsimp(C1*x*2**x, [C1])) == C1*x*2**x def test_constant_add(): assert constant_renumber(constantsimp(C1 + C1, [C1])) == C1 assert constant_renumber(constantsimp(C1 + 2, [C1])) == C1 assert constant_renumber(constantsimp(2 + C1, [C1])) == C1 assert constant_renumber(constantsimp(C1 + y, [C1, y])) == C1 assert constant_renumber(constantsimp(C1 + x, [C1])) == C1 + x assert constant_renumber(constantsimp(C1 + C1, [C1])) == C1 assert constant_renumber(constantsimp(C1 + C2, [C1, C2])) == C1 assert constant_renumber(constantsimp(C2 + C1, [C1, C2])) == C1 assert constant_renumber(constantsimp(C1 + C2 + C1, [C1, C2])) == C1 def test_constant_power_as_base(): assert constant_renumber(constantsimp(C1**C1, [C1])) == C1 assert constant_renumber(constantsimp(Pow(C1, C1), [C1])) == C1 assert constant_renumber(constantsimp(C1**C1, [C1])) == C1 assert constant_renumber(constantsimp(C1**C2, [C1, C2])) == C1 assert constant_renumber(constantsimp(C2**C1, [C1, C2])) == C1 assert constant_renumber(constantsimp(C2**C2, [C1, C2])) == C1 assert constant_renumber(constantsimp(C1**y, [C1, y])) == C1 assert constant_renumber(constantsimp(C1**x, [C1])) == C1**x assert constant_renumber(constantsimp(C1**2, [C1])) == C1 assert constant_renumber( constantsimp(C1**(x*y), [C1])) == C1**(x*y) def test_constant_power_as_exp(): assert constant_renumber(constantsimp(x**C1, [C1])) == x**C1 assert constant_renumber(constantsimp(y**C1, [C1, y])) == C1 assert constant_renumber(constantsimp(x**y**C1, [C1, y])) == x**C1 assert constant_renumber( constantsimp((x**y)**C1, [C1])) == (x**y)**C1 assert constant_renumber( constantsimp(x**(y**C1), [C1, y])) == x**C1 assert constant_renumber(constantsimp(x**C1**y, [C1, y])) == x**C1 assert constant_renumber( constantsimp(x**(C1**y), [C1, y])) == x**C1 assert constant_renumber( constantsimp((x**C1)**y, [C1])) == (x**C1)**y assert constant_renumber(constantsimp(2**C1, [C1])) == C1 assert constant_renumber(constantsimp(S(2)**C1, [C1])) == C1 assert constant_renumber(constantsimp(exp(C1), [C1])) == C1 assert constant_renumber( constantsimp(exp(C1 + x), [C1])) == C1*exp(x) assert constant_renumber(constantsimp(Pow(2, C1), [C1])) == C1 def test_constant_function(): assert constant_renumber(constantsimp(sin(C1), [C1])) == C1 assert constant_renumber(constantsimp(f(C1), [C1])) == C1 assert constant_renumber(constantsimp(f(C1, C1), [C1])) == C1 assert constant_renumber(constantsimp(f(C1, C2), [C1, C2])) == C1 assert constant_renumber(constantsimp(f(C2, C1), [C1, C2])) == C1 assert constant_renumber(constantsimp(f(C2, C2), [C1, C2])) == C1 assert constant_renumber( constantsimp(f(C1, x), [C1])) == f(C1, x) assert constant_renumber(constantsimp(f(C1, y), [C1, y])) == C1 assert constant_renumber(constantsimp(f(y, C1), [C1, y])) == C1 assert constant_renumber(constantsimp(f(C1, y, C2), [C1, C2, y])) == C1 def test_constant_function_multiple(): # The rules to not renumber in this case would be too complicated, and # dsolve is not likely to ever encounter anything remotely like this. assert constant_renumber( constantsimp(f(C1, C1, x), [C1])) == f(C1, C1, x) def test_constant_multiple(): assert constant_renumber(constantsimp(C1*2 + 2, [C1])) == C1 assert constant_renumber(constantsimp(x*2/C1, [C1])) == C1*x assert constant_renumber(constantsimp(C1**2*2 + 2, [C1])) == C1 assert constant_renumber( constantsimp(sin(2*C1) + x + sqrt(2), [C1])) == C1 + x assert constant_renumber(constantsimp(2*C1 + C2, [C1, C2])) == C1 def test_constant_repeated(): assert C1 + C1*x == constant_renumber( C1 + C1*x) def test_ode_solutions(): # only a few examples here, the rest will be tested in the actual dsolve tests assert constant_renumber(constantsimp(C1*exp(2*x) + exp(x)*(C2 + C3), [C1, C2, C3])) == \ constant_renumber(C1*exp(x) + C2*exp(2*x)) assert constant_renumber( constantsimp(Eq(f(x), I*C1*sinh(x/3) + C2*cosh(x/3)), [C1, C2]) ) == constant_renumber(Eq(f(x), C1*sinh(x/3) + C2*cosh(x/3))) assert constant_renumber(constantsimp(Eq(f(x), acos((-C1)/cos(x))), [C1])) == \ Eq(f(x), acos(C1/cos(x))) assert constant_renumber( constantsimp(Eq(log(f(x)/C1) + 2*exp(x/f(x)), 0), [C1]) ) == Eq(log(C1*f(x)) + 2*exp(x/f(x)), 0) assert constant_renumber(constantsimp(Eq(log(x*sqrt(2)*sqrt(1/x)*sqrt(f(x)) /C1) + x**2/(2*f(x)**2), 0), [C1])) == \ Eq(log(C1*sqrt(x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0) assert constant_renumber(constantsimp(Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(x/C1) - cos(f(x)/x)*exp(-f(x)/x)/2, 0), [C1])) == \ Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(C1*x) - cos(f(x)/x)* exp(-f(x)/x)/2, 0) assert constant_renumber(constantsimp(Eq(-Integral(-1/(sqrt(1 - u2**2)*u2), (u2, _a, x/f(x))) + log(f(x)/C1), 0), [C1])) == \ Eq(-Integral(-1/(u2*sqrt(1 - u2**2)), (u2, _a, x/f(x))) + log(C1*f(x)), 0) assert [constantsimp(i, [C1]) for i in [Eq(f(x), sqrt(-C1*x + x**2)), Eq(f(x), -sqrt(-C1*x + x**2))]] == \ [Eq(f(x), sqrt(x*(C1 + x))), Eq(f(x), -sqrt(x*(C1 + x)))] @XFAIL def test_nonlocal_simplification(): assert constantsimp(C1 + C2+x*C2, [C1, C2]) == C1 + C2*x def test_constant_Eq(): # C1 on the rhs is well-tested, but the lhs is only tested here assert constantsimp(Eq(C1, 3 + f(x)*x), [C1]) == Eq(x*f(x), C1) assert constantsimp(Eq(C1, 3 * f(x)*x), [C1]) == Eq(f(x)*x, C1)
f9c86a28608b9a1756ab35f96db716980a07cbae67099b3ef30af1dc86723929
from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.numbers import (Rational, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.matrices.dense import Matrix from sympy.ntheory.factor_ import factorint from sympy.simplify.powsimp import powsimp from sympy.core.function import _mexpand from sympy.core.sorting import default_sort_key, ordered from sympy.functions.elementary.trigonometric import sin from sympy.solvers.diophantine import diophantine from sympy.solvers.diophantine.diophantine import (diop_DN, diop_solve, diop_ternary_quadratic_normal, diop_general_pythagorean, diop_ternary_quadratic, diop_linear, diop_quadratic, diop_general_sum_of_squares, diop_general_sum_of_even_powers, descent, diop_bf_DN, divisible, equivalent, find_DN, ldescent, length, reconstruct, partition, power_representation, prime_as_sum_of_two_squares, square_factor, sum_of_four_squares, sum_of_three_squares, transformation_to_DN, transformation_to_normal, classify_diop, base_solution_linear, cornacchia, sqf_normal, gaussian_reduce, holzer, check_param, parametrize_ternary_quadratic, sum_of_powers, sum_of_squares, _diop_ternary_quadratic_normal, _nint_or_floor, _odd, _even, _remove_gcd, _can_do_sum_of_squares, DiophantineSolutionSet, GeneralPythagorean, BinaryQuadratic) from sympy.testing.pytest import slow, raises, XFAIL from sympy.utilities.iterables import ( signed_permutations) a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z = symbols( "a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z", integer=True) t_0, t_1, t_2, t_3, t_4, t_5, t_6 = symbols("t_:7", integer=True) m1, m2, m3 = symbols('m1:4', integer=True) n1 = symbols('n1', integer=True) def diop_simplify(eq): return _mexpand(powsimp(_mexpand(eq))) def test_input_format(): raises(TypeError, lambda: diophantine(sin(x))) raises(TypeError, lambda: diophantine(x/pi - 3)) def test_nosols(): # diophantine should sympify eq so that these are equivalent assert diophantine(3) == set() assert diophantine(S(3)) == set() def test_univariate(): assert diop_solve((x - 1)*(x - 2)**2) == {(1,), (2,)} assert diop_solve((x - 1)*(x - 2)) == {(1,), (2,)} def test_classify_diop(): raises(TypeError, lambda: classify_diop(x**2/3 - 1)) raises(ValueError, lambda: classify_diop(1)) raises(NotImplementedError, lambda: classify_diop(w*x*y*z - 1)) raises(NotImplementedError, lambda: classify_diop(x**3 + y**3 + z**4 - 90)) assert classify_diop(14*x**2 + 15*x - 42) == ( [x], {1: -42, x: 15, x**2: 14}, 'univariate') assert classify_diop(x*y + z) == ( [x, y, z], {x*y: 1, z: 1}, 'inhomogeneous_ternary_quadratic') assert classify_diop(x*y + z + w + x**2) == ( [w, x, y, z], {x*y: 1, w: 1, x**2: 1, z: 1}, 'inhomogeneous_general_quadratic') assert classify_diop(x*y + x*z + x**2 + 1) == ( [x, y, z], {x*y: 1, x*z: 1, x**2: 1, 1: 1}, 'inhomogeneous_general_quadratic') assert classify_diop(x*y + z + w + 42) == ( [w, x, y, z], {x*y: 1, w: 1, 1: 42, z: 1}, 'inhomogeneous_general_quadratic') assert classify_diop(x*y + z*w) == ( [w, x, y, z], {x*y: 1, w*z: 1}, 'homogeneous_general_quadratic') assert classify_diop(x*y**2 + 1) == ( [x, y], {x*y**2: 1, 1: 1}, 'cubic_thue') assert classify_diop(x**4 + y**4 + z**4 - (1 + 16 + 81)) == ( [x, y, z], {1: -98, x**4: 1, z**4: 1, y**4: 1}, 'general_sum_of_even_powers') assert classify_diop(x**2 + y**2 + z**2) == ( [x, y, z], {x**2: 1, y**2: 1, z**2: 1}, 'homogeneous_ternary_quadratic_normal') def test_linear(): assert diop_solve(x) == (0,) assert diop_solve(1*x) == (0,) assert diop_solve(3*x) == (0,) assert diop_solve(x + 1) == (-1,) assert diop_solve(2*x + 1) == (None,) assert diop_solve(2*x + 4) == (-2,) assert diop_solve(y + x) == (t_0, -t_0) assert diop_solve(y + x + 0) == (t_0, -t_0) assert diop_solve(y + x - 0) == (t_0, -t_0) assert diop_solve(0*x - y - 5) == (-5,) assert diop_solve(3*y + 2*x - 5) == (3*t_0 - 5, -2*t_0 + 5) assert diop_solve(2*x - 3*y - 5) == (3*t_0 - 5, 2*t_0 - 5) assert diop_solve(-2*x - 3*y - 5) == (3*t_0 + 5, -2*t_0 - 5) assert diop_solve(7*x + 5*y) == (5*t_0, -7*t_0) assert diop_solve(2*x + 4*y) == (2*t_0, -t_0) assert diop_solve(4*x + 6*y - 4) == (3*t_0 - 2, -2*t_0 + 2) assert diop_solve(4*x + 6*y - 3) == (None, None) assert diop_solve(0*x + 3*y - 4*z + 5) == (4*t_0 + 5, 3*t_0 + 5) assert diop_solve(4*x + 3*y - 4*z + 5) == (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5) assert diop_solve(4*x + 3*y - 4*z + 5, None) == (0, 5, 5) assert diop_solve(4*x + 2*y + 8*z - 5) == (None, None, None) assert diop_solve(5*x + 7*y - 2*z - 6) == (t_0, -3*t_0 + 2*t_1 + 6, -8*t_0 + 7*t_1 + 18) assert diop_solve(3*x - 6*y + 12*z - 9) == (2*t_0 + 3, t_0 + 2*t_1, t_1) assert diop_solve(6*w + 9*x + 20*y - z) == (t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 20*t_2) # to ignore constant factors, use diophantine raises(TypeError, lambda: diop_solve(x/2)) def test_quadratic_simple_hyperbolic_case(): # Simple Hyperbolic case: A = C = 0 and B != 0 assert diop_solve(3*x*y + 34*x - 12*y + 1) == \ {(-133, -11), (5, -57)} assert diop_solve(6*x*y + 2*x + 3*y + 1) == set() assert diop_solve(-13*x*y + 2*x - 4*y - 54) == {(27, 0)} assert diop_solve(-27*x*y - 30*x - 12*y - 54) == {(-14, -1)} assert diop_solve(2*x*y + 5*x + 56*y + 7) == {(-161, -3), (-47, -6), (-35, -12), (-29, -69), (-27, 64), (-21, 7), (-9, 1), (105, -2)} assert diop_solve(6*x*y + 9*x + 2*y + 3) == set() assert diop_solve(x*y + x + y + 1) == {(-1, t), (t, -1)} assert diophantine(48*x*y) def test_quadratic_elliptical_case(): # Elliptical case: B**2 - 4AC < 0 assert diop_solve(42*x**2 + 8*x*y + 15*y**2 + 23*x + 17*y - 4915) == {(-11, -1)} assert diop_solve(4*x**2 + 3*y**2 + 5*x - 11*y + 12) == set() assert diop_solve(x**2 + y**2 + 2*x + 2*y + 2) == {(-1, -1)} assert diop_solve(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950) == {(-15, 6)} assert diop_solve(10*x**2 + 12*x*y + 12*y**2 - 34) == \ {(-1, -1), (-1, 2), (1, -2), (1, 1)} def test_quadratic_parabolic_case(): # Parabolic case: B**2 - 4AC = 0 assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 5*x + 7*y + 16) assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 6*x + 12*y - 6) assert check_solutions(8*x**2 + 24*x*y + 18*y**2 + 4*x + 6*y - 7) assert check_solutions(-4*x**2 + 4*x*y - y**2 + 2*x - 3) assert check_solutions(x**2 + 2*x*y + y**2 + 2*x + 2*y + 1) assert check_solutions(x**2 - 2*x*y + y**2 + 2*x + 2*y + 1) assert check_solutions(y**2 - 41*x + 40) def test_quadratic_perfect_square(): # B**2 - 4*A*C > 0 # B**2 - 4*A*C is a perfect square assert check_solutions(48*x*y) assert check_solutions(4*x**2 - 5*x*y + y**2 + 2) assert check_solutions(-2*x**2 - 3*x*y + 2*y**2 -2*x - 17*y + 25) assert check_solutions(12*x**2 + 13*x*y + 3*y**2 - 2*x + 3*y - 12) assert check_solutions(8*x**2 + 10*x*y + 2*y**2 - 32*x - 13*y - 23) assert check_solutions(4*x**2 - 4*x*y - 3*y- 8*x - 3) assert check_solutions(- 4*x*y - 4*y**2 - 3*y- 5*x - 10) assert check_solutions(x**2 - y**2 - 2*x - 2*y) assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y) assert check_solutions(4*x**2 - 9*y**2 - 4*x - 12*y - 3) def test_quadratic_non_perfect_square(): # B**2 - 4*A*C is not a perfect square # Used check_solutions() since the solutions are complex expressions involving # square roots and exponents assert check_solutions(x**2 - 2*x - 5*y**2) assert check_solutions(3*x**2 - 2*y**2 - 2*x - 2*y) assert check_solutions(x**2 - x*y - y**2 - 3*y) assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y) assert BinaryQuadratic(x**2 + y**2 + 2*x + 2*y + 2).solve() == {(-1, -1)} def test_issue_9106(): eq = -48 - 2*x*(3*x - 1) + y*(3*y - 1) v = (x, y) for sol in diophantine(eq): assert not diop_simplify(eq.xreplace(dict(zip(v, sol)))) def test_issue_18138(): eq = x**2 - x - y**2 v = (x, y) for sol in diophantine(eq): assert not diop_simplify(eq.xreplace(dict(zip(v, sol)))) @slow def test_quadratic_non_perfect_slow(): assert check_solutions(8*x**2 + 10*x*y - 2*y**2 - 32*x - 13*y - 23) # This leads to very large numbers. # assert check_solutions(5*x**2 - 13*x*y + y**2 - 4*x - 4*y - 15) assert check_solutions(-3*x**2 - 2*x*y + 7*y**2 - 5*x - 7) assert check_solutions(-4 - x + 4*x**2 - y - 3*x*y - 4*y**2) assert check_solutions(1 + 2*x + 2*x**2 + 2*y + x*y - 2*y**2) def test_DN(): # Most of the test cases were adapted from, # Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004. # https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf # others are verified using Wolfram Alpha. # Covers cases where D <= 0 or D > 0 and D is a square or N = 0 # Solutions are straightforward in these cases. assert diop_DN(3, 0) == [(0, 0)] assert diop_DN(-17, -5) == [] assert diop_DN(-19, 23) == [(2, 1)] assert diop_DN(-13, 17) == [(2, 1)] assert diop_DN(-15, 13) == [] assert diop_DN(0, 5) == [] assert diop_DN(0, 9) == [(3, t)] assert diop_DN(9, 0) == [(3*t, t)] assert diop_DN(16, 24) == [] assert diop_DN(9, 180) == [(18, 4)] assert diop_DN(9, -180) == [(12, 6)] assert diop_DN(7, 0) == [(0, 0)] # When equation is x**2 + y**2 = N # Solutions are interchangeable assert diop_DN(-1, 5) == [(2, 1), (1, 2)] assert diop_DN(-1, 169) == [(12, 5), (5, 12), (13, 0), (0, 13)] # D > 0 and D is not a square # N = 1 assert diop_DN(13, 1) == [(649, 180)] assert diop_DN(980, 1) == [(51841, 1656)] assert diop_DN(981, 1) == [(158070671986249, 5046808151700)] assert diop_DN(986, 1) == [(49299, 1570)] assert diop_DN(991, 1) == [(379516400906811930638014896080, 12055735790331359447442538767)] assert diop_DN(17, 1) == [(33, 8)] assert diop_DN(19, 1) == [(170, 39)] # N = -1 assert diop_DN(13, -1) == [(18, 5)] assert diop_DN(991, -1) == [] assert diop_DN(41, -1) == [(32, 5)] assert diop_DN(290, -1) == [(17, 1)] assert diop_DN(21257, -1) == [(13913102721304, 95427381109)] assert diop_DN(32, -1) == [] # |N| > 1 # Some tests were created using calculator at # http://www.numbertheory.org/php/patz.html assert diop_DN(13, -4) == [(3, 1), (393, 109), (36, 10)] # Source I referred returned (3, 1), (393, 109) and (-3, 1) as fundamental solutions # So (-3, 1) and (393, 109) should be in the same equivalent class assert equivalent(-3, 1, 393, 109, 13, -4) == True assert diop_DN(13, 27) == [(220, 61), (40, 11), (768, 213), (12, 3)] assert set(diop_DN(157, 12)) == {(13, 1), (10663, 851), (579160, 46222), (483790960, 38610722), (26277068347, 2097138361), (21950079635497, 1751807067011)} assert diop_DN(13, 25) == [(3245, 900)] assert diop_DN(192, 18) == [] assert diop_DN(23, 13) == [(-6, 1), (6, 1)] assert diop_DN(167, 2) == [(13, 1)] assert diop_DN(167, -2) == [] assert diop_DN(123, -2) == [(11, 1)] # One calculator returned [(11, 1), (-11, 1)] but both of these are in # the same equivalence class assert equivalent(11, 1, -11, 1, 123, -2) assert diop_DN(123, -23) == [(-10, 1), (10, 1)] assert diop_DN(0, 0, t) == [(0, t)] assert diop_DN(0, -1, t) == [] def test_bf_pell(): assert diop_bf_DN(13, -4) == [(3, 1), (-3, 1), (36, 10)] assert diop_bf_DN(13, 27) == [(12, 3), (-12, 3), (40, 11), (-40, 11)] assert diop_bf_DN(167, -2) == [] assert diop_bf_DN(1729, 1) == [(44611924489705, 1072885712316)] assert diop_bf_DN(89, -8) == [(9, 1), (-9, 1)] assert diop_bf_DN(21257, -1) == [(13913102721304, 95427381109)] assert diop_bf_DN(340, -4) == [(756, 41)] assert diop_bf_DN(-1, 0, t) == [(0, 0)] assert diop_bf_DN(0, 0, t) == [(0, t)] assert diop_bf_DN(4, 0, t) == [(2*t, t), (-2*t, t)] assert diop_bf_DN(3, 0, t) == [(0, 0)] assert diop_bf_DN(1, -2, t) == [] def test_length(): assert length(2, 1, 0) == 1 assert length(-2, 4, 5) == 3 assert length(-5, 4, 17) == 4 assert length(0, 4, 13) == 6 assert length(7, 13, 11) == 23 assert length(1, 6, 4) == 2 def is_pell_transformation_ok(eq): """ Test whether X*Y, X, or Y terms are present in the equation after transforming the equation using the transformation returned by transformation_to_pell(). If they are not present we are good. Moreover, coefficient of X**2 should be a divisor of coefficient of Y**2 and the constant term. """ A, B = transformation_to_DN(eq) u = (A*Matrix([X, Y]) + B)[0] v = (A*Matrix([X, Y]) + B)[1] simplified = diop_simplify(eq.subs(zip((x, y), (u, v)))) coeff = dict([reversed(t.as_independent(*[X, Y])) for t in simplified.args]) for term in [X*Y, X, Y]: if term in coeff.keys(): return False for term in [X**2, Y**2, 1]: if term not in coeff.keys(): coeff[term] = 0 if coeff[X**2] != 0: return divisible(coeff[Y**2], coeff[X**2]) and \ divisible(coeff[1], coeff[X**2]) return True def test_transformation_to_pell(): assert is_pell_transformation_ok(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y - 14) assert is_pell_transformation_ok(-17*x**2 + 19*x*y - 7*y**2 - 5*x - 13*y - 23) assert is_pell_transformation_ok(x**2 - y**2 + 17) assert is_pell_transformation_ok(-x**2 + 7*y**2 - 23) assert is_pell_transformation_ok(25*x**2 - 45*x*y + 5*y**2 - 5*x - 10*y + 5) assert is_pell_transformation_ok(190*x**2 + 30*x*y + y**2 - 3*y - 170*x - 130) assert is_pell_transformation_ok(x**2 - 2*x*y -190*y**2 - 7*y - 23*x - 89) assert is_pell_transformation_ok(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950) def test_find_DN(): assert find_DN(x**2 - 2*x - y**2) == (1, 1) assert find_DN(x**2 - 3*y**2 - 5) == (3, 5) assert find_DN(x**2 - 2*x*y - 4*y**2 - 7) == (5, 7) assert find_DN(4*x**2 - 8*x*y - y**2 - 9) == (20, 36) assert find_DN(7*x**2 - 2*x*y - y**2 - 12) == (8, 84) assert find_DN(-3*x**2 + 4*x*y -y**2) == (1, 0) assert find_DN(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y -14) == (101, -7825480) def test_ldescent(): # Equations which have solutions u = ([(13, 23), (3, -11), (41, -113), (4, -7), (-7, 4), (91, -3), (1, 1), (1, -1), (4, 32), (17, 13), (123689, 1), (19, -570)]) for a, b in u: w, x, y = ldescent(a, b) assert a*x**2 + b*y**2 == w**2 assert ldescent(-1, -1) is None def test_diop_ternary_quadratic_normal(): assert check_solutions(234*x**2 - 65601*y**2 - z**2) assert check_solutions(23*x**2 + 616*y**2 - z**2) assert check_solutions(5*x**2 + 4*y**2 - z**2) assert check_solutions(3*x**2 + 6*y**2 - 3*z**2) assert check_solutions(x**2 + 3*y**2 - z**2) assert check_solutions(4*x**2 + 5*y**2 - z**2) assert check_solutions(x**2 + y**2 - z**2) assert check_solutions(16*x**2 + y**2 - 25*z**2) assert check_solutions(6*x**2 - y**2 + 10*z**2) assert check_solutions(213*x**2 + 12*y**2 - 9*z**2) assert check_solutions(34*x**2 - 3*y**2 - 301*z**2) assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2) def is_normal_transformation_ok(eq): A = transformation_to_normal(eq) X, Y, Z = A*Matrix([x, y, z]) simplified = diop_simplify(eq.subs(zip((x, y, z), (X, Y, Z)))) coeff = dict([reversed(t.as_independent(*[X, Y, Z])) for t in simplified.args]) for term in [X*Y, Y*Z, X*Z]: if term in coeff.keys(): return False return True def test_transformation_to_normal(): assert is_normal_transformation_ok(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z) assert is_normal_transformation_ok(x**2 + 3*y**2 - 100*z**2) assert is_normal_transformation_ok(x**2 + 23*y*z) assert is_normal_transformation_ok(3*y**2 - 100*z**2 - 12*x*y) assert is_normal_transformation_ok(x**2 + 23*x*y - 34*y*z + 12*x*z) assert is_normal_transformation_ok(z**2 + 34*x*y - 23*y*z + x*z) assert is_normal_transformation_ok(x**2 + y**2 + z**2 - x*y - y*z - x*z) assert is_normal_transformation_ok(x**2 + 2*y*z + 3*z**2) assert is_normal_transformation_ok(x*y + 2*x*z + 3*y*z) assert is_normal_transformation_ok(2*x*z + 3*y*z) def test_diop_ternary_quadratic(): assert check_solutions(2*x**2 + z**2 + y**2 - 4*x*y) assert check_solutions(x**2 - y**2 - z**2 - x*y - y*z) assert check_solutions(3*x**2 - x*y - y*z - x*z) assert check_solutions(x**2 - y*z - x*z) assert check_solutions(5*x**2 - 3*x*y - x*z) assert check_solutions(4*x**2 - 5*y**2 - x*z) assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) assert check_solutions(8*x**2 - 12*y*z) assert check_solutions(45*x**2 - 7*y**2 - 8*x*y - z**2) assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y) assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z) assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 17*y*z) assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 16*y*z + 12*x*z) assert check_solutions(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z) assert check_solutions(x*y - 7*y*z + 13*x*z) assert diop_ternary_quadratic_normal(x**2 + y**2 + z**2) == (None, None, None) assert diop_ternary_quadratic_normal(x**2 + y**2) is None raises(ValueError, lambda: _diop_ternary_quadratic_normal((x, y, z), {x*y: 1, x**2: 2, y**2: 3, z**2: 0})) eq = -2*x*y - 6*x*z + 7*y**2 - 3*y*z + 4*z**2 assert diop_ternary_quadratic(eq) == (7, 2, 0) assert diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) == \ (1, 0, 2) assert diop_ternary_quadratic(x*y + 2*y*z) == \ (-2, 0, n1) eq = -5*x*y - 8*x*z - 3*y*z + 8*z**2 assert parametrize_ternary_quadratic(eq) == \ (8*p**2 - 3*p*q, -8*p*q + 8*q**2, 5*p*q) # this cannot be tested with diophantine because it will # factor into a product assert diop_solve(x*y + 2*y*z) == (-2*p*q, -n1*p**2 + p**2, p*q) def test_square_factor(): assert square_factor(1) == square_factor(-1) == 1 assert square_factor(0) == 1 assert square_factor(5) == square_factor(-5) == 1 assert square_factor(4) == square_factor(-4) == 2 assert square_factor(12) == square_factor(-12) == 2 assert square_factor(6) == 1 assert square_factor(18) == 3 assert square_factor(52) == 2 assert square_factor(49) == 7 assert square_factor(392) == 14 assert square_factor(factorint(-12)) == 2 def test_parametrize_ternary_quadratic(): assert check_solutions(x**2 + y**2 - z**2) assert check_solutions(x**2 + 2*x*y + z**2) assert check_solutions(234*x**2 - 65601*y**2 - z**2) assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) assert check_solutions(x**2 - y**2 - z**2) assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y - 8*x*y) assert check_solutions(8*x*y + z**2) assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2) assert check_solutions(236*x**2 - 225*y**2 - 11*x*y - 13*y*z - 17*x*z) assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z) assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2) def test_no_square_ternary_quadratic(): assert check_solutions(2*x*y + y*z - 3*x*z) assert check_solutions(189*x*y - 345*y*z - 12*x*z) assert check_solutions(23*x*y + 34*y*z) assert check_solutions(x*y + y*z + z*x) assert check_solutions(23*x*y + 23*y*z + 23*x*z) def test_descent(): u = ([(13, 23), (3, -11), (41, -113), (91, -3), (1, 1), (1, -1), (17, 13), (123689, 1), (19, -570)]) for a, b in u: w, x, y = descent(a, b) assert a*x**2 + b*y**2 == w**2 # the docstring warns against bad input, so these are expected results # - can't both be negative raises(TypeError, lambda: descent(-1, -3)) # A can't be zero unless B != 1 raises(ZeroDivisionError, lambda: descent(0, 3)) # supposed to be square-free raises(TypeError, lambda: descent(4, 3)) def test_diophantine(): assert check_solutions((x - y)*(y - z)*(z - x)) assert check_solutions((x - y)*(x**2 + y**2 - z**2)) assert check_solutions((x - 3*y + 7*z)*(x**2 + y**2 - z**2)) assert check_solutions(x**2 - 3*y**2 - 1) assert check_solutions(y**2 + 7*x*y) assert check_solutions(x**2 - 3*x*y + y**2) assert check_solutions(z*(x**2 - y**2 - 15)) assert check_solutions(x*(2*y - 2*z + 5)) assert check_solutions((x**2 - 3*y**2 - 1)*(x**2 - y**2 - 15)) assert check_solutions((x**2 - 3*y**2 - 1)*(y - 7*z)) assert check_solutions((x**2 + y**2 - z**2)*(x - 7*y - 3*z + 4*w)) # Following test case caused problems in parametric representation # But this can be solved by factoring out y. # No need to use methods for ternary quadratic equations. assert check_solutions(y**2 - 7*x*y + 4*y*z) assert check_solutions(x**2 - 2*x + 1) assert diophantine(x - y) == diophantine(Eq(x, y)) # 18196 eq = x**4 + y**4 - 97 assert diophantine(eq, permute=True) == diophantine(-eq, permute=True) assert diophantine(3*x*pi - 2*y*pi) == {(2*t_0, 3*t_0)} eq = x**2 + y**2 + z**2 - 14 base_sol = {(1, 2, 3)} assert diophantine(eq) == base_sol complete_soln = set(signed_permutations(base_sol.pop())) assert diophantine(eq, permute=True) == complete_soln assert diophantine(x**2 + x*Rational(15, 14) - 3) == set() # test issue 11049 eq = 92*x**2 - 99*y**2 - z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ {(9, 7, 51)} assert diophantine(eq) == {( 891*p**2 + 9*q**2, -693*p**2 - 102*p*q + 7*q**2, 5049*p**2 - 1386*p*q - 51*q**2)} eq = 2*x**2 + 2*y**2 - z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ {(1, 1, 2)} assert diophantine(eq) == {( 2*p**2 - q**2, -2*p**2 + 4*p*q - q**2, 4*p**2 - 4*p*q + 2*q**2)} eq = 411*x**2+57*y**2-221*z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ {(2021, 2645, 3066)} assert diophantine(eq) == \ {(115197*p**2 - 446641*q**2, -150765*p**2 + 1355172*p*q - 584545*q**2, 174762*p**2 - 301530*p*q + 677586*q**2)} eq = 573*x**2+267*y**2-984*z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ {(49, 233, 127)} assert diophantine(eq) == \ {(4361*p**2 - 16072*q**2, -20737*p**2 + 83312*p*q - 76424*q**2, 11303*p**2 - 41474*p*q + 41656*q**2)} # this produces factors during reconstruction eq = x**2 + 3*y**2 - 12*z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ {(0, 2, 1)} assert diophantine(eq) == \ {(24*p*q, 2*p**2 - 24*q**2, p**2 + 12*q**2)} # solvers have not been written for every type raises(NotImplementedError, lambda: diophantine(x*y**2 + 1)) # rational expressions assert diophantine(1/x) == set() assert diophantine(1/x + 1/y - S.Half) == {(6, 3), (-2, 1), (4, 4), (1, -2), (3, 6)} assert diophantine(x**2 + y**2 +3*x- 5, permute=True) == \ {(-1, 1), (-4, -1), (1, -1), (1, 1), (-4, 1), (-1, -1), (4, 1), (4, -1)} #test issue 18186 assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(x, y), permute=True) == \ {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)} assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(y, x), permute=True) == \ {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)} # issue 18122 assert check_solutions(x**2-y) assert check_solutions(y**2-x) assert diophantine((x**2-y), t) == {(t, t**2)} assert diophantine((y**2-x), t) == {(t**2, -t)} def test_general_pythagorean(): from sympy.abc import a, b, c, d, e assert check_solutions(a**2 + b**2 + c**2 - d**2) assert check_solutions(a**2 + 4*b**2 + 4*c**2 - d**2) assert check_solutions(9*a**2 + 4*b**2 + 4*c**2 - d**2) assert check_solutions(9*a**2 + 4*b**2 - 25*d**2 + 4*c**2 ) assert check_solutions(9*a**2 - 16*d**2 + 4*b**2 + 4*c**2) assert check_solutions(-e**2 + 9*a**2 + 4*b**2 + 4*c**2 + 25*d**2) assert check_solutions(16*a**2 - b**2 + 9*c**2 + d**2 + 25*e**2) assert GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve(parameters=[x, y, z]) == \ {(x**2 + y**2 - z**2, 2*x*z, 2*y*z, x**2 + y**2 + z**2)} def test_diop_general_sum_of_squares_quick(): for i in range(3, 10): assert check_solutions(sum(i**2 for i in symbols(':%i' % i)) - i) assert diop_general_sum_of_squares(x**2 + y**2 - 2) is None assert diop_general_sum_of_squares(x**2 + y**2 + z**2 + 2) == set() eq = x**2 + y**2 + z**2 - (1 + 4 + 9) assert diop_general_sum_of_squares(eq) == \ {(1, 2, 3)} eq = u**2 + v**2 + x**2 + y**2 + z**2 - 1313 assert len(diop_general_sum_of_squares(eq, 3)) == 3 # issue 11016 var = symbols(':5') + (symbols('6', negative=True),) eq = Add(*[i**2 for i in var]) - 112 base_soln = {(0, 1, 1, 5, 6, -7), (1, 1, 1, 3, 6, -8), (2, 3, 3, 4, 5, -7), (0, 1, 1, 1, 3, -10), (0, 0, 4, 4, 4, -8), (1, 2, 3, 3, 5, -8), (0, 1, 2, 3, 7, -7), (2, 2, 4, 4, 6, -6), (1, 1, 3, 4, 6, -7), (0, 2, 3, 3, 3, -9), (0, 0, 2, 2, 2, -10), (1, 1, 2, 3, 4, -9), (0, 1, 1, 2, 5, -9), (0, 0, 2, 6, 6, -6), (1, 3, 4, 5, 5, -6), (0, 2, 2, 2, 6, -8), (0, 3, 3, 3, 6, -7), (0, 2, 3, 5, 5, -7), (0, 1, 5, 5, 5, -6)} assert diophantine(eq) == base_soln assert len(diophantine(eq, permute=True)) == 196800 # handle negated squares with signsimp assert diophantine(12 - x**2 - y**2 - z**2) == {(2, 2, 2)} # diophantine handles simplification, so classify_diop should # not have to look for additional patterns that are removed # by diophantine eq = a**2 + b**2 + c**2 + d**2 - 4 raises(NotImplementedError, lambda: classify_diop(-eq)) def test_diop_partition(): for n in [8, 10]: for k in range(1, 8): for p in partition(n, k): assert len(p) == k assert [p for p in partition(3, 5)] == [] assert [list(p) for p in partition(3, 5, 1)] == [ [0, 0, 0, 0, 3], [0, 0, 0, 1, 2], [0, 0, 1, 1, 1]] assert list(partition(0)) == [()] assert list(partition(1, 0)) == [()] assert [list(i) for i in partition(3)] == [[1, 1, 1], [1, 2], [3]] def test_prime_as_sum_of_two_squares(): for i in [5, 13, 17, 29, 37, 41, 2341, 3557, 34841, 64601]: a, b = prime_as_sum_of_two_squares(i) assert a**2 + b**2 == i assert prime_as_sum_of_two_squares(7) is None ans = prime_as_sum_of_two_squares(800029) assert ans == (450, 773) and type(ans[0]) is int def test_sum_of_three_squares(): for i in [0, 1, 2, 34, 123, 34304595905, 34304595905394941, 343045959052344, 800, 801, 802, 803, 804, 805, 806]: a, b, c = sum_of_three_squares(i) assert a**2 + b**2 + c**2 == i assert sum_of_three_squares(7) is None assert sum_of_three_squares((4**5)*15) is None assert sum_of_three_squares(25) == (5, 0, 0) assert sum_of_three_squares(4) == (0, 0, 2) def test_sum_of_four_squares(): from random import randint # this should never fail n = randint(1, 100000000000000) assert sum(i**2 for i in sum_of_four_squares(n)) == n assert sum_of_four_squares(0) == (0, 0, 0, 0) assert sum_of_four_squares(14) == (0, 1, 2, 3) assert sum_of_four_squares(15) == (1, 1, 2, 3) assert sum_of_four_squares(18) == (1, 2, 2, 3) assert sum_of_four_squares(19) == (0, 1, 3, 3) assert sum_of_four_squares(48) == (0, 4, 4, 4) def test_power_representation(): tests = [(1729, 3, 2), (234, 2, 4), (2, 1, 2), (3, 1, 3), (5, 2, 2), (12352, 2, 4), (32760, 2, 3)] for test in tests: n, p, k = test f = power_representation(n, p, k) while True: try: l = next(f) assert len(l) == k chk_sum = 0 for l_i in l: chk_sum = chk_sum + l_i**p assert chk_sum == n except StopIteration: break assert list(power_representation(20, 2, 4, True)) == \ [(1, 1, 3, 3), (0, 0, 2, 4)] raises(ValueError, lambda: list(power_representation(1.2, 2, 2))) raises(ValueError, lambda: list(power_representation(2, 0, 2))) raises(ValueError, lambda: list(power_representation(2, 2, 0))) assert list(power_representation(-1, 2, 2)) == [] assert list(power_representation(1, 1, 1)) == [(1,)] assert list(power_representation(3, 2, 1)) == [] assert list(power_representation(4, 2, 1)) == [(2,)] assert list(power_representation(3**4, 4, 6, zeros=True)) == \ [(1, 2, 2, 2, 2, 2), (0, 0, 0, 0, 0, 3)] assert list(power_representation(3**4, 4, 5, zeros=False)) == [] assert list(power_representation(-2, 3, 2)) == [(-1, -1)] assert list(power_representation(-2, 4, 2)) == [] assert list(power_representation(0, 3, 2, True)) == [(0, 0)] assert list(power_representation(0, 3, 2, False)) == [] # when we are dealing with squares, do feasibility checks assert len(list(power_representation(4**10*(8*10 + 7), 2, 3))) == 0 # there will be a recursion error if these aren't recognized big = 2**30 for i in [13, 10, 7, 5, 4, 2, 1]: assert list(sum_of_powers(big, 2, big - i)) == [] def test_assumptions(): """ Test whether diophantine respects the assumptions. """ #Test case taken from the below so question regarding assumptions in diophantine module #https://stackoverflow.com/questions/23301941/how-can-i-declare-natural-symbols-with-sympy m, n = symbols('m n', integer=True, positive=True) diof = diophantine(n**2 + m*n - 500) assert diof == {(5, 20), (40, 10), (95, 5), (121, 4), (248, 2), (499, 1)} a, b = symbols('a b', integer=True, positive=False) diof = diophantine(a*b + 2*a + 3*b - 6) assert diof == {(-15, -3), (-9, -4), (-7, -5), (-6, -6), (-5, -8), (-4, -14)} def check_solutions(eq): """ Determines whether solutions returned by diophantine() satisfy the original equation. Hope to generalize this so we can remove functions like check_ternay_quadratic, check_solutions_normal, check_solutions() """ s = diophantine(eq) factors = Mul.make_args(eq) var = list(eq.free_symbols) var.sort(key=default_sort_key) while s: solution = s.pop() for f in factors: if diop_simplify(f.subs(zip(var, solution))) == 0: break else: return False return True def test_diopcoverage(): eq = (2*x + y + 1)**2 assert diop_solve(eq) == {(t_0, -2*t_0 - 1)} eq = 2*x**2 + 6*x*y + 12*x + 4*y**2 + 18*y + 18 assert diop_solve(eq) == {(t, -t - 3), (2*t - 3, -t)} assert diop_quadratic(x + y**2 - 3) == {(-t**2 + 3, -t)} assert diop_linear(x + y - 3) == (t_0, 3 - t_0) assert base_solution_linear(0, 1, 2, t=None) == (0, 0) ans = (3*t - 1, -2*t + 1) assert base_solution_linear(4, 8, 12, t) == ans assert base_solution_linear(4, 8, 12, t=None) == tuple(_.subs(t, 0) for _ in ans) assert cornacchia(1, 1, 20) is None assert cornacchia(1, 1, 5) == {(2, 1)} assert cornacchia(1, 2, 17) == {(3, 2)} raises(ValueError, lambda: reconstruct(4, 20, 1)) assert gaussian_reduce(4, 1, 3) == (1, 1) eq = -w**2 - x**2 - y**2 + z**2 assert diop_general_pythagorean(eq) == \ diop_general_pythagorean(-eq) == \ (m1**2 + m2**2 - m3**2, 2*m1*m3, 2*m2*m3, m1**2 + m2**2 + m3**2) assert len(check_param(S(3) + x/3, S(4) + x/2, S(2), [x])) == 0 assert len(check_param(Rational(3, 2), S(4) + x, S(2), [x])) == 0 assert len(check_param(S(4) + x, Rational(3, 2), S(2), [x])) == 0 assert _nint_or_floor(16, 10) == 2 assert _odd(1) == (not _even(1)) == True assert _odd(0) == (not _even(0)) == False assert _remove_gcd(2, 4, 6) == (1, 2, 3) raises(TypeError, lambda: _remove_gcd((2, 4, 6))) assert sqf_normal(2*3**2*5, 2*5*11, 2*7**2*11) == \ (11, 1, 5) # it's ok if these pass some day when the solvers are implemented raises(NotImplementedError, lambda: diophantine(x**2 + y**2 + x*y + 2*y*z - 12)) raises(NotImplementedError, lambda: diophantine(x**3 + y**2)) assert diop_quadratic(x**2 + y**2 - 1**2 - 3**4) == \ {(-9, -1), (-9, 1), (-1, -9), (-1, 9), (1, -9), (1, 9), (9, -1), (9, 1)} def test_holzer(): # if the input is good, don't let it diverge in holzer() # (but see test_fail_holzer below) assert holzer(2, 7, 13, 4, 79, 23) == (2, 7, 13) # None in uv condition met; solution is not Holzer reduced # so this will hopefully change but is here for coverage assert holzer(2, 6, 2, 1, 1, 10) == (2, 6, 2) raises(ValueError, lambda: holzer(2, 7, 14, 4, 79, 23)) @XFAIL def test_fail_holzer(): eq = lambda x, y, z: a*x**2 + b*y**2 - c*z**2 a, b, c = 4, 79, 23 x, y, z = xyz = 26, 1, 11 X, Y, Z = ans = 2, 7, 13 assert eq(*xyz) == 0 assert eq(*ans) == 0 assert max(a*x**2, b*y**2, c*z**2) <= a*b*c assert max(a*X**2, b*Y**2, c*Z**2) <= a*b*c h = holzer(x, y, z, a, b, c) assert h == ans # it would be nice to get the smaller soln def test_issue_9539(): assert diophantine(6*w + 9*y + 20*x - z) == \ {(t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 9*t_2)} def test_issue_8943(): assert diophantine( 3*(x**2 + y**2 + z**2) - 14*(x*y + y*z + z*x)) == \ {(0, 0, 0)} def test_diop_sum_of_even_powers(): eq = x**4 + y**4 + z**4 - 2673 assert diop_solve(eq) == {(3, 6, 6), (2, 4, 7)} assert diop_general_sum_of_even_powers(eq, 2) == {(3, 6, 6), (2, 4, 7)} raises(NotImplementedError, lambda: diop_general_sum_of_even_powers(-eq, 2)) neg = symbols('neg', negative=True) eq = x**4 + y**4 + neg**4 - 2673 assert diop_general_sum_of_even_powers(eq) == {(-3, 6, 6)} assert diophantine(x**4 + y**4 + 2) == set() assert diop_general_sum_of_even_powers(x**4 + y**4 - 2, limit=0) == set() def test_sum_of_squares_powers(): tru = {(0, 0, 1, 1, 11), (0, 0, 5, 7, 7), (0, 1, 3, 7, 8), (0, 1, 4, 5, 9), (0, 3, 4, 7, 7), (0, 3, 5, 5, 8), (1, 1, 2, 6, 9), (1, 1, 6, 6, 7), (1, 2, 3, 3, 10), (1, 3, 4, 4, 9), (1, 5, 5, 6, 6), (2, 2, 3, 5, 9), (2, 3, 5, 6, 7), (3, 3, 4, 5, 8)} eq = u**2 + v**2 + x**2 + y**2 + z**2 - 123 ans = diop_general_sum_of_squares(eq, oo) # allow oo to be used assert len(ans) == 14 assert ans == tru raises(ValueError, lambda: list(sum_of_squares(10, -1))) assert list(sum_of_squares(-10, 2)) == [] assert list(sum_of_squares(2, 3)) == [] assert list(sum_of_squares(0, 3, True)) == [(0, 0, 0)] assert list(sum_of_squares(0, 3)) == [] assert list(sum_of_squares(4, 1)) == [(2,)] assert list(sum_of_squares(5, 1)) == [] assert list(sum_of_squares(50, 2)) == [(5, 5), (1, 7)] assert list(sum_of_squares(11, 5, True)) == [ (1, 1, 1, 2, 2), (0, 0, 1, 1, 3)] assert list(sum_of_squares(8, 8)) == [(1, 1, 1, 1, 1, 1, 1, 1)] assert [len(list(sum_of_squares(i, 5, True))) for i in range(30)] == [ 1, 1, 1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 3, 2, 1, 3, 3, 3, 3, 4, 3, 3, 2, 2, 4, 4, 4, 4, 5] assert [len(list(sum_of_squares(i, 5))) for i in range(30)] == [ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 3] for i in range(30): s1 = set(sum_of_squares(i, 5, True)) assert not s1 or all(sum(j**2 for j in t) == i for t in s1) s2 = set(sum_of_squares(i, 5)) assert all(sum(j**2 for j in t) == i for t in s2) raises(ValueError, lambda: list(sum_of_powers(2, -1, 1))) raises(ValueError, lambda: list(sum_of_powers(2, 1, -1))) assert list(sum_of_powers(-2, 3, 2)) == [(-1, -1)] assert list(sum_of_powers(-2, 4, 2)) == [] assert list(sum_of_powers(2, 1, 1)) == [(2,)] assert list(sum_of_powers(2, 1, 3, True)) == [(0, 0, 2), (0, 1, 1)] assert list(sum_of_powers(5, 1, 2, True)) == [(0, 5), (1, 4), (2, 3)] assert list(sum_of_powers(6, 2, 2)) == [] assert list(sum_of_powers(3**5, 3, 1)) == [] assert list(sum_of_powers(3**6, 3, 1)) == [(9,)] and (9**3 == 3**6) assert list(sum_of_powers(2**1000, 5, 2)) == [] def test__can_do_sum_of_squares(): assert _can_do_sum_of_squares(3, -1) is False assert _can_do_sum_of_squares(-3, 1) is False assert _can_do_sum_of_squares(0, 1) assert _can_do_sum_of_squares(4, 1) assert _can_do_sum_of_squares(1, 2) assert _can_do_sum_of_squares(2, 2) assert _can_do_sum_of_squares(3, 2) is False def test_diophantine_permute_sign(): from sympy.abc import a, b, c, d, e eq = a**4 + b**4 - (2**4 + 3**4) base_sol = {(2, 3)} assert diophantine(eq) == base_sol complete_soln = set(signed_permutations(base_sol.pop())) assert diophantine(eq, permute=True) == complete_soln eq = a**2 + b**2 + c**2 + d**2 + e**2 - 234 assert len(diophantine(eq)) == 35 assert len(diophantine(eq, permute=True)) == 62000 soln = {(-1, -1), (-1, 2), (1, -2), (1, 1)} assert diophantine(10*x**2 + 12*x*y + 12*y**2 - 34, permute=True) == soln @XFAIL def test_not_implemented(): eq = x**2 + y**4 - 1**2 - 3**4 assert diophantine(eq, syms=[x, y]) == {(9, 1), (1, 3)} def test_issue_9538(): eq = x - 3*y + 2 assert diophantine(eq, syms=[y,x]) == {(t_0, 3*t_0 - 2)} raises(TypeError, lambda: diophantine(eq, syms={y, x})) def test_ternary_quadratic(): # solution with 3 parameters s = diophantine(2*x**2 + y**2 - 2*z**2) p, q, r = ordered(S(s).free_symbols) assert s == {( p**2 - 2*q**2, -2*p**2 + 4*p*q - 4*p*r - 4*q**2, p**2 - 4*p*q + 2*q**2 - 4*q*r)} # solution with Mul in solution s = diophantine(x**2 + 2*y**2 - 2*z**2) assert s == {(4*p*q, p**2 - 2*q**2, p**2 + 2*q**2)} # solution with no Mul in solution s = diophantine(2*x**2 + 2*y**2 - z**2) assert s == {(2*p**2 - q**2, -2*p**2 + 4*p*q - q**2, 4*p**2 - 4*p*q + 2*q**2)} # reduced form when parametrized s = diophantine(3*x**2 + 72*y**2 - 27*z**2) assert s == {(24*p**2 - 9*q**2, 6*p*q, 8*p**2 + 3*q**2)} assert parametrize_ternary_quadratic( 3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) == ( 2*p**2 - 2*p*q - q**2, 2*p**2 + 2*p*q - q**2, 2*p**2 - 2*p*q + 3*q**2) assert parametrize_ternary_quadratic( 124*x**2 - 30*y**2 - 7729*z**2) == ( -1410*p**2 - 363263*q**2, 2700*p**2 + 30916*p*q - 695610*q**2, -60*p**2 + 5400*p*q + 15458*q**2) def test_diophantine_solution_set(): s1 = DiophantineSolutionSet([], []) assert set(s1) == set() assert s1.symbols == () assert s1.parameters == () raises(ValueError, lambda: s1.add((x,))) assert list(s1.dict_iterator()) == [] s2 = DiophantineSolutionSet([x, y], [t, u]) assert s2.symbols == (x, y) assert s2.parameters == (t, u) raises(ValueError, lambda: s2.add((1,))) s2.add((3, 4)) assert set(s2) == {(3, 4)} s2.update((3, 4), (-1, u)) assert set(s2) == {(3, 4), (-1, u)} raises(ValueError, lambda: s1.update(s2)) assert list(s2.dict_iterator()) == [{x: -1, y: u}, {x: 3, y: 4}] s3 = DiophantineSolutionSet([x, y, z], [t, u]) assert len(s3.parameters) == 2 s3.add((t**2 + u, t - u, 1)) assert set(s3) == {(t**2 + u, t - u, 1)} assert s3.subs(t, 2) == {(u + 4, 2 - u, 1)} assert s3(2) == {(u + 4, 2 - u, 1)} assert s3.subs({t: 7, u: 8}) == {(57, -1, 1)} assert s3(7, 8) == {(57, -1, 1)} assert s3.subs({t: 5}) == {(u + 25, 5 - u, 1)} assert s3(5) == {(u + 25, 5 - u, 1)} assert s3.subs(u, -3) == {(t**2 - 3, t + 3, 1)} assert s3(None, -3) == {(t**2 - 3, t + 3, 1)} assert s3.subs({t: 2, u: 8}) == {(12, -6, 1)} assert s3(2, 8) == {(12, -6, 1)} assert s3.subs({t: 5, u: -3}) == {(22, 8, 1)} assert s3(5, -3) == {(22, 8, 1)} raises(ValueError, lambda: s3.subs(x=1)) raises(ValueError, lambda: s3.subs(1, 2, 3)) raises(ValueError, lambda: s3.add(())) raises(ValueError, lambda: s3.add((1, 2, 3, 4))) raises(ValueError, lambda: s3.add((1, 2))) raises(ValueError, lambda: s3(1, 2, 3)) raises(TypeError, lambda: s3(t=1)) s4 = DiophantineSolutionSet([x, y], [t, u]) s4.add((t, 11*t)) s4.add((-t, 22*t)) assert s4(0, 0) == {(0, 0)} def test_quadratic_parameter_passing(): eq = -33*x*y + 3*y**2 solution = BinaryQuadratic(eq).solve(parameters=[t, u]) # test that parameters are passed all the way to the final solution assert solution == {(t, 11*t), (-t, 22*t)} assert solution(0, 0) == {(0, 0)}
862ddfd3460aa284e05ab8a19615ddba1028c3d5891039c1ae784adab1ffb1c2
from random import randint from sympy.core.function import Function from sympy.core.mul import Mul from sympy.core.numbers import (I, Rational, oo) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Dummy, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import tanh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.polys.polytools import Poly from sympy.simplify.ratsimp import ratsimp from sympy.solvers.ode.subscheck import checkodesol from sympy.testing.pytest import slow from sympy.solvers.ode.riccati import (riccati_normal, riccati_inverse_normal, riccati_reduced, match_riccati, inverse_transform_poly, limit_at_inf, check_necessary_conds, val_at_inf, construct_c_case_1, construct_c_case_2, construct_c_case_3, construct_d_case_4, construct_d_case_5, construct_d_case_6, rational_laurent_series, solve_riccati) f = Function('f') x = symbols('x') # These are the functions used to generate the tests # SHOULD NOT BE USED DIRECTLY IN TESTS def rand_rational(maxint): return Rational(randint(-maxint, maxint), randint(1, maxint)) def rand_poly(x, degree, maxint): return Poly([rand_rational(maxint) for _ in range(degree+1)], x) def rand_rational_function(x, degree, maxint): degnum = randint(1, degree) degden = randint(1, degree) num = rand_poly(x, degnum, maxint) den = rand_poly(x, degden, maxint) while den == Poly(0, x): den = rand_poly(x, degden, maxint) return num / den def find_riccati_ode(ratfunc, x, yf): y = ratfunc yp = y.diff(x) q1 = rand_rational_function(x, 1, 3) q2 = rand_rational_function(x, 1, 3) while q2 == 0: q2 = rand_rational_function(x, 1, 3) q0 = ratsimp(yp - q1*y - q2*y**2) eq = Eq(yf.diff(), q0 + q1*yf + q2*yf**2) sol = Eq(yf, y) assert checkodesol(eq, sol) == (True, 0) return eq, q0, q1, q2 # Testing functions start def test_riccati_transformation(): """ This function tests the transformation of the solution of a Riccati ODE to the solution of its corresponding normal Riccati ODE. Each test case 4 values - 1. w - The solution to be transformed 2. b1 - The coefficient of f(x) in the ODE. 3. b2 - The coefficient of f(x)**2 in the ODE. 4. y - The solution to the normal Riccati ODE. """ tests = [ ( x/(x - 1), (x**2 + 7)/3*x, x, -x**2/(x - 1) - x*(x**2/3 + S(7)/3)/2 - 1/(2*x) ), ( (2*x + 3)/(2*x + 2), (3 - 3*x)/(x + 1), 5*x, -5*x*(2*x + 3)/(2*x + 2) - (3 - 3*x)/(Mul(2, x + 1, evaluate=False)) - 1/(2*x) ), ( -1/(2*x**2 - 1), 0, (2 - x)/(4*x - 2), (2 - x)/((4*x - 2)*(2*x**2 - 1)) - (4*x - 2)*(Mul(-4, 2 - x, evaluate=False)/(4*x - \ 2)**2 - 1/(4*x - 2))/(Mul(2, 2 - x, evaluate=False)) ), ( x, (8*x - 12)/(12*x + 9), x**3/(6*x - 9), -x**4/(6*x - 9) - (8*x - 12)/(Mul(2, 12*x + 9, evaluate=False)) - (6*x - 9)*(-6*x**3/(6*x \ - 9)**2 + 3*x**2/(6*x - 9))/(2*x**3) )] for w, b1, b2, y in tests: assert y == riccati_normal(w, x, b1, b2) assert w == riccati_inverse_normal(y, x, b1, b2).cancel() # Test bp parameter in riccati_inverse_normal tests = [ ( (-2*x - 1)/(2*x**2 + 2*x - 2), -2/x, (-x - 1)/(4*x), 8*x**2*(1/(4*x) + (-x - 1)/(4*x**2))/(-x - 1)**2 + 4/(-x - 1), -2*x*(-1/(4*x) - (-x - 1)/(4*x**2))/(-x - 1) - (-2*x - 1)*(-x - 1)/(4*x*(2*x**2 + 2*x \ - 2)) + 1/x ), ( 3/(2*x**2), -2/x, (-x - 1)/(4*x), 8*x**2*(1/(4*x) + (-x - 1)/(4*x**2))/(-x - 1)**2 + 4/(-x - 1), -2*x*(-1/(4*x) - (-x - 1)/(4*x**2))/(-x - 1) + 1/x - Mul(3, -x - 1, evaluate=False)/(8*x**3) )] for w, b1, b2, bp, y in tests: assert y == riccati_normal(w, x, b1, b2) assert w == riccati_inverse_normal(y, x, b1, b2, bp).cancel() def test_riccati_reduced(): """ This function tests the transformation of a Riccati ODE to its normal Riccati ODE. Each test case 2 values - 1. eq - A Riccati ODE. 2. normal_eq - The normal Riccati ODE of eq. """ tests = [ ( f(x).diff(x) - x**2 - x*f(x) - x*f(x)**2, f(x).diff(x) + f(x)**2 + x**3 - x**2/4 - 3/(4*x**2) ), ( 6*x/(2*x + 9) + f(x).diff(x) - (x + 1)*f(x)**2/x, -3*x**2*(1/x + (-x - 1)/x**2)**2/(4*(-x - 1)**2) + Mul(6, \ -x - 1, evaluate=False)/(2*x + 9) + f(x)**2 + f(x).diff(x) \ - (-1 + (x + 1)/x)/(x*(-x - 1)) ), ( f(x)**2 + f(x).diff(x) - (x - 1)*f(x)/(-x - S(1)/2), -(2*x - 2)**2/(4*(2*x + 1)**2) + (2*x - 2)/(2*x + 1)**2 + \ f(x)**2 + f(x).diff(x) - 1/(2*x + 1) ), ( f(x).diff(x) - f(x)**2/x, f(x)**2 + f(x).diff(x) + 1/(4*x**2) ), ( -3*(-x**2 - x + 1)/(x**2 + 6*x + 1) + f(x).diff(x) + f(x)**2/x, f(x)**2 + f(x).diff(x) + (3*x**2/(x**2 + 6*x + 1) + 3*x/(x**2 \ + 6*x + 1) - 3/(x**2 + 6*x + 1))/x + 1/(4*x**2) ), ( 6*x/(2*x + 9) + f(x).diff(x) - (x + 1)*f(x)/x, False ), ( f(x)*f(x).diff(x) - 1/x + f(x)/3 + f(x)**2/(x**2 - 2), False )] for eq, normal_eq in tests: assert normal_eq == riccati_reduced(eq, f, x) def test_match_riccati(): """ This function tests if an ODE is Riccati or not. Each test case has 5 values - 1. eq - The Riccati ODE. 2. match - Boolean indicating if eq is a Riccati ODE. 3. b0 - 4. b1 - Coefficient of f(x) in eq. 5. b2 - Coefficient of f(x)**2 in eq. """ tests = [ # Test Rational Riccati ODEs ( f(x).diff(x) - (405*x**3 - 882*x**2 - 78*x + 92)/(243*x**4 \ - 945*x**3 + 846*x**2 + 180*x - 72) - 2 - f(x)**2/(3*x + 1) \ - (S(1)/3 - x)*f(x)/(S(1)/3 - 3*x/2), True, 45*x**3/(27*x**4 - 105*x**3 + 94*x**2 + 20*x - 8) - 98*x**2/ \ (27*x**4 - 105*x**3 + 94*x**2 + 20*x - 8) - 26*x/(81*x**4 - \ 315*x**3 + 282*x**2 + 60*x - 24) + 2 + 92/(243*x**4 - 945*x**3 \ + 846*x**2 + 180*x - 72), Mul(-1, 2 - 6*x, evaluate=False)/(9*x - 2), 1/(3*x + 1) ), ( f(x).diff(x) + 4*x/27 - (x/3 - 1)*f(x)**2 - (2*x/3 + \ 1)*f(x)/(3*x + 2) - S(10)/27 - (265*x**2 + 423*x + 162) \ /(324*x**3 + 216*x**2), True, -4*x/27 + S(10)/27 + 3/(6*x**3 + 4*x**2) + 47/(36*x**2 \ + 24*x) + 265/(324*x + 216), Mul(-1, -2*x - 3, evaluate=False)/(9*x + 6), x/3 - 1 ), ( f(x).diff(x) - (304*x**5 - 745*x**4 + 631*x**3 - 876*x**2 \ + 198*x - 108)/(36*x**6 - 216*x**5 + 477*x**4 - 567*x**3 + \ 360*x**2 - 108*x) - S(17)/9 - (x - S(3)/2)*f(x)/(x/2 - \ S(3)/2) - (x/3 - 3)*f(x)**2/(3*x), True, 304*x**4/(36*x**5 - 216*x**4 + 477*x**3 - 567*x**2 + 360*x - \ 108) - 745*x**3/(36*x**5 - 216*x**4 + 477*x**3 - 567*x**2 + \ 360*x - 108) + 631*x**2/(36*x**5 - 216*x**4 + 477*x**3 - 567* \ x**2 + 360*x - 108) - 292*x/(12*x**5 - 72*x**4 + 159*x**3 - \ 189*x**2 + 120*x - 36) + S(17)/9 - 12/(4*x**6 - 24*x**5 + \ 53*x**4 - 63*x**3 + 40*x**2 - 12*x) + 22/(4*x**5 - 24*x**4 \ + 53*x**3 - 63*x**2 + 40*x - 12), Mul(-1, 3 - 2*x, evaluate=False)/(x - 3), Mul(-1, 9 - x, evaluate=False)/(9*x) ), # Test Non-Rational Riccati ODEs ( f(x).diff(x) - x**(S(3)/2)/(x**(S(1)/2) - 2) + x**2*f(x) + \ x*f(x)**2/(x**(S(3)/4)), False, 0, 0, 0 ), ( f(x).diff(x) - sin(x**2) + exp(x)*f(x) + log(x)*f(x)**2, False, 0, 0, 0 ), ( f(x).diff(x) - tanh(x + sqrt(x)) + f(x) + x**4*f(x)**2, False, 0, 0, 0 ), # Test Non-Riccati ODEs ( (1 - x**2)*f(x).diff(x, 2) - 2*x*f(x).diff(x) + 20*f(x), False, 0, 0, 0 ), ( f(x).diff(x) - x**2 + x**3*f(x) + (x**2/(x + 1))*f(x)**3, False, 0, 0, 0 ), ( f(x).diff(x)*f(x)**2 + (x**2 - 1)/(x**3 + 1)*f(x) + 1/(2*x \ + 3) + f(x)**2, False, 0, 0, 0 )] for eq, res, b0, b1, b2 in tests: match, funcs = match_riccati(eq, f, x) assert match == res if res: assert [b0, b1, b2] == funcs def test_val_at_inf(): """ This function tests the valuation of rational function at oo. Each test case has 3 values - 1. num - Numerator of rational function. 2. den - Denominator of rational function. 3. val_inf - Valuation of rational function at oo """ tests = [ # degree(denom) > degree(numer) ( Poly(10*x**3 + 8*x**2 - 13*x + 6, x), Poly(-13*x**10 - x**9 + 5*x**8 + 7*x**7 + 10*x**6 + 6*x**5 - 7*x**4 + 11*x**3 - 8*x**2 + 5*x + 13, x), 7 ), ( Poly(1, x), Poly(-9*x**4 + 3*x**3 + 15*x**2 - 6*x - 14, x), 4 ), # degree(denom) == degree(numer) ( Poly(-6*x**3 - 8*x**2 + 8*x - 6, x), Poly(-5*x**3 + 12*x**2 - 6*x - 9, x), 0 ), # degree(denom) < degree(numer) ( Poly(12*x**8 - 12*x**7 - 11*x**6 + 8*x**5 + 3*x**4 - x**3 + x**2 - 11*x, x), Poly(-14*x**2 + x, x), -6 ), ( Poly(5*x**6 + 9*x**5 - 11*x**4 - 9*x**3 + x**2 - 4*x + 4, x), Poly(15*x**4 + 3*x**3 - 8*x**2 + 15*x + 12, x), -2 )] for num, den, val in tests: assert val_at_inf(num, den, x) == val def test_necessary_conds(): """ This function tests the necessary conditions for a Riccati ODE to have a rational particular solution. """ # Valuation at Infinity is an odd negative integer assert check_necessary_conds(-3, [1, 2, 4]) == False # Valuation at Infinity is a positive integer lesser than 2 assert check_necessary_conds(1, [1, 2, 4]) == False # Multiplicity of a pole is an odd integer greater than 1 assert check_necessary_conds(2, [3, 1, 6]) == False # All values are correct assert check_necessary_conds(-10, [1, 2, 8, 12]) == True def test_inverse_transform_poly(): """ This function tests the substitution x -> 1/x in rational functions represented using Poly. """ fns = [ (15*x**3 - 8*x**2 - 2*x - 6)/(18*x + 6), (180*x**5 + 40*x**4 + 80*x**3 + 30*x**2 - 60*x - 80)/(180*x**3 - 150*x**2 + 75*x + 12), (-15*x**5 - 36*x**4 + 75*x**3 - 60*x**2 - 80*x - 60)/(80*x**4 + 60*x**3 + 60*x**2 + 60*x - 80), (60*x**7 + 24*x**6 - 15*x**5 - 20*x**4 + 30*x**2 + 100*x - 60)/(240*x**2 - 20*x - 30), (30*x**6 - 12*x**5 + 15*x**4 - 15*x**2 + 10*x + 60)/(3*x**10 - 45*x**9 + 15*x**5 + 15*x**4 - 5*x**3 \ + 15*x**2 + 45*x - 15) ] for f in fns: num, den = [Poly(e, x) for e in f.as_numer_denom()] num, den = inverse_transform_poly(num, den, x) assert f.subs(x, 1/x).cancel() == num/den def test_limit_at_inf(): """ This function tests the limit at oo of a rational function. Each test case has 3 values - 1. num - Numerator of rational function. 2. den - Denominator of rational function. 3. limit_at_inf - Limit of rational function at oo """ tests = [ # deg(denom) > deg(numer) ( Poly(-12*x**2 + 20*x + 32, x), Poly(32*x**3 + 72*x**2 + 3*x - 32, x), 0 ), # deg(denom) < deg(numer) ( Poly(1260*x**4 - 1260*x**3 - 700*x**2 - 1260*x + 1400, x), Poly(6300*x**3 - 1575*x**2 + 756*x - 540, x), oo ), # deg(denom) < deg(numer), one of the leading coefficients is negative ( Poly(-735*x**8 - 1400*x**7 + 1680*x**6 - 315*x**5 - 600*x**4 + 840*x**3 - 525*x**2 \ + 630*x + 3780, x), Poly(1008*x**7 - 2940*x**6 - 84*x**5 + 2940*x**4 - 420*x**3 + 1512*x**2 + 105*x + 168, x), -oo ), # deg(denom) == deg(numer) ( Poly(105*x**7 - 960*x**6 + 60*x**5 + 60*x**4 - 80*x**3 + 45*x**2 + 120*x + 15, x), Poly(735*x**7 + 525*x**6 + 720*x**5 + 720*x**4 - 8400*x**3 - 2520*x**2 + 2800*x + 280, x), S(1)/7 ), ( Poly(288*x**4 - 450*x**3 + 280*x**2 - 900*x - 90, x), Poly(607*x**4 + 840*x**3 - 1050*x**2 + 420*x + 420, x), S(288)/607 )] for num, den, lim in tests: assert limit_at_inf(num, den, x) == lim def test_construct_c_case_1(): """ This function tests the Case 1 in the step to calculate coefficients of c-vectors. Each test case has 4 values - 1. num - Numerator of the rational function a(x). 2. den - Denominator of the rational function a(x). 3. pole - Pole of a(x) for which c-vector is being calculated. 4. c - The c-vector for the pole. """ tests = [ ( Poly(-3*x**3 + 3*x**2 + 4*x - 5, x, extension=True), Poly(4*x**8 + 16*x**7 + 9*x**5 + 12*x**4 + 6*x**3 + 12*x**2, x, extension=True), S(0), [[S(1)/2 + sqrt(6)*I/6], [S(1)/2 - sqrt(6)*I/6]] ), ( Poly(1200*x**3 + 1440*x**2 + 816*x + 560, x, extension=True), Poly(128*x**5 - 656*x**4 + 1264*x**3 - 1125*x**2 + 385*x + 49, x, extension=True), S(7)/4, [[S(1)/2 + sqrt(16367978)/634], [S(1)/2 - sqrt(16367978)/634]] ), ( Poly(4*x + 2, x, extension=True), Poly(18*x**4 + (2 - 18*sqrt(3))*x**3 + (14 - 11*sqrt(3))*x**2 + (4 - 6*sqrt(3))*x \ + 8*sqrt(3) + 16, x, domain='QQ<sqrt(3)>'), (S(1) + sqrt(3))/2, [[S(1)/2 + sqrt(Mul(4, 2*sqrt(3) + 4, evaluate=False)/(19*sqrt(3) + 44) + 1)/2], \ [S(1)/2 - sqrt(Mul(4, 2*sqrt(3) + 4, evaluate=False)/(19*sqrt(3) + 44) + 1)/2]] )] for num, den, pole, c in tests: assert construct_c_case_1(num, den, x, pole) == c def test_construct_c_case_2(): """ This function tests the Case 2 in the step to calculate coefficients of c-vectors. Each test case has 5 values - 1. num - Numerator of the rational function a(x). 2. den - Denominator of the rational function a(x). 3. pole - Pole of a(x) for which c-vector is being calculated. 4. mul - The multiplicity of the pole. 5. c - The c-vector for the pole. """ tests = [ # Testing poles with multiplicity 2 ( Poly(1, x, extension=True), Poly((x - 1)**2*(x - 2), x, extension=True), 1, 2, [[-I*(-1 - I)/2], [I*(-1 + I)/2]] ), ( Poly(3*x**5 - 12*x**4 - 7*x**3 + 1, x, extension=True), Poly((3*x - 1)**2*(x + 2)**2, x, extension=True), S(1)/3, 2, [[-S(89)/98], [-S(9)/98]] ), # Testing poles with multiplicity 4 ( Poly(x**3 - x**2 + 4*x, x, extension=True), Poly((x - 2)**4*(x + 5)**2, x, extension=True), 2, 4, [[7*sqrt(3)*(S(60)/343 - 4*sqrt(3)/7)/12, 2*sqrt(3)/7], \ [-7*sqrt(3)*(S(60)/343 + 4*sqrt(3)/7)/12, -2*sqrt(3)/7]] ), ( Poly(3*x**5 + x**4 + 3, x, extension=True), Poly((4*x + 1)**4*(x + 2), x, extension=True), -S(1)/4, 4, [[128*sqrt(439)*(-sqrt(439)/128 - S(55)/14336)/439, sqrt(439)/256], \ [-128*sqrt(439)*(sqrt(439)/128 - S(55)/14336)/439, -sqrt(439)/256]] ), # Testing poles with multiplicity 6 ( Poly(x**3 + 2, x, extension=True), Poly((3*x - 1)**6*(x**2 + 1), x, extension=True), S(1)/3, 6, [[27*sqrt(66)*(-sqrt(66)/54 - S(131)/267300)/22, -2*sqrt(66)/1485, sqrt(66)/162], \ [-27*sqrt(66)*(sqrt(66)/54 - S(131)/267300)/22, 2*sqrt(66)/1485, -sqrt(66)/162]] ), ( Poly(x**2 + 12, x, extension=True), Poly((x - sqrt(2))**6, x, extension=True), sqrt(2), 6, [[sqrt(14)*(S(6)/7 - 3*sqrt(14))/28, sqrt(7)/7, sqrt(14)], \ [-sqrt(14)*(S(6)/7 + 3*sqrt(14))/28, -sqrt(7)/7, -sqrt(14)]] )] for num, den, pole, mul, c in tests: assert construct_c_case_2(num, den, x, pole, mul) == c def test_construct_c_case_3(): """ This function tests the Case 3 in the step to calculate coefficients of c-vectors. """ assert construct_c_case_3() == [[1]] def test_construct_d_case_4(): """ This function tests the Case 4 in the step to calculate coefficients of the d-vector. Each test case has 4 values - 1. num - Numerator of the rational function a(x). 2. den - Denominator of the rational function a(x). 3. mul - Multiplicity of oo as a pole. 4. d - The d-vector. """ tests = [ # Tests with multiplicity at oo = 2 ( Poly(-x**5 - 2*x**4 + 4*x**3 + 2*x + 5, x, extension=True), Poly(9*x**3 - 2*x**2 + 10*x - 2, x, extension=True), 2, [[10*I/27, I/3, -3*I*(S(158)/243 - I/3)/2], \ [-10*I/27, -I/3, 3*I*(S(158)/243 + I/3)/2]] ), ( Poly(-x**6 + 9*x**5 + 5*x**4 + 6*x**3 + 5*x**2 + 6*x + 7, x, extension=True), Poly(x**4 + 3*x**3 + 12*x**2 - x + 7, x, extension=True), 2, [[-6*I, I, -I*(17 - I)/2], [6*I, -I, I*(17 + I)/2]] ), # Tests with multiplicity at oo = 4 ( Poly(-2*x**6 - x**5 - x**4 - 2*x**3 - x**2 - 3*x - 3, x, extension=True), Poly(3*x**2 + 10*x + 7, x, extension=True), 4, [[269*sqrt(6)*I/288, -17*sqrt(6)*I/36, sqrt(6)*I/3, -sqrt(6)*I*(S(16969)/2592 \ - 2*sqrt(6)*I/3)/4], [-269*sqrt(6)*I/288, 17*sqrt(6)*I/36, -sqrt(6)*I/3, \ sqrt(6)*I*(S(16969)/2592 + 2*sqrt(6)*I/3)/4]] ), ( Poly(-3*x**5 - 3*x**4 - 3*x**3 - x**2 - 1, x, extension=True), Poly(12*x - 2, x, extension=True), 4, [[41*I/192, 7*I/24, I/2, -I*(-S(59)/6912 - I)], \ [-41*I/192, -7*I/24, -I/2, I*(-S(59)/6912 + I)]] ), # Tests with multiplicity at oo = 4 ( Poly(-x**7 - x**5 - x**4 - x**2 - x, x, extension=True), Poly(x + 2, x, extension=True), 6, [[-5*I/2, 2*I, -I, I, -I*(-9 - 3*I)/2], [5*I/2, -2*I, I, -I, I*(-9 + 3*I)/2]] ), ( Poly(-x**7 - x**6 - 2*x**5 - 2*x**4 - x**3 - x**2 + 2*x - 2, x, extension=True), Poly(2*x - 2, x, extension=True), 6, [[3*sqrt(2)*I/4, 3*sqrt(2)*I/4, sqrt(2)*I/2, sqrt(2)*I/2, -sqrt(2)*I*(-S(7)/8 - \ 3*sqrt(2)*I/2)/2], [-3*sqrt(2)*I/4, -3*sqrt(2)*I/4, -sqrt(2)*I/2, -sqrt(2)*I/2, \ sqrt(2)*I*(-S(7)/8 + 3*sqrt(2)*I/2)/2]] )] for num, den, mul, d in tests: ser = rational_laurent_series(num, den, x, oo, mul, 1) assert construct_d_case_4(ser, mul//2) == d def test_construct_d_case_5(): """ This function tests the Case 5 in the step to calculate coefficients of the d-vector. Each test case has 3 values - 1. num - Numerator of the rational function a(x). 2. den - Denominator of the rational function a(x). 3. d - The d-vector. """ tests = [ ( Poly(2*x**3 + x**2 + x - 2, x, extension=True), Poly(9*x**3 + 5*x**2 + 2*x - 1, x, extension=True), [[sqrt(2)/3, -sqrt(2)/108], [-sqrt(2)/3, sqrt(2)/108]] ), ( Poly(3*x**5 + x**4 - x**3 + x**2 - 2*x - 2, x, domain='ZZ'), Poly(9*x**5 + 7*x**4 + 3*x**3 + 2*x**2 + 5*x + 7, x, domain='ZZ'), [[sqrt(3)/3, -2*sqrt(3)/27], [-sqrt(3)/3, 2*sqrt(3)/27]] ), ( Poly(x**2 - x + 1, x, domain='ZZ'), Poly(3*x**2 + 7*x + 3, x, domain='ZZ'), [[sqrt(3)/3, -5*sqrt(3)/9], [-sqrt(3)/3, 5*sqrt(3)/9]] )] for num, den, d in tests: # Multiplicity of oo is 0 ser = rational_laurent_series(num, den, x, oo, 0, 1) assert construct_d_case_5(ser) == d def test_construct_d_case_6(): """ This function tests the Case 6 in the step to calculate coefficients of the d-vector. Each test case has 3 values - 1. num - Numerator of the rational function a(x). 2. den - Denominator of the rational function a(x). 3. d - The d-vector. """ tests = [ ( Poly(-2*x**2 - 5, x, domain='ZZ'), Poly(4*x**4 + 2*x**2 + 10*x + 2, x, domain='ZZ'), [[S(1)/2 + I/2], [S(1)/2 - I/2]] ), ( Poly(-2*x**3 - 4*x**2 - 2*x - 5, x, domain='ZZ'), Poly(x**6 - x**5 + 2*x**4 - 4*x**3 - 5*x**2 - 5*x + 9, x, domain='ZZ'), [[1], [0]] ), ( Poly(-5*x**3 + x**2 + 11*x + 12, x, domain='ZZ'), Poly(6*x**8 - 26*x**7 - 27*x**6 - 10*x**5 - 44*x**4 - 46*x**3 - 34*x**2 \ - 27*x - 42, x, domain='ZZ'), [[1], [0]] )] for num, den, d in tests: assert construct_d_case_6(num, den, x) == d def test_rational_laurent_series(): """ This function tests the computation of coefficients of Laurent series of a rational function. Each test case has 5 values - 1. num - Numerator of the rational function. 2. den - Denominator of the rational function. 3. x0 - Point about which Laurent series is to be calculated. 4. mul - Multiplicity of x0 if x0 is a pole of the rational function (0 otherwise). 5. n - Number of terms upto which the series is to be calcuated. """ tests = [ # Laurent series about simple pole (Multiplicity = 1) ( Poly(x**2 - 3*x + 9, x, extension=True), Poly(x**2 - x, x, extension=True), S(1), 1, 6, {1: 7, 0: -8, -1: 9, -2: -9, -3: 9, -4: -9} ), # Laurent series about multiple pole (Multiplicty > 1) ( Poly(64*x**3 - 1728*x + 1216, x, extension=True), Poly(64*x**4 - 80*x**3 - 831*x**2 + 1809*x - 972, x, extension=True), S(9)/8, 2, 3, {0: S(32177152)/46521675, 2: S(1019)/984, -1: S(11947565056)/28610830125, \ 1: S(209149)/75645} ), ( Poly(1, x, extension=True), Poly(x**5 + (-4*sqrt(2) - 1)*x**4 + (4*sqrt(2) + 12)*x**3 + (-12 - 8*sqrt(2))*x**2 \ + (4 + 8*sqrt(2))*x - 4, x, extension=True), sqrt(2), 4, 6, {4: 1 + sqrt(2), 3: -3 - 2*sqrt(2), 2: Mul(-1, -3 - 2*sqrt(2), evaluate=False)/(-1 \ + sqrt(2)), 1: (-3 - 2*sqrt(2))/(-1 + sqrt(2))**2, 0: Mul(-1, -3 - 2*sqrt(2), evaluate=False \ )/(-1 + sqrt(2))**3, -1: (-3 - 2*sqrt(2))/(-1 + sqrt(2))**4} ), # Laurent series about oo ( Poly(x**5 - 4*x**3 + 6*x**2 + 10*x - 13, x, extension=True), Poly(x**2 - 5, x, extension=True), oo, 3, 6, {3: 1, 2: 0, 1: 1, 0: 6, -1: 15, -2: 17} ), # Laurent series at x0 where x0 is not a pole of the function # Using multiplicity as 0 (as x0 will not be a pole) ( Poly(3*x**3 + 6*x**2 - 2*x + 5, x, extension=True), Poly(9*x**4 - x**3 - 3*x**2 + 4*x + 4, x, extension=True), S(2)/5, 0, 1, {0: S(3345)/3304, -1: S(399325)/2729104, -2: S(3926413375)/4508479808, \ -3: S(-5000852751875)/1862002160704, -4: S(-6683640101653125)/6152055138966016} ), ( Poly(-7*x**2 + 2*x - 4, x, extension=True), Poly(7*x**5 + 9*x**4 + 8*x**3 + 3*x**2 + 6*x + 9, x, extension=True), oo, 0, 6, {0: 0, -2: 0, -5: -S(71)/49, -1: 0, -3: -1, -4: S(11)/7} )] for num, den, x0, mul, n, ser in tests: assert ser == rational_laurent_series(num, den, x, x0, mul, n) def check_dummy_sol(eq, solse, dummy_sym): """ Helper function to check if actual solution matches expected solution if actual solution contains dummy symbols. """ if isinstance(eq, Eq): eq = eq.lhs - eq.rhs _, funcs = match_riccati(eq, f, x) sols = solve_riccati(f(x), x, *funcs) C1 = Dummy('C1') sols = [sol.subs(C1, dummy_sym) for sol in sols] assert all([x[0] for x in checkodesol(eq, sols)]) assert all([s1.dummy_eq(s2, dummy_sym) for s1, s2 in zip(sols, solse)]) def test_solve_riccati(): """ This function tests the computation of rational particular solutions for a Riccati ODE. Each test case has 2 values - 1. eq - Riccati ODE to be solved. 2. sol - Expected solution to the equation. Some examples have been taken from the paper - "Statistical Investigation of First-Order Algebraic ODEs and their Rational General Solutions" by Georg Grasegger, N. Thieu Vo, Franz Winkler https://www3.risc.jku.at/publications/download/risc_5197/RISCReport15-19.pdf """ C0 = Dummy('C0') # Type: 1st Order Rational Riccati, dy/dx = a + b*y + c*y**2, # a, b, c are rational functions of x tests = [ # a(x) is a constant ( Eq(f(x).diff(x) + f(x)**2 - 2, 0), [Eq(f(x), sqrt(2)), Eq(f(x), -sqrt(2))] ), # a(x) is a constant ( f(x)**2 + f(x).diff(x) + 4*f(x)/x + 2/x**2, [Eq(f(x), (-2*C0 - x)/(C0*x + x**2))] ), # a(x) is a constant ( 2*x**2*f(x).diff(x) - x*(4*f(x) + f(x).diff(x) - 4) + (f(x) - 1)*f(x), [Eq(f(x), (C0 + 2*x**2)/(C0 + x))] ), # Pole with multiplicity 1 ( Eq(f(x).diff(x), -f(x)**2 - 2/(x**3 - x**2)), [Eq(f(x), 1/(x**2 - x))] ), # One pole of multiplicity 2 ( x**2 - (2*x + 1/x)*f(x) + f(x)**2 + f(x).diff(x), [Eq(f(x), (C0*x + x**3 + 2*x)/(C0 + x**2)), Eq(f(x), x)] ), ( x**4*f(x).diff(x) + x**2 - x*(2*f(x)**2 + f(x).diff(x)) + f(x), [Eq(f(x), (C0*x**2 + x)/(C0 + x**2)), Eq(f(x), x**2)] ), # Multiple poles of multiplicity 2 ( -f(x)**2 + f(x).diff(x) + (15*x**2 - 20*x + 7)/((x - 1)**2*(2*x \ - 1)**2), [Eq(f(x), (9*C0*x - 6*C0 - 15*x**5 + 60*x**4 - 94*x**3 + 72*x**2 \ - 30*x + 6)/(6*C0*x**2 - 9*C0*x + 3*C0 + 6*x**6 - 29*x**5 + \ 57*x**4 - 58*x**3 + 30*x**2 - 6*x)), Eq(f(x), (3*x - 2)/(2*x**2 \ - 3*x + 1))] ), # Regression: Poles with even multiplicity > 2 fixed ( f(x)**2 + f(x).diff(x) - (4*x**6 - 8*x**5 + 12*x**4 + 4*x**3 + \ 7*x**2 - 20*x + 4)/(4*x**4), [Eq(f(x), (2*x**5 - 2*x**4 - x**3 + 4*x**2 + 3*x - 2)/(2*x**4 \ - 2*x**2))] ), # Regression: Poles with even multiplicity > 2 fixed ( Eq(f(x).diff(x), (-x**6 + 15*x**4 - 40*x**3 + 45*x**2 - 24*x + 4)/\ (x**12 - 12*x**11 + 66*x**10 - 220*x**9 + 495*x**8 - 792*x**7 + 924*x**6 - \ 792*x**5 + 495*x**4 - 220*x**3 + 66*x**2 - 12*x + 1) + f(x)**2 + f(x)), [Eq(f(x), 1/(x**6 - 6*x**5 + 15*x**4 - 20*x**3 + 15*x**2 - 6*x + 1))] ), # More than 2 poles with multiplicity 2 # Regression: Fixed mistake in necessary conditions ( Eq(f(x).diff(x), x*f(x) + 2*x + (3*x - 2)*f(x)**2/(4*x + 2) + \ (8*x**2 - 7*x + 26)/(16*x**3 - 24*x**2 + 8) - S(3)/2), [Eq(f(x), (1 - 4*x)/(2*x - 2))] ), # Regression: Fixed mistake in necessary conditions ( Eq(f(x).diff(x), (-12*x**2 - 48*x - 15)/(24*x**3 - 40*x**2 + 8*x + 8) \ + 3*f(x)**2/(6*x + 2)), [Eq(f(x), (2*x + 1)/(2*x - 2))] ), # Imaginary poles ( f(x).diff(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), [Eq(f(x), (-C0 - x**3 + x**2 - 2*x)/(C0*x - C0 + x**4 - x**3 + x**2 \ - x)), Eq(f(x), -1/(x - 1))], ), # Imaginary coefficients in equation ( f(x).diff(x) - 2*I*(f(x)**2 + 1)/x, [Eq(f(x), (-I*C0 + I*x**4)/(C0 + x**4)), Eq(f(x), -I)] ), # Regression: linsolve returning empty solution # Large value of m (> 10) ( Eq(f(x).diff(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)), [Eq(f(x), (9 - x)/x), Eq(f(x), (40*x**14 + 28*x**13 + 420*x**12 + 2940*x**11 + \ 18480*x**10 + 103950*x**9 + 519750*x**8 + 2286900*x**7 + 8731800*x**6 + 28378350*\ x**5 + 76403250*x**4 + 163721250*x**3 + 261954000*x**2 + 278326125*x + 147349125)/\ ((24*x**14 + 140*x**13 + 840*x**12 + 4620*x**11 + 23100*x**10 + 103950*x**9 + \ 415800*x**8 + 1455300*x**7 + 4365900*x**6 + 10914750*x**5 + 21829500*x**4 + 32744250\ *x**3 + 32744250*x**2 + 16372125*x)))] ), # Regression: Fixed bug due to a typo in paper ( Eq(f(x).diff(x), 18*x**3 + 18*x**2 + (-x/2 - S(1)/2)*f(x)**2 + 6), [Eq(f(x), 6*x)] ), # Regression: Fixed bug due to a typo in paper ( Eq(f(x).diff(x), -3*x**3/4 + 15*x/2 + (x/3 - S(4)/3)*f(x)**2 \ + 9 + (1 - x)*f(x)/x + 3/x), [Eq(f(x), -3*x/2 - 3)] )] for eq, sol in tests: check_dummy_sol(eq, sol, C0) @slow def test_solve_riccati_slow(): """ This function tests the computation of rational particular solutions for a Riccati ODE. Each test case has 2 values - 1. eq - Riccati ODE to be solved. 2. sol - Expected solution to the equation. """ C0 = Dummy('C0') tests = [ # Very large values of m (989 and 991) ( Eq(f(x).diff(x), (1 - x)*f(x)/(x - 3) + (2 - 12*x)*f(x)**2/(2*x - 9) + \ (54924*x**3 - 405264*x**2 + 1084347*x - 1087533)/(8*x**4 - 132*x**3 + 810*x**2 - \ 2187*x + 2187) + 495), [Eq(f(x), (18*x + 6)/(2*x - 9))] )] for eq, sol in tests: check_dummy_sol(eq, sol, C0)
a7c9e7c0fac98b19777dde3e1becac6831cfc80e796d9704848d4abcf19e308f
from sympy.core.function import (Derivative, Function, Subs, diff) from sympy.core.numbers import (I, Rational, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (im, re) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import acosh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (atan2, cos, sin, tan) from sympy.integrals.integrals import Integral from sympy.polys.polytools import Poly from sympy.series.order import O from sympy.simplify.radsimp import collect from sympy.solvers.ode import (classify_ode, homogeneous_order, dsolve) from sympy.solvers.ode.subscheck import checkodesol from sympy.solvers.ode.ode import (classify_sysode, constant_renumber, constantsimp, get_numbered_constants, solve_ics) from sympy.solvers.ode.nonhomogeneous import _undetermined_coefficients_match from sympy.solvers.ode.single import LinearCoefficients from sympy.solvers.deutils import ode_order from sympy.testing.pytest import XFAIL, raises, slow C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C0:11') u, x, y, z = symbols('u,x:z', real=True) f = Function('f') g = Function('g') h = Function('h') # Note: Examples which were specifically testing Single ODE solver are moved to test_single.py # and all the system of ode examples are moved to test_systems.py # Note: the tests below may fail (but still be correct) if ODE solver, # the integral engine, solve(), or even simplify() changes. Also, in # differently formatted solutions, the arbitrary constants might not be # equal. Using specific hints in tests can help to avoid this. # Tests of order higher than 1 should run the solutions through # constant_renumber because it will normalize it (constant_renumber causes # dsolve() to return different results on different machines) def test_get_numbered_constants(): with raises(ValueError): get_numbered_constants(None) def test_dsolve_all_hint(): eq = f(x).diff(x) output = dsolve(eq, hint='all') # Match the Dummy variables: sol1 = output['separable_Integral'] _y = sol1.lhs.args[1][0] sol1 = output['1st_homogeneous_coeff_subs_dep_div_indep_Integral'] _u1 = sol1.rhs.args[1].args[1][0] expected = {'Bernoulli_Integral': Eq(f(x), C1 + Integral(0, x)), '1st_homogeneous_coeff_best': Eq(f(x), C1), 'Bernoulli': Eq(f(x), C1), 'nth_algebraic': Eq(f(x), C1), 'nth_linear_euler_eq_homogeneous': Eq(f(x), C1), 'nth_linear_constant_coeff_homogeneous': Eq(f(x), C1), 'separable': Eq(f(x), C1), '1st_homogeneous_coeff_subs_indep_div_dep': Eq(f(x), C1), 'nth_algebraic_Integral': Eq(f(x), C1), '1st_linear': Eq(f(x), C1), '1st_linear_Integral': Eq(f(x), C1 + Integral(0, x)), '1st_exact': Eq(f(x), C1), '1st_exact_Integral': Eq(Subs(Integral(0, x) + Integral(1, _y), _y, f(x)), C1), 'lie_group': Eq(f(x), C1), '1st_homogeneous_coeff_subs_dep_div_indep': Eq(f(x), C1), '1st_homogeneous_coeff_subs_dep_div_indep_Integral': Eq(log(x), C1 + Integral(-1/_u1, (_u1, f(x)/x))), '1st_power_series': Eq(f(x), C1), 'separable_Integral': Eq(Integral(1, (_y, f(x))), C1 + Integral(0, x)), '1st_homogeneous_coeff_subs_indep_div_dep_Integral': Eq(f(x), C1), 'best': Eq(f(x), C1), 'best_hint': 'nth_algebraic', 'default': 'nth_algebraic', 'order': 1} assert output == expected assert dsolve(eq, hint='best') == Eq(f(x), C1) def test_dsolve_ics(): # Maybe this should just use one of the solutions instead of raising... with raises(NotImplementedError): dsolve(f(x).diff(x) - sqrt(f(x)), ics={f(1):1}) @slow def test_dsolve_options(): eq = x*f(x).diff(x) + f(x) a = dsolve(eq, hint='all') b = dsolve(eq, hint='all', simplify=False) c = dsolve(eq, hint='all_Integral') keys = ['1st_exact', '1st_exact_Integral', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear', '1st_linear_Integral', 'Bernoulli', 'Bernoulli_Integral', 'almost_linear', 'almost_linear_Integral', 'best', 'best_hint', 'default', 'factorable', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'order', 'separable', 'separable_Integral'] Integral_keys = ['1st_exact_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear_Integral', 'Bernoulli_Integral', 'almost_linear_Integral', 'best', 'best_hint', 'default', 'factorable', 'nth_linear_euler_eq_homogeneous', 'order', 'separable_Integral'] assert sorted(a.keys()) == keys assert a['order'] == ode_order(eq, f(x)) assert a['best'] == Eq(f(x), C1/x) assert dsolve(eq, hint='best') == Eq(f(x), C1/x) assert a['default'] == 'factorable' assert a['best_hint'] == 'factorable' assert not a['1st_exact'].has(Integral) assert not a['separable'].has(Integral) assert not a['1st_homogeneous_coeff_best'].has(Integral) assert not a['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral) assert not a['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral) assert not a['1st_linear'].has(Integral) assert a['1st_linear_Integral'].has(Integral) assert a['1st_exact_Integral'].has(Integral) assert a['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral) assert a['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral) assert a['separable_Integral'].has(Integral) assert sorted(b.keys()) == keys assert b['order'] == ode_order(eq, f(x)) assert b['best'] == Eq(f(x), C1/x) assert dsolve(eq, hint='best', simplify=False) == Eq(f(x), C1/x) assert b['default'] == 'factorable' assert b['best_hint'] == 'factorable' assert a['separable'] != b['separable'] assert a['1st_homogeneous_coeff_subs_dep_div_indep'] != \ b['1st_homogeneous_coeff_subs_dep_div_indep'] assert a['1st_homogeneous_coeff_subs_indep_div_dep'] != \ b['1st_homogeneous_coeff_subs_indep_div_dep'] assert not b['1st_exact'].has(Integral) assert not b['separable'].has(Integral) assert not b['1st_homogeneous_coeff_best'].has(Integral) assert not b['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral) assert not b['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral) assert not b['1st_linear'].has(Integral) assert b['1st_linear_Integral'].has(Integral) assert b['1st_exact_Integral'].has(Integral) assert b['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral) assert b['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral) assert b['separable_Integral'].has(Integral) assert sorted(c.keys()) == Integral_keys raises(ValueError, lambda: dsolve(eq, hint='notarealhint')) raises(ValueError, lambda: dsolve(eq, hint='Liouville')) assert dsolve(f(x).diff(x) - 1/f(x)**2, hint='all')['best'] == \ dsolve(f(x).diff(x) - 1/f(x)**2, hint='best') assert dsolve(f(x) + f(x).diff(x) + sin(x).diff(x) + 1, f(x), hint="1st_linear_Integral") == \ Eq(f(x), (C1 + Integral((-sin(x).diff(x) - 1)* exp(Integral(1, x)), x))*exp(-Integral(1, x))) def test_classify_ode(): assert classify_ode(f(x).diff(x, 2), f(x)) == \ ( 'nth_algebraic', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'Liouville', '2nd_power_series_ordinary', 'nth_algebraic_Integral', 'Liouville_Integral', ) assert classify_ode(f(x), f(x)) == ('nth_algebraic', 'nth_algebraic_Integral') assert classify_ode(Eq(f(x).diff(x), 0), f(x)) == ( 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') assert classify_ode(f(x).diff(x)**2, f(x)) == ('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') # issue 4749: f(x) should be cleared from highest derivative before classifying a = classify_ode(Eq(f(x).diff(x) + f(x), x), f(x)) b = classify_ode(f(x).diff(x)*f(x) + f(x)*f(x) - x*f(x), f(x)) c = classify_ode(f(x).diff(x)/f(x) + f(x)/f(x) - x/f(x), f(x)) assert a == ('1st_exact', '1st_linear', 'Bernoulli', 'almost_linear', '1st_power_series', "lie_group", 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', 'almost_linear_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert b == ('factorable', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert c == ('factorable', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert classify_ode( 2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x) ) == ('factorable', '1st_exact', 'Bernoulli', 'almost_linear', 'lie_group', '1st_exact_Integral', 'Bernoulli_Integral', 'almost_linear_Integral') assert 'Riccati_special_minus2' in \ classify_ode(2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2), f(x)) raises(ValueError, lambda: classify_ode(x + f(x, y).diff(x).diff( y), f(x, y))) # issue 5176 k = Symbol('k') assert classify_ode(f(x).diff(x)/(k*f(x) + k*x*f(x)) + 2*f(x)/(k*f(x) + k*x*f(x)) + x*f(x).diff(x)/(k*f(x) + k*x*f(x)) + z, f(x)) == \ ('factorable', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral') # preprocessing ans = ('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral') # w/o f(x) given assert classify_ode(diff(f(x) + x, x) + diff(f(x), x)) == ans # w/ f(x) and prep=True assert classify_ode(diff(f(x) + x, x) + diff(f(x), x), f(x), prep=True) == ans assert classify_ode(Eq(2*x**3*f(x).diff(x), 0), f(x)) == \ ('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral') assert classify_ode(Eq(2*f(x)**3*f(x).diff(x), 0), f(x)) == \ ('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral') # test issue 13864 assert classify_ode(Eq(diff(f(x), x) - f(x)**x, 0), f(x)) == \ ('1st_power_series', 'lie_group') assert isinstance(classify_ode(Eq(f(x), 5), f(x), dict=True), dict) #This is for new behavior of classify_ode when called internally with default, It should # return the first hint which matches therefore, 'ordered_hints' key will not be there. assert sorted(classify_ode(Eq(f(x).diff(x), 0), f(x), dict=True).keys()) == \ ['default', 'nth_linear_constant_coeff_homogeneous', 'order'] a = classify_ode(2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x), dict=True, hint='Bernoulli') assert sorted(a.keys()) == ['Bernoulli', 'Bernoulli_Integral', 'default', 'order', 'ordered_hints'] # test issue 22155 a = classify_ode(f(x).diff(x) - exp(f(x) - x), f(x)) assert a == ('separable', '1st_exact', '1st_power_series', 'lie_group', 'separable_Integral', '1st_exact_Integral') def test_classify_ode_ics(): # Dummy eq = f(x).diff(x, x) - f(x) # Not f(0) or f'(0) ics = {x: 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) ############################ # f(0) type (AppliedUndef) # ############################ # Wrong function ics = {g(0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Contains x ics = {f(x): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Too many args ics = {f(0, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # point contains f # XXX: Should be NotImplementedError ics = {f(0): f(1)} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Does not raise ics = {f(0): 1} classify_ode(eq, f(x), ics=ics) ##################### # f'(0) type (Subs) # ##################### # Wrong function ics = {g(x).diff(x).subs(x, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Contains x ics = {f(y).diff(y).subs(y, x): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Wrong variable ics = {f(y).diff(y).subs(y, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Too many args ics = {f(x, y).diff(x).subs(x, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Derivative wrt wrong vars ics = {Derivative(f(x), x, y).subs(x, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # point contains f # XXX: Should be NotImplementedError ics = {f(x).diff(x).subs(x, 0): f(0)} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Does not raise ics = {f(x).diff(x).subs(x, 0): 1} classify_ode(eq, f(x), ics=ics) ########################### # f'(y) type (Derivative) # ########################### # Wrong function ics = {g(x).diff(x).subs(x, y): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Contains x ics = {f(y).diff(y).subs(y, x): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Too many args ics = {f(x, y).diff(x).subs(x, y): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Derivative wrt wrong vars ics = {Derivative(f(x), x, z).subs(x, y): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # point contains f # XXX: Should be NotImplementedError ics = {f(x).diff(x).subs(x, y): f(0)} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Does not raise ics = {f(x).diff(x).subs(x, y): 1} classify_ode(eq, f(x), ics=ics) def test_classify_sysode(): # Here x is assumed to be x(t) and y as y(t) for simplicity. # Similarly diff(x,t) and diff(y,y) is assumed to be x1 and y1 respectively. k, l, m, n = symbols('k, l, m, n', Integer=True) k1, k2, k3, l1, l2, l3, m1, m2, m3 = symbols('k1, k2, k3, l1, l2, l3, m1, m2, m3', Integer=True) P, Q, R, p, q, r = symbols('P, Q, R, p, q, r', cls=Function) P1, P2, P3, Q1, Q2, R1, R2 = symbols('P1, P2, P3, Q1, Q2, R1, R2', cls=Function) x, y, z = symbols('x, y, z', cls=Function) t = symbols('t') x1 = diff(x(t),t) ; y1 = diff(y(t),t) ; eq6 = (Eq(x1, exp(k*x(t))*P(x(t),y(t))), Eq(y1,r(y(t))*P(x(t),y(t)))) sol6 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \ (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': 'type2', 'func': \ [x(t), y(t)], 'is_linear': False, 'eq': [-P(x(t), y(t))*exp(k*x(t)) + Derivative(x(t), t), -P(x(t), \ y(t))*r(y(t)) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq6) == sol6 eq7 = (Eq(x1, x(t)**2+y(t)/x(t)), Eq(y1, x(t)/y(t))) sol7 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \ (1, x(t), 0): -1/y(t), (0, y(t), 1): 0, (0, y(t), 0): -1/x(t), (1, y(t), 1): 1}, 'type_of_equation': 'type3', \ 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)**2 + Derivative(x(t), t) - y(t)/x(t), -x(t)/y(t) + \ Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq7) == sol7 eq8 = (Eq(x1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)), Eq(y1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t))) sol8 = {'func': [x(t), y(t)], 'is_linear': False, 'type_of_equation': 'type4', 'eq': \ [-P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + Derivative(x(t), t), -P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + \ Derivative(y(t), t)], 'func_coeff': {(0, y(t), 1): 0, (1, y(t), 1): 1, (1, x(t), 1): 0, (0, y(t), 0): 0, \ (1, x(t), 0): 0, (0, x(t), 0): 0, (1, y(t), 0): 0, (0, x(t), 1): 1}, 'order': {y(t): 1, x(t): 1}, 'no_of_equation': 2} assert classify_sysode(eq8) == sol8 eq11 = (Eq(x1,x(t)*y(t)**3), Eq(y1,y(t)**5)) sol11 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)**3, (1, x(t), 1): 0, (0, x(t), 1): 1, \ (1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': \ 'type1', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)**3 + Derivative(x(t), t), \ -y(t)**5 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq11) == sol11 eq13 = (Eq(x1,x(t)*y(t)*sin(t)**2), Eq(y1,y(t)**2*sin(t)**2)) sol13 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)*sin(t)**2, (1, x(t), 1): 0, (0, x(t), 1): 1, \ (1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): -x(t)*sin(t)**2, (1, y(t), 1): 1}, \ 'type_of_equation': 'type4', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)*sin(t)**2 + \ Derivative(x(t), t), -y(t)**2*sin(t)**2 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq13) == sol13 def test_solve_ics(): # Basic tests that things work from dsolve. assert dsolve(f(x).diff(x) - 1/f(x), f(x), ics={f(1): 2}) == \ Eq(f(x), sqrt(2 * x + 2)) assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(0): 1}) == Eq(f(x), exp(x)) assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), exp(x)) assert dsolve(f(x).diff(x, x) + f(x), f(x), ics={f(0): 1, f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), sin(x) + cos(x)) assert dsolve([f(x).diff(x) - f(x) + g(x), g(x).diff(x) - g(x) - f(x)], [f(x), g(x)], ics={f(0): 1, g(0): 0}) == [Eq(f(x), exp(x)*cos(x)), Eq(g(x), exp(x)*sin(x))] # Test cases where dsolve returns two solutions. eq = (x**2*f(x)**2 - x).diff(x) assert dsolve(eq, f(x), ics={f(1): 0}) == [Eq(f(x), -sqrt(x - 1)/x), Eq(f(x), sqrt(x - 1)/x)] assert dsolve(eq, f(x), ics={f(x).diff(x).subs(x, 1): 0}) == [Eq(f(x), -sqrt(x - S.Half)/x), Eq(f(x), sqrt(x - S.Half)/x)] eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x) assert dsolve(eq, f(x), ics={f(0):1}, hint='1st_exact', simplify=False) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3)) assert dsolve(eq, f(x), ics={f(0):1}, hint='1st_exact', simplify=True) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3)) assert solve_ics([Eq(f(x), C1*exp(x))], [f(x)], [C1], {f(0): 1}) == {C1: 1} assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(pi/2): 1}) == {C1: 1, C2: 1} assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(x).diff(x).subs(x, 0): 1}) == {C1: 1, C2: 1} assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1}) == \ {C2: 1} # Some more complicated tests Refer to PR #16098 assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x, 1):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6 - x / 2)} assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0})) == \ {Eq(f(x), 0), Eq(f(x), C2*x + x**3/6)} K, r, f0 = symbols('K r f0') sol = Eq(f(x), K*f0*exp(r*x)/((-K + f0)*(f0*exp(r*x)/(-K + f0) - 1))) assert (dsolve(Eq(f(x).diff(x), r * f(x) * (1 - f(x) / K)), f(x), ics={f(0): f0})) == sol #Order dependent issues Refer to PR #16098 assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(x).diff(x).subs(x,0):0, f(0):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6)} assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x,0):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6)} # XXX: Ought to be ValueError raises(ValueError, lambda: solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(pi): 1})) # Degenerate case. f'(0) is identically 0. raises(ValueError, lambda: solve_ics([Eq(f(x), sqrt(C1 - x**2))], [f(x)], [C1], {f(x).diff(x).subs(x, 0): 0})) EI, q, L = symbols('EI q L') # eq = Eq(EI*diff(f(x), x, 4), q) sols = [Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3 + q*x**4/(24*EI))] funcs = [f(x)] constants = [C1, C2, C3, C4] # Test both cases, Derivative (the default from f(x).diff(x).subs(x, L)), # and Subs ics1 = {f(0): 0, f(x).diff(x).subs(x, 0): 0, f(L).diff(L, 2): 0, f(L).diff(L, 3): 0} ics2 = {f(0): 0, f(x).diff(x).subs(x, 0): 0, Subs(f(x).diff(x, 2), x, L): 0, Subs(f(x).diff(x, 3), x, L): 0} solved_constants1 = solve_ics(sols, funcs, constants, ics1) solved_constants2 = solve_ics(sols, funcs, constants, ics2) assert solved_constants1 == solved_constants2 == { C1: 0, C2: 0, C3: L**2*q/(4*EI), C4: -L*q/(6*EI)} def test_ode_order(): f = Function('f') g = Function('g') x = Symbol('x') assert ode_order(3*x*exp(f(x)), f(x)) == 0 assert ode_order(x*diff(f(x), x) + 3*x*f(x) - sin(x)/x, f(x)) == 1 assert ode_order(x**2*f(x).diff(x, x) + x*diff(f(x), x) - f(x), f(x)) == 2 assert ode_order(diff(x*exp(f(x)), x, x), f(x)) == 2 assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), f(x)) == 3 assert ode_order(diff(f(x), x, x), g(x)) == 0 assert ode_order(diff(f(x), x, x)*diff(g(x), x), f(x)) == 2 assert ode_order(diff(f(x), x, x)*diff(g(x), x), g(x)) == 1 assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), g(x)) == 0 # issue 5835: ode_order has to also work for unevaluated derivatives # (ie, without using doit()). assert ode_order(Derivative(x*f(x), x), f(x)) == 1 assert ode_order(x*sin(Derivative(x*f(x)**2, x, x)), f(x)) == 2 assert ode_order(Derivative(x*Derivative(x*exp(f(x)), x, x), x), g(x)) == 0 assert ode_order(Derivative(f(x), x, x), g(x)) == 0 assert ode_order(Derivative(x*exp(f(x)), x, x), f(x)) == 2 assert ode_order(Derivative(f(x), x, x)*Derivative(g(x), x), g(x)) == 1 assert ode_order(Derivative(x*Derivative(f(x), x, x), x), f(x)) == 3 assert ode_order( x*sin(Derivative(x*Derivative(f(x), x)**2, x, x)), f(x)) == 3 def test_homogeneous_order(): assert homogeneous_order(exp(y/x) + tan(y/x), x, y) == 0 assert homogeneous_order(x**2 + sin(x)*cos(y), x, y) is None assert homogeneous_order(x - y - x*sin(y/x), x, y) == 1 assert homogeneous_order((x*y + sqrt(x**4 + y**4) + x**2*(log(x) - log(y)))/ (pi*x**Rational(2, 3)*sqrt(y)**3), x, y) == Rational(-1, 6) assert homogeneous_order(y/x*cos(y/x) - x/y*sin(y/x) + cos(y/x), x, y) == 0 assert homogeneous_order(f(x), x, f(x)) == 1 assert homogeneous_order(f(x)**2, x, f(x)) == 2 assert homogeneous_order(x*y*z, x, y) == 2 assert homogeneous_order(x*y*z, x, y, z) == 3 assert homogeneous_order(x**2*f(x)/sqrt(x**2 + f(x)**2), f(x)) is None assert homogeneous_order(f(x, y)**2, x, f(x, y), y) == 2 assert homogeneous_order(f(x, y)**2, x, f(x), y) is None assert homogeneous_order(f(x, y)**2, x, f(x, y)) is None assert homogeneous_order(f(y, x)**2, x, y, f(x, y)) is None assert homogeneous_order(f(y), f(x), x) is None assert homogeneous_order(-f(x)/x + 1/sin(f(x)/ x), f(x), x) == 0 assert homogeneous_order(log(1/y) + log(x**2), x, y) is None assert homogeneous_order(log(1/y) + log(x), x, y) == 0 assert homogeneous_order(log(x/y), x, y) == 0 assert homogeneous_order(2*log(1/y) + 2*log(x), x, y) == 0 a = Symbol('a') assert homogeneous_order(a*log(1/y) + a*log(x), x, y) == 0 assert homogeneous_order(f(x).diff(x), x, y) is None assert homogeneous_order(-f(x).diff(x) + x, x, y) is None assert homogeneous_order(O(x), x, y) is None assert homogeneous_order(x + O(x**2), x, y) is None assert homogeneous_order(x**pi, x) == pi assert homogeneous_order(x**x, x) is None raises(ValueError, lambda: homogeneous_order(x*y)) @XFAIL def test_noncircularized_real_imaginary_parts(): # If this passes, lines numbered 3878-3882 (at the time of this commit) # of sympy/solvers/ode.py for nth_linear_constant_coeff_homogeneous # should be removed. y = sqrt(1+x) i, r = im(y), re(y) assert not (i.has(atan2) and r.has(atan2)) def test_collect_respecting_exponentials(): # If this test passes, lines 1306-1311 (at the time of this commit) # of sympy/solvers/ode.py should be removed. sol = 1 + exp(x/2) assert sol == collect( sol, exp(x/3)) def test_undetermined_coefficients_match(): assert _undetermined_coefficients_match(g(x), x) == {'test': False} assert _undetermined_coefficients_match(sin(2*x + sqrt(5)), x) == \ {'test': True, 'trialset': {cos(2*x + sqrt(5)), sin(2*x + sqrt(5))}} assert _undetermined_coefficients_match(sin(x)*cos(x), x) == \ {'test': False} s = {cos(x), x*cos(x), x**2*cos(x), x**2*sin(x), x*sin(x), sin(x)} assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': s} assert _undetermined_coefficients_match( sin(x)*x**2 + sin(x)*x + sin(x), x) == {'test': True, 'trialset': s} assert _undetermined_coefficients_match( exp(2*x)*sin(x)*(x**2 + x + 1), x ) == { 'test': True, 'trialset': {exp(2*x)*sin(x), x**2*exp(2*x)*sin(x), cos(x)*exp(2*x), x**2*cos(x)*exp(2*x), x*cos(x)*exp(2*x), x*exp(2*x)*sin(x)}} assert _undetermined_coefficients_match(1/sin(x), x) == {'test': False} assert _undetermined_coefficients_match(log(x), x) == {'test': False} assert _undetermined_coefficients_match(2**(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': {2**x, x*2**x, x**2*2**x}} assert _undetermined_coefficients_match(x**y, x) == {'test': False} assert _undetermined_coefficients_match(exp(x)*exp(2*x + 1), x) == \ {'test': True, 'trialset': {exp(1 + 3*x)}} assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': {x*cos(x), x*sin(x), x**2*cos(x), x**2*sin(x), cos(x), sin(x)}} assert _undetermined_coefficients_match(sin(x)*(x + sin(x)), x) == \ {'test': False} assert _undetermined_coefficients_match(sin(x)*(x + sin(2*x)), x) == \ {'test': False} assert _undetermined_coefficients_match(sin(x)*tan(x), x) == \ {'test': False} assert _undetermined_coefficients_match( x**2*sin(x)*exp(x) + x*sin(x) + x, x ) == { 'test': True, 'trialset': {x**2*cos(x)*exp(x), x, cos(x), S.One, exp(x)*sin(x), sin(x), x*exp(x)*sin(x), x*cos(x), x*cos(x)*exp(x), x*sin(x), cos(x)*exp(x), x**2*exp(x)*sin(x)}} assert _undetermined_coefficients_match(4*x*sin(x - 2), x) == { 'trialset': {x*cos(x - 2), x*sin(x - 2), cos(x - 2), sin(x - 2)}, 'test': True, } assert _undetermined_coefficients_match(2**x*x, x) == \ {'test': True, 'trialset': {2**x, x*2**x}} assert _undetermined_coefficients_match(2**x*exp(2*x), x) == \ {'test': True, 'trialset': {2**x*exp(2*x)}} assert _undetermined_coefficients_match(exp(-x)/x, x) == \ {'test': False} # Below are from Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 231 assert _undetermined_coefficients_match(S(4), x) == \ {'test': True, 'trialset': {S.One}} assert _undetermined_coefficients_match(12*exp(x), x) == \ {'test': True, 'trialset': {exp(x)}} assert _undetermined_coefficients_match(exp(I*x), x) == \ {'test': True, 'trialset': {exp(I*x)}} assert _undetermined_coefficients_match(sin(x), x) == \ {'test': True, 'trialset': {cos(x), sin(x)}} assert _undetermined_coefficients_match(cos(x), x) == \ {'test': True, 'trialset': {cos(x), sin(x)}} assert _undetermined_coefficients_match(8 + 6*exp(x) + 2*sin(x), x) == \ {'test': True, 'trialset': {S.One, cos(x), sin(x), exp(x)}} assert _undetermined_coefficients_match(x**2, x) == \ {'test': True, 'trialset': {S.One, x, x**2}} assert _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) == \ {'test': True, 'trialset': {x*exp(x), exp(x), exp(-x)}} assert _undetermined_coefficients_match(2*exp(2*x)*sin(x), x) == \ {'test': True, 'trialset': {exp(2*x)*sin(x), cos(x)*exp(2*x)}} assert _undetermined_coefficients_match(x - sin(x), x) == \ {'test': True, 'trialset': {S.One, x, cos(x), sin(x)}} assert _undetermined_coefficients_match(x**2 + 2*x, x) == \ {'test': True, 'trialset': {S.One, x, x**2}} assert _undetermined_coefficients_match(4*x*sin(x), x) == \ {'test': True, 'trialset': {x*cos(x), x*sin(x), cos(x), sin(x)}} assert _undetermined_coefficients_match(x*sin(2*x), x) == \ {'test': True, 'trialset': {x*cos(2*x), x*sin(2*x), cos(2*x), sin(2*x)}} assert _undetermined_coefficients_match(x**2*exp(-x), x) == \ {'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}} assert _undetermined_coefficients_match(2*exp(-x) - x**2*exp(-x), x) == \ {'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}} assert _undetermined_coefficients_match(exp(-2*x) + x**2, x) == \ {'test': True, 'trialset': {S.One, x, x**2, exp(-2*x)}} assert _undetermined_coefficients_match(x*exp(-x), x) == \ {'test': True, 'trialset': {x*exp(-x), exp(-x)}} assert _undetermined_coefficients_match(x + exp(2*x), x) == \ {'test': True, 'trialset': {S.One, x, exp(2*x)}} assert _undetermined_coefficients_match(sin(x) + exp(-x), x) == \ {'test': True, 'trialset': {cos(x), sin(x), exp(-x)}} assert _undetermined_coefficients_match(exp(x), x) == \ {'test': True, 'trialset': {exp(x)}} # converted from sin(x)**2 assert _undetermined_coefficients_match(S.Half - cos(2*x)/2, x) == \ {'test': True, 'trialset': {S.One, cos(2*x), sin(2*x)}} # converted from exp(2*x)*sin(x)**2 assert _undetermined_coefficients_match( exp(2*x)*(S.Half + cos(2*x)/2), x ) == { 'test': True, 'trialset': {exp(2*x)*sin(2*x), cos(2*x)*exp(2*x), exp(2*x)}} assert _undetermined_coefficients_match(2*x + sin(x) + cos(x), x) == \ {'test': True, 'trialset': {S.One, x, cos(x), sin(x)}} # converted from sin(2*x)*sin(x) assert _undetermined_coefficients_match(cos(x)/2 - cos(3*x)/2, x) == \ {'test': True, 'trialset': {cos(x), cos(3*x), sin(x), sin(3*x)}} assert _undetermined_coefficients_match(cos(x**2), x) == {'test': False} assert _undetermined_coefficients_match(2**(x**2), x) == {'test': False} def test_issue_4785(): from sympy.abc import A eq = x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2 assert classify_ode(eq, f(x)) == ('factorable', '1st_exact', '1st_linear', 'almost_linear', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_exact_Integral', '1st_linear_Integral', 'almost_linear_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') # issue 4864 eq = (x**2 + f(x)**2)*f(x).diff(x) - 2*x*f(x) assert classify_ode(eq, f(x)) == ('factorable', '1st_exact', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', '1st_exact_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') def test_issue_4825(): raises(ValueError, lambda: dsolve(f(x, y).diff(x) - y*f(x, y), f(x))) assert classify_ode(f(x, y).diff(x) - y*f(x, y), f(x), dict=True) == \ {'order': 0, 'default': None, 'ordered_hints': ()} # See also issue 3793, test Z13. raises(ValueError, lambda: dsolve(f(x).diff(x), f(y))) assert classify_ode(f(x).diff(x), f(y), dict=True) == \ {'order': 0, 'default': None, 'ordered_hints': ()} def test_constant_renumber_order_issue_5308(): from sympy.utilities.iterables import variations assert constant_renumber(C1*x + C2*y) == \ constant_renumber(C1*y + C2*x) == \ C1*x + C2*y e = C1*(C2 + x)*(C3 + y) for a, b, c in variations([C1, C2, C3], 3): assert constant_renumber(a*(b + x)*(c + y)) == e def test_constant_renumber(): e1, e2, x, y = symbols("e1:3 x y") exprs = [e2*x, e1*x + e2*y] assert constant_renumber(exprs[0]) == e2*x assert constant_renumber(exprs[0], variables=[x]) == C1*x assert constant_renumber(exprs[0], variables=[x], newconstants=[C2]) == C2*x assert constant_renumber(exprs, variables=[x, y]) == [C1*x, C1*y + C2*x] assert constant_renumber(exprs, variables=[x, y], newconstants=symbols("C3:5")) == [C3*x, C3*y + C4*x] def test_issue_5770(): k = Symbol("k", real=True) t = Symbol('t') w = Function('w') sol = dsolve(w(t).diff(t, 6) - k**6*w(t), w(t)) assert len([s for s in sol.free_symbols if s.name.startswith('C')]) == 6 assert constantsimp((C1*cos(x) + C2*cos(x))*exp(x), {C1, C2}) == \ C1*cos(x)*exp(x) assert constantsimp(C1*cos(x) + C2*cos(x) + C3*sin(x), {C1, C2, C3}) == \ C1*cos(x) + C3*sin(x) assert constantsimp(exp(C1 + x), {C1}) == C1*exp(x) assert constantsimp(x + C1 + y, {C1, y}) == C1 + x assert constantsimp(x + C1 + Integral(x, (x, 1, 2)), {C1}) == C1 + x def test_issue_5112_5430(): assert homogeneous_order(-log(x) + acosh(x), x) is None assert homogeneous_order(y - log(x), x, y) is None def test_issue_5095(): f = Function('f') raises(ValueError, lambda: dsolve(f(x).diff(x)**2, f(x), 'fdsjf')) def test_homogeneous_function(): f = Function('f') eq1 = tan(x + f(x)) eq2 = sin((3*x)/(4*f(x))) eq3 = cos(x*f(x)*Rational(3, 4)) eq4 = log((3*x + 4*f(x))/(5*f(x) + 7*x)) eq5 = exp((2*x**2)/(3*f(x)**2)) eq6 = log((3*x + 4*f(x))/(5*f(x) + 7*x) + exp((2*x**2)/(3*f(x)**2))) eq7 = sin((3*x)/(5*f(x) + x**2)) assert homogeneous_order(eq1, x, f(x)) == None assert homogeneous_order(eq2, x, f(x)) == 0 assert homogeneous_order(eq3, x, f(x)) == None assert homogeneous_order(eq4, x, f(x)) == 0 assert homogeneous_order(eq5, x, f(x)) == 0 assert homogeneous_order(eq6, x, f(x)) == 0 assert homogeneous_order(eq7, x, f(x)) == None def test_linear_coeff_match(): n, d = z*(2*x + 3*f(x) + 5), z*(7*x + 9*f(x) + 11) rat = n/d eq1 = sin(rat) + cos(rat.expand()) obj1 = LinearCoefficients(eq1) eq2 = rat obj2 = LinearCoefficients(eq2) eq3 = log(sin(rat)) obj3 = LinearCoefficients(eq3) ans = (4, Rational(-13, 3)) assert obj1._linear_coeff_match(eq1, f(x)) == ans assert obj2._linear_coeff_match(eq2, f(x)) == ans assert obj3._linear_coeff_match(eq3, f(x)) == ans # no c eq4 = (3*x)/f(x) obj4 = LinearCoefficients(eq4) # not x and f(x) eq5 = (3*x + 2)/x obj5 = LinearCoefficients(eq5) # denom will be zero eq6 = (3*x + 2*f(x) + 1)/(3*x + 2*f(x) + 5) obj6 = LinearCoefficients(eq6) # not rational coefficient eq7 = (3*x + 2*f(x) + sqrt(2))/(3*x + 2*f(x) + 5) obj7 = LinearCoefficients(eq7) assert obj4._linear_coeff_match(eq4, f(x)) is None assert obj5._linear_coeff_match(eq5, f(x)) is None assert obj6._linear_coeff_match(eq6, f(x)) is None assert obj7._linear_coeff_match(eq7, f(x)) is None def test_constantsimp_take_problem(): c = exp(C1) + 2 assert len(Poly(constantsimp(exp(C1) + c + c*x, [C1])).gens) == 2 def test_series(): C1 = Symbol("C1") eq = f(x).diff(x) - f(x) sol = Eq(f(x), C1 + C1*x + C1*x**2/2 + C1*x**3/6 + C1*x**4/24 + C1*x**5/120 + O(x**6)) assert dsolve(eq, hint='1st_power_series') == sol assert checkodesol(eq, sol, order=1)[0] eq = f(x).diff(x) - x*f(x) sol = Eq(f(x), C1*x**4/8 + C1*x**2/2 + C1 + O(x**6)) assert dsolve(eq, hint='1st_power_series') == sol assert checkodesol(eq, sol, order=1)[0] eq = f(x).diff(x) - sin(x*f(x)) sol = Eq(f(x), (x - 2)**2*(1+ sin(4))*cos(4) + (x - 2)*sin(4) + 2 + O(x**3)) assert dsolve(eq, hint='1st_power_series', ics={f(2): 2}, n=3) == sol # FIXME: The solution here should be O((x-2)**3) so is incorrect #assert checkodesol(eq, sol, order=1)[0] @slow def test_2nd_power_series_ordinary(): C1, C2 = symbols("C1 C2") eq = f(x).diff(x, 2) - x*f(x) assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary') sol = Eq(f(x), C2*(x**3/6 + 1) + C1*x*(x**3/12 + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_ordinary') == sol assert checkodesol(eq, sol) == (True, 0) sol = Eq(f(x), C2*((x + 2)**4/6 + (x + 2)**3/6 - (x + 2)**2 + 1) + C1*(x + (x + 2)**4/12 - (x + 2)**3/3 + S(2)) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_ordinary', x0=-2) == sol # FIXME: Solution should be O((x+2)**6) # assert checkodesol(eq, sol) == (True, 0) sol = Eq(f(x), C2*x + C1 + O(x**2)) assert dsolve(eq, hint='2nd_power_series_ordinary', n=2) == sol assert checkodesol(eq, sol) == (True, 0) eq = (1 + x**2)*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) -2*f(x) assert classify_ode(eq) == ('factorable', '2nd_hypergeometric', '2nd_hypergeometric_Integral', '2nd_power_series_ordinary') sol = Eq(f(x), C2*(-x**4/3 + x**2 + 1) + C1*x + O(x**6)) assert dsolve(eq, hint='2nd_power_series_ordinary') == sol assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + x*(f(x).diff(x)) + f(x) assert classify_ode(eq) == ('factorable', '2nd_power_series_ordinary',) sol = Eq(f(x), C2*(x**4/8 - x**2/2 + 1) + C1*x*(-x**2/3 + 1) + O(x**6)) assert dsolve(eq) == sol # FIXME: checkodesol fails for this solution... # assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + f(x).diff(x) - x*f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) sol = Eq(f(x), C2*(-x**4/24 + x**3/6 + 1) + C1*x*(x**3/24 + x**2/6 - x/2 + 1) + O(x**6)) assert dsolve(eq) == sol # FIXME: checkodesol fails for this solution... # assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + x*f(x) assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary') sol = Eq(f(x), C2*(x**6/180 - x**3/6 + 1) + C1*x*(-x**3/12 + 1) + O(x**7)) assert dsolve(eq, hint='2nd_power_series_ordinary', n=7) == sol assert checkodesol(eq, sol) == (True, 0) def test_2nd_power_series_regular(): C1, C2, a = symbols("C1 C2 a") eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x) sol = Eq(f(x), C1*x**2*(-16*x**3/9 + 4*x**2 - 4*x + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_regular') == sol assert checkodesol(eq, sol) == (True, 0) eq = 4*x**2*(f(x).diff(x, 2)) -8*x**2*(f(x).diff(x)) + (4*x**2 + 1)*f(x) sol = Eq(f(x), C1*sqrt(x)*(x**4/24 + x**3/6 + x**2/2 + x + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_regular') == sol assert checkodesol(eq, sol) == (True, 0) eq = x**2*(f(x).diff(x, 2)) - x**2*(f(x).diff(x)) + ( x**2 - 2)*f(x) sol = Eq(f(x), C1*(-x**6/720 - 3*x**5/80 - x**4/8 + x**2/2 + x/2 + 1)/x + C2*x**2*(-x**3/60 + x**2/20 + x/2 + 1) + O(x**6)) assert dsolve(eq) == sol assert checkodesol(eq, sol) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - Rational(1, 4))*f(x) sol = Eq(f(x), C1*(x**4/24 - x**2/2 + 1)/sqrt(x) + C2*sqrt(x)*(x**4/120 - x**2/6 + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_regular') == sol assert checkodesol(eq, sol) == (True, 0) eq = x*f(x).diff(x, 2) + f(x).diff(x) - a*x*f(x) sol = Eq(f(x), C1*(a**2*x**4/64 + a*x**2/4 + 1) + O(x**6)) assert dsolve(eq, f(x), hint="2nd_power_series_regular") == sol assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + ((1 - x)/x)*f(x).diff(x) + (a/x)*f(x) sol = Eq(f(x), C1*(-a*x**5*(a - 4)*(a - 3)*(a - 2)*(a - 1)/14400 + \ a*x**4*(a - 3)*(a - 2)*(a - 1)/576 - a*x**3*(a - 2)*(a - 1)/36 + \ a*x**2*(a - 1)/4 - a*x + 1) + O(x**6)) assert dsolve(eq, f(x), hint="2nd_power_series_regular") == sol assert checkodesol(eq, sol) == (True, 0) def test_issue_15056(): t = Symbol('t') C3 = Symbol('C3') assert get_numbered_constants(Symbol('C1') * Function('C2')(t)) == C3 def test_issue_15913(): eq = -C1/x - 2*x*f(x) - f(x) + Derivative(f(x), x) sol = C2*exp(x**2 + x) + exp(x**2 + x)*Integral(C1*exp(-x**2 - x)/x, x) assert checkodesol(eq, sol) == (True, 0) sol = C1 + C2*exp(-x*y) eq = Derivative(y*f(x), x) + f(x).diff(x, 2) assert checkodesol(eq, sol, f(x)) == (True, 0) def test_issue_16146(): raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x), g(x), h(x)])) raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x)])) def test_dsolve_remove_redundant_solutions(): eq = (f(x)-2)*f(x).diff(x) sol = Eq(f(x), C1) assert dsolve(eq) == sol eq = (f(x)-sin(x))*(f(x).diff(x, 2)) sol = {Eq(f(x), C1 + C2*x), Eq(f(x), sin(x))} assert set(dsolve(eq)) == sol eq = (f(x)**2-2*f(x)+1)*f(x).diff(x, 3) sol = Eq(f(x), C1 + C2*x + C3*x**2) assert dsolve(eq) == sol def test_issue_13060(): A, B = symbols("A B", cls=Function) t = Symbol("t") eq = [Eq(Derivative(A(t), t), A(t)*B(t)), Eq(Derivative(B(t), t), A(t)*B(t))] sol = dsolve(eq) assert checkodesol(eq, sol) == (True, [0, 0])
1b3c1cf61f67eb394d3a127c421e9f403781f2085a46682fde4b4101f3c9c7e5
from sympy.core.function import (Derivative, Function, diff) from sympy.core.numbers import (I, Rational, pi) from sympy.core.relational import Eq from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.error_functions import (Ei, erf, erfi) from sympy.integrals.integrals import Integral from sympy.solvers.ode.subscheck import checkodesol, checksysodesol from sympy.functions import besselj, bessely from sympy.testing.pytest import raises, slow C0, C1, C2, C3, C4 = symbols('C0:5') u, x, y, z = symbols('u,x:z', real=True) f = Function('f') g = Function('g') h = Function('h') @slow def test_checkodesol(): # For the most part, checkodesol is well tested in the tests below. # These tests only handle cases not checked below. raises(ValueError, lambda: checkodesol(f(x, y).diff(x), Eq(f(x, y), x))) raises(ValueError, lambda: checkodesol(f(x).diff(x), Eq(f(x, y), x), f(x, y))) assert checkodesol(f(x).diff(x), Eq(f(x, y), x)) == \ (False, -f(x).diff(x) + f(x, y).diff(x) - 1) assert checkodesol(f(x).diff(x), Eq(f(x), x)) is not True assert checkodesol(f(x).diff(x), Eq(f(x), x)) == (False, 1) sol1 = Eq(f(x)**5 + 11*f(x) - 2*f(x) + x, 0) assert checkodesol(diff(sol1.lhs, x), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x)*exp(f(x)), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 2), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 2)*exp(f(x)), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 3), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 3)*exp(f(x)), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 3), Eq(f(x), x*log(x))) == \ (False, 60*x**4*((log(x) + 1)**2 + log(x))*( log(x) + 1)*log(x)**2 - 5*x**4*log(x)**4 - 9) assert checkodesol(diff(exp(f(x)) + x, x)*x, Eq(exp(f(x)) + x, 0)) == \ (True, 0) assert checkodesol(diff(exp(f(x)) + x, x)*x, Eq(exp(f(x)) + x, 0), solve_for_func=False) == (True, 0) assert checkodesol(f(x).diff(x, 2), [Eq(f(x), C1 + C2*x), Eq(f(x), C2 + C1*x), Eq(f(x), C1*x + C2*x**2)]) == \ [(True, 0), (True, 0), (False, C2)] assert checkodesol(f(x).diff(x, 2), {Eq(f(x), C1 + C2*x), Eq(f(x), C2 + C1*x), Eq(f(x), C1*x + C2*x**2)}) == \ {(True, 0), (True, 0), (False, C2)} assert checkodesol(f(x).diff(x) - 1/f(x)/2, Eq(f(x)**2, x)) == \ [(True, 0), (True, 0)] assert checkodesol(f(x).diff(x) - f(x), Eq(C1*exp(x), f(x))) == (True, 0) # Based on test_1st_homogeneous_coeff_ode2_eq3sol. Make sure that # checkodesol tries back substituting f(x) when it can. eq3 = x*exp(f(x)/x) + f(x) - x*f(x).diff(x) sol3 = Eq(f(x), log(log(C1/x)**(-x))) assert not checkodesol(eq3, sol3)[1].has(f(x)) # This case was failing intermittently depending on hash-seed: eqn = Eq(Derivative(x*Derivative(f(x), x), x)/x, exp(x)) sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x)) assert checkodesol(eqn, sol, order=2, solve_for_func=False)[0] eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (2*x**2 +25)*f(x) sol = Eq(f(x), C1*besselj(5*I, sqrt(2)*x) + C2*bessely(5*I, sqrt(2)*x)) assert checkodesol(eq, sol) == (True, 0) eqs = [Eq(f(x).diff(x), f(x) + g(x)), Eq(g(x).diff(x), f(x) + g(x))] sol = [Eq(f(x), -C1 + C2*exp(2*x)), Eq(g(x), C1 + C2*exp(2*x))] assert checkodesol(eqs, sol) == (True, [0, 0]) def test_checksysodesol(): x, y, z = symbols('x, y, z', cls=Function) t = Symbol('t') eq = (Eq(diff(x(t),t), 9*y(t)), Eq(diff(y(t),t), 12*x(t))) sol = [Eq(x(t), 9*C1*exp(-6*sqrt(3)*t) + 9*C2*exp(6*sqrt(3)*t)), \ Eq(y(t), -6*sqrt(3)*C1*exp(-6*sqrt(3)*t) + 6*sqrt(3)*C2*exp(6*sqrt(3)*t))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 2*x(t) + 4*y(t)), Eq(diff(y(t),t), 12*x(t) + 41*y(t))) sol = [Eq(x(t), 4*C1*exp(t*(-sqrt(1713)/2 + Rational(43, 2))) + 4*C2*exp(t*(sqrt(1713)/2 + \ Rational(43, 2)))), Eq(y(t), C1*(-sqrt(1713)/2 + Rational(39, 2))*exp(t*(-sqrt(1713)/2 + \ Rational(43, 2))) + C2*(Rational(39, 2) + sqrt(1713)/2)*exp(t*(sqrt(1713)/2 + Rational(43, 2))))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), x(t) + y(t)), Eq(diff(y(t),t), -2*x(t) + 2*y(t))) sol = [Eq(x(t), (C1*sin(sqrt(7)*t/2) + C2*cos(sqrt(7)*t/2))*exp(t*Rational(3, 2))), \ Eq(y(t), ((C1/2 - sqrt(7)*C2/2)*sin(sqrt(7)*t/2) + (sqrt(7)*C1/2 + \ C2/2)*cos(sqrt(7)*t/2))*exp(t*Rational(3, 2)))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23)) sol = [Eq(x(t), C1*exp(t*(-sqrt(6) + 3)) + C2*exp(t*(sqrt(6) + 3)) - \ Rational(22, 3)), Eq(y(t), C1*(-sqrt(6) + 2)*exp(t*(-sqrt(6) + 3)) + C2*(2 + \ sqrt(6))*exp(t*(sqrt(6) + 3)) - Rational(5, 3))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), x(t) + y(t) + 81), Eq(diff(y(t),t), -2*x(t) + y(t) + 23)) sol = [Eq(x(t), (C1*sin(sqrt(2)*t) + C2*cos(sqrt(2)*t))*exp(t) - Rational(58, 3)), \ Eq(y(t), (sqrt(2)*C1*cos(sqrt(2)*t) - sqrt(2)*C2*sin(sqrt(2)*t))*exp(t) - Rational(185, 3))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t))) sol = [Eq(x(t), (C1*exp(Integral(2, t).doit()) + C2*exp(-(Integral(2, t)).doit()))*\ exp((Integral(5*t, t)).doit())), Eq(y(t), (C1*exp((Integral(2, t)).doit()) - \ C2*exp(-(Integral(2, t)).doit()))*exp((Integral(5*t, t)).doit()))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t))) sol = [Eq(x(t), (C1*cos((Integral(t**2, t)).doit()) + C2*sin((Integral(t**2, t)).doit()))*\ exp((Integral(5*t, t)).doit())), Eq(y(t), (-C1*sin((Integral(t**2, t)).doit()) + \ C2*cos((Integral(t**2, t)).doit()))*exp((Integral(5*t, t)).doit()))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + (5*t+9*t**2)*y(t))) sol = [Eq(x(t), (C1*exp((-sqrt(77)/2 + Rational(9, 2))*(Integral(t**2, t)).doit()) + \ C2*exp((sqrt(77)/2 + Rational(9, 2))*(Integral(t**2, t)).doit()))*exp((Integral(5*t, t)).doit())), \ Eq(y(t), (C1*(-sqrt(77)/2 + Rational(9, 2))*exp((-sqrt(77)/2 + Rational(9, 2))*(Integral(t**2, t)).doit()) + \ C2*(sqrt(77)/2 + Rational(9, 2))*exp((sqrt(77)/2 + Rational(9, 2))*(Integral(t**2, t)).doit()))*exp((Integral(5*t, t)).doit()))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t,t), 5*x(t) + 43*y(t)), Eq(diff(y(t),t,t), x(t) + 9*y(t))) root0 = -sqrt(-sqrt(47) + 7) root1 = sqrt(-sqrt(47) + 7) root2 = -sqrt(sqrt(47) + 7) root3 = sqrt(sqrt(47) + 7) sol = [Eq(x(t), 43*C1*exp(t*root0) + 43*C2*exp(t*root1) + 43*C3*exp(t*root2) + 43*C4*exp(t*root3)), \ Eq(y(t), C1*(root0**2 - 5)*exp(t*root0) + C2*(root1**2 - 5)*exp(t*root1) + \ C3*(root2**2 - 5)*exp(t*root2) + C4*(root3**2 - 5)*exp(t*root3))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t,t), 8*x(t)+3*y(t)+31), Eq(diff(y(t),t,t), 9*x(t)+7*y(t)+12)) root0 = -sqrt(-sqrt(109)/2 + Rational(15, 2)) root1 = sqrt(-sqrt(109)/2 + Rational(15, 2)) root2 = -sqrt(sqrt(109)/2 + Rational(15, 2)) root3 = sqrt(sqrt(109)/2 + Rational(15, 2)) sol = [Eq(x(t), 3*C1*exp(t*root0) + 3*C2*exp(t*root1) + 3*C3*exp(t*root2) + 3*C4*exp(t*root3) - Rational(181, 29)), \ Eq(y(t), C1*(root0**2 - 8)*exp(t*root0) + C2*(root1**2 - 8)*exp(t*root1) + \ C3*(root2**2 - 8)*exp(t*root2) + C4*(root3**2 - 8)*exp(t*root3) + Rational(183, 29))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t,t) - 9*diff(y(t),t) + 7*x(t),0), Eq(diff(y(t),t,t) + 9*diff(x(t),t) + 7*y(t),0)) sol = [Eq(x(t), C1*cos(t*(Rational(9, 2) + sqrt(109)/2)) + C2*sin(t*(Rational(9, 2) + sqrt(109)/2)) + \ C3*cos(t*(-sqrt(109)/2 + Rational(9, 2))) + C4*sin(t*(-sqrt(109)/2 + Rational(9, 2)))), Eq(y(t), -C1*sin(t*(Rational(9, 2) + sqrt(109)/2)) \ + C2*cos(t*(Rational(9, 2) + sqrt(109)/2)) - C3*sin(t*(-sqrt(109)/2 + Rational(9, 2))) + C4*cos(t*(-sqrt(109)/2 + Rational(9, 2))))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t,t), 9*t*diff(y(t),t)-9*y(t)), Eq(diff(y(t),t,t),7*t*diff(x(t),t)-7*x(t))) I1 = sqrt(6)*7**Rational(1, 4)*sqrt(pi)*erfi(sqrt(6)*7**Rational(1, 4)*t/2)/2 - exp(3*sqrt(7)*t**2/2)/t I2 = -sqrt(6)*7**Rational(1, 4)*sqrt(pi)*erf(sqrt(6)*7**Rational(1, 4)*t/2)/2 - exp(-3*sqrt(7)*t**2/2)/t sol = [Eq(x(t), C3*t + t*(9*C1*I1 + 9*C2*I2)), Eq(y(t), C4*t + t*(3*sqrt(7)*C1*I1 - 3*sqrt(7)*C2*I2))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 21*x(t)), Eq(diff(y(t),t), 17*x(t)+3*y(t)), Eq(diff(z(t),t), 5*x(t)+7*y(t)+9*z(t))) sol = [Eq(x(t), C1*exp(21*t)), Eq(y(t), 17*C1*exp(21*t)/18 + C2*exp(3*t)), \ Eq(z(t), 209*C1*exp(21*t)/216 - 7*C2*exp(3*t)/6 + C3*exp(9*t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(diff(x(t),t),3*y(t)-11*z(t)),Eq(diff(y(t),t),7*z(t)-3*x(t)),Eq(diff(z(t),t),11*x(t)-7*y(t))) sol = [Eq(x(t), 7*C0 + sqrt(179)*C1*cos(sqrt(179)*t) + (77*C1/3 + 130*C2/3)*sin(sqrt(179)*t)), \ Eq(y(t), 11*C0 + sqrt(179)*C2*cos(sqrt(179)*t) + (-58*C1/3 - 77*C2/3)*sin(sqrt(179)*t)), \ Eq(z(t), 3*C0 + sqrt(179)*(-7*C1/3 - 11*C2/3)*cos(sqrt(179)*t) + (11*C1 - 7*C2)*sin(sqrt(179)*t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(3*diff(x(t),t),4*5*(y(t)-z(t))),Eq(4*diff(y(t),t),3*5*(z(t)-x(t))),Eq(5*diff(z(t),t),3*4*(x(t)-y(t)))) sol = [Eq(x(t), C0 + 5*sqrt(2)*C1*cos(5*sqrt(2)*t) + (12*C1/5 + 164*C2/15)*sin(5*sqrt(2)*t)), \ Eq(y(t), C0 + 5*sqrt(2)*C2*cos(5*sqrt(2)*t) + (-51*C1/10 - 12*C2/5)*sin(5*sqrt(2)*t)), \ Eq(z(t), C0 + 5*sqrt(2)*(-9*C1/25 - 16*C2/25)*cos(5*sqrt(2)*t) + (12*C1/5 - 12*C2/5)*sin(5*sqrt(2)*t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(diff(x(t),t),4*x(t) - z(t)),Eq(diff(y(t),t),2*x(t)+2*y(t)-z(t)),Eq(diff(z(t),t),3*x(t)+y(t))) sol = [Eq(x(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t) + C3*exp(2*t)), \ Eq(y(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t)), \ Eq(z(t), 2*C1*exp(2*t) + 2*C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t) + C3*t*exp(2*t) + C3*exp(2*t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(diff(x(t),t),4*x(t) - y(t) - 2*z(t)),Eq(diff(y(t),t),2*x(t) + y(t)- 2*z(t)),Eq(diff(z(t),t),5*x(t)-3*z(t))) sol = [Eq(x(t), C1*exp(2*t) + C2*(-sin(t) + 3*cos(t)) + C3*(3*sin(t) + cos(t))), \ Eq(y(t), C2*(-sin(t) + 3*cos(t)) + C3*(3*sin(t) + cos(t))), Eq(z(t), C1*exp(2*t) + 5*C2*cos(t) + 5*C3*sin(t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(diff(x(t),t),x(t)*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol = [Eq(x(t), C1*exp((-1/(4*C2 + 4*t))**(Rational(-1, 4)))), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), \ Eq(x(t), C1*exp(-1/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), \ Eq(x(t), C1*exp(-I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), \ Eq(x(t), C1*exp(I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), exp(3*x(t))*y(t)**3),Eq(diff(y(t),t), y(t)**5)) sol = [Eq(x(t), -log(C1 - 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), \ Eq(x(t), -log(C1 + 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), \ Eq(x(t), -log(C1 + 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), \ Eq(x(t), -log(C1 - 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(x(t),t*diff(x(t),t)+diff(x(t),t)*diff(y(t),t)), Eq(y(t),t*diff(y(t),t)+diff(y(t),t)**2)) sol = {Eq(x(t), C1*C2 + C1*t), Eq(y(t), C2**2 + C2*t)} assert checksysodesol(eq, sol) == (True, [0, 0])
d9793567326caae8f865ebecfe8fdf1dc10a46f885a7698fefd129c59bb45bc0
# # 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)] 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) 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) 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) 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 + C1*exp(t*(-R - sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)) + C2*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), C1*exp(t*(-R - sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)) + C2*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) + C2*exp(x*(-2 - sqrt(2))) + C3*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
be0d72cbff9ae71d579b621c564122e5c0f6b80e70139823aa97c1c24575bd97
from sympy.core.function import Function from sympy.core.numbers import Rational from sympy.core.relational import Eq from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (atan, sin, tan) from sympy.solvers.ode import (classify_ode, checkinfsol, dsolve, infinitesimals) from sympy.solvers.ode.subscheck import checkodesol from sympy.testing.pytest import XFAIL C1 = Symbol('C1') x, y = symbols("x y") f = Function('f') xi = Function('xi') eta = Function('eta') def test_heuristic1(): a, b, c, a4, a3, a2, a1, a0 = symbols("a b c a4 a3 a2 a1 a0") df = f(x).diff(x) eq = Eq(df, x**2*f(x)) eq1 = f(x).diff(x) + a*f(x) - c*exp(b*x) eq2 = f(x).diff(x) + 2*x*f(x) - x*exp(-x**2) eq3 = (1 + 2*x)*df + 2 - 4*exp(-f(x)) eq4 = f(x).diff(x) - (a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**Rational(-1, 2) eq5 = x**2*df - f(x) + x**2*exp(x - (1/x)) eqlist = [eq, eq1, eq2, eq3, eq4, eq5] i = infinitesimals(eq, hint='abaco1_simple') assert i == [{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}, {eta(x, f(x)): f(x), xi(x, f(x)): 0}, {eta(x, f(x)): 0, xi(x, f(x)): x**(-2)}] i1 = infinitesimals(eq1, hint='abaco1_simple') assert i1 == [{eta(x, f(x)): exp(-a*x), xi(x, f(x)): 0}] i2 = infinitesimals(eq2, hint='abaco1_simple') assert i2 == [{eta(x, f(x)): exp(-x**2), xi(x, f(x)): 0}] i3 = infinitesimals(eq3, hint='abaco1_simple') assert i3 == [{eta(x, f(x)): 0, xi(x, f(x)): 2*x + 1}, {eta(x, f(x)): 0, xi(x, f(x)): 1/(exp(f(x)) - 2)}] i4 = infinitesimals(eq4, hint='abaco1_simple') assert i4 == [{eta(x, f(x)): 1, xi(x, f(x)): 0}, {eta(x, f(x)): 0, xi(x, f(x)): sqrt(a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4)}] i5 = infinitesimals(eq5, hint='abaco1_simple') assert i5 == [{xi(x, f(x)): 0, eta(x, f(x)): exp(-1/x)}] ilist = [i, i1, i2, i3, i4, i5] for eq, i in (zip(eqlist, ilist)): check = checkinfsol(eq, i) assert check[0] # This ODE can be solved by the Lie Group method, when there are # better assumptions eq6 = df - (f(x)/x)*(x*log(x**2/f(x)) + 2) i = infinitesimals(eq6, hint='abaco1_product') assert i == [{eta(x, f(x)): f(x)*exp(-x), xi(x, f(x)): 0}] assert checkinfsol(eq6, i)[0] eq7 = x*(f(x).diff(x)) + 1 - f(x)**2 i = infinitesimals(eq7, hint='chi') assert checkinfsol(eq7, i)[0] def test_heuristic3(): a, b = symbols("a b") df = f(x).diff(x) eq = x**2*df + x*f(x) + f(x)**2 + x**2 i = infinitesimals(eq, hint='bivariate') assert i == [{eta(x, f(x)): f(x), xi(x, f(x)): x}] assert checkinfsol(eq, i)[0] eq = x**2*(-f(x)**2 + df)- a*x**2*f(x) + 2 - a*x i = infinitesimals(eq, hint='bivariate') assert checkinfsol(eq, i)[0] def test_heuristic_function_sum(): eq = f(x).diff(x) - (3*(1 + x**2/f(x)**2)*atan(f(x)/x) + (1 - 2*f(x))/x + (1 - 3*f(x))*(x/f(x)**2)) i = infinitesimals(eq, hint='function_sum') assert i == [{eta(x, f(x)): f(x)**(-2) + x**(-2), xi(x, f(x)): 0}] assert checkinfsol(eq, i)[0] def test_heuristic_abaco2_similar(): a, b = symbols("a b") F = Function('F') eq = f(x).diff(x) - F(a*x + b*f(x)) i = infinitesimals(eq, hint='abaco2_similar') assert i == [{eta(x, f(x)): -a/b, xi(x, f(x)): 1}] assert checkinfsol(eq, i)[0] eq = f(x).diff(x) - (f(x)**2 / (sin(f(x) - x) - x**2 + 2*x*f(x))) i = infinitesimals(eq, hint='abaco2_similar') assert i == [{eta(x, f(x)): f(x)**2, xi(x, f(x)): f(x)**2}] assert checkinfsol(eq, i)[0] def test_heuristic_abaco2_unique_unknown(): a, b = symbols("a b") F = Function('F') eq = f(x).diff(x) - x**(a - 1)*(f(x)**(1 - b))*F(x**a/a + f(x)**b/b) i = infinitesimals(eq, hint='abaco2_unique_unknown') assert i == [{eta(x, f(x)): -f(x)*f(x)**(-b), xi(x, f(x)): x*x**(-a)}] assert checkinfsol(eq, i)[0] eq = f(x).diff(x) + tan(F(x**2 + f(x)**2) + atan(x/f(x))) i = infinitesimals(eq, hint='abaco2_unique_unknown') assert i == [{eta(x, f(x)): x, xi(x, f(x)): -f(x)}] assert checkinfsol(eq, i)[0] eq = (x*f(x).diff(x) + f(x) + 2*x)**2 -4*x*f(x) -4*x**2 -4*a i = infinitesimals(eq, hint='abaco2_unique_unknown') assert checkinfsol(eq, i)[0] def test_heuristic_linear(): a, b, m, n = symbols("a b m n") eq = x**(n*(m + 1) - m)*(f(x).diff(x)) - a*f(x)**n -b*x**(n*(m + 1)) i = infinitesimals(eq, hint='linear') assert checkinfsol(eq, i)[0] @XFAIL def test_kamke(): a, b, alpha, c = symbols("a b alpha c") eq = x**2*(a*f(x)**2+(f(x).diff(x))) + b*x**alpha + c i = infinitesimals(eq, hint='sum_function') # XFAIL assert checkinfsol(eq, i)[0] def test_user_infinitesimals(): x = Symbol("x") # assuming x is real generates an error eq = x*(f(x).diff(x)) + 1 - f(x)**2 sol = Eq(f(x), (C1 + x**2)/(C1 - x**2)) infinitesimals = {'xi':sqrt(f(x) - 1)/sqrt(f(x) + 1), 'eta':0} assert dsolve(eq, hint='lie_group', **infinitesimals) == sol assert checkodesol(eq, sol) == (True, 0) @XFAIL def test_lie_group_issue15219(): eqn = exp(f(x).diff(x)-f(x)) assert 'lie_group' not in classify_ode(eqn, f(x))
2d1c66b7d12b029c243e10bb728f3fdd472b0d447c7b0062a93222682ca1cf07
from sympy.core.function import (Derivative, Function, diff) from sympy.core.mul import Mul from sympy.core.numbers import (I, Rational, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.hyperbolic import sinh from sympy.functions.elementary.miscellaneous import sqrt from sympy.matrices.dense import Matrix from sympy.core.containers import Tuple from sympy.functions import exp, cos, sin, log, tan, Ci, Si, erf, erfi from sympy.matrices import dotprodsimp, NonSquareMatrixError from sympy.solvers.ode import dsolve from sympy.solvers.ode.ode import constant_renumber from sympy.solvers.ode.subscheck import checksysodesol from sympy.solvers.ode.systems import (_classify_linear_system, linear_ode_to_matrix, ODEOrderError, ODENonlinearError, _simpsol, _is_commutative_anti_derivative, linodesolve, canonical_odes, dsolve_system, _component_division, _eqs2dict, _dict2graph) from sympy.functions import airyai, airybi from sympy.integrals.integrals import Integral from sympy.simplify.ratsimp import ratsimp from sympy.testing.pytest import ON_TRAVIS, raises, slow, skip, XFAIL C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C0:11') x = symbols('x') f = Function('f') g = Function('g') h = Function('h') def test_linear_ode_to_matrix(): f, g, h = symbols("f, g, h", cls=Function) t = Symbol("t") funcs = [f(t), g(t), h(t)] f1 = f(t).diff(t) g1 = g(t).diff(t) h1 = h(t).diff(t) f2 = f(t).diff(t, 2) g2 = g(t).diff(t, 2) h2 = h(t).diff(t, 2) eqs_1 = [Eq(f1, g(t)), Eq(g1, f(t))] sol_1 = ([Matrix([[1, 0], [0, 1]]), Matrix([[ 0, 1], [1, 0]])], Matrix([[0],[0]])) assert linear_ode_to_matrix(eqs_1, funcs[:-1], t, 1) == sol_1 eqs_2 = [Eq(f1, f(t) + 2*g(t)), Eq(g1, h(t)), Eq(h1, g(t) + h(t) + f(t))] sol_2 = ([Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), Matrix([[1, 2, 0], [ 0, 0, 1], [1, 1, 1]])], Matrix([[0], [0], [0]])) assert linear_ode_to_matrix(eqs_2, funcs, t, 1) == sol_2 eqs_3 = [Eq(2*f1 + 3*h1, f(t) + g(t)), Eq(4*h1 + 5*g1, f(t) + h(t)), Eq(5*f1 + 4*g1, g(t) + h(t))] sol_3 = ([Matrix([[2, 0, 3], [0, 5, 4], [5, 4, 0]]), Matrix([[1, 1, 0], [1, 0, 1], [0, 1, 1]])], Matrix([[0], [0], [0]])) assert linear_ode_to_matrix(eqs_3, funcs, t, 1) == sol_3 eqs_4 = [Eq(f2 + h(t), f1 + g(t)), Eq(2*h2 + g2 + g1 + g(t), 0), Eq(3*h1, 4)] sol_4 = ([Matrix([[1, 0, 0], [0, 1, 2], [0, 0, 0]]), Matrix([[1, 0, 0], [0, -1, 0], [0, 0, -3]]), Matrix([[0, 1, -1], [0, -1, 0], [0, 0, 0]])], Matrix([[0], [0], [4]])) assert linear_ode_to_matrix(eqs_4, funcs, t, 2) == sol_4 eqs_5 = [Eq(f2, g(t)), Eq(f1 + g1, f(t))] raises(ODEOrderError, lambda: linear_ode_to_matrix(eqs_5, funcs[:-1], t, 1)) eqs_6 = [Eq(f1, f(t)**2), Eq(g1, f(t) + g(t))] raises(ODENonlinearError, lambda: linear_ode_to_matrix(eqs_6, funcs[:-1], t, 1)) def test__classify_linear_system(): x, y, z, w = symbols('x, y, z, w', cls=Function) t, k, l = symbols('t k l') x1 = diff(x(t), t) y1 = diff(y(t), t) z1 = diff(z(t), t) w1 = diff(w(t), t) x2 = diff(x(t), t, t) y2 = diff(y(t), t, t) funcs = [x(t), y(t)] funcs_2 = funcs + [z(t), w(t)] eqs_1 = (5 * x1 + 12 * x(t) - 6 * (y(t)), (2 * y1 - 11 * t * x(t) + 3 * y(t) + t)) assert _classify_linear_system(eqs_1, funcs, t) is None eqs_2 = (5 * (x1**2) + 12 * x(t) - 6 * (y(t)), (2 * y1 - 11 * t * x(t) + 3 * y(t) + t)) sol2 = {'is_implicit': True, 'canon_eqs': [[Eq(Derivative(x(t), t), -sqrt(-12*x(t)/5 + 6*y(t)/5)), Eq(Derivative(y(t), t), 11*t*x(t)/2 - t/2 - 3*y(t)/2)], [Eq(Derivative(x(t), t), sqrt(-12*x(t)/5 + 6*y(t)/5)), Eq(Derivative(y(t), t), 11*t*x(t)/2 - t/2 - 3*y(t)/2)]]} assert _classify_linear_system(eqs_2, funcs, t) == sol2 eqs_2_1 = [Eq(Derivative(x(t), t), -sqrt(-12*x(t)/5 + 6*y(t)/5)), Eq(Derivative(y(t), t), 11*t*x(t)/2 - t/2 - 3*y(t)/2)] assert _classify_linear_system(eqs_2_1, funcs, t) is None eqs_2_2 = [Eq(Derivative(x(t), t), sqrt(-12*x(t)/5 + 6*y(t)/5)), Eq(Derivative(y(t), t), 11*t*x(t)/2 - t/2 - 3*y(t)/2)] assert _classify_linear_system(eqs_2_2, funcs, t) is None eqs_3 = (5 * x1 + 12 * x(t) - 6 * (y(t)), (2 * y1 - 11 * x(t) + 3 * y(t)), (5 * w1 + z(t)), (z1 + w(t))) answer_3 = {'no_of_equation': 4, 'eq': (12*x(t) - 6*y(t) + 5*Derivative(x(t), t), -11*x(t) + 3*y(t) + 2*Derivative(y(t), t), z(t) + 5*Derivative(w(t), t), w(t) + Derivative(z(t), t)), 'func': [x(t), y(t), z(t), w(t)], 'order': {x(t): 1, y(t): 1, z(t): 1, w(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [Rational(12, 5), Rational(-6, 5), 0, 0], [Rational(-11, 2), Rational(3, 2), 0, 0], [0, 0, 0, 1], [0, 0, Rational(1, 5), 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_3, funcs_2, t) == answer_3 eqs_4 = (5 * x1 + 12 * x(t) - 6 * (y(t)), (2 * y1 - 11 * x(t) + 3 * y(t)), (z1 - w(t)), (w1 - z(t))) answer_4 = {'no_of_equation': 4, 'eq': (12 * x(t) - 6 * y(t) + 5 * Derivative(x(t), t), -11 * x(t) + 3 * y(t) + 2 * Derivative(y(t), t), -w(t) + Derivative(z(t), t), -z(t) + Derivative(w(t), t)), 'func': [x(t), y(t), z(t), w(t)], 'order': {x(t): 1, y(t): 1, z(t): 1, w(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [Rational(12, 5), Rational(-6, 5), 0, 0], [Rational(-11, 2), Rational(3, 2), 0, 0], [0, 0, 0, -1], [0, 0, -1, 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_4, funcs_2, t) == answer_4 eqs_5 = (5*x1 + 12*x(t) - 6*(y(t)) + x2, (2*y1 - 11*x(t) + 3*y(t)), (z1 - w(t)), (w1 - z(t))) answer_5 = {'no_of_equation': 4, 'eq': (12*x(t) - 6*y(t) + 5*Derivative(x(t), t) + Derivative(x(t), (t, 2)), -11*x(t) + 3*y(t) + 2*Derivative(y(t), t), -w(t) + Derivative(z(t), t), -z(t) + Derivative(w(t), t)), 'func': [x(t), y(t), z(t), w(t)], 'order': {x(t): 2, y(t): 1, z(t): 1, w(t): 1}, 'is_linear': True, 'is_homogeneous': True, 'is_general': True, 'type_of_equation': 'type0', 'is_higher_order': True} assert _classify_linear_system(eqs_5, funcs_2, t) == answer_5 eqs_6 = (Eq(x1, 3*y(t) - 11*z(t)), Eq(y1, 7*z(t) - 3*x(t)), Eq(z1, 11*x(t) - 7*y(t))) answer_6 = {'no_of_equation': 3, 'eq': (Eq(Derivative(x(t), t), 3*y(t) - 11*z(t)), Eq(Derivative(y(t), t), -3*x(t) + 7*z(t)), Eq(Derivative(z(t), t), 11*x(t) - 7*y(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [ 0, -3, 11], [ 3, 0, -7], [-11, 7, 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_6, funcs_2[:-1], t) == answer_6 eqs_7 = (Eq(x1, y(t)), Eq(y1, x(t))) answer_7 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), t), y(t)), Eq(Derivative(y(t), t), x(t))), 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [ 0, -1], [-1, 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_7, funcs, t) == answer_7 eqs_8 = (Eq(x1, 21*x(t)), Eq(y1, 17*x(t) + 3*y(t)), Eq(z1, 5*x(t) + 7*y(t) + 9*z(t))) answer_8 = {'no_of_equation': 3, 'eq': (Eq(Derivative(x(t), t), 21*x(t)), Eq(Derivative(y(t), t), 17*x(t) + 3*y(t)), Eq(Derivative(z(t), t), 5*x(t) + 7*y(t) + 9*z(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [-21, 0, 0], [-17, -3, 0], [ -5, -7, -9]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_8, funcs_2[:-1], t) == answer_8 eqs_9 = (Eq(x1, 4*x(t) + 5*y(t) + 2*z(t)), Eq(y1, x(t) + 13*y(t) + 9*z(t)), Eq(z1, 32*x(t) + 41*y(t) + 11*z(t))) answer_9 = {'no_of_equation': 3, 'eq': (Eq(Derivative(x(t), t), 4*x(t) + 5*y(t) + 2*z(t)), Eq(Derivative(y(t), t), x(t) + 13*y(t) + 9*z(t)), Eq(Derivative(z(t), t), 32*x(t) + 41*y(t) + 11*z(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [ -4, -5, -2], [ -1, -13, -9], [-32, -41, -11]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_9, funcs_2[:-1], t) == answer_9 eqs_10 = (Eq(3*x1, 4*5*(y(t) - z(t))), Eq(4*y1, 3*5*(z(t) - x(t))), Eq(5*z1, 3*4*(x(t) - y(t)))) answer_10 = {'no_of_equation': 3, 'eq': (Eq(3*Derivative(x(t), t), 20*y(t) - 20*z(t)), Eq(4*Derivative(y(t), t), -15*x(t) + 15*z(t)), Eq(5*Derivative(z(t), t), 12*x(t) - 12*y(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [ 0, Rational(-20, 3), Rational(20, 3)], [Rational(15, 4), 0, Rational(-15, 4)], [Rational(-12, 5), Rational(12, 5), 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_10, funcs_2[:-1], t) == answer_10 eq11 = (Eq(x1, 3*y(t) - 11*z(t)), Eq(y1, 7*z(t) - 3*x(t)), Eq(z1, 11*x(t) - 7*y(t))) sol11 = {'no_of_equation': 3, 'eq': (Eq(Derivative(x(t), t), 3*y(t) - 11*z(t)), Eq(Derivative(y(t), t), -3*x(t) + 7*z(t)), Eq(Derivative(z(t), t), 11*x(t) - 7*y(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [ 0, -3, 11], [ 3, 0, -7], [-11, 7, 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eq11, funcs_2[:-1], t) == sol11 eq12 = (Eq(Derivative(x(t), t), y(t)), Eq(Derivative(y(t), t), x(t))) sol12 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), t), y(t)), Eq(Derivative(y(t), t), x(t))), 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [0, -1], [-1, 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eq12, [x(t), y(t)], t) == sol12 eq13 = (Eq(Derivative(x(t), t), 21*x(t)), Eq(Derivative(y(t), t), 17*x(t) + 3*y(t)), Eq(Derivative(z(t), t), 5*x(t) + 7*y(t) + 9*z(t))) sol13 = {'no_of_equation': 3, 'eq': ( Eq(Derivative(x(t), t), 21 * x(t)), Eq(Derivative(y(t), t), 17 * x(t) + 3 * y(t)), Eq(Derivative(z(t), t), 5 * x(t) + 7 * y(t) + 9 * z(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [-21, 0, 0], [-17, -3, 0], [-5, -7, -9]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eq13, [x(t), y(t), z(t)], t) == sol13 eq14 = ( Eq(Derivative(x(t), t), 4*x(t) + 5*y(t) + 2*z(t)), Eq(Derivative(y(t), t), x(t) + 13*y(t) + 9*z(t)), Eq(Derivative(z(t), t), 32*x(t) + 41*y(t) + 11*z(t))) sol14 = {'no_of_equation': 3, 'eq': ( Eq(Derivative(x(t), t), 4 * x(t) + 5 * y(t) + 2 * z(t)), Eq(Derivative(y(t), t), x(t) + 13 * y(t) + 9 * z(t)), Eq(Derivative(z(t), t), 32 * x(t) + 41 * y(t) + 11 * z(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [-4, -5, -2], [-1, -13, -9], [-32, -41, -11]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eq14, [x(t), y(t), z(t)], t) == sol14 eq15 = (Eq(3*Derivative(x(t), t), 20*y(t) - 20*z(t)), Eq(4*Derivative(y(t), t), -15*x(t) + 15*z(t)), Eq(5*Derivative(z(t), t), 12*x(t) - 12*y(t))) sol15 = {'no_of_equation': 3, 'eq': ( Eq(3 * Derivative(x(t), t), 20 * y(t) - 20 * z(t)), Eq(4 * Derivative(y(t), t), -15 * x(t) + 15 * z(t)), Eq(5 * Derivative(z(t), t), 12 * x(t) - 12 * y(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [0, Rational(-20, 3), Rational(20, 3)], [Rational(15, 4), 0, Rational(-15, 4)], [Rational(-12, 5), Rational(12, 5), 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eq15, [x(t), y(t), z(t)], t) == sol15 # Constant coefficient homogeneous ODEs eq1 = (Eq(diff(x(t), t), x(t) + y(t) + 9), Eq(diff(y(t), t), 2*x(t) + 5*y(t) + 23)) sol1 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), t), x(t) + y(t) + 9), Eq(Derivative(y(t), t), 2*x(t) + 5*y(t) + 23)), 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([[-1, -1], [-2, -5]]), 'rhs': Matrix([[ 9], [23]]), 'type_of_equation': 'type2'} assert _classify_linear_system(eq1, funcs, t) == sol1 # Non constant coefficient homogeneous ODEs eq1 = (Eq(diff(x(t), t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t), t), 2*x(t) + 5*t*y(t))) sol1 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), t), 5*t*x(t) + 2*y(t)), Eq(Derivative(y(t), t), 5*t*y(t) + 2*x(t))), 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': False, 'is_homogeneous': True, 'func_coeff': -Matrix([ [-5*t, -2], [ -2, -5*t]]), 'commutative_antiderivative': Matrix([ [5*t**2/2, 2*t], [ 2*t, 5*t**2/2]]), 'type_of_equation': 'type3', 'is_general': True} assert _classify_linear_system(eq1, funcs, t) == sol1 # Non constant coefficient non-homogeneous ODEs eq1 = [Eq(x1, x(t) + t*y(t) + t), Eq(y1, t*x(t) + y(t))] sol1 = {'no_of_equation': 2, 'eq': [Eq(Derivative(x(t), t), t*y(t) + t + x(t)), Eq(Derivative(y(t), t), t*x(t) + y(t))], 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': False, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-1, -t], [-t, -1]]), 'commutative_antiderivative': Matrix([ [ t, t**2/2], [t**2/2, t]]), 'rhs': Matrix([ [t], [0]]), 'type_of_equation': 'type4'} assert _classify_linear_system(eq1, funcs, t) == sol1 eq2 = [Eq(x1, t*x(t) + t*y(t) + t), Eq(y1, t*x(t) + t*y(t) + cos(t))] sol2 = {'no_of_equation': 2, 'eq': [Eq(Derivative(x(t), t), t*x(t) + t*y(t) + t), Eq(Derivative(y(t), t), t*x(t) + t*y(t) + cos(t))], 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_homogeneous': False, 'is_general': True, 'rhs': Matrix([ [ t], [cos(t)]]), 'func_coeff': Matrix([ [t, t], [t, t]]), 'is_constant': False, 'type_of_equation': 'type4', 'commutative_antiderivative': Matrix([ [t**2/2, t**2/2], [t**2/2, t**2/2]])} assert _classify_linear_system(eq2, funcs, t) == sol2 eq3 = [Eq(x1, t*(x(t) + y(t) + z(t) + 1)), Eq(y1, t*(x(t) + y(t) + z(t))), Eq(z1, t*(x(t) + y(t) + z(t)))] sol3 = {'no_of_equation': 3, 'eq': [Eq(Derivative(x(t), t), t*(x(t) + y(t) + z(t) + 1)), Eq(Derivative(y(t), t), t*(x(t) + y(t) + z(t))), Eq(Derivative(z(t), t), t*(x(t) + y(t) + z(t)))], 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': False, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-t, -t, -t], [-t, -t, -t], [-t, -t, -t]]), 'commutative_antiderivative': Matrix([ [t**2/2, t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2]]), 'rhs': Matrix([ [t], [0], [0]]), 'type_of_equation': 'type4'} assert _classify_linear_system(eq3, funcs_2[:-1], t) == sol3 eq4 = [Eq(x1, x(t) + y(t) + t*z(t) + 1), Eq(y1, x(t) + t*y(t) + z(t) + 10), Eq(z1, t*x(t) + y(t) + z(t) + t)] sol4 = {'no_of_equation': 3, 'eq': [Eq(Derivative(x(t), t), t*z(t) + x(t) + y(t) + 1), Eq(Derivative(y(t), t), t*y(t) + x(t) + z(t) + 10), Eq(Derivative(z(t), t), t*x(t) + t + y(t) + z(t))], 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': False, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-1, -1, -t], [-1, -t, -1], [-t, -1, -1]]), 'commutative_antiderivative': Matrix([ [ t, t, t**2/2], [ t, t**2/2, t], [t**2/2, t, t]]), 'rhs': Matrix([ [ 1], [10], [ t]]), 'type_of_equation': 'type4'} assert _classify_linear_system(eq4, funcs_2[:-1], t) == sol4 sum_terms = t*(x(t) + y(t) + z(t) + w(t)) eq5 = [Eq(x1, sum_terms), Eq(y1, sum_terms), Eq(z1, sum_terms + 1), Eq(w1, sum_terms)] sol5 = {'no_of_equation': 4, 'eq': [Eq(Derivative(x(t), t), t*(w(t) + x(t) + y(t) + z(t))), Eq(Derivative(y(t), t), t*(w(t) + x(t) + y(t) + z(t))), Eq(Derivative(z(t), t), t*(w(t) + x(t) + y(t) + z(t)) + 1), Eq(Derivative(w(t), t), t*(w(t) + x(t) + y(t) + z(t)))], 'func': [x(t), y(t), z(t), w(t)], 'order': {x(t): 1, y(t): 1, z(t): 1, w(t): 1}, 'is_linear': True, 'is_constant': False, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-t, -t, -t, -t], [-t, -t, -t, -t], [-t, -t, -t, -t], [-t, -t, -t, -t]]), 'commutative_antiderivative': Matrix([ [t**2/2, t**2/2, t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2, t**2/2]]), 'rhs': Matrix([ [0], [0], [1], [0]]), 'type_of_equation': 'type4'} assert _classify_linear_system(eq5, funcs_2, t) == sol5 # Second Order t_ = symbols("t_") eq1 = (Eq(9*x(t) + 7*y(t) + 4*Derivative(x(t), t) + Derivative(x(t), (t, 2)) + 3*Derivative(y(t), t), 11*exp(I*t)), Eq(3*x(t) + 12*y(t) + 5*Derivative(x(t), t) + 8*Derivative(y(t), t) + Derivative(y(t), (t, 2)), 2*exp(I*t))) sol1 = {'no_of_equation': 2, 'eq': (Eq(9*x(t) + 7*y(t) + 4*Derivative(x(t), t) + Derivative(x(t), (t, 2)) + 3*Derivative(y(t), t), 11*exp(I*t)), Eq(3*x(t) + 12*y(t) + 5*Derivative(x(t), t) + 8*Derivative(y(t), t) + Derivative(y(t), (t, 2)), 2*exp(I*t))), 'func': [x(t), y(t)], 'order': {x(t): 2, y(t): 2}, 'is_linear': True, 'is_homogeneous': False, 'is_general': True, 'rhs': Matrix([ [11*exp(I*t)], [ 2*exp(I*t)]]), 'type_of_equation': 'type0', 'is_second_order': True, 'is_higher_order': True} assert _classify_linear_system(eq1, funcs, t) == sol1 eq2 = (Eq((4*t**2 + 7*t + 1)**2*Derivative(x(t), (t, 2)), 5*x(t) + 35*y(t)), Eq((4*t**2 + 7*t + 1)**2*Derivative(y(t), (t, 2)), x(t) + 9*y(t))) sol2 = {'no_of_equation': 2, 'eq': (Eq((4*t**2 + 7*t + 1)**2*Derivative(x(t), (t, 2)), 5*x(t) + 35*y(t)), Eq((4*t**2 + 7*t + 1)**2*Derivative(y(t), (t, 2)), x(t) + 9*y(t))), 'func': [x(t), y(t)], 'order': {x(t): 2, y(t): 2}, 'is_linear': True, 'is_homogeneous': True, 'is_general': True, 'type_of_equation': 'type2', 'A0': Matrix([ [Rational(53, 4), 35], [ 1, Rational(69, 4)]]), 'g(t)': sqrt(4*t**2 + 7*t + 1), 'tau': sqrt(33)*log(t - sqrt(33)/8 + Rational(7, 8))/33 - sqrt(33)*log(t + sqrt(33)/8 + Rational(7, 8))/33, 'is_transformed': True, 't_': t_, 'is_second_order': True, 'is_higher_order': True} assert _classify_linear_system(eq2, funcs, t) == sol2 eq3 = ((t*Derivative(x(t), t) - x(t))*log(t) + (t*Derivative(y(t), t) - y(t))*exp(t) + Derivative(x(t), (t, 2)), t**2*(t*Derivative(x(t), t) - x(t)) + t*(t*Derivative(y(t), t) - y(t)) + Derivative(y(t), (t, 2))) sol3 = {'no_of_equation': 2, 'eq': ((t*Derivative(x(t), t) - x(t))*log(t) + (t*Derivative(y(t), t) - y(t))*exp(t) + Derivative(x(t), (t, 2)), t**2*(t*Derivative(x(t), t) - x(t)) + t*(t*Derivative(y(t), t) - y(t)) + Derivative(y(t), (t, 2))), 'func': [x(t), y(t)], 'order': {x(t): 2, y(t): 2}, 'is_linear': True, 'is_homogeneous': True, 'is_general': True, 'type_of_equation': 'type1', 'A1': Matrix([ [-t*log(t), -t*exp(t)], [ -t**3, -t**2]]), 'is_second_order': True, 'is_higher_order': True} assert _classify_linear_system(eq3, funcs, t) == sol3 eq4 = (Eq(x2, k*x(t) - l*y1), Eq(y2, l*x1 + k*y(t))) sol4 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), (t, 2)), k*x(t) - l*Derivative(y(t), t)), Eq(Derivative(y(t), (t, 2)), k*y(t) + l*Derivative(x(t), t))), 'func': [x(t), y(t)], 'order': {x(t): 2, y(t): 2}, 'is_linear': True, 'is_homogeneous': True, 'is_general': True, 'type_of_equation': 'type0', 'is_second_order': True, 'is_higher_order': True} assert _classify_linear_system(eq4, funcs, t) == sol4 # Multiple matchs f, g = symbols("f g", cls=Function) y, t_ = symbols("y t_") funcs = [f(t), g(t)] eq1 = [Eq(Derivative(f(t), t)**2 - 2*Derivative(f(t), t) + 1, 4), Eq(-y*f(t) + Derivative(g(t), t), 0)] sol1 = {'is_implicit': True, 'canon_eqs': [[Eq(Derivative(f(t), t), -1), Eq(Derivative(g(t), t), y*f(t))], [Eq(Derivative(f(t), t), 3), Eq(Derivative(g(t), t), y*f(t))]]} assert _classify_linear_system(eq1, funcs, t) == sol1 raises(ValueError, lambda: _classify_linear_system(eq1, funcs[:1], t)) eq2 = [Eq(Derivative(f(t), t), (2*f(t) + g(t) + 1)/t), Eq(Derivative(g(t), t), (f(t) + 2*g(t))/t)] sol2 = {'no_of_equation': 2, 'eq': [Eq(Derivative(f(t), t), (2*f(t) + g(t) + 1)/t), Eq(Derivative(g(t), t), (f(t) + 2*g(t))/t)], 'func': [f(t), g(t)], 'order': {f(t): 1, g(t): 1}, 'is_linear': True, 'is_homogeneous': False, 'is_general': True, 'rhs': Matrix([ [1], [0]]), 'func_coeff': Matrix([ [2, 1], [1, 2]]), 'is_constant': False, 'type_of_equation': 'type6', 't_': t_, 'tau': log(t), 'commutative_antiderivative': Matrix([ [2*log(t), log(t)], [ log(t), 2*log(t)]])} assert _classify_linear_system(eq2, funcs, t) == sol2 eq3 = [Eq(Derivative(f(t), t), (2*f(t) + g(t))/t), Eq(Derivative(g(t), t), (f(t) + 2*g(t))/t)] sol3 = {'no_of_equation': 2, 'eq': [Eq(Derivative(f(t), t), (2*f(t) + g(t))/t), Eq(Derivative(g(t), t), (f(t) + 2*g(t))/t)], 'func': [f(t), g(t)], 'order': {f(t): 1, g(t): 1}, 'is_linear': True, 'is_homogeneous': True, 'is_general': True, 'func_coeff': Matrix([ [2, 1], [1, 2]]), 'is_constant': False, 'type_of_equation': 'type5', 't_': t_, 'rhs': Matrix([ [0], [0]]), 'tau': log(t), 'commutative_antiderivative': Matrix([ [2*log(t), log(t)], [ log(t), 2*log(t)]])} assert _classify_linear_system(eq3, funcs, t) == sol3 def test_matrix_exp(): from sympy.matrices.dense import Matrix, eye, zeros from sympy.solvers.ode.systems import matrix_exp t = Symbol('t') for n in range(1, 6+1): assert matrix_exp(zeros(n), t) == eye(n) for n in range(1, 6+1): A = eye(n) expAt = exp(t) * eye(n) assert matrix_exp(A, t) == expAt for n in range(1, 6+1): A = Matrix(n, n, lambda i,j: i+1 if i==j else 0) expAt = Matrix(n, n, lambda i,j: exp((i+1)*t) if i==j else 0) assert matrix_exp(A, t) == expAt A = Matrix([[0, 1], [-1, 0]]) expAt = Matrix([[cos(t), sin(t)], [-sin(t), cos(t)]]) assert matrix_exp(A, t) == expAt A = Matrix([[2, -5], [2, -4]]) expAt = Matrix([ [3*exp(-t)*sin(t) + exp(-t)*cos(t), -5*exp(-t)*sin(t)], [2*exp(-t)*sin(t), -3*exp(-t)*sin(t) + exp(-t)*cos(t)] ]) assert matrix_exp(A, t) == expAt A = Matrix([[21, 17, 6], [-5, -1, -6], [4, 4, 16]]) # TO update this. # expAt = Matrix([ # [(8*t*exp(12*t) + 5*exp(12*t) - 1)*exp(4*t)/4, # (8*t*exp(12*t) + 5*exp(12*t) - 5)*exp(4*t)/4, # (exp(12*t) - 1)*exp(4*t)/2], # [(-8*t*exp(12*t) - exp(12*t) + 1)*exp(4*t)/4, # (-8*t*exp(12*t) - exp(12*t) + 5)*exp(4*t)/4, # (-exp(12*t) + 1)*exp(4*t)/2], # [4*t*exp(16*t), 4*t*exp(16*t), exp(16*t)]]) expAt = Matrix([ [2*t*exp(16*t) + 5*exp(16*t)/4 - exp(4*t)/4, 2*t*exp(16*t) + 5*exp(16*t)/4 - 5*exp(4*t)/4, exp(16*t)/2 - exp(4*t)/2], [ -2*t*exp(16*t) - exp(16*t)/4 + exp(4*t)/4, -2*t*exp(16*t) - exp(16*t)/4 + 5*exp(4*t)/4, -exp(16*t)/2 + exp(4*t)/2], [ 4*t*exp(16*t), 4*t*exp(16*t), exp(16*t)] ]) assert matrix_exp(A, t) == expAt A = Matrix([[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, -S(1)/8], [0, 0, S(1)/2, S(1)/2]]) expAt = Matrix([ [exp(t), t*exp(t), 4*t*exp(3*t/4) + 8*t*exp(t) + 48*exp(3*t/4) - 48*exp(t), -2*t*exp(3*t/4) - 2*t*exp(t) - 16*exp(3*t/4) + 16*exp(t)], [0, exp(t), -t*exp(3*t/4) - 8*exp(3*t/4) + 8*exp(t), t*exp(3*t/4)/2 + 2*exp(3*t/4) - 2*exp(t)], [0, 0, t*exp(3*t/4)/4 + exp(3*t/4), -t*exp(3*t/4)/8], [0, 0, t*exp(3*t/4)/2, -t*exp(3*t/4)/4 + exp(3*t/4)] ]) assert matrix_exp(A, t) == expAt A = Matrix([ [ 0, 1, 0, 0], [-1, 0, 0, 0], [ 0, 0, 0, 1], [ 0, 0, -1, 0]]) expAt = Matrix([ [ cos(t), sin(t), 0, 0], [-sin(t), cos(t), 0, 0], [ 0, 0, cos(t), sin(t)], [ 0, 0, -sin(t), cos(t)]]) assert matrix_exp(A, t) == expAt A = Matrix([ [ 0, 1, 1, 0], [-1, 0, 0, 1], [ 0, 0, 0, 1], [ 0, 0, -1, 0]]) expAt = Matrix([ [ cos(t), sin(t), t*cos(t), t*sin(t)], [-sin(t), cos(t), -t*sin(t), t*cos(t)], [ 0, 0, cos(t), sin(t)], [ 0, 0, -sin(t), cos(t)]]) assert matrix_exp(A, t) == expAt # This case is unacceptably slow right now but should be solvable... #a, b, c, d, e, f = symbols('a b c d e f') #A = Matrix([ #[-a, b, c, d], #[ a, -b, e, 0], #[ 0, 0, -c - e - f, 0], #[ 0, 0, f, -d]]) A = Matrix([[0, I], [I, 0]]) expAt = Matrix([ [exp(I*t)/2 + exp(-I*t)/2, exp(I*t)/2 - exp(-I*t)/2], [exp(I*t)/2 - exp(-I*t)/2, exp(I*t)/2 + exp(-I*t)/2]]) assert matrix_exp(A, t) == expAt # Testing Errors M = Matrix([[1, 2, 3], [4, 5, 6], [7, 7, 7]]) M1 = Matrix([[t, 1], [1, 1]]) raises(ValueError, lambda: matrix_exp(M[:, :2], t)) raises(ValueError, lambda: matrix_exp(M[:2, :], t)) raises(ValueError, lambda: matrix_exp(M1, t)) raises(ValueError, lambda: matrix_exp(M1[:1, :1], t)) def test_canonical_odes(): f, g, h = symbols('f g h', cls=Function) x = symbols('x') funcs = [f(x), g(x), h(x)] eqs1 = [Eq(f(x).diff(x, x), f(x) + 2*g(x)), Eq(g(x) + 1, g(x).diff(x) + f(x))] sol1 = [[Eq(Derivative(f(x), (x, 2)), f(x) + 2*g(x)), Eq(Derivative(g(x), x), -f(x) + g(x) + 1)]] assert canonical_odes(eqs1, funcs[:2], x) == sol1 eqs2 = [Eq(f(x).diff(x), h(x).diff(x) + f(x)), Eq(g(x).diff(x)**2, f(x) + h(x)), Eq(h(x).diff(x), f(x))] sol2 = [[Eq(Derivative(f(x), x), 2*f(x)), Eq(Derivative(g(x), x), -sqrt(f(x) + h(x))), Eq(Derivative(h(x), x), f(x))], [Eq(Derivative(f(x), x), 2*f(x)), Eq(Derivative(g(x), x), sqrt(f(x) + h(x))), Eq(Derivative(h(x), x), f(x))]] assert canonical_odes(eqs2, funcs, x) == sol2 def test_sysode_linear_neq_order1_type1(): f, g, x, y, h = symbols('f g x y h', cls=Function) a, b, c, t = symbols('a b c t') eqs1 = [Eq(Derivative(x(t), t), x(t)), Eq(Derivative(y(t), t), y(t))] sol1 = [Eq(x(t), C1*exp(t)), Eq(y(t), C2*exp(t))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) eqs2 = [Eq(Derivative(x(t), t), 2*x(t)), Eq(Derivative(y(t), t), 3*y(t))] sol2 = [Eq(x(t), C1*exp(2*t)), Eq(y(t), C2*exp(3*t))] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0]) eqs3 = [Eq(Derivative(x(t), t), a*x(t)), Eq(Derivative(y(t), t), a*y(t))] sol3 = [Eq(x(t), C1*exp(a*t)), Eq(y(t), C2*exp(a*t))] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0]) # Regression test case for issue #15474 # https://github.com/sympy/sympy/issues/15474 eqs4 = [Eq(Derivative(x(t), t), a*x(t)), Eq(Derivative(y(t), t), b*y(t))] sol4 = [Eq(x(t), C1*exp(a*t)), Eq(y(t), C2*exp(b*t))] assert dsolve(eqs4) == sol4 assert checksysodesol(eqs4, sol4) == (True, [0, 0]) eqs5 = [Eq(Derivative(x(t), t), -y(t)), Eq(Derivative(y(t), t), x(t))] sol5 = [Eq(x(t), -C1*sin(t) - C2*cos(t)), Eq(y(t), C1*cos(t) - C2*sin(t))] assert dsolve(eqs5) == sol5 assert checksysodesol(eqs5, sol5) == (True, [0, 0]) eqs6 = [Eq(Derivative(x(t), t), -2*y(t)), Eq(Derivative(y(t), t), 2*x(t))] sol6 = [Eq(x(t), -C1*sin(2*t) - C2*cos(2*t)), Eq(y(t), C1*cos(2*t) - C2*sin(2*t))] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0]) eqs7 = [Eq(Derivative(x(t), t), I*y(t)), Eq(Derivative(y(t), t), I*x(t))] sol7 = [Eq(x(t), -C1*exp(-I*t) + C2*exp(I*t)), Eq(y(t), C1*exp(-I*t) + C2*exp(I*t))] assert dsolve(eqs7) == sol7 assert checksysodesol(eqs7, sol7) == (True, [0, 0]) eqs8 = [Eq(Derivative(x(t), t), -a*y(t)), Eq(Derivative(y(t), t), a*x(t))] sol8 = [Eq(x(t), -I*C1*exp(-I*a*t) + I*C2*exp(I*a*t)), Eq(y(t), C1*exp(-I*a*t) + C2*exp(I*a*t))] assert dsolve(eqs8) == sol8 assert checksysodesol(eqs8, sol8) == (True, [0, 0]) eqs9 = [Eq(Derivative(x(t), t), x(t) + y(t)), Eq(Derivative(y(t), t), x(t) - y(t))] sol9 = [Eq(x(t), C1*(1 - sqrt(2))*exp(-sqrt(2)*t) + C2*(1 + sqrt(2))*exp(sqrt(2)*t)), Eq(y(t), C1*exp(-sqrt(2)*t) + C2*exp(sqrt(2)*t))] assert dsolve(eqs9) == sol9 assert checksysodesol(eqs9, sol9) == (True, [0, 0]) eqs10 = [Eq(Derivative(x(t), t), x(t) + y(t)), Eq(Derivative(y(t), t), x(t) + y(t))] sol10 = [Eq(x(t), -C1 + C2*exp(2*t)), Eq(y(t), C1 + C2*exp(2*t))] assert dsolve(eqs10) == sol10 assert checksysodesol(eqs10, sol10) == (True, [0, 0]) eqs11 = [Eq(Derivative(x(t), t), 2*x(t) + y(t)), Eq(Derivative(y(t), t), -x(t) + 2*y(t))] sol11 = [Eq(x(t), C1*exp(2*t)*sin(t) + C2*exp(2*t)*cos(t)), Eq(y(t), C1*exp(2*t)*cos(t) - C2*exp(2*t)*sin(t))] assert dsolve(eqs11) == sol11 assert checksysodesol(eqs11, sol11) == (True, [0, 0]) eqs12 = [Eq(Derivative(x(t), t), x(t) + 2*y(t)), Eq(Derivative(y(t), t), 2*x(t) + y(t))] sol12 = [Eq(x(t), -C1*exp(-t) + C2*exp(3*t)), Eq(y(t), C1*exp(-t) + C2*exp(3*t))] assert dsolve(eqs12) == sol12 assert checksysodesol(eqs12, sol12) == (True, [0, 0]) eqs13 = [Eq(Derivative(x(t), t), 4*x(t) + y(t)), Eq(Derivative(y(t), t), -x(t) + 2*y(t))] sol13 = [Eq(x(t), C2*t*exp(3*t) + (C1 + C2)*exp(3*t)), Eq(y(t), -C1*exp(3*t) - C2*t*exp(3*t))] assert dsolve(eqs13) == sol13 assert checksysodesol(eqs13, sol13) == (True, [0, 0]) eqs14 = [Eq(Derivative(x(t), t), a*y(t)), Eq(Derivative(y(t), t), a*x(t))] sol14 = [Eq(x(t), -C1*exp(-a*t) + C2*exp(a*t)), Eq(y(t), C1*exp(-a*t) + C2*exp(a*t))] assert dsolve(eqs14) == sol14 assert checksysodesol(eqs14, sol14) == (True, [0, 0]) eqs15 = [Eq(Derivative(x(t), t), a*y(t)), Eq(Derivative(y(t), t), b*x(t))] sol15 = [Eq(x(t), -C1*a*exp(-t*sqrt(a*b))/sqrt(a*b) + C2*a*exp(t*sqrt(a*b))/sqrt(a*b)), Eq(y(t), C1*exp(-t*sqrt(a*b)) + C2*exp(t*sqrt(a*b)))] assert dsolve(eqs15) == sol15 assert checksysodesol(eqs15, sol15) == (True, [0, 0]) eqs16 = [Eq(Derivative(x(t), t), a*x(t) + b*y(t)), Eq(Derivative(y(t), t), c*x(t))] sol16 = [Eq(x(t), -2*C1*b*exp(t*(a + sqrt(a**2 + 4*b*c))/2)/(a - sqrt(a**2 + 4*b*c)) - 2*C2*b*exp(t*(a - sqrt(a**2 + 4*b*c))/2)/(a + sqrt(a**2 + 4*b*c))), Eq(y(t), C1*exp(t*(a + sqrt(a**2 + 4*b*c))/2) + C2*exp(t*(a - sqrt(a**2 + 4*b*c))/2))] assert dsolve(eqs16) == sol16 assert checksysodesol(eqs16, sol16) == (True, [0, 0]) # Regression test case for issue #18562 # https://github.com/sympy/sympy/issues/18562 eqs17 = [Eq(Derivative(x(t), t), a*y(t) + x(t)), Eq(Derivative(y(t), t), a*x(t) - y(t))] sol17 = [Eq(x(t), C1*a*exp(t*sqrt(a**2 + 1))/(sqrt(a**2 + 1) - 1) - C2*a*exp(-t*sqrt(a**2 + 1))/(sqrt(a**2 + 1) + 1)), Eq(y(t), C1*exp(t*sqrt(a**2 + 1)) + C2*exp(-t*sqrt(a**2 + 1)))] assert dsolve(eqs17) == sol17 assert checksysodesol(eqs17, sol17) == (True, [0, 0]) eqs18 = [Eq(Derivative(x(t), t), 0), Eq(Derivative(y(t), t), 0)] sol18 = [Eq(x(t), C1), Eq(y(t), C2)] assert dsolve(eqs18) == sol18 assert checksysodesol(eqs18, sol18) == (True, [0, 0]) eqs19 = [Eq(Derivative(x(t), t), 2*x(t) - y(t)), Eq(Derivative(y(t), t), x(t))] sol19 = [Eq(x(t), C2*t*exp(t) + (C1 + C2)*exp(t)), Eq(y(t), C1*exp(t) + C2*t*exp(t))] assert dsolve(eqs19) == sol19 assert checksysodesol(eqs19, sol19) == (True, [0, 0]) eqs20 = [Eq(Derivative(x(t), t), x(t)), Eq(Derivative(y(t), t), x(t) + y(t))] sol20 = [Eq(x(t), C1*exp(t)), Eq(y(t), C1*t*exp(t) + C2*exp(t))] assert dsolve(eqs20) == sol20 assert checksysodesol(eqs20, sol20) == (True, [0, 0]) eqs21 = [Eq(Derivative(x(t), t), 3*x(t)), Eq(Derivative(y(t), t), x(t) + y(t))] sol21 = [Eq(x(t), 2*C1*exp(3*t)), Eq(y(t), C1*exp(3*t) + C2*exp(t))] assert dsolve(eqs21) == sol21 assert checksysodesol(eqs21, sol21) == (True, [0, 0]) eqs22 = [Eq(Derivative(x(t), t), 3*x(t)), Eq(Derivative(y(t), t), y(t))] sol22 = [Eq(x(t), C1*exp(3*t)), Eq(y(t), C2*exp(t))] assert dsolve(eqs22) == sol22 assert checksysodesol(eqs22, sol22) == (True, [0, 0]) @slow def test_sysode_linear_neq_order1_type1_slow(): t = Symbol('t') Z0 = Function('Z0') Z1 = Function('Z1') Z2 = Function('Z2') Z3 = Function('Z3') k01, k10, k20, k21, k23, k30 = symbols('k01 k10 k20 k21 k23 k30') eqs1 = [Eq(Derivative(Z0(t), t), -k01*Z0(t) + k10*Z1(t) + k20*Z2(t) + k30*Z3(t)), Eq(Derivative(Z1(t), t), k01*Z0(t) - k10*Z1(t) + k21*Z2(t)), Eq(Derivative(Z2(t), t), (-k20 - k21 - k23)*Z2(t)), Eq(Derivative(Z3(t), t), k23*Z2(t) - k30*Z3(t))] sol1 = [Eq(Z0(t), C1*k10/k01 - C2*(k10 - k30)*exp(-k30*t)/(k01 + k10 - k30) - C3*(k10*(k20 + k21 - k30) - k20**2 - k20*(k21 + k23 - k30) + k23*k30)*exp(-t*(k20 + k21 + k23))/(k23*(-k01 - k10 + k20 + k21 + k23)) - C4*exp(-t*(k01 + k10))), Eq(Z1(t), C1 - C2*k01*exp(-k30*t)/(k01 + k10 - k30) + C3*(-k01*(k20 + k21 - k30) + k20*k21 + k21**2 + k21*(k23 - k30))*exp(-t*(k20 + k21 + k23))/(k23*(-k01 - k10 + k20 + k21 + k23)) + C4*exp(-t*(k01 + k10))), Eq(Z2(t), -C3*(k20 + k21 + k23 - k30)*exp(-t*(k20 + k21 + k23))/k23), Eq(Z3(t), C2*exp(-k30*t) + C3*exp(-t*(k20 + k21 + k23)))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0, 0, 0]) x, y, z, u, v, w = symbols('x y z u v w', cls=Function) k2, k3 = symbols('k2 k3') a_b, a_c = symbols('a_b a_c', real=True) eqs2 = [Eq(Derivative(z(t), t), k2*y(t)), Eq(Derivative(x(t), t), k3*y(t)), Eq(Derivative(y(t), t), (-k2 - k3)*y(t))] sol2 = [Eq(z(t), C1 - C2*k2*exp(-t*(k2 + k3))/(k2 + k3)), Eq(x(t), -C2*k3*exp(-t*(k2 + k3))/(k2 + k3) + C3), Eq(y(t), C2*exp(-t*(k2 + k3)))] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0, 0]) eqs3 = [4*u(t) - v(t) - 2*w(t) + Derivative(u(t), t), 2*u(t) + v(t) - 2*w(t) + Derivative(v(t), t), 5*u(t) + v(t) - 3*w(t) + Derivative(w(t), t)] sol3 = [Eq(u(t), C3*exp(-2*t) + (C1/2 + sqrt(3)*C2/6)*cos(sqrt(3)*t) + sin(sqrt(3)*t)*(sqrt(3)*C1/6 + C2*Rational(-1, 2))), Eq(v(t), (C1/2 + sqrt(3)*C2/6)*cos(sqrt(3)*t) + sin(sqrt(3)*t)*(sqrt(3)*C1/6 + C2*Rational(-1, 2))), Eq(w(t), C1*cos(sqrt(3)*t) - C2*sin(sqrt(3)*t) + C3*exp(-2*t))] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0, 0]) eqs4 = [Eq(Derivative(x(t), t), w(t)*Rational(-2, 9) + 2*x(t) + y(t) + z(t)*Rational(-8, 9)), Eq(Derivative(y(t), t), w(t)*Rational(4, 9) + 2*y(t) + z(t)*Rational(16, 9)), Eq(Derivative(z(t), t), w(t)*Rational(-2, 9) + z(t)*Rational(37, 9)), Eq(Derivative(w(t), t), w(t)*Rational(44, 9) + z(t)*Rational(-4, 9))] sol4 = [Eq(x(t), C1*exp(2*t) + C2*t*exp(2*t)), Eq(y(t), C2*exp(2*t) + 2*C3*exp(4*t)), Eq(z(t), 2*C3*exp(4*t) + C4*exp(5*t)*Rational(-1, 4)), Eq(w(t), C3*exp(4*t) + C4*exp(5*t))] assert dsolve(eqs4) == sol4 assert checksysodesol(eqs4, sol4) == (True, [0, 0, 0, 0]) # Regression test case for issue #15574 # https://github.com/sympy/sympy/issues/15574 eq5 = [Eq(x(t).diff(t), x(t)), Eq(y(t).diff(t), y(t)), Eq(z(t).diff(t), z(t)), Eq(w(t).diff(t), w(t))] sol5 = [Eq(x(t), C1*exp(t)), Eq(y(t), C2*exp(t)), Eq(z(t), C3*exp(t)), Eq(w(t), C4*exp(t))] assert dsolve(eq5) == sol5 assert checksysodesol(eq5, sol5) == (True, [0, 0, 0, 0]) eqs6 = [Eq(Derivative(x(t), t), x(t) + y(t)), Eq(Derivative(y(t), t), y(t) + z(t)), Eq(Derivative(z(t), t), w(t)*Rational(-1, 8) + z(t)), Eq(Derivative(w(t), t), w(t)/2 + z(t)/2)] sol6 = [Eq(x(t), C1*exp(t) + C2*t*exp(t) + 4*C4*t*exp(t*Rational(3, 4)) + (4*C3 + 48*C4)*exp(t*Rational(3, 4))), Eq(y(t), C2*exp(t) - C4*t*exp(t*Rational(3, 4)) - (C3 + 8*C4)*exp(t*Rational(3, 4))), Eq(z(t), C4*t*exp(t*Rational(3, 4))/4 + (C3/4 + C4)*exp(t*Rational(3, 4))), Eq(w(t), C3*exp(t*Rational(3, 4))/2 + C4*t*exp(t*Rational(3, 4))/2)] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0, 0, 0]) # Regression test case for issue #15574 # https://github.com/sympy/sympy/issues/15574 eq7 = [Eq(Derivative(x(t), t), x(t)), Eq(Derivative(y(t), t), y(t)), Eq(Derivative(z(t), t), z(t)), Eq(Derivative(w(t), t), w(t)), Eq(Derivative(u(t), t), u(t))] sol7 = [Eq(x(t), C1*exp(t)), Eq(y(t), C2*exp(t)), Eq(z(t), C3*exp(t)), Eq(w(t), C4*exp(t)), Eq(u(t), C5*exp(t))] assert dsolve(eq7) == sol7 assert checksysodesol(eq7, sol7) == (True, [0, 0, 0, 0, 0]) eqs8 = [Eq(Derivative(x(t), t), 2*x(t) + y(t)), Eq(Derivative(y(t), t), 2*y(t)), Eq(Derivative(z(t), t), 4*z(t)), Eq(Derivative(w(t), t), u(t) + 5*w(t)), Eq(Derivative(u(t), t), 5*u(t))] sol8 = [Eq(x(t), C1*exp(2*t) + C2*t*exp(2*t)), Eq(y(t), C2*exp(2*t)), Eq(z(t), C3*exp(4*t)), Eq(w(t), C4*exp(5*t) + C5*t*exp(5*t)), Eq(u(t), C5*exp(5*t))] assert dsolve(eqs8) == sol8 assert checksysodesol(eqs8, sol8) == (True, [0, 0, 0, 0, 0]) # Regression test case for issue #15574 # https://github.com/sympy/sympy/issues/15574 eq9 = [Eq(Derivative(x(t), t), x(t)), Eq(Derivative(y(t), t), y(t)), Eq(Derivative(z(t), t), z(t))] sol9 = [Eq(x(t), C1*exp(t)), Eq(y(t), C2*exp(t)), Eq(z(t), C3*exp(t))] assert dsolve(eq9) == sol9 assert checksysodesol(eq9, sol9) == (True, [0, 0, 0]) # Regression test case for issue #15407 # https://github.com/sympy/sympy/issues/15407 eqs10 = [Eq(Derivative(x(t), t), (-a_b - a_c)*x(t)), Eq(Derivative(y(t), t), a_b*y(t)), Eq(Derivative(z(t), t), a_c*x(t))] sol10 = [Eq(x(t), -C1*(a_b + a_c)*exp(-t*(a_b + a_c))/a_c), Eq(y(t), C2*exp(a_b*t)), Eq(z(t), C1*exp(-t*(a_b + a_c)) + C3)] assert dsolve(eqs10) == sol10 assert checksysodesol(eqs10, sol10) == (True, [0, 0, 0]) # Regression test case for issue #14312 # https://github.com/sympy/sympy/issues/14312 eqs11 = [Eq(Derivative(x(t), t), k3*y(t)), Eq(Derivative(y(t), t), (-k2 - k3)*y(t)), Eq(Derivative(z(t), t), k2*y(t))] sol11 = [Eq(x(t), C1 + C2*k3*exp(-t*(k2 + k3))/k2), Eq(y(t), -C2*(k2 + k3)*exp(-t*(k2 + k3))/k2), Eq(z(t), C2*exp(-t*(k2 + k3)) + C3)] assert dsolve(eqs11) == sol11 assert checksysodesol(eqs11, sol11) == (True, [0, 0, 0]) # Regression test case for issue #14312 # https://github.com/sympy/sympy/issues/14312 eqs12 = [Eq(Derivative(z(t), t), k2*y(t)), Eq(Derivative(x(t), t), k3*y(t)), Eq(Derivative(y(t), t), (-k2 - k3)*y(t))] sol12 = [Eq(z(t), C1 - C2*k2*exp(-t*(k2 + k3))/(k2 + k3)), Eq(x(t), -C2*k3*exp(-t*(k2 + k3))/(k2 + k3) + C3), Eq(y(t), C2*exp(-t*(k2 + k3)))] assert dsolve(eqs12) == sol12 assert checksysodesol(eqs12, sol12) == (True, [0, 0, 0]) f, g, h = symbols('f, g, h', cls=Function) a, b, c = symbols('a, b, c') # Regression test case for issue #15474 # https://github.com/sympy/sympy/issues/15474 eqs13 = [Eq(Derivative(f(t), t), 2*f(t) + g(t)), Eq(Derivative(g(t), t), a*f(t))] sol13 = [Eq(f(t), C1*exp(t*(sqrt(a + 1) + 1))/(sqrt(a + 1) - 1) - C2*exp(-t*(sqrt(a + 1) - 1))/(sqrt(a + 1) + 1)), Eq(g(t), C1*exp(t*(sqrt(a + 1) + 1)) + C2*exp(-t*(sqrt(a + 1) - 1)))] assert dsolve(eqs13) == sol13 assert checksysodesol(eqs13, sol13) == (True, [0, 0]) eqs14 = [Eq(Derivative(f(t), t), 2*g(t) - 3*h(t)), Eq(Derivative(g(t), t), -2*f(t) + 4*h(t)), Eq(Derivative(h(t), t), 3*f(t) - 4*g(t))] sol14 = [Eq(f(t), 2*C1 - sin(sqrt(29)*t)*(sqrt(29)*C2*Rational(3, 25) + C3*Rational(-8, 25)) - cos(sqrt(29)*t)*(C2*Rational(8, 25) + sqrt(29)*C3*Rational(3, 25))), Eq(g(t), C1*Rational(3, 2) + sin(sqrt(29)*t)*(sqrt(29)*C2*Rational(4, 25) + C3*Rational(6, 25)) - cos(sqrt(29)*t)*(C2*Rational(6, 25) + sqrt(29)*C3*Rational(-4, 25))), Eq(h(t), C1 + C2*cos(sqrt(29)*t) - C3*sin(sqrt(29)*t))] assert dsolve(eqs14) == sol14 assert checksysodesol(eqs14, sol14) == (True, [0, 0, 0]) eqs15 = [Eq(2*Derivative(f(t), t), 12*g(t) - 12*h(t)), Eq(3*Derivative(g(t), t), -8*f(t) + 8*h(t)), Eq(4*Derivative(h(t), t), 6*f(t) - 6*g(t))] sol15 = [Eq(f(t), C1 - sin(sqrt(29)*t)*(sqrt(29)*C2*Rational(6, 13) + C3*Rational(-16, 13)) - cos(sqrt(29)*t)*(C2*Rational(16, 13) + sqrt(29)*C3*Rational(6, 13))), Eq(g(t), C1 + sin(sqrt(29)*t)*(sqrt(29)*C2*Rational(8, 39) + C3*Rational(16, 13)) - cos(sqrt(29)*t)*(C2*Rational(16, 13) + sqrt(29)*C3*Rational(-8, 39))), Eq(h(t), C1 + C2*cos(sqrt(29)*t) - C3*sin(sqrt(29)*t))] assert dsolve(eqs15) == sol15 assert checksysodesol(eqs15, sol15) == (True, [0, 0, 0]) eq16 = (Eq(diff(x(t), t), 21*x(t)), Eq(diff(y(t), t), 17*x(t) + 3*y(t)), Eq(diff(z(t), t), 5*x(t) + 7*y(t) + 9*z(t))) sol16 = [Eq(x(t), 216*C1*exp(21*t)/209), Eq(y(t), 204*C1*exp(21*t)/209 - 6*C2*exp(3*t)/7), Eq(z(t), C1*exp(21*t) + C2*exp(3*t) + C3*exp(9*t))] assert dsolve(eq16) == sol16 assert checksysodesol(eq16, sol16) == (True, [0, 0, 0]) eqs17 = [Eq(Derivative(x(t), t), 3*y(t) - 11*z(t)), Eq(Derivative(y(t), t), -3*x(t) + 7*z(t)), Eq(Derivative(z(t), t), 11*x(t) - 7*y(t))] sol17 = [Eq(x(t), C1*Rational(7, 3) - sin(sqrt(179)*t)*(sqrt(179)*C2*Rational(11, 170) + C3*Rational(-21, 170)) - cos(sqrt(179)*t)*(C2*Rational(21, 170) + sqrt(179)*C3*Rational(11, 170))), Eq(y(t), C1*Rational(11, 3) + sin(sqrt(179)*t)*(sqrt(179)*C2*Rational(7, 170) + C3*Rational(33, 170)) - cos(sqrt(179)*t)*(C2*Rational(33, 170) + sqrt(179)*C3*Rational(-7, 170))), Eq(z(t), C1 + C2*cos(sqrt(179)*t) - C3*sin(sqrt(179)*t))] assert dsolve(eqs17) == sol17 assert checksysodesol(eqs17, sol17) == (True, [0, 0, 0]) eqs18 = [Eq(3*Derivative(x(t), t), 20*y(t) - 20*z(t)), Eq(4*Derivative(y(t), t), -15*x(t) + 15*z(t)), Eq(5*Derivative(z(t), t), 12*x(t) - 12*y(t))] sol18 = [Eq(x(t), C1 - sin(5*sqrt(2)*t)*(sqrt(2)*C2*Rational(4, 3) - C3) - cos(5*sqrt(2)*t)*(C2 + sqrt(2)*C3*Rational(4, 3))), Eq(y(t), C1 + sin(5*sqrt(2)*t)*(sqrt(2)*C2*Rational(3, 4) + C3) - cos(5*sqrt(2)*t)*(C2 + sqrt(2)*C3*Rational(-3, 4))), Eq(z(t), C1 + C2*cos(5*sqrt(2)*t) - C3*sin(5*sqrt(2)*t))] assert dsolve(eqs18) == sol18 assert checksysodesol(eqs18, sol18) == (True, [0, 0, 0]) eqs19 = [Eq(Derivative(x(t), t), 4*x(t) - z(t)), Eq(Derivative(y(t), t), 2*x(t) + 2*y(t) - z(t)), Eq(Derivative(z(t), t), 3*x(t) + y(t))] sol19 = [Eq(x(t), C2*t**2*exp(2*t)/2 + t*(2*C2 + C3)*exp(2*t) + (C1 + C2 + 2*C3)*exp(2*t)), Eq(y(t), C2*t**2*exp(2*t)/2 + t*(2*C2 + C3)*exp(2*t) + (C1 + 2*C3)*exp(2*t)), Eq(z(t), C2*t**2*exp(2*t) + t*(3*C2 + 2*C3)*exp(2*t) + (2*C1 + 3*C3)*exp(2*t))] assert dsolve(eqs19) == sol19 assert checksysodesol(eqs19, sol19) == (True, [0, 0, 0]) eqs20 = [Eq(Derivative(x(t), t), 4*x(t) - y(t) - 2*z(t)), Eq(Derivative(y(t), t), 2*x(t) + y(t) - 2*z(t)), Eq(Derivative(z(t), t), 5*x(t) - 3*z(t))] sol20 = [Eq(x(t), C1*exp(2*t) - sin(t)*(C2*Rational(3, 5) + C3/5) - cos(t)*(C2/5 + C3*Rational(-3, 5))), Eq(y(t), -sin(t)*(C2*Rational(3, 5) + C3/5) - cos(t)*(C2/5 + C3*Rational(-3, 5))), Eq(z(t), C1*exp(2*t) - C2*sin(t) + C3*cos(t))] assert dsolve(eqs20) == sol20 assert checksysodesol(eqs20, sol20) == (True, [0, 0, 0]) eq21 = (Eq(diff(x(t), t), 9*y(t)), Eq(diff(y(t), t), 12*x(t))) sol21 = [Eq(x(t), -sqrt(3)*C1*exp(-6*sqrt(3)*t)/2 + sqrt(3)*C2*exp(6*sqrt(3)*t)/2), Eq(y(t), C1*exp(-6*sqrt(3)*t) + C2*exp(6*sqrt(3)*t))] assert dsolve(eq21) == sol21 assert checksysodesol(eq21, sol21) == (True, [0, 0]) eqs22 = [Eq(Derivative(x(t), t), 2*x(t) + 4*y(t)), Eq(Derivative(y(t), t), 12*x(t) + 41*y(t))] sol22 = [Eq(x(t), C1*(39 - sqrt(1713))*exp(t*(sqrt(1713) + 43)/2)*Rational(-1, 24) + C2*(39 + sqrt(1713))*exp(t*(43 - sqrt(1713))/2)*Rational(-1, 24)), Eq(y(t), C1*exp(t*(sqrt(1713) + 43)/2) + C2*exp(t*(43 - sqrt(1713))/2))] assert dsolve(eqs22) == sol22 assert checksysodesol(eqs22, sol22) == (True, [0, 0]) eqs23 = [Eq(Derivative(x(t), t), x(t) + y(t)), Eq(Derivative(y(t), t), -2*x(t) + 2*y(t))] sol23 = [Eq(x(t), (C1/4 + sqrt(7)*C2/4)*cos(sqrt(7)*t/2)*exp(t*Rational(3, 2)) + sin(sqrt(7)*t/2)*(sqrt(7)*C1/4 + C2*Rational(-1, 4))*exp(t*Rational(3, 2))), Eq(y(t), C1*cos(sqrt(7)*t/2)*exp(t*Rational(3, 2)) - C2*sin(sqrt(7)*t/2)*exp(t*Rational(3, 2)))] assert dsolve(eqs23) == sol23 assert checksysodesol(eqs23, sol23) == (True, [0, 0]) # Regression test case for issue #15474 # https://github.com/sympy/sympy/issues/15474 a = Symbol("a", real=True) eq24 = [x(t).diff(t) - a*y(t), y(t).diff(t) + a*x(t)] sol24 = [Eq(x(t), C1*sin(a*t) + C2*cos(a*t)), Eq(y(t), C1*cos(a*t) - C2*sin(a*t))] assert dsolve(eq24) == sol24 assert checksysodesol(eq24, sol24) == (True, [0, 0]) # Regression test case for issue #19150 # https://github.com/sympy/sympy/issues/19150 eqs25 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), (f(t) - 2*g(t) + x(t))/(b*c)), Eq(Derivative(x(t), t), (g(t) - 2*x(t) + y(t))/(b*c)), Eq(Derivative(y(t), t), (h(t) + x(t) - 2*y(t))/(b*c)), Eq(Derivative(h(t), t), 0)] sol25 = [Eq(f(t), -3*C1 + 4*C2), Eq(g(t), -2*C1 + 3*C2 - C3*exp(-2*t/(b*c)) + C4*exp(-t*(sqrt(2) + 2)/(b*c)) + C5*exp(-t*(2 - sqrt(2))/(b*c))), Eq(x(t), -C1 + 2*C2 - sqrt(2)*C4*exp(-t*(sqrt(2) + 2)/(b*c)) + sqrt(2)*C5*exp(-t*(2 - sqrt(2))/(b*c))), Eq(y(t), C2 + C3*exp(-2*t/(b*c)) + C4*exp(-t*(sqrt(2) + 2)/(b*c)) + C5*exp(-t*(2 - sqrt(2))/(b*c))), Eq(h(t), C1)] assert dsolve(eqs25) == sol25 assert checksysodesol(eqs25, sol25) == (True, [0, 0, 0, 0, 0]) eq26 = [Eq(Derivative(f(t), t), 2*f(t)), Eq(Derivative(g(t), t), 3*f(t) + 7*g(t))] sol26 = [Eq(f(t), -5*C1*exp(2*t)/3), Eq(g(t), C1*exp(2*t) + C2*exp(7*t))] assert dsolve(eq26) == sol26 assert checksysodesol(eq26, sol26) == (True, [0, 0]) eq27 = [Eq(Derivative(f(t), t), -9*I*f(t) - 4*g(t)), Eq(Derivative(g(t), t), -4*I*g(t))] sol27 = [Eq(f(t), 4*I*C1*exp(-4*I*t)/5 + C2*exp(-9*I*t)), Eq(g(t), C1*exp(-4*I*t))] assert dsolve(eq27) == sol27 assert checksysodesol(eq27, sol27) == (True, [0, 0]) eq28 = [Eq(Derivative(f(t), t), -9*I*f(t)), Eq(Derivative(g(t), t), -4*I*g(t))] sol28 = [Eq(f(t), C1*exp(-9*I*t)), Eq(g(t), C2*exp(-4*I*t))] assert dsolve(eq28) == sol28 assert checksysodesol(eq28, sol28) == (True, [0, 0]) eq29 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), 0)] sol29 = [Eq(f(t), C1), Eq(g(t), C2)] assert dsolve(eq29) == sol29 assert checksysodesol(eq29, sol29) == (True, [0, 0]) eq30 = [Eq(Derivative(f(t), t), f(t)), Eq(Derivative(g(t), t), 0)] sol30 = [Eq(f(t), C1*exp(t)), Eq(g(t), C2)] assert dsolve(eq30) == sol30 assert checksysodesol(eq30, sol30) == (True, [0, 0]) eq31 = [Eq(Derivative(f(t), t), g(t)), Eq(Derivative(g(t), t), 0)] sol31 = [Eq(f(t), C1 + C2*t), Eq(g(t), C2)] assert dsolve(eq31) == sol31 assert checksysodesol(eq31, sol31) == (True, [0, 0]) eq32 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), f(t))] sol32 = [Eq(f(t), C1), Eq(g(t), C1*t + C2)] assert dsolve(eq32) == sol32 assert checksysodesol(eq32, sol32) == (True, [0, 0]) eq33 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), g(t))] sol33 = [Eq(f(t), C1), Eq(g(t), C2*exp(t))] assert dsolve(eq33) == sol33 assert checksysodesol(eq33, sol33) == (True, [0, 0]) eq34 = [Eq(Derivative(f(t), t), f(t)), Eq(Derivative(g(t), t), I*g(t))] sol34 = [Eq(f(t), C1*exp(t)), Eq(g(t), C2*exp(I*t))] assert dsolve(eq34) == sol34 assert checksysodesol(eq34, sol34) == (True, [0, 0]) eq35 = [Eq(Derivative(f(t), t), I*f(t)), Eq(Derivative(g(t), t), -I*g(t))] sol35 = [Eq(f(t), C1*exp(I*t)), Eq(g(t), C2*exp(-I*t))] assert dsolve(eq35) == sol35 assert checksysodesol(eq35, sol35) == (True, [0, 0]) eq36 = [Eq(Derivative(f(t), t), I*g(t)), Eq(Derivative(g(t), t), 0)] sol36 = [Eq(f(t), I*C1 + I*C2*t), Eq(g(t), C2)] assert dsolve(eq36) == sol36 assert checksysodesol(eq36, sol36) == (True, [0, 0]) eq37 = [Eq(Derivative(f(t), t), I*g(t)), Eq(Derivative(g(t), t), I*f(t))] sol37 = [Eq(f(t), -C1*exp(-I*t) + C2*exp(I*t)), Eq(g(t), C1*exp(-I*t) + C2*exp(I*t))] assert dsolve(eq37) == sol37 assert checksysodesol(eq37, sol37) == (True, [0, 0]) # Multiple systems eq1 = [Eq(Derivative(f(t), t)**2, g(t)**2), Eq(-f(t) + Derivative(g(t), t), 0)] sol1 = [[Eq(f(t), -C1*sin(t) - C2*cos(t)), Eq(g(t), C1*cos(t) - C2*sin(t))], [Eq(f(t), -C1*exp(-t) + C2*exp(t)), Eq(g(t), C1*exp(-t) + C2*exp(t))]] assert dsolve(eq1) == sol1 for sol in sol1: assert checksysodesol(eq1, sol) == (True, [0, 0]) def test_sysode_linear_neq_order1_type2(): f, g, h, k = symbols('f g h k', cls=Function) x, t, a, b, c, d, y = symbols('x t a b c d y') k1, k2 = symbols('k1 k2') eqs1 = [Eq(Derivative(f(x), x), f(x) + g(x) + 5), Eq(Derivative(g(x), x), -f(x) - g(x) + 7)] sol1 = [Eq(f(x), C1 + C2 + 6*x**2 + x*(C2 + 5)), Eq(g(x), -C1 - 6*x**2 - x*(C2 - 7))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) eqs2 = [Eq(Derivative(f(x), x), f(x) + g(x) + 5), Eq(Derivative(g(x), x), f(x) + g(x) + 7)] sol2 = [Eq(f(x), -C1 + C2*exp(2*x) - x - 3), Eq(g(x), C1 + C2*exp(2*x) + x - 3)] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0]) eqs3 = [Eq(Derivative(f(x), x), f(x) + 5), Eq(Derivative(g(x), x), f(x) + 7)] sol3 = [Eq(f(x), C1*exp(x) - 5), Eq(g(x), C1*exp(x) + C2 + 2*x - 5)] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0]) eqs4 = [Eq(Derivative(f(x), x), f(x) + exp(x)), Eq(Derivative(g(x), x), x*exp(x) + f(x) + g(x))] sol4 = [Eq(f(x), C1*exp(x) + x*exp(x)), Eq(g(x), C1*x*exp(x) + C2*exp(x) + x**2*exp(x))] assert dsolve(eqs4) == sol4 assert checksysodesol(eqs4, sol4) == (True, [0, 0]) eqs5 = [Eq(Derivative(f(x), x), 5*x + f(x) + g(x)), Eq(Derivative(g(x), x), f(x) - g(x))] sol5 = [Eq(f(x), C1*(1 + sqrt(2))*exp(sqrt(2)*x) + C2*(1 - sqrt(2))*exp(-sqrt(2)*x) + x*Rational(-5, 2) + Rational(-5, 2)), Eq(g(x), C1*exp(sqrt(2)*x) + C2*exp(-sqrt(2)*x) + x*Rational(-5, 2))] assert dsolve(eqs5) == sol5 assert checksysodesol(eqs5, sol5) == (True, [0, 0]) eqs6 = [Eq(Derivative(f(x), x), -9*f(x) - 4*g(x)), Eq(Derivative(g(x), x), -4*g(x)), Eq(Derivative(h(x), x), h(x) + exp(x))] sol6 = [Eq(f(x), C1*exp(-4*x)*Rational(-4, 5) + C2*exp(-9*x)), Eq(g(x), C1*exp(-4*x)), Eq(h(x), C3*exp(x) + x*exp(x))] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0, 0]) # Regression test case for issue #8859 # https://github.com/sympy/sympy/issues/8859 eqs7 = [Eq(Derivative(f(t), t), 3*t + f(t)), Eq(Derivative(g(t), t), g(t))] sol7 = [Eq(f(t), C1*exp(t) - 3*t - 3), Eq(g(t), C2*exp(t))] assert dsolve(eqs7) == sol7 assert checksysodesol(eqs7, sol7) == (True, [0, 0]) # Regression test case for issue #8567 # https://github.com/sympy/sympy/issues/8567 eqs8 = [Eq(Derivative(f(t), t), f(t) + 2*g(t)), Eq(Derivative(g(t), t), -2*f(t) + g(t) + 2*exp(t))] sol8 = [Eq(f(t), C1*exp(t)*sin(2*t) + C2*exp(t)*cos(2*t) + exp(t)*cos(2*t)**2 + 2*exp(t)*sin(2*t)*tan(t)/(tan(t)**2 + 1)), Eq(g(t), C1*exp(t)*cos(2*t) - C2*exp(t)*sin(2*t) - exp(t)*sin(2*t)*cos(2*t) + 2*exp(t)*cos(2*t)*tan(t)/(tan(t)**2 + 1))] assert dsolve(eqs8) == sol8 assert checksysodesol(eqs8, sol8) == (True, [0, 0]) # Regression test case for issue #19150 # https://github.com/sympy/sympy/issues/19150 eqs9 = [Eq(Derivative(f(t), t), (c - 2*f(t) + g(t))/(a*b)), Eq(Derivative(g(t), t), (f(t) - 2*g(t) + h(t))/(a*b)), Eq(Derivative(h(t), t), (d + g(t) - 2*h(t))/(a*b))] sol9 = [Eq(f(t), -C1*exp(-2*t/(a*b)) + C2*exp(-t*(sqrt(2) + 2)/(a*b)) + C3*exp(-t*(2 - sqrt(2))/(a*b)) + Mul(Rational(1, 4), 3*c + d, evaluate=False)), Eq(g(t), -sqrt(2)*C2*exp(-t*(sqrt(2) + 2)/(a*b)) + sqrt(2)*C3*exp(-t*(2 - sqrt(2))/(a*b)) + Mul(Rational(1, 2), c + d, evaluate=False)), Eq(h(t), C1*exp(-2*t/(a*b)) + C2*exp(-t*(sqrt(2) + 2)/(a*b)) + C3*exp(-t*(2 - sqrt(2))/(a*b)) + Mul(Rational(1, 4), c + 3*d, evaluate=False))] assert dsolve(eqs9) == sol9 assert checksysodesol(eqs9, sol9) == (True, [0, 0, 0]) # Regression test case for issue #16635 # https://github.com/sympy/sympy/issues/16635 eqs10 = [Eq(Derivative(f(t), t), 15*t + f(t) - g(t) - 10), Eq(Derivative(g(t), t), -15*t + f(t) - g(t) - 5)] sol10 = [Eq(f(t), C1 + C2 + 5*t**3 + 5*t**2 + t*(C2 - 10)), Eq(g(t), C1 + 5*t**3 - 10*t**2 + t*(C2 - 5))] assert dsolve(eqs10) == sol10 assert checksysodesol(eqs10, sol10) == (True, [0, 0]) # Multiple solutions eqs11 = [Eq(Derivative(f(t), t)**2 - 2*Derivative(f(t), t) + 1, 4), Eq(-y*f(t) + Derivative(g(t), t), 0)] sol11 = [[Eq(f(t), C1 - t), Eq(g(t), C1*t*y + C2*y + t**2*y*Rational(-1, 2))], [Eq(f(t), C1 + 3*t), Eq(g(t), C1*t*y + C2*y + t**2*y*Rational(3, 2))]] assert dsolve(eqs11) == sol11 for s11 in sol11: assert checksysodesol(eqs11, s11) == (True, [0, 0]) # test case for issue #19831 # https://github.com/sympy/sympy/issues/19831 n = symbols('n', positive=True) x0 = symbols('x_0') t0 = symbols('t_0') x_0 = symbols('x_0') t_0 = symbols('t_0') t = symbols('t') x = Function('x') y = Function('y') T = symbols('T') eqs12 = [Eq(Derivative(y(t), t), x(t)), Eq(Derivative(x(t), t), n*(y(t) + 1))] sol12 = [Eq(y(t), C1*exp(sqrt(n)*t)*n**Rational(-1, 2) - C2*exp(-sqrt(n)*t)*n**Rational(-1, 2) - 1), Eq(x(t), C1*exp(sqrt(n)*t) + C2*exp(-sqrt(n)*t))] assert dsolve(eqs12) == sol12 assert checksysodesol(eqs12, sol12) == (True, [0, 0]) sol12b = [ Eq(y(t), (T*exp(-sqrt(n)*t_0)/2 + exp(-sqrt(n)*t_0)/2 + x_0*exp(-sqrt(n)*t_0)/(2*sqrt(n)))*exp(sqrt(n)*t) + (T*exp(sqrt(n)*t_0)/2 + exp(sqrt(n)*t_0)/2 - x_0*exp(sqrt(n)*t_0)/(2*sqrt(n)))*exp(-sqrt(n)*t) - 1), Eq(x(t), (T*sqrt(n)*exp(-sqrt(n)*t_0)/2 + sqrt(n)*exp(-sqrt(n)*t_0)/2 + x_0*exp(-sqrt(n)*t_0)/2)*exp(sqrt(n)*t) - (T*sqrt(n)*exp(sqrt(n)*t_0)/2 + sqrt(n)*exp(sqrt(n)*t_0)/2 - x_0*exp(sqrt(n)*t_0)/2)*exp(-sqrt(n)*t)) ] assert dsolve(eqs12, ics={y(t0): T, x(t0): x0}) == sol12b assert checksysodesol(eqs12, sol12b) == (True, [0, 0]) #Test cases added for the issue 19763 #https://github.com/sympy/sympy/issues/19763 eq13 = [Eq(Derivative(f(t), t), f(t) + g(t) + 9), Eq(Derivative(g(t), t), 2*f(t) + 5*g(t) + 23)] sol13 = [Eq(f(t), -C1*(2 + sqrt(6))*exp(t*(3 - sqrt(6)))/2 - C2*(2 - sqrt(6))*exp(t*(sqrt(6) + 3))/2 - Rational(22,3)), Eq(g(t), C1*exp(t*(3 - sqrt(6))) + C2*exp(t*(sqrt(6) + 3)) - Rational(5,3))] assert dsolve(eq13) == sol13 assert checksysodesol(eq13, sol13) == (True, [0, 0]) eq14 = [Eq(Derivative(f(t), t), f(t) + g(t) + 81), Eq(Derivative(g(t), t), -2*f(t) + g(t) + 23)] sol14 = [Eq(f(t), sqrt(2)*C1*exp(t)*sin(sqrt(2)*t)/2 + sqrt(2)*C2*exp(t)*cos(sqrt(2)*t)/2 + sqrt(2)*exp(t)*sin(sqrt(2)*t)*Integral(-23*exp(-t)*sin(sqrt(2)*t)**2/cos(sqrt(2)*t) + 81*sqrt(2)*exp(-t)*sin(sqrt(2)*t) + 23*exp(-t)/cos(sqrt(2)*t), t)/2 + 185*sqrt(2)*sin(sqrt(2)*t)*cos(sqrt(2)*t)/6 - 58*cos(sqrt(2)*t)**2/3), Eq(g(t), C1*exp(t)*cos(sqrt(2)*t) - C2*exp(t)*sin(sqrt(2)*t) + exp(t)*cos(sqrt(2)*t)*Integral(-23*exp(-t)*sin(sqrt(2)*t)**2/cos(sqrt(2)*t) + 81*sqrt(2)*exp(-t)*sin(sqrt(2)*t) + 23*exp(-t)/cos(sqrt(2)*t), t) - 185*sin(sqrt(2)*t)**2/3 + 58*sqrt(2)*sin(sqrt(2)*t)*cos(sqrt(2)*t)/3)] assert dsolve(eq14) == sol14 assert checksysodesol(eq14, sol14) == (True, [0,0]) eq15 = [Eq(Derivative(f(t), t), f(t) + 2*g(t) + k1), Eq(Derivative(g(t), t), 3*f(t) + 4*g(t) + k2)] sol15 = [Eq(f(t), -C1*(3 - sqrt(33))*exp(t*(5 + sqrt(33))/2)/6 - C2*(3 + sqrt(33))*exp(t*(5 - sqrt(33))/2)/6 + 2*k1 - k2), Eq(g(t), C1*exp(t*(5 + sqrt(33))/2) + C2*exp(t*(5 - sqrt(33))/2) - Mul(Rational(1,2), 3*k1 - k2, evaluate = False))] assert dsolve(eq15) == sol15 assert checksysodesol(eq15, sol15) == (True, [0,0]) eq16 = [Eq(Derivative(f(t), t), k1), Eq(Derivative(g(t), t), k2)] sol16 = [Eq(f(t), C1 + k1*t), Eq(g(t), C2 + k2*t)] assert dsolve(eq16) == sol16 assert checksysodesol(eq16, sol16) == (True, [0,0]) eq17 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), c*f(t) + k2)] sol17 = [Eq(f(t), C1), Eq(g(t), C2*c + t*(C1*c + k2))] assert dsolve(eq17) == sol17 assert checksysodesol(eq17 , sol17) == (True , [0,0]) eq18 = [Eq(Derivative(f(t), t), k1), Eq(Derivative(g(t), t), f(t) + k2)] sol18 = [Eq(f(t), C1 + k1*t), Eq(g(t), C2 + k1*t**2/2 + t*(C1 + k2))] assert dsolve(eq18) == sol18 assert checksysodesol(eq18 , sol18) == (True , [0,0]) eq19 = [Eq(Derivative(f(t), t), k1), Eq(Derivative(g(t), t), f(t) + 2*g(t) + k2)] sol19 = [Eq(f(t), -2*C1 + k1*t), Eq(g(t), C1 + C2*exp(2*t) - k1*t/2 - Mul(Rational(1,4), k1 + 2*k2 , evaluate = False))] assert dsolve(eq19) == sol19 assert checksysodesol(eq19 , sol19) == (True , [0,0]) eq20 = [Eq(diff(f(t), t), f(t) + k1), Eq(diff(g(t), t), k2)] sol20 = [Eq(f(t), C1*exp(t) - k1), Eq(g(t), C2 + k2*t)] assert dsolve(eq20) == sol20 assert checksysodesol(eq20 , sol20) == (True , [0,0]) eq21 = [Eq(diff(f(t), t), g(t) + k1), Eq(diff(g(t), t), 0)] sol21 = [Eq(f(t), C1 + t*(C2 + k1)), Eq(g(t), C2)] assert dsolve(eq21) == sol21 assert checksysodesol(eq21 , sol21) == (True , [0,0]) eq22 = [Eq(Derivative(f(t), t), f(t) + 2*g(t) + k1), Eq(Derivative(g(t), t), k2)] sol22 = [Eq(f(t), -2*C1 + C2*exp(t) - k1 - 2*k2*t - 2*k2), Eq(g(t), C1 + k2*t)] assert dsolve(eq22) == sol22 assert checksysodesol(eq22 , sol22) == (True , [0,0]) eq23 = [Eq(Derivative(f(t), t), g(t) + k1), Eq(Derivative(g(t), t), 2*g(t) + k2)] sol23 = [Eq(f(t), C1 + C2*exp(2*t)/2 - k2/4 + t*(2*k1 - k2)/2), Eq(g(t), C2*exp(2*t) - k2/2)] assert dsolve(eq23) == sol23 assert checksysodesol(eq23 , sol23) == (True , [0,0]) eq24 = [Eq(Derivative(f(t), t), f(t) + k1), Eq(Derivative(g(t), t), 2*f(t) + k2)] sol24 = [Eq(f(t), C1*exp(t)/2 - k1), Eq(g(t), C1*exp(t) + C2 - 2*k1 - t*(2*k1 - k2))] assert dsolve(eq24) == sol24 assert checksysodesol(eq24 , sol24) == (True , [0,0]) eq25 = [Eq(Derivative(f(t), t), f(t) + 2*g(t) + k1), Eq(Derivative(g(t), t), 3*f(t) + 6*g(t) + k2)] sol25 = [Eq(f(t), -2*C1 + C2*exp(7*t)/3 + 2*t*(3*k1 - k2)/7 - Mul(Rational(1,49), k1 + 2*k2 , evaluate = False)), Eq(g(t), C1 + C2*exp(7*t) - t*(3*k1 - k2)/7 - Mul(Rational(3,49), k1 + 2*k2 , evaluate = False))] assert dsolve(eq25) == sol25 assert checksysodesol(eq25 , sol25) == (True , [0,0]) eq26 = [Eq(Derivative(f(t), t), 2*f(t) - g(t) + k1), Eq(Derivative(g(t), t), 4*f(t) - 2*g(t) + 2*k1)] sol26 = [Eq(f(t), C1 + 2*C2 + t*(2*C1 + k1)), Eq(g(t), 4*C2 + t*(4*C1 + 2*k1))] assert dsolve(eq26) == sol26 assert checksysodesol(eq26 , sol26) == (True , [0,0]) def test_sysode_linear_neq_order1_type3(): f, g, h, k, x0 , y0 = symbols('f g h k x0 y0', cls=Function) x, t, a = symbols('x t a') r = symbols('r', real=True) eqs1 = [Eq(Derivative(f(r), r), r*g(r) + f(r)), Eq(Derivative(g(r), r), -r*f(r) + g(r))] sol1 = [Eq(f(r), C1*exp(r)*sin(r**2/2) + C2*exp(r)*cos(r**2/2)), Eq(g(r), C1*exp(r)*cos(r**2/2) - C2*exp(r)*sin(r**2/2))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) eqs2 = [Eq(Derivative(f(x), x), x**2*g(x) + x*f(x)), Eq(Derivative(g(x), x), 2*x**2*f(x) + (3*x**2 + x)*g(x))] sol2 = [Eq(f(x), (sqrt(17)*C1/17 + C2*(17 - 3*sqrt(17))/34)*exp(x**3*(3 + sqrt(17))/6 + x**2/2) - exp(x**3*(3 - sqrt(17))/6 + x**2/2)*(sqrt(17)*C1/17 + C2*(3*sqrt(17) + 17)*Rational(-1, 34))), Eq(g(x), exp(x**3*(3 - sqrt(17))/6 + x**2/2)*(C1*(17 - 3*sqrt(17))/34 + sqrt(17)*C2*Rational(-2, 17)) + exp(x**3*(3 + sqrt(17))/6 + x**2/2)*(C1*(3*sqrt(17) + 17)/34 + sqrt(17)*C2*Rational(2, 17)))] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0]) eqs3 = [Eq(f(x).diff(x), x*f(x) + g(x)), Eq(g(x).diff(x), -f(x) + x*g(x))] sol3 = [Eq(f(x), (C1/2 + I*C2/2)*exp(x**2/2 - I*x) + exp(x**2/2 + I*x)*(C1/2 + I*C2*Rational(-1, 2))), Eq(g(x), (I*C1/2 + C2/2)*exp(x**2/2 + I*x) - exp(x**2/2 - I*x)*(I*C1/2 + C2*Rational(-1, 2)))] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0]) eqs4 = [Eq(f(x).diff(x), x*(f(x) + g(x) + h(x))), Eq(g(x).diff(x), x*(f(x) + g(x) + h(x))), Eq(h(x).diff(x), x*(f(x) + g(x) + h(x)))] sol4 = [Eq(f(x), -C1/3 - C2/3 + 2*C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2)), Eq(g(x), 2*C1/3 - C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2)), Eq(h(x), -C1/3 + 2*C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2))] assert dsolve(eqs4) == sol4 assert checksysodesol(eqs4, sol4) == (True, [0, 0, 0]) eqs5 = [Eq(f(x).diff(x), x**2*(f(x) + g(x) + h(x))), Eq(g(x).diff(x), x**2*(f(x) + g(x) + h(x))), Eq(h(x).diff(x), x**2*(f(x) + g(x) + h(x)))] sol5 = [Eq(f(x), -C1/3 - C2/3 + 2*C3/3 + (C1/3 + C2/3 + C3/3)*exp(x**3)), Eq(g(x), 2*C1/3 - C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(x**3)), Eq(h(x), -C1/3 + 2*C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(x**3))] assert dsolve(eqs5) == sol5 assert checksysodesol(eqs5, sol5) == (True, [0, 0, 0]) eqs6 = [Eq(Derivative(f(x), x), x*(f(x) + g(x) + h(x) + k(x))), Eq(Derivative(g(x), x), x*(f(x) + g(x) + h(x) + k(x))), Eq(Derivative(h(x), x), x*(f(x) + g(x) + h(x) + k(x))), Eq(Derivative(k(x), x), x*(f(x) + g(x) + h(x) + k(x)))] sol6 = [Eq(f(x), -C1/4 - C2/4 - C3/4 + 3*C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2)), Eq(g(x), 3*C1/4 - C2/4 - C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2)), Eq(h(x), -C1/4 + 3*C2/4 - C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2)), Eq(k(x), -C1/4 - C2/4 + 3*C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2))] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0, 0, 0]) y = symbols("y", real=True) eqs7 = [Eq(Derivative(f(y), y), y*f(y) + g(y)), Eq(Derivative(g(y), y), y*g(y) - f(y))] sol7 = [Eq(f(y), C1*exp(y**2/2)*sin(y) + C2*exp(y**2/2)*cos(y)), Eq(g(y), C1*exp(y**2/2)*cos(y) - C2*exp(y**2/2)*sin(y))] assert dsolve(eqs7) == sol7 assert checksysodesol(eqs7, sol7) == (True, [0, 0]) #Test cases added for the issue 19763 #https://github.com/sympy/sympy/issues/19763 eqs8 = [Eq(Derivative(f(t), t), 5*t*f(t) + 2*h(t)), Eq(Derivative(h(t), t), 2*f(t) + 5*t*h(t))] sol8 = [Eq(f(t), Mul(-1, (C1/2 - C2/2), evaluate = False)*exp(5*t**2/2 - 2*t) + (C1/2 + C2/2)*exp(5*t**2/2 + 2*t)), Eq(h(t), (C1/2 - C2/2)*exp(5*t**2/2 - 2*t) + (C1/2 + C2/2)*exp(5*t**2/2 + 2*t))] assert dsolve(eqs8) == sol8 assert checksysodesol(eqs8, sol8) == (True, [0, 0]) eqs9 = [Eq(diff(f(t), t), 5*t*f(t) + t**2*g(t)), Eq(diff(g(t), t), -t**2*f(t) + 5*t*g(t))] sol9 = [Eq(f(t), (C1/2 - I*C2/2)*exp(I*t**3/3 + 5*t**2/2) + (C1/2 + I*C2/2)*exp(-I*t**3/3 + 5*t**2/2)), Eq(g(t), Mul(-1, (I*C1/2 - C2/2) , evaluate = False)*exp(-I*t**3/3 + 5*t**2/2) + (I*C1/2 + C2/2)*exp(I*t**3/3 + 5*t**2/2))] assert dsolve(eqs9) == sol9 assert checksysodesol(eqs9 , sol9) == (True , [0,0]) eqs10 = [Eq(diff(f(t), t), t**2*g(t) + 5*t*f(t)), Eq(diff(g(t), t), -t**2*f(t) + (9*t**2 + 5*t)*g(t))] sol10 = [Eq(f(t), (C1*(77 - 9*sqrt(77))/154 + sqrt(77)*C2/77)*exp(t**3*(sqrt(77) + 9)/6 + 5*t**2/2) + (C1*(77 + 9*sqrt(77))/154 - sqrt(77)*C2/77)*exp(t**3*(9 - sqrt(77))/6 + 5*t**2/2)), Eq(g(t), (sqrt(77)*C1/77 + C2*(77 - 9*sqrt(77))/154)*exp(t**3*(9 - sqrt(77))/6 + 5*t**2/2) - (sqrt(77)*C1/77 - C2*(77 + 9*sqrt(77))/154)*exp(t**3*(sqrt(77) + 9)/6 + 5*t**2/2))] assert dsolve(eqs10) == sol10 assert checksysodesol(eqs10 , sol10) == (True , [0,0]) eqs11 = [Eq(diff(f(t), t), 5*t*f(t) + t**2*g(t)), Eq(diff(g(t), t), (1-t**2)*f(t) + (5*t + 9*t**2)*g(t))] sol11 = [Eq(f(t), C1*x0(t) + C2*x0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t)), Eq(g(t), C1*y0(t) + C2*(y0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t) + exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)))] assert dsolve(eqs11) == sol11 @slow def test_sysode_linear_neq_order1_type4(): f, g, h, k = symbols('f g h k', cls=Function) x, t, a = symbols('x t a') r = symbols('r', real=True) eqs1 = [Eq(diff(f(r), r), f(r) + r*g(r) + r**2), Eq(diff(g(r), r), -r*f(r) + g(r) + r)] sol1 = [Eq(f(r), C1*exp(r)*sin(r**2/2) + C2*exp(r)*cos(r**2/2) + exp(r)*sin(r**2/2)*Integral(r**2*exp(-r)*sin(r**2/2) + r*exp(-r)*cos(r**2/2), r) + exp(r)*cos(r**2/2)*Integral(r**2*exp(-r)*cos(r**2/2) - r*exp(-r)*sin(r**2/2), r)), Eq(g(r), C1*exp(r)*cos(r**2/2) - C2*exp(r)*sin(r**2/2) - exp(r)*sin(r**2/2)*Integral(r**2*exp(-r)*cos(r**2/2) - r*exp(-r)*sin(r**2/2), r) + exp(r)*cos(r**2/2)*Integral(r**2*exp(-r)*sin(r**2/2) + r*exp(-r)*cos(r**2/2), r))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) eqs2 = [Eq(diff(f(r), r), f(r) + r*g(r) + r), Eq(diff(g(r), r), -r*f(r) + g(r) + log(r))] sol2 = [Eq(f(r), C1*exp(r)*sin(r**2/2) + C2*exp(r)*cos(r**2/2) + exp(r)*sin(r**2/2)*Integral(r*exp(-r)*sin(r**2/2) + exp(-r)*log(r)*cos(r**2/2), r) + exp(r)*cos(r**2/2)*Integral(r*exp(-r)*cos(r**2/2) - exp(-r)*log(r)*sin( r**2/2), r)), Eq(g(r), C1*exp(r)*cos(r**2/2) - C2*exp(r)*sin(r**2/2) - exp(r)*sin(r**2/2)*Integral(r*exp(-r)*cos(r**2/2) - exp(-r)*log(r)*sin(r**2/2), r) + exp(r)*cos(r**2/2)*Integral(r*exp(-r)*sin(r**2/2) + exp(-r)*log(r)*cos( r**2/2), r))] # XXX: dsolve hangs for this in integration assert dsolve_system(eqs2, simplify=False, doit=False) == [sol2] assert checksysodesol(eqs2, sol2) == (True, [0, 0]) eqs3 = [Eq(Derivative(f(x), x), x*(f(x) + g(x) + h(x)) + x), Eq(Derivative(g(x), x), x*(f(x) + g(x) + h(x)) + x), Eq(Derivative(h(x), x), x*(f(x) + g(x) + h(x)) + 1)] sol3 = [Eq(f(x), C1*Rational(-1, 3) + C2*Rational(-1, 3) + C3*Rational(2, 3) + x**2/6 + x*Rational(-1, 3) + (C1/3 + C2/3 + C3/3)*exp(x**2*Rational(3, 2)) + sqrt(6)*sqrt(pi)*erf(sqrt(6)*x/2)*exp(x**2*Rational(3, 2))/18 + Rational(-2, 9)), Eq(g(x), C1*Rational(2, 3) + C2*Rational(-1, 3) + C3*Rational(-1, 3) + x**2/6 + x*Rational(-1, 3) + (C1/3 + C2/3 + C3/3)*exp(x**2*Rational(3, 2)) + sqrt(6)*sqrt(pi)*erf(sqrt(6)*x/2)*exp(x**2*Rational(3, 2))/18 + Rational(-2, 9)), Eq(h(x), C1*Rational(-1, 3) + C2*Rational(2, 3) + C3*Rational(-1, 3) + x**2*Rational(-1, 3) + x*Rational(2, 3) + (C1/3 + C2/3 + C3/3)*exp(x**2*Rational(3, 2)) + sqrt(6)*sqrt(pi)*erf(sqrt(6)*x/2)*exp(x**2*Rational(3, 2))/18 + Rational(-2, 9))] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0, 0]) eqs4 = [Eq(Derivative(f(x), x), x*(f(x) + g(x) + h(x)) + sin(x)), Eq(Derivative(g(x), x), x*(f(x) + g(x) + h(x)) + sin(x)), Eq(Derivative(h(x), x), x*(f(x) + g(x) + h(x)) + sin(x))] sol4 = [Eq(f(x), C1*Rational(-1, 3) + C2*Rational(-1, 3) + C3*Rational(2, 3) + (C1/3 + C2/3 + C3/3)*exp(x**2*Rational(3, 2)) + Integral(sin(x)*exp(x**2*Rational(-3, 2)), x)*exp(x**2*Rational(3, 2))), Eq(g(x), C1*Rational(2, 3) + C2*Rational(-1, 3) + C3*Rational(-1, 3) + (C1/3 + C2/3 + C3/3)*exp(x**2*Rational(3, 2)) + Integral(sin(x)*exp(x**2*Rational(-3, 2)), x)*exp(x**2*Rational(3, 2))), Eq(h(x), C1*Rational(-1, 3) + C2*Rational(2, 3) + C3*Rational(-1, 3) + (C1/3 + C2/3 + C3/3)*exp(x**2*Rational(3, 2)) + Integral(sin(x)*exp(x**2*Rational(-3, 2)), x)*exp(x**2*Rational(3, 2)))] assert dsolve(eqs4) == sol4 assert checksysodesol(eqs4, sol4) == (True, [0, 0, 0]) eqs5 = [Eq(Derivative(f(x), x), x*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(g(x), x), x*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(h(x), x), x*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(k(x), x), x*(f(x) + g(x) + h(x) + k(x) + 1))] sol5 = [Eq(f(x), C1*Rational(-1, 4) + C2*Rational(-1, 4) + C3*Rational(-1, 4) + C4*Rational(3, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2) + Rational(-1, 4)), Eq(g(x), C1*Rational(3, 4) + C2*Rational(-1, 4) + C3*Rational(-1, 4) + C4*Rational(-1, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2) + Rational(-1, 4)), Eq(h(x), C1*Rational(-1, 4) + C2*Rational(3, 4) + C3*Rational(-1, 4) + C4*Rational(-1, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2) + Rational(-1, 4)), Eq(k(x), C1*Rational(-1, 4) + C2*Rational(-1, 4) + C3*Rational(3, 4) + C4*Rational(-1, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2) + Rational(-1, 4))] assert dsolve(eqs5) == sol5 assert checksysodesol(eqs5, sol5) == (True, [0, 0, 0, 0]) eqs6 = [Eq(Derivative(f(x), x), x**2*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(g(x), x), x**2*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(h(x), x), x**2*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(k(x), x), x**2*(f(x) + g(x) + h(x) + k(x) + 1))] sol6 = [Eq(f(x), C1*Rational(-1, 4) + C2*Rational(-1, 4) + C3*Rational(-1, 4) + C4*Rational(3, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x**3*Rational(4, 3)) + Rational(-1, 4)), Eq(g(x), C1*Rational(3, 4) + C2*Rational(-1, 4) + C3*Rational(-1, 4) + C4*Rational(-1, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x**3*Rational(4, 3)) + Rational(-1, 4)), Eq(h(x), C1*Rational(-1, 4) + C2*Rational(3, 4) + C3*Rational(-1, 4) + C4*Rational(-1, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x**3*Rational(4, 3)) + Rational(-1, 4)), Eq(k(x), C1*Rational(-1, 4) + C2*Rational(-1, 4) + C3*Rational(3, 4) + C4*Rational(-1, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x**3*Rational(4, 3)) + Rational(-1, 4))] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0, 0, 0]) eqs7 = [Eq(Derivative(f(x), x), (f(x) + g(x) + h(x))*log(x) + sin(x)), Eq(Derivative(g(x), x), (f(x) + g(x) + h(x))*log(x) + sin(x)), Eq(Derivative(h(x), x), (f(x) + g(x) + h(x))*log(x) + sin(x))] sol7 = [Eq(f(x), -C1/3 - C2/3 + 2*C3/3 + (C1/3 + C2/3 + C3/3)*exp(x*(3*log(x) - 3)) + exp(x*(3*log(x) - 3))*Integral(exp(3*x)*exp(-3*x*log(x))*sin(x), x)), Eq(g(x), 2*C1/3 - C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(x*(3*log(x) - 3)) + exp(x*(3*log(x) - 3))*Integral(exp(3*x)*exp(-3*x*log(x))*sin(x), x)), Eq(h(x), -C1/3 + 2*C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(x*(3*log(x) - 3)) + exp(x*(3*log(x) - 3))*Integral(exp(3*x)*exp(-3*x*log(x))*sin(x), x))] with dotprodsimp(True): assert dsolve(eqs7, simplify=False, doit=False) == sol7 assert checksysodesol(eqs7, sol7) == (True, [0, 0, 0]) eqs8 = [Eq(Derivative(f(x), x), (f(x) + g(x) + h(x) + k(x))*log(x) + sin(x)), Eq(Derivative(g(x), x), (f(x) + g(x) + h(x) + k(x))*log(x) + sin(x)), Eq(Derivative(h(x), x), (f(x) + g(x) + h(x) + k(x))*log(x) + sin(x)), Eq(Derivative(k(x), x), (f(x) + g(x) + h(x) + k(x))*log(x) + sin(x))] sol8 = [Eq(f(x), -C1/4 - C2/4 - C3/4 + 3*C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x*(4*log(x) - 4)) + exp(x*(4*log(x) - 4))*Integral(exp(4*x)*exp(-4*x*log(x))*sin(x), x)), Eq(g(x), 3*C1/4 - C2/4 - C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x*(4*log(x) - 4)) + exp(x*(4*log(x) - 4))*Integral(exp(4*x)*exp(-4*x*log(x))*sin(x), x)), Eq(h(x), -C1/4 + 3*C2/4 - C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x*(4*log(x) - 4)) + exp(x*(4*log(x) - 4))*Integral(exp(4*x)*exp(-4*x*log(x))*sin(x), x)), Eq(k(x), -C1/4 - C2/4 + 3*C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x*(4*log(x) - 4)) + exp(x*(4*log(x) - 4))*Integral(exp(4*x)*exp(-4*x*log(x))*sin(x), x))] with dotprodsimp(True): assert dsolve(eqs8) == sol8 assert checksysodesol(eqs8, sol8) == (True, [0, 0, 0, 0]) def test_sysode_linear_neq_order1_type5_type6(): f, g = symbols("f g", cls=Function) x, x_ = symbols("x x_") # Type 5 eqs1 = [Eq(Derivative(f(x), x), (2*f(x) + g(x))/x), Eq(Derivative(g(x), x), (f(x) + 2*g(x))/x)] sol1 = [Eq(f(x), -C1*x + C2*x**3), Eq(g(x), C1*x + C2*x**3)] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) # Type 6 eqs2 = [Eq(Derivative(f(x), x), (2*f(x) + g(x) + 1)/x), Eq(Derivative(g(x), x), (x + f(x) + 2*g(x))/x)] sol2 = [Eq(f(x), C2*x**3 - x*(C1 + Rational(1, 4)) + x*log(x)*Rational(-1, 2) + Rational(-2, 3)), Eq(g(x), C2*x**3 + x*log(x)/2 + x*(C1 + Rational(-1, 4)) + Rational(1, 3))] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0]) def test_higher_order_to_first_order(): f, g = symbols('f g', cls=Function) x = symbols('x') eqs1 = [Eq(Derivative(f(x), (x, 2)), 2*f(x) + g(x)), Eq(Derivative(g(x), (x, 2)), -f(x))] sol1 = [Eq(f(x), -C2*x*exp(-x) + C3*x*exp(x) - (C1 - C2)*exp(-x) + (C3 + C4)*exp(x)), Eq(g(x), C2*x*exp(-x) - C3*x*exp(x) + (C1 + C2)*exp(-x) + (C3 - C4)*exp(x))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) eqs2 = [Eq(f(x).diff(x, 2), 0), Eq(g(x).diff(x, 2), f(x))] sol2 = [Eq(f(x), C1 + C2*x), Eq(g(x), C1*x**2/2 + C2*x**3/6 + C3 + C4*x)] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0]) eqs3 = [Eq(Derivative(f(x), (x, 2)), 2*f(x)), Eq(Derivative(g(x), (x, 2)), -f(x) + 2*g(x))] sol3 = [Eq(f(x), 4*C1*exp(-sqrt(2)*x) + 4*C2*exp(sqrt(2)*x)), Eq(g(x), sqrt(2)*C1*x*exp(-sqrt(2)*x) - sqrt(2)*C2*x*exp(sqrt(2)*x) + (C1 + sqrt(2)*C4)*exp(-sqrt(2)*x) + (C2 - sqrt(2)*C3)*exp(sqrt(2)*x))] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0]) eqs4 = [Eq(Derivative(f(x), (x, 2)), 2*f(x) + g(x)), Eq(Derivative(g(x), (x, 2)), 2*g(x))] sol4 = [Eq(f(x), C1*x*exp(sqrt(2)*x)/4 + C3*x*exp(-sqrt(2)*x)/4 + (C2/4 + sqrt(2)*C3/8)*exp(-sqrt(2)*x) - exp(sqrt(2)*x)*(sqrt(2)*C1/8 + C4*Rational(-1, 4))), Eq(g(x), sqrt(2)*C1*exp(sqrt(2)*x)/2 + sqrt(2)*C3*exp(-sqrt(2)*x)*Rational(-1, 2))] assert dsolve(eqs4) == sol4 assert checksysodesol(eqs4, sol4) == (True, [0, 0]) eqs5 = [Eq(f(x).diff(x, 2), f(x)), Eq(g(x).diff(x, 2), f(x))] sol5 = [Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), -C1*exp(-x) + C2*exp(x) + C3 + C4*x)] assert dsolve(eqs5) == sol5 assert checksysodesol(eqs5, sol5) == (True, [0, 0]) eqs6 = [Eq(Derivative(f(x), (x, 2)), f(x) + g(x)), Eq(Derivative(g(x), (x, 2)), -f(x) - g(x))] sol6 = [Eq(f(x), C1 + C2*x**2/2 + C2 + C4*x**3/6 + x*(C3 + C4)), Eq(g(x), -C1 + C2*x**2*Rational(-1, 2) - C3*x + C4*x**3*Rational(-1, 6))] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0]) eqs7 = [Eq(Derivative(f(x), (x, 2)), f(x) + g(x) + 1), Eq(Derivative(g(x), (x, 2)), f(x) + g(x) + 1)] sol7 = [Eq(f(x), -C1 - C2*x + sqrt(2)*C3*exp(sqrt(2)*x)/2 + sqrt(2)*C4*exp(-sqrt(2)*x)*Rational(-1, 2) + Rational(-1, 2)), Eq(g(x), C1 + C2*x + sqrt(2)*C3*exp(sqrt(2)*x)/2 + sqrt(2)*C4*exp(-sqrt(2)*x)*Rational(-1, 2) + Rational(-1, 2))] assert dsolve(eqs7) == sol7 assert checksysodesol(eqs7, sol7) == (True, [0, 0]) eqs8 = [Eq(Derivative(f(x), (x, 2)), f(x) + g(x) + 1), Eq(Derivative(g(x), (x, 2)), -f(x) - g(x) + 1)] sol8 = [Eq(f(x), C1 + C2 + C4*x**3/6 + x**4/12 + x**2*(C2/2 + Rational(1, 2)) + x*(C3 + C4)), Eq(g(x), -C1 - C3*x + C4*x**3*Rational(-1, 6) + x**4*Rational(-1, 12) - x**2*(C2/2 + Rational(-1, 2)))] assert dsolve(eqs8) == sol8 assert checksysodesol(eqs8, sol8) == (True, [0, 0]) x, y = symbols('x, y', cls=Function) t, l = symbols('t, l') eqs10 = [Eq(Derivative(x(t), (t, 2)), 5*x(t) + 43*y(t)), Eq(Derivative(y(t), (t, 2)), x(t) + 9*y(t))] sol10 = [Eq(x(t), C1*(61 - 9*sqrt(47))*sqrt(sqrt(47) + 7)*exp(-t*sqrt(sqrt(47) + 7))/2 + C2*sqrt(7 - sqrt(47))*(61 + 9*sqrt(47))*exp(-t*sqrt(7 - sqrt(47)))/2 + C3*(61 - 9*sqrt(47))*sqrt(sqrt(47) + 7)*exp(t*sqrt(sqrt(47) + 7))*Rational(-1, 2) + C4*sqrt(7 - sqrt(47))*(61 + 9*sqrt(47))*exp(t*sqrt(7 - sqrt(47)))*Rational(-1, 2)), Eq(y(t), C1*(7 - sqrt(47))*sqrt(sqrt(47) + 7)*exp(-t*sqrt(sqrt(47) + 7))*Rational(-1, 2) + C2*sqrt(7 - sqrt(47))*(sqrt(47) + 7)*exp(-t*sqrt(7 - sqrt(47)))*Rational(-1, 2) + C3*(7 - sqrt(47))*sqrt(sqrt(47) + 7)*exp(t*sqrt(sqrt(47) + 7))/2 + C4*sqrt(7 - sqrt(47))*(sqrt(47) + 7)*exp(t*sqrt(7 - sqrt(47)))/2)] assert dsolve(eqs10) == sol10 assert checksysodesol(eqs10, sol10) == (True, [0, 0]) eqs11 = [Eq(7*x(t) + Derivative(x(t), (t, 2)) - 9*Derivative(y(t), t), 0), Eq(7*y(t) + 9*Derivative(x(t), t) + Derivative(y(t), (t, 2)), 0)] sol11 = [Eq(y(t), C1*(9 - sqrt(109))*sin(sqrt(2)*t*sqrt(9*sqrt(109) + 95)/2)/14 + C2*(9 - sqrt(109))*cos(sqrt(2)*t*sqrt(9*sqrt(109) + 95)/2)*Rational(-1, 14) + C3*(9 + sqrt(109))*sin(sqrt(2)*t*sqrt(95 - 9*sqrt(109))/2)/14 + C4*(9 + sqrt(109))*cos(sqrt(2)*t*sqrt(95 - 9*sqrt(109))/2)*Rational(-1, 14)), Eq(x(t), C1*(9 - sqrt(109))*cos(sqrt(2)*t*sqrt(9*sqrt(109) + 95)/2)*Rational(-1, 14) + C2*(9 - sqrt(109))*sin(sqrt(2)*t*sqrt(9*sqrt(109) + 95)/2)*Rational(-1, 14) + C3*(9 + sqrt(109))*cos(sqrt(2)*t*sqrt(95 - 9*sqrt(109))/2)/14 + C4*(9 + sqrt(109))*sin(sqrt(2)*t*sqrt(95 - 9*sqrt(109))/2)/14)] assert dsolve(eqs11) == sol11 assert checksysodesol(eqs11, sol11) == (True, [0, 0]) # Euler Systems # Note: To add examples of euler systems solver with non-homogeneous term. eqs13 = [Eq(Derivative(f(t), (t, 2)), Derivative(f(t), t)/t + f(t)/t**2 + g(t)/t**2), Eq(Derivative(g(t), (t, 2)), g(t)/t**2)] sol13 = [Eq(f(t), C1*(sqrt(5) + 3)*Rational(-1, 2)*t**(Rational(1, 2) + sqrt(5)*Rational(-1, 2)) + C2*t**(Rational(1, 2) + sqrt(5)/2)*(3 - sqrt(5))*Rational(-1, 2) - C3*t**(1 - sqrt(2))*(1 + sqrt(2)) - C4*t**(1 + sqrt(2))*(1 - sqrt(2))), Eq(g(t), C1*(1 + sqrt(5))*Rational(-1, 2)*t**(Rational(1, 2) + sqrt(5)*Rational(-1, 2)) + C2*t**(Rational(1, 2) + sqrt(5)/2)*(1 - sqrt(5))*Rational(-1, 2))] assert dsolve(eqs13) == sol13 assert checksysodesol(eqs13, sol13) == (True, [0, 0]) # Solving systems using dsolve separately eqs14 = [Eq(Derivative(f(t), (t, 2)), t*f(t)), Eq(Derivative(g(t), (t, 2)), t*g(t))] sol14 = [Eq(f(t), C1*airyai(t) + C2*airybi(t)), Eq(g(t), C3*airyai(t) + C4*airybi(t))] assert dsolve(eqs14) == sol14 assert checksysodesol(eqs14, sol14) == (True, [0, 0]) eqs15 = [Eq(Derivative(x(t), (t, 2)), t*(4*Derivative(x(t), t) + 8*Derivative(y(t), t))), Eq(Derivative(y(t), (t, 2)), t*(12*Derivative(x(t), t) - 6*Derivative(y(t), t)))] sol15 = [Eq(x(t), C1 - erf(sqrt(6)*t)*(sqrt(6)*sqrt(pi)*C2/33 + sqrt(6)*sqrt(pi)*C3*Rational(-1, 44)) + erfi(sqrt(5)*t)*(sqrt(5)*sqrt(pi)*C2*Rational(2, 55) + sqrt(5)*sqrt(pi)*C3*Rational(4, 55))), Eq(y(t), C4 + erf(sqrt(6)*t)*(sqrt(6)*sqrt(pi)*C2*Rational(2, 33) + sqrt(6)*sqrt(pi)*C3*Rational(-1, 22)) + erfi(sqrt(5)*t)*(sqrt(5)*sqrt(pi)*C2*Rational(3, 110) + sqrt(5)*sqrt(pi)*C3*Rational(3, 55)))] assert dsolve(eqs15) == sol15 assert checksysodesol(eqs15, sol15) == (True, [0, 0]) @slow def test_higher_order_to_first_order_9(): f, g = symbols('f g', cls=Function) x = symbols('x') eqs9 = [f(x) + g(x) - 2*exp(I*x) + 2*Derivative(f(x), x) + Derivative(f(x), (x, 2)), f(x) + g(x) - 2*exp(I*x) + 2*Derivative(g(x), x) + Derivative(g(x), (x, 2))] sol9 = [Eq(f(x), -C1 + C2*exp(-2*x)/2 + (C3/2 + C4/2)*exp(-x)*sin(x) + (2 + I)*exp(I*x)*sin(x)**2*Rational(-1, 5) + (1 - 2*I)*exp(I*x)*sin(x)*cos(x)*Rational(2, 5) + (4 - 3*I)*exp(I*x)*cos(x)**2/5 + exp(-x)*sin(x)*Integral(-exp(x)*exp(I*x)*sin(x)**2/cos(x) + exp(x)*exp(I*x)*sin(x) + exp(x)*exp(I*x)/cos(x), x) - exp(-x)*cos(x)*Integral(-exp(x)*exp(I*x)*sin(x)**2/cos(x) + exp(x)*exp(I*x)*sin(x) + exp(x)*exp(I*x)/cos(x), x) - exp(-x)*cos(x)*(C3/2 + C4*Rational(-1, 2))), Eq(g(x), C1 + C2*exp(-2*x)*Rational(-1, 2) + (C3/2 + C4/2)*exp(-x)*sin(x) + (2 + I)*exp(I*x)*sin(x)**2*Rational(-1, 5) + (1 - 2*I)*exp(I*x)*sin(x)*cos(x)*Rational(2, 5) + (4 - 3*I)*exp(I*x)*cos(x)**2/5 + exp(-x)*sin(x)*Integral(-exp(x)*exp(I*x)*sin(x)**2/cos(x) + exp(x)*exp(I*x)*sin(x) + exp(x)*exp(I*x)/cos(x), x) - exp(-x)*cos(x)*Integral(-exp(x)*exp(I*x)*sin(x)**2/cos(x) + exp(x)*exp(I*x)*sin(x) + exp(x)*exp(I*x)/cos(x), x) - exp(-x)*cos(x)*(C3/2 + C4*Rational(-1, 2)))] assert dsolve(eqs9) == sol9 assert checksysodesol(eqs9, sol9) == (True, [0, 0]) def test_higher_order_to_first_order_12(): f, g = symbols('f g', cls=Function) x = symbols('x') x, y = symbols('x, y', cls=Function) t, l = symbols('t, l') eqs12 = [Eq(4*x(t) + Derivative(x(t), (t, 2)) + 8*Derivative(y(t), t), 0), Eq(4*y(t) - 8*Derivative(x(t), t) + Derivative(y(t), (t, 2)), 0)] sol12 = [Eq(y(t), C1*(2 - sqrt(5))*sin(2*t*sqrt(4*sqrt(5) + 9))*Rational(-1, 2) + C2*(2 - sqrt(5))*cos(2*t*sqrt(4*sqrt(5) + 9))/2 + C3*(2 + sqrt(5))*sin(2*t*sqrt(9 - 4*sqrt(5)))*Rational(-1, 2) + C4*(2 + sqrt(5))*cos(2*t*sqrt(9 - 4*sqrt(5)))/2), Eq(x(t), C1*(2 - sqrt(5))*cos(2*t*sqrt(4*sqrt(5) + 9))*Rational(-1, 2) + C2*(2 - sqrt(5))*sin(2*t*sqrt(4*sqrt(5) + 9))*Rational(-1, 2) + C3*(2 + sqrt(5))*cos(2*t*sqrt(9 - 4*sqrt(5)))/2 + C4*(2 + sqrt(5))*sin(2*t*sqrt(9 - 4*sqrt(5)))/2)] assert dsolve(eqs12) == sol12 assert checksysodesol(eqs12, sol12) == (True, [0, 0]) def test_second_order_to_first_order_2(): f, g = symbols("f g", cls=Function) x, t, x_, t_, d, a, m = symbols("x t x_ t_ d a m") eqs2 = [Eq(f(x).diff(x, 2), 2*(x*g(x).diff(x) - g(x))), Eq(g(x).diff(x, 2),-2*(x*f(x).diff(x) - f(x)))] sol2 = [Eq(f(x), C1*x + x*Integral(C2*exp(-x_)*exp(I*exp(2*x_))/2 + C2*exp(-x_)*exp(-I*exp(2*x_))/2 - I*C3*exp(-x_)*exp(I*exp(2*x_))/2 + I*C3*exp(-x_)*exp(-I*exp(2*x_))/2, (x_, log(x)))), Eq(g(x), C4*x + x*Integral(I*C2*exp(-x_)*exp(I*exp(2*x_))/2 - I*C2*exp(-x_)*exp(-I*exp(2*x_))/2 + C3*exp(-x_)*exp(I*exp(2*x_))/2 + C3*exp(-x_)*exp(-I*exp(2*x_))/2, (x_, log(x))))] # XXX: dsolve hangs for this in integration assert dsolve_system(eqs2, simplify=False, doit=False) == [sol2] assert checksysodesol(eqs2, sol2) == (True, [0, 0]) eqs3 = (Eq(diff(f(t),t,t), 9*t*diff(g(t),t)-9*g(t)), Eq(diff(g(t),t,t),7*t*diff(f(t),t)-7*f(t))) sol3 = [Eq(f(t), C1*t + t*Integral(C2*exp(-t_)*exp(3*sqrt(7)*exp(2*t_)/2)/2 + C2*exp(-t_)* exp(-3*sqrt(7)*exp(2*t_)/2)/2 + 3*sqrt(7)*C3*exp(-t_)*exp(3*sqrt(7)*exp(2*t_)/2)/14 - 3*sqrt(7)*C3*exp(-t_)*exp(-3*sqrt(7)*exp(2*t_)/2)/14, (t_, log(t)))), Eq(g(t), C4*t + t*Integral(sqrt(7)*C2*exp(-t_)*exp(3*sqrt(7)*exp(2*t_)/2)/6 - sqrt(7)*C2*exp(-t_)* exp(-3*sqrt(7)*exp(2*t_)/2)/6 + C3*exp(-t_)*exp(3*sqrt(7)*exp(2*t_)/2)/2 + C3*exp(-t_)*exp(-3*sqrt(7)* exp(2*t_)/2)/2, (t_, log(t))))] # XXX: dsolve hangs for this in integration assert dsolve_system(eqs3, simplify=False, doit=False) == [sol3] assert checksysodesol(eqs3, sol3) == (True, [0, 0]) # Regression Test case for sympy#19238 # https://github.com/sympy/sympy/issues/19238 # Note: When the doit method is removed, these particular types of systems # can be divided first so that we have lesser number of big matrices. eqs5 = [Eq(Derivative(g(t), (t, 2)), a*m), Eq(Derivative(f(t), (t, 2)), 0)] sol5 = [Eq(g(t), C1 + C2*t + a*m*t**2/2), Eq(f(t), C3 + C4*t)] assert dsolve(eqs5) == sol5 assert checksysodesol(eqs5, sol5) == (True, [0, 0]) # Type 2 eqs6 = [Eq(Derivative(f(t), (t, 2)), f(t)/t**4), Eq(Derivative(g(t), (t, 2)), d*g(t)/t**4)] sol6 = [Eq(f(t), C1*sqrt(t**2)*exp(-1/t) - C2*sqrt(t**2)*exp(1/t)), Eq(g(t), C3*sqrt(t**2)*exp(-sqrt(d)/t)*d**Rational(-1, 2) - C4*sqrt(t**2)*exp(sqrt(d)/t)*d**Rational(-1, 2))] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0]) @slow def test_second_order_to_first_order_slow1(): f, g = symbols("f g", cls=Function) x, t, x_, t_, d, a, m = symbols("x t x_ t_ d a m") # Type 1 eqs1 = [Eq(f(x).diff(x, 2), 2/x *(x*g(x).diff(x) - g(x))), Eq(g(x).diff(x, 2),-2/x *(x*f(x).diff(x) - f(x)))] sol1 = [Eq(f(x), C1*x + 2*C2*x*Ci(2*x) - C2*sin(2*x) - 2*C3*x*Si(2*x) - C3*cos(2*x)), Eq(g(x), -2*C2*x*Si(2*x) - C2*cos(2*x) - 2*C3*x*Ci(2*x) + C3*sin(2*x) + C4*x)] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) def test_second_order_to_first_order_slow4(): f, g = symbols("f g", cls=Function) x, t, x_, t_, d, a, m = symbols("x t x_ t_ d a m") eqs4 = [Eq(Derivative(f(t), (t, 2)), t*sin(t)*Derivative(g(t), t) - g(t)*sin(t)), Eq(Derivative(g(t), (t, 2)), t*sin(t)*Derivative(f(t), t) - f(t)*sin(t))] sol4 = [Eq(f(t), C1*t + t*Integral(C2*exp(-t_)*exp(exp(t_)*cos(exp(t_)))*exp(-sin(exp(t_)))/2 + C2*exp(-t_)*exp(-exp(t_)*cos(exp(t_)))*exp(sin(exp(t_)))/2 - C3*exp(-t_)*exp(exp(t_)*cos(exp(t_)))* exp(-sin(exp(t_)))/2 + C3*exp(-t_)*exp(-exp(t_)*cos(exp(t_)))*exp(sin(exp(t_)))/2, (t_, log(t)))), Eq(g(t), C4*t + t*Integral(-C2*exp(-t_)*exp(exp(t_)*cos(exp(t_)))*exp(-sin(exp(t_)))/2 + C2*exp(-t_)*exp(-exp(t_)*cos(exp(t_)))*exp(sin(exp(t_)))/2 + C3*exp(-t_)*exp(exp(t_)*cos(exp(t_)))* exp(-sin(exp(t_)))/2 + C3*exp(-t_)*exp(-exp(t_)*cos(exp(t_)))*exp(sin(exp(t_)))/2, (t_, log(t))))] # XXX: dsolve hangs for this in integration assert dsolve_system(eqs4, simplify=False, doit=False) == [sol4] assert checksysodesol(eqs4, sol4) == (True, [0, 0]) def test_component_division(): f, g, h, k = symbols('f g h k', cls=Function) x = symbols("x") funcs = [f(x), g(x), h(x), k(x)] eqs1 = [Eq(Derivative(f(x), x), 2*f(x)), Eq(Derivative(g(x), x), f(x)), Eq(Derivative(h(x), x), h(x)), Eq(Derivative(k(x), x), h(x)**4 + k(x))] sol1 = [Eq(f(x), 2*C1*exp(2*x)), Eq(g(x), C1*exp(2*x) + C2), Eq(h(x), C3*exp(x)), Eq(k(x), C3**4*exp(4*x)/3 + C4*exp(x))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0, 0, 0]) components1 = {((Eq(Derivative(f(x), x), 2*f(x)),), (Eq(Derivative(g(x), x), f(x)),)), ((Eq(Derivative(h(x), x), h(x)),), (Eq(Derivative(k(x), x), h(x)**4 + k(x)),))} eqsdict1 = ({f(x): set(), g(x): {f(x)}, h(x): set(), k(x): {h(x)}}, {f(x): Eq(Derivative(f(x), x), 2*f(x)), g(x): Eq(Derivative(g(x), x), f(x)), h(x): Eq(Derivative(h(x), x), h(x)), k(x): Eq(Derivative(k(x), x), h(x)**4 + k(x))}) graph1 = [{f(x), g(x), h(x), k(x)}, {(g(x), f(x)), (k(x), h(x))}] assert {tuple(tuple(scc) for scc in wcc) for wcc in _component_division(eqs1, funcs, x)} == components1 assert _eqs2dict(eqs1, funcs) == eqsdict1 assert [set(element) for element in _dict2graph(eqsdict1[0])] == graph1 eqs2 = [Eq(Derivative(f(x), x), 2*f(x)), Eq(Derivative(g(x), x), f(x)), Eq(Derivative(h(x), x), h(x)), Eq(Derivative(k(x), x), f(x)**4 + k(x))] sol2 = [Eq(f(x), C1*exp(2*x)), Eq(g(x), C1*exp(2*x)/2 + C2), Eq(h(x), C3*exp(x)), Eq(k(x), C1**4*exp(8*x)/7 + C4*exp(x))] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0, 0, 0]) components2 = {frozenset([(Eq(Derivative(f(x), x), 2*f(x)),), (Eq(Derivative(g(x), x), f(x)),), (Eq(Derivative(k(x), x), f(x)**4 + k(x)),)]), frozenset([(Eq(Derivative(h(x), x), h(x)),)])} eqsdict2 = ({f(x): set(), g(x): {f(x)}, h(x): set(), k(x): {f(x)}}, {f(x): Eq(Derivative(f(x), x), 2*f(x)), g(x): Eq(Derivative(g(x), x), f(x)), h(x): Eq(Derivative(h(x), x), h(x)), k(x): Eq(Derivative(k(x), x), f(x)**4 + k(x))}) graph2 = [{f(x), g(x), h(x), k(x)}, {(g(x), f(x)), (k(x), f(x))}] assert {frozenset(tuple(scc) for scc in wcc) for wcc in _component_division(eqs2, funcs, x)} == components2 assert _eqs2dict(eqs2, funcs) == eqsdict2 assert [set(element) for element in _dict2graph(eqsdict2[0])] == graph2 eqs3 = [Eq(Derivative(f(x), x), 2*f(x)), Eq(Derivative(g(x), x), x + f(x)), Eq(Derivative(h(x), x), h(x)), Eq(Derivative(k(x), x), f(x)**4 + k(x))] sol3 = [Eq(f(x), C1*exp(2*x)), Eq(g(x), C1*exp(2*x)/2 + C2 + x**2/2), Eq(h(x), C3*exp(x)), Eq(k(x), C1**4*exp(8*x)/7 + C4*exp(x))] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0, 0, 0]) components3 = {frozenset([(Eq(Derivative(f(x), x), 2*f(x)),), (Eq(Derivative(g(x), x), x + f(x)),), (Eq(Derivative(k(x), x), f(x)**4 + k(x)),)]), frozenset([(Eq(Derivative(h(x), x), h(x)),),])} eqsdict3 = ({f(x): set(), g(x): {f(x)}, h(x): set(), k(x): {f(x)}}, {f(x): Eq(Derivative(f(x), x), 2*f(x)), g(x): Eq(Derivative(g(x), x), x + f(x)), h(x): Eq(Derivative(h(x), x), h(x)), k(x): Eq(Derivative(k(x), x), f(x)**4 + k(x))}) graph3 = [{f(x), g(x), h(x), k(x)}, {(g(x), f(x)), (k(x), f(x))}] assert {frozenset(tuple(scc) for scc in wcc) for wcc in _component_division(eqs3, funcs, x)} == components3 assert _eqs2dict(eqs3, funcs) == eqsdict3 assert [set(l) for l in _dict2graph(eqsdict3[0])] == graph3 # Note: To be uncommented when the default option to call dsolve first for # single ODE system can be rearranged. This can be done after the doit # option in dsolve is made False by default. eqs4 = [Eq(Derivative(f(x), x), x*f(x) + 2*g(x)), Eq(Derivative(g(x), x), f(x) + x*g(x) + x), Eq(Derivative(h(x), x), h(x)), Eq(Derivative(k(x), x), f(x)**4 + k(x))] sol4 = [Eq(f(x), (C1/2 - sqrt(2)*C2/2 - sqrt(2)*Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 +\ sqrt(2)*x)/2, x)/2 + Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 +\ sqrt(2)*x)/2, x)/2)*exp(x**2/2 - sqrt(2)*x) + (C1/2 + sqrt(2)*C2/2 + sqrt(2)*Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2)*exp(x**2/2 + sqrt(2)*x)), Eq(g(x), (-sqrt(2)*C1/4 + C2/2 + Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 -\ sqrt(2)*Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/4)*exp(x**2/2 - sqrt(2)*x) + (sqrt(2)*C1/4 + C2/2 + Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + sqrt(2)*Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/4)*exp(x**2/2 + sqrt(2)*x)), Eq(h(x), C3*exp(x)), Eq(k(x), C4*exp(x) + exp(x)*Integral((C1*exp(x**2/2 - sqrt(2)*x)/2 + C1*exp(x**2/2 + sqrt(2)*x)/2 - sqrt(2)*C2*exp(x**2/2 - sqrt(2)*x)/2 + sqrt(2)*C2*exp(x**2/2 + sqrt(2)*x)/2 - sqrt(2)*exp(x**2/2 - sqrt(2)*x)*Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + exp(x**2/2 - sqrt(2)*x)*Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + sqrt(2)*exp(x**2/2 + sqrt(2)*x)*Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + exp(x**2/2 + sqrt(2)*x)*Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2)**4*exp(-x), x))] components4 = {(frozenset([Eq(Derivative(f(x), x), x*f(x) + 2*g(x)), Eq(Derivative(g(x), x), x*g(x) + x + f(x))]), frozenset([Eq(Derivative(k(x), x), f(x)**4 + k(x)),])), (frozenset([Eq(Derivative(h(x), x), h(x)),]),)} eqsdict4 = ({f(x): {g(x)}, g(x): {f(x)}, h(x): set(), k(x): {f(x)}}, {f(x): Eq(Derivative(f(x), x), x*f(x) + 2*g(x)), g(x): Eq(Derivative(g(x), x), x*g(x) + x + f(x)), h(x): Eq(Derivative(h(x), x), h(x)), k(x): Eq(Derivative(k(x), x), f(x)**4 + k(x))}) graph4 = [{f(x), g(x), h(x), k(x)}, {(f(x), g(x)), (g(x), f(x)), (k(x), f(x))}] assert {tuple(frozenset(scc) for scc in wcc) for wcc in _component_division(eqs4, funcs, x)} == components4 assert _eqs2dict(eqs4, funcs) == eqsdict4 assert [set(element) for element in _dict2graph(eqsdict4[0])] == graph4 # XXX: dsolve hangs in integration here: assert dsolve_system(eqs4, simplify=False, doit=False) == [sol4] assert checksysodesol(eqs4, sol4) == (True, [0, 0, 0, 0]) eqs5 = [Eq(Derivative(f(x), x), x*f(x) + 2*g(x)), Eq(Derivative(g(x), x), x*g(x) + f(x)), Eq(Derivative(h(x), x), h(x)), Eq(Derivative(k(x), x), f(x)**4 + k(x))] sol5 = [Eq(f(x), (C1/2 - sqrt(2)*C2/2)*exp(x**2/2 - sqrt(2)*x) + (C1/2 + sqrt(2)*C2/2)*exp(x**2/2 + sqrt(2)*x)), Eq(g(x), (-sqrt(2)*C1/4 + C2/2)*exp(x**2/2 - sqrt(2)*x) + (sqrt(2)*C1/4 + C2/2)*exp(x**2/2 + sqrt(2)*x)), Eq(h(x), C3*exp(x)), Eq(k(x), C4*exp(x) + exp(x)*Integral((C1*exp(x**2/2 - sqrt(2)*x)/2 + C1*exp(x**2/2 + sqrt(2)*x)/2 - sqrt(2)*C2*exp(x**2/2 - sqrt(2)*x)/2 + sqrt(2)*C2*exp(x**2/2 + sqrt(2)*x)/2)**4*exp(-x), x))] components5 = {(frozenset([Eq(Derivative(f(x), x), x*f(x) + 2*g(x)), Eq(Derivative(g(x), x), x*g(x) + f(x))]), frozenset([Eq(Derivative(k(x), x), f(x)**4 + k(x)),])), (frozenset([Eq(Derivative(h(x), x), h(x)),]),)} eqsdict5 = ({f(x): {g(x)}, g(x): {f(x)}, h(x): set(), k(x): {f(x)}}, {f(x): Eq(Derivative(f(x), x), x*f(x) + 2*g(x)), g(x): Eq(Derivative(g(x), x), x*g(x) + f(x)), h(x): Eq(Derivative(h(x), x), h(x)), k(x): Eq(Derivative(k(x), x), f(x)**4 + k(x))}) graph5 = [{f(x), g(x), h(x), k(x)}, {(f(x), g(x)), (g(x), f(x)), (k(x), f(x))}] assert {tuple(frozenset(scc) for scc in wcc) for wcc in _component_division(eqs5, funcs, x)} == components5 assert _eqs2dict(eqs5, funcs) == eqsdict5 assert [set(element) for element in _dict2graph(eqsdict5[0])] == graph5 # XXX: dsolve hangs in integration here: assert dsolve_system(eqs5, simplify=False, doit=False) == [sol5] assert checksysodesol(eqs5, sol5) == (True, [0, 0, 0, 0]) def test_linodesolve(): t, x, a = symbols("t x a") f, g, h = symbols("f g h", cls=Function) # Testing the Errors raises(ValueError, lambda: linodesolve(1, t)) raises(ValueError, lambda: linodesolve(a, t)) A1 = Matrix([[1, 2], [2, 4], [4, 6]]) raises(NonSquareMatrixError, lambda: linodesolve(A1, t)) A2 = Matrix([[1, 2, 1], [3, 1, 2]]) raises(NonSquareMatrixError, lambda: linodesolve(A2, t)) # Testing auto functionality func = [f(t), g(t)] eq = [Eq(f(t).diff(t) + g(t).diff(t), g(t)), Eq(g(t).diff(t), f(t))] ceq = canonical_odes(eq, func, t) (A1, A0), b = linear_ode_to_matrix(ceq[0], func, t, 1) A = A0 sol = [C1*(-Rational(1, 2) + sqrt(5)/2)*exp(t*(-Rational(1, 2) + sqrt(5)/2)) + C2*(-sqrt(5)/2 - Rational(1, 2))* exp(t*(-sqrt(5)/2 - Rational(1, 2))), C1*exp(t*(-Rational(1, 2) + sqrt(5)/2)) + C2*exp(t*(-sqrt(5)/2 - Rational(1, 2)))] assert constant_renumber(linodesolve(A, t), variables=Tuple(*eq).free_symbols) == sol # Testing the Errors raises(ValueError, lambda: linodesolve(1, t, b=Matrix([t+1]))) raises(ValueError, lambda: linodesolve(a, t, b=Matrix([log(t) + sin(t)]))) raises(ValueError, lambda: linodesolve(Matrix([7]), t, b=t**2)) raises(ValueError, lambda: linodesolve(Matrix([a+10]), t, b=log(t)*cos(t))) raises(ValueError, lambda: linodesolve(7, t, b=t**2)) raises(ValueError, lambda: linodesolve(a, t, b=log(t) + sin(t))) A1 = Matrix([[1, 2], [2, 4], [4, 6]]) b1 = Matrix([t, 1, t**2]) raises(NonSquareMatrixError, lambda: linodesolve(A1, t, b=b1)) A2 = Matrix([[1, 2, 1], [3, 1, 2]]) b2 = Matrix([t, t**2]) raises(NonSquareMatrixError, lambda: linodesolve(A2, t, b=b2)) raises(ValueError, lambda: linodesolve(A1[:2, :], t, b=b1)) raises(ValueError, lambda: linodesolve(A1[:2, :], t, b=b1[:1])) # DOIT check A1 = Matrix([[1, -1], [1, -1]]) b1 = Matrix([15*t - 10, -15*t - 5]) sol1 = [C1 + C2*t + C2 - 10*t**3 + 10*t**2 + t*(15*t**2 - 5*t) - 10*t, C1 + C2*t - 10*t**3 - 5*t**2 + t*(15*t**2 - 5*t) - 5*t] assert constant_renumber(linodesolve(A1, t, b=b1, type="type2", doit=True), variables=[t]) == sol1 # Testing auto functionality func = [f(t), g(t)] eq = [Eq(f(t).diff(t) + g(t).diff(t), g(t) + t), Eq(g(t).diff(t), f(t))] ceq = canonical_odes(eq, func, t) (A1, A0), b = linear_ode_to_matrix(ceq[0], func, t, 1) A = A0 sol = [-C1*exp(-t/2 + sqrt(5)*t/2)/2 + sqrt(5)*C1*exp(-t/2 + sqrt(5)*t/2)/2 - sqrt(5)*C2*exp(-sqrt(5)*t/2 - t/2)/2 - C2*exp(-sqrt(5)*t/2 - t/2)/2 - exp(-t/2 + sqrt(5)*t/2)*Integral(t*exp(-sqrt(5)*t/2 + t/2)/(-5 + sqrt(5)) - sqrt(5)*t*exp(-sqrt(5)*t/2 + t/2)/(-5 + sqrt(5)), t)/2 + sqrt(5)*exp(-t/2 + sqrt(5)*t/2)*Integral(t*exp(-sqrt(5)*t/2 + t/2)/(-5 + sqrt(5)) - sqrt(5)*t*exp(-sqrt(5)*t/2 + t/2)/(-5 + sqrt(5)), t)/2 - sqrt(5)*exp(-sqrt(5)*t/2 - t/2)*Integral(-sqrt(5)*t*exp(t/2 + sqrt(5)*t/2)/5, t)/2 - exp(-sqrt(5)*t/2 - t/2)*Integral(-sqrt(5)*t*exp(t/2 + sqrt(5)*t/2)/5, t)/2, C1*exp(-t/2 + sqrt(5)*t/2) + C2*exp(-sqrt(5)*t/2 - t/2) + exp(-t/2 + sqrt(5)*t/2)*Integral(t*exp(-sqrt(5)*t/2 + t/2)/(-5 + sqrt(5)) - sqrt(5)*t*exp(-sqrt(5)*t/2 + t/2)/(-5 + sqrt(5)), t) + exp(-sqrt(5)*t/2 - t/2)*Integral(-sqrt(5)*t*exp(t/2 + sqrt(5)*t/2)/5, t)] assert constant_renumber(linodesolve(A, t, b=b), variables=[t]) == sol # non-homogeneous term assumed to be 0 sol1 = [-C1*exp(-t/2 + sqrt(5)*t/2)/2 + sqrt(5)*C1*exp(-t/2 + sqrt(5)*t/2)/2 - sqrt(5)*C2*exp(-sqrt(5)*t/2 - t/2)/2 - C2*exp(-sqrt(5)*t/2 - t/2)/2 - exp(-t/2 + sqrt(5)*t/2)*Integral(0, t)/2 + sqrt(5)*exp(-t/2 + sqrt(5)*t/2)*Integral(0, t)/2 - sqrt(5)*exp(-sqrt(5)*t/2 - t/2)*Integral(0, t)/2 - exp(-sqrt(5)*t/2 - t/2)*Integral(0, t)/2, C1*exp(-t/2 + sqrt(5)*t/2) + C2*exp(-sqrt(5)*t/2 - t/2) + exp(-t/2 + sqrt(5)*t/2)*Integral(0, t) + exp(-sqrt(5)*t/2 - t/2)*Integral(0, t)] assert constant_renumber(linodesolve(A, t, type="type2"), variables=[t]) == sol1 # Testing the Errors raises(ValueError, lambda: linodesolve(t+10, t)) raises(ValueError, lambda: linodesolve(a*t, t)) A1 = Matrix([[1, t], [-t, 1]]) B1, _ = _is_commutative_anti_derivative(A1, t) raises(NonSquareMatrixError, lambda: linodesolve(A1[:, :1], t, B=B1)) raises(ValueError, lambda: linodesolve(A1, t, B=1)) A2 = Matrix([[t, t, t], [t, t, t], [t, t, t]]) B2, _ = _is_commutative_anti_derivative(A2, t) raises(NonSquareMatrixError, lambda: linodesolve(A2, t, B=B2[:2, :])) raises(ValueError, lambda: linodesolve(A2, t, B=2)) raises(ValueError, lambda: linodesolve(A2, t, B=B2, type="type31")) raises(ValueError, lambda: linodesolve(A1, t, B=B2)) raises(ValueError, lambda: linodesolve(A2, t, B=B1)) # Testing auto functionality func = [f(t), g(t)] eq = [Eq(f(t).diff(t), f(t) + t*g(t)), Eq(g(t).diff(t), -t*f(t) + g(t))] ceq = canonical_odes(eq, func, t) (A1, A0), b = linear_ode_to_matrix(ceq[0], func, t, 1) A = A0 sol = [(C1/2 - I*C2/2)*exp(I*t**2/2 + t) + (C1/2 + I*C2/2)*exp(-I*t**2/2 + t), (-I*C1/2 + C2/2)*exp(-I*t**2/2 + t) + (I*C1/2 + C2/2)*exp(I*t**2/2 + t)] assert constant_renumber(linodesolve(A, t), variables=Tuple(*eq).free_symbols) == sol assert constant_renumber(linodesolve(A, t, type="type3"), variables=Tuple(*eq).free_symbols) == sol A1 = Matrix([[t, 1], [t, -1]]) raises(NotImplementedError, lambda: linodesolve(A1, t)) # Testing the Errors raises(ValueError, lambda: linodesolve(t+10, t, b=Matrix([t+1]))) raises(ValueError, lambda: linodesolve(a*t, t, b=Matrix([log(t) + sin(t)]))) raises(ValueError, lambda: linodesolve(Matrix([7*t]), t, b=t**2)) raises(ValueError, lambda: linodesolve(Matrix([a + 10*log(t)]), t, b=log(t)*cos(t))) raises(ValueError, lambda: linodesolve(7*t, t, b=t**2)) raises(ValueError, lambda: linodesolve(a*t**2, t, b=log(t) + sin(t))) A1 = Matrix([[1, t], [-t, 1]]) b1 = Matrix([t, t ** 2]) B1, _ = _is_commutative_anti_derivative(A1, t) raises(NonSquareMatrixError, lambda: linodesolve(A1[:, :1], t, b=b1)) A2 = Matrix([[t, t, t], [t, t, t], [t, t, t]]) b2 = Matrix([t, 1, t**2]) B2, _ = _is_commutative_anti_derivative(A2, t) raises(NonSquareMatrixError, lambda: linodesolve(A2[:2, :], t, b=b2)) raises(ValueError, lambda: linodesolve(A1, t, b=b2)) raises(ValueError, lambda: linodesolve(A2, t, b=b1)) raises(ValueError, lambda: linodesolve(A1, t, b=b1, B=B2)) raises(ValueError, lambda: linodesolve(A2, t, b=b2, B=B1)) # Testing auto functionality func = [f(x), g(x), h(x)] eq = [Eq(f(x).diff(x), x*(f(x) + g(x) + h(x)) + x), Eq(g(x).diff(x), x*(f(x) + g(x) + h(x)) + x), Eq(h(x).diff(x), x*(f(x) + g(x) + h(x)) + 1)] ceq = canonical_odes(eq, func, x) (A1, A0), b = linear_ode_to_matrix(ceq[0], func, x, 1) A = A0 _x1 = exp(-3*x**2/2) _x2 = exp(3*x**2/2) _x3 = Integral(2*_x1*x/3 + _x1/3 + x/3 - Rational(1, 3), x) _x4 = 2*_x2*_x3/3 _x5 = Integral(2*_x1*x/3 + _x1/3 - 2*x/3 + Rational(2, 3), x) sol = [ C1*_x2/3 - C1/3 + C2*_x2/3 - C2/3 + C3*_x2/3 + 2*C3/3 + _x2*_x5/3 + _x3/3 + _x4 - _x5/3, C1*_x2/3 + 2*C1/3 + C2*_x2/3 - C2/3 + C3*_x2/3 - C3/3 + _x2*_x5/3 + _x3/3 + _x4 - _x5/3, C1*_x2/3 - C1/3 + C2*_x2/3 + 2*C2/3 + C3*_x2/3 - C3/3 + _x2*_x5/3 - 2*_x3/3 + _x4 + 2*_x5/3, ] assert constant_renumber(linodesolve(A, x, b=b), variables=Tuple(*eq).free_symbols) == sol assert constant_renumber(linodesolve(A, x, b=b, type="type4"), variables=Tuple(*eq).free_symbols) == sol A1 = Matrix([[t, 1], [t, -1]]) raises(NotImplementedError, lambda: linodesolve(A1, t, b=b1)) # non-homogeneous term not passed sol1 = [-C1/3 - C2/3 + 2*C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2), 2*C1/3 - C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2), -C1/3 + 2*C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2)] assert constant_renumber(linodesolve(A, x, type="type4", doit=True), variables=Tuple(*eq).free_symbols) == sol1 @slow def test_linear_3eq_order1_type4_slow(): x, y, z = symbols('x, y, z', cls=Function) t = Symbol('t') f = t ** 3 + log(t) g = t ** 2 + sin(t) eq1 = (Eq(diff(x(t), t), (4 * f + g) * x(t) - f * y(t) - 2 * f * z(t)), Eq(diff(y(t), t), 2 * f * x(t) + (f + g) * y(t) - 2 * f * z(t)), Eq(diff(z(t), t), 5 * f * x(t) + f * y( t) + (-3 * f + g) * z(t))) with dotprodsimp(True): dsolve(eq1) @slow def test_linear_neq_order1_type2_slow1(): i, r1, c1, r2, c2, t = symbols('i, r1, c1, r2, c2, t') x1 = Function('x1') x2 = Function('x2') eq1 = r1*c1*Derivative(x1(t), t) + x1(t) - x2(t) - r1*i eq2 = r2*c1*Derivative(x1(t), t) + r2*c2*Derivative(x2(t), t) + x2(t) - r2*i eq = [eq1, eq2] # XXX: Solution is too complicated [sol] = dsolve_system(eq, simplify=False, doit=False) assert checksysodesol(eq, sol) == (True, [0, 0]) # Regression test case for issue #9204 # https://github.com/sympy/sympy/issues/9204 @slow def test_linear_new_order1_type2_de_lorentz_slow_check(): if ON_TRAVIS: skip("Too slow for travis.") m = Symbol("m", real=True) q = Symbol("q", real=True) t = Symbol("t", real=True) e1, e2, e3 = symbols("e1:4", real=True) b1, b2, b3 = symbols("b1:4", real=True) v1, v2, v3 = symbols("v1:4", cls=Function, real=True) eqs = [ -e1*q + m*Derivative(v1(t), t) - q*(-b2*v3(t) + b3*v2(t)), -e2*q + m*Derivative(v2(t), t) - q*(b1*v3(t) - b3*v1(t)), -e3*q + m*Derivative(v3(t), t) - q*(-b1*v2(t) + b2*v1(t)) ] sol = dsolve(eqs) assert checksysodesol(eqs, sol) == (True, [0, 0, 0]) # Regression test case for issue #14001 # https://github.com/sympy/sympy/issues/14001 @slow def test_linear_neq_order1_type2_slow_check(): RC, t, C, Vs, L, R1, V0, I0 = symbols("RC t C Vs L R1 V0 I0") V = Function("V") I = Function("I") system = [Eq(V(t).diff(t), -1/RC*V(t) + I(t)/C), Eq(I(t).diff(t), -R1/L*I(t) - 1/L*V(t) + Vs/L)] [sol] = dsolve_system(system, simplify=False, doit=False) assert checksysodesol(system, sol) == (True, [0, 0]) def _linear_3eq_order1_type4_long(): x, y, z = symbols('x, y, z', cls=Function) t = Symbol('t') f = t ** 3 + log(t) g = t ** 2 + sin(t) eq1 = (Eq(diff(x(t), t), (4*f + g)*x(t) - f*y(t) - 2*f*z(t)), Eq(diff(y(t), t), 2*f*x(t) + (f + g)*y(t) - 2*f*z(t)), Eq(diff(z(t), t), 5*f*x(t) + f*y( t) + (-3*f + g)*z(t))) dsolve_sol = dsolve(eq1) dsolve_sol1 = [_simpsol(sol) for sol in dsolve_sol] x_1 = sqrt(-t**6 - 8*t**3*log(t) + 8*t**3 - 16*log(t)**2 + 32*log(t) - 16) x_2 = sqrt(3) x_3 = 8324372644*C1*x_1*x_2 + 4162186322*C2*x_1*x_2 - 8324372644*C3*x_1*x_2 x_4 = 1 / (1903457163*t**3 + 3825881643*x_1*x_2 + 7613828652*log(t) - 7613828652) x_5 = exp(t**3/3 + t*x_1*x_2/4 - cos(t)) x_6 = exp(t**3/3 - t*x_1*x_2/4 - cos(t)) x_7 = exp(t**4/2 + t**3/3 + 2*t*log(t) - 2*t - cos(t)) x_8 = 91238*C1*x_1*x_2 + 91238*C2*x_1*x_2 - 91238*C3*x_1*x_2 x_9 = 1 / (66049*t**3 - 50629*x_1*x_2 + 264196*log(t) - 264196) x_10 = 50629 * C1 / 25189 + 37909*C2/25189 - 50629*C3/25189 - x_3*x_4 x_11 = -50629*C1/25189 - 12720*C2/25189 + 50629*C3/25189 + x_3*x_4 sol = [Eq(x(t), x_10*x_5 + x_11*x_6 + x_7*(C1 - C2)), Eq(y(t), x_10*x_5 + x_11*x_6), Eq(z(t), x_5*( -424*C1/257 - 167*C2/257 + 424*C3/257 - x_8*x_9) + x_6*(167*C1/257 + 424*C2/257 - 167*C3/257 + x_8*x_9) + x_7*(C1 - C2))] assert dsolve_sol1 == sol assert checksysodesol(eq1, dsolve_sol1) == (True, [0, 0, 0]) @slow def test_neq_order1_type4_slow_check1(): f, g = symbols("f g", cls=Function) x = symbols("x") eqs = [Eq(diff(f(x), x), x*f(x) + x**2*g(x) + x), Eq(diff(g(x), x), 2*x**2*f(x) + (x + 3*x**2)*g(x) + 1)] sol = dsolve(eqs) assert checksysodesol(eqs, sol) == (True, [0, 0]) @slow def test_neq_order1_type4_slow_check2(): f, g, h = symbols("f, g, h", cls=Function) x = Symbol("x") eqs = [ Eq(Derivative(f(x), x), x*h(x) + f(x) + g(x) + 1), Eq(Derivative(g(x), x), x*g(x) + f(x) + h(x) + 10), Eq(Derivative(h(x), x), x*f(x) + x + g(x) + h(x)) ] with dotprodsimp(True): sol = dsolve(eqs) assert checksysodesol(eqs, sol) == (True, [0, 0, 0]) def _neq_order1_type4_slow3(): f, g = symbols("f g", cls=Function) x = symbols("x") eqs = [ Eq(Derivative(f(x), x), x*f(x) + g(x) + sin(x)), Eq(Derivative(g(x), x), x**2 + x*g(x) - f(x)) ] sol = [ Eq(f(x), (C1/2 - I*C2/2 - I*Integral(x**2*exp(-x**2/2 - I*x)/2 + x**2*exp(-x**2/2 + I*x)/2 + I*exp(-x**2/2 - I*x)*sin(x)/2 - I*exp(-x**2/2 + I*x)*sin(x)/2, x)/2 + Integral(-I*x**2*exp(-x**2/2 - I*x)/2 + I*x**2*exp(-x**2/2 + I*x)/2 + exp(-x**2/2 - I*x)*sin(x)/2 + exp(-x**2/2 + I*x)*sin(x)/2, x)/2)*exp(x**2/2 + I*x) + (C1/2 + I*C2/2 + I*Integral(x**2*exp(-x**2/2 - I*x)/2 + x**2*exp(-x**2/2 + I*x)/2 + I*exp(-x**2/2 - I*x)*sin(x)/2 - I*exp(-x**2/2 + I*x)*sin(x)/2, x)/2 + Integral(-I*x**2*exp(-x**2/2 - I*x)/2 + I*x**2*exp(-x**2/2 + I*x)/2 + exp(-x**2/2 - I*x)*sin(x)/2 + exp(-x**2/2 + I*x)*sin(x)/2, x)/2)*exp(x**2/2 - I*x)), Eq(g(x), (-I*C1/2 + C2/2 + Integral(x**2*exp(-x**2/2 - I*x)/2 + x**2*exp(-x**2/2 + I*x)/2 + I*exp(-x**2/2 - I*x)*sin(x)/2 - I*exp(-x**2/2 + I*x)*sin(x)/2, x)/2 - I*Integral(-I*x**2*exp(-x**2/2 - I*x)/2 + I*x**2*exp(-x**2/2 + I*x)/2 + exp(-x**2/2 - I*x)*sin(x)/2 + exp(-x**2/2 + I*x)*sin(x)/2, x)/2)*exp(x**2/2 - I*x) + (I*C1/2 + C2/2 + Integral(x**2*exp(-x**2/2 - I*x)/2 + x**2*exp(-x**2/2 + I*x)/2 + I*exp(-x**2/2 - I*x)*sin(x)/2 - I*exp(-x**2/2 + I*x)*sin(x)/2, x)/2 + I*Integral(-I*x**2*exp(-x**2/2 - I*x)/2 + I*x**2*exp(-x**2/2 + I*x)/2 + exp(-x**2/2 - I*x)*sin(x)/2 + exp(-x**2/2 + I*x)*sin(x)/2, x)/2)*exp(x**2/2 + I*x)) ] return eqs, sol def test_neq_order1_type4_slow3(): eqs, sol = _neq_order1_type4_slow3() assert dsolve_system(eqs, simplify=False, doit=False) == [sol] # XXX: dsolve gives an error in integration: # assert dsolve(eqs) == sol # https://github.com/sympy/sympy/issues/20155 @slow def test_neq_order1_type4_slow_check3(): eqs, sol = _neq_order1_type4_slow3() assert checksysodesol(eqs, sol) == (True, [0, 0]) @XFAIL @slow def test_linear_3eq_order1_type4_long_dsolve_slow_xfail(): if ON_TRAVIS: skip("Too slow for travis.") eq, sol = _linear_3eq_order1_type4_long() dsolve_sol = dsolve(eq) dsolve_sol1 = [_simpsol(sol) for sol in dsolve_sol] assert dsolve_sol1 == sol @slow def test_linear_3eq_order1_type4_long_dsolve_dotprodsimp(): if ON_TRAVIS: skip("Too slow for travis.") eq, sol = _linear_3eq_order1_type4_long() # XXX: Only works with dotprodsimp see # test_linear_3eq_order1_type4_long_dsolve_slow_xfail which is too slow with dotprodsimp(True): dsolve_sol = dsolve(eq) dsolve_sol1 = [_simpsol(sol) for sol in dsolve_sol] assert dsolve_sol1 == sol @slow def test_linear_3eq_order1_type4_long_check(): if ON_TRAVIS: skip("Too slow for travis.") eq, sol = _linear_3eq_order1_type4_long() assert checksysodesol(eq, sol) == (True, [0, 0, 0]) def test_dsolve_system(): f, g = symbols("f g", cls=Function) x = symbols("x") eqs = [Eq(f(x).diff(x), f(x) + g(x)), Eq(g(x).diff(x), f(x) + g(x))] funcs = [f(x), g(x)] sol = [[Eq(f(x), -C1 + C2*exp(2*x)), Eq(g(x), C1 + C2*exp(2*x))]] assert dsolve_system(eqs, funcs=funcs, t=x, doit=True) == sol raises(ValueError, lambda: dsolve_system(1)) raises(ValueError, lambda: dsolve_system(eqs, 1)) raises(ValueError, lambda: dsolve_system(eqs, funcs, 1)) raises(ValueError, lambda: dsolve_system(eqs, funcs[:1], x)) eq = (Eq(f(x).diff(x), 12 * f(x) - 6 * g(x)), Eq(g(x).diff(x) ** 2, 11 * f(x) + 3 * g(x))) raises(NotImplementedError, lambda: dsolve_system(eq) == ([], [])) raises(NotImplementedError, lambda: dsolve_system(eq, funcs=[f(x), g(x)]) == ([], [])) raises(NotImplementedError, lambda: dsolve_system(eq, funcs=[f(x), g(x)], t=x) == ([], [])) raises(NotImplementedError, lambda: dsolve_system(eq, funcs=[f(x), g(x)], t=x, ics={f(0): 1, g(0): 1}) == ([], [])) raises(NotImplementedError, lambda: dsolve_system(eq, t=x, ics={f(0): 1, g(0): 1}) == ([], [])) raises(NotImplementedError, lambda: dsolve_system(eq, ics={f(0): 1, g(0): 1}) == ([], [])) raises(NotImplementedError, lambda: dsolve_system(eq, funcs=[f(x), g(x)], ics={f(0): 1, g(0): 1}) == ([], [])) def test_dsolve(): f, g = symbols('f g', cls=Function) x, y = symbols('x y') eqs = [f(x).diff(x) - x, f(x).diff(x) + x] with raises(ValueError): dsolve(eqs) eqs = [f(x, y).diff(x)] with raises(ValueError): dsolve(eqs) eqs = [f(x, y).diff(x)+g(x).diff(x), g(x).diff(x)] with raises(ValueError): dsolve(eqs) @slow def test_higher_order1_slow1(): x, y = symbols("x y", cls=Function) t = symbols("t") eq = [ Eq(diff(x(t),t,t), (log(t)+t**2)*diff(x(t),t)+(log(t)+t**2)*3*diff(y(t),t)), Eq(diff(y(t),t,t), (log(t)+t**2)*2*diff(x(t),t)+(log(t)+t**2)*9*diff(y(t),t)) ] sol, = dsolve_system(eq, simplify=False, doit=False) # The solution is too long to write out explicitly and checkodesol is too # slow so we test for particular values of t: for e in eq: res = (e.lhs - e.rhs).subs({sol[0].lhs:sol[0].rhs, sol[1].lhs:sol[1].rhs}) res = res.subs({d: d.doit(deep=False) for d in res.atoms(Derivative)}) assert ratsimp(res.subs(t, 1)) == 0 def test_second_order_type2_slow1(): x, y, z = symbols('x, y, z', cls=Function) t, l = symbols('t, l') eqs1 = [Eq(Derivative(x(t), (t, 2)), t*(2*x(t) + y(t))), Eq(Derivative(y(t), (t, 2)), t*(-x(t) + 2*y(t)))] sol1 = [Eq(x(t), I*C1*airyai(t*(2 - I)**(S(1)/3)) + I*C2*airybi(t*(2 - I)**(S(1)/3)) - I*C3*airyai(t*(2 + I)**(S(1)/3)) - I*C4*airybi(t*(2 + I)**(S(1)/3))), Eq(y(t), C1*airyai(t*(2 - I)**(S(1)/3)) + C2*airybi(t*(2 - I)**(S(1)/3)) + C3*airyai(t*(2 + I)**(S(1)/3)) + C4*airybi(t*(2 + I)**(S(1)/3)))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) @slow @XFAIL def test_nonlinear_3eq_order1_type1(): if ON_TRAVIS: skip("Too slow for travis.") a, b, c = symbols('a b c') eqs = [ a * f(x).diff(x) - (b - c) * g(x) * h(x), b * g(x).diff(x) - (c - a) * h(x) * f(x), c * h(x).diff(x) - (a - b) * f(x) * g(x), ] assert dsolve(eqs) # NotImplementedError @XFAIL def test_nonlinear_3eq_order1_type4(): eqs = [ Eq(f(x).diff(x), (2*h(x)*g(x) - 3*g(x)*h(x))), Eq(g(x).diff(x), (4*f(x)*h(x) - 2*h(x)*f(x))), Eq(h(x).diff(x), (3*g(x)*f(x) - 4*f(x)*g(x))), ] dsolve(eqs) # KeyError when matching # sol = ? # assert dsolve_sol == sol # assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0]) @slow @XFAIL def test_nonlinear_3eq_order1_type3(): if ON_TRAVIS: skip("Too slow for travis.") eqs = [ Eq(f(x).diff(x), (2*f(x)**2 - 3 )), Eq(g(x).diff(x), (4 - 2*h(x) )), Eq(h(x).diff(x), (3*h(x) - 4*f(x)**2)), ] dsolve(eqs) # Not sure if this finishes... # sol = ? # assert dsolve_sol == sol # assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0]) @XFAIL def test_nonlinear_3eq_order1_type5(): eqs = [ Eq(f(x).diff(x), f(x)*(2*f(x) - 3*g(x))), Eq(g(x).diff(x), g(x)*(4*g(x) - 2*h(x))), Eq(h(x).diff(x), h(x)*(3*h(x) - 4*f(x))), ] dsolve(eqs) # KeyError # sol = ? # assert dsolve_sol == sol # assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0]) def test_linear_2eq_order1(): x, y, z = symbols('x, y, z', cls=Function) k, l, m, n = symbols('k, l, m, n', Integer=True) t = Symbol('t') x0, y0 = symbols('x0, y0', cls=Function) eq1 = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23)) sol1 = [Eq(x(t), C1*exp(t*(sqrt(6) + 3)) + C2*exp(t*(-sqrt(6) + 3)) - Rational(22, 3)), \ Eq(y(t), C1*(2 + sqrt(6))*exp(t*(sqrt(6) + 3)) + C2*(-sqrt(6) + 2)*exp(t*(-sqrt(6) + 3)) - Rational(5, 3))] assert checksysodesol(eq1, sol1) == (True, [0, 0]) eq2 = (Eq(diff(x(t),t), x(t) + y(t) + 81), Eq(diff(y(t),t), -2*x(t) + y(t) + 23)) sol2 = [Eq(x(t), (C1*cos(sqrt(2)*t) + C2*sin(sqrt(2)*t))*exp(t) - Rational(58, 3)), \ Eq(y(t), (-sqrt(2)*C1*sin(sqrt(2)*t) + sqrt(2)*C2*cos(sqrt(2)*t))*exp(t) - Rational(185, 3))] assert checksysodesol(eq2, sol2) == (True, [0, 0]) eq3 = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t))) sol3 = [Eq(x(t), (C1*exp(2*t) + C2*exp(-2*t))*exp(Rational(5, 2)*t**2)), \ Eq(y(t), (C1*exp(2*t) - C2*exp(-2*t))*exp(Rational(5, 2)*t**2))] assert checksysodesol(eq3, sol3) == (True, [0, 0]) eq4 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t))) sol4 = [Eq(x(t), (C1*cos((t**3)/3) + C2*sin((t**3)/3))*exp(Rational(5, 2)*t**2)), \ Eq(y(t), (-C1*sin((t**3)/3) + C2*cos((t**3)/3))*exp(Rational(5, 2)*t**2))] assert checksysodesol(eq4, sol4) == (True, [0, 0]) eq5 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + (5*t+9*t**2)*y(t))) sol5 = [Eq(x(t), (C1*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \ C2*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2)), \ Eq(y(t), (C1*(sqrt(77)/2 + Rational(9, 2))*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \ C2*(-sqrt(77)/2 + Rational(9, 2))*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2))] assert checksysodesol(eq5, sol5) == (True, [0, 0]) eq6 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), (1-t**2)*x(t) + (5*t+9*t**2)*y(t))) sol6 = [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t)), \ Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t) + \ exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)))] s = dsolve(eq6) assert s == sol6 # too complicated to test with subs and simplify # assert checksysodesol(eq10, sol10) == (True, [0, 0]) # this one fails def test_nonlinear_2eq_order1(): x, y, z = symbols('x, y, z', cls=Function) t = Symbol('t') eq1 = (Eq(diff(x(t),t),x(t)*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol1 = [ Eq(x(t), C1*exp((-1/(4*C2 + 4*t))**(Rational(-1, 4)))), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), C1*exp(-1/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), C1*exp(-I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), C1*exp(I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert dsolve(eq1) == sol1 assert checksysodesol(eq1, sol1) == (True, [0, 0]) eq2 = (Eq(diff(x(t),t), exp(3*x(t))*y(t)**3),Eq(diff(y(t),t), y(t)**5)) sol2 = [ Eq(x(t), -log(C1 - 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), -log(C1 + 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), -log(C1 + 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), -log(C1 - 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert dsolve(eq2) == sol2 assert checksysodesol(eq2, sol2) == (True, [0, 0]) eq3 = (Eq(diff(x(t),t), y(t)*x(t)), Eq(diff(y(t),t), x(t)**3)) tt = Rational(2, 3) sol3 = [ Eq(x(t), 6**tt/(6*(-sinh(sqrt(C1)*(C2 + t)/2)/sqrt(C1))**tt)), Eq(y(t), sqrt(C1 + C1/sinh(sqrt(C1)*(C2 + t)/2)**2)/3)] assert dsolve(eq3) == sol3 # FIXME: assert checksysodesol(eq3, sol3) == (True, [0, 0]) eq4 = (Eq(diff(x(t),t),x(t)*y(t)*sin(t)**2), Eq(diff(y(t),t),y(t)**2*sin(t)**2)) sol4 = {Eq(x(t), -2*exp(C1)/(C2*exp(C1) + t - sin(2*t)/2)), Eq(y(t), -2/(C1 + t - sin(2*t)/2))} assert dsolve(eq4) == sol4 # FIXME: assert checksysodesol(eq4, sol4) == (True, [0, 0]) eq5 = (Eq(x(t),t*diff(x(t),t)+diff(x(t),t)*diff(y(t),t)), Eq(y(t),t*diff(y(t),t)+diff(y(t),t)**2)) sol5 = {Eq(x(t), C1*C2 + C1*t), Eq(y(t), C2**2 + C2*t)} assert dsolve(eq5) == sol5 assert checksysodesol(eq5, sol5) == (True, [0, 0]) eq6 = (Eq(diff(x(t),t),x(t)**2*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol6 = [ Eq(x(t), 1/(C1 - 1/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), 1/(C1 + (-1/(4*C2 + 4*t))**(Rational(-1, 4)))), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), 1/(C1 + I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), 1/(C1 - I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert dsolve(eq6) == sol6 assert checksysodesol(eq6, sol6) == (True, [0, 0]) @slow def test_nonlinear_3eq_order1(): x, y, z = symbols('x, y, z', cls=Function) t, u = symbols('t u') eq1 = (4*diff(x(t),t) + 2*y(t)*z(t), 3*diff(y(t),t) - z(t)*x(t), 5*diff(z(t),t) - x(t)*y(t)) sol1 = [Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)), (u, x(t))), C3 - sqrt(15)*t/15), Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)), (u, y(t))), C3 + sqrt(5)*t/10), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)* sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*t/6)] assert [i.dummy_eq(j) for i, j in zip(dsolve(eq1), sol1)] # FIXME: assert checksysodesol(eq1, sol1) == (True, [0, 0, 0]) eq2 = (4*diff(x(t),t) + 2*y(t)*z(t)*sin(t), 3*diff(y(t),t) - z(t)*x(t)*sin(t), 5*diff(z(t),t) - x(t)*y(t)*sin(t)) sol2 = [Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)), (u, x(t))), C3 + sqrt(5)*cos(t)/10), Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)), (u, y(t))), C3 - sqrt(15)*cos(t)/15), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)* sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*cos(t)/6)] assert [i.dummy_eq(j) for i, j in zip(dsolve(eq2), sol2)] # FIXME: assert checksysodesol(eq2, sol2) == (True, [0, 0, 0]) def test_C1_function_9239(): t = Symbol('t') C1 = Function('C1') C2 = Function('C2') C3 = Symbol('C3') C4 = Symbol('C4') eq = (Eq(diff(C1(t), t), 9*C2(t)), Eq(diff(C2(t), t), 12*C1(t))) sol = [Eq(C1(t), 9*C3*exp(6*sqrt(3)*t) + 9*C4*exp(-6*sqrt(3)*t)), Eq(C2(t), 6*sqrt(3)*C3*exp(6*sqrt(3)*t) - 6*sqrt(3)*C4*exp(-6*sqrt(3)*t))] assert checksysodesol(eq, sol) == (True, [0, 0]) def test_dsolve_linsystem_symbol(): eps = Symbol('epsilon', positive=True) eq1 = (Eq(diff(f(x), x), -eps*g(x)), Eq(diff(g(x), x), eps*f(x))) sol1 = [Eq(f(x), -C1*eps*cos(eps*x) - C2*eps*sin(eps*x)), Eq(g(x), -C1*eps*sin(eps*x) + C2*eps*cos(eps*x))] assert checksysodesol(eq1, sol1) == (True, [0, 0])
1730bbc2f9086581750152622280749a6757394c8a11c0c3f62321c5f436818b
from sympy.core.numbers import (E, Rational, pi) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.core import S, symbols, I from sympy.discrete.convolutions import ( convolution, convolution_fft, convolution_ntt, convolution_fwht, convolution_subset, covering_product, intersecting_product) from sympy.testing.pytest import raises from sympy.abc import x, y def test_convolution(): # fft a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)] b = [9, 5, 5, 4, 3, 2] c = [3, 5, 3, 7, 8] d = [1422, 6572, 3213, 5552] assert convolution(a, b) == convolution_fft(a, b) assert convolution(a, b, dps=9) == convolution_fft(a, b, dps=9) assert convolution(a, d, dps=7) == convolution_fft(d, a, dps=7) assert convolution(a, d[1:], dps=3) == convolution_fft(d[1:], a, dps=3) # prime moduli of the form (m*2**k + 1), sequence length # should be a divisor of 2**k p = 7*17*2**23 + 1 q = 19*2**10 + 1 # ntt assert convolution(d, b, prime=q) == convolution_ntt(b, d, prime=q) assert convolution(c, b, prime=p) == convolution_ntt(b, c, prime=p) assert convolution(d, c, prime=p) == convolution_ntt(c, d, prime=p) raises(TypeError, lambda: convolution(b, d, dps=5, prime=q)) raises(TypeError, lambda: convolution(b, d, dps=6, prime=q)) # fwht assert convolution(a, b, dyadic=True) == convolution_fwht(a, b) assert convolution(a, b, dyadic=False) == convolution(a, b) raises(TypeError, lambda: convolution(b, d, dps=2, dyadic=True)) raises(TypeError, lambda: convolution(b, d, prime=p, dyadic=True)) raises(TypeError, lambda: convolution(a, b, dps=2, dyadic=True)) raises(TypeError, lambda: convolution(b, c, prime=p, dyadic=True)) # subset assert convolution(a, b, subset=True) == convolution_subset(a, b) == \ convolution(a, b, subset=True, dyadic=False) == \ convolution(a, b, subset=True) assert convolution(a, b, subset=False) == convolution(a, b) raises(TypeError, lambda: convolution(a, b, subset=True, dyadic=True)) raises(TypeError, lambda: convolution(c, d, subset=True, dps=6)) raises(TypeError, lambda: convolution(a, c, subset=True, prime=q)) def test_cyclic_convolution(): # fft a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)] b = [9, 5, 5, 4, 3, 2] assert convolution([1, 2, 3], [4, 5, 6], cycle=0) == \ convolution([1, 2, 3], [4, 5, 6], cycle=5) == \ convolution([1, 2, 3], [4, 5, 6]) assert convolution([1, 2, 3], [4, 5, 6], cycle=3) == [31, 31, 28] a = [Rational(1, 3), Rational(7, 3), Rational(5, 9), Rational(2, 7), Rational(5, 8)] b = [Rational(3, 5), Rational(4, 7), Rational(7, 8), Rational(8, 9)] assert convolution(a, b, cycle=0) == \ convolution(a, b, cycle=len(a) + len(b) - 1) assert convolution(a, b, cycle=4) == [Rational(87277, 26460), Rational(30521, 11340), Rational(11125, 4032), Rational(3653, 1080)] assert convolution(a, b, cycle=6) == [Rational(20177, 20160), Rational(676, 315), Rational(47, 24), Rational(3053, 1080), Rational(16397, 5292), Rational(2497, 2268)] assert convolution(a, b, cycle=9) == \ convolution(a, b, cycle=0) + [S.Zero] # ntt a = [2313, 5323532, S(3232), 42142, 42242421] b = [S(33456), 56757, 45754, 432423] assert convolution(a, b, prime=19*2**10 + 1, cycle=0) == \ convolution(a, b, prime=19*2**10 + 1, cycle=8) == \ convolution(a, b, prime=19*2**10 + 1) assert convolution(a, b, prime=19*2**10 + 1, cycle=5) == [96, 17146, 2664, 15534, 3517] assert convolution(a, b, prime=19*2**10 + 1, cycle=7) == [4643, 3458, 1260, 15534, 3517, 16314, 13688] assert convolution(a, b, prime=19*2**10 + 1, cycle=9) == \ convolution(a, b, prime=19*2**10 + 1) + [0] # fwht u, v, w, x, y = symbols('u v w x y') p, q, r, s, t = symbols('p q r s t') c = [u, v, w, x, y] d = [p, q, r, s, t] assert convolution(a, b, dyadic=True, cycle=3) == \ [2499522285783, 19861417974796, 4702176579021] assert convolution(a, b, dyadic=True, cycle=5) == [2718149225143, 2114320852171, 20571217906407, 246166418903, 1413262436976] assert convolution(c, d, dyadic=True, cycle=4) == \ [p*u + p*y + q*v + r*w + s*x + t*u + t*y, p*v + q*u + q*y + r*x + s*w + t*v, p*w + q*x + r*u + r*y + s*v + t*w, p*x + q*w + r*v + s*u + s*y + t*x] assert convolution(c, d, dyadic=True, cycle=6) == \ [p*u + q*v + r*w + r*y + s*x + t*w + t*y, p*v + q*u + r*x + s*w + s*y + t*x, p*w + q*x + r*u + s*v, p*x + q*w + r*v + s*u, p*y + t*u, q*y + t*v] # subset assert convolution(a, b, subset=True, cycle=7) == [18266671799811, 178235365533, 213958794, 246166418903, 1413262436976, 2397553088697, 1932759730434] assert convolution(a[1:], b, subset=True, cycle=4) == \ [178104086592, 302255835516, 244982785880, 3717819845434] assert convolution(a, b[:-1], subset=True, cycle=6) == [1932837114162, 178235365533, 213958794, 245166224504, 1413262436976, 2397553088697] assert convolution(c, d, subset=True, cycle=3) == \ [p*u + p*x + q*w + r*v + r*y + s*u + t*w, p*v + p*y + q*u + s*y + t*u + t*x, p*w + q*y + r*u + t*v] assert convolution(c, d, subset=True, cycle=5) == \ [p*u + q*y + t*v, p*v + q*u + r*y + t*w, p*w + r*u + s*y + t*x, p*x + q*w + r*v + s*u, p*y + t*u] raises(ValueError, lambda: convolution([1, 2, 3], [4, 5, 6], cycle=-1)) def test_convolution_fft(): assert all(convolution_fft([], x, dps=y) == [] for x in ([], [1]) for y in (None, 3)) assert convolution_fft([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18] assert convolution_fft([1], [5, 6, 7]) == [5, 6, 7] assert convolution_fft([1, 3], [5, 6, 7]) == [5, 21, 25, 21] assert convolution_fft([1 + 2*I], [2 + 3*I]) == [-4 + 7*I] assert convolution_fft([1 + 2*I, 3 + 4*I, 5 + Rational(3, 5)*I], [Rational(2, 5) + Rational(4, 7)*I]) == \ [Rational(-26, 35) + I*Rational(48, 35), Rational(-38, 35) + I*Rational(116, 35), Rational(58, 35) + I*Rational(542, 175)] assert convolution_fft([Rational(3, 4), Rational(5, 6)], [Rational(7, 8), Rational(1, 3), Rational(2, 5)]) == \ [Rational(21, 32), Rational(47, 48), Rational(26, 45), Rational(1, 3)] assert convolution_fft([Rational(1, 9), Rational(2, 3), Rational(3, 5)], [Rational(2, 5), Rational(3, 7), Rational(4, 9)]) == \ [Rational(2, 45), Rational(11, 35), Rational(8152, 14175), Rational(523, 945), Rational(4, 15)] assert convolution_fft([pi, E, sqrt(2)], [sqrt(3), 1/pi, 1/E]) == \ [sqrt(3)*pi, 1 + sqrt(3)*E, E/pi + pi*exp(-1) + sqrt(6), sqrt(2)/pi + 1, sqrt(2)*exp(-1)] assert convolution_fft([2321, 33123], [5321, 6321, 71323]) == \ [12350041, 190918524, 374911166, 2362431729] assert convolution_fft([312313, 31278232], [32139631, 319631]) == \ [10037624576503, 1005370659728895, 9997492572392] raises(TypeError, lambda: convolution_fft(x, y)) raises(ValueError, lambda: convolution_fft([x, y], [y, x])) def test_convolution_ntt(): # prime moduli of the form (m*2**k + 1), sequence length # should be a divisor of 2**k p = 7*17*2**23 + 1 q = 19*2**10 + 1 r = 2*500000003 + 1 # only for sequences of length 1 or 2 # s = 2*3*5*7 # composite modulus assert all(convolution_ntt([], x, prime=y) == [] for x in ([], [1]) for y in (p, q, r)) assert convolution_ntt([2], [3], r) == [6] assert convolution_ntt([2, 3], [4], r) == [8, 12] assert convolution_ntt([32121, 42144, 4214, 4241], [32132, 3232, 87242], p) == [33867619, 459741727, 79180879, 831885249, 381344700, 369993322] assert convolution_ntt([121913, 3171831, 31888131, 12], [17882, 21292, 29921, 312], q) == \ [8158, 3065, 3682, 7090, 1239, 2232, 3744] assert convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], p) == \ convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], q) assert convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], p) == \ convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], q) raises(ValueError, lambda: convolution_ntt([2, 3], [4, 5], r)) raises(ValueError, lambda: convolution_ntt([x, y], [y, x], q)) raises(TypeError, lambda: convolution_ntt(x, y, p)) def test_convolution_fwht(): assert convolution_fwht([], []) == [] assert convolution_fwht([], [1]) == [] assert convolution_fwht([1, 2, 3], [4, 5, 6]) == [32, 13, 18, 27] assert convolution_fwht([Rational(5, 7), Rational(6, 8), Rational(7, 3)], [2, 4, Rational(6, 7)]) == \ [Rational(45, 7), Rational(61, 14), Rational(776, 147), Rational(419, 42)] a = [1, Rational(5, 3), sqrt(3), Rational(7, 5), 4 + 5*I] b = [94, 51, 53, 45, 31, 27, 13] c = [3 + 4*I, 5 + 7*I, 3, Rational(7, 6), 8] assert convolution_fwht(a, b) == [53*sqrt(3) + 366 + 155*I, 45*sqrt(3) + Rational(5848, 15) + 135*I, 94*sqrt(3) + Rational(1257, 5) + 65*I, 51*sqrt(3) + Rational(3974, 15), 13*sqrt(3) + 452 + 470*I, Rational(4513, 15) + 255*I, 31*sqrt(3) + Rational(1314, 5) + 265*I, 27*sqrt(3) + Rational(3676, 15) + 225*I] assert convolution_fwht(b, c) == [Rational(1993, 2) + 733*I, Rational(6215, 6) + 862*I, Rational(1659, 2) + 527*I, Rational(1988, 3) + 551*I, 1019 + 313*I, Rational(3955, 6) + 325*I, Rational(1175, 2) + 52*I, Rational(3253, 6) + 91*I] assert convolution_fwht(a[3:], c) == [Rational(-54, 5) + I*Rational(293, 5), -1 + I*Rational(204, 5), Rational(133, 15) + I*Rational(35, 6), Rational(409, 30) + 15*I, Rational(56, 5), 32 + 40*I, 0, 0] u, v, w, x, y, z = symbols('u v w x y z') assert convolution_fwht([u, v], [x, y]) == [u*x + v*y, u*y + v*x] assert convolution_fwht([u, v, w], [x, y]) == \ [u*x + v*y, u*y + v*x, w*x, w*y] assert convolution_fwht([u, v, w], [x, y, z]) == \ [u*x + v*y + w*z, u*y + v*x, u*z + w*x, v*z + w*y] raises(TypeError, lambda: convolution_fwht(x, y)) raises(TypeError, lambda: convolution_fwht(x*y, u + v)) def test_convolution_subset(): assert convolution_subset([], []) == [] assert convolution_subset([], [Rational(1, 3)]) == [] assert convolution_subset([6 + I*Rational(3, 7)], [Rational(2, 3)]) == [4 + I*Rational(2, 7)] a = [1, Rational(5, 3), sqrt(3), 4 + 5*I] b = [64, 71, 55, 47, 33, 29, 15] c = [3 + I*Rational(2, 3), 5 + 7*I, 7, Rational(7, 5), 9] assert convolution_subset(a, b) == [64, Rational(533, 3), 55 + 64*sqrt(3), 71*sqrt(3) + Rational(1184, 3) + 320*I, 33, 84, 15 + 33*sqrt(3), 29*sqrt(3) + 157 + 165*I] assert convolution_subset(b, c) == [192 + I*Rational(128, 3), 533 + I*Rational(1486, 3), 613 + I*Rational(110, 3), Rational(5013, 5) + I*Rational(1249, 3), 675 + 22*I, 891 + I*Rational(751, 3), 771 + 10*I, Rational(3736, 5) + 105*I] assert convolution_subset(a, c) == convolution_subset(c, a) assert convolution_subset(a[:2], b) == \ [64, Rational(533, 3), 55, Rational(416, 3), 33, 84, 15, 25] assert convolution_subset(a[:2], c) == \ [3 + I*Rational(2, 3), 10 + I*Rational(73, 9), 7, Rational(196, 15), 9, 15, 0, 0] u, v, w, x, y, z = symbols('u v w x y z') assert convolution_subset([u, v, w], [x, y]) == [u*x, u*y + v*x, w*x, w*y] assert convolution_subset([u, v, w, x], [y, z]) == \ [u*y, u*z + v*y, w*y, w*z + x*y] assert convolution_subset([u, v], [x, y, z]) == \ convolution_subset([x, y, z], [u, v]) raises(TypeError, lambda: convolution_subset(x, z)) raises(TypeError, lambda: convolution_subset(Rational(7, 3), u)) def test_covering_product(): assert covering_product([], []) == [] assert covering_product([], [Rational(1, 3)]) == [] assert covering_product([6 + I*Rational(3, 7)], [Rational(2, 3)]) == [4 + I*Rational(2, 7)] a = [1, Rational(5, 8), sqrt(7), 4 + 9*I] b = [66, 81, 95, 49, 37, 89, 17] c = [3 + I*Rational(2, 3), 51 + 72*I, 7, Rational(7, 15), 91] assert covering_product(a, b) == [66, Rational(1383, 8), 95 + 161*sqrt(7), 130*sqrt(7) + 1303 + 2619*I, 37, Rational(671, 4), 17 + 54*sqrt(7), 89*sqrt(7) + Rational(4661, 8) + 1287*I] assert covering_product(b, c) == [198 + 44*I, 7740 + 10638*I, 1412 + I*Rational(190, 3), Rational(42684, 5) + I*Rational(31202, 3), 9484 + I*Rational(74, 3), 22163 + I*Rational(27394, 3), 10621 + I*Rational(34, 3), Rational(90236, 15) + 1224*I] assert covering_product(a, c) == covering_product(c, a) assert covering_product(b, c[:-1]) == [198 + 44*I, 7740 + 10638*I, 1412 + I*Rational(190, 3), Rational(42684, 5) + I*Rational(31202, 3), 111 + I*Rational(74, 3), 6693 + I*Rational(27394, 3), 429 + I*Rational(34, 3), Rational(23351, 15) + 1224*I] assert covering_product(a, c[:-1]) == [3 + I*Rational(2, 3), Rational(339, 4) + I*Rational(1409, 12), 7 + 10*sqrt(7) + 2*sqrt(7)*I/3, -403 + 772*sqrt(7)/15 + 72*sqrt(7)*I + I*Rational(12658, 15)] u, v, w, x, y, z = symbols('u v w x y z') assert covering_product([u, v, w], [x, y]) == \ [u*x, u*y + v*x + v*y, w*x, w*y] assert covering_product([u, v, w, x], [y, z]) == \ [u*y, u*z + v*y + v*z, w*y, w*z + x*y + x*z] assert covering_product([u, v], [x, y, z]) == \ covering_product([x, y, z], [u, v]) raises(TypeError, lambda: covering_product(x, z)) raises(TypeError, lambda: covering_product(Rational(7, 3), u)) def test_intersecting_product(): assert intersecting_product([], []) == [] assert intersecting_product([], [Rational(1, 3)]) == [] assert intersecting_product([6 + I*Rational(3, 7)], [Rational(2, 3)]) == [4 + I*Rational(2, 7)] a = [1, sqrt(5), Rational(3, 8) + 5*I, 4 + 7*I] b = [67, 51, 65, 48, 36, 79, 27] c = [3 + I*Rational(2, 5), 5 + 9*I, 7, Rational(7, 19), 13] assert intersecting_product(a, b) == [195*sqrt(5) + Rational(6979, 8) + 1886*I, 178*sqrt(5) + 520 + 910*I, Rational(841, 2) + 1344*I, 192 + 336*I, 0, 0, 0, 0] assert intersecting_product(b, c) == [Rational(128553, 19) + I*Rational(9521, 5), Rational(17820, 19) + 1602*I, Rational(19264, 19), Rational(336, 19), 1846, 0, 0, 0] assert intersecting_product(a, c) == intersecting_product(c, a) assert intersecting_product(b[1:], c[:-1]) == [Rational(64788, 19) + I*Rational(8622, 5), Rational(12804, 19) + 1152*I, Rational(11508, 19), Rational(252, 19), 0, 0, 0, 0] assert intersecting_product(a, c[:-2]) == \ [Rational(-99, 5) + 10*sqrt(5) + 2*sqrt(5)*I/5 + I*Rational(3021, 40), -43 + 5*sqrt(5) + 9*sqrt(5)*I + 71*I, Rational(245, 8) + 84*I, 0] u, v, w, x, y, z = symbols('u v w x y z') assert intersecting_product([u, v, w], [x, y]) == \ [u*x + u*y + v*x + w*x + w*y, v*y, 0, 0] assert intersecting_product([u, v, w, x], [y, z]) == \ [u*y + u*z + v*y + w*y + w*z + x*y, v*z + x*z, 0, 0] assert intersecting_product([u, v], [x, y, z]) == \ intersecting_product([x, y, z], [u, v]) raises(TypeError, lambda: intersecting_product(x, z)) raises(TypeError, lambda: intersecting_product(u, Rational(8, 3)))
b39644650dbada072704ba428c956678a953290072453401adcf8df69ff85bc7
from sympy.core.numbers import Rational from sympy.functions.combinatorial.numbers import fibonacci from sympy.core import S, symbols from sympy.testing.pytest import raises from sympy.discrete.recurrences import linrec def test_linrec(): assert linrec(coeffs=[1, 1], init=[1, 1], n=20) == 10946 assert linrec(coeffs=[1, 2, 3, 4, 5], init=[1, 1, 0, 2], n=10) == 1040 assert linrec(coeffs=[0, 0, 11, 13], init=[23, 27], n=25) == 59628567384 assert linrec(coeffs=[0, 0, 1, 1, 2], init=[1, 5, 3], n=15) == 165 assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=70) == \ 56889923441670659718376223533331214868804815612050381493741233489928913241 assert linrec(coeffs=[0]*55 + [1, 1, 2, 3], init=[0]*50 + [1, 2, 3], n=4000) == \ 702633573874937994980598979769135096432444135301118916539 assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**4) assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**5) assert all(linrec(coeffs=[1, 1], init=[0, 1], n=n) == fibonacci(n) for n in range(95, 115)) assert all(linrec(coeffs=[1, 1], init=[1, 1], n=n) == fibonacci(n + 1) for n in range(595, 615)) a = [S.Half, Rational(3, 4), Rational(5, 6), 7, Rational(8, 9), Rational(3, 5)] b = [1, 2, 8, Rational(5, 7), Rational(3, 7), Rational(2, 9), 6] x, y, z = symbols('x y z') assert linrec(coeffs=a[:5], init=b[:4], n=80) == \ Rational(1726244235456268979436592226626304376013002142588105090705187189, 1960143456748895967474334873705475211264) assert linrec(coeffs=a[:4], init=b[:4], n=50) == \ Rational(368949940033050147080268092104304441, 504857282956046106624) assert linrec(coeffs=a[3:], init=b[:3], n=35) == \ Rational(97409272177295731943657945116791049305244422833125109, 814315512679031689453125) assert linrec(coeffs=[0]*60 + [Rational(2, 3), Rational(4, 5)], init=b, n=3000) == \ Rational(26777668739896791448594650497024, 48084516708184142230517578125) raises(TypeError, lambda: linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4, 5], n=1)) raises(TypeError, lambda: linrec(coeffs=a[:4], init=b[:5], n=10000)) raises(ValueError, lambda: linrec(coeffs=a[:4], init=b[:4], n=-10000)) raises(TypeError, lambda: linrec(x, b, n=10000)) raises(TypeError, lambda: linrec(a, y, n=10000)) assert linrec(coeffs=[x, y, z], init=[1, 1, 1], n=4) == \ x**2 + x*y + x*z + y + z assert linrec(coeffs=[1, 2, 1], init=[x, y, z], n=20) == \ 269542*x + 664575*y + 578949*z assert linrec(coeffs=[0, 3, 1, 2], init=[x, y], n=30) == \ 58516436*x + 56372788*y assert linrec(coeffs=[0]*50 + [1, 2, 3], init=[x, y, z], n=1000) == \ 11477135884896*x + 25999077948732*y + 41975630244216*z assert linrec(coeffs=[], init=[1, 1], n=20) == 0 assert linrec(coeffs=[x, y, z], init=[1, 2, 3], n=2) == 3
a5f37df9cd18d360af6ae30d6ca4d084f85321138538e51c49393f220eb17802
from sympy.functions.elementary.miscellaneous import sqrt from sympy.core import S, Symbol, symbols, I, Rational from sympy.discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform, inverse_mobius_transform) from sympy.testing.pytest import raises def test_fft_ifft(): assert all(tf(ls) == ls for tf in (fft, ifft) for ls in ([], [Rational(5, 3)])) ls = list(range(6)) fls = [15, -7*sqrt(2)/2 - 4 - sqrt(2)*I/2 + 2*I, 2 + 3*I, -4 + 7*sqrt(2)/2 - 2*I - sqrt(2)*I/2, -3, -4 + 7*sqrt(2)/2 + sqrt(2)*I/2 + 2*I, 2 - 3*I, -7*sqrt(2)/2 - 4 - 2*I + sqrt(2)*I/2] assert fft(ls) == fls assert ifft(fls) == ls + [S.Zero]*2 ls = [1 + 2*I, 3 + 4*I, 5 + 6*I] ifls = [Rational(9, 4) + 3*I, I*Rational(-7, 4), Rational(3, 4) + I, -2 - I/4] assert ifft(ls) == ifls assert fft(ifls) == ls + [S.Zero] x = Symbol('x', real=True) raises(TypeError, lambda: fft(x)) raises(ValueError, lambda: ifft([x, 2*x, 3*x**2, 4*x**3])) def test_ntt_intt(): # prime moduli of the form (m*2**k + 1), sequence length # should be a divisor of 2**k p = 7*17*2**23 + 1 q = 2*500000003 + 1 # only for sequences of length 1 or 2 r = 2*3*5*7 # composite modulus assert all(tf(ls, p) == ls for tf in (ntt, intt) for ls in ([], [5])) ls = list(range(6)) nls = [15, 801133602, 738493201, 334102277, 998244350, 849020224, 259751156, 12232587] assert ntt(ls, p) == nls assert intt(nls, p) == ls + [0]*2 ls = [1 + 2*I, 3 + 4*I, 5 + 6*I] x = Symbol('x', integer=True) raises(TypeError, lambda: ntt(x, p)) raises(ValueError, lambda: intt([x, 2*x, 3*x**2, 4*x**3], p)) raises(ValueError, lambda: intt(ls, p)) raises(ValueError, lambda: ntt([1.2, 2.1, 3.5], p)) raises(ValueError, lambda: ntt([3, 5, 6], q)) raises(ValueError, lambda: ntt([4, 5, 7], r)) raises(ValueError, lambda: ntt([1.0, 2.0, 3.0], p)) def test_fwht_ifwht(): assert all(tf(ls) == ls for tf in (fwht, ifwht) \ for ls in ([], [Rational(7, 4)])) ls = [213, 321, 43235, 5325, 312, 53] fls = [49459, 38061, -47661, -37759, 48729, 37543, -48391, -38277] assert fwht(ls) == fls assert ifwht(fls) == ls + [S.Zero]*2 ls = [S.Half + 2*I, Rational(3, 7) + 4*I, Rational(5, 6) + 6*I, Rational(7, 3), Rational(9, 4)] ifls = [Rational(533, 672) + I*Rational(3, 2), Rational(23, 224) + I/2, Rational(1, 672), Rational(107, 224) - I, Rational(155, 672) + I*Rational(3, 2), Rational(-103, 224) + I/2, Rational(-377, 672), Rational(-19, 224) - I] assert ifwht(ls) == ifls assert fwht(ifls) == ls + [S.Zero]*3 x, y = symbols('x y') raises(TypeError, lambda: fwht(x)) ls = [x, 2*x, 3*x**2, 4*x**3] ifls = [x**3 + 3*x**2/4 + x*Rational(3, 4), -x**3 + 3*x**2/4 - x/4, -x**3 - 3*x**2/4 + x*Rational(3, 4), x**3 - 3*x**2/4 - x/4] assert ifwht(ls) == ifls assert fwht(ifls) == ls ls = [x, y, x**2, y**2, x*y] fls = [x**2 + x*y + x + y**2 + y, x**2 + x*y + x - y**2 - y, -x**2 + x*y + x - y**2 + y, -x**2 + x*y + x + y**2 - y, x**2 - x*y + x + y**2 + y, x**2 - x*y + x - y**2 - y, -x**2 - x*y + x - y**2 + y, -x**2 - x*y + x + y**2 - y] assert fwht(ls) == fls assert ifwht(fls) == ls + [S.Zero]*3 ls = list(range(6)) assert fwht(ls) == [x*8 for x in ifwht(ls)] def test_mobius_transform(): assert all(tf(ls, subset=subset) == ls for ls in ([], [Rational(7, 4)]) for subset in (True, False) for tf in (mobius_transform, inverse_mobius_transform)) w, x, y, z = symbols('w x y z') assert mobius_transform([x, y]) == [x, x + y] assert inverse_mobius_transform([x, x + y]) == [x, y] assert mobius_transform([x, y], subset=False) == [x + y, y] assert inverse_mobius_transform([x + y, y], subset=False) == [x, y] assert mobius_transform([w, x, y, z]) == [w, w + x, w + y, w + x + y + z] assert inverse_mobius_transform([w, w + x, w + y, w + x + y + z]) == \ [w, x, y, z] assert mobius_transform([w, x, y, z], subset=False) == \ [w + x + y + z, x + z, y + z, z] assert inverse_mobius_transform([w + x + y + z, x + z, y + z, z], subset=False) == \ [w, x, y, z] ls = [Rational(2, 3), Rational(6, 7), Rational(5, 8), 9, Rational(5, 3) + 7*I] mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168), Rational(7, 3) + 7*I, Rational(67, 21) + 7*I, Rational(71, 24) + 7*I, Rational(2153, 168) + 7*I] assert mobius_transform(ls) == mls assert inverse_mobius_transform(mls) == ls + [S.Zero]*3 mls = [Rational(2153, 168) + 7*I, Rational(69, 7), Rational(77, 8), 9, Rational(5, 3) + 7*I, 0, 0, 0] assert mobius_transform(ls, subset=False) == mls assert inverse_mobius_transform(mls, subset=False) == ls + [S.Zero]*3 ls = ls[:-1] mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168)] assert mobius_transform(ls) == mls assert inverse_mobius_transform(mls) == ls mls = [Rational(1873, 168), Rational(69, 7), Rational(77, 8), 9] assert mobius_transform(ls, subset=False) == mls assert inverse_mobius_transform(mls, subset=False) == ls raises(TypeError, lambda: mobius_transform(x, subset=True)) raises(TypeError, lambda: inverse_mobius_transform(y, subset=False))
aab3b8a028eb8e4a75b83beb36d6e000d57268e131a8e2cdb48a48c43d6e1f45
from sympy.liealgebras.cartan_type import CartanType from sympy.matrices import Matrix def test_type_D(): c = CartanType("D4") m = Matrix(4, 4, [2, -1, 0, 0, -1, 2, -1, -1, 0, -1, 2, 0, 0, -1, 0, 2]) assert c.cartan_matrix() == m assert c.basis() == 6 assert c.lie_algebra() == "so(8)" assert c.roots() == 24 assert c.simple_root(3) == [0, 0, 1, -1] diag = " 3\n 0\n |\n |\n0---0---0\n1 2 4" assert diag == c.dynkin_diagram() assert c.positive_roots() == {1: [1, -1, 0, 0], 2: [1, 1, 0, 0], 3: [1, 0, -1, 0], 4: [1, 0, 1, 0], 5: [1, 0, 0, -1], 6: [1, 0, 0, 1], 7: [0, 1, -1, 0], 8: [0, 1, 1, 0], 9: [0, 1, 0, -1], 10: [0, 1, 0, 1], 11: [0, 0, 1, -1], 12: [0, 0, 1, 1]}
616a6db38a564a2604c11b22e432d0d7a2600bdd74f7ef4d29920bfc83bafc0c
from sympy.core.function import (Derivative as D, Function) from sympy.core.relational import Eq from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.testing.pytest import raises from sympy.calculus.euler import euler_equations as euler def test_euler_interface(): x = Function('x') y = Symbol('y') t = Symbol('t') raises(TypeError, lambda: euler()) raises(TypeError, lambda: euler(D(x(t), t)*y(t), [x(t), y])) raises(ValueError, lambda: euler(D(x(t), t)*x(y), [x(t), x(y)])) raises(TypeError, lambda: euler(D(x(t), t)**2, x(0))) raises(TypeError, lambda: euler(D(x(t), t)*y(t), [t])) assert euler(D(x(t), t)**2/2, {x(t)}) == [Eq(-D(x(t), t, t), 0)] assert euler(D(x(t), t)**2/2, x(t), {t}) == [Eq(-D(x(t), t, t), 0)] def test_euler_pendulum(): x = Function('x') t = Symbol('t') L = D(x(t), t)**2/2 + cos(x(t)) assert euler(L, x(t), t) == [Eq(-sin(x(t)) - D(x(t), t, t), 0)] def test_euler_henonheiles(): x = Function('x') y = Function('y') t = Symbol('t') L = sum(D(z(t), t)**2/2 - z(t)**2/2 for z in [x, y]) L += -x(t)**2*y(t) + y(t)**3/3 assert euler(L, [x(t), y(t)], t) == [Eq(-2*x(t)*y(t) - x(t) - D(x(t), t, t), 0), Eq(-x(t)**2 + y(t)**2 - y(t) - D(y(t), t, t), 0)] def test_euler_sineg(): psi = Function('psi') t = Symbol('t') x = Symbol('x') L = D(psi(t, x), t)**2/2 - D(psi(t, x), x)**2/2 + cos(psi(t, x)) assert euler(L, psi(t, x), [t, x]) == [Eq(-sin(psi(t, x)) - D(psi(t, x), t, t) + D(psi(t, x), x, x), 0)] def test_euler_high_order(): # an example from hep-th/0309038 m = Symbol('m') k = Symbol('k') x = Function('x') y = Function('y') t = Symbol('t') L = (m*D(x(t), t)**2/2 + m*D(y(t), t)**2/2 - k*D(x(t), t)*D(y(t), t, t) + k*D(y(t), t)*D(x(t), t, t)) assert euler(L, [x(t), y(t)]) == [Eq(2*k*D(y(t), t, t, t) - m*D(x(t), t, t), 0), Eq(-2*k*D(x(t), t, t, t) - m*D(y(t), t, t), 0)] w = Symbol('w') L = D(x(t, w), t, w)**2/2 assert euler(L) == [Eq(D(x(t, w), t, t, w, w), 0)] def test_issue_18653(): x, y, z = symbols("x y z") f, g, h = symbols("f g h", cls=Function, args=(x, y)) f, g, h = f(), g(), h() expr2 = f.diff(x)*h.diff(z) assert euler(expr2, (f,), (x, y)) == []
89b01000ac85650470a3feb13e738b7a44ce46d108a849dbbf379c785494943c
from sympy.core.numbers import (I, Rational, oo) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.calculus.singularities import ( singularities, is_increasing, is_strictly_increasing, is_decreasing, is_strictly_decreasing, is_monotonic ) from sympy.sets import Interval, FiniteSet from sympy.testing.pytest import raises from sympy.abc import x, y def test_singularities(): x = Symbol('x') assert singularities(x**2, x) == S.EmptySet assert singularities(x/(x**2 + 3*x + 2), x) == FiniteSet(-2, -1) assert singularities(1/(x**2 + 1), x) == FiniteSet(I, -I) assert singularities(x/(x**3 + 1), x) == \ FiniteSet(-1, (1 - sqrt(3) * I) / 2, (1 + sqrt(3) * I) / 2) assert singularities(1/(y**2 + 2*I*y + 1), y) == \ FiniteSet(-I + sqrt(2)*I, -I - sqrt(2)*I) x = Symbol('x', real=True) assert singularities(1/(x**2 + 1), x) == S.EmptySet assert singularities(exp(1/x), x, S.Reals) == FiniteSet(0) assert singularities(exp(1/x), x, Interval(1, 2)) == S.EmptySet assert singularities(log((x - 2)**2), x, Interval(1, 3)) == FiniteSet(2) raises(NotImplementedError, lambda: singularities(x**-oo, x)) def test_is_increasing(): """Test whether is_increasing returns correct value.""" a = Symbol('a', negative=True) assert is_increasing(x**3 - 3*x**2 + 4*x, S.Reals) assert is_increasing(-x**2, Interval(-oo, 0)) assert not is_increasing(-x**2, Interval(0, oo)) assert not is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) assert is_increasing(x**2 + y, Interval(1, oo), x) assert is_increasing(-x**2*a, Interval(1, oo), x) assert is_increasing(1) assert is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) is False def test_is_strictly_increasing(): """Test whether is_strictly_increasing returns correct value.""" assert is_strictly_increasing( 4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2)) assert is_strictly_increasing( 4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo)) assert not is_strictly_increasing( 4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) assert not is_strictly_increasing(-x**2, Interval(0, oo)) assert not is_strictly_decreasing(1) assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) is False def test_is_decreasing(): """Test whether is_decreasing returns correct value.""" b = Symbol('b', positive=True) assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3)) assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) assert not is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2))) assert not is_decreasing(-x**2, Interval(-oo, 0)) assert not is_decreasing(-x**2*b, Interval(-oo, 0), x) def test_is_strictly_decreasing(): """Test whether is_strictly_decreasing returns correct value.""" assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) assert not is_strictly_decreasing( 1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2))) assert not is_strictly_decreasing(-x**2, Interval(-oo, 0)) assert not is_strictly_decreasing(1) assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3)) def test_is_monotonic(): """Test whether is_monotonic returns correct value.""" assert is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3)) assert is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo)) assert is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals) assert not is_monotonic(-x**2, S.Reals) assert is_monotonic(x**2 + y + 1, Interval(1, 2), x) raises(NotImplementedError, lambda: is_monotonic(x**2 + y + 1))
55134d7ddbbdd5081aa8866e0f532d97f6a60c3413d05250ed6832597ac74f06
from sympy.core.numbers import (E, I, Rational, oo, pi, zoo) 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 (Max, Min, 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, AccumBounds, is_convex, stationary_points, minimum, maximum) from sympy.core import Add, Mul, Pow from sympy.core.expr import unchanged from sympy.sets.sets import (Interval, FiniteSet, Complement, Union) from sympy.testing.pytest import raises, _both_exp_pow, XFAIL from sympy.abc import x a = Symbol('a', real=True) B = AccumBounds 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(0, oo)) == True assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False assert is_convex(x**2, x, domain=Interval(0, oo)) == True assert is_convex(log(x), x) == False raises(NotImplementedError, lambda: is_convex(log(x), x, a)) def test_stationary_points(): x, y = symbols('x y') assert stationary_points(sin(x), x, Interval(-pi/2, pi/2) ) == {-pi/2, pi/2} assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4) ) 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_AccumBounds(): assert B(1, 2).args == (1, 2) assert B(1, 2).delta is S.One assert B(1, 2).mid == Rational(3, 2) assert B(1, 3).is_real == True assert B(1, 1) is S.One assert B(1, 2) + 1 == B(2, 3) assert 1 + B(1, 2) == B(2, 3) assert B(1, 2) + B(2, 3) == B(3, 5) assert -B(1, 2) == B(-2, -1) assert B(1, 2) - 1 == B(0, 1) assert 1 - B(1, 2) == B(-1, 0) assert B(2, 3) - B(1, 2) == B(0, 2) assert x + B(1, 2) == Add(B(1, 2), x) assert a + B(1, 2) == B(1 + a, 2 + a) assert B(1, 2) - x == Add(B(1, 2), -x) assert B(-oo, 1) + oo == B(-oo, oo) assert B(1, oo) + oo is oo assert B(1, oo) - oo == B(-oo, oo) assert (-oo - B(-1, oo)) is -oo assert B(-oo, 1) - oo is -oo assert B(1, oo) - oo == B(-oo, oo) assert B(-oo, 1) - (-oo) == B(-oo, oo) assert (oo - B(1, oo)) == B(-oo, oo) assert (-oo - B(1, oo)) is -oo assert B(1, 2)/2 == B(S.Half, 1) assert 2/B(2, 3) == B(Rational(2, 3), 1) assert 1/B(-1, 1) == B(-oo, oo) assert abs(B(1, 2)) == B(1, 2) assert abs(B(-2, -1)) == B(1, 2) assert abs(B(-2, 1)) == B(0, 2) assert abs(B(-1, 2)) == B(0, 2) c = Symbol('c') raises(ValueError, lambda: B(0, c)) raises(ValueError, lambda: B(1, -1)) r = Symbol('r', real=True) raises(ValueError, lambda: B(r, r - 1)) def test_AccumBounds_mul(): assert B(1, 2)*2 == B(2, 4) assert 2*B(1, 2) == B(2, 4) assert B(1, 2)*B(2, 3) == B(2, 6) assert B(0, 2)*B(2, oo) == B(0, oo) l, r = B(-oo, oo), B(-a, a) assert l*r == B(-oo, oo) assert r*l == B(-oo, oo) l, r = B(1, oo), B(-3, -2) assert l*r == B(-oo, -2) assert r*l == B(-oo, -2) assert B(1, 2)*0 == 0 assert B(1, oo)*0 == B(0, oo) assert B(-oo, 1)*0 == B(-oo, 0) assert B(-oo, oo)*0 == B(-oo, oo) assert B(1, 2)*x == Mul(B(1, 2), x, evaluate=False) assert B(0, 2)*oo == B(0, oo) assert B(-2, 0)*oo == B(-oo, 0) assert B(0, 2)*(-oo) == B(-oo, 0) assert B(-2, 0)*(-oo) == B(0, oo) assert B(-1, 1)*oo == B(-oo, oo) assert B(-1, 1)*(-oo) == B(-oo, oo) assert B(-oo, oo)*oo == B(-oo, oo) def test_AccumBounds_div(): assert B(-1, 3)/B(3, 4) == B(Rational(-1, 3), 1) assert B(-2, 4)/B(-3, 4) == B(-oo, oo) assert B(-3, -2)/B(-4, 0) == B(S.Half, oo) # these two tests can have a better answer # after Union of B is improved assert B(-3, -2)/B(-2, 1) == B(-oo, oo) assert B(2, 3)/B(-2, 2) == B(-oo, oo) assert B(-3, -2)/B(0, 4) == B(-oo, Rational(-1, 2)) assert B(2, 4)/B(-3, 0) == B(-oo, Rational(-2, 3)) assert B(2, 4)/B(0, 3) == B(Rational(2, 3), oo) assert B(0, 1)/B(0, 1) == B(0, oo) assert B(-1, 0)/B(0, 1) == B(-oo, 0) assert B(-1, 2)/B(-2, 2) == B(-oo, oo) assert 1/B(-1, 2) == B(-oo, oo) assert 1/B(0, 2) == B(S.Half, oo) assert (-1)/B(0, 2) == B(-oo, Rational(-1, 2)) assert 1/B(-oo, 0) == B(-oo, 0) assert 1/B(-1, 0) == B(-oo, -1) assert (-2)/B(-oo, 0) == B(0, oo) assert 1/B(-oo, -1) == B(-1, 0) assert B(1, 2)/a == Mul(B(1, 2), 1/a, evaluate=False) assert B(1, 2)/0 == B(1, 2)*zoo assert B(1, oo)/oo == B(0, oo) assert B(1, oo)/(-oo) == B(-oo, 0) assert B(-oo, -1)/oo == B(-oo, 0) assert B(-oo, -1)/(-oo) == B(0, oo) assert B(-oo, oo)/oo == B(-oo, oo) assert B(-oo, oo)/(-oo) == B(-oo, oo) assert B(-1, oo)/oo == B(0, oo) assert B(-1, oo)/(-oo) == B(-oo, 0) assert B(-oo, 1)/oo == B(-oo, 0) assert B(-oo, 1)/(-oo) == B(0, oo) def test_issue_18795(): r = Symbol('r', real=True) a = B(-1,1) c = B(7, oo) b = B(-oo, oo) assert c - tan(r) == B(7-tan(r), oo) assert b + tan(r) == B(-oo, oo) assert (a + r)/a == B(-oo, oo)*B(r - 1, r + 1) assert (b + a)/a == B(-oo, oo) def test_AccumBounds_func(): assert (x**2 + 2*x + 1).subs(x, B(-1, 1)) == B(-1, 4) assert exp(B(0, 1)) == B(1, E) assert exp(B(-oo, oo)) == B(0, oo) assert log(B(3, 6)) == B(log(3), log(6)) @XFAIL def test_AccumBounds_powf(): nn = Symbol('nn', nonnegative=True) assert B(1 + nn, 2 + nn)**B(1, 2) == B(1 + nn, (2 + nn)**2) i = Symbol('i', integer=True, negative=True) assert B(1, 2)**i == B(2**i, 1) def test_AccumBounds_pow(): assert B(0, 2)**2 == B(0, 4) assert B(-1, 1)**2 == B(0, 1) assert B(1, 2)**2 == B(1, 4) assert B(-1, 2)**3 == B(-1, 8) assert B(-1, 1)**0 == 1 assert B(1, 2)**Rational(5, 2) == B(1, 4*sqrt(2)) assert B(0, 2)**S.Half == B(0, sqrt(2)) neg = Symbol('neg', negative=True) assert unchanged(Pow, B(neg, 1), S.Half) nn = Symbol('nn', nonnegative=True) assert B(nn, nn + 1)**S.Half == B(sqrt(nn), sqrt(nn + 1)) assert B(nn, nn + 1)**nn == B(nn**nn, (nn + 1)**nn) assert unchanged(Pow, B(nn, nn + 1), x) i = Symbol('i', integer=True) assert B(1, 2)**i == B(Min(1, 2**i), Max(1, 2**i)) i = Symbol('i', integer=True, nonnegative=True) assert B(1, 2)**i == B(1, 2**i) assert B(0, 1)**i == B(0**i, 1) assert B(1, 5)**(-2) == B(Rational(1, 25), 1) assert B(-1, 3)**(-2) == B(0, oo) assert B(0, 2)**(-3) == B(Rational(1, 8), oo) assert B(-2, 0)**(-3) == B(-oo, -Rational(1, 8)) assert B(0, 2)**(-2) == B(Rational(1, 4), oo) assert B(-1, 2)**(-3) == B(-oo, oo) assert B(-3, -2)**(-3) == B(Rational(-1, 8), Rational(-1, 27)) assert B(-3, -2)**(-2) == B(Rational(1, 9), Rational(1, 4)) assert B(0, oo)**S.Half == B(0, oo) assert B(-oo, 0)**(-2) == B(0, oo) assert B(-2, 0)**(-2) == B(Rational(1, 4), oo) assert B(Rational(1, 3), S.Half)**oo is S.Zero assert B(0, S.Half)**oo is S.Zero assert B(S.Half, 1)**oo == B(0, oo) assert B(0, 1)**oo == B(0, oo) assert B(2, 3)**oo is oo assert B(1, 2)**oo == B(0, oo) assert B(S.Half, 3)**oo == B(0, oo) assert B(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero assert B(-1, Rational(-1, 2))**oo is S.NaN assert B(-3, -2)**oo is zoo assert B(-2, -1)**oo is S.NaN assert B(-2, Rational(-1, 2))**oo is S.NaN assert B(Rational(-1, 2), S.Half)**oo is S.Zero assert B(Rational(-1, 2), 1)**oo == B(0, oo) assert B(Rational(-2, 3), 2)**oo == B(0, oo) assert B(-1, 1)**oo == B(-oo, oo) assert B(-1, S.Half)**oo == B(-oo, oo) assert B(-1, 2)**oo == B(-oo, oo) assert B(-2, S.Half)**oo == B(-oo, oo) assert B(1, 2)**x == Pow(B(1, 2), x, evaluate=False) assert B(2, 3)**(-oo) is S.Zero assert B(0, 2)**(-oo) == B(0, oo) assert B(-1, 2)**(-oo) == B(-oo, oo) assert (tan(x)**sin(2*x)).subs(x, B(0, pi/2)) == \ Pow(B(-oo, oo), B(0, 1)) def test_AccumBounds_exponent(): # base is 0 z = 0**B(a, a + S.Half) assert z.subs(a, 0) == B(0, 1) assert z.subs(a, 1) == 0 p = z.subs(a, -1) assert p.is_Pow and p.args == (0, B(-1, -S.Half)) # base > 0 # when base is 1 the type of bounds does not matter assert 1**B(a, a + 1) == 1 # otherwise we need to know if 0 is in the bounds assert S.Half**B(-2, 2) == B(S(1)/4, 4) assert 2**B(-2, 2) == B(S(1)/4, 4) # +eps may introduce +oo # if there is a negative integer exponent assert B(0, 1)**B(S(1)/2, 1) == B(0, 1) assert B(0, 1)**B(0, 1) == B(0, 1) # positive bases have positive bounds assert B(2, 3)**B(-3, -2) == B(S(1)/27, S(1)/4) assert B(2, 3)**B(-3, 2) == B(S(1)/27, 9) # bounds generating imaginary parts unevaluated assert unchanged(Pow, B(-1, 1), B(1, 2)) assert B(0, S(1)/2)**B(1, oo) == B(0, S(1)/2) assert B(0, 1)**B(1, oo) == B(0, oo) assert B(0, 2)**B(1, oo) == B(0, oo) assert B(0, oo)**B(1, oo) == B(0, oo) assert B(S(1)/2, 1)**B(1, oo) == B(0, oo) assert B(S(1)/2, 1)**B(-oo, -1) == B(0, oo) assert B(S(1)/2, 1)**B(-oo, oo) == B(0, oo) assert B(S(1)/2, 2)**B(1, oo) == B(0, oo) assert B(S(1)/2, 2)**B(-oo, -1) == B(0, oo) assert B(S(1)/2, 2)**B(-oo, oo) == B(0, oo) assert B(S(1)/2, oo)**B(1, oo) == B(0, oo) assert B(S(1)/2, oo)**B(-oo, -1) == B(0, oo) assert B(S(1)/2, oo)**B(-oo, oo) == B(0, oo) assert B(1, 2)**B(1, oo) == B(0, oo) assert B(1, 2)**B(-oo, -1) == B(0, oo) assert B(1, 2)**B(-oo, oo) == B(0, oo) assert B(1, oo)**B(1, oo) == B(0, oo) assert B(1, oo)**B(-oo, -1) == B(0, oo) assert B(1, oo)**B(-oo, oo) == B(0, oo) assert B(2, oo)**B(1, oo) == B(2, oo) assert B(2, oo)**B(-oo, -1) == B(0, S(1)/2) assert B(2, oo)**B(-oo, oo) == B(0, oo) def test_comparison_AccumBounds(): assert (B(1, 3) < 4) == S.true assert (B(1, 3) < -1) == S.false assert (B(1, 3) < 2).rel_op == '<' assert (B(1, 3) <= 2).rel_op == '<=' assert (B(1, 3) > 4) == S.false assert (B(1, 3) > -1) == S.true assert (B(1, 3) > 2).rel_op == '>' assert (B(1, 3) >= 2).rel_op == '>=' assert (B(1, 3) < B(4, 6)) == S.true assert (B(1, 3) < B(2, 4)).rel_op == '<' assert (B(1, 3) < B(-2, 0)) == S.false assert (B(1, 3) <= B(4, 6)) == S.true assert (B(1, 3) <= B(-2, 0)) == S.false assert (B(1, 3) > B(4, 6)) == S.false assert (B(1, 3) > B(-2, 0)) == S.true assert (B(1, 3) >= B(4, 6)) == S.false assert (B(1, 3) >= B(-2, 0)) == S.true # issue 13499 assert (cos(x) > 0).subs(x, oo) == (B(-1, 1) > 0) c = Symbol('c') raises(TypeError, lambda: (B(0, 1) < c)) raises(TypeError, lambda: (B(0, 1) <= c)) raises(TypeError, lambda: (B(0, 1) > c)) raises(TypeError, lambda: (B(0, 1) >= c)) def test_contains_AccumBounds(): assert (1 in B(1, 2)) == S.true raises(TypeError, lambda: a in B(1, 2)) assert 0 in B(-1, 0) raises(TypeError, lambda: (cos(1)**2 + sin(1)**2 - 1) in B(-1, 0)) assert (-oo in B(1, oo)) == S.true assert (oo in B(-oo, 0)) == S.true # issue 13159 assert Mul(0, B(-1, 1)) == Mul(B(-1, 1), 0) == 0 import itertools for perm in itertools.permutations([0, B(-1, 1), x]): assert Mul(*perm) == 0 def test_intersection_AccumBounds(): assert B(0, 3).intersection(B(1, 2)) == B(1, 2) assert B(0, 3).intersection(B(1, 4)) == B(1, 3) assert B(0, 3).intersection(B(-1, 2)) == B(0, 2) assert B(0, 3).intersection(B(-1, 4)) == B(0, 3) assert B(0, 1).intersection(B(2, 3)) == S.EmptySet raises(TypeError, lambda: B(0, 3).intersection(1)) def test_union_AccumBounds(): assert B(0, 3).union(B(1, 2)) == B(0, 3) assert B(0, 3).union(B(1, 4)) == B(0, 4) assert B(0, 3).union(B(-1, 2)) == B(-1, 3) assert B(0, 3).union(B(-1, 4)) == B(-1, 4) raises(TypeError, lambda: B(0, 3).union(1)) def test_issue_16469(): x = Symbol("x", real=True) f = abs(x) assert function_range(f, x, S.Reals) == Interval(0, oo, False, True) @_both_exp_pow def test_issue_18747(): assert periodicity(exp(pi*I*(x/4+S.Half/2)), x) == 8
525b1c291f2c25d0a0eb1709b513e680c6adcfaff5a3e895e311dcc10b1732b7
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, ignore_warnings from sympy.utilities.exceptions import SymPyDeprecationWarning def test_apply_finite_diff(): x, h = symbols('x h') f = Function('f') assert (apply_finite_diff(1, [x-h, x+h], [f(x-h), f(x+h)], x) - (f(x+h)-f(x-h))/(2*h)).simplify() == 0 assert (apply_finite_diff(1, [5, 6, 7], [f(5), f(6), f(7)], 5) - (Rational(-3, 2)*f(5) + 2*f(6) - S.Half*f(7))).simplify() == 0 raises(ValueError, lambda: apply_finite_diff(1, [x, h], [f(x)])) def test_finite_diff_weights(): d = finite_diff_weights(1, [5, 6, 7], 5) assert d[1][2] == [Rational(-3, 2), 2, Rational(-1, 2)] # Table 1, p. 702 in doi:10.1090/S0025-5718-1988-0935077-0 # -------------------------------------------------------- xl = [0, 1, -1, 2, -2, 3, -3, 4, -4] # d holds all coefficients d = finite_diff_weights(4, xl, S.Zero) # Zeroeth derivative for i in range(5): assert d[0][i] == [S.One] + [S.Zero]*8 # First derivative assert d[1][0] == [S.Zero]*9 assert d[1][2] == [S.Zero, S.Half, Rational(-1, 2)] + [S.Zero]*6 assert d[1][4] == [S.Zero, Rational(2, 3), Rational(-2, 3), Rational(-1, 12), Rational(1, 12)] + [S.Zero]*4 assert d[1][6] == [S.Zero, Rational(3, 4), Rational(-3, 4), Rational(-3, 20), Rational(3, 20), Rational(1, 60), Rational(-1, 60)] + [S.Zero]*2 assert d[1][8] == [S.Zero, Rational(4, 5), Rational(-4, 5), Rational(-1, 5), Rational(1, 5), Rational(4, 105), Rational(-4, 105), Rational(-1, 280), Rational(1, 280)] # Second derivative for i in range(2): assert d[2][i] == [S.Zero]*9 assert d[2][2] == [-S(2), S.One, S.One] + [S.Zero]*6 assert d[2][4] == [Rational(-5, 2), Rational(4, 3), Rational(4, 3), Rational(-1, 12), Rational(-1, 12)] + [S.Zero]*4 assert d[2][6] == [Rational(-49, 18), Rational(3, 2), Rational(3, 2), Rational(-3, 20), Rational(-3, 20), Rational(1, 90), Rational(1, 90)] + [S.Zero]*2 assert d[2][8] == [Rational(-205, 72), Rational(8, 5), Rational(8, 5), Rational(-1, 5), Rational(-1, 5), Rational(8, 315), Rational(8, 315), Rational(-1, 560), Rational(-1, 560)] # Third derivative for i in range(3): assert d[3][i] == [S.Zero]*9 assert d[3][4] == [S.Zero, -S.One, S.One, S.Half, Rational(-1, 2)] + [S.Zero]*4 assert d[3][6] == [S.Zero, Rational(-13, 8), Rational(13, 8), S.One, -S.One, Rational(-1, 8), Rational(1, 8)] + [S.Zero]*2 assert d[3][8] == [S.Zero, Rational(-61, 30), Rational(61, 30), Rational(169, 120), Rational(-169, 120), Rational(-3, 10), Rational(3, 10), Rational(7, 240), Rational(-7, 240)] # Fourth derivative for i in range(4): assert d[4][i] == [S.Zero]*9 assert d[4][4] == [S(6), -S(4), -S(4), S.One, S.One] + [S.Zero]*4 assert d[4][6] == [Rational(28, 3), Rational(-13, 2), Rational(-13, 2), S(2), S(2), Rational(-1, 6), Rational(-1, 6)] + [S.Zero]*2 assert d[4][8] == [Rational(91, 8), Rational(-122, 15), Rational(-122, 15), Rational(169, 60), Rational(169, 60), Rational(-2, 5), Rational(-2, 5), Rational(7, 240), Rational(7, 240)] # Table 2, p. 703 in doi:10.1090/S0025-5718-1988-0935077-0 # -------------------------------------------------------- xl = [[j/S(2) for j in list(range(-i*2+1, 0, 2))+list(range(1, i*2+1, 2))] for i in range(1, 5)] # d holds all coefficients d = [finite_diff_weights({0: 1, 1: 2, 2: 4, 3: 4}[i], xl[i], 0) for i in range(4)] # Zeroth derivative assert d[0][0][1] == [S.Half, S.Half] assert d[1][0][3] == [Rational(-1, 16), Rational(9, 16), Rational(9, 16), Rational(-1, 16)] assert d[2][0][5] == [Rational(3, 256), Rational(-25, 256), Rational(75, 128), Rational(75, 128), Rational(-25, 256), Rational(3, 256)] assert d[3][0][7] == [Rational(-5, 2048), Rational(49, 2048), Rational(-245, 2048), Rational(1225, 2048), Rational(1225, 2048), Rational(-245, 2048), Rational(49, 2048), Rational(-5, 2048)] # First derivative assert d[0][1][1] == [-S.One, S.One] assert d[1][1][3] == [Rational(1, 24), Rational(-9, 8), Rational(9, 8), Rational(-1, 24)] assert d[2][1][5] == [Rational(-3, 640), Rational(25, 384), Rational(-75, 64), Rational(75, 64), Rational(-25, 384), Rational(3, 640)] assert d[3][1][7] == [Rational(5, 7168), Rational(-49, 5120), Rational(245, 3072), Rational(-1225, 1024), Rational(1225, 1024), Rational(-245, 3072), Rational(49, 5120), Rational(-5, 7168)] # Reasonably the rest of the table is also correct... (testing of that # deemed excessive at the moment) raises(ValueError, lambda: finite_diff_weights(-1, [1, 2])) raises(ValueError, lambda: finite_diff_weights(1.2, [1, 2])) x = symbols('x') raises(ValueError, lambda: finite_diff_weights(x, [1, 2])) def test_as_finite_diff(): x = symbols('x') f = Function('f') dx = Function('dx') with warns_deprecated_sympy(): as_finite_diff(f(x).diff(x), [x-2, x-1, x, x+1, x+2]) # Use of undefined functions in ``points`` df_true = -f(x+dx(x)/2-dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) \ + f(x+dx(x)/2+dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) df_test = diff(f(x), x).as_finite_difference(points=dx(x), x0=x+dx(x)/2) assert (df_test - df_true).simplify() == 0 def test_differentiate_finite(): x, y, h = symbols('x y h') f = Function('f') with ignore_warnings(SymPyDeprecationWarning): res0 = differentiate_finite(f(x, y) + exp(42), x, y, evaluate=True) xm, xp, ym, yp = [v + sign*S.Half for v, sign in product([x, y], [-1, 1])] ref0 = f(xm, ym) + f(xp, yp) - f(xm, yp) - f(xp, ym) assert (res0 - ref0).simplify() == 0 g = Function('g') with ignore_warnings(SymPyDeprecationWarning): res1 = differentiate_finite(f(x)*g(x) + 42, x, evaluate=True) ref1 = (-f(x - S.Half) + f(x + S.Half))*g(x) + \ (-g(x - S.Half) + g(x + S.Half))*f(x) assert (res1 - ref1).simplify() == 0 res2 = differentiate_finite(f(x) + x**3 + 42, x, points=[x-1, x+1]) ref2 = (f(x + 1) + (x + 1)**3 - f(x - 1) - (x - 1)**3)/2 assert (res2 - ref2).simplify() == 0 raises(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
50ad84db083d10cc1d6b8570a73ca3deb997b3a9e2df71ea71bc9aa80c30eb0c
from sympy.sandbox.indexed_integrals import IndexedIntegral from sympy.core.symbol import symbols from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.tensor.indexed import (Idx, IndexedBase) def test_indexed_integrals(): A = IndexedBase('A') i, j = symbols('i j', integer=True) a1, a2 = symbols('a1:3', cls=Idx) assert isinstance(a1, Idx) assert IndexedIntegral(1, A[i]).doit() == A[i] assert IndexedIntegral(A[i], A[i]).doit() == A[i] ** 2 / 2 assert IndexedIntegral(A[j], A[i]).doit() == A[i] * A[j] assert IndexedIntegral(A[i] * A[j], A[i]).doit() == A[i] ** 2 * A[j] / 2 assert IndexedIntegral(sin(A[i]), A[i]).doit() == -cos(A[i]) assert IndexedIntegral(sin(A[j]), A[i]).doit() == sin(A[j]) * A[i] assert IndexedIntegral(1, A[a1]).doit() == A[a1] assert IndexedIntegral(A[a1], A[a1]).doit() == A[a1] ** 2 / 2 assert IndexedIntegral(A[a2], A[a1]).doit() == A[a1] * A[a2] assert IndexedIntegral(A[a1] * A[a2], A[a1]).doit() == A[a1] ** 2 * A[a2] / 2 assert IndexedIntegral(sin(A[a1]), A[a1]).doit() == -cos(A[a1]) assert IndexedIntegral(sin(A[a2]), A[a1]).doit() == sin(A[a2]) * A[a1]
34b2605fb0bfb6b462c658543cd9159d352af71987c4d2a7b00c3c2b22d78ab3
from sympy.core.singleton import S from sympy.strategies.rl import (rm_id, glom, flatten, unpack, sort, distribute, subs, rebuild) from sympy.core.basic import Basic def test_rm_id(): rmzeros = rm_id(lambda x: x == 0) assert rmzeros(Basic(0, 1)) == Basic(1) assert rmzeros(Basic(0, 0)) == Basic(0) assert rmzeros(Basic(2, 1)) == Basic(2, 1) def test_glom(): from sympy.core.add import Add from sympy.abc import x key = lambda x: x.as_coeff_Mul()[1] count = lambda x: x.as_coeff_Mul()[0] newargs = lambda cnt, arg: cnt * arg rl = glom(key, count, newargs) result = rl(Add(x, -x, 3*x, 2, 3, evaluate=False)) expected = Add(3*x, 5) assert set(result.args) == set(expected.args) def test_flatten(): assert flatten(Basic(1, 2, Basic(3, 4))) == Basic(1, 2, 3, 4) def test_unpack(): assert unpack(Basic(2)) == 2 assert unpack(Basic(2, 3)) == Basic(2, 3) def test_sort(): assert sort(str)(Basic(3,1,2)) == Basic(1,2,3) def test_distribute(): class T1(Basic): pass class T2(Basic): pass distribute_t12 = distribute(T1, T2) assert distribute_t12(T1(1, 2, T2(3, 4), 5)) == \ T2(T1(1, 2, 3, 5), T1(1, 2, 4, 5)) assert distribute_t12(T1(1, 2, 3)) == T1(1, 2, 3) def test_distribute_add_mul(): from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.symbol import symbols x, y = symbols('x, y') expr = Mul(2, Add(x, y), evaluate=False) expected = Add(Mul(2, x), Mul(2, y)) distribute_mul = distribute(Mul, Add) assert distribute_mul(expr) == expected def test_subs(): rl = subs(1, 2) assert rl(1) == 2 assert rl(3) == 3 def test_rebuild(): from sympy.core.add import Add expr = Basic.__new__(Add, S(1), S(2)) assert rebuild(expr) == 3
c86664ec223bce055730c1f7a1a0c8ca80f45fd00bc86a4cc2617aa9b8617dae
from sympy.strategies.tools import subs, typed from sympy.strategies.rl import rm_id from sympy.core.basic import Basic def test_subs(): from sympy.core.symbol import symbols a,b,c,d,e,f = symbols('a,b,c,d,e,f') mapping = {a: d, d: a, Basic(e): Basic(f)} expr = Basic(a, Basic(b, c), Basic(d, Basic(e))) result = Basic(d, Basic(b, c), Basic(a, Basic(f))) assert subs(mapping)(expr) == result def test_subs_empty(): assert subs({})(Basic(1, 2)) == Basic(1, 2) def test_typed(): class A(Basic): pass class B(Basic): pass rmzeros = rm_id(lambda x: x == 0) rmones = rm_id(lambda x: x == 1) remove_something = typed({A: rmzeros, B: rmones}) assert remove_something(A(0, 1)) == A(1) assert remove_something(B(0, 1)) == B(0)
81128a560a41e6830a7970af13c097f723321b5443799c4d152612532af3b6ce
from sympy.strategies.traverse import (top_down, bottom_up, sall, top_down_once, bottom_up_once, basic_fns) from sympy.strategies.rl import rebuild from sympy.strategies.util import expr_fns from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.abc import x, y, z def zero_symbols(expression): return S.Zero if isinstance(expression, Symbol) else expression def test_sall(): zero_onelevel = sall(zero_symbols) assert zero_onelevel(Basic(x, y, Basic(x, z))) == Basic(0, 0, Basic(x, z)) def test_bottom_up(): _test_global_traversal(bottom_up) _test_stop_on_non_basics(bottom_up) def test_top_down(): _test_global_traversal(top_down) _test_stop_on_non_basics(top_down) def _test_global_traversal(trav): zero_all_symbols = trav(zero_symbols) assert zero_all_symbols(Basic(x, y, Basic(x, z))) == \ Basic(0, 0, Basic(0, 0)) def _test_stop_on_non_basics(trav): def add_one_if_can(expr): try: return expr + 1 except TypeError: return expr expr = Basic(1, 'a', Basic(2, 'b')) expected = Basic(2, 'a', Basic(3, 'b')) rl = trav(add_one_if_can) assert rl(expr) == expected class Basic2(Basic): pass rl = lambda x: Basic2(*x.args) if isinstance(x, Basic) else x def test_top_down_once(): top_rl = top_down_once(rl) assert top_rl(Basic(1, 2, Basic(3, 4))) == Basic2(1, 2, Basic(3, 4)) def test_bottom_up_once(): bottom_rl = bottom_up_once(rl) assert bottom_rl(Basic(1, 2, Basic(3, 4))) == Basic(1, 2, Basic2(3, 4)) def test_expr_fns(): expr = x + y**3 e = bottom_up(lambda v: v + 1, expr_fns)(expr) b = bottom_up(lambda v: Basic.__new__(Add, v, S(1)), basic_fns)(expr) assert rebuild(b) == e
bd69ded27501a67139febad81c2fbd8c6373a4eed86f3ce9d9ab35626523f995
from sympy.core.singleton import S from sympy.strategies.core import (null_safe, exhaust, memoize, condition, chain, tryit, do_one, debug, switch, minimize) def test_null_safe(): def rl(expr): if expr == 1: return 2 safe_rl = null_safe(rl) assert rl(1) == safe_rl(1) assert rl(3) == None assert safe_rl(3) == 3 def posdec(x): if x > 0: return x-1 else: return x def test_exhaust(): sink = exhaust(posdec) assert sink(5) == 0 assert sink(10) == 0 def test_memoize(): rl = memoize(posdec) assert rl(5) == posdec(5) assert rl(5) == posdec(5) assert rl(-2) == posdec(-2) def test_condition(): rl = condition(lambda x: x%2 == 0, posdec) assert rl(5) == 5 assert rl(4) == 3 def test_chain(): rl = chain(posdec, posdec) assert rl(5) == 3 assert rl(1) == 0 def test_tryit(): def rl(expr): assert False safe_rl = tryit(rl, AssertionError) assert safe_rl(S(1)) == 1 def test_do_one(): rl = do_one(posdec, posdec) assert rl(5) == 4 rl1 = lambda x: 2 if x == 1 else x rl2 = lambda x: 3 if x == 2 else x rule = do_one(rl1, rl2) assert rule(1) == 2 assert rule(rule(1)) == 3 def test_debug(): from io import StringIO file = StringIO() rl = debug(posdec, file) rl(5) log = file.getvalue() file.close() assert posdec.__name__ in log assert '5' in log assert '4' in log def test_switch(): inc = lambda x: x + 1 dec = lambda x: x - 1 key = lambda x: x % 3 rl = switch(key, {0: inc, 1: dec}) assert rl(3) == 4 assert rl(4) == 3 assert rl(5) == 5 def test_minimize(): inc = lambda x: x + 1 dec = lambda x: x - 1 rl = minimize(inc, dec) assert rl(4) == 3 rl = minimize(inc, dec, objective=lambda x: -x) assert rl(4) == 5
9ecb5c7ced4f37c957b0c3164ba6fe1c07a200580f2b175e79870a4992d14484
from sympy.strategies.branch.tools import canon from sympy.core.basic import Basic def posdec(x): if isinstance(x, int) and x > 0: yield x-1 else: yield x def branch5(x): if isinstance(x, int): if 0 < x < 5: yield x-1 elif 5 < x < 10: yield x+1 elif x == 5: yield x+1 yield x-1 else: yield x def test_zero_ints(): expr = Basic(2, Basic(5, 3), 8) expected = {Basic(0, Basic(0, 0), 0)} brl = canon(posdec) assert set(brl(expr)) == expected def test_split5(): expr = Basic(2, Basic(5, 3), 8) expected = {Basic(0, Basic(0, 0), 10), Basic(0, Basic(10, 0), 10)} brl = canon(branch5) assert set(brl(expr)) == expected
17b086db9be06e0422451d9a66a61d0589d4ce4d317616e21671367ee69021ae
from sympy.core.basic import Basic from sympy.strategies.branch.traverse import top_down, sall from sympy.strategies.branch.core import do_one, identity def inc(x): if isinstance(x, int): yield x + 1 def test_top_down_easy(): expr = Basic(1, 2) expected = Basic(2, 3) brl = top_down(inc) assert set(brl(expr)) == {expected} def test_top_down_big_tree(): expr = Basic(1, Basic(2), Basic(3, Basic(4), 5)) expected = Basic(2, Basic(3), Basic(4, Basic(5), 6)) brl = top_down(inc) assert set(brl(expr)) == {expected} def test_top_down_harder_function(): def split5(x): if x == 5: yield x - 1 yield x + 1 expr = Basic(Basic(5, 6), 1) expected = {Basic(Basic(4, 6), 1), Basic(Basic(6, 6), 1)} brl = top_down(split5) assert set(brl(expr)) == expected def test_sall(): expr = Basic(1, 2) expected = Basic(2, 3) brl = sall(inc) assert list(brl(expr)) == [expected] expr = Basic(1, 2, Basic(3, 4)) expected = Basic(2, 3, Basic(3, 4)) brl = sall(do_one(inc, identity)) assert list(brl(expr)) == [expected]
fe48b2476c49db4ab4ab708f352fc54cd8e92c53eaa78cd951a05dbf173f3c60
import glob import os import shutil import subprocess import sys import tempfile import warnings from sysconfig import get_config_var, get_config_vars, get_path from .runners import ( CCompilerRunner, CppCompilerRunner, FortranCompilerRunner ) from .util import ( get_abspath, make_dirs, copy, Glob, ArbitraryDepthGlob, glob_at_depth, import_module_from_file, pyx_is_cplus, sha256_of_string, sha256_of_file, CompileError ) if os.name == 'posix': objext = '.o' elif os.name == 'nt': objext = '.obj' else: warnings.warn("Unknown os.name: {}".format(os.name)) objext = '.o' def compile_sources(files, Runner=None, destdir=None, cwd=None, keep_dir_struct=False, per_file_kwargs=None, **kwargs): """ Compile source code files to object files. Parameters ========== files : iterable of str Paths to source files, if ``cwd`` is given, the paths are taken as relative. Runner: CompilerRunner subclass (optional) Could be e.g. ``FortranCompilerRunner``. Will be inferred from filename extensions if missing. destdir: str Output directory, if cwd is given, the path is taken as relative. cwd: str Working directory. Specify to have compiler run in other directory. also used as root of relative paths. keep_dir_struct: bool Reproduce directory structure in `destdir`. default: ``False`` per_file_kwargs: dict Dict mapping instances in ``files`` to keyword arguments. \\*\\*kwargs: dict Default keyword arguments to pass to ``Runner``. """ _per_file_kwargs = {} if per_file_kwargs is not None: for k, v in per_file_kwargs.items(): if isinstance(k, Glob): for path in glob.glob(k.pathname): _per_file_kwargs[path] = v elif isinstance(k, ArbitraryDepthGlob): for path in glob_at_depth(k.filename, cwd): _per_file_kwargs[path] = v else: _per_file_kwargs[k] = v # Set up destination directory destdir = destdir or '.' if not os.path.isdir(destdir): if os.path.exists(destdir): raise OSError("{} is not a directory".format(destdir)) else: make_dirs(destdir) if cwd is None: cwd = '.' for f in files: copy(f, destdir, only_update=True, dest_is_dir=True) # Compile files and return list of paths to the objects dstpaths = [] for f in files: if keep_dir_struct: name, ext = os.path.splitext(f) else: name, ext = os.path.splitext(os.path.basename(f)) file_kwargs = kwargs.copy() file_kwargs.update(_per_file_kwargs.get(f, {})) dstpaths.append(src2obj(f, Runner, cwd=cwd, **file_kwargs)) return dstpaths def get_mixed_fort_c_linker(vendor=None, cplus=False, cwd=None): vendor = vendor or os.environ.get('SYMPY_COMPILER_VENDOR', 'gnu') if vendor.lower() == 'intel': if cplus: return (FortranCompilerRunner, {'flags': ['-nofor_main', '-cxxlib']}, vendor) else: return (FortranCompilerRunner, {'flags': ['-nofor_main']}, vendor) elif vendor.lower() == 'gnu' or 'llvm': if cplus: return (CppCompilerRunner, {'lib_options': ['fortran']}, vendor) else: return (FortranCompilerRunner, {}, vendor) else: raise ValueError("No vendor found.") def link(obj_files, out_file=None, shared=False, Runner=None, cwd=None, cplus=False, fort=False, **kwargs): """ Link object files. Parameters ========== obj_files: iterable of str Paths to object files. out_file: str (optional) Path to executable/shared library, if ``None`` it will be deduced from the last item in obj_files. shared: bool Generate a shared library? Runner: CompilerRunner subclass (optional) If not given the ``cplus`` and ``fort`` flags will be inspected (fallback is the C compiler). cwd: str Path to the root of relative paths and working directory for compiler. cplus: bool C++ objects? default: ``False``. fort: bool Fortran objects? default: ``False``. \\*\\*kwargs: dict Keyword arguments passed to ``Runner``. Returns ======= The absolute path to the generated shared object / executable. """ if out_file is None: out_file, ext = os.path.splitext(os.path.basename(obj_files[-1])) if shared: out_file += get_config_var('EXT_SUFFIX') if not Runner: if fort: Runner, extra_kwargs, vendor = \ get_mixed_fort_c_linker( vendor=kwargs.get('vendor', None), cplus=cplus, cwd=cwd, ) for k, v in extra_kwargs.items(): if k in kwargs: kwargs[k].expand(v) else: kwargs[k] = v else: if cplus: Runner = CppCompilerRunner else: Runner = CCompilerRunner flags = kwargs.pop('flags', []) if shared: if '-shared' not in flags: flags.append('-shared') run_linker = kwargs.pop('run_linker', True) if not run_linker: raise ValueError("run_linker was set to False (nonsensical).") out_file = get_abspath(out_file, cwd=cwd) runner = Runner(obj_files, out_file, flags, cwd=cwd, **kwargs) runner.run() return out_file def link_py_so(obj_files, so_file=None, cwd=None, libraries=None, cplus=False, fort=False, **kwargs): """ Link Python extension module (shared object) for importing Parameters ========== obj_files: iterable of str Paths to object files to be linked. so_file: str Name (path) of shared object file to create. If not specified it will have the basname of the last object file in `obj_files` but with the extension '.so' (Unix). cwd: path string Root of relative paths and working directory of linker. libraries: iterable of strings Libraries to link against, e.g. ['m']. cplus: bool Any C++ objects? default: ``False``. fort: bool Any Fortran objects? default: ``False``. kwargs**: dict Keyword arguments passed to ``link(...)``. Returns ======= Absolute path to the generate shared object. """ libraries = libraries or [] include_dirs = kwargs.pop('include_dirs', []) library_dirs = kwargs.pop('library_dirs', []) # from distutils/command/build_ext.py: if sys.platform == "win32": warnings.warn("Windows not yet supported.") elif sys.platform == 'darwin': # Don't use the default code below pass elif sys.platform[:3] == 'aix': # Don't use the default code below pass else: if get_config_var('Py_ENABLE_SHARED'): cfgDict = get_config_vars() kwargs['linkline'] = kwargs.get('linkline', []) + [cfgDict['PY_LDFLAGS']] # PY_LDFLAGS or just LDFLAGS? library_dirs += [cfgDict['LIBDIR']] for opt in cfgDict['BLDLIBRARY'].split(): if opt.startswith('-l'): libraries += [opt[2:]] else: pass flags = kwargs.pop('flags', []) needed_flags = ('-pthread',) for flag in needed_flags: if flag not in flags: flags.append(flag) return link(obj_files, shared=True, flags=flags, cwd=cwd, cplus=cplus, fort=fort, include_dirs=include_dirs, libraries=libraries, library_dirs=library_dirs, **kwargs) def simple_cythonize(src, destdir=None, cwd=None, **cy_kwargs): """ Generates a C file from a Cython source file. Parameters ========== src: str Path to Cython source. destdir: str (optional) Path to output directory (default: '.'). cwd: path string (optional) Root of relative paths (default: '.'). **cy_kwargs: Second argument passed to cy_compile. Generates a .cpp file if ``cplus=True`` in ``cy_kwargs``, else a .c file. """ from Cython.Compiler.Main import ( default_options, CompilationOptions ) from Cython.Compiler.Main import compile as cy_compile assert src.lower().endswith('.pyx') or src.lower().endswith('.py') cwd = cwd or '.' destdir = destdir or '.' ext = '.cpp' if cy_kwargs.get('cplus', False) else '.c' c_name = os.path.splitext(os.path.basename(src))[0] + ext dstfile = os.path.join(destdir, c_name) if cwd: ori_dir = os.getcwd() else: ori_dir = '.' os.chdir(cwd) try: cy_options = CompilationOptions(default_options) cy_options.__dict__.update(cy_kwargs) cy_result = cy_compile([src], cy_options) if cy_result.num_errors > 0: raise ValueError("Cython compilation failed.") if os.path.abspath(os.path.dirname(src)) != os.path.abspath(destdir): if os.path.exists(dstfile): os.unlink(dstfile) shutil.move(os.path.join(os.path.dirname(src), c_name), destdir) finally: os.chdir(ori_dir) return dstfile extension_mapping = { '.c': (CCompilerRunner, None), '.cpp': (CppCompilerRunner, None), '.cxx': (CppCompilerRunner, None), '.f': (FortranCompilerRunner, None), '.for': (FortranCompilerRunner, None), '.ftn': (FortranCompilerRunner, None), '.f90': (FortranCompilerRunner, None), # ifort only knows about .f90 '.f95': (FortranCompilerRunner, 'f95'), '.f03': (FortranCompilerRunner, 'f2003'), '.f08': (FortranCompilerRunner, 'f2008'), } def src2obj(srcpath, Runner=None, objpath=None, cwd=None, inc_py=False, **kwargs): """ Compiles a source code file to an object file. Files ending with '.pyx' assumed to be cython files and are dispatched to pyx2obj. Parameters ========== srcpath: str Path to source file. Runner: CompilerRunner subclass (optional) If ``None``: deduced from extension of srcpath. objpath : str (optional) Path to generated object. If ``None``: deduced from ``srcpath``. cwd: str (optional) Working directory and root of relative paths. If ``None``: current dir. inc_py: bool Add Python include path to kwarg "include_dirs". Default: False \\*\\*kwargs: dict keyword arguments passed to Runner or pyx2obj """ name, ext = os.path.splitext(os.path.basename(srcpath)) if objpath is None: if os.path.isabs(srcpath): objpath = '.' else: objpath = os.path.dirname(srcpath) objpath = objpath or '.' # avoid objpath == '' if os.path.isdir(objpath): objpath = os.path.join(objpath, name + objext) include_dirs = kwargs.pop('include_dirs', []) if inc_py: py_inc_dir = get_path('include') if py_inc_dir not in include_dirs: include_dirs.append(py_inc_dir) if ext.lower() == '.pyx': return pyx2obj(srcpath, objpath=objpath, include_dirs=include_dirs, cwd=cwd, **kwargs) if Runner is None: Runner, std = extension_mapping[ext.lower()] if 'std' not in kwargs: kwargs['std'] = std flags = kwargs.pop('flags', []) needed_flags = ('-fPIC',) for flag in needed_flags: if flag not in flags: flags.append(flag) # src2obj implies not running the linker... run_linker = kwargs.pop('run_linker', False) if run_linker: raise CompileError("src2obj called with run_linker=True") runner = Runner([srcpath], objpath, include_dirs=include_dirs, run_linker=run_linker, cwd=cwd, flags=flags, **kwargs) runner.run() return objpath def pyx2obj(pyxpath, objpath=None, destdir=None, cwd=None, include_dirs=None, cy_kwargs=None, cplus=None, **kwargs): """ Convenience function If cwd is specified, pyxpath and dst are taken to be relative If only_update is set to `True` the modification time is checked and compilation is only run if the source is newer than the destination Parameters ========== pyxpath: str Path to Cython source file. objpath: str (optional) Path to object file to generate. destdir: str (optional) Directory to put generated C file. When ``None``: directory of ``objpath``. cwd: str (optional) Working directory and root of relative paths. include_dirs: iterable of path strings (optional) Passed onto src2obj and via cy_kwargs['include_path'] to simple_cythonize. cy_kwargs: dict (optional) Keyword arguments passed onto `simple_cythonize` cplus: bool (optional) Indicate whether C++ is used. default: auto-detect using ``.util.pyx_is_cplus``. compile_kwargs: dict keyword arguments passed onto src2obj Returns ======= Absolute path of generated object file. """ assert pyxpath.endswith('.pyx') cwd = cwd or '.' objpath = objpath or '.' destdir = destdir or os.path.dirname(objpath) abs_objpath = get_abspath(objpath, cwd=cwd) if os.path.isdir(abs_objpath): pyx_fname = os.path.basename(pyxpath) name, ext = os.path.splitext(pyx_fname) objpath = os.path.join(objpath, name + objext) cy_kwargs = cy_kwargs or {} cy_kwargs['output_dir'] = cwd if cplus is None: cplus = pyx_is_cplus(pyxpath) cy_kwargs['cplus'] = cplus interm_c_file = simple_cythonize(pyxpath, destdir=destdir, cwd=cwd, **cy_kwargs) include_dirs = include_dirs or [] flags = kwargs.pop('flags', []) needed_flags = ('-fwrapv', '-pthread', '-fPIC') for flag in needed_flags: if flag not in flags: flags.append(flag) options = kwargs.pop('options', []) if kwargs.pop('strict_aliasing', False): raise CompileError("Cython requires strict aliasing to be disabled.") # Let's be explicit about standard if cplus: std = kwargs.pop('std', 'c++98') else: std = kwargs.pop('std', 'c99') return src2obj(interm_c_file, objpath=objpath, cwd=cwd, include_dirs=include_dirs, flags=flags, std=std, options=options, inc_py=True, strict_aliasing=False, **kwargs) def _any_X(srcs, cls): for src in srcs: name, ext = os.path.splitext(src) key = ext.lower() if key in extension_mapping: if extension_mapping[key][0] == cls: return True return False def any_fortran_src(srcs): return _any_X(srcs, FortranCompilerRunner) def any_cplus_src(srcs): return _any_X(srcs, CppCompilerRunner) def compile_link_import_py_ext(sources, extname=None, build_dir='.', compile_kwargs=None, link_kwargs=None): """ Compiles sources to a shared object (Python extension) and imports it Sources in ``sources`` which is imported. If shared object is newer than the sources, they are not recompiled but instead it is imported. Parameters ========== sources : string List of paths to sources. extname : string Name of extension (default: ``None``). If ``None``: taken from the last file in ``sources`` without extension. build_dir: str Path to directory in which objects files etc. are generated. compile_kwargs: dict keyword arguments passed to ``compile_sources`` link_kwargs: dict keyword arguments passed to ``link_py_so`` Returns ======= The imported module from of the Python extension. """ if extname is None: extname = os.path.splitext(os.path.basename(sources[-1]))[0] compile_kwargs = compile_kwargs or {} link_kwargs = link_kwargs or {} try: mod = import_module_from_file(os.path.join(build_dir, extname), sources) except ImportError: objs = compile_sources(list(map(get_abspath, sources)), destdir=build_dir, cwd=build_dir, **compile_kwargs) so = link_py_so(objs, cwd=build_dir, fort=any_fortran_src(sources), cplus=any_cplus_src(sources), **link_kwargs) mod = import_module_from_file(so) return mod def _write_sources_to_build_dir(sources, build_dir): build_dir = build_dir or tempfile.mkdtemp() if not os.path.isdir(build_dir): raise OSError("Non-existent directory: ", build_dir) source_files = [] for name, src in sources: dest = os.path.join(build_dir, name) differs = True sha256_in_mem = sha256_of_string(src.encode('utf-8')).hexdigest() if os.path.exists(dest): if os.path.exists(dest + '.sha256'): sha256_on_disk = open(dest + '.sha256').read() else: sha256_on_disk = sha256_of_file(dest).hexdigest() differs = sha256_on_disk != sha256_in_mem if differs: with open(dest, 'wt') as fh: fh.write(src) open(dest + '.sha256', 'wt').write(sha256_in_mem) source_files.append(dest) return source_files, build_dir def compile_link_import_strings(sources, build_dir=None, **kwargs): """ Compiles, links and imports extension module from source. Parameters ========== sources : iterable of name/source pair tuples build_dir : string (default: None) Path. ``None`` implies use a temporary directory. **kwargs: Keyword arguments passed onto `compile_link_import_py_ext`. Returns ======= mod : module The compiled and imported extension module. info : dict Containing ``build_dir`` as 'build_dir'. """ source_files, build_dir = _write_sources_to_build_dir(sources, build_dir) mod = compile_link_import_py_ext(source_files, build_dir=build_dir, **kwargs) info = dict(build_dir=build_dir) return mod, info def compile_run_strings(sources, build_dir=None, clean=False, compile_kwargs=None, link_kwargs=None): """ Compiles, links and runs a program built from sources. Parameters ========== sources : iterable of name/source pair tuples build_dir : string (default: None) Path. ``None`` implies use a temporary directory. clean : bool Whether to remove build_dir after use. This will only have an effect if ``build_dir`` is ``None`` (which creates a temporary directory). Passing ``clean == True`` and ``build_dir != None`` raises a ``ValueError``. This will also set ``build_dir`` in returned info dictionary to ``None``. compile_kwargs: dict Keyword arguments passed onto ``compile_sources`` link_kwargs: dict Keyword arguments passed onto ``link`` Returns ======= (stdout, stderr): pair of strings info: dict Containing exit status as 'exit_status' and ``build_dir`` as 'build_dir' """ if clean and build_dir is not None: raise ValueError("Automatic removal of build_dir is only available for temporary directory.") try: source_files, build_dir = _write_sources_to_build_dir(sources, build_dir) objs = compile_sources(list(map(get_abspath, source_files)), destdir=build_dir, cwd=build_dir, **(compile_kwargs or {})) prog = link(objs, cwd=build_dir, fort=any_fortran_src(source_files), cplus=any_cplus_src(source_files), **(link_kwargs or {})) p = subprocess.Popen([prog], stdout=subprocess.PIPE, stderr=subprocess.PIPE) exit_status = p.wait() stdout, stderr = [txt.decode('utf-8') for txt in p.communicate()] finally: if clean and os.path.isdir(build_dir): shutil.rmtree(build_dir) build_dir = None info = dict(exit_status=exit_status, build_dir=build_dir) return (stdout, stderr), info
7b8bc3ad3a51fe213c5cbbab89183c4cd1c1eb062d86b8589dfe0628cd730fb4
from typing import Callable, Dict as tDict, Optional, Tuple as tTuple, Union as tUnion from collections import OrderedDict import os import re import subprocess from .util import ( find_binary_of_command, unique_list, CompileError ) class CompilerRunner: """ CompilerRunner base class. Parameters ========== sources : list of str Paths to sources. out : str flags : iterable of str Compiler flags. run_linker : bool compiler_name_exe : (str, str) tuple Tuple of compiler name & command to call. cwd : str Path of root of relative paths. include_dirs : list of str Include directories. libraries : list of str Libraries to link against. library_dirs : list of str Paths to search for shared libraries. std : str Standard string, e.g. ``'c++11'``, ``'c99'``, ``'f2003'``. define: iterable of strings macros to define undef : iterable of strings macros to undefine preferred_vendor : string name of preferred vendor e.g. 'gnu' or 'intel' Methods ======= run(): Invoke compilation as a subprocess. """ # Subclass to vendor/binary dict compiler_dict = None # type: tDict[str, str] # Standards should be a tuple of supported standards # (first one will be the default) standards = None # type: tTuple[tUnion[None, str], ...] # Subclass to dict of binary/formater-callback std_formater = None # type: tDict[str, Callable[[Optional[str]], str]] # subclass to be e.g. {'gcc': 'gnu', ...} compiler_name_vendor_mapping = None # type: tDict[str, str] def __init__(self, sources, out, flags=None, run_linker=True, compiler=None, cwd='.', include_dirs=None, libraries=None, library_dirs=None, std=None, define=None, undef=None, strict_aliasing=None, preferred_vendor=None, linkline=None, **kwargs): if isinstance(sources, str): raise ValueError("Expected argument sources to be a list of strings.") self.sources = list(sources) self.out = out self.flags = flags or [] self.cwd = cwd if compiler: self.compiler_name, self.compiler_binary = compiler else: # Find a compiler if preferred_vendor is None: preferred_vendor = os.environ.get('SYMPY_COMPILER_VENDOR', None) self.compiler_name, self.compiler_binary, self.compiler_vendor = self.find_compiler(preferred_vendor) if self.compiler_binary is None: raise ValueError("No compiler found (searched: {})".format(', '.join(self.compiler_dict.values()))) self.define = define or [] self.undef = undef or [] self.include_dirs = include_dirs or [] self.libraries = libraries or [] self.library_dirs = library_dirs or [] self.std = std or self.standards[0] self.run_linker = run_linker if self.run_linker: # both gnu and intel compilers use '-c' for disabling linker self.flags = list(filter(lambda x: x != '-c', self.flags)) else: if '-c' not in self.flags: self.flags.append('-c') if self.std: self.flags.append(self.std_formater[ self.compiler_name](self.std)) self.linkline = linkline or [] if strict_aliasing is not None: nsa_re = re.compile("no-strict-aliasing$") sa_re = re.compile("strict-aliasing$") if strict_aliasing is True: if any(map(nsa_re.match, flags)): raise CompileError("Strict aliasing cannot be both enforced and disabled") elif any(map(sa_re.match, flags)): pass # already enforced else: flags.append('-fstrict-aliasing') elif strict_aliasing is False: if any(map(nsa_re.match, flags)): pass # already disabled else: if any(map(sa_re.match, flags)): raise CompileError("Strict aliasing cannot be both enforced and disabled") else: flags.append('-fno-strict-aliasing') else: msg = "Expected argument strict_aliasing to be True/False, got {}" raise ValueError(msg.format(strict_aliasing)) @classmethod def find_compiler(cls, preferred_vendor=None): """ Identify a suitable C/fortran/other compiler. """ candidates = list(cls.compiler_dict.keys()) if preferred_vendor: if preferred_vendor in candidates: candidates = [preferred_vendor]+candidates else: raise ValueError("Unknown vendor {}".format(preferred_vendor)) name, path = find_binary_of_command([cls.compiler_dict[x] for x in candidates]) return name, path, cls.compiler_name_vendor_mapping[name] def cmd(self): """ List of arguments (str) to be passed to e.g. ``subprocess.Popen``. """ cmd = ( [self.compiler_binary] + self.flags + ['-U'+x for x in self.undef] + ['-D'+x for x in self.define] + ['-I'+x for x in self.include_dirs] + self.sources ) if self.run_linker: cmd += (['-L'+x for x in self.library_dirs] + ['-l'+x for x in self.libraries] + self.linkline) counted = [] for envvar in re.findall(r'\$\{(\w+)\}', ' '.join(cmd)): if os.getenv(envvar) is None: if envvar not in counted: counted.append(envvar) msg = "Environment variable '{}' undefined.".format(envvar) raise CompileError(msg) return cmd def run(self): self.flags = unique_list(self.flags) # Append output flag and name to tail of flags self.flags.extend(['-o', self.out]) env = os.environ.copy() env['PWD'] = self.cwd # NOTE: intel compilers seems to need shell=True p = subprocess.Popen(' '.join(self.cmd()), shell=True, cwd=self.cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env) comm = p.communicate() try: self.cmd_outerr = comm[0].decode('utf-8') except UnicodeDecodeError: self.cmd_outerr = comm[0].decode('iso-8859-1') # win32 self.cmd_returncode = p.returncode # Error handling if self.cmd_returncode != 0: msg = "Error executing '{}' in {} (exited status {}):\n {}\n".format( ' '.join(self.cmd()), self.cwd, str(self.cmd_returncode), self.cmd_outerr ) raise CompileError(msg) return self.cmd_outerr, self.cmd_returncode class CCompilerRunner(CompilerRunner): compiler_dict = OrderedDict([ ('gnu', 'gcc'), ('intel', 'icc'), ('llvm', 'clang'), ]) standards = ('c89', 'c90', 'c99', 'c11') # First is default std_formater = { 'gcc': '-std={}'.format, 'icc': '-std={}'.format, 'clang': '-std={}'.format, } compiler_name_vendor_mapping = { 'gcc': 'gnu', 'icc': 'intel', 'clang': 'llvm' } def _mk_flag_filter(cmplr_name): # helper for class initialization not_welcome = {'g++': ("Wimplicit-interface",)} # "Wstrict-prototypes",)} if cmplr_name in not_welcome: def fltr(x): for nw in not_welcome[cmplr_name]: if nw in x: return False return True else: def fltr(x): return True return fltr class CppCompilerRunner(CompilerRunner): compiler_dict = OrderedDict([ ('gnu', 'g++'), ('intel', 'icpc'), ('llvm', 'clang++'), ]) # First is the default, c++0x == c++11 standards = ('c++98', 'c++0x') std_formater = { 'g++': '-std={}'.format, 'icpc': '-std={}'.format, 'clang++': '-std={}'.format, } compiler_name_vendor_mapping = { 'g++': 'gnu', 'icpc': 'intel', 'clang++': 'llvm' } class FortranCompilerRunner(CompilerRunner): standards = (None, 'f77', 'f95', 'f2003', 'f2008') std_formater = { 'gfortran': lambda x: '-std=gnu' if x is None else '-std=legacy' if x == 'f77' else '-std={}'.format(x), 'ifort': lambda x: '-stand f08' if x is None else '-stand f{}'.format(x[-2:]), # f2008 => f08 } compiler_dict = OrderedDict([ ('gnu', 'gfortran'), ('intel', 'ifort'), ]) compiler_name_vendor_mapping = { 'gfortran': 'gnu', 'ifort': 'intel', }
1100ab17ee5f558e1656db757a610013b4be4b07c4e230e8f96669d78ecc3b86
from collections import namedtuple from hashlib import sha256 import os import shutil import sys import fnmatch from sympy.testing.pytest import XFAIL def may_xfail(func): if sys.platform.lower() == 'darwin' or os.name == 'nt': # sympy.utilities._compilation needs more testing on Windows and macOS # once those two platforms are reliably supported this xfail decorator # may be removed. return XFAIL(func) else: return func class CompilerNotFoundError(FileNotFoundError): pass class CompileError (Exception): """Failure to compile one or more C/C++ source files.""" def get_abspath(path, cwd='.'): """ Returns the aboslute path. Parameters ========== path : str (relative) path. cwd : str Path to root of relative path. """ if os.path.isabs(path): return path else: if not os.path.isabs(cwd): cwd = os.path.abspath(cwd) return os.path.abspath( os.path.join(cwd, path) ) def make_dirs(path): """ Create directories (equivalent of ``mkdir -p``). """ if path[-1] == '/': parent = os.path.dirname(path[:-1]) else: parent = os.path.dirname(path) if len(parent) > 0: if not os.path.exists(parent): make_dirs(parent) if not os.path.exists(path): os.mkdir(path, 0o777) else: assert os.path.isdir(path) def copy(src, dst, only_update=False, copystat=True, cwd=None, dest_is_dir=False, create_dest_dirs=False): """ Variation of ``shutil.copy`` with extra options. Parameters ========== src : str Path to source file. dst : str Path to destination. only_update : bool Only copy if source is newer than destination (returns None if it was newer), default: ``False``. copystat : bool See ``shutil.copystat``. default: ``True``. cwd : str Path to working directory (root of relative paths). dest_is_dir : bool Ensures that dst is treated as a directory. default: ``False`` create_dest_dirs : bool Creates directories if needed. Returns ======= Path to the copied file. """ if cwd: # Handle working directory if not os.path.isabs(src): src = os.path.join(cwd, src) if not os.path.isabs(dst): dst = os.path.join(cwd, dst) if not os.path.exists(src): # Make sure source file extists raise FileNotFoundError("Source: `{}` does not exist".format(src)) # We accept both (re)naming destination file _or_ # passing a (possible non-existent) destination directory if dest_is_dir: if not dst[-1] == '/': dst = dst+'/' else: if os.path.exists(dst) and os.path.isdir(dst): dest_is_dir = True if dest_is_dir: dest_dir = dst dest_fname = os.path.basename(src) dst = os.path.join(dest_dir, dest_fname) else: dest_dir = os.path.dirname(dst) if not os.path.exists(dest_dir): if create_dest_dirs: make_dirs(dest_dir) else: raise FileNotFoundError("You must create directory first.") if only_update: # This function is not defined: # XXX: This branch is clearly not tested! if not missing_or_other_newer(dst, src): # noqa return if os.path.islink(dst): dst = os.path.abspath(os.path.realpath(dst), cwd=cwd) shutil.copy(src, dst) if copystat: shutil.copystat(src, dst) return dst Glob = namedtuple('Glob', 'pathname') ArbitraryDepthGlob = namedtuple('ArbitraryDepthGlob', 'filename') def glob_at_depth(filename_glob, cwd=None): if cwd is not None: cwd = '.' globbed = [] for root, dirs, filenames in os.walk(cwd): for fn in filenames: # This is not tested: if fnmatch.fnmatch(fn, filename_glob): globbed.append(os.path.join(root, fn)) return globbed def sha256_of_file(path, nblocks=128): """ Computes the SHA256 hash of a file. Parameters ========== path : string Path to file to compute hash of. nblocks : int Number of blocks to read per iteration. Returns ======= hashlib sha256 hash object. Use ``.digest()`` or ``.hexdigest()`` on returned object to get binary or hex encoded string. """ sh = sha256() with open(path, 'rb') as f: for chunk in iter(lambda: f.read(nblocks*sh.block_size), b''): sh.update(chunk) return sh def sha256_of_string(string): """ Computes the SHA256 hash of a string. """ sh = sha256() sh.update(string) return sh def pyx_is_cplus(path): """ Inspect a Cython source file (.pyx) and look for comment line like: # distutils: language = c++ Returns True if such a file is present in the file, else False. """ for line in open(path): if line.startswith('#') and '=' in line: splitted = line.split('=') if len(splitted) != 2: continue lhs, rhs = splitted if lhs.strip().split()[-1].lower() == 'language' and \ rhs.strip().split()[0].lower() == 'c++': return True return False def import_module_from_file(filename, only_if_newer_than=None): """ Imports Python extension (from shared object file) Provide a list of paths in `only_if_newer_than` to check timestamps of dependencies. import_ raises an ImportError if any is newer. Word of warning: The OS may cache shared objects which makes reimporting same path of an shared object file very problematic. It will not detect the new time stamp, nor new checksum, but will instead silently use old module. Use unique names for this reason. Parameters ========== filename : str Path to shared object. only_if_newer_than : iterable of strings Paths to dependencies of the shared object. Raises ====== ``ImportError`` if any of the files specified in ``only_if_newer_than`` are newer than the file given by filename. """ path, name = os.path.split(filename) name, ext = os.path.splitext(name) name = name.split('.')[0] if sys.version_info[0] == 2: from imp import find_module, load_module fobj, filename, data = find_module(name, [path]) if only_if_newer_than: for dep in only_if_newer_than: if os.path.getmtime(filename) < os.path.getmtime(dep): raise ImportError("{} is newer than {}".format(dep, filename)) mod = load_module(name, fobj, filename, data) else: import importlib.util spec = importlib.util.spec_from_file_location(name, filename) if spec is None: raise ImportError("Failed to import: '%s'" % filename) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod def find_binary_of_command(candidates): """ Finds binary first matching name among candidates. Calls ``which`` from shutils for provided candidates and returns first hit. Parameters ========== candidates : iterable of str Names of candidate commands Raises ====== CompilerNotFoundError if no candidates match. """ from shutil import which for c in candidates: binary_path = which(c) if c and binary_path: return c, binary_path raise CompilerNotFoundError('No binary located for candidates: {}'.format(candidates)) def unique_list(l): """ Uniquify a list (skip duplicate items). """ result = [] for x in l: if x not in result: result.append(x) return result
49083bf402e844268ca8aba9b20fe181af90742f4429629400934bafbe55225c
# Tests that require installed backends go into # sympy/test_external/test_autowrap import os import tempfile import shutil from io import StringIO from sympy.core import symbols, Eq from sympy.utilities.autowrap import (autowrap, binary_function, CythonCodeWrapper, UfuncifyCodeWrapper, CodeWrapper) from sympy.utilities.codegen import ( CCodeGen, C99CodeGen, CodeGenArgumentListError, make_routine ) from sympy.testing.pytest import raises from sympy.testing.tmpfiles import TmpFileManager def get_string(dump_fn, routines, prefix="file", **kwargs): """Wrapper for dump_fn. dump_fn writes its results to a stream object and this wrapper returns the contents of that stream as a string. This auxiliary function is used by many tests below. The header and the empty lines are not generator to facilitate the testing of the output. """ output = StringIO() dump_fn(routines, output, prefix, **kwargs) source = output.getvalue() output.close() return source def test_cython_wrapper_scalar_function(): x, y, z = symbols('x,y,z') expr = (x + y)*z routine = make_routine("test", expr) code_gen = CythonCodeWrapper(CCodeGen()) source = get_string(code_gen.dump_pyx, [routine]) expected = ( "cdef extern from 'file.h':\n" " double test(double x, double y, double z)\n" "\n" "def test_c(double x, double y, double z):\n" "\n" " return test(x, y, z)") assert source == expected def test_cython_wrapper_outarg(): from sympy.core.relational import Equality x, y, z = symbols('x,y,z') code_gen = CythonCodeWrapper(C99CodeGen()) routine = make_routine("test", Equality(z, x + y)) source = get_string(code_gen.dump_pyx, [routine]) expected = ( "cdef extern from 'file.h':\n" " void test(double x, double y, double *z)\n" "\n" "def test_c(double x, double y):\n" "\n" " cdef double z = 0\n" " test(x, y, &z)\n" " return z") assert source == expected def test_cython_wrapper_inoutarg(): from sympy.core.relational import Equality x, y, z = symbols('x,y,z') code_gen = CythonCodeWrapper(C99CodeGen()) routine = make_routine("test", Equality(z, x + y + z)) source = get_string(code_gen.dump_pyx, [routine]) expected = ( "cdef extern from 'file.h':\n" " void test(double x, double y, double *z)\n" "\n" "def test_c(double x, double y, double z):\n" "\n" " test(x, y, &z)\n" " return z") assert source == expected def test_cython_wrapper_compile_flags(): from sympy.core.relational import Equality x, y, z = symbols('x,y,z') routine = make_routine("test", Equality(z, x + y)) code_gen = CythonCodeWrapper(CCodeGen()) expected = """\ try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize cy_opts = {} ext_mods = [Extension( 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], include_dirs=[], library_dirs=[], libraries=[], extra_compile_args=['-std=c99'], extra_link_args=[] )] setup(ext_modules=cythonize(ext_mods, **cy_opts)) """ % {'num': CodeWrapper._module_counter} temp_dir = tempfile.mkdtemp() TmpFileManager.tmp_folder(temp_dir) setup_file_path = os.path.join(temp_dir, 'setup.py') code_gen._prepare_files(routine, build_dir=temp_dir) with open(setup_file_path) as f: setup_text = f.read() assert setup_text == expected code_gen = CythonCodeWrapper(CCodeGen(), include_dirs=['/usr/local/include', '/opt/booger/include'], library_dirs=['/user/local/lib'], libraries=['thelib', 'nilib'], extra_compile_args=['-slow-math'], extra_link_args=['-lswamp', '-ltrident'], cythonize_options={'compiler_directives': {'boundscheck': False}} ) expected = """\ try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize cy_opts = {'compiler_directives': {'boundscheck': False}} ext_mods = [Extension( 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], include_dirs=['/usr/local/include', '/opt/booger/include'], library_dirs=['/user/local/lib'], libraries=['thelib', 'nilib'], extra_compile_args=['-slow-math', '-std=c99'], extra_link_args=['-lswamp', '-ltrident'] )] setup(ext_modules=cythonize(ext_mods, **cy_opts)) """ % {'num': CodeWrapper._module_counter} code_gen._prepare_files(routine, build_dir=temp_dir) with open(setup_file_path) as f: setup_text = f.read() assert setup_text == expected expected = """\ try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize cy_opts = {'compiler_directives': {'boundscheck': False}} import numpy as np ext_mods = [Extension( 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], include_dirs=['/usr/local/include', '/opt/booger/include', np.get_include()], library_dirs=['/user/local/lib'], libraries=['thelib', 'nilib'], extra_compile_args=['-slow-math', '-std=c99'], extra_link_args=['-lswamp', '-ltrident'] )] setup(ext_modules=cythonize(ext_mods, **cy_opts)) """ % {'num': CodeWrapper._module_counter} code_gen._need_numpy = True code_gen._prepare_files(routine, build_dir=temp_dir) with open(setup_file_path) as f: setup_text = f.read() assert setup_text == expected TmpFileManager.cleanup() def test_cython_wrapper_unique_dummyvars(): from sympy.core.relational import Equality from sympy.core.symbol import Dummy x, y, z = Dummy('x'), Dummy('y'), Dummy('z') x_id, y_id, z_id = [str(d.dummy_index) for d in [x, y, z]] expr = Equality(z, x + y) routine = make_routine("test", expr) code_gen = CythonCodeWrapper(CCodeGen()) source = get_string(code_gen.dump_pyx, [routine]) expected_template = ( "cdef extern from 'file.h':\n" " void test(double x_{x_id}, double y_{y_id}, double *z_{z_id})\n" "\n" "def test_c(double x_{x_id}, double y_{y_id}):\n" "\n" " cdef double z_{z_id} = 0\n" " test(x_{x_id}, y_{y_id}, &z_{z_id})\n" " return z_{z_id}") expected = expected_template.format(x_id=x_id, y_id=y_id, z_id=z_id) assert source == expected def test_autowrap_dummy(): x, y, z = symbols('x y z') # Uses DummyWrapper to test that codegen works as expected f = autowrap(x + y, backend='dummy') assert f() == str(x + y) assert f.args == "x, y" assert f.returns == "nameless" f = autowrap(Eq(z, x + y), backend='dummy') assert f() == str(x + y) assert f.args == "x, y" assert f.returns == "z" f = autowrap(Eq(z, x + y + z), backend='dummy') assert f() == str(x + y + z) assert f.args == "x, y, z" assert f.returns == "z" def test_autowrap_args(): x, y, z = symbols('x y z') raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y), backend='dummy', args=[x])) f = autowrap(Eq(z, x + y), backend='dummy', args=[y, x]) assert f() == str(x + y) assert f.args == "y, x" assert f.returns == "z" raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y + z), backend='dummy', args=[x, y])) f = autowrap(Eq(z, x + y + z), backend='dummy', args=[y, x, z]) assert f() == str(x + y + z) assert f.args == "y, x, z" assert f.returns == "z" f = autowrap(Eq(z, x + y + z), backend='dummy', args=(y, x, z)) assert f() == str(x + y + z) assert f.args == "y, x, z" assert f.returns == "z" def test_autowrap_store_files(): x, y = symbols('x y') tmp = tempfile.mkdtemp() TmpFileManager.tmp_folder(tmp) f = autowrap(x + y, backend='dummy', tempdir=tmp) assert f() == str(x + y) assert os.access(tmp, os.F_OK) TmpFileManager.cleanup() def test_autowrap_store_files_issue_gh12939(): x, y = symbols('x y') tmp = './tmp' try: f = autowrap(x + y, backend='dummy', tempdir=tmp) assert f() == str(x + y) assert os.access(tmp, os.F_OK) finally: shutil.rmtree(tmp) def test_binary_function(): x, y = symbols('x y') f = binary_function('f', x + y, backend='dummy') assert f._imp_() == str(x + y) def test_ufuncify_source(): x, y, z = symbols('x,y,z') code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) routine = make_routine("test", x + y + z) source = get_string(code_wrapper.dump_c, [routine]) expected = """\ #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/halffloat.h" #include "file.h" static PyMethodDef wrapper_module_%(num)sMethods[] = { {NULL, NULL, 0, NULL} }; static void test_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; char *in0 = args[0]; char *in1 = args[1]; char *in2 = args[2]; char *out0 = args[3]; npy_intp in0_step = steps[0]; npy_intp in1_step = steps[1]; npy_intp in2_step = steps[2]; npy_intp out0_step = steps[3]; for (i = 0; i < n; i++) { *((double *)out0) = test(*(double *)in0, *(double *)in1, *(double *)in2); in0 += in0_step; in1 += in1_step; in2 += in2_step; out0 += out0_step; } } PyUFuncGenericFunction test_funcs[1] = {&test_ufunc}; static char test_types[4] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; static void *test_data[1] = {NULL}; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "wrapper_module_%(num)s", NULL, -1, wrapper_module_%(num)sMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) { PyObject *m, *d; PyObject *ufunc0; m = PyModule_Create(&moduledef); if (!m) { return NULL; } import_array(); import_umath(); d = PyModule_GetDict(m); ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); PyDict_SetItemString(d, "test", ufunc0); Py_DECREF(ufunc0); return m; } #else PyMODINIT_FUNC initwrapper_module_%(num)s(void) { PyObject *m, *d; PyObject *ufunc0; m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); if (m == NULL) { return; } import_array(); import_umath(); d = PyModule_GetDict(m); ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); PyDict_SetItemString(d, "test", ufunc0); Py_DECREF(ufunc0); } #endif""" % {'num': CodeWrapper._module_counter} assert source == expected def test_ufuncify_source_multioutput(): x, y, z = symbols('x,y,z') var_symbols = (x, y, z) expr = x + y**3 + 10*z**2 code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) routines = [make_routine("func{}".format(i), expr.diff(var_symbols[i]), var_symbols) for i in range(len(var_symbols))] source = get_string(code_wrapper.dump_c, routines, funcname='multitest') expected = """\ #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/halffloat.h" #include "file.h" static PyMethodDef wrapper_module_%(num)sMethods[] = { {NULL, NULL, 0, NULL} }; static void multitest_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; char *in0 = args[0]; char *in1 = args[1]; char *in2 = args[2]; char *out0 = args[3]; char *out1 = args[4]; char *out2 = args[5]; npy_intp in0_step = steps[0]; npy_intp in1_step = steps[1]; npy_intp in2_step = steps[2]; npy_intp out0_step = steps[3]; npy_intp out1_step = steps[4]; npy_intp out2_step = steps[5]; for (i = 0; i < n; i++) { *((double *)out0) = func0(*(double *)in0, *(double *)in1, *(double *)in2); *((double *)out1) = func1(*(double *)in0, *(double *)in1, *(double *)in2); *((double *)out2) = func2(*(double *)in0, *(double *)in1, *(double *)in2); in0 += in0_step; in1 += in1_step; in2 += in2_step; out0 += out0_step; out1 += out1_step; out2 += out2_step; } } PyUFuncGenericFunction multitest_funcs[1] = {&multitest_ufunc}; static char multitest_types[6] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; static void *multitest_data[1] = {NULL}; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "wrapper_module_%(num)s", NULL, -1, wrapper_module_%(num)sMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) { PyObject *m, *d; PyObject *ufunc0; m = PyModule_Create(&moduledef); if (!m) { return NULL; } import_array(); import_umath(); d = PyModule_GetDict(m); ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); PyDict_SetItemString(d, "multitest", ufunc0); Py_DECREF(ufunc0); return m; } #else PyMODINIT_FUNC initwrapper_module_%(num)s(void) { PyObject *m, *d; PyObject *ufunc0; m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); if (m == NULL) { return; } import_array(); import_umath(); d = PyModule_GetDict(m); ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); PyDict_SetItemString(d, "multitest", ufunc0); Py_DECREF(ufunc0); } #endif""" % {'num': CodeWrapper._module_counter} assert source == expected
5ac9077297b0f3b5cb8609ebf75a8871cbd89cf0da6e3635b7653b0635bd478b
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 from sympy.utilities.misc import translate, replace, ordinal, rawlines, strlines, as_int def test_translate(): abc = 'abc' translate(abc, None, 'a') == 'bc' translate(abc, None, '') == 'abc' translate(abc, {'a': 'x'}, 'c') == 'xb' assert translate(abc, {'a': 'bc'}, 'c') == 'bcb' assert translate(abc, {'ab': 'x'}, 'c') == 'x' assert translate(abc, {'ab': ''}, 'c') == '' assert translate(abc, {'bc': 'x'}, 'c') == 'ab' assert translate(abc, {'abc': 'x', 'a': 'y'}) == 'x' u = chr(4096) assert translate(abc, 'a', 'x', u) == 'xbc' assert (u in translate(abc, 'a', u, u)) is True def test_replace(): assert replace('abc', ('a', 'b')) == 'bbc' assert replace('abc', {'a': 'Aa'}) == 'Aabc' assert replace('abc', ('a', 'b'), ('c', 'C')) == 'bbC' def test_ordinal(): assert ordinal(-1) == '-1st' assert ordinal(0) == '0th' assert ordinal(1) == '1st' assert ordinal(2) == '2nd' assert ordinal(3) == '3rd' assert all(ordinal(i).endswith('th') for i in range(4, 21)) assert ordinal(100) == '100th' assert ordinal(101) == '101st' assert ordinal(102) == '102nd' assert ordinal(103) == '103rd' assert ordinal(104) == '104th' assert ordinal(200) == '200th' assert all(ordinal(i) == str(i) + 'th' for i in range(-220, -203)) def test_rawlines(): assert rawlines('a a\na') == "dedent('''\\\n a a\n a''')" assert rawlines('a a') == "'a a'" assert rawlines(strlines('\\le"ft')) == ( '(\n' " '(\\n'\n" ' \'r\\\'\\\\le"ft\\\'\\n\'\n' " ')'\n" ')') def test_strlines(): q = 'this quote (") is in the middle' # the following assert rhs was prepared with # print(rawlines(strlines(q, 10))) assert strlines(q, 10) == dedent('''\ ( 'this quo' 'te (") i' 's in the' ' middle' )''') assert q == ( 'this quo' 'te (") i' 's in the' ' middle' ) q = "this quote (') is in the middle" assert strlines(q, 20) == dedent('''\ ( "this quote (') is " "in the middle" )''') assert strlines('\\left') == ( '(\n' "r'\\left'\n" ')') assert strlines('\\left', short=True) == r"r'\left'" assert strlines('\\le"ft') == ( '(\n' 'r\'\\le"ft\'\n' ')') q = 'this\nother line' assert strlines(q) == rawlines(q) def test_translate_args(): try: translate(None, None, None, 'not_none') except ValueError: pass # Exception raised successfully else: assert False assert translate('s', None, None, None) == 's' try: translate('s', 'a', 'bc') except ValueError: pass # Exception raised successfully else: assert False def test_debug_output(): env = os.environ.copy() env['SYMPY_DEBUG'] = 'True' cmd = 'from sympy import *; x = Symbol("x"); print(integrate((1-cos(x))/x, x))' cmdline = [sys.executable, '-c', cmd] proc = Popen(cmdline, env=env, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() out = out.decode('ascii') # utf-8? err = err.decode('ascii') expected = 'substituted: -x*(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
ff277db86287673c1416975ead26bd136718aadf0931c12d06e37a53bffb6c9d
from io import StringIO from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function from sympy.core.relational import Equality from sympy.functions.elementary.piecewise import Piecewise from sympy.matrices import Matrix, MatrixSymbol from sympy.utilities.codegen import OctaveCodeGen, codegen, make_routine from sympy.testing.pytest import raises from sympy.testing.pytest import XFAIL import sympy x, y, z = symbols('x,y,z') def test_empty_m_code(): code_gen = OctaveCodeGen() output = StringIO() code_gen.dump_m([], output, "file", header=False, empty=False) source = output.getvalue() assert source == "" def test_m_simple_code(): name_expr = ("test", (x + y)*z) result, = codegen(name_expr, "Octave", header=False, empty=False) assert result[0] == "test.m" source = result[1] expected = ( "function out1 = test(x, y, z)\n" " out1 = z.*(x + y);\n" "end\n" ) assert source == expected def test_m_simple_code_with_header(): name_expr = ("test", (x + y)*z) result, = codegen(name_expr, "Octave", header=True, empty=False) assert result[0] == "test.m" source = result[1] expected = ( "function out1 = test(x, y, z)\n" " %TEST Autogenerated by SymPy\n" " % Code generated with SymPy " + sympy.__version__ + "\n" " %\n" " % See http://www.sympy.org/ for more information.\n" " %\n" " % This file is part of 'project'\n" " out1 = z.*(x + y);\n" "end\n" ) assert source == expected def test_m_simple_code_nameout(): expr = Equality(z, (x + y)) name_expr = ("test", expr) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function z = test(x, y)\n" " z = x + y;\n" "end\n" ) assert source == expected def test_m_numbersymbol(): name_expr = ("test", pi**Catalan) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function out1 = test()\n" " out1 = pi^%s;\n" "end\n" ) % Catalan.evalf(17) assert source == expected @XFAIL def test_m_numbersymbol_no_inline(): # FIXME: how to pass inline=False to the OctaveCodePrinter? name_expr = ("test", [pi**Catalan, EulerGamma]) result, = codegen(name_expr, "Octave", header=False, empty=False, inline=False) source = result[1] expected = ( "function [out1, out2] = test()\n" " Catalan = 0.915965594177219; % constant\n" " EulerGamma = 0.5772156649015329; % constant\n" " out1 = pi^Catalan;\n" " out2 = EulerGamma;\n" "end\n" ) assert source == expected def test_m_code_argument_order(): expr = x + y routine = make_routine("test", expr, argument_sequence=[z, x, y], language="octave") code_gen = OctaveCodeGen() output = StringIO() code_gen.dump_m([routine], output, "test", header=False, empty=False) source = output.getvalue() expected = ( "function out1 = test(z, x, y)\n" " out1 = x + y;\n" "end\n" ) assert source == expected def test_multiple_results_m(): # Here the output order is the input order expr1 = (x + y)*z expr2 = (x - y)*z name_expr = ("test", [expr1, expr2]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [out1, out2] = test(x, y, z)\n" " out1 = z.*(x + y);\n" " out2 = z.*(x - y);\n" "end\n" ) assert source == expected def test_results_named_unordered(): # Here output order is based on name_expr A, B, C = symbols('A,B,C') expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, (x - y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [C, A, B] = test(x, y, z)\n" " C = z.*(x + y);\n" " A = z.*(x - y);\n" " B = 2*x;\n" "end\n" ) assert source == expected def test_results_named_ordered(): A, B, C = symbols('A,B,C') expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, (x - y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result = codegen(name_expr, "Octave", header=False, empty=False, argument_sequence=(x, z, y)) assert result[0][0] == "test.m" source = result[0][1] expected = ( "function [C, A, B] = test(x, z, y)\n" " C = z.*(x + y);\n" " A = z.*(x - y);\n" " B = 2*x;\n" "end\n" ) assert source == expected def test_complicated_m_codegen(): from sympy.functions.elementary.trigonometric import (cos, sin, tan) name_expr = ("testlong", [ ((sin(x) + cos(y) + tan(z))**3).expand(), cos(cos(cos(cos(cos(cos(cos(cos(x + y + z)))))))) ]) result = codegen(name_expr, "Octave", header=False, empty=False) assert result[0][0] == "testlong.m" source = result[0][1] expected = ( "function [out1, out2] = testlong(x, y, z)\n" " out1 = sin(x).^3 + 3*sin(x).^2.*cos(y) + 3*sin(x).^2.*tan(z)" " + 3*sin(x).*cos(y).^2 + 6*sin(x).*cos(y).*tan(z) + 3*sin(x).*tan(z).^2" " + cos(y).^3 + 3*cos(y).^2.*tan(z) + 3*cos(y).*tan(z).^2 + tan(z).^3;\n" " out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n" "end\n" ) assert source == expected def test_m_output_arg_mixed_unordered(): # named outputs are alphabetical, unnamed output appear in the given order from sympy.functions.elementary.trigonometric import (cos, sin) a = symbols("a") name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))]) result, = codegen(name_expr, "Octave", header=False, empty=False) assert result[0] == "foo.m" source = result[1]; expected = ( 'function [out1, y, out3, a] = foo(x)\n' ' out1 = cos(2*x);\n' ' y = sin(x);\n' ' out3 = cos(x);\n' ' a = sin(2*x);\n' 'end\n' ) assert source == expected def test_m_piecewise_(): pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False) name_expr = ("pwtest", pw) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function out1 = pwtest(x)\n" " out1 = ((x < -1).*(0) + (~(x < -1)).*( ...\n" " (x <= 1).*(x.^2) + (~(x <= 1)).*( ...\n" " (x > 1).*(2 - x) + (~(x > 1)).*(1))));\n" "end\n" ) assert source == expected @XFAIL def test_m_piecewise_no_inline(): # FIXME: how to pass inline=False to the OctaveCodePrinter? pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True)) name_expr = ("pwtest", pw) result, = codegen(name_expr, "Octave", header=False, empty=False, inline=False) source = result[1] expected = ( "function out1 = pwtest(x)\n" " if (x < -1)\n" " out1 = 0;\n" " elseif (x <= 1)\n" " out1 = x.^2;\n" " elseif (x > 1)\n" " out1 = -x + 2;\n" " else\n" " out1 = 1;\n" " end\n" "end\n" ) assert source == expected def test_m_multifcns_per_file(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Octave", header=False, empty=False) assert result[0][0] == "foo.m" source = result[0][1]; expected = ( "function [out1, out2] = foo(x, y)\n" " out1 = 2*x;\n" " out2 = 3*y;\n" "end\n" "function [out1, out2] = bar(y)\n" " out1 = y.^2;\n" " out2 = 4*y;\n" "end\n" ) assert source == expected def test_m_multifcns_per_file_w_header(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Octave", header=True, empty=False) assert result[0][0] == "foo.m" source = result[0][1]; expected = ( "function [out1, out2] = foo(x, y)\n" " %FOO Autogenerated by SymPy\n" " % Code generated with SymPy " + sympy.__version__ + "\n" " %\n" " % See http://www.sympy.org/ for more information.\n" " %\n" " % This file is part of 'project'\n" " out1 = 2*x;\n" " out2 = 3*y;\n" "end\n" "function [out1, out2] = bar(y)\n" " out1 = y.^2;\n" " out2 = 4*y;\n" "end\n" ) assert source == expected def test_m_filename_match_first_fcn(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] raises(ValueError, lambda: codegen(name_expr, "Octave", prefix="bar", header=False, empty=False)) def test_m_matrix_named(): e2 = Matrix([[x, 2*y, pi*z]]) name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2)) result = codegen(name_expr, "Octave", header=False, empty=False) assert result[0][0] == "test.m" source = result[0][1] expected = ( "function myout1 = test(x, y, z)\n" " myout1 = [x 2*y pi*z];\n" "end\n" ) assert source == expected def test_m_matrix_named_matsym(): myout1 = MatrixSymbol('myout1', 1, 3) e2 = Matrix([[x, 2*y, pi*z]]) name_expr = ("test", Equality(myout1, e2, evaluate=False)) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function myout1 = test(x, y, z)\n" " myout1 = [x 2*y pi*z];\n" "end\n" ) assert source == expected def test_m_matrix_output_autoname(): expr = Matrix([[x, x+y, 3]]) name_expr = ("test", expr) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function out1 = test(x, y)\n" " out1 = [x x + y 3];\n" "end\n" ) assert source == expected def test_m_matrix_output_autoname_2(): e1 = (x + y) e2 = Matrix([[2*x, 2*y, 2*z]]) e3 = Matrix([[x], [y], [z]]) e4 = Matrix([[x, y], [z, 16]]) name_expr = ("test", (e1, e2, e3, e4)) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [out1, out2, out3, out4] = test(x, y, z)\n" " out1 = x + y;\n" " out2 = [2*x 2*y 2*z];\n" " out3 = [x; y; z];\n" " out4 = [x y; z 16];\n" "end\n" ) assert source == expected def test_m_results_matrix_named_ordered(): B, C = symbols('B,C') A = MatrixSymbol('A', 1, 3) expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, Matrix([[1, 2, x]])) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result, = codegen(name_expr, "Octave", header=False, empty=False, argument_sequence=(x, z, y)) source = result[1] expected = ( "function [C, A, B] = test(x, z, y)\n" " C = z.*(x + y);\n" " A = [1 2 x];\n" " B = 2*x;\n" "end\n" ) assert source == expected def test_m_matrixsymbol_slice(): A = MatrixSymbol('A', 2, 3) B = MatrixSymbol('B', 1, 3) C = MatrixSymbol('C', 1, 3) D = MatrixSymbol('D', 2, 1) name_expr = ("test", [Equality(B, A[0, :]), Equality(C, A[1, :]), Equality(D, A[:, 2])]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [B, C, D] = test(A)\n" " B = A(1, :);\n" " C = A(2, :);\n" " D = A(:, 3);\n" "end\n" ) assert source == expected def test_m_matrixsymbol_slice2(): A = MatrixSymbol('A', 3, 4) B = MatrixSymbol('B', 2, 2) C = MatrixSymbol('C', 2, 2) name_expr = ("test", [Equality(B, A[0:2, 0:2]), Equality(C, A[0:2, 1:3])]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [B, C] = test(A)\n" " B = A(1:2, 1:2);\n" " C = A(1:2, 2:3);\n" "end\n" ) assert source == expected def test_m_matrixsymbol_slice3(): A = MatrixSymbol('A', 8, 7) B = MatrixSymbol('B', 2, 2) C = MatrixSymbol('C', 4, 2) name_expr = ("test", [Equality(B, A[6:, 1::3]), Equality(C, A[::2, ::3])]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [B, C] = test(A)\n" " B = A(7:end, 2:3:end);\n" " C = A(1:2:end, 1:3:end);\n" "end\n" ) assert source == expected def test_m_matrixsymbol_slice_autoname(): A = MatrixSymbol('A', 2, 3) B = MatrixSymbol('B', 1, 3) name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [B, out2, out3, out4] = test(A)\n" " B = A(1, :);\n" " out2 = A(2, :);\n" " out3 = A(:, 1);\n" " out4 = A(:, 2);\n" "end\n" ) assert source == expected def test_m_loops(): # Note: an Octave programmer would probably vectorize this across one or # more dimensions. Also, size(A) would be used rather than passing in m # and n. Perhaps users would expect us to vectorize automatically here? # Or is it possible to represent such things using IndexedBase? from sympy.tensor import IndexedBase, Idx from sympy.core.symbol import symbols n, m = symbols('n m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j]*x[j])), "Octave", header=False, empty=False) source = result[1] expected = ( 'function y = mat_vec_mult(A, m, n, x)\n' ' for i = 1:m\n' ' y(i) = 0;\n' ' end\n' ' for i = 1:m\n' ' for j = 1:n\n' ' y(i) = %(rhs)s + y(i);\n' ' end\n' ' end\n' 'end\n' ) assert (source == expected % {'rhs': 'A(%s, %s).*x(j)' % (i, j)} or source == expected % {'rhs': 'x(j).*A(%s, %s)' % (i, j)}) def test_m_tensor_loops_multiple_contractions(): # see comments in previous test about vectorizing from sympy.tensor import IndexedBase, Idx from sympy.core.symbol import symbols n, m, o, p = symbols('n m o p', integer=True) A = IndexedBase('A') B = IndexedBase('B') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) l = Idx('l', p) result, = codegen(('tensorthing', Eq(y[i], B[j, k, l]*A[i, j, k, l])), "Octave", header=False, empty=False) source = result[1] expected = ( 'function y = tensorthing(A, B, m, n, o, p)\n' ' for i = 1:m\n' ' y(i) = 0;\n' ' end\n' ' for i = 1:m\n' ' for j = 1:n\n' ' for k = 1:o\n' ' for l = 1:p\n' ' y(i) = A(i, j, k, l).*B(j, k, l) + y(i);\n' ' end\n' ' end\n' ' end\n' ' end\n' 'end\n' ) assert source == expected def test_m_InOutArgument(): expr = Equality(x, x**2) name_expr = ("mysqr", expr) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function x = mysqr(x)\n" " x = x.^2;\n" "end\n" ) assert source == expected def test_m_InOutArgument_order(): # can specify the order as (x, y) expr = Equality(x, x**2 + y) name_expr = ("test", expr) result, = codegen(name_expr, "Octave", header=False, empty=False, argument_sequence=(x,y)) source = result[1] expected = ( "function x = test(x, y)\n" " x = x.^2 + y;\n" "end\n" ) assert source == expected # make sure it gives (x, y) not (y, x) expr = Equality(x, x**2 + y) name_expr = ("test", expr) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function x = test(x, y)\n" " x = x.^2 + y;\n" "end\n" ) assert source == expected def test_m_not_supported(): f = Function('f') name_expr = ("test", [f(x).diff(x), S.ComplexInfinity]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [out1, out2] = test(x)\n" " % unsupported: Derivative(f(x), x)\n" " % unsupported: zoo\n" " out1 = Derivative(f(x), x);\n" " out2 = zoo;\n" "end\n" ) assert source == expected def test_global_vars_octave(): x, y, z, t = symbols("x y z t") result = codegen(('f', x*y), "Octave", header=False, empty=False, global_vars=(y,)) source = result[0][1] expected = ( "function out1 = f(x)\n" " global y\n" " out1 = x.*y;\n" "end\n" ) assert source == expected result = codegen(('f', x*y+z), "Octave", header=False, empty=False, argument_sequence=(x, y), global_vars=(z, t)) source = result[0][1] expected = ( "function out1 = f(x, y)\n" " global t z\n" " out1 = x.*y + z;\n" "end\n" ) assert source == expected
a07955022234bf90e65e478ce23a05b12c46f0e1246e3ec54bc96bad056d92c3
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)
42a84e78a85420eeca758f3304678e4e026b4496069360fb62c90b5f7eaf2c75
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('value', 'feature', issue=12345, deprecated_since_version='1.0') check(w) def test_issue_18438(): assert pickle.loads(pickle.dumps(S.Half)) == 1/2
c0987a6260dfabc85a1a32439e20da554b0320a123deb4ff381e2beae2c8efb6
from io import StringIO from sympy.core import S, symbols, pi, Catalan, EulerGamma, Function from sympy.core.relational import Equality from sympy.functions.elementary.piecewise import Piecewise from sympy.utilities.codegen import RustCodeGen, codegen, make_routine from sympy.testing.pytest import XFAIL import sympy x, y, z = symbols('x,y,z') def test_empty_rust_code(): code_gen = RustCodeGen() output = StringIO() code_gen.dump_rs([], output, "file", header=False, empty=False) source = output.getvalue() assert source == "" def test_simple_rust_code(): name_expr = ("test", (x + y)*z) result, = codegen(name_expr, "Rust", header=False, empty=False) assert result[0] == "test.rs" source = result[1] expected = ( "fn test(x: f64, y: f64, z: f64) -> f64 {\n" " let out1 = z*(x + y);\n" " out1\n" "}\n" ) assert source == expected def test_simple_code_with_header(): name_expr = ("test", (x + y)*z) result, = codegen(name_expr, "Rust", header=True, empty=False) assert result[0] == "test.rs" source = result[1] version_str = "Code generated with SymPy %s" % sympy.__version__ version_line = version_str.center(76).rstrip() expected = ( "/*\n" " *%(version_line)s\n" " *\n" " * See http://www.sympy.org/ for more information.\n" " *\n" " * This file is part of 'project'\n" " */\n" "fn test(x: f64, y: f64, z: f64) -> f64 {\n" " let out1 = z*(x + y);\n" " out1\n" "}\n" ) % {'version_line': version_line} assert source == expected def test_simple_code_nameout(): expr = Equality(z, (x + y)) name_expr = ("test", expr) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn test(x: f64, y: f64) -> f64 {\n" " let z = x + y;\n" " z\n" "}\n" ) assert source == expected def test_numbersymbol(): name_expr = ("test", pi**Catalan) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn test() -> f64 {\n" " const Catalan: f64 = %s;\n" " let out1 = PI.powf(Catalan);\n" " out1\n" "}\n" ) % Catalan.evalf(17) assert source == expected @XFAIL def test_numbersymbol_inline(): # FIXME: how to pass inline to the RustCodePrinter? name_expr = ("test", [pi**Catalan, EulerGamma]) result, = codegen(name_expr, "Rust", header=False, empty=False, inline=True) source = result[1] expected = ( "fn test() -> (f64, f64) {\n" " const Catalan: f64 = %s;\n" " const EulerGamma: f64 = %s;\n" " let out1 = PI.powf(Catalan);\n" " let out2 = EulerGamma);\n" " (out1, out2)\n" "}\n" ) % (Catalan.evalf(17), EulerGamma.evalf(17)) assert source == expected def test_argument_order(): expr = x + y routine = make_routine("test", expr, argument_sequence=[z, x, y], language="rust") code_gen = RustCodeGen() output = StringIO() code_gen.dump_rs([routine], output, "test", header=False, empty=False) source = output.getvalue() expected = ( "fn test(z: f64, x: f64, y: f64) -> f64 {\n" " let out1 = x + y;\n" " out1\n" "}\n" ) assert source == expected def test_multiple_results_rust(): # Here the output order is the input order expr1 = (x + y)*z expr2 = (x - y)*z name_expr = ("test", [expr1, expr2]) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn test(x: f64, y: f64, z: f64) -> (f64, f64) {\n" " let out1 = z*(x + y);\n" " let out2 = z*(x - y);\n" " (out1, out2)\n" "}\n" ) assert source == expected def test_results_named_unordered(): # Here output order is based on name_expr A, B, C = symbols('A,B,C') expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, (x - y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn test(x: f64, y: f64, z: f64) -> (f64, f64, f64) {\n" " let C = z*(x + y);\n" " let A = z*(x - y);\n" " let B = 2*x;\n" " (C, A, B)\n" "}\n" ) assert source == expected def test_results_named_ordered(): A, B, C = symbols('A,B,C') expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, (x - y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result = codegen(name_expr, "Rust", header=False, empty=False, argument_sequence=(x, z, y)) assert result[0][0] == "test.rs" source = result[0][1] expected = ( "fn test(x: f64, z: f64, y: f64) -> (f64, f64, f64) {\n" " let C = z*(x + y);\n" " let A = z*(x - y);\n" " let B = 2*x;\n" " (C, A, B)\n" "}\n" ) assert source == expected def test_complicated_rs_codegen(): from sympy.functions.elementary.trigonometric import (cos, sin, tan) name_expr = ("testlong", [ ((sin(x) + cos(y) + tan(z))**3).expand(), cos(cos(cos(cos(cos(cos(cos(cos(x + y + z)))))))) ]) result = codegen(name_expr, "Rust", header=False, empty=False) assert result[0][0] == "testlong.rs" source = result[0][1] expected = ( "fn testlong(x: f64, y: f64, z: f64) -> (f64, f64) {\n" " let out1 = x.sin().powi(3) + 3*x.sin().powi(2)*y.cos()" " + 3*x.sin().powi(2)*z.tan() + 3*x.sin()*y.cos().powi(2)" " + 6*x.sin()*y.cos()*z.tan() + 3*x.sin()*z.tan().powi(2)" " + y.cos().powi(3) + 3*y.cos().powi(2)*z.tan()" " + 3*y.cos()*z.tan().powi(2) + z.tan().powi(3);\n" " let out2 = (x + y + z).cos().cos().cos().cos()" ".cos().cos().cos().cos();\n" " (out1, out2)\n" "}\n" ) assert source == expected def test_output_arg_mixed_unordered(): # named outputs are alphabetical, unnamed output appear in the given order from sympy.functions.elementary.trigonometric import (cos, sin) a = symbols("a") name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))]) result, = codegen(name_expr, "Rust", header=False, empty=False) assert result[0] == "foo.rs" source = result[1]; expected = ( "fn foo(x: f64) -> (f64, f64, f64, f64) {\n" " let out1 = (2*x).cos();\n" " let y = x.sin();\n" " let out3 = x.cos();\n" " let a = (2*x).sin();\n" " (out1, y, out3, a)\n" "}\n" ) assert source == expected def test_piecewise_(): pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False) name_expr = ("pwtest", pw) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn pwtest(x: f64) -> f64 {\n" " let out1 = if (x < -1) {\n" " 0\n" " } else if (x <= 1) {\n" " x.powi(2)\n" " } else if (x > 1) {\n" " 2 - x\n" " } else {\n" " 1\n" " };\n" " out1\n" "}\n" ) assert source == expected @XFAIL def test_piecewise_inline(): # FIXME: how to pass inline to the RustCodePrinter? pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True)) name_expr = ("pwtest", pw) result, = codegen(name_expr, "Rust", header=False, empty=False, inline=True) source = result[1] expected = ( "fn pwtest(x: f64) -> f64 {\n" " let out1 = if (x < -1) { 0 } else if (x <= 1) { x.powi(2) }" " else if (x > 1) { -x + 2 } else { 1 };\n" " out1\n" "}\n" ) assert source == expected def test_multifcns_per_file(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Rust", header=False, empty=False) assert result[0][0] == "foo.rs" source = result[0][1]; expected = ( "fn foo(x: f64, y: f64) -> (f64, f64) {\n" " let out1 = 2*x;\n" " let out2 = 3*y;\n" " (out1, out2)\n" "}\n" "fn bar(y: f64) -> (f64, f64) {\n" " let out1 = y.powi(2);\n" " let out2 = 4*y;\n" " (out1, out2)\n" "}\n" ) assert source == expected def test_multifcns_per_file_w_header(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Rust", header=True, empty=False) assert result[0][0] == "foo.rs" source = result[0][1]; version_str = "Code generated with SymPy %s" % sympy.__version__ version_line = version_str.center(76).rstrip() expected = ( "/*\n" " *%(version_line)s\n" " *\n" " * See http://www.sympy.org/ for more information.\n" " *\n" " * This file is part of 'project'\n" " */\n" "fn foo(x: f64, y: f64) -> (f64, f64) {\n" " let out1 = 2*x;\n" " let out2 = 3*y;\n" " (out1, out2)\n" "}\n" "fn bar(y: f64) -> (f64, f64) {\n" " let out1 = y.powi(2);\n" " let out2 = 4*y;\n" " (out1, out2)\n" "}\n" ) % {'version_line': version_line} assert source == expected def test_filename_match_prefix(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result, = codegen(name_expr, "Rust", prefix="baz", header=False, empty=False) assert result[0] == "baz.rs" def test_InOutArgument(): expr = Equality(x, x**2) name_expr = ("mysqr", expr) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn mysqr(x: f64) -> f64 {\n" " let x = x.powi(2);\n" " x\n" "}\n" ) assert source == expected def test_InOutArgument_order(): # can specify the order as (x, y) expr = Equality(x, x**2 + y) name_expr = ("test", expr) result, = codegen(name_expr, "Rust", header=False, empty=False, argument_sequence=(x,y)) source = result[1] expected = ( "fn test(x: f64, y: f64) -> f64 {\n" " let x = x.powi(2) + y;\n" " x\n" "}\n" ) assert source == expected # make sure it gives (x, y) not (y, x) expr = Equality(x, x**2 + y) name_expr = ("test", expr) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn test(x: f64, y: f64) -> f64 {\n" " let x = x.powi(2) + y;\n" " x\n" "}\n" ) assert source == expected def test_not_supported(): f = Function('f') name_expr = ("test", [f(x).diff(x), S.ComplexInfinity]) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn test(x: f64) -> (f64, f64) {\n" " // unsupported: Derivative(f(x), x)\n" " // unsupported: zoo\n" " let out1 = Derivative(f(x), x);\n" " let out2 = zoo;\n" " (out1, out2)\n" "}\n" ) assert source == expected def test_global_vars_rust(): x, y, z, t = symbols("x y z t") result = codegen(('f', x*y), "Rust", header=False, empty=False, global_vars=(y,)) source = result[0][1] expected = ( "fn f(x: f64) -> f64 {\n" " let out1 = x*y;\n" " out1\n" "}\n" ) assert source == expected result = codegen(('f', x*y+z), "Rust", header=False, empty=False, argument_sequence=(x, y), global_vars=(z, t)) source = result[0][1] expected = ( "fn f(x: f64, y: f64) -> f64 {\n" " let out1 = x*y + z;\n" " out1\n" "}\n" ) assert source == expected
694c3a9db4b3069f21fe9937e5867fbb3467711a0b612b5b96875e88344593a2
from itertools import zip_longest from sympy.utilities.enumerative import ( list_visitor, MultisetPartitionTraverser, multiset_partitions_taocp ) from sympy.utilities.iterables import _set_partitions # first some functions only useful as test scaffolding - these provide # straightforward, but slow reference implementations against which to # compare the real versions, and also a comparison to verify that # different versions are giving identical results. def part_range_filter(partition_iterator, lb, ub): """ Filters (on the number of parts) a multiset partition enumeration Arguments ========= lb, and ub are a range (in the Python slice sense) on the lpart variable returned from a multiset partition enumeration. Recall that lpart is 0-based (it points to the topmost part on the part stack), so if you want to return parts of sizes 2,3,4,5 you would use lb=1 and ub=5. """ for state in partition_iterator: f, lpart, pstack = state if lpart >= lb and lpart < ub: yield state def multiset_partitions_baseline(multiplicities, components): """Enumerates partitions of a multiset Parameters ========== multiplicities list of integer multiplicities of the components of the multiset. components the components (elements) themselves Returns ======= Set of partitions. Each partition is tuple of parts, and each part is a tuple of components (with repeats to indicate multiplicity) Notes ===== Multiset partitions can be created as equivalence classes of set partitions, and this function does just that. This approach is slow and memory intensive compared to the more advanced algorithms available, but the code is simple and easy to understand. Hence this routine is strictly for testing -- to provide a straightforward baseline against which to regress the production versions. (This code is a simplified version of an earlier production implementation.) """ canon = [] # list of components with repeats for ct, elem in zip(multiplicities, components): canon.extend([elem]*ct) # accumulate the multiset partitions in a set to eliminate dups cache = set() n = len(canon) for nc, q in _set_partitions(n): rv = [[] for i in range(nc)] for i in range(n): rv[q[i]].append(canon[i]) canonical = tuple( sorted([tuple(p) for p in rv])) cache.add(canonical) return cache def compare_multiset_w_baseline(multiplicities): """ Enumerates the partitions of multiset with AOCP algorithm and baseline implementation, and compare the results. """ letters = "abcdefghijklmnopqrstuvwxyz" bl_partitions = multiset_partitions_baseline(multiplicities, letters) # The partitions returned by the different algorithms may have # their parts in different orders. Also, they generate partitions # in different orders. Hence the sorting, and set comparison. aocp_partitions = set() for state in multiset_partitions_taocp(multiplicities): p1 = tuple(sorted( [tuple(p) for p in list_visitor(state, letters)])) aocp_partitions.add(p1) assert bl_partitions == aocp_partitions def compare_multiset_states(s1, s2): """compare for equality two instances of multiset partition states This is useful for comparing different versions of the algorithm to verify correctness.""" # Comparison is physical, the only use of semantics is to ignore # trash off the top of the stack. f1, lpart1, pstack1 = s1 f2, lpart2, pstack2 = s2 if (lpart1 == lpart2) and (f1[0:lpart1+1] == f2[0:lpart2+1]): if pstack1[0:f1[lpart1+1]] == pstack2[0:f2[lpart2+1]]: return True return False def test_multiset_partitions_taocp(): """Compares the output of multiset_partitions_taocp with a baseline (set partition based) implementation.""" # Test cases should not be too large, since the baseline # implementation is fairly slow. multiplicities = [2,2] compare_multiset_w_baseline(multiplicities) multiplicities = [4,3,1] compare_multiset_w_baseline(multiplicities) def test_multiset_partitions_versions(): """Compares Knuth-based versions of multiset_partitions""" multiplicities = [5,2,2,1] m = MultisetPartitionTraverser() for s1, s2 in zip_longest(m.enum_all(multiplicities), multiset_partitions_taocp(multiplicities)): assert compare_multiset_states(s1, s2) def subrange_exercise(mult, lb, ub): """Compare filter-based and more optimized subrange implementations Helper for tests, called with both small and larger multisets. """ m = MultisetPartitionTraverser() assert m.count_partitions(mult) == \ m.count_partitions_slow(mult) # Note - multiple traversals from the same # MultisetPartitionTraverser object cannot execute at the same # time, hence make several instances here. ma = MultisetPartitionTraverser() mc = MultisetPartitionTraverser() md = MultisetPartitionTraverser() # Several paths to compute just the size two partitions a_it = ma.enum_range(mult, lb, ub) b_it = part_range_filter(multiset_partitions_taocp(mult), lb, ub) c_it = part_range_filter(mc.enum_small(mult, ub), lb, sum(mult)) d_it = part_range_filter(md.enum_large(mult, lb), 0, ub) for sa, sb, sc, sd in zip_longest(a_it, b_it, c_it, d_it): assert compare_multiset_states(sa, sb) assert compare_multiset_states(sa, sc) assert compare_multiset_states(sa, sd) def test_subrange(): # Quick, but doesn't hit some of the corner cases mult = [4,4,2,1] # mississippi lb = 1 ub = 2 subrange_exercise(mult, lb, ub) def test_subrange_large(): # takes a second or so, depending on cpu, Python version, etc. mult = [6,3,2,1] lb = 4 ub = 7 subrange_exercise(mult, lb, ub)
ce76308199c773c54226d5fc519f9c3459ed3203186cb66a843f3664d124924c
from itertools import product import math import inspect import mpmath from sympy.testing.pytest import raises 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.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.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') 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_namespace_type(): # lambdify had a bug where it would reject modules of type unicode # on Python 2. x = sympy.Symbol('x') lambdify(x, x, modules='math') def test_imps(): # Here we check if the default returned functions are anonymous - in # the sense that we can have more than one function with the same name f = implemented_function('f', lambda x: 2*x) g = implemented_function('f', lambda x: math.sqrt(x)) l1 = lambdify(x, f(x)) l2 = lambdify(x, g(x)) assert str(f(x)) == str(g(x)) assert l1(3) == 6 assert l2(3) == math.sqrt(3) # check that we can pass in a Function as input func = sympy.Function('myfunc') assert not hasattr(func, '_imp_') my_f = implemented_function(func, lambda x: 2*x) assert hasattr(my_f, '_imp_') # Error for functions with same name and different implementation f2 = implemented_function("f", lambda x: x + 101) raises(ValueError, lambda: lambdify(x, f(f2(x)))) def test_imps_errors(): # Test errors that implemented functions can return, and still be able to # form expressions. # See: https://github.com/sympy/sympy/issues/10810 # # XXX: Removed AttributeError here. This test was added due to issue 10810 # but that issue was about ValueError. It doesn't seem reasonable to # "support" catching AttributeError in the same context... for val, error_class in product((0, 0., 2, 2.0), (TypeError, ValueError)): def myfunc(a): if a == 0: raise error_class return 1 f = implemented_function('f', myfunc) expr = f(val) assert expr == f(val) def test_imps_wrong_args(): raises(ValueError, lambda: implemented_function(sin, lambda x: x)) def test_lambdify_imps(): # Test lambdify with implemented functions # first test basic (sympy) lambdify f = sympy.cos assert lambdify(x, f(x))(0) == 1 assert lambdify(x, 1 + f(x))(0) == 2 assert lambdify((x, y), y + f(x))(0, 1) == 2 # make an implemented function and test f = implemented_function("f", lambda x: x + 100) assert lambdify(x, f(x))(0) == 100 assert lambdify(x, 1 + f(x))(0) == 101 assert lambdify((x, y), y + f(x))(0, 1) == 101 # Can also handle tuples, lists, dicts as expressions lam = lambdify(x, (f(x), x)) assert lam(3) == (103, 3) lam = lambdify(x, [f(x), x]) assert lam(3) == [103, 3] lam = lambdify(x, [f(x), (f(x), x)]) assert lam(3) == [103, (103, 3)] lam = lambdify(x, {f(x): x}) assert lam(3) == {103: 3} lam = lambdify(x, {f(x): x}) assert lam(3) == {103: 3} lam = lambdify(x, {x: f(x)}) assert lam(3) == {3: 103} # Check that imp preferred to other namespaces by default d = {'f': lambda x: x + 99} lam = lambdify(x, f(x), d) assert lam(3) == 103 # Unless flag passed lam = lambdify(x, f(x), d, use_imps=False) assert lam(3) == 102 def test_dummification(): t = symbols('t') F = Function('F') G = Function('G') #"\alpha" is not a valid Python variable name #lambdify should sub in a dummy for it, and return #without a syntax error alpha = symbols(r'\alpha') some_expr = 2 * F(t)**2 / G(t) lam = lambdify((F(t), G(t)), some_expr) assert lam(3, 9) == 2 lam = lambdify(sin(t), 2 * sin(t)**2) assert lam(F(t)) == 2 * F(t)**2 #Test that \alpha was properly dummified lam = lambdify((alpha, t), 2*alpha + t) assert lam(2, 1) == 5 raises(SyntaxError, lambda: lambdify(F(t) * G(t), F(t) * G(t) + 5)) raises(SyntaxError, lambda: lambdify(2 * F(t), 2 * F(t) + 5)) raises(SyntaxError, lambda: lambdify(2 * F(t), 4 * F(t) + 5)) def test_curly_matrix_symbol(): # Issue #15009 curlyv = sympy.MatrixSymbol("{v}", 2, 1) lam = lambdify(curlyv, curlyv) assert lam(1)==1 lam = lambdify(curlyv, curlyv, dummify=True) assert lam(1)==1 def test_python_keywords(): # Test for issue 7452. The automatic dummification should ensure use of # Python reserved keywords as symbol names will create valid lambda # functions. This is an additional regression test. python_if = symbols('if') expr = python_if / 2 f = lambdify(python_if, expr) assert f(4.0) == 2.0 def test_lambdify_docstring(): func = lambdify((w, x, y, z), w + x + y + z) ref = ( "Created with lambdify. Signature:\n\n" "func(w, x, y, z)\n\n" "Expression:\n\n" "w + x + y + z" ).splitlines() assert func.__doc__.splitlines()[:len(ref)] == ref syms = symbols('a1:26') func = lambdify(syms, sum(syms)) ref = ( "Created with lambdify. Signature:\n\n" "func(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15,\n" " a16, a17, a18, a19, a20, a21, a22, a23, a24, a25)\n\n" "Expression:\n\n" "a1 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a2 + a20 +..." ).splitlines() assert func.__doc__.splitlines()[:len(ref)] == ref #================== Test special printers ========================== def test_special_printers(): from sympy.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_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)
554d4b42c65840998b630615de94f1f740546a3fcead3b2dc7b98faaafd59a12
""" Tests from Michael Wester's 1999 paper "Review of CAS mathematical capabilities". http://www.math.unm.edu/~wester/cas/book/Wester.pdf See also http://math.unm.edu/~wester/cas_review.html for detailed output of each tested system. """ from sympy.assumptions.ask import Q, ask from sympy.assumptions.refine import refine from sympy.concrete.products import product from sympy.core import EulerGamma from sympy.core.evalf import N from sympy.core.function import (Derivative, Function, Lambda, Subs, diff, expand, expand_func) from sympy.core.mul import Mul from sympy.core.numbers import (AlgebraicNumber, E, I, Rational, igcd, nan, oo, pi, zoo) from sympy.core.relational import Eq, Lt from sympy.core.singleton import S from sympy.core.symbol import Dummy, Symbol, symbols from sympy.functions.combinatorial.factorials import (rf, binomial, factorial, factorial2) from sympy.functions.combinatorial.numbers import bernoulli, fibonacci from sympy.functions.elementary.complexes import (conjugate, im, re, sign) from sympy.functions.elementary.exponential import LambertW, exp, log from sympy.functions.elementary.hyperbolic import (asinh, cosh, sinh, tanh) from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.miscellaneous import Max, Min, sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, acot, asin, atan, cos, cot, csc, sec, sin, tan) from sympy.functions.special.bessel import besselj from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.elliptic_integrals import (elliptic_e, elliptic_f) from sympy.functions.special.gamma_functions import gamma, polygamma from sympy.functions.special.hyper import hyper from sympy.functions.special.polynomials import (assoc_legendre, chebyshevt) from sympy.functions.special.zeta_functions import polylog from sympy.geometry.util import idiff from sympy.logic.boolalg import And from sympy.matrices.dense import hessian, wronskian from sympy.matrices.expressions.matmul import MatMul from sympy.ntheory.continued_fraction import ( continued_fraction_convergents as cf_c, continued_fraction_iterator as cf_i, continued_fraction_periodic as cf_p, continued_fraction_reduce as cf_r) from sympy.ntheory.factor_ import factorint, totient from sympy.ntheory.generate import primerange from sympy.ntheory.partitions_ import npartitions from sympy.polys.domains.integerring import ZZ from sympy.polys.orthopolys import legendre_poly from sympy.polys.partfrac import apart from sympy.polys.polytools import Poly, factor, gcd, resultant from sympy.series.limits import limit from sympy.series.order import O from sympy.series.residues import residue from sympy.series.series import series from sympy.sets.fancysets import ImageSet from sympy.sets.sets import FiniteSet, Intersection, Interval, Union from sympy.simplify.combsimp import combsimp from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.powsimp import powdenest, powsimp from sympy.simplify.radsimp import radsimp from sympy.simplify.simplify import logcombine, simplify from sympy.simplify.sqrtdenest import sqrtdenest from sympy.simplify.trigsimp import trigsimp from sympy.solvers.solvers import solve import mpmath from sympy.functions.combinatorial.numbers import stirling from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.error_functions import Ci, Si, erf from sympy.functions.special.zeta_functions import zeta from sympy.testing.pytest import (XFAIL, slow, SKIP, skip, ON_TRAVIS, raises) from sympy.utilities.iterables import partitions from mpmath import mpi, mpc from sympy.matrices import Matrix, GramSchmidt, eye from sympy.matrices.expressions.blockmatrix import BlockMatrix, block_collapse from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix from sympy.physics.quantum import Commutator from sympy.assumptions import assuming from sympy.polys.rings import PolyRing from sympy.polys.fields import FracField from sympy.polys.solvers import solve_lin_sys from sympy.concrete import Sum from sympy.concrete.products import Product from sympy.integrals import integrate from sympy.integrals.transforms import laplace_transform,\ inverse_laplace_transform, LaplaceTransform, fourier_transform,\ mellin_transform from sympy.solvers.recurr import rsolve from sympy.solvers.solveset import solveset, solveset_real, linsolve from sympy.solvers.ode import dsolve from sympy.core.relational import Equality from itertools import islice, takewhile from sympy.series.formal import fps from sympy.series.fourier import fourier_series from sympy.calculus.util import minimum EmptySet = S.EmptySet R = Rational x, y, z = symbols('x y z') i, j, k, l, m, n = symbols('i j k l m n', integer=True) f = Function('f') g = Function('g') # A. Boolean Logic and Quantifier Elimination # Not implemented. # B. Set Theory def test_B1(): assert (FiniteSet(i, j, j, k, k, k) | FiniteSet(l, k, j) | FiniteSet(j, m, j)) == FiniteSet(i, j, k, l, m) def test_B2(): assert (FiniteSet(i, j, j, k, k, k) & FiniteSet(l, k, j) & FiniteSet(j, m, j)) == Intersection({j, m}, {i, j, k}, {j, k, l}) # Previous output below. Not sure why that should be the expected output. # There should probably be a way to rewrite Intersections that way but I # don't see why an Intersection should evaluate like that: # # == Union({j}, Intersection({m}, Union({j, k}, Intersection({i}, {l})))) def test_B3(): assert (FiniteSet(i, j, k, l, m) - FiniteSet(j) == FiniteSet(i, k, l, m)) def test_B4(): assert (FiniteSet(*(FiniteSet(i, j)*FiniteSet(k, l))) == FiniteSet((i, k), (i, l), (j, k), (j, l))) # C. Numbers def test_C1(): assert (factorial(50) == 30414093201713378043612608166064768844377641568960512000000000000) def test_C2(): assert (factorint(factorial(50)) == {2: 47, 3: 22, 5: 12, 7: 8, 11: 4, 13: 3, 17: 2, 19: 2, 23: 2, 29: 1, 31: 1, 37: 1, 41: 1, 43: 1, 47: 1}) def test_C3(): assert (factorial2(10), factorial2(9)) == (3840, 945) # Base conversions; not really implemented by SymPy # Whatever. Take credit! def test_C4(): assert 0xABC == 2748 def test_C5(): assert 123 == int('234', 7) def test_C6(): assert int('677', 8) == int('1BF', 16) == 447 def test_C7(): assert log(32768, 8) == 5 def test_C8(): # Modular multiplicative inverse. Would be nice if divmod could do this. assert ZZ.invert(5, 7) == 3 assert ZZ.invert(5, 6) == 5 def test_C9(): assert igcd(igcd(1776, 1554), 5698) == 74 def test_C10(): x = 0 for n in range(2, 11): x += R(1, n) assert x == R(4861, 2520) def test_C11(): assert R(1, 7) == S('0.[142857]') def test_C12(): assert R(7, 11) * R(22, 7) == 2 def test_C13(): test = R(10, 7) * (1 + R(29, 1000)) ** R(1, 3) good = 3 ** R(1, 3) assert test == good def test_C14(): assert sqrtdenest(sqrt(2*sqrt(3) + 4)) == 1 + sqrt(3) def test_C15(): test = sqrtdenest(sqrt(14 + 3*sqrt(3 + 2*sqrt(5 - 12*sqrt(3 - 2*sqrt(2)))))) good = sqrt(2) + 3 assert test == good def test_C16(): test = sqrtdenest(sqrt(10 + 2*sqrt(6) + 2*sqrt(10) + 2*sqrt(15))) good = sqrt(2) + sqrt(3) + sqrt(5) assert test == good def test_C17(): test = radsimp((sqrt(3) + sqrt(2)) / (sqrt(3) - sqrt(2))) good = 5 + 2*sqrt(6) assert test == good def test_C18(): assert simplify((sqrt(-2 + sqrt(-5)) * sqrt(-2 - sqrt(-5))).expand(complex=True)) == 3 @XFAIL def test_C19(): assert radsimp(simplify((90 + 34*sqrt(7)) ** R(1, 3))) == 3 + sqrt(7) def test_C20(): inside = (135 + 78*sqrt(3)) test = AlgebraicNumber((inside**R(2, 3) + 3) * sqrt(3) / inside**R(1, 3)) assert simplify(test) == AlgebraicNumber(12) def test_C21(): assert simplify(AlgebraicNumber((41 + 29*sqrt(2)) ** R(1, 5))) == \ AlgebraicNumber(1 + sqrt(2)) @XFAIL def test_C22(): test = simplify(((6 - 4*sqrt(2))*log(3 - 2*sqrt(2)) + (3 - 2*sqrt(2))*log(17 - 12*sqrt(2)) + 32 - 24*sqrt(2)) / (48*sqrt(2) - 72)) good = sqrt(2)/3 - log(sqrt(2) - 1)/3 assert test == good def test_C23(): assert 2 * oo - 3 is oo @XFAIL def test_C24(): raise NotImplementedError("2**aleph_null == aleph_1") # D. Numerical Analysis def test_D1(): assert 0.0 / sqrt(2) == 0.0 def test_D2(): assert str(exp(-1000000).evalf()) == '3.29683147808856e-434295' def test_D3(): assert exp(pi*sqrt(163)).evalf(50).num.ae(262537412640768744) def test_D4(): assert floor(R(-5, 3)) == -2 assert ceiling(R(-5, 3)) == -1 @XFAIL def test_D5(): raise NotImplementedError("cubic_spline([1, 2, 4, 5], [1, 4, 2, 3], x)(3) == 27/8") @XFAIL def test_D6(): raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to FORTRAN") @XFAIL def test_D7(): raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to C") @XFAIL def test_D8(): # One way is to cheat by converting the sum to a string, # and replacing the '[' and ']' with ''. # E.g., horner(S(str(_).replace('[','').replace(']',''))) raise NotImplementedError("apply Horner's rule to sum(a[i]*x**i, (i,1,5))") @XFAIL def test_D9(): raise NotImplementedError("translate D8 to FORTRAN") @XFAIL def test_D10(): raise NotImplementedError("translate D8 to C") @XFAIL def test_D11(): #Is there a way to use count_ops? raise NotImplementedError("flops(sum(product(f[i][k], (i,1,k)), (k,1,n)))") @XFAIL def test_D12(): assert (mpi(-4, 2) * x + mpi(1, 3)) ** 2 == mpi(-8, 16)*x**2 + mpi(-24, 12)*x + mpi(1, 9) @XFAIL def test_D13(): raise NotImplementedError("discretize a PDE: diff(f(x,t),t) == diff(diff(f(x,t),x),x)") # E. Statistics # See scipy; all of this is numerical. # F. Combinatorial Theory. def test_F1(): assert rf(x, 3) == x*(1 + x)*(2 + x) def test_F2(): assert expand_func(binomial(n, 3)) == n*(n - 1)*(n - 2)/6 @XFAIL def test_F3(): assert combsimp(2**n * factorial(n) * factorial2(2*n - 1)) == factorial(2*n) @XFAIL def test_F4(): assert combsimp(2**n * factorial(n) * product(2*k - 1, (k, 1, n))) == factorial(2*n) @XFAIL def test_F5(): assert gamma(n + R(1, 2)) / sqrt(pi) / factorial(n) == factorial(2*n)/2**(2*n)/factorial(n)**2 def test_F6(): partTest = [p.copy() for p in partitions(4)] partDesired = [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2:1}, {1: 4}] assert partTest == partDesired def test_F7(): assert npartitions(4) == 5 def test_F8(): assert stirling(5, 2, signed=True) == -50 # if signed, then kind=1 def test_F9(): assert totient(1776) == 576 # G. Number Theory def test_G1(): assert list(primerange(999983, 1000004)) == [999983, 1000003] @XFAIL def test_G2(): raise NotImplementedError("find the primitive root of 191 == 19") @XFAIL def test_G3(): raise NotImplementedError("(a+b)**p mod p == a**p + b**p mod p; p prime") # ... G14 Modular equations are not implemented. def test_G15(): assert Rational(sqrt(3).evalf()).limit_denominator(15) == R(26, 15) assert list(takewhile(lambda x: x.q <= 15, cf_c(cf_i(sqrt(3)))))[-1] == \ R(26, 15) def test_G16(): assert list(islice(cf_i(pi),10)) == [3, 7, 15, 1, 292, 1, 1, 1, 2, 1] def test_G17(): assert cf_p(0, 1, 23) == [4, [1, 3, 1, 8]] def test_G18(): assert cf_p(1, 2, 5) == [[1]] assert cf_r([[1]]).expand() == S.Half + sqrt(5)/2 @XFAIL def test_G19(): s = symbols('s', integer=True, positive=True) it = cf_i((exp(1/s) - 1)/(exp(1/s) + 1)) assert list(islice(it, 5)) == [0, 2*s, 6*s, 10*s, 14*s] def test_G20(): s = symbols('s', integer=True, positive=True) # Wester erroneously has this as -s + sqrt(s**2 + 1) assert cf_r([[2*s]]) == s + sqrt(s**2 + 1) @XFAIL def test_G20b(): s = symbols('s', integer=True, positive=True) assert cf_p(s, 1, s**2 + 1) == [[2*s]] # H. Algebra def test_H1(): assert simplify(2*2**n) == simplify(2**(n + 1)) assert powdenest(2*2**n) == simplify(2**(n + 1)) def test_H2(): assert powsimp(4 * 2**n) == 2**(n + 2) def test_H3(): assert (-1)**(n*(n + 1)) == 1 def test_H4(): expr = factor(6*x - 10) assert type(expr) is Mul assert expr.args[0] == 2 assert expr.args[1] == 3*x - 5 p1 = 64*x**34 - 21*x**47 - 126*x**8 - 46*x**5 - 16*x**60 - 81 p2 = 72*x**60 - 25*x**25 - 19*x**23 - 22*x**39 - 83*x**52 + 54*x**10 + 81 q = 34*x**19 - 25*x**16 + 70*x**7 + 20*x**3 - 91*x - 86 def test_H5(): assert gcd(p1, p2, x) == 1 def test_H6(): assert gcd(expand(p1 * q), expand(p2 * q)) == q def test_H7(): p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z assert gcd(p1, p2, x, y, z) == 1 def test_H8(): p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z q = 11*x**12*y**7*z**13 - 23*x**2*y**8*z**10 + 47*x**17*y**5*z**8 assert gcd(p1 * q, p2 * q, x, y, z) == q def test_H9(): p1 = 2*x**(n + 4) - x**(n + 2) p2 = 4*x**(n + 1) + 3*x**n assert gcd(p1, p2) == x**n def test_H10(): p1 = 3*x**4 + 3*x**3 + x**2 - x - 2 p2 = x**3 - 3*x**2 + x + 5 assert resultant(p1, p2, x) == 0 def test_H11(): assert resultant(p1 * q, p2 * q, x) == 0 def test_H12(): num = x**2 - 4 den = x**2 + 4*x + 4 assert simplify(num/den) == (x - 2)/(x + 2) @XFAIL def test_H13(): assert simplify((exp(x) - 1) / (exp(x/2) + 1)) == exp(x/2) - 1 def test_H14(): p = (x + 1) ** 20 ep = expand(p) assert ep == (1 + 20*x + 190*x**2 + 1140*x**3 + 4845*x**4 + 15504*x**5 + 38760*x**6 + 77520*x**7 + 125970*x**8 + 167960*x**9 + 184756*x**10 + 167960*x**11 + 125970*x**12 + 77520*x**13 + 38760*x**14 + 15504*x**15 + 4845*x**16 + 1140*x**17 + 190*x**18 + 20*x**19 + x**20) dep = diff(ep, x) assert dep == (20 + 380*x + 3420*x**2 + 19380*x**3 + 77520*x**4 + 232560*x**5 + 542640*x**6 + 1007760*x**7 + 1511640*x**8 + 1847560*x**9 + 1847560*x**10 + 1511640*x**11 + 1007760*x**12 + 542640*x**13 + 232560*x**14 + 77520*x**15 + 19380*x**16 + 3420*x**17 + 380*x**18 + 20*x**19) assert factor(dep) == 20*(1 + x)**19 def test_H15(): assert simplify(Mul(*[x - r for r in solveset(x**3 + x**2 - 7)])) == x**3 + x**2 - 7 def test_H16(): assert factor(x**100 - 1) == ((x - 1)*(x + 1)*(x**2 + 1)*(x**4 - x**3 + x**2 - x + 1)*(x**4 + x**3 + x**2 + x + 1)*(x**8 - x**6 + x**4 - x**2 + 1)*(x**20 - x**15 + x**10 - x**5 + 1)*(x**20 + x**15 + x**10 + x**5 + 1)*(x**40 - x**30 + x**20 - x**10 + 1)) def test_H17(): assert simplify(factor(expand(p1 * p2)) - p1*p2) == 0 @XFAIL def test_H18(): # Factor over complex rationals. test = factor(4*x**4 + 8*x**3 + 77*x**2 + 18*x + 153) good = (2*x + 3*I)*(2*x - 3*I)*(x + 1 - 4*I)*(x + 1 + 4*I) assert test == good def test_H19(): a = symbols('a') # The idea is to let a**2 == 2, then solve 1/(a-1). Answer is a+1") assert Poly(a - 1).invert(Poly(a**2 - 2)) == a + 1 @XFAIL def test_H20(): raise NotImplementedError("let a**2==2; (x**3 + (a-2)*x**2 - " + "(2*a+3)*x - 3*a) / (x**2-2) = (x**2 - 2*x - 3) / (x-a)") @XFAIL def test_H21(): raise NotImplementedError("evaluate (b+c)**4 assuming b**3==2, c**2==3. \ Answer is 2*b + 8*c + 18*b**2 + 12*b*c + 9") def test_H22(): assert factor(x**4 - 3*x**2 + 1, modulus=5) == (x - 2)**2 * (x + 2)**2 def test_H23(): f = x**11 + x + 1 g = (x**2 + x + 1) * (x**9 - x**8 + x**6 - x**5 + x**3 - x**2 + 1) assert factor(f, modulus=65537) == g def test_H24(): phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi') assert factor(x**4 - 3*x**2 + 1, extension=phi) == \ (x - phi)*(x + 1 - phi)*(x - 1 + phi)*(x + phi) def test_H25(): e = (x - 2*y**2 + 3*z**3) ** 20 assert factor(expand(e)) == e def test_H26(): g = expand((sin(x) - 2*cos(y)**2 + 3*tan(z)**3)**20) assert factor(g, expand=False) == (-sin(x) + 2*cos(y)**2 - 3*tan(z)**3)**20 def test_H27(): f = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 g = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z h = -2*z*y**7 \ *(6*x**9*y**9*z**3 + 10*x**7*z**6 + 17*y*x**5*z**12 + 40*y**7) \ *(3*x**22 + 47*x**17*y**5*z**8 - 6*x**15*y**9*z**2 - 24*x*y**19*z**8 - 5) assert factor(expand(f*g)) == h @XFAIL def test_H28(): raise NotImplementedError("expand ((1 - c**2)**5 * (1 - s**2)**5 * " + "(c**2 + s**2)**10) with c**2 + s**2 = 1. Answer is c**10*s**10.") @XFAIL def test_H29(): assert factor(4*x**2 - 21*x*y + 20*y**2, modulus=3) == (x + y)*(x - y) def test_H30(): test = factor(x**3 + y**3, extension=sqrt(-3)) answer = (x + y)*(x + y*(-R(1, 2) - sqrt(3)/2*I))*(x + y*(-R(1, 2) + sqrt(3)/2*I)) assert answer == test def test_H31(): f = (x**2 + 2*x + 3)/(x**3 + 4*x**2 + 5*x + 2) g = 2 / (x + 1)**2 - 2 / (x + 1) + 3 / (x + 2) assert apart(f) == g @XFAIL def test_H32(): # issue 6558 raise NotImplementedError("[A*B*C - (A*B*C)**(-1)]*A*C*B (product \ of a non-commuting product and its inverse)") def test_H33(): A, B, C = symbols('A, B, C', commutative=False) assert (Commutator(A, Commutator(B, C)) + Commutator(B, Commutator(C, A)) + Commutator(C, Commutator(A, B))).doit().expand() == 0 # I. Trigonometry def test_I1(): assert tan(pi*R(7, 10)) == -sqrt(1 + 2/sqrt(5)) @XFAIL def test_I2(): assert sqrt((1 + cos(6))/2) == -cos(3) def test_I3(): assert cos(n*pi) + sin((4*n - 1)*pi/2) == (-1)**n - 1 def test_I4(): assert refine(cos(pi*cos(n*pi)) + sin(pi/2*cos(n*pi)), Q.integer(n)) == (-1)**n - 1 @XFAIL def test_I5(): assert sin((n**5/5 + n**4/2 + n**3/3 - n/30) * pi) == 0 @XFAIL def test_I6(): raise NotImplementedError("assuming -3*pi<x<-5*pi/2, abs(cos(x)) == -cos(x), abs(sin(x)) == -sin(x)") @XFAIL def test_I7(): assert cos(3*x)/cos(x) == cos(x)**2 - 3*sin(x)**2 @XFAIL def test_I8(): assert cos(3*x)/cos(x) == 2*cos(2*x) - 1 @XFAIL def test_I9(): # Supposed to do this with rewrite rules. assert cos(3*x)/cos(x) == cos(x)**2 - 3*sin(x)**2 def test_I10(): assert trigsimp((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1)) is nan @SKIP("hangs") @XFAIL def test_I11(): assert limit((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x, 0) != 0 @XFAIL def test_I12(): # This should fail or return nan or something. res = diff((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x) assert res is nan # trigsimp(res) gives nan # J. Special functions. def test_J1(): assert bernoulli(16) == R(-3617, 510) def test_J2(): assert diff(elliptic_e(x, y**2), y) == (elliptic_e(x, y**2) - elliptic_f(x, y**2))/y @XFAIL def test_J3(): raise NotImplementedError("Jacobi elliptic functions: diff(dn(u,k), u) == -k**2*sn(u,k)*cn(u,k)") def test_J4(): assert gamma(R(-1, 2)) == -2*sqrt(pi) def test_J5(): assert polygamma(0, R(1, 3)) == -log(3) - sqrt(3)*pi/6 - EulerGamma - log(sqrt(3)) def test_J6(): assert mpmath.besselj(2, 1 + 1j).ae(mpc('0.04157988694396212', '0.24739764151330632')) def test_J7(): assert simplify(besselj(R(-5,2), pi/2)) == 12/(pi**2) def test_J8(): p = besselj(R(3,2), z) q = (sin(z)/z - cos(z))/sqrt(pi*z/2) assert simplify(expand_func(p) -q) == 0 def test_J9(): assert besselj(0, z).diff(z) == - besselj(1, z) def test_J10(): mu, nu = symbols('mu, nu', integer=True) assert assoc_legendre(nu, mu, 0) == 2**mu*sqrt(pi)/gamma((nu - mu)/2 + 1)/gamma((-nu - mu + 1)/2) def test_J11(): assert simplify(assoc_legendre(3, 1, x)) == simplify(-R(3, 2)*sqrt(1 - x**2)*(5*x**2 - 1)) @slow def test_J12(): assert simplify(chebyshevt(1008, x) - 2*x*chebyshevt(1007, x) + chebyshevt(1006, x)) == 0 def test_J13(): a = symbols('a', integer=True, negative=False) assert chebyshevt(a, -1) == (-1)**a def test_J14(): p = hyper([S.Half, S.Half], [R(3, 2)], z**2) assert hyperexpand(p) == asin(z)/z @XFAIL def test_J15(): raise NotImplementedError("F((n+2)/2,-(n-2)/2,R(3,2),sin(z)**2) == sin(n*z)/(n*sin(z)*cos(z)); F(.) is hypergeometric function") @XFAIL def test_J16(): raise NotImplementedError("diff(zeta(x), x) @ x=0 == -log(2*pi)/2") def test_J17(): assert integrate(f((x + 2)/5)*DiracDelta((x - 2)/3) - g(x)*diff(DiracDelta(x - 1), x), (x, 0, 3)) == 3*f(R(4, 5)) + Subs(Derivative(g(x), x), x, 1) @XFAIL def test_J18(): raise NotImplementedError("define an antisymmetric function") # K. The Complex Domain def test_K1(): z1, z2 = symbols('z1, z2', complex=True) assert re(z1 + I*z2) == -im(z2) + re(z1) assert im(z1 + I*z2) == im(z1) + re(z2) def test_K2(): assert abs(3 - sqrt(7) + I*sqrt(6*sqrt(7) - 15)) == 1 @XFAIL def test_K3(): a, b = symbols('a, b', real=True) assert simplify(abs(1/(a + I/a + I*b))) == 1/sqrt(a**2 + (I/a + b)**2) def test_K4(): assert log(3 + 4*I).expand(complex=True) == log(5) + I*atan(R(4, 3)) def test_K5(): x, y = symbols('x, y', real=True) assert tan(x + I*y).expand(complex=True) == (sin(2*x)/(cos(2*x) + cosh(2*y)) + I*sinh(2*y)/(cos(2*x) + cosh(2*y))) def test_K6(): assert sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) == sqrt(x*y)/sqrt(x) assert sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) != sqrt(y) def test_K7(): y = symbols('y', real=True, negative=False) expr = sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) sexpr = simplify(expr) assert sexpr == sqrt(y) def test_K8(): z = symbols('z', complex=True) assert simplify(sqrt(1/z) - 1/sqrt(z)) != 0 # Passes z = symbols('z', complex=True, negative=False) assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0 # Fails def test_K9(): z = symbols('z', real=True, positive=True) assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0 def test_K10(): z = symbols('z', real=True, negative=True) assert simplify(sqrt(1/z) + 1/sqrt(z)) == 0 # This goes up to K25 # L. Determining Zero Equivalence def test_L1(): assert sqrt(997) - (997**3)**R(1, 6) == 0 def test_L2(): assert sqrt(999983) - (999983**3)**R(1, 6) == 0 def test_L3(): assert simplify((2**R(1, 3) + 4**R(1, 3))**3 - 6*(2**R(1, 3) + 4**R(1, 3)) - 6) == 0 def test_L4(): assert trigsimp(cos(x)**3 + cos(x)*sin(x)**2 - cos(x)) == 0 @XFAIL def test_L5(): assert log(tan(R(1, 2)*x + pi/4)) - asinh(tan(x)) == 0 def test_L6(): assert (log(tan(x/2 + pi/4)) - asinh(tan(x))).diff(x).subs({x: 0}) == 0 @XFAIL def test_L7(): assert simplify(log((2*sqrt(x) + 1)/(sqrt(4*x + 4*sqrt(x) + 1)))) == 0 @XFAIL def test_L8(): assert simplify((4*x + 4*sqrt(x) + 1)**(sqrt(x)/(2*sqrt(x) + 1)) \ *(2*sqrt(x) + 1)**(1/(2*sqrt(x) + 1)) - 2*sqrt(x) - 1) == 0 @XFAIL def test_L9(): z = symbols('z', complex=True) assert simplify(2**(1 - z)*gamma(z)*zeta(z)*cos(z*pi/2) - pi**2*zeta(1 - z)) == 0 # M. Equations @XFAIL def test_M1(): assert Equality(x, 2)/2 + Equality(1, 1) == Equality(x/2 + 1, 2) def test_M2(): # The roots of this equation should all be real. Note that this # doesn't test that they are correct. sol = solveset(3*x**3 - 18*x**2 + 33*x - 19, x) assert all(s.expand(complex=True).is_real for s in sol) @XFAIL def test_M5(): assert solveset(x**6 - 9*x**4 - 4*x**3 + 27*x**2 - 36*x - 23, x) == FiniteSet(2**(1/3) + sqrt(3), 2**(1/3) - sqrt(3), +sqrt(3) - 1/2**(2/3) + I*sqrt(3)/2**(2/3), +sqrt(3) - 1/2**(2/3) - I*sqrt(3)/2**(2/3), -sqrt(3) - 1/2**(2/3) + I*sqrt(3)/2**(2/3), -sqrt(3) - 1/2**(2/3) - I*sqrt(3)/2**(2/3)) def test_M6(): assert set(solveset(x**7 - 1, x)) == \ {cos(n*pi*R(2, 7)) + I*sin(n*pi*R(2, 7)) for n in range(0, 7)} # The paper asks for exp terms, but sin's and cos's may be acceptable; # if the results are simplified, exp terms appear for all but # -sin(pi/14) - I*cos(pi/14) and -sin(pi/14) + I*cos(pi/14) which # will simplify if you apply the transformation foo.rewrite(exp).expand() def test_M7(): # TODO: Replace solve with solveset, as of now test fails for solveset sol = solve(x**8 - 8*x**7 + 34*x**6 - 92*x**5 + 175*x**4 - 236*x**3 + 226*x**2 - 140*x + 46, x) assert [s.simplify() for s in sol] == [ 1 - sqrt(-6 - 2*I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(-6 - 2*I*sqrt(3 + 4*sqrt(3)))/2, 1 - sqrt(-6 + 2*I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(-6 + 2*I*sqrt(3 + 4*sqrt (3)))/2, 1 - sqrt(-6 + 2*sqrt(-3 + 4*sqrt(3)))/2, 1 + sqrt(-6 + 2*sqrt(-3 + 4*sqrt(3)))/2, 1 - sqrt(-6 - 2*sqrt(-3 + 4*sqrt(3)))/2, 1 + sqrt(-6 - 2*sqrt(-3 + 4*sqrt(3)))/2] @XFAIL # There are an infinite number of solutions. def test_M8(): x = Symbol('x') z = symbols('z', complex=True) assert solveset(exp(2*x) + 2*exp(x) + 1 - z, x, S.Reals) == \ FiniteSet(log(1 + z - 2*sqrt(z))/2, log(1 + z + 2*sqrt(z))/2) # This one could be simplified better (the 1/2 could be pulled into the log # as a sqrt, and the function inside the log can be factored as a square, # giving [log(sqrt(z) - 1), log(sqrt(z) + 1)]). Also, there should be an # infinite number of solutions. # x = {log(sqrt(z) - 1), log(sqrt(z) + 1) + i pi} [+ n 2 pi i, + n 2 pi i] # where n is an arbitrary integer. See url of detailed output above. @XFAIL def test_M9(): # x = symbols('x') raise NotImplementedError("solveset(exp(2-x**2)-exp(-x),x) has complex solutions.") def test_M10(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(exp(x) - x, x) == [-LambertW(-1)] @XFAIL def test_M11(): assert solveset(x**x - x, x) == FiniteSet(-1, 1) def test_M12(): # TODO: x = [-1, 2*(+/-asinh(1)*I + n*pi}, 3*(pi/6 + n*pi/3)] # TODO: Replace solve with solveset, as of now test fails for solveset assert solve((x + 1)*(sin(x)**2 + 1)**2*cos(3*x)**3, x) == [ -1, pi/6, pi/2, - I*log(1 + sqrt(2)), I*log(1 + sqrt(2)), pi - I*log(1 + sqrt(2)), pi + I*log(1 + sqrt(2)), ] @XFAIL def test_M13(): n = Dummy('n') assert solveset_real(sin(x) - cos(x), x) == ImageSet(Lambda(n, n*pi - pi*R(7, 4)), S.Integers) @XFAIL def test_M14(): n = Dummy('n') assert solveset_real(tan(x) - 1, x) == ImageSet(Lambda(n, n*pi + pi/4), S.Integers) def test_M15(): n = Dummy('n') got = solveset(sin(x) - S.Half) assert any(got.dummy_eq(i) for i in ( Union(ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi*R(5, 6)), S.Integers)), Union(ImageSet(Lambda(n, 2*n*pi + pi*R(5, 6)), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers)))) @XFAIL def test_M16(): n = Dummy('n') assert solveset(sin(x) - tan(x), x) == ImageSet(Lambda(n, n*pi), S.Integers) @XFAIL def test_M17(): assert solveset_real(asin(x) - atan(x), x) == FiniteSet(0) @XFAIL def test_M18(): assert solveset_real(acos(x) - atan(x), x) == FiniteSet(sqrt((sqrt(5) - 1)/2)) def test_M19(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve((x - 2)/x**R(1, 3), x) == [2] def test_M20(): assert solveset(sqrt(x**2 + 1) - x + 2, x) == EmptySet def test_M21(): assert solveset(x + sqrt(x) - 2) == FiniteSet(1) def test_M22(): assert solveset(2*sqrt(x) + 3*x**R(1, 4) - 2) == FiniteSet(R(1, 16)) def test_M23(): x = symbols('x', complex=True) # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(x - 1/sqrt(1 + x**2)) == [ -I*sqrt(S.Half + sqrt(5)/2), sqrt(Rational(-1, 2) + sqrt(5)/2)] def test_M24(): # TODO: Replace solve with solveset, as of now test fails for solveset solution = solve(1 - binomial(m, 2)*2**k, k) answer = log(2/(m*(m - 1)), 2) assert solution[0].expand() == answer.expand() def test_M25(): a, b, c, d = symbols(':d', positive=True) x = symbols('x') # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(a*b**x - c*d**x, x)[0].expand() == (log(c/a)/log(b/d)).expand() def test_M26(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(sqrt(log(x)) - log(sqrt(x))) == [1, exp(4)] def test_M27(): x = symbols('x', real=True) b = symbols('b', real=True) with assuming(sin(cos(1/E**2) + 1) + b > 0): # TODO: Replace solve with solveset solve(log(acos(asin(x**R(2, 3) - b) - 1)) + 2, x) == [-b - sin(1 + cos(1/E**2))**R(3/2), b + sin(1 + cos(1/E**2))**R(3/2)] @XFAIL def test_M28(): assert solveset_real(5*x + exp((x - 5)/2) - 8*x**3, x, assume=Q.real(x)) == [-0.784966, -0.016291, 0.802557] def test_M29(): x = symbols('x') assert solveset(abs(x - 1) - 2, domain=S.Reals) == FiniteSet(-1, 3) def test_M30(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # assert solve(abs(2*x + 5) - abs(x - 2),x, assume=Q.real(x)) == [-1, -7] assert solveset_real(abs(2*x + 5) - abs(x - 2), x) == FiniteSet(-1, -7) def test_M31(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # assert solve(1 - abs(x) - max(-x - 2, x - 2),x, assume=Q.real(x)) == [-3/2, 3/2] assert solveset_real(1 - abs(x) - Max(-x - 2, x - 2), x) == FiniteSet(R(-3, 2), R(3, 2)) @XFAIL def test_M32(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions assert solveset_real(Max(2 - x**2, x)- Max(-x, (x**3)/9), x) == FiniteSet(-1, 3) @XFAIL def test_M33(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # Second answer can be written in another form. The second answer is the root of x**3 + 9*x**2 - 18 = 0 in the interval (-2, -1). assert solveset_real(Max(2 - x**2, x) - x**3/9, x) == FiniteSet(-3, -1.554894, 3) @XFAIL def test_M34(): z = symbols('z', complex=True) assert solveset((1 + I) * z + (2 - I) * conjugate(z) + 3*I, z) == FiniteSet(2 + 3*I) def test_M35(): x, y = symbols('x y', real=True) assert linsolve((3*x - 2*y - I*y + 3*I).as_real_imag(), y, x) == FiniteSet((3, 2)) def test_M36(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports solving for function # assert solve(f**2 + f - 2, x) == [Eq(f(x), 1), Eq(f(x), -2)] assert solveset(f(x)**2 + f(x) - 2, f(x)) == FiniteSet(-2, 1) def test_M37(): assert linsolve([x + y + z - 6, 2*x + y + 2*z - 10, x + 3*y + z - 10 ], x, y, z) == \ FiniteSet((-z + 4, 2, z)) def test_M38(): a, b, c = symbols('a, b, c') domain = FracField([a, b, c], ZZ).to_domain() ring = PolyRing('k1:50', domain) (k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k20, k21, k22, k23, k24, k25, k26, k27, k28, k29, k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k40, k41, k42, k43, k44, k45, k46, k47, k48, k49) = ring.gens system = [ -b*k8/a + c*k8/a, -b*k11/a + c*k11/a, -b*k10/a + c*k10/a + k2, -k3 - b*k9/a + c*k9/a, -b*k14/a + c*k14/a, -b*k15/a + c*k15/a, -b*k18/a + c*k18/a - k2, -b*k17/a + c*k17/a, -b*k16/a + c*k16/a + k4, -b*k13/a + c*k13/a - b*k21/a + c*k21/a + b*k5/a - c*k5/a, b*k44/a - c*k44/a, -b*k45/a + c*k45/a, -b*k20/a + c*k20/a, -b*k44/a + c*k44/a, b*k46/a - c*k46/a, b**2*k47/a**2 - 2*b*c*k47/a**2 + c**2*k47/a**2, k3, -k4, -b*k12/a + c*k12/a - a*k6/b + c*k6/b, -b*k19/a + c*k19/a + a*k7/c - b*k7/c, b*k45/a - c*k45/a, -b*k46/a + c*k46/a, -k48 + c*k48/a + c*k48/b - c**2*k48/(a*b), -k49 + b*k49/a + b*k49/c - b**2*k49/(a*c), a*k1/b - c*k1/b, a*k4/b - c*k4/b, a*k3/b - c*k3/b + k9, -k10 + a*k2/b - c*k2/b, a*k7/b - c*k7/b, -k9, k11, b*k12/a - c*k12/a + a*k6/b - c*k6/b, a*k15/b - c*k15/b, k10 + a*k18/b - c*k18/b, -k11 + a*k17/b - c*k17/b, a*k16/b - c*k16/b, -a*k13/b + c*k13/b + a*k21/b - c*k21/b + a*k5/b - c*k5/b, -a*k44/b + c*k44/b, a*k45/b - c*k45/b, a*k14/c - b*k14/c + a*k20/b - c*k20/b, a*k44/b - c*k44/b, -a*k46/b + c*k46/b, -k47 + c*k47/a + c*k47/b - c**2*k47/(a*b), a*k19/b - c*k19/b, -a*k45/b + c*k45/b, a*k46/b - c*k46/b, a**2*k48/b**2 - 2*a*c*k48/b**2 + c**2*k48/b**2, -k49 + a*k49/b + a*k49/c - a**2*k49/(b*c), k16, -k17, -a*k1/c + b*k1/c, -k16 - a*k4/c + b*k4/c, -a*k3/c + b*k3/c, k18 - a*k2/c + b*k2/c, b*k19/a - c*k19/a - a*k7/c + b*k7/c, -a*k6/c + b*k6/c, -a*k8/c + b*k8/c, -a*k11/c + b*k11/c + k17, -a*k10/c + b*k10/c - k18, -a*k9/c + b*k9/c, -a*k14/c + b*k14/c - a*k20/b + c*k20/b, -a*k13/c + b*k13/c + a*k21/c - b*k21/c - a*k5/c + b*k5/c, a*k44/c - b*k44/c, -a*k45/c + b*k45/c, -a*k44/c + b*k44/c, a*k46/c - b*k46/c, -k47 + b*k47/a + b*k47/c - b**2*k47/(a*c), -a*k12/c + b*k12/c, a*k45/c - b*k45/c, -a*k46/c + b*k46/c, -k48 + a*k48/b + a*k48/c - a**2*k48/(b*c), a**2*k49/c**2 - 2*a*b*k49/c**2 + b**2*k49/c**2, k8, k11, -k15, k10 - k18, -k17, k9, -k16, -k29, k14 - k32, -k21 + k23 - k31, -k24 - k30, -k35, k44, -k45, k36, k13 - k23 + k39, -k20 + k38, k25 + k37, b*k26/a - c*k26/a - k34 + k42, -2*k44, k45, k46, b*k47/a - c*k47/a, k41, k44, -k46, -b*k47/a + c*k47/a, k12 + k24, -k19 - k25, -a*k27/b + c*k27/b - k33, k45, -k46, -a*k48/b + c*k48/b, a*k28/c - b*k28/c + k40, -k45, k46, a*k48/b - c*k48/b, a*k49/c - b*k49/c, -a*k49/c + b*k49/c, -k1, -k4, -k3, k15, k18 - k2, k17, k16, k22, k25 - k7, k24 + k30, k21 + k23 - k31, k28, -k44, k45, -k30 - k6, k20 + k32, k27 + b*k33/a - c*k33/a, k44, -k46, -b*k47/a + c*k47/a, -k36, k31 - k39 - k5, -k32 - k38, k19 - k37, k26 - a*k34/b + c*k34/b - k42, k44, -2*k45, k46, a*k48/b - c*k48/b, a*k35/c - b*k35/c - k41, -k44, k46, b*k47/a - c*k47/a, -a*k49/c + b*k49/c, -k40, k45, -k46, -a*k48/b + c*k48/b, a*k49/c - b*k49/c, k1, k4, k3, -k8, -k11, -k10 + k2, -k9, k37 + k7, -k14 - k38, -k22, -k25 - k37, -k24 + k6, -k13 - k23 + k39, -k28 + b*k40/a - c*k40/a, k44, -k45, -k27, -k44, k46, b*k47/a - c*k47/a, k29, k32 + k38, k31 - k39 + k5, -k12 + k30, k35 - a*k41/b + c*k41/b, -k44, k45, -k26 + k34 + a*k42/c - b*k42/c, k44, k45, -2*k46, -b*k47/a + c*k47/a, -a*k48/b + c*k48/b, a*k49/c - b*k49/c, k33, -k45, k46, a*k48/b - c*k48/b, -a*k49/c + b*k49/c ] solution = { k49: 0, k48: 0, k47: 0, k46: 0, k45: 0, k44: 0, k41: 0, k40: 0, k38: 0, k37: 0, k36: 0, k35: 0, k33: 0, k32: 0, k30: 0, k29: 0, k28: 0, k27: 0, k25: 0, k24: 0, k22: 0, k21: 0, k20: 0, k19: 0, k18: 0, k17: 0, k16: 0, k15: 0, k14: 0, k13: 0, k12: 0, k11: 0, k10: 0, k9: 0, k8: 0, k7: 0, k6: 0, k5: 0, k4: 0, k3: 0, k2: 0, k1: 0, k34: b/c*k42, k31: k39, k26: a/c*k42, k23: k39 } assert solve_lin_sys(system, ring) == solution def test_M39(): x, y, z = symbols('x y z', complex=True) # TODO: Replace solve with solveset, as of now # solveset doesn't supports non-linear multivariate assert solve([x**2*y + 3*y*z - 4, -3*x**2*z + 2*y**2 + 1, 2*y*z**2 - z**2 - 1 ]) ==\ [{y: 1, z: 1, x: -1}, {y: 1, z: 1, x: 1},\ {y: sqrt(2)*I, z: R(1,3) - sqrt(2)*I/3, x: -sqrt(-1 - sqrt(2)*I)},\ {y: sqrt(2)*I, z: R(1,3) - sqrt(2)*I/3, x: sqrt(-1 - sqrt(2)*I)},\ {y: -sqrt(2)*I, z: R(1,3) + sqrt(2)*I/3, x: -sqrt(-1 + sqrt(2)*I)},\ {y: -sqrt(2)*I, z: R(1,3) + sqrt(2)*I/3, x: sqrt(-1 + sqrt(2)*I)}] # N. Inequalities def test_N1(): assert ask(E**pi > pi**E) @XFAIL def test_N2(): x = symbols('x', real=True) assert ask(x**4 - x + 1 > 0) is True assert ask(x**4 - x + 1 > 1) is False @XFAIL def test_N3(): x = symbols('x', real=True) assert ask(And(Lt(-1, x), Lt(x, 1)), abs(x) < 1 ) @XFAIL def test_N4(): x, y = symbols('x y', real=True) assert ask(2*x**2 > 2*y**2, (x > y) & (y > 0)) is True @XFAIL def test_N5(): x, y, k = symbols('x y k', real=True) assert ask(k*x**2 > k*y**2, (x > y) & (y > 0) & (k > 0)) is True @slow @XFAIL def test_N6(): x, y, k, n = symbols('x y k n', real=True) assert ask(k*x**n > k*y**n, (x > y) & (y > 0) & (k > 0) & (n > 0)) is True @XFAIL def test_N7(): x, y = symbols('x y', real=True) assert ask(y > 0, (x > 1) & (y >= x - 1)) is True @XFAIL @slow def test_N8(): x, y, z = symbols('x y z', real=True) assert ask(Eq(x, y) & Eq(y, z), (x >= y) & (y >= z) & (z >= x)) def test_N9(): x = Symbol('x') assert solveset(abs(x - 1) > 2, domain=S.Reals) == Union(Interval(-oo, -1, False, True), Interval(3, oo, True)) def test_N10(): x = Symbol('x') p = (x - 1)*(x - 2)*(x - 3)*(x - 4)*(x - 5) assert solveset(expand(p) < 0, domain=S.Reals) == Union(Interval(-oo, 1, True, True), Interval(2, 3, True, True), Interval(4, 5, True, True)) def test_N11(): x = Symbol('x') assert solveset(6/(x - 3) <= 3, domain=S.Reals) == Union(Interval(-oo, 3, True, True), Interval(5, oo)) def test_N12(): x = Symbol('x') assert solveset(sqrt(x) < 2, domain=S.Reals) == Interval(0, 4, False, True) def test_N13(): x = Symbol('x') assert solveset(sin(x) < 2, domain=S.Reals) == S.Reals @XFAIL def test_N14(): x = Symbol('x') # Gives 'Union(Interval(Integer(0), Mul(Rational(1, 2), pi), false, true), # Interval(Mul(Rational(1, 2), pi), Mul(Integer(2), pi), true, false))' # which is not the correct answer, but the provided also seems wrong. assert solveset(sin(x) < 1, x, domain=S.Reals) == Union(Interval(-oo, pi/2, True, True), Interval(pi/2, oo, True, True)) def test_N15(): r, t = symbols('r t') # raises NotImplementedError: only univariate inequalities are supported solveset(abs(2*r*(cos(t) - 1) + 1) <= 1, r, S.Reals) def test_N16(): r, t = symbols('r t') solveset((r**2)*((cos(t) - 4)**2)*sin(t)**2 < 9, r, S.Reals) @XFAIL def test_N17(): # currently only univariate inequalities are supported assert solveset((x + y > 0, x - y < 0), (x, y)) == (abs(x) < y) def test_O1(): M = Matrix((1 + I, -2, 3*I)) assert sqrt(expand(M.dot(M.H))) == sqrt(15) def test_O2(): assert Matrix((2, 2, -3)).cross(Matrix((1, 3, 1))) == Matrix([[11], [-5], [4]]) # The vector module has no way of representing vectors symbolically (without # respect to a basis) @XFAIL def test_O3(): # assert (va ^ vb) | (vc ^ vd) == -(va | vc)*(vb | vd) + (va | vd)*(vb | vc) raise NotImplementedError("""The vector module has no way of representing vectors symbolically (without respect to a basis)""") def test_O4(): from sympy.vector import CoordSys3D, Del N = CoordSys3D("N") delop = Del() i, j, k = N.base_vectors() x, y, z = N.base_scalars() F = i*(x*y*z) + j*((x*y*z)**2) + k*((y**2)*(z**3)) assert delop.cross(F).doit() == (-2*x**2*y**2*z + 2*y*z**3)*i + x*y*j + (2*x*y**2*z**2 - x*z)*k @XFAIL def test_O5(): #assert grad|(f^g)-g|(grad^f)+f|(grad^g) == 0 raise NotImplementedError("""The vector module has no way of representing vectors symbolically (without respect to a basis)""") #testO8-O9 MISSING!! def test_O10(): L = [Matrix([2, 3, 5]), Matrix([3, 6, 2]), Matrix([8, 3, 6])] assert GramSchmidt(L) == [Matrix([ [2], [3], [5]]), Matrix([ [R(23, 19)], [R(63, 19)], [R(-47, 19)]]), Matrix([ [R(1692, 353)], [R(-1551, 706)], [R(-423, 706)]])] def test_P1(): assert Matrix(3, 3, lambda i, j: j - i).diagonal(-1) == Matrix( 1, 2, [-1, -1]) def test_P2(): M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) M.row_del(1) M.col_del(2) assert M == Matrix([[1, 2], [7, 8]]) def test_P3(): A = Matrix([ [11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]) A11 = A[0:3, 1:4] A12 = A[(0, 1, 3), (2, 0, 3)] A21 = A A221 = -A[0:2, 2:4] A222 = -A[(3, 0), (2, 1)] A22 = BlockMatrix([[A221, A222]]).T rows = [[-A11, A12], [A21, A22]] raises(ValueError, lambda: BlockMatrix(rows)) B = Matrix(rows) assert B == Matrix([ [-12, -13, -14, 13, 11, 14], [-22, -23, -24, 23, 21, 24], [-32, -33, -34, 43, 41, 44], [11, 12, 13, 14, -13, -23], [21, 22, 23, 24, -14, -24], [31, 32, 33, 34, -43, -13], [41, 42, 43, 44, -42, -12]]) @XFAIL def test_P4(): raise NotImplementedError("Block matrix diagonalization not supported") def test_P5(): M = Matrix([[7, 11], [3, 8]]) assert M % 2 == Matrix([[1, 1], [1, 0]]) def test_P6(): M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]]) assert M.diff(x, 2) == Matrix([[-cos(x), -sin(x)], [sin(x), -cos(x)]]) def test_P7(): M = Matrix([[x, y]])*( z*Matrix([[1, 3, 5], [2, 4, 6]]) + Matrix([[7, -9, 11], [-8, 10, -12]])) assert M == Matrix([[x*(z + 7) + y*(2*z - 8), x*(3*z - 9) + y*(4*z + 10), x*(5*z + 11) + y*(6*z - 12)]]) def test_P8(): M = Matrix([[1, -2*I], [-3*I, 4]]) assert M.norm(ord=S.Infinity) == 7 def test_P9(): a, b, c = symbols('a b c', nonzero=True) M = Matrix([[a/(b*c), 1/c, 1/b], [1/c, b/(a*c), 1/a], [1/b, 1/a, c/(a*b)]]) assert factor(M.norm('fro')) == (a**2 + b**2 + c**2)/(abs(a)*abs(b)*abs(c)) @XFAIL def test_P10(): M = Matrix([[1, 2 + 3*I], [f(4 - 5*I), 6]]) # conjugate(f(4 - 5*i)) is not simplified to f(4+5*I) assert M.H == Matrix([[1, f(4 + 5*I)], [2 + 3*I, 6]]) @XFAIL def test_P11(): # raises NotImplementedError("Matrix([[x,y],[1,x*y]]).inv() # not simplifying to extract common factor") assert Matrix([[x, y], [1, x*y]]).inv() == (1/(x**2 - 1))*Matrix([[x, -1], [-1/y, x/y]]) def test_P11_workaround(): # This test was changed to inverse method ADJ because it depended on the # specific form of inverse returned from the 'GE' method which has changed. M = Matrix([[x, y], [1, x*y]]).inv('ADJ') c = gcd(tuple(M)) assert MatMul(c, M/c, evaluate=False) == MatMul(c, Matrix([ [x*y, -y], [ -1, x]]), evaluate=False) def test_P12(): A11 = MatrixSymbol('A11', n, n) A12 = MatrixSymbol('A12', n, n) A22 = MatrixSymbol('A22', n, n) B = BlockMatrix([[A11, A12], [ZeroMatrix(n, n), A22]]) assert block_collapse(B.I) == BlockMatrix([[A11.I, (-1)*A11.I*A12*A22.I], [ZeroMatrix(n, n), A22.I]]) def test_P13(): M = Matrix([[1, x - 2, x - 3], [x - 1, x**2 - 3*x + 6, x**2 - 3*x - 2], [x - 2, x**2 - 8, 2*(x**2) - 12*x + 14]]) L, U, _ = M.LUdecomposition() assert simplify(L) == Matrix([[1, 0, 0], [x - 1, 1, 0], [x - 2, x - 3, 1]]) assert simplify(U) == Matrix([[1, x - 2, x - 3], [0, 4, x - 5], [0, 0, x - 7]]) def test_P14(): M = Matrix([[1, 2, 3, 1, 3], [3, 2, 1, 1, 7], [0, 2, 4, 1, 1], [1, 1, 1, 1, 4]]) R, _ = M.rref() assert R == Matrix([[1, 0, -1, 0, 2], [0, 1, 2, 0, -1], [0, 0, 0, 1, 3], [0, 0, 0, 0, 0]]) def test_P15(): M = Matrix([[-1, 3, 7, -5], [4, -2, 1, 3], [2, 4, 15, -7]]) assert M.rank() == 2 def test_P16(): M = Matrix([[2*sqrt(2), 8], [6*sqrt(6), 24*sqrt(3)]]) assert M.rank() == 1 def test_P17(): t = symbols('t', real=True) M=Matrix([ [sin(2*t), cos(2*t)], [2*(1 - (cos(t)**2))*cos(t), (1 - 2*(sin(t)**2))*sin(t)]]) assert M.rank() == 1 def test_P18(): M = Matrix([[1, 0, -2, 0], [-2, 1, 0, 3], [-1, 2, -6, 6]]) assert M.nullspace() == [Matrix([[2], [4], [1], [0]]), Matrix([[0], [-3], [0], [1]])] def test_P19(): w = symbols('w') M = Matrix([[1, 1, 1, 1], [w, x, y, z], [w**2, x**2, y**2, z**2], [w**3, x**3, y**3, z**3]]) assert M.det() == (w**3*x**2*y - w**3*x**2*z - w**3*x*y**2 + w**3*x*z**2 + w**3*y**2*z - w**3*y*z**2 - w**2*x**3*y + w**2*x**3*z + w**2*x*y**3 - w**2*x*z**3 - w**2*y**3*z + w**2*y*z**3 + w*x**3*y**2 - w*x**3*z**2 - w*x**2*y**3 + w*x**2*z**3 + w*y**3*z**2 - w*y**2*z**3 - x**3*y**2*z + x**3*y*z**2 + x**2*y**3*z - x**2*y*z**3 - x*y**3*z**2 + x*y**2*z**3 ) @XFAIL def test_P20(): raise NotImplementedError("Matrix minimal polynomial not supported") def test_P21(): M = Matrix([[5, -3, -7], [-2, 1, 2], [2, -3, -4]]) assert M.charpoly(x).as_expr() == x**3 - 2*x**2 - 5*x + 6 def test_P22(): d = 100 M = (2 - x)*eye(d) assert M.eigenvals() == {-x + 2: d} def test_P23(): M = Matrix([ [2, 1, 0, 0, 0], [1, 2, 1, 0, 0], [0, 1, 2, 1, 0], [0, 0, 1, 2, 1], [0, 0, 0, 1, 2]]) assert M.eigenvals() == { S('1'): 1, S('2'): 1, S('3'): 1, S('sqrt(3) + 2'): 1, S('-sqrt(3) + 2'): 1} def test_P24(): M = Matrix([[611, 196, -192, 407, -8, -52, -49, 29], [196, 899, 113, -192, -71, -43, -8, -44], [-192, 113, 899, 196, 61, 49, 8, 52], [ 407, -192, 196, 611, 8, 44, 59, -23], [ -8, -71, 61, 8, 411, -599, 208, 208], [ -52, -43, 49, 44, -599, 411, 208, 208], [ -49, -8, 8, 59, 208, 208, 99, -911], [ 29, -44, 52, -23, 208, 208, -911, 99]]) assert M.eigenvals() == { S('0'): 1, S('10*sqrt(10405)'): 1, S('100*sqrt(26) + 510'): 1, S('1000'): 2, S('-100*sqrt(26) + 510'): 1, S('-10*sqrt(10405)'): 1, S('1020'): 1} def test_P25(): MF = N(Matrix([[ 611, 196, -192, 407, -8, -52, -49, 29], [ 196, 899, 113, -192, -71, -43, -8, -44], [-192, 113, 899, 196, 61, 49, 8, 52], [ 407, -192, 196, 611, 8, 44, 59, -23], [ -8, -71, 61, 8, 411, -599, 208, 208], [ -52, -43, 49, 44, -599, 411, 208, 208], [ -49, -8, 8, 59, 208, 208, 99, -911], [ 29, -44, 52, -23, 208, 208, -911, 99]])) ev_1 = sorted(MF.eigenvals(multiple=True)) ev_2 = sorted( [-1020.0490184299969, 0.0, 0.09804864072151699, 1000.0, 1000.0, 1019.9019513592784, 1020.0, 1020.0490184299969]) for x, y in zip(ev_1, ev_2): assert abs(x - y) < 1e-12 def test_P26(): a0, a1, a2, a3, a4 = symbols('a0 a1 a2 a3 a4') M = Matrix([[-a4, -a3, -a2, -a1, -a0, 0, 0, 0, 0], [ 1, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 1, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 1, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 1, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, -1, -1, 0, 0], [ 0, 0, 0, 0, 0, 1, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 1, -1, -1], [ 0, 0, 0, 0, 0, 0, 0, 1, 0]]) assert M.eigenvals(error_when_incomplete=False) == { S('-1/2 - sqrt(3)*I/2'): 2, S('-1/2 + sqrt(3)*I/2'): 2} def test_P27(): a = symbols('a') M = Matrix([[a, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, a, 0, 0], [0, 0, 0, a, 0], [0, -2, 0, 0, 2]]) assert M.eigenvects() == [ (a, 3, [ Matrix([1, 0, 0, 0, 0]), Matrix([0, 0, 1, 0, 0]), Matrix([0, 0, 0, 1, 0]) ]), (1 - I, 1, [ Matrix([0, (1 + I)/2, 0, 0, 1]) ]), (1 + I, 1, [ Matrix([0, (1 - I)/2, 0, 0, 1]) ]), ] @XFAIL def test_P28(): raise NotImplementedError("Generalized eigenvectors not supported \ https://github.com/sympy/sympy/issues/5293") @XFAIL def test_P29(): raise NotImplementedError("Generalized eigenvectors not supported \ https://github.com/sympy/sympy/issues/5293") def test_P30(): M = Matrix([[1, 0, 0, 1, -1], [0, 1, -2, 3, -3], [0, 0, -1, 2, -2], [1, -1, 1, 0, 1], [1, -1, 1, -1, 2]]) _, J = M.jordan_form() assert J == Matrix([[-1, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0, 1]]) @XFAIL def test_P31(): raise NotImplementedError("Smith normal form not implemented") def test_P32(): M = Matrix([[1, -2], [2, 1]]) assert exp(M).rewrite(cos).simplify() == Matrix([[E*cos(2), -E*sin(2)], [E*sin(2), E*cos(2)]]) def test_P33(): w, t = symbols('w t') M = Matrix([[0, 1, 0, 0], [0, 0, 0, 2*w], [0, 0, 0, 1], [0, -2*w, 3*w**2, 0]]) assert exp(M*t).rewrite(cos).expand() == Matrix([ [1, -3*t + 4*sin(t*w)/w, 6*t*w - 6*sin(t*w), -2*cos(t*w)/w + 2/w], [0, 4*cos(t*w) - 3, -6*w*cos(t*w) + 6*w, 2*sin(t*w)], [0, 2*cos(t*w)/w - 2/w, -3*cos(t*w) + 4, sin(t*w)/w], [0, -2*sin(t*w), 3*w*sin(t*w), cos(t*w)]]) @XFAIL def test_P34(): a, b, c = symbols('a b c', real=True) M = Matrix([[a, 1, 0, 0, 0, 0], [0, a, 0, 0, 0, 0], [0, 0, b, 0, 0, 0], [0, 0, 0, c, 1, 0], [0, 0, 0, 0, c, 1], [0, 0, 0, 0, 0, c]]) # raises exception, sin(M) not supported. exp(M*I) also not supported # https://github.com/sympy/sympy/issues/6218 assert sin(M) == Matrix([[sin(a), cos(a), 0, 0, 0, 0], [0, sin(a), 0, 0, 0, 0], [0, 0, sin(b), 0, 0, 0], [0, 0, 0, sin(c), cos(c), -sin(c)/2], [0, 0, 0, 0, sin(c), cos(c)], [0, 0, 0, 0, 0, sin(c)]]) @XFAIL def test_P35(): M = pi/2*Matrix([[2, 1, 1], [2, 3, 2], [1, 1, 2]]) # raises exception, sin(M) not supported. exp(M*I) also not supported # https://github.com/sympy/sympy/issues/6218 assert sin(M) == eye(3) @XFAIL def test_P36(): M = Matrix([[10, 7], [7, 17]]) assert sqrt(M) == Matrix([[3, 1], [1, 4]]) def test_P37(): M = Matrix([[1, 1, 0], [0, 1, 0], [0, 0, 1]]) assert M**S.Half == Matrix([[1, R(1, 2), 0], [0, 1, 0], [0, 0, 1]]) @XFAIL def test_P38(): M=Matrix([[0, 1, 0], [0, 0, 0], [0, 0, 0]]) #raises ValueError: Matrix det == 0; not invertible M**S.Half @XFAIL def test_P39(): """ M=Matrix([ [1, 1], [2, 2], [3, 3]]) M.SVD() """ raise NotImplementedError("Singular value decomposition not implemented") def test_P40(): r, t = symbols('r t', real=True) M = Matrix([r*cos(t), r*sin(t)]) assert M.jacobian(Matrix([r, t])) == Matrix([[cos(t), -r*sin(t)], [sin(t), r*cos(t)]]) def test_P41(): r, t = symbols('r t', real=True) assert hessian(r**2*sin(t),(r,t)) == Matrix([[ 2*sin(t), 2*r*cos(t)], [2*r*cos(t), -r**2*sin(t)]]) def test_P42(): assert wronskian([cos(x), sin(x)], x).simplify() == 1 def test_P43(): def __my_jacobian(M, Y): return Matrix([M.diff(v).T for v in Y]).T r, t = symbols('r t', real=True) M = Matrix([r*cos(t), r*sin(t)]) assert __my_jacobian(M,[r,t]) == Matrix([[cos(t), -r*sin(t)], [sin(t), r*cos(t)]]) def test_P44(): def __my_hessian(f, Y): V = Matrix([diff(f, v) for v in Y]) return Matrix([V.T.diff(v) for v in Y]) r, t = symbols('r t', real=True) assert __my_hessian(r**2*sin(t), (r, t)) == Matrix([ [ 2*sin(t), 2*r*cos(t)], [2*r*cos(t), -r**2*sin(t)]]) def test_P45(): def __my_wronskian(Y, v): M = Matrix([Matrix(Y).T.diff(x, n) for n in range(0, len(Y))]) return M.det() assert __my_wronskian([cos(x), sin(x)], x).simplify() == 1 # Q1-Q6 Tensor tests missing @XFAIL def test_R1(): i, j, n = symbols('i j n', integer=True, positive=True) xn = MatrixSymbol('xn', n, 1) Sm = Sum((xn[i, 0] - Sum(xn[j, 0], (j, 0, n - 1))/n)**2, (i, 0, n - 1)) # sum does not calculate # Unknown result Sm.doit() raise NotImplementedError('Unknown result') @XFAIL def test_R2(): m, b = symbols('m b') i, n = symbols('i n', integer=True, positive=True) xn = MatrixSymbol('xn', n, 1) yn = MatrixSymbol('yn', n, 1) f = Sum((yn[i, 0] - m*xn[i, 0] - b)**2, (i, 0, n - 1)) f1 = diff(f, m) f2 = diff(f, b) # raises TypeError: solveset() takes at most 2 arguments (3 given) solveset((f1, f2), (m, b), domain=S.Reals) @XFAIL def test_R3(): n, k = symbols('n k', integer=True, positive=True) sk = ((-1)**k) * (binomial(2*n, k))**2 Sm = Sum(sk, (k, 1, oo)) T = Sm.doit() T2 = T.combsimp() # returns -((-1)**n*factorial(2*n) # - (factorial(n))**2)*exp_polar(-I*pi)/(factorial(n))**2 assert T2 == (-1)**n*binomial(2*n, n) @XFAIL def test_R4(): # Macsyma indefinite sum test case: #(c15) /* Check whether the full Gosper algorithm is implemented # => 1/2^(n + 1) binomial(n, k - 1) */ #closedform(indefsum(binomial(n, k)/2^n - binomial(n + 1, k)/2^(n + 1), k)); #Time= 2690 msecs # (- n + k - 1) binomial(n + 1, k) #(d15) - -------------------------------- # n # 2 2 (n + 1) # #(c16) factcomb(makefact(%)); #Time= 220 msecs # n! #(d16) ---------------- # n # 2 k! 2 (n - k)! # Might be possible after fixing https://github.com/sympy/sympy/pull/1879 raise NotImplementedError("Indefinite sum not supported") @XFAIL def test_R5(): a, b, c, n, k = symbols('a b c n k', integer=True, positive=True) sk = ((-1)**k)*(binomial(a + b, a + k) *binomial(b + c, b + k)*binomial(c + a, c + k)) Sm = Sum(sk, (k, 1, oo)) T = Sm.doit() # hypergeometric series not calculated assert T == factorial(a+b+c)/(factorial(a)*factorial(b)*factorial(c)) def test_R6(): n, k = symbols('n k', integer=True, positive=True) gn = MatrixSymbol('gn', n + 2, 1) Sm = Sum(gn[k, 0] - gn[k - 1, 0], (k, 1, n + 1)) assert Sm.doit() == -gn[0, 0] + gn[n + 1, 0] def test_R7(): n, k = symbols('n k', integer=True, positive=True) T = Sum(k**3,(k,1,n)).doit() assert T.factor() == n**2*(n + 1)**2/4 @XFAIL def test_R8(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(k**2*binomial(n, k), (k, 1, n)) T = Sm.doit() #returns Piecewise function assert T.combsimp() == n*(n + 1)*2**(n - 2) def test_R9(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n, k - 1)/k, (k, 1, n + 1)) assert Sm.doit().simplify() == (2**(n + 1) - 1)/(n + 1) @XFAIL def test_R10(): n, m, r, k = symbols('n m r k', integer=True, positive=True) Sm = Sum(binomial(n, k)*binomial(m, r - k), (k, 0, r)) T = Sm.doit() T2 = T.combsimp().rewrite(factorial) assert T2 == factorial(m + n)/(factorial(r)*factorial(m + n - r)) assert T2 == binomial(m + n, r).rewrite(factorial) # rewrite(binomial) is not working. # https://github.com/sympy/sympy/issues/7135 T3 = T2.rewrite(binomial) assert T3 == binomial(m + n, r) @XFAIL def test_R11(): n, k = symbols('n k', integer=True, positive=True) sk = binomial(n, k)*fibonacci(k) Sm = Sum(sk, (k, 0, n)) T = Sm.doit() # Fibonacci simplification not implemented # https://github.com/sympy/sympy/issues/7134 assert T == fibonacci(2*n) @XFAIL def test_R12(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(fibonacci(k)**2, (k, 0, n)) T = Sm.doit() assert T == fibonacci(n)*fibonacci(n + 1) @XFAIL def test_R13(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(sin(k*x), (k, 1, n)) T = Sm.doit() # Sum is not calculated assert T.simplify() == cot(x/2)/2 - cos(x*(2*n + 1)/2)/(2*sin(x/2)) @XFAIL def test_R14(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(sin((2*k - 1)*x), (k, 1, n)) T = Sm.doit() # Sum is not calculated assert T.simplify() == sin(n*x)**2/sin(x) @XFAIL def test_R15(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n - k, k), (k, 0, floor(n/2))) T = Sm.doit() # Sum is not calculated assert T.simplify() == fibonacci(n + 1) def test_R16(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/k**2 + 1/k**3, (k, 1, oo)) assert Sm.doit() == zeta(3) + pi**2/6 def test_R17(): k = symbols('k', integer=True, positive=True) assert abs(float(Sum(1/k**2 + 1/k**3, (k, 1, oo))) - 2.8469909700078206) < 1e-15 def test_R18(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/(2**k*k**2), (k, 1, oo)) T = Sm.doit() assert T.simplify() == -log(2)**2/2 + pi**2/12 @slow @XFAIL def test_R19(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/((3*k + 1)*(3*k + 2)*(3*k + 3)), (k, 0, oo)) T = Sm.doit() # assert fails, T not simplified assert T.simplify() == -log(3)/4 + sqrt(3)*pi/12 @XFAIL def test_R20(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n, 4*k), (k, 0, oo)) T = Sm.doit() # assert fails, T not simplified assert T.simplify() == 2**(n/2)*cos(pi*n/4)/2 + 2**(n - 1)/2 @XFAIL def test_R21(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/(sqrt(k*(k + 1)) * (sqrt(k) + sqrt(k + 1))), (k, 1, oo)) T = Sm.doit() # Sum not calculated assert T.simplify() == 1 # test_R22 answer not available in Wester samples # Sum(Sum(binomial(n, k)*binomial(n - k, n - 2*k)*x**n*y**(n - 2*k), # (k, 0, floor(n/2))), (n, 0, oo)) with abs(x*y)<1? @XFAIL def test_R23(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(Sum((factorial(n)/(factorial(k)**2*factorial(n - 2*k)))* (x/y)**k*(x*y)**(n - k), (n, 2*k, oo)), (k, 0, oo)) # Missing how to express constraint abs(x*y)<1? T = Sm.doit() # Sum not calculated assert T == -1/sqrt(x**2*y**2 - 4*x**2 - 2*x*y + 1) def test_R24(): m, k = symbols('m k', integer=True, positive=True) Sm = Sum(Product(k/(2*k - 1), (k, 1, m)), (m, 2, oo)) assert Sm.doit() == pi/2 def test_S1(): k = symbols('k', integer=True, positive=True) Pr = Product(gamma(k/3), (k, 1, 8)) assert Pr.doit().simplify() == 640*sqrt(3)*pi**3/6561 def test_S2(): n, k = symbols('n k', integer=True, positive=True) assert Product(k, (k, 1, n)).doit() == factorial(n) def test_S3(): n, k = symbols('n k', integer=True, positive=True) assert Product(x**k, (k, 1, n)).doit().simplify() == x**(n*(n + 1)/2) def test_S4(): n, k = symbols('n k', integer=True, positive=True) assert Product(1 + 1/k, (k, 1, n -1)).doit().simplify() == n def test_S5(): n, k = symbols('n k', integer=True, positive=True) assert (Product((2*k - 1)/(2*k), (k, 1, n)).doit().gammasimp() == gamma(n + S.Half)/(sqrt(pi)*gamma(n + 1))) @XFAIL def test_S6(): n, k = symbols('n k', integer=True, positive=True) # Product does not evaluate assert (Product(x**2 -2*x*cos(k*pi/n) + 1, (k, 1, n - 1)).doit().simplify() == (x**(2*n) - 1)/(x**2 - 1)) @XFAIL def test_S7(): k = symbols('k', integer=True, positive=True) Pr = Product((k**3 - 1)/(k**3 + 1), (k, 2, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == R(2, 3) @XFAIL def test_S8(): k = symbols('k', integer=True, positive=True) Pr = Product(1 - 1/(2*k)**2, (k, 1, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == 2/pi @XFAIL def test_S9(): k = symbols('k', integer=True, positive=True) Pr = Product(1 + (-1)**(k + 1)/(2*k - 1), (k, 1, oo)) T = Pr.doit() # Product produces 0 # https://github.com/sympy/sympy/issues/7133 assert T.simplify() == sqrt(2) @XFAIL def test_S10(): k = symbols('k', integer=True, positive=True) Pr = Product((k*(k + 1) + 1 + I)/(k*(k + 1) + 1 - I), (k, 0, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == -1 def test_T1(): assert limit((1 + 1/n)**n, n, oo) == E assert limit((1 - cos(x))/x**2, x, 0) == S.Half def test_T2(): assert limit((3**x + 5**x)**(1/x), x, oo) == 5 def test_T3(): assert limit(log(x)/(log(x) + sin(x)), x, oo) == 1 def test_T4(): assert limit((exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1)))) - exp(x))/x, x, oo) == -exp(2) def test_T5(): assert limit(x*log(x)*log(x*exp(x) - x**2)**2/log(log(x**2 + 2*exp(exp(3*x**3*log(x))))), x, oo) == R(1, 3) def test_T6(): assert limit(1/n * factorial(n)**(1/n), n, oo) == exp(-1) def test_T7(): limit(1/n * gamma(n + 1)**(1/n), n, oo) def test_T8(): a, z = symbols('a z', real=True, positive=True) assert limit(gamma(z + a)/gamma(z)*exp(-a*log(z)), z, oo) == 1 @XFAIL def test_T9(): z, k = symbols('z k', real=True, positive=True) # raises NotImplementedError: # Don't know how to calculate the mrv of '(1, k)' assert limit(hyper((1, k), (1,), z/k), k, oo) == exp(z) @XFAIL def test_T10(): # No longer raises PoleError, but should return euler-mascheroni constant assert limit(zeta(x) - 1/(x - 1), x, 1) == integrate(-1/x + 1/floor(x), (x, 1, oo)) @XFAIL def test_T11(): n, k = symbols('n k', integer=True, positive=True) # evaluates to 0 assert limit(n**x/(x*product((1 + x/k), (k, 1, n))), n, oo) == gamma(x) def test_T12(): x, t = symbols('x t', real=True) # Does not evaluate the limit but returns an expression with erf assert limit(x * integrate(exp(-t**2), (t, 0, x))/(1 - exp(-x**2)), x, 0) == 1 def test_T13(): x = symbols('x', real=True) assert [limit(x/abs(x), x, 0, dir='-'), limit(x/abs(x), x, 0, dir='+')] == [-1, 1] def test_T14(): x = symbols('x', real=True) assert limit(atan(-log(x)), x, 0, dir='+') == pi/2 def test_U1(): x = symbols('x', real=True) assert diff(abs(x), x) == sign(x) def test_U2(): f = Lambda(x, Piecewise((-x, x < 0), (x, x >= 0))) assert diff(f(x), x) == Piecewise((-1, x < 0), (1, x >= 0)) def test_U3(): f = Lambda(x, Piecewise((x**2 - 1, x == 1), (x**3, x != 1))) f1 = Lambda(x, diff(f(x), x)) assert f1(x) == 3*x**2 assert f1(1) == 3 @XFAIL def test_U4(): n = symbols('n', integer=True, positive=True) x = symbols('x', real=True) d = diff(x**n, x, n) assert d.rewrite(factorial) == factorial(n) def test_U5(): # issue 6681 t = symbols('t') ans = ( Derivative(f(g(t)), g(t))*Derivative(g(t), (t, 2)) + Derivative(f(g(t)), (g(t), 2))*Derivative(g(t), t)**2) assert f(g(t)).diff(t, 2) == ans assert ans.doit() == ans def test_U6(): h = Function('h') T = integrate(f(y), (y, h(x), g(x))) assert T.diff(x) == ( f(g(x))*Derivative(g(x), x) - f(h(x))*Derivative(h(x), x)) @XFAIL def test_U7(): p, t = symbols('p t', real=True) # Exact differential => d(V(P, T)) => dV/dP DP + dV/dT DT # raises ValueError: Since there is more than one variable in the # expression, the variable(s) of differentiation must be supplied to # differentiate f(p,t) diff(f(p, t)) def test_U8(): x, y = symbols('x y', real=True) eq = cos(x*y) + x # If SymPy had implicit_diff() function this hack could be avoided # TODO: Replace solve with solveset, current test fails for solveset assert idiff(y - eq, y, x) == (-y*sin(x*y) + 1)/(x*sin(x*y) + 1) def test_U9(): # Wester sample case for Maple: # O29 := diff(f(x, y), x) + diff(f(x, y), y); # /d \ /d \ # |-- f(x, y)| + |-- f(x, y)| # \dx / \dy / # # O30 := factor(subs(f(x, y) = g(x^2 + y^2), %)); # 2 2 # 2 D(g)(x + y ) (x + y) x, y = symbols('x y', real=True) su = diff(f(x, y), x) + diff(f(x, y), y) s2 = su.subs(f(x, y), g(x**2 + y**2)) s3 = s2.doit().factor() # Subs not performed, s3 = 2*(x + y)*Subs(Derivative( # g(_xi_1), _xi_1), _xi_1, x**2 + y**2) # Derivative(g(x*2 + y**2), x**2 + y**2) is not valid in SymPy, # and probably will remain that way. You can take derivatives with respect # to other expressions only if they are atomic, like a symbol or a # function. # D operator should be added to SymPy # See https://github.com/sympy/sympy/issues/4719. assert s3 == (x + y)*Subs(Derivative(g(x), x), x, x**2 + y**2)*2 def test_U10(): # see issue 2519: assert residue((z**3 + 5)/((z**4 - 1)*(z + 1)), z, -1) == R(-9, 4) @XFAIL def test_U11(): # assert (2*dx + dz) ^ (3*dx + dy + dz) ^ (dx + dy + 4*dz) == 8*dx ^ dy ^dz raise NotImplementedError @XFAIL def test_U12(): # Wester sample case: # (c41) /* d(3 x^5 dy /\ dz + 5 x y^2 dz /\ dx + 8 z dx /\ dy) # => (15 x^4 + 10 x y + 8) dx /\ dy /\ dz */ # factor(ext_diff(3*x^5 * dy ~ dz + 5*x*y^2 * dz ~ dx + 8*z * dx ~ dy)); # 4 # (d41) (10 x y + 15 x + 8) dx dy dz raise NotImplementedError( "External diff of differential form not supported") def test_U13(): assert minimum(x**4 - x + 1, x) == -3*2**R(1,3)/8 + 1 @XFAIL def test_U14(): #f = 1/(x**2 + y**2 + 1) #assert [minimize(f), maximize(f)] == [0,1] raise NotImplementedError("minimize(), maximize() not supported") @XFAIL def test_U15(): raise NotImplementedError("minimize() not supported and also solve does \ not support multivariate inequalities") @XFAIL def test_U16(): raise NotImplementedError("minimize() not supported in SymPy and also \ solve does not support multivariate inequalities") @XFAIL def test_U17(): raise NotImplementedError("Linear programming, symbolic simplex not \ supported in SymPy") def test_V1(): x = symbols('x', real=True) assert integrate(abs(x), x) == Piecewise((-x**2/2, x <= 0), (x**2/2, True)) def test_V2(): assert integrate(Piecewise((-x, x < 0), (x, x >= 0)), x ) == Piecewise((-x**2/2, x < 0), (x**2/2, True)) def test_V3(): assert integrate(1/(x**3 + 2),x).diff().simplify() == 1/(x**3 + 2) def test_V4(): assert integrate(2**x/sqrt(1 + 4**x), x) == asinh(2**x)/log(2) @XFAIL def test_V5(): # Returns (-45*x**2 + 80*x - 41)/(5*sqrt(2*x - 1)*(4*x**2 - 4*x + 1)) assert (integrate((3*x - 5)**2/(2*x - 1)**R(7, 2), x).simplify() == (-41 + 80*x - 45*x**2)/(5*(2*x - 1)**R(5, 2))) @XFAIL def test_V6(): # returns RootSum(40*_z**2 - 1, Lambda(_i, _i*log(-4*_i + exp(-m*x))))/m assert (integrate(1/(2*exp(m*x) - 5*exp(-m*x)), x) == sqrt(10)*( log(2*exp(m*x) - sqrt(10)) - log(2*exp(m*x) + sqrt(10)))/(20*m)) def test_V7(): r1 = integrate(sinh(x)**4/cosh(x)**2) assert r1.simplify() == x*R(-3, 2) + sinh(x)**3/(2*cosh(x)) + 3*tanh(x)/2 @XFAIL def test_V8_V9(): #Macsyma test case: #(c27) /* This example involves several symbolic parameters # => 1/sqrt(b^2 - a^2) log([sqrt(b^2 - a^2) tan(x/2) + a + b]/ # [sqrt(b^2 - a^2) tan(x/2) - a - b]) (a^2 < b^2) # [Gradshteyn and Ryzhik 2.553(3)] */ #assume(b^2 > a^2)$ #(c28) integrate(1/(a + b*cos(x)), x); #(c29) trigsimp(ratsimp(diff(%, x))); # 1 #(d29) ------------ # b cos(x) + a raise NotImplementedError( "Integrate with assumption not supported") def test_V10(): assert integrate(1/(3 + 3*cos(x) + 4*sin(x)), x) == log(tan(x/2) + R(3, 4))/4 def test_V11(): r1 = integrate(1/(4 + 3*cos(x) + 4*sin(x)), x) r2 = factor(r1) assert (logcombine(r2, force=True) == log(((tan(x/2) + 1)/(tan(x/2) + 7))**R(1, 3))) def test_V12(): r1 = integrate(1/(5 + 3*cos(x) + 4*sin(x)), x) assert r1 == -1/(tan(x/2) + 2) @XFAIL def test_V13(): r1 = integrate(1/(6 + 3*cos(x) + 4*sin(x)), x) # expression not simplified, returns: -sqrt(11)*I*log(tan(x/2) + 4/3 # - sqrt(11)*I/3)/11 + sqrt(11)*I*log(tan(x/2) + 4/3 + sqrt(11)*I/3)/11 assert r1.simplify() == 2*sqrt(11)*atan(sqrt(11)*(3*tan(x/2) + 4)/11)/11 @slow @XFAIL def test_V14(): r1 = integrate(log(abs(x**2 - y**2)), x) # Piecewise result does not simplify to the desired result. assert (r1.simplify() == x*log(abs(x**2 - y**2)) + y*log(x + y) - y*log(x - y) - 2*x) def test_V15(): r1 = integrate(x*acot(x/y), x) assert simplify(r1 - (x*y + (x**2 + y**2)*acot(x/y))/2) == 0 @XFAIL def test_V16(): # Integral not calculated assert integrate(cos(5*x)*Ci(2*x), x) == Ci(2*x)*sin(5*x)/5 - (Si(3*x) + Si(7*x))/10 @XFAIL def test_V17(): r1 = integrate((diff(f(x), x)*g(x) - f(x)*diff(g(x), x))/(f(x)**2 - g(x)**2), x) # integral not calculated assert simplify(r1 - (f(x) - g(x))/(f(x) + g(x))/2) == 0 @XFAIL def test_W1(): # The function has a pole at y. # The integral has a Cauchy principal value of zero but SymPy returns -I*pi # https://github.com/sympy/sympy/issues/7159 assert integrate(1/(x - y), (x, y - 1, y + 1)) == 0 @XFAIL def test_W2(): # The function has a pole at y. # The integral is divergent but SymPy returns -2 # https://github.com/sympy/sympy/issues/7160 # Test case in Macsyma: # (c6) errcatch(integrate(1/(x - a)^2, x, a - 1, a + 1)); # Integral is divergent assert integrate(1/(x - y)**2, (x, y - 1, y + 1)) is zoo @XFAIL @slow def test_W3(): # integral is not calculated # https://github.com/sympy/sympy/issues/7161 assert integrate(sqrt(x + 1/x - 2), (x, 0, 1)) == R(4, 3) @XFAIL @slow def test_W4(): # integral is not calculated assert integrate(sqrt(x + 1/x - 2), (x, 1, 2)) == -2*sqrt(2)/3 + R(4, 3) @XFAIL @slow def test_W5(): # integral is not calculated assert integrate(sqrt(x + 1/x - 2), (x, 0, 2)) == -2*sqrt(2)/3 + R(8, 3) @XFAIL @slow def test_W6(): # integral is not calculated assert integrate(sqrt(2 - 2*cos(2*x))/2, (x, pi*R(-3, 4), -pi/4)) == sqrt(2) def test_W7(): a = symbols('a', real=True, positive=True) r1 = integrate(cos(x)/(x**2 + a**2), (x, -oo, oo)) assert r1.simplify() == pi*exp(-a)/a @XFAIL def test_W8(): # Test case in Mathematica: # In[19]:= Integrate[t^(a - 1)/(1 + t), {t, 0, Infinity}, # Assumptions -> 0 < a < 1] # Out[19]= Pi Csc[a Pi] raise NotImplementedError( "Integrate with assumption 0 < a < 1 not supported") @XFAIL @slow def test_W9(): # Integrand with a residue at infinity => -2 pi [sin(pi/5) + sin(2pi/5)] # (principal value) [Levinson and Redheffer, p. 234] *) r1 = integrate(5*x**3/(1 + x + x**2 + x**3 + x**4), (x, -oo, oo)) r2 = r1.doit() assert r2 == -2*pi*(sqrt(-sqrt(5)/8 + 5/8) + sqrt(sqrt(5)/8 + 5/8)) @XFAIL def test_W10(): # integrate(1/[1 + x + x^2 + ... + x^(2 n)], x = -infinity..infinity) = # 2 pi/(2 n + 1) [1 + cos(pi/[2 n + 1])] csc(2 pi/[2 n + 1]) # [Levinson and Redheffer, p. 255] => 2 pi/5 [1 + cos(pi/5)] csc(2 pi/5) */ r1 = integrate(x/(1 + x + x**2 + x**4), (x, -oo, oo)) r2 = r1.doit() assert r2 == 2*pi*(sqrt(5)/4 + 5/4)*csc(pi*R(2, 5))/5 @XFAIL def test_W11(): # integral not calculated assert (integrate(sqrt(1 - x**2)/(1 + x**2), (x, -1, 1)) == pi*(-1 + sqrt(2))) def test_W12(): p = symbols('p', real=True, positive=True) q = symbols('q', real=True) r1 = integrate(x*exp(-p*x**2 + 2*q*x), (x, -oo, oo)) assert r1.simplify() == sqrt(pi)*q*exp(q**2/p)/p**R(3, 2) @XFAIL def test_W13(): # Integral not calculated. Expected result is 2*(Euler_mascheroni_constant) r1 = integrate(1/log(x) + 1/(1 - x) - log(log(1/x)), (x, 0, 1)) assert r1 == 2*EulerGamma def test_W14(): assert integrate(sin(x)/x*exp(2*I*x), (x, -oo, oo)) == 0 @XFAIL def test_W15(): # integral not calculated assert integrate(log(gamma(x))*cos(6*pi*x), (x, 0, 1)) == R(1, 12) def test_W16(): assert integrate((1 + x)**3*legendre_poly(1, x)*legendre_poly(2, x), (x, -1, 1)) == R(36, 35) def test_W17(): a, b = symbols('a b', real=True, positive=True) assert integrate(exp(-a*x)*besselj(0, b*x), (x, 0, oo)) == 1/(b*sqrt(a**2/b**2 + 1)) def test_W18(): assert integrate((besselj(1, x)/x)**2, (x, 0, oo)) == 4/(3*pi) @XFAIL def test_W19(): # Integral not calculated # Expected result is (cos 7 - 1)/7 [Gradshteyn and Ryzhik 6.782(3)] assert integrate(Ci(x)*besselj(0, 2*sqrt(7*x)), (x, 0, oo)) == (cos(7) - 1)/7 @XFAIL def test_W20(): # integral not calculated assert (integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1)) == -pi**2/36 - R(17, 108) + zeta(3)/4 + (-pi**2/2 - 4*log(2) + log(2)**2 + 35/3)*log(2)/9) def test_W21(): assert abs(N(integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1))) - 0.210882859565594) < 1e-15 def test_W22(): t, u = symbols('t u', real=True) s = Lambda(x, Piecewise((1, And(x >= 1, x <= 2)), (0, True))) assert integrate(s(t)*cos(t), (t, 0, u)) == Piecewise( (0, u < 0), (-sin(Min(1, u)) + sin(Min(2, u)), True)) @slow def test_W23(): a, b = symbols('a b', real=True, positive=True) r1 = integrate(integrate(x/(x**2 + y**2), (x, a, b)), (y, -oo, oo)) assert r1.collect(pi).cancel() == -pi*a + pi*b def test_W23b(): # like W23 but limits are reversed a, b = symbols('a b', real=True, positive=True) r2 = integrate(integrate(x/(x**2 + y**2), (y, -oo, oo)), (x, a, b)) assert r2.collect(pi) == pi*(-a + b) @XFAIL @slow def test_W24(): if ON_TRAVIS: skip("Too slow for travis.") # Not that slow, but does not fully evaluate so simplify is slow. # Maybe also require doit() x, y = symbols('x y', real=True) r1 = integrate(integrate(sqrt(x**2 + y**2), (x, 0, 1)), (y, 0, 1)) assert (r1 - (sqrt(2) + asinh(1))/3).simplify() == 0 @XFAIL @slow def test_W25(): if ON_TRAVIS: skip("Too slow for travis.") a, x, y = symbols('a x y', real=True) i1 = integrate( sin(a)*sin(y)/sqrt(1 - sin(a)**2*sin(x)**2*sin(y)**2), (x, 0, pi/2)) i2 = integrate(i1, (y, 0, pi/2)) assert (i2 - pi*a/2).simplify() == 0 def test_W26(): x, y = symbols('x y', real=True) assert integrate(integrate(abs(y - x**2), (y, 0, 2)), (x, -1, 1)) == R(46, 15) def test_W27(): a, b, c = symbols('a b c') assert integrate(integrate(integrate(1, (z, 0, c*(1 - x/a - y/b))), (y, 0, b*(1 - x/a))), (x, 0, a)) == a*b*c/6 def test_X1(): v, c = symbols('v c', real=True) assert (series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) == 5*v**6/(16*c**6) + 3*v**4/(8*c**4) + v**2/(2*c**2) + 1 + O(v**8)) def test_X2(): v, c = symbols('v c', real=True) s1 = series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) assert (1/s1**2).series(v, x0=0, n=8) == -v**2/c**2 + 1 + O(v**8) def test_X3(): s1 = (sin(x).series()/cos(x).series()).series() s2 = tan(x).series() assert s2 == x + x**3/3 + 2*x**5/15 + O(x**6) assert s1 == s2 def test_X4(): s1 = log(sin(x)/x).series() assert s1 == -x**2/6 - x**4/180 + O(x**6) assert log(series(sin(x)/x)).series() == s1 @XFAIL def test_X5(): # test case in Mathematica syntax: # In[21]:= (* => [a f'(a d) + g(b d) + integrate(h(c y), y = 0..d)] # + [a^2 f''(a d) + b g'(b d) + h(c d)] (x - d) *) # In[22]:= D[f[a*x], x] + g[b*x] + Integrate[h[c*y], {y, 0, x}] # Out[22]= g[b x] + Integrate[h[c y], {y, 0, x}] + a f'[a x] # In[23]:= Series[%, {x, d, 1}] # Out[23]= (g[b d] + Integrate[h[c y], {y, 0, d}] + a f'[a d]) + # 2 2 # (h[c d] + b g'[b d] + a f''[a d]) (-d + x) + O[-d + x] h = Function('h') a, b, c, d = symbols('a b c d', real=True) # series() raises NotImplementedError: # The _eval_nseries method should be added to <class # 'sympy.core.function.Subs'> to give terms up to O(x**n) at x=0 series(diff(f(a*x), x) + g(b*x) + integrate(h(c*y), (y, 0, x)), x, x0=d, n=2) # assert missing, until exception is removed def test_X6(): # Taylor series of nonscalar objects (noncommutative multiplication) # expected result => (B A - A B) t^2/2 + O(t^3) [Stanly Steinberg] a, b = symbols('a b', commutative=False, scalar=False) assert (series(exp((a + b)*x) - exp(a*x) * exp(b*x), x, x0=0, n=3) == x**2*(-a*b/2 + b*a/2) + O(x**3)) def test_X7(): # => sum( Bernoulli[k]/k! x^(k - 2), k = 1..infinity ) # = 1/x^2 - 1/(2 x) + 1/12 - x^2/720 + x^4/30240 + O(x^6) # [Levinson and Redheffer, p. 173] assert (series(1/(x*(exp(x) - 1)), x, 0, 7) == x**(-2) - 1/(2*x) + R(1, 12) - x**2/720 + x**4/30240 - x**6/1209600 + O(x**7)) def test_X8(): # Puiseux series (terms with fractional degree): # => 1/sqrt(x - 3/2 pi) + (x - 3/2 pi)^(3/2) / 12 + O([x - 3/2 pi]^(7/2)) # see issue 7167: x = symbols('x', real=True) assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) == 1/sqrt(x - pi*R(3, 2)) + (x - pi*R(3, 2))**R(3, 2)/12 + (x - pi*R(3, 2))**R(7, 2)/160 + O((x - pi*R(3, 2))**4, (x, pi*R(3, 2)))) def test_X9(): assert (series(x**x, x, x0=0, n=4) == 1 + x*log(x) + x**2*log(x)**2/2 + x**3*log(x)**3/6 + O(x**4*log(x)**4)) def test_X10(): z, w = symbols('z w') assert (series(log(sinh(z)) + log(cosh(z + w)), z, x0=0, n=2) == log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) def test_X11(): z, w = symbols('z w') assert (series(log(sinh(z) * cosh(z + w)), z, x0=0, n=2) == log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) @XFAIL def test_X12(): # Look at the generalized Taylor series around x = 1 # Result => (x - 1)^a/e^b [1 - (a + 2 b) (x - 1) / 2 + O((x - 1)^2)] a, b, x = symbols('a b x', real=True) # series returns O(log(x-1)**2) # https://github.com/sympy/sympy/issues/7168 assert (series(log(x)**a*exp(-b*x), x, x0=1, n=2) == (x - 1)**a/exp(b)*(1 - (a + 2*b)*(x - 1)/2 + O((x - 1)**2))) def test_X13(): assert series(sqrt(2*x**2 + 1), x, x0=oo, n=1) == sqrt(2)*x + O(1/x, (x, oo)) @XFAIL def test_X14(): # Wallis' product => 1/sqrt(pi n) + ... [Knopp, p. 385] assert series(1/2**(2*n)*binomial(2*n, n), n, x==oo, n=1) == 1/(sqrt(pi)*sqrt(n)) + O(1/x, (x, oo)) @SKIP("https://github.com/sympy/sympy/issues/7164") def test_X15(): # => 0!/x - 1!/x^2 + 2!/x^3 - 3!/x^4 + O(1/x^5) [Knopp, p. 544] x, t = symbols('x t', real=True) # raises RuntimeError: maximum recursion depth exceeded # https://github.com/sympy/sympy/issues/7164 # 2019-02-17: Raises # PoleError: # Asymptotic expansion of Ei around [-oo] is not implemented. e1 = integrate(exp(-t)/t, (t, x, oo)) assert (series(e1, x, x0=oo, n=5) == 6/x**4 + 2/x**3 - 1/x**2 + 1/x + O(x**(-5), (x, oo))) def test_X16(): # Multivariate Taylor series expansion => 1 - (x^2 + 2 x y + y^2)/2 + O(x^4) assert (series(cos(x + y), x + y, x0=0, n=4) == 1 - (x + y)**2/2 + O(x**4 + x**3*y + x**2*y**2 + x*y**3 + y**4, x, y)) @XFAIL def test_X17(): # Power series (compute the general formula) # (c41) powerseries(log(sin(x)/x), x, 0); # /aquarius/data2/opt/local/macsyma_422/library1/trgred.so being loaded. # inf # ==== i1 2 i1 2 i1 # \ (- 1) 2 bern(2 i1) x # (d41) > ------------------------------ # / 2 i1 (2 i1)! # ==== # i1 = 1 # fps does not calculate assert fps(log(sin(x)/x)) == \ Sum((-1)**k*2**(2*k - 1)*bernoulli(2*k)*x**(2*k)/(k*factorial(2*k)), (k, 1, oo)) @XFAIL def test_X18(): # Power series (compute the general formula). Maple FPS: # > FormalPowerSeries(exp(-x)*sin(x), x = 0); # infinity # ----- (1/2 k) k # \ 2 sin(3/4 k Pi) x # ) ------------------------- # / k! # ----- # # Now, SymPy returns # oo # _____ # \ ` # \ / k k\ # \ k |I*(-1 - I) I*(-1 + I) | # \ x *|----------- - -----------| # / \ 2 2 / # / ------------------------------ # / k! # /____, # k = 0 k = Dummy('k') assert fps(exp(-x)*sin(x)) == \ Sum(2**(S.Half*k)*sin(R(3, 4)*k*pi)*x**k/factorial(k), (k, 0, oo)) @XFAIL def test_X19(): # (c45) /* Derive an explicit Taylor series solution of y as a function of # x from the following implicit relation: # y = x - 1 + (x - 1)^2/2 + 2/3 (x - 1)^3 + (x - 1)^4 + # 17/10 (x - 1)^5 + ... # */ # x = sin(y) + cos(y); # Time= 0 msecs # (d45) x = sin(y) + cos(y) # # (c46) taylor_revert(%, y, 7); raise NotImplementedError("Solve using series not supported. \ Inverse Taylor series expansion also not supported") @XFAIL def test_X20(): # Pade (rational function) approximation => (2 - x)/(2 + x) # > numapprox[pade](exp(-x), x = 0, [1, 1]); # bytes used=9019816, alloc=3669344, time=13.12 # 1 - 1/2 x # --------- # 1 + 1/2 x # mpmath support numeric Pade approximant but there is # no symbolic implementation in SymPy # https://en.wikipedia.org/wiki/Pad%C3%A9_approximant raise NotImplementedError("Symbolic Pade approximant not supported") def test_X21(): """ Test whether `fourier_series` of x periodical on the [-p, p] interval equals `- (2 p / pi) sum( (-1)^n / n sin(n pi x / p), n = 1..infinity )`. """ p = symbols('p', positive=True) n = symbols('n', positive=True, integer=True) s = fourier_series(x, (x, -p, p)) # All cosine coefficients are equal to 0 assert s.an.formula == 0 # Check for sine coefficients assert s.bn.formula.subs(s.bn.variables[0], 0) == 0 assert s.bn.formula.subs(s.bn.variables[0], n) == \ -2*p/pi * (-1)**n / n * sin(n*pi*x/p) @XFAIL def test_X22(): # (c52) /* => p / 2 # - (2 p / pi^2) sum( [1 - (-1)^n] cos(n pi x / p) / n^2, # n = 1..infinity ) */ # fourier_series(abs(x), x, p); # p # (e52) a = - # 0 2 # # %nn # (2 (- 1) - 2) p # (e53) a = ------------------ # %nn 2 2 # %pi %nn # # (e54) b = 0 # %nn # # Time= 5290 msecs # inf %nn %pi %nn x # ==== (2 (- 1) - 2) cos(---------) # \ p # p > ------------------------------- # / 2 # ==== %nn # %nn = 1 p # (d54) ----------------------------------------- + - # 2 2 # %pi raise NotImplementedError("Fourier series not supported") def test_Y1(): t = symbols('t', real=True, positive=True) w = symbols('w', real=True) s = symbols('s') F, _, _ = laplace_transform(cos((w - 1)*t), t, s) assert F == s/(s**2 + (w - 1)**2) def test_Y2(): t = symbols('t', real=True, positive=True) w = symbols('w', real=True) s = symbols('s') f = inverse_laplace_transform(s/(s**2 + (w - 1)**2), s, t) assert f == cos(t*w - t) def test_Y3(): t = symbols('t', real=True, positive=True) w = symbols('w', real=True) s = symbols('s') F, _, _ = laplace_transform(sinh(w*t)*cosh(w*t), t, s) assert F == w/(s**2 - 4*w**2) def test_Y4(): t = symbols('t', real=True, positive=True) s = symbols('s') F, _, _ = laplace_transform(erf(3/sqrt(t)), t, s) assert F == (1 - exp(-6*sqrt(s)))/s @XFAIL def test_Y5_Y6(): # Solve y'' + y = 4 [H(t - 1) - H(t - 2)], y(0) = 1, y'(0) = 0 where H is the # Heaviside (unit step) function (the RHS describes a pulse of magnitude 4 and # duration 1). See David A. Sanchez, Richard C. Allen, Jr. and Walter T. # Kyner, _Differential Equations: An Introduction_, Addison-Wesley Publishing # Company, 1983, p. 211. First, take the Laplace transform of the ODE # => s^2 Y(s) - s + Y(s) = 4/s [e^(-s) - e^(-2 s)] # where Y(s) is the Laplace transform of y(t) t = symbols('t', real=True, positive=True) s = symbols('s') y = Function('y') F, _, _ = laplace_transform(diff(y(t), t, 2) + y(t) - 4*(Heaviside(t - 1) - Heaviside(t - 2)), t, s) # Laplace transform for diff() not calculated # https://github.com/sympy/sympy/issues/7176 assert (F == s**2*LaplaceTransform(y(t), t, s) - s + LaplaceTransform(y(t), t, s) - 4*exp(-s)/s + 4*exp(-2*s)/s) # TODO implement second part of test case # Now, solve for Y(s) and then take the inverse Laplace transform # => Y(s) = s/(s^2 + 1) + 4 [1/s - s/(s^2 + 1)] [e^(-s) - e^(-2 s)] # => y(t) = cos t + 4 {[1 - cos(t - 1)] H(t - 1) - [1 - cos(t - 2)] H(t - 2)} @XFAIL def test_Y7(): # What is the Laplace transform of an infinite square wave? # => 1/s + 2 sum( (-1)^n e^(- s n a)/s, n = 1..infinity ) # [Sanchez, Allen and Kyner, p. 213] t = symbols('t', real=True, positive=True) a = symbols('a', real=True) s = symbols('s') F, _, _ = laplace_transform(1 + 2*Sum((-1)**n*Heaviside(t - n*a), (n, 1, oo)), t, s) # returns 2*LaplaceTransform(Sum((-1)**n*Heaviside(-a*n + t), # (n, 1, oo)), t, s) + 1/s # https://github.com/sympy/sympy/issues/7177 assert F == 2*Sum((-1)**n*exp(-a*n*s)/s, (n, 1, oo)) + 1/s @XFAIL def test_Y8(): assert fourier_transform(1, x, z) == DiracDelta(z) def test_Y9(): assert (fourier_transform(exp(-9*x**2), x, z) == sqrt(pi)*exp(-pi**2*z**2/9)/3) def test_Y10(): assert (fourier_transform(abs(x)*exp(-3*abs(x)), x, z).cancel() == (-8*pi**2*z**2 + 18)/(16*pi**4*z**4 + 72*pi**2*z**2 + 81)) @SKIP("https://github.com/sympy/sympy/issues/7181") @slow def test_Y11(): # => pi cot(pi s) (0 < Re s < 1) [Gradshteyn and Ryzhik 17.43(5)] x, s = symbols('x s') # raises RuntimeError: maximum recursion depth exceeded # https://github.com/sympy/sympy/issues/7181 # Update 2019-02-17 raises: # TypeError: cannot unpack non-iterable MellinTransform object F, _, _ = mellin_transform(1/(1 - x), x, s) assert F == pi*cot(pi*s) @XFAIL def test_Y12(): # => 2^(s - 4) gamma(s/2)/gamma(4 - s/2) (0 < Re s < 1) # [Gradshteyn and Ryzhik 17.43(16)] x, s = symbols('x s') # returns Wrong value -2**(s - 4)*gamma(s/2 - 3)/gamma(-s/2 + 1) # https://github.com/sympy/sympy/issues/7182 F, _, _ = mellin_transform(besselj(3, x)/x**3, x, s) assert F == -2**(s - 4)*gamma(s/2)/gamma(-s/2 + 4) @XFAIL def test_Y13(): # Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) z raise NotImplementedError("z-transform not supported") @XFAIL def test_Y14(): # Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) raise NotImplementedError("z-transform not supported") def test_Z1(): r = Function('r') assert (rsolve(r(n + 2) - 2*r(n + 1) + r(n) - 2, r(n), {r(0): 1, r(1): m}).simplify() == n**2 + n*(m - 2) + 1) def test_Z2(): r = Function('r') assert (rsolve(r(n) - (5*r(n - 1) - 6*r(n - 2)), r(n), {r(0): 0, r(1): 1}) == -2**n + 3**n) def test_Z3(): # => r(n) = Fibonacci[n + 1] [Cohen, p. 83] r = Function('r') # recurrence solution is correct, Wester expects it to be simplified to # fibonacci(n+1), but that is quite hard expected = ((S(1)/2 - sqrt(5)/2)**n*(S(1)/2 - sqrt(5)/10) + (S(1)/2 + sqrt(5)/2)**n*(sqrt(5)/10 + S(1)/2)) sol = rsolve(r(n) - (r(n - 1) + r(n - 2)), r(n), {r(1): 1, r(2): 2}) assert sol == expected @XFAIL def test_Z4(): # => [c^(n+1) [c^(n+1) - 2 c - 2] + (n+1) c^2 + 2 c - n] / [(c-1)^3 (c+1)] # [Joan Z. Yu and Robert Israel in sci.math.symbolic] r = Function('r') c = symbols('c') # raises ValueError: Polynomial or rational function expected, # got '(c**2 - c**n)/(c - c**n) s = rsolve(r(n) - ((1 + c - c**(n-1) - c**(n+1))/(1 - c**n)*r(n - 1) - c*(1 - c**(n-2))/(1 - c**(n-1))*r(n - 2) + 1), r(n), {r(1): 1, r(2): (2 + 2*c + c**2)/(1 + c)}) assert (s - (c*(n + 1)*(c*(n + 1) - 2*c - 2) + (n + 1)*c**2 + 2*c - n)/((c-1)**3*(c+1)) == 0) @XFAIL def test_Z5(): # Second order ODE with initial conditions---solve directly # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 C1, C2 = symbols('C1 C2') # initial conditions not supported, this is a manual workaround # https://github.com/sympy/sympy/issues/4720 eq = Derivative(f(x), x, 2) + 4*f(x) - sin(2*x) sol = dsolve(eq, f(x)) f0 = Lambda(x, sol.rhs) assert f0(x) == C2*sin(2*x) + (C1 - x/4)*cos(2*x) f1 = Lambda(x, diff(f0(x), x)) # TODO: Replace solve with solveset, when it works for solveset const_dict = solve((f0(0), f1(0))) result = f0(x).subs(C1, const_dict[C1]).subs(C2, const_dict[C2]) assert result == -x*cos(2*x)/4 + sin(2*x)/8 # Result is OK, but ODE solving with initial conditions should be # supported without all this manual work raise NotImplementedError('ODE solving with initial conditions \ not supported') @XFAIL def test_Z6(): # Second order ODE with initial conditions---solve using Laplace # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 t = symbols('t', real=True, positive=True) s = symbols('s') eq = Derivative(f(t), t, 2) + 4*f(t) - sin(2*t) F, _, _ = laplace_transform(eq, t, s) # Laplace transform for diff() not calculated # https://github.com/sympy/sympy/issues/7176 assert (F == s**2*LaplaceTransform(f(t), t, s) + 4*LaplaceTransform(f(t), t, s) - 2/(s**2 + 4)) # rest of test case not implemented
330aed9de57e26105c758070f15330d12cc0a8547ce0e99f082a59f48ef55368
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 w, x, y, z = symbols('w,x,y,z') 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'] 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 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
569f0a356c09d5eca7a40ab33403d15bcec9d7b195a41d323b2e483a34f5a55f
from functools import wraps from sympy.utilities.decorator import threaded, xthreaded, memoize_property 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
4d8723f91007b73a23f19f241ee9e477147a5095eb83106ea090f553fe64e08d
from io import StringIO from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function from sympy.core.relational import Equality from sympy.functions.elementary.piecewise import Piecewise from sympy.matrices import Matrix, MatrixSymbol from sympy.utilities.codegen import JuliaCodeGen, codegen, make_routine from sympy.testing.pytest import XFAIL import sympy x, y, z = symbols('x,y,z') def test_empty_jl_code(): code_gen = JuliaCodeGen() output = StringIO() code_gen.dump_jl([], output, "file", header=False, empty=False) source = output.getvalue() assert source == "" def test_jl_simple_code(): name_expr = ("test", (x + y)*z) result, = codegen(name_expr, "Julia", header=False, empty=False) assert result[0] == "test.jl" source = result[1] expected = ( "function test(x, y, z)\n" " out1 = z.*(x + y)\n" " return out1\n" "end\n" ) assert source == expected def test_jl_simple_code_with_header(): name_expr = ("test", (x + y)*z) result, = codegen(name_expr, "Julia", header=True, empty=False) assert result[0] == "test.jl" source = result[1] expected = ( "# Code generated with SymPy " + sympy.__version__ + "\n" "#\n" "# See http://www.sympy.org/ for more information.\n" "#\n" "# This file is part of 'project'\n" "function test(x, y, z)\n" " out1 = z.*(x + y)\n" " return out1\n" "end\n" ) assert source == expected def test_jl_simple_code_nameout(): expr = Equality(z, (x + y)) name_expr = ("test", expr) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y)\n" " z = x + y\n" " return z\n" "end\n" ) assert source == expected def test_jl_numbersymbol(): name_expr = ("test", pi**Catalan) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test()\n" " out1 = pi^catalan\n" " return out1\n" "end\n" ) assert source == expected @XFAIL def test_jl_numbersymbol_no_inline(): # FIXME: how to pass inline=False to the JuliaCodePrinter? name_expr = ("test", [pi**Catalan, EulerGamma]) result, = codegen(name_expr, "Julia", header=False, empty=False, inline=False) source = result[1] expected = ( "function test()\n" " Catalan = 0.915965594177219\n" " EulerGamma = 0.5772156649015329\n" " out1 = pi^Catalan\n" " out2 = EulerGamma\n" " return out1, out2\n" "end\n" ) assert source == expected def test_jl_code_argument_order(): expr = x + y routine = make_routine("test", expr, argument_sequence=[z, x, y], language="julia") code_gen = JuliaCodeGen() output = StringIO() code_gen.dump_jl([routine], output, "test", header=False, empty=False) source = output.getvalue() expected = ( "function test(z, x, y)\n" " out1 = x + y\n" " return out1\n" "end\n" ) assert source == expected def test_multiple_results_m(): # Here the output order is the input order expr1 = (x + y)*z expr2 = (x - y)*z name_expr = ("test", [expr1, expr2]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y, z)\n" " out1 = z.*(x + y)\n" " out2 = z.*(x - y)\n" " return out1, out2\n" "end\n" ) assert source == expected def test_results_named_unordered(): # Here output order is based on name_expr A, B, C = symbols('A,B,C') expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, (x - y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y, z)\n" " C = z.*(x + y)\n" " A = z.*(x - y)\n" " B = 2*x\n" " return C, A, B\n" "end\n" ) assert source == expected def test_results_named_ordered(): A, B, C = symbols('A,B,C') expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, (x - y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result = codegen(name_expr, "Julia", header=False, empty=False, argument_sequence=(x, z, y)) assert result[0][0] == "test.jl" source = result[0][1] expected = ( "function test(x, z, y)\n" " C = z.*(x + y)\n" " A = z.*(x - y)\n" " B = 2*x\n" " return C, A, B\n" "end\n" ) assert source == expected def test_complicated_jl_codegen(): from sympy.functions.elementary.trigonometric import (cos, sin, tan) name_expr = ("testlong", [ ((sin(x) + cos(y) + tan(z))**3).expand(), cos(cos(cos(cos(cos(cos(cos(cos(x + y + z)))))))) ]) result = codegen(name_expr, "Julia", header=False, empty=False) assert result[0][0] == "testlong.jl" source = result[0][1] expected = ( "function testlong(x, y, z)\n" " out1 = sin(x).^3 + 3*sin(x).^2.*cos(y) + 3*sin(x).^2.*tan(z)" " + 3*sin(x).*cos(y).^2 + 6*sin(x).*cos(y).*tan(z) + 3*sin(x).*tan(z).^2" " + cos(y).^3 + 3*cos(y).^2.*tan(z) + 3*cos(y).*tan(z).^2 + tan(z).^3\n" " out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n" " return out1, out2\n" "end\n" ) assert source == expected def test_jl_output_arg_mixed_unordered(): # named outputs are alphabetical, unnamed output appear in the given order from sympy.functions.elementary.trigonometric import (cos, sin) a = symbols("a") name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))]) result, = codegen(name_expr, "Julia", header=False, empty=False) assert result[0] == "foo.jl" source = result[1]; expected = ( 'function foo(x)\n' ' out1 = cos(2*x)\n' ' y = sin(x)\n' ' out3 = cos(x)\n' ' a = sin(2*x)\n' ' return out1, y, out3, a\n' 'end\n' ) assert source == expected def test_jl_piecewise_(): pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False) name_expr = ("pwtest", pw) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function pwtest(x)\n" " out1 = ((x < -1) ? (0) :\n" " (x <= 1) ? (x.^2) :\n" " (x > 1) ? (2 - x) : (1))\n" " return out1\n" "end\n" ) assert source == expected @XFAIL def test_jl_piecewise_no_inline(): # FIXME: how to pass inline=False to the JuliaCodePrinter? pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True)) name_expr = ("pwtest", pw) result, = codegen(name_expr, "Julia", header=False, empty=False, inline=False) source = result[1] expected = ( "function pwtest(x)\n" " if (x < -1)\n" " out1 = 0\n" " elseif (x <= 1)\n" " out1 = x.^2\n" " elseif (x > 1)\n" " out1 = -x + 2\n" " else\n" " out1 = 1\n" " end\n" " return out1\n" "end\n" ) assert source == expected def test_jl_multifcns_per_file(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Julia", header=False, empty=False) assert result[0][0] == "foo.jl" source = result[0][1]; expected = ( "function foo(x, y)\n" " out1 = 2*x\n" " out2 = 3*y\n" " return out1, out2\n" "end\n" "function bar(y)\n" " out1 = y.^2\n" " out2 = 4*y\n" " return out1, out2\n" "end\n" ) assert source == expected def test_jl_multifcns_per_file_w_header(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Julia", header=True, empty=False) assert result[0][0] == "foo.jl" source = result[0][1]; expected = ( "# Code generated with SymPy " + sympy.__version__ + "\n" "#\n" "# See http://www.sympy.org/ for more information.\n" "#\n" "# This file is part of 'project'\n" "function foo(x, y)\n" " out1 = 2*x\n" " out2 = 3*y\n" " return out1, out2\n" "end\n" "function bar(y)\n" " out1 = y.^2\n" " out2 = 4*y\n" " return out1, out2\n" "end\n" ) assert source == expected def test_jl_filename_match_prefix(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result, = codegen(name_expr, "Julia", prefix="baz", header=False, empty=False) assert result[0] == "baz.jl" def test_jl_matrix_named(): e2 = Matrix([[x, 2*y, pi*z]]) name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2)) result = codegen(name_expr, "Julia", header=False, empty=False) assert result[0][0] == "test.jl" source = result[0][1] expected = ( "function test(x, y, z)\n" " myout1 = [x 2*y pi*z]\n" " return myout1\n" "end\n" ) assert source == expected def test_jl_matrix_named_matsym(): myout1 = MatrixSymbol('myout1', 1, 3) e2 = Matrix([[x, 2*y, pi*z]]) name_expr = ("test", Equality(myout1, e2, evaluate=False)) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y, z)\n" " myout1 = [x 2*y pi*z]\n" " return myout1\n" "end\n" ) assert source == expected def test_jl_matrix_output_autoname(): expr = Matrix([[x, x+y, 3]]) name_expr = ("test", expr) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y)\n" " out1 = [x x + y 3]\n" " return out1\n" "end\n" ) assert source == expected def test_jl_matrix_output_autoname_2(): e1 = (x + y) e2 = Matrix([[2*x, 2*y, 2*z]]) e3 = Matrix([[x], [y], [z]]) e4 = Matrix([[x, y], [z, 16]]) name_expr = ("test", (e1, e2, e3, e4)) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y, z)\n" " out1 = x + y\n" " out2 = [2*x 2*y 2*z]\n" " out3 = [x, y, z]\n" " out4 = [x y;\n" " z 16]\n" " return out1, out2, out3, out4\n" "end\n" ) assert source == expected def test_jl_results_matrix_named_ordered(): B, C = symbols('B,C') A = MatrixSymbol('A', 1, 3) expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, Matrix([[1, 2, x]])) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result, = codegen(name_expr, "Julia", header=False, empty=False, argument_sequence=(x, z, y)) source = result[1] expected = ( "function test(x, z, y)\n" " C = z.*(x + y)\n" " A = [1 2 x]\n" " B = 2*x\n" " return C, A, B\n" "end\n" ) assert source == expected def test_jl_matrixsymbol_slice(): A = MatrixSymbol('A', 2, 3) B = MatrixSymbol('B', 1, 3) C = MatrixSymbol('C', 1, 3) D = MatrixSymbol('D', 2, 1) name_expr = ("test", [Equality(B, A[0, :]), Equality(C, A[1, :]), Equality(D, A[:, 2])]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(A)\n" " B = A[1,:]\n" " C = A[2,:]\n" " D = A[:,3]\n" " return B, C, D\n" "end\n" ) assert source == expected def test_jl_matrixsymbol_slice2(): A = MatrixSymbol('A', 3, 4) B = MatrixSymbol('B', 2, 2) C = MatrixSymbol('C', 2, 2) name_expr = ("test", [Equality(B, A[0:2, 0:2]), Equality(C, A[0:2, 1:3])]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(A)\n" " B = A[1:2,1:2]\n" " C = A[1:2,2:3]\n" " return B, C\n" "end\n" ) assert source == expected def test_jl_matrixsymbol_slice3(): A = MatrixSymbol('A', 8, 7) B = MatrixSymbol('B', 2, 2) C = MatrixSymbol('C', 4, 2) name_expr = ("test", [Equality(B, A[6:, 1::3]), Equality(C, A[::2, ::3])]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(A)\n" " B = A[7:end,2:3:end]\n" " C = A[1:2:end,1:3:end]\n" " return B, C\n" "end\n" ) assert source == expected def test_jl_matrixsymbol_slice_autoname(): A = MatrixSymbol('A', 2, 3) B = MatrixSymbol('B', 1, 3) name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(A)\n" " B = A[1,:]\n" " out2 = A[2,:]\n" " out3 = A[:,1]\n" " out4 = A[:,2]\n" " return B, out2, out3, out4\n" "end\n" ) assert source == expected def test_jl_loops(): # Note: an Julia programmer would probably vectorize this across one or # more dimensions. Also, size(A) would be used rather than passing in m # and n. Perhaps users would expect us to vectorize automatically here? # Or is it possible to represent such things using IndexedBase? from sympy.tensor import IndexedBase, Idx from sympy.core.symbol import symbols n, m = symbols('n m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j]*x[j])), "Julia", header=False, empty=False) source = result[1] expected = ( 'function mat_vec_mult(y, A, m, n, x)\n' ' for i = 1:m\n' ' y[i] = 0\n' ' end\n' ' for i = 1:m\n' ' for j = 1:n\n' ' y[i] = %(rhs)s + y[i]\n' ' end\n' ' end\n' ' return y\n' 'end\n' ) assert (source == expected % {'rhs': 'A[%s,%s].*x[j]' % (i, j)} or source == expected % {'rhs': 'x[j].*A[%s,%s]' % (i, j)}) def test_jl_tensor_loops_multiple_contractions(): # see comments in previous test about vectorizing from sympy.tensor import IndexedBase, Idx from sympy.core.symbol import symbols n, m, o, p = symbols('n m o p', integer=True) A = IndexedBase('A') B = IndexedBase('B') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) l = Idx('l', p) result, = codegen(('tensorthing', Eq(y[i], B[j, k, l]*A[i, j, k, l])), "Julia", header=False, empty=False) source = result[1] expected = ( 'function tensorthing(y, A, B, m, n, o, p)\n' ' for i = 1:m\n' ' y[i] = 0\n' ' end\n' ' for i = 1:m\n' ' for j = 1:n\n' ' for k = 1:o\n' ' for l = 1:p\n' ' y[i] = A[i,j,k,l].*B[j,k,l] + y[i]\n' ' end\n' ' end\n' ' end\n' ' end\n' ' return y\n' 'end\n' ) assert source == expected def test_jl_InOutArgument(): expr = Equality(x, x**2) name_expr = ("mysqr", expr) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function mysqr(x)\n" " x = x.^2\n" " return x\n" "end\n" ) assert source == expected def test_jl_InOutArgument_order(): # can specify the order as (x, y) expr = Equality(x, x**2 + y) name_expr = ("test", expr) result, = codegen(name_expr, "Julia", header=False, empty=False, argument_sequence=(x,y)) source = result[1] expected = ( "function test(x, y)\n" " x = x.^2 + y\n" " return x\n" "end\n" ) assert source == expected # make sure it gives (x, y) not (y, x) expr = Equality(x, x**2 + y) name_expr = ("test", expr) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y)\n" " x = x.^2 + y\n" " return x\n" "end\n" ) assert source == expected def test_jl_not_supported(): f = Function('f') name_expr = ("test", [f(x).diff(x), S.ComplexInfinity]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x)\n" " # unsupported: Derivative(f(x), x)\n" " # unsupported: zoo\n" " out1 = Derivative(f(x), x)\n" " out2 = zoo\n" " return out1, out2\n" "end\n" ) assert source == expected def test_global_vars_octave(): x, y, z, t = symbols("x y z t") result = codegen(('f', x*y), "Julia", header=False, empty=False, global_vars=(y,)) source = result[0][1] expected = ( "function f(x)\n" " out1 = x.*y\n" " return out1\n" "end\n" ) assert source == expected result = codegen(('f', x*y+z), "Julia", header=False, empty=False, argument_sequence=(x, y), global_vars=(z, t)) source = result[0][1] expected = ( "function f(x, y)\n" " out1 = x.*y + z\n" " return out1\n" "end\n" ) assert source == expected
4c11db93ad7f57011f0ef1fbd72c6050e0e00b72c70eba620a8a58e96a6e9f06
from io import StringIO from sympy.core import symbols, Eq, pi, Catalan, Lambda, Dummy from sympy.core.relational import Equality from sympy.core.symbol import Symbol from sympy.functions.special.error_functions import erf from sympy.integrals.integrals import Integral from sympy.matrices import Matrix, MatrixSymbol from sympy.utilities.codegen import ( codegen, make_routine, CCodeGen, C89CodeGen, C99CodeGen, InputArgument, CodeGenError, FCodeGen, CodeGenArgumentListError, OutputArgument, InOutArgument) from sympy.testing.pytest import raises from sympy.utilities.lambdify import implemented_function #FIXME: Fails due to circular import in with core # from sympy import codegen def get_string(dump_fn, routines, prefix="file", header=False, empty=False): """Wrapper for dump_fn. dump_fn writes its results to a stream object and this wrapper returns the contents of that stream as a string. This auxiliary function is used by many tests below. The header and the empty lines are not generated to facilitate the testing of the output. """ output = StringIO() dump_fn(routines, output, prefix, header, empty) source = output.getvalue() output.close() return source def test_Routine_argument_order(): a, x, y, z = symbols('a x y z') expr = (x + y)*z raises(CodeGenArgumentListError, lambda: make_routine("test", expr, argument_sequence=[z, x])) raises(CodeGenArgumentListError, lambda: make_routine("test", Eq(a, expr), argument_sequence=[z, x, y])) r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y]) assert [ arg.name for arg in r.arguments ] == [z, x, a, y] assert [ type(arg) for arg in r.arguments ] == [ InputArgument, InputArgument, OutputArgument, InputArgument ] r = make_routine('test', Eq(z, expr), argument_sequence=[z, x, y]) assert [ type(arg) for arg in r.arguments ] == [ InOutArgument, InputArgument, InputArgument ] from sympy.tensor import IndexedBase, Idx A, B = map(IndexedBase, ['A', 'B']) m = symbols('m', integer=True) i = Idx('i', m) r = make_routine('test', Eq(A[i], B[i]), argument_sequence=[B, A, m]) assert [ arg.name for arg in r.arguments ] == [B.label, A.label, m] expr = Integral(x*y*z, (x, 1, 2), (y, 1, 3)) r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y]) assert [ arg.name for arg in r.arguments ] == [z, x, a, y] def test_empty_c_code(): code_gen = C89CodeGen() source = get_string(code_gen.dump_c, []) assert source == "#include \"file.h\"\n#include <math.h>\n" def test_empty_c_code_with_comment(): code_gen = C89CodeGen() source = get_string(code_gen.dump_c, [], header=True) assert source[:82] == ( "/******************************************************************************\n *" ) # " Code generated with SymPy 0.7.2-git " assert source[158:] == ( "*\n" " * *\n" " * See http://www.sympy.org/ for more information. *\n" " * *\n" " * This file is part of 'project' *\n" " ******************************************************************************/\n" "#include \"file.h\"\n" "#include <math.h>\n" ) def test_empty_c_header(): code_gen = C99CodeGen() source = get_string(code_gen.dump_h, []) assert source == "#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n#endif\n" def test_simple_c_code(): x, y, z = symbols('x,y,z') expr = (x + y)*z routine = make_routine("test", expr) code_gen = C89CodeGen() source = get_string(code_gen.dump_c, [routine]) expected = ( "#include \"file.h\"\n" "#include <math.h>\n" "double test(double x, double y, double z) {\n" " double test_result;\n" " test_result = z*(x + y);\n" " return test_result;\n" "}\n" ) assert source == expected def test_c_code_reserved_words(): x, y, z = symbols('if, typedef, while') expr = (x + y) * z routine = make_routine("test", expr) code_gen = C99CodeGen() source = get_string(code_gen.dump_c, [routine]) expected = ( "#include \"file.h\"\n" "#include <math.h>\n" "double test(double if_, double typedef_, double while_) {\n" " double test_result;\n" " test_result = while_*(if_ + typedef_);\n" " return test_result;\n" "}\n" ) assert source == expected def test_numbersymbol_c_code(): routine = make_routine("test", pi**Catalan) code_gen = C89CodeGen() source = get_string(code_gen.dump_c, [routine]) expected = ( "#include \"file.h\"\n" "#include <math.h>\n" "double test() {\n" " double test_result;\n" " double const Catalan = %s;\n" " test_result = pow(M_PI, Catalan);\n" " return test_result;\n" "}\n" ) % Catalan.evalf(17) assert source == expected def test_c_code_argument_order(): x, y, z = symbols('x,y,z') expr = x + y routine = make_routine("test", expr, argument_sequence=[z, x, y]) code_gen = C89CodeGen() source = get_string(code_gen.dump_c, [routine]) expected = ( "#include \"file.h\"\n" "#include <math.h>\n" "double test(double z, double x, double y) {\n" " double test_result;\n" " test_result = x + y;\n" " return test_result;\n" "}\n" ) assert source == expected def test_simple_c_header(): x, y, z = symbols('x,y,z') expr = (x + y)*z routine = make_routine("test", expr) code_gen = C89CodeGen() source = get_string(code_gen.dump_h, [routine]) expected = ( "#ifndef PROJECT__FILE__H\n" "#define PROJECT__FILE__H\n" "double test(double x, double y, double z);\n" "#endif\n" ) assert source == expected def test_simple_c_codegen(): x, y, z = symbols('x,y,z') expr = (x + y)*z expected = [ ("file.c", "#include \"file.h\"\n" "#include <math.h>\n" "double test(double x, double y, double z) {\n" " double test_result;\n" " test_result = z*(x + y);\n" " return test_result;\n" "}\n"), ("file.h", "#ifndef PROJECT__FILE__H\n" "#define PROJECT__FILE__H\n" "double test(double x, double y, double z);\n" "#endif\n") ] result = codegen(("test", expr), "C", "file", header=False, empty=False) assert result == expected def test_multiple_results_c(): x, y, z = symbols('x,y,z') expr1 = (x + y)*z expr2 = (x - y)*z routine = make_routine( "test", [expr1, expr2] ) code_gen = C99CodeGen() raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine])) def test_no_results_c(): raises(ValueError, lambda: make_routine("test", [])) def test_ansi_math1_codegen(): # not included: log10 from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import log from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh) from sympy.functions.elementary.integers import (ceiling, floor) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan) x = symbols('x') name_expr = [ ("test_fabs", Abs(x)), ("test_acos", acos(x)), ("test_asin", asin(x)), ("test_atan", atan(x)), ("test_ceil", ceiling(x)), ("test_cos", cos(x)), ("test_cosh", cosh(x)), ("test_floor", floor(x)), ("test_log", log(x)), ("test_ln", log(x)), ("test_sin", sin(x)), ("test_sinh", sinh(x)), ("test_sqrt", sqrt(x)), ("test_tan", tan(x)), ("test_tanh", tanh(x)), ] result = codegen(name_expr, "C89", "file", header=False, empty=False) assert result[0][0] == "file.c" assert result[0][1] == ( '#include "file.h"\n#include <math.h>\n' 'double test_fabs(double x) {\n double test_fabs_result;\n test_fabs_result = fabs(x);\n return test_fabs_result;\n}\n' 'double test_acos(double x) {\n double test_acos_result;\n test_acos_result = acos(x);\n return test_acos_result;\n}\n' 'double test_asin(double x) {\n double test_asin_result;\n test_asin_result = asin(x);\n return test_asin_result;\n}\n' 'double test_atan(double x) {\n double test_atan_result;\n test_atan_result = atan(x);\n return test_atan_result;\n}\n' 'double test_ceil(double x) {\n double test_ceil_result;\n test_ceil_result = ceil(x);\n return test_ceil_result;\n}\n' 'double test_cos(double x) {\n double test_cos_result;\n test_cos_result = cos(x);\n return test_cos_result;\n}\n' 'double test_cosh(double x) {\n double test_cosh_result;\n test_cosh_result = cosh(x);\n return test_cosh_result;\n}\n' 'double test_floor(double x) {\n double test_floor_result;\n test_floor_result = floor(x);\n return test_floor_result;\n}\n' 'double test_log(double x) {\n double test_log_result;\n test_log_result = log(x);\n return test_log_result;\n}\n' 'double test_ln(double x) {\n double test_ln_result;\n test_ln_result = log(x);\n return test_ln_result;\n}\n' 'double test_sin(double x) {\n double test_sin_result;\n test_sin_result = sin(x);\n return test_sin_result;\n}\n' 'double test_sinh(double x) {\n double test_sinh_result;\n test_sinh_result = sinh(x);\n return test_sinh_result;\n}\n' 'double test_sqrt(double x) {\n double test_sqrt_result;\n test_sqrt_result = sqrt(x);\n return test_sqrt_result;\n}\n' 'double test_tan(double x) {\n double test_tan_result;\n test_tan_result = tan(x);\n return test_tan_result;\n}\n' 'double test_tanh(double x) {\n double test_tanh_result;\n test_tanh_result = tanh(x);\n return test_tanh_result;\n}\n' ) assert result[1][0] == "file.h" assert result[1][1] == ( '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n' 'double test_fabs(double x);\ndouble test_acos(double x);\n' 'double test_asin(double x);\ndouble test_atan(double x);\n' 'double test_ceil(double x);\ndouble test_cos(double x);\n' 'double test_cosh(double x);\ndouble test_floor(double x);\n' 'double test_log(double x);\ndouble test_ln(double x);\n' 'double test_sin(double x);\ndouble test_sinh(double x);\n' 'double test_sqrt(double x);\ndouble test_tan(double x);\n' 'double test_tanh(double x);\n#endif\n' ) def test_ansi_math2_codegen(): # not included: frexp, ldexp, modf, fmod from sympy.functions.elementary.trigonometric import atan2 x, y = symbols('x,y') name_expr = [ ("test_atan2", atan2(x, y)), ("test_pow", x**y), ] result = codegen(name_expr, "C89", "file", header=False, empty=False) assert result[0][0] == "file.c" assert result[0][1] == ( '#include "file.h"\n#include <math.h>\n' 'double test_atan2(double x, double y) {\n double test_atan2_result;\n test_atan2_result = atan2(x, y);\n return test_atan2_result;\n}\n' 'double test_pow(double x, double y) {\n double test_pow_result;\n test_pow_result = pow(x, y);\n return test_pow_result;\n}\n' ) assert result[1][0] == "file.h" assert result[1][1] == ( '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n' 'double test_atan2(double x, double y);\n' 'double test_pow(double x, double y);\n' '#endif\n' ) def test_complicated_codegen(): from sympy.functions.elementary.trigonometric import (cos, sin, tan) x, y, z = symbols('x,y,z') name_expr = [ ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()), ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))), ] result = codegen(name_expr, "C89", "file", header=False, empty=False) assert result[0][0] == "file.c" assert result[0][1] == ( '#include "file.h"\n#include <math.h>\n' 'double test1(double x, double y, double z) {\n' ' double test1_result;\n' ' test1_result = ' 'pow(sin(x), 7) + ' '7*pow(sin(x), 6)*cos(y) + ' '7*pow(sin(x), 6)*tan(z) + ' '21*pow(sin(x), 5)*pow(cos(y), 2) + ' '42*pow(sin(x), 5)*cos(y)*tan(z) + ' '21*pow(sin(x), 5)*pow(tan(z), 2) + ' '35*pow(sin(x), 4)*pow(cos(y), 3) + ' '105*pow(sin(x), 4)*pow(cos(y), 2)*tan(z) + ' '105*pow(sin(x), 4)*cos(y)*pow(tan(z), 2) + ' '35*pow(sin(x), 4)*pow(tan(z), 3) + ' '35*pow(sin(x), 3)*pow(cos(y), 4) + ' '140*pow(sin(x), 3)*pow(cos(y), 3)*tan(z) + ' '210*pow(sin(x), 3)*pow(cos(y), 2)*pow(tan(z), 2) + ' '140*pow(sin(x), 3)*cos(y)*pow(tan(z), 3) + ' '35*pow(sin(x), 3)*pow(tan(z), 4) + ' '21*pow(sin(x), 2)*pow(cos(y), 5) + ' '105*pow(sin(x), 2)*pow(cos(y), 4)*tan(z) + ' '210*pow(sin(x), 2)*pow(cos(y), 3)*pow(tan(z), 2) + ' '210*pow(sin(x), 2)*pow(cos(y), 2)*pow(tan(z), 3) + ' '105*pow(sin(x), 2)*cos(y)*pow(tan(z), 4) + ' '21*pow(sin(x), 2)*pow(tan(z), 5) + ' '7*sin(x)*pow(cos(y), 6) + ' '42*sin(x)*pow(cos(y), 5)*tan(z) + ' '105*sin(x)*pow(cos(y), 4)*pow(tan(z), 2) + ' '140*sin(x)*pow(cos(y), 3)*pow(tan(z), 3) + ' '105*sin(x)*pow(cos(y), 2)*pow(tan(z), 4) + ' '42*sin(x)*cos(y)*pow(tan(z), 5) + ' '7*sin(x)*pow(tan(z), 6) + ' 'pow(cos(y), 7) + ' '7*pow(cos(y), 6)*tan(z) + ' '21*pow(cos(y), 5)*pow(tan(z), 2) + ' '35*pow(cos(y), 4)*pow(tan(z), 3) + ' '35*pow(cos(y), 3)*pow(tan(z), 4) + ' '21*pow(cos(y), 2)*pow(tan(z), 5) + ' '7*cos(y)*pow(tan(z), 6) + ' 'pow(tan(z), 7);\n' ' return test1_result;\n' '}\n' 'double test2(double x, double y, double z) {\n' ' double test2_result;\n' ' test2_result = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n' ' return test2_result;\n' '}\n' ) assert result[1][0] == "file.h" assert result[1][1] == ( '#ifndef PROJECT__FILE__H\n' '#define PROJECT__FILE__H\n' 'double test1(double x, double y, double z);\n' 'double test2(double x, double y, double z);\n' '#endif\n' ) def test_loops_c(): from sympy.tensor import IndexedBase, Idx from sympy.core.symbol import symbols n, m = symbols('n m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) (f1, code), (f2, interface) = codegen( ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "C99", "file", header=False, empty=False) assert f1 == 'file.c' expected = ( '#include "file.h"\n' '#include <math.h>\n' 'void matrix_vector(double *A, int m, int n, double *x, double *y) {\n' ' for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' ' }\n' ' for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = %(rhs)s + y[i];\n' ' }\n' ' }\n' '}\n' ) assert (code == expected % {'rhs': 'A[%s]*x[j]' % (i*n + j)} or code == expected % {'rhs': 'A[%s]*x[j]' % (j + i*n)} or code == expected % {'rhs': 'x[j]*A[%s]' % (i*n + j)} or code == expected % {'rhs': 'x[j]*A[%s]' % (j + i*n)}) assert f2 == 'file.h' assert interface == ( '#ifndef PROJECT__FILE__H\n' '#define PROJECT__FILE__H\n' 'void matrix_vector(double *A, int m, int n, double *x, double *y);\n' '#endif\n' ) def test_dummy_loops_c(): from sympy.tensor import IndexedBase, Idx i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( '#include "file.h"\n' '#include <math.h>\n' 'void test_dummies(int m_%(mno)i, double *x, double *y) {\n' ' for (int i_%(ino)i=0; i_%(ino)i<m_%(mno)i; i_%(ino)i++){\n' ' y[i_%(ino)i] = x[i_%(ino)i];\n' ' }\n' '}\n' ) % {'ino': i.label.dummy_index, 'mno': m.dummy_index} r = make_routine('test_dummies', Eq(y[i], x[i])) c89 = C89CodeGen() c99 = C99CodeGen() code = get_string(c99.dump_c, [r]) assert code == expected with raises(NotImplementedError): get_string(c89.dump_c, [r]) def test_partial_loops_c(): # check that loop boundaries are determined by Idx, and array strides # determined by shape of IndexedBase object. from sympy.tensor import IndexedBase, Idx from sympy.core.symbol import symbols n, m, o, p = symbols('n m o p', integer=True) A = IndexedBase('A', shape=(m, p)) x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', (o, m - 5)) # Note: bounds are inclusive j = Idx('j', n) # dimension n corresponds to bounds (0, n - 1) (f1, code), (f2, interface) = codegen( ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "C99", "file", header=False, empty=False) assert f1 == 'file.c' expected = ( '#include "file.h"\n' '#include <math.h>\n' 'void matrix_vector(double *A, int m, int n, int o, int p, double *x, double *y) {\n' ' for (int i=o; i<%(upperi)s; i++){\n' ' y[i] = 0;\n' ' }\n' ' for (int i=o; i<%(upperi)s; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = %(rhs)s + y[i];\n' ' }\n' ' }\n' '}\n' ) % {'upperi': m - 4, 'rhs': '%(rhs)s'} assert (code == expected % {'rhs': 'A[%s]*x[j]' % (i*p + j)} or code == expected % {'rhs': 'A[%s]*x[j]' % (j + i*p)} or code == expected % {'rhs': 'x[j]*A[%s]' % (i*p + j)} or code == expected % {'rhs': 'x[j]*A[%s]' % (j + i*p)}) assert f2 == 'file.h' assert interface == ( '#ifndef PROJECT__FILE__H\n' '#define PROJECT__FILE__H\n' 'void matrix_vector(double *A, int m, int n, int o, int p, double *x, double *y);\n' '#endif\n' ) def test_output_arg_c(): from sympy.core.relational import Equality from sympy.functions.elementary.trigonometric import (cos, sin) x, y, z = symbols("x,y,z") r = make_routine("foo", [Equality(y, sin(x)), cos(x)]) c = C89CodeGen() result = c.write([r], "test", header=False, empty=False) assert result[0][0] == "test.c" expected = ( '#include "test.h"\n' '#include <math.h>\n' 'double foo(double x, double *y) {\n' ' (*y) = sin(x);\n' ' double foo_result;\n' ' foo_result = cos(x);\n' ' return foo_result;\n' '}\n' ) assert result[0][1] == expected def test_output_arg_c_reserved_words(): from sympy.core.relational import Equality from sympy.functions.elementary.trigonometric import (cos, sin) x, y, z = symbols("if, while, z") r = make_routine("foo", [Equality(y, sin(x)), cos(x)]) c = C89CodeGen() result = c.write([r], "test", header=False, empty=False) assert result[0][0] == "test.c" expected = ( '#include "test.h"\n' '#include <math.h>\n' 'double foo(double if_, double *while_) {\n' ' (*while_) = sin(if_);\n' ' double foo_result;\n' ' foo_result = cos(if_);\n' ' return foo_result;\n' '}\n' ) assert result[0][1] == expected def test_multidim_c_argument_cse(): A_sym = MatrixSymbol('A', 3, 3) b_sym = MatrixSymbol('b', 3, 1) A = Matrix(A_sym) b = Matrix(b_sym) c = A*b cgen = CCodeGen(project="test", cse=True) r = cgen.routine("c", c) r.arguments[-1].result_var = "out" r.arguments[-1]._name = "out" code = get_string(cgen.dump_c, [r], prefix="test") expected = ( '#include "test.h"\n' "#include <math.h>\n" "void c(double *A, double *b, double *out) {\n" " double x0[9];\n" " x0[0] = A[0];\n" " x0[1] = A[1];\n" " x0[2] = A[2];\n" " x0[3] = A[3];\n" " x0[4] = A[4];\n" " x0[5] = A[5];\n" " x0[6] = A[6];\n" " x0[7] = A[7];\n" " x0[8] = A[8];\n" " double x1[3];\n" " x1[0] = b[0];\n" " x1[1] = b[1];\n" " x1[2] = b[2];\n" " const double x2 = x1[0];\n" " const double x3 = x1[1];\n" " const double x4 = x1[2];\n" " out[0] = x2*x0[0] + x3*x0[1] + x4*x0[2];\n" " out[1] = x2*x0[3] + x3*x0[4] + x4*x0[5];\n" " out[2] = x2*x0[6] + x3*x0[7] + x4*x0[8];\n" "}\n" ) assert code == expected def test_ccode_results_named_ordered(): x, y, z = symbols('x,y,z') B, C = symbols('B,C') A = MatrixSymbol('A', 1, 3) expr1 = Equality(A, Matrix([[1, 2, x]])) expr2 = Equality(C, (x + y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) expected = ( '#include "test.h"\n' '#include <math.h>\n' 'void test(double x, double *C, double z, double y, double *A, double *B) {\n' ' (*C) = z*(x + y);\n' ' A[0] = 1;\n' ' A[1] = 2;\n' ' A[2] = x;\n' ' (*B) = 2*x;\n' '}\n' ) result = codegen(name_expr, "c", "test", header=False, empty=False, argument_sequence=(x, C, z, y, A, B)) source = result[0][1] assert source == expected def test_ccode_matrixsymbol_slice(): A = MatrixSymbol('A', 5, 3) B = MatrixSymbol('B', 1, 3) C = MatrixSymbol('C', 1, 3) D = MatrixSymbol('D', 5, 1) name_expr = ("test", [Equality(B, A[0, :]), Equality(C, A[1, :]), Equality(D, A[:, 2])]) result = codegen(name_expr, "c99", "test", header=False, empty=False) source = result[0][1] expected = ( '#include "test.h"\n' '#include <math.h>\n' 'void test(double *A, double *B, double *C, double *D) {\n' ' B[0] = A[0];\n' ' B[1] = A[1];\n' ' B[2] = A[2];\n' ' C[0] = A[3];\n' ' C[1] = A[4];\n' ' C[2] = A[5];\n' ' D[0] = A[2];\n' ' D[1] = A[5];\n' ' D[2] = A[8];\n' ' D[3] = A[11];\n' ' D[4] = A[14];\n' '}\n' ) assert source == expected def test_ccode_cse(): a, b, c, d = symbols('a b c d') e = MatrixSymbol('e', 3, 1) name_expr = ("test", [Equality(e, Matrix([[a*b], [a*b + c*d], [a*b*c*d]]))]) generator = CCodeGen(cse=True) result = codegen(name_expr, code_gen=generator, header=False, empty=False) source = result[0][1] expected = ( '#include "test.h"\n' '#include <math.h>\n' 'void test(double a, double b, double c, double d, double *e) {\n' ' const double x0 = a*b;\n' ' const double x1 = c*d;\n' ' e[0] = x0;\n' ' e[1] = x0 + x1;\n' ' e[2] = x0*x1;\n' '}\n' ) assert source == expected def test_ccode_unused_array_arg(): x = MatrixSymbol('x', 2, 1) # x does not appear in output name_expr = ("test", 1.0) generator = CCodeGen() result = codegen(name_expr, code_gen=generator, header=False, empty=False, argument_sequence=(x,)) source = result[0][1] # note: x should appear as (double *) expected = ( '#include "test.h"\n' '#include <math.h>\n' 'double test(double *x) {\n' ' double test_result;\n' ' test_result = 1.0;\n' ' return test_result;\n' '}\n' ) assert source == expected def test_empty_f_code(): code_gen = FCodeGen() source = get_string(code_gen.dump_f95, []) assert source == "" def test_empty_f_code_with_header(): code_gen = FCodeGen() source = get_string(code_gen.dump_f95, [], header=True) assert source[:82] == ( "!******************************************************************************\n!*" ) # " Code generated with SymPy 0.7.2-git " assert source[158:] == ( "*\n" "!* *\n" "!* See http://www.sympy.org/ for more information. *\n" "!* *\n" "!* This file is part of 'project' *\n" "!******************************************************************************\n" ) def test_empty_f_header(): code_gen = FCodeGen() source = get_string(code_gen.dump_h, []) assert source == "" def test_simple_f_code(): x, y, z = symbols('x,y,z') expr = (x + y)*z routine = make_routine("test", expr) code_gen = FCodeGen() source = get_string(code_gen.dump_f95, [routine]) expected = ( "REAL*8 function test(x, y, z)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "REAL*8, intent(in) :: z\n" "test = z*(x + y)\n" "end function\n" ) assert source == expected def test_numbersymbol_f_code(): routine = make_routine("test", pi**Catalan) code_gen = FCodeGen() source = get_string(code_gen.dump_f95, [routine]) expected = ( "REAL*8 function test()\n" "implicit none\n" "REAL*8, parameter :: Catalan = %sd0\n" "REAL*8, parameter :: pi = %sd0\n" "test = pi**Catalan\n" "end function\n" ) % (Catalan.evalf(17), pi.evalf(17)) assert source == expected def test_erf_f_code(): x = symbols('x') routine = make_routine("test", erf(x) - erf(-2 * x)) code_gen = FCodeGen() source = get_string(code_gen.dump_f95, [routine]) expected = ( "REAL*8 function test(x)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "test = erf(x) + erf(2.0d0*x)\n" "end function\n" ) assert source == expected, source def test_f_code_argument_order(): x, y, z = symbols('x,y,z') expr = x + y routine = make_routine("test", expr, argument_sequence=[z, x, y]) code_gen = FCodeGen() source = get_string(code_gen.dump_f95, [routine]) expected = ( "REAL*8 function test(z, x, y)\n" "implicit none\n" "REAL*8, intent(in) :: z\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "test = x + y\n" "end function\n" ) assert source == expected def test_simple_f_header(): x, y, z = symbols('x,y,z') expr = (x + y)*z routine = make_routine("test", expr) code_gen = FCodeGen() source = get_string(code_gen.dump_h, [routine]) expected = ( "interface\n" "REAL*8 function test(x, y, z)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "REAL*8, intent(in) :: z\n" "end function\n" "end interface\n" ) assert source == expected def test_simple_f_codegen(): x, y, z = symbols('x,y,z') expr = (x + y)*z result = codegen( ("test", expr), "F95", "file", header=False, empty=False) expected = [ ("file.f90", "REAL*8 function test(x, y, z)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "REAL*8, intent(in) :: z\n" "test = z*(x + y)\n" "end function\n"), ("file.h", "interface\n" "REAL*8 function test(x, y, z)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "REAL*8, intent(in) :: z\n" "end function\n" "end interface\n") ] assert result == expected def test_multiple_results_f(): x, y, z = symbols('x,y,z') expr1 = (x + y)*z expr2 = (x - y)*z routine = make_routine( "test", [expr1, expr2] ) code_gen = FCodeGen() raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine])) def test_no_results_f(): raises(ValueError, lambda: make_routine("test", [])) def test_intrinsic_math_codegen(): # not included: log10 from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import log from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan) x = symbols('x') name_expr = [ ("test_abs", Abs(x)), ("test_acos", acos(x)), ("test_asin", asin(x)), ("test_atan", atan(x)), ("test_cos", cos(x)), ("test_cosh", cosh(x)), ("test_log", log(x)), ("test_ln", log(x)), ("test_sin", sin(x)), ("test_sinh", sinh(x)), ("test_sqrt", sqrt(x)), ("test_tan", tan(x)), ("test_tanh", tanh(x)), ] result = codegen(name_expr, "F95", "file", header=False, empty=False) assert result[0][0] == "file.f90" expected = ( 'REAL*8 function test_abs(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_abs = abs(x)\n' 'end function\n' 'REAL*8 function test_acos(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_acos = acos(x)\n' 'end function\n' 'REAL*8 function test_asin(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_asin = asin(x)\n' 'end function\n' 'REAL*8 function test_atan(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_atan = atan(x)\n' 'end function\n' 'REAL*8 function test_cos(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_cos = cos(x)\n' 'end function\n' 'REAL*8 function test_cosh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_cosh = cosh(x)\n' 'end function\n' 'REAL*8 function test_log(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_log = log(x)\n' 'end function\n' 'REAL*8 function test_ln(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_ln = log(x)\n' 'end function\n' 'REAL*8 function test_sin(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_sin = sin(x)\n' 'end function\n' 'REAL*8 function test_sinh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_sinh = sinh(x)\n' 'end function\n' 'REAL*8 function test_sqrt(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_sqrt = sqrt(x)\n' 'end function\n' 'REAL*8 function test_tan(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_tan = tan(x)\n' 'end function\n' 'REAL*8 function test_tanh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_tanh = tanh(x)\n' 'end function\n' ) assert result[0][1] == expected assert result[1][0] == "file.h" expected = ( 'interface\n' 'REAL*8 function test_abs(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_acos(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_asin(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_atan(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_cos(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_cosh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_log(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_ln(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_sin(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_sinh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_sqrt(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_tan(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_tanh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' ) assert result[1][1] == expected def test_intrinsic_math2_codegen(): # not included: frexp, ldexp, modf, fmod from sympy.functions.elementary.trigonometric import atan2 x, y = symbols('x,y') name_expr = [ ("test_atan2", atan2(x, y)), ("test_pow", x**y), ] result = codegen(name_expr, "F95", "file", header=False, empty=False) assert result[0][0] == "file.f90" expected = ( 'REAL*8 function test_atan2(x, y)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'test_atan2 = atan2(x, y)\n' 'end function\n' 'REAL*8 function test_pow(x, y)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'test_pow = x**y\n' 'end function\n' ) assert result[0][1] == expected assert result[1][0] == "file.h" expected = ( 'interface\n' 'REAL*8 function test_atan2(x, y)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_pow(x, y)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'end function\n' 'end interface\n' ) assert result[1][1] == expected def test_complicated_codegen_f95(): from sympy.functions.elementary.trigonometric import (cos, sin, tan) x, y, z = symbols('x,y,z') name_expr = [ ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()), ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))), ] result = codegen(name_expr, "F95", "file", header=False, empty=False) assert result[0][0] == "file.f90" expected = ( 'REAL*8 function test1(x, y, z)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'REAL*8, intent(in) :: z\n' 'test1 = sin(x)**7 + 7*sin(x)**6*cos(y) + 7*sin(x)**6*tan(z) + 21*sin(x) &\n' ' **5*cos(y)**2 + 42*sin(x)**5*cos(y)*tan(z) + 21*sin(x)**5*tan(z) &\n' ' **2 + 35*sin(x)**4*cos(y)**3 + 105*sin(x)**4*cos(y)**2*tan(z) + &\n' ' 105*sin(x)**4*cos(y)*tan(z)**2 + 35*sin(x)**4*tan(z)**3 + 35*sin( &\n' ' x)**3*cos(y)**4 + 140*sin(x)**3*cos(y)**3*tan(z) + 210*sin(x)**3* &\n' ' cos(y)**2*tan(z)**2 + 140*sin(x)**3*cos(y)*tan(z)**3 + 35*sin(x) &\n' ' **3*tan(z)**4 + 21*sin(x)**2*cos(y)**5 + 105*sin(x)**2*cos(y)**4* &\n' ' tan(z) + 210*sin(x)**2*cos(y)**3*tan(z)**2 + 210*sin(x)**2*cos(y) &\n' ' **2*tan(z)**3 + 105*sin(x)**2*cos(y)*tan(z)**4 + 21*sin(x)**2*tan &\n' ' (z)**5 + 7*sin(x)*cos(y)**6 + 42*sin(x)*cos(y)**5*tan(z) + 105* &\n' ' sin(x)*cos(y)**4*tan(z)**2 + 140*sin(x)*cos(y)**3*tan(z)**3 + 105 &\n' ' *sin(x)*cos(y)**2*tan(z)**4 + 42*sin(x)*cos(y)*tan(z)**5 + 7*sin( &\n' ' x)*tan(z)**6 + cos(y)**7 + 7*cos(y)**6*tan(z) + 21*cos(y)**5*tan( &\n' ' z)**2 + 35*cos(y)**4*tan(z)**3 + 35*cos(y)**3*tan(z)**4 + 21*cos( &\n' ' y)**2*tan(z)**5 + 7*cos(y)*tan(z)**6 + tan(z)**7\n' 'end function\n' 'REAL*8 function test2(x, y, z)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'REAL*8, intent(in) :: z\n' 'test2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n' 'end function\n' ) assert result[0][1] == expected assert result[1][0] == "file.h" expected = ( 'interface\n' 'REAL*8 function test1(x, y, z)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'REAL*8, intent(in) :: z\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test2(x, y, z)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'REAL*8, intent(in) :: z\n' 'end function\n' 'end interface\n' ) assert result[1][1] == expected def test_loops(): from sympy.tensor import IndexedBase, Idx from sympy.core.symbol import symbols n, m = symbols('n,m', integer=True) A, x, y = map(IndexedBase, 'Axy') i = Idx('i', m) j = Idx('j', n) (f1, code), (f2, interface) = codegen( ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False) assert f1 == 'file.f90' expected = ( 'subroutine matrix_vector(A, m, n, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m\n' 'INTEGER*4, intent(in) :: n\n' 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' 'REAL*8, intent(in), dimension(1:n) :: x\n' 'REAL*8, intent(out), dimension(1:m) :: y\n' 'INTEGER*4 :: i\n' 'INTEGER*4 :: j\n' 'do i = 1, m\n' ' y(i) = 0\n' 'end do\n' 'do i = 1, m\n' ' do j = 1, n\n' ' y(i) = %(rhs)s + y(i)\n' ' end do\n' 'end do\n' 'end subroutine\n' ) assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\ code == expected % {'rhs': 'x(j)*A(i, j)'} assert f2 == 'file.h' assert interface == ( 'interface\n' 'subroutine matrix_vector(A, m, n, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m\n' 'INTEGER*4, intent(in) :: n\n' 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' 'REAL*8, intent(in), dimension(1:n) :: x\n' 'REAL*8, intent(out), dimension(1:m) :: y\n' 'end subroutine\n' 'end interface\n' ) def test_dummy_loops_f95(): from sympy.tensor import IndexedBase, Idx i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( 'subroutine test_dummies(m_%(mcount)i, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m_%(mcount)i\n' 'REAL*8, intent(in), dimension(1:m_%(mcount)i) :: x\n' 'REAL*8, intent(out), dimension(1:m_%(mcount)i) :: y\n' 'INTEGER*4 :: i_%(icount)i\n' 'do i_%(icount)i = 1, m_%(mcount)i\n' ' y(i_%(icount)i) = x(i_%(icount)i)\n' 'end do\n' 'end subroutine\n' ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} r = make_routine('test_dummies', Eq(y[i], x[i])) c = FCodeGen() code = get_string(c.dump_f95, [r]) assert code == expected def test_loops_InOut(): from sympy.tensor import IndexedBase, Idx from sympy.core.symbol import symbols i, j, n, m = symbols('i,j,n,m', integer=True) A, x, y = symbols('A,x,y') A = IndexedBase(A)[Idx(i, m), Idx(j, n)] x = IndexedBase(x)[Idx(j, n)] y = IndexedBase(y)[Idx(i, m)] (f1, code), (f2, interface) = codegen( ('matrix_vector', Eq(y, y + A*x)), "F95", "file", header=False, empty=False) assert f1 == 'file.f90' expected = ( 'subroutine matrix_vector(A, m, n, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m\n' 'INTEGER*4, intent(in) :: n\n' 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' 'REAL*8, intent(in), dimension(1:n) :: x\n' 'REAL*8, intent(inout), dimension(1:m) :: y\n' 'INTEGER*4 :: i\n' 'INTEGER*4 :: j\n' 'do i = 1, m\n' ' do j = 1, n\n' ' y(i) = %(rhs)s + y(i)\n' ' end do\n' 'end do\n' 'end subroutine\n' ) assert (code == expected % {'rhs': 'A(i, j)*x(j)'} or code == expected % {'rhs': 'x(j)*A(i, j)'}) assert f2 == 'file.h' assert interface == ( 'interface\n' 'subroutine matrix_vector(A, m, n, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m\n' 'INTEGER*4, intent(in) :: n\n' 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' 'REAL*8, intent(in), dimension(1:n) :: x\n' 'REAL*8, intent(inout), dimension(1:m) :: y\n' 'end subroutine\n' 'end interface\n' ) def test_partial_loops_f(): # check that loop boundaries are determined by Idx, and array strides # determined by shape of IndexedBase object. from sympy.tensor import IndexedBase, Idx from sympy.core.symbol import symbols n, m, o, p = symbols('n m o p', integer=True) A = IndexedBase('A', shape=(m, p)) x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', (o, m - 5)) # Note: bounds are inclusive j = Idx('j', n) # dimension n corresponds to bounds (0, n - 1) (f1, code), (f2, interface) = codegen( ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False) expected = ( 'subroutine matrix_vector(A, m, n, o, p, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m\n' 'INTEGER*4, intent(in) :: n\n' 'INTEGER*4, intent(in) :: o\n' 'INTEGER*4, intent(in) :: p\n' 'REAL*8, intent(in), dimension(1:m, 1:p) :: A\n' 'REAL*8, intent(in), dimension(1:n) :: x\n' 'REAL*8, intent(out), dimension(1:%(iup-ilow)s) :: y\n' 'INTEGER*4 :: i\n' 'INTEGER*4 :: j\n' 'do i = %(ilow)s, %(iup)s\n' ' y(i) = 0\n' 'end do\n' 'do i = %(ilow)s, %(iup)s\n' ' do j = 1, n\n' ' y(i) = %(rhs)s + y(i)\n' ' end do\n' 'end do\n' 'end subroutine\n' ) % { 'rhs': '%(rhs)s', 'iup': str(m - 4), 'ilow': str(1 + o), 'iup-ilow': str(m - 4 - o) } assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\ code == expected % {'rhs': 'x(j)*A(i, j)'} def test_output_arg_f(): from sympy.core.relational import Equality from sympy.functions.elementary.trigonometric import (cos, sin) x, y, z = symbols("x,y,z") r = make_routine("foo", [Equality(y, sin(x)), cos(x)]) c = FCodeGen() result = c.write([r], "test", header=False, empty=False) assert result[0][0] == "test.f90" assert result[0][1] == ( 'REAL*8 function foo(x, y)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(out) :: y\n' 'y = sin(x)\n' 'foo = cos(x)\n' 'end function\n' ) def test_inline_function(): from sympy.tensor import IndexedBase, Idx from sympy.core.symbol import symbols n, m = symbols('n m', integer=True) A, x, y = map(IndexedBase, 'Axy') i = Idx('i', m) p = FCodeGen() func = implemented_function('func', Lambda(n, n*(n + 1))) routine = make_routine('test_inline', Eq(y[i], func(x[i]))) code = get_string(p.dump_f95, [routine]) expected = ( 'subroutine test_inline(m, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m\n' 'REAL*8, intent(in), dimension(1:m) :: x\n' 'REAL*8, intent(out), dimension(1:m) :: y\n' 'INTEGER*4 :: i\n' 'do i = 1, m\n' ' y(i) = %s*%s\n' 'end do\n' 'end subroutine\n' ) args = ('x(i)', '(x(i) + 1)') assert code == expected % args or\ code == expected % args[::-1] def test_f_code_call_signature_wrap(): # Issue #7934 x = symbols('x:20') expr = 0 for sym in x: expr += sym routine = make_routine("test", expr) code_gen = FCodeGen() source = get_string(code_gen.dump_f95, [routine]) expected = """\ REAL*8 function test(x0, x1, x10, x11, x12, x13, x14, x15, x16, x17, x18, & x19, x2, x3, x4, x5, x6, x7, x8, x9) implicit none REAL*8, intent(in) :: x0 REAL*8, intent(in) :: x1 REAL*8, intent(in) :: x10 REAL*8, intent(in) :: x11 REAL*8, intent(in) :: x12 REAL*8, intent(in) :: x13 REAL*8, intent(in) :: x14 REAL*8, intent(in) :: x15 REAL*8, intent(in) :: x16 REAL*8, intent(in) :: x17 REAL*8, intent(in) :: x18 REAL*8, intent(in) :: x19 REAL*8, intent(in) :: x2 REAL*8, intent(in) :: x3 REAL*8, intent(in) :: x4 REAL*8, intent(in) :: x5 REAL*8, intent(in) :: x6 REAL*8, intent(in) :: x7 REAL*8, intent(in) :: x8 REAL*8, intent(in) :: x9 test = x0 + x1 + x10 + x11 + x12 + x13 + x14 + x15 + x16 + x17 + x18 + & x19 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 end function """ assert source == expected def test_check_case(): x, X = symbols('x,X') raises(CodeGenError, lambda: codegen(('test', x*X), 'f95', 'prefix')) def test_check_case_false_positive(): # The upper case/lower case exception should not be triggered by SymPy # objects that differ only because of assumptions. (It may be useful to # have a check for that as well, but here we only want to test against # false positives with respect to case checking.) x1 = symbols('x') x2 = symbols('x', my_assumption=True) try: codegen(('test', x1*x2), 'f95', 'prefix') except CodeGenError as e: if e.args[0].startswith("Fortran ignores case."): raise AssertionError("This exception should not be raised!") def test_c_fortran_omit_routine_name(): x, y = symbols("x,y") name_expr = [("foo", 2*x)] result = codegen(name_expr, "F95", header=False, empty=False) expresult = codegen(name_expr, "F95", "foo", header=False, empty=False) assert result[0][1] == expresult[0][1] name_expr = ("foo", x*y) result = codegen(name_expr, "F95", header=False, empty=False) expresult = codegen(name_expr, "F95", "foo", header=False, empty=False) assert result[0][1] == expresult[0][1] name_expr = ("foo", Matrix([[x, y], [x+y, x-y]])) result = codegen(name_expr, "C89", header=False, empty=False) expresult = codegen(name_expr, "C89", "foo", header=False, empty=False) assert result[0][1] == expresult[0][1] def test_fcode_matrix_output(): x, y, z = symbols('x,y,z') e1 = x + y e2 = Matrix([[x, y], [z, 16]]) name_expr = ("test", (e1, e2)) result = codegen(name_expr, "f95", "test", header=False, empty=False) source = result[0][1] expected = ( "REAL*8 function test(x, y, z, out_%(hash)s)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "REAL*8, intent(in) :: z\n" "REAL*8, intent(out), dimension(1:2, 1:2) :: out_%(hash)s\n" "out_%(hash)s(1, 1) = x\n" "out_%(hash)s(2, 1) = z\n" "out_%(hash)s(1, 2) = y\n" "out_%(hash)s(2, 2) = 16\n" "test = x + y\n" "end function\n" ) # look for the magic number a = source.splitlines()[5] b = a.split('_') out = b[1] expected = expected % {'hash': out} assert source == expected def test_fcode_results_named_ordered(): x, y, z = symbols('x,y,z') B, C = symbols('B,C') A = MatrixSymbol('A', 1, 3) expr1 = Equality(A, Matrix([[1, 2, x]])) expr2 = Equality(C, (x + y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result = codegen(name_expr, "f95", "test", header=False, empty=False, argument_sequence=(x, z, y, C, A, B)) source = result[0][1] expected = ( "subroutine test(x, z, y, C, A, B)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: z\n" "REAL*8, intent(in) :: y\n" "REAL*8, intent(out) :: C\n" "REAL*8, intent(out) :: B\n" "REAL*8, intent(out), dimension(1:1, 1:3) :: A\n" "C = z*(x + y)\n" "A(1, 1) = 1\n" "A(1, 2) = 2\n" "A(1, 3) = x\n" "B = 2*x\n" "end subroutine\n" ) assert source == expected def test_fcode_matrixsymbol_slice(): A = MatrixSymbol('A', 2, 3) B = MatrixSymbol('B', 1, 3) C = MatrixSymbol('C', 1, 3) D = MatrixSymbol('D', 2, 1) name_expr = ("test", [Equality(B, A[0, :]), Equality(C, A[1, :]), Equality(D, A[:, 2])]) result = codegen(name_expr, "f95", "test", header=False, empty=False) source = result[0][1] expected = ( "subroutine test(A, B, C, D)\n" "implicit none\n" "REAL*8, intent(in), dimension(1:2, 1:3) :: A\n" "REAL*8, intent(out), dimension(1:1, 1:3) :: B\n" "REAL*8, intent(out), dimension(1:1, 1:3) :: C\n" "REAL*8, intent(out), dimension(1:2, 1:1) :: D\n" "B(1, 1) = A(1, 1)\n" "B(1, 2) = A(1, 2)\n" "B(1, 3) = A(1, 3)\n" "C(1, 1) = A(2, 1)\n" "C(1, 2) = A(2, 2)\n" "C(1, 3) = A(2, 3)\n" "D(1, 1) = A(1, 3)\n" "D(2, 1) = A(2, 3)\n" "end subroutine\n" ) assert source == expected def test_fcode_matrixsymbol_slice_autoname(): # see issue #8093 A = MatrixSymbol('A', 2, 3) name_expr = ("test", A[:, 1]) result = codegen(name_expr, "f95", "test", header=False, empty=False) source = result[0][1] expected = ( "subroutine test(A, out_%(hash)s)\n" "implicit none\n" "REAL*8, intent(in), dimension(1:2, 1:3) :: A\n" "REAL*8, intent(out), dimension(1:2, 1:1) :: out_%(hash)s\n" "out_%(hash)s(1, 1) = A(1, 2)\n" "out_%(hash)s(2, 1) = A(2, 2)\n" "end subroutine\n" ) # look for the magic number a = source.splitlines()[3] b = a.split('_') out = b[1] expected = expected % {'hash': out} assert source == expected def test_global_vars(): x, y, z, t = symbols("x y z t") result = codegen(('f', x*y), "F95", header=False, empty=False, global_vars=(y,)) source = result[0][1] expected = ( "REAL*8 function f(x)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "f = x*y\n" "end function\n" ) assert source == expected expected = ( '#include "f.h"\n' '#include <math.h>\n' 'double f(double x, double y) {\n' ' double f_result;\n' ' f_result = x*y + z;\n' ' return f_result;\n' '}\n' ) result = codegen(('f', x*y+z), "C", header=False, empty=False, global_vars=(z, t)) source = result[0][1] assert source == expected def test_custom_codegen(): from sympy.printing.c import C99CodePrinter from sympy.functions.elementary.exponential import exp printer = C99CodePrinter(settings={'user_functions': {'exp': 'fastexp'}}) x, y = symbols('x y') expr = exp(x + y) # replace math.h with a different header gen = C99CodeGen(printer=printer, preprocessor_statements=['#include "fastexp.h"']) expected = ( '#include "expr.h"\n' '#include "fastexp.h"\n' 'double expr(double x, double y) {\n' ' double expr_result;\n' ' expr_result = fastexp(x + y);\n' ' return expr_result;\n' '}\n' ) result = codegen(('expr', expr), header=False, empty=False, code_gen=gen) source = result[0][1] assert source == expected # use both math.h and an external header gen = C99CodeGen(printer=printer) gen.preprocessor_statements.append('#include "fastexp.h"') expected = ( '#include "expr.h"\n' '#include <math.h>\n' '#include "fastexp.h"\n' 'double expr(double x, double y) {\n' ' double expr_result;\n' ' expr_result = fastexp(x + y);\n' ' return expr_result;\n' '}\n' ) result = codegen(('expr', expr), header=False, empty=False, code_gen=gen) source = result[0][1] assert source == expected def test_c_with_printer(): #issue 13586 from sympy.printing.c import C99CodePrinter class CustomPrinter(C99CodePrinter): def _print_Pow(self, expr): return "fastpow({}, {})".format(self._print(expr.base), self._print(expr.exp)) x = symbols('x') expr = x**3 expected =[ ("file.c", "#include \"file.h\"\n" "#include <math.h>\n" "double test(double x) {\n" " double test_result;\n" " test_result = fastpow(x, 3);\n" " return test_result;\n" "}\n"), ("file.h", "#ifndef PROJECT__FILE__H\n" "#define PROJECT__FILE__H\n" "double test(double x);\n" "#endif\n") ] result = codegen(("test", expr), "C","file", header=False, empty=False, printer = CustomPrinter()) assert result == expected def test_fcode_complex(): import sympy.utilities.codegen sympy.utilities.codegen.COMPLEX_ALLOWED = True x = Symbol('x', real=True) y = Symbol('y',real=True) result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False) source = (result[0][1]) expected = ( "REAL*8 function test(x, y)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "test = x + y\n" "end function\n") assert source == expected x = Symbol('x') y = Symbol('y',real=True) result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False) source = (result[0][1]) expected = ( "COMPLEX*16 function test(x, y)\n" "implicit none\n" "COMPLEX*16, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "test = x + y\n" "end function\n" ) assert source==expected sympy.utilities.codegen.COMPLEX_ALLOWED = False
330feb449afa2fd82ad67c2658927ed5aa8c180cf237c676068b5d4aba038d81
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 SymPyDeprecationWarning 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)) 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: SymPyDeprecationWarning( feature="Permutation.print_cyclic = {}".format(perm_cyclic), useinstead="init_printing(perm_cyclic={})" .format(perm_cyclic), issue=15201, deprecated_since_version="1.6").warn() else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: return self._print_Cycle(Cycle(expr)) lower = expr.array_form upper = list(range(len(lower))) result = stringPict('') first = True for u, l in zip(upper, lower): s1 = self._print(u) s2 = self._print(l) col = prettyForm(*s1.below(s2)) if first: first = False else: col = prettyForm(*col.left(" ")) result = prettyForm(*result.right(col)) return prettyForm(*result.parens()) def _print_Integral(self, integral): f = integral.function # Add parentheses if arg involves addition of terms and # create a pretty form for the argument prettyF = self._print(f) # XXX generalize parens if f.is_Add: prettyF = prettyForm(*prettyF.parens()) # dx dy dz ... arg = prettyF for x in integral.limits: prettyArg = self._print(x[0]) # XXX qparens (parens if needs-parens) if prettyArg.width() > 1: prettyArg = prettyForm(*prettyArg.parens()) arg = prettyForm(*arg.right(' d', prettyArg)) # \int \int \int ... firstterm = True s = None for lim in integral.limits: # 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: circled_times = "\u2297" return self._print_seq(expr.args, None, None, circled_times, parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"]) def _print_WedgeProduct(self, expr): # This should somehow share the code with _print_TensorProduct: wedge_symbol = "\u2227" return self._print_seq(expr.args, None, None, wedge_symbol, parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"]) def _print_Trace(self, e): D = self._print(e.arg) D = prettyForm(*D.parens('(',')')) D.baseline = D.height()//2 D = prettyForm(*D.left('\n'*(0) + 'tr')) return D def _print_MatrixElement(self, expr): from sympy.matrices import MatrixSymbol 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): 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): 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}': tempstr = tempstr[:paren] + '\N{right parenthesis extension}'\ + ' ' + vectstrs[i] + tempstr[paren + 1:] break elif '\N{RIGHT PARENTHESIS LOWER HOOK}' in tempstr: flag[i] = 1 tempstr = tempstr.replace('\N{RIGHT PARENTHESIS LOWER HOOK}', '\N{RIGHT PARENTHESIS LOWER HOOK}' + ' ' + vectstrs[i]) else: tempstr = tempstr.replace('\N{RIGHT PARENTHESIS UPPER HOOK}', '\N{RIGHT PARENTHESIS UPPER HOOK}' + ' ' + vectstrs[i]) o1[i] = tempstr o1 = [x.split('\n') for x in o1] n_newlines = max([len(x) for x in o1]) # Width of part in its pretty form if 1 in flag: # If there was a fractional scalar for i, parts in enumerate(o1): if len(parts) == 1: # If part has no newline parts.insert(0, ' ' * (len(parts[0]))) flag[i] = 1 for i, parts in enumerate(o1): lengths.append(len(parts[flag[i]])) for j in range(n_newlines): if j+1 <= len(parts): if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths)-1))) if j == flag[i]: strs[flag[i]] += parts[flag[i]] + ' + ' else: strs[j] += parts[j] + ' '*(lengths[-1] - len(parts[j])+ 3) else: if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths)-1))) strs[j] += ' '*(lengths[-1]+3) return prettyForm('\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): # optional argument func_name for supplying custom names # XXX works only for applied functions return self._helper_print_function(e.func, e.args, sort=sort, func_name=func_name) def _print_mathieuc(self, e): return self._print_Function(e, func_name='C') def _print_mathieus(self, e): return self._print_Function(e, func_name='S') def _print_mathieucprime(self, e): return self._print_Function(e, func_name="C'") def _print_mathieusprime(self, e): return self._print_Function(e, func_name="S'") def _helper_print_function(self, func, args, sort=False, func_name=None, delimiter=', ', elementwise=False): if sort: args = sorted(args, key=default_sort_key) if not func_name and hasattr(func, "__name__"): func_name = func.__name__ if func_name: prettyFunc = self._print(Symbol(func_name)) else: prettyFunc = prettyForm(*self._print(func).parens()) if elementwise: if self._use_unicode: circ = pretty_atom('Modifier Letter Low Ring') else: circ = '.' circ = self._print(circ) prettyFunc = prettyForm( binding=prettyForm.LINE, *stringPict.next(prettyFunc, circ) ) prettyArgs = prettyForm(*self._print_seq(args, delimiter=delimiter).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_ElementwiseApplyFunction(self, e): func = e.function arg = e.expr args = [arg] return self._helper_print_function(func, args, delimiter="", elementwise=True) @property def _special_function_classes(self): from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.gamma_functions import gamma, lowergamma from sympy.functions.special.zeta_functions import lerchphi from sympy.functions.special.beta_functions import beta from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.error_functions import Chi return {KroneckerDelta: [greek_unicode['delta'], 'delta'], gamma: [greek_unicode['Gamma'], 'Gamma'], lerchphi: [greek_unicode['Phi'], 'lerchphi'], lowergamma: [greek_unicode['gamma'], 'gamma'], beta: [greek_unicode['Beta'], 'B'], DiracDelta: [greek_unicode['delta'], 'delta'], Chi: ['Chi', 'Chi']} def _print_FunctionClass(self, expr): for cls in self._special_function_classes: if issubclass(expr, cls) and expr.__name__ == cls.__name__: if self._use_unicode: return prettyForm(self._special_function_classes[cls][0]) else: return prettyForm(self._special_function_classes[cls][1]) func_name = expr.__name__ return prettyForm(pretty_symbol(func_name)) def _print_GeometryEntity(self, expr): # GeometryEntity is based on Tuple but should not print like a Tuple return self.emptyPrinter(expr) def _print_lerchphi(self, e): func_name = greek_unicode['Phi'] if self._use_unicode else 'lerchphi' return self._print_Function(e, func_name=func_name) def _print_dirichlet_eta(self, e): func_name = greek_unicode['eta'] if self._use_unicode else 'dirichlet_eta' return self._print_Function(e, func_name=func_name) def _print_Heaviside(self, e): func_name = greek_unicode['theta'] if self._use_unicode else 'Heaviside' 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_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_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) from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.functions.elementary.piecewise import Piecewise from sympy.integrals.integrals import Integral # Convert to pretty forms. Add parens to Add instances if there # is more than one term in the numer/denom for i in range(0, len(a)): if (a[i].is_Add and len(a) > 1) or (i != len(a) - 1 and isinstance(a[i], (Integral, Piecewise, Product, Sum))): a[i] = prettyForm(*self._print(a[i]).parens()) elif a[i].is_Relational: a[i] = prettyForm(*self._print(a[i]).parens()) else: a[i] = self._print(a[i]) for i in range(0, len(b)): if (b[i].is_Add and len(b) > 1) or (i != len(b) - 1 and isinstance(b[i], (Integral, Piecewise, Product, Sum))): b[i] = prettyForm(*self._print(b[i]).parens()) else: b[i] = self._print(b[i]) # Construct a pretty form if len(b) == 0: return prettyForm.__mul__(*a) else: if len(a) == 0: a.append( self._print(S.One) ) return prettyForm.__mul__(*a)/prettyForm.__mul__(*b) # A helper function for _print_Pow to print x**(1/n) def _print_nth_root(self, base, 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 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): field = diff._form_field if hasattr(field, '_coord_sys'): string = field._coord_sys.symbols[field._index].name return self._print('\N{DOUBLE-STRUCK ITALIC SMALL D} ' + pretty_symbol(string)) else: pform = self._print(field) pform = prettyForm(*pform.parens()) return prettyForm(*pform.left("\N{DOUBLE-STRUCK ITALIC SMALL D}")) def _print_Tr(self, p): #TODO: Handle indices pform = self._print(p.args[0]) pform = prettyForm(*pform.left('%s(' % (p.__class__.__name__))) pform = prettyForm(*pform.right(')')) return pform def _print_primenu(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) if self._use_unicode: pform = prettyForm(*pform.left(greek_unicode['nu'])) else: pform = prettyForm(*pform.left('nu')) return pform def _print_primeomega(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) if self._use_unicode: pform = prettyForm(*pform.left(greek_unicode['Omega'])) else: pform = prettyForm(*pform.left('Omega')) return pform def _print_Quantity(self, e): if e.name.name == 'degree': pform = self._print("\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()))
bb4e2324cbbc136644e9a33c0862072ee7eefe402d9eae55b1323c67e8072418
"""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 SymPyDeprecationWarning # 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): SymPyDeprecationWarning( feature="``xstr`` function", useinstead="``str``", deprecated_since_version="1.7").warn() 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 shouldn't be counted """ return len(line.translate(_remove_combining))
ee4af4910f532daa289af5600b6bb1fc0289d729b9c8e2eeb8a04c80763444b0
from typing import Any, Dict as tDict from sympy.testing.pytest import raises 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): """ sT := sreprTest Tests that srepr delivers the expected string and that the condition eval(srepr(expr))==expr holds. """ if import_stmt is None: ENV2 = ENV else: ENV2 = ENV.copy() exec(import_stmt, ENV2) assert srepr(expr) == string assert eval(string, ENV2) == expr def test_printmethod(): class R(Abs): def _sympyrepr(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert srepr(R(x)) == "foo(Symbol('x'))" def test_Add(): sT(x + y, "Add(Symbol('x'), Symbol('y'))") assert srepr(x**2 + 1, order='lex') == "Add(Pow(Symbol('x'), Integer(2)), Integer(1))" assert srepr(x**2 + 1, order='old') == "Add(Integer(1), Pow(Symbol('x'), Integer(2)))" 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), "Permutation(1, 2)", import_stmt) 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'))")
51608d25ed141e467d27644f3971ff80d6d00f2c5e77ece10b52a8f9cc15e296
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 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.numpy import NumPyPrinter, SciPyPrinter from sympy.testing.pytest import raises, skip from sympy.tensor import IndexedBase 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]" def test_PythonCodePrinter_standard(): import sys prntr = PythonCodePrinter({'standard':None}) python_version = sys.version_info.major if python_version == 2: assert prntr.standard == 'python2' if python_version == 3: assert prntr.standard == 'python3' raises(ValueError, lambda: PythonCodePrinter({'standard':'python4'})) def test_MpmathPrinter(): p = MpmathPrinter() assert p.doprint(sign(x)) == 'mpmath.sign(x)' assert p.doprint(Rational(1, 2)) == 'mpmath.mpf(1)/mpmath.mpf(2)' assert p.doprint(S.Exp1) == 'mpmath.e' assert p.doprint(S.Pi) == 'mpmath.pi' assert p.doprint(S.GoldenRatio) == 'mpmath.phi' assert p.doprint(S.EulerGamma) == 'mpmath.euler' assert p.doprint(S.NaN) == 'mpmath.nan' assert p.doprint(S.Infinity) == 'mpmath.inf' assert p.doprint(S.NegativeInfinity) == 'mpmath.ninf' 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' : 'python2'}) assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1./2.)' assert prntr._print_Pow(1/sqrt(x), rational=True) == 'x**(-1./2.)' prntr = PythonCodePrinter({'standard' : 'python3'}) assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' assert prntr._print_Pow(1/sqrt(x), rational=True) == 'x**(-1/2)' prntr = MpmathPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'mpmath.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == \ "x**(mpmath.mpf(1)/mpmath.mpf(2))" prntr = NumPyPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'numpy.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' prntr = SciPyPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'numpy.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' prntr = SymPyPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'sympy.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' 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) == "float('nan')" assert prntr.doprint(-oo) == "float('-inf')" def test_NumPyPrinter_print_seq(): n = NumPyPrinter() assert n._print_seq(range(2)) == '(0, 1,)' def test_issue_16535_16536(): from sympy.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)'
8a425060dff60ffad4db03af84e66f913a34ce57fe2a11dfa2a82f4b85e85db9
from sympy.core.symbol import symbols from sympy.functions import beta, Ei, zeta, Max, Min, sqrt, riemann_xi, frac from sympy.printing.cxx import CXX98CodePrinter, CXX11CodePrinter, CXX17CodePrinter, cxxcode from sympy.codegen.cfunctions import log1p from sympy.testing.pytest import warns_deprecated_sympy x, y, u, v = symbols('x y u v') def test_CXX98CodePrinter(): assert CXX98CodePrinter().doprint(Max(x, 3)) in ('std::max(x, 3)', 'std::max(3, x)') assert CXX98CodePrinter().doprint(Min(x, 3, sqrt(x))) == 'std::min(3, std::min(x, std::sqrt(x)))' cxx98printer = CXX98CodePrinter() assert cxx98printer.language == 'C++' assert cxx98printer.standard == 'C++98' assert 'template' in cxx98printer.reserved_words assert 'alignas' not in cxx98printer.reserved_words def test_CXX11CodePrinter(): assert CXX11CodePrinter().doprint(log1p(x)) == 'std::log1p(x)' cxx11printer = CXX11CodePrinter() assert cxx11printer.language == 'C++' assert cxx11printer.standard == 'C++11' assert 'operator' in cxx11printer.reserved_words assert 'noexcept' in cxx11printer.reserved_words assert 'concept' not in cxx11printer.reserved_words def test_subclass_print_method(): class MyPrinter(CXX11CodePrinter): def _print_log1p(self, expr): return 'my_library::log1p(%s)' % ', '.join(map(self._print, expr.args)) assert MyPrinter().doprint(log1p(x)) == 'my_library::log1p(x)' def test_subclass_print_method__ns(): class MyPrinter(CXX11CodePrinter): _ns = 'my_library::' p = CXX11CodePrinter() myp = MyPrinter() assert p.doprint(log1p(x)) == 'std::log1p(x)' assert myp.doprint(log1p(x)) == 'my_library::log1p(x)' def test_CXX17CodePrinter(): assert CXX17CodePrinter().doprint(beta(x, y)) == 'std::beta(x, y)' assert CXX17CodePrinter().doprint(Ei(x)) == 'std::expint(x)' assert CXX17CodePrinter().doprint(zeta(x)) == 'std::riemann_zeta(x)' # Automatic rewrite assert CXX17CodePrinter().doprint(frac(x)) == 'x - std::floor(x)' assert CXX17CodePrinter().doprint(riemann_xi(x)) == '(1.0/2.0)*std::pow(M_PI, -1.0/2.0*x)*x*(x - 1)*std::tgamma((1.0/2.0)*x)*std::riemann_zeta(x)' def test_cxxcode(): assert sorted(cxxcode(sqrt(x)*.5).split('*')) == sorted(['0.5', 'std::sqrt(x)']) def test_cxxcode_submodule(): # Test the compatibility sympy.printing.cxxcode module imports with warns_deprecated_sympy(): import sympy.printing.cxxcode # noqa:F401 def test_cxxcode_nested_minmax(): assert cxxcode(Max(Min(x, y), Min(u, v))) \ == 'std::max(std::min(u, v), std::min(x, y))' assert cxxcode(Min(Max(x, y), Max(u, v))) \ == 'std::min(std::max(u, v), std::max(x, y))'
54d16f5d5084574576cb3884703118a000965d9c7f244a14d5e49a6fc0cb69f6
from sympy.algebras.quaternion import Quaternion from sympy.assumptions.ask import Q from sympy.calculus.util 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 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 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_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]"
752571886a9d351ea06c5e34578276b46850f93e110ef4b21b2a47bd870f0d83
# -*- coding: utf-8 -*- from sympy.core.relational import Eq from sympy.core.symbol import Symbol from sympy.functions.elementary.piecewise import Piecewise from sympy.printing.preview import preview from io import BytesIO def test_preview(): x = Symbol('x') obj = BytesIO() try: preview(x, output='png', viewer='BytesIO', outputbuffer=obj) except RuntimeError: pass # latex not installed on CI server def test_preview_unicode_symbol(): # issue 9107 a = Symbol('α') obj = BytesIO() try: preview(a, output='png', viewer='BytesIO', outputbuffer=obj) except RuntimeError: pass # latex not installed on CI server def test_preview_latex_construct_in_expr(): # see PR 9801 x = Symbol('x') pw = Piecewise((1, Eq(x, 0)), (0, True)) obj = BytesIO() try: preview(pw, output='png', viewer='BytesIO', outputbuffer=obj) except RuntimeError: pass # latex not installed on CI server
4cc6b76f7d4e1d2c797be68deb95b45ef96f3fa26abc933f82a3c776420b7b31
from sympy.core.add import Add from sympy.core.function import (Function, Lambda, diff) from sympy.core.mod import Mod from sympy.core import (Catalan, EulerGamma, GoldenRatio) from sympy.core.numbers import (E, Float, I, Integer, Rational, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Dummy, symbols) from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (conjugate, sign) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (atan2, cos, sin) from sympy.functions.special.gamma_functions import gamma from sympy.integrals.integrals import Integral from sympy.sets.fancysets import Range from sympy.codegen import For, Assignment, aug_assign from sympy.codegen.ast import Declaration, Variable, float32, float64, \ value_const, real, bool_, While, FunctionPrototype, FunctionDefinition, \ integer, Return from sympy.core.expr import UnevaluatedExpr from sympy.core.relational import Relational from sympy.logic.boolalg import And, Or, Not, Equivalent, Xor from sympy.matrices import Matrix, MatrixSymbol from sympy.printing.fortran import fcode, FCodePrinter from sympy.tensor import IndexedBase, Idx from sympy.utilities.lambdify import implemented_function from sympy.testing.pytest import raises, warns_deprecated_sympy def test_UnevaluatedExpr(): p, q, r = symbols("p q r", real=True) q_r = UnevaluatedExpr(q + r) expr = abs(exp(p+q_r)) assert fcode(expr, source_format="free") == "exp(p + (q + r))" x, y, z = symbols("x y z") y_z = UnevaluatedExpr(y + z) expr2 = abs(exp(x+y_z)) assert fcode(expr2, human=False)[2].lstrip() == "exp(re(x) + re(y + z))" assert fcode(expr2, user_functions={"re": "realpart"}).lstrip() == "exp(realpart(x) + realpart(y + z))" def test_printmethod(): x = symbols('x') class nint(Function): def _fcode(self, printer): return "nint(%s)" % printer._print(self.args[0]) assert fcode(nint(x)) == " nint(x)" def test_fcode_sign(): #issue 12267 x=symbols('x') y=symbols('y', integer=True) z=symbols('z', complex=True) assert fcode(sign(x), standard=95, source_format='free') == "merge(0d0, dsign(1d0, x), x == 0d0)" assert fcode(sign(y), standard=95, source_format='free') == "merge(0, isign(1, y), y == 0)" assert fcode(sign(z), standard=95, source_format='free') == "merge(cmplx(0d0, 0d0), z/abs(z), abs(z) == 0d0)" raises(NotImplementedError, lambda: fcode(sign(x))) def test_fcode_Pow(): x, y = symbols('x,y') n = symbols('n', integer=True) assert fcode(x**3) == " x**3" assert fcode(x**(y**3)) == " x**(y**3)" assert fcode(1/(sin(x)*3.5)**(x - y**x)/(x**2 + y)) == \ " (3.5d0*sin(x))**(-x + y**x)/(x**2 + y)" assert fcode(sqrt(x)) == ' sqrt(x)' assert fcode(sqrt(n)) == ' sqrt(dble(n))' assert fcode(x**0.5) == ' sqrt(x)' assert fcode(sqrt(x)) == ' sqrt(x)' assert fcode(sqrt(10)) == ' sqrt(10.0d0)' assert fcode(x**-1.0) == ' 1d0/x' assert fcode(x**-2.0, 'y', source_format='free') == 'y = x**(-2.0d0)' # 2823 assert fcode(x**Rational(3, 7)) == ' x**(3.0d0/7.0d0)' def test_fcode_Rational(): x = symbols('x') assert fcode(Rational(3, 7)) == " 3.0d0/7.0d0" assert fcode(Rational(18, 9)) == " 2" assert fcode(Rational(3, -7)) == " -3.0d0/7.0d0" assert fcode(Rational(-3, -7)) == " 3.0d0/7.0d0" assert fcode(x + Rational(3, 7)) == " x + 3.0d0/7.0d0" assert fcode(Rational(3, 7)*x) == " (3.0d0/7.0d0)*x" def test_fcode_Integer(): assert fcode(Integer(67)) == " 67" assert fcode(Integer(-1)) == " -1" def test_fcode_Float(): assert fcode(Float(42.0)) == " 42.0000000000000d0" assert fcode(Float(-1e20)) == " -1.00000000000000d+20" def test_fcode_functions(): x, y = symbols('x,y') assert fcode(sin(x) ** cos(y)) == " sin(x)**cos(y)" raises(NotImplementedError, lambda: fcode(Mod(x, y), standard=66)) raises(NotImplementedError, lambda: fcode(x % y, standard=66)) raises(NotImplementedError, lambda: fcode(Mod(x, y), standard=77)) raises(NotImplementedError, lambda: fcode(x % y, standard=77)) for standard in [90, 95, 2003, 2008]: assert fcode(Mod(x, y), standard=standard) == " modulo(x, y)" assert fcode(x % y, standard=standard) == " modulo(x, y)" def test_case(): ob = FCodePrinter() x,x_,x__,y,X,X_,Y = symbols('x,x_,x__,y,X,X_,Y') assert fcode(exp(x_) + sin(x*y) + cos(X*Y)) == \ ' exp(x_) + sin(x*y) + cos(X__*Y_)' assert fcode(exp(x__) + 2*x*Y*X_**Rational(7, 2)) == \ ' 2*X_**(7.0d0/2.0d0)*Y*x + exp(x__)' assert fcode(exp(x_) + sin(x*y) + cos(X*Y), name_mangling=False) == \ ' exp(x_) + sin(x*y) + cos(X*Y)' assert fcode(x - cos(X), name_mangling=False) == ' x - cos(X)' assert ob.doprint(X*sin(x) + x_, assign_to='me') == ' me = X*sin(x_) + x__' assert ob.doprint(X*sin(x), assign_to='mu') == ' mu = X*sin(x_)' assert ob.doprint(x_, assign_to='ad') == ' ad = x__' n, m = symbols('n,m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) I = Idx('I', n) assert fcode(A[i, I]*x[I], assign_to=y[i], source_format='free') == ( "do i = 1, m\n" " y(i) = 0\n" "end do\n" "do i = 1, m\n" " do I_ = 1, n\n" " y(i) = A(i, I_)*x(I_) + y(i)\n" " end do\n" "end do" ) #issue 6814 def test_fcode_functions_with_integers(): x= symbols('x') log10_17 = log(10).evalf(17) loglog10_17 = '0.8340324452479558d0' assert fcode(x * log(10)) == " x*%sd0" % log10_17 assert fcode(x * log(10)) == " x*%sd0" % log10_17 assert fcode(x * log(S(10))) == " x*%sd0" % log10_17 assert fcode(log(S(10))) == " %sd0" % log10_17 assert fcode(exp(10)) == " %sd0" % exp(10).evalf(17) assert fcode(x * log(log(10))) == " x*%s" % loglog10_17 assert fcode(x * log(log(S(10)))) == " x*%s" % loglog10_17 def test_fcode_NumberSymbol(): prec = 17 p = FCodePrinter() assert fcode(Catalan) == ' parameter (Catalan = %sd0)\n Catalan' % Catalan.evalf(prec) assert fcode(EulerGamma) == ' parameter (EulerGamma = %sd0)\n EulerGamma' % EulerGamma.evalf(prec) assert fcode(E) == ' parameter (E = %sd0)\n E' % E.evalf(prec) assert fcode(GoldenRatio) == ' parameter (GoldenRatio = %sd0)\n GoldenRatio' % GoldenRatio.evalf(prec) assert fcode(pi) == ' parameter (pi = %sd0)\n pi' % pi.evalf(prec) assert fcode( pi, precision=5) == ' parameter (pi = %sd0)\n pi' % pi.evalf(5) assert fcode(Catalan, human=False) == ({ (Catalan, p._print(Catalan.evalf(prec)))}, set(), ' Catalan') assert fcode(EulerGamma, human=False) == ({(EulerGamma, p._print( EulerGamma.evalf(prec)))}, set(), ' EulerGamma') assert fcode(E, human=False) == ( {(E, p._print(E.evalf(prec)))}, set(), ' E') assert fcode(GoldenRatio, human=False) == ({(GoldenRatio, p._print( GoldenRatio.evalf(prec)))}, set(), ' GoldenRatio') assert fcode(pi, human=False) == ( {(pi, p._print(pi.evalf(prec)))}, set(), ' pi') assert fcode(pi, precision=5, human=False) == ( {(pi, p._print(pi.evalf(5)))}, set(), ' pi') def test_fcode_complex(): assert fcode(I) == " cmplx(0,1)" x = symbols('x') assert fcode(4*I) == " cmplx(0,4)" assert fcode(3 + 4*I) == " cmplx(3,4)" assert fcode(3 + 4*I + x) == " cmplx(3,4) + x" assert fcode(I*x) == " cmplx(0,1)*x" assert fcode(3 + 4*I - x) == " cmplx(3,4) - x" x = symbols('x', imaginary=True) assert fcode(5*x) == " 5*x" assert fcode(I*x) == " cmplx(0,1)*x" assert fcode(3 + x) == " x + 3" def test_implicit(): x, y = symbols('x,y') assert fcode(sin(x)) == " sin(x)" assert fcode(atan2(x, y)) == " atan2(x, y)" assert fcode(conjugate(x)) == " conjg(x)" def test_not_fortran(): x = symbols('x') g = Function('g') gamma_f = fcode(gamma(x)) assert gamma_f == "C Not supported in Fortran:\nC gamma\n gamma(x)" assert fcode(Integral(sin(x))) == "C Not supported in Fortran:\nC Integral\n Integral(sin(x), x)" assert fcode(g(x)) == "C Not supported in Fortran:\nC g\n g(x)" def test_user_functions(): x = symbols('x') assert fcode(sin(x), user_functions={"sin": "zsin"}) == " zsin(x)" x = symbols('x') assert fcode( gamma(x), user_functions={"gamma": "mygamma"}) == " mygamma(x)" g = Function('g') assert fcode(g(x), user_functions={"g": "great"}) == " great(x)" n = symbols('n', integer=True) assert fcode( factorial(n), user_functions={"factorial": "fct"}) == " fct(n)" def test_inline_function(): x = symbols('x') g = implemented_function('g', Lambda(x, 2*x)) assert fcode(g(x)) == " 2*x" g = implemented_function('g', Lambda(x, 2*pi/x)) assert fcode(g(x)) == ( " parameter (pi = %sd0)\n" " 2*pi/x" ) % pi.evalf(17) A = IndexedBase('A') i = Idx('i', symbols('n', integer=True)) g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) assert fcode(g(A[i]), assign_to=A[i]) == ( " do i = 1, n\n" " A(i) = (A(i) + 1)*(A(i) + 2)*A(i)\n" " end do" ) def test_assign_to(): x = symbols('x') assert fcode(sin(x), assign_to="s") == " s = sin(x)" def test_line_wrapping(): x, y = symbols('x,y') assert fcode(((x + y)**10).expand(), assign_to="var") == ( " var = x**10 + 10*x**9*y + 45*x**8*y**2 + 120*x**7*y**3 + 210*x**6*\n" " @ y**4 + 252*x**5*y**5 + 210*x**4*y**6 + 120*x**3*y**7 + 45*x**2*y\n" " @ **8 + 10*x*y**9 + y**10" ) e = [x**i for i in range(11)] assert fcode(Add(*e)) == ( " x**10 + x**9 + x**8 + x**7 + x**6 + x**5 + x**4 + x**3 + x**2 + x\n" " @ + 1" ) def test_fcode_precedence(): x, y = symbols("x y") assert fcode(And(x < y, y < x + 1), source_format="free") == \ "x < y .and. y < x + 1" assert fcode(Or(x < y, y < x + 1), source_format="free") == \ "x < y .or. y < x + 1" assert fcode(Xor(x < y, y < x + 1, evaluate=False), source_format="free") == "x < y .neqv. y < x + 1" assert fcode(Equivalent(x < y, y < x + 1), source_format="free") == \ "x < y .eqv. y < x + 1" def test_fcode_Logical(): x, y, z = symbols("x y z") # unary Not assert fcode(Not(x), source_format="free") == ".not. x" # binary And assert fcode(And(x, y), source_format="free") == "x .and. y" assert fcode(And(x, Not(y)), source_format="free") == "x .and. .not. y" assert fcode(And(Not(x), y), source_format="free") == "y .and. .not. x" assert fcode(And(Not(x), Not(y)), source_format="free") == \ ".not. x .and. .not. y" assert fcode(Not(And(x, y), evaluate=False), source_format="free") == \ ".not. (x .and. y)" # binary Or assert fcode(Or(x, y), source_format="free") == "x .or. y" assert fcode(Or(x, Not(y)), source_format="free") == "x .or. .not. y" assert fcode(Or(Not(x), y), source_format="free") == "y .or. .not. x" assert fcode(Or(Not(x), Not(y)), source_format="free") == \ ".not. x .or. .not. y" assert fcode(Not(Or(x, y), evaluate=False), source_format="free") == \ ".not. (x .or. y)" # mixed And/Or assert fcode(And(Or(y, z), x), source_format="free") == "x .and. (y .or. z)" assert fcode(And(Or(z, x), y), source_format="free") == "y .and. (x .or. z)" assert fcode(And(Or(x, y), z), source_format="free") == "z .and. (x .or. y)" assert fcode(Or(And(y, z), x), source_format="free") == "x .or. y .and. z" assert fcode(Or(And(z, x), y), source_format="free") == "y .or. x .and. z" assert fcode(Or(And(x, y), z), source_format="free") == "z .or. x .and. y" # trinary And assert fcode(And(x, y, z), source_format="free") == "x .and. y .and. z" assert fcode(And(x, y, Not(z)), source_format="free") == \ "x .and. y .and. .not. z" assert fcode(And(x, Not(y), z), source_format="free") == \ "x .and. z .and. .not. y" assert fcode(And(Not(x), y, z), source_format="free") == \ "y .and. z .and. .not. x" assert fcode(Not(And(x, y, z), evaluate=False), source_format="free") == \ ".not. (x .and. y .and. z)" # trinary Or assert fcode(Or(x, y, z), source_format="free") == "x .or. y .or. z" assert fcode(Or(x, y, Not(z)), source_format="free") == \ "x .or. y .or. .not. z" assert fcode(Or(x, Not(y), z), source_format="free") == \ "x .or. z .or. .not. y" assert fcode(Or(Not(x), y, z), source_format="free") == \ "y .or. z .or. .not. x" assert fcode(Not(Or(x, y, z), evaluate=False), source_format="free") == \ ".not. (x .or. y .or. z)" def test_fcode_Xlogical(): x, y, z = symbols("x y z") # binary Xor assert fcode(Xor(x, y, evaluate=False), source_format="free") == \ "x .neqv. y" assert fcode(Xor(x, Not(y), evaluate=False), source_format="free") == \ "x .neqv. .not. y" assert fcode(Xor(Not(x), y, evaluate=False), source_format="free") == \ "y .neqv. .not. x" assert fcode(Xor(Not(x), Not(y), evaluate=False), source_format="free") == ".not. x .neqv. .not. y" assert fcode(Not(Xor(x, y, evaluate=False), evaluate=False), source_format="free") == ".not. (x .neqv. y)" # binary Equivalent assert fcode(Equivalent(x, y), source_format="free") == "x .eqv. y" assert fcode(Equivalent(x, Not(y)), source_format="free") == \ "x .eqv. .not. y" assert fcode(Equivalent(Not(x), y), source_format="free") == \ "y .eqv. .not. x" assert fcode(Equivalent(Not(x), Not(y)), source_format="free") == \ ".not. x .eqv. .not. y" assert fcode(Not(Equivalent(x, y), evaluate=False), source_format="free") == ".not. (x .eqv. y)" # mixed And/Equivalent assert fcode(Equivalent(And(y, z), x), source_format="free") == \ "x .eqv. y .and. z" assert fcode(Equivalent(And(z, x), y), source_format="free") == \ "y .eqv. x .and. z" assert fcode(Equivalent(And(x, y), z), source_format="free") == \ "z .eqv. x .and. y" assert fcode(And(Equivalent(y, z), x), source_format="free") == \ "x .and. (y .eqv. z)" assert fcode(And(Equivalent(z, x), y), source_format="free") == \ "y .and. (x .eqv. z)" assert fcode(And(Equivalent(x, y), z), source_format="free") == \ "z .and. (x .eqv. y)" # mixed Or/Equivalent assert fcode(Equivalent(Or(y, z), x), source_format="free") == \ "x .eqv. y .or. z" assert fcode(Equivalent(Or(z, x), y), source_format="free") == \ "y .eqv. x .or. z" assert fcode(Equivalent(Or(x, y), z), source_format="free") == \ "z .eqv. x .or. y" assert fcode(Or(Equivalent(y, z), x), source_format="free") == \ "x .or. (y .eqv. z)" assert fcode(Or(Equivalent(z, x), y), source_format="free") == \ "y .or. (x .eqv. z)" assert fcode(Or(Equivalent(x, y), z), source_format="free") == \ "z .or. (x .eqv. y)" # mixed Xor/Equivalent assert fcode(Equivalent(Xor(y, z, evaluate=False), x), source_format="free") == "x .eqv. (y .neqv. z)" assert fcode(Equivalent(Xor(z, x, evaluate=False), y), source_format="free") == "y .eqv. (x .neqv. z)" assert fcode(Equivalent(Xor(x, y, evaluate=False), z), source_format="free") == "z .eqv. (x .neqv. y)" assert fcode(Xor(Equivalent(y, z), x, evaluate=False), source_format="free") == "x .neqv. (y .eqv. z)" assert fcode(Xor(Equivalent(z, x), y, evaluate=False), source_format="free") == "y .neqv. (x .eqv. z)" assert fcode(Xor(Equivalent(x, y), z, evaluate=False), source_format="free") == "z .neqv. (x .eqv. y)" # mixed And/Xor assert fcode(Xor(And(y, z), x, evaluate=False), source_format="free") == \ "x .neqv. y .and. z" assert fcode(Xor(And(z, x), y, evaluate=False), source_format="free") == \ "y .neqv. x .and. z" assert fcode(Xor(And(x, y), z, evaluate=False), source_format="free") == \ "z .neqv. x .and. y" assert fcode(And(Xor(y, z, evaluate=False), x), source_format="free") == \ "x .and. (y .neqv. z)" assert fcode(And(Xor(z, x, evaluate=False), y), source_format="free") == \ "y .and. (x .neqv. z)" assert fcode(And(Xor(x, y, evaluate=False), z), source_format="free") == \ "z .and. (x .neqv. y)" # mixed Or/Xor assert fcode(Xor(Or(y, z), x, evaluate=False), source_format="free") == \ "x .neqv. y .or. z" assert fcode(Xor(Or(z, x), y, evaluate=False), source_format="free") == \ "y .neqv. x .or. z" assert fcode(Xor(Or(x, y), z, evaluate=False), source_format="free") == \ "z .neqv. x .or. y" assert fcode(Or(Xor(y, z, evaluate=False), x), source_format="free") == \ "x .or. (y .neqv. z)" assert fcode(Or(Xor(z, x, evaluate=False), y), source_format="free") == \ "y .or. (x .neqv. z)" assert fcode(Or(Xor(x, y, evaluate=False), z), source_format="free") == \ "z .or. (x .neqv. y)" # trinary Xor assert fcode(Xor(x, y, z, evaluate=False), source_format="free") == \ "x .neqv. y .neqv. z" assert fcode(Xor(x, y, Not(z), evaluate=False), source_format="free") == \ "x .neqv. y .neqv. .not. z" assert fcode(Xor(x, Not(y), z, evaluate=False), source_format="free") == \ "x .neqv. z .neqv. .not. y" assert fcode(Xor(Not(x), y, z, evaluate=False), source_format="free") == \ "y .neqv. z .neqv. .not. x" def test_fcode_Relational(): x, y = symbols("x y") assert fcode(Relational(x, y, "=="), source_format="free") == "x == y" assert fcode(Relational(x, y, "!="), source_format="free") == "x /= y" assert fcode(Relational(x, y, ">="), source_format="free") == "x >= y" assert fcode(Relational(x, y, "<="), source_format="free") == "x <= y" assert fcode(Relational(x, y, ">"), source_format="free") == "x > y" assert fcode(Relational(x, y, "<"), source_format="free") == "x < y" def test_fcode_Piecewise(): x = symbols('x') expr = Piecewise((x, x < 1), (x**2, True)) # Check that inline conditional (merge) fails if standard isn't 95+ raises(NotImplementedError, lambda: fcode(expr)) code = fcode(expr, standard=95) expected = " merge(x, x**2, x < 1)" assert code == expected assert fcode(Piecewise((x, x < 1), (x**2, True)), assign_to="var") == ( " if (x < 1) then\n" " var = x\n" " else\n" " var = x**2\n" " end if" ) a = cos(x)/x b = sin(x)/x for i in range(10): a = diff(a, x) b = diff(b, x) expected = ( " if (x < 0) then\n" " weird_name = -cos(x)/x + 10*sin(x)/x**2 + 90*cos(x)/x**3 - 720*\n" " @ sin(x)/x**4 - 5040*cos(x)/x**5 + 30240*sin(x)/x**6 + 151200*cos(x\n" " @ )/x**7 - 604800*sin(x)/x**8 - 1814400*cos(x)/x**9 + 3628800*sin(x\n" " @ )/x**10 + 3628800*cos(x)/x**11\n" " else\n" " weird_name = -sin(x)/x - 10*cos(x)/x**2 + 90*sin(x)/x**3 + 720*\n" " @ cos(x)/x**4 - 5040*sin(x)/x**5 - 30240*cos(x)/x**6 + 151200*sin(x\n" " @ )/x**7 + 604800*cos(x)/x**8 - 1814400*sin(x)/x**9 - 3628800*cos(x\n" " @ )/x**10 + 3628800*sin(x)/x**11\n" " end if" ) code = fcode(Piecewise((a, x < 0), (b, True)), assign_to="weird_name") assert code == expected code = fcode(Piecewise((x, x < 1), (x**2, x > 1), (sin(x), True)), standard=95) expected = " merge(x, merge(x**2, sin(x), x > 1), x < 1)" assert code == expected # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: fcode(expr)) def test_wrap_fortran(): # "########################################################################" printer = FCodePrinter() lines = [ "C This is a long comment on a single line that must be wrapped properly to produce nice output", " this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement(that)/must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement(that)/must + be + wrapped + properly", ] wrapped_lines = printer._wrap_fortran(lines) expected_lines = [ "C This is a long comment on a single line that must be wrapped", "C properly to produce nice output", " this = is + a + long + and + nasty + fortran + statement + that *", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that *", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that", " @ * must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that", " @ *must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement +", " @ that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that", " @ **must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that", " @ **must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement +", " @ that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement(that)/", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement(that)", " @ /must + be + wrapped + properly", ] for line in wrapped_lines: assert len(line) <= 72 for w, e in zip(wrapped_lines, expected_lines): assert w == e assert len(wrapped_lines) == len(expected_lines) def test_wrap_fortran_keep_d0(): printer = FCodePrinter() lines = [ ' this_variable_is_very_long_because_we_try_to_test_line_break=1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break = 10.0d0' ] expected = [ ' this_variable_is_very_long_because_we_try_to_test_line_break=1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 10.0d0' ] assert printer._wrap_fortran(lines) == expected def test_settings(): raises(TypeError, lambda: fcode(S(4), method="garbage")) def test_free_form_code_line(): x, y = symbols('x,y') assert fcode(cos(x) + sin(y), source_format='free') == "sin(y) + cos(x)" def test_free_form_continuation_line(): x, y = symbols('x,y') result = fcode(((cos(x) + sin(y))**(7)).expand(), source_format='free') expected = ( 'sin(y)**7 + 7*sin(y)**6*cos(x) + 21*sin(y)**5*cos(x)**2 + 35*sin(y)**4* &\n' ' cos(x)**3 + 35*sin(y)**3*cos(x)**4 + 21*sin(y)**2*cos(x)**5 + 7* &\n' ' sin(y)*cos(x)**6 + cos(x)**7' ) assert result == expected def test_free_form_comment_line(): printer = FCodePrinter({'source_format': 'free'}) lines = [ "! This is a long comment on a single line that must be wrapped properly to produce nice output"] expected = [ '! This is a long comment on a single line that must be wrapped properly', '! to produce nice output'] assert printer._wrap_fortran(lines) == expected def test_loops(): n, m = symbols('n,m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) expected = ( 'do i = 1, m\n' ' y(i) = 0\n' 'end do\n' 'do i = 1, m\n' ' do j = 1, n\n' ' y(i) = %(rhs)s\n' ' end do\n' 'end do' ) code = fcode(A[i, j]*x[j], assign_to=y[i], source_format='free') assert (code == expected % {'rhs': 'y(i) + A(i, j)*x(j)'} or code == expected % {'rhs': 'y(i) + x(j)*A(i, j)'} or code == expected % {'rhs': 'x(j)*A(i, j) + y(i)'} or code == expected % {'rhs': 'A(i, j)*x(j) + y(i)'}) def test_dummy_loops(): i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( 'do i_%(icount)i = 1, m_%(mcount)i\n' ' y(i_%(icount)i) = x(i_%(icount)i)\n' 'end do' ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} code = fcode(x[i], assign_to=y[i], source_format='free') assert code == expected def test_fcode_Indexed_without_looking_for_contraction(): len_y = 5 y = IndexedBase('y', shape=(len_y,)) x = IndexedBase('x', shape=(len_y,)) Dy = IndexedBase('Dy', shape=(len_y-1,)) i = Idx('i', len_y-1) e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i])) code0 = fcode(e.rhs, assign_to=e.lhs, contract=False) assert code0.endswith('Dy(i) = (y(i + 1) - y(i))/(x(i + 1) - x(i))') def test_derived_classes(): class MyFancyFCodePrinter(FCodePrinter): _default_settings = FCodePrinter._default_settings.copy() printer = MyFancyFCodePrinter() x = symbols('x') assert printer.doprint(sin(x), "bork") == " bork = sin(x)" def test_indent(): codelines = ( 'subroutine test(a)\n' 'integer :: a, i, j\n' '\n' 'do\n' 'do \n' 'do j = 1, 5\n' 'if (a>b) then\n' 'if(b>0) then\n' 'a = 3\n' 'donot_indent_me = 2\n' 'do_not_indent_me_either = 2\n' 'ifIam_indented_something_went_wrong = 2\n' 'if_I_am_indented_something_went_wrong = 2\n' 'end should not be unindented here\n' 'end if\n' 'endif\n' 'end do\n' 'end do\n' 'enddo\n' 'end subroutine\n' '\n' 'subroutine test2(a)\n' 'integer :: a\n' 'do\n' 'a = a + 1\n' 'end do \n' 'end subroutine\n' ) expected = ( 'subroutine test(a)\n' 'integer :: a, i, j\n' '\n' 'do\n' ' do \n' ' do j = 1, 5\n' ' if (a>b) then\n' ' if(b>0) then\n' ' a = 3\n' ' donot_indent_me = 2\n' ' do_not_indent_me_either = 2\n' ' ifIam_indented_something_went_wrong = 2\n' ' if_I_am_indented_something_went_wrong = 2\n' ' end should not be unindented here\n' ' end if\n' ' endif\n' ' end do\n' ' end do\n' 'enddo\n' 'end subroutine\n' '\n' 'subroutine test2(a)\n' 'integer :: a\n' 'do\n' ' a = a + 1\n' 'end do \n' 'end subroutine\n' ) p = FCodePrinter({'source_format': 'free'}) result = p.indent_code(codelines) assert result == expected def test_Matrix_printing(): x, y, z = symbols('x,y,z') # Test returning a Matrix mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)]) A = MatrixSymbol('A', 3, 1) assert fcode(mat, A) == ( " A(1, 1) = x*y\n" " if (y > 0) then\n" " A(2, 1) = x + 2\n" " else\n" " A(2, 1) = y\n" " end if\n" " A(3, 1) = sin(z)") # Test using MatrixElements in expressions expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0] assert fcode(expr, standard=95) == ( " merge(2*A(3, 1), A(3, 1), x > 0) + sin(A(2, 1)) + A(1, 1)") # Test using MatrixElements in a Matrix q = MatrixSymbol('q', 5, 1) M = MatrixSymbol('M', 3, 3) m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])], [q[1,0] + q[2,0], q[3, 0], 5], [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]]) assert fcode(m, M) == ( " M(1, 1) = sin(q(2, 1))\n" " M(2, 1) = q(2, 1) + q(3, 1)\n" " M(3, 1) = 2*q(5, 1)/q(2, 1)\n" " M(1, 2) = 0\n" " M(2, 2) = q(4, 1)\n" " M(3, 2) = sqrt(q(1, 1)) + 4\n" " M(1, 3) = cos(q(3, 1))\n" " M(2, 3) = 5\n" " M(3, 3) = 0") def test_fcode_For(): x, y = symbols('x y') f = For(x, Range(0, 10, 2), [Assignment(y, x * y)]) sol = fcode(f) assert sol == (" do x = 0, 10, 2\n" " y = x*y\n" " end do") def test_fcode_Declaration(): def check(expr, ref, **kwargs): assert fcode(expr, standard=95, source_format='free', **kwargs) == ref i = symbols('i', integer=True) var1 = Variable.deduced(i) dcl1 = Declaration(var1) check(dcl1, "integer*4 :: i") x, y = symbols('x y') var2 = Variable(x, float32, value=42, attrs={value_const}) dcl2b = Declaration(var2) check(dcl2b, 'real*4, parameter :: x = 42') var3 = Variable(y, type=bool_) dcl3 = Declaration(var3) check(dcl3, 'logical :: y') check(float32, "real*4") check(float64, "real*8") check(real, "real*4", type_aliases={real: float32}) check(real, "real*8", type_aliases={real: float64}) def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(fcode(A[0, 0]) == " A(1, 1)") assert(fcode(3 * A[0, 0]) == " 3*A(1, 1)") F = C[0, 0].subs(C, A - B) assert(fcode(F) == " (A - B)(1, 1)") def test_aug_assign(): x = symbols('x') assert fcode(aug_assign(x, '+', 1), source_format='free') == 'x = x + 1' def test_While(): x = symbols('x') assert fcode(While(abs(x) > 1, [aug_assign(x, '-', 1)]), source_format='free') == ( 'do while (abs(x) > 1)\n' ' x = x - 1\n' 'end do' ) def test_FunctionPrototype_print(): x = symbols('x') n = symbols('n', integer=True) vx = Variable(x, type=real) vn = Variable(n, type=integer) fp1 = FunctionPrototype(real, 'power', [vx, vn]) # Should be changed to proper test once multi-line generation is working # see https://github.com/sympy/sympy/issues/15824 raises(NotImplementedError, lambda: fcode(fp1)) def test_FunctionDefinition_print(): x = symbols('x') n = symbols('n', integer=True) vx = Variable(x, type=real) vn = Variable(n, type=integer) body = [Assignment(x, x**n), Return(x)] fd1 = FunctionDefinition(real, 'power', [vx, vn], body) # Should be changed to proper test once multi-line generation is working # see https://github.com/sympy/sympy/issues/15824 raises(NotImplementedError, lambda: fcode(fd1)) def test_fcode_submodule(): # Test the compatibility sympy.printing.fcode module imports with warns_deprecated_sympy(): import sympy.printing.fcode # noqa:F401
0894d71839bcc2f8e4becb6402de01059774b0f202b9e51e58c60a93e33e7497
from sympy.core import ( S, pi, oo, symbols, Rational, Integer, Float, Mod, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, nan, Mul, Pow, UnevaluatedExpr ) from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne) from sympy.functions import ( Abs, acos, acosh, asin, asinh, atan, atanh, atan2, ceiling, cos, cosh, erf, erfc, exp, floor, gamma, log, loggamma, Max, Min, Piecewise, sign, sin, sinh, sqrt, tan, tanh, fibonacci, lucas ) from sympy.sets import Range from sympy.logic import ITE, Implies, Equivalent from sympy.codegen import For, aug_assign, Assignment from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy from sympy.printing.c import C89CodePrinter, C99CodePrinter, get_math_macros from sympy.codegen.ast import ( AddAugmentedAssignment, Element, Type, FloatType, Declaration, Pointer, Variable, value_const, pointer_const, While, Scope, Print, FunctionPrototype, FunctionDefinition, FunctionCall, Return, real, float32, float64, float80, float128, intc, Comment, CodeBlock ) from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, fma, log10, Cbrt, hypot, Sqrt from sympy.codegen.cnodes import restrict from sympy.utilities.lambdify import implemented_function from sympy.tensor import IndexedBase, Idx from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix from sympy.printing.codeprinter import ccode x, y, z = symbols('x,y,z') def test_printmethod(): class fabs(Abs): def _ccode(self, printer): return "fabs(%s)" % printer._print(self.args[0]) assert ccode(fabs(x)) == "fabs(x)" def test_ccode_sqrt(): assert ccode(sqrt(x)) == "sqrt(x)" assert ccode(x**0.5) == "sqrt(x)" assert ccode(sqrt(x)) == "sqrt(x)" def test_ccode_Pow(): assert ccode(x**3) == "pow(x, 3)" assert ccode(x**(y**3)) == "pow(x, pow(y, 3))" g = implemented_function('g', Lambda(x, 2*x)) assert ccode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2) + y)" assert ccode(x**-1.0) == '1.0/x' assert ccode(x**Rational(2, 3)) == 'pow(x, 2.0/3.0)' assert ccode(x**Rational(2, 3), type_aliases={real: float80}) == 'powl(x, 2.0L/3.0L)' _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"), (lambda base, exp: not exp.is_integer, "pow")] assert ccode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)' assert ccode(x**0.5, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 0.5)' assert ccode(x**Rational(16, 5), user_functions={'Pow': _cond_cfunc}) == 'pow(x, 16.0/5.0)' _cond_cfunc2 = [(lambda base, exp: base == 2, lambda base, exp: 'exp2(%s)' % exp), (lambda base, exp: base != 2, 'pow')] # Related to gh-11353 assert ccode(2**x, user_functions={'Pow': _cond_cfunc2}) == 'exp2(x)' assert ccode(x**2, user_functions={'Pow': _cond_cfunc2}) == 'pow(x, 2)' # For issue 14160 assert ccode(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), evaluate=False)) == '-2*x/(y*y)' def test_ccode_Max(): # Test for gh-11926 assert ccode(Max(x,x*x),user_functions={"Max":"my_max", "Pow":"my_pow"}) == 'my_max(x, my_pow(x, 2))' def test_ccode_Min_performance(): #Shouldn't take more than a few seconds big_min = Min(*symbols('a[0:50]')) for curr_standard in ('c89', 'c99', 'c11'): output = ccode(big_min, standard=curr_standard) assert output.count('(') == output.count(')') def test_ccode_constants_mathh(): assert ccode(exp(1)) == "M_E" assert ccode(pi) == "M_PI" assert ccode(oo, standard='c89') == "HUGE_VAL" assert ccode(-oo, standard='c89') == "-HUGE_VAL" assert ccode(oo) == "INFINITY" assert ccode(-oo, standard='c99') == "-INFINITY" assert ccode(pi, type_aliases={real: float80}) == "M_PIl" def test_ccode_constants_other(): assert ccode(2*GoldenRatio) == "const double GoldenRatio = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17) assert ccode( 2*Catalan) == "const double Catalan = %s;\n2*Catalan" % Catalan.evalf(17) assert ccode(2*EulerGamma) == "const double EulerGamma = %s;\n2*EulerGamma" % EulerGamma.evalf(17) def test_ccode_Rational(): assert ccode(Rational(3, 7)) == "3.0/7.0" assert ccode(Rational(3, 7), type_aliases={real: float80}) == "3.0L/7.0L" assert ccode(Rational(18, 9)) == "2" assert ccode(Rational(3, -7)) == "-3.0/7.0" assert ccode(Rational(3, -7), type_aliases={real: float80}) == "-3.0L/7.0L" assert ccode(Rational(-3, -7)) == "3.0/7.0" assert ccode(Rational(-3, -7), type_aliases={real: float80}) == "3.0L/7.0L" assert ccode(x + Rational(3, 7)) == "x + 3.0/7.0" assert ccode(x + Rational(3, 7), type_aliases={real: float80}) == "x + 3.0L/7.0L" assert ccode(Rational(3, 7)*x) == "(3.0/7.0)*x" assert ccode(Rational(3, 7)*x, type_aliases={real: float80}) == "(3.0L/7.0L)*x" def test_ccode_Integer(): assert ccode(Integer(67)) == "67" assert ccode(Integer(-1)) == "-1" def test_ccode_functions(): assert ccode(sin(x) ** cos(x)) == "pow(sin(x), cos(x))" def test_ccode_inline_function(): x = symbols('x') g = implemented_function('g', Lambda(x, 2*x)) assert ccode(g(x)) == "2*x" g = implemented_function('g', Lambda(x, 2*x/Catalan)) assert ccode( g(x)) == "const double Catalan = %s;\n2*x/Catalan" % Catalan.evalf(17) A = IndexedBase('A') i = Idx('i', symbols('n', integer=True)) g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) assert ccode(g(A[i]), assign_to=A[i]) == ( "for (int i=0; i<n; i++){\n" " A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n" "}" ) def test_ccode_exceptions(): assert ccode(gamma(x), standard='C99') == "tgamma(x)" gamma_c89 = ccode(gamma(x), standard='C89') assert 'not supported in c' in gamma_c89.lower() gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=False) assert 'not supported in c' in gamma_c89.lower() gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=True) assert not 'not supported in c' in gamma_c89.lower() def test_ccode_functions2(): assert ccode(ceiling(x)) == "ceil(x)" assert ccode(Abs(x)) == "fabs(x)" assert ccode(gamma(x)) == "tgamma(x)" r, s = symbols('r,s', real=True) assert ccode(Mod(ceiling(r), ceiling(s))) == '((ceil(r) % ceil(s)) + '\ 'ceil(s)) % ceil(s)' assert ccode(Mod(r, s)) == "fmod(r, s)" p1, p2 = symbols('p1 p2', integer=True, positive=True) assert ccode(Mod(p1, p2)) == 'p1 % p2' assert ccode(Mod(p1, p2 + 3)) == 'p1 % (p2 + 3)' assert ccode(Mod(-3, -7, evaluate=False)) == '(-3) % (-7)' assert ccode(-Mod(3, 7, evaluate=False)) == '-(3 % 7)' assert ccode(r*Mod(p1, p2)) == 'r*(p1 % p2)' assert ccode(Mod(p1, p2)**s) == 'pow(p1 % p2, s)' n = symbols('n', integer=True, negative=True) assert ccode(Mod(-n, p2)) == '(-n) % p2' assert ccode(fibonacci(n)) == '(1.0/5.0)*pow(2, -n)*sqrt(5)*(-pow(1 - sqrt(5), n) + pow(1 + sqrt(5), n))' assert ccode(lucas(n)) == 'pow(2, -n)*(pow(1 - sqrt(5), n) + pow(1 + sqrt(5), n))' def test_ccode_user_functions(): x = symbols('x', integer=False) n = symbols('n', integer=True) custom_functions = { "ceiling": "ceil", "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")], } assert ccode(ceiling(x), user_functions=custom_functions) == "ceil(x)" assert ccode(Abs(x), user_functions=custom_functions) == "fabs(x)" assert ccode(Abs(n), user_functions=custom_functions) == "abs(n)" def test_ccode_boolean(): assert ccode(True) == "true" assert ccode(S.true) == "true" assert ccode(False) == "false" assert ccode(S.false) == "false" assert ccode(x & y) == "x && y" assert ccode(x | y) == "x || y" assert ccode(~x) == "!x" assert ccode(x & y & z) == "x && y && z" assert ccode(x | y | z) == "x || y || z" assert ccode((x & y) | z) == "z || x && y" assert ccode((x | y) & z) == "z && (x || y)" # Automatic rewrites assert ccode(x ^ y) == '(x || y) && (!x || !y)' assert ccode((x ^ y) ^ z) == '(x || y || z) && (x || !y || !z) && (y || !x || !z) && (z || !x || !y)' assert ccode(Implies(x, y)) == 'y || !x' assert ccode(Equivalent(x, z ^ y, Implies(z, x))) == '(x || (y || !z) && (z || !y)) && (z && !x || (y || z) && (!y || !z))' def test_ccode_Relational(): assert ccode(Eq(x, y)) == "x == y" assert ccode(Ne(x, y)) == "x != y" assert ccode(Le(x, y)) == "x <= y" assert ccode(Lt(x, y)) == "x < y" assert ccode(Gt(x, y)) == "x > y" assert ccode(Ge(x, y)) == "x >= y" def test_ccode_Piecewise(): expr = Piecewise((x, x < 1), (x**2, True)) assert ccode(expr) == ( "((x < 1) ? (\n" " x\n" ")\n" ": (\n" " pow(x, 2)\n" "))") assert ccode(expr, assign_to="c") == ( "if (x < 1) {\n" " c = x;\n" "}\n" "else {\n" " c = pow(x, 2);\n" "}") expr = Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True)) assert ccode(expr) == ( "((x < 1) ? (\n" " x\n" ")\n" ": ((x < 2) ? (\n" " x + 1\n" ")\n" ": (\n" " pow(x, 2)\n" ")))") assert ccode(expr, assign_to='c') == ( "if (x < 1) {\n" " c = x;\n" "}\n" "else if (x < 2) {\n" " c = x + 1;\n" "}\n" "else {\n" " c = pow(x, 2);\n" "}") # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: ccode(expr)) def test_ccode_sinc(): from sympy.functions.elementary.trigonometric import sinc expr = sinc(x) assert ccode(expr) == ( "((x != 0) ? (\n" " sin(x)/x\n" ")\n" ": (\n" " 1\n" "))") def test_ccode_Piecewise_deep(): p = ccode(2*Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True))) assert p == ( "2*((x < 1) ? (\n" " x\n" ")\n" ": ((x < 2) ? (\n" " x + 1\n" ")\n" ": (\n" " pow(x, 2)\n" ")))") expr = x*y*z + x**2 + y**2 + Piecewise((0, x < 0.5), (1, True)) + cos(z) - 1 assert ccode(expr) == ( "pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n" " 0\n" ")\n" ": (\n" " 1\n" ")) + cos(z) - 1") assert ccode(expr, assign_to='c') == ( "c = pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n" " 0\n" ")\n" ": (\n" " 1\n" ")) + cos(z) - 1;") def test_ccode_ITE(): expr = ITE(x < 1, y, z) assert ccode(expr) == ( "((x < 1) ? (\n" " y\n" ")\n" ": (\n" " z\n" "))") def test_ccode_settings(): raises(TypeError, lambda: ccode(sin(x), method="garbage")) def test_ccode_Indexed(): s, n, m, o = symbols('s n m o', integer=True) i, j, k = Idx('i', n), Idx('j', m), Idx('k', o) x = IndexedBase('x')[j] A = IndexedBase('A')[i, j] B = IndexedBase('B')[i, j, k] p = C99CodePrinter() assert p._print_Indexed(x) == 'x[j]' assert p._print_Indexed(A) == 'A[%s]' % (m*i+j) assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k) A = IndexedBase('A', shape=(5,3))[i, j] assert p._print_Indexed(A) == 'A[%s]' % (3*i + j) A = IndexedBase('A', shape=(5,3), strides='F')[i, j] assert ccode(A) == 'A[%s]' % (i + 5*j) A = IndexedBase('A', shape=(29,29), strides=(1, s), offset=o)[i, j] assert ccode(A) == 'A[o + s*j + i]' Abase = IndexedBase('A', strides=(s, m, n), offset=o) assert ccode(Abase[i, j, k]) == 'A[m*j + n*k + o + s*i]' assert ccode(Abase[2, 3, k]) == 'A[3*m + n*k + o + 2*s]' def test_Element(): assert ccode(Element('x', 'ij')) == 'x[i][j]' assert ccode(Element('x', 'ij', strides='kl', offset='o')) == 'x[i*k + j*l + o]' assert ccode(Element('x', (3,))) == 'x[3]' assert ccode(Element('x', (3,4,5))) == 'x[3][4][5]' def test_ccode_Indexed_without_looking_for_contraction(): len_y = 5 y = IndexedBase('y', shape=(len_y,)) x = IndexedBase('x', shape=(len_y,)) Dy = IndexedBase('Dy', shape=(len_y-1,)) i = Idx('i', len_y-1) e = Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i])) code0 = ccode(e.rhs, assign_to=e.lhs, contract=False) assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1) def test_ccode_loops_matrix_vector(): n, m = symbols('n m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = A[%s]*x[j] + y[i];\n' % (i*n + j) +\ ' }\n' '}' ) assert ccode(A[i, j]*x[j], assign_to=y[i]) == s def test_dummy_loops(): i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( 'for (int i_%(icount)i=0; i_%(icount)i<m_%(mcount)i; i_%(icount)i++){\n' ' y[i_%(icount)i] = x[i_%(icount)i];\n' '}' ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} assert ccode(x[i], assign_to=y[i]) == expected def test_ccode_loops_add(): n, m = symbols('n m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') z = IndexedBase('z') i = Idx('i', m) j = Idx('j', n) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = x[i] + z[i];\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = A[%s]*x[j] + y[i];\n' % (i*n + j) +\ ' }\n' '}' ) assert ccode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) == s def test_ccode_loops_multiple_contractions(): n, m, o, p = symbols('n m o p', integer=True) a = IndexedBase('a') b = IndexedBase('b') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) l = Idx('l', p) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' for (int k=0; k<o; k++){\n' ' for (int l=0; l<p; l++){\n' ' y[i] = a[%s]*b[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\ ' }\n' ' }\n' ' }\n' '}' ) assert ccode(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) == s def test_ccode_loops_addfactor(): n, m, o, p = symbols('n m o p', integer=True) a = IndexedBase('a') b = IndexedBase('b') c = IndexedBase('c') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) l = Idx('l', p) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' for (int k=0; k<o; k++){\n' ' for (int l=0; l<p; l++){\n' ' y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\ ' }\n' ' }\n' ' }\n' '}' ) assert ccode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i]) == s def test_ccode_loops_multiple_terms(): n, m, o, p = symbols('n m o p', integer=True) a = IndexedBase('a') b = IndexedBase('b') c = IndexedBase('c') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) s0 = ( 'for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' ) s1 = ( 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' for (int k=0; k<o; k++){\n' ' y[i] = b[j]*b[k]*c[%s] + y[i];\n' % (i*n*o + j*o + k) +\ ' }\n' ' }\n' '}\n' ) s2 = ( 'for (int i=0; i<m; i++){\n' ' for (int k=0; k<o; k++){\n' ' y[i] = a[%s]*b[k] + y[i];\n' % (i*o + k) +\ ' }\n' '}\n' ) s3 = ( 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = a[%s]*b[j] + y[i];\n' % (i*n + j) +\ ' }\n' '}\n' ) c = ccode(b[j]*a[i, j] + b[k]*a[i, k] + b[j]*b[k]*c[i, j, k], assign_to=y[i]) assert (c == s0 + s1 + s2 + s3[:-1] or c == s0 + s1 + s3 + s2[:-1] or c == s0 + s2 + s1 + s3[:-1] or c == s0 + s2 + s3 + s1[:-1] or c == s0 + s3 + s1 + s2[:-1] or c == s0 + s3 + s2 + s1[:-1]) def test_dereference_printing(): expr = x + y + sin(z) + z assert ccode(expr, dereference=[z]) == "x + y + (*z) + sin((*z))" def test_Matrix_printing(): # Test returning a Matrix mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)]) A = MatrixSymbol('A', 3, 1) assert ccode(mat, A) == ( "A[0] = x*y;\n" "if (y > 0) {\n" " A[1] = x + 2;\n" "}\n" "else {\n" " A[1] = y;\n" "}\n" "A[2] = sin(z);") # Test using MatrixElements in expressions expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0] assert ccode(expr) == ( "((x > 0) ? (\n" " 2*A[2]\n" ")\n" ": (\n" " A[2]\n" ")) + sin(A[1]) + A[0]") # Test using MatrixElements in a Matrix q = MatrixSymbol('q', 5, 1) M = MatrixSymbol('M', 3, 3) m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])], [q[1,0] + q[2,0], q[3, 0], 5], [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]]) assert ccode(m, M) == ( "M[0] = sin(q[1]);\n" "M[1] = 0;\n" "M[2] = cos(q[2]);\n" "M[3] = q[1] + q[2];\n" "M[4] = q[3];\n" "M[5] = 5;\n" "M[6] = 2*q[4]/q[1];\n" "M[7] = sqrt(q[0]) + 4;\n" "M[8] = 0;") def test_sparse_matrix(): # gh-15791 assert 'Not supported in C' in ccode(SparseMatrix([[1, 2, 3]])) def test_ccode_reserved_words(): x, y = symbols('x, if') with raises(ValueError): ccode(y**2, error_on_reserved=True, standard='C99') assert ccode(y**2) == 'pow(if_, 2)' assert ccode(x * y**2, dereference=[y]) == 'pow((*if_), 2)*x' assert ccode(y**2, reserved_word_suffix='_unreserved') == 'pow(if_unreserved, 2)' def test_ccode_sign(): expr1, ref1 = sign(x) * y, 'y*(((x) > 0) - ((x) < 0))' expr2, ref2 = sign(cos(x)), '(((cos(x)) > 0) - ((cos(x)) < 0))' expr3, ref3 = sign(2 * x + x**2) * x + x**2, 'pow(x, 2) + x*(((pow(x, 2) + 2*x) > 0) - ((pow(x, 2) + 2*x) < 0))' assert ccode(expr1) == ref1 assert ccode(expr1, 'z') == 'z = %s;' % ref1 assert ccode(expr2) == ref2 assert ccode(expr3) == ref3 def test_ccode_Assignment(): assert ccode(Assignment(x, y + z)) == 'x = y + z;' assert ccode(aug_assign(x, '+', y + z)) == 'x += y + z;' def test_ccode_For(): f = For(x, Range(0, 10, 2), [aug_assign(y, '*', x)]) assert ccode(f) == ("for (x = 0; x < 10; x += 2) {\n" " y *= x;\n" "}") def test_ccode_Max_Min(): assert ccode(Max(x, 0), standard='C89') == '((0 > x) ? 0 : x)' assert ccode(Max(x, 0), standard='C99') == 'fmax(0, x)' assert ccode(Min(x, 0, sqrt(x)), standard='c89') == ( '((0 < ((x < sqrt(x)) ? x : sqrt(x))) ? 0 : ((x < sqrt(x)) ? x : sqrt(x)))' ) def test_ccode_standard(): assert ccode(expm1(x), standard='c99') == 'expm1(x)' assert ccode(nan, standard='c99') == 'NAN' assert ccode(float('nan'), standard='c99') == 'NAN' def test_C89CodePrinter(): c89printer = C89CodePrinter() assert c89printer.language == 'C' assert c89printer.standard == 'C89' assert 'void' in c89printer.reserved_words assert 'template' not in c89printer.reserved_words def test_C99CodePrinter(): assert C99CodePrinter().doprint(expm1(x)) == 'expm1(x)' assert C99CodePrinter().doprint(log1p(x)) == 'log1p(x)' assert C99CodePrinter().doprint(exp2(x)) == 'exp2(x)' assert C99CodePrinter().doprint(log2(x)) == 'log2(x)' assert C99CodePrinter().doprint(fma(x, y, -z)) == 'fma(x, y, -z)' assert C99CodePrinter().doprint(log10(x)) == 'log10(x)' assert C99CodePrinter().doprint(Cbrt(x)) == 'cbrt(x)' # note Cbrt due to cbrt already taken. assert C99CodePrinter().doprint(hypot(x, y)) == 'hypot(x, y)' assert C99CodePrinter().doprint(loggamma(x)) == 'lgamma(x)' assert C99CodePrinter().doprint(Max(x, 3, x**2)) == 'fmax(3, fmax(x, pow(x, 2)))' assert C99CodePrinter().doprint(Min(x, 3)) == 'fmin(3, x)' c99printer = C99CodePrinter() assert c99printer.language == 'C' assert c99printer.standard == 'C99' assert 'restrict' in c99printer.reserved_words assert 'using' not in c99printer.reserved_words @XFAIL def test_C99CodePrinter__precision_f80(): f80_printer = C99CodePrinter(dict(type_aliases={real: float80})) assert f80_printer.doprint(sin(x+Float('2.1'))) == 'sinl(x + 2.1L)' def test_C99CodePrinter__precision(): n = symbols('n', integer=True) p = symbols('p', integer=True, positive=True) f32_printer = C99CodePrinter(dict(type_aliases={real: float32})) f64_printer = C99CodePrinter(dict(type_aliases={real: float64})) f80_printer = C99CodePrinter(dict(type_aliases={real: float80})) assert f32_printer.doprint(sin(x+2.1)) == 'sinf(x + 2.1F)' assert f64_printer.doprint(sin(x+2.1)) == 'sin(x + 2.1000000000000001)' assert f80_printer.doprint(sin(x+Float('2.0'))) == 'sinl(x + 2.0L)' for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ['f', '', 'l']): def check(expr, ref): assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper()) check(Abs(n), 'abs(n)') check(Abs(x + 2.0), 'fabs{s}(x + 2.0{S})') check(sin(x + 4.0)**cos(x - 2.0), 'pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))') check(exp(x*8.0), 'exp{s}(8.0{S}*x)') check(exp2(x), 'exp2{s}(x)') check(expm1(x*4.0), 'expm1{s}(4.0{S}*x)') check(Mod(p, 2), 'p % 2') check(Mod(2*p + 3, 3*p + 5, evaluate=False), '(2*p + 3) % (3*p + 5)') check(Mod(x + 2.0, 3.0), 'fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})') check(Mod(x, 2.0*x + 3.0), 'fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})') check(log(x/2), 'log{s}((1.0{S}/2.0{S})*x)') check(log10(3*x/2), 'log10{s}((3.0{S}/2.0{S})*x)') check(log2(x*8.0), 'log2{s}(8.0{S}*x)') check(log1p(x), 'log1p{s}(x)') check(2**x, 'pow{s}(2, x)') check(2.0**x, 'pow{s}(2.0{S}, x)') check(x**3, 'pow{s}(x, 3)') check(x**4.0, 'pow{s}(x, 4.0{S})') check(sqrt(3+x), 'sqrt{s}(x + 3)') check(Cbrt(x-2.0), 'cbrt{s}(x - 2.0{S})') check(hypot(x, y), 'hypot{s}(x, y)') check(sin(3.*x + 2.), 'sin{s}(3.0{S}*x + 2.0{S})') check(cos(3.*x - 1.), 'cos{s}(3.0{S}*x - 1.0{S})') check(tan(4.*y + 2.), 'tan{s}(4.0{S}*y + 2.0{S})') check(asin(3.*x + 2.), 'asin{s}(3.0{S}*x + 2.0{S})') check(acos(3.*x + 2.), 'acos{s}(3.0{S}*x + 2.0{S})') check(atan(3.*x + 2.), 'atan{s}(3.0{S}*x + 2.0{S})') check(atan2(3.*x, 2.*y), 'atan2{s}(3.0{S}*x, 2.0{S}*y)') check(sinh(3.*x + 2.), 'sinh{s}(3.0{S}*x + 2.0{S})') check(cosh(3.*x - 1.), 'cosh{s}(3.0{S}*x - 1.0{S})') check(tanh(4.0*y + 2.), 'tanh{s}(4.0{S}*y + 2.0{S})') check(asinh(3.*x + 2.), 'asinh{s}(3.0{S}*x + 2.0{S})') check(acosh(3.*x + 2.), 'acosh{s}(3.0{S}*x + 2.0{S})') check(atanh(3.*x + 2.), 'atanh{s}(3.0{S}*x + 2.0{S})') check(erf(42.*x), 'erf{s}(42.0{S}*x)') check(erfc(42.*x), 'erfc{s}(42.0{S}*x)') check(gamma(x), 'tgamma{s}(x)') check(loggamma(x), 'lgamma{s}(x)') check(ceiling(x + 2.), "ceil{s}(x + 2.0{S})") check(floor(x + 2.), "floor{s}(x + 2.0{S})") check(fma(x, y, -z), 'fma{s}(x, y, -z)') check(Max(x, 8.0, x**4.0), 'fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))') check(Min(x, 2.0), 'fmin{s}(2.0{S}, x)') def test_get_math_macros(): macros = get_math_macros() assert macros[exp(1)] == 'M_E' assert macros[1/Sqrt(2)] == 'M_SQRT1_2' def test_ccode_Declaration(): i = symbols('i', integer=True) var1 = Variable(i, type=Type.from_expr(i)) dcl1 = Declaration(var1) assert ccode(dcl1) == 'int i' var2 = Variable(x, type=float32, attrs={value_const}) dcl2a = Declaration(var2) assert ccode(dcl2a) == 'const float x' dcl2b = var2.as_Declaration(value=pi) assert ccode(dcl2b) == 'const float x = M_PI' var3 = Variable(y, type=Type('bool')) dcl3 = Declaration(var3) printer = C89CodePrinter() assert 'stdbool.h' not in printer.headers assert printer.doprint(dcl3) == 'bool y' assert 'stdbool.h' in printer.headers u = symbols('u', real=True) ptr4 = Pointer.deduced(u, attrs={pointer_const, restrict}) dcl4 = Declaration(ptr4) assert ccode(dcl4) == 'double * const restrict u' var5 = Variable(x, Type('__float128'), attrs={value_const}) dcl5a = Declaration(var5) assert ccode(dcl5a) == 'const __float128 x' var5b = Variable(var5.symbol, var5.type, pi, attrs=var5.attrs) dcl5b = Declaration(var5b) assert ccode(dcl5b) == 'const __float128 x = M_PI' def test_C99CodePrinter_custom_type(): # We will look at __float128 (new in glibc 2.26) f128 = FloatType('_Float128', float128.nbits, float128.nmant, float128.nexp) p128 = C99CodePrinter(dict( type_aliases={real: f128}, type_literal_suffixes={f128: 'Q'}, type_func_suffixes={f128: 'f128'}, type_math_macro_suffixes={ real: 'f128', f128: 'f128' }, type_macros={ f128: ('__STDC_WANT_IEC_60559_TYPES_EXT__',) } )) assert p128.doprint(x) == 'x' assert not p128.headers assert not p128.libraries assert not p128.macros assert p128.doprint(2.0) == '2.0Q' assert not p128.headers assert not p128.libraries assert p128.macros == {'__STDC_WANT_IEC_60559_TYPES_EXT__'} assert p128.doprint(Rational(1, 2)) == '1.0Q/2.0Q' assert p128.doprint(sin(x)) == 'sinf128(x)' assert p128.doprint(cos(2., evaluate=False)) == 'cosf128(2.0Q)' assert p128.doprint(x**-1.0) == '1.0Q/x' var5 = Variable(x, f128, attrs={value_const}) dcl5a = Declaration(var5) assert ccode(dcl5a) == 'const _Float128 x' var5b = Variable(x, f128, pi, attrs={value_const}) dcl5b = Declaration(var5b) assert p128.doprint(dcl5b) == 'const _Float128 x = M_PIf128' var5b = Variable(x, f128, value=Catalan.evalf(38), attrs={value_const}) dcl5c = Declaration(var5b) assert p128.doprint(dcl5c) == 'const _Float128 x = %sQ' % Catalan.evalf(f128.decimal_dig) def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(ccode(A[0, 0]) == "A[0]") assert(ccode(3 * A[0, 0]) == "3*A[0]") F = C[0, 0].subs(C, A - B) assert(ccode(F) == "(A - B)[0]") def test_ccode_math_macros(): assert ccode(z + exp(1)) == 'z + M_E' assert ccode(z + log2(exp(1))) == 'z + M_LOG2E' assert ccode(z + 1/log(2)) == 'z + M_LOG2E' assert ccode(z + log(2)) == 'z + M_LN2' assert ccode(z + log(10)) == 'z + M_LN10' assert ccode(z + pi) == 'z + M_PI' assert ccode(z + pi/2) == 'z + M_PI_2' assert ccode(z + pi/4) == 'z + M_PI_4' assert ccode(z + 1/pi) == 'z + M_1_PI' assert ccode(z + 2/pi) == 'z + M_2_PI' assert ccode(z + 2/sqrt(pi)) == 'z + M_2_SQRTPI' assert ccode(z + 2/Sqrt(pi)) == 'z + M_2_SQRTPI' assert ccode(z + sqrt(2)) == 'z + M_SQRT2' assert ccode(z + Sqrt(2)) == 'z + M_SQRT2' assert ccode(z + 1/sqrt(2)) == 'z + M_SQRT1_2' assert ccode(z + 1/Sqrt(2)) == 'z + M_SQRT1_2' def test_ccode_Type(): assert ccode(Type('float')) == 'float' assert ccode(intc) == 'int' def test_ccode_codegen_ast(): assert ccode(Comment("this is a comment")) == "// this is a comment" assert ccode(While(abs(x) > 1, [aug_assign(x, '-', 1)])) == ( 'while (fabs(x) > 1) {\n' ' x -= 1;\n' '}' ) assert ccode(Scope([AddAugmentedAssignment(x, 1)])) == ( '{\n' ' x += 1;\n' '}' ) inp_x = Declaration(Variable(x, type=real)) assert ccode(FunctionPrototype(real, 'pwer', [inp_x])) == 'double pwer(double x)' assert ccode(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)])) == ( 'double pwer(double x){\n' ' x = pow(x, 2);\n' '}' ) # Elements of CodeBlock are formatted as statements: block = CodeBlock( x, Print([x, y], "%d %d"), FunctionCall('pwer', [x]), Return(x), ) assert ccode(block) == '\n'.join([ 'x;', 'printf("%d %d", x, y);', 'pwer(x);', 'return x;', ]) def test_ccode_submodule(): # Test the compatibility sympy.printing.ccode module imports with warns_deprecated_sympy(): import sympy.printing.ccode # noqa:F401 def test_ccode_UnevaluatedExpr(): assert ccode(UnevaluatedExpr(y * x) + z) == "z + x*y" assert ccode(UnevaluatedExpr(y + x) + z) == "z + (x + y)" # gh-21955 w = symbols('w') assert ccode(UnevaluatedExpr(y + x) + UnevaluatedExpr(z + w)) == "(w + z) + (x + y)" p, q, r = symbols("p q r", real=True) q_r = UnevaluatedExpr(q + r) expr = abs(exp(p+q_r)) assert ccode(expr) == "exp(p + (q + r))" def test_ccode_array_like_containers(): assert ccode([2,3,4]) == "{2, 3, 4}" assert ccode((2,3,4)) == "{2, 3, 4}"
667391e691b91adde4ddc5fb0ed3795d4830c6d81e72d3e75b55b9df008ae65a
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' : 'python2'}) assert prntr._print_Pow(sqrt(x), rational=False) == 'sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1./2.)' prntr = LambdaPrinter({'standard' : 'python3'}) assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' def test_settings(): raises(TypeError, lambda: lambdarepr(sin(x), method="garbage")) 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) == \ "evaluate('where((x > 0), True, False)', truediv=True)" class CustomPrintedObject(Expr): def _lambdacode(self, printer): return 'lambda' def _tensorflowcode(self, printer): return 'tensorflow' def _numpycode(self, printer): return 'numpy' def _numexprcode(self, printer): return 'numexpr' def _mpmathcode(self, printer): return 'mpmath' def test_printmethod(): # In each case, printmethod is called to test # its working obj = CustomPrintedObject() assert LambdaPrinter().doprint(obj) == 'lambda' assert TensorflowPrinter().doprint(obj) == 'tensorflow' assert NumExprPrinter().doprint(obj) == "evaluate('numexpr', truediv=True)" assert NumExprPrinter().doprint(Piecewise((y, x >= 0), (z, x < 0))) == \ "evaluate('where((x >= 0), y, z)', truediv=True)"
caa3e953717459c6f12263c10401dddd8119a641467dcabf4cb2b858dfe0b4fe
# -*- coding: utf-8 -*- from sympy.core.function import (Derivative, Function) from sympy.core.numbers import oo from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.trigonometric import cos from sympy.integrals.integrals import Integral from sympy.functions.special.bessel import besselj from sympy.functions.special.polynomials import legendre from sympy.functions.combinatorial.numbers import bell from sympy.printing.conventions import split_super_sub, requires_partial from sympy.testing.pytest import XFAIL def test_super_sub(): assert split_super_sub("beta_13_2") == ("beta", [], ["13", "2"]) assert split_super_sub("beta_132_20") == ("beta", [], ["132", "20"]) assert split_super_sub("beta_13") == ("beta", [], ["13"]) assert split_super_sub("x_a_b") == ("x", [], ["a", "b"]) assert split_super_sub("x_1_2_3") == ("x", [], ["1", "2", "3"]) assert split_super_sub("x_a_b1") == ("x", [], ["a", "b1"]) assert split_super_sub("x_a_1") == ("x", [], ["a", "1"]) assert split_super_sub("x_1_a") == ("x", [], ["1", "a"]) assert split_super_sub("x_1^aa") == ("x", ["aa"], ["1"]) assert split_super_sub("x_1__aa") == ("x", ["aa"], ["1"]) assert split_super_sub("x_11^a") == ("x", ["a"], ["11"]) assert split_super_sub("x_11__a") == ("x", ["a"], ["11"]) assert split_super_sub("x_a_b_c_d") == ("x", [], ["a", "b", "c", "d"]) assert split_super_sub("x_a_b^c^d") == ("x", ["c", "d"], ["a", "b"]) assert split_super_sub("x_a_b__c__d") == ("x", ["c", "d"], ["a", "b"]) assert split_super_sub("x_a^b_c^d") == ("x", ["b", "d"], ["a", "c"]) assert split_super_sub("x_a__b_c__d") == ("x", ["b", "d"], ["a", "c"]) assert split_super_sub("x^a^b_c_d") == ("x", ["a", "b"], ["c", "d"]) assert split_super_sub("x__a__b_c_d") == ("x", ["a", "b"], ["c", "d"]) assert split_super_sub("x^a^b^c^d") == ("x", ["a", "b", "c", "d"], []) assert split_super_sub("x__a__b__c__d") == ("x", ["a", "b", "c", "d"], []) assert split_super_sub("alpha_11") == ("alpha", [], ["11"]) assert split_super_sub("alpha_11_11") == ("alpha", [], ["11", "11"]) assert split_super_sub("w1") == ("w", [], ["1"]) assert split_super_sub("w𝟙") == ("w", [], ["𝟙"]) assert split_super_sub("w11") == ("w", [], ["11"]) assert split_super_sub("w𝟙𝟙") == ("w", [], ["𝟙𝟙"]) assert split_super_sub("w𝟙2𝟙") == ("w", [], ["𝟙2𝟙"]) assert split_super_sub("w1^a") == ("w", ["a"], ["1"]) assert split_super_sub("ω1") == ("ω", [], ["1"]) assert split_super_sub("ω11") == ("ω", [], ["11"]) assert split_super_sub("ω1^a") == ("ω", ["a"], ["1"]) assert split_super_sub("ω𝟙^α") == ("ω", ["α"], ["𝟙"]) assert split_super_sub("ω𝟙2^3α") == ("ω", ["3α"], ["𝟙2"]) assert split_super_sub("") == ("", [], []) def test_requires_partial(): x, y, z, t, nu = symbols('x y z t nu') n = symbols('n', integer=True) f = x * y assert requires_partial(Derivative(f, x)) is True assert requires_partial(Derivative(f, y)) is True ## integrating out one of the variables assert requires_partial(Derivative(Integral(exp(-x * y), (x, 0, oo)), y, evaluate=False)) is False ## bessel function with smooth parameter f = besselj(nu, x) assert requires_partial(Derivative(f, x)) is True assert requires_partial(Derivative(f, nu)) is True ## bessel function with integer parameter f = besselj(n, x) assert requires_partial(Derivative(f, x)) is False # this is not really valid (differentiating with respect to an integer) # but there's no reason to use the partial derivative symbol there. make # sure we don't throw an exception here, though assert requires_partial(Derivative(f, n)) is False ## bell polynomial f = bell(n, x) assert requires_partial(Derivative(f, x)) is False # again, invalid assert requires_partial(Derivative(f, n)) is False ## legendre polynomial f = legendre(0, x) assert requires_partial(Derivative(f, x)) is False f = legendre(n, x) assert requires_partial(Derivative(f, x)) is False # again, invalid assert requires_partial(Derivative(f, n)) is False f = x ** n assert requires_partial(Derivative(f, x)) is False assert requires_partial(Derivative(Integral((x*y) ** n * exp(-x * y), (x, 0, oo)), y, evaluate=False)) is False # parametric equation f = (exp(t), cos(t)) g = sum(f) assert requires_partial(Derivative(g, t)) is False f = symbols('f', cls=Function) assert requires_partial(Derivative(f(x), x)) is False assert requires_partial(Derivative(f(x), y)) is False assert requires_partial(Derivative(f(x, y), x)) is True assert requires_partial(Derivative(f(x, y), y)) is True assert requires_partial(Derivative(f(x, y), z)) is True assert requires_partial(Derivative(f(x, y), x, y)) is True @XFAIL def test_requires_partial_unspecified_variables(): x, y = symbols('x y') # function of unspecified variables f = symbols('f', cls=Function) assert requires_partial(Derivative(f, x)) is False assert requires_partial(Derivative(f, x, y)) is True
fa13b9d8cd5125241ed2a4954a5e81d4bb9d64881a04c99ed0d91de9d406afa8
from sympy.concrete.summations import Sum from sympy.functions.elementary.exponential import log from sympy.functions.elementary.miscellaneous import sqrt from sympy.utilities.lambdify import lambdify from sympy.abc import x, i, a, b from sympy.codegen.numpy_nodes import logaddexp from sympy.printing.numpy import CuPyPrinter, _cupy_known_constants, _cupy_known_functions from sympy.testing.pytest import skip from sympy.external import import_module cp = import_module('cupy') def test_cupy_print(): prntr = CuPyPrinter() assert prntr.doprint(logaddexp(a, b)) == 'cupy.logaddexp(a, b)' assert prntr.doprint(sqrt(x)) == 'cupy.sqrt(x)' assert prntr.doprint(log(x)) == 'cupy.log(x)' assert prntr.doprint("acos(x)") == 'cupy.arccos(x)' assert prntr.doprint("exp(x)") == 'cupy.exp(x)' assert prntr.doprint("Abs(x)") == 'abs(x)' def test_not_cupy_print(): prntr = CuPyPrinter() assert "Not supported" in prntr.doprint("abcd(x)") def test_cupy_sum(): if not cp: skip("CuPy not installed") s = Sum(x ** i, (i, a, b)) f = lambdify((a, b, x), s, 'cupy') a_, b_ = 0, 10 x_ = cp.linspace(-1, +1, 10) assert cp.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_ = cp.linspace(-1, +1, 10) assert cp.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1))) def test_cupy_known_funcs_consts(): assert _cupy_known_constants['NaN'] == 'cupy.nan' assert _cupy_known_constants['EulerGamma'] == 'cupy.euler_gamma' assert _cupy_known_functions['acos'] == 'cupy.arccos' assert _cupy_known_functions['log'] == 'cupy.log' def test_cupy_print_methods(): prntr = CuPyPrinter() assert hasattr(prntr, '_print_acos') assert hasattr(prntr, '_print_log')
1a7042669036b1742806d74a3e0140335a7bcf1c21d07382e8261d18fcdf012e
from sympy.algebras.quaternion import Quaternion from sympy.calculus.util 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 (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, 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.sets import (FiniteSet, Interval, Union, Intersection, Complement, SymmetricDifference, ProductSet) from sympy.sets.setexpr import SetExpr 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 (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 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(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)" def test_latex_Float(): assert latex(Float(1.0e100)) == r"1.0 \cdot 10^{100}" assert latex(Float(1.0e-100)) == r"1.0 \cdot 10^{-100}" assert latex(Float(1.0e-100), mul_symbol="times") == \ r"1.0 \times 10^{-100}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=2) == \ r"1.0 \cdot 10^{4}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=4) == \ r"1.0 \cdot 10^{4}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=5) == \ r"10000.0" assert latex(Float('0.099999'), full_prec=True, min=-2, max=5) == \ r"9.99990000000000 \cdot 10^{-2}" def test_latex_vector_expressions(): A = CoordSys3D('A') assert latex(Cross(A.i, A.j*A.x*3+A.k)) == \ r"\mathbf{\hat{i}_{A}} \times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)" assert latex(Cross(A.i, A.j)) == \ r"\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}" assert latex(x*Cross(A.i, A.j)) == \ r"x \left(\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}\right)" assert latex(Cross(x*A.i, A.j)) == \ r'- \mathbf{\hat{j}_{A}} \times \left((x)\mathbf{\hat{i}_{A}}\right)' assert latex(Curl(3*A.x*A.j)) == \ r"\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Curl(3*A.x*A.j+A.i)) == \ r"\nabla\times \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Curl(3*x*A.x*A.j)) == \ r"\nabla\times \left((3 \mathbf{{x}_{A}} x)\mathbf{\hat{j}_{A}}\right)" assert latex(x*Curl(3*A.x*A.j)) == \ r"x \left(\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)" assert latex(Divergence(3*A.x*A.j+A.i)) == \ r"\nabla\cdot \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Divergence(3*A.x*A.j)) == \ r"\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(x*Divergence(3*A.x*A.j)) == \ r"x \left(\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)" assert latex(Dot(A.i, A.j*A.x*3+A.k)) == \ r"\mathbf{\hat{i}_{A}} \cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)" assert latex(Dot(A.i, A.j)) == \ r"\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}" assert latex(Dot(x*A.i, A.j)) == \ r"\mathbf{\hat{j}_{A}} \cdot \left((x)\mathbf{\hat{i}_{A}}\right)" assert latex(x*Dot(A.i, A.j)) == \ r"x \left(\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}\right)" assert latex(Gradient(A.x)) == r"\nabla \mathbf{{x}_{A}}" assert latex(Gradient(A.x + 3*A.y)) == \ r"\nabla \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)" assert latex(x*Gradient(A.x)) == r"x \left(\nabla \mathbf{{x}_{A}}\right)" assert latex(Gradient(x*A.x)) == r"\nabla \left(\mathbf{{x}_{A}} x\right)" assert latex(Laplacian(A.x)) == r"\triangle \mathbf{{x}_{A}}" assert latex(Laplacian(A.x + 3*A.y)) == \ r"\triangle \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)" assert latex(x*Laplacian(A.x)) == r"x \left(\triangle \mathbf{{x}_{A}}\right)" assert latex(Laplacian(x*A.x)) == r"\triangle \left(\mathbf{{x}_{A}} x\right)" def test_latex_symbols(): Gamma, lmbda, rho = symbols('Gamma, lambda, rho') tau, Tau, TAU, taU = symbols('tau, Tau, TAU, taU') assert latex(tau) == r"\tau" assert latex(Tau) == 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{arcsinh}{\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' assert latex(Indexed('x1', Symbol('i'))) == r'{x_{1}}_{i}' 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)}' 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" 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_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_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\}\text{ in }\left\{1, 2\right\}' def test_PrettyPoly(): from sympy.polys.domains import QQ F = QQ.frac_field(x, y) R = QQ[x, y] assert latex(F.convert(x/(x + y))) == latex(x/(x + y)) assert latex(R.convert(x + y)) == latex(x + y) def test_integral_transforms(): x = Symbol("x") k = Symbol("k") f = Function("f") a = Symbol("a") b = Symbol("b") assert latex(MellinTransform(f(x), x, k)) == \ r"\mathcal{M}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseMellinTransform(f(k), k, x, a, b)) == \ r"\mathcal{M}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(LaplaceTransform(f(x), x, k)) == \ r"\mathcal{L}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseLaplaceTransform(f(k), k, x, (a, b))) == \ r"\mathcal{L}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(FourierTransform(f(x), x, k)) == \ r"\mathcal{F}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseFourierTransform(f(k), k, x)) == \ r"\mathcal{F}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(CosineTransform(f(x), x, k)) == \ r"\mathcal{COS}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseCosineTransform(f(k), k, x)) == \ r"\mathcal{COS}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(SineTransform(f(x), x, k)) == \ r"\mathcal{SIN}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseSineTransform(f(k), k, x)) == \ r"\mathcal{SIN}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" def test_PolynomialRingBase(): from sympy.polys.domains import QQ assert latex(QQ.old_poly_ring(x, y)) == r"\mathbb{Q}\left[x, y\right]" assert latex(QQ.old_poly_ring(x, y, order="ilex")) == \ r"S_<^{-1}\mathbb{Q}\left[x, y\right]" def test_categories(): from sympy.categories import (Object, IdentityMorphism, NamedMorphism, Category, Diagram, DiagramGrid) A1 = Object("A1") A2 = Object("A2") A3 = Object("A3") f1 = NamedMorphism(A1, A2, "f1") f2 = NamedMorphism(A2, A3, "f2") id_A1 = IdentityMorphism(A1) K1 = Category("K1") assert latex(A1) == 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}' def test_Transpose(): from sympy.matrices import Transpose, MatPow, HadamardPower X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(Transpose(X)) == r'X^{T}' assert latex(Transpose(X + Y)) == r'\left(X + Y\right)^{T}' assert latex(Transpose(HadamardPower(X, 2))) == r'\left(X^{\circ {2}}\right)^{T}' assert latex(HadamardPower(Transpose(X), 2)) == r'\left(X^{T}\right)^{\circ {2}}' assert latex(Transpose(MatPow(X, 2))) == r'\left(X^{2}\right)^{T}' assert latex(MatPow(Transpose(X), 2)) == r'\left(X^{T}\right)^{2}' def test_Hadamard(): from sympy.matrices import HadamardProduct, HadamardPower from sympy.matrices.expressions import MatAdd, MatMul, MatPow X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(HadamardProduct(X, Y*Y)) == r'X \circ Y^{2}' assert latex(HadamardProduct(X, Y)*Y) == r'\left(X \circ Y\right) Y' assert latex(HadamardPower(X, 2)) == r'X^{\circ {2}}' assert latex(HadamardPower(X, -1)) == r'X^{\circ \left({-1}\right)}' assert latex(HadamardPower(MatAdd(X, Y), 2)) == \ r'\left(X + Y\right)^{\circ {2}}' assert latex(HadamardPower(MatMul(X, Y), 2)) == \ r'\left(X Y\right)^{\circ {2}}' assert latex(HadamardPower(MatPow(X, -1), -1)) == \ r'\left(X^{-1}\right)^{\circ \left({-1}\right)}' assert latex(MatPow(HadamardPower(X, -1), -1)) == \ r'\left(X^{\circ \left({-1}\right)}\right)^{-1}' assert latex(HadamardPower(X, n+1)) == \ r'X^{\circ \left({n + 1}\right)}' def test_ElementwiseApplyFunction(): 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_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_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'UnimplementedExpr\left(x\right)' assert latex(unimplemented_expr(x**2)) == \ r'UnimplementedExpr\left(x^{2}\right)' assert latex(unimplemented_expr_sup_sub(x)) == \ r'UnimplementedExpr^{1}_{x}\left(x\right)' def test_MatrixSymbol_bold(): # Issue #15871 from sympy.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_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}}"
7994d8277ccde4b12df2d9792a10038351f072ba1f85242cc1a80fff3731a0cc
from sympy.core import (S, pi, oo, symbols, Rational, Integer, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, Eq, Ne, Le, Lt, Gt, Ge, Mod) from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt, sign, floor) from sympy.logic import ITE from sympy.testing.pytest import raises from sympy.utilities.lambdify import implemented_function from sympy.tensor import IndexedBase, Idx from sympy.matrices import MatrixSymbol, SparseMatrix, Matrix from sympy.printing.rust import rust_code x, y, z = symbols('x,y,z') def test_Integer(): assert rust_code(Integer(42)) == "42" assert rust_code(Integer(-56)) == "-56" def test_Relational(): assert rust_code(Eq(x, y)) == "x == y" assert rust_code(Ne(x, y)) == "x != y" assert rust_code(Le(x, y)) == "x <= y" assert rust_code(Lt(x, y)) == "x < y" assert rust_code(Gt(x, y)) == "x > y" assert rust_code(Ge(x, y)) == "x >= y" def test_Rational(): assert rust_code(Rational(3, 7)) == "3_f64/7.0" assert rust_code(Rational(18, 9)) == "2" assert rust_code(Rational(3, -7)) == "-3_f64/7.0" assert rust_code(Rational(-3, -7)) == "3_f64/7.0" assert rust_code(x + Rational(3, 7)) == "x + 3_f64/7.0" assert rust_code(Rational(3, 7)*x) == "(3_f64/7.0)*x" def test_basic_ops(): assert rust_code(x + y) == "x + y" assert rust_code(x - y) == "x - y" assert rust_code(x * y) == "x*y" assert rust_code(x / y) == "x/y" assert rust_code(-x) == "-x" def test_printmethod(): class fabs(Abs): def _rust_code(self, printer): return "%s.fabs()" % printer._print(self.args[0]) assert rust_code(fabs(x)) == "x.fabs()" a = MatrixSymbol("a", 1, 3) assert rust_code(a[0,0]) == 'a[0]' def test_Functions(): assert rust_code(sin(x) ** cos(x)) == "x.sin().powf(x.cos())" assert rust_code(abs(x)) == "x.abs()" assert rust_code(ceiling(x)) == "x.ceil()" assert rust_code(floor(x)) == "x.floor()" # Automatic rewrite assert rust_code(Mod(x, 3)) == 'x - 3*((1_f64/3.0)*x).floor()' def test_Pow(): assert rust_code(1/x) == "x.recip()" assert rust_code(x**-1) == rust_code(x**-1.0) == "x.recip()" assert rust_code(sqrt(x)) == "x.sqrt()" assert rust_code(x**S.Half) == rust_code(x**0.5) == "x.sqrt()" assert rust_code(1/sqrt(x)) == "x.sqrt().recip()" assert rust_code(x**-S.Half) == rust_code(x**-0.5) == "x.sqrt().recip()" assert rust_code(1/pi) == "PI.recip()" assert rust_code(pi**-1) == rust_code(pi**-1.0) == "PI.recip()" assert rust_code(pi**-0.5) == "PI.sqrt().recip()" assert rust_code(x**Rational(1, 3)) == "x.cbrt()" assert rust_code(2**x) == "x.exp2()" assert rust_code(exp(x)) == "x.exp()" assert rust_code(x**3) == "x.powi(3)" assert rust_code(x**(y**3)) == "x.powf(y.powi(3))" assert rust_code(x**Rational(2, 3)) == "x.powf(2_f64/3.0)" g = implemented_function('g', Lambda(x, 2*x)) assert rust_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ "(3.5*2*x).powf(-x + y.powf(x))/(x.powi(2) + y)" _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi", 1), (lambda base, exp: not exp.is_integer, "pow", 1)] assert rust_code(x**3, user_functions={'Pow': _cond_cfunc}) == 'x.dpowi(3)' assert rust_code(x**3.2, user_functions={'Pow': _cond_cfunc}) == 'x.pow(3.2)' def test_constants(): assert rust_code(pi) == "PI" assert rust_code(oo) == "INFINITY" assert rust_code(S.Infinity) == "INFINITY" assert rust_code(-oo) == "NEG_INFINITY" assert rust_code(S.NegativeInfinity) == "NEG_INFINITY" assert rust_code(S.NaN) == "NAN" assert rust_code(exp(1)) == "E" assert rust_code(S.Exp1) == "E" def test_constants_other(): assert rust_code(2*GoldenRatio) == "const GoldenRatio: f64 = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17) assert rust_code( 2*Catalan) == "const Catalan: f64 = %s;\n2*Catalan" % Catalan.evalf(17) assert rust_code(2*EulerGamma) == "const EulerGamma: f64 = %s;\n2*EulerGamma" % EulerGamma.evalf(17) def test_boolean(): assert rust_code(True) == "true" assert rust_code(S.true) == "true" assert rust_code(False) == "false" assert rust_code(S.false) == "false" assert rust_code(x & y) == "x && y" assert rust_code(x | y) == "x || y" assert rust_code(~x) == "!x" assert rust_code(x & y & z) == "x && y && z" assert rust_code(x | y | z) == "x || y || z" assert rust_code((x & y) | z) == "z || x && y" assert rust_code((x | y) & z) == "z && (x || y)" def test_Piecewise(): expr = Piecewise((x, x < 1), (x + 2, True)) assert rust_code(expr) == ( "if (x < 1) {\n" " x\n" "} else {\n" " x + 2\n" "}") assert rust_code(expr, assign_to="r") == ( "r = if (x < 1) {\n" " x\n" "} else {\n" " x + 2\n" "};") assert rust_code(expr, assign_to="r", inline=True) == ( "r = if (x < 1) { x } else { x + 2 };") expr = Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True)) assert rust_code(expr, inline=True) == ( "if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 }") assert rust_code(expr, assign_to="r", inline=True) == ( "r = if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 };") assert rust_code(expr, assign_to="r") == ( "r = if (x < 1) {\n" " x\n" "} else if (x < 5) {\n" " x + 1\n" "} else {\n" " x + 2\n" "};") expr = 2*Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True)) assert rust_code(expr, inline=True) == ( "2*if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 }") expr = 2*Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True)) - 42 assert rust_code(expr, inline=True) == ( "2*if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 } - 42") # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: rust_code(expr)) def test_dereference_printing(): expr = x + y + sin(z) + z assert rust_code(expr, dereference=[z]) == "x + y + (*z) + (*z).sin()" def test_sign(): expr = sign(x) * y assert rust_code(expr) == "y*x.signum()" assert rust_code(expr, assign_to='r') == "r = y*x.signum();" expr = sign(x + y) + 42 assert rust_code(expr) == "(x + y).signum() + 42" assert rust_code(expr, assign_to='r') == "r = (x + y).signum() + 42;" expr = sign(cos(x)) assert rust_code(expr) == "x.cos().signum()" def test_reserved_words(): x, y = symbols("x if") expr = sin(y) assert rust_code(expr) == "if_.sin()" assert rust_code(expr, dereference=[y]) == "(*if_).sin()" assert rust_code(expr, reserved_word_suffix='_unreserved') == "if_unreserved.sin()" with raises(ValueError): rust_code(expr, error_on_reserved=True) def test_ITE(): expr = ITE(x < 1, y, z) assert rust_code(expr) == ( "if (x < 1) {\n" " y\n" "} else {\n" " z\n" "}") def test_Indexed(): n, m, o = symbols('n m o', integer=True) i, j, k = Idx('i', n), Idx('j', m), Idx('k', o) x = IndexedBase('x')[j] assert rust_code(x) == "x[j]" A = IndexedBase('A')[i, j] assert rust_code(A) == "A[m*i + j]" B = IndexedBase('B')[i, j, k] assert rust_code(B) == "B[m*o*i + o*j + k]" def test_dummy_loops(): i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) assert rust_code(x[i], assign_to=y[i]) == ( "for i in 0..m {\n" " y[i] = x[i];\n" "}") def test_loops(): m, n = symbols('m n', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') z = IndexedBase('z') i = Idx('i', m) j = Idx('j', n) assert rust_code(A[i, j]*x[j], assign_to=y[i]) == ( "for i in 0..m {\n" " y[i] = 0;\n" "}\n" "for i in 0..m {\n" " for j in 0..n {\n" " y[i] = A[n*i + j]*x[j] + y[i];\n" " }\n" "}") assert rust_code(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) == ( "for i in 0..m {\n" " y[i] = x[i] + z[i];\n" "}\n" "for i in 0..m {\n" " for j in 0..n {\n" " y[i] = A[n*i + j]*x[j] + y[i];\n" " }\n" "}") def test_loops_multiple_contractions(): n, m, o, p = symbols('n m o p', integer=True) a = IndexedBase('a') b = IndexedBase('b') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) l = Idx('l', p) assert rust_code(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) == ( "for i in 0..m {\n" " y[i] = 0;\n" "}\n" "for i in 0..m {\n" " for j in 0..n {\n" " for k in 0..o {\n" " for l in 0..p {\n" " y[i] = a[%s]*b[%s] + y[i];\n" % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\ " }\n" " }\n" " }\n" "}") def test_loops_addfactor(): m, n, o, p = symbols('m n o p', integer=True) a = IndexedBase('a') b = IndexedBase('b') c = IndexedBase('c') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) l = Idx('l', p) code = rust_code((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i]) assert code == ( "for i in 0..m {\n" " y[i] = 0;\n" "}\n" "for i in 0..m {\n" " for j in 0..n {\n" " for k in 0..o {\n" " for l in 0..p {\n" " y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n" % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\ " }\n" " }\n" " }\n" "}") def test_settings(): raises(TypeError, lambda: rust_code(sin(x), method="garbage")) def test_inline_function(): x = symbols('x') g = implemented_function('g', Lambda(x, 2*x)) assert rust_code(g(x)) == "2*x" g = implemented_function('g', Lambda(x, 2*x/Catalan)) assert rust_code(g(x)) == ( "const Catalan: f64 = %s;\n2*x/Catalan" % Catalan.evalf(17)) A = IndexedBase('A') i = Idx('i', symbols('n', integer=True)) g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) assert rust_code(g(A[i]), assign_to=A[i]) == ( "for i in 0..n {\n" " A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n" "}") def test_user_functions(): x = symbols('x', integer=False) n = symbols('n', integer=True) custom_functions = { "ceiling": "ceil", "Abs": [(lambda x: not x.is_integer, "fabs", 4), (lambda x: x.is_integer, "abs", 4)], } assert rust_code(ceiling(x), user_functions=custom_functions) == "x.ceil()" assert rust_code(Abs(x), user_functions=custom_functions) == "fabs(x)" assert rust_code(Abs(n), user_functions=custom_functions) == "abs(n)" def test_matrix(): assert rust_code(Matrix([1, 2, 3])) == '[1, 2, 3]' with raises(ValueError): rust_code(Matrix([[1, 2, 3]])) def test_sparse_matrix(): # gh-15791 assert 'Not supported in Rust' in rust_code(SparseMatrix([[1, 2, 3]]))