hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
d1d246eae87d877764fea2ba1de86c27e579c846281c079324245cf6b06b3a9b | from typing import Tuple as tTuple, Union as tUnion
from sympy.core.add import Add
from sympy.core.cache import cacheit
from sympy.core.expr import Expr
from sympy.core.function import Function, ArgumentIndexError, PoleError, expand_mul
from sympy.core.logic import fuzzy_not, fuzzy_or, FuzzyBool, fuzzy_and
from sympy.core.mod import Mod
from sympy.core.numbers import Rational, pi, Integer, Float, equal_valued
from sympy.core.relational import Ne, Eq
from sympy.core.singleton import S
from sympy.core.symbol import Symbol, Dummy
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import factorial, RisingFactorial
from sympy.functions.combinatorial.numbers import bernoulli, euler
from sympy.functions.elementary.complexes import arg as arg_f, im, re
from sympy.functions.elementary.exponential import log, exp
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt, Min, Max
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary._trigonometric_special import (
cos_table, ipartfrac, fermat_coords)
from sympy.logic.boolalg import And
from sympy.ntheory import factorint
from sympy.polys.specialpolys import symmetric_poly
from sympy.utilities.iterables import numbered_symbols
###############################################################################
########################## UTILITIES ##########################################
###############################################################################
def _imaginary_unit_as_coefficient(arg):
""" Helper to extract symbolic coefficient for imaginary unit """
if isinstance(arg, Float):
return None
else:
return arg.as_coefficient(S.ImaginaryUnit)
###############################################################################
########################## TRIGONOMETRIC FUNCTIONS ############################
###############################################################################
class TrigonometricFunction(Function):
"""Base class for trigonometric functions. """
unbranched = True
_singularities = (S.ComplexInfinity,)
def _eval_is_rational(self):
s = self.func(*self.args)
if s.func == self.func:
if s.args[0].is_rational and fuzzy_not(s.args[0].is_zero):
return False
else:
return s.is_rational
def _eval_is_algebraic(self):
s = self.func(*self.args)
if s.func == self.func:
if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic:
return False
pi_coeff = _pi_coeff(self.args[0])
if pi_coeff is not None and pi_coeff.is_rational:
return True
else:
return s.is_algebraic
def _eval_expand_complex(self, deep=True, **hints):
re_part, im_part = self.as_real_imag(deep=deep, **hints)
return re_part + im_part*S.ImaginaryUnit
def _as_real_imag(self, deep=True, **hints):
if self.args[0].is_extended_real:
if deep:
hints['complex'] = False
return (self.args[0].expand(deep, **hints), S.Zero)
else:
return (self.args[0], S.Zero)
if deep:
re, im = self.args[0].expand(deep, **hints).as_real_imag()
else:
re, im = self.args[0].as_real_imag()
return (re, im)
def _period(self, general_period, symbol=None):
f = expand_mul(self.args[0])
if symbol is None:
symbol = tuple(f.free_symbols)[0]
if not f.has(symbol):
return S.Zero
if f == symbol:
return general_period
if symbol in f.free_symbols:
if f.is_Mul:
g, h = f.as_independent(symbol)
if h == symbol:
return general_period/abs(g)
if f.is_Add:
a, h = f.as_independent(symbol)
g, h = h.as_independent(symbol, as_Add=False)
if h == symbol:
return general_period/abs(g)
raise NotImplementedError("Use the periodicity function instead.")
@cacheit
def _table2():
# If nested sqrt's are worse than un-evaluation
# you can require q to be in (1, 2, 3, 4, 6, 12)
# q <= 12, q=15, q=20, q=24, q=30, q=40, q=60, q=120 return
# expressions with 2 or fewer sqrt nestings.
return {
12: (3, 4),
20: (4, 5),
30: (5, 6),
15: (6, 10),
24: (6, 8),
40: (8, 10),
60: (20, 30),
120: (40, 60)
}
def _peeloff_pi(arg):
r"""
Split ARG into two parts, a "rest" and a multiple of $\pi$.
This assumes ARG to be an Add.
The multiple of $\pi$ returned in the second position is always a Rational.
Examples
========
>>> from sympy.functions.elementary.trigonometric import _peeloff_pi
>>> from sympy import pi
>>> from sympy.abc import x, y
>>> _peeloff_pi(x + pi/2)
(x, 1/2)
>>> _peeloff_pi(x + 2*pi/3 + pi*y)
(x + pi*y + pi/6, 1/2)
"""
pi_coeff = S.Zero
rest_terms = []
for a in Add.make_args(arg):
K = a.coeff(pi)
if K and K.is_rational:
pi_coeff += K
else:
rest_terms.append(a)
if pi_coeff is S.Zero:
return arg, S.Zero
m1 = (pi_coeff % S.Half)
m2 = pi_coeff - m1
if m2.is_integer or ((2*m2).is_integer and m2.is_even is False):
return Add(*(rest_terms + [m1*pi])), m2
return arg, S.Zero
def _pi_coeff(arg: Expr, cycles: int = 1) -> tUnion[Expr, None]:
r"""
When arg is a Number times $\pi$ (e.g. $3\pi/2$) then return the Number
normalized to be in the range $[0, 2]$, else `None`.
When an even multiple of $\pi$ is encountered, if it is multiplying
something with known parity then the multiple is returned as 0 otherwise
as 2.
Examples
========
>>> from sympy.functions.elementary.trigonometric import _pi_coeff
>>> from sympy import pi, Dummy
>>> from sympy.abc import x
>>> _pi_coeff(3*x*pi)
3*x
>>> _pi_coeff(11*pi/7)
11/7
>>> _pi_coeff(-11*pi/7)
3/7
>>> _pi_coeff(4*pi)
0
>>> _pi_coeff(5*pi)
1
>>> _pi_coeff(5.0*pi)
1
>>> _pi_coeff(5.5*pi)
3/2
>>> _pi_coeff(2 + pi)
>>> _pi_coeff(2*Dummy(integer=True)*pi)
2
>>> _pi_coeff(2*Dummy(even=True)*pi)
0
"""
if arg is pi:
return S.One
elif not arg:
return S.Zero
elif arg.is_Mul:
cx = arg.coeff(pi)
if cx:
c, x = cx.as_coeff_Mul() # pi is not included as coeff
if c.is_Float:
# recast exact binary fractions to Rationals
f = abs(c) % 1
if f != 0:
p = -int(round(log(f, 2).evalf()))
m = 2**p
cm = c*m
i = int(cm)
if equal_valued(i, cm):
c = Rational(i, m)
cx = c*x
else:
c = Rational(int(c))
cx = c*x
if x.is_integer:
c2 = c % 2
if c2 == 1:
return x
elif not c2:
if x.is_even is not None: # known parity
return S.Zero
return Integer(2)
else:
return c2*x
return cx
elif arg.is_zero:
return S.Zero
return None
class sin(TrigonometricFunction):
r"""
The sine function.
Returns the sine of x (measured in radians).
Explanation
===========
This function will evaluate automatically in the
case $x/\pi$ is some rational number [4]_. For example,
if $x$ is a multiple of $\pi$, $\pi/2$, $\pi/3$, $\pi/4$, and $\pi/6$.
Examples
========
>>> from sympy import sin, pi
>>> from sympy.abc import x
>>> sin(x**2).diff(x)
2*x*cos(x**2)
>>> sin(1).diff(x)
0
>>> sin(pi)
0
>>> sin(pi/2)
1
>>> sin(pi/6)
1/2
>>> sin(pi/12)
-sqrt(2)/4 + sqrt(6)/4
See Also
========
csc, cos, sec, tan, cot
asin, acsc, acos, asec, atan, acot, atan2
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigonometric_functions
.. [2] http://dlmf.nist.gov/4.14
.. [3] http://functions.wolfram.com/ElementaryFunctions/Sin
.. [4] http://mathworld.wolfram.com/TrigonometryAngles.html
"""
def period(self, symbol=None):
return self._period(2*pi, symbol)
def fdiff(self, argindex=1):
if argindex == 1:
return cos(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.sets.setexpr import SetExpr
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg.is_zero:
return S.Zero
elif arg in (S.Infinity, S.NegativeInfinity):
return AccumBounds(-1, 1)
if arg is S.ComplexInfinity:
return S.NaN
if isinstance(arg, AccumBounds):
from sympy.sets.sets import FiniteSet
min, max = arg.min, arg.max
d = floor(min/(2*pi))
if min is not S.NegativeInfinity:
min = min - d*2*pi
if max is not S.Infinity:
max = max - d*2*pi
if AccumBounds(min, max).intersection(FiniteSet(pi/2, pi*Rational(5, 2))) \
is not S.EmptySet and \
AccumBounds(min, max).intersection(FiniteSet(pi*Rational(3, 2),
pi*Rational(7, 2))) is not S.EmptySet:
return AccumBounds(-1, 1)
elif AccumBounds(min, max).intersection(FiniteSet(pi/2, pi*Rational(5, 2))) \
is not S.EmptySet:
return AccumBounds(Min(sin(min), sin(max)), 1)
elif AccumBounds(min, max).intersection(FiniteSet(pi*Rational(3, 2), pi*Rational(8, 2))) \
is not S.EmptySet:
return AccumBounds(-1, Max(sin(min), sin(max)))
else:
return AccumBounds(Min(sin(min), sin(max)),
Max(sin(min), sin(max)))
elif isinstance(arg, SetExpr):
return arg._eval_func(cls)
if arg.could_extract_minus_sign():
return -cls(-arg)
i_coeff = _imaginary_unit_as_coefficient(arg)
if i_coeff is not None:
from sympy.functions.elementary.hyperbolic import sinh
return S.ImaginaryUnit*sinh(i_coeff)
pi_coeff = _pi_coeff(arg)
if pi_coeff is not None:
if pi_coeff.is_integer:
return S.Zero
if (2*pi_coeff).is_integer:
# is_even-case handled above as then pi_coeff.is_integer,
# so check if known to be not even
if pi_coeff.is_even is False:
return S.NegativeOne**(pi_coeff - S.Half)
if not pi_coeff.is_Rational:
narg = pi_coeff*pi
if narg != arg:
return cls(narg)
return None
# https://github.com/sympy/sympy/issues/6048
# transform a sine to a cosine, to avoid redundant code
if pi_coeff.is_Rational:
x = pi_coeff % 2
if x > 1:
return -cls((x % 1)*pi)
if 2*x > 1:
return cls((1 - x)*pi)
narg = ((pi_coeff + Rational(3, 2)) % 2)*pi
result = cos(narg)
if not isinstance(result, cos):
return result
if pi_coeff*pi != arg:
return cls(pi_coeff*pi)
return None
if arg.is_Add:
x, m = _peeloff_pi(arg)
if m:
m = m*pi
return sin(m)*cos(x) + cos(m)*sin(x)
if arg.is_zero:
return S.Zero
if isinstance(arg, asin):
return arg.args[0]
if isinstance(arg, atan):
x = arg.args[0]
return x/sqrt(1 + x**2)
if isinstance(arg, atan2):
y, x = arg.args
return y/sqrt(x**2 + y**2)
if isinstance(arg, acos):
x = arg.args[0]
return sqrt(1 - x**2)
if isinstance(arg, acot):
x = arg.args[0]
return 1/(sqrt(1 + 1/x**2)*x)
if isinstance(arg, acsc):
x = arg.args[0]
return 1/x
if isinstance(arg, asec):
x = arg.args[0]
return sqrt(1 - 1/x**2)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 2:
p = previous_terms[-2]
return -p*x**2/(n*(n - 1))
else:
return S.NegativeOne**(n//2)*x**n/factorial(n)
def _eval_nseries(self, x, n, logx, cdir=0):
arg = self.args[0]
if logx is not None:
arg = arg.subs(log(x), logx)
if arg.subs(x, 0).has(S.NaN, S.ComplexInfinity):
raise PoleError("Cannot expand %s around 0" % (self))
return Function._eval_nseries(self, x, n=n, logx=logx, cdir=cdir)
def _eval_rewrite_as_exp(self, arg, **kwargs):
from sympy.functions.elementary.hyperbolic import HyperbolicFunction
I = S.ImaginaryUnit
if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)):
arg = arg.func(arg.args[0]).rewrite(exp)
return (exp(arg*I) - exp(-arg*I))/(2*I)
def _eval_rewrite_as_Pow(self, arg, **kwargs):
if isinstance(arg, log):
I = S.ImaginaryUnit
x = arg.args[0]
return I*x**-I/2 - I*x**I /2
def _eval_rewrite_as_cos(self, arg, **kwargs):
return cos(arg - pi/2, evaluate=False)
def _eval_rewrite_as_tan(self, arg, **kwargs):
tan_half = tan(S.Half*arg)
return 2*tan_half/(1 + tan_half**2)
def _eval_rewrite_as_sincos(self, arg, **kwargs):
return sin(arg)*cos(arg)/cos(arg)
def _eval_rewrite_as_cot(self, arg, **kwargs):
cot_half = cot(S.Half*arg)
return Piecewise((0, And(Eq(im(arg), 0), Eq(Mod(arg, pi), 0))),
(2*cot_half/(1 + cot_half**2), True))
def _eval_rewrite_as_pow(self, arg, **kwargs):
return self.rewrite(cos).rewrite(pow)
def _eval_rewrite_as_sqrt(self, arg, **kwargs):
return self.rewrite(cos).rewrite(sqrt)
def _eval_rewrite_as_csc(self, arg, **kwargs):
return 1/csc(arg)
def _eval_rewrite_as_sec(self, arg, **kwargs):
return 1/sec(arg - pi/2, evaluate=False)
def _eval_rewrite_as_sinc(self, arg, **kwargs):
return arg*sinc(arg)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
from sympy.functions.elementary.hyperbolic import cosh, sinh
re, im = self._as_real_imag(deep=deep, **hints)
return (sin(re)*cosh(im), cos(re)*sinh(im))
def _eval_expand_trig(self, **hints):
from sympy.functions.special.polynomials import chebyshevt, chebyshevu
arg = self.args[0]
x = None
if arg.is_Add: # TODO, implement more if deep stuff here
# TODO: Do this more efficiently for more than two terms
x, y = arg.as_two_terms()
sx = sin(x, evaluate=False)._eval_expand_trig()
sy = sin(y, evaluate=False)._eval_expand_trig()
cx = cos(x, evaluate=False)._eval_expand_trig()
cy = cos(y, evaluate=False)._eval_expand_trig()
return sx*cy + sy*cx
elif arg.is_Mul:
n, x = arg.as_coeff_Mul(rational=True)
if n.is_Integer: # n will be positive because of .eval
# canonicalization
# See http://mathworld.wolfram.com/Multiple-AngleFormulas.html
if n.is_odd:
return S.NegativeOne**((n - 1)/2)*chebyshevt(n, sin(x))
else:
return expand_mul(S.NegativeOne**(n/2 - 1)*cos(x)*
chebyshevu(n - 1, sin(x)), deep=False)
pi_coeff = _pi_coeff(arg)
if pi_coeff is not None:
if pi_coeff.is_Rational:
return self.rewrite(sqrt)
return sin(arg)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.calculus.accumulationbounds import AccumBounds
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
n = x0/pi
if n.is_integer:
lt = (arg - n*pi).as_leading_term(x)
return (S.NegativeOne**n)*lt
if x0 is S.ComplexInfinity:
x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
if x0 in [S.Infinity, S.NegativeInfinity]:
return AccumBounds(-1, 1)
return self.func(x0) if x0.is_finite else self
def _eval_is_extended_real(self):
if self.args[0].is_extended_real:
return True
def _eval_is_finite(self):
arg = self.args[0]
if arg.is_extended_real:
return True
def _eval_is_zero(self):
rest, pi_mult = _peeloff_pi(self.args[0])
if rest.is_zero:
return pi_mult.is_integer
def _eval_is_complex(self):
if self.args[0].is_extended_real \
or self.args[0].is_complex:
return True
class cos(TrigonometricFunction):
"""
The cosine function.
Returns the cosine of x (measured in radians).
Explanation
===========
See :func:`sin` for notes about automatic evaluation.
Examples
========
>>> from sympy import cos, pi
>>> from sympy.abc import x
>>> cos(x**2).diff(x)
-2*x*sin(x**2)
>>> cos(1).diff(x)
0
>>> cos(pi)
-1
>>> cos(pi/2)
0
>>> cos(2*pi/3)
-1/2
>>> cos(pi/12)
sqrt(2)/4 + sqrt(6)/4
See Also
========
sin, csc, sec, tan, cot
asin, acsc, acos, asec, atan, acot, atan2
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigonometric_functions
.. [2] http://dlmf.nist.gov/4.14
.. [3] http://functions.wolfram.com/ElementaryFunctions/Cos
"""
def period(self, symbol=None):
return self._period(2*pi, symbol)
def fdiff(self, argindex=1):
if argindex == 1:
return -sin(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
from sympy.functions.special.polynomials import chebyshevt
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.sets.setexpr import SetExpr
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg.is_zero:
return S.One
elif arg in (S.Infinity, S.NegativeInfinity):
# In this case it is better to return AccumBounds(-1, 1)
# rather than returning S.NaN, since AccumBounds(-1, 1)
# preserves the information that sin(oo) is between
# -1 and 1, where S.NaN does not do that.
return AccumBounds(-1, 1)
if arg is S.ComplexInfinity:
return S.NaN
if isinstance(arg, AccumBounds):
return sin(arg + pi/2)
elif isinstance(arg, SetExpr):
return arg._eval_func(cls)
if arg.is_extended_real and arg.is_finite is False:
return AccumBounds(-1, 1)
if arg.could_extract_minus_sign():
return cls(-arg)
i_coeff = _imaginary_unit_as_coefficient(arg)
if i_coeff is not None:
from sympy.functions.elementary.hyperbolic import cosh
return cosh(i_coeff)
pi_coeff = _pi_coeff(arg)
if pi_coeff is not None:
if pi_coeff.is_integer:
return (S.NegativeOne)**pi_coeff
if (2*pi_coeff).is_integer:
# is_even-case handled above as then pi_coeff.is_integer,
# so check if known to be not even
if pi_coeff.is_even is False:
return S.Zero
if not pi_coeff.is_Rational:
narg = pi_coeff*pi
if narg != arg:
return cls(narg)
return None
# cosine formula #####################
# https://github.com/sympy/sympy/issues/6048
# explicit calculations are performed for
# cos(k pi/n) for n = 8,10,12,15,20,24,30,40,60,120
# Some other exact values like cos(k pi/240) can be
# calculated using a partial-fraction decomposition
# by calling cos( X ).rewrite(sqrt)
if pi_coeff.is_Rational:
q = pi_coeff.q
p = pi_coeff.p % (2*q)
if p > q:
narg = (pi_coeff - 1)*pi
return -cls(narg)
if 2*p > q:
narg = (1 - pi_coeff)*pi
return -cls(narg)
# If nested sqrt's are worse than un-evaluation
# you can require q to be in (1, 2, 3, 4, 6, 12)
# q <= 12, q=15, q=20, q=24, q=30, q=40, q=60, q=120 return
# expressions with 2 or fewer sqrt nestings.
table2 = _table2()
if q in table2:
a, b = table2[q]
a, b = p*pi/a, p*pi/b
nvala, nvalb = cls(a), cls(b)
if None in (nvala, nvalb):
return None
return nvala*nvalb + cls(pi/2 - a)*cls(pi/2 - b)
if q > 12:
return None
cst_table_some = {
3: S.Half,
5: (sqrt(5) + 1) / 4,
}
if q in cst_table_some:
cts = cst_table_some[pi_coeff.q]
return chebyshevt(pi_coeff.p, cts).expand()
if 0 == q % 2:
narg = (pi_coeff*2)*pi
nval = cls(narg)
if None == nval:
return None
x = (2*pi_coeff + 1)/2
sign_cos = (-1)**((-1 if x < 0 else 1)*int(abs(x)))
return sign_cos*sqrt( (1 + nval)/2 )
return None
if arg.is_Add:
x, m = _peeloff_pi(arg)
if m:
m = m*pi
return cos(m)*cos(x) - sin(m)*sin(x)
if arg.is_zero:
return S.One
if isinstance(arg, acos):
return arg.args[0]
if isinstance(arg, atan):
x = arg.args[0]
return 1/sqrt(1 + x**2)
if isinstance(arg, atan2):
y, x = arg.args
return x/sqrt(x**2 + y**2)
if isinstance(arg, asin):
x = arg.args[0]
return sqrt(1 - x ** 2)
if isinstance(arg, acot):
x = arg.args[0]
return 1/sqrt(1 + 1/x**2)
if isinstance(arg, acsc):
x = arg.args[0]
return sqrt(1 - 1/x**2)
if isinstance(arg, asec):
x = arg.args[0]
return 1/x
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 1:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 2:
p = previous_terms[-2]
return -p*x**2/(n*(n - 1))
else:
return S.NegativeOne**(n//2)*x**n/factorial(n)
def _eval_nseries(self, x, n, logx, cdir=0):
arg = self.args[0]
if logx is not None:
arg = arg.subs(log(x), logx)
if arg.subs(x, 0).has(S.NaN, S.ComplexInfinity):
raise PoleError("Cannot expand %s around 0" % (self))
return Function._eval_nseries(self, x, n=n, logx=logx, cdir=cdir)
def _eval_rewrite_as_exp(self, arg, **kwargs):
I = S.ImaginaryUnit
from sympy.functions.elementary.hyperbolic import HyperbolicFunction
if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)):
arg = arg.func(arg.args[0]).rewrite(exp)
return (exp(arg*I) + exp(-arg*I))/2
def _eval_rewrite_as_Pow(self, arg, **kwargs):
if isinstance(arg, log):
I = S.ImaginaryUnit
x = arg.args[0]
return x**I/2 + x**-I/2
def _eval_rewrite_as_sin(self, arg, **kwargs):
return sin(arg + pi/2, evaluate=False)
def _eval_rewrite_as_tan(self, arg, **kwargs):
tan_half = tan(S.Half*arg)**2
return (1 - tan_half)/(1 + tan_half)
def _eval_rewrite_as_sincos(self, arg, **kwargs):
return sin(arg)*cos(arg)/sin(arg)
def _eval_rewrite_as_cot(self, arg, **kwargs):
cot_half = cot(S.Half*arg)**2
return Piecewise((1, And(Eq(im(arg), 0), Eq(Mod(arg, 2*pi), 0))),
((cot_half - 1)/(cot_half + 1), True))
def _eval_rewrite_as_pow(self, arg, **kwargs):
return self._eval_rewrite_as_sqrt(arg)
def _eval_rewrite_as_sqrt(self, arg: Expr, **kwargs):
from sympy.functions.special.polynomials import chebyshevt
pi_coeff = _pi_coeff(arg)
if pi_coeff is None:
return None
if isinstance(pi_coeff, Integer):
return None
if not isinstance(pi_coeff, Rational):
return None
cst_table_some = cos_table()
if pi_coeff.q in cst_table_some:
rv = chebyshevt(pi_coeff.p, cst_table_some[pi_coeff.q]())
if pi_coeff.q < 257:
rv = rv.expand()
return rv
if not pi_coeff.q % 2: # recursively remove factors of 2
pico2 = pi_coeff * 2
nval = cos(pico2 * pi).rewrite(sqrt)
x = (pico2 + 1) / 2
sign_cos = -1 if int(x) % 2 else 1
return sign_cos * sqrt((1 + nval) / 2)
FC = fermat_coords(pi_coeff.q)
if FC:
denoms = FC
else:
denoms = [b**e for b, e in factorint(pi_coeff.q).items()]
apart = ipartfrac(*denoms)
decomp = (pi_coeff.p * Rational(n, d) for n, d in zip(apart, denoms))
X = [(x[1], x[0]*pi) for x in zip(decomp, numbered_symbols('z'))]
pcls = cos(sum(x[0] for x in X))._eval_expand_trig().subs(X)
if not FC or len(FC) == 1:
return pcls
return pcls.rewrite(sqrt)
def _eval_rewrite_as_sec(self, arg, **kwargs):
return 1/sec(arg)
def _eval_rewrite_as_csc(self, arg, **kwargs):
return 1/sec(arg).rewrite(csc)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
from sympy.functions.elementary.hyperbolic import cosh, sinh
re, im = self._as_real_imag(deep=deep, **hints)
return (cos(re)*cosh(im), -sin(re)*sinh(im))
def _eval_expand_trig(self, **hints):
from sympy.functions.special.polynomials import chebyshevt
arg = self.args[0]
x = None
if arg.is_Add: # TODO: Do this more efficiently for more than two terms
x, y = arg.as_two_terms()
sx = sin(x, evaluate=False)._eval_expand_trig()
sy = sin(y, evaluate=False)._eval_expand_trig()
cx = cos(x, evaluate=False)._eval_expand_trig()
cy = cos(y, evaluate=False)._eval_expand_trig()
return cx*cy - sx*sy
elif arg.is_Mul:
coeff, terms = arg.as_coeff_Mul(rational=True)
if coeff.is_Integer:
return chebyshevt(coeff, cos(terms))
pi_coeff = _pi_coeff(arg)
if pi_coeff is not None:
if pi_coeff.is_Rational:
return self.rewrite(sqrt)
return cos(arg)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.calculus.accumulationbounds import AccumBounds
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
n = (x0 + pi/2)/pi
if n.is_integer:
lt = (arg - n*pi + pi/2).as_leading_term(x)
return (S.NegativeOne**n)*lt
if x0 is S.ComplexInfinity:
x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
if x0 in [S.Infinity, S.NegativeInfinity]:
return AccumBounds(-1, 1)
return self.func(x0) if x0.is_finite else self
def _eval_is_extended_real(self):
if self.args[0].is_extended_real:
return True
def _eval_is_finite(self):
arg = self.args[0]
if arg.is_extended_real:
return True
def _eval_is_complex(self):
if self.args[0].is_extended_real \
or self.args[0].is_complex:
return True
def _eval_is_zero(self):
rest, pi_mult = _peeloff_pi(self.args[0])
if rest.is_zero and pi_mult:
return (pi_mult - S.Half).is_integer
class tan(TrigonometricFunction):
"""
The tangent function.
Returns the tangent of x (measured in radians).
Explanation
===========
See :class:`sin` for notes about automatic evaluation.
Examples
========
>>> from sympy import tan, pi
>>> from sympy.abc import x
>>> tan(x**2).diff(x)
2*x*(tan(x**2)**2 + 1)
>>> tan(1).diff(x)
0
>>> tan(pi/8).expand()
-1 + sqrt(2)
See Also
========
sin, csc, cos, sec, cot
asin, acsc, acos, asec, atan, acot, atan2
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigonometric_functions
.. [2] http://dlmf.nist.gov/4.14
.. [3] http://functions.wolfram.com/ElementaryFunctions/Tan
"""
def period(self, symbol=None):
return self._period(pi, symbol)
def fdiff(self, argindex=1):
if argindex == 1:
return S.One + self**2
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return atan
@classmethod
def eval(cls, arg):
from sympy.calculus.accumulationbounds import AccumBounds
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg.is_zero:
return S.Zero
elif arg in (S.Infinity, S.NegativeInfinity):
return AccumBounds(S.NegativeInfinity, S.Infinity)
if arg is S.ComplexInfinity:
return S.NaN
if isinstance(arg, AccumBounds):
min, max = arg.min, arg.max
d = floor(min/pi)
if min is not S.NegativeInfinity:
min = min - d*pi
if max is not S.Infinity:
max = max - d*pi
from sympy.sets.sets import FiniteSet
if AccumBounds(min, max).intersection(FiniteSet(pi/2, pi*Rational(3, 2))):
return AccumBounds(S.NegativeInfinity, S.Infinity)
else:
return AccumBounds(tan(min), tan(max))
if arg.could_extract_minus_sign():
return -cls(-arg)
i_coeff = _imaginary_unit_as_coefficient(arg)
if i_coeff is not None:
from sympy.functions.elementary.hyperbolic import tanh
return S.ImaginaryUnit*tanh(i_coeff)
pi_coeff = _pi_coeff(arg, 2)
if pi_coeff is not None:
if pi_coeff.is_integer:
return S.Zero
if not pi_coeff.is_Rational:
narg = pi_coeff*pi
if narg != arg:
return cls(narg)
return None
if pi_coeff.is_Rational:
q = pi_coeff.q
p = pi_coeff.p % q
# ensure simplified results are returned for n*pi/5, n*pi/10
table10 = {
1: sqrt(1 - 2*sqrt(5)/5),
2: sqrt(5 - 2*sqrt(5)),
3: sqrt(1 + 2*sqrt(5)/5),
4: sqrt(5 + 2*sqrt(5))
}
if q in (5, 10):
n = 10*p/q
if n > 5:
n = 10 - n
return -table10[n]
else:
return table10[n]
if not pi_coeff.q % 2:
narg = pi_coeff*pi*2
cresult, sresult = cos(narg), cos(narg - pi/2)
if not isinstance(cresult, cos) \
and not isinstance(sresult, cos):
if sresult == 0:
return S.ComplexInfinity
return 1/sresult - cresult/sresult
table2 = _table2()
if q in table2:
a, b = table2[q]
nvala, nvalb = cls(p*pi/a), cls(p*pi/b)
if None in (nvala, nvalb):
return None
return (nvala - nvalb)/(1 + nvala*nvalb)
narg = ((pi_coeff + S.Half) % 1 - S.Half)*pi
# see cos() to specify which expressions should be
# expanded automatically in terms of radicals
cresult, sresult = cos(narg), cos(narg - pi/2)
if not isinstance(cresult, cos) \
and not isinstance(sresult, cos):
if cresult == 0:
return S.ComplexInfinity
return (sresult/cresult)
if narg != arg:
return cls(narg)
if arg.is_Add:
x, m = _peeloff_pi(arg)
if m:
tanm = tan(m*pi)
if tanm is S.ComplexInfinity:
return -cot(x)
else: # tanm == 0
return tan(x)
if arg.is_zero:
return S.Zero
if isinstance(arg, atan):
return arg.args[0]
if isinstance(arg, atan2):
y, x = arg.args
return y/x
if isinstance(arg, asin):
x = arg.args[0]
return x/sqrt(1 - x**2)
if isinstance(arg, acos):
x = arg.args[0]
return sqrt(1 - x**2)/x
if isinstance(arg, acot):
x = arg.args[0]
return 1/x
if isinstance(arg, acsc):
x = arg.args[0]
return 1/(sqrt(1 - 1/x**2)*x)
if isinstance(arg, asec):
x = arg.args[0]
return sqrt(1 - 1/x**2)*x
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
a, b = ((n - 1)//2), 2**(n + 1)
B = bernoulli(n + 1)
F = factorial(n + 1)
return S.NegativeOne**a*b*(b - 1)*B/F*x**n
def _eval_nseries(self, x, n, logx, cdir=0):
i = self.args[0].limit(x, 0)*2/pi
if i and i.is_Integer:
return self.rewrite(cos)._eval_nseries(x, n=n, logx=logx)
return Function._eval_nseries(self, x, n=n, logx=logx)
def _eval_rewrite_as_Pow(self, arg, **kwargs):
if isinstance(arg, log):
I = S.ImaginaryUnit
x = arg.args[0]
return I*(x**-I - x**I)/(x**-I + x**I)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
re, im = self._as_real_imag(deep=deep, **hints)
if im:
from sympy.functions.elementary.hyperbolic import cosh, sinh
denom = cos(2*re) + cosh(2*im)
return (sin(2*re)/denom, sinh(2*im)/denom)
else:
return (self.func(re), S.Zero)
def _eval_expand_trig(self, **hints):
arg = self.args[0]
x = None
if arg.is_Add:
n = len(arg.args)
TX = []
for x in arg.args:
tx = tan(x, evaluate=False)._eval_expand_trig()
TX.append(tx)
Yg = numbered_symbols('Y')
Y = [ next(Yg) for i in range(n) ]
p = [0, 0]
for i in range(n + 1):
p[1 - i % 2] += symmetric_poly(i, Y)*(-1)**((i % 4)//2)
return (p[0]/p[1]).subs(list(zip(Y, TX)))
elif arg.is_Mul:
coeff, terms = arg.as_coeff_Mul(rational=True)
if coeff.is_Integer and coeff > 1:
I = S.ImaginaryUnit
z = Symbol('dummy', real=True)
P = ((1 + I*z)**coeff).expand()
return (im(P)/re(P)).subs([(z, tan(terms))])
return tan(arg)
def _eval_rewrite_as_exp(self, arg, **kwargs):
I = S.ImaginaryUnit
from sympy.functions.elementary.hyperbolic import HyperbolicFunction
if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)):
arg = arg.func(arg.args[0]).rewrite(exp)
neg_exp, pos_exp = exp(-arg*I), exp(arg*I)
return I*(neg_exp - pos_exp)/(neg_exp + pos_exp)
def _eval_rewrite_as_sin(self, x, **kwargs):
return 2*sin(x)**2/sin(2*x)
def _eval_rewrite_as_cos(self, x, **kwargs):
return cos(x - pi/2, evaluate=False)/cos(x)
def _eval_rewrite_as_sincos(self, arg, **kwargs):
return sin(arg)/cos(arg)
def _eval_rewrite_as_cot(self, arg, **kwargs):
return 1/cot(arg)
def _eval_rewrite_as_sec(self, arg, **kwargs):
sin_in_sec_form = sin(arg).rewrite(sec)
cos_in_sec_form = cos(arg).rewrite(sec)
return sin_in_sec_form/cos_in_sec_form
def _eval_rewrite_as_csc(self, arg, **kwargs):
sin_in_csc_form = sin(arg).rewrite(csc)
cos_in_csc_form = cos(arg).rewrite(csc)
return sin_in_csc_form/cos_in_csc_form
def _eval_rewrite_as_pow(self, arg, **kwargs):
y = self.rewrite(cos).rewrite(pow)
if y.has(cos):
return None
return y
def _eval_rewrite_as_sqrt(self, arg, **kwargs):
y = self.rewrite(cos).rewrite(sqrt)
if y.has(cos):
return None
return y
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.functions.elementary.complexes import re
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
n = 2*x0/pi
if n.is_integer:
lt = (arg - n*pi/2).as_leading_term(x)
return lt if n.is_even else -1/lt
if x0 is S.ComplexInfinity:
x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
if x0 in (S.Infinity, S.NegativeInfinity):
return AccumBounds(S.NegativeInfinity, S.Infinity)
return self.func(x0) if x0.is_finite else self
def _eval_is_extended_real(self):
# FIXME: currently tan(pi/2) return zoo
return self.args[0].is_extended_real
def _eval_is_real(self):
arg = self.args[0]
if arg.is_real and (arg/pi - S.Half).is_integer is False:
return True
def _eval_is_finite(self):
arg = self.args[0]
if arg.is_real and (arg/pi - S.Half).is_integer is False:
return True
if arg.is_imaginary:
return True
def _eval_is_zero(self):
rest, pi_mult = _peeloff_pi(self.args[0])
if rest.is_zero:
return pi_mult.is_integer
def _eval_is_complex(self):
arg = self.args[0]
if arg.is_real and (arg/pi - S.Half).is_integer is False:
return True
class cot(TrigonometricFunction):
"""
The cotangent function.
Returns the cotangent of x (measured in radians).
Explanation
===========
See :class:`sin` for notes about automatic evaluation.
Examples
========
>>> from sympy import cot, pi
>>> from sympy.abc import x
>>> cot(x**2).diff(x)
2*x*(-cot(x**2)**2 - 1)
>>> cot(1).diff(x)
0
>>> cot(pi/12)
sqrt(3) + 2
See Also
========
sin, csc, cos, sec, tan
asin, acsc, acos, asec, atan, acot, atan2
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigonometric_functions
.. [2] http://dlmf.nist.gov/4.14
.. [3] http://functions.wolfram.com/ElementaryFunctions/Cot
"""
def period(self, symbol=None):
return self._period(pi, symbol)
def fdiff(self, argindex=1):
if argindex == 1:
return S.NegativeOne - self**2
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return acot
@classmethod
def eval(cls, arg):
from sympy.calculus.accumulationbounds import AccumBounds
if arg.is_Number:
if arg is S.NaN:
return S.NaN
if arg.is_zero:
return S.ComplexInfinity
elif arg in (S.Infinity, S.NegativeInfinity):
return AccumBounds(S.NegativeInfinity, S.Infinity)
if arg is S.ComplexInfinity:
return S.NaN
if isinstance(arg, AccumBounds):
return -tan(arg + pi/2)
if arg.could_extract_minus_sign():
return -cls(-arg)
i_coeff = _imaginary_unit_as_coefficient(arg)
if i_coeff is not None:
from sympy.functions.elementary.hyperbolic import coth
return -S.ImaginaryUnit*coth(i_coeff)
pi_coeff = _pi_coeff(arg, 2)
if pi_coeff is not None:
if pi_coeff.is_integer:
return S.ComplexInfinity
if not pi_coeff.is_Rational:
narg = pi_coeff*pi
if narg != arg:
return cls(narg)
return None
if pi_coeff.is_Rational:
if pi_coeff.q in (5, 10):
return tan(pi/2 - arg)
if pi_coeff.q > 2 and not pi_coeff.q % 2:
narg = pi_coeff*pi*2
cresult, sresult = cos(narg), cos(narg - pi/2)
if not isinstance(cresult, cos) \
and not isinstance(sresult, cos):
return 1/sresult + cresult/sresult
q = pi_coeff.q
p = pi_coeff.p % q
table2 = _table2()
if q in table2:
a, b = table2[q]
nvala, nvalb = cls(p*pi/a), cls(p*pi/b)
if None in (nvala, nvalb):
return None
return (1 + nvala*nvalb)/(nvalb - nvala)
narg = (((pi_coeff + S.Half) % 1) - S.Half)*pi
# see cos() to specify which expressions should be
# expanded automatically in terms of radicals
cresult, sresult = cos(narg), cos(narg - pi/2)
if not isinstance(cresult, cos) \
and not isinstance(sresult, cos):
if sresult == 0:
return S.ComplexInfinity
return cresult/sresult
if narg != arg:
return cls(narg)
if arg.is_Add:
x, m = _peeloff_pi(arg)
if m:
cotm = cot(m*pi)
if cotm is S.ComplexInfinity:
return cot(x)
else: # cotm == 0
return -tan(x)
if arg.is_zero:
return S.ComplexInfinity
if isinstance(arg, acot):
return arg.args[0]
if isinstance(arg, atan):
x = arg.args[0]
return 1/x
if isinstance(arg, atan2):
y, x = arg.args
return x/y
if isinstance(arg, asin):
x = arg.args[0]
return sqrt(1 - x**2)/x
if isinstance(arg, acos):
x = arg.args[0]
return x/sqrt(1 - x**2)
if isinstance(arg, acsc):
x = arg.args[0]
return sqrt(1 - 1/x**2)*x
if isinstance(arg, asec):
x = arg.args[0]
return 1/(sqrt(1 - 1/x**2)*x)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n == 0:
return 1/sympify(x)
elif n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
B = bernoulli(n + 1)
F = factorial(n + 1)
return S.NegativeOne**((n + 1)//2)*2**(n + 1)*B/F*x**n
def _eval_nseries(self, x, n, logx, cdir=0):
i = self.args[0].limit(x, 0)/pi
if i and i.is_Integer:
return self.rewrite(cos)._eval_nseries(x, n=n, logx=logx)
return self.rewrite(tan)._eval_nseries(x, n=n, logx=logx)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
re, im = self._as_real_imag(deep=deep, **hints)
if im:
from sympy.functions.elementary.hyperbolic import cosh, sinh
denom = cos(2*re) - cosh(2*im)
return (-sin(2*re)/denom, sinh(2*im)/denom)
else:
return (self.func(re), S.Zero)
def _eval_rewrite_as_exp(self, arg, **kwargs):
from sympy.functions.elementary.hyperbolic import HyperbolicFunction
I = S.ImaginaryUnit
if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)):
arg = arg.func(arg.args[0]).rewrite(exp)
neg_exp, pos_exp = exp(-arg*I), exp(arg*I)
return I*(pos_exp + neg_exp)/(pos_exp - neg_exp)
def _eval_rewrite_as_Pow(self, arg, **kwargs):
if isinstance(arg, log):
I = S.ImaginaryUnit
x = arg.args[0]
return -I*(x**-I + x**I)/(x**-I - x**I)
def _eval_rewrite_as_sin(self, x, **kwargs):
return sin(2*x)/(2*(sin(x)**2))
def _eval_rewrite_as_cos(self, x, **kwargs):
return cos(x)/cos(x - pi/2, evaluate=False)
def _eval_rewrite_as_sincos(self, arg, **kwargs):
return cos(arg)/sin(arg)
def _eval_rewrite_as_tan(self, arg, **kwargs):
return 1/tan(arg)
def _eval_rewrite_as_sec(self, arg, **kwargs):
cos_in_sec_form = cos(arg).rewrite(sec)
sin_in_sec_form = sin(arg).rewrite(sec)
return cos_in_sec_form/sin_in_sec_form
def _eval_rewrite_as_csc(self, arg, **kwargs):
cos_in_csc_form = cos(arg).rewrite(csc)
sin_in_csc_form = sin(arg).rewrite(csc)
return cos_in_csc_form/sin_in_csc_form
def _eval_rewrite_as_pow(self, arg, **kwargs):
y = self.rewrite(cos).rewrite(pow)
if y.has(cos):
return None
return y
def _eval_rewrite_as_sqrt(self, arg, **kwargs):
y = self.rewrite(cos).rewrite(sqrt)
if y.has(cos):
return None
return y
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.functions.elementary.complexes import re
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
n = 2*x0/pi
if n.is_integer:
lt = (arg - n*pi/2).as_leading_term(x)
return 1/lt if n.is_even else -lt
if x0 is S.ComplexInfinity:
x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
if x0 in (S.Infinity, S.NegativeInfinity):
return AccumBounds(S.NegativeInfinity, S.Infinity)
return self.func(x0) if x0.is_finite else self
def _eval_is_extended_real(self):
return self.args[0].is_extended_real
def _eval_expand_trig(self, **hints):
arg = self.args[0]
x = None
if arg.is_Add:
n = len(arg.args)
CX = []
for x in arg.args:
cx = cot(x, evaluate=False)._eval_expand_trig()
CX.append(cx)
Yg = numbered_symbols('Y')
Y = [ next(Yg) for i in range(n) ]
p = [0, 0]
for i in range(n, -1, -1):
p[(n - i) % 2] += symmetric_poly(i, Y)*(-1)**(((n - i) % 4)//2)
return (p[0]/p[1]).subs(list(zip(Y, CX)))
elif arg.is_Mul:
coeff, terms = arg.as_coeff_Mul(rational=True)
if coeff.is_Integer and coeff > 1:
I = S.ImaginaryUnit
z = Symbol('dummy', real=True)
P = ((z + I)**coeff).expand()
return (re(P)/im(P)).subs([(z, cot(terms))])
return cot(arg) # XXX sec and csc return 1/cos and 1/sin
def _eval_is_finite(self):
arg = self.args[0]
if arg.is_real and (arg/pi).is_integer is False:
return True
if arg.is_imaginary:
return True
def _eval_is_real(self):
arg = self.args[0]
if arg.is_real and (arg/pi).is_integer is False:
return True
def _eval_is_complex(self):
arg = self.args[0]
if arg.is_real and (arg/pi).is_integer is False:
return True
def _eval_is_zero(self):
rest, pimult = _peeloff_pi(self.args[0])
if pimult and rest.is_zero:
return (pimult - S.Half).is_integer
def _eval_subs(self, old, new):
arg = self.args[0]
argnew = arg.subs(old, new)
if arg != argnew and (argnew/pi).is_integer:
return S.ComplexInfinity
return cot(argnew)
class ReciprocalTrigonometricFunction(TrigonometricFunction):
"""Base class for reciprocal functions of trigonometric functions. """
_reciprocal_of = None # mandatory, to be defined in subclass
_singularities = (S.ComplexInfinity,)
# _is_even and _is_odd are used for correct evaluation of csc(-x), sec(-x)
# TODO refactor into TrigonometricFunction common parts of
# trigonometric functions eval() like even/odd, func(x+2*k*pi), etc.
# optional, to be defined in subclasses:
_is_even: FuzzyBool = None
_is_odd: FuzzyBool = None
@classmethod
def eval(cls, arg):
if arg.could_extract_minus_sign():
if cls._is_even:
return cls(-arg)
if cls._is_odd:
return -cls(-arg)
pi_coeff = _pi_coeff(arg)
if (pi_coeff is not None
and not (2*pi_coeff).is_integer
and pi_coeff.is_Rational):
q = pi_coeff.q
p = pi_coeff.p % (2*q)
if p > q:
narg = (pi_coeff - 1)*pi
return -cls(narg)
if 2*p > q:
narg = (1 - pi_coeff)*pi
if cls._is_odd:
return cls(narg)
elif cls._is_even:
return -cls(narg)
if hasattr(arg, 'inverse') and arg.inverse() == cls:
return arg.args[0]
t = cls._reciprocal_of.eval(arg)
if t is None:
return t
elif any(isinstance(i, cos) for i in (t, -t)):
return (1/t).rewrite(sec)
elif any(isinstance(i, sin) for i in (t, -t)):
return (1/t).rewrite(csc)
else:
return 1/t
def _call_reciprocal(self, method_name, *args, **kwargs):
# Calls method_name on _reciprocal_of
o = self._reciprocal_of(self.args[0])
return getattr(o, method_name)(*args, **kwargs)
def _calculate_reciprocal(self, method_name, *args, **kwargs):
# If calling method_name on _reciprocal_of returns a value != None
# then return the reciprocal of that value
t = self._call_reciprocal(method_name, *args, **kwargs)
return 1/t if t is not None else t
def _rewrite_reciprocal(self, method_name, arg):
# Special handling for rewrite functions. If reciprocal rewrite returns
# unmodified expression, then return None
t = self._call_reciprocal(method_name, arg)
if t is not None and t != self._reciprocal_of(arg):
return 1/t
def _period(self, symbol):
f = expand_mul(self.args[0])
return self._reciprocal_of(f).period(symbol)
def fdiff(self, argindex=1):
return -self._calculate_reciprocal("fdiff", argindex)/self**2
def _eval_rewrite_as_exp(self, arg, **kwargs):
return self._rewrite_reciprocal("_eval_rewrite_as_exp", arg)
def _eval_rewrite_as_Pow(self, arg, **kwargs):
return self._rewrite_reciprocal("_eval_rewrite_as_Pow", arg)
def _eval_rewrite_as_sin(self, arg, **kwargs):
return self._rewrite_reciprocal("_eval_rewrite_as_sin", arg)
def _eval_rewrite_as_cos(self, arg, **kwargs):
return self._rewrite_reciprocal("_eval_rewrite_as_cos", arg)
def _eval_rewrite_as_tan(self, arg, **kwargs):
return self._rewrite_reciprocal("_eval_rewrite_as_tan", arg)
def _eval_rewrite_as_pow(self, arg, **kwargs):
return self._rewrite_reciprocal("_eval_rewrite_as_pow", arg)
def _eval_rewrite_as_sqrt(self, arg, **kwargs):
return self._rewrite_reciprocal("_eval_rewrite_as_sqrt", arg)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
return (1/self._reciprocal_of(self.args[0])).as_real_imag(deep,
**hints)
def _eval_expand_trig(self, **hints):
return self._calculate_reciprocal("_eval_expand_trig", **hints)
def _eval_is_extended_real(self):
return self._reciprocal_of(self.args[0])._eval_is_extended_real()
def _eval_as_leading_term(self, x, logx=None, cdir=0):
return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x)
def _eval_is_finite(self):
return (1/self._reciprocal_of(self.args[0])).is_finite
def _eval_nseries(self, x, n, logx, cdir=0):
return (1/self._reciprocal_of(self.args[0]))._eval_nseries(x, n, logx)
class sec(ReciprocalTrigonometricFunction):
"""
The secant function.
Returns the secant of x (measured in radians).
Explanation
===========
See :class:`sin` for notes about automatic evaluation.
Examples
========
>>> from sympy import sec
>>> from sympy.abc import x
>>> sec(x**2).diff(x)
2*x*tan(x**2)*sec(x**2)
>>> sec(1).diff(x)
0
See Also
========
sin, csc, cos, tan, cot
asin, acsc, acos, asec, atan, acot, atan2
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigonometric_functions
.. [2] http://dlmf.nist.gov/4.14
.. [3] http://functions.wolfram.com/ElementaryFunctions/Sec
"""
_reciprocal_of = cos
_is_even = True
def period(self, symbol=None):
return self._period(symbol)
def _eval_rewrite_as_cot(self, arg, **kwargs):
cot_half_sq = cot(arg/2)**2
return (cot_half_sq + 1)/(cot_half_sq - 1)
def _eval_rewrite_as_cos(self, arg, **kwargs):
return (1/cos(arg))
def _eval_rewrite_as_sincos(self, arg, **kwargs):
return sin(arg)/(cos(arg)*sin(arg))
def _eval_rewrite_as_sin(self, arg, **kwargs):
return (1/cos(arg).rewrite(sin))
def _eval_rewrite_as_tan(self, arg, **kwargs):
return (1/cos(arg).rewrite(tan))
def _eval_rewrite_as_csc(self, arg, **kwargs):
return csc(pi/2 - arg, evaluate=False)
def fdiff(self, argindex=1):
if argindex == 1:
return tan(self.args[0])*sec(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
def _eval_is_complex(self):
arg = self.args[0]
if arg.is_complex and (arg/pi - S.Half).is_integer is False:
return True
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
# Reference Formula:
# http://functions.wolfram.com/ElementaryFunctions/Sec/06/01/02/01/
if n < 0 or n % 2 == 1:
return S.Zero
else:
x = sympify(x)
k = n//2
return S.NegativeOne**k*euler(2*k)/factorial(2*k)*x**(2*k)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.functions.elementary.complexes import re
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
n = (x0 + pi/2)/pi
if n.is_integer:
lt = (arg - n*pi + pi/2).as_leading_term(x)
return (S.NegativeOne**n)/lt
if x0 is S.ComplexInfinity:
x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
if x0 in (S.Infinity, S.NegativeInfinity):
return AccumBounds(S.NegativeInfinity, S.Infinity)
return self.func(x0) if x0.is_finite else self
class csc(ReciprocalTrigonometricFunction):
"""
The cosecant function.
Returns the cosecant of x (measured in radians).
Explanation
===========
See :func:`sin` for notes about automatic evaluation.
Examples
========
>>> from sympy import csc
>>> from sympy.abc import x
>>> csc(x**2).diff(x)
-2*x*cot(x**2)*csc(x**2)
>>> csc(1).diff(x)
0
See Also
========
sin, cos, sec, tan, cot
asin, acsc, acos, asec, atan, acot, atan2
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigonometric_functions
.. [2] http://dlmf.nist.gov/4.14
.. [3] http://functions.wolfram.com/ElementaryFunctions/Csc
"""
_reciprocal_of = sin
_is_odd = True
def period(self, symbol=None):
return self._period(symbol)
def _eval_rewrite_as_sin(self, arg, **kwargs):
return (1/sin(arg))
def _eval_rewrite_as_sincos(self, arg, **kwargs):
return cos(arg)/(sin(arg)*cos(arg))
def _eval_rewrite_as_cot(self, arg, **kwargs):
cot_half = cot(arg/2)
return (1 + cot_half**2)/(2*cot_half)
def _eval_rewrite_as_cos(self, arg, **kwargs):
return 1/sin(arg).rewrite(cos)
def _eval_rewrite_as_sec(self, arg, **kwargs):
return sec(pi/2 - arg, evaluate=False)
def _eval_rewrite_as_tan(self, arg, **kwargs):
return (1/sin(arg).rewrite(tan))
def fdiff(self, argindex=1):
if argindex == 1:
return -cot(self.args[0])*csc(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
def _eval_is_complex(self):
arg = self.args[0]
if arg.is_real and (arg/pi).is_integer is False:
return True
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n == 0:
return 1/sympify(x)
elif n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
k = n//2 + 1
return (S.NegativeOne**(k - 1)*2*(2**(2*k - 1) - 1)*
bernoulli(2*k)*x**(2*k - 1)/factorial(2*k))
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.functions.elementary.complexes import re
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
n = x0/pi
if n.is_integer:
lt = (arg - n*pi).as_leading_term(x)
return (S.NegativeOne**n)/lt
if x0 is S.ComplexInfinity:
x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
if x0 in (S.Infinity, S.NegativeInfinity):
return AccumBounds(S.NegativeInfinity, S.Infinity)
return self.func(x0) if x0.is_finite else self
class sinc(Function):
r"""
Represents an unnormalized sinc function:
.. math::
\operatorname{sinc}(x) =
\begin{cases}
\frac{\sin x}{x} & \qquad x \neq 0 \\
1 & \qquad x = 0
\end{cases}
Examples
========
>>> from sympy import sinc, oo, jn
>>> from sympy.abc import x
>>> sinc(x)
sinc(x)
* Automated Evaluation
>>> sinc(0)
1
>>> sinc(oo)
0
* Differentiation
>>> sinc(x).diff()
cos(x)/x - sin(x)/x**2
* Series Expansion
>>> sinc(x).series()
1 - x**2/6 + x**4/120 + O(x**6)
* As zero'th order spherical Bessel Function
>>> sinc(x).rewrite(jn)
jn(0, x)
See also
========
sin
References
==========
.. [1] https://en.wikipedia.org/wiki/Sinc_function
"""
_singularities = (S.ComplexInfinity,)
def fdiff(self, argindex=1):
x = self.args[0]
if argindex == 1:
# We would like to return the Piecewise here, but Piecewise.diff
# currently can't handle removable singularities, meaning things
# like sinc(x).diff(x, 2) give the wrong answer at x = 0. See
# https://github.com/sympy/sympy/issues/11402.
#
# return Piecewise(((x*cos(x) - sin(x))/x**2, Ne(x, S.Zero)), (S.Zero, S.true))
return cos(x)/x - sin(x)/x**2
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
if arg.is_zero:
return S.One
if arg.is_Number:
if arg in [S.Infinity, S.NegativeInfinity]:
return S.Zero
elif arg is S.NaN:
return S.NaN
if arg is S.ComplexInfinity:
return S.NaN
if arg.could_extract_minus_sign():
return cls(-arg)
pi_coeff = _pi_coeff(arg)
if pi_coeff is not None:
if pi_coeff.is_integer:
if fuzzy_not(arg.is_zero):
return S.Zero
elif (2*pi_coeff).is_integer:
return S.NegativeOne**(pi_coeff - S.Half)/arg
def _eval_nseries(self, x, n, logx, cdir=0):
x = self.args[0]
return (sin(x)/x)._eval_nseries(x, n, logx)
def _eval_rewrite_as_jn(self, arg, **kwargs):
from sympy.functions.special.bessel import jn
return jn(0, arg)
def _eval_rewrite_as_sin(self, arg, **kwargs):
return Piecewise((sin(arg)/arg, Ne(arg, S.Zero)), (S.One, S.true))
def _eval_is_zero(self):
if self.args[0].is_infinite:
return True
rest, pi_mult = _peeloff_pi(self.args[0])
if rest.is_zero:
return fuzzy_and([pi_mult.is_integer, pi_mult.is_nonzero])
if rest.is_Number and pi_mult.is_integer:
return False
def _eval_is_real(self):
if self.args[0].is_extended_real or self.args[0].is_imaginary:
return True
_eval_is_finite = _eval_is_real
###############################################################################
########################### TRIGONOMETRIC INVERSES ############################
###############################################################################
class InverseTrigonometricFunction(Function):
"""Base class for inverse trigonometric functions."""
_singularities = (S.One, S.NegativeOne, S.Zero, S.ComplexInfinity) # type: tTuple[Expr, ...]
@staticmethod
@cacheit
def _asin_table():
# Only keys with could_extract_minus_sign() == False
# are actually needed.
return {
sqrt(3)/2: pi/3,
sqrt(2)/2: pi/4,
1/sqrt(2): pi/4,
sqrt((5 - sqrt(5))/8): pi/5,
sqrt(2)*sqrt(5 - sqrt(5))/4: pi/5,
sqrt((5 + sqrt(5))/8): pi*Rational(2, 5),
sqrt(2)*sqrt(5 + sqrt(5))/4: pi*Rational(2, 5),
S.Half: pi/6,
sqrt(2 - sqrt(2))/2: pi/8,
sqrt(S.Half - sqrt(2)/4): pi/8,
sqrt(2 + sqrt(2))/2: pi*Rational(3, 8),
sqrt(S.Half + sqrt(2)/4): pi*Rational(3, 8),
(sqrt(5) - 1)/4: pi/10,
(1 - sqrt(5))/4: -pi/10,
(sqrt(5) + 1)/4: pi*Rational(3, 10),
sqrt(6)/4 - sqrt(2)/4: pi/12,
-sqrt(6)/4 + sqrt(2)/4: -pi/12,
(sqrt(3) - 1)/sqrt(8): pi/12,
(1 - sqrt(3))/sqrt(8): -pi/12,
sqrt(6)/4 + sqrt(2)/4: pi*Rational(5, 12),
(1 + sqrt(3))/sqrt(8): pi*Rational(5, 12)
}
@staticmethod
@cacheit
def _atan_table():
# Only keys with could_extract_minus_sign() == False
# are actually needed.
return {
sqrt(3)/3: pi/6,
1/sqrt(3): pi/6,
sqrt(3): pi/3,
sqrt(2) - 1: pi/8,
1 - sqrt(2): -pi/8,
1 + sqrt(2): pi*Rational(3, 8),
sqrt(5 - 2*sqrt(5)): pi/5,
sqrt(5 + 2*sqrt(5)): pi*Rational(2, 5),
sqrt(1 - 2*sqrt(5)/5): pi/10,
sqrt(1 + 2*sqrt(5)/5): pi*Rational(3, 10),
2 - sqrt(3): pi/12,
-2 + sqrt(3): -pi/12,
2 + sqrt(3): pi*Rational(5, 12)
}
@staticmethod
@cacheit
def _acsc_table():
# Keys for which could_extract_minus_sign()
# will obviously return True are omitted.
return {
2*sqrt(3)/3: pi/3,
sqrt(2): pi/4,
sqrt(2 + 2*sqrt(5)/5): pi/5,
1/sqrt(Rational(5, 8) - sqrt(5)/8): pi/5,
sqrt(2 - 2*sqrt(5)/5): pi*Rational(2, 5),
1/sqrt(Rational(5, 8) + sqrt(5)/8): pi*Rational(2, 5),
2: pi/6,
sqrt(4 + 2*sqrt(2)): pi/8,
2/sqrt(2 - sqrt(2)): pi/8,
sqrt(4 - 2*sqrt(2)): pi*Rational(3, 8),
2/sqrt(2 + sqrt(2)): pi*Rational(3, 8),
1 + sqrt(5): pi/10,
sqrt(5) - 1: pi*Rational(3, 10),
-(sqrt(5) - 1): pi*Rational(-3, 10),
sqrt(6) + sqrt(2): pi/12,
sqrt(6) - sqrt(2): pi*Rational(5, 12),
-(sqrt(6) - sqrt(2)): pi*Rational(-5, 12)
}
class asin(InverseTrigonometricFunction):
r"""
The inverse sine function.
Returns the arcsine of x in radians.
Explanation
===========
``asin(x)`` will evaluate automatically in the cases
$x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when the
result is a rational multiple of $\pi$ (see the ``eval`` class method).
A purely imaginary argument will lead to an asinh expression.
Examples
========
>>> from sympy import asin, oo
>>> asin(1)
pi/2
>>> asin(-1)
-pi/2
>>> asin(-oo)
oo*I
>>> asin(oo)
-oo*I
See Also
========
sin, csc, cos, sec, tan, cot
acsc, acos, asec, atan, acot, atan2
References
==========
.. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
.. [2] http://dlmf.nist.gov/4.23
.. [3] http://functions.wolfram.com/ElementaryFunctions/ArcSin
"""
def fdiff(self, argindex=1):
if argindex == 1:
return 1/sqrt(1 - self.args[0]**2)
else:
raise ArgumentIndexError(self, argindex)
def _eval_is_rational(self):
s = self.func(*self.args)
if s.func == self.func:
if s.args[0].is_rational:
return False
else:
return s.is_rational
def _eval_is_positive(self):
return self._eval_is_extended_real() and self.args[0].is_positive
def _eval_is_negative(self):
return self._eval_is_extended_real() and self.args[0].is_negative
@classmethod
def eval(cls, arg):
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.NegativeInfinity*S.ImaginaryUnit
elif arg is S.NegativeInfinity:
return S.Infinity*S.ImaginaryUnit
elif arg.is_zero:
return S.Zero
elif arg is S.One:
return pi/2
elif arg is S.NegativeOne:
return -pi/2
if arg is S.ComplexInfinity:
return S.ComplexInfinity
if arg.could_extract_minus_sign():
return -cls(-arg)
if arg.is_number:
asin_table = cls._asin_table()
if arg in asin_table:
return asin_table[arg]
i_coeff = _imaginary_unit_as_coefficient(arg)
if i_coeff is not None:
from sympy.functions.elementary.hyperbolic import asinh
return S.ImaginaryUnit*asinh(i_coeff)
if arg.is_zero:
return S.Zero
if isinstance(arg, sin):
ang = arg.args[0]
if ang.is_comparable:
ang %= 2*pi # restrict to [0,2*pi)
if ang > pi: # restrict to (-pi,pi]
ang = pi - ang
# restrict to [-pi/2,pi/2]
if ang > pi/2:
ang = pi - ang
if ang < -pi/2:
ang = -pi - ang
return ang
if isinstance(arg, cos): # acos(x) + asin(x) = pi/2
ang = arg.args[0]
if ang.is_comparable:
return pi/2 - acos(arg)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) >= 2 and n > 2:
p = previous_terms[-2]
return p*(n - 2)**2/(n*(n - 1))*x**2
else:
k = (n - 1) // 2
R = RisingFactorial(S.Half, k)
F = factorial(k)
return R/F*x**n/n
def _eval_as_leading_term(self, x, logx=None, cdir=0): # asin
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
if x0.is_zero:
return arg.as_leading_term(x)
# Handling branch points
if x0 in (-S.One, S.One, S.ComplexInfinity):
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand()
# Handling points lying on branch cuts (-oo, -1) U (1, oo)
if (1 - x0**2).is_negative:
ndir = arg.dir(x, cdir if cdir else 1)
if im(ndir).is_negative:
if x0.is_negative:
return -pi - self.func(x0)
elif im(ndir).is_positive:
if x0.is_positive:
return pi - self.func(x0)
else:
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand()
return self.func(x0)
def _eval_nseries(self, x, n, logx, cdir=0): # asin
from sympy.series.order import O
arg0 = self.args[0].subs(x, 0)
# Handling branch points
if arg0 is S.One:
t = Dummy('t', positive=True)
ser = asin(S.One - t**2).rewrite(log).nseries(t, 0, 2*n)
arg1 = S.One - self.args[0]
f = arg1.as_leading_term(x)
g = (arg1 - f)/ f
if not g.is_meromorphic(x, 0): # cannot be expanded
return O(1) if n == 0 else pi/2 + O(sqrt(x))
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
res = (res1.removeO()*sqrt(f)).expand()
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
if arg0 is S.NegativeOne:
t = Dummy('t', positive=True)
ser = asin(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n)
arg1 = S.One + self.args[0]
f = arg1.as_leading_term(x)
g = (arg1 - f)/ f
if not g.is_meromorphic(x, 0): # cannot be expanded
return O(1) if n == 0 else -pi/2 + O(sqrt(x))
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
res = (res1.removeO()*sqrt(f)).expand()
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
res = Function._eval_nseries(self, x, n=n, logx=logx)
if arg0 is S.ComplexInfinity:
return res
# Handling points lying on branch cuts (-oo, -1) U (1, oo)
if (1 - arg0**2).is_negative:
ndir = self.args[0].dir(x, cdir if cdir else 1)
if im(ndir).is_negative:
if arg0.is_negative:
return -pi - res
elif im(ndir).is_positive:
if arg0.is_positive:
return pi - res
else:
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
return res
def _eval_rewrite_as_acos(self, x, **kwargs):
return pi/2 - acos(x)
def _eval_rewrite_as_atan(self, x, **kwargs):
return 2*atan(x/(1 + sqrt(1 - x**2)))
def _eval_rewrite_as_log(self, x, **kwargs):
return -S.ImaginaryUnit*log(S.ImaginaryUnit*x + sqrt(1 - x**2))
_eval_rewrite_as_tractable = _eval_rewrite_as_log
def _eval_rewrite_as_acot(self, arg, **kwargs):
return 2*acot((1 + sqrt(1 - arg**2))/arg)
def _eval_rewrite_as_asec(self, arg, **kwargs):
return pi/2 - asec(1/arg)
def _eval_rewrite_as_acsc(self, arg, **kwargs):
return acsc(1/arg)
def _eval_is_extended_real(self):
x = self.args[0]
return x.is_extended_real and (1 - abs(x)).is_nonnegative
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return sin
class acos(InverseTrigonometricFunction):
r"""
The inverse cosine function.
Explanation
===========
Returns the arc cosine of x (measured in radians).
``acos(x)`` will evaluate automatically in the cases
$x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when
the result is a rational multiple of $\pi$ (see the eval class method).
``acos(zoo)`` evaluates to ``zoo``
(see note in :class:`sympy.functions.elementary.trigonometric.asec`)
A purely imaginary argument will be rewritten to asinh.
Examples
========
>>> from sympy import acos, oo
>>> acos(1)
0
>>> acos(0)
pi/2
>>> acos(oo)
oo*I
See Also
========
sin, csc, cos, sec, tan, cot
asin, acsc, asec, atan, acot, atan2
References
==========
.. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
.. [2] http://dlmf.nist.gov/4.23
.. [3] http://functions.wolfram.com/ElementaryFunctions/ArcCos
"""
def fdiff(self, argindex=1):
if argindex == 1:
return -1/sqrt(1 - self.args[0]**2)
else:
raise ArgumentIndexError(self, argindex)
def _eval_is_rational(self):
s = self.func(*self.args)
if s.func == self.func:
if s.args[0].is_rational:
return False
else:
return s.is_rational
@classmethod
def eval(cls, arg):
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Infinity*S.ImaginaryUnit
elif arg is S.NegativeInfinity:
return S.NegativeInfinity*S.ImaginaryUnit
elif arg.is_zero:
return pi/2
elif arg is S.One:
return S.Zero
elif arg is S.NegativeOne:
return pi
if arg is S.ComplexInfinity:
return S.ComplexInfinity
if arg.is_number:
asin_table = cls._asin_table()
if arg in asin_table:
return pi/2 - asin_table[arg]
elif -arg in asin_table:
return pi/2 + asin_table[-arg]
i_coeff = _imaginary_unit_as_coefficient(arg)
if i_coeff is not None:
return pi/2 - asin(arg)
if isinstance(arg, cos):
ang = arg.args[0]
if ang.is_comparable:
ang %= 2*pi # restrict to [0,2*pi)
if ang > pi: # restrict to [0,pi]
ang = 2*pi - ang
return ang
if isinstance(arg, sin): # acos(x) + asin(x) = pi/2
ang = arg.args[0]
if ang.is_comparable:
return pi/2 - asin(arg)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n == 0:
return pi/2
elif n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) >= 2 and n > 2:
p = previous_terms[-2]
return p*(n - 2)**2/(n*(n - 1))*x**2
else:
k = (n - 1) // 2
R = RisingFactorial(S.Half, k)
F = factorial(k)
return -R/F*x**n/n
def _eval_as_leading_term(self, x, logx=None, cdir=0): # acos
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
# Handling branch points
if x0 == 1:
return sqrt(2)*sqrt((S.One - arg).as_leading_term(x))
if x0 in (-S.One, S.ComplexInfinity):
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
# Handling points lying on branch cuts (-oo, -1) U (1, oo)
if (1 - x0**2).is_negative:
ndir = arg.dir(x, cdir if cdir else 1)
if im(ndir).is_negative:
if x0.is_negative:
return 2*pi - self.func(x0)
elif im(ndir).is_positive:
if x0.is_positive:
return -self.func(x0)
else:
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand()
return self.func(x0)
def _eval_is_extended_real(self):
x = self.args[0]
return x.is_extended_real and (1 - abs(x)).is_nonnegative
def _eval_is_nonnegative(self):
return self._eval_is_extended_real()
def _eval_nseries(self, x, n, logx, cdir=0): # acos
from sympy.series.order import O
arg0 = self.args[0].subs(x, 0)
# Handling branch points
if arg0 is S.One:
t = Dummy('t', positive=True)
ser = acos(S.One - t**2).rewrite(log).nseries(t, 0, 2*n)
arg1 = S.One - self.args[0]
f = arg1.as_leading_term(x)
g = (arg1 - f)/ f
if not g.is_meromorphic(x, 0): # cannot be expanded
return O(1) if n == 0 else O(sqrt(x))
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
res = (res1.removeO()*sqrt(f)).expand()
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
if arg0 is S.NegativeOne:
t = Dummy('t', positive=True)
ser = acos(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n)
arg1 = S.One + self.args[0]
f = arg1.as_leading_term(x)
g = (arg1 - f)/ f
if not g.is_meromorphic(x, 0): # cannot be expanded
return O(1) if n == 0 else pi + O(sqrt(x))
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
res = (res1.removeO()*sqrt(f)).expand()
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
res = Function._eval_nseries(self, x, n=n, logx=logx)
if arg0 is S.ComplexInfinity:
return res
# Handling points lying on branch cuts (-oo, -1) U (1, oo)
if (1 - arg0**2).is_negative:
ndir = self.args[0].dir(x, cdir if cdir else 1)
if im(ndir).is_negative:
if arg0.is_negative:
return 2*pi - res
elif im(ndir).is_positive:
if arg0.is_positive:
return -res
else:
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
return res
def _eval_rewrite_as_log(self, x, **kwargs):
return pi/2 + S.ImaginaryUnit*\
log(S.ImaginaryUnit*x + sqrt(1 - x**2))
_eval_rewrite_as_tractable = _eval_rewrite_as_log
def _eval_rewrite_as_asin(self, x, **kwargs):
return pi/2 - asin(x)
def _eval_rewrite_as_atan(self, x, **kwargs):
return atan(sqrt(1 - x**2)/x) + (pi/2)*(1 - x*sqrt(1/x**2))
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return cos
def _eval_rewrite_as_acot(self, arg, **kwargs):
return pi/2 - 2*acot((1 + sqrt(1 - arg**2))/arg)
def _eval_rewrite_as_asec(self, arg, **kwargs):
return asec(1/arg)
def _eval_rewrite_as_acsc(self, arg, **kwargs):
return pi/2 - acsc(1/arg)
def _eval_conjugate(self):
z = self.args[0]
r = self.func(self.args[0].conjugate())
if z.is_extended_real is False:
return r
elif z.is_extended_real and (z + 1).is_nonnegative and (z - 1).is_nonpositive:
return r
class atan(InverseTrigonometricFunction):
r"""
The inverse tangent function.
Returns the arc tangent of x (measured in radians).
Explanation
===========
``atan(x)`` will evaluate automatically in the cases
$x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when the
result is a rational multiple of $\pi$ (see the eval class method).
Examples
========
>>> from sympy import atan, oo
>>> atan(0)
0
>>> atan(1)
pi/4
>>> atan(oo)
pi/2
See Also
========
sin, csc, cos, sec, tan, cot
asin, acsc, acos, asec, acot, atan2
References
==========
.. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
.. [2] http://dlmf.nist.gov/4.23
.. [3] http://functions.wolfram.com/ElementaryFunctions/ArcTan
"""
args: tTuple[Expr]
_singularities = (S.ImaginaryUnit, -S.ImaginaryUnit)
def fdiff(self, argindex=1):
if argindex == 1:
return 1/(1 + self.args[0]**2)
else:
raise ArgumentIndexError(self, argindex)
def _eval_is_rational(self):
s = self.func(*self.args)
if s.func == self.func:
if s.args[0].is_rational:
return False
else:
return s.is_rational
def _eval_is_positive(self):
return self.args[0].is_extended_positive
def _eval_is_nonnegative(self):
return self.args[0].is_extended_nonnegative
def _eval_is_zero(self):
return self.args[0].is_zero
def _eval_is_real(self):
return self.args[0].is_extended_real
@classmethod
def eval(cls, arg):
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return pi/2
elif arg is S.NegativeInfinity:
return -pi/2
elif arg.is_zero:
return S.Zero
elif arg is S.One:
return pi/4
elif arg is S.NegativeOne:
return -pi/4
if arg is S.ComplexInfinity:
from sympy.calculus.accumulationbounds import AccumBounds
return AccumBounds(-pi/2, pi/2)
if arg.could_extract_minus_sign():
return -cls(-arg)
if arg.is_number:
atan_table = cls._atan_table()
if arg in atan_table:
return atan_table[arg]
i_coeff = _imaginary_unit_as_coefficient(arg)
if i_coeff is not None:
from sympy.functions.elementary.hyperbolic import atanh
return S.ImaginaryUnit*atanh(i_coeff)
if arg.is_zero:
return S.Zero
if isinstance(arg, tan):
ang = arg.args[0]
if ang.is_comparable:
ang %= pi # restrict to [0,pi)
if ang > pi/2: # restrict to [-pi/2,pi/2]
ang -= pi
return ang
if isinstance(arg, cot): # atan(x) + acot(x) = pi/2
ang = arg.args[0]
if ang.is_comparable:
ang = pi/2 - acot(arg)
if ang > pi/2: # restrict to [-pi/2,pi/2]
ang -= pi
return ang
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
return S.NegativeOne**((n - 1)//2)*x**n/n
def _eval_as_leading_term(self, x, logx=None, cdir=0): # atan
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
if x0.is_zero:
return arg.as_leading_term(x)
# Handling branch points
if x0 in (-S.ImaginaryUnit, S.ImaginaryUnit, S.ComplexInfinity):
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand()
# Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo)
if (1 + x0**2).is_negative:
ndir = arg.dir(x, cdir if cdir else 1)
if re(ndir).is_negative:
if im(x0).is_positive:
return self.func(x0) - pi
elif re(ndir).is_positive:
if im(x0).is_negative:
return self.func(x0) + pi
else:
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand()
return self.func(x0)
def _eval_nseries(self, x, n, logx, cdir=0): # atan
arg0 = self.args[0].subs(x, 0)
# Handling branch points
if arg0 in (S.ImaginaryUnit, S.NegativeOne*S.ImaginaryUnit):
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
res = Function._eval_nseries(self, x, n=n, logx=logx)
ndir = self.args[0].dir(x, cdir if cdir else 1)
if arg0 is S.ComplexInfinity:
if re(ndir) > 0:
return res - pi
return res
# Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo)
if (1 + arg0**2).is_negative:
if re(ndir).is_negative:
if im(arg0).is_positive:
return res - pi
elif re(ndir).is_positive:
if im(arg0).is_negative:
return res + pi
else:
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
return res
def _eval_rewrite_as_log(self, x, **kwargs):
return S.ImaginaryUnit/2*(log(S.One - S.ImaginaryUnit*x)
- log(S.One + S.ImaginaryUnit*x))
_eval_rewrite_as_tractable = _eval_rewrite_as_log
def _eval_aseries(self, n, args0, x, logx):
if args0[0] is S.Infinity:
return (pi/2 - atan(1/self.args[0]))._eval_nseries(x, n, logx)
elif args0[0] is S.NegativeInfinity:
return (-pi/2 - atan(1/self.args[0]))._eval_nseries(x, n, logx)
else:
return super()._eval_aseries(n, args0, x, logx)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return tan
def _eval_rewrite_as_asin(self, arg, **kwargs):
return sqrt(arg**2)/arg*(pi/2 - asin(1/sqrt(1 + arg**2)))
def _eval_rewrite_as_acos(self, arg, **kwargs):
return sqrt(arg**2)/arg*acos(1/sqrt(1 + arg**2))
def _eval_rewrite_as_acot(self, arg, **kwargs):
return acot(1/arg)
def _eval_rewrite_as_asec(self, arg, **kwargs):
return sqrt(arg**2)/arg*asec(sqrt(1 + arg**2))
def _eval_rewrite_as_acsc(self, arg, **kwargs):
return sqrt(arg**2)/arg*(pi/2 - acsc(sqrt(1 + arg**2)))
class acot(InverseTrigonometricFunction):
r"""
The inverse cotangent function.
Returns the arc cotangent of x (measured in radians).
Explanation
===========
``acot(x)`` will evaluate automatically in the cases
$x \in \{\infty, -\infty, \tilde{\infty}, 0, 1, -1\}$
and for some instances when the result is a rational multiple of $\pi$
(see the eval class method).
A purely imaginary argument will lead to an ``acoth`` expression.
``acot(x)`` has a branch cut along $(-i, i)$, hence it is discontinuous
at 0. Its range for real $x$ is $(-\frac{\pi}{2}, \frac{\pi}{2}]$.
Examples
========
>>> from sympy import acot, sqrt
>>> acot(0)
pi/2
>>> acot(1)
pi/4
>>> acot(sqrt(3) - 2)
-5*pi/12
See Also
========
sin, csc, cos, sec, tan, cot
asin, acsc, acos, asec, atan, atan2
References
==========
.. [1] http://dlmf.nist.gov/4.23
.. [2] http://functions.wolfram.com/ElementaryFunctions/ArcCot
"""
_singularities = (S.ImaginaryUnit, -S.ImaginaryUnit)
def fdiff(self, argindex=1):
if argindex == 1:
return -1/(1 + self.args[0]**2)
else:
raise ArgumentIndexError(self, argindex)
def _eval_is_rational(self):
s = self.func(*self.args)
if s.func == self.func:
if s.args[0].is_rational:
return False
else:
return s.is_rational
def _eval_is_positive(self):
return self.args[0].is_nonnegative
def _eval_is_negative(self):
return self.args[0].is_negative
def _eval_is_extended_real(self):
return self.args[0].is_extended_real
@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 S.NegativeInfinity:
return S.Zero
elif arg.is_zero:
return pi/ 2
elif arg is S.One:
return pi/4
elif arg is S.NegativeOne:
return -pi/4
if arg is S.ComplexInfinity:
return S.Zero
if arg.could_extract_minus_sign():
return -cls(-arg)
if arg.is_number:
atan_table = cls._atan_table()
if arg in atan_table:
ang = pi/2 - atan_table[arg]
if ang > pi/2: # restrict to (-pi/2,pi/2]
ang -= pi
return ang
i_coeff = _imaginary_unit_as_coefficient(arg)
if i_coeff is not None:
from sympy.functions.elementary.hyperbolic import acoth
return -S.ImaginaryUnit*acoth(i_coeff)
if arg.is_zero:
return pi*S.Half
if isinstance(arg, cot):
ang = arg.args[0]
if ang.is_comparable:
ang %= pi # restrict to [0,pi)
if ang > pi/2: # restrict to (-pi/2,pi/2]
ang -= pi;
return ang
if isinstance(arg, tan): # atan(x) + acot(x) = pi/2
ang = arg.args[0]
if ang.is_comparable:
ang = pi/2 - atan(arg)
if ang > pi/2: # restrict to (-pi/2,pi/2]
ang -= pi
return ang
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n == 0:
return pi/2 # FIX THIS
elif n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
return S.NegativeOne**((n + 1)//2)*x**n/n
def _eval_as_leading_term(self, x, logx=None, cdir=0): # acot
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
if x0 is S.ComplexInfinity:
return (1/arg).as_leading_term(x)
# Handling branch points
if x0 in (-S.ImaginaryUnit, S.ImaginaryUnit, S.Zero):
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand()
# Handling points lying on branch cuts [-I, I]
if x0.is_imaginary and (1 + x0**2).is_positive:
ndir = arg.dir(x, cdir if cdir else 1)
if re(ndir).is_positive:
if im(x0).is_positive:
return self.func(x0) + pi
elif re(ndir).is_negative:
if im(x0).is_negative:
return self.func(x0) - pi
else:
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand()
return self.func(x0)
def _eval_nseries(self, x, n, logx, cdir=0): # acot
arg0 = self.args[0].subs(x, 0)
# Handling branch points
if arg0 in (S.ImaginaryUnit, S.NegativeOne*S.ImaginaryUnit):
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
res = Function._eval_nseries(self, x, n=n, logx=logx)
if arg0 is S.ComplexInfinity:
return res
ndir = self.args[0].dir(x, cdir if cdir else 1)
if arg0.is_zero:
if re(ndir) < 0:
return res - pi
return res
# Handling points lying on branch cuts [-I, I]
if arg0.is_imaginary and (1 + arg0**2).is_positive:
if re(ndir).is_positive:
if im(arg0).is_positive:
return res + pi
elif re(ndir).is_negative:
if im(arg0).is_negative:
return res - pi
else:
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
return res
def _eval_aseries(self, n, args0, x, logx):
if args0[0] is S.Infinity:
return (pi/2 - acot(1/self.args[0]))._eval_nseries(x, n, logx)
elif args0[0] is S.NegativeInfinity:
return (pi*Rational(3, 2) - acot(1/self.args[0]))._eval_nseries(x, n, logx)
else:
return super(atan, self)._eval_aseries(n, args0, x, logx)
def _eval_rewrite_as_log(self, x, **kwargs):
return S.ImaginaryUnit/2*(log(1 - S.ImaginaryUnit/x)
- log(1 + S.ImaginaryUnit/x))
_eval_rewrite_as_tractable = _eval_rewrite_as_log
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return cot
def _eval_rewrite_as_asin(self, arg, **kwargs):
return (arg*sqrt(1/arg**2)*
(pi/2 - asin(sqrt(-arg**2)/sqrt(-arg**2 - 1))))
def _eval_rewrite_as_acos(self, arg, **kwargs):
return arg*sqrt(1/arg**2)*acos(sqrt(-arg**2)/sqrt(-arg**2 - 1))
def _eval_rewrite_as_atan(self, arg, **kwargs):
return atan(1/arg)
def _eval_rewrite_as_asec(self, arg, **kwargs):
return arg*sqrt(1/arg**2)*asec(sqrt((1 + arg**2)/arg**2))
def _eval_rewrite_as_acsc(self, arg, **kwargs):
return arg*sqrt(1/arg**2)*(pi/2 - acsc(sqrt((1 + arg**2)/arg**2)))
class asec(InverseTrigonometricFunction):
r"""
The inverse secant function.
Returns the arc secant of x (measured in radians).
Explanation
===========
``asec(x)`` will evaluate automatically in the cases
$x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when the
result is a rational multiple of $\pi$ (see the eval class method).
``asec(x)`` has branch cut in the interval $[-1, 1]$. For complex arguments,
it can be defined [4]_ as
.. math::
\operatorname{sec^{-1}}(z) = -i\frac{\log\left(\sqrt{1 - z^2} + 1\right)}{z}
At ``x = 0``, for positive branch cut, the limit evaluates to ``zoo``. For
negative branch cut, the limit
.. math::
\lim_{z \to 0}-i\frac{\log\left(-\sqrt{1 - z^2} + 1\right)}{z}
simplifies to :math:`-i\log\left(z/2 + O\left(z^3\right)\right)` which
ultimately evaluates to ``zoo``.
As ``acos(x) = asec(1/x)``, a similar argument can be given for
``acos(x)``.
Examples
========
>>> from sympy import asec, oo
>>> asec(1)
0
>>> asec(-1)
pi
>>> asec(0)
zoo
>>> asec(-oo)
pi/2
See Also
========
sin, csc, cos, sec, tan, cot
asin, acsc, acos, atan, acot, atan2
References
==========
.. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
.. [2] http://dlmf.nist.gov/4.23
.. [3] http://functions.wolfram.com/ElementaryFunctions/ArcSec
.. [4] http://reference.wolfram.com/language/ref/ArcSec.html
"""
@classmethod
def eval(cls, arg):
if arg.is_zero:
return S.ComplexInfinity
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.One:
return S.Zero
elif arg is S.NegativeOne:
return pi
if arg in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
return pi/2
if arg.is_number:
acsc_table = cls._acsc_table()
if arg in acsc_table:
return pi/2 - acsc_table[arg]
elif -arg in acsc_table:
return pi/2 + acsc_table[-arg]
if arg.is_infinite:
return pi/2
if isinstance(arg, sec):
ang = arg.args[0]
if ang.is_comparable:
ang %= 2*pi # restrict to [0,2*pi)
if ang > pi: # restrict to [0,pi]
ang = 2*pi - ang
return ang
if isinstance(arg, csc): # asec(x) + acsc(x) = pi/2
ang = arg.args[0]
if ang.is_comparable:
return pi/2 - acsc(arg)
def fdiff(self, argindex=1):
if argindex == 1:
return 1/(self.args[0]**2*sqrt(1 - 1/self.args[0]**2))
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return sec
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n == 0:
return S.ImaginaryUnit*log(2 / x)
elif n < 0 or n % 2 == 1:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 2 and n > 2:
p = previous_terms[-2]
return p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2)
else:
k = n // 2
R = RisingFactorial(S.Half, k) * n
F = factorial(k) * n // 2 * n // 2
return -S.ImaginaryUnit * R / F * x**n / 4
def _eval_as_leading_term(self, x, logx=None, cdir=0): # asec
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
# Handling branch points
if x0 == 1:
return sqrt(2)*sqrt((arg - S.One).as_leading_term(x))
if x0 in (-S.One, S.Zero):
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
# Handling points lying on branch cuts (-1, 1)
if x0.is_real and (1 - x0**2).is_positive:
ndir = arg.dir(x, cdir if cdir else 1)
if im(ndir).is_negative:
if x0.is_positive:
return -self.func(x0)
elif im(ndir).is_positive:
if x0.is_negative:
return 2*pi - self.func(x0)
else:
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand()
return self.func(x0)
def _eval_nseries(self, x, n, logx, cdir=0): # asec
from sympy.series.order import O
arg0 = self.args[0].subs(x, 0)
# Handling branch points
if arg0 is S.One:
t = Dummy('t', positive=True)
ser = asec(S.One + t**2).rewrite(log).nseries(t, 0, 2*n)
arg1 = S.NegativeOne + self.args[0]
f = arg1.as_leading_term(x)
g = (arg1 - f)/ f
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
res = (res1.removeO()*sqrt(f)).expand()
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
if arg0 is S.NegativeOne:
t = Dummy('t', positive=True)
ser = asec(S.NegativeOne - t**2).rewrite(log).nseries(t, 0, 2*n)
arg1 = S.NegativeOne - self.args[0]
f = arg1.as_leading_term(x)
g = (arg1 - f)/ f
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
res = (res1.removeO()*sqrt(f)).expand()
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
res = Function._eval_nseries(self, x, n=n, logx=logx)
if arg0 is S.ComplexInfinity:
return res
# Handling points lying on branch cuts (-1, 1)
if arg0.is_real and (1 - arg0**2).is_positive:
ndir = self.args[0].dir(x, cdir if cdir else 1)
if im(ndir).is_negative:
if arg0.is_positive:
return -res
elif im(ndir).is_positive:
if arg0.is_negative:
return 2*pi - res
else:
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
return res
def _eval_is_extended_real(self):
x = self.args[0]
if x.is_extended_real is False:
return False
return fuzzy_or(((x - 1).is_nonnegative, (-x - 1).is_nonnegative))
def _eval_rewrite_as_log(self, arg, **kwargs):
return pi/2 + S.ImaginaryUnit*log(S.ImaginaryUnit/arg + sqrt(1 - 1/arg**2))
_eval_rewrite_as_tractable = _eval_rewrite_as_log
def _eval_rewrite_as_asin(self, arg, **kwargs):
return pi/2 - asin(1/arg)
def _eval_rewrite_as_acos(self, arg, **kwargs):
return acos(1/arg)
def _eval_rewrite_as_atan(self, x, **kwargs):
sx2x = sqrt(x**2)/x
return pi/2*(1 - sx2x) + sx2x*atan(sqrt(x**2 - 1))
def _eval_rewrite_as_acot(self, x, **kwargs):
sx2x = sqrt(x**2)/x
return pi/2*(1 - sx2x) + sx2x*acot(1/sqrt(x**2 - 1))
def _eval_rewrite_as_acsc(self, arg, **kwargs):
return pi/2 - acsc(arg)
class acsc(InverseTrigonometricFunction):
r"""
The inverse cosecant function.
Returns the arc cosecant of x (measured in radians).
Explanation
===========
``acsc(x)`` will evaluate automatically in the cases
$x \in \{\infty, -\infty, 0, 1, -1\}$` and for some instances when the
result is a rational multiple of $\pi$ (see the ``eval`` class method).
Examples
========
>>> from sympy import acsc, oo
>>> acsc(1)
pi/2
>>> acsc(-1)
-pi/2
>>> acsc(oo)
0
>>> acsc(-oo) == acsc(oo)
True
>>> acsc(0)
zoo
See Also
========
sin, csc, cos, sec, tan, cot
asin, acos, asec, atan, acot, atan2
References
==========
.. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
.. [2] http://dlmf.nist.gov/4.23
.. [3] http://functions.wolfram.com/ElementaryFunctions/ArcCsc
"""
@classmethod
def eval(cls, arg):
if arg.is_zero:
return S.ComplexInfinity
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.One:
return pi/2
elif arg is S.NegativeOne:
return -pi/2
if arg in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
return S.Zero
if arg.could_extract_minus_sign():
return -cls(-arg)
if arg.is_infinite:
return S.Zero
if arg.is_number:
acsc_table = cls._acsc_table()
if arg in acsc_table:
return acsc_table[arg]
if isinstance(arg, csc):
ang = arg.args[0]
if ang.is_comparable:
ang %= 2*pi # restrict to [0,2*pi)
if ang > pi: # restrict to (-pi,pi]
ang = pi - ang
# restrict to [-pi/2,pi/2]
if ang > pi/2:
ang = pi - ang
if ang < -pi/2:
ang = -pi - ang
return ang
if isinstance(arg, sec): # asec(x) + acsc(x) = pi/2
ang = arg.args[0]
if ang.is_comparable:
return pi/2 - asec(arg)
def fdiff(self, argindex=1):
if argindex == 1:
return -1/(self.args[0]**2*sqrt(1 - 1/self.args[0]**2))
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return csc
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n == 0:
return pi/2 - S.ImaginaryUnit*log(2) + S.ImaginaryUnit*log(x)
elif n < 0 or n % 2 == 1:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 2 and n > 2:
p = previous_terms[-2]
return p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2)
else:
k = n // 2
R = RisingFactorial(S.Half, k) * n
F = factorial(k) * n // 2 * n // 2
return S.ImaginaryUnit * R / F * x**n / 4
def _eval_as_leading_term(self, x, logx=None, cdir=0): # acsc
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
# Handling branch points
if x0 in (-S.One, S.One, S.Zero):
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand()
if x0 is S.ComplexInfinity:
return (1/arg).as_leading_term(x)
# Handling points lying on branch cuts (-1, 1)
if x0.is_real and (1 - x0**2).is_positive:
ndir = arg.dir(x, cdir if cdir else 1)
if im(ndir).is_negative:
if x0.is_positive:
return pi - self.func(x0)
elif im(ndir).is_positive:
if x0.is_negative:
return -pi - self.func(x0)
else:
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand()
return self.func(x0)
def _eval_nseries(self, x, n, logx, cdir=0): # acsc
from sympy.series.order import O
arg0 = self.args[0].subs(x, 0)
# Handling branch points
if arg0 is S.One:
t = Dummy('t', positive=True)
ser = acsc(S.One + t**2).rewrite(log).nseries(t, 0, 2*n)
arg1 = S.NegativeOne + self.args[0]
f = arg1.as_leading_term(x)
g = (arg1 - f)/ f
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
res = (res1.removeO()*sqrt(f)).expand()
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
if arg0 is S.NegativeOne:
t = Dummy('t', positive=True)
ser = acsc(S.NegativeOne - t**2).rewrite(log).nseries(t, 0, 2*n)
arg1 = S.NegativeOne - self.args[0]
f = arg1.as_leading_term(x)
g = (arg1 - f)/ f
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
res = (res1.removeO()*sqrt(f)).expand()
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
res = Function._eval_nseries(self, x, n=n, logx=logx)
if arg0 is S.ComplexInfinity:
return res
# Handling points lying on branch cuts (-1, 1)
if arg0.is_real and (1 - arg0**2).is_positive:
ndir = self.args[0].dir(x, cdir if cdir else 1)
if im(ndir).is_negative:
if arg0.is_positive:
return pi - res
elif im(ndir).is_positive:
if arg0.is_negative:
return -pi - res
else:
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
return res
def _eval_rewrite_as_log(self, arg, **kwargs):
return -S.ImaginaryUnit*log(S.ImaginaryUnit/arg + sqrt(1 - 1/arg**2))
_eval_rewrite_as_tractable = _eval_rewrite_as_log
def _eval_rewrite_as_asin(self, arg, **kwargs):
return asin(1/arg)
def _eval_rewrite_as_acos(self, arg, **kwargs):
return pi/2 - acos(1/arg)
def _eval_rewrite_as_atan(self, x, **kwargs):
return sqrt(x**2)/x*(pi/2 - atan(sqrt(x**2 - 1)))
def _eval_rewrite_as_acot(self, arg, **kwargs):
return sqrt(arg**2)/arg*(pi/2 - acot(1/sqrt(arg**2 - 1)))
def _eval_rewrite_as_asec(self, arg, **kwargs):
return pi/2 - asec(arg)
class atan2(InverseTrigonometricFunction):
r"""
The function ``atan2(y, x)`` computes `\operatorname{atan}(y/x)` taking
two arguments `y` and `x`. Signs of both `y` and `x` are considered to
determine the appropriate quadrant of `\operatorname{atan}(y/x)`.
The range is `(-\pi, \pi]`. The complete definition reads as follows:
.. math::
\operatorname{atan2}(y, x) =
\begin{cases}
\arctan\left(\frac y x\right) & \qquad x > 0 \\
\arctan\left(\frac y x\right) + \pi& \qquad y \ge 0, x < 0 \\
\arctan\left(\frac y x\right) - \pi& \qquad y < 0, x < 0 \\
+\frac{\pi}{2} & \qquad y > 0, x = 0 \\
-\frac{\pi}{2} & \qquad y < 0, x = 0 \\
\text{undefined} & \qquad y = 0, x = 0
\end{cases}
Attention: Note the role reversal of both arguments. The `y`-coordinate
is the first argument and the `x`-coordinate the second.
If either `x` or `y` is complex:
.. math::
\operatorname{atan2}(y, x) =
-i\log\left(\frac{x + iy}{\sqrt{x^2 + y^2}}\right)
Examples
========
Going counter-clock wise around the origin we find the
following angles:
>>> from sympy import atan2
>>> atan2(0, 1)
0
>>> atan2(1, 1)
pi/4
>>> atan2(1, 0)
pi/2
>>> atan2(1, -1)
3*pi/4
>>> atan2(0, -1)
pi
>>> atan2(-1, -1)
-3*pi/4
>>> atan2(-1, 0)
-pi/2
>>> atan2(-1, 1)
-pi/4
which are all correct. Compare this to the results of the ordinary
`\operatorname{atan}` function for the point `(x, y) = (-1, 1)`
>>> from sympy import atan, S
>>> atan(S(1)/-1)
-pi/4
>>> atan2(1, -1)
3*pi/4
where only the `\operatorname{atan2}` function reurns what we expect.
We can differentiate the function with respect to both arguments:
>>> from sympy import diff
>>> from sympy.abc import x, y
>>> diff(atan2(y, x), x)
-y/(x**2 + y**2)
>>> diff(atan2(y, x), y)
x/(x**2 + y**2)
We can express the `\operatorname{atan2}` function in terms of
complex logarithms:
>>> from sympy import log
>>> atan2(y, x).rewrite(log)
-I*log((x + I*y)/sqrt(x**2 + y**2))
and in terms of `\operatorname(atan)`:
>>> from sympy import atan
>>> atan2(y, x).rewrite(atan)
Piecewise((2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)), (pi, re(x) < 0), (0, Ne(x, 0)), (nan, True))
but note that this form is undefined on the negative real axis.
See Also
========
sin, csc, cos, sec, tan, cot
asin, acsc, acos, asec, atan, acot
References
==========
.. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
.. [2] https://en.wikipedia.org/wiki/Atan2
.. [3] http://functions.wolfram.com/ElementaryFunctions/ArcTan2
"""
@classmethod
def eval(cls, y, x):
from sympy.functions.special.delta_functions import Heaviside
if x is S.NegativeInfinity:
if y.is_zero:
# Special case y = 0 because we define Heaviside(0) = 1/2
return pi
return 2*pi*(Heaviside(re(y))) - pi
elif x is S.Infinity:
return S.Zero
elif x.is_imaginary and y.is_imaginary and x.is_number and y.is_number:
x = im(x)
y = im(y)
if x.is_extended_real and y.is_extended_real:
if x.is_positive:
return atan(y/x)
elif x.is_negative:
if y.is_negative:
return atan(y/x) - pi
elif y.is_nonnegative:
return atan(y/x) + pi
elif x.is_zero:
if y.is_positive:
return pi/2
elif y.is_negative:
return -pi/2
elif y.is_zero:
return S.NaN
if y.is_zero:
if x.is_extended_nonzero:
return pi*(S.One - Heaviside(x))
if x.is_number:
return Piecewise((pi, re(x) < 0),
(0, Ne(x, 0)),
(S.NaN, True))
if x.is_number and y.is_number:
return -S.ImaginaryUnit*log(
(x + S.ImaginaryUnit*y)/sqrt(x**2 + y**2))
def _eval_rewrite_as_log(self, y, x, **kwargs):
return -S.ImaginaryUnit*log((x + S.ImaginaryUnit*y)/sqrt(x**2 + y**2))
def _eval_rewrite_as_atan(self, y, x, **kwargs):
return Piecewise((2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)),
(pi, re(x) < 0),
(0, Ne(x, 0)),
(S.NaN, True))
def _eval_rewrite_as_arg(self, y, x, **kwargs):
if x.is_extended_real and y.is_extended_real:
return arg_f(x + y*S.ImaginaryUnit)
n = x + S.ImaginaryUnit*y
d = x**2 + y**2
return arg_f(n/sqrt(d)) - S.ImaginaryUnit*log(abs(n)/sqrt(abs(d)))
def _eval_is_extended_real(self):
return self.args[0].is_extended_real and self.args[1].is_extended_real
def _eval_conjugate(self):
return self.func(self.args[0].conjugate(), self.args[1].conjugate())
def fdiff(self, argindex):
y, x = self.args
if argindex == 1:
# Diff wrt y
return x/(x**2 + y**2)
elif argindex == 2:
# Diff wrt x
return -y/(x**2 + y**2)
else:
raise ArgumentIndexError(self, argindex)
def _eval_evalf(self, prec):
y, x = self.args
if x.is_extended_real and y.is_extended_real:
return super()._eval_evalf(prec)
|
b99a1f7dd21435735fcdc6de618fbcf1f4dd90faafd96aeeef8db3bbde34a9d4 | from sympy.core import Function, S, sympify, NumberKind
from sympy.utilities.iterables import sift
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.operations import LatticeOp, ShortCircuit
from sympy.core.function import (Application, Lambda,
ArgumentIndexError)
from sympy.core.expr import Expr
from sympy.core.exprtools import factor_terms
from sympy.core.mod import Mod
from sympy.core.mul import Mul
from sympy.core.numbers import Rational
from sympy.core.power import Pow
from sympy.core.relational import Eq, Relational
from sympy.core.singleton import Singleton
from sympy.core.sorting import ordered
from sympy.core.symbol import Dummy
from sympy.core.rules import Transform
from sympy.core.logic import fuzzy_and, fuzzy_or, _torf
from sympy.core.traversal import walk
from sympy.core.numbers import Integer
from sympy.logic.boolalg import And, Or
def _minmax_as_Piecewise(op, *args):
# helper for Min/Max rewrite as Piecewise
from sympy.functions.elementary.piecewise import Piecewise
ec = []
for i, a in enumerate(args):
c = [Relational(a, args[j], op) for j in range(i + 1, len(args))]
ec.append((a, And(*c)))
return Piecewise(*ec)
class IdentityFunction(Lambda, metaclass=Singleton):
"""
The identity function
Examples
========
>>> from sympy import Id, Symbol
>>> x = Symbol('x')
>>> Id(x)
x
"""
_symbol = Dummy('x')
@property
def signature(self):
return Tuple(self._symbol)
@property
def expr(self):
return self._symbol
Id = S.IdentityFunction
###############################################################################
############################# ROOT and SQUARE ROOT FUNCTION ###################
###############################################################################
def sqrt(arg, evaluate=None):
"""Returns the principal square root.
Parameters
==========
evaluate : bool, optional
The parameter determines if the expression should be evaluated.
If ``None``, its value is taken from
``global_parameters.evaluate``.
Examples
========
>>> from sympy import sqrt, Symbol, S
>>> x = Symbol('x')
>>> sqrt(x)
sqrt(x)
>>> sqrt(x)**2
x
Note that sqrt(x**2) does not simplify to x.
>>> sqrt(x**2)
sqrt(x**2)
This is because the two are not equal to each other in general.
For example, consider x == -1:
>>> from sympy import Eq
>>> Eq(sqrt(x**2), x).subs(x, -1)
False
This is because sqrt computes the principal square root, so the square may
put the argument in a different branch. This identity does hold if x is
positive:
>>> y = Symbol('y', positive=True)
>>> sqrt(y**2)
y
You can force this simplification by using the powdenest() function with
the force option set to True:
>>> from sympy import powdenest
>>> sqrt(x**2)
sqrt(x**2)
>>> powdenest(sqrt(x**2), force=True)
x
To get both branches of the square root you can use the rootof function:
>>> from sympy import rootof
>>> [rootof(x**2-3,i) for i in (0,1)]
[-sqrt(3), sqrt(3)]
Although ``sqrt`` is printed, there is no ``sqrt`` function so looking for
``sqrt`` in an expression will fail:
>>> from sympy.utilities.misc import func_name
>>> func_name(sqrt(x))
'Pow'
>>> sqrt(x).has(sqrt)
False
To find ``sqrt`` look for ``Pow`` with an exponent of ``1/2``:
>>> (x + 1/sqrt(x)).find(lambda i: i.is_Pow and abs(i.exp) is S.Half)
{1/sqrt(x)}
See Also
========
sympy.polys.rootoftools.rootof, root, real_root
References
==========
.. [1] https://en.wikipedia.org/wiki/Square_root
.. [2] https://en.wikipedia.org/wiki/Principal_value
"""
# arg = sympify(arg) is handled by Pow
return Pow(arg, S.Half, evaluate=evaluate)
def cbrt(arg, evaluate=None):
"""Returns the principal cube root.
Parameters
==========
evaluate : bool, optional
The parameter determines if the expression should be evaluated.
If ``None``, its value is taken from
``global_parameters.evaluate``.
Examples
========
>>> from sympy import cbrt, Symbol
>>> x = Symbol('x')
>>> cbrt(x)
x**(1/3)
>>> cbrt(x)**3
x
Note that cbrt(x**3) does not simplify to x.
>>> cbrt(x**3)
(x**3)**(1/3)
This is because the two are not equal to each other in general.
For example, consider `x == -1`:
>>> from sympy import Eq
>>> Eq(cbrt(x**3), x).subs(x, -1)
False
This is because cbrt computes the principal cube root, this
identity does hold if `x` is positive:
>>> y = Symbol('y', positive=True)
>>> cbrt(y**3)
y
See Also
========
sympy.polys.rootoftools.rootof, root, real_root
References
==========
.. [1] https://en.wikipedia.org/wiki/Cube_root
.. [2] https://en.wikipedia.org/wiki/Principal_value
"""
return Pow(arg, Rational(1, 3), evaluate=evaluate)
def root(arg, n, k=0, evaluate=None):
r"""Returns the *k*-th *n*-th root of ``arg``.
Parameters
==========
k : int, optional
Should be an integer in $\{0, 1, ..., n-1\}$.
Defaults to the principal root if $0$.
evaluate : bool, optional
The parameter determines if the expression should be evaluated.
If ``None``, its value is taken from
``global_parameters.evaluate``.
Examples
========
>>> from sympy import root, Rational
>>> from sympy.abc import x, n
>>> root(x, 2)
sqrt(x)
>>> root(x, 3)
x**(1/3)
>>> root(x, n)
x**(1/n)
>>> root(x, -Rational(2, 3))
x**(-3/2)
To get the k-th n-th root, specify k:
>>> root(-2, 3, 2)
-(-1)**(2/3)*2**(1/3)
To get all n n-th roots you can use the rootof function.
The following examples show the roots of unity for n
equal 2, 3 and 4:
>>> from sympy import rootof
>>> [rootof(x**2 - 1, i) for i in range(2)]
[-1, 1]
>>> [rootof(x**3 - 1,i) for i in range(3)]
[1, -1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2]
>>> [rootof(x**4 - 1,i) for i in range(4)]
[-1, 1, -I, I]
SymPy, like other symbolic algebra systems, returns the
complex root of negative numbers. This is the principal
root and differs from the text-book result that one might
be expecting. For example, the cube root of -8 does not
come back as -2:
>>> root(-8, 3)
2*(-1)**(1/3)
The real_root function can be used to either make the principal
result real (or simply to return the real root directly):
>>> from sympy import real_root
>>> real_root(_)
-2
>>> real_root(-32, 5)
-2
Alternatively, the n//2-th n-th root of a negative number can be
computed with root:
>>> root(-32, 5, 5//2)
-2
See Also
========
sympy.polys.rootoftools.rootof
sympy.core.power.integer_nthroot
sqrt, real_root
References
==========
.. [1] https://en.wikipedia.org/wiki/Square_root
.. [2] https://en.wikipedia.org/wiki/Real_root
.. [3] https://en.wikipedia.org/wiki/Root_of_unity
.. [4] https://en.wikipedia.org/wiki/Principal_value
.. [5] http://mathworld.wolfram.com/CubeRoot.html
"""
n = sympify(n)
if k:
return Mul(Pow(arg, S.One/n, evaluate=evaluate), S.NegativeOne**(2*k/n), evaluate=evaluate)
return Pow(arg, 1/n, evaluate=evaluate)
def real_root(arg, n=None, evaluate=None):
r"""Return the real *n*'th-root of *arg* if possible.
Parameters
==========
n : int or None, optional
If *n* is ``None``, then all instances of
$(-n)^{1/\text{odd}}$ will be changed to $-n^{1/\text{odd}}$.
This will only create a real root of a principal root.
The presence of other factors may cause the result to not be
real.
evaluate : bool, optional
The parameter determines if the expression should be evaluated.
If ``None``, its value is taken from
``global_parameters.evaluate``.
Examples
========
>>> from sympy import root, real_root
>>> real_root(-8, 3)
-2
>>> root(-8, 3)
2*(-1)**(1/3)
>>> real_root(_)
-2
If one creates a non-principal root and applies real_root, the
result will not be real (so use with caution):
>>> root(-8, 3, 2)
-2*(-1)**(2/3)
>>> real_root(_)
-2*(-1)**(2/3)
See Also
========
sympy.polys.rootoftools.rootof
sympy.core.power.integer_nthroot
root, sqrt
"""
from sympy.functions.elementary.complexes import Abs, im, sign
from sympy.functions.elementary.piecewise import Piecewise
if n is not None:
return Piecewise(
(root(arg, n, evaluate=evaluate), Or(Eq(n, S.One), Eq(n, S.NegativeOne))),
(Mul(sign(arg), root(Abs(arg), n, evaluate=evaluate), evaluate=evaluate),
And(Eq(im(arg), S.Zero), Eq(Mod(n, 2), S.One))),
(root(arg, n, evaluate=evaluate), True))
rv = sympify(arg)
n1pow = Transform(lambda x: -(-x.base)**x.exp,
lambda x:
x.is_Pow and
x.base.is_negative and
x.exp.is_Rational and
x.exp.p == 1 and x.exp.q % 2)
return rv.xreplace(n1pow)
###############################################################################
############################# MINIMUM and MAXIMUM #############################
###############################################################################
class MinMaxBase(Expr, LatticeOp):
def __new__(cls, *args, **assumptions):
from sympy.core.parameters import global_parameters
evaluate = assumptions.pop('evaluate', global_parameters.evaluate)
args = (sympify(arg) for arg in args)
# first standard filter, for cls.zero and cls.identity
# also reshape Max(a, Max(b, c)) to Max(a, b, c)
if evaluate:
try:
args = frozenset(cls._new_args_filter(args))
except ShortCircuit:
return cls.zero
# remove redundant args that are easily identified
args = cls._collapse_arguments(args, **assumptions)
# find local zeros
args = cls._find_localzeros(args, **assumptions)
args = frozenset(args)
if not args:
return cls.identity
if len(args) == 1:
return list(args).pop()
# base creation
obj = Expr.__new__(cls, *ordered(args), **assumptions)
obj._argset = args
return obj
@classmethod
def _collapse_arguments(cls, args, **assumptions):
"""Remove redundant args.
Examples
========
>>> from sympy import Min, Max
>>> from sympy.abc import a, b, c, d, e
Any arg in parent that appears in any
parent-like function in any of the flat args
of parent can be removed from that sub-arg:
>>> Min(a, Max(b, Min(a, c, d)))
Min(a, Max(b, Min(c, d)))
If the arg of parent appears in an opposite-than parent
function in any of the flat args of parent that function
can be replaced with the arg:
>>> Min(a, Max(b, Min(c, d, Max(a, e))))
Min(a, Max(b, Min(a, c, d)))
"""
if not args:
return args
args = list(ordered(args))
if cls == Min:
other = Max
else:
other = Min
# find global comparable max of Max and min of Min if a new
# value is being introduced in these args at position 0 of
# the ordered args
if args[0].is_number:
sifted = mins, maxs = [], []
for i in args:
for v in walk(i, Min, Max):
if v.args[0].is_comparable:
sifted[isinstance(v, Max)].append(v)
small = Min.identity
for i in mins:
v = i.args[0]
if v.is_number and (v < small) == True:
small = v
big = Max.identity
for i in maxs:
v = i.args[0]
if v.is_number and (v > big) == True:
big = v
# at the point when this function is called from __new__,
# there may be more than one numeric arg present since
# local zeros have not been handled yet, so look through
# more than the first arg
if cls == Min:
for arg in args:
if not arg.is_number:
break
if (arg < small) == True:
small = arg
elif cls == Max:
for arg in args:
if not arg.is_number:
break
if (arg > big) == True:
big = arg
T = None
if cls == Min:
if small != Min.identity:
other = Max
T = small
elif big != Max.identity:
other = Min
T = big
if T is not None:
# remove numerical redundancy
for i in range(len(args)):
a = args[i]
if isinstance(a, other):
a0 = a.args[0]
if ((a0 > T) if other == Max else (a0 < T)) == True:
args[i] = cls.identity
# remove redundant symbolic args
def do(ai, a):
if not isinstance(ai, (Min, Max)):
return ai
cond = a in ai.args
if not cond:
return ai.func(*[do(i, a) for i in ai.args],
evaluate=False)
if isinstance(ai, cls):
return ai.func(*[do(i, a) for i in ai.args if i != a],
evaluate=False)
return a
for i, a in enumerate(args):
args[i + 1:] = [do(ai, a) for ai in args[i + 1:]]
# factor out common elements as for
# Min(Max(x, y), Max(x, z)) -> Max(x, Min(y, z))
# and vice versa when swapping Min/Max -- do this only for the
# easy case where all functions contain something in common;
# trying to find some optimal subset of args to modify takes
# too long
def factor_minmax(args):
is_other = lambda arg: isinstance(arg, other)
other_args, remaining_args = sift(args, is_other, binary=True)
if not other_args:
return args
# Min(Max(x, y, z), Max(x, y, u, v)) -> {x,y}, ({z}, {u,v})
arg_sets = [set(arg.args) for arg in other_args]
common = set.intersection(*arg_sets)
if not common:
return args
new_other_args = list(common)
arg_sets_diff = [arg_set - common for arg_set in arg_sets]
# If any set is empty after removing common then all can be
# discarded e.g. Min(Max(a, b, c), Max(a, b)) -> Max(a, b)
if all(arg_sets_diff):
other_args_diff = [other(*s, evaluate=False) for s in arg_sets_diff]
new_other_args.append(cls(*other_args_diff, evaluate=False))
other_args_factored = other(*new_other_args, evaluate=False)
return remaining_args + [other_args_factored]
if len(args) > 1:
args = factor_minmax(args)
return args
@classmethod
def _new_args_filter(cls, arg_sequence):
"""
Generator filtering args.
first standard filter, for cls.zero and cls.identity.
Also reshape ``Max(a, Max(b, c))`` to ``Max(a, b, c)``,
and check arguments for comparability
"""
for arg in arg_sequence:
# pre-filter, checking comparability of arguments
if not isinstance(arg, Expr) or arg.is_extended_real is False or (
arg.is_number and
not arg.is_comparable):
raise ValueError("The argument '%s' is not comparable." % arg)
if arg == cls.zero:
raise ShortCircuit(arg)
elif arg == cls.identity:
continue
elif arg.func == cls:
yield from arg.args
else:
yield arg
@classmethod
def _find_localzeros(cls, values, **options):
"""
Sequentially allocate values to localzeros.
When a value is identified as being more extreme than another member it
replaces that member; if this is never true, then the value is simply
appended to the localzeros.
"""
localzeros = set()
for v in values:
is_newzero = True
localzeros_ = list(localzeros)
for z in localzeros_:
if id(v) == id(z):
is_newzero = False
else:
con = cls._is_connected(v, z)
if con:
is_newzero = False
if con is True or con == cls:
localzeros.remove(z)
localzeros.update([v])
if is_newzero:
localzeros.update([v])
return localzeros
@classmethod
def _is_connected(cls, x, y):
"""
Check if x and y are connected somehow.
"""
for i in range(2):
if x == y:
return True
t, f = Max, Min
for op in "><":
for j in range(2):
try:
if op == ">":
v = x >= y
else:
v = x <= y
except TypeError:
return False # non-real arg
if not v.is_Relational:
return t if v else f
t, f = f, t
x, y = y, x
x, y = y, x # run next pass with reversed order relative to start
# simplification can be expensive, so be conservative
# in what is attempted
x = factor_terms(x - y)
y = S.Zero
return False
def _eval_derivative(self, s):
# f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s)
i = 0
l = []
for a in self.args:
i += 1
da = a.diff(s)
if da.is_zero:
continue
try:
df = self.fdiff(i)
except ArgumentIndexError:
df = Function.fdiff(self, i)
l.append(df * da)
return Add(*l)
def _eval_rewrite_as_Abs(self, *args, **kwargs):
from sympy.functions.elementary.complexes import Abs
s = (args[0] + self.func(*args[1:]))/2
d = abs(args[0] - self.func(*args[1:]))/2
return (s + d if isinstance(self, Max) else s - d).rewrite(Abs)
def evalf(self, n=15, **options):
return self.func(*[a.evalf(n, **options) for a in self.args])
def n(self, *args, **kwargs):
return self.evalf(*args, **kwargs)
_eval_is_algebraic = lambda s: _torf(i.is_algebraic for i in s.args)
_eval_is_antihermitian = lambda s: _torf(i.is_antihermitian for i in s.args)
_eval_is_commutative = lambda s: _torf(i.is_commutative for i in s.args)
_eval_is_complex = lambda s: _torf(i.is_complex for i in s.args)
_eval_is_composite = lambda s: _torf(i.is_composite for i in s.args)
_eval_is_even = lambda s: _torf(i.is_even for i in s.args)
_eval_is_finite = lambda s: _torf(i.is_finite for i in s.args)
_eval_is_hermitian = lambda s: _torf(i.is_hermitian for i in s.args)
_eval_is_imaginary = lambda s: _torf(i.is_imaginary for i in s.args)
_eval_is_infinite = lambda s: _torf(i.is_infinite for i in s.args)
_eval_is_integer = lambda s: _torf(i.is_integer for i in s.args)
_eval_is_irrational = lambda s: _torf(i.is_irrational for i in s.args)
_eval_is_negative = lambda s: _torf(i.is_negative for i in s.args)
_eval_is_noninteger = lambda s: _torf(i.is_noninteger for i in s.args)
_eval_is_nonnegative = lambda s: _torf(i.is_nonnegative for i in s.args)
_eval_is_nonpositive = lambda s: _torf(i.is_nonpositive for i in s.args)
_eval_is_nonzero = lambda s: _torf(i.is_nonzero for i in s.args)
_eval_is_odd = lambda s: _torf(i.is_odd for i in s.args)
_eval_is_polar = lambda s: _torf(i.is_polar for i in s.args)
_eval_is_positive = lambda s: _torf(i.is_positive for i in s.args)
_eval_is_prime = lambda s: _torf(i.is_prime for i in s.args)
_eval_is_rational = lambda s: _torf(i.is_rational for i in s.args)
_eval_is_real = lambda s: _torf(i.is_real for i in s.args)
_eval_is_extended_real = lambda s: _torf(i.is_extended_real for i in s.args)
_eval_is_transcendental = lambda s: _torf(i.is_transcendental for i in s.args)
_eval_is_zero = lambda s: _torf(i.is_zero for i in s.args)
class Max(MinMaxBase, Application):
r"""
Return, if possible, the maximum value of the list.
When number of arguments is equal one, then
return this argument.
When number of arguments is equal two, then
return, if possible, the value from (a, b) that is $\ge$ the other.
In common case, when the length of list greater than 2, the task
is more complicated. Return only the arguments, which are greater
than others, if it is possible to determine directional relation.
If is not possible to determine such a relation, return a partially
evaluated result.
Assumptions are used to make the decision too.
Also, only comparable arguments are permitted.
It is named ``Max`` and not ``max`` to avoid conflicts
with the built-in function ``max``.
Examples
========
>>> from sympy import Max, Symbol, oo
>>> from sympy.abc import x, y, z
>>> p = Symbol('p', positive=True)
>>> n = Symbol('n', negative=True)
>>> Max(x, -2)
Max(-2, x)
>>> Max(x, -2).subs(x, 3)
3
>>> Max(p, -2)
p
>>> Max(x, y)
Max(x, y)
>>> Max(x, y) == Max(y, x)
True
>>> Max(x, Max(y, z))
Max(x, y, z)
>>> Max(n, 8, p, 7, -oo)
Max(8, p)
>>> Max (1, x, oo)
oo
* Algorithm
The task can be considered as searching of supremums in the
directed complete partial orders [1]_.
The source values are sequentially allocated by the isolated subsets
in which supremums are searched and result as Max arguments.
If the resulted supremum is single, then it is returned.
The isolated subsets are the sets of values which are only the comparable
with each other in the current set. E.g. natural numbers are comparable with
each other, but not comparable with the `x` symbol. Another example: the
symbol `x` with negative assumption is comparable with a natural number.
Also there are "least" elements, which are comparable with all others,
and have a zero property (maximum or minimum for all elements).
For example, in case of $\infty$, the allocation operation is terminated
and only this value is returned.
Assumption:
- if $A > B > C$ then $A > C$
- if $A = B$ then $B$ can be removed
References
==========
.. [1] https://en.wikipedia.org/wiki/Directed_complete_partial_order
.. [2] https://en.wikipedia.org/wiki/Lattice_%28order%29
See Also
========
Min : find minimum values
"""
zero = S.Infinity
identity = S.NegativeInfinity
def fdiff( self, argindex ):
from sympy.functions.special.delta_functions import Heaviside
n = len(self.args)
if 0 < argindex and argindex <= n:
argindex -= 1
if n == 2:
return Heaviside(self.args[argindex] - self.args[1 - argindex])
newargs = tuple([self.args[i] for i in range(n) if i != argindex])
return Heaviside(self.args[argindex] - Max(*newargs))
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Heaviside(self, *args, **kwargs):
from sympy.functions.special.delta_functions import Heaviside
return Add(*[j*Mul(*[Heaviside(j - i) for i in args if i!=j]) \
for j in args])
def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
return _minmax_as_Piecewise('>=', *args)
def _eval_is_positive(self):
return fuzzy_or(a.is_positive for a in self.args)
def _eval_is_nonnegative(self):
return fuzzy_or(a.is_nonnegative for a in self.args)
def _eval_is_negative(self):
return fuzzy_and(a.is_negative for a in self.args)
class Min(MinMaxBase, Application):
"""
Return, if possible, the minimum value of the list.
It is named ``Min`` and not ``min`` to avoid conflicts
with the built-in function ``min``.
Examples
========
>>> from sympy import Min, Symbol, oo
>>> from sympy.abc import x, y
>>> p = Symbol('p', positive=True)
>>> n = Symbol('n', negative=True)
>>> Min(x, -2)
Min(-2, x)
>>> Min(x, -2).subs(x, 3)
-2
>>> Min(p, -3)
-3
>>> Min(x, y)
Min(x, y)
>>> Min(n, 8, p, -7, p, oo)
Min(-7, n)
See Also
========
Max : find maximum values
"""
zero = S.NegativeInfinity
identity = S.Infinity
def fdiff( self, argindex ):
from sympy.functions.special.delta_functions import Heaviside
n = len(self.args)
if 0 < argindex and argindex <= n:
argindex -= 1
if n == 2:
return Heaviside( self.args[1-argindex] - self.args[argindex] )
newargs = tuple([ self.args[i] for i in range(n) if i != argindex])
return Heaviside( Min(*newargs) - self.args[argindex] )
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Heaviside(self, *args, **kwargs):
from sympy.functions.special.delta_functions import Heaviside
return Add(*[j*Mul(*[Heaviside(i-j) for i in args if i!=j]) \
for j in args])
def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
return _minmax_as_Piecewise('<=', *args)
def _eval_is_positive(self):
return fuzzy_and(a.is_positive for a in self.args)
def _eval_is_nonnegative(self):
return fuzzy_and(a.is_nonnegative for a in self.args)
def _eval_is_negative(self):
return fuzzy_or(a.is_negative for a in self.args)
class Rem(Function):
"""Returns the remainder when ``p`` is divided by ``q`` where ``p`` is finite
and ``q`` is not equal to zero. The result, ``p - int(p/q)*q``, has the same sign
as the divisor.
Parameters
==========
p : Expr
Dividend.
q : Expr
Divisor.
Notes
=====
``Rem`` corresponds to the ``%`` operator in C.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import Rem
>>> Rem(x**3, y)
Rem(x**3, y)
>>> Rem(x**3, y).subs({x: -5, y: 3})
-2
See Also
========
Mod
"""
kind = NumberKind
@classmethod
def eval(cls, p, q):
"""Return the function remainder if both p, q are numbers and q is not
zero.
"""
if q.is_zero:
raise ZeroDivisionError("Division by zero")
if p is S.NaN or q is S.NaN or p.is_finite is False or q.is_finite is False:
return S.NaN
if p is S.Zero or p in (q, -q) or (p.is_integer and q == 1):
return S.Zero
if q.is_Number:
if p.is_Number:
return p - Integer(p/q)*q
|
a3ccb64d429c9fdbdaade6e1adc65241083e0ceaa324747668fd360a88600c4a | from sympy.core import S, Function, diff, Tuple, Dummy, Mul
from sympy.core.basic import Basic, as_Basic
from sympy.core.numbers import Rational, NumberSymbol, _illegal
from sympy.core.parameters import global_parameters
from sympy.core.relational import (Lt, Gt, Eq, Ne, Relational,
_canonical, _canonical_coeff)
from sympy.core.sorting import ordered
from sympy.functions.elementary.miscellaneous import Max, Min
from sympy.logic.boolalg import (And, Boolean, distribute_and_over_or, Not,
true, false, Or, ITE, simplify_logic, to_cnf, distribute_or_over_and)
from sympy.utilities.iterables import uniq, sift, common_prefix
from sympy.utilities.misc import filldedent, func_name
from itertools import product
Undefined = S.NaN # Piecewise()
class ExprCondPair(Tuple):
"""Represents an expression, condition pair."""
def __new__(cls, expr, cond):
expr = as_Basic(expr)
if cond == True:
return Tuple.__new__(cls, expr, true)
elif cond == False:
return Tuple.__new__(cls, expr, false)
elif isinstance(cond, Basic) and cond.has(Piecewise):
cond = piecewise_fold(cond)
if isinstance(cond, Piecewise):
cond = cond.rewrite(ITE)
if not isinstance(cond, Boolean):
raise TypeError(filldedent('''
Second argument must be a Boolean,
not `%s`''' % func_name(cond)))
return Tuple.__new__(cls, expr, cond)
@property
def expr(self):
"""
Returns the expression of this pair.
"""
return self.args[0]
@property
def cond(self):
"""
Returns the condition of this pair.
"""
return self.args[1]
@property
def is_commutative(self):
return self.expr.is_commutative
def __iter__(self):
yield self.expr
yield self.cond
def _eval_simplify(self, **kwargs):
return self.func(*[a.simplify(**kwargs) for a in self.args])
class Piecewise(Function):
"""
Represents a piecewise function.
Usage:
Piecewise( (expr,cond), (expr,cond), ... )
- Each argument is a 2-tuple defining an expression and condition
- The conds are evaluated in turn returning the first that is True.
If any of the evaluated conds are not explicitly False,
e.g. ``x < 1``, the function is returned in symbolic form.
- If the function is evaluated at a place where all conditions are False,
nan will be returned.
- Pairs where the cond is explicitly False, will be removed and no pair
appearing after a True condition will ever be retained. If a single
pair with a True condition remains, it will be returned, even when
evaluation is False.
Examples
========
>>> from sympy import Piecewise, log, piecewise_fold
>>> from sympy.abc import x, y
>>> f = x**2
>>> g = log(x)
>>> p = Piecewise((0, x < -1), (f, x <= 1), (g, True))
>>> p.subs(x,1)
1
>>> p.subs(x,5)
log(5)
Booleans can contain Piecewise elements:
>>> cond = (x < y).subs(x, Piecewise((2, x < 0), (3, True))); cond
Piecewise((2, x < 0), (3, True)) < y
The folded version of this results in a Piecewise whose
expressions are Booleans:
>>> folded_cond = piecewise_fold(cond); folded_cond
Piecewise((2 < y, x < 0), (3 < y, True))
When a Boolean containing Piecewise (like cond) or a Piecewise
with Boolean expressions (like folded_cond) is used as a condition,
it is converted to an equivalent :class:`~.ITE` object:
>>> Piecewise((1, folded_cond))
Piecewise((1, ITE(x < 0, y > 2, y > 3)))
When a condition is an ``ITE``, it will be converted to a simplified
Boolean expression:
>>> piecewise_fold(_)
Piecewise((1, ((x >= 0) | (y > 2)) & ((y > 3) | (x < 0))))
See Also
========
piecewise_fold
piecewise_exclusive
ITE
"""
nargs = None
is_Piecewise = True
def __new__(cls, *args, **options):
if len(args) == 0:
raise TypeError("At least one (expr, cond) pair expected.")
# (Try to) sympify args first
newargs = []
for ec in args:
# ec could be a ExprCondPair or a tuple
pair = ExprCondPair(*getattr(ec, 'args', ec))
cond = pair.cond
if cond is false:
continue
newargs.append(pair)
if cond is true:
break
eval = options.pop('evaluate', global_parameters.evaluate)
if eval:
r = cls.eval(*newargs)
if r is not None:
return r
elif len(newargs) == 1 and newargs[0].cond == True:
return newargs[0].expr
return Basic.__new__(cls, *newargs, **options)
@classmethod
def eval(cls, *_args):
"""Either return a modified version of the args or, if no
modifications were made, return None.
Modifications that are made here:
1. relationals are made canonical
2. any False conditions are dropped
3. any repeat of a previous condition is ignored
4. any args past one with a true condition are dropped
If there are no args left, nan will be returned.
If there is a single arg with a True condition, its
corresponding expression will be returned.
EXAMPLES
========
>>> from sympy import Piecewise
>>> from sympy.abc import x
>>> cond = -x < -1
>>> args = [(1, cond), (4, cond), (3, False), (2, True), (5, x < 1)]
>>> Piecewise(*args, evaluate=False)
Piecewise((1, -x < -1), (4, -x < -1), (2, True))
>>> Piecewise(*args)
Piecewise((1, x > 1), (2, True))
"""
if not _args:
return Undefined
if len(_args) == 1 and _args[0][-1] == True:
return _args[0][0]
newargs = _piecewise_collapse_arguments(_args)
# some conditions may have been redundant
missing = len(newargs) != len(_args)
# some conditions may have changed
same = all(a == b for a, b in zip(newargs, _args))
# if either change happened we return the expr with the
# updated args
if not newargs:
raise ValueError(filldedent('''
There are no conditions (or none that
are not trivially false) to define an
expression.'''))
if missing or not same:
return cls(*newargs)
def doit(self, **hints):
"""
Evaluate this piecewise function.
"""
newargs = []
for e, c in self.args:
if hints.get('deep', True):
if isinstance(e, Basic):
newe = e.doit(**hints)
if newe != self:
e = newe
if isinstance(c, Basic):
c = c.doit(**hints)
newargs.append((e, c))
return self.func(*newargs)
def _eval_simplify(self, **kwargs):
return piecewise_simplify(self, **kwargs)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
for e, c in self.args:
if c == True or c.subs(x, 0) == True:
return e.as_leading_term(x)
def _eval_adjoint(self):
return self.func(*[(e.adjoint(), c) for e, c in self.args])
def _eval_conjugate(self):
return self.func(*[(e.conjugate(), c) for e, c in self.args])
def _eval_derivative(self, x):
return self.func(*[(diff(e, x), c) for e, c in self.args])
def _eval_evalf(self, prec):
return self.func(*[(e._evalf(prec), c) for e, c in self.args])
def _eval_is_meromorphic(self, x, a):
# Conditions often implicitly assume that the argument is real.
# Hence, there needs to be some check for as_set.
if not a.is_real:
return None
# Then, scan ExprCondPairs in the given order to find a piece that would contain a,
# possibly as a boundary point.
for e, c in self.args:
cond = c.subs(x, a)
if cond.is_Relational:
return None
if a in c.as_set().boundary:
return None
# Apply expression if a is an interior point of the domain of e.
if cond:
return e._eval_is_meromorphic(x, a)
def piecewise_integrate(self, x, **kwargs):
"""Return the Piecewise with each expression being
replaced with its antiderivative. To obtain a continuous
antiderivative, use the :func:`~.integrate` function or method.
Examples
========
>>> from sympy import Piecewise
>>> from sympy.abc import x
>>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
>>> p.piecewise_integrate(x)
Piecewise((0, x < 0), (x, x < 1), (2*x, True))
Note that this does not give a continuous function, e.g.
at x = 1 the 3rd condition applies and the antiderivative
there is 2*x so the value of the antiderivative is 2:
>>> anti = _
>>> anti.subs(x, 1)
2
The continuous derivative accounts for the integral *up to*
the point of interest, however:
>>> p.integrate(x)
Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
>>> _.subs(x, 1)
1
See Also
========
Piecewise._eval_integral
"""
from sympy.integrals import integrate
return self.func(*[(integrate(e, x, **kwargs), c) for e, c in self.args])
def _handle_irel(self, x, handler):
"""Return either None (if the conditions of self depend only on x) else
a Piecewise expression whose expressions (handled by the handler that
was passed) are paired with the governing x-independent relationals,
e.g. Piecewise((A, a(x) & b(y)), (B, c(x) | c(y)) ->
Piecewise(
(handler(Piecewise((A, a(x) & True), (B, c(x) | True)), b(y) & c(y)),
(handler(Piecewise((A, a(x) & True), (B, c(x) | False)), b(y)),
(handler(Piecewise((A, a(x) & False), (B, c(x) | True)), c(y)),
(handler(Piecewise((A, a(x) & False), (B, c(x) | False)), True))
"""
# identify governing relationals
rel = self.atoms(Relational)
irel = list(ordered([r for r in rel if x not in r.free_symbols
and r not in (S.true, S.false)]))
if irel:
args = {}
exprinorder = []
for truth in product((1, 0), repeat=len(irel)):
reps = dict(zip(irel, truth))
# only store the true conditions since the false are implied
# when they appear lower in the Piecewise args
if 1 not in truth:
cond = None # flag this one so it doesn't get combined
else:
andargs = Tuple(*[i for i in reps if reps[i]])
free = list(andargs.free_symbols)
if len(free) == 1:
from sympy.solvers.inequalities import (
reduce_inequalities, _solve_inequality)
try:
t = reduce_inequalities(andargs, free[0])
# ValueError when there are potentially
# nonvanishing imaginary parts
except (ValueError, NotImplementedError):
# at least isolate free symbol on left
t = And(*[_solve_inequality(
a, free[0], linear=True)
for a in andargs])
else:
t = And(*andargs)
if t is S.false:
continue # an impossible combination
cond = t
expr = handler(self.xreplace(reps))
if isinstance(expr, self.func) and len(expr.args) == 1:
expr, econd = expr.args[0]
cond = And(econd, True if cond is None else cond)
# the ec pairs are being collected since all possibilities
# are being enumerated, but don't put the last one in since
# its expr might match a previous expression and it
# must appear last in the args
if cond is not None:
args.setdefault(expr, []).append(cond)
# but since we only store the true conditions we must maintain
# the order so that the expression with the most true values
# comes first
exprinorder.append(expr)
# convert collected conditions as args of Or
for k in args:
args[k] = Or(*args[k])
# take them in the order obtained
args = [(e, args[e]) for e in uniq(exprinorder)]
# add in the last arg
args.append((expr, True))
return Piecewise(*args)
def _eval_integral(self, x, _first=True, **kwargs):
"""Return the indefinite integral of the
Piecewise such that subsequent substitution of x with a
value will give the value of the integral (not including
the constant of integration) up to that point. To only
integrate the individual parts of Piecewise, use the
``piecewise_integrate`` method.
Examples
========
>>> from sympy import Piecewise
>>> from sympy.abc import x
>>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
>>> p.integrate(x)
Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
>>> p.piecewise_integrate(x)
Piecewise((0, x < 0), (x, x < 1), (2*x, True))
See Also
========
Piecewise.piecewise_integrate
"""
from sympy.integrals.integrals import integrate
if _first:
def handler(ipw):
if isinstance(ipw, self.func):
return ipw._eval_integral(x, _first=False, **kwargs)
else:
return ipw.integrate(x, **kwargs)
irv = self._handle_irel(x, handler)
if irv is not None:
return irv
# handle a Piecewise from -oo to oo with and no x-independent relationals
# -----------------------------------------------------------------------
ok, abei = self._intervals(x)
if not ok:
from sympy.integrals.integrals import Integral
return Integral(self, x) # unevaluated
pieces = [(a, b) for a, b, _, _ in abei]
oo = S.Infinity
done = [(-oo, oo, -1)]
for k, p in enumerate(pieces):
if p == (-oo, oo):
# all undone intervals will get this key
for j, (a, b, i) in enumerate(done):
if i == -1:
done[j] = a, b, k
break # nothing else to consider
N = len(done) - 1
for j, (a, b, i) in enumerate(reversed(done)):
if i == -1:
j = N - j
done[j: j + 1] = _clip(p, (a, b), k)
done = [(a, b, i) for a, b, i in done if a != b]
# append an arg if there is a hole so a reference to
# argument -1 will give Undefined
if any(i == -1 for (a, b, i) in done):
abei.append((-oo, oo, Undefined, -1))
# return the sum of the intervals
args = []
sum = None
for a, b, i in done:
anti = integrate(abei[i][-2], x, **kwargs)
if sum is None:
sum = anti
else:
sum = sum.subs(x, a)
e = anti._eval_interval(x, a, x)
if sum.has(*_illegal) or e.has(*_illegal):
sum = anti
else:
sum += e
# see if we know whether b is contained in original
# condition
if b is S.Infinity:
cond = True
elif self.args[abei[i][-1]].cond.subs(x, b) == False:
cond = (x < b)
else:
cond = (x <= b)
args.append((sum, cond))
return Piecewise(*args)
def _eval_interval(self, sym, a, b, _first=True):
"""Evaluates the function along the sym in a given interval [a, b]"""
# FIXME: Currently complex intervals are not supported. A possible
# replacement algorithm, discussed in issue 5227, can be found in the
# following papers;
# http://portal.acm.org/citation.cfm?id=281649
# http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.70.4127&rep=rep1&type=pdf
if a is None or b is None:
# In this case, it is just simple substitution
return super()._eval_interval(sym, a, b)
else:
x, lo, hi = map(as_Basic, (sym, a, b))
if _first: # get only x-dependent relationals
def handler(ipw):
if isinstance(ipw, self.func):
return ipw._eval_interval(x, lo, hi, _first=None)
else:
return ipw._eval_interval(x, lo, hi)
irv = self._handle_irel(x, handler)
if irv is not None:
return irv
if (lo < hi) is S.false or (
lo is S.Infinity or hi is S.NegativeInfinity):
rv = self._eval_interval(x, hi, lo, _first=False)
if isinstance(rv, Piecewise):
rv = Piecewise(*[(-e, c) for e, c in rv.args])
else:
rv = -rv
return rv
if (lo < hi) is S.true or (
hi is S.Infinity or lo is S.NegativeInfinity):
pass
else:
_a = Dummy('lo')
_b = Dummy('hi')
a = lo if lo.is_comparable else _a
b = hi if hi.is_comparable else _b
pos = self._eval_interval(x, a, b, _first=False)
if a == _a and b == _b:
# it's purely symbolic so just swap lo and hi and
# change the sign to get the value for when lo > hi
neg, pos = (-pos.xreplace({_a: hi, _b: lo}),
pos.xreplace({_a: lo, _b: hi}))
else:
# at least one of the bounds was comparable, so allow
# _eval_interval to use that information when computing
# the interval with lo and hi reversed
neg, pos = (-self._eval_interval(x, hi, lo, _first=False),
pos.xreplace({_a: lo, _b: hi}))
# allow simplification based on ordering of lo and hi
p = Dummy('', positive=True)
if lo.is_Symbol:
pos = pos.xreplace({lo: hi - p}).xreplace({p: hi - lo})
neg = neg.xreplace({lo: hi + p}).xreplace({p: lo - hi})
elif hi.is_Symbol:
pos = pos.xreplace({hi: lo + p}).xreplace({p: hi - lo})
neg = neg.xreplace({hi: lo - p}).xreplace({p: lo - hi})
# evaluate limits that may have unevaluate Min/Max
touch = lambda _: _.replace(
lambda x: isinstance(x, (Min, Max)),
lambda x: x.func(*x.args))
neg = touch(neg)
pos = touch(pos)
# assemble return expression; make the first condition be Lt
# b/c then the first expression will look the same whether
# the lo or hi limit is symbolic
if a == _a: # the lower limit was symbolic
rv = Piecewise(
(pos,
lo < hi),
(neg,
True))
else:
rv = Piecewise(
(neg,
hi < lo),
(pos,
True))
if rv == Undefined:
raise ValueError("Can't integrate across undefined region.")
if any(isinstance(i, Piecewise) for i in (pos, neg)):
rv = piecewise_fold(rv)
return rv
# handle a Piecewise with lo <= hi and no x-independent relationals
# -----------------------------------------------------------------
ok, abei = self._intervals(x)
if not ok:
from sympy.integrals.integrals import Integral
# not being able to do the interval of f(x) can
# be stated as not being able to do the integral
# of f'(x) over the same range
return Integral(self.diff(x), (x, lo, hi)) # unevaluated
pieces = [(a, b) for a, b, _, _ in abei]
done = [(lo, hi, -1)]
oo = S.Infinity
for k, p in enumerate(pieces):
if p[:2] == (-oo, oo):
# all undone intervals will get this key
for j, (a, b, i) in enumerate(done):
if i == -1:
done[j] = a, b, k
break # nothing else to consider
N = len(done) - 1
for j, (a, b, i) in enumerate(reversed(done)):
if i == -1:
j = N - j
done[j: j + 1] = _clip(p, (a, b), k)
done = [(a, b, i) for a, b, i in done if a != b]
# return the sum of the intervals
sum = S.Zero
upto = None
for a, b, i in done:
if i == -1:
if upto is None:
return Undefined
# TODO simplify hi <= upto
return Piecewise((sum, hi <= upto), (Undefined, True))
sum += abei[i][-2]._eval_interval(x, a, b)
upto = b
return sum
def _intervals(self, sym, err_on_Eq=False):
r"""Return a bool and a message (when bool is False), else a
list of unique tuples, (a, b, e, i), where a and b
are the lower and upper bounds in which the expression e of
argument i in self is defined and $a < b$ (when involving
numbers) or $a \le b$ when involving symbols.
If there are any relationals not involving sym, or any
relational cannot be solved for sym, the bool will be False
a message be given as the second return value. The calling
routine should have removed such relationals before calling
this routine.
The evaluated conditions will be returned as ranges.
Discontinuous ranges will be returned separately with
identical expressions. The first condition that evaluates to
True will be returned as the last tuple with a, b = -oo, oo.
"""
from sympy.solvers.inequalities import _solve_inequality
assert isinstance(self, Piecewise)
def nonsymfail(cond):
return False, filldedent('''
A condition not involving
%s appeared: %s''' % (sym, cond))
def _solve_relational(r):
if sym not in r.free_symbols:
return nonsymfail(r)
try:
rv = _solve_inequality(r, sym)
except NotImplementedError:
return False, 'Unable to solve relational %s for %s.' % (r, sym)
if isinstance(rv, Relational):
free = rv.args[1].free_symbols
if rv.args[0] != sym or sym in free:
return False, 'Unable to solve relational %s for %s.' % (r, sym)
if rv.rel_op == '==':
# this equality has been affirmed to have the form
# Eq(sym, rhs) where rhs is sym-free; it represents
# a zero-width interval which will be ignored
# whether it is an isolated condition or contained
# within an And or an Or
rv = S.false
elif rv.rel_op == '!=':
try:
rv = Or(sym < rv.rhs, sym > rv.rhs)
except TypeError:
# e.g. x != I ==> all real x satisfy
rv = S.true
elif rv == (S.NegativeInfinity < sym) & (sym < S.Infinity):
rv = S.true
return True, rv
args = list(self.args)
# make self canonical wrt Relationals
keys = self.atoms(Relational)
reps = {}
for r in keys:
ok, s = _solve_relational(r)
if ok != True:
return False, ok
reps[r] = s
# process args individually so if any evaluate, their position
# in the original Piecewise will be known
args = [i.xreplace(reps) for i in self.args]
# precondition args
expr_cond = []
default = idefault = None
for i, (expr, cond) in enumerate(args):
if cond is S.false:
continue
if cond is S.true:
default = expr
idefault = i
break
if isinstance(cond, Eq):
# unanticipated condition, but it is here in case a
# replacement caused an Eq to appear
if err_on_Eq:
return False, 'encountered Eq condition: %s' % cond
continue # zero width interval
cond = to_cnf(cond)
if isinstance(cond, And):
cond = distribute_or_over_and(cond)
if isinstance(cond, Or):
expr_cond.extend(
[(i, expr, o) for o in cond.args
if not isinstance(o, Eq)])
elif cond is not S.false:
expr_cond.append((i, expr, cond))
elif cond is S.true:
default = expr
idefault = i
break
# determine intervals represented by conditions
int_expr = []
for iarg, expr, cond in expr_cond:
if isinstance(cond, And):
lower = S.NegativeInfinity
upper = S.Infinity
exclude = []
for cond2 in cond.args:
if not isinstance(cond2, Relational):
return False, 'expecting only Relationals'
if isinstance(cond2, Eq):
lower = upper # ignore
if err_on_Eq:
return False, 'encountered secondary Eq condition'
break
elif isinstance(cond2, Ne):
l, r = cond2.args
if l == sym:
exclude.append(r)
elif r == sym:
exclude.append(l)
else:
return nonsymfail(cond2)
continue
elif cond2.lts == sym:
upper = Min(cond2.gts, upper)
elif cond2.gts == sym:
lower = Max(cond2.lts, lower)
else:
return nonsymfail(cond2) # should never get here
if exclude:
exclude = list(ordered(exclude))
newcond = []
for i, e in enumerate(exclude):
if e < lower == True or e > upper == True:
continue
if not newcond:
newcond.append((None, lower)) # add a primer
newcond.append((newcond[-1][1], e))
newcond.append((newcond[-1][1], upper))
newcond.pop(0) # remove the primer
expr_cond.extend([(iarg, expr, And(i[0] < sym, sym < i[1])) for i in newcond])
continue
elif isinstance(cond, Relational) and cond.rel_op != '!=':
lower, upper = cond.lts, cond.gts # part 1: initialize with givens
if cond.lts == sym: # part 1a: expand the side ...
lower = S.NegativeInfinity # e.g. x <= 0 ---> -oo <= 0
elif cond.gts == sym: # part 1a: ... that can be expanded
upper = S.Infinity # e.g. x >= 0 ---> oo >= 0
else:
return nonsymfail(cond)
else:
return False, 'unrecognized condition: %s' % cond
lower, upper = lower, Max(lower, upper)
if err_on_Eq and lower == upper:
return False, 'encountered Eq condition'
if (lower >= upper) is not S.true:
int_expr.append((lower, upper, expr, iarg))
if default is not None:
int_expr.append(
(S.NegativeInfinity, S.Infinity, default, idefault))
return True, list(uniq(int_expr))
def _eval_nseries(self, x, n, logx, cdir=0):
args = [(ec.expr._eval_nseries(x, n, logx), ec.cond) for ec in self.args]
return self.func(*args)
def _eval_power(self, s):
return self.func(*[(e**s, c) for e, c in self.args])
def _eval_subs(self, old, new):
# this is strictly not necessary, but we can keep track
# of whether True or False conditions arise and be
# somewhat more efficient by avoiding other substitutions
# and avoiding invalid conditions that appear after a
# True condition
args = list(self.args)
args_exist = False
for i, (e, c) in enumerate(args):
c = c._subs(old, new)
if c != False:
args_exist = True
e = e._subs(old, new)
args[i] = (e, c)
if c == True:
break
if not args_exist:
args = ((Undefined, True),)
return self.func(*args)
def _eval_transpose(self):
return self.func(*[(e.transpose(), c) for e, c in self.args])
def _eval_template_is_attr(self, is_attr):
b = None
for expr, _ in self.args:
a = getattr(expr, is_attr)
if a is None:
return
if b is None:
b = a
elif b is not a:
return
return b
_eval_is_finite = lambda self: self._eval_template_is_attr(
'is_finite')
_eval_is_complex = lambda self: self._eval_template_is_attr('is_complex')
_eval_is_even = lambda self: self._eval_template_is_attr('is_even')
_eval_is_imaginary = lambda self: self._eval_template_is_attr(
'is_imaginary')
_eval_is_integer = lambda self: self._eval_template_is_attr('is_integer')
_eval_is_irrational = lambda self: self._eval_template_is_attr(
'is_irrational')
_eval_is_negative = lambda self: self._eval_template_is_attr('is_negative')
_eval_is_nonnegative = lambda self: self._eval_template_is_attr(
'is_nonnegative')
_eval_is_nonpositive = lambda self: self._eval_template_is_attr(
'is_nonpositive')
_eval_is_nonzero = lambda self: self._eval_template_is_attr(
'is_nonzero')
_eval_is_odd = lambda self: self._eval_template_is_attr('is_odd')
_eval_is_polar = lambda self: self._eval_template_is_attr('is_polar')
_eval_is_positive = lambda self: self._eval_template_is_attr('is_positive')
_eval_is_extended_real = lambda self: self._eval_template_is_attr(
'is_extended_real')
_eval_is_extended_positive = lambda self: self._eval_template_is_attr(
'is_extended_positive')
_eval_is_extended_negative = lambda self: self._eval_template_is_attr(
'is_extended_negative')
_eval_is_extended_nonzero = lambda self: self._eval_template_is_attr(
'is_extended_nonzero')
_eval_is_extended_nonpositive = lambda self: self._eval_template_is_attr(
'is_extended_nonpositive')
_eval_is_extended_nonnegative = lambda self: self._eval_template_is_attr(
'is_extended_nonnegative')
_eval_is_real = lambda self: self._eval_template_is_attr('is_real')
_eval_is_zero = lambda self: self._eval_template_is_attr(
'is_zero')
@classmethod
def __eval_cond(cls, cond):
"""Return the truth value of the condition."""
if cond == True:
return True
if isinstance(cond, Eq):
try:
diff = cond.lhs - cond.rhs
if diff.is_commutative:
return diff.is_zero
except TypeError:
pass
def as_expr_set_pairs(self, domain=None):
"""Return tuples for each argument of self that give
the expression and the interval in which it is valid
which is contained within the given domain.
If a condition cannot be converted to a set, an error
will be raised. The variable of the conditions is
assumed to be real; sets of real values are returned.
Examples
========
>>> from sympy import Piecewise, Interval
>>> from sympy.abc import x
>>> p = Piecewise(
... (1, x < 2),
... (2,(x > 0) & (x < 4)),
... (3, True))
>>> p.as_expr_set_pairs()
[(1, Interval.open(-oo, 2)),
(2, Interval.Ropen(2, 4)),
(3, Interval(4, oo))]
>>> p.as_expr_set_pairs(Interval(0, 3))
[(1, Interval.Ropen(0, 2)),
(2, Interval(2, 3))]
"""
if domain is None:
domain = S.Reals
exp_sets = []
U = domain
complex = not domain.is_subset(S.Reals)
cond_free = set()
for expr, cond in self.args:
cond_free |= cond.free_symbols
if len(cond_free) > 1:
raise NotImplementedError(filldedent('''
multivariate conditions are not handled.'''))
if complex:
for i in cond.atoms(Relational):
if not isinstance(i, (Eq, Ne)):
raise ValueError(filldedent('''
Inequalities in the complex domain are
not supported. Try the real domain by
setting domain=S.Reals'''))
cond_int = U.intersect(cond.as_set())
U = U - cond_int
if cond_int != S.EmptySet:
exp_sets.append((expr, cond_int))
return exp_sets
def _eval_rewrite_as_ITE(self, *args, **kwargs):
byfree = {}
args = list(args)
default = any(c == True for b, c in args)
for i, (b, c) in enumerate(args):
if not isinstance(b, Boolean) and b != True:
raise TypeError(filldedent('''
Expecting Boolean or bool but got `%s`
''' % func_name(b)))
if c == True:
break
# loop over independent conditions for this b
for c in c.args if isinstance(c, Or) else [c]:
free = c.free_symbols
x = free.pop()
try:
byfree[x] = byfree.setdefault(
x, S.EmptySet).union(c.as_set())
except NotImplementedError:
if not default:
raise NotImplementedError(filldedent('''
A method to determine whether a multivariate
conditional is consistent with a complete coverage
of all variables has not been implemented so the
rewrite is being stopped after encountering `%s`.
This error would not occur if a default expression
like `(foo, True)` were given.
''' % c))
if byfree[x] in (S.UniversalSet, S.Reals):
# collapse the ith condition to True and break
args[i] = list(args[i])
c = args[i][1] = True
break
if c == True:
break
if c != True:
raise ValueError(filldedent('''
Conditions must cover all reals or a final default
condition `(foo, True)` must be given.
'''))
last, _ = args[i] # ignore all past ith arg
for a, c in reversed(args[:i]):
last = ITE(c, a, last)
return _canonical(last)
def _eval_rewrite_as_KroneckerDelta(self, *args):
from sympy.functions.special.tensor_functions import KroneckerDelta
rules = {
And: [False, False],
Or: [True, True],
Not: [True, False],
Eq: [None, None],
Ne: [None, None]
}
class UnrecognizedCondition(Exception):
pass
def rewrite(cond):
if isinstance(cond, Eq):
return KroneckerDelta(*cond.args)
if isinstance(cond, Ne):
return 1 - KroneckerDelta(*cond.args)
cls, args = type(cond), cond.args
if cls not in rules:
raise UnrecognizedCondition(cls)
b1, b2 = rules[cls]
k = Mul(*[1 - rewrite(c) for c in args]) if b1 else Mul(*[rewrite(c) for c in args])
if b2:
return 1 - k
return k
conditions = []
true_value = None
for value, cond in args:
if type(cond) in rules:
conditions.append((value, cond))
elif cond is S.true:
if true_value is None:
true_value = value
else:
return
if true_value is not None:
result = true_value
for value, cond in conditions[::-1]:
try:
k = rewrite(cond)
result = k * value + (1 - k) * result
except UnrecognizedCondition:
return
return result
def piecewise_fold(expr, evaluate=True):
"""
Takes an expression containing a piecewise function and returns the
expression in piecewise form. In addition, any ITE conditions are
rewritten in negation normal form and simplified.
The final Piecewise is evaluated (default) but if the raw form
is desired, send ``evaluate=False``; if trivial evaluation is
desired, send ``evaluate=None`` and duplicate conditions and
processing of True and False will be handled.
Examples
========
>>> from sympy import Piecewise, piecewise_fold, S
>>> from sympy.abc import x
>>> p = Piecewise((x, x < 1), (1, S(1) <= x))
>>> piecewise_fold(x*p)
Piecewise((x**2, x < 1), (x, True))
See Also
========
Piecewise
piecewise_exclusive
"""
if not isinstance(expr, Basic) or not expr.has(Piecewise):
return expr
new_args = []
if isinstance(expr, (ExprCondPair, Piecewise)):
for e, c in expr.args:
if not isinstance(e, Piecewise):
e = piecewise_fold(e)
# we don't keep Piecewise in condition because
# it has to be checked to see that it's complete
# and we convert it to ITE at that time
assert not c.has(Piecewise) # pragma: no cover
if isinstance(c, ITE):
c = c.to_nnf()
c = simplify_logic(c, form='cnf')
if isinstance(e, Piecewise):
new_args.extend([(piecewise_fold(ei), And(ci, c))
for ei, ci in e.args])
else:
new_args.append((e, c))
else:
# Given
# P1 = Piecewise((e11, c1), (e12, c2), A)
# P2 = Piecewise((e21, c1), (e22, c2), B)
# ...
# the folding of f(P1, P2) is trivially
# Piecewise(
# (f(e11, e21), c1),
# (f(e12, e22), c2),
# (f(Piecewise(A), Piecewise(B)), True))
# Certain objects end up rewriting themselves as thus, so
# we do that grouping before the more generic folding.
# The following applies this idea when f = Add or f = Mul
# (and the expression is commutative).
if expr.is_Add or expr.is_Mul and expr.is_commutative:
p, args = sift(expr.args, lambda x: x.is_Piecewise, binary=True)
pc = sift(p, lambda x: tuple([c for e,c in x.args]))
for c in list(ordered(pc)):
if len(pc[c]) > 1:
pargs = [list(i.args) for i in pc[c]]
# the first one is the same; there may be more
com = common_prefix(*[
[i.cond for i in j] for j in pargs])
n = len(com)
collected = []
for i in range(n):
collected.append((
expr.func(*[ai[i].expr for ai in pargs]),
com[i]))
remains = []
for a in pargs:
if n == len(a): # no more args
continue
if a[n].cond == True: # no longer Piecewise
remains.append(a[n].expr)
else: # restore the remaining Piecewise
remains.append(
Piecewise(*a[n:], evaluate=False))
if remains:
collected.append((expr.func(*remains), True))
args.append(Piecewise(*collected, evaluate=False))
continue
args.extend(pc[c])
else:
args = expr.args
# fold
folded = list(map(piecewise_fold, args))
for ec in product(*[
(i.args if isinstance(i, Piecewise) else
[(i, true)]) for i in folded]):
e, c = zip(*ec)
new_args.append((expr.func(*e), And(*c)))
if evaluate is None:
# don't return duplicate conditions, otherwise don't evaluate
new_args = list(reversed([(e, c) for c, e in {
c: e for e, c in reversed(new_args)}.items()]))
rv = Piecewise(*new_args, evaluate=evaluate)
if evaluate is None and len(rv.args) == 1 and rv.args[0].cond == True:
return rv.args[0].expr
if any(s.expr.has(Piecewise) for p in rv.atoms(Piecewise) for s in p.args):
return piecewise_fold(rv)
return rv
def _clip(A, B, k):
"""Return interval B as intervals that are covered by A (keyed
to k) and all other intervals of B not covered by A keyed to -1.
The reference point of each interval is the rhs; if the lhs is
greater than the rhs then an interval of zero width interval will
result, e.g. (4, 1) is treated like (1, 1).
Examples
========
>>> from sympy.functions.elementary.piecewise import _clip
>>> from sympy import Tuple
>>> A = Tuple(1, 3)
>>> B = Tuple(2, 4)
>>> _clip(A, B, 0)
[(2, 3, 0), (3, 4, -1)]
Interpretation: interval portion (2, 3) of interval (2, 4) is
covered by interval (1, 3) and is keyed to 0 as requested;
interval (3, 4) was not covered by (1, 3) and is keyed to -1.
"""
a, b = B
c, d = A
c, d = Min(Max(c, a), b), Min(Max(d, a), b)
a, b = Min(a, b), b
p = []
if a != c:
p.append((a, c, -1))
else:
pass
if c != d:
p.append((c, d, k))
else:
pass
if b != d:
if d == c and p and p[-1][-1] == -1:
p[-1] = p[-1][0], b, -1
else:
p.append((d, b, -1))
else:
pass
return p
def piecewise_simplify_arguments(expr, **kwargs):
from sympy.simplify.simplify import simplify
# simplify conditions
f1 = expr.args[0].cond.free_symbols
args = None
if len(f1) == 1 and not expr.atoms(Eq):
x = f1.pop()
# this won't return intervals involving Eq
# and it won't handle symbols treated as
# booleans
ok, abe_ = expr._intervals(x, err_on_Eq=True)
def include(c, x, a):
"return True if c.subs(x, a) is True, else False"
try:
return c.subs(x, a) == True
except TypeError:
return False
if ok:
args = []
covered = S.EmptySet
from sympy.sets.sets import Interval
for a, b, e, i in abe_:
c = expr.args[i].cond
incl_a = include(c, x, a)
incl_b = include(c, x, b)
iv = Interval(a, b, not incl_a, not incl_b)
cset = iv - covered
if not cset:
continue
if incl_a and incl_b:
if a.is_infinite and b.is_infinite:
c = S.true
elif b.is_infinite:
c = (x >= a)
elif a in covered or a.is_infinite:
c = (x <= b)
else:
c = And(a <= x, x <= b)
elif incl_a:
if a in covered or a.is_infinite:
c = (x < b)
else:
c = And(a <= x, x < b)
elif incl_b:
if b.is_infinite:
c = (x > a)
else:
c = (x <= b)
else:
if a in covered:
c = (x < b)
else:
c = And(a < x, x < b)
covered |= iv
if a is S.NegativeInfinity and incl_a:
covered |= {S.NegativeInfinity}
if b is S.Infinity and incl_b:
covered |= {S.Infinity}
args.append((e, c))
if not S.Reals.is_subset(covered):
args.append((Undefined, True))
if args is None:
args = list(expr.args)
for i in range(len(args)):
e, c = args[i]
if isinstance(c, Basic):
c = simplify(c, **kwargs)
args[i] = (e, c)
# simplify expressions
doit = kwargs.pop('doit', None)
for i in range(len(args)):
e, c = args[i]
if isinstance(e, Basic):
# Skip doit to avoid growth at every call for some integrals
# and sums, see sympy/sympy#17165
newe = simplify(e, doit=False, **kwargs)
if newe != e:
e = newe
args[i] = (e, c)
# restore kwargs flag
if doit is not None:
kwargs['doit'] = doit
return Piecewise(*args)
def _piecewise_collapse_arguments(_args):
newargs = [] # the unevaluated conditions
current_cond = set() # the conditions up to a given e, c pair
for expr, cond in _args:
cond = cond.replace(
lambda _: _.is_Relational, _canonical_coeff)
# Check here if expr is a Piecewise and collapse if one of
# the conds in expr matches cond. This allows the collapsing
# of Piecewise((Piecewise((x,x<0)),x<0)) to Piecewise((x,x<0)).
# This is important when using piecewise_fold to simplify
# multiple Piecewise instances having the same conds.
# Eventually, this code should be able to collapse Piecewise's
# having different intervals, but this will probably require
# using the new assumptions.
if isinstance(expr, Piecewise):
unmatching = []
for i, (e, c) in enumerate(expr.args):
if c in current_cond:
# this would already have triggered
continue
if c == cond:
if c != True:
# nothing past this condition will ever
# trigger and only those args before this
# that didn't match a previous condition
# could possibly trigger
if unmatching:
expr = Piecewise(*(
unmatching + [(e, c)]))
else:
expr = e
break
else:
unmatching.append((e, c))
# check for condition repeats
got = False
# -- if an And contains a condition that was
# already encountered, then the And will be
# False: if the previous condition was False
# then the And will be False and if the previous
# condition is True then then we wouldn't get to
# this point. In either case, we can skip this condition.
for i in ([cond] +
(list(cond.args) if isinstance(cond, And) else
[])):
if i in current_cond:
got = True
break
if got:
continue
# -- if not(c) is already in current_cond then c is
# a redundant condition in an And. This does not
# apply to Or, however: (e1, c), (e2, Or(~c, d))
# is not (e1, c), (e2, d) because if c and d are
# both False this would give no results when the
# true answer should be (e2, True)
if isinstance(cond, And):
nonredundant = []
for c in cond.args:
if isinstance(c, Relational):
if c.negated.canonical in current_cond:
continue
# if a strict inequality appears after
# a non-strict one, then the condition is
# redundant
if isinstance(c, (Lt, Gt)) and (
c.weak in current_cond):
cond = False
break
nonredundant.append(c)
else:
cond = cond.func(*nonredundant)
elif isinstance(cond, Relational):
if cond.negated.canonical in current_cond:
cond = S.true
current_cond.add(cond)
# collect successive e,c pairs when exprs or cond match
if newargs:
if newargs[-1].expr == expr:
orcond = Or(cond, newargs[-1].cond)
if isinstance(orcond, (And, Or)):
orcond = distribute_and_over_or(orcond)
newargs[-1] = ExprCondPair(expr, orcond)
continue
elif newargs[-1].cond == cond:
continue
newargs.append(ExprCondPair(expr, cond))
return newargs
_blessed = lambda e: getattr(e.lhs, '_diff_wrt', False) and (
getattr(e.rhs, '_diff_wrt', None) or
isinstance(e.rhs, (Rational, NumberSymbol)))
def piecewise_simplify(expr, **kwargs):
expr = piecewise_simplify_arguments(expr, **kwargs)
if not isinstance(expr, Piecewise):
return expr
args = list(expr.args)
args = _piecewise_simplify_eq_and(args)
args = _piecewise_simplify_equal_to_next_segment(args)
return Piecewise(*args)
def _piecewise_simplify_equal_to_next_segment(args):
"""
See if expressions valid for an Equal expression happens to evaluate
to the same function as in the next piecewise segment, see:
https://github.com/sympy/sympy/issues/8458
"""
prevexpr = None
for i, (expr, cond) in reversed(list(enumerate(args))):
if prevexpr is not None:
if isinstance(cond, And):
eqs, other = sift(cond.args,
lambda i: isinstance(i, Eq), binary=True)
elif isinstance(cond, Eq):
eqs, other = [cond], []
else:
eqs = other = []
_prevexpr = prevexpr
_expr = expr
if eqs and not other:
eqs = list(ordered(eqs))
for e in eqs:
# allow 2 args to collapse into 1 for any e
# otherwise limit simplification to only simple-arg
# Eq instances
if len(args) == 2 or _blessed(e):
_prevexpr = _prevexpr.subs(*e.args)
_expr = _expr.subs(*e.args)
# Did it evaluate to the same?
if _prevexpr == _expr:
# Set the expression for the Not equal section to the same
# as the next. These will be merged when creating the new
# Piecewise
args[i] = args[i].func(args[i + 1][0], cond)
else:
# Update the expression that we compare against
prevexpr = expr
else:
prevexpr = expr
return args
def _piecewise_simplify_eq_and(args):
"""
Try to simplify conditions and the expression for
equalities that are part of the condition, e.g.
Piecewise((n, And(Eq(n,0), Eq(n + m, 0))), (1, True))
-> Piecewise((0, And(Eq(n, 0), Eq(m, 0))), (1, True))
"""
for i, (expr, cond) in enumerate(args):
if isinstance(cond, And):
eqs, other = sift(cond.args,
lambda i: isinstance(i, Eq), binary=True)
elif isinstance(cond, Eq):
eqs, other = [cond], []
else:
eqs = other = []
if eqs:
eqs = list(ordered(eqs))
for j, e in enumerate(eqs):
# these blessed lhs objects behave like Symbols
# and the rhs are simple replacements for the "symbols"
if _blessed(e):
expr = expr.subs(*e.args)
eqs[j + 1:] = [ei.subs(*e.args) for ei in eqs[j + 1:]]
other = [ei.subs(*e.args) for ei in other]
cond = And(*(eqs + other))
args[i] = args[i].func(expr, cond)
return args
def piecewise_exclusive(expr, *, skip_nan=False, deep=True):
"""
Rewrite :class:`Piecewise` with mutually exclusive conditions.
Explanation
===========
SymPy represents the conditions of a :class:`Piecewise` in an
"if-elif"-fashion, allowing more than one condition to be simultaneously
True. The interpretation is that the first condition that is True is the
case that holds. While this is a useful representation computationally it
is not how a piecewise formula is typically shown in a mathematical text.
The :func:`piecewise_exclusive` function can be used to rewrite any
:class:`Piecewise` with more typical mutually exclusive conditions.
Note that further manipulation of the resulting :class:`Piecewise`, e.g.
simplifying it, will most likely make it non-exclusive. Hence, this is
primarily a function to be used in conjunction with printing the Piecewise
or if one would like to reorder the expression-condition pairs.
If it is not possible to determine that all possibilities are covered by
the different cases of the :class:`Piecewise` then a final
:class:`~sympy.core.numbers.NaN` case will be included explicitly. This
can be prevented by passing ``skip_nan=True``.
Examples
========
>>> from sympy import piecewise_exclusive, Symbol, Piecewise, S
>>> x = Symbol('x', real=True)
>>> p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True))
>>> piecewise_exclusive(p)
Piecewise((0, x < 0), (1/2, Eq(x, 0)), (1, x > 0))
>>> piecewise_exclusive(Piecewise((2, x > 1)))
Piecewise((2, x > 1), (nan, x <= 1))
>>> piecewise_exclusive(Piecewise((2, x > 1)), skip_nan=True)
Piecewise((2, x > 1))
Parameters
==========
expr: a SymPy expression.
Any :class:`Piecewise` in the expression will be rewritten.
skip_nan: ``bool`` (default ``False``)
If ``skip_nan`` is set to ``True`` then a final
:class:`~sympy.core.numbers.NaN` case will not be included.
deep: ``bool`` (default ``True``)
If ``deep`` is ``True`` then :func:`piecewise_exclusive` will rewrite
any :class:`Piecewise` subexpressions in ``expr`` rather than just
rewriting ``expr`` itself.
Returns
=======
An expression equivalent to ``expr`` but where all :class:`Piecewise` have
been rewritten with mutually exclusive conditions.
See Also
========
Piecewise
piecewise_fold
"""
def make_exclusive(*pwargs):
cumcond = false
newargs = []
# Handle the first n-1 cases
for expr_i, cond_i in pwargs[:-1]:
cancond = And(cond_i, Not(cumcond)).simplify()
cumcond = Or(cond_i, cumcond).simplify()
newargs.append((expr_i, cancond))
# For the nth case defer simplification of cumcond
expr_n, cond_n = pwargs[-1]
cancond_n = And(cond_n, Not(cumcond)).simplify()
newargs.append((expr_n, cancond_n))
if not skip_nan:
cumcond = Or(cond_n, cumcond).simplify()
if cumcond is not true:
newargs.append((Undefined, Not(cumcond).simplify()))
return Piecewise(*newargs, evaluate=False)
if deep:
return expr.replace(Piecewise, make_exclusive)
elif isinstance(expr, Piecewise):
return make_exclusive(*expr.args)
else:
return expr
|
d30f170450507e5c8e42e083ab265b4325557ccb6b14de7a3b7804b49cecd7ec | r"""A module for special angle forumlas for trigonometric functions
TODO
====
This module should be developed in the future to contain direct squrae root
representation of
.. math
F(\frac{n}{m} \pi)
for every
- $m \in \{ 3, 5, 17, 257, 65537 \}$
- $n \in \mathbb{N}$, $0 \le n < m$
- $F \in \{\sin, \cos, \tan, \csc, \sec, \cot\}$
Without multi-step rewrites
(e.g. $\tan \to \cos/\sin \to \cos/\sqrt \to \ sqrt$)
or using chebyshev identities
(e.g. $\cos \to \cos + \cos^2 + \cdots \to \sqrt{} + \sqrt{}^2 + \cdots $),
which are trivial to implement in sympy,
and had used to give overly complicated expressions.
The reference can be found below, if anyone may need help implementing them.
References
==========
.. [*] Gottlieb, Christian. (1999). The Simple and straightforward construction
of the regular 257-gon. The Mathematical Intelligencer. 21. 31-37.
10.1007/BF03024829.
.. [*] https://resources.wolframcloud.com/FunctionRepository/resources/Cos2PiOverFermatPrime
"""
from __future__ import annotations
from typing import Callable
from functools import reduce
from sympy.core.expr import Expr
from sympy.core.singleton import S
from sympy.core.numbers import igcdex, Integer
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.core.cache import cacheit
def migcdex(*x: int) -> tuple[tuple[int, ...], int]:
r"""Compute extended gcd for multiple integers.
Explanation
===========
Given the integers $x_1, \cdots, x_n$ and
an extended gcd for multiple arguments are defined as a solution
$(y_1, \cdots, y_n), g$ for the diophantine equation
$x_1 y_1 + \cdots + x_n y_n = g$ such that
$g = \gcd(x_1, \cdots, x_n)$.
Examples
========
>>> from sympy.functions.elementary._trigonometric_special import migcdex
>>> migcdex()
((), 0)
>>> migcdex(4)
((1,), 4)
>>> migcdex(4, 6)
((-1, 1), 2)
>>> migcdex(6, 10, 15)
((1, 1, -1), 1)
"""
if not x:
return (), 0
if len(x) == 1:
return (1,), x[0]
if len(x) == 2:
u, v, h = igcdex(x[0], x[1])
return (u, v), h
y, g = migcdex(*x[1:])
u, v, h = igcdex(x[0], g)
return (u, *(v * i for i in y)), h
def ipartfrac(*denoms: int) -> tuple[int, ...]:
r"""Compute the the partial fraction decomposition.
Explanation
===========
Given a rational number $\frac{1}{q_1 \cdots q_n}$ where all
$q_1, \cdots, q_n$ are pairwise coprime,
A partial fraction decomposition is defined as
.. math::
\frac{1}{q_1 \cdots q_n} = \frac{p_1}{q_1} + \cdots + \frac{p_n}{q_n}
And it can be derived from solving the following diophantine equation for
the $p_1, \cdots, p_n$
.. math::
1 = p_1 \prod_{i \ne 1}q_i + \cdots + p_n \prod_{i \ne n}q_i
Where $q_1, \cdots, q_n$ being pairwise coprime implies
$\gcd(\prod_{i \ne 1}q_i, \cdots, \prod_{i \ne n}q_i) = 1$,
which guarantees the existance of the solution.
It is sufficient to compute partial fraction decomposition only
for numerator $1$ because partial fraction decomposition for any
$\frac{n}{q_1 \cdots q_n}$ can be easily computed by multiplying
the result by $n$ afterwards.
Parameters
==========
denoms : int
The pairwise coprime integer denominators $q_i$ which defines the
rational number $\frac{1}{q_1 \cdots q_n}$
Returns
=======
tuple[int, ...]
The list of numerators which semantically corresponds to $p_i$ of the
partial fraction decomposition
$\frac{1}{q_1 \cdots q_n} = \frac{p_1}{q_1} + \cdots + \frac{p_n}{q_n}$
Examples
========
>>> from sympy import Rational, Mul
>>> from sympy.functions.elementary._trigonometric_special import ipartfrac
>>> denoms = 2, 3, 5
>>> numers = ipartfrac(2, 3, 5)
>>> numers
(1, 7, -14)
>>> Rational(1, Mul(*denoms))
1/30
>>> out = 0
>>> for n, d in zip(numers, denoms):
... out += Rational(n, d)
>>> out
1/30
"""
if not denoms:
return ()
def mul(x: int, y: int) -> int:
return x * y
denom = reduce(mul, denoms)
a = [denom // x for x in denoms]
h, _ = migcdex(*a)
return h
def fermat_coords(n: int) -> list[int] | None:
"""If n can be factored in terms of Fermat primes with
multiplicity of each being 1, return those primes, else
None
"""
primes = []
for p in [3, 5, 17, 257, 65537]:
quotient, remainder = divmod(n, p)
if remainder == 0:
n = quotient
primes.append(p)
if n == 1:
return primes
return None
@cacheit
def cos_3() -> Expr:
r"""Computes $\cos \frac{\pi}{3}$ in square roots"""
return S.Half
@cacheit
def cos_5() -> Expr:
r"""Computes $\cos \frac{\pi}{5}$ in square roots"""
return (sqrt(5) + 1) / 4
@cacheit
def cos_17() -> Expr:
r"""Computes $\cos \frac{\pi}{17}$ in square roots"""
return sqrt(
(15 + sqrt(17)) / 32 + sqrt(2) * (sqrt(17 - sqrt(17)) +
sqrt(sqrt(2) * (-8 * sqrt(17 + sqrt(17)) - (1 - sqrt(17))
* sqrt(17 - sqrt(17))) + 6 * sqrt(17) + 34)) / 32)
@cacheit
def cos_257() -> Expr:
r"""Computes $\cos \frac{\pi}{257}$ in square roots
References
==========
.. [*] http://math.stackexchange.com/questions/516142/how-does-cos2-pi-257-look-like-in-real-radicals
.. [*] https://r-knott.surrey.ac.uk/Fibonacci/simpleTrig.html
"""
def f1(a: Expr, b: Expr) -> tuple[Expr, Expr]:
return (a + sqrt(a**2 + b)) / 2, (a - sqrt(a**2 + b)) / 2
def f2(a: Expr, b: Expr) -> Expr:
return (a - sqrt(a**2 + b))/2
t1, t2 = f1(S.NegativeOne, Integer(256))
z1, z3 = f1(t1, Integer(64))
z2, z4 = f1(t2, Integer(64))
y1, y5 = f1(z1, 4*(5 + t1 + 2*z1))
y6, y2 = f1(z2, 4*(5 + t2 + 2*z2))
y3, y7 = f1(z3, 4*(5 + t1 + 2*z3))
y8, y4 = f1(z4, 4*(5 + t2 + 2*z4))
x1, x9 = f1(y1, -4*(t1 + y1 + y3 + 2*y6))
x2, x10 = f1(y2, -4*(t2 + y2 + y4 + 2*y7))
x3, x11 = f1(y3, -4*(t1 + y3 + y5 + 2*y8))
x4, x12 = f1(y4, -4*(t2 + y4 + y6 + 2*y1))
x5, x13 = f1(y5, -4*(t1 + y5 + y7 + 2*y2))
x6, x14 = f1(y6, -4*(t2 + y6 + y8 + 2*y3))
x15, x7 = f1(y7, -4*(t1 + y7 + y1 + 2*y4))
x8, x16 = f1(y8, -4*(t2 + y8 + y2 + 2*y5))
v1 = f2(x1, -4*(x1 + x2 + x3 + x6))
v2 = f2(x2, -4*(x2 + x3 + x4 + x7))
v3 = f2(x8, -4*(x8 + x9 + x10 + x13))
v4 = f2(x9, -4*(x9 + x10 + x11 + x14))
v5 = f2(x10, -4*(x10 + x11 + x12 + x15))
v6 = f2(x16, -4*(x16 + x1 + x2 + x5))
u1 = -f2(-v1, -4*(v2 + v3))
u2 = -f2(-v4, -4*(v5 + v6))
w1 = -2*f2(-u1, -4*u2)
return sqrt(sqrt(2)*sqrt(w1 + 4)/8 + S.Half)
def cos_table() -> dict[int, Callable[[], Expr]]:
r"""Lazily evaluated table for $\cos \frac{\pi}{n}$ in square roots for
$n \in \{3, 5, 17, 257, 65537\}$.
Notes
=====
65537 is the only other known Fermat prime and it is nearly impossible to
build in the current SymPy due to performance issues.
References
==========
https://r-knott.surrey.ac.uk/Fibonacci/simpleTrig.html
"""
return {
3: cos_3,
5: cos_5,
17: cos_17,
257: cos_257
}
|
a146bfcccf7a2d9ba4ccd44640aaf0660ed615f6c461e8e65cb1cbff9c49eca4 | from math import prod
from sympy.core import Add, S, Dummy, expand_func
from sympy.core.expr import Expr
from sympy.core.function import Function, ArgumentIndexError, PoleError
from sympy.core.logic import fuzzy_and, fuzzy_not
from sympy.core.numbers import Rational, pi, oo, I
from sympy.core.power import Pow
from sympy.functions.special.zeta_functions import zeta
from sympy.functions.special.error_functions import erf, erfc, Ei
from sympy.functions.elementary.complexes import re, unpolarify
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.integers import ceiling, floor
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin, cos, cot
from sympy.functions.combinatorial.numbers import bernoulli, harmonic
from sympy.functions.combinatorial.factorials import factorial, rf, RisingFactorial
from sympy.utilities.misc import as_int
from mpmath import mp, workprec
from mpmath.libmp.libmpf import prec_to_dps
def intlike(n):
try:
as_int(n, strict=False)
return True
except ValueError:
return False
###############################################################################
############################ COMPLETE GAMMA FUNCTION ##########################
###############################################################################
class gamma(Function):
r"""
The gamma function
.. math::
\Gamma(x) := \int^{\infty}_{0} t^{x-1} e^{-t} \mathrm{d}t.
Explanation
===========
The ``gamma`` function implements the function which passes through the
values of the factorial function (i.e., $\Gamma(n) = (n - 1)!$ when n is
an integer). More generally, $\Gamma(z)$ is defined in the whole complex
plane except at the negative integers where there are simple poles.
Examples
========
>>> from sympy import S, I, pi, gamma
>>> from sympy.abc import x
Several special values are known:
>>> gamma(1)
1
>>> gamma(4)
6
>>> gamma(S(3)/2)
sqrt(pi)/2
The ``gamma`` function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(gamma(x))
gamma(conjugate(x))
Differentiation with respect to $x$ is supported:
>>> from sympy import diff
>>> diff(gamma(x), x)
gamma(x)*polygamma(0, x)
Series expansion is also supported:
>>> from sympy import series
>>> series(gamma(x), x, 0, 3)
1/x - EulerGamma + x*(EulerGamma**2/2 + pi**2/12) + x**2*(-EulerGamma*pi**2/12 - zeta(3)/3 - EulerGamma**3/6) + O(x**3)
We can numerically evaluate the ``gamma`` function to arbitrary precision
on the whole complex plane:
>>> gamma(pi).evalf(40)
2.288037795340032417959588909060233922890
>>> gamma(1+I).evalf(20)
0.49801566811835604271 - 0.15494982830181068512*I
See Also
========
lowergamma: Lower incomplete gamma function.
uppergamma: Upper incomplete gamma function.
polygamma: Polygamma function.
loggamma: Log Gamma function.
digamma: Digamma function.
trigamma: Trigamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Gamma_function
.. [2] http://dlmf.nist.gov/5
.. [3] http://mathworld.wolfram.com/GammaFunction.html
.. [4] http://functions.wolfram.com/GammaBetaErf/Gamma/
"""
unbranched = True
_singularities = (S.ComplexInfinity,)
def fdiff(self, argindex=1):
if argindex == 1:
return self.func(self.args[0])*polygamma(0, self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is oo:
return oo
elif intlike(arg):
if arg.is_positive:
return factorial(arg - 1)
else:
return S.ComplexInfinity
elif arg.is_Rational:
if arg.q == 2:
n = abs(arg.p) // arg.q
if arg.is_positive:
k, coeff = n, S.One
else:
n = k = n + 1
if n & 1 == 0:
coeff = S.One
else:
coeff = S.NegativeOne
coeff *= prod(range(3, 2*k, 2))
if arg.is_positive:
return coeff*sqrt(pi) / 2**n
else:
return 2**n*sqrt(pi) / coeff
def _eval_expand_func(self, **hints):
arg = self.args[0]
if arg.is_Rational:
if abs(arg.p) > arg.q:
x = Dummy('x')
n = arg.p // arg.q
p = arg.p - n*arg.q
return self.func(x + n)._eval_expand_func().subs(x, Rational(p, arg.q))
if arg.is_Add:
coeff, tail = arg.as_coeff_add()
if coeff and coeff.q != 1:
intpart = floor(coeff)
tail = (coeff - intpart,) + tail
coeff = intpart
tail = arg._new_rawargs(*tail, reeval=False)
return self.func(tail)*RisingFactorial(tail, coeff)
return self.func(*self.args)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def _eval_is_real(self):
x = self.args[0]
if x.is_nonpositive and x.is_integer:
return False
if intlike(x) and x <= 0:
return False
if x.is_positive or x.is_noninteger:
return True
def _eval_is_positive(self):
x = self.args[0]
if x.is_positive:
return True
elif x.is_noninteger:
return floor(x).is_even
def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
return exp(loggamma(z))
def _eval_rewrite_as_factorial(self, z, **kwargs):
return factorial(z - 1)
def _eval_nseries(self, x, n, logx, cdir=0):
x0 = self.args[0].limit(x, 0)
if not (x0.is_Integer and x0 <= 0):
return super()._eval_nseries(x, n, logx)
t = self.args[0] - x0
return (self.func(t + 1)/rf(self.args[0], -x0 + 1))._eval_nseries(x, n, logx)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
arg = self.args[0]
x0 = arg.subs(x, 0)
if x0.is_integer and x0.is_nonpositive:
n = -x0
res = S.NegativeOne**n/self.func(n + 1)
return res/(arg + n).as_leading_term(x)
elif not x0.is_infinite:
return self.func(x0)
raise PoleError()
###############################################################################
################## LOWER and UPPER INCOMPLETE GAMMA FUNCTIONS #################
###############################################################################
class lowergamma(Function):
r"""
The lower incomplete gamma function.
Explanation
===========
It can be defined as the meromorphic continuation of
.. math::
\gamma(s, x) := \int_0^x t^{s-1} e^{-t} \mathrm{d}t = \Gamma(s) - \Gamma(s, x).
This can be shown to be the same as
.. math::
\gamma(s, x) = \frac{x^s}{s} {}_1F_1\left({s \atop s+1} \middle| -x\right),
where ${}_1F_1$ is the (confluent) hypergeometric function.
Examples
========
>>> from sympy import lowergamma, S
>>> from sympy.abc import s, x
>>> lowergamma(s, x)
lowergamma(s, x)
>>> lowergamma(3, x)
-2*(x**2/2 + x + 1)*exp(-x) + 2
>>> lowergamma(-S(1)/2, x)
-2*sqrt(pi)*erf(sqrt(x)) - 2*exp(-x)/sqrt(x)
See Also
========
gamma: Gamma function.
uppergamma: Upper incomplete gamma function.
polygamma: Polygamma function.
loggamma: Log Gamma function.
digamma: Digamma function.
trigamma: Trigamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Incomplete_gamma_function#Lower_incomplete_gamma_function
.. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6,
Section 5, Handbook of Mathematical Functions with Formulas, Graphs,
and Mathematical Tables
.. [3] http://dlmf.nist.gov/8
.. [4] http://functions.wolfram.com/GammaBetaErf/Gamma2/
.. [5] http://functions.wolfram.com/GammaBetaErf/Gamma3/
"""
def fdiff(self, argindex=2):
from sympy.functions.special.hyper import meijerg
if argindex == 2:
a, z = self.args
return exp(-unpolarify(z))*z**(a - 1)
elif argindex == 1:
a, z = self.args
return gamma(a)*digamma(a) - log(z)*uppergamma(a, z) \
- meijerg([], [1, 1], [0, 0, a], [], z)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, a, x):
# For lack of a better place, we use this one to extract branching
# information. The following can be
# found in the literature (c/f references given above), albeit scattered:
# 1) For fixed x != 0, lowergamma(s, x) is an entire function of s
# 2) For fixed positive integers s, lowergamma(s, x) is an entire
# function of x.
# 3) For fixed non-positive integers s,
# lowergamma(s, exp(I*2*pi*n)*x) =
# 2*pi*I*n*(-1)**(-s)/factorial(-s) + lowergamma(s, x)
# (this follows from lowergamma(s, x).diff(x) = x**(s-1)*exp(-x)).
# 4) For fixed non-integral s,
# lowergamma(s, x) = x**s*gamma(s)*lowergamma_unbranched(s, x),
# where lowergamma_unbranched(s, x) is an entire function (in fact
# of both s and x), i.e.
# lowergamma(s, exp(2*I*pi*n)*x) = exp(2*pi*I*n*a)*lowergamma(a, x)
if x is S.Zero:
return S.Zero
nx, n = x.extract_branch_factor()
if a.is_integer and a.is_positive:
nx = unpolarify(x)
if nx != x:
return lowergamma(a, nx)
elif a.is_integer and a.is_nonpositive:
if n != 0:
return 2*pi*I*n*S.NegativeOne**(-a)/factorial(-a) + lowergamma(a, nx)
elif n != 0:
return exp(2*pi*I*n*a)*lowergamma(a, nx)
# Special values.
if a.is_Number:
if a is S.One:
return S.One - exp(-x)
elif a is S.Half:
return sqrt(pi)*erf(sqrt(x))
elif a.is_Integer or (2*a).is_Integer:
b = a - 1
if b.is_positive:
if a.is_integer:
return factorial(b) - exp(-x) * factorial(b) * Add(*[x ** k / factorial(k) for k in range(a)])
else:
return gamma(a)*(lowergamma(S.Half, x)/sqrt(pi) - exp(-x)*Add(*[x**(k - S.Half)/gamma(S.Half + k) for k in range(1, a + S.Half)]))
if not a.is_Integer:
return S.NegativeOne**(S.Half - a)*pi*erf(sqrt(x))/gamma(1 - a) + exp(-x)*Add(*[x**(k + a - 1)*gamma(a)/gamma(a + k) for k in range(1, Rational(3, 2) - a)])
if x.is_zero:
return S.Zero
def _eval_evalf(self, prec):
if all(x.is_number for x in self.args):
a = self.args[0]._to_mpmath(prec)
z = self.args[1]._to_mpmath(prec)
with workprec(prec):
res = mp.gammainc(a, 0, z)
return Expr._from_mpmath(res, prec)
else:
return self
def _eval_conjugate(self):
x = self.args[1]
if x not in (S.Zero, S.NegativeInfinity):
return self.func(self.args[0].conjugate(), x.conjugate())
def _eval_is_meromorphic(self, x, a):
# By https://en.wikipedia.org/wiki/Incomplete_gamma_function#Holomorphic_extension,
# lowergamma(s, z) = z**s*gamma(s)*gammastar(s, z),
# where gammastar(s, z) is holomorphic for all s and z.
# Hence the singularities of lowergamma are z = 0 (branch
# point) and nonpositive integer values of s (poles of gamma(s)).
s, z = self.args
args_merom = fuzzy_and([z._eval_is_meromorphic(x, a),
s._eval_is_meromorphic(x, a)])
if not args_merom:
return args_merom
z0 = z.subs(x, a)
if s.is_integer:
return fuzzy_and([s.is_positive, z0.is_finite])
s0 = s.subs(x, a)
return fuzzy_and([s0.is_finite, z0.is_finite, fuzzy_not(z0.is_zero)])
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import O
s, z = self.args
if args0[0] is oo and not z.has(x):
coeff = z**s*exp(-z)
sum_expr = sum(z**k/rf(s, k + 1) for k in range(n - 1))
o = O(z**s*s**(-n))
return coeff*sum_expr + o
return super()._eval_aseries(n, args0, x, logx)
def _eval_rewrite_as_uppergamma(self, s, x, **kwargs):
return gamma(s) - uppergamma(s, x)
def _eval_rewrite_as_expint(self, s, x, **kwargs):
from sympy.functions.special.error_functions import expint
if s.is_integer and s.is_nonpositive:
return self
return self.rewrite(uppergamma).rewrite(expint)
def _eval_is_zero(self):
x = self.args[1]
if x.is_zero:
return True
class uppergamma(Function):
r"""
The upper incomplete gamma function.
Explanation
===========
It can be defined as the meromorphic continuation of
.. math::
\Gamma(s, x) := \int_x^\infty t^{s-1} e^{-t} \mathrm{d}t = \Gamma(s) - \gamma(s, x).
where $\gamma(s, x)$ is the lower incomplete gamma function,
:class:`lowergamma`. This can be shown to be the same as
.. math::
\Gamma(s, x) = \Gamma(s) - \frac{x^s}{s} {}_1F_1\left({s \atop s+1} \middle| -x\right),
where ${}_1F_1$ is the (confluent) hypergeometric function.
The upper incomplete gamma function is also essentially equivalent to the
generalized exponential integral:
.. math::
\operatorname{E}_{n}(x) = \int_{1}^{\infty}{\frac{e^{-xt}}{t^n} \, dt} = x^{n-1}\Gamma(1-n,x).
Examples
========
>>> from sympy import uppergamma, S
>>> from sympy.abc import s, x
>>> uppergamma(s, x)
uppergamma(s, x)
>>> uppergamma(3, x)
2*(x**2/2 + x + 1)*exp(-x)
>>> uppergamma(-S(1)/2, x)
-2*sqrt(pi)*erfc(sqrt(x)) + 2*exp(-x)/sqrt(x)
>>> uppergamma(-2, x)
expint(3, x)/x**2
See Also
========
gamma: Gamma function.
lowergamma: Lower incomplete gamma function.
polygamma: Polygamma function.
loggamma: Log Gamma function.
digamma: Digamma function.
trigamma: Trigamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Incomplete_gamma_function#Upper_incomplete_gamma_function
.. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6,
Section 5, Handbook of Mathematical Functions with Formulas, Graphs,
and Mathematical Tables
.. [3] http://dlmf.nist.gov/8
.. [4] http://functions.wolfram.com/GammaBetaErf/Gamma2/
.. [5] http://functions.wolfram.com/GammaBetaErf/Gamma3/
.. [6] https://en.wikipedia.org/wiki/Exponential_integral#Relation_with_other_functions
"""
def fdiff(self, argindex=2):
from sympy.functions.special.hyper import meijerg
if argindex == 2:
a, z = self.args
return -exp(-unpolarify(z))*z**(a - 1)
elif argindex == 1:
a, z = self.args
return uppergamma(a, z)*log(z) + meijerg([], [1, 1], [0, 0, a], [], z)
else:
raise ArgumentIndexError(self, argindex)
def _eval_evalf(self, prec):
if all(x.is_number for x in self.args):
a = self.args[0]._to_mpmath(prec)
z = self.args[1]._to_mpmath(prec)
with workprec(prec):
res = mp.gammainc(a, z, mp.inf)
return Expr._from_mpmath(res, prec)
return self
@classmethod
def eval(cls, a, z):
from sympy.functions.special.error_functions import expint
if z.is_Number:
if z is S.NaN:
return S.NaN
elif z is oo:
return S.Zero
elif z.is_zero:
if re(a).is_positive:
return gamma(a)
# We extract branching information here. C/f lowergamma.
nx, n = z.extract_branch_factor()
if a.is_integer and a.is_positive:
nx = unpolarify(z)
if z != nx:
return uppergamma(a, nx)
elif a.is_integer and a.is_nonpositive:
if n != 0:
return -2*pi*I*n*S.NegativeOne**(-a)/factorial(-a) + uppergamma(a, nx)
elif n != 0:
return gamma(a)*(1 - exp(2*pi*I*n*a)) + exp(2*pi*I*n*a)*uppergamma(a, nx)
# Special values.
if a.is_Number:
if a is S.Zero and z.is_positive:
return -Ei(-z)
elif a is S.One:
return exp(-z)
elif a is S.Half:
return sqrt(pi)*erfc(sqrt(z))
elif a.is_Integer or (2*a).is_Integer:
b = a - 1
if b.is_positive:
if a.is_integer:
return exp(-z) * factorial(b) * Add(*[z**k / factorial(k)
for k in range(a)])
else:
return (gamma(a) * erfc(sqrt(z)) +
S.NegativeOne**(a - S(3)/2) * exp(-z) * sqrt(z)
* Add(*[gamma(-S.Half - k) * (-z)**k / gamma(1-a)
for k in range(a - S.Half)]))
elif b.is_Integer:
return expint(-b, z)*unpolarify(z)**(b + 1)
if not a.is_Integer:
return (S.NegativeOne**(S.Half - a) * pi*erfc(sqrt(z))/gamma(1-a)
- z**a * exp(-z) * Add(*[z**k * gamma(a) / gamma(a+k+1)
for k in range(S.Half - a)]))
if a.is_zero and z.is_positive:
return -Ei(-z)
if z.is_zero and re(a).is_positive:
return gamma(a)
def _eval_conjugate(self):
z = self.args[1]
if z not in (S.Zero, S.NegativeInfinity):
return self.func(self.args[0].conjugate(), z.conjugate())
def _eval_is_meromorphic(self, x, a):
return lowergamma._eval_is_meromorphic(self, x, a)
def _eval_rewrite_as_lowergamma(self, s, x, **kwargs):
return gamma(s) - lowergamma(s, x)
def _eval_rewrite_as_tractable(self, s, x, **kwargs):
return exp(loggamma(s)) - lowergamma(s, x)
def _eval_rewrite_as_expint(self, s, x, **kwargs):
from sympy.functions.special.error_functions import expint
return expint(1 - s, x)*x**s
###############################################################################
###################### POLYGAMMA and LOGGAMMA FUNCTIONS #######################
###############################################################################
class polygamma(Function):
r"""
The function ``polygamma(n, z)`` returns ``log(gamma(z)).diff(n + 1)``.
Explanation
===========
It is a meromorphic function on $\mathbb{C}$ and defined as the $(n+1)$-th
derivative of the logarithm of the gamma function:
.. math::
\psi^{(n)} (z) := \frac{\mathrm{d}^{n+1}}{\mathrm{d} z^{n+1}} \log\Gamma(z).
For `n` not a nonnegative integer the generalization by Espinosa and Moll [5]_
is used:
.. math:: \psi(s,z) = \frac{\zeta'(s+1, z) + (\gamma + \psi(-s)) \zeta(s+1, z)}
{\Gamma(-s)}
Examples
========
Several special values are known:
>>> from sympy import S, polygamma
>>> polygamma(0, 1)
-EulerGamma
>>> polygamma(0, 1/S(2))
-2*log(2) - EulerGamma
>>> polygamma(0, 1/S(3))
-log(3) - sqrt(3)*pi/6 - EulerGamma - log(sqrt(3))
>>> polygamma(0, 1/S(4))
-pi/2 - log(4) - log(2) - EulerGamma
>>> polygamma(0, 2)
1 - EulerGamma
>>> polygamma(0, 23)
19093197/5173168 - EulerGamma
>>> from sympy import oo, I
>>> polygamma(0, oo)
oo
>>> polygamma(0, -oo)
oo
>>> polygamma(0, I*oo)
oo
>>> polygamma(0, -I*oo)
oo
Differentiation with respect to $x$ is supported:
>>> from sympy import Symbol, diff
>>> x = Symbol("x")
>>> diff(polygamma(0, x), x)
polygamma(1, x)
>>> diff(polygamma(0, x), x, 2)
polygamma(2, x)
>>> diff(polygamma(0, x), x, 3)
polygamma(3, x)
>>> diff(polygamma(1, x), x)
polygamma(2, x)
>>> diff(polygamma(1, x), x, 2)
polygamma(3, x)
>>> diff(polygamma(2, x), x)
polygamma(3, x)
>>> diff(polygamma(2, x), x, 2)
polygamma(4, x)
>>> n = Symbol("n")
>>> diff(polygamma(n, x), x)
polygamma(n + 1, x)
>>> diff(polygamma(n, x), x, 2)
polygamma(n + 2, x)
We can rewrite ``polygamma`` functions in terms of harmonic numbers:
>>> from sympy import harmonic
>>> polygamma(0, x).rewrite(harmonic)
harmonic(x - 1) - EulerGamma
>>> polygamma(2, x).rewrite(harmonic)
2*harmonic(x - 1, 3) - 2*zeta(3)
>>> ni = Symbol("n", integer=True)
>>> polygamma(ni, x).rewrite(harmonic)
(-1)**(n + 1)*(-harmonic(x - 1, n + 1) + zeta(n + 1))*factorial(n)
See Also
========
gamma: Gamma function.
lowergamma: Lower incomplete gamma function.
uppergamma: Upper incomplete gamma function.
loggamma: Log Gamma function.
digamma: Digamma function.
trigamma: Trigamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Polygamma_function
.. [2] http://mathworld.wolfram.com/PolygammaFunction.html
.. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma/
.. [4] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/
.. [5] O. Espinosa and V. Moll, "A generalized polygamma function",
*Integral Transforms and Special Functions* (2004), 101-115.
"""
@classmethod
def eval(cls, n, z):
if n is S.NaN or z is S.NaN:
return S.NaN
elif z is oo:
return oo if n.is_zero else S.Zero
elif z.is_Integer and z.is_nonpositive:
return S.ComplexInfinity
elif n is S.NegativeOne:
return loggamma(z) - log(2*pi) / 2
elif n.is_zero:
if z is -oo or z.extract_multiplicatively(I) in (oo, -oo):
return oo
elif z.is_Integer:
return harmonic(z-1) - S.EulerGamma
elif z.is_Rational:
# TODO n == 1 also can do some rational z
p, q = z.as_numer_denom()
# only expand for small denominators to avoid creating long expressions
if q <= 6:
return expand_func(polygamma(S.Zero, z, evaluate=False))
elif n.is_integer and n.is_nonnegative:
nz = unpolarify(z)
if z != nz:
return polygamma(n, nz)
if z.is_Integer:
return S.NegativeOne**(n+1) * factorial(n) * zeta(n+1, z)
elif z is S.Half:
return S.NegativeOne**(n+1) * factorial(n) * (2**(n+1)-1) * zeta(n+1)
def _eval_is_real(self):
if self.args[0].is_positive and self.args[1].is_positive:
return True
def _eval_is_complex(self):
z = self.args[1]
is_negative_integer = fuzzy_and([z.is_negative, z.is_integer])
return fuzzy_and([z.is_complex, fuzzy_not(is_negative_integer)])
def _eval_is_positive(self):
n, z = self.args
if n.is_positive:
if n.is_odd and z.is_real:
return True
if n.is_even and z.is_positive:
return False
def _eval_is_negative(self):
n, z = self.args
if n.is_positive:
if n.is_even and z.is_positive:
return True
if n.is_odd and z.is_real:
return False
def _eval_expand_func(self, **hints):
n, z = self.args
if n.is_Integer and n.is_nonnegative:
if z.is_Add:
coeff = z.args[0]
if coeff.is_Integer:
e = -(n + 1)
if coeff > 0:
tail = Add(*[Pow(
z - i, e) for i in range(1, int(coeff) + 1)])
else:
tail = -Add(*[Pow(
z + i, e) for i in range(int(-coeff))])
return polygamma(n, z - coeff) + S.NegativeOne**n*factorial(n)*tail
elif z.is_Mul:
coeff, z = z.as_two_terms()
if coeff.is_Integer and coeff.is_positive:
tail = [polygamma(n, z + Rational(
i, coeff)) for i in range(int(coeff))]
if n == 0:
return Add(*tail)/coeff + log(coeff)
else:
return Add(*tail)/coeff**(n + 1)
z *= coeff
if n == 0 and z.is_Rational:
p, q = z.as_numer_denom()
# Reference:
# Values of the polygamma functions at rational arguments, J. Choi, 2007
part_1 = -S.EulerGamma - pi * cot(p * pi / q) / 2 - log(q) + Add(
*[cos(2 * k * pi * p / q) * log(2 * sin(k * pi / q)) for k in range(1, q)])
if z > 0:
n = floor(z)
z0 = z - n
return part_1 + Add(*[1 / (z0 + k) for k in range(n)])
elif z < 0:
n = floor(1 - z)
z0 = z + n
return part_1 - Add(*[1 / (z0 - 1 - k) for k in range(n)])
if n == -1:
return loggamma(z) - log(2*pi) / 2
if n.is_integer is False or n.is_nonnegative is False:
s = Dummy("s")
dzt = zeta(s, z).diff(s).subs(s, n+1)
return (dzt + (S.EulerGamma + digamma(-n)) * zeta(n+1, z)) / gamma(-n)
return polygamma(n, z)
def _eval_rewrite_as_zeta(self, n, z, **kwargs):
if n.is_integer and n.is_positive:
return S.NegativeOne**(n + 1)*factorial(n)*zeta(n + 1, z)
def _eval_rewrite_as_harmonic(self, n, z, **kwargs):
if n.is_integer:
if n.is_zero:
return harmonic(z - 1) - S.EulerGamma
else:
return S.NegativeOne**(n+1) * factorial(n) * (zeta(n+1) - harmonic(z-1, n+1))
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.series.order import Order
n, z = [a.as_leading_term(x) for a in self.args]
o = Order(z, x)
if n == 0 and o.contains(1/x):
logx = log(x) if logx is None else logx
return o.getn() * logx
else:
return self.func(n, z)
def fdiff(self, argindex=2):
if argindex == 2:
n, z = self.args[:2]
return polygamma(n + 1, z)
else:
raise ArgumentIndexError(self, argindex)
def _eval_aseries(self, n, args0, x, logx):
from sympy.series.order import Order
if args0[1] != oo or not \
(self.args[0].is_Integer and self.args[0].is_nonnegative):
return super()._eval_aseries(n, args0, x, logx)
z = self.args[1]
N = self.args[0]
if N == 0:
# digamma function series
# Abramowitz & Stegun, p. 259, 6.3.18
r = log(z) - 1/(2*z)
o = None
if n < 2:
o = Order(1/z, x)
else:
m = ceiling((n + 1)//2)
l = [bernoulli(2*k) / (2*k*z**(2*k)) for k in range(1, m)]
r -= Add(*l)
o = Order(1/z**n, x)
return r._eval_nseries(x, n, logx) + o
else:
# proper polygamma function
# Abramowitz & Stegun, p. 260, 6.4.10
# We return terms to order higher than O(x**n) on purpose
# -- otherwise we would not be able to return any terms for
# quite a long time!
fac = gamma(N)
e0 = fac + N*fac/(2*z)
m = ceiling((n + 1)//2)
for k in range(1, m):
fac = fac*(2*k + N - 1)*(2*k + N - 2) / ((2*k)*(2*k - 1))
e0 += bernoulli(2*k)*fac/z**(2*k)
o = Order(1/z**(2*m), x)
if n == 0:
o = Order(1/z, x)
elif n == 1:
o = Order(1/z**2, x)
r = e0._eval_nseries(z, n, logx) + o
return (-1 * (-1/z)**N * r)._eval_nseries(x, n, logx)
def _eval_evalf(self, prec):
if not all(i.is_number for i in self.args):
return
s = self.args[0]._to_mpmath(prec+12)
z = self.args[1]._to_mpmath(prec+12)
if mp.isint(z) and z <= 0:
return S.ComplexInfinity
with workprec(prec+12):
if mp.isint(s) and s >= 0:
res = mp.polygamma(s, z)
else:
zt = mp.zeta(s+1, z)
dzt = mp.zeta(s+1, z, 1)
res = (dzt + (mp.euler + mp.digamma(-s)) * zt) * mp.rgamma(-s)
return Expr._from_mpmath(res, prec)
class loggamma(Function):
r"""
The ``loggamma`` function implements the logarithm of the
gamma function (i.e., $\log\Gamma(x)$).
Examples
========
Several special values are known. For numerical integral
arguments we have:
>>> from sympy import loggamma
>>> loggamma(-2)
oo
>>> loggamma(0)
oo
>>> loggamma(1)
0
>>> loggamma(2)
0
>>> loggamma(3)
log(2)
And for symbolic values:
>>> from sympy import Symbol
>>> n = Symbol("n", integer=True, positive=True)
>>> loggamma(n)
log(gamma(n))
>>> loggamma(-n)
oo
For half-integral values:
>>> from sympy import S
>>> loggamma(S(5)/2)
log(3*sqrt(pi)/4)
>>> loggamma(n/2)
log(2**(1 - n)*sqrt(pi)*gamma(n)/gamma(n/2 + 1/2))
And general rational arguments:
>>> from sympy import expand_func
>>> L = loggamma(S(16)/3)
>>> expand_func(L).doit()
-5*log(3) + loggamma(1/3) + log(4) + log(7) + log(10) + log(13)
>>> L = loggamma(S(19)/4)
>>> expand_func(L).doit()
-4*log(4) + loggamma(3/4) + log(3) + log(7) + log(11) + log(15)
>>> L = loggamma(S(23)/7)
>>> expand_func(L).doit()
-3*log(7) + log(2) + loggamma(2/7) + log(9) + log(16)
The ``loggamma`` function has the following limits towards infinity:
>>> from sympy import oo
>>> loggamma(oo)
oo
>>> loggamma(-oo)
zoo
The ``loggamma`` function obeys the mirror symmetry
if $x \in \mathbb{C} \setminus \{-\infty, 0\}$:
>>> from sympy.abc import x
>>> from sympy import conjugate
>>> conjugate(loggamma(x))
loggamma(conjugate(x))
Differentiation with respect to $x$ is supported:
>>> from sympy import diff
>>> diff(loggamma(x), x)
polygamma(0, x)
Series expansion is also supported:
>>> from sympy import series
>>> series(loggamma(x), x, 0, 4).cancel()
-log(x) - EulerGamma*x + pi**2*x**2/12 - x**3*zeta(3)/3 + O(x**4)
We can numerically evaluate the ``loggamma`` function
to arbitrary precision on the whole complex plane:
>>> from sympy import I
>>> loggamma(5).evalf(30)
3.17805383034794561964694160130
>>> loggamma(I).evalf(20)
-0.65092319930185633889 - 1.8724366472624298171*I
See Also
========
gamma: Gamma function.
lowergamma: Lower incomplete gamma function.
uppergamma: Upper incomplete gamma function.
polygamma: Polygamma function.
digamma: Digamma function.
trigamma: Trigamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Gamma_function
.. [2] http://dlmf.nist.gov/5
.. [3] http://mathworld.wolfram.com/LogGammaFunction.html
.. [4] http://functions.wolfram.com/GammaBetaErf/LogGamma/
"""
@classmethod
def eval(cls, z):
if z.is_integer:
if z.is_nonpositive:
return oo
elif z.is_positive:
return log(gamma(z))
elif z.is_rational:
p, q = z.as_numer_denom()
# Half-integral values:
if p.is_positive and q == 2:
return log(sqrt(pi) * 2**(1 - p) * gamma(p) / gamma((p + 1)*S.Half))
if z is oo:
return oo
elif abs(z) is oo:
return S.ComplexInfinity
if z is S.NaN:
return S.NaN
def _eval_expand_func(self, **hints):
from sympy.concrete.summations import Sum
z = self.args[0]
if z.is_Rational:
p, q = z.as_numer_denom()
# General rational arguments (u + p/q)
# Split z as n + p/q with p < q
n = p // q
p = p - n*q
if p.is_positive and q.is_positive and p < q:
k = Dummy("k")
if n.is_positive:
return loggamma(p / q) - n*log(q) + Sum(log((k - 1)*q + p), (k, 1, n))
elif n.is_negative:
return loggamma(p / q) - n*log(q) + pi*I*n - Sum(log(k*q - p), (k, 1, -n))
elif n.is_zero:
return loggamma(p / q)
return self
def _eval_nseries(self, x, n, 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_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
if args0[0] != oo:
return super()._eval_aseries(n, args0, x, logx)
z = self.args[0]
r = log(z)*(z - S.Half) - z + log(2*pi)/2
l = [bernoulli(2*k) / (2*k*(2*k - 1)*z**(2*k - 1)) for k in range(1, n)]
o = None
if n == 0:
o = Order(1, x)
else:
o = Order(1/z**n, x)
# It is very inefficient to first add the order and then do the nseries
return (r + Add(*l))._eval_nseries(x, n, logx) + o
def _eval_rewrite_as_intractable(self, z, **kwargs):
return log(gamma(z))
def _eval_is_real(self):
z = self.args[0]
if z.is_positive:
return True
elif z.is_nonpositive:
return False
def _eval_conjugate(self):
z = self.args[0]
if z not in (S.Zero, S.NegativeInfinity):
return self.func(z.conjugate())
def fdiff(self, argindex=1):
if argindex == 1:
return polygamma(0, self.args[0])
else:
raise ArgumentIndexError(self, argindex)
class digamma(Function):
r"""
The ``digamma`` function is the first derivative of the ``loggamma``
function
.. math::
\psi(x) := \frac{\mathrm{d}}{\mathrm{d} z} \log\Gamma(z)
= \frac{\Gamma'(z)}{\Gamma(z) }.
In this case, ``digamma(z) = polygamma(0, z)``.
Examples
========
>>> from sympy import digamma
>>> digamma(0)
zoo
>>> from sympy import Symbol
>>> z = Symbol('z')
>>> digamma(z)
polygamma(0, z)
To retain ``digamma`` as it is:
>>> digamma(0, evaluate=False)
digamma(0)
>>> digamma(z, evaluate=False)
digamma(z)
See Also
========
gamma: Gamma function.
lowergamma: Lower incomplete gamma function.
uppergamma: Upper incomplete gamma function.
polygamma: Polygamma function.
loggamma: Log Gamma function.
trigamma: Trigamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Digamma_function
.. [2] http://mathworld.wolfram.com/DigammaFunction.html
.. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/
"""
def _eval_evalf(self, prec):
z = self.args[0]
nprec = prec_to_dps(prec)
return polygamma(0, z).evalf(n=nprec)
def fdiff(self, argindex=1):
z = self.args[0]
return polygamma(0, z).fdiff()
def _eval_is_real(self):
z = self.args[0]
return polygamma(0, z).is_real
def _eval_is_positive(self):
z = self.args[0]
return polygamma(0, z).is_positive
def _eval_is_negative(self):
z = self.args[0]
return polygamma(0, z).is_negative
def _eval_aseries(self, n, args0, x, logx):
as_polygamma = self.rewrite(polygamma)
args0 = [S.Zero,] + args0
return as_polygamma._eval_aseries(n, args0, x, logx)
@classmethod
def eval(cls, z):
return polygamma(0, z)
def _eval_expand_func(self, **hints):
z = self.args[0]
return polygamma(0, z).expand(func=True)
def _eval_rewrite_as_harmonic(self, z, **kwargs):
return harmonic(z - 1) - S.EulerGamma
def _eval_rewrite_as_polygamma(self, z, **kwargs):
return polygamma(0, z)
def _eval_as_leading_term(self, x, logx=None, cdir=0):
z = self.args[0]
return polygamma(0, z).as_leading_term(x)
class trigamma(Function):
r"""
The ``trigamma`` function is the second derivative of the ``loggamma``
function
.. math::
\psi^{(1)}(z) := \frac{\mathrm{d}^{2}}{\mathrm{d} z^{2}} \log\Gamma(z).
In this case, ``trigamma(z) = polygamma(1, z)``.
Examples
========
>>> from sympy import trigamma
>>> trigamma(0)
zoo
>>> from sympy import Symbol
>>> z = Symbol('z')
>>> trigamma(z)
polygamma(1, z)
To retain ``trigamma`` as it is:
>>> trigamma(0, evaluate=False)
trigamma(0)
>>> trigamma(z, evaluate=False)
trigamma(z)
See Also
========
gamma: Gamma function.
lowergamma: Lower incomplete gamma function.
uppergamma: Upper incomplete gamma function.
polygamma: Polygamma function.
loggamma: Log Gamma function.
digamma: Digamma function.
beta: Euler Beta function.
References
==========
.. [1] https://en.wikipedia.org/wiki/Trigamma_function
.. [2] http://mathworld.wolfram.com/TrigammaFunction.html
.. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/
"""
def _eval_evalf(self, prec):
z = self.args[0]
nprec = prec_to_dps(prec)
return polygamma(1, z).evalf(n=nprec)
def fdiff(self, argindex=1):
z = self.args[0]
return polygamma(1, z).fdiff()
def _eval_is_real(self):
z = self.args[0]
return polygamma(1, z).is_real
def _eval_is_positive(self):
z = self.args[0]
return polygamma(1, z).is_positive
def _eval_is_negative(self):
z = self.args[0]
return polygamma(1, z).is_negative
def _eval_aseries(self, n, args0, x, logx):
as_polygamma = self.rewrite(polygamma)
args0 = [S.One,] + args0
return as_polygamma._eval_aseries(n, args0, x, logx)
@classmethod
def eval(cls, z):
return polygamma(1, z)
def _eval_expand_func(self, **hints):
z = self.args[0]
return polygamma(1, z).expand(func=True)
def _eval_rewrite_as_zeta(self, z, **kwargs):
return zeta(2, z)
def _eval_rewrite_as_polygamma(self, z, **kwargs):
return polygamma(1, z)
def _eval_rewrite_as_harmonic(self, z, **kwargs):
return -harmonic(z - 1, 2) + pi**2 / 6
def _eval_as_leading_term(self, x, logx=None, cdir=0):
z = self.args[0]
return polygamma(1, z).as_leading_term(x)
###############################################################################
##################### COMPLETE MULTIVARIATE GAMMA FUNCTION ####################
###############################################################################
class multigamma(Function):
r"""
The multivariate gamma function is a generalization of the gamma function
.. math::
\Gamma_p(z) = \pi^{p(p-1)/4}\prod_{k=1}^p \Gamma[z + (1 - k)/2].
In a special case, ``multigamma(x, 1) = gamma(x)``.
Examples
========
>>> from sympy import S, multigamma
>>> from sympy import Symbol
>>> x = Symbol('x')
>>> p = Symbol('p', positive=True, integer=True)
>>> multigamma(x, p)
pi**(p*(p - 1)/4)*Product(gamma(-_k/2 + x + 1/2), (_k, 1, p))
Several special values are known:
>>> multigamma(1, 1)
1
>>> multigamma(4, 1)
6
>>> multigamma(S(3)/2, 1)
sqrt(pi)/2
Writing ``multigamma`` in terms of the ``gamma`` function:
>>> multigamma(x, 1)
gamma(x)
>>> multigamma(x, 2)
sqrt(pi)*gamma(x)*gamma(x - 1/2)
>>> multigamma(x, 3)
pi**(3/2)*gamma(x)*gamma(x - 1)*gamma(x - 1/2)
Parameters
==========
p : order or dimension of the multivariate gamma function
See Also
========
gamma, lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma,
beta
References
==========
.. [1] https://en.wikipedia.org/wiki/Multivariate_gamma_function
"""
unbranched = True
def fdiff(self, argindex=2):
from sympy.concrete.summations import Sum
if argindex == 2:
x, p = self.args
k = Dummy("k")
return self.func(x, p)*Sum(polygamma(0, x + (1 - k)/2), (k, 1, p))
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, x, p):
from sympy.concrete.products import Product
if p.is_positive is False or p.is_integer is False:
raise ValueError('Order parameter p must be positive integer.')
k = Dummy("k")
return (pi**(p*(p - 1)/4)*Product(gamma(x + (1 - k)/2),
(k, 1, p))).doit()
def _eval_conjugate(self):
x, p = self.args
return self.func(x.conjugate(), p)
def _eval_is_real(self):
x, p = self.args
y = 2*x
if y.is_integer and (y <= (p - 1)) is True:
return False
if intlike(y) and (y <= (p - 1)):
return False
if y > (p - 1) or y.is_noninteger:
return True
|
08e768f35d2af2f8d5c8788e62c803e537001381b76d0533417944ae80d6b23d | 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 (Float, 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, Limit
from sympy.series.order import O
from sympy.functions import (
bernoulli, harmonic, bell, fibonacci, tribonacci, lucas, euler, catalan,
genocchi, andre, partition, motzkin, binomial, gamma, sqrt, cbrt, hyper, log, digamma,
trigamma, polygamma, factorial, sin, cos, cot, polylog, zeta, dirichlet_eta)
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 raises, nocache_fail, warns_deprecated_sympy
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]
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))
with warns_deprecated_sympy():
assert carmichael.is_prime(2821) == False
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
assert bernoulli(x, 1) == bernoulli(x)
assert str(bernoulli(0.0, 2.3).evalf(n=10)) == '1.000000000'
assert str(bernoulli(1.0).evalf(n=10)) == '0.5000000000'
assert str(bernoulli(1.2).evalf(n=10)) == '0.4195995367'
assert str(bernoulli(1.2, 0.8).evalf(n=10)) == '0.2144830348'
assert str(bernoulli(1.2, -0.8).evalf(n=10)) == '-1.158865646 - 0.6745558744*I'
assert str(bernoulli(3.0, 1j).evalf(n=10)) == '1.5 - 0.5*I'
assert str(bernoulli(I).evalf(n=10)) == '0.9268485643 - 0.5821580598*I'
assert str(bernoulli(I, I).evalf(n=10)) == '0.1267792071 + 0.01947413152*I'
assert bernoulli(x).evalf() == bernoulli(x)
def test_bernoulli_rewrite():
from sympy.functions.elementary.piecewise import Piecewise
n = Symbol('n', integer=True, nonnegative=True)
assert bernoulli(-1).rewrite(zeta) == pi**2/6
assert bernoulli(-2).rewrite(zeta) == 2*zeta(3)
assert not bernoulli(n, -3).rewrite(zeta).has(harmonic)
assert bernoulli(-4, x).rewrite(zeta) == 4*zeta(5, x)
assert isinstance(bernoulli(n, x).rewrite(zeta), Piecewise)
assert bernoulli(n+1, x).rewrite(zeta) == -(n+1) * zeta(-n, x)
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() == \
Float(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() == \
Float(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) == 1
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
assert harmonic(-1, -1) == 0
assert harmonic(-1, 0) == -1
assert harmonic(-1, 1) is S.ComplexInfinity
assert harmonic(-1, 2) is S.NaN
assert harmonic(-3, -2) == -5
assert harmonic(-3, -3) == 9
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
assert str(harmonic(4.0, -3).evalf(n=10)) == '100.0000000'
assert str(harmonic(7.0, 1.0).evalf(n=10)) == '2.592857143'
assert str(harmonic(1, pi).evalf(n=10)) == '1.000000000'
assert str(harmonic(2, pi).evalf(n=10)) == '1.113314732'
assert str(harmonic(1000.0, pi).evalf(n=10)) == '1.176241563'
assert str(harmonic(I).evalf(n=10)) == '0.6718659855 + 1.076674047*I'
assert str(harmonic(I, I).evalf(n=10)) == '-0.3970915266 + 1.9629689*I'
assert harmonic(-1.0, 1).evalf() is S.NaN
assert harmonic(-2.0, 2.0).evalf() is S.NaN
def test_harmonic_rewrite():
from sympy.functions.elementary.piecewise import Piecewise
n = Symbol("n")
m = Symbol("m", integer=True, positive=True)
x1 = Symbol("x1", positive=True)
x2 = Symbol("x2", negative=True)
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 isinstance(harmonic(n,m).rewrite(polygamma), Piecewise)
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)
assert harmonic(n, x1).rewrite("tractable") == harmonic(n, x1)
assert harmonic(n, x1 + 1).rewrite("tractable") == zeta(x1 + 1) - zeta(x1 + 1, n + 1)
assert harmonic(n, x2).rewrite("tractable") == zeta(x2) - zeta(x2, n + 1)
_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)))
def test_harmonic_calculus():
y = Symbol("y", positive=True)
z = Symbol("z", negative=True)
assert harmonic(x, 1).limit(x, 0) == 0
assert harmonic(x, y).limit(x, 0) == 0
assert harmonic(x, 1).series(x, y, 2) == \
harmonic(y) + (x - y)*zeta(2, y + 1) + O((x - y)**2, (x, y))
assert limit(harmonic(x, y), x, oo) == harmonic(oo, y)
assert limit(harmonic(x, y + 1), x, oo) == zeta(y + 1)
assert limit(harmonic(x, y - 1), x, oo) == harmonic(oo, y - 1)
assert limit(harmonic(x, z), x, oo) == Limit(harmonic(x, z), x, oo, dir='-')
assert limit(harmonic(x, z + 1), x, oo) == oo
assert limit(harmonic(x, z + 2), x, oo) == harmonic(oo, z + 2)
assert limit(harmonic(x, z - 1), x, oo) == Limit(harmonic(x, z - 1), x, oo, dir='-')
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
assert euler(-1) == S.Pi / 2
assert euler(-1, 1) == 2*log(2)
assert euler(-2).evalf() == (2*S.Catalan).evalf()
assert euler(-3).evalf() == (S.Pi**3 / 16).evalf()
assert str(euler(2.3).evalf(n=10)) == '-1.052850274'
assert str(euler(1.2, 3.4).evalf(n=10)) == '3.575613489'
assert str(euler(I).evalf(n=10)) == '1.248446443 - 0.7675445124*I'
assert str(euler(I, I).evalf(n=10)) == '0.04812930469 + 0.01052411008*I'
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
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 = [0, -1, -1, 0, 1, 0, -3, 0, 17]
for n, g in enumerate(genocchis):
assert genocchi(n) == g
m = Symbol('m', integer=True)
n = Symbol('n', integer=True, positive=True)
assert unchanged(genocchi, m)
assert genocchi(2*n + 1) == 0
gn = 2 * (1 - 2**n) * bernoulli(n)
assert genocchi(n).rewrite(bernoulli).factor() == gn.factor()
gnx = 2 * (bernoulli(n, x) - 2**n * bernoulli(n, (x+1) / 2))
assert genocchi(n, x).rewrite(bernoulli).factor() == gnx.factor()
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
g0 = genocchi(0, evaluate=False)
assert g0.is_positive is False
assert g0.is_negative is False
assert g0.is_even is True
assert g0.is_odd is False
assert genocchi(0, x) == 0
assert genocchi(1, x) == -1
assert genocchi(2, x) == 1 - 2*x
assert genocchi(3, x) == 3*x - 3*x**2
assert genocchi(4, x) == -1 + 6*x**2 - 4*x**3
y = Symbol("y")
assert genocchi(5, (x+y)**100) == -5*(x+y)**400 + 10*(x+y)**300 - 5*(x+y)**100
assert str(genocchi(5.0, 4.0).evalf(n=10)) == '-660.0000000'
assert str(genocchi(Rational(5, 4)).evalf(n=10)) == '-1.104286457'
assert str(genocchi(-2).evalf(n=10)) == '3.606170709'
assert str(genocchi(1.3, 3.7).evalf(n=10)) == '-1.847375373'
assert str(genocchi(I, 1.0).evalf(n=10)) == '-0.3161917278 - 1.45311955*I'
n = Symbol('n')
assert genocchi(n, x).rewrite(dirichlet_eta) == -2*n * dirichlet_eta(1-n, x)
def test_andre():
nums = [1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
for n, a in enumerate(nums):
assert andre(n) == a
assert andre(S.Infinity) == S.Infinity
assert andre(-1) == -log(2)
assert andre(-2) == -2*S.Catalan
assert andre(-3) == 3*zeta(3)/16
assert andre(-5) == -15*zeta(5)/256
# In fact andre(-2*n) is related to the Dirichlet *beta* function
# at 2*n, but SymPy doesn't implement that (or general L-functions)
assert unchanged(andre, -4)
n = Symbol('n', integer=True, nonnegative=True)
assert unchanged(andre, n)
assert andre(n).is_integer is True
assert andre(n).is_positive is True
assert str(andre(10, evaluate=False).evalf(n=10)) == '50521.00000'
assert str(andre(-1, evaluate=False).evalf(n=10)) == '-0.6931471806'
assert str(andre(-2, evaluate=False).evalf(n=10)) == '-1.831931188'
assert str(andre(-4, evaluate=False).evalf(n=10)) == '1.977889103'
assert str(andre(I, evaluate=False).evalf(n=10)) == '2.378417833 + 0.6343322845*I'
assert andre(x).rewrite(polylog) == \
(-I)**(x+1) * polylog(-x, I) + I**(x+1) * polylog(-x, -I)
assert andre(x).rewrite(zeta) == \
2 * gamma(x+1) / (2*pi)**(x+1) * \
(zeta(x+1, Rational(1,4)) - cos(pi*x) * zeta(x+1, Rational(3,4)))
@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 sympy.core.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}))
|
c6c7f9377d082dbfe6769c7a09be44d28d506395788a6a435f6c2a00d2675c11 | from sympy.calculus.accumulationbounds import AccumBounds
from sympy.core.add import Add
from sympy.core.function import (Lambda, diff)
from sympy.core.mod import Mod
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')
z = symbols('z', imaginary=True)
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(z*I) == I*sinh(z)
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(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) == \
Piecewise((0, Eq(im(x), 0) & Eq(Mod(x, pi), 0)),
(2*cot(x/2)/(cot(x/2)**2 + 1), True))
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
assert cos(0, evaluate=False).is_zero is False
assert cos(Rational(1, 2)).is_zero is False
# The following test will return None as the result, but really it should
# be True even if it is not always possible to resolve an assumptions query.
assert cos(asin(-1, evaluate=False), evaluate=False).is_zero is None
for d in list(range(1, 22)) + [60, 85]:
for n in range(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) == \
Piecewise((1, Eq(im(x), 0) & Eq(Mod(x, 2*pi), 0)),
((cot(x/2)**2 - 1)/(cot(x/2)**2 + 1), True))
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 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))
@slow
def test_tan_rewrite_slow():
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(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(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))
@slow
def test_cot_rewrite_slow():
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(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(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_leading_term():
assert asin(x).as_leading_term(x) == x
# Tests concerning branch points
assert asin(x + 1).as_leading_term(x) == pi/2
assert asin(x - 1).as_leading_term(x) == -pi/2
assert asin(1/x).as_leading_term(x, cdir=1) == I*log(x) + pi/2 - I*log(2)
assert asin(1/x).as_leading_term(x, cdir=-1) == -I*log(x) - 3*pi/2 + I*log(2)
# Tests concerning points lying on branch cuts
assert asin(I*x + 2).as_leading_term(x, cdir=1) == pi - asin(2)
assert asin(-I*x + 2).as_leading_term(x, cdir=1) == asin(2)
assert asin(I*x - 2).as_leading_term(x, cdir=1) == -asin(2)
assert asin(-I*x - 2).as_leading_term(x, cdir=1) == -pi + asin(2)
# Tests concerning im(ndir) == 0
assert asin(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == -pi/2 + I*log(2 - sqrt(3))
assert asin(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(2 - sqrt(3))
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(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_leading_term():
assert acos(x).as_leading_term(x) == pi/2
# Tests concerning branch points
assert acos(x + 1).as_leading_term(x) == sqrt(2)*sqrt(-x)
assert acos(x - 1).as_leading_term(x) == pi
assert acos(1/x).as_leading_term(x, cdir=1) == -I*log(x) + I*log(2)
assert acos(1/x).as_leading_term(x, cdir=-1) == I*log(x) + 2*pi - I*log(2)
# Tests concerning points lying on branch cuts
assert acos(I*x + 2).as_leading_term(x, cdir=1) == -acos(2)
assert acos(-I*x + 2).as_leading_term(x, cdir=1) == acos(2)
assert acos(I*x - 2).as_leading_term(x, cdir=1) == acos(-2)
assert acos(-I*x - 2).as_leading_term(x, cdir=1) == 2*pi - acos(-2)
# Tests concerning im(ndir) == 0
assert acos(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == pi + I*log(sqrt(3) + 2)
assert acos(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == pi + I*log(sqrt(3) + 2)
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) == pi*(-x*sqrt(x**(-2)) + 1)/2 + atan(sqrt(1 - x**2)/x)
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(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_atan_leading_term():
assert atan(x).as_leading_term(x) == x
assert atan(1/x).as_leading_term(x, cdir=1) == pi/2
assert atan(1/x).as_leading_term(x, cdir=-1) == -pi/2
# Tests concerning branch points
assert atan(x + I).as_leading_term(x, cdir=1) == -I*log(x)/2 + pi/4 + I*log(2)/2
assert atan(x + I).as_leading_term(x, cdir=-1) == -I*log(x)/2 - 3*pi/4 + I*log(2)/2
assert atan(x - I).as_leading_term(x, cdir=1) == I*log(x)/2 + pi/4 - I*log(2)/2
assert atan(x - I).as_leading_term(x, cdir=-1) == I*log(x)/2 + pi/4 - I*log(2)/2
# Tests concerning points lying on branch cuts
assert atan(x + 2*I).as_leading_term(x, cdir=1) == I*atanh(2)
assert atan(x + 2*I).as_leading_term(x, cdir=-1) == -pi + I*atanh(2)
assert atan(x - 2*I).as_leading_term(x, cdir=1) == pi - I*atanh(2)
assert atan(x - 2*I).as_leading_term(x, cdir=-1) == -I*atanh(2)
# Tests concerning re(ndir) == 0
assert atan(2*I - I*x - x**2).as_leading_term(x, cdir=1) == -pi/2 + I*log(3)/2
assert atan(2*I - I*x - x**2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(3)/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(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_acot_leading_term():
assert acot(1/x).as_leading_term(x) == x
# Tests concerning branch points
assert acot(x + I).as_leading_term(x, cdir=1) == I*log(x)/2 + pi/4 - I*log(2)/2
assert acot(x + I).as_leading_term(x, cdir=-1) == I*log(x)/2 + pi/4 - I*log(2)/2
assert acot(x - I).as_leading_term(x, cdir=1) == -I*log(x)/2 + pi/4 + I*log(2)/2
assert acot(x - I).as_leading_term(x, cdir=-1) == -I*log(x)/2 - 3*pi/4 + I*log(2)/2
# Tests concerning points lying on branch cuts
assert acot(x).as_leading_term(x, cdir=1) == pi/2
assert acot(x).as_leading_term(x, cdir=-1) == -pi/2
assert acot(x + I/2).as_leading_term(x, cdir=1) == pi - I*acoth(S(1)/2)
assert acot(x + I/2).as_leading_term(x, cdir=-1) == -I*acoth(S(1)/2)
assert acot(x - I/2).as_leading_term(x, cdir=1) == I*acoth(S(1)/2)
assert acot(x - I/2).as_leading_term(x, cdir=-1) == -pi + I*acoth(S(1)/2)
# Tests concerning re(ndir) == 0
assert acot(I/2 - I*x - x**2).as_leading_term(x, cdir=1) == -pi/2 - I*log(3)/2
assert acot(I/2 - I*x - x**2).as_leading_term(x, cdir=-1) == -pi/2 - I*log(3)/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_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
def test_leading_terms():
assert sin(1/x).as_leading_term(x) == AccumBounds(-1, 1)
assert sin(S.Half).as_leading_term(x) == sin(S.Half)
assert cos(1/x).as_leading_term(x) == AccumBounds(-1, 1)
assert cos(S.Half).as_leading_term(x) == cos(S.Half)
assert sec(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
assert csc(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
assert tan(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
assert cot(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
# https://github.com/sympy/sympy/issues/21038
f = sin(pi*(x + 4))/(3*x)
assert f.as_leading_term(x) == pi/3
def test_atan2_expansion():
assert cancel(atan2(x**2, x + 1).diff(x) - atan(x**2/(x + 1)).diff(x)) == 0
assert cancel(atan(y/x).series(y, 0, 5) - atan2(y, x).series(y, 0, 5)
+ atan2(0, x) - atan(0)) == O(y**5)
assert cancel(atan(y/x).series(x, 1, 4) - atan2(y, x).series(x, 1, 4)
+ atan2(y, 1) - atan(y)) == O((x - 1)**4, (x, 1))
assert cancel(atan((y + x)/x).series(x, 1, 3) - atan2(y + x, x).series(x, 1, 3)
+ atan2(1 + y, 1) - atan(1 + y)) == O((x - 1)**3, (x, 1))
assert Matrix([atan2(y, x)]).jacobian([y, x]) == \
Matrix([[x/(y**2 + x**2), -y/(y**2 + x**2)]])
def test_aseries():
def t(n, v, d, e):
assert abs(
n(1/v).evalf() - n(1/x).series(x, dir=d).removeO().subs(x, v)) < e
t(atan, 0.1, '+', 1e-5)
t(atan, -0.1, '-', 1e-5)
t(acot, 0.1, '+', 1e-5)
t(acot, -0.1, '-', 1e-5)
def test_issue_4420():
i = Symbol('i', integer=True)
e = Symbol('e', even=True)
o = Symbol('o', odd=True)
# unknown parity for variable
assert cos(4*i*pi) == 1
assert sin(4*i*pi) == 0
assert tan(4*i*pi) == 0
assert cot(4*i*pi) is zoo
assert cos(3*i*pi) == cos(pi*i) # +/-1
assert sin(3*i*pi) == 0
assert tan(3*i*pi) == 0
assert cot(3*i*pi) is zoo
assert cos(4.0*i*pi) == 1
assert sin(4.0*i*pi) == 0
assert tan(4.0*i*pi) == 0
assert cot(4.0*i*pi) is zoo
assert cos(3.0*i*pi) == cos(pi*i) # +/-1
assert sin(3.0*i*pi) == 0
assert tan(3.0*i*pi) == 0
assert cot(3.0*i*pi) is zoo
assert cos(4.5*i*pi) == cos(0.5*pi*i)
assert sin(4.5*i*pi) == sin(0.5*pi*i)
assert tan(4.5*i*pi) == tan(0.5*pi*i)
assert cot(4.5*i*pi) == cot(0.5*pi*i)
# parity of variable is known
assert cos(4*e*pi) == 1
assert sin(4*e*pi) == 0
assert tan(4*e*pi) == 0
assert cot(4*e*pi) is zoo
assert cos(3*e*pi) == 1
assert sin(3*e*pi) == 0
assert tan(3*e*pi) == 0
assert cot(3*e*pi) is zoo
assert cos(4.0*e*pi) == 1
assert sin(4.0*e*pi) == 0
assert tan(4.0*e*pi) == 0
assert cot(4.0*e*pi) is zoo
assert cos(3.0*e*pi) == 1
assert sin(3.0*e*pi) == 0
assert tan(3.0*e*pi) == 0
assert cot(3.0*e*pi) is zoo
assert cos(4.5*e*pi) == cos(0.5*pi*e)
assert sin(4.5*e*pi) == sin(0.5*pi*e)
assert tan(4.5*e*pi) == tan(0.5*pi*e)
assert cot(4.5*e*pi) == cot(0.5*pi*e)
assert cos(4*o*pi) == 1
assert sin(4*o*pi) == 0
assert tan(4*o*pi) == 0
assert cot(4*o*pi) is zoo
assert cos(3*o*pi) == -1
assert sin(3*o*pi) == 0
assert tan(3*o*pi) == 0
assert cot(3*o*pi) is zoo
assert cos(4.0*o*pi) == 1
assert sin(4.0*o*pi) == 0
assert tan(4.0*o*pi) == 0
assert cot(4.0*o*pi) is zoo
assert cos(3.0*o*pi) == -1
assert sin(3.0*o*pi) == 0
assert tan(3.0*o*pi) == 0
assert cot(3.0*o*pi) is zoo
assert cos(4.5*o*pi) == cos(0.5*pi*o)
assert sin(4.5*o*pi) == sin(0.5*pi*o)
assert tan(4.5*o*pi) == tan(0.5*pi*o)
assert cot(4.5*o*pi) == cot(0.5*pi*o)
# x could be imaginary
assert cos(4*x*pi) == cos(4*pi*x)
assert sin(4*x*pi) == sin(4*pi*x)
assert tan(4*x*pi) == tan(4*pi*x)
assert cot(4*x*pi) == cot(4*pi*x)
assert cos(3*x*pi) == cos(3*pi*x)
assert sin(3*x*pi) == sin(3*pi*x)
assert tan(3*x*pi) == tan(3*pi*x)
assert cot(3*x*pi) == cot(3*pi*x)
assert cos(4.0*x*pi) == cos(4.0*pi*x)
assert sin(4.0*x*pi) == sin(4.0*pi*x)
assert tan(4.0*x*pi) == tan(4.0*pi*x)
assert cot(4.0*x*pi) == cot(4.0*pi*x)
assert cos(3.0*x*pi) == cos(3.0*pi*x)
assert sin(3.0*x*pi) == sin(3.0*pi*x)
assert tan(3.0*x*pi) == tan(3.0*pi*x)
assert cot(3.0*x*pi) == cot(3.0*pi*x)
assert cos(4.5*x*pi) == cos(4.5*pi*x)
assert sin(4.5*x*pi) == sin(4.5*pi*x)
assert tan(4.5*x*pi) == tan(4.5*pi*x)
assert cot(4.5*x*pi) == cot(4.5*pi*x)
def test_inverses():
raises(AttributeError, lambda: sin(x).inverse())
raises(AttributeError, lambda: cos(x).inverse())
assert tan(x).inverse() == atan
assert cot(x).inverse() == acot
raises(AttributeError, lambda: csc(x).inverse())
raises(AttributeError, lambda: sec(x).inverse())
assert asin(x).inverse() == sin
assert acos(x).inverse() == cos
assert atan(x).inverse() == tan
assert acot(x).inverse() == cot
def test_real_imag():
a, b = symbols('a b', real=True)
z = a + b*I
for deep in [True, False]:
assert sin(
z).as_real_imag(deep=deep) == (sin(a)*cosh(b), cos(a)*sinh(b))
assert cos(
z).as_real_imag(deep=deep) == (cos(a)*cosh(b), -sin(a)*sinh(b))
assert tan(z).as_real_imag(deep=deep) == (sin(2*a)/(cos(2*a) +
cosh(2*b)), sinh(2*b)/(cos(2*a) + cosh(2*b)))
assert cot(z).as_real_imag(deep=deep) == (-sin(2*a)/(cos(2*a) -
cosh(2*b)), sinh(2*b)/(cos(2*a) - cosh(2*b)))
assert sin(a).as_real_imag(deep=deep) == (sin(a), 0)
assert cos(a).as_real_imag(deep=deep) == (cos(a), 0)
assert tan(a).as_real_imag(deep=deep) == (tan(a), 0)
assert cot(a).as_real_imag(deep=deep) == (cot(a), 0)
@XFAIL
def test_sin_cos_with_infinity():
# Test for issue 5196
# https://github.com/sympy/sympy/issues/5196
assert sin(oo) is S.NaN
assert cos(oo) is S.NaN
@slow
def test_sincos_rewrite_sqrt():
# equivalent to testing rewrite(pow)
for p in [1, 3, 5, 17]:
for t in [1, 8]:
n = t*p
# The vertices `exp(i*pi/n)` of a regular `n`-gon can
# be expressed by means of nested square roots if and
# only if `n` is a product of Fermat primes, `p`, and
# powers of 2, `t'. The code aims to check all vertices
# not belonging to an `m`-gon for `m < n`(`gcd(i, n) == 1`).
# For large `n` this makes the test too slow, therefore
# the vertices are limited to those of index `i < 10`.
for i in range(1, min((n + 1)//2 + 1, 10)):
if 1 == gcd(i, n):
x = i*pi/n
s1 = sin(x).rewrite(sqrt)
c1 = cos(x).rewrite(sqrt)
assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
assert 1e-3 > abs(sin(x.evalf(5)) - s1.evalf(2)), "fails for %d*pi/%d" % (i, n)
assert 1e-3 > abs(cos(x.evalf(5)) - c1.evalf(2)), "fails for %d*pi/%d" % (i, n)
assert cos(pi/14).rewrite(sqrt) == sqrt(cos(pi/7)/2 + S.Half)
assert cos(pi*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_sincos_rewrite_sqrt_257():
assert cos(pi/257).rewrite(sqrt).evalf(64) == cos(pi/257).evalf(64)
@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).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) == \
pi*(1 - sqrt(x**2)/x)/2 + sqrt(x**2)*atan(sqrt(x**2 - 1))/x
assert asec(x).rewrite(acot) == \
pi*(1 - sqrt(x**2)/x)/2 + sqrt(x**2)*acot(1/sqrt(x**2 - 1))/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_asec_leading_term():
assert asec(1/x).as_leading_term(x) == pi/2
# Tests concerning branch points
assert asec(x + 1).as_leading_term(x) == sqrt(2)*sqrt(x)
assert asec(x - 1).as_leading_term(x) == pi
# Tests concerning points lying on branch cuts
assert asec(x).as_leading_term(x, cdir=1) == -I*log(x) + I*log(2)
assert asec(x).as_leading_term(x, cdir=-1) == I*log(x) + 2*pi - I*log(2)
assert asec(I*x + 1/2).as_leading_term(x, cdir=1) == asec(1/2)
assert asec(-I*x + 1/2).as_leading_term(x, cdir=1) == -asec(1/2)
assert asec(I*x - 1/2).as_leading_term(x, cdir=1) == 2*pi - asec(-1/2)
assert asec(-I*x - 1/2).as_leading_term(x, cdir=1) == asec(-1/2)
# Tests concerning im(ndir) == 0
assert asec(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=1) == pi + I*log(2 - sqrt(3))
assert asec(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=-1) == pi + I*log(2 - sqrt(3))
def test_asec_series():
assert asec(x).series(x, 0, 9) == \
I*log(2) - I*log(x) - I*x**2/4 - 3*I*x**4/32 \
- 5*I*x**6/96 - 35*I*x**8/1024 + O(x**9)
t4 = asec(x).taylor_term(4, x)
assert t4 == -3*I*x**4/32
assert asec(x).taylor_term(6, x, t4, 0) == -5*I*x**6/96
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).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_acsc_leading_term():
assert acsc(1/x).as_leading_term(x) == x
# Tests concerning branch points
assert acsc(x + 1).as_leading_term(x) == pi/2
assert acsc(x - 1).as_leading_term(x) == -pi/2
# Tests concerning points lying on branch cuts
assert acsc(x).as_leading_term(x, cdir=1) == I*log(x) + pi/2 - I*log(2)
assert acsc(x).as_leading_term(x, cdir=-1) == -I*log(x) - 3*pi/2 + I*log(2)
assert acsc(I*x + 1/2).as_leading_term(x, cdir=1) == acsc(1/2)
assert acsc(-I*x + 1/2).as_leading_term(x, cdir=1) == pi - acsc(1/2)
assert acsc(I*x - 1/2).as_leading_term(x, cdir=1) == -pi - acsc(-1/2)
assert acsc(-I*x - 1/2).as_leading_term(x, cdir=1) == -acsc(1/2)
# Tests concerning im(ndir) == 0
assert acsc(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=1) == -pi/2 + I*log(sqrt(3) + 2)
assert acsc(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(sqrt(3) + 2)
def test_acsc_series():
assert acsc(x).series(x, 0, 9) == \
-I*log(2) + pi/2 + I*log(x) + I*x**2/4 \
+ 3*I*x**4/32 + 5*I*x**6/96 + 35*I*x**8/1024 + O(x**9)
t6 = acsc(x).taylor_term(6, x)
assert t6 == 5*I*x**6/96
assert acsc(x).taylor_term(8, x, t6, 0) == 35*I*x**8/1024
def test_asin_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)
# testing nseries for asin at branch points
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)
def test_acos_nseries():
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)
# testing nseries for acos at branch points
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)
def test_atan_nseries():
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(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)
# testing nseries for atan at branch points
assert atan(x + I)._eval_nseries(x, 4, None) == I*log(2)/2 + pi/4 - \
I*log(x)/2 + x/4 + I*x**2/16 - x**3/48 + O(x**4)
assert atan(x - I)._eval_nseries(x, 4, None) == -I*log(2)/2 + pi/4 + \
I*log(x)/2 + x/4 - I*x**2/16 - x**3/48 + O(x**4)
def test_acot_nseries():
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)._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)
# testing nseries for acot at branch points
assert acot(x + I)._eval_nseries(x, 4, None) == -I*log(2)/2 + pi/4 + \
I*log(x)/2 - x/4 - I*x**2/16 + x**3/48 + O(x**4)
assert acot(x - I)._eval_nseries(x, 4, None) == I*log(2)/2 + pi/4 - \
I*log(x)/2 - x/4 + I*x**2/16 + x**3/48 + O(x**4)
def test_asec_nseries():
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)
# testing nseries for asec at branch points
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)
def test_acsc_nseries():
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)
# testing nseries for acsc at branch points
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
|
419a56c392aaf43d66f26c65802542512b32e8deac2d559f6e399603047e1273 | from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.expr import unchanged
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, piecewise_exclusive, Undefined, ExprCondPair)
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.printing import srepr
from sympy.sets.contains import Contains
from sympy.sets.sets import Interval
from sympy.solvers.solvers import solve
from sympy.testing.pytest import raises, slow
from sympy.utilities.lambdify import lambdify
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() == Piecewise((-1.0, x < -1), (x**2, x < 0), (log(x), True))
assert p.evalf(subs={x: -2}) == -1.0
assert p.evalf(subs={x: -1}) == 1.0
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)
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)
b = Symbol('b', real=True)
x = Symbol('x', real=True)
y = Symbol('y', real=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), (S.Half, x > b), (1, True))
p2 = Piecewise((S.Half, x > b), (0, x < a), (1, True))
p3 = Piecewise((0, x < a), (1, x < b), (S.Half, True))
p4 = Piecewise((S.Half, x > b), (1, x > a), (0, True))
p5 = Piecewise((1, And(a < x, x < b)), (S.Half, 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_issue_22917():
p = (Piecewise((0, ITE((x - y > 1) | (2 * x - 2 * y > 1), False,
ITE(x - y > 1, 2 * y - 2 < -1, 2 * x - 2 * y > 1))),
(Piecewise((0, ITE(x - y > 1, True, 2 * x - 2 * y > 1)),
(2 * Piecewise((0, x - y > 1), (y, True)), True)), True))
+ 2 * Piecewise((1, ITE((x - y > 1) | (2 * x - 2 * y > 1), False,
ITE(x - y > 1, 2 * y - 2 < -1, 2 * x - 2 * y > 1))),
(Piecewise((1, ITE(x - y > 1, True, 2 * x - 2 * y > 1)),
(2 * Piecewise((1, x - y > 1), (x, True)), True)), True)))
assert piecewise_fold(p) == Piecewise((2, (x - y > S.Half) | (x - y > 1)),
(2*y + 4, x - y > 1),
(4*x + 2*y, True))
assert piecewise_fold(p > 1).rewrite(ITE) == ITE((x - y > S.Half) | (x - y > 1), True,
ITE(x - y > 1, 2*y + 4 > 1, 4*x + 2*y > 1))
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", 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
# issue 22747
p = Piecewise((0, (t < -2) & (t < -1) & (t < 0)), ((t/2 + 1)*(t +
1)*(t + 2), (t < -1) & (t < 0)), ((S.Half - t/2)*(1 - t)*(t + 1),
(t < -2) & (t < -1) & (t < 1)), ((t + 1)*(-t*(t/2 + 1) + (S.Half
- t/2)*(1 - t)), (t < -2) & (t < -1) & (t < 0) & (t < 1)), ((t +
1)*((S.Half - t/2)*(1 - t) + (t/2 + 1)*(t + 2)), (t < -1) & (t <
1)), ((t + 1)*(-t*(t/2 + 1) + (S.Half - t/2)*(1 - t)), (t < -1) &
(t < 0) & (t < 1)), (0, (t < -2) & (t < -1)), ((t/2 + 1)*(t +
1)*(t + 2), t < -1), ((t + 1)*(-t*(t/2 + 1) + (S.Half - t/2)*(t +
1)), (t < 0) & ((t < -2) | (t < 0))), ((S.Half - t/2)*(1 - t)*(t
+ 1), (t < 1) & ((t < -2) | (t < 1))), (0, True)) + Piecewise((0,
(t < -1) & (t < 0) & (t < 1)), ((1 - t)*(t/2 + S.Half)*(t + 1),
(t < 0) & (t < 1)), ((1 - t)*(1 - t/2)*(2 - t), (t < -1) & (t <
0) & (t < 2)), ((1 - t)*((1 - t)*(t/2 + S.Half) + (1 - t/2)*(2 -
t)), (t < -1) & (t < 0) & (t < 1) & (t < 2)), ((1 - t)*((1 -
t/2)*(2 - t) + (t/2 + S.Half)*(t + 1)), (t < 0) & (t < 2)), ((1 -
t)*((1 - t)*(t/2 + S.Half) + (1 - t/2)*(2 - t)), (t < 0) & (t <
1) & (t < 2)), (0, (t < -1) & (t < 0)), ((1 - t)*(t/2 +
S.Half)*(t + 1), t < 0), ((1 - t)*(t*(1 - t/2) + (1 - t)*(t/2 +
S.Half)), (t < 1) & ((t < -1) | (t < 1))), ((1 - t)*(1 - t/2)*(2
- t), (t < 2) & ((t < -1) | (t < 2))), (0, True))
assert p.simplify() == Piecewise(
(0, t < -2), ((t + 1)*(t + 2)**2/2, t < -1), (-3*t**3/2
- 5*t**2/2 + 1, t < 0), (3*t**3/2 - 5*t**2/2 + 1, t < 1), ((1 -
t)*(t - 2)**2/2, t < 2), (0, True))
# coverage
nan = Undefined
covered = Piecewise((1, x > 3), (2, x < 2), (3, x > 1))
assert covered.simplify().args == covered.args
assert Piecewise((1, x < 2), (2, x < 1), (3, True)).simplify(
) == Piecewise((1, x < 2), (3, True))
assert Piecewise((1, x > 2)).simplify() == Piecewise((1, x > 2),
(nan, True))
assert Piecewise((1, (x >= 2) & (x < oo))
).simplify() == Piecewise((1, (x >= 2) & (x < oo)), (nan, True))
assert Piecewise((1, x < 2), (2, (x > 1) & (x < 3)), (3, True)
). simplify() == Piecewise((1, x < 2), (2, x < 3), (3, True))
assert Piecewise((1, x < 2), (2, (x <= 3) & (x > 1)), (3, True)
).simplify() == Piecewise((1, x < 2), (2, x <= 3), (3, True))
assert Piecewise((1, x < 2), (2, (x > 2) & (x < 3)), (3, True)
).simplify() == Piecewise((1, x < 2), (2, (x > 2) & (x < 3)),
(3, True))
assert Piecewise((1, x < 2), (2, (x >= 1) & (x <= 3)), (3, True)
).simplify() == Piecewise((1, x < 2), (2, x <= 3), (3, True))
assert Piecewise((1, x < 1), (2, (x >= 2) & (x <= 3)), (3, True)
).simplify() == Piecewise((1, x < 1), (2, (x >= 2) & (x <= 3)),
(3, True))
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_exclusive():
p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True))
assert piecewise_exclusive(p) == Piecewise((0, x < 0), (S.Half, Eq(x, 0)),
(1, x > 0), evaluate=False)
assert piecewise_exclusive(p + 2) == Piecewise((0, x < 0), (S.Half, Eq(x, 0)),
(1, x > 0), evaluate=False) + 2
assert piecewise_exclusive(Piecewise((1, y <= 0),
(-Piecewise((2, y >= 0)), True))) == \
Piecewise((1, y <= 0),
(-Piecewise((2, y >= 0),
(S.NaN, y < 0), evaluate=False), y > 0), evaluate=False)
assert piecewise_exclusive(Piecewise((1, x > y))) == Piecewise((1, x > y),
(S.NaN, x <= y),
evaluate=False)
assert piecewise_exclusive(Piecewise((1, x > y)),
skip_nan=True) == Piecewise((1, x > y))
xr, yr = symbols('xr, yr', real=True)
p1 = Piecewise((1, xr < 0), (2, True), evaluate=False)
p1x = Piecewise((1, xr < 0), (2, xr >= 0), evaluate=False)
p2 = Piecewise((p1, yr < 0), (3, True), evaluate=False)
p2x = Piecewise((p1, yr < 0), (3, yr >= 0), evaluate=False)
p2xx = Piecewise((p1x, yr < 0), (3, yr >= 0), evaluate=False)
assert piecewise_exclusive(p2) == p2xx
assert piecewise_exclusive(p2, deep=False) == p2x
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, 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)
b = Symbol('b', real=True)
x = Symbol('x', real=True)
y = Symbol('y', real=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.0
# 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 eq.simplify() == (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)
def test_issue_22533():
x = Symbol('x', real=True)
f = Piecewise((-1 / x, x <= 0), (1 / x, True))
assert integrate(f, x) == Piecewise((-log(x), x <= 0), (log(x), True))
def test_issue_24072():
assert Piecewise((1, x > 1), (2, x <= 1), (3, x <= 1)
) == Piecewise((1, x > 1), (2, True))
def test_piecewise__eval_is_meromorphic():
""" Issue 24127: Tests eval_is_meromorphic auxiliary method """
x = symbols('x', real=True)
f = Piecewise((1, x < 0), (sqrt(1 - x), True))
assert f.is_meromorphic(x, I) is None
assert f.is_meromorphic(x, -1) == True
assert f.is_meromorphic(x, 0) == None
assert f.is_meromorphic(x, 1) == False
assert f.is_meromorphic(x, 2) == True
assert f.is_meromorphic(x, Symbol('a')) == None
assert f.is_meromorphic(x, Symbol('a', real=True)) == None
|
d289acab73ac1cae9660a7ad44c94bb2877fe1eb8aa1ed6784eaa6050381fabc | 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.0
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 sympy.core.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
def test_minmax_no_evaluate():
from sympy import evaluate
p = Symbol('p', positive=True)
assert Max(1, 3) == 3
assert Max(1, 3).args == ()
assert Max(0, p) == p
assert Max(0, p).args == ()
assert Min(0, p) == 0
assert Min(0, p).args == ()
assert Max(1, 3, evaluate=False) != 3
assert Max(1, 3, evaluate=False).args == (1, 3)
assert Max(0, p, evaluate=False) != p
assert Max(0, p, evaluate=False).args == (0, p)
assert Min(0, p, evaluate=False) != 0
assert Min(0, p, evaluate=False).args == (0, p)
with evaluate(False):
assert Max(1, 3) != 3
assert Max(1, 3).args == (1, 3)
assert Max(0, p) != p
assert Max(0, p).args == (0, p)
assert Min(0, p) != 0
assert Min(0, p).args == (0, p)
|
533f66c8f0f321cd928075ee5c9f6e8b4a3a9243b302d097dbe1a233e388df2f | 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)))
rep = {p: v for p, v in zip(self.parameters, args) if v is not None}
return self.subs(rep)
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 Ai, Bi in zip(A, 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, Ai, Bi, 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 = Symbol("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 = {}
_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.
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 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)}
>>> 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('''
Although this type of equation was identified, it is not yet
handled. It should, however, be listed in `diop_known` at the
top of this file. Developers should see comments at the end of
`classify_diop`.
''')) # pragma: no cover
else:
raise NotImplementedError(
'No solver has been written for %s.' % eq_type)
def classify_diop(eq, _dict=True):
# docstring supplied externally
matched = False
diop_type = None
for diop_class in all_diop_classes:
diop_type = diop_class(eq)
if diop_type.matches():
matched = True
break
if matched:
return diop_type.free_symbols, dict(diop_type.coeff) if _dict else diop_type.coeff, diop_type.name
# new diop type instructions
# --------------------------
# if this error raises and the equation *can* be classified,
# * it should be identified in the if-block above
# * the type should be added to the diop_known
# if a solver can be written for it,
# * a dedicated handler should be written (e.g. diop_linear)
# * it should be passed to that handler in diop_solve
raise NotImplementedError(filldedent('''
This equation is not yet recognized or else has not been
simplified sufficiently to put it in a form recognized by
diop_classify().'''))
classify_diop.func_doc = ( # type: ignore
'''
Helper routine used by diop_solve() to find information about ``eq``.
Explanation
===========
Returns a tuple containing the type of the diophantine equation
along with the variables (free symbols) and their coefficients.
Variables are returned as a list and coefficients are returned
as a dict with the key being the respective term and the constant
term is keyed to 1. The type is one of the following:
* %s
Usage
=====
``classify_diop(eq)``: Return variables, coefficients and type of the
``eq``.
Details
=======
``eq`` should be an expression which is assumed to be zero.
``_dict`` is for internal use: when True (default) a dict is returned,
otherwise a defaultdict which supplies 0 for missing keys is returned.
Examples
========
>>> from sympy.solvers.diophantine import classify_diop
>>> from sympy.abc import x, y, z, w, t
>>> classify_diop(4*x + 6*y - 4)
([x, y], {1: -4, x: 4, y: 6}, 'linear')
>>> classify_diop(x + 3*y -4*z + 5)
([x, y, z], {1: 5, x: 1, y: 3, z: -4}, 'linear')
>>> classify_diop(x**2 + y**2 - x*y + x + 5)
([x, y], {1: 5, x: 1, x**2: 1, y**2: 1, x*y: -1}, 'binary_quadratic')
''' % ('\n * '.join(sorted(diop_known))))
def diop_linear(eq, param=symbols("t", integer=True)):
"""
Solves linear diophantine equations.
A linear diophantine equation is an equation of the form `a_{1}x_{1} +
a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are
integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables.
Usage
=====
``diop_linear(eq)``: Returns a tuple containing solutions to the
diophantine equation ``eq``. Values in the tuple is arranged in the same
order as the sorted variables.
Details
=======
``eq`` is a linear diophantine equation which is assumed to be zero.
``param`` is the parameter to be used in the solution.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_linear
>>> from sympy.abc import x, y, z
>>> diop_linear(2*x - 3*y - 5) # solves equation 2*x - 3*y - 5 == 0
(3*t_0 - 5, 2*t_0 - 5)
Here x = -3*t_0 - 5 and y = -2*t_0 - 5
>>> diop_linear(2*x - 3*y - 4*z -3)
(t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3)
See Also
========
diop_quadratic(), diop_ternary_quadratic(), diop_general_pythagorean(),
diop_general_sum_of_squares()
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == Linear.name:
parameters = None
if param is not None:
parameters = symbols('%s_0:%i' % (param, len(var)), integer=True)
result = Linear(eq).solve(parameters=parameters)
if param is None:
result = result(*[0]*len(result.parameters))
if len(result) > 0:
return list(result)[0]
else:
return tuple([None]*len(result.parameters))
def base_solution_linear(c, a, b, t=None):
"""
Return the base solution for the linear equation, `ax + by = c`.
Explanation
===========
Used by ``diop_linear()`` to find the base solution of a linear
Diophantine equation. If ``t`` is given then the parametrized solution is
returned.
Usage
=====
``base_solution_linear(c, a, b, t)``: ``a``, ``b``, ``c`` are coefficients
in `ax + by = c` and ``t`` is the parameter to be used in the solution.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import base_solution_linear
>>> from sympy.abc import t
>>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5
(-5, 5)
>>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0
(0, 0)
>>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5
(3*t - 5, 5 - 2*t)
>>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0
(7*t, -5*t)
"""
a, b, c = _remove_gcd(a, b, c)
if c == 0:
if t is not None:
if b < 0:
t = -t
return (b*t, -a*t)
else:
return (0, 0)
else:
x0, y0, d = igcdex(abs(a), abs(b))
x0 *= sign(a)
y0 *= sign(b)
if divisible(c, d):
if t is not None:
if b < 0:
t = -t
return (c*x0 + b*t, c*y0 - a*t)
else:
return (c*x0, c*y0)
else:
return (None, None)
def diop_univariate(eq):
"""
Solves a univariate diophantine equations.
Explanation
===========
A univariate diophantine equation is an equation of the form
`a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are
integer constants and `x` is an integer variable.
Usage
=====
``diop_univariate(eq)``: Returns a set containing solutions to the
diophantine equation ``eq``.
Details
=======
``eq`` is a univariate diophantine equation which is assumed to be zero.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_univariate
>>> from sympy.abc import x
>>> diop_univariate((x - 2)*(x - 3)**2) # solves equation (x - 2)*(x - 3)**2 == 0
{(2,), (3,)}
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == Univariate.name:
return {(int(i),) for i in solveset_real(
eq, var[0]).intersect(S.Integers)}
def divisible(a, b):
"""
Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise.
"""
return not a % b
def diop_quadratic(eq, param=symbols("t", integer=True)):
"""
Solves quadratic diophantine equations.
i.e. equations of the form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`. Returns a
set containing the tuples `(x, y)` which contains the solutions. If there
are no solutions then `(None, None)` is returned.
Usage
=====
``diop_quadratic(eq, param)``: ``eq`` is a quadratic binary diophantine
equation. ``param`` is used to indicate the parameter to be used in the
solution.
Details
=======
``eq`` should be an expression which is assumed to be zero.
``param`` is a parameter to be used in the solution.
Examples
========
>>> from sympy.abc import x, y, t
>>> from sympy.solvers.diophantine.diophantine import diop_quadratic
>>> diop_quadratic(x**2 + y**2 + 2*x + 2*y + 2, t)
{(-1, -1)}
References
==========
.. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online],
Available: http://www.alpertron.com.ar/METHODS.HTM
.. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online],
Available: https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
See Also
========
diop_linear(), diop_ternary_quadratic(), diop_general_sum_of_squares(),
diop_general_pythagorean()
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == BinaryQuadratic.name:
if param is not None:
parameters = [param, Symbol("u", integer=True)]
else:
parameters = None
return set(BinaryQuadratic(eq).solve(parameters=parameters))
def is_solution_quad(var, coeff, u, v):
"""
Check whether `(u, v)` is solution to the quadratic binary diophantine
equation with the variable list ``var`` and coefficient dictionary
``coeff``.
Not intended for use by normal users.
"""
reps = dict(zip(var, (u, v)))
eq = Add(*[j*i.xreplace(reps) for i, j in coeff.items()])
return _mexpand(eq) == 0
def diop_DN(D, N, t=symbols("t", integer=True)):
"""
Solves the equation `x^2 - Dy^2 = N`.
Explanation
===========
Mainly concerned with the case `D > 0, D` is not a perfect square,
which is the same as the generalized Pell equation. The LMM
algorithm [1]_ is used to solve this equation.
Returns one solution tuple, (`x, y)` for each class of the solutions.
Other solutions of the class can be constructed according to the
values of ``D`` and ``N``.
Usage
=====
``diop_DN(D, N, t)``: D and N are integers as in `x^2 - Dy^2 = N` and
``t`` is the parameter to be used in the solutions.
Details
=======
``D`` and ``N`` correspond to D and N in the equation.
``t`` is the parameter to be used in the solutions.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_DN
>>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4
[(3, 1), (393, 109), (36, 10)]
The output can be interpreted as follows: There are three fundamental
solutions to the equation `x^2 - 13y^2 = -4` given by (3, 1), (393, 109)
and (36, 10). Each tuple is in the form (x, y), i.e. solution (3, 1) means
that `x = 3` and `y = 1`.
>>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1
[(49299, 1570)]
See Also
========
find_DN(), diop_bf_DN()
References
==========
.. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
Robertson, July 31, 2004, Pages 16 - 17. [online], Available:
https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
"""
if D < 0:
if N == 0:
return [(0, 0)]
elif N < 0:
return []
elif N > 0:
sol = []
for d in divisors(square_factor(N)):
sols = cornacchia(1, -D, N // d**2)
if sols:
for x, y in sols:
sol.append((d*x, d*y))
if D == -1:
sol.append((d*y, d*x))
return sol
elif D == 0:
if N < 0:
return []
if N == 0:
return [(0, t)]
sN, _exact = integer_nthroot(N, 2)
if _exact:
return [(sN, t)]
else:
return []
else: # D > 0
sD, _exact = integer_nthroot(D, 2)
if _exact:
if N == 0:
return [(sD*t, t)]
else:
sol = []
for y in range(floor(sign(N)*(N - 1)/(2*sD)) + 1):
try:
sq, _exact = integer_nthroot(D*y**2 + N, 2)
except ValueError:
_exact = False
if _exact:
sol.append((sq, y))
return sol
elif 1 < N**2 < D:
# It is much faster to call `_special_diop_DN`.
return _special_diop_DN(D, N)
else:
if N == 0:
return [(0, 0)]
elif abs(N) == 1:
pqa = PQa(0, 1, D)
j = 0
G = []
B = []
for i in pqa:
a = i[2]
G.append(i[5])
B.append(i[4])
if j != 0 and a == 2*sD:
break
j = j + 1
if _odd(j):
if N == -1:
x = G[j - 1]
y = B[j - 1]
else:
count = j
while count < 2*j - 1:
i = next(pqa)
G.append(i[5])
B.append(i[4])
count += 1
x = G[count]
y = B[count]
else:
if N == 1:
x = G[j - 1]
y = B[j - 1]
else:
return []
return [(x, y)]
else:
fs = []
sol = []
div = divisors(N)
for d in div:
if divisible(N, d**2):
fs.append(d)
for f in fs:
m = N // f**2
zs = sqrt_mod(D, abs(m), all_roots=True)
zs = [i for i in zs if i <= abs(m) // 2 ]
if abs(m) != 2:
zs = zs + [-i for i in zs if i] # omit dupl 0
for z in zs:
pqa = PQa(z, abs(m), D)
j = 0
G = []
B = []
for i in pqa:
G.append(i[5])
B.append(i[4])
if j != 0 and abs(i[1]) == 1:
r = G[j-1]
s = B[j-1]
if r**2 - D*s**2 == m:
sol.append((f*r, f*s))
elif diop_DN(D, -1) != []:
a = diop_DN(D, -1)
sol.append((f*(r*a[0][0] + a[0][1]*s*D), f*(r*a[0][1] + s*a[0][0])))
break
j = j + 1
if j == length(z, abs(m), D):
break
return sol
def _special_diop_DN(D, N):
"""
Solves the equation `x^2 - Dy^2 = N` for the special case where
`1 < N**2 < D` and `D` is not a perfect square.
It is better to call `diop_DN` rather than this function, as
the former checks the condition `1 < N**2 < D`, and calls the latter only
if appropriate.
Usage
=====
WARNING: Internal method. Do not call directly!
``_special_diop_DN(D, N)``: D and N are integers as in `x^2 - Dy^2 = N`.
Details
=======
``D`` and ``N`` correspond to D and N in the equation.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import _special_diop_DN
>>> _special_diop_DN(13, -3) # Solves equation x**2 - 13*y**2 = -3
[(7, 2), (137, 38)]
The output can be interpreted as follows: There are two fundamental
solutions to the equation `x^2 - 13y^2 = -3` given by (7, 2) and
(137, 38). Each tuple is in the form (x, y), i.e. solution (7, 2) means
that `x = 7` and `y = 2`.
>>> _special_diop_DN(2445, -20) # Solves equation x**2 - 2445*y**2 = -20
[(445, 9), (17625560, 356454), (698095554475, 14118073569)]
See Also
========
diop_DN()
References
==========
.. [1] Section 4.4.4 of the following book:
Quadratic Diophantine Equations, T. Andreescu and D. Andrica,
Springer, 2015.
"""
# The following assertion was removed for efficiency, with the understanding
# that this method is not called directly. The parent method, `diop_DN`
# is responsible for performing the appropriate checks.
#
# assert (1 < N**2 < D) and (not integer_nthroot(D, 2)[1])
sqrt_D = sqrt(D)
F = [(N, 1)]
f = 2
while True:
f2 = f**2
if f2 > abs(N):
break
n, r = divmod(N, f2)
if r == 0:
F.append((n, f))
f += 1
P = 0
Q = 1
G0, G1 = 0, 1
B0, B1 = 1, 0
solutions = []
i = 0
while True:
a = floor((P + sqrt_D) / Q)
P = a*Q - P
Q = (D - P**2) // Q
G2 = a*G1 + G0
B2 = a*B1 + B0
for n, f in F:
if G2**2 - D*B2**2 == n:
solutions.append((f*G2, f*B2))
i += 1
if Q == 1 and i % 2 == 0:
break
G0, G1 = G1, G2
B0, B1 = B1, B2
return solutions
def cornacchia(a, b, m):
r"""
Solves `ax^2 + by^2 = m` where `\gcd(a, b) = 1 = gcd(a, m)` and `a, b > 0`.
Explanation
===========
Uses the algorithm due to Cornacchia. The method only finds primitive
solutions, i.e. ones with `\gcd(x, y) = 1`. So this method cannot be used to
find the solutions of `x^2 + y^2 = 20` since the only solution to former is
`(x, y) = (4, 2)` and it is not primitive. When `a = b`, only the
solutions with `x \leq y` are found. For more details, see the References.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import cornacchia
>>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35
{(2, 3), (4, 1)}
>>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25
{(4, 3)}
References
===========
.. [1] A. Nitaj, "L'algorithme de Cornacchia"
.. [2] Solving the diophantine equation ax**2 + by**2 = m by Cornacchia's
method, [online], Available:
http://www.numbertheory.org/php/cornacchia.html
See Also
========
sympy.utilities.iterables.signed_permutations
"""
sols = set()
a1 = igcdex(a, m)[0]
v = sqrt_mod(-b*a1, m, all_roots=True)
if not v:
return None
for t in v:
if t < m // 2:
continue
u, r = t, m
while True:
u, r = r, u % r
if a*r**2 < m:
break
m1 = m - a*r**2
if m1 % b == 0:
m1 = m1 // b
s, _exact = integer_nthroot(m1, 2)
if _exact:
if a == b and r < s:
r, s = s, r
sols.add((int(r), int(s)))
return sols
def PQa(P_0, Q_0, D):
r"""
Returns useful information needed to solve the Pell equation.
Explanation
===========
There are six sequences of integers defined related to the continued
fraction representation of `\\frac{P + \sqrt{D}}{Q}`, namely {`P_{i}`},
{`Q_{i}`}, {`a_{i}`},{`A_{i}`}, {`B_{i}`}, {`G_{i}`}. ``PQa()`` Returns
these values as a 6-tuple in the same order as mentioned above. Refer [1]_
for more detailed information.
Usage
=====
``PQa(P_0, Q_0, D)``: ``P_0``, ``Q_0`` and ``D`` are integers corresponding
to `P_{0}`, `Q_{0}` and `D` in the continued fraction
`\\frac{P_{0} + \sqrt{D}}{Q_{0}}`.
Also it's assumed that `P_{0}^2 == D mod(|Q_{0}|)` and `D` is square free.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import PQa
>>> pqa = PQa(13, 4, 5) # (13 + sqrt(5))/4
>>> next(pqa) # (P_0, Q_0, a_0, A_0, B_0, G_0)
(13, 4, 3, 3, 1, -1)
>>> next(pqa) # (P_1, Q_1, a_1, A_1, B_1, G_1)
(-1, 1, 1, 4, 1, 3)
References
==========
.. [1] Solving the generalized Pell equation x^2 - Dy^2 = N, John P.
Robertson, July 31, 2004, Pages 4 - 8. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
"""
A_i_2 = B_i_1 = 0
A_i_1 = B_i_2 = 1
G_i_2 = -P_0
G_i_1 = Q_0
P_i = P_0
Q_i = Q_0
while True:
a_i = floor((P_i + sqrt(D))/Q_i)
A_i = a_i*A_i_1 + A_i_2
B_i = a_i*B_i_1 + B_i_2
G_i = a_i*G_i_1 + G_i_2
yield P_i, Q_i, a_i, A_i, B_i, G_i
A_i_1, A_i_2 = A_i, A_i_1
B_i_1, B_i_2 = B_i, B_i_1
G_i_1, G_i_2 = G_i, G_i_1
P_i = a_i*Q_i - P_i
Q_i = (D - P_i**2)/Q_i
def diop_bf_DN(D, N, t=symbols("t", integer=True)):
r"""
Uses brute force to solve the equation, `x^2 - Dy^2 = N`.
Explanation
===========
Mainly concerned with the generalized Pell equation which is the case when
`D > 0, D` is not a perfect square. For more information on the case refer
[1]_. Let `(t, u)` be the minimal positive solution of the equation
`x^2 - Dy^2 = 1`. Then this method requires
`\sqrt{\\frac{\mid N \mid (t \pm 1)}{2D}}` to be small.
Usage
=====
``diop_bf_DN(D, N, t)``: ``D`` and ``N`` are coefficients in
`x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions.
Details
=======
``D`` and ``N`` correspond to D and N in the equation.
``t`` is the parameter to be used in the solutions.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_bf_DN
>>> diop_bf_DN(13, -4)
[(3, 1), (-3, 1), (36, 10)]
>>> diop_bf_DN(986, 1)
[(49299, 1570)]
See Also
========
diop_DN()
References
==========
.. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
Robertson, July 31, 2004, Page 15. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
"""
D = as_int(D)
N = as_int(N)
sol = []
a = diop_DN(D, 1)
u = a[0][0]
if abs(N) == 1:
return diop_DN(D, N)
elif N > 1:
L1 = 0
L2 = integer_nthroot(int(N*(u - 1)/(2*D)), 2)[0] + 1
elif N < -1:
L1, _exact = integer_nthroot(-int(N/D), 2)
if not _exact:
L1 += 1
L2 = integer_nthroot(-int(N*(u + 1)/(2*D)), 2)[0] + 1
else: # N = 0
if D < 0:
return [(0, 0)]
elif D == 0:
return [(0, t)]
else:
sD, _exact = integer_nthroot(D, 2)
if _exact:
return [(sD*t, t), (-sD*t, t)]
else:
return [(0, 0)]
for y in range(L1, L2):
try:
x, _exact = integer_nthroot(N + D*y**2, 2)
except ValueError:
_exact = False
if _exact:
sol.append((x, y))
if not equivalent(x, y, -x, y, D, N):
sol.append((-x, y))
return sol
def equivalent(u, v, r, s, D, N):
"""
Returns True if two solutions `(u, v)` and `(r, s)` of `x^2 - Dy^2 = N`
belongs to the same equivalence class and False otherwise.
Explanation
===========
Two solutions `(u, v)` and `(r, s)` to the above equation fall to the same
equivalence class iff both `(ur - Dvs)` and `(us - vr)` are divisible by
`N`. See reference [1]_. No test is performed to test whether `(u, v)` and
`(r, s)` are actually solutions to the equation. User should take care of
this.
Usage
=====
``equivalent(u, v, r, s, D, N)``: `(u, v)` and `(r, s)` are two solutions
of the equation `x^2 - Dy^2 = N` and all parameters involved are integers.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import equivalent
>>> equivalent(18, 5, -18, -5, 13, -1)
True
>>> equivalent(3, 1, -18, 393, 109, -4)
False
References
==========
.. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
Robertson, July 31, 2004, Page 12. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
"""
return divisible(u*r - D*v*s, N) and divisible(u*s - v*r, N)
def length(P, Q, D):
r"""
Returns the (length of aperiodic part + length of periodic part) of
continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`.
It is important to remember that this does NOT return the length of the
periodic part but the sum of the lengths of the two parts as mentioned
above.
Usage
=====
``length(P, Q, D)``: ``P``, ``Q`` and ``D`` are integers corresponding to
the continued fraction `\\frac{P + \sqrt{D}}{Q}`.
Details
=======
``P``, ``D`` and ``Q`` corresponds to P, D and Q in the continued fraction,
`\\frac{P + \sqrt{D}}{Q}`.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import length
>>> length(-2, 4, 5) # (-2 + sqrt(5))/4
3
>>> length(-5, 4, 17) # (-5 + sqrt(17))/4
4
See Also
========
sympy.ntheory.continued_fraction.continued_fraction_periodic
"""
from sympy.ntheory.continued_fraction import continued_fraction_periodic
v = continued_fraction_periodic(P, Q, D)
if isinstance(v[-1], list):
rpt = len(v[-1])
nonrpt = len(v) - 1
else:
rpt = 0
nonrpt = len(v)
return rpt + nonrpt
def transformation_to_DN(eq):
"""
This function transforms general quadratic,
`ax^2 + bxy + cy^2 + dx + ey + f = 0`
to more easy to deal with `X^2 - DY^2 = N` form.
Explanation
===========
This is used to solve the general quadratic equation by transforming it to
the latter form. Refer to [1]_ for more detailed information on the
transformation. This function returns a tuple (A, B) where A is a 2 X 2
matrix and B is a 2 X 1 matrix such that,
Transpose([x y]) = A * Transpose([X Y]) + B
Usage
=====
``transformation_to_DN(eq)``: where ``eq`` is the quadratic to be
transformed.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.solvers.diophantine.diophantine import transformation_to_DN
>>> A, B = transformation_to_DN(x**2 - 3*x*y - y**2 - 2*y + 1)
>>> A
Matrix([
[1/26, 3/26],
[ 0, 1/13]])
>>> B
Matrix([
[-6/13],
[-4/13]])
A, B returned are such that Transpose((x y)) = A * Transpose((X Y)) + B.
Substituting these values for `x` and `y` and a bit of simplifying work
will give an equation of the form `x^2 - Dy^2 = N`.
>>> from sympy.abc import X, Y
>>> from sympy import Matrix, simplify
>>> u = (A*Matrix([X, Y]) + B)[0] # Transformation for x
>>> u
X/26 + 3*Y/26 - 6/13
>>> v = (A*Matrix([X, Y]) + B)[1] # Transformation for y
>>> v
Y/13 - 4/13
Next we will substitute these formulas for `x` and `y` and do
``simplify()``.
>>> eq = simplify((x**2 - 3*x*y - y**2 - 2*y + 1).subs(zip((x, y), (u, v))))
>>> eq
X**2/676 - Y**2/52 + 17/13
By multiplying the denominator appropriately, we can get a Pell equation
in the standard form.
>>> eq * 676
X**2 - 13*Y**2 + 884
If only the final equation is needed, ``find_DN()`` can be used.
See Also
========
find_DN()
References
==========
.. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0,
John P.Robertson, May 8, 2003, Page 7 - 11.
https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == BinaryQuadratic.name:
return _transformation_to_DN(var, coeff)
def _transformation_to_DN(var, coeff):
x, y = var
a = coeff[x**2]
b = coeff[x*y]
c = coeff[y**2]
d = coeff[x]
e = coeff[y]
f = coeff[1]
a, b, c, d, e, f = [as_int(i) for i in _remove_gcd(a, b, c, d, e, f)]
X, Y = symbols("X, Y", integer=True)
if b:
B, C = _rational_pq(2*a, b)
A, T = _rational_pq(a, B**2)
# eq_1 = A*B*X**2 + B*(c*T - A*C**2)*Y**2 + d*T*X + (B*e*T - d*T*C)*Y + f*T*B
coeff = {X**2: A*B, X*Y: 0, Y**2: B*(c*T - A*C**2), X: d*T, Y: B*e*T - d*T*C, 1: f*T*B}
A_0, B_0 = _transformation_to_DN([X, Y], coeff)
return Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*A_0, Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*B_0
else:
if d:
B, C = _rational_pq(2*a, d)
A, T = _rational_pq(a, B**2)
# eq_2 = A*X**2 + c*T*Y**2 + e*T*Y + f*T - A*C**2
coeff = {X**2: A, X*Y: 0, Y**2: c*T, X: 0, Y: e*T, 1: f*T - A*C**2}
A_0, B_0 = _transformation_to_DN([X, Y], coeff)
return Matrix(2, 2, [S.One/B, 0, 0, 1])*A_0, Matrix(2, 2, [S.One/B, 0, 0, 1])*B_0 + Matrix([-S(C)/B, 0])
else:
if e:
B, C = _rational_pq(2*c, e)
A, T = _rational_pq(c, B**2)
# eq_3 = a*T*X**2 + A*Y**2 + f*T - A*C**2
coeff = {X**2: a*T, X*Y: 0, Y**2: A, X: 0, Y: 0, 1: f*T - A*C**2}
A_0, B_0 = _transformation_to_DN([X, Y], coeff)
return Matrix(2, 2, [1, 0, 0, S.One/B])*A_0, Matrix(2, 2, [1, 0, 0, S.One/B])*B_0 + Matrix([0, -S(C)/B])
else:
# TODO: pre-simplification: Not necessary but may simplify
# the equation.
return Matrix(2, 2, [S.One/a, 0, 0, 1]), Matrix([0, 0])
def find_DN(eq):
"""
This function returns a tuple, `(D, N)` of the simplified form,
`x^2 - Dy^2 = N`, corresponding to the general quadratic,
`ax^2 + bxy + cy^2 + dx + ey + f = 0`.
Solving the general quadratic is then equivalent to solving the equation
`X^2 - DY^2 = N` and transforming the solutions by using the transformation
matrices returned by ``transformation_to_DN()``.
Usage
=====
``find_DN(eq)``: where ``eq`` is the quadratic to be transformed.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.solvers.diophantine.diophantine import find_DN
>>> find_DN(x**2 - 3*x*y - y**2 - 2*y + 1)
(13, -884)
Interpretation of the output is that we get `X^2 -13Y^2 = -884` after
transforming `x^2 - 3xy - y^2 - 2y + 1` using the transformation returned
by ``transformation_to_DN()``.
See Also
========
transformation_to_DN()
References
==========
.. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0,
John P.Robertson, May 8, 2003, Page 7 - 11.
https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == BinaryQuadratic.name:
return _find_DN(var, coeff)
def _find_DN(var, coeff):
x, y = var
X, Y = symbols("X, Y", integer=True)
A, B = _transformation_to_DN(var, coeff)
u = (A*Matrix([X, Y]) + B)[0]
v = (A*Matrix([X, Y]) + B)[1]
eq = x**2*coeff[x**2] + x*y*coeff[x*y] + y**2*coeff[y**2] + x*coeff[x] + y*coeff[y] + coeff[1]
simplified = _mexpand(eq.subs(zip((x, y), (u, v))))
coeff = simplified.as_coefficients_dict()
return -coeff[Y**2]/coeff[X**2], -coeff[1]/coeff[X**2]
def check_param(x, y, a, params):
"""
If there is a number modulo ``a`` such that ``x`` and ``y`` are both
integers, then return a parametric representation for ``x`` and ``y``
else return (None, None).
Here ``x`` and ``y`` are functions of ``t``.
"""
from sympy.simplify.simplify import clear_coefficients
if x.is_number and not x.is_Integer:
return DiophantineSolutionSet([x, y], parameters=params)
if y.is_number and not y.is_Integer:
return DiophantineSolutionSet([x, y], parameters=params)
m, n = symbols("m, n", integer=True)
c, p = (m*x + n*y).as_content_primitive()
if a % c.q:
return DiophantineSolutionSet([x, y], parameters=params)
# clear_coefficients(mx + b, R)[1] -> (R - b)/m
eq = clear_coefficients(x, m)[1] - clear_coefficients(y, n)[1]
junk, eq = eq.as_content_primitive()
return _diop_solve(eq, params=params)
def diop_ternary_quadratic(eq, parameterize=False):
"""
Solves the general quadratic ternary form,
`ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`.
Returns a tuple `(x, y, z)` which is a base solution for the above
equation. If there are no solutions, `(None, None, None)` is returned.
Usage
=====
``diop_ternary_quadratic(eq)``: Return a tuple containing a basic solution
to ``eq``.
Details
=======
``eq`` should be an homogeneous expression of degree two in three variables
and it is assumed to be zero.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic
>>> diop_ternary_quadratic(x**2 + 3*y**2 - z**2)
(1, 0, 1)
>>> diop_ternary_quadratic(4*x**2 + 5*y**2 - z**2)
(1, 0, 2)
>>> diop_ternary_quadratic(45*x**2 - 7*y**2 - 8*x*y - z**2)
(28, 45, 105)
>>> diop_ternary_quadratic(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y)
(9, 1, 5)
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type in (
HomogeneousTernaryQuadratic.name,
HomogeneousTernaryQuadraticNormal.name):
sol = _diop_ternary_quadratic(var, coeff)
if len(sol) > 0:
x_0, y_0, z_0 = list(sol)[0]
else:
x_0, y_0, z_0 = None, None, None
if parameterize:
return _parametrize_ternary_quadratic(
(x_0, y_0, z_0), var, coeff)
return x_0, y_0, z_0
def _diop_ternary_quadratic(_var, coeff):
eq = sum([i*coeff[i] for i in coeff])
if HomogeneousTernaryQuadratic(eq).matches():
return HomogeneousTernaryQuadratic(eq, free_symbols=_var).solve()
elif HomogeneousTernaryQuadraticNormal(eq).matches():
return HomogeneousTernaryQuadraticNormal(eq, free_symbols=_var).solve()
def transformation_to_normal(eq):
"""
Returns the transformation Matrix that converts a general ternary
quadratic equation ``eq`` (`ax^2 + by^2 + cz^2 + dxy + eyz + fxz`)
to a form without cross terms: `ax^2 + by^2 + cz^2 = 0`. This is
not used in solving ternary quadratics; it is only implemented for
the sake of completeness.
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type in (
"homogeneous_ternary_quadratic",
"homogeneous_ternary_quadratic_normal"):
return _transformation_to_normal(var, coeff)
def _transformation_to_normal(var, coeff):
_var = list(var) # copy
x, y, z = var
if not any(coeff[i**2] for i in var):
# https://math.stackexchange.com/questions/448051/transform-quadratic-ternary-form-to-normal-form/448065#448065
a = coeff[x*y]
b = coeff[y*z]
c = coeff[x*z]
swap = False
if not a: # b can't be 0 or else there aren't 3 vars
swap = True
a, b = b, a
T = Matrix(((1, 1, -b/a), (1, -1, -c/a), (0, 0, 1)))
if swap:
T.row_swap(0, 1)
T.col_swap(0, 1)
return T
if coeff[x**2] == 0:
# If the coefficient of x is zero change the variables
if coeff[y**2] == 0:
_var[0], _var[2] = var[2], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 2)
T.col_swap(0, 2)
return T
else:
_var[0], _var[1] = var[1], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 1)
T.col_swap(0, 1)
return T
# Apply the transformation x --> X - (B*Y + C*Z)/(2*A)
if coeff[x*y] != 0 or coeff[x*z] != 0:
A = coeff[x**2]
B = coeff[x*y]
C = coeff[x*z]
D = coeff[y**2]
E = coeff[y*z]
F = coeff[z**2]
_coeff = {}
_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:
https://nottingham-repository.worktribe.com/output/1023265/efficient-solution-of-rational-conics
"""
if abs(A) > abs(B):
w, y, x = ldescent(B, A)
return w, x, y
if A == 1:
return (1, 1, 0)
if B == 1:
return (1, 0, 1)
if B == -1: # and A == -1
return
r = sqrt_mod(A, B)
Q = (r**2 - A) // B
if Q == 0:
B_0 = 1
d = 0
else:
div = divisors(Q)
B_0 = None
for i in div:
sQ, _exact = integer_nthroot(abs(Q) // i, 2)
if _exact:
B_0, d = sign(Q)*i, sQ
break
if B_0 is not None:
W, X, Y = ldescent(A, B_0)
return _remove_gcd((-A*X + r*W), (r*X - W), Y*(B_0*d))
def descent(A, B):
"""
Returns a non-trivial solution, (x, y, z), to `x^2 = Ay^2 + Bz^2`
using Lagrange's descent method with lattice-reduction. `A` and `B`
are assumed to be valid for such a solution to exist.
This is faster than the normal Lagrange's descent algorithm because
the Gaussian reduction is used.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import descent
>>> descent(3, 1) # x**2 = 3*y**2 + z**2
(1, 0, 1)
`(x, y, z) = (1, 0, 1)` is a solution to the above equation.
>>> descent(41, -113)
(-16, -3, 1)
References
==========
.. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
Mathematics of Computation, Volume 00, Number 0.
"""
if abs(A) > abs(B):
x, y, z = descent(B, A)
return x, z, y
if B == 1:
return (1, 0, 1)
if A == 1:
return (1, 1, 0)
if B == -A:
return (0, 1, 1)
if B == A:
x, z, y = descent(-1, A)
return (A*y, z, x)
w = sqrt_mod(A, B)
x_0, z_0 = gaussian_reduce(w, A, B)
t = (x_0**2 - A*z_0**2) // B
t_2 = square_factor(t)
t_1 = t // t_2**2
x_1, z_1, y_1 = descent(A, t_1)
return _remove_gcd(x_0*x_1 + A*z_0*z_1, z_0*x_1 + x_0*z_1, t_1*t_2*y_1)
def gaussian_reduce(w, a, b):
r"""
Returns a reduced solution `(x, z)` to the congruence
`X^2 - aZ^2 \equiv 0 \ (mod \ b)` so that `x^2 + |a|z^2` is minimal.
Details
=======
Here ``w`` is a solution of the congruence `x^2 \equiv a \ (mod \ b)`
References
==========
.. [1] Gaussian lattice Reduction [online]. Available:
http://home.ie.cuhk.edu.hk/~wkshum/wordpress/?p=404
.. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
Mathematics of Computation, Volume 00, Number 0.
"""
u = (0, 1)
v = (1, 0)
if dot(u, v, w, a, b) < 0:
v = (-v[0], -v[1])
if norm(u, w, a, b) < norm(v, w, a, b):
u, v = v, u
while norm(u, w, a, b) > norm(v, w, a, b):
k = dot(u, v, w, a, b) // dot(v, v, w, a, b)
u, v = v, (u[0]- k*v[0], u[1]- k*v[1])
u, v = v, u
if dot(u, v, w, a, b) < dot(v, v, w, a, b)/2 or norm((u[0]-v[0], u[1]-v[1]), w, a, b) > norm(v, w, a, b):
c = v
else:
c = (u[0] - v[0], u[1] - v[1])
return c[0]*w + b*c[1], c[0]
def dot(u, v, w, a, b):
r"""
Returns a special dot product of the vectors `u = (u_{1}, u_{2})` and
`v = (v_{1}, v_{2})` which is defined in order to reduce solution of
the congruence equation `X^2 - aZ^2 \equiv 0 \ (mod \ b)`.
"""
u_1, u_2 = u
v_1, v_2 = v
return (w*u_1 + b*u_2)*(w*v_1 + b*v_2) + abs(a)*u_1*v_1
def norm(u, w, a, b):
r"""
Returns the norm of the vector `u = (u_{1}, u_{2})` under the dot product
defined by `u \cdot v = (wu_{1} + bu_{2})(w*v_{1} + bv_{2}) + |a|*u_{1}*v_{1}`
where `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})`.
"""
u_1, u_2 = u
return sqrt(dot((u_1, u_2), (u_1, u_2), w, a, b))
def holzer(x, y, z, a, b, c):
r"""
Simplify the solution `(x, y, z)` of the equation
`ax^2 + by^2 = cz^2` with `a, b, c > 0` and `z^2 \geq \mid ab \mid` to
a new reduced solution `(x', y', z')` such that `z'^2 \leq \mid ab \mid`.
The algorithm is an interpretation of Mordell's reduction as described
on page 8 of Cremona and Rusin's paper [1]_ and the work of Mordell in
reference [2]_.
References
==========
.. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
Mathematics of Computation, Volume 00, Number 0.
.. [2] Diophantine Equations, L. J. Mordell, page 48.
"""
if _odd(c):
k = 2*c
else:
k = c//2
small = a*b*c
step = 0
while True:
t1, t2, t3 = a*x**2, b*y**2, c*z**2
# check that it's a solution
if t1 + t2 != t3:
if step == 0:
raise ValueError('bad starting solution')
break
x_0, y_0, z_0 = x, y, z
if max(t1, t2, t3) <= small:
# Holzer condition
break
uv = u, v = base_solution_linear(k, y_0, -x_0)
if None in uv:
break
p, q = -(a*u*x_0 + b*v*y_0), c*z_0
r = Rational(p, q)
if _even(c):
w = _nint_or_floor(p, q)
assert abs(w - r) <= S.Half
else:
w = p//q # floor
if _odd(a*u + b*v + c*w):
w += 1
assert abs(w - r) <= S.One
A = (a*u**2 + b*v**2 + c*w**2)
B = (a*u*x_0 + b*v*y_0 + c*w*z_0)
x = Rational(x_0*A - 2*u*B, k)
y = Rational(y_0*A - 2*v*B, k)
z = Rational(z_0*A - 2*w*B, k)
assert all(i.is_Integer for i in (x, y, z))
step += 1
return tuple([int(i) for i in (x_0, y_0, z_0)])
def diop_general_pythagorean(eq, param=symbols("m", integer=True)):
"""
Solves the general pythagorean equation,
`a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`.
Returns a tuple which contains a parametrized solution to the equation,
sorted in the same order as the input variables.
Usage
=====
``diop_general_pythagorean(eq, param)``: where ``eq`` is a general
pythagorean equation which is assumed to be zero and ``param`` is the base
parameter used to construct other parameters by subscripting.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_general_pythagorean
>>> from sympy.abc import a, b, c, d, e
>>> diop_general_pythagorean(a**2 + b**2 + c**2 - d**2)
(m1**2 + m2**2 - m3**2, 2*m1*m3, 2*m2*m3, m1**2 + m2**2 + m3**2)
>>> diop_general_pythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2)
(10*m1**2 + 10*m2**2 + 10*m3**2 - 10*m4**2, 15*m1**2 + 15*m2**2 + 15*m3**2 + 15*m4**2, 15*m1*m4, 12*m2*m4, 60*m3*m4)
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == GeneralPythagorean.name:
if param is None:
params = None
else:
params = symbols('%s1:%i' % (param, len(var)), integer=True)
return list(GeneralPythagorean(eq).solve(parameters=params))[0]
def diop_general_sum_of_squares(eq, limit=1):
r"""
Solves the equation `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.
Returns at most ``limit`` number of solutions.
Usage
=====
``general_sum_of_squares(eq, limit)`` : Here ``eq`` is an expression which
is assumed to be zero. Also, ``eq`` should be in the form,
`x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.
Details
=======
When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be
no solutions. Refer to [1]_ for more details.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_squares
>>> from sympy.abc import a, b, c, d, e
>>> diop_general_sum_of_squares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345)
{(15, 22, 22, 24, 24)}
Reference
=========
.. [1] Representing an integer as a sum of three squares, [online],
Available:
http://www.proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == GeneralSumOfSquares.name:
return set(GeneralSumOfSquares(eq).solve(limit=limit))
def diop_general_sum_of_even_powers(eq, limit=1):
"""
Solves the equation `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`
where `e` is an even, integer power.
Returns at most ``limit`` number of solutions.
Usage
=====
``general_sum_of_even_powers(eq, limit)`` : Here ``eq`` is an expression which
is assumed to be zero. Also, ``eq`` should be in the form,
`x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_even_powers
>>> from sympy.abc import a, b
>>> diop_general_sum_of_even_powers(a**4 + b**4 - (2**4 + 3**4))
{(2, 3)}
See Also
========
power_representation
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == GeneralSumOfEvenPowers.name:
return set(GeneralSumOfEvenPowers(eq).solve(limit=limit))
## Functions below this comment can be more suitably grouped under
## an Additive number theory module rather than the Diophantine
## equation module.
def partition(n, k=None, zeros=False):
"""
Returns a generator that can be used to generate partitions of an integer
`n`.
Explanation
===========
A partition of `n` is a set of positive integers which add up to `n`. For
example, partitions of 3 are 3, 1 + 2, 1 + 1 + 1. A partition is returned
as a tuple. If ``k`` equals None, then all possible partitions are returned
irrespective of their size, otherwise only the partitions of size ``k`` are
returned. If the ``zero`` parameter is set to True then a suitable
number of zeros are added at the end of every partition of size less than
``k``.
``zero`` parameter is considered only if ``k`` is not None. When the
partitions are over, the last `next()` call throws the ``StopIteration``
exception, so this function should always be used inside a try - except
block.
Details
=======
``partition(n, k)``: Here ``n`` is a positive integer and ``k`` is the size
of the partition which is also positive integer.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import partition
>>> f = partition(5)
>>> next(f)
(1, 1, 1, 1, 1)
>>> next(f)
(1, 1, 1, 2)
>>> g = partition(5, 3)
>>> next(g)
(1, 1, 3)
>>> next(g)
(1, 2, 2)
>>> g = partition(5, 3, zeros=True)
>>> next(g)
(0, 0, 5)
"""
if not zeros or k is None:
for i in ordered_partitions(n, k):
yield tuple(i)
else:
for m in range(1, k + 1):
for i in ordered_partitions(n, m):
i = tuple(i)
yield (0,)*(k - len(i)) + i
def prime_as_sum_of_two_squares(p):
"""
Represent a prime `p` as a unique sum of two squares; this can
only be done if the prime is congruent to 1 mod 4.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import prime_as_sum_of_two_squares
>>> prime_as_sum_of_two_squares(7) # can't be done
>>> prime_as_sum_of_two_squares(5)
(1, 2)
Reference
=========
.. [1] Representing a number as a sum of four squares, [online],
Available: http://schorn.ch/lagrange.html
See Also
========
sum_of_squares()
"""
if not p % 4 == 1:
return
if p % 8 == 5:
b = 2
else:
b = 3
while pow(b, (p - 1) // 2, p) == 1:
b = nextprime(b)
b = pow(b, (p - 1) // 4, p)
a = p
while b**2 > p:
a, b = b, a % b
return (int(a % b), int(b)) # convert from long
def sum_of_three_squares(n):
r"""
Returns a 3-tuple $(a, b, c)$ such that $a^2 + b^2 + c^2 = n$ and
$a, b, c \geq 0$.
Returns None if $n = 4^a(8m + 7)$ for some `a, m \in \mathbb{Z}`. See
[1]_ for more details.
Usage
=====
``sum_of_three_squares(n)``: Here ``n`` is a non-negative integer.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import sum_of_three_squares
>>> sum_of_three_squares(44542)
(18, 37, 207)
References
==========
.. [1] Representing a number as a sum of three squares, [online],
Available: http://schorn.ch/lagrange.html
See Also
========
sum_of_squares()
"""
special = {1:(1, 0, 0), 2:(1, 1, 0), 3:(1, 1, 1), 10: (1, 3, 0), 34: (3, 3, 4), 58:(3, 7, 0),
85:(6, 7, 0), 130:(3, 11, 0), 214:(3, 6, 13), 226:(8, 9, 9), 370:(8, 9, 15),
526:(6, 7, 21), 706:(15, 15, 16), 730:(1, 27, 0), 1414:(6, 17, 33), 1906:(13, 21, 36),
2986: (21, 32, 39), 9634: (56, 57, 57)}
v = 0
if n == 0:
return (0, 0, 0)
v = multiplicity(4, n)
n //= 4**v
if n % 8 == 7:
return
if n in special.keys():
x, y, z = special[n]
return _sorted_tuple(2**v*x, 2**v*y, 2**v*z)
s, _exact = integer_nthroot(n, 2)
if _exact:
return (2**v*s, 0, 0)
x = None
if n % 8 == 3:
s = s if _odd(s) else s - 1
for x in range(s, -1, -2):
N = (n - x**2) // 2
if isprime(N):
y, z = prime_as_sum_of_two_squares(N)
return _sorted_tuple(2**v*x, 2**v*(y + z), 2**v*abs(y - z))
return
if n % 8 in (2, 6):
s = s if _odd(s) else s - 1
else:
s = s - 1 if _odd(s) else s
for x in range(s, -1, -2):
N = n - x**2
if isprime(N):
y, z = prime_as_sum_of_two_squares(N)
return _sorted_tuple(2**v*x, 2**v*y, 2**v*z)
def sum_of_four_squares(n):
r"""
Returns a 4-tuple `(a, b, c, d)` such that `a^2 + b^2 + c^2 + d^2 = n`.
Here `a, b, c, d \geq 0`.
Usage
=====
``sum_of_four_squares(n)``: Here ``n`` is a non-negative integer.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import sum_of_four_squares
>>> sum_of_four_squares(3456)
(8, 8, 32, 48)
>>> sum_of_four_squares(1294585930293)
(0, 1234, 2161, 1137796)
References
==========
.. [1] Representing a number as a sum of four squares, [online],
Available: http://schorn.ch/lagrange.html
See Also
========
sum_of_squares()
"""
if n == 0:
return (0, 0, 0, 0)
v = multiplicity(4, n)
n //= 4**v
if n % 8 == 7:
d = 2
n = n - 4
elif n % 8 in (2, 6):
d = 1
n = n - 1
else:
d = 0
x, y, z = sum_of_three_squares(n)
return _sorted_tuple(2**v*d, 2**v*x, 2**v*y, 2**v*z)
def power_representation(n, p, k, zeros=False):
r"""
Returns a generator for finding k-tuples of integers,
`(n_{1}, n_{2}, . . . n_{k})`, such that
`n = n_{1}^p + n_{2}^p + . . . n_{k}^p`.
Usage
=====
``power_representation(n, p, k, zeros)``: Represent non-negative number
``n`` as a sum of ``k`` ``p``\ th powers. If ``zeros`` is true, then the
solutions is allowed to contain zeros.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import power_representation
Represent 1729 as a sum of two cubes:
>>> f = power_representation(1729, 3, 2)
>>> next(f)
(9, 10)
>>> next(f)
(1, 12)
If the flag `zeros` is True, the solution may contain tuples with
zeros; any such solutions will be generated after the solutions
without zeros:
>>> list(power_representation(125, 2, 3, zeros=True))
[(5, 6, 8), (3, 4, 10), (0, 5, 10), (0, 2, 11)]
For even `p` the `permute_sign` function can be used to get all
signed values:
>>> from sympy.utilities.iterables import permute_signs
>>> list(permute_signs((1, 12)))
[(1, 12), (-1, 12), (1, -12), (-1, -12)]
All possible signed permutations can also be obtained:
>>> from sympy.utilities.iterables import signed_permutations
>>> list(signed_permutations((1, 12)))
[(1, 12), (-1, 12), (1, -12), (-1, -12), (12, 1), (-12, 1), (12, -1), (-12, -1)]
"""
n, p, k = [as_int(i) for i in (n, p, k)]
if n < 0:
if p % 2:
for t in power_representation(-n, p, k, zeros):
yield tuple(-i for i in t)
return
if p < 1 or k < 1:
raise ValueError(filldedent('''
Expecting positive integers for `(p, k)`, but got `(%s, %s)`'''
% (p, k)))
if n == 0:
if zeros:
yield (0,)*k
return
if k == 1:
if p == 1:
yield (n,)
else:
be = perfect_power(n)
if be:
b, e = be
d, r = divmod(e, p)
if not r:
yield (b**d,)
return
if p == 1:
for t in partition(n, k, zeros=zeros):
yield t
return
if p == 2:
feasible = _can_do_sum_of_squares(n, k)
if not feasible:
return
if not zeros and n > 33 and k >= 5 and k <= n and n - k in (
13, 10, 7, 5, 4, 2, 1):
'''Todd G. Will, "When Is n^2 a Sum of k Squares?", [online].
Available: https://www.maa.org/sites/default/files/Will-MMz-201037918.pdf'''
return
if feasible is not True: # it's prime and k == 2
yield prime_as_sum_of_two_squares(n)
return
if k == 2 and p > 2:
be = perfect_power(n)
if be and be[1] % p == 0:
return # Fermat: a**n + b**n = c**n has no solution for n > 2
if n >= k:
a = integer_nthroot(n - (k - 1), p)[0]
for t in pow_rep_recursive(a, k, n, [], p):
yield tuple(reversed(t))
if zeros:
a = integer_nthroot(n, p)[0]
for i in range(1, k):
for t in pow_rep_recursive(a, i, n, [], p):
yield tuple(reversed(t + (0,)*(k - i)))
sum_of_powers = power_representation
def pow_rep_recursive(n_i, k, n_remaining, terms, p):
# Invalid arguments
if n_i <= 0 or k <= 0:
return
# No solutions may exist
if n_remaining < k:
return
if k * pow(n_i, p) < n_remaining:
return
if k == 0 and n_remaining == 0:
yield tuple(terms)
elif k == 1:
# next_term^p must equal to n_remaining
next_term, exact = integer_nthroot(n_remaining, p)
if exact and next_term <= n_i:
yield tuple(terms + [next_term])
return
else:
# TODO: Fall back to diop_DN when k = 2
if n_i >= 1 and k > 0:
for next_term in range(1, n_i + 1):
residual = n_remaining - pow(next_term, p)
if residual < 0:
break
yield from pow_rep_recursive(next_term, k - 1, residual, terms + [next_term], 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
|
b58b8ab9eacfccb42de8f0eb2304bb64d5ad7af880a62d98f952be90968e5b3b | r"""
This module contains :py:meth:`~sympy.solvers.ode.dsolve` and different helper
functions that it uses.
:py:meth:`~sympy.solvers.ode.dsolve` solves ordinary differential equations.
See the docstring on the various functions for their uses. Note that partial
differential equations support is in ``pde.py``. Note that hint functions
have docstrings describing their various methods, but they are intended for
internal use. Use ``dsolve(ode, func, hint=hint)`` to solve an ODE using a
specific hint. See also the docstring on
:py:meth:`~sympy.solvers.ode.dsolve`.
**Functions in this module**
These are the user functions in this module:
- :py:meth:`~sympy.solvers.ode.dsolve` - Solves ODEs.
- :py:meth:`~sympy.solvers.ode.classify_ode` - Classifies ODEs into
possible hints for :py:meth:`~sympy.solvers.ode.dsolve`.
- :py:meth:`~sympy.solvers.ode.checkodesol` - Checks if an equation is the
solution to an ODE.
- :py:meth:`~sympy.solvers.ode.homogeneous_order` - Returns the
homogeneous order of an expression.
- :py:meth:`~sympy.solvers.ode.infinitesimals` - Returns the infinitesimals
of the Lie group of point transformations of an ODE, such that it is
invariant.
- :py:meth:`~sympy.solvers.ode.checkinfsol` - Checks if the given infinitesimals
are the actual infinitesimals of a first order ODE.
These are the non-solver helper functions that are for internal use. The
user should use the various options to
:py:meth:`~sympy.solvers.ode.dsolve` to obtain the functionality provided
by these functions:
- :py:meth:`~sympy.solvers.ode.ode.odesimp` - Does all forms of ODE
simplification.
- :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity` - A key function for
comparing solutions by simplicity.
- :py:meth:`~sympy.solvers.ode.constantsimp` - Simplifies arbitrary
constants.
- :py:meth:`~sympy.solvers.ode.ode.constant_renumber` - Renumber arbitrary
constants.
- :py:meth:`~sympy.solvers.ode.ode._handle_Integral` - Evaluate unevaluated
Integrals.
See also the docstrings of these functions.
**Currently implemented solver methods**
The following methods are implemented for solving ordinary differential
equations. See the docstrings of the various hint functions for more
information on each (run ``help(ode)``):
- 1st order separable differential equations.
- 1st order differential equations whose coefficients or `dx` and `dy` are
functions homogeneous of the same order.
- 1st order exact differential equations.
- 1st order linear differential equations.
- 1st order Bernoulli differential equations.
- Power series solutions for first order differential equations.
- Lie Group method of solving first order differential equations.
- 2nd order Liouville differential equations.
- Power series solutions for second order differential equations
at ordinary and regular singular points.
- `n`\th order differential equation that can be solved with algebraic
rearrangement and integration.
- `n`\th order linear homogeneous differential equation with constant
coefficients.
- `n`\th order linear inhomogeneous differential equation with constant
coefficients using the method of undetermined coefficients.
- `n`\th order linear inhomogeneous differential equation with constant
coefficients using the method of variation of parameters.
**Philosophy behind this module**
This module is designed to make it easy to add new ODE solving methods without
having to mess with the solving code for other methods. The idea is that
there is a :py:meth:`~sympy.solvers.ode.classify_ode` function, which takes in
an ODE and tells you what hints, if any, will solve the ODE. It does this
without attempting to solve the ODE, so it is fast. Each solving method is a
hint, and it has its own function, named ``ode_<hint>``. That function takes
in the ODE and any match expression gathered by
:py:meth:`~sympy.solvers.ode.classify_ode` and returns a solved result. If
this result has any integrals in it, the hint function will return an
unevaluated :py:class:`~sympy.integrals.integrals.Integral` class.
:py:meth:`~sympy.solvers.ode.dsolve`, which is the user wrapper function
around all of this, will then call :py:meth:`~sympy.solvers.ode.ode.odesimp` on
the result, which, among other things, will attempt to solve the equation for
the dependent variable (the function we are solving for), simplify the
arbitrary constants in the expression, and evaluate any integrals, if the hint
allows it.
**How to add new solution methods**
If you have an ODE that you want :py:meth:`~sympy.solvers.ode.dsolve` to be
able to solve, try to avoid adding special case code here. Instead, try
finding a general method that will solve your ODE, as well as others. This
way, the :py:mod:`~sympy.solvers.ode` module will become more robust, and
unhindered by special case hacks. WolphramAlpha and Maple's
DETools[odeadvisor] function are two resources you can use to classify a
specific ODE. It is also better for a method to work with an `n`\th order ODE
instead of only with specific orders, if possible.
To add a new method, there are a few things that you need to do. First, you
need a hint name for your method. Try to name your hint so that it is
unambiguous with all other methods, including ones that may not be implemented
yet. If your method uses integrals, also include a ``hint_Integral`` hint.
If there is more than one way to solve ODEs with your method, include a hint
for each one, as well as a ``<hint>_best`` hint. Your ``ode_<hint>_best()``
function should choose the best using min with ``ode_sol_simplicity`` as the
key argument. See
:obj:`~sympy.solvers.ode.single.HomogeneousCoeffBest`, for example.
The function that uses your method will be called ``ode_<hint>()``, so the
hint must only use characters that are allowed in a Python function name
(alphanumeric characters and the underscore '``_``' character). Include a
function for every hint, except for ``_Integral`` hints
(:py:meth:`~sympy.solvers.ode.dsolve` takes care of those automatically).
Hint names should be all lowercase, unless a word is commonly capitalized
(such as Integral or Bernoulli). If you have a hint that you do not want to
run with ``all_Integral`` that does not have an ``_Integral`` counterpart (such
as a best hint that would defeat the purpose of ``all_Integral``), you will
need to remove it manually in the :py:meth:`~sympy.solvers.ode.dsolve` code.
See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for
guidelines on writing a hint name.
Determine *in general* how the solutions returned by your method compare with
other methods that can potentially solve the same ODEs. Then, put your hints
in the :py:data:`~sympy.solvers.ode.allhints` tuple in the order that they
should be called. The ordering of this tuple determines which hints are
default. Note that exceptions are ok, because it is easy for the user to
choose individual hints with :py:meth:`~sympy.solvers.ode.dsolve`. In
general, ``_Integral`` variants should go at the end of the list, and
``_best`` variants should go before the various hints they apply to. For
example, the ``undetermined_coefficients`` hint comes before the
``variation_of_parameters`` hint because, even though variation of parameters
is more general than undetermined coefficients, undetermined coefficients
generally returns cleaner results for the ODEs that it can solve than
variation of parameters does, and it does not require integration, so it is
much faster.
Next, you need to have a match expression or a function that matches the type
of the ODE, which you should put in :py:meth:`~sympy.solvers.ode.classify_ode`
(if the match function is more than just a few lines. It should match the
ODE without solving for it as much as possible, so that
:py:meth:`~sympy.solvers.ode.classify_ode` remains fast and is not hindered by
bugs in solving code. Be sure to consider corner cases. For example, if your
solution method involves dividing by something, make sure you exclude the case
where that division will be 0.
In most cases, the matching of the ODE will also give you the various parts
that you need to solve it. You should put that in a dictionary (``.match()``
will do this for you), and add that as ``matching_hints['hint'] = matchdict``
in the relevant part of :py:meth:`~sympy.solvers.ode.classify_ode`.
:py:meth:`~sympy.solvers.ode.classify_ode` will then send this to
:py:meth:`~sympy.solvers.ode.dsolve`, which will send it to your function as
the ``match`` argument. Your function should be named ``ode_<hint>(eq, func,
order, match)`. If you need to send more information, put it in the ``match``
dictionary. For example, if you had to substitute in a dummy variable in
:py:meth:`~sympy.solvers.ode.classify_ode` to match the ODE, you will need to
pass it to your function using the `match` dict to access it. You can access
the independent variable using ``func.args[0]``, and the dependent variable
(the function you are trying to solve for) as ``func.func``. If, while trying
to solve the ODE, you find that you cannot, raise ``NotImplementedError``.
:py:meth:`~sympy.solvers.ode.dsolve` will catch this error with the ``all``
meta-hint, rather than causing the whole routine to fail.
Add a docstring to your function that describes the method employed. Like
with anything else in SymPy, you will need to add a doctest to the docstring,
in addition to real tests in ``test_ode.py``. Try to maintain consistency
with the other hint functions' docstrings. Add your method to the list at the
top of this docstring. Also, add your method to ``ode.rst`` in the
``docs/src`` directory, so that the Sphinx docs will pull its docstring into
the main SymPy documentation. Be sure to make the Sphinx documentation by
running ``make html`` from within the doc directory to verify that the
docstring formats correctly.
If your solution method involves integrating, use :py:obj:`~.Integral` instead of
:py:meth:`~sympy.core.expr.Expr.integrate`. This allows the user to bypass
hard/slow integration by using the ``_Integral`` variant of your hint. In
most cases, calling :py:meth:`sympy.core.basic.Basic.doit` will integrate your
solution. If this is not the case, you will need to write special code in
:py:meth:`~sympy.solvers.ode.ode._handle_Integral`. Arbitrary constants should be
symbols named ``C1``, ``C2``, and so on. All solution methods should return
an equality instance. If you need an arbitrary number of arbitrary constants,
you can use ``constants = numbered_symbols(prefix='C', cls=Symbol, start=1)``.
If it is possible to solve for the dependent function in a general way, do so.
Otherwise, do as best as you can, but do not call solve in your
``ode_<hint>()`` function. :py:meth:`~sympy.solvers.ode.ode.odesimp` will attempt
to solve the solution for you, so you do not need to do that. Lastly, if your
ODE has a common simplification that can be applied to your solutions, you can
add a special case in :py:meth:`~sympy.solvers.ode.ode.odesimp` for it. For
example, solutions returned from the ``1st_homogeneous_coeff`` hints often
have many :obj:`~sympy.functions.elementary.exponential.log` terms, so
:py:meth:`~sympy.solvers.ode.ode.odesimp` calls
:py:meth:`~sympy.simplify.simplify.logcombine` on them (it also helps to write
the arbitrary constant as ``log(C1)`` instead of ``C1`` in this case). Also
consider common ways that you can rearrange your solution to have
:py:meth:`~sympy.solvers.ode.constantsimp` take better advantage of it. It is
better to put simplification in :py:meth:`~sympy.solvers.ode.ode.odesimp` than in
your method, because it can then be turned off with the simplify flag in
:py:meth:`~sympy.solvers.ode.dsolve`. If you have any extraneous
simplification in your function, be sure to only run it using ``if
match.get('simplify', True):``, especially if it can be slow or if it can
reduce the domain of the solution.
Finally, as with every contribution to SymPy, your method will need to be
tested. Add a test for each method in ``test_ode.py``. Follow the
conventions there, i.e., test the solver using ``dsolve(eq, f(x),
hint=your_hint)``, and also test the solution using
:py:meth:`~sympy.solvers.ode.checkodesol` (you can put these in a separate
tests and skip/XFAIL if it runs too slow/does not work). Be sure to call your
hint specifically in :py:meth:`~sympy.solvers.ode.dsolve`, that way the test
will not be broken simply by the introduction of another matching hint. If your
method works for higher order (>1) ODEs, you will need to run ``sol =
constant_renumber(sol, 'C', 1, order)`` for each solution, where ``order`` is
the order of the ODE. This is because ``constant_renumber`` renumbers the
arbitrary constants by printing order, which is platform dependent. Try to
test every corner case of your solver, including a range of orders if it is a
`n`\th order solver, but if your solver is slow, such as if it involves hard
integration, try to keep the test run time down.
Feel free to refactor existing hints to avoid duplicating code or creating
inconsistencies. If you can show that your method exactly duplicates an
existing method, including in the simplicity and speed of obtaining the
solutions, then you can remove the old, less general method. The existing
code is tested extensively in ``test_ode.py``, so if anything is broken, one
of those tests will surely fail.
"""
from sympy.core import Add, S, Mul, Pow, oo
from sympy.core.containers import Tuple
from sympy.core.expr import AtomicExpr, Expr
from sympy.core.function import (Function, Derivative, AppliedUndef, diff,
expand, expand_mul, Subs)
from sympy.core.multidimensional import vectorize
from sympy.core.numbers import nan, zoo, Number
from sympy.core.relational import Equality, Eq
from sympy.core.sorting import default_sort_key, ordered
from sympy.core.symbol import Symbol, Wild, Dummy, symbols
from sympy.core.sympify import sympify
from sympy.core.traversal import preorder_traversal
from sympy.logic.boolalg import (BooleanAtom, BooleanTrue,
BooleanFalse)
from sympy.functions import exp, log, sqrt
from sympy.functions.combinatorial.factorials import factorial
from sympy.integrals.integrals import Integral
from sympy.polys import (Poly, terms_gcd, PolynomialError, lcm)
from sympy.polys.polytools import cancel
from sympy.series import Order
from sympy.series.series import series
from sympy.simplify import (collect, logcombine, powsimp, # type: ignore
separatevars, simplify, cse)
from sympy.simplify.radsimp import collect_const
from sympy.solvers import checksol, solve
from sympy.utilities import numbered_symbols
from sympy.utilities.iterables import uniq, sift, iterable
from sympy.solvers.deutils import _preprocess, ode_order, _desolve
#: This is a list of hints in the order that they should be preferred by
#: :py:meth:`~sympy.solvers.ode.classify_ode`. In general, hints earlier in the
#: list should produce simpler solutions than those later in the list (for
#: ODEs that fit both). For now, the order of this list is based on empirical
#: observations by the developers of SymPy.
#:
#: The hint used by :py:meth:`~sympy.solvers.ode.dsolve` for a specific ODE
#: can be overridden (see the docstring).
#:
#: In general, ``_Integral`` hints are grouped at the end of the list, unless
#: there is a method that returns an unevaluable integral most of the time
#: (which go near the end of the list anyway). ``default``, ``all``,
#: ``best``, and ``all_Integral`` meta-hints should not be included in this
#: list, but ``_best`` and ``_Integral`` hints should be included.
allhints = (
"factorable",
"nth_algebraic",
"separable",
"1st_exact",
"1st_linear",
"Bernoulli",
"1st_rational_riccati",
"Riccati_special_minus2",
"1st_homogeneous_coeff_best",
"1st_homogeneous_coeff_subs_indep_div_dep",
"1st_homogeneous_coeff_subs_dep_div_indep",
"almost_linear",
"linear_coefficients",
"separable_reduced",
"1st_power_series",
"lie_group",
"nth_linear_constant_coeff_homogeneous",
"nth_linear_euler_eq_homogeneous",
"nth_linear_constant_coeff_undetermined_coefficients",
"nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients",
"nth_linear_constant_coeff_variation_of_parameters",
"nth_linear_euler_eq_nonhomogeneous_variation_of_parameters",
"Liouville",
"2nd_linear_airy",
"2nd_linear_bessel",
"2nd_hypergeometric",
"2nd_hypergeometric_Integral",
"nth_order_reducible",
"2nd_power_series_ordinary",
"2nd_power_series_regular",
"nth_algebraic_Integral",
"separable_Integral",
"1st_exact_Integral",
"1st_linear_Integral",
"Bernoulli_Integral",
"1st_homogeneous_coeff_subs_indep_div_dep_Integral",
"1st_homogeneous_coeff_subs_dep_div_indep_Integral",
"almost_linear_Integral",
"linear_coefficients_Integral",
"separable_reduced_Integral",
"nth_linear_constant_coeff_variation_of_parameters_Integral",
"nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral",
"Liouville_Integral",
"2nd_nonlinear_autonomous_conserved",
"2nd_nonlinear_autonomous_conserved_Integral",
)
def get_numbered_constants(eq, num=1, start=1, prefix='C'):
"""
Returns a list of constants that do not occur
in eq already.
"""
ncs = iter_numbered_constants(eq, start, prefix)
Cs = [next(ncs) for i in range(num)]
return (Cs[0] if num == 1 else tuple(Cs))
def iter_numbered_constants(eq, start=1, prefix='C'):
"""
Returns an iterator of constants that do not occur
in eq already.
"""
if isinstance(eq, (Expr, Eq)):
eq = [eq]
elif not iterable(eq):
raise ValueError("Expected Expr or iterable but got %s" % eq)
atom_set = set().union(*[i.free_symbols for i in eq])
func_set = set().union(*[i.atoms(Function) for i in eq])
if func_set:
atom_set |= {Symbol(str(f.func)) for f in func_set}
return numbered_symbols(start=start, prefix=prefix, exclude=atom_set)
def dsolve(eq, func=None, hint="default", simplify=True,
ics= None, xi=None, eta=None, x0=0, n=6, **kwargs):
r"""
Solves any (supported) kind of ordinary differential equation and
system of ordinary differential equations.
For single ordinary differential equation
=========================================
It is classified under this when number of equation in ``eq`` is one.
**Usage**
``dsolve(eq, f(x), hint)`` -> Solve ordinary differential equation
``eq`` for function ``f(x)``, using method ``hint``.
**Details**
``eq`` can be any supported ordinary differential equation (see the
:py:mod:`~sympy.solvers.ode` docstring for supported methods).
This can either be an :py:class:`~sympy.core.relational.Equality`,
or an expression, which is assumed to be equal to ``0``.
``f(x)`` is a function of one variable whose derivatives in that
variable make up the ordinary differential equation ``eq``. In
many cases it is not necessary to provide this; it will be
autodetected (and an error raised if it could not be detected).
``hint`` is the solving method that you want dsolve to use. Use
``classify_ode(eq, f(x))`` to get all of the possible hints for an
ODE. The default hint, ``default``, will use whatever hint is
returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. See
Hints below for more options that you can use for hint.
``simplify`` enables simplification by
:py:meth:`~sympy.solvers.ode.ode.odesimp`. See its docstring for more
information. Turn this off, for example, to disable solving of
solutions for ``func`` or simplification of arbitrary constants.
It will still integrate with this hint. Note that the solution may
contain more arbitrary constants than the order of the ODE with
this option enabled.
``xi`` and ``eta`` are the infinitesimal functions of an ordinary
differential equation. They are the infinitesimals of the Lie group
of point transformations for which the differential equation is
invariant. The user can specify values for the infinitesimals. If
nothing is specified, ``xi`` and ``eta`` are calculated using
:py:meth:`~sympy.solvers.ode.infinitesimals` with the help of various
heuristics.
``ics`` is the set of initial/boundary conditions for the differential equation.
It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2):
x3}`` and so on. For power series solutions, if no initial
conditions are specified ``f(0)`` is assumed to be ``C0`` and the power
series solution is calculated about 0.
``x0`` is the point about which the power series solution of a differential
equation is to be evaluated.
``n`` gives the exponent of the dependent variable up to which the power series
solution of a differential equation is to be evaluated.
**Hints**
Aside from the various solving methods, there are also some meta-hints
that you can pass to :py:meth:`~sympy.solvers.ode.dsolve`:
``default``:
This uses whatever hint is returned first by
:py:meth:`~sympy.solvers.ode.classify_ode`. This is the
default argument to :py:meth:`~sympy.solvers.ode.dsolve`.
``all``:
To make :py:meth:`~sympy.solvers.ode.dsolve` apply all
relevant classification hints, use ``dsolve(ODE, func,
hint="all")``. This will return a dictionary of
``hint:solution`` terms. If a hint causes dsolve to raise the
``NotImplementedError``, value of that hint's key will be the
exception object raised. The dictionary will also include
some special keys:
- ``order``: The order of the ODE. See also
:py:meth:`~sympy.solvers.deutils.ode_order` in
``deutils.py``.
- ``best``: The simplest hint; what would be returned by
``best`` below.
- ``best_hint``: The hint that would produce the solution
given by ``best``. If more than one hint produces the best
solution, the first one in the tuple returned by
:py:meth:`~sympy.solvers.ode.classify_ode` is chosen.
- ``default``: The solution that would be returned by default.
This is the one produced by the hint that appears first in
the tuple returned by
:py:meth:`~sympy.solvers.ode.classify_ode`.
``all_Integral``:
This is the same as ``all``, except if a hint also has a
corresponding ``_Integral`` hint, it only returns the
``_Integral`` hint. This is useful if ``all`` causes
:py:meth:`~sympy.solvers.ode.dsolve` to hang because of a
difficult or impossible integral. This meta-hint will also be
much faster than ``all``, because
:py:meth:`~sympy.core.expr.Expr.integrate` is an expensive
routine.
``best``:
To have :py:meth:`~sympy.solvers.ode.dsolve` try all methods
and return the simplest one. This takes into account whether
the solution is solvable in the function, whether it contains
any Integral classes (i.e. unevaluatable integrals), and
which one is the shortest in size.
See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for
more info on hints, and the :py:mod:`~sympy.solvers.ode` docstring for
a list of all supported hints.
**Tips**
- You can declare the derivative of an unknown function this way:
>>> from sympy import Function, Derivative
>>> from sympy.abc import x # x is the independent variable
>>> f = Function("f")(x) # f is a function of x
>>> # f_ will be the derivative of f with respect to x
>>> f_ = Derivative(f, x)
- See ``test_ode.py`` for many tests, which serves also as a set of
examples for how to use :py:meth:`~sympy.solvers.ode.dsolve`.
- :py:meth:`~sympy.solvers.ode.dsolve` always returns an
:py:class:`~sympy.core.relational.Equality` class (except for the
case when the hint is ``all`` or ``all_Integral``). If possible, it
solves the solution explicitly for the function being solved for.
Otherwise, it returns an implicit solution.
- Arbitrary constants are symbols named ``C1``, ``C2``, and so on.
- Because all solutions should be mathematically equivalent, some
hints may return the exact same result for an ODE. Often, though,
two different hints will return the same solution formatted
differently. The two should be equivalent. Also note that sometimes
the values of the arbitrary constants in two different solutions may
not be the same, because one constant may have "absorbed" other
constants into it.
- Do ``help(ode.ode_<hintname>)`` to get help more information on a
specific hint, where ``<hintname>`` is the name of a hint without
``_Integral``.
For system of ordinary differential equations
=============================================
**Usage**
``dsolve(eq, func)`` -> Solve a system of ordinary differential
equations ``eq`` for ``func`` being list of functions including
`x(t)`, `y(t)`, `z(t)` where number of functions in the list depends
upon the number of equations provided in ``eq``.
**Details**
``eq`` can be any supported system of ordinary differential equations
This can either be an :py:class:`~sympy.core.relational.Equality`,
or an expression, which is assumed to be equal to ``0``.
``func`` holds ``x(t)`` and ``y(t)`` being functions of one variable which
together with some of their derivatives make up the system of ordinary
differential equation ``eq``. It is not necessary to provide this; it
will be autodetected (and an error raised if it could not be detected).
**Hints**
The hints are formed by parameters returned by classify_sysode, combining
them give hints name used later for forming method name.
Examples
========
>>> from sympy import Function, dsolve, Eq, Derivative, sin, cos, symbols
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(Derivative(f(x), x, x) + 9*f(x), f(x))
Eq(f(x), C1*sin(3*x) + C2*cos(3*x))
>>> eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x)
>>> dsolve(eq, hint='1st_exact')
[Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
>>> dsolve(eq, hint='almost_linear')
[Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
>>> t = symbols('t')
>>> x, y = symbols('x, y', cls=Function)
>>> eq = (Eq(Derivative(x(t),t), 12*t*x(t) + 8*y(t)), Eq(Derivative(y(t),t), 21*x(t) + 7*t*y(t)))
>>> dsolve(eq)
[Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t)),
Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t) +
exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)))]
>>> eq = (Eq(Derivative(x(t),t),x(t)*y(t)*sin(t)), Eq(Derivative(y(t),t),y(t)**2*sin(t)))
>>> dsolve(eq)
{Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t))), Eq(y(t), -1/(C1 - cos(t)))}
"""
if iterable(eq):
from sympy.solvers.ode.systems import dsolve_system
# This may have to be changed in future
# when we have weakly and strongly
# connected components. This have to
# changed to show the systems that haven't
# been solved.
try:
sol = dsolve_system(eq, funcs=func, ics=ics, doit=True)
return sol[0] if len(sol) == 1 else sol
except NotImplementedError:
pass
match = classify_sysode(eq, func)
eq = match['eq']
order = match['order']
func = match['func']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
# keep highest order term coefficient positive
for i in range(len(eq)):
for func_ in func:
if isinstance(func_, list):
pass
else:
if eq[i].coeff(diff(func[i],t,ode_order(eq[i], func[i]))).is_negative:
eq[i] = -eq[i]
match['eq'] = eq
if len(set(order.values()))!=1:
raise ValueError("It solves only those systems of equations whose orders are equal")
match['order'] = list(order.values())[0]
def recur_len(l):
return sum(recur_len(item) if isinstance(item,list) else 1 for item in l)
if recur_len(func) != len(eq):
raise ValueError("dsolve() and classify_sysode() work with "
"number of functions being equal to number of equations")
if match['type_of_equation'] is None:
raise NotImplementedError
else:
if match['is_linear'] == True:
solvefunc = globals()['sysode_linear_%(no_of_equation)seq_order%(order)s' % match]
else:
solvefunc = globals()['sysode_nonlinear_%(no_of_equation)seq_order%(order)s' % match]
sols = solvefunc(match)
if ics:
constants = Tuple(*sols).free_symbols - Tuple(*eq).free_symbols
solved_constants = solve_ics(sols, func, constants, ics)
return [sol.subs(solved_constants) for sol in sols]
return sols
else:
given_hint = hint # hint given by the user
# See the docstring of _desolve for more details.
hints = _desolve(eq, func=func,
hint=hint, simplify=True, xi=xi, eta=eta, type='ode', ics=ics,
x0=x0, n=n, **kwargs)
eq = hints.pop('eq', eq)
all_ = hints.pop('all', False)
if all_:
retdict = {}
failed_hints = {}
gethints = classify_ode(eq, dict=True, hint='all')
orderedhints = gethints['ordered_hints']
for hint in hints:
try:
rv = _helper_simplify(eq, hint, hints[hint], simplify)
except NotImplementedError as detail:
failed_hints[hint] = detail
else:
retdict[hint] = rv
func = hints[hint]['func']
retdict['best'] = min(list(retdict.values()), key=lambda x:
ode_sol_simplicity(x, func, trysolving=not simplify))
if given_hint == 'best':
return retdict['best']
for i in orderedhints:
if retdict['best'] == retdict.get(i, None):
retdict['best_hint'] = i
break
retdict['default'] = gethints['default']
retdict['order'] = gethints['order']
retdict.update(failed_hints)
return retdict
else:
# The key 'hint' stores the hint needed to be solved for.
hint = hints['hint']
return _helper_simplify(eq, hint, hints, simplify, ics=ics)
def _helper_simplify(eq, hint, match, simplify=True, ics=None, **kwargs):
r"""
Helper function of dsolve that calls the respective
:py:mod:`~sympy.solvers.ode` functions to solve for the ordinary
differential equations. This minimizes the computation in calling
:py:meth:`~sympy.solvers.deutils._desolve` multiple times.
"""
r = match
func = r['func']
order = r['order']
match = r[hint]
if isinstance(match, SingleODESolver):
solvefunc = match
elif hint.endswith('_Integral'):
solvefunc = globals()['ode_' + hint[:-len('_Integral')]]
else:
solvefunc = globals()['ode_' + hint]
free = eq.free_symbols
cons = lambda s: s.free_symbols.difference(free)
if simplify:
# odesimp() will attempt to integrate, if necessary, apply constantsimp(),
# attempt to solve for func, and apply any other hint specific
# simplifications
if isinstance(solvefunc, SingleODESolver):
sols = solvefunc.get_general_solution()
else:
sols = solvefunc(eq, func, order, match)
if iterable(sols):
rv = [odesimp(eq, s, func, hint) for s in sols]
else:
rv = odesimp(eq, sols, func, hint)
else:
# We still want to integrate (you can disable it separately with the hint)
if isinstance(solvefunc, SingleODESolver):
exprs = solvefunc.get_general_solution(simplify=False)
else:
match['simplify'] = False # Some hints can take advantage of this option
exprs = solvefunc(eq, func, order, match)
if isinstance(exprs, list):
rv = [_handle_Integral(expr, func, hint) for expr in exprs]
else:
rv = _handle_Integral(exprs, func, hint)
if isinstance(rv, list):
if simplify:
rv = _remove_redundant_solutions(eq, rv, order, func.args[0])
if len(rv) == 1:
rv = rv[0]
if ics and 'power_series' not in hint:
if isinstance(rv, (Expr, Eq)):
solved_constants = solve_ics([rv], [r['func']], cons(rv), ics)
rv = rv.subs(solved_constants)
else:
rv1 = []
for s in rv:
try:
solved_constants = solve_ics([s], [r['func']], cons(s), ics)
except ValueError:
continue
rv1.append(s.subs(solved_constants))
if len(rv1) == 1:
return rv1[0]
rv = rv1
return rv
def solve_ics(sols, funcs, constants, ics):
"""
Solve for the constants given initial conditions
``sols`` is a list of solutions.
``funcs`` is a list of functions.
``constants`` is a list of constants.
``ics`` is the set of initial/boundary conditions for the differential
equation. It should be given in the form of ``{f(x0): x1,
f(x).diff(x).subs(x, x2): x3}`` and so on.
Returns a dictionary mapping constants to values.
``solution.subs(constants)`` will replace the constants in ``solution``.
Example
=======
>>> # From dsolve(f(x).diff(x) - f(x), f(x))
>>> from sympy import symbols, Eq, exp, Function
>>> from sympy.solvers.ode.ode import solve_ics
>>> f = Function('f')
>>> x, C1 = symbols('x C1')
>>> sols = [Eq(f(x), C1*exp(x))]
>>> funcs = [f(x)]
>>> constants = [C1]
>>> ics = {f(0): 2}
>>> solved_constants = solve_ics(sols, funcs, constants, ics)
>>> solved_constants
{C1: 2}
>>> sols[0].subs(solved_constants)
Eq(f(x), 2*exp(x))
"""
# Assume ics are of the form f(x0): value or Subs(diff(f(x), x, n), (x,
# x0)): value (currently checked by classify_ode). To solve, replace x
# with x0, f(x0) with value, then solve for constants. For f^(n)(x0),
# differentiate the solution n times, so that f^(n)(x) appears.
x = funcs[0].args[0]
diff_sols = []
subs_sols = []
diff_variables = set()
for funcarg, value in ics.items():
if isinstance(funcarg, AppliedUndef):
x0 = funcarg.args[0]
matching_func = [f for f in funcs if f.func == funcarg.func][0]
S = sols
elif isinstance(funcarg, (Subs, Derivative)):
if isinstance(funcarg, Subs):
# Make sure it stays a subs. Otherwise subs below will produce
# a different looking term.
funcarg = funcarg.doit()
if isinstance(funcarg, Subs):
deriv = funcarg.expr
x0 = funcarg.point[0]
variables = funcarg.expr.variables
matching_func = deriv
elif isinstance(funcarg, Derivative):
deriv = funcarg
x0 = funcarg.variables[0]
variables = (x,)*len(funcarg.variables)
matching_func = deriv.subs(x0, x)
for sol in sols:
if sol.has(deriv.expr.func):
diff_sols.append(Eq(sol.lhs.diff(*variables), sol.rhs.diff(*variables)))
diff_variables.add(variables)
S = diff_sols
else:
raise NotImplementedError("Unrecognized initial condition")
for sol in S:
if sol.has(matching_func):
sol2 = sol
sol2 = sol2.subs(x, x0)
sol2 = sol2.subs(funcarg, value)
# This check is necessary because of issue #15724
if not isinstance(sol2, BooleanAtom) or not subs_sols:
subs_sols = [s for s in subs_sols if not isinstance(s, BooleanAtom)]
subs_sols.append(sol2)
# TODO: Use solveset here
try:
solved_constants = solve(subs_sols, constants, dict=True)
except NotImplementedError:
solved_constants = []
# XXX: We can't differentiate between the solution not existing because of
# invalid initial conditions, and not existing because solve is not smart
# enough. If we could use solveset, this might be improvable, but for now,
# we use NotImplementedError in this case.
if not solved_constants:
raise ValueError("Couldn't solve for initial conditions")
if solved_constants == True:
raise ValueError("Initial conditions did not produce any solutions for constants. Perhaps they are degenerate.")
if len(solved_constants) > 1:
raise NotImplementedError("Initial conditions produced too many solutions for constants")
return solved_constants[0]
def classify_ode(eq, func=None, dict=False, ics=None, *, prep=True, xi=None, eta=None, n=None, **kwargs):
r"""
Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve`
classifications for an ODE.
The tuple is ordered so that first item is the classification that
:py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In
general, classifications at the near the beginning of the list will
produce better solutions faster than those near the end, thought there are
always exceptions. To make :py:meth:`~sympy.solvers.ode.dsolve` use a
different classification, use ``dsolve(ODE, func,
hint=<classification>)``. See also the
:py:meth:`~sympy.solvers.ode.dsolve` docstring for different meta-hints
you can use.
If ``dict`` is true, :py:meth:`~sympy.solvers.ode.classify_ode` will
return a dictionary of ``hint:match`` expression terms. This is intended
for internal use by :py:meth:`~sympy.solvers.ode.dsolve`. Note that
because dictionaries are ordered arbitrarily, this will most likely not be
in the same order as the tuple.
You can get help on different hints by executing
``help(ode.ode_hintname)``, where ``hintname`` is the name of the hint
without ``_Integral``.
See :py:data:`~sympy.solvers.ode.allhints` or the
:py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints
that can be returned from :py:meth:`~sympy.solvers.ode.classify_ode`.
Notes
=====
These are remarks on hint names.
``_Integral``
If a classification has ``_Integral`` at the end, it will return the
expression with an unevaluated :py:class:`~.Integral`
class in it. Note that a hint may do this anyway if
:py:meth:`~sympy.core.expr.Expr.integrate` cannot do the integral,
though just using an ``_Integral`` will do so much faster. Indeed, an
``_Integral`` hint will always be faster than its corresponding hint
without ``_Integral`` because
:py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine.
If :py:meth:`~sympy.solvers.ode.dsolve` hangs, it is probably because
:py:meth:`~sympy.core.expr.Expr.integrate` is hanging on a tough or
impossible integral. Try using an ``_Integral`` hint or
``all_Integral`` to get it return something.
Note that some hints do not have ``_Integral`` counterparts. This is
because :py:func:`~sympy.integrals.integrals.integrate` is not used in
solving the ODE for those method. For example, `n`\th order linear
homogeneous ODEs with constant coefficients do not require integration
to solve, so there is no
``nth_linear_homogeneous_constant_coeff_Integrate`` hint. You can
easily evaluate any unevaluated
:py:class:`~sympy.integrals.integrals.Integral`\s in an expression by
doing ``expr.doit()``.
Ordinals
Some hints contain an ordinal such as ``1st_linear``. This is to help
differentiate them from other hints, as well as from other methods
that may not be implemented yet. If a hint has ``nth`` in it, such as
the ``nth_linear`` hints, this means that the method used to applies
to ODEs of any order.
``indep`` and ``dep``
Some hints contain the words ``indep`` or ``dep``. These reference
the independent variable and the dependent function, respectively. For
example, if an ODE is in terms of `f(x)`, then ``indep`` will refer to
`x` and ``dep`` will refer to `f`.
``subs``
If a hints has the word ``subs`` in it, it means that the ODE is solved
by substituting the expression given after the word ``subs`` for a
single dummy variable. This is usually in terms of ``indep`` and
``dep`` as above. The substituted expression will be written only in
characters allowed for names of Python objects, meaning operators will
be spelled out. For example, ``indep``/``dep`` will be written as
``indep_div_dep``.
``coeff``
The word ``coeff`` in a hint refers to the coefficients of something
in the ODE, usually of the derivative terms. See the docstring for
the individual methods for more info (``help(ode)``). This is
contrast to ``coefficients``, as in ``undetermined_coefficients``,
which refers to the common name of a method.
``_best``
Methods that have more than one fundamental way to solve will have a
hint for each sub-method and a ``_best`` meta-classification. This
will evaluate all hints and return the best, using the same
considerations as the normal ``best`` meta-hint.
Examples
========
>>> from sympy import Function, classify_ode, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> classify_ode(Eq(f(x).diff(x), 0), f(x))
('nth_algebraic',
'separable',
'1st_exact',
'1st_linear',
'Bernoulli',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral',
'1st_linear_Integral', 'Bernoulli_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
>>> classify_ode(f(x).diff(x, 2) + 3*f(x).diff(x) + 2*f(x) - 4)
('factorable', 'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
"""
ics = sympify(ics)
if func and len(func.args) != 1:
raise ValueError("dsolve() and classify_ode() only "
"work with functions of one variable, not %s" % func)
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
# Some methods want the unprocessed equation
eq_orig = eq
if prep or func is None:
eq, func_ = _preprocess(eq, func)
if func is None:
func = func_
x = func.args[0]
f = func.func
y = Dummy('y')
terms = 5 if n is None else n
order = ode_order(eq, f(x))
# hint:matchdict or hint:(tuple of matchdicts)
# Also will contain "default":<default hint> and "order":order items.
matching_hints = {"order": order}
df = f(x).diff(x)
a = Wild('a', exclude=[f(x)])
d = Wild('d', exclude=[df, f(x).diff(x, 2)])
e = Wild('e', exclude=[df])
n = Wild('n', exclude=[x, f(x), df])
c1 = Wild('c1', exclude=[x])
a3 = Wild('a3', exclude=[f(x), df, f(x).diff(x, 2)])
b3 = Wild('b3', exclude=[f(x), df, f(x).diff(x, 2)])
c3 = Wild('c3', exclude=[f(x), df, f(x).diff(x, 2)])
boundary = {} # Used to extract initial conditions
C1 = Symbol("C1")
# Preprocessing to get the initial conditions out
if ics is not None:
for funcarg in ics:
# Separating derivatives
if isinstance(funcarg, (Subs, Derivative)):
# f(x).diff(x).subs(x, 0) is a Subs, but f(x).diff(x).subs(x,
# y) is a Derivative
if isinstance(funcarg, Subs):
deriv = funcarg.expr
old = funcarg.variables[0]
new = funcarg.point[0]
elif isinstance(funcarg, Derivative):
deriv = funcarg
# No information on this. Just assume it was x
old = x
new = funcarg.variables[0]
if (isinstance(deriv, Derivative) and isinstance(deriv.args[0],
AppliedUndef) and deriv.args[0].func == f and
len(deriv.args[0].args) == 1 and old == x and not
new.has(x) and all(i == deriv.variables[0] for i in
deriv.variables) and x not in ics[funcarg].free_symbols):
dorder = ode_order(deriv, x)
temp = 'f' + str(dorder)
boundary.update({temp: new, temp + 'val': ics[funcarg]})
else:
raise ValueError("Invalid 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 x not in ics[funcarg].free_symbols):
boundary.update({'f0': funcarg.args[0], 'f0val': ics[funcarg]})
else:
raise ValueError("Invalid boundary conditions for Function")
else:
raise ValueError("Enter boundary conditions of the form ics={f(point): value, f(x).diff(x, order).subs(x, point): value}")
ode = SingleODEProblem(eq_orig, func, x, prep=prep, xi=xi, eta=eta)
user_hint = kwargs.get('hint', 'default')
# Used when dsolve is called without an explicit hint.
# We exit early to return the first valid match
early_exit = (user_hint=='default')
if user_hint.endswith('_Integral'):
user_hint = user_hint[:-len('_Integral')]
user_map = solver_map
# An explicit hint has been given to dsolve
# Skip matching code for other hints
if user_hint not in ['default', 'all', 'all_Integral', 'best'] and user_hint in solver_map:
user_map = {user_hint: solver_map[user_hint]}
for hint in user_map:
solver = user_map[hint](ode)
if solver.matches():
matching_hints[hint] = solver
if user_map[hint].has_integral:
matching_hints[hint + "_Integral"] = solver
if dict and early_exit:
matching_hints["default"] = hint
return matching_hints
eq = expand(eq)
# Precondition to try remove f(x) from highest order derivative
reduced_eq = None
if eq.is_Add:
deriv_coef = eq.coeff(f(x).diff(x, order))
if deriv_coef not in (1, 0):
r = deriv_coef.match(a*f(x)**c1)
if r and r[c1]:
den = f(x)**r[c1]
reduced_eq = Add(*[arg/den for arg in eq.args])
if not reduced_eq:
reduced_eq = eq
if order == 1:
# NON-REDUCED FORM OF EQUATION matches
r = collect(eq, df, exact=True).match(d + e * df)
if r:
r['d'] = d
r['e'] = e
r['y'] = y
r[d] = r[d].subs(f(x), y)
r[e] = r[e].subs(f(x), y)
# FIRST ORDER POWER SERIES WHICH NEEDS INITIAL CONDITIONS
# TODO: Hint first order series should match only if d/e is analytic.
# For now, only d/e and (d/e).diff(arg) is checked for existence at
# at a given point.
# This is currently done internally in ode_1st_power_series.
point = boundary.get('f0', 0)
value = boundary.get('f0val', C1)
check = cancel(r[d]/r[e])
check1 = check.subs({x: point, y: value})
if not check1.has(oo) and not check1.has(zoo) and \
not check1.has(nan) and not check1.has(-oo):
check2 = (check1.diff(x)).subs({x: point, y: value})
if not check2.has(oo) and not check2.has(zoo) and \
not check2.has(nan) and not check2.has(-oo):
rseries = r.copy()
rseries.update({'terms': terms, 'f0': point, 'f0val': value})
matching_hints["1st_power_series"] = rseries
elif order == 2:
# Homogeneous second order differential equation of the form
# a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3
# It has a definite power series solution at point x0 if, b3/a3 and c3/a3
# are analytic at x0.
deq = a3*(f(x).diff(x, 2)) + b3*df + c3*f(x)
r = collect(reduced_eq,
[f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
ordinary = False
if r:
if not all(r[key].is_polynomial() for key in r):
n, d = reduced_eq.as_numer_denom()
reduced_eq = expand(n)
r = collect(reduced_eq,
[f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
if r and r[a3] != 0:
p = cancel(r[b3]/r[a3]) # Used below
q = cancel(r[c3]/r[a3]) # Used below
point = kwargs.get('x0', 0)
check = p.subs(x, point)
if not check.has(oo, nan, zoo, -oo):
check = q.subs(x, point)
if not check.has(oo, nan, zoo, -oo):
ordinary = True
r.update({'a3': a3, 'b3': b3, 'c3': c3, 'x0': point, 'terms': terms})
matching_hints["2nd_power_series_ordinary"] = r
# Checking if the differential equation has a regular singular point
# at x0. It has a regular singular point at x0, if (b3/a3)*(x - x0)
# and (c3/a3)*((x - x0)**2) are analytic at x0.
if not ordinary:
p = cancel((x - point)*p)
check = p.subs(x, point)
if not check.has(oo, nan, zoo, -oo):
q = cancel(((x - point)**2)*q)
check = q.subs(x, point)
if not check.has(oo, nan, zoo, -oo):
coeff_dict = {'p': p, 'q': q, 'x0': point, 'terms': terms}
matching_hints["2nd_power_series_regular"] = coeff_dict
# Order keys based on allhints.
retlist = [i for i in allhints if i in matching_hints]
if dict:
# Dictionaries are ordered arbitrarily, so make note of which
# hint would come first for dsolve(). Use an ordered dict in Py 3.
matching_hints["default"] = retlist[0] if retlist else None
matching_hints["ordered_hints"] = tuple(retlist)
return matching_hints
else:
return tuple(retlist)
def classify_sysode(eq, funcs=None, **kwargs):
r"""
Returns a dictionary of parameter names and values that define the system
of ordinary differential equations in ``eq``.
The parameters are further used in
:py:meth:`~sympy.solvers.ode.dsolve` for solving that system.
Some parameter names and values are:
'is_linear' (boolean), which tells whether the given system is linear.
Note that "linear" here refers to the operator: terms such as ``x*diff(x,t)`` are
nonlinear, whereas terms like ``sin(t)*diff(x,t)`` are still linear operators.
'func' (list) contains the :py:class:`~sympy.core.function.Function`s that
appear with a derivative in the ODE, i.e. those that we are trying to solve
the ODE for.
'order' (dict) with the maximum derivative for each element of the 'func'
parameter.
'func_coeff' (dict or Matrix) with the coefficient for each triple ``(equation number,
function, order)```. The coefficients are those subexpressions that do not
appear in 'func', and hence can be considered constant for purposes of ODE
solving. The value of this parameter can also be a Matrix if the system of ODEs are
linear first order of the form X' = AX where X is the vector of dependent variables.
Here, this function returns the coefficient matrix A.
'eq' (list) with the equations from ``eq``, sympified and transformed into
expressions (we are solving for these expressions to be zero).
'no_of_equations' (int) is the number of equations (same as ``len(eq)``).
'type_of_equation' (string) is an internal classification of the type of
ODE.
'is_constant' (boolean), which tells if the system of ODEs is constant coefficient
or not. This key is temporary addition for now and is in the match dict only when
the system of ODEs is linear first order constant coefficient homogeneous. So, this
key's value is True for now if it is available else it does not exist.
'is_homogeneous' (boolean), which tells if the system of ODEs is homogeneous. Like the
key 'is_constant', this key is a temporary addition and it is True since this key value
is available only when the system is linear first order constant coefficient homogeneous.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode-toc1.htm
-A. D. Polyanin and A. V. Manzhirov, Handbook of Mathematics for Engineers and Scientists
Examples
========
>>> from sympy import Function, Eq, symbols, diff
>>> from sympy.solvers.ode.ode import classify_sysode
>>> from sympy.abc import t
>>> f, x, y = symbols('f, x, y', cls=Function)
>>> k, l, m, n = symbols('k, l, m, n', Integer=True)
>>> x1 = diff(x(t), t) ; y1 = diff(y(t), t)
>>> x2 = diff(x(t), t, t) ; y2 = diff(y(t), t, t)
>>> eq = (Eq(x1, 12*x(t) - 6*y(t)), Eq(y1, 11*x(t) + 3*y(t)))
>>> classify_sysode(eq)
{'eq': [-12*x(t) + 6*y(t) + Derivative(x(t), t), -11*x(t) - 3*y(t) + Derivative(y(t), t)], 'func': [x(t), y(t)],
'func_coeff': {(0, x(t), 0): -12, (0, x(t), 1): 1, (0, y(t), 0): 6, (0, y(t), 1): 0, (1, x(t), 0): -11, (1, x(t), 1): 0, (1, y(t), 0): -3, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': None}
>>> eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t) + 2), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t)))
>>> classify_sysode(eq)
{'eq': [-t**2*y(t) - 5*t*x(t) + Derivative(x(t), t) - 2, t**2*x(t) - 5*t*y(t) + Derivative(y(t), t)],
'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -5*t, (0, x(t), 1): 1, (0, y(t), 0): -t**2, (0, y(t), 1): 0,
(1, x(t), 0): t**2, (1, x(t), 1): 0, (1, y(t), 0): -5*t, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2,
'order': {x(t): 1, y(t): 1}, 'type_of_equation': None}
"""
# Sympify equations and convert iterables of equations into
# a list of equations
def _sympify(eq):
return list(map(sympify, eq if iterable(eq) else [eq]))
eq, funcs = (_sympify(w) for w in [eq, funcs])
for i, fi in enumerate(eq):
if isinstance(fi, Equality):
eq[i] = fi.lhs - fi.rhs
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
matching_hints = {"no_of_equation":i+1}
matching_hints['eq'] = eq
if i==0:
raise ValueError("classify_sysode() works for systems of ODEs. "
"For scalar ODEs, classify_ode should be used")
# find all the functions if not given
order = {}
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 = {}
for func in funcs:
if not order.get(func, False):
max_order = 0
for i, eqs_ in enumerate(eq):
order_ = ode_order(eqs_,func)
if max_order < order_:
max_order = order_
eq_no = i
if eq_no in func_dict:
func_dict[eq_no] = [func_dict[eq_no], func]
else:
func_dict[eq_no] = func
order[func] = max_order
funcs = [func_dict[i] for i in range(len(func_dict))]
matching_hints['func'] = funcs
for func in funcs:
if isinstance(func, list):
for func_elem in func:
if len(func_elem.args) != 1:
raise ValueError("dsolve() and classify_sysode() work with "
"functions of one variable only, not %s" % func)
else:
if func and len(func.args) != 1:
raise ValueError("dsolve() and classify_sysode() work with "
"functions of one variable only, not %s" % func)
# find the order of all equation in system of odes
matching_hints["order"] = order
# find coefficients of terms f(t), diff(f(t),t) and higher derivatives
# and similarly for other functions g(t), diff(g(t),t) in all equations.
# Here j denotes the equation number, funcs[l] denotes the function about
# which we are talking about and k denotes the order of function funcs[l]
# whose coefficient we are calculating.
def linearity_check(eqs, j, func, is_linear_):
for k in range(order[func] + 1):
func_coef[j, func, k] = collect(eqs.expand(), [diff(func, t, k)]).coeff(diff(func, t, k))
if is_linear_ == True:
if func_coef[j, func, k] == 0:
if k == 0:
coef = eqs.as_independent(func, as_Add=True)[1]
for xr in range(1, ode_order(eqs,func) + 1):
coef -= eqs.as_independent(diff(func, t, xr), as_Add=True)[1]
if coef != 0:
is_linear_ = False
else:
if eqs.as_independent(diff(func, t, k), as_Add=True)[1]:
is_linear_ = False
else:
for func_ in funcs:
if isinstance(func_, list):
for elem_func_ in func_:
dep = func_coef[j, func, k].as_independent(elem_func_, as_Add=True)[1]
if dep != 0:
is_linear_ = False
else:
dep = func_coef[j, func, k].as_independent(func_, as_Add=True)[1]
if dep != 0:
is_linear_ = False
return is_linear_
func_coef = {}
is_linear = True
for j, eqs in enumerate(eq):
for func in funcs:
if isinstance(func, list):
for func_elem in func:
is_linear = linearity_check(eqs, j, func_elem, is_linear)
else:
is_linear = linearity_check(eqs, j, func, is_linear)
matching_hints['func_coeff'] = func_coef
matching_hints['is_linear'] = is_linear
if len(set(order.values())) == 1:
order_eq = list(matching_hints['order'].values())[0]
if matching_hints['is_linear'] == True:
if matching_hints['no_of_equation'] == 2:
if order_eq == 1:
type_of_equation = check_linear_2eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
# If the equation does not match up with any of the
# general case solvers in systems.py and the number
# of equations is greater than 2, then NotImplementedError
# should be raised.
else:
type_of_equation = None
else:
if matching_hints['no_of_equation'] == 2:
if order_eq == 1:
type_of_equation = check_nonlinear_2eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
elif matching_hints['no_of_equation'] == 3:
if order_eq == 1:
type_of_equation = check_nonlinear_3eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
else:
type_of_equation = None
else:
type_of_equation = None
matching_hints['type_of_equation'] = type_of_equation
return matching_hints
def check_linear_2eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = {}
# for equations Eq(a1*diff(x(t),t), b1*x(t) + c1*y(t) + d1)
# and Eq(a2*diff(y(t),t), b2*x(t) + c2*y(t) + d2)
r['a1'] = fc[0,x(t),1] ; r['a2'] = fc[1,y(t),1]
r['b1'] = -fc[0,x(t),0]/fc[0,x(t),1] ; r['b2'] = -fc[1,x(t),0]/fc[1,y(t),1]
r['c1'] = -fc[0,y(t),0]/fc[0,x(t),1] ; r['c2'] = -fc[1,y(t),0]/fc[1,y(t),1]
forcing = [S.Zero,S.Zero]
for i in range(2):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t)):
forcing[i] += j
if not (forcing[0].has(t) or forcing[1].has(t)):
# We can handle homogeneous case and simple constant forcings
r['d1'] = forcing[0]
r['d2'] = forcing[1]
else:
# Issue #9244: nonhomogeneous linear systems are not supported
return None
# Conditions to check for type 6 whose equations are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and
# Eq(diff(y(t),t), a*[f(t) + a*h(t)]x(t) + a*[g(t) - h(t)]*y(t))
p = 0
q = 0
p1 = cancel(r['b2']/(cancel(r['b2']/r['c2']).as_numer_denom()[0]))
p2 = cancel(r['b1']/(cancel(r['b1']/r['c1']).as_numer_denom()[0]))
for n, i in enumerate([p1, p2]):
for j in Mul.make_args(collect_const(i)):
if not j.has(t):
q = j
if q and n==0:
if ((r['b2']/j - r['b1'])/(r['c1'] - r['c2']/j)) == j:
p = 1
elif q and n==1:
if ((r['b1']/j - r['b2'])/(r['c2'] - r['c1']/j)) == j:
p = 2
# End of condition for type 6
if r['d1']!=0 or r['d2']!=0:
return None
else:
if not any(r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2'.split()):
return None
else:
r['b1'] = r['b1']/r['a1'] ; r['b2'] = r['b2']/r['a2']
r['c1'] = r['c1']/r['a1'] ; r['c2'] = r['c2']/r['a2']
if p:
return "type6"
else:
# Equations for type 7 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), h(t)*x(t) + p(t)*y(t))
return "type7"
def check_nonlinear_2eq_order1(eq, func, func_coef):
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
f = Wild('f')
g = Wild('g')
u, v = symbols('u, v', cls=Dummy)
def check_type(x, y):
r1 = eq[0].match(t*diff(x(t),t) - x(t) + f)
r2 = eq[1].match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t)
r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t)
if not (r1 and r2):
r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f)
r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t)
r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t)
if r1 and r2 and not (r1[f].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t) \
or r2[g].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t)):
return 'type5'
else:
return None
for func_ in func:
if isinstance(func_, list):
x = func[0][0].func
y = func[0][1].func
eq_type = check_type(x, y)
if not eq_type:
eq_type = check_type(y, x)
return eq_type
x = func[0].func
y = func[1].func
fc = func_coef
n = Wild('n', exclude=[x(t),y(t)])
f1 = Wild('f1', exclude=[v,t])
f2 = Wild('f2', exclude=[v,t])
g1 = Wild('g1', exclude=[u,t])
g2 = Wild('g2', exclude=[u,t])
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
r = eq[0].match(diff(x(t),t) - x(t)**n*f)
if r:
g = (diff(y(t),t) - eq[1])/r[f]
if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)):
return 'type1'
r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f)
if r:
g = (diff(y(t),t) - eq[1])/r[f]
if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)):
return 'type2'
g = Wild('g')
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
if r1 and r2 and not (r1[f].subs(x(t),u).subs(y(t),v).has(t) or \
r2[g].subs(x(t),u).subs(y(t),v).has(t)):
return 'type3'
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
num, den = (
(r1[f].subs(x(t),u).subs(y(t),v))/
(r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom()
R1 = num.match(f1*g1)
R2 = den.match(f2*g2)
# phi = (r1[f].subs(x(t),u).subs(y(t),v))/num
if R1 and R2:
return 'type4'
return None
def check_nonlinear_2eq_order2(eq, func, func_coef):
return None
def check_nonlinear_3eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
z = func[2].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
u, v, w = symbols('u, v, w', cls=Dummy)
a = Wild('a', exclude=[x(t), y(t), z(t), t])
b = Wild('b', exclude=[x(t), y(t), z(t), t])
c = Wild('c', exclude=[x(t), y(t), z(t), t])
f = Wild('f')
F1 = Wild('F1')
F2 = Wild('F2')
F3 = Wild('F3')
for i in range(3):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
r1 = eq[0].match(diff(x(t),t) - a*y(t)*z(t))
r2 = eq[1].match(diff(y(t),t) - b*z(t)*x(t))
r3 = eq[2].match(diff(z(t),t) - c*x(t)*y(t))
if r1 and r2 and r3:
num1, den1 = r1[a].as_numer_denom()
num2, den2 = r2[b].as_numer_denom()
num3, den3 = r3[c].as_numer_denom()
if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]):
return 'type1'
r = eq[0].match(diff(x(t),t) - y(t)*z(t)*f)
if r:
r1 = collect_const(r[f]).match(a*f)
r2 = ((diff(y(t),t) - eq[1])/r1[f]).match(b*z(t)*x(t))
r3 = ((diff(z(t),t) - eq[2])/r1[f]).match(c*x(t)*y(t))
if r1 and r2 and r3:
num1, den1 = r1[a].as_numer_denom()
num2, den2 = r2[b].as_numer_denom()
num3, den3 = r3[c].as_numer_denom()
if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]):
return 'type2'
r = eq[0].match(diff(x(t),t) - (F2-F3))
if r:
r1 = collect_const(r[F2]).match(c*F2)
r1.update(collect_const(r[F3]).match(b*F3))
if r1:
if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
r1[F2], r1[F3] = r1[F3], r1[F2]
r1[c], r1[b] = -r1[b], -r1[c]
r2 = eq[1].match(diff(y(t),t) - a*r1[F3] + r1[c]*F1)
if r2:
r3 = (eq[2] == diff(z(t),t) - r1[b]*r2[F1] + r2[a]*r1[F2])
if r1 and r2 and r3:
return 'type3'
r = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3)
if r:
r1 = collect_const(r[F2]).match(c*F2)
r1.update(collect_const(r[F3]).match(b*F3))
if r1:
if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
r1[F2], r1[F3] = r1[F3], r1[F2]
r1[c], r1[b] = -r1[b], -r1[c]
r2 = (diff(y(t),t) - eq[1]).match(a*x(t)*r1[F3] - r1[c]*z(t)*F1)
if r2:
r3 = (diff(z(t),t) - eq[2] == r1[b]*y(t)*r2[F1] - r2[a]*x(t)*r1[F2])
if r1 and r2 and r3:
return 'type4'
r = (diff(x(t),t) - eq[0]).match(x(t)*(F2 - F3))
if r:
r1 = collect_const(r[F2]).match(c*F2)
r1.update(collect_const(r[F3]).match(b*F3))
if r1:
if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
r1[F2], r1[F3] = r1[F3], r1[F2]
r1[c], r1[b] = -r1[b], -r1[c]
r2 = (diff(y(t),t) - eq[1]).match(y(t)*(a*r1[F3] - r1[c]*F1))
if r2:
r3 = (diff(z(t),t) - eq[2] == z(t)*(r1[b]*r2[F1] - r2[a]*r1[F2]))
if r1 and r2 and r3:
return 'type5'
return None
def check_nonlinear_3eq_order2(eq, func, func_coef):
return None
@vectorize(0)
def odesimp(ode, eq, func, hint):
r"""
Simplifies solutions of ODEs, including trying to solve for ``func`` and
running :py:meth:`~sympy.solvers.ode.constantsimp`.
It may use knowledge of the type of solution that the hint returns to
apply additional simplifications.
It also attempts to integrate any :py:class:`~sympy.integrals.integrals.Integral`\s
in the expression, if the hint is not an ``_Integral`` hint.
This function should have no effect on expressions returned by
:py:meth:`~sympy.solvers.ode.dsolve`, as
:py:meth:`~sympy.solvers.ode.dsolve` already calls
:py:meth:`~sympy.solvers.ode.ode.odesimp`, but the individual hint functions
do not call :py:meth:`~sympy.solvers.ode.ode.odesimp` (because the
:py:meth:`~sympy.solvers.ode.dsolve` wrapper does). Therefore, this
function is designed for mainly internal use.
Examples
========
>>> from sympy import sin, symbols, dsolve, pprint, Function
>>> from sympy.solvers.ode.ode import odesimp
>>> x, u2, C1= symbols('x,u2,C1')
>>> f = Function('f')
>>> eq = dsolve(x*f(x).diff(x) - f(x) - x*sin(f(x)/x), f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral',
... simplify=False)
>>> pprint(eq, wrap_line=False)
x
----
f(x)
/
|
| / 1 \
| -|u1 + -------|
| | /1 \|
| | sin|--||
| \ \u1//
log(f(x)) = log(C1) + | ---------------- d(u1)
| 2
| u1
|
/
>>> pprint(odesimp(eq, f(x), 1, {C1},
... hint='1st_homogeneous_coeff_subs_indep_div_dep'
... )) #doctest: +SKIP
x
--------- = C1
/f(x)\
tan|----|
\2*x /
"""
x = func.args[0]
f = func.func
C1 = get_numbered_constants(eq, num=1)
constants = eq.free_symbols - ode.free_symbols
# First, integrate if the hint allows it.
eq = _handle_Integral(eq, func, hint)
if hint.startswith("nth_linear_euler_eq_nonhomogeneous"):
eq = simplify(eq)
if not isinstance(eq, Equality):
raise TypeError("eq should be an instance of Equality")
# Second, clean up the arbitrary constants.
# Right now, nth linear hints can put as many as 2*order constants in an
# expression. If that number grows with another hint, the third argument
# here should be raised accordingly, or constantsimp() rewritten to handle
# an arbitrary number of constants.
eq = constantsimp(eq, constants)
# Lastly, now that we have cleaned up the expression, try solving for func.
# When CRootOf is implemented in solve(), we will want to return a CRootOf
# every time instead of an Equality.
# Get the f(x) on the left if possible.
if eq.rhs == func and not eq.lhs.has(func):
eq = [Eq(eq.rhs, eq.lhs)]
# make sure we are working with lists of solutions in simplified form.
if eq.lhs == func and not eq.rhs.has(func):
# The solution is already solved
eq = [eq]
else:
# The solution is not solved, so try to solve it
try:
floats = any(i.is_Float for i in eq.atoms(Number))
eqsol = solve(eq, func, force=True, rational=False if floats else None)
if not eqsol:
raise NotImplementedError
except (NotImplementedError, PolynomialError):
eq = [eq]
else:
def _expand(expr):
numer, denom = expr.as_numer_denom()
if denom.is_Add:
return expr
else:
return powsimp(expr.expand(), combine='exp', deep=True)
# XXX: the rest of odesimp() expects each ``t`` to be in a
# specific normal form: rational expression with numerator
# expanded, but with combined exponential functions (at
# least in this setup all tests pass).
eq = [Eq(f(x), _expand(t)) for t in eqsol]
# special simplification of the lhs.
if hint.startswith("1st_homogeneous_coeff"):
for j, eqi in enumerate(eq):
newi = logcombine(eqi, force=True)
if isinstance(newi.lhs, log) and newi.rhs == 0:
newi = Eq(newi.lhs.args[0]/C1, C1)
eq[j] = newi
# We cleaned up the constants before solving to help the solve engine with
# a simpler expression, but the solved expression could have introduced
# things like -C1, so rerun constantsimp() one last time before returning.
for i, eqi in enumerate(eq):
eq[i] = constantsimp(eqi, constants)
eq[i] = constant_renumber(eq[i], ode.free_symbols)
# If there is only 1 solution, return it;
# otherwise return the list of solutions.
if len(eq) == 1:
eq = eq[0]
return eq
def ode_sol_simplicity(sol, func, trysolving=True):
r"""
Returns an extended integer representing how simple a solution to an ODE
is.
The following things are considered, in order from most simple to least:
- ``sol`` is solved for ``func``.
- ``sol`` is not solved for ``func``, but can be if passed to solve (e.g.,
a solution returned by ``dsolve(ode, func, simplify=False``).
- If ``sol`` is not solved for ``func``, then base the result on the
length of ``sol``, as computed by ``len(str(sol))``.
- If ``sol`` has any unevaluated :py:class:`~sympy.integrals.integrals.Integral`\s,
this will automatically be considered less simple than any of the above.
This function returns an integer such that if solution A is simpler than
solution B by above metric, then ``ode_sol_simplicity(sola, func) <
ode_sol_simplicity(solb, func)``.
Currently, the following are the numbers returned, but if the heuristic is
ever improved, this may change. Only the ordering is guaranteed.
+----------------------------------------------+-------------------+
| Simplicity | Return |
+==============================================+===================+
| ``sol`` solved for ``func`` | ``-2`` |
+----------------------------------------------+-------------------+
| ``sol`` not solved for ``func`` but can be | ``-1`` |
+----------------------------------------------+-------------------+
| ``sol`` is not solved nor solvable for | ``len(str(sol))`` |
| ``func`` | |
+----------------------------------------------+-------------------+
| ``sol`` contains an | ``oo`` |
| :obj:`~sympy.integrals.integrals.Integral` | |
+----------------------------------------------+-------------------+
``oo`` here means the SymPy infinity, which should compare greater than
any integer.
If you already know :py:meth:`~sympy.solvers.solvers.solve` cannot solve
``sol``, you can use ``trysolving=False`` to skip that step, which is the
only potentially slow step. For example,
:py:meth:`~sympy.solvers.ode.dsolve` with the ``simplify=False`` flag
should do this.
If ``sol`` is a list of solutions, if the worst solution in the list
returns ``oo`` it returns that, otherwise it returns ``len(str(sol))``,
that is, the length of the string representation of the whole list.
Examples
========
This function is designed to be passed to ``min`` as the key argument,
such as ``min(listofsolutions, key=lambda i: ode_sol_simplicity(i,
f(x)))``.
>>> from sympy import symbols, Function, Eq, tan, Integral
>>> from sympy.solvers.ode.ode import ode_sol_simplicity
>>> x, C1, C2 = symbols('x, C1, C2')
>>> f = Function('f')
>>> ode_sol_simplicity(Eq(f(x), C1*x**2), f(x))
-2
>>> ode_sol_simplicity(Eq(x**2 + f(x), C1), f(x))
-1
>>> ode_sol_simplicity(Eq(f(x), C1*Integral(2*x, x)), f(x))
oo
>>> eq1 = Eq(f(x)/tan(f(x)/(2*x)), C1)
>>> eq2 = Eq(f(x)/tan(f(x)/(2*x) + f(x)), C2)
>>> [ode_sol_simplicity(eq, f(x)) for eq in [eq1, eq2]]
[28, 35]
>>> min([eq1, eq2], key=lambda i: ode_sol_simplicity(i, f(x)))
Eq(f(x)/tan(f(x)/(2*x)), C1)
"""
# TODO: if two solutions are solved for f(x), we still want to be
# able to get the simpler of the two
# See the docstring for the coercion rules. We check easier (faster)
# things here first, to save time.
if iterable(sol):
# See if there are Integrals
for i in sol:
if ode_sol_simplicity(i, func, trysolving=trysolving) == oo:
return oo
return len(str(sol))
if sol.has(Integral):
return oo
# Next, try to solve for func. This code will change slightly when CRootOf
# is implemented in solve(). Probably a CRootOf solution should fall
# somewhere between a normal solution and an unsolvable expression.
# First, see if they are already solved
if sol.lhs == func and not sol.rhs.has(func) or \
sol.rhs == func and not sol.lhs.has(func):
return -2
# We are not so lucky, try solving manually
if trysolving:
try:
sols = solve(sol, func)
if not sols:
raise NotImplementedError
except NotImplementedError:
pass
else:
return -1
# Finally, a naive computation based on the length of the string version
# of the expression. This may favor combined fractions because they
# will not have duplicate denominators, and may slightly favor expressions
# with fewer additions and subtractions, as those are separated by spaces
# by the printer.
# Additional ideas for simplicity heuristics are welcome, like maybe
# checking if a equation has a larger domain, or if constantsimp has
# introduced arbitrary constants numbered higher than the order of a
# given ODE that sol is a solution of.
return len(str(sol))
def _extract_funcs(eqs):
funcs = []
for eq in eqs:
derivs = [node for node in preorder_traversal(eq) if isinstance(node, Derivative)]
func = []
for d in derivs:
func += list(d.atoms(AppliedUndef))
for func_ in func:
funcs.append(func_)
funcs = list(uniq(funcs))
return funcs
def _get_constant_subexpressions(expr, Cs):
Cs = set(Cs)
Ces = []
def _recursive_walk(expr):
expr_syms = expr.free_symbols
if expr_syms and expr_syms.issubset(Cs):
Ces.append(expr)
else:
if expr.func == exp:
expr = expr.expand(mul=True)
if expr.func in (Add, Mul):
d = sift(expr.args, lambda i : i.free_symbols.issubset(Cs))
if len(d[True]) > 1:
x = expr.func(*d[True])
if not x.is_number:
Ces.append(x)
elif isinstance(expr, Integral):
if expr.free_symbols.issubset(Cs) and \
all(len(x) == 3 for x in expr.limits):
Ces.append(expr)
for i in expr.args:
_recursive_walk(i)
return
_recursive_walk(expr)
return Ces
def __remove_linear_redundancies(expr, Cs):
cnts = {i: expr.count(i) for i in Cs}
Cs = [i for i in Cs if cnts[i] > 0]
def _linear(expr):
if isinstance(expr, Add):
xs = [i for i in Cs if expr.count(i)==cnts[i] \
and 0 == expr.diff(i, 2)]
d = {}
for x in xs:
y = expr.diff(x)
if y not in d:
d[y]=[]
d[y].append(x)
for y in d:
if len(d[y]) > 1:
d[y].sort(key=str)
for x in d[y][1:]:
expr = expr.subs(x, 0)
return expr
def _recursive_walk(expr):
if len(expr.args) != 0:
expr = expr.func(*[_recursive_walk(i) for i in expr.args])
expr = _linear(expr)
return expr
if isinstance(expr, Equality):
lhs, rhs = [_recursive_walk(i) for i in expr.args]
f = lambda i: isinstance(i, Number) or i in Cs
if isinstance(lhs, Symbol) and lhs in Cs:
rhs, lhs = lhs, rhs
if lhs.func in (Add, Symbol) and rhs.func in (Add, Symbol):
dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f)
drhs = sift([rhs] if isinstance(rhs, AtomicExpr) else rhs.args, f)
for i in [True, False]:
for hs in [dlhs, drhs]:
if i not in hs:
hs[i] = [0]
# this calculation can be simplified
lhs = Add(*dlhs[False]) - Add(*drhs[False])
rhs = Add(*drhs[True]) - Add(*dlhs[True])
elif lhs.func in (Mul, Symbol) and rhs.func in (Mul, Symbol):
dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f)
if True in dlhs:
if False not in dlhs:
dlhs[False] = [1]
lhs = Mul(*dlhs[False])
rhs = rhs/Mul(*dlhs[True])
return Eq(lhs, rhs)
else:
return _recursive_walk(expr)
@vectorize(0)
def constantsimp(expr, constants):
r"""
Simplifies an expression with arbitrary constants in it.
This function is written specifically to work with
:py:meth:`~sympy.solvers.ode.dsolve`, and is not intended for general use.
Simplification is done by "absorbing" the arbitrary constants into other
arbitrary constants, numbers, and symbols that they are not independent
of.
The symbols must all have the same name with numbers after it, for
example, ``C1``, ``C2``, ``C3``. The ``symbolname`` here would be
'``C``', the ``startnumber`` would be 1, and the ``endnumber`` would be 3.
If the arbitrary constants are independent of the variable ``x``, then the
independent symbol would be ``x``. There is no need to specify the
dependent function, such as ``f(x)``, because it already has the
independent symbol, ``x``, in it.
Because terms are "absorbed" into arbitrary constants and because
constants are renumbered after simplifying, the arbitrary constants in
expr are not necessarily equal to the ones of the same name in the
returned result.
If two or more arbitrary constants are added, multiplied, or raised to the
power of each other, they are first absorbed together into a single
arbitrary constant. Then the new constant is combined into other terms if
necessary.
Absorption of constants is done with limited assistance:
1. terms of :py:class:`~sympy.core.add.Add`\s are collected to try join
constants so `e^x (C_1 \cos(x) + C_2 \cos(x))` will simplify to `e^x
C_1 \cos(x)`;
2. powers with exponents that are :py:class:`~sympy.core.add.Add`\s are
expanded so `e^{C_1 + x}` will be simplified to `C_1 e^x`.
Use :py:meth:`~sympy.solvers.ode.ode.constant_renumber` to renumber constants
after simplification or else arbitrary numbers on constants may appear,
e.g. `C_1 + C_3 x`.
In rare cases, a single constant can be "simplified" into two constants.
Every differential equation solution should have as many arbitrary
constants as the order of the differential equation. The result here will
be technically correct, but it may, for example, have `C_1` and `C_2` in
an expression, when `C_1` is actually equal to `C_2`. Use your discretion
in such situations, and also take advantage of the ability to use hints in
:py:meth:`~sympy.solvers.ode.dsolve`.
Examples
========
>>> from sympy import symbols
>>> from sympy.solvers.ode.ode import constantsimp
>>> C1, C2, C3, x, y = symbols('C1, C2, C3, x, y')
>>> constantsimp(2*C1*x, {C1, C2, C3})
C1*x
>>> constantsimp(C1 + 2 + x, {C1, C2, C3})
C1 + x
>>> constantsimp(C1*C2 + 2 + C2 + C3*x, {C1, C2, C3})
C1 + C3*x
"""
# This function works recursively. The idea is that, for Mul,
# Add, Pow, and Function, if the class has a constant in it, then
# we can simplify it, which we do by recursing down and
# simplifying up. Otherwise, we can skip that part of the
# expression.
Cs = constants
orig_expr = expr
constant_subexprs = _get_constant_subexpressions(expr, Cs)
for xe in constant_subexprs:
xes = list(xe.free_symbols)
if not xes:
continue
if all(expr.count(c) == xe.count(c) for c in xes):
xes.sort(key=str)
expr = expr.subs(xe, xes[0])
# try to perform common sub-expression elimination of constant terms
try:
commons, rexpr = cse(expr)
commons.reverse()
rexpr = rexpr[0]
for s in commons:
cs = list(s[1].atoms(Symbol))
if len(cs) == 1 and cs[0] in Cs and \
cs[0] not in rexpr.atoms(Symbol) and \
not any(cs[0] in ex for ex in commons if ex != s):
rexpr = rexpr.subs(s[0], cs[0])
else:
rexpr = rexpr.subs(*s)
expr = rexpr
except IndexError:
pass
expr = __remove_linear_redundancies(expr, Cs)
def _conditional_term_factoring(expr):
new_expr = terms_gcd(expr, clear=False, deep=True, expand=False)
# we do not want to factor exponentials, so handle this separately
if new_expr.is_Mul:
infac = False
asfac = False
for m in new_expr.args:
if isinstance(m, exp):
asfac = True
elif m.is_Add:
infac = any(isinstance(fi, exp) for t in m.args
for fi in Mul.make_args(t))
if asfac and infac:
new_expr = expr
break
return new_expr
expr = _conditional_term_factoring(expr)
# call recursively if more simplification is possible
if orig_expr != expr:
return constantsimp(expr, Cs)
return expr
def constant_renumber(expr, variables=None, newconstants=None):
r"""
Renumber arbitrary constants in ``expr`` to use the symbol names as given
in ``newconstants``. In the process, this reorders expression terms in a
standard way.
If ``newconstants`` is not provided then the new constant names will be
``C1``, ``C2`` etc. Otherwise ``newconstants`` should be an iterable
giving the new symbols to use for the constants in order.
The ``variables`` argument is a list of non-constant symbols. All other
free symbols found in ``expr`` are assumed to be constants and will be
renumbered. If ``variables`` is not given then any numbered symbol
beginning with ``C`` (e.g. ``C1``) is assumed to be a constant.
Symbols are renumbered based on ``.sort_key()``, so they should be
numbered roughly in the order that they appear in the final, printed
expression. Note that this ordering is based in part on hashes, so it can
produce different results on different machines.
The structure of this function is very similar to that of
:py:meth:`~sympy.solvers.ode.constantsimp`.
Examples
========
>>> from sympy import symbols
>>> from sympy.solvers.ode.ode import constant_renumber
>>> x, C1, C2, C3 = symbols('x,C1:4')
>>> expr = C3 + C2*x + C1*x**2
>>> expr
C1*x**2 + C2*x + C3
>>> constant_renumber(expr)
C1 + C2*x + C3*x**2
The ``variables`` argument specifies which are constants so that the
other symbols will not be renumbered:
>>> constant_renumber(expr, [C1, x])
C1*x**2 + C2 + C3*x
The ``newconstants`` argument is used to specify what symbols to use when
replacing the constants:
>>> constant_renumber(expr, [x], newconstants=symbols('E1:4'))
E1 + E2*x + E3*x**2
"""
# System of expressions
if isinstance(expr, (set, list, tuple)):
return type(expr)(constant_renumber(Tuple(*expr),
variables=variables, newconstants=newconstants))
# Symbols in solution but not ODE are constants
if variables is not None:
variables = set(variables)
free_symbols = expr.free_symbols
constantsymbols = list(free_symbols - variables)
# Any Cn is a constant...
else:
variables = set()
isconstant = lambda s: s.startswith('C') and s[1:].isdigit()
constantsymbols = [sym for sym in expr.free_symbols if isconstant(sym.name)]
# Find new constants checking that they aren't already in the ODE
if newconstants is None:
iter_constants = numbered_symbols(start=1, prefix='C', exclude=variables)
else:
iter_constants = (sym for sym in newconstants if sym not in variables)
constants_found = []
# make a mapping to send all constantsymbols to S.One and use
# that to make sure that term ordering is not dependent on
# the indexed value of C
C_1 = [(ci, S.One) for ci in constantsymbols]
sort_key=lambda arg: default_sort_key(arg.subs(C_1))
def _constant_renumber(expr):
r"""
We need to have an internal recursive function
"""
# For system of expressions
if isinstance(expr, Tuple):
renumbered = [_constant_renumber(e) for e in expr]
return Tuple(*renumbered)
if isinstance(expr, Equality):
return Eq(
_constant_renumber(expr.lhs),
_constant_renumber(expr.rhs))
if type(expr) not in (Mul, Add, Pow) and not expr.is_Function and \
not expr.has(*constantsymbols):
# Base case, as above. Hope there aren't constants inside
# of some other class, because they won't be renumbered.
return expr
elif expr.is_Piecewise:
return expr
elif expr in constantsymbols:
if expr not in constants_found:
constants_found.append(expr)
return expr
elif expr.is_Function or expr.is_Pow:
return expr.func(
*[_constant_renumber(x) for x in expr.args])
else:
sortedargs = list(expr.args)
sortedargs.sort(key=sort_key)
return expr.func(*[_constant_renumber(x) for x in sortedargs])
expr = _constant_renumber(expr)
# Don't renumber symbols present in the ODE.
constants_found = [c for c in constants_found if c not in variables]
# Renumbering happens here
subs_dict = {var: cons for var, cons in zip(constants_found, iter_constants)}
expr = expr.subs(subs_dict, simultaneous=True)
return expr
def _handle_Integral(expr, func, hint):
r"""
Converts a solution with Integrals in it into an actual solution.
For most hints, this simply runs ``expr.doit()``.
"""
if hint == "nth_linear_constant_coeff_homogeneous":
sol = expr
elif not hint.endswith("_Integral"):
sol = expr.doit()
else:
sol = expr
return sol
# XXX: Should this function maybe go somewhere else?
def homogeneous_order(eq, *symbols):
r"""
Returns the order `n` if `g` is homogeneous and ``None`` if it is not
homogeneous.
Determines if a function is homogeneous and if so of what order. A
function `f(x, y, \cdots)` is homogeneous of order `n` if `f(t x, t y,
\cdots) = t^n f(x, y, \cdots)`.
If the function is of two variables, `F(x, y)`, then `f` being homogeneous
of any order is equivalent to being able to rewrite `F(x, y)` as `G(x/y)`
or `H(y/x)`. This fact is used to solve 1st order ordinary differential
equations whose coefficients are homogeneous of the same order (see the
docstrings of
:obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsDepDivIndep` and
:obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsIndepDivDep`).
Symbols can be functions, but every argument of the function must be a
symbol, and the arguments of the function that appear in the expression
must match those given in the list of symbols. If a declared function
appears with different arguments than given in the list of symbols,
``None`` is returned.
Examples
========
>>> from sympy import Function, homogeneous_order, sqrt
>>> from sympy.abc import x, y
>>> f = Function('f')
>>> homogeneous_order(f(x), f(x)) is None
True
>>> homogeneous_order(f(x,y), f(y, x), x, y) is None
True
>>> homogeneous_order(f(x), f(x), x)
1
>>> homogeneous_order(x**2*f(x)/sqrt(x**2+f(x)**2), x, f(x))
2
>>> homogeneous_order(x**2+f(x), x, f(x)) is None
True
"""
if not symbols:
raise ValueError("homogeneous_order: no symbols were given.")
symset = set(symbols)
eq = sympify(eq)
# The following are not supported
if eq.has(Order, Derivative):
return None
# These are all constants
if (eq.is_Number or
eq.is_NumberSymbol or
eq.is_number
):
return S.Zero
# Replace all functions with dummy variables
dum = numbered_symbols(prefix='d', cls=Dummy)
newsyms = set()
for i in [j for j in symset if getattr(j, 'is_Function')]:
iargs = set(i.args)
if iargs.difference(symset):
return None
else:
dummyvar = next(dum)
eq = eq.subs(i, dummyvar)
symset.remove(i)
newsyms.add(dummyvar)
symset.update(newsyms)
if not eq.free_symbols & symset:
return None
# assuming order of a nested function can only be equal to zero
if isinstance(eq, Function):
return None if homogeneous_order(
eq.args[0], *tuple(symset)) != 0 else S.Zero
# make the replacement of x with x*t and see if t can be factored out
t = Dummy('t', positive=True) # It is sufficient that t > 0
eqs = separatevars(eq.subs([(i, t*i) for i in symset]), [t], dict=True)[t]
if eqs is S.One:
return S.Zero # there was no term with only t
i, d = eqs.as_independent(t, as_Add=False)
b, e = d.as_base_exp()
if b == t:
return e
def ode_2nd_power_series_ordinary(eq, func, order, match):
r"""
Gives a power series solution to a second order homogeneous differential
equation with polynomial coefficients at an ordinary point. A homogeneous
differential equation is of the form
.. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) y(x) = 0
For simplicity it is assumed that `P(x)`, `Q(x)` and `R(x)` are polynomials,
it is sufficient that `\frac{Q(x)}{P(x)}` and `\frac{R(x)}{P(x)}` exists at
`x_{0}`. A recurrence relation is obtained by substituting `y` as `\sum_{n=0}^\infty a_{n}x^{n}`,
in the differential equation, and equating the nth term. Using this relation
various terms can be generated.
Examples
========
>>> from sympy import dsolve, Function, pprint
>>> from sympy.abc import x
>>> f = Function("f")
>>> eq = f(x).diff(x, 2) + f(x)
>>> pprint(dsolve(eq, hint='2nd_power_series_ordinary'))
/ 4 2 \ / 2\
|x x | | x | / 6\
f(x) = C2*|-- - -- + 1| + C1*x*|1 - --| + O\x /
\24 2 / \ 6 /
References
==========
- http://tutorial.math.lamar.edu/Classes/DE/SeriesSolutions.aspx
- George E. Simmons, "Differential Equations with Applications and
Historical Notes", p.p 176 - 184
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
n = Dummy("n", integer=True)
s = Wild("s")
k = Wild("k", exclude=[x])
x0 = match['x0']
terms = match['terms']
p = match[match['a3']]
q = match[match['b3']]
r = match[match['c3']]
seriesdict = {}
recurr = Function("r")
# Generating the recurrence relation which works this way:
# for the second order term the summation begins at n = 2. The coefficients
# p is multiplied with an*(n - 1)*(n - 2)*x**n-2 and a substitution is made such that
# the exponent of x becomes n.
# For example, if p is x, then the second degree recurrence term is
# an*(n - 1)*(n - 2)*x**n-1, substituting (n - 1) as n, it transforms to
# an+1*n*(n - 1)*x**n.
# A similar process is done with the first order and zeroth order term.
coefflist = [(recurr(n), r), (n*recurr(n), q), (n*(n - 1)*recurr(n), p)]
for index, coeff in enumerate(coefflist):
if coeff[1]:
f2 = powsimp(expand((coeff[1]*(x - x0)**(n - index)).subs(x, x + x0)))
if f2.is_Add:
addargs = f2.args
else:
addargs = [f2]
for arg in addargs:
powm = arg.match(s*x**k)
term = coeff[0]*powm[s]
if not powm[k].is_Symbol:
term = term.subs(n, n - powm[k].as_independent(n)[0])
startind = powm[k].subs(n, index)
# Seeing if the startterm can be reduced further.
# If it vanishes for n lesser than startind, it is
# equal to summation from n.
if startind:
for i in reversed(range(startind)):
if not term.subs(n, i):
seriesdict[term] = i
else:
seriesdict[term] = i + 1
break
else:
seriesdict[term] = S.Zero
# Stripping of terms so that the sum starts with the same number.
teq = S.Zero
suminit = seriesdict.values()
rkeys = seriesdict.keys()
req = Add(*rkeys)
if any(suminit):
maxval = max(suminit)
for term in seriesdict:
val = seriesdict[term]
if val != maxval:
for i in range(val, maxval):
teq += term.subs(n, val)
finaldict = {}
if teq:
fargs = teq.atoms(AppliedUndef)
if len(fargs) == 1:
finaldict[fargs.pop()] = 0
else:
maxf = max(fargs, key = lambda x: x.args[0])
sol = solve(teq, maxf)
if isinstance(sol, list):
sol = sol[0]
finaldict[maxf] = sol
# Finding the recurrence relation in terms of the largest term.
fargs = req.atoms(AppliedUndef)
maxf = max(fargs, key = lambda x: x.args[0])
minf = min(fargs, key = lambda x: x.args[0])
if minf.args[0].is_Symbol:
startiter = 0
else:
startiter = -minf.args[0].as_independent(n)[0]
lhs = maxf
rhs = solve(req, maxf)
if isinstance(rhs, list):
rhs = rhs[0]
# Checking how many values are already present
tcounter = len([t for t in finaldict.values() if t])
for _ in range(tcounter, terms - 3): # Assuming c0 and c1 to be arbitrary
check = rhs.subs(n, startiter)
nlhs = lhs.subs(n, startiter)
nrhs = check.subs(finaldict)
finaldict[nlhs] = nrhs
startiter += 1
# Post processing
series = C0 + C1*(x - x0)
for term in finaldict:
if finaldict[term]:
fact = term.args[0]
series += (finaldict[term].subs([(recurr(0), C0), (recurr(1), C1)])*(
x - x0)**fact)
series = collect(expand_mul(series), [C0, C1]) + Order(x**terms)
return Eq(f(x), series)
def ode_2nd_power_series_regular(eq, func, order, match):
r"""
Gives a power series solution to a second order homogeneous differential
equation with polynomial coefficients at a regular point. A second order
homogeneous differential equation is of the form
.. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) y(x) = 0
A point is said to regular singular at `x0` if `x - x0\frac{Q(x)}{P(x)}`
and `(x - x0)^{2}\frac{R(x)}{P(x)}` are analytic at `x0`. For simplicity
`P(x)`, `Q(x)` and `R(x)` are assumed to be polynomials. The algorithm for
finding the power series solutions is:
1. Try expressing `(x - x0)P(x)` and `((x - x0)^{2})Q(x)` as power series
solutions about x0. Find `p0` and `q0` which are the constants of the
power series expansions.
2. Solve the indicial equation `f(m) = m(m - 1) + m*p0 + q0`, to obtain the
roots `m1` and `m2` of the indicial equation.
3. If `m1 - m2` is a non integer there exists two series solutions. If
`m1 = m2`, there exists only one solution. If `m1 - m2` is an integer,
then the existence of one solution is confirmed. The other solution may
or may not exist.
The power series solution is of the form `x^{m}\sum_{n=0}^\infty a_{n}x^{n}`. The
coefficients are determined by the following recurrence relation.
`a_{n} = -\frac{\sum_{k=0}^{n-1} q_{n-k} + (m + k)p_{n-k}}{f(m + n)}`. For the case
in which `m1 - m2` is an integer, it can be seen from the recurrence relation
that for the lower root `m`, when `n` equals the difference of both the
roots, the denominator becomes zero. So if the numerator is not equal to zero,
a second series solution exists.
Examples
========
>>> from sympy import dsolve, Function, pprint
>>> from sympy.abc import x
>>> f = Function("f")
>>> eq = x*(f(x).diff(x, 2)) + 2*(f(x).diff(x)) + x*f(x)
>>> pprint(dsolve(eq, hint='2nd_power_series_regular'))
/ 6 4 2 \
| x x x |
/ 4 2 \ C1*|- --- + -- - -- + 1|
| x x | \ 720 24 2 / / 6\
f(x) = C2*|--- - -- + 1| + ------------------------ + O\x /
\120 6 / x
References
==========
- George E. Simmons, "Differential Equations with Applications and
Historical Notes", p.p 176 - 184
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
m = Dummy("m") # for solving the indicial equation
x0 = match['x0']
terms = match['terms']
p = match['p']
q = match['q']
# Generating the indicial equation
indicial = []
for term in [p, q]:
if not term.has(x):
indicial.append(term)
else:
term = series(term, x=x, n=1, x0=x0)
if isinstance(term, Order):
indicial.append(S.Zero)
else:
for arg in term.args:
if not arg.has(x):
indicial.append(arg)
break
p0, q0 = indicial
sollist = solve(m*(m - 1) + m*p0 + q0, m)
if sollist and isinstance(sollist, list) and all(
sol.is_real for sol in sollist):
serdict1 = {}
serdict2 = {}
if len(sollist) == 1:
# Only one series solution exists in this case.
m1 = m2 = sollist.pop()
if terms-m1-1 <= 0:
return Eq(f(x), Order(terms))
serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
else:
m1 = sollist[0]
m2 = sollist[1]
if m1 < m2:
m1, m2 = m2, m1
# Irrespective of whether m1 - m2 is an integer or not, one
# Frobenius series solution exists.
serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
if not (m1 - m2).is_integer:
# Second frobenius series solution exists.
serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1)
else:
# Check if second frobenius series solution exists.
serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1, check=m1)
if serdict1:
finalseries1 = C0
for key in serdict1:
power = int(key.name[1:])
finalseries1 += serdict1[key]*(x - x0)**power
finalseries1 = (x - x0)**m1*finalseries1
finalseries2 = S.Zero
if serdict2:
for key in serdict2:
power = int(key.name[1:])
finalseries2 += serdict2[key]*(x - x0)**power
finalseries2 += C1
finalseries2 = (x - x0)**m2*finalseries2
return Eq(f(x), collect(finalseries1 + finalseries2,
[C0, C1]) + Order(x**terms))
def _frobenius(n, m, p0, q0, p, q, x0, x, c, check=None):
r"""
Returns a dict with keys as coefficients and values as their values in terms of C0
"""
n = int(n)
# In cases where m1 - m2 is not an integer
m2 = check
d = Dummy("d")
numsyms = numbered_symbols("C", start=0)
numsyms = [next(numsyms) for i in range(n + 1)]
serlist = []
for ser in [p, q]:
# Order term not present
if ser.is_polynomial(x) and Poly(ser, x).degree() <= n:
if x0:
ser = ser.subs(x, x + x0)
dict_ = Poly(ser, x).as_dict()
# Order term present
else:
tseries = series(ser, x=x0, n=n+1)
# Removing order
dict_ = Poly(list(ordered(tseries.args))[: -1], x).as_dict()
# Fill in with zeros, if coefficients are zero.
for i in range(n + 1):
if (i,) not in dict_:
dict_[(i,)] = S.Zero
serlist.append(dict_)
pseries = serlist[0]
qseries = serlist[1]
indicial = d*(d - 1) + d*p0 + q0
frobdict = {}
for i in range(1, n + 1):
num = c*(m*pseries[(i,)] + qseries[(i,)])
for j in range(1, i):
sym = Symbol("C" + str(j))
num += frobdict[sym]*((m + j)*pseries[(i - j,)] + qseries[(i - j,)])
# Checking for cases when m1 - m2 is an integer. If num equals zero
# then a second Frobenius series solution cannot be found. If num is not zero
# then set constant as zero and proceed.
if m2 is not None and i == m2 - m:
if num:
return False
else:
frobdict[numsyms[i]] = S.Zero
else:
frobdict[numsyms[i]] = -num/(indicial.subs(d, m+i))
return frobdict
def _remove_redundant_solutions(eq, solns, order, var):
r"""
Remove redundant solutions from the set of solutions.
This function is needed because otherwise dsolve can return
redundant solutions. As an example consider:
eq = Eq((f(x).diff(x, 2))*f(x).diff(x), 0)
There are two ways to find solutions to eq. The first is to solve f(x).diff(x, 2) = 0
leading to solution f(x)=C1 + C2*x. The second is to solve the equation f(x).diff(x) = 0
leading to the solution f(x) = C1. In this particular case we then see
that the second solution is a special case of the first and we do not
want to return it.
This does not always happen. If we have
eq = Eq((f(x)**2-4)*(f(x).diff(x)-4), 0)
then we get the algebraic solution f(x) = [-2, 2] and the integral solution
f(x) = x + C1 and in this case the two solutions are not equivalent wrt
initial conditions so both should be returned.
"""
def is_special_case_of(soln1, soln2):
return _is_special_case_of(soln1, soln2, eq, order, var)
unique_solns = []
for soln1 in solns:
for soln2 in unique_solns[:]:
if is_special_case_of(soln1, soln2):
break
elif is_special_case_of(soln2, soln1):
unique_solns.remove(soln2)
else:
unique_solns.append(soln1)
return unique_solns
def _is_special_case_of(soln1, soln2, eq, order, var):
r"""
True if soln1 is found to be a special case of soln2 wrt some value of the
constants that appear in soln2. False otherwise.
"""
# The solutions returned by dsolve may be given explicitly or implicitly.
# We will equate the sol1=(soln1.rhs - soln1.lhs), sol2=(soln2.rhs - soln2.lhs)
# of the two solutions.
#
# Since this is supposed to hold for all x it also holds for derivatives.
# For an order n ode we should be able to differentiate
# each solution n times to get n+1 equations.
#
# We then try to solve those n+1 equations for the integrations constants
# in sol2. If we can find a solution that does not depend on x then it
# means that some value of the constants in sol1 is a special case of
# sol2 corresponding to a particular choice of the integration constants.
# In case the solution is in implicit form we subtract the sides
soln1 = soln1.rhs - soln1.lhs
soln2 = soln2.rhs - soln2.lhs
# Work for the series solution
if soln1.has(Order) and soln2.has(Order):
if soln1.getO() == soln2.getO():
soln1 = soln1.removeO()
soln2 = soln2.removeO()
else:
return False
elif soln1.has(Order) or soln2.has(Order):
return False
constants1 = soln1.free_symbols.difference(eq.free_symbols)
constants2 = soln2.free_symbols.difference(eq.free_symbols)
constants1_new = get_numbered_constants(Tuple(soln1, soln2), len(constants1))
if len(constants1) == 1:
constants1_new = {constants1_new}
for c_old, c_new in zip(constants1, constants1_new):
soln1 = soln1.subs(c_old, c_new)
# n equations for sol1 = sol2, sol1'=sol2', ...
lhs = soln1
rhs = soln2
eqns = [Eq(lhs, rhs)]
for n in range(1, order):
lhs = lhs.diff(var)
rhs = rhs.diff(var)
eq = Eq(lhs, rhs)
eqns.append(eq)
# BooleanTrue/False awkwardly show up for trivial equations
if any(isinstance(eq, BooleanFalse) for eq in eqns):
return False
eqns = [eq for eq in eqns if not isinstance(eq, BooleanTrue)]
try:
constant_solns = solve(eqns, constants2)
except NotImplementedError:
return False
# Sometimes returns a dict and sometimes a list of dicts
if isinstance(constant_solns, dict):
constant_solns = [constant_solns]
# after solving the issue 17418, maybe we don't need the following checksol code.
for constant_soln in constant_solns:
for eq in eqns:
eq=eq.rhs-eq.lhs
if checksol(eq, constant_soln) is not True:
return False
# If any solution gives all constants as expressions that don't depend on
# x then there exists constants for soln2 that give soln1
for constant_soln in constant_solns:
if not any(c.has(var) for c in constant_soln.values()):
return True
return False
def ode_1st_power_series(eq, func, order, match):
r"""
The power series solution is a method which gives the Taylor series expansion
to the solution of a differential equation.
For a first order differential equation `\frac{dy}{dx} = h(x, y)`, a power
series solution exists at a point `x = x_{0}` if `h(x, y)` is analytic at `x_{0}`.
The solution is given by
.. math:: y(x) = y(x_{0}) + \sum_{n = 1}^{\infty} \frac{F_{n}(x_{0},b)(x - x_{0})^n}{n!},
where `y(x_{0}) = b` is the value of y at the initial value of `x_{0}`.
To compute the values of the `F_{n}(x_{0},b)` the following algorithm is
followed, until the required number of terms are generated.
1. `F_1 = h(x_{0}, b)`
2. `F_{n+1} = \frac{\partial F_{n}}{\partial x} + \frac{\partial F_{n}}{\partial y}F_{1}`
Examples
========
>>> from sympy import Function, pprint, exp, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = exp(x)*(f(x).diff(x)) - f(x)
>>> pprint(dsolve(eq, hint='1st_power_series'))
3 4 5
C1*x C1*x C1*x / 6\
f(x) = C1 + C1*x - ----- + ----- + ----- + O\x /
6 24 60
References
==========
- Travis W. Walker, Analytic power series technique for solving first-order
differential equations, p.p 17, 18
"""
x = func.args[0]
y = match['y']
f = func.func
h = -match[match['d']]/match[match['e']]
point = match['f0']
value = match['f0val']
terms = match['terms']
# First term
F = h
if not h:
return Eq(f(x), value)
# Initialization
series = value
if terms > 1:
hc = h.subs({x: point, y: value})
if hc.has(oo) or hc.has(nan) or hc.has(zoo):
# Derivative does not exist, not analytic
return Eq(f(x), oo)
elif hc:
series += hc*(x - point)
for factcount in range(2, terms):
Fnew = F.diff(x) + F.diff(y)*h
Fnewc = Fnew.subs({x: point, y: value})
# Same logic as above
if Fnewc.has(oo) or Fnewc.has(nan) or Fnewc.has(-oo) or Fnewc.has(zoo):
return Eq(f(x), oo)
series += Fnewc*((x - point)**factcount)/factorial(factcount)
F = Fnew
series += Order(x**terms)
return Eq(f(x), series)
def checkinfsol(eq, infinitesimals, func=None, order=None):
r"""
This function is used to check if the given infinitesimals are the
actual infinitesimals of the given first order differential equation.
This method is specific to the Lie Group Solver of ODEs.
As of now, it simply checks, by substituting the infinitesimals in the
partial differential equation.
.. math:: \frac{\partial \eta}{\partial x} + \left(\frac{\partial \eta}{\partial y}
- \frac{\partial \xi}{\partial x}\right)*h
- \frac{\partial \xi}{\partial y}*h^{2}
- \xi\frac{\partial h}{\partial x} - \eta\frac{\partial h}{\partial y} = 0
where `\eta`, and `\xi` are the infinitesimals and `h(x,y) = \frac{dy}{dx}`
The infinitesimals should be given in the form of a list of dicts
``[{xi(x, y): inf, eta(x, y): inf}]``, corresponding to the
output of the function infinitesimals. It returns a list
of values of the form ``[(True/False, sol)]`` where ``sol`` is the value
obtained after substituting the infinitesimals in the PDE. If it
is ``True``, then ``sol`` would be 0.
"""
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
if not func:
eq, func = _preprocess(eq)
variables = func.args
if len(variables) != 1:
raise ValueError("ODE's have only one independent variable")
else:
x = variables[0]
if not order:
order = ode_order(eq, func)
if order != 1:
raise NotImplementedError("Lie groups solver has been implemented "
"only for first order differential equations")
else:
df = func.diff(x)
a = Wild('a', exclude = [df])
b = Wild('b', exclude = [df])
match = collect(expand(eq), df).match(a*df + b)
if match:
h = -simplify(match[b]/match[a])
else:
try:
sol = solve(eq, df)
except NotImplementedError:
raise NotImplementedError("Infinitesimals for the "
"first order ODE could not be found")
else:
h = sol[0] # Find infinitesimals for one solution
y = Dummy('y')
h = h.subs(func, y)
xi = Function('xi')(x, y)
eta = Function('eta')(x, y)
dxi = Function('xi')(x, func)
deta = Function('eta')(x, func)
pde = (eta.diff(x) + (eta.diff(y) - xi.diff(x))*h -
(xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)))
soltup = []
for sol in infinitesimals:
tsol = {xi: S(sol[dxi]).subs(func, y),
eta: S(sol[deta]).subs(func, y)}
sol = simplify(pde.subs(tsol).doit())
if sol:
soltup.append((False, sol.subs(y, func)))
else:
soltup.append((True, 0))
return soltup
def sysode_linear_2eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
r = {}
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
for i in range(2):
eq[i] = Add(*[terms/fc[i,func[i],1] for terms in Add.make_args(eq[i])])
# 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
|
00487e0bbd05a2632191c77884f2d109d28b1a5e0acff1b1111b0c8af650baa0 | #
# This is the module for ODE solver classes for single ODEs.
#
from __future__ import annotations
from typing import ClassVar, Iterator
from .riccati import match_riccati, solve_riccati
from sympy.core import Add, S, Pow, Rational
from sympy.core.cache import cached_property
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
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: ClassVar[str]
# Subclasses should define this to indicate if they support an _Integral
# hint.
has_integral: ClassVar[bool]
# The ODE to be solved
ode_problem = None # type: SingleODEProblem
# Cache whether or not the equation has matched the method
_matched: bool | None = None
# 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: list | None = None
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: dict[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_with_variable_coefficients
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 92
# indirect doctest
"""
hint = '1st_linear'
has_integral = True
order = [1]
def _wilds(self, f, x, order):
P = Wild('P', exclude=[f(x)])
Q = Wild('Q', exclude=[f(x), f(x).diff(x)])
return P, Q
def _equation(self, fx, x, order):
P, Q = self.wilds()
return fx.diff(x) + P*fx - Q
def _get_general_solution(self, *, simplify_flag: bool = True):
P, Q = self.wilds_match()
fx = self.ode_problem.func
x = self.ode_problem.sym
(C1,) = self.ode_problem.get_numbered_constants(num=1)
gensol = Eq(fx, ((C1 + Integral(Q*exp(Integral(P, x)), x))
* exp(-Integral(P, x))))
return [gensol]
class AlmostLinear(SinglePatternODESolver):
r"""
Solves an almost-linear differential equation.
The general form of an almost linear differential equation is
.. math:: a(x) g'(f(x)) f'(x) + b(x) g(f(x)) + c(x)
Here `f(x)` is the function to be solved for (the dependent variable).
The substitution `g(f(x)) = u(x)` leads to a linear differential equation
for `u(x)` of the form `a(x) u' + b(x) u + c(x) = 0`. This can be solved
for `u(x)` by the `first_linear` hint and then `f(x)` is found by solving
`g(f(x)) = u(x)`.
See Also
========
:obj:`sympy.solvers.ode.single.FirstLinear`
Examples
========
>>> from sympy import dsolve, Function, pprint, sin, cos
>>> from sympy.abc import x
>>> f = Function('f')
>>> d = f(x).diff(x)
>>> eq = x*d + x*f(x) + 1
>>> dsolve(eq, f(x), hint='almost_linear')
Eq(f(x), (C1 - Ei(x))*exp(-x))
>>> pprint(dsolve(eq, f(x), hint='almost_linear'))
-x
f(x) = (C1 - Ei(x))*e
>>> example = cos(f(x))*f(x).diff(x) + sin(f(x)) + 1
>>> pprint(example)
d
sin(f(x)) + cos(f(x))*--(f(x)) + 1
dx
>>> pprint(dsolve(example, f(x), hint='almost_linear'))
/ -x \ / -x \
[f(x) = pi - asin\C1*e - 1/, f(x) = asin\C1*e - 1/]
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
hint = "almost_linear"
has_integral = True
order = [1]
def _wilds(self, f, x, order):
P = Wild('P', exclude=[f(x).diff(x)])
Q = Wild('Q', exclude=[f(x).diff(x)])
return P, Q
def _equation(self, fx, x, order):
P, Q = self.wilds()
return P*fx.diff(x) + Q
def _verify(self, fx):
a, b = self.wilds_match()
c, b = b.as_independent(fx) if b.is_Add else (S.Zero, b)
# a, b and c are the function a(x), b(x) and c(x) respectively.
# c(x) is obtained by separating out b as terms with and without fx i.e, l(y)
# The following conditions checks if the given equation is an almost-linear differential equation using the fact that
# a(x)*(l(y))' / l(y)' is independent of l(y)
if b.diff(fx) != 0 and not simplify(b.diff(fx)/a).has(fx):
self.ly = factor_terms(b).as_independent(fx, as_Add=False)[1] # Gives the term containing fx i.e., l(y)
self.ax = a / self.ly.diff(fx)
self.cx = -c # cx is taken as -c(x) to simplify expression in the solution integral
self.bx = factor_terms(b) / self.ly
return True
return False
def _get_general_solution(self, *, simplify_flag: bool = True):
x = self.ode_problem.sym
(C1,) = self.ode_problem.get_numbered_constants(num=1)
gensol = Eq(self.ly, ((C1 + Integral((self.cx/self.ax)*exp(Integral(self.bx/self.ax, x)), x))
* exp(-Integral(self.bx/self.ax, x))))
return [gensol]
class Bernoulli(SinglePatternODESolver):
r"""
Solves Bernoulli differential equations.
These are equations of the form
.. math:: dy/dx + P(x) y = Q(x) y^n\text{, }n \ne 1`\text{.}
The substitution `w = 1/y^{1-n}` will transform an equation of this form
into one that is linear (see the docstring of
:obj:`~sympy.solvers.ode.single.FirstLinear`). The general solution is::
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x, n
>>> f, P, Q = map(Function, ['f', 'P', 'Q'])
>>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)**n)
>>> pprint(genform)
d n
P(x)*f(x) + --(f(x)) = Q(x)*f (x)
dx
>>> pprint(dsolve(genform, f(x), hint='Bernoulli_Integral'), num_columns=110)
-1
-----
n - 1
// / / \ \
|| | | | |
|| | / | / | / |
|| | | | | | | |
|| | -(n - 1)* | P(x) dx | -(n - 1)* | P(x) dx | (n - 1)* | P(x) dx|
|| | | | | | | |
|| | / | / | / |
f(x) = ||C1 - n* | Q(x)*e dx + | Q(x)*e dx|*e |
|| | | | |
\\ / / / /
Note that the equation is separable when `n = 1` (see the docstring of
:obj:`~sympy.solvers.ode.single.Separable`).
>>> pprint(dsolve(Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)), f(x),
... hint='separable_Integral'))
f(x)
/
| /
| 1 |
| - dy = C1 + | (-P(x) + Q(x)) dx
| y |
| /
/
Examples
========
>>> from sympy import Function, dsolve, Eq, pprint, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(Eq(x*f(x).diff(x) + f(x), log(x)*f(x)**2),
... f(x), hint='Bernoulli'))
1
f(x) = -----------------
C1*x + log(x) + 1
References
==========
- https://en.wikipedia.org/wiki/Bernoulli_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 95
# indirect doctest
"""
hint = "Bernoulli"
has_integral = True
order = [1]
def _wilds(self, f, x, order):
P = Wild('P', exclude=[f(x)])
Q = Wild('Q', exclude=[f(x)])
n = Wild('n', exclude=[x, f(x), f(x).diff(x)])
return P, Q, n
def _equation(self, fx, x, order):
P, Q, n = self.wilds()
return fx.diff(x) + P*fx - Q*fx**n
def _get_general_solution(self, *, simplify_flag: bool = True):
P, Q, n = self.wilds_match()
fx = self.ode_problem.func
x = self.ode_problem.sym
(C1,) = self.ode_problem.get_numbered_constants(num=1)
if n==1:
gensol = Eq(log(fx), (
C1 + Integral((-P + Q), x)
))
else:
gensol = Eq(fx**(1-n), (
(C1 - (n - 1) * Integral(Q*exp(-n*Integral(P, x))
* exp(Integral(P, x)), x)
) * exp(-(1 - n)*Integral(P, x)))
)
return [gensol]
class Factorable(SingleODESolver):
r"""
Solves equations having a solvable factor.
This function is used to solve the equation having factors. Factors may be of type algebraic or ode. It
will try to solve each factor independently. Factors will be solved by calling dsolve. We will return the
list of solutions.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = (f(x)**2-4)*(f(x).diff(x)+f(x))
>>> pprint(dsolve(eq, f(x)))
-x
[f(x) = 2, f(x) = -2, f(x) = C1*e ]
"""
hint = "factorable"
has_integral = False
def _matches(self):
eq_orig = self.ode_problem.eq
f = self.ode_problem.func.func
x = self.ode_problem.sym
df = f(x).diff(x)
self.eqs = []
eq = eq_orig.collect(f(x), func = cancel)
eq = fraction(factor(eq))[0]
factors = Mul.make_args(factor(eq))
roots = [fac.as_base_exp() for fac in factors if len(fac.args)!=0]
if len(roots)>1 or roots[0][1]>1:
for base, expo in roots:
if base.has(f(x)):
self.eqs.append(base)
if len(self.eqs)>0:
return True
roots = solve(eq, df)
if len(roots)>0:
self.eqs = [(df - root) for root in roots]
# Avoid infinite recursion
matches = self.eqs != [eq_orig]
return matches
for i in factors:
if i.has(f(x)):
self.eqs.append(i)
return len(self.eqs)>0 and len(factors)>1
def _get_general_solution(self, *, simplify_flag: bool = True):
func = self.ode_problem.func.func
x = self.ode_problem.sym
eqns = self.eqs
sols = []
for eq in eqns:
try:
sol = dsolve(eq, func(x))
except NotImplementedError:
continue
else:
if isinstance(sol, list):
sols.extend(sol)
else:
sols.append(sol)
if sols == []:
raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by"
+ " the factorable group method")
return sols
class RiccatiSpecial(SinglePatternODESolver):
r"""
The general Riccati equation has the form
.. math:: dy/dx = f(x) y^2 + g(x) y + h(x)\text{.}
While it does not have a general solution [1], the "special" form, `dy/dx
= a y^2 - b x^c`, does have solutions in many cases [2]. This routine
returns a solution for `a(dy/dx) = b y^2 + c y/x + d/x^2` that is obtained
by using a suitable change of variables to reduce it to the special form
and is valid when neither `a` nor `b` are zero and either `c` or `d` is
zero.
>>> from sympy.abc import x, a, b, c, d
>>> from sympy import dsolve, checkodesol, pprint, Function
>>> f = Function('f')
>>> y = f(x)
>>> genform = a*y.diff(x) - (b*y**2 + c*y/x + d/x**2)
>>> sol = dsolve(genform, y, hint="Riccati_special_minus2")
>>> pprint(sol, wrap_line=False)
/ / __________________ \\
| __________________ | / 2 ||
| / 2 | \/ 4*b*d - (a + c) *log(x)||
-|a + c - \/ 4*b*d - (a + c) *tan|C1 + ----------------------------||
\ \ 2*a //
f(x) = ------------------------------------------------------------------------
2*b*x
>>> checkodesol(genform, sol, order=1)[0]
True
References
==========
- http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Riccati
- http://eqworld.ipmnet.ru/en/solutions/ode/ode0106.pdf -
http://eqworld.ipmnet.ru/en/solutions/ode/ode0123.pdf
"""
hint = "Riccati_special_minus2"
has_integral = False
order = [1]
def _wilds(self, f, x, order):
a = Wild('a', exclude=[x, f(x), f(x).diff(x), 0])
b = Wild('b', exclude=[x, f(x), f(x).diff(x), 0])
c = Wild('c', exclude=[x, f(x), f(x).diff(x)])
d = Wild('d', exclude=[x, f(x), f(x).diff(x)])
return a, b, c, d
def _equation(self, fx, x, order):
a, b, c, d = self.wilds()
return a*fx.diff(x) + b*fx**2 + c*fx/x + d/x**2
def _get_general_solution(self, *, simplify_flag: bool = True):
a, b, c, d = self.wilds_match()
fx = self.ode_problem.func
x = self.ode_problem.sym
(C1,) = self.ode_problem.get_numbered_constants(num=1)
mu = sqrt(4*d*b - (a - c)**2)
gensol = Eq(fx, (a - c - mu*tan(mu/(2*a)*log(x) + C1))/(2*b*x))
return [gensol]
class RationalRiccati(SinglePatternODESolver):
r"""
Gives general solutions to the first order Riccati differential
equations that have atleast one rational particular solution.
.. math :: y' = b_0(x) + b_1(x) y + b_2(x) y^2
where `b_0`, `b_1` and `b_2` are rational functions of `x`
with `b_2 \ne 0` (`b_2 = 0` would make it a Bernoulli equation).
Examples
========
>>> from sympy import Symbol, Function, dsolve, checkodesol
>>> f = Function('f')
>>> x = Symbol('x')
>>> eq = -x**4*f(x)**2 + x**3*f(x).diff(x) + x**2*f(x) + 20
>>> sol = dsolve(eq, hint="1st_rational_riccati")
>>> sol
Eq(f(x), (4*C1 - 5*x**9 - 4)/(x**2*(C1 + x**9 - 1)))
>>> checkodesol(eq, sol)
(True, 0)
References
==========
- Riccati ODE: https://en.wikipedia.org/wiki/Riccati_equation
- N. Thieu Vo - Rational and Algebraic Solutions of First-Order Algebraic ODEs:
Algorithm 11, pp. 78 - https://www3.risc.jku.at/publications/download/risc_5387/PhDThesisThieu.pdf
"""
has_integral = False
hint = "1st_rational_riccati"
order = [1]
def _wilds(self, f, x, order):
b0 = Wild('b0', exclude=[f(x), f(x).diff(x)])
b1 = Wild('b1', exclude=[f(x), f(x).diff(x)])
b2 = Wild('b2', exclude=[f(x), f(x).diff(x)])
return (b0, b1, b2)
def _equation(self, fx, x, order):
b0, b1, b2 = self.wilds()
return fx.diff(x) - b0 - b1*fx - b2*fx**2
def _matches(self):
eq = self.ode_problem.eq_expanded
f = self.ode_problem.func.func
x = self.ode_problem.sym
order = self.ode_problem.order
if order != 1:
return False
match, funcs = match_riccati(eq, f, x)
if not match:
return False
_b0, _b1, _b2 = funcs
b0, b1, b2 = self.wilds()
self._wilds_match = match = {b0: _b0, b1: _b1, b2: _b2}
return True
def _get_general_solution(self, *, simplify_flag: bool = True):
# Match the equation
b0, b1, b2 = self.wilds_match()
fx = self.ode_problem.func
x = self.ode_problem.sym
return solve_riccati(fx, x, b0, b1, b2, gensol=True)
class SecondNonlinearAutonomousConserved(SinglePatternODESolver):
r"""
Gives solution for the autonomous second order nonlinear
differential equation of the form
.. math :: f''(x) = g(f(x))
The solution for this differential equation can be computed
by multiplying by `f'(x)` and integrating on both sides,
converting it into a first order differential equation.
Examples
========
>>> from sympy import Function, symbols, dsolve
>>> f, g = symbols('f g', cls=Function)
>>> x = symbols('x')
>>> eq = f(x).diff(x, 2) - g(f(x))
>>> dsolve(eq, simplify=False)
[Eq(Integral(1/sqrt(C1 + 2*Integral(g(_u), _u)), (_u, f(x))), C2 + x),
Eq(Integral(1/sqrt(C1 + 2*Integral(g(_u), _u)), (_u, f(x))), C2 - x)]
>>> from sympy import exp, log
>>> eq = f(x).diff(x, 2) - exp(f(x)) + log(f(x))
>>> dsolve(eq, simplify=False)
[Eq(Integral(1/sqrt(-2*_u*log(_u) + 2*_u + C1 + 2*exp(_u)), (_u, f(x))), C2 + x),
Eq(Integral(1/sqrt(-2*_u*log(_u) + 2*_u + C1 + 2*exp(_u)), (_u, f(x))), C2 - x)]
References
==========
- http://eqworld.ipmnet.ru/en/solutions/ode/ode0301.pdf
"""
hint = "2nd_nonlinear_autonomous_conserved"
has_integral = True
order = [2]
def _wilds(self, f, x, order):
fy = Wild('fy', exclude=[0, f(x).diff(x), f(x).diff(x, 2)])
return (fy, )
def _equation(self, fx, x, order):
fy = self.wilds()[0]
return fx.diff(x, 2) + fy
def _verify(self, fx):
return self.ode_problem.is_autonomous
def _get_general_solution(self, *, simplify_flag: bool = True):
g = self.wilds_match()[0]
fx = self.ode_problem.func
x = self.ode_problem.sym
u = Dummy('u')
g = g.subs(fx, u)
C1, C2 = self.ode_problem.get_numbered_constants(num=2)
inside = -2*Integral(g, u) + C1
lhs = Integral(1/sqrt(inside), (u, fx))
return [Eq(lhs, C2 + x), Eq(lhs, C2 - x)]
class Liouville(SinglePatternODESolver):
r"""
Solves 2nd order Liouville differential equations.
The general form of a Liouville ODE is
.. math:: \frac{d^2 y}{dx^2} + g(y) \left(\!
\frac{dy}{dx}\!\right)^2 + h(x)
\frac{dy}{dx}\text{.}
The general solution is:
>>> from sympy import Function, dsolve, Eq, pprint, diff
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = Eq(diff(f(x),x,x) + g(f(x))*diff(f(x),x)**2 +
... h(x)*diff(f(x),x), 0)
>>> pprint(genform)
2 2
/d \ d d
g(f(x))*|--(f(x))| + h(x)*--(f(x)) + ---(f(x)) = 0
\dx / dx 2
dx
>>> pprint(dsolve(genform, f(x), hint='Liouville_Integral'))
f(x)
/ /
| |
| / | /
| | | |
| - | h(x) dx | | g(y) dy
| | | |
| / | /
C1 + C2* | e dx + | e dy = 0
| |
/ /
Examples
========
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(diff(f(x), x, x) + diff(f(x), x)**2/f(x) +
... diff(f(x), x)/x, f(x), hint='Liouville'))
________________ ________________
[f(x) = -\/ C1 + C2*log(x) , f(x) = \/ C1 + C2*log(x) ]
References
==========
- Goldstein and Braun, "Advanced Methods for the Solution of Differential
Equations", pp. 98
- http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Liouville
# indirect doctest
"""
hint = "Liouville"
has_integral = True
order = [2]
def _wilds(self, f, x, order):
d = Wild('d', exclude=[f(x).diff(x), f(x).diff(x, 2)])
e = Wild('e', exclude=[f(x).diff(x)])
k = Wild('k', exclude=[f(x).diff(x)])
return d, e, k
def _equation(self, fx, x, order):
# Liouville ODE in the form
# f(x).diff(x, 2) + g(f(x))*(f(x).diff(x))**2 + h(x)*f(x).diff(x)
# See Goldstein and Braun, "Advanced Methods for the Solution of
# Differential Equations", pg. 98
d, e, k = self.wilds()
return d*fx.diff(x, 2) + e*fx.diff(x)**2 + k*fx.diff(x)
def _verify(self, fx):
d, e, k = self.wilds_match()
self.y = Dummy('y')
x = self.ode_problem.sym
self.g = simplify(e/d).subs(fx, self.y)
self.h = simplify(k/d).subs(fx, self.y)
if self.y in self.h.free_symbols or x in self.g.free_symbols:
return False
return True
def _get_general_solution(self, *, simplify_flag: bool = True):
d, e, k = self.wilds_match()
fx = self.ode_problem.func
x = self.ode_problem.sym
C1, C2 = self.ode_problem.get_numbered_constants(num=2)
int = Integral(exp(Integral(self.g, self.y)), (self.y, None, fx))
gen_sol = Eq(int + C1*Integral(exp(-Integral(self.h, x)), x) + C2, 0)
return [gen_sol]
class Separable(SinglePatternODESolver):
r"""
Solves separable 1st order differential equations.
This is any differential equation that can be written as `P(y)
\tfrac{dy}{dx} = Q(x)`. The solution can then just be found by
rearranging terms and integrating: `\int P(y) \,dy = \int Q(x) \,dx`.
This hint uses :py:meth:`sympy.simplify.simplify.separatevars` as its back
end, so if a separable equation is not caught by this solver, it is most
likely the fault of that function.
:py:meth:`~sympy.simplify.simplify.separatevars` is
smart enough to do most expansion and factoring necessary to convert a
separable equation `F(x, y)` into the proper form `P(x)\cdot{}Q(y)`. The
general solution is::
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x
>>> a, b, c, d, f = map(Function, ['a', 'b', 'c', 'd', 'f'])
>>> genform = Eq(a(x)*b(f(x))*f(x).diff(x), c(x)*d(f(x)))
>>> pprint(genform)
d
a(x)*b(f(x))*--(f(x)) = c(x)*d(f(x))
dx
>>> pprint(dsolve(genform, f(x), hint='separable_Integral'))
f(x)
/ /
| |
| b(y) | c(x)
| ---- dy = C1 + | ---- dx
| d(y) | a(x)
| |
/ /
Examples
========
>>> from sympy import Function, dsolve, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(Eq(f(x)*f(x).diff(x) + x, 3*x*f(x)**2), f(x),
... hint='separable', simplify=False))
/ 2 \ 2
log\3*f (x) - 1/ x
---------------- = C1 + --
6 2
References
==========
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 52
# indirect doctest
"""
hint = "separable"
has_integral = True
order = [1]
def _wilds(self, f, x, order):
d = Wild('d', exclude=[f(x).diff(x), f(x).diff(x, 2)])
e = Wild('e', exclude=[f(x).diff(x)])
return d, e
def _equation(self, fx, x, order):
d, e = self.wilds()
return d + e*fx.diff(x)
def _verify(self, fx):
d, e = self.wilds_match()
self.y = Dummy('y')
x = self.ode_problem.sym
d = separatevars(d.subs(fx, self.y))
e = separatevars(e.subs(fx, self.y))
# m1[coeff]*m1[x]*m1[y] + m2[coeff]*m2[x]*m2[y]*y'
self.m1 = separatevars(d, dict=True, symbols=(x, self.y))
self.m2 = separatevars(e, dict=True, symbols=(x, self.y))
if self.m1 and self.m2:
return True
return False
def _get_match_object(self):
fx = self.ode_problem.func
x = self.ode_problem.sym
return self.m1, self.m2, x, fx
def _get_general_solution(self, *, simplify_flag: bool = True):
m1, m2, x, fx = self._get_match_object()
(C1,) = self.ode_problem.get_numbered_constants(num=1)
int = Integral(m2['coeff']*m2[self.y]/m1[self.y],
(self.y, None, fx))
gen_sol = Eq(int, Integral(-m1['coeff']*m1[x]/
m2[x], x) + C1)
return [gen_sol]
class SeparableReduced(Separable):
r"""
Solves a differential equation that can be reduced to the separable form.
The general form of this equation is
.. math:: y' + (y/x) H(x^n y) = 0\text{}.
This can be solved by substituting `u(y) = x^n y`. The equation then
reduces to the separable form `\frac{u'}{u (\mathrm{power} - H(u))} -
\frac{1}{x} = 0`.
The general solution is:
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x, n
>>> f, g = map(Function, ['f', 'g'])
>>> genform = f(x).diff(x) + (f(x)/x)*g(x**n*f(x))
>>> pprint(genform)
/ n \
d f(x)*g\x *f(x)/
--(f(x)) + ---------------
dx x
>>> pprint(dsolve(genform, hint='separable_reduced'))
n
x *f(x)
/
|
| 1
| ------------ dy = C1 + log(x)
| y*(n - g(y))
|
/
See Also
========
:obj:`sympy.solvers.ode.single.Separable`
Examples
========
>>> from sympy import dsolve, Function, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> d = f(x).diff(x)
>>> eq = (x - x**2*f(x))*d - f(x)
>>> dsolve(eq, hint='separable_reduced')
[Eq(f(x), (1 - sqrt(C1*x**2 + 1))/x), Eq(f(x), (sqrt(C1*x**2 + 1) + 1)/x)]
>>> pprint(dsolve(eq, hint='separable_reduced'))
___________ ___________
/ 2 / 2
1 - \/ C1*x + 1 \/ C1*x + 1 + 1
[f(x) = ------------------, f(x) = ------------------]
x x
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
hint = "separable_reduced"
has_integral = True
order = [1]
def _degree(self, expr, x):
# Made this function to calculate the degree of
# x in an expression. If expr will be of form
# x**p*y, (wheare p can be variables/rationals) then it
# will return p.
for val in expr:
if val.has(x):
if isinstance(val, Pow) and val.as_base_exp()[0] == x:
return (val.as_base_exp()[1])
elif val == x:
return (val.as_base_exp()[1])
else:
return self._degree(val.args, x)
return 0
def _powers(self, expr):
# this function will return all the different relative power of x w.r.t f(x).
# expr = x**p * f(x)**q then it will return {p/q}.
pows = set()
fx = self.ode_problem.func
x = self.ode_problem.sym
self.y = Dummy('y')
if isinstance(expr, Add):
exprs = expr.atoms(Add)
elif isinstance(expr, Mul):
exprs = expr.atoms(Mul)
elif isinstance(expr, Pow):
exprs = expr.atoms(Pow)
else:
exprs = {expr}
for arg in exprs:
if arg.has(x):
_, u = arg.as_independent(x, fx)
pow = self._degree((u.subs(fx, self.y), ), x)/self._degree((u.subs(fx, self.y), ), self.y)
pows.add(pow)
return pows
def _verify(self, fx):
num, den = self.wilds_match()
x = self.ode_problem.sym
factor = simplify(x/fx*num/den)
# Try representing factor in terms of x^n*y
# where n is lowest power of x in factor;
# first remove terms like sqrt(2)*3 from factor.atoms(Mul)
num, dem = factor.as_numer_denom()
num = expand(num)
dem = expand(dem)
pows = self._powers(num)
pows.update(self._powers(dem))
pows = list(pows)
if(len(pows)==1) and pows[0]!=zoo:
self.t = Dummy('t')
self.r2 = {'t': self.t}
num = num.subs(x**pows[0]*fx, self.t)
dem = dem.subs(x**pows[0]*fx, self.t)
test = num/dem
free = test.free_symbols
if len(free) == 1 and free.pop() == self.t:
self.r2.update({'power' : pows[0], 'u' : test})
return True
return False
return False
def _get_match_object(self):
fx = self.ode_problem.func
x = self.ode_problem.sym
u = self.r2['u'].subs(self.r2['t'], self.y)
ycoeff = 1/(self.y*(self.r2['power'] - u))
m1 = {self.y: 1, x: -1/x, 'coeff': 1}
m2 = {self.y: ycoeff, x: 1, 'coeff': 1}
return m1, m2, x, x**self.r2['power']*fx
class HomogeneousCoeffSubsDepDivIndep(SinglePatternODESolver):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_1 = \frac{\text{<dependent
variable>}}{\text{<independent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that `P` and `Q` are homogeneous and of the same order. A function
`F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`.
Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See
also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`.
If the coefficients `P` and `Q` in the differential equation above are
homogeneous functions of the same order, then it can be shown that the
substitution `y = u_1 x` (i.e. `u_1 = y/x`) will turn the differential
equation into an equation separable in the variables `x` and `u`. If
`h(u_1)` is the function that results from making the substitution `u_1 =
f(x)/x` on `P(x, f(x))` and `g(u_2)` is the function that results from the
substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) +
Q(x, f(x)) f'(x) = 0`, then the general solution is::
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = g(f(x)/x) + h(f(x)/x)*f(x).diff(x)
>>> pprint(genform)
/f(x)\ /f(x)\ d
g|----| + h|----|*--(f(x))
\ x / \ x / dx
>>> pprint(dsolve(genform, f(x),
... hint='1st_homogeneous_coeff_subs_dep_div_indep_Integral'))
f(x)
----
x
/
|
| -h(u1)
log(x) = C1 + | ---------------- d(u1)
| u1*h(u1) + g(u1)
|
/
Where `u_1 h(u_1) + g(u_1) \ne 0` and `x \ne 0`.
See also the docstrings of
:obj:`~sympy.solvers.ode.single.HomogeneousCoeffBest` and
:obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsIndepDivDep`.
Examples
========
>>> from sympy import Function, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False))
/ 3 \
|3*f(x) f (x)|
log|------ + -----|
| x 3 |
\ x /
log(x) = log(C1) - -------------------
3
References
==========
- https://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
hint = "1st_homogeneous_coeff_subs_dep_div_indep"
has_integral = True
order = [1]
def _wilds(self, f, x, order):
d = Wild('d', exclude=[f(x).diff(x), f(x).diff(x, 2)])
e = Wild('e', exclude=[f(x).diff(x)])
return d, e
def _equation(self, fx, x, order):
d, e = self.wilds()
return d + e*fx.diff(x)
def _verify(self, fx):
self.d, self.e = self.wilds_match()
self.y = Dummy('y')
x = self.ode_problem.sym
self.d = separatevars(self.d.subs(fx, self.y))
self.e = separatevars(self.e.subs(fx, self.y))
ordera = homogeneous_order(self.d, x, self.y)
orderb = homogeneous_order(self.e, x, self.y)
if ordera == orderb and ordera is not None:
self.u = Dummy('u')
if simplify((self.d + self.u*self.e).subs({x: 1, self.y: self.u})) != 0:
return True
return False
return False
def _get_match_object(self):
fx = self.ode_problem.func
x = self.ode_problem.sym
self.u1 = Dummy('u1')
xarg = 0
yarg = 0
return [self.d, self.e, fx, x, self.u, self.u1, self.y, xarg, yarg]
def _get_general_solution(self, *, simplify_flag: bool = True):
d, e, fx, x, u, u1, y, xarg, yarg = self._get_match_object()
(C1,) = self.ode_problem.get_numbered_constants(num=1)
int = Integral(
(-e/(d + u1*e)).subs({x: 1, y: u1}),
(u1, None, fx/x))
sol = logcombine(Eq(log(x), int + log(C1)), force=True)
gen_sol = sol.subs(fx, u).subs(((u, u - yarg), (x, x - xarg), (u, fx)))
return [gen_sol]
class HomogeneousCoeffSubsIndepDivDep(SinglePatternODESolver):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_2 = \frac{\text{<independent
variable>}}{\text{<dependent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that `P` and `Q` are homogeneous and of the same order. A function
`F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`.
Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See
also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`.
If the coefficients `P` and `Q` in the differential equation above are
homogeneous functions of the same order, then it can be shown that the
substitution `x = u_2 y` (i.e. `u_2 = x/y`) will turn the differential
equation into an equation separable in the variables `y` and `u_2`. If
`h(u_2)` is the function that results from making the substitution `u_2 =
x/f(x)` on `P(x, f(x))` and `g(u_2)` is the function that results from the
substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) +
Q(x, f(x)) f'(x) = 0`, then the general solution is:
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = g(x/f(x)) + h(x/f(x))*f(x).diff(x)
>>> pprint(genform)
/ x \ / x \ d
g|----| + h|----|*--(f(x))
\f(x)/ \f(x)/ dx
>>> pprint(dsolve(genform, f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral'))
x
----
f(x)
/
|
| -g(u1)
| ---------------- d(u1)
| u1*g(u1) + h(u1)
|
/
<BLANKLINE>
f(x) = C1*e
Where `u_1 g(u_1) + h(u_1) \ne 0` and `f(x) \ne 0`.
See also the docstrings of
:obj:`~sympy.solvers.ode.single.HomogeneousCoeffBest` and
:obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsDepDivIndep`.
Examples
========
>>> from sympy import Function, pprint, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep',
... simplify=False))
/ 2 \
| 3*x |
log|----- + 1|
| 2 |
\f (x) /
log(f(x)) = log(C1) - --------------
3
References
==========
- https://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
hint = "1st_homogeneous_coeff_subs_indep_div_dep"
has_integral = True
order = [1]
def _wilds(self, f, x, order):
d = Wild('d', exclude=[f(x).diff(x), f(x).diff(x, 2)])
e = Wild('e', exclude=[f(x).diff(x)])
return d, e
def _equation(self, fx, x, order):
d, e = self.wilds()
return d + e*fx.diff(x)
def _verify(self, fx):
self.d, self.e = self.wilds_match()
self.y = Dummy('y')
x = self.ode_problem.sym
self.d = separatevars(self.d.subs(fx, self.y))
self.e = separatevars(self.e.subs(fx, self.y))
ordera = homogeneous_order(self.d, x, self.y)
orderb = homogeneous_order(self.e, x, self.y)
if ordera == orderb and ordera is not None:
self.u = Dummy('u')
if simplify((self.e + self.u*self.d).subs({x: self.u, self.y: 1})) != 0:
return True
return False
return False
def _get_match_object(self):
fx = self.ode_problem.func
x = self.ode_problem.sym
self.u1 = Dummy('u1')
xarg = 0
yarg = 0
return [self.d, self.e, fx, x, self.u, self.u1, self.y, xarg, yarg]
def _get_general_solution(self, *, simplify_flag: bool = True):
d, e, fx, x, u, u1, y, xarg, yarg = self._get_match_object()
(C1,) = self.ode_problem.get_numbered_constants(num=1)
int = Integral(simplify((-d/(e + u1*d)).subs({x: u1, y: 1})), (u1, None, x/fx)) # type: ignore
sol = logcombine(Eq(log(fx), int + log(C1)), force=True)
gen_sol = sol.subs(fx, u).subs(((u, u - yarg), (x, x - xarg), (u, fx)))
return [gen_sol]
class HomogeneousCoeffBest(HomogeneousCoeffSubsIndepDivDep, HomogeneousCoeffSubsDepDivIndep):
r"""
Returns the best solution to an ODE from the two hints
``1st_homogeneous_coeff_subs_dep_div_indep`` and
``1st_homogeneous_coeff_subs_indep_div_dep``.
This is as determined by :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity`.
See the
:obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsIndepDivDep`
and
:obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsDepDivIndep`
docstrings for more information on these hints. Note that there is no
``ode_1st_homogeneous_coeff_best_Integral`` hint.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_best', simplify=False))
/ 2 \
| 3*x |
log|----- + 1|
| 2 |
\f (x) /
log(f(x)) = log(C1) - --------------
3
References
==========
- https://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
hint = "1st_homogeneous_coeff_best"
has_integral = False
order = [1]
def _verify(self, fx):
if HomogeneousCoeffSubsIndepDivDep._verify(self, fx) and HomogeneousCoeffSubsDepDivIndep._verify(self, fx):
return True
return False
def _get_general_solution(self, *, simplify_flag: bool = True):
# There are two substitutions that solve the equation, u1=y/x and u2=x/y
# # They produce different integrals, so try them both and see which
# # one is easier
sol1 = HomogeneousCoeffSubsIndepDivDep._get_general_solution(self)
sol2 = HomogeneousCoeffSubsDepDivIndep._get_general_solution(self)
fx = self.ode_problem.func
if simplify_flag:
sol1 = odesimp(self.ode_problem.eq, *sol1, fx, "1st_homogeneous_coeff_subs_indep_div_dep")
sol2 = odesimp(self.ode_problem.eq, *sol2, fx, "1st_homogeneous_coeff_subs_dep_div_indep")
return min([sol1, sol2], key=lambda x: ode_sol_simplicity(x, fx, trysolving=not simplify))
class LinearCoefficients(HomogeneousCoeffBest):
r"""
Solves a differential equation with linear coefficients.
The general form of a differential equation with linear coefficients is
.. math:: y' + F\left(\!\frac{a_1 x + b_1 y + c_1}{a_2 x + b_2 y +
c_2}\!\right) = 0\text{,}
where `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are constants and `a_1 b_2
- a_2 b_1 \ne 0`.
This can be solved by substituting:
.. math:: x = x' + \frac{b_2 c_1 - b_1 c_2}{a_2 b_1 - a_1 b_2}
y = y' + \frac{a_1 c_2 - a_2 c_1}{a_2 b_1 - a_1
b_2}\text{.}
This substitution reduces the equation to a homogeneous differential
equation.
See Also
========
:obj:`sympy.solvers.ode.single.HomogeneousCoeffBest`
:obj:`sympy.solvers.ode.single.HomogeneousCoeffSubsIndepDivDep`
:obj:`sympy.solvers.ode.single.HomogeneousCoeffSubsDepDivIndep`
Examples
========
>>> from sympy import dsolve, Function, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> df = f(x).diff(x)
>>> eq = (x + f(x) + 1)*df + (f(x) - 6*x + 1)
>>> dsolve(eq, hint='linear_coefficients')
[Eq(f(x), -x - sqrt(C1 + 7*x**2) - 1), Eq(f(x), -x + sqrt(C1 + 7*x**2) - 1)]
>>> pprint(dsolve(eq, hint='linear_coefficients'))
___________ ___________
/ 2 / 2
[f(x) = -x - \/ C1 + 7*x - 1, f(x) = -x + \/ C1 + 7*x - 1]
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
hint = "linear_coefficients"
has_integral = True
order = [1]
def _wilds(self, f, x, order):
d = Wild('d', exclude=[f(x).diff(x), f(x).diff(x, 2)])
e = Wild('e', exclude=[f(x).diff(x)])
return d, e
def _equation(self, fx, x, order):
d, e = self.wilds()
return d + e*fx.diff(x)
def _verify(self, fx):
self.d, self.e = self.wilds_match()
a, b = self.wilds()
F = self.d/self.e
x = self.ode_problem.sym
params = self._linear_coeff_match(F, fx)
if params:
self.xarg, self.yarg = params
u = Dummy('u')
t = Dummy('t')
self.y = Dummy('y')
# Dummy substitution for df and f(x).
dummy_eq = self.ode_problem.eq.subs(((fx.diff(x), t), (fx, u)))
reps = ((x, x + self.xarg), (u, u + self.yarg), (t, fx.diff(x)), (u, fx))
dummy_eq = simplify(dummy_eq.subs(reps))
# get the re-cast values for e and d
r2 = collect(expand(dummy_eq), [fx.diff(x), fx]).match(a*fx.diff(x) + b)
if r2:
self.d, self.e = r2[b], r2[a]
orderd = homogeneous_order(self.d, x, fx)
ordere = homogeneous_order(self.e, x, fx)
if orderd == ordere and orderd is not None:
self.d = self.d.subs(fx, self.y)
self.e = self.e.subs(fx, self.y)
return True
return False
return False
def _linear_coeff_match(self, expr, func):
r"""
Helper function to match hint ``linear_coefficients``.
Matches the expression to the form `(a_1 x + b_1 f(x) + c_1)/(a_2 x + b_2
f(x) + c_2)` where the following conditions hold:
1. `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are Rationals;
2. `c_1` or `c_2` are not equal to zero;
3. `a_2 b_1 - a_1 b_2` is not equal to zero.
Return ``xarg``, ``yarg`` where
1. ``xarg`` = `(b_2 c_1 - b_1 c_2)/(a_2 b_1 - a_1 b_2)`
2. ``yarg`` = `(a_1 c_2 - a_2 c_1)/(a_2 b_1 - a_1 b_2)`
Examples
========
>>> from sympy import Function, sin
>>> from sympy.abc import x
>>> from sympy.solvers.ode.single import LinearCoefficients
>>> f = Function('f')
>>> eq = (-25*f(x) - 8*x + 62)/(4*f(x) + 11*x - 11)
>>> obj = LinearCoefficients(eq)
>>> obj._linear_coeff_match(eq, f(x))
(1/9, 22/9)
>>> eq = sin((-5*f(x) - 8*x + 6)/(4*f(x) + x - 1))
>>> obj = LinearCoefficients(eq)
>>> obj._linear_coeff_match(eq, f(x))
(19/27, 2/27)
>>> eq = sin(f(x)/x)
>>> obj = LinearCoefficients(eq)
>>> obj._linear_coeff_match(eq, f(x))
"""
f = func.func
x = func.args[0]
def abc(eq):
r'''
Internal function of _linear_coeff_match
that returns Rationals a, b, c
if eq is a*x + b*f(x) + c, else None.
'''
eq = _mexpand(eq)
c = eq.as_independent(x, f(x), as_Add=True)[0]
if not c.is_Rational:
return
a = eq.coeff(x)
if not a.is_Rational:
return
b = eq.coeff(f(x))
if not b.is_Rational:
return
if eq == a*x + b*f(x) + c:
return a, b, c
def match(arg):
r'''
Internal function of _linear_coeff_match that returns Rationals a1,
b1, c1, a2, b2, c2 and a2*b1 - a1*b2 of the expression (a1*x + b1*f(x)
+ c1)/(a2*x + b2*f(x) + c2) if one of c1 or c2 and a2*b1 - a1*b2 is
non-zero, else None.
'''
n, d = arg.together().as_numer_denom()
m = abc(n)
if m is not None:
a1, b1, c1 = m
m = abc(d)
if m is not None:
a2, b2, c2 = m
d = a2*b1 - a1*b2
if (c1 or c2) and d:
return a1, b1, c1, a2, b2, c2, d
m = [fi.args[0] for fi in expr.atoms(Function) if fi.func != f and
len(fi.args) == 1 and not fi.args[0].is_Function] or {expr}
m1 = match(m.pop())
if m1 and all(match(mi) == m1 for mi in m):
a1, b1, c1, a2, b2, c2, denom = m1
return (b2*c1 - b1*c2)/denom, (a1*c2 - a2*c1)/denom
def _get_match_object(self):
fx = self.ode_problem.func
x = self.ode_problem.sym
self.u1 = Dummy('u1')
u = Dummy('u')
return [self.d, self.e, fx, x, u, self.u1, self.y, self.xarg, self.yarg]
class NthOrderReducible(SingleODESolver):
r"""
Solves ODEs that only involve derivatives of the dependent variable using
a substitution of the form `f^n(x) = g(x)`.
For example any second order ODE of the form `f''(x) = h(f'(x), x)` can be
transformed into a pair of 1st order ODEs `g'(x) = h(g(x), x)` and
`f'(x) = g(x)`. Usually the 1st order ODE for `g` is easier to solve. If
that gives an explicit solution for `g` then `f` is found simply by
integration.
Examples
========
>>> from sympy import Function, dsolve, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = Eq(x*f(x).diff(x)**2 + f(x).diff(x, 2), 0)
>>> dsolve(eq, f(x), hint='nth_order_reducible')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), C1 - sqrt(-1/C2)*log(-C2*sqrt(-1/C2) + x) + sqrt(-1/C2)*log(C2*sqrt(-1/C2) + x))
"""
hint = "nth_order_reducible"
has_integral = False
def _matches(self):
# Any ODE that can be solved with a substitution and
# repeated integration e.g.:
# `d^2/dx^2(y) + x*d/dx(y) = constant
#f'(x) must be finite for this to work
eq = self.ode_problem.eq_preprocessed
func = self.ode_problem.func
x = self.ode_problem.sym
r"""
Matches any differential equation that can be rewritten with a smaller
order. Only derivatives of ``func`` alone, wrt a single variable,
are considered, and only in them should ``func`` appear.
"""
# ODE only handles functions of 1 variable so this affirms that state
assert len(func.args) == 1
vc = [d.variable_count[0] for d in eq.atoms(Derivative)
if d.expr == func and len(d.variable_count) == 1]
ords = [c for v, c in vc if v == x]
if len(ords) < 2:
return False
self.smallest = min(ords)
# make sure func does not appear outside of derivatives
D = Dummy()
if eq.subs(func.diff(x, self.smallest), D).has(func):
return False
return True
def _get_general_solution(self, *, simplify_flag: bool = True):
eq = self.ode_problem.eq
f = self.ode_problem.func.func
x = self.ode_problem.sym
n = self.smallest
# get a unique function name for g
names = [a.name for a in eq.atoms(AppliedUndef)]
while True:
name = Dummy().name
if name not in names:
g = Function(name)
break
w = f(x).diff(x, n)
geq = eq.subs(w, g(x))
gsol = dsolve(geq, g(x))
if not isinstance(gsol, list):
gsol = [gsol]
# Might be multiple solutions to the reduced ODE:
fsol = []
for gsoli in gsol:
fsoli = dsolve(gsoli.subs(g(x), w), f(x)) # or do integration n times
fsol.append(fsoli)
return fsol
class SecondHypergeometric(SingleODESolver):
r"""
Solves 2nd order linear differential equations.
It computes special function solutions which can be expressed using the
2F1, 1F1 or 0F1 hypergeometric functions.
.. math:: y'' + A(x) y' + B(x) y = 0\text{,}
where `A` and `B` are rational functions.
These kinds of differential equations have solution of non-Liouvillian form.
Given linear ODE can be obtained from 2F1 given by
.. math:: (x^2 - x) y'' + ((a + b + 1) x - c) y' + b a y = 0\text{,}
where {a, b, c} are arbitrary constants.
Notes
=====
The algorithm should find any solution of the form
.. math:: y = P(x) _pF_q(..; ..;\frac{\alpha x^k + \beta}{\gamma x^k + \delta})\text{,}
where pFq is any of 2F1, 1F1 or 0F1 and `P` is an "arbitrary function".
Currently only the 2F1 case is implemented in SymPy but the other cases are
described in the paper and could be implemented in future (contributions
welcome!).
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = (x*x - x)*f(x).diff(x,2) + (5*x - 1)*f(x).diff(x) + 4*f(x)
>>> pprint(dsolve(eq, f(x), '2nd_hypergeometric'))
_
/ / 4 \\ |_ /-1, -1 | \
|C1 + C2*|log(x) + -----||* | | | x|
\ \ x + 1// 2 1 \ 1 | /
f(x) = --------------------------------------------
3
(x - 1)
References
==========
- "Non-Liouvillian solutions for second order linear ODEs" by L. Chan, E.S. Cheb-Terrab
"""
hint = "2nd_hypergeometric"
has_integral = True
def _matches(self):
eq = self.ode_problem.eq_preprocessed
func = self.ode_problem.func
r = match_2nd_hypergeometric(eq, func)
self.match_object = None
if r:
A, B = r
d = equivalence_hypergeometric(A, B, func)
if d:
if d['type'] == "2F1":
self.match_object = match_2nd_2F1_hypergeometric(d['I0'], d['k'], d['sing_point'], func)
if self.match_object is not None:
self.match_object.update({'A':A, 'B':B})
# We can extend it for 1F1 and 0F1 type also.
return self.match_object is not None
def _get_general_solution(self, *, simplify_flag: bool = True):
eq = self.ode_problem.eq
func = self.ode_problem.func
if self.match_object['type'] == "2F1":
sol = get_sol_2F1_hypergeometric(eq, func, self.match_object)
if sol is None:
raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by"
+ " the hypergeometric method")
return [sol]
class NthLinearConstantCoeffHomogeneous(SingleODESolver):
r"""
Solves an `n`\th order linear homogeneous differential equation with
constant coefficients.
This is an equation of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = 0\text{.}
These equations can be solved in a general manner, by taking the roots of
the characteristic equation `a_n m^n + a_{n-1} m^{n-1} + \cdots + a_1 m +
a_0 = 0`. The solution will then be the sum of `C_n x^i e^{r x}` terms,
for each where `C_n` is an arbitrary constant, `r` is a root of the
characteristic equation and `i` is one of each from 0 to the multiplicity
of the root - 1 (for example, a root 3 of multiplicity 2 would create the
terms `C_1 e^{3 x} + C_2 x e^{3 x}`). The exponential is usually expanded
for complex roots using Euler's equation `e^{I x} = \cos(x) + I \sin(x)`.
Complex roots always come in conjugate pairs in polynomials with real
coefficients, so the two roots will be represented (after simplifying the
constants) as `e^{a x} \left(C_1 \cos(b x) + C_2 \sin(b x)\right)`.
If SymPy cannot find exact roots to the characteristic equation, a
:py:class:`~sympy.polys.rootoftools.ComplexRootOf` instance will be return
instead.
>>> from sympy import Function, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(f(x).diff(x, 5) + 10*f(x).diff(x) - 2*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), C5*exp(x*CRootOf(_x**5 + 10*_x - 2, 0))
+ (C1*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 1)))
+ C2*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 1))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 1)))
+ (C3*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 3)))
+ C4*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 3))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 3))))
Note that because this method does not involve integration, there is no
``nth_linear_constant_coeff_homogeneous_Integral`` hint.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 4) + 2*f(x).diff(x, 3) -
... 2*f(x).diff(x, 2) - 6*f(x).diff(x) + 5*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous'))
x -2*x
f(x) = (C1 + C2*x)*e + (C3*sin(x) + C4*cos(x))*e
References
==========
- https://en.wikipedia.org/wiki/Linear_differential_equation section:
Nonhomogeneous_equation_with_constant_coefficients
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 211
# indirect doctest
"""
hint = "nth_linear_constant_coeff_homogeneous"
has_integral = False
def _matches(self):
eq = self.ode_problem.eq_high_order_free
func = self.ode_problem.func
order = self.ode_problem.order
x = self.ode_problem.sym
self.r = self.ode_problem.get_linear_coefficients(eq, func, order)
if order and self.r and not any(self.r[i].has(x) for i in self.r if i >= 0):
if not self.r[-1]:
return True
else:
return False
return False
def _get_general_solution(self, *, simplify_flag: bool = True):
fx = self.ode_problem.func
order = self.ode_problem.order
roots, collectterms = _get_const_characteristic_eq_sols(self.r, fx, order)
# A generator of constants
constants = self.ode_problem.get_numbered_constants(num=len(roots))
gsol = Add(*[i*j for (i, j) in zip(constants, roots)])
gsol = Eq(fx, gsol)
if simplify_flag:
gsol = _get_simplified_sol([gsol], fx, collectterms)
return [gsol]
class NthLinearConstantCoeffVariationOfParameters(SingleODESolver):
r"""
Solves an `n`\th order linear differential equation with constant
coefficients using the method of variation of parameters.
This method works on any differential equations of the form
.. math:: f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0
f(x) = P(x)\text{.}
This method works by assuming that the particular solution takes the form
.. math:: \sum_{x=1}^{n} c_i(x) y_i(x)\text{,}
where `y_i` is the `i`\th solution to the homogeneous equation. The
solution is then solved using Wronskian's and Cramer's Rule. The
particular solution is given by
.. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx
\right) y_i(x) \text{,}
where `W(x)` is the Wronskian of the fundamental system (the system of `n`
linearly independent solutions to the homogeneous equation), and `W_i(x)`
is the Wronskian of the fundamental system with the `i`\th column replaced
with `[0, 0, \cdots, 0, P(x)]`.
This method is general enough to solve any `n`\th order inhomogeneous
linear differential equation with constant coefficients, but sometimes
SymPy cannot simplify the Wronskian well enough to integrate it. If this
method hangs, try using the
``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and
simplifying the integrals manually. Also, prefer using
``nth_linear_constant_coeff_undetermined_coefficients`` when it
applies, because it does not use integration, making it faster and more
reliable.
Warning, using simplify=False with
'nth_linear_constant_coeff_variation_of_parameters' in
:py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will
not attempt to simplify the Wronskian before integrating. It is
recommended that you only use simplify=False with
'nth_linear_constant_coeff_variation_of_parameters_Integral' for this
method, especially if the solution to the homogeneous equation has
trigonometric functions in it.
Examples
========
>>> from sympy import Function, dsolve, pprint, exp, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 3) - 3*f(x).diff(x, 2) +
... 3*f(x).diff(x) - f(x) - exp(x)*log(x), f(x),
... hint='nth_linear_constant_coeff_variation_of_parameters'))
/ / / x*log(x) 11*x\\\ x
f(x) = |C1 + x*|C2 + x*|C3 + -------- - ----|||*e
\ \ \ 6 36 ///
References
==========
- https://en.wikipedia.org/wiki/Variation_of_parameters
- http://planetmath.org/VariationOfParameters
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 233
# indirect doctest
"""
hint = "nth_linear_constant_coeff_variation_of_parameters"
has_integral = True
def _matches(self):
eq = self.ode_problem.eq_high_order_free
func = self.ode_problem.func
order = self.ode_problem.order
x = self.ode_problem.sym
self.r = self.ode_problem.get_linear_coefficients(eq, func, order)
if order and self.r and not any(self.r[i].has(x) for i in self.r if i >= 0):
if self.r[-1]:
return True
else:
return False
return False
def _get_general_solution(self, *, simplify_flag: bool = True):
eq = self.ode_problem.eq_high_order_free
f = self.ode_problem.func.func
x = self.ode_problem.sym
order = self.ode_problem.order
roots, collectterms = _get_const_characteristic_eq_sols(self.r, f(x), order)
# A generator of constants
constants = self.ode_problem.get_numbered_constants(num=len(roots))
homogen_sol = Add(*[i*j for (i, j) in zip(constants, roots)])
homogen_sol = Eq(f(x), homogen_sol)
homogen_sol = _solve_variation_of_parameters(eq, f(x), roots, homogen_sol, order, self.r, simplify_flag)
if simplify_flag:
homogen_sol = _get_simplified_sol([homogen_sol], f(x), collectterms)
return [homogen_sol]
class NthLinearConstantCoeffUndeterminedCoefficients(SingleODESolver):
r"""
Solves an `n`\th order linear differential equation with constant
coefficients using the method of undetermined coefficients.
This method works on differential equations of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = P(x)\text{,}
where `P(x)` is a function that has a finite number of linearly
independent derivatives.
Functions that fit this requirement are finite sums functions of the form
`a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i`
is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For
example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`,
and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have
a finite number of derivatives, because they can be expanded into `\sin(a
x)` and `\cos(b x)` terms. However, SymPy currently cannot do that
expansion, so you will need to manually rewrite the expression in terms of
the above to use this method. So, for example, you will need to manually
convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method
of undetermined coefficients on it.
This method works by creating a trial function from the expression and all
of its linear independent derivatives and substituting them into the
original ODE. The coefficients for each term will be a system of linear
equations, which are be solved for and substituted, giving the solution.
If any of the trial functions are linearly dependent on the solution to
the homogeneous equation, they are multiplied by sufficient `x` to make
them linearly independent.
Examples
========
>>> from sympy import Function, dsolve, pprint, exp, cos
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 2) + 2*f(x).diff(x) + f(x) -
... 4*exp(-x)*x**2 + cos(2*x), f(x),
... hint='nth_linear_constant_coeff_undetermined_coefficients'))
/ / 3\\
| | x || -x 4*sin(2*x) 3*cos(2*x)
f(x) = |C1 + x*|C2 + --||*e - ---------- + ----------
\ \ 3 // 25 25
References
==========
- https://en.wikipedia.org/wiki/Method_of_undetermined_coefficients
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 221
# indirect doctest
"""
hint = "nth_linear_constant_coeff_undetermined_coefficients"
has_integral = False
def _matches(self):
eq = self.ode_problem.eq_high_order_free
func = self.ode_problem.func
order = self.ode_problem.order
x = self.ode_problem.sym
self.r = self.ode_problem.get_linear_coefficients(eq, func, order)
does_match = False
if order and self.r and not any(self.r[i].has(x) for i in self.r if i >= 0):
if self.r[-1]:
eq_homogeneous = Add(eq, -self.r[-1])
undetcoeff = _undetermined_coefficients_match(self.r[-1], x, func, eq_homogeneous)
if undetcoeff['test']:
self.trialset = undetcoeff['trialset']
does_match = True
return does_match
def _get_general_solution(self, *, simplify_flag: bool = True):
eq = self.ode_problem.eq
f = self.ode_problem.func.func
x = self.ode_problem.sym
order = self.ode_problem.order
roots, collectterms = _get_const_characteristic_eq_sols(self.r, f(x), order)
# A generator of constants
constants = self.ode_problem.get_numbered_constants(num=len(roots))
homogen_sol = Add(*[i*j for (i, j) in zip(constants, roots)])
homogen_sol = Eq(f(x), homogen_sol)
self.r.update({'list': roots, 'sol': homogen_sol, 'simpliy_flag': simplify_flag})
gsol = _solve_undetermined_coefficients(eq, f(x), order, self.r, self.trialset)
if simplify_flag:
gsol = _get_simplified_sol([gsol], f(x), collectterms)
return [gsol]
class NthLinearEulerEqHomogeneous(SingleODESolver):
r"""
Solves an `n`\th order linear homogeneous variable-coefficient
Cauchy-Euler equidimensional ordinary differential equation.
This is an equation with form `0 = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
These equations can be solved in a general manner, by substituting
solutions of the form `f(x) = x^r`, and deriving a characteristic equation
for `r`. When there are repeated roots, we include extra terms of the
form `C_{r k} \ln^k(x) x^r`, where `C_{r k}` is an arbitrary integration
constant, `r` is a root of the characteristic equation, and `k` ranges
over the multiplicity of `r`. In the cases where the roots are complex,
solutions of the form `C_1 x^a \sin(b \log(x)) + C_2 x^a \cos(b \log(x))`
are returned, based on expansions with Euler's formula. The general
solution is the sum of the terms found. If SymPy cannot find exact roots
to the characteristic equation, a
:py:obj:`~.ComplexRootOf` instance will be returned
instead.
>>> from sympy import Function, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(4*x**2*f(x).diff(x, 2) + f(x), f(x),
... hint='nth_linear_euler_eq_homogeneous')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), sqrt(x)*(C1 + C2*log(x)))
Note that because this method does not involve integration, there is no
``nth_linear_euler_eq_homogeneous_Integral`` hint.
The following is for internal use:
- ``returns = 'sol'`` returns the solution to the ODE.
- ``returns = 'list'`` returns a list of linearly independent solutions,
corresponding to the fundamental solution set, for use with non
homogeneous solution methods like variation of parameters and
undetermined coefficients. Note that, though the solutions should be
linearly independent, this function does not explicitly check that. You
can do ``assert simplify(wronskian(sollist)) != 0`` to check for linear
independence. Also, ``assert len(sollist) == order`` will need to pass.
- ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>,
'list': <list of linearly independent solutions>}``.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = f(x).diff(x, 2)*x**2 - 4*f(x).diff(x)*x + 6*f(x)
>>> pprint(dsolve(eq, f(x),
... hint='nth_linear_euler_eq_homogeneous'))
2
f(x) = x *(C1 + C2*x)
References
==========
- https://en.wikipedia.org/wiki/Cauchy%E2%80%93Euler_equation
- C. Bender & S. Orszag, "Advanced Mathematical Methods for Scientists and
Engineers", Springer 1999, pp. 12
# indirect doctest
"""
hint = "nth_linear_euler_eq_homogeneous"
has_integral = False
def _matches(self):
eq = self.ode_problem.eq_preprocessed
f = self.ode_problem.func.func
order = self.ode_problem.order
x = self.ode_problem.sym
match = self.ode_problem.get_linear_coefficients(eq, f(x), order)
self.r = None
does_match = False
if order and match:
coeff = match[order]
factor = x**order / coeff
self.r = {i: factor*match[i] for i in match}
if self.r and all(_test_term(self.r[i], f(x), i) for i in
self.r if i >= 0):
if not self.r[-1]:
does_match = True
return does_match
def _get_general_solution(self, *, simplify_flag: bool = True):
fx = self.ode_problem.func
eq = self.ode_problem.eq
homogen_sol = _get_euler_characteristic_eq_sols(eq, fx, self.r)[0]
return [homogen_sol]
class NthLinearEulerEqNonhomogeneousVariationOfParameters(SingleODESolver):
r"""
Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional
ordinary differential equation using variation of parameters.
This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
This method works by assuming that the particular solution takes the form
.. math:: \sum_{x=1}^{n} c_i(x) y_i(x) {a_n} {x^n} \text{, }
where `y_i` is the `i`\th solution to the homogeneous equation. The
solution is then solved using Wronskian's and Cramer's Rule. The
particular solution is given by multiplying eq given below with `a_n x^{n}`
.. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \, dx
\right) y_i(x) \text{, }
where `W(x)` is the Wronskian of the fundamental system (the system of `n`
linearly independent solutions to the homogeneous equation), and `W_i(x)`
is the Wronskian of the fundamental system with the `i`\th column replaced
with `[0, 0, \cdots, 0, \frac{x^{- n}}{a_n} g{\left(x \right)}]`.
This method is general enough to solve any `n`\th order inhomogeneous
linear differential equation, but sometimes SymPy cannot simplify the
Wronskian well enough to integrate it. If this method hangs, try using the
``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and
simplifying the integrals manually. Also, prefer using
``nth_linear_constant_coeff_undetermined_coefficients`` when it
applies, because it does not use integration, making it faster and more
reliable.
Warning, using simplify=False with
'nth_linear_constant_coeff_variation_of_parameters' in
:py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will
not attempt to simplify the Wronskian before integrating. It is
recommended that you only use simplify=False with
'nth_linear_constant_coeff_variation_of_parameters_Integral' for this
method, especially if the solution to the homogeneous equation has
trigonometric functions in it.
Examples
========
>>> from sympy import Function, dsolve, Derivative
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - x**4
>>> dsolve(eq, f(x),
... hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters').expand()
Eq(f(x), C1*x + C2*x**2 + x**4/6)
"""
hint = "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters"
has_integral = True
def _matches(self):
eq = self.ode_problem.eq_preprocessed
f = self.ode_problem.func.func
order = self.ode_problem.order
x = self.ode_problem.sym
match = self.ode_problem.get_linear_coefficients(eq, f(x), order)
self.r = None
does_match = False
if order and match:
coeff = match[order]
factor = x**order / coeff
self.r = {i: factor*match[i] for i in match}
if self.r and all(_test_term(self.r[i], f(x), i) for i in
self.r if i >= 0):
if self.r[-1]:
does_match = True
return does_match
def _get_general_solution(self, *, simplify_flag: bool = True):
eq = self.ode_problem.eq
f = self.ode_problem.func.func
x = self.ode_problem.sym
order = self.ode_problem.order
homogen_sol, roots = _get_euler_characteristic_eq_sols(eq, f(x), self.r)
self.r[-1] = self.r[-1]/self.r[order]
sol = _solve_variation_of_parameters(eq, f(x), roots, homogen_sol, order, self.r, simplify_flag)
return [Eq(f(x), homogen_sol.rhs + (sol.rhs - homogen_sol.rhs)*self.r[order])]
class NthLinearEulerEqNonhomogeneousUndeterminedCoefficients(SingleODESolver):
r"""
Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional
ordinary differential equation using undetermined coefficients.
This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
These equations can be solved in a general manner, by substituting
solutions of the form `x = exp(t)`, and deriving a characteristic equation
of form `g(exp(t)) = b_0 f(t) + b_1 f'(t) + b_2 f''(t) \cdots` which can
be then solved by nth_linear_constant_coeff_undetermined_coefficients if
g(exp(t)) has finite number of linearly independent derivatives.
Functions that fit this requirement are finite sums functions of the form
`a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i`
is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For
example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`,
and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have
a finite number of derivatives, because they can be expanded into `\sin(a
x)` and `\cos(b x)` terms. However, SymPy currently cannot do that
expansion, so you will need to manually rewrite the expression in terms of
the above to use this method. So, for example, you will need to manually
convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method
of undetermined coefficients on it.
After replacement of x by exp(t), this method works by creating a trial function
from the expression and all of its linear independent derivatives and
substituting them into the original ODE. The coefficients for each term
will be a system of linear equations, which are be solved for and
substituted, giving the solution. If any of the trial functions are linearly
dependent on the solution to the homogeneous equation, they are multiplied
by sufficient `x` to make them linearly independent.
Examples
========
>>> from sympy import dsolve, Function, Derivative, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x)
>>> dsolve(eq, f(x),
... hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients').expand()
Eq(f(x), C1*x + C2*x**2 + log(x)/2 + 3/4)
"""
hint = "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients"
has_integral = False
def _matches(self):
eq = self.ode_problem.eq_high_order_free
f = self.ode_problem.func.func
order = self.ode_problem.order
x = self.ode_problem.sym
match = self.ode_problem.get_linear_coefficients(eq, f(x), order)
self.r = None
does_match = False
if order and match:
coeff = match[order]
factor = x**order / coeff
self.r = {i: factor*match[i] for i in match}
if self.r and all(_test_term(self.r[i], f(x), i) for i in
self.r if i >= 0):
if self.r[-1]:
e, re = posify(self.r[-1].subs(x, exp(x)))
undetcoeff = _undetermined_coefficients_match(e.subs(re), x)
if undetcoeff['test']:
does_match = True
return does_match
def _get_general_solution(self, *, simplify_flag: bool = True):
f = self.ode_problem.func.func
x = self.ode_problem.sym
chareq, eq, symbol = S.Zero, S.Zero, Dummy('x')
for i in self.r.keys():
if i >= 0:
chareq += (self.r[i]*diff(x**symbol, x, i)*x**-symbol).expand()
for i in range(1, degree(Poly(chareq, symbol))+1):
eq += chareq.coeff(symbol**i)*diff(f(x), x, i)
if chareq.as_coeff_add(symbol)[0]:
eq += chareq.as_coeff_add(symbol)[0]*f(x)
e, re = posify(self.r[-1].subs(x, exp(x)))
eq += e.subs(re)
self.const_undet_instance = NthLinearConstantCoeffUndeterminedCoefficients(SingleODEProblem(eq, f(x), x))
sol = self.const_undet_instance.get_general_solution(simplify = simplify_flag)[0]
sol = sol.subs(x, log(x))
sol = sol.subs(f(log(x)), f(x)).expand()
return [sol]
class SecondLinearBessel(SingleODESolver):
r"""
Gives solution of the Bessel differential equation
.. math :: x^2 \frac{d^2y}{dx^2} + x \frac{dy}{dx} y(x) + (x^2-n^2) y(x)
if `n` is integer then the solution is of the form ``Eq(f(x), C0 besselj(n,x)
+ C1 bessely(n,x))`` as both the solutions are linearly independent else if
`n` is a fraction then the solution is of the form ``Eq(f(x), C0 besselj(n,x)
+ C1 besselj(-n,x))`` which can also transform into ``Eq(f(x), C0 besselj(n,x)
+ C1 bessely(n,x))``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import Symbol
>>> v = Symbol('v', positive=True)
>>> from sympy import dsolve, Function
>>> f = Function('f')
>>> y = f(x)
>>> genform = x**2*y.diff(x, 2) + x*y.diff(x) + (x**2 - v**2)*y
>>> dsolve(genform)
Eq(f(x), C1*besselj(v, x) + C2*bessely(v, x))
References
==========
https://www.math24.net/bessel-differential-equation/
"""
hint = "2nd_linear_bessel"
has_integral = False
def _matches(self):
eq = self.ode_problem.eq_high_order_free
f = self.ode_problem.func
order = self.ode_problem.order
x = self.ode_problem.sym
df = f.diff(x)
a = Wild('a', exclude=[f,df])
b = Wild('b', exclude=[x, f,df])
a4 = Wild('a4', exclude=[x,f,df])
b4 = Wild('b4', exclude=[x,f,df])
c4 = Wild('c4', exclude=[x,f,df])
d4 = Wild('d4', exclude=[x,f,df])
a3 = Wild('a3', exclude=[f, df, f.diff(x, 2)])
b3 = Wild('b3', exclude=[f, df, f.diff(x, 2)])
c3 = Wild('c3', exclude=[f, df, f.diff(x, 2)])
deq = a3*(f.diff(x, 2)) + b3*df + c3*f
r = collect(eq,
[f.diff(x, 2), df, f]).match(deq)
if order == 2 and r:
if not all(r[key].is_polynomial() for key in r):
n, d = eq.as_numer_denom()
eq = expand(n)
r = collect(eq,
[f.diff(x, 2), df, f]).match(deq)
if r and r[a3] != 0:
# leading coeff of f(x).diff(x, 2)
coeff = factor(r[a3]).match(a4*(x-b)**b4)
if coeff:
# if coeff[b4] = 0 means constant coefficient
if coeff[b4] == 0:
return False
point = coeff[b]
else:
return False
if point:
r[a3] = simplify(r[a3].subs(x, x+point))
r[b3] = simplify(r[b3].subs(x, x+point))
r[c3] = simplify(r[c3].subs(x, x+point))
# making a3 in the form of x**2
r[a3] = cancel(r[a3]/(coeff[a4]*(x)**(-2+coeff[b4])))
r[b3] = cancel(r[b3]/(coeff[a4]*(x)**(-2+coeff[b4])))
r[c3] = cancel(r[c3]/(coeff[a4]*(x)**(-2+coeff[b4])))
# checking if b3 is of form c*(x-b)
coeff1 = factor(r[b3]).match(a4*(x))
if coeff1 is None:
return False
# c3 maybe of very complex form so I am simply checking (a - b) form
# if yes later I will match with the standerd form of bessel in a and b
# a, b are wild variable defined above.
_coeff2 = r[c3].match(a - b)
if _coeff2 is None:
return False
# matching with standerd form for c3
coeff2 = factor(_coeff2[a]).match(c4**2*(x)**(2*a4))
if coeff2 is None:
return False
if _coeff2[b] == 0:
coeff2[d4] = 0
else:
coeff2[d4] = factor(_coeff2[b]).match(d4**2)[d4]
self.rn = {'n':coeff2[d4], 'a4':coeff2[c4], 'd4':coeff2[a4]}
self.rn['c4'] = coeff1[a4]
self.rn['b4'] = point
return True
return False
def _get_general_solution(self, *, simplify_flag: bool = True):
f = self.ode_problem.func.func
x = self.ode_problem.sym
n = self.rn['n']
a4 = self.rn['a4']
c4 = self.rn['c4']
d4 = self.rn['d4']
b4 = self.rn['b4']
n = sqrt(n**2 + Rational(1, 4)*(c4 - 1)**2)
(C1, C2) = self.ode_problem.get_numbered_constants(num=2)
return [Eq(f(x), ((x**(Rational(1-c4,2)))*(C1*besselj(n/d4,a4*x**d4/d4)
+ C2*bessely(n/d4,a4*x**d4/d4))).subs(x, x-b4))]
class SecondLinearAiry(SingleODESolver):
r"""
Gives solution of the Airy differential equation
.. math :: \frac{d^2y}{dx^2} + (a + b x) y(x) = 0
in terms of Airy special functions airyai and airybi.
Examples
========
>>> from sympy import dsolve, Function
>>> from sympy.abc import x
>>> f = Function("f")
>>> eq = f(x).diff(x, 2) - x*f(x)
>>> dsolve(eq)
Eq(f(x), C1*airyai(x) + C2*airybi(x))
"""
hint = "2nd_linear_airy"
has_integral = False
def _matches(self):
eq = self.ode_problem.eq_high_order_free
f = self.ode_problem.func
order = self.ode_problem.order
x = self.ode_problem.sym
df = f.diff(x)
a4 = Wild('a4', exclude=[x,f,df])
b4 = Wild('b4', exclude=[x,f,df])
match = self.ode_problem.get_linear_coefficients(eq, f, order)
does_match = False
if order == 2 and match and match[2] != 0:
if match[1].is_zero:
self.rn = cancel(match[0]/match[2]).match(a4+b4*x)
if self.rn and self.rn[b4] != 0:
self.rn = {'b':self.rn[a4],'m':self.rn[b4]}
does_match = True
return does_match
def _get_general_solution(self, *, simplify_flag: bool = True):
f = self.ode_problem.func.func
x = self.ode_problem.sym
(C1, C2) = self.ode_problem.get_numbered_constants(num=2)
b = self.rn['b']
m = self.rn['m']
if m.is_positive:
arg = - b/cbrt(m)**2 - cbrt(m)*x
elif m.is_negative:
arg = - b/cbrt(-m)**2 + cbrt(-m)*x
else:
arg = - b/cbrt(-m)**2 + cbrt(-m)*x
return [Eq(f(x), C1*airyai(arg) + C2*airybi(arg))]
class LieGroup(SingleODESolver):
r"""
This hint implements the Lie group method of solving first order differential
equations. The aim is to convert the given differential equation from the
given coordinate system into another coordinate system where it becomes
invariant under the one-parameter Lie group of translations. The converted
ODE can be easily solved by quadrature. It makes use of the
:py:meth:`sympy.solvers.ode.infinitesimals` function which returns the
infinitesimals of the transformation.
The coordinates `r` and `s` can be found by solving the following Partial
Differential Equations.
.. math :: \xi\frac{\partial r}{\partial x} + \eta\frac{\partial r}{\partial y}
= 0
.. math :: \xi\frac{\partial s}{\partial x} + \eta\frac{\partial s}{\partial y}
= 1
The differential equation becomes separable in the new coordinate system
.. math :: \frac{ds}{dr} = \frac{\frac{\partial s}{\partial x} +
h(x, y)\frac{\partial s}{\partial y}}{
\frac{\partial r}{\partial x} + h(x, y)\frac{\partial r}{\partial y}}
After finding the solution by integration, it is then converted back to the original
coordinate system by substituting `r` and `s` in terms of `x` and `y` again.
Examples
========
>>> from sympy import Function, dsolve, exp, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x) + 2*x*f(x) - x*exp(-x**2), f(x),
... hint='lie_group'))
/ 2\ 2
| x | -x
f(x) = |C1 + --|*e
\ 2 /
References
==========
- Solving differential equations by Symmetry Groups,
John Starrett, pp. 1 - pp. 14
"""
hint = "lie_group"
has_integral = False
def _has_additional_params(self):
return 'xi' in self.ode_problem.params and 'eta' in self.ode_problem.params
def _matches(self):
eq = self.ode_problem.eq
f = self.ode_problem.func.func
order = self.ode_problem.order
x = self.ode_problem.sym
df = f(x).diff(x)
y = Dummy('y')
d = Wild('d', exclude=[df, f(x).diff(x, 2)])
e = Wild('e', exclude=[df])
does_match = False
if self._has_additional_params() and order == 1:
xi = self.ode_problem.params['xi']
eta = self.ode_problem.params['eta']
self.r3 = {'xi': xi, 'eta': eta}
r = collect(eq, df, exact=True).match(d + e * df)
if r:
r['d'] = d
r['e'] = e
r['y'] = y
r[d] = r[d].subs(f(x), y)
r[e] = r[e].subs(f(x), y)
self.r3.update(r)
does_match = True
return does_match
def _get_general_solution(self, *, simplify_flag: bool = True):
eq = self.ode_problem.eq
x = self.ode_problem.sym
func = self.ode_problem.func
order = self.ode_problem.order
df = func.diff(x)
try:
eqsol = solve(eq, df)
except NotImplementedError:
eqsol = []
desols = []
for s in eqsol:
sol = _ode_lie_group(s, func, order, match=self.r3)
if sol:
desols.extend(sol)
if desols == []:
raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by"
+ " the lie group method")
return desols
solver_map = {
'factorable': Factorable,
'nth_linear_constant_coeff_homogeneous': NthLinearConstantCoeffHomogeneous,
'nth_linear_euler_eq_homogeneous': NthLinearEulerEqHomogeneous,
'nth_linear_constant_coeff_undetermined_coefficients': NthLinearConstantCoeffUndeterminedCoefficients,
'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients': NthLinearEulerEqNonhomogeneousUndeterminedCoefficients,
'separable': Separable,
'1st_exact': FirstExact,
'1st_linear': FirstLinear,
'Bernoulli': Bernoulli,
'Riccati_special_minus2': RiccatiSpecial,
'1st_rational_riccati': RationalRiccati,
'1st_homogeneous_coeff_best': HomogeneousCoeffBest,
'1st_homogeneous_coeff_subs_indep_div_dep': HomogeneousCoeffSubsIndepDivDep,
'1st_homogeneous_coeff_subs_dep_div_indep': HomogeneousCoeffSubsDepDivIndep,
'almost_linear': AlmostLinear,
'linear_coefficients': LinearCoefficients,
'separable_reduced': SeparableReduced,
'nth_linear_constant_coeff_variation_of_parameters': NthLinearConstantCoeffVariationOfParameters,
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters': NthLinearEulerEqNonhomogeneousVariationOfParameters,
'Liouville': Liouville,
'2nd_linear_airy': SecondLinearAiry,
'2nd_linear_bessel': SecondLinearBessel,
'2nd_hypergeometric': SecondHypergeometric,
'nth_order_reducible': NthOrderReducible,
'2nd_nonlinear_autonomous_conserved': SecondNonlinearAutonomousConserved,
'nth_algebraic': NthAlgebraic,
'lie_group': LieGroup,
}
# Avoid circular import:
from .ode import dsolve, ode_sol_simplicity, odesimp, homogeneous_order
|
2631b6967f2aa132650de0b0c641f1336a6c1d9469db5dadbaf39918051478dd | from sympy.assumptions.ask import (Q, ask)
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.function import (Derivative, Function, diff)
from sympy.core.mul import Mul
from sympy.core import (GoldenRatio, TribonacciConstant)
from sympy.core.numbers import (E, Float, I, Rational, oo, pi)
from sympy.core.relational import (Eq, Gt, Lt, Ne)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, Wild, symbols)
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import binomial
from sympy.functions.elementary.complexes import (Abs, arg, conjugate, im, re)
from sympy.functions.elementary.exponential import (LambertW, exp, log)
from sympy.functions.elementary.hyperbolic import (atanh, cosh, sinh, tanh)
from sympy.functions.elementary.miscellaneous import (cbrt, root, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, asin, atan, atan2, cos, sec, sin, tan)
from sympy.functions.special.error_functions import (erf, erfc, erfcinv, erfinv)
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import (And, Or)
from sympy.matrices.dense import Matrix
from sympy.matrices import SparseMatrix
from sympy.polys.polytools import Poly
from sympy.printing.str import sstr
from sympy.simplify.radsimp import denom
from sympy.solvers.solvers import (nsolve, solve, solve_linear)
from sympy.core.function import nfloat
from sympy.solvers import solve_linear_system, solve_linear_system_LU, \
solve_undetermined_coeffs
from sympy.solvers.bivariate import _filtered_gens, _solve_lambert, _lambert
from sympy.solvers.solvers import _invert, unrad, checksol, posify, _ispow, \
det_quick, det_perm, det_minor, _simple_dens, denoms
from sympy.physics.units import cm
from sympy.polys.rootoftools import CRootOf
from sympy.testing.pytest import slow, XFAIL, SKIP, raises
from sympy.core.random import verify_numerically as tn
from sympy.abc import a, b, c, d, e, k, h, p, x, y, z, t, q, m, R
def NS(e, n=15, **options):
return sstr(sympify(e).evalf(n, **options), full_prec=True)
def test_swap_back():
f, g = map(Function, 'fg')
fx, gx = f(x), g(x)
assert solve([fx + y - 2, fx - gx - 5], fx, y, gx) == \
{fx: gx + 5, y: -gx - 3}
assert solve(fx + gx*x - 2, [fx, gx], dict=True) == [{fx: 2, gx: 0}]
assert solve(fx + gx**2*x - y, [fx, gx], dict=True) == [{fx: y, gx: 0}]
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 raises
raises(ValueError, lambda: solve((x - 3, y + 2), x, y, x))
raises(ValueError, lambda: solve(x, x, x))
# no error in exclude
assert solve(x, x, exclude=[y, y]) == [0]
# duplicate symbols raises
raises(ValueError, lambda: solve((x - 3, y + 2), x, y, x))
raises(ValueError, lambda: solve(x, x, x))
# no error in exclude
assert solve(x, x, exclude=[y, y]) == [0]
# 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}
assert solve((a + b)*x + b - c, [a, b]) == {a: -c, b: c}
eq = a*x**2 + b*x + c - ((x - h)**2 + 4*p*k)/4/p
# - check that flags are obeyed
sol = solve(eq, [h, p, k], exclude=[a, b, c])
assert sol == {h: -b/(2*a), k: (4*a*c - b**2)/(4*a), p: 1/(4*a)}
assert solve(eq, [h, p, k], dict=True) == [sol]
assert solve(eq, [h, p, k], set=True) == \
([h, p, k], {(-b/(2*a), 1/(4*a), (4*a*c - b**2)/(4*a))})
# issue 23889 - polysys not simplified
assert solve(eq, [h, p, k], exclude=[a, b, c], simplify=False) == \
{h: -b/(2*a), k: (4*a*c - b**2)/(4*a), p: 1/(4*a)}
# but this only happens when system has a single solution
args = (a + b)*x - b**2 + 2, a, b
assert solve(*args) == [((b**2 - b*x - 2)/x, b)]
# and if the system has a solution; the following doesn't so
# an algebraic solution is returned
assert solve(a*x + b**2/(x + 4) - 3*x - 4/x, a, b, dict=True) == \
[{a: (-b**2*x + 3*x**3 + 12*x**2 + 4*x + 16)/(x**2*(x + 4))}]
# failed single equation
assert solve(1/(1/x - y + exp(y))) == []
raises(
NotImplementedError, lambda: solve(exp(x) + sin(x) + exp(y) + sin(y)))
# failed system
# -- when no symbols given, 1 fails
assert solve([y, exp(x) + x]) == [{x: -LambertW(1), y: 0}]
# both fail
assert solve(
(exp(x) - x, exp(y) - y)) == [{x: -LambertW(-1), y: -LambertW(-1)}]
# -- when symbols given
assert solve([y, exp(x) + x], x, y) == [(-LambertW(1), 0)]
# symbol is a number
assert solve(x**2 - pi, pi) == [x**2]
# no equations
assert solve([], [x]) == []
# nonlinear system
assert solve((x**2 - 4, y - 2), x, y) == [(-2, 2), (2, 2)]
assert solve((x**2 - 4, y - 2), y, x) == [(2, -2), (2, 2)]
assert solve((x**2 - 4 + z, y - 2 - z), a, z, y, x, set=True
) == ([a, z, y, x], {
(a, z, z + 2, -sqrt(4 - z)),
(a, z, z + 2, sqrt(4 - z))})
# 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.0] # issue 19048
assert solve([True, Eq(x, 0)], [x], dict=True) == [{x: 0}]
assert solve([Eq(x, x), Eq(x, 0), Eq(x, x+1)], [x], dict=True) == []
assert not solve([Eq(x, x+1), x < 2], x)
assert solve([Eq(x, 0), x+1<2]) == Eq(x, 0)
assert solve([Eq(x, x), Eq(x, x+1)], x) == []
assert solve(True, x) == []
assert solve([x - 1, False], [x], set=True) == ([], set())
assert solve([-y*(x + y - 1)/2, (y - 1)/x/y + 1/y],
set=True, check=False) == ([x, y], {(1 - y, y), (x, 0)})
# ordering should be canonical, fastest to order by keys instead
# of by size
assert list(solve((y - 1, x - sqrt(3)*z)).keys()) == [x, y]
# as set always returns as symbols, set even if no solution
assert solve([x - 1, x], (y, x), set=True) == ([y, x], set())
assert solve([x - 1, x], {y, x}, set=True) == ([x, y], 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 = {x: S.Zero, y: S.Zero}
assert solve((x - y, x + y), x, y ) == solution
assert solve((x - y, x + y), (x, y)) == solution
assert solve((x - y, x + y), [x, y]) == solution
assert set(solve(x**3 - 15*x - 4, x)) == {
-2 + 3**S.Half,
S(4),
-2 - 3**S.Half
}
assert set(solve((x**2 - 1)**2 - a, x)) == \
{sqrt(1 + sqrt(a)), -sqrt(1 + sqrt(a)),
sqrt(1 - sqrt(a)), -sqrt(1 - sqrt(a))}
def test_solve_polynomial2():
assert solve(4, x) == []
def test_solve_polynomial_cv_1a():
"""
Test for solving on equations that can be converted to a polynomial equation
using the change of variable y -> x**Rational(p, q)
"""
assert solve( sqrt(x) - 1, x) == [1]
assert solve( sqrt(x) - 2, x) == [4]
assert solve( x**Rational(1, 4) - 2, x) == [16]
assert solve( x**Rational(1, 3) - 3, x) == [27]
assert solve(sqrt(x) + x**Rational(1, 3) + x**Rational(1, 4), x) == [0]
def test_solve_polynomial_cv_1b():
assert set(solve(4*x*(1 - a*sqrt(x)), x)) == {S.Zero, 1/a**2}
assert set(solve(x*(root(x, 3) - 3), x)) == {S.Zero, S(27)}
def test_solve_polynomial_cv_2():
"""
Test for solving on equations that can be converted to a polynomial equation
multiplying both sides of the equation by x**m
"""
assert solve(x + 1/x - 1, x) in \
[[ S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2],
[ S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2]]
def test_quintics_1():
f = x**5 - 110*x**3 - 55*x**2 + 2310*x + 979
s = solve(f, check=False)
for r in s:
res = f.subs(x, r.n()).n()
assert tn(res, 0)
f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20
s = solve(f)
for r in s:
assert r.func == CRootOf
# if one uses solve to get the roots of a polynomial that has a CRootOf
# solution, make sure that the use of nfloat during the solve process
# doesn't fail. Note: if you want numerical solutions to a polynomial
# it is *much* faster to use nroots to get them than to solve the
# equation only to get RootOf solutions which are then numerically
# evaluated. So for eq = x**5 + 3*x + 7 do Poly(eq).nroots() rather
# than [i.n() for i in solve(eq)] to get the numerical roots of eq.
assert nfloat(solve(x**5 + 3*x**3 + 7)[0], exponent=False) == \
CRootOf(x**5 + 3*x**3 + 7, 0).n()
def test_quintics_2():
f = x**5 + 15*x + 12
s = solve(f, check=False)
for r in s:
res = f.subs(x, r.n()).n()
assert tn(res, 0)
f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20
s = solve(f)
for r in s:
assert r.func == CRootOf
assert solve(x**5 - 6*x**3 - 6*x**2 + x - 6) == [
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 0),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 1),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 2),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 3),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 4)]
def test_quintics_3():
y = x**5 + x**3 - 2**Rational(1, 3)
assert solve(y) == solve(-y) == []
def test_highorder_poly():
# just testing that the uniq generator is unpacked
sol = solve(x**6 - 2*x + 2)
assert all(isinstance(i, CRootOf) for i in sol) and len(sol) == 6
def test_solve_rational():
"""Test solve for rational functions"""
assert solve( ( x - y**3 )/( (y**2)*sqrt(1 - y**2) ), x) == [y**3]
def test_solve_conjugate():
"""Test solve for simple conjugate functions"""
assert solve(conjugate(x) -3 + I) == [3 + I]
def test_solve_nonlinear():
assert solve(x**2 - y**2, x, y, dict=True) == [{x: -y}, {x: y}]
assert solve(x**2 - y**2/exp(x), y, x, dict=True) == [{y: -x*sqrt(exp(x))},
{y: x*sqrt(exp(x))}]
def test_issue_8666():
x = symbols('x')
assert solve(Eq(x**2 - 1/(x**2 - 4), 4 - 1/(x**2 - 4)), x) == []
assert solve(Eq(x + 1/x, 1/x), x) == []
def test_issue_7228():
assert solve(4**(2*(x**2) + 2*x) - 8, x) == [Rational(-3, 2), S.Half]
def test_issue_7190():
assert solve(log(x-3) + log(x+3), x) == [sqrt(10)]
def test_issue_21004():
x = symbols('x')
f = x/sqrt(x**2+1)
f_diff = f.diff(x)
assert solve(f_diff, x) == []
def test_linear_system():
x, y, z, t, n = symbols('x, y, z, t, n')
assert solve([x - 1, x - y, x - 2*y, y - 1], [x, y]) == []
assert solve([x - 1, x - y, x - 2*y, x - 1], [x, y]) == []
assert solve([x - 1, x - 1, x - y, x - 2*y], [x, y]) == []
assert solve([x + 5*y - 2, -3*x + 6*y - 15], x, y) == {x: -3, y: 1}
M = Matrix([[0, 0, n*(n + 1), (n + 1)**2, 0],
[n + 1, n + 1, -2*n - 1, -(n + 1), 0],
[-1, 0, 1, 0, 0]])
assert solve_linear_system(M, x, y, z, t) == \
{x: t*(-n-1)/n, y: 0, z: t*(-n-1)/n}
assert solve([x + y + z + t, -z - t], x, y, z, t) == {x: -y, z: -t}
@XFAIL
def test_linear_system_xfail():
# https://github.com/sympy/sympy/issues/6420
M = Matrix([[0, 15.0, 10.0, 700.0],
[1, 1, 1, 100.0],
[0, 10.0, 5.0, 200.0],
[-5.0, 0, 0, 0 ]])
assert solve_linear_system(M, x, y, z) == {x: 0, y: -60.0, z: 160.0}
def test_linear_system_function():
a = Function('a')
assert solve([a(0, 0) + a(0, 1) + a(1, 0) + a(1, 1), -a(1, 0) - a(1, 1)],
a(0, 0), a(0, 1), a(1, 0), a(1, 1)) == {a(1, 0): -a(1, 1), a(0, 0): -a(0, 1)}
def test_linear_system_symbols_doesnt_hang_1():
def _mk_eqs(wy):
# Equations for fitting a wy*2 - 1 degree polynomial between two points,
# at end points derivatives are known up to order: wy - 1
order = 2*wy - 1
x, x0, x1 = symbols('x, x0, x1', real=True)
y0s = symbols('y0_:{}'.format(wy), real=True)
y1s = symbols('y1_:{}'.format(wy), real=True)
c = symbols('c_:{}'.format(order+1), real=True)
expr = sum([coeff*x**o for o, coeff in enumerate(c)])
eqs = []
for i in range(wy):
eqs.append(expr.diff(x, i).subs({x: x0}) - y0s[i])
eqs.append(expr.diff(x, i).subs({x: x1}) - y1s[i])
return eqs, c
#
# The purpose of this test is just to see that these calls don't hang. The
# expressions returned are complicated so are not included here. Testing
# their correctness takes longer than solving the system.
#
for n in range(1, 7+1):
eqs, c = _mk_eqs(n)
solve(eqs, c)
def test_linear_system_symbols_doesnt_hang_2():
M = Matrix([
[66, 24, 39, 50, 88, 40, 37, 96, 16, 65, 31, 11, 37, 72, 16, 19, 55, 37, 28, 76],
[10, 93, 34, 98, 59, 44, 67, 74, 74, 94, 71, 61, 60, 23, 6, 2, 57, 8, 29, 78],
[19, 91, 57, 13, 64, 65, 24, 53, 77, 34, 85, 58, 87, 39, 39, 7, 36, 67, 91, 3],
[74, 70, 15, 53, 68, 43, 86, 83, 81, 72, 25, 46, 67, 17, 59, 25, 78, 39, 63, 6],
[69, 40, 67, 21, 67, 40, 17, 13, 93, 44, 46, 89, 62, 31, 30, 38, 18, 20, 12, 81],
[50, 22, 74, 76, 34, 45, 19, 76, 28, 28, 11, 99, 97, 82, 8, 46, 99, 57, 68, 35],
[58, 18, 45, 88, 10, 64, 9, 34, 90, 82, 17, 41, 43, 81, 45, 83, 22, 88, 24, 39],
[42, 21, 70, 68, 6, 33, 64, 81, 83, 15, 86, 75, 86, 17, 77, 34, 62, 72, 20, 24],
[ 7, 8, 2, 72, 71, 52, 96, 5, 32, 51, 31, 36, 79, 88, 25, 77, 29, 26, 33, 13],
[19, 31, 30, 85, 81, 39, 63, 28, 19, 12, 16, 49, 37, 66, 38, 13, 3, 71, 61, 51],
[29, 82, 80, 49, 26, 85, 1, 37, 2, 74, 54, 82, 26, 47, 54, 9, 35, 0, 99, 40],
[15, 49, 82, 91, 93, 57, 45, 25, 45, 97, 15, 98, 48, 52, 66, 24, 62, 54, 97, 37],
[62, 23, 73, 53, 52, 86, 28, 38, 0, 74, 92, 38, 97, 70, 71, 29, 26, 90, 67, 45],
[ 2, 32, 23, 24, 71, 37, 25, 71, 5, 41, 97, 65, 93, 13, 65, 45, 25, 88, 69, 50],
[40, 56, 1, 29, 79, 98, 79, 62, 37, 28, 45, 47, 3, 1, 32, 74, 98, 35, 84, 32],
[33, 15, 87, 79, 65, 9, 14, 63, 24, 19, 46, 28, 74, 20, 29, 96, 84, 91, 93, 1],
[97, 18, 12, 52, 1, 2, 50, 14, 52, 76, 19, 82, 41, 73, 51, 79, 13, 3, 82, 96],
[40, 28, 52, 10, 10, 71, 56, 78, 82, 5, 29, 48, 1, 26, 16, 18, 50, 76, 86, 52],
[38, 89, 83, 43, 29, 52, 90, 77, 57, 0, 67, 20, 81, 88, 48, 96, 88, 58, 14, 3]])
syms = x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18 = symbols('x:19')
sol = {
x0: -S(1967374186044955317099186851240896179)/3166636564687820453598895768302256588,
x1: -S(84268280268757263347292368432053826)/791659141171955113399723942075564147,
x2: -S(229962957341664730974463872411844965)/1583318282343910226799447884151128294,
x3: S(990156781744251750886760432229180537)/6333273129375640907197791536604513176,
x4: -S(2169830351210066092046760299593096265)/18999819388126922721593374609813539528,
x5: S(4680868883477577389628494526618745355)/9499909694063461360796687304906769764,
x6: -S(1590820774344371990683178396480879213)/3166636564687820453598895768302256588,
x7: -S(54104723404825537735226491634383072)/339282489073695048599881689460956063,
x8: S(3182076494196560075964847771774733847)/6333273129375640907197791536604513176,
x9: -S(10870817431029210431989147852497539675)/18999819388126922721593374609813539528,
x10: -S(13118019242576506476316318268573312603)/18999819388126922721593374609813539528,
x11: -S(5173852969886775824855781403820641259)/4749954847031730680398343652453384882,
x12: S(4261112042731942783763341580651820563)/4749954847031730680398343652453384882,
x13: -S(821833082694661608993818117038209051)/6333273129375640907197791536604513176,
x14: S(906881575107250690508618713632090559)/904753304196520129599684505229216168,
x15: -S(732162528717458388995329317371283987)/6333273129375640907197791536604513176,
x16: S(4524215476705983545537087360959896817)/9499909694063461360796687304906769764,
x17: -S(3898571347562055611881270844646055217)/6333273129375640907197791536604513176,
x18: S(7513502486176995632751685137907442269)/18999819388126922721593374609813539528
}
eqs = list(M * Matrix(syms + (1,)))
assert solve(eqs, syms) == sol
y = Symbol('y')
eqs = list(y * M * Matrix(syms + (1,)))
assert solve(eqs, syms) == sol
def test_linear_systemLU():
n = Symbol('n')
M = Matrix([[1, 2, 0, 1], [1, 3, 2*n, 1], [4, -1, n**2, 1]])
assert solve_linear_system_LU(M, [x, y, z]) == {z: -3/(n**2 + 18*n),
x: 1 - 12*n/(n**2 + 18*n),
y: 6*n/(n**2 + 18*n)}
# Note: multiple solutions exist for some of these equations, so the tests
# should be expected to break if the implementation of the solver changes
# in such a way that a different branch is chosen
@slow
def test_solve_transcendental():
from sympy.abc import a, b
assert solve(exp(x) - 3, x) == [log(3)]
assert set(solve((a*x + b)*(exp(x) - 3), x)) == {-b/a, log(3)}
assert solve(cos(x) - y, x) == [-acos(y) + 2*pi, acos(y)]
assert solve(2*cos(x) - y, x) == [-acos(y/2) + 2*pi, acos(y/2)]
assert solve(Eq(cos(x), sin(x)), x) == [pi/4]
assert set(solve(exp(x) + exp(-x) - y, x)) in [{
log(y/2 - sqrt(y**2 - 4)/2),
log(y/2 + sqrt(y**2 - 4)/2),
}, {
log(y - sqrt(y**2 - 4)) - log(2),
log(y + sqrt(y**2 - 4)) - log(2)},
{
log(y/2 - sqrt((y - 2)*(y + 2))/2),
log(y/2 + sqrt((y - 2)*(y + 2))/2)}]
assert solve(exp(x) - 3, x) == [log(3)]
assert solve(Eq(exp(x), 3), x) == [log(3)]
assert solve(log(x) - 3, x) == [exp(3)]
assert solve(sqrt(3*x) - 4, x) == [Rational(16, 3)]
assert solve(3**(x + 2), x) == []
assert solve(3**(2 - x), x) == []
assert solve(x + 2**x, x) == [-LambertW(log(2))/log(2)]
assert solve(2*x + 5 + log(3*x - 2), x) == \
[Rational(2, 3) + LambertW(2*exp(Rational(-19, 3))/3)/2]
assert solve(3*x + log(4*x), x) == [LambertW(Rational(3, 4))/3]
assert set(solve((2*x + 8)*(8 + exp(x)), x)) == {S(-4), log(8) + pi*I}
eq = 2*exp(3*x + 4) - 3
ans = solve(eq, x) # this generated a failure in flatten
assert len(ans) == 3 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans)
assert solve(2*log(3*x + 4) - 3, x) == [(exp(Rational(3, 2)) - 4)/3]
assert solve(exp(x) + 1, x) == [pi*I]
eq = 2*(3*x + 4)**5 - 6*7**(3*x + 9)
result = solve(eq, x)
x0 = -log(2401)
x1 = 3**Rational(1, 5)
x2 = log(7**(7*x1/20))
x3 = sqrt(2)
x4 = sqrt(5)
x5 = x3*sqrt(x4 - 5)
x6 = x4 + 1
x7 = 1/(3*log(7))
x8 = -x4
x9 = x3*sqrt(x8 - 5)
x10 = x8 + 1
ans = [x7*(x0 - 5*LambertW(x2*(-x5 + x6))),
x7*(x0 - 5*LambertW(x2*(x5 + x6))),
x7*(x0 - 5*LambertW(x2*(x10 - x9))),
x7*(x0 - 5*LambertW(x2*(x10 + x9))),
x7*(x0 - 5*LambertW(-log(7**(7*x1/5))))]
assert result == ans, result
# it works if expanded, too
assert solve(eq.expand(), x) == result
assert solve(z*cos(x) - y, x) == [-acos(y/z) + 2*pi, acos(y/z)]
assert solve(z*cos(2*x) - y, x) == [-acos(y/z)/2 + pi, acos(y/z)/2]
assert solve(z*cos(sin(x)) - y, x) == [
pi - asin(acos(y/z)), asin(acos(y/z) - 2*pi) + pi,
-asin(acos(y/z) - 2*pi), asin(acos(y/z))]
assert solve(z*cos(x), x) == [pi/2, pi*Rational(3, 2)]
# issue 4508
assert solve(y - b*x/(a + x), x) in [[-a*y/(y - b)], [a*y/(b - y)]]
assert solve(y - b*exp(a/x), x) == [a/log(y/b)]
# issue 4507
assert solve(y - b/(1 + a*x), x) in [[(b - y)/(a*y)], [-((y - b)/(a*y))]]
# issue 4506
assert solve(y - a*x**b, x) == [(y/a)**(1/b)]
# issue 4505
assert solve(z**x - y, x) == [log(y)/log(z)]
# issue 4504
assert solve(2**x - 10, x) == [1 + log(5)/log(2)]
# issue 6744
assert solve(x*y) == [{x: 0}, {y: 0}]
assert solve([x*y]) == [{x: 0}, {y: 0}]
assert solve(x**y - 1) == [{x: 1}, {y: 0}]
assert solve([x**y - 1]) == [{x: 1}, {y: 0}]
assert solve(x*y*(x**2 - y**2)) == [{x: 0}, {x: -y}, {x: y}, {y: 0}]
assert solve([x*y*(x**2 - y**2)]) == [{x: 0}, {x: -y}, {x: y}, {y: 0}]
# issue 4739
assert solve(exp(log(5)*x) - 2**x, x) == [0]
# issue 14791
assert solve(exp(log(5)*x) - exp(log(2)*x), x) == [0]
f = Function('f')
assert solve(y*f(log(5)*x) - y*f(log(2)*x), x) == [0]
assert solve(f(x) - f(0), x) == [0]
assert solve(f(x) - f(2 - x), x) == [1]
raises(NotImplementedError, lambda: solve(f(x, y) - f(1, 2), x))
raises(NotImplementedError, lambda: solve(f(x, y) - f(2 - x, 2), x))
raises(ValueError, lambda: solve(f(x, y) - f(1 - x), x))
raises(ValueError, lambda: solve(f(x, y) - f(1), x))
# misc
# make sure that the right variables is picked up in tsolve
# shouldn't generate a GeneratorsNeeded error in _tsolve when the NaN is generated
# for eq_down. Actual answers, as determined numerically are approx. +/- 0.83
raises(NotImplementedError, lambda:
solve(sinh(x)*sinh(sinh(x)) + cosh(x)*cosh(sinh(x)) - 3))
# watch out for recursive loop in tsolve
raises(NotImplementedError, lambda: solve((x + 2)**y*x - 3, x))
# issue 7245
assert solve(sin(sqrt(x))) == [0, pi**2]
# issue 7602
a, b = symbols('a, b', real=True, negative=False)
assert str(solve(Eq(a, 0.5 - cos(pi*b)/2), b)) == \
'[2.0 - 0.318309886183791*acos(1.0 - 2.0*a), 0.318309886183791*acos(1.0 - 2.0*a)]'
# issue 15325
assert solve(y**(1/x) - z, x) == [log(y)/log(z)]
def test_solve_for_functions_derivatives():
t = Symbol('t')
x = Function('x')(t)
y = Function('y')(t)
a11, a12, a21, a22, b1, b2 = symbols('a11,a12,a21,a22,b1,b2')
soln = solve([a11*x + a12*y - b1, a21*x + a22*y - b2], x, y)
assert soln == {
x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21),
y: (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
}
assert solve(x - 1, x) == [1]
assert solve(3*x - 2, x) == [Rational(2, 3)]
soln = solve([a11*x.diff(t) + a12*y.diff(t) - b1, a21*x.diff(t) +
a22*y.diff(t) - b2], x.diff(t), y.diff(t))
assert soln == { y.diff(t): (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
x.diff(t): (a22*b1 - a12*b2)/(a11*a22 - a12*a21) }
assert solve(x.diff(t) - 1, x.diff(t)) == [1]
assert solve(3*x.diff(t) - 2, x.diff(t)) == [Rational(2, 3)]
eqns = {3*x - 1, 2*y - 4}
assert solve(eqns, {x, y}) == { x: Rational(1, 3), y: 2 }
x = Symbol('x')
f = Function('f')
F = x**2 + f(x)**2 - 4*x - 1
assert solve(F.diff(x), diff(f(x), x)) == [(-x + 2)/f(x)]
# Mixed cased with a Symbol and a Function
x = Symbol('x')
y = Function('y')(t)
soln = solve([a11*x + a12*y.diff(t) - b1, a21*x +
a22*y.diff(t) - b2], x, y.diff(t))
assert soln == { y.diff(t): (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21) }
# issue 13263
x = Symbol('x')
f = Function('f')
soln = solve([f(x).diff(x) + f(x).diff(x, 2) - 1, f(x).diff(x) - f(x).diff(x, 2)],
f(x).diff(x), f(x).diff(x, 2))
assert soln == { f(x).diff(x, 2): S(1)/2, f(x).diff(x): S(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}
# multivariate
X, Y, Z = y, x**y, y*x**y
eq = a*X + b*Y + c*Z - X - 2*Y - 3*Z
coeffs = a, b, c
syms = x, y
assert solve_undetermined_coeffs(eq, coeffs) == {
a: 1, b: 2, c: 3}
assert solve_undetermined_coeffs(eq, coeffs, syms) == {
a: 1, b: 2, c: 3}
assert solve_undetermined_coeffs(eq, coeffs, *syms) == {
a: 1, b: 2, c: 3}
# check output format
assert solve_undetermined_coeffs(a*x + a - 2, [a]) == []
assert solve_undetermined_coeffs(a**2*x - 4*x, [a]) == [
{a: -2}, {a: 2}]
assert solve_undetermined_coeffs(0, [a]) == []
assert solve_undetermined_coeffs(0, [a], dict=True) == []
assert solve_undetermined_coeffs(0, [a], set=True) == ([], {})
assert solve_undetermined_coeffs(1, [a]) == []
abeq = a*x - 2*x + b - 3
s = {b, a}
assert solve_undetermined_coeffs(abeq, s, x) == {a: 2, b: 3}
assert solve_undetermined_coeffs(abeq, s, x, set=True) == ([a, b], {(2, 3)})
assert solve_undetermined_coeffs(sin(a*x) - sin(2*x), (a,)) is None
assert solve_undetermined_coeffs(a*x + b*x - 2*x, (a, b)) == {a: 2 - b}
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), 2 - y**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 _make_example_24609():
D, R, H, B_g, V, D_c = symbols("D, R, H, B_g, V, D_c", real=True, positive=True)
Sigma_f, Sigma_a, nu = symbols("Sigma_f, Sigma_a, nu", real=True, positive=True)
x = symbols("x", real=True, positive=True)
eq = (
2**(S(2)/3)*pi**(S(2)/3)*D_c*(S(231361)/10000 + pi**2/x**2)
/(6*V**(S(2)/3)*x**(S(1)/3))
- 2**(S(2)/3)*pi**(S(8)/3)*D_c/(2*V**(S(2)/3)*x**(S(7)/3))
)
expected = 100*sqrt(2)*pi/481
return eq, expected, x
def test_issue_24609():
# https://github.com/sympy/sympy/issues/24609
eq, expected, x = _make_example_24609()
assert solve(eq, x, simplify=True) == [expected]
[solapprox] = solve(eq.n(), x)
assert abs(solapprox - expected.n()) < 1e-14
@XFAIL
def test_issue_24609_xfail():
#
# This returns 5 solutions when it should be 1 (with x positive).
# Simplification reveals all solutions to be equivalent. It is expected
# that solve without simplify=True returns duplicate solutions in some
# cases but the core of this equation is a simple quadratic that can easily
# be solved without introducing any redundant solutions:
#
# >>> print(factor_terms(eq.as_numer_denom()[0]))
# 2**(2/3)*pi**(2/3)*D_c*V**(2/3)*x**(7/3)*(231361*x**2 - 20000*pi**2)
#
eq, expected, x = _make_example_24609()
assert len(solve(eq, x)) == [expected]
#
# We do not want to pass this test just by using simplify so if the above
# passes then uncomment the additional test below:
#
# assert len(solve(eq, x, simplify=False)) == 1
def test_polysys():
assert set(solve([x**2 + 2/y - 2, x + y - 3], [x, y])) == \
{(S.One, S(2)), (1 + sqrt(5), 2 - sqrt(5)),
(1 - sqrt(5), 2 + sqrt(5))}
assert solve([x**2 + y - 2, x**2 + y]) == []
# the ordering should be whatever the user requested
assert solve([x**2 + y - 3, x - y - 4], (x, y)) != solve([x**2 +
y - 3, x - y - 4], (y, x))
@slow
def test_unrad1():
raises(NotImplementedError, lambda:
unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) + 3))
raises(NotImplementedError, lambda:
unrad(sqrt(x) + (x + 1)**Rational(1, 3) + 2*sqrt(y)))
s = symbols('s', cls=Dummy)
# checkers to deal with possibility of answer coming
# back with a sign change (cf issue 5203)
def check(rv, ans):
assert bool(rv[1]) == bool(ans[1])
if ans[1]:
return s_check(rv, ans)
e = rv[0].expand()
a = ans[0].expand()
return e in [a, -a] and rv[1] == ans[1]
def s_check(rv, ans):
# get the dummy
rv = list(rv)
d = rv[0].atoms(Dummy)
reps = list(zip(d, [s]*len(d)))
# replace s with this dummy
rv = (rv[0].subs(reps).expand(), [rv[1][0].subs(reps), rv[1][1].subs(reps)])
ans = (ans[0].subs(reps).expand(), [ans[1][0].subs(reps), ans[1][1].subs(reps)])
return str(rv[0]) in [str(ans[0]), str(-ans[0])] and \
str(rv[1]) == str(ans[1])
assert unrad(1) is None
assert check(unrad(sqrt(x)),
(x, []))
assert check(unrad(sqrt(x) + 1),
(x - 1, []))
assert check(unrad(sqrt(x) + root(x, 3) + 2),
(s**3 + s**2 + 2, [s, s**6 - x]))
assert check(unrad(sqrt(x)*root(x, 3) + 2),
(x**5 - 64, []))
assert check(unrad(sqrt(x) + (x + 1)**Rational(1, 3)),
(x**3 - (x + 1)**2, []))
assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(2*x)),
(-2*sqrt(2)*x - 2*x + 1, []))
assert check(unrad(sqrt(x) + sqrt(x + 1) + 2),
(16*x - 9, []))
assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - x)),
(5*x**2 - 4*x, []))
assert check(unrad(a*sqrt(x) + b*sqrt(x) + c*sqrt(y) + d*sqrt(y)),
((a*sqrt(x) + b*sqrt(x))**2 - (c*sqrt(y) + d*sqrt(y))**2, []))
assert check(unrad(sqrt(x) + sqrt(1 - x)),
(2*x - 1, []))
assert check(unrad(sqrt(x) + sqrt(1 - x) - 3),
(x**2 - x + 16, []))
assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x)),
(5*x**2 - 2*x + 1, []))
assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - 3) in [
(25*x**4 + 376*x**3 + 1256*x**2 - 2272*x + 784, []),
(25*x**8 - 476*x**6 + 2534*x**4 - 1468*x**2 + 169, [])]
assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - sqrt(1 - 2*x)) == \
(41*x**4 + 40*x**3 + 232*x**2 - 160*x + 16, []) # orig root at 0.487
assert check(unrad(sqrt(x) + sqrt(x + 1)), (S.One, []))
eq = sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x))
assert check(unrad(eq),
(16*x**2 - 9*x, []))
assert set(solve(eq, check=False)) == {S.Zero, Rational(9, 16)}
assert solve(eq) == []
# but this one really does have those solutions
assert set(solve(sqrt(x) - sqrt(x + 1) + sqrt(1 - sqrt(x)))) == \
{S.Zero, Rational(9, 16)}
assert check(unrad(sqrt(x) + root(x + 1, 3) + 2*sqrt(y), y),
(S('2*sqrt(x)*(x + 1)**(1/3) + x - 4*y + (x + 1)**(2/3)'), []))
assert check(unrad(sqrt(x/(1 - x)) + (x + 1)**Rational(1, 3)),
(x**5 - x**4 - x**3 + 2*x**2 + x - 1, []))
assert check(unrad(sqrt(x/(1 - x)) + 2*sqrt(y), y),
(4*x*y + x - 4*y, []))
assert check(unrad(sqrt(x)*sqrt(1 - x) + 2, x),
(x**2 - x + 4, []))
# http://tutorial.math.lamar.edu/
# Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a
assert solve(Eq(x, sqrt(x + 6))) == [3]
assert solve(Eq(x + sqrt(x - 4), 4)) == [4]
assert solve(Eq(1, x + sqrt(2*x - 3))) == []
assert set(solve(Eq(sqrt(5*x + 6) - 2, x))) == {-S.One, S(2)}
assert set(solve(Eq(sqrt(2*x - 1) - sqrt(x - 4), 2))) == {S(5), S(13)}
assert solve(Eq(sqrt(x + 7) + 2, sqrt(3 - x))) == [-6]
# http://www.purplemath.com/modules/solverad.htm
assert solve((2*x - 5)**Rational(1, 3) - 3) == [16]
assert set(solve(x + 1 - root(x**4 + 4*x**3 - x, 4))) == \
{Rational(-1, 2), Rational(-1, 3)}
assert set(solve(sqrt(2*x**2 - 7) - (3 - x))) == {-S(8), S(2)}
assert solve(sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4)) == [0]
assert solve(sqrt(x + 4) + sqrt(2*x - 1) - 3*sqrt(x - 1)) == [5]
assert solve(sqrt(x)*sqrt(x - 7) - 12) == [16]
assert solve(sqrt(x - 3) + sqrt(x) - 3) == [4]
assert solve(sqrt(9*x**2 + 4) - (3*x + 2)) == [0]
assert solve(sqrt(x) - 2 - 5) == [49]
assert solve(sqrt(x - 3) - sqrt(x) - 3) == []
assert solve(sqrt(x - 1) - x + 7) == [10]
assert solve(sqrt(x - 2) - 5) == [27]
assert solve(sqrt(17*x - sqrt(x**2 - 5)) - 7) == [3]
assert solve(sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x))) == []
# don't posify the expression in unrad and do use _mexpand
z = sqrt(2*x + 1)/sqrt(x) - sqrt(2 + 1/x)
p = posify(z)[0]
assert solve(p) == []
assert solve(z) == []
assert solve(z + 6*I) == [Rational(-1, 11)]
assert solve(p + 6*I) == []
# issue 8622
assert unrad(root(x + 1, 5) - root(x, 3)) == (
-(x**5 - x**3 - 3*x**2 - 3*x - 1), [])
# issue #8679
assert check(unrad(x + root(x, 3) + root(x, 3)**2 + sqrt(y), x),
(s**3 + s**2 + s + sqrt(y), [s, s**3 - x]))
# for coverage
assert check(unrad(sqrt(x) + root(x, 3) + y),
(s**3 + s**2 + y, [s, s**6 - x]))
assert solve(sqrt(x) + root(x, 3) - 2) == [1]
raises(NotImplementedError, lambda:
solve(sqrt(x) + root(x, 3) + root(x + 1, 5) - 2))
# fails through a different code path
raises(NotImplementedError, lambda: solve(-sqrt(2) + cosh(x)/x))
# unrad some
assert solve(sqrt(x + root(x, 3))+root(x - y, 5), y) == [
x + (x**Rational(1, 3) + x)**Rational(5, 2)]
assert check(unrad(sqrt(x) - root(x + 1, 3)*sqrt(x + 2) + 2),
(s**10 + 8*s**8 + 24*s**6 - 12*s**5 - 22*s**4 - 160*s**3 - 212*s**2 -
192*s - 56, [s, s**2 - x]))
e = root(x + 1, 3) + root(x, 3)
assert unrad(e) == (2*x + 1, [])
eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5)
assert check(unrad(eq),
(15625*x**4 + 173000*x**3 + 355600*x**2 - 817920*x + 331776, []))
assert check(unrad(root(x, 4) + root(x, 4)**3 - 1),
(s**3 + s - 1, [s, s**4 - x]))
assert check(unrad(root(x, 2) + root(x, 2)**3 - 1),
(x**3 + 2*x**2 + x - 1, []))
assert unrad(x**0.5) is None
assert check(unrad(t + root(x + y, 5) + root(x + y, 5)**3),
(s**3 + s + t, [s, s**5 - x - y]))
assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, y),
(s**3 + s + x, [s, s**5 - x - y]))
assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, x),
(s**5 + s**3 + s - y, [s, s**5 - x - y]))
assert check(unrad(root(x - 1, 3) + root(x + 1, 5) + root(2, 5)),
(s**5 + 5*2**Rational(1, 5)*s**4 + s**3 + 10*2**Rational(2, 5)*s**3 +
10*2**Rational(3, 5)*s**2 + 5*2**Rational(4, 5)*s + 4, [s, s**3 - x + 1]))
raises(NotImplementedError, lambda:
unrad((root(x, 2) + root(x, 3) + root(x, 4)).subs(x, x**5 - x + 1)))
# the simplify flag should be reset to False for unrad results;
# if it's not then this next test will take a long time
assert solve(root(x, 3) + root(x, 5) - 2) == [1]
eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5)
assert check(unrad(eq),
((5*x - 4)*(3125*x**3 + 37100*x**2 + 100800*x - 82944), []))
ans = S('''
[4/5, -1484/375 + 172564/(140625*(114*sqrt(12657)/78125 +
12459439/52734375)**(1/3)) +
4*(114*sqrt(12657)/78125 + 12459439/52734375)**(1/3)]''')
assert solve(eq) == ans
# duplicate radical handling
assert check(unrad(sqrt(x + root(x + 1, 3)) - root(x + 1, 3) - 2),
(s**3 - s**2 - 3*s - 5, [s, s**3 - x - 1]))
# cov post-processing
e = root(x**2 + 1, 3) - root(x**2 - 1, 5) - 2
assert check(unrad(e),
(s**5 - 10*s**4 + 39*s**3 - 80*s**2 + 80*s - 30,
[s, s**3 - x**2 - 1]))
e = sqrt(x + root(x + 1, 2)) - root(x + 1, 3) - 2
assert check(unrad(e),
(s**6 - 2*s**5 - 7*s**4 - 3*s**3 + 26*s**2 + 40*s + 25,
[s, s**3 - x - 1]))
assert check(unrad(e, _reverse=True),
(s**6 - 14*s**5 + 73*s**4 - 187*s**3 + 276*s**2 - 228*s + 89,
[s, s**2 - x - sqrt(x + 1)]))
# this one needs r0, r1 reversal to work
assert check(unrad(sqrt(x + sqrt(root(x, 3) - 1)) - root(x, 6) - 2),
(s**12 - 2*s**8 - 8*s**7 - 8*s**6 + s**4 + 8*s**3 + 23*s**2 +
32*s + 17, [s, s**6 - x]))
# why does this pass
assert unrad(root(cosh(x), 3)/x*root(x + 1, 5) - 1) == (
-(x**15 - x**3*cosh(x)**5 - 3*x**2*cosh(x)**5 - 3*x*cosh(x)**5
- cosh(x)**5), [])
# and this fail?
#assert unrad(sqrt(cosh(x)/x) + root(x + 1, 3)*sqrt(x) - 1) == (
# -s**6 + 6*s**5 - 15*s**4 + 20*s**3 - 15*s**2 + 6*s + x**5 +
# 2*x**4 + x**3 - 1, [s, s**2 - cosh(x)/x])
# watch for symbols in exponents
assert unrad(S('(x+y)**(2*y/3) + (x+y)**(1/3) + 1')) is None
assert check(unrad(S('(x+y)**(2*y/3) + (x+y)**(1/3) + 1'), x),
(s**(2*y) + s + 1, [s, s**3 - x - y]))
# should _Q be so lenient?
assert unrad(x**(S.Half/y) + y, x) == (x**(1/y) - y**2, [])
# This tests two things: that if full unrad is attempted and fails
# the solution should still be found; also it tests that the use of
# composite
assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3
assert len(solve(-512*y**3 + 1344*(x + 2)**Rational(1, 3)*y**2 -
1176*(x + 2)**Rational(2, 3)*y - 169*x + 686, y, _unrad=False)) == 3
# watch out for when the cov doesn't involve the symbol of interest
eq = S('-x + (7*y/8 - (27*x/2 + 27*sqrt(x**2)/2)**(1/3)/3)**3 - 1')
assert solve(eq, y) == [
2**(S(2)/3)*(27*x + 27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 +
S(512)/343)**(S(1)/3)*(-S(1)/2 - sqrt(3)*I/2), 2**(S(2)/3)*(27*x +
27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 +
S(512)/343)**(S(1)/3)*(-S(1)/2 + sqrt(3)*I/2), 2**(S(2)/3)*(27*x +
27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 + S(512)/343)**(S(1)/3)]
eq = root(x + 1, 3) - (root(x, 3) + root(x, 5))
assert check(unrad(eq),
(3*s**13 + 3*s**11 + s**9 - 1, [s, s**15 - x]))
assert check(unrad(eq - 2),
(3*s**13 + 3*s**11 + 6*s**10 + s**9 + 12*s**8 + 6*s**6 + 12*s**5 +
12*s**3 + 7, [s, s**15 - x]))
assert check(unrad(root(x, 3) - root(x + 1, 4)/2 + root(x + 2, 3)),
(s*(4096*s**9 + 960*s**8 + 48*s**7 - s**6 - 1728),
[s, s**4 - x - 1])) # orig expr has two real roots: -1, -.389
assert check(unrad(root(x, 3) + root(x + 1, 4) - root(x + 2, 3)/2),
(343*s**13 + 2904*s**12 + 1344*s**11 + 512*s**10 - 1323*s**9 -
3024*s**8 - 1728*s**7 + 1701*s**5 + 216*s**4 - 729*s, [s, s**4 - x -
1])) # orig expr has one real root: -0.048
assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3)),
(729*s**13 - 216*s**12 + 1728*s**11 - 512*s**10 + 1701*s**9 -
3024*s**8 + 1344*s**7 + 1323*s**5 - 2904*s**4 + 343*s, [s, s**4 - x -
1])) # orig expr has 2 real roots: -0.91, -0.15
assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3) - 2),
(729*s**13 + 1242*s**12 + 18496*s**10 + 129701*s**9 + 388602*s**8 +
453312*s**7 - 612864*s**6 - 3337173*s**5 - 6332418*s**4 - 7134912*s**3
- 5064768*s**2 - 2111913*s - 398034, [s, s**4 - x - 1]))
# orig expr has 1 real root: 19.53
ans = solve(sqrt(x) + sqrt(x + 1) -
sqrt(1 - x) - sqrt(2 + x))
assert len(ans) == 1 and NS(ans[0])[:4] == '0.73'
# the fence optimization problem
# https://github.com/sympy/sympy/issues/4793#issuecomment-36994519
F = Symbol('F')
eq = F - (2*x + 2*y + sqrt(x**2 + y**2))
ans = F*Rational(2, 7) - sqrt(2)*F/14
X = solve(eq, x, check=False)
for xi in reversed(X): # reverse since currently, ans is the 2nd one
Y = solve((x*y).subs(x, xi).diff(y), y, simplify=False, check=False)
if any((a - ans).expand().is_zero for a in Y):
break
else:
assert None # no answer was found
assert solve(sqrt(x + 1) + root(x, 3) - 2) == S('''
[(-11/(9*(47/54 + sqrt(93)/6)**(1/3)) + 1/3 + (47/54 +
sqrt(93)/6)**(1/3))**3]''')
assert solve(sqrt(sqrt(x + 1)) + x**Rational(1, 3) - 2) == S('''
[(-sqrt(-2*(-1/16 + sqrt(6913)/16)**(1/3) + 6/(-1/16 +
sqrt(6913)/16)**(1/3) + 17/2 + 121/(4*sqrt(-6/(-1/16 +
sqrt(6913)/16)**(1/3) + 2*(-1/16 + sqrt(6913)/16)**(1/3) + 17/4)))/2 +
sqrt(-6/(-1/16 + sqrt(6913)/16)**(1/3) + 2*(-1/16 +
sqrt(6913)/16)**(1/3) + 17/4)/2 + 9/4)**3]''')
assert solve(sqrt(x) + root(sqrt(x) + 1, 3) - 2) == S('''
[(-(81/2 + 3*sqrt(741)/2)**(1/3)/3 + (81/2 + 3*sqrt(741)/2)**(-1/3) +
2)**2]''')
eq = S('''
-x + (1/2 - sqrt(3)*I/2)*(3*x**3/2 - x*(3*x**2 - 34)/2 + sqrt((-3*x**3
+ x*(3*x**2 - 34) + 90)**2/4 - 39304/27) - 45)**(1/3) + 34/(3*(1/2 -
sqrt(3)*I/2)*(3*x**3/2 - x*(3*x**2 - 34)/2 + sqrt((-3*x**3 + x*(3*x**2
- 34) + 90)**2/4 - 39304/27) - 45)**(1/3))''')
assert check(unrad(eq),
(s*-(-s**6 + sqrt(3)*s**6*I - 153*2**Rational(2, 3)*3**Rational(1, 3)*s**4 +
51*12**Rational(1, 3)*s**4 - 102*2**Rational(2, 3)*3**Rational(5, 6)*s**4*I - 1620*s**3 +
1620*sqrt(3)*s**3*I + 13872*18**Rational(1, 3)*s**2 - 471648 +
471648*sqrt(3)*I), [s, s**3 - 306*x - sqrt(3)*sqrt(31212*x**2 -
165240*x + 61484) + 810]))
assert solve(eq) == [] # not other code errors
eq = root(x, 3) - root(y, 3) + root(x, 5)
assert check(unrad(eq),
(s**15 + 3*s**13 + 3*s**11 + s**9 - y, [s, s**15 - x]))
eq = root(x, 3) + root(y, 3) + root(x*y, 4)
assert check(unrad(eq),
(s*y*(-s**12 - 3*s**11*y - 3*s**10*y**2 - s**9*y**3 -
3*s**8*y**2 + 21*s**7*y**3 - 3*s**6*y**4 - 3*s**4*y**4 -
3*s**3*y**5 - y**6), [s, s**4 - x*y]))
raises(NotImplementedError,
lambda: unrad(root(x, 3) + root(y, 3) + root(x*y, 5)))
# Test unrad with an Equality
eq = Eq(-x**(S(1)/5) + x**(S(1)/3), -3**(S(1)/3) - (-1)**(S(3)/5)*3**(S(1)/5))
assert check(unrad(eq),
(-s**5 + s**3 - 3**(S(1)/3) - (-1)**(S(3)/5)*3**(S(1)/5), [s, s**15 - x]))
# make sure buried radicals are exposed
s = sqrt(x) - 1
assert unrad(s**2 - s**3) == (x**3 - 6*x**2 + 9*x - 4, [])
# make sure numerators which are already polynomial are rejected
assert unrad((x/(x + 1) + 3)**(-2), x) is None
# https://github.com/sympy/sympy/issues/23707
eq = sqrt(x - y)*exp(t*sqrt(x - y)) - exp(t*sqrt(x - y))
assert solve(eq, y) == [x - 1]
assert unrad(eq) is None
@slow
def test_unrad_slow():
# this has roots with multiplicity > 1; there should be no
# repeats in roots obtained, however
eq = (sqrt(1 + sqrt(1 - 4*x**2)) - x*(1 + sqrt(1 + 2*sqrt(1 - 4*x**2))))
assert solve(eq) == [S.Half]
@XFAIL
def test_unrad_fail():
# this only works if we check real_root(eq.subs(x, Rational(1, 3)))
# but checksol doesn't work like that
assert solve(root(x**3 - 3*x**2, 3) + 1 - x) == [Rational(1, 3)]
assert solve(root(x + 1, 3) + root(x**2 - 2, 5) + 1) == [
-1, -1 + CRootOf(x**5 + x**4 + 5*x**3 + 8*x**2 + 10*x + 5, 0)**3]
def test_checksol():
x, y, r, t = symbols('x, y, r, t')
eq = r - x**2 - y**2
dict_var_soln = {y: - sqrt(r) / sqrt(tan(t)**2 + 1),
x: -sqrt(r)*tan(t)/sqrt(tan(t)**2 + 1)}
assert checksol(eq, dict_var_soln) == True
assert checksol(Eq(x, False), {x: False}) is True
assert checksol(Ne(x, False), {x: False}) is False
assert checksol(Eq(x < 1, True), {x: 0}) is True
assert checksol(Eq(x < 1, True), {x: 1}) is False
assert checksol(Eq(x < 1, False), {x: 1}) is True
assert checksol(Eq(x < 1, False), {x: 0}) is False
assert checksol(Eq(x + 1, x**2 + 1), {x: 1}) is True
assert checksol([x - 1, x**2 - 1], x, 1) is True
assert checksol([x - 1, x**2 - 2], x, 1) is False
assert checksol(Poly(x**2 - 1), x, 1) is True
assert checksol(0, {}) is True
assert checksol([1e-10, x - 2], x, 2) is False
assert checksol([0.5, 0, x], x, 0) is False
assert checksol(y, x, 2) is False
assert checksol(x+1e-10, x, 0, numerical=True) is True
assert checksol(x+1e-10, x, 0, numerical=False) is False
assert checksol(exp(92*x), {x: log(sqrt(2)/2)}) is False
assert checksol(exp(92*x), {x: log(sqrt(2)/2) + I*pi}) is False
assert checksol(1/x**5, x, 1000) is False
raises(ValueError, lambda: checksol(x, 1))
raises(ValueError, lambda: checksol([], x, 1))
def test__invert():
assert _invert(x - 2) == (2, x)
assert _invert(2) == (2, 0)
assert _invert(exp(1/x) - 3, x) == (1/log(3), x)
assert _invert(exp(1/x + a/x) - 3, x) == ((a + 1)/log(3), x)
assert _invert(a, x) == (a, 0)
def test_issue_4463():
assert solve(-a*x + 2*x*log(x), x) == [exp(a/2)]
assert solve(x**x) == []
assert solve(x**x - 2) == [exp(LambertW(log(2)))]
assert solve(((x - 3)*(x - 2))**((x - 3)*(x - 4))) == [2]
@slow
def test_issue_5114_solvers():
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('a:r')
# there is no 'a' in the equation set but this is how the
# problem was originally posed
syms = a, b, c, f, h, k, n
eqs = [b + r/d - c/d,
c*(1/d + 1/e + 1/g) - f/g - r/d,
f*(1/g + 1/i + 1/j) - c/g - h/i,
h*(1/i + 1/l + 1/m) - f/i - k/m,
k*(1/m + 1/o + 1/p) - h/m - n/p,
n*(1/p + 1/q) - k/p]
assert len(solve(eqs, syms, manual=True, check=False, simplify=False)) == 1
def test_issue_5849():
#
# XXX: This system does not have a solution for most values of the
# parameters. Generally solve returns the empty set for systems that are
# generically inconsistent.
#
I1, I2, I3, I4, I5, I6 = symbols('I1:7')
dI1, dI4, dQ2, dQ4, Q2, Q4 = symbols('dI1,dI4,dQ2,dQ4,Q2,Q4')
e = (
I1 - I2 - I3,
I3 - I4 - I5,
I4 + I5 - I6,
-I1 + I2 + I6,
-2*I1 - 2*I3 - 2*I5 - 3*I6 - dI1/2 + 12,
-I4 + dQ4,
-I2 + dQ2,
2*I3 + 2*I5 + 3*I6 - Q2,
I4 - 2*I5 + 2*Q4 + dI4
)
ans = [{
I1: I2 + I3,
dI1: -4*I2 - 8*I3 - 4*I5 - 6*I6 + 24,
I4: I3 - I5,
dQ4: I3 - I5,
Q4: -I3/2 + 3*I5/2 - dI4/2,
dQ2: I2,
Q2: 2*I3 + 2*I5 + 3*I6}]
v = I1, I4, Q2, Q4, dI1, dI4, dQ2, dQ4
assert solve(e, *v, manual=True, check=False, dict=True) == ans
assert solve(e, *v, manual=True, check=False) == [
tuple([a.get(i, i) for i in v]) for a in ans]
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}]
# but not {a: 0, f: 0, b: 0, k: S(3)/2, c: 0, d: 0, g: 0}
# since this is already covered by the first solution
got = solve(equations, unknowns, dict=True)
assert got == answer, (got,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) == \
[(3*D, 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) == \
([h(a), g(a)], {
(-sqrt(f(a)**2*g(a)**2 - G)/f(a), g(a)),
(sqrt(f(a)**2*g(a)**2 - G)/f(a), g(a))}), solve(-f(a)**2*g(a)**2 + f(a)**2*h(a)**2 + g(a).diff(a),
h(a), g(a), set=True)
args = [[f(x).diff(x, 2)*(f(x) + g(x)), 2 - g(x)**2], f(x), g(x)]
assert solve(*args, set=True)[1] == \
{(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))}
eqs = [f(x)**2 + g(x) - 2*f(x).diff(x), g(x)**2 - 4]
assert solve(eqs, f(x), g(x), set=True) == \
([f(x), g(x)], {
(-sqrt(2*D - 2), S(2)),
(sqrt(2*D - 2), S(2)),
(-sqrt(2*D + 2), -S(2)),
(sqrt(2*D + 2), -S(2))})
# the underlying problem was in solve_linear that was not masking off
# anything but a Mul or Add; it now raises an error if it gets anything
# but a symbol and solve handles the substitutions necessary so solve_linear
# won't make this error
raises(
ValueError, lambda: solve_linear(f(x) + f(x).diff(x), symbols=[f(x)]))
assert solve_linear(f(x) + f(x).diff(x), symbols=[x]) == \
(f(x) + Derivative(f(x), x), 1)
assert solve_linear(f(x) + Integral(x, (x, y)), symbols=[x]) == \
(f(x) + Integral(x, (x, y)), 1)
assert solve_linear(f(x) + Integral(x, (x, y)) + x, symbols=[x]) == \
(x + f(x) + Integral(x, (x, y)), 1)
assert solve_linear(f(y) + Integral(x, (x, y)) + x, symbols=[x]) == \
(x, -f(y) - Integral(x, (x, y)))
assert solve_linear(x - f(x)/a + (f(x) - 1)/a, symbols=[x]) == \
(x, 1/a)
assert solve_linear(x + Derivative(2*x, x)) == \
(x, -2)
assert solve_linear(x + Integral(x, y), symbols=[x]) == \
(x, 0)
assert solve_linear(x + Integral(x, y) - 2, symbols=[x]) == \
(x, 2/(y + 1))
assert set(solve(x + exp(x)**2, exp(x))) == \
{-sqrt(-x), sqrt(-x)}
assert solve(x + exp(x), x, implicit=True) == \
[-exp(x)]
assert solve(cos(x) - sin(x), x, implicit=True) == []
assert solve(x - sin(x), x, implicit=True) == \
[sin(x)]
assert solve(x**2 + x - 3, x, implicit=True) == \
[-x**2 + 3]
assert solve(x**2 + x - 3, x**2, implicit=True) == \
[-x + 3]
def test_issue_5912():
assert set(solve(x**2 - x - 0.1, rational=True)) == \
{S.Half + sqrt(35)/10, -sqrt(35)/10 + S.Half}
ans = solve(x**2 - x - 0.1, rational=False)
assert len(ans) == 2 and all(a.is_Number for a in ans)
ans = solve(x**2 - x - 0.1)
assert len(ans) == 2 and all(a.is_Number for a in ans)
def test_float_handling():
def test(e1, e2):
return len(e1.atoms(Float)) == len(e2.atoms(Float))
assert solve(x - 0.5, rational=True)[0].is_Rational
assert solve(x - 0.5, rational=False)[0].is_Float
assert solve(x - S.Half, rational=False)[0].is_Rational
assert solve(x - 0.5, rational=None)[0].is_Float
assert solve(x - S.Half, rational=None)[0].is_Rational
assert test(nfloat(1 + 2*x), 1.0 + 2.0*x)
for contain in [list, tuple, set]:
ans = nfloat(contain([1 + 2*x]))
assert type(ans) is contain and test(list(ans)[0], 1.0 + 2.0*x)
k, v = list(nfloat({2*x: [1 + 2*x]}).items())[0]
assert test(k, 2*x) and test(v[0], 1.0 + 2.0*x)
assert test(nfloat(cos(2*x)), cos(2.0*x))
assert test(nfloat(3*x**2), 3.0*x**2)
assert test(nfloat(3*x**2, exponent=True), 3.0*x**2.0)
assert test(nfloat(exp(2*x)), exp(2.0*x))
assert test(nfloat(x/3), x/3.0)
assert test(nfloat(x**4 + 2*x + cos(Rational(1, 3)) + 1),
x**4 + 2.0*x + 1.94495694631474)
# don't call nfloat if there is no solution
tot = 100 + c + z + t
assert solve(((.7 + c)/tot - .6, (.2 + z)/tot - .3, t/tot - .1)) == []
def test_check_assumptions():
x = symbols('x', positive=True)
assert solve(x**2 - 1) == [1]
def test_issue_6056():
assert solve(tanh(x + 3)*tanh(x - 3) - 1) == []
assert solve(tanh(x - 1)*tanh(x + 1) + 1) == \
[I*pi*Rational(-3, 4), -I*pi/4, I*pi/4, I*pi*Rational(3, 4)]
assert solve((tanh(x + 3)*tanh(x - 3) + 1)**2) == \
[I*pi*Rational(-3, 4), -I*pi/4, I*pi/4, I*pi*Rational(3, 4)]
def test_issue_5673():
eq = -x + exp(exp(LambertW(log(x)))*LambertW(log(x)))
assert checksol(eq, x, 2) is True
assert checksol(eq, x, 2, numerical=False) is None
def test_exclude():
R, C, Ri, Vout, V1, Vminus, Vplus, s = \
symbols('R, C, Ri, Vout, V1, Vminus, Vplus, s')
Rf = symbols('Rf', positive=True) # to eliminate Rf = 0 soln
eqs = [C*V1*s + Vplus*(-2*C*s - 1/R),
Vminus*(-1/Ri - 1/Rf) + Vout/Rf,
C*Vplus*s + V1*(-C*s - 1/R) + Vout/R,
-Vminus + Vplus]
assert solve(eqs, exclude=s*C*R) == [
{
Rf: Ri*(C*R*s + 1)**2/(C*R*s),
Vminus: Vplus,
V1: 2*Vplus + Vplus/(C*R*s),
Vout: C*R*Vplus*s + 3*Vplus + Vplus/(C*R*s)},
{
Vplus: 0,
Vminus: 0,
V1: 0,
Vout: 0},
]
# TODO: Investigate why currently solution [0] is preferred over [1].
assert solve(eqs, exclude=[Vplus, s, C]) in [[{
Vminus: Vplus,
V1: Vout/2 + Vplus/2 + sqrt((Vout - 5*Vplus)*(Vout - Vplus))/2,
R: (Vout - 3*Vplus - sqrt(Vout**2 - 6*Vout*Vplus + 5*Vplus**2))/(2*C*Vplus*s),
Rf: Ri*(Vout - Vplus)/Vplus,
}, {
Vminus: Vplus,
V1: Vout/2 + Vplus/2 - sqrt((Vout - 5*Vplus)*(Vout - Vplus))/2,
R: (Vout - 3*Vplus + sqrt(Vout**2 - 6*Vout*Vplus + 5*Vplus**2))/(2*C*Vplus*s),
Rf: Ri*(Vout - Vplus)/Vplus,
}], [{
Vminus: Vplus,
Vout: (V1**2 - V1*Vplus - Vplus**2)/(V1 - 2*Vplus),
Rf: Ri*(V1 - Vplus)**2/(Vplus*(V1 - 2*Vplus)),
R: Vplus/(C*s*(V1 - 2*Vplus)),
}]]
def test_high_order_roots():
s = x**5 + 4*x**3 + 3*x**2 + Rational(7, 4)
assert set(solve(s)) == set(Poly(s*4, domain='ZZ').all_roots())
def test_minsolve_linear_system():
pqt = dict(quick=True, particular=True)
pqf = dict(quick=False, particular=True)
assert solve([x + y - 5, 2*x - y - 1], **pqt) == {x: 2, y: 3}
assert solve([x + y - 5, 2*x - y - 1], **pqf) == {x: 2, y: 3}
def count(dic):
return len([x for x in dic.values() if x == 0])
assert count(solve([x + y + z, y + z + a + t], **pqt)) == 3
assert count(solve([x + y + z, y + z + a + t], **pqf)) == 3
assert count(solve([x + y + z, y + z + a], **pqt)) == 1
assert count(solve([x + y + z, y + z + a], **pqf)) == 2
# issue 22718
A = Matrix([
[ 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0],
[ 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, -1, -1, 0, 0],
[-1, -1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 1, 0, 1],
[ 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, -1, 0, -1, 0],
[-1, 0, -1, 0, 0, -1, 0, 0, 0, 0, 1, 0, 1, 1],
[-1, 0, 0, -1, 0, 0, -1, 0, 0, 0, -1, 0, 0, -1],
[ 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, -1, -1, 0],
[ 0, -1, -1, 0, 0, 0, 0, -1, 0, 0, 0, 1, 1, 1],
[ 0, -1, 0, -1, 0, 0, 0, 0, -1, 0, 0, -1, 0, -1],
[ 0, 0, -1, -1, 0, 0, 0, 0, 0, -1, 0, 0, -1, -1],
[ 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
[ 0, 0, 0, 0, -1, -1, 0, -1, 0, 0, 0, 0, 0, 0]])
v = Matrix(symbols("v:14", integer=True))
B = Matrix([[2], [-2], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0]])
eqs = A@v-B
assert solve(eqs) == []
assert solve(eqs, particular=True) == [] # assumption violated
assert all(v for v in solve([x + y + z, y + z + a]).values())
for _q in (True, False):
assert not all(v for v in solve(
[x + y + z, y + z + a], quick=_q,
particular=True).values())
# raise error if quick used w/o particular=True
raises(ValueError, lambda: solve([x + 1], quick=_q))
raises(ValueError, lambda: solve([x + 1], quick=_q, particular=False))
# and give a good error message if someone tries to use
# particular with a single equation
raises(ValueError, lambda: solve(x + 1, particular=True))
def test_real_roots():
# cf. issue 6650
x = Symbol('x', real=True)
assert len(solve(x**5 + x**3 + 1)) == 1
def test_issue_6528():
eqs = [
327600995*x**2 - 37869137*x + 1809975124*y**2 - 9998905626,
895613949*x**2 - 273830224*x*y + 530506983*y**2 - 10000000000]
# two expressions encountered are > 1400 ops long so if this hangs
# it is likely because simplification is being done
assert len(solve(eqs, y, x, check=False)) == 4
def test_overdetermined():
x = symbols('x', real=True)
eqs = [Abs(4*x - 7) - 5, Abs(3 - 8*x) - 1]
assert solve(eqs, x) == [(S.Half,)]
assert solve(eqs, x, manual=True) == [(S.Half,)]
assert solve(eqs, x, manual=True, check=False) == [(S.Half,), (S(3),)]
def test_issue_6605():
x = symbols('x')
assert solve(4**(x/2) - 2**(x/3)) == [0, 3*I*pi/log(2)]
# while the first one passed, this one failed
x = symbols('x', real=True)
assert solve(5**(x/2) - 2**(x/3)) == [0]
b = sqrt(6)*sqrt(log(2))/sqrt(log(5))
assert solve(5**(x/2) - 2**(3/x)) == [-b, b]
def test__ispow():
assert _ispow(x**2)
assert not _ispow(x)
assert not _ispow(True)
def test_issue_6644():
eq = -sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) + sqrt((-m**2/2 - sqrt(
4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt(
4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2)
sol = solve(eq, q, simplify=False, check=False)
assert len(sol) == 5
def test_issue_6752():
assert solve([a**2 + a, a - b], [a, b]) == [(-1, -1), (0, 0)]
assert solve([a**2 + a*c, a - b], [a, b]) == [(0, 0), (-c, -c)]
def test_issue_6792():
assert solve(x*(x - 1)**2*(x + 1)*(x**6 - x + 1)) == [
-1, 0, 1, CRootOf(x**6 - x + 1, 0), CRootOf(x**6 - x + 1, 1),
CRootOf(x**6 - x + 1, 2), CRootOf(x**6 - x + 1, 3),
CRootOf(x**6 - x + 1, 4), CRootOf(x**6 - x + 1, 5)]
def test_issues_6819_6820_6821_6248_8692():
# issue 6821
x, y = symbols('x y', real=True)
assert solve(abs(x + 3) - 2*abs(x - 3)) == [1, 9]
assert solve([abs(x) - 2, arg(x) - pi], x) == [(-2,)]
assert set(solve(abs(x - 7) - 8)) == {-S.One, S(15)}
# issue 8692
assert solve(Eq(Abs(x + 1) + Abs(x**2 - 7), 9), x) == [
Rational(-1, 2) + sqrt(61)/2, -sqrt(69)/2 + S.Half]
# issue 7145
assert solve(2*abs(x) - abs(x - 1)) == [-1, Rational(1, 3)]
x = symbols('x')
assert solve([re(x) - 1, im(x) - 2], x) == [
{re(x): 1, x: 1 + 2*I, im(x): 2}]
# check for 'dict' handling of solution
eq = sqrt(re(x)**2 + im(x)**2) - 3
assert solve(eq) == solve(eq, x)
i = symbols('i', imaginary=True)
assert solve(abs(i) - 3) == [-3*I, 3*I]
raises(NotImplementedError, lambda: solve(abs(x) - 3))
w = symbols('w', integer=True)
assert solve(2*x**w - 4*y**w, w) == solve((x/y)**w - 2, w)
x, y = symbols('x y', real=True)
assert solve(x + y*I + 3) == {y: 0, x: -3}
# issue 2642
assert solve(x*(1 + I)) == [0]
x, y = symbols('x y', imaginary=True)
assert solve(x + y*I + 3 + 2*I) == {x: -2*I, y: 3*I}
x = symbols('x', real=True)
assert solve(x + y + 3 + 2*I) == {x: -3, y: -2*I}
# issue 6248
f = Function('f')
assert solve(f(x + 1) - f(2*x - 1)) == [2]
assert solve(log(x + 1) - log(2*x - 1)) == [2]
x = symbols('x')
assert solve(2**x + 4**x) == [I*pi/log(2)]
def test_issue_17638():
assert solve(((2-exp(2*x))*exp(x))/(exp(2*x)+2)**2 > 0, x) == (-oo < x) & (x < log(2)/2)
assert solve(((2-exp(2*x)+2)*exp(x+2))/(exp(x)+2)**2 > 0, x) == (-oo < x) & (x < log(4)/2)
assert solve((exp(x)+2+x**2)*exp(2*x+2)/(exp(x)+2)**2 > 0, x) == (-oo < x) & (x < oo)
def test_issue_14607():
# issue 14607
s, tau_c, tau_1, tau_2, phi, K = symbols(
's, tau_c, tau_1, tau_2, phi, K')
target = (s**2*tau_1*tau_2 + s*tau_1 + s*tau_2 + 1)/(K*s*(-phi + tau_c))
K_C, tau_I, tau_D = symbols('K_C, tau_I, tau_D',
positive=True, nonzero=True)
PID = K_C*(1 + 1/(tau_I*s) + tau_D*s)
eq = (target - PID).together()
eq *= denom(eq).simplify()
eq = Poly(eq, s)
c = eq.coeffs()
vars = [K_C, tau_I, tau_D]
s = solve(c, vars, dict=True)
assert len(s) == 1
knownsolution = {K_C: -(tau_1 + tau_2)/(K*(phi - tau_c)),
tau_I: tau_1 + tau_2,
tau_D: tau_1*tau_2/(tau_1 + tau_2)}
for var in vars:
assert s[0][var].simplify() == knownsolution[var].simplify()
def test_lambert_multivariate():
from sympy.abc import x, y
assert _filtered_gens(Poly(x + 1/x + exp(x) + y), x) == {x, exp(x)}
assert _lambert(x, x) == []
assert solve((x**2 - 2*x + 1).subs(x, log(x) + 3*x)) == [LambertW(3*S.Exp1)/3]
assert solve((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1)) == \
[LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3]
assert solve((x**2 - 2*x - 2).subs(x, log(x) + 3*x)) == \
[LambertW(3*exp(1 - sqrt(3)))/3, LambertW(3*exp(1 + sqrt(3)))/3]
eq = (x*exp(x) - 3).subs(x, x*exp(x))
assert solve(eq) == [LambertW(3*exp(-LambertW(3)))]
# coverage test
raises(NotImplementedError, lambda: solve(x - sin(x)*log(y - x), x))
ans = [3, -3*LambertW(-log(3)/3)/log(3)] # 3 and 2.478...
assert solve(x**3 - 3**x, x) == ans
assert set(solve(3*log(x) - x*log(3))) == set(ans)
assert solve(LambertW(2*x) - y, x) == [y*exp(y)/2]
@XFAIL
def test_other_lambert():
assert solve(3*sin(x) - x*sin(3), x) == [3]
assert set(solve(x**a - a**x), x) == {
a, -a*LambertW(-log(a)/a)/log(a)}
@slow
def test_lambert_bivariate():
# tests passing current implementation
assert solve((x**2 + x)*exp(x**2 + x) - 1) == [
Rational(-1, 2) + sqrt(1 + 4*LambertW(1))/2,
Rational(-1, 2) - sqrt(1 + 4*LambertW(1))/2]
assert solve((x**2 + x)*exp((x**2 + x)*2) - 1) == [
Rational(-1, 2) + sqrt(1 + 2*LambertW(2))/2,
Rational(-1, 2) - sqrt(1 + 2*LambertW(2))/2]
assert solve(a/x + exp(x/2), x) == [2*LambertW(-a/2)]
assert solve((a/x + exp(x/2)).diff(x), x) == \
[4*LambertW(-sqrt(2)*sqrt(a)/4), 4*LambertW(sqrt(2)*sqrt(a)/4)]
assert solve((1/x + exp(x/2)).diff(x), x) == \
[4*LambertW(-sqrt(2)/4),
4*LambertW(sqrt(2)/4), # nsimplifies as 2*2**(141/299)*3**(206/299)*5**(205/299)*7**(37/299)/21
4*LambertW(-sqrt(2)/4, -1)]
assert solve(x*log(x) + 3*x + 1, x) == \
[exp(-3 + LambertW(-exp(3)))]
assert solve(-x**2 + 2**x, x) == [2, 4, -2*LambertW(log(2)/2)/log(2)]
assert solve(x**2 - 2**x, x) == [2, 4, -2*LambertW(log(2)/2)/log(2)]
ans = solve(3*x + 5 + 2**(-5*x + 3), x)
assert len(ans) == 1 and ans[0].expand() == \
Rational(-5, 3) + LambertW(-10240*root(2, 3)*log(2)/3)/(5*log(2))
assert solve(5*x - 1 + 3*exp(2 - 7*x), x) == \
[Rational(1, 5) + LambertW(-21*exp(Rational(3, 5))/5)/7]
assert solve((log(x) + x).subs(x, x**2 + 1)) == [
-I*sqrt(-LambertW(1) + 1), sqrt(-1 + LambertW(1))]
# check collection
ax = a**(3*x + 5)
ans = solve(3*log(ax) + b*log(ax) + ax, x)
x0 = 1/log(a)
x1 = sqrt(3)*I
x2 = b + 3
x3 = x2*LambertW(1/x2)/a**5
x4 = x3**Rational(1, 3)/2
assert ans == [
x0*log(x4*(-x1 - 1)),
x0*log(x4*(x1 - 1)),
x0*log(x3)/3]
x1 = LambertW(Rational(1, 3))
x2 = a**(-5)
x3 = -3**Rational(1, 3)
x4 = 3**Rational(5, 6)*I
x5 = x1**Rational(1, 3)*x2**Rational(1, 3)/2
ans = solve(3*log(ax) + ax, x)
assert ans == [
x0*log(3*x1*x2)/3,
x0*log(x5*(x3 - x4)),
x0*log(x5*(x3 + x4))]
# coverage
p = symbols('p', positive=True)
eq = 4*2**(2*p + 3) - 2*p - 3
assert _solve_lambert(eq, p, _filtered_gens(Poly(eq), p)) == [
Rational(-3, 2) - LambertW(-4*log(2))/(2*log(2))]
assert set(solve(3**cos(x) - cos(x)**3)) == {
acos(3), acos(-3*LambertW(-log(3)/3)/log(3))}
# should give only one solution after using `uniq`
assert solve(2*log(x) - 2*log(z) + log(z + log(x) + log(z)), x) == [
exp(-z + LambertW(2*z**4*exp(2*z))/2)/z]
# cases when p != S.One
# issue 4271
ans = solve((a/x + exp(x/2)).diff(x, 2), x)
x0 = (-a)**Rational(1, 3)
x1 = sqrt(3)*I
x2 = x0/6
assert ans == [
6*LambertW(x0/3),
6*LambertW(x2*(-x1 - 1)),
6*LambertW(x2*(x1 - 1))]
assert solve((1/x + exp(x/2)).diff(x, 2), x) == \
[6*LambertW(Rational(-1, 3)), 6*LambertW(Rational(1, 6) - sqrt(3)*I/6), \
6*LambertW(Rational(1, 6) + sqrt(3)*I/6), 6*LambertW(Rational(-1, 3), -1)]
assert solve(x**2 - y**2/exp(x), x, y, dict=True) == \
[{x: 2*LambertW(-y/2)}, {x: 2*LambertW(y/2)}]
# this is slow but not exceedingly slow
assert solve((x**3)**(x/2) + pi/2, x) == [
exp(LambertW(-2*log(2)/3 + 2*log(pi)/3 + I*pi*Rational(2, 3)))]
# issue 23253
assert solve((1/log(sqrt(x) + 2)**2 - 1/x)) == [
(LambertW(-exp(-2), -1) + 2)**2]
assert solve((1/log(1/sqrt(x) + 2)**2 - x)) == [
(LambertW(-exp(-2), -1) + 2)**-2]
assert solve((1/log(x**2 + 2)**2 - x**-4)) == [
-I*sqrt(2 - LambertW(exp(2))),
-I*sqrt(LambertW(-exp(-2)) + 2),
sqrt(-2 - LambertW(-exp(-2))),
sqrt(-2 + LambertW(exp(2))),
-sqrt(-2 - LambertW(-exp(-2), -1)),
sqrt(-2 - LambertW(-exp(-2), -1))]
def test_rewrite_trig():
assert solve(sin(x) + tan(x)) == [0, -pi, pi, 2*pi]
assert solve(sin(x) + sec(x)) == [
-2*atan(Rational(-1, 2) + sqrt(2)*sqrt(1 - sqrt(3)*I)/2 + sqrt(3)*I/2),
2*atan(S.Half - sqrt(2)*sqrt(1 + sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half
+ sqrt(2)*sqrt(1 + sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half -
sqrt(3)*I/2 + sqrt(2)*sqrt(1 - sqrt(3)*I)/2)]
assert solve(sinh(x) + tanh(x)) == [0, I*pi]
# issue 6157
assert solve(2*sin(x) - cos(x), x) == [atan(S.Half)]
@XFAIL
def test_rewrite_trigh():
# if this import passes then the test below should also pass
from sympy.functions.elementary.hyperbolic import sech
assert solve(sinh(x) + sech(x)) == [
2*atanh(Rational(-1, 2) + sqrt(5)/2 - sqrt(-2*sqrt(5) + 2)/2),
2*atanh(Rational(-1, 2) + sqrt(5)/2 + sqrt(-2*sqrt(5) + 2)/2),
2*atanh(-sqrt(5)/2 - S.Half + sqrt(2 + 2*sqrt(5))/2),
2*atanh(-sqrt(2 + 2*sqrt(5))/2 - sqrt(5)/2 - S.Half)]
def test_uselogcombine():
eq = z - log(x) + log(y/(x*(-1 + y**2/x**2)))
assert solve(eq, x, force=True) == [-sqrt(y*(y - exp(z))), sqrt(y*(y - exp(z)))]
assert solve(log(x + 3) + log(1 + 3/x) - 3) in [
[-3 + sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 + exp(3)/2,
-sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 - 3 + exp(3)/2],
[-3 + sqrt(-36 + (-exp(3) + 6)**2)/2 + exp(3)/2,
-3 - sqrt(-36 + (-exp(3) + 6)**2)/2 + exp(3)/2],
]
assert solve(log(exp(2*x) + 1) + log(-tanh(x) + 1) - log(2)) == []
def test_atan2():
assert solve(atan2(x, 2) - pi/3, x) == [2*sqrt(3)]
def test_errorinverses():
assert solve(erf(x) - y, x) == [erfinv(y)]
assert solve(erfinv(x) - y, x) == [erf(y)]
assert solve(erfc(x) - y, x) == [erfcinv(y)]
assert solve(erfcinv(x) - y, x) == [erfc(y)]
def test_issue_2725():
R = Symbol('R')
eq = sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1)
sol = solve(eq, R, set=True)[1]
assert sol == {(Rational(5, 3) + (Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) +
sqrt(111)*I/9)**Rational(1, 3) + 40/(9*((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) +
sqrt(111)*I/9)**Rational(1, 3))),), (Rational(5, 3) + 40/(9*(Rational(251, 27) +
sqrt(111)*I/9)**Rational(1, 3)) + (Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3),)}
def test_issue_5114_6611():
# See that it doesn't hang; this solves in about 2 seconds.
# Also check that the solution is relatively small.
# Note: the system in issue 6611 solves in about 5 seconds and has
# an op-count of 138336 (with simplify=False).
b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('b:r')
eqs = Matrix([
[b - c/d + r/d], [c*(1/g + 1/e + 1/d) - f/g - r/d],
[-c/g + f*(1/j + 1/i + 1/g) - h/i], [-f/i + h*(1/m + 1/l + 1/i) - k/m],
[-h/m + k*(1/p + 1/o + 1/m) - n/p], [-k/p + n*(1/q + 1/p)]])
v = Matrix([f, h, k, n, b, c])
ans = solve(list(eqs), list(v), simplify=False)
# If time is taken to simplify then then 2617 below becomes
# 1168 and the time is about 50 seconds instead of 2.
assert sum([s.count_ops() for s in ans.values()]) <= 3270
def test_det_quick():
m = Matrix(3, 3, symbols('a:9'))
assert m.det() == det_quick(m) # calls det_perm
m[0, 0] = 1
assert m.det() == det_quick(m) # calls det_minor
m = Matrix(3, 3, list(range(9)))
assert m.det() == det_quick(m) # defaults to .det()
# make sure they work with Sparse
s = SparseMatrix(2, 2, (1, 2, 1, 4))
assert det_perm(s) == det_minor(s) == s.det()
def test_real_imag_splitting():
a, b = symbols('a b', real=True)
assert solve(sqrt(a**2 + b**2) - 3, a) == \
[-sqrt(-b**2 + 9), sqrt(-b**2 + 9)]
a, b = symbols('a b', imaginary=True)
assert solve(sqrt(a**2 + b**2) - 3, a) == []
def test_issue_7110():
y = -2*x**3 + 4*x**2 - 2*x + 5
assert any(ask(Q.real(i)) for i in solve(y))
def test_units():
assert solve(1/x - 1/(2*cm)) == [2*cm]
def test_issue_7547():
A, B, V = symbols('A,B,V')
eq1 = Eq(630.26*(V - 39.0)*V*(V + 39) - A + B, 0)
eq2 = Eq(B, 1.36*10**8*(V - 39))
eq3 = Eq(A, 5.75*10**5*V*(V + 39.0))
sol = Matrix(nsolve(Tuple(eq1, eq2, eq3), [A, B, V], (0, 0, 0)))
assert str(sol) == str(Matrix(
[['4442890172.68209'],
['4289299466.1432'],
['70.5389666628177']]))
def test_issue_7895():
r = symbols('r', real=True)
assert solve(sqrt(r) - 2) == [4]
def test_issue_2777():
# the equations represent two circles
x, y = symbols('x y', real=True)
e1, e2 = sqrt(x**2 + y**2) - 10, sqrt(y**2 + (-x + 10)**2) - 3
a, b = Rational(191, 20), 3*sqrt(391)/20
ans = [(a, -b), (a, b)]
assert solve((e1, e2), (x, y)) == ans
assert solve((e1, e2/(x - a)), (x, y)) == []
# make the 2nd circle's radius be -3
e2 += 6
assert solve((e1, e2), (x, y)) == []
assert solve((e1, e2), (x, y), check=False) == ans
def test_issue_7322():
number = 5.62527e-35
assert solve(x - number, x)[0] == number
def test_nsolve():
raises(ValueError, lambda: nsolve(x, (-1, 1), method='bisect'))
raises(TypeError, lambda: nsolve((x - y + 3,x + y,z - y),(x,y,z),(-50,50)))
raises(TypeError, lambda: nsolve((x + y, x - y), (0, 1)))
@slow
def test_high_order_multivariate():
assert len(solve(a*x**3 - x + 1, x)) == 3
assert len(solve(a*x**4 - x + 1, x)) == 4
assert solve(a*x**5 - x + 1, x) == [] # incomplete solution allowed
raises(NotImplementedError, lambda:
solve(a*x**5 - x + 1, x, incomplete=False))
# result checking must always consider the denominator and CRootOf
# must be checked, too
d = x**5 - x + 1
assert solve(d*(1 + 1/d)) == [CRootOf(d + 1, i) for i in range(5)]
d = x - 1
assert solve(d*(2 + 1/d)) == [S.Half]
def test_base_0_exp_0():
assert solve(0**x - 1) == [0]
assert solve(0**(x - 2) - 1) == [2]
assert solve(S('x*(1/x**0 - x)', evaluate=False)) == \
[0, 1]
def test__simple_dens():
assert _simple_dens(1/x**0, [x]) == set()
assert _simple_dens(1/x**y, [x]) == {x**y}
assert _simple_dens(1/root(x, 3), [x]) == {x}
def test_issue_8755():
# This tests two things: that if full unrad is attempted and fails
# the solution should still be found; also it tests the use of
# keyword `composite`.
assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3
assert len(solve(-512*y**3 + 1344*(x + 2)**Rational(1, 3)*y**2 -
1176*(x + 2)**Rational(2, 3)*y - 169*x + 686, y, _unrad=False)) == 3
@slow
def test_issue_8828():
x1 = 0
y1 = -620
r1 = 920
x2 = 126
y2 = 276
x3 = 51
y3 = 205
r3 = 104
v = x, y, z
f1 = (x - x1)**2 + (y - y1)**2 - (r1 - z)**2
f2 = (x - x2)**2 + (y - y2)**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]
sol = solve(terms, [a, b, c, d, e, f, g], dict=True)
s = sqrt(-f**2 - 1)
s2 = sqrt(2 - f**2)
s3 = sqrt(6 - 3*f**2)
s4 = sqrt(3)*f
s5 = sqrt(3)*s2
assert sol == [
{a: -s, b: -s, c: -s, d: f, e: f, g: -1},
{a: s, b: s, c: s, d: f, e: f, g: -1},
{a: -s4/2 - s2/2, b: s4/2 - s2/2, c: s2,
d: -f/2 + s3/2, e: -f/2 - s5/2, g: 2},
{a: -s4/2 + s2/2, b: s4/2 + s2/2, c: -s2,
d: -f/2 - s3/2, e: -f/2 + s5/2, g: 2},
{a: s4/2 - s2/2, b: -s4/2 - s2/2, c: s2,
d: -f/2 - s3/2, e: -f/2 + s5/2, g: 2},
{a: s4/2 + s2/2, b: -s4/2 + s2/2, c: -s2,
d: -f/2 + s3/2, e: -f/2 - s5/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)]
# constants inside hyperbolic functions should not be rewritten in terms of exp
assert solve(system, x, y, z) == [(cosh(cos(4)), sinh(cos(a)), tanh(cosh(cos(4))))]
# but if the variable of interest is present in a hyperbolic function,
# then it should be rewritten in terms of exp and solved further
newsystem = [(exp(x) - exp(-x)) - tanh(x)*(exp(x) + exp(-x)) + x - 5]
assert solve(newsystem, x) == {x: 5}
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 == [((a*b**(1 - e) - b**(1 - e) +
d**(1 - e))/a)**(1/(1 - e))]
def test_solver_flags():
root = solve(x**5 + x**2 - x - 1, cubics=False)
rad = solve(x**5 + x**2 - x - 1, cubics=True)
assert root != rad
def test_issue_22768():
eq = 2*x**3 - 16*(y - 1)**6*z**3
assert solve(eq.expand(), x, simplify=False
) == [2*z*(y - 1)**2, z*(-1 + sqrt(3)*I)*(y - 1)**2,
-z*(1 + sqrt(3)*I)*(y - 1)**2]
def test_issue_22717():
assert solve((-y**2 + log(y**2/x) + 2, -2*x*y + 2*x/y)) == [
{y: -1, x: E}, {y: 1, x: E}]
def test_issue_10169():
eq = S(-8*a - x**5*(a + b + c + e) - x**4*(4*a - 2**Rational(3,4)*c + 4*c +
d + 2**Rational(3,4)*e + 4*e + k) - x**3*(-4*2**Rational(3,4)*c + sqrt(2)*c -
2**Rational(3,4)*d + 4*d + sqrt(2)*e + 4*2**Rational(3,4)*e + 2**Rational(3,4)*k + 4*k) -
x**2*(4*sqrt(2)*c - 4*2**Rational(3,4)*d + sqrt(2)*d + 4*sqrt(2)*e +
sqrt(2)*k + 4*2**Rational(3,4)*k) - x*(2*a + 2*b + 4*sqrt(2)*d +
4*sqrt(2)*k) + 5)
assert solve_undetermined_coeffs(eq, [a, b, c, d, e, k], x) == {
a: Rational(5,8),
b: Rational(-5,1032),
c: Rational(-40,129) - 5*2**Rational(3,4)/129 + 5*2**Rational(1,4)/1032,
d: -20*2**Rational(3,4)/129 - 10*sqrt(2)/129 - 5*2**Rational(1,4)/258,
e: Rational(-40,129) - 5*2**Rational(1,4)/1032 + 5*2**Rational(3,4)/129,
k: -10*sqrt(2)/129 + 5*2**Rational(1,4)/258 + 20*2**Rational(3,4)/129
}
def test_solve_undetermined_coeffs_issue_23927():
A, B, r, phi = symbols('A, B, r, phi')
eq = Eq(A*sin(t) + B*cos(t), r*sin(t - phi)).rewrite(Add).expand(trig=True)
soln = solve_undetermined_coeffs(eq, (r, phi), t)
assert soln == [{
phi: 2*atan((A - sqrt(A**2 + B**2))/B),
r: (-A**2 + A*sqrt(A**2 + B**2) - B**2)/(A - sqrt(A**2 + B**2))
}, {
phi: 2*atan((A + sqrt(A**2 + B**2))/B),
r: (A**2 + A*sqrt(A**2 + B**2) + B**2)/(A + sqrt(A**2 + B**2))/-1
}]
|
11ea86102a40b07a1a5ee942b0e109eb30059f98bc883cb9d94a3aedac050082 | from sympy.core.function import nfloat
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, 1, 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) == nfloat(-x0)
assert nsolve(eqn.T, x.T, x0.T) == nfloat(-x0)
|
cd50872728d5170f71a50fc4142b00df7cc11b0090f2049e2ed6cb180f6dd2e4 | 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(Rational(3,2), 3))
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(Rational(3,2), 3))
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(Rational(3,2), 3))
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))
def test_issue_23401():
x = Symbol('x')
expr = (x + 1)/(-1.0e-3*x**2 + 0.1*x + 0.1)
assert is_increasing(expr, Interval(1,2), x)
|
9797da9a87102c77fd0a26740a343509fde07951b2d234f8294654482bd6b73b | import inspect
import copy
import pickle
from sympy.physics.units import meter
from sympy.testing.pytest import XFAIL, raises
from sympy.core.basic import Atom, Basic
from sympy.core.core import BasicMeta
from sympy.core.singleton import SingletonRegistry
from sympy.core.symbol import Str, Dummy, Symbol, Wild
from sympy.core.numbers import (E, I, pi, oo, zoo, nan, Integer,
Rational, Float, AlgebraicNumber)
from sympy.core.relational import (Equality, GreaterThan, LessThan, Relational,
StrictGreaterThan, StrictLessThan, Unequality)
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.function import Derivative, Function, FunctionClass, Lambda, \
WildFunction
from sympy.sets.sets import Interval
from sympy.core.multidimensional import vectorize
from sympy.external.gmpy import HAS_GMPY
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.external import import_module
cloudpickle = import_module('cloudpickle')
excluded_attrs = {
'_assumptions', # This is a local cache that isn't automatically filled on creation
'_mhash', # Cached after __hash__ is called but set to None after creation
'is_EmptySet', # Deprecated from SymPy 1.5. This can be removed when is_EmptySet is removed.
'expr_free_symbols', # Deprecated from SymPy 1.9. This can be removed when exr_free_symbols is removed.
'_mat', # Deprecated from SymPy 1.9. This can be removed when Matrix._mat is removed
'_smat', # Deprecated from SymPy 1.9. This can be removed when SparseMatrix._smat is removed
}
def check(a, exclude=[], check_attr=True):
""" Check that pickling and copying round-trips.
"""
# Pickling with protocols 0 and 1 is disabled for Basic instances:
if isinstance(a, Basic):
for protocol in [0, 1]:
raises(NotImplementedError, lambda: pickle.dumps(a, protocol))
protocols = [2, copy.copy, copy.deepcopy, 3, 4]
if cloudpickle:
protocols.extend([cloudpickle])
for protocol in protocols:
if protocol in exclude:
continue
if callable(protocol):
if isinstance(a, BasicMeta):
# Classes can't be copied, but that's okay.
continue
b = protocol(a)
elif inspect.ismodule(protocol):
b = protocol.loads(protocol.dumps(a))
else:
b = pickle.loads(pickle.dumps(a, protocol))
d1 = dir(a)
d2 = dir(b)
assert set(d1) == set(d2)
if not check_attr:
continue
def c(a, b, d):
for i in d:
if i in excluded_attrs:
continue
if not hasattr(a, i):
continue
attr = getattr(a, i)
if not hasattr(attr, "__call__"):
assert hasattr(b, i), i
assert getattr(b, i) == attr, "%s != %s, protocol: %s" % (getattr(b, i), attr, protocol)
c(a, b, d1)
c(b, a, d2)
#================== core =========================
def test_core_basic():
for c in (Atom, Atom(),
Basic, Basic(),
# XXX: dynamically created types are not picklable
# BasicMeta, BasicMeta("test", (), {}),
SingletonRegistry, S):
check(c)
def test_core_Str():
check(Str('x'))
def test_core_symbol():
# make the Symbol a unique name that doesn't class with any other
# testing variable in this file since after this test the symbol
# having the same name will be cached as noncommutative
for c in (Dummy, Dummy("x", commutative=False), Symbol,
Symbol("_issue_3130", commutative=False), Wild, Wild("x")):
check(c)
def test_core_numbers():
for c in (Integer(2), Rational(2, 3), Float("1.2")):
check(c)
for c in (AlgebraicNumber, AlgebraicNumber(sqrt(3))):
check(c, check_attr=False)
def test_core_float_copy():
# See gh-7457
y = Symbol("x") + 1.0
check(y) # does not raise TypeError ("argument is not an mpz")
def test_core_relational():
x = Symbol("x")
y = Symbol("y")
for c in (Equality, Equality(x, y), GreaterThan, GreaterThan(x, y),
LessThan, LessThan(x, y), Relational, Relational(x, y),
StrictGreaterThan, StrictGreaterThan(x, y), StrictLessThan,
StrictLessThan(x, y), Unequality, Unequality(x, y)):
check(c)
def test_core_add():
x = Symbol("x")
for c in (Add, Add(x, 4)):
check(c)
def test_core_mul():
x = Symbol("x")
for c in (Mul, Mul(x, 4)):
check(c)
def test_core_power():
x = Symbol("x")
for c in (Pow, Pow(x, 4)):
check(c)
def test_core_function():
x = Symbol("x")
for f in (Derivative, Derivative(x), Function, FunctionClass, Lambda,
WildFunction):
check(f)
def test_core_undefinedfunctions():
f = Function("f")
# Full XFAILed test below
exclude = list(range(5))
# https://github.com/cloudpipe/cloudpickle/issues/65
# https://github.com/cloudpipe/cloudpickle/issues/190
exclude.append(cloudpickle)
check(f, exclude=exclude)
@XFAIL
def test_core_undefinedfunctions_fail():
# This fails because f is assumed to be a class at sympy.basic.function.f
f = Function("f")
check(f)
def test_core_interval():
for c in (Interval, Interval(0, 2)):
check(c)
def test_core_multidimensional():
for c in (vectorize, vectorize(0)):
check(c)
def test_Singletons():
protocols = [0, 1, 2, 3, 4]
copiers = [copy.copy, copy.deepcopy]
copiers += [lambda x: pickle.loads(pickle.dumps(x, proto))
for proto in protocols]
if cloudpickle:
copiers += [lambda x: cloudpickle.loads(cloudpickle.dumps(x))]
for obj in (Integer(-1), Integer(0), Integer(1), Rational(1, 2), pi, E, I,
oo, -oo, zoo, nan, S.GoldenRatio, S.TribonacciConstant,
S.EulerGamma, S.Catalan, S.EmptySet, S.IdentityFunction):
for func in copiers:
assert func(obj) is obj
#================== functions ===================
from sympy.functions import (Piecewise, lowergamma, acosh, chebyshevu,
chebyshevt, ln, chebyshevt_root, legendre, Heaviside, bernoulli, coth,
tanh, assoc_legendre, sign, arg, asin, DiracDelta, re, rf, Abs,
uppergamma, binomial, sinh, cos, cot, acos, acot, gamma, bell,
hermite, harmonic, LambertW, zeta, log, factorial, asinh, acoth, cosh,
dirichlet_eta, Eijk, loggamma, erf, ceiling, im, fibonacci,
tribonacci, conjugate, tan, chebyshevu_root, floor, atanh, sqrt, sin,
atan, ff, lucas, atan2, polygamma, exp)
def test_functions():
one_var = (acosh, ln, Heaviside, factorial, bernoulli, coth, tanh,
sign, arg, asin, DiracDelta, re, Abs, sinh, cos, cot, acos, acot,
gamma, bell, harmonic, LambertW, zeta, log, factorial, asinh,
acoth, cosh, dirichlet_eta, loggamma, erf, ceiling, im, fibonacci,
tribonacci, conjugate, tan, floor, atanh, sin, atan, lucas, exp)
two_var = (rf, ff, lowergamma, chebyshevu, chebyshevt, binomial,
atan2, polygamma, hermite, legendre, uppergamma)
x, y, z = symbols("x,y,z")
others = (chebyshevt_root, chebyshevu_root, Eijk(x, y, z),
Piecewise( (0, x < -1), (x**2, x <= 1), (x**3, True)),
assoc_legendre)
for cls in one_var:
check(cls)
c = cls(x)
check(c)
for cls in two_var:
check(cls)
c = cls(x, y)
check(c)
for cls in others:
check(cls)
#================== geometry ====================
from sympy.geometry.entity import GeometryEntity
from sympy.geometry.point import Point
from sympy.geometry.ellipse import Circle, Ellipse
from sympy.geometry.line import Line, LinearEntity, Ray, Segment
from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle
def test_geometry():
p1 = Point(1, 2)
p2 = Point(2, 3)
p3 = Point(0, 0)
p4 = Point(0, 1)
for c in (
GeometryEntity, GeometryEntity(), Point, p1, Circle, Circle(p1, 2),
Ellipse, Ellipse(p1, 3, 4), Line, Line(p1, p2), LinearEntity,
LinearEntity(p1, p2), Ray, Ray(p1, p2), Segment, Segment(p1, p2),
Polygon, Polygon(p1, p2, p3, p4), RegularPolygon,
RegularPolygon(p1, 4, 5), Triangle, Triangle(p1, p2, p3)):
check(c, check_attr=False)
#================== integrals ====================
from sympy.integrals.integrals import Integral
def test_integrals():
x = Symbol("x")
for c in (Integral, Integral(x)):
check(c)
#==================== logic =====================
from sympy.core.logic import Logic
def test_logic():
for c in (Logic, Logic(1)):
check(c)
#================== matrices ====================
from sympy.matrices import Matrix, SparseMatrix
def test_matrices():
for c in (Matrix, Matrix([1, 2, 3]), SparseMatrix, SparseMatrix([[1, 2], [3, 4]])):
check(c)
#================== ntheory =====================
from sympy.ntheory.generate import Sieve
def test_ntheory():
for c in (Sieve, Sieve()):
check(c)
#================== physics =====================
from sympy.physics.paulialgebra import Pauli
from sympy.physics.units import Unit
def test_physics():
for c in (Unit, meter, Pauli, Pauli(1)):
check(c)
#================== plotting ====================
# XXX: These tests are not complete, so XFAIL them
@XFAIL
def test_plotting():
from sympy.plotting.pygletplot.color_scheme import ColorGradient, ColorScheme
from sympy.plotting.pygletplot.managed_window import ManagedWindow
from sympy.plotting.plot import Plot, ScreenShot
from sympy.plotting.pygletplot.plot_axes import PlotAxes, PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate
from sympy.plotting.pygletplot.plot_camera import PlotCamera
from sympy.plotting.pygletplot.plot_controller import PlotController
from sympy.plotting.pygletplot.plot_curve import PlotCurve
from sympy.plotting.pygletplot.plot_interval import PlotInterval
from sympy.plotting.pygletplot.plot_mode import PlotMode
from sympy.plotting.pygletplot.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \
ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical
from sympy.plotting.pygletplot.plot_object import PlotObject
from sympy.plotting.pygletplot.plot_surface import PlotSurface
from sympy.plotting.pygletplot.plot_window import PlotWindow
for c in (
ColorGradient, ColorGradient(0.2, 0.4), ColorScheme, ManagedWindow,
ManagedWindow, Plot, ScreenShot, PlotAxes, PlotAxesBase,
PlotAxesFrame, PlotAxesOrdinate, PlotCamera, PlotController,
PlotCurve, PlotInterval, PlotMode, Cartesian2D, Cartesian3D,
Cylindrical, ParametricCurve2D, ParametricCurve3D,
ParametricSurface, Polar, Spherical, PlotObject, PlotSurface,
PlotWindow):
check(c)
@XFAIL
def test_plotting2():
#from sympy.plotting.color_scheme import ColorGradient
from sympy.plotting.pygletplot.color_scheme import ColorScheme
#from sympy.plotting.managed_window import ManagedWindow
from sympy.plotting.plot import Plot
#from sympy.plotting.plot import ScreenShot
from sympy.plotting.pygletplot.plot_axes import PlotAxes
#from sympy.plotting.plot_axes import PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate
#from sympy.plotting.plot_camera import PlotCamera
#from sympy.plotting.plot_controller import PlotController
#from sympy.plotting.plot_curve import PlotCurve
#from sympy.plotting.plot_interval import PlotInterval
#from sympy.plotting.plot_mode import PlotMode
#from sympy.plotting.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \
# ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical
#from sympy.plotting.plot_object import PlotObject
#from sympy.plotting.plot_surface import PlotSurface
# from sympy.plotting.plot_window import PlotWindow
check(ColorScheme("rainbow"))
check(Plot(1, visible=False))
check(PlotAxes())
#================== polys =======================
from sympy.polys.domains.integerring import ZZ
from sympy.polys.domains.rationalfield import QQ
from sympy.polys.orderings import lex
from sympy.polys.polytools import Poly
def test_pickling_polys_polytools():
from sympy.polys.polytools import PurePoly
# from sympy.polys.polytools import GroebnerBasis
x = Symbol('x')
for c in (Poly, Poly(x, x)):
check(c)
for c in (PurePoly, PurePoly(x)):
check(c)
# TODO: fix pickling of Options class (see GroebnerBasis._options)
# for c in (GroebnerBasis, GroebnerBasis([x**2 - 1], x, order=lex)):
# check(c)
def test_pickling_polys_polyclasses():
from sympy.polys.polyclasses import DMP, DMF, ANP
for c in (DMP, DMP([[ZZ(1)], [ZZ(2)], [ZZ(3)]], ZZ)):
check(c)
for c in (DMF, DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(3)]), ZZ)):
check(c)
for c in (ANP, ANP([QQ(1), QQ(2)], [QQ(1), QQ(2), QQ(3)], QQ)):
check(c)
@XFAIL
def test_pickling_polys_rings():
# NOTE: can't use protocols < 2 because we have to execute __new__ to
# make sure caching of rings works properly.
from sympy.polys.rings import PolyRing
ring = PolyRing("x,y,z", ZZ, lex)
for c in (PolyRing, ring):
check(c, exclude=[0, 1])
for c in (ring.dtype, ring.one):
check(c, exclude=[0, 1], check_attr=False) # TODO: Py3k
def test_pickling_polys_fields():
pass
# NOTE: can't use protocols < 2 because we have to execute __new__ to
# make sure caching of fields works properly.
# from sympy.polys.fields import FracField
# field = FracField("x,y,z", ZZ, lex)
# TODO: AssertionError: assert id(obj) not in self.memo
# for c in (FracField, field):
# check(c, exclude=[0, 1])
# TODO: AssertionError: assert id(obj) not in self.memo
# for c in (field.dtype, field.one):
# check(c, exclude=[0, 1])
def test_pickling_polys_elements():
from sympy.polys.domains.pythonrational import PythonRational
#from sympy.polys.domains.pythonfinitefield import PythonFiniteField
#from sympy.polys.domains.mpelements import MPContext
for c in (PythonRational, PythonRational(1, 7)):
check(c)
#gf = PythonFiniteField(17)
# TODO: fix pickling of ModularInteger
# for c in (gf.dtype, gf(5)):
# check(c)
#mp = MPContext()
# TODO: fix pickling of RealElement
# for c in (mp.mpf, mp.mpf(1.0)):
# check(c)
# TODO: fix pickling of ComplexElement
# for c in (mp.mpc, mp.mpc(1.0, -1.5)):
# check(c)
def test_pickling_polys_domains():
# from sympy.polys.domains.pythonfinitefield import PythonFiniteField
from sympy.polys.domains.pythonintegerring import PythonIntegerRing
from sympy.polys.domains.pythonrationalfield import PythonRationalField
# TODO: fix pickling of ModularInteger
# for c in (PythonFiniteField, PythonFiniteField(17)):
# check(c)
for c in (PythonIntegerRing, PythonIntegerRing()):
check(c, check_attr=False)
for c in (PythonRationalField, PythonRationalField()):
check(c, check_attr=False)
if HAS_GMPY:
# from sympy.polys.domains.gmpyfinitefield import GMPYFiniteField
from sympy.polys.domains.gmpyintegerring import GMPYIntegerRing
from sympy.polys.domains.gmpyrationalfield import GMPYRationalField
# TODO: fix pickling of ModularInteger
# for c in (GMPYFiniteField, GMPYFiniteField(17)):
# check(c)
for c in (GMPYIntegerRing, GMPYIntegerRing()):
check(c, check_attr=False)
for c in (GMPYRationalField, GMPYRationalField()):
check(c, check_attr=False)
#from sympy.polys.domains.realfield import RealField
#from sympy.polys.domains.complexfield import ComplexField
from sympy.polys.domains.algebraicfield import AlgebraicField
#from sympy.polys.domains.polynomialring import PolynomialRing
#from sympy.polys.domains.fractionfield import FractionField
from sympy.polys.domains.expressiondomain import ExpressionDomain
# TODO: fix pickling of RealElement
# for c in (RealField, RealField(100)):
# check(c)
# TODO: fix pickling of ComplexElement
# for c in (ComplexField, ComplexField(100)):
# check(c)
for c in (AlgebraicField, AlgebraicField(QQ, sqrt(3))):
check(c, check_attr=False)
# TODO: AssertionError
# for c in (PolynomialRing, PolynomialRing(ZZ, "x,y,z")):
# check(c)
# TODO: AttributeError: 'PolyElement' object has no attribute 'ring'
# for c in (FractionField, FractionField(ZZ, "x,y,z")):
# check(c)
for c in (ExpressionDomain, ExpressionDomain()):
check(c, check_attr=False)
def test_pickling_polys_orderings():
from sympy.polys.orderings import (LexOrder, GradedLexOrder,
ReversedGradedLexOrder, InverseOrder)
# from sympy.polys.orderings import ProductOrder
for c in (LexOrder, LexOrder()):
check(c)
for c in (GradedLexOrder, GradedLexOrder()):
check(c)
for c in (ReversedGradedLexOrder, ReversedGradedLexOrder()):
check(c)
# TODO: Argh, Python is so naive. No lambdas nor inner function support in
# pickling module. Maybe someone could figure out what to do with this.
#
# for c in (ProductOrder, ProductOrder((LexOrder(), lambda m: m[:2]),
# (GradedLexOrder(), lambda m: m[2:]))):
# check(c)
for c in (InverseOrder, InverseOrder(LexOrder())):
check(c)
def test_pickling_polys_monomials():
from sympy.polys.monomials import MonomialOps, Monomial
x, y, z = symbols("x,y,z")
for c in (MonomialOps, MonomialOps(3)):
check(c)
for c in (Monomial, Monomial((1, 2, 3), (x, y, z))):
check(c)
def test_pickling_polys_errors():
from sympy.polys.polyerrors import (HeuristicGCDFailed,
HomomorphismFailed, IsomorphismFailed, ExtraneousFactors,
EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible,
NotReversible, NotAlgebraic, DomainError, PolynomialError,
UnificationFailed, GeneratorsError, GeneratorsNeeded,
UnivariatePolynomialError, MultivariatePolynomialError, OptionError,
FlagError)
# from sympy.polys.polyerrors import (ExactQuotientFailed,
# OperationNotSupported, ComputationFailed, PolificationFailed)
# x = Symbol('x')
# TODO: TypeError: __init__() takes at least 3 arguments (1 given)
# for c in (ExactQuotientFailed, ExactQuotientFailed(x, 3*x, ZZ)):
# check(c)
# TODO: TypeError: can't pickle instancemethod objects
# for c in (OperationNotSupported, OperationNotSupported(Poly(x), Poly.gcd)):
# check(c)
for c in (HeuristicGCDFailed, HeuristicGCDFailed()):
check(c)
for c in (HomomorphismFailed, HomomorphismFailed()):
check(c)
for c in (IsomorphismFailed, IsomorphismFailed()):
check(c)
for c in (ExtraneousFactors, ExtraneousFactors()):
check(c)
for c in (EvaluationFailed, EvaluationFailed()):
check(c)
for c in (RefinementFailed, RefinementFailed()):
check(c)
for c in (CoercionFailed, CoercionFailed()):
check(c)
for c in (NotInvertible, NotInvertible()):
check(c)
for c in (NotReversible, NotReversible()):
check(c)
for c in (NotAlgebraic, NotAlgebraic()):
check(c)
for c in (DomainError, DomainError()):
check(c)
for c in (PolynomialError, PolynomialError()):
check(c)
for c in (UnificationFailed, UnificationFailed()):
check(c)
for c in (GeneratorsError, GeneratorsError()):
check(c)
for c in (GeneratorsNeeded, GeneratorsNeeded()):
check(c)
# TODO: PicklingError: Can't pickle <function <lambda> at 0x38578c0>: it's not found as __main__.<lambda>
# for c in (ComputationFailed, ComputationFailed(lambda t: t, 3, None)):
# check(c)
for c in (UnivariatePolynomialError, UnivariatePolynomialError()):
check(c)
for c in (MultivariatePolynomialError, MultivariatePolynomialError()):
check(c)
# TODO: TypeError: __init__() takes at least 3 arguments (1 given)
# for c in (PolificationFailed, PolificationFailed({}, x, x, False)):
# check(c)
for c in (OptionError, OptionError()):
check(c)
for c in (FlagError, FlagError()):
check(c)
#def test_pickling_polys_options():
#from sympy.polys.polyoptions import Options
# TODO: fix pickling of `symbols' flag
# for c in (Options, Options((), dict(domain='ZZ', polys=False))):
# check(c)
# TODO: def test_pickling_polys_rootisolation():
# RealInterval
# ComplexInterval
def test_pickling_polys_rootoftools():
from sympy.polys.rootoftools import CRootOf, RootSum
x = Symbol('x')
f = x**3 + x + 3
for c in (CRootOf, CRootOf(f, 0)):
check(c)
for c in (RootSum, RootSum(f, exp)):
check(c)
#================== printing ====================
from sympy.printing.latex import LatexPrinter
from sympy.printing.mathml import MathMLContentPrinter, MathMLPresentationPrinter
from sympy.printing.pretty.pretty import PrettyPrinter
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.printing.printer import Printer
from sympy.printing.python import PythonPrinter
def test_printing():
for c in (LatexPrinter, LatexPrinter(), MathMLContentPrinter,
MathMLPresentationPrinter, PrettyPrinter, prettyForm, stringPict,
stringPict("a"), Printer, Printer(), PythonPrinter,
PythonPrinter()):
check(c)
@XFAIL
def test_printing1():
check(MathMLContentPrinter())
@XFAIL
def test_printing2():
check(MathMLPresentationPrinter())
@XFAIL
def test_printing3():
check(PrettyPrinter())
#================== series ======================
from sympy.series.limits import Limit
from sympy.series.order import Order
def test_series():
e = Symbol("e")
x = Symbol("x")
for c in (Limit, Limit(e, x, 1), Order, Order(e)):
check(c)
#================== concrete ==================
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
def test_concrete():
x = Symbol("x")
for c in (Product, Product(x, (x, 2, 4)), Sum, Sum(x, (x, 2, 4))):
check(c)
def test_deprecation_warning():
w = SymPyDeprecationWarning("message", deprecated_since_version='1.0', active_deprecations_target="active-deprecations")
check(w)
def test_issue_18438():
assert pickle.loads(pickle.dumps(S.Half)) == S.Half
#================= old pickles =================
def test_unpickle_from_older_versions():
data = (
b'\x80\x04\x95^\x00\x00\x00\x00\x00\x00\x00\x8c\x10sympy.core.power'
b'\x94\x8c\x03Pow\x94\x93\x94\x8c\x12sympy.core.numbers\x94\x8c'
b'\x07Integer\x94\x93\x94K\x02\x85\x94R\x94}\x94bh\x03\x8c\x04Half'
b'\x94\x93\x94)R\x94}\x94b\x86\x94R\x94}\x94b.'
)
assert pickle.loads(data) == sqrt(2)
|
5097b982974bb01883963143ce4456e363ed13adb167ab5d25ada7014ce263b7 | from itertools import product
import math
import inspect
import mpmath
from sympy.testing.pytest import raises, warns_deprecated_sympy
from sympy.concrete.summations import Sum
from sympy.core.function import (Function, Lambda, diff)
from sympy.core.numbers import (E, Float, I, Rational, oo, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial)
from sympy.functions.combinatorial.numbers import bernoulli, harmonic
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.hyperbolic import acosh
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, cos, cot, sin,
sinc, tan)
from sympy.functions.special.bessel import (besseli, besselj, besselk, bessely)
from sympy.functions.special.beta_functions import (beta, betainc, betainc_regularized)
from sympy.functions.special.delta_functions import (Heaviside)
from sympy.functions.special.error_functions import (Ei, erf, erfc, fresnelc, fresnels, Si, Ci)
from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma, polygamma)
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import (And, false, ITE, Not, Or, true)
from sympy.matrices.expressions.dotproduct import DotProduct
from sympy.tensor.array import derive_by_array, Array
from sympy.tensor.indexed import IndexedBase
from sympy.utilities.lambdify import lambdify
from sympy.core.expr import UnevaluatedExpr
from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, log10, hypot
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.codegen.scipy_nodes import cosm1, powm1
from sympy.functions.elementary.complexes import re, im, arg
from sympy.functions.special.polynomials import \
chebyshevt, chebyshevu, legendre, hermite, laguerre, gegenbauer, \
assoc_legendre, assoc_laguerre, jacobi
from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix
from sympy.printing.lambdarepr import LambdaPrinter
from sympy.printing.numpy import NumPyPrinter
from sympy.utilities.lambdify import implemented_function, lambdastr
from sympy.testing.pytest import skip
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.utilities.exceptions import ignore_warnings
from sympy.external import import_module
from sympy.functions.special.gamma_functions import uppergamma, lowergamma
import sympy
MutableDenseMatrix = Matrix
numpy = import_module('numpy')
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
numexpr = import_module('numexpr')
tensorflow = import_module('tensorflow')
cupy = import_module('cupy')
jax = import_module('jax')
numba = import_module('numba')
if tensorflow:
# Hide Tensorflow warnings
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
w, x, y, z = symbols('w,x,y,z')
#================== Test different arguments =======================
def test_no_args():
f = lambdify([], 1)
raises(TypeError, lambda: f(-1))
assert f() == 1
def test_single_arg():
f = lambdify(x, 2*x)
assert f(1) == 2
def test_list_args():
f = lambdify([x, y], x + y)
assert f(1, 2) == 3
def test_nested_args():
f1 = lambdify([[w, x]], [w, x])
assert f1([91, 2]) == [91, 2]
raises(TypeError, lambda: f1(1, 2))
f2 = lambdify([(w, x), (y, z)], [w, x, y, z])
assert f2((18, 12), (73, 4)) == [18, 12, 73, 4]
raises(TypeError, lambda: f2(3, 4))
f3 = lambdify([w, [[[x]], y], z], [w, x, y, z])
assert f3(10, [[[52]], 31], 44) == [10, 52, 31, 44]
def test_str_args():
f = lambdify('x,y,z', 'z,y,x')
assert f(3, 2, 1) == (1, 2, 3)
assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0)
# make sure correct number of args required
raises(TypeError, lambda: f(0))
def test_own_namespace_1():
myfunc = lambda x: 1
f = lambdify(x, sin(x), {"sin": myfunc})
assert f(0.1) == 1
assert f(100) == 1
def test_own_namespace_2():
def myfunc(x):
return 1
f = lambdify(x, sin(x), {'sin': myfunc})
assert f(0.1) == 1
assert f(100) == 1
def test_own_module():
f = lambdify(x, sin(x), math)
assert f(0) == 0.0
p, q, r = symbols("p q r", real=True)
ae = abs(exp(p+UnevaluatedExpr(q+r)))
f = lambdify([p, q, r], [ae, ae], modules=math)
results = f(1.0, 1e18, -1e18)
refvals = [math.exp(1.0)]*2
for res, ref in zip(results, refvals):
assert abs((res-ref)/ref) < 1e-15
def test_bad_args():
# no vargs given
raises(TypeError, lambda: lambdify(1))
# same with vector exprs
raises(TypeError, lambda: lambdify([1, 2]))
def test_atoms():
# Non-Symbol atoms should not be pulled out from the expression namespace
f = lambdify(x, pi + x, {"pi": 3.14})
assert f(0) == 3.14
f = lambdify(x, I + x, {"I": 1j})
assert f(1) == 1 + 1j
#================== Test different modules =========================
# high precision output of sin(0.2*pi) is used to detect if precision is lost unwanted
@conserve_mpmath_dps
def test_sympy_lambda():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin(x), "sympy")
assert f(x) == sin(x)
prec = 1e-15
assert -prec < f(Rational(1, 5)).evalf() - Float(str(sin02)) < prec
# arctan is in numpy module and should not be available
# The arctan below gives NameError. What is this supposed to test?
# raises(NameError, lambda: lambdify(x, arctan(x), "sympy"))
@conserve_mpmath_dps
def test_math_lambda():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin(x), "math")
prec = 1e-15
assert -prec < f(0.2) - sin02 < prec
raises(TypeError, lambda: f(x))
# if this succeeds, it can't be a Python math function
@conserve_mpmath_dps
def test_mpmath_lambda():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin(x), "mpmath")
prec = 1e-49 # mpmath precision is around 50 decimal places
assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec
raises(TypeError, lambda: f(x))
# if this succeeds, it can't be a mpmath function
ref2 = (mpmath.mpf("1e-30")
- mpmath.mpf("1e-45")/2
+ 5*mpmath.mpf("1e-60")/6
- 3*mpmath.mpf("1e-75")/4
+ 33*mpmath.mpf("1e-90")/40
)
f2a = lambdify((x, y), x**y - 1, "mpmath")
f2b = lambdify((x, y), powm1(x, y), "mpmath")
f2c = lambdify((x,), expm1(x*log1p(x)), "mpmath")
ans2a = f2a(mpmath.mpf("1")+mpmath.mpf("1e-15"), mpmath.mpf("1e-15"))
ans2b = f2b(mpmath.mpf("1")+mpmath.mpf("1e-15"), mpmath.mpf("1e-15"))
ans2c = f2c(mpmath.mpf("1e-15"))
assert abs(ans2a - ref2) < 1e-51
assert abs(ans2b - ref2) < 1e-67
assert abs(ans2c - ref2) < 1e-80
@conserve_mpmath_dps
def test_number_precision():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin02, "mpmath")
prec = 1e-49 # mpmath precision is around 50 decimal places
assert -prec < f(0) - sin02 < prec
@conserve_mpmath_dps
def test_mpmath_precision():
mpmath.mp.dps = 100
assert str(lambdify((), pi.evalf(100), 'mpmath')()) == str(pi.evalf(100))
#================== Test Translations ==============================
# We can only check if all translated functions are valid. It has to be checked
# by hand if they are complete.
def test_math_transl():
from sympy.utilities.lambdify import MATH_TRANSLATIONS
for sym, mat in MATH_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert mat in math.__dict__
def test_mpmath_transl():
from sympy.utilities.lambdify import MPMATH_TRANSLATIONS
for sym, mat in MPMATH_TRANSLATIONS.items():
assert sym in sympy.__dict__ or sym == 'Matrix'
assert mat in mpmath.__dict__
def test_numpy_transl():
if not numpy:
skip("numpy not installed.")
from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
for sym, nump in NUMPY_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert nump in numpy.__dict__
def test_scipy_transl():
if not scipy:
skip("scipy not installed.")
from sympy.utilities.lambdify import SCIPY_TRANSLATIONS
for sym, scip in SCIPY_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert scip in scipy.__dict__ or scip in scipy.special.__dict__
def test_numpy_translation_abs():
if not numpy:
skip("numpy not installed.")
f = lambdify(x, Abs(x), "numpy")
assert f(-1) == 1
assert f(1) == 1
def test_numexpr_printer():
if not numexpr:
skip("numexpr not installed.")
# if translation/printing is done incorrectly then evaluating
# a lambdified numexpr expression will throw an exception
from sympy.printing.lambdarepr import NumExprPrinter
blacklist = ('where', 'complex', 'contains')
arg_tuple = (x, y, z) # some functions take more than one argument
for sym in NumExprPrinter._numexpr_functions.keys():
if sym in blacklist:
continue
ssym = S(sym)
if hasattr(ssym, '_nargs'):
nargs = ssym._nargs[0]
else:
nargs = 1
args = arg_tuple[:nargs]
f = lambdify(args, ssym(*args), modules='numexpr')
assert f(*(1, )*nargs) is not None
def test_issue_9334():
if not numexpr:
skip("numexpr not installed.")
if not numpy:
skip("numpy not installed.")
expr = S('b*a - sqrt(a**2)')
a, b = sorted(expr.free_symbols, key=lambda s: s.name)
func_numexpr = lambdify((a,b), expr, modules=[numexpr], dummify=False)
foo, bar = numpy.random.random((2, 4))
func_numexpr(foo, bar)
def test_issue_12984():
if not numexpr:
skip("numexpr not installed.")
func_numexpr = lambdify((x,y,z), Piecewise((y, x >= 0), (z, x > -1)), numexpr)
with ignore_warnings(RuntimeWarning):
assert func_numexpr(1, 24, 42) == 24
assert str(func_numexpr(-1, 24, 42)) == 'nan'
def test_empty_modules():
x, y = symbols('x y')
expr = -(x % y)
no_modules = lambdify([x, y], expr)
empty_modules = lambdify([x, y], expr, modules=[])
assert no_modules(3, 7) == empty_modules(3, 7)
assert no_modules(3, 7) == -3
def test_exponentiation():
f = lambdify(x, x**2)
assert f(-1) == 1
assert f(0) == 0
assert f(1) == 1
assert f(-2) == 4
assert f(2) == 4
assert f(2.5) == 6.25
def test_sqrt():
f = lambdify(x, sqrt(x))
assert f(0) == 0.0
assert f(1) == 1.0
assert f(4) == 2.0
assert abs(f(2) - 1.414) < 0.001
assert f(6.25) == 2.5
def test_trig():
f = lambdify([x], [cos(x), sin(x)], 'math')
d = f(pi)
prec = 1e-11
assert -prec < d[0] + 1 < prec
assert -prec < d[1] < prec
d = f(3.14159)
prec = 1e-5
assert -prec < d[0] + 1 < prec
assert -prec < d[1] < prec
def test_integral():
if numpy and not scipy:
skip("scipy not installed.")
f = Lambda(x, exp(-x**2))
l = lambdify(y, Integral(f(x), (x, y, oo)))
d = l(-oo)
assert 1.77245385 < d < 1.772453851
def test_double_integral():
if numpy and not scipy:
skip("scipy not installed.")
# example from http://mpmath.org/doc/current/calculus/integration.html
i = Integral(1/(1 - x**2*y**2), (x, 0, 1), (y, 0, z))
l = lambdify([z], i)
d = l(1)
assert 1.23370055 < d < 1.233700551
#================== Test vectors ===================================
def test_vector_simple():
f = lambdify((x, y, z), (z, y, x))
assert f(3, 2, 1) == (1, 2, 3)
assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0)
# make sure correct number of args required
raises(TypeError, lambda: f(0))
def test_vector_discontinuous():
f = lambdify(x, (-1/x, 1/x))
raises(ZeroDivisionError, lambda: f(0))
assert f(1) == (-1.0, 1.0)
assert f(2) == (-0.5, 0.5)
assert f(-2) == (0.5, -0.5)
def test_trig_symbolic():
f = lambdify([x], [cos(x), sin(x)], 'math')
d = f(pi)
assert abs(d[0] + 1) < 0.0001
assert abs(d[1] - 0) < 0.0001
def test_trig_float():
f = lambdify([x], [cos(x), sin(x)])
d = f(3.14159)
assert abs(d[0] + 1) < 0.0001
assert abs(d[1] - 0) < 0.0001
def test_docs():
f = lambdify(x, x**2)
assert f(2) == 4
f = lambdify([x, y, z], [z, y, x])
assert f(1, 2, 3) == [3, 2, 1]
f = lambdify(x, sqrt(x))
assert f(4) == 2.0
f = lambdify((x, y), sin(x*y)**2)
assert f(0, 5) == 0
def test_math():
f = lambdify((x, y), sin(x), modules="math")
assert f(0, 5) == 0
def test_sin():
f = lambdify(x, sin(x)**2)
assert isinstance(f(2), float)
f = lambdify(x, sin(x)**2, modules="math")
assert isinstance(f(2), float)
def test_matrix():
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol = Matrix([[1, 2], [sin(3) + 4, 1]])
f = lambdify((x, y, z), A, modules="sympy")
assert f(1, 2, 3) == sol
f = lambdify((x, y, z), (A, [A]), modules="sympy")
assert f(1, 2, 3) == (sol, [sol])
J = Matrix((x, x + y)).jacobian((x, y))
v = Matrix((x, y))
sol = Matrix([[1, 0], [1, 1]])
assert lambdify(v, J, modules='sympy')(1, 2) == sol
assert lambdify(v.T, J, modules='sympy')(1, 2) == sol
def test_numpy_matrix():
if not numpy:
skip("numpy not installed.")
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]])
#Lambdify array first, to ensure return to array as default
f = lambdify((x, y, z), A, ['numpy'])
numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
#Check that the types are arrays and matrices
assert isinstance(f(1, 2, 3), numpy.ndarray)
# gh-15071
class dot(Function):
pass
x_dot_mtx = dot(x, Matrix([[2], [1], [0]]))
f_dot1 = lambdify(x, x_dot_mtx)
inp = numpy.zeros((17, 3))
assert numpy.all(f_dot1(inp) == 0)
strict_kw = dict(allow_unknown_functions=False, inline=True, fully_qualified_modules=False)
p2 = NumPyPrinter(dict(user_functions={'dot': 'dot'}, **strict_kw))
f_dot2 = lambdify(x, x_dot_mtx, printer=p2)
assert numpy.all(f_dot2(inp) == 0)
p3 = NumPyPrinter(strict_kw)
# The line below should probably fail upon construction (before calling with "(inp)"):
raises(Exception, lambda: lambdify(x, x_dot_mtx, printer=p3)(inp))
def test_numpy_transpose():
if not numpy:
skip("numpy not installed.")
A = Matrix([[1, x], [0, 1]])
f = lambdify((x), A.T, modules="numpy")
numpy.testing.assert_array_equal(f(2), numpy.array([[1, 0], [2, 1]]))
def test_numpy_dotproduct():
if not numpy:
skip("numpy not installed")
A = Matrix([x, y, z])
f1 = lambdify([x, y, z], DotProduct(A, A), modules='numpy')
f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy')
f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='numpy')
f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy')
assert f1(1, 2, 3) == \
f2(1, 2, 3) == \
f3(1, 2, 3) == \
f4(1, 2, 3) == \
numpy.array([14])
def test_numpy_inverse():
if not numpy:
skip("numpy not installed.")
A = Matrix([[1, x], [0, 1]])
f = lambdify((x), A**-1, modules="numpy")
numpy.testing.assert_array_equal(f(2), numpy.array([[1, -2], [0, 1]]))
def test_numpy_old_matrix():
if not numpy:
skip("numpy not installed.")
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]])
f = lambdify((x, y, z), A, [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy'])
with ignore_warnings(PendingDeprecationWarning):
numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
assert isinstance(f(1, 2, 3), numpy.matrix)
def test_scipy_sparse_matrix():
if not scipy:
skip("scipy not installed.")
A = SparseMatrix([[x, 0], [0, y]])
f = lambdify((x, y), A, modules="scipy")
B = f(1, 2)
assert isinstance(B, scipy.sparse.coo_matrix)
def test_python_div_zero_issue_11306():
if not numpy:
skip("numpy not installed.")
p = Piecewise((1 / x, y < -1), (x, y < 1), (1 / x, True))
f = lambdify([x, y], p, modules='numpy')
numpy.seterr(divide='ignore')
assert float(f(numpy.array([0]),numpy.array([0.5]))) == 0
assert str(float(f(numpy.array([0]),numpy.array([1])))) == 'inf'
numpy.seterr(divide='warn')
def test_issue9474():
mods = [None, 'math']
if numpy:
mods.append('numpy')
if mpmath:
mods.append('mpmath')
for mod in mods:
f = lambdify(x, S.One/x, modules=mod)
assert f(2) == 0.5
f = lambdify(x, floor(S.One/x), modules=mod)
assert f(2) == 0
for absfunc, modules in product([Abs, abs], mods):
f = lambdify(x, absfunc(x), modules=modules)
assert f(-1) == 1
assert f(1) == 1
assert f(3+4j) == 5
def test_issue_9871():
if not numexpr:
skip("numexpr not installed.")
if not numpy:
skip("numpy not installed.")
r = sqrt(x**2 + y**2)
expr = diff(1/r, x)
xn = yn = numpy.linspace(1, 10, 16)
# expr(xn, xn) = -xn/(sqrt(2)*xn)^3
fv_exact = -numpy.sqrt(2.)**-3 * xn**-2
fv_numpy = lambdify((x, y), expr, modules='numpy')(xn, yn)
fv_numexpr = lambdify((x, y), expr, modules='numexpr')(xn, yn)
numpy.testing.assert_allclose(fv_numpy, fv_exact, rtol=1e-10)
numpy.testing.assert_allclose(fv_numexpr, fv_exact, rtol=1e-10)
def test_numpy_piecewise():
if not numpy:
skip("numpy not installed.")
pieces = Piecewise((x, x < 3), (x**2, x > 5), (0, True))
f = lambdify(x, pieces, modules="numpy")
numpy.testing.assert_array_equal(f(numpy.arange(10)),
numpy.array([0, 1, 2, 0, 0, 0, 36, 49, 64, 81]))
# If we evaluate somewhere all conditions are False, we should get back NaN
nodef_func = lambdify(x, Piecewise((x, x > 0), (-x, x < 0)))
numpy.testing.assert_array_equal(nodef_func(numpy.array([-1, 0, 1])),
numpy.array([1, numpy.nan, 1]))
def test_numpy_logical_ops():
if not numpy:
skip("numpy not installed.")
and_func = lambdify((x, y), And(x, y), modules="numpy")
and_func_3 = lambdify((x, y, z), And(x, y, z), modules="numpy")
or_func = lambdify((x, y), Or(x, y), modules="numpy")
or_func_3 = lambdify((x, y, z), Or(x, y, z), modules="numpy")
not_func = lambdify((x), Not(x), modules="numpy")
arr1 = numpy.array([True, True])
arr2 = numpy.array([False, True])
arr3 = numpy.array([True, False])
numpy.testing.assert_array_equal(and_func(arr1, arr2), numpy.array([False, True]))
numpy.testing.assert_array_equal(and_func_3(arr1, arr2, arr3), numpy.array([False, False]))
numpy.testing.assert_array_equal(or_func(arr1, arr2), numpy.array([True, True]))
numpy.testing.assert_array_equal(or_func_3(arr1, arr2, arr3), numpy.array([True, True]))
numpy.testing.assert_array_equal(not_func(arr2), numpy.array([True, False]))
def test_numpy_matmul():
if not numpy:
skip("numpy not installed.")
xmat = Matrix([[x, y], [z, 1+z]])
ymat = Matrix([[x**2], [Abs(x)]])
mat_func = lambdify((x, y, z), xmat*ymat, modules="numpy")
numpy.testing.assert_array_equal(mat_func(0.5, 3, 4), numpy.array([[1.625], [3.5]]))
numpy.testing.assert_array_equal(mat_func(-0.5, 3, 4), numpy.array([[1.375], [3.5]]))
# Multiple matrices chained together in multiplication
f = lambdify((x, y, z), xmat*xmat*xmat, modules="numpy")
numpy.testing.assert_array_equal(f(0.5, 3, 4), numpy.array([[72.125, 119.25],
[159, 251]]))
def test_numpy_numexpr():
if not numpy:
skip("numpy not installed.")
if not numexpr:
skip("numexpr not installed.")
a, b, c = numpy.random.randn(3, 128, 128)
# ensure that numpy and numexpr return same value for complicated expression
expr = sin(x) + cos(y) + tan(z)**2 + Abs(z-y)*acos(sin(y*z)) + \
Abs(y-z)*acosh(2+exp(y-x))- sqrt(x**2+I*y**2)
npfunc = lambdify((x, y, z), expr, modules='numpy')
nefunc = lambdify((x, y, z), expr, modules='numexpr')
assert numpy.allclose(npfunc(a, b, c), nefunc(a, b, c))
def test_numexpr_userfunctions():
if not numpy:
skip("numpy not installed.")
if not numexpr:
skip("numexpr not installed.")
a, b = numpy.random.randn(2, 10)
uf = type('uf', (Function, ),
{'eval' : classmethod(lambda x, y : y**2+1)})
func = lambdify(x, 1-uf(x), modules='numexpr')
assert numpy.allclose(func(a), -(a**2))
uf = implemented_function(Function('uf'), lambda x, y : 2*x*y+1)
func = lambdify((x, y), uf(x, y), modules='numexpr')
assert numpy.allclose(func(a, b), 2*a*b+1)
def test_tensorflow_basic_math():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(sin(x), Abs(1/(x+2)))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
a = tensorflow.constant(0, dtype=tensorflow.float32)
assert func(a).eval(session=s) == 0.5
def test_tensorflow_placeholders():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(sin(x), Abs(1/(x+2)))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
a = tensorflow.compat.v1.placeholder(dtype=tensorflow.float32)
assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5
def test_tensorflow_variables():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(sin(x), Abs(1/(x+2)))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
a = tensorflow.Variable(0, dtype=tensorflow.float32)
s.run(a.initializer)
assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5
def test_tensorflow_logical_operations():
if not tensorflow:
skip("tensorflow not installed.")
expr = Not(And(Or(x, y), y))
func = lambdify([x, y], expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(False, True).eval(session=s) == False
def test_tensorflow_piecewise():
if not tensorflow:
skip("tensorflow not installed.")
expr = Piecewise((0, Eq(x,0)), (-1, x < 0), (1, x > 0))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(-1).eval(session=s) == -1
assert func(0).eval(session=s) == 0
assert func(1).eval(session=s) == 1
def test_tensorflow_multi_max():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(x, -x, x**2)
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(-2).eval(session=s) == 4
def test_tensorflow_multi_min():
if not tensorflow:
skip("tensorflow not installed.")
expr = Min(x, -x, x**2)
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(-2).eval(session=s) == -2
def test_tensorflow_relational():
if not tensorflow:
skip("tensorflow not installed.")
expr = x >= 0
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(1).eval(session=s) == True
def test_tensorflow_complexes():
if not tensorflow:
skip("tensorflow not installed")
func1 = lambdify(x, re(x), modules="tensorflow")
func2 = lambdify(x, im(x), modules="tensorflow")
func3 = lambdify(x, Abs(x), modules="tensorflow")
func4 = lambdify(x, arg(x), modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
# For versions before
# https://github.com/tensorflow/tensorflow/issues/30029
# resolved, using Python numeric types may not work
a = tensorflow.constant(1+2j)
assert func1(a).eval(session=s) == 1
assert func2(a).eval(session=s) == 2
tensorflow_result = func3(a).eval(session=s)
sympy_result = Abs(1 + 2j).evalf()
assert abs(tensorflow_result-sympy_result) < 10**-6
tensorflow_result = func4(a).eval(session=s)
sympy_result = arg(1 + 2j).evalf()
assert abs(tensorflow_result-sympy_result) < 10**-6
def test_tensorflow_array_arg():
# Test for issue 14655 (tensorflow part)
if not tensorflow:
skip("tensorflow not installed.")
f = lambdify([[x, y]], x*x + y, 'tensorflow')
with tensorflow.compat.v1.Session() as s:
fcall = f(tensorflow.constant([2.0, 1.0]))
assert fcall.eval(session=s) == 5.0
#================== Test symbolic ==================================
def test_sym_single_arg():
f = lambdify(x, x * y)
assert f(z) == z * y
def test_sym_list_args():
f = lambdify([x, y], x + y + z)
assert f(1, 2) == 3 + z
def test_sym_integral():
f = Lambda(x, exp(-x**2))
l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy")
assert l(y) == Integral(exp(-y**2), (y, -oo, oo))
assert l(y).doit() == sqrt(pi)
def test_namespace_order():
# lambdify had a bug, such that module dictionaries or cached module
# dictionaries would pull earlier namespaces into themselves.
# Because the module dictionaries form the namespace of the
# generated lambda, this meant that the behavior of a previously
# generated lambda function could change as a result of later calls
# to lambdify.
n1 = {'f': lambda x: 'first f'}
n2 = {'f': lambda x: 'second f',
'g': lambda x: 'function g'}
f = sympy.Function('f')
g = sympy.Function('g')
if1 = lambdify(x, f(x), modules=(n1, "sympy"))
assert if1(1) == 'first f'
if2 = lambdify(x, g(x), modules=(n2, "sympy"))
# previously gave 'second f'
assert if1(1) == 'first f'
assert if2(1) == 'function g'
def test_imps():
# Here we check if the default returned functions are anonymous - in
# the sense that we can have more than one function with the same name
f = implemented_function('f', lambda x: 2*x)
g = implemented_function('f', lambda x: math.sqrt(x))
l1 = lambdify(x, f(x))
l2 = lambdify(x, g(x))
assert str(f(x)) == str(g(x))
assert l1(3) == 6
assert l2(3) == math.sqrt(3)
# check that we can pass in a Function as input
func = sympy.Function('myfunc')
assert not hasattr(func, '_imp_')
my_f = implemented_function(func, lambda x: 2*x)
assert hasattr(my_f, '_imp_')
# Error for functions with same name and different implementation
f2 = implemented_function("f", lambda x: x + 101)
raises(ValueError, lambda: lambdify(x, f(f2(x))))
def test_imps_errors():
# Test errors that implemented functions can return, and still be able to
# form expressions.
# See: https://github.com/sympy/sympy/issues/10810
#
# XXX: Removed AttributeError here. This test was added due to issue 10810
# but that issue was about ValueError. It doesn't seem reasonable to
# "support" catching AttributeError in the same context...
for val, error_class in product((0, 0., 2, 2.0), (TypeError, ValueError)):
def myfunc(a):
if a == 0:
raise error_class
return 1
f = implemented_function('f', myfunc)
expr = f(val)
assert expr == f(val)
def test_imps_wrong_args():
raises(ValueError, lambda: implemented_function(sin, lambda x: x))
def test_lambdify_imps():
# Test lambdify with implemented functions
# first test basic (sympy) lambdify
f = sympy.cos
assert lambdify(x, f(x))(0) == 1
assert lambdify(x, 1 + f(x))(0) == 2
assert lambdify((x, y), y + f(x))(0, 1) == 2
# make an implemented function and test
f = implemented_function("f", lambda x: x + 100)
assert lambdify(x, f(x))(0) == 100
assert lambdify(x, 1 + f(x))(0) == 101
assert lambdify((x, y), y + f(x))(0, 1) == 101
# Can also handle tuples, lists, dicts as expressions
lam = lambdify(x, (f(x), x))
assert lam(3) == (103, 3)
lam = lambdify(x, [f(x), x])
assert lam(3) == [103, 3]
lam = lambdify(x, [f(x), (f(x), x)])
assert lam(3) == [103, (103, 3)]
lam = lambdify(x, {f(x): x})
assert lam(3) == {103: 3}
lam = lambdify(x, {f(x): x})
assert lam(3) == {103: 3}
lam = lambdify(x, {x: f(x)})
assert lam(3) == {3: 103}
# Check that imp preferred to other namespaces by default
d = {'f': lambda x: x + 99}
lam = lambdify(x, f(x), d)
assert lam(3) == 103
# Unless flag passed
lam = lambdify(x, f(x), d, use_imps=False)
assert lam(3) == 102
def test_dummification():
t = symbols('t')
F = Function('F')
G = Function('G')
#"\alpha" is not a valid Python variable name
#lambdify should sub in a dummy for it, and return
#without a syntax error
alpha = symbols(r'\alpha')
some_expr = 2 * F(t)**2 / G(t)
lam = lambdify((F(t), G(t)), some_expr)
assert lam(3, 9) == 2
lam = lambdify(sin(t), 2 * sin(t)**2)
assert lam(F(t)) == 2 * F(t)**2
#Test that \alpha was properly dummified
lam = lambdify((alpha, t), 2*alpha + t)
assert lam(2, 1) == 5
raises(SyntaxError, lambda: lambdify(F(t) * G(t), F(t) * G(t) + 5))
raises(SyntaxError, lambda: lambdify(2 * F(t), 2 * F(t) + 5))
raises(SyntaxError, lambda: lambdify(2 * F(t), 4 * F(t) + 5))
def test_curly_matrix_symbol():
# Issue #15009
curlyv = sympy.MatrixSymbol("{v}", 2, 1)
lam = lambdify(curlyv, curlyv)
assert lam(1)==1
lam = lambdify(curlyv, curlyv, dummify=True)
assert lam(1)==1
def test_python_keywords():
# Test for issue 7452. The automatic dummification should ensure use of
# Python reserved keywords as symbol names will create valid lambda
# functions. This is an additional regression test.
python_if = symbols('if')
expr = python_if / 2
f = lambdify(python_if, expr)
assert f(4.0) == 2.0
def test_lambdify_docstring():
func = lambdify((w, x, y, z), w + x + y + z)
ref = (
"Created with lambdify. Signature:\n\n"
"func(w, x, y, z)\n\n"
"Expression:\n\n"
"w + x + y + z"
).splitlines()
assert func.__doc__.splitlines()[:len(ref)] == ref
syms = symbols('a1:26')
func = lambdify(syms, sum(syms))
ref = (
"Created with lambdify. Signature:\n\n"
"func(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15,\n"
" a16, a17, a18, a19, a20, a21, a22, a23, a24, a25)\n\n"
"Expression:\n\n"
"a1 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a2 + a20 +..."
).splitlines()
assert func.__doc__.splitlines()[:len(ref)] == ref
#================== Test special printers ==========================
def test_special_printers():
from sympy.printing.lambdarepr import IntervalPrinter
def intervalrepr(expr):
return IntervalPrinter().doprint(expr)
expr = sqrt(sqrt(2) + sqrt(3)) + S.Half
func0 = lambdify((), expr, modules="mpmath", printer=intervalrepr)
func1 = lambdify((), expr, modules="mpmath", printer=IntervalPrinter)
func2 = lambdify((), expr, modules="mpmath", printer=IntervalPrinter())
mpi = type(mpmath.mpi(1, 2))
assert isinstance(func0(), mpi)
assert isinstance(func1(), mpi)
assert isinstance(func2(), mpi)
# To check Is lambdify loggamma works for mpmath or not
exp1 = lambdify(x, loggamma(x), 'mpmath')(5)
exp2 = lambdify(x, loggamma(x), 'mpmath')(1.8)
exp3 = lambdify(x, loggamma(x), 'mpmath')(15)
exp_ls = [exp1, exp2, exp3]
sol1 = mpmath.loggamma(5)
sol2 = mpmath.loggamma(1.8)
sol3 = mpmath.loggamma(15)
sol_ls = [sol1, sol2, sol3]
assert exp_ls == sol_ls
def test_true_false():
# We want exact is comparison here, not just ==
assert lambdify([], true)() is True
assert lambdify([], false)() is False
def test_issue_2790():
assert lambdify((x, (y, z)), x + y)(1, (2, 4)) == 3
assert lambdify((x, (y, (w, z))), w + x + y + z)(1, (2, (3, 4))) == 10
assert lambdify(x, x + 1, dummify=False)(1) == 2
def test_issue_12092():
f = implemented_function('f', lambda x: x**2)
assert f(f(2)).evalf() == Float(16)
def test_issue_14911():
class Variable(sympy.Symbol):
def _sympystr(self, printer):
return printer.doprint(self.name)
_lambdacode = _sympystr
_numpycode = _sympystr
x = Variable('x')
y = 2 * x
code = LambdaPrinter().doprint(y)
assert code.replace(' ', '') == '2*x'
def test_ITE():
assert lambdify((x, y, z), ITE(x, y, z))(True, 5, 3) == 5
assert lambdify((x, y, z), ITE(x, y, z))(False, 5, 3) == 3
def test_Min_Max():
# see gh-10375
assert lambdify((x, y, z), Min(x, y, z))(1, 2, 3) == 1
assert lambdify((x, y, z), Max(x, y, z))(1, 2, 3) == 3
def test_Indexed():
# Issue #10934
if not numpy:
skip("numpy not installed")
a = IndexedBase('a')
i, j = symbols('i j')
b = numpy.array([[1, 2], [3, 4]])
assert lambdify(a, Sum(a[x, y], (x, 0, 1), (y, 0, 1)))(b) == 10
def test_issue_12173():
#test for issue 12173
expr1 = lambdify((x, y), uppergamma(x, y),"mpmath")(1, 2)
expr2 = lambdify((x, y), lowergamma(x, y),"mpmath")(1, 2)
assert expr1 == uppergamma(1, 2).evalf()
assert expr2 == lowergamma(1, 2).evalf()
def test_issue_13642():
if not numpy:
skip("numpy not installed")
f = lambdify(x, sinc(x))
assert Abs(f(1) - sinc(1)).n() < 1e-15
def test_sinc_mpmath():
f = lambdify(x, sinc(x), "mpmath")
assert Abs(f(1) - sinc(1)).n() < 1e-15
def test_lambdify_dummy_arg():
d1 = Dummy()
f1 = lambdify(d1, d1 + 1, dummify=False)
assert f1(2) == 3
f1b = lambdify(d1, d1 + 1)
assert f1b(2) == 3
d2 = Dummy('x')
f2 = lambdify(d2, d2 + 1)
assert f2(2) == 3
f3 = lambdify([[d2]], d2 + 1)
assert f3([2]) == 3
def test_lambdify_mixed_symbol_dummy_args():
d = Dummy()
# Contrived example of name clash
dsym = symbols(str(d))
f = lambdify([d, dsym], d - dsym)
assert f(4, 1) == 3
def test_numpy_array_arg():
# Test for issue 14655 (numpy part)
if not numpy:
skip("numpy not installed")
f = lambdify([[x, y]], x*x + y, 'numpy')
assert f(numpy.array([2.0, 1.0])) == 5
def test_scipy_fns():
if not scipy:
skip("scipy not installed")
single_arg_sympy_fns = [Ei, erf, erfc, factorial, gamma, loggamma, digamma, Si, Ci]
single_arg_scipy_fns = [scipy.special.expi, scipy.special.erf, scipy.special.erfc,
scipy.special.factorial, scipy.special.gamma, scipy.special.gammaln,
scipy.special.psi, scipy.special.sici, scipy.special.sici]
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()
scipy_result = scipy_fn(tv)
# SciPy's sici returns a tuple with both Si and Ci present in it
# which needs to be unpacked
if sympy_fn == Si:
scipy_result = scipy_fn(tv)[0]
if sympy_fn == Ci:
scipy_result = scipy_fn(tv)[1]
assert abs(f(tv) - sympy_result) < 1e-13*(1 + abs(sympy_result))
assert abs(f(tv) - scipy_result) < 1e-13*(1 + abs(sympy_result))
double_arg_sympy_fns = [RisingFactorial, besselj, bessely, besseli,
besselk, polygamma]
double_arg_scipy_fns = [scipy.special.poch, scipy.special.jv,
scipy.special.yv, scipy.special.iv, scipy.special.kv, scipy.special.polygamma]
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 requires a real valued 2nd argument for: poch, polygamma
if sympy_fn in (RisingFactorial, polygamma):
tv2 = numpy.real(tv2)
if sympy_fn == polygamma:
tv1 = abs(int(tv1)) # first argument to polygamma must be a non-negative integral.
sympy_result = sympy_fn(tv1, tv2).evalf()
assert abs(f(tv1, tv2) - sympy_result) < 1e-13*(1 + abs(sympy_result))
assert abs(f(tv1, tv2) - scipy_fn(tv1, tv2)) < 1e-13*(1 + abs(sympy_result))
def test_scipy_polys():
if not scipy:
skip("scipy not installed")
numpy.random.seed(0)
params = symbols('n k a b')
# list polynomials with the number of parameters
polys = [
(chebyshevt, 1),
(chebyshevu, 1),
(legendre, 1),
(hermite, 1),
(laguerre, 1),
(gegenbauer, 2),
(assoc_legendre, 2),
(assoc_laguerre, 2),
(jacobi, 3)
]
msg = \
"The random test of the function {func} with the arguments " \
"{args} had failed because the SymPy result {sympy_result} " \
"and SciPy result {scipy_result} had failed to converge " \
"within the tolerance {tol} " \
"(Actual absolute difference : {diff})"
for sympy_fn, num_params in polys:
args = params[:num_params] + (x,)
f = lambdify(args, sympy_fn(*args))
for _ in range(10):
tn = numpy.random.randint(3, 10)
tparams = tuple(numpy.random.uniform(0, 5, size=num_params-1))
tv = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5)
# SciPy supports hermite for real arguments only
if sympy_fn == hermite:
tv = numpy.real(tv)
# assoc_legendre needs x in (-1, 1) and integer param at most n
if sympy_fn == assoc_legendre:
tv = numpy.random.uniform(-1, 1)
tparams = tuple(numpy.random.randint(1, tn, size=1))
vals = (tn,) + tparams + (tv,)
scipy_result = f(*vals)
sympy_result = sympy_fn(*vals).evalf()
atol = 1e-9*(1 + abs(sympy_result))
diff = abs(scipy_result - sympy_result)
try:
assert diff < atol
except TypeError:
raise AssertionError(
msg.format(
func=repr(sympy_fn),
args=repr(vals),
sympy_result=repr(sympy_result),
scipy_result=repr(scipy_result),
diff=diff,
tol=atol)
)
def test_lambdify_inspect():
f = lambdify(x, x**2)
# Test that inspect.getsource works but don't hard-code implementation
# details
assert 'x**2' in inspect.getsource(f)
def test_issue_14941():
x, y = Dummy(), Dummy()
# test dict
f1 = lambdify([x, y], {x: 3, y: 3}, 'sympy')
assert f1(2, 3) == {2: 3, 3: 3}
# test tuple
f2 = lambdify([x, y], (y, x), 'sympy')
assert f2(2, 3) == (3, 2)
f2b = lambdify([], (1,)) # gh-23224
assert f2b() == (1,)
# test list
f3 = lambdify([x, y], [y, x], 'sympy')
assert f3(2, 3) == [3, 2]
def test_lambdify_Derivative_arg_issue_16468():
f = Function('f')(x)
fx = f.diff()
assert lambdify((f, fx), f + fx)(10, 5) == 15
assert eval(lambdastr((f, fx), f/fx))(10, 5) == 2
raises(SyntaxError, lambda:
eval(lambdastr((f, fx), f/fx, dummify=False)))
assert eval(lambdastr((f, fx), f/fx, dummify=True))(10, 5) == 2
assert eval(lambdastr((fx, f), f/fx, dummify=True))(S(10), 5) == S.Half
assert lambdify(fx, 1 + fx)(41) == 42
assert eval(lambdastr(fx, 1 + fx, dummify=True))(41) == 42
def test_imag_real():
f_re = lambdify([z], sympy.re(z))
val = 3+2j
assert f_re(val) == val.real
f_im = lambdify([z], sympy.im(z)) # see #15400
assert f_im(val) == val.imag
def test_MatrixSymbol_issue_15578():
if not numpy:
skip("numpy not installed")
A = MatrixSymbol('A', 2, 2)
A0 = numpy.array([[1, 2], [3, 4]])
f = lambdify(A, A**(-1))
assert numpy.allclose(f(A0), numpy.array([[-2., 1.], [1.5, -0.5]]))
g = lambdify(A, A**3)
assert numpy.allclose(g(A0), numpy.array([[37, 54], [81, 118]]))
def test_issue_15654():
if not scipy:
skip("scipy not installed")
from sympy.abc import n, l, r, Z
from sympy.physics import hydrogen
nv, lv, rv, Zv = 1, 0, 3, 1
sympy_value = hydrogen.R_nl(nv, lv, rv, Zv).evalf()
f = lambdify((n, l, r, Z), hydrogen.R_nl(n, l, r, Z))
scipy_value = f(nv, lv, rv, Zv)
assert abs(sympy_value - scipy_value) < 1e-15
def test_issue_15827():
if not numpy:
skip("numpy not installed")
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 2, 3)
C = MatrixSymbol("C", 3, 4)
D = MatrixSymbol("D", 4, 5)
k=symbols("k")
f = lambdify(A, (2*k)*A)
g = lambdify(A, (2+k)*A)
h = lambdify(A, 2*A)
i = lambdify((B, C, D), 2*B*C*D)
assert numpy.array_equal(f(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \
numpy.array([[2*k, 4*k, 6*k], [2*k, 4*k, 6*k], [2*k, 4*k, 6*k]], dtype=object))
assert numpy.array_equal(g(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \
numpy.array([[k + 2, 2*k + 4, 3*k + 6], [k + 2, 2*k + 4, 3*k + 6], \
[k + 2, 2*k + 4, 3*k + 6]], dtype=object))
assert numpy.array_equal(h(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \
numpy.array([[2, 4, 6], [2, 4, 6], [2, 4, 6]]))
assert numpy.array_equal(i(numpy.array([[1, 2, 3], [1, 2, 3]]), numpy.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]), \
numpy.array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])), numpy.array([[ 120, 240, 360, 480, 600], \
[ 120, 240, 360, 480, 600]]))
def test_issue_16930():
if not scipy:
skip("scipy not installed")
x = symbols("x")
f = lambda x: S.GoldenRatio * x**2
f_ = lambdify(x, f(x), modules='scipy')
assert f_(1) == scipy.constants.golden_ratio
def test_issue_17898():
if not scipy:
skip("scipy not installed")
x = symbols("x")
f_ = lambdify([x], sympy.LambertW(x,-1), modules='scipy')
assert f_(0.1) == mpmath.lambertw(0.1, -1)
def test_issue_13167_21411():
if not numpy:
skip("numpy not installed")
f1 = lambdify(x, sympy.Heaviside(x))
f2 = lambdify(x, sympy.Heaviside(x, 1))
res1 = f1([-1, 0, 1])
res2 = f2([-1, 0, 1])
assert Abs(res1[0]).n() < 1e-15 # First functionality: only one argument passed
assert Abs(res1[1] - 1/2).n() < 1e-15
assert Abs(res1[2] - 1).n() < 1e-15
assert Abs(res2[0]).n() < 1e-15 # Second functionality: two arguments passed
assert Abs(res2[1] - 1).n() < 1e-15
assert Abs(res2[2] - 1).n() < 1e-15
def test_single_e():
f = lambdify(x, E)
assert f(23) == exp(1.0)
def test_issue_16536():
if not scipy:
skip("scipy not installed")
a = symbols('a')
f1 = lowergamma(a, x)
F = lambdify((a, x), f1, modules='scipy')
assert abs(lowergamma(1, 3) - F(1, 3)) <= 1e-10
f2 = uppergamma(a, x)
F = lambdify((a, x), f2, modules='scipy')
assert abs(uppergamma(1, 3) - F(1, 3)) <= 1e-10
def test_issue_22726():
if not numpy:
skip("numpy not installed")
x1, x2 = symbols('x1 x2')
f = Max(S.Zero, Min(x1, x2))
g = derive_by_array(f, (x1, x2))
G = lambdify((x1, x2), g, modules='numpy')
point = {x1: 1, x2: 2}
assert (abs(g.subs(point) - G(*point.values())) <= 1e-10).all()
def test_issue_22739():
if not numpy:
skip("numpy not installed")
x1, x2 = symbols('x1 x2')
f = Heaviside(Min(x1, x2))
F = lambdify((x1, x2), f, modules='numpy')
point = {x1: 1, x2: 2}
assert abs(f.subs(point) - F(*point.values())) <= 1e-10
def test_issue_22992():
if not numpy:
skip("numpy not installed")
a, t = symbols('a t')
expr = a*(log(cot(t/2)) - cos(t))
F = lambdify([a, t], expr, 'numpy')
point = {a: 10, t: 2}
assert abs(expr.subs(point) - F(*point.values())) <= 1e-10
# Standard math
F = lambdify([a, t], expr)
assert abs(expr.subs(point) - F(*point.values())) <= 1e-10
def test_issue_19764():
if not numpy:
skip("numpy not installed")
expr = Array([x, x**2])
f = lambdify(x, expr, 'numpy')
assert f(1).__class__ == numpy.ndarray
def test_issue_20070():
if not numba:
skip("numba not installed")
f = lambdify(x, sin(x), 'numpy')
assert numba.jit(f)(1)==0.8414709848078965
def test_fresnel_integrals_scipy():
if not scipy:
skip("scipy not installed")
f1 = fresnelc(x)
f2 = fresnels(x)
F1 = lambdify(x, f1, modules='scipy')
F2 = lambdify(x, f2, modules='scipy')
assert abs(fresnelc(1.3) - F1(1.3)) <= 1e-10
assert abs(fresnels(1.3) - F2(1.3)) <= 1e-10
def test_beta_scipy():
if not scipy:
skip("scipy not installed")
f = beta(x, y)
F = lambdify((x, y), f, modules='scipy')
assert abs(beta(1.3, 2.3) - F(1.3, 2.3)) <= 1e-10
def test_beta_math():
f = beta(x, y)
F = lambdify((x, y), f, modules='math')
assert abs(beta(1.3, 2.3) - F(1.3, 2.3)) <= 1e-10
def test_betainc_scipy():
if not scipy:
skip("scipy not installed")
f = betainc(w, x, y, z)
F = lambdify((w, x, y, z), f, modules='scipy')
assert abs(betainc(1.4, 3.1, 0.1, 0.5) - F(1.4, 3.1, 0.1, 0.5)) <= 1e-10
def test_betainc_regularized_scipy():
if not scipy:
skip("scipy not installed")
f = betainc_regularized(w, x, y, z)
F = lambdify((w, x, y, z), f, modules='scipy')
assert abs(betainc_regularized(0.2, 3.5, 0.1, 1) - F(0.2, 3.5, 0.1, 1)) <= 1e-10
def test_numpy_special_math():
if not numpy:
skip("numpy not installed")
funcs = [expm1, log1p, exp2, log2, log10, hypot, logaddexp, logaddexp2]
for func in funcs:
if 2 in func.nargs:
expr = func(x, y)
args = (x, y)
num_args = (0.3, 0.4)
elif 1 in func.nargs:
expr = func(x)
args = (x,)
num_args = (0.3,)
else:
raise NotImplementedError("Need to handle other than unary & binary functions in test")
f = lambdify(args, expr)
result = f(*num_args)
reference = expr.subs(dict(zip(args, num_args))).evalf()
assert numpy.allclose(result, float(reference))
lae2 = lambdify((x, y), logaddexp2(log2(x), log2(y)))
assert abs(2.0**lae2(1e-50, 2.5e-50) - 3.5e-50) < 1e-62 # from NumPy's docstring
def test_scipy_special_math():
if not scipy:
skip("scipy not installed")
cm1 = lambdify((x,), cosm1(x), modules='scipy')
assert abs(cm1(1e-20) + 5e-41) < 1e-200
have_scipy_1_10plus = tuple(map(int, scipy.version.version.split('.')[:2])) >= (1, 10)
if have_scipy_1_10plus:
cm2 = lambdify((x, y), powm1(x, y), modules='scipy')
assert abs(cm2(1.2, 1e-9) - 1.82321557e-10) < 1e-17
def test_scipy_bernoulli():
if not scipy:
skip("scipy not installed")
bern = lambdify((x,), bernoulli(x), modules='scipy')
assert bern(1) == 0.5
def test_scipy_harmonic():
if not scipy:
skip("scipy not installed")
hn = lambdify((x,), harmonic(x), modules='scipy')
assert hn(2) == 1.5
hnm = lambdify((x, y), harmonic(x, y), modules='scipy')
assert hnm(2, 2) == 1.25
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 "officially" support this,
# depends on numpy __array_function__ support
if not cupy:
skip("CuPy not installed")
f = lambdify([[x, y]], x*x + y, 'numpy')
result = f(cupy.array([2.0, 1.0]))
assert result == 5
assert "cupy" in str(type(result))
def test_cupy_dotproduct():
if not cupy:
skip("CuPy not installed")
A = Matrix([x, y, z])
f1 = lambdify([x, y, z], DotProduct(A, A), modules='cupy')
f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='cupy')
f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='cupy')
f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='cupy')
assert f1(1, 2, 3) == \
f2(1, 2, 3) == \
f3(1, 2, 3) == \
f4(1, 2, 3) == \
cupy.array([14])
def test_jax_array_arg():
if not jax:
skip("JAX not installed")
f = lambdify([[x, y]], x*x + y, 'jax')
result = f(jax.numpy.array([2.0, 1.0]))
assert result == 5
assert "jax" in str(type(result))
def test_jax_array_arg_using_numpy():
if not jax:
skip("JAX not installed")
f = lambdify([[x, y]], x*x + y, 'numpy')
result = f(jax.numpy.array([2.0, 1.0]))
assert result == 5
assert "jax" in str(type(result))
def test_jax_dotproduct():
if not jax:
skip("JAX not installed")
A = Matrix([x, y, z])
f1 = lambdify([x, y, z], DotProduct(A, A), modules='jax')
f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='jax')
f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='jax')
f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='jax')
assert f1(1, 2, 3) == \
f2(1, 2, 3) == \
f3(1, 2, 3) == \
f4(1, 2, 3) == \
jax.numpy.array([14])
def test_lambdify_cse():
def dummy_cse(exprs):
return (), exprs
def minmem(exprs):
from sympy.simplify.cse_main import cse_release_variables, cse
return cse(exprs, postprocess=cse_release_variables)
class Case:
def __init__(self, *, args, exprs, num_args, requires_numpy=False):
self.args = args
self.exprs = exprs
self.num_args = num_args
subs_dict = dict(zip(self.args, self.num_args))
self.ref = [e.subs(subs_dict).evalf() for e in exprs]
self.requires_numpy = requires_numpy
def lambdify(self, *, cse):
return lambdify(self.args, self.exprs, cse=cse)
def assertAllClose(self, result, *, abstol=1e-15, reltol=1e-15):
if self.requires_numpy:
assert all(numpy.allclose(result[i], numpy.asarray(r, dtype=float),
rtol=reltol, atol=abstol)
for i, r in enumerate(self.ref))
return
for i, r in enumerate(self.ref):
abs_err = abs(result[i] - r)
if r == 0:
assert abs_err < abstol
else:
assert abs_err/abs(r) < reltol
cases = [
Case(
args=(x, y, z),
exprs=[
x + y + z,
x + y - z,
2*x + 2*y - z,
(x+y)**2 + (y+z)**2,
],
num_args=(2., 3., 4.)
),
Case(
args=(x, y, z),
exprs=[
x + sympy.Heaviside(x),
y + sympy.Heaviside(x),
z + sympy.Heaviside(x, 1),
z/sympy.Heaviside(x, 1)
],
num_args=(0., 3., 4.)
),
Case(
args=(x, y, z),
exprs=[
x + sinc(y),
y + sinc(y),
z - sinc(y)
],
num_args=(0.1, 0.2, 0.3)
),
Case(
args=(x, y, z),
exprs=[
Matrix([[x, x*y], [sin(z) + 4, x**z]]),
x*y+sin(z)-x**z,
Matrix([x*x, sin(z), x**z])
],
num_args=(1.,2.,3.),
requires_numpy=True
),
Case(
args=(x, y),
exprs=[(x + y - 1)**2, x, x + y,
(x + y)/(2*x + 1) + (x + y - 1)**2, (2*x + 1)**(x + y)],
num_args=(1,2)
)
]
for case in cases:
if not numpy and case.requires_numpy:
continue
for cse in [False, True, minmem, dummy_cse]:
f = case.lambdify(cse=cse)
result = f(*case.num_args)
case.assertAllClose(result)
def test_deprecated_set():
with warns_deprecated_sympy():
lambdify({x, y}, x + y)
def test_issue_13881():
if not numpy:
skip("numpy not installed.")
X = MatrixSymbol('X', 3, 1)
f = lambdify(X, X.T*X, 'numpy')
assert f(numpy.array([1, 2, 3])) == 14
assert f(numpy.array([3, 2, 1])) == 14
f = lambdify(X, X*X.T, 'numpy')
assert f(numpy.array([1, 2, 3])) == 14
assert f(numpy.array([3, 2, 1])) == 14
f = lambdify(X, (X*X.T)*X, 'numpy')
arr1 = numpy.array([[1], [2], [3]])
arr2 = numpy.array([[14],[28],[42]])
assert numpy.array_equal(f(arr1), arr2)
def test_23536_lambdify_cse_dummy():
f = Function('x')(y)
g = Function('w')(y)
expr = z + (f**4 + g**5)*(f**3 + (g*f)**3)
expr = expr.expand()
eval_expr = lambdify(((f, g), z), expr, cse=True)
ans = eval_expr((1.0, 2.0), 3.0) # shouldn't raise NameError
assert ans == 300.0 # not a list and value is 300
|
6289b7f58ab1a9bee63b4171491aac3a6c5252faf009a391744e1effbf181889 | import itertools
from sympy.core import S
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.function import Function
from sympy.core.mul import Mul
from sympy.core.numbers import Number, Rational
from sympy.core.power import Pow
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import Symbol
from sympy.core.sympify import SympifyError
from sympy.printing.conventions import requires_partial
from sympy.printing.precedence import PRECEDENCE, precedence, precedence_traditional
from sympy.printing.printer import Printer, print_function
from sympy.printing.str import sstr
from sympy.utilities.iterables import has_variety
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.printing.pretty.pretty_symbology import hobj, vobj, xobj, \
xsym, pretty_symbol, pretty_atom, pretty_use_unicode, greek_unicode, U, \
pretty_try_use_unicode, annotated
# rename for usage from outside
pprint_use_unicode = pretty_use_unicode
pprint_try_use_unicode = pretty_try_use_unicode
class PrettyPrinter(Printer):
"""Printer, which converts an expression into 2D ASCII-art figure."""
printmethod = "_pretty"
_default_settings = {
"order": None,
"full_prec": "auto",
"use_unicode": None,
"wrap_line": True,
"num_columns": None,
"use_unicode_sqrt_char": True,
"root_notation": True,
"mat_symbol_style": "plain",
"imaginary_unit": "i",
"perm_cyclic": True
}
def __init__(self, settings=None):
Printer.__init__(self, settings)
if not isinstance(self._settings['imaginary_unit'], str):
raise TypeError("'imaginary_unit' must a string, not {}".format(self._settings['imaginary_unit']))
elif self._settings['imaginary_unit'] not in ("i", "j"):
raise ValueError("'imaginary_unit' must be either 'i' or 'j', not '{}'".format(self._settings['imaginary_unit']))
def emptyPrinter(self, expr):
return prettyForm(str(expr))
@property
def _use_unicode(self):
if self._settings['use_unicode']:
return True
else:
return pretty_use_unicode()
def doprint(self, expr):
return self._print(expr).render(**self._settings)
# empty op so _print(stringPict) returns the same
def _print_stringPict(self, e):
return e
def _print_basestring(self, e):
return prettyForm(e)
def _print_atan2(self, e):
pform = prettyForm(*self._print_seq(e.args).parens())
pform = prettyForm(*pform.left('atan2'))
return pform
def _print_Symbol(self, e, bold_name=False):
symb = pretty_symbol(e.name, bold_name)
return prettyForm(symb)
_print_RandomSymbol = _print_Symbol
def _print_MatrixSymbol(self, e):
return self._print_Symbol(e, self._settings['mat_symbol_style'] == "bold")
def _print_Float(self, e):
# we will use StrPrinter's Float printer, but we need to handle the
# full_prec ourselves, according to the self._print_level
full_prec = self._settings["full_prec"]
if full_prec == "auto":
full_prec = self._print_level == 1
return prettyForm(sstr(e, full_prec=full_prec))
def _print_Cross(self, e):
vec1 = e._expr1
vec2 = e._expr2
pform = self._print(vec2)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN'))))
pform = prettyForm(*pform.left(')'))
pform = prettyForm(*pform.left(self._print(vec1)))
pform = prettyForm(*pform.left('('))
return pform
def _print_Curl(self, e):
vec = e._expr
pform = self._print(vec)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN'))))
pform = prettyForm(*pform.left(self._print(U('NABLA'))))
return pform
def _print_Divergence(self, e):
vec = e._expr
pform = self._print(vec)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR'))))
pform = prettyForm(*pform.left(self._print(U('NABLA'))))
return pform
def _print_Dot(self, e):
vec1 = e._expr1
vec2 = e._expr2
pform = self._print(vec2)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR'))))
pform = prettyForm(*pform.left(')'))
pform = prettyForm(*pform.left(self._print(vec1)))
pform = prettyForm(*pform.left('('))
return pform
def _print_Gradient(self, e):
func = e._expr
pform = self._print(func)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('NABLA'))))
return pform
def _print_Laplacian(self, e):
func = e._expr
pform = self._print(func)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('INCREMENT'))))
return pform
def _print_Atom(self, e):
try:
# print atoms like Exp1 or Pi
return prettyForm(pretty_atom(e.__class__.__name__, printer=self))
except KeyError:
return self.emptyPrinter(e)
# Infinity inherits from Number, so we have to override _print_XXX order
_print_Infinity = _print_Atom
_print_NegativeInfinity = _print_Atom
_print_EmptySet = _print_Atom
_print_Naturals = _print_Atom
_print_Naturals0 = _print_Atom
_print_Integers = _print_Atom
_print_Rationals = _print_Atom
_print_Complexes = _print_Atom
_print_EmptySequence = _print_Atom
def _print_Reals(self, e):
if self._use_unicode:
return self._print_Atom(e)
else:
inf_list = ['-oo', 'oo']
return self._print_seq(inf_list, '(', ')')
def _print_subfactorial(self, e):
x = e.args[0]
pform = self._print(x)
# Add parentheses if needed
if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol):
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left('!'))
return pform
def _print_factorial(self, e):
x = e.args[0]
pform = self._print(x)
# Add parentheses if needed
if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol):
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.right('!'))
return pform
def _print_factorial2(self, e):
x = e.args[0]
pform = self._print(x)
# Add parentheses if needed
if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol):
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.right('!!'))
return pform
def _print_binomial(self, e):
n, k = e.args
n_pform = self._print(n)
k_pform = self._print(k)
bar = ' '*max(n_pform.width(), k_pform.width())
pform = prettyForm(*k_pform.above(bar))
pform = prettyForm(*pform.above(n_pform))
pform = prettyForm(*pform.parens('(', ')'))
pform.baseline = (pform.baseline + 1)//2
return pform
def _print_Relational(self, e):
op = prettyForm(' ' + xsym(e.rel_op) + ' ')
l = self._print(e.lhs)
r = self._print(e.rhs)
pform = prettyForm(*stringPict.next(l, op, r), binding=prettyForm.OPEN)
return pform
def _print_Not(self, e):
from sympy.logic.boolalg import (Equivalent, Implies)
if self._use_unicode:
arg = e.args[0]
pform = self._print(arg)
if isinstance(arg, Equivalent):
return self._print_Equivalent(arg, altchar="\N{LEFT RIGHT DOUBLE ARROW WITH STROKE}")
if isinstance(arg, Implies):
return self._print_Implies(arg, altchar="\N{RIGHTWARDS ARROW WITH STROKE}")
if arg.is_Boolean and not arg.is_Not:
pform = prettyForm(*pform.parens())
return prettyForm(*pform.left("\N{NOT SIGN}"))
else:
return self._print_Function(e)
def __print_Boolean(self, e, char, sort=True):
args = e.args
if sort:
args = sorted(e.args, key=default_sort_key)
arg = args[0]
pform = self._print(arg)
if arg.is_Boolean and not arg.is_Not:
pform = prettyForm(*pform.parens())
for arg in args[1:]:
pform_arg = self._print(arg)
if arg.is_Boolean and not arg.is_Not:
pform_arg = prettyForm(*pform_arg.parens())
pform = prettyForm(*pform.right(' %s ' % char))
pform = prettyForm(*pform.right(pform_arg))
return pform
def _print_And(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{LOGICAL AND}")
else:
return self._print_Function(e, sort=True)
def _print_Or(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{LOGICAL OR}")
else:
return self._print_Function(e, sort=True)
def _print_Xor(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{XOR}")
else:
return self._print_Function(e, sort=True)
def _print_Nand(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{NAND}")
else:
return self._print_Function(e, sort=True)
def _print_Nor(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{NOR}")
else:
return self._print_Function(e, sort=True)
def _print_Implies(self, e, altchar=None):
if self._use_unicode:
return self.__print_Boolean(e, altchar or "\N{RIGHTWARDS ARROW}", sort=False)
else:
return self._print_Function(e)
def _print_Equivalent(self, e, altchar=None):
if self._use_unicode:
return self.__print_Boolean(e, altchar or "\N{LEFT RIGHT DOUBLE ARROW}")
else:
return self._print_Function(e, sort=True)
def _print_conjugate(self, e):
pform = self._print(e.args[0])
return prettyForm( *pform.above( hobj('_', pform.width())) )
def _print_Abs(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens('|', '|'))
return pform
def _print_floor(self, e):
if self._use_unicode:
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens('lfloor', 'rfloor'))
return pform
else:
return self._print_Function(e)
def _print_ceiling(self, e):
if self._use_unicode:
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens('lceil', 'rceil'))
return pform
else:
return self._print_Function(e)
def _print_Derivative(self, deriv):
if requires_partial(deriv.expr) and self._use_unicode:
deriv_symbol = U('PARTIAL DIFFERENTIAL')
else:
deriv_symbol = r'd'
x = None
count_total_deriv = 0
for sym, num in reversed(deriv.variable_count):
s = self._print(sym)
ds = prettyForm(*s.left(deriv_symbol))
count_total_deriv += num
if (not num.is_Integer) or (num > 1):
ds = ds**prettyForm(str(num))
if x is None:
x = ds
else:
x = prettyForm(*x.right(' '))
x = prettyForm(*x.right(ds))
f = prettyForm(
binding=prettyForm.FUNC, *self._print(deriv.expr).parens())
pform = prettyForm(deriv_symbol)
if (count_total_deriv > 1) != False:
pform = pform**prettyForm(str(count_total_deriv))
pform = prettyForm(*pform.below(stringPict.LINE, x))
pform.baseline = pform.baseline + 1
pform = prettyForm(*stringPict.next(pform, f))
pform.binding = prettyForm.MUL
return pform
def _print_Cycle(self, dc):
from sympy.combinatorics.permutations import Permutation, Cycle
# for Empty Cycle
if dc == Cycle():
cyc = stringPict('')
return prettyForm(*cyc.parens())
dc_list = Permutation(dc.list()).cyclic_form
# for Identity Cycle
if dc_list == []:
cyc = self._print(dc.size - 1)
return prettyForm(*cyc.parens())
cyc = stringPict('')
for i in dc_list:
l = self._print(str(tuple(i)).replace(',', ''))
cyc = prettyForm(*cyc.right(l))
return cyc
def _print_Permutation(self, expr):
from sympy.combinatorics.permutations import Permutation, Cycle
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
sympy_deprecation_warning(
f"""
Setting Permutation.print_cyclic is deprecated. Instead use
init_printing(perm_cyclic={perm_cyclic}).
""",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-permutation-print_cyclic",
stacklevel=7,
)
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
return self._print_Cycle(Cycle(expr))
lower = expr.array_form
upper = list(range(len(lower)))
result = stringPict('')
first = True
for u, l in zip(upper, lower):
s1 = self._print(u)
s2 = self._print(l)
col = prettyForm(*s1.below(s2))
if first:
first = False
else:
col = prettyForm(*col.left(" "))
result = prettyForm(*result.right(col))
return prettyForm(*result.parens())
def _print_Integral(self, integral):
f = integral.function
# Add parentheses if arg involves addition of terms and
# create a pretty form for the argument
prettyF = self._print(f)
# XXX generalize parens
if f.is_Add:
prettyF = prettyForm(*prettyF.parens())
# dx dy dz ...
arg = prettyF
for x in integral.limits:
prettyArg = self._print(x[0])
# XXX qparens (parens if needs-parens)
if prettyArg.width() > 1:
prettyArg = prettyForm(*prettyArg.parens())
arg = prettyForm(*arg.right(' d', prettyArg))
# \int \int \int ...
firstterm = True
s = None
for lim in integral.limits:
# Create bar based on the height of the argument
h = arg.height()
H = h + 2
# XXX hack!
ascii_mode = not self._use_unicode
if ascii_mode:
H += 2
vint = vobj('int', H)
# Construct the pretty form with the integral sign and the argument
pform = prettyForm(vint)
pform.baseline = arg.baseline + (
H - h)//2 # covering the whole argument
if len(lim) > 1:
# Create pretty forms for endpoints, if definite integral.
# Do not print empty endpoints.
if len(lim) == 2:
prettyA = prettyForm("")
prettyB = self._print(lim[1])
if len(lim) == 3:
prettyA = self._print(lim[1])
prettyB = self._print(lim[2])
if ascii_mode: # XXX hack
# Add spacing so that endpoint can more easily be
# identified with the correct integral sign
spc = max(1, 3 - prettyB.width())
prettyB = prettyForm(*prettyB.left(' ' * spc))
spc = max(1, 4 - prettyA.width())
prettyA = prettyForm(*prettyA.right(' ' * spc))
pform = prettyForm(*pform.above(prettyB))
pform = prettyForm(*pform.below(prettyA))
if not ascii_mode: # XXX hack
pform = prettyForm(*pform.right(' '))
if firstterm:
s = pform # first term
firstterm = False
else:
s = prettyForm(*s.left(pform))
pform = prettyForm(*arg.left(s))
pform.binding = prettyForm.MUL
return pform
def _print_Product(self, expr):
func = expr.term
pretty_func = self._print(func)
horizontal_chr = xobj('_', 1)
corner_chr = xobj('_', 1)
vertical_chr = xobj('|', 1)
if self._use_unicode:
# use unicode corners
horizontal_chr = xobj('-', 1)
corner_chr = '\N{BOX DRAWINGS LIGHT DOWN AND HORIZONTAL}'
func_height = pretty_func.height()
first = True
max_upper = 0
sign_height = 0
for lim in expr.limits:
pretty_lower, pretty_upper = self.__print_SumProduct_Limits(lim)
width = (func_height + 2) * 5 // 3 - 2
sign_lines = [horizontal_chr + corner_chr + (horizontal_chr * (width-2)) + corner_chr + horizontal_chr]
for _ in range(func_height + 1):
sign_lines.append(' ' + vertical_chr + (' ' * (width-2)) + vertical_chr + ' ')
pretty_sign = stringPict('')
pretty_sign = prettyForm(*pretty_sign.stack(*sign_lines))
max_upper = max(max_upper, pretty_upper.height())
if first:
sign_height = pretty_sign.height()
pretty_sign = prettyForm(*pretty_sign.above(pretty_upper))
pretty_sign = prettyForm(*pretty_sign.below(pretty_lower))
if first:
pretty_func.baseline = 0
first = False
height = pretty_sign.height()
padding = stringPict('')
padding = prettyForm(*padding.stack(*[' ']*(height - 1)))
pretty_sign = prettyForm(*pretty_sign.right(padding))
pretty_func = prettyForm(*pretty_sign.right(pretty_func))
pretty_func.baseline = max_upper + sign_height//2
pretty_func.binding = prettyForm.MUL
return pretty_func
def __print_SumProduct_Limits(self, lim):
def print_start(lhs, rhs):
op = prettyForm(' ' + xsym("==") + ' ')
l = self._print(lhs)
r = self._print(rhs)
pform = prettyForm(*stringPict.next(l, op, r))
return pform
prettyUpper = self._print(lim[2])
prettyLower = print_start(lim[0], lim[1])
return prettyLower, prettyUpper
def _print_Sum(self, expr):
ascii_mode = not self._use_unicode
def asum(hrequired, lower, upper, use_ascii):
def adjust(s, wid=None, how='<^>'):
if not wid or len(s) > wid:
return s
need = wid - len(s)
if how in ('<^>', "<") or how not in list('<^>'):
return s + ' '*need
half = need//2
lead = ' '*half
if how == ">":
return " "*need + s
return lead + s + ' '*(need - len(lead))
h = max(hrequired, 2)
d = h//2
w = d + 1
more = hrequired % 2
lines = []
if use_ascii:
lines.append("_"*(w) + ' ')
lines.append(r"\%s`" % (' '*(w - 1)))
for i in range(1, d):
lines.append('%s\\%s' % (' '*i, ' '*(w - i)))
if more:
lines.append('%s)%s' % (' '*(d), ' '*(w - d)))
for i in reversed(range(1, d)):
lines.append('%s/%s' % (' '*i, ' '*(w - i)))
lines.append("/" + "_"*(w - 1) + ',')
return d, h + more, lines, more
else:
w = w + more
d = d + more
vsum = vobj('sum', 4)
lines.append("_"*(w))
for i in range(0, d):
lines.append('%s%s%s' % (' '*i, vsum[2], ' '*(w - i - 1)))
for i in reversed(range(0, d)):
lines.append('%s%s%s' % (' '*i, vsum[4], ' '*(w - i - 1)))
lines.append(vsum[8]*(w))
return d, h + 2*more, lines, more
f = expr.function
prettyF = self._print(f)
if f.is_Add: # add parens
prettyF = prettyForm(*prettyF.parens())
H = prettyF.height() + 2
# \sum \sum \sum ...
first = True
max_upper = 0
sign_height = 0
for lim in expr.limits:
prettyLower, prettyUpper = self.__print_SumProduct_Limits(lim)
max_upper = max(max_upper, prettyUpper.height())
# Create sum sign based on the height of the argument
d, h, slines, adjustment = asum(
H, prettyLower.width(), prettyUpper.width(), ascii_mode)
prettySign = stringPict('')
prettySign = prettyForm(*prettySign.stack(*slines))
if first:
sign_height = prettySign.height()
prettySign = prettyForm(*prettySign.above(prettyUpper))
prettySign = prettyForm(*prettySign.below(prettyLower))
if first:
# change F baseline so it centers on the sign
prettyF.baseline -= d - (prettyF.height()//2 -
prettyF.baseline)
first = False
# put padding to the right
pad = stringPict('')
pad = prettyForm(*pad.stack(*[' ']*h))
prettySign = prettyForm(*prettySign.right(pad))
# put the present prettyF to the right
prettyF = prettyForm(*prettySign.right(prettyF))
# adjust baseline of ascii mode sigma with an odd height so that it is
# exactly through the center
ascii_adjustment = ascii_mode if not adjustment else 0
prettyF.baseline = max_upper + sign_height//2 + ascii_adjustment
prettyF.binding = prettyForm.MUL
return prettyF
def _print_Limit(self, l):
e, z, z0, dir = l.args
E = self._print(e)
if precedence(e) <= PRECEDENCE["Mul"]:
E = prettyForm(*E.parens('(', ')'))
Lim = prettyForm('lim')
LimArg = self._print(z)
if self._use_unicode:
LimArg = prettyForm(*LimArg.right('\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{RIGHTWARDS ARROW}'))
else:
LimArg = prettyForm(*LimArg.right('->'))
LimArg = prettyForm(*LimArg.right(self._print(z0)))
if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity):
dir = ""
else:
if self._use_unicode:
dir = '\N{SUPERSCRIPT PLUS SIGN}' if str(dir) == "+" else '\N{SUPERSCRIPT MINUS}'
LimArg = prettyForm(*LimArg.right(self._print(dir)))
Lim = prettyForm(*Lim.below(LimArg))
Lim = prettyForm(*Lim.right(E), binding=prettyForm.MUL)
return Lim
def _print_matrix_contents(self, e):
"""
This method factors out what is essentially grid printing.
"""
M = e # matrix
Ms = {} # i,j -> pretty(M[i,j])
for i in range(M.rows):
for j in range(M.cols):
Ms[i, j] = self._print(M[i, j])
# h- and v- spacers
hsep = 2
vsep = 1
# max width for columns
maxw = [-1] * M.cols
for j in range(M.cols):
maxw[j] = max([Ms[i, j].width() for i in range(M.rows)] or [0])
# drawing result
D = None
for i in range(M.rows):
D_row = None
for j in range(M.cols):
s = Ms[i, j]
# reshape s to maxw
# XXX this should be generalized, and go to stringPict.reshape ?
assert s.width() <= maxw[j]
# hcenter it, +0.5 to the right 2
# ( it's better to align formula starts for say 0 and r )
# XXX this is not good in all cases -- maybe introduce vbaseline?
wdelta = maxw[j] - s.width()
wleft = wdelta // 2
wright = wdelta - wleft
s = prettyForm(*s.right(' '*wright))
s = prettyForm(*s.left(' '*wleft))
# we don't need vcenter cells -- this is automatically done in
# a pretty way because when their baselines are taking into
# account in .right()
if D_row is None:
D_row = s # first box in a row
continue
D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer
D_row = prettyForm(*D_row.right(s))
if D is None:
D = D_row # first row in a picture
continue
# v-spacer
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
if D is None:
D = prettyForm('') # Empty Matrix
return D
def _print_MatrixBase(self, e, lparens='[', rparens=']'):
D = self._print_matrix_contents(e)
D.baseline = D.height()//2
D = prettyForm(*D.parens(lparens, rparens))
return D
def _print_Determinant(self, e):
mat = e.arg
if mat.is_MatrixExpr:
from sympy.matrices.expressions.blockmatrix import BlockMatrix
if isinstance(mat, BlockMatrix):
return self._print_MatrixBase(mat.blocks, lparens='|', rparens='|')
D = self._print(mat)
D.baseline = D.height()//2
return prettyForm(*D.parens('|', '|'))
else:
return self._print_MatrixBase(mat, lparens='|', rparens='|')
def _print_TensorProduct(self, expr):
# This should somehow share the code with _print_WedgeProduct:
if self._use_unicode:
circled_times = "\u2297"
else:
circled_times = ".*"
return self._print_seq(expr.args, None, None, circled_times,
parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"])
def _print_WedgeProduct(self, expr):
# This should somehow share the code with _print_TensorProduct:
if self._use_unicode:
wedge_symbol = "\u2227"
else:
wedge_symbol = '/\\'
return self._print_seq(expr.args, None, None, wedge_symbol,
parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"])
def _print_Trace(self, e):
D = self._print(e.arg)
D = prettyForm(*D.parens('(',')'))
D.baseline = D.height()//2
D = prettyForm(*D.left('\n'*(0) + 'tr'))
return D
def _print_MatrixElement(self, expr):
from sympy.matrices import MatrixSymbol
if (isinstance(expr.parent, MatrixSymbol)
and expr.i.is_number and expr.j.is_number):
return self._print(
Symbol(expr.parent.name + '_%d%d' % (expr.i, expr.j)))
else:
prettyFunc = self._print(expr.parent)
prettyFunc = prettyForm(*prettyFunc.parens())
prettyIndices = self._print_seq((expr.i, expr.j), delimiter=', '
).parens(left='[', right=']')[0]
pform = prettyForm(binding=prettyForm.FUNC,
*stringPict.next(prettyFunc, prettyIndices))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyIndices
return pform
def _print_MatrixSlice(self, m):
# XXX works only for applied functions
from sympy.matrices import MatrixSymbol
prettyFunc = self._print(m.parent)
if not isinstance(m.parent, MatrixSymbol):
prettyFunc = prettyForm(*prettyFunc.parens())
def ppslice(x, dim):
x = list(x)
if x[2] == 1:
del x[2]
if x[0] == 0:
x[0] = ''
if x[1] == dim:
x[1] = ''
return prettyForm(*self._print_seq(x, delimiter=':'))
prettyArgs = self._print_seq((ppslice(m.rowslice, m.parent.rows),
ppslice(m.colslice, m.parent.cols)), delimiter=', ').parens(left='[', right=']')[0]
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform
def _print_Transpose(self, expr):
mat = expr.arg
pform = self._print(mat)
from sympy.matrices import MatrixSymbol, BlockMatrix
if (not isinstance(mat, MatrixSymbol) and
not isinstance(mat, BlockMatrix) and mat.is_MatrixExpr):
pform = prettyForm(*pform.parens())
pform = pform**(prettyForm('T'))
return pform
def _print_Adjoint(self, expr):
mat = expr.arg
pform = self._print(mat)
if self._use_unicode:
dag = prettyForm('\N{DAGGER}')
else:
dag = prettyForm('+')
from sympy.matrices import MatrixSymbol, BlockMatrix
if (not isinstance(mat, MatrixSymbol) and
not isinstance(mat, BlockMatrix) and mat.is_MatrixExpr):
pform = prettyForm(*pform.parens())
pform = pform**dag
return pform
def _print_BlockMatrix(self, B):
if B.blocks.shape == (1, 1):
return self._print(B.blocks[0, 0])
return self._print(B.blocks)
def _print_MatAdd(self, expr):
s = None
for item in expr.args:
pform = self._print(item)
if s is None:
s = pform # First element
else:
coeff = item.as_coeff_mmul()[0]
if S(coeff).could_extract_minus_sign():
s = prettyForm(*stringPict.next(s, ' '))
pform = self._print(item)
else:
s = prettyForm(*stringPict.next(s, ' + '))
s = prettyForm(*stringPict.next(s, pform))
return s
def _print_MatMul(self, expr):
args = list(expr.args)
from sympy.matrices.expressions.hadamard import HadamardProduct
from sympy.matrices.expressions.kronecker import KroneckerProduct
from sympy.matrices.expressions.matadd import MatAdd
for i, a in enumerate(args):
if (isinstance(a, (Add, MatAdd, HadamardProduct, KroneckerProduct))
and len(expr.args) > 1):
args[i] = prettyForm(*self._print(a).parens())
else:
args[i] = self._print(a)
return prettyForm.__mul__(*args)
def _print_Identity(self, expr):
if self._use_unicode:
return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL I}')
else:
return prettyForm('I')
def _print_ZeroMatrix(self, expr):
if self._use_unicode:
return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}')
else:
return prettyForm('0')
def _print_OneMatrix(self, expr):
if self._use_unicode:
return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ONE}')
else:
return prettyForm('1')
def _print_DotProduct(self, expr):
args = list(expr.args)
for i, a in enumerate(args):
args[i] = self._print(a)
return prettyForm.__mul__(*args)
def _print_MatPow(self, expr):
pform = self._print(expr.base)
from sympy.matrices import MatrixSymbol
if not isinstance(expr.base, MatrixSymbol) and expr.base.is_MatrixExpr:
pform = prettyForm(*pform.parens())
pform = pform**(self._print(expr.exp))
return pform
def _print_HadamardProduct(self, expr):
from sympy.matrices.expressions.hadamard import HadamardProduct
from sympy.matrices.expressions.matadd import MatAdd
from sympy.matrices.expressions.matmul import MatMul
if self._use_unicode:
delim = pretty_atom('Ring')
else:
delim = '.*'
return self._print_seq(expr.args, None, None, delim,
parenthesize=lambda x: isinstance(x, (MatAdd, MatMul, HadamardProduct)))
def _print_HadamardPower(self, expr):
# from sympy import MatAdd, MatMul
if self._use_unicode:
circ = pretty_atom('Ring')
else:
circ = self._print('.')
pretty_base = self._print(expr.base)
pretty_exp = self._print(expr.exp)
if precedence(expr.exp) < PRECEDENCE["Mul"]:
pretty_exp = prettyForm(*pretty_exp.parens())
pretty_circ_exp = prettyForm(
binding=prettyForm.LINE,
*stringPict.next(circ, pretty_exp)
)
return pretty_base**pretty_circ_exp
def _print_KroneckerProduct(self, expr):
from sympy.matrices.expressions.matadd import MatAdd
from sympy.matrices.expressions.matmul import MatMul
if self._use_unicode:
delim = ' \N{N-ARY CIRCLED TIMES OPERATOR} '
else:
delim = ' x '
return self._print_seq(expr.args, None, None, delim,
parenthesize=lambda x: isinstance(x, (MatAdd, MatMul)))
def _print_FunctionMatrix(self, X):
D = self._print(X.lamda.expr)
D = prettyForm(*D.parens('[', ']'))
return D
def _print_TransferFunction(self, expr):
if not expr.num == 1:
num, den = expr.num, expr.den
res = Mul(num, Pow(den, -1, evaluate=False), evaluate=False)
return self._print_Mul(res)
else:
return self._print(1)/self._print(expr.den)
def _print_Series(self, expr):
args = list(expr.args)
for i, a in enumerate(expr.args):
args[i] = prettyForm(*self._print(a).parens())
return prettyForm.__mul__(*args)
def _print_MIMOSeries(self, expr):
from sympy.physics.control.lti import MIMOParallel
args = list(expr.args)
pretty_args = []
for i, a in enumerate(reversed(args)):
if (isinstance(a, MIMOParallel) and len(expr.args) > 1):
expression = self._print(a)
expression.baseline = expression.height()//2
pretty_args.append(prettyForm(*expression.parens()))
else:
expression = self._print(a)
expression.baseline = expression.height()//2
pretty_args.append(expression)
return prettyForm.__mul__(*pretty_args)
def _print_Parallel(self, expr):
s = None
for item in expr.args:
pform = self._print(item)
if s is None:
s = pform # First element
else:
s = prettyForm(*stringPict.next(s))
s.baseline = s.height()//2
s = prettyForm(*stringPict.next(s, ' + '))
s = prettyForm(*stringPict.next(s, pform))
return s
def _print_MIMOParallel(self, expr):
from sympy.physics.control.lti import TransferFunctionMatrix
s = None
for item in expr.args:
pform = self._print(item)
if s is None:
s = pform # First element
else:
s = prettyForm(*stringPict.next(s))
s.baseline = s.height()//2
s = prettyForm(*stringPict.next(s, ' + '))
if isinstance(item, TransferFunctionMatrix):
s.baseline = s.height() - 1
s = prettyForm(*stringPict.next(s, pform))
# s.baseline = s.height()//2
return s
def _print_Feedback(self, expr):
from sympy.physics.control import TransferFunction, Series
num, tf = expr.sys1, TransferFunction(1, 1, expr.var)
num_arg_list = list(num.args) if isinstance(num, Series) else [num]
den_arg_list = list(expr.sys2.args) if \
isinstance(expr.sys2, Series) else [expr.sys2]
if isinstance(num, Series) and isinstance(expr.sys2, Series):
den = Series(*num_arg_list, *den_arg_list)
elif isinstance(num, Series) and isinstance(expr.sys2, TransferFunction):
if expr.sys2 == tf:
den = Series(*num_arg_list)
else:
den = Series(*num_arg_list, expr.sys2)
elif isinstance(num, TransferFunction) and isinstance(expr.sys2, Series):
if num == tf:
den = Series(*den_arg_list)
else:
den = Series(num, *den_arg_list)
else:
if num == tf:
den = Series(*den_arg_list)
elif expr.sys2 == tf:
den = Series(*num_arg_list)
else:
den = Series(*num_arg_list, *den_arg_list)
denom = prettyForm(*stringPict.next(self._print(tf)))
denom.baseline = denom.height()//2
denom = prettyForm(*stringPict.next(denom, ' + ')) if expr.sign == -1 \
else prettyForm(*stringPict.next(denom, ' - '))
denom = prettyForm(*stringPict.next(denom, self._print(den)))
return self._print(num)/denom
def _print_MIMOFeedback(self, expr):
from sympy.physics.control import MIMOSeries, TransferFunctionMatrix
inv_mat = self._print(MIMOSeries(expr.sys2, expr.sys1))
plant = self._print(expr.sys1)
_feedback = prettyForm(*stringPict.next(inv_mat))
_feedback = prettyForm(*stringPict.right("I + ", _feedback)) if expr.sign == -1 \
else prettyForm(*stringPict.right("I - ", _feedback))
_feedback = prettyForm(*stringPict.parens(_feedback))
_feedback.baseline = 0
_feedback = prettyForm(*stringPict.right(_feedback, '-1 '))
_feedback.baseline = _feedback.height()//2
_feedback = prettyForm.__mul__(_feedback, prettyForm(" "))
if isinstance(expr.sys1, TransferFunctionMatrix):
_feedback.baseline = _feedback.height() - 1
_feedback = prettyForm(*stringPict.next(_feedback, plant))
return _feedback
def _print_TransferFunctionMatrix(self, expr):
mat = self._print(expr._expr_mat)
mat.baseline = mat.height() - 1
subscript = greek_unicode['tau'] if self._use_unicode else r'{t}'
mat = prettyForm(*mat.right(subscript))
return mat
def _print_BasisDependent(self, expr):
from sympy.vector import Vector
if not self._use_unicode:
raise NotImplementedError("ASCII pretty printing of BasisDependent is not implemented")
if expr == expr.zero:
return prettyForm(expr.zero._pretty_form)
o1 = []
vectstrs = []
if isinstance(expr, Vector):
items = expr.separate().items()
else:
items = [(0, expr)]
for system, vect in items:
inneritems = list(vect.components.items())
inneritems.sort(key = lambda x: x[0].__str__())
for k, v in inneritems:
#if the coef of the basis vector is 1
#we skip the 1
if v == 1:
o1.append("" +
k._pretty_form)
#Same for -1
elif v == -1:
o1.append("(-1) " +
k._pretty_form)
#For a general expr
else:
#We always wrap the measure numbers in
#parentheses
arg_str = self._print(
v).parens()[0]
o1.append(arg_str + ' ' + k._pretty_form)
vectstrs.append(k._pretty_form)
#outstr = u("").join(o1)
if o1[0].startswith(" + "):
o1[0] = o1[0][3:]
elif o1[0].startswith(" "):
o1[0] = o1[0][1:]
#Fixing the newlines
lengths = []
strs = ['']
flag = []
for i, partstr in enumerate(o1):
flag.append(0)
# XXX: What is this hack?
if '\n' in partstr:
tempstr = partstr
tempstr = tempstr.replace(vectstrs[i], '')
if '\N{RIGHT PARENTHESIS EXTENSION}' in tempstr: # If scalar is a fraction
for paren in range(len(tempstr)):
flag[i] = 1
if tempstr[paren] == '\N{RIGHT PARENTHESIS EXTENSION}' and tempstr[paren + 1] == '\n':
# We want to place the vector string after all the right parentheses, because
# otherwise, the vector will be in the middle of the string
tempstr = tempstr[:paren] + '\N{RIGHT PARENTHESIS EXTENSION}'\
+ ' ' + vectstrs[i] + tempstr[paren + 1:]
break
elif '\N{RIGHT PARENTHESIS LOWER HOOK}' in tempstr:
# We want to place the vector string after all the right parentheses, because
# otherwise, the vector will be in the middle of the string. For this reason,
# we insert the vector string at the rightmost index.
index = tempstr.rfind('\N{RIGHT PARENTHESIS LOWER HOOK}')
if index != -1: # then this character was found in this string
flag[i] = 1
tempstr = tempstr[:index] + '\N{RIGHT PARENTHESIS LOWER HOOK}'\
+ ' ' + vectstrs[i] + tempstr[index + 1:]
o1[i] = tempstr
o1 = [x.split('\n') for x in o1]
n_newlines = max([len(x) for x in o1]) # Width of part in its pretty form
if 1 in flag: # If there was a fractional scalar
for i, parts in enumerate(o1):
if len(parts) == 1: # If part has no newline
parts.insert(0, ' ' * (len(parts[0])))
flag[i] = 1
for i, parts in enumerate(o1):
lengths.append(len(parts[flag[i]]))
for j in range(n_newlines):
if j+1 <= len(parts):
if j >= len(strs):
strs.append(' ' * (sum(lengths[:-1]) +
3*(len(lengths)-1)))
if j == flag[i]:
strs[flag[i]] += parts[flag[i]] + ' + '
else:
strs[j] += parts[j] + ' '*(lengths[-1] -
len(parts[j])+
3)
else:
if j >= len(strs):
strs.append(' ' * (sum(lengths[:-1]) +
3*(len(lengths)-1)))
strs[j] += ' '*(lengths[-1]+3)
return prettyForm('\n'.join([s[:-3] for s in strs]))
def _print_NDimArray(self, expr):
from sympy.matrices.immutable import ImmutableMatrix
if expr.rank() == 0:
return self._print(expr[()])
level_str = [[]] + [[] for i in range(expr.rank())]
shape_ranges = [list(range(i)) for i in expr.shape]
# leave eventual matrix elements unflattened
mat = lambda x: ImmutableMatrix(x, evaluate=False)
for outer_i in itertools.product(*shape_ranges):
level_str[-1].append(expr[outer_i])
even = True
for back_outer_i in range(expr.rank()-1, -1, -1):
if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]:
break
if even:
level_str[back_outer_i].append(level_str[back_outer_i+1])
else:
level_str[back_outer_i].append(mat(
level_str[back_outer_i+1]))
if len(level_str[back_outer_i + 1]) == 1:
level_str[back_outer_i][-1] = mat(
[[level_str[back_outer_i][-1]]])
even = not even
level_str[back_outer_i+1] = []
out_expr = level_str[0][0]
if expr.rank() % 2 == 1:
out_expr = mat([out_expr])
return self._print(out_expr)
def _printer_tensor_indices(self, name, indices, index_map={}):
center = stringPict(name)
top = stringPict(" "*center.width())
bot = stringPict(" "*center.width())
last_valence = None
prev_map = None
for i, index in enumerate(indices):
indpic = self._print(index.args[0])
if ((index in index_map) or prev_map) and last_valence == index.is_up:
if index.is_up:
top = prettyForm(*stringPict.next(top, ","))
else:
bot = prettyForm(*stringPict.next(bot, ","))
if index in index_map:
indpic = prettyForm(*stringPict.next(indpic, "="))
indpic = prettyForm(*stringPict.next(indpic, self._print(index_map[index])))
prev_map = True
else:
prev_map = False
if index.is_up:
top = stringPict(*top.right(indpic))
center = stringPict(*center.right(" "*indpic.width()))
bot = stringPict(*bot.right(" "*indpic.width()))
else:
bot = stringPict(*bot.right(indpic))
center = stringPict(*center.right(" "*indpic.width()))
top = stringPict(*top.right(" "*indpic.width()))
last_valence = index.is_up
pict = prettyForm(*center.above(top))
pict = prettyForm(*pict.below(bot))
return pict
def _print_Tensor(self, expr):
name = expr.args[0].name
indices = expr.get_indices()
return self._printer_tensor_indices(name, indices)
def _print_TensorElement(self, expr):
name = expr.expr.args[0].name
indices = expr.expr.get_indices()
index_map = expr.index_map
return self._printer_tensor_indices(name, indices, index_map)
def _print_TensMul(self, expr):
sign, args = expr._get_args_for_traditional_printer()
args = [
prettyForm(*self._print(i).parens()) if
precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i)
for i in args
]
pform = prettyForm.__mul__(*args)
if sign:
return prettyForm(*pform.left(sign))
else:
return pform
def _print_TensAdd(self, expr):
args = [
prettyForm(*self._print(i).parens()) if
precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i)
for i in expr.args
]
return prettyForm.__add__(*args)
def _print_TensorIndex(self, expr):
sym = expr.args[0]
if not expr.is_up:
sym = -sym
return self._print(sym)
def _print_PartialDerivative(self, deriv):
if self._use_unicode:
deriv_symbol = U('PARTIAL DIFFERENTIAL')
else:
deriv_symbol = r'd'
x = None
for variable in reversed(deriv.variables):
s = self._print(variable)
ds = prettyForm(*s.left(deriv_symbol))
if x is None:
x = ds
else:
x = prettyForm(*x.right(' '))
x = prettyForm(*x.right(ds))
f = prettyForm(
binding=prettyForm.FUNC, *self._print(deriv.expr).parens())
pform = prettyForm(deriv_symbol)
if len(deriv.variables) > 1:
pform = pform**self._print(len(deriv.variables))
pform = prettyForm(*pform.below(stringPict.LINE, x))
pform.baseline = pform.baseline + 1
pform = prettyForm(*stringPict.next(pform, f))
pform.binding = prettyForm.MUL
return pform
def _print_Piecewise(self, pexpr):
P = {}
for n, ec in enumerate(pexpr.args):
P[n, 0] = self._print(ec.expr)
if ec.cond == True:
P[n, 1] = prettyForm('otherwise')
else:
P[n, 1] = prettyForm(
*prettyForm('for ').right(self._print(ec.cond)))
hsep = 2
vsep = 1
len_args = len(pexpr.args)
# max widths
maxw = [max([P[i, j].width() for i in range(len_args)])
for j in range(2)]
# FIXME: Refactor this code and matrix into some tabular environment.
# drawing result
D = None
for i in range(len_args):
D_row = None
for j in range(2):
p = P[i, j]
assert p.width() <= maxw[j]
wdelta = maxw[j] - p.width()
wleft = wdelta // 2
wright = wdelta - wleft
p = prettyForm(*p.right(' '*wright))
p = prettyForm(*p.left(' '*wleft))
if D_row is None:
D_row = p
continue
D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer
D_row = prettyForm(*D_row.right(p))
if D is None:
D = D_row # first row in a picture
continue
# v-spacer
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
D = prettyForm(*D.parens('{', ''))
D.baseline = D.height()//2
D.binding = prettyForm.OPEN
return D
def _print_ITE(self, ite):
from sympy.functions.elementary.piecewise import Piecewise
return self._print(ite.rewrite(Piecewise))
def _hprint_vec(self, v):
D = None
for a in v:
p = a
if D is None:
D = p
else:
D = prettyForm(*D.right(', '))
D = prettyForm(*D.right(p))
if D is None:
D = stringPict(' ')
return D
def _hprint_vseparator(self, p1, p2, left=None, right=None, delimiter='', ifascii_nougly=False):
if ifascii_nougly and not self._use_unicode:
return self._print_seq((p1, '|', p2), left=left, right=right,
delimiter=delimiter, ifascii_nougly=True)
tmp = self._print_seq((p1, p2,), left=left, right=right, delimiter=delimiter)
sep = stringPict(vobj('|', tmp.height()), baseline=tmp.baseline)
return self._print_seq((p1, sep, p2), left=left, right=right,
delimiter=delimiter)
def _print_hyper(self, e):
# FIXME refactor Matrix, Piecewise, and this into a tabular environment
ap = [self._print(a) for a in e.ap]
bq = [self._print(b) for b in e.bq]
P = self._print(e.argument)
P.baseline = P.height()//2
# Drawing result - first create the ap, bq vectors
D = None
for v in [ap, bq]:
D_row = self._hprint_vec(v)
if D is None:
D = D_row # first row in a picture
else:
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
# make sure that the argument `z' is centred vertically
D.baseline = D.height()//2
# insert horizontal separator
P = prettyForm(*P.left(' '))
D = prettyForm(*D.right(' '))
# insert separating `|`
D = self._hprint_vseparator(D, P)
# add parens
D = prettyForm(*D.parens('(', ')'))
# create the F symbol
above = D.height()//2 - 1
below = D.height() - above - 1
sz, t, b, add, img = annotated('F')
F = prettyForm('\n' * (above - t) + img + '\n' * (below - b),
baseline=above + sz)
add = (sz + 1)//2
F = prettyForm(*F.left(self._print(len(e.ap))))
F = prettyForm(*F.right(self._print(len(e.bq))))
F.baseline = above + add
D = prettyForm(*F.right(' ', D))
return D
def _print_meijerg(self, e):
# FIXME refactor Matrix, Piecewise, and this into a tabular environment
v = {}
v[(0, 0)] = [self._print(a) for a in e.an]
v[(0, 1)] = [self._print(a) for a in e.aother]
v[(1, 0)] = [self._print(b) for b in e.bm]
v[(1, 1)] = [self._print(b) for b in e.bother]
P = self._print(e.argument)
P.baseline = P.height()//2
vp = {}
for idx in v:
vp[idx] = self._hprint_vec(v[idx])
for i in range(2):
maxw = max(vp[(0, i)].width(), vp[(1, i)].width())
for j in range(2):
s = vp[(j, i)]
left = (maxw - s.width()) // 2
right = maxw - left - s.width()
s = prettyForm(*s.left(' ' * left))
s = prettyForm(*s.right(' ' * right))
vp[(j, i)] = s
D1 = prettyForm(*vp[(0, 0)].right(' ', vp[(0, 1)]))
D1 = prettyForm(*D1.below(' '))
D2 = prettyForm(*vp[(1, 0)].right(' ', vp[(1, 1)]))
D = prettyForm(*D1.below(D2))
# make sure that the argument `z' is centred vertically
D.baseline = D.height()//2
# insert horizontal separator
P = prettyForm(*P.left(' '))
D = prettyForm(*D.right(' '))
# insert separating `|`
D = self._hprint_vseparator(D, P)
# add parens
D = prettyForm(*D.parens('(', ')'))
# create the G symbol
above = D.height()//2 - 1
below = D.height() - above - 1
sz, t, b, add, img = annotated('G')
F = prettyForm('\n' * (above - t) + img + '\n' * (below - b),
baseline=above + sz)
pp = self._print(len(e.ap))
pq = self._print(len(e.bq))
pm = self._print(len(e.bm))
pn = self._print(len(e.an))
def adjust(p1, p2):
diff = p1.width() - p2.width()
if diff == 0:
return p1, p2
elif diff > 0:
return p1, prettyForm(*p2.left(' '*diff))
else:
return prettyForm(*p1.left(' '*-diff)), p2
pp, pm = adjust(pp, pm)
pq, pn = adjust(pq, pn)
pu = prettyForm(*pm.right(', ', pn))
pl = prettyForm(*pp.right(', ', pq))
ht = F.baseline - above - 2
if ht > 0:
pu = prettyForm(*pu.below('\n'*ht))
p = prettyForm(*pu.below(pl))
F.baseline = above
F = prettyForm(*F.right(p))
F.baseline = above + add
D = prettyForm(*F.right(' ', D))
return D
def _print_ExpBase(self, e):
# TODO should exp_polar be printed differently?
# what about exp_polar(0), exp_polar(1)?
base = prettyForm(pretty_atom('Exp1', 'e'))
return base ** self._print(e.args[0])
def _print_Exp1(self, e):
return prettyForm(pretty_atom('Exp1', 'e'))
def _print_Function(self, e, sort=False, func_name=None, left='(',
right=')'):
# optional argument func_name for supplying custom names
# XXX works only for applied functions
return self._helper_print_function(e.func, e.args, sort=sort, func_name=func_name, left=left, right=right)
def _print_mathieuc(self, e):
return self._print_Function(e, func_name='C')
def _print_mathieus(self, e):
return self._print_Function(e, func_name='S')
def _print_mathieucprime(self, e):
return self._print_Function(e, func_name="C'")
def _print_mathieusprime(self, e):
return self._print_Function(e, func_name="S'")
def _helper_print_function(self, func, args, sort=False, func_name=None,
delimiter=', ', elementwise=False, left='(',
right=')'):
if sort:
args = sorted(args, key=default_sort_key)
if not func_name and hasattr(func, "__name__"):
func_name = func.__name__
if func_name:
prettyFunc = self._print(Symbol(func_name))
else:
prettyFunc = prettyForm(*self._print(func).parens())
if elementwise:
if self._use_unicode:
circ = pretty_atom('Modifier Letter Low Ring')
else:
circ = '.'
circ = self._print(circ)
prettyFunc = prettyForm(
binding=prettyForm.LINE,
*stringPict.next(prettyFunc, circ)
)
prettyArgs = prettyForm(*self._print_seq(args, delimiter=delimiter).parens(
left=left, right=right))
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform
def _print_ElementwiseApplyFunction(self, e):
func = e.function
arg = e.expr
args = [arg]
return self._helper_print_function(func, args, delimiter="", elementwise=True)
@property
def _special_function_classes(self):
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.functions.special.gamma_functions import gamma, lowergamma
from sympy.functions.special.zeta_functions import lerchphi
from sympy.functions.special.beta_functions import beta
from sympy.functions.special.delta_functions import DiracDelta
from sympy.functions.special.error_functions import Chi
return {KroneckerDelta: [greek_unicode['delta'], 'delta'],
gamma: [greek_unicode['Gamma'], 'Gamma'],
lerchphi: [greek_unicode['Phi'], 'lerchphi'],
lowergamma: [greek_unicode['gamma'], 'gamma'],
beta: [greek_unicode['Beta'], 'B'],
DiracDelta: [greek_unicode['delta'], 'delta'],
Chi: ['Chi', 'Chi']}
def _print_FunctionClass(self, expr):
for cls in self._special_function_classes:
if issubclass(expr, cls) and expr.__name__ == cls.__name__:
if self._use_unicode:
return prettyForm(self._special_function_classes[cls][0])
else:
return prettyForm(self._special_function_classes[cls][1])
func_name = expr.__name__
return prettyForm(pretty_symbol(func_name))
def _print_GeometryEntity(self, expr):
# GeometryEntity is based on Tuple but should not print like a Tuple
return self.emptyPrinter(expr)
def _print_lerchphi(self, e):
func_name = greek_unicode['Phi'] if self._use_unicode else 'lerchphi'
return self._print_Function(e, func_name=func_name)
def _print_dirichlet_eta(self, e):
func_name = greek_unicode['eta'] if self._use_unicode else 'dirichlet_eta'
return self._print_Function(e, func_name=func_name)
def _print_Heaviside(self, e):
func_name = greek_unicode['theta'] if self._use_unicode else 'Heaviside'
if e.args[1] is S.Half:
pform = prettyForm(*self._print(e.args[0]).parens())
pform = prettyForm(*pform.left(func_name))
return pform
else:
return self._print_Function(e, func_name=func_name)
def _print_fresnels(self, e):
return self._print_Function(e, func_name="S")
def _print_fresnelc(self, e):
return self._print_Function(e, func_name="C")
def _print_airyai(self, e):
return self._print_Function(e, func_name="Ai")
def _print_airybi(self, e):
return self._print_Function(e, func_name="Bi")
def _print_airyaiprime(self, e):
return self._print_Function(e, func_name="Ai'")
def _print_airybiprime(self, e):
return self._print_Function(e, func_name="Bi'")
def _print_LambertW(self, e):
return self._print_Function(e, func_name="W")
def _print_Covariance(self, e):
return self._print_Function(e, func_name="Cov")
def _print_Variance(self, e):
return self._print_Function(e, func_name="Var")
def _print_Probability(self, e):
return self._print_Function(e, func_name="P")
def _print_Expectation(self, e):
return self._print_Function(e, func_name="E", left='[', right=']')
def _print_Lambda(self, e):
expr = e.expr
sig = e.signature
if self._use_unicode:
arrow = " \N{RIGHTWARDS ARROW FROM BAR} "
else:
arrow = " -> "
if len(sig) == 1 and sig[0].is_symbol:
sig = sig[0]
var_form = self._print(sig)
return prettyForm(*stringPict.next(var_form, arrow, self._print(expr)), binding=8)
def _print_Order(self, expr):
pform = self._print(expr.expr)
if (expr.point and any(p != S.Zero for p in expr.point)) or \
len(expr.variables) > 1:
pform = prettyForm(*pform.right("; "))
if len(expr.variables) > 1:
pform = prettyForm(*pform.right(self._print(expr.variables)))
elif len(expr.variables):
pform = prettyForm(*pform.right(self._print(expr.variables[0])))
if self._use_unicode:
pform = prettyForm(*pform.right(" \N{RIGHTWARDS ARROW} "))
else:
pform = prettyForm(*pform.right(" -> "))
if len(expr.point) > 1:
pform = prettyForm(*pform.right(self._print(expr.point)))
else:
pform = prettyForm(*pform.right(self._print(expr.point[0])))
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left("O"))
return pform
def _print_SingularityFunction(self, e):
if self._use_unicode:
shift = self._print(e.args[0]-e.args[1])
n = self._print(e.args[2])
base = prettyForm("<")
base = prettyForm(*base.right(shift))
base = prettyForm(*base.right(">"))
pform = base**n
return pform
else:
n = self._print(e.args[2])
shift = self._print(e.args[0]-e.args[1])
base = self._print_seq(shift, "<", ">", ' ')
return base**n
def _print_beta(self, e):
func_name = greek_unicode['Beta'] if self._use_unicode else 'B'
return self._print_Function(e, func_name=func_name)
def _print_betainc(self, e):
func_name = "B'"
return self._print_Function(e, func_name=func_name)
def _print_betainc_regularized(self, e):
func_name = 'I'
return self._print_Function(e, func_name=func_name)
def _print_gamma(self, e):
func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma'
return self._print_Function(e, func_name=func_name)
def _print_uppergamma(self, e):
func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma'
return self._print_Function(e, func_name=func_name)
def _print_lowergamma(self, e):
func_name = greek_unicode['gamma'] if self._use_unicode else 'lowergamma'
return self._print_Function(e, func_name=func_name)
def _print_DiracDelta(self, e):
if self._use_unicode:
if len(e.args) == 2:
a = prettyForm(greek_unicode['delta'])
b = self._print(e.args[1])
b = prettyForm(*b.parens())
c = self._print(e.args[0])
c = prettyForm(*c.parens())
pform = a**b
pform = prettyForm(*pform.right(' '))
pform = prettyForm(*pform.right(c))
return pform
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left(greek_unicode['delta']))
return pform
else:
return self._print_Function(e)
def _print_expint(self, e):
if e.args[0].is_Integer and self._use_unicode:
return self._print_Function(Function('E_%s' % e.args[0])(e.args[1]))
return self._print_Function(e)
def _print_Chi(self, e):
# This needs a special case since otherwise it comes out as greek
# letter chi...
prettyFunc = prettyForm("Chi")
prettyArgs = prettyForm(*self._print_seq(e.args).parens())
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform
def _print_elliptic_e(self, e):
pforma0 = self._print(e.args[0])
if len(e.args) == 1:
pform = pforma0
else:
pforma1 = self._print(e.args[1])
pform = self._hprint_vseparator(pforma0, pforma1)
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left('E'))
return pform
def _print_elliptic_k(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left('K'))
return pform
def _print_elliptic_f(self, e):
pforma0 = self._print(e.args[0])
pforma1 = self._print(e.args[1])
pform = self._hprint_vseparator(pforma0, pforma1)
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left('F'))
return pform
def _print_elliptic_pi(self, e):
name = greek_unicode['Pi'] if self._use_unicode else 'Pi'
pforma0 = self._print(e.args[0])
pforma1 = self._print(e.args[1])
if len(e.args) == 2:
pform = self._hprint_vseparator(pforma0, pforma1)
else:
pforma2 = self._print(e.args[2])
pforma = self._hprint_vseparator(pforma1, pforma2, ifascii_nougly=False)
pforma = prettyForm(*pforma.left('; '))
pform = prettyForm(*pforma.left(pforma0))
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left(name))
return pform
def _print_GoldenRatio(self, expr):
if self._use_unicode:
return prettyForm(pretty_symbol('phi'))
return self._print(Symbol("GoldenRatio"))
def _print_EulerGamma(self, expr):
if self._use_unicode:
return prettyForm(pretty_symbol('gamma'))
return self._print(Symbol("EulerGamma"))
def _print_Catalan(self, expr):
return self._print(Symbol("G"))
def _print_Mod(self, expr):
pform = self._print(expr.args[0])
if pform.binding > prettyForm.MUL:
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.right(' mod '))
pform = prettyForm(*pform.right(self._print(expr.args[1])))
pform.binding = prettyForm.OPEN
return pform
def _print_Add(self, expr, order=None):
terms = self._as_ordered_terms(expr, order=order)
pforms, indices = [], []
def pretty_negative(pform, index):
"""Prepend a minus sign to a pretty form. """
#TODO: Move this code to prettyForm
if index == 0:
if pform.height() > 1:
pform_neg = '- '
else:
pform_neg = '-'
else:
pform_neg = ' - '
if (pform.binding > prettyForm.NEG
or pform.binding == prettyForm.ADD):
p = stringPict(*pform.parens())
else:
p = pform
p = stringPict.next(pform_neg, p)
# Lower the binding to NEG, even if it was higher. Otherwise, it
# will print as a + ( - (b)), instead of a - (b).
return prettyForm(binding=prettyForm.NEG, *p)
for i, term in enumerate(terms):
if term.is_Mul and term.could_extract_minus_sign():
coeff, other = term.as_coeff_mul(rational=False)
if coeff == -1:
negterm = Mul(*other, evaluate=False)
else:
negterm = Mul(-coeff, *other, evaluate=False)
pform = self._print(negterm)
pforms.append(pretty_negative(pform, i))
elif term.is_Rational and term.q > 1:
pforms.append(None)
indices.append(i)
elif term.is_Number and term < 0:
pform = self._print(-term)
pforms.append(pretty_negative(pform, i))
elif term.is_Relational:
pforms.append(prettyForm(*self._print(term).parens()))
else:
pforms.append(self._print(term))
if indices:
large = True
for pform in pforms:
if pform is not None and pform.height() > 1:
break
else:
large = False
for i in indices:
term, negative = terms[i], False
if term < 0:
term, negative = -term, True
if large:
pform = prettyForm(str(term.p))/prettyForm(str(term.q))
else:
pform = self._print(term)
if negative:
pform = pretty_negative(pform, i)
pforms[i] = pform
return prettyForm.__add__(*pforms)
def _print_Mul(self, product):
from sympy.physics.units import Quantity
# Check for unevaluated Mul. In this case we need to make sure the
# identities are visible, multiple Rational factors are not combined
# etc so we display in a straight-forward form that fully preserves all
# args and their order.
args = product.args
if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]):
strargs = list(map(self._print, args))
# XXX: This is a hack to work around the fact that
# prettyForm.__mul__ absorbs a leading -1 in the args. Probably it
# would be better to fix this in prettyForm.__mul__ instead.
negone = strargs[0] == '-1'
if negone:
strargs[0] = prettyForm('1', 0, 0)
obj = prettyForm.__mul__(*strargs)
if negone:
obj = prettyForm('-' + obj.s, obj.baseline, obj.binding)
return obj
a = [] # items in the numerator
b = [] # items that are in the denominator (if any)
if self.order not in ('old', 'none'):
args = product.as_ordered_factors()
else:
args = list(product.args)
# If quantities are present append them at the back
args = sorted(args, key=lambda x: isinstance(x, Quantity) or
(isinstance(x, Pow) and isinstance(x.base, Quantity)))
# Gather terms for numerator/denominator
for item in args:
if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative:
if item.exp != -1:
b.append(Pow(item.base, -item.exp, evaluate=False))
else:
b.append(Pow(item.base, -item.exp))
elif item.is_Rational and item is not S.Infinity:
if item.p != 1:
a.append( Rational(item.p) )
if item.q != 1:
b.append( Rational(item.q) )
else:
a.append(item)
# Convert to pretty forms. Parentheses are added by `__mul__`.
a = [self._print(ai) for ai in a]
b = [self._print(bi) for bi in b]
# Construct a pretty form
if len(b) == 0:
return prettyForm.__mul__(*a)
else:
if len(a) == 0:
a.append( self._print(S.One) )
return prettyForm.__mul__(*a)/prettyForm.__mul__(*b)
# A helper function for _print_Pow to print x**(1/n)
def _print_nth_root(self, base, root):
bpretty = self._print(base)
# In very simple cases, use a single-char root sign
if (self._settings['use_unicode_sqrt_char'] and self._use_unicode
and root == 2 and bpretty.height() == 1
and (bpretty.width() == 1
or (base.is_Integer and base.is_nonnegative))):
return prettyForm(*bpretty.left('\N{SQUARE ROOT}'))
# Construct root sign, start with the \/ shape
_zZ = xobj('/', 1)
rootsign = xobj('\\', 1) + _zZ
# Constructing the number to put on root
rpretty = self._print(root)
# roots look bad if they are not a single line
if rpretty.height() != 1:
return self._print(base)**self._print(1/root)
# If power is half, no number should appear on top of root sign
exp = '' if root == 2 else str(rpretty).ljust(2)
if len(exp) > 2:
rootsign = ' '*(len(exp) - 2) + rootsign
# Stack the exponent
rootsign = stringPict(exp + '\n' + rootsign)
rootsign.baseline = 0
# Diagonal: length is one less than height of base
linelength = bpretty.height() - 1
diagonal = stringPict('\n'.join(
' '*(linelength - i - 1) + _zZ + ' '*i
for i in range(linelength)
))
# Put baseline just below lowest line: next to exp
diagonal.baseline = linelength - 1
# Make the root symbol
rootsign = prettyForm(*rootsign.right(diagonal))
# Det the baseline to match contents to fix the height
# but if the height of bpretty is one, the rootsign must be one higher
rootsign.baseline = max(1, bpretty.baseline)
#build result
s = prettyForm(hobj('_', 2 + bpretty.width()))
s = prettyForm(*bpretty.above(s))
s = prettyForm(*s.left(rootsign))
return s
def _print_Pow(self, power):
from sympy.simplify.simplify import fraction
b, e = power.as_base_exp()
if power.is_commutative:
if e is S.NegativeOne:
return prettyForm("1")/self._print(b)
n, d = fraction(e)
if n is S.One and d.is_Atom and not e.is_Integer and (e.is_Rational or d.is_Symbol) \
and self._settings['root_notation']:
return self._print_nth_root(b, d)
if e.is_Rational and e < 0:
return prettyForm("1")/self._print(Pow(b, -e, evaluate=False))
if b.is_Relational:
return prettyForm(*self._print(b).parens()).__pow__(self._print(e))
return self._print(b)**self._print(e)
def _print_UnevaluatedExpr(self, expr):
return self._print(expr.args[0])
def __print_numer_denom(self, p, q):
if q == 1:
if p < 0:
return prettyForm(str(p), binding=prettyForm.NEG)
else:
return prettyForm(str(p))
elif abs(p) >= 10 and abs(q) >= 10:
# If more than one digit in numer and denom, print larger fraction
if p < 0:
return prettyForm(str(p), binding=prettyForm.NEG)/prettyForm(str(q))
# Old printing method:
#pform = prettyForm(str(-p))/prettyForm(str(q))
#return prettyForm(binding=prettyForm.NEG, *pform.left('- '))
else:
return prettyForm(str(p))/prettyForm(str(q))
else:
return None
def _print_Rational(self, expr):
result = self.__print_numer_denom(expr.p, expr.q)
if result is not None:
return result
else:
return self.emptyPrinter(expr)
def _print_Fraction(self, expr):
result = self.__print_numer_denom(expr.numerator, expr.denominator)
if result is not None:
return result
else:
return self.emptyPrinter(expr)
def _print_ProductSet(self, p):
if len(p.sets) >= 1 and not has_variety(p.sets):
return self._print(p.sets[0]) ** self._print(len(p.sets))
else:
prod_char = "\N{MULTIPLICATION SIGN}" if self._use_unicode else 'x'
return self._print_seq(p.sets, None, None, ' %s ' % prod_char,
parenthesize=lambda set: set.is_Union or
set.is_Intersection or set.is_ProductSet)
def _print_FiniteSet(self, s):
items = sorted(s.args, key=default_sort_key)
return self._print_seq(items, '{', '}', ', ' )
def _print_Range(self, s):
if self._use_unicode:
dots = "\N{HORIZONTAL ELLIPSIS}"
else:
dots = '...'
if s.start.is_infinite and s.stop.is_infinite:
if s.step.is_positive:
printset = dots, -1, 0, 1, dots
else:
printset = dots, 1, 0, -1, dots
elif s.start.is_infinite:
printset = dots, s[-1] - s.step, s[-1]
elif s.stop.is_infinite:
it = iter(s)
printset = next(it), next(it), dots
elif len(s) > 4:
it = iter(s)
printset = next(it), next(it), dots, s[-1]
else:
printset = tuple(s)
return self._print_seq(printset, '{', '}', ', ' )
def _print_Interval(self, i):
if i.start == i.end:
return self._print_seq(i.args[:1], '{', '}')
else:
if i.left_open:
left = '('
else:
left = '['
if i.right_open:
right = ')'
else:
right = ']'
return self._print_seq(i.args[:2], left, right)
def _print_AccumulationBounds(self, i):
left = '<'
right = '>'
return self._print_seq(i.args[:2], left, right)
def _print_Intersection(self, u):
delimiter = ' %s ' % pretty_atom('Intersection', 'n')
return self._print_seq(u.args, None, None, delimiter,
parenthesize=lambda set: set.is_ProductSet or
set.is_Union or set.is_Complement)
def _print_Union(self, u):
union_delimiter = ' %s ' % pretty_atom('Union', 'U')
return self._print_seq(u.args, None, None, union_delimiter,
parenthesize=lambda set: set.is_ProductSet or
set.is_Intersection or set.is_Complement)
def _print_SymmetricDifference(self, u):
if not self._use_unicode:
raise NotImplementedError("ASCII pretty printing of SymmetricDifference is not implemented")
sym_delimeter = ' %s ' % pretty_atom('SymmetricDifference')
return self._print_seq(u.args, None, None, sym_delimeter)
def _print_Complement(self, u):
delimiter = r' \ '
return self._print_seq(u.args, None, None, delimiter,
parenthesize=lambda set: set.is_ProductSet or set.is_Intersection
or set.is_Union)
def _print_ImageSet(self, ts):
if self._use_unicode:
inn = "\N{SMALL ELEMENT OF}"
else:
inn = 'in'
fun = ts.lamda
sets = ts.base_sets
signature = fun.signature
expr = self._print(fun.expr)
# TODO: the stuff to the left of the | and the stuff to the right of
# the | should have independent baselines, that way something like
# ImageSet(Lambda(x, 1/x**2), S.Naturals) prints the "x in N" part
# centered on the right instead of aligned with the fraction bar on
# the left. The same also applies to ConditionSet and ComplexRegion
if len(signature) == 1:
S = self._print_seq((signature[0], inn, sets[0]),
delimiter=' ')
return self._hprint_vseparator(expr, S,
left='{', right='}',
ifascii_nougly=True, delimiter=' ')
else:
pargs = tuple(j for var, setv in zip(signature, sets) for j in
(var, ' ', inn, ' ', setv, ", "))
S = self._print_seq(pargs[:-1], delimiter='')
return self._hprint_vseparator(expr, S,
left='{', right='}',
ifascii_nougly=True, delimiter=' ')
def _print_ConditionSet(self, ts):
if self._use_unicode:
inn = "\N{SMALL ELEMENT OF}"
# using _and because and is a keyword and it is bad practice to
# overwrite them
_and = "\N{LOGICAL AND}"
else:
inn = 'in'
_and = 'and'
variables = self._print_seq(Tuple(ts.sym))
as_expr = getattr(ts.condition, 'as_expr', None)
if as_expr is not None:
cond = self._print(ts.condition.as_expr())
else:
cond = self._print(ts.condition)
if self._use_unicode:
cond = self._print(cond)
cond = prettyForm(*cond.parens())
if ts.base_set is S.UniversalSet:
return self._hprint_vseparator(variables, cond, left="{",
right="}", ifascii_nougly=True,
delimiter=' ')
base = self._print(ts.base_set)
C = self._print_seq((variables, inn, base, _and, cond),
delimiter=' ')
return self._hprint_vseparator(variables, C, left="{", right="}",
ifascii_nougly=True, delimiter=' ')
def _print_ComplexRegion(self, ts):
if self._use_unicode:
inn = "\N{SMALL ELEMENT OF}"
else:
inn = 'in'
variables = self._print_seq(ts.variables)
expr = self._print(ts.expr)
prodsets = self._print(ts.sets)
C = self._print_seq((variables, inn, prodsets),
delimiter=' ')
return self._hprint_vseparator(expr, C, left="{", right="}",
ifascii_nougly=True, delimiter=' ')
def _print_Contains(self, e):
var, set = e.args
if self._use_unicode:
el = " \N{ELEMENT OF} "
return prettyForm(*stringPict.next(self._print(var),
el, self._print(set)), binding=8)
else:
return prettyForm(sstr(e))
def _print_FourierSeries(self, s):
if s.an.formula is S.Zero and s.bn.formula is S.Zero:
return self._print(s.a0)
if self._use_unicode:
dots = "\N{HORIZONTAL ELLIPSIS}"
else:
dots = '...'
return self._print_Add(s.truncate()) + self._print(dots)
def _print_FormalPowerSeries(self, s):
return self._print_Add(s.infinite)
def _print_SetExpr(self, se):
pretty_set = prettyForm(*self._print(se.set).parens())
pretty_name = self._print(Symbol("SetExpr"))
return prettyForm(*pretty_name.right(pretty_set))
def _print_SeqFormula(self, s):
if self._use_unicode:
dots = "\N{HORIZONTAL ELLIPSIS}"
else:
dots = '...'
if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0:
raise NotImplementedError("Pretty printing of sequences with symbolic bound not implemented")
if s.start is S.NegativeInfinity:
stop = s.stop
printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2),
s.coeff(stop - 1), s.coeff(stop))
elif s.stop is S.Infinity or s.length > 4:
printset = s[:4]
printset.append(dots)
printset = tuple(printset)
else:
printset = tuple(s)
return self._print_list(printset)
_print_SeqPer = _print_SeqFormula
_print_SeqAdd = _print_SeqFormula
_print_SeqMul = _print_SeqFormula
def _print_seq(self, seq, left=None, right=None, delimiter=', ',
parenthesize=lambda x: False, ifascii_nougly=True):
try:
pforms = []
for item in seq:
pform = self._print(item)
if parenthesize(item):
pform = prettyForm(*pform.parens())
if pforms:
pforms.append(delimiter)
pforms.append(pform)
if not pforms:
s = stringPict('')
else:
s = prettyForm(*stringPict.next(*pforms))
# XXX: Under the tests from #15686 the above raises:
# AttributeError: 'Fake' object has no attribute 'baseline'
# This is caught below but that is not the right way to
# fix it.
except AttributeError:
s = None
for item in seq:
pform = self.doprint(item)
if parenthesize(item):
pform = prettyForm(*pform.parens())
if s is None:
# first element
s = pform
else :
s = prettyForm(*stringPict.next(s, delimiter))
s = prettyForm(*stringPict.next(s, pform))
if s is None:
s = stringPict('')
s = prettyForm(*s.parens(left, right, ifascii_nougly=ifascii_nougly))
return s
def join(self, delimiter, args):
pform = None
for arg in args:
if pform is None:
pform = arg
else:
pform = prettyForm(*pform.right(delimiter))
pform = prettyForm(*pform.right(arg))
if pform is None:
return prettyForm("")
else:
return pform
def _print_list(self, l):
return self._print_seq(l, '[', ']')
def _print_tuple(self, t):
if len(t) == 1:
ptuple = prettyForm(*stringPict.next(self._print(t[0]), ','))
return prettyForm(*ptuple.parens('(', ')', ifascii_nougly=True))
else:
return self._print_seq(t, '(', ')')
def _print_Tuple(self, expr):
return self._print_tuple(expr)
def _print_dict(self, d):
keys = sorted(d.keys(), key=default_sort_key)
items = []
for k in keys:
K = self._print(k)
V = self._print(d[k])
s = prettyForm(*stringPict.next(K, ': ', V))
items.append(s)
return self._print_seq(items, '{', '}')
def _print_Dict(self, d):
return self._print_dict(d)
def _print_set(self, s):
if not s:
return prettyForm('set()')
items = sorted(s, key=default_sort_key)
pretty = self._print_seq(items)
pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True))
return pretty
def _print_frozenset(self, s):
if not s:
return prettyForm('frozenset()')
items = sorted(s, key=default_sort_key)
pretty = self._print_seq(items)
pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True))
pretty = prettyForm(*pretty.parens('(', ')', ifascii_nougly=True))
pretty = prettyForm(*stringPict.next(type(s).__name__, pretty))
return pretty
def _print_UniversalSet(self, s):
if self._use_unicode:
return prettyForm("\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL U}")
else:
return prettyForm('UniversalSet')
def _print_PolyRing(self, ring):
return prettyForm(sstr(ring))
def _print_FracField(self, field):
return prettyForm(sstr(field))
def _print_FreeGroupElement(self, elm):
return prettyForm(str(elm))
def _print_PolyElement(self, poly):
return prettyForm(sstr(poly))
def _print_FracElement(self, frac):
return prettyForm(sstr(frac))
def _print_AlgebraicNumber(self, expr):
if expr.is_aliased:
return self._print(expr.as_poly().as_expr())
else:
return self._print(expr.as_expr())
def _print_ComplexRootOf(self, expr):
args = [self._print_Add(expr.expr, order='lex'), expr.index]
pform = prettyForm(*self._print_seq(args).parens())
pform = prettyForm(*pform.left('CRootOf'))
return pform
def _print_RootSum(self, expr):
args = [self._print_Add(expr.expr, order='lex')]
if expr.fun is not S.IdentityFunction:
args.append(self._print(expr.fun))
pform = prettyForm(*self._print_seq(args).parens())
pform = prettyForm(*pform.left('RootSum'))
return pform
def _print_FiniteField(self, expr):
if self._use_unicode:
form = '\N{DOUBLE-STRUCK CAPITAL Z}_%d'
else:
form = 'GF(%d)'
return prettyForm(pretty_symbol(form % expr.mod))
def _print_IntegerRing(self, expr):
if self._use_unicode:
return prettyForm('\N{DOUBLE-STRUCK CAPITAL Z}')
else:
return prettyForm('ZZ')
def _print_RationalField(self, expr):
if self._use_unicode:
return prettyForm('\N{DOUBLE-STRUCK CAPITAL Q}')
else:
return prettyForm('QQ')
def _print_RealField(self, domain):
if self._use_unicode:
prefix = '\N{DOUBLE-STRUCK CAPITAL R}'
else:
prefix = 'RR'
if domain.has_default_precision:
return prettyForm(prefix)
else:
return self._print(pretty_symbol(prefix + "_" + str(domain.precision)))
def _print_ComplexField(self, domain):
if self._use_unicode:
prefix = '\N{DOUBLE-STRUCK CAPITAL C}'
else:
prefix = 'CC'
if domain.has_default_precision:
return prettyForm(prefix)
else:
return self._print(pretty_symbol(prefix + "_" + str(domain.precision)))
def _print_PolynomialRing(self, expr):
args = list(expr.symbols)
if not expr.order.is_default:
order = prettyForm(*prettyForm("order=").right(self._print(expr.order)))
args.append(order)
pform = self._print_seq(args, '[', ']')
pform = prettyForm(*pform.left(self._print(expr.domain)))
return pform
def _print_FractionField(self, expr):
args = list(expr.symbols)
if not expr.order.is_default:
order = prettyForm(*prettyForm("order=").right(self._print(expr.order)))
args.append(order)
pform = self._print_seq(args, '(', ')')
pform = prettyForm(*pform.left(self._print(expr.domain)))
return pform
def _print_PolynomialRingBase(self, expr):
g = expr.symbols
if str(expr.order) != str(expr.default_order):
g = g + ("order=" + str(expr.order),)
pform = self._print_seq(g, '[', ']')
pform = prettyForm(*pform.left(self._print(expr.domain)))
return pform
def _print_GroebnerBasis(self, basis):
exprs = [ self._print_Add(arg, order=basis.order)
for arg in basis.exprs ]
exprs = prettyForm(*self.join(", ", exprs).parens(left="[", right="]"))
gens = [ self._print(gen) for gen in basis.gens ]
domain = prettyForm(
*prettyForm("domain=").right(self._print(basis.domain)))
order = prettyForm(
*prettyForm("order=").right(self._print(basis.order)))
pform = self.join(", ", [exprs] + gens + [domain, order])
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left(basis.__class__.__name__))
return pform
def _print_Subs(self, e):
pform = self._print(e.expr)
pform = prettyForm(*pform.parens())
h = pform.height() if pform.height() > 1 else 2
rvert = stringPict(vobj('|', h), baseline=pform.baseline)
pform = prettyForm(*pform.right(rvert))
b = pform.baseline
pform.baseline = pform.height() - 1
pform = prettyForm(*pform.right(self._print_seq([
self._print_seq((self._print(v[0]), xsym('=='), self._print(v[1])),
delimiter='') for v in zip(e.variables, e.point) ])))
pform.baseline = b
return pform
def _print_number_function(self, e, name):
# Print name_arg[0] for one argument or name_arg[0](arg[1])
# for more than one argument
pform = prettyForm(name)
arg = self._print(e.args[0])
pform_arg = prettyForm(" "*arg.width())
pform_arg = prettyForm(*pform_arg.below(arg))
pform = prettyForm(*pform.right(pform_arg))
if len(e.args) == 1:
return pform
m, x = e.args
# TODO: copy-pasted from _print_Function: can we do better?
prettyFunc = pform
prettyArgs = prettyForm(*self._print_seq([x]).parens())
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform
def _print_euler(self, e):
return self._print_number_function(e, "E")
def _print_catalan(self, e):
return self._print_number_function(e, "C")
def _print_bernoulli(self, e):
return self._print_number_function(e, "B")
_print_bell = _print_bernoulli
def _print_lucas(self, e):
return self._print_number_function(e, "L")
def _print_fibonacci(self, e):
return self._print_number_function(e, "F")
def _print_tribonacci(self, e):
return self._print_number_function(e, "T")
def _print_stieltjes(self, e):
if self._use_unicode:
return self._print_number_function(e, '\N{GREEK SMALL LETTER GAMMA}')
else:
return self._print_number_function(e, "stieltjes")
def _print_KroneckerDelta(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.right(prettyForm(',')))
pform = prettyForm(*pform.right(self._print(e.args[1])))
if self._use_unicode:
a = stringPict(pretty_symbol('delta'))
else:
a = stringPict('d')
b = pform
top = stringPict(*b.left(' '*a.width()))
bot = stringPict(*a.right(' '*b.width()))
return prettyForm(binding=prettyForm.POW, *bot.below(top))
def _print_RandomDomain(self, d):
if hasattr(d, 'as_boolean'):
pform = self._print('Domain: ')
pform = prettyForm(*pform.right(self._print(d.as_boolean())))
return pform
elif hasattr(d, 'set'):
pform = self._print('Domain: ')
pform = prettyForm(*pform.right(self._print(d.symbols)))
pform = prettyForm(*pform.right(self._print(' in ')))
pform = prettyForm(*pform.right(self._print(d.set)))
return pform
elif hasattr(d, 'symbols'):
pform = self._print('Domain on ')
pform = prettyForm(*pform.right(self._print(d.symbols)))
return pform
else:
return self._print(None)
def _print_DMP(self, p):
try:
if p.ring is not None:
# TODO incorporate order
return self._print(p.ring.to_sympy(p))
except SympifyError:
pass
return self._print(repr(p))
def _print_DMF(self, p):
return self._print_DMP(p)
def _print_Object(self, object):
return self._print(pretty_symbol(object.name))
def _print_Morphism(self, morphism):
arrow = xsym("-->")
domain = self._print(morphism.domain)
codomain = self._print(morphism.codomain)
tail = domain.right(arrow, codomain)[0]
return prettyForm(tail)
def _print_NamedMorphism(self, morphism):
pretty_name = self._print(pretty_symbol(morphism.name))
pretty_morphism = self._print_Morphism(morphism)
return prettyForm(pretty_name.right(":", pretty_morphism)[0])
def _print_IdentityMorphism(self, morphism):
from sympy.categories import NamedMorphism
return self._print_NamedMorphism(
NamedMorphism(morphism.domain, morphism.codomain, "id"))
def _print_CompositeMorphism(self, morphism):
circle = xsym(".")
# All components of the morphism have names and it is thus
# possible to build the name of the composite.
component_names_list = [pretty_symbol(component.name) for
component in morphism.components]
component_names_list.reverse()
component_names = circle.join(component_names_list) + ":"
pretty_name = self._print(component_names)
pretty_morphism = self._print_Morphism(morphism)
return prettyForm(pretty_name.right(pretty_morphism)[0])
def _print_Category(self, category):
return self._print(pretty_symbol(category.name))
def _print_Diagram(self, diagram):
if not diagram.premises:
# This is an empty diagram.
return self._print(S.EmptySet)
pretty_result = self._print(diagram.premises)
if diagram.conclusions:
results_arrow = " %s " % xsym("==>")
pretty_conclusions = self._print(diagram.conclusions)[0]
pretty_result = pretty_result.right(
results_arrow, pretty_conclusions)
return prettyForm(pretty_result[0])
def _print_DiagramGrid(self, grid):
from sympy.matrices import Matrix
matrix = Matrix([[grid[i, j] if grid[i, j] else Symbol(" ")
for j in range(grid.width)]
for i in range(grid.height)])
return self._print_matrix_contents(matrix)
def _print_FreeModuleElement(self, m):
# Print as row vector for convenience, for now.
return self._print_seq(m, '[', ']')
def _print_SubModule(self, M):
return self._print_seq(M.gens, '<', '>')
def _print_FreeModule(self, M):
return self._print(M.ring)**self._print(M.rank)
def _print_ModuleImplementedIdeal(self, M):
return self._print_seq([x for [x] in M._module.gens], '<', '>')
def _print_QuotientRing(self, R):
return self._print(R.ring) / self._print(R.base_ideal)
def _print_QuotientRingElement(self, R):
return self._print(R.data) + self._print(R.ring.base_ideal)
def _print_QuotientModuleElement(self, m):
return self._print(m.data) + self._print(m.module.killed_module)
def _print_QuotientModule(self, M):
return self._print(M.base) / self._print(M.killed_module)
def _print_MatrixHomomorphism(self, h):
matrix = self._print(h._sympy_matrix())
matrix.baseline = matrix.height() // 2
pform = prettyForm(*matrix.right(' : ', self._print(h.domain),
' %s> ' % hobj('-', 2), self._print(h.codomain)))
return pform
def _print_Manifold(self, manifold):
return self._print(manifold.name)
def _print_Patch(self, patch):
return self._print(patch.name)
def _print_CoordSystem(self, coords):
return self._print(coords.name)
def _print_BaseScalarField(self, field):
string = field._coord_sys.symbols[field._index].name
return self._print(pretty_symbol(string))
def _print_BaseVectorField(self, field):
s = U('PARTIAL DIFFERENTIAL') + '_' + field._coord_sys.symbols[field._index].name
return self._print(pretty_symbol(s))
def _print_Differential(self, diff):
if self._use_unicode:
d = '\N{DOUBLE-STRUCK ITALIC SMALL D}'
else:
d = 'd'
field = diff._form_field
if hasattr(field, '_coord_sys'):
string = field._coord_sys.symbols[field._index].name
return self._print(d + ' ' + pretty_symbol(string))
else:
pform = self._print(field)
pform = prettyForm(*pform.parens())
return prettyForm(*pform.left(d))
def _print_Tr(self, p):
#TODO: Handle indices
pform = self._print(p.args[0])
pform = prettyForm(*pform.left('%s(' % (p.__class__.__name__)))
pform = prettyForm(*pform.right(')'))
return pform
def _print_primenu(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens())
if self._use_unicode:
pform = prettyForm(*pform.left(greek_unicode['nu']))
else:
pform = prettyForm(*pform.left('nu'))
return pform
def _print_primeomega(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens())
if self._use_unicode:
pform = prettyForm(*pform.left(greek_unicode['Omega']))
else:
pform = prettyForm(*pform.left('Omega'))
return pform
def _print_Quantity(self, e):
if e.name.name == 'degree':
pform = self._print("\N{DEGREE SIGN}")
return pform
else:
return self.emptyPrinter(e)
def _print_AssignmentBase(self, e):
op = prettyForm(' ' + xsym(e.op) + ' ')
l = self._print(e.lhs)
r = self._print(e.rhs)
pform = prettyForm(*stringPict.next(l, op, r))
return pform
def _print_Str(self, s):
return self._print(s.name)
@print_function(PrettyPrinter)
def pretty(expr, **settings):
"""Returns a string containing the prettified form of expr.
For information on keyword arguments see pretty_print function.
"""
pp = PrettyPrinter(settings)
# XXX: this is an ugly hack, but at least it works
use_unicode = pp._settings['use_unicode']
uflag = pretty_use_unicode(use_unicode)
try:
return pp.doprint(expr)
finally:
pretty_use_unicode(uflag)
def pretty_print(expr, **kwargs):
"""Prints expr in pretty form.
pprint is just a shortcut for this function.
Parameters
==========
expr : expression
The expression to print.
wrap_line : bool, optional (default=True)
Line wrapping enabled/disabled.
num_columns : int or None, optional (default=None)
Number of columns before line breaking (default to None which reads
the terminal width), useful when using SymPy without terminal.
use_unicode : bool or None, optional (default=None)
Use unicode characters, such as the Greek letter pi instead of
the string pi.
full_prec : bool or string, optional (default="auto")
Use full precision.
order : bool or string, optional (default=None)
Set to 'none' for long expressions if slow; default is None.
use_unicode_sqrt_char : bool, optional (default=True)
Use compact single-character square root symbol (when unambiguous).
root_notation : bool, optional (default=True)
Set to 'False' for printing exponents of the form 1/n in fractional form.
By default exponent is printed in root form.
mat_symbol_style : string, optional (default="plain")
Set to "bold" for printing MatrixSymbols using a bold mathematical symbol face.
By default the standard face is used.
imaginary_unit : string, optional (default="i")
Letter to use for imaginary unit when use_unicode is True.
Can be "i" (default) or "j".
"""
print(pretty(expr, **kwargs))
pprint = pretty_print
def pager_print(expr, **settings):
"""Prints expr using the pager, in pretty form.
This invokes a pager command using pydoc. Lines are not wrapped
automatically. This routine is meant to be used with a pager that allows
sideways scrolling, like ``less -S``.
Parameters are the same as for ``pretty_print``. If you wish to wrap lines,
pass ``num_columns=None`` to auto-detect the width of the terminal.
"""
from pydoc import pager
from locale import getpreferredencoding
if 'num_columns' not in settings:
settings['num_columns'] = 500000 # disable line wrap
pager(pretty(expr, **settings).encode(getpreferredencoding()))
|
edf1a77203f3bd46d28ed96db2efa4c220853eff6d265bf6ccf2d1168dd990dc | from sympy.concrete.summations import Sum
from sympy.core.mod import Mod
from sympy.core.relational import (Equality, Unequality)
from sympy.core.symbol import Symbol
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.special.gamma_functions import polygamma
from sympy.functions.special.error_functions import (Si, Ci)
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import Identity
from sympy.utilities.lambdify import lambdify
from sympy.abc import x, i, j, a, b, c, d
from sympy.core import Pow
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.codegen.cfunctions import log1p, expm1, hypot, log10, exp2, log2, Sqrt
from sympy.tensor.array import Array
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, \
PermuteDims, ArrayDiagonal
from sympy.printing.numpy import NumPyPrinter, SciPyPrinter, _numpy_known_constants, \
_numpy_known_functions, _scipy_known_constants, _scipy_known_functions
from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
from sympy.testing.pytest import skip, raises
from sympy.external import import_module
np = import_module('numpy')
if np:
deafult_float_info = np.finfo(np.array([]).dtype)
NUMPY_DEFAULT_EPSILON = deafult_float_info.eps
def test_numpy_piecewise_regression():
"""
NumPyPrinter needs to print Piecewise()'s choicelist as a list to avoid
breaking compatibility with numpy 1.8. This is not necessary in numpy 1.9+.
See gh-9747 and gh-9749 for details.
"""
printer = NumPyPrinter()
p = Piecewise((1, x < 0), (0, True))
assert printer.doprint(p) == \
'numpy.select([numpy.less(x, 0),True], [1,0], default=numpy.nan)'
assert printer.module_imports == {'numpy': {'select', 'less', 'nan'}}
def test_numpy_logaddexp():
lae = logaddexp(a, b)
assert NumPyPrinter().doprint(lae) == 'numpy.logaddexp(a, b)'
lae2 = logaddexp2(a, b)
assert NumPyPrinter().doprint(lae2) == 'numpy.logaddexp2(a, b)'
def test_sum():
if not np:
skip("NumPy not installed")
s = Sum(x ** i, (i, a, b))
f = lambdify((a, b, x), s, 'numpy')
a_, b_ = 0, 10
x_ = np.linspace(-1, +1, 10)
assert np.allclose(f(a_, b_, x_), sum(x_ ** i_ for i_ in range(a_, b_ + 1)))
s = Sum(i * x, (i, a, b))
f = lambdify((a, b, x), s, 'numpy')
a_, b_ = 0, 10
x_ = np.linspace(-1, +1, 10)
assert np.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1)))
def test_multiple_sums():
if not np:
skip("NumPy not installed")
s = Sum((x + j) * i, (i, a, b), (j, c, d))
f = lambdify((a, b, c, d, x), s, 'numpy')
a_, b_ = 0, 10
c_, d_ = 11, 21
x_ = np.linspace(-1, +1, 10)
assert np.allclose(f(a_, b_, c_, d_, x_),
sum((x_ + j_) * i_ for i_ in range(a_, b_ + 1) for j_ in range(c_, d_ + 1)))
def test_codegen_einsum():
if not np:
skip("NumPy not installed")
M = MatrixSymbol("M", 2, 2)
N = MatrixSymbol("N", 2, 2)
cg = convert_matrix_to_array(M * N)
f = lambdify((M, N), cg, 'numpy')
ma = np.array([[1, 2], [3, 4]])
mb = np.array([[1,-2], [-1, 3]])
assert (f(ma, mb) == np.matmul(ma, mb)).all()
def test_codegen_extra():
if not np:
skip("NumPy not installed")
M = MatrixSymbol("M", 2, 2)
N = MatrixSymbol("N", 2, 2)
P = MatrixSymbol("P", 2, 2)
Q = MatrixSymbol("Q", 2, 2)
ma = np.array([[1, 2], [3, 4]])
mb = np.array([[1,-2], [-1, 3]])
mc = np.array([[2, 0], [1, 2]])
md = np.array([[1,-1], [4, 7]])
cg = ArrayTensorProduct(M, N)
f = lambdify((M, N), cg, 'numpy')
assert (f(ma, mb) == np.einsum(ma, [0, 1], mb, [2, 3])).all()
cg = ArrayAdd(M, N)
f = lambdify((M, N), cg, 'numpy')
assert (f(ma, mb) == ma+mb).all()
cg = ArrayAdd(M, N, P)
f = lambdify((M, N, P), cg, 'numpy')
assert (f(ma, mb, mc) == ma+mb+mc).all()
cg = ArrayAdd(M, N, P, Q)
f = lambdify((M, N, P, Q), cg, 'numpy')
assert (f(ma, mb, mc, md) == ma+mb+mc+md).all()
cg = PermuteDims(M, [1, 0])
f = lambdify((M,), cg, 'numpy')
assert (f(ma) == ma.T).all()
cg = PermuteDims(ArrayTensorProduct(M, N), [1, 2, 3, 0])
f = lambdify((M, N), cg, 'numpy')
assert (f(ma, mb) == np.transpose(np.einsum(ma, [0, 1], mb, [2, 3]), (1, 2, 3, 0))).all()
cg = ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2))
f = lambdify((M, N), cg, 'numpy')
assert (f(ma, mb) == np.diagonal(np.einsum(ma, [0, 1], mb, [2, 3]), axis1=1, axis2=2)).all()
def test_relational():
if not np:
skip("NumPy not installed")
e = Equality(x, 1)
f = lambdify((x,), e)
x_ = np.array([0, 1, 2])
assert np.array_equal(f(x_), [False, True, False])
e = Unequality(x, 1)
f = lambdify((x,), e)
x_ = np.array([0, 1, 2])
assert np.array_equal(f(x_), [True, False, True])
e = (x < 1)
f = lambdify((x,), e)
x_ = np.array([0, 1, 2])
assert np.array_equal(f(x_), [True, False, False])
e = (x <= 1)
f = lambdify((x,), e)
x_ = np.array([0, 1, 2])
assert np.array_equal(f(x_), [True, True, False])
e = (x > 1)
f = lambdify((x,), e)
x_ = np.array([0, 1, 2])
assert np.array_equal(f(x_), [False, False, True])
e = (x >= 1)
f = lambdify((x,), e)
x_ = np.array([0, 1, 2])
assert np.array_equal(f(x_), [False, True, True])
def test_mod():
if not np:
skip("NumPy not installed")
e = Mod(a, b)
f = lambdify((a, b), e)
a_ = np.array([0, 1, 2, 3])
b_ = 2
assert np.array_equal(f(a_, b_), [0, 1, 0, 1])
a_ = np.array([0, 1, 2, 3])
b_ = np.array([2, 2, 2, 2])
assert np.array_equal(f(a_, b_), [0, 1, 0, 1])
a_ = np.array([2, 3, 4, 5])
b_ = np.array([2, 3, 4, 5])
assert np.array_equal(f(a_, b_), [0, 0, 0, 0])
def test_pow():
if not np:
skip('NumPy not installed')
expr = Pow(2, -1, evaluate=False)
f = lambdify([], expr, 'numpy')
assert f() == 0.5
def test_expm1():
if not np:
skip("NumPy not installed")
f = lambdify((a,), expm1(a), 'numpy')
assert abs(f(1e-10) - 1e-10 - 5e-21) <= 1e-10 * NUMPY_DEFAULT_EPSILON
def test_log1p():
if not np:
skip("NumPy not installed")
f = lambdify((a,), log1p(a), 'numpy')
assert abs(f(1e-99) - 1e-99) <= 1e-99 * NUMPY_DEFAULT_EPSILON
def test_hypot():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a, b), hypot(a, b), 'numpy')(3, 4) - 5) <= NUMPY_DEFAULT_EPSILON
def test_log10():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), log10(a), 'numpy')(100) - 2) <= NUMPY_DEFAULT_EPSILON
def test_exp2():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), exp2(a), 'numpy')(5) - 32) <= NUMPY_DEFAULT_EPSILON
def test_log2():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), log2(a), 'numpy')(256) - 8) <= NUMPY_DEFAULT_EPSILON
def test_Sqrt():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), Sqrt(a), 'numpy')(4) - 2) <= NUMPY_DEFAULT_EPSILON
def test_sqrt():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), sqrt(a), 'numpy')(4) - 2) <= NUMPY_DEFAULT_EPSILON
def test_matsolve():
if not np:
skip("NumPy not installed")
M = MatrixSymbol("M", 3, 3)
x = MatrixSymbol("x", 3, 1)
expr = M**(-1) * x + x
matsolve_expr = MatrixSolve(M, x) + x
f = lambdify((M, x), expr)
f_matsolve = lambdify((M, x), matsolve_expr)
m0 = np.array([[1, 2, 3], [3, 2, 5], [5, 6, 7]])
assert np.linalg.matrix_rank(m0) == 3
x0 = np.array([3, 4, 5])
assert np.allclose(f_matsolve(m0, x0), f(m0, x0))
def test_16857():
if not np:
skip("NumPy not installed")
a_1 = MatrixSymbol('a_1', 10, 3)
a_2 = MatrixSymbol('a_2', 10, 3)
a_3 = MatrixSymbol('a_3', 10, 3)
a_4 = MatrixSymbol('a_4', 10, 3)
A = BlockMatrix([[a_1, a_2], [a_3, a_4]])
assert A.shape == (20, 6)
printer = NumPyPrinter()
assert printer.doprint(A) == 'numpy.block([[a_1, a_2], [a_3, a_4]])'
def test_issue_17006():
if not np:
skip("NumPy not installed")
M = MatrixSymbol("M", 2, 2)
f = lambdify(M, M + Identity(2))
ma = np.array([[1, 2], [3, 4]])
mr = np.array([[2, 2], [3, 5]])
assert (f(ma) == mr).all()
from sympy.core.symbol import symbols
n = symbols('n', integer=True)
N = MatrixSymbol("M", n, n)
raises(NotImplementedError, lambda: lambdify(N, N + Identity(n)))
def test_numpy_array():
assert NumPyPrinter().doprint(Array(((1, 2), (3, 5)))) == 'numpy.array([[1, 2], [3, 5]])'
assert NumPyPrinter().doprint(Array((1, 2))) == 'numpy.array((1, 2))'
def test_numpy_known_funcs_consts():
assert _numpy_known_constants['NaN'] == 'numpy.nan'
assert _numpy_known_constants['EulerGamma'] == 'numpy.euler_gamma'
assert _numpy_known_functions['acos'] == 'numpy.arccos'
assert _numpy_known_functions['log'] == 'numpy.log'
def test_scipy_known_funcs_consts():
assert _scipy_known_constants['GoldenRatio'] == 'scipy.constants.golden_ratio'
assert _scipy_known_constants['Pi'] == 'scipy.constants.pi'
assert _scipy_known_functions['erf'] == 'scipy.special.erf'
assert _scipy_known_functions['factorial'] == 'scipy.special.factorial'
def test_numpy_print_methods():
prntr = NumPyPrinter()
assert hasattr(prntr, '_print_acos')
assert hasattr(prntr, '_print_log')
def test_scipy_print_methods():
prntr = SciPyPrinter()
assert hasattr(prntr, '_print_acos')
assert hasattr(prntr, '_print_log')
assert hasattr(prntr, '_print_erf')
assert hasattr(prntr, '_print_factorial')
assert hasattr(prntr, '_print_chebyshevt')
k = Symbol('k', integer=True, nonnegative=True)
x = Symbol('x', real=True)
assert prntr.doprint(polygamma(k, x)) == "scipy.special.polygamma(k, x)"
assert prntr.doprint(Si(x)) == "scipy.special.sici(x)[0]"
assert prntr.doprint(Ci(x)) == "scipy.special.sici(x)[1]"
|
3731a1911da950c7ddf25214d9c151f5b15ad09f3d473a47b37cc3820016b57a | from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.core import S, Rational
from sympy.integrals.intpoly import (decompose, best_origin, distance_to_side,
polytope_integrate, point_sort,
hyperplane_parameters, main_integrate3d,
main_integrate, polygon_integrate,
lineseg_integrate, integration_reduction,
integration_reduction_dynamic, is_vertex)
from sympy.geometry.line import Segment2D
from sympy.geometry.polygon import Polygon
from sympy.geometry.point import Point, Point2D
from sympy.abc import x, y, z
from sympy.testing.pytest import slow
def test_decompose():
assert decompose(x) == {1: x}
assert decompose(x**2) == {2: x**2}
assert decompose(x*y) == {2: x*y}
assert decompose(x + y) == {1: x + y}
assert decompose(x**2 + y) == {1: y, 2: x**2}
assert decompose(8*x**2 + 4*y + 7) == {0: 7, 1: 4*y, 2: 8*x**2}
assert decompose(x**2 + 3*y*x) == {2: x**2 + 3*x*y}
assert decompose(9*x**2 + y + 4*x + x**3 + y**2*x + 3) ==\
{0: 3, 1: 4*x + y, 2: 9*x**2, 3: x**3 + x*y**2}
assert decompose(x, True) == {x}
assert decompose(x ** 2, True) == {x**2}
assert decompose(x * y, True) == {x * y}
assert decompose(x + y, True) == {x, y}
assert decompose(x ** 2 + y, True) == {y, x ** 2}
assert decompose(8 * x ** 2 + 4 * y + 7, True) == {7, 4*y, 8*x**2}
assert decompose(x ** 2 + 3 * y * x, True) == {x ** 2, 3 * x * y}
assert decompose(9 * x ** 2 + y + 4 * x + x ** 3 + y ** 2 * x + 3, True) == \
{3, y, 4*x, 9*x**2, x*y**2, x**3}
def test_best_origin():
expr1 = y ** 2 * x ** 5 + y ** 5 * x ** 7 + 7 * x + x ** 12 + y ** 7 * x
l1 = Segment2D(Point(0, 3), Point(1, 1))
l2 = Segment2D(Point(S(3) / 2, 0), Point(S(3) / 2, 3))
l3 = Segment2D(Point(0, S(3) / 2), Point(3, S(3) / 2))
l4 = Segment2D(Point(0, 2), Point(2, 0))
l5 = Segment2D(Point(0, 2), Point(1, 1))
l6 = Segment2D(Point(2, 0), Point(1, 1))
assert best_origin((2, 1), 3, l1, expr1) == (0, 3)
# XXX: Should these return exact Rational output? Maybe best_origin should
# sympify its arguments...
assert best_origin((2, 0), 3, l2, x ** 7) == (1.5, 0)
assert best_origin((0, 2), 3, l3, x ** 7) == (0, 1.5)
assert best_origin((1, 1), 2, l4, x ** 7 * y ** 3) == (0, 2)
assert best_origin((1, 1), 2, l4, x ** 3 * y ** 7) == (2, 0)
assert best_origin((1, 1), 2, l5, x ** 2 * y ** 9) == (0, 2)
assert best_origin((1, 1), 2, l6, x ** 9 * y ** 2) == (2, 0)
@slow
def test_polytope_integrate():
# Convex 2-Polytopes
# Vertex representation
assert polytope_integrate(Polygon(Point(0, 0), Point(0, 2),
Point(4, 0)), 1) == 4
assert polytope_integrate(Polygon(Point(0, 0), Point(0, 1),
Point(1, 1), Point(1, 0)), x * y) ==\
Rational(1, 4)
assert polytope_integrate(Polygon(Point(0, 3), Point(5, 3), Point(1, 1)),
6*x**2 - 40*y) == Rational(-935, 3)
assert polytope_integrate(Polygon(Point(0, 0), Point(0, sqrt(3)),
Point(sqrt(3), sqrt(3)),
Point(sqrt(3), 0)), 1) == 3
hexagon = Polygon(Point(0, 0), Point(-sqrt(3) / 2, S.Half),
Point(-sqrt(3) / 2, S(3) / 2), Point(0, 2),
Point(sqrt(3) / 2, S(3) / 2), Point(sqrt(3) / 2, S.Half))
assert polytope_integrate(hexagon, 1) == S(3*sqrt(3)) / 2
# Hyperplane representation
assert polytope_integrate([((-1, 0), 0), ((1, 2), 4),
((0, -1), 0)], 1) == 4
assert polytope_integrate([((-1, 0), 0), ((0, 1), 1),
((1, 0), 1), ((0, -1), 0)], x * y) == Rational(1, 4)
assert polytope_integrate([((0, 1), 3), ((1, -2), -1),
((-2, -1), -3)], 6*x**2 - 40*y) == Rational(-935, 3)
assert polytope_integrate([((-1, 0), 0), ((0, sqrt(3)), 3),
((sqrt(3), 0), 3), ((0, -1), 0)], 1) == 3
hexagon = [((Rational(-1, 2), -sqrt(3) / 2), 0),
((-1, 0), sqrt(3) / 2),
((Rational(-1, 2), sqrt(3) / 2), sqrt(3)),
((S.Half, sqrt(3) / 2), sqrt(3)),
((1, 0), sqrt(3) / 2),
((S.Half, -sqrt(3) / 2), 0)]
assert polytope_integrate(hexagon, 1) == S(3*sqrt(3)) / 2
# Non-convex polytopes
# Vertex representation
assert polytope_integrate(Polygon(Point(-1, -1), Point(-1, 1),
Point(1, 1), Point(0, 0),
Point(1, -1)), 1) == 3
assert polytope_integrate(Polygon(Point(-1, -1), Point(-1, 1),
Point(0, 0), Point(1, 1),
Point(1, -1), Point(0, 0)), 1) == 2
# Hyperplane representation
assert polytope_integrate([((-1, 0), 1), ((0, 1), 1), ((1, -1), 0),
((1, 1), 0), ((0, -1), 1)], 1) == 3
assert polytope_integrate([((-1, 0), 1), ((1, 1), 0), ((-1, 1), 0),
((1, 0), 1), ((-1, -1), 0),
((1, -1), 0)], 1) == 2
# Tests for 2D polytopes mentioned in Chin et al(Page 10):
# http://dilbert.engr.ucdavis.edu/~suku/quadrature/cls-integration.pdf
fig1 = Polygon(Point(1.220, -0.827), Point(-1.490, -4.503),
Point(-3.766, -1.622), Point(-4.240, -0.091),
Point(-3.160, 4), Point(-0.981, 4.447),
Point(0.132, 4.027))
assert polytope_integrate(fig1, x**2 + x*y + y**2) ==\
S(2031627344735367)/(8*10**12)
fig2 = Polygon(Point(4.561, 2.317), Point(1.491, -1.315),
Point(-3.310, -3.164), Point(-4.845, -3.110),
Point(-4.569, 1.867))
assert polytope_integrate(fig2, x**2 + x*y + y**2) ==\
S(517091313866043)/(16*10**11)
fig3 = Polygon(Point(-2.740, -1.888), Point(-3.292, 4.233),
Point(-2.723, -0.697), Point(-0.643, -3.151))
assert polytope_integrate(fig3, x**2 + x*y + y**2) ==\
S(147449361647041)/(8*10**12)
fig4 = Polygon(Point(0.211, -4.622), Point(-2.684, 3.851),
Point(0.468, 4.879), Point(4.630, -1.325),
Point(-0.411, -1.044))
assert polytope_integrate(fig4, x**2 + x*y + y**2) ==\
S(180742845225803)/(10**12)
# Tests for many polynomials with maximum degree given(2D case).
tri = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
polys = []
expr1 = x**9*y + x**7*y**3 + 2*x**2*y**8
expr2 = x**6*y**4 + x**5*y**5 + 2*y**10
expr3 = x**10 + x**9*y + x**8*y**2 + x**5*y**5
polys.extend((expr1, expr2, expr3))
result_dict = polytope_integrate(tri, polys, max_degree=10)
assert result_dict[expr1] == Rational(615780107, 594)
assert result_dict[expr2] == Rational(13062161, 27)
assert result_dict[expr3] == Rational(1946257153, 924)
tri = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
expr1 = x**7*y**1 + 2*x**2*y**6
expr2 = x**6*y**4 + x**5*y**5 + 2*y**10
expr3 = x**10 + x**9*y + x**8*y**2 + x**5*y**5
polys.extend((expr1, expr2, expr3))
assert polytope_integrate(tri, polys, max_degree=9) == \
{x**7*y + 2*x**2*y**6: Rational(489262, 9)}
# Tests when all integral of all monomials up to a max_degree is to be
# calculated.
assert polytope_integrate(Polygon(Point(0, 0), Point(0, 1),
Point(1, 1), Point(1, 0)),
max_degree=4) == {0: 0, 1: 1, x: S.Half,
x ** 2 * y ** 2: S.One / 9,
x ** 4: S.One / 5,
y ** 4: S.One / 5,
y: S.Half,
x * y ** 2: S.One / 6,
y ** 2: S.One / 3,
x ** 3: S.One / 4,
x ** 2 * y: S.One / 6,
x ** 3 * y: S.One / 8,
x * y: S.One / 4,
y ** 3: S.One / 4,
x ** 2: S.One / 3,
x * y ** 3: S.One / 8}
# Tests for 3D polytopes
cube1 = [[(0, 0, 0), (0, 6, 6), (6, 6, 6), (3, 6, 0),
(0, 6, 0), (6, 0, 6), (3, 0, 0), (0, 0, 6)],
[1, 2, 3, 4], [3, 2, 5, 6], [1, 7, 5, 2], [0, 6, 5, 7],
[1, 4, 0, 7], [0, 4, 3, 6]]
assert polytope_integrate(cube1, 1) == S(162)
# 3D Test cases in Chin et al(2015)
cube2 = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),
(5, 0, 5), (5, 5, 0), (5, 5, 5)],
[3, 7, 6, 2], [1, 5, 7, 3], [5, 4, 6, 7], [0, 4, 5, 1],
[2, 0, 1, 3], [2, 6, 4, 0]]
cube3 = [[(0, 0, 0), (5, 0, 0), (5, 4, 0), (3, 2, 0), (3, 5, 0),
(0, 5, 0), (0, 0, 5), (5, 0, 5), (5, 4, 5), (3, 2, 5),
(3, 5, 5), (0, 5, 5)],
[6, 11, 5, 0], [1, 7, 6, 0], [5, 4, 3, 2, 1, 0], [11, 10, 4, 5],
[10, 9, 3, 4], [9, 8, 2, 3], [8, 7, 1, 2], [7, 8, 9, 10, 11, 6]]
cube4 = [[(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1),
(S.One / 4, S.One / 4, S.One / 4)],
[0, 2, 1], [1, 3, 0], [4, 2, 3], [4, 3, 1],
[0, 1, 2], [2, 4, 1], [0, 3, 2]]
assert polytope_integrate(cube2, x ** 2 + y ** 2 + x * y + z ** 2) ==\
Rational(15625, 4)
assert polytope_integrate(cube3, x ** 2 + y ** 2 + x * y + z ** 2) ==\
S(33835) / 12
assert polytope_integrate(cube4, x ** 2 + y ** 2 + x * y + z ** 2) ==\
S(37) / 960
# Test cases from Mathematica's PolyhedronData library
octahedron = [[(S.NegativeOne / sqrt(2), 0, 0), (0, S.One / sqrt(2), 0),
(0, 0, S.NegativeOne / sqrt(2)), (0, 0, S.One / sqrt(2)),
(0, S.NegativeOne / sqrt(2), 0), (S.One / sqrt(2), 0, 0)],
[3, 4, 5], [3, 5, 1], [3, 1, 0], [3, 0, 4], [4, 0, 2],
[4, 2, 5], [2, 0, 1], [5, 2, 1]]
assert polytope_integrate(octahedron, 1) == sqrt(2) / 3
great_stellated_dodecahedron =\
[[(-0.32491969623290634095, 0, 0.42532540417601993887),
(0.32491969623290634095, 0, -0.42532540417601993887),
(-0.52573111211913359231, 0, 0.10040570794311363956),
(0.52573111211913359231, 0, -0.10040570794311363956),
(-0.10040570794311363956, -0.3090169943749474241, 0.42532540417601993887),
(-0.10040570794311363956, 0.30901699437494742410, 0.42532540417601993887),
(0.10040570794311363956, -0.3090169943749474241, -0.42532540417601993887),
(0.10040570794311363956, 0.30901699437494742410, -0.42532540417601993887),
(-0.16245984811645317047, -0.5, 0.10040570794311363956),
(-0.16245984811645317047, 0.5, 0.10040570794311363956),
(0.16245984811645317047, -0.5, -0.10040570794311363956),
(0.16245984811645317047, 0.5, -0.10040570794311363956),
(-0.42532540417601993887, -0.3090169943749474241, -0.10040570794311363956),
(-0.42532540417601993887, 0.30901699437494742410, -0.10040570794311363956),
(-0.26286555605956679615, 0.1909830056250525759, -0.42532540417601993887),
(-0.26286555605956679615, -0.1909830056250525759, -0.42532540417601993887),
(0.26286555605956679615, 0.1909830056250525759, 0.42532540417601993887),
(0.26286555605956679615, -0.1909830056250525759, 0.42532540417601993887),
(0.42532540417601993887, -0.3090169943749474241, 0.10040570794311363956),
(0.42532540417601993887, 0.30901699437494742410, 0.10040570794311363956)],
[12, 3, 0, 6, 16], [17, 7, 0, 3, 13],
[9, 6, 0, 7, 8], [18, 2, 1, 4, 14],
[15, 5, 1, 2, 19], [11, 4, 1, 5, 10],
[8, 19, 2, 18, 9], [10, 13, 3, 12, 11],
[16, 14, 4, 11, 12], [13, 10, 5, 15, 17],
[14, 16, 6, 9, 18], [19, 8, 7, 17, 15]]
# Actual volume is : 0.163118960624632
assert Abs(polytope_integrate(great_stellated_dodecahedron, 1) -\
0.163118960624632) < 1e-12
expr = x **2 + y ** 2 + z ** 2
octahedron_five_compound = [[(0, -0.7071067811865475244, 0),
(0, 0.70710678118654752440, 0),
(0.1148764602736805918,
-0.35355339059327376220, -0.60150095500754567366),
(0.1148764602736805918, 0.35355339059327376220,
-0.60150095500754567366),
(0.18587401723009224507,
-0.57206140281768429760, 0.37174803446018449013),
(0.18587401723009224507, 0.57206140281768429760,
0.37174803446018449013),
(0.30075047750377283683, -0.21850801222441053540,
0.60150095500754567366),
(0.30075047750377283683, 0.21850801222441053540,
0.60150095500754567366),
(0.48662449473386508189, -0.35355339059327376220,
-0.37174803446018449013),
(0.48662449473386508189, 0.35355339059327376220,
-0.37174803446018449013),
(-0.60150095500754567366, 0, -0.37174803446018449013),
(-0.30075047750377283683, -0.21850801222441053540,
-0.60150095500754567366),
(-0.30075047750377283683, 0.21850801222441053540,
-0.60150095500754567366),
(0.60150095500754567366, 0, 0.37174803446018449013),
(0.4156269377774534286, -0.57206140281768429760, 0),
(0.4156269377774534286, 0.57206140281768429760, 0),
(0.37174803446018449013, 0, -0.60150095500754567366),
(-0.4156269377774534286, -0.57206140281768429760, 0),
(-0.4156269377774534286, 0.57206140281768429760, 0),
(-0.67249851196395732696, -0.21850801222441053540, 0),
(-0.67249851196395732696, 0.21850801222441053540, 0),
(0.67249851196395732696, -0.21850801222441053540, 0),
(0.67249851196395732696, 0.21850801222441053540, 0),
(-0.37174803446018449013, 0, 0.60150095500754567366),
(-0.48662449473386508189, -0.35355339059327376220,
0.37174803446018449013),
(-0.48662449473386508189, 0.35355339059327376220,
0.37174803446018449013),
(-0.18587401723009224507, -0.57206140281768429760,
-0.37174803446018449013),
(-0.18587401723009224507, 0.57206140281768429760,
-0.37174803446018449013),
(-0.11487646027368059176, -0.35355339059327376220,
0.60150095500754567366),
(-0.11487646027368059176, 0.35355339059327376220,
0.60150095500754567366)],
[0, 10, 16], [23, 10, 0], [16, 13, 0],
[0, 13, 23], [16, 10, 1], [1, 10, 23],
[1, 13, 16], [23, 13, 1], [2, 4, 19],
[22, 4, 2], [2, 19, 27], [27, 22, 2],
[20, 5, 3], [3, 5, 21], [26, 20, 3],
[3, 21, 26], [29, 19, 4], [4, 22, 29],
[5, 20, 28], [28, 21, 5], [6, 8, 15],
[17, 8, 6], [6, 15, 25], [25, 17, 6],
[14, 9, 7], [7, 9, 18], [24, 14, 7],
[7, 18, 24], [8, 12, 15], [17, 12, 8],
[14, 11, 9], [9, 11, 18], [11, 14, 24],
[24, 18, 11], [25, 15, 12], [12, 17, 25],
[29, 27, 19], [20, 26, 28], [28, 26, 21],
[22, 27, 29]]
assert Abs(polytope_integrate(octahedron_five_compound, expr)) - 0.353553\
< 1e-6
cube_five_compound = [[(-0.1624598481164531631, -0.5, -0.6881909602355867691),
(-0.1624598481164531631, 0.5, -0.6881909602355867691),
(0.1624598481164531631, -0.5, 0.68819096023558676910),
(0.1624598481164531631, 0.5, 0.68819096023558676910),
(-0.52573111211913359231, 0, -0.6881909602355867691),
(0.52573111211913359231, 0, 0.68819096023558676910),
(-0.26286555605956679615, -0.8090169943749474241,
-0.1624598481164531631),
(-0.26286555605956679615, 0.8090169943749474241,
-0.1624598481164531631),
(0.26286555605956680301, -0.8090169943749474241,
0.1624598481164531631),
(0.26286555605956680301, 0.8090169943749474241,
0.1624598481164531631),
(-0.42532540417601993887, -0.3090169943749474241,
0.68819096023558676910),
(-0.42532540417601993887, 0.30901699437494742410,
0.68819096023558676910),
(0.42532540417601996609, -0.3090169943749474241,
-0.6881909602355867691),
(0.42532540417601996609, 0.30901699437494742410,
-0.6881909602355867691),
(-0.6881909602355867691, -0.5, 0.1624598481164531631),
(-0.6881909602355867691, 0.5, 0.1624598481164531631),
(0.68819096023558676910, -0.5, -0.1624598481164531631),
(0.68819096023558676910, 0.5, -0.1624598481164531631),
(-0.85065080835203998877, 0, -0.1624598481164531631),
(0.85065080835203993218, 0, 0.1624598481164531631)],
[18, 10, 3, 7], [13, 19, 8, 0], [18, 0, 8, 10],
[3, 19, 13, 7], [18, 7, 13, 0], [8, 19, 3, 10],
[6, 2, 11, 18], [1, 9, 19, 12], [11, 9, 1, 18],
[6, 12, 19, 2], [1, 12, 6, 18], [11, 2, 19, 9],
[4, 14, 11, 7], [17, 5, 8, 12], [4, 12, 8, 14],
[11, 5, 17, 7], [4, 7, 17, 12], [8, 5, 11, 14],
[6, 10, 15, 4], [13, 9, 5, 16], [15, 9, 13, 4],
[6, 16, 5, 10], [13, 16, 6, 4], [15, 10, 5, 9],
[14, 15, 1, 0], [16, 17, 3, 2], [14, 2, 3, 15],
[1, 17, 16, 0], [14, 0, 16, 2], [3, 17, 1, 15]]
assert Abs(polytope_integrate(cube_five_compound, expr) - 1.25) < 1e-12
echidnahedron = [[(0, 0, -2.4898982848827801995),
(0, 0, 2.4898982848827802734),
(0, -4.2360679774997896964, -2.4898982848827801995),
(0, -4.2360679774997896964, 2.4898982848827802734),
(0, 4.2360679774997896964, -2.4898982848827801995),
(0, 4.2360679774997896964, 2.4898982848827802734),
(-4.0287400534704067567, -1.3090169943749474241, -2.4898982848827801995),
(-4.0287400534704067567, -1.3090169943749474241, 2.4898982848827802734),
(-4.0287400534704067567, 1.3090169943749474241, -2.4898982848827801995),
(-4.0287400534704067567, 1.3090169943749474241, 2.4898982848827802734),
(4.0287400534704069747, -1.3090169943749474241, -2.4898982848827801995),
(4.0287400534704069747, -1.3090169943749474241, 2.4898982848827802734),
(4.0287400534704069747, 1.3090169943749474241, -2.4898982848827801995),
(4.0287400534704069747, 1.3090169943749474241, 2.4898982848827802734),
(-2.4898982848827801995, -3.4270509831248422723, -2.4898982848827801995),
(-2.4898982848827801995, -3.4270509831248422723, 2.4898982848827802734),
(-2.4898982848827801995, 3.4270509831248422723, -2.4898982848827801995),
(-2.4898982848827801995, 3.4270509831248422723, 2.4898982848827802734),
(2.4898982848827802734, -3.4270509831248422723, -2.4898982848827801995),
(2.4898982848827802734, -3.4270509831248422723, 2.4898982848827802734),
(2.4898982848827802734, 3.4270509831248422723, -2.4898982848827801995),
(2.4898982848827802734, 3.4270509831248422723, 2.4898982848827802734),
(-4.7169310137059934362, -0.8090169943749474241, -1.1135163644116066184),
(-4.7169310137059934362, 0.8090169943749474241, -1.1135163644116066184),
(4.7169310137059937438, -0.8090169943749474241, 1.11351636441160673519),
(4.7169310137059937438, 0.8090169943749474241, 1.11351636441160673519),
(-4.2916056095299737777, -2.1180339887498948482, 1.11351636441160673519),
(-4.2916056095299737777, 2.1180339887498948482, 1.11351636441160673519),
(4.2916056095299737777, -2.1180339887498948482, -1.1135163644116066184),
(4.2916056095299737777, 2.1180339887498948482, -1.1135163644116066184),
(-3.6034146492943870399, 0, -3.3405490932348205213),
(3.6034146492943870399, 0, 3.3405490932348202056),
(-3.3405490932348205213, -3.4270509831248422723, 1.11351636441160673519),
(-3.3405490932348205213, 3.4270509831248422723, 1.11351636441160673519),
(3.3405490932348202056, -3.4270509831248422723, -1.1135163644116066184),
(3.3405490932348202056, 3.4270509831248422723, -1.1135163644116066184),
(-2.9152236890588002395, -2.1180339887498948482, 3.3405490932348202056),
(-2.9152236890588002395, 2.1180339887498948482, 3.3405490932348202056),
(2.9152236890588002395, -2.1180339887498948482, -3.3405490932348205213),
(2.9152236890588002395, 2.1180339887498948482, -3.3405490932348205213),
(-2.2270327288232132368, 0, -1.1135163644116066184),
(-2.2270327288232132368, -4.2360679774997896964, -1.1135163644116066184),
(-2.2270327288232132368, 4.2360679774997896964, -1.1135163644116066184),
(2.2270327288232134704, 0, 1.11351636441160673519),
(2.2270327288232134704, -4.2360679774997896964, 1.11351636441160673519),
(2.2270327288232134704, 4.2360679774997896964, 1.11351636441160673519),
(-1.8017073246471935200, -1.3090169943749474241, 1.11351636441160673519),
(-1.8017073246471935200, 1.3090169943749474241, 1.11351636441160673519),
(1.8017073246471935043, -1.3090169943749474241, -1.1135163644116066184),
(1.8017073246471935043, 1.3090169943749474241, -1.1135163644116066184),
(-1.3763819204711735382, 0, -4.7169310137059934362),
(-1.3763819204711735382, 0, 0.26286555605956679615),
(1.37638192047117353821, 0, 4.7169310137059937438),
(1.37638192047117353821, 0, -0.26286555605956679615),
(-1.1135163644116066184, -3.4270509831248422723, -3.3405490932348205213),
(-1.1135163644116066184, -0.8090169943749474241, 4.7169310137059937438),
(-1.1135163644116066184, -0.8090169943749474241, -0.26286555605956679615),
(-1.1135163644116066184, 0.8090169943749474241, 4.7169310137059937438),
(-1.1135163644116066184, 0.8090169943749474241, -0.26286555605956679615),
(-1.1135163644116066184, 3.4270509831248422723, -3.3405490932348205213),
(1.11351636441160673519, -3.4270509831248422723, 3.3405490932348202056),
(1.11351636441160673519, -0.8090169943749474241, -4.7169310137059934362),
(1.11351636441160673519, -0.8090169943749474241, 0.26286555605956679615),
(1.11351636441160673519, 0.8090169943749474241, -4.7169310137059934362),
(1.11351636441160673519, 0.8090169943749474241, 0.26286555605956679615),
(1.11351636441160673519, 3.4270509831248422723, 3.3405490932348202056),
(-0.85065080835203998877, 0, 1.11351636441160673519),
(0.85065080835203993218, 0, -1.1135163644116066184),
(-0.6881909602355867691, -0.5, -1.1135163644116066184),
(-0.6881909602355867691, 0.5, -1.1135163644116066184),
(-0.6881909602355867691, -4.7360679774997896964, -1.1135163644116066184),
(-0.6881909602355867691, -2.1180339887498948482, -1.1135163644116066184),
(-0.6881909602355867691, 2.1180339887498948482, -1.1135163644116066184),
(-0.6881909602355867691, 4.7360679774997896964, -1.1135163644116066184),
(0.68819096023558676910, -0.5, 1.11351636441160673519),
(0.68819096023558676910, 0.5, 1.11351636441160673519),
(0.68819096023558676910, -4.7360679774997896964, 1.11351636441160673519),
(0.68819096023558676910, -2.1180339887498948482, 1.11351636441160673519),
(0.68819096023558676910, 2.1180339887498948482, 1.11351636441160673519),
(0.68819096023558676910, 4.7360679774997896964, 1.11351636441160673519),
(-0.42532540417601993887, -1.3090169943749474241, -4.7169310137059934362),
(-0.42532540417601993887, -1.3090169943749474241, 0.26286555605956679615),
(-0.42532540417601993887, 1.3090169943749474241, -4.7169310137059934362),
(-0.42532540417601993887, 1.3090169943749474241, 0.26286555605956679615),
(-0.26286555605956679615, -0.8090169943749474241, 1.11351636441160673519),
(-0.26286555605956679615, 0.8090169943749474241, 1.11351636441160673519),
(0.26286555605956679615, -0.8090169943749474241, -1.1135163644116066184),
(0.26286555605956679615, 0.8090169943749474241, -1.1135163644116066184),
(0.42532540417601996609, -1.3090169943749474241, 4.7169310137059937438),
(0.42532540417601996609, -1.3090169943749474241, -0.26286555605956679615),
(0.42532540417601996609, 1.3090169943749474241, 4.7169310137059937438),
(0.42532540417601996609, 1.3090169943749474241, -0.26286555605956679615)],
[9, 66, 47], [44, 62, 77], [20, 91, 49], [33, 47, 83],
[3, 77, 84], [12, 49, 53], [36, 84, 66], [28, 53, 62],
[73, 83, 91], [15, 84, 46], [25, 64, 43], [16, 58, 72],
[26, 46, 51], [11, 43, 74], [4, 72, 91], [60, 74, 84],
[35, 91, 64], [23, 51, 58], [19, 74, 77], [79, 83, 78],
[6, 56, 40], [76, 77, 81], [21, 78, 75], [8, 40, 58],
[31, 75, 74], [42, 58, 83], [41, 81, 56], [13, 75, 43],
[27, 51, 47], [2, 89, 71], [24, 43, 62], [17, 47, 85],
[14, 71, 56], [65, 85, 75], [22, 56, 51], [34, 62, 89],
[5, 85, 78], [32, 81, 46], [10, 53, 48], [45, 78, 64],
[7, 46, 66], [18, 48, 89], [37, 66, 85], [70, 89, 81],
[29, 64, 53], [88, 74, 1], [38, 67, 48], [42, 83, 72],
[57, 1, 85], [34, 48, 62], [59, 72, 87], [19, 62, 74],
[63, 87, 67], [17, 85, 83], [52, 75, 1], [39, 87, 49],
[22, 51, 40], [55, 1, 66], [29, 49, 64], [30, 40, 69],
[13, 64, 75], [82, 69, 87], [7, 66, 51], [90, 85, 1],
[59, 69, 72], [70, 81, 71], [88, 1, 84], [73, 72, 83],
[54, 71, 68], [5, 83, 85], [50, 68, 69], [3, 84, 81],
[57, 66, 1], [30, 68, 40], [28, 62, 48], [52, 1, 74],
[23, 40, 51], [38, 48, 86], [9, 51, 66], [80, 86, 68],
[11, 74, 62], [55, 84, 1], [54, 86, 71], [35, 64, 49],
[90, 1, 75], [41, 71, 81], [39, 49, 67], [15, 81, 84],
[61, 67, 86], [21, 75, 64], [24, 53, 43], [50, 69, 0],
[37, 85, 47], [31, 43, 75], [61, 0, 67], [27, 47, 58],
[10, 67, 53], [8, 58, 69], [90, 75, 85], [45, 91, 78],
[80, 68, 0], [36, 66, 46], [65, 78, 85], [63, 0, 87],
[32, 46, 56], [20, 87, 91], [14, 56, 68], [57, 85, 66],
[33, 58, 47], [61, 86, 0], [60, 84, 77], [37, 47, 66],
[82, 0, 69], [44, 77, 89], [16, 69, 58], [18, 89, 86],
[55, 66, 84], [26, 56, 46], [63, 67, 0], [31, 74, 43],
[36, 46, 84], [50, 0, 68], [25, 43, 53], [6, 68, 56],
[12, 53, 67], [88, 84, 74], [76, 89, 77], [82, 87, 0],
[65, 75, 78], [60, 77, 74], [80, 0, 86], [79, 78, 91],
[2, 86, 89], [4, 91, 87], [52, 74, 75], [21, 64, 78],
[18, 86, 48], [23, 58, 40], [5, 78, 83], [28, 48, 53],
[6, 40, 68], [25, 53, 64], [54, 68, 86], [33, 83, 58],
[17, 83, 47], [12, 67, 49], [41, 56, 71], [9, 47, 51],
[35, 49, 91], [2, 71, 86], [79, 91, 83], [38, 86, 67],
[26, 51, 56], [7, 51, 46], [4, 87, 72], [34, 89, 48],
[15, 46, 81], [42, 72, 58], [10, 48, 67], [27, 58, 51],
[39, 67, 87], [76, 81, 89], [3, 81, 77], [8, 69, 40],
[29, 53, 49], [19, 77, 62], [22, 40, 56], [20, 49, 87],
[32, 56, 81], [59, 87, 69], [24, 62, 53], [11, 62, 43],
[14, 68, 71], [73, 91, 72], [13, 43, 64], [70, 71, 89],
[16, 72, 69], [44, 89, 62], [30, 69, 68], [45, 64, 91]]
# Actual volume is : 51.405764746872634
assert Abs(polytope_integrate(echidnahedron, 1) - 51.4057647468726) < 1e-12
assert Abs(polytope_integrate(echidnahedron, expr) - 253.569603474519) <\
1e-12
# Tests for many polynomials with maximum degree given(2D case).
assert polytope_integrate(cube2, [x**2, y*z], max_degree=2) == \
{y * z: 3125 / S(4), x ** 2: 3125 / S(3)}
assert polytope_integrate(cube2, max_degree=2) == \
{1: 125, x: 625 / S(2), x * z: 3125 / S(4), y: 625 / S(2),
y * z: 3125 / S(4), z ** 2: 3125 / S(3), y ** 2: 3125 / S(3),
z: 625 / S(2), x * y: 3125 / S(4), x ** 2: 3125 / S(3)}
def test_point_sort():
assert point_sort([Point(0, 0), Point(1, 0), Point(1, 1)]) == \
[Point2D(1, 1), Point2D(1, 0), Point2D(0, 0)]
fig6 = Polygon((0, 0), (1, 0), (1, 1))
assert polytope_integrate(fig6, x*y) == Rational(-1, 8)
assert polytope_integrate(fig6, x*y, clockwise = True) == Rational(1, 8)
def test_polytopes_intersecting_sides():
fig5 = Polygon(Point(-4.165, -0.832), Point(-3.668, 1.568),
Point(-3.266, 1.279), Point(-1.090, -2.080),
Point(3.313, -0.683), Point(3.033, -4.845),
Point(-4.395, 4.840), Point(-1.007, -3.328))
assert polytope_integrate(fig5, x**2 + x*y + y**2) ==\
S(1633405224899363)/(24*10**12)
fig6 = Polygon(Point(-3.018, -4.473), Point(-0.103, 2.378),
Point(-1.605, -2.308), Point(4.516, -0.771),
Point(4.203, 0.478))
assert polytope_integrate(fig6, x**2 + x*y + y**2) ==\
S(88161333955921)/(3*10**12)
def test_max_degree():
polygon = Polygon((0, 0), (0, 1), (1, 1), (1, 0))
polys = [1, x, y, x*y, x**2*y, x*y**2]
assert polytope_integrate(polygon, polys, max_degree=3) == \
{1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4), x**2*y: Rational(1, 6), x*y**2: Rational(1, 6)}
assert polytope_integrate(polygon, polys, max_degree=2) == \
{1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4)}
assert polytope_integrate(polygon, polys, max_degree=1) == \
{1: 1, x: S.Half, y: S.Half}
def test_main_integrate3d():
cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
[3, 1, 0, 2], [0, 4, 6, 2]]
vertices = cube[0]
faces = cube[1:]
hp_params = hyperplane_parameters(faces, vertices)
assert main_integrate3d(1, faces, vertices, hp_params) == -125
assert main_integrate3d(1, faces, vertices, hp_params, max_degree=1) == \
{1: -125, y: Rational(-625, 2), z: Rational(-625, 2), x: Rational(-625, 2)}
def test_main_integrate():
triangle = Polygon((0, 3), (5, 3), (1, 1))
facets = triangle.sides
hp_params = hyperplane_parameters(triangle)
assert main_integrate(x**2 + y**2, facets, hp_params) == Rational(325, 6)
assert main_integrate(x**2 + y**2, facets, hp_params, max_degree=1) == \
{0: 0, 1: 5, y: Rational(35, 3), x: 10}
def test_polygon_integrate():
cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
[3, 1, 0, 2], [0, 4, 6, 2]]
facet = cube[1]
facets = cube[1:]
vertices = cube[0]
assert polygon_integrate(facet, [(0, 1, 0), 5], 0, facets, vertices, 1, 0) == -25
def test_distance_to_side():
point = (0, 0, 0)
assert distance_to_side(point, [(0, 0, 1), (0, 1, 0)], (1, 0, 0)) == -sqrt(2)/2
def test_lineseg_integrate():
polygon = [(0, 5, 0), (5, 5, 0), (5, 5, 5), (0, 5, 5)]
line_seg = [(0, 5, 0), (5, 5, 0)]
assert lineseg_integrate(polygon, 0, line_seg, 1, 0) == 5
assert lineseg_integrate(polygon, 0, line_seg, 0, 0) == 0
def test_integration_reduction():
triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
facets = triangle.sides
a, b = hyperplane_parameters(triangle)[0]
assert integration_reduction(facets, 0, a, b, 1, (x, y), 0) == 5
assert integration_reduction(facets, 0, a, b, 0, (x, y), 0) == 0
def test_integration_reduction_dynamic():
triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
facets = triangle.sides
a, b = hyperplane_parameters(triangle)[0]
x0 = facets[0].points[0]
monomial_values = [[0, 0, 0, 0], [1, 0, 0, 5],\
[y, 0, 1, 15], [x, 1, 0, None]]
assert integration_reduction_dynamic(facets, 0, a, b, x, 1, (x, y), 1,\
0, 1, x0, monomial_values, 3) == Rational(25, 2)
assert integration_reduction_dynamic(facets, 0, a, b, 0, 1, (x, y), 1,\
0, 1, x0, monomial_values, 3) == 0
def test_is_vertex():
assert is_vertex(2) is False
assert is_vertex((2, 3)) is True
assert is_vertex(Point(2, 3)) is True
assert is_vertex((2, 3, 4)) is True
assert is_vertex((2, 3, 4, 5)) is False
def test_issue_19234():
polygon = Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0))
polys = [ 1, x, y, x*y, x**2*y, x*y**2]
assert polytope_integrate(polygon, polys) == \
{1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4), x**2*y: Rational(1, 6), x*y**2: Rational(1, 6)}
polys = [ 1, x, y, x*y, 3 + x**2*y, x + x*y**2]
assert polytope_integrate(polygon, polys) == \
{1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4), x**2*y + 3: Rational(19, 6), x*y**2 + x: Rational(2, 3)}
|
8f0682bd62685bfe7f0939030c125e443b4b0941dd633cb3b3e7fb1b22436957 | import math
from sympy.concrete.summations import (Sum, summation)
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import (Derivative, Function, Lambda, diff)
from sympy.core import EulerGamma
from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
from sympy.core.relational import (Eq, Ne)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.functions.elementary.complexes import (Abs, im, polar_lift, re, sign)
from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log)
from sympy.functions.elementary.hyperbolic import (acosh, asinh, cosh, coth, csch, sinh, tanh, sech)
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, sinc, tan, sec)
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
from sympy.functions.special.error_functions import (Ci, Ei, Si, erf, erfc, erfi, fresnelc, li)
from sympy.functions.special.gamma_functions import (gamma, polygamma)
from sympy.functions.special.hyper import (hyper, meijerg)
from sympy.functions.special.singularity_functions import SingularityFunction
from sympy.functions.special.zeta_functions import lerchphi
from sympy.integrals.integrals import integrate
from sympy.logic.boolalg import And
from sympy.matrices.dense import Matrix
from sympy.polys.polytools import (Poly, factor)
from sympy.printing.str import sstr
from sympy.series.order import O
from sympy.sets.sets import Interval
from sympy.simplify.gammasimp import gammasimp
from sympy.simplify.simplify import simplify
from sympy.simplify.trigsimp import trigsimp
from sympy.tensor.indexed import (Idx, IndexedBase)
from sympy.core.expr import unchanged
from sympy.functions.elementary.integers import floor
from sympy.integrals.integrals import Integral
from sympy.integrals.risch import NonElementaryIntegral
from sympy.physics import units
from sympy.testing.pytest import (raises, slow, skip, ON_CI,
warns_deprecated_sympy, warns)
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.core.random import verify_numerically
x, y, z, a, b, c, d, e, s, t, x_1, x_2 = symbols('x y z a b c d e s t x_1 x_2')
n = Symbol('n', integer=True)
f = Function('f')
def NS(e, n=15, **options):
return sstr(sympify(e).evalf(n, **options), full_prec=True)
def test_poly_deprecated():
p = Poly(2*x, x)
assert p.integrate(x) == Poly(x**2, x, domain='QQ')
# The stacklevel is based on Integral(Poly)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
integrate(p, x)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
Integral(p, (x,))
@slow
def test_principal_value():
g = 1 / x
assert Integral(g, (x, -oo, oo)).principal_value() == 0
assert Integral(g, (y, -oo, oo)).principal_value() == oo * sign(1 / x)
raises(ValueError, lambda: Integral(g, (x)).principal_value())
raises(ValueError, lambda: Integral(g).principal_value())
l = 1 / ((x ** 3) - 1)
assert Integral(l, (x, -oo, oo)).principal_value().together() == -sqrt(3)*pi/3
raises(ValueError, lambda: Integral(l, (x, -oo, 1)).principal_value())
d = 1 / (x ** 2 - 1)
assert Integral(d, (x, -oo, oo)).principal_value() == 0
assert Integral(d, (x, -2, 2)).principal_value() == -log(3)
v = x / (x ** 2 - 1)
assert Integral(v, (x, -oo, oo)).principal_value() == 0
assert Integral(v, (x, -2, 2)).principal_value() == 0
s = x ** 2 / (x ** 2 - 1)
assert Integral(s, (x, -oo, oo)).principal_value() is oo
assert Integral(s, (x, -2, 2)).principal_value() == -log(3) + 4
f = 1 / ((x ** 2 - 1) * (1 + x ** 2))
assert Integral(f, (x, -oo, oo)).principal_value() == -pi / 2
assert Integral(f, (x, -2, 2)).principal_value() == -atan(2) - log(3) / 2
def diff_test(i):
"""Return the set of symbols, s, which were used in testing that
i.diff(s) agrees with i.doit().diff(s). If there is an error then
the assertion will fail, causing the test to fail."""
syms = i.free_symbols
for s in syms:
assert (i.diff(s).doit() - i.doit().diff(s)).expand() == 0
return syms
def test_improper_integral():
assert integrate(log(x), (x, 0, 1)) == -1
assert integrate(x**(-2), (x, 1, oo)) == 1
assert integrate(1/(1 + exp(x)), (x, 0, oo)) == log(2)
def test_constructor():
# this is shared by Sum, so testing Integral's constructor
# is equivalent to testing Sum's
s1 = Integral(n, n)
assert s1.limits == (Tuple(n),)
s2 = Integral(n, (n,))
assert s2.limits == (Tuple(n),)
s3 = Integral(Sum(x, (x, 1, y)))
assert s3.limits == (Tuple(y),)
s4 = Integral(n, Tuple(n,))
assert s4.limits == (Tuple(n),)
s5 = Integral(n, (n, Interval(1, 2)))
assert s5.limits == (Tuple(n, 1, 2),)
# Testing constructor with inequalities:
s6 = Integral(n, n > 10)
assert s6.limits == (Tuple(n, 10, oo),)
s7 = Integral(n, (n > 2) & (n < 5))
assert s7.limits == (Tuple(n, 2, 5),)
def test_basics():
assert Integral(0, x) != 0
assert Integral(x, (x, 1, 1)) != 0
assert Integral(oo, x) != oo
assert Integral(S.NaN, x) is S.NaN
assert diff(Integral(y, y), x) == 0
assert diff(Integral(x, (x, 0, 1)), x) == 0
assert diff(Integral(x, x), x) == x
assert diff(Integral(t, (t, 0, x)), x) == x
e = (t + 1)**2
assert diff(integrate(e, (t, 0, x)), x) == \
diff(Integral(e, (t, 0, x)), x).doit().expand() == \
((1 + x)**2).expand()
assert diff(integrate(e, (t, 0, x)), t) == \
diff(Integral(e, (t, 0, x)), t) == 0
assert diff(integrate(e, (t, 0, x)), a) == \
diff(Integral(e, (t, 0, x)), a) == 0
assert diff(integrate(e, t), a) == diff(Integral(e, t), a) == 0
assert integrate(e, (t, a, x)).diff(x) == \
Integral(e, (t, a, x)).diff(x).doit().expand()
assert Integral(e, (t, a, x)).diff(x).doit() == ((1 + x)**2)
assert integrate(e, (t, x, a)).diff(x).doit() == (-(1 + x)**2).expand()
assert integrate(t**2, (t, x, 2*x)).diff(x) == 7*x**2
assert Integral(x, x).atoms() == {x}
assert Integral(f(x), (x, 0, 1)).atoms() == {S.Zero, S.One, x}
assert diff_test(Integral(x, (x, 3*y))) == {y}
assert diff_test(Integral(x, (a, 3*y))) == {x, y}
assert integrate(x, (x, oo, oo)) == 0 #issue 8171
assert integrate(x, (x, -oo, -oo)) == 0
# sum integral of terms
assert integrate(y + x + exp(x), x) == x*y + x**2/2 + exp(x)
assert Integral(x).is_commutative
n = Symbol('n', commutative=False)
assert Integral(n + x, x).is_commutative is False
def test_diff_wrt():
class Test(Expr):
_diff_wrt = True
is_commutative = True
t = Test()
assert integrate(t + 1, t) == t**2/2 + t
assert integrate(t + 1, (t, 0, 1)) == Rational(3, 2)
raises(ValueError, lambda: integrate(x + 1, x + 1))
raises(ValueError, lambda: integrate(x + 1, (x + 1, 0, 1)))
def test_basics_multiple():
assert diff_test(Integral(x, (x, 3*x, 5*y), (y, x, 2*x))) == {x}
assert diff_test(Integral(x, (x, 5*y), (y, x, 2*x))) == {x}
assert diff_test(Integral(x, (x, 5*y), (y, y, 2*x))) == {x, y}
assert diff_test(Integral(y, y, x)) == {x, y}
assert diff_test(Integral(y*x, x, y)) == {x, y}
assert diff_test(Integral(x + y, y, (y, 1, x))) == {x}
assert diff_test(Integral(x + y, (x, x, y), (y, y, x))) == {x, y}
def test_conjugate_transpose():
A, B = symbols("A B", commutative=False)
x = Symbol("x", complex=True)
p = Integral(A*B, (x,))
assert p.adjoint().doit() == p.doit().adjoint()
assert p.conjugate().doit() == p.doit().conjugate()
assert p.transpose().doit() == p.doit().transpose()
x = Symbol("x", real=True)
p = Integral(A*B, (x,))
assert p.adjoint().doit() == p.doit().adjoint()
assert p.conjugate().doit() == p.doit().conjugate()
assert p.transpose().doit() == p.doit().transpose()
def test_integration():
assert integrate(0, (t, 0, x)) == 0
assert integrate(3, (t, 0, x)) == 3*x
assert integrate(t, (t, 0, x)) == x**2/2
assert integrate(3*t, (t, 0, x)) == 3*x**2/2
assert integrate(3*t**2, (t, 0, x)) == x**3
assert integrate(1/t, (t, 1, x)) == log(x)
assert integrate(-1/t**2, (t, 1, x)) == 1/x - 1
assert integrate(t**2 + 5*t - 8, (t, 0, x)) == x**3/3 + 5*x**2/2 - 8*x
assert integrate(x**2, x) == x**3/3
assert integrate((3*t*x)**5, x) == (3*t)**5 * x**6 / 6
b = Symbol("b")
c = Symbol("c")
assert integrate(a*t, (t, 0, x)) == a*x**2/2
assert integrate(a*t**4, (t, 0, x)) == a*x**5/5
assert integrate(a*t**2 + b*t + c, (t, 0, x)) == a*x**3/3 + b*x**2/2 + c*x
def test_multiple_integration():
assert integrate((x**2)*(y**2), (x, 0, 1), (y, -1, 2)) == Rational(1)
assert integrate((y**2)*(x**2), x, y) == Rational(1, 9)*(x**3)*(y**3)
assert integrate(1/(x + 3)/(1 + x)**3, x) == \
log(3 + x)*Rational(-1, 8) + log(1 + x)*Rational(1, 8) + x/(4 + 8*x + 4*x**2)
assert integrate(sin(x*y)*y, (x, 0, 1), (y, 0, 1)) == -sin(1) + 1
def test_issue_3532():
assert integrate(exp(-x), (x, 0, oo)) == 1
def test_issue_3560():
assert integrate(sqrt(x)**3, x) == 2*sqrt(x)**5/5
assert integrate(sqrt(x), x) == 2*sqrt(x)**3/3
assert integrate(1/sqrt(x)**3, x) == -2/sqrt(x)
def test_issue_18038():
raises(AttributeError, lambda: integrate((x, x)))
def test_integrate_poly():
p = Poly(x + x**2*y + y**3, x, y)
# The stacklevel is based on Integral(Poly)
with warns_deprecated_sympy():
qx = Integral(p, x)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
qx = integrate(p, x)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
qy = integrate(p, y)
assert isinstance(qx, Poly) is True
assert isinstance(qy, Poly) is True
assert qx.gens == (x, y)
assert qy.gens == (x, y)
assert qx.as_expr() == x**2/2 + x**3*y/3 + x*y**3
assert qy.as_expr() == x*y + x**2*y**2/2 + y**4/4
def test_integrate_poly_definite():
p = Poly(x + x**2*y + y**3, x, y)
with warns_deprecated_sympy():
Qx = Integral(p, (x, 0, 1))
with warns(SymPyDeprecationWarning, test_stacklevel=False):
Qx = integrate(p, (x, 0, 1))
with warns(SymPyDeprecationWarning, test_stacklevel=False):
Qy = integrate(p, (y, 0, pi))
assert isinstance(Qx, Poly) is True
assert isinstance(Qy, Poly) is True
assert Qx.gens == (y,)
assert Qy.gens == (x,)
assert Qx.as_expr() == S.Half + y/3 + y**3
assert Qy.as_expr() == pi**4/4 + pi*x + pi**2*x**2/2
def test_integrate_omit_var():
y = Symbol('y')
assert integrate(x) == x**2/2
raises(ValueError, lambda: integrate(2))
raises(ValueError, lambda: integrate(x*y))
def test_integrate_poly_accurately():
y = Symbol('y')
assert integrate(x*sin(y), x) == x**2*sin(y)/2
# when passed to risch_norman, this will be a CPU hog, so this really
# checks, that integrated function is recognized as polynomial
assert integrate(x**1000*sin(y), x) == x**1001*sin(y)/1001
def test_issue_3635():
y = Symbol('y')
assert integrate(x**2, y) == x**2*y
assert integrate(x**2, (y, -1, 1)) == 2*x**2
# works in SymPy and py.test but hangs in `setup.py test`
def test_integrate_linearterm_pow():
# check integrate((a*x+b)^c, x) -- issue 3499
y = Symbol('y', positive=True)
# TODO: Remove conds='none' below, let the assumption take care of it.
assert integrate(x**y, x, conds='none') == x**(y + 1)/(y + 1)
assert integrate((exp(y)*x + 1/y)**(1 + sin(y)), x, conds='none') == \
exp(-y)*(exp(y)*x + 1/y)**(2 + sin(y)) / (2 + sin(y))
def test_issue_3618():
assert integrate(pi*sqrt(x), x) == 2*pi*sqrt(x)**3/3
assert integrate(pi*sqrt(x) + E*sqrt(x)**3, x) == \
2*pi*sqrt(x)**3/3 + 2*E *sqrt(x)**5/5
def test_issue_3623():
assert integrate(cos((n + 1)*x), x) == Piecewise(
(sin(x*(n + 1))/(n + 1), Ne(n + 1, 0)), (x, True))
assert integrate(cos((n - 1)*x), x) == Piecewise(
(sin(x*(n - 1))/(n - 1), Ne(n - 1, 0)), (x, True))
assert integrate(cos((n + 1)*x) + cos((n - 1)*x), x) == \
Piecewise((sin(x*(n - 1))/(n - 1), Ne(n - 1, 0)), (x, True)) + \
Piecewise((sin(x*(n + 1))/(n + 1), Ne(n + 1, 0)), (x, True))
def test_issue_3664():
n = Symbol('n', integer=True, nonzero=True)
assert integrate(-1./2 * x * sin(n * pi * x/2), [x, -2, 0]) == \
2.0*cos(pi*n)/(pi*n)
assert integrate(x * sin(n * pi * x/2) * Rational(-1, 2), [x, -2, 0]) == \
2*cos(pi*n)/(pi*n)
def test_issue_3679():
# definite integration of rational functions gives wrong answers
assert NS(Integral(1/(x**2 - 8*x + 17), (x, 2, 4))) == '1.10714871779409'
def test_issue_3686(): # remove this when fresnel integrals are implemented
from sympy.core.function import expand_func
from sympy.functions.special.error_functions import fresnels
assert expand_func(integrate(sin(x**2), x)) == \
sqrt(2)*sqrt(pi)*fresnels(sqrt(2)*x/sqrt(pi))/2
def test_integrate_units():
m = units.m
s = units.s
assert integrate(x * m/s, (x, 1*s, 5*s)) == 12*m*s
def test_transcendental_functions():
assert integrate(LambertW(2*x), x) == \
-x + x*LambertW(2*x) + x/LambertW(2*x)
def test_log_polylog():
assert integrate(log(1 - x)/x, (x, 0, 1)) == -pi**2/6
assert integrate(log(x)*(1 - x)**(-1), (x, 0, 1)) == -pi**2/6
def test_issue_3740():
f = 4*log(x) - 2*log(x)**2
fid = diff(integrate(f, x), x)
assert abs(f.subs(x, 42).evalf() - fid.subs(x, 42).evalf()) < 1e-10
def test_issue_3788():
assert integrate(1/(1 + x**2), x) == atan(x)
def test_issue_3952():
f = sin(x)
assert integrate(f, x) == -cos(x)
raises(ValueError, lambda: integrate(f, 2*x))
def test_issue_4516():
assert integrate(2**x - 2*x, x) == 2**x/log(2) - x**2
def test_issue_7450():
ans = integrate(exp(-(1 + I)*x), (x, 0, oo))
assert re(ans) == S.Half and im(ans) == Rational(-1, 2)
def test_issue_8623():
assert integrate((1 + cos(2*x)) / (3 - 2*cos(2*x)), (x, 0, pi)) == -pi/2 + sqrt(5)*pi/2
assert integrate((1 + cos(2*x))/(3 - 2*cos(2*x))) == -x/2 + sqrt(5)*(atan(sqrt(5)*tan(x)) + \
pi*floor((x - pi/2)/pi))/2
def test_issue_9569():
assert integrate(1 / (2 - cos(x)), (x, 0, pi)) == pi/sqrt(3)
assert integrate(1/(2 - cos(x))) == 2*sqrt(3)*(atan(sqrt(3)*tan(x/2)) + pi*floor((x/2 - pi/2)/pi))/3
def test_issue_13733():
s = Symbol('s', positive=True)
pz = exp(-(z - y)**2/(2*s*s))/sqrt(2*pi*s*s)
pzgx = integrate(pz, (z, x, oo))
assert integrate(pzgx, (x, 0, oo)) == sqrt(2)*s*exp(-y**2/(2*s**2))/(2*sqrt(pi)) + \
y*erf(sqrt(2)*y/(2*s))/2 + y/2
def test_issue_13749():
assert integrate(1 / (2 + cos(x)), (x, 0, pi)) == pi/sqrt(3)
assert integrate(1/(2 + cos(x))) == 2*sqrt(3)*(atan(sqrt(3)*tan(x/2)/3) + pi*floor((x/2 - pi/2)/pi))/3
def test_issue_18133():
assert integrate(exp(x)/(1 + x)**2, x) == NonElementaryIntegral(exp(x)/(x + 1)**2, x)
def test_issue_21741():
a = Float('3999999.9999999995', precision=53)
b = Float('2.5000000000000004e-7', precision=53)
r = Piecewise((b*I*exp(-a*I*pi*t*y)*exp(-a*I*pi*x*z)/(pi*x),
Ne(1.0*pi*x*exp(a*I*pi*t*y), 0)),
(z*exp(-a*I*pi*t*y), True))
fun = E**((-2*I*pi*(z*x+t*y))/(500*10**(-9)))
assert integrate(fun, z) == r
def test_matrices():
M = Matrix(2, 2, lambda i, j: (i + j + 1)*sin((i + j + 1)*x))
assert integrate(M, x) == Matrix([
[-cos(x), -cos(2*x)],
[-cos(2*x), -cos(3*x)],
])
def test_integrate_functions():
# issue 4111
assert integrate(f(x), x) == Integral(f(x), x)
assert integrate(f(x), (x, 0, 1)) == Integral(f(x), (x, 0, 1))
assert integrate(f(x)*diff(f(x), x), x) == f(x)**2/2
assert integrate(diff(f(x), x) / f(x), x) == log(f(x))
def test_integrate_derivatives():
assert integrate(Derivative(f(x), x), x) == f(x)
assert integrate(Derivative(f(y), y), x) == x*Derivative(f(y), y)
assert integrate(Derivative(f(x), x)**2, x) == \
Integral(Derivative(f(x), x)**2, x)
def test_transform():
a = Integral(x**2 + 1, (x, -1, 2))
fx = x
fy = 3*y + 1
assert a.doit() == a.transform(fx, fy).doit()
assert a.transform(fx, fy).transform(fy, fx) == a
fx = 3*x + 1
fy = y
assert a.transform(fx, fy).transform(fy, fx) == a
a = Integral(sin(1/x), (x, 0, 1))
assert a.transform(x, 1/y) == Integral(sin(y)/y**2, (y, 1, oo))
assert a.transform(x, 1/y).transform(y, 1/x) == a
a = Integral(exp(-x**2), (x, -oo, oo))
assert a.transform(x, 2*y) == Integral(2*exp(-4*y**2), (y, -oo, oo))
# < 3 arg limit handled properly
assert Integral(x, x).transform(x, a*y).doit() == \
Integral(y*a**2, y).doit()
_3 = S(3)
assert Integral(x, (x, 0, -_3)).transform(x, 1/y).doit() == \
Integral(-1/x**3, (x, -oo, -1/_3)).doit()
assert Integral(x, (x, 0, _3)).transform(x, 1/y) == \
Integral(y**(-3), (y, 1/_3, oo))
# issue 8400
i = Integral(x + y, (x, 1, 2), (y, 1, 2))
assert i.transform(x, (x + 2*y, x)).doit() == \
i.transform(x, (x + 2*z, x)).doit() == 3
i = Integral(x, (x, a, b))
assert i.transform(x, 2*s) == Integral(4*s, (s, a/2, b/2))
raises(ValueError, lambda: i.transform(x, 1))
raises(ValueError, lambda: i.transform(x, s*t))
raises(ValueError, lambda: i.transform(x, -s))
raises(ValueError, lambda: i.transform(x, (s, t)))
raises(ValueError, lambda: i.transform(2*x, 2*s))
i = Integral(x**2, (x, 1, 2))
raises(ValueError, lambda: i.transform(x**2, s))
am = Symbol('a', negative=True)
bp = Symbol('b', positive=True)
i = Integral(x, (x, bp, am))
i.transform(x, 2*s)
assert i.transform(x, 2*s) == Integral(-4*s, (s, am/2, bp/2))
i = Integral(x, (x, a))
assert i.transform(x, 2*s) == Integral(4*s, (s, a/2))
def test_issue_4052():
f = S.Half*asin(x) + x*sqrt(1 - x**2)/2
assert integrate(cos(asin(x)), x) == f
assert integrate(sin(acos(x)), x) == f
@slow
def test_evalf_integrals():
assert NS(Integral(x, (x, 2, 5)), 15) == '10.5000000000000'
gauss = Integral(exp(-x**2), (x, -oo, oo))
assert NS(gauss, 15) == '1.77245385090552'
assert NS(gauss**2 - pi + E*Rational(
1, 10**20), 15) in ('2.71828182845904e-20', '2.71828182845905e-20')
# A monster of an integral from http://mathworld.wolfram.com/DefiniteIntegral.html
t = Symbol('t')
a = 8*sqrt(3)/(1 + 3*t**2)
b = 16*sqrt(2)*(3*t + 1)*sqrt(4*t**2 + t + 1)**3
c = (3*t**2 + 1)*(11*t**2 + 2*t + 3)**2
d = sqrt(2)*(249*t**2 + 54*t + 65)/(11*t**2 + 2*t + 3)**2
f = a - b/c - d
assert NS(Integral(f, (t, 0, 1)), 50) == \
NS((3*sqrt(2) - 49*pi + 162*atan(sqrt(2)))/12, 50)
# http://mathworld.wolfram.com/VardisIntegral.html
assert NS(Integral(log(log(1/x))/(1 + x + x**2), (x, 0, 1)), 15) == \
NS('pi/sqrt(3) * log(2*pi**(5/6) / gamma(1/6))', 15)
# http://mathworld.wolfram.com/AhmedsIntegral.html
assert NS(Integral(atan(sqrt(x**2 + 2))/(sqrt(x**2 + 2)*(x**2 + 1)), (x,
0, 1)), 15) == NS(5*pi**2/96, 15)
# http://mathworld.wolfram.com/AbelsIntegral.html
assert NS(Integral(x/((exp(pi*x) - exp(
-pi*x))*(x**2 + 1)), (x, 0, oo)), 15) == NS('log(2)/2-1/4', 15)
# Complex part trimming
# http://mathworld.wolfram.com/VardisIntegral.html
assert NS(Integral(log(log(sin(x)/cos(x))), (x, pi/4, pi/2)), 15, chop=True) == \
NS('pi/4*log(4*pi**3/gamma(1/4)**4)', 15)
#
# Endpoints causing trouble (rounding error in integration points -> complex log)
assert NS(
2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 17, chop=True) == NS(2, 17)
assert NS(
2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 20, chop=True) == NS(2, 20)
assert NS(
2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 22, chop=True) == NS(2, 22)
# Needs zero handling
assert NS(pi - 4*Integral(
'sqrt(1-x**2)', (x, 0, 1)), 15, maxn=30, chop=True) in ('0.0', '0')
# Oscillatory quadrature
a = Integral(sin(x)/x**2, (x, 1, oo)).evalf(maxn=15)
assert 0.49 < a < 0.51
assert NS(
Integral(sin(x)/x**2, (x, 1, oo)), quad='osc') == '0.504067061906928'
assert NS(Integral(
cos(pi*x + 1)/x, (x, -oo, -1)), quad='osc') == '0.276374705640365'
# indefinite integrals aren't evaluated
assert NS(Integral(x, x)) == 'Integral(x, x)'
assert NS(Integral(x, (x, y))) == 'Integral(x, (x, y))'
def test_evalf_issue_939():
# https://github.com/sympy/sympy/issues/4038
# The output form of an integral may differ by a step function between
# revisions, making this test a bit useless. This can't be said about
# other two tests. For now, all values of this evaluation are used here,
# but in future this should be reconsidered.
assert NS(integrate(1/(x**5 + 1), x).subs(x, 4), chop=True) in \
['-0.000976138910649103', '0.965906660135753', '1.93278945918216']
assert NS(Integral(1/(x**5 + 1), (x, 2, 4))) == '0.0144361088886740'
assert NS(
integrate(1/(x**5 + 1), (x, 2, 4)), chop=True) == '0.0144361088886740'
def test_double_previously_failing_integrals():
# Double integrals not implemented <- Sure it is!
res = integrate(sqrt(x) + x*y, (x, 1, 2), (y, -1, 1))
# Old numerical test
assert NS(res, 15) == '2.43790283299492'
# Symbolic test
assert res == Rational(-4, 3) + 8*sqrt(2)/3
# double integral + zero detection
assert integrate(sin(x + x*y), (x, -1, 1), (y, -1, 1)) is S.Zero
def test_integrate_SingularityFunction():
in_1 = SingularityFunction(x, a, 3) + SingularityFunction(x, 5, -1)
out_1 = SingularityFunction(x, a, 4)/4 + SingularityFunction(x, 5, 0)
assert integrate(in_1, x) == out_1
in_2 = 10*SingularityFunction(x, 4, 0) - 5*SingularityFunction(x, -6, -2)
out_2 = 10*SingularityFunction(x, 4, 1) - 5*SingularityFunction(x, -6, -1)
assert integrate(in_2, x) == out_2
in_3 = 2*x**2*y -10*SingularityFunction(x, -4, 7) - 2*SingularityFunction(y, 10, -2)
out_3_1 = 2*x**3*y/3 - 2*x*SingularityFunction(y, 10, -2) - 5*SingularityFunction(x, -4, 8)/4
out_3_2 = x**2*y**2 - 10*y*SingularityFunction(x, -4, 7) - 2*SingularityFunction(y, 10, -1)
assert integrate(in_3, x) == out_3_1
assert integrate(in_3, y) == out_3_2
assert unchanged(Integral, in_3, (x,))
assert Integral(in_3, x) == Integral(in_3, (x,))
assert Integral(in_3, x).doit() == out_3_1
in_4 = 10*SingularityFunction(x, -4, 7) - 2*SingularityFunction(x, 10, -2)
out_4 = 5*SingularityFunction(x, -4, 8)/4 - 2*SingularityFunction(x, 10, -1)
assert integrate(in_4, (x, -oo, x)) == out_4
assert integrate(SingularityFunction(x, 5, -1), x) == SingularityFunction(x, 5, 0)
assert integrate(SingularityFunction(x, 0, -1), (x, -oo, oo)) == 1
assert integrate(5*SingularityFunction(x, 5, -1), (x, -oo, oo)) == 5
assert integrate(SingularityFunction(x, 5, -1) * f(x), (x, -oo, oo)) == f(5)
def test_integrate_DiracDelta():
# This is here to check that deltaintegrate is being called, but also
# to test definite integrals. More tests are in test_deltafunctions.py
assert integrate(DiracDelta(x) * f(x), (x, -oo, oo)) == f(0)
assert integrate(DiracDelta(x)**2, (x, -oo, oo)) == DiracDelta(0)
# issue 4522
assert integrate(integrate((4 - 4*x + x*y - 4*y) * \
DiracDelta(x)*DiracDelta(y - 1), (x, 0, 1)), (y, 0, 1)) == 0
# issue 5729
p = exp(-(x**2 + y**2))/pi
assert integrate(p*DiracDelta(x - 10*y), (x, -oo, oo), (y, -oo, oo)) == \
integrate(p*DiracDelta(x - 10*y), (y, -oo, oo), (x, -oo, oo)) == \
integrate(p*DiracDelta(10*x - y), (x, -oo, oo), (y, -oo, oo)) == \
integrate(p*DiracDelta(10*x - y), (y, -oo, oo), (x, -oo, oo)) == \
1/sqrt(101*pi)
def test_integrate_returns_piecewise():
assert integrate(x**y, x) == Piecewise(
(x**(y + 1)/(y + 1), Ne(y, -1)), (log(x), True))
assert integrate(x**y, y) == Piecewise(
(x**y/log(x), Ne(log(x), 0)), (y, True))
assert integrate(exp(n*x), x) == Piecewise(
(exp(n*x)/n, Ne(n, 0)), (x, True))
assert integrate(x*exp(n*x), x) == Piecewise(
((n*x - 1)*exp(n*x)/n**2, Ne(n**2, 0)), (x**2/2, True))
assert integrate(x**(n*y), x) == Piecewise(
(x**(n*y + 1)/(n*y + 1), Ne(n*y, -1)), (log(x), True))
assert integrate(x**(n*y), y) == Piecewise(
(x**(n*y)/(n*log(x)), Ne(n*log(x), 0)), (y, True))
assert integrate(cos(n*x), x) == Piecewise(
(sin(n*x)/n, Ne(n, 0)), (x, True))
assert integrate(cos(n*x)**2, x) == Piecewise(
((n*x/2 + sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (x, True))
assert integrate(x*cos(n*x), x) == Piecewise(
(x*sin(n*x)/n + cos(n*x)/n**2, Ne(n, 0)), (x**2/2, True))
assert integrate(sin(n*x), x) == Piecewise(
(-cos(n*x)/n, Ne(n, 0)), (0, True))
assert integrate(sin(n*x)**2, x) == Piecewise(
((n*x/2 - sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (0, True))
assert integrate(x*sin(n*x), x) == Piecewise(
(-x*cos(n*x)/n + sin(n*x)/n**2, Ne(n, 0)), (0, True))
assert integrate(exp(x*y), (x, 0, z)) == Piecewise(
(exp(y*z)/y - 1/y, (y > -oo) & (y < oo) & Ne(y, 0)), (z, True))
# https://github.com/sympy/sympy/issues/23707
assert integrate(exp(t)*exp(-t*sqrt(x - y)), t) == Piecewise(
(-exp(t)/(sqrt(x - y)*exp(t*sqrt(x - y)) - exp(t*sqrt(x - y))),
Ne(x, y + 1)), (t, True))
def test_integrate_max_min():
x = symbols('x', real=True)
assert integrate(Min(x, 2), (x, 0, 3)) == 4
assert integrate(Max(x**2, x**3), (x, 0, 2)) == Rational(49, 12)
assert integrate(Min(exp(x), exp(-x))**2, x) == Piecewise( \
(exp(2*x)/2, x <= 0), (1 - exp(-2*x)/2, True))
# issue 7907
c = symbols('c', extended_real=True)
int1 = integrate(Max(c, x)*exp(-x**2), (x, -oo, oo))
int2 = integrate(c*exp(-x**2), (x, -oo, c))
int3 = integrate(x*exp(-x**2), (x, c, oo))
assert int1 == int2 + int3 == sqrt(pi)*c*erf(c)/2 + \
sqrt(pi)*c/2 + exp(-c**2)/2
def test_integrate_Abs_sign():
assert integrate(Abs(x), (x, -2, 1)) == Rational(5, 2)
assert integrate(Abs(x), (x, 0, 1)) == S.Half
assert integrate(Abs(x + 1), (x, 0, 1)) == Rational(3, 2)
assert integrate(Abs(x**2 - 1), (x, -2, 2)) == 4
assert integrate(Abs(x**2 - 3*x), (x, -15, 15)) == 2259
assert integrate(sign(x), (x, -1, 2)) == 1
assert integrate(sign(x)*sin(x), (x, -pi, pi)) == 4
assert integrate(sign(x - 2) * x**2, (x, 0, 3)) == Rational(11, 3)
t, s = symbols('t s', real=True)
assert integrate(Abs(t), t) == Piecewise(
(-t**2/2, t <= 0), (t**2/2, True))
assert integrate(Abs(2*t - 6), t) == Piecewise(
(-t**2 + 6*t, t <= 3), (t**2 - 6*t + 18, True))
assert (integrate(abs(t - s**2), (t, 0, 2)) ==
2*s**2*Min(2, s**2) - 2*s**2 - Min(2, s**2)**2 + 2)
assert integrate(exp(-Abs(t)), t) == Piecewise(
(exp(t), t <= 0), (2 - exp(-t), True))
assert integrate(sign(2*t - 6), t) == Piecewise(
(-t, t < 3), (t - 6, True))
assert integrate(2*t*sign(t**2 - 1), t) == Piecewise(
(t**2, t < -1), (-t**2 + 2, t < 1), (t**2, True))
assert integrate(sign(t), (t, s + 1)) == Piecewise(
(s + 1, s + 1 > 0), (-s - 1, s + 1 < 0), (0, True))
def test_subs1():
e = Integral(exp(x - y), x)
assert e.subs(y, 3) == Integral(exp(x - 3), x)
e = Integral(exp(x - y), (x, 0, 1))
assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 1))
f = Lambda(x, exp(-x**2))
conv = Integral(f(x - y)*f(y), (y, -oo, oo))
assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo))
def test_subs2():
e = Integral(exp(x - y), x, t)
assert e.subs(y, 3) == Integral(exp(x - 3), x, t)
e = Integral(exp(x - y), (x, 0, 1), (t, 0, 1))
assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 1), (t, 0, 1))
f = Lambda(x, exp(-x**2))
conv = Integral(f(x - y)*f(y), (y, -oo, oo), (t, 0, 1))
assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1))
def test_subs3():
e = Integral(exp(x - y), (x, 0, y), (t, y, 1))
assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 3), (t, 3, 1))
f = Lambda(x, exp(-x**2))
conv = Integral(f(x - y)*f(y), (y, -oo, oo), (t, x, 1))
assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1))
def test_subs4():
e = Integral(exp(x), (x, 0, y), (t, y, 1))
assert e.subs(y, 3) == Integral(exp(x), (x, 0, 3), (t, 3, 1))
f = Lambda(x, exp(-x**2))
conv = Integral(f(y)*f(y), (y, -oo, oo), (t, x, 1))
assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1))
def test_subs5():
e = Integral(exp(-x**2), (x, -oo, oo))
assert e.subs(x, 5) == e
e = Integral(exp(-x**2 + y), x)
assert e.subs(y, 5) == Integral(exp(-x**2 + 5), x)
e = Integral(exp(-x**2 + y), (x, x))
assert e.subs(x, 5) == Integral(exp(y - x**2), (x, 5))
assert e.subs(y, 5) == Integral(exp(-x**2 + 5), x)
e = Integral(exp(-x**2 + y), (y, -oo, oo), (x, -oo, oo))
assert e.subs(x, 5) == e
assert e.subs(y, 5) == e
# Test evaluation of antiderivatives
e = Integral(exp(-x**2), (x, x))
assert e.subs(x, 5) == Integral(exp(-x**2), (x, 5))
e = Integral(exp(x), x)
assert (e.subs(x,1) - e.subs(x,0) - Integral(exp(x), (x, 0, 1))
).doit().is_zero
def test_subs6():
a, b = symbols('a b')
e = Integral(x*y, (x, f(x), f(y)))
assert e.subs(x, 1) == Integral(x*y, (x, f(1), f(y)))
assert e.subs(y, 1) == Integral(x, (x, f(x), f(1)))
e = Integral(x*y, (x, f(x), f(y)), (y, f(x), f(y)))
assert e.subs(x, 1) == Integral(x*y, (x, f(1), f(y)), (y, f(1), f(y)))
assert e.subs(y, 1) == Integral(x*y, (x, f(x), f(y)), (y, f(x), f(1)))
e = Integral(x*y, (x, f(x), f(a)), (y, f(x), f(a)))
assert e.subs(a, 1) == Integral(x*y, (x, f(x), f(1)), (y, f(x), f(1)))
def test_subs7():
e = Integral(x, (x, 1, y), (y, 1, 2))
assert e.subs({x: 1, y: 2}) == e
e = Integral(sin(x) + sin(y), (x, sin(x), sin(y)),
(y, 1, 2))
assert e.subs(sin(y), 1) == e
assert e.subs(sin(x), 1) == Integral(sin(x) + sin(y), (x, 1, sin(y)),
(y, 1, 2))
def test_expand():
e = Integral(f(x)+f(x**2), (x, 1, y))
assert e.expand() == Integral(f(x), (x, 1, y)) + Integral(f(x**2), (x, 1, y))
e = Integral(f(x)+f(x**2), (x, 1, oo))
assert e.expand() == e
assert e.expand(force=True) == Integral(f(x), (x, 1, oo)) + \
Integral(f(x**2), (x, 1, oo))
def test_integration_variable():
raises(ValueError, lambda: Integral(exp(-x**2), 3))
raises(ValueError, lambda: Integral(exp(-x**2), (3, -oo, oo)))
def test_expand_integral():
assert Integral(cos(x**2)*(sin(x**2) + 1), (x, 0, 1)).expand() == \
Integral(cos(x**2)*sin(x**2), (x, 0, 1)) + \
Integral(cos(x**2), (x, 0, 1))
assert Integral(cos(x**2)*(sin(x**2) + 1), x).expand() == \
Integral(cos(x**2)*sin(x**2), x) + \
Integral(cos(x**2), x)
def test_as_sum_midpoint1():
e = Integral(sqrt(x**3 + 1), (x, 2, 10))
assert e.as_sum(1, method="midpoint") == 8*sqrt(217)
assert e.as_sum(2, method="midpoint") == 4*sqrt(65) + 12*sqrt(57)
assert e.as_sum(3, method="midpoint") == 8*sqrt(217)/3 + \
8*sqrt(3081)/27 + 8*sqrt(52809)/27
assert e.as_sum(4, method="midpoint") == 2*sqrt(730) + \
4*sqrt(7) + 4*sqrt(86) + 6*sqrt(14)
assert abs(e.as_sum(4, method="midpoint").n() - e.n()) < 0.5
e = Integral(sqrt(x**3 + y**3), (x, 2, 10), (y, 0, 10))
raises(NotImplementedError, lambda: e.as_sum(4))
def test_as_sum_midpoint2():
e = Integral((x + y)**2, (x, 0, 1))
n = Symbol('n', positive=True, integer=True)
assert e.as_sum(1, method="midpoint").expand() == Rational(1, 4) + y + y**2
assert e.as_sum(2, method="midpoint").expand() == Rational(5, 16) + y + y**2
assert e.as_sum(3, method="midpoint").expand() == Rational(35, 108) + y + y**2
assert e.as_sum(4, method="midpoint").expand() == Rational(21, 64) + y + y**2
assert e.as_sum(n, method="midpoint").expand() == \
y**2 + y + Rational(1, 3) - 1/(12*n**2)
def test_as_sum_left():
e = Integral((x + y)**2, (x, 0, 1))
assert e.as_sum(1, method="left").expand() == y**2
assert e.as_sum(2, method="left").expand() == Rational(1, 8) + y/2 + y**2
assert e.as_sum(3, method="left").expand() == Rational(5, 27) + y*Rational(2, 3) + y**2
assert e.as_sum(4, method="left").expand() == Rational(7, 32) + y*Rational(3, 4) + y**2
assert e.as_sum(n, method="left").expand() == \
y**2 + y + Rational(1, 3) - y/n - 1/(2*n) + 1/(6*n**2)
assert e.as_sum(10, method="left", evaluate=False).has(Sum)
def test_as_sum_right():
e = Integral((x + y)**2, (x, 0, 1))
assert e.as_sum(1, method="right").expand() == 1 + 2*y + y**2
assert e.as_sum(2, method="right").expand() == Rational(5, 8) + y*Rational(3, 2) + y**2
assert e.as_sum(3, method="right").expand() == Rational(14, 27) + y*Rational(4, 3) + y**2
assert e.as_sum(4, method="right").expand() == Rational(15, 32) + y*Rational(5, 4) + y**2
assert e.as_sum(n, method="right").expand() == \
y**2 + y + Rational(1, 3) + y/n + 1/(2*n) + 1/(6*n**2)
def test_as_sum_trapezoid():
e = Integral((x + y)**2, (x, 0, 1))
assert e.as_sum(1, method="trapezoid").expand() == y**2 + y + S.Half
assert e.as_sum(2, method="trapezoid").expand() == y**2 + y + Rational(3, 8)
assert e.as_sum(3, method="trapezoid").expand() == y**2 + y + Rational(19, 54)
assert e.as_sum(4, method="trapezoid").expand() == y**2 + y + Rational(11, 32)
assert e.as_sum(n, method="trapezoid").expand() == \
y**2 + y + Rational(1, 3) + 1/(6*n**2)
assert Integral(sign(x), (x, 0, 1)).as_sum(1, 'trapezoid') == S.Half
def test_as_sum_raises():
e = Integral((x + y)**2, (x, 0, 1))
raises(ValueError, lambda: e.as_sum(-1))
raises(ValueError, lambda: e.as_sum(0))
raises(ValueError, lambda: Integral(x).as_sum(3))
raises(ValueError, lambda: e.as_sum(oo))
raises(ValueError, lambda: e.as_sum(3, method='xxxx2'))
def test_nested_doit():
e = Integral(Integral(x, x), x)
f = Integral(x, x, x)
assert e.doit() == f.doit()
def test_issue_4665():
# Allow only upper or lower limit evaluation
e = Integral(x**2, (x, None, 1))
f = Integral(x**2, (x, 1, None))
assert e.doit() == Rational(1, 3)
assert f.doit() == Rational(-1, 3)
assert Integral(x*y, (x, None, y)).subs(y, t) == Integral(x*t, (x, None, t))
assert Integral(x*y, (x, y, None)).subs(y, t) == Integral(x*t, (x, t, None))
assert integrate(x**2, (x, None, 1)) == Rational(1, 3)
assert integrate(x**2, (x, 1, None)) == Rational(-1, 3)
assert integrate("x**2", ("x", "1", None)) == Rational(-1, 3)
def test_integral_reconstruct():
e = Integral(x**2, (x, -1, 1))
assert e == Integral(*e.args)
def test_doit_integrals():
e = Integral(Integral(2*x), (x, 0, 1))
assert e.doit() == Rational(1, 3)
assert e.doit(deep=False) == Rational(1, 3)
f = Function('f')
# doesn't matter if the integral can't be performed
assert Integral(f(x), (x, 1, 1)).doit() == 0
# doesn't matter if the limits can't be evaluated
assert Integral(0, (x, 1, Integral(f(x), x))).doit() == 0
assert Integral(x, (a, 0)).doit() == 0
limits = ((a, 1, exp(x)), (x, 0))
assert Integral(a, *limits).doit() == Rational(1, 4)
assert Integral(a, *list(reversed(limits))).doit() == 0
def test_issue_4884():
assert integrate(sqrt(x)*(1 + x)) == \
Piecewise(
(2*sqrt(x)*(x + 1)**2/5 - 2*sqrt(x)*(x + 1)/15 - 4*sqrt(x)/15,
Abs(x + 1) > 1),
(2*I*sqrt(-x)*(x + 1)**2/5 - 2*I*sqrt(-x)*(x + 1)/15 -
4*I*sqrt(-x)/15, True))
assert integrate(x**x*(1 + log(x))) == x**x
def test_issue_18153():
assert integrate(x**n*log(x),x) == \
Piecewise(
(n*x*x**n*log(x)/(n**2 + 2*n + 1) +
x*x**n*log(x)/(n**2 + 2*n + 1) - x*x**n/(n**2 + 2*n + 1)
, Ne(n, -1)), (log(x)**2/2, True)
)
def test_is_number():
from sympy.abc import x, y, z
assert Integral(x).is_number is False
assert Integral(1, x).is_number is False
assert Integral(1, (x, 1)).is_number is True
assert Integral(1, (x, 1, 2)).is_number is True
assert Integral(1, (x, 1, y)).is_number is False
assert Integral(1, (x, y)).is_number is False
assert Integral(x, y).is_number is False
assert Integral(x, (y, 1, x)).is_number is False
assert Integral(x, (y, 1, 2)).is_number is False
assert Integral(x, (x, 1, 2)).is_number is True
# `foo.is_number` should always be equivalent to `not foo.free_symbols`
# in each of these cases, there are pseudo-free symbols
i = Integral(x, (y, 1, 1))
assert i.is_number is False and i.n() == 0
i = Integral(x, (y, z, z))
assert i.is_number is False and i.n() == 0
i = Integral(1, (y, z, z + 2))
assert i.is_number is False and i.n() == 2.0
assert Integral(x*y, (x, 1, 2), (y, 1, 3)).is_number is True
assert Integral(x*y, (x, 1, 2), (y, 1, z)).is_number is False
assert Integral(x, (x, 1)).is_number is True
assert Integral(x, (x, 1, Integral(y, (y, 1, 2)))).is_number is True
assert Integral(Sum(z, (z, 1, 2)), (x, 1, 2)).is_number is True
# it is possible to get a false negative if the integrand is
# actually an unsimplified zero, but this is true of is_number in general.
assert Integral(sin(x)**2 + cos(x)**2 - 1, x).is_number is False
assert Integral(f(x), (x, 0, 1)).is_number is True
def test_free_symbols():
from sympy.abc import x, y, z
assert Integral(0, x).free_symbols == {x}
assert Integral(x).free_symbols == {x}
assert Integral(x, (x, None, y)).free_symbols == {y}
assert Integral(x, (x, y, None)).free_symbols == {y}
assert Integral(x, (x, 1, y)).free_symbols == {y}
assert Integral(x, (x, y, 1)).free_symbols == {y}
assert Integral(x, (x, x, y)).free_symbols == {x, y}
assert Integral(x, x, y).free_symbols == {x, y}
assert Integral(x, (x, 1, 2)).free_symbols == set()
assert Integral(x, (y, 1, 2)).free_symbols == {x}
# pseudo-free in this case
assert Integral(x, (y, z, z)).free_symbols == {x, z}
assert Integral(x, (y, 1, 2), (y, None, None)
).free_symbols == {x, y}
assert Integral(x, (y, 1, 2), (x, 1, y)
).free_symbols == {y}
assert Integral(2, (y, 1, 2), (y, 1, x), (x, 1, 2)
).free_symbols == set()
assert Integral(2, (y, x, 2), (y, 1, x), (x, 1, 2)
).free_symbols == set()
assert Integral(2, (x, 1, 2), (y, x, 2), (y, 1, 2)
).free_symbols == {x}
assert Integral(f(x), (f(x), 1, y)).free_symbols == {y}
assert Integral(f(x), (f(x), 1, x)).free_symbols == {x}
def test_is_zero():
from sympy.abc import x, m
assert Integral(0, (x, 1, x)).is_zero
assert Integral(1, (x, 1, 1)).is_zero
assert Integral(1, (x, 1, 2), (y, 2)).is_zero is False
assert Integral(x, (m, 0)).is_zero
assert Integral(x + m, (m, 0)).is_zero is None
i = Integral(m, (m, 1, exp(x)), (x, 0))
assert i.is_zero is None
assert Integral(m, (x, 0), (m, 1, exp(x))).is_zero is True
assert Integral(x, (x, oo, oo)).is_zero # issue 8171
assert Integral(x, (x, -oo, -oo)).is_zero
# this is zero but is beyond the scope of what is_zero
# should be doing
assert Integral(sin(x), (x, 0, 2*pi)).is_zero is None
def test_series():
from sympy.abc import x
i = Integral(cos(x), (x, x))
e = i.lseries(x)
assert i.nseries(x, n=8).removeO() == Add(*[next(e) for j in range(4)])
def test_trig_nonelementary_integrals():
x = Symbol('x')
assert integrate((1 + sin(x))/x, x) == log(x) + Si(x)
# next one comes out as log(x) + log(x**2)/2 + Ci(x)
# so not hardcoding this log ugliness
assert integrate((cos(x) + 2)/x, x).has(Ci)
def test_issue_4403():
x = Symbol('x')
y = Symbol('y')
z = Symbol('z', positive=True)
assert integrate(sqrt(x**2 + z**2), x) == \
z**2*asinh(x/z)/2 + x*sqrt(x**2 + z**2)/2
assert integrate(sqrt(x**2 - z**2), x) == \
x*sqrt(x**2 - z**2)/2 - z**2*log(x + sqrt(x**2 - z**2))/2
x = Symbol('x', real=True)
y = Symbol('y', positive=True)
assert integrate(1/(x**2 + y**2)**S('3/2'), x) == \
x/(y**2*sqrt(x**2 + y**2))
# If y is real and nonzero, we get x*Abs(y)/(y**3*sqrt(x**2 + y**2)),
# which results from sqrt(1 + x**2/y**2) = sqrt(x**2 + y**2)/|y|.
def test_issue_4403_2():
assert integrate(sqrt(-x**2 - 4), x) == \
-2*atan(x/sqrt(-4 - x**2)) + x*sqrt(-4 - x**2)/2
def test_issue_4100():
R = Symbol('R', positive=True)
assert integrate(sqrt(R**2 - x**2), (x, 0, R)) == pi*R**2/4
def test_issue_5167():
from sympy.abc import w, x, y, z
f = Function('f')
assert Integral(Integral(f(x), x), x) == Integral(f(x), x, x)
assert Integral(f(x)).args == (f(x), Tuple(x))
assert Integral(Integral(f(x))).args == (f(x), Tuple(x), Tuple(x))
assert Integral(Integral(f(x)), y).args == (f(x), Tuple(x), Tuple(y))
assert Integral(Integral(f(x), z), y).args == (f(x), Tuple(z), Tuple(y))
assert Integral(Integral(Integral(f(x), x), y), z).args == \
(f(x), Tuple(x), Tuple(y), Tuple(z))
assert integrate(Integral(f(x), x), x) == Integral(f(x), x, x)
assert integrate(Integral(f(x), y), x) == y*Integral(f(x), x)
assert integrate(Integral(f(x), x), y) in [Integral(y*f(x), x), y*Integral(f(x), x)]
assert integrate(Integral(2, x), x) == x**2
assert integrate(Integral(2, x), y) == 2*x*y
# don't re-order given limits
assert Integral(1, x, y).args != Integral(1, y, x).args
# do as many as possible
assert Integral(f(x), y, x, y, x).doit() == y**2*Integral(f(x), x, x)/2
assert Integral(f(x), (x, 1, 2), (w, 1, x), (z, 1, y)).doit() == \
y*(x - 1)*Integral(f(x), (x, 1, 2)) - (x - 1)*Integral(f(x), (x, 1, 2))
def test_issue_4890():
z = Symbol('z', positive=True)
assert integrate(exp(-log(x)**2), x) == \
sqrt(pi)*exp(Rational(1, 4))*erf(log(x) - S.Half)/2
assert integrate(exp(log(x)**2), x) == \
sqrt(pi)*exp(Rational(-1, 4))*erfi(log(x)+S.Half)/2
assert integrate(exp(-z*log(x)**2), x) == \
sqrt(pi)*exp(1/(4*z))*erf(sqrt(z)*log(x) - 1/(2*sqrt(z)))/(2*sqrt(z))
def test_issue_4551():
assert not integrate(1/(x*sqrt(1 - x**2)), x).has(Integral)
def test_issue_4376():
n = Symbol('n', integer=True, positive=True)
assert simplify(integrate(n*(x**(1/n) - 1), (x, 0, S.Half)) -
(n**2 - 2**(1/n)*n**2 - n*2**(1/n))/(2**(1 + 1/n) + n*2**(1 + 1/n))) == 0
def test_issue_4517():
assert integrate((sqrt(x) - x**3)/x**Rational(1, 3), x) == \
6*x**Rational(7, 6)/7 - 3*x**Rational(11, 3)/11
def test_issue_4527():
k, m = symbols('k m', integer=True)
assert integrate(sin(k*x)*sin(m*x), (x, 0, pi)).simplify() == \
Piecewise((0, Eq(k, 0) | Eq(m, 0)),
(-pi/2, Eq(k, -m) | (Eq(k, 0) & Eq(m, 0))),
(pi/2, Eq(k, m) | (Eq(k, 0) & Eq(m, 0))),
(0, True))
# Should be possible to further simplify to:
# Piecewise(
# (0, Eq(k, 0) | Eq(m, 0)),
# (-pi/2, Eq(k, -m)),
# (pi/2, Eq(k, m)),
# (0, True))
assert integrate(sin(k*x)*sin(m*x), (x,)) == Piecewise(
(0, And(Eq(k, 0), Eq(m, 0))),
(-x*sin(m*x)**2/2 - x*cos(m*x)**2/2 + sin(m*x)*cos(m*x)/(2*m), Eq(k, -m)),
(x*sin(m*x)**2/2 + x*cos(m*x)**2/2 - sin(m*x)*cos(m*x)/(2*m), Eq(k, m)),
(m*sin(k*x)*cos(m*x)/(k**2 - m**2) -
k*sin(m*x)*cos(k*x)/(k**2 - m**2), True))
def test_issue_4199():
ypos = Symbol('y', positive=True)
# TODO: Remove conds='none' below, let the assumption take care of it.
assert integrate(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo), conds='none') == \
Integral(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo))
def test_issue_3940():
a, b, c, d = symbols('a:d', positive=True)
assert integrate(exp(-x**2 + I*c*x), x) == \
-sqrt(pi)*exp(-c**2/4)*erf(I*c/2 - x)/2
assert integrate(exp(a*x**2 + b*x + c), x) == \
sqrt(pi)*exp(c)*exp(-b**2/(4*a))*erfi(sqrt(a)*x + b/(2*sqrt(a)))/(2*sqrt(a))
from sympy.core.function import expand_mul
from sympy.abc import k
assert expand_mul(integrate(exp(-x**2)*exp(I*k*x), (x, -oo, oo))) == \
sqrt(pi)*exp(-k**2/4)
a, d = symbols('a d', positive=True)
assert expand_mul(integrate(exp(-a*x**2 + 2*d*x), (x, -oo, oo))) == \
sqrt(pi)*exp(d**2/a)/sqrt(a)
def test_issue_5413():
# Note that this is not the same as testing ratint() because integrate()
# pulls out the coefficient.
assert integrate(-a/(a**2 + x**2), x) == I*log(-I*a + x)/2 - I*log(I*a + x)/2
def test_issue_4892a():
A, z = symbols('A z')
c = Symbol('c', nonzero=True)
P1 = -A*exp(-z)
P2 = -A/(c*t)*(sin(x)**2 + cos(y)**2)
h1 = -sin(x)**2 - cos(y)**2
h2 = -sin(x)**2 + sin(y)**2 - 1
# there is still some non-deterministic behavior in integrate
# or trigsimp which permits one of the following
assert integrate(c*(P2 - P1), t) in [
c*(-A*(-h1)*log(c*t)/c + A*t*exp(-z)),
c*(-A*(-h2)*log(c*t)/c + A*t*exp(-z)),
c*( A* h1 *log(c*t)/c + A*t*exp(-z)),
c*( A* h2 *log(c*t)/c + A*t*exp(-z)),
(A*c*t - A*(-h1)*log(t)*exp(z))*exp(-z),
(A*c*t - A*(-h2)*log(t)*exp(z))*exp(-z),
]
def test_issue_4892b():
# Issues relating to issue 4596 are making the actual result of this hard
# to test. The answer should be something like
#
# (-sin(y) + sqrt(-72 + 48*cos(y) - 8*cos(y)**2)/2)*log(x + sqrt(-72 +
# 48*cos(y) - 8*cos(y)**2)/(2*(3 - cos(y)))) + (-sin(y) - sqrt(-72 +
# 48*cos(y) - 8*cos(y)**2)/2)*log(x - sqrt(-72 + 48*cos(y) -
# 8*cos(y)**2)/(2*(3 - cos(y)))) + x**2*sin(y)/2 + 2*x*cos(y)
expr = (sin(y)*x**3 + 2*cos(y)*x**2 + 12)/(x**2 + 2)
assert trigsimp(factor(integrate(expr, x).diff(x) - expr)) == 0
def test_issue_5178():
assert integrate(sin(x)*f(y, z), (x, 0, pi), (y, 0, pi), (z, 0, pi)) == \
2*Integral(f(y, z), (y, 0, pi), (z, 0, pi))
def test_integrate_series():
f = sin(x).series(x, 0, 10)
g = x**2/2 - x**4/24 + x**6/720 - x**8/40320 + x**10/3628800 + O(x**11)
assert integrate(f, x) == g
assert diff(integrate(f, x), x) == f
assert integrate(O(x**5), x) == O(x**6)
def test_atom_bug():
from sympy.integrals.heurisch import heurisch
assert heurisch(meijerg([], [], [1], [], x), x) is None
def test_limit_bug():
z = Symbol('z', zero=False)
assert integrate(sin(x*y*z), (x, 0, pi), (y, 0, pi)).together() == \
(log(z) - Ci(pi**2*z) + EulerGamma + 2*log(pi))/z
def test_issue_4703():
g = Function('g')
assert integrate(exp(x)*g(x), x).has(Integral)
def test_issue_1888():
f = Function('f')
assert integrate(f(x).diff(x)**2, x).has(Integral)
# The following tests work using meijerint.
def test_issue_3558():
assert integrate(cos(x*y), (x, -pi/2, pi/2), (y, 0, pi)) == 2*Si(pi**2/2)
def test_issue_4422():
assert integrate(1/sqrt(16 + 4*x**2), x) == asinh(x/2) / 2
def test_issue_4493():
assert simplify(integrate(x*sqrt(1 + 2*x), x)) == \
sqrt(2*x + 1)*(6*x**2 + x - 1)/15
def test_issue_4737():
assert integrate(sin(x)/x, (x, -oo, oo)) == pi
assert integrate(sin(x)/x, (x, 0, oo)) == pi/2
assert integrate(sin(x)/x, x) == Si(x)
def test_issue_4992():
# Note: psi in _check_antecedents becomes NaN.
from sympy.core.function import expand_func
a = Symbol('a', positive=True)
assert simplify(expand_func(integrate(exp(-x)*log(x)*x**a, (x, 0, oo)))) == \
(a*polygamma(0, a) + 1)*gamma(a)
def test_issue_4487():
from sympy.functions.special.gamma_functions import lowergamma
assert simplify(integrate(exp(-x)*x**y, x)) == lowergamma(y + 1, x)
def test_issue_4215():
x = Symbol("x")
assert integrate(1/(x**2), (x, -1, 1)) is oo
def test_issue_4400():
n = Symbol('n', integer=True, positive=True)
assert integrate((x**n)*log(x), x) == \
n*x*x**n*log(x)/(n**2 + 2*n + 1) + x*x**n*log(x)/(n**2 + 2*n + 1) - \
x*x**n/(n**2 + 2*n + 1)
def test_issue_6253():
# Note: this used to raise NotImplementedError
# Note: psi in _check_antecedents becomes NaN.
assert integrate((sqrt(1 - x) + sqrt(1 + x))**2/x, x, meijerg=True) == \
Integral((sqrt(-x + 1) + sqrt(x + 1))**2/x, x)
def test_issue_4153():
assert integrate(1/(1 + x + y + z), (x, 0, 1), (y, 0, 1), (z, 0, 1)) in [
-12*log(3) - 3*log(6)/2 + 3*log(8)/2 + 5*log(2) + 7*log(4),
6*log(2) + 8*log(4) - 27*log(3)/2, 22*log(2) - 27*log(3)/2,
-12*log(3) - 3*log(6)/2 + 47*log(2)/2]
def test_issue_4326():
R, b, h = symbols('R b h')
# It doesn't matter if we can do the integral. Just make sure the result
# doesn't contain nan. This is really a test against _eval_interval.
e = integrate(((h*(x - R + b))/b)*sqrt(R**2 - x**2), (x, R - b, R))
assert not e.has(nan)
# See that it evaluates
assert not e.has(Integral)
def test_powers():
assert integrate(2**x + 3**x, x) == 2**x/log(2) + 3**x/log(3)
def test_manual_option():
raises(ValueError, lambda: integrate(1/x, x, manual=True, meijerg=True))
# an example of a function that manual integration cannot handle
assert integrate(log(1+x)/x, (x, 0, 1), manual=True).has(Integral)
def test_meijerg_option():
raises(ValueError, lambda: integrate(1/x, x, meijerg=True, risch=True))
# an example of a function that meijerg integration cannot handle
assert integrate(tan(x), x, meijerg=True) == Integral(tan(x), x)
def test_risch_option():
# risch=True only allowed on indefinite integrals
raises(ValueError, lambda: integrate(1/log(x), (x, 0, oo), risch=True))
assert integrate(exp(-x**2), x, risch=True) == NonElementaryIntegral(exp(-x**2), x)
assert integrate(log(1/x)*y, x, y, risch=True) == y**2*(x*log(1/x)/2 + x/2)
assert integrate(erf(x), x, risch=True) == Integral(erf(x), x)
# TODO: How to test risch=False?
@slow
def test_heurisch_option():
raises(ValueError, lambda: integrate(1/x, x, risch=True, heurisch=True))
# an integral that heurisch can handle
assert integrate(exp(x**2), x, heurisch=True) == sqrt(pi)*erfi(x)/2
# an integral that heurisch currently cannot handle
assert integrate(exp(x)/x, x, heurisch=True) == Integral(exp(x)/x, x)
# an integral where heurisch currently hangs, issue 15471
assert integrate(log(x)*cos(log(x))/x**Rational(3, 4), x, heurisch=False) == (
-128*x**Rational(1, 4)*sin(log(x))/289 + 240*x**Rational(1, 4)*cos(log(x))/289 +
(16*x**Rational(1, 4)*sin(log(x))/17 + 4*x**Rational(1, 4)*cos(log(x))/17)*log(x))
def test_issue_6828():
f = 1/(1.08*x**2 - 4.3)
g = integrate(f, x).diff(x)
assert verify_numerically(f, g, tol=1e-12)
def test_issue_4803():
x_max = Symbol("x_max")
assert integrate(y/pi*exp(-(x_max - x)/cos(a)), x) == \
y*exp((x - x_max)/cos(a))*cos(a)/pi
def test_issue_4234():
assert integrate(1/sqrt(1 + tan(x)**2)) == tan(x)/sqrt(1 + tan(x)**2)
def test_issue_4492():
assert simplify(integrate(x**2 * sqrt(5 - x**2), x)).factor(
deep=True) == Piecewise(
(I*(2*x**5 - 15*x**3 + 25*x - 25*sqrt(x**2 - 5)*acosh(sqrt(5)*x/5)) /
(8*sqrt(x**2 - 5)), (x > sqrt(5)) | (x < -sqrt(5))),
((2*x**5 - 15*x**3 + 25*x - 25*sqrt(5 - x**2)*asin(sqrt(5)*x/5)) /
(-8*sqrt(-x**2 + 5)), True))
def test_issue_2708():
# This test needs to use an integration function that can
# not be evaluated in closed form. Update as needed.
f = 1/(a + z + log(z))
integral_f = NonElementaryIntegral(f, (z, 2, 3))
assert Integral(f, (z, 2, 3)).doit() == integral_f
assert integrate(f + exp(z), (z, 2, 3)) == integral_f - exp(2) + exp(3)
assert integrate(2*f + exp(z), (z, 2, 3)) == \
2*integral_f - exp(2) + exp(3)
assert integrate(exp(1.2*n*s*z*(-t + z)/t), (z, 0, x)) == \
NonElementaryIntegral(exp(-1.2*n*s*z)*exp(1.2*n*s*z**2/t),
(z, 0, x))
def test_issue_2884():
f = (4.000002016020*x + 4.000002016020*y + 4.000006024032)*exp(10.0*x)
e = integrate(f, (x, 0.1, 0.2))
assert str(e) == '1.86831064982608*y + 2.16387491480008'
def test_issue_8368i():
from sympy.functions.elementary.complexes import arg, Abs
assert integrate(exp(-s*x)*cosh(x), (x, 0, oo)) == \
Piecewise(
( pi*Piecewise(
( -s/(pi*(-s**2 + 1)),
Abs(s**2) < 1),
( 1/(pi*s*(1 - 1/s**2)),
Abs(s**(-2)) < 1),
( meijerg(
((S.Half,), (0, 0)),
((0, S.Half), (0,)),
polar_lift(s)**2),
True)
),
s**2 > 1
),
(
Integral(exp(-s*x)*cosh(x), (x, 0, oo)),
True))
assert integrate(exp(-s*x)*sinh(x), (x, 0, oo)) == \
Piecewise(
( -1/(s + 1)/2 - 1/(-s + 1)/2,
And(
Abs(s) > 1,
Abs(arg(s)) < pi/2,
Abs(arg(s)) <= pi/2
)),
( Integral(exp(-s*x)*sinh(x), (x, 0, oo)),
True))
def test_issue_8901():
assert integrate(sinh(1.0*x)) == 1.0*cosh(1.0*x)
assert integrate(tanh(1.0*x)) == 1.0*x - 1.0*log(tanh(1.0*x) + 1)
assert integrate(tanh(x)) == x - log(tanh(x) + 1)
@slow
def test_issue_8945():
assert integrate(sin(x)**3/x, (x, 0, 1)) == -Si(3)/4 + 3*Si(1)/4
assert integrate(sin(x)**3/x, (x, 0, oo)) == pi/4
assert integrate(cos(x)**2/x**2, x) == -Si(2*x) - cos(2*x)/(2*x) - 1/(2*x)
@slow
def test_issue_7130():
if ON_CI:
skip("Too slow for CI.")
i, L, a, b = symbols('i L a b')
integrand = (cos(pi*i*x/L)**2 / (a + b*x)).rewrite(exp)
assert x not in integrate(integrand, (x, 0, L)).free_symbols
def test_issue_10567():
a, b, c, t = symbols('a b c t')
vt = Matrix([a*t, b, c])
assert integrate(vt, t) == Integral(vt, t).doit()
assert integrate(vt, t) == Matrix([[a*t**2/2], [b*t], [c*t]])
def test_issue_11742():
assert integrate(sqrt(-x**2 + 8*x + 48), (x, 4, 12)) == 16*pi
def test_issue_11856():
t = symbols('t')
assert integrate(sinc(pi*t), t) == Si(pi*t)/pi
@slow
def test_issue_11876():
assert integrate(sqrt(log(1/x)), (x, 0, 1)) == sqrt(pi)/2
def test_issue_4950():
assert integrate((-60*exp(x) - 19.2*exp(4*x))*exp(4*x), x) ==\
-2.4*exp(8*x) - 12.0*exp(5*x)
def test_issue_4968():
assert integrate(sin(log(x**2))) == x*sin(log(x**2))/5 - 2*x*cos(log(x**2))/5
def test_singularities():
assert integrate(1/x**2, (x, -oo, oo)) is oo
assert integrate(1/x**2, (x, -1, 1)) is oo
assert integrate(1/(x - 1)**2, (x, -2, 2)) is oo
assert integrate(1/x**2, (x, 1, -1)) is -oo
assert integrate(1/(x - 1)**2, (x, 2, -2)) is -oo
def test_issue_12645():
x, y = symbols('x y', real=True)
assert (integrate(sin(x*x*x + y*y),
(x, -sqrt(pi - y*y), sqrt(pi - y*y)),
(y, -sqrt(pi), sqrt(pi)))
== Integral(sin(x**3 + y**2),
(x, -sqrt(-y**2 + pi), sqrt(-y**2 + pi)),
(y, -sqrt(pi), sqrt(pi))))
def test_issue_12677():
assert integrate(sin(x) / (cos(x)**3), (x, 0, pi/6)) == Rational(1, 6)
def test_issue_14078():
assert integrate((cos(3*x)-cos(x))/x, (x, 0, oo)) == -log(3)
def test_issue_14064():
assert integrate(1/cosh(x), (x, 0, oo)) == pi/2
def test_issue_14027():
assert integrate(1/(1 + exp(x - S.Half)/(1 + exp(x))), x) == \
x - exp(S.Half)*log(exp(x) + exp(S.Half)/(1 + exp(S.Half)))/(exp(S.Half) + E)
def test_issue_8170():
assert integrate(tan(x), (x, 0, pi/2)) is S.Infinity
def test_issue_8440_14040():
assert integrate(1/x, (x, -1, 1)) is S.NaN
assert integrate(1/(x + 1), (x, -2, 3)) is S.NaN
def test_issue_14096():
assert integrate(1/(x + y)**2, (x, 0, 1)) == -1/(y + 1) + 1/y
assert integrate(1/(1 + x + y + z)**2, (x, 0, 1), (y, 0, 1), (z, 0, 1)) == \
-4*log(4) - 6*log(2) + 9*log(3)
def test_issue_14144():
assert Abs(integrate(1/sqrt(1 - x**3), (x, 0, 1)).n() - 1.402182) < 1e-6
assert Abs(integrate(sqrt(1 - x**3), (x, 0, 1)).n() - 0.841309) < 1e-6
def test_issue_14375():
# This raised a TypeError. The antiderivative has exp_polar, which
# may be possible to unpolarify, so the exact output is not asserted here.
assert integrate(exp(I*x)*log(x), x).has(Ei)
def test_issue_14437():
f = Function('f')(x, y, z)
assert integrate(f, (x, 0, 1), (y, 0, 2), (z, 0, 3)) == \
Integral(f, (x, 0, 1), (y, 0, 2), (z, 0, 3))
def test_issue_14470():
assert integrate(1/sqrt(exp(x) + 1), x) == log(sqrt(exp(x) + 1) - 1) - log(sqrt(exp(x) + 1) + 1)
def test_issue_14877():
f = exp(1 - exp(x**2)*x + 2*x**2)*(2*x**3 + x)/(1 - exp(x**2)*x)**2
assert integrate(f, x) == \
-exp(2*x**2 - x*exp(x**2) + 1)/(x*exp(3*x**2) - exp(2*x**2))
def test_issue_14782():
f = sqrt(-x**2 + 1)*(-x**2 + x)
assert integrate(f, [x, -1, 1]) == - pi / 8
@slow
def test_issue_14782_slow():
f = sqrt(-x**2 + 1)*(-x**2 + x)
assert integrate(f, [x, 0, 1]) == S.One / 3 - pi / 16
def test_issue_12081():
f = x**(Rational(-3, 2))*exp(-x)
assert integrate(f, [x, 0, oo]) is oo
def test_issue_15285():
y = 1/x - 1
f = 4*y*exp(-2*y)/x**2
assert integrate(f, [x, 0, 1]) == 1
def test_issue_15432():
assert integrate(x**n * exp(-x) * log(x), (x, 0, oo)).gammasimp() == Piecewise(
(gamma(n + 1)*polygamma(0, n) + gamma(n + 1)/n, re(n) + 1 > 0),
(Integral(x**n*exp(-x)*log(x), (x, 0, oo)), True))
def test_issue_15124():
omega = IndexedBase('omega')
m, p = symbols('m p', cls=Idx)
assert integrate(exp(x*I*(omega[m] + omega[p])), x, conds='none') == \
-I*exp(I*x*omega[m])*exp(I*x*omega[p])/(omega[m] + omega[p])
def test_issue_15218():
with warns_deprecated_sympy():
Integral(Eq(x, y))
with warns_deprecated_sympy():
assert Integral(Eq(x, y), x) == Eq(Integral(x, x), Integral(y, x))
with warns_deprecated_sympy():
assert Integral(Eq(x, y), x).doit() == Eq(x**2/2, x*y)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
# The warning is made in the ExprWithLimits superclass. The stacklevel
# is correct for integrate(Eq) but not Eq.integrate
assert Eq(x, y).integrate(x) == Eq(x**2/2, x*y)
# These are not deprecated because they are definite integrals
assert integrate(Eq(x, y), (x, 0, 1)) == Eq(S.Half, y)
assert Eq(x, y).integrate((x, 0, 1)) == Eq(S.Half, y)
def test_issue_15292():
res = integrate(exp(-x**2*cos(2*t)) * cos(x**2*sin(2*t)), (x, 0, oo))
assert isinstance(res, Piecewise)
assert gammasimp((res - sqrt(pi)/2 * cos(t)).subs(t, pi/6)) == 0
def test_issue_4514():
assert integrate(sin(2*x)/sin(x), x) == 2*sin(x)
def test_issue_15457():
x, a, b = symbols('x a b', real=True)
definite = integrate(exp(Abs(x-2)), (x, a, b))
indefinite = integrate(exp(Abs(x-2)), x)
assert definite.subs({a: 1, b: 3}) == -2 + 2*E
assert indefinite.subs(x, 3) - indefinite.subs(x, 1) == -2 + 2*E
assert definite.subs({a: -3, b: -1}) == -exp(3) + exp(5)
assert indefinite.subs(x, -1) - indefinite.subs(x, -3) == -exp(3) + exp(5)
def test_issue_15431():
assert integrate(x*exp(x)*log(x), x) == \
(x*exp(x) - exp(x))*log(x) - exp(x) + Ei(x)
def test_issue_15640_log_substitutions():
f = x/log(x)
F = Ei(2*log(x))
assert integrate(f, x) == F and F.diff(x) == f
f = x**3/log(x)**2
F = -x**4/log(x) + 4*Ei(4*log(x))
assert integrate(f, x) == F and F.diff(x) == f
f = sqrt(log(x))/x**2
F = -sqrt(pi)*erfc(sqrt(log(x)))/2 - sqrt(log(x))/x
assert integrate(f, x) == F and F.diff(x) == f
def test_issue_15509():
from sympy.vector import CoordSys3D
N = CoordSys3D('N')
x = N.x
assert integrate(cos(a*x + b), (x, x_1, x_2), heurisch=True) == Piecewise(
(-sin(a*x_1 + b)/a + sin(a*x_2 + b)/a, (a > -oo) & (a < oo) & Ne(a, 0)), \
(-x_1*cos(b) + x_2*cos(b), True))
def test_issue_4311_fast():
x = symbols('x', real=True)
assert integrate(x*abs(9-x**2), x) == Piecewise(
(x**4/4 - 9*x**2/2, x <= -3),
(-x**4/4 + 9*x**2/2 - Rational(81, 2), x <= 3),
(x**4/4 - 9*x**2/2, True))
def test_integrate_with_complex_constants():
K = Symbol('K', positive=True)
x = Symbol('x', real=True)
m = Symbol('m', real=True)
t = Symbol('t', real=True)
assert integrate(exp(-I*K*x**2+m*x), x) == sqrt(I)*sqrt(pi)*exp(-I*m**2
/(4*K))*erfi((-2*I*K*x + m)/(2*sqrt(K)*sqrt(-I)))/(2*sqrt(K))
assert integrate(1/(1 + I*x**2), x) == (-I*(sqrt(-I)*log(x - I*sqrt(-I))/2
- sqrt(-I)*log(x + I*sqrt(-I))/2))
assert integrate(exp(-I*x**2), x) == sqrt(pi)*erf(sqrt(I)*x)/(2*sqrt(I))
assert integrate((1/(exp(I*t)-2)), t) == -t/2 - I*log(exp(I*t) - 2)/2
assert integrate((1/(exp(I*t)-2)), (t, 0, 2*pi)) == -pi
def test_issue_14241():
x = Symbol('x')
n = Symbol('n', positive=True, integer=True)
assert integrate(n * x ** (n - 1) / (x + 1), x) == \
n**2*x**n*lerchphi(x*exp_polar(I*pi), 1, n)*gamma(n)/gamma(n + 1)
def test_issue_13112():
assert integrate(sin(t)**2 / (5 - 4*cos(t)), [t, 0, 2*pi]) == pi / 4
def test_issue_14709b():
h = Symbol('h', positive=True)
i = integrate(x*acos(1 - 2*x/h), (x, 0, h))
assert i == 5*h**2*pi/16
def test_issue_8614():
x = Symbol('x')
t = Symbol('t')
assert integrate(exp(t)/t, (t, -oo, x)) == Ei(x)
assert integrate((exp(-x) - exp(-2*x))/x, (x, 0, oo)) == log(2)
@slow
def test_issue_15494():
s = symbols('s', positive=True)
integrand = (exp(s/2) - 2*exp(1.6*s) + exp(s))*exp(s)
solution = integrate(integrand, s)
assert solution != S.NaN
# Not sure how to test this properly as it is a symbolic expression with floats
# assert str(solution) == '0.666666666666667*exp(1.5*s) + 0.5*exp(2.0*s) - 0.769230769230769*exp(2.6*s)'
# Maybe
assert abs(solution.subs(s, 1) - (-3.67440080236188)) <= 1e-8
integrand = (exp(s/2) - 2*exp(S(8)/5*s) + exp(s))*exp(s)
assert integrate(integrand, s) == -10*exp(13*s/5)/13 + 2*exp(3*s/2)/3 + exp(2*s)/2
def test_li_integral():
y = Symbol('y')
assert Integral(li(y*x**2), x).doit() == Piecewise((x*li(x**2*y) - \
x*Ei(3*log(x**2*y)/2)/sqrt(x**2*y),
Ne(y, 0)), (0, True))
def test_issue_17473():
x = Symbol('x')
n = Symbol('n')
h = S.Half
ans = x**(n + 1)*gamma(h + h/n)*hyper((h + h/n,),
(3*h, 3*h + h/n), -x**(2*n)/4)/(2*n*gamma(3*h + h/n))
got = integrate(sin(x**n), x)
assert got == ans
_x = Symbol('x', zero=False)
reps = {x: _x}
assert integrate(sin(_x**n), _x) == ans.xreplace(reps).expand()
def test_issue_17671():
assert integrate(log(log(x)) / x**2, [x, 1, oo]) == -EulerGamma
assert integrate(log(log(x)) / x**3, [x, 1, oo]) == -log(2)/2 - EulerGamma/2
assert integrate(log(log(x)) / x**10, [x, 1, oo]) == -log(9)/9 - EulerGamma/9
def test_issue_2975():
w = Symbol('w')
C = Symbol('C')
y = Symbol('y')
assert integrate(1/(y**2+C)**(S(3)/2), (y, -w/2, w/2)) == w/(C**(S(3)/2)*sqrt(1 + w**2/(4*C)))
def test_issue_7827():
x, n, M = symbols('x n M')
N = Symbol('N', integer=True)
assert integrate(summation(x*n, (n, 1, N)), x) == x**2*(N**2/4 + N/4)
assert integrate(summation(x*sin(n), (n,1,N)), x) == \
Sum(x**2*sin(n)/2, (n, 1, N))
assert integrate(summation(sin(n*x), (n,1,N)), x) == \
Sum(Piecewise((-cos(n*x)/n, Ne(n, 0)), (0, True)), (n, 1, N))
assert integrate(integrate(summation(sin(n*x), (n,1,N)), x), x) == \
Piecewise((Sum(Piecewise((-sin(n*x)/n**2, Ne(n, 0)), (-x/n, True)),
(n, 1, N)), (n > -oo) & (n < oo) & Ne(n, 0)), (0, True))
assert integrate(Sum(x, (n, 1, M)), x) == M*x**2/2
raises(ValueError, lambda: integrate(Sum(x, (x, y, n)), y))
raises(ValueError, lambda: integrate(Sum(x, (x, 1, n)), n))
raises(ValueError, lambda: integrate(Sum(x, (x, 1, y)), x))
def test_issue_4231():
f = (1 + 2*x + sqrt(x + log(x))*(1 + 3*x) + x**2)/(x*(x + sqrt(x + log(x)))*sqrt(x + log(x)))
assert integrate(f, x) == 2*sqrt(x + log(x)) + 2*log(x + sqrt(x + log(x)))
def test_issue_17841():
f = diff(1/(x**2+x+I), x)
assert integrate(f, x) == 1/(x**2 + x + I)
def test_issue_21034():
x = Symbol('x', real=True, nonzero=True)
f1 = x*(-x**4/asin(5)**4 - x*sinh(x + log(asin(5))) + 5)
f2 = (x + cosh(cos(4)))/(x*(x + 1/(12*x)))
assert integrate(f1, x) == \
-x**6/(6*asin(5)**4) - x**2*cosh(x + log(asin(5))) + 5*x**2/2 + 2*x*sinh(x + log(asin(5))) - 2*cosh(x + log(asin(5)))
assert integrate(f2, x) == \
log(x**2 + S(1)/12)/2 + 2*sqrt(3)*cosh(cos(4))*atan(2*sqrt(3)*x)
def test_issue_4187():
assert integrate(log(x)*exp(-x), x) == Ei(-x) - exp(-x)*log(x)
assert integrate(log(x)*exp(-x), (x, 0, oo)) == -EulerGamma
def test_issue_5547():
L = Symbol('L')
z = Symbol('z')
r0 = Symbol('r0')
R0 = Symbol('R0')
assert integrate(r0**2*cos(z)**2, (z, -L/2, L/2)) == -r0**2*(-L/4 -
sin(L/2)*cos(L/2)/2) + r0**2*(L/4 + sin(L/2)*cos(L/2)/2)
assert integrate(r0**2*cos(R0*z)**2, (z, -L/2, L/2)) == Piecewise(
(-r0**2*(-L*R0/4 - sin(L*R0/2)*cos(L*R0/2)/2)/R0 +
r0**2*(L*R0/4 + sin(L*R0/2)*cos(L*R0/2)/2)/R0, (R0 > -oo) & (R0 < oo) & Ne(R0, 0)),
(L*r0**2, True))
w = 2*pi*z/L
sol = sqrt(2)*sqrt(L)*r0**2*fresnelc(sqrt(2)*sqrt(L))*gamma(S.One/4)/(16*gamma(S(5)/4)) + L*r0**2/2
assert integrate(r0**2*cos(w*z)**2, (z, -L/2, L/2)) == sol
def test_issue_15810():
assert integrate(1/(2**(2*x/3) + 1), (x, 0, oo)) == Rational(3, 2)
def test_issue_21024():
x = Symbol('x', real=True, nonzero=True)
f = log(x)*log(4*x) + log(3*x + exp(2))
F = x*log(x)**2 + x*(1 - 2*log(2)) + (-2*x + 2*x*log(2))*log(x) + \
(x + exp(2)/6)*log(3*x + exp(2)) + exp(2)*log(3*x + exp(2))/6
assert F == integrate(f, x)
f = (x + exp(3))/x**2
F = log(x) - exp(3)/x
assert F == integrate(f, x)
f = (x**2 + exp(5))/x
F = x**2/2 + exp(5)*log(x)
assert F == integrate(f, x)
f = x/(2*x + tanh(1))
F = x/2 - log(2*x + tanh(1))*tanh(1)/4
assert F == integrate(f, x)
f = x - sinh(4)/x
F = x**2/2 - log(x)*sinh(4)
assert F == integrate(f, x)
f = log(x + exp(5)/x)
F = x*log(x + exp(5)/x) - x + 2*exp(Rational(5, 2))*atan(x*exp(Rational(-5, 2)))
assert F == integrate(f, x)
f = x**5/(x + E)
F = x**5/5 - E*x**4/4 + x**3*exp(2)/3 - x**2*exp(3)/2 + x*exp(4) - exp(5)*log(x + E)
assert F == integrate(f, x)
f = 4*x/(x + sinh(5))
F = 4*x - 4*log(x + sinh(5))*sinh(5)
assert F == integrate(f, x)
f = x**2/(2*x + sinh(2))
F = x**2/4 - x*sinh(2)/4 + log(2*x + sinh(2))*sinh(2)**2/8
assert F == integrate(f, x)
f = -x**2/(x + E)
F = -x**2/2 + E*x - exp(2)*log(x + E)
assert F == integrate(f, x)
f = (2*x + 3)*exp(5)/x
F = 2*x*exp(5) + 3*exp(5)*log(x)
assert F == integrate(f, x)
f = x + 2 + cosh(3)/x
F = x**2/2 + 2*x + log(x)*cosh(3)
assert F == integrate(f, x)
f = x - tanh(1)/x**3
F = x**2/2 + tanh(1)/(2*x**2)
assert F == integrate(f, x)
f = (3*x - exp(6))/x
F = 3*x - exp(6)*log(x)
assert F == integrate(f, x)
f = x**4/(x + exp(5))**2 + x
F = x**3/3 + x**2*(Rational(1, 2) - exp(5)) + 3*x*exp(10) - 4*exp(15)*log(x + exp(5)) - exp(20)/(x + exp(5))
assert F == integrate(f, x)
f = x*(x + exp(10)/x**2) + x
F = x**3/3 + x**2/2 + exp(10)*log(x)
assert F == integrate(f, x)
f = x + x/(5*x + sinh(3))
F = x**2/2 + x/5 - log(5*x + sinh(3))*sinh(3)/25
assert F == integrate(f, x)
f = (x + exp(3))/(2*x**2 + 2*x)
F = exp(3)*log(x)/2 - exp(3)*log(x + 1)/2 + log(x + 1)/2
assert F == integrate(f, x).expand()
f = log(x + 4*sinh(4))
F = x*log(x + 4*sinh(4)) - x + 4*log(x + 4*sinh(4))*sinh(4)
assert F == integrate(f, x)
f = -x + 20*(exp(-5) - atan(4)/x)**3*sin(4)/x
F = (-x**2*exp(15)/2 + 20*log(x)*sin(4) - (-180*x**2*exp(5)*sin(4)*atan(4) + 90*x*exp(10)*sin(4)*atan(4)**2 - \
20*exp(15)*sin(4)*atan(4)**3)/(3*x**3))*exp(-15)
assert F == integrate(f, x)
f = 2*x**2*exp(-4) + 6/x
F_true = (2*x**3/3 + 6*exp(4)*log(x))*exp(-4)
assert F_true == integrate(f, x)
def test_issue_21721():
a = Symbol('a')
assert integrate(1/(pi*(1+(x-a)**2)),(x,-oo,oo)).expand() == \
-Heaviside(im(a) - 1, 0) + Heaviside(im(a) + 1, 0)
def test_issue_21831():
theta = symbols('theta')
assert integrate(cos(3*theta)/(5-4*cos(theta)), (theta, 0, 2*pi)) == pi/12
integrand = cos(2*theta)/(5 - 4*cos(theta))
assert integrate(integrand, (theta, 0, 2*pi)) == pi/6
@slow
def test_issue_22033_integral():
assert integrate((x**2 - Rational(1, 4))**2 * sqrt(1 - x**2), (x, -1, 1)) == pi/32
@slow
def test_issue_21671():
assert integrate(1,(z,x**2+y**2,2-x**2-y**2),(y,-sqrt(1-x**2),sqrt(1-x**2)),(x,-1,1)) == pi
assert integrate(-4*(1 - x**2)**(S(3)/2)/3 + 2*sqrt(1 - x**2)*(2 - 2*x**2), (x, -1, 1)) == pi
def test_issue_18527():
# The manual integrator can not currently solve this. Assert that it does
# not give an incorrect result involving Abs when x has real assumptions.
xr = symbols('xr', real=True)
expr = (cos(x)/(4+(sin(x))**2))
res_real = integrate(expr.subs(x, xr), xr, manual=True).subs(xr, x)
assert integrate(expr, x, manual=True) == res_real == Integral(expr, x)
def test_issue_23718():
f = 1/(b*cos(x) + a*sin(x))
Fpos = (-log(-a/b + tan(x/2) - sqrt(a**2 + b**2)/b)/sqrt(a**2 + b**2)
+log(-a/b + tan(x/2) + sqrt(a**2 + b**2)/b)/sqrt(a**2 + b**2))
F = Piecewise(
# XXX: The zoo case here is for a=b=0 so it should just be zoo or maybe
# it doesn't really need to be included at all given that the original
# integrand is really undefined in that case anyway.
(zoo*(-log(tan(x/2) - 1) + log(tan(x/2) + 1)), Eq(a, 0) & Eq(b, 0)),
(log(tan(x/2))/a, Eq(b, 0)),
(-I/(-I*b*sin(x) + b*cos(x)), Eq(a, -I*b)),
(I/(I*b*sin(x) + b*cos(x)), Eq(a, I*b)),
(Fpos, True),
)
assert integrate(f, x) == F
ap, bp = symbols('a, b', positive=True)
rep = {a: ap, b: bp}
assert integrate(f.subs(rep), x) == Fpos.subs(rep)
def test_issue_23566():
i = integrate(1/sqrt(x**2-1), (x, -2, -1))
assert i == -log(2 - sqrt(3))
assert math.isclose(i.n(), 1.31695789692482)
def test_pr_23583():
# This result from meijerg is wrong. Check whether new result is correct when this test fail.
assert integrate(1/sqrt((x - I)**2-1)) == Piecewise((acosh(x - I), Abs((x - I)**2) > 1), (-I*asin(x - I), True))
def test_issue_7264():
assert integrate(exp(x)*sqrt(1 + exp(2*x))) == sqrt(exp(2*x) + 1)*exp(x)/2 + asinh(exp(x))/2
def test_issue_11254a():
assert integrate(sech(x), (x, 0, 1)) == 2*atan(tanh(S.Half))
def test_issue_11254b():
assert integrate(csch(x), x) == log(tanh(x/2))
assert integrate(csch(x), (x, 0, 1)) == oo
def test_issue_11254d():
assert integrate((sech(x)**2).rewrite(sinh), x) == 2*tanh(x/2)/(tanh(x/2)**2 + 1)
def test_issue_22863():
i = integrate((3*x**3-x**2+2*x-4)/sqrt(x**2-3*x+2), (x, 0, 1))
assert i == -101*sqrt(2)/8 - 135*log(3 - 2*sqrt(2))/16
assert math.isclose(i.n(), -2.98126694400554)
def test_issue_9723():
assert integrate(sqrt(x + sqrt(x))) == \
2*sqrt(sqrt(x) + x)*(sqrt(x)/12 + x/3 - S(1)/8) + log(2*sqrt(x) + 2*sqrt(sqrt(x) + x) + 1)/8
assert integrate(sqrt(2*x+3+sqrt(4*x+5))**3) == \
sqrt(2*x + sqrt(4*x + 5) + 3) * \
(9*x/10 + 11*(4*x + 5)**(S(3)/2)/40 + sqrt(4*x + 5)/40 + (4*x + 5)**2/10 + S(11)/10)/2
def test_issue_23704():
# XXX: This is testing that an exception is not raised in risch Ideally
# manualintegrate (manual=True) would be able to compute this but
# manualintegrate is very slow for this example so we don't test that here.
assert (integrate(log(x)/x**2/(c*x**2+b*x+a),x, risch=True)
== NonElementaryIntegral(log(x)/(a*x**2 + b*x**3 + c*x**4), x))
def test_exp_substitution():
assert integrate(1/sqrt(1-exp(2*x))) == log(sqrt(1 - exp(2*x)) - 1)/2 - log(sqrt(1 - exp(2*x)) + 1)/2
def test_hyperbolic():
assert integrate(coth(x)) == x - log(tanh(x) + 1) + log(tanh(x))
assert integrate(sech(x)) == 2*atan(tanh(x/2))
assert integrate(csch(x)) == log(tanh(x/2))
def test_nested_pow():
assert integrate(sqrt(x**2)) == x*sqrt(x**2)/2
assert integrate(sqrt(x**(S(5)/3))) == 6*x*sqrt(x**(S(5)/3))/11
assert integrate(1/sqrt(x**2)) == x*log(x)/sqrt(x**2)
assert integrate(x*sqrt(x**(-4))) == x**2*sqrt(x**-4)*log(x)
def test_sqrt_quadratic():
assert integrate(1/sqrt(3*x**2+4*x+5)) == sqrt(3)*asinh(3*sqrt(11)*(x + S(2)/3)/11)/3
assert integrate(1/sqrt(-3*x**2+4*x+5)) == sqrt(3)*asin(3*sqrt(19)*(x - S(2)/3)/19)/3
assert integrate(1/sqrt(3*x**2+4*x-5)) == sqrt(3)*log(6*x + 2*sqrt(3)*sqrt(3*x**2 + 4*x - 5) + 4)/3
assert integrate(1/sqrt(4*x**2-4*x+1)) == (x - S.Half)*log(x - S.Half)/(2*sqrt((x - S.Half)**2))
assert integrate(1/sqrt(a+b*x+c*x**2), x) == \
Piecewise((log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(c, 0) & Ne(a - b**2/(4*c), 0)),
((b/(2*c) + x)*log(b/(2*c) + x)/sqrt(c*(b/(2*c) + x)**2), Ne(c, 0)),
(2*sqrt(a + b*x)/b, Ne(b, 0)), (x/sqrt(a), True))
assert integrate((7*x+6)/sqrt(3*x**2+4*x+5)) == \
7*sqrt(3*x**2 + 4*x + 5)/3 + 4*sqrt(3)*asinh(3*sqrt(11)*(x + S(2)/3)/11)/9
assert integrate((7*x+6)/sqrt(-3*x**2+4*x+5)) == \
-7*sqrt(-3*x**2 + 4*x + 5)/3 + 32*sqrt(3)*asin(3*sqrt(19)*(x - S(2)/3)/19)/9
assert integrate((7*x+6)/sqrt(3*x**2+4*x-5)) == \
7*sqrt(3*x**2 + 4*x - 5)/3 + 4*sqrt(3)*log(6*x + 2*sqrt(3)*sqrt(3*x**2 + 4*x - 5) + 4)/9
assert integrate((d+e*x)/sqrt(a+b*x+c*x**2), x) == \
Piecewise(((-b*e/(2*c) + d) *
Piecewise((log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(a - b**2/(4*c), 0)),
((b/(2*c) + x)*log(b/(2*c) + x)/sqrt(c*(b/(2*c) + x)**2), True)) +
e*sqrt(a + b*x + c*x**2)/c, Ne(c, 0)),
((2*d*sqrt(a + b*x) + 2*e*(-a*sqrt(a + b*x) + (a + b*x)**(S(3)/2)/3)/b)/b, Ne(b, 0)),
((d*x + e*x**2/2)/sqrt(a), True))
assert integrate((3*x**3-x**2+2*x-4)/sqrt(x**2-3*x+2)) == \
sqrt(x**2 - 3*x + 2)*(x**2 + 13*x/4 + S(101)/8) + 135*log(2*x + 2*sqrt(x**2 - 3*x + 2) - 3)/16
assert integrate(sqrt(53225*x**2-66732*x+23013)) == \
(x/2 - S(16683)/53225)*sqrt(53225*x**2 - 66732*x + 23013) + \
111576969*sqrt(2129)*asinh(53225*x/10563 - S(11122)/3521)/1133160250
assert integrate(sqrt(a+b*x+c*x**2), x) == \
Piecewise(((a/2 - b**2/(8*c)) *
Piecewise((log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(a - b**2/(4*c), 0)),
((b/(2*c) + x)*log(b/(2*c) + x)/sqrt(c*(b/(2*c) + x)**2), True)) +
(b/(4*c) + x/2)*sqrt(a + b*x + c*x**2), Ne(c, 0)),
(2*(a + b*x)**(S(3)/2)/(3*b), Ne(b, 0)),
(sqrt(a)*x, True))
assert integrate(x*sqrt(x**2+2*x+4)) == \
(x**2/3 + x/6 + S(5)/6)*sqrt(x**2 + 2*x + 4) - 3*asinh(sqrt(3)*(x + 1)/3)/2
def test_mul_pow_derivative():
assert integrate(x*sec(x)*tan(x)) == x*sec(x) - log(tan(x) + sec(x))
assert integrate(x*sec(x)**2, x) == x*tan(x) + log(cos(x))
assert integrate(x**3*Derivative(f(x), (x, 4))) == \
x**3*Derivative(f(x), (x, 3)) - 3*x**2*Derivative(f(x), (x, 2)) + 6*x*Derivative(f(x), x) - 6*f(x)
|
def845b94ed581c4c1d78104e00450dc194ae612e666445d01da7cd5c6b8dd3b | from sympy.integrals.laplace import (
laplace_transform, inverse_laplace_transform,
LaplaceTransform, InverseLaplaceTransform)
from sympy.core.function import Function, expand_mul
from sympy.core import EulerGamma, Subs, Derivative, diff
from sympy.core.exprtools import factor_terms
from sympy.core.numbers import I, oo, pi
from sympy.core.singleton import S
from sympy.core.symbol import Symbol, symbols
from sympy.simplify.simplify import simplify
from sympy.functions.elementary.complexes import Abs, re
from sympy.functions.elementary.exponential import exp, log, exp_polar
from sympy.functions.elementary.hyperbolic import cosh, sinh, coth, asinh
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import atan, cos, sin
from sympy.functions.special.gamma_functions import lowergamma, gamma
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
from sympy.functions.special.zeta_functions import lerchphi
from sympy.functions.special.error_functions import (
fresnelc, fresnels, erf, erfc, Ei, Ci, expint, E1)
from sympy.functions.special.bessel import besseli, besselj, besselk, bessely
from sympy.testing.pytest import slow, warns_deprecated_sympy
from sympy.matrices import Matrix, eye
from sympy.abc import s
@slow
def test_laplace_transform():
LT = laplace_transform
a, b, c, = symbols('a, b, c', positive=True)
t, w, x = symbols('t, w, x')
f = Function("f")
g = Function("g")
# Test whether `noconds=True` in `doit`:
assert (2*LaplaceTransform(exp(t), t, s) - 1).doit() == -1 + 2/(s - 1)
assert LT(a*t+t**2+t**(S(5)/2), t, s) ==\
(a/s**2 + 2/s**3 + 15*sqrt(pi)/(8*s**(S(7)/2)), 0, True)
assert LT(b/(t+a), t, s) == (-b*exp(-a*s)*Ei(-a*s), 0, True)
assert LT(1/sqrt(t+a), t, s) ==\
(sqrt(pi)*sqrt(1/s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True)
assert LT(sqrt(t)/(t+a), t, s) ==\
(-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s),
0, True)
assert LT((t+a)**(-S(3)/2), t, s) ==\
(-2*sqrt(pi)*sqrt(s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + 2/sqrt(a),
0, True)
assert LT(t**(S(1)/2)*(t+a)**(-1), t, s) ==\
(-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s),
0, True)
assert LT(1/(a*sqrt(t) + t**(3/2)), t, s) ==\
(pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True)
assert LT((t+a)**b, t, s) ==\
(s**(-b - 1)*exp(-a*s)*lowergamma(b + 1, a*s), 0, True)
assert LT(t**5/(t+a), t, s) == (120*a**5*lowergamma(-5, a*s), 0, True)
assert LT(exp(t), t, s) == (1/(s - 1), 1, True)
assert LT(exp(2*t), t, s) == (1/(s - 2), 2, True)
assert LT(exp(a*t), t, s) == (1/(s - a), a, True)
assert LT(exp(a*(t-b)), t, s) == (exp(-a*b)/(-a + s), a, True)
assert LT(t*exp(-a*(t)), t, s) == ((a + s)**(-2), -a, True)
assert LT(t*exp(-a*(t-b)), t, s) == (exp(a*b)/(a + s)**2, -a, True)
assert LT(b*t*exp(-a*t), t, s) == (b/(a + s)**2, -a, True)
assert LT(t**(S(7)/4)*exp(-8*t)/gamma(S(11)/4), t, s) ==\
((s + 8)**(-S(11)/4), -8, True)
assert LT(t**(S(3)/2)*exp(-8*t), t, s) ==\
(3*sqrt(pi)/(4*(s + 8)**(S(5)/2)), -8, True)
assert LT(t**a*exp(-a*t), t, s) == ((a+s)**(-a-1)*gamma(a+1), -a, True)
assert LT(b*exp(-a*t**2), t, s) ==\
(sqrt(pi)*b*exp(s**2/(4*a))*erfc(s/(2*sqrt(a)))/(2*sqrt(a)), 0, True)
assert LT(exp(-2*t**2), t, s) ==\
(sqrt(2)*sqrt(pi)*exp(s**2/8)*erfc(sqrt(2)*s/4)/4, 0, True)
assert LT(b*exp(2*t**2), t, s) ==\
(b*LaplaceTransform(exp(2*t**2), t, s), -oo, True)
assert LT(t*exp(-a*t**2), t, s) ==\
(1/(2*a) - s*erfc(s/(2*sqrt(a)))/(4*sqrt(pi)*a**(S(3)/2)), 0, True)
assert LT(exp(-a/t), t, s) ==\
(2*sqrt(a)*sqrt(1/s)*besselk(1, 2*sqrt(a)*sqrt(s)), 0, True)
assert LT(sqrt(t)*exp(-a/t), t, s, simplify=True) ==\
(sqrt(pi)*(sqrt(a)*sqrt(s) + 1/S(2))*sqrt(s**(-3))*exp(-2*sqrt(a)*sqrt(s)),
0, True)
assert LT(exp(-a/t)/sqrt(t), t, s) ==\
(sqrt(pi)*sqrt(1/s)*exp(-2*sqrt(a)*sqrt(s)), 0, True)
assert LT( exp(-a/t)/(t*sqrt(t)), t, s) ==\
(sqrt(pi)*sqrt(1/a)*exp(-2*sqrt(a)*sqrt(s)), 0, True)
assert LT(exp(-2*sqrt(a*t)), t, s) ==\
( 1/s -sqrt(pi)*sqrt(a) * exp(a/s)*erfc(sqrt(a)*sqrt(1/s))/\
s**(S(3)/2), 0, True)
assert LT(exp(-2*sqrt(a*t))/sqrt(t), t, s) == (exp(a/s)*erfc(sqrt(a)*\
sqrt(1/s))*(sqrt(pi)*sqrt(1/s)), 0, True)
assert LT(t**4*exp(-2/t), t, s) ==\
(8*sqrt(2)*(1/s)**(S(5)/2)*besselk(5, 2*sqrt(2)*sqrt(s)), 0, True)
assert LT(sinh(a*t), t, s) == (a/(-a**2 + s**2), a, True)
assert LT(b*sinh(a*t)**2, t, s, simplify=True) ==\
(2*a**2*b/(s*(-4*a**2 + s**2)), 2*a, True)
# The following line confirms that issue #21202 is solved
assert LT(cosh(2*t), t, s) == (s/(-4 + s**2), 2, True)
assert LT(cosh(a*t), t, s) == (s/(-a**2 + s**2), a, True)
assert LT(cosh(a*t)**2, t, s, simplify=True) ==\
((2*a**2 - s**2)/(s*(4*a**2 - s**2)), 2*a, True)
assert LT(sinh(x+3), x, s, simplify=True) ==\
((s*sinh(3) + cosh(3))/(s**2 - 1), 1, True)
# The following line replaces the old test test_issue_7173()
assert LT(sinh(a*t)*cosh(a*t), t, s, simplify=True) == (a/(-4*a**2 + s**2),
2*a, True)
assert LT(sinh(a*t)/t, t, s) == (log((a + s)/(-a + s))/2, a, True)
assert LT(t**(-S(3)/2)*sinh(a*t), t, s) ==\
(sqrt(pi)*(-sqrt(-a + s) + sqrt(a + s)), a, True)
assert LT(sinh(2*sqrt(a*t)), t, s) ==\
(sqrt(pi)*sqrt(a)*exp(a/s)/s**(S(3)/2), 0, True)
assert LT(sqrt(t)*sinh(2*sqrt(a*t)), t, s, simplify=True) ==\
((-sqrt(a)*s**(S(5)/2) + sqrt(pi)*s**2*(2*a + s)*exp(a/s)*\
erf(sqrt(a)*sqrt(1/s))/2)/s**(S(9)/2), 0, True)
assert LT(sinh(2*sqrt(a*t))/sqrt(t), t, s) ==\
(sqrt(pi)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/sqrt(s), 0, True)
assert LT(sinh(sqrt(a*t))**2/sqrt(t), t, s) ==\
(sqrt(pi)*(exp(a/s) - 1)/(2*sqrt(s)), 0, True)
assert LT(t**(S(3)/7)*cosh(a*t), t, s) ==\
(((a + s)**(-S(10)/7) + (-a+s)**(-S(10)/7))*gamma(S(10)/7)/2, a, True)
assert LT(cosh(2*sqrt(a*t)), t, s) ==\
(sqrt(pi)*sqrt(a)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/s**(S(3)/2) + 1/s,
0, True)
assert LT(sqrt(t)*cosh(2*sqrt(a*t)), t, s) ==\
(sqrt(pi)*(a + s/2)*exp(a/s)/s**(S(5)/2), 0, True)
assert LT(cosh(2*sqrt(a*t))/sqrt(t), t, s) ==\
(sqrt(pi)*exp(a/s)/sqrt(s), 0, True)
assert LT(cosh(sqrt(a*t))**2/sqrt(t), t, s) ==\
(sqrt(pi)*(exp(a/s) + 1)/(2*sqrt(s)), 0, True)
assert LT(log(t), t, s, simplify=True) == ((-log(s) - EulerGamma)/s, 0, True)
assert LT(-log(t/a), t, s, simplify=True) ==\
((log(a) + log(s) + EulerGamma)/s, 0, True)
assert LT(log(1+a*t), t, s) == (-exp(s/a)*Ei(-s/a)/s, 0, True)
assert LT(log(t+a), t, s, simplify=True) ==\
((s*log(a) - exp(s/a)*Ei(-s/a))/s**2, 0, True)
assert LT(log(t)/sqrt(t), t, s, simplify=True) ==\
(sqrt(pi)*(-log(s) - log(4) - EulerGamma)/sqrt(s), 0, True)
assert LT(t**(S(5)/2)*log(t), t, s, simplify=True) ==\
(sqrt(pi)*(-15*log(s) - log(1073741824) - 15*EulerGamma + 46)/\
(8*s**(S(7)/2)), 0, True)
assert (LT(t**3*log(t), t, s, noconds=True, simplify=True)-\
6*(-log(s) - S.EulerGamma + S(11)/6)/s**4).simplify() == S.Zero
assert LT(log(t)**2, t, s, simplify=True) ==\
(((log(s) + EulerGamma)**2 + pi**2/6)/s, 0, True)
assert LT(exp(-a*t)*log(t), t, s, simplify=True) ==\
((-log(a + s) - EulerGamma)/(a + s), -a, True)
assert LT(sin(a*t), t, s) == (a/(a**2 + s**2), 0, True)
assert LT(Abs(sin(a*t)), t, s) ==\
(a*coth(pi*s/(2*a))/(a**2 + s**2), 0, True)
assert LT(sin(a*t)/t, t, s) == (atan(a/s), 0, True)
assert LT(sin(a*t)**2/t, t, s) == (log(4*a**2/s**2 + 1)/4, 0, True)
assert LT(sin(a*t)**2/t**2, t, s) ==\
(a*atan(2*a/s) - s*log(4*a**2/s**2 + 1)/4, 0, True)
assert LT(sin(2*sqrt(a*t)), t, s) ==\
(sqrt(pi)*sqrt(a)*exp(-a/s)/s**(S(3)/2), 0, True)
assert LT(sin(2*sqrt(a*t))/t, t, s) == (pi*erf(sqrt(a)*sqrt(1/s)), 0, True)
assert LT(cos(a*t), t, s) == (s/(a**2 + s**2), 0, True)
assert LT(cos(a*t)**2, t, s) ==\
((2*a**2 + s**2)/(s*(4*a**2 + s**2)), 0, True)
assert LT(sqrt(t)*cos(2*sqrt(a*t)), t, s, simplify=True) ==\
(sqrt(pi)*(-a + s/2)*exp(-a/s)/s**(S(5)/2), 0, True)
assert LT(cos(2*sqrt(a*t))/sqrt(t), t, s) ==\
(sqrt(pi)*sqrt(1/s)*exp(-a/s), 0, True)
assert LT(sin(a*t)*sin(b*t), t, s) ==\
(2*a*b*s/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)), 0, True)
assert LT(cos(a*t)*sin(b*t), t, s) ==\
(b*(-a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)),
0, True)
assert LT(cos(a*t)*cos(b*t), t, s) ==\
(s*(a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)),
0, True)
assert LT(-a*t*cos(a*t) + sin(a*t), t, s, simplify=True) ==\
(2*a**3/(a**4 + 2*a**2*s**2 + s**4), 0, True)
assert LT(c*exp(-b*t)*sin(a*t), t, s) == (a*c/(a**2 + (b + s)**2), -b, True)
assert LT(c*exp(-b*t)*cos(a*t), t, s) == ((b + s)*c/(a**2 + (b + s)**2),
-b, True)
assert LT(cos(x + 3), x, s, simplify=True) ==\
((s*cos(3) - sin(3))/(s**2 + 1), 0, True)
# Error functions (laplace7.pdf)
assert LT(erf(a*t), t, s) == (exp(s**2/(4*a**2))*erfc(s/(2*a))/s, 0, True)
assert LT(erf(sqrt(a*t)), t, s) == (sqrt(a)/(s*sqrt(a + s)), 0, True)
assert LT(exp(a*t)*erf(sqrt(a*t)), t, s, simplify=True) ==\
(-sqrt(a)/(sqrt(s)*(a - s)), a, True)
assert LT(erf(sqrt(a/t)/2), t, s, simplify=True) ==\
(1/s - exp(-sqrt(a)*sqrt(s))/s, 0, True)
assert LT(erfc(sqrt(a*t)), t, s, simplify=True) ==\
(-sqrt(a)/(s*sqrt(a + s)) + 1/s, -a, True)
assert LT(exp(a*t)*erfc(sqrt(a*t)), t, s) ==\
(1/(sqrt(a)*sqrt(s) + s), 0, True)
assert LT(erfc(sqrt(a/t)/2), t, s) == (exp(-sqrt(a)*sqrt(s))/s, 0, True)
# Bessel functions (laplace8.pdf)
assert LT(besselj(0, a*t), t, s) == (1/sqrt(a**2 + s**2), 0, True)
assert LT(besselj(1, a*t), t, s, simplify=True) ==\
(a/(a**2 + s**2 + s*sqrt(a**2 + s**2)), 0, True)
assert LT(besselj(2, a*t), t, s, simplify=True) ==\
(a**2/(sqrt(a**2 + s**2)*(s + sqrt(a**2 + s**2))**2), 0, True)
assert LT(t*besselj(0, a*t), t, s) ==\
(s/(a**2 + s**2)**(S(3)/2), 0, True)
assert LT(t*besselj(1, a*t), t, s) ==\
(a/(a**2 + s**2)**(S(3)/2), 0, True)
assert LT(t**2*besselj(2, a*t), t, s) ==\
(3*a**2/(a**2 + s**2)**(S(5)/2), 0, True)
assert LT(besselj(0, 2*sqrt(a*t)), t, s) == (exp(-a/s)/s, 0, True)
assert LT(t**(S(3)/2)*besselj(3, 2*sqrt(a*t)), t, s) ==\
(a**(S(3)/2)*exp(-a/s)/s**4, 0, True)
assert LT(besselj(0, a*sqrt(t**2+b*t)), t, s, simplify=True) ==\
(exp(b*(s - sqrt(a**2 + s**2)))/sqrt(a**2 + s**2), 0, True)
assert LT(besseli(0, a*t), t, s) == (1/sqrt(-a**2 + s**2), a, True)
assert LT(besseli(1, a*t), t, s, simplify=True) ==\
(a/(-a**2 + s**2 + s*sqrt(-a**2 + s**2)), a, True)
assert LT(besseli(2, a*t), t, s, simplify=True) ==\
(a**2/(sqrt(-a**2 + s**2)*(s + sqrt(-a**2 + s**2))**2), a, True)
assert LT(t*besseli(0, a*t), t, s) == (s/(-a**2 + s**2)**(S(3)/2), a, True)
assert LT(t*besseli(1, a*t), t, s) == (a/(-a**2 + s**2)**(S(3)/2), a, True)
assert LT(t**2*besseli(2, a*t), t, s) ==\
(3*a**2/(-a**2 + s**2)**(S(5)/2), a, True)
assert LT(t**(S(3)/2)*besseli(3, 2*sqrt(a*t)), t, s) ==\
(a**(S(3)/2)*exp(a/s)/s**4, 0, True)
assert LT(bessely(0, a*t), t, s) ==\
(-2*asinh(s/a)/(pi*sqrt(a**2 + s**2)), 0, True)
assert LT(besselk(0, a*t), t, s) ==\
(log((s + sqrt(-a**2 + s**2))/a)/sqrt(-a**2 + s**2), -a, True)
assert LT(sin(a*t)**8, t, s, simplify=True) ==\
(40320*a**8/(s*(147456*a**8 + 52480*a**6*s**2 + 4368*a**4*s**4 +\
120*a**2*s**6 + s**8)), 0, True)
# Test general rules and unevaluated forms
# These all also test whether issue #7219 is solved.
assert LT(Heaviside(t-1)*cos(t-1), t, s) == (s*exp(-s)/(s**2 + 1), 0, True)
assert LT(a*f(t), t, w) == (a*LaplaceTransform(f(t), t, w), -oo, True)
assert LT(a*Heaviside(t+1)*f(t+1), t, s) ==\
(a*LaplaceTransform(f(t + 1), t, s), -oo, True)
assert LT(a*Heaviside(t-1)*f(t-1), t, s) ==\
(a*LaplaceTransform(f(t), t, s)*exp(-s), -oo, True)
assert LT(b*f(t/a), t, s) == (a*b*LaplaceTransform(f(t), t, a*s),
-oo, True)
assert LT(exp(-f(x)*t), t, s) == (1/(s + f(x)), -f(x), True)
assert LT(exp(-a*t)*f(t), t, s) ==\
(LaplaceTransform(f(t), t, a + s), -oo, True)
assert LT(exp(-a*t)*erfc(sqrt(b/t)/2), t, s) ==\
(exp(-sqrt(b)*sqrt(a + s))/(a + s), -a, True)
assert LT(sinh(a*t)*f(t), t, s) ==\
(LaplaceTransform(f(t), t, -a + s)/2 -\
LaplaceTransform(f(t), t, a + s)/2, -oo, True)
assert LT(sinh(a*t)*t, t, s, simplify=True) ==\
(2*a*s/(a**4 - 2*a**2*s**2 + s**4), a, True)
assert LT(cosh(a*t)*f(t), t, s) ==\
(LaplaceTransform(f(t), t, -a + s)/2 +\
LaplaceTransform(f(t), t, a + s)/2, -oo, True)
assert LT(cosh(a*t)*t, t, s, simplify=True) ==\
(1/(2*(a + s)**2) + 1/(2*(a - s)**2), a, True)
assert LT(sin(a*t)*f(t), t, s, simplify=True) ==\
(I*(-LaplaceTransform(f(t), t, -I*a + s) +\
LaplaceTransform(f(t), t, I*a + s))/2, -oo, True)
assert LT(sin(a*t)*t, t, s, simplify=True) ==\
(2*a*s/(a**4 + 2*a**2*s**2 + s**4), 0, True)
assert LT(cos(a*t)*f(t), t, s) ==\
(LaplaceTransform(f(t), t, -I*a + s)/2 +\
LaplaceTransform(f(t), t, I*a + s)/2, -oo, True)
assert LT(cos(a*t)*t, t, s, simplify=True) ==\
((-a**2 + s**2)/(a**4 + 2*a**2*s**2 + s**4), 0, True)
assert LT(t**2*exp(-t**2), t, s) ==\
(sqrt(pi)*s**2*exp(s**2/4)*erfc(s/2)/8 - s/4 +\
sqrt(pi)*exp(s**2/4)*erfc(s/2)/4, 0, True)
assert LT((a*t**2 + b*t + c)*f(t), t, s) ==\
(a*Derivative(LaplaceTransform(f(t), t, s), (s, 2)) -\
b*Derivative(LaplaceTransform(f(t), t, s), s) +\
c*LaplaceTransform(f(t), t, s), -oo, True)
# The following two lines test whether issues #5813 and #7176 are solved.
assert LT(diff(f(t), (t, 1)), t, s, noconds=True) ==\
s*LaplaceTransform(f(t), t, s) - f(0)
assert LT(diff(f(t), (t, 3)), t, s, noconds=True) ==\
s**3*LaplaceTransform(f(t), t, s) - s**2*f(0) -\
s*Subs(Derivative(f(t), t), t, 0) -\
Subs(Derivative(f(t), (t, 2)), t, 0)
# Issue #7219
assert LT(diff(f(x, t, w), t, 2), t, s) ==\
(s**2*LaplaceTransform(f(x, t, w), t, s) - s*f(x, 0, w) -\
Subs(Derivative(f(x, t, w), t), t, 0), -oo, True)
# Issue #23307
assert LT(10*diff(f(t), (t, 1)), t, s, noconds=True) ==\
10*s*LaplaceTransform(f(t), t, s) - 10*f(0)
assert LT(a*f(b*t)+g(c*t), t, s, noconds=True) ==\
a*LaplaceTransform(f(t), t, s/b)/b + LaplaceTransform(g(t), t, s/c)/c
assert inverse_laplace_transform(
f(w), w, t, plane=0) == InverseLaplaceTransform(f(w), w, t, 0)
assert LT(f(t)*g(t), t, s, noconds=True) ==\
LaplaceTransform(f(t)*g(t), t, s)
# Issue #24294
assert LT(b*f(a*t), t, s, noconds=True) ==\
b*LaplaceTransform(f(t), t, s/a)/a
assert LT(3*exp(t)*Heaviside(t), t, s) == (3/(s - 1), 1, True)
assert LT(2*sin(t)*Heaviside(t), t, s, simplify=True) == (2/(s**2 + 1),
0, True)
# additional basic tests from wikipedia
assert LT((t - a)**b*exp(-c*(t - a))*Heaviside(t - a), t, s) == \
((c + s)**(-b - 1)*exp(-a*s)*gamma(b + 1), -c, True)
assert LT((exp(2*t)-1)*exp(-b-t)*Heaviside(t)/2, t, s, noconds=True,
simplify=True) == exp(-b)/(s**2 - 1)
# DiracDelta function: standard cases
assert LT(DiracDelta(t), t, s) == (1, -oo, True)
assert LT(DiracDelta(a*t), t, s) == (1/a, -oo, True)
assert LT(DiracDelta(t/42), t, s) == (42, -oo, True)
assert LT(DiracDelta(t+42), t, s) == (0, -oo, True)
assert LT(DiracDelta(t)+DiracDelta(t-42), t, s) == \
(1 + exp(-42*s), -oo, True)
assert LT(DiracDelta(t)-a*exp(-a*t), t, s, simplify=True) == \
(s/(a + s), -a, True)
assert LT(exp(-t)*(DiracDelta(t)+DiracDelta(t-42)), t, s, simplify=True) == \
(exp(-42*s - 42) + 1, -oo, True)
assert LT(f(t)*DiracDelta(t-42), t, s) == (f(42)*exp(-42*s), -oo, True)
assert LT(f(t)*DiracDelta(b*t-a), t, s) == (f(a/b)*exp(-a*s/b)/b,
-oo, True)
assert LT(f(t)*DiracDelta(b*t+a), t, s) == (0, -oo, True)
# Collection of cases that cannot be fully evaluated and/or would catch
# some common implementation errors
assert LT(DiracDelta(t**2), t, s, noconds=True) ==\
LaplaceTransform(DiracDelta(t**2), t, s)
assert LT(DiracDelta(t**2 - 1), t, s) == (exp(-s)/2, -oo, True)
assert LT(DiracDelta(t*(1 - t)), t, s) == (1 - exp(-s), -oo, True)
assert LT((DiracDelta(t) + 1)*(DiracDelta(t - 1) + 1), t, s) == \
(LaplaceTransform(DiracDelta(t)*DiracDelta(t - 1), t, s) + \
1 + exp(-s) + 1/s, 0, True)
assert LT(DiracDelta(2*t-2*exp(a)), t, s) == (exp(-s*exp(a))/2, -oo, True)
assert LT(DiracDelta(-2*t+2*exp(a)), t, s) == (exp(-s*exp(a))/2, -oo, True)
# Heaviside tests
assert LT(Heaviside(t), t, s) == (1/s, 0, True)
assert LT(Heaviside(t - a), t, s) == (exp(-a*s)/s, 0, True)
assert LT(Heaviside(t-1), t, s) == (exp(-s)/s, 0, True)
assert LT(Heaviside(2*t-4), t, s) == (exp(-2*s)/s, 0, True)
assert LT(Heaviside(2*t+4), t, s) == (1/s, 0, True)
assert LT(Heaviside(-2*t+4), t, s, simplify=True) == (1/s - exp(-2*s)/s,
0, True)
assert LT(g(t)*Heaviside(t - w), t, s) ==\
(LaplaceTransform(g(t)*Heaviside(t - w), t, s), -oo, True)
# Fresnel functions
assert laplace_transform(fresnels(t), t, s, simplify=True) == \
((-sin(s**2/(2*pi))*fresnels(s/pi) + sqrt(2)*sin(s**2/(2*pi) + pi/4)/2\
- cos(s**2/(2*pi))*fresnelc(s/pi))/s, 0, True)
assert laplace_transform(fresnelc(t), t, s, simplify=True) == \
((sin(s**2/(2*pi))*fresnelc(s/pi) - cos(s**2/(2*pi))*fresnels(s/pi)\
+ sqrt(2)*cos(s**2/(2*pi) + pi/4)/2)/s, 0, True)
# Matrix tests
Mt = Matrix([[exp(t), t*exp(-t)], [t*exp(-t), exp(t)]])
Ms = Matrix([[ 1/(s - 1), (s + 1)**(-2)],
[(s + 1)**(-2), 1/(s - 1)]])
# The default behaviour for Laplace transform of a Matrix returns a Matrix
# of Tuples and is deprecated:
with warns_deprecated_sympy():
Ms_conds = Matrix([[(1/(s - 1), 1, True), ((s + 1)**(-2),
-1, True)], [((s + 1)**(-2), -1, True), (1/(s - 1), 1, True)]])
with warns_deprecated_sympy():
assert LT(Mt, t, s) == Ms_conds
# The new behavior is to return a tuple of a Matrix and the convergence
# conditions for the matrix as a whole:
assert LT(Mt, t, s, legacy_matrix=False) == (Ms, 1, True)
# With noconds=True the transformed matrix is returned without conditions
# either way:
assert LT(Mt, t, s, noconds=True) == Ms
assert LT(Mt, t, s, legacy_matrix=False, noconds=True) == Ms
@slow
def test_inverse_laplace_transform():
from sympy.functions.special.delta_functions import DiracDelta
ILT = inverse_laplace_transform
a, b, c, d = symbols('a b c d', positive=True)
r = Symbol('r', real=True)
t, z = symbols('t z')
f = Function('f')
def simp_hyp(expr):
return factor_terms(expand_mul(expr)).rewrite(sin)
assert ILT(1, s, t) == DiracDelta(t)
assert ILT(1/s, s, t) == Heaviside(t)
assert ILT(a/(a + s), s, t) == a*exp(-a*t)*Heaviside(t)
assert ILT(s/(a + s), s, t) == -a*exp(-a*t)*Heaviside(t) + DiracDelta(t)
assert ILT((s-a)**(-b), s, t) == t**(b - 1)*exp(a*t)*Heaviside(t)/gamma(b)
assert ILT((a + s)**(-2), s, t) == t*exp(-a*t)*Heaviside(t)
assert ILT((a + s)**(-5), s, t) == t**4*exp(-a*t)*Heaviside(t)/24
assert ILT(a/(a**2 + s**2), s, t) == sin(a*t)*Heaviside(t)
assert ILT(s/(s**2 + a**2), s, t) == cos(a*t)*Heaviside(t)
assert ILT(b/(b**2 + (a + s)**2), s, t) == exp(-a*t)*sin(b*t)*Heaviside(t)
assert ILT(b*s/(b**2 + (a + s)**2), s, t) == \
(-a*sin(b*t) + b*cos(b*t))*exp(-a*t)*Heaviside(t)
assert ILT(exp(-a*s)/s, s, t) == Heaviside(-a + t)
assert ILT(exp(-a*s)/(b + s), s, t) == exp(b*(a - t))*Heaviside(-a + t)
assert ILT((b + s)/(a**2 + (b + s)**2), s, t) == \
exp(-b*t)*cos(a*t)*Heaviside(t)
assert ILT(exp(-a*s)/s**b, s, t) == \
(-a + t)**(b - 1)*Heaviside(-a + t)/gamma(b)
assert ILT(exp(-a*s)/sqrt(s**2 + 1), s, t) == \
Heaviside(-a + t)*besselj(0, a - t)
assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t))
assert ILT(1/(s**2*(s**2 + 1)), s, t) == (t - sin(t))*Heaviside(t)
assert ILT(s**2/(s**2 + 1), s, t) == -sin(t)*Heaviside(t) + DiracDelta(t)
assert ILT(1 - 1/(s**2 + 1), s, t) == -sin(t)*Heaviside(t) + DiracDelta(t)
assert ILT(1/s**2, s, t) == t*Heaviside(t)
assert ILT(1/s**5, s, t) == t**4*Heaviside(t)/24
# Issue #24424
assert ILT((s + 8)/((s + 2)*(s**2 + 2*s + 10)), s, t) ==\
((8*sin(3*t) - 9*cos(3*t))*exp(t) + 9)*exp(-2*t)*Heaviside(t)/15
assert simp_hyp(ILT(a/(s**2 - a**2), s, t)) == sinh(a*t)*Heaviside(t)
assert simp_hyp(ILT(s/(s**2 - a**2), s, t)) == cosh(a*t)*Heaviside(t)
# TODO sinh/cosh shifted come out a mess. also delayed trig is a mess
# TODO should this simplify further?
assert ILT(exp(-a*s)/s**b, s, t) == \
(t - a)**(b - 1)*Heaviside(t - a)/gamma(b)
assert ILT(exp(-a*s)/sqrt(1 + s**2), s, t) == \
Heaviside(t - a)*besselj(0, a - t) # note: besselj(0, x) is even
# XXX ILT turns these branch factor into trig functions ...
assert simplify(ILT(a**b*(s + sqrt(s**2 - a**2))**(-b)/sqrt(s**2 - a**2),
s, t).rewrite(exp)) == \
Heaviside(t)*besseli(b, a*t)
assert ILT(a**b*(s + sqrt(s**2 + a**2))**(-b)/sqrt(s**2 + a**2),
s, t).rewrite(exp) == \
Heaviside(t)*besselj(b, a*t)
assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t))
# TODO can we make erf(t) work?
assert ILT(1/(s**2*(s**2 + 1)),s,t) == (t - sin(t))*Heaviside(t)
assert ILT( (s * eye(2) - Matrix([[1, 0], [0, 2]])).inv(), s, t) ==\
Matrix([[exp(t)*Heaviside(t), 0], [0, exp(2*t)*Heaviside(t)]])
# New tests for rules
assert ILT(b/(s**2-a**2), s, t) == b*sinh(a*t)*Heaviside(t)/a
assert ILT(b*s/(s**2-a**2), s, t) == b*cosh(a*t)*Heaviside(t)
assert ILT(b/(s*(s+a)), s, t) == b*(exp(a*t) - 1)*exp(-a*t)*Heaviside(t)/a
assert ILT(b*s/(s+a)**2, s, t) == b*(-a*t + 1)*exp(-a*t)*Heaviside(t)
assert ILT(c/((s+a)*(s+b)), s, t) ==\
c*(exp(a*t) - exp(b*t))*exp(-t*(a + b))*Heaviside(t)/(a - b)
assert ILT(c*s/((s+a)*(s+b)), s, t) ==\
c*(a*exp(b*t) - b*exp(a*t))*exp(-t*(a + b))*Heaviside(t)/(a - b)
assert ILT(c*s/(d**2*(s+a)**2+b**2), s, t) ==\
c*(-a*d*sin(b*t/d) + b*cos(b*t/d))*exp(-a*t)*Heaviside(t)/(b*d**2)
# Test time_diff rule
assert ILT(s**42*f(s), s, t) ==\
Derivative(InverseLaplaceTransform(f(s), s, t, None), (t, 42))
assert ILT((b*s**2 + d)/(a**2 + s**2)**2, s, t) ==\
(a**3*b*t*cos(a*t) + 4*a**2*b*sin(a*t)*Heaviside(t) +\
a**2*b*sin(a*t) - a*d*t*cos(a*t)*Heaviside(t) +\
d*sin(a*t)*Heaviside(t))/(2*a**3)
# Rules for testing different DiracDelta cases
assert ILT(2, s, t) == 2*DiracDelta(t)
assert ILT(2*exp(3*s) - 5*exp(-7*s), s, t) == \
2*InverseLaplaceTransform(exp(3*s), s, t, None) - 5*DiracDelta(t - 7)
a = cos(sin(7)/2)
assert ILT(a*exp(-3*s), s, t) == a*DiracDelta(t - 3)
assert ILT(exp(2*s), s, t) == InverseLaplaceTransform(exp(2*s), s, t, None)
r = Symbol('r', real=True)
assert ILT(exp(r*s), s, t) == InverseLaplaceTransform(exp(r*s), s, t, None)
# Rules from the previous test_inverse_laplace_transform_delta_cond():
assert ILT(exp(r*s), s, t, noconds=False) ==\
(InverseLaplaceTransform(exp(r*s), s, t, None), True)
# inversion does not exist: verify it doesn't evaluate to DiracDelta
for z in (Symbol('z', extended_real=False),
Symbol('z', imaginary=True, zero=False)):
f = ILT(exp(z*s), s, t, noconds=False)
f = f[0] if isinstance(f, tuple) else f
assert f.func != DiracDelta
# old test for Issue 8514, is not important anymore since this function
# is not solved by integration anymore
assert ILT(1/(a*s**2+b*s+c),s, t) ==\
2*exp(-b*t/(2*a))*sin(t*sqrt(4*a*c - b**2)/(2*a))*\
Heaviside(t)/sqrt(4*a*c - b**2)
@slow
def test_expint():
x = Symbol('x')
a = Symbol('a')
u = Symbol('u', polar=True)
# TODO LT of Si, Shi, Chi is a mess ...
assert laplace_transform(Ci(x), x, s) == (-log(1 + s**2)/2/s, 0, True)
assert laplace_transform(expint(a, x), x, s, simplify=True) == \
(lerchphi(s*exp_polar(I*pi), 1, a), 0, re(a) > S.Zero)
assert laplace_transform(expint(1, x), x, s, simplify=True) == \
(log(s + 1)/s, 0, True)
assert laplace_transform(expint(2, x), x, s, simplify=True) == \
((s - log(s + 1))/s**2, 0, True)
assert inverse_laplace_transform(-log(1 + s**2)/2/s, s, u).expand() == \
Heaviside(u)*Ci(u)
assert inverse_laplace_transform(log(s + 1)/s, s, x).rewrite(expint) == \
Heaviside(x)*E1(x)
assert inverse_laplace_transform((s - log(s + 1))/s**2, s,
x).rewrite(expint).expand() == \
(expint(2, x)*Heaviside(x)).rewrite(Ei).rewrite(expint).expand()
|
39ff57129cf0074086cbbdb6cf8d6839d5046df980b1cb0084cbad7b6ffca1e0 | from sympy.integrals.transforms import (
mellin_transform, inverse_mellin_transform,
fourier_transform, inverse_fourier_transform,
sine_transform, inverse_sine_transform,
cosine_transform, inverse_cosine_transform,
hankel_transform, inverse_hankel_transform,
FourierTransform, SineTransform, CosineTransform, InverseFourierTransform,
InverseSineTransform, InverseCosineTransform, IntegralTransformError)
from sympy.integrals.laplace import (
laplace_transform, inverse_laplace_transform)
from sympy.core.function import Function, expand_mul
from sympy.core import EulerGamma
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.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import re, unpolarify
from sympy.functions.elementary.exponential import exp, exp_polar, log
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import atan, cos, sin, tan
from sympy.functions.special.bessel import besseli, besselj, besselk, bessely
from sympy.functions.special.delta_functions import Heaviside
from sympy.functions.special.error_functions import erf, expint
from sympy.functions.special.gamma_functions import gamma
from sympy.functions.special.hyper import meijerg
from sympy.simplify.gammasimp import gammasimp
from sympy.simplify.hyperexpand import hyperexpand
from sympy.simplify.trigsimp import trigsimp
from sympy.testing.pytest import XFAIL, slow, skip, raises
from sympy.abc import x, s, a, b, c, d
nu, beta, rho = symbols('nu beta rho')
def test_undefined_function():
from sympy.integrals.transforms import MellinTransform
f = Function('f')
assert mellin_transform(f(x), x, s) == MellinTransform(f(x), x, s)
assert mellin_transform(f(x) + exp(-x), x, s) == \
(MellinTransform(f(x), x, s) + gamma(s + 1)/s, (0, oo), True)
def test_free_symbols():
f = Function('f')
assert mellin_transform(f(x), x, s).free_symbols == {s}
assert mellin_transform(f(x)*a, x, s).free_symbols == {s, a}
def test_as_integral():
from sympy.integrals.integrals import Integral
f = Function('f')
assert mellin_transform(f(x), x, s).rewrite('Integral') == \
Integral(x**(s - 1)*f(x), (x, 0, oo))
assert fourier_transform(f(x), x, s).rewrite('Integral') == \
Integral(f(x)*exp(-2*I*pi*s*x), (x, -oo, oo))
assert laplace_transform(f(x), x, s, noconds=True).rewrite('Integral') == \
Integral(f(x)*exp(-s*x), (x, 0, oo))
assert str(2*pi*I*inverse_mellin_transform(f(s), s, x, (a, b)).rewrite('Integral')) \
== "Integral(f(s)/x**s, (s, _c - oo*I, _c + oo*I))"
assert str(2*pi*I*inverse_laplace_transform(f(s), s, x).rewrite('Integral')) == \
"Integral(f(s)*exp(s*x), (s, _c - oo*I, _c + oo*I))"
assert inverse_fourier_transform(f(s), s, x).rewrite('Integral') == \
Integral(f(s)*exp(2*I*pi*s*x), (s, -oo, oo))
# NOTE this is stuck in risch because meijerint cannot handle it
@slow
@XFAIL
def test_mellin_transform_fail():
skip("Risch takes forever.")
MT = mellin_transform
bpos = symbols('b', positive=True)
# bneg = symbols('b', negative=True)
expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2)
# TODO does not work with bneg, argument wrong. Needs changes to matching.
assert MT(expr.subs(b, -bpos), x, s) == \
((-1)**(a + 1)*2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(a + s)
*gamma(1 - a - 2*s)/gamma(1 - s),
(-re(a), -re(a)/2 + S.Half), True)
expr = (sqrt(x + b**2) + b)**a
assert MT(expr.subs(b, -bpos), x, s) == \
(
2**(a + 2*s)*a*bpos**(a + 2*s)*gamma(-a - 2*
s)*gamma(a + s)/gamma(-s + 1),
(-re(a), -re(a)/2), True)
# Test exponent 1:
assert MT(expr.subs({b: -bpos, a: 1}), x, s) == \
(-bpos**(2*s + 1)*gamma(s)*gamma(-s - S.Half)/(2*sqrt(pi)),
(-1, Rational(-1, 2)), True)
def test_mellin_transform():
from sympy.functions.elementary.miscellaneous import (Max, Min)
MT = mellin_transform
bpos = symbols('b', positive=True)
# 8.4.2
assert MT(x**nu*Heaviside(x - 1), x, s) == \
(-1/(nu + s), (-oo, -re(nu)), True)
assert MT(x**nu*Heaviside(1 - x), x, s) == \
(1/(nu + s), (-re(nu), oo), True)
assert MT((1 - x)**(beta - 1)*Heaviside(1 - x), x, s) == \
(gamma(beta)*gamma(s)/gamma(beta + s), (0, oo), re(beta) > 0)
assert MT((x - 1)**(beta - 1)*Heaviside(x - 1), x, s) == \
(gamma(beta)*gamma(1 - beta - s)/gamma(1 - s),
(-oo, 1 - re(beta)), re(beta) > 0)
assert MT((1 + x)**(-rho), x, s) == \
(gamma(s)*gamma(rho - s)/gamma(rho), (0, re(rho)), True)
assert MT(abs(1 - x)**(-rho), x, s) == (
2*sin(pi*rho/2)*gamma(1 - rho)*
cos(pi*(s - rho/2))*gamma(s)*gamma(rho-s)/pi,
(0, re(rho)), re(rho) < 1)
mt = MT((1 - x)**(beta - 1)*Heaviside(1 - x)
+ a*(x - 1)**(beta - 1)*Heaviside(x - 1), x, s)
assert mt[1], mt[2] == ((0, -re(beta) + 1), re(beta) > 0)
assert MT((x**a - b**a)/(x - b), x, s)[0] == \
pi*b**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s)))
assert MT((x**a - bpos**a)/(x - bpos), x, s) == \
(pi*bpos**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s))),
(Max(0, -re(a)), Min(1, 1 - re(a))), True)
expr = (sqrt(x + b**2) + b)**a
assert MT(expr.subs(b, bpos), x, s) == \
(-a*(2*bpos)**(a + 2*s)*gamma(s)*gamma(-a - 2*s)/gamma(-a - s + 1),
(0, -re(a)/2), True)
expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2)
assert MT(expr.subs(b, bpos), x, s) == \
(2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(s)
*gamma(1 - a - 2*s)/gamma(1 - a - s),
(0, -re(a)/2 + S.Half), True)
# 8.4.2
assert MT(exp(-x), x, s) == (gamma(s), (0, oo), True)
assert MT(exp(-1/x), x, s) == (gamma(-s), (-oo, 0), True)
# 8.4.5
assert MT(log(x)**4*Heaviside(1 - x), x, s) == (24/s**5, (0, oo), True)
assert MT(log(x)**3*Heaviside(x - 1), x, s) == (6/s**4, (-oo, 0), True)
assert MT(log(x + 1), x, s) == (pi/(s*sin(pi*s)), (-1, 0), True)
assert MT(log(1/x + 1), x, s) == (pi/(s*sin(pi*s)), (0, 1), True)
assert MT(log(abs(1 - x)), x, s) == (pi/(s*tan(pi*s)), (-1, 0), True)
assert MT(log(abs(1 - 1/x)), x, s) == (pi/(s*tan(pi*s)), (0, 1), True)
# 8.4.14
assert MT(erf(sqrt(x)), x, s) == \
(-gamma(s + S.Half)/(sqrt(pi)*s), (Rational(-1, 2), 0), True)
def test_mellin_transform2():
MT = mellin_transform
# TODO we cannot currently do these (needs summation of 3F2(-1))
# this also implies that they cannot be written as a single g-function
# (although this is possible)
mt = MT(log(x)/(x + 1), x, s)
assert mt[1:] == ((0, 1), True)
assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
mt = MT(log(x)**2/(x + 1), x, s)
assert mt[1:] == ((0, 1), True)
assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
mt = MT(log(x)/(x + 1)**2, x, s)
assert mt[1:] == ((0, 2), True)
assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
@slow
def test_mellin_transform_bessel():
from sympy.functions.elementary.miscellaneous import Max
MT = mellin_transform
# 8.4.19
assert MT(besselj(a, 2*sqrt(x)), x, s) == \
(gamma(a/2 + s)/gamma(a/2 - s + 1), (-re(a)/2, Rational(3, 4)), True)
assert MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s) == \
(2**a*gamma(-2*s + S.Half)*gamma(a/2 + s + S.Half)/(
gamma(-a/2 - s + 1)*gamma(a - 2*s + 1)), (
-re(a)/2 - S.Half, Rational(1, 4)), True)
assert MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s) == \
(2**a*gamma(a/2 + s)*gamma(-2*s + S.Half)/(
gamma(-a/2 - s + S.Half)*gamma(a - 2*s + 1)), (
-re(a)/2, Rational(1, 4)), True)
assert MT(besselj(a, sqrt(x))**2, x, s) == \
(gamma(a + s)*gamma(S.Half - s)
/ (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
(-re(a), S.Half), True)
assert MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s) == \
(gamma(s)*gamma(S.Half - s)
/ (sqrt(pi)*gamma(1 - a - s)*gamma(1 + a - s)),
(0, S.Half), True)
# NOTE: prudnikov gives the strip below as (1/2 - re(a), 1). As far as
# I can see this is wrong (since besselj(z) ~ 1/sqrt(z) for z large)
assert MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s) == \
(gamma(1 - s)*gamma(a + s - S.Half)
/ (sqrt(pi)*gamma(Rational(3, 2) - s)*gamma(a - s + S.Half)),
(S.Half - re(a), S.Half), True)
assert MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s) == \
(4**s*gamma(1 - 2*s)*gamma((a + b)/2 + s)
/ (gamma(1 - s + (b - a)/2)*gamma(1 - s + (a - b)/2)
*gamma( 1 - s + (a + b)/2)),
(-(re(a) + re(b))/2, S.Half), True)
assert MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)[1:] == \
((Max(re(a), -re(a)), S.Half), True)
# Section 8.4.20
assert MT(bessely(a, 2*sqrt(x)), x, s) == \
(-cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)/pi,
(Max(-re(a)/2, re(a)/2), Rational(3, 4)), True)
assert MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s) == \
(-4**s*sin(pi*(a/2 - s))*gamma(S.Half - 2*s)
* gamma((1 - a)/2 + s)*gamma((1 + a)/2 + s)
/ (sqrt(pi)*gamma(1 - s - a/2)*gamma(1 - s + a/2)),
(Max(-(re(a) + 1)/2, (re(a) - 1)/2), Rational(1, 4)), True)
assert MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s) == \
(-4**s*cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)*gamma(S.Half - 2*s)
/ (sqrt(pi)*gamma(S.Half - s - a/2)*gamma(S.Half - s + a/2)),
(Max(-re(a)/2, re(a)/2), Rational(1, 4)), True)
assert MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s) == \
(-cos(pi*s)*gamma(s)*gamma(a + s)*gamma(S.Half - s)
/ (pi**S('3/2')*gamma(1 + a - s)),
(Max(-re(a), 0), S.Half), True)
assert MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s) == \
(-4**s*cos(pi*(a/2 - b/2 + s))*gamma(1 - 2*s)
* gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s)
/ (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
(Max((-re(a) + re(b))/2, (-re(a) - re(b))/2), S.Half), True)
# NOTE bessely(a, sqrt(x))**2 and bessely(a, sqrt(x))*bessely(b, sqrt(x))
# are a mess (no matter what way you look at it ...)
assert MT(bessely(a, sqrt(x))**2, x, s)[1:] == \
((Max(-re(a), 0, re(a)), S.Half), True)
# Section 8.4.22
# TODO we can't do any of these (delicate cancellation)
# Section 8.4.23
assert MT(besselk(a, 2*sqrt(x)), x, s) == \
(gamma(
s - a/2)*gamma(s + a/2)/2, (Max(-re(a)/2, re(a)/2), oo), True)
assert MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk(
a, 2*sqrt(2*sqrt(x))), x, s) == (4**(-s)*gamma(2*s)*
gamma(a/2 + s)/(2*gamma(a/2 - s + 1)), (Max(0, -re(a)/2), oo), True)
# TODO bessely(a, x)*besselk(a, x) is a mess
assert MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s) == \
(gamma(s)*gamma(
a + s)*gamma(-s + S.Half)/(2*sqrt(pi)*gamma(a - s + 1)),
(Max(-re(a), 0), S.Half), True)
assert MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s) == \
(2**(2*s - 1)*gamma(-2*s + 1)*gamma(-a/2 + b/2 + s)* \
gamma(a/2 + b/2 + s)/(gamma(-a/2 + b/2 - s + 1)* \
gamma(a/2 + b/2 - s + 1)), (Max(-re(a)/2 - re(b)/2, \
re(a)/2 - re(b)/2), S.Half), True)
# TODO products of besselk are a mess
mt = MT(exp(-x/2)*besselk(a, x/2), x, s)
mt0 = gammasimp(trigsimp(gammasimp(mt[0].expand(func=True))))
assert mt0 == 2*pi**Rational(3, 2)*cos(pi*s)*gamma(S.Half - s)/(
(cos(2*pi*a) - cos(2*pi*s))*gamma(-a - s + 1)*gamma(a - s + 1))
assert mt[1:] == ((Max(-re(a), re(a)), oo), True)
# TODO exp(x/2)*besselk(a, x/2) [etc] cannot currently be done
# TODO various strange products of special orders
@slow
def test_expint():
from sympy.functions.elementary.miscellaneous import Max
from sympy.functions.special.error_functions import Ci, E1, Si
from sympy.simplify.simplify import simplify
aneg = Symbol('a', negative=True)
u = Symbol('u', polar=True)
assert mellin_transform(E1(x), x, s) == (gamma(s)/s, (0, oo), True)
assert inverse_mellin_transform(gamma(s)/s, s, x,
(0, oo)).rewrite(expint).expand() == E1(x)
assert mellin_transform(expint(a, x), x, s) == \
(gamma(s)/(a + s - 1), (Max(1 - re(a), 0), oo), True)
# XXX IMT has hickups with complicated strips ...
assert simplify(unpolarify(
inverse_mellin_transform(gamma(s)/(aneg + s - 1), s, x,
(1 - aneg, oo)).rewrite(expint).expand(func=True))) == \
expint(aneg, x)
assert mellin_transform(Si(x), x, s) == \
(-2**s*sqrt(pi)*gamma(s/2 + S.Half)/(
2*s*gamma(-s/2 + 1)), (-1, 0), True)
assert inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2)
/(2*s*gamma(-s/2 + 1)), s, x, (-1, 0)) \
== Si(x)
assert mellin_transform(Ci(sqrt(x)), x, s) == \
(-2**(2*s - 1)*sqrt(pi)*gamma(s)/(s*gamma(-s + S.Half)), (0, 1), True)
assert inverse_mellin_transform(
-4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S.Half)),
s, u, (0, 1)).expand() == Ci(sqrt(u))
@slow
def test_inverse_mellin_transform():
from sympy.core.function import expand
from sympy.functions.elementary.miscellaneous import (Max, Min)
from sympy.functions.elementary.trigonometric import cot
from sympy.simplify.powsimp import powsimp
from sympy.simplify.simplify import simplify
IMT = inverse_mellin_transform
assert IMT(gamma(s), s, x, (0, oo)) == exp(-x)
assert IMT(gamma(-s), s, x, (-oo, 0)) == exp(-1/x)
assert simplify(IMT(s/(2*s**2 - 2), s, x, (2, oo))) == \
(x**2 + 1)*Heaviside(1 - x)/(4*x)
# test passing "None"
assert IMT(1/(s**2 - 1), s, x, (-1, None)) == \
-x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)
assert IMT(1/(s**2 - 1), s, x, (None, 1)) == \
-x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)
# test expansion of sums
assert IMT(gamma(s) + gamma(s - 1), s, x, (1, oo)) == (x + 1)*exp(-x)/x
# test factorisation of polys
r = symbols('r', real=True)
assert IMT(1/(s**2 + 1), s, exp(-x), (None, oo)
).subs(x, r).rewrite(sin).simplify() \
== sin(r)*Heaviside(1 - exp(-r))
# test multiplicative substitution
_a, _b = symbols('a b', positive=True)
assert IMT(_b**(-s/_a)*factorial(s/_a)/s, s, x, (0, oo)) == exp(-_b*x**_a)
assert IMT(factorial(_a/_b + s/_b)/(_a + s), s, x, (-_a, oo)) == x**_a*exp(-x**_b)
def simp_pows(expr):
return simplify(powsimp(expand_mul(expr, deep=False), force=True)).replace(exp_polar, exp)
# Now test the inverses of all direct transforms tested above
# Section 8.4.2
nu = symbols('nu', real=True)
assert IMT(-1/(nu + s), s, x, (-oo, None)) == x**nu*Heaviside(x - 1)
assert IMT(1/(nu + s), s, x, (None, oo)) == x**nu*Heaviside(1 - x)
assert simp_pows(IMT(gamma(beta)*gamma(s)/gamma(s + beta), s, x, (0, oo))) \
== (1 - x)**(beta - 1)*Heaviside(1 - x)
assert simp_pows(IMT(gamma(beta)*gamma(1 - beta - s)/gamma(1 - s),
s, x, (-oo, None))) \
== (x - 1)**(beta - 1)*Heaviside(x - 1)
assert simp_pows(IMT(gamma(s)*gamma(rho - s)/gamma(rho), s, x, (0, None))) \
== (1/(x + 1))**rho
assert simp_pows(IMT(d**c*d**(s - 1)*sin(pi*c)
*gamma(s)*gamma(s + c)*gamma(1 - s)*gamma(1 - s - c)/pi,
s, x, (Max(-re(c), 0), Min(1 - re(c), 1)))) \
== (x**c - d**c)/(x - d)
assert simplify(IMT(1/sqrt(pi)*(-c/2)*gamma(s)*gamma((1 - c)/2 - s)
*gamma(-c/2 - s)/gamma(1 - c - s),
s, x, (0, -re(c)/2))) == \
(1 + sqrt(x + 1))**c
assert simplify(IMT(2**(a + 2*s)*b**(a + 2*s - 1)*gamma(s)*gamma(1 - a - 2*s)
/gamma(1 - a - s), s, x, (0, (-re(a) + 1)/2))) == \
b**(a - 1)*(b**2*(sqrt(1 + x/b**2) + 1)**a + x*(sqrt(1 + x/b**2) + 1
)**(a - 1))/(b**2 + x)
assert simplify(IMT(-2**(c + 2*s)*c*b**(c + 2*s)*gamma(s)*gamma(-c - 2*s)
/ gamma(-c - s + 1), s, x, (0, -re(c)/2))) == \
b**c*(sqrt(1 + x/b**2) + 1)**c
# Section 8.4.5
assert IMT(24/s**5, s, x, (0, oo)) == log(x)**4*Heaviside(1 - x)
assert expand(IMT(6/s**4, s, x, (-oo, 0)), force=True) == \
log(x)**3*Heaviside(x - 1)
assert IMT(pi/(s*sin(pi*s)), s, x, (-1, 0)) == log(x + 1)
assert IMT(pi/(s*sin(pi*s/2)), s, x, (-2, 0)) == log(x**2 + 1)
assert IMT(pi/(s*sin(2*pi*s)), s, x, (Rational(-1, 2), 0)) == log(sqrt(x) + 1)
assert IMT(pi/(s*sin(pi*s)), s, x, (0, 1)) == log(1 + 1/x)
# TODO
def mysimp(expr):
from sympy.core.function import expand
from sympy.simplify.powsimp import powsimp
from sympy.simplify.simplify import logcombine
return expand(
powsimp(logcombine(expr, force=True), force=True, deep=True),
force=True).replace(exp_polar, exp)
assert mysimp(mysimp(IMT(pi/(s*tan(pi*s)), s, x, (-1, 0)))) in [
log(1 - x)*Heaviside(1 - x) + log(x - 1)*Heaviside(x - 1),
log(x)*Heaviside(x - 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x +
1)*Heaviside(-x + 1)]
# test passing cot
assert mysimp(IMT(pi*cot(pi*s)/s, s, x, (0, 1))) in [
log(1/x - 1)*Heaviside(1 - x) + log(1 - 1/x)*Heaviside(x - 1),
-log(x)*Heaviside(-x + 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x +
1)*Heaviside(-x + 1), ]
# 8.4.14
assert IMT(-gamma(s + S.Half)/(sqrt(pi)*s), s, x, (Rational(-1, 2), 0)) == \
erf(sqrt(x))
# 8.4.19
assert simplify(IMT(gamma(a/2 + s)/gamma(a/2 - s + 1), s, x, (-re(a)/2, Rational(3, 4)))) \
== besselj(a, 2*sqrt(x))
assert simplify(IMT(2**a*gamma(S.Half - 2*s)*gamma(s + (a + 1)/2)
/ (gamma(1 - s - a/2)*gamma(1 - 2*s + a)),
s, x, (-(re(a) + 1)/2, Rational(1, 4)))) == \
sin(sqrt(x))*besselj(a, sqrt(x))
assert simplify(IMT(2**a*gamma(a/2 + s)*gamma(S.Half - 2*s)
/ (gamma(S.Half - s - a/2)*gamma(1 - 2*s + a)),
s, x, (-re(a)/2, Rational(1, 4)))) == \
cos(sqrt(x))*besselj(a, sqrt(x))
# TODO this comes out as an amazing mess, but simplifies nicely
assert simplify(IMT(gamma(a + s)*gamma(S.Half - s)
/ (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
s, x, (-re(a), S.Half))) == \
besselj(a, sqrt(x))**2
assert simplify(IMT(gamma(s)*gamma(S.Half - s)
/ (sqrt(pi)*gamma(1 - s - a)*gamma(1 + a - s)),
s, x, (0, S.Half))) == \
besselj(-a, sqrt(x))*besselj(a, sqrt(x))
assert simplify(IMT(4**s*gamma(-2*s + 1)*gamma(a/2 + b/2 + s)
/ (gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1)
*gamma(a/2 + b/2 - s + 1)),
s, x, (-(re(a) + re(b))/2, S.Half))) == \
besselj(a, sqrt(x))*besselj(b, sqrt(x))
# Section 8.4.20
# TODO this can be further simplified!
assert simplify(IMT(-2**(2*s)*cos(pi*a/2 - pi*b/2 + pi*s)*gamma(-2*s + 1) *
gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) /
(pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
s, x,
(Max(-re(a)/2 - re(b)/2, -re(a)/2 + re(b)/2), S.Half))) == \
besselj(a, sqrt(x))*-(besselj(-b, sqrt(x)) -
besselj(b, sqrt(x))*cos(pi*b))/sin(pi*b)
# TODO more
# for coverage
assert IMT(pi/cos(pi*s), s, x, (0, S.Half)) == sqrt(x)/(x + 1)
def test_fourier_transform():
from sympy.core.function import (expand, expand_complex, expand_trig)
from sympy.polys.polytools import factor
from sympy.simplify.simplify import simplify
FT = fourier_transform
IFT = inverse_fourier_transform
def simp(x):
return simplify(expand_trig(expand_complex(expand(x))))
def sinc(x):
return sin(pi*x)/(pi*x)
k = symbols('k', real=True)
f = Function("f")
# TODO for this to work with real a, need to expand abs(a*x) to abs(a)*abs(x)
a = symbols('a', positive=True)
b = symbols('b', positive=True)
posk = symbols('posk', positive=True)
# Test unevaluated form
assert fourier_transform(f(x), x, k) == FourierTransform(f(x), x, k)
assert inverse_fourier_transform(
f(k), k, x) == InverseFourierTransform(f(k), k, x)
# basic examples from wikipedia
assert simp(FT(Heaviside(1 - abs(2*a*x)), x, k)) == sinc(k/a)/a
# TODO IFT is a *mess*
assert simp(FT(Heaviside(1 - abs(a*x))*(1 - abs(a*x)), x, k)) == sinc(k/a)**2/a
# TODO IFT
assert factor(FT(exp(-a*x)*Heaviside(x), x, k), extension=I) == \
1/(a + 2*pi*I*k)
# NOTE: the ift comes out in pieces
assert IFT(1/(a + 2*pi*I*x), x, posk,
noconds=False) == (exp(-a*posk), True)
assert IFT(1/(a + 2*pi*I*x), x, -posk,
noconds=False) == (0, True)
assert IFT(1/(a + 2*pi*I*x), x, symbols('k', negative=True),
noconds=False) == (0, True)
# TODO IFT without factoring comes out as meijer g
assert factor(FT(x*exp(-a*x)*Heaviside(x), x, k), extension=I) == \
1/(a + 2*pi*I*k)**2
assert FT(exp(-a*x)*sin(b*x)*Heaviside(x), x, k) == \
b/(b**2 + (a + 2*I*pi*k)**2)
assert FT(exp(-a*x**2), x, k) == sqrt(pi)*exp(-pi**2*k**2/a)/sqrt(a)
assert IFT(sqrt(pi/a)*exp(-(pi*k)**2/a), k, x) == exp(-a*x**2)
assert FT(exp(-a*abs(x)), x, k) == 2*a/(a**2 + 4*pi**2*k**2)
# TODO IFT (comes out as meijer G)
# TODO besselj(n, x), n an integer > 0 actually can be done...
# TODO are there other common transforms (no distributions!)?
def test_sine_transform():
t = symbols("t")
w = symbols("w")
a = symbols("a")
f = Function("f")
# Test unevaluated form
assert sine_transform(f(t), t, w) == SineTransform(f(t), t, w)
assert inverse_sine_transform(
f(w), w, t) == InverseSineTransform(f(w), w, t)
assert sine_transform(1/sqrt(t), t, w) == 1/sqrt(w)
assert inverse_sine_transform(1/sqrt(w), w, t) == 1/sqrt(t)
assert sine_transform((1/sqrt(t))**3, t, w) == 2*sqrt(w)
assert sine_transform(t**(-a), t, w) == 2**(
-a + S.Half)*w**(a - 1)*gamma(-a/2 + 1)/gamma((a + 1)/2)
assert inverse_sine_transform(2**(-a + S(
1)/2)*w**(a - 1)*gamma(-a/2 + 1)/gamma(a/2 + S.Half), w, t) == t**(-a)
assert sine_transform(
exp(-a*t), t, w) == sqrt(2)*w/(sqrt(pi)*(a**2 + w**2))
assert inverse_sine_transform(
sqrt(2)*w/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t)
assert sine_transform(
log(t)/t, t, w) == sqrt(2)*sqrt(pi)*-(log(w**2) + 2*EulerGamma)/4
assert sine_transform(
t*exp(-a*t**2), t, w) == sqrt(2)*w*exp(-w**2/(4*a))/(4*a**Rational(3, 2))
assert inverse_sine_transform(
sqrt(2)*w*exp(-w**2/(4*a))/(4*a**Rational(3, 2)), w, t) == t*exp(-a*t**2)
def test_cosine_transform():
from sympy.functions.special.error_functions import (Ci, Si)
t = symbols("t")
w = symbols("w")
a = symbols("a")
f = Function("f")
# Test unevaluated form
assert cosine_transform(f(t), t, w) == CosineTransform(f(t), t, w)
assert inverse_cosine_transform(
f(w), w, t) == InverseCosineTransform(f(w), w, t)
assert cosine_transform(1/sqrt(t), t, w) == 1/sqrt(w)
assert inverse_cosine_transform(1/sqrt(w), w, t) == 1/sqrt(t)
assert cosine_transform(1/(
a**2 + t**2), t, w) == sqrt(2)*sqrt(pi)*exp(-a*w)/(2*a)
assert cosine_transform(t**(
-a), t, w) == 2**(-a + S.Half)*w**(a - 1)*gamma((-a + 1)/2)/gamma(a/2)
assert inverse_cosine_transform(2**(-a + S(
1)/2)*w**(a - 1)*gamma(-a/2 + S.Half)/gamma(a/2), w, t) == t**(-a)
assert cosine_transform(
exp(-a*t), t, w) == sqrt(2)*a/(sqrt(pi)*(a**2 + w**2))
assert inverse_cosine_transform(
sqrt(2)*a/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t)
assert cosine_transform(exp(-a*sqrt(t))*cos(a*sqrt(
t)), t, w) == a*exp(-a**2/(2*w))/(2*w**Rational(3, 2))
assert cosine_transform(1/(a + t), t, w) == sqrt(2)*(
(-2*Si(a*w) + pi)*sin(a*w)/2 - cos(a*w)*Ci(a*w))/sqrt(pi)
assert inverse_cosine_transform(sqrt(2)*meijerg(((S.Half, 0), ()), (
(S.Half, 0, 0), (S.Half,)), a**2*w**2/4)/(2*pi), w, t) == 1/(a + t)
assert cosine_transform(1/sqrt(a**2 + t**2), t, w) == sqrt(2)*meijerg(
((S.Half,), ()), ((0, 0), (S.Half,)), a**2*w**2/4)/(2*sqrt(pi))
assert inverse_cosine_transform(sqrt(2)*meijerg(((S.Half,), ()), ((0, 0), (S.Half,)), a**2*w**2/4)/(2*sqrt(pi)), w, t) == 1/(t*sqrt(a**2/t**2 + 1))
def test_hankel_transform():
r = Symbol("r")
k = Symbol("k")
nu = Symbol("nu")
m = Symbol("m")
a = symbols("a")
assert hankel_transform(1/r, r, k, 0) == 1/k
assert inverse_hankel_transform(1/k, k, r, 0) == 1/r
assert hankel_transform(
1/r**m, r, k, 0) == 2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2)
assert inverse_hankel_transform(
2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2), k, r, 0) == r**(-m)
assert hankel_transform(1/r**m, r, k, nu) == (
2*2**(-m)*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2))
assert inverse_hankel_transform(2**(-m + 1)*k**(
m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2), k, r, nu) == r**(-m)
assert hankel_transform(r**nu*exp(-a*r), r, k, nu) == \
2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - S(
3)/2)*gamma(nu + Rational(3, 2))/sqrt(pi)
assert inverse_hankel_transform(
2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - Rational(3, 2))*gamma(
nu + Rational(3, 2))/sqrt(pi), k, r, nu) == r**nu*exp(-a*r)
def test_issue_7181():
assert mellin_transform(1/(1 - x), x, s) != None
def test_issue_8882():
# This is the original test.
# from sympy import diff, Integral, integrate
# r = Symbol('r')
# psi = 1/r*sin(r)*exp(-(a0*r))
# h = -1/2*diff(psi, r, r) - 1/r*psi
# f = 4*pi*psi*h*r**2
# assert integrate(f, (r, -oo, 3), meijerg=True).has(Integral) == True
# To save time, only the critical part is included.
F = -a**(-s + 1)*(4 + 1/a**2)**(-s/2)*sqrt(1/a**2)*exp(-s*I*pi)* \
sin(s*atan(sqrt(1/a**2)/2))*gamma(s)
raises(IntegralTransformError, lambda:
inverse_mellin_transform(F, s, x, (-1, oo),
**{'as_meijerg': True, 'needeval': True}))
def test_issue_12591():
x, y = symbols("x y", real=True)
assert fourier_transform(exp(x), x, y) == FourierTransform(exp(x), x, y)
|
45167bafe025b420b3ec2c5fba7f22b39c555549255e36c17c3543a05a2901fd | from sympy.assumptions.refine import refine
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.expr import (ExprBuilder, unchanged, Expr,
UnevaluatedExpr)
from sympy.core.function import (Function, expand, WildFunction,
AppliedUndef, Derivative, diff, Subs)
from sympy.core.mul import Mul
from sympy.core.numbers import (NumberSymbol, E, zoo, oo, Float, I,
Rational, nan, Integer, Number, pi, _illegal)
from sympy.core.power import Pow
from sympy.core.relational import Ge, Lt, Gt, Le
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import Symbol, symbols, Dummy, Wild
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.exponential import exp_polar, exp, log
from sympy.functions.elementary.miscellaneous import sqrt, Max
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import tan, sin, cos
from sympy.functions.special.delta_functions import (Heaviside,
DiracDelta)
from sympy.functions.special.error_functions import Si
from sympy.functions.special.gamma_functions import gamma
from sympy.integrals.integrals import integrate, Integral
from sympy.physics.secondquant import FockState
from sympy.polys.partfrac import apart
from sympy.polys.polytools import factor, cancel, Poly
from sympy.polys.rationaltools import together
from sympy.series.order import O
from sympy.sets.sets import FiniteSet
from sympy.simplify.combsimp import combsimp
from sympy.simplify.gammasimp import gammasimp
from sympy.simplify.powsimp import powsimp
from sympy.simplify.radsimp import collect, radsimp
from sympy.simplify.ratsimp import ratsimp
from sympy.simplify.simplify import simplify, nsimplify
from sympy.simplify.trigsimp import trigsimp
from sympy.tensor.indexed import Indexed
from sympy.physics.units import meter
from sympy.testing.pytest import raises, XFAIL
from sympy.abc import a, b, c, n, t, u, x, y, z
f, g, h = symbols('f,g,h', cls=Function)
class DummyNumber:
"""
Minimal implementation of a number that works with SymPy.
If one has a Number class (e.g. Sage Integer, or some other custom class)
that one wants to work well with SymPy, one has to implement at least the
methods of this class DummyNumber, resp. its subclasses I5 and F1_1.
Basically, one just needs to implement either __int__() or __float__() and
then one needs to make sure that the class works with Python integers and
with itself.
"""
def __radd__(self, a):
if isinstance(a, (int, float)):
return a + self.number
return NotImplemented
def __add__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number + a
return NotImplemented
def __rsub__(self, a):
if isinstance(a, (int, float)):
return a - self.number
return NotImplemented
def __sub__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number - a
return NotImplemented
def __rmul__(self, a):
if isinstance(a, (int, float)):
return a * self.number
return NotImplemented
def __mul__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number * a
return NotImplemented
def __rtruediv__(self, a):
if isinstance(a, (int, float)):
return a / self.number
return NotImplemented
def __truediv__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number / a
return NotImplemented
def __rpow__(self, a):
if isinstance(a, (int, float)):
return a ** self.number
return NotImplemented
def __pow__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number ** a
return NotImplemented
def __pos__(self):
return self.number
def __neg__(self):
return - self.number
class I5(DummyNumber):
number = 5
def __int__(self):
return self.number
class F1_1(DummyNumber):
number = 1.1
def __float__(self):
return self.number
i5 = I5()
f1_1 = F1_1()
# basic SymPy objects
basic_objs = [
Rational(2),
Float("1.3"),
x,
y,
pow(x, y)*y,
]
# all supported objects
all_objs = basic_objs + [
5,
5.5,
i5,
f1_1
]
def dotest(s):
for xo in all_objs:
for yo in all_objs:
s(xo, yo)
return True
def test_basic():
def j(a, b):
x = a
x = +a
x = -a
x = a + b
x = a - b
x = a*b
x = a/b
x = a**b
del x
assert dotest(j)
def test_ibasic():
def s(a, b):
x = a
x += b
x = a
x -= b
x = a
x *= b
x = a
x /= b
assert dotest(s)
class NonBasic:
'''This class represents an object that knows how to implement binary
operations like +, -, etc with Expr but is not a subclass of Basic itself.
The NonExpr subclass below does subclass Basic but not Expr.
For both NonBasic and NonExpr it should be possible for them to override
Expr.__add__ etc because Expr.__add__ should be returning NotImplemented
for non Expr classes. Otherwise Expr.__add__ would create meaningless
objects like Add(Integer(1), FiniteSet(2)) and it wouldn't be possible for
other classes to override these operations when interacting with Expr.
'''
def __add__(self, other):
return SpecialOp('+', self, other)
def __radd__(self, other):
return SpecialOp('+', other, self)
def __sub__(self, other):
return SpecialOp('-', self, other)
def __rsub__(self, other):
return SpecialOp('-', other, self)
def __mul__(self, other):
return SpecialOp('*', self, other)
def __rmul__(self, other):
return SpecialOp('*', other, self)
def __truediv__(self, other):
return SpecialOp('/', self, other)
def __rtruediv__(self, other):
return SpecialOp('/', other, self)
def __floordiv__(self, other):
return SpecialOp('//', self, other)
def __rfloordiv__(self, other):
return SpecialOp('//', other, self)
def __mod__(self, other):
return SpecialOp('%', self, other)
def __rmod__(self, other):
return SpecialOp('%', other, self)
def __divmod__(self, other):
return SpecialOp('divmod', self, other)
def __rdivmod__(self, other):
return SpecialOp('divmod', other, self)
def __pow__(self, other):
return SpecialOp('**', self, other)
def __rpow__(self, other):
return SpecialOp('**', other, self)
def __lt__(self, other):
return SpecialOp('<', self, other)
def __gt__(self, other):
return SpecialOp('>', self, other)
def __le__(self, other):
return SpecialOp('<=', self, other)
def __ge__(self, other):
return SpecialOp('>=', self, other)
class NonExpr(Basic, NonBasic):
'''Like NonBasic above except this is a subclass of Basic but not Expr'''
pass
class SpecialOp():
'''Represents the results of operations with NonBasic and NonExpr'''
def __new__(cls, op, arg1, arg2):
obj = object.__new__(cls)
obj.args = (op, arg1, arg2)
return obj
class NonArithmetic(Basic):
'''Represents a Basic subclass that does not support arithmetic operations'''
pass
def test_cooperative_operations():
'''Tests that Expr uses binary operations cooperatively.
In particular it should be possible for non-Expr classes to override
binary operators like +, - etc when used with Expr instances. This should
work for non-Expr classes whether they are Basic subclasses or not. Also
non-Expr classes that do not define binary operators with Expr should give
TypeError.
'''
# A bunch of instances of Expr subclasses
exprs = [
Expr(),
S.Zero,
S.One,
S.Infinity,
S.NegativeInfinity,
S.ComplexInfinity,
S.Half,
Float(0.5),
Integer(2),
Symbol('x'),
Mul(2, Symbol('x')),
Add(2, Symbol('x')),
Pow(2, Symbol('x')),
]
for e in exprs:
# Test that these classes can override arithmetic operations in
# combination with various Expr types.
for ne in [NonBasic(), NonExpr()]:
results = [
(ne + e, ('+', ne, e)),
(e + ne, ('+', e, ne)),
(ne - e, ('-', ne, e)),
(e - ne, ('-', e, ne)),
(ne * e, ('*', ne, e)),
(e * ne, ('*', e, ne)),
(ne / e, ('/', ne, e)),
(e / ne, ('/', e, ne)),
(ne // e, ('//', ne, e)),
(e // ne, ('//', e, ne)),
(ne % e, ('%', ne, e)),
(e % ne, ('%', e, ne)),
(divmod(ne, e), ('divmod', ne, e)),
(divmod(e, ne), ('divmod', e, ne)),
(ne ** e, ('**', ne, e)),
(e ** ne, ('**', e, ne)),
(e < ne, ('>', ne, e)),
(ne < e, ('<', ne, e)),
(e > ne, ('<', ne, e)),
(ne > e, ('>', ne, e)),
(e <= ne, ('>=', ne, e)),
(ne <= e, ('<=', ne, e)),
(e >= ne, ('<=', ne, e)),
(ne >= e, ('>=', ne, e)),
]
for res, args in results:
assert type(res) is SpecialOp and res.args == args
# These classes do not support binary operators with Expr. Every
# operation should raise in combination with any of the Expr types.
for na in [NonArithmetic(), object()]:
raises(TypeError, lambda : e + na)
raises(TypeError, lambda : na + e)
raises(TypeError, lambda : e - na)
raises(TypeError, lambda : na - e)
raises(TypeError, lambda : e * na)
raises(TypeError, lambda : na * e)
raises(TypeError, lambda : e / na)
raises(TypeError, lambda : na / e)
raises(TypeError, lambda : e // na)
raises(TypeError, lambda : na // e)
raises(TypeError, lambda : e % na)
raises(TypeError, lambda : na % e)
raises(TypeError, lambda : divmod(e, na))
raises(TypeError, lambda : divmod(na, e))
raises(TypeError, lambda : e ** na)
raises(TypeError, lambda : na ** e)
raises(TypeError, lambda : e > na)
raises(TypeError, lambda : na > e)
raises(TypeError, lambda : e < na)
raises(TypeError, lambda : na < e)
raises(TypeError, lambda : e >= na)
raises(TypeError, lambda : na >= e)
raises(TypeError, lambda : e <= na)
raises(TypeError, lambda : na <= e)
def test_relational():
from sympy.core.relational import Lt
assert (pi < 3) is S.false
assert (pi <= 3) is S.false
assert (pi > 3) is S.true
assert (pi >= 3) is S.true
assert (-pi < 3) is S.true
assert (-pi <= 3) is S.true
assert (-pi > 3) is S.false
assert (-pi >= 3) is S.false
r = Symbol('r', real=True)
assert (r - 2 < r - 3) is S.false
assert Lt(x + I, x + I + 2).func == Lt # issue 8288
def test_relational_assumptions():
m1 = Symbol("m1", nonnegative=False)
m2 = Symbol("m2", positive=False)
m3 = Symbol("m3", nonpositive=False)
m4 = Symbol("m4", negative=False)
assert (m1 < 0) == Lt(m1, 0)
assert (m2 <= 0) == Le(m2, 0)
assert (m3 > 0) == Gt(m3, 0)
assert (m4 >= 0) == Ge(m4, 0)
m1 = Symbol("m1", nonnegative=False, real=True)
m2 = Symbol("m2", positive=False, real=True)
m3 = Symbol("m3", nonpositive=False, real=True)
m4 = Symbol("m4", negative=False, real=True)
assert (m1 < 0) is S.true
assert (m2 <= 0) is S.true
assert (m3 > 0) is S.true
assert (m4 >= 0) is S.true
m1 = Symbol("m1", negative=True)
m2 = Symbol("m2", nonpositive=True)
m3 = Symbol("m3", positive=True)
m4 = Symbol("m4", nonnegative=True)
assert (m1 < 0) is S.true
assert (m2 <= 0) is S.true
assert (m3 > 0) is S.true
assert (m4 >= 0) is S.true
m1 = Symbol("m1", negative=False, real=True)
m2 = Symbol("m2", nonpositive=False, real=True)
m3 = Symbol("m3", positive=False, real=True)
m4 = Symbol("m4", nonnegative=False, real=True)
assert (m1 < 0) is S.false
assert (m2 <= 0) is S.false
assert (m3 > 0) is S.false
assert (m4 >= 0) is S.false
# See https://github.com/sympy/sympy/issues/17708
#def test_relational_noncommutative():
# from sympy import Lt, Gt, Le, Ge
# A, B = symbols('A,B', commutative=False)
# assert (A < B) == Lt(A, B)
# assert (A <= B) == Le(A, B)
# assert (A > B) == Gt(A, B)
# assert (A >= B) == Ge(A, B)
def test_basic_nostr():
for obj in basic_objs:
raises(TypeError, lambda: obj + '1')
raises(TypeError, lambda: obj - '1')
if obj == 2:
assert obj * '1' == '11'
else:
raises(TypeError, lambda: obj * '1')
raises(TypeError, lambda: obj / '1')
raises(TypeError, lambda: obj ** '1')
def test_series_expansion_for_uniform_order():
assert (1/x + y + x).series(x, 0, 0) == 1/x + O(1, x)
assert (1/x + y + x).series(x, 0, 1) == 1/x + y + O(x)
assert (1/x + 1 + x).series(x, 0, 0) == 1/x + O(1, x)
assert (1/x + 1 + x).series(x, 0, 1) == 1/x + 1 + O(x)
assert (1/x + x).series(x, 0, 0) == 1/x + O(1, x)
assert (1/x + y + y*x + x).series(x, 0, 0) == 1/x + O(1, x)
assert (1/x + y + y*x + x).series(x, 0, 1) == 1/x + y + O(x)
def test_leadterm():
assert (3 + 2*x**(log(3)/log(2) - 1)).leadterm(x) == (3, 0)
assert (1/x**2 + 1 + x + x**2).leadterm(x)[1] == -2
assert (1/x + 1 + x + x**2).leadterm(x)[1] == -1
assert (x**2 + 1/x).leadterm(x)[1] == -1
assert (1 + x**2).leadterm(x)[1] == 0
assert (x + 1).leadterm(x)[1] == 0
assert (x + x**2).leadterm(x)[1] == 1
assert (x**2).leadterm(x)[1] == 2
def test_as_leading_term():
assert (3 + 2*x**(log(3)/log(2) - 1)).as_leading_term(x) == 3
assert (1/x**2 + 1 + x + x**2).as_leading_term(x) == 1/x**2
assert (1/x + 1 + x + x**2).as_leading_term(x) == 1/x
assert (x**2 + 1/x).as_leading_term(x) == 1/x
assert (1 + x**2).as_leading_term(x) == 1
assert (x + 1).as_leading_term(x) == 1
assert (x + x**2).as_leading_term(x) == x
assert (x**2).as_leading_term(x) == x**2
assert (x + oo).as_leading_term(x) is oo
raises(ValueError, lambda: (x + 1).as_leading_term(1))
# https://github.com/sympy/sympy/issues/21177
e = -3*x + (x + Rational(3, 2) - sqrt(3)*S.ImaginaryUnit/2)**2\
- Rational(3, 2) + 3*sqrt(3)*S.ImaginaryUnit/2
assert e.as_leading_term(x) == \
(12*sqrt(3)*x - 12*S.ImaginaryUnit*x)/(4*sqrt(3) + 12*S.ImaginaryUnit)
# https://github.com/sympy/sympy/issues/21245
e = 1 - x - x**2
d = (1 + sqrt(5))/2
assert e.subs(x, y + 1/d).as_leading_term(y) == \
(-576*sqrt(5)*y - 1280*y)/(256*sqrt(5) + 576)
def test_leadterm2():
assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).leadterm(x) == \
(sin(1 + sin(1)), 0)
def test_leadterm3():
assert (y + z + x).leadterm(x) == (y + z, 0)
def test_as_leading_term2():
assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).as_leading_term(x) == \
sin(1 + sin(1))
def test_as_leading_term3():
assert (2 + pi + x).as_leading_term(x) == 2 + pi
assert (2*x + pi*x + x**2).as_leading_term(x) == 2*x + pi*x
def test_as_leading_term4():
# see issue 6843
n = Symbol('n', integer=True, positive=True)
r = -n**3/(2*n**2 + 4*n + 2) - n**2/(n**2 + 2*n + 1) + \
n**2/(n + 1) - n/(2*n**2 + 4*n + 2) + n/(n*x + x) + 2*n/(n + 1) - \
1 + 1/(n*x + x) + 1/(n + 1) - 1/x
assert r.as_leading_term(x).cancel() == n/2
def test_as_leading_term_stub():
class foo(Function):
pass
assert foo(1/x).as_leading_term(x) == foo(1/x)
assert foo(1).as_leading_term(x) == foo(1)
raises(NotImplementedError, lambda: foo(x).as_leading_term(x))
def test_as_leading_term_deriv_integral():
# related to issue 11313
assert Derivative(x ** 3, x).as_leading_term(x) == 3*x**2
assert Derivative(x ** 3, y).as_leading_term(x) == 0
assert Integral(x ** 3, x).as_leading_term(x) == x**4/4
assert Integral(x ** 3, y).as_leading_term(x) == y*x**3
assert Derivative(exp(x), x).as_leading_term(x) == 1
assert Derivative(log(x), x).as_leading_term(x) == (1/x).as_leading_term(x)
def test_atoms():
assert x.atoms() == {x}
assert (1 + x).atoms() == {x, S.One}
assert (1 + 2*cos(x)).atoms(Symbol) == {x}
assert (1 + 2*cos(x)).atoms(Symbol, Number) == {S.One, S(2), x}
assert (2*(x**(y**x))).atoms() == {S(2), x, y}
assert S.Half.atoms() == {S.Half}
assert S.Half.atoms(Symbol) == set()
assert sin(oo).atoms(oo) == set()
assert Poly(0, x).atoms() == {S.Zero, x}
assert Poly(1, x).atoms() == {S.One, x}
assert Poly(x, x).atoms() == {x}
assert Poly(x, x, y).atoms() == {x, y}
assert Poly(x + y, x, y).atoms() == {x, y}
assert Poly(x + y, x, y, z).atoms() == {x, y, z}
assert Poly(x + y*t, x, y, z).atoms() == {t, x, y, z}
assert (I*pi).atoms(NumberSymbol) == {pi}
assert (I*pi).atoms(NumberSymbol, I) == \
(I*pi).atoms(I, NumberSymbol) == {pi, I}
assert exp(exp(x)).atoms(exp) == {exp(exp(x)), exp(x)}
assert (1 + x*(2 + y) + exp(3 + z)).atoms(Add) == \
{1 + x*(2 + y) + exp(3 + z), 2 + y, 3 + z}
# issue 6132
e = (f(x) + sin(x) + 2)
assert e.atoms(AppliedUndef) == \
{f(x)}
assert e.atoms(AppliedUndef, Function) == \
{f(x), sin(x)}
assert e.atoms(Function) == \
{f(x), sin(x)}
assert e.atoms(AppliedUndef, Number) == \
{f(x), S(2)}
assert e.atoms(Function, Number) == \
{S(2), sin(x), f(x)}
def test_is_polynomial():
k = Symbol('k', nonnegative=True, integer=True)
assert Rational(2).is_polynomial(x, y, z) is True
assert (S.Pi).is_polynomial(x, y, z) is True
assert x.is_polynomial(x) is True
assert x.is_polynomial(y) is True
assert (x**2).is_polynomial(x) is True
assert (x**2).is_polynomial(y) is True
assert (x**(-2)).is_polynomial(x) is False
assert (x**(-2)).is_polynomial(y) is True
assert (2**x).is_polynomial(x) is False
assert (2**x).is_polynomial(y) is True
assert (x**k).is_polynomial(x) is False
assert (x**k).is_polynomial(k) is False
assert (x**x).is_polynomial(x) is False
assert (k**k).is_polynomial(k) is False
assert (k**x).is_polynomial(k) is False
assert (x**(-k)).is_polynomial(x) is False
assert ((2*x)**k).is_polynomial(x) is False
assert (x**2 + 3*x - 8).is_polynomial(x) is True
assert (x**2 + 3*x - 8).is_polynomial(y) is True
assert (x**2 + 3*x - 8).is_polynomial() is True
assert sqrt(x).is_polynomial(x) is False
assert (sqrt(x)**3).is_polynomial(x) is False
assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(x) is True
assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(y) is False
assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial() is True
assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial() is False
assert (
(x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial(x, y) is True
assert (
(x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial(x, y) is False
assert (1/f(x) + 1).is_polynomial(f(x)) is False
def test_is_rational_function():
assert Integer(1).is_rational_function() is True
assert Integer(1).is_rational_function(x) is True
assert Rational(17, 54).is_rational_function() is True
assert Rational(17, 54).is_rational_function(x) is True
assert (12/x).is_rational_function() is True
assert (12/x).is_rational_function(x) is True
assert (x/y).is_rational_function() is True
assert (x/y).is_rational_function(x) is True
assert (x/y).is_rational_function(x, y) is True
assert (x**2 + 1/x/y).is_rational_function() is True
assert (x**2 + 1/x/y).is_rational_function(x) is True
assert (x**2 + 1/x/y).is_rational_function(x, y) is True
assert (sin(y)/x).is_rational_function() is False
assert (sin(y)/x).is_rational_function(y) is False
assert (sin(y)/x).is_rational_function(x) is True
assert (sin(y)/x).is_rational_function(x, y) is False
for i in _illegal:
assert not i.is_rational_function()
for d in (1, x):
assert not (i/d).is_rational_function()
def test_is_meromorphic():
f = a/x**2 + b + x + c*x**2
assert f.is_meromorphic(x, 0) is True
assert f.is_meromorphic(x, 1) is True
assert f.is_meromorphic(x, zoo) is True
g = 3 + 2*x**(log(3)/log(2) - 1)
assert g.is_meromorphic(x, 0) is False
assert g.is_meromorphic(x, 1) is True
assert g.is_meromorphic(x, zoo) is False
n = Symbol('n', integer=True)
e = sin(1/x)**n*x
assert e.is_meromorphic(x, 0) is False
assert e.is_meromorphic(x, 1) is True
assert e.is_meromorphic(x, zoo) is False
e = log(x)**pi
assert e.is_meromorphic(x, 0) is False
assert e.is_meromorphic(x, 1) is False
assert e.is_meromorphic(x, 2) is True
assert e.is_meromorphic(x, zoo) is False
assert (log(x)**a).is_meromorphic(x, 0) is False
assert (log(x)**a).is_meromorphic(x, 1) is False
assert (a**log(x)).is_meromorphic(x, 0) is None
assert (3**log(x)).is_meromorphic(x, 0) is False
assert (3**log(x)).is_meromorphic(x, 1) is True
def test_is_algebraic_expr():
assert sqrt(3).is_algebraic_expr(x) is True
assert sqrt(3).is_algebraic_expr() is True
eq = ((1 + x**2)/(1 - y**2))**(S.One/3)
assert eq.is_algebraic_expr(x) is True
assert eq.is_algebraic_expr(y) is True
assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(x) is True
assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(y) is True
assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr() is True
assert (cos(y)/sqrt(x)).is_algebraic_expr() is False
assert (cos(y)/sqrt(x)).is_algebraic_expr(x) is True
assert (cos(y)/sqrt(x)).is_algebraic_expr(y) is False
assert (cos(y)/sqrt(x)).is_algebraic_expr(x, y) is False
def test_SAGE1():
#see https://github.com/sympy/sympy/issues/3346
class MyInt:
def _sympy_(self):
return Integer(5)
m = MyInt()
e = Rational(2)*m
assert e == 10
raises(TypeError, lambda: Rational(2)*MyInt)
def test_SAGE2():
class MyInt:
def __int__(self):
return 5
assert sympify(MyInt()) == 5
e = Rational(2)*MyInt()
assert e == 10
raises(TypeError, lambda: Rational(2)*MyInt)
def test_SAGE3():
class MySymbol:
def __rmul__(self, other):
return ('mys', other, self)
o = MySymbol()
e = x*o
assert e == ('mys', x, o)
def test_len():
e = x*y
assert len(e.args) == 2
e = x + y + z
assert len(e.args) == 3
def test_doit():
a = Integral(x**2, x)
assert isinstance(a.doit(), Integral) is False
assert isinstance(a.doit(integrals=True), Integral) is False
assert isinstance(a.doit(integrals=False), Integral) is True
assert (2*Integral(x, x)).doit() == x**2
def test_attribute_error():
raises(AttributeError, lambda: x.cos())
raises(AttributeError, lambda: x.sin())
raises(AttributeError, lambda: x.exp())
def test_args():
assert (x*y).args in ((x, y), (y, x))
assert (x + y).args in ((x, y), (y, x))
assert (x*y + 1).args in ((x*y, 1), (1, x*y))
assert sin(x*y).args == (x*y,)
assert sin(x*y).args[0] == x*y
assert (x**y).args == (x, y)
assert (x**y).args[0] == x
assert (x**y).args[1] == y
def test_noncommutative_expand_issue_3757():
A, B, C = symbols('A,B,C', commutative=False)
assert A*B - B*A != 0
assert (A*(A + B)*B).expand() == A**2*B + A*B**2
assert (A*(A + B + C)*B).expand() == A**2*B + A*B**2 + A*C*B
def test_as_numer_denom():
a, b, c = symbols('a, b, c')
assert nan.as_numer_denom() == (nan, 1)
assert oo.as_numer_denom() == (oo, 1)
assert (-oo).as_numer_denom() == (-oo, 1)
assert zoo.as_numer_denom() == (zoo, 1)
assert (-zoo).as_numer_denom() == (zoo, 1)
assert x.as_numer_denom() == (x, 1)
assert (1/x).as_numer_denom() == (1, x)
assert (x/y).as_numer_denom() == (x, y)
assert (x/2).as_numer_denom() == (x, 2)
assert (x*y/z).as_numer_denom() == (x*y, z)
assert (x/(y*z)).as_numer_denom() == (x, y*z)
assert S.Half.as_numer_denom() == (1, 2)
assert (1/y**2).as_numer_denom() == (1, y**2)
assert (x/y**2).as_numer_denom() == (x, y**2)
assert ((x**2 + 1)/y).as_numer_denom() == (x**2 + 1, y)
assert (x*(y + 1)/y**7).as_numer_denom() == (x*(y + 1), y**7)
assert (x**-2).as_numer_denom() == (1, x**2)
assert (a/x + b/2/x + c/3/x).as_numer_denom() == \
(6*a + 3*b + 2*c, 6*x)
assert (a/x + b/2/x + c/3/y).as_numer_denom() == \
(2*c*x + y*(6*a + 3*b), 6*x*y)
assert (a/x + b/2/x + c/.5/x).as_numer_denom() == \
(2*a + b + 4.0*c, 2*x)
# this should take no more than a few seconds
assert int(log(Add(*[Dummy()/i/x for i in range(1, 705)]
).as_numer_denom()[1]/x).n(4)) == 705
for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
assert (i + x/3).as_numer_denom() == \
(x + i, 3)
assert (S.Infinity + x/3 + y/4).as_numer_denom() == \
(4*x + 3*y + S.Infinity, 12)
assert (oo*x + zoo*y).as_numer_denom() == \
(zoo*y + oo*x, 1)
A, B, C = symbols('A,B,C', commutative=False)
assert (A*B*C**-1).as_numer_denom() == (A*B*C**-1, 1)
assert (A*B*C**-1/x).as_numer_denom() == (A*B*C**-1, x)
assert (C**-1*A*B).as_numer_denom() == (C**-1*A*B, 1)
assert (C**-1*A*B/x).as_numer_denom() == (C**-1*A*B, x)
assert ((A*B*C)**-1).as_numer_denom() == ((A*B*C)**-1, 1)
assert ((A*B*C)**-1/x).as_numer_denom() == ((A*B*C)**-1, x)
# the following morphs from Add to Mul during processing
assert Add(0, (x + y)/z/-2, evaluate=False).as_numer_denom(
) == (-x - y, 2*z)
def test_trunc():
import math
x, y = symbols('x y')
assert math.trunc(2) == 2
assert math.trunc(4.57) == 4
assert math.trunc(-5.79) == -5
assert math.trunc(pi) == 3
assert math.trunc(log(7)) == 1
assert math.trunc(exp(5)) == 148
assert math.trunc(cos(pi)) == -1
assert math.trunc(sin(5)) == 0
raises(TypeError, lambda: math.trunc(x))
raises(TypeError, lambda: math.trunc(x + y**2))
raises(TypeError, lambda: math.trunc(oo))
def test_as_independent():
assert S.Zero.as_independent(x, as_Add=True) == (0, 0)
assert S.Zero.as_independent(x, as_Add=False) == (0, 0)
assert (2*x*sin(x) + y + x).as_independent(x) == (y, x + 2*x*sin(x))
assert (2*x*sin(x) + y + x).as_independent(y) == (x + 2*x*sin(x), y)
assert (2*x*sin(x) + y + x).as_independent(x, y) == (0, y + x + 2*x*sin(x))
assert (x*sin(x)*cos(y)).as_independent(x) == (cos(y), x*sin(x))
assert (x*sin(x)*cos(y)).as_independent(y) == (x*sin(x), cos(y))
assert (x*sin(x)*cos(y)).as_independent(x, y) == (1, x*sin(x)*cos(y))
assert (sin(x)).as_independent(x) == (1, sin(x))
assert (sin(x)).as_independent(y) == (sin(x), 1)
assert (2*sin(x)).as_independent(x) == (2, sin(x))
assert (2*sin(x)).as_independent(y) == (2*sin(x), 1)
# issue 4903 = 1766b
n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
assert (n1 + n1*n2).as_independent(n2) == (n1, n1*n2)
assert (n2*n1 + n1*n2).as_independent(n2) == (0, n1*n2 + n2*n1)
assert (n1*n2*n1).as_independent(n2) == (n1, n2*n1)
assert (n1*n2*n1).as_independent(n1) == (1, n1*n2*n1)
assert (3*x).as_independent(x, as_Add=True) == (0, 3*x)
assert (3*x).as_independent(x, as_Add=False) == (3, x)
assert (3 + x).as_independent(x, as_Add=True) == (3, x)
assert (3 + x).as_independent(x, as_Add=False) == (1, 3 + x)
# issue 5479
assert (3*x).as_independent(Symbol) == (3, x)
# issue 5648
assert (n1*x*y).as_independent(x) == (n1*y, x)
assert ((x + n1)*(x - y)).as_independent(x) == (1, (x + n1)*(x - y))
assert ((x + n1)*(x - y)).as_independent(y) == (x + n1, x - y)
assert (DiracDelta(x - n1)*DiracDelta(x - y)).as_independent(x) \
== (1, DiracDelta(x - n1)*DiracDelta(x - y))
assert (x*y*n1*n2*n3).as_independent(n2) == (x*y*n1, n2*n3)
assert (x*y*n1*n2*n3).as_independent(n1) == (x*y, n1*n2*n3)
assert (x*y*n1*n2*n3).as_independent(n3) == (x*y*n1*n2, n3)
assert (DiracDelta(x - n1)*DiracDelta(y - n1)*DiracDelta(x - n2)).as_independent(y) == \
(DiracDelta(x - n1)*DiracDelta(x - n2), DiracDelta(y - n1))
# issue 5784
assert (x + Integral(x, (x, 1, 2))).as_independent(x, strict=True) == \
(Integral(x, (x, 1, 2)), x)
eq = Add(x, -x, 2, -3, evaluate=False)
assert eq.as_independent(x) == (-1, Add(x, -x, evaluate=False))
eq = Mul(x, 1/x, 2, -3, evaluate=False)
assert eq.as_independent(x) == (-6, Mul(x, 1/x, evaluate=False))
assert (x*y).as_independent(z, as_Add=True) == (x*y, 0)
@XFAIL
def test_call_2():
# TODO UndefinedFunction does not subclass Expr
assert (2*f)(x) == 2*f(x)
def test_replace():
e = log(sin(x)) + tan(sin(x**2))
assert e.replace(sin, cos) == log(cos(x)) + tan(cos(x**2))
assert e.replace(
sin, lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
a = Wild('a')
b = Wild('b')
assert e.replace(sin(a), cos(a)) == log(cos(x)) + tan(cos(x**2))
assert e.replace(
sin(a), lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
# test exact
assert (2*x).replace(a*x + b, b - a, exact=True) == 2*x
assert (2*x).replace(a*x + b, b - a) == 2*x
assert (2*x).replace(a*x + b, b - a, exact=False) == 2/x
assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=True) == 2*x
assert (2*x).replace(a*x + b, lambda a, b: b - a) == 2*x
assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=False) == 2/x
g = 2*sin(x**3)
assert g.replace(
lambda expr: expr.is_Number, lambda expr: expr**2) == 4*sin(x**9)
assert cos(x).replace(cos, sin, map=True) == (sin(x), {cos(x): sin(x)})
assert sin(x).replace(cos, sin) == sin(x)
cond, func = lambda x: x.is_Mul, lambda x: 2*x
assert (x*y).replace(cond, func, map=True) == (2*x*y, {x*y: 2*x*y})
assert (x*(1 + x*y)).replace(cond, func, map=True) == \
(2*x*(2*x*y + 1), {x*(2*x*y + 1): 2*x*(2*x*y + 1), x*y: 2*x*y})
assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y, map=True) == \
(sin(x), {sin(x): sin(x)/y})
# if not simultaneous then y*sin(x) -> y*sin(x)/y = sin(x) -> sin(x)/y
assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y,
simultaneous=False) == sin(x)/y
assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e
) == x**2/2 + O(x**3)
assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e,
simultaneous=False) == x**2/2 + O(x**3)
assert (x*(x*y + 3)).replace(lambda x: x.is_Mul, lambda x: 2 + x) == \
x*(x*y + 5) + 2
e = (x*y + 1)*(2*x*y + 1) + 1
assert e.replace(cond, func, map=True) == (
2*((2*x*y + 1)*(4*x*y + 1)) + 1,
{2*x*y: 4*x*y, x*y: 2*x*y, (2*x*y + 1)*(4*x*y + 1):
2*((2*x*y + 1)*(4*x*y + 1))})
assert x.replace(x, y) == y
assert (x + 1).replace(1, 2) == x + 2
# https://groups.google.com/forum/#!topic/sympy/8wCgeC95tz0
n1, n2, n3 = symbols('n1:4', commutative=False)
assert (n1*f(n2)).replace(f, lambda x: x) == n1*n2
assert (n3*f(n2)).replace(f, lambda x: x) == n3*n2
# issue 16725
assert S.Zero.replace(Wild('x'), 1) == 1
# let the user override the default decision of False
assert S.Zero.replace(Wild('x'), 1, exact=True) == 0
def test_find():
expr = (x + y + 2 + sin(3*x))
assert expr.find(lambda u: u.is_Integer) == {S(2), S(3)}
assert expr.find(lambda u: u.is_Symbol) == {x, y}
assert expr.find(lambda u: u.is_Integer, group=True) == {S(2): 1, S(3): 1}
assert expr.find(lambda u: u.is_Symbol, group=True) == {x: 2, y: 1}
assert expr.find(Integer) == {S(2), S(3)}
assert expr.find(Symbol) == {x, y}
assert expr.find(Integer, group=True) == {S(2): 1, S(3): 1}
assert expr.find(Symbol, group=True) == {x: 2, y: 1}
a = Wild('a')
expr = sin(sin(x)) + sin(x) + cos(x) + x
assert expr.find(lambda u: type(u) is sin) == {sin(x), sin(sin(x))}
assert expr.find(
lambda u: type(u) is sin, group=True) == {sin(x): 2, sin(sin(x)): 1}
assert expr.find(sin(a)) == {sin(x), sin(sin(x))}
assert expr.find(sin(a), group=True) == {sin(x): 2, sin(sin(x)): 1}
assert expr.find(sin) == {sin(x), sin(sin(x))}
assert expr.find(sin, group=True) == {sin(x): 2, sin(sin(x)): 1}
def test_count():
expr = (x + y + 2 + sin(3*x))
assert expr.count(lambda u: u.is_Integer) == 2
assert expr.count(lambda u: u.is_Symbol) == 3
assert expr.count(Integer) == 2
assert expr.count(Symbol) == 3
assert expr.count(2) == 1
a = Wild('a')
assert expr.count(sin) == 1
assert expr.count(sin(a)) == 1
assert expr.count(lambda u: type(u) is sin) == 1
assert f(x).count(f(x)) == 1
assert f(x).diff(x).count(f(x)) == 1
assert f(x).diff(x).count(x) == 2
def test_has_basics():
p = Wild('p')
assert sin(x).has(x)
assert sin(x).has(sin)
assert not sin(x).has(y)
assert not sin(x).has(cos)
assert f(x).has(x)
assert f(x).has(f)
assert not f(x).has(y)
assert not f(x).has(g)
assert f(x).diff(x).has(x)
assert f(x).diff(x).has(f)
assert f(x).diff(x).has(Derivative)
assert not f(x).diff(x).has(y)
assert not f(x).diff(x).has(g)
assert not f(x).diff(x).has(sin)
assert (x**2).has(Symbol)
assert not (x**2).has(Wild)
assert (2*p).has(Wild)
assert not x.has()
def test_has_multiple():
f = x**2*y + sin(2**t + log(z))
assert f.has(x)
assert f.has(y)
assert f.has(z)
assert f.has(t)
assert not f.has(u)
assert f.has(x, y, z, t)
assert f.has(x, y, z, t, u)
i = Integer(4400)
assert not i.has(x)
assert (i*x**i).has(x)
assert not (i*y**i).has(x)
assert (i*y**i).has(x, y)
assert not (i*y**i).has(x, z)
def test_has_piecewise():
f = (x*y + 3/y)**(3 + 2)
p = Piecewise((g(x), x < -1), (1, x <= 1), (f, True))
assert p.has(x)
assert p.has(y)
assert not p.has(z)
assert p.has(1)
assert p.has(3)
assert not p.has(4)
assert p.has(f)
assert p.has(g)
assert not p.has(h)
def test_has_iterative():
A, B, C = symbols('A,B,C', commutative=False)
f = x*gamma(x)*sin(x)*exp(x*y)*A*B*C*cos(x*A*B)
assert f.has(x)
assert f.has(x*y)
assert f.has(x*sin(x))
assert not f.has(x*sin(y))
assert f.has(x*A)
assert f.has(x*A*B)
assert not f.has(x*A*C)
assert f.has(x*A*B*C)
assert not f.has(x*A*C*B)
assert f.has(x*sin(x)*A*B*C)
assert not f.has(x*sin(x)*A*C*B)
assert not f.has(x*sin(y)*A*B*C)
assert f.has(x*gamma(x))
assert not f.has(x + sin(x))
assert (x & y & z).has(x & z)
def test_has_integrals():
f = Integral(x**2 + sin(x*y*z), (x, 0, x + y + z))
assert f.has(x + y)
assert f.has(x + z)
assert f.has(y + z)
assert f.has(x*y)
assert f.has(x*z)
assert f.has(y*z)
assert not f.has(2*x + y)
assert not f.has(2*x*y)
def test_has_tuple():
assert Tuple(x, y).has(x)
assert not Tuple(x, y).has(z)
assert Tuple(f(x), g(x)).has(x)
assert not Tuple(f(x), g(x)).has(y)
assert Tuple(f(x), g(x)).has(f)
assert Tuple(f(x), g(x)).has(f(x))
# XXX to be deprecated
#assert not Tuple(f, g).has(x)
#assert Tuple(f, g).has(f)
#assert not Tuple(f, g).has(h)
assert Tuple(True).has(True)
assert Tuple(True).has(S.true)
assert not Tuple(True).has(1)
def test_has_units():
from sympy.physics.units import m, s
assert (x*m/s).has(x)
assert (x*m/s).has(y, z) is False
def test_has_polys():
poly = Poly(x**2 + x*y*sin(z), x, y, t)
assert poly.has(x)
assert poly.has(x, y, z)
assert poly.has(x, y, z, t)
def test_has_physics():
assert FockState((x, y)).has(x)
def test_as_poly_as_expr():
f = x**2 + 2*x*y
assert f.as_poly().as_expr() == f
assert f.as_poly(x, y).as_expr() == f
assert (f + sin(x)).as_poly(x, y) is None
p = Poly(f, x, y)
assert p.as_poly() == p
# https://github.com/sympy/sympy/issues/20610
assert S(2).as_poly() is None
assert sqrt(2).as_poly(extension=True) is None
raises(AttributeError, lambda: Tuple(x, x).as_poly(x))
raises(AttributeError, lambda: Tuple(x ** 2, x, y).as_poly(x))
def test_nonzero():
assert bool(S.Zero) is False
assert bool(S.One) is True
assert bool(x) is True
assert bool(x + y) is True
assert bool(x - x) is False
assert bool(x*y) is True
assert bool(x*1) is True
assert bool(x*0) is False
def test_is_number():
assert Float(3.14).is_number is True
assert Integer(737).is_number is True
assert Rational(3, 2).is_number is True
assert Rational(8).is_number is True
assert x.is_number is False
assert (2*x).is_number is False
assert (x + y).is_number is False
assert log(2).is_number is True
assert log(x).is_number is False
assert (2 + log(2)).is_number is True
assert (8 + log(2)).is_number is True
assert (2 + log(x)).is_number is False
assert (8 + log(2) + x).is_number is False
assert (1 + x**2/x - x).is_number is True
assert Tuple(Integer(1)).is_number is False
assert Add(2, x).is_number is False
assert Mul(3, 4).is_number is True
assert Pow(log(2), 2).is_number is True
assert oo.is_number is True
g = WildFunction('g')
assert g.is_number is False
assert (2*g).is_number is False
assert (x**2).subs(x, 3).is_number is True
# test extensibility of .is_number
# on subinstances of Basic
class A(Basic):
pass
a = A()
assert a.is_number is False
def test_as_coeff_add():
assert S(2).as_coeff_add() == (2, ())
assert S(3.0).as_coeff_add() == (0, (S(3.0),))
assert S(-3.0).as_coeff_add() == (0, (S(-3.0),))
assert x.as_coeff_add() == (0, (x,))
assert (x - 1).as_coeff_add() == (-1, (x,))
assert (x + 1).as_coeff_add() == (1, (x,))
assert (x + 2).as_coeff_add() == (2, (x,))
assert (x + y).as_coeff_add(y) == (x, (y,))
assert (3*x).as_coeff_add(y) == (3*x, ())
# don't do expansion
e = (x + y)**2
assert e.as_coeff_add(y) == (0, (e,))
def test_as_coeff_mul():
assert S(2).as_coeff_mul() == (2, ())
assert S(3.0).as_coeff_mul() == (1, (S(3.0),))
assert S(-3.0).as_coeff_mul() == (-1, (S(3.0),))
assert S(-3.0).as_coeff_mul(rational=False) == (-S(3.0), ())
assert x.as_coeff_mul() == (1, (x,))
assert (-x).as_coeff_mul() == (-1, (x,))
assert (2*x).as_coeff_mul() == (2, (x,))
assert (x*y).as_coeff_mul(y) == (x, (y,))
assert (3 + x).as_coeff_mul() == (1, (3 + x,))
assert (3 + x).as_coeff_mul(y) == (3 + x, ())
# don't do expansion
e = exp(x + y)
assert e.as_coeff_mul(y) == (1, (e,))
e = 2**(x + y)
assert e.as_coeff_mul(y) == (1, (e,))
assert (1.1*x).as_coeff_mul(rational=False) == (1.1, (x,))
assert (1.1*x).as_coeff_mul() == (1, (1.1, x))
assert (-oo*x).as_coeff_mul(rational=True) == (-1, (oo, x))
def test_as_coeff_exponent():
assert (3*x**4).as_coeff_exponent(x) == (3, 4)
assert (2*x**3).as_coeff_exponent(x) == (2, 3)
assert (4*x**2).as_coeff_exponent(x) == (4, 2)
assert (6*x**1).as_coeff_exponent(x) == (6, 1)
assert (3*x**0).as_coeff_exponent(x) == (3, 0)
assert (2*x**0).as_coeff_exponent(x) == (2, 0)
assert (1*x**0).as_coeff_exponent(x) == (1, 0)
assert (0*x**0).as_coeff_exponent(x) == (0, 0)
assert (-1*x**0).as_coeff_exponent(x) == (-1, 0)
assert (-2*x**0).as_coeff_exponent(x) == (-2, 0)
assert (2*x**3 + pi*x**3).as_coeff_exponent(x) == (2 + pi, 3)
assert (x*log(2)/(2*x + pi*x)).as_coeff_exponent(x) == \
(log(2)/(2 + pi), 0)
# issue 4784
D = Derivative
fx = D(f(x), x)
assert fx.as_coeff_exponent(f(x)) == (fx, 0)
def test_extractions():
for base in (2, S.Exp1):
assert Pow(base**x, 3, evaluate=False
).extract_multiplicatively(base**x) == base**(2*x)
assert (base**(5*x)).extract_multiplicatively(
base**(3*x)) == base**(2*x)
assert ((x*y)**3).extract_multiplicatively(x**2 * y) == x*y**2
assert ((x*y)**3).extract_multiplicatively(x**4 * y) is None
assert (2*x).extract_multiplicatively(2) == x
assert (2*x).extract_multiplicatively(3) is None
assert (2*x).extract_multiplicatively(-1) is None
assert (S.Half*x).extract_multiplicatively(3) == x/6
assert (sqrt(x)).extract_multiplicatively(x) is None
assert (sqrt(x)).extract_multiplicatively(1/x) is None
assert x.extract_multiplicatively(-x) is None
assert (-2 - 4*I).extract_multiplicatively(-2) == 1 + 2*I
assert (-2 - 4*I).extract_multiplicatively(3) is None
assert (-2*x - 4*y - 8).extract_multiplicatively(-2) == x + 2*y + 4
assert (-2*x*y - 4*x**2*y).extract_multiplicatively(-2*y) == 2*x**2 + x
assert (2*x*y + 4*x**2*y).extract_multiplicatively(2*y) == 2*x**2 + x
assert (-4*y**2*x).extract_multiplicatively(-3*y) is None
assert (2*x).extract_multiplicatively(1) == 2*x
assert (-oo).extract_multiplicatively(5) is -oo
assert (oo).extract_multiplicatively(5) is oo
assert ((x*y)**3).extract_additively(1) is None
assert (x + 1).extract_additively(x) == 1
assert (x + 1).extract_additively(2*x) is None
assert (x + 1).extract_additively(-x) is None
assert (-x + 1).extract_additively(2*x) is None
assert (2*x + 3).extract_additively(x) == x + 3
assert (2*x + 3).extract_additively(2) == 2*x + 1
assert (2*x + 3).extract_additively(3) == 2*x
assert (2*x + 3).extract_additively(-2) is None
assert (2*x + 3).extract_additively(3*x) is None
assert (2*x + 3).extract_additively(2*x) == 3
assert x.extract_additively(0) == x
assert S(2).extract_additively(x) is None
assert S(2.).extract_additively(2.) is S.Zero
assert S(2.).extract_additively(2) is S.Zero
assert S(2*x + 3).extract_additively(x + 1) == x + 2
assert S(2*x + 3).extract_additively(y + 1) is None
assert S(2*x - 3).extract_additively(x + 1) is None
assert S(2*x - 3).extract_additively(y + z) is None
assert ((a + 1)*x*4 + y).extract_additively(x).expand() == \
4*a*x + 3*x + y
assert ((a + 1)*x*4 + 3*y).extract_additively(x + 2*y).expand() == \
4*a*x + 3*x + y
assert (y*(x + 1)).extract_additively(x + 1) is None
assert ((y + 1)*(x + 1) + 3).extract_additively(x + 1) == \
y*(x + 1) + 3
assert ((x + y)*(x + 1) + x + y + 3).extract_additively(x + y) == \
x*(x + y) + 3
assert (x + y + 2*((x + y)*(x + 1)) + 3).extract_additively((x + y)*(x + 1)) == \
x + y + (x + 1)*(x + y) + 3
assert ((y + 1)*(x + 2*y + 1) + 3).extract_additively(y + 1) == \
(x + 2*y)*(y + 1) + 3
assert (-x - x*I).extract_additively(-x) == -I*x
# extraction does not leave artificats, now
assert (4*x*(y + 1) + y).extract_additively(x) == x*(4*y + 3) + y
n = Symbol("n", integer=True)
assert (Integer(-3)).could_extract_minus_sign() is True
assert (-n*x + x).could_extract_minus_sign() != \
(n*x - x).could_extract_minus_sign()
assert (x - y).could_extract_minus_sign() != \
(-x + y).could_extract_minus_sign()
assert (1 - x - y).could_extract_minus_sign() is True
assert (1 - x + y).could_extract_minus_sign() is False
assert ((-x - x*y)/y).could_extract_minus_sign() is False
assert ((x + x*y)/(-y)).could_extract_minus_sign() is True
assert ((x + x*y)/y).could_extract_minus_sign() is False
assert ((-x - y)/(x + y)).could_extract_minus_sign() is False
class sign_invariant(Function, Expr):
nargs = 1
def __neg__(self):
return self
foo = sign_invariant(x)
assert foo == -foo
assert foo.could_extract_minus_sign() is False
assert (x - y).could_extract_minus_sign() is False
assert (-x + y).could_extract_minus_sign() is True
assert (x - 1).could_extract_minus_sign() is False
assert (1 - x).could_extract_minus_sign() is True
assert (sqrt(2) - 1).could_extract_minus_sign() is True
assert (1 - sqrt(2)).could_extract_minus_sign() is False
# check that result is canonical
eq = (3*x + 15*y).extract_multiplicatively(3)
assert eq.args == eq.func(*eq.args).args
def test_nan_extractions():
for r in (1, 0, I, nan):
assert nan.extract_additively(r) is None
assert nan.extract_multiplicatively(r) is None
def test_coeff():
assert (x + 1).coeff(x + 1) == 1
assert (3*x).coeff(0) == 0
assert (z*(1 + x)*x**2).coeff(1 + x) == z*x**2
assert (1 + 2*x*x**(1 + x)).coeff(x*x**(1 + x)) == 2
assert (1 + 2*x**(y + z)).coeff(x**(y + z)) == 2
assert (3 + 2*x + 4*x**2).coeff(1) == 0
assert (3 + 2*x + 4*x**2).coeff(-1) == 0
assert (3 + 2*x + 4*x**2).coeff(x) == 2
assert (3 + 2*x + 4*x**2).coeff(x**2) == 4
assert (3 + 2*x + 4*x**2).coeff(x**3) == 0
assert (-x/8 + x*y).coeff(x) == Rational(-1, 8) + y
assert (-x/8 + x*y).coeff(-x) == S.One/8
assert (4*x).coeff(2*x) == 0
assert (2*x).coeff(2*x) == 1
assert (-oo*x).coeff(x*oo) == -1
assert (10*x).coeff(x, 0) == 0
assert (10*x).coeff(10*x, 0) == 0
n1, n2 = symbols('n1 n2', commutative=False)
assert (n1*n2).coeff(n1) == 1
assert (n1*n2).coeff(n2) == n1
assert (n1*n2 + x*n1).coeff(n1) == 1 # 1*n1*(n2+x)
assert (n2*n1 + x*n1).coeff(n1) == n2 + x
assert (n2*n1 + x*n1**2).coeff(n1) == n2
assert (n1**x).coeff(n1) == 0
assert (n1*n2 + n2*n1).coeff(n1) == 0
assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=1) == n2
assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=0) == 2
assert (2*f(x) + 3*f(x).diff(x)).coeff(f(x)) == 2
expr = z*(x + y)**2
expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2
assert expr.coeff(z) == (x + y)**2
assert expr.coeff(x + y) == 0
assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2
assert (x + y + 3*z).coeff(1) == x + y
assert (-x + 2*y).coeff(-1) == x
assert (x - 2*y).coeff(-1) == 2*y
assert (3 + 2*x + 4*x**2).coeff(1) == 0
assert (-x - 2*y).coeff(2) == -y
assert (x + sqrt(2)*x).coeff(sqrt(2)) == x
assert (3 + 2*x + 4*x**2).coeff(x) == 2
assert (3 + 2*x + 4*x**2).coeff(x**2) == 4
assert (3 + 2*x + 4*x**2).coeff(x**3) == 0
assert (z*(x + y)**2).coeff((x + y)**2) == z
assert (z*(x + y)**2).coeff(x + y) == 0
assert (2 + 2*x + (x + 1)*y).coeff(x + 1) == y
assert (x + 2*y + 3).coeff(1) == x
assert (x + 2*y + 3).coeff(x, 0) == 2*y + 3
assert (x**2 + 2*y + 3*x).coeff(x**2, 0) == 2*y + 3*x
assert x.coeff(0, 0) == 0
assert x.coeff(x, 0) == 0
n, m, o, l = symbols('n m o l', commutative=False)
assert n.coeff(n) == 1
assert y.coeff(n) == 0
assert (3*n).coeff(n) == 3
assert (2 + n).coeff(x*m) == 0
assert (2*x*n*m).coeff(x) == 2*n*m
assert (2 + n).coeff(x*m*n + y) == 0
assert (2*x*n*m).coeff(3*n) == 0
assert (n*m + m*n*m).coeff(n) == 1 + m
assert (n*m + m*n*m).coeff(n, right=True) == m # = (1 + m)*n*m
assert (n*m + m*n).coeff(n) == 0
assert (n*m + o*m*n).coeff(m*n) == o
assert (n*m + o*m*n).coeff(m*n, right=True) == 1
assert (n*m + n*m*n).coeff(n*m, right=True) == 1 + n # = n*m*(n + 1)
assert (x*y).coeff(z, 0) == x*y
assert (x*n + y*n + z*m).coeff(n) == x + y
assert (n*m + n*o + o*l).coeff(n, right=True) == m + o
assert (x*n*m*n + y*n*m*o + z*l).coeff(m, right=True) == x*n + y*o
assert (x*n*m*n + x*n*m*o + z*l).coeff(m, right=True) == n + o
assert (x*n*m*n + x*n*m*o + z*l).coeff(m) == x*n
def test_coeff2():
r, kappa = symbols('r, kappa')
psi = Function("psi")
g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
g = g.expand()
assert g.coeff(psi(r).diff(r)) == 2/r
def test_coeff2_0():
r, kappa = symbols('r, kappa')
psi = Function("psi")
g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
g = g.expand()
assert g.coeff(psi(r).diff(r, 2)) == 1
def test_coeff_expand():
expr = z*(x + y)**2
expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2
assert expr.coeff(z) == (x + y)**2
assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2
def test_integrate():
assert x.integrate(x) == x**2/2
assert x.integrate((x, 0, 1)) == S.Half
def test_as_base_exp():
assert x.as_base_exp() == (x, S.One)
assert (x*y*z).as_base_exp() == (x*y*z, S.One)
assert (x + y + z).as_base_exp() == (x + y + z, S.One)
assert ((x + y)**z).as_base_exp() == (x + y, z)
def test_issue_4963():
assert hasattr(Mul(x, y), "is_commutative")
assert hasattr(Mul(x, y, evaluate=False), "is_commutative")
assert hasattr(Pow(x, y), "is_commutative")
assert hasattr(Pow(x, y, evaluate=False), "is_commutative")
expr = Mul(Pow(2, 2, evaluate=False), 3, evaluate=False) + 1
assert hasattr(expr, "is_commutative")
def test_action_verbs():
assert nsimplify(1/(exp(3*pi*x/5) + 1)) == \
(1/(exp(3*pi*x/5) + 1)).nsimplify()
assert ratsimp(1/x + 1/y) == (1/x + 1/y).ratsimp()
assert trigsimp(log(x), deep=True) == (log(x)).trigsimp(deep=True)
assert radsimp(1/(2 + sqrt(2))) == (1/(2 + sqrt(2))).radsimp()
assert radsimp(1/(a + b*sqrt(c)), symbolic=False) == \
(1/(a + b*sqrt(c))).radsimp(symbolic=False)
assert powsimp(x**y*x**z*y**z, combine='all') == \
(x**y*x**z*y**z).powsimp(combine='all')
assert (x**t*y**t).powsimp(force=True) == (x*y)**t
assert simplify(x**y*x**z*y**z) == (x**y*x**z*y**z).simplify()
assert together(1/x + 1/y) == (1/x + 1/y).together()
assert collect(a*x**2 + b*x**2 + a*x - b*x + c, x) == \
(a*x**2 + b*x**2 + a*x - b*x + c).collect(x)
assert apart(y/(y + 2)/(y + 1), y) == (y/(y + 2)/(y + 1)).apart(y)
assert combsimp(y/(x + 2)/(x + 1)) == (y/(x + 2)/(x + 1)).combsimp()
assert gammasimp(gamma(x)/gamma(x-5)) == (gamma(x)/gamma(x-5)).gammasimp()
assert factor(x**2 + 5*x + 6) == (x**2 + 5*x + 6).factor()
assert refine(sqrt(x**2)) == sqrt(x**2).refine()
assert cancel((x**2 + 5*x + 6)/(x + 2)) == ((x**2 + 5*x + 6)/(x + 2)).cancel()
def test_as_powers_dict():
assert x.as_powers_dict() == {x: 1}
assert (x**y*z).as_powers_dict() == {x: y, z: 1}
assert Mul(2, 2, evaluate=False).as_powers_dict() == {S(2): S(2)}
assert (x*y).as_powers_dict()[z] == 0
assert (x + y).as_powers_dict()[z] == 0
def test_as_coefficients_dict():
check = [S.One, x, y, x*y, 1]
assert [Add(3*x, 2*x, y, 3).as_coefficients_dict()[i] for i in check] == \
[3, 5, 1, 0, 3]
assert [Add(3*x, 2*x, y, 3, evaluate=False).as_coefficients_dict()[i]
for i in check] == [3, 5, 1, 0, 3]
assert [(3*x*y).as_coefficients_dict()[i] for i in check] == \
[0, 0, 0, 3, 0]
assert [(3.0*x*y).as_coefficients_dict()[i] for i in check] == \
[0, 0, 0, 3.0, 0]
assert (3.0*x*y).as_coefficients_dict()[3.0*x*y] == 0
eq = x*(x + 1)*a + x*b + c/x
assert eq.as_coefficients_dict(x) == {x: b, 1/x: c,
x*(x + 1): a}
assert eq.expand().as_coefficients_dict(x) == {x**2: a, x: a + b, 1/x: c}
assert x.as_coefficients_dict() == {x: S.One}
def test_args_cnc():
A = symbols('A', commutative=False)
assert (x + A).args_cnc() == \
[[], [x + A]]
assert (x + a).args_cnc() == \
[[a + x], []]
assert (x*a).args_cnc() == \
[[a, x], []]
assert (x*y*A*(A + 1)).args_cnc(cset=True) == \
[{x, y}, [A, 1 + A]]
assert Mul(x, x, evaluate=False).args_cnc(cset=True, warn=False) == \
[{x}, []]
assert Mul(x, x**2, evaluate=False).args_cnc(cset=True, warn=False) == \
[{x, x**2}, []]
raises(ValueError, lambda: Mul(x, x, evaluate=False).args_cnc(cset=True))
assert Mul(x, y, x, evaluate=False).args_cnc() == \
[[x, y, x], []]
# always split -1 from leading number
assert (-1.*x).args_cnc() == [[-1, 1.0, x], []]
def test_new_rawargs():
n = Symbol('n', commutative=False)
a = x + n
assert a.is_commutative is False
assert a._new_rawargs(x).is_commutative
assert a._new_rawargs(x, y).is_commutative
assert a._new_rawargs(x, n).is_commutative is False
assert a._new_rawargs(x, y, n).is_commutative is False
m = x*n
assert m.is_commutative is False
assert m._new_rawargs(x).is_commutative
assert m._new_rawargs(n).is_commutative is False
assert m._new_rawargs(x, y).is_commutative
assert m._new_rawargs(x, n).is_commutative is False
assert m._new_rawargs(x, y, n).is_commutative is False
assert m._new_rawargs(x, n, reeval=False).is_commutative is False
assert m._new_rawargs(S.One) is S.One
def test_issue_5226():
assert Add(evaluate=False) == 0
assert Mul(evaluate=False) == 1
assert Mul(x + y, evaluate=False).is_Add
def test_free_symbols():
# free_symbols should return the free symbols of an object
assert S.One.free_symbols == set()
assert x.free_symbols == {x}
assert Integral(x, (x, 1, y)).free_symbols == {y}
assert (-Integral(x, (x, 1, y))).free_symbols == {y}
assert meter.free_symbols == set()
assert (meter**x).free_symbols == {x}
def test_has_free():
assert x.has_free(x)
assert not x.has_free(y)
assert (x + y).has_free(x)
assert (x + y).has_free(*(x, z))
assert f(x).has_free(x)
assert f(x).has_free(f(x))
assert Integral(f(x), (f(x), 1, y)).has_free(y)
assert not Integral(f(x), (f(x), 1, y)).has_free(x)
assert not Integral(f(x), (f(x), 1, y)).has_free(f(x))
# simple extraction
assert (x + 1 + y).has_free(x + 1)
assert not (x + 2 + y).has_free(x + 1)
assert (2 + 3*x*y).has_free(3*x)
raises(TypeError, lambda: x.has_free({x, y}))
s = FiniteSet(1, 2)
assert Piecewise((s, x > 3), (4, True)).has_free(s)
assert not Piecewise((1, x > 3), (4, True)).has_free(s)
# can't make set of these, but fallback will handle
raises(TypeError, lambda: x.has_free(y, []))
def test_has_xfree():
assert (x + 1).has_xfree({x})
assert ((x + 1)**2).has_xfree({x + 1})
assert not (x + y + 1).has_xfree({x + 1})
raises(TypeError, lambda: x.has_xfree(x))
raises(TypeError, lambda: x.has_xfree([x]))
def test_issue_5300():
x = Symbol('x', commutative=False)
assert x*sqrt(2)/sqrt(6) == x*sqrt(3)/3
def test_floordiv():
from sympy.functions.elementary.integers import floor
assert x // y == floor(x / y)
def test_as_coeff_Mul():
assert Integer(3).as_coeff_Mul() == (Integer(3), Integer(1))
assert Rational(3, 4).as_coeff_Mul() == (Rational(3, 4), Integer(1))
assert Float(5.0).as_coeff_Mul() == (Float(5.0), Integer(1))
assert (Integer(3)*x).as_coeff_Mul() == (Integer(3), x)
assert (Rational(3, 4)*x).as_coeff_Mul() == (Rational(3, 4), x)
assert (Float(5.0)*x).as_coeff_Mul() == (Float(5.0), x)
assert (Integer(3)*x*y).as_coeff_Mul() == (Integer(3), x*y)
assert (Rational(3, 4)*x*y).as_coeff_Mul() == (Rational(3, 4), x*y)
assert (Float(5.0)*x*y).as_coeff_Mul() == (Float(5.0), x*y)
assert (x).as_coeff_Mul() == (S.One, x)
assert (x*y).as_coeff_Mul() == (S.One, x*y)
assert (-oo*x).as_coeff_Mul(rational=True) == (-1, oo*x)
def test_as_coeff_Add():
assert Integer(3).as_coeff_Add() == (Integer(3), Integer(0))
assert Rational(3, 4).as_coeff_Add() == (Rational(3, 4), Integer(0))
assert Float(5.0).as_coeff_Add() == (Float(5.0), Integer(0))
assert (Integer(3) + x).as_coeff_Add() == (Integer(3), x)
assert (Rational(3, 4) + x).as_coeff_Add() == (Rational(3, 4), x)
assert (Float(5.0) + x).as_coeff_Add() == (Float(5.0), x)
assert (Float(5.0) + x).as_coeff_Add(rational=True) == (0, Float(5.0) + x)
assert (Integer(3) + x + y).as_coeff_Add() == (Integer(3), x + y)
assert (Rational(3, 4) + x + y).as_coeff_Add() == (Rational(3, 4), x + y)
assert (Float(5.0) + x + y).as_coeff_Add() == (Float(5.0), x + y)
assert (x).as_coeff_Add() == (S.Zero, x)
assert (x*y).as_coeff_Add() == (S.Zero, x*y)
def test_expr_sorting():
exprs = [1/x**2, 1/x, sqrt(sqrt(x)), sqrt(x), x, sqrt(x)**3, x**2]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [x, 2*x, 2*x**2, 2*x**3, x**n, 2*x**n, sin(x), sin(x)**n,
sin(x**2), cos(x), cos(x**2), tan(x)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [x + 1, x**2 + x + 1, x**3 + x**2 + x + 1]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [S(4), x - 3*I/2, x + 3*I/2, x - 4*I + 1, x + 4*I + 1]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [f(x), g(x), exp(x), sin(x), cos(x), factorial(x)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [Tuple(x, y), Tuple(x, z), Tuple(x, y, z)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [[3], [1, 2]]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [[1, 2], [2, 3]]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [[1, 2], [1, 2, 3]]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [{x: -y}, {x: y}]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [{1}, {1, 2}]
assert sorted(exprs, key=default_sort_key) == exprs
a, b = exprs = [Dummy('x'), Dummy('x')]
assert sorted([b, a], key=default_sort_key) == exprs
def test_as_ordered_factors():
assert x.as_ordered_factors() == [x]
assert (2*x*x**n*sin(x)*cos(x)).as_ordered_factors() \
== [Integer(2), x, x**n, sin(x), cos(x)]
args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
expr = Mul(*args)
assert expr.as_ordered_factors() == args
A, B = symbols('A,B', commutative=False)
assert (A*B).as_ordered_factors() == [A, B]
assert (B*A).as_ordered_factors() == [B, A]
def test_as_ordered_terms():
assert x.as_ordered_terms() == [x]
assert (sin(x)**2*cos(x) + sin(x)*cos(x)**2 + 1).as_ordered_terms() \
== [sin(x)**2*cos(x), sin(x)*cos(x)**2, 1]
args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
expr = Add(*args)
assert expr.as_ordered_terms() == args
assert (1 + 4*sqrt(3)*pi*x).as_ordered_terms() == [4*pi*x*sqrt(3), 1]
assert ( 2 + 3*I).as_ordered_terms() == [2, 3*I]
assert (-2 + 3*I).as_ordered_terms() == [-2, 3*I]
assert ( 2 - 3*I).as_ordered_terms() == [2, -3*I]
assert (-2 - 3*I).as_ordered_terms() == [-2, -3*I]
assert ( 4 + 3*I).as_ordered_terms() == [4, 3*I]
assert (-4 + 3*I).as_ordered_terms() == [-4, 3*I]
assert ( 4 - 3*I).as_ordered_terms() == [4, -3*I]
assert (-4 - 3*I).as_ordered_terms() == [-4, -3*I]
e = x**2*y**2 + x*y**4 + y + 2
assert e.as_ordered_terms(order="lex") == [x**2*y**2, x*y**4, y, 2]
assert e.as_ordered_terms(order="grlex") == [x*y**4, x**2*y**2, y, 2]
assert e.as_ordered_terms(order="rev-lex") == [2, y, x*y**4, x**2*y**2]
assert e.as_ordered_terms(order="rev-grlex") == [2, y, x**2*y**2, x*y**4]
k = symbols('k')
assert k.as_ordered_terms(data=True) == ([(k, ((1.0, 0.0), (1,), ()))], [k])
def test_sort_key_atomic_expr():
from sympy.physics.units import m, s
assert sorted([-m, s], key=lambda arg: arg.sort_key()) == [-m, s]
def test_eval_interval():
assert exp(x)._eval_interval(*Tuple(x, 0, 1)) == exp(1) - exp(0)
# issue 4199
a = x/y
raises(NotImplementedError, lambda: a._eval_interval(x, S.Zero, oo)._eval_interval(y, oo, S.Zero))
raises(NotImplementedError, lambda: a._eval_interval(x, S.Zero, oo)._eval_interval(y, S.Zero, oo))
a = x - y
raises(NotImplementedError, lambda: a._eval_interval(x, S.One, oo)._eval_interval(y, oo, S.One))
raises(ValueError, lambda: x._eval_interval(x, None, None))
a = -y*Heaviside(x - y)
assert a._eval_interval(x, -oo, oo) == -y
assert a._eval_interval(x, oo, -oo) == y
def test_eval_interval_zoo():
# Test that limit is used when zoo is returned
assert Si(1/x)._eval_interval(x, S.Zero, S.One) == -pi/2 + Si(1)
def test_primitive():
assert (3*(x + 1)**2).primitive() == (3, (x + 1)**2)
assert (6*x + 2).primitive() == (2, 3*x + 1)
assert (x/2 + 3).primitive() == (S.Half, x + 6)
eq = (6*x + 2)*(x/2 + 3)
assert eq.primitive()[0] == 1
eq = (2 + 2*x)**2
assert eq.primitive()[0] == 1
assert (4.0*x).primitive() == (1, 4.0*x)
assert (4.0*x + y/2).primitive() == (S.Half, 8.0*x + y)
assert (-2*x).primitive() == (2, -x)
assert Add(5*z/7, 0.5*x, 3*y/2, evaluate=False).primitive() == \
(S.One/14, 7.0*x + 21*y + 10*z)
for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
assert (i + x/3).primitive() == \
(S.One/3, i + x)
assert (S.Infinity + 2*x/3 + 4*y/7).primitive() == \
(S.One/21, 14*x + 12*y + oo)
assert S.Zero.primitive() == (S.One, S.Zero)
def test_issue_5843():
a = 1 + x
assert (2*a).extract_multiplicatively(a) == 2
assert (4*a).extract_multiplicatively(2*a) == 2
assert ((3*a)*(2*a)).extract_multiplicatively(a) == 6*a
def test_is_constant():
from sympy.solvers.solvers import checksol
assert Sum(x, (x, 1, 10)).is_constant() is True
assert Sum(x, (x, 1, n)).is_constant() is False
assert Sum(x, (x, 1, n)).is_constant(y) is True
assert Sum(x, (x, 1, n)).is_constant(n) is False
assert Sum(x, (x, 1, n)).is_constant(x) is True
eq = a*cos(x)**2 + a*sin(x)**2 - a
assert eq.is_constant() is True
assert eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
assert x.is_constant() is False
assert x.is_constant(y) is True
assert log(x/y).is_constant() is False
assert checksol(x, x, Sum(x, (x, 1, n))) is False
assert checksol(x, x, Sum(x, (x, 1, n))) is False
assert f(1).is_constant
assert checksol(x, x, f(x)) is False
assert Pow(x, S.Zero, evaluate=False).is_constant() is True # == 1
assert Pow(S.Zero, x, evaluate=False).is_constant() is False # == 0 or 1
assert (2**x).is_constant() is False
assert Pow(S(2), S(3), evaluate=False).is_constant() is True
z1, z2 = symbols('z1 z2', zero=True)
assert (z1 + 2*z2).is_constant() is True
assert meter.is_constant() is True
assert (3*meter).is_constant() is True
assert (x*meter).is_constant() is False
def test_equals():
assert (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2).equals(0)
assert (x**2 - 1).equals((x + 1)*(x - 1))
assert (cos(x)**2 + sin(x)**2).equals(1)
assert (a*cos(x)**2 + a*sin(x)**2).equals(a)
r = sqrt(2)
assert (-1/(r + r*x) + 1/r/(1 + x)).equals(0)
assert factorial(x + 1).equals((x + 1)*factorial(x))
assert sqrt(3).equals(2*sqrt(3)) is False
assert (sqrt(5)*sqrt(3)).equals(sqrt(3)) is False
assert (sqrt(5) + sqrt(3)).equals(0) is False
assert (sqrt(5) + pi).equals(0) is False
assert meter.equals(0) is False
assert (3*meter**2).equals(0) is False
eq = -(-1)**(S(3)/4)*6**(S.One/4) + (-6)**(S.One/4)*I
if eq != 0: # if canonicalization makes this zero, skip the test
assert eq.equals(0)
assert sqrt(x).equals(0) is False
# from integrate(x*sqrt(1 + 2*x), x);
# diff is zero only when assumptions allow
i = 2*sqrt(2)*x**(S(5)/2)*(1 + 1/(2*x))**(S(5)/2)/5 + \
2*sqrt(2)*x**(S(3)/2)*(1 + 1/(2*x))**(S(5)/2)/(-6 - 3/x)
ans = sqrt(2*x + 1)*(6*x**2 + x - 1)/15
diff = i - ans
assert diff.equals(0) is None # should be False, but previously this was False due to wrong intermediate result
assert diff.subs(x, Rational(-1, 2)/2) == 7*sqrt(2)/120
# there are regions for x for which the expression is True, for
# example, when x < -1/2 or x > 0 the expression is zero
p = Symbol('p', positive=True)
assert diff.subs(x, p).equals(0) is True
assert diff.subs(x, -1).equals(0) is True
# prove via minimal_polynomial or self-consistency
eq = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3))
assert eq.equals(0)
q = 3**Rational(1, 3) + 3
p = expand(q**3)**Rational(1, 3)
assert (p - q).equals(0)
# issue 6829
# eq = q*x + q/4 + x**4 + x**3 + 2*x**2 - S.One/3
# z = eq.subs(x, solve(eq, x)[0])
q = symbols('q')
z = (q*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 -
S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4) + q/4 + (-sqrt(-2*(-(q
- S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q
- S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/6)/2 - S.One/4)**4 + (-sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q -
S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/6)/2 - S.One/4)**3 + 2*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q -
S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/6)/2 - S.One/4)**2 - Rational(1, 3))
assert z.equals(0)
def test_random():
from sympy.functions.combinatorial.numbers import lucas
from sympy.simplify.simplify import posify
assert posify(x)[0]._random() is not None
assert lucas(n)._random(2, -2, 0, -1, 1) is None
# issue 8662
assert Piecewise((Max(x, y), z))._random() is None
def test_round():
assert str(Float('0.1249999').round(2)) == '0.12'
d20 = 12345678901234567890
ans = S(d20).round(2)
assert ans.is_Integer and ans == d20
ans = S(d20).round(-2)
assert ans.is_Integer and ans == 12345678901234567900
assert str(S('1/7').round(4)) == '0.1429'
assert str(S('.[12345]').round(4)) == '0.1235'
assert str(S('.1349').round(2)) == '0.13'
n = S(12345)
ans = n.round()
assert ans.is_Integer
assert ans == n
ans = n.round(1)
assert ans.is_Integer
assert ans == n
ans = n.round(4)
assert ans.is_Integer
assert ans == n
assert n.round(-1) == 12340
r = Float(str(n)).round(-4)
assert r == 10000.0
assert n.round(-5) == 0
assert str((pi + sqrt(2)).round(2)) == '4.56'
assert (10*(pi + sqrt(2))).round(-1) == 50.0
raises(TypeError, lambda: round(x + 2, 2))
assert str(S(2.3).round(1)) == '2.3'
# rounding in SymPy (as in Decimal) should be
# exact for the given precision; we check here
# that when a 5 follows the last digit that
# the rounded digit will be even.
for i in range(-99, 100):
# construct a decimal that ends in 5, e.g. 123 -> 0.1235
s = str(abs(i))
p = len(s) # we are going to round to the last digit of i
n = '0.%s5' % s # put a 5 after i's digits
j = p + 2 # 2 for '0.'
if i < 0: # 1 for '-'
j += 1
n = '-' + n
v = str(Float(n).round(p))[:j] # pertinent digits
if v.endswith('.'):
continue # it ends with 0 which is even
L = int(v[-1]) # last digit
assert L % 2 == 0, (n, '->', v)
assert (Float(.3, 3) + 2*pi).round() == 7
assert (Float(.3, 3) + 2*pi*100).round() == 629
assert (pi + 2*E*I).round() == 3 + 5*I
# don't let request for extra precision give more than
# what is known (in this case, only 3 digits)
assert str((Float(.03, 3) + 2*pi/100).round(5)) == '0.0928'
assert str((Float(.03, 3) + 2*pi/100).round(4)) == '0.0928'
assert S.Zero.round() == 0
a = (Add(1, Float('1.' + '9'*27, ''), evaluate=0))
assert a.round(10) == Float('3.000000000000000000000000000', '')
assert a.round(25) == Float('3.000000000000000000000000000', '')
assert a.round(26) == Float('3.000000000000000000000000000', '')
assert a.round(27) == Float('2.999999999999999999999999999', '')
assert a.round(30) == Float('2.999999999999999999999999999', '')
# XXX: Should round set the precision of the result?
# The previous version of the tests above is this but they only pass
# because Floats with unequal precision compare equal:
#
# assert a.round(10) == Float('3.0000000000', '')
# assert a.round(25) == Float('3.0000000000000000000000000', '')
# assert a.round(26) == Float('3.00000000000000000000000000', '')
# assert a.round(27) == Float('2.999999999999999999999999999', '')
# assert a.round(30) == Float('2.999999999999999999999999999', '')
raises(TypeError, lambda: x.round())
raises(TypeError, lambda: f(1).round())
# exact magnitude of 10
assert str(S.One.round()) == '1'
assert str(S(100).round()) == '100'
# applied to real and imaginary portions
assert (2*pi + E*I).round() == 6 + 3*I
assert (2*pi + I/10).round() == 6
assert (pi/10 + 2*I).round() == 2*I
# the lhs re and im parts are Float with dps of 2
# and those on the right have dps of 15 so they won't compare
# equal unless we use string or compare components (which will
# then coerce the floats to the same precision) or re-create
# the floats
assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I'
assert str((pi/10 + E*I).round(2).as_real_imag()) == '(0.31, 2.72)'
assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I'
# issue 6914
assert (I**(I + 3)).round(3) == Float('-0.208', '')*I
# issue 8720
assert S(-123.6).round() == -124
assert S(-1.5).round() == -2
assert S(-100.5).round() == -100
assert S(-1.5 - 10.5*I).round() == -2 - 10*I
# issue 7961
assert str(S(0.006).round(2)) == '0.01'
assert str(S(0.00106).round(4)) == '0.0011'
# issue 8147
assert S.NaN.round() is S.NaN
assert S.Infinity.round() is S.Infinity
assert S.NegativeInfinity.round() is S.NegativeInfinity
assert S.ComplexInfinity.round() is S.ComplexInfinity
# check that types match
for i in range(2):
fi = float(i)
# 2 args
assert all(type(round(i, p)) is int for p in (-1, 0, 1))
assert all(S(i).round(p).is_Integer for p in (-1, 0, 1))
assert all(type(round(fi, p)) is float for p in (-1, 0, 1))
assert all(S(fi).round(p).is_Float for p in (-1, 0, 1))
# 1 arg (p is None)
assert type(round(i)) is int
assert S(i).round().is_Integer
assert type(round(fi)) is int
assert S(fi).round().is_Integer
def test_held_expression_UnevaluatedExpr():
x = symbols("x")
he = UnevaluatedExpr(1/x)
e1 = x*he
assert isinstance(e1, Mul)
assert e1.args == (x, he)
assert e1.doit() == 1
assert UnevaluatedExpr(Derivative(x, x)).doit(deep=False
) == Derivative(x, x)
assert UnevaluatedExpr(Derivative(x, x)).doit() == 1
xx = Mul(x, x, evaluate=False)
assert xx != x**2
ue2 = UnevaluatedExpr(xx)
assert isinstance(ue2, UnevaluatedExpr)
assert ue2.args == (xx,)
assert ue2.doit() == x**2
assert ue2.doit(deep=False) == xx
x2 = UnevaluatedExpr(2)*2
assert type(x2) is Mul
assert x2.args == (2, UnevaluatedExpr(2))
def test_round_exception_nostr():
# Don't use the string form of the expression in the round exception, as
# it's too slow
s = Symbol('bad')
try:
s.round()
except TypeError as e:
assert 'bad' not in str(e)
else:
# Did not raise
raise AssertionError("Did not raise")
def test_extract_branch_factor():
assert exp_polar(2.0*I*pi).extract_branch_factor() == (1, 1)
def test_identity_removal():
assert Add.make_args(x + 0) == (x,)
assert Mul.make_args(x*1) == (x,)
def test_float_0():
assert Float(0.0) + 1 == Float(1.0)
@XFAIL
def test_float_0_fail():
assert Float(0.0)*x == Float(0.0)
assert (x + Float(0.0)).is_Add
def test_issue_6325():
ans = (b**2 + z**2 - (b*(a + b*t) + z*(c + t*z))**2/(
(a + b*t)**2 + (c + t*z)**2))/sqrt((a + b*t)**2 + (c + t*z)**2)
e = sqrt((a + b*t)**2 + (c + z*t)**2)
assert diff(e, t, 2) == ans
assert e.diff(t, 2) == ans
assert diff(e, t, 2, simplify=False) != ans
def test_issue_7426():
f1 = a % c
f2 = x % z
assert f1.equals(f2) is None
def test_issue_11122():
x = Symbol('x', extended_positive=False)
assert unchanged(Gt, x, 0) # (x > 0)
# (x > 0) should remain unevaluated after PR #16956
x = Symbol('x', positive=False, real=True)
assert (x > 0) is S.false
def test_issue_10651():
x = Symbol('x', real=True)
e1 = (-1 + x)/(1 - x)
e3 = (4*x**2 - 4)/((1 - x)*(1 + x))
e4 = 1/(cos(x)**2) - (tan(x))**2
x = Symbol('x', positive=True)
e5 = (1 + x)/x
assert e1.is_constant() is None
assert e3.is_constant() is None
assert e4.is_constant() is None
assert e5.is_constant() is False
def test_issue_10161():
x = symbols('x', real=True)
assert x*abs(x)*abs(x) == x**3
def test_issue_10755():
x = symbols('x')
raises(TypeError, lambda: int(log(x)))
raises(TypeError, lambda: log(x).round(2))
def test_issue_11877():
x = symbols('x')
assert integrate(log(S.Half - x), (x, 0, S.Half)) == Rational(-1, 2) -log(2)/2
def test_normal():
x = symbols('x')
e = Mul(S.Half, 1 + x, evaluate=False)
assert e.normal() == e
def test_expr():
x = symbols('x')
raises(TypeError, lambda: tan(x).series(x, 2, oo, "+"))
def test_ExprBuilder():
eb = ExprBuilder(Mul)
eb.args.extend([x, x])
assert eb.build() == x**2
def test_issue_22020():
from sympy.parsing.sympy_parser import parse_expr
x = parse_expr("log((2*V/3-V)/C)/-(R+r)*C")
y = parse_expr("log((2*V/3-V)/C)/-(R+r)*2")
assert x.equals(y) is False
def test_non_string_equality():
# Expressions should not compare equal to strings
x = symbols('x')
one = sympify(1)
assert (x == 'x') is False
assert (x != 'x') is True
assert (one == '1') is False
assert (one != '1') is True
assert (x + 1 == 'x + 1') is False
assert (x + 1 != 'x + 1') is True
# Make sure == doesn't try to convert the resulting expression to a string
# (e.g., by calling sympify() instead of _sympify())
class BadRepr:
def __repr__(self):
raise RuntimeError
assert (x == BadRepr()) is False
assert (x != BadRepr()) is True
def test_21494():
from sympy.testing.pytest import warns_deprecated_sympy
with warns_deprecated_sympy():
assert x.expr_free_symbols == {x}
with warns_deprecated_sympy():
assert Basic().expr_free_symbols == set()
with warns_deprecated_sympy():
assert S(2).expr_free_symbols == {S(2)}
with warns_deprecated_sympy():
assert Indexed("A", x).expr_free_symbols == {Indexed("A", x)}
with warns_deprecated_sympy():
assert Subs(x, x, 0).expr_free_symbols == set()
def test_Expr__eq__iterable_handling():
assert x != range(3)
def test_format():
assert '{:1.2f}'.format(S.Zero) == '0.00'
assert '{:+3.0f}'.format(S(3)) == ' +3'
assert '{:23.20f}'.format(pi) == ' 3.14159265358979323846'
assert '{:50.48f}'.format(exp(sin(1))) == '2.319776824715853173956590377503266813254904772376'
|
21e192f1d5a0da733c2e770afbf5c7e32b82ca80634881e07a60c61298951277 | """Test whether all elements of cls.args are instances of Basic. """
# NOTE: keep tests sorted by (module, class name) key. If a class can't
# be instantiated, add it here anyway with @SKIP("abstract class) (see
# e.g. Function).
import os
import re
from sympy.assumptions.ask import Q
from sympy.core.basic import Basic
from sympy.core.function import (Function, Lambda)
from sympy.core.numbers import (Rational, oo, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin
from sympy.testing.pytest import SKIP
a, b, c, x, y, z = symbols('a,b,c,x,y,z')
whitelist = [
"sympy.assumptions.predicates", # tested by test_predicates()
"sympy.assumptions.relation.equality", # tested by test_predicates()
]
def test_all_classes_are_tested():
this = os.path.split(__file__)[0]
path = os.path.join(this, os.pardir, os.pardir)
sympy_path = os.path.abspath(path)
prefix = os.path.split(sympy_path)[0] + os.sep
re_cls = re.compile(r"^class ([A-Za-z][A-Za-z0-9_]*)\s*\(", re.MULTILINE)
modules = {}
for root, dirs, files in os.walk(sympy_path):
module = root.replace(prefix, "").replace(os.sep, ".")
for file in files:
if file.startswith(("_", "test_", "bench_")):
continue
if not file.endswith(".py"):
continue
with open(os.path.join(root, file), encoding='utf-8') as f:
text = f.read()
submodule = module + '.' + file[:-3]
if any(submodule.startswith(wpath) for wpath in whitelist):
continue
names = re_cls.findall(text)
if not names:
continue
try:
mod = __import__(submodule, fromlist=names)
except ImportError:
continue
def is_Basic(name):
cls = getattr(mod, name)
if hasattr(cls, '_sympy_deprecated_func'):
cls = cls._sympy_deprecated_func
if not isinstance(cls, type):
# check instance of singleton class with same name
cls = type(cls)
return issubclass(cls, Basic)
names = list(filter(is_Basic, names))
if names:
modules[submodule] = names
ns = globals()
failed = []
for module, names in modules.items():
mod = module.replace('.', '__')
for name in names:
test = 'test_' + mod + '__' + name
if test not in ns:
failed.append(module + '.' + name)
assert not failed, "Missing classes: %s. Please add tests for these to sympy/core/tests/test_args.py." % ", ".join(failed)
def _test_args(obj):
all_basic = all(isinstance(arg, Basic) for arg in obj.args)
# Ideally obj.func(*obj.args) would always recreate the object, but for
# now, we only require it for objects with non-empty .args
recreatable = not obj.args or obj.func(*obj.args) == obj
return all_basic and recreatable
def test_sympy__algebras__quaternion__Quaternion():
from sympy.algebras.quaternion import Quaternion
assert _test_args(Quaternion(x, 1, 2, 3))
def test_sympy__assumptions__assume__AppliedPredicate():
from sympy.assumptions.assume import AppliedPredicate, Predicate
assert _test_args(AppliedPredicate(Predicate("test"), 2))
assert _test_args(Q.is_true(True))
@SKIP("abstract class")
def test_sympy__assumptions__assume__Predicate():
pass
def test_predicates():
predicates = [
getattr(Q, attr)
for attr in Q.__class__.__dict__
if not attr.startswith('__')]
for p in predicates:
assert _test_args(p)
def test_sympy__assumptions__assume__UndefinedPredicate():
from sympy.assumptions.assume import Predicate
assert _test_args(Predicate("test"))
@SKIP('abstract class')
def test_sympy__assumptions__relation__binrel__BinaryRelation():
pass
def test_sympy__assumptions__relation__binrel__AppliedBinaryRelation():
assert _test_args(Q.eq(1, 2))
def test_sympy__assumptions__wrapper__AssumptionsWrapper():
from sympy.assumptions.wrapper import AssumptionsWrapper
assert _test_args(AssumptionsWrapper(x, Q.positive(x)))
@SKIP("abstract Class")
def test_sympy__codegen__ast__CodegenAST():
from sympy.codegen.ast import CodegenAST
assert _test_args(CodegenAST())
@SKIP("abstract Class")
def test_sympy__codegen__ast__AssignmentBase():
from sympy.codegen.ast import AssignmentBase
assert _test_args(AssignmentBase(x, 1))
@SKIP("abstract Class")
def test_sympy__codegen__ast__AugmentedAssignment():
from sympy.codegen.ast import AugmentedAssignment
assert _test_args(AugmentedAssignment(x, 1))
def test_sympy__codegen__ast__AddAugmentedAssignment():
from sympy.codegen.ast import AddAugmentedAssignment
assert _test_args(AddAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__SubAugmentedAssignment():
from sympy.codegen.ast import SubAugmentedAssignment
assert _test_args(SubAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__MulAugmentedAssignment():
from sympy.codegen.ast import MulAugmentedAssignment
assert _test_args(MulAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__DivAugmentedAssignment():
from sympy.codegen.ast import DivAugmentedAssignment
assert _test_args(DivAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__ModAugmentedAssignment():
from sympy.codegen.ast import ModAugmentedAssignment
assert _test_args(ModAugmentedAssignment(x, 1))
def test_sympy__codegen__ast__CodeBlock():
from sympy.codegen.ast import CodeBlock, Assignment
assert _test_args(CodeBlock(Assignment(x, 1), Assignment(y, 2)))
def test_sympy__codegen__ast__For():
from sympy.codegen.ast import For, CodeBlock, AddAugmentedAssignment
from sympy.sets import Range
assert _test_args(For(x, Range(10), CodeBlock(AddAugmentedAssignment(y, 1))))
def test_sympy__codegen__ast__Token():
from sympy.codegen.ast import Token
assert _test_args(Token())
def test_sympy__codegen__ast__ContinueToken():
from sympy.codegen.ast import ContinueToken
assert _test_args(ContinueToken())
def test_sympy__codegen__ast__BreakToken():
from sympy.codegen.ast import BreakToken
assert _test_args(BreakToken())
def test_sympy__codegen__ast__NoneToken():
from sympy.codegen.ast import NoneToken
assert _test_args(NoneToken())
def test_sympy__codegen__ast__String():
from sympy.codegen.ast import String
assert _test_args(String('foobar'))
def test_sympy__codegen__ast__QuotedString():
from sympy.codegen.ast import QuotedString
assert _test_args(QuotedString('foobar'))
def test_sympy__codegen__ast__Comment():
from sympy.codegen.ast import Comment
assert _test_args(Comment('this is a comment'))
def test_sympy__codegen__ast__Node():
from sympy.codegen.ast import Node
assert _test_args(Node())
assert _test_args(Node(attrs={1, 2, 3}))
def test_sympy__codegen__ast__Type():
from sympy.codegen.ast import Type
assert _test_args(Type('float128'))
def test_sympy__codegen__ast__IntBaseType():
from sympy.codegen.ast import IntBaseType
assert _test_args(IntBaseType('bigint'))
def test_sympy__codegen__ast___SizedIntType():
from sympy.codegen.ast import _SizedIntType
assert _test_args(_SizedIntType('int128', 128))
def test_sympy__codegen__ast__SignedIntType():
from sympy.codegen.ast import SignedIntType
assert _test_args(SignedIntType('int128_with_sign', 128))
def test_sympy__codegen__ast__UnsignedIntType():
from sympy.codegen.ast import UnsignedIntType
assert _test_args(UnsignedIntType('unt128', 128))
def test_sympy__codegen__ast__FloatBaseType():
from sympy.codegen.ast import FloatBaseType
assert _test_args(FloatBaseType('positive_real'))
def test_sympy__codegen__ast__FloatType():
from sympy.codegen.ast import FloatType
assert _test_args(FloatType('float242', 242, nmant=142, nexp=99))
def test_sympy__codegen__ast__ComplexBaseType():
from sympy.codegen.ast import ComplexBaseType
assert _test_args(ComplexBaseType('positive_cmplx'))
def test_sympy__codegen__ast__ComplexType():
from sympy.codegen.ast import ComplexType
assert _test_args(ComplexType('complex42', 42, nmant=15, nexp=5))
def test_sympy__codegen__ast__Attribute():
from sympy.codegen.ast import Attribute
assert _test_args(Attribute('noexcept'))
def test_sympy__codegen__ast__Variable():
from sympy.codegen.ast import Variable, Type, value_const
assert _test_args(Variable(x))
assert _test_args(Variable(y, Type('float32'), {value_const}))
assert _test_args(Variable(z, type=Type('float64')))
def test_sympy__codegen__ast__Pointer():
from sympy.codegen.ast import Pointer, Type, pointer_const
assert _test_args(Pointer(x))
assert _test_args(Pointer(y, type=Type('float32')))
assert _test_args(Pointer(z, Type('float64'), {pointer_const}))
def test_sympy__codegen__ast__Declaration():
from sympy.codegen.ast import Declaration, Variable, Type
vx = Variable(x, type=Type('float'))
assert _test_args(Declaration(vx))
def test_sympy__codegen__ast__While():
from sympy.codegen.ast import While, AddAugmentedAssignment
assert _test_args(While(abs(x) < 1, [AddAugmentedAssignment(x, -1)]))
def test_sympy__codegen__ast__Scope():
from sympy.codegen.ast import Scope, AddAugmentedAssignment
assert _test_args(Scope([AddAugmentedAssignment(x, -1)]))
def test_sympy__codegen__ast__Stream():
from sympy.codegen.ast import Stream
assert _test_args(Stream('stdin'))
def test_sympy__codegen__ast__Print():
from sympy.codegen.ast import Print
assert _test_args(Print([x, y]))
assert _test_args(Print([x, y], "%d %d"))
def test_sympy__codegen__ast__FunctionPrototype():
from sympy.codegen.ast import FunctionPrototype, real, Declaration, Variable
inp_x = Declaration(Variable(x, type=real))
assert _test_args(FunctionPrototype(real, 'pwer', [inp_x]))
def test_sympy__codegen__ast__FunctionDefinition():
from sympy.codegen.ast import FunctionDefinition, real, Declaration, Variable, Assignment
inp_x = Declaration(Variable(x, type=real))
assert _test_args(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)]))
def test_sympy__codegen__ast__Return():
from sympy.codegen.ast import Return
assert _test_args(Return(x))
def test_sympy__codegen__ast__FunctionCall():
from sympy.codegen.ast import FunctionCall
assert _test_args(FunctionCall('pwer', [x]))
def test_sympy__codegen__ast__Element():
from sympy.codegen.ast import Element
assert _test_args(Element('x', range(3)))
def test_sympy__codegen__cnodes__CommaOperator():
from sympy.codegen.cnodes import CommaOperator
assert _test_args(CommaOperator(1, 2))
def test_sympy__codegen__cnodes__goto():
from sympy.codegen.cnodes import goto
assert _test_args(goto('early_exit'))
def test_sympy__codegen__cnodes__Label():
from sympy.codegen.cnodes import Label
assert _test_args(Label('early_exit'))
def test_sympy__codegen__cnodes__PreDecrement():
from sympy.codegen.cnodes import PreDecrement
assert _test_args(PreDecrement(x))
def test_sympy__codegen__cnodes__PostDecrement():
from sympy.codegen.cnodes import PostDecrement
assert _test_args(PostDecrement(x))
def test_sympy__codegen__cnodes__PreIncrement():
from sympy.codegen.cnodes import PreIncrement
assert _test_args(PreIncrement(x))
def test_sympy__codegen__cnodes__PostIncrement():
from sympy.codegen.cnodes import PostIncrement
assert _test_args(PostIncrement(x))
def test_sympy__codegen__cnodes__struct():
from sympy.codegen.ast import real, Variable
from sympy.codegen.cnodes import struct
assert _test_args(struct(declarations=[
Variable(x, type=real),
Variable(y, type=real)
]))
def test_sympy__codegen__cnodes__union():
from sympy.codegen.ast import float32, int32, Variable
from sympy.codegen.cnodes import union
assert _test_args(union(declarations=[
Variable(x, type=float32),
Variable(y, type=int32)
]))
def test_sympy__codegen__cxxnodes__using():
from sympy.codegen.cxxnodes import using
assert _test_args(using('std::vector'))
assert _test_args(using('std::vector', 'vec'))
def test_sympy__codegen__fnodes__Program():
from sympy.codegen.fnodes import Program
assert _test_args(Program('foobar', []))
def test_sympy__codegen__fnodes__Module():
from sympy.codegen.fnodes import Module
assert _test_args(Module('foobar', [], []))
def test_sympy__codegen__fnodes__Subroutine():
from sympy.codegen.fnodes import Subroutine
x = symbols('x', real=True)
assert _test_args(Subroutine('foo', [x], []))
def test_sympy__codegen__fnodes__GoTo():
from sympy.codegen.fnodes import GoTo
assert _test_args(GoTo([10]))
assert _test_args(GoTo([10, 20], x > 1))
def test_sympy__codegen__fnodes__FortranReturn():
from sympy.codegen.fnodes import FortranReturn
assert _test_args(FortranReturn(10))
def test_sympy__codegen__fnodes__Extent():
from sympy.codegen.fnodes import Extent
assert _test_args(Extent())
assert _test_args(Extent(None))
assert _test_args(Extent(':'))
assert _test_args(Extent(-3, 4))
assert _test_args(Extent(x, y))
def test_sympy__codegen__fnodes__use_rename():
from sympy.codegen.fnodes import use_rename
assert _test_args(use_rename('loc', 'glob'))
def test_sympy__codegen__fnodes__use():
from sympy.codegen.fnodes import use
assert _test_args(use('modfoo', only='bar'))
def test_sympy__codegen__fnodes__SubroutineCall():
from sympy.codegen.fnodes import SubroutineCall
assert _test_args(SubroutineCall('foo', ['bar', 'baz']))
def test_sympy__codegen__fnodes__Do():
from sympy.codegen.fnodes import Do
assert _test_args(Do([], 'i', 1, 42))
def test_sympy__codegen__fnodes__ImpliedDoLoop():
from sympy.codegen.fnodes import ImpliedDoLoop
assert _test_args(ImpliedDoLoop('i', 'i', 1, 42))
def test_sympy__codegen__fnodes__ArrayConstructor():
from sympy.codegen.fnodes import ArrayConstructor
assert _test_args(ArrayConstructor([1, 2, 3]))
from sympy.codegen.fnodes import ImpliedDoLoop
idl = ImpliedDoLoop('i', 'i', 1, 42)
assert _test_args(ArrayConstructor([1, idl, 3]))
def test_sympy__codegen__fnodes__sum_():
from sympy.codegen.fnodes import sum_
assert _test_args(sum_('arr'))
def test_sympy__codegen__fnodes__product_():
from sympy.codegen.fnodes import product_
assert _test_args(product_('arr'))
def test_sympy__codegen__numpy_nodes__logaddexp():
from sympy.codegen.numpy_nodes import logaddexp
assert _test_args(logaddexp(x, y))
def test_sympy__codegen__numpy_nodes__logaddexp2():
from sympy.codegen.numpy_nodes import logaddexp2
assert _test_args(logaddexp2(x, y))
def test_sympy__codegen__pynodes__List():
from sympy.codegen.pynodes import List
assert _test_args(List(1, 2, 3))
def test_sympy__codegen__pynodes__NumExprEvaluate():
from sympy.codegen.pynodes import NumExprEvaluate
assert _test_args(NumExprEvaluate(x))
def test_sympy__codegen__scipy_nodes__cosm1():
from sympy.codegen.scipy_nodes import cosm1
assert _test_args(cosm1(x))
def test_sympy__codegen__scipy_nodes__powm1():
from sympy.codegen.scipy_nodes import powm1
assert _test_args(powm1(x, y))
def test_sympy__codegen__abstract_nodes__List():
from sympy.codegen.abstract_nodes import List
assert _test_args(List(1, 2, 3))
def test_sympy__combinatorics__graycode__GrayCode():
from sympy.combinatorics.graycode import GrayCode
# an integer is given and returned from GrayCode as the arg
assert _test_args(GrayCode(3, start='100'))
assert _test_args(GrayCode(3, rank=1))
def test_sympy__combinatorics__permutations__Permutation():
from sympy.combinatorics.permutations import Permutation
assert _test_args(Permutation([0, 1, 2, 3]))
def test_sympy__combinatorics__permutations__AppliedPermutation():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.permutations import AppliedPermutation
p = Permutation([0, 1, 2, 3])
assert _test_args(AppliedPermutation(p, x))
def test_sympy__combinatorics__perm_groups__PermutationGroup():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.perm_groups import PermutationGroup
assert _test_args(PermutationGroup([Permutation([0, 1])]))
def test_sympy__combinatorics__polyhedron__Polyhedron():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.polyhedron import Polyhedron
from sympy.abc import w, x, y, z
pgroup = [Permutation([[0, 1, 2], [3]]),
Permutation([[0, 1, 3], [2]]),
Permutation([[0, 2, 3], [1]]),
Permutation([[1, 2, 3], [0]]),
Permutation([[0, 1], [2, 3]]),
Permutation([[0, 2], [1, 3]]),
Permutation([[0, 3], [1, 2]]),
Permutation([[0, 1, 2, 3]])]
corners = [w, x, y, z]
faces = [(w, x, y), (w, y, z), (w, z, x), (x, y, z)]
assert _test_args(Polyhedron(corners, faces, pgroup))
def test_sympy__combinatorics__prufer__Prufer():
from sympy.combinatorics.prufer import Prufer
assert _test_args(Prufer([[0, 1], [0, 2], [0, 3]], 4))
def test_sympy__combinatorics__partitions__Partition():
from sympy.combinatorics.partitions import Partition
assert _test_args(Partition([1]))
def test_sympy__combinatorics__partitions__IntegerPartition():
from sympy.combinatorics.partitions import IntegerPartition
assert _test_args(IntegerPartition([1]))
def test_sympy__concrete__products__Product():
from sympy.concrete.products import Product
assert _test_args(Product(x, (x, 0, 10)))
assert _test_args(Product(x, (x, 0, y), (y, 0, 10)))
@SKIP("abstract Class")
def test_sympy__concrete__expr_with_limits__ExprWithLimits():
from sympy.concrete.expr_with_limits import ExprWithLimits
assert _test_args(ExprWithLimits(x, (x, 0, 10)))
assert _test_args(ExprWithLimits(x*y, (x, 0, 10.),(y,1.,3)))
@SKIP("abstract Class")
def test_sympy__concrete__expr_with_limits__AddWithLimits():
from sympy.concrete.expr_with_limits import AddWithLimits
assert _test_args(AddWithLimits(x, (x, 0, 10)))
assert _test_args(AddWithLimits(x*y, (x, 0, 10),(y,1,3)))
@SKIP("abstract Class")
def test_sympy__concrete__expr_with_intlimits__ExprWithIntLimits():
from sympy.concrete.expr_with_intlimits import ExprWithIntLimits
assert _test_args(ExprWithIntLimits(x, (x, 0, 10)))
assert _test_args(ExprWithIntLimits(x*y, (x, 0, 10),(y,1,3)))
def test_sympy__concrete__summations__Sum():
from sympy.concrete.summations import Sum
assert _test_args(Sum(x, (x, 0, 10)))
assert _test_args(Sum(x, (x, 0, y), (y, 0, 10)))
def test_sympy__core__add__Add():
from sympy.core.add import Add
assert _test_args(Add(x, y, z, 2))
def test_sympy__core__basic__Atom():
from sympy.core.basic import Atom
assert _test_args(Atom())
def test_sympy__core__basic__Basic():
from sympy.core.basic import Basic
assert _test_args(Basic())
def test_sympy__core__containers__Dict():
from sympy.core.containers import Dict
assert _test_args(Dict({x: y, y: z}))
def test_sympy__core__containers__Tuple():
from sympy.core.containers import Tuple
assert _test_args(Tuple(x, y, z, 2))
def test_sympy__core__expr__AtomicExpr():
from sympy.core.expr import AtomicExpr
assert _test_args(AtomicExpr())
def test_sympy__core__expr__Expr():
from sympy.core.expr import Expr
assert _test_args(Expr())
def test_sympy__core__expr__UnevaluatedExpr():
from sympy.core.expr import UnevaluatedExpr
from sympy.abc import x
assert _test_args(UnevaluatedExpr(x))
def test_sympy__core__function__Application():
from sympy.core.function import Application
assert _test_args(Application(1, 2, 3))
def test_sympy__core__function__AppliedUndef():
from sympy.core.function import AppliedUndef
assert _test_args(AppliedUndef(1, 2, 3))
def test_sympy__core__function__Derivative():
from sympy.core.function import Derivative
assert _test_args(Derivative(2, x, y, 3))
@SKIP("abstract class")
def test_sympy__core__function__Function():
pass
def test_sympy__core__function__Lambda():
assert _test_args(Lambda((x, y), x + y + z))
def test_sympy__core__function__Subs():
from sympy.core.function import Subs
assert _test_args(Subs(x + y, x, 2))
def test_sympy__core__function__WildFunction():
from sympy.core.function import WildFunction
assert _test_args(WildFunction('f'))
def test_sympy__core__mod__Mod():
from sympy.core.mod import Mod
assert _test_args(Mod(x, 2))
def test_sympy__core__mul__Mul():
from sympy.core.mul import Mul
assert _test_args(Mul(2, x, y, z))
def test_sympy__core__numbers__Catalan():
from sympy.core.numbers import Catalan
assert _test_args(Catalan())
def test_sympy__core__numbers__ComplexInfinity():
from sympy.core.numbers import ComplexInfinity
assert _test_args(ComplexInfinity())
def test_sympy__core__numbers__EulerGamma():
from sympy.core.numbers import EulerGamma
assert _test_args(EulerGamma())
def test_sympy__core__numbers__Exp1():
from sympy.core.numbers import Exp1
assert _test_args(Exp1())
def test_sympy__core__numbers__Float():
from sympy.core.numbers import Float
assert _test_args(Float(1.23))
def test_sympy__core__numbers__GoldenRatio():
from sympy.core.numbers import GoldenRatio
assert _test_args(GoldenRatio())
def test_sympy__core__numbers__TribonacciConstant():
from sympy.core.numbers import TribonacciConstant
assert _test_args(TribonacciConstant())
def test_sympy__core__numbers__Half():
from sympy.core.numbers import Half
assert _test_args(Half())
def test_sympy__core__numbers__ImaginaryUnit():
from sympy.core.numbers import ImaginaryUnit
assert _test_args(ImaginaryUnit())
def test_sympy__core__numbers__Infinity():
from sympy.core.numbers import Infinity
assert _test_args(Infinity())
def test_sympy__core__numbers__Integer():
from sympy.core.numbers import Integer
assert _test_args(Integer(7))
@SKIP("abstract class")
def test_sympy__core__numbers__IntegerConstant():
pass
def test_sympy__core__numbers__NaN():
from sympy.core.numbers import NaN
assert _test_args(NaN())
def test_sympy__core__numbers__NegativeInfinity():
from sympy.core.numbers import NegativeInfinity
assert _test_args(NegativeInfinity())
def test_sympy__core__numbers__NegativeOne():
from sympy.core.numbers import NegativeOne
assert _test_args(NegativeOne())
def test_sympy__core__numbers__Number():
from sympy.core.numbers import Number
assert _test_args(Number(1, 7))
def test_sympy__core__numbers__NumberSymbol():
from sympy.core.numbers import NumberSymbol
assert _test_args(NumberSymbol())
def test_sympy__core__numbers__One():
from sympy.core.numbers import One
assert _test_args(One())
def test_sympy__core__numbers__Pi():
from sympy.core.numbers import Pi
assert _test_args(Pi())
def test_sympy__core__numbers__Rational():
from sympy.core.numbers import Rational
assert _test_args(Rational(1, 7))
@SKIP("abstract class")
def test_sympy__core__numbers__RationalConstant():
pass
def test_sympy__core__numbers__Zero():
from sympy.core.numbers import Zero
assert _test_args(Zero())
@SKIP("abstract class")
def test_sympy__core__operations__AssocOp():
pass
@SKIP("abstract class")
def test_sympy__core__operations__LatticeOp():
pass
def test_sympy__core__power__Pow():
from sympy.core.power import Pow
assert _test_args(Pow(x, 2))
def test_sympy__core__relational__Equality():
from sympy.core.relational import Equality
assert _test_args(Equality(x, 2))
def test_sympy__core__relational__GreaterThan():
from sympy.core.relational import GreaterThan
assert _test_args(GreaterThan(x, 2))
def test_sympy__core__relational__LessThan():
from sympy.core.relational import LessThan
assert _test_args(LessThan(x, 2))
@SKIP("abstract class")
def test_sympy__core__relational__Relational():
pass
def test_sympy__core__relational__StrictGreaterThan():
from sympy.core.relational import StrictGreaterThan
assert _test_args(StrictGreaterThan(x, 2))
def test_sympy__core__relational__StrictLessThan():
from sympy.core.relational import StrictLessThan
assert _test_args(StrictLessThan(x, 2))
def test_sympy__core__relational__Unequality():
from sympy.core.relational import Unequality
assert _test_args(Unequality(x, 2))
def test_sympy__sandbox__indexed_integrals__IndexedIntegral():
from sympy.tensor import IndexedBase, Idx
from sympy.sandbox.indexed_integrals import IndexedIntegral
A = IndexedBase('A')
i, j = symbols('i j', integer=True)
a1, a2 = symbols('a1:3', cls=Idx)
assert _test_args(IndexedIntegral(A[a1], A[a2]))
assert _test_args(IndexedIntegral(A[i], A[j]))
def test_sympy__calculus__accumulationbounds__AccumulationBounds():
from sympy.calculus.accumulationbounds import AccumulationBounds
assert _test_args(AccumulationBounds(0, 1))
def test_sympy__sets__ordinals__OmegaPower():
from sympy.sets.ordinals import OmegaPower
assert _test_args(OmegaPower(1, 1))
def test_sympy__sets__ordinals__Ordinal():
from sympy.sets.ordinals import Ordinal, OmegaPower
assert _test_args(Ordinal(OmegaPower(2, 1)))
def test_sympy__sets__ordinals__OrdinalOmega():
from sympy.sets.ordinals import OrdinalOmega
assert _test_args(OrdinalOmega())
def test_sympy__sets__ordinals__OrdinalZero():
from sympy.sets.ordinals import OrdinalZero
assert _test_args(OrdinalZero())
def test_sympy__sets__powerset__PowerSet():
from sympy.sets.powerset import PowerSet
from sympy.core.singleton import S
assert _test_args(PowerSet(S.EmptySet))
def test_sympy__sets__sets__EmptySet():
from sympy.sets.sets import EmptySet
assert _test_args(EmptySet())
def test_sympy__sets__sets__UniversalSet():
from sympy.sets.sets import UniversalSet
assert _test_args(UniversalSet())
def test_sympy__sets__sets__FiniteSet():
from sympy.sets.sets import FiniteSet
assert _test_args(FiniteSet(x, y, z))
def test_sympy__sets__sets__Interval():
from sympy.sets.sets import Interval
assert _test_args(Interval(0, 1))
def test_sympy__sets__sets__ProductSet():
from sympy.sets.sets import ProductSet, Interval
assert _test_args(ProductSet(Interval(0, 1), Interval(0, 1)))
@SKIP("does it make sense to test this?")
def test_sympy__sets__sets__Set():
from sympy.sets.sets import Set
assert _test_args(Set())
def test_sympy__sets__sets__Intersection():
from sympy.sets.sets import Intersection, Interval
from sympy.core.symbol import Symbol
x = Symbol('x')
y = Symbol('y')
S = Intersection(Interval(0, x), Interval(y, 1))
assert isinstance(S, Intersection)
assert _test_args(S)
def test_sympy__sets__sets__Union():
from sympy.sets.sets import Union, Interval
assert _test_args(Union(Interval(0, 1), Interval(2, 3)))
def test_sympy__sets__sets__Complement():
from sympy.sets.sets import Complement, Interval
assert _test_args(Complement(Interval(0, 2), Interval(0, 1)))
def test_sympy__sets__sets__SymmetricDifference():
from sympy.sets.sets import FiniteSet, SymmetricDifference
assert _test_args(SymmetricDifference(FiniteSet(1, 2, 3), \
FiniteSet(2, 3, 4)))
def test_sympy__sets__sets__DisjointUnion():
from sympy.sets.sets import FiniteSet, DisjointUnion
assert _test_args(DisjointUnion(FiniteSet(1, 2, 3), \
FiniteSet(2, 3, 4)))
def test_sympy__physics__quantum__trace__Tr():
from sympy.physics.quantum.trace import Tr
a, b = symbols('a b', commutative=False)
assert _test_args(Tr(a + b))
def test_sympy__sets__setexpr__SetExpr():
from sympy.sets.setexpr import SetExpr
from sympy.sets.sets import Interval
assert _test_args(SetExpr(Interval(0, 1)))
def test_sympy__sets__fancysets__Rationals():
from sympy.sets.fancysets import Rationals
assert _test_args(Rationals())
def test_sympy__sets__fancysets__Naturals():
from sympy.sets.fancysets import Naturals
assert _test_args(Naturals())
def test_sympy__sets__fancysets__Naturals0():
from sympy.sets.fancysets import Naturals0
assert _test_args(Naturals0())
def test_sympy__sets__fancysets__Integers():
from sympy.sets.fancysets import Integers
assert _test_args(Integers())
def test_sympy__sets__fancysets__Reals():
from sympy.sets.fancysets import Reals
assert _test_args(Reals())
def test_sympy__sets__fancysets__Complexes():
from sympy.sets.fancysets import Complexes
assert _test_args(Complexes())
def test_sympy__sets__fancysets__ComplexRegion():
from sympy.sets.fancysets import ComplexRegion
from sympy.core.singleton import S
from sympy.sets import Interval
a = Interval(0, 1)
b = Interval(2, 3)
theta = Interval(0, 2*S.Pi)
assert _test_args(ComplexRegion(a*b))
assert _test_args(ComplexRegion(a*theta, polar=True))
def test_sympy__sets__fancysets__CartesianComplexRegion():
from sympy.sets.fancysets import CartesianComplexRegion
from sympy.sets import Interval
a = Interval(0, 1)
b = Interval(2, 3)
assert _test_args(CartesianComplexRegion(a*b))
def test_sympy__sets__fancysets__PolarComplexRegion():
from sympy.sets.fancysets import PolarComplexRegion
from sympy.core.singleton import S
from sympy.sets import Interval
a = Interval(0, 1)
theta = Interval(0, 2*S.Pi)
assert _test_args(PolarComplexRegion(a*theta))
def test_sympy__sets__fancysets__ImageSet():
from sympy.sets.fancysets import ImageSet
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
x = Symbol('x')
assert _test_args(ImageSet(Lambda(x, x**2), S.Naturals))
def test_sympy__sets__fancysets__Range():
from sympy.sets.fancysets import Range
assert _test_args(Range(1, 5, 1))
def test_sympy__sets__conditionset__ConditionSet():
from sympy.sets.conditionset import ConditionSet
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
x = Symbol('x')
assert _test_args(ConditionSet(x, Eq(x**2, 1), S.Reals))
def test_sympy__sets__contains__Contains():
from sympy.sets.fancysets import Range
from sympy.sets.contains import Contains
assert _test_args(Contains(x, Range(0, 10, 2)))
# STATS
from sympy.stats.crv_types import NormalDistribution
nd = NormalDistribution(0, 1)
from sympy.stats.frv_types import DieDistribution
die = DieDistribution(6)
def test_sympy__stats__crv__ContinuousDomain():
from sympy.sets.sets import Interval
from sympy.stats.crv import ContinuousDomain
assert _test_args(ContinuousDomain({x}, Interval(-oo, oo)))
def test_sympy__stats__crv__SingleContinuousDomain():
from sympy.sets.sets import Interval
from sympy.stats.crv import SingleContinuousDomain
assert _test_args(SingleContinuousDomain(x, Interval(-oo, oo)))
def test_sympy__stats__crv__ProductContinuousDomain():
from sympy.sets.sets import Interval
from sympy.stats.crv import SingleContinuousDomain, ProductContinuousDomain
D = SingleContinuousDomain(x, Interval(-oo, oo))
E = SingleContinuousDomain(y, Interval(0, oo))
assert _test_args(ProductContinuousDomain(D, E))
def test_sympy__stats__crv__ConditionalContinuousDomain():
from sympy.sets.sets import Interval
from sympy.stats.crv import (SingleContinuousDomain,
ConditionalContinuousDomain)
D = SingleContinuousDomain(x, Interval(-oo, oo))
assert _test_args(ConditionalContinuousDomain(D, x > 0))
def test_sympy__stats__crv__ContinuousPSpace():
from sympy.sets.sets import Interval
from sympy.stats.crv import ContinuousPSpace, SingleContinuousDomain
D = SingleContinuousDomain(x, Interval(-oo, oo))
assert _test_args(ContinuousPSpace(D, nd))
def test_sympy__stats__crv__SingleContinuousPSpace():
from sympy.stats.crv import SingleContinuousPSpace
assert _test_args(SingleContinuousPSpace(x, nd))
@SKIP("abstract class")
def test_sympy__stats__rv__Distribution():
pass
@SKIP("abstract class")
def test_sympy__stats__crv__SingleContinuousDistribution():
pass
def test_sympy__stats__drv__SingleDiscreteDomain():
from sympy.stats.drv import SingleDiscreteDomain
assert _test_args(SingleDiscreteDomain(x, S.Naturals))
def test_sympy__stats__drv__ProductDiscreteDomain():
from sympy.stats.drv import SingleDiscreteDomain, ProductDiscreteDomain
X = SingleDiscreteDomain(x, S.Naturals)
Y = SingleDiscreteDomain(y, S.Integers)
assert _test_args(ProductDiscreteDomain(X, Y))
def test_sympy__stats__drv__SingleDiscretePSpace():
from sympy.stats.drv import SingleDiscretePSpace
from sympy.stats.drv_types import PoissonDistribution
assert _test_args(SingleDiscretePSpace(x, PoissonDistribution(1)))
def test_sympy__stats__drv__DiscretePSpace():
from sympy.stats.drv import DiscretePSpace, SingleDiscreteDomain
density = Lambda(x, 2**(-x))
domain = SingleDiscreteDomain(x, S.Naturals)
assert _test_args(DiscretePSpace(domain, density))
def test_sympy__stats__drv__ConditionalDiscreteDomain():
from sympy.stats.drv import ConditionalDiscreteDomain, SingleDiscreteDomain
X = SingleDiscreteDomain(x, S.Naturals0)
assert _test_args(ConditionalDiscreteDomain(X, x > 2))
def test_sympy__stats__joint_rv__JointPSpace():
from sympy.stats.joint_rv import JointPSpace, JointDistribution
assert _test_args(JointPSpace('X', JointDistribution(1)))
def test_sympy__stats__joint_rv__JointRandomSymbol():
from sympy.stats.joint_rv import JointRandomSymbol
assert _test_args(JointRandomSymbol(x))
def test_sympy__stats__joint_rv_types__JointDistributionHandmade():
from sympy.tensor.indexed import Indexed
from sympy.stats.joint_rv_types import JointDistributionHandmade
x1, x2 = (Indexed('x', i) for i in (1, 2))
assert _test_args(JointDistributionHandmade(x1 + x2, S.Reals**2))
def test_sympy__stats__joint_rv__MarginalDistribution():
from sympy.stats.rv import RandomSymbol
from sympy.stats.joint_rv import MarginalDistribution
r = RandomSymbol(S('r'))
assert _test_args(MarginalDistribution(r, (r,)))
def test_sympy__stats__compound_rv__CompoundDistribution():
from sympy.stats.compound_rv import CompoundDistribution
from sympy.stats.drv_types import PoissonDistribution, Poisson
r = Poisson('r', 10)
assert _test_args(CompoundDistribution(PoissonDistribution(r)))
def test_sympy__stats__compound_rv__CompoundPSpace():
from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution
from sympy.stats.drv_types import PoissonDistribution, Poisson
r = Poisson('r', 5)
C = CompoundDistribution(PoissonDistribution(r))
assert _test_args(CompoundPSpace('C', C))
@SKIP("abstract class")
def test_sympy__stats__drv__SingleDiscreteDistribution():
pass
@SKIP("abstract class")
def test_sympy__stats__drv__DiscreteDistribution():
pass
@SKIP("abstract class")
def test_sympy__stats__drv__DiscreteDomain():
pass
def test_sympy__stats__rv__RandomDomain():
from sympy.stats.rv import RandomDomain
from sympy.sets.sets import FiniteSet
assert _test_args(RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3)))
def test_sympy__stats__rv__SingleDomain():
from sympy.stats.rv import SingleDomain
from sympy.sets.sets import FiniteSet
assert _test_args(SingleDomain(x, FiniteSet(1, 2, 3)))
def test_sympy__stats__rv__ConditionalDomain():
from sympy.stats.rv import ConditionalDomain, RandomDomain
from sympy.sets.sets import FiniteSet
D = RandomDomain(FiniteSet(x), FiniteSet(1, 2))
assert _test_args(ConditionalDomain(D, x > 1))
def test_sympy__stats__rv__MatrixDomain():
from sympy.stats.rv import MatrixDomain
from sympy.matrices import MatrixSet
from sympy.core.singleton import S
assert _test_args(MatrixDomain(x, MatrixSet(2, 2, S.Reals)))
def test_sympy__stats__rv__PSpace():
from sympy.stats.rv import PSpace, RandomDomain
from sympy.sets.sets import FiniteSet
D = RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3, 4, 5, 6))
assert _test_args(PSpace(D, die))
@SKIP("abstract Class")
def test_sympy__stats__rv__SinglePSpace():
pass
def test_sympy__stats__rv__RandomSymbol():
from sympy.stats.rv import RandomSymbol
from sympy.stats.crv import SingleContinuousPSpace
A = SingleContinuousPSpace(x, nd)
assert _test_args(RandomSymbol(x, A))
@SKIP("abstract Class")
def test_sympy__stats__rv__ProductPSpace():
pass
def test_sympy__stats__rv__IndependentProductPSpace():
from sympy.stats.rv import IndependentProductPSpace
from sympy.stats.crv import SingleContinuousPSpace
A = SingleContinuousPSpace(x, nd)
B = SingleContinuousPSpace(y, nd)
assert _test_args(IndependentProductPSpace(A, B))
def test_sympy__stats__rv__ProductDomain():
from sympy.sets.sets import Interval
from sympy.stats.rv import ProductDomain, SingleDomain
D = SingleDomain(x, Interval(-oo, oo))
E = SingleDomain(y, Interval(0, oo))
assert _test_args(ProductDomain(D, E))
def test_sympy__stats__symbolic_probability__Probability():
from sympy.stats.symbolic_probability import Probability
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(Probability(X > 0))
def test_sympy__stats__symbolic_probability__Expectation():
from sympy.stats.symbolic_probability import Expectation
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(Expectation(X > 0))
def test_sympy__stats__symbolic_probability__Covariance():
from sympy.stats.symbolic_probability import Covariance
from sympy.stats import Normal
X = Normal('X', 0, 1)
Y = Normal('Y', 0, 3)
assert _test_args(Covariance(X, Y))
def test_sympy__stats__symbolic_probability__Variance():
from sympy.stats.symbolic_probability import Variance
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(Variance(X))
def test_sympy__stats__symbolic_probability__Moment():
from sympy.stats.symbolic_probability import Moment
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(Moment(X, 3, 2, X > 3))
def test_sympy__stats__symbolic_probability__CentralMoment():
from sympy.stats.symbolic_probability import CentralMoment
from sympy.stats import Normal
X = Normal('X', 0, 1)
assert _test_args(CentralMoment(X, 2, X > 1))
def test_sympy__stats__frv_types__DiscreteUniformDistribution():
from sympy.stats.frv_types import DiscreteUniformDistribution
from sympy.core.containers import Tuple
assert _test_args(DiscreteUniformDistribution(Tuple(*list(range(6)))))
def test_sympy__stats__frv_types__DieDistribution():
assert _test_args(die)
def test_sympy__stats__frv_types__BernoulliDistribution():
from sympy.stats.frv_types import BernoulliDistribution
assert _test_args(BernoulliDistribution(S.Half, 0, 1))
def test_sympy__stats__frv_types__BinomialDistribution():
from sympy.stats.frv_types import BinomialDistribution
assert _test_args(BinomialDistribution(5, S.Half, 1, 0))
def test_sympy__stats__frv_types__BetaBinomialDistribution():
from sympy.stats.frv_types import BetaBinomialDistribution
assert _test_args(BetaBinomialDistribution(5, 1, 1))
def test_sympy__stats__frv_types__HypergeometricDistribution():
from sympy.stats.frv_types import HypergeometricDistribution
assert _test_args(HypergeometricDistribution(10, 5, 3))
def test_sympy__stats__frv_types__RademacherDistribution():
from sympy.stats.frv_types import RademacherDistribution
assert _test_args(RademacherDistribution())
def test_sympy__stats__frv_types__IdealSolitonDistribution():
from sympy.stats.frv_types import IdealSolitonDistribution
assert _test_args(IdealSolitonDistribution(10))
def test_sympy__stats__frv_types__RobustSolitonDistribution():
from sympy.stats.frv_types import RobustSolitonDistribution
assert _test_args(RobustSolitonDistribution(1000, 0.5, 0.1))
def test_sympy__stats__frv__FiniteDomain():
from sympy.stats.frv import FiniteDomain
assert _test_args(FiniteDomain({(x, 1), (x, 2)})) # x can be 1 or 2
def test_sympy__stats__frv__SingleFiniteDomain():
from sympy.stats.frv import SingleFiniteDomain
assert _test_args(SingleFiniteDomain(x, {1, 2})) # x can be 1 or 2
def test_sympy__stats__frv__ProductFiniteDomain():
from sympy.stats.frv import SingleFiniteDomain, ProductFiniteDomain
xd = SingleFiniteDomain(x, {1, 2})
yd = SingleFiniteDomain(y, {1, 2})
assert _test_args(ProductFiniteDomain(xd, yd))
def test_sympy__stats__frv__ConditionalFiniteDomain():
from sympy.stats.frv import SingleFiniteDomain, ConditionalFiniteDomain
xd = SingleFiniteDomain(x, {1, 2})
assert _test_args(ConditionalFiniteDomain(xd, x > 1))
def test_sympy__stats__frv__FinitePSpace():
from sympy.stats.frv import FinitePSpace, SingleFiniteDomain
xd = SingleFiniteDomain(x, {1, 2, 3, 4, 5, 6})
assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half}))
xd = SingleFiniteDomain(x, {1, 2})
assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half}))
def test_sympy__stats__frv__SingleFinitePSpace():
from sympy.stats.frv import SingleFinitePSpace
from sympy.core.symbol import Symbol
assert _test_args(SingleFinitePSpace(Symbol('x'), die))
def test_sympy__stats__frv__ProductFinitePSpace():
from sympy.stats.frv import SingleFinitePSpace, ProductFinitePSpace
from sympy.core.symbol import Symbol
xp = SingleFinitePSpace(Symbol('x'), die)
yp = SingleFinitePSpace(Symbol('y'), die)
assert _test_args(ProductFinitePSpace(xp, yp))
@SKIP("abstract class")
def test_sympy__stats__frv__SingleFiniteDistribution():
pass
@SKIP("abstract class")
def test_sympy__stats__crv__ContinuousDistribution():
pass
def test_sympy__stats__frv_types__FiniteDistributionHandmade():
from sympy.stats.frv_types import FiniteDistributionHandmade
from sympy.core.containers import Dict
assert _test_args(FiniteDistributionHandmade(Dict({1: 1})))
def test_sympy__stats__crv_types__ContinuousDistributionHandmade():
from sympy.stats.crv_types import ContinuousDistributionHandmade
from sympy.core.function import Lambda
from sympy.sets.sets import Interval
from sympy.abc import x
assert _test_args(ContinuousDistributionHandmade(Lambda(x, 2*x),
Interval(0, 1)))
def test_sympy__stats__drv_types__DiscreteDistributionHandmade():
from sympy.stats.drv_types import DiscreteDistributionHandmade
from sympy.core.function import Lambda
from sympy.sets.sets import FiniteSet
from sympy.abc import x
assert _test_args(DiscreteDistributionHandmade(Lambda(x, Rational(1, 10)),
FiniteSet(*range(10))))
def test_sympy__stats__rv__Density():
from sympy.stats.rv import Density
from sympy.stats.crv_types import Normal
assert _test_args(Density(Normal('x', 0, 1)))
def test_sympy__stats__crv_types__ArcsinDistribution():
from sympy.stats.crv_types import ArcsinDistribution
assert _test_args(ArcsinDistribution(0, 1))
def test_sympy__stats__crv_types__BeniniDistribution():
from sympy.stats.crv_types import BeniniDistribution
assert _test_args(BeniniDistribution(1, 1, 1))
def test_sympy__stats__crv_types__BetaDistribution():
from sympy.stats.crv_types import BetaDistribution
assert _test_args(BetaDistribution(1, 1))
def test_sympy__stats__crv_types__BetaNoncentralDistribution():
from sympy.stats.crv_types import BetaNoncentralDistribution
assert _test_args(BetaNoncentralDistribution(1, 1, 1))
def test_sympy__stats__crv_types__BetaPrimeDistribution():
from sympy.stats.crv_types import BetaPrimeDistribution
assert _test_args(BetaPrimeDistribution(1, 1))
def test_sympy__stats__crv_types__BoundedParetoDistribution():
from sympy.stats.crv_types import BoundedParetoDistribution
assert _test_args(BoundedParetoDistribution(1, 1, 2))
def test_sympy__stats__crv_types__CauchyDistribution():
from sympy.stats.crv_types import CauchyDistribution
assert _test_args(CauchyDistribution(0, 1))
def test_sympy__stats__crv_types__ChiDistribution():
from sympy.stats.crv_types import ChiDistribution
assert _test_args(ChiDistribution(1))
def test_sympy__stats__crv_types__ChiNoncentralDistribution():
from sympy.stats.crv_types import ChiNoncentralDistribution
assert _test_args(ChiNoncentralDistribution(1,1))
def test_sympy__stats__crv_types__ChiSquaredDistribution():
from sympy.stats.crv_types import ChiSquaredDistribution
assert _test_args(ChiSquaredDistribution(1))
def test_sympy__stats__crv_types__DagumDistribution():
from sympy.stats.crv_types import DagumDistribution
assert _test_args(DagumDistribution(1, 1, 1))
def test_sympy__stats__crv_types__ExGaussianDistribution():
from sympy.stats.crv_types import ExGaussianDistribution
assert _test_args(ExGaussianDistribution(1, 1, 1))
def test_sympy__stats__crv_types__ExponentialDistribution():
from sympy.stats.crv_types import ExponentialDistribution
assert _test_args(ExponentialDistribution(1))
def test_sympy__stats__crv_types__ExponentialPowerDistribution():
from sympy.stats.crv_types import ExponentialPowerDistribution
assert _test_args(ExponentialPowerDistribution(0, 1, 1))
def test_sympy__stats__crv_types__FDistributionDistribution():
from sympy.stats.crv_types import FDistributionDistribution
assert _test_args(FDistributionDistribution(1, 1))
def test_sympy__stats__crv_types__FisherZDistribution():
from sympy.stats.crv_types import FisherZDistribution
assert _test_args(FisherZDistribution(1, 1))
def test_sympy__stats__crv_types__FrechetDistribution():
from sympy.stats.crv_types import FrechetDistribution
assert _test_args(FrechetDistribution(1, 1, 1))
def test_sympy__stats__crv_types__GammaInverseDistribution():
from sympy.stats.crv_types import GammaInverseDistribution
assert _test_args(GammaInverseDistribution(1, 1))
def test_sympy__stats__crv_types__GammaDistribution():
from sympy.stats.crv_types import GammaDistribution
assert _test_args(GammaDistribution(1, 1))
def test_sympy__stats__crv_types__GumbelDistribution():
from sympy.stats.crv_types import GumbelDistribution
assert _test_args(GumbelDistribution(1, 1, False))
def test_sympy__stats__crv_types__GompertzDistribution():
from sympy.stats.crv_types import GompertzDistribution
assert _test_args(GompertzDistribution(1, 1))
def test_sympy__stats__crv_types__KumaraswamyDistribution():
from sympy.stats.crv_types import KumaraswamyDistribution
assert _test_args(KumaraswamyDistribution(1, 1))
def test_sympy__stats__crv_types__LaplaceDistribution():
from sympy.stats.crv_types import LaplaceDistribution
assert _test_args(LaplaceDistribution(0, 1))
def test_sympy__stats__crv_types__LevyDistribution():
from sympy.stats.crv_types import LevyDistribution
assert _test_args(LevyDistribution(0, 1))
def test_sympy__stats__crv_types__LogCauchyDistribution():
from sympy.stats.crv_types import LogCauchyDistribution
assert _test_args(LogCauchyDistribution(0, 1))
def test_sympy__stats__crv_types__LogisticDistribution():
from sympy.stats.crv_types import LogisticDistribution
assert _test_args(LogisticDistribution(0, 1))
def test_sympy__stats__crv_types__LogLogisticDistribution():
from sympy.stats.crv_types import LogLogisticDistribution
assert _test_args(LogLogisticDistribution(1, 1))
def test_sympy__stats__crv_types__LogitNormalDistribution():
from sympy.stats.crv_types import LogitNormalDistribution
assert _test_args(LogitNormalDistribution(0, 1))
def test_sympy__stats__crv_types__LogNormalDistribution():
from sympy.stats.crv_types import LogNormalDistribution
assert _test_args(LogNormalDistribution(0, 1))
def test_sympy__stats__crv_types__LomaxDistribution():
from sympy.stats.crv_types import LomaxDistribution
assert _test_args(LomaxDistribution(1, 2))
def test_sympy__stats__crv_types__MaxwellDistribution():
from sympy.stats.crv_types import MaxwellDistribution
assert _test_args(MaxwellDistribution(1))
def test_sympy__stats__crv_types__MoyalDistribution():
from sympy.stats.crv_types import MoyalDistribution
assert _test_args(MoyalDistribution(1,2))
def test_sympy__stats__crv_types__NakagamiDistribution():
from sympy.stats.crv_types import NakagamiDistribution
assert _test_args(NakagamiDistribution(1, 1))
def test_sympy__stats__crv_types__NormalDistribution():
from sympy.stats.crv_types import NormalDistribution
assert _test_args(NormalDistribution(0, 1))
def test_sympy__stats__crv_types__GaussianInverseDistribution():
from sympy.stats.crv_types import GaussianInverseDistribution
assert _test_args(GaussianInverseDistribution(1, 1))
def test_sympy__stats__crv_types__ParetoDistribution():
from sympy.stats.crv_types import ParetoDistribution
assert _test_args(ParetoDistribution(1, 1))
def test_sympy__stats__crv_types__PowerFunctionDistribution():
from sympy.stats.crv_types import PowerFunctionDistribution
assert _test_args(PowerFunctionDistribution(2,0,1))
def test_sympy__stats__crv_types__QuadraticUDistribution():
from sympy.stats.crv_types import QuadraticUDistribution
assert _test_args(QuadraticUDistribution(1, 2))
def test_sympy__stats__crv_types__RaisedCosineDistribution():
from sympy.stats.crv_types import RaisedCosineDistribution
assert _test_args(RaisedCosineDistribution(1, 1))
def test_sympy__stats__crv_types__RayleighDistribution():
from sympy.stats.crv_types import RayleighDistribution
assert _test_args(RayleighDistribution(1))
def test_sympy__stats__crv_types__ReciprocalDistribution():
from sympy.stats.crv_types import ReciprocalDistribution
assert _test_args(ReciprocalDistribution(5, 30))
def test_sympy__stats__crv_types__ShiftedGompertzDistribution():
from sympy.stats.crv_types import ShiftedGompertzDistribution
assert _test_args(ShiftedGompertzDistribution(1, 1))
def test_sympy__stats__crv_types__StudentTDistribution():
from sympy.stats.crv_types import StudentTDistribution
assert _test_args(StudentTDistribution(1))
def test_sympy__stats__crv_types__TrapezoidalDistribution():
from sympy.stats.crv_types import TrapezoidalDistribution
assert _test_args(TrapezoidalDistribution(1, 2, 3, 4))
def test_sympy__stats__crv_types__TriangularDistribution():
from sympy.stats.crv_types import TriangularDistribution
assert _test_args(TriangularDistribution(-1, 0, 1))
def test_sympy__stats__crv_types__UniformDistribution():
from sympy.stats.crv_types import UniformDistribution
assert _test_args(UniformDistribution(0, 1))
def test_sympy__stats__crv_types__UniformSumDistribution():
from sympy.stats.crv_types import UniformSumDistribution
assert _test_args(UniformSumDistribution(1))
def test_sympy__stats__crv_types__VonMisesDistribution():
from sympy.stats.crv_types import VonMisesDistribution
assert _test_args(VonMisesDistribution(1, 1))
def test_sympy__stats__crv_types__WeibullDistribution():
from sympy.stats.crv_types import WeibullDistribution
assert _test_args(WeibullDistribution(1, 1))
def test_sympy__stats__crv_types__WignerSemicircleDistribution():
from sympy.stats.crv_types import WignerSemicircleDistribution
assert _test_args(WignerSemicircleDistribution(1))
def test_sympy__stats__drv_types__GeometricDistribution():
from sympy.stats.drv_types import GeometricDistribution
assert _test_args(GeometricDistribution(.5))
def test_sympy__stats__drv_types__HermiteDistribution():
from sympy.stats.drv_types import HermiteDistribution
assert _test_args(HermiteDistribution(1, 2))
def test_sympy__stats__drv_types__LogarithmicDistribution():
from sympy.stats.drv_types import LogarithmicDistribution
assert _test_args(LogarithmicDistribution(.5))
def test_sympy__stats__drv_types__NegativeBinomialDistribution():
from sympy.stats.drv_types import NegativeBinomialDistribution
assert _test_args(NegativeBinomialDistribution(.5, .5))
def test_sympy__stats__drv_types__FlorySchulzDistribution():
from sympy.stats.drv_types import FlorySchulzDistribution
assert _test_args(FlorySchulzDistribution(.5))
def test_sympy__stats__drv_types__PoissonDistribution():
from sympy.stats.drv_types import PoissonDistribution
assert _test_args(PoissonDistribution(1))
def test_sympy__stats__drv_types__SkellamDistribution():
from sympy.stats.drv_types import SkellamDistribution
assert _test_args(SkellamDistribution(1, 1))
def test_sympy__stats__drv_types__YuleSimonDistribution():
from sympy.stats.drv_types import YuleSimonDistribution
assert _test_args(YuleSimonDistribution(.5))
def test_sympy__stats__drv_types__ZetaDistribution():
from sympy.stats.drv_types import ZetaDistribution
assert _test_args(ZetaDistribution(1.5))
def test_sympy__stats__joint_rv__JointDistribution():
from sympy.stats.joint_rv import JointDistribution
assert _test_args(JointDistribution(1, 2, 3, 4))
def test_sympy__stats__joint_rv_types__MultivariateNormalDistribution():
from sympy.stats.joint_rv_types import MultivariateNormalDistribution
assert _test_args(
MultivariateNormalDistribution([0, 1], [[1, 0],[0, 1]]))
def test_sympy__stats__joint_rv_types__MultivariateLaplaceDistribution():
from sympy.stats.joint_rv_types import MultivariateLaplaceDistribution
assert _test_args(MultivariateLaplaceDistribution([0, 1], [[1, 0],[0, 1]]))
def test_sympy__stats__joint_rv_types__MultivariateTDistribution():
from sympy.stats.joint_rv_types import MultivariateTDistribution
assert _test_args(MultivariateTDistribution([0, 1], [[1, 0],[0, 1]], 1))
def test_sympy__stats__joint_rv_types__NormalGammaDistribution():
from sympy.stats.joint_rv_types import NormalGammaDistribution
assert _test_args(NormalGammaDistribution(1, 2, 3, 4))
def test_sympy__stats__joint_rv_types__GeneralizedMultivariateLogGammaDistribution():
from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaDistribution
v, l, mu = (4, [1, 2, 3, 4], [1, 2, 3, 4])
assert _test_args(GeneralizedMultivariateLogGammaDistribution(S.Half, v, l, mu))
def test_sympy__stats__joint_rv_types__MultivariateBetaDistribution():
from sympy.stats.joint_rv_types import MultivariateBetaDistribution
assert _test_args(MultivariateBetaDistribution([1, 2, 3]))
def test_sympy__stats__joint_rv_types__MultivariateEwensDistribution():
from sympy.stats.joint_rv_types import MultivariateEwensDistribution
assert _test_args(MultivariateEwensDistribution(5, 1))
def test_sympy__stats__joint_rv_types__MultinomialDistribution():
from sympy.stats.joint_rv_types import MultinomialDistribution
assert _test_args(MultinomialDistribution(5, [0.5, 0.1, 0.3]))
def test_sympy__stats__joint_rv_types__NegativeMultinomialDistribution():
from sympy.stats.joint_rv_types import NegativeMultinomialDistribution
assert _test_args(NegativeMultinomialDistribution(5, [0.5, 0.1, 0.3]))
def test_sympy__stats__rv__RandomIndexedSymbol():
from sympy.stats.rv import RandomIndexedSymbol, pspace
from sympy.stats.stochastic_process_types import DiscreteMarkovChain
X = DiscreteMarkovChain("X")
assert _test_args(RandomIndexedSymbol(X[0].symbol, pspace(X[0])))
def test_sympy__stats__rv__RandomMatrixSymbol():
from sympy.stats.rv import RandomMatrixSymbol
from sympy.stats.random_matrix import RandomMatrixPSpace
pspace = RandomMatrixPSpace('P')
assert _test_args(RandomMatrixSymbol('M', 3, 3, pspace))
def test_sympy__stats__stochastic_process__StochasticPSpace():
from sympy.stats.stochastic_process import StochasticPSpace
from sympy.stats.stochastic_process_types import StochasticProcess
from sympy.stats.frv_types import BernoulliDistribution
assert _test_args(StochasticPSpace("Y", StochasticProcess("Y", [1, 2, 3]), BernoulliDistribution(S.Half, 1, 0)))
def test_sympy__stats__stochastic_process_types__StochasticProcess():
from sympy.stats.stochastic_process_types import StochasticProcess
assert _test_args(StochasticProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__MarkovProcess():
from sympy.stats.stochastic_process_types import MarkovProcess
assert _test_args(MarkovProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__DiscreteTimeStochasticProcess():
from sympy.stats.stochastic_process_types import DiscreteTimeStochasticProcess
assert _test_args(DiscreteTimeStochasticProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__ContinuousTimeStochasticProcess():
from sympy.stats.stochastic_process_types import ContinuousTimeStochasticProcess
assert _test_args(ContinuousTimeStochasticProcess("Y", [1, 2, 3]))
def test_sympy__stats__stochastic_process_types__TransitionMatrixOf():
from sympy.stats.stochastic_process_types import TransitionMatrixOf, DiscreteMarkovChain
from sympy.matrices.expressions.matexpr import MatrixSymbol
DMC = DiscreteMarkovChain("Y")
assert _test_args(TransitionMatrixOf(DMC, MatrixSymbol('T', 3, 3)))
def test_sympy__stats__stochastic_process_types__GeneratorMatrixOf():
from sympy.stats.stochastic_process_types import GeneratorMatrixOf, ContinuousMarkovChain
from sympy.matrices.expressions.matexpr import MatrixSymbol
DMC = ContinuousMarkovChain("Y")
assert _test_args(GeneratorMatrixOf(DMC, MatrixSymbol('T', 3, 3)))
def test_sympy__stats__stochastic_process_types__StochasticStateSpaceOf():
from sympy.stats.stochastic_process_types import StochasticStateSpaceOf, DiscreteMarkovChain
DMC = DiscreteMarkovChain("Y")
assert _test_args(StochasticStateSpaceOf(DMC, [0, 1, 2]))
def test_sympy__stats__stochastic_process_types__DiscreteMarkovChain():
from sympy.stats.stochastic_process_types import DiscreteMarkovChain
from sympy.matrices.expressions.matexpr import MatrixSymbol
assert _test_args(DiscreteMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3)))
def test_sympy__stats__stochastic_process_types__ContinuousMarkovChain():
from sympy.stats.stochastic_process_types import ContinuousMarkovChain
from sympy.matrices.expressions.matexpr import MatrixSymbol
assert _test_args(ContinuousMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3)))
def test_sympy__stats__stochastic_process_types__BernoulliProcess():
from sympy.stats.stochastic_process_types import BernoulliProcess
assert _test_args(BernoulliProcess("B", 0.5, 1, 0))
def test_sympy__stats__stochastic_process_types__CountingProcess():
from sympy.stats.stochastic_process_types import CountingProcess
assert _test_args(CountingProcess("C"))
def test_sympy__stats__stochastic_process_types__PoissonProcess():
from sympy.stats.stochastic_process_types import PoissonProcess
assert _test_args(PoissonProcess("X", 2))
def test_sympy__stats__stochastic_process_types__WienerProcess():
from sympy.stats.stochastic_process_types import WienerProcess
assert _test_args(WienerProcess("X"))
def test_sympy__stats__stochastic_process_types__GammaProcess():
from sympy.stats.stochastic_process_types import GammaProcess
assert _test_args(GammaProcess("X", 1, 2))
def test_sympy__stats__random_matrix__RandomMatrixPSpace():
from sympy.stats.random_matrix import RandomMatrixPSpace
from sympy.stats.random_matrix_models import RandomMatrixEnsembleModel
model = RandomMatrixEnsembleModel('R', 3)
assert _test_args(RandomMatrixPSpace('P', model=model))
def test_sympy__stats__random_matrix_models__RandomMatrixEnsembleModel():
from sympy.stats.random_matrix_models import RandomMatrixEnsembleModel
assert _test_args(RandomMatrixEnsembleModel('R', 3))
def test_sympy__stats__random_matrix_models__GaussianEnsembleModel():
from sympy.stats.random_matrix_models import GaussianEnsembleModel
assert _test_args(GaussianEnsembleModel('G', 3))
def test_sympy__stats__random_matrix_models__GaussianUnitaryEnsembleModel():
from sympy.stats.random_matrix_models import GaussianUnitaryEnsembleModel
assert _test_args(GaussianUnitaryEnsembleModel('U', 3))
def test_sympy__stats__random_matrix_models__GaussianOrthogonalEnsembleModel():
from sympy.stats.random_matrix_models import GaussianOrthogonalEnsembleModel
assert _test_args(GaussianOrthogonalEnsembleModel('U', 3))
def test_sympy__stats__random_matrix_models__GaussianSymplecticEnsembleModel():
from sympy.stats.random_matrix_models import GaussianSymplecticEnsembleModel
assert _test_args(GaussianSymplecticEnsembleModel('U', 3))
def test_sympy__stats__random_matrix_models__CircularEnsembleModel():
from sympy.stats.random_matrix_models import CircularEnsembleModel
assert _test_args(CircularEnsembleModel('C', 3))
def test_sympy__stats__random_matrix_models__CircularUnitaryEnsembleModel():
from sympy.stats.random_matrix_models import CircularUnitaryEnsembleModel
assert _test_args(CircularUnitaryEnsembleModel('U', 3))
def test_sympy__stats__random_matrix_models__CircularOrthogonalEnsembleModel():
from sympy.stats.random_matrix_models import CircularOrthogonalEnsembleModel
assert _test_args(CircularOrthogonalEnsembleModel('O', 3))
def test_sympy__stats__random_matrix_models__CircularSymplecticEnsembleModel():
from sympy.stats.random_matrix_models import CircularSymplecticEnsembleModel
assert _test_args(CircularSymplecticEnsembleModel('S', 3))
def test_sympy__stats__symbolic_multivariate_probability__ExpectationMatrix():
from sympy.stats import ExpectationMatrix
from sympy.stats.rv import RandomMatrixSymbol
assert _test_args(ExpectationMatrix(RandomMatrixSymbol('R', 2, 1)))
def test_sympy__stats__symbolic_multivariate_probability__VarianceMatrix():
from sympy.stats import VarianceMatrix
from sympy.stats.rv import RandomMatrixSymbol
assert _test_args(VarianceMatrix(RandomMatrixSymbol('R', 3, 1)))
def test_sympy__stats__symbolic_multivariate_probability__CrossCovarianceMatrix():
from sympy.stats import CrossCovarianceMatrix
from sympy.stats.rv import RandomMatrixSymbol
assert _test_args(CrossCovarianceMatrix(RandomMatrixSymbol('R', 3, 1),
RandomMatrixSymbol('X', 3, 1)))
def test_sympy__stats__matrix_distributions__MatrixPSpace():
from sympy.stats.matrix_distributions import MatrixDistribution, MatrixPSpace
from sympy.matrices.dense import Matrix
M = MatrixDistribution(1, Matrix([[1, 0], [0, 1]]))
assert _test_args(MatrixPSpace('M', M, 2, 2))
def test_sympy__stats__matrix_distributions__MatrixDistribution():
from sympy.stats.matrix_distributions import MatrixDistribution
from sympy.matrices.dense import Matrix
assert _test_args(MatrixDistribution(1, Matrix([[1, 0], [0, 1]])))
def test_sympy__stats__matrix_distributions__MatrixGammaDistribution():
from sympy.stats.matrix_distributions import MatrixGammaDistribution
from sympy.matrices.dense import Matrix
assert _test_args(MatrixGammaDistribution(3, 4, Matrix([[1, 0], [0, 1]])))
def test_sympy__stats__matrix_distributions__WishartDistribution():
from sympy.stats.matrix_distributions import WishartDistribution
from sympy.matrices.dense import Matrix
assert _test_args(WishartDistribution(3, Matrix([[1, 0], [0, 1]])))
def test_sympy__stats__matrix_distributions__MatrixNormalDistribution():
from sympy.stats.matrix_distributions import MatrixNormalDistribution
from sympy.matrices.expressions.matexpr import MatrixSymbol
L = MatrixSymbol('L', 1, 2)
S1 = MatrixSymbol('S1', 1, 1)
S2 = MatrixSymbol('S2', 2, 2)
assert _test_args(MatrixNormalDistribution(L, S1, S2))
def test_sympy__stats__matrix_distributions__MatrixStudentTDistribution():
from sympy.stats.matrix_distributions import MatrixStudentTDistribution
from sympy.matrices.expressions.matexpr import MatrixSymbol
v = symbols('v', positive=True)
Omega = MatrixSymbol('Omega', 3, 3)
Sigma = MatrixSymbol('Sigma', 1, 1)
Location = MatrixSymbol('Location', 1, 3)
assert _test_args(MatrixStudentTDistribution(v, Location, Omega, Sigma))
def test_sympy__utilities__matchpy_connector__WildDot():
from sympy.utilities.matchpy_connector import WildDot
assert _test_args(WildDot("w_"))
def test_sympy__utilities__matchpy_connector__WildPlus():
from sympy.utilities.matchpy_connector import WildPlus
assert _test_args(WildPlus("w__"))
def test_sympy__utilities__matchpy_connector__WildStar():
from sympy.utilities.matchpy_connector import WildStar
assert _test_args(WildStar("w___"))
def test_sympy__core__symbol__Str():
from sympy.core.symbol import Str
assert _test_args(Str('t'))
def test_sympy__core__symbol__Dummy():
from sympy.core.symbol import Dummy
assert _test_args(Dummy('t'))
def test_sympy__core__symbol__Symbol():
from sympy.core.symbol import Symbol
assert _test_args(Symbol('t'))
def test_sympy__core__symbol__Wild():
from sympy.core.symbol import Wild
assert _test_args(Wild('x', exclude=[x]))
@SKIP("abstract class")
def test_sympy__functions__combinatorial__factorials__CombinatorialFunction():
pass
def test_sympy__functions__combinatorial__factorials__FallingFactorial():
from sympy.functions.combinatorial.factorials import FallingFactorial
assert _test_args(FallingFactorial(2, x))
def test_sympy__functions__combinatorial__factorials__MultiFactorial():
from sympy.functions.combinatorial.factorials import MultiFactorial
assert _test_args(MultiFactorial(x))
def test_sympy__functions__combinatorial__factorials__RisingFactorial():
from sympy.functions.combinatorial.factorials import RisingFactorial
assert _test_args(RisingFactorial(2, x))
def test_sympy__functions__combinatorial__factorials__binomial():
from sympy.functions.combinatorial.factorials import binomial
assert _test_args(binomial(2, x))
def test_sympy__functions__combinatorial__factorials__subfactorial():
from sympy.functions.combinatorial.factorials import subfactorial
assert _test_args(subfactorial(x))
def test_sympy__functions__combinatorial__factorials__factorial():
from sympy.functions.combinatorial.factorials import factorial
assert _test_args(factorial(x))
def test_sympy__functions__combinatorial__factorials__factorial2():
from sympy.functions.combinatorial.factorials import factorial2
assert _test_args(factorial2(x))
def test_sympy__functions__combinatorial__numbers__bell():
from sympy.functions.combinatorial.numbers import bell
assert _test_args(bell(x, y))
def test_sympy__functions__combinatorial__numbers__bernoulli():
from sympy.functions.combinatorial.numbers import bernoulli
assert _test_args(bernoulli(x))
def test_sympy__functions__combinatorial__numbers__catalan():
from sympy.functions.combinatorial.numbers import catalan
assert _test_args(catalan(x))
def test_sympy__functions__combinatorial__numbers__genocchi():
from sympy.functions.combinatorial.numbers import genocchi
assert _test_args(genocchi(x))
def test_sympy__functions__combinatorial__numbers__euler():
from sympy.functions.combinatorial.numbers import euler
assert _test_args(euler(x))
def test_sympy__functions__combinatorial__numbers__andre():
from sympy.functions.combinatorial.numbers import andre
assert _test_args(andre(x))
def test_sympy__functions__combinatorial__numbers__carmichael():
from sympy.functions.combinatorial.numbers import carmichael
assert _test_args(carmichael(x))
def test_sympy__functions__combinatorial__numbers__motzkin():
from sympy.functions.combinatorial.numbers import motzkin
assert _test_args(motzkin(5))
def test_sympy__functions__combinatorial__numbers__fibonacci():
from sympy.functions.combinatorial.numbers import fibonacci
assert _test_args(fibonacci(x))
def test_sympy__functions__combinatorial__numbers__tribonacci():
from sympy.functions.combinatorial.numbers import tribonacci
assert _test_args(tribonacci(x))
def test_sympy__functions__combinatorial__numbers__harmonic():
from sympy.functions.combinatorial.numbers import harmonic
assert _test_args(harmonic(x, 2))
def test_sympy__functions__combinatorial__numbers__lucas():
from sympy.functions.combinatorial.numbers import lucas
assert _test_args(lucas(x))
def test_sympy__functions__combinatorial__numbers__partition():
from sympy.core.symbol import Symbol
from sympy.functions.combinatorial.numbers import partition
assert _test_args(partition(Symbol('a', integer=True)))
def test_sympy__functions__elementary__complexes__Abs():
from sympy.functions.elementary.complexes import Abs
assert _test_args(Abs(x))
def test_sympy__functions__elementary__complexes__adjoint():
from sympy.functions.elementary.complexes import adjoint
assert _test_args(adjoint(x))
def test_sympy__functions__elementary__complexes__arg():
from sympy.functions.elementary.complexes import arg
assert _test_args(arg(x))
def test_sympy__functions__elementary__complexes__conjugate():
from sympy.functions.elementary.complexes import conjugate
assert _test_args(conjugate(x))
def test_sympy__functions__elementary__complexes__im():
from sympy.functions.elementary.complexes import im
assert _test_args(im(x))
def test_sympy__functions__elementary__complexes__re():
from sympy.functions.elementary.complexes import re
assert _test_args(re(x))
def test_sympy__functions__elementary__complexes__sign():
from sympy.functions.elementary.complexes import sign
assert _test_args(sign(x))
def test_sympy__functions__elementary__complexes__polar_lift():
from sympy.functions.elementary.complexes import polar_lift
assert _test_args(polar_lift(x))
def test_sympy__functions__elementary__complexes__periodic_argument():
from sympy.functions.elementary.complexes import periodic_argument
assert _test_args(periodic_argument(x, y))
def test_sympy__functions__elementary__complexes__principal_branch():
from sympy.functions.elementary.complexes import principal_branch
assert _test_args(principal_branch(x, y))
def test_sympy__functions__elementary__complexes__transpose():
from sympy.functions.elementary.complexes import transpose
assert _test_args(transpose(x))
def test_sympy__functions__elementary__exponential__LambertW():
from sympy.functions.elementary.exponential import LambertW
assert _test_args(LambertW(2))
@SKIP("abstract class")
def test_sympy__functions__elementary__exponential__ExpBase():
pass
def test_sympy__functions__elementary__exponential__exp():
from sympy.functions.elementary.exponential import exp
assert _test_args(exp(2))
def test_sympy__functions__elementary__exponential__exp_polar():
from sympy.functions.elementary.exponential import exp_polar
assert _test_args(exp_polar(2))
def test_sympy__functions__elementary__exponential__log():
from sympy.functions.elementary.exponential import log
assert _test_args(log(2))
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__HyperbolicFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__ReciprocalHyperbolicFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__hyperbolic__InverseHyperbolicFunction():
pass
def test_sympy__functions__elementary__hyperbolic__acosh():
from sympy.functions.elementary.hyperbolic import acosh
assert _test_args(acosh(2))
def test_sympy__functions__elementary__hyperbolic__acoth():
from sympy.functions.elementary.hyperbolic import acoth
assert _test_args(acoth(2))
def test_sympy__functions__elementary__hyperbolic__asinh():
from sympy.functions.elementary.hyperbolic import asinh
assert _test_args(asinh(2))
def test_sympy__functions__elementary__hyperbolic__atanh():
from sympy.functions.elementary.hyperbolic import atanh
assert _test_args(atanh(2))
def test_sympy__functions__elementary__hyperbolic__asech():
from sympy.functions.elementary.hyperbolic import asech
assert _test_args(asech(x))
def test_sympy__functions__elementary__hyperbolic__acsch():
from sympy.functions.elementary.hyperbolic import acsch
assert _test_args(acsch(x))
def test_sympy__functions__elementary__hyperbolic__cosh():
from sympy.functions.elementary.hyperbolic import cosh
assert _test_args(cosh(2))
def test_sympy__functions__elementary__hyperbolic__coth():
from sympy.functions.elementary.hyperbolic import coth
assert _test_args(coth(2))
def test_sympy__functions__elementary__hyperbolic__csch():
from sympy.functions.elementary.hyperbolic import csch
assert _test_args(csch(2))
def test_sympy__functions__elementary__hyperbolic__sech():
from sympy.functions.elementary.hyperbolic import sech
assert _test_args(sech(2))
def test_sympy__functions__elementary__hyperbolic__sinh():
from sympy.functions.elementary.hyperbolic import sinh
assert _test_args(sinh(2))
def test_sympy__functions__elementary__hyperbolic__tanh():
from sympy.functions.elementary.hyperbolic import tanh
assert _test_args(tanh(2))
@SKIP("abstract class")
def test_sympy__functions__elementary__integers__RoundFunction():
pass
def test_sympy__functions__elementary__integers__ceiling():
from sympy.functions.elementary.integers import ceiling
assert _test_args(ceiling(x))
def test_sympy__functions__elementary__integers__floor():
from sympy.functions.elementary.integers import floor
assert _test_args(floor(x))
def test_sympy__functions__elementary__integers__frac():
from sympy.functions.elementary.integers import frac
assert _test_args(frac(x))
def test_sympy__functions__elementary__miscellaneous__IdentityFunction():
from sympy.functions.elementary.miscellaneous import IdentityFunction
assert _test_args(IdentityFunction())
def test_sympy__functions__elementary__miscellaneous__Max():
from sympy.functions.elementary.miscellaneous import Max
assert _test_args(Max(x, 2))
def test_sympy__functions__elementary__miscellaneous__Min():
from sympy.functions.elementary.miscellaneous import Min
assert _test_args(Min(x, 2))
@SKIP("abstract class")
def test_sympy__functions__elementary__miscellaneous__MinMaxBase():
pass
def test_sympy__functions__elementary__miscellaneous__Rem():
from sympy.functions.elementary.miscellaneous import Rem
assert _test_args(Rem(x, 2))
def test_sympy__functions__elementary__piecewise__ExprCondPair():
from sympy.functions.elementary.piecewise import ExprCondPair
assert _test_args(ExprCondPair(1, True))
def test_sympy__functions__elementary__piecewise__Piecewise():
from sympy.functions.elementary.piecewise import Piecewise
assert _test_args(Piecewise((1, x >= 0), (0, True)))
@SKIP("abstract class")
def test_sympy__functions__elementary__trigonometric__TrigonometricFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__trigonometric__ReciprocalTrigonometricFunction():
pass
@SKIP("abstract class")
def test_sympy__functions__elementary__trigonometric__InverseTrigonometricFunction():
pass
def test_sympy__functions__elementary__trigonometric__acos():
from sympy.functions.elementary.trigonometric import acos
assert _test_args(acos(2))
def test_sympy__functions__elementary__trigonometric__acot():
from sympy.functions.elementary.trigonometric import acot
assert _test_args(acot(2))
def test_sympy__functions__elementary__trigonometric__asin():
from sympy.functions.elementary.trigonometric import asin
assert _test_args(asin(2))
def test_sympy__functions__elementary__trigonometric__asec():
from sympy.functions.elementary.trigonometric import asec
assert _test_args(asec(x))
def test_sympy__functions__elementary__trigonometric__acsc():
from sympy.functions.elementary.trigonometric import acsc
assert _test_args(acsc(x))
def test_sympy__functions__elementary__trigonometric__atan():
from sympy.functions.elementary.trigonometric import atan
assert _test_args(atan(2))
def test_sympy__functions__elementary__trigonometric__atan2():
from sympy.functions.elementary.trigonometric import atan2
assert _test_args(atan2(2, 3))
def test_sympy__functions__elementary__trigonometric__cos():
from sympy.functions.elementary.trigonometric import cos
assert _test_args(cos(2))
def test_sympy__functions__elementary__trigonometric__csc():
from sympy.functions.elementary.trigonometric import csc
assert _test_args(csc(2))
def test_sympy__functions__elementary__trigonometric__cot():
from sympy.functions.elementary.trigonometric import cot
assert _test_args(cot(2))
def test_sympy__functions__elementary__trigonometric__sin():
assert _test_args(sin(2))
def test_sympy__functions__elementary__trigonometric__sinc():
from sympy.functions.elementary.trigonometric import sinc
assert _test_args(sinc(2))
def test_sympy__functions__elementary__trigonometric__sec():
from sympy.functions.elementary.trigonometric import sec
assert _test_args(sec(2))
def test_sympy__functions__elementary__trigonometric__tan():
from sympy.functions.elementary.trigonometric import tan
assert _test_args(tan(2))
@SKIP("abstract class")
def test_sympy__functions__special__bessel__BesselBase():
pass
@SKIP("abstract class")
def test_sympy__functions__special__bessel__SphericalBesselBase():
pass
@SKIP("abstract class")
def test_sympy__functions__special__bessel__SphericalHankelBase():
pass
def test_sympy__functions__special__bessel__besseli():
from sympy.functions.special.bessel import besseli
assert _test_args(besseli(x, 1))
def test_sympy__functions__special__bessel__besselj():
from sympy.functions.special.bessel import besselj
assert _test_args(besselj(x, 1))
def test_sympy__functions__special__bessel__besselk():
from sympy.functions.special.bessel import besselk
assert _test_args(besselk(x, 1))
def test_sympy__functions__special__bessel__bessely():
from sympy.functions.special.bessel import bessely
assert _test_args(bessely(x, 1))
def test_sympy__functions__special__bessel__hankel1():
from sympy.functions.special.bessel import hankel1
assert _test_args(hankel1(x, 1))
def test_sympy__functions__special__bessel__hankel2():
from sympy.functions.special.bessel import hankel2
assert _test_args(hankel2(x, 1))
def test_sympy__functions__special__bessel__jn():
from sympy.functions.special.bessel import jn
assert _test_args(jn(0, x))
def test_sympy__functions__special__bessel__yn():
from sympy.functions.special.bessel import yn
assert _test_args(yn(0, x))
def test_sympy__functions__special__bessel__hn1():
from sympy.functions.special.bessel import hn1
assert _test_args(hn1(0, x))
def test_sympy__functions__special__bessel__hn2():
from sympy.functions.special.bessel import hn2
assert _test_args(hn2(0, x))
def test_sympy__functions__special__bessel__AiryBase():
pass
def test_sympy__functions__special__bessel__airyai():
from sympy.functions.special.bessel import airyai
assert _test_args(airyai(2))
def test_sympy__functions__special__bessel__airybi():
from sympy.functions.special.bessel import airybi
assert _test_args(airybi(2))
def test_sympy__functions__special__bessel__airyaiprime():
from sympy.functions.special.bessel import airyaiprime
assert _test_args(airyaiprime(2))
def test_sympy__functions__special__bessel__airybiprime():
from sympy.functions.special.bessel import airybiprime
assert _test_args(airybiprime(2))
def test_sympy__functions__special__bessel__marcumq():
from sympy.functions.special.bessel import marcumq
assert _test_args(marcumq(x, y, z))
def test_sympy__functions__special__elliptic_integrals__elliptic_k():
from sympy.functions.special.elliptic_integrals import elliptic_k as K
assert _test_args(K(x))
def test_sympy__functions__special__elliptic_integrals__elliptic_f():
from sympy.functions.special.elliptic_integrals import elliptic_f as F
assert _test_args(F(x, y))
def test_sympy__functions__special__elliptic_integrals__elliptic_e():
from sympy.functions.special.elliptic_integrals import elliptic_e as E
assert _test_args(E(x))
assert _test_args(E(x, y))
def test_sympy__functions__special__elliptic_integrals__elliptic_pi():
from sympy.functions.special.elliptic_integrals import elliptic_pi as P
assert _test_args(P(x, y))
assert _test_args(P(x, y, z))
def test_sympy__functions__special__delta_functions__DiracDelta():
from sympy.functions.special.delta_functions import DiracDelta
assert _test_args(DiracDelta(x, 1))
def test_sympy__functions__special__singularity_functions__SingularityFunction():
from sympy.functions.special.singularity_functions import SingularityFunction
assert _test_args(SingularityFunction(x, y, z))
def test_sympy__functions__special__delta_functions__Heaviside():
from sympy.functions.special.delta_functions import Heaviside
assert _test_args(Heaviside(x))
def test_sympy__functions__special__error_functions__erf():
from sympy.functions.special.error_functions import erf
assert _test_args(erf(2))
def test_sympy__functions__special__error_functions__erfc():
from sympy.functions.special.error_functions import erfc
assert _test_args(erfc(2))
def test_sympy__functions__special__error_functions__erfi():
from sympy.functions.special.error_functions import erfi
assert _test_args(erfi(2))
def test_sympy__functions__special__error_functions__erf2():
from sympy.functions.special.error_functions import erf2
assert _test_args(erf2(2, 3))
def test_sympy__functions__special__error_functions__erfinv():
from sympy.functions.special.error_functions import erfinv
assert _test_args(erfinv(2))
def test_sympy__functions__special__error_functions__erfcinv():
from sympy.functions.special.error_functions import erfcinv
assert _test_args(erfcinv(2))
def test_sympy__functions__special__error_functions__erf2inv():
from sympy.functions.special.error_functions import erf2inv
assert _test_args(erf2inv(2, 3))
@SKIP("abstract class")
def test_sympy__functions__special__error_functions__FresnelIntegral():
pass
def test_sympy__functions__special__error_functions__fresnels():
from sympy.functions.special.error_functions import fresnels
assert _test_args(fresnels(2))
def test_sympy__functions__special__error_functions__fresnelc():
from sympy.functions.special.error_functions import fresnelc
assert _test_args(fresnelc(2))
def test_sympy__functions__special__error_functions__erfs():
from sympy.functions.special.error_functions import _erfs
assert _test_args(_erfs(2))
def test_sympy__functions__special__error_functions__Ei():
from sympy.functions.special.error_functions import Ei
assert _test_args(Ei(2))
def test_sympy__functions__special__error_functions__li():
from sympy.functions.special.error_functions import li
assert _test_args(li(2))
def test_sympy__functions__special__error_functions__Li():
from sympy.functions.special.error_functions import Li
assert _test_args(Li(5))
@SKIP("abstract class")
def test_sympy__functions__special__error_functions__TrigonometricIntegral():
pass
def test_sympy__functions__special__error_functions__Si():
from sympy.functions.special.error_functions import Si
assert _test_args(Si(2))
def test_sympy__functions__special__error_functions__Ci():
from sympy.functions.special.error_functions import Ci
assert _test_args(Ci(2))
def test_sympy__functions__special__error_functions__Shi():
from sympy.functions.special.error_functions import Shi
assert _test_args(Shi(2))
def test_sympy__functions__special__error_functions__Chi():
from sympy.functions.special.error_functions import Chi
assert _test_args(Chi(2))
def test_sympy__functions__special__error_functions__expint():
from sympy.functions.special.error_functions import expint
assert _test_args(expint(y, x))
def test_sympy__functions__special__gamma_functions__gamma():
from sympy.functions.special.gamma_functions import gamma
assert _test_args(gamma(x))
def test_sympy__functions__special__gamma_functions__loggamma():
from sympy.functions.special.gamma_functions import loggamma
assert _test_args(loggamma(x))
def test_sympy__functions__special__gamma_functions__lowergamma():
from sympy.functions.special.gamma_functions import lowergamma
assert _test_args(lowergamma(x, 2))
def test_sympy__functions__special__gamma_functions__polygamma():
from sympy.functions.special.gamma_functions import polygamma
assert _test_args(polygamma(x, 2))
def test_sympy__functions__special__gamma_functions__digamma():
from sympy.functions.special.gamma_functions import digamma
assert _test_args(digamma(x))
def test_sympy__functions__special__gamma_functions__trigamma():
from sympy.functions.special.gamma_functions import trigamma
assert _test_args(trigamma(x))
def test_sympy__functions__special__gamma_functions__uppergamma():
from sympy.functions.special.gamma_functions import uppergamma
assert _test_args(uppergamma(x, 2))
def test_sympy__functions__special__gamma_functions__multigamma():
from sympy.functions.special.gamma_functions import multigamma
assert _test_args(multigamma(x, 1))
def test_sympy__functions__special__beta_functions__beta():
from sympy.functions.special.beta_functions import beta
assert _test_args(beta(x))
assert _test_args(beta(x, x))
def test_sympy__functions__special__beta_functions__betainc():
from sympy.functions.special.beta_functions import betainc
assert _test_args(betainc(a, b, x, y))
def test_sympy__functions__special__beta_functions__betainc_regularized():
from sympy.functions.special.beta_functions import betainc_regularized
assert _test_args(betainc_regularized(a, b, x, y))
def test_sympy__functions__special__mathieu_functions__MathieuBase():
pass
def test_sympy__functions__special__mathieu_functions__mathieus():
from sympy.functions.special.mathieu_functions import mathieus
assert _test_args(mathieus(1, 1, 1))
def test_sympy__functions__special__mathieu_functions__mathieuc():
from sympy.functions.special.mathieu_functions import mathieuc
assert _test_args(mathieuc(1, 1, 1))
def test_sympy__functions__special__mathieu_functions__mathieusprime():
from sympy.functions.special.mathieu_functions import mathieusprime
assert _test_args(mathieusprime(1, 1, 1))
def test_sympy__functions__special__mathieu_functions__mathieucprime():
from sympy.functions.special.mathieu_functions import mathieucprime
assert _test_args(mathieucprime(1, 1, 1))
@SKIP("abstract class")
def test_sympy__functions__special__hyper__TupleParametersBase():
pass
@SKIP("abstract class")
def test_sympy__functions__special__hyper__TupleArg():
pass
def test_sympy__functions__special__hyper__hyper():
from sympy.functions.special.hyper import hyper
assert _test_args(hyper([1, 2, 3], [4, 5], x))
def test_sympy__functions__special__hyper__meijerg():
from sympy.functions.special.hyper import meijerg
assert _test_args(meijerg([1, 2, 3], [4, 5], [6], [], x))
@SKIP("abstract class")
def test_sympy__functions__special__hyper__HyperRep():
pass
def test_sympy__functions__special__hyper__HyperRep_power1():
from sympy.functions.special.hyper import HyperRep_power1
assert _test_args(HyperRep_power1(x, y))
def test_sympy__functions__special__hyper__HyperRep_power2():
from sympy.functions.special.hyper import HyperRep_power2
assert _test_args(HyperRep_power2(x, y))
def test_sympy__functions__special__hyper__HyperRep_log1():
from sympy.functions.special.hyper import HyperRep_log1
assert _test_args(HyperRep_log1(x))
def test_sympy__functions__special__hyper__HyperRep_atanh():
from sympy.functions.special.hyper import HyperRep_atanh
assert _test_args(HyperRep_atanh(x))
def test_sympy__functions__special__hyper__HyperRep_asin1():
from sympy.functions.special.hyper import HyperRep_asin1
assert _test_args(HyperRep_asin1(x))
def test_sympy__functions__special__hyper__HyperRep_asin2():
from sympy.functions.special.hyper import HyperRep_asin2
assert _test_args(HyperRep_asin2(x))
def test_sympy__functions__special__hyper__HyperRep_sqrts1():
from sympy.functions.special.hyper import HyperRep_sqrts1
assert _test_args(HyperRep_sqrts1(x, y))
def test_sympy__functions__special__hyper__HyperRep_sqrts2():
from sympy.functions.special.hyper import HyperRep_sqrts2
assert _test_args(HyperRep_sqrts2(x, y))
def test_sympy__functions__special__hyper__HyperRep_log2():
from sympy.functions.special.hyper import HyperRep_log2
assert _test_args(HyperRep_log2(x))
def test_sympy__functions__special__hyper__HyperRep_cosasin():
from sympy.functions.special.hyper import HyperRep_cosasin
assert _test_args(HyperRep_cosasin(x, y))
def test_sympy__functions__special__hyper__HyperRep_sinasin():
from sympy.functions.special.hyper import HyperRep_sinasin
assert _test_args(HyperRep_sinasin(x, y))
def test_sympy__functions__special__hyper__appellf1():
from sympy.functions.special.hyper import appellf1
a, b1, b2, c, x, y = symbols('a b1 b2 c x y')
assert _test_args(appellf1(a, b1, b2, c, x, y))
@SKIP("abstract class")
def test_sympy__functions__special__polynomials__OrthogonalPolynomial():
pass
def test_sympy__functions__special__polynomials__jacobi():
from sympy.functions.special.polynomials import jacobi
assert _test_args(jacobi(x, y, 2, 2))
def test_sympy__functions__special__polynomials__gegenbauer():
from sympy.functions.special.polynomials import gegenbauer
assert _test_args(gegenbauer(x, 2, 2))
def test_sympy__functions__special__polynomials__chebyshevt():
from sympy.functions.special.polynomials import chebyshevt
assert _test_args(chebyshevt(x, 2))
def test_sympy__functions__special__polynomials__chebyshevt_root():
from sympy.functions.special.polynomials import chebyshevt_root
assert _test_args(chebyshevt_root(3, 2))
def test_sympy__functions__special__polynomials__chebyshevu():
from sympy.functions.special.polynomials import chebyshevu
assert _test_args(chebyshevu(x, 2))
def test_sympy__functions__special__polynomials__chebyshevu_root():
from sympy.functions.special.polynomials import chebyshevu_root
assert _test_args(chebyshevu_root(3, 2))
def test_sympy__functions__special__polynomials__hermite():
from sympy.functions.special.polynomials import hermite
assert _test_args(hermite(x, 2))
def test_sympy__functions__special__polynomials__hermite_prob():
from sympy.functions.special.polynomials import hermite_prob
assert _test_args(hermite_prob(x, 2))
def test_sympy__functions__special__polynomials__legendre():
from sympy.functions.special.polynomials import legendre
assert _test_args(legendre(x, 2))
def test_sympy__functions__special__polynomials__assoc_legendre():
from sympy.functions.special.polynomials import assoc_legendre
assert _test_args(assoc_legendre(x, 0, y))
def test_sympy__functions__special__polynomials__laguerre():
from sympy.functions.special.polynomials import laguerre
assert _test_args(laguerre(x, 2))
def test_sympy__functions__special__polynomials__assoc_laguerre():
from sympy.functions.special.polynomials import assoc_laguerre
assert _test_args(assoc_laguerre(x, 0, y))
def test_sympy__functions__special__spherical_harmonics__Ynm():
from sympy.functions.special.spherical_harmonics import Ynm
assert _test_args(Ynm(1, 1, x, y))
def test_sympy__functions__special__spherical_harmonics__Znm():
from sympy.functions.special.spherical_harmonics import Znm
assert _test_args(Znm(x, y, 1, 1))
def test_sympy__functions__special__tensor_functions__LeviCivita():
from sympy.functions.special.tensor_functions import LeviCivita
assert _test_args(LeviCivita(x, y, 2))
def test_sympy__functions__special__tensor_functions__KroneckerDelta():
from sympy.functions.special.tensor_functions import KroneckerDelta
assert _test_args(KroneckerDelta(x, y))
def test_sympy__functions__special__zeta_functions__dirichlet_eta():
from sympy.functions.special.zeta_functions import dirichlet_eta
assert _test_args(dirichlet_eta(x))
def test_sympy__functions__special__zeta_functions__riemann_xi():
from sympy.functions.special.zeta_functions import riemann_xi
assert _test_args(riemann_xi(x))
def test_sympy__functions__special__zeta_functions__zeta():
from sympy.functions.special.zeta_functions import zeta
assert _test_args(zeta(101))
def test_sympy__functions__special__zeta_functions__lerchphi():
from sympy.functions.special.zeta_functions import lerchphi
assert _test_args(lerchphi(x, y, z))
def test_sympy__functions__special__zeta_functions__polylog():
from sympy.functions.special.zeta_functions import polylog
assert _test_args(polylog(x, y))
def test_sympy__functions__special__zeta_functions__stieltjes():
from sympy.functions.special.zeta_functions import stieltjes
assert _test_args(stieltjes(x, y))
def test_sympy__integrals__integrals__Integral():
from sympy.integrals.integrals import Integral
assert _test_args(Integral(2, (x, 0, 1)))
def test_sympy__integrals__risch__NonElementaryIntegral():
from sympy.integrals.risch import NonElementaryIntegral
assert _test_args(NonElementaryIntegral(exp(-x**2), x))
@SKIP("abstract class")
def test_sympy__integrals__transforms__IntegralTransform():
pass
def test_sympy__integrals__transforms__MellinTransform():
from sympy.integrals.transforms import MellinTransform
assert _test_args(MellinTransform(2, x, y))
def test_sympy__integrals__transforms__InverseMellinTransform():
from sympy.integrals.transforms import InverseMellinTransform
assert _test_args(InverseMellinTransform(2, x, y, 0, 1))
def test_sympy__integrals__laplace__LaplaceTransform():
from sympy.integrals.laplace import LaplaceTransform
assert _test_args(LaplaceTransform(2, x, y))
def test_sympy__integrals__laplace__InverseLaplaceTransform():
from sympy.integrals.laplace import InverseLaplaceTransform
assert _test_args(InverseLaplaceTransform(2, x, y, 0))
@SKIP("abstract class")
def test_sympy__integrals__transforms__FourierTypeTransform():
pass
def test_sympy__integrals__transforms__InverseFourierTransform():
from sympy.integrals.transforms import InverseFourierTransform
assert _test_args(InverseFourierTransform(2, x, y))
def test_sympy__integrals__transforms__FourierTransform():
from sympy.integrals.transforms import FourierTransform
assert _test_args(FourierTransform(2, x, y))
@SKIP("abstract class")
def test_sympy__integrals__transforms__SineCosineTypeTransform():
pass
def test_sympy__integrals__transforms__InverseSineTransform():
from sympy.integrals.transforms import InverseSineTransform
assert _test_args(InverseSineTransform(2, x, y))
def test_sympy__integrals__transforms__SineTransform():
from sympy.integrals.transforms import SineTransform
assert _test_args(SineTransform(2, x, y))
def test_sympy__integrals__transforms__InverseCosineTransform():
from sympy.integrals.transforms import InverseCosineTransform
assert _test_args(InverseCosineTransform(2, x, y))
def test_sympy__integrals__transforms__CosineTransform():
from sympy.integrals.transforms import CosineTransform
assert _test_args(CosineTransform(2, x, y))
@SKIP("abstract class")
def test_sympy__integrals__transforms__HankelTypeTransform():
pass
def test_sympy__integrals__transforms__InverseHankelTransform():
from sympy.integrals.transforms import InverseHankelTransform
assert _test_args(InverseHankelTransform(2, x, y, 0))
def test_sympy__integrals__transforms__HankelTransform():
from sympy.integrals.transforms import HankelTransform
assert _test_args(HankelTransform(2, x, y, 0))
def test_sympy__liealgebras__cartan_type__Standard_Cartan():
from sympy.liealgebras.cartan_type import Standard_Cartan
assert _test_args(Standard_Cartan("A", 2))
def test_sympy__liealgebras__weyl_group__WeylGroup():
from sympy.liealgebras.weyl_group import WeylGroup
assert _test_args(WeylGroup("B4"))
def test_sympy__liealgebras__root_system__RootSystem():
from sympy.liealgebras.root_system import RootSystem
assert _test_args(RootSystem("A2"))
def test_sympy__liealgebras__type_a__TypeA():
from sympy.liealgebras.type_a import TypeA
assert _test_args(TypeA(2))
def test_sympy__liealgebras__type_b__TypeB():
from sympy.liealgebras.type_b import TypeB
assert _test_args(TypeB(4))
def test_sympy__liealgebras__type_c__TypeC():
from sympy.liealgebras.type_c import TypeC
assert _test_args(TypeC(4))
def test_sympy__liealgebras__type_d__TypeD():
from sympy.liealgebras.type_d import TypeD
assert _test_args(TypeD(4))
def test_sympy__liealgebras__type_e__TypeE():
from sympy.liealgebras.type_e import TypeE
assert _test_args(TypeE(6))
def test_sympy__liealgebras__type_f__TypeF():
from sympy.liealgebras.type_f import TypeF
assert _test_args(TypeF(4))
def test_sympy__liealgebras__type_g__TypeG():
from sympy.liealgebras.type_g import TypeG
assert _test_args(TypeG(2))
def test_sympy__logic__boolalg__And():
from sympy.logic.boolalg import And
assert _test_args(And(x, y, 1))
@SKIP("abstract class")
def test_sympy__logic__boolalg__Boolean():
pass
def test_sympy__logic__boolalg__BooleanFunction():
from sympy.logic.boolalg import BooleanFunction
assert _test_args(BooleanFunction(1, 2, 3))
@SKIP("abstract class")
def test_sympy__logic__boolalg__BooleanAtom():
pass
def test_sympy__logic__boolalg__BooleanTrue():
from sympy.logic.boolalg import true
assert _test_args(true)
def test_sympy__logic__boolalg__BooleanFalse():
from sympy.logic.boolalg import false
assert _test_args(false)
def test_sympy__logic__boolalg__Equivalent():
from sympy.logic.boolalg import Equivalent
assert _test_args(Equivalent(x, 2))
def test_sympy__logic__boolalg__ITE():
from sympy.logic.boolalg import ITE
assert _test_args(ITE(x, y, 1))
def test_sympy__logic__boolalg__Implies():
from sympy.logic.boolalg import Implies
assert _test_args(Implies(x, y))
def test_sympy__logic__boolalg__Nand():
from sympy.logic.boolalg import Nand
assert _test_args(Nand(x, y, 1))
def test_sympy__logic__boolalg__Nor():
from sympy.logic.boolalg import Nor
assert _test_args(Nor(x, y))
def test_sympy__logic__boolalg__Not():
from sympy.logic.boolalg import Not
assert _test_args(Not(x))
def test_sympy__logic__boolalg__Or():
from sympy.logic.boolalg import Or
assert _test_args(Or(x, y))
def test_sympy__logic__boolalg__Xor():
from sympy.logic.boolalg import Xor
assert _test_args(Xor(x, y, 2))
def test_sympy__logic__boolalg__Xnor():
from sympy.logic.boolalg import Xnor
assert _test_args(Xnor(x, y, 2))
def test_sympy__logic__boolalg__Exclusive():
from sympy.logic.boolalg import Exclusive
assert _test_args(Exclusive(x, y, z))
def test_sympy__matrices__matrices__DeferredVector():
from sympy.matrices.matrices import DeferredVector
assert _test_args(DeferredVector("X"))
@SKIP("abstract class")
def test_sympy__matrices__expressions__matexpr__MatrixBase():
pass
@SKIP("abstract class")
def test_sympy__matrices__immutable__ImmutableRepMatrix():
pass
def test_sympy__matrices__immutable__ImmutableDenseMatrix():
from sympy.matrices.immutable import ImmutableDenseMatrix
m = ImmutableDenseMatrix([[1, 2], [3, 4]])
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableDenseMatrix(1, 1, [1])
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableDenseMatrix(2, 2, lambda i, j: 1)
assert m[0, 0] is S.One
m = ImmutableDenseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j))
assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympified
assert _test_args(m)
assert _test_args(Basic(*list(m)))
def test_sympy__matrices__immutable__ImmutableSparseMatrix():
from sympy.matrices.immutable import ImmutableSparseMatrix
m = ImmutableSparseMatrix([[1, 2], [3, 4]])
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableSparseMatrix(1, 1, {(0, 0): 1})
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableSparseMatrix(1, 1, [1])
assert _test_args(m)
assert _test_args(Basic(*list(m)))
m = ImmutableSparseMatrix(2, 2, lambda i, j: 1)
assert m[0, 0] is S.One
m = ImmutableSparseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j))
assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympified
assert _test_args(m)
assert _test_args(Basic(*list(m)))
def test_sympy__matrices__expressions__slice__MatrixSlice():
from sympy.matrices.expressions.slice import MatrixSlice
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', 4, 4)
assert _test_args(MatrixSlice(X, (0, 2), (0, 2)))
def test_sympy__matrices__expressions__applyfunc__ElementwiseApplyFunction():
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol("X", x, x)
func = Lambda(x, x**2)
assert _test_args(ElementwiseApplyFunction(func, X))
def test_sympy__matrices__expressions__blockmatrix__BlockDiagMatrix():
from sympy.matrices.expressions.blockmatrix import BlockDiagMatrix
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, x)
Y = MatrixSymbol('Y', y, y)
assert _test_args(BlockDiagMatrix(X, Y))
def test_sympy__matrices__expressions__blockmatrix__BlockMatrix():
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix
X = MatrixSymbol('X', x, x)
Y = MatrixSymbol('Y', y, y)
Z = MatrixSymbol('Z', x, y)
O = ZeroMatrix(y, x)
assert _test_args(BlockMatrix([[X, Z], [O, Y]]))
def test_sympy__matrices__expressions__inverse__Inverse():
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Inverse(MatrixSymbol('A', 3, 3)))
def test_sympy__matrices__expressions__matadd__MatAdd():
from sympy.matrices.expressions.matadd import MatAdd
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', x, y)
assert _test_args(MatAdd(X, Y))
@SKIP("abstract class")
def test_sympy__matrices__expressions__matexpr__MatrixExpr():
pass
def test_sympy__matrices__expressions__matexpr__MatrixElement():
from sympy.matrices.expressions.matexpr import MatrixSymbol, MatrixElement
from sympy.core.singleton import S
assert _test_args(MatrixElement(MatrixSymbol('A', 3, 5), S(2), S(3)))
def test_sympy__matrices__expressions__matexpr__MatrixSymbol():
from sympy.matrices.expressions.matexpr import MatrixSymbol
assert _test_args(MatrixSymbol('A', 3, 5))
def test_sympy__matrices__expressions__special__OneMatrix():
from sympy.matrices.expressions.special import OneMatrix
assert _test_args(OneMatrix(3, 5))
def test_sympy__matrices__expressions__special__ZeroMatrix():
from sympy.matrices.expressions.special import ZeroMatrix
assert _test_args(ZeroMatrix(3, 5))
def test_sympy__matrices__expressions__special__GenericZeroMatrix():
from sympy.matrices.expressions.special import GenericZeroMatrix
assert _test_args(GenericZeroMatrix())
def test_sympy__matrices__expressions__special__Identity():
from sympy.matrices.expressions.special import Identity
assert _test_args(Identity(3))
def test_sympy__matrices__expressions__special__GenericIdentity():
from sympy.matrices.expressions.special import GenericIdentity
assert _test_args(GenericIdentity())
def test_sympy__matrices__expressions__sets__MatrixSet():
from sympy.matrices.expressions.sets import MatrixSet
from sympy.core.singleton import S
assert _test_args(MatrixSet(2, 2, S.Reals))
def test_sympy__matrices__expressions__matmul__MatMul():
from sympy.matrices.expressions.matmul import MatMul
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', y, x)
assert _test_args(MatMul(X, Y))
def test_sympy__matrices__expressions__dotproduct__DotProduct():
from sympy.matrices.expressions.dotproduct import DotProduct
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, 1)
Y = MatrixSymbol('Y', x, 1)
assert _test_args(DotProduct(X, Y))
def test_sympy__matrices__expressions__diagonal__DiagonalMatrix():
from sympy.matrices.expressions.diagonal import DiagonalMatrix
from sympy.matrices.expressions import MatrixSymbol
x = MatrixSymbol('x', 10, 1)
assert _test_args(DiagonalMatrix(x))
def test_sympy__matrices__expressions__diagonal__DiagonalOf():
from sympy.matrices.expressions.diagonal import DiagonalOf
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('x', 10, 10)
assert _test_args(DiagonalOf(X))
def test_sympy__matrices__expressions__diagonal__DiagMatrix():
from sympy.matrices.expressions.diagonal import DiagMatrix
from sympy.matrices.expressions import MatrixSymbol
x = MatrixSymbol('x', 10, 1)
assert _test_args(DiagMatrix(x))
def test_sympy__matrices__expressions__hadamard__HadamardProduct():
from sympy.matrices.expressions.hadamard import HadamardProduct
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', x, y)
assert _test_args(HadamardProduct(X, Y))
def test_sympy__matrices__expressions__hadamard__HadamardPower():
from sympy.matrices.expressions.hadamard import HadamardPower
from sympy.matrices.expressions import MatrixSymbol
from sympy.core.symbol import Symbol
X = MatrixSymbol('X', x, y)
n = Symbol("n")
assert _test_args(HadamardPower(X, n))
def test_sympy__matrices__expressions__kronecker__KroneckerProduct():
from sympy.matrices.expressions.kronecker import KroneckerProduct
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, y)
Y = MatrixSymbol('Y', x, y)
assert _test_args(KroneckerProduct(X, Y))
def test_sympy__matrices__expressions__matpow__MatPow():
from sympy.matrices.expressions.matpow import MatPow
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', x, x)
assert _test_args(MatPow(X, 2))
def test_sympy__matrices__expressions__transpose__Transpose():
from sympy.matrices.expressions.transpose import Transpose
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Transpose(MatrixSymbol('A', 3, 5)))
def test_sympy__matrices__expressions__adjoint__Adjoint():
from sympy.matrices.expressions.adjoint import Adjoint
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Adjoint(MatrixSymbol('A', 3, 5)))
def test_sympy__matrices__expressions__trace__Trace():
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Trace(MatrixSymbol('A', 3, 3)))
def test_sympy__matrices__expressions__determinant__Determinant():
from sympy.matrices.expressions.determinant import Determinant
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Determinant(MatrixSymbol('A', 3, 3)))
def test_sympy__matrices__expressions__determinant__Permanent():
from sympy.matrices.expressions.determinant import Permanent
from sympy.matrices.expressions import MatrixSymbol
assert _test_args(Permanent(MatrixSymbol('A', 3, 4)))
def test_sympy__matrices__expressions__funcmatrix__FunctionMatrix():
from sympy.matrices.expressions.funcmatrix import FunctionMatrix
from sympy.core.symbol import symbols
i, j = symbols('i,j')
assert _test_args(FunctionMatrix(3, 3, Lambda((i, j), i - j) ))
def test_sympy__matrices__expressions__fourier__DFT():
from sympy.matrices.expressions.fourier import DFT
from sympy.core.singleton import S
assert _test_args(DFT(S(2)))
def test_sympy__matrices__expressions__fourier__IDFT():
from sympy.matrices.expressions.fourier import IDFT
from sympy.core.singleton import S
assert _test_args(IDFT(S(2)))
from sympy.matrices.expressions import MatrixSymbol
X = MatrixSymbol('X', 10, 10)
def test_sympy__matrices__expressions__factorizations__LofLU():
from sympy.matrices.expressions.factorizations import LofLU
assert _test_args(LofLU(X))
def test_sympy__matrices__expressions__factorizations__UofLU():
from sympy.matrices.expressions.factorizations import UofLU
assert _test_args(UofLU(X))
def test_sympy__matrices__expressions__factorizations__QofQR():
from sympy.matrices.expressions.factorizations import QofQR
assert _test_args(QofQR(X))
def test_sympy__matrices__expressions__factorizations__RofQR():
from sympy.matrices.expressions.factorizations import RofQR
assert _test_args(RofQR(X))
def test_sympy__matrices__expressions__factorizations__LofCholesky():
from sympy.matrices.expressions.factorizations import LofCholesky
assert _test_args(LofCholesky(X))
def test_sympy__matrices__expressions__factorizations__UofCholesky():
from sympy.matrices.expressions.factorizations import UofCholesky
assert _test_args(UofCholesky(X))
def test_sympy__matrices__expressions__factorizations__EigenVectors():
from sympy.matrices.expressions.factorizations import EigenVectors
assert _test_args(EigenVectors(X))
def test_sympy__matrices__expressions__factorizations__EigenValues():
from sympy.matrices.expressions.factorizations import EigenValues
assert _test_args(EigenValues(X))
def test_sympy__matrices__expressions__factorizations__UofSVD():
from sympy.matrices.expressions.factorizations import UofSVD
assert _test_args(UofSVD(X))
def test_sympy__matrices__expressions__factorizations__VofSVD():
from sympy.matrices.expressions.factorizations import VofSVD
assert _test_args(VofSVD(X))
def test_sympy__matrices__expressions__factorizations__SofSVD():
from sympy.matrices.expressions.factorizations import SofSVD
assert _test_args(SofSVD(X))
@SKIP("abstract class")
def test_sympy__matrices__expressions__factorizations__Factorization():
pass
def test_sympy__matrices__expressions__permutation__PermutationMatrix():
from sympy.combinatorics import Permutation
from sympy.matrices.expressions.permutation import PermutationMatrix
assert _test_args(PermutationMatrix(Permutation([2, 0, 1])))
def test_sympy__matrices__expressions__permutation__MatrixPermute():
from sympy.combinatorics import Permutation
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.permutation import MatrixPermute
A = MatrixSymbol('A', 3, 3)
assert _test_args(MatrixPermute(A, Permutation([2, 0, 1])))
def test_sympy__matrices__expressions__companion__CompanionMatrix():
from sympy.core.symbol import Symbol
from sympy.matrices.expressions.companion import CompanionMatrix
from sympy.polys.polytools import Poly
x = Symbol('x')
p = Poly([1, 2, 3], x)
assert _test_args(CompanionMatrix(p))
def test_sympy__physics__vector__frame__CoordinateSym():
from sympy.physics.vector import CoordinateSym
from sympy.physics.vector import ReferenceFrame
assert _test_args(CoordinateSym('R_x', ReferenceFrame('R'), 0))
def test_sympy__physics__paulialgebra__Pauli():
from sympy.physics.paulialgebra import Pauli
assert _test_args(Pauli(1))
def test_sympy__physics__quantum__anticommutator__AntiCommutator():
from sympy.physics.quantum.anticommutator import AntiCommutator
assert _test_args(AntiCommutator(x, y))
def test_sympy__physics__quantum__cartesian__PositionBra3D():
from sympy.physics.quantum.cartesian import PositionBra3D
assert _test_args(PositionBra3D(x, y, z))
def test_sympy__physics__quantum__cartesian__PositionKet3D():
from sympy.physics.quantum.cartesian import PositionKet3D
assert _test_args(PositionKet3D(x, y, z))
def test_sympy__physics__quantum__cartesian__PositionState3D():
from sympy.physics.quantum.cartesian import PositionState3D
assert _test_args(PositionState3D(x, y, z))
def test_sympy__physics__quantum__cartesian__PxBra():
from sympy.physics.quantum.cartesian import PxBra
assert _test_args(PxBra(x, y, z))
def test_sympy__physics__quantum__cartesian__PxKet():
from sympy.physics.quantum.cartesian import PxKet
assert _test_args(PxKet(x, y, z))
def test_sympy__physics__quantum__cartesian__PxOp():
from sympy.physics.quantum.cartesian import PxOp
assert _test_args(PxOp(x, y, z))
def test_sympy__physics__quantum__cartesian__XBra():
from sympy.physics.quantum.cartesian import XBra
assert _test_args(XBra(x))
def test_sympy__physics__quantum__cartesian__XKet():
from sympy.physics.quantum.cartesian import XKet
assert _test_args(XKet(x))
def test_sympy__physics__quantum__cartesian__XOp():
from sympy.physics.quantum.cartesian import XOp
assert _test_args(XOp(x))
def test_sympy__physics__quantum__cartesian__YOp():
from sympy.physics.quantum.cartesian import YOp
assert _test_args(YOp(x))
def test_sympy__physics__quantum__cartesian__ZOp():
from sympy.physics.quantum.cartesian import ZOp
assert _test_args(ZOp(x))
def test_sympy__physics__quantum__cg__CG():
from sympy.physics.quantum.cg import CG
from sympy.core.singleton import S
assert _test_args(CG(Rational(3, 2), Rational(3, 2), S.Half, Rational(-1, 2), 1, 1))
def test_sympy__physics__quantum__cg__Wigner3j():
from sympy.physics.quantum.cg import Wigner3j
assert _test_args(Wigner3j(6, 0, 4, 0, 2, 0))
def test_sympy__physics__quantum__cg__Wigner6j():
from sympy.physics.quantum.cg import Wigner6j
assert _test_args(Wigner6j(1, 2, 3, 2, 1, 2))
def test_sympy__physics__quantum__cg__Wigner9j():
from sympy.physics.quantum.cg import Wigner9j
assert _test_args(Wigner9j(2, 1, 1, Rational(3, 2), S.Half, 1, S.Half, S.Half, 0))
def test_sympy__physics__quantum__circuitplot__Mz():
from sympy.physics.quantum.circuitplot import Mz
assert _test_args(Mz(0))
def test_sympy__physics__quantum__circuitplot__Mx():
from sympy.physics.quantum.circuitplot import Mx
assert _test_args(Mx(0))
def test_sympy__physics__quantum__commutator__Commutator():
from sympy.physics.quantum.commutator import Commutator
A, B = symbols('A,B', commutative=False)
assert _test_args(Commutator(A, B))
def test_sympy__physics__quantum__constants__HBar():
from sympy.physics.quantum.constants import HBar
assert _test_args(HBar())
def test_sympy__physics__quantum__dagger__Dagger():
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.state import Ket
assert _test_args(Dagger(Dagger(Ket('psi'))))
def test_sympy__physics__quantum__gate__CGate():
from sympy.physics.quantum.gate import CGate, Gate
assert _test_args(CGate((0, 1), Gate(2)))
def test_sympy__physics__quantum__gate__CGateS():
from sympy.physics.quantum.gate import CGateS, Gate
assert _test_args(CGateS((0, 1), Gate(2)))
def test_sympy__physics__quantum__gate__CNotGate():
from sympy.physics.quantum.gate import CNotGate
assert _test_args(CNotGate(0, 1))
def test_sympy__physics__quantum__gate__Gate():
from sympy.physics.quantum.gate import Gate
assert _test_args(Gate(0))
def test_sympy__physics__quantum__gate__HadamardGate():
from sympy.physics.quantum.gate import HadamardGate
assert _test_args(HadamardGate(0))
def test_sympy__physics__quantum__gate__IdentityGate():
from sympy.physics.quantum.gate import IdentityGate
assert _test_args(IdentityGate(0))
def test_sympy__physics__quantum__gate__OneQubitGate():
from sympy.physics.quantum.gate import OneQubitGate
assert _test_args(OneQubitGate(0))
def test_sympy__physics__quantum__gate__PhaseGate():
from sympy.physics.quantum.gate import PhaseGate
assert _test_args(PhaseGate(0))
def test_sympy__physics__quantum__gate__SwapGate():
from sympy.physics.quantum.gate import SwapGate
assert _test_args(SwapGate(0, 1))
def test_sympy__physics__quantum__gate__TGate():
from sympy.physics.quantum.gate import TGate
assert _test_args(TGate(0))
def test_sympy__physics__quantum__gate__TwoQubitGate():
from sympy.physics.quantum.gate import TwoQubitGate
assert _test_args(TwoQubitGate(0))
def test_sympy__physics__quantum__gate__UGate():
from sympy.physics.quantum.gate import UGate
from sympy.matrices.immutable import ImmutableDenseMatrix
from sympy.core.containers import Tuple
from sympy.core.numbers import Integer
assert _test_args(
UGate(Tuple(Integer(1)), ImmutableDenseMatrix([[1, 0], [0, 2]])))
def test_sympy__physics__quantum__gate__XGate():
from sympy.physics.quantum.gate import XGate
assert _test_args(XGate(0))
def test_sympy__physics__quantum__gate__YGate():
from sympy.physics.quantum.gate import YGate
assert _test_args(YGate(0))
def test_sympy__physics__quantum__gate__ZGate():
from sympy.physics.quantum.gate import ZGate
assert _test_args(ZGate(0))
def test_sympy__physics__quantum__grover__OracleGateFunction():
from sympy.physics.quantum.grover import OracleGateFunction
@OracleGateFunction
def f(qubit):
return
assert _test_args(f)
def test_sympy__physics__quantum__grover__OracleGate():
from sympy.physics.quantum.grover import OracleGate
def f(qubit):
return
assert _test_args(OracleGate(1,f))
def test_sympy__physics__quantum__grover__WGate():
from sympy.physics.quantum.grover import WGate
assert _test_args(WGate(1))
def test_sympy__physics__quantum__hilbert__ComplexSpace():
from sympy.physics.quantum.hilbert import ComplexSpace
assert _test_args(ComplexSpace(x))
def test_sympy__physics__quantum__hilbert__DirectSumHilbertSpace():
from sympy.physics.quantum.hilbert import DirectSumHilbertSpace, ComplexSpace, FockSpace
c = ComplexSpace(2)
f = FockSpace()
assert _test_args(DirectSumHilbertSpace(c, f))
def test_sympy__physics__quantum__hilbert__FockSpace():
from sympy.physics.quantum.hilbert import FockSpace
assert _test_args(FockSpace())
def test_sympy__physics__quantum__hilbert__HilbertSpace():
from sympy.physics.quantum.hilbert import HilbertSpace
assert _test_args(HilbertSpace())
def test_sympy__physics__quantum__hilbert__L2():
from sympy.physics.quantum.hilbert import L2
from sympy.core.numbers import oo
from sympy.sets.sets import Interval
assert _test_args(L2(Interval(0, oo)))
def test_sympy__physics__quantum__hilbert__TensorPowerHilbertSpace():
from sympy.physics.quantum.hilbert import TensorPowerHilbertSpace, FockSpace
f = FockSpace()
assert _test_args(TensorPowerHilbertSpace(f, 2))
def test_sympy__physics__quantum__hilbert__TensorProductHilbertSpace():
from sympy.physics.quantum.hilbert import TensorProductHilbertSpace, FockSpace, ComplexSpace
c = ComplexSpace(2)
f = FockSpace()
assert _test_args(TensorProductHilbertSpace(f, c))
def test_sympy__physics__quantum__innerproduct__InnerProduct():
from sympy.physics.quantum import Bra, Ket, InnerProduct
b = Bra('b')
k = Ket('k')
assert _test_args(InnerProduct(b, k))
def test_sympy__physics__quantum__operator__DifferentialOperator():
from sympy.physics.quantum.operator import DifferentialOperator
from sympy.core.function import (Derivative, Function)
f = Function('f')
assert _test_args(DifferentialOperator(1/x*Derivative(f(x), x), f(x)))
def test_sympy__physics__quantum__operator__HermitianOperator():
from sympy.physics.quantum.operator import HermitianOperator
assert _test_args(HermitianOperator('H'))
def test_sympy__physics__quantum__operator__IdentityOperator():
from sympy.physics.quantum.operator import IdentityOperator
assert _test_args(IdentityOperator(5))
def test_sympy__physics__quantum__operator__Operator():
from sympy.physics.quantum.operator import Operator
assert _test_args(Operator('A'))
def test_sympy__physics__quantum__operator__OuterProduct():
from sympy.physics.quantum.operator import OuterProduct
from sympy.physics.quantum import Ket, Bra
b = Bra('b')
k = Ket('k')
assert _test_args(OuterProduct(k, b))
def test_sympy__physics__quantum__operator__UnitaryOperator():
from sympy.physics.quantum.operator import UnitaryOperator
assert _test_args(UnitaryOperator('U'))
def test_sympy__physics__quantum__piab__PIABBra():
from sympy.physics.quantum.piab import PIABBra
assert _test_args(PIABBra('B'))
def test_sympy__physics__quantum__boson__BosonOp():
from sympy.physics.quantum.boson import BosonOp
assert _test_args(BosonOp('a'))
assert _test_args(BosonOp('a', False))
def test_sympy__physics__quantum__boson__BosonFockKet():
from sympy.physics.quantum.boson import BosonFockKet
assert _test_args(BosonFockKet(1))
def test_sympy__physics__quantum__boson__BosonFockBra():
from sympy.physics.quantum.boson import BosonFockBra
assert _test_args(BosonFockBra(1))
def test_sympy__physics__quantum__boson__BosonCoherentKet():
from sympy.physics.quantum.boson import BosonCoherentKet
assert _test_args(BosonCoherentKet(1))
def test_sympy__physics__quantum__boson__BosonCoherentBra():
from sympy.physics.quantum.boson import BosonCoherentBra
assert _test_args(BosonCoherentBra(1))
def test_sympy__physics__quantum__fermion__FermionOp():
from sympy.physics.quantum.fermion import FermionOp
assert _test_args(FermionOp('c'))
assert _test_args(FermionOp('c', False))
def test_sympy__physics__quantum__fermion__FermionFockKet():
from sympy.physics.quantum.fermion import FermionFockKet
assert _test_args(FermionFockKet(1))
def test_sympy__physics__quantum__fermion__FermionFockBra():
from sympy.physics.quantum.fermion import FermionFockBra
assert _test_args(FermionFockBra(1))
def test_sympy__physics__quantum__pauli__SigmaOpBase():
from sympy.physics.quantum.pauli import SigmaOpBase
assert _test_args(SigmaOpBase())
def test_sympy__physics__quantum__pauli__SigmaX():
from sympy.physics.quantum.pauli import SigmaX
assert _test_args(SigmaX())
def test_sympy__physics__quantum__pauli__SigmaY():
from sympy.physics.quantum.pauli import SigmaY
assert _test_args(SigmaY())
def test_sympy__physics__quantum__pauli__SigmaZ():
from sympy.physics.quantum.pauli import SigmaZ
assert _test_args(SigmaZ())
def test_sympy__physics__quantum__pauli__SigmaMinus():
from sympy.physics.quantum.pauli import SigmaMinus
assert _test_args(SigmaMinus())
def test_sympy__physics__quantum__pauli__SigmaPlus():
from sympy.physics.quantum.pauli import SigmaPlus
assert _test_args(SigmaPlus())
def test_sympy__physics__quantum__pauli__SigmaZKet():
from sympy.physics.quantum.pauli import SigmaZKet
assert _test_args(SigmaZKet(0))
def test_sympy__physics__quantum__pauli__SigmaZBra():
from sympy.physics.quantum.pauli import SigmaZBra
assert _test_args(SigmaZBra(0))
def test_sympy__physics__quantum__piab__PIABHamiltonian():
from sympy.physics.quantum.piab import PIABHamiltonian
assert _test_args(PIABHamiltonian('P'))
def test_sympy__physics__quantum__piab__PIABKet():
from sympy.physics.quantum.piab import PIABKet
assert _test_args(PIABKet('K'))
def test_sympy__physics__quantum__qexpr__QExpr():
from sympy.physics.quantum.qexpr import QExpr
assert _test_args(QExpr(0))
def test_sympy__physics__quantum__qft__Fourier():
from sympy.physics.quantum.qft import Fourier
assert _test_args(Fourier(0, 1))
def test_sympy__physics__quantum__qft__IQFT():
from sympy.physics.quantum.qft import IQFT
assert _test_args(IQFT(0, 1))
def test_sympy__physics__quantum__qft__QFT():
from sympy.physics.quantum.qft import QFT
assert _test_args(QFT(0, 1))
def test_sympy__physics__quantum__qft__RkGate():
from sympy.physics.quantum.qft import RkGate
assert _test_args(RkGate(0, 1))
def test_sympy__physics__quantum__qubit__IntQubit():
from sympy.physics.quantum.qubit import IntQubit
assert _test_args(IntQubit(0))
def test_sympy__physics__quantum__qubit__IntQubitBra():
from sympy.physics.quantum.qubit import IntQubitBra
assert _test_args(IntQubitBra(0))
def test_sympy__physics__quantum__qubit__IntQubitState():
from sympy.physics.quantum.qubit import IntQubitState, QubitState
assert _test_args(IntQubitState(QubitState(0, 1)))
def test_sympy__physics__quantum__qubit__Qubit():
from sympy.physics.quantum.qubit import Qubit
assert _test_args(Qubit(0, 0, 0))
def test_sympy__physics__quantum__qubit__QubitBra():
from sympy.physics.quantum.qubit import QubitBra
assert _test_args(QubitBra('1', 0))
def test_sympy__physics__quantum__qubit__QubitState():
from sympy.physics.quantum.qubit import QubitState
assert _test_args(QubitState(0, 1))
def test_sympy__physics__quantum__density__Density():
from sympy.physics.quantum.density import Density
from sympy.physics.quantum.state import Ket
assert _test_args(Density([Ket(0), 0.5], [Ket(1), 0.5]))
@SKIP("TODO: sympy.physics.quantum.shor: Cmod Not Implemented")
def test_sympy__physics__quantum__shor__CMod():
from sympy.physics.quantum.shor import CMod
assert _test_args(CMod())
def test_sympy__physics__quantum__spin__CoupledSpinState():
from sympy.physics.quantum.spin import CoupledSpinState
assert _test_args(CoupledSpinState(1, 0, (1, 1)))
assert _test_args(CoupledSpinState(1, 0, (1, S.Half, S.Half)))
assert _test_args(CoupledSpinState(
1, 0, (1, S.Half, S.Half), ((2, 3, S.Half), (1, 2, 1)) ))
j, m, j1, j2, j3, j12, x = symbols('j m j1:4 j12 x')
assert CoupledSpinState(
j, m, (j1, j2, j3)).subs(j2, x) == CoupledSpinState(j, m, (j1, x, j3))
assert CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, j12), (1, 2, j)) ).subs(j12, x) == \
CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, x), (1, 2, j)) )
def test_sympy__physics__quantum__spin__J2Op():
from sympy.physics.quantum.spin import J2Op
assert _test_args(J2Op('J'))
def test_sympy__physics__quantum__spin__JminusOp():
from sympy.physics.quantum.spin import JminusOp
assert _test_args(JminusOp('J'))
def test_sympy__physics__quantum__spin__JplusOp():
from sympy.physics.quantum.spin import JplusOp
assert _test_args(JplusOp('J'))
def test_sympy__physics__quantum__spin__JxBra():
from sympy.physics.quantum.spin import JxBra
assert _test_args(JxBra(1, 0))
def test_sympy__physics__quantum__spin__JxBraCoupled():
from sympy.physics.quantum.spin import JxBraCoupled
assert _test_args(JxBraCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JxKet():
from sympy.physics.quantum.spin import JxKet
assert _test_args(JxKet(1, 0))
def test_sympy__physics__quantum__spin__JxKetCoupled():
from sympy.physics.quantum.spin import JxKetCoupled
assert _test_args(JxKetCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JxOp():
from sympy.physics.quantum.spin import JxOp
assert _test_args(JxOp('J'))
def test_sympy__physics__quantum__spin__JyBra():
from sympy.physics.quantum.spin import JyBra
assert _test_args(JyBra(1, 0))
def test_sympy__physics__quantum__spin__JyBraCoupled():
from sympy.physics.quantum.spin import JyBraCoupled
assert _test_args(JyBraCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JyKet():
from sympy.physics.quantum.spin import JyKet
assert _test_args(JyKet(1, 0))
def test_sympy__physics__quantum__spin__JyKetCoupled():
from sympy.physics.quantum.spin import JyKetCoupled
assert _test_args(JyKetCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JyOp():
from sympy.physics.quantum.spin import JyOp
assert _test_args(JyOp('J'))
def test_sympy__physics__quantum__spin__JzBra():
from sympy.physics.quantum.spin import JzBra
assert _test_args(JzBra(1, 0))
def test_sympy__physics__quantum__spin__JzBraCoupled():
from sympy.physics.quantum.spin import JzBraCoupled
assert _test_args(JzBraCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JzKet():
from sympy.physics.quantum.spin import JzKet
assert _test_args(JzKet(1, 0))
def test_sympy__physics__quantum__spin__JzKetCoupled():
from sympy.physics.quantum.spin import JzKetCoupled
assert _test_args(JzKetCoupled(1, 0, (1, 1)))
def test_sympy__physics__quantum__spin__JzOp():
from sympy.physics.quantum.spin import JzOp
assert _test_args(JzOp('J'))
def test_sympy__physics__quantum__spin__Rotation():
from sympy.physics.quantum.spin import Rotation
assert _test_args(Rotation(pi, 0, pi/2))
def test_sympy__physics__quantum__spin__SpinState():
from sympy.physics.quantum.spin import SpinState
assert _test_args(SpinState(1, 0))
def test_sympy__physics__quantum__spin__WignerD():
from sympy.physics.quantum.spin import WignerD
assert _test_args(WignerD(0, 1, 2, 3, 4, 5))
def test_sympy__physics__quantum__state__Bra():
from sympy.physics.quantum.state import Bra
assert _test_args(Bra(0))
def test_sympy__physics__quantum__state__BraBase():
from sympy.physics.quantum.state import BraBase
assert _test_args(BraBase(0))
def test_sympy__physics__quantum__state__Ket():
from sympy.physics.quantum.state import Ket
assert _test_args(Ket(0))
def test_sympy__physics__quantum__state__KetBase():
from sympy.physics.quantum.state import KetBase
assert _test_args(KetBase(0))
def test_sympy__physics__quantum__state__State():
from sympy.physics.quantum.state import State
assert _test_args(State(0))
def test_sympy__physics__quantum__state__StateBase():
from sympy.physics.quantum.state import StateBase
assert _test_args(StateBase(0))
def test_sympy__physics__quantum__state__OrthogonalBra():
from sympy.physics.quantum.state import OrthogonalBra
assert _test_args(OrthogonalBra(0))
def test_sympy__physics__quantum__state__OrthogonalKet():
from sympy.physics.quantum.state import OrthogonalKet
assert _test_args(OrthogonalKet(0))
def test_sympy__physics__quantum__state__OrthogonalState():
from sympy.physics.quantum.state import OrthogonalState
assert _test_args(OrthogonalState(0))
def test_sympy__physics__quantum__state__TimeDepBra():
from sympy.physics.quantum.state import TimeDepBra
assert _test_args(TimeDepBra('psi', 't'))
def test_sympy__physics__quantum__state__TimeDepKet():
from sympy.physics.quantum.state import TimeDepKet
assert _test_args(TimeDepKet('psi', 't'))
def test_sympy__physics__quantum__state__TimeDepState():
from sympy.physics.quantum.state import TimeDepState
assert _test_args(TimeDepState('psi', 't'))
def test_sympy__physics__quantum__state__Wavefunction():
from sympy.physics.quantum.state import Wavefunction
from sympy.functions import sin
from sympy.functions.elementary.piecewise import Piecewise
n = 1
L = 1
g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))
assert _test_args(Wavefunction(g, x))
def test_sympy__physics__quantum__tensorproduct__TensorProduct():
from sympy.physics.quantum.tensorproduct import TensorProduct
x, y = symbols("x y", commutative=False)
assert _test_args(TensorProduct(x, y))
def test_sympy__physics__quantum__identitysearch__GateIdentity():
from sympy.physics.quantum.gate import X
from sympy.physics.quantum.identitysearch import GateIdentity
assert _test_args(GateIdentity(X(0), X(0)))
def test_sympy__physics__quantum__sho1d__SHOOp():
from sympy.physics.quantum.sho1d import SHOOp
assert _test_args(SHOOp('a'))
def test_sympy__physics__quantum__sho1d__RaisingOp():
from sympy.physics.quantum.sho1d import RaisingOp
assert _test_args(RaisingOp('a'))
def test_sympy__physics__quantum__sho1d__LoweringOp():
from sympy.physics.quantum.sho1d import LoweringOp
assert _test_args(LoweringOp('a'))
def test_sympy__physics__quantum__sho1d__NumberOp():
from sympy.physics.quantum.sho1d import NumberOp
assert _test_args(NumberOp('N'))
def test_sympy__physics__quantum__sho1d__Hamiltonian():
from sympy.physics.quantum.sho1d import Hamiltonian
assert _test_args(Hamiltonian('H'))
def test_sympy__physics__quantum__sho1d__SHOState():
from sympy.physics.quantum.sho1d import SHOState
assert _test_args(SHOState(0))
def test_sympy__physics__quantum__sho1d__SHOKet():
from sympy.physics.quantum.sho1d import SHOKet
assert _test_args(SHOKet(0))
def test_sympy__physics__quantum__sho1d__SHOBra():
from sympy.physics.quantum.sho1d import SHOBra
assert _test_args(SHOBra(0))
def test_sympy__physics__secondquant__AnnihilateBoson():
from sympy.physics.secondquant import AnnihilateBoson
assert _test_args(AnnihilateBoson(0))
def test_sympy__physics__secondquant__AnnihilateFermion():
from sympy.physics.secondquant import AnnihilateFermion
assert _test_args(AnnihilateFermion(0))
@SKIP("abstract class")
def test_sympy__physics__secondquant__Annihilator():
pass
def test_sympy__physics__secondquant__AntiSymmetricTensor():
from sympy.physics.secondquant import AntiSymmetricTensor
i, j = symbols('i j', below_fermi=True)
a, b = symbols('a b', above_fermi=True)
assert _test_args(AntiSymmetricTensor('v', (a, i), (b, j)))
def test_sympy__physics__secondquant__BosonState():
from sympy.physics.secondquant import BosonState
assert _test_args(BosonState((0, 1)))
@SKIP("abstract class")
def test_sympy__physics__secondquant__BosonicOperator():
pass
def test_sympy__physics__secondquant__Commutator():
from sympy.physics.secondquant import Commutator
x, y = symbols('x y', commutative=False)
assert _test_args(Commutator(x, y))
def test_sympy__physics__secondquant__CreateBoson():
from sympy.physics.secondquant import CreateBoson
assert _test_args(CreateBoson(0))
def test_sympy__physics__secondquant__CreateFermion():
from sympy.physics.secondquant import CreateFermion
assert _test_args(CreateFermion(0))
@SKIP("abstract class")
def test_sympy__physics__secondquant__Creator():
pass
def test_sympy__physics__secondquant__Dagger():
from sympy.physics.secondquant import Dagger
assert _test_args(Dagger(x))
def test_sympy__physics__secondquant__FermionState():
from sympy.physics.secondquant import FermionState
assert _test_args(FermionState((0, 1)))
def test_sympy__physics__secondquant__FermionicOperator():
from sympy.physics.secondquant import FermionicOperator
assert _test_args(FermionicOperator(0))
def test_sympy__physics__secondquant__FockState():
from sympy.physics.secondquant import FockState
assert _test_args(FockState((0, 1)))
def test_sympy__physics__secondquant__FockStateBosonBra():
from sympy.physics.secondquant import FockStateBosonBra
assert _test_args(FockStateBosonBra((0, 1)))
def test_sympy__physics__secondquant__FockStateBosonKet():
from sympy.physics.secondquant import FockStateBosonKet
assert _test_args(FockStateBosonKet((0, 1)))
def test_sympy__physics__secondquant__FockStateBra():
from sympy.physics.secondquant import FockStateBra
assert _test_args(FockStateBra((0, 1)))
def test_sympy__physics__secondquant__FockStateFermionBra():
from sympy.physics.secondquant import FockStateFermionBra
assert _test_args(FockStateFermionBra((0, 1)))
def test_sympy__physics__secondquant__FockStateFermionKet():
from sympy.physics.secondquant import FockStateFermionKet
assert _test_args(FockStateFermionKet((0, 1)))
def test_sympy__physics__secondquant__FockStateKet():
from sympy.physics.secondquant import FockStateKet
assert _test_args(FockStateKet((0, 1)))
def test_sympy__physics__secondquant__InnerProduct():
from sympy.physics.secondquant import InnerProduct
from sympy.physics.secondquant import FockStateKet, FockStateBra
assert _test_args(InnerProduct(FockStateBra((0, 1)), FockStateKet((0, 1))))
def test_sympy__physics__secondquant__NO():
from sympy.physics.secondquant import NO, F, Fd
assert _test_args(NO(Fd(x)*F(y)))
def test_sympy__physics__secondquant__PermutationOperator():
from sympy.physics.secondquant import PermutationOperator
assert _test_args(PermutationOperator(0, 1))
def test_sympy__physics__secondquant__SqOperator():
from sympy.physics.secondquant import SqOperator
assert _test_args(SqOperator(0))
def test_sympy__physics__secondquant__TensorSymbol():
from sympy.physics.secondquant import TensorSymbol
assert _test_args(TensorSymbol(x))
def test_sympy__physics__control__lti__LinearTimeInvariant():
# Direct instances of LinearTimeInvariant class are not allowed.
# func(*args) tests for its derived classes (TransferFunction,
# Series, Parallel and TransferFunctionMatrix) should pass.
pass
def test_sympy__physics__control__lti__SISOLinearTimeInvariant():
# Direct instances of SISOLinearTimeInvariant class are not allowed.
pass
def test_sympy__physics__control__lti__MIMOLinearTimeInvariant():
# Direct instances of MIMOLinearTimeInvariant class are not allowed.
pass
def test_sympy__physics__control__lti__TransferFunction():
from sympy.physics.control.lti import TransferFunction
assert _test_args(TransferFunction(2, 3, x))
def test_sympy__physics__control__lti__Series():
from sympy.physics.control import Series, TransferFunction
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
assert _test_args(Series(tf1, tf2))
def test_sympy__physics__control__lti__MIMOSeries():
from sympy.physics.control import MIMOSeries, TransferFunction, TransferFunctionMatrix
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
tfm_1 = TransferFunctionMatrix([[tf2, tf1]])
tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
tfm_3 = TransferFunctionMatrix([[tf1], [tf2]])
assert _test_args(MIMOSeries(tfm_3, tfm_2, tfm_1))
def test_sympy__physics__control__lti__Parallel():
from sympy.physics.control import Parallel, TransferFunction
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
assert _test_args(Parallel(tf1, tf2))
def test_sympy__physics__control__lti__MIMOParallel():
from sympy.physics.control import MIMOParallel, TransferFunction, TransferFunctionMatrix
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]])
assert _test_args(MIMOParallel(tfm_1, tfm_2))
def test_sympy__physics__control__lti__Feedback():
from sympy.physics.control import TransferFunction, Feedback
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
assert _test_args(Feedback(tf1, tf2))
assert _test_args(Feedback(tf1, tf2, 1))
def test_sympy__physics__control__lti__MIMOFeedback():
from sympy.physics.control import TransferFunction, MIMOFeedback, TransferFunctionMatrix
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
tfm_1 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]])
tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
assert _test_args(MIMOFeedback(tfm_1, tfm_2))
assert _test_args(MIMOFeedback(tfm_1, tfm_2, 1))
def test_sympy__physics__control__lti__TransferFunctionMatrix():
from sympy.physics.control import TransferFunction, TransferFunctionMatrix
tf1 = TransferFunction(x**2 - y**3, y - z, x)
tf2 = TransferFunction(y - x, z + y, x)
assert _test_args(TransferFunctionMatrix([[tf1, tf2]]))
def test_sympy__physics__units__dimensions__Dimension():
from sympy.physics.units.dimensions import Dimension
assert _test_args(Dimension("length", "L"))
def test_sympy__physics__units__dimensions__DimensionSystem():
from sympy.physics.units.dimensions import DimensionSystem
from sympy.physics.units.definitions.dimension_definitions import length, time, velocity
assert _test_args(DimensionSystem((length, time), (velocity,)))
def test_sympy__physics__units__quantities__Quantity():
from sympy.physics.units.quantities import Quantity
assert _test_args(Quantity("dam"))
def test_sympy__physics__units__quantities__PhysicalConstant():
from sympy.physics.units.quantities import PhysicalConstant
assert _test_args(PhysicalConstant("foo"))
def test_sympy__physics__units__prefixes__Prefix():
from sympy.physics.units.prefixes import Prefix
assert _test_args(Prefix('kilo', 'k', 3))
def test_sympy__core__numbers__AlgebraicNumber():
from sympy.core.numbers import AlgebraicNumber
assert _test_args(AlgebraicNumber(sqrt(2), [1, 2, 3]))
def test_sympy__polys__polytools__GroebnerBasis():
from sympy.polys.polytools import GroebnerBasis
assert _test_args(GroebnerBasis([x, y, z], x, y, z))
def test_sympy__polys__polytools__Poly():
from sympy.polys.polytools import Poly
assert _test_args(Poly(2, x, y))
def test_sympy__polys__polytools__PurePoly():
from sympy.polys.polytools import PurePoly
assert _test_args(PurePoly(2, x, y))
@SKIP('abstract class')
def test_sympy__polys__rootoftools__RootOf():
pass
def test_sympy__polys__rootoftools__ComplexRootOf():
from sympy.polys.rootoftools import ComplexRootOf
assert _test_args(ComplexRootOf(x**3 + x + 1, 0))
def test_sympy__polys__rootoftools__RootSum():
from sympy.polys.rootoftools import RootSum
assert _test_args(RootSum(x**3 + x + 1, sin))
def test_sympy__series__limits__Limit():
from sympy.series.limits import Limit
assert _test_args(Limit(x, x, 0, dir='-'))
def test_sympy__series__order__Order():
from sympy.series.order import Order
assert _test_args(Order(1, x, y))
@SKIP('Abstract Class')
def test_sympy__series__sequences__SeqBase():
pass
def test_sympy__series__sequences__EmptySequence():
# Need to import the instance from series not the class from
# series.sequence
from sympy.series import EmptySequence
assert _test_args(EmptySequence)
@SKIP('Abstract Class')
def test_sympy__series__sequences__SeqExpr():
pass
def test_sympy__series__sequences__SeqPer():
from sympy.series.sequences import SeqPer
assert _test_args(SeqPer((1, 2, 3), (0, 10)))
def test_sympy__series__sequences__SeqFormula():
from sympy.series.sequences import SeqFormula
assert _test_args(SeqFormula(x**2, (0, 10)))
def test_sympy__series__sequences__RecursiveSeq():
from sympy.series.sequences import RecursiveSeq
y = Function("y")
n = symbols("n")
assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y(n), n, (0, 1)))
assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y(n), n))
def test_sympy__series__sequences__SeqExprOp():
from sympy.series.sequences import SeqExprOp, sequence
s1 = sequence((1, 2, 3))
s2 = sequence(x**2)
assert _test_args(SeqExprOp(s1, s2))
def test_sympy__series__sequences__SeqAdd():
from sympy.series.sequences import SeqAdd, sequence
s1 = sequence((1, 2, 3))
s2 = sequence(x**2)
assert _test_args(SeqAdd(s1, s2))
def test_sympy__series__sequences__SeqMul():
from sympy.series.sequences import SeqMul, sequence
s1 = sequence((1, 2, 3))
s2 = sequence(x**2)
assert _test_args(SeqMul(s1, s2))
@SKIP('Abstract Class')
def test_sympy__series__series_class__SeriesBase():
pass
def test_sympy__series__fourier__FourierSeries():
from sympy.series.fourier import fourier_series
assert _test_args(fourier_series(x, (x, -pi, pi)))
def test_sympy__series__fourier__FiniteFourierSeries():
from sympy.series.fourier import fourier_series
assert _test_args(fourier_series(sin(pi*x), (x, -1, 1)))
def test_sympy__series__formal__FormalPowerSeries():
from sympy.series.formal import fps
assert _test_args(fps(log(1 + x), x))
def test_sympy__series__formal__Coeff():
from sympy.series.formal import fps
assert _test_args(fps(x**2 + x + 1, x))
@SKIP('Abstract Class')
def test_sympy__series__formal__FiniteFormalPowerSeries():
pass
def test_sympy__series__formal__FormalPowerSeriesProduct():
from sympy.series.formal import fps
f1, f2 = fps(sin(x)), fps(exp(x))
assert _test_args(f1.product(f2, x))
def test_sympy__series__formal__FormalPowerSeriesCompose():
from sympy.series.formal import fps
f1, f2 = fps(exp(x)), fps(sin(x))
assert _test_args(f1.compose(f2, x))
def test_sympy__series__formal__FormalPowerSeriesInverse():
from sympy.series.formal import fps
f1 = fps(exp(x))
assert _test_args(f1.inverse(x))
def test_sympy__simplify__hyperexpand__Hyper_Function():
from sympy.simplify.hyperexpand import Hyper_Function
assert _test_args(Hyper_Function([2], [1]))
def test_sympy__simplify__hyperexpand__G_Function():
from sympy.simplify.hyperexpand import G_Function
assert _test_args(G_Function([2], [1], [], []))
@SKIP("abstract class")
def test_sympy__tensor__array__ndim_array__ImmutableNDimArray():
pass
def test_sympy__tensor__array__dense_ndim_array__ImmutableDenseNDimArray():
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert _test_args(densarr)
def test_sympy__tensor__array__sparse_ndim_array__ImmutableSparseNDimArray():
from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray
sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert _test_args(sparr)
def test_sympy__tensor__array__array_comprehension__ArrayComprehension():
from sympy.tensor.array.array_comprehension import ArrayComprehension
arrcom = ArrayComprehension(x, (x, 1, 5))
assert _test_args(arrcom)
def test_sympy__tensor__array__array_comprehension__ArrayComprehensionMap():
from sympy.tensor.array.array_comprehension import ArrayComprehensionMap
arrcomma = ArrayComprehensionMap(lambda: 0, (x, 1, 5))
assert _test_args(arrcomma)
def test_sympy__tensor__array__array_derivatives__ArrayDerivative():
from sympy.tensor.array.array_derivatives import ArrayDerivative
A = MatrixSymbol("A", 2, 2)
arrder = ArrayDerivative(A, A, evaluate=False)
assert _test_args(arrder)
def test_sympy__tensor__array__expressions__array_expressions__ArraySymbol():
from sympy.tensor.array.expressions.array_expressions import ArraySymbol
m, n, k = symbols("m n k")
array = ArraySymbol("A", (m, n, k, 2))
assert _test_args(array)
def test_sympy__tensor__array__expressions__array_expressions__ArrayElement():
from sympy.tensor.array.expressions.array_expressions import ArrayElement
m, n, k = symbols("m n k")
ae = ArrayElement("A", (m, n, k, 2))
assert _test_args(ae)
def test_sympy__tensor__array__expressions__array_expressions__ZeroArray():
from sympy.tensor.array.expressions.array_expressions import ZeroArray
m, n, k = symbols("m n k")
za = ZeroArray(m, n, k, 2)
assert _test_args(za)
def test_sympy__tensor__array__expressions__array_expressions__OneArray():
from sympy.tensor.array.expressions.array_expressions import OneArray
m, n, k = symbols("m n k")
za = OneArray(m, n, k, 2)
assert _test_args(za)
def test_sympy__tensor__functions__TensorProduct():
from sympy.tensor.functions import TensorProduct
A = MatrixSymbol('A', 3, 3)
B = MatrixSymbol('B', 3, 3)
tp = TensorProduct(A, B)
assert _test_args(tp)
def test_sympy__tensor__indexed__Idx():
from sympy.tensor.indexed import Idx
assert _test_args(Idx('test'))
assert _test_args(Idx('test', (0, 10)))
assert _test_args(Idx('test', 2))
assert _test_args(Idx('test', x))
def test_sympy__tensor__indexed__Indexed():
from sympy.tensor.indexed import Indexed, Idx
assert _test_args(Indexed('A', Idx('i'), Idx('j')))
def test_sympy__tensor__indexed__IndexedBase():
from sympy.tensor.indexed import IndexedBase
assert _test_args(IndexedBase('A', shape=(x, y)))
assert _test_args(IndexedBase('A', 1))
assert _test_args(IndexedBase('A')[0, 1])
def test_sympy__tensor__tensor__TensorIndexType():
from sympy.tensor.tensor import TensorIndexType
assert _test_args(TensorIndexType('Lorentz'))
@SKIP("deprecated class")
def test_sympy__tensor__tensor__TensorType():
pass
def test_sympy__tensor__tensor__TensorSymmetry():
from sympy.tensor.tensor import TensorSymmetry, get_symmetric_group_sgs
assert _test_args(TensorSymmetry(get_symmetric_group_sgs(2)))
def test_sympy__tensor__tensor__TensorHead():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
sym = TensorSymmetry(get_symmetric_group_sgs(1))
assert _test_args(TensorHead('p', [Lorentz], sym, 0))
def test_sympy__tensor__tensor__TensorIndex():
from sympy.tensor.tensor import TensorIndexType, TensorIndex
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
assert _test_args(TensorIndex('i', Lorentz))
@SKIP("abstract class")
def test_sympy__tensor__tensor__TensExpr():
pass
def test_sympy__tensor__tensor__TensAdd():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, TensAdd, tensor_heads
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
sym = TensorSymmetry(get_symmetric_group_sgs(1))
p, q = tensor_heads('p,q', [Lorentz], sym)
t1 = p(a)
t2 = q(a)
assert _test_args(TensAdd(t1, t2))
def test_sympy__tensor__tensor__Tensor():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, TensorHead
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
sym = TensorSymmetry(get_symmetric_group_sgs(1))
p = TensorHead('p', [Lorentz], sym)
assert _test_args(p(a))
def test_sympy__tensor__tensor__TensMul():
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, tensor_heads
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
sym = TensorSymmetry(get_symmetric_group_sgs(1))
p, q = tensor_heads('p, q', [Lorentz], sym)
assert _test_args(3*p(a)*q(b))
def test_sympy__tensor__tensor__TensorElement():
from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorElement
L = TensorIndexType("L")
A = TensorHead("A", [L, L])
telem = TensorElement(A(x, y), {x: 1})
assert _test_args(telem)
def test_sympy__tensor__tensor__WildTensor():
from sympy.tensor.tensor import TensorIndexType, WildTensorHead, TensorIndex
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a = TensorIndex('a', Lorentz)
p = WildTensorHead('p')
assert _test_args(p(a))
def test_sympy__tensor__tensor__WildTensorHead():
from sympy.tensor.tensor import WildTensorHead
assert _test_args(WildTensorHead('p'))
def test_sympy__tensor__tensor__WildTensorIndex():
from sympy.tensor.tensor import TensorIndexType, WildTensorIndex
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
assert _test_args(WildTensorIndex('i', Lorentz))
def test_sympy__tensor__toperators__PartialDerivative():
from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead
from sympy.tensor.toperators import PartialDerivative
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
A = TensorHead("A", [Lorentz])
assert _test_args(PartialDerivative(A(a), A(b)))
def test_as_coeff_add():
assert (7, (3*x, 4*x**2)) == (7 + 3*x + 4*x**2).as_coeff_add()
def test_sympy__geometry__curve__Curve():
from sympy.geometry.curve import Curve
assert _test_args(Curve((x, 1), (x, 0, 1)))
def test_sympy__geometry__point__Point():
from sympy.geometry.point import Point
assert _test_args(Point(0, 1))
def test_sympy__geometry__point__Point2D():
from sympy.geometry.point import Point2D
assert _test_args(Point2D(0, 1))
def test_sympy__geometry__point__Point3D():
from sympy.geometry.point import Point3D
assert _test_args(Point3D(0, 1, 2))
def test_sympy__geometry__ellipse__Ellipse():
from sympy.geometry.ellipse import Ellipse
assert _test_args(Ellipse((0, 1), 2, 3))
def test_sympy__geometry__ellipse__Circle():
from sympy.geometry.ellipse import Circle
assert _test_args(Circle((0, 1), 2))
def test_sympy__geometry__parabola__Parabola():
from sympy.geometry.parabola import Parabola
from sympy.geometry.line import Line
assert _test_args(Parabola((0, 0), Line((2, 3), (4, 3))))
@SKIP("abstract class")
def test_sympy__geometry__line__LinearEntity():
pass
def test_sympy__geometry__line__Line():
from sympy.geometry.line import Line
assert _test_args(Line((0, 1), (2, 3)))
def test_sympy__geometry__line__Ray():
from sympy.geometry.line import Ray
assert _test_args(Ray((0, 1), (2, 3)))
def test_sympy__geometry__line__Segment():
from sympy.geometry.line import Segment
assert _test_args(Segment((0, 1), (2, 3)))
@SKIP("abstract class")
def test_sympy__geometry__line__LinearEntity2D():
pass
def test_sympy__geometry__line__Line2D():
from sympy.geometry.line import Line2D
assert _test_args(Line2D((0, 1), (2, 3)))
def test_sympy__geometry__line__Ray2D():
from sympy.geometry.line import Ray2D
assert _test_args(Ray2D((0, 1), (2, 3)))
def test_sympy__geometry__line__Segment2D():
from sympy.geometry.line import Segment2D
assert _test_args(Segment2D((0, 1), (2, 3)))
@SKIP("abstract class")
def test_sympy__geometry__line__LinearEntity3D():
pass
def test_sympy__geometry__line__Line3D():
from sympy.geometry.line import Line3D
assert _test_args(Line3D((0, 1, 1), (2, 3, 4)))
def test_sympy__geometry__line__Segment3D():
from sympy.geometry.line import Segment3D
assert _test_args(Segment3D((0, 1, 1), (2, 3, 4)))
def test_sympy__geometry__line__Ray3D():
from sympy.geometry.line import Ray3D
assert _test_args(Ray3D((0, 1, 1), (2, 3, 4)))
def test_sympy__geometry__plane__Plane():
from sympy.geometry.plane import Plane
assert _test_args(Plane((1, 1, 1), (-3, 4, -2), (1, 2, 3)))
def test_sympy__geometry__polygon__Polygon():
from sympy.geometry.polygon import Polygon
assert _test_args(Polygon((0, 1), (2, 3), (4, 5), (6, 7)))
def test_sympy__geometry__polygon__RegularPolygon():
from sympy.geometry.polygon import RegularPolygon
assert _test_args(RegularPolygon((0, 1), 2, 3, 4))
def test_sympy__geometry__polygon__Triangle():
from sympy.geometry.polygon import Triangle
assert _test_args(Triangle((0, 1), (2, 3), (4, 5)))
def test_sympy__geometry__entity__GeometryEntity():
from sympy.geometry.entity import GeometryEntity
from sympy.geometry.point import Point
assert _test_args(GeometryEntity(Point(1, 0), 1, [1, 2]))
@SKIP("abstract class")
def test_sympy__geometry__entity__GeometrySet():
pass
def test_sympy__diffgeom__diffgeom__Manifold():
from sympy.diffgeom import Manifold
assert _test_args(Manifold('name', 3))
def test_sympy__diffgeom__diffgeom__Patch():
from sympy.diffgeom import Manifold, Patch
assert _test_args(Patch('name', Manifold('name', 3)))
def test_sympy__diffgeom__diffgeom__CoordSystem():
from sympy.diffgeom import Manifold, Patch, CoordSystem
assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3))))
assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]))
def test_sympy__diffgeom__diffgeom__CoordinateSymbol():
from sympy.diffgeom import Manifold, Patch, CoordSystem, CoordinateSymbol
assert _test_args(CoordinateSymbol(CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]), 0))
def test_sympy__diffgeom__diffgeom__Point():
from sympy.diffgeom import Manifold, Patch, CoordSystem, Point
assert _test_args(Point(
CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]), [x, y]))
def test_sympy__diffgeom__diffgeom__BaseScalarField():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
assert _test_args(BaseScalarField(cs, 0))
def test_sympy__diffgeom__diffgeom__BaseVectorField():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
assert _test_args(BaseVectorField(cs, 0))
def test_sympy__diffgeom__diffgeom__Differential():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
assert _test_args(Differential(BaseScalarField(cs, 0)))
def test_sympy__diffgeom__diffgeom__Commutator():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, Commutator
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
cs1 = CoordSystem('name1', Patch('name', Manifold('name', 3)), [a, b, c])
v = BaseVectorField(cs, 0)
v1 = BaseVectorField(cs1, 0)
assert _test_args(Commutator(v, v1))
def test_sympy__diffgeom__diffgeom__TensorProduct():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, TensorProduct
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
d = Differential(BaseScalarField(cs, 0))
assert _test_args(TensorProduct(d, d))
def test_sympy__diffgeom__diffgeom__WedgeProduct():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, WedgeProduct
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
d = Differential(BaseScalarField(cs, 0))
d1 = Differential(BaseScalarField(cs, 1))
assert _test_args(WedgeProduct(d, d1))
def test_sympy__diffgeom__diffgeom__LieDerivative():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, BaseVectorField, LieDerivative
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
d = Differential(BaseScalarField(cs, 0))
v = BaseVectorField(cs, 0)
assert _test_args(LieDerivative(v, d))
def test_sympy__diffgeom__diffgeom__BaseCovarDerivativeOp():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseCovarDerivativeOp
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
assert _test_args(BaseCovarDerivativeOp(cs, 0, [[[0, ]*3, ]*3, ]*3))
def test_sympy__diffgeom__diffgeom__CovarDerivativeOp():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, CovarDerivativeOp
cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])
v = BaseVectorField(cs, 0)
_test_args(CovarDerivativeOp(v, [[[0, ]*3, ]*3, ]*3))
def test_sympy__categories__baseclasses__Class():
from sympy.categories.baseclasses import Class
assert _test_args(Class())
def test_sympy__categories__baseclasses__Object():
from sympy.categories import Object
assert _test_args(Object("A"))
@SKIP("abstract class")
def test_sympy__categories__baseclasses__Morphism():
pass
def test_sympy__categories__baseclasses__IdentityMorphism():
from sympy.categories import Object, IdentityMorphism
assert _test_args(IdentityMorphism(Object("A")))
def test_sympy__categories__baseclasses__NamedMorphism():
from sympy.categories import Object, NamedMorphism
assert _test_args(NamedMorphism(Object("A"), Object("B"), "f"))
def test_sympy__categories__baseclasses__CompositeMorphism():
from sympy.categories import Object, NamedMorphism, CompositeMorphism
A = Object("A")
B = Object("B")
C = Object("C")
f = NamedMorphism(A, B, "f")
g = NamedMorphism(B, C, "g")
assert _test_args(CompositeMorphism(f, g))
def test_sympy__categories__baseclasses__Diagram():
from sympy.categories import Object, NamedMorphism, Diagram
A = Object("A")
B = Object("B")
f = NamedMorphism(A, B, "f")
d = Diagram([f])
assert _test_args(d)
def test_sympy__categories__baseclasses__Category():
from sympy.categories import Object, NamedMorphism, Diagram, Category
A = Object("A")
B = Object("B")
C = Object("C")
f = NamedMorphism(A, B, "f")
g = NamedMorphism(B, C, "g")
d1 = Diagram([f, g])
d2 = Diagram([f])
K = Category("K", commutative_diagrams=[d1, d2])
assert _test_args(K)
def test_sympy__ntheory__factor___totient():
from sympy.ntheory.factor_ import totient
k = symbols('k', integer=True)
t = totient(k)
assert _test_args(t)
def test_sympy__ntheory__factor___reduced_totient():
from sympy.ntheory.factor_ import reduced_totient
k = symbols('k', integer=True)
t = reduced_totient(k)
assert _test_args(t)
def test_sympy__ntheory__factor___divisor_sigma():
from sympy.ntheory.factor_ import divisor_sigma
k = symbols('k', integer=True)
n = symbols('n', integer=True)
t = divisor_sigma(n, k)
assert _test_args(t)
def test_sympy__ntheory__factor___udivisor_sigma():
from sympy.ntheory.factor_ import udivisor_sigma
k = symbols('k', integer=True)
n = symbols('n', integer=True)
t = udivisor_sigma(n, k)
assert _test_args(t)
def test_sympy__ntheory__factor___primenu():
from sympy.ntheory.factor_ import primenu
n = symbols('n', integer=True)
t = primenu(n)
assert _test_args(t)
def test_sympy__ntheory__factor___primeomega():
from sympy.ntheory.factor_ import primeomega
n = symbols('n', integer=True)
t = primeomega(n)
assert _test_args(t)
def test_sympy__ntheory__residue_ntheory__mobius():
from sympy.ntheory import mobius
assert _test_args(mobius(2))
def test_sympy__ntheory__generate__primepi():
from sympy.ntheory import primepi
n = symbols('n')
t = primepi(n)
assert _test_args(t)
def test_sympy__physics__optics__waves__TWave():
from sympy.physics.optics import TWave
A, f, phi = symbols('A, f, phi')
assert _test_args(TWave(A, f, phi))
def test_sympy__physics__optics__gaussopt__BeamParameter():
from sympy.physics.optics import BeamParameter
assert _test_args(BeamParameter(530e-9, 1, w=1e-3, n=1))
def test_sympy__physics__optics__medium__Medium():
from sympy.physics.optics import Medium
assert _test_args(Medium('m'))
def test_sympy__physics__optics__medium__MediumN():
from sympy.physics.optics.medium import Medium
assert _test_args(Medium('m', n=2))
def test_sympy__physics__optics__medium__MediumPP():
from sympy.physics.optics.medium import Medium
assert _test_args(Medium('m', permittivity=2, permeability=2))
def test_sympy__tensor__array__expressions__array_expressions__ArrayContraction():
from sympy.tensor.array.expressions.array_expressions import ArrayContraction
from sympy.tensor.indexed import IndexedBase
A = symbols("A", cls=IndexedBase)
assert _test_args(ArrayContraction(A, (0, 1)))
def test_sympy__tensor__array__expressions__array_expressions__ArrayDiagonal():
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal
from sympy.tensor.indexed import IndexedBase
A = symbols("A", cls=IndexedBase)
assert _test_args(ArrayDiagonal(A, (0, 1)))
def test_sympy__tensor__array__expressions__array_expressions__ArrayTensorProduct():
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
from sympy.tensor.indexed import IndexedBase
A, B = symbols("A B", cls=IndexedBase)
assert _test_args(ArrayTensorProduct(A, B))
def test_sympy__tensor__array__expressions__array_expressions__ArrayAdd():
from sympy.tensor.array.expressions.array_expressions import ArrayAdd
from sympy.tensor.indexed import IndexedBase
A, B = symbols("A B", cls=IndexedBase)
assert _test_args(ArrayAdd(A, B))
def test_sympy__tensor__array__expressions__array_expressions__PermuteDims():
from sympy.tensor.array.expressions.array_expressions import PermuteDims
A = MatrixSymbol("A", 4, 4)
assert _test_args(PermuteDims(A, (1, 0)))
def test_sympy__tensor__array__expressions__array_expressions__ArrayElementwiseApplyFunc():
from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElementwiseApplyFunc
A = ArraySymbol("A", (4,))
assert _test_args(ArrayElementwiseApplyFunc(exp, A))
def test_sympy__tensor__array__expressions__array_expressions__Reshape():
from sympy.tensor.array.expressions.array_expressions import ArraySymbol, Reshape
A = ArraySymbol("A", (4,))
assert _test_args(Reshape(A, (2, 2)))
def test_sympy__codegen__ast__Assignment():
from sympy.codegen.ast import Assignment
assert _test_args(Assignment(x, y))
def test_sympy__codegen__cfunctions__expm1():
from sympy.codegen.cfunctions import expm1
assert _test_args(expm1(x))
def test_sympy__codegen__cfunctions__log1p():
from sympy.codegen.cfunctions import log1p
assert _test_args(log1p(x))
def test_sympy__codegen__cfunctions__exp2():
from sympy.codegen.cfunctions import exp2
assert _test_args(exp2(x))
def test_sympy__codegen__cfunctions__log2():
from sympy.codegen.cfunctions import log2
assert _test_args(log2(x))
def test_sympy__codegen__cfunctions__fma():
from sympy.codegen.cfunctions import fma
assert _test_args(fma(x, y, z))
def test_sympy__codegen__cfunctions__log10():
from sympy.codegen.cfunctions import log10
assert _test_args(log10(x))
def test_sympy__codegen__cfunctions__Sqrt():
from sympy.codegen.cfunctions import Sqrt
assert _test_args(Sqrt(x))
def test_sympy__codegen__cfunctions__Cbrt():
from sympy.codegen.cfunctions import Cbrt
assert _test_args(Cbrt(x))
def test_sympy__codegen__cfunctions__hypot():
from sympy.codegen.cfunctions import hypot
assert _test_args(hypot(x, y))
def test_sympy__codegen__fnodes__FFunction():
from sympy.codegen.fnodes import FFunction
assert _test_args(FFunction('f'))
def test_sympy__codegen__fnodes__F95Function():
from sympy.codegen.fnodes import F95Function
assert _test_args(F95Function('f'))
def test_sympy__codegen__fnodes__isign():
from sympy.codegen.fnodes import isign
assert _test_args(isign(1, x))
def test_sympy__codegen__fnodes__dsign():
from sympy.codegen.fnodes import dsign
assert _test_args(dsign(1, x))
def test_sympy__codegen__fnodes__cmplx():
from sympy.codegen.fnodes import cmplx
assert _test_args(cmplx(x, y))
def test_sympy__codegen__fnodes__kind():
from sympy.codegen.fnodes import kind
assert _test_args(kind(x))
def test_sympy__codegen__fnodes__merge():
from sympy.codegen.fnodes import merge
assert _test_args(merge(1, 2, Eq(x, 0)))
def test_sympy__codegen__fnodes___literal():
from sympy.codegen.fnodes import _literal
assert _test_args(_literal(1))
def test_sympy__codegen__fnodes__literal_sp():
from sympy.codegen.fnodes import literal_sp
assert _test_args(literal_sp(1))
def test_sympy__codegen__fnodes__literal_dp():
from sympy.codegen.fnodes import literal_dp
assert _test_args(literal_dp(1))
def test_sympy__codegen__matrix_nodes__MatrixSolve():
from sympy.matrices import MatrixSymbol
from sympy.codegen.matrix_nodes import MatrixSolve
A = MatrixSymbol('A', 3, 3)
v = MatrixSymbol('x', 3, 1)
assert _test_args(MatrixSolve(A, v))
def test_sympy__vector__coordsysrect__CoordSys3D():
from sympy.vector.coordsysrect import CoordSys3D
assert _test_args(CoordSys3D('C'))
def test_sympy__vector__point__Point():
from sympy.vector.point import Point
assert _test_args(Point('P'))
def test_sympy__vector__basisdependent__BasisDependent():
#from sympy.vector.basisdependent import BasisDependent
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
pass
def test_sympy__vector__basisdependent__BasisDependentMul():
#from sympy.vector.basisdependent import BasisDependentMul
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
pass
def test_sympy__vector__basisdependent__BasisDependentAdd():
#from sympy.vector.basisdependent import BasisDependentAdd
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
pass
def test_sympy__vector__basisdependent__BasisDependentZero():
#from sympy.vector.basisdependent import BasisDependentZero
#These classes have been created to maintain an OOP hierarchy
#for Vectors and Dyadics. Are NOT meant to be initialized
pass
def test_sympy__vector__vector__BaseVector():
from sympy.vector.vector import BaseVector
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(BaseVector(0, C, ' ', ' '))
def test_sympy__vector__vector__VectorAdd():
from sympy.vector.vector import VectorAdd, VectorMul
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
from sympy.abc import a, b, c, x, y, z
v1 = a*C.i + b*C.j + c*C.k
v2 = x*C.i + y*C.j + z*C.k
assert _test_args(VectorAdd(v1, v2))
assert _test_args(VectorMul(x, v1))
def test_sympy__vector__vector__VectorMul():
from sympy.vector.vector import VectorMul
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
from sympy.abc import a
assert _test_args(VectorMul(a, C.i))
def test_sympy__vector__vector__VectorZero():
from sympy.vector.vector import VectorZero
assert _test_args(VectorZero())
def test_sympy__vector__vector__Vector():
#from sympy.vector.vector import Vector
#Vector is never to be initialized using args
pass
def test_sympy__vector__vector__Cross():
from sympy.vector.vector import Cross
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
_test_args(Cross(C.i, C.j))
def test_sympy__vector__vector__Dot():
from sympy.vector.vector import Dot
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
_test_args(Dot(C.i, C.j))
def test_sympy__vector__dyadic__Dyadic():
#from sympy.vector.dyadic import Dyadic
#Dyadic is never to be initialized using args
pass
def test_sympy__vector__dyadic__BaseDyadic():
from sympy.vector.dyadic import BaseDyadic
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(BaseDyadic(C.i, C.j))
def test_sympy__vector__dyadic__DyadicMul():
from sympy.vector.dyadic import BaseDyadic, DyadicMul
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(DyadicMul(3, BaseDyadic(C.i, C.j)))
def test_sympy__vector__dyadic__DyadicAdd():
from sympy.vector.dyadic import BaseDyadic, DyadicAdd
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(2 * DyadicAdd(BaseDyadic(C.i, C.i),
BaseDyadic(C.i, C.j)))
def test_sympy__vector__dyadic__DyadicZero():
from sympy.vector.dyadic import DyadicZero
assert _test_args(DyadicZero())
def test_sympy__vector__deloperator__Del():
from sympy.vector.deloperator import Del
assert _test_args(Del())
def test_sympy__vector__implicitregion__ImplicitRegion():
from sympy.vector.implicitregion import ImplicitRegion
from sympy.abc import x, y
assert _test_args(ImplicitRegion((x, y), y**3 - 4*x))
def test_sympy__vector__integrals__ParametricIntegral():
from sympy.vector.integrals import ParametricIntegral
from sympy.vector.parametricregion import ParametricRegion
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(ParametricIntegral(C.y*C.i - 10*C.j,\
ParametricRegion((x, y), (x, 1, 3), (y, -2, 2))))
def test_sympy__vector__operators__Curl():
from sympy.vector.operators import Curl
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(Curl(C.i))
def test_sympy__vector__operators__Laplacian():
from sympy.vector.operators import Laplacian
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(Laplacian(C.i))
def test_sympy__vector__operators__Divergence():
from sympy.vector.operators import Divergence
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(Divergence(C.i))
def test_sympy__vector__operators__Gradient():
from sympy.vector.operators import Gradient
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(Gradient(C.x))
def test_sympy__vector__orienters__Orienter():
#from sympy.vector.orienters import Orienter
#Not to be initialized
pass
def test_sympy__vector__orienters__ThreeAngleOrienter():
#from sympy.vector.orienters import ThreeAngleOrienter
#Not to be initialized
pass
def test_sympy__vector__orienters__AxisOrienter():
from sympy.vector.orienters import AxisOrienter
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(AxisOrienter(x, C.i))
def test_sympy__vector__orienters__BodyOrienter():
from sympy.vector.orienters import BodyOrienter
assert _test_args(BodyOrienter(x, y, z, '123'))
def test_sympy__vector__orienters__SpaceOrienter():
from sympy.vector.orienters import SpaceOrienter
assert _test_args(SpaceOrienter(x, y, z, '123'))
def test_sympy__vector__orienters__QuaternionOrienter():
from sympy.vector.orienters import QuaternionOrienter
a, b, c, d = symbols('a b c d')
assert _test_args(QuaternionOrienter(a, b, c, d))
def test_sympy__vector__parametricregion__ParametricRegion():
from sympy.abc import t
from sympy.vector.parametricregion import ParametricRegion
assert _test_args(ParametricRegion((t, t**3), (t, 0, 2)))
def test_sympy__vector__scalar__BaseScalar():
from sympy.vector.scalar import BaseScalar
from sympy.vector.coordsysrect import CoordSys3D
C = CoordSys3D('C')
assert _test_args(BaseScalar(0, C, ' ', ' '))
def test_sympy__physics__wigner__Wigner3j():
from sympy.physics.wigner import Wigner3j
assert _test_args(Wigner3j(0, 0, 0, 0, 0, 0))
def test_sympy__combinatorics__schur_number__SchurNumber():
from sympy.combinatorics.schur_number import SchurNumber
assert _test_args(SchurNumber(x))
def test_sympy__combinatorics__perm_groups__SymmetricPermutationGroup():
from sympy.combinatorics.perm_groups import SymmetricPermutationGroup
assert _test_args(SymmetricPermutationGroup(5))
def test_sympy__combinatorics__perm_groups__Coset():
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.perm_groups import PermutationGroup, Coset
a = Permutation(1, 2)
b = Permutation(0, 1)
G = PermutationGroup([a, b])
assert _test_args(Coset(a, G))
|
02015ddd124031a908e80c420f37ceac68125fb51e023c6f3c7b374739369ece | import numbers as nums
import decimal
from sympy.concrete.summations import Sum
from sympy.core import (EulerGamma, Catalan, TribonacciConstant,
GoldenRatio)
from sympy.core.containers import Tuple
from sympy.core.expr import unchanged
from sympy.core.logic import fuzzy_not
from sympy.core.mul import Mul
from sympy.core.numbers import (mpf_norm, mod_inverse, igcd, seterr,
igcd_lehmer, Integer, I, pi, comp, ilcm, Rational, E, nan, igcd2,
oo, AlgebraicNumber, igcdex, Number, Float, zoo, equal_valued)
from sympy.core.power import Pow
from sympy.core.relational import Ge, Gt, Le, Lt
from sympy.core.singleton import S
from sympy.core.symbol import Dummy, Symbol
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.integers import floor
from sympy.functions.combinatorial.numbers import fibonacci
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.miscellaneous import sqrt, cbrt
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.polys.domains.realfield import RealField
from sympy.printing.latex import latex
from sympy.printing.repr import srepr
from sympy.simplify import simplify
from sympy.core.power import integer_nthroot, isqrt, integer_log
from sympy.polys.domains.groundtypes import PythonRational
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.utilities.iterables import permutations
from sympy.testing.pytest import XFAIL, raises, _both_exp_pow
from mpmath import mpf
from mpmath.rational import mpq
import mpmath
from sympy.core import numbers
t = Symbol('t', real=False)
_ninf = float(-oo)
_inf = float(oo)
def same_and_same_prec(a, b):
# stricter matching for Floats
return a == b and a._prec == b._prec
def test_seterr():
seterr(divide=True)
raises(ValueError, lambda: S.Zero/S.Zero)
seterr(divide=False)
assert S.Zero / S.Zero is S.NaN
def test_mod():
x = S.Half
y = Rational(3, 4)
z = Rational(5, 18043)
assert x % x == 0
assert x % y == S.Half
assert x % z == Rational(3, 36086)
assert y % x == Rational(1, 4)
assert y % y == 0
assert y % z == Rational(9, 72172)
assert z % x == Rational(5, 18043)
assert z % y == Rational(5, 18043)
assert z % z == 0
a = Float(2.6)
assert (a % .2) == 0.0
assert (a % 2).round(15) == 0.6
assert (a % 0.5).round(15) == 0.1
p = Symbol('p', infinite=True)
assert oo % oo is nan
assert zoo % oo is nan
assert 5 % oo is nan
assert p % 5 is nan
# In these two tests, if the precision of m does
# not match the precision of the ans, then it is
# likely that the change made now gives an answer
# with degraded accuracy.
r = Rational(500, 41)
f = Float('.36', 3)
m = r % f
ans = Float(r % Rational(f), 3)
assert m == ans and m._prec == ans._prec
f = Float('8.36', 3)
m = f % r
ans = Float(Rational(f) % r, 3)
assert m == ans and m._prec == ans._prec
s = S.Zero
assert s % float(1) == 0.0
# No rounding required since these numbers can be represented
# exactly.
assert Rational(3, 4) % Float(1.1) == 0.75
assert Float(1.5) % Rational(5, 4) == 0.25
assert Rational(5, 4).__rmod__(Float('1.5')) == 0.25
assert Float('1.5').__rmod__(Float('2.75')) == Float('1.25')
assert 2.75 % Float('1.5') == Float('1.25')
a = Integer(7)
b = Integer(4)
assert type(a % b) == Integer
assert a % b == Integer(3)
assert Integer(1) % Rational(2, 3) == Rational(1, 3)
assert Rational(7, 5) % Integer(1) == Rational(2, 5)
assert Integer(2) % 1.5 == 0.5
assert Integer(3).__rmod__(Integer(10)) == Integer(1)
assert Integer(10) % 4 == Integer(2)
assert 15 % Integer(4) == Integer(3)
def test_divmod():
x = Symbol("x")
assert divmod(S(12), S(8)) == Tuple(1, 4)
assert divmod(-S(12), S(8)) == Tuple(-2, 4)
assert divmod(S.Zero, S.One) == Tuple(0, 0)
raises(ZeroDivisionError, lambda: divmod(S.Zero, S.Zero))
raises(ZeroDivisionError, lambda: divmod(S.One, S.Zero))
assert divmod(S(12), 8) == Tuple(1, 4)
assert divmod(12, S(8)) == Tuple(1, 4)
assert S(1024)//x == 1024//x == floor(1024/x)
assert divmod(S("2"), S("3/2")) == Tuple(S("1"), S("1/2"))
assert divmod(S("3/2"), S("2")) == Tuple(S("0"), S("3/2"))
assert divmod(S("2"), S("3.5")) == Tuple(S("0"), S("2"))
assert divmod(S("3.5"), S("2")) == Tuple(S("1"), S("1.5"))
assert divmod(S("2"), S("1/3")) == Tuple(S("6"), S("0"))
assert divmod(S("1/3"), S("2")) == Tuple(S("0"), S("1/3"))
assert divmod(S("2"), S("1/10")) == Tuple(S("20"), S("0"))
assert divmod(S("2"), S(".1"))[0] == 19
assert divmod(S("0.1"), S("2")) == Tuple(S("0"), S("0.1"))
assert divmod(S("2"), 2) == Tuple(S("1"), S("0"))
assert divmod(2, S("2")) == Tuple(S("1"), S("0"))
assert divmod(S("2"), 1.5) == Tuple(S("1"), S("0.5"))
assert divmod(1.5, S("2")) == Tuple(S("0"), S("1.5"))
assert divmod(0.3, S("2")) == Tuple(S("0"), S("0.3"))
assert divmod(S("3/2"), S("3.5")) == Tuple(S("0"), S("3/2"))
assert divmod(S("3.5"), S("3/2")) == Tuple(S("2"), S("0.5"))
assert divmod(S("3/2"), S("1/3")) == Tuple(S("4"), S("1/6"))
assert divmod(S("1/3"), S("3/2")) == Tuple(S("0"), S("1/3"))
assert divmod(S("3/2"), S("0.1"))[0] == 14
assert divmod(S("0.1"), S("3/2")) == Tuple(S("0"), S("0.1"))
assert divmod(S("3/2"), 2) == Tuple(S("0"), S("3/2"))
assert divmod(2, S("3/2")) == Tuple(S("1"), S("1/2"))
assert divmod(S("3/2"), 1.5) == Tuple(S("1"), S("0"))
assert divmod(1.5, S("3/2")) == Tuple(S("1"), S("0"))
assert divmod(S("3/2"), 0.3) == Tuple(S("5"), S("0"))
assert divmod(0.3, S("3/2")) == Tuple(S("0"), S("0.3"))
assert divmod(S("1/3"), S("3.5")) == Tuple(S("0"), S("1/3"))
assert divmod(S("3.5"), S("0.1")) == Tuple(S("35"), S("0"))
assert divmod(S("0.1"), S("3.5")) == Tuple(S("0"), S("0.1"))
assert divmod(S("3.5"), 2) == Tuple(S("1"), S("1.5"))
assert divmod(2, S("3.5")) == Tuple(S("0"), S("2"))
assert divmod(S("3.5"), 1.5) == Tuple(S("2"), S("0.5"))
assert divmod(1.5, S("3.5")) == Tuple(S("0"), S("1.5"))
assert divmod(0.3, S("3.5")) == Tuple(S("0"), S("0.3"))
assert divmod(S("0.1"), S("1/3")) == Tuple(S("0"), S("0.1"))
assert divmod(S("1/3"), 2) == Tuple(S("0"), S("1/3"))
assert divmod(2, S("1/3")) == Tuple(S("6"), S("0"))
assert divmod(S("1/3"), 1.5) == Tuple(S("0"), S("1/3"))
assert divmod(0.3, S("1/3")) == Tuple(S("0"), S("0.3"))
assert divmod(S("0.1"), 2) == Tuple(S("0"), S("0.1"))
assert divmod(2, S("0.1"))[0] == 19
assert divmod(S("0.1"), 1.5) == Tuple(S("0"), S("0.1"))
assert divmod(1.5, S("0.1")) == Tuple(S("15"), S("0"))
assert divmod(S("0.1"), 0.3) == Tuple(S("0"), S("0.1"))
assert str(divmod(S("2"), 0.3)) == '(6, 0.2)'
assert str(divmod(S("3.5"), S("1/3"))) == '(10, 0.166666666666667)'
assert str(divmod(S("3.5"), 0.3)) == '(11, 0.2)'
assert str(divmod(S("1/3"), S("0.1"))) == '(3, 0.0333333333333333)'
assert str(divmod(1.5, S("1/3"))) == '(4, 0.166666666666667)'
assert str(divmod(S("1/3"), 0.3)) == '(1, 0.0333333333333333)'
assert str(divmod(0.3, S("0.1"))) == '(2, 0.1)'
assert divmod(-3, S(2)) == (-2, 1)
assert divmod(S(-3), S(2)) == (-2, 1)
assert divmod(S(-3), 2) == (-2, 1)
assert divmod(S(4), S(-3.1)) == Tuple(-2, -2.2)
assert divmod(S(4), S(-2.1)) == divmod(4, -2.1)
assert divmod(S(-8), S(-2.5) ) == Tuple(3, -0.5)
assert divmod(oo, 1) == (S.NaN, S.NaN)
assert divmod(S.NaN, 1) == (S.NaN, S.NaN)
assert divmod(1, S.NaN) == (S.NaN, S.NaN)
ans = [(-1, oo), (-1, oo), (0, 0), (0, 1), (0, 2)]
OO = float('inf')
ANS = [tuple(map(float, i)) for i in ans]
assert [divmod(i, oo) for i in range(-2, 3)] == ans
ans = [(0, -2), (0, -1), (0, 0), (-1, -oo), (-1, -oo)]
ANS = [tuple(map(float, i)) for i in ans]
assert [divmod(i, -oo) for i in range(-2, 3)] == ans
assert [divmod(i, -OO) for i in range(-2, 3)] == ANS
assert divmod(S(3.5), S(-2)) == divmod(3.5, -2)
assert divmod(-S(3.5), S(-2)) == divmod(-3.5, -2)
assert divmod(S(0.0), S(9)) == divmod(0.0, 9)
assert divmod(S(0), S(9.0)) == divmod(0, 9.0)
def test_igcd():
assert igcd(0, 0) == 0
assert igcd(0, 1) == 1
assert igcd(1, 0) == 1
assert igcd(0, 7) == 7
assert igcd(7, 0) == 7
assert igcd(7, 1) == 1
assert igcd(1, 7) == 1
assert igcd(-1, 0) == 1
assert igcd(0, -1) == 1
assert igcd(-1, -1) == 1
assert igcd(-1, 7) == 1
assert igcd(7, -1) == 1
assert igcd(8, 2) == 2
assert igcd(4, 8) == 4
assert igcd(8, 16) == 8
assert igcd(7, -3) == 1
assert igcd(-7, 3) == 1
assert igcd(-7, -3) == 1
assert igcd(*[10, 20, 30]) == 10
raises(TypeError, lambda: igcd())
raises(TypeError, lambda: igcd(2))
raises(ValueError, lambda: igcd(0, None))
raises(ValueError, lambda: igcd(1, 2.2))
for args in permutations((45.1, 1, 30)):
raises(ValueError, lambda: igcd(*args))
for args in permutations((1, 2, None)):
raises(ValueError, lambda: igcd(*args))
def test_igcd_lehmer():
a, b = fibonacci(10001), fibonacci(10000)
# len(str(a)) == 2090
# small divisors, long Euclidean sequence
assert igcd_lehmer(a, b) == 1
c = fibonacci(100)
assert igcd_lehmer(a*c, b*c) == c
# big divisor
assert igcd_lehmer(a, 10**1000) == 1
# swapping argument
assert igcd_lehmer(1, 2) == igcd_lehmer(2, 1)
def test_igcd2():
# short loop
assert igcd2(2**100 - 1, 2**99 - 1) == 1
# Lehmer's algorithm
a, b = int(fibonacci(10001)), int(fibonacci(10000))
assert igcd2(a, b) == 1
def test_ilcm():
assert ilcm(0, 0) == 0
assert ilcm(1, 0) == 0
assert ilcm(0, 1) == 0
assert ilcm(1, 1) == 1
assert ilcm(2, 1) == 2
assert ilcm(8, 2) == 8
assert ilcm(8, 6) == 24
assert ilcm(8, 7) == 56
assert ilcm(*[10, 20, 30]) == 60
raises(ValueError, lambda: ilcm(8.1, 7))
raises(ValueError, lambda: ilcm(8, 7.1))
raises(TypeError, lambda: ilcm(8))
def test_igcdex():
assert igcdex(2, 3) == (-1, 1, 1)
assert igcdex(10, 12) == (-1, 1, 2)
assert igcdex(100, 2004) == (-20, 1, 4)
assert igcdex(0, 0) == (0, 1, 0)
assert igcdex(1, 0) == (1, 0, 1)
def _strictly_equal(a, b):
return (a.p, a.q, type(a.p), type(a.q)) == \
(b.p, b.q, type(b.p), type(b.q))
def _test_rational_new(cls):
"""
Tests that are common between Integer and Rational.
"""
assert cls(0) is S.Zero
assert cls(1) is S.One
assert cls(-1) is S.NegativeOne
# These look odd, but are similar to int():
assert cls('1') is S.One
assert cls('-1') is S.NegativeOne
i = Integer(10)
assert _strictly_equal(i, cls('10'))
assert _strictly_equal(i, cls('10'))
assert _strictly_equal(i, cls(int(10)))
assert _strictly_equal(i, cls(i))
raises(TypeError, lambda: cls(Symbol('x')))
def test_Integer_new():
"""
Test for Integer constructor
"""
_test_rational_new(Integer)
assert _strictly_equal(Integer(0.9), S.Zero)
assert _strictly_equal(Integer(10.5), Integer(10))
raises(ValueError, lambda: Integer("10.5"))
assert Integer(Rational('1.' + '9'*20)) == 1
def test_Rational_new():
""""
Test for Rational constructor
"""
_test_rational_new(Rational)
n1 = S.Half
assert n1 == Rational(Integer(1), 2)
assert n1 == Rational(Integer(1), Integer(2))
assert n1 == Rational(1, Integer(2))
assert n1 == Rational(S.Half)
assert 1 == Rational(n1, n1)
assert Rational(3, 2) == Rational(S.Half, Rational(1, 3))
assert Rational(3, 1) == Rational(1, Rational(1, 3))
n3_4 = Rational(3, 4)
assert Rational('3/4') == n3_4
assert -Rational('-3/4') == n3_4
assert Rational('.76').limit_denominator(4) == n3_4
assert Rational(19, 25).limit_denominator(4) == n3_4
assert Rational('19/25').limit_denominator(4) == n3_4
assert Rational(1.0, 3) == Rational(1, 3)
assert Rational(1, 3.0) == Rational(1, 3)
assert Rational(Float(0.5)) == S.Half
assert Rational('1e2/1e-2') == Rational(10000)
assert Rational('1 234') == Rational(1234)
assert Rational('1/1 234') == Rational(1, 1234)
assert Rational(-1, 0) is S.ComplexInfinity
assert Rational(1, 0) is S.ComplexInfinity
# Make sure Rational doesn't lose precision on Floats
assert Rational(pi.evalf(100)).evalf(100) == pi.evalf(100)
raises(TypeError, lambda: Rational('3**3'))
raises(TypeError, lambda: Rational('1/2 + 2/3'))
# handle fractions.Fraction instances
try:
import fractions
assert Rational(fractions.Fraction(1, 2)) == S.Half
except ImportError:
pass
assert Rational(mpq(2, 6)) == Rational(1, 3)
assert Rational(PythonRational(2, 6)) == Rational(1, 3)
assert Rational(2, 4, gcd=1).q == 4
n = Rational(2, -4, gcd=1)
assert n.q == 4
assert n.p == -2
def test_issue_24543():
for p in ('1.5', 1.5, 2):
for q in ('1.5', 1.5, 2):
assert Rational(p, q).as_numer_denom() == Rational('%s/%s'%(p,q)).as_numer_denom()
assert Rational('0.5', '100') == Rational(1, 200)
def test_Number_new():
""""
Test for Number constructor
"""
# Expected behavior on numbers and strings
assert Number(1) is S.One
assert Number(2).__class__ is Integer
assert Number(-622).__class__ is Integer
assert Number(5, 3).__class__ is Rational
assert Number(5.3).__class__ is Float
assert Number('1') is S.One
assert Number('2').__class__ is Integer
assert Number('-622').__class__ is Integer
assert Number('5/3').__class__ is Rational
assert Number('5.3').__class__ is Float
raises(ValueError, lambda: Number('cos'))
raises(TypeError, lambda: Number(cos))
a = Rational(3, 5)
assert Number(a) is a # Check idempotence on Numbers
u = ['inf', '-inf', 'nan', 'iNF', '+inf']
v = [oo, -oo, nan, oo, oo]
for i, a in zip(u, v):
assert Number(i) is a, (i, Number(i), a)
def test_Number_cmp():
n1 = Number(1)
n2 = Number(2)
n3 = Number(-3)
assert n1 < n2
assert n1 <= n2
assert n3 < n1
assert n2 > n3
assert n2 >= n3
raises(TypeError, lambda: n1 < S.NaN)
raises(TypeError, lambda: n1 <= S.NaN)
raises(TypeError, lambda: n1 > S.NaN)
raises(TypeError, lambda: n1 >= S.NaN)
def test_Rational_cmp():
n1 = Rational(1, 4)
n2 = Rational(1, 3)
n3 = Rational(2, 4)
n4 = Rational(2, -4)
n5 = Rational(0)
n6 = Rational(1)
n7 = Rational(3)
n8 = Rational(-3)
assert n8 < n5
assert n5 < n6
assert n6 < n7
assert n8 < n7
assert n7 > n8
assert (n1 + 1)**n2 < 2
assert ((n1 + n6)/n7) < 1
assert n4 < n3
assert n2 < n3
assert n1 < n2
assert n3 > n1
assert not n3 < n1
assert not (Rational(-1) > 0)
assert Rational(-1) < 0
raises(TypeError, lambda: n1 < S.NaN)
raises(TypeError, lambda: n1 <= S.NaN)
raises(TypeError, lambda: n1 > S.NaN)
raises(TypeError, lambda: n1 >= S.NaN)
def test_Float():
def eq(a, b):
t = Float("1.0E-15")
return (-t < a - b < t)
zeros = (0, S.Zero, 0., Float(0))
for i, j in permutations(zeros, 2):
assert i == j
for z in zeros:
assert z in zeros
assert S.Zero.is_zero
a = Float(2) ** Float(3)
assert eq(a.evalf(), Float(8))
assert eq((pi ** -1).evalf(), Float("0.31830988618379067"))
a = Float(2) ** Float(4)
assert eq(a.evalf(), Float(16))
assert (S(.3) == S(.5)) is False
mpf = (0, 5404319552844595, -52, 53)
x_str = Float((0, '13333333333333', -52, 53))
x_0xstr = Float((0, '0x13333333333333', -52, 53))
x2_str = Float((0, '26666666666666', -53, 54))
x_hex = Float((0, int(0x13333333333333), -52, 53))
x_dec = Float(mpf)
assert x_str == x_0xstr == x_hex == x_dec == Float(1.2)
# x2_str was entered slightly malformed in that the mantissa
# was even -- it should be odd and the even part should be
# included with the exponent, but this is resolved by normalization
# ONLY IF REQUIREMENTS of mpf_norm are met: the bitcount must
# be exact: double the mantissa ==> increase bc by 1
assert Float(1.2)._mpf_ == mpf
assert x2_str._mpf_ == mpf
assert Float((0, int(0), -123, -1)) is S.NaN
assert Float((0, int(0), -456, -2)) is S.Infinity
assert Float((1, int(0), -789, -3)) is S.NegativeInfinity
# if you don't give the full signature, it's not special
assert Float((0, int(0), -123)) == Float(0)
assert Float((0, int(0), -456)) == Float(0)
assert Float((1, int(0), -789)) == Float(0)
raises(ValueError, lambda: Float((0, 7, 1, 3), ''))
assert Float('0.0').is_finite is True
assert Float('0.0').is_negative is False
assert Float('0.0').is_positive is False
assert Float('0.0').is_infinite is False
assert Float('0.0').is_zero is True
# rationality properties
# if the integer test fails then the use of intlike
# should be removed from gamma_functions.py
assert Float(1).is_integer is False
assert Float(1).is_rational is None
assert Float(1).is_irrational is None
assert sqrt(2).n(15).is_rational is None
assert sqrt(2).n(15).is_irrational is None
# do not automatically evalf
def teq(a):
assert (a.evalf() == a) is False
assert (a.evalf() != a) is True
assert (a == a.evalf()) is False
assert (a != a.evalf()) is True
teq(pi)
teq(2*pi)
teq(cos(0.1, evaluate=False))
# long integer
i = 12345678901234567890
assert same_and_same_prec(Float(12, ''), Float('12', ''))
assert same_and_same_prec(Float(Integer(i), ''), Float(i, ''))
assert same_and_same_prec(Float(i, ''), Float(str(i), 20))
assert same_and_same_prec(Float(str(i)), Float(i, ''))
assert same_and_same_prec(Float(i), Float(i, ''))
# inexact floats (repeating binary = denom not multiple of 2)
# cannot have precision greater than 15
assert Float(.125, 22) == .125
assert Float(2.0, 22) == 2
assert float(Float('.12500000000000001', '')) == .125
raises(ValueError, lambda: Float(.12500000000000001, ''))
# allow spaces
assert Float('123 456.123 456') == Float('123456.123456')
assert Integer('123 456') == Integer('123456')
assert Rational('123 456.123 456') == Rational('123456.123456')
assert Float(' .3e2') == Float('0.3e2')
# allow underscore
assert Float('1_23.4_56') == Float('123.456')
assert Float('1_') == Float('1.0')
assert Float('1_.') == Float('1.0')
assert Float('1._') == Float('1.0')
assert Float('1__2') == Float('12.0')
# assert Float('1_23.4_5_6', 12) == Float('123.456', 12)
# ...but not in all cases (per Py 3.6)
raises(ValueError, lambda: Float('_1'))
raises(ValueError, lambda: Float('_inf'))
# allow auto precision detection
assert Float('.1', '') == Float(.1, 1)
assert Float('.125', '') == Float(.125, 3)
assert Float('.100', '') == Float(.1, 3)
assert Float('2.0', '') == Float('2', 2)
raises(ValueError, lambda: Float("12.3d-4", ""))
raises(ValueError, lambda: Float(12.3, ""))
raises(ValueError, lambda: Float('.'))
raises(ValueError, lambda: Float('-.'))
zero = Float('0.0')
assert Float('-0') == zero
assert Float('.0') == zero
assert Float('-.0') == zero
assert Float('-0.0') == zero
assert Float(0.0) == zero
assert Float(0) == zero
assert Float(0, '') == Float('0', '')
assert Float(1) == Float(1.0)
assert Float(S.Zero) == zero
assert Float(S.One) == Float(1.0)
assert Float(decimal.Decimal('0.1'), 3) == Float('.1', 3)
assert Float(decimal.Decimal('nan')) is S.NaN
assert Float(decimal.Decimal('Infinity')) is S.Infinity
assert Float(decimal.Decimal('-Infinity')) is S.NegativeInfinity
assert '{:.3f}'.format(Float(4.236622)) == '4.237'
assert '{:.35f}'.format(Float(pi.n(40), 40)) == \
'3.14159265358979323846264338327950288'
# unicode
assert Float('0.73908513321516064100000000') == \
Float('0.73908513321516064100000000')
assert Float('0.73908513321516064100000000', 28) == \
Float('0.73908513321516064100000000', 28)
# binary precision
# Decimal value 0.1 cannot be expressed precisely as a base 2 fraction
a = Float(S.One/10, dps=15)
b = Float(S.One/10, dps=16)
p = Float(S.One/10, precision=53)
q = Float(S.One/10, precision=54)
assert a._mpf_ == p._mpf_
assert not a._mpf_ == q._mpf_
assert not b._mpf_ == q._mpf_
# Precision specifying errors
raises(ValueError, lambda: Float("1.23", dps=3, precision=10))
raises(ValueError, lambda: Float("1.23", dps="", precision=10))
raises(ValueError, lambda: Float("1.23", dps=3, precision=""))
raises(ValueError, lambda: Float("1.23", dps="", precision=""))
# from NumberSymbol
assert same_and_same_prec(Float(pi, 32), pi.evalf(32))
assert same_and_same_prec(Float(Catalan), Catalan.evalf())
# oo and nan
u = ['inf', '-inf', 'nan', 'iNF', '+inf']
v = [oo, -oo, nan, oo, oo]
for i, a in zip(u, v):
assert Float(i) is a
def test_zero_not_false():
# https://github.com/sympy/sympy/issues/20796
assert (S(0.0) == S.false) is False
assert (S.false == S(0.0)) is False
assert (S(0) == S.false) is False
assert (S.false == S(0)) is False
@conserve_mpmath_dps
def test_float_mpf():
import mpmath
mpmath.mp.dps = 100
mp_pi = mpmath.pi()
assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100)
mpmath.mp.dps = 15
assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100)
def test_Float_RealElement():
repi = RealField(dps=100)(pi.evalf(100))
# We still have to pass the precision because Float doesn't know what
# RealElement is, but make sure it keeps full precision from the result.
assert Float(repi, 100) == pi.evalf(100)
def test_Float_default_to_highprec_from_str():
s = str(pi.evalf(128))
assert same_and_same_prec(Float(s), Float(s, ''))
def test_Float_eval():
a = Float(3.2)
assert (a**2).is_Float
def test_Float_issue_2107():
a = Float(0.1, 10)
b = Float("0.1", 10)
assert a - a == 0
assert a + (-a) == 0
assert S.Zero + a - a == 0
assert S.Zero + a + (-a) == 0
assert b - b == 0
assert b + (-b) == 0
assert S.Zero + b - b == 0
assert S.Zero + b + (-b) == 0
def test_issue_14289():
from sympy.polys.numberfields import to_number_field
a = 1 - sqrt(2)
b = to_number_field(a)
assert b.as_expr() == a
assert b.minpoly(a).expand() == 0
def test_Float_from_tuple():
a = Float((0, '1L', 0, 1))
b = Float((0, '1', 0, 1))
assert a == b
def test_Infinity():
assert oo != 1
assert 1*oo is oo
assert 1 != oo
assert oo != -oo
assert oo != Symbol("x")**3
assert oo + 1 is oo
assert 2 + oo is oo
assert 3*oo + 2 is oo
assert S.Half**oo == 0
assert S.Half**(-oo) is oo
assert -oo*3 is -oo
assert oo + oo is oo
assert -oo + oo*(-5) is -oo
assert 1/oo == 0
assert 1/(-oo) == 0
assert 8/oo == 0
assert oo % 2 is nan
assert 2 % oo is nan
assert oo/oo is nan
assert oo/-oo is nan
assert -oo/oo is nan
assert -oo/-oo is nan
assert oo - oo is nan
assert oo - -oo is oo
assert -oo - oo is -oo
assert -oo - -oo is nan
assert oo + -oo is nan
assert -oo + oo is nan
assert oo + oo is oo
assert -oo + oo is nan
assert oo + -oo is nan
assert -oo + -oo is -oo
assert oo*oo is oo
assert -oo*oo is -oo
assert oo*-oo is -oo
assert -oo*-oo is oo
assert oo/0 is oo
assert -oo/0 is -oo
assert 0/oo == 0
assert 0/-oo == 0
assert oo*0 is nan
assert -oo*0 is nan
assert 0*oo is nan
assert 0*-oo is nan
assert oo + 0 is oo
assert -oo + 0 is -oo
assert 0 + oo is oo
assert 0 + -oo is -oo
assert oo - 0 is oo
assert -oo - 0 is -oo
assert 0 - oo is -oo
assert 0 - -oo is oo
assert oo/2 is oo
assert -oo/2 is -oo
assert oo/-2 is -oo
assert -oo/-2 is oo
assert oo*2 is oo
assert -oo*2 is -oo
assert oo*-2 is -oo
assert 2/oo == 0
assert 2/-oo == 0
assert -2/oo == 0
assert -2/-oo == 0
assert 2*oo is oo
assert 2*-oo is -oo
assert -2*oo is -oo
assert -2*-oo is oo
assert 2 + oo is oo
assert 2 - oo is -oo
assert -2 + oo is oo
assert -2 - oo is -oo
assert 2 + -oo is -oo
assert 2 - -oo is oo
assert -2 + -oo is -oo
assert -2 - -oo is oo
assert S(2) + oo is oo
assert S(2) - oo is -oo
assert oo/I == -oo*I
assert -oo/I == oo*I
assert oo*float(1) == _inf and (oo*float(1)) is oo
assert -oo*float(1) == _ninf and (-oo*float(1)) is -oo
assert oo/float(1) == _inf and (oo/float(1)) is oo
assert -oo/float(1) == _ninf and (-oo/float(1)) is -oo
assert oo*float(-1) == _ninf and (oo*float(-1)) is -oo
assert -oo*float(-1) == _inf and (-oo*float(-1)) is oo
assert oo/float(-1) == _ninf and (oo/float(-1)) is -oo
assert -oo/float(-1) == _inf and (-oo/float(-1)) is oo
assert oo + float(1) == _inf and (oo + float(1)) is oo
assert -oo + float(1) == _ninf and (-oo + float(1)) is -oo
assert oo - float(1) == _inf and (oo - float(1)) is oo
assert -oo - float(1) == _ninf and (-oo - float(1)) is -oo
assert float(1)*oo == _inf and (float(1)*oo) is oo
assert float(1)*-oo == _ninf and (float(1)*-oo) is -oo
assert float(1)/oo == 0
assert float(1)/-oo == 0
assert float(-1)*oo == _ninf and (float(-1)*oo) is -oo
assert float(-1)*-oo == _inf and (float(-1)*-oo) is oo
assert float(-1)/oo == 0
assert float(-1)/-oo == 0
assert float(1) + oo is oo
assert float(1) + -oo is -oo
assert float(1) - oo is -oo
assert float(1) - -oo is oo
assert oo == float(oo)
assert (oo != float(oo)) is False
assert type(float(oo)) is float
assert -oo == float(-oo)
assert (-oo != float(-oo)) is False
assert type(float(-oo)) is float
assert Float('nan') is nan
assert nan*1.0 is nan
assert -1.0*nan is nan
assert nan*oo is nan
assert nan*-oo is nan
assert nan/oo is nan
assert nan/-oo is nan
assert nan + oo is nan
assert nan + -oo is nan
assert nan - oo is nan
assert nan - -oo is nan
assert -oo * S.Zero is nan
assert oo*nan is nan
assert -oo*nan is nan
assert oo/nan is nan
assert -oo/nan is nan
assert oo + nan is nan
assert -oo + nan is nan
assert oo - nan is nan
assert -oo - nan is nan
assert S.Zero * oo is nan
assert oo.is_Rational is False
assert isinstance(oo, Rational) is False
assert S.One/oo == 0
assert -S.One/oo == 0
assert S.One/-oo == 0
assert -S.One/-oo == 0
assert S.One*oo is oo
assert -S.One*oo is -oo
assert S.One*-oo is -oo
assert -S.One*-oo is oo
assert S.One/nan is nan
assert S.One - -oo is oo
assert S.One + nan is nan
assert S.One - nan is nan
assert nan - S.One is nan
assert nan/S.One is nan
assert -oo - S.One is -oo
def test_Infinity_2():
x = Symbol('x')
assert oo*x != oo
assert oo*(pi - 1) is oo
assert oo*(1 - pi) is -oo
assert (-oo)*x != -oo
assert (-oo)*(pi - 1) is -oo
assert (-oo)*(1 - pi) is oo
assert (-1)**S.NaN is S.NaN
assert oo - _inf is S.NaN
assert oo + _ninf is S.NaN
assert oo*0 is S.NaN
assert oo/_inf is S.NaN
assert oo/_ninf is S.NaN
assert oo**S.NaN is S.NaN
assert -oo + _inf is S.NaN
assert -oo - _ninf is S.NaN
assert -oo*S.NaN is S.NaN
assert -oo*0 is S.NaN
assert -oo/_inf is S.NaN
assert -oo/_ninf is S.NaN
assert -oo/S.NaN is S.NaN
assert abs(-oo) is oo
assert all((-oo)**i is S.NaN for i in (oo, -oo, S.NaN))
assert (-oo)**3 is -oo
assert (-oo)**2 is oo
assert abs(S.ComplexInfinity) is oo
def test_Mul_Infinity_Zero():
assert Float(0)*_inf is nan
assert Float(0)*_ninf is nan
assert Float(0)*_inf is nan
assert Float(0)*_ninf is nan
assert _inf*Float(0) is nan
assert _ninf*Float(0) is nan
assert _inf*Float(0) is nan
assert _ninf*Float(0) is nan
def test_Div_By_Zero():
assert 1/S.Zero is zoo
assert 1/Float(0) is zoo
assert 0/S.Zero is nan
assert 0/Float(0) is nan
assert S.Zero/0 is nan
assert Float(0)/0 is nan
assert -1/S.Zero is zoo
assert -1/Float(0) is zoo
@_both_exp_pow
def test_Infinity_inequations():
assert oo > pi
assert not (oo < pi)
assert exp(-3) < oo
assert _inf > pi
assert not (_inf < pi)
assert exp(-3) < _inf
raises(TypeError, lambda: oo < I)
raises(TypeError, lambda: oo <= I)
raises(TypeError, lambda: oo > I)
raises(TypeError, lambda: oo >= I)
raises(TypeError, lambda: -oo < I)
raises(TypeError, lambda: -oo <= I)
raises(TypeError, lambda: -oo > I)
raises(TypeError, lambda: -oo >= I)
raises(TypeError, lambda: I < oo)
raises(TypeError, lambda: I <= oo)
raises(TypeError, lambda: I > oo)
raises(TypeError, lambda: I >= oo)
raises(TypeError, lambda: I < -oo)
raises(TypeError, lambda: I <= -oo)
raises(TypeError, lambda: I > -oo)
raises(TypeError, lambda: I >= -oo)
assert oo > -oo and oo >= -oo
assert (oo < -oo) == False and (oo <= -oo) == False
assert -oo < oo and -oo <= oo
assert (-oo > oo) == False and (-oo >= oo) == False
assert (oo < oo) == False # issue 7775
assert (oo > oo) == False
assert (-oo > -oo) == False and (-oo < -oo) == False
assert oo >= oo and oo <= oo and -oo >= -oo and -oo <= -oo
assert (-oo < -_inf) == False
assert (oo > _inf) == False
assert -oo >= -_inf
assert oo <= _inf
x = Symbol('x')
b = Symbol('b', finite=True, real=True)
assert (x < oo) == Lt(x, oo) # issue 7775
assert b < oo and b > -oo and b <= oo and b >= -oo
assert oo > b and oo >= b and (oo < b) == False and (oo <= b) == False
assert (-oo > b) == False and (-oo >= b) == False and -oo < b and -oo <= b
assert (oo < x) == Lt(oo, x) and (oo > x) == Gt(oo, x)
assert (oo <= x) == Le(oo, x) and (oo >= x) == Ge(oo, x)
assert (-oo < x) == Lt(-oo, x) and (-oo > x) == Gt(-oo, x)
assert (-oo <= x) == Le(-oo, x) and (-oo >= x) == Ge(-oo, x)
def test_NaN():
assert nan is nan
assert nan != 1
assert 1*nan is nan
assert 1 != nan
assert -nan is nan
assert oo != Symbol("x")**3
assert 2 + nan is nan
assert 3*nan + 2 is nan
assert -nan*3 is nan
assert nan + nan is nan
assert -nan + nan*(-5) is nan
assert 8/nan is nan
raises(TypeError, lambda: nan > 0)
raises(TypeError, lambda: nan < 0)
raises(TypeError, lambda: nan >= 0)
raises(TypeError, lambda: nan <= 0)
raises(TypeError, lambda: 0 < nan)
raises(TypeError, lambda: 0 > nan)
raises(TypeError, lambda: 0 <= nan)
raises(TypeError, lambda: 0 >= nan)
assert nan**0 == 1 # as per IEEE 754
assert 1**nan is nan # IEEE 754 is not the best choice for symbolic work
# test Pow._eval_power's handling of NaN
assert Pow(nan, 0, evaluate=False)**2 == 1
for n in (1, 1., S.One, S.NegativeOne, Float(1)):
assert n + nan is nan
assert n - nan is nan
assert nan + n is nan
assert nan - n is nan
assert n/nan is nan
assert nan/n is nan
def test_special_numbers():
assert isinstance(S.NaN, Number) is True
assert isinstance(S.Infinity, Number) is True
assert isinstance(S.NegativeInfinity, Number) is True
assert S.NaN.is_number is True
assert S.Infinity.is_number is True
assert S.NegativeInfinity.is_number is True
assert S.ComplexInfinity.is_number is True
assert isinstance(S.NaN, Rational) is False
assert isinstance(S.Infinity, Rational) is False
assert isinstance(S.NegativeInfinity, Rational) is False
assert S.NaN.is_rational is not True
assert S.Infinity.is_rational is not True
assert S.NegativeInfinity.is_rational is not True
def test_powers():
assert integer_nthroot(1, 2) == (1, True)
assert integer_nthroot(1, 5) == (1, True)
assert integer_nthroot(2, 1) == (2, True)
assert integer_nthroot(2, 2) == (1, False)
assert integer_nthroot(2, 5) == (1, False)
assert integer_nthroot(4, 2) == (2, True)
assert integer_nthroot(123**25, 25) == (123, True)
assert integer_nthroot(123**25 + 1, 25) == (123, False)
assert integer_nthroot(123**25 - 1, 25) == (122, False)
assert integer_nthroot(1, 1) == (1, True)
assert integer_nthroot(0, 1) == (0, True)
assert integer_nthroot(0, 3) == (0, True)
assert integer_nthroot(10000, 1) == (10000, True)
assert integer_nthroot(4, 2) == (2, True)
assert integer_nthroot(16, 2) == (4, True)
assert integer_nthroot(26, 2) == (5, False)
assert integer_nthroot(1234567**7, 7) == (1234567, True)
assert integer_nthroot(1234567**7 + 1, 7) == (1234567, False)
assert integer_nthroot(1234567**7 - 1, 7) == (1234566, False)
b = 25**1000
assert integer_nthroot(b, 1000) == (25, True)
assert integer_nthroot(b + 1, 1000) == (25, False)
assert integer_nthroot(b - 1, 1000) == (24, False)
c = 10**400
c2 = c**2
assert integer_nthroot(c2, 2) == (c, True)
assert integer_nthroot(c2 + 1, 2) == (c, False)
assert integer_nthroot(c2 - 1, 2) == (c - 1, False)
assert integer_nthroot(2, 10**10) == (1, False)
p, r = integer_nthroot(int(factorial(10000)), 100)
assert p % (10**10) == 5322420655
assert not r
# Test that this is fast
assert integer_nthroot(2, 10**10) == (1, False)
# output should be int if possible
assert type(integer_nthroot(2**61, 2)[0]) is int
def test_integer_nthroot_overflow():
assert integer_nthroot(10**(50*50), 50) == (10**50, True)
assert integer_nthroot(10**100000, 10000) == (10**10, True)
def test_integer_log():
raises(ValueError, lambda: integer_log(2, 1))
raises(ValueError, lambda: integer_log(0, 2))
raises(ValueError, lambda: integer_log(1.1, 2))
raises(ValueError, lambda: integer_log(1, 2.2))
assert integer_log(1, 2) == (0, True)
assert integer_log(1, 3) == (0, True)
assert integer_log(2, 3) == (0, False)
assert integer_log(3, 3) == (1, True)
assert integer_log(3*2, 3) == (1, False)
assert integer_log(3**2, 3) == (2, True)
assert integer_log(3*4, 3) == (2, False)
assert integer_log(3**3, 3) == (3, True)
assert integer_log(27, 5) == (2, False)
assert integer_log(2, 3) == (0, False)
assert integer_log(-4, -2) == (2, False)
assert integer_log(27, -3) == (3, False)
assert integer_log(-49, 7) == (0, False)
assert integer_log(-49, -7) == (2, False)
def test_isqrt():
from math import sqrt as _sqrt
limit = 4503599761588223
assert int(_sqrt(limit)) == integer_nthroot(limit, 2)[0]
assert int(_sqrt(limit + 1)) != integer_nthroot(limit + 1, 2)[0]
assert isqrt(limit + 1) == integer_nthroot(limit + 1, 2)[0]
assert isqrt(limit + S.Half) == integer_nthroot(limit, 2)[0]
assert isqrt(limit + 1 + S.Half) == integer_nthroot(limit + 1, 2)[0]
assert isqrt(limit + 2 + S.Half) == integer_nthroot(limit + 2, 2)[0]
# Regression tests for https://github.com/sympy/sympy/issues/17034
assert isqrt(4503599761588224) == 67108864
assert isqrt(9999999999999999) == 99999999
# Other corner cases, especially involving non-integers.
raises(ValueError, lambda: isqrt(-1))
raises(ValueError, lambda: isqrt(-10**1000))
raises(ValueError, lambda: isqrt(Rational(-1, 2)))
tiny = Rational(1, 10**1000)
raises(ValueError, lambda: isqrt(-tiny))
assert isqrt(1-tiny) == 0
assert isqrt(4503599761588224-tiny) == 67108864
assert isqrt(10**100 - tiny) == 10**50 - 1
# Check that using an inaccurate math.sqrt doesn't affect the results.
from sympy.core import power
old_sqrt = power._sqrt
power._sqrt = lambda x: 2.999999999
try:
assert isqrt(9) == 3
assert isqrt(10000) == 100
finally:
power._sqrt = old_sqrt
def test_powers_Integer():
"""Test Integer._eval_power"""
# check infinity
assert S.One ** S.Infinity is S.NaN
assert S.NegativeOne** S.Infinity is S.NaN
assert S(2) ** S.Infinity is S.Infinity
assert S(-2)** S.Infinity == zoo
assert S(0) ** S.Infinity is S.Zero
# check Nan
assert S.One ** S.NaN is S.NaN
assert S.NegativeOne ** S.NaN is S.NaN
# check for exact roots
assert S.NegativeOne ** Rational(6, 5) == - (-1)**(S.One/5)
assert sqrt(S(4)) == 2
assert sqrt(S(-4)) == I * 2
assert S(16) ** Rational(1, 4) == 2
assert S(-16) ** Rational(1, 4) == 2 * (-1)**Rational(1, 4)
assert S(9) ** Rational(3, 2) == 27
assert S(-9) ** Rational(3, 2) == -27*I
assert S(27) ** Rational(2, 3) == 9
assert S(-27) ** Rational(2, 3) == 9 * (S.NegativeOne ** Rational(2, 3))
assert (-2) ** Rational(-2, 1) == Rational(1, 4)
# not exact roots
assert sqrt(-3) == I*sqrt(3)
assert (3) ** (Rational(3, 2)) == 3 * sqrt(3)
assert (-3) ** (Rational(3, 2)) == - 3 * sqrt(-3)
assert (-3) ** (Rational(5, 2)) == 9 * I * sqrt(3)
assert (-3) ** (Rational(7, 2)) == - I * 27 * sqrt(3)
assert (2) ** (Rational(3, 2)) == 2 * sqrt(2)
assert (2) ** (Rational(-3, 2)) == sqrt(2) / 4
assert (81) ** (Rational(2, 3)) == 9 * (S(3) ** (Rational(2, 3)))
assert (-81) ** (Rational(2, 3)) == 9 * (S(-3) ** (Rational(2, 3)))
assert (-3) ** Rational(-7, 3) == \
-(-1)**Rational(2, 3)*3**Rational(2, 3)/27
assert (-3) ** Rational(-2, 3) == \
-(-1)**Rational(1, 3)*3**Rational(1, 3)/3
# join roots
assert sqrt(6) + sqrt(24) == 3*sqrt(6)
assert sqrt(2) * sqrt(3) == sqrt(6)
# separate symbols & constansts
x = Symbol("x")
assert sqrt(49 * x) == 7 * sqrt(x)
assert sqrt((3 - sqrt(pi)) ** 2) == 3 - sqrt(pi)
# check that it is fast for big numbers
assert (2**64 + 1) ** Rational(4, 3)
assert (2**64 + 1) ** Rational(17, 25)
# negative rational power and negative base
assert (-3) ** Rational(-7, 3) == \
-(-1)**Rational(2, 3)*3**Rational(2, 3)/27
assert (-3) ** Rational(-2, 3) == \
-(-1)**Rational(1, 3)*3**Rational(1, 3)/3
assert (-2) ** Rational(-10, 3) == \
(-1)**Rational(2, 3)*2**Rational(2, 3)/16
assert abs(Pow(-2, Rational(-10, 3)).n() -
Pow(-2, Rational(-10, 3), evaluate=False).n()) < 1e-16
# negative base and rational power with some simplification
assert (-8) ** Rational(2, 5) == \
2*(-1)**Rational(2, 5)*2**Rational(1, 5)
assert (-4) ** Rational(9, 5) == \
-8*(-1)**Rational(4, 5)*2**Rational(3, 5)
assert S(1234).factors() == {617: 1, 2: 1}
assert Rational(2*3, 3*5*7).factors() == {2: 1, 5: -1, 7: -1}
# test that eval_power factors numbers bigger than
# the current limit in factor_trial_division (2**15)
from sympy.ntheory.generate import nextprime
n = nextprime(2**15)
assert sqrt(n**2) == n
assert sqrt(n**3) == n*sqrt(n)
assert sqrt(4*n) == 2*sqrt(n)
# check that factors of base with powers sharing gcd with power are removed
assert (2**4*3)**Rational(1, 6) == 2**Rational(2, 3)*3**Rational(1, 6)
assert (2**4*3)**Rational(5, 6) == 8*2**Rational(1, 3)*3**Rational(5, 6)
# check that bases sharing a gcd are exptracted
assert 2**Rational(1, 3)*3**Rational(1, 4)*6**Rational(1, 5) == \
2**Rational(8, 15)*3**Rational(9, 20)
assert sqrt(8)*24**Rational(1, 3)*6**Rational(1, 5) == \
4*2**Rational(7, 10)*3**Rational(8, 15)
assert sqrt(8)*(-24)**Rational(1, 3)*(-6)**Rational(1, 5) == \
4*(-3)**Rational(8, 15)*2**Rational(7, 10)
assert 2**Rational(1, 3)*2**Rational(8, 9) == 2*2**Rational(2, 9)
assert 2**Rational(2, 3)*6**Rational(1, 3) == 2*3**Rational(1, 3)
assert 2**Rational(2, 3)*6**Rational(8, 9) == \
2*2**Rational(5, 9)*3**Rational(8, 9)
assert (-2)**Rational(2, S(3))*(-4)**Rational(1, S(3)) == -2*2**Rational(1, 3)
assert 3*Pow(3, 2, evaluate=False) == 3**3
assert 3*Pow(3, Rational(-1, 3), evaluate=False) == 3**Rational(2, 3)
assert (-2)**Rational(1, 3)*(-3)**Rational(1, 4)*(-5)**Rational(5, 6) == \
-(-1)**Rational(5, 12)*2**Rational(1, 3)*3**Rational(1, 4) * \
5**Rational(5, 6)
assert Integer(-2)**Symbol('', even=True) == \
Integer(2)**Symbol('', even=True)
assert (-1)**Float(.5) == 1.0*I
def test_powers_Rational():
"""Test Rational._eval_power"""
# check infinity
assert S.Half ** S.Infinity == 0
assert Rational(3, 2) ** S.Infinity is S.Infinity
assert Rational(-1, 2) ** S.Infinity == 0
assert Rational(-3, 2) ** S.Infinity == zoo
# check Nan
assert Rational(3, 4) ** S.NaN is S.NaN
assert Rational(-2, 3) ** S.NaN is S.NaN
# exact roots on numerator
assert sqrt(Rational(4, 3)) == 2 * sqrt(3) / 3
assert Rational(4, 3) ** Rational(3, 2) == 8 * sqrt(3) / 9
assert sqrt(Rational(-4, 3)) == I * 2 * sqrt(3) / 3
assert Rational(-4, 3) ** Rational(3, 2) == - I * 8 * sqrt(3) / 9
assert Rational(27, 2) ** Rational(1, 3) == 3 * (2 ** Rational(2, 3)) / 2
assert Rational(5**3, 8**3) ** Rational(4, 3) == Rational(5**4, 8**4)
# exact root on denominator
assert sqrt(Rational(1, 4)) == S.Half
assert sqrt(Rational(1, -4)) == I * S.Half
assert sqrt(Rational(3, 4)) == sqrt(3) / 2
assert sqrt(Rational(3, -4)) == I * sqrt(3) / 2
assert Rational(5, 27) ** Rational(1, 3) == (5 ** Rational(1, 3)) / 3
# not exact roots
assert sqrt(S.Half) == sqrt(2) / 2
assert sqrt(Rational(-4, 7)) == I * sqrt(Rational(4, 7))
assert Rational(-3, 2)**Rational(-7, 3) == \
-4*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/27
assert Rational(-3, 2)**Rational(-2, 3) == \
-(-1)**Rational(1, 3)*2**Rational(2, 3)*3**Rational(1, 3)/3
assert Rational(-3, 2)**Rational(-10, 3) == \
8*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/81
assert abs(Pow(Rational(-2, 3), Rational(-7, 4)).n() -
Pow(Rational(-2, 3), Rational(-7, 4), evaluate=False).n()) < 1e-16
# negative integer power and negative rational base
assert Rational(-2, 3) ** Rational(-2, 1) == Rational(9, 4)
a = Rational(1, 10)
assert a**Float(a, 2) == Float(a, 2)**Float(a, 2)
assert Rational(-2, 3)**Symbol('', even=True) == \
Rational(2, 3)**Symbol('', even=True)
def test_powers_Float():
assert str((S('-1/10')**S('3/10')).n()) == str(Float(-.1)**(.3))
def test_lshift_Integer():
assert Integer(0) << Integer(2) == Integer(0)
assert Integer(0) << 2 == Integer(0)
assert 0 << Integer(2) == Integer(0)
assert Integer(0b11) << Integer(0) == Integer(0b11)
assert Integer(0b11) << 0 == Integer(0b11)
assert 0b11 << Integer(0) == Integer(0b11)
assert Integer(0b11) << Integer(2) == Integer(0b11 << 2)
assert Integer(0b11) << 2 == Integer(0b11 << 2)
assert 0b11 << Integer(2) == Integer(0b11 << 2)
assert Integer(-0b11) << Integer(2) == Integer(-0b11 << 2)
assert Integer(-0b11) << 2 == Integer(-0b11 << 2)
assert -0b11 << Integer(2) == Integer(-0b11 << 2)
raises(TypeError, lambda: Integer(2) << 0.0)
raises(TypeError, lambda: 0.0 << Integer(2))
raises(ValueError, lambda: Integer(1) << Integer(-1))
def test_rshift_Integer():
assert Integer(0) >> Integer(2) == Integer(0)
assert Integer(0) >> 2 == Integer(0)
assert 0 >> Integer(2) == Integer(0)
assert Integer(0b11) >> Integer(0) == Integer(0b11)
assert Integer(0b11) >> 0 == Integer(0b11)
assert 0b11 >> Integer(0) == Integer(0b11)
assert Integer(0b11) >> Integer(2) == Integer(0)
assert Integer(0b11) >> 2 == Integer(0)
assert 0b11 >> Integer(2) == Integer(0)
assert Integer(-0b11) >> Integer(2) == Integer(-1)
assert Integer(-0b11) >> 2 == Integer(-1)
assert -0b11 >> Integer(2) == Integer(-1)
assert Integer(0b1100) >> Integer(2) == Integer(0b1100 >> 2)
assert Integer(0b1100) >> 2 == Integer(0b1100 >> 2)
assert 0b1100 >> Integer(2) == Integer(0b1100 >> 2)
assert Integer(-0b1100) >> Integer(2) == Integer(-0b1100 >> 2)
assert Integer(-0b1100) >> 2 == Integer(-0b1100 >> 2)
assert -0b1100 >> Integer(2) == Integer(-0b1100 >> 2)
raises(TypeError, lambda: Integer(0b10) >> 0.0)
raises(TypeError, lambda: 0.0 >> Integer(2))
raises(ValueError, lambda: Integer(1) >> Integer(-1))
def test_and_Integer():
assert Integer(0b01010101) & Integer(0b10101010) == Integer(0)
assert Integer(0b01010101) & 0b10101010 == Integer(0)
assert 0b01010101 & Integer(0b10101010) == Integer(0)
assert Integer(0b01010101) & Integer(0b11011011) == Integer(0b01010001)
assert Integer(0b01010101) & 0b11011011 == Integer(0b01010001)
assert 0b01010101 & Integer(0b11011011) == Integer(0b01010001)
assert -Integer(0b01010101) & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011)
assert Integer(-0b01010101) & 0b11011011 == Integer(-0b01010101 & 0b11011011)
assert -0b01010101 & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011)
assert Integer(0b01010101) & -Integer(0b11011011) == Integer(0b01010101 & -0b11011011)
assert Integer(0b01010101) & -0b11011011 == Integer(0b01010101 & -0b11011011)
assert 0b01010101 & Integer(-0b11011011) == Integer(0b01010101 & -0b11011011)
raises(TypeError, lambda: Integer(2) & 0.0)
raises(TypeError, lambda: 0.0 & Integer(2))
def test_xor_Integer():
assert Integer(0b01010101) ^ Integer(0b11111111) == Integer(0b10101010)
assert Integer(0b01010101) ^ 0b11111111 == Integer(0b10101010)
assert 0b01010101 ^ Integer(0b11111111) == Integer(0b10101010)
assert Integer(0b01010101) ^ Integer(0b11011011) == Integer(0b10001110)
assert Integer(0b01010101) ^ 0b11011011 == Integer(0b10001110)
assert 0b01010101 ^ Integer(0b11011011) == Integer(0b10001110)
assert -Integer(0b01010101) ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011)
assert Integer(-0b01010101) ^ 0b11011011 == Integer(-0b01010101 ^ 0b11011011)
assert -0b01010101 ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011)
assert Integer(0b01010101) ^ -Integer(0b11011011) == Integer(0b01010101 ^ -0b11011011)
assert Integer(0b01010101) ^ -0b11011011 == Integer(0b01010101 ^ -0b11011011)
assert 0b01010101 ^ Integer(-0b11011011) == Integer(0b01010101 ^ -0b11011011)
raises(TypeError, lambda: Integer(2) ^ 0.0)
raises(TypeError, lambda: 0.0 ^ Integer(2))
def test_or_Integer():
assert Integer(0b01010101) | Integer(0b10101010) == Integer(0b11111111)
assert Integer(0b01010101) | 0b10101010 == Integer(0b11111111)
assert 0b01010101 | Integer(0b10101010) == Integer(0b11111111)
assert Integer(0b01010101) | Integer(0b11011011) == Integer(0b11011111)
assert Integer(0b01010101) | 0b11011011 == Integer(0b11011111)
assert 0b01010101 | Integer(0b11011011) == Integer(0b11011111)
assert -Integer(0b01010101) | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011)
assert Integer(-0b01010101) | 0b11011011 == Integer(-0b01010101 | 0b11011011)
assert -0b01010101 | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011)
assert Integer(0b01010101) | -Integer(0b11011011) == Integer(0b01010101 | -0b11011011)
assert Integer(0b01010101) | -0b11011011 == Integer(0b01010101 | -0b11011011)
assert 0b01010101 | Integer(-0b11011011) == Integer(0b01010101 | -0b11011011)
raises(TypeError, lambda: Integer(2) | 0.0)
raises(TypeError, lambda: 0.0 | Integer(2))
def test_invert_Integer():
assert ~Integer(0b01010101) == Integer(-0b01010110)
assert ~Integer(0b01010101) == Integer(~0b01010101)
assert ~(~Integer(0b01010101)) == Integer(0b01010101)
def test_abs1():
assert Rational(1, 6) != Rational(-1, 6)
assert abs(Rational(1, 6)) == abs(Rational(-1, 6))
def test_accept_int():
assert Float(4) == 4
def test_dont_accept_str():
assert Float("0.2") != "0.2"
assert not (Float("0.2") == "0.2")
def test_int():
a = Rational(5)
assert int(a) == 5
a = Rational(9, 10)
assert int(a) == int(-a) == 0
assert 1/(-1)**Rational(2, 3) == -(-1)**Rational(1, 3)
# issue 10368
a = Rational(32442016954, 78058255275)
assert type(int(a)) is type(int(-a)) is int
def test_int_NumberSymbols():
assert int(Catalan) == 0
assert int(EulerGamma) == 0
assert int(pi) == 3
assert int(E) == 2
assert int(GoldenRatio) == 1
assert int(TribonacciConstant) == 1
for i in [Catalan, E, EulerGamma, GoldenRatio, TribonacciConstant, pi]:
a, b = i.approximation_interval(Integer)
ia = int(i)
assert ia == a
assert isinstance(ia, int)
assert b == a + 1
assert a.is_Integer and b.is_Integer
def test_real_bug():
x = Symbol("x")
assert str(2.0*x*x) in ["(2.0*x)*x", "2.0*x**2", "2.00000000000000*x**2"]
assert str(2.1*x*x) != "(2.0*x)*x"
def test_bug_sqrt():
assert ((sqrt(Rational(2)) + 1)*(sqrt(Rational(2)) - 1)).expand() == 1
def test_pi_Pi():
"Test that pi (instance) is imported, but Pi (class) is not"
from sympy import pi # noqa
with raises(ImportError):
from sympy import Pi # noqa
def test_no_len():
# there should be no len for numbers
raises(TypeError, lambda: len(Rational(2)))
raises(TypeError, lambda: len(Rational(2, 3)))
raises(TypeError, lambda: len(Integer(2)))
def test_issue_3321():
assert sqrt(Rational(1, 5)) == Rational(1, 5)**S.Half
assert 5 * sqrt(Rational(1, 5)) == sqrt(5)
def test_issue_3692():
assert ((-1)**Rational(1, 6)).expand(complex=True) == I/2 + sqrt(3)/2
assert ((-5)**Rational(1, 6)).expand(complex=True) == \
5**Rational(1, 6)*I/2 + 5**Rational(1, 6)*sqrt(3)/2
assert ((-64)**Rational(1, 6)).expand(complex=True) == I + sqrt(3)
def test_issue_3423():
x = Symbol("x")
assert sqrt(x - 1).as_base_exp() == (x - 1, S.Half)
assert sqrt(x - 1) != I*sqrt(1 - x)
def test_issue_3449():
x = Symbol("x")
assert sqrt(x - 1).subs(x, 5) == 2
def test_issue_13890():
x = Symbol("x")
e = (-x/4 - S.One/12)**x - 1
f = simplify(e)
a = Rational(9, 5)
assert abs(e.subs(x,a).evalf() - f.subs(x,a).evalf()) < 1e-15
def test_Integer_factors():
def F(i):
return Integer(i).factors()
assert F(1) == {}
assert F(2) == {2: 1}
assert F(3) == {3: 1}
assert F(4) == {2: 2}
assert F(5) == {5: 1}
assert F(6) == {2: 1, 3: 1}
assert F(7) == {7: 1}
assert F(8) == {2: 3}
assert F(9) == {3: 2}
assert F(10) == {2: 1, 5: 1}
assert F(11) == {11: 1}
assert F(12) == {2: 2, 3: 1}
assert F(13) == {13: 1}
assert F(14) == {2: 1, 7: 1}
assert F(15) == {3: 1, 5: 1}
assert F(16) == {2: 4}
assert F(17) == {17: 1}
assert F(18) == {2: 1, 3: 2}
assert F(19) == {19: 1}
assert F(20) == {2: 2, 5: 1}
assert F(21) == {3: 1, 7: 1}
assert F(22) == {2: 1, 11: 1}
assert F(23) == {23: 1}
assert F(24) == {2: 3, 3: 1}
assert F(25) == {5: 2}
assert F(26) == {2: 1, 13: 1}
assert F(27) == {3: 3}
assert F(28) == {2: 2, 7: 1}
assert F(29) == {29: 1}
assert F(30) == {2: 1, 3: 1, 5: 1}
assert F(31) == {31: 1}
assert F(32) == {2: 5}
assert F(33) == {3: 1, 11: 1}
assert F(34) == {2: 1, 17: 1}
assert F(35) == {5: 1, 7: 1}
assert F(36) == {2: 2, 3: 2}
assert F(37) == {37: 1}
assert F(38) == {2: 1, 19: 1}
assert F(39) == {3: 1, 13: 1}
assert F(40) == {2: 3, 5: 1}
assert F(41) == {41: 1}
assert F(42) == {2: 1, 3: 1, 7: 1}
assert F(43) == {43: 1}
assert F(44) == {2: 2, 11: 1}
assert F(45) == {3: 2, 5: 1}
assert F(46) == {2: 1, 23: 1}
assert F(47) == {47: 1}
assert F(48) == {2: 4, 3: 1}
assert F(49) == {7: 2}
assert F(50) == {2: 1, 5: 2}
assert F(51) == {3: 1, 17: 1}
def test_Rational_factors():
def F(p, q, visual=None):
return Rational(p, q).factors(visual=visual)
assert F(2, 3) == {2: 1, 3: -1}
assert F(2, 9) == {2: 1, 3: -2}
assert F(2, 15) == {2: 1, 3: -1, 5: -1}
assert F(6, 10) == {3: 1, 5: -1}
def test_issue_4107():
assert pi*(E + 10) + pi*(-E - 10) != 0
assert pi*(E + 10**10) + pi*(-E - 10**10) != 0
assert pi*(E + 10**20) + pi*(-E - 10**20) != 0
assert pi*(E + 10**80) + pi*(-E - 10**80) != 0
assert (pi*(E + 10) + pi*(-E - 10)).expand() == 0
assert (pi*(E + 10**10) + pi*(-E - 10**10)).expand() == 0
assert (pi*(E + 10**20) + pi*(-E - 10**20)).expand() == 0
assert (pi*(E + 10**80) + pi*(-E - 10**80)).expand() == 0
def test_IntegerInteger():
a = Integer(4)
b = Integer(a)
assert a == b
def test_Rational_gcd_lcm_cofactors():
assert Integer(4).gcd(2) == Integer(2)
assert Integer(4).lcm(2) == Integer(4)
assert Integer(4).gcd(Integer(2)) == Integer(2)
assert Integer(4).lcm(Integer(2)) == Integer(4)
a, b = 720**99911, 480**12342
assert Integer(a).lcm(b) == a*b/Integer(a).gcd(b)
assert Integer(4).gcd(3) == Integer(1)
assert Integer(4).lcm(3) == Integer(12)
assert Integer(4).gcd(Integer(3)) == Integer(1)
assert Integer(4).lcm(Integer(3)) == Integer(12)
assert Rational(4, 3).gcd(2) == Rational(2, 3)
assert Rational(4, 3).lcm(2) == Integer(4)
assert Rational(4, 3).gcd(Integer(2)) == Rational(2, 3)
assert Rational(4, 3).lcm(Integer(2)) == Integer(4)
assert Integer(4).gcd(Rational(2, 9)) == Rational(2, 9)
assert Integer(4).lcm(Rational(2, 9)) == Integer(4)
assert Rational(4, 3).gcd(Rational(2, 9)) == Rational(2, 9)
assert Rational(4, 3).lcm(Rational(2, 9)) == Rational(4, 3)
assert Rational(4, 5).gcd(Rational(2, 9)) == Rational(2, 45)
assert Rational(4, 5).lcm(Rational(2, 9)) == Integer(4)
assert Rational(5, 9).lcm(Rational(3, 7)) == Rational(Integer(5).lcm(3),Integer(9).gcd(7))
assert Integer(4).cofactors(2) == (Integer(2), Integer(2), Integer(1))
assert Integer(4).cofactors(Integer(2)) == \
(Integer(2), Integer(2), Integer(1))
assert Integer(4).gcd(Float(2.0)) == Float(1.0)
assert Integer(4).lcm(Float(2.0)) == Float(8.0)
assert Integer(4).cofactors(Float(2.0)) == (Float(1.0), Float(4.0), Float(2.0))
assert S.Half.gcd(Float(2.0)) == Float(1.0)
assert S.Half.lcm(Float(2.0)) == Float(1.0)
assert S.Half.cofactors(Float(2.0)) == \
(Float(1.0), Float(0.5), Float(2.0))
def test_Float_gcd_lcm_cofactors():
assert Float(2.0).gcd(Integer(4)) == Float(1.0)
assert Float(2.0).lcm(Integer(4)) == Float(8.0)
assert Float(2.0).cofactors(Integer(4)) == (Float(1.0), Float(2.0), Float(4.0))
assert Float(2.0).gcd(S.Half) == Float(1.0)
assert Float(2.0).lcm(S.Half) == Float(1.0)
assert Float(2.0).cofactors(S.Half) == \
(Float(1.0), Float(2.0), Float(0.5))
def test_issue_4611():
assert abs(pi._evalf(50) - 3.14159265358979) < 1e-10
assert abs(E._evalf(50) - 2.71828182845905) < 1e-10
assert abs(Catalan._evalf(50) - 0.915965594177219) < 1e-10
assert abs(EulerGamma._evalf(50) - 0.577215664901533) < 1e-10
assert abs(GoldenRatio._evalf(50) - 1.61803398874989) < 1e-10
assert abs(TribonacciConstant._evalf(50) - 1.83928675521416) < 1e-10
x = Symbol("x")
assert (pi + x).evalf() == pi.evalf() + x
assert (E + x).evalf() == E.evalf() + x
assert (Catalan + x).evalf() == Catalan.evalf() + x
assert (EulerGamma + x).evalf() == EulerGamma.evalf() + x
assert (GoldenRatio + x).evalf() == GoldenRatio.evalf() + x
assert (TribonacciConstant + x).evalf() == TribonacciConstant.evalf() + x
@conserve_mpmath_dps
def test_conversion_to_mpmath():
assert mpmath.mpmathify(Integer(1)) == mpmath.mpf(1)
assert mpmath.mpmathify(S.Half) == mpmath.mpf(0.5)
assert mpmath.mpmathify(Float('1.23', 15)) == mpmath.mpf('1.23')
assert mpmath.mpmathify(I) == mpmath.mpc(1j)
assert mpmath.mpmathify(1 + 2*I) == mpmath.mpc(1 + 2j)
assert mpmath.mpmathify(1.0 + 2*I) == mpmath.mpc(1 + 2j)
assert mpmath.mpmathify(1 + 2.0*I) == mpmath.mpc(1 + 2j)
assert mpmath.mpmathify(1.0 + 2.0*I) == mpmath.mpc(1 + 2j)
assert mpmath.mpmathify(S.Half + S.Half*I) == mpmath.mpc(0.5 + 0.5j)
assert mpmath.mpmathify(2*I) == mpmath.mpc(2j)
assert mpmath.mpmathify(2.0*I) == mpmath.mpc(2j)
assert mpmath.mpmathify(S.Half*I) == mpmath.mpc(0.5j)
mpmath.mp.dps = 100
assert mpmath.mpmathify(pi.evalf(100) + pi.evalf(100)*I) == mpmath.pi + mpmath.pi*mpmath.j
assert mpmath.mpmathify(pi.evalf(100)*I) == mpmath.pi*mpmath.j
def test_relational():
# real
x = S(.1)
assert (x != cos) is True
assert (x == cos) is False
# rational
x = Rational(1, 3)
assert (x != cos) is True
assert (x == cos) is False
# integer defers to rational so these tests are omitted
# number symbol
x = pi
assert (x != cos) is True
assert (x == cos) is False
def test_Integer_as_index():
assert 'hello'[Integer(2):] == 'llo'
def test_Rational_int():
assert int( Rational(7, 5)) == 1
assert int( S.Half) == 0
assert int(Rational(-1, 2)) == 0
assert int(-Rational(7, 5)) == -1
def test_zoo():
b = Symbol('b', finite=True)
nz = Symbol('nz', nonzero=True)
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
im = Symbol('i', imaginary=True)
c = Symbol('c', complex=True)
pb = Symbol('pb', positive=True)
nb = Symbol('nb', negative=True)
imb = Symbol('ib', imaginary=True, finite=True)
for i in [I, S.Infinity, S.NegativeInfinity, S.Zero, S.One, S.Pi, S.Half, S(3), log(3),
b, nz, p, n, im, pb, nb, imb, c]:
if i.is_finite and (i.is_real or i.is_imaginary):
assert i + zoo is zoo
assert i - zoo is zoo
assert zoo + i is zoo
assert zoo - i is zoo
elif i.is_finite is not False:
assert (i + zoo).is_Add
assert (i - zoo).is_Add
assert (zoo + i).is_Add
assert (zoo - i).is_Add
else:
assert (i + zoo) is S.NaN
assert (i - zoo) is S.NaN
assert (zoo + i) is S.NaN
assert (zoo - i) is S.NaN
if fuzzy_not(i.is_zero) and (i.is_extended_real or i.is_imaginary):
assert i*zoo is zoo
assert zoo*i is zoo
elif i.is_zero:
assert i*zoo is S.NaN
assert zoo*i is S.NaN
else:
assert (i*zoo).is_Mul
assert (zoo*i).is_Mul
if fuzzy_not((1/i).is_zero) and (i.is_real or i.is_imaginary):
assert zoo/i is zoo
elif (1/i).is_zero:
assert zoo/i is S.NaN
elif i.is_zero:
assert zoo/i is zoo
else:
assert (zoo/i).is_Mul
assert (I*oo).is_Mul # allow directed infinity
assert zoo + zoo is S.NaN
assert zoo * zoo is zoo
assert zoo - zoo is S.NaN
assert zoo/zoo is S.NaN
assert zoo**zoo is S.NaN
assert zoo**0 is S.One
assert zoo**2 is zoo
assert 1/zoo is S.Zero
assert Mul.flatten([S.NegativeOne, oo, S(0)]) == ([S.NaN], [], None)
def test_issue_4122():
x = Symbol('x', nonpositive=True)
assert oo + x is oo
x = Symbol('x', extended_nonpositive=True)
assert (oo + x).is_Add
x = Symbol('x', finite=True)
assert (oo + x).is_Add # x could be imaginary
x = Symbol('x', nonnegative=True)
assert oo + x is oo
x = Symbol('x', extended_nonnegative=True)
assert oo + x is oo
x = Symbol('x', finite=True, real=True)
assert oo + x is oo
# similarly for negative infinity
x = Symbol('x', nonnegative=True)
assert -oo + x is -oo
x = Symbol('x', extended_nonnegative=True)
assert (-oo + x).is_Add
x = Symbol('x', finite=True)
assert (-oo + x).is_Add
x = Symbol('x', nonpositive=True)
assert -oo + x is -oo
x = Symbol('x', extended_nonpositive=True)
assert -oo + x is -oo
x = Symbol('x', finite=True, real=True)
assert -oo + x is -oo
def test_GoldenRatio_expand():
assert GoldenRatio.expand(func=True) == S.Half + sqrt(5)/2
def test_TribonacciConstant_expand():
assert TribonacciConstant.expand(func=True) == \
(1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
def test_as_content_primitive():
assert S.Zero.as_content_primitive() == (1, 0)
assert S.Half.as_content_primitive() == (S.Half, 1)
assert (Rational(-1, 2)).as_content_primitive() == (S.Half, -1)
assert S(3).as_content_primitive() == (3, 1)
assert S(3.1).as_content_primitive() == (1, 3.1)
def test_hashing_sympy_integers():
# Test for issue 5072
assert {Integer(3)} == {int(3)}
assert hash(Integer(4)) == hash(int(4))
def test_rounding_issue_4172():
assert int((E**100).round()) == \
26881171418161354484126255515800135873611119
assert int((pi**100).round()) == \
51878483143196131920862615246303013562686760680406
assert int((Rational(1)/EulerGamma**100).round()) == \
734833795660954410469466
@XFAIL
def test_mpmath_issues():
from mpmath.libmp.libmpf import _normalize
import mpmath.libmp as mlib
rnd = mlib.round_nearest
mpf = (0, int(0), -123, -1, 53, rnd) # nan
assert _normalize(mpf, 53) != (0, int(0), 0, 0)
mpf = (0, int(0), -456, -2, 53, rnd) # +inf
assert _normalize(mpf, 53) != (0, int(0), 0, 0)
mpf = (1, int(0), -789, -3, 53, rnd) # -inf
assert _normalize(mpf, 53) != (0, int(0), 0, 0)
from mpmath.libmp.libmpf import fnan
assert mlib.mpf_eq(fnan, fnan)
def test_Catalan_EulerGamma_prec():
n = GoldenRatio
f = Float(n.n(), 5)
assert f._mpf_ == (0, int(212079), -17, 18)
assert f._prec == 20
assert n._as_mpf_val(20) == f._mpf_
n = EulerGamma
f = Float(n.n(), 5)
assert f._mpf_ == (0, int(302627), -19, 19)
assert f._prec == 20
assert n._as_mpf_val(20) == f._mpf_
def test_Catalan_rewrite():
k = Dummy('k', integer=True, nonnegative=True)
assert Catalan.rewrite(Sum).dummy_eq(
Sum((-1)**k/(2*k + 1)**2, (k, 0, oo)))
assert Catalan.rewrite() == Catalan
def test_bool_eq():
assert 0 == False
assert S(0) == False
assert S(0) != S.false
assert 1 == True
assert S.One == True
assert S.One != S.true
def test_Float_eq():
# all .5 values are the same
assert Float(.5, 10) == Float(.5, 11) == Float(.5, 1)
# but floats that aren't exact in base-2 still
# don't compare the same because they have different
# underlying mpf values
assert Float(.12, 3) != Float(.12, 4)
assert Float(.12, 3) != .12
assert 0.12 != Float(.12, 3)
assert Float('.12', 22) != .12
# issue 11707
# but Float/Rational -- except for 0 --
# are exact so Rational(x) = Float(y) only if
# Rational(x) == Rational(Float(y))
assert Float('1.1') != Rational(11, 10)
assert Rational(11, 10) != Float('1.1')
# coverage
assert not Float(3) == 2
assert not Float(2**2) == S.Half
assert Float(2**2) == 4
assert not Float(2**-2) == 1
assert Float(2**-1) == S.Half
assert not Float(2*3) == 3
assert not Float(2*3) == S.Half
assert Float(2*3) == 6
assert not Float(2*3) == 8
assert Float(.75) == Rational(3, 4)
assert Float(5/18) == 5/18
# 4473
assert Float(2.) != 3
assert Float((0,1,-3)) == S.One/8
assert Float((0,1,-3)) != S.One/9
# 16196
assert 2 == Float(2) # as per Python
# but in a computation...
assert t**2 != t**2.0
def test_issue_6640():
from mpmath.libmp.libmpf import finf, fninf
# fnan is not included because Float no longer returns fnan,
# but otherwise, the same sort of test could apply
assert Float(finf).is_zero is False
assert Float(fninf).is_zero is False
assert bool(Float(0)) is False
def test_issue_6349():
assert Float('23.e3', '')._prec == 10
assert Float('23e3', '')._prec == 20
assert Float('23000', '')._prec == 20
assert Float('-23000', '')._prec == 20
def test_mpf_norm():
assert mpf_norm((1, 0, 1, 0), 10) == mpf('0')._mpf_
assert Float._new((1, 0, 1, 0), 10)._mpf_ == mpf('0')._mpf_
def test_latex():
assert latex(pi) == r"\pi"
assert latex(E) == r"e"
assert latex(GoldenRatio) == r"\phi"
assert latex(TribonacciConstant) == r"\text{TribonacciConstant}"
assert latex(EulerGamma) == r"\gamma"
assert latex(oo) == r"\infty"
assert latex(-oo) == r"-\infty"
assert latex(zoo) == r"\tilde{\infty}"
assert latex(nan) == r"\text{NaN}"
assert latex(I) == r"i"
def test_issue_7742():
assert -oo % 1 is nan
def test_simplify_AlgebraicNumber():
A = AlgebraicNumber
e = 3**(S.One/6)*(3 + (135 + 78*sqrt(3))**Rational(2, 3))/(45 + 26*sqrt(3))**(S.One/3)
assert simplify(A(e)) == A(12) # wester test_C20
e = (41 + 29*sqrt(2))**(S.One/5)
assert simplify(A(e)) == A(1 + sqrt(2)) # wester test_C21
e = (3 + 4*I)**Rational(3, 2)
assert simplify(A(e)) == A(2 + 11*I) # issue 4401
def test_Float_idempotence():
x = Float('1.23', '')
y = Float(x)
z = Float(x, 15)
assert same_and_same_prec(y, x)
assert not same_and_same_prec(z, x)
x = Float(10**20)
y = Float(x)
z = Float(x, 15)
assert same_and_same_prec(y, x)
assert not same_and_same_prec(z, x)
def test_comp1():
# sqrt(2) = 1.414213 5623730950...
a = sqrt(2).n(7)
assert comp(a, 1.4142129) is False
assert comp(a, 1.4142130)
# ...
assert comp(a, 1.4142141)
assert comp(a, 1.4142142) is False
assert comp(sqrt(2).n(2), '1.4')
assert comp(sqrt(2).n(2), Float(1.4, 2), '')
assert comp(sqrt(2).n(2), 1.4, '')
assert comp(sqrt(2).n(2), Float(1.4, 3), '') is False
assert comp(sqrt(2) + sqrt(3)*I, 1.4 + 1.7*I, .1)
assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.89, .1)
assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.90, .1)
assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.07, .1)
assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.08, .1)
assert [(i, j)
for i in range(130, 150)
for j in range(170, 180)
if comp((sqrt(2)+ I*sqrt(3)).n(3), i/100. + I*j/100.)] == [
(141, 173), (142, 173)]
raises(ValueError, lambda: comp(t, '1'))
raises(ValueError, lambda: comp(t, 1))
assert comp(0, 0.0)
assert comp(.5, S.Half)
assert comp(2 + sqrt(2), 2.0 + sqrt(2))
assert not comp(0, 1)
assert not comp(2, sqrt(2))
assert not comp(2 + I, 2.0 + sqrt(2))
assert not comp(2.0 + sqrt(2), 2 + I)
assert not comp(2.0 + sqrt(2), sqrt(3))
assert comp(1/pi.n(4), 0.3183, 1e-5)
assert not comp(1/pi.n(4), 0.3183, 8e-6)
def test_issue_9491():
assert oo**zoo is nan
def test_issue_10063():
assert 2**Float(3) == Float(8)
def test_issue_10020():
assert oo**I is S.NaN
assert oo**(1 + I) is S.ComplexInfinity
assert oo**(-1 + I) is S.Zero
assert (-oo)**I is S.NaN
assert (-oo)**(-1 + I) is S.Zero
assert oo**t == Pow(oo, t, evaluate=False)
assert (-oo)**t == Pow(-oo, t, evaluate=False)
def test_invert_numbers():
assert S(2).invert(5) == 3
assert S(2).invert(Rational(5, 2)) == S.Half
assert S(2).invert(5.) == S.Half
assert S(2).invert(S(5)) == 3
assert S(2.).invert(5) == 0.5
assert S(sqrt(2)).invert(5) == 1/sqrt(2)
assert S(sqrt(2)).invert(sqrt(3)) == 1/sqrt(2)
def test_mod_inverse():
assert mod_inverse(3, 11) == 4
assert mod_inverse(5, 11) == 9
assert mod_inverse(21124921, 521512) == 7713
assert mod_inverse(124215421, 5125) == 2981
assert mod_inverse(214, 12515) == 1579
assert mod_inverse(5823991, 3299) == 1442
assert mod_inverse(123, 44) == 39
assert mod_inverse(2, 5) == 3
assert mod_inverse(-2, 5) == 2
assert mod_inverse(2, -5) == -2
assert mod_inverse(-2, -5) == -3
assert mod_inverse(-3, -7) == -5
x = Symbol('x')
assert S(2).invert(x) == S.Half
raises(TypeError, lambda: mod_inverse(2, x))
raises(ValueError, lambda: mod_inverse(2, S.Half))
raises(ValueError, lambda: mod_inverse(2, cos(1)**2 + sin(1)**2))
def test_golden_ratio_rewrite_as_sqrt():
assert GoldenRatio.rewrite(sqrt) == S.Half + sqrt(5)*S.Half
def test_tribonacci_constant_rewrite_as_sqrt():
assert TribonacciConstant.rewrite(sqrt) == \
(1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
def test_comparisons_with_unknown_type():
class Foo:
"""
Class that is unaware of Basic, and relies on both classes returning
the NotImplemented singleton for equivalence to evaluate to False.
"""
ni, nf, nr = Integer(3), Float(1.0), Rational(1, 3)
foo = Foo()
for n in ni, nf, nr, oo, -oo, zoo, nan:
assert n != foo
assert foo != n
assert not n == foo
assert not foo == n
raises(TypeError, lambda: n < foo)
raises(TypeError, lambda: foo > n)
raises(TypeError, lambda: n > foo)
raises(TypeError, lambda: foo < n)
raises(TypeError, lambda: n <= foo)
raises(TypeError, lambda: foo >= n)
raises(TypeError, lambda: n >= foo)
raises(TypeError, lambda: foo <= n)
class Bar:
"""
Class that considers itself equal to any instance of Number except
infinities and nans, and relies on SymPy types returning the
NotImplemented singleton for symmetric equality relations.
"""
def __eq__(self, other):
if other in (oo, -oo, zoo, nan):
return False
if isinstance(other, Number):
return True
return NotImplemented
def __ne__(self, other):
return not self == other
bar = Bar()
for n in ni, nf, nr:
assert n == bar
assert bar == n
assert not n != bar
assert not bar != n
for n in oo, -oo, zoo, nan:
assert n != bar
assert bar != n
assert not n == bar
assert not bar == n
for n in ni, nf, nr, oo, -oo, zoo, nan:
raises(TypeError, lambda: n < bar)
raises(TypeError, lambda: bar > n)
raises(TypeError, lambda: n > bar)
raises(TypeError, lambda: bar < n)
raises(TypeError, lambda: n <= bar)
raises(TypeError, lambda: bar >= n)
raises(TypeError, lambda: n >= bar)
raises(TypeError, lambda: bar <= n)
def test_NumberSymbol_comparison():
from sympy.core.tests.test_relational import rel_check
rpi = Rational('905502432259640373/288230376151711744')
fpi = Float(float(pi))
assert rel_check(rpi, fpi)
def test_Integer_precision():
# Make sure Integer inputs for keyword args work
assert Float('1.0', dps=Integer(15))._prec == 53
assert Float('1.0', precision=Integer(15))._prec == 15
assert type(Float('1.0', precision=Integer(15))._prec) == int
assert sympify(srepr(Float('1.0', precision=15))) == Float('1.0', precision=15)
def test_numpy_to_float():
from sympy.testing.pytest import skip
from sympy.external import import_module
np = import_module('numpy')
if not np:
skip('numpy not installed. Abort numpy tests.')
def check_prec_and_relerr(npval, ratval):
prec = np.finfo(npval).nmant + 1
x = Float(npval)
assert x._prec == prec
y = Float(ratval, precision=prec)
assert abs((x - y)/y) < 2**(-(prec + 1))
check_prec_and_relerr(np.float16(2.0/3), Rational(2, 3))
check_prec_and_relerr(np.float32(2.0/3), Rational(2, 3))
check_prec_and_relerr(np.float64(2.0/3), Rational(2, 3))
# extended precision, on some arch/compilers:
x = np.longdouble(2)/3
check_prec_and_relerr(x, Rational(2, 3))
y = Float(x, precision=10)
assert same_and_same_prec(y, Float(Rational(2, 3), precision=10))
raises(TypeError, lambda: Float(np.complex64(1+2j)))
raises(TypeError, lambda: Float(np.complex128(1+2j)))
def test_Integer_ceiling_floor():
a = Integer(4)
assert a.floor() == a
assert a.ceiling() == a
def test_ComplexInfinity():
assert zoo.floor() is zoo
assert zoo.ceiling() is zoo
assert zoo**zoo is S.NaN
def test_Infinity_floor_ceiling_power():
assert oo.floor() is oo
assert oo.ceiling() is oo
assert oo**S.NaN is S.NaN
assert oo**zoo is S.NaN
def test_One_power():
assert S.One**12 is S.One
assert S.NegativeOne**S.NaN is S.NaN
def test_NegativeInfinity():
assert (-oo).floor() is -oo
assert (-oo).ceiling() is -oo
assert (-oo)**11 is -oo
assert (-oo)**12 is oo
def test_issue_6133():
raises(TypeError, lambda: (-oo < None))
raises(TypeError, lambda: (S(-2) < None))
raises(TypeError, lambda: (oo < None))
raises(TypeError, lambda: (oo > None))
raises(TypeError, lambda: (S(2) < None))
def test_abc():
x = numbers.Float(5)
assert(isinstance(x, nums.Number))
assert(isinstance(x, numbers.Number))
assert(isinstance(x, nums.Real))
y = numbers.Rational(1, 3)
assert(isinstance(y, nums.Number))
assert(y.numerator == 1)
assert(y.denominator == 3)
assert(isinstance(y, nums.Rational))
z = numbers.Integer(3)
assert(isinstance(z, nums.Number))
assert(isinstance(z, numbers.Number))
assert(isinstance(z, nums.Rational))
assert(isinstance(z, numbers.Rational))
assert(isinstance(z, nums.Integral))
def test_floordiv():
assert S(2)//S.Half == 4
def test_negation():
assert -S.Zero is S.Zero
assert -Float(0) is not S.Zero and -Float(0) == 0.0
def test_exponentiation_of_0():
x = Symbol('x')
assert 0**-x == zoo**x
assert unchanged(Pow, 0, x)
x = Symbol('x', zero=True)
assert 0**-x == S.One
assert 0**x == S.One
def test_equal_valued():
x = Symbol('x')
equal_values = [
[1, 1.0, S(1), S(1.0), S(1).n(5)],
[2, 2.0, S(2), S(2.0), S(2).n(5)],
[-1, -1.0, -S(1), -S(1.0), -S(1).n(5)],
[0.5, S(0.5), S(1)/2],
[-0.5, -S(0.5), -S(1)/2],
[0, 0.0, S(0), S(0.0), S(0).n()],
[pi], [pi.n()], # <-- not equal
[S(1)/10], [0.1, S(0.1)], # <-- not equal
[S(0.1).n(5)],
[oo],
[cos(x/2)], [cos(0.5*x)], # <-- no recursion
]
for m, values_m in enumerate(equal_values):
for value_i in values_m:
# All values in same list equal
for value_j in values_m:
assert equal_valued(value_i, value_j) is True
# Not equal to anything in any other list:
for n, values_n in enumerate(equal_values):
if n == m:
continue
for value_j in values_n:
assert equal_valued(value_i, value_j) is False
|
bd5a176321b37533b712d951bb4b0e3718c1ddfa6b5f167bffd55ee87747f38b | from sympy.concrete.summations import Sum
from sympy.core.basic import Basic, _aresame
from sympy.core.cache import clear_cache
from sympy.core.containers import Dict, Tuple
from sympy.core.expr import Expr, unchanged
from sympy.core.function import (Subs, Function, diff, Lambda, expand,
nfloat, Derivative)
from sympy.core.numbers import E, Float, zoo, Rational, pi, I, oo, nan
from sympy.core.power import Pow
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import symbols, Dummy, Symbol
from sympy.functions.elementary.complexes import im, re
from sympy.functions.elementary.exponential import log, exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import sin, cos, acos
from sympy.functions.special.error_functions import expint
from sympy.functions.special.gamma_functions import loggamma, polygamma
from sympy.matrices.dense import Matrix
from sympy.printing.str import sstr
from sympy.series.order import O
from sympy.tensor.indexed import Indexed
from sympy.core.function import (PoleError, _mexpand, arity,
BadSignatureError, BadArgumentsError)
from sympy.core.parameters import _exp_is_pow
from sympy.core.sympify import sympify, SympifyError
from sympy.matrices import MutableMatrix, ImmutableMatrix
from sympy.sets.sets import FiniteSet
from sympy.solvers.solveset import solveset
from sympy.tensor.array import NDimArray
from sympy.utilities.iterables import subsets, variations
from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy, _both_exp_pow
from sympy.abc import t, w, x, y, z
f, g, h = symbols('f g h', cls=Function)
_xi_1, _xi_2, _xi_3 = [Dummy() for i in range(3)]
def test_f_expand_complex():
x = Symbol('x', real=True)
assert f(x).expand(complex=True) == I*im(f(x)) + re(f(x))
assert exp(x).expand(complex=True) == exp(x)
assert exp(I*x).expand(complex=True) == cos(x) + I*sin(x)
assert exp(z).expand(complex=True) == cos(im(z))*exp(re(z)) + \
I*sin(im(z))*exp(re(z))
def test_bug1():
e = sqrt(-log(w))
assert e.subs(log(w), -x) == sqrt(x)
e = sqrt(-5*log(w))
assert e.subs(log(w), -x) == sqrt(5*x)
def test_general_function():
nu = Function('nu')
e = nu(x)
edx = e.diff(x)
edy = e.diff(y)
edxdx = e.diff(x).diff(x)
edxdy = e.diff(x).diff(y)
assert e == nu(x)
assert edx != nu(x)
assert edx == diff(nu(x), x)
assert edy == 0
assert edxdx == diff(diff(nu(x), x), x)
assert edxdy == 0
def test_general_function_nullary():
nu = Function('nu')
e = nu()
edx = e.diff(x)
edxdx = e.diff(x).diff(x)
assert e == nu()
assert edx != nu()
assert edx == 0
assert edxdx == 0
def test_derivative_subs_bug():
e = diff(g(x), x)
assert e.subs(g(x), f(x)) != e
assert e.subs(g(x), f(x)) == Derivative(f(x), x)
assert e.subs(g(x), -f(x)) == Derivative(-f(x), x)
assert e.subs(x, y) == Derivative(g(y), y)
def test_derivative_subs_self_bug():
d = diff(f(x), x)
assert d.subs(d, y) == y
def test_derivative_linearity():
assert diff(-f(x), x) == -diff(f(x), x)
assert diff(8*f(x), x) == 8*diff(f(x), x)
assert diff(8*f(x), x) != 7*diff(f(x), x)
assert diff(8*f(x)*x, x) == 8*f(x) + 8*x*diff(f(x), x)
assert diff(8*f(x)*y*x, x).expand() == 8*y*f(x) + 8*y*x*diff(f(x), x)
def test_derivative_evaluate():
assert Derivative(sin(x), x) != diff(sin(x), x)
assert Derivative(sin(x), x).doit() == diff(sin(x), x)
assert Derivative(Derivative(f(x), x), x) == diff(f(x), x, x)
assert Derivative(sin(x), x, 0) == sin(x)
assert Derivative(sin(x), (x, y), (x, -y)) == sin(x)
def test_diff_symbols():
assert diff(f(x, y, z), x, y, z) == Derivative(f(x, y, z), x, y, z)
assert diff(f(x, y, z), x, x, x) == Derivative(f(x, y, z), x, x, x) == Derivative(f(x, y, z), (x, 3))
assert diff(f(x, y, z), x, 3) == Derivative(f(x, y, z), x, 3)
# issue 5028
assert [diff(-z + x/y, sym) for sym in (z, x, y)] == [-1, 1/y, -x/y**2]
assert diff(f(x, y, z), x, y, z, 2) == Derivative(f(x, y, z), x, y, z, z)
assert diff(f(x, y, z), x, y, z, 2, evaluate=False) == \
Derivative(f(x, y, z), x, y, z, z)
assert Derivative(f(x, y, z), x, y, z)._eval_derivative(z) == \
Derivative(f(x, y, z), x, y, z, z)
assert Derivative(Derivative(f(x, y, z), x), y)._eval_derivative(z) == \
Derivative(f(x, y, z), x, y, z)
raises(TypeError, lambda: cos(x).diff((x, y)).variables)
assert cos(x).diff((x, y))._wrt_variables == [x]
# issue 23222
assert sympify("a*x+b").diff("x") == sympify("a")
def test_Function():
class myfunc(Function):
@classmethod
def eval(cls): # zero args
return
assert myfunc.nargs == FiniteSet(0)
assert myfunc().nargs == FiniteSet(0)
raises(TypeError, lambda: myfunc(x).nargs)
class myfunc(Function):
@classmethod
def eval(cls, x): # one arg
return
assert myfunc.nargs == FiniteSet(1)
assert myfunc(x).nargs == FiniteSet(1)
raises(TypeError, lambda: myfunc(x, y).nargs)
class myfunc(Function):
@classmethod
def eval(cls, *x): # star args
return
assert myfunc.nargs == S.Naturals0
assert myfunc(x).nargs == S.Naturals0
def test_nargs():
f = Function('f')
assert f.nargs == S.Naturals0
assert f(1).nargs == S.Naturals0
assert Function('f', nargs=2)(1, 2).nargs == FiniteSet(2)
assert sin.nargs == FiniteSet(1)
assert sin(2).nargs == FiniteSet(1)
assert log.nargs == FiniteSet(1, 2)
assert log(2).nargs == FiniteSet(1, 2)
assert Function('f', nargs=2).nargs == FiniteSet(2)
assert Function('f', nargs=0).nargs == FiniteSet(0)
assert Function('f', nargs=(0, 1)).nargs == FiniteSet(0, 1)
assert Function('f', nargs=None).nargs == S.Naturals0
raises(ValueError, lambda: Function('f', nargs=()))
def test_nargs_inheritance():
class f1(Function):
nargs = 2
class f2(f1):
pass
class f3(f2):
pass
class f4(f3):
nargs = 1,2
class f5(f4):
pass
class f6(f5):
pass
class f7(f6):
nargs=None
class f8(f7):
pass
class f9(f8):
pass
class f10(f9):
nargs = 1
class f11(f10):
pass
assert f1.nargs == FiniteSet(2)
assert f2.nargs == FiniteSet(2)
assert f3.nargs == FiniteSet(2)
assert f4.nargs == FiniteSet(1, 2)
assert f5.nargs == FiniteSet(1, 2)
assert f6.nargs == FiniteSet(1, 2)
assert f7.nargs == S.Naturals0
assert f8.nargs == S.Naturals0
assert f9.nargs == S.Naturals0
assert f10.nargs == FiniteSet(1)
assert f11.nargs == FiniteSet(1)
def test_arity():
f = lambda x, y: 1
assert arity(f) == 2
def f(x, y, z=None):
pass
assert arity(f) == (2, 3)
assert arity(lambda *x: x) is None
assert arity(log) == (1, 2)
def test_Lambda():
e = Lambda(x, x**2)
assert e(4) == 16
assert e(x) == x**2
assert e(y) == y**2
assert Lambda((), 42)() == 42
assert unchanged(Lambda, (), 42)
assert Lambda((), 42) != Lambda((), 43)
assert Lambda((), f(x))() == f(x)
assert Lambda((), 42).nargs == FiniteSet(0)
assert unchanged(Lambda, (x,), x**2)
assert Lambda(x, x**2) == Lambda((x,), x**2)
assert Lambda(x, x**2) != Lambda(x, x**2 + 1)
assert Lambda((x, y), x**y) != Lambda((y, x), y**x)
assert Lambda((x, y), x**y) != Lambda((x, y), y**x)
assert Lambda((x, y), x**y)(x, y) == x**y
assert Lambda((x, y), x**y)(3, 3) == 3**3
assert Lambda((x, y), x**y)(x, 3) == x**3
assert Lambda((x, y), x**y)(3, y) == 3**y
assert Lambda(x, f(x))(x) == f(x)
assert Lambda(x, x**2)(e(x)) == x**4
assert e(e(x)) == x**4
x1, x2 = (Indexed('x', i) for i in (1, 2))
assert Lambda((x1, x2), x1 + x2)(x, y) == x + y
assert Lambda((x, y), x + y).nargs == FiniteSet(2)
p = x, y, z, t
assert Lambda(p, t*(x + y + z))(*p) == t * (x + y + z)
eq = Lambda(x, 2*x) + Lambda(y, 2*y)
assert eq != 2*Lambda(x, 2*x)
assert eq.as_dummy() == 2*Lambda(x, 2*x).as_dummy()
assert Lambda(x, 2*x) not in [ Lambda(x, x) ]
raises(BadSignatureError, lambda: Lambda(1, x))
assert Lambda(x, 1)(1) is S.One
raises(BadSignatureError, lambda: Lambda((x, x), x + 2))
raises(BadSignatureError, lambda: Lambda(((x, x), y), x))
raises(BadSignatureError, lambda: Lambda(((y, x), x), x))
raises(BadSignatureError, lambda: Lambda(((y, 1), 2), x))
with warns_deprecated_sympy():
assert Lambda([x, y], x+y) == Lambda((x, y), x+y)
flam = Lambda(((x, y),), x + y)
assert flam((2, 3)) == 5
flam = Lambda(((x, y), z), x + y + z)
assert flam((2, 3), 1) == 6
flam = Lambda((((x, y), z),), x + y + z)
assert flam(((2, 3), 1)) == 6
raises(BadArgumentsError, lambda: flam(1, 2, 3))
flam = Lambda( (x,), (x, x))
assert flam(1,) == (1, 1)
assert flam((1,)) == ((1,), (1,))
flam = Lambda( ((x,),), (x, x))
raises(BadArgumentsError, lambda: flam(1))
assert flam((1,)) == (1, 1)
# Previously TypeError was raised so this is potentially needed for
# backwards compatibility.
assert issubclass(BadSignatureError, TypeError)
assert issubclass(BadArgumentsError, TypeError)
# These are tested to see they don't raise:
hash(Lambda(x, 2*x))
hash(Lambda(x, x)) # IdentityFunction subclass
def test_IdentityFunction():
assert Lambda(x, x) is Lambda(y, y) is S.IdentityFunction
assert Lambda(x, 2*x) is not S.IdentityFunction
assert Lambda((x, y), x) is not S.IdentityFunction
def test_Lambda_symbols():
assert Lambda(x, 2*x).free_symbols == set()
assert Lambda(x, x*y).free_symbols == {y}
assert Lambda((), 42).free_symbols == set()
assert Lambda((), x*y).free_symbols == {x,y}
def test_functionclas_symbols():
assert f.free_symbols == set()
def test_Lambda_arguments():
raises(TypeError, lambda: Lambda(x, 2*x)(x, y))
raises(TypeError, lambda: Lambda((x, y), x + y)(x))
raises(TypeError, lambda: Lambda((), 42)(x))
def test_Lambda_equality():
assert Lambda((x, y), 2*x) == Lambda((x, y), 2*x)
# these, of course, should never be equal
assert Lambda(x, 2*x) != Lambda((x, y), 2*x)
assert Lambda(x, 2*x) != 2*x
# But it is tempting to want expressions that differ only
# in bound symbols to compare the same. But this is not what
# Python's `==` is intended to do; two objects that compare
# as equal means that they are indistibguishable and cache to the
# same value. We wouldn't want to expression that are
# mathematically the same but written in different variables to be
# interchanged else what is the point of allowing for different
# variable names?
assert Lambda(x, 2*x) != Lambda(y, 2*y)
def test_Subs():
assert Subs(1, (), ()) is S.One
# check null subs influence on hashing
assert Subs(x, y, z) != Subs(x, y, 1)
# neutral subs works
assert Subs(x, x, 1).subs(x, y).has(y)
# self mapping var/point
assert Subs(Derivative(f(x), (x, 2)), x, x).doit() == f(x).diff(x, x)
assert Subs(x, x, 0).has(x) # it's a structural answer
assert not Subs(x, x, 0).free_symbols
assert Subs(Subs(x + y, x, 2), y, 1) == Subs(x + y, (x, y), (2, 1))
assert Subs(x, (x,), (0,)) == Subs(x, x, 0)
assert Subs(x, x, 0) == Subs(y, y, 0)
assert Subs(x, x, 0).subs(x, 1) == Subs(x, x, 0)
assert Subs(y, x, 0).subs(y, 1) == Subs(1, x, 0)
assert Subs(f(x), x, 0).doit() == f(0)
assert Subs(f(x**2), x**2, 0).doit() == f(0)
assert Subs(f(x, y, z), (x, y, z), (0, 1, 1)) != \
Subs(f(x, y, z), (x, y, z), (0, 0, 1))
assert Subs(x, y, 2).subs(x, y).doit() == 2
assert Subs(f(x, y), (x, y, z), (0, 1, 1)) != \
Subs(f(x, y) + z, (x, y, z), (0, 1, 0))
assert Subs(f(x, y), (x, y), (0, 1)).doit() == f(0, 1)
assert Subs(Subs(f(x, y), x, 0), y, 1).doit() == f(0, 1)
raises(ValueError, lambda: Subs(f(x, y), (x, y), (0, 0, 1)))
raises(ValueError, lambda: Subs(f(x, y), (x, x, y), (0, 0, 1)))
assert len(Subs(f(x, y), (x, y), (0, 1)).variables) == 2
assert Subs(f(x, y), (x, y), (0, 1)).point == Tuple(0, 1)
assert Subs(f(x), x, 0) == Subs(f(y), y, 0)
assert Subs(f(x, y), (x, y), (0, 1)) == Subs(f(x, y), (y, x), (1, 0))
assert Subs(f(x)*y, (x, y), (0, 1)) == Subs(f(y)*x, (y, x), (0, 1))
assert Subs(f(x)*y, (x, y), (1, 1)) == Subs(f(y)*x, (x, y), (1, 1))
assert Subs(f(x), x, 0).subs(x, 1).doit() == f(0)
assert Subs(f(x), x, y).subs(y, 0) == Subs(f(x), x, 0)
assert Subs(y*f(x), x, y).subs(y, 2) == Subs(2*f(x), x, 2)
assert (2 * Subs(f(x), x, 0)).subs(Subs(f(x), x, 0), y) == 2*y
assert Subs(f(x), x, 0).free_symbols == set()
assert Subs(f(x, y), x, z).free_symbols == {y, z}
assert Subs(f(x).diff(x), x, 0).doit(), Subs(f(x).diff(x), x, 0)
assert Subs(1 + f(x).diff(x), x, 0).doit(), 1 + Subs(f(x).diff(x), x, 0)
assert Subs(y*f(x, y).diff(x), (x, y), (0, 2)).doit() == \
2*Subs(Derivative(f(x, 2), x), x, 0)
assert Subs(y**2*f(x), x, 0).diff(y) == 2*y*f(0)
e = Subs(y**2*f(x), x, y)
assert e.diff(y) == e.doit().diff(y) == y**2*Derivative(f(y), y) + 2*y*f(y)
assert Subs(f(x), x, 0) + Subs(f(x), x, 0) == 2*Subs(f(x), x, 0)
e1 = Subs(z*f(x), x, 1)
e2 = Subs(z*f(y), y, 1)
assert e1 + e2 == 2*e1
assert e1.__hash__() == e2.__hash__()
assert Subs(z*f(x + 1), x, 1) not in [ e1, e2 ]
assert Derivative(f(x), x).subs(x, g(x)) == Derivative(f(g(x)), g(x))
assert Derivative(f(x), x).subs(x, x + y) == Subs(Derivative(f(x), x),
x, x + y)
assert Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).n(2) == \
Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).evalf(2) == \
z + Rational('1/2').n(2)*f(0)
assert f(x).diff(x).subs(x, 0).subs(x, y) == f(x).diff(x).subs(x, 0)
assert (x*f(x).diff(x).subs(x, 0)).subs(x, y) == y*f(x).diff(x).subs(x, 0)
assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x)
).doit() == 2*exp(x)
assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x)
).doit(deep=False) == 2*Derivative(exp(x), x)
assert Derivative(f(x, g(x)), x).doit() == Derivative(
f(x, g(x)), g(x))*Derivative(g(x), x) + Subs(Derivative(
f(y, g(x)), y), y, x)
def test_doitdoit():
done = Derivative(f(x, g(x)), x, g(x)).doit()
assert done == done.doit()
@XFAIL
def test_Subs2():
# this reflects a limitation of subs(), probably won't fix
assert Subs(f(x), x**2, x).doit() == f(sqrt(x))
def test_expand_function():
assert expand(x + y) == x + y
assert expand(x + y, complex=True) == I*im(x) + I*im(y) + re(x) + re(y)
assert expand((x + y)**11, modulus=11) == x**11 + y**11
def test_function_comparable():
assert sin(x).is_comparable is False
assert cos(x).is_comparable is False
assert sin(Float('0.1')).is_comparable is True
assert cos(Float('0.1')).is_comparable is True
assert sin(E).is_comparable is True
assert cos(E).is_comparable is True
assert sin(Rational(1, 3)).is_comparable is True
assert cos(Rational(1, 3)).is_comparable is True
def test_function_comparable_infinities():
assert sin(oo).is_comparable is False
assert sin(-oo).is_comparable is False
assert sin(zoo).is_comparable is False
assert sin(nan).is_comparable is False
def test_deriv1():
# These all require derivatives evaluated at a point (issue 4719) to work.
# See issue 4624
assert f(2*x).diff(x) == 2*Subs(Derivative(f(x), x), x, 2*x)
assert (f(x)**3).diff(x) == 3*f(x)**2*f(x).diff(x)
assert (f(2*x)**3).diff(x) == 6*f(2*x)**2*Subs(
Derivative(f(x), x), x, 2*x)
assert f(2 + x).diff(x) == Subs(Derivative(f(x), x), x, x + 2)
assert f(2 + 3*x).diff(x) == 3*Subs(
Derivative(f(x), x), x, 3*x + 2)
assert f(3*sin(x)).diff(x) == 3*cos(x)*Subs(
Derivative(f(x), x), x, 3*sin(x))
# See issue 8510
assert f(x, x + z).diff(x) == (
Subs(Derivative(f(y, x + z), y), y, x) +
Subs(Derivative(f(x, y), y), y, x + z))
assert f(x, x**2).diff(x) == (
2*x*Subs(Derivative(f(x, y), y), y, x**2) +
Subs(Derivative(f(y, x**2), y), y, x))
# but Subs is not always necessary
assert f(x, g(y)).diff(g(y)) == Derivative(f(x, g(y)), g(y))
def test_deriv2():
assert (x**3).diff(x) == 3*x**2
assert (x**3).diff(x, evaluate=False) != 3*x**2
assert (x**3).diff(x, evaluate=False) == Derivative(x**3, x)
assert diff(x**3, x) == 3*x**2
assert diff(x**3, x, evaluate=False) != 3*x**2
assert diff(x**3, x, evaluate=False) == Derivative(x**3, x)
def test_func_deriv():
assert f(x).diff(x) == Derivative(f(x), x)
# issue 4534
assert f(x, y).diff(x, y) - f(x, y).diff(y, x) == 0
assert Derivative(f(x, y), x, y).args[1:] == ((x, 1), (y, 1))
assert Derivative(f(x, y), y, x).args[1:] == ((y, 1), (x, 1))
assert (Derivative(f(x, y), x, y) - Derivative(f(x, y), y, x)).doit() == 0
def test_suppressed_evaluation():
a = sin(0, evaluate=False)
assert a != 0
assert a.func is sin
assert a.args == (0,)
def test_function_evalf():
def eq(a, b, eps):
return abs(a - b) < eps
assert eq(sin(1).evalf(15), Float("0.841470984807897"), 1e-13)
assert eq(
sin(2).evalf(25), Float("0.9092974268256816953960199", 25), 1e-23)
assert eq(sin(1 + I).evalf(
15), Float("1.29845758141598") + Float("0.634963914784736")*I, 1e-13)
assert eq(exp(1 + I).evalf(15), Float(
"1.46869393991588") + Float("2.28735528717884239")*I, 1e-13)
assert eq(exp(-0.5 + 1.5*I).evalf(15), Float(
"0.0429042815937374") + Float("0.605011292285002")*I, 1e-13)
assert eq(log(pi + sqrt(2)*I).evalf(
15), Float("1.23699044022052") + Float("0.422985442737893")*I, 1e-13)
assert eq(cos(100).evalf(15), Float("0.86231887228768"), 1e-13)
def test_extensibility_eval():
class MyFunc(Function):
@classmethod
def eval(cls, *args):
return (0, 0, 0)
assert MyFunc(0) == (0, 0, 0)
@_both_exp_pow
def test_function_non_commutative():
x = Symbol('x', commutative=False)
assert f(x).is_commutative is False
assert sin(x).is_commutative is False
assert exp(x).is_commutative is False
assert log(x).is_commutative is False
assert f(x).is_complex is False
assert sin(x).is_complex is False
assert exp(x).is_complex is False
assert log(x).is_complex is False
def test_function_complex():
x = Symbol('x', complex=True)
xzf = Symbol('x', complex=True, zero=False)
assert f(x).is_commutative is True
assert sin(x).is_commutative is True
assert exp(x).is_commutative is True
assert log(x).is_commutative is True
assert f(x).is_complex is None
assert sin(x).is_complex is True
assert exp(x).is_complex is True
assert log(x).is_complex is None
assert log(xzf).is_complex is True
def test_function__eval_nseries():
n = Symbol('n')
assert sin(x)._eval_nseries(x, 2, None) == x + O(x**2)
assert sin(x + 1)._eval_nseries(x, 2, None) == x*cos(1) + sin(1) + O(x**2)
assert sin(pi*(1 - x))._eval_nseries(x, 2, None) == pi*x + O(x**2)
assert acos(1 - x**2)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(x**2) + O(x**2)
assert polygamma(n, x + 1)._eval_nseries(x, 2, None) == \
polygamma(n, 1) + polygamma(n + 1, 1)*x + O(x**2)
raises(PoleError, lambda: sin(1/x)._eval_nseries(x, 2, None))
assert acos(1 - x)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(x) + sqrt(2)*x**(S(3)/2)/12 + O(x**2)
assert acos(1 + x)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(-x) + sqrt(2)*(-x)**(S(3)/2)/12 + O(x**2)
assert loggamma(1/x)._eval_nseries(x, 0, None) == \
log(x)/2 - log(x)/x - 1/x + O(1, x)
assert loggamma(log(1/x)).nseries(x, n=1, logx=y) == loggamma(-y)
# issue 6725:
assert expint(Rational(3, 2), -x)._eval_nseries(x, 5, None) == \
2 - 2*sqrt(pi)*sqrt(-x) - 2*x + x**2 + x**3/3 + x**4/12 + 4*I*x**(S(3)/2)*sqrt(-x)/3 + \
2*I*x**(S(5)/2)*sqrt(-x)/5 + 2*I*x**(S(7)/2)*sqrt(-x)/21 + O(x**5)
assert sin(sqrt(x))._eval_nseries(x, 3, None) == \
sqrt(x) - x**Rational(3, 2)/6 + x**Rational(5, 2)/120 + O(x**3)
# issue 19065:
s1 = f(x,y).series(y, n=2)
assert {i.name for i in s1.atoms(Symbol)} == {'x', 'xi', 'y'}
xi = Symbol('xi')
s2 = f(xi, y).series(y, n=2)
assert {i.name for i in s2.atoms(Symbol)} == {'xi', 'xi0', 'y'}
def test_doit():
n = Symbol('n', integer=True)
f = Sum(2 * n * x, (n, 1, 3))
d = Derivative(f, x)
assert d.doit() == 12
assert d.doit(deep=False) == Sum(2*n, (n, 1, 3))
def test_evalf_default():
from sympy.functions.special.gamma_functions import polygamma
assert type(sin(4.0)) == Float
assert type(re(sin(I + 1.0))) == Float
assert type(im(sin(I + 1.0))) == Float
assert type(sin(4)) == sin
assert type(polygamma(2.0, 4.0)) == Float
assert type(sin(Rational(1, 4))) == sin
def test_issue_5399():
args = [x, y, S(2), S.Half]
def ok(a):
"""Return True if the input args for diff are ok"""
if not a:
return False
if a[0].is_Symbol is False:
return False
s_at = [i for i in range(len(a)) if a[i].is_Symbol]
n_at = [i for i in range(len(a)) if not a[i].is_Symbol]
# every symbol is followed by symbol or int
# every number is followed by a symbol
return (all(a[i + 1].is_Symbol or a[i + 1].is_Integer
for i in s_at if i + 1 < len(a)) and
all(a[i + 1].is_Symbol
for i in n_at if i + 1 < len(a)))
eq = x**10*y**8
for a in subsets(args):
for v in variations(a, len(a)):
if ok(v):
eq.diff(*v) # does not raise
else:
raises(ValueError, lambda: eq.diff(*v))
def test_derivative_numerically():
z0 = x._random()
assert abs(Derivative(sin(x), x).doit_numerically(z0) - cos(z0)) < 1e-15
def test_fdiff_argument_index_error():
from sympy.core.function import ArgumentIndexError
class myfunc(Function):
nargs = 1 # define since there is no eval routine
def fdiff(self, idx):
raise ArgumentIndexError
mf = myfunc(x)
assert mf.diff(x) == Derivative(mf, x)
raises(TypeError, lambda: myfunc(x, x))
def test_deriv_wrt_function():
x = f(t)
xd = diff(x, t)
xdd = diff(xd, t)
y = g(t)
yd = diff(y, t)
assert diff(x, t) == xd
assert diff(2 * x + 4, t) == 2 * xd
assert diff(2 * x + 4 + y, t) == 2 * xd + yd
assert diff(2 * x + 4 + y * x, t) == 2 * xd + x * yd + xd * y
assert diff(2 * x + 4 + y * x, x) == 2 + y
assert (diff(4 * x**2 + 3 * x + x * y, t) == 3 * xd + x * yd + xd * y +
8 * x * xd)
assert (diff(4 * x**2 + 3 * xd + x * y, t) == 3 * xdd + x * yd + xd * y +
8 * x * xd)
assert diff(4 * x**2 + 3 * xd + x * y, xd) == 3
assert diff(4 * x**2 + 3 * xd + x * y, xdd) == 0
assert diff(sin(x), t) == xd * cos(x)
assert diff(exp(x), t) == xd * exp(x)
assert diff(sqrt(x), t) == xd / (2 * sqrt(x))
def test_diff_wrt_value():
assert Expr()._diff_wrt is False
assert x._diff_wrt is True
assert f(x)._diff_wrt is True
assert Derivative(f(x), x)._diff_wrt is True
assert Derivative(x**2, x)._diff_wrt is False
def test_diff_wrt():
fx = f(x)
dfx = diff(f(x), x)
ddfx = diff(f(x), x, x)
assert diff(sin(fx) + fx**2, fx) == cos(fx) + 2*fx
assert diff(sin(dfx) + dfx**2, dfx) == cos(dfx) + 2*dfx
assert diff(sin(ddfx) + ddfx**2, ddfx) == cos(ddfx) + 2*ddfx
assert diff(fx**2, dfx) == 0
assert diff(fx**2, ddfx) == 0
assert diff(dfx**2, fx) == 0
assert diff(dfx**2, ddfx) == 0
assert diff(ddfx**2, dfx) == 0
assert diff(fx*dfx*ddfx, fx) == dfx*ddfx
assert diff(fx*dfx*ddfx, dfx) == fx*ddfx
assert diff(fx*dfx*ddfx, ddfx) == fx*dfx
assert diff(f(x), x).diff(f(x)) == 0
assert (sin(f(x)) - cos(diff(f(x), x))).diff(f(x)) == cos(f(x))
assert diff(sin(fx), fx, x) == diff(sin(fx), x, fx)
# Chain rule cases
assert f(g(x)).diff(x) == \
Derivative(g(x), x)*Derivative(f(g(x)), g(x))
assert diff(f(g(x), h(y)), x) == \
Derivative(g(x), x)*Derivative(f(g(x), h(y)), g(x))
assert diff(f(g(x), h(x)), x) == (
Derivative(f(g(x), h(x)), g(x))*Derivative(g(x), x) +
Derivative(f(g(x), h(x)), h(x))*Derivative(h(x), x))
assert f(
sin(x)).diff(x) == cos(x)*Subs(Derivative(f(x), x), x, sin(x))
assert diff(f(g(x)), g(x)) == Derivative(f(g(x)), g(x))
def test_diff_wrt_func_subs():
assert f(g(x)).diff(x).subs(g, Lambda(x, 2*x)).doit() == f(2*x).diff(x)
def test_subs_in_derivative():
expr = sin(x*exp(y))
u = Function('u')
v = Function('v')
assert Derivative(expr, y).subs(expr, y) == Derivative(y, y)
assert Derivative(expr, y).subs(y, x).doit() == \
Derivative(expr, y).doit().subs(y, x)
assert Derivative(f(x, y), y).subs(y, x) == Subs(Derivative(f(x, y), y), y, x)
assert Derivative(f(x, y), y).subs(x, y) == Subs(Derivative(f(x, y), y), x, y)
assert Derivative(f(x, y), y).subs(y, g(x, y)) == Subs(Derivative(f(x, y), y), y, g(x, y)).doit()
assert Derivative(f(x, y), y).subs(x, g(x, y)) == Subs(Derivative(f(x, y), y), x, g(x, y))
assert Derivative(f(x, y), g(y)).subs(x, g(x, y)) == Derivative(f(g(x, y), y), g(y))
assert Derivative(f(u(x), h(y)), h(y)).subs(h(y), g(x, y)) == \
Subs(Derivative(f(u(x), h(y)), h(y)), h(y), g(x, y)).doit()
assert Derivative(f(x, y), y).subs(y, z) == Derivative(f(x, z), z)
assert Derivative(f(x, y), y).subs(y, g(y)) == Derivative(f(x, g(y)), g(y))
assert Derivative(f(g(x), h(y)), h(y)).subs(h(y), u(y)) == \
Derivative(f(g(x), u(y)), u(y))
assert Derivative(f(x, f(x, x)), f(x, x)).subs(
f, Lambda((x, y), x + y)) == Subs(
Derivative(z + x, z), z, 2*x)
assert Subs(Derivative(f(f(x)), x), f, cos).doit() == sin(x)*sin(cos(x))
assert Subs(Derivative(f(f(x)), f(x)), f, cos).doit() == -sin(cos(x))
# Issue 13791. No comparison (it's a long formula) but this used to raise an exception.
assert isinstance(v(x, y, u(x, y)).diff(y).diff(x).diff(y), Expr)
# This is also related to issues 13791 and 13795; issue 15190
F = Lambda((x, y), exp(2*x + 3*y))
abstract = f(x, f(x, x)).diff(x, 2)
concrete = F(x, F(x, x)).diff(x, 2)
assert (abstract.subs(f, F).doit() - concrete).simplify() == 0
# don't introduce a new symbol if not necessary
assert x in f(x).diff(x).subs(x, 0).atoms()
# case (4)
assert Derivative(f(x,f(x,y)), x, y).subs(x, g(y)
) == Subs(Derivative(f(x, f(x, y)), x, y), x, g(y))
assert Derivative(f(x, x), x).subs(x, 0
) == Subs(Derivative(f(x, x), x), x, 0)
# issue 15194
assert Derivative(f(y, g(x)), (x, z)).subs(z, x
) == Derivative(f(y, g(x)), (x, x))
df = f(x).diff(x)
assert df.subs(df, 1) is S.One
assert df.diff(df) is S.One
dxy = Derivative(f(x, y), x, y)
dyx = Derivative(f(x, y), y, x)
assert dxy.subs(Derivative(f(x, y), y, x), 1) is S.One
assert dxy.diff(dyx) is S.One
assert Derivative(f(x, y), x, 2, y, 3).subs(
dyx, g(x, y)) == Derivative(g(x, y), x, 1, y, 2)
assert Derivative(f(x, x - y), y).subs(x, x + y) == Subs(
Derivative(f(x, x - y), y), x, x + y)
def test_diff_wrt_not_allowed():
# issue 7027 included
for wrt in (
cos(x), re(x), x**2, x*y, 1 + x,
Derivative(cos(x), x), Derivative(f(f(x)), x)):
raises(ValueError, lambda: diff(f(x), wrt))
# if we don't differentiate wrt then don't raise error
assert diff(exp(x*y), x*y, 0) == exp(x*y)
def test_diff_wrt_intlike():
class Two:
def __int__(self):
return 2
assert cos(x).diff(x, Two()) == -cos(x)
def test_klein_gordon_lagrangian():
m = Symbol('m')
phi = f(x, t)
L = -(diff(phi, t)**2 - diff(phi, x)**2 - m**2*phi**2)/2
eqna = Eq(
diff(L, phi) - diff(L, diff(phi, x), x) - diff(L, diff(phi, t), t), 0)
eqnb = Eq(diff(phi, t, t) - diff(phi, x, x) + m**2*phi, 0)
assert eqna == eqnb
def test_sho_lagrangian():
m = Symbol('m')
k = Symbol('k')
x = f(t)
L = m*diff(x, t)**2/2 - k*x**2/2
eqna = Eq(diff(L, x), diff(L, diff(x, t), t))
eqnb = Eq(-k*x, m*diff(x, t, t))
assert eqna == eqnb
assert diff(L, x, t) == diff(L, t, x)
assert diff(L, diff(x, t), t) == m*diff(x, t, 2)
assert diff(L, t, diff(x, t)) == -k*x + m*diff(x, t, 2)
def test_straight_line():
F = f(x)
Fd = F.diff(x)
L = sqrt(1 + Fd**2)
assert diff(L, F) == 0
assert diff(L, Fd) == Fd/sqrt(1 + Fd**2)
def test_sort_variable():
vsort = Derivative._sort_variable_count
def vsort0(*v, reverse=False):
return [i[0] for i in vsort([(i, 0) for i in (
reversed(v) if reverse else v)])]
for R in range(2):
assert vsort0(y, x, reverse=R) == [x, y]
assert vsort0(f(x), x, reverse=R) == [x, f(x)]
assert vsort0(f(y), f(x), reverse=R) == [f(x), f(y)]
assert vsort0(g(x), f(y), reverse=R) == [f(y), g(x)]
assert vsort0(f(x, y), f(x), reverse=R) == [f(x), f(x, y)]
fx = f(x).diff(x)
assert vsort0(fx, y, reverse=R) == [y, fx]
fy = f(y).diff(y)
assert vsort0(fy, fx, reverse=R) == [fx, fy]
fxx = fx.diff(x)
assert vsort0(fxx, fx, reverse=R) == [fx, fxx]
assert vsort0(Basic(x), f(x), reverse=R) == [f(x), Basic(x)]
assert vsort0(Basic(y), Basic(x), reverse=R) == [Basic(x), Basic(y)]
assert vsort0(Basic(y, z), Basic(x), reverse=R) == [
Basic(x), Basic(y, z)]
assert vsort0(fx, x, reverse=R) == [
x, fx] if R else [fx, x]
assert vsort0(Basic(x), x, reverse=R) == [
x, Basic(x)] if R else [Basic(x), x]
assert vsort0(Basic(f(x)), f(x), reverse=R) == [
f(x), Basic(f(x))] if R else [Basic(f(x)), f(x)]
assert vsort0(Basic(x, z), Basic(x), reverse=R) == [
Basic(x), Basic(x, z)] if R else [Basic(x, z), Basic(x)]
assert vsort([]) == []
assert _aresame(vsort([(x, 1)]), [Tuple(x, 1)])
assert vsort([(x, y), (x, z)]) == [(x, y + z)]
assert vsort([(y, 1), (x, 1 + y)]) == [(x, 1 + y), (y, 1)]
# coverage complete; legacy tests below
assert vsort([(x, 3), (y, 2), (z, 1)]) == [(x, 3), (y, 2), (z, 1)]
assert vsort([(h(x), 1), (g(x), 1), (f(x), 1)]) == [
(f(x), 1), (g(x), 1), (h(x), 1)]
assert vsort([(z, 1), (y, 2), (x, 3), (h(x), 1), (g(x), 1),
(f(x), 1)]) == [(x, 3), (y, 2), (z, 1), (f(x), 1), (g(x), 1),
(h(x), 1)]
assert vsort([(x, 1), (f(x), 1), (y, 1), (f(y), 1)]) == [(x, 1),
(y, 1), (f(x), 1), (f(y), 1)]
assert vsort([(y, 1), (x, 2), (g(x), 1), (f(x), 1), (z, 1),
(h(x), 1), (y, 2), (x, 1)]) == [(x, 3), (y, 3), (z, 1),
(f(x), 1), (g(x), 1), (h(x), 1)]
assert vsort([(z, 1), (y, 1), (f(x), 1), (x, 1), (f(x), 1),
(g(x), 1)]) == [(x, 1), (y, 1), (z, 1), (f(x), 2), (g(x), 1)]
assert vsort([(z, 1), (y, 2), (f(x), 1), (x, 2), (f(x), 2),
(g(x), 1), (z, 2), (z, 1), (y, 1), (x, 1)]) == [(x, 3), (y, 3),
(z, 4), (f(x), 3), (g(x), 1)]
assert vsort(((y, 2), (x, 1), (y, 1), (x, 1))) == [(x, 2), (y, 3)]
assert isinstance(vsort([(x, 3), (y, 2), (z, 1)])[0], Tuple)
assert vsort([(x, 1), (f(x), 1), (x, 1)]) == [(x, 2), (f(x), 1)]
assert vsort([(y, 2), (x, 3), (z, 1)]) == [(x, 3), (y, 2), (z, 1)]
assert vsort([(h(y), 1), (g(x), 1), (f(x), 1)]) == [
(f(x), 1), (g(x), 1), (h(y), 1)]
assert vsort([(x, 1), (y, 1), (x, 1)]) == [(x, 2), (y, 1)]
assert vsort([(f(x), 1), (f(y), 1), (f(x), 1)]) == [
(f(x), 2), (f(y), 1)]
dfx = f(x).diff(x)
self = [(dfx, 1), (x, 1)]
assert vsort(self) == self
assert vsort([
(dfx, 1), (y, 1), (f(x), 1), (x, 1), (f(y), 1), (x, 1)]) == [
(y, 1), (f(x), 1), (f(y), 1), (dfx, 1), (x, 2)]
dfy = f(y).diff(y)
assert vsort([(dfy, 1), (dfx, 1)]) == [(dfx, 1), (dfy, 1)]
d2fx = dfx.diff(x)
assert vsort([(d2fx, 1), (dfx, 1)]) == [(dfx, 1), (d2fx, 1)]
def test_multiple_derivative():
# Issue #15007
assert f(x, y).diff(y, y, x, y, x
) == Derivative(f(x, y), (x, 2), (y, 3))
def test_unhandled():
class MyExpr(Expr):
def _eval_derivative(self, s):
if not s.name.startswith('xi'):
return self
else:
return None
eq = MyExpr(f(x), y, z)
assert diff(eq, x, y, f(x), z) == Derivative(eq, f(x))
assert diff(eq, f(x), x) == Derivative(eq, f(x))
assert f(x, y).diff(x,(y, z)) == Derivative(f(x, y), x, (y, z))
assert f(x, y).diff(x,(y, 0)) == Derivative(f(x, y), x)
def test_nfloat():
from sympy.core.basic import _aresame
from sympy.polys.rootoftools import rootof
x = Symbol("x")
eq = x**Rational(4, 3) + 4*x**(S.One/3)/3
assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(S.One/3))
assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3))
eq = x**Rational(4, 3) + 4*x**(x/3)/3
assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(x/3))
big = 12345678901234567890
# specify precision to match value used in nfloat
Float_big = Float(big, 15)
assert _aresame(nfloat(big), Float_big)
assert _aresame(nfloat(big*x), Float_big*x)
assert _aresame(nfloat(x**big, exponent=True), x**Float_big)
assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2)))
# issue 6342
f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
assert not any(a.free_symbols for a in solveset(f.subs(x, -0.139)))
# issue 6632
assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \
9.99999999800000e-11
# issue 7122
eq = cos(3*x**4 + y)*rootof(x**5 + 3*x**3 + 1, 0)
assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)'
# issue 10933
for ti in (dict, Dict):
d = ti({S.Half: S.Half})
n = nfloat(d)
assert isinstance(n, ti)
assert _aresame(list(n.items()).pop(), (S.Half, Float(.5)))
for ti in (dict, Dict):
d = ti({S.Half: S.Half})
n = nfloat(d, dkeys=True)
assert isinstance(n, ti)
assert _aresame(list(n.items()).pop(), (Float(.5), Float(.5)))
d = [S.Half]
n = nfloat(d)
assert type(n) is list
assert _aresame(n[0], Float(.5))
assert _aresame(nfloat(Eq(x, S.Half)).rhs, Float(.5))
assert _aresame(nfloat(S(True)), S(True))
assert _aresame(nfloat(Tuple(S.Half))[0], Float(.5))
assert nfloat(Eq((3 - I)**2/2 + I, 0)) == S.false
# pass along kwargs
assert nfloat([{S.Half: x}], dkeys=True) == [{Float(0.5): x}]
# Issue 17706
A = MutableMatrix([[1, 2], [3, 4]])
B = MutableMatrix(
[[Float('1.0', precision=53), Float('2.0', precision=53)],
[Float('3.0', precision=53), Float('4.0', precision=53)]])
assert _aresame(nfloat(A), B)
A = ImmutableMatrix([[1, 2], [3, 4]])
B = ImmutableMatrix(
[[Float('1.0', precision=53), Float('2.0', precision=53)],
[Float('3.0', precision=53), Float('4.0', precision=53)]])
assert _aresame(nfloat(A), B)
# issue 22524
f = Function('f')
assert not nfloat(f(2)).atoms(Float)
def test_issue_7068():
from sympy.abc import a, b
f = Function('f')
y1 = Dummy('y')
y2 = Dummy('y')
func1 = f(a + y1 * b)
func2 = f(a + y2 * b)
func1_y = func1.diff(y1)
func2_y = func2.diff(y2)
assert func1_y != func2_y
z1 = Subs(f(a), a, y1)
z2 = Subs(f(a), a, y2)
assert z1 != z2
def test_issue_7231():
from sympy.abc import a
ans1 = f(x).series(x, a)
res = (f(a) + (-a + x)*Subs(Derivative(f(y), y), y, a) +
(-a + x)**2*Subs(Derivative(f(y), y, y), y, a)/2 +
(-a + x)**3*Subs(Derivative(f(y), y, y, y),
y, a)/6 +
(-a + x)**4*Subs(Derivative(f(y), y, y, y, y),
y, a)/24 +
(-a + x)**5*Subs(Derivative(f(y), y, y, y, y, y),
y, a)/120 + O((-a + x)**6, (x, a)))
assert res == ans1
ans2 = f(x).series(x, a)
assert res == ans2
def test_issue_7687():
from sympy.core.function import Function
from sympy.abc import x
f = Function('f')(x)
ff = Function('f')(x)
match_with_cache = ff.matches(f)
assert isinstance(f, type(ff))
clear_cache()
ff = Function('f')(x)
assert isinstance(f, type(ff))
assert match_with_cache == ff.matches(f)
def test_issue_7688():
from sympy.core.function import Function, UndefinedFunction
f = Function('f') # actually an UndefinedFunction
clear_cache()
class A(UndefinedFunction):
pass
a = A('f')
assert isinstance(a, type(f))
def test_mexpand():
from sympy.abc import x
assert _mexpand(None) is None
assert _mexpand(1) is S.One
assert _mexpand(x*(x + 1)**2) == (x*(x + 1)**2).expand()
def test_issue_8469():
# This should not take forever to run
N = 40
def g(w, theta):
return 1/(1+exp(w-theta))
ws = symbols(['w%i'%i for i in range(N)])
import functools
expr = functools.reduce(g, ws)
assert isinstance(expr, Pow)
def test_issue_12996():
# foo=True imitates the sort of arguments that Derivative can get
# from Integral when it passes doit to the expression
assert Derivative(im(x), x).doit(foo=True) == Derivative(im(x), x)
def test_should_evalf():
# This should not take forever to run (see #8506)
assert isinstance(sin((1.0 + 1.0*I)**10000 + 1), sin)
def test_Derivative_as_finite_difference():
# Central 1st derivative at gridpoint
x, h = symbols('x h', real=True)
dfdx = f(x).diff(x)
assert (dfdx.as_finite_difference([x-2, x-1, x, x+1, x+2]) -
(S.One/12*(f(x-2)-f(x+2)) + Rational(2, 3)*(f(x+1)-f(x-1)))).simplify() == 0
# Central 1st derivative "half-way"
assert (dfdx.as_finite_difference() -
(f(x + S.Half)-f(x - S.Half))).simplify() == 0
assert (dfdx.as_finite_difference(h) -
(f(x + h/S(2))-f(x - h/S(2)))/h).simplify() == 0
assert (dfdx.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) -
(S(9)/(8*2*h)*(f(x+h) - f(x-h)) +
S.One/(24*2*h)*(f(x - 3*h) - f(x + 3*h)))).simplify() == 0
# One sided 1st derivative at gridpoint
assert (dfdx.as_finite_difference([0, 1, 2], 0) -
(Rational(-3, 2)*f(0) + 2*f(1) - f(2)/2)).simplify() == 0
assert (dfdx.as_finite_difference([x, x+h], x) -
(f(x+h) - f(x))/h).simplify() == 0
assert (dfdx.as_finite_difference([x-h, x, x+h], x-h) -
(-S(3)/(2*h)*f(x-h) + 2/h*f(x) -
S.One/(2*h)*f(x+h))).simplify() == 0
# One sided 1st derivative "half-way"
assert (dfdx.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h, x + 7*h])
- 1/(2*h)*(-S(11)/(12)*f(x-h) + S(17)/(24)*f(x+h)
+ Rational(3, 8)*f(x + 3*h) - Rational(5, 24)*f(x + 5*h)
+ S.One/24*f(x + 7*h))).simplify() == 0
d2fdx2 = f(x).diff(x, 2)
# Central 2nd derivative at gridpoint
assert (d2fdx2.as_finite_difference([x-h, x, x+h]) -
h**-2 * (f(x-h) + f(x+h) - 2*f(x))).simplify() == 0
assert (d2fdx2.as_finite_difference([x - 2*h, x-h, x, x+h, x + 2*h]) -
h**-2 * (Rational(-1, 12)*(f(x - 2*h) + f(x + 2*h)) +
Rational(4, 3)*(f(x+h) + f(x-h)) - Rational(5, 2)*f(x))).simplify() == 0
# Central 2nd derivative "half-way"
assert (d2fdx2.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) -
(2*h)**-2 * (S.Half*(f(x - 3*h) + f(x + 3*h)) -
S.Half*(f(x+h) + f(x-h)))).simplify() == 0
# One sided 2nd derivative at gridpoint
assert (d2fdx2.as_finite_difference([x, x+h, x + 2*h, x + 3*h]) -
h**-2 * (2*f(x) - 5*f(x+h) +
4*f(x+2*h) - f(x+3*h))).simplify() == 0
# One sided 2nd derivative at "half-way"
assert (d2fdx2.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h]) -
(2*h)**-2 * (Rational(3, 2)*f(x-h) - Rational(7, 2)*f(x+h) + Rational(5, 2)*f(x + 3*h) -
S.Half*f(x + 5*h))).simplify() == 0
d3fdx3 = f(x).diff(x, 3)
# Central 3rd derivative at gridpoint
assert (d3fdx3.as_finite_difference() -
(-f(x - Rational(3, 2)) + 3*f(x - S.Half) -
3*f(x + S.Half) + f(x + Rational(3, 2)))).simplify() == 0
assert (d3fdx3.as_finite_difference(
[x - 3*h, x - 2*h, x-h, x, x+h, x + 2*h, x + 3*h]) -
h**-3 * (S.One/8*(f(x - 3*h) - f(x + 3*h)) - f(x - 2*h) +
f(x + 2*h) + Rational(13, 8)*(f(x-h) - f(x+h)))).simplify() == 0
# Central 3rd derivative at "half-way"
assert (d3fdx3.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) -
(2*h)**-3 * (f(x + 3*h)-f(x - 3*h) +
3*(f(x-h)-f(x+h)))).simplify() == 0
# One sided 3rd derivative at gridpoint
assert (d3fdx3.as_finite_difference([x, x+h, x + 2*h, x + 3*h]) -
h**-3 * (f(x + 3*h)-f(x) + 3*(f(x+h)-f(x + 2*h)))).simplify() == 0
# One sided 3rd derivative at "half-way"
assert (d3fdx3.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h]) -
(2*h)**-3 * (f(x + 5*h)-f(x-h) +
3*(f(x+h)-f(x + 3*h)))).simplify() == 0
# issue 11007
y = Symbol('y', real=True)
d2fdxdy = f(x, y).diff(x, y)
ref0 = Derivative(f(x + S.Half, y), y) - Derivative(f(x - S.Half, y), y)
assert (d2fdxdy.as_finite_difference(wrt=x) - ref0).simplify() == 0
half = S.Half
xm, xp, ym, yp = x-half, x+half, y-half, y+half
ref2 = f(xm, ym) + f(xp, yp) - f(xp, ym) - f(xm, yp)
assert (d2fdxdy.as_finite_difference() - ref2).simplify() == 0
def test_issue_11159():
# Tests Application._eval_subs
with _exp_is_pow(False):
expr1 = E
expr0 = expr1 * expr1
expr1 = expr0.subs(expr1,expr0)
assert expr0 == expr1
with _exp_is_pow(True):
expr1 = E
expr0 = expr1 * expr1
expr2 = expr0.subs(expr1, expr0)
assert expr2 == E ** 4
def test_issue_12005():
e1 = Subs(Derivative(f(x), x), x, x)
assert e1.diff(x) == Derivative(f(x), x, x)
e2 = Subs(Derivative(f(x), x), x, x**2 + 1)
assert e2.diff(x) == 2*x*Subs(Derivative(f(x), x, x), x, x**2 + 1)
e3 = Subs(Derivative(f(x) + y**2 - y, y), y, y**2)
assert e3.diff(y) == 4*y
e4 = Subs(Derivative(f(x + y), y), y, (x**2))
assert e4.diff(y) is S.Zero
e5 = Subs(Derivative(f(x), x), (y, z), (y, z))
assert e5.diff(x) == Derivative(f(x), x, x)
assert f(g(x)).diff(g(x), g(x)) == Derivative(f(g(x)), g(x), g(x))
def test_issue_13843():
x = symbols('x')
f = Function('f')
m, n = symbols('m n', integer=True)
assert Derivative(Derivative(f(x), (x, m)), (x, n)) == Derivative(f(x), (x, m + n))
assert Derivative(Derivative(f(x), (x, m+5)), (x, n+3)) == Derivative(f(x), (x, m + n + 8))
assert Derivative(f(x), (x, n)).doit() == Derivative(f(x), (x, n))
def test_order_could_be_zero():
x, y = symbols('x, y')
n = symbols('n', integer=True, nonnegative=True)
m = symbols('m', integer=True, positive=True)
assert diff(y, (x, n)) == Piecewise((y, Eq(n, 0)), (0, True))
assert diff(y, (x, n + 1)) is S.Zero
assert diff(y, (x, m)) is S.Zero
def test_undefined_function_eq():
f = Function('f')
f2 = Function('f')
g = Function('g')
f_real = Function('f', is_real=True)
# This test may only be meaningful if the cache is turned off
assert f == f2
assert hash(f) == hash(f2)
assert f == f
assert f != g
assert f != f_real
def test_function_assumptions():
x = Symbol('x')
f = Function('f')
f_real = Function('f', real=True)
f_real1 = Function('f', real=1)
f_real_inherit = Function(Symbol('f', real=True))
assert f_real == f_real1 # assumptions are sanitized
assert f != f_real
assert f(x) != f_real(x)
assert f(x).is_real is None
assert f_real(x).is_real is True
assert f_real_inherit(x).is_real is True and f_real_inherit.name == 'f'
# Can also do it this way, but it won't be equal to f_real because of the
# way UndefinedFunction.__new__ works. Any non-recognized assumptions
# are just added literally as something which is used in the hash
f_real2 = Function('f', is_real=True)
assert f_real2(x).is_real is True
def test_undef_fcn_float_issue_6938():
f = Function('ceil')
assert not f(0.3).is_number
f = Function('sin')
assert not f(0.3).is_number
assert not f(pi).evalf().is_number
x = Symbol('x')
assert not f(x).evalf(subs={x:1.2}).is_number
def test_undefined_function_eval():
# Issue 15170. Make sure UndefinedFunction with eval defined works
# properly.
fdiff = lambda self, argindex=1: cos(self.args[argindex - 1])
eval = classmethod(lambda cls, t: None)
_imp_ = classmethod(lambda cls, t: sin(t))
temp = Function('temp', fdiff=fdiff, eval=eval, _imp_=_imp_)
expr = temp(t)
assert sympify(expr) == expr
assert type(sympify(expr)).fdiff.__name__ == "<lambda>"
assert expr.diff(t) == cos(t)
def test_issue_15241():
F = f(x)
Fx = F.diff(x)
assert (F + x*Fx).diff(x, Fx) == 2
assert (F + x*Fx).diff(Fx, x) == 1
assert (x*F + x*Fx*F).diff(F, x) == x*Fx.diff(x) + Fx + 1
assert (x*F + x*Fx*F).diff(x, F) == x*Fx.diff(x) + Fx + 1
y = f(x)
G = f(y)
Gy = G.diff(y)
assert (G + y*Gy).diff(y, Gy) == 2
assert (G + y*Gy).diff(Gy, y) == 1
assert (y*G + y*Gy*G).diff(G, y) == y*Gy.diff(y) + Gy + 1
assert (y*G + y*Gy*G).diff(y, G) == y*Gy.diff(y) + Gy + 1
def test_issue_15226():
assert Subs(Derivative(f(y), x, y), y, g(x)).doit() != 0
def test_issue_7027():
for wrt in (cos(x), re(x), Derivative(cos(x), x)):
raises(ValueError, lambda: diff(f(x), wrt))
def test_derivative_quick_exit():
assert f(x).diff(y) == 0
assert f(x).diff(y, f(x)) == 0
assert f(x).diff(x, f(y)) == 0
assert f(f(x)).diff(x, f(x), f(y)) == 0
assert f(f(x)).diff(x, f(x), y) == 0
assert f(x).diff(g(x)) == 0
assert f(x).diff(x, f(x).diff(x)) == 1
df = f(x).diff(x)
assert f(x).diff(df) == 0
dg = g(x).diff(x)
assert dg.diff(df).doit() == 0
def test_issue_15084_13166():
eq = f(x, g(x))
assert eq.diff((g(x), y)) == Derivative(f(x, g(x)), (g(x), y))
# issue 13166
assert eq.diff(x, 2).doit() == (
(Derivative(f(x, g(x)), (g(x), 2))*Derivative(g(x), x) +
Subs(Derivative(f(x, _xi_2), _xi_2, x), _xi_2, g(x)))*Derivative(g(x),
x) + Derivative(f(x, g(x)), g(x))*Derivative(g(x), (x, 2)) +
Derivative(g(x), x)*Subs(Derivative(f(_xi_1, g(x)), _xi_1, g(x)),
_xi_1, x) + Subs(Derivative(f(_xi_1, g(x)), (_xi_1, 2)), _xi_1, x))
# issue 6681
assert diff(f(x, t, g(x, t)), x).doit() == (
Derivative(f(x, t, g(x, t)), g(x, t))*Derivative(g(x, t), x) +
Subs(Derivative(f(_xi_1, t, g(x, t)), _xi_1), _xi_1, x))
# make sure the order doesn't matter when using diff
assert eq.diff(x, g(x)) == eq.diff(g(x), x)
def test_negative_counts():
# issue 13873
raises(ValueError, lambda: sin(x).diff(x, -1))
def test_Derivative__new__():
raises(TypeError, lambda: f(x).diff((x, 2), 0))
assert f(x, y).diff([(x, y), 0]) == f(x, y)
assert f(x, y).diff([(x, y), 1]) == NDimArray([
Derivative(f(x, y), x), Derivative(f(x, y), y)])
assert f(x,y).diff(y, (x, z), y, x) == Derivative(
f(x, y), (x, z + 1), (y, 2))
assert Matrix([x]).diff(x, 2) == Matrix([0]) # is_zero exit
def test_issue_14719_10150():
class V(Expr):
_diff_wrt = True
is_scalar = False
assert V().diff(V()) == Derivative(V(), V())
assert (2*V()).diff(V()) == 2*Derivative(V(), V())
class X(Expr):
_diff_wrt = True
assert X().diff(X()) == 1
assert (2*X()).diff(X()) == 2
def test_noncommutative_issue_15131():
x = Symbol('x', commutative=False)
t = Symbol('t', commutative=False)
fx = Function('Fx', commutative=False)(x)
ft = Function('Ft', commutative=False)(t)
A = Symbol('A', commutative=False)
eq = fx * A * ft
eqdt = eq.diff(t)
assert eqdt.args[-1] == ft.diff(t)
def test_Subs_Derivative():
a = Derivative(f(g(x), h(x)), g(x), h(x),x)
b = Derivative(Derivative(f(g(x), h(x)), g(x), h(x)),x)
c = f(g(x), h(x)).diff(g(x), h(x), x)
d = f(g(x), h(x)).diff(g(x), h(x)).diff(x)
e = Derivative(f(g(x), h(x)), x)
eqs = (a, b, c, d, e)
subs = lambda arg: arg.subs(f, Lambda((x, y), exp(x + y))
).subs(g(x), 1/x).subs(h(x), x**3)
ans = 3*x**2*exp(1/x)*exp(x**3) - exp(1/x)*exp(x**3)/x**2
assert all(subs(i).doit().expand() == ans for i in eqs)
assert all(subs(i.doit()).doit().expand() == ans for i in eqs)
def test_issue_15360():
f = Function('f')
assert f.name == 'f'
def test_issue_15947():
assert f._diff_wrt is False
raises(TypeError, lambda: f(f))
raises(TypeError, lambda: f(x).diff(f))
def test_Derivative_free_symbols():
f = Function('f')
n = Symbol('n', integer=True, positive=True)
assert diff(f(x), (x, n)).free_symbols == {n, x}
def test_issue_20683():
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
y = Derivative(z, x).subs(x,0)
assert y.doit() == 0
y = Derivative(8, x).subs(x,0)
assert y.doit() == 0
def test_issue_10503():
f = exp(x**3)*cos(x**6)
assert f.series(x, 0, 14) == 1 + x**3 + x**6/2 + x**9/6 - 11*x**12/24 + O(x**14)
def test_issue_17382():
# copied from sympy/core/tests/test_evalf.py
def NS(e, n=15, **options):
return sstr(sympify(e).evalf(n, **options), full_prec=True)
x = Symbol('x')
expr = solveset(2 * cos(x) * cos(2 * x) - 1, x, S.Reals)
expected = "Union(" \
"ImageSet(Lambda(_n, 6.28318530717959*_n + 5.79812359592087), Integers), " \
"ImageSet(Lambda(_n, 6.28318530717959*_n + 0.485061711258717), Integers))"
assert NS(expr) == expected
def test_eval_sympified():
# Check both arguments and return types from eval are sympified
class F(Function):
@classmethod
def eval(cls, x):
assert x is S.One
return 1
assert F(1) is S.One
# String arguments are not allowed
class F2(Function):
@classmethod
def eval(cls, x):
if x == 0:
return '1'
raises(SympifyError, lambda: F2(0))
F2(1) # Doesn't raise
# TODO: Disable string inputs (https://github.com/sympy/sympy/issues/11003)
# raises(SympifyError, lambda: F2('2'))
def test_eval_classmethod_check():
with raises(TypeError):
class F(Function):
def eval(self, x):
pass
|
8de6cf8ebdf6550b0bf96de568e3312ae624ca8f5216991d5eb4c57ea0cbddee | from sympy.core.logic import fuzzy_and
from sympy.core.sympify import _sympify
from sympy.multipledispatch import dispatch
from sympy.testing.pytest import XFAIL, raises
from sympy.assumptions.ask import Q
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.expr import Expr
from sympy.core.function import Function
from sympy.core.mul import Mul
from sympy.core.numbers import (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.exponential import (exp, exp_polar, log)
from sympy.functions.elementary.integers import (ceiling, floor)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.logic.boolalg import (And, Implies, Not, Or, Xor)
from sympy.sets import Reals
from sympy.simplify.simplify import simplify
from sympy.simplify.trigsimp import trigsimp
from sympy.core.relational import (Relational, Equality, Unequality,
GreaterThan, LessThan, StrictGreaterThan,
StrictLessThan, Rel, Eq, Lt, Le,
Gt, Ge, Ne, is_le, is_gt, is_ge, is_lt, is_eq, is_neq)
from sympy.sets.sets import Interval, FiniteSet
from itertools import combinations
x, y, z, t = symbols('x,y,z,t')
def rel_check(a, b):
from sympy.testing.pytest import raises
assert a.is_number and b.is_number
for do in range(len({type(a), type(b)})):
if S.NaN in (a, b):
v = [(a == b), (a != b)]
assert len(set(v)) == 1 and v[0] == False
assert not (a != b) and not (a == b)
assert raises(TypeError, lambda: a < b)
assert raises(TypeError, lambda: a <= b)
assert raises(TypeError, lambda: a > b)
assert raises(TypeError, lambda: a >= b)
else:
E = [(a == b), (a != b)]
assert len(set(E)) == 2
v = [
(a < b), (a <= b), (a > b), (a >= b)]
i = [
[True, True, False, False],
[False, True, False, True], # <-- i == 1
[False, False, True, True]].index(v)
if i == 1:
assert E[0] or (a.is_Float != b.is_Float) # ugh
else:
assert E[1]
a, b = b, a
return True
def test_rel_ne():
assert Relational(x, y, '!=') == Ne(x, y)
# issue 6116
p = Symbol('p', positive=True)
assert Ne(p, 0) is S.true
def test_rel_subs():
e = Relational(x, y, '==')
e = e.subs(x, z)
assert isinstance(e, Equality)
assert e.lhs == z
assert e.rhs == y
e = Relational(x, y, '>=')
e = e.subs(x, z)
assert isinstance(e, GreaterThan)
assert e.lhs == z
assert e.rhs == y
e = Relational(x, y, '<=')
e = e.subs(x, z)
assert isinstance(e, LessThan)
assert e.lhs == z
assert e.rhs == y
e = Relational(x, y, '>')
e = e.subs(x, z)
assert isinstance(e, StrictGreaterThan)
assert e.lhs == z
assert e.rhs == y
e = Relational(x, y, '<')
e = e.subs(x, z)
assert isinstance(e, StrictLessThan)
assert e.lhs == z
assert e.rhs == y
e = Eq(x, 0)
assert e.subs(x, 0) is S.true
assert e.subs(x, 1) is S.false
def test_wrappers():
e = x + x**2
res = Relational(y, e, '==')
assert Rel(y, x + x**2, '==') == res
assert Eq(y, x + x**2) == res
res = Relational(y, e, '<')
assert Lt(y, x + x**2) == res
res = Relational(y, e, '<=')
assert Le(y, x + x**2) == res
res = Relational(y, e, '>')
assert Gt(y, x + x**2) == res
res = Relational(y, e, '>=')
assert Ge(y, x + x**2) == res
res = Relational(y, e, '!=')
assert Ne(y, x + x**2) == res
def test_Eq_Ne():
assert Eq(x, x) # issue 5719
# issue 6116
p = Symbol('p', positive=True)
assert Eq(p, 0) is S.false
# issue 13348; 19048
# SymPy is strict about 0 and 1 not being
# interpreted as Booleans
assert Eq(True, 1) is S.false
assert Eq(False, 0) is S.false
assert Eq(~x, 0) is S.false
assert Eq(~x, 1) is S.false
assert Ne(True, 1) is S.true
assert Ne(False, 0) is S.true
assert Ne(~x, 0) is S.true
assert Ne(~x, 1) is S.true
assert Eq((), 1) is S.false
assert Ne((), 1) is S.true
def test_as_poly():
from sympy.polys.polytools import Poly
# Only Eq should have an as_poly method:
assert Eq(x, 1).as_poly() == Poly(x - 1, x, domain='ZZ')
raises(AttributeError, lambda: Ne(x, 1).as_poly())
raises(AttributeError, lambda: Ge(x, 1).as_poly())
raises(AttributeError, lambda: Gt(x, 1).as_poly())
raises(AttributeError, lambda: Le(x, 1).as_poly())
raises(AttributeError, lambda: Lt(x, 1).as_poly())
def test_rel_Infinity():
# NOTE: All of these are actually handled by sympy.core.Number, and do
# not create Relational objects.
assert (oo > oo) is S.false
assert (oo > -oo) is S.true
assert (oo > 1) is S.true
assert (oo < oo) is S.false
assert (oo < -oo) is S.false
assert (oo < 1) is S.false
assert (oo >= oo) is S.true
assert (oo >= -oo) is S.true
assert (oo >= 1) is S.true
assert (oo <= oo) is S.true
assert (oo <= -oo) is S.false
assert (oo <= 1) is S.false
assert (-oo > oo) is S.false
assert (-oo > -oo) is S.false
assert (-oo > 1) is S.false
assert (-oo < oo) is S.true
assert (-oo < -oo) is S.false
assert (-oo < 1) is S.true
assert (-oo >= oo) is S.false
assert (-oo >= -oo) is S.true
assert (-oo >= 1) is S.false
assert (-oo <= oo) is S.true
assert (-oo <= -oo) is S.true
assert (-oo <= 1) is S.true
def test_infinite_symbol_inequalities():
x = Symbol('x', extended_positive=True, infinite=True)
y = Symbol('y', extended_positive=True, infinite=True)
z = Symbol('z', extended_negative=True, infinite=True)
w = Symbol('w', extended_negative=True, infinite=True)
inf_set = (x, y, oo)
ninf_set = (z, w, -oo)
for inf1 in inf_set:
assert (inf1 < 1) is S.false
assert (inf1 > 1) is S.true
assert (inf1 <= 1) is S.false
assert (inf1 >= 1) is S.true
for inf2 in inf_set:
assert (inf1 < inf2) is S.false
assert (inf1 > inf2) is S.false
assert (inf1 <= inf2) is S.true
assert (inf1 >= inf2) is S.true
for ninf1 in ninf_set:
assert (inf1 < ninf1) is S.false
assert (inf1 > ninf1) is S.true
assert (inf1 <= ninf1) is S.false
assert (inf1 >= ninf1) is S.true
assert (ninf1 < inf1) is S.true
assert (ninf1 > inf1) is S.false
assert (ninf1 <= inf1) is S.true
assert (ninf1 >= inf1) is S.false
for ninf1 in ninf_set:
assert (ninf1 < 1) is S.true
assert (ninf1 > 1) is S.false
assert (ninf1 <= 1) is S.true
assert (ninf1 >= 1) is S.false
for ninf2 in ninf_set:
assert (ninf1 < ninf2) is S.false
assert (ninf1 > ninf2) is S.false
assert (ninf1 <= ninf2) is S.true
assert (ninf1 >= ninf2) is S.true
def test_bool():
assert Eq(0, 0) is S.true
assert Eq(1, 0) is S.false
assert Ne(0, 0) is S.false
assert Ne(1, 0) is S.true
assert Lt(0, 1) is S.true
assert Lt(1, 0) is S.false
assert Le(0, 1) is S.true
assert Le(1, 0) is S.false
assert Le(0, 0) is S.true
assert Gt(1, 0) is S.true
assert Gt(0, 1) is S.false
assert Ge(1, 0) is S.true
assert Ge(0, 1) is S.false
assert Ge(1, 1) is S.true
assert Eq(I, 2) is S.false
assert Ne(I, 2) is S.true
raises(TypeError, lambda: Gt(I, 2))
raises(TypeError, lambda: Ge(I, 2))
raises(TypeError, lambda: Lt(I, 2))
raises(TypeError, lambda: Le(I, 2))
a = Float('.000000000000000000001', '')
b = Float('.0000000000000000000001', '')
assert Eq(pi + a, pi + b) is S.false
def test_rich_cmp():
assert (x < y) == Lt(x, y)
assert (x <= y) == Le(x, y)
assert (x > y) == Gt(x, y)
assert (x >= y) == Ge(x, y)
def test_doit():
from sympy.core.symbol import Symbol
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
np = Symbol('np', nonpositive=True)
nn = Symbol('nn', nonnegative=True)
assert Gt(p, 0).doit() is S.true
assert Gt(p, 1).doit() == Gt(p, 1)
assert Ge(p, 0).doit() is S.true
assert Le(p, 0).doit() is S.false
assert Lt(n, 0).doit() is S.true
assert Le(np, 0).doit() is S.true
assert Gt(nn, 0).doit() == Gt(nn, 0)
assert Lt(nn, 0).doit() is S.false
assert Eq(x, 0).doit() == Eq(x, 0)
def test_new_relational():
x = Symbol('x')
assert Eq(x, 0) == Relational(x, 0) # None ==> Equality
assert Eq(x, 0) == Relational(x, 0, '==')
assert Eq(x, 0) == Relational(x, 0, 'eq')
assert Eq(x, 0) == Equality(x, 0)
assert Eq(x, 0) != Relational(x, 1) # None ==> Equality
assert Eq(x, 0) != Relational(x, 1, '==')
assert Eq(x, 0) != Relational(x, 1, 'eq')
assert Eq(x, 0) != Equality(x, 1)
assert Eq(x, -1) == Relational(x, -1) # None ==> Equality
assert Eq(x, -1) == Relational(x, -1, '==')
assert Eq(x, -1) == Relational(x, -1, 'eq')
assert Eq(x, -1) == Equality(x, -1)
assert Eq(x, -1) != Relational(x, 1) # None ==> Equality
assert Eq(x, -1) != Relational(x, 1, '==')
assert Eq(x, -1) != Relational(x, 1, 'eq')
assert Eq(x, -1) != Equality(x, 1)
assert Ne(x, 0) == Relational(x, 0, '!=')
assert Ne(x, 0) == Relational(x, 0, '<>')
assert Ne(x, 0) == Relational(x, 0, 'ne')
assert Ne(x, 0) == Unequality(x, 0)
assert Ne(x, 0) != Relational(x, 1, '!=')
assert Ne(x, 0) != Relational(x, 1, '<>')
assert Ne(x, 0) != Relational(x, 1, 'ne')
assert Ne(x, 0) != Unequality(x, 1)
assert Ge(x, 0) == Relational(x, 0, '>=')
assert Ge(x, 0) == Relational(x, 0, 'ge')
assert Ge(x, 0) == GreaterThan(x, 0)
assert Ge(x, 1) != Relational(x, 0, '>=')
assert Ge(x, 1) != Relational(x, 0, 'ge')
assert Ge(x, 1) != GreaterThan(x, 0)
assert (x >= 1) == Relational(x, 1, '>=')
assert (x >= 1) == Relational(x, 1, 'ge')
assert (x >= 1) == GreaterThan(x, 1)
assert (x >= 0) != Relational(x, 1, '>=')
assert (x >= 0) != Relational(x, 1, 'ge')
assert (x >= 0) != GreaterThan(x, 1)
assert Le(x, 0) == Relational(x, 0, '<=')
assert Le(x, 0) == Relational(x, 0, 'le')
assert Le(x, 0) == LessThan(x, 0)
assert Le(x, 1) != Relational(x, 0, '<=')
assert Le(x, 1) != Relational(x, 0, 'le')
assert Le(x, 1) != LessThan(x, 0)
assert (x <= 1) == Relational(x, 1, '<=')
assert (x <= 1) == Relational(x, 1, 'le')
assert (x <= 1) == LessThan(x, 1)
assert (x <= 0) != Relational(x, 1, '<=')
assert (x <= 0) != Relational(x, 1, 'le')
assert (x <= 0) != LessThan(x, 1)
assert Gt(x, 0) == Relational(x, 0, '>')
assert Gt(x, 0) == Relational(x, 0, 'gt')
assert Gt(x, 0) == StrictGreaterThan(x, 0)
assert Gt(x, 1) != Relational(x, 0, '>')
assert Gt(x, 1) != Relational(x, 0, 'gt')
assert Gt(x, 1) != StrictGreaterThan(x, 0)
assert (x > 1) == Relational(x, 1, '>')
assert (x > 1) == Relational(x, 1, 'gt')
assert (x > 1) == StrictGreaterThan(x, 1)
assert (x > 0) != Relational(x, 1, '>')
assert (x > 0) != Relational(x, 1, 'gt')
assert (x > 0) != StrictGreaterThan(x, 1)
assert Lt(x, 0) == Relational(x, 0, '<')
assert Lt(x, 0) == Relational(x, 0, 'lt')
assert Lt(x, 0) == StrictLessThan(x, 0)
assert Lt(x, 1) != Relational(x, 0, '<')
assert Lt(x, 1) != Relational(x, 0, 'lt')
assert Lt(x, 1) != StrictLessThan(x, 0)
assert (x < 1) == Relational(x, 1, '<')
assert (x < 1) == Relational(x, 1, 'lt')
assert (x < 1) == StrictLessThan(x, 1)
assert (x < 0) != Relational(x, 1, '<')
assert (x < 0) != Relational(x, 1, 'lt')
assert (x < 0) != StrictLessThan(x, 1)
# finally, some fuzz testing
from sympy.core.random import randint
for i in range(100):
while 1:
strtype, length = (chr, 65535) if randint(0, 1) else (chr, 255)
relation_type = strtype(randint(0, length))
if randint(0, 1):
relation_type += strtype(randint(0, length))
if relation_type not in ('==', 'eq', '!=', '<>', 'ne', '>=', 'ge',
'<=', 'le', '>', 'gt', '<', 'lt', ':=',
'+=', '-=', '*=', '/=', '%='):
break
raises(ValueError, lambda: Relational(x, 1, relation_type))
assert all(Relational(x, 0, op).rel_op == '==' for op in ('eq', '=='))
assert all(Relational(x, 0, op).rel_op == '!='
for op in ('ne', '<>', '!='))
assert all(Relational(x, 0, op).rel_op == '>' for op in ('gt', '>'))
assert all(Relational(x, 0, op).rel_op == '<' for op in ('lt', '<'))
assert all(Relational(x, 0, op).rel_op == '>=' for op in ('ge', '>='))
assert all(Relational(x, 0, op).rel_op == '<=' for op in ('le', '<='))
def test_relational_arithmetic():
for cls in [Eq, Ne, Le, Lt, Ge, Gt]:
rel = cls(x, y)
raises(TypeError, lambda: 0+rel)
raises(TypeError, lambda: 1*rel)
raises(TypeError, lambda: 1**rel)
raises(TypeError, lambda: rel**1)
raises(TypeError, lambda: Add(0, rel))
raises(TypeError, lambda: Mul(1, rel))
raises(TypeError, lambda: Pow(1, rel))
raises(TypeError, lambda: Pow(rel, 1))
def test_relational_bool_output():
# https://github.com/sympy/sympy/issues/5931
raises(TypeError, lambda: bool(x > 3))
raises(TypeError, lambda: bool(x >= 3))
raises(TypeError, lambda: bool(x < 3))
raises(TypeError, lambda: bool(x <= 3))
raises(TypeError, lambda: bool(Eq(x, 3)))
raises(TypeError, lambda: bool(Ne(x, 3)))
def test_relational_logic_symbols():
# See issue 6204
assert (x < y) & (z < t) == And(x < y, z < t)
assert (x < y) | (z < t) == Or(x < y, z < t)
assert ~(x < y) == Not(x < y)
assert (x < y) >> (z < t) == Implies(x < y, z < t)
assert (x < y) << (z < t) == Implies(z < t, x < y)
assert (x < y) ^ (z < t) == Xor(x < y, z < t)
assert isinstance((x < y) & (z < t), And)
assert isinstance((x < y) | (z < t), Or)
assert isinstance(~(x < y), GreaterThan)
assert isinstance((x < y) >> (z < t), Implies)
assert isinstance((x < y) << (z < t), Implies)
assert isinstance((x < y) ^ (z < t), (Or, Xor))
def test_univariate_relational_as_set():
assert (x > 0).as_set() == Interval(0, oo, True, True)
assert (x >= 0).as_set() == Interval(0, oo)
assert (x < 0).as_set() == Interval(-oo, 0, True, True)
assert (x <= 0).as_set() == Interval(-oo, 0)
assert Eq(x, 0).as_set() == FiniteSet(0)
assert Ne(x, 0).as_set() == Interval(-oo, 0, True, True) + \
Interval(0, oo, True, True)
assert (x**2 >= 4).as_set() == Interval(-oo, -2) + Interval(2, oo)
@XFAIL
def test_multivariate_relational_as_set():
assert (x*y >= 0).as_set() == Interval(0, oo)*Interval(0, oo) + \
Interval(-oo, 0)*Interval(-oo, 0)
def test_Not():
assert Not(Equality(x, y)) == Unequality(x, y)
assert Not(Unequality(x, y)) == Equality(x, y)
assert Not(StrictGreaterThan(x, y)) == LessThan(x, y)
assert Not(StrictLessThan(x, y)) == GreaterThan(x, y)
assert Not(GreaterThan(x, y)) == StrictLessThan(x, y)
assert Not(LessThan(x, y)) == StrictGreaterThan(x, y)
def test_evaluate():
assert str(Eq(x, x, evaluate=False)) == 'Eq(x, x)'
assert Eq(x, x, evaluate=False).doit() == S.true
assert str(Ne(x, x, evaluate=False)) == 'Ne(x, x)'
assert Ne(x, x, evaluate=False).doit() == S.false
assert str(Ge(x, x, evaluate=False)) == 'x >= x'
assert str(Le(x, x, evaluate=False)) == 'x <= x'
assert str(Gt(x, x, evaluate=False)) == 'x > x'
assert str(Lt(x, x, evaluate=False)) == 'x < x'
def assert_all_ineq_raise_TypeError(a, b):
raises(TypeError, lambda: a > b)
raises(TypeError, lambda: a >= b)
raises(TypeError, lambda: a < b)
raises(TypeError, lambda: a <= b)
raises(TypeError, lambda: b > a)
raises(TypeError, lambda: b >= a)
raises(TypeError, lambda: b < a)
raises(TypeError, lambda: b <= a)
def assert_all_ineq_give_class_Inequality(a, b):
"""All inequality operations on `a` and `b` result in class Inequality."""
from sympy.core.relational import _Inequality as Inequality
assert isinstance(a > b, Inequality)
assert isinstance(a >= b, Inequality)
assert isinstance(a < b, Inequality)
assert isinstance(a <= b, Inequality)
assert isinstance(b > a, Inequality)
assert isinstance(b >= a, Inequality)
assert isinstance(b < a, Inequality)
assert isinstance(b <= a, Inequality)
def test_imaginary_compare_raises_TypeError():
# See issue #5724
assert_all_ineq_raise_TypeError(I, x)
def test_complex_compare_not_real():
# two cases which are not real
y = Symbol('y', imaginary=True)
z = Symbol('z', complex=True, extended_real=False)
for w in (y, z):
assert_all_ineq_raise_TypeError(2, w)
# some cases which should remain un-evaluated
t = Symbol('t')
x = Symbol('x', real=True)
z = Symbol('z', complex=True)
for w in (x, z, t):
assert_all_ineq_give_class_Inequality(2, w)
def test_imaginary_and_inf_compare_raises_TypeError():
# See pull request #7835
y = Symbol('y', imaginary=True)
assert_all_ineq_raise_TypeError(oo, y)
assert_all_ineq_raise_TypeError(-oo, y)
def test_complex_pure_imag_not_ordered():
raises(TypeError, lambda: 2*I < 3*I)
# more generally
x = Symbol('x', real=True, nonzero=True)
y = Symbol('y', imaginary=True)
z = Symbol('z', complex=True)
assert_all_ineq_raise_TypeError(I, y)
t = I*x # an imaginary number, should raise errors
assert_all_ineq_raise_TypeError(2, t)
t = -I*y # a real number, so no errors
assert_all_ineq_give_class_Inequality(2, t)
t = I*z # unknown, should be unevaluated
assert_all_ineq_give_class_Inequality(2, t)
def test_x_minus_y_not_same_as_x_lt_y():
"""
A consequence of pull request #7792 is that `x - y < 0` and `x < y`
are not synonymous.
"""
x = I + 2
y = I + 3
raises(TypeError, lambda: x < y)
assert x - y < 0
ineq = Lt(x, y, evaluate=False)
raises(TypeError, lambda: ineq.doit())
assert ineq.lhs - ineq.rhs < 0
t = Symbol('t', imaginary=True)
x = 2 + t
y = 3 + t
ineq = Lt(x, y, evaluate=False)
raises(TypeError, lambda: ineq.doit())
assert ineq.lhs - ineq.rhs < 0
# this one should give error either way
x = I + 2
y = 2*I + 3
raises(TypeError, lambda: x < y)
raises(TypeError, lambda: x - y < 0)
def test_nan_equality_exceptions():
# See issue #7774
import random
assert Equality(nan, nan) is S.false
assert Unequality(nan, nan) is S.true
# See issue #7773
A = (x, S.Zero, S.One/3, pi, oo, -oo)
assert Equality(nan, random.choice(A)) is S.false
assert Equality(random.choice(A), nan) is S.false
assert Unequality(nan, random.choice(A)) is S.true
assert Unequality(random.choice(A), nan) is S.true
def test_nan_inequality_raise_errors():
# See discussion in pull request #7776. We test inequalities with
# a set including examples of various classes.
for q in (x, S.Zero, S(10), S.One/3, pi, S(1.3), oo, -oo, nan):
assert_all_ineq_raise_TypeError(q, nan)
def test_nan_complex_inequalities():
# Comparisons of NaN with non-real raise errors, we're not too
# fussy whether its the NaN error or complex error.
for r in (I, zoo, Symbol('z', imaginary=True)):
assert_all_ineq_raise_TypeError(r, nan)
def test_complex_infinity_inequalities():
raises(TypeError, lambda: zoo > 0)
raises(TypeError, lambda: zoo >= 0)
raises(TypeError, lambda: zoo < 0)
raises(TypeError, lambda: zoo <= 0)
def test_inequalities_symbol_name_same():
"""Using the operator and functional forms should give same results."""
# We test all combinations from a set
# FIXME: could replace with random selection after test passes
A = (x, y, S.Zero, S.One/3, pi, oo, -oo)
for a in A:
for b in A:
assert Gt(a, b) == (a > b)
assert Lt(a, b) == (a < b)
assert Ge(a, b) == (a >= b)
assert Le(a, b) == (a <= b)
for b in (y, S.Zero, S.One/3, pi, oo, -oo):
assert Gt(x, b, evaluate=False) == (x > b)
assert Lt(x, b, evaluate=False) == (x < b)
assert Ge(x, b, evaluate=False) == (x >= b)
assert Le(x, b, evaluate=False) == (x <= b)
for b in (y, S.Zero, S.One/3, pi, oo, -oo):
assert Gt(b, x, evaluate=False) == (b > x)
assert Lt(b, x, evaluate=False) == (b < x)
assert Ge(b, x, evaluate=False) == (b >= x)
assert Le(b, x, evaluate=False) == (b <= x)
def test_inequalities_symbol_name_same_complex():
"""Using the operator and functional forms should give same results.
With complex non-real numbers, both should raise errors.
"""
# FIXME: could replace with random selection after test passes
for a in (x, S.Zero, S.One/3, pi, oo, Rational(1, 3)):
raises(TypeError, lambda: Gt(a, I))
raises(TypeError, lambda: a > I)
raises(TypeError, lambda: Lt(a, I))
raises(TypeError, lambda: a < I)
raises(TypeError, lambda: Ge(a, I))
raises(TypeError, lambda: a >= I)
raises(TypeError, lambda: Le(a, I))
raises(TypeError, lambda: a <= I)
def test_inequalities_cant_sympify_other():
# see issue 7833
from operator import gt, lt, ge, le
bar = "foo"
for a in (x, S.Zero, S.One/3, pi, I, zoo, oo, -oo, nan, Rational(1, 3)):
for op in (lt, gt, le, ge):
raises(TypeError, lambda: op(a, bar))
def test_ineq_avoid_wild_symbol_flip():
# see issue #7951, we try to avoid this internally, e.g., by using
# __lt__ instead of "<".
from sympy.core.symbol import Wild
p = symbols('p', cls=Wild)
# x > p might flip, but Gt should not:
assert Gt(x, p) == Gt(x, p, evaluate=False)
# Previously failed as 'p > x':
e = Lt(x, y).subs({y: p})
assert e == Lt(x, p, evaluate=False)
# Previously failed as 'p <= x':
e = Ge(x, p).doit()
assert e == Ge(x, p, evaluate=False)
def test_issue_8245():
a = S("6506833320952669167898688709329/5070602400912917605986812821504")
assert rel_check(a, a.n(10))
assert rel_check(a, a.n(20))
assert rel_check(a, a.n())
# prec of 31 is enough to fully capture a as mpf
assert Float(a, 31) == Float(str(a.p), '')/Float(str(a.q), '')
for i in range(31):
r = Rational(Float(a, i))
f = Float(r)
assert (f < a) == (Rational(f) < a)
# test sign handling
assert (-f < -a) == (Rational(-f) < -a)
# test equivalence handling
isa = Float(a.p,'')/Float(a.q,'')
assert isa <= a
assert not isa < a
assert isa >= a
assert not isa > a
assert isa > 0
a = sqrt(2)
r = Rational(str(a.n(30)))
assert rel_check(a, r)
a = sqrt(2)
r = Rational(str(a.n(29)))
assert rel_check(a, r)
assert Eq(log(cos(2)**2 + sin(2)**2), 0) is S.true
def test_issue_8449():
p = Symbol('p', nonnegative=True)
assert Lt(-oo, p)
assert Ge(-oo, p) is S.false
assert Gt(oo, -p)
assert Le(oo, -p) is S.false
def test_simplify_relational():
assert simplify(x*(y + 1) - x*y - x + 1 < x) == (x > 1)
assert simplify(x*(y + 1) - x*y - x - 1 < x) == (x > -1)
assert simplify(x < x*(y + 1) - x*y - x + 1) == (x < 1)
q, r = symbols("q r")
assert (((-q + r) - (q - r)) <= 0).simplify() == (q >= r)
root2 = sqrt(2)
equation = ((root2 * (-q + r) - root2 * (q - r)) <= 0).simplify()
assert equation == (q >= r)
r = S.One < x
# canonical operations are not the same as simplification,
# so if there is no simplification, canonicalization will
# be done unless the measure forbids it
assert simplify(r) == r.canonical
assert simplify(r, ratio=0) != r.canonical
# this is not a random test; in _eval_simplify
# this will simplify to S.false and that is the
# reason for the 'if r.is_Relational' in Relational's
# _eval_simplify routine
assert simplify(-(2**(pi*Rational(3, 2)) + 6**pi)**(1/pi) +
2*(2**(pi/2) + 3**pi)**(1/pi) < 0) is S.false
# canonical at least
assert Eq(y, x).simplify() == Eq(x, y)
assert Eq(x - 1, 0).simplify() == Eq(x, 1)
assert Eq(x - 1, x).simplify() == S.false
assert Eq(2*x - 1, x).simplify() == Eq(x, 1)
assert Eq(2*x, 4).simplify() == Eq(x, 2)
z = cos(1)**2 + sin(1)**2 - 1 # z.is_zero is None
assert Eq(z*x, 0).simplify() == S.true
assert Ne(y, x).simplify() == Ne(x, y)
assert Ne(x - 1, 0).simplify() == Ne(x, 1)
assert Ne(x - 1, x).simplify() == S.true
assert Ne(2*x - 1, x).simplify() == Ne(x, 1)
assert Ne(2*x, 4).simplify() == Ne(x, 2)
assert Ne(z*x, 0).simplify() == S.false
# No real-valued assumptions
assert Ge(y, x).simplify() == Le(x, y)
assert Ge(x - 1, 0).simplify() == Ge(x, 1)
assert Ge(x - 1, x).simplify() == S.false
assert Ge(2*x - 1, x).simplify() == Ge(x, 1)
assert Ge(2*x, 4).simplify() == Ge(x, 2)
assert Ge(z*x, 0).simplify() == S.true
assert Ge(x, -2).simplify() == Ge(x, -2)
assert Ge(-x, -2).simplify() == Le(x, 2)
assert Ge(x, 2).simplify() == Ge(x, 2)
assert Ge(-x, 2).simplify() == Le(x, -2)
assert Le(y, x).simplify() == Ge(x, y)
assert Le(x - 1, 0).simplify() == Le(x, 1)
assert Le(x - 1, x).simplify() == S.true
assert Le(2*x - 1, x).simplify() == Le(x, 1)
assert Le(2*x, 4).simplify() == Le(x, 2)
assert Le(z*x, 0).simplify() == S.true
assert Le(x, -2).simplify() == Le(x, -2)
assert Le(-x, -2).simplify() == Ge(x, 2)
assert Le(x, 2).simplify() == Le(x, 2)
assert Le(-x, 2).simplify() == Ge(x, -2)
assert Gt(y, x).simplify() == Lt(x, y)
assert Gt(x - 1, 0).simplify() == Gt(x, 1)
assert Gt(x - 1, x).simplify() == S.false
assert Gt(2*x - 1, x).simplify() == Gt(x, 1)
assert Gt(2*x, 4).simplify() == Gt(x, 2)
assert Gt(z*x, 0).simplify() == S.false
assert Gt(x, -2).simplify() == Gt(x, -2)
assert Gt(-x, -2).simplify() == Lt(x, 2)
assert Gt(x, 2).simplify() == Gt(x, 2)
assert Gt(-x, 2).simplify() == Lt(x, -2)
assert Lt(y, x).simplify() == Gt(x, y)
assert Lt(x - 1, 0).simplify() == Lt(x, 1)
assert Lt(x - 1, x).simplify() == S.true
assert Lt(2*x - 1, x).simplify() == Lt(x, 1)
assert Lt(2*x, 4).simplify() == Lt(x, 2)
assert Lt(z*x, 0).simplify() == S.false
assert Lt(x, -2).simplify() == Lt(x, -2)
assert Lt(-x, -2).simplify() == Gt(x, 2)
assert Lt(x, 2).simplify() == Lt(x, 2)
assert Lt(-x, 2).simplify() == Gt(x, -2)
# Test particulat branches of _eval_simplify
m = exp(1) - exp_polar(1)
assert simplify(m*x > 1) is S.false
# These two tests the same branch
assert simplify(m*x + 2*m*y > 1) is S.false
assert simplify(m*x + y > 1 + y) is S.false
def test_equals():
w, x, y, z = symbols('w:z')
f = Function('f')
assert Eq(x, 1).equals(Eq(x*(y + 1) - x*y - x + 1, x))
assert Eq(x, y).equals(x < y, True) == False
assert Eq(x, f(1)).equals(Eq(x, f(2)), True) == f(1) - f(2)
assert Eq(f(1), y).equals(Eq(f(2), y), True) == f(1) - f(2)
assert Eq(x, f(1)).equals(Eq(f(2), x), True) == f(1) - f(2)
assert Eq(f(1), x).equals(Eq(x, f(2)), True) == f(1) - f(2)
assert Eq(w, x).equals(Eq(y, z), True) == False
assert Eq(f(1), f(2)).equals(Eq(f(3), f(4)), True) == f(1) - f(3)
assert (x < y).equals(y > x, True) == True
assert (x < y).equals(y >= x, True) == False
assert (x < y).equals(z < y, True) == False
assert (x < y).equals(x < z, True) == False
assert (x < f(1)).equals(x < f(2), True) == f(1) - f(2)
assert (f(1) < x).equals(f(2) < x, True) == f(1) - f(2)
def test_reversed():
assert (x < y).reversed == (y > x)
assert (x <= y).reversed == (y >= x)
assert Eq(x, y, evaluate=False).reversed == Eq(y, x, evaluate=False)
assert Ne(x, y, evaluate=False).reversed == Ne(y, x, evaluate=False)
assert (x >= y).reversed == (y <= x)
assert (x > y).reversed == (y < x)
def test_canonical():
c = [i.canonical for i in (
x + y < z,
x + 2 > 3,
x < 2,
S(2) > x,
x**2 > -x/y,
Gt(3, 2, evaluate=False)
)]
assert [i.canonical for i in c] == c
assert [i.reversed.canonical for i in c] == c
assert not any(i.lhs.is_Number and not i.rhs.is_Number for i in c)
c = [i.reversed.func(i.rhs, i.lhs, evaluate=False).canonical for i in c]
assert [i.canonical for i in c] == c
assert [i.reversed.canonical for i in c] == c
assert not any(i.lhs.is_Number and not i.rhs.is_Number for i in c)
assert Eq(y < x, x > y).canonical is S.true
@XFAIL
def test_issue_8444_nonworkingtests():
x = symbols('x', real=True)
assert (x <= oo) == (x >= -oo) == True
x = symbols('x')
assert x >= floor(x)
assert (x < floor(x)) == False
assert x <= ceiling(x)
assert (x > ceiling(x)) == False
def test_issue_8444_workingtests():
x = symbols('x')
assert Gt(x, floor(x)) == Gt(x, floor(x), evaluate=False)
assert Ge(x, floor(x)) == Ge(x, floor(x), evaluate=False)
assert Lt(x, ceiling(x)) == Lt(x, ceiling(x), evaluate=False)
assert Le(x, ceiling(x)) == Le(x, ceiling(x), evaluate=False)
i = symbols('i', integer=True)
assert (i > floor(i)) == False
assert (i < ceiling(i)) == False
def test_issue_10304():
d = cos(1)**2 + sin(1)**2 - 1
assert d.is_comparable is False # if this fails, find a new d
e = 1 + d*I
assert simplify(Eq(e, 0)) is S.false
def test_issue_18412():
d = (Rational(1, 6) + z / 4 / y)
assert Eq(x, pi * y**3 * d).replace(y**3, z) == Eq(x, pi * z * d)
def test_issue_10401():
x = symbols('x')
fin = symbols('inf', finite=True)
inf = symbols('inf', infinite=True)
inf2 = symbols('inf2', infinite=True)
infx = symbols('infx', infinite=True, extended_real=True)
# Used in the commented tests below:
#infx2 = symbols('infx2', infinite=True, extended_real=True)
infnx = symbols('inf~x', infinite=True, extended_real=False)
infnx2 = symbols('inf~x2', infinite=True, extended_real=False)
infp = symbols('infp', infinite=True, extended_positive=True)
infp1 = symbols('infp1', infinite=True, extended_positive=True)
infn = symbols('infn', infinite=True, extended_negative=True)
zero = symbols('z', zero=True)
nonzero = symbols('nz', zero=False, finite=True)
assert Eq(1/(1/x + 1), 1).func is Eq
assert Eq(1/(1/x + 1), 1).subs(x, S.ComplexInfinity) is S.true
assert Eq(1/(1/fin + 1), 1) is S.false
T, F = S.true, S.false
assert Eq(fin, inf) is F
assert Eq(inf, inf2) not in (T, F) and inf != inf2
assert Eq(1 + inf, 2 + inf2) not in (T, F) and inf != inf2
assert Eq(infp, infp1) is T
assert Eq(infp, infn) is F
assert Eq(1 + I*oo, I*oo) is F
assert Eq(I*oo, 1 + I*oo) is F
assert Eq(1 + I*oo, 2 + I*oo) is F
assert Eq(1 + I*oo, 2 + I*infx) is F
assert Eq(1 + I*oo, 2 + infx) is F
# FIXME: The test below fails because (-infx).is_extended_positive is True
# (should be None)
#assert Eq(1 + I*infx, 1 + I*infx2) not in (T, F) and infx != infx2
#
assert Eq(zoo, sqrt(2) + I*oo) is F
assert Eq(zoo, oo) is F
r = Symbol('r', real=True)
i = Symbol('i', imaginary=True)
assert Eq(i*I, r) not in (T, F)
assert Eq(infx, infnx) is F
assert Eq(infnx, infnx2) not in (T, F) and infnx != infnx2
assert Eq(zoo, oo) is F
assert Eq(inf/inf2, 0) is F
assert Eq(inf/fin, 0) is F
assert Eq(fin/inf, 0) is T
assert Eq(zero/nonzero, 0) is T and ((zero/nonzero) != 0)
# The commented out test below is incorrect because:
assert zoo == -zoo
assert Eq(zoo, -zoo) is T
assert Eq(oo, -oo) is F
assert Eq(inf, -inf) not in (T, F)
assert Eq(fin/(fin + 1), 1) is S.false
o = symbols('o', odd=True)
assert Eq(o, 2*o) is S.false
p = symbols('p', positive=True)
assert Eq(p/(p - 1), 1) is F
def test_issue_10633():
assert Eq(True, False) == False
assert Eq(False, True) == False
assert Eq(True, True) == True
assert Eq(False, False) == True
def test_issue_10927():
x = symbols('x')
assert str(Eq(x, oo)) == 'Eq(x, oo)'
assert str(Eq(x, -oo)) == 'Eq(x, -oo)'
def test_issues_13081_12583_12534():
# 13081
r = Rational('905502432259640373/288230376151711744')
assert (r < pi) is S.false
assert (r > pi) is S.true
# 12583
v = sqrt(2)
u = sqrt(v) + 2/sqrt(10 - 8/sqrt(2 - v) + 4*v*(1/sqrt(2 - v) - 1))
assert (u >= 0) is S.true
# 12534; Rational vs NumberSymbol
# here are some precisions for which Rational forms
# at a lower and higher precision bracket the value of pi
# e.g. for p = 20:
# Rational(pi.n(p + 1)).n(25) = 3.14159265358979323846 2834
# pi.n(25) = 3.14159265358979323846 2643
# Rational(pi.n(p )).n(25) = 3.14159265358979323846 1987
assert [p for p in range(20, 50) if
(Rational(pi.n(p)) < pi) and
(pi < Rational(pi.n(p + 1)))] == [20, 24, 27, 33, 37, 43, 48]
# pick one such precision and affirm that the reversed operation
# gives the opposite result, i.e. if x < y is true then x > y
# must be false
for i in (20, 21):
v = pi.n(i)
assert rel_check(Rational(v), pi)
assert rel_check(v, pi)
assert rel_check(pi.n(20), pi.n(21))
# Float vs Rational
# the rational form is less than the floating representation
# at the same precision
assert [i for i in range(15, 50) if Rational(pi.n(i)) > pi.n(i)] == []
# this should be the same if we reverse the relational
assert [i for i in range(15, 50) if pi.n(i) < Rational(pi.n(i))] == []
def test_issue_18188():
from sympy.sets.conditionset import ConditionSet
result1 = Eq(x*cos(x) - 3*sin(x), 0)
assert result1.as_set() == ConditionSet(x, Eq(x*cos(x) - 3*sin(x), 0), Reals)
result2 = Eq(x**2 + sqrt(x*2) + sin(x), 0)
assert result2.as_set() == ConditionSet(x, Eq(sqrt(2)*sqrt(x) + x**2 + sin(x), 0), Reals)
def test_binary_symbols():
ans = {x}
for f in Eq, Ne:
for t in S.true, S.false:
eq = f(x, S.true)
assert eq.binary_symbols == ans
assert eq.reversed.binary_symbols == ans
assert f(x, 1).binary_symbols == set()
def test_rel_args():
# can't have Boolean args; this is automatic for True/False
# with Python 3 and we confirm that SymPy does the same
# for true/false
for op in ['<', '<=', '>', '>=']:
for b in (S.true, x < 1, And(x, y)):
for v in (0.1, 1, 2**32, t, S.One):
raises(TypeError, lambda: Relational(b, v, op))
def test_Equality_rewrite_as_Add():
eq = Eq(x + y, y - x)
assert eq.rewrite(Add) == 2*x
assert eq.rewrite(Add, evaluate=None).args == (x, x, y, -y)
assert eq.rewrite(Add, evaluate=False).args == (x, y, x, -y)
for e in (True, False, None):
assert Eq(x, 0, evaluate=e).rewrite(Add) == x
assert Eq(0, x, evaluate=e).rewrite(Add) == x
def test_issue_15847():
a = Ne(x*(x+y), x**2 + x*y)
assert simplify(a) == False
def test_negated_property():
eq = Eq(x, y)
assert eq.negated == Ne(x, y)
eq = Ne(x, y)
assert eq.negated == Eq(x, y)
eq = Ge(x + y, y - x)
assert eq.negated == Lt(x + y, y - x)
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(x, y).negated.negated == f(x, y)
def test_reversedsign_property():
eq = Eq(x, y)
assert eq.reversedsign == Eq(-x, -y)
eq = Ne(x, y)
assert eq.reversedsign == Ne(-x, -y)
eq = Ge(x + y, y - x)
assert eq.reversedsign == Le(-x - y, x - y)
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(x, y).reversedsign.reversedsign == f(x, y)
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(-x, y).reversedsign.reversedsign == f(-x, y)
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(x, -y).reversedsign.reversedsign == f(x, -y)
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(-x, -y).reversedsign.reversedsign == f(-x, -y)
def test_reversed_reversedsign_property():
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(x, y).reversed.reversedsign == f(x, y).reversedsign.reversed
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(-x, y).reversed.reversedsign == f(-x, y).reversedsign.reversed
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(x, -y).reversed.reversedsign == f(x, -y).reversedsign.reversed
for f in (Eq, Ne, Ge, Gt, Le, Lt):
assert f(-x, -y).reversed.reversedsign == \
f(-x, -y).reversedsign.reversed
def test_improved_canonical():
def test_different_forms(listofforms):
for form1, form2 in combinations(listofforms, 2):
assert form1.canonical == form2.canonical
def generate_forms(expr):
return [expr, expr.reversed, expr.reversedsign,
expr.reversed.reversedsign]
test_different_forms(generate_forms(x > -y))
test_different_forms(generate_forms(x >= -y))
test_different_forms(generate_forms(Eq(x, -y)))
test_different_forms(generate_forms(Ne(x, -y)))
test_different_forms(generate_forms(pi < x))
test_different_forms(generate_forms(pi - 5*y < -x + 2*y**2 - 7))
assert (pi >= x).canonical == (x <= pi)
def test_set_equality_canonical():
a, b, c = symbols('a b c')
A = Eq(FiniteSet(a, b, c), FiniteSet(1, 2, 3))
B = Ne(FiniteSet(a, b, c), FiniteSet(4, 5, 6))
assert A.canonical == A.reversed
assert B.canonical == B.reversed
def test_trigsimp():
# issue 16736
s, c = sin(2*x), cos(2*x)
eq = Eq(s, c)
assert trigsimp(eq) == eq # no rearrangement of sides
# simplification of sides might result in
# an unevaluated Eq
changed = trigsimp(Eq(s + c, sqrt(2)))
assert isinstance(changed, Eq)
assert changed.subs(x, pi/8) is S.true
# or an evaluated one
assert trigsimp(Eq(cos(x)**2 + sin(x)**2, 1)) is S.true
def test_polynomial_relation_simplification():
assert Ge(3*x*(x + 1) + 4, 3*x).simplify() in [Ge(x**2, -Rational(4,3)), Le(-x**2, Rational(4, 3))]
assert Le(-(3*x*(x + 1) + 4), -3*x).simplify() in [Ge(x**2, -Rational(4,3)), Le(-x**2, Rational(4, 3))]
assert ((x**2+3)*(x**2-1)+3*x >= 2*x**2).simplify() in [(x**4 + 3*x >= 3), (-x**4 - 3*x <= -3)]
def test_multivariate_linear_function_simplification():
assert Ge(x + y, x - y).simplify() == Ge(y, 0)
assert Le(-x + y, -x - y).simplify() == Le(y, 0)
assert Eq(2*x + y, 2*x + y - 3).simplify() == False
assert (2*x + y > 2*x + y - 3).simplify() == True
assert (2*x + y < 2*x + y - 3).simplify() == False
assert (2*x + y < 2*x + y + 3).simplify() == True
a, b, c, d, e, f, g = symbols('a b c d e f g')
assert Lt(a + b + c + 2*d, 3*d - f + g). simplify() == Lt(a, -b - c + d - f + g)
def test_nonpolymonial_relations():
assert Eq(cos(x), 0).simplify() == Eq(cos(x), 0)
def test_18778():
raises(TypeError, lambda: is_le(Basic(), Basic()))
raises(TypeError, lambda: is_gt(Basic(), Basic()))
raises(TypeError, lambda: is_ge(Basic(), Basic()))
raises(TypeError, lambda: is_lt(Basic(), Basic()))
def test_EvalEq():
"""
This test exists to ensure backwards compatibility.
The method to use is _eval_is_eq
"""
from sympy.core.expr import Expr
class PowTest(Expr):
def __new__(cls, base, exp):
return Basic.__new__(PowTest, _sympify(base), _sympify(exp))
def _eval_Eq(lhs, rhs):
if type(lhs) == PowTest and type(rhs) == PowTest:
return lhs.args[0] == rhs.args[0] and lhs.args[1] == rhs.args[1]
assert is_eq(PowTest(3, 4), PowTest(3,4))
assert is_eq(PowTest(3, 4), _sympify(4)) is None
assert is_neq(PowTest(3, 4), PowTest(3,7))
def test_is_eq():
# test assumptions
assert is_eq(x, y, Q.infinite(x) & Q.finite(y)) is False
assert is_eq(x, y, Q.infinite(x) & Q.infinite(y) & Q.extended_real(x) & ~Q.extended_real(y)) is False
assert is_eq(x, y, Q.infinite(x) & Q.infinite(y) & Q.extended_positive(x) & Q.extended_negative(y)) is False
assert is_eq(x+I, y+I, Q.infinite(x) & Q.finite(y)) is False
assert is_eq(1+x*I, 1+y*I, Q.infinite(x) & Q.finite(y)) is False
assert is_eq(x, S(0), assumptions=Q.zero(x))
assert is_eq(x, S(0), assumptions=~Q.zero(x)) is False
assert is_eq(x, S(0), assumptions=Q.nonzero(x)) is False
assert is_neq(x, S(0), assumptions=Q.zero(x)) is False
assert is_neq(x, S(0), assumptions=~Q.zero(x))
assert is_neq(x, S(0), assumptions=Q.nonzero(x))
# test registration
class PowTest(Expr):
def __new__(cls, base, exp):
return Basic.__new__(cls, _sympify(base), _sympify(exp))
@dispatch(PowTest, PowTest)
def _eval_is_eq(lhs, rhs):
if type(lhs) == PowTest and type(rhs) == PowTest:
return fuzzy_and([is_eq(lhs.args[0], rhs.args[0]), is_eq(lhs.args[1], rhs.args[1])])
assert is_eq(PowTest(3, 4), PowTest(3,4))
assert is_eq(PowTest(3, 4), _sympify(4)) is None
assert is_neq(PowTest(3, 4), PowTest(3,7))
def test_is_ge_le():
# test assumptions
assert is_ge(x, S(0), Q.nonnegative(x)) is True
assert is_ge(x, S(0), Q.negative(x)) is False
# test registration
class PowTest(Expr):
def __new__(cls, base, exp):
return Basic.__new__(cls, _sympify(base), _sympify(exp))
@dispatch(PowTest, PowTest)
def _eval_is_ge(lhs, rhs):
if type(lhs) == PowTest and type(rhs) == PowTest:
return fuzzy_and([is_ge(lhs.args[0], rhs.args[0]), is_ge(lhs.args[1], rhs.args[1])])
assert is_ge(PowTest(3, 9), PowTest(3,2))
assert is_gt(PowTest(3, 9), PowTest(3,2))
assert is_le(PowTest(3, 2), PowTest(3,9))
assert is_lt(PowTest(3, 2), PowTest(3,9))
def test_weak_strict():
for func in (Eq, Ne):
eq = func(x, 1)
assert eq.strict == eq.weak == eq
eq = Gt(x, 1)
assert eq.weak == Ge(x, 1)
assert eq.strict == eq
eq = Lt(x, 1)
assert eq.weak == Le(x, 1)
assert eq.strict == eq
eq = Ge(x, 1)
assert eq.strict == Gt(x, 1)
assert eq.weak == eq
eq = Le(x, 1)
assert eq.strict == Lt(x, 1)
assert eq.weak == eq
|
8549b2e17c94fc0016da9e3dc22b4fe204c04aa0d7cbda3b2c91cefab6127b71 | from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.function import (Function, Lambda)
from sympy.core.mul import Mul
from sympy.core.numbers import (Float, I, Integer, Rational, pi, oo)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
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.logic.boolalg import (false, Or, true, Xor)
from sympy.matrices.dense import Matrix
from sympy.parsing.sympy_parser import null
from sympy.polys.polytools import Poly
from sympy.printing.repr import srepr
from sympy.sets.fancysets import Range
from sympy.sets.sets import Interval
from sympy.abc import x, y
from sympy.core.sympify import (sympify, _sympify, SympifyError, kernS,
CantSympify, converter)
from sympy.core.decorators import _sympifyit
from sympy.external import import_module
from sympy.testing.pytest import raises, XFAIL, skip, warns_deprecated_sympy
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.geometry import Point, Line
from sympy.functions.combinatorial.factorials import factorial, factorial2
from sympy.abc import _clash, _clash1, _clash2
from sympy.external.gmpy import HAS_GMPY
from sympy.sets import FiniteSet, EmptySet
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
import mpmath
from collections import defaultdict, OrderedDict
from mpmath.rational import mpq
numpy = import_module('numpy')
def test_issue_3538():
v = sympify("exp(x)")
assert v == exp(x)
assert type(v) == type(exp(x))
assert str(type(v)) == str(type(exp(x)))
def test_sympify1():
assert sympify("x") == Symbol("x")
assert sympify(" x") == Symbol("x")
assert sympify(" x ") == Symbol("x")
# issue 4877
assert sympify('--.5') == 0.5
assert sympify('-1/2') == -S.Half
assert sympify('-+--.5') == -0.5
assert sympify('-.[3]') == Rational(-1, 3)
assert sympify('.[3]') == Rational(1, 3)
assert sympify('+.[3]') == Rational(1, 3)
assert sympify('+0.[3]*10**-2') == Rational(1, 300)
assert sympify('.[052631578947368421]') == Rational(1, 19)
assert sympify('.0[526315789473684210]') == Rational(1, 19)
assert sympify('.034[56]') == Rational(1711, 49500)
# options to make reals into rationals
assert sympify('1.22[345]', rational=True) == \
1 + Rational(22, 100) + Rational(345, 99900)
assert sympify('2/2.6', rational=True) == Rational(10, 13)
assert sympify('2.6/2', rational=True) == Rational(13, 10)
assert sympify('2.6e2/17', rational=True) == Rational(260, 17)
assert sympify('2.6e+2/17', rational=True) == Rational(260, 17)
assert sympify('2.6e-2/17', rational=True) == Rational(26, 17000)
assert sympify('2.1+3/4', rational=True) == \
Rational(21, 10) + Rational(3, 4)
assert sympify('2.234456', rational=True) == Rational(279307, 125000)
assert sympify('2.234456e23', rational=True) == 223445600000000000000000
assert sympify('2.234456e-23', rational=True) == \
Rational(279307, 12500000000000000000000000000)
assert sympify('-2.234456e-23', rational=True) == \
Rational(-279307, 12500000000000000000000000000)
assert sympify('12345678901/17', rational=True) == \
Rational(12345678901, 17)
assert sympify('1/.3 + x', rational=True) == Rational(10, 3) + x
# make sure longs in fractions work
assert sympify('222222222222/11111111111') == \
Rational(222222222222, 11111111111)
# ... even if they come from repetend notation
assert sympify('1/.2[123456789012]') == Rational(333333333333, 70781892967)
# ... or from high precision reals
assert sympify('.1234567890123456', rational=True) == \
Rational(19290123283179, 156250000000000)
def test_sympify_Fraction():
try:
import fractions
except ImportError:
pass
else:
value = sympify(fractions.Fraction(101, 127))
assert value == Rational(101, 127) and type(value) is Rational
def test_sympify_gmpy():
if HAS_GMPY:
if HAS_GMPY == 2:
import gmpy2 as gmpy
elif HAS_GMPY == 1:
import gmpy
value = sympify(gmpy.mpz(1000001))
assert value == Integer(1000001) and type(value) is Integer
value = sympify(gmpy.mpq(101, 127))
assert value == Rational(101, 127) and type(value) is Rational
@conserve_mpmath_dps
def test_sympify_mpmath():
value = sympify(mpmath.mpf(1.0))
assert value == Float(1.0) and type(value) is Float
mpmath.mp.dps = 12
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-12")) == True
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-13")) == False
mpmath.mp.dps = 6
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-5")) == True
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-6")) == False
mpmath.mp.dps = 15
assert sympify(mpmath.mpc(1.0 + 2.0j)) == Float(1.0) + Float(2.0)*I
assert sympify(mpq(1, 2)) == S.Half
def test_sympify2():
class A:
def _sympy_(self):
return Symbol("x")**3
a = A()
assert _sympify(a) == x**3
assert sympify(a) == x**3
assert a == x**3
def test_sympify3():
assert sympify("x**3") == x**3
assert sympify("x^3") == x**3
assert sympify("1/2") == Integer(1)/2
raises(SympifyError, lambda: _sympify('x**3'))
raises(SympifyError, lambda: _sympify('1/2'))
def test_sympify_keywords():
raises(SympifyError, lambda: sympify('if'))
raises(SympifyError, lambda: sympify('for'))
raises(SympifyError, lambda: sympify('while'))
raises(SympifyError, lambda: sympify('lambda'))
def test_sympify_float():
assert sympify("1e-64") != 0
assert sympify("1e-20000") != 0
def test_sympify_bool():
assert sympify(True) is true
assert sympify(False) is false
def test_sympyify_iterables():
ans = [Rational(3, 10), Rational(1, 5)]
assert sympify(['.3', '.2'], rational=True) == ans
assert sympify(dict(x=0, y=1)) == {x: 0, y: 1}
assert sympify(['1', '2', ['3', '4']]) == [S(1), S(2), [S(3), S(4)]]
@XFAIL
def test_issue_16772():
# because there is a converter for tuple, the
# args are only sympified without the flags being passed
# along; list, on the other hand, is not converted
# with a converter so its args are traversed later
ans = [Rational(3, 10), Rational(1, 5)]
assert sympify(tuple(['.3', '.2']), rational=True) == Tuple(*ans)
def test_issue_16859():
class no(float, CantSympify):
pass
raises(SympifyError, lambda: sympify(no(1.2)))
def test_sympify4():
class A:
def _sympy_(self):
return Symbol("x")
a = A()
assert _sympify(a)**3 == x**3
assert sympify(a)**3 == x**3
assert a == x
def test_sympify_text():
assert sympify('some') == Symbol('some')
assert sympify('core') == Symbol('core')
assert sympify('True') is True
assert sympify('False') is False
assert sympify('Poly') == Poly
assert sympify('sin') == sin
def test_sympify_function():
assert sympify('factor(x**2-1, x)') == -(1 - x)*(x + 1)
assert sympify('sin(pi/2)*cos(pi)') == -Integer(1)
def test_sympify_poly():
p = Poly(x**2 + x + 1, x)
assert _sympify(p) is p
assert sympify(p) is p
def test_sympify_factorial():
assert sympify('x!') == factorial(x)
assert sympify('(x+1)!') == factorial(x + 1)
assert sympify('(1 + y*(x + 1))!') == factorial(1 + y*(x + 1))
assert sympify('(1 + y*(x + 1)!)^2') == (1 + y*factorial(x + 1))**2
assert sympify('y*x!') == y*factorial(x)
assert sympify('x!!') == factorial2(x)
assert sympify('(x+1)!!') == factorial2(x + 1)
assert sympify('(1 + y*(x + 1))!!') == factorial2(1 + y*(x + 1))
assert sympify('(1 + y*(x + 1)!!)^2') == (1 + y*factorial2(x + 1))**2
assert sympify('y*x!!') == y*factorial2(x)
assert sympify('factorial2(x)!') == factorial(factorial2(x))
raises(SympifyError, lambda: sympify("+!!"))
raises(SympifyError, lambda: sympify(")!!"))
raises(SympifyError, lambda: sympify("!"))
raises(SympifyError, lambda: sympify("(!)"))
raises(SympifyError, lambda: sympify("x!!!"))
def test_issue_3595():
assert sympify("a_") == Symbol("a_")
assert sympify("_a") == Symbol("_a")
def test_lambda():
x = Symbol('x')
assert sympify('lambda: 1') == Lambda((), 1)
assert sympify('lambda x: x') == Lambda(x, x)
assert sympify('lambda x: 2*x') == Lambda(x, 2*x)
assert sympify('lambda x, y: 2*x+y') == Lambda((x, y), 2*x + y)
def test_lambda_raises():
raises(SympifyError, lambda: sympify("lambda *args: args")) # args argument error
raises(SympifyError, lambda: sympify("lambda **kwargs: kwargs[0]")) # kwargs argument error
raises(SympifyError, lambda: sympify("lambda x = 1: x")) # Keyword argument error
with raises(SympifyError):
_sympify('lambda: 1')
def test_sympify_raises():
raises(SympifyError, lambda: sympify("fx)"))
class A:
def __str__(self):
return 'x'
with warns_deprecated_sympy():
assert sympify(A()) == Symbol('x')
def test__sympify():
x = Symbol('x')
f = Function('f')
# positive _sympify
assert _sympify(x) is x
assert _sympify(1) == Integer(1)
assert _sympify(0.5) == Float("0.5")
assert _sympify(1 + 1j) == 1.0 + I*1.0
# Function f is not Basic and can't sympify to Basic. We allow it to pass
# with sympify but not with _sympify.
# https://github.com/sympy/sympy/issues/20124
assert sympify(f) is f
raises(SympifyError, lambda: _sympify(f))
class A:
def _sympy_(self):
return Integer(5)
a = A()
assert _sympify(a) == Integer(5)
# negative _sympify
raises(SympifyError, lambda: _sympify('1'))
raises(SympifyError, lambda: _sympify([1, 2, 3]))
def test_sympifyit():
x = Symbol('x')
y = Symbol('y')
@_sympifyit('b', NotImplemented)
def add(a, b):
return a + b
assert add(x, 1) == x + 1
assert add(x, 0.5) == x + Float('0.5')
assert add(x, y) == x + y
assert add(x, '1') == NotImplemented
@_sympifyit('b')
def add_raises(a, b):
return a + b
assert add_raises(x, 1) == x + 1
assert add_raises(x, 0.5) == x + Float('0.5')
assert add_raises(x, y) == x + y
raises(SympifyError, lambda: add_raises(x, '1'))
def test_int_float():
class F1_1:
def __float__(self):
return 1.1
class F1_1b:
"""
This class is still a float, even though it also implements __int__().
"""
def __float__(self):
return 1.1
def __int__(self):
return 1
class F1_1c:
"""
This class is still a float, because it implements _sympy_()
"""
def __float__(self):
return 1.1
def __int__(self):
return 1
def _sympy_(self):
return Float(1.1)
class I5:
def __int__(self):
return 5
class I5b:
"""
This class implements both __int__() and __float__(), so it will be
treated as Float in SymPy. One could change this behavior, by using
float(a) == int(a), but deciding that integer-valued floats represent
exact numbers is arbitrary and often not correct, so we do not do it.
If, in the future, we decide to do it anyway, the tests for I5b need to
be changed.
"""
def __float__(self):
return 5.0
def __int__(self):
return 5
class I5c:
"""
This class implements both __int__() and __float__(), but also
a _sympy_() method, so it will be Integer.
"""
def __float__(self):
return 5.0
def __int__(self):
return 5
def _sympy_(self):
return Integer(5)
i5 = I5()
i5b = I5b()
i5c = I5c()
f1_1 = F1_1()
f1_1b = F1_1b()
f1_1c = F1_1c()
assert sympify(i5) == 5
assert isinstance(sympify(i5), Integer)
assert sympify(i5b) == 5.0
assert isinstance(sympify(i5b), Float)
assert sympify(i5c) == 5
assert isinstance(sympify(i5c), Integer)
assert abs(sympify(f1_1) - 1.1) < 1e-5
assert abs(sympify(f1_1b) - 1.1) < 1e-5
assert abs(sympify(f1_1c) - 1.1) < 1e-5
assert _sympify(i5) == 5
assert isinstance(_sympify(i5), Integer)
assert _sympify(i5b) == 5.0
assert isinstance(_sympify(i5b), Float)
assert _sympify(i5c) == 5
assert isinstance(_sympify(i5c), Integer)
assert abs(_sympify(f1_1) - 1.1) < 1e-5
assert abs(_sympify(f1_1b) - 1.1) < 1e-5
assert abs(_sympify(f1_1c) - 1.1) < 1e-5
def test_evaluate_false():
cases = {
'2 + 3': Add(2, 3, evaluate=False),
'2**2 / 3': Mul(Pow(2, 2, evaluate=False), Pow(3, -1, evaluate=False), evaluate=False),
'2 + 3 * 5': Add(2, Mul(3, 5, evaluate=False), evaluate=False),
'2 - 3 * 5': Add(2, Mul(-1, Mul(3, 5,evaluate=False), evaluate=False), evaluate=False),
'1 / 3': Mul(1, Pow(3, -1, evaluate=False), evaluate=False),
'True | False': Or(True, False, evaluate=False),
'1 + 2 + 3 + 5*3 + integrate(x)': Add(1, 2, 3, Mul(5, 3, evaluate=False), x**2/2, evaluate=False),
'2 * 4 * 6 + 8': Add(Mul(2, 4, 6, evaluate=False), 8, evaluate=False),
'2 - 8 / 4': Add(2, Mul(-1, Mul(8, Pow(4, -1, evaluate=False), evaluate=False), evaluate=False), evaluate=False),
'2 - 2**2': Add(2, Mul(-1, Pow(2, 2, evaluate=False), evaluate=False), evaluate=False),
}
for case, result in cases.items():
assert sympify(case, evaluate=False) == result
def test_issue_4133():
a = sympify('Integer(4)')
assert a == Integer(4)
assert a.is_Integer
def test_issue_3982():
a = [3, 2.0]
assert sympify(a) == [Integer(3), Float(2.0)]
assert sympify(tuple(a)) == Tuple(Integer(3), Float(2.0))
assert sympify(set(a)) == FiniteSet(Integer(3), Float(2.0))
def test_S_sympify():
assert S(1)/2 == sympify(1)/2 == S.Half
assert (-2)**(S(1)/2) == sqrt(2)*I
def test_issue_4788():
assert srepr(S(1.0 + 0J)) == srepr(S(1.0)) == srepr(Float(1.0))
def test_issue_4798_None():
assert S(None) is None
def test_issue_3218():
assert sympify("x+\ny") == x + y
def test_issue_4988_builtins():
C = Symbol('C')
vars = {'C': C}
exp1 = sympify('C')
assert exp1 == C # Make sure it did not get mixed up with sympy.C
exp2 = sympify('C', vars)
assert exp2 == C # Make sure it did not get mixed up with sympy.C
def test_geometry():
p = sympify(Point(0, 1))
assert p == Point(0, 1) and isinstance(p, Point)
L = sympify(Line(p, (1, 0)))
assert L == Line((0, 1), (1, 0)) and isinstance(L, Line)
def test_kernS():
s = '-1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x)))'
# when 1497 is fixed, this no longer should pass: the expression
# should be unchanged
assert -1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) == -1
# sympification should not allow the constant to enter a Mul
# or else the structure can change dramatically
ss = kernS(s)
assert ss != -1 and ss.simplify() == -1
s = '-1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x)))'.replace(
'x', '_kern')
ss = kernS(s)
assert ss != -1 and ss.simplify() == -1
# issue 6687
assert (kernS('Interval(-1,-2 - 4*(-3))')
== Interval(-1, Add(-2, Mul(12, 1, evaluate=False), evaluate=False)))
assert kernS('_kern') == Symbol('_kern')
assert kernS('E**-(x)') == exp(-x)
e = 2*(x + y)*y
assert kernS(['2*(x + y)*y', ('2*(x + y)*y',)]) == [e, (e,)]
assert kernS('-(2*sin(x)**2 + 2*sin(x)*cos(x))*y/2') == \
-y*(2*sin(x)**2 + 2*sin(x)*cos(x))/2
# issue 15132
assert kernS('(1 - x)/(1 - x*(1-y))') == kernS('(1-x)/(1-(1-y)*x)')
assert kernS('(1-2**-(4+1)*(1-y)*x)') == (1 - x*(1 - y)/32)
assert kernS('(1-2**(4+1)*(1-y)*x)') == (1 - 32*x*(1 - y))
assert kernS('(1-2.*(1-y)*x)') == 1 - 2.*x*(1 - y)
one = kernS('x - (x - 1)')
assert one != 1 and one.expand() == 1
assert kernS("(2*x)/(x-1)") == 2*x/(x-1)
def test_issue_6540_6552():
assert S('[[1/3,2], (2/5,)]') == [[Rational(1, 3), 2], (Rational(2, 5),)]
assert S('[[2/6,2], (2/4,)]') == [[Rational(1, 3), 2], (S.Half,)]
assert S('[[[2*(1)]]]') == [[[2]]]
assert S('Matrix([2*(1)])') == Matrix([2])
def test_issue_6046():
assert str(S("Q & C", locals=_clash1)) == 'C & Q'
assert str(S('pi(x)', locals=_clash2)) == 'pi(x)'
locals = {}
exec("from sympy.abc import Q, C", locals)
assert str(S('C&Q', locals)) == 'C & Q'
# clash can act as Symbol or Function
assert str(S('pi(C, Q)', locals=_clash)) == 'pi(C, Q)'
assert len(S('pi + x', locals=_clash2).free_symbols) == 2
# but not both
raises(TypeError, lambda: S('pi + pi(x)', locals=_clash2))
assert all(set(i.values()) == {null} for i in (
_clash, _clash1, _clash2))
def test_issue_8821_highprec_from_str():
s = str(pi.evalf(128))
p = sympify(s)
assert Abs(sin(p)) < 1e-127
def test_issue_10295():
if not numpy:
skip("numpy not installed.")
A = numpy.array([[1, 3, -1],
[0, 1, 7]])
sA = S(A)
assert sA.shape == (2, 3)
for (ri, ci), val in numpy.ndenumerate(A):
assert sA[ri, ci] == val
B = numpy.array([-7, x, 3*y**2])
sB = S(B)
assert sB.shape == (3,)
assert B[0] == sB[0] == -7
assert B[1] == sB[1] == x
assert B[2] == sB[2] == 3*y**2
C = numpy.arange(0, 24)
C.resize(2,3,4)
sC = S(C)
assert sC[0, 0, 0].is_integer
assert sC[0, 0, 0] == 0
a1 = numpy.array([1, 2, 3])
a2 = numpy.array([i for i in range(24)])
a2.resize(2, 4, 3)
assert sympify(a1) == ImmutableDenseNDimArray([1, 2, 3])
assert sympify(a2) == ImmutableDenseNDimArray([i for i in range(24)], (2, 4, 3))
def test_Range():
# Only works in Python 3 where range returns a range type
assert sympify(range(10)) == Range(10)
assert _sympify(range(10)) == Range(10)
def test_sympify_set():
n = Symbol('n')
assert sympify({n}) == FiniteSet(n)
assert sympify(set()) == EmptySet
def test_sympify_numpy():
if not numpy:
skip('numpy not installed. Abort numpy tests.')
np = numpy
def equal(x, y):
return x == y and type(x) == type(y)
assert sympify(np.bool_(1)) is S(True)
try:
assert equal(
sympify(np.int_(1234567891234567891)), S(1234567891234567891))
assert equal(
sympify(np.intp(1234567891234567891)), S(1234567891234567891))
except OverflowError:
# May fail on 32-bit systems: Python int too large to convert to C long
pass
assert equal(sympify(np.intc(1234567891)), S(1234567891))
assert equal(sympify(np.int8(-123)), S(-123))
assert equal(sympify(np.int16(-12345)), S(-12345))
assert equal(sympify(np.int32(-1234567891)), S(-1234567891))
assert equal(
sympify(np.int64(-1234567891234567891)), S(-1234567891234567891))
assert equal(sympify(np.uint8(123)), S(123))
assert equal(sympify(np.uint16(12345)), S(12345))
assert equal(sympify(np.uint32(1234567891)), S(1234567891))
assert equal(
sympify(np.uint64(1234567891234567891)), S(1234567891234567891))
assert equal(sympify(np.float32(1.123456)), Float(1.123456, precision=24))
assert equal(sympify(np.float64(1.1234567891234)),
Float(1.1234567891234, precision=53))
# The exact precision of np.longdouble, npfloat128 and other extended
# precision dtypes is platform dependent.
ldprec = np.finfo(np.longdouble(1)).nmant + 1
assert equal(sympify(np.longdouble(1.123456789)),
Float(1.123456789, precision=ldprec))
assert equal(sympify(np.complex64(1 + 2j)), S(1.0 + 2.0*I))
assert equal(sympify(np.complex128(1 + 2j)), S(1.0 + 2.0*I))
lcprec = np.finfo(np.longcomplex(1)).nmant + 1
assert equal(sympify(np.longcomplex(1 + 2j)),
Float(1.0, precision=lcprec) + Float(2.0, precision=lcprec)*I)
#float96 does not exist on all platforms
if hasattr(np, 'float96'):
f96prec = np.finfo(np.float96(1)).nmant + 1
assert equal(sympify(np.float96(1.123456789)),
Float(1.123456789, precision=f96prec))
#float128 does not exist on all platforms
if hasattr(np, 'float128'):
f128prec = np.finfo(np.float128(1)).nmant + 1
assert equal(sympify(np.float128(1.123456789123)),
Float(1.123456789123, precision=f128prec))
@XFAIL
def test_sympify_rational_numbers_set():
ans = [Rational(3, 10), Rational(1, 5)]
assert sympify({'.3', '.2'}, rational=True) == FiniteSet(*ans)
def test_sympify_mro():
"""Tests the resolution order for classes that implement _sympy_"""
class a:
def _sympy_(self):
return Integer(1)
class b(a):
def _sympy_(self):
return Integer(2)
class c(a):
pass
assert sympify(a()) == Integer(1)
assert sympify(b()) == Integer(2)
assert sympify(c()) == Integer(1)
def test_sympify_converter():
"""Tests the resolution order for classes in converter"""
class a:
pass
class b(a):
pass
class c(a):
pass
converter[a] = lambda x: Integer(1)
converter[b] = lambda x: Integer(2)
assert sympify(a()) == Integer(1)
assert sympify(b()) == Integer(2)
assert sympify(c()) == Integer(1)
class MyInteger(Integer):
pass
if int in converter:
int_converter = converter[int]
else:
int_converter = None
try:
converter[int] = MyInteger
assert sympify(1) == MyInteger(1)
finally:
if int_converter is None:
del converter[int]
else:
converter[int] = int_converter
def test_issue_13924():
if not numpy:
skip("numpy not installed.")
a = sympify(numpy.array([1]))
assert isinstance(a, ImmutableDenseNDimArray)
assert a[0] == 1
def test_numpy_sympify_args():
# Issue 15098. Make sure sympify args work with numpy types (like numpy.str_)
if not numpy:
skip("numpy not installed.")
a = sympify(numpy.str_('a'))
assert type(a) is Symbol
assert a == Symbol('a')
class CustomSymbol(Symbol):
pass
a = sympify(numpy.str_('a'), {"Symbol": CustomSymbol})
assert isinstance(a, CustomSymbol)
a = sympify(numpy.str_('x^y'))
assert a == x**y
a = sympify(numpy.str_('x^y'), convert_xor=False)
assert a == Xor(x, y)
raises(SympifyError, lambda: sympify(numpy.str_('x'), strict=True))
a = sympify(numpy.str_('1.1'))
assert isinstance(a, Float)
assert a == 1.1
a = sympify(numpy.str_('1.1'), rational=True)
assert isinstance(a, Rational)
assert a == Rational(11, 10)
a = sympify(numpy.str_('x + x'))
assert isinstance(a, Mul)
assert a == 2*x
a = sympify(numpy.str_('x + x'), evaluate=False)
assert isinstance(a, Add)
assert a == Add(x, x, evaluate=False)
def test_issue_5939():
a = Symbol('a')
b = Symbol('b')
assert sympify('''a+\nb''') == a + b
def test_issue_16759():
d = sympify({.5: 1})
assert S.Half not in d
assert Float(.5) in d
assert d[.5] is S.One
d = sympify(OrderedDict({.5: 1}))
assert S.Half not in d
assert Float(.5) in d
assert d[.5] is S.One
d = sympify(defaultdict(int, {.5: 1}))
assert S.Half not in d
assert Float(.5) in d
assert d[.5] is S.One
def test_issue_17811():
a = Function('a')
assert sympify('a(x)*5', evaluate=False) == Mul(a(x), 5, evaluate=False)
def test_issue_8439():
assert sympify(float('inf')) == oo
assert x + float('inf') == x + oo
assert S(float('inf')) == oo
def test_issue_14706():
if not numpy:
skip("numpy not installed.")
z1 = numpy.zeros((1, 1), dtype=numpy.float64)
z2 = numpy.zeros((2, 2), dtype=numpy.float64)
z3 = numpy.zeros((), dtype=numpy.float64)
y1 = numpy.ones((1, 1), dtype=numpy.float64)
y2 = numpy.ones((2, 2), dtype=numpy.float64)
y3 = numpy.ones((), dtype=numpy.float64)
assert numpy.all(x + z1 == numpy.full((1, 1), x))
assert numpy.all(x + z2 == numpy.full((2, 2), x))
assert numpy.all(z1 + x == numpy.full((1, 1), x))
assert numpy.all(z2 + x == numpy.full((2, 2), x))
for z in [z3,
numpy.int64(0),
numpy.float64(0),
numpy.complex64(0)]:
assert x + z == x
assert z + x == x
assert isinstance(x + z, Symbol)
assert isinstance(z + x, Symbol)
# If these tests fail, then it means that numpy has finally
# fixed the issue of scalar conversion for rank>0 arrays
# which is mentioned in numpy/numpy#10404. In that case,
# some changes have to be made in sympify.py.
# Note: For future reference, for anyone who takes up this
# issue when numpy has finally fixed their side of the problem,
# the changes for this temporary fix were introduced in PR 18651
assert numpy.all(x + y1 == numpy.full((1, 1), x + 1.0))
assert numpy.all(x + y2 == numpy.full((2, 2), x + 1.0))
assert numpy.all(y1 + x == numpy.full((1, 1), x + 1.0))
assert numpy.all(y2 + x == numpy.full((2, 2), x + 1.0))
for y_ in [y3,
numpy.int64(1),
numpy.float64(1),
numpy.complex64(1)]:
assert x + y_ == y_ + x
assert isinstance(x + y_, Add)
assert isinstance(y_ + x, Add)
assert x + numpy.array(x) == 2 * x
assert x + numpy.array([x]) == numpy.array([2*x], dtype=object)
assert sympify(numpy.array([1])) == ImmutableDenseNDimArray([1], 1)
assert sympify(numpy.array([[[1]]])) == ImmutableDenseNDimArray([1], (1, 1, 1))
assert sympify(z1) == ImmutableDenseNDimArray([0.0], (1, 1))
assert sympify(z2) == ImmutableDenseNDimArray([0.0, 0.0, 0.0, 0.0], (2, 2))
assert sympify(z3) == ImmutableDenseNDimArray([0.0], ())
assert sympify(z3, strict=True) == 0.0
raises(SympifyError, lambda: sympify(numpy.array([1]), strict=True))
raises(SympifyError, lambda: sympify(z1, strict=True))
raises(SympifyError, lambda: sympify(z2, strict=True))
def test_issue_21536():
#test to check evaluate=False in case of iterable input
u = sympify("x+3*x+2", evaluate=False)
v = sympify("2*x+4*x+2+4", evaluate=False)
assert u.is_Add and set(u.args) == {x, 3*x, 2}
assert v.is_Add and set(v.args) == {2*x, 4*x, 2, 4}
assert sympify(["x+3*x+2", "2*x+4*x+2+4"], evaluate=False) == [u, v]
#test to check evaluate=True in case of iterable input
u = sympify("x+3*x+2", evaluate=True)
v = sympify("2*x+4*x+2+4", evaluate=True)
assert u.is_Add and set(u.args) == {4*x, 2}
assert v.is_Add and set(v.args) == {6*x, 6}
assert sympify(["x+3*x+2", "2*x+4*x+2+4"], evaluate=True) == [u, v]
#test to check evaluate with no input in case of iterable input
u = sympify("x+3*x+2")
v = sympify("2*x+4*x+2+4")
assert u.is_Add and set(u.args) == {4*x, 2}
assert v.is_Add and set(v.args) == {6*x, 6}
assert sympify(["x+3*x+2", "2*x+4*x+2+4"]) == [u, v]
|
4a13ad6b5f3173e8c59529e79478725ac0ee98bc9046bf756220b58ff80bf52c | import math
from sympy.concrete.products import (Product, product)
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.evalf import N
from sympy.core.function import (Function, nfloat)
from sympy.core.mul import Mul
from sympy.core import (GoldenRatio)
from sympy.core.numbers import (AlgebraicNumber, E, Float, I, Rational,
oo, zoo, nan, pi)
from sympy.core.power import Pow
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.combinatorial.numbers import fibonacci
from sympy.functions.elementary.complexes import (Abs, re, im)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.hyperbolic import (acosh, cosh)
from sympy.functions.elementary.integers import (ceiling, floor)
from sympy.functions.elementary.miscellaneous import (Max, sqrt)
from sympy.functions.elementary.trigonometric import (acos, atan, cos, sin, tan)
from sympy.integrals.integrals import (Integral, integrate)
from sympy.polys.polytools import factor
from sympy.polys.rootoftools import CRootOf
from sympy.polys.specialpolys import cyclotomic_poly
from sympy.printing import srepr
from sympy.printing.str import sstr
from sympy.simplify.simplify import simplify
from sympy.core.numbers import comp
from sympy.core.evalf import (complex_accuracy, PrecisionExhausted,
scaled_zero, get_integer_part, as_mpmath, evalf, _evalf_with_bounded_error)
from mpmath import inf, ninf, make_mpc
from mpmath.libmp.libmpf import from_float, fzero
from sympy.core.expr import unchanged
from sympy.testing.pytest import raises, XFAIL
from sympy.abc import n, x, y
def NS(e, n=15, **options):
return sstr(sympify(e).evalf(n, **options), full_prec=True)
def test_evalf_helpers():
from mpmath.libmp import finf
assert complex_accuracy((from_float(2.0), None, 35, None)) == 35
assert complex_accuracy((from_float(2.0), from_float(10.0), 35, 100)) == 37
assert complex_accuracy(
(from_float(2.0), from_float(1000.0), 35, 100)) == 43
assert complex_accuracy((from_float(2.0), from_float(10.0), 100, 35)) == 35
assert complex_accuracy(
(from_float(2.0), from_float(1000.0), 100, 35)) == 35
assert complex_accuracy(finf) == math.inf
assert complex_accuracy(zoo) == math.inf
raises(ValueError, lambda: get_integer_part(zoo, 1, {}))
def test_evalf_basic():
assert NS('pi', 15) == '3.14159265358979'
assert NS('2/3', 10) == '0.6666666667'
assert NS('355/113-pi', 6) == '2.66764e-7'
assert NS('16*atan(1/5)-4*atan(1/239)', 15) == '3.14159265358979'
def test_cancellation():
assert NS(Add(pi, Rational(1, 10**1000), -pi, evaluate=False), 15,
maxn=1200) == '1.00000000000000e-1000'
def test_evalf_powers():
assert NS('pi**(10**20)', 10) == '1.339148777e+49714987269413385435'
assert NS(pi**(10**100), 10) == ('4.946362032e+4971498726941338543512682882'
'9089887365167832438044244613405349992494711208'
'95526746555473864642912223')
assert NS('2**(1/10**50)', 15) == '1.00000000000000'
assert NS('2**(1/10**50)-1', 15) == '6.93147180559945e-51'
# Evaluation of Rump's ill-conditioned polynomial
def test_evalf_rump():
a = 1335*y**6/4 + x**2*(11*x**2*y**2 - y**6 - 121*y**4 - 2) + 11*y**8/2 + x/(2*y)
assert NS(a, 15, subs={x: 77617, y: 33096}) == '-0.827396059946821'
def test_evalf_complex():
assert NS('2*sqrt(pi)*I', 10) == '3.544907702*I'
assert NS('3+3*I', 15) == '3.00000000000000 + 3.00000000000000*I'
assert NS('E+pi*I', 15) == '2.71828182845905 + 3.14159265358979*I'
assert NS('pi * (3+4*I)', 15) == '9.42477796076938 + 12.5663706143592*I'
assert NS('I*(2+I)', 15) == '-1.00000000000000 + 2.00000000000000*I'
@XFAIL
def test_evalf_complex_bug():
assert NS('(pi+E*I)*(E+pi*I)', 15) in ('0.e-15 + 17.25866050002*I',
'0.e-17 + 17.25866050002*I', '-0.e-17 + 17.25866050002*I')
def test_evalf_complex_powers():
assert NS('(E+pi*I)**100000000000000000') == \
'-3.58896782867793e+61850354284995199 + 4.58581754997159e+61850354284995199*I'
# XXX: rewrite if a+a*I simplification introduced in SymPy
#assert NS('(pi + pi*I)**2') in ('0.e-15 + 19.7392088021787*I', '0.e-16 + 19.7392088021787*I')
assert NS('(pi + pi*I)**2', chop=True) == '19.7392088021787*I'
assert NS(
'(pi + 1/10**8 + pi*I)**2') == '6.2831853e-8 + 19.7392088650106*I'
assert NS('(pi + 1/10**12 + pi*I)**2') == '6.283e-12 + 19.7392088021850*I'
assert NS('(pi + pi*I)**4', chop=True) == '-389.636364136010'
assert NS(
'(pi + 1/10**8 + pi*I)**4') == '-389.636366616512 + 2.4805021e-6*I'
assert NS('(pi + 1/10**12 + pi*I)**4') == '-389.636364136258 + 2.481e-10*I'
assert NS(
'(10000*pi + 10000*pi*I)**4', chop=True) == '-3.89636364136010e+18'
@XFAIL
def test_evalf_complex_powers_bug():
assert NS('(pi + pi*I)**4') == '-389.63636413601 + 0.e-14*I'
def test_evalf_exponentiation():
assert NS(sqrt(-pi)) == '1.77245385090552*I'
assert NS(Pow(pi*I, Rational(
1, 2), evaluate=False)) == '1.25331413731550 + 1.25331413731550*I'
assert NS(pi**I) == '0.413292116101594 + 0.910598499212615*I'
assert NS(pi**(E + I/3)) == '20.8438653991931 + 8.36343473930031*I'
assert NS((pi + I/3)**(E + I/3)) == '17.2442906093590 + 13.6839376767037*I'
assert NS(exp(pi)) == '23.1406926327793'
assert NS(exp(pi + E*I)) == '-21.0981542849657 + 9.50576358282422*I'
assert NS(pi**pi) == '36.4621596072079'
assert NS((-pi)**pi) == '-32.9138577418939 - 15.6897116534332*I'
assert NS((-pi)**(-pi)) == '-0.0247567717232697 + 0.0118013091280262*I'
# An example from Smith, "Multiple Precision Complex Arithmetic and Functions"
def test_evalf_complex_cancellation():
A = Rational('63287/100000')
B = Rational('52498/100000')
C = Rational('69301/100000')
D = Rational('83542/100000')
F = Rational('2231321613/2500000000')
# XXX: the number of returned mantissa digits in the real part could
# change with the implementation. What matters is that the returned digits are
# correct; those that are showing now are correct.
# >>> ((A+B*I)*(C+D*I)).expand()
# 64471/10000000000 + 2231321613*I/2500000000
# >>> 2231321613*4
# 8925286452L
assert NS((A + B*I)*(C + D*I), 6) == '6.44710e-6 + 0.892529*I'
assert NS((A + B*I)*(C + D*I), 10) == '6.447100000e-6 + 0.8925286452*I'
assert NS((A + B*I)*(
C + D*I) - F*I, 5) in ('6.4471e-6 + 0.e-14*I', '6.4471e-6 - 0.e-14*I')
def test_evalf_logs():
assert NS("log(3+pi*I)", 15) == '1.46877619736226 + 0.808448792630022*I'
assert NS("log(pi*I)", 15) == '1.14472988584940 + 1.57079632679490*I'
assert NS('log(-1 + 0.00001)', 2) == '-1.0e-5 + 3.1*I'
assert NS('log(100, 10, evaluate=False)', 15) == '2.00000000000000'
assert NS('-2*I*log(-(-1)**(S(1)/9))', 15) == '-5.58505360638185'
def test_evalf_trig():
assert NS('sin(1)', 15) == '0.841470984807897'
assert NS('cos(1)', 15) == '0.540302305868140'
assert NS('sin(10**-6)', 15) == '9.99999999999833e-7'
assert NS('cos(10**-6)', 15) == '0.999999999999500'
assert NS('sin(E*10**100)', 15) == '0.409160531722613'
# Some input near roots
assert NS(sin(exp(pi*sqrt(163))*pi), 15) == '-2.35596641936785e-12'
assert NS(sin(pi*10**100 + Rational(7, 10**5), evaluate=False), 15, maxn=120) == \
'6.99999999428333e-5'
assert NS(sin(Rational(7, 10**5), evaluate=False), 15) == \
'6.99999999428333e-5'
# Check detection of various false identities
def test_evalf_near_integers():
# Binet's formula
f = lambda n: ((1 + sqrt(5))**n)/(2**n * sqrt(5))
assert NS(f(5000) - fibonacci(5000), 10, maxn=1500) == '5.156009964e-1046'
# Some near-integer identities from
# http://mathworld.wolfram.com/AlmostInteger.html
assert NS('sin(2017*2**(1/5))', 15) == '-1.00000000000000'
assert NS('sin(2017*2**(1/5))', 20) == '-0.99999999999999997857'
assert NS('1+sin(2017*2**(1/5))', 15) == '2.14322287389390e-17'
assert NS('45 - 613*E/37 + 35/991', 15) == '6.03764498766326e-11'
def test_evalf_ramanujan():
assert NS(exp(pi*sqrt(163)) - 640320**3 - 744, 10) == '-7.499274028e-13'
# A related identity
A = 262537412640768744*exp(-pi*sqrt(163))
B = 196884*exp(-2*pi*sqrt(163))
C = 103378831900730205293632*exp(-3*pi*sqrt(163))
assert NS(1 - A - B + C, 10) == '1.613679005e-59'
# Input that for various reasons have failed at some point
def test_evalf_bugs():
assert NS(sin(1) + exp(-10**10), 10) == NS(sin(1), 10)
assert NS(exp(10**10) + sin(1), 10) == NS(exp(10**10), 10)
assert NS('expand_log(log(1+1/10**50))', 20) == '1.0000000000000000000e-50'
assert NS('log(10**100,10)', 10) == '100.0000000'
assert NS('log(2)', 10) == '0.6931471806'
assert NS(
'(sin(x)-x)/x**3', 15, subs={x: '1/10**50'}) == '-0.166666666666667'
assert NS(sin(1) + Rational(
1, 10**100)*I, 15) == '0.841470984807897 + 1.00000000000000e-100*I'
assert x.evalf() == x
assert NS((1 + I)**2*I, 6) == '-2.00000'
d = {n: (
-1)**Rational(6, 7), y: (-1)**Rational(4, 7), x: (-1)**Rational(2, 7)}
assert NS((x*(1 + y*(1 + n))).subs(d).evalf(), 6) == '0.346011 + 0.433884*I'
assert NS(((-I - sqrt(2)*I)**2).evalf()) == '-5.82842712474619'
assert NS((1 + I)**2*I, 15) == '-2.00000000000000'
# issue 4758 (1/2):
assert NS(pi.evalf(69) - pi) == '-4.43863937855894e-71'
# issue 4758 (2/2): With the bug present, this still only fails if the
# terms are in the order given here. This is not generally the case,
# because the order depends on the hashes of the terms.
assert NS(20 - 5008329267844*n**25 - 477638700*n**37 - 19*n,
subs={n: .01}) == '19.8100000000000'
assert NS(((x - 1)*(1 - x)**1000).n()
) == '(1.00000000000000 - x)**1000*(x - 1.00000000000000)'
assert NS((-x).n()) == '-x'
assert NS((-2*x).n()) == '-2.00000000000000*x'
assert NS((-2*x*y).n()) == '-2.00000000000000*x*y'
assert cos(x).n(subs={x: 1+I}) == cos(x).subs(x, 1+I).n()
# issue 6660. Also NaN != mpmath.nan
# In this order:
# 0*nan, 0/nan, 0*inf, 0/inf
# 0+nan, 0-nan, 0+inf, 0-inf
# >>> n = Some Number
# n*nan, n/nan, n*inf, n/inf
# n+nan, n-nan, n+inf, n-inf
assert (0*E**(oo)).n() is S.NaN
assert (0/E**(oo)).n() is S.Zero
assert (0+E**(oo)).n() is S.Infinity
assert (0-E**(oo)).n() is S.NegativeInfinity
assert (5*E**(oo)).n() is S.Infinity
assert (5/E**(oo)).n() is S.Zero
assert (5+E**(oo)).n() is S.Infinity
assert (5-E**(oo)).n() is S.NegativeInfinity
#issue 7416
assert as_mpmath(0.0, 10, {'chop': True}) == 0
#issue 5412
assert ((oo*I).n() == S.Infinity*I)
assert ((oo+oo*I).n() == S.Infinity + S.Infinity*I)
#issue 11518
assert NS(2*x**2.5, 5) == '2.0000*x**2.5000'
#issue 13076
assert NS(Mul(Max(0, y), x, evaluate=False).evalf()) == 'x*Max(0, y)'
#issue 18516
assert NS(log(S(3273390607896141870013189696827599152216642046043064789483291368096133796404674554883270092325904157150886684127560071009217256545885393053328527589376)/36360291795869936842385267079543319118023385026001623040346035832580600191583895484198508262979388783308179702534403855752855931517013066142992430916562025780021771247847643450125342836565813209972590371590152578728008385990139795377610001).evalf(15, chop=True)) == '-oo'
def test_evalf_integer_parts():
a = floor(log(8)/log(2) - exp(-1000), evaluate=False)
b = floor(log(8)/log(2), evaluate=False)
assert a.evalf() == 3.0
assert b.evalf() == 3.0
# equals, as a fallback, can still fail but it might succeed as here
assert ceiling(10*(sin(1)**2 + cos(1)**2)) == 10
assert int(floor(factorial(50)/E, evaluate=False).evalf(70)) == \
int(11188719610782480504630258070757734324011354208865721592720336800)
assert int(ceiling(factorial(50)/E, evaluate=False).evalf(70)) == \
int(11188719610782480504630258070757734324011354208865721592720336801)
assert int(floor(GoldenRatio**999 / sqrt(5) + S.Half)
.evalf(1000)) == fibonacci(999)
assert int(floor(GoldenRatio**1000 / sqrt(5) + S.Half)
.evalf(1000)) == fibonacci(1000)
assert ceiling(x).evalf(subs={x: 3}) == 3.0
assert ceiling(x).evalf(subs={x: 3*I}) == 3.0*I
assert ceiling(x).evalf(subs={x: 2 + 3*I}) == 2.0 + 3.0*I
assert ceiling(x).evalf(subs={x: 3.}) == 3.0
assert ceiling(x).evalf(subs={x: 3.*I}) == 3.0*I
assert ceiling(x).evalf(subs={x: 2. + 3*I}) == 2.0 + 3.0*I
assert float((floor(1.5, evaluate=False)+1/9).evalf()) == 1 + 1/9
assert float((floor(0.5, evaluate=False)+20).evalf()) == 20
# issue 19991
n = 1169809367327212570704813632106852886389036911
r = 744723773141314414542111064094745678855643068
assert floor(n / (pi / 2)) == r
assert floor(80782 * sqrt(2)) == 114242
# issue 20076
assert 260515 - floor(260515/pi + 1/2) * pi == atan(tan(260515))
def test_evalf_trig_zero_detection():
a = sin(160*pi, evaluate=False)
t = a.evalf(maxn=100)
assert abs(t) < 1e-100
assert t._prec < 2
assert a.evalf(chop=True) == 0
raises(PrecisionExhausted, lambda: a.evalf(strict=True))
def test_evalf_sum():
assert Sum(n,(n,1,2)).evalf() == 3.
assert Sum(n,(n,1,2)).doit().evalf() == 3.
# the next test should return instantly
assert Sum(1/n,(n,1,2)).evalf() == 1.5
# issue 8219
assert Sum(E/factorial(n), (n, 0, oo)).evalf() == (E*E).evalf()
# issue 8254
assert Sum(2**n*n/factorial(n), (n, 0, oo)).evalf() == (2*E*E).evalf()
# issue 8411
s = Sum(1/x**2, (x, 100, oo))
assert s.n() == s.doit().n()
def test_evalf_divergent_series():
raises(ValueError, lambda: Sum(1/n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum(n/(n**2 + 1), (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum((-1)**n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum((-1)**n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum(n**2, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum(2**n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum((-2)**n, (n, 1, oo)).evalf())
raises(ValueError, lambda: Sum((2*n + 3)/(3*n**2 + 4), (n, 0, oo)).evalf())
raises(ValueError, lambda: Sum((0.5*n**3)/(n**4 + 1), (n, 0, oo)).evalf())
def test_evalf_product():
assert Product(n, (n, 1, 10)).evalf() == 3628800.
assert comp(Product(1 - S.Half**2/n**2, (n, 1, oo)).n(5), 0.63662)
assert Product(n, (n, -1, 3)).evalf() == 0
def test_evalf_py_methods():
assert abs(float(pi + 1) - 4.1415926535897932) < 1e-10
assert abs(complex(pi + 1) - 4.1415926535897932) < 1e-10
assert abs(
complex(pi + E*I) - (3.1415926535897931 + 2.7182818284590451j)) < 1e-10
raises(TypeError, lambda: float(pi + x))
def test_evalf_power_subs_bugs():
assert (x**2).evalf(subs={x: 0}) == 0
assert sqrt(x).evalf(subs={x: 0}) == 0
assert (x**Rational(2, 3)).evalf(subs={x: 0}) == 0
assert (x**x).evalf(subs={x: 0}) == 1.0
assert (3**x).evalf(subs={x: 0}) == 1.0
assert exp(x).evalf(subs={x: 0}) == 1.0
assert ((2 + I)**x).evalf(subs={x: 0}) == 1.0
assert (0**x).evalf(subs={x: 0}) == 1.0
def test_evalf_arguments():
raises(TypeError, lambda: pi.evalf(method="garbage"))
def test_implemented_function_evalf():
from sympy.utilities.lambdify import implemented_function
f = Function('f')
f = implemented_function(f, lambda x: x + 1)
assert str(f(x)) == "f(x)"
assert str(f(2)) == "f(2)"
assert f(2).evalf() == 3.0
assert f(x).evalf() == f(x)
f = implemented_function(Function('sin'), lambda x: x + 1)
assert f(2).evalf() != sin(2)
del f._imp_ # XXX: due to caching _imp_ would influence all other tests
def test_evaluate_false():
for no in [0, False]:
assert Add(3, 2, evaluate=no).is_Add
assert Mul(3, 2, evaluate=no).is_Mul
assert Pow(3, 2, evaluate=no).is_Pow
assert Pow(y, 2, evaluate=True) - Pow(y, 2, evaluate=True) == 0
def test_evalf_relational():
assert Eq(x/5, y/10).evalf() == Eq(0.2*x, 0.1*y)
# if this first assertion fails it should be replaced with
# one that doesn't
assert unchanged(Eq, (3 - I)**2/2 + I, 0)
assert Eq((3 - I)**2/2 + I, 0).n() is S.false
assert nfloat(Eq((3 - I)**2 + I, 0)) == S.false
def test_issue_5486():
assert not cos(sqrt(0.5 + I)).n().is_Function
def test_issue_5486_bug():
from sympy.core.expr import Expr
from sympy.core.numbers import I
assert abs(Expr._from_mpmath(I._to_mpmath(15), 15) - I) < 1.0e-15
def test_bugs():
from sympy.functions.elementary.complexes import (polar_lift, re)
assert abs(re((1 + I)**2)) < 1e-15
# anything that evalf's to 0 will do in place of polar_lift
assert abs(polar_lift(0)).n() == 0
def test_subs():
assert NS('besseli(-x, y) - besseli(x, y)', subs={x: 3.5, y: 20.0}) == \
'-4.92535585957223e-10'
assert NS('Piecewise((x, x>0)) + Piecewise((1-x, x>0))', subs={x: 0.1}) == \
'1.00000000000000'
raises(TypeError, lambda: x.evalf(subs=(x, 1)))
def test_issue_4956_5204():
# issue 4956
v = S('''(-27*12**(1/3)*sqrt(31)*I +
27*2**(2/3)*3**(1/3)*sqrt(31)*I)/(-2511*2**(2/3)*3**(1/3) +
(29*18**(1/3) + 9*2**(1/3)*3**(2/3)*sqrt(31)*I +
87*2**(1/3)*3**(1/6)*I)**2)''')
assert NS(v, 1) == '0.e-118 - 0.e-118*I'
# issue 5204
v = S('''-(357587765856 + 18873261792*249**(1/2) + 56619785376*I*83**(1/2) +
108755765856*I*3**(1/2) + 41281887168*6**(1/3)*(1422 +
54*249**(1/2))**(1/3) - 1239810624*6**(1/3)*249**(1/2)*(1422 +
54*249**(1/2))**(1/3) - 3110400000*I*6**(1/3)*83**(1/2)*(1422 +
54*249**(1/2))**(1/3) + 13478400000*I*3**(1/2)*6**(1/3)*(1422 +
54*249**(1/2))**(1/3) + 1274950152*6**(2/3)*(1422 +
54*249**(1/2))**(2/3) + 32347944*6**(2/3)*249**(1/2)*(1422 +
54*249**(1/2))**(2/3) - 1758790152*I*3**(1/2)*6**(2/3)*(1422 +
54*249**(1/2))**(2/3) - 304403832*I*6**(2/3)*83**(1/2)*(1422 +
4*249**(1/2))**(2/3))/(175732658352 + (1106028 + 25596*249**(1/2) +
76788*I*83**(1/2))**2)''')
assert NS(v, 5) == '0.077284 + 1.1104*I'
assert NS(v, 1) == '0.08 + 1.*I'
def test_old_docstring():
a = (E + pi*I)*(E - pi*I)
assert NS(a) == '17.2586605000200'
assert a.n() == 17.25866050002001
def test_issue_4806():
assert integrate(atan(x)**2, (x, -1, 1)).evalf().round(1) == Float(0.5, 1)
assert atan(0, evaluate=False).n() == 0
def test_evalf_mul():
# SymPy should not try to expand this; it should be handled term-wise
# in evalf through mpmath
assert NS(product(1 + sqrt(n)*I, (n, 1, 500)), 1) == '5.e+567 + 2.e+568*I'
def test_scaled_zero():
a, b = (([0], 1, 100, 1), -1)
assert scaled_zero(100) == (a, b)
assert scaled_zero(a) == (0, 1, 100, 1)
a, b = (([1], 1, 100, 1), -1)
assert scaled_zero(100, -1) == (a, b)
assert scaled_zero(a) == (1, 1, 100, 1)
raises(ValueError, lambda: scaled_zero(scaled_zero(100)))
raises(ValueError, lambda: scaled_zero(100, 2))
raises(ValueError, lambda: scaled_zero(100, 0))
raises(ValueError, lambda: scaled_zero((1, 5, 1, 3)))
def test_chop_value():
for i in range(-27, 28):
assert (Pow(10, i)*2).n(chop=10**i) and not (Pow(10, i)).n(chop=10**i)
def test_infinities():
assert oo.evalf(chop=True) == inf
assert (-oo).evalf(chop=True) == ninf
def test_to_mpmath():
assert sqrt(3)._to_mpmath(20)._mpf_ == (0, int(908093), -19, 20)
assert S(3.2)._to_mpmath(20)._mpf_ == (0, int(838861), -18, 20)
def test_issue_6632_evalf():
add = (-100000*sqrt(2500000001) + 5000000001)
assert add.n() == 9.999999998e-11
assert (add*add).n() == 9.999999996e-21
def test_issue_4945():
from sympy.abc import H
assert (H/0).evalf(subs={H:1}) == zoo
def test_evalf_integral():
# test that workprec has to increase in order to get a result other than 0
eps = Rational(1, 1000000)
assert Integral(sin(x), (x, -pi, pi + eps)).n(2)._prec == 10
def test_issue_8821_highprec_from_str():
s = str(pi.evalf(128))
p = N(s)
assert Abs(sin(p)) < 1e-15
p = N(s, 64)
assert Abs(sin(p)) < 1e-64
def test_issue_8853():
p = Symbol('x', even=True, positive=True)
assert floor(-p - S.Half).is_even == False
assert floor(-p + S.Half).is_even == True
assert ceiling(p - S.Half).is_even == True
assert ceiling(p + S.Half).is_even == False
assert get_integer_part(S.Half, -1, {}, True) == (0, 0)
assert get_integer_part(S.Half, 1, {}, True) == (1, 0)
assert get_integer_part(Rational(-1, 2), -1, {}, True) == (-1, 0)
assert get_integer_part(Rational(-1, 2), 1, {}, True) == (0, 0)
def test_issue_17681():
class identity_func(Function):
def _eval_evalf(self, *args, **kwargs):
return self.args[0].evalf(*args, **kwargs)
assert floor(identity_func(S(0))) == 0
assert get_integer_part(S(0), 1, {}, True) == (0, 0)
def test_issue_9326():
from sympy.core.symbol import Dummy
d1 = Dummy('d')
d2 = Dummy('d')
e = d1 + d2
assert e.evalf(subs = {d1: 1, d2: 2}) == 3.0
def test_issue_10323():
assert ceiling(sqrt(2**30 + 1)) == 2**15 + 1
def test_AssocOp_Function():
# the first arg of Min is not comparable in the imaginary part
raises(ValueError, lambda: S('''
Min(-sqrt(3)*cos(pi/18)/6 + re(1/((-1/2 - sqrt(3)*I/2)*(1/6 +
sqrt(3)*I/18)**(1/3)))/3 + sin(pi/18)/2 + 2 + I*(-cos(pi/18)/2 -
sqrt(3)*sin(pi/18)/6 + im(1/((-1/2 - sqrt(3)*I/2)*(1/6 +
sqrt(3)*I/18)**(1/3)))/3), re(1/((-1/2 + sqrt(3)*I/2)*(1/6 +
sqrt(3)*I/18)**(1/3)))/3 - sqrt(3)*cos(pi/18)/6 - sin(pi/18)/2 + 2 +
I*(im(1/((-1/2 + sqrt(3)*I/2)*(1/6 + sqrt(3)*I/18)**(1/3)))/3 -
sqrt(3)*sin(pi/18)/6 + cos(pi/18)/2))'''))
# if that is changed so a non-comparable number remains as
# an arg, then the Min/Max instantiation needs to be changed
# to watch out for non-comparable args when making simplifications
# and the following test should be added instead (with e being
# the sympified expression above):
# raises(ValueError, lambda: e._eval_evalf(2))
def test_issue_10395():
eq = x*Max(0, y)
assert nfloat(eq) == eq
eq = x*Max(y, -1.1)
assert nfloat(eq) == eq
assert Max(y, 4).n() == Max(4.0, y)
def test_issue_13098():
assert floor(log(S('9.'+'9'*20), 10)) == 0
assert ceiling(log(S('9.'+'9'*20), 10)) == 1
assert floor(log(20 - S('9.'+'9'*20), 10)) == 1
assert ceiling(log(20 - S('9.'+'9'*20), 10)) == 2
def test_issue_14601():
e = 5*x*y/2 - y*(35*(x**3)/2 - 15*x/2)
subst = {x:0.0, y:0.0}
e2 = e.evalf(subs=subst)
assert float(e2) == 0.0
assert float((x + x*(x**2 + x)).evalf(subs={x: 0.0})) == 0.0
def test_issue_11151():
z = S.Zero
e = Sum(z, (x, 1, 2))
assert e != z # it shouldn't evaluate
# when it does evaluate, this is what it should give
assert evalf(e, 15, {}) == \
evalf(z, 15, {}) == (None, None, 15, None)
# so this shouldn't fail
assert (e/2).n() == 0
# this was where the issue appeared
expr0 = Sum(x**2 + x, (x, 1, 2))
expr1 = Sum(0, (x, 1, 2))
expr2 = expr1/expr0
assert simplify(factor(expr2) - expr2) == 0
def test_issue_13425():
assert N('2**.5', 30) == N('sqrt(2)', 30)
assert N('x - x', 30) == 0
assert abs((N('pi*.1', 22)*10 - pi).n()) < 1e-22
def test_issue_17421():
assert N(acos(-I + acosh(cosh(cosh(1) + I)))) == 1.0*I
def test_issue_20291():
from sympy.sets import EmptySet, Reals
from sympy.sets.sets import (Complement, FiniteSet, Intersection)
a = Symbol('a')
b = Symbol('b')
A = FiniteSet(a, b)
assert A.evalf(subs={a: 1, b: 2}) == FiniteSet(1.0, 2.0)
B = FiniteSet(a-b, 1)
assert B.evalf(subs={a: 1, b: 2}) == FiniteSet(-1.0, 1.0)
sol = Complement(Intersection(FiniteSet(-b/2 - sqrt(b**2-4*pi)/2), Reals), FiniteSet(0))
assert sol.evalf(subs={b: 1}) == EmptySet
def test_evalf_with_zoo():
assert (1/x).evalf(subs={x: 0}) == zoo # issue 8242
assert (-1/x).evalf(subs={x: 0}) == zoo # PR 16150
assert (0 ** x).evalf(subs={x: -1}) == zoo # PR 16150
assert (0 ** x).evalf(subs={x: -1 + I}) == nan
assert Mul(2, Pow(0, -1, evaluate=False), evaluate=False).evalf() == zoo # issue 21147
assert Mul(x, 1/x, evaluate=False).evalf(subs={x: 0}) == Mul(x, 1/x, evaluate=False).subs(x, 0) == nan
assert Mul(1/x, 1/x, evaluate=False).evalf(subs={x: 0}) == zoo
assert Mul(1/x, Abs(1/x), evaluate=False).evalf(subs={x: 0}) == zoo
assert Abs(zoo, evaluate=False).evalf() == oo
assert re(zoo, evaluate=False).evalf() == nan
assert im(zoo, evaluate=False).evalf() == nan
assert Add(zoo, zoo, evaluate=False).evalf() == nan
assert Add(oo, zoo, evaluate=False).evalf() == nan
assert Pow(zoo, -1, evaluate=False).evalf() == 0
assert Pow(zoo, Rational(-1, 3), evaluate=False).evalf() == 0
assert Pow(zoo, Rational(1, 3), evaluate=False).evalf() == zoo
assert Pow(zoo, S.Half, evaluate=False).evalf() == zoo
assert Pow(zoo, 2, evaluate=False).evalf() == zoo
assert Pow(0, zoo, evaluate=False).evalf() == nan
assert log(zoo, evaluate=False).evalf() == zoo
assert zoo.evalf(chop=True) == zoo
assert x.evalf(subs={x: zoo}) == zoo
def test_evalf_with_bounded_error():
cases = [
# zero
(Rational(0), None, 1),
# zero im part
(pi, None, 10),
# zero real part
(pi*I, None, 10),
# re and im nonzero
(2-3*I, None, 5),
# similar tests again, but using eps instead of m
(Rational(0), Rational(1, 2), None),
(pi, Rational(1, 1000), None),
(pi * I, Rational(1, 1000), None),
(2 - 3 * I, Rational(1, 1000), None),
# very large eps
(2 - 3 * I, Rational(1000), None),
# case where x already small, hence some cancellation in p = m + n - 1
(Rational(1234, 10**8), Rational(1, 10**12), None),
]
for x0, eps, m in cases:
a, b, _, _ = evalf(x0, 53, {})
c, d, _, _ = _evalf_with_bounded_error(x0, eps, m)
if eps is None:
eps = 2**(-m)
z = make_mpc((a or fzero, b or fzero))
w = make_mpc((c or fzero, d or fzero))
assert abs(w - z) < eps
# eps must be positive
raises(ValueError, lambda: _evalf_with_bounded_error(pi, Rational(0)))
raises(ValueError, lambda: _evalf_with_bounded_error(pi, -pi))
raises(ValueError, lambda: _evalf_with_bounded_error(pi, I))
def test_issue_22849():
a = -8 + 3 * sqrt(3)
x = AlgebraicNumber(a)
assert evalf(a, 1, {}) == evalf(x, 1, {})
def test_evalf_real_alg_num():
# This test demonstrates why the entry for `AlgebraicNumber` in
# `sympy.core.evalf._create_evalf_table()` has to use `x.to_root()`,
# instead of `x.as_expr()`. If the latter is used, then `z` will be
# a complex number with `0.e-20` for imaginary part, even though `a5`
# is a real number.
zeta = Symbol('zeta')
a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1), [-1, -1, 0, 0], alias=zeta)
z = a5.evalf()
assert isinstance(z, Float)
assert not hasattr(z, '_mpc_')
assert hasattr(z, '_mpf_')
def test_issue_20733():
expr = 1/((x - 9)*(x - 8)*(x - 7)*(x - 4)**2*(x - 3)**3*(x - 2))
assert str(expr.evalf(1, subs={x:1})) == '-4.e-5'
assert str(expr.evalf(2, subs={x:1})) == '-4.1e-5'
assert str(expr.evalf(11, subs={x:1})) == '-4.1335978836e-5'
assert str(expr.evalf(20, subs={x:1})) == '-0.000041335978835978835979'
expr = Mul(*((x - i) for i in range(2, 1000)))
assert srepr(expr.evalf(2, subs={x: 1})) == "Float('4.0271e+2561', precision=10)"
assert srepr(expr.evalf(10, subs={x: 1})) == "Float('4.02790050126e+2561', precision=37)"
assert srepr(expr.evalf(53, subs={x: 1})) == "Float('4.0279005012722099453824067459760158730668154575647110393e+2561', precision=179)"
|
e0f5d4c09fd8757f5e81b60dacfc08facdc89034c6c9185867ac5cff554b53b0 | """Implementation of :class:`AlgebraicField` class. """
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.polys.domains.field import Field
from sympy.polys.domains.simpledomain import SimpleDomain
from sympy.polys.polyclasses import ANP
from sympy.polys.polyerrors import CoercionFailed, DomainError, NotAlgebraic, IsomorphismFailed
from sympy.utilities import public
@public
class AlgebraicField(Field, CharacteristicZero, SimpleDomain):
r"""Algebraic number field :ref:`QQ(a)`
A :ref:`QQ(a)` domain represents an `algebraic number field`_
`\mathbb{Q}(a)` as a :py:class:`~.Domain` in the domain system (see
:ref:`polys-domainsintro`).
A :py:class:`~.Poly` created from an expression involving `algebraic
numbers`_ will treat the algebraic numbers as generators if the generators
argument is not specified.
>>> from sympy import Poly, Symbol, sqrt
>>> x = Symbol('x')
>>> Poly(x**2 + sqrt(2))
Poly(x**2 + (sqrt(2)), x, sqrt(2), domain='ZZ')
That is a multivariate polynomial with ``sqrt(2)`` treated as one of the
generators (variables). If the generators are explicitly specified then
``sqrt(2)`` will be considered to be a coefficient but by default the
:ref:`EX` domain is used. To make a :py:class:`~.Poly` with a :ref:`QQ(a)`
domain the argument ``extension=True`` can be given.
>>> Poly(x**2 + sqrt(2), x)
Poly(x**2 + sqrt(2), x, domain='EX')
>>> Poly(x**2 + sqrt(2), x, extension=True)
Poly(x**2 + sqrt(2), x, domain='QQ<sqrt(2)>')
A generator of the algebraic field extension can also be specified
explicitly which is particularly useful if the coefficients are all
rational but an extension field is needed (e.g. to factor the
polynomial).
>>> Poly(x**2 + 1)
Poly(x**2 + 1, x, domain='ZZ')
>>> Poly(x**2 + 1, extension=sqrt(2))
Poly(x**2 + 1, x, domain='QQ<sqrt(2)>')
It is possible to factorise a polynomial over a :ref:`QQ(a)` domain using
the ``extension`` argument to :py:func:`~.factor` or by specifying the domain
explicitly.
>>> from sympy import factor, QQ
>>> factor(x**2 - 2)
x**2 - 2
>>> factor(x**2 - 2, extension=sqrt(2))
(x - sqrt(2))*(x + sqrt(2))
>>> factor(x**2 - 2, domain='QQ<sqrt(2)>')
(x - sqrt(2))*(x + sqrt(2))
>>> factor(x**2 - 2, domain=QQ.algebraic_field(sqrt(2)))
(x - sqrt(2))*(x + sqrt(2))
The ``extension=True`` argument can be used but will only create an
extension that contains the coefficients which is usually not enough to
factorise the polynomial.
>>> p = x**3 + sqrt(2)*x**2 - 2*x - 2*sqrt(2)
>>> factor(p) # treats sqrt(2) as a symbol
(x + sqrt(2))*(x**2 - 2)
>>> factor(p, extension=True)
(x - sqrt(2))*(x + sqrt(2))**2
>>> factor(x**2 - 2, extension=True) # all rational coefficients
x**2 - 2
It is also possible to use :ref:`QQ(a)` with the :py:func:`~.cancel`
and :py:func:`~.gcd` functions.
>>> from sympy import cancel, gcd
>>> cancel((x**2 - 2)/(x - sqrt(2)))
(x**2 - 2)/(x - sqrt(2))
>>> cancel((x**2 - 2)/(x - sqrt(2)), extension=sqrt(2))
x + sqrt(2)
>>> gcd(x**2 - 2, x - sqrt(2))
1
>>> gcd(x**2 - 2, x - sqrt(2), extension=sqrt(2))
x - sqrt(2)
When using the domain directly :ref:`QQ(a)` can be used as a constructor
to create instances which then support the operations ``+,-,*,**,/``. The
:py:meth:`~.Domain.algebraic_field` method is used to construct a
particular :ref:`QQ(a)` domain. The :py:meth:`~.Domain.from_sympy` method
can be used to create domain elements from normal SymPy expressions.
>>> K = QQ.algebraic_field(sqrt(2))
>>> K
QQ<sqrt(2)>
>>> xk = K.from_sympy(3 + 4*sqrt(2))
>>> xk # doctest: +SKIP
ANP([4, 3], [1, 0, -2], QQ)
Elements of :ref:`QQ(a)` are instances of :py:class:`~.ANP` which have
limited printing support. The raw display shows the internal
representation of the element as the list ``[4, 3]`` representing the
coefficients of ``1`` and ``sqrt(2)`` for this element in the form
``a * sqrt(2) + b * 1`` where ``a`` and ``b`` are elements of :ref:`QQ`.
The minimal polynomial for the generator ``(x**2 - 2)`` is also shown in
the :ref:`dup-representation` as the list ``[1, 0, -2]``. We can use
:py:meth:`~.Domain.to_sympy` to get a better printed form for the
elements and to see the results of operations.
>>> xk = K.from_sympy(3 + 4*sqrt(2))
>>> yk = K.from_sympy(2 + 3*sqrt(2))
>>> xk * yk # doctest: +SKIP
ANP([17, 30], [1, 0, -2], QQ)
>>> K.to_sympy(xk * yk)
17*sqrt(2) + 30
>>> K.to_sympy(xk + yk)
5 + 7*sqrt(2)
>>> K.to_sympy(xk ** 2)
24*sqrt(2) + 41
>>> K.to_sympy(xk / yk)
sqrt(2)/14 + 9/7
Any expression representing an algebraic number can be used to generate
a :ref:`QQ(a)` domain provided its `minimal polynomial`_ can be computed.
The function :py:func:`~.minpoly` function is used for this.
>>> from sympy import exp, I, pi, minpoly
>>> g = exp(2*I*pi/3)
>>> g
exp(2*I*pi/3)
>>> g.is_algebraic
True
>>> minpoly(g, x)
x**2 + x + 1
>>> factor(x**3 - 1, extension=g)
(x - 1)*(x - exp(2*I*pi/3))*(x + 1 + exp(2*I*pi/3))
It is also possible to make an algebraic field from multiple extension
elements.
>>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
>>> K
QQ<sqrt(2) + sqrt(3)>
>>> p = x**4 - 5*x**2 + 6
>>> factor(p)
(x**2 - 3)*(x**2 - 2)
>>> factor(p, domain=K)
(x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3))
>>> factor(p, extension=[sqrt(2), sqrt(3)])
(x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3))
Multiple extension elements are always combined together to make a single
`primitive element`_. In the case of ``[sqrt(2), sqrt(3)]`` the primitive
element chosen is ``sqrt(2) + sqrt(3)`` which is why the domain displays
as ``QQ<sqrt(2) + sqrt(3)>``. The minimal polynomial for the primitive
element is computed using the :py:func:`~.primitive_element` function.
>>> from sympy import primitive_element
>>> primitive_element([sqrt(2), sqrt(3)], x)
(x**4 - 10*x**2 + 1, [1, 1])
>>> minpoly(sqrt(2) + sqrt(3), x)
x**4 - 10*x**2 + 1
The extension elements that generate the domain can be accessed from the
domain using the :py:attr:`~.ext` and :py:attr:`~.orig_ext` attributes as
instances of :py:class:`~.AlgebraicNumber`. The minimal polynomial for
the primitive element as a :py:class:`~.DMP` instance is available as
:py:attr:`~.mod`.
>>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
>>> K
QQ<sqrt(2) + sqrt(3)>
>>> K.ext
sqrt(2) + sqrt(3)
>>> K.orig_ext
(sqrt(2), sqrt(3))
>>> K.mod
DMP([1, 0, -10, 0, 1], QQ, None)
The `discriminant`_ of the field can be obtained from the
:py:meth:`~.discriminant` method, and an `integral basis`_ from the
:py:meth:`~.integral_basis` method. The latter returns a list of
:py:class:`~.ANP` instances by default, but can be made to return instances
of :py:class:`~.Expr` or :py:class:`~.AlgebraicNumber` by passing a ``fmt``
argument. The maximal order, or ring of integers, of the field can also be
obtained from the :py:meth:`~.maximal_order` method, as a
:py:class:`~sympy.polys.numberfields.modules.Submodule`.
>>> zeta5 = exp(2*I*pi/5)
>>> K = QQ.algebraic_field(zeta5)
>>> K
QQ<exp(2*I*pi/5)>
>>> K.discriminant()
125
>>> K = QQ.algebraic_field(sqrt(5))
>>> K
QQ<sqrt(5)>
>>> K.integral_basis(fmt='sympy')
[1, 1/2 + sqrt(5)/2]
>>> K.maximal_order()
Submodule[[2, 0], [1, 1]]/2
The factorization of a rational prime into prime ideals of the field is
computed by the :py:meth:`~.primes_above` method, which returns a list
of :py:class:`~sympy.polys.numberfields.primes.PrimeIdeal` instances.
>>> zeta7 = exp(2*I*pi/7)
>>> K = QQ.algebraic_field(zeta7)
>>> K
QQ<exp(2*I*pi/7)>
>>> K.primes_above(11)
[(11, _x**3 + 5*_x**2 + 4*_x - 1), (11, _x**3 - 4*_x**2 - 5*_x - 1)]
Notes
=====
It is not currently possible to generate an algebraic extension over any
domain other than :ref:`QQ`. Ideally it would be possible to generate
extensions like ``QQ(x)(sqrt(x**2 - 2))``. This is equivalent to the
quotient ring ``QQ(x)[y]/(y**2 - x**2 + 2)`` and there are two
implementations of this kind of quotient ring/extension in the
:py:class:`~.QuotientRing` and :py:class:`~.MonogenicFiniteExtension`
classes. Each of those implementations needs some work to make them fully
usable though.
.. _algebraic number field: https://en.wikipedia.org/wiki/Algebraic_number_field
.. _algebraic numbers: https://en.wikipedia.org/wiki/Algebraic_number
.. _discriminant: https://en.wikipedia.org/wiki/Discriminant_of_an_algebraic_number_field
.. _integral basis: https://en.wikipedia.org/wiki/Algebraic_number_field#Integral_basis
.. _minimal polynomial: https://en.wikipedia.org/wiki/Minimal_polynomial_(field_theory)
.. _primitive element: https://en.wikipedia.org/wiki/Primitive_element_theorem
"""
dtype = ANP
is_AlgebraicField = is_Algebraic = True
is_Numerical = True
has_assoc_Ring = False
has_assoc_Field = True
def __init__(self, dom, *ext, alias=None):
r"""
Parameters
==========
dom : :py:class:`~.Domain`
The base field over which this is an extension field.
Currently only :ref:`QQ` is accepted.
*ext : One or more :py:class:`~.Expr`
Generators of the extension. These should be expressions that are
algebraic over `\mathbb{Q}`.
alias : str, :py:class:`~.Symbol`, None, optional (default=None)
If provided, this will be used as the alias symbol for the
primitive element of the :py:class:`~.AlgebraicField`.
If ``None``, while ``ext`` consists of exactly one
:py:class:`~.AlgebraicNumber`, its alias (if any) will be used.
"""
if not dom.is_QQ:
raise DomainError("ground domain must be a rational field")
from sympy.polys.numberfields import to_number_field
if len(ext) == 1 and isinstance(ext[0], tuple):
orig_ext = ext[0][1:]
else:
orig_ext = ext
if alias is None and len(ext) == 1:
alias = getattr(ext[0], 'alias', None)
self.orig_ext = orig_ext
"""
Original elements given to generate the extension.
>>> from sympy import QQ, sqrt
>>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
>>> K.orig_ext
(sqrt(2), sqrt(3))
"""
self.ext = to_number_field(ext, alias=alias)
"""
Primitive element used for the extension.
>>> from sympy import QQ, sqrt
>>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
>>> K.ext
sqrt(2) + sqrt(3)
"""
self.mod = self.ext.minpoly.rep
"""
Minimal polynomial for the primitive element of the extension.
>>> from sympy import QQ, sqrt
>>> K = QQ.algebraic_field(sqrt(2))
>>> K.mod
DMP([1, 0, -2], QQ, None)
"""
self.domain = self.dom = dom
self.ngens = 1
self.symbols = self.gens = (self.ext,)
self.unit = self([dom(1), dom(0)])
self.zero = self.dtype.zero(self.mod.rep, dom)
self.one = self.dtype.one(self.mod.rep, dom)
self._maximal_order = None
self._discriminant = None
self._nilradicals_mod_p = {}
def new(self, element):
return self.dtype(element, self.mod.rep, self.dom)
def __str__(self):
return str(self.dom) + '<' + str(self.ext) + '>'
def __hash__(self):
return hash((self.__class__.__name__, self.dtype, self.dom, self.ext))
def __eq__(self, other):
"""Returns ``True`` if two domains are equivalent. """
return isinstance(other, AlgebraicField) and \
self.dtype == other.dtype and self.ext == other.ext
def algebraic_field(self, *extension, alias=None):
r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. """
return AlgebraicField(self.dom, *((self.ext,) + extension), alias=alias)
def to_alg_num(self, a):
"""Convert ``a`` of ``dtype`` to an :py:class:`~.AlgebraicNumber`. """
return self.ext.field_element(a)
def to_sympy(self, a):
"""Convert ``a`` of ``dtype`` to a SymPy object. """
# Precompute a converter to be reused:
if not hasattr(self, '_converter'):
self._converter = _make_converter(self)
return self._converter(a)
def from_sympy(self, a):
"""Convert SymPy's expression to ``dtype``. """
try:
return self([self.dom.from_sympy(a)])
except CoercionFailed:
pass
from sympy.polys.numberfields import to_number_field
try:
return self(to_number_field(a, self.ext).native_coeffs())
except (NotAlgebraic, IsomorphismFailed):
raise CoercionFailed(
"%s is not a valid algebraic number in %s" % (a, self))
def from_ZZ(K1, a, K0):
"""Convert a Python ``int`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_ZZ_python(K1, a, K0):
"""Convert a Python ``int`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_QQ(K1, a, K0):
"""Convert a Python ``Fraction`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_QQ_python(K1, a, K0):
"""Convert a Python ``Fraction`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_ZZ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpz`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_QQ_gmpy(K1, a, K0):
"""Convert a GMPY ``mpq`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def from_RealField(K1, a, K0):
"""Convert a mpmath ``mpf`` object to ``dtype``. """
return K1(K1.dom.convert(a, K0))
def get_ring(self):
"""Returns a ring associated with ``self``. """
raise DomainError('there is no ring associated with %s' % self)
def is_positive(self, a):
"""Returns True if ``a`` is positive. """
return self.dom.is_positive(a.LC())
def is_negative(self, a):
"""Returns True if ``a`` is negative. """
return self.dom.is_negative(a.LC())
def is_nonpositive(self, a):
"""Returns True if ``a`` is non-positive. """
return self.dom.is_nonpositive(a.LC())
def is_nonnegative(self, a):
"""Returns True if ``a`` is non-negative. """
return self.dom.is_nonnegative(a.LC())
def numer(self, a):
"""Returns numerator of ``a``. """
return a
def denom(self, a):
"""Returns denominator of ``a``. """
return self.one
def from_AlgebraicField(K1, a, K0):
"""Convert AlgebraicField element 'a' to another AlgebraicField """
return K1.from_sympy(K0.to_sympy(a))
def from_GaussianIntegerRing(K1, a, K0):
"""Convert a GaussianInteger element 'a' to ``dtype``. """
return K1.from_sympy(K0.to_sympy(a))
def from_GaussianRationalField(K1, a, K0):
"""Convert a GaussianRational element 'a' to ``dtype``. """
return K1.from_sympy(K0.to_sympy(a))
def _do_round_two(self):
from sympy.polys.numberfields.basis import round_two
ZK, dK = round_two(self, radicals=self._nilradicals_mod_p)
self._maximal_order = ZK
self._discriminant = dK
def maximal_order(self):
"""
Compute the maximal order, or ring of integers, of the field.
Returns
=======
:py:class:`~sympy.polys.numberfields.modules.Submodule`.
See Also
========
integral_basis
"""
if self._maximal_order is None:
self._do_round_two()
return self._maximal_order
def integral_basis(self, fmt=None):
r"""
Get an integral basis for the field.
Parameters
==========
fmt : str, None, optional (default=None)
If ``None``, return a list of :py:class:`~.ANP` instances.
If ``"sympy"``, convert each element of the list to an
:py:class:`~.Expr`, using ``self.to_sympy()``.
If ``"alg"``, convert each element of the list to an
:py:class:`~.AlgebraicNumber`, using ``self.to_alg_num()``.
Examples
========
>>> from sympy import QQ, AlgebraicNumber, sqrt
>>> alpha = AlgebraicNumber(sqrt(5), alias='alpha')
>>> k = QQ.algebraic_field(alpha)
>>> B0 = k.integral_basis()
>>> B1 = k.integral_basis(fmt='sympy')
>>> B2 = k.integral_basis(fmt='alg')
>>> print(B0[1]) # doctest: +SKIP
ANP([mpq(1,2), mpq(1,2)], [mpq(1,1), mpq(0,1), mpq(-5,1)], QQ)
>>> print(B1[1])
1/2 + alpha/2
>>> print(B2[1])
alpha/2 + 1/2
In the last two cases we get legible expressions, which print somewhat
differently because of the different types involved:
>>> print(type(B1[1]))
<class 'sympy.core.add.Add'>
>>> print(type(B2[1]))
<class 'sympy.core.numbers.AlgebraicNumber'>
See Also
========
to_sympy
to_alg_num
maximal_order
"""
ZK = self.maximal_order()
M = ZK.QQ_matrix
n = M.shape[1]
B = [self.new(list(reversed(M[:, j].flat()))) for j in range(n)]
if fmt == 'sympy':
return [self.to_sympy(b) for b in B]
elif fmt == 'alg':
return [self.to_alg_num(b) for b in B]
return B
def discriminant(self):
"""Get the discriminant of the field."""
if self._discriminant is None:
self._do_round_two()
return self._discriminant
def primes_above(self, p):
"""Compute the prime ideals lying above a given rational prime *p*."""
from sympy.polys.numberfields.primes import prime_decomp
ZK = self.maximal_order()
dK = self.discriminant()
rad = self._nilradicals_mod_p.get(p)
return prime_decomp(p, ZK=ZK, dK=dK, radical=rad)
def _make_converter(K):
"""Construct the converter to convert back to Expr"""
# Precompute the effect of converting to SymPy and expanding expressions
# like (sqrt(2) + sqrt(3))**2. Asking Expr to do the expansion on every
# conversion from K to Expr is slow. Here we compute the expansions for
# each power of the generator and collect together the resulting algebraic
# terms and the rational coefficients into a matrix.
gen = K.ext.as_expr()
todom = K.dom.from_sympy
# We'll let Expr compute the expansions. We won't make any presumptions
# about what this results in except that it is QQ-linear in some terms
# that we will call algebraics. The final result will be expressed in
# terms of those.
powers = [S.One, gen]
for n in range(2, K.mod.degree()):
powers.append((gen * powers[-1]).expand())
# Collect the rational coefficients and algebraic Expr that can
# map the ANP coefficients into an expanded SymPy expression
terms = [dict(t.as_coeff_Mul()[::-1] for t in Add.make_args(p)) for p in powers]
algebraics = set().union(*terms)
matrix = [[todom(t.get(a, S.Zero)) for t in terms] for a in algebraics]
# Create a function to do the conversion efficiently:
def converter(a):
"""Convert a to Expr using converter"""
ai = a.rep[::-1]
tosympy = K.dom.to_sympy
coeffs_dom = [sum(mij*aj for mij, aj in zip(mi, ai)) for mi in matrix]
coeffs_sympy = [tosympy(c) for c in coeffs_dom]
res = Add(*(Mul(c, a) for c, a in zip(coeffs_sympy, algebraics)))
return res
return converter
|
4f632f222108dce3c5a0e439129dc781984d5357af3fe5b1bb4a03546ee825af | """Implementation of :class:`IntegerRing` class. """
from sympy.external.gmpy import MPZ, HAS_GMPY
from sympy.polys.domains.groundtypes import (
SymPyInteger,
factorial,
gcdex, gcd, lcm, sqrt,
)
from sympy.polys.domains.characteristiczero import CharacteristicZero
from sympy.polys.domains.ring import Ring
from sympy.polys.domains.simpledomain import SimpleDomain
from sympy.polys.polyerrors import CoercionFailed
from sympy.utilities import public
import math
@public
class IntegerRing(Ring, CharacteristicZero, SimpleDomain):
r"""The domain ``ZZ`` representing the integers `\mathbb{Z}`.
The :py:class:`IntegerRing` class represents the ring of integers as a
:py:class:`~.Domain` in the domain system. :py:class:`IntegerRing` is a
super class of :py:class:`PythonIntegerRing` and
:py:class:`GMPYIntegerRing` one of which will be the implementation for
:ref:`ZZ` depending on whether or not ``gmpy`` or ``gmpy2`` is installed.
See also
========
Domain
"""
rep = 'ZZ'
alias = 'ZZ'
dtype = MPZ
zero = dtype(0)
one = dtype(1)
tp = type(one)
is_IntegerRing = is_ZZ = True
is_Numerical = True
is_PID = True
has_assoc_Ring = True
has_assoc_Field = True
def __init__(self):
"""Allow instantiation of this domain. """
def to_sympy(self, a):
"""Convert ``a`` to a SymPy object. """
return SymPyInteger(int(a))
def from_sympy(self, a):
"""Convert SymPy's Integer to ``dtype``. """
if a.is_Integer:
return MPZ(a.p)
elif a.is_Float and int(a) == a:
return MPZ(int(a))
else:
raise CoercionFailed("expected an integer, got %s" % a)
def get_field(self):
r"""Return the associated field of fractions :ref:`QQ`
Returns
=======
:ref:`QQ`:
The associated field of fractions :ref:`QQ`, a
:py:class:`~.Domain` representing the rational numbers
`\mathbb{Q}`.
Examples
========
>>> from sympy import ZZ
>>> ZZ.get_field()
QQ
"""
from sympy.polys.domains import QQ
return QQ
def algebraic_field(self, *extension, alias=None):
r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`.
Parameters
==========
*extension : One or more :py:class:`~.Expr`.
Generators of the extension. These should be expressions that are
algebraic over `\mathbb{Q}`.
alias : str, :py:class:`~.Symbol`, None, optional (default=None)
If provided, this will be used as the alias symbol for the
primitive element of the returned :py:class:`~.AlgebraicField`.
Returns
=======
:py:class:`~.AlgebraicField`
A :py:class:`~.Domain` representing the algebraic field extension.
Examples
========
>>> from sympy import ZZ, sqrt
>>> ZZ.algebraic_field(sqrt(2))
QQ<sqrt(2)>
"""
return self.get_field().algebraic_field(*extension, alias=alias)
def from_AlgebraicField(K1, a, K0):
"""Convert a :py:class:`~.ANP` object to :ref:`ZZ`.
See :py:meth:`~.Domain.convert`.
"""
if a.is_ground:
return K1.convert(a.LC(), K0.dom)
def log(self, a, b):
r"""Logarithm of *a* to the base *b*.
Parameters
==========
a: number
b: number
Returns
=======
$\\lfloor\log(a, b)\\rfloor$:
Floor of the logarithm of *a* to the base *b*
Examples
========
>>> from sympy import ZZ
>>> ZZ.log(ZZ(8), ZZ(2))
3
>>> ZZ.log(ZZ(9), ZZ(2))
3
Notes
=====
This function uses ``math.log`` which is based on ``float`` so it will
fail for large integer arguments.
"""
return self.dtype(math.log(int(a), b))
def from_FF(K1, a, K0):
"""Convert ``ModularInteger(int)`` to GMPY's ``mpz``. """
return MPZ(a.to_int())
def from_FF_python(K1, a, K0):
"""Convert ``ModularInteger(int)`` to GMPY's ``mpz``. """
return MPZ(a.to_int())
def from_ZZ(K1, a, K0):
"""Convert Python's ``int`` to GMPY's ``mpz``. """
return MPZ(a)
def from_ZZ_python(K1, a, K0):
"""Convert Python's ``int`` to GMPY's ``mpz``. """
return MPZ(a)
def from_QQ(K1, a, K0):
"""Convert Python's ``Fraction`` to GMPY's ``mpz``. """
if a.denominator == 1:
return MPZ(a.numerator)
def from_QQ_python(K1, a, K0):
"""Convert Python's ``Fraction`` to GMPY's ``mpz``. """
if a.denominator == 1:
return MPZ(a.numerator)
def from_FF_gmpy(K1, a, K0):
"""Convert ``ModularInteger(mpz)`` to GMPY's ``mpz``. """
return a.to_int()
def from_ZZ_gmpy(K1, a, K0):
"""Convert GMPY's ``mpz`` to GMPY's ``mpz``. """
return a
def from_QQ_gmpy(K1, a, K0):
"""Convert GMPY ``mpq`` to GMPY's ``mpz``. """
if a.denominator == 1:
return a.numerator
def from_RealField(K1, a, K0):
"""Convert mpmath's ``mpf`` to GMPY's ``mpz``. """
p, q = K0.to_rational(a)
if q == 1:
return MPZ(p)
def from_GaussianIntegerRing(K1, a, K0):
if a.y == 0:
return a.x
def gcdex(self, a, b):
"""Compute extended GCD of ``a`` and ``b``. """
h, s, t = gcdex(a, b)
if HAS_GMPY:
return s, t, h
else:
return h, s, t
def gcd(self, a, b):
"""Compute GCD of ``a`` and ``b``. """
return gcd(a, b)
def lcm(self, a, b):
"""Compute LCM of ``a`` and ``b``. """
return lcm(a, b)
def sqrt(self, a):
"""Compute square root of ``a``. """
return sqrt(a)
def factorial(self, a):
"""Compute factorial of ``a``. """
return factorial(a)
ZZ = IntegerRing()
|
a6c55fdd803530c91eb95be7f88a6617fadcdc012187c538534f61e9d118f6ed | """Tests for the implementation of RootOf class and related tools. """
from sympy.polys.polytools import Poly
import sympy.polys.rootoftools as rootoftools
from sympy.polys.rootoftools import (rootof, RootOf, CRootOf, RootSum,
_pure_key_dict as D)
from sympy.polys.polyerrors import (
MultivariatePolynomialError,
GeneratorsNeeded,
PolynomialError,
)
from sympy.core.function import (Function, Lambda)
from sympy.core.numbers import (Float, I, Rational)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import tan
from sympy.integrals.integrals import Integral
from sympy.polys.orthopolys import legendre_poly
from sympy.solvers.solvers import solve
from sympy.testing.pytest import raises, slow
from sympy.core.expr import unchanged
from sympy.abc import a, b, x, y, z, r
def test_CRootOf___new__():
assert rootof(x, 0) == 0
assert rootof(x, -1) == 0
assert rootof(x, S.Zero) == 0
assert rootof(x - 1, 0) == 1
assert rootof(x - 1, -1) == 1
assert rootof(x + 1, 0) == -1
assert rootof(x + 1, -1) == -1
assert rootof(x**2 + 2*x + 3, 0) == -1 - I*sqrt(2)
assert rootof(x**2 + 2*x + 3, 1) == -1 + I*sqrt(2)
assert rootof(x**2 + 2*x + 3, -1) == -1 + I*sqrt(2)
assert rootof(x**2 + 2*x + 3, -2) == -1 - I*sqrt(2)
r = rootof(x**2 + 2*x + 3, 0, radicals=False)
assert isinstance(r, RootOf) is True
r = rootof(x**2 + 2*x + 3, 1, radicals=False)
assert isinstance(r, RootOf) is True
r = rootof(x**2 + 2*x + 3, -1, radicals=False)
assert isinstance(r, RootOf) is True
r = rootof(x**2 + 2*x + 3, -2, radicals=False)
assert isinstance(r, RootOf) is True
assert rootof((x - 1)*(x + 1), 0, radicals=False) == -1
assert rootof((x - 1)*(x + 1), 1, radicals=False) == 1
assert rootof((x - 1)*(x + 1), -1, radicals=False) == 1
assert rootof((x - 1)*(x + 1), -2, radicals=False) == -1
assert rootof((x - 1)*(x + 1), 0, radicals=True) == -1
assert rootof((x - 1)*(x + 1), 1, radicals=True) == 1
assert rootof((x - 1)*(x + 1), -1, radicals=True) == 1
assert rootof((x - 1)*(x + 1), -2, radicals=True) == -1
assert rootof((x - 1)*(x**3 + x + 3), 0) == rootof(x**3 + x + 3, 0)
assert rootof((x - 1)*(x**3 + x + 3), 1) == 1
assert rootof((x - 1)*(x**3 + x + 3), 2) == rootof(x**3 + x + 3, 1)
assert rootof((x - 1)*(x**3 + x + 3), 3) == rootof(x**3 + x + 3, 2)
assert rootof((x - 1)*(x**3 + x + 3), -1) == rootof(x**3 + x + 3, 2)
assert rootof((x - 1)*(x**3 + x + 3), -2) == rootof(x**3 + x + 3, 1)
assert rootof((x - 1)*(x**3 + x + 3), -3) == 1
assert rootof((x - 1)*(x**3 + x + 3), -4) == rootof(x**3 + x + 3, 0)
assert rootof(x**4 + 3*x**3, 0) == -3
assert rootof(x**4 + 3*x**3, 1) == 0
assert rootof(x**4 + 3*x**3, 2) == 0
assert rootof(x**4 + 3*x**3, 3) == 0
raises(GeneratorsNeeded, lambda: rootof(0, 0))
raises(GeneratorsNeeded, lambda: rootof(1, 0))
raises(PolynomialError, lambda: rootof(Poly(0, x), 0))
raises(PolynomialError, lambda: rootof(Poly(1, x), 0))
raises(PolynomialError, lambda: rootof(x - y, 0))
# issue 8617
raises(PolynomialError, lambda: rootof(exp(x), 0))
raises(NotImplementedError, lambda: rootof(x**3 - x + sqrt(2), 0))
raises(NotImplementedError, lambda: rootof(x**3 - x + I, 0))
raises(IndexError, lambda: rootof(x**2 - 1, -4))
raises(IndexError, lambda: rootof(x**2 - 1, -3))
raises(IndexError, lambda: rootof(x**2 - 1, 2))
raises(IndexError, lambda: rootof(x**2 - 1, 3))
raises(ValueError, lambda: rootof(x**2 - 1, x))
assert rootof(Poly(x - y, x), 0) == y
assert rootof(Poly(x**2 - y, x), 0) == -sqrt(y)
assert rootof(Poly(x**2 - y, x), 1) == sqrt(y)
assert rootof(Poly(x**3 - y, x), 0) == y**Rational(1, 3)
assert rootof(y*x**3 + y*x + 2*y, x, 0) == -1
raises(NotImplementedError, lambda: rootof(x**3 + x + 2*y, x, 0))
assert rootof(x**3 + x + 1, 0).is_commutative is True
def test_CRootOf_attributes():
r = rootof(x**3 + x + 3, 0)
assert r.is_number
assert r.free_symbols == set()
# if the following assertion fails then multivariate polynomials
# are apparently supported and the RootOf.free_symbols routine
# should be changed to return whatever symbols would not be
# the PurePoly dummy symbol
raises(NotImplementedError, lambda: rootof(Poly(x**3 + y*x + 1, x), 0))
def test_CRootOf___eq__():
assert (rootof(x**3 + x + 3, 0) == rootof(x**3 + x + 3, 0)) is True
assert (rootof(x**3 + x + 3, 0) == rootof(x**3 + x + 3, 1)) is False
assert (rootof(x**3 + x + 3, 1) == rootof(x**3 + x + 3, 1)) is True
assert (rootof(x**3 + x + 3, 1) == rootof(x**3 + x + 3, 2)) is False
assert (rootof(x**3 + x + 3, 2) == rootof(x**3 + x + 3, 2)) is True
assert (rootof(x**3 + x + 3, 0) == rootof(y**3 + y + 3, 0)) is True
assert (rootof(x**3 + x + 3, 0) == rootof(y**3 + y + 3, 1)) is False
assert (rootof(x**3 + x + 3, 1) == rootof(y**3 + y + 3, 1)) is True
assert (rootof(x**3 + x + 3, 1) == rootof(y**3 + y + 3, 2)) is False
assert (rootof(x**3 + x + 3, 2) == rootof(y**3 + y + 3, 2)) is True
def test_CRootOf___eval_Eq__():
f = Function('f')
eq = x**3 + x + 3
r = rootof(eq, 2)
r1 = rootof(eq, 1)
assert Eq(r, r1) is S.false
assert Eq(r, r) is S.true
assert unchanged(Eq, r, x)
assert Eq(r, 0) is S.false
assert Eq(r, S.Infinity) is S.false
assert Eq(r, I) is S.false
assert unchanged(Eq, r, f(0))
sol = solve(eq)
for s in sol:
if s.is_real:
assert Eq(r, s) is S.false
r = rootof(eq, 0)
for s in sol:
if s.is_real:
assert Eq(r, s) is S.true
eq = x**3 + x + 1
sol = solve(eq)
assert [Eq(rootof(eq, i), j) for i in range(3) for j in sol
].count(True) == 3
assert Eq(rootof(eq, 0), 1 + S.ImaginaryUnit) == False
def test_CRootOf_is_real():
assert rootof(x**3 + x + 3, 0).is_real is True
assert rootof(x**3 + x + 3, 1).is_real is False
assert rootof(x**3 + x + 3, 2).is_real is False
def test_CRootOf_is_complex():
assert rootof(x**3 + x + 3, 0).is_complex is True
def test_CRootOf_subs():
assert rootof(x**3 + x + 1, 0).subs(x, y) == rootof(y**3 + y + 1, 0)
def test_CRootOf_diff():
assert rootof(x**3 + x + 1, 0).diff(x) == 0
assert rootof(x**3 + x + 1, 0).diff(y) == 0
@slow
def test_CRootOf_evalf():
real = rootof(x**3 + x + 3, 0).evalf(n=20)
assert real.epsilon_eq(Float("-1.2134116627622296341"))
re, im = rootof(x**3 + x + 3, 1).evalf(n=20).as_real_imag()
assert re.epsilon_eq( Float("0.60670583138111481707"))
assert im.epsilon_eq(-Float("1.45061224918844152650"))
re, im = rootof(x**3 + x + 3, 2).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("0.60670583138111481707"))
assert im.epsilon_eq(Float("1.45061224918844152650"))
p = legendre_poly(4, x, polys=True)
roots = [str(r.n(17)) for r in p.real_roots()]
# magnitudes are given by
# sqrt(3/S(7) - 2*sqrt(6/S(5))/7)
# and
# sqrt(3/S(7) + 2*sqrt(6/S(5))/7)
assert roots == [
"-0.86113631159405258",
"-0.33998104358485626",
"0.33998104358485626",
"0.86113631159405258",
]
re = rootof(x**5 - 5*x + 12, 0).evalf(n=20)
assert re.epsilon_eq(Float("-1.84208596619025438271"))
re, im = rootof(x**5 - 5*x + 12, 1).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("-0.351854240827371999559"))
assert im.epsilon_eq(Float("-1.709561043370328882010"))
re, im = rootof(x**5 - 5*x + 12, 2).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("-0.351854240827371999559"))
assert im.epsilon_eq(Float("+1.709561043370328882010"))
re, im = rootof(x**5 - 5*x + 12, 3).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("+1.272897223922499190910"))
assert im.epsilon_eq(Float("-0.719798681483861386681"))
re, im = rootof(x**5 - 5*x + 12, 4).evalf(n=20).as_real_imag()
assert re.epsilon_eq(Float("+1.272897223922499190910"))
assert im.epsilon_eq(Float("+0.719798681483861386681"))
# issue 6393
assert str(rootof(x**5 + 2*x**4 + x**3 - 68719476736, 0).n(3)) == '147.'
eq = (531441*x**11 + 3857868*x**10 + 13730229*x**9 + 32597882*x**8 +
55077472*x**7 + 60452000*x**6 + 32172064*x**5 - 4383808*x**4 -
11942912*x**3 - 1506304*x**2 + 1453312*x + 512)
a, b = rootof(eq, 1).n(2).as_real_imag()
c, d = rootof(eq, 2).n(2).as_real_imag()
assert a == c
assert b < d
assert b == -d
# issue 6451
r = rootof(legendre_poly(64, x), 7)
assert r.n(2) == r.n(100).n(2)
# issue 9019
r0 = rootof(x**2 + 1, 0, radicals=False)
r1 = rootof(x**2 + 1, 1, radicals=False)
assert r0.n(4) == Float(-1.0, 4) * I
assert r1.n(4) == Float(1.0, 4) * I
# make sure verification is used in case a max/min traps the "root"
assert str(rootof(4*x**5 + 16*x**3 + 12*x**2 + 7, 0).n(3)) == '-0.976'
# watch out for UnboundLocalError
c = CRootOf(90720*x**6 - 4032*x**4 + 84*x**2 - 1, 0)
assert c._eval_evalf(2) # doesn't fail
# watch out for imaginary parts that don't want to evaluate
assert str(RootOf(x**16 + 32*x**14 + 508*x**12 + 5440*x**10 +
39510*x**8 + 204320*x**6 + 755548*x**4 + 1434496*x**2 +
877969, 10).n(2)) == '-3.4*I'
assert abs(RootOf(x**4 + 10*x**2 + 1, 0).n(2)) < 0.4
# check reset and args
r = [RootOf(x**3 + x + 3, i) for i in range(3)]
r[0]._reset()
for ri in r:
i = ri._get_interval()
ri.n(2)
assert i != ri._get_interval()
ri._reset()
assert i == ri._get_interval()
assert i == i.func(*i.args)
def test_CRootOf_evalf_caching_bug():
r = rootof(x**5 - 5*x + 12, 1)
r.n()
a = r._get_interval()
r = rootof(x**5 - 5*x + 12, 1)
r.n()
b = r._get_interval()
assert a == b
def test_CRootOf_real_roots():
assert Poly(x**5 + x + 1).real_roots() == [rootof(x**3 - x**2 + 1, 0)]
assert Poly(x**5 + x + 1).real_roots(radicals=False) == [rootof(
x**3 - x**2 + 1, 0)]
# https://github.com/sympy/sympy/issues/20902
p = Poly(-3*x**4 - 10*x**3 - 12*x**2 - 6*x - 1, x, domain='ZZ')
assert CRootOf.real_roots(p) == [S(-1), S(-1), S(-1), S(-1)/3]
def test_CRootOf_all_roots():
assert Poly(x**5 + x + 1).all_roots() == [
rootof(x**3 - x**2 + 1, 0),
Rational(-1, 2) - sqrt(3)*I/2,
Rational(-1, 2) + sqrt(3)*I/2,
rootof(x**3 - x**2 + 1, 1),
rootof(x**3 - x**2 + 1, 2),
]
assert Poly(x**5 + x + 1).all_roots(radicals=False) == [
rootof(x**3 - x**2 + 1, 0),
rootof(x**2 + x + 1, 0, radicals=False),
rootof(x**2 + x + 1, 1, radicals=False),
rootof(x**3 - x**2 + 1, 1),
rootof(x**3 - x**2 + 1, 2),
]
def test_CRootOf_eval_rational():
p = legendre_poly(4, x, polys=True)
roots = [r.eval_rational(n=18) for r in p.real_roots()]
for root in roots:
assert isinstance(root, Rational)
roots = [str(root.n(17)) for root in roots]
assert roots == [
"-0.86113631159405258",
"-0.33998104358485626",
"0.33998104358485626",
"0.86113631159405258",
]
def test_CRootOf_lazy():
# irreducible poly with both real and complex roots:
f = Poly(x**3 + 2*x + 2)
# real root:
CRootOf.clear_cache()
r = CRootOf(f, 0)
# Not yet in cache, after construction:
assert r.poly not in rootoftools._reals_cache
assert r.poly not in rootoftools._complexes_cache
r.evalf()
# In cache after evaluation:
assert r.poly in rootoftools._reals_cache
assert r.poly not in rootoftools._complexes_cache
# complex root:
CRootOf.clear_cache()
r = CRootOf(f, 1)
# Not yet in cache, after construction:
assert r.poly not in rootoftools._reals_cache
assert r.poly not in rootoftools._complexes_cache
r.evalf()
# In cache after evaluation:
assert r.poly in rootoftools._reals_cache
assert r.poly in rootoftools._complexes_cache
# composite poly with both real and complex roots:
f = Poly((x**2 - 2)*(x**2 + 1))
# real root:
CRootOf.clear_cache()
r = CRootOf(f, 0)
# In cache immediately after construction:
assert r.poly in rootoftools._reals_cache
assert r.poly not in rootoftools._complexes_cache
# complex root:
CRootOf.clear_cache()
r = CRootOf(f, 2)
# In cache immediately after construction:
assert r.poly in rootoftools._reals_cache
assert r.poly in rootoftools._complexes_cache
def test_RootSum___new__():
f = x**3 + x + 3
g = Lambda(r, log(r*x))
s = RootSum(f, g)
assert isinstance(s, RootSum) is True
assert RootSum(f**2, g) == 2*RootSum(f, g)
assert RootSum((x - 7)*f**3, g) == log(7*x) + 3*RootSum(f, g)
# issue 5571
assert hash(RootSum((x - 7)*f**3, g)) == hash(log(7*x) + 3*RootSum(f, g))
raises(MultivariatePolynomialError, lambda: RootSum(x**3 + x + y))
raises(ValueError, lambda: RootSum(x**2 + 3, lambda x: x))
assert RootSum(f, exp) == RootSum(f, Lambda(x, exp(x)))
assert RootSum(f, log) == RootSum(f, Lambda(x, log(x)))
assert isinstance(RootSum(f, auto=False), RootSum) is True
assert RootSum(f) == 0
assert RootSum(f, Lambda(x, x)) == 0
assert RootSum(f, Lambda(x, x**2)) == -2
assert RootSum(f, Lambda(x, 1)) == 3
assert RootSum(f, Lambda(x, 2)) == 6
assert RootSum(f, auto=False).is_commutative is True
assert RootSum(f, Lambda(x, 1/(x + x**2))) == Rational(11, 3)
assert RootSum(f, Lambda(x, y/(x + x**2))) == Rational(11, 3)*y
assert RootSum(x**2 - 1, Lambda(x, 3*x**2), x) == 6
assert RootSum(x**2 - y, Lambda(x, 3*x**2), x) == 6*y
assert RootSum(x**2 - 1, Lambda(x, z*x**2), x) == 2*z
assert RootSum(x**2 - y, Lambda(x, z*x**2), x) == 2*z*y
assert RootSum(
x**2 - 1, Lambda(x, exp(x)), quadratic=True) == exp(-1) + exp(1)
assert RootSum(x**3 + a*x + a**3, tan, x) == \
RootSum(x**3 + x + 1, Lambda(x, tan(a*x)))
assert RootSum(a**3*x**3 + a*x + 1, tan, x) == \
RootSum(x**3 + x + 1, Lambda(x, tan(x/a)))
def test_RootSum_free_symbols():
assert RootSum(x**3 + x + 3, Lambda(r, exp(r))).free_symbols == set()
assert RootSum(x**3 + x + 3, Lambda(r, exp(a*r))).free_symbols == {a}
assert RootSum(
x**3 + x + y, Lambda(r, exp(a*r)), x).free_symbols == {a, y}
def test_RootSum___eq__():
f = Lambda(x, exp(x))
assert (RootSum(x**3 + x + 1, f) == RootSum(x**3 + x + 1, f)) is True
assert (RootSum(x**3 + x + 1, f) == RootSum(y**3 + y + 1, f)) is True
assert (RootSum(x**3 + x + 1, f) == RootSum(x**3 + x + 2, f)) is False
assert (RootSum(x**3 + x + 1, f) == RootSum(y**3 + y + 2, f)) is False
def test_RootSum_doit():
rs = RootSum(x**2 + 1, exp)
assert isinstance(rs, RootSum) is True
assert rs.doit() == exp(-I) + exp(I)
rs = RootSum(x**2 + a, exp, x)
assert isinstance(rs, RootSum) is True
assert rs.doit() == exp(-sqrt(-a)) + exp(sqrt(-a))
def test_RootSum_evalf():
rs = RootSum(x**2 + 1, exp)
assert rs.evalf(n=20, chop=True).epsilon_eq(Float("1.0806046117362794348"))
assert rs.evalf(n=15, chop=True).epsilon_eq(Float("1.08060461173628"))
rs = RootSum(x**2 + a, exp, x)
assert rs.evalf() == rs
def test_RootSum_diff():
f = x**3 + x + 3
g = Lambda(r, exp(r*x))
h = Lambda(r, r*exp(r*x))
assert RootSum(f, g).diff(x) == RootSum(f, h)
def test_RootSum_subs():
f = x**3 + x + 3
g = Lambda(r, exp(r*x))
F = y**3 + y + 3
G = Lambda(r, exp(r*y))
assert RootSum(f, g).subs(y, 1) == RootSum(f, g)
assert RootSum(f, g).subs(x, y) == RootSum(F, G)
def test_RootSum_rational():
assert RootSum(
z**5 - z + 1, Lambda(z, z/(x - z))) == (4*x - 5)/(x**5 - x + 1)
f = 161*z**3 + 115*z**2 + 19*z + 1
g = Lambda(z, z*log(
-3381*z**4/4 - 3381*z**3/4 - 625*z**2/2 - z*Rational(125, 2) - 5 + exp(x)))
assert RootSum(f, g).diff(x) == -(
(5*exp(2*x) - 6*exp(x) + 4)*exp(x)/(exp(3*x) - exp(2*x) + 1))/7
def test_RootSum_independent():
f = (x**3 - a)**2*(x**4 - b)**3
g = Lambda(x, 5*tan(x) + 7)
h = Lambda(x, tan(x))
r0 = RootSum(x**3 - a, h, x)
r1 = RootSum(x**4 - b, h, x)
assert RootSum(f, g, x).as_ordered_terms() == [10*r0, 15*r1, 126]
def test_issue_7876():
l1 = Poly(x**6 - x + 1, x).all_roots()
l2 = [rootof(x**6 - x + 1, i) for i in range(6)]
assert frozenset(l1) == frozenset(l2)
def test_issue_8316():
f = Poly(7*x**8 - 9)
assert len(f.all_roots()) == 8
f = Poly(7*x**8 - 10)
assert len(f.all_roots()) == 8
def test__imag_count():
from sympy.polys.rootoftools import _imag_count_of_factor
def imag_count(p):
return sum([_imag_count_of_factor(f)*m for f, m in
p.factor_list()[1]])
assert imag_count(Poly(x**6 + 10*x**2 + 1)) == 2
assert imag_count(Poly(x**2)) == 0
assert imag_count(Poly([1]*3 + [-1], x)) == 0
assert imag_count(Poly(x**3 + 1)) == 0
assert imag_count(Poly(x**2 + 1)) == 2
assert imag_count(Poly(x**2 - 1)) == 0
assert imag_count(Poly(x**4 - 1)) == 2
assert imag_count(Poly(x**4 + 1)) == 0
assert imag_count(Poly([1, 2, 3], x)) == 0
assert imag_count(Poly(x**3 + x + 1)) == 0
assert imag_count(Poly(x**4 + x + 1)) == 0
def q(r1, r2, p):
return Poly(((x - r1)*(x - r2)).subs(x, x**p), x)
assert imag_count(q(-1, -2, 2)) == 4
assert imag_count(q(-1, 2, 2)) == 2
assert imag_count(q(1, 2, 2)) == 0
assert imag_count(q(1, 2, 4)) == 4
assert imag_count(q(-1, 2, 4)) == 2
assert imag_count(q(-1, -2, 4)) == 0
def test_RootOf_is_imaginary():
r = RootOf(x**4 + 4*x**2 + 1, 1)
i = r._get_interval()
assert r.is_imaginary and i.ax*i.bx <= 0
def test_is_disjoint():
eq = x**3 + 5*x + 1
ir = rootof(eq, 0)._get_interval()
ii = rootof(eq, 1)._get_interval()
assert ir.is_disjoint(ii)
assert ii.is_disjoint(ir)
def test_pure_key_dict():
p = D()
assert (x in p) is False
assert (1 in p) is False
p[x] = 1
assert x in p
assert y in p
assert p[y] == 1
raises(KeyError, lambda: p[1])
def dont(k):
p[k] = 2
raises(ValueError, lambda: dont(1))
@slow
def test_eval_approx_relative():
CRootOf.clear_cache()
t = [CRootOf(x**3 + 10*x + 1, i) for i in range(3)]
assert [i.eval_rational(1e-1) for i in t] == [
Rational(-21, 220), Rational(15, 256) - I*805/256,
Rational(15, 256) + I*805/256]
t[0]._reset()
assert [i.eval_rational(1e-1, 1e-4) for i in t] == [
Rational(-21, 220), Rational(3275, 65536) - I*414645/131072,
Rational(3275, 65536) + I*414645/131072]
assert S(t[0]._get_interval().dx) < 1e-1
assert S(t[1]._get_interval().dx) < 1e-1
assert S(t[1]._get_interval().dy) < 1e-4
assert S(t[2]._get_interval().dx) < 1e-1
assert S(t[2]._get_interval().dy) < 1e-4
t[0]._reset()
assert [i.eval_rational(1e-4, 1e-4) for i in t] == [
Rational(-2001, 20020), Rational(6545, 131072) - I*414645/131072,
Rational(6545, 131072) + I*414645/131072]
assert S(t[0]._get_interval().dx) < 1e-4
assert S(t[1]._get_interval().dx) < 1e-4
assert S(t[1]._get_interval().dy) < 1e-4
assert S(t[2]._get_interval().dx) < 1e-4
assert S(t[2]._get_interval().dy) < 1e-4
# in the following, the actual relative precision is
# less than tested, but it should never be greater
t[0]._reset()
assert [i.eval_rational(n=2) for i in t] == [
Rational(-202201, 2024022), Rational(104755, 2097152) - I*6634255/2097152,
Rational(104755, 2097152) + I*6634255/2097152]
assert abs(S(t[0]._get_interval().dx)/t[0]) < 1e-2
assert abs(S(t[1]._get_interval().dx)/t[1]).n() < 1e-2
assert abs(S(t[1]._get_interval().dy)/t[1]).n() < 1e-2
assert abs(S(t[2]._get_interval().dx)/t[2]).n() < 1e-2
assert abs(S(t[2]._get_interval().dy)/t[2]).n() < 1e-2
t[0]._reset()
assert [i.eval_rational(n=3) for i in t] == [
Rational(-202201, 2024022), Rational(1676045, 33554432) - I*106148135/33554432,
Rational(1676045, 33554432) + I*106148135/33554432]
assert abs(S(t[0]._get_interval().dx)/t[0]) < 1e-3
assert abs(S(t[1]._get_interval().dx)/t[1]).n() < 1e-3
assert abs(S(t[1]._get_interval().dy)/t[1]).n() < 1e-3
assert abs(S(t[2]._get_interval().dx)/t[2]).n() < 1e-3
assert abs(S(t[2]._get_interval().dy)/t[2]).n() < 1e-3
t[0]._reset()
a = [i.eval_approx(2) for i in t]
assert [str(i) for i in a] == [
'-0.10', '0.05 - 3.2*I', '0.05 + 3.2*I']
assert all(abs(((a[i] - t[i])/t[i]).n()) < 1e-2 for i in range(len(a)))
def test_issue_15920():
r = rootof(x**5 - x + 1, 0)
p = Integral(x, (x, 1, y))
assert unchanged(Eq, r, p)
def test_issue_19113():
eq = y**3 - y + 1
# generator is a canonical x in RootOf
assert str(Poly(eq).real_roots()) == '[CRootOf(x**3 - x + 1, 0)]'
assert str(Poly(eq.subs(y, tan(y))).real_roots()
) == '[CRootOf(x**3 - x + 1, 0)]'
assert str(Poly(eq.subs(y, tan(x))).real_roots()
) == '[CRootOf(x**3 - x + 1, 0)]'
|
b4392326bcc6a836aeec720f5d33a08b41962a39a30cbba0174c991fbef7eaf6 | """Tests for user-friendly public interface to polynomial functions. """
import pickle
from sympy.polys.polytools import (
Poly, PurePoly, poly,
parallel_poly_from_expr,
degree, degree_list,
total_degree,
LC, LM, LT,
pdiv, prem, pquo, pexquo,
div, rem, quo, exquo,
half_gcdex, gcdex, invert,
subresultants,
resultant, discriminant,
terms_gcd, cofactors,
gcd, gcd_list,
lcm, lcm_list,
trunc,
monic, content, primitive,
compose, decompose,
sturm,
gff_list, gff,
sqf_norm, sqf_part, sqf_list, sqf,
factor_list, factor,
intervals, refine_root, count_roots,
real_roots, nroots, ground_roots,
nth_power_roots_poly,
cancel, reduced, groebner,
GroebnerBasis, is_zero_dimensional,
_torational_factor_list,
to_rational_coeffs)
from sympy.polys.polyerrors import (
MultivariatePolynomialError,
ExactQuotientFailed,
PolificationFailed,
ComputationFailed,
UnificationFailed,
RefinementFailed,
GeneratorsNeeded,
GeneratorsError,
PolynomialError,
CoercionFailed,
DomainError,
OptionError,
FlagError)
from sympy.polys.polyclasses import DMP
from sympy.polys.fields import field
from sympy.polys.domains import FF, ZZ, QQ, ZZ_I, QQ_I, RR, EX
from sympy.polys.domains.realfield import RealField
from sympy.polys.domains.complexfield import ComplexField
from sympy.polys.orderings import lex, grlex, grevlex
from sympy.core.add import Add
from sympy.core.basic import _aresame
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import (Derivative, diff, expand)
from sympy.core.mul import _keep_coeff, Mul
from sympy.core.numbers import (Float, I, Integer, Rational, oo, pi)
from sympy.core.power import Pow
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.elementary.complexes import (im, re)
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.hyperbolic import tanh
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import sin
from sympy.matrices.dense import Matrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.polys.rootoftools import rootof
from sympy.simplify.simplify import signsimp
from sympy.utilities.iterables import iterable
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.testing.pytest import raises, warns_deprecated_sympy, warns
from sympy.abc import a, b, c, d, p, q, t, w, x, y, z
def _epsilon_eq(a, b):
for u, v in zip(a, b):
if abs(u - v) > 1e-10:
return False
return True
def _strict_eq(a, b):
if type(a) == type(b):
if iterable(a):
if len(a) == len(b):
return all(_strict_eq(c, d) for c, d in zip(a, b))
else:
return False
else:
return isinstance(a, Poly) and a.eq(b, strict=True)
else:
return False
def test_Poly_mixed_operations():
p = Poly(x, x)
with warns_deprecated_sympy():
p * exp(x)
with warns_deprecated_sympy():
p + exp(x)
with warns_deprecated_sympy():
p - exp(x)
def test_Poly_from_dict():
K = FF(3)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict(
{0: 1, 1: 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict(
{(0,): 1, (1,): 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_dict({(0, 0): 1, (1, 1): 2}, gens=(
x, y), domain=K).rep == DMP([[K(2), K(0)], [K(1)]], K)
assert Poly.from_dict({0: 1, 1: 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{0: 1, 1: 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_dict(
{(0,): 1, (1,): 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_dict({(1,): sin(y)}, gens=x, composite=False) == \
Poly(sin(y)*x, x, domain='EX')
assert Poly.from_dict({(1,): y}, gens=x, composite=False) == \
Poly(y*x, x, domain='EX')
assert Poly.from_dict({(1, 1): 1}, gens=(x, y), composite=False) == \
Poly(x*y, x, y, domain='ZZ')
assert Poly.from_dict({(1, 0): y}, gens=(x, z), composite=False) == \
Poly(y*x, x, z, domain='EX')
def test_Poly_from_list():
K = FF(3)
assert Poly.from_list([2, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_list([5, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K)
assert Poly.from_list([2, 1], gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_list([2, 1], gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_list([2, 1], gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ)
assert Poly.from_list([2, 1], gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ)
assert Poly.from_list([0, 1.0], gens=x).rep == DMP([RR(1.0)], RR)
assert Poly.from_list([1.0, 0], gens=x).rep == DMP([RR(1.0), RR(0.0)], RR)
raises(MultivariatePolynomialError, lambda: Poly.from_list([[]], gens=(x, y)))
def test_Poly_from_poly():
f = Poly(x + 7, x, domain=ZZ)
g = Poly(x + 2, x, modulus=3)
h = Poly(x + y, x, y, domain=ZZ)
K = FF(3)
assert Poly.from_poly(f) == f
assert Poly.from_poly(f, domain=K).rep == DMP([K(1), K(1)], K)
assert Poly.from_poly(f, domain=ZZ).rep == DMP([1, 7], ZZ)
assert Poly.from_poly(f, domain=QQ).rep == DMP([1, 7], QQ)
assert Poly.from_poly(f, gens=x) == f
assert Poly.from_poly(f, gens=x, domain=K).rep == DMP([K(1), K(1)], K)
assert Poly.from_poly(f, gens=x, domain=ZZ).rep == DMP([1, 7], ZZ)
assert Poly.from_poly(f, gens=x, domain=QQ).rep == DMP([1, 7], QQ)
assert Poly.from_poly(f, gens=y) == Poly(x + 7, y, domain='ZZ[x]')
raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=K))
raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=ZZ))
raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=QQ))
assert Poly.from_poly(f, gens=(x, y)) == Poly(x + 7, x, y, domain='ZZ')
assert Poly.from_poly(
f, gens=(x, y), domain=ZZ) == Poly(x + 7, x, y, domain='ZZ')
assert Poly.from_poly(
f, gens=(x, y), domain=QQ) == Poly(x + 7, x, y, domain='QQ')
assert Poly.from_poly(
f, gens=(x, y), modulus=3) == Poly(x + 7, x, y, domain='FF(3)')
K = FF(2)
assert Poly.from_poly(g) == g
assert Poly.from_poly(g, domain=ZZ).rep == DMP([1, -1], ZZ)
raises(CoercionFailed, lambda: Poly.from_poly(g, domain=QQ))
assert Poly.from_poly(g, domain=K).rep == DMP([K(1), K(0)], K)
assert Poly.from_poly(g, gens=x) == g
assert Poly.from_poly(g, gens=x, domain=ZZ).rep == DMP([1, -1], ZZ)
raises(CoercionFailed, lambda: Poly.from_poly(g, gens=x, domain=QQ))
assert Poly.from_poly(g, gens=x, domain=K).rep == DMP([K(1), K(0)], K)
K = FF(3)
assert Poly.from_poly(h) == h
assert Poly.from_poly(
h, domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(h, domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K)
assert Poly.from_poly(h, gens=x) == Poly(x + y, x, domain=ZZ[y])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=ZZ))
assert Poly.from_poly(
h, gens=x, domain=ZZ[y]) == Poly(x + y, x, domain=ZZ[y])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=QQ))
assert Poly.from_poly(
h, gens=x, domain=QQ[y]) == Poly(x + y, x, domain=QQ[y])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, modulus=3))
assert Poly.from_poly(h, gens=y) == Poly(x + y, y, domain=ZZ[x])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=ZZ))
assert Poly.from_poly(
h, gens=y, domain=ZZ[x]) == Poly(x + y, y, domain=ZZ[x])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=QQ))
assert Poly.from_poly(
h, gens=y, domain=QQ[x]) == Poly(x + y, y, domain=QQ[x])
raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, modulus=3))
assert Poly.from_poly(h, gens=(x, y)) == h
assert Poly.from_poly(
h, gens=(x, y), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, gens=(x, y), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(
h, gens=(x, y), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K)
assert Poly.from_poly(
h, gens=(y, x)).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, gens=(y, x), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ)
assert Poly.from_poly(
h, gens=(y, x), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(
h, gens=(y, x), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K)
assert Poly.from_poly(
h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
assert Poly.from_poly(
h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ)
def test_Poly_from_expr():
raises(GeneratorsNeeded, lambda: Poly.from_expr(S.Zero))
raises(GeneratorsNeeded, lambda: Poly.from_expr(S(7)))
F3 = FF(3)
assert Poly.from_expr(x + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(y + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(x + 5, x, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(y + 5, y, domain=F3).rep == DMP([F3(1), F3(2)], F3)
assert Poly.from_expr(x + y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3)
assert Poly.from_expr(x + y, x, y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3)
assert Poly.from_expr(x + 5).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, x).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5, y).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, x, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(y + 5, y, domain=ZZ).rep == DMP([1, 5], ZZ)
assert Poly.from_expr(x + 5, x, y, domain=ZZ).rep == DMP([[1], [5]], ZZ)
assert Poly.from_expr(y + 5, x, y, domain=ZZ).rep == DMP([[1, 5]], ZZ)
def test_poly_from_domain_element():
dom = ZZ[x]
assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom)
dom = dom.get_field()
assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom)
dom = QQ[x]
assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom)
dom = dom.get_field()
assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom)
dom = ZZ.old_poly_ring(x)
assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom)
dom = dom.get_field()
assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom)
dom = QQ.old_poly_ring(x)
assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom)
dom = dom.get_field()
assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom)
dom = QQ.algebraic_field(I)
assert Poly(dom([1, 1]), x, domain=dom).rep == DMP([dom([1, 1])], dom)
def test_Poly__new__():
raises(GeneratorsError, lambda: Poly(x + 1, x, x))
raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[x]))
raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[y]))
raises(OptionError, lambda: Poly(x, x, symmetric=True))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, domain=QQ))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, gaussian=True))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, gaussian=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=[sqrt(3)]))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=[sqrt(3)]))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=True))
raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=True))
raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=False))
raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=False))
raises(NotImplementedError, lambda: Poly(x + 1, x, modulus=3, order='grlex'))
raises(NotImplementedError, lambda: Poly(x + 1, x, order='grlex'))
raises(GeneratorsNeeded, lambda: Poly({1: 2, 0: 1}))
raises(GeneratorsNeeded, lambda: Poly([2, 1]))
raises(GeneratorsNeeded, lambda: Poly((2, 1)))
raises(GeneratorsNeeded, lambda: Poly(1))
f = a*x**2 + b*x + c
assert Poly({2: a, 1: b, 0: c}, x) == f
assert Poly(iter([a, b, c]), x) == f
assert Poly([a, b, c], x) == f
assert Poly((a, b, c), x) == f
f = Poly({}, x, y, z)
assert f.gens == (x, y, z) and f.as_expr() == 0
assert Poly(Poly(a*x + b*y, x, y), x) == Poly(a*x + b*y, x)
assert Poly(3*x**2 + 2*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1]
assert Poly(3*x**2 + 2*x + 1, domain='QQ').all_coeffs() == [3, 2, 1]
assert Poly(3*x**2 + 2*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0]
raises(CoercionFailed, lambda: Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='ZZ'))
assert Poly(
3*x**2/5 + x*Rational(2, 5) + 1, domain='QQ').all_coeffs() == [Rational(3, 5), Rational(2, 5), 1]
assert _epsilon_eq(
Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='RR').all_coeffs(), [0.6, 0.4, 1.0])
assert Poly(3.0*x**2 + 2.0*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1]
assert Poly(3.0*x**2 + 2.0*x + 1, domain='QQ').all_coeffs() == [3, 2, 1]
assert Poly(
3.0*x**2 + 2.0*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0]
raises(CoercionFailed, lambda: Poly(3.1*x**2 + 2.1*x + 1, domain='ZZ'))
assert Poly(3.1*x**2 + 2.1*x + 1, domain='QQ').all_coeffs() == [Rational(31, 10), Rational(21, 10), 1]
assert Poly(3.1*x**2 + 2.1*x + 1, domain='RR').all_coeffs() == [3.1, 2.1, 1.0]
assert Poly({(2, 1): 1, (1, 2): 2, (1, 1): 3}, x, y) == \
Poly(x**2*y + 2*x*y**2 + 3*x*y, x, y)
assert Poly(x**2 + 1, extension=I).get_domain() == QQ.algebraic_field(I)
f = 3*x**5 - x**4 + x**3 - x** 2 + 65538
assert Poly(f, x, modulus=65537, symmetric=True) == \
Poly(3*x**5 - x**4 + x**3 - x** 2 + 1, x, modulus=65537,
symmetric=True)
assert Poly(f, x, modulus=65537, symmetric=False) == \
Poly(3*x**5 + 65536*x**4 + x**3 + 65536*x** 2 + 1, x,
modulus=65537, symmetric=False)
assert isinstance(Poly(x**2 + x + 1.0).get_domain(), RealField)
assert isinstance(Poly(x**2 + x + I + 1.0).get_domain(), ComplexField)
def test_Poly__args():
assert Poly(x**2 + 1).args == (x**2 + 1, x)
def test_Poly__gens():
assert Poly((x - p)*(x - q), x).gens == (x,)
assert Poly((x - p)*(x - q), p).gens == (p,)
assert Poly((x - p)*(x - q), q).gens == (q,)
assert Poly((x - p)*(x - q), x, p).gens == (x, p)
assert Poly((x - p)*(x - q), x, q).gens == (x, q)
assert Poly((x - p)*(x - q), x, p, q).gens == (x, p, q)
assert Poly((x - p)*(x - q), p, x, q).gens == (p, x, q)
assert Poly((x - p)*(x - q), p, q, x).gens == (p, q, x)
assert Poly((x - p)*(x - q)).gens == (x, p, q)
assert Poly((x - p)*(x - q), sort='x > p > q').gens == (x, p, q)
assert Poly((x - p)*(x - q), sort='p > x > q').gens == (p, x, q)
assert Poly((x - p)*(x - q), sort='p > q > x').gens == (p, q, x)
assert Poly((x - p)*(x - q), x, p, q, sort='p > q > x').gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt='x').gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt='p').gens == (p, x, q)
assert Poly((x - p)*(x - q), wrt='q').gens == (q, x, p)
assert Poly((x - p)*(x - q), wrt=x).gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt=p).gens == (p, x, q)
assert Poly((x - p)*(x - q), wrt=q).gens == (q, x, p)
assert Poly((x - p)*(x - q), x, p, q, wrt='p').gens == (x, p, q)
assert Poly((x - p)*(x - q), wrt='p', sort='q > x').gens == (p, q, x)
assert Poly((x - p)*(x - q), wrt='q', sort='p > x').gens == (q, p, x)
def test_Poly_zero():
assert Poly(x).zero == Poly(0, x, domain=ZZ)
assert Poly(x/2).zero == Poly(0, x, domain=QQ)
def test_Poly_one():
assert Poly(x).one == Poly(1, x, domain=ZZ)
assert Poly(x/2).one == Poly(1, x, domain=QQ)
def test_Poly__unify():
raises(UnificationFailed, lambda: Poly(x)._unify(y))
F3 = FF(3)
F5 = FF(5)
assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=3))[2:] == (
DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3))
assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=5))[2:] == (
DMP([[F5(1)], []], F5), DMP([[F5(1), F5(0)]], F5))
assert Poly(y, x, y)._unify(Poly(x, x, modulus=3))[2:] == (DMP([[F3(1), F3(0)]], F3), DMP([[F3(1)], []], F3))
assert Poly(x, x, modulus=3)._unify(Poly(y, x, y))[2:] == (DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3))
assert Poly(x + 1, x)._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], ZZ), DMP([1, 2], ZZ))
assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ))
assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, x)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ))
assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ))
assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ))
assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ))
assert Poly(x**2 + I, x, domain=ZZ_I).unify(Poly(x**2 + sqrt(2), x, extension=True)) == \
(Poly(x**2 + I, x, domain='QQ<sqrt(2) + I>'), Poly(x**2 + sqrt(2), x, domain='QQ<sqrt(2) + I>'))
F, A, B = field("a,b", ZZ)
assert Poly(a*x, x, domain='ZZ[a]')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \
(DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain()))
assert Poly(a*x, x, domain='ZZ(a)')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \
(DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain()))
raises(CoercionFailed, lambda: Poly(Poly(x**2 + x**2*z, y, field=True), domain='ZZ(x)'))
f = Poly(t**2 + t/3 + x, t, domain='QQ(x)')
g = Poly(t**2 + t/3 + x, t, domain='QQ[x]')
assert f._unify(g)[2:] == (f.rep, f.rep)
def test_Poly_free_symbols():
assert Poly(x**2 + 1).free_symbols == {x}
assert Poly(x**2 + y*z).free_symbols == {x, y, z}
assert Poly(x**2 + y*z, x).free_symbols == {x, y, z}
assert Poly(x**2 + sin(y*z)).free_symbols == {x, y, z}
assert Poly(x**2 + sin(y*z), x).free_symbols == {x, y, z}
assert Poly(x**2 + sin(y*z), x, domain=EX).free_symbols == {x, y, z}
assert Poly(1 + x + x**2, x, y, z).free_symbols == {x}
assert Poly(x + sin(y), z).free_symbols == {x, y}
def test_PurePoly_free_symbols():
assert PurePoly(x**2 + 1).free_symbols == set()
assert PurePoly(x**2 + y*z).free_symbols == set()
assert PurePoly(x**2 + y*z, x).free_symbols == {y, z}
assert PurePoly(x**2 + sin(y*z)).free_symbols == set()
assert PurePoly(x**2 + sin(y*z), x).free_symbols == {y, z}
assert PurePoly(x**2 + sin(y*z), x, domain=EX).free_symbols == {y, z}
def test_Poly__eq__():
assert (Poly(x, x) == Poly(x, x)) is True
assert (Poly(x, x, domain=QQ) == Poly(x, x)) is False
assert (Poly(x, x) == Poly(x, x, domain=QQ)) is False
assert (Poly(x, x, domain=ZZ[a]) == Poly(x, x)) is False
assert (Poly(x, x) == Poly(x, x, domain=ZZ[a])) is False
assert (Poly(x*y, x, y) == Poly(x, x)) is False
assert (Poly(x, x, y) == Poly(x, x)) is False
assert (Poly(x, x) == Poly(x, x, y)) is False
assert (Poly(x**2 + 1, x) == Poly(y**2 + 1, y)) is False
assert (Poly(y**2 + 1, y) == Poly(x**2 + 1, x)) is False
f = Poly(x, x, domain=ZZ)
g = Poly(x, x, domain=QQ)
assert f.eq(g) is False
assert f.ne(g) is True
assert f.eq(g, strict=True) is False
assert f.ne(g, strict=True) is True
t0 = Symbol('t0')
f = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='QQ[x,t0]')
g = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='ZZ(x,t0)')
assert (f == g) is False
def test_PurePoly__eq__():
assert (PurePoly(x, x) == PurePoly(x, x)) is True
assert (PurePoly(x, x, domain=QQ) == PurePoly(x, x)) is True
assert (PurePoly(x, x) == PurePoly(x, x, domain=QQ)) is True
assert (PurePoly(x, x, domain=ZZ[a]) == PurePoly(x, x)) is True
assert (PurePoly(x, x) == PurePoly(x, x, domain=ZZ[a])) is True
assert (PurePoly(x*y, x, y) == PurePoly(x, x)) is False
assert (PurePoly(x, x, y) == PurePoly(x, x)) is False
assert (PurePoly(x, x) == PurePoly(x, x, y)) is False
assert (PurePoly(x**2 + 1, x) == PurePoly(y**2 + 1, y)) is True
assert (PurePoly(y**2 + 1, y) == PurePoly(x**2 + 1, x)) is True
f = PurePoly(x, x, domain=ZZ)
g = PurePoly(x, x, domain=QQ)
assert f.eq(g) is True
assert f.ne(g) is False
assert f.eq(g, strict=True) is False
assert f.ne(g, strict=True) is True
f = PurePoly(x, x, domain=ZZ)
g = PurePoly(y, y, domain=QQ)
assert f.eq(g) is True
assert f.ne(g) is False
assert f.eq(g, strict=True) is False
assert f.ne(g, strict=True) is True
def test_PurePoly_Poly():
assert isinstance(PurePoly(Poly(x**2 + 1)), PurePoly) is True
assert isinstance(Poly(PurePoly(x**2 + 1)), Poly) is True
def test_Poly_get_domain():
assert Poly(2*x).get_domain() == ZZ
assert Poly(2*x, domain='ZZ').get_domain() == ZZ
assert Poly(2*x, domain='QQ').get_domain() == QQ
assert Poly(x/2).get_domain() == QQ
raises(CoercionFailed, lambda: Poly(x/2, domain='ZZ'))
assert Poly(x/2, domain='QQ').get_domain() == QQ
assert isinstance(Poly(0.2*x).get_domain(), RealField)
def test_Poly_set_domain():
assert Poly(2*x + 1).set_domain(ZZ) == Poly(2*x + 1)
assert Poly(2*x + 1).set_domain('ZZ') == Poly(2*x + 1)
assert Poly(2*x + 1).set_domain(QQ) == Poly(2*x + 1, domain='QQ')
assert Poly(2*x + 1).set_domain('QQ') == Poly(2*x + 1, domain='QQ')
assert Poly(Rational(2, 10)*x + Rational(1, 10)).set_domain('RR') == Poly(0.2*x + 0.1)
assert Poly(0.2*x + 0.1).set_domain('QQ') == Poly(Rational(2, 10)*x + Rational(1, 10))
raises(CoercionFailed, lambda: Poly(x/2 + 1).set_domain(ZZ))
raises(CoercionFailed, lambda: Poly(x + 1, modulus=2).set_domain(QQ))
raises(GeneratorsError, lambda: Poly(x*y, x, y).set_domain(ZZ[y]))
def test_Poly_get_modulus():
assert Poly(x**2 + 1, modulus=2).get_modulus() == 2
raises(PolynomialError, lambda: Poly(x**2 + 1).get_modulus())
def test_Poly_set_modulus():
assert Poly(
x**2 + 1, modulus=2).set_modulus(7) == Poly(x**2 + 1, modulus=7)
assert Poly(
x**2 + 5, modulus=7).set_modulus(2) == Poly(x**2 + 1, modulus=2)
assert Poly(x**2 + 1).set_modulus(2) == Poly(x**2 + 1, modulus=2)
raises(CoercionFailed, lambda: Poly(x/2 + 1).set_modulus(2))
def test_Poly_add_ground():
assert Poly(x + 1).add_ground(2) == Poly(x + 3)
def test_Poly_sub_ground():
assert Poly(x + 1).sub_ground(2) == Poly(x - 1)
def test_Poly_mul_ground():
assert Poly(x + 1).mul_ground(2) == Poly(2*x + 2)
def test_Poly_quo_ground():
assert Poly(2*x + 4).quo_ground(2) == Poly(x + 2)
assert Poly(2*x + 3).quo_ground(2) == Poly(x + 1)
def test_Poly_exquo_ground():
assert Poly(2*x + 4).exquo_ground(2) == Poly(x + 2)
raises(ExactQuotientFailed, lambda: Poly(2*x + 3).exquo_ground(2))
def test_Poly_abs():
assert Poly(-x + 1, x).abs() == abs(Poly(-x + 1, x)) == Poly(x + 1, x)
def test_Poly_neg():
assert Poly(-x + 1, x).neg() == -Poly(-x + 1, x) == Poly(x - 1, x)
def test_Poly_add():
assert Poly(0, x).add(Poly(0, x)) == Poly(0, x)
assert Poly(0, x) + Poly(0, x) == Poly(0, x)
assert Poly(1, x).add(Poly(0, x)) == Poly(1, x)
assert Poly(1, x, y) + Poly(0, x) == Poly(1, x, y)
assert Poly(0, x).add(Poly(1, x, y)) == Poly(1, x, y)
assert Poly(0, x, y) + Poly(1, x, y) == Poly(1, x, y)
assert Poly(1, x) + x == Poly(x + 1, x)
with warns_deprecated_sympy():
Poly(1, x) + sin(x)
assert Poly(x, x) + 1 == Poly(x + 1, x)
assert 1 + Poly(x, x) == Poly(x + 1, x)
def test_Poly_sub():
assert Poly(0, x).sub(Poly(0, x)) == Poly(0, x)
assert Poly(0, x) - Poly(0, x) == Poly(0, x)
assert Poly(1, x).sub(Poly(0, x)) == Poly(1, x)
assert Poly(1, x, y) - Poly(0, x) == Poly(1, x, y)
assert Poly(0, x).sub(Poly(1, x, y)) == Poly(-1, x, y)
assert Poly(0, x, y) - Poly(1, x, y) == Poly(-1, x, y)
assert Poly(1, x) - x == Poly(1 - x, x)
with warns_deprecated_sympy():
Poly(1, x) - sin(x)
assert Poly(x, x) - 1 == Poly(x - 1, x)
assert 1 - Poly(x, x) == Poly(1 - x, x)
def test_Poly_mul():
assert Poly(0, x).mul(Poly(0, x)) == Poly(0, x)
assert Poly(0, x) * Poly(0, x) == Poly(0, x)
assert Poly(2, x).mul(Poly(4, x)) == Poly(8, x)
assert Poly(2, x, y) * Poly(4, x) == Poly(8, x, y)
assert Poly(4, x).mul(Poly(2, x, y)) == Poly(8, x, y)
assert Poly(4, x, y) * Poly(2, x, y) == Poly(8, x, y)
assert Poly(1, x) * x == Poly(x, x)
with warns_deprecated_sympy():
Poly(1, x) * sin(x)
assert Poly(x, x) * 2 == Poly(2*x, x)
assert 2 * Poly(x, x) == Poly(2*x, x)
def test_issue_13079():
assert Poly(x)*x == Poly(x**2, x, domain='ZZ')
assert x*Poly(x) == Poly(x**2, x, domain='ZZ')
assert -2*Poly(x) == Poly(-2*x, x, domain='ZZ')
assert S(-2)*Poly(x) == Poly(-2*x, x, domain='ZZ')
assert Poly(x)*S(-2) == Poly(-2*x, x, domain='ZZ')
def test_Poly_sqr():
assert Poly(x*y, x, y).sqr() == Poly(x**2*y**2, x, y)
def test_Poly_pow():
assert Poly(x, x).pow(10) == Poly(x**10, x)
assert Poly(x, x).pow(Integer(10)) == Poly(x**10, x)
assert Poly(2*y, x, y).pow(4) == Poly(16*y**4, x, y)
assert Poly(2*y, x, y).pow(Integer(4)) == Poly(16*y**4, x, y)
assert Poly(7*x*y, x, y)**3 == Poly(343*x**3*y**3, x, y)
raises(TypeError, lambda: Poly(x*y + 1, x, y)**(-1))
raises(TypeError, lambda: Poly(x*y + 1, x, y)**x)
def test_Poly_divmod():
f, g = Poly(x**2), Poly(x)
q, r = g, Poly(0, x)
assert divmod(f, g) == (q, r)
assert f // g == q
assert f % g == r
assert divmod(f, x) == (q, r)
assert f // x == q
assert f % x == r
q, r = Poly(0, x), Poly(2, x)
assert divmod(2, g) == (q, r)
assert 2 // g == q
assert 2 % g == r
assert Poly(x)/Poly(x) == 1
assert Poly(x**2)/Poly(x) == x
assert Poly(x)/Poly(x**2) == 1/x
def test_Poly_eq_ne():
assert (Poly(x + y, x, y) == Poly(x + y, x, y)) is True
assert (Poly(x + y, x) == Poly(x + y, x, y)) is False
assert (Poly(x + y, x, y) == Poly(x + y, x)) is False
assert (Poly(x + y, x) == Poly(x + y, x)) is True
assert (Poly(x + y, y) == Poly(x + y, y)) is True
assert (Poly(x + y, x, y) == x + y) is True
assert (Poly(x + y, x) == x + y) is True
assert (Poly(x + y, x, y) == x + y) is True
assert (Poly(x + y, x) == x + y) is True
assert (Poly(x + y, y) == x + y) is True
assert (Poly(x + y, x, y) != Poly(x + y, x, y)) is False
assert (Poly(x + y, x) != Poly(x + y, x, y)) is True
assert (Poly(x + y, x, y) != Poly(x + y, x)) is True
assert (Poly(x + y, x) != Poly(x + y, x)) is False
assert (Poly(x + y, y) != Poly(x + y, y)) is False
assert (Poly(x + y, x, y) != x + y) is False
assert (Poly(x + y, x) != x + y) is False
assert (Poly(x + y, x, y) != x + y) is False
assert (Poly(x + y, x) != x + y) is False
assert (Poly(x + y, y) != x + y) is False
assert (Poly(x, x) == sin(x)) is False
assert (Poly(x, x) != sin(x)) is True
def test_Poly_nonzero():
assert not bool(Poly(0, x)) is True
assert not bool(Poly(1, x)) is False
def test_Poly_properties():
assert Poly(0, x).is_zero is True
assert Poly(1, x).is_zero is False
assert Poly(1, x).is_one is True
assert Poly(2, x).is_one is False
assert Poly(x - 1, x).is_sqf is True
assert Poly((x - 1)**2, x).is_sqf is False
assert Poly(x - 1, x).is_monic is True
assert Poly(2*x - 1, x).is_monic is False
assert Poly(3*x + 2, x).is_primitive is True
assert Poly(4*x + 2, x).is_primitive is False
assert Poly(1, x).is_ground is True
assert Poly(x, x).is_ground is False
assert Poly(x + y + z + 1).is_linear is True
assert Poly(x*y*z + 1).is_linear is False
assert Poly(x*y + z + 1).is_quadratic is True
assert Poly(x*y*z + 1).is_quadratic is False
assert Poly(x*y).is_monomial is True
assert Poly(x*y + 1).is_monomial is False
assert Poly(x**2 + x*y).is_homogeneous is True
assert Poly(x**3 + x*y).is_homogeneous is False
assert Poly(x).is_univariate is True
assert Poly(x*y).is_univariate is False
assert Poly(x*y).is_multivariate is True
assert Poly(x).is_multivariate is False
assert Poly(
x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1).is_cyclotomic is False
assert Poly(
x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1).is_cyclotomic is True
def test_Poly_is_irreducible():
assert Poly(x**2 + x + 1).is_irreducible is True
assert Poly(x**2 + 2*x + 1).is_irreducible is False
assert Poly(7*x + 3, modulus=11).is_irreducible is True
assert Poly(7*x**2 + 3*x + 1, modulus=11).is_irreducible is False
def test_Poly_subs():
assert Poly(x + 1).subs(x, 0) == 1
assert Poly(x + 1).subs(x, x) == Poly(x + 1)
assert Poly(x + 1).subs(x, y) == Poly(y + 1)
assert Poly(x*y, x).subs(y, x) == x**2
assert Poly(x*y, x).subs(x, y) == y**2
def test_Poly_replace():
assert Poly(x + 1).replace(x) == Poly(x + 1)
assert Poly(x + 1).replace(y) == Poly(y + 1)
raises(PolynomialError, lambda: Poly(x + y).replace(z))
assert Poly(x + 1).replace(x, x) == Poly(x + 1)
assert Poly(x + 1).replace(x, y) == Poly(y + 1)
assert Poly(x + y).replace(x, x) == Poly(x + y)
assert Poly(x + y).replace(x, z) == Poly(z + y, z, y)
assert Poly(x + y).replace(y, y) == Poly(x + y)
assert Poly(x + y).replace(y, z) == Poly(x + z, x, z)
assert Poly(x + y).replace(z, t) == Poly(x + y)
raises(PolynomialError, lambda: Poly(x + y).replace(x, y))
assert Poly(x + y, x).replace(x, z) == Poly(z + y, z)
assert Poly(x + y, y).replace(y, z) == Poly(x + z, z)
raises(PolynomialError, lambda: Poly(x + y, x).replace(x, y))
raises(PolynomialError, lambda: Poly(x + y, y).replace(y, x))
def test_Poly_reorder():
raises(PolynomialError, lambda: Poly(x + y).reorder(x, z))
assert Poly(x + y, x, y).reorder(x, y) == Poly(x + y, x, y)
assert Poly(x + y, x, y).reorder(y, x) == Poly(x + y, y, x)
assert Poly(x + y, y, x).reorder(x, y) == Poly(x + y, x, y)
assert Poly(x + y, y, x).reorder(y, x) == Poly(x + y, y, x)
assert Poly(x + y, x, y).reorder(wrt=x) == Poly(x + y, x, y)
assert Poly(x + y, x, y).reorder(wrt=y) == Poly(x + y, y, x)
def test_Poly_ltrim():
f = Poly(y**2 + y*z**2, x, y, z).ltrim(y)
assert f.as_expr() == y**2 + y*z**2 and f.gens == (y, z)
assert Poly(x*y - x, z, x, y).ltrim(1) == Poly(x*y - x, x, y)
raises(PolynomialError, lambda: Poly(x*y**2 + y**2, x, y).ltrim(y))
raises(PolynomialError, lambda: Poly(x*y - x, x, y).ltrim(-1))
def test_Poly_has_only_gens():
assert Poly(x*y + 1, x, y, z).has_only_gens(x, y) is True
assert Poly(x*y + z, x, y, z).has_only_gens(x, y) is False
raises(GeneratorsError, lambda: Poly(x*y**2 + y**2, x, y).has_only_gens(t))
def test_Poly_to_ring():
assert Poly(2*x + 1, domain='ZZ').to_ring() == Poly(2*x + 1, domain='ZZ')
assert Poly(2*x + 1, domain='QQ').to_ring() == Poly(2*x + 1, domain='ZZ')
raises(CoercionFailed, lambda: Poly(x/2 + 1).to_ring())
raises(DomainError, lambda: Poly(2*x + 1, modulus=3).to_ring())
def test_Poly_to_field():
assert Poly(2*x + 1, domain='ZZ').to_field() == Poly(2*x + 1, domain='QQ')
assert Poly(2*x + 1, domain='QQ').to_field() == Poly(2*x + 1, domain='QQ')
assert Poly(x/2 + 1, domain='QQ').to_field() == Poly(x/2 + 1, domain='QQ')
assert Poly(2*x + 1, modulus=3).to_field() == Poly(2*x + 1, modulus=3)
assert Poly(2.0*x + 1.0).to_field() == Poly(2.0*x + 1.0)
def test_Poly_to_exact():
assert Poly(2*x).to_exact() == Poly(2*x)
assert Poly(x/2).to_exact() == Poly(x/2)
assert Poly(0.1*x).to_exact() == Poly(x/10)
def test_Poly_retract():
f = Poly(x**2 + 1, x, domain=QQ[y])
assert f.retract() == Poly(x**2 + 1, x, domain='ZZ')
assert f.retract(field=True) == Poly(x**2 + 1, x, domain='QQ')
assert Poly(0, x, y).retract() == Poly(0, x, y)
def test_Poly_slice():
f = Poly(x**3 + 2*x**2 + 3*x + 4)
assert f.slice(0, 0) == Poly(0, x)
assert f.slice(0, 1) == Poly(4, x)
assert f.slice(0, 2) == Poly(3*x + 4, x)
assert f.slice(0, 3) == Poly(2*x**2 + 3*x + 4, x)
assert f.slice(0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x)
assert f.slice(x, 0, 0) == Poly(0, x)
assert f.slice(x, 0, 1) == Poly(4, x)
assert f.slice(x, 0, 2) == Poly(3*x + 4, x)
assert f.slice(x, 0, 3) == Poly(2*x**2 + 3*x + 4, x)
assert f.slice(x, 0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x)
def test_Poly_coeffs():
assert Poly(0, x).coeffs() == [0]
assert Poly(1, x).coeffs() == [1]
assert Poly(2*x + 1, x).coeffs() == [2, 1]
assert Poly(7*x**2 + 2*x + 1, x).coeffs() == [7, 2, 1]
assert Poly(7*x**4 + 2*x + 1, x).coeffs() == [7, 2, 1]
assert Poly(x*y**7 + 2*x**2*y**3).coeffs('lex') == [2, 1]
assert Poly(x*y**7 + 2*x**2*y**3).coeffs('grlex') == [1, 2]
def test_Poly_monoms():
assert Poly(0, x).monoms() == [(0,)]
assert Poly(1, x).monoms() == [(0,)]
assert Poly(2*x + 1, x).monoms() == [(1,), (0,)]
assert Poly(7*x**2 + 2*x + 1, x).monoms() == [(2,), (1,), (0,)]
assert Poly(7*x**4 + 2*x + 1, x).monoms() == [(4,), (1,), (0,)]
assert Poly(x*y**7 + 2*x**2*y**3).monoms('lex') == [(2, 3), (1, 7)]
assert Poly(x*y**7 + 2*x**2*y**3).monoms('grlex') == [(1, 7), (2, 3)]
def test_Poly_terms():
assert Poly(0, x).terms() == [((0,), 0)]
assert Poly(1, x).terms() == [((0,), 1)]
assert Poly(2*x + 1, x).terms() == [((1,), 2), ((0,), 1)]
assert Poly(7*x**2 + 2*x + 1, x).terms() == [((2,), 7), ((1,), 2), ((0,), 1)]
assert Poly(7*x**4 + 2*x + 1, x).terms() == [((4,), 7), ((1,), 2), ((0,), 1)]
assert Poly(
x*y**7 + 2*x**2*y**3).terms('lex') == [((2, 3), 2), ((1, 7), 1)]
assert Poly(
x*y**7 + 2*x**2*y**3).terms('grlex') == [((1, 7), 1), ((2, 3), 2)]
def test_Poly_all_coeffs():
assert Poly(0, x).all_coeffs() == [0]
assert Poly(1, x).all_coeffs() == [1]
assert Poly(2*x + 1, x).all_coeffs() == [2, 1]
assert Poly(7*x**2 + 2*x + 1, x).all_coeffs() == [7, 2, 1]
assert Poly(7*x**4 + 2*x + 1, x).all_coeffs() == [7, 0, 0, 2, 1]
def test_Poly_all_monoms():
assert Poly(0, x).all_monoms() == [(0,)]
assert Poly(1, x).all_monoms() == [(0,)]
assert Poly(2*x + 1, x).all_monoms() == [(1,), (0,)]
assert Poly(7*x**2 + 2*x + 1, x).all_monoms() == [(2,), (1,), (0,)]
assert Poly(7*x**4 + 2*x + 1, x).all_monoms() == [(4,), (3,), (2,), (1,), (0,)]
def test_Poly_all_terms():
assert Poly(0, x).all_terms() == [((0,), 0)]
assert Poly(1, x).all_terms() == [((0,), 1)]
assert Poly(2*x + 1, x).all_terms() == [((1,), 2), ((0,), 1)]
assert Poly(7*x**2 + 2*x + 1, x).all_terms() == \
[((2,), 7), ((1,), 2), ((0,), 1)]
assert Poly(7*x**4 + 2*x + 1, x).all_terms() == \
[((4,), 7), ((3,), 0), ((2,), 0), ((1,), 2), ((0,), 1)]
def test_Poly_termwise():
f = Poly(x**2 + 20*x + 400)
g = Poly(x**2 + 2*x + 4)
def func(monom, coeff):
(k,) = monom
return coeff//10**(2 - k)
assert f.termwise(func) == g
def func(monom, coeff):
(k,) = monom
return (k,), coeff//10**(2 - k)
assert f.termwise(func) == g
def test_Poly_length():
assert Poly(0, x).length() == 0
assert Poly(1, x).length() == 1
assert Poly(x, x).length() == 1
assert Poly(x + 1, x).length() == 2
assert Poly(x**2 + 1, x).length() == 2
assert Poly(x**2 + x + 1, x).length() == 3
def test_Poly_as_dict():
assert Poly(0, x).as_dict() == {}
assert Poly(0, x, y, z).as_dict() == {}
assert Poly(1, x).as_dict() == {(0,): 1}
assert Poly(1, x, y, z).as_dict() == {(0, 0, 0): 1}
assert Poly(x**2 + 3, x).as_dict() == {(2,): 1, (0,): 3}
assert Poly(x**2 + 3, x, y, z).as_dict() == {(2, 0, 0): 1, (0, 0, 0): 3}
assert Poly(3*x**2*y*z**3 + 4*x*y + 5*x*z).as_dict() == {(2, 1, 3): 3,
(1, 1, 0): 4, (1, 0, 1): 5}
def test_Poly_as_expr():
assert Poly(0, x).as_expr() == 0
assert Poly(0, x, y, z).as_expr() == 0
assert Poly(1, x).as_expr() == 1
assert Poly(1, x, y, z).as_expr() == 1
assert Poly(x**2 + 3, x).as_expr() == x**2 + 3
assert Poly(x**2 + 3, x, y, z).as_expr() == x**2 + 3
assert Poly(
3*x**2*y*z**3 + 4*x*y + 5*x*z).as_expr() == 3*x**2*y*z**3 + 4*x*y + 5*x*z
f = Poly(x**2 + 2*x*y**2 - y, x, y)
assert f.as_expr() == -y + x**2 + 2*x*y**2
assert f.as_expr({x: 5}) == 25 - y + 10*y**2
assert f.as_expr({y: 6}) == -6 + 72*x + x**2
assert f.as_expr({x: 5, y: 6}) == 379
assert f.as_expr(5, 6) == 379
raises(GeneratorsError, lambda: f.as_expr({z: 7}))
def test_Poly_lift():
assert Poly(x**4 - I*x + 17*I, x, gaussian=True).lift() == \
Poly(x**16 + 2*x**10 + 578*x**8 + x**4 - 578*x**2 + 83521,
x, domain='QQ')
def test_Poly_deflate():
assert Poly(0, x).deflate() == ((1,), Poly(0, x))
assert Poly(1, x).deflate() == ((1,), Poly(1, x))
assert Poly(x, x).deflate() == ((1,), Poly(x, x))
assert Poly(x**2, x).deflate() == ((2,), Poly(x, x))
assert Poly(x**17, x).deflate() == ((17,), Poly(x, x))
assert Poly(
x**2*y*z**11 + x**4*z**11).deflate() == ((2, 1, 11), Poly(x*y*z + x**2*z))
def test_Poly_inject():
f = Poly(x**2*y + x*y**3 + x*y + 1, x)
assert f.inject() == Poly(x**2*y + x*y**3 + x*y + 1, x, y)
assert f.inject(front=True) == Poly(y**3*x + y*x**2 + y*x + 1, y, x)
def test_Poly_eject():
f = Poly(x**2*y + x*y**3 + x*y + 1, x, y)
assert f.eject(x) == Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]')
assert f.eject(y) == Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]')
ex = x + y + z + t + w
g = Poly(ex, x, y, z, t, w)
assert g.eject(x) == Poly(ex, y, z, t, w, domain='ZZ[x]')
assert g.eject(x, y) == Poly(ex, z, t, w, domain='ZZ[x, y]')
assert g.eject(x, y, z) == Poly(ex, t, w, domain='ZZ[x, y, z]')
assert g.eject(w) == Poly(ex, x, y, z, t, domain='ZZ[w]')
assert g.eject(t, w) == Poly(ex, x, y, z, domain='ZZ[t, w]')
assert g.eject(z, t, w) == Poly(ex, x, y, domain='ZZ[z, t, w]')
raises(DomainError, lambda: Poly(x*y, x, y, domain=ZZ[z]).eject(y))
raises(NotImplementedError, lambda: Poly(x*y, x, y, z).eject(y))
def test_Poly_exclude():
assert Poly(x, x, y).exclude() == Poly(x, x)
assert Poly(x*y, x, y).exclude() == Poly(x*y, x, y)
assert Poly(1, x, y).exclude() == Poly(1, x, y)
def test_Poly__gen_to_level():
assert Poly(1, x, y)._gen_to_level(-2) == 0
assert Poly(1, x, y)._gen_to_level(-1) == 1
assert Poly(1, x, y)._gen_to_level( 0) == 0
assert Poly(1, x, y)._gen_to_level( 1) == 1
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(-3))
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level( 2))
assert Poly(1, x, y)._gen_to_level(x) == 0
assert Poly(1, x, y)._gen_to_level(y) == 1
assert Poly(1, x, y)._gen_to_level('x') == 0
assert Poly(1, x, y)._gen_to_level('y') == 1
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(z))
raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level('z'))
def test_Poly_degree():
assert Poly(0, x).degree() is -oo
assert Poly(1, x).degree() == 0
assert Poly(x, x).degree() == 1
assert Poly(0, x).degree(gen=0) is -oo
assert Poly(1, x).degree(gen=0) == 0
assert Poly(x, x).degree(gen=0) == 1
assert Poly(0, x).degree(gen=x) is -oo
assert Poly(1, x).degree(gen=x) == 0
assert Poly(x, x).degree(gen=x) == 1
assert Poly(0, x).degree(gen='x') is -oo
assert Poly(1, x).degree(gen='x') == 0
assert Poly(x, x).degree(gen='x') == 1
raises(PolynomialError, lambda: Poly(1, x).degree(gen=1))
raises(PolynomialError, lambda: Poly(1, x).degree(gen=y))
raises(PolynomialError, lambda: Poly(1, x).degree(gen='y'))
assert Poly(1, x, y).degree() == 0
assert Poly(2*y, x, y).degree() == 0
assert Poly(x*y, x, y).degree() == 1
assert Poly(1, x, y).degree(gen=x) == 0
assert Poly(2*y, x, y).degree(gen=x) == 0
assert Poly(x*y, x, y).degree(gen=x) == 1
assert Poly(1, x, y).degree(gen=y) == 0
assert Poly(2*y, x, y).degree(gen=y) == 1
assert Poly(x*y, x, y).degree(gen=y) == 1
assert degree(0, x) is -oo
assert degree(1, x) == 0
assert degree(x, x) == 1
assert degree(x*y**2, x) == 1
assert degree(x*y**2, y) == 2
assert degree(x*y**2, z) == 0
assert degree(pi) == 1
raises(TypeError, lambda: degree(y**2 + x**3))
raises(TypeError, lambda: degree(y**2 + x**3, 1))
raises(PolynomialError, lambda: degree(x, 1.1))
raises(PolynomialError, lambda: degree(x**2/(x**3 + 1), x))
assert degree(Poly(0,x),z) is -oo
assert degree(Poly(1,x),z) == 0
assert degree(Poly(x**2+y**3,y)) == 3
assert degree(Poly(y**2 + x**3, y, x), 1) == 3
assert degree(Poly(y**2 + x**3, x), z) == 0
assert degree(Poly(y**2 + x**3 + z**4, x), z) == 4
def test_Poly_degree_list():
assert Poly(0, x).degree_list() == (-oo,)
assert Poly(0, x, y).degree_list() == (-oo, -oo)
assert Poly(0, x, y, z).degree_list() == (-oo, -oo, -oo)
assert Poly(1, x).degree_list() == (0,)
assert Poly(1, x, y).degree_list() == (0, 0)
assert Poly(1, x, y, z).degree_list() == (0, 0, 0)
assert Poly(x**2*y + x**3*z**2 + 1).degree_list() == (3, 1, 2)
assert degree_list(1, x) == (0,)
assert degree_list(x, x) == (1,)
assert degree_list(x*y**2) == (1, 2)
raises(ComputationFailed, lambda: degree_list(1))
def test_Poly_total_degree():
assert Poly(x**2*y + x**3*z**2 + 1).total_degree() == 5
assert Poly(x**2 + z**3).total_degree() == 3
assert Poly(x*y*z + z**4).total_degree() == 4
assert Poly(x**3 + x + 1).total_degree() == 3
assert total_degree(x*y + z**3) == 3
assert total_degree(x*y + z**3, x, y) == 2
assert total_degree(1) == 0
assert total_degree(Poly(y**2 + x**3 + z**4)) == 4
assert total_degree(Poly(y**2 + x**3 + z**4, x)) == 3
assert total_degree(Poly(y**2 + x**3 + z**4, x), z) == 4
assert total_degree(Poly(x**9 + x*z*y + x**3*z**2 + z**7,x), z) == 7
def test_Poly_homogenize():
assert Poly(x**2+y).homogenize(z) == Poly(x**2+y*z)
assert Poly(x+y).homogenize(z) == Poly(x+y, x, y, z)
assert Poly(x+y**2).homogenize(y) == Poly(x*y+y**2)
def test_Poly_homogeneous_order():
assert Poly(0, x, y).homogeneous_order() is -oo
assert Poly(1, x, y).homogeneous_order() == 0
assert Poly(x, x, y).homogeneous_order() == 1
assert Poly(x*y, x, y).homogeneous_order() == 2
assert Poly(x + 1, x, y).homogeneous_order() is None
assert Poly(x*y + x, x, y).homogeneous_order() is None
assert Poly(x**5 + 2*x**3*y**2 + 9*x*y**4).homogeneous_order() == 5
assert Poly(x**5 + 2*x**3*y**3 + 9*x*y**4).homogeneous_order() is None
def test_Poly_LC():
assert Poly(0, x).LC() == 0
assert Poly(1, x).LC() == 1
assert Poly(2*x**2 + x, x).LC() == 2
assert Poly(x*y**7 + 2*x**2*y**3).LC('lex') == 2
assert Poly(x*y**7 + 2*x**2*y**3).LC('grlex') == 1
assert LC(x*y**7 + 2*x**2*y**3, order='lex') == 2
assert LC(x*y**7 + 2*x**2*y**3, order='grlex') == 1
def test_Poly_TC():
assert Poly(0, x).TC() == 0
assert Poly(1, x).TC() == 1
assert Poly(2*x**2 + x, x).TC() == 0
def test_Poly_EC():
assert Poly(0, x).EC() == 0
assert Poly(1, x).EC() == 1
assert Poly(2*x**2 + x, x).EC() == 1
assert Poly(x*y**7 + 2*x**2*y**3).EC('lex') == 1
assert Poly(x*y**7 + 2*x**2*y**3).EC('grlex') == 2
def test_Poly_coeff():
assert Poly(0, x).coeff_monomial(1) == 0
assert Poly(0, x).coeff_monomial(x) == 0
assert Poly(1, x).coeff_monomial(1) == 1
assert Poly(1, x).coeff_monomial(x) == 0
assert Poly(x**8, x).coeff_monomial(1) == 0
assert Poly(x**8, x).coeff_monomial(x**7) == 0
assert Poly(x**8, x).coeff_monomial(x**8) == 1
assert Poly(x**8, x).coeff_monomial(x**9) == 0
assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(1) == 1
assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(x*y**2) == 3
p = Poly(24*x*y*exp(8) + 23*x, x, y)
assert p.coeff_monomial(x) == 23
assert p.coeff_monomial(y) == 0
assert p.coeff_monomial(x*y) == 24*exp(8)
assert p.as_expr().coeff(x) == 24*y*exp(8) + 23
raises(NotImplementedError, lambda: p.coeff(x))
raises(ValueError, lambda: Poly(x + 1).coeff_monomial(0))
raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x))
raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x*y))
def test_Poly_nth():
assert Poly(0, x).nth(0) == 0
assert Poly(0, x).nth(1) == 0
assert Poly(1, x).nth(0) == 1
assert Poly(1, x).nth(1) == 0
assert Poly(x**8, x).nth(0) == 0
assert Poly(x**8, x).nth(7) == 0
assert Poly(x**8, x).nth(8) == 1
assert Poly(x**8, x).nth(9) == 0
assert Poly(3*x*y**2 + 1, x, y).nth(0, 0) == 1
assert Poly(3*x*y**2 + 1, x, y).nth(1, 2) == 3
raises(ValueError, lambda: Poly(x*y + 1, x, y).nth(1))
def test_Poly_LM():
assert Poly(0, x).LM() == (0,)
assert Poly(1, x).LM() == (0,)
assert Poly(2*x**2 + x, x).LM() == (2,)
assert Poly(x*y**7 + 2*x**2*y**3).LM('lex') == (2, 3)
assert Poly(x*y**7 + 2*x**2*y**3).LM('grlex') == (1, 7)
assert LM(x*y**7 + 2*x**2*y**3, order='lex') == x**2*y**3
assert LM(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7
def test_Poly_LM_custom_order():
f = Poly(x**2*y**3*z + x**2*y*z**3 + x*y*z + 1)
rev_lex = lambda monom: tuple(reversed(monom))
assert f.LM(order='lex') == (2, 3, 1)
assert f.LM(order=rev_lex) == (2, 1, 3)
def test_Poly_EM():
assert Poly(0, x).EM() == (0,)
assert Poly(1, x).EM() == (0,)
assert Poly(2*x**2 + x, x).EM() == (1,)
assert Poly(x*y**7 + 2*x**2*y**3).EM('lex') == (1, 7)
assert Poly(x*y**7 + 2*x**2*y**3).EM('grlex') == (2, 3)
def test_Poly_LT():
assert Poly(0, x).LT() == ((0,), 0)
assert Poly(1, x).LT() == ((0,), 1)
assert Poly(2*x**2 + x, x).LT() == ((2,), 2)
assert Poly(x*y**7 + 2*x**2*y**3).LT('lex') == ((2, 3), 2)
assert Poly(x*y**7 + 2*x**2*y**3).LT('grlex') == ((1, 7), 1)
assert LT(x*y**7 + 2*x**2*y**3, order='lex') == 2*x**2*y**3
assert LT(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7
def test_Poly_ET():
assert Poly(0, x).ET() == ((0,), 0)
assert Poly(1, x).ET() == ((0,), 1)
assert Poly(2*x**2 + x, x).ET() == ((1,), 1)
assert Poly(x*y**7 + 2*x**2*y**3).ET('lex') == ((1, 7), 1)
assert Poly(x*y**7 + 2*x**2*y**3).ET('grlex') == ((2, 3), 2)
def test_Poly_max_norm():
assert Poly(-1, x).max_norm() == 1
assert Poly( 0, x).max_norm() == 0
assert Poly( 1, x).max_norm() == 1
def test_Poly_l1_norm():
assert Poly(-1, x).l1_norm() == 1
assert Poly( 0, x).l1_norm() == 0
assert Poly( 1, x).l1_norm() == 1
def test_Poly_clear_denoms():
coeff, poly = Poly(x + 2, x).clear_denoms()
assert coeff == 1 and poly == Poly(
x + 2, x, domain='ZZ') and poly.get_domain() == ZZ
coeff, poly = Poly(x/2 + 1, x).clear_denoms()
assert coeff == 2 and poly == Poly(
x + 2, x, domain='QQ') and poly.get_domain() == QQ
coeff, poly = Poly(x/2 + 1, x).clear_denoms(convert=True)
assert coeff == 2 and poly == Poly(
x + 2, x, domain='ZZ') and poly.get_domain() == ZZ
coeff, poly = Poly(x/y + 1, x).clear_denoms(convert=True)
assert coeff == y and poly == Poly(
x + y, x, domain='ZZ[y]') and poly.get_domain() == ZZ[y]
coeff, poly = Poly(x/3 + sqrt(2), x, domain='EX').clear_denoms()
assert coeff == 3 and poly == Poly(
x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX
coeff, poly = Poly(
x/3 + sqrt(2), x, domain='EX').clear_denoms(convert=True)
assert coeff == 3 and poly == Poly(
x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX
def test_Poly_rat_clear_denoms():
f = Poly(x**2/y + 1, x)
g = Poly(x**3 + y, x)
assert f.rat_clear_denoms(g) == \
(Poly(x**2 + y, x), Poly(y*x**3 + y**2, x))
f = f.set_domain(EX)
g = g.set_domain(EX)
assert f.rat_clear_denoms(g) == (f, g)
def test_issue_20427():
f = Poly(-117968192370600*18**(S(1)/3)/(217603955769048*(24201 +
253*sqrt(9165))**(S(1)/3) + 2273005839412*sqrt(9165)*(24201 +
253*sqrt(9165))**(S(1)/3)) - 15720318185*2**(S(2)/3)*3**(S(1)/3)*(24201
+ 253*sqrt(9165))**(S(2)/3)/(217603955769048*(24201 + 253*sqrt(9165))**
(S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3))
+ 15720318185*12**(S(1)/3)*(24201 + 253*sqrt(9165))**(S(2)/3)/(
217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412*
sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) + 117968192370600*2**(
S(1)/3)*3**(S(2)/3)/(217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3)
+ 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)), x)
assert f == Poly(0, x, domain='EX')
def test_Poly_integrate():
assert Poly(x + 1).integrate() == Poly(x**2/2 + x)
assert Poly(x + 1).integrate(x) == Poly(x**2/2 + x)
assert Poly(x + 1).integrate((x, 1)) == Poly(x**2/2 + x)
assert Poly(x*y + 1).integrate(x) == Poly(x**2*y/2 + x)
assert Poly(x*y + 1).integrate(y) == Poly(x*y**2/2 + y)
assert Poly(x*y + 1).integrate(x, x) == Poly(x**3*y/6 + x**2/2)
assert Poly(x*y + 1).integrate(y, y) == Poly(x*y**3/6 + y**2/2)
assert Poly(x*y + 1).integrate((x, 2)) == Poly(x**3*y/6 + x**2/2)
assert Poly(x*y + 1).integrate((y, 2)) == Poly(x*y**3/6 + y**2/2)
assert Poly(x*y + 1).integrate(x, y) == Poly(x**2*y**2/4 + x*y)
assert Poly(x*y + 1).integrate(y, x) == Poly(x**2*y**2/4 + x*y)
def test_Poly_diff():
assert Poly(x**2 + x).diff() == Poly(2*x + 1)
assert Poly(x**2 + x).diff(x) == Poly(2*x + 1)
assert Poly(x**2 + x).diff((x, 1)) == Poly(2*x + 1)
assert Poly(x**2*y**2 + x*y).diff(x) == Poly(2*x*y**2 + y)
assert Poly(x**2*y**2 + x*y).diff(y) == Poly(2*x**2*y + x)
assert Poly(x**2*y**2 + x*y).diff(x, x) == Poly(2*y**2, x, y)
assert Poly(x**2*y**2 + x*y).diff(y, y) == Poly(2*x**2, x, y)
assert Poly(x**2*y**2 + x*y).diff((x, 2)) == Poly(2*y**2, x, y)
assert Poly(x**2*y**2 + x*y).diff((y, 2)) == Poly(2*x**2, x, y)
assert Poly(x**2*y**2 + x*y).diff(x, y) == Poly(4*x*y + 1)
assert Poly(x**2*y**2 + x*y).diff(y, x) == Poly(4*x*y + 1)
def test_issue_9585():
assert diff(Poly(x**2 + x)) == Poly(2*x + 1)
assert diff(Poly(x**2 + x), x, evaluate=False) == \
Derivative(Poly(x**2 + x), x)
assert Derivative(Poly(x**2 + x), x).doit() == Poly(2*x + 1)
def test_Poly_eval():
assert Poly(0, x).eval(7) == 0
assert Poly(1, x).eval(7) == 1
assert Poly(x, x).eval(7) == 7
assert Poly(0, x).eval(0, 7) == 0
assert Poly(1, x).eval(0, 7) == 1
assert Poly(x, x).eval(0, 7) == 7
assert Poly(0, x).eval(x, 7) == 0
assert Poly(1, x).eval(x, 7) == 1
assert Poly(x, x).eval(x, 7) == 7
assert Poly(0, x).eval('x', 7) == 0
assert Poly(1, x).eval('x', 7) == 1
assert Poly(x, x).eval('x', 7) == 7
raises(PolynomialError, lambda: Poly(1, x).eval(1, 7))
raises(PolynomialError, lambda: Poly(1, x).eval(y, 7))
raises(PolynomialError, lambda: Poly(1, x).eval('y', 7))
assert Poly(123, x, y).eval(7) == Poly(123, y)
assert Poly(2*y, x, y).eval(7) == Poly(2*y, y)
assert Poly(x*y, x, y).eval(7) == Poly(7*y, y)
assert Poly(123, x, y).eval(x, 7) == Poly(123, y)
assert Poly(2*y, x, y).eval(x, 7) == Poly(2*y, y)
assert Poly(x*y, x, y).eval(x, 7) == Poly(7*y, y)
assert Poly(123, x, y).eval(y, 7) == Poly(123, x)
assert Poly(2*y, x, y).eval(y, 7) == Poly(14, x)
assert Poly(x*y, x, y).eval(y, 7) == Poly(7*x, x)
assert Poly(x*y + y, x, y).eval({x: 7}) == Poly(8*y, y)
assert Poly(x*y + y, x, y).eval({y: 7}) == Poly(7*x + 7, x)
assert Poly(x*y + y, x, y).eval({x: 6, y: 7}) == 49
assert Poly(x*y + y, x, y).eval({x: 7, y: 6}) == 48
assert Poly(x*y + y, x, y).eval((6, 7)) == 49
assert Poly(x*y + y, x, y).eval([6, 7]) == 49
assert Poly(x + 1, domain='ZZ').eval(S.Half) == Rational(3, 2)
assert Poly(x + 1, domain='ZZ').eval(sqrt(2)) == sqrt(2) + 1
raises(ValueError, lambda: Poly(x*y + y, x, y).eval((6, 7, 8)))
raises(DomainError, lambda: Poly(x + 1, domain='ZZ').eval(S.Half, auto=False))
# issue 6344
alpha = Symbol('alpha')
result = (2*alpha*z - 2*alpha + z**2 + 3)/(z**2 - 2*z + 1)
f = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, domain='ZZ[alpha]')
assert f.eval((z + 1)/(z - 1)) == result
g = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, y, domain='ZZ[alpha]')
assert g.eval((z + 1)/(z - 1)) == Poly(result, y, domain='ZZ(alpha,z)')
def test_Poly___call__():
f = Poly(2*x*y + 3*x + y + 2*z)
assert f(2) == Poly(5*y + 2*z + 6)
assert f(2, 5) == Poly(2*z + 31)
assert f(2, 5, 7) == 45
def test_parallel_poly_from_expr():
assert parallel_poly_from_expr(
[x - 1, x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[Poly(x - 1, x), x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x - 1, Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr([Poly(
x - 1, x), Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x - 1, x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr([Poly(
x - 1, x), x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr([x - 1, Poly(
x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr([Poly(x - 1, x), Poly(
x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)]
assert parallel_poly_from_expr(
[x - 1, x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[Poly(x - 1, x), x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x - 1, Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[Poly(x - 1, x), Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)]
assert parallel_poly_from_expr(
[x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr(
[x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr(
[Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr(
[Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)]
assert parallel_poly_from_expr([Poly(x, x, y), Poly(y, x, y)], x, y, order='lex')[0] == \
[Poly(x, x, y, domain='ZZ'), Poly(y, x, y, domain='ZZ')]
raises(PolificationFailed, lambda: parallel_poly_from_expr([0, 1]))
def test_pdiv():
f, g = x**2 - y**2, x - y
q, r = x + y, 0
F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ]
assert F.pdiv(G) == (Q, R)
assert F.prem(G) == R
assert F.pquo(G) == Q
assert F.pexquo(G) == Q
assert pdiv(f, g) == (q, r)
assert prem(f, g) == r
assert pquo(f, g) == q
assert pexquo(f, g) == q
assert pdiv(f, g, x, y) == (q, r)
assert prem(f, g, x, y) == r
assert pquo(f, g, x, y) == q
assert pexquo(f, g, x, y) == q
assert pdiv(f, g, (x, y)) == (q, r)
assert prem(f, g, (x, y)) == r
assert pquo(f, g, (x, y)) == q
assert pexquo(f, g, (x, y)) == q
assert pdiv(F, G) == (Q, R)
assert prem(F, G) == R
assert pquo(F, G) == Q
assert pexquo(F, G) == Q
assert pdiv(f, g, polys=True) == (Q, R)
assert prem(f, g, polys=True) == R
assert pquo(f, g, polys=True) == Q
assert pexquo(f, g, polys=True) == Q
assert pdiv(F, G, polys=False) == (q, r)
assert prem(F, G, polys=False) == r
assert pquo(F, G, polys=False) == q
assert pexquo(F, G, polys=False) == q
raises(ComputationFailed, lambda: pdiv(4, 2))
raises(ComputationFailed, lambda: prem(4, 2))
raises(ComputationFailed, lambda: pquo(4, 2))
raises(ComputationFailed, lambda: pexquo(4, 2))
def test_div():
f, g = x**2 - y**2, x - y
q, r = x + y, 0
F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ]
assert F.div(G) == (Q, R)
assert F.rem(G) == R
assert F.quo(G) == Q
assert F.exquo(G) == Q
assert div(f, g) == (q, r)
assert rem(f, g) == r
assert quo(f, g) == q
assert exquo(f, g) == q
assert div(f, g, x, y) == (q, r)
assert rem(f, g, x, y) == r
assert quo(f, g, x, y) == q
assert exquo(f, g, x, y) == q
assert div(f, g, (x, y)) == (q, r)
assert rem(f, g, (x, y)) == r
assert quo(f, g, (x, y)) == q
assert exquo(f, g, (x, y)) == q
assert div(F, G) == (Q, R)
assert rem(F, G) == R
assert quo(F, G) == Q
assert exquo(F, G) == Q
assert div(f, g, polys=True) == (Q, R)
assert rem(f, g, polys=True) == R
assert quo(f, g, polys=True) == Q
assert exquo(f, g, polys=True) == Q
assert div(F, G, polys=False) == (q, r)
assert rem(F, G, polys=False) == r
assert quo(F, G, polys=False) == q
assert exquo(F, G, polys=False) == q
raises(ComputationFailed, lambda: div(4, 2))
raises(ComputationFailed, lambda: rem(4, 2))
raises(ComputationFailed, lambda: quo(4, 2))
raises(ComputationFailed, lambda: exquo(4, 2))
f, g = x**2 + 1, 2*x - 4
qz, rz = 0, x**2 + 1
qq, rq = x/2 + 1, 5
assert div(f, g) == (qq, rq)
assert div(f, g, auto=True) == (qq, rq)
assert div(f, g, auto=False) == (qz, rz)
assert div(f, g, domain=ZZ) == (qz, rz)
assert div(f, g, domain=QQ) == (qq, rq)
assert div(f, g, domain=ZZ, auto=True) == (qq, rq)
assert div(f, g, domain=ZZ, auto=False) == (qz, rz)
assert div(f, g, domain=QQ, auto=True) == (qq, rq)
assert div(f, g, domain=QQ, auto=False) == (qq, rq)
assert rem(f, g) == rq
assert rem(f, g, auto=True) == rq
assert rem(f, g, auto=False) == rz
assert rem(f, g, domain=ZZ) == rz
assert rem(f, g, domain=QQ) == rq
assert rem(f, g, domain=ZZ, auto=True) == rq
assert rem(f, g, domain=ZZ, auto=False) == rz
assert rem(f, g, domain=QQ, auto=True) == rq
assert rem(f, g, domain=QQ, auto=False) == rq
assert quo(f, g) == qq
assert quo(f, g, auto=True) == qq
assert quo(f, g, auto=False) == qz
assert quo(f, g, domain=ZZ) == qz
assert quo(f, g, domain=QQ) == qq
assert quo(f, g, domain=ZZ, auto=True) == qq
assert quo(f, g, domain=ZZ, auto=False) == qz
assert quo(f, g, domain=QQ, auto=True) == qq
assert quo(f, g, domain=QQ, auto=False) == qq
f, g, q = x**2, 2*x, x/2
assert exquo(f, g) == q
assert exquo(f, g, auto=True) == q
raises(ExactQuotientFailed, lambda: exquo(f, g, auto=False))
raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ))
assert exquo(f, g, domain=QQ) == q
assert exquo(f, g, domain=ZZ, auto=True) == q
raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ, auto=False))
assert exquo(f, g, domain=QQ, auto=True) == q
assert exquo(f, g, domain=QQ, auto=False) == q
f, g = Poly(x**2), Poly(x)
q, r = f.div(g)
assert q.get_domain().is_ZZ and r.get_domain().is_ZZ
r = f.rem(g)
assert r.get_domain().is_ZZ
q = f.quo(g)
assert q.get_domain().is_ZZ
q = f.exquo(g)
assert q.get_domain().is_ZZ
f, g = Poly(x+y, x), Poly(2*x+y, x)
q, r = f.div(g)
assert q.get_domain().is_Frac and r.get_domain().is_Frac
# https://github.com/sympy/sympy/issues/19579
p = Poly(2+3*I, x, domain=ZZ_I)
q = Poly(1-I, x, domain=ZZ_I)
assert p.div(q, auto=False) == \
(Poly(0, x, domain='ZZ_I'), Poly(2 + 3*I, x, domain='ZZ_I'))
assert p.div(q, auto=True) == \
(Poly(-S(1)/2 + 5*I/2, x, domain='QQ_I'), Poly(0, x, domain='QQ_I'))
def test_issue_7864():
q, r = div(a, .408248290463863*a)
assert abs(q - 2.44948974278318) < 1e-14
assert r == 0
def test_gcdex():
f, g = 2*x, x**2 - 16
s, t, h = x/32, Rational(-1, 16), 1
F, G, S, T, H = [ Poly(u, x, domain='QQ') for u in (f, g, s, t, h) ]
assert F.half_gcdex(G) == (S, H)
assert F.gcdex(G) == (S, T, H)
assert F.invert(G) == S
assert half_gcdex(f, g) == (s, h)
assert gcdex(f, g) == (s, t, h)
assert invert(f, g) == s
assert half_gcdex(f, g, x) == (s, h)
assert gcdex(f, g, x) == (s, t, h)
assert invert(f, g, x) == s
assert half_gcdex(f, g, (x,)) == (s, h)
assert gcdex(f, g, (x,)) == (s, t, h)
assert invert(f, g, (x,)) == s
assert half_gcdex(F, G) == (S, H)
assert gcdex(F, G) == (S, T, H)
assert invert(F, G) == S
assert half_gcdex(f, g, polys=True) == (S, H)
assert gcdex(f, g, polys=True) == (S, T, H)
assert invert(f, g, polys=True) == S
assert half_gcdex(F, G, polys=False) == (s, h)
assert gcdex(F, G, polys=False) == (s, t, h)
assert invert(F, G, polys=False) == s
assert half_gcdex(100, 2004) == (-20, 4)
assert gcdex(100, 2004) == (-20, 1, 4)
assert invert(3, 7) == 5
raises(DomainError, lambda: half_gcdex(x + 1, 2*x + 1, auto=False))
raises(DomainError, lambda: gcdex(x + 1, 2*x + 1, auto=False))
raises(DomainError, lambda: invert(x + 1, 2*x + 1, auto=False))
def test_revert():
f = Poly(1 - x**2/2 + x**4/24 - x**6/720)
g = Poly(61*x**6/720 + 5*x**4/24 + x**2/2 + 1)
assert f.revert(8) == g
def test_subresultants():
f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2
F, G, H = Poly(f), Poly(g), Poly(h)
assert F.subresultants(G) == [F, G, H]
assert subresultants(f, g) == [f, g, h]
assert subresultants(f, g, x) == [f, g, h]
assert subresultants(f, g, (x,)) == [f, g, h]
assert subresultants(F, G) == [F, G, H]
assert subresultants(f, g, polys=True) == [F, G, H]
assert subresultants(F, G, polys=False) == [f, g, h]
raises(ComputationFailed, lambda: subresultants(4, 2))
def test_resultant():
f, g, h = x**2 - 2*x + 1, x**2 - 1, 0
F, G = Poly(f), Poly(g)
assert F.resultant(G) == h
assert resultant(f, g) == h
assert resultant(f, g, x) == h
assert resultant(f, g, (x,)) == h
assert resultant(F, G) == h
assert resultant(f, g, polys=True) == h
assert resultant(F, G, polys=False) == h
assert resultant(f, g, includePRS=True) == (h, [f, g, 2*x - 2])
f, g, h = x - a, x - b, a - b
F, G, H = Poly(f), Poly(g), Poly(h)
assert F.resultant(G) == H
assert resultant(f, g) == h
assert resultant(f, g, x) == h
assert resultant(f, g, (x,)) == h
assert resultant(F, G) == H
assert resultant(f, g, polys=True) == H
assert resultant(F, G, polys=False) == h
raises(ComputationFailed, lambda: resultant(4, 2))
def test_discriminant():
f, g = x**3 + 3*x**2 + 9*x - 13, -11664
F = Poly(f)
assert F.discriminant() == g
assert discriminant(f) == g
assert discriminant(f, x) == g
assert discriminant(f, (x,)) == g
assert discriminant(F) == g
assert discriminant(f, polys=True) == g
assert discriminant(F, polys=False) == g
f, g = a*x**2 + b*x + c, b**2 - 4*a*c
F, G = Poly(f), Poly(g)
assert F.discriminant() == G
assert discriminant(f) == g
assert discriminant(f, x, a, b, c) == g
assert discriminant(f, (x, a, b, c)) == g
assert discriminant(F) == G
assert discriminant(f, polys=True) == G
assert discriminant(F, polys=False) == g
raises(ComputationFailed, lambda: discriminant(4))
def test_dispersion():
# We test only the API here. For more mathematical
# tests see the dedicated test file.
fp = poly((x + 1)*(x + 2), x)
assert sorted(fp.dispersionset()) == [0, 1]
assert fp.dispersion() == 1
fp = poly(x**4 - 3*x**2 + 1, x)
gp = fp.shift(-3)
assert sorted(fp.dispersionset(gp)) == [2, 3, 4]
assert fp.dispersion(gp) == 4
def test_gcd_list():
F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2]
assert gcd_list(F) == x - 1
assert gcd_list(F, polys=True) == Poly(x - 1)
assert gcd_list([]) == 0
assert gcd_list([1, 2]) == 1
assert gcd_list([4, 6, 8]) == 2
assert gcd_list([x*(y + 42) - x*y - x*42]) == 0
gcd = gcd_list([], x)
assert gcd.is_Number and gcd is S.Zero
gcd = gcd_list([], x, polys=True)
assert gcd.is_Poly and gcd.is_zero
a = sqrt(2)
assert gcd_list([a, -a]) == gcd_list([-a, a]) == a
raises(ComputationFailed, lambda: gcd_list([], polys=True))
def test_lcm_list():
F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2]
assert lcm_list(F) == x**5 - x**4 - 2*x**3 - x**2 + x + 2
assert lcm_list(F, polys=True) == Poly(x**5 - x**4 - 2*x**3 - x**2 + x + 2)
assert lcm_list([]) == 1
assert lcm_list([1, 2]) == 2
assert lcm_list([4, 6, 8]) == 24
assert lcm_list([x*(y + 42) - x*y - x*42]) == 0
lcm = lcm_list([], x)
assert lcm.is_Number and lcm is S.One
lcm = lcm_list([], x, polys=True)
assert lcm.is_Poly and lcm.is_one
raises(ComputationFailed, lambda: lcm_list([], polys=True))
def test_gcd():
f, g = x**3 - 1, x**2 - 1
s, t = x**2 + x + 1, x + 1
h, r = x - 1, x**4 + x**3 - x - 1
F, G, S, T, H, R = [ Poly(u) for u in (f, g, s, t, h, r) ]
assert F.cofactors(G) == (H, S, T)
assert F.gcd(G) == H
assert F.lcm(G) == R
assert cofactors(f, g) == (h, s, t)
assert gcd(f, g) == h
assert lcm(f, g) == r
assert cofactors(f, g, x) == (h, s, t)
assert gcd(f, g, x) == h
assert lcm(f, g, x) == r
assert cofactors(f, g, (x,)) == (h, s, t)
assert gcd(f, g, (x,)) == h
assert lcm(f, g, (x,)) == r
assert cofactors(F, G) == (H, S, T)
assert gcd(F, G) == H
assert lcm(F, G) == R
assert cofactors(f, g, polys=True) == (H, S, T)
assert gcd(f, g, polys=True) == H
assert lcm(f, g, polys=True) == R
assert cofactors(F, G, polys=False) == (h, s, t)
assert gcd(F, G, polys=False) == h
assert lcm(F, G, polys=False) == r
f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0
h, s, t = g, 1.0*x + 1.0, 1.0
assert cofactors(f, g) == (h, s, t)
assert gcd(f, g) == h
assert lcm(f, g) == f
f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0
h, s, t = g, 1.0*x + 1.0, 1.0
assert cofactors(f, g) == (h, s, t)
assert gcd(f, g) == h
assert lcm(f, g) == f
assert cofactors(8, 6) == (2, 4, 3)
assert gcd(8, 6) == 2
assert lcm(8, 6) == 24
f, g = x**2 - 3*x - 4, x**3 - 4*x**2 + x - 4
l = x**4 - 3*x**3 - 3*x**2 - 3*x - 4
h, s, t = x - 4, x + 1, x**2 + 1
assert cofactors(f, g, modulus=11) == (h, s, t)
assert gcd(f, g, modulus=11) == h
assert lcm(f, g, modulus=11) == l
f, g = x**2 + 8*x + 7, x**3 + 7*x**2 + x + 7
l = x**4 + 8*x**3 + 8*x**2 + 8*x + 7
h, s, t = x + 7, x + 1, x**2 + 1
assert cofactors(f, g, modulus=11, symmetric=False) == (h, s, t)
assert gcd(f, g, modulus=11, symmetric=False) == h
assert lcm(f, g, modulus=11, symmetric=False) == l
a, b = sqrt(2), -sqrt(2)
assert gcd(a, b) == gcd(b, a) == sqrt(2)
a, b = sqrt(-2), -sqrt(-2)
assert gcd(a, b) == gcd(b, a) == sqrt(2)
assert gcd(Poly(x - 2, x), Poly(I*x, x)) == Poly(1, x, domain=ZZ_I)
raises(TypeError, lambda: gcd(x))
raises(TypeError, lambda: lcm(x))
def test_gcd_numbers_vs_polys():
assert isinstance(gcd(3, 9), Integer)
assert isinstance(gcd(3*x, 9), Integer)
assert gcd(3, 9) == 3
assert gcd(3*x, 9) == 3
assert isinstance(gcd(Rational(3, 2), Rational(9, 4)), Rational)
assert isinstance(gcd(Rational(3, 2)*x, Rational(9, 4)), Rational)
assert gcd(Rational(3, 2), Rational(9, 4)) == Rational(3, 4)
assert gcd(Rational(3, 2)*x, Rational(9, 4)) == 1
assert isinstance(gcd(3.0, 9.0), Float)
assert isinstance(gcd(3.0*x, 9.0), Float)
assert gcd(3.0, 9.0) == 1.0
assert gcd(3.0*x, 9.0) == 1.0
# partial fix of 20597
assert gcd(Mul(2, 3, evaluate=False), 2) == 2
def test_terms_gcd():
assert terms_gcd(1) == 1
assert terms_gcd(1, x) == 1
assert terms_gcd(x - 1) == x - 1
assert terms_gcd(-x - 1) == -x - 1
assert terms_gcd(2*x + 3) == 2*x + 3
assert terms_gcd(6*x + 4) == Mul(2, 3*x + 2, evaluate=False)
assert terms_gcd(x**3*y + x*y**3) == x*y*(x**2 + y**2)
assert terms_gcd(2*x**3*y + 2*x*y**3) == 2*x*y*(x**2 + y**2)
assert terms_gcd(x**3*y/2 + x*y**3/2) == x*y/2*(x**2 + y**2)
assert terms_gcd(x**3*y + 2*x*y**3) == x*y*(x**2 + 2*y**2)
assert terms_gcd(2*x**3*y + 4*x*y**3) == 2*x*y*(x**2 + 2*y**2)
assert terms_gcd(2*x**3*y/3 + 4*x*y**3/5) == x*y*Rational(2, 15)*(5*x**2 + 6*y**2)
assert terms_gcd(2.0*x**3*y + 4.1*x*y**3) == x*y*(2.0*x**2 + 4.1*y**2)
assert _aresame(terms_gcd(2.0*x + 3), 2.0*x + 3)
assert terms_gcd((3 + 3*x)*(x + x*y), expand=False) == \
(3*x + 3)*(x*y + x)
assert terms_gcd((3 + 3*x)*(x + x*sin(3 + 3*y)), expand=False, deep=True) == \
3*x*(x + 1)*(sin(Mul(3, y + 1, evaluate=False)) + 1)
assert terms_gcd(sin(x + x*y), deep=True) == \
sin(x*(y + 1))
eq = Eq(2*x, 2*y + 2*z*y)
assert terms_gcd(eq) == Eq(2*x, 2*y*(z + 1))
assert terms_gcd(eq, deep=True) == Eq(2*x, 2*y*(z + 1))
raises(TypeError, lambda: terms_gcd(x < 2))
def test_trunc():
f, g = x**5 + 2*x**4 + 3*x**3 + 4*x**2 + 5*x + 6, x**5 - x**4 + x**2 - x
F, G = Poly(f), Poly(g)
assert F.trunc(3) == G
assert trunc(f, 3) == g
assert trunc(f, 3, x) == g
assert trunc(f, 3, (x,)) == g
assert trunc(F, 3) == G
assert trunc(f, 3, polys=True) == G
assert trunc(F, 3, polys=False) == g
f, g = 6*x**5 + 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, -x**4 + x**3 - x + 1
F, G = Poly(f), Poly(g)
assert F.trunc(3) == G
assert trunc(f, 3) == g
assert trunc(f, 3, x) == g
assert trunc(f, 3, (x,)) == g
assert trunc(F, 3) == G
assert trunc(f, 3, polys=True) == G
assert trunc(F, 3, polys=False) == g
f = Poly(x**2 + 2*x + 3, modulus=5)
assert f.trunc(2) == Poly(x**2 + 1, modulus=5)
def test_monic():
f, g = 2*x - 1, x - S.Half
F, G = Poly(f, domain='QQ'), Poly(g)
assert F.monic() == G
assert monic(f) == g
assert monic(f, x) == g
assert monic(f, (x,)) == g
assert monic(F) == G
assert monic(f, polys=True) == G
assert monic(F, polys=False) == g
raises(ComputationFailed, lambda: monic(4))
assert monic(2*x**2 + 6*x + 4, auto=False) == x**2 + 3*x + 2
raises(ExactQuotientFailed, lambda: monic(2*x + 6*x + 1, auto=False))
assert monic(2.0*x**2 + 6.0*x + 4.0) == 1.0*x**2 + 3.0*x + 2.0
assert monic(2*x**2 + 3*x + 4, modulus=5) == x**2 - x + 2
def test_content():
f, F = 4*x + 2, Poly(4*x + 2)
assert F.content() == 2
assert content(f) == 2
raises(ComputationFailed, lambda: content(4))
f = Poly(2*x, modulus=3)
assert f.content() == 1
def test_primitive():
f, g = 4*x + 2, 2*x + 1
F, G = Poly(f), Poly(g)
assert F.primitive() == (2, G)
assert primitive(f) == (2, g)
assert primitive(f, x) == (2, g)
assert primitive(f, (x,)) == (2, g)
assert primitive(F) == (2, G)
assert primitive(f, polys=True) == (2, G)
assert primitive(F, polys=False) == (2, g)
raises(ComputationFailed, lambda: primitive(4))
f = Poly(2*x, modulus=3)
g = Poly(2.0*x, domain=RR)
assert f.primitive() == (1, f)
assert g.primitive() == (1.0, g)
assert primitive(S('-3*x/4 + y + 11/8')) == \
S('(1/8, -6*x + 8*y + 11)')
def test_compose():
f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9
g = x**4 - 2*x + 9
h = x**3 + 5*x
F, G, H = map(Poly, (f, g, h))
assert G.compose(H) == F
assert compose(g, h) == f
assert compose(g, h, x) == f
assert compose(g, h, (x,)) == f
assert compose(G, H) == F
assert compose(g, h, polys=True) == F
assert compose(G, H, polys=False) == f
assert F.decompose() == [G, H]
assert decompose(f) == [g, h]
assert decompose(f, x) == [g, h]
assert decompose(f, (x,)) == [g, h]
assert decompose(F) == [G, H]
assert decompose(f, polys=True) == [G, H]
assert decompose(F, polys=False) == [g, h]
raises(ComputationFailed, lambda: compose(4, 2))
raises(ComputationFailed, lambda: decompose(4))
assert compose(x**2 - y**2, x - y, x, y) == x**2 - 2*x*y
assert compose(x**2 - y**2, x - y, y, x) == -y**2 + 2*x*y
def test_shift():
assert Poly(x**2 - 2*x + 1, x).shift(2) == Poly(x**2 + 2*x + 1, x)
def test_transform():
# Also test that 3-way unification is done correctly
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \
Poly(4, x) == \
cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - 1)))
assert Poly(x**2 - x/2 + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \
Poly(3*x**2/2 + Rational(5, 2), x) == \
cancel((x - 1)**2*(x**2 - x/2 + 1).subs(x, (x + 1)/(x - 1)))
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + S.Half), Poly(x - 1)) == \
Poly(Rational(9, 4), x) == \
cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + S.Half)/(x - 1)))
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - S.Half)) == \
Poly(Rational(9, 4), x) == \
cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - S.Half)))
# Unify ZZ, QQ, and RR
assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1.0), Poly(x - S.Half)) == \
Poly(Rational(9, 4), x, domain='RR') == \
cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1.0)/(x - S.Half)))
raises(ValueError, lambda: Poly(x*y).transform(Poly(x + 1), Poly(x - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(y + 1), Poly(x - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(y - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(x*y + 1), Poly(x - 1)))
raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(x*y - 1)))
def test_sturm():
f, F = x, Poly(x, domain='QQ')
g, G = 1, Poly(1, x, domain='QQ')
assert F.sturm() == [F, G]
assert sturm(f) == [f, g]
assert sturm(f, x) == [f, g]
assert sturm(f, (x,)) == [f, g]
assert sturm(F) == [F, G]
assert sturm(f, polys=True) == [F, G]
assert sturm(F, polys=False) == [f, g]
raises(ComputationFailed, lambda: sturm(4))
raises(DomainError, lambda: sturm(f, auto=False))
f = Poly(S(1024)/(15625*pi**8)*x**5
- S(4096)/(625*pi**8)*x**4
+ S(32)/(15625*pi**4)*x**3
- S(128)/(625*pi**4)*x**2
+ Rational(1, 62500)*x
- Rational(1, 625), x, domain='ZZ(pi)')
assert sturm(f) == \
[Poly(x**3 - 100*x**2 + pi**4/64*x - 25*pi**4/16, x, domain='ZZ(pi)'),
Poly(3*x**2 - 200*x + pi**4/64, x, domain='ZZ(pi)'),
Poly((Rational(20000, 9) - pi**4/96)*x + 25*pi**4/18, x, domain='ZZ(pi)'),
Poly((-3686400000000*pi**4 - 11520000*pi**8 - 9*pi**12)/(26214400000000 - 245760000*pi**4 + 576*pi**8), x, domain='ZZ(pi)')]
def test_gff():
f = x**5 + 2*x**4 - x**3 - 2*x**2
assert Poly(f).gff_list() == [(Poly(x), 1), (Poly(x + 2), 4)]
assert gff_list(f) == [(x, 1), (x + 2, 4)]
raises(NotImplementedError, lambda: gff(f))
f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5)
assert Poly(f).gff_list() == [(
Poly(x**2 - 5*x + 4), 1), (Poly(x**2 - 5*x + 4), 2), (Poly(x), 3)]
assert gff_list(f) == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)]
raises(NotImplementedError, lambda: gff(f))
def test_norm():
a, b = sqrt(2), sqrt(3)
f = Poly(a*x + b*y, x, y, extension=(a, b))
assert f.norm() == Poly(4*x**4 - 12*x**2*y**2 + 9*y**4, x, y, domain='QQ')
def test_sqf_norm():
assert sqf_norm(x**2 - 2, extension=sqrt(3)) == \
(1, x**2 - 2*sqrt(3)*x + 1, x**4 - 10*x**2 + 1)
assert sqf_norm(x**2 - 3, extension=sqrt(2)) == \
(1, x**2 - 2*sqrt(2)*x - 1, x**4 - 10*x**2 + 1)
assert Poly(x**2 - 2, extension=sqrt(3)).sqf_norm() == \
(1, Poly(x**2 - 2*sqrt(3)*x + 1, x, extension=sqrt(3)),
Poly(x**4 - 10*x**2 + 1, x, domain='QQ'))
assert Poly(x**2 - 3, extension=sqrt(2)).sqf_norm() == \
(1, Poly(x**2 - 2*sqrt(2)*x - 1, x, extension=sqrt(2)),
Poly(x**4 - 10*x**2 + 1, x, domain='QQ'))
def test_sqf():
f = x**5 - x**3 - x**2 + 1
g = x**3 + 2*x**2 + 2*x + 1
h = x - 1
p = x**4 + x**3 - x - 1
F, G, H, P = map(Poly, (f, g, h, p))
assert F.sqf_part() == P
assert sqf_part(f) == p
assert sqf_part(f, x) == p
assert sqf_part(f, (x,)) == p
assert sqf_part(F) == P
assert sqf_part(f, polys=True) == P
assert sqf_part(F, polys=False) == p
assert F.sqf_list() == (1, [(G, 1), (H, 2)])
assert sqf_list(f) == (1, [(g, 1), (h, 2)])
assert sqf_list(f, x) == (1, [(g, 1), (h, 2)])
assert sqf_list(f, (x,)) == (1, [(g, 1), (h, 2)])
assert sqf_list(F) == (1, [(G, 1), (H, 2)])
assert sqf_list(f, polys=True) == (1, [(G, 1), (H, 2)])
assert sqf_list(F, polys=False) == (1, [(g, 1), (h, 2)])
assert F.sqf_list_include() == [(G, 1), (H, 2)]
raises(ComputationFailed, lambda: sqf_part(4))
assert sqf(1) == 1
assert sqf_list(1) == (1, [])
assert sqf((2*x**2 + 2)**7) == 128*(x**2 + 1)**7
assert sqf(f) == g*h**2
assert sqf(f, x) == g*h**2
assert sqf(f, (x,)) == g*h**2
d = x**2 + y**2
assert sqf(f/d) == (g*h**2)/d
assert sqf(f/d, x) == (g*h**2)/d
assert sqf(f/d, (x,)) == (g*h**2)/d
assert sqf(x - 1) == x - 1
assert sqf(-x - 1) == -x - 1
assert sqf(x - 1) == x - 1
assert sqf(6*x - 10) == Mul(2, 3*x - 5, evaluate=False)
assert sqf((6*x - 10)/(3*x - 6)) == Rational(2, 3)*((3*x - 5)/(x - 2))
assert sqf(Poly(x**2 - 2*x + 1)) == (x - 1)**2
f = 3 + x - x*(1 + x) + x**2
assert sqf(f) == 3
f = (x**2 + 2*x + 1)**20000000000
assert sqf(f) == (x + 1)**40000000000
assert sqf_list(f) == (1, [(x + 1, 40000000000)])
def test_factor():
f = x**5 - x**3 - x**2 + 1
u = x + 1
v = x - 1
w = x**2 + x + 1
F, U, V, W = map(Poly, (f, u, v, w))
assert F.factor_list() == (1, [(U, 1), (V, 2), (W, 1)])
assert factor_list(f) == (1, [(u, 1), (v, 2), (w, 1)])
assert factor_list(f, x) == (1, [(u, 1), (v, 2), (w, 1)])
assert factor_list(f, (x,)) == (1, [(u, 1), (v, 2), (w, 1)])
assert factor_list(F) == (1, [(U, 1), (V, 2), (W, 1)])
assert factor_list(f, polys=True) == (1, [(U, 1), (V, 2), (W, 1)])
assert factor_list(F, polys=False) == (1, [(u, 1), (v, 2), (w, 1)])
assert F.factor_list_include() == [(U, 1), (V, 2), (W, 1)]
assert factor_list(1) == (1, [])
assert factor_list(6) == (6, [])
assert factor_list(sqrt(3), x) == (sqrt(3), [])
assert factor_list((-1)**x, x) == (1, [(-1, x)])
assert factor_list((2*x)**y, x) == (1, [(2, y), (x, y)])
assert factor_list(sqrt(x*y), x) == (1, [(x*y, S.Half)])
assert factor(6) == 6 and factor(6).is_Integer
assert factor_list(3*x) == (3, [(x, 1)])
assert factor_list(3*x**2) == (3, [(x, 2)])
assert factor(3*x) == 3*x
assert factor(3*x**2) == 3*x**2
assert factor((2*x**2 + 2)**7) == 128*(x**2 + 1)**7
assert factor(f) == u*v**2*w
assert factor(f, x) == u*v**2*w
assert factor(f, (x,)) == u*v**2*w
g, p, q, r = x**2 - y**2, x - y, x + y, x**2 + 1
assert factor(f/g) == (u*v**2*w)/(p*q)
assert factor(f/g, x) == (u*v**2*w)/(p*q)
assert factor(f/g, (x,)) == (u*v**2*w)/(p*q)
p = Symbol('p', positive=True)
i = Symbol('i', integer=True)
r = Symbol('r', real=True)
assert factor(sqrt(x*y)).is_Pow is True
assert factor(sqrt(3*x**2 - 3)) == sqrt(3)*sqrt((x - 1)*(x + 1))
assert factor(sqrt(3*x**2 + 3)) == sqrt(3)*sqrt(x**2 + 1)
assert factor((y*x**2 - y)**i) == y**i*(x - 1)**i*(x + 1)**i
assert factor((y*x**2 + y)**i) == y**i*(x**2 + 1)**i
assert factor((y*x**2 - y)**t) == (y*(x - 1)*(x + 1))**t
assert factor((y*x**2 + y)**t) == (y*(x**2 + 1))**t
f = sqrt(expand((r**2 + 1)*(p + 1)*(p - 1)*(p - 2)**3))
g = sqrt((p - 2)**3*(p - 1))*sqrt(p + 1)*sqrt(r**2 + 1)
assert factor(f) == g
assert factor(g) == g
g = (x - 1)**5*(r**2 + 1)
f = sqrt(expand(g))
assert factor(f) == sqrt(g)
f = Poly(sin(1)*x + 1, x, domain=EX)
assert f.factor_list() == (1, [(f, 1)])
f = x**4 + 1
assert factor(f) == f
assert factor(f, extension=I) == (x**2 - I)*(x**2 + I)
assert factor(f, gaussian=True) == (x**2 - I)*(x**2 + I)
assert factor(
f, extension=sqrt(2)) == (x**2 + sqrt(2)*x + 1)*(x**2 - sqrt(2)*x + 1)
assert factor(x**2 + 4*I*x - 4) == (x + 2*I)**2
f = x**2 + 2*I*x - 4
assert factor(f) == f
f = 8192*x**2 + x*(22656 + 175232*I) - 921416 + 242313*I
f_zzi = I*(x*(64 - 64*I) + 773 + 596*I)**2
f_qqi = 8192*(x + S(177)/128 + 1369*I/128)**2
assert factor(f) == f_zzi
assert factor(f, domain=ZZ_I) == f_zzi
assert factor(f, domain=QQ_I) == f_qqi
f = x**2 + 2*sqrt(2)*x + 2
assert factor(f, extension=sqrt(2)) == (x + sqrt(2))**2
assert factor(f**3, extension=sqrt(2)) == (x + sqrt(2))**6
assert factor(x**2 - 2*y**2, extension=sqrt(2)) == \
(x + sqrt(2)*y)*(x - sqrt(2)*y)
assert factor(2*x**2 - 4*y**2, extension=sqrt(2)) == \
2*((x + sqrt(2)*y)*(x - sqrt(2)*y))
assert factor(x - 1) == x - 1
assert factor(-x - 1) == -x - 1
assert factor(x - 1) == x - 1
assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False)
assert factor(x**11 + x + 1, modulus=65537, symmetric=True) == \
(x**2 + x + 1)*(x**9 - x**8 + x**6 - x**5 + x**3 - x** 2 + 1)
assert factor(x**11 + x + 1, modulus=65537, symmetric=False) == \
(x**2 + x + 1)*(x**9 + 65536*x**8 + x**6 + 65536*x**5 +
x**3 + 65536*x** 2 + 1)
f = x/pi + x*sin(x)/pi
g = y/(pi**2 + 2*pi + 1) + y*sin(x)/(pi**2 + 2*pi + 1)
assert factor(f) == x*(sin(x) + 1)/pi
assert factor(g) == y*(sin(x) + 1)/(pi + 1)**2
assert factor(Eq(
x**2 + 2*x + 1, x**3 + 1)) == Eq((x + 1)**2, (x + 1)*(x**2 - x + 1))
f = (x**2 - 1)/(x**2 + 4*x + 4)
assert factor(f) == (x + 1)*(x - 1)/(x + 2)**2
assert factor(f, x) == (x + 1)*(x - 1)/(x + 2)**2
f = 3 + x - x*(1 + x) + x**2
assert factor(f) == 3
assert factor(f, x) == 3
assert factor(1/(x**2 + 2*x + 1/x) - 1) == -((1 - x + 2*x**2 +
x**3)/(1 + 2*x**2 + x**3))
assert factor(f, expand=False) == f
raises(PolynomialError, lambda: factor(f, x, expand=False))
raises(FlagError, lambda: factor(x**2 - 1, polys=True))
assert factor([x, Eq(x**2 - y**2, Tuple(x**2 - z**2, 1/x + 1/y))]) == \
[x, Eq((x - y)*(x + y), Tuple((x - z)*(x + z), (x + y)/x/y))]
assert not isinstance(
Poly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True
assert isinstance(
PurePoly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True
assert factor(sqrt(-x)) == sqrt(-x)
# issue 5917
e = (-2*x*(-x + 1)*(x - 1)*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2)*(x**2*(x -
1) - x*(x - 1) - x) - (-2*x**2*(x - 1)**2 - x*(-x + 1)*(-x*(-x + 1) +
x*(x - 1)))*(x**2*(x - 1)**4 - x*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2)))
assert factor(e) == 0
# deep option
assert factor(sin(x**2 + x) + x, deep=True) == sin(x*(x + 1)) + x
assert factor(sin(x**2 + x)*x, deep=True) == sin(x*(x + 1))*x
assert factor(sqrt(x**2)) == sqrt(x**2)
# issue 13149
assert factor(expand((0.5*x+1)*(0.5*y+1))) == Mul(1.0, 0.5*x + 1.0,
0.5*y + 1.0, evaluate = False)
assert factor(expand((0.5*x+0.5)**2)) == 0.25*(1.0*x + 1.0)**2
eq = x**2*y**2 + 11*x**2*y + 30*x**2 + 7*x*y**2 + 77*x*y + 210*x + 12*y**2 + 132*y + 360
assert factor(eq, x) == (x + 3)*(x + 4)*(y**2 + 11*y + 30)
assert factor(eq, x, deep=True) == (x + 3)*(x + 4)*(y**2 + 11*y + 30)
assert factor(eq, y, deep=True) == (y + 5)*(y + 6)*(x**2 + 7*x + 12)
# fraction option
f = 5*x + 3*exp(2 - 7*x)
assert factor(f, deep=True) == factor(f, deep=True, fraction=True)
assert factor(f, deep=True, fraction=False) == 5*x + 3*exp(2)*exp(-7*x)
assert factor_list(x**3 - x*y**2, t, w, x) == (
1, [(x, 1), (x - y, 1), (x + y, 1)])
def test_factor_large():
f = (x**2 + 4*x + 4)**10000000*(x**2 + 1)*(x**2 + 2*x + 1)**1234567
g = ((x**2 + 2*x + 1)**3000*y**2 + (x**2 + 2*x + 1)**3000*2*y + (
x**2 + 2*x + 1)**3000)
assert factor(f) == (x + 2)**20000000*(x**2 + 1)*(x + 1)**2469134
assert factor(g) == (x + 1)**6000*(y + 1)**2
assert factor_list(
f) == (1, [(x + 1, 2469134), (x + 2, 20000000), (x**2 + 1, 1)])
assert factor_list(g) == (1, [(y + 1, 2), (x + 1, 6000)])
f = (x**2 - y**2)**200000*(x**7 + 1)
g = (x**2 + y**2)**200000*(x**7 + 1)
assert factor(f) == \
(x + 1)*(x - y)**200000*(x + y)**200000*(x**6 - x**5 +
x**4 - x**3 + x**2 - x + 1)
assert factor(g, gaussian=True) == \
(x + 1)*(x - I*y)**200000*(x + I*y)**200000*(x**6 - x**5 +
x**4 - x**3 + x**2 - x + 1)
assert factor_list(f) == \
(1, [(x + 1, 1), (x - y, 200000), (x + y, 200000), (x**6 -
x**5 + x**4 - x**3 + x**2 - x + 1, 1)])
assert factor_list(g, gaussian=True) == \
(1, [(x + 1, 1), (x - I*y, 200000), (x + I*y, 200000), (
x**6 - x**5 + x**4 - x**3 + x**2 - x + 1, 1)])
def test_factor_noeval():
assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False)
assert factor((6*x - 10)/(3*x - 6)) == Mul(Rational(2, 3), 3*x - 5, 1/(x - 2))
def test_intervals():
assert intervals(0) == []
assert intervals(1) == []
assert intervals(x, sqf=True) == [(0, 0)]
assert intervals(x) == [((0, 0), 1)]
assert intervals(x**128) == [((0, 0), 128)]
assert intervals([x**2, x**4]) == [((0, 0), {0: 2, 1: 4})]
f = Poly((x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257)))
assert f.intervals(sqf=True) == [(-1, 0), (14, 15)]
assert f.intervals() == [((-1, 0), 1), ((14, 15), 1)]
assert f.intervals(fast=True, sqf=True) == [(-1, 0), (14, 15)]
assert f.intervals(fast=True) == [((-1, 0), 1), ((14, 15), 1)]
assert f.intervals(eps=Rational(1, 10)) == f.intervals(eps=0.1) == \
[((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert f.intervals(eps=Rational(1, 100)) == f.intervals(eps=0.01) == \
[((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert f.intervals(eps=Rational(1, 1000)) == f.intervals(eps=0.001) == \
[((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert f.intervals(eps=Rational(1, 10000)) == f.intervals(eps=0.0001) == \
[((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
f = (x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257))
assert intervals(f, sqf=True) == [(-1, 0), (14, 15)]
assert intervals(f) == [((-1, 0), 1), ((14, 15), 1)]
assert intervals(f, eps=Rational(1, 10)) == intervals(f, eps=0.1) == \
[((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert intervals(f, eps=Rational(1, 100)) == intervals(f, eps=0.01) == \
[((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert intervals(f, eps=Rational(1, 1000)) == intervals(f, eps=0.001) == \
[((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
assert intervals(f, eps=Rational(1, 10000)) == intervals(f, eps=0.0001) == \
[((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)]
f = Poly((x**2 - 2)*(x**2 - 3)**7*(x + 1)*(7*x + 3)**3)
assert f.intervals() == \
[((-2, Rational(-3, 2)), 7), ((Rational(-3, 2), -1), 1),
((-1, -1), 1), ((-1, 0), 3),
((1, Rational(3, 2)), 1), ((Rational(3, 2), 2), 7)]
assert intervals([x**5 - 200, x**5 - 201]) == \
[((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})]
assert intervals([x**5 - 200, x**5 - 201], fast=True) == \
[((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})]
assert intervals([x**2 - 200, x**2 - 201]) == \
[((Rational(-71, 5), Rational(-85, 6)), {1: 1}), ((Rational(-85, 6), -14), {0: 1}),
((14, Rational(85, 6)), {0: 1}), ((Rational(85, 6), Rational(71, 5)), {1: 1})]
assert intervals([x + 1, x + 2, x - 1, x + 1, 1, x - 1, x - 1, (x - 2)**2]) == \
[((-2, -2), {1: 1}), ((-1, -1), {0: 1, 3: 1}), ((1, 1), {2:
1, 5: 1, 6: 1}), ((2, 2), {7: 2})]
f, g, h = x**2 - 2, x**4 - 4*x**2 + 4, x - 1
assert intervals(f, inf=Rational(7, 4), sqf=True) == []
assert intervals(f, inf=Rational(7, 5), sqf=True) == [(Rational(7, 5), Rational(3, 2))]
assert intervals(f, sup=Rational(7, 4), sqf=True) == [(-2, -1), (1, Rational(3, 2))]
assert intervals(f, sup=Rational(7, 5), sqf=True) == [(-2, -1)]
assert intervals(g, inf=Rational(7, 4)) == []
assert intervals(g, inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), 2)]
assert intervals(g, sup=Rational(7, 4)) == [((-2, -1), 2), ((1, Rational(3, 2)), 2)]
assert intervals(g, sup=Rational(7, 5)) == [((-2, -1), 2)]
assert intervals([g, h], inf=Rational(7, 4)) == []
assert intervals([g, h], inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), {0: 2})]
assert intervals([g, h], sup=S(
7)/4) == [((-2, -1), {0: 2}), ((1, 1), {1: 1}), ((1, Rational(3, 2)), {0: 2})]
assert intervals(
[g, h], sup=Rational(7, 5)) == [((-2, -1), {0: 2}), ((1, 1), {1: 1})]
assert intervals([x + 2, x**2 - 2]) == \
[((-2, -2), {0: 1}), ((-2, -1), {1: 1}), ((1, 2), {1: 1})]
assert intervals([x + 2, x**2 - 2], strict=True) == \
[((-2, -2), {0: 1}), ((Rational(-3, 2), -1), {1: 1}), ((1, 2), {1: 1})]
f = 7*z**4 - 19*z**3 + 20*z**2 + 17*z + 20
assert intervals(f) == []
real_part, complex_part = intervals(f, all=True, sqf=True)
assert real_part == []
assert all(re(a) < re(r) < re(b) and im(
a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f)))
assert complex_part == [(Rational(-40, 7) - I*40/7, 0),
(Rational(-40, 7), I*40/7),
(I*Rational(-40, 7), Rational(40, 7)),
(0, Rational(40, 7) + I*40/7)]
real_part, complex_part = intervals(f, all=True, sqf=True, eps=Rational(1, 10))
assert real_part == []
assert all(re(a) < re(r) < re(b) and im(
a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f)))
raises(ValueError, lambda: intervals(x**2 - 2, eps=10**-100000))
raises(ValueError, lambda: Poly(x**2 - 2).intervals(eps=10**-100000))
raises(
ValueError, lambda: intervals([x**2 - 2, x**2 - 3], eps=10**-100000))
def test_refine_root():
f = Poly(x**2 - 2)
assert f.refine_root(1, 2, steps=0) == (1, 2)
assert f.refine_root(-2, -1, steps=0) == (-2, -1)
assert f.refine_root(1, 2, steps=None) == (1, Rational(3, 2))
assert f.refine_root(-2, -1, steps=None) == (Rational(-3, 2), -1)
assert f.refine_root(1, 2, steps=1) == (1, Rational(3, 2))
assert f.refine_root(-2, -1, steps=1) == (Rational(-3, 2), -1)
assert f.refine_root(1, 2, steps=1, fast=True) == (1, Rational(3, 2))
assert f.refine_root(-2, -1, steps=1, fast=True) == (Rational(-3, 2), -1)
assert f.refine_root(1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12))
assert f.refine_root(1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12))
raises(PolynomialError, lambda: (f**2).refine_root(1, 2, check_sqf=True))
raises(RefinementFailed, lambda: (f**2).refine_root(1, 2))
raises(RefinementFailed, lambda: (f**2).refine_root(2, 3))
f = x**2 - 2
assert refine_root(f, 1, 2, steps=1) == (1, Rational(3, 2))
assert refine_root(f, -2, -1, steps=1) == (Rational(-3, 2), -1)
assert refine_root(f, 1, 2, steps=1, fast=True) == (1, Rational(3, 2))
assert refine_root(f, -2, -1, steps=1, fast=True) == (Rational(-3, 2), -1)
assert refine_root(f, 1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12))
assert refine_root(f, 1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12))
raises(PolynomialError, lambda: refine_root(1, 7, 8, eps=Rational(1, 100)))
raises(ValueError, lambda: Poly(f).refine_root(1, 2, eps=10**-100000))
raises(ValueError, lambda: refine_root(f, 1, 2, eps=10**-100000))
def test_count_roots():
assert count_roots(x**2 - 2) == 2
assert count_roots(x**2 - 2, inf=-oo) == 2
assert count_roots(x**2 - 2, sup=+oo) == 2
assert count_roots(x**2 - 2, inf=-oo, sup=+oo) == 2
assert count_roots(x**2 - 2, inf=-2) == 2
assert count_roots(x**2 - 2, inf=-1) == 1
assert count_roots(x**2 - 2, sup=1) == 1
assert count_roots(x**2 - 2, sup=2) == 2
assert count_roots(x**2 - 2, inf=-1, sup=1) == 0
assert count_roots(x**2 - 2, inf=-2, sup=2) == 2
assert count_roots(x**2 - 2, inf=-1, sup=1) == 0
assert count_roots(x**2 - 2, inf=-2, sup=2) == 2
assert count_roots(x**2 + 2) == 0
assert count_roots(x**2 + 2, inf=-2*I) == 2
assert count_roots(x**2 + 2, sup=+2*I) == 2
assert count_roots(x**2 + 2, inf=-2*I, sup=+2*I) == 2
assert count_roots(x**2 + 2, inf=0) == 0
assert count_roots(x**2 + 2, sup=0) == 0
assert count_roots(x**2 + 2, inf=-I) == 1
assert count_roots(x**2 + 2, sup=+I) == 1
assert count_roots(x**2 + 2, inf=+I/2, sup=+I) == 0
assert count_roots(x**2 + 2, inf=-I, sup=-I/2) == 0
raises(PolynomialError, lambda: count_roots(1))
def test_Poly_root():
f = Poly(2*x**3 - 7*x**2 + 4*x + 4)
assert f.root(0) == Rational(-1, 2)
assert f.root(1) == 2
assert f.root(2) == 2
raises(IndexError, lambda: f.root(3))
assert Poly(x**5 + x + 1).root(0) == rootof(x**3 - x**2 + 1, 0)
def test_real_roots():
assert real_roots(x) == [0]
assert real_roots(x, multiple=False) == [(0, 1)]
assert real_roots(x**3) == [0, 0, 0]
assert real_roots(x**3, multiple=False) == [(0, 3)]
assert real_roots(x*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0]
assert real_roots(x*(x**3 + x + 3), multiple=False) == [(rootof(
x**3 + x + 3, 0), 1), (0, 1)]
assert real_roots(
x**3*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0, 0, 0]
assert real_roots(x**3*(x**3 + x + 3), multiple=False) == [(rootof(
x**3 + x + 3, 0), 1), (0, 3)]
f = 2*x**3 - 7*x**2 + 4*x + 4
g = x**3 + x + 1
assert Poly(f).real_roots() == [Rational(-1, 2), 2, 2]
assert Poly(g).real_roots() == [rootof(g, 0)]
def test_all_roots():
f = 2*x**3 - 7*x**2 + 4*x + 4
g = x**3 + x + 1
assert Poly(f).all_roots() == [Rational(-1, 2), 2, 2]
assert Poly(g).all_roots() == [rootof(g, 0), rootof(g, 1), rootof(g, 2)]
def test_nroots():
assert Poly(0, x).nroots() == []
assert Poly(1, x).nroots() == []
assert Poly(x**2 - 1, x).nroots() == [-1.0, 1.0]
assert Poly(x**2 + 1, x).nroots() == [-1.0*I, 1.0*I]
roots = Poly(x**2 - 1, x).nroots()
assert roots == [-1.0, 1.0]
roots = Poly(x**2 + 1, x).nroots()
assert roots == [-1.0*I, 1.0*I]
roots = Poly(x**2/3 - Rational(1, 3), x).nroots()
assert roots == [-1.0, 1.0]
roots = Poly(x**2/3 + Rational(1, 3), x).nroots()
assert roots == [-1.0*I, 1.0*I]
assert Poly(x**2 + 2*I, x).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I]
assert Poly(
x**2 + 2*I, x, extension=I).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I]
assert Poly(0.2*x + 0.1).nroots() == [-0.5]
roots = nroots(x**5 + x + 1, n=5)
eps = Float("1e-5")
assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.true
assert im(roots[0]) == 0.0
assert re(roots[1]) == Float(-0.5, 5)
assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.true
assert re(roots[2]) == Float(-0.5, 5)
assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.true
assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.true
assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.true
assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.true
assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.true
eps = Float("1e-6")
assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.false
assert im(roots[0]) == 0.0
assert re(roots[1]) == Float(-0.5, 5)
assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.false
assert re(roots[2]) == Float(-0.5, 5)
assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.false
assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.false
assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.false
assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.false
assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.false
raises(DomainError, lambda: Poly(x + y, x).nroots())
raises(MultivariatePolynomialError, lambda: Poly(x + y).nroots())
assert nroots(x**2 - 1) == [-1.0, 1.0]
roots = nroots(x**2 - 1)
assert roots == [-1.0, 1.0]
assert nroots(x + I) == [-1.0*I]
assert nroots(x + 2*I) == [-2.0*I]
raises(PolynomialError, lambda: nroots(0))
# issue 8296
f = Poly(x**4 - 1)
assert f.nroots(2) == [w.n(2) for w in f.all_roots()]
assert str(Poly(x**16 + 32*x**14 + 508*x**12 + 5440*x**10 +
39510*x**8 + 204320*x**6 + 755548*x**4 + 1434496*x**2 +
877969).nroots(2)) == ('[-1.7 - 1.9*I, -1.7 + 1.9*I, -1.7 '
'- 2.5*I, -1.7 + 2.5*I, -1.0*I, 1.0*I, -1.7*I, 1.7*I, -2.8*I, '
'2.8*I, -3.4*I, 3.4*I, 1.7 - 1.9*I, 1.7 + 1.9*I, 1.7 - 2.5*I, '
'1.7 + 2.5*I]')
assert str(Poly(1e-15*x**2 -1).nroots()) == ('[-31622776.6016838, 31622776.6016838]')
def test_ground_roots():
f = x**6 - 4*x**4 + 4*x**3 - x**2
assert Poly(f).ground_roots() == {S.One: 2, S.Zero: 2}
assert ground_roots(f) == {S.One: 2, S.Zero: 2}
def test_nth_power_roots_poly():
f = x**4 - x**2 + 1
f_2 = (x**2 - x + 1)**2
f_3 = (x**2 + 1)**2
f_4 = (x**2 + x + 1)**2
f_12 = (x - 1)**4
assert nth_power_roots_poly(f, 1) == f
raises(ValueError, lambda: nth_power_roots_poly(f, 0))
raises(ValueError, lambda: nth_power_roots_poly(f, x))
assert factor(nth_power_roots_poly(f, 2)) == f_2
assert factor(nth_power_roots_poly(f, 3)) == f_3
assert factor(nth_power_roots_poly(f, 4)) == f_4
assert factor(nth_power_roots_poly(f, 12)) == f_12
raises(MultivariatePolynomialError, lambda: nth_power_roots_poly(
x + y, 2, x, y))
def test_same_root():
f = Poly(x**4 + x**3 + x**2 + x + 1)
eq = f.same_root
r0 = exp(2 * I * pi / 5)
assert [i for i, r in enumerate(f.all_roots()) if eq(r, r0)] == [3]
raises(PolynomialError,
lambda: Poly(x + 1, domain=QQ).same_root(0, 0))
raises(DomainError,
lambda: Poly(x**2 + 1, domain=FF(7)).same_root(0, 0))
raises(DomainError,
lambda: Poly(x ** 2 + 1, domain=ZZ_I).same_root(0, 0))
raises(DomainError,
lambda: Poly(y * x**2 + 1, domain=ZZ[y]).same_root(0, 0))
raises(MultivariatePolynomialError,
lambda: Poly(x * y + 1, domain=ZZ).same_root(0, 0))
def test_torational_factor_list():
p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}))
assert _torational_factor_list(p, x) == (-2, [
(-x*(1 + sqrt(2))/2 + 1, 1),
(-x*(1 + sqrt(2)) - 1, 1),
(-x*(1 + sqrt(2)) + 1, 1)])
p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + 2**Rational(1, 4))}))
assert _torational_factor_list(p, x) is None
def test_cancel():
assert cancel(0) == 0
assert cancel(7) == 7
assert cancel(x) == x
assert cancel(oo) is oo
assert cancel((2, 3)) == (1, 2, 3)
assert cancel((1, 0), x) == (1, 1, 0)
assert cancel((0, 1), x) == (1, 0, 1)
f, g, p, q = 4*x**2 - 4, 2*x - 2, 2*x + 2, 1
F, G, P, Q = [ Poly(u, x) for u in (f, g, p, q) ]
assert F.cancel(G) == (1, P, Q)
assert cancel((f, g)) == (1, p, q)
assert cancel((f, g), x) == (1, p, q)
assert cancel((f, g), (x,)) == (1, p, q)
assert cancel((F, G)) == (1, P, Q)
assert cancel((f, g), polys=True) == (1, P, Q)
assert cancel((F, G), polys=False) == (1, p, q)
f = (x**2 - 2)/(x + sqrt(2))
assert cancel(f) == f
assert cancel(f, greedy=False) == x - sqrt(2)
f = (x**2 - 2)/(x - sqrt(2))
assert cancel(f) == f
assert cancel(f, greedy=False) == x + sqrt(2)
assert cancel((x**2/4 - 1, x/2 - 1)) == (1, x + 2, 2)
# assert cancel((x**2/4 - 1, x/2 - 1)) == (S.Half, x + 2, 1)
assert cancel((x**2 - y)/(x - y)) == 1/(x - y)*(x**2 - y)
assert cancel((x**2 - y**2)/(x - y), x) == x + y
assert cancel((x**2 - y**2)/(x - y), y) == x + y
assert cancel((x**2 - y**2)/(x - y)) == x + y
assert cancel((x**3 - 1)/(x**2 - 1)) == (x**2 + x + 1)/(x + 1)
assert cancel((x**3/2 - S.Half)/(x**2 - 1)) == (x**2 + x + 1)/(2*x + 2)
assert cancel((exp(2*x) + 2*exp(x) + 1)/(exp(x) + 1)) == exp(x) + 1
f = Poly(x**2 - a**2, x)
g = Poly(x - a, x)
F = Poly(x + a, x, domain='ZZ[a]')
G = Poly(1, x, domain='ZZ[a]')
assert cancel((f, g)) == (1, F, G)
f = x**3 + (sqrt(2) - 2)*x**2 - (2*sqrt(2) + 3)*x - 3*sqrt(2)
g = x**2 - 2
assert cancel((f, g), extension=True) == (1, x**2 - 2*x - 3, x - sqrt(2))
f = Poly(-2*x + 3, x)
g = Poly(-x**9 + x**8 + x**6 - x**5 + 2*x**2 - 3*x + 1, x)
assert cancel((f, g)) == (1, -f, -g)
f = Poly(y, y, domain='ZZ(x)')
g = Poly(1, y, domain='ZZ[x]')
assert f.cancel(
g) == (1, Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)'))
assert f.cancel(g, include=True) == (
Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)'))
f = Poly(5*x*y + x, y, domain='ZZ(x)')
g = Poly(2*x**2*y, y, domain='ZZ(x)')
assert f.cancel(g, include=True) == (
Poly(5*y + 1, y, domain='ZZ(x)'), Poly(2*x*y, y, domain='ZZ(x)'))
f = -(-2*x - 4*y + 0.005*(z - y)**2)/((z - y)*(-z + y + 2))
assert cancel(f).is_Mul == True
P = tanh(x - 3.0)
Q = tanh(x + 3.0)
f = ((-2*P**2 + 2)*(-P**2 + 1)*Q**2/2 + (-2*P**2 + 2)*(-2*Q**2 + 2)*P*Q - (-2*P**2 + 2)*P**2*Q**2 + (-2*Q**2 + 2)*(-Q**2 + 1)*P**2/2 - (-2*Q**2 + 2)*P**2*Q**2)/(2*sqrt(P**2*Q**2 + 0.0001)) \
+ (-(-2*P**2 + 2)*P*Q**2/2 - (-2*Q**2 + 2)*P**2*Q/2)*((-2*P**2 + 2)*P*Q**2/2 + (-2*Q**2 + 2)*P**2*Q/2)/(2*(P**2*Q**2 + 0.0001)**Rational(3, 2))
assert cancel(f).is_Mul == True
# issue 7022
A = Symbol('A', commutative=False)
p1 = Piecewise((A*(x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True))
p2 = Piecewise((A*(x - 1), x > 1), (1/x, True))
assert cancel(p1) == p2
assert cancel(2*p1) == 2*p2
assert cancel(1 + p1) == 1 + p2
assert cancel((x**2 - 1)/(x + 1)*p1) == (x - 1)*p2
assert cancel((x**2 - 1)/(x + 1) + p1) == (x - 1) + p2
p3 = Piecewise(((x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True))
p4 = Piecewise(((x - 1), x > 1), (1/x, True))
assert cancel(p3) == p4
assert cancel(2*p3) == 2*p4
assert cancel(1 + p3) == 1 + p4
assert cancel((x**2 - 1)/(x + 1)*p3) == (x - 1)*p4
assert cancel((x**2 - 1)/(x + 1) + p3) == (x - 1) + p4
# issue 4077
q = S('''(2*1*(x - 1/x)/(x*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x -
1/x)) - 2/x)) - 2*1*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x -
1/x)))*((-x + 1/x)*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x -
1/x)))/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) -
2/x) + 1)*((x - 1/x)/((x - 1/x)**2) - ((x - 1/x)/((x*(x - 1/x)**2)) -
1/(x*(x - 1/x)))**2/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x
- 1/x)) - 2/x) - 1/(x - 1/x))*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) -
1/(x**2*(x - 1/x)) - 2/x)/x - 1/x)*(((-x + 1/x)/((x*(x - 1/x)**2)) +
1/(x*(x - 1/x)))*((-(x - 1/x)/(x*(x - 1/x)) - 1/x)*((x - 1/x)/((x*(x -
1/x)**2)) - 1/(x*(x - 1/x)))/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) -
1/(x**2*(x - 1/x)) - 2/x) - 1 + (x - 1/x)/(x - 1/x))/((x*((x -
1/x)/((x - 1/x)**2) - ((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x -
1/x)))**2/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) -
2/x) - 1/(x - 1/x))*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x
- 1/x)) - 2/x))) + ((x - 1/x)/((x*(x - 1/x))) + 1/x)/((x*(2*x - (-x +
1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x))) + 1/x)/(2*x +
2*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))*((-(x - 1/x)/(x*(x
- 1/x)) - 1/x)*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))/(2*x -
(-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1 + (x -
1/x)/(x - 1/x))/((x*((x - 1/x)/((x - 1/x)**2) - ((x - 1/x)/((x*(x -
1/x)**2)) - 1/(x*(x - 1/x)))**2/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2)
- 1/(x**2*(x - 1/x)) - 2/x) - 1/(x - 1/x))*(2*x - (-x + 1/x)/(x**2*(x
- 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x))) - 2*((x - 1/x)/((x*(x -
1/x))) + 1/x)/(x*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x -
1/x)) - 2/x)) - 2/x) - ((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x -
1/x)))*((-x + 1/x)*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x -
1/x)))/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) -
2/x) + 1)/(x*((x - 1/x)/((x - 1/x)**2) - ((x - 1/x)/((x*(x - 1/x)**2))
- 1/(x*(x - 1/x)))**2/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) -
1/(x**2*(x - 1/x)) - 2/x) - 1/(x - 1/x))*(2*x - (-x + 1/x)/(x**2*(x -
1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x)) + (x - 1/x)/((x*(2*x - (-x +
1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x))) - 1/x''',
evaluate=False)
assert cancel(q, _signsimp=False) is S.NaN
assert q.subs(x, 2) is S.NaN
assert signsimp(q) is S.NaN
# issue 9363
M = MatrixSymbol('M', 5, 5)
assert cancel(M[0,0] + 7) == M[0,0] + 7
expr = sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2] / z
assert cancel(expr) == (z*sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2]) / z
assert cancel((x**2 + 1)/(x - I)) == x + I
def test_reduced():
f = 2*x**4 + y**2 - x**2 + y**3
G = [x**3 - x, y**3 - y]
Q = [2*x, 1]
r = x**2 + y**2 + y
assert reduced(f, G) == (Q, r)
assert reduced(f, G, x, y) == (Q, r)
H = groebner(G)
assert H.reduce(f) == (Q, r)
Q = [Poly(2*x, x, y), Poly(1, x, y)]
r = Poly(x**2 + y**2 + y, x, y)
assert _strict_eq(reduced(f, G, polys=True), (Q, r))
assert _strict_eq(reduced(f, G, x, y, polys=True), (Q, r))
H = groebner(G, polys=True)
assert _strict_eq(H.reduce(f), (Q, r))
f = 2*x**3 + y**3 + 3*y
G = groebner([x**2 + y**2 - 1, x*y - 2])
Q = [x**2 - x*y**3/2 + x*y/2 + y**6/4 - y**4/2 + y**2/4, -y**5/4 + y**3/2 + y*Rational(3, 4)]
r = 0
assert reduced(f, G) == (Q, r)
assert G.reduce(f) == (Q, r)
assert reduced(f, G, auto=False)[1] != 0
assert G.reduce(f, auto=False)[1] != 0
assert G.contains(f) is True
assert G.contains(f + 1) is False
assert reduced(1, [1], x) == ([1], 0)
raises(ComputationFailed, lambda: reduced(1, [1]))
def test_groebner():
assert groebner([], x, y, z) == []
assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex') == [1 + x**2, -1 + y**4]
assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex') == [-1 + y**4, z**3, 1 + x**2]
assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex', polys=True) == \
[Poly(1 + x**2, x, y), Poly(-1 + y**4, x, y)]
assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex', polys=True) == \
[Poly(-1 + y**4, x, y, z), Poly(z**3, x, y, z), Poly(1 + x**2, x, y, z)]
assert groebner([x**3 - 1, x**2 - 1]) == [x - 1]
assert groebner([Eq(x**3, 1), Eq(x**2, 1)]) == [x - 1]
F = [3*x**2 + y*z - 5*x - 1, 2*x + 3*x*y + y**2, x - 3*y + x*z - 2*z**2]
f = z**9 - x**2*y**3 - 3*x*y**2*z + 11*y*z**2 + x**2*z**2 - 5
G = groebner(F, x, y, z, modulus=7, symmetric=False)
assert G == [1 + x + y + 3*z + 2*z**2 + 2*z**3 + 6*z**4 + z**5,
1 + 3*y + y**2 + 6*z**2 + 3*z**3 + 3*z**4 + 3*z**5 + 4*z**6,
1 + 4*y + 4*z + y*z + 4*z**3 + z**4 + z**6,
6 + 6*z + z**2 + 4*z**3 + 3*z**4 + 6*z**5 + 3*z**6 + z**7]
Q, r = reduced(f, G, x, y, z, modulus=7, symmetric=False, polys=True)
assert sum([ q*g for q, g in zip(Q, G.polys)], r) == Poly(f, modulus=7)
F = [x*y - 2*y, 2*y**2 - x**2]
assert groebner(F, x, y, order='grevlex') == \
[y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y]
assert groebner(F, y, x, order='grevlex') == \
[x**3 - 2*x**2, -x**2 + 2*y**2, x*y - 2*y]
assert groebner(F, order='grevlex', field=True) == \
[y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y]
assert groebner([1], x) == [1]
assert groebner([x**2 + 2.0*y], x, y) == [1.0*x**2 + 2.0*y]
raises(ComputationFailed, lambda: groebner([1]))
assert groebner([x**2 - 1, x**3 + 1], method='buchberger') == [x + 1]
assert groebner([x**2 - 1, x**3 + 1], method='f5b') == [x + 1]
raises(ValueError, lambda: groebner([x, y], method='unknown'))
def test_fglm():
F = [a + b + c + d, a*b + a*d + b*c + b*d, a*b*c + a*b*d + a*c*d + b*c*d, a*b*c*d - 1]
G = groebner(F, a, b, c, d, order=grlex)
B = [
4*a + 3*d**9 - 4*d**5 - 3*d,
4*b + 4*c - 3*d**9 + 4*d**5 + 7*d,
4*c**2 + 3*d**10 - 4*d**6 - 3*d**2,
4*c*d**4 + 4*c - d**9 + 4*d**5 + 5*d,
d**12 - d**8 - d**4 + 1,
]
assert groebner(F, a, b, c, d, order=lex) == B
assert G.fglm(lex) == B
F = [9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9,
-72*t*x**7 - 252*t*x**6 + 192*t*x**5 + 1260*t*x**4 + 312*t*x**3 - 404*t*x**2 - 576*t*x + \
108*t - 72*x**7 - 256*x**6 + 192*x**5 + 1280*x**4 + 312*x**3 - 576*x + 96]
G = groebner(F, t, x, order=grlex)
B = [
203577793572507451707*t + 627982239411707112*x**7 - 666924143779443762*x**6 - \
10874593056632447619*x**5 + 5119998792707079562*x**4 + 72917161949456066376*x**3 + \
20362663855832380362*x**2 - 142079311455258371571*x + 183756699868981873194,
9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9,
]
assert groebner(F, t, x, order=lex) == B
assert G.fglm(lex) == B
F = [x**2 - x - 3*y + 1, -2*x + y**2 + y - 1]
G = groebner(F, x, y, order=lex)
B = [
x**2 - x - 3*y + 1,
y**2 - 2*x + y - 1,
]
assert groebner(F, x, y, order=grlex) == B
assert G.fglm(grlex) == B
def test_is_zero_dimensional():
assert is_zero_dimensional([x, y], x, y) is True
assert is_zero_dimensional([x**3 + y**2], x, y) is False
assert is_zero_dimensional([x, y, z], x, y, z) is True
assert is_zero_dimensional([x, y, z], x, y, z, t) is False
F = [x*y - z, y*z - x, x*y - y]
assert is_zero_dimensional(F, x, y, z) is True
F = [x**2 - 2*x*z + 5, x*y**2 + y*z**3, 3*y**2 - 8*z**2]
assert is_zero_dimensional(F, x, y, z) is True
def test_GroebnerBasis():
F = [x*y - 2*y, 2*y**2 - x**2]
G = groebner(F, x, y, order='grevlex')
H = [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y]
P = [ Poly(h, x, y) for h in H ]
assert groebner(F + [0], x, y, order='grevlex') == G
assert isinstance(G, GroebnerBasis) is True
assert len(G) == 3
assert G[0] == H[0] and not G[0].is_Poly
assert G[1] == H[1] and not G[1].is_Poly
assert G[2] == H[2] and not G[2].is_Poly
assert G[1:] == H[1:] and not any(g.is_Poly for g in G[1:])
assert G[:2] == H[:2] and not any(g.is_Poly for g in G[1:])
assert G.exprs == H
assert G.polys == P
assert G.gens == (x, y)
assert G.domain == ZZ
assert G.order == grevlex
assert G == H
assert G == tuple(H)
assert G == P
assert G == tuple(P)
assert G != []
G = groebner(F, x, y, order='grevlex', polys=True)
assert G[0] == P[0] and G[0].is_Poly
assert G[1] == P[1] and G[1].is_Poly
assert G[2] == P[2] and G[2].is_Poly
assert G[1:] == P[1:] and all(g.is_Poly for g in G[1:])
assert G[:2] == P[:2] and all(g.is_Poly for g in G[1:])
def test_poly():
assert poly(x) == Poly(x, x)
assert poly(y) == Poly(y, y)
assert poly(x + y) == Poly(x + y, x, y)
assert poly(x + sin(x)) == Poly(x + sin(x), x, sin(x))
assert poly(x + y, wrt=y) == Poly(x + y, y, x)
assert poly(x + sin(x), wrt=sin(x)) == Poly(x + sin(x), sin(x), x)
assert poly(x*y + 2*x*z**2 + 17) == Poly(x*y + 2*x*z**2 + 17, x, y, z)
assert poly(2*(y + z)**2 - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - 1, y, z)
assert poly(
x*(y + z)**2 - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - 1, x, y, z)
assert poly(2*x*(
y + z)**2 - 1) == Poly(2*x*y**2 + 4*x*y*z + 2*x*z**2 - 1, x, y, z)
assert poly(2*(
y + z)**2 - x - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - x - 1, x, y, z)
assert poly(x*(
y + z)**2 - x - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - x - 1, x, y, z)
assert poly(2*x*(y + z)**2 - x - 1) == Poly(2*x*y**2 + 4*x*y*z + 2*
x*z**2 - x - 1, x, y, z)
assert poly(x*y + (x + y)**2 + (x + z)**2) == \
Poly(2*x*z + 3*x*y + y**2 + z**2 + 2*x**2, x, y, z)
assert poly(x*y*(x + y)*(x + z)**2) == \
Poly(x**3*y**2 + x*y**2*z**2 + y*x**2*z**2 + 2*z*x**2*
y**2 + 2*y*z*x**3 + y*x**4, x, y, z)
assert poly(Poly(x + y + z, y, x, z)) == Poly(x + y + z, y, x, z)
assert poly((x + y)**2, x) == Poly(x**2 + 2*x*y + y**2, x, domain=ZZ[y])
assert poly((x + y)**2, y) == Poly(x**2 + 2*x*y + y**2, y, domain=ZZ[x])
assert poly(1, x) == Poly(1, x)
raises(GeneratorsNeeded, lambda: poly(1))
# issue 6184
assert poly(x + y, x, y) == Poly(x + y, x, y)
assert poly(x + y, y, x) == Poly(x + y, y, x)
def test_keep_coeff():
u = Mul(2, x + 1, evaluate=False)
assert _keep_coeff(S.One, x) == x
assert _keep_coeff(S.NegativeOne, x) == -x
assert _keep_coeff(S(1.0), x) == 1.0*x
assert _keep_coeff(S(-1.0), x) == -1.0*x
assert _keep_coeff(S.One, 2*x) == 2*x
assert _keep_coeff(S(2), x/2) == x
assert _keep_coeff(S(2), sin(x)) == 2*sin(x)
assert _keep_coeff(S(2), x + 1) == u
assert _keep_coeff(x, 1/x) == 1
assert _keep_coeff(x + 1, S(2)) == u
assert _keep_coeff(S.Half, S.One) == S.Half
p = Pow(2, 3, evaluate=False)
assert _keep_coeff(S(-1), p) == Mul(-1, p, evaluate=False)
a = Add(2, p, evaluate=False)
assert _keep_coeff(S.Half, a, clear=True
) == Mul(S.Half, a, evaluate=False)
assert _keep_coeff(S.Half, a, clear=False
) == Add(1, Mul(S.Half, p, evaluate=False), evaluate=False)
def test_poly_matching_consistency():
# Test for this issue:
# https://github.com/sympy/sympy/issues/5514
assert I * Poly(x, x) == Poly(I*x, x)
assert Poly(x, x) * I == Poly(I*x, x)
def test_issue_5786():
assert expand(factor(expand(
(x - I*y)*(z - I*t)), extension=[I])) == -I*t*x - t*y + x*z - I*y*z
def test_noncommutative():
class foo(Expr):
is_commutative=False
e = x/(x + x*y)
c = 1/( 1 + y)
assert cancel(foo(e)) == foo(c)
assert cancel(e + foo(e)) == c + foo(c)
assert cancel(e*foo(c)) == c*foo(c)
def test_to_rational_coeffs():
assert to_rational_coeffs(
Poly(x**3 + y*x**2 + sqrt(y), x, domain='EX')) is None
# issue 21268
assert to_rational_coeffs(
Poly(y**3 + sqrt(2)*y**2*sin(x) + 1, y)) is None
assert to_rational_coeffs(Poly(x, y)) is None
assert to_rational_coeffs(Poly(sqrt(2)*y)) is None
def test_factor_terms():
# issue 7067
assert factor_list(x*(x + y)) == (1, [(x, 1), (x + y, 1)])
assert sqf_list(x*(x + y)) == (1, [(x**2 + x*y, 1)])
def test_as_list():
# issue 14496
assert Poly(x**3 + 2, x, domain='ZZ').as_list() == [1, 0, 0, 2]
assert Poly(x**2 + y + 1, x, y, domain='ZZ').as_list() == [[1], [], [1, 1]]
assert Poly(x**2 + y + 1, x, y, z, domain='ZZ').as_list() == \
[[[1]], [[]], [[1], [1]]]
def test_issue_11198():
assert factor_list(sqrt(2)*x) == (sqrt(2), [(x, 1)])
assert factor_list(sqrt(2)*sin(x), sin(x)) == (sqrt(2), [(sin(x), 1)])
def test_Poly_precision():
# Make sure Poly doesn't lose precision
p = Poly(pi.evalf(100)*x)
assert p.as_expr() == pi.evalf(100)*x
def test_issue_12400():
# Correction of check for negative exponents
assert poly(1/(1+sqrt(2)), x) == \
Poly(1/(1+sqrt(2)), x, domain='EX')
def test_issue_14364():
assert gcd(S(6)*(1 + sqrt(3))/5, S(3)*(1 + sqrt(3))/10) == Rational(3, 10) * (1 + sqrt(3))
assert gcd(sqrt(5)*Rational(4, 7), sqrt(5)*Rational(2, 3)) == sqrt(5)*Rational(2, 21)
assert lcm(Rational(2, 3)*sqrt(3), Rational(5, 6)*sqrt(3)) == S(10)*sqrt(3)/3
assert lcm(3*sqrt(3), 4/sqrt(3)) == 12*sqrt(3)
assert lcm(S(5)*(1 + 2**Rational(1, 3))/6, S(3)*(1 + 2**Rational(1, 3))/8) == Rational(15, 2) * (1 + 2**Rational(1, 3))
assert gcd(Rational(2, 3)*sqrt(3), Rational(5, 6)/sqrt(3)) == sqrt(3)/18
assert gcd(S(4)*sqrt(13)/7, S(3)*sqrt(13)/14) == sqrt(13)/14
# gcd_list and lcm_list
assert gcd([S(2)*sqrt(47)/7, S(6)*sqrt(47)/5, S(8)*sqrt(47)/5]) == sqrt(47)*Rational(2, 35)
assert gcd([S(6)*(1 + sqrt(7))/5, S(2)*(1 + sqrt(7))/7, S(4)*(1 + sqrt(7))/13]) == (1 + sqrt(7))*Rational(2, 455)
assert lcm((Rational(7, 2)/sqrt(15), Rational(5, 6)/sqrt(15), Rational(5, 8)/sqrt(15))) == Rational(35, 2)/sqrt(15)
assert lcm([S(5)*(2 + 2**Rational(5, 7))/6, S(7)*(2 + 2**Rational(5, 7))/2, S(13)*(2 + 2**Rational(5, 7))/4]) == Rational(455, 2) * (2 + 2**Rational(5, 7))
def test_issue_15669():
x = Symbol("x", positive=True)
expr = (16*x**3/(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**2 -
2*2**Rational(4, 5)*x*(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**Rational(3, 5) + 10*x)
assert factor(expr, deep=True) == x*(x**2 + 2)
def test_issue_17988():
x = Symbol('x')
p = poly(x - 1)
with warns_deprecated_sympy():
M = Matrix([[poly(x + 1), poly(x + 1)]])
with warns(SymPyDeprecationWarning, test_stacklevel=False):
assert p * M == M * p == Matrix([[poly(x**2 - 1), poly(x**2 - 1)]])
def test_issue_18205():
assert cancel((2 + I)*(3 - I)) == 7 + I
assert cancel((2 + I)*(2 - I)) == 5
def test_issue_8695():
p = (x**2 + 1) * (x - 1)**2 * (x - 2)**3 * (x - 3)**3
result = (1, [(x**2 + 1, 1), (x - 1, 2), (x**2 - 5*x + 6, 3)])
assert sqf_list(p) == result
def test_issue_19113():
eq = sin(x)**3 - sin(x) + 1
raises(PolynomialError, lambda: refine_root(eq, 1, 2, 1e-2))
raises(PolynomialError, lambda: count_roots(eq, -1, 1))
raises(PolynomialError, lambda: real_roots(eq))
raises(PolynomialError, lambda: nroots(eq))
raises(PolynomialError, lambda: ground_roots(eq))
raises(PolynomialError, lambda: nth_power_roots_poly(eq, 2))
def test_issue_19360():
f = 2*x**2 - 2*sqrt(2)*x*y + y**2
assert factor(f, extension=sqrt(2)) == 2*(x - (sqrt(2)*y/2))**2
f = -I*t*x - t*y + x*z - I*y*z
assert factor(f, extension=I) == (x - I*y)*(-I*t + z)
def test_poly_copy_equals_original():
poly = Poly(x + y, x, y, z)
copy = poly.copy()
assert poly == copy, (
"Copied polynomial not equal to original.")
assert poly.gens == copy.gens, (
"Copied polynomial has different generators than original.")
def test_deserialized_poly_equals_original():
poly = Poly(x + y, x, y, z)
deserialized = pickle.loads(pickle.dumps(poly))
assert poly == deserialized, (
"Deserialized polynomial not equal to original.")
assert poly.gens == deserialized.gens, (
"Deserialized polynomial has different generators than original.")
def test_issue_20389():
result = degree(x * (x + 1) - x ** 2 - x, x)
assert result == -oo
def test_issue_20985():
from sympy.core.symbol import symbols
w, R = symbols('w R')
poly = Poly(1.0 + I*w/R, w, 1/R)
assert poly.degree() == S(1)
|
f5f9961436a5f281b7958c3e300f7c129a200ebb03f80e88c608e138f57eecf2 | from __future__ import annotations
from math import floor as mfloor
from sympy.polys.domains import ZZ, QQ
from sympy.polys.matrices.exceptions import DMRankError, DMShapeError, DMValueError, DMDomainError
linear_dependent_error = "input matrix contains linearly dependent rows"
def ddm_lll(x, delta=QQ(3, 4)):
if QQ(1, 4) >= delta or delta >= QQ(1, 1):
raise DMValueError("delta must lie in range (0.25, 1)")
if x.shape[0] > x.shape[1]:
raise DMShapeError("input matrix must have shape (m, n) with m <= n")
if x.domain != ZZ:
raise DMDomainError("input matrix domain must be ZZ")
m = x.shape[0]
n = x.shape[1]
k = 1
y = x.copy()
y_star = x.zeros((m, n), QQ)
mu = x.zeros((m, m), QQ)
g_star = [QQ(0, 1) for _ in range(m)]
half = QQ(1, 2)
def closest_integer(x):
return ZZ(mfloor(x + half))
def lovasz_condition(k: int) -> bool:
return g_star[k] >= ((delta - mu[k][k - 1] ** 2) * g_star[k - 1])
def mu_small(k: int, j: int) -> bool:
return abs(mu[k][j]) <= half
def dot_rows(x, y, rows: tuple[int, int]):
return sum([x[rows[0]][z] * y[rows[1]][z] for z in range(x.shape[1])])
def reduce_row(mu, y, rows: tuple[int, int]):
r = closest_integer(mu[rows[0]][rows[1]])
y[rows[0]] = [y[rows[0]][z] - r * y[rows[1]][z] for z in range(n)]
for j in range(rows[1]):
mu[rows[0]][j] -= r * mu[rows[1]][j]
mu[rows[0]][rows[1]] -= r
for i in range(m):
y_star[i] = [QQ.convert_from(z, ZZ) for z in y[i]]
for j in range(i):
row_dot = dot_rows(y, y_star, (i, j))
try:
mu[i][j] = row_dot / g_star[j]
except ZeroDivisionError:
raise DMRankError(linear_dependent_error)
y_star[i] = [y_star[i][z] - mu[i][j] * y_star[j][z] for z in range(n)]
g_star[i] = dot_rows(y_star, y_star, (i, i))
while k < m:
if not mu_small(k, k - 1):
reduce_row(mu, y, (k, k - 1))
if lovasz_condition(k):
for l in range(k - 2, -1, -1):
if not mu_small(k, l):
reduce_row(mu, y, (k, l))
k += 1
else:
nu = mu[k][k - 1]
alpha = g_star[k] + nu ** 2 * g_star[k - 1]
try:
beta = g_star[k - 1] / alpha
except ZeroDivisionError:
raise DMRankError(linear_dependent_error)
mu[k][k - 1] = nu * beta
g_star[k] = g_star[k] * beta
g_star[k - 1] = alpha
y[k], y[k - 1] = y[k - 1], y[k]
mu[k][:k - 1], mu[k - 1][:k - 1] = mu[k - 1][:k - 1], mu[k][:k - 1]
for i in range(k + 1, m):
xi = mu[i][k]
mu[i][k] = mu[i][k - 1] - nu * xi
mu[i][k - 1] = mu[k][k - 1] * mu[i][k] + xi
k = max(k - 1, 1)
assert all([lovasz_condition(i) for i in range(1, m)])
assert all([mu_small(i, j) for i in range(m) for j in range(i)])
return y
|
9242610bcc843240718cc007ed4ed86a23b3d35f4c0b9ba40e0966693d113b87 | """
Module for the DomainMatrix class.
A DomainMatrix represents a matrix with elements that are in a particular
Domain. Each DomainMatrix internally wraps a DDM which is used for the
lower-level operations. The idea is that the DomainMatrix class provides the
convenience routines for converting between Expr and the poly domains as well
as unifying matrices with different domains.
"""
from functools import reduce
from typing import Union as tUnion, Tuple as tTuple
from sympy.core.sympify import _sympify
from ..domains import Domain
from ..constructor import construct_domain
from .exceptions import (DMNonSquareMatrixError, DMShapeError,
DMDomainError, DMFormatError, DMBadInputError,
DMNotAField)
from .ddm import DDM
from .sdm import SDM
from .domainscalar import DomainScalar
from sympy.polys.domains import ZZ, EXRAW, QQ
def DM(rows, domain):
"""Convenient alias for DomainMatrix.from_list
Examples
=======
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DM
>>> DM([[1, 2], [3, 4]], ZZ)
DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
See also
=======
DomainMatrix.from_list
"""
return DomainMatrix.from_list(rows, domain)
class DomainMatrix:
r"""
Associate Matrix with :py:class:`~.Domain`
Explanation
===========
DomainMatrix uses :py:class:`~.Domain` for its internal representation
which makes it faster than the SymPy Matrix class (currently) for many
common operations, but this advantage makes it not entirely compatible
with Matrix. DomainMatrix are analogous to numpy arrays with "dtype".
In the DomainMatrix, each element has a domain such as :ref:`ZZ`
or :ref:`QQ(a)`.
Examples
========
Creating a DomainMatrix from the existing Matrix class:
>>> from sympy import Matrix
>>> from sympy.polys.matrices import DomainMatrix
>>> Matrix1 = Matrix([
... [1, 2],
... [3, 4]])
>>> A = DomainMatrix.from_Matrix(Matrix1)
>>> A
DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ)
Directly forming a DomainMatrix:
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A
DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
See Also
========
DDM
SDM
Domain
Poly
"""
rep: tUnion[SDM, DDM]
shape: tTuple[int, int]
domain: Domain
def __new__(cls, rows, shape, domain, *, fmt=None):
"""
Creates a :py:class:`~.DomainMatrix`.
Parameters
==========
rows : Represents elements of DomainMatrix as list of lists
shape : Represents dimension of DomainMatrix
domain : Represents :py:class:`~.Domain` of DomainMatrix
Raises
======
TypeError
If any of rows, shape and domain are not provided
"""
if isinstance(rows, (DDM, SDM)):
raise TypeError("Use from_rep to initialise from SDM/DDM")
elif isinstance(rows, list):
rep = DDM(rows, shape, domain)
elif isinstance(rows, dict):
rep = SDM(rows, shape, domain)
else:
msg = "Input should be list-of-lists or dict-of-dicts"
raise TypeError(msg)
if fmt is not None:
if fmt == 'sparse':
rep = rep.to_sdm()
elif fmt == 'dense':
rep = rep.to_ddm()
else:
raise ValueError("fmt should be 'sparse' or 'dense'")
return cls.from_rep(rep)
def __getnewargs__(self):
rep = self.rep
if isinstance(rep, DDM):
arg = list(rep)
elif isinstance(rep, SDM):
arg = dict(rep)
else:
raise RuntimeError # pragma: no cover
return arg, self.shape, self.domain
def __getitem__(self, key):
i, j = key
m, n = self.shape
if not (isinstance(i, slice) or isinstance(j, slice)):
return DomainScalar(self.rep.getitem(i, j), self.domain)
if not isinstance(i, slice):
if not -m <= i < m:
raise IndexError("Row index out of range")
i = i % m
i = slice(i, i+1)
if not isinstance(j, slice):
if not -n <= j < n:
raise IndexError("Column index out of range")
j = j % n
j = slice(j, j+1)
return self.from_rep(self.rep.extract_slice(i, j))
def getitem_sympy(self, i, j):
return self.domain.to_sympy(self.rep.getitem(i, j))
def extract(self, rowslist, colslist):
return self.from_rep(self.rep.extract(rowslist, colslist))
def __setitem__(self, key, value):
i, j = key
if not self.domain.of_type(value):
raise TypeError
if isinstance(i, int) and isinstance(j, int):
self.rep.setitem(i, j, value)
else:
raise NotImplementedError
@classmethod
def from_rep(cls, rep):
"""Create a new DomainMatrix efficiently from DDM/SDM.
Examples
========
Create a :py:class:`~.DomainMatrix` with an dense internal
representation as :py:class:`~.DDM`:
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy.polys.matrices.ddm import DDM
>>> drep = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> dM = DomainMatrix.from_rep(drep)
>>> dM
DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
Create a :py:class:`~.DomainMatrix` with a sparse internal
representation as :py:class:`~.SDM`:
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy import ZZ
>>> drep = SDM({0:{1:ZZ(1)},1:{0:ZZ(2)}}, (2, 2), ZZ)
>>> dM = DomainMatrix.from_rep(drep)
>>> dM
DomainMatrix({0: {1: 1}, 1: {0: 2}}, (2, 2), ZZ)
Parameters
==========
rep: SDM or DDM
The internal sparse or dense representation of the matrix.
Returns
=======
DomainMatrix
A :py:class:`~.DomainMatrix` wrapping *rep*.
Notes
=====
This takes ownership of rep as its internal representation. If rep is
being mutated elsewhere then a copy should be provided to
``from_rep``. Only minimal verification or checking is done on *rep*
as this is supposed to be an efficient internal routine.
"""
if not isinstance(rep, (DDM, SDM)):
raise TypeError("rep should be of type DDM or SDM")
self = super().__new__(cls)
self.rep = rep
self.shape = rep.shape
self.domain = rep.domain
return self
@classmethod
def from_list(cls, rows, domain):
r"""
Convert a list of lists into a DomainMatrix
Parameters
==========
rows: list of lists
Each element of the inner lists should be either the single arg,
or tuple of args, that would be passed to the domain constructor
in order to form an element of the domain. See examples.
Returns
=======
DomainMatrix containing elements defined in rows
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import FF, QQ, ZZ
>>> A = DomainMatrix.from_list([[1, 0, 1], [0, 0, 1]], ZZ)
>>> A
DomainMatrix([[1, 0, 1], [0, 0, 1]], (2, 3), ZZ)
>>> B = DomainMatrix.from_list([[1, 0, 1], [0, 0, 1]], FF(7))
>>> B
DomainMatrix([[1 mod 7, 0 mod 7, 1 mod 7], [0 mod 7, 0 mod 7, 1 mod 7]], (2, 3), GF(7))
>>> C = DomainMatrix.from_list([[(1, 2), (3, 1)], [(1, 4), (5, 1)]], QQ)
>>> C
DomainMatrix([[1/2, 3], [1/4, 5]], (2, 2), QQ)
See Also
========
from_list_sympy
"""
nrows = len(rows)
ncols = 0 if not nrows else len(rows[0])
conv = lambda e: domain(*e) if isinstance(e, tuple) else domain(e)
domain_rows = [[conv(e) for e in row] for row in rows]
return DomainMatrix(domain_rows, (nrows, ncols), domain)
@classmethod
def from_list_sympy(cls, nrows, ncols, rows, **kwargs):
r"""
Convert a list of lists of Expr into a DomainMatrix using construct_domain
Parameters
==========
nrows: number of rows
ncols: number of columns
rows: list of lists
Returns
=======
DomainMatrix containing elements of rows
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy.abc import x, y, z
>>> A = DomainMatrix.from_list_sympy(1, 3, [[x, y, z]])
>>> A
DomainMatrix([[x, y, z]], (1, 3), ZZ[x,y,z])
See Also
========
sympy.polys.constructor.construct_domain, from_dict_sympy
"""
assert len(rows) == nrows
assert all(len(row) == ncols for row in rows)
items_sympy = [_sympify(item) for row in rows for item in row]
domain, items_domain = cls.get_domain(items_sympy, **kwargs)
domain_rows = [[items_domain[ncols*r + c] for c in range(ncols)] for r in range(nrows)]
return DomainMatrix(domain_rows, (nrows, ncols), domain)
@classmethod
def from_dict_sympy(cls, nrows, ncols, elemsdict, **kwargs):
"""
Parameters
==========
nrows: number of rows
ncols: number of cols
elemsdict: dict of dicts containing non-zero elements of the DomainMatrix
Returns
=======
DomainMatrix containing elements of elemsdict
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy.abc import x,y,z
>>> elemsdict = {0: {0:x}, 1:{1: y}, 2: {2: z}}
>>> A = DomainMatrix.from_dict_sympy(3, 3, elemsdict)
>>> A
DomainMatrix({0: {0: x}, 1: {1: y}, 2: {2: z}}, (3, 3), ZZ[x,y,z])
See Also
========
from_list_sympy
"""
if not all(0 <= r < nrows for r in elemsdict):
raise DMBadInputError("Row out of range")
if not all(0 <= c < ncols for row in elemsdict.values() for c in row):
raise DMBadInputError("Column out of range")
items_sympy = [_sympify(item) for row in elemsdict.values() for item in row.values()]
domain, items_domain = cls.get_domain(items_sympy, **kwargs)
idx = 0
items_dict = {}
for i, row in elemsdict.items():
items_dict[i] = {}
for j in row:
items_dict[i][j] = items_domain[idx]
idx += 1
return DomainMatrix(items_dict, (nrows, ncols), domain)
@classmethod
def from_Matrix(cls, M, fmt='sparse',**kwargs):
r"""
Convert Matrix to DomainMatrix
Parameters
==========
M: Matrix
Returns
=======
Returns DomainMatrix with identical elements as M
Examples
========
>>> from sympy import Matrix
>>> from sympy.polys.matrices import DomainMatrix
>>> M = Matrix([
... [1.0, 3.4],
... [2.4, 1]])
>>> A = DomainMatrix.from_Matrix(M)
>>> A
DomainMatrix({0: {0: 1.0, 1: 3.4}, 1: {0: 2.4, 1: 1.0}}, (2, 2), RR)
We can keep internal representation as ddm using fmt='dense'
>>> from sympy import Matrix, QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix.from_Matrix(Matrix([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]]), fmt='dense')
>>> A.rep
[[1/2, 3/4], [0, 0]]
See Also
========
Matrix
"""
if fmt == 'dense':
return cls.from_list_sympy(*M.shape, M.tolist(), **kwargs)
return cls.from_dict_sympy(*M.shape, M.todod(), **kwargs)
@classmethod
def get_domain(cls, items_sympy, **kwargs):
K, items_K = construct_domain(items_sympy, **kwargs)
return K, items_K
def copy(self):
return self.from_rep(self.rep.copy())
def convert_to(self, K):
r"""
Change the domain of DomainMatrix to desired domain or field
Parameters
==========
K : Represents the desired domain or field.
Alternatively, ``None`` may be passed, in which case this method
just returns a copy of this DomainMatrix.
Returns
=======
DomainMatrix
DomainMatrix with the desired domain or field
Examples
========
>>> from sympy import ZZ, ZZ_I
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A.convert_to(ZZ_I)
DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ_I)
"""
if K is None:
return self.copy()
return self.from_rep(self.rep.convert_to(K))
def to_sympy(self):
return self.convert_to(EXRAW)
def to_field(self):
r"""
Returns a DomainMatrix with the appropriate field
Returns
=======
DomainMatrix
DomainMatrix with the appropriate field
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A.to_field()
DomainMatrix([[1, 2], [3, 4]], (2, 2), QQ)
"""
K = self.domain.get_field()
return self.convert_to(K)
def to_sparse(self):
"""
Return a sparse DomainMatrix representation of *self*.
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import QQ
>>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ)
>>> A.rep
[[1, 0], [0, 2]]
>>> B = A.to_sparse()
>>> B.rep
{0: {0: 1}, 1: {1: 2}}
"""
if self.rep.fmt == 'sparse':
return self
return self.from_rep(SDM.from_ddm(self.rep))
def to_dense(self):
"""
Return a dense DomainMatrix representation of *self*.
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import QQ
>>> A = DomainMatrix({0: {0: 1}, 1: {1: 2}}, (2, 2), QQ)
>>> A.rep
{0: {0: 1}, 1: {1: 2}}
>>> B = A.to_dense()
>>> B.rep
[[1, 0], [0, 2]]
"""
if self.rep.fmt == 'dense':
return self
return self.from_rep(SDM.to_ddm(self.rep))
@classmethod
def _unify_domain(cls, *matrices):
"""Convert matrices to a common domain"""
domains = {matrix.domain for matrix in matrices}
if len(domains) == 1:
return matrices
domain = reduce(lambda x, y: x.unify(y), domains)
return tuple(matrix.convert_to(domain) for matrix in matrices)
@classmethod
def _unify_fmt(cls, *matrices, fmt=None):
"""Convert matrices to the same format.
If all matrices have the same format, then return unmodified.
Otherwise convert both to the preferred format given as *fmt* which
should be 'dense' or 'sparse'.
"""
formats = {matrix.rep.fmt for matrix in matrices}
if len(formats) == 1:
return matrices
if fmt == 'sparse':
return tuple(matrix.to_sparse() for matrix in matrices)
elif fmt == 'dense':
return tuple(matrix.to_dense() for matrix in matrices)
else:
raise ValueError("fmt should be 'sparse' or 'dense'")
def unify(self, *others, fmt=None):
"""
Unifies the domains and the format of self and other
matrices.
Parameters
==========
others : DomainMatrix
fmt: string 'dense', 'sparse' or `None` (default)
The preferred format to convert to if self and other are not
already in the same format. If `None` or not specified then no
conversion if performed.
Returns
=======
Tuple[DomainMatrix]
Matrices with unified domain and format
Examples
========
Unify the domain of DomainMatrix that have different domains:
>>> from sympy import ZZ, QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
>>> B = DomainMatrix([[QQ(1, 2), QQ(2)]], (1, 2), QQ)
>>> Aq, Bq = A.unify(B)
>>> Aq
DomainMatrix([[1, 2]], (1, 2), QQ)
>>> Bq
DomainMatrix([[1/2, 2]], (1, 2), QQ)
Unify the format (dense or sparse):
>>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
>>> B = DomainMatrix({0:{0: ZZ(1)}}, (2, 2), ZZ)
>>> B.rep
{0: {0: 1}}
>>> A2, B2 = A.unify(B, fmt='dense')
>>> B2.rep
[[1, 0], [0, 0]]
See Also
========
convert_to, to_dense, to_sparse
"""
matrices = (self,) + others
matrices = DomainMatrix._unify_domain(*matrices)
if fmt is not None:
matrices = DomainMatrix._unify_fmt(*matrices, fmt=fmt)
return matrices
def to_Matrix(self):
r"""
Convert DomainMatrix to Matrix
Returns
=======
Matrix
MutableDenseMatrix for the DomainMatrix
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A.to_Matrix()
Matrix([
[1, 2],
[3, 4]])
See Also
========
from_Matrix
"""
from sympy.matrices.dense import MutableDenseMatrix
elemlist = self.rep.to_list()
elements_sympy = [self.domain.to_sympy(e) for row in elemlist for e in row]
return MutableDenseMatrix(*self.shape, elements_sympy)
def to_list(self):
return self.rep.to_list()
def to_list_flat(self):
return self.rep.to_list_flat()
def to_dok(self):
return self.rep.to_dok()
def __repr__(self):
return 'DomainMatrix(%s, %r, %r)' % (str(self.rep), self.shape, self.domain)
def transpose(self):
"""Matrix transpose of ``self``"""
return self.from_rep(self.rep.transpose())
def flat(self):
rows, cols = self.shape
return [self[i,j].element for i in range(rows) for j in range(cols)]
@property
def is_zero_matrix(self):
return self.rep.is_zero_matrix()
@property
def is_upper(self):
"""
Says whether this matrix is upper-triangular. True can be returned
even if the matrix is not square.
"""
return self.rep.is_upper()
@property
def is_lower(self):
"""
Says whether this matrix is lower-triangular. True can be returned
even if the matrix is not square.
"""
return self.rep.is_lower()
@property
def is_square(self):
return self.shape[0] == self.shape[1]
def rank(self):
rref, pivots = self.rref()
return len(pivots)
def hstack(A, *B):
r"""Horizontally stack the given matrices.
Parameters
==========
B: DomainMatrix
Matrices to stack horizontally.
Returns
=======
DomainMatrix
DomainMatrix by stacking horizontally.
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
>>> A.hstack(B)
DomainMatrix([[1, 2, 5, 6], [3, 4, 7, 8]], (2, 4), ZZ)
>>> C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
>>> A.hstack(B, C)
DomainMatrix([[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]], (2, 6), ZZ)
See Also
========
unify
"""
A, *B = A.unify(*B, fmt='dense')
return DomainMatrix.from_rep(A.rep.hstack(*(Bk.rep for Bk in B)))
def vstack(A, *B):
r"""Vertically stack the given matrices.
Parameters
==========
B: DomainMatrix
Matrices to stack vertically.
Returns
=======
DomainMatrix
DomainMatrix by stacking vertically.
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
>>> A.vstack(B)
DomainMatrix([[1, 2], [3, 4], [5, 6], [7, 8]], (4, 2), ZZ)
>>> C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
>>> A.vstack(B, C)
DomainMatrix([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]], (6, 2), ZZ)
See Also
========
unify
"""
A, *B = A.unify(*B, fmt='dense')
return DomainMatrix.from_rep(A.rep.vstack(*(Bk.rep for Bk in B)))
def applyfunc(self, func, domain=None):
if domain is None:
domain = self.domain
return self.from_rep(self.rep.applyfunc(func, domain))
def __add__(A, B):
if not isinstance(B, DomainMatrix):
return NotImplemented
A, B = A.unify(B, fmt='dense')
return A.add(B)
def __sub__(A, B):
if not isinstance(B, DomainMatrix):
return NotImplemented
A, B = A.unify(B, fmt='dense')
return A.sub(B)
def __neg__(A):
return A.neg()
def __mul__(A, B):
"""A * B"""
if isinstance(B, DomainMatrix):
A, B = A.unify(B, fmt='dense')
return A.matmul(B)
elif B in A.domain:
return A.scalarmul(B)
elif isinstance(B, DomainScalar):
A, B = A.unify(B)
return A.scalarmul(B.element)
else:
return NotImplemented
def __rmul__(A, B):
if B in A.domain:
return A.rscalarmul(B)
elif isinstance(B, DomainScalar):
A, B = A.unify(B)
return A.rscalarmul(B.element)
else:
return NotImplemented
def __pow__(A, n):
"""A ** n"""
if not isinstance(n, int):
return NotImplemented
return A.pow(n)
def _check(a, op, b, ashape, bshape):
if a.domain != b.domain:
msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain)
raise DMDomainError(msg)
if ashape != bshape:
msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape)
raise DMShapeError(msg)
if a.rep.fmt != b.rep.fmt:
msg = "Format mismatch: %s %s %s" % (a.rep.fmt, op, b.rep.fmt)
raise DMFormatError(msg)
def add(A, B):
r"""
Adds two DomainMatrix matrices of the same Domain
Parameters
==========
A, B: DomainMatrix
matrices to add
Returns
=======
DomainMatrix
DomainMatrix after Addition
Raises
======
DMShapeError
If the dimensions of the two DomainMatrix are not equal
ValueError
If the domain of the two DomainMatrix are not same
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([
... [ZZ(4), ZZ(3)],
... [ZZ(2), ZZ(1)]], (2, 2), ZZ)
>>> A.add(B)
DomainMatrix([[5, 5], [5, 5]], (2, 2), ZZ)
See Also
========
sub, matmul
"""
A._check('+', B, A.shape, B.shape)
return A.from_rep(A.rep.add(B.rep))
def sub(A, B):
r"""
Subtracts two DomainMatrix matrices of the same Domain
Parameters
==========
A, B: DomainMatrix
matrices to subtract
Returns
=======
DomainMatrix
DomainMatrix after Subtraction
Raises
======
DMShapeError
If the dimensions of the two DomainMatrix are not equal
ValueError
If the domain of the two DomainMatrix are not same
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([
... [ZZ(4), ZZ(3)],
... [ZZ(2), ZZ(1)]], (2, 2), ZZ)
>>> A.sub(B)
DomainMatrix([[-3, -1], [1, 3]], (2, 2), ZZ)
See Also
========
add, matmul
"""
A._check('-', B, A.shape, B.shape)
return A.from_rep(A.rep.sub(B.rep))
def neg(A):
r"""
Returns the negative of DomainMatrix
Parameters
==========
A : Represents a DomainMatrix
Returns
=======
DomainMatrix
DomainMatrix after Negation
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A.neg()
DomainMatrix([[-1, -2], [-3, -4]], (2, 2), ZZ)
"""
return A.from_rep(A.rep.neg())
def mul(A, b):
r"""
Performs term by term multiplication for the second DomainMatrix
w.r.t first DomainMatrix. Returns a DomainMatrix whose rows are
list of DomainMatrix matrices created after term by term multiplication.
Parameters
==========
A, B: DomainMatrix
matrices to multiply term-wise
Returns
=======
DomainMatrix
DomainMatrix after term by term multiplication
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([
... [ZZ(1), ZZ(1)],
... [ZZ(0), ZZ(1)]], (2, 2), ZZ)
>>> A.mul(B)
DomainMatrix([[DomainMatrix([[1, 1], [0, 1]], (2, 2), ZZ),
DomainMatrix([[2, 2], [0, 2]], (2, 2), ZZ)],
[DomainMatrix([[3, 3], [0, 3]], (2, 2), ZZ),
DomainMatrix([[4, 4], [0, 4]], (2, 2), ZZ)]], (2, 2), ZZ)
See Also
========
matmul
"""
return A.from_rep(A.rep.mul(b))
def rmul(A, b):
return A.from_rep(A.rep.rmul(b))
def matmul(A, B):
r"""
Performs matrix multiplication of two DomainMatrix matrices
Parameters
==========
A, B: DomainMatrix
to multiply
Returns
=======
DomainMatrix
DomainMatrix after multiplication
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([
... [ZZ(1), ZZ(1)],
... [ZZ(0), ZZ(1)]], (2, 2), ZZ)
>>> A.matmul(B)
DomainMatrix([[1, 3], [3, 7]], (2, 2), ZZ)
See Also
========
mul, pow, add, sub
"""
A._check('*', B, A.shape[1], B.shape[0])
return A.from_rep(A.rep.matmul(B.rep))
def _scalarmul(A, lamda, reverse):
if lamda == A.domain.zero:
return DomainMatrix.zeros(A.shape, A.domain)
elif lamda == A.domain.one:
return A.copy()
elif reverse:
return A.rmul(lamda)
else:
return A.mul(lamda)
def scalarmul(A, lamda):
return A._scalarmul(lamda, reverse=False)
def rscalarmul(A, lamda):
return A._scalarmul(lamda, reverse=True)
def mul_elementwise(A, B):
assert A.domain == B.domain
return A.from_rep(A.rep.mul_elementwise(B.rep))
def __truediv__(A, lamda):
""" Method for Scalar Division"""
if isinstance(lamda, int) or ZZ.of_type(lamda):
lamda = DomainScalar(ZZ(lamda), ZZ)
if not isinstance(lamda, DomainScalar):
return NotImplemented
A, lamda = A.to_field().unify(lamda)
if lamda.element == lamda.domain.zero:
raise ZeroDivisionError
if lamda.element == lamda.domain.one:
return A.to_field()
return A.mul(1 / lamda.element)
def pow(A, n):
r"""
Computes A**n
Parameters
==========
A : DomainMatrix
n : exponent for A
Returns
=======
DomainMatrix
DomainMatrix on computing A**n
Raises
======
NotImplementedError
if n is negative.
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(1)],
... [ZZ(0), ZZ(1)]], (2, 2), ZZ)
>>> A.pow(2)
DomainMatrix([[1, 2], [0, 1]], (2, 2), ZZ)
See Also
========
matmul
"""
nrows, ncols = A.shape
if nrows != ncols:
raise DMNonSquareMatrixError('Power of a nonsquare matrix')
if n < 0:
raise NotImplementedError('Negative powers')
elif n == 0:
return A.eye(nrows, A.domain)
elif n == 1:
return A
elif n % 2 == 1:
return A * A**(n - 1)
else:
sqrtAn = A ** (n // 2)
return sqrtAn * sqrtAn
def scc(self):
"""Compute the strongly connected components of a DomainMatrix
Explanation
===========
A square matrix can be considered as the adjacency matrix for a
directed graph where the row and column indices are the vertices. In
this graph if there is an edge from vertex ``i`` to vertex ``j`` if
``M[i, j]`` is nonzero. This routine computes the strongly connected
components of that graph which are subsets of the rows and columns that
are connected by some nonzero element of the matrix. The strongly
connected components are useful because many operations such as the
determinant can be computed by working with the submatrices
corresponding to each component.
Examples
========
Find the strongly connected components of a matrix:
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> M = DomainMatrix([[ZZ(1), ZZ(0), ZZ(2)],
... [ZZ(0), ZZ(3), ZZ(0)],
... [ZZ(4), ZZ(6), ZZ(5)]], (3, 3), ZZ)
>>> M.scc()
[[1], [0, 2]]
Compute the determinant from the components:
>>> MM = M.to_Matrix()
>>> MM
Matrix([
[1, 0, 2],
[0, 3, 0],
[4, 6, 5]])
>>> MM[[1], [1]]
Matrix([[3]])
>>> MM[[0, 2], [0, 2]]
Matrix([
[1, 2],
[4, 5]])
>>> MM.det()
-9
>>> MM[[1], [1]].det() * MM[[0, 2], [0, 2]].det()
-9
The components are given in reverse topological order and represent a
permutation of the rows and columns that will bring the matrix into
block lower-triangular form:
>>> MM[[1, 0, 2], [1, 0, 2]]
Matrix([
[3, 0, 0],
[0, 1, 2],
[6, 4, 5]])
Returns
=======
List of lists of integers
Each list represents a strongly connected component.
See also
========
sympy.matrices.matrices.MatrixBase.strongly_connected_components
sympy.utilities.iterables.strongly_connected_components
"""
rows, cols = self.shape
assert rows == cols
return self.rep.scc()
def rref(self):
r"""
Returns reduced-row echelon form and list of pivots for the DomainMatrix
Returns
=======
(DomainMatrix, list)
reduced-row echelon form and list of pivots for the DomainMatrix
Raises
======
ValueError
If the domain of DomainMatrix not a Field
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(2), QQ(-1), QQ(0)],
... [QQ(-1), QQ(2), QQ(-1)],
... [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ)
>>> rref_matrix, rref_pivots = A.rref()
>>> rref_matrix
DomainMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], (3, 3), QQ)
>>> rref_pivots
(0, 1, 2)
See Also
========
convert_to, lu
"""
if not self.domain.is_Field:
raise DMNotAField('Not a field')
rref_ddm, pivots = self.rep.rref()
return self.from_rep(rref_ddm), tuple(pivots)
def columnspace(self):
r"""
Returns the columnspace for the DomainMatrix
Returns
=======
DomainMatrix
The columns of this matrix form a basis for the columnspace.
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(1), QQ(-1)],
... [QQ(2), QQ(-2)]], (2, 2), QQ)
>>> A.columnspace()
DomainMatrix([[1], [2]], (2, 1), QQ)
"""
if not self.domain.is_Field:
raise DMNotAField('Not a field')
rref, pivots = self.rref()
rows, cols = self.shape
return self.extract(range(rows), pivots)
def rowspace(self):
r"""
Returns the rowspace for the DomainMatrix
Returns
=======
DomainMatrix
The rows of this matrix form a basis for the rowspace.
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(1), QQ(-1)],
... [QQ(2), QQ(-2)]], (2, 2), QQ)
>>> A.rowspace()
DomainMatrix([[1, -1]], (1, 2), QQ)
"""
if not self.domain.is_Field:
raise DMNotAField('Not a field')
rref, pivots = self.rref()
rows, cols = self.shape
return self.extract(range(len(pivots)), range(cols))
def nullspace(self):
r"""
Returns the nullspace for the DomainMatrix
Returns
=======
DomainMatrix
The rows of this matrix form a basis for the nullspace.
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(1), QQ(-1)],
... [QQ(2), QQ(-2)]], (2, 2), QQ)
>>> A.nullspace()
DomainMatrix([[1, 1]], (1, 2), QQ)
"""
if not self.domain.is_Field:
raise DMNotAField('Not a field')
return self.from_rep(self.rep.nullspace()[0])
def inv(self):
r"""
Finds the inverse of the DomainMatrix if exists
Returns
=======
DomainMatrix
DomainMatrix after inverse
Raises
======
ValueError
If the domain of DomainMatrix not a Field
DMNonSquareMatrixError
If the DomainMatrix is not a not Square DomainMatrix
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(2), QQ(-1), QQ(0)],
... [QQ(-1), QQ(2), QQ(-1)],
... [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ)
>>> A.inv()
DomainMatrix([[2/3, 1/3, 1/6], [1/3, 2/3, 1/3], [0, 0, 1/2]], (3, 3), QQ)
See Also
========
neg
"""
if not self.domain.is_Field:
raise DMNotAField('Not a field')
m, n = self.shape
if m != n:
raise DMNonSquareMatrixError
inv = self.rep.inv()
return self.from_rep(inv)
def det(self):
r"""
Returns the determinant of a Square DomainMatrix
Returns
=======
S.Complexes
determinant of Square DomainMatrix
Raises
======
ValueError
If the domain of DomainMatrix not a Field
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A.det()
-2
"""
m, n = self.shape
if m != n:
raise DMNonSquareMatrixError
return self.rep.det()
def lu(self):
r"""
Returns Lower and Upper decomposition of the DomainMatrix
Returns
=======
(L, U, exchange)
L, U are Lower and Upper decomposition of the DomainMatrix,
exchange is the list of indices of rows exchanged in the decomposition.
Raises
======
ValueError
If the domain of DomainMatrix not a Field
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(1), QQ(-1)],
... [QQ(2), QQ(-2)]], (2, 2), QQ)
>>> A.lu()
(DomainMatrix([[1, 0], [2, 1]], (2, 2), QQ), DomainMatrix([[1, -1], [0, 0]], (2, 2), QQ), [])
See Also
========
lu_solve
"""
if not self.domain.is_Field:
raise DMNotAField('Not a field')
L, U, swaps = self.rep.lu()
return self.from_rep(L), self.from_rep(U), swaps
def lu_solve(self, rhs):
r"""
Solver for DomainMatrix x in the A*x = B
Parameters
==========
rhs : DomainMatrix B
Returns
=======
DomainMatrix
x in A*x = B
Raises
======
DMShapeError
If the DomainMatrix A and rhs have different number of rows
ValueError
If the domain of DomainMatrix A not a Field
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(1), QQ(2)],
... [QQ(3), QQ(4)]], (2, 2), QQ)
>>> B = DomainMatrix([
... [QQ(1), QQ(1)],
... [QQ(0), QQ(1)]], (2, 2), QQ)
>>> A.lu_solve(B)
DomainMatrix([[-2, -1], [3/2, 1]], (2, 2), QQ)
See Also
========
lu
"""
if self.shape[0] != rhs.shape[0]:
raise DMShapeError("Shape")
if not self.domain.is_Field:
raise DMNotAField('Not a field')
sol = self.rep.lu_solve(rhs.rep)
return self.from_rep(sol)
def _solve(A, b):
# XXX: Not sure about this method or its signature. It is just created
# because it is needed by the holonomic module.
if A.shape[0] != b.shape[0]:
raise DMShapeError("Shape")
if A.domain != b.domain or not A.domain.is_Field:
raise DMNotAField('Not a field')
Aaug = A.hstack(b)
Arref, pivots = Aaug.rref()
particular = Arref.from_rep(Arref.rep.particular())
nullspace_rep, nonpivots = Arref[:,:-1].rep.nullspace()
nullspace = Arref.from_rep(nullspace_rep)
return particular, nullspace
def charpoly(self):
r"""
Returns the coefficients of the characteristic polynomial
of the DomainMatrix. These elements will be domain elements.
The domain of the elements will be same as domain of the DomainMatrix.
Returns
=======
list
coefficients of the characteristic polynomial
Raises
======
DMNonSquareMatrixError
If the DomainMatrix is not a not Square DomainMatrix
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A.charpoly()
[1, -5, -2]
"""
m, n = self.shape
if m != n:
raise DMNonSquareMatrixError("not square")
return self.rep.charpoly()
@classmethod
def eye(cls, shape, domain):
r"""
Return identity matrix of size n
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import QQ
>>> DomainMatrix.eye(3, QQ)
DomainMatrix({0: {0: 1}, 1: {1: 1}, 2: {2: 1}}, (3, 3), QQ)
"""
if isinstance(shape, int):
shape = (shape, shape)
return cls.from_rep(SDM.eye(shape, domain))
@classmethod
def diag(cls, diagonal, domain, shape=None):
r"""
Return diagonal matrix with entries from ``diagonal``.
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import ZZ
>>> DomainMatrix.diag([ZZ(5), ZZ(6)], ZZ)
DomainMatrix({0: {0: 5}, 1: {1: 6}}, (2, 2), ZZ)
"""
if shape is None:
N = len(diagonal)
shape = (N, N)
return cls.from_rep(SDM.diag(diagonal, domain, shape))
@classmethod
def zeros(cls, shape, domain, *, fmt='sparse'):
"""Returns a zero DomainMatrix of size shape, belonging to the specified domain
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import QQ
>>> DomainMatrix.zeros((2, 3), QQ)
DomainMatrix({}, (2, 3), QQ)
"""
return cls.from_rep(SDM.zeros(shape, domain))
@classmethod
def ones(cls, shape, domain):
"""Returns a DomainMatrix of 1s, of size shape, belonging to the specified domain
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import QQ
>>> DomainMatrix.ones((2,3), QQ)
DomainMatrix([[1, 1, 1], [1, 1, 1]], (2, 3), QQ)
"""
return cls.from_rep(DDM.ones(shape, domain))
def __eq__(A, B):
r"""
Checks for two DomainMatrix matrices to be equal or not
Parameters
==========
A, B: DomainMatrix
to check equality
Returns
=======
Boolean
True for equal, else False
Raises
======
NotImplementedError
If B is not a DomainMatrix
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([
... [ZZ(1), ZZ(1)],
... [ZZ(0), ZZ(1)]], (2, 2), ZZ)
>>> A.__eq__(A)
True
>>> A.__eq__(B)
False
"""
if not isinstance(A, type(B)):
return NotImplemented
return A.domain == B.domain and A.rep == B.rep
def unify_eq(A, B):
if A.shape != B.shape:
return False
if A.domain != B.domain:
A, B = A.unify(B)
return A == B
def lll(A, delta=QQ(3, 4)) -> 'DomainMatrix':
"""
Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm.
See [1]_ and [2]_.
Parameters
==========
delta : QQ, optional
The Lovász parameter. Must be in the interval (0.25, 1), with larger
values producing a more reduced basis. The default is 0.75 for
historical reasons.
Returns
=======
The reduced basis as a DomainMatrix over ZZ.
Throws
======
DMValueError: if delta is not in the range (0.25, 1)
DMShapeError: if the matrix is not of shape (m, n) with m <= n
DMDomainError: if the matrix domain is not ZZ
DMRankError: if the matrix contains linearly dependent rows
Examples
========
>>> from sympy.polys.domains import ZZ, QQ
>>> from sympy.polys.matrices import DM
>>> x = DM([[1, 0, 0, 0, -20160],
... [0, 1, 0, 0, 33768],
... [0, 0, 1, 0, 39578],
... [0, 0, 0, 1, 47757]], ZZ)
>>> y = DM([[10, -3, -2, 8, -4],
... [3, -9, 8, 1, -11],
... [-3, 13, -9, -3, -9],
... [-12, -7, -11, 9, -1]], ZZ)
>>> assert x.lll(delta=QQ(5, 6)) == y
Notes
=====
The implementation is derived from the Maple code given in Figures 4.3
and 4.4 of [3]_ (pp.68-69). It uses the efficient method of only calculating
state updates as they are required.
References
==========
.. [1] https://en.wikipedia.org/wiki/Lenstra–Lenstra–Lovász_lattice_basis_reduction_algorithm
.. [2] https://web.cs.elte.hu/~lovasz/scans/lll.pdf
.. [3] Murray R. Bremner, "Lattice Basis Reduction: An Introduction to the LLL Algorithm and Its Applications"
"""
return DomainMatrix.from_rep(A.rep.lll(delta=delta))
|
6b2dcbbf6d57dd0aaccf2b0137bd7176bf4a190b82e640c197dd1ad928f1ea93 | """
Module to define exceptions to be used in sympy.polys.matrices modules and
classes.
Ideally all exceptions raised in these modules would be defined and documented
here and not e.g. imported from matrices. Also ideally generic exceptions like
ValueError/TypeError would not be raised anywhere.
"""
class DMError(Exception):
"""Base class for errors raised by DomainMatrix"""
pass
class DMBadInputError(DMError):
"""list of lists is inconsistent with shape"""
pass
class DMDomainError(DMError):
"""domains do not match"""
pass
class DMNotAField(DMDomainError):
"""domain is not a field"""
pass
class DMFormatError(DMError):
"""mixed dense/sparse not supported"""
pass
class DMNonInvertibleMatrixError(DMError):
"""The matrix in not invertible"""
pass
class DMRankError(DMError):
"""matrix does not have expected rank"""
pass
class DMShapeError(DMError):
"""shapes are inconsistent"""
pass
class DMNonSquareMatrixError(DMShapeError):
"""The matrix is not square"""
pass
class DMValueError(DMError):
"""The value passed is invalid"""
pass
__all__ = [
'DMError', 'DMBadInputError', 'DMDomainError', 'DMFormatError',
'DMRankError', 'DMShapeError', 'DMNotAField',
'DMNonInvertibleMatrixError', 'DMNonSquareMatrixError', 'DMValueError'
]
|
a6c826bbfe5ec54dfdf9bc234ba1bcc1c2e815eb2533efc5597a4f7412bde07b | """
Module for the SDM class.
"""
from operator import add, neg, pos, sub, mul
from collections import defaultdict
from sympy.utilities.iterables import _strongly_connected_components
from .exceptions import DMBadInputError, DMDomainError, DMShapeError
from .ddm import DDM
from .lll import ddm_lll
from sympy.polys.domains import QQ
class SDM(dict):
r"""Sparse matrix based on polys domain elements
This is a dict subclass and is a wrapper for a dict of dicts that supports
basic matrix arithmetic +, -, *, **.
In order to create a new :py:class:`~.SDM`, a dict
of dicts mapping non-zero elements to their
corresponding row and column in the matrix is needed.
We also need to specify the shape and :py:class:`~.Domain`
of our :py:class:`~.SDM` object.
We declare a 2x2 :py:class:`~.SDM` matrix belonging
to QQ domain as shown below.
The 2x2 Matrix in the example is
.. math::
A = \left[\begin{array}{ccc}
0 & \frac{1}{2} \\
0 & 0 \end{array} \right]
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy import QQ
>>> elemsdict = {0:{1:QQ(1, 2)}}
>>> A = SDM(elemsdict, (2, 2), QQ)
>>> A
{0: {1: 1/2}}
We can manipulate :py:class:`~.SDM` the same way
as a Matrix class
>>> from sympy import ZZ
>>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
>>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ)
>>> A + B
{0: {0: 3, 1: 2}, 1: {0: 1, 1: 4}}
Multiplication
>>> A*B
{0: {1: 8}, 1: {0: 3}}
>>> A*ZZ(2)
{0: {1: 4}, 1: {0: 2}}
"""
fmt = 'sparse'
def __init__(self, elemsdict, shape, domain):
super().__init__(elemsdict)
self.shape = self.rows, self.cols = m, n = shape
self.domain = domain
if not all(0 <= r < m for r in self):
raise DMBadInputError("Row out of range")
if not all(0 <= c < n for row in self.values() for c in row):
raise DMBadInputError("Column out of range")
def getitem(self, i, j):
try:
return self[i][j]
except KeyError:
m, n = self.shape
if -m <= i < m and -n <= j < n:
try:
return self[i % m][j % n]
except KeyError:
return self.domain.zero
else:
raise IndexError("index out of range")
def setitem(self, i, j, value):
m, n = self.shape
if not (-m <= i < m and -n <= j < n):
raise IndexError("index out of range")
i, j = i % m, j % n
if value:
try:
self[i][j] = value
except KeyError:
self[i] = {j: value}
else:
rowi = self.get(i, None)
if rowi is not None:
try:
del rowi[j]
except KeyError:
pass
else:
if not rowi:
del self[i]
def extract_slice(self, slice1, slice2):
m, n = self.shape
ri = range(m)[slice1]
ci = range(n)[slice2]
sdm = {}
for i, row in self.items():
if i in ri:
row = {ci.index(j): e for j, e in row.items() if j in ci}
if row:
sdm[ri.index(i)] = row
return self.new(sdm, (len(ri), len(ci)), self.domain)
def extract(self, rows, cols):
if not (self and rows and cols):
return self.zeros((len(rows), len(cols)), self.domain)
m, n = self.shape
if not (-m <= min(rows) <= max(rows) < m):
raise IndexError('Row index out of range')
if not (-n <= min(cols) <= max(cols) < n):
raise IndexError('Column index out of range')
# rows and cols can contain duplicates e.g. M[[1, 2, 2], [0, 1]]
# Build a map from row/col in self to list of rows/cols in output
rowmap = defaultdict(list)
colmap = defaultdict(list)
for i2, i1 in enumerate(rows):
rowmap[i1 % m].append(i2)
for j2, j1 in enumerate(cols):
colmap[j1 % n].append(j2)
# Used to efficiently skip zero rows/cols
rowset = set(rowmap)
colset = set(colmap)
sdm1 = self
sdm2 = {}
for i1 in rowset & set(sdm1):
row1 = sdm1[i1]
row2 = {}
for j1 in colset & set(row1):
row1_j1 = row1[j1]
for j2 in colmap[j1]:
row2[j2] = row1_j1
if row2:
for i2 in rowmap[i1]:
sdm2[i2] = row2.copy()
return self.new(sdm2, (len(rows), len(cols)), self.domain)
def __str__(self):
rowsstr = []
for i, row in self.items():
elemsstr = ', '.join('%s: %s' % (j, elem) for j, elem in row.items())
rowsstr.append('%s: {%s}' % (i, elemsstr))
return '{%s}' % ', '.join(rowsstr)
def __repr__(self):
cls = type(self).__name__
rows = dict.__repr__(self)
return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain)
@classmethod
def new(cls, sdm, shape, domain):
"""
Parameters
==========
sdm: A dict of dicts for non-zero elements in SDM
shape: tuple representing dimension of SDM
domain: Represents :py:class:`~.Domain` of SDM
Returns
=======
An :py:class:`~.SDM` object
Examples
========
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy import QQ
>>> elemsdict = {0:{1: QQ(2)}}
>>> A = SDM.new(elemsdict, (2, 2), QQ)
>>> A
{0: {1: 2}}
"""
return cls(sdm, shape, domain)
def copy(A):
"""
Returns the copy of a :py:class:`~.SDM` object
Examples
========
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy import QQ
>>> elemsdict = {0:{1:QQ(2)}, 1:{}}
>>> A = SDM(elemsdict, (2, 2), QQ)
>>> B = A.copy()
>>> B
{0: {1: 2}, 1: {}}
"""
Ac = {i: Ai.copy() for i, Ai in A.items()}
return A.new(Ac, A.shape, A.domain)
@classmethod
def from_list(cls, ddm, shape, domain):
"""
Parameters
==========
ddm:
list of lists containing domain elements
shape:
Dimensions of :py:class:`~.SDM` matrix
domain:
Represents :py:class:`~.Domain` of :py:class:`~.SDM` object
Returns
=======
:py:class:`~.SDM` containing elements of ddm
Examples
========
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy import QQ
>>> ddm = [[QQ(1, 2), QQ(0)], [QQ(0), QQ(3, 4)]]
>>> A = SDM.from_list(ddm, (2, 2), QQ)
>>> A
{0: {0: 1/2}, 1: {1: 3/4}}
"""
m, n = shape
if not (len(ddm) == m and all(len(row) == n for row in ddm)):
raise DMBadInputError("Inconsistent row-list/shape")
getrow = lambda i: {j:ddm[i][j] for j in range(n) if ddm[i][j]}
irows = ((i, getrow(i)) for i in range(m))
sdm = {i: row for i, row in irows if row}
return cls(sdm, shape, domain)
@classmethod
def from_ddm(cls, ddm):
"""
converts object of :py:class:`~.DDM` to
:py:class:`~.SDM`
Examples
========
>>> from sympy.polys.matrices.ddm import DDM
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy import QQ
>>> ddm = DDM( [[QQ(1, 2), 0], [0, QQ(3, 4)]], (2, 2), QQ)
>>> A = SDM.from_ddm(ddm)
>>> A
{0: {0: 1/2}, 1: {1: 3/4}}
"""
return cls.from_list(ddm, ddm.shape, ddm.domain)
def to_list(M):
"""
Converts a :py:class:`~.SDM` object to a list
Examples
========
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy import QQ
>>> elemsdict = {0:{1:QQ(2)}, 1:{}}
>>> A = SDM(elemsdict, (2, 2), QQ)
>>> A.to_list()
[[0, 2], [0, 0]]
"""
m, n = M.shape
zero = M.domain.zero
ddm = [[zero] * n for _ in range(m)]
for i, row in M.items():
for j, e in row.items():
ddm[i][j] = e
return ddm
def to_list_flat(M):
m, n = M.shape
zero = M.domain.zero
flat = [zero] * (m * n)
for i, row in M.items():
for j, e in row.items():
flat[i*n + j] = e
return flat
def to_dok(M):
return {(i, j): e for i, row in M.items() for j, e in row.items()}
def to_ddm(M):
"""
Convert a :py:class:`~.SDM` object to a :py:class:`~.DDM` object
Examples
========
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy import QQ
>>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ)
>>> A.to_ddm()
[[0, 2], [0, 0]]
"""
return DDM(M.to_list(), M.shape, M.domain)
def to_sdm(M):
return M
@classmethod
def zeros(cls, shape, domain):
r"""
Returns a :py:class:`~.SDM` of size shape,
belonging to the specified domain
In the example below we declare a matrix A where,
.. math::
A := \left[\begin{array}{ccc}
0 & 0 & 0 \\
0 & 0 & 0 \end{array} \right]
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy import QQ
>>> A = SDM.zeros((2, 3), QQ)
>>> A
{}
"""
return cls({}, shape, domain)
@classmethod
def ones(cls, shape, domain):
one = domain.one
m, n = shape
row = dict(zip(range(n), [one]*n))
sdm = {i: row.copy() for i in range(m)}
return cls(sdm, shape, domain)
@classmethod
def eye(cls, shape, domain):
"""
Returns a identity :py:class:`~.SDM` matrix of dimensions
size x size, belonging to the specified domain
Examples
========
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy import QQ
>>> I = SDM.eye((2, 2), QQ)
>>> I
{0: {0: 1}, 1: {1: 1}}
"""
rows, cols = shape
one = domain.one
sdm = {i: {i: one} for i in range(min(rows, cols))}
return cls(sdm, shape, domain)
@classmethod
def diag(cls, diagonal, domain, shape):
sdm = {i: {i: v} for i, v in enumerate(diagonal) if v}
return cls(sdm, shape, domain)
def transpose(M):
"""
Returns the transpose of a :py:class:`~.SDM` matrix
Examples
========
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy import QQ
>>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ)
>>> A.transpose()
{1: {0: 2}}
"""
MT = sdm_transpose(M)
return M.new(MT, M.shape[::-1], M.domain)
def __add__(A, B):
if not isinstance(B, SDM):
return NotImplemented
return A.add(B)
def __sub__(A, B):
if not isinstance(B, SDM):
return NotImplemented
return A.sub(B)
def __neg__(A):
return A.neg()
def __mul__(A, B):
"""A * B"""
if isinstance(B, SDM):
return A.matmul(B)
elif B in A.domain:
return A.mul(B)
else:
return NotImplemented
def __rmul__(a, b):
if b in a.domain:
return a.rmul(b)
else:
return NotImplemented
def matmul(A, B):
"""
Performs matrix multiplication of two SDM matrices
Parameters
==========
A, B: SDM to multiply
Returns
=======
SDM
SDM after multiplication
Raises
======
DomainError
If domain of A does not match
with that of B
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
>>> B = SDM({0:{0:ZZ(2), 1:ZZ(3)}, 1:{0:ZZ(4)}}, (2, 2), ZZ)
>>> A.matmul(B)
{0: {0: 8}, 1: {0: 2, 1: 3}}
"""
if A.domain != B.domain:
raise DMDomainError
m, n = A.shape
n2, o = B.shape
if n != n2:
raise DMShapeError
C = sdm_matmul(A, B, A.domain, m, o)
return A.new(C, (m, o), A.domain)
def mul(A, b):
"""
Multiplies each element of A with a scalar b
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
>>> A.mul(ZZ(3))
{0: {1: 6}, 1: {0: 3}}
"""
Csdm = unop_dict(A, lambda aij: aij*b)
return A.new(Csdm, A.shape, A.domain)
def rmul(A, b):
Csdm = unop_dict(A, lambda aij: b*aij)
return A.new(Csdm, A.shape, A.domain)
def mul_elementwise(A, B):
if A.domain != B.domain:
raise DMDomainError
if A.shape != B.shape:
raise DMShapeError
zero = A.domain.zero
fzero = lambda e: zero
Csdm = binop_dict(A, B, mul, fzero, fzero)
return A.new(Csdm, A.shape, A.domain)
def add(A, B):
"""
Adds two :py:class:`~.SDM` matrices
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
>>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ)
>>> A.add(B)
{0: {0: 3, 1: 2}, 1: {0: 1, 1: 4}}
"""
Csdm = binop_dict(A, B, add, pos, pos)
return A.new(Csdm, A.shape, A.domain)
def sub(A, B):
"""
Subtracts two :py:class:`~.SDM` matrices
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
>>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ)
>>> A.sub(B)
{0: {0: -3, 1: 2}, 1: {0: 1, 1: -4}}
"""
Csdm = binop_dict(A, B, sub, pos, neg)
return A.new(Csdm, A.shape, A.domain)
def neg(A):
"""
Returns the negative of a :py:class:`~.SDM` matrix
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
>>> A.neg()
{0: {1: -2}, 1: {0: -1}}
"""
Csdm = unop_dict(A, neg)
return A.new(Csdm, A.shape, A.domain)
def convert_to(A, K):
"""
Converts the :py:class:`~.Domain` of a :py:class:`~.SDM` matrix to K
Examples
========
>>> from sympy import ZZ, QQ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
>>> A.convert_to(QQ)
{0: {1: 2}, 1: {0: 1}}
"""
Kold = A.domain
if K == Kold:
return A.copy()
Ak = unop_dict(A, lambda e: K.convert_from(e, Kold))
return A.new(Ak, A.shape, K)
def scc(A):
"""Strongly connected components of a square matrix *A*.
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{0: ZZ(2)}, 1:{1:ZZ(1)}}, (2, 2), ZZ)
>>> A.scc()
[[0], [1]]
See also
========
sympy.polys.matrices.domainmatrix.DomainMatrix.scc
"""
rows, cols = A.shape
assert rows == cols
V = range(rows)
Emap = {v: list(A.get(v, [])) for v in V}
return _strongly_connected_components(V, Emap)
def rref(A):
"""
Returns reduced-row echelon form and list of pivots for the :py:class:`~.SDM`
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(2), 1:QQ(4)}}, (2, 2), QQ)
>>> A.rref()
({0: {0: 1, 1: 2}}, [0])
"""
B, pivots, _ = sdm_irref(A)
return A.new(B, A.shape, A.domain), pivots
def inv(A):
"""
Returns inverse of a matrix A
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
>>> A.inv()
{0: {0: -2, 1: 1}, 1: {0: 3/2, 1: -1/2}}
"""
return A.from_ddm(A.to_ddm().inv())
def det(A):
"""
Returns determinant of A
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
>>> A.det()
-2
"""
return A.to_ddm().det()
def lu(A):
"""
Returns LU decomposition for a matrix A
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
>>> A.lu()
({0: {0: 1}, 1: {0: 3, 1: 1}}, {0: {0: 1, 1: 2}, 1: {1: -2}}, [])
"""
L, U, swaps = A.to_ddm().lu()
return A.from_ddm(L), A.from_ddm(U), swaps
def lu_solve(A, b):
"""
Uses LU decomposition to solve Ax = b,
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
>>> b = SDM({0:{0:QQ(1)}, 1:{0:QQ(2)}}, (2, 1), QQ)
>>> A.lu_solve(b)
{1: {0: 1/2}}
"""
return A.from_ddm(A.to_ddm().lu_solve(b.to_ddm()))
def nullspace(A):
"""
Returns nullspace for a :py:class:`~.SDM` matrix A
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0: QQ(2), 1: QQ(4)}}, (2, 2), QQ)
>>> A.nullspace()
({0: {0: -2, 1: 1}}, [1])
"""
ncols = A.shape[1]
one = A.domain.one
B, pivots, nzcols = sdm_irref(A)
K, nonpivots = sdm_nullspace_from_rref(B, one, ncols, pivots, nzcols)
K = dict(enumerate(K))
shape = (len(K), ncols)
return A.new(K, shape, A.domain), nonpivots
def particular(A):
ncols = A.shape[1]
B, pivots, nzcols = sdm_irref(A)
P = sdm_particular_from_rref(B, ncols, pivots)
rep = {0:P} if P else {}
return A.new(rep, (1, ncols-1), A.domain)
def hstack(A, *B):
"""Horizontally stacks :py:class:`~.SDM` matrices.
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ)
>>> B = SDM({0: {0: ZZ(5), 1: ZZ(6)}, 1: {0: ZZ(7), 1: ZZ(8)}}, (2, 2), ZZ)
>>> A.hstack(B)
{0: {0: 1, 1: 2, 2: 5, 3: 6}, 1: {0: 3, 1: 4, 2: 7, 3: 8}}
>>> C = SDM({0: {0: ZZ(9), 1: ZZ(10)}, 1: {0: ZZ(11), 1: ZZ(12)}}, (2, 2), ZZ)
>>> A.hstack(B, C)
{0: {0: 1, 1: 2, 2: 5, 3: 6, 4: 9, 5: 10}, 1: {0: 3, 1: 4, 2: 7, 3: 8, 4: 11, 5: 12}}
"""
Anew = dict(A.copy())
rows, cols = A.shape
domain = A.domain
for Bk in B:
Bkrows, Bkcols = Bk.shape
assert Bkrows == rows
assert Bk.domain == domain
for i, Bki in Bk.items():
Ai = Anew.get(i, None)
if Ai is None:
Anew[i] = Ai = {}
for j, Bkij in Bki.items():
Ai[j + cols] = Bkij
cols += Bkcols
return A.new(Anew, (rows, cols), A.domain)
def vstack(A, *B):
"""Vertically stacks :py:class:`~.SDM` matrices.
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices.sdm import SDM
>>> A = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ)
>>> B = SDM({0: {0: ZZ(5), 1: ZZ(6)}, 1: {0: ZZ(7), 1: ZZ(8)}}, (2, 2), ZZ)
>>> A.vstack(B)
{0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}, 2: {0: 5, 1: 6}, 3: {0: 7, 1: 8}}
>>> C = SDM({0: {0: ZZ(9), 1: ZZ(10)}, 1: {0: ZZ(11), 1: ZZ(12)}}, (2, 2), ZZ)
>>> A.vstack(B, C)
{0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}, 2: {0: 5, 1: 6}, 3: {0: 7, 1: 8}, 4: {0: 9, 1: 10}, 5: {0: 11, 1: 12}}
"""
Anew = dict(A.copy())
rows, cols = A.shape
domain = A.domain
for Bk in B:
Bkrows, Bkcols = Bk.shape
assert Bkcols == cols
assert Bk.domain == domain
for i, Bki in Bk.items():
Anew[i + rows] = Bki
rows += Bkrows
return A.new(Anew, (rows, cols), A.domain)
def applyfunc(self, func, domain):
sdm = {i: {j: func(e) for j, e in row.items()} for i, row in self.items()}
return self.new(sdm, self.shape, domain)
def charpoly(A):
"""
Returns the coefficients of the characteristic polynomial
of the :py:class:`~.SDM` matrix. These elements will be domain elements.
The domain of the elements will be same as domain of the :py:class:`~.SDM`.
Examples
========
>>> from sympy import QQ, Symbol
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy.polys import Poly
>>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
>>> A.charpoly()
[1, -5, -2]
We can create a polynomial using the
coefficients using :py:class:`~.Poly`
>>> x = Symbol('x')
>>> p = Poly(A.charpoly(), x, domain=A.domain)
>>> p
Poly(x**2 - 5*x - 2, x, domain='QQ')
"""
return A.to_ddm().charpoly()
def is_zero_matrix(self):
"""
Says whether this matrix has all zero entries.
"""
return not self
def is_upper(self):
"""
Says whether this matrix is upper-triangular. True can be returned
even if the matrix is not square.
"""
return all(i <= j for i, row in self.items() for j in row)
def is_lower(self):
"""
Says whether this matrix is lower-triangular. True can be returned
even if the matrix is not square.
"""
return all(i >= j for i, row in self.items() for j in row)
def lll(A, delta=QQ(3, 4)) -> 'SDM':
return A.from_ddm(ddm_lll(A.to_ddm(), delta))
def binop_dict(A, B, fab, fa, fb):
Anz, Bnz = set(A), set(B)
C = {}
for i in Anz & Bnz:
Ai, Bi = A[i], B[i]
Ci = {}
Anzi, Bnzi = set(Ai), set(Bi)
for j in Anzi & Bnzi:
Cij = fab(Ai[j], Bi[j])
if Cij:
Ci[j] = Cij
for j in Anzi - Bnzi:
Cij = fa(Ai[j])
if Cij:
Ci[j] = Cij
for j in Bnzi - Anzi:
Cij = fb(Bi[j])
if Cij:
Ci[j] = Cij
if Ci:
C[i] = Ci
for i in Anz - Bnz:
Ai = A[i]
Ci = {}
for j, Aij in Ai.items():
Cij = fa(Aij)
if Cij:
Ci[j] = Cij
if Ci:
C[i] = Ci
for i in Bnz - Anz:
Bi = B[i]
Ci = {}
for j, Bij in Bi.items():
Cij = fb(Bij)
if Cij:
Ci[j] = Cij
if Ci:
C[i] = Ci
return C
def unop_dict(A, f):
B = {}
for i, Ai in A.items():
Bi = {}
for j, Aij in Ai.items():
Bij = f(Aij)
if Bij:
Bi[j] = Bij
if Bi:
B[i] = Bi
return B
def sdm_transpose(M):
MT = {}
for i, Mi in M.items():
for j, Mij in Mi.items():
try:
MT[j][i] = Mij
except KeyError:
MT[j] = {i: Mij}
return MT
def sdm_matmul(A, B, K, m, o):
#
# Should be fast if A and B are very sparse.
# Consider e.g. A = B = eye(1000).
#
# The idea here is that we compute C = A*B in terms of the rows of C and
# B since the dict of dicts representation naturally stores the matrix as
# rows. The ith row of C (Ci) is equal to the sum of Aik * Bk where Bk is
# the kth row of B. The algorithm below loops over each nonzero element
# Aik of A and if the corresponding row Bj is nonzero then we do
# Ci += Aik * Bk.
# To make this more efficient we don't need to loop over all elements Aik.
# Instead for each row Ai we compute the intersection of the nonzero
# columns in Ai with the nonzero rows in B. That gives the k such that
# Aik and Bk are both nonzero. In Python the intersection of two sets
# of int can be computed very efficiently.
#
if K.is_EXRAW:
return sdm_matmul_exraw(A, B, K, m, o)
C = {}
B_knz = set(B)
for i, Ai in A.items():
Ci = {}
Ai_knz = set(Ai)
for k in Ai_knz & B_knz:
Aik = Ai[k]
for j, Bkj in B[k].items():
Cij = Ci.get(j, None)
if Cij is not None:
Cij = Cij + Aik * Bkj
if Cij:
Ci[j] = Cij
else:
Ci.pop(j)
else:
Cij = Aik * Bkj
if Cij:
Ci[j] = Cij
if Ci:
C[i] = Ci
return C
def sdm_matmul_exraw(A, B, K, m, o):
#
# Like sdm_matmul above except that:
#
# - Handles cases like 0*oo -> nan (sdm_matmul skips multipication by zero)
# - Uses K.sum (Add(*items)) for efficient addition of Expr
#
zero = K.zero
C = {}
B_knz = set(B)
for i, Ai in A.items():
Ci_list = defaultdict(list)
Ai_knz = set(Ai)
# Nonzero row/column pair
for k in Ai_knz & B_knz:
Aik = Ai[k]
if zero * Aik == zero:
# This is the main inner loop:
for j, Bkj in B[k].items():
Ci_list[j].append(Aik * Bkj)
else:
for j in range(o):
Ci_list[j].append(Aik * B[k].get(j, zero))
# Zero row in B, check for infinities in A
for k in Ai_knz - B_knz:
zAik = zero * Ai[k]
if zAik != zero:
for j in range(o):
Ci_list[j].append(zAik)
# Add terms using K.sum (Add(*terms)) for efficiency
Ci = {}
for j, Cij_list in Ci_list.items():
Cij = K.sum(Cij_list)
if Cij:
Ci[j] = Cij
if Ci:
C[i] = Ci
# Find all infinities in B
for k, Bk in B.items():
for j, Bkj in Bk.items():
if zero * Bkj != zero:
for i in range(m):
Aik = A.get(i, {}).get(k, zero)
# If Aik is not zero then this was handled above
if Aik == zero:
Ci = C.get(i, {})
Cij = Ci.get(j, zero) + Aik * Bkj
if Cij != zero:
Ci[j] = Cij
else: # pragma: no cover
# Not sure how we could get here but let's raise an
# exception just in case.
raise RuntimeError
C[i] = Ci
return C
def sdm_irref(A):
"""RREF and pivots of a sparse matrix *A*.
Compute the reduced row echelon form (RREF) of the matrix *A* and return a
list of the pivot columns. This routine does not work in place and leaves
the original matrix *A* unmodified.
Examples
========
This routine works with a dict of dicts sparse representation of a matrix:
>>> from sympy import QQ
>>> from sympy.polys.matrices.sdm import sdm_irref
>>> A = {0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}
>>> Arref, pivots, _ = sdm_irref(A)
>>> Arref
{0: {0: 1}, 1: {1: 1}}
>>> pivots
[0, 1]
The analogous calculation with :py:class:`~.Matrix` would be
>>> from sympy import Matrix
>>> M = Matrix([[1, 2], [3, 4]])
>>> Mrref, pivots = M.rref()
>>> Mrref
Matrix([
[1, 0],
[0, 1]])
>>> pivots
(0, 1)
Notes
=====
The cost of this algorithm is determined purely by the nonzero elements of
the matrix. No part of the cost of any step in this algorithm depends on
the number of rows or columns in the matrix. No step depends even on the
number of nonzero rows apart from the primary loop over those rows. The
implementation is much faster than ddm_rref for sparse matrices. In fact
at the time of writing it is also (slightly) faster than the dense
implementation even if the input is a fully dense matrix so it seems to be
faster in all cases.
The elements of the matrix should support exact division with ``/``. For
example elements of any domain that is a field (e.g. ``QQ``) should be
fine. No attempt is made to handle inexact arithmetic.
"""
#
# Any zeros in the matrix are not stored at all so an element is zero if
# its row dict has no index at that key. A row is entirely zero if its
# row index is not in the outer dict. Since rref reorders the rows and
# removes zero rows we can completely discard the row indices. The first
# step then copies the row dicts into a list sorted by the index of the
# first nonzero column in each row.
#
# The algorithm then processes each row Ai one at a time. Previously seen
# rows are used to cancel their pivot columns from Ai. Then a pivot from
# Ai is chosen and is cancelled from all previously seen rows. At this
# point Ai joins the previously seen rows. Once all rows are seen all
# elimination has occurred and the rows are sorted by pivot column index.
#
# The previously seen rows are stored in two separate groups. The reduced
# group consists of all rows that have been reduced to a single nonzero
# element (the pivot). There is no need to attempt any further reduction
# with these. Rows that still have other nonzeros need to be considered
# when Ai is cancelled from the previously seen rows.
#
# A dict nonzerocolumns is used to map from a column index to a set of
# previously seen rows that still have a nonzero element in that column.
# This means that we can cancel the pivot from Ai into the previously seen
# rows without needing to loop over each row that might have a zero in
# that column.
#
# Row dicts sorted by index of first nonzero column
# (Maybe sorting is not needed/useful.)
Arows = sorted((Ai.copy() for Ai in A.values()), key=min)
# Each processed row has an associated pivot column.
# pivot_row_map maps from the pivot column index to the row dict.
# This means that we can represent a set of rows purely as a set of their
# pivot indices.
pivot_row_map = {}
# Set of pivot indices for rows that are fully reduced to a single nonzero.
reduced_pivots = set()
# Set of pivot indices for rows not fully reduced
nonreduced_pivots = set()
# Map from column index to a set of pivot indices representing the rows
# that have a nonzero at that column.
nonzero_columns = defaultdict(set)
while Arows:
# Select pivot element and row
Ai = Arows.pop()
# Nonzero columns from fully reduced pivot rows can be removed
Ai = {j: Aij for j, Aij in Ai.items() if j not in reduced_pivots}
# Others require full row cancellation
for j in nonreduced_pivots & set(Ai):
Aj = pivot_row_map[j]
Aij = Ai[j]
Ainz = set(Ai)
Ajnz = set(Aj)
for k in Ajnz - Ainz:
Ai[k] = - Aij * Aj[k]
Ai.pop(j)
Ainz.remove(j)
for k in Ajnz & Ainz:
Aik = Ai[k] - Aij * Aj[k]
if Aik:
Ai[k] = Aik
else:
Ai.pop(k)
# We have now cancelled previously seen pivots from Ai.
# If it is zero then discard it.
if not Ai:
continue
# Choose a pivot from Ai:
j = min(Ai)
Aij = Ai[j]
pivot_row_map[j] = Ai
Ainz = set(Ai)
# Normalise the pivot row to make the pivot 1.
#
# This approach is slow for some domains. Cross cancellation might be
# better for e.g. QQ(x) with division delayed to the final steps.
Aijinv = Aij**-1
for l in Ai:
Ai[l] *= Aijinv
# Use Aij to cancel column j from all previously seen rows
for k in nonzero_columns.pop(j, ()):
Ak = pivot_row_map[k]
Akj = Ak[j]
Aknz = set(Ak)
for l in Ainz - Aknz:
Ak[l] = - Akj * Ai[l]
nonzero_columns[l].add(k)
Ak.pop(j)
Aknz.remove(j)
for l in Ainz & Aknz:
Akl = Ak[l] - Akj * Ai[l]
if Akl:
Ak[l] = Akl
else:
# Drop nonzero elements
Ak.pop(l)
if l != j:
nonzero_columns[l].remove(k)
if len(Ak) == 1:
reduced_pivots.add(k)
nonreduced_pivots.remove(k)
if len(Ai) == 1:
reduced_pivots.add(j)
else:
nonreduced_pivots.add(j)
for l in Ai:
if l != j:
nonzero_columns[l].add(j)
# All done!
pivots = sorted(reduced_pivots | nonreduced_pivots)
pivot2row = {p: n for n, p in enumerate(pivots)}
nonzero_columns = {c: set(pivot2row[p] for p in s) for c, s in nonzero_columns.items()}
rows = [pivot_row_map[i] for i in pivots]
rref = dict(enumerate(rows))
return rref, pivots, nonzero_columns
def sdm_nullspace_from_rref(A, one, ncols, pivots, nonzero_cols):
"""Get nullspace from A which is in RREF"""
nonpivots = sorted(set(range(ncols)) - set(pivots))
K = []
for j in nonpivots:
Kj = {j:one}
for i in nonzero_cols.get(j, ()):
Kj[pivots[i]] = -A[i][j]
K.append(Kj)
return K, nonpivots
def sdm_particular_from_rref(A, ncols, pivots):
"""Get a particular solution from A which is in RREF"""
P = {}
for i, j in enumerate(pivots):
Ain = A[i].get(ncols-1, None)
if Ain is not None:
P[j] = Ain / A[i][j]
return P
|
2dc158d4e004bc8697cdd4e80fce15bd4fc3666370452899b773c0fba602c0c4 | """
Module for the ddm_* routines for operating on a matrix in list of lists
matrix representation.
These routines are used internally by the DDM class which also provides a
friendlier interface for them. The idea here is to implement core matrix
routines in a way that can be applied to any simple list representation
without the need to use any particular matrix class. For example we can
compute the RREF of a matrix like:
>>> from sympy.polys.matrices.dense import ddm_irref
>>> M = [[1, 2, 3], [4, 5, 6]]
>>> pivots = ddm_irref(M)
>>> M
[[1.0, 0.0, -1.0], [0, 1.0, 2.0]]
These are lower-level routines that work mostly in place.The routines at this
level should not need to know what the domain of the elements is but should
ideally document what operations they will use and what functions they need to
be provided with.
The next-level up is the DDM class which uses these routines but wraps them up
with an interface that handles copying etc and keeps track of the Domain of
the elements of the matrix:
>>> from sympy.polys.domains import QQ
>>> from sympy.polys.matrices.ddm import DDM
>>> M = DDM([[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]], (2, 3), QQ)
>>> M
[[1, 2, 3], [4, 5, 6]]
>>> Mrref, pivots = M.rref()
>>> Mrref
[[1, 0, -1], [0, 1, 2]]
"""
from __future__ import annotations
from operator import mul
from .exceptions import (
DMShapeError,
DMNonInvertibleMatrixError,
DMNonSquareMatrixError,
)
from typing import Sequence, TypeVar
from sympy.polys.matrices._typing import RingElement
T = TypeVar('T')
R = TypeVar('R', bound=RingElement)
def ddm_transpose(matrix: Sequence[Sequence[T]]) -> list[list[T]]:
"""matrix transpose"""
return list(map(list, zip(*matrix)))
def ddm_iadd(a: list[list[R]], b: Sequence[Sequence[R]]) -> None:
"""a += b"""
for ai, bi in zip(a, b):
for j, bij in enumerate(bi):
ai[j] += bij
def ddm_isub(a: list[list[R]], b: Sequence[Sequence[R]]) -> None:
"""a -= b"""
for ai, bi in zip(a, b):
for j, bij in enumerate(bi):
ai[j] -= bij
def ddm_ineg(a: list[list[R]]) -> None:
"""a <-- -a"""
for ai in a:
for j, aij in enumerate(ai):
ai[j] = -aij
def ddm_imul(a: list[list[R]], b: R) -> None:
for ai in a:
for j, aij in enumerate(ai):
ai[j] = aij * b
def ddm_irmul(a: list[list[R]], b: R) -> None:
for ai in a:
for j, aij in enumerate(ai):
ai[j] = b * aij
def ddm_imatmul(
a: list[list[R]], b: Sequence[Sequence[R]], c: Sequence[Sequence[R]]
) -> None:
"""a += b @ c"""
cT = list(zip(*c))
for bi, ai in zip(b, a):
for j, cTj in enumerate(cT):
ai[j] = sum(map(mul, bi, cTj), ai[j])
def ddm_irref(a, _partial_pivot=False):
"""a <-- rref(a)"""
# a is (m x n)
m = len(a)
if not m:
return []
n = len(a[0])
i = 0
pivots = []
for j in range(n):
# Proper pivoting should be used for all domains for performance
# reasons but it is only strictly needed for RR and CC (and possibly
# other domains like RR(x)). This path is used by DDM.rref() if the
# domain is RR or CC. It uses partial (row) pivoting based on the
# absolute value of the pivot candidates.
if _partial_pivot:
ip = max(range(i, m), key=lambda ip: abs(a[ip][j]))
a[i], a[ip] = a[ip], a[i]
# pivot
aij = a[i][j]
# zero-pivot
if not aij:
for ip in range(i+1, m):
aij = a[ip][j]
# row-swap
if aij:
a[i], a[ip] = a[ip], a[i]
break
else:
# next column
continue
# normalise row
ai = a[i]
aijinv = aij**-1
for l in range(j, n):
ai[l] *= aijinv # ai[j] = one
# eliminate above and below to the right
for k, ak in enumerate(a):
if k == i or not ak[j]:
continue
akj = ak[j]
ak[j] -= akj # ak[j] = zero
for l in range(j+1, n):
ak[l] -= akj * ai[l]
# next row
pivots.append(j)
i += 1
# no more rows?
if i >= m:
break
return pivots
def ddm_idet(a, K):
"""a <-- echelon(a); return det"""
# Bareiss algorithm
# https://www.math.usm.edu/perry/Research/Thesis_DRL.pdf
# a is (m x n)
m = len(a)
if not m:
return K.one
n = len(a[0])
exquo = K.exquo
# uf keeps track of the sign change from row swaps
uf = K.one
for k in range(n-1):
if not a[k][k]:
for i in range(k+1, n):
if a[i][k]:
a[k], a[i] = a[i], a[k]
uf = -uf
break
else:
return K.zero
akkm1 = a[k-1][k-1] if k else K.one
for i in range(k+1, n):
for j in range(k+1, n):
a[i][j] = exquo(a[i][j]*a[k][k] - a[i][k]*a[k][j], akkm1)
return uf * a[-1][-1]
def ddm_iinv(ainv, a, K):
if not K.is_Field:
raise ValueError('Not a field')
# a is (m x n)
m = len(a)
if not m:
return
n = len(a[0])
if m != n:
raise DMNonSquareMatrixError
eye = [[K.one if i==j else K.zero for j in range(n)] for i in range(n)]
Aaug = [row + eyerow for row, eyerow in zip(a, eye)]
pivots = ddm_irref(Aaug)
if pivots != list(range(n)):
raise DMNonInvertibleMatrixError('Matrix det == 0; not invertible.')
ainv[:] = [row[n:] for row in Aaug]
def ddm_ilu_split(L, U, K):
"""L, U <-- LU(U)"""
m = len(U)
if not m:
return []
n = len(U[0])
swaps = ddm_ilu(U)
zeros = [K.zero] * min(m, n)
for i in range(1, m):
j = min(i, n)
L[i][:j] = U[i][:j]
U[i][:j] = zeros[:j]
return swaps
def ddm_ilu(a):
"""a <-- LU(a)"""
m = len(a)
if not m:
return []
n = len(a[0])
swaps = []
for i in range(min(m, n)):
if not a[i][i]:
for ip in range(i+1, m):
if a[ip][i]:
swaps.append((i, ip))
a[i], a[ip] = a[ip], a[i]
break
else:
# M = Matrix([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]])
continue
for j in range(i+1, m):
l_ji = a[j][i] / a[i][i]
a[j][i] = l_ji
for k in range(i+1, n):
a[j][k] -= l_ji * a[i][k]
return swaps
def ddm_ilu_solve(x, L, U, swaps, b):
"""x <-- solve(L*U*x = swaps(b))"""
m = len(U)
if not m:
return
n = len(U[0])
m2 = len(b)
if not m2:
raise DMShapeError("Shape mismtch")
o = len(b[0])
if m != m2:
raise DMShapeError("Shape mismtch")
if m < n:
raise NotImplementedError("Underdetermined")
if swaps:
b = [row[:] for row in b]
for i1, i2 in swaps:
b[i1], b[i2] = b[i2], b[i1]
# solve Ly = b
y = [[None] * o for _ in range(m)]
for k in range(o):
for i in range(m):
rhs = b[i][k]
for j in range(i):
rhs -= L[i][j] * y[j][k]
y[i][k] = rhs
if m > n:
for i in range(n, m):
for j in range(o):
if y[i][j]:
raise DMNonInvertibleMatrixError
# Solve Ux = y
for k in range(o):
for i in reversed(range(n)):
if not U[i][i]:
raise DMNonInvertibleMatrixError
rhs = y[i][k]
for j in range(i+1, n):
rhs -= U[i][j] * x[j][k]
x[i][k] = rhs / U[i][i]
def ddm_berk(M, K):
m = len(M)
if not m:
return [[K.one]]
n = len(M[0])
if m != n:
raise DMShapeError("Not square")
if n == 1:
return [[K.one], [-M[0][0]]]
a = M[0][0]
R = [M[0][1:]]
C = [[row[0]] for row in M[1:]]
A = [row[1:] for row in M[1:]]
q = ddm_berk(A, K)
T = [[K.zero] * n for _ in range(n+1)]
for i in range(n):
T[i][i] = K.one
T[i+1][i] = -a
for i in range(2, n+1):
if i == 2:
AnC = C
else:
C = AnC
AnC = [[K.zero] for row in C]
ddm_imatmul(AnC, A, C)
RAnC = [[K.zero]]
ddm_imatmul(RAnC, R, AnC)
for j in range(0, n+1-i):
T[i+j][j] = -RAnC[0][0]
qout = [[K.zero] for _ in range(n+1)]
ddm_imatmul(qout, T, q)
return qout
|
64cc4ef36ba9ae4f650aae029472fea60ebfc0e9a69cba33834b10849ae36db9 | from typing import TypeVar, Protocol
T = TypeVar('T')
class RingElement(Protocol):
def __add__(self: T, other: T, /) -> T: ...
def __sub__(self: T, other: T, /) -> T: ...
def __mul__(self: T, other: T, /) -> T: ...
def __pow__(self: T, other: int, /) -> T: ...
def __neg__(self: T, /) -> T: ...
|
59d6904a2124e7a33b911122f2e04f2fda8e1ce86188b60f1374d05a8b661a6c | """
Module for the DDM class.
The DDM class is an internal representation used by DomainMatrix. The letters
DDM stand for Dense Domain Matrix. A DDM instance represents a matrix using
elements from a polynomial Domain (e.g. ZZ, QQ, ...) in a dense-matrix
representation.
Basic usage:
>>> from sympy import ZZ, QQ
>>> from sympy.polys.matrices.ddm import DDM
>>> A = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ)
>>> A.shape
(2, 2)
>>> A
[[0, 1], [-1, 0]]
>>> type(A)
<class 'sympy.polys.matrices.ddm.DDM'>
>>> A @ A
[[-1, 0], [0, -1]]
The ddm_* functions are designed to operate on DDM as well as on an ordinary
list of lists:
>>> from sympy.polys.matrices.dense import ddm_idet
>>> ddm_idet(A, QQ)
1
>>> ddm_idet([[0, 1], [-1, 0]], QQ)
1
>>> A
[[-1, 0], [0, -1]]
Note that ddm_idet modifies the input matrix in-place. It is recommended to
use the DDM.det method as a friendlier interface to this instead which takes
care of copying the matrix:
>>> B = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ)
>>> B.det()
1
Normally DDM would not be used directly and is just part of the internal
representation of DomainMatrix which adds further functionality including e.g.
unifying domains.
The dense format used by DDM is a list of lists of elements e.g. the 2x2
identity matrix is like [[1, 0], [0, 1]]. The DDM class itself is a subclass
of list and its list items are plain lists. Elements are accessed as e.g.
ddm[i][j] where ddm[i] gives the ith row and ddm[i][j] gets the element in the
jth column of that row. Subclassing list makes e.g. iteration and indexing
very efficient. We do not override __getitem__ because it would lose that
benefit.
The core routines are implemented by the ddm_* functions defined in dense.py.
Those functions are intended to be able to operate on a raw list-of-lists
representation of matrices with most functions operating in-place. The DDM
class takes care of copying etc and also stores a Domain object associated
with its elements. This makes it possible to implement things like A + B with
domain checking and also shape checking so that the list of lists
representation is friendlier.
"""
from itertools import chain
from .exceptions import DMBadInputError, DMShapeError, DMDomainError
from .dense import (
ddm_transpose,
ddm_iadd,
ddm_isub,
ddm_ineg,
ddm_imul,
ddm_irmul,
ddm_imatmul,
ddm_irref,
ddm_idet,
ddm_iinv,
ddm_ilu_split,
ddm_ilu_solve,
ddm_berk,
)
from sympy.polys.domains import QQ
from .lll import ddm_lll
class DDM(list):
"""Dense matrix based on polys domain elements
This is a list subclass and is a wrapper for a list of lists that supports
basic matrix arithmetic +, -, *, **.
"""
fmt = 'dense'
def __init__(self, rowslist, shape, domain):
super().__init__(rowslist)
self.shape = self.rows, self.cols = m, n = shape
self.domain = domain
if not (len(self) == m and all(len(row) == n for row in self)):
raise DMBadInputError("Inconsistent row-list/shape")
def getitem(self, i, j):
return self[i][j]
def setitem(self, i, j, value):
self[i][j] = value
def extract_slice(self, slice1, slice2):
ddm = [row[slice2] for row in self[slice1]]
rows = len(ddm)
cols = len(ddm[0]) if ddm else len(range(self.shape[1])[slice2])
return DDM(ddm, (rows, cols), self.domain)
def extract(self, rows, cols):
ddm = []
for i in rows:
rowi = self[i]
ddm.append([rowi[j] for j in cols])
return DDM(ddm, (len(rows), len(cols)), self.domain)
def to_list(self):
return list(self)
def to_list_flat(self):
flat = []
for row in self:
flat.extend(row)
return flat
def flatiter(self):
return chain.from_iterable(self)
def flat(self):
items = []
for row in self:
items.extend(row)
return items
def to_dok(self):
return {(i, j): e for i, row in enumerate(self) for j, e in enumerate(row)}
def to_ddm(self):
return self
def to_sdm(self):
return SDM.from_list(self, self.shape, self.domain)
def convert_to(self, K):
Kold = self.domain
if K == Kold:
return self.copy()
rows = ([K.convert_from(e, Kold) for e in row] for row in self)
return DDM(rows, self.shape, K)
def __str__(self):
rowsstr = ['[%s]' % ', '.join(map(str, row)) for row in self]
return '[%s]' % ', '.join(rowsstr)
def __repr__(self):
cls = type(self).__name__
rows = list.__repr__(self)
return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain)
def __eq__(self, other):
if not isinstance(other, DDM):
return False
return (super().__eq__(other) and self.domain == other.domain)
def __ne__(self, other):
return not self.__eq__(other)
@classmethod
def zeros(cls, shape, domain):
z = domain.zero
m, n = shape
rowslist = ([z] * n for _ in range(m))
return DDM(rowslist, shape, domain)
@classmethod
def ones(cls, shape, domain):
one = domain.one
m, n = shape
rowlist = ([one] * n for _ in range(m))
return DDM(rowlist, shape, domain)
@classmethod
def eye(cls, size, domain):
one = domain.one
ddm = cls.zeros((size, size), domain)
for i in range(size):
ddm[i][i] = one
return ddm
def copy(self):
copyrows = (row[:] for row in self)
return DDM(copyrows, self.shape, self.domain)
def transpose(self):
rows, cols = self.shape
if rows:
ddmT = ddm_transpose(self)
else:
ddmT = [[]] * cols
return DDM(ddmT, (cols, rows), self.domain)
def __add__(a, b):
if not isinstance(b, DDM):
return NotImplemented
return a.add(b)
def __sub__(a, b):
if not isinstance(b, DDM):
return NotImplemented
return a.sub(b)
def __neg__(a):
return a.neg()
def __mul__(a, b):
if b in a.domain:
return a.mul(b)
else:
return NotImplemented
def __rmul__(a, b):
if b in a.domain:
return a.mul(b)
else:
return NotImplemented
def __matmul__(a, b):
if isinstance(b, DDM):
return a.matmul(b)
else:
return NotImplemented
@classmethod
def _check(cls, a, op, b, ashape, bshape):
if a.domain != b.domain:
msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain)
raise DMDomainError(msg)
if ashape != bshape:
msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape)
raise DMShapeError(msg)
def add(a, b):
"""a + b"""
a._check(a, '+', b, a.shape, b.shape)
c = a.copy()
ddm_iadd(c, b)
return c
def sub(a, b):
"""a - b"""
a._check(a, '-', b, a.shape, b.shape)
c = a.copy()
ddm_isub(c, b)
return c
def neg(a):
"""-a"""
b = a.copy()
ddm_ineg(b)
return b
def mul(a, b):
c = a.copy()
ddm_imul(c, b)
return c
def rmul(a, b):
c = a.copy()
ddm_irmul(c, b)
return c
def matmul(a, b):
"""a @ b (matrix product)"""
m, o = a.shape
o2, n = b.shape
a._check(a, '*', b, o, o2)
c = a.zeros((m, n), a.domain)
ddm_imatmul(c, a, b)
return c
def mul_elementwise(a, b):
assert a.shape == b.shape
assert a.domain == b.domain
c = [[aij * bij for aij, bij in zip(ai, bi)] for ai, bi in zip(a, b)]
return DDM(c, a.shape, a.domain)
def hstack(A, *B):
"""Horizontally stacks :py:class:`~.DDM` matrices.
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices.sdm import DDM
>>> A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DDM([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
>>> A.hstack(B)
[[1, 2, 5, 6], [3, 4, 7, 8]]
>>> C = DDM([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
>>> A.hstack(B, C)
[[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]]
"""
Anew = list(A.copy())
rows, cols = A.shape
domain = A.domain
for Bk in B:
Bkrows, Bkcols = Bk.shape
assert Bkrows == rows
assert Bk.domain == domain
cols += Bkcols
for i, Bki in enumerate(Bk):
Anew[i].extend(Bki)
return DDM(Anew, (rows, cols), A.domain)
def vstack(A, *B):
"""Vertically stacks :py:class:`~.DDM` matrices.
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices.sdm import DDM
>>> A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DDM([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
>>> A.vstack(B)
[[1, 2], [3, 4], [5, 6], [7, 8]]
>>> C = DDM([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
>>> A.vstack(B, C)
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]
"""
Anew = list(A.copy())
rows, cols = A.shape
domain = A.domain
for Bk in B:
Bkrows, Bkcols = Bk.shape
assert Bkcols == cols
assert Bk.domain == domain
rows += Bkrows
Anew.extend(Bk.copy())
return DDM(Anew, (rows, cols), A.domain)
def applyfunc(self, func, domain):
elements = (list(map(func, row)) for row in self)
return DDM(elements, self.shape, domain)
def scc(a):
"""Strongly connected components of a square matrix *a*.
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices.sdm import DDM
>>> A = DDM([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ)
>>> A.scc()
[[0], [1]]
See also
========
sympy.polys.matrices.domainmatrix.DomainMatrix.scc
"""
return a.to_sdm().scc()
def rref(a):
"""Reduced-row echelon form of a and list of pivots"""
b = a.copy()
K = a.domain
partial_pivot = K.is_RealField or K.is_ComplexField
pivots = ddm_irref(b, _partial_pivot=partial_pivot)
return b, pivots
def nullspace(a):
rref, pivots = a.rref()
rows, cols = a.shape
domain = a.domain
basis = []
nonpivots = []
for i in range(cols):
if i in pivots:
continue
nonpivots.append(i)
vec = [domain.one if i == j else domain.zero for j in range(cols)]
for ii, jj in enumerate(pivots):
vec[jj] -= rref[ii][i]
basis.append(vec)
return DDM(basis, (len(basis), cols), domain), nonpivots
def particular(a):
return a.to_sdm().particular().to_ddm()
def det(a):
"""Determinant of a"""
m, n = a.shape
if m != n:
raise DMShapeError("Determinant of non-square matrix")
b = a.copy()
K = b.domain
deta = ddm_idet(b, K)
return deta
def inv(a):
"""Inverse of a"""
m, n = a.shape
if m != n:
raise DMShapeError("Determinant of non-square matrix")
ainv = a.copy()
K = a.domain
ddm_iinv(ainv, a, K)
return ainv
def lu(a):
"""L, U decomposition of a"""
m, n = a.shape
K = a.domain
U = a.copy()
L = a.eye(m, K)
swaps = ddm_ilu_split(L, U, K)
return L, U, swaps
def lu_solve(a, b):
"""x where a*x = b"""
m, n = a.shape
m2, o = b.shape
a._check(a, 'lu_solve', b, m, m2)
L, U, swaps = a.lu()
x = a.zeros((n, o), a.domain)
ddm_ilu_solve(x, L, U, swaps, b)
return x
def charpoly(a):
"""Coefficients of characteristic polynomial of a"""
K = a.domain
m, n = a.shape
if m != n:
raise DMShapeError("Charpoly of non-square matrix")
vec = ddm_berk(a, K)
coeffs = [vec[i][0] for i in range(n+1)]
return coeffs
def is_zero_matrix(self):
"""
Says whether this matrix has all zero entries.
"""
zero = self.domain.zero
return all(Mij == zero for Mij in self.flatiter())
def is_upper(self):
"""
Says whether this matrix is upper-triangular. True can be returned
even if the matrix is not square.
"""
zero = self.domain.zero
return all(Mij == zero for i, Mi in enumerate(self) for Mij in Mi[:i])
def is_lower(self):
"""
Says whether this matrix is lower-triangular. True can be returned
even if the matrix is not square.
"""
zero = self.domain.zero
return all(Mij == zero for i, Mi in enumerate(self) for Mij in Mi[i+1:])
def lll(A, delta=QQ(3, 4)) -> 'DDM':
return ddm_lll(A, delta)
from .sdm import SDM
|
cba704355488379614785f8f71c33801337505d85da9b953357348a4330acca1 | from sympy.polys.domains import ZZ, QQ
from sympy.polys.matrices import DM
from sympy.polys.matrices.domainmatrix import DomainMatrix
from sympy.polys.matrices.exceptions import DMRankError, DMValueError, DMShapeError, DMDomainError
from sympy.polys.matrices.lll import ddm_lll
from sympy.testing.pytest import raises
def test_lll():
normal_test_data = [
(
DM([[1, 0, 0, 0, -20160],
[0, 1, 0, 0, 33768],
[0, 0, 1, 0, 39578],
[0, 0, 0, 1, 47757]], ZZ),
DM([[10, -3, -2, 8, -4],
[3, -9, 8, 1, -11],
[-3, 13, -9, -3, -9],
[-12, -7, -11, 9, -1]], ZZ)
),
(
DM([[20, 52, 3456],
[14, 31, -1],
[34, -442, 0]], ZZ),
DM([[14, 31, -1],
[188, -101, -11],
[236, 13, 3443]], ZZ)
),
(
DM([[34, -1, -86, 12],
[-54, 34, 55, 678],
[23, 3498, 234, 6783],
[87, 49, 665, 11]], ZZ),
DM([[34, -1, -86, 12],
[291, 43, 149, 83],
[-54, 34, 55, 678],
[-189, 3077, -184, -223]], ZZ)
)
]
delta = QQ(5, 6)
for basis_dm, reduced_dm in normal_test_data:
assert ddm_lll(basis_dm.rep, delta=delta) == reduced_dm.rep
assert basis_dm.rep.lll(delta=delta) == reduced_dm.rep
assert basis_dm.rep.to_sdm().lll(delta=delta) == reduced_dm.rep.to_sdm()
assert basis_dm.lll(delta=delta) == reduced_dm
def test_lll_linear_dependent():
linear_dependent_test_data = [
DM([[0, -1, -2, -3],
[1, 0, -1, -2],
[2, 1, 0, -1],
[3, 2, 1, 0]], ZZ),
DM([[1, 0, 0, 1],
[0, 1, 0, 1],
[0, 0, 1, 1],
[1, 2, 3, 6]], ZZ),
DM([[3, -5, 1],
[4, 6, 0],
[10, -4, 2]], ZZ)
]
for not_basis in linear_dependent_test_data:
raises(DMRankError, lambda: ddm_lll(not_basis.rep))
raises(DMRankError, lambda: not_basis.rep.lll())
raises(DMRankError, lambda: not_basis.rep.to_sdm().lll())
raises(DMRankError, lambda: not_basis.lll())
def test_lll_wrong_delta():
dummy_matrix = DomainMatrix.ones((3, 3), ZZ)
for wrong_delta in [QQ(-1, 4), QQ(0, 1), QQ(1, 4), QQ(1, 1), QQ(100, 1)]:
raises(DMValueError, lambda: ddm_lll(dummy_matrix.rep, delta=wrong_delta))
raises(DMValueError, lambda: dummy_matrix.rep.lll(delta=wrong_delta))
raises(DMValueError, lambda: dummy_matrix.rep.to_sdm().lll(delta=wrong_delta))
raises(DMValueError, lambda: dummy_matrix.lll(delta=wrong_delta))
def test_lll_wrong_shape():
wrong_shape_matrix = DomainMatrix.ones((4, 3), ZZ)
raises(DMShapeError, lambda: ddm_lll(wrong_shape_matrix.rep))
raises(DMShapeError, lambda: wrong_shape_matrix.rep.lll())
raises(DMShapeError, lambda: wrong_shape_matrix.rep.to_sdm().lll())
raises(DMShapeError, lambda: wrong_shape_matrix.lll())
def test_lll_wrong_domain():
wrong_domain_matrix = DomainMatrix.ones((3, 3), QQ)
raises(DMDomainError, lambda: ddm_lll(wrong_domain_matrix.rep))
raises(DMDomainError, lambda: wrong_domain_matrix.rep.lll())
raises(DMDomainError, lambda: wrong_domain_matrix.rep.to_sdm().lll())
raises(DMDomainError, lambda: wrong_domain_matrix.lll())
|
60eebbce29ac1153b4eca1b22c95535566bdefde5f6865c9a0515c7762b86b37 | from sympy.core.basic import Basic
from sympy.core.numbers import (I, Rational, pi)
from sympy.core.parameters import evaluate
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.geometry import Line, Point, Point2D, Point3D, Line3D, Plane
from sympy.geometry.entity import rotate, scale, translate, GeometryEntity
from sympy.matrices import Matrix
from sympy.utilities.iterables import subsets, permutations, cartes
from sympy.utilities.misc import Undecidable
from sympy.testing.pytest import raises, warns
def test_point():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
x1 = Symbol('x1', real=True)
x2 = Symbol('x2', real=True)
y1 = Symbol('y1', real=True)
y2 = Symbol('y2', real=True)
half = S.Half
p1 = Point(x1, x2)
p2 = Point(y1, y2)
p3 = Point(0, 0)
p4 = Point(1, 1)
p5 = Point(0, 1)
line = Line(Point(1, 0), slope=1)
assert p1 in p1
assert p1 not in p2
assert p2.y == y2
assert (p3 + p4) == p4
assert (p2 - p1) == Point(y1 - x1, y2 - x2)
assert -p2 == Point(-y1, -y2)
raises(TypeError, lambda: Point(1))
raises(ValueError, lambda: Point([1]))
raises(ValueError, lambda: Point(3, I))
raises(ValueError, lambda: Point(2*I, I))
raises(ValueError, lambda: Point(3 + I, I))
assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
assert Point.midpoint(p3, p4) == Point(half, half)
assert Point.midpoint(p1, p4) == Point(half + half*x1, half + half*x2)
assert Point.midpoint(p2, p2) == p2
assert p2.midpoint(p2) == p2
assert p1.origin == Point(0, 0)
assert Point.distance(p3, p4) == sqrt(2)
assert Point.distance(p1, p1) == 0
assert Point.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2)
raises(TypeError, lambda: Point.distance(p1, 0))
raises(TypeError, lambda: Point.distance(p1, GeometryEntity()))
# distance should be symmetric
assert p1.distance(line) == line.distance(p1)
assert p4.distance(line) == line.distance(p4)
assert Point.taxicab_distance(p4, p3) == 2
assert Point.canberra_distance(p4, p5) == 1
raises(ValueError, lambda: Point.canberra_distance(p3, p3))
p1_1 = Point(x1, x1)
p1_2 = Point(y2, y2)
p1_3 = Point(x1 + 1, x1)
assert Point.is_collinear(p3)
with warns(UserWarning, test_stacklevel=False):
assert Point.is_collinear(p3, Point(p3, dim=4))
assert p3.is_collinear()
assert Point.is_collinear(p3, p4)
assert Point.is_collinear(p3, p4, p1_1, p1_2)
assert Point.is_collinear(p3, p4, p1_1, p1_3) is False
assert Point.is_collinear(p3, p3, p4, p5) is False
raises(TypeError, lambda: Point.is_collinear(line))
raises(TypeError, lambda: p1_1.is_collinear(line))
assert p3.intersection(Point(0, 0)) == [p3]
assert p3.intersection(p4) == []
assert p3.intersection(line) == []
with warns(UserWarning, test_stacklevel=False):
assert Point.intersection(Point(0, 0, 0), Point(0, 0)) == [Point(0, 0, 0)]
x_pos = Symbol('x', positive=True)
p2_1 = Point(x_pos, 0)
p2_2 = Point(0, x_pos)
p2_3 = Point(-x_pos, 0)
p2_4 = Point(0, -x_pos)
p2_5 = Point(x_pos, 5)
assert Point.is_concyclic(p2_1)
assert Point.is_concyclic(p2_1, p2_2)
assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4)
for pts in permutations((p2_1, p2_2, p2_3, p2_5)):
assert Point.is_concyclic(*pts) is False
assert Point.is_concyclic(p4, p4 * 2, p4 * 3) is False
assert Point(0, 0).is_concyclic((1, 1), (2, 2), (2, 1)) is False
assert Point.is_concyclic(Point(0, 0, 0, 0), Point(1, 0, 0, 0), Point(1, 1, 0, 0), Point(1, 1, 1, 0)) is False
assert p1.is_scalar_multiple(p1)
assert p1.is_scalar_multiple(2*p1)
assert not p1.is_scalar_multiple(p2)
assert Point.is_scalar_multiple(Point(1, 1), (-1, -1))
assert Point.is_scalar_multiple(Point(0, 0), (0, -1))
# test when is_scalar_multiple can't be determined
raises(Undecidable, lambda: Point.is_scalar_multiple(Point(sympify("x1%y1"), sympify("x2%y2")), Point(0, 1)))
assert Point(0, 1).orthogonal_direction == Point(1, 0)
assert Point(1, 0).orthogonal_direction == Point(0, 1)
assert p1.is_zero is None
assert p3.is_zero
assert p4.is_zero is False
assert p1.is_nonzero is None
assert p3.is_nonzero is False
assert p4.is_nonzero
assert p4.scale(2, 3) == Point(2, 3)
assert p3.scale(2, 3) == p3
assert p4.rotate(pi, Point(0.5, 0.5)) == p3
assert p1.__radd__(p2) == p1.midpoint(p2).scale(2, 2)
assert (-p3).__rsub__(p4) == p3.midpoint(p4).scale(2, 2)
assert p4 * 5 == Point(5, 5)
assert p4 / 5 == Point(0.2, 0.2)
assert 5 * p4 == Point(5, 5)
raises(ValueError, lambda: Point(0, 0) + 10)
# Point differences should be simplified
assert Point(x*(x - 1), y) - Point(x**2 - x, y + 1) == Point(0, -1)
a, b = S.Half, Rational(1, 3)
assert Point(a, b).evalf(2) == \
Point(a.n(2), b.n(2), evaluate=False)
raises(ValueError, lambda: Point(1, 2) + 1)
# test project
assert Point.project((0, 1), (1, 0)) == Point(0, 0)
assert Point.project((1, 1), (1, 0)) == Point(1, 0)
raises(ValueError, lambda: Point.project(p1, Point(0, 0)))
# test transformations
p = Point(1, 0)
assert p.rotate(pi/2) == Point(0, 1)
assert p.rotate(pi/2, p) == p
p = Point(1, 1)
assert p.scale(2, 3) == Point(2, 3)
assert p.translate(1, 2) == Point(2, 3)
assert p.translate(1) == Point(2, 1)
assert p.translate(y=1) == Point(1, 2)
assert p.translate(*p.args) == Point(2, 2)
# Check invalid input for transform
raises(ValueError, lambda: p3.transform(p3))
raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))
# test __contains__
assert 0 in Point(0, 0, 0, 0)
assert 1 not in Point(0, 0, 0, 0)
# test affine_rank
assert Point.affine_rank() == -1
def test_point3D():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
x1 = Symbol('x1', real=True)
x2 = Symbol('x2', real=True)
x3 = Symbol('x3', real=True)
y1 = Symbol('y1', real=True)
y2 = Symbol('y2', real=True)
y3 = Symbol('y3', real=True)
half = S.Half
p1 = Point3D(x1, x2, x3)
p2 = Point3D(y1, y2, y3)
p3 = Point3D(0, 0, 0)
p4 = Point3D(1, 1, 1)
p5 = Point3D(0, 1, 2)
assert p1 in p1
assert p1 not in p2
assert p2.y == y2
assert (p3 + p4) == p4
assert (p2 - p1) == Point3D(y1 - x1, y2 - x2, y3 - x3)
assert -p2 == Point3D(-y1, -y2, -y3)
assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
assert Point3D.midpoint(p3, p4) == Point3D(half, half, half)
assert Point3D.midpoint(p1, p4) == Point3D(half + half*x1, half + half*x2,
half + half*x3)
assert Point3D.midpoint(p2, p2) == p2
assert p2.midpoint(p2) == p2
assert Point3D.distance(p3, p4) == sqrt(3)
assert Point3D.distance(p1, p1) == 0
assert Point3D.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2 + p2.z**2)
p1_1 = Point3D(x1, x1, x1)
p1_2 = Point3D(y2, y2, y2)
p1_3 = Point3D(x1 + 1, x1, x1)
Point3D.are_collinear(p3)
assert Point3D.are_collinear(p3, p4)
assert Point3D.are_collinear(p3, p4, p1_1, p1_2)
assert Point3D.are_collinear(p3, p4, p1_1, p1_3) is False
assert Point3D.are_collinear(p3, p3, p4, p5) is False
assert p3.intersection(Point3D(0, 0, 0)) == [p3]
assert p3.intersection(p4) == []
assert p4 * 5 == Point3D(5, 5, 5)
assert p4 / 5 == Point3D(0.2, 0.2, 0.2)
assert 5 * p4 == Point3D(5, 5, 5)
raises(ValueError, lambda: Point3D(0, 0, 0) + 10)
# Test coordinate properties
assert p1.coordinates == (x1, x2, x3)
assert p2.coordinates == (y1, y2, y3)
assert p3.coordinates == (0, 0, 0)
assert p4.coordinates == (1, 1, 1)
assert p5.coordinates == (0, 1, 2)
assert p5.x == 0
assert p5.y == 1
assert p5.z == 2
# Point differences should be simplified
assert Point3D(x*(x - 1), y, 2) - Point3D(x**2 - x, y + 1, 1) == \
Point3D(0, -1, 1)
a, b, c = S.Half, Rational(1, 3), Rational(1, 4)
assert Point3D(a, b, c).evalf(2) == \
Point(a.n(2), b.n(2), c.n(2), evaluate=False)
raises(ValueError, lambda: Point3D(1, 2, 3) + 1)
# test transformations
p = Point3D(1, 1, 1)
assert p.scale(2, 3) == Point3D(2, 3, 1)
assert p.translate(1, 2) == Point3D(2, 3, 1)
assert p.translate(1) == Point3D(2, 1, 1)
assert p.translate(z=1) == Point3D(1, 1, 2)
assert p.translate(*p.args) == Point3D(2, 2, 2)
# Test __new__
assert Point3D(0.1, 0.2, evaluate=False, on_morph='ignore').args[0].is_Float
# Test length property returns correctly
assert p.length == 0
assert p1_1.length == 0
assert p1_2.length == 0
# Test are_colinear type error
raises(TypeError, lambda: Point3D.are_collinear(p, x))
# Test are_coplanar
assert Point.are_coplanar()
assert Point.are_coplanar((1, 2, 0), (1, 2, 0), (1, 3, 0))
assert Point.are_coplanar((1, 2, 0), (1, 2, 3))
with warns(UserWarning, test_stacklevel=False):
raises(ValueError, lambda: Point2D.are_coplanar((1, 2), (1, 2, 3)))
assert Point3D.are_coplanar((1, 2, 0), (1, 2, 3))
assert Point.are_coplanar((0, 0, 0), (1, 1, 0), (1, 1, 1), (1, 2, 1)) is False
planar2 = Point3D(1, -1, 1)
planar3 = Point3D(-1, 1, 1)
assert Point3D.are_coplanar(p, planar2, planar3) == True
assert Point3D.are_coplanar(p, planar2, planar3, p3) == False
assert Point.are_coplanar(p, planar2)
planar2 = Point3D(1, 1, 2)
planar3 = Point3D(1, 1, 3)
assert Point3D.are_coplanar(p, planar2, planar3) # line, not plane
plane = Plane((1, 2, 1), (2, 1, 0), (3, 1, 2))
assert Point.are_coplanar(*[plane.projection(((-1)**i, i)) for i in range(4)])
# all 2D points are coplanar
assert Point.are_coplanar(Point(x, y), Point(x, x + y), Point(y, x + 2)) is True
# Test Intersection
assert planar2.intersection(Line3D(p, planar3)) == [Point3D(1, 1, 2)]
# Test Scale
assert planar2.scale(1, 1, 1) == planar2
assert planar2.scale(2, 2, 2, planar3) == Point3D(1, 1, 1)
assert planar2.scale(1, 1, 1, p3) == planar2
# Test Transform
identity = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
assert p.transform(identity) == p
trans = Matrix([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]])
assert p.transform(trans) == Point3D(2, 2, 2)
raises(ValueError, lambda: p.transform(p))
raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))
# Test Equals
assert p.equals(x1) == False
# Test __sub__
p_4d = Point(0, 0, 0, 1)
with warns(UserWarning, test_stacklevel=False):
assert p - p_4d == Point(1, 1, 1, -1)
p_4d3d = Point(0, 0, 1, 0)
with warns(UserWarning, test_stacklevel=False):
assert p - p_4d3d == Point(1, 1, 0, 0)
def test_Point2D():
# Test Distance
p1 = Point2D(1, 5)
p2 = Point2D(4, 2.5)
p3 = (6, 3)
assert p1.distance(p2) == sqrt(61)/2
assert p2.distance(p3) == sqrt(17)/2
# Test coordinates
assert p1.x == 1
assert p1.y == 5
assert p2.x == 4
assert p2.y == S(5)/2
assert p1.coordinates == (1, 5)
assert p2.coordinates == (4, S(5)/2)
# test bounds
assert p1.bounds == (1, 5, 1, 5)
def test_issue_9214():
p1 = Point3D(4, -2, 6)
p2 = Point3D(1, 2, 3)
p3 = Point3D(7, 2, 3)
assert Point3D.are_collinear(p1, p2, p3) is False
def test_issue_11617():
p1 = Point3D(1,0,2)
p2 = Point2D(2,0)
with warns(UserWarning, test_stacklevel=False):
assert p1.distance(p2) == sqrt(5)
def test_transform():
p = Point(1, 1)
assert p.transform(rotate(pi/2)) == Point(-1, 1)
assert p.transform(scale(3, 2)) == Point(3, 2)
assert p.transform(translate(1, 2)) == Point(2, 3)
assert Point(1, 1).scale(2, 3, (4, 5)) == \
Point(-2, -7)
assert Point(1, 1).translate(4, 5) == \
Point(5, 6)
def test_concyclic_doctest_bug():
p1, p2 = Point(-1, 0), Point(1, 0)
p3, p4 = Point(0, 1), Point(-1, 2)
assert Point.is_concyclic(p1, p2, p3)
assert not Point.is_concyclic(p1, p2, p3, p4)
def test_arguments():
"""Functions accepting `Point` objects in `geometry`
should also accept tuples and lists and
automatically convert them to points."""
singles2d = ((1,2), [1,2], Point(1,2))
singles2d2 = ((1,3), [1,3], Point(1,3))
doubles2d = cartes(singles2d, singles2d2)
p2d = Point2D(1,2)
singles3d = ((1,2,3), [1,2,3], Point(1,2,3))
doubles3d = subsets(singles3d, 2)
p3d = Point3D(1,2,3)
singles4d = ((1,2,3,4), [1,2,3,4], Point(1,2,3,4))
doubles4d = subsets(singles4d, 2)
p4d = Point(1,2,3,4)
# test 2D
test_single = ['distance', 'is_scalar_multiple', 'taxicab_distance', 'midpoint', 'intersection', 'dot', 'equals', '__add__', '__sub__']
test_double = ['is_concyclic', 'is_collinear']
for p in singles2d:
Point2D(p)
for func in test_single:
for p in singles2d:
getattr(p2d, func)(p)
for func in test_double:
for p in doubles2d:
getattr(p2d, func)(*p)
# test 3D
test_double = ['is_collinear']
for p in singles3d:
Point3D(p)
for func in test_single:
for p in singles3d:
getattr(p3d, func)(p)
for func in test_double:
for p in doubles3d:
getattr(p3d, func)(*p)
# test 4D
test_double = ['is_collinear']
for p in singles4d:
Point(p)
for func in test_single:
for p in singles4d:
getattr(p4d, func)(p)
for func in test_double:
for p in doubles4d:
getattr(p4d, func)(*p)
# test evaluate=False for ops
x = Symbol('x')
a = Point(0, 1)
assert a + (0.1, x) == Point(0.1, 1 + x, evaluate=False)
a = Point(0, 1)
assert a/10.0 == Point(0, 0.1, evaluate=False)
a = Point(0, 1)
assert a*10.0 == Point(0.0, 10.0, evaluate=False)
# test evaluate=False when changing dimensions
u = Point(.1, .2, evaluate=False)
u4 = Point(u, dim=4, on_morph='ignore')
assert u4.args == (.1, .2, 0, 0)
assert all(i.is_Float for i in u4.args[:2])
# and even when *not* changing dimensions
assert all(i.is_Float for i in Point(u).args)
# never raise error if creating an origin
assert Point(dim=3, on_morph='error')
# raise error with unmatched dimension
raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='error'))
# test unknown on_morph
raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='unknown'))
# test invalid expressions
raises(TypeError, lambda: Point(Basic(), Basic()))
def test_unit():
assert Point(1, 1).unit == Point(sqrt(2)/2, sqrt(2)/2)
def test_dot():
raises(TypeError, lambda: Point(1, 2).dot(Line((0, 0), (1, 1))))
def test__normalize_dimension():
assert Point._normalize_dimension(Point(1, 2), Point(3, 4)) == [
Point(1, 2), Point(3, 4)]
assert Point._normalize_dimension(
Point(1, 2), Point(3, 4, 0), on_morph='ignore') == [
Point(1, 2, 0), Point(3, 4, 0)]
def test_issue_22684():
# Used to give an error
with evaluate(False):
Point(1, 2)
def test_direction_cosine():
p1 = Point3D(0, 0, 0)
p2 = Point3D(1, 1, 1)
assert p1.direction_cosine(Point3D(1, 0, 0)) == [1, 0, 0]
assert p1.direction_cosine(Point3D(0, 1, 0)) == [0, 1, 0]
assert p1.direction_cosine(Point3D(0, 0, pi)) == [0, 0, 1]
assert p1.direction_cosine(Point3D(5, 0, 0)) == [1, 0, 0]
assert p1.direction_cosine(Point3D(0, sqrt(3), 0)) == [0, 1, 0]
assert p1.direction_cosine(Point3D(0, 0, 5)) == [0, 0, 1]
assert p1.direction_cosine(Point3D(2.4, 2.4, 0)) == [sqrt(2)/2, sqrt(2)/2, 0]
assert p1.direction_cosine(Point3D(1, 1, 1)) == [sqrt(3) / 3, sqrt(3) / 3, sqrt(3) / 3]
assert p1.direction_cosine(Point3D(-12, 0 -15)) == [-4*sqrt(41)/41, -5*sqrt(41)/41, 0]
assert p2.direction_cosine(Point3D(0, 0, 0)) == [-sqrt(3) / 3, -sqrt(3) / 3, -sqrt(3) / 3]
assert p2.direction_cosine(Point3D(1, 1, 12)) == [0, 0, 1]
assert p2.direction_cosine(Point3D(12, 1, 12)) == [sqrt(2) / 2, 0, sqrt(2) / 2]
|
3bb6205716b6d494e19d23d1e2486e2d71aae3bc44f2e858c9d0fe2c6d692344 | # -*- coding: utf-8 -*-
import sys
import builtins
import types
from sympy.assumptions import Q
from sympy.core import Symbol, Function, Float, Rational, Integer, I, Mul, Pow, Eq
from sympy.functions import exp, factorial, factorial2, sin, Min, Max
from sympy.logic import And
from sympy.series import Limit
from sympy.testing.pytest import raises, skip
from sympy.parsing.sympy_parser import (
parse_expr, standard_transformations, rationalize, TokenError,
split_symbols, implicit_multiplication, convert_equals_signs,
convert_xor, function_exponentiation, lambda_notation, auto_symbol,
repeated_decimals, implicit_multiplication_application,
auto_number, factorial_notation, implicit_application,
_transformation, T
)
def test_sympy_parser():
x = Symbol('x')
inputs = {
'2*x': 2 * x,
'3.00': Float(3),
'22/7': Rational(22, 7),
'2+3j': 2 + 3*I,
'exp(x)': exp(x),
'x!': factorial(x),
'x!!': factorial2(x),
'(x + 1)! - 1': factorial(x + 1) - 1,
'3.[3]': Rational(10, 3),
'.0[3]': Rational(1, 30),
'3.2[3]': Rational(97, 30),
'1.3[12]': Rational(433, 330),
'1 + 3.[3]': Rational(13, 3),
'1 + .0[3]': Rational(31, 30),
'1 + 3.2[3]': Rational(127, 30),
'.[0011]': Rational(1, 909),
'0.1[00102] + 1': Rational(366697, 333330),
'1.[0191]': Rational(10190, 9999),
'10!': 3628800,
'-(2)': -Integer(2),
'[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)],
'Symbol("x").free_symbols': x.free_symbols,
"S('S(3).n(n=3)')": Float(3, 3),
'factorint(12, visual=True)': Mul(
Pow(2, 2, evaluate=False),
Pow(3, 1, evaluate=False),
evaluate=False),
'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'),
'Q.even(x)': Q.even(x),
}
for text, result in inputs.items():
assert parse_expr(text) == result
raises(TypeError, lambda:
parse_expr('x', standard_transformations))
raises(TypeError, lambda:
parse_expr('x', transformations=lambda x,y: 1))
raises(TypeError, lambda:
parse_expr('x', transformations=(lambda x,y: 1,)))
raises(TypeError, lambda: parse_expr('x', transformations=((),)))
raises(TypeError, lambda: parse_expr('x', {}, [], []))
raises(TypeError, lambda: parse_expr('x', [], [], {}))
raises(TypeError, lambda: parse_expr('x', [], [], {}))
def test_rationalize():
inputs = {
'0.123': Rational(123, 1000)
}
transformations = standard_transformations + (rationalize,)
for text, result in inputs.items():
assert parse_expr(text, transformations=transformations) == result
def test_factorial_fail():
inputs = ['x!!!', 'x!!!!', '(!)']
for text in inputs:
try:
parse_expr(text)
assert False
except TokenError:
assert True
def test_repeated_fail():
inputs = ['1[1]', '.1e1[1]', '0x1[1]', '1.1j[1]', '1.1[1 + 1]',
'0.1[[1]]', '0x1.1[1]']
# All are valid Python, so only raise TypeError for invalid indexing
for text in inputs:
raises(TypeError, lambda: parse_expr(text))
inputs = ['0.1[', '0.1[1', '0.1[]']
for text in inputs:
raises((TokenError, SyntaxError), lambda: parse_expr(text))
def test_repeated_dot_only():
assert parse_expr('.[1]') == Rational(1, 9)
assert parse_expr('1 + .[1]') == Rational(10, 9)
def test_local_dict():
local_dict = {
'my_function': lambda x: x + 2
}
inputs = {
'my_function(2)': Integer(4)
}
for text, result in inputs.items():
assert parse_expr(text, local_dict=local_dict) == result
def test_local_dict_split_implmult():
t = standard_transformations + (split_symbols, implicit_multiplication,)
w = Symbol('w', real=True)
y = Symbol('y')
assert parse_expr('yx', local_dict={'x':w}, transformations=t) == y*w
def test_local_dict_symbol_to_fcn():
x = Symbol('x')
d = {'foo': Function('bar')}
assert parse_expr('foo(x)', local_dict=d) == d['foo'](x)
d = {'foo': Symbol('baz')}
raises(TypeError, lambda: parse_expr('foo(x)', local_dict=d))
def test_global_dict():
global_dict = {
'Symbol': Symbol
}
inputs = {
'Q & S': And(Symbol('Q'), Symbol('S'))
}
for text, result in inputs.items():
assert parse_expr(text, global_dict=global_dict) == result
def test_no_globals():
# Replicate creating the default global_dict:
default_globals = {}
exec('from sympy import *', default_globals)
builtins_dict = vars(builtins)
for name, obj in builtins_dict.items():
if isinstance(obj, types.BuiltinFunctionType):
default_globals[name] = obj
default_globals['max'] = Max
default_globals['min'] = Min
# Need to include Symbol or parse_expr will not work:
default_globals.pop('Symbol')
global_dict = {'Symbol':Symbol}
for name in default_globals:
obj = parse_expr(name, global_dict=global_dict)
assert obj == Symbol(name)
def test_issue_2515():
raises(TokenError, lambda: parse_expr('(()'))
raises(TokenError, lambda: parse_expr('"""'))
def test_issue_7663():
x = Symbol('x')
e = '2*(x+1)'
assert parse_expr(e, evaluate=0) == parse_expr(e, evaluate=False)
assert parse_expr(e, evaluate=0).equals(2*(x+1))
def test_recursive_evaluate_false_10560():
inputs = {
'4*-3' : '4*-3',
'-4*3' : '(-4)*3',
"-2*x*y": '(-2)*x*y',
"x*-4*x": "x*(-4)*x"
}
for text, result in inputs.items():
assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
def test_function_evaluate_false():
inputs = [
'Abs(0)', 'im(0)', 're(0)', 'sign(0)', 'arg(0)', 'conjugate(0)',
'acos(0)', 'acot(0)', 'acsc(0)', 'asec(0)', 'asin(0)', 'atan(0)',
'acosh(0)', 'acoth(0)', 'acsch(0)', 'asech(0)', 'asinh(0)', 'atanh(0)',
'cos(0)', 'cot(0)', 'csc(0)', 'sec(0)', 'sin(0)', 'tan(0)',
'cosh(0)', 'coth(0)', 'csch(0)', 'sech(0)', 'sinh(0)', 'tanh(0)',
'exp(0)', 'log(0)', 'sqrt(0)',
]
for case in inputs:
expr = parse_expr(case, evaluate=False)
assert case == str(expr) != str(expr.doit())
assert str(parse_expr('ln(0)', evaluate=False)) == 'log(0)'
assert str(parse_expr('cbrt(0)', evaluate=False)) == '0**(1/3)'
def test_issue_10773():
inputs = {
'-10/5': '(-10)/5',
'-10/-5' : '(-10)/(-5)',
}
for text, result in inputs.items():
assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
def test_split_symbols():
transformations = standard_transformations + \
(split_symbols, implicit_multiplication,)
x = Symbol('x')
y = Symbol('y')
xy = Symbol('xy')
assert parse_expr("xy") == xy
assert parse_expr("xy", transformations=transformations) == x*y
def test_split_symbols_function():
transformations = standard_transformations + \
(split_symbols, implicit_multiplication,)
x = Symbol('x')
y = Symbol('y')
a = Symbol('a')
f = Function('f')
assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x+1)
assert parse_expr("af(x+1)", transformations=transformations,
local_dict={'f':f}) == a*f(x+1)
def test_functional_exponent():
t = standard_transformations + (convert_xor, function_exponentiation)
x = Symbol('x')
y = Symbol('y')
a = Symbol('a')
yfcn = Function('y')
assert parse_expr("sin^2(x)", transformations=t) == (sin(x))**2
assert parse_expr("sin^y(x)", transformations=t) == (sin(x))**y
assert parse_expr("exp^y(x)", transformations=t) == (exp(x))**y
assert parse_expr("E^y(x)", transformations=t) == exp(yfcn(x))
assert parse_expr("a^y(x)", transformations=t) == a**(yfcn(x))
def test_match_parentheses_implicit_multiplication():
transformations = standard_transformations + \
(implicit_multiplication,)
raises(TokenError, lambda: parse_expr('(1,2),(3,4]',transformations=transformations))
def test_convert_equals_signs():
transformations = standard_transformations + \
(convert_equals_signs, )
x = Symbol('x')
y = Symbol('y')
assert parse_expr("1*2=x", transformations=transformations) == Eq(2, x)
assert parse_expr("y = x", transformations=transformations) == Eq(y, x)
assert parse_expr("(2*y = x) = False",
transformations=transformations) == Eq(Eq(2*y, x), False)
def test_parse_function_issue_3539():
x = Symbol('x')
f = Function('f')
assert parse_expr('f(x)') == f(x)
def test_split_symbols_numeric():
transformations = (
standard_transformations +
(implicit_multiplication_application,))
n = Symbol('n')
expr1 = parse_expr('2**n * 3**n')
expr2 = parse_expr('2**n3**n', transformations=transformations)
assert expr1 == expr2 == 2**n*3**n
expr1 = parse_expr('n12n34', transformations=transformations)
assert expr1 == n*12*n*34
def test_unicode_names():
assert parse_expr('α') == Symbol('α')
def test_python3_features():
# Make sure the tokenizer can handle Python 3-only features
if sys.version_info < (3, 8):
skip("test_python3_features requires Python 3.8 or newer")
assert parse_expr("123_456") == 123456
assert parse_expr("1.2[3_4]") == parse_expr("1.2[34]") == Rational(611, 495)
assert parse_expr("1.2[012_012]") == parse_expr("1.2[012012]") == Rational(400, 333)
assert parse_expr('.[3_4]') == parse_expr('.[34]') == Rational(34, 99)
assert parse_expr('.1[3_4]') == parse_expr('.1[34]') == Rational(133, 990)
assert parse_expr('123_123.123_123[3_4]') == parse_expr('123123.123123[34]') == Rational(12189189189211, 99000000)
def test_issue_19501():
x = Symbol('x')
eq = parse_expr('E**x(1+x)', local_dict={'x': x}, transformations=(
standard_transformations +
(implicit_multiplication_application,)))
assert eq.free_symbols == {x}
def test_parsing_definitions():
from sympy.abc import x
assert len(_transformation) == 12 # if this changes, extend below
assert _transformation[0] == lambda_notation
assert _transformation[1] == auto_symbol
assert _transformation[2] == repeated_decimals
assert _transformation[3] == auto_number
assert _transformation[4] == factorial_notation
assert _transformation[5] == implicit_multiplication_application
assert _transformation[6] == convert_xor
assert _transformation[7] == implicit_application
assert _transformation[8] == implicit_multiplication
assert _transformation[9] == convert_equals_signs
assert _transformation[10] == function_exponentiation
assert _transformation[11] == rationalize
assert T[:5] == T[0,1,2,3,4] == standard_transformations
t = _transformation
assert T[-1, 0] == (t[len(t) - 1], t[0])
assert T[:5, 8] == standard_transformations + (t[8],)
assert parse_expr('0.3x^2', transformations='all') == 3*x**2/10
assert parse_expr('sin 3x', transformations='implicit') == sin(3*x)
def test_builtins():
cases = [
('abs(x)', 'Abs(x)'),
('max(x, y)', 'Max(x, y)'),
('min(x, y)', 'Min(x, y)'),
('pow(x, y)', 'Pow(x, y)'),
]
for built_in_func_call, sympy_func_call in cases:
assert parse_expr(built_in_func_call) == parse_expr(sympy_func_call)
assert str(parse_expr('pow(38, -1, 97)')) == '23'
def test_issue_22822():
raises(ValueError, lambda: parse_expr('x', {'': 1}))
data = {'some_parameter': None}
assert parse_expr('some_parameter is None', data) is True
|
d69c6552ae033cf811745a0b3fca4160222d2363dc4bef8a78cf033a8d38295f | from .lti import (TransferFunction, Series, MIMOSeries, Parallel, MIMOParallel,
Feedback, MIMOFeedback, TransferFunctionMatrix, bilinear)
from .control_plots import (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
step_response_plot, impulse_response_numerical_data, impulse_response_plot, ramp_response_numerical_data,
ramp_response_plot, bode_magnitude_numerical_data, bode_phase_numerical_data, bode_magnitude_plot,
bode_phase_plot, bode_plot)
__all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel',
'MIMOParallel', 'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix','bilinear',
'pole_zero_numerical_data',
'pole_zero_plot', 'step_response_numerical_data', 'step_response_plot',
'impulse_response_numerical_data', 'impulse_response_plot',
'ramp_response_numerical_data', 'ramp_response_plot',
'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot']
|
7da95f61b2f178d557c1dda499b5f30d3daa3eae8c9ad0aa3d61f5a4523cc4ad | from typing import Type
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.evalf import EvalfMixin
from sympy.core.expr import Expr
from sympy.core.function import expand
from sympy.core.logic import fuzzy_and
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import Dummy, Symbol
from sympy.core.sympify import sympify, _sympify
from sympy.matrices import ImmutableMatrix, eye
from sympy.matrices.expressions import MatMul, MatAdd
from sympy.polys import Poly, rootof
from sympy.polys.polyroots import roots
from sympy.polys.polytools import (cancel, degree)
from sympy.series import limit
from mpmath.libmp.libmpf import prec_to_dps
__all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel', 'MIMOParallel',
'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix', 'bilinear']
def _roots(poly, var):
""" like roots, but works on higher-order polynomials. """
r = roots(poly, var, multiple=True)
n = degree(poly)
if len(r) != n:
r = [rootof(poly, var, k) for k in range(n)]
return r
def bilinear(tf, sample_per):
"""
Returns falling coeffs of H(z) from numerator and denominator.
H(z) is the corresponding discretized transfer function,
discretized with the bilinear transform method.
H(z) is obtained from the continuous transfer function H(s)
by substituting s(z) = 2/T * (z-1)/(z+1) into H(s), where T is the
sample period.
Coefficients are falling, i.e. H(z) = (az+b)/(cz+d) is returned
as [a, b], [c, d].
Examples
========
>>> from sympy.physics.control.lti import TransferFunction, bilinear
>>> from sympy.abc import s, L, R, T
>>> tf = TransferFunction(1, s*L + R, s)
>>> numZ, denZ = bilinear(tf, T)
>>> numZ
[T, T]
>>> denZ
[2*L + R*T, -2*L + R*T]
"""
z = Symbol('z') # discrete variable z
T = sample_per # and sample period T
s = tf.var
np = tf.num.as_poly(s).all_coeffs()
dp = tf.den.as_poly(s).all_coeffs()
# The next line results from multiplying H(z) with (z+1)^N/(z+1)^N
N = max(len(np), len(dp)) - 1
num = Add(*[ T**(N-i)*2**i*c*(z-1)**i*(z+1)**(N-i) for c, i in zip(np[::-1], range(len(np))) ])
den = Add(*[ T**(N-i)*2**i*c*(z-1)**i*(z+1)**(N-i) for c, i in zip(dp[::-1], range(len(dp))) ])
num_coefs = num.as_poly(z).all_coeffs()
den_coefs = den.as_poly(z).all_coeffs()
return num_coefs, den_coefs
class LinearTimeInvariant(Basic, EvalfMixin):
"""A common class for all the Linear Time-Invariant Dynamical Systems."""
_clstype: Type
# Users should not directly interact with this class.
def __new__(cls, *system, **kwargs):
if cls is LinearTimeInvariant:
raise NotImplementedError('The LTICommon class is not meant to be used directly.')
return super(LinearTimeInvariant, cls).__new__(cls, *system, **kwargs)
@classmethod
def _check_args(cls, args):
if not args:
raise ValueError("Atleast 1 argument must be passed.")
if not all(isinstance(arg, cls._clstype) for arg in args):
raise TypeError(f"All arguments must be of type {cls._clstype}.")
var_set = {arg.var for arg in args}
if len(var_set) != 1:
raise ValueError("All transfer functions should use the same complex variable"
f" of the Laplace transform. {len(var_set)} different values found.")
@property
def is_SISO(self):
"""Returns `True` if the passed LTI system is SISO else returns False."""
return self._is_SISO
class SISOLinearTimeInvariant(LinearTimeInvariant):
"""A common class for all the SISO Linear Time-Invariant Dynamical Systems."""
# Users should not directly interact with this class.
_is_SISO = True
class MIMOLinearTimeInvariant(LinearTimeInvariant):
"""A common class for all the MIMO Linear Time-Invariant Dynamical Systems."""
# Users should not directly interact with this class.
_is_SISO = False
SISOLinearTimeInvariant._clstype = SISOLinearTimeInvariant
MIMOLinearTimeInvariant._clstype = MIMOLinearTimeInvariant
def _check_other_SISO(func):
def wrapper(*args, **kwargs):
if not isinstance(args[-1], SISOLinearTimeInvariant):
return NotImplemented
else:
return func(*args, **kwargs)
return wrapper
def _check_other_MIMO(func):
def wrapper(*args, **kwargs):
if not isinstance(args[-1], MIMOLinearTimeInvariant):
return NotImplemented
else:
return func(*args, **kwargs)
return wrapper
class TransferFunction(SISOLinearTimeInvariant):
r"""
A class for representing LTI (Linear, time-invariant) systems that can be strictly described
by ratio of polynomials in the Laplace transform complex variable. The arguments
are ``num``, ``den``, and ``var``, where ``num`` and ``den`` are numerator and
denominator polynomials of the ``TransferFunction`` respectively, and the third argument is
a complex variable of the Laplace transform used by these polynomials of the transfer function.
``num`` and ``den`` can be either polynomials or numbers, whereas ``var``
has to be a :py:class:`~.Symbol`.
Explanation
===========
Generally, a dynamical system representing a physical model can be described in terms of Linear
Ordinary Differential Equations like -
$\small{b_{m}y^{\left(m\right)}+b_{m-1}y^{\left(m-1\right)}+\dots+b_{1}y^{\left(1\right)}+b_{0}y=
a_{n}x^{\left(n\right)}+a_{n-1}x^{\left(n-1\right)}+\dots+a_{1}x^{\left(1\right)}+a_{0}x}$
Here, $x$ is the input signal and $y$ is the output signal and superscript on both is the order of derivative
(not exponent). Derivative is taken with respect to the independent variable, $t$. Also, generally $m$ is greater
than $n$.
It is not feasible to analyse the properties of such systems in their native form therefore, we use
mathematical tools like Laplace transform to get a better perspective. Taking the Laplace transform
of both the sides in the equation (at zero initial conditions), we get -
$\small{\mathcal{L}[b_{m}y^{\left(m\right)}+b_{m-1}y^{\left(m-1\right)}+\dots+b_{1}y^{\left(1\right)}+b_{0}y]=
\mathcal{L}[a_{n}x^{\left(n\right)}+a_{n-1}x^{\left(n-1\right)}+\dots+a_{1}x^{\left(1\right)}+a_{0}x]}$
Using the linearity property of Laplace transform and also considering zero initial conditions
(i.e. $\small{y(0^{-}) = 0}$, $\small{y'(0^{-}) = 0}$ and so on), the equation
above gets translated to -
$\small{b_{m}\mathcal{L}[y^{\left(m\right)}]+\dots+b_{1}\mathcal{L}[y^{\left(1\right)}]+b_{0}\mathcal{L}[y]=
a_{n}\mathcal{L}[x^{\left(n\right)}]+\dots+a_{1}\mathcal{L}[x^{\left(1\right)}]+a_{0}\mathcal{L}[x]}$
Now, applying Derivative property of Laplace transform,
$\small{b_{m}s^{m}\mathcal{L}[y]+\dots+b_{1}s\mathcal{L}[y]+b_{0}\mathcal{L}[y]=
a_{n}s^{n}\mathcal{L}[x]+\dots+a_{1}s\mathcal{L}[x]+a_{0}\mathcal{L}[x]}$
Here, the superscript on $s$ is **exponent**. Note that the zero initial conditions assumption, mentioned above, is very important
and cannot be ignored otherwise the dynamical system cannot be considered time-independent and the simplified equation above
cannot be reached.
Collecting $\mathcal{L}[y]$ and $\mathcal{L}[x]$ terms from both the sides and taking the ratio
$\frac{ \mathcal{L}\left\{y\right\} }{ \mathcal{L}\left\{x\right\} }$, we get the typical rational form of transfer
function.
The numerator of the transfer function is, therefore, the Laplace transform of the output signal
(The signals are represented as functions of time) and similarly, the denominator
of the transfer function is the Laplace transform of the input signal. It is also a convention
to denote the input and output signal's Laplace transform with capital alphabets like shown below.
$H(s) = \frac{Y(s)}{X(s)} = \frac{ \mathcal{L}\left\{y(t)\right\} }{ \mathcal{L}\left\{x(t)\right\} }$
$s$, also known as complex frequency, is a complex variable in the Laplace domain. It corresponds to the
equivalent variable $t$, in the time domain. Transfer functions are sometimes also referred to as the Laplace
transform of the system's impulse response. Transfer function, $H$, is represented as a rational
function in $s$ like,
$H(s) =\ \frac{a_{n}s^{n}+a_{n-1}s^{n-1}+\dots+a_{1}s+a_{0}}{b_{m}s^{m}+b_{m-1}s^{m-1}+\dots+b_{1}s+b_{0}}$
Parameters
==========
num : Expr, Number
The numerator polynomial of the transfer function.
den : Expr, Number
The denominator polynomial of the transfer function.
var : Symbol
Complex variable of the Laplace transform used by the
polynomials of the transfer function.
Raises
======
TypeError
When ``var`` is not a Symbol or when ``num`` or ``den`` is not a
number or a polynomial.
ValueError
When ``den`` is zero.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(s + a, s**2 + s + 1, s)
>>> tf1
TransferFunction(a + s, s**2 + s + 1, s)
>>> tf1.num
a + s
>>> tf1.den
s**2 + s + 1
>>> tf1.var
s
>>> tf1.args
(a + s, s**2 + s + 1, s)
Any complex variable can be used for ``var``.
>>> tf2 = TransferFunction(a*p**3 - a*p**2 + s*p, p + a**2, p)
>>> tf2
TransferFunction(a*p**3 - a*p**2 + p*s, a**2 + p, p)
>>> tf3 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
>>> tf3
TransferFunction((p - 1)*(p + 3), (p - 1)*(p + 5), p)
To negate a transfer function the ``-`` operator can be prepended:
>>> tf4 = TransferFunction(-a + s, p**2 + s, p)
>>> -tf4
TransferFunction(a - s, p**2 + s, p)
>>> tf5 = TransferFunction(s**4 - 2*s**3 + 5*s + 4, s + 4, s)
>>> -tf5
TransferFunction(-s**4 + 2*s**3 - 5*s - 4, s + 4, s)
You can use a float or an integer (or other constants) as numerator and denominator:
>>> tf6 = TransferFunction(1/2, 4, s)
>>> tf6.num
0.500000000000000
>>> tf6.den
4
>>> tf6.var
s
>>> tf6.args
(0.5, 4, s)
You can take the integer power of a transfer function using the ``**`` operator:
>>> tf7 = TransferFunction(s + a, s - a, s)
>>> tf7**3
TransferFunction((a + s)**3, (-a + s)**3, s)
>>> tf7**0
TransferFunction(1, 1, s)
>>> tf8 = TransferFunction(p + 4, p - 3, p)
>>> tf8**-1
TransferFunction(p - 3, p + 4, p)
Addition, subtraction, and multiplication of transfer functions can form
unevaluated ``Series`` or ``Parallel`` objects.
>>> tf9 = TransferFunction(s + 1, s**2 + s + 1, s)
>>> tf10 = TransferFunction(s - p, s + 3, s)
>>> tf11 = TransferFunction(4*s**2 + 2*s - 4, s - 1, s)
>>> tf12 = TransferFunction(1 - s, s**2 + 4, s)
>>> tf9 + tf10
Parallel(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-p + s, s + 3, s))
>>> tf10 - tf11
Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(-4*s**2 - 2*s + 4, s - 1, s))
>>> tf9 * tf10
Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-p + s, s + 3, s))
>>> tf10 - (tf9 + tf12)
Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(-s - 1, s**2 + s + 1, s), TransferFunction(s - 1, s**2 + 4, s))
>>> tf10 - (tf9 * tf12)
Parallel(TransferFunction(-p + s, s + 3, s), Series(TransferFunction(-1, 1, s), TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(1 - s, s**2 + 4, s)))
>>> tf11 * tf10 * tf9
Series(TransferFunction(4*s**2 + 2*s - 4, s - 1, s), TransferFunction(-p + s, s + 3, s), TransferFunction(s + 1, s**2 + s + 1, s))
>>> tf9 * tf11 + tf10 * tf12
Parallel(Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(4*s**2 + 2*s - 4, s - 1, s)), Series(TransferFunction(-p + s, s + 3, s), TransferFunction(1 - s, s**2 + 4, s)))
>>> (tf9 + tf12) * (tf10 + tf11)
Series(Parallel(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(1 - s, s**2 + 4, s)), Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(4*s**2 + 2*s - 4, s - 1, s)))
These unevaluated ``Series`` or ``Parallel`` objects can convert into the
resultant transfer function using ``.doit()`` method or by ``.rewrite(TransferFunction)``.
>>> ((tf9 + tf10) * tf12).doit()
TransferFunction((1 - s)*((-p + s)*(s**2 + s + 1) + (s + 1)*(s + 3)), (s + 3)*(s**2 + 4)*(s**2 + s + 1), s)
>>> (tf9 * tf10 - tf11 * tf12).rewrite(TransferFunction)
TransferFunction(-(1 - s)*(s + 3)*(s**2 + s + 1)*(4*s**2 + 2*s - 4) + (-p + s)*(s - 1)*(s + 1)*(s**2 + 4), (s - 1)*(s + 3)*(s**2 + 4)*(s**2 + s + 1), s)
See Also
========
Feedback, Series, Parallel
References
==========
.. [1] https://en.wikipedia.org/wiki/Transfer_function
.. [2] https://en.wikipedia.org/wiki/Laplace_transform
"""
def __new__(cls, num, den, var):
num, den = _sympify(num), _sympify(den)
if not isinstance(var, Symbol):
raise TypeError("Variable input must be a Symbol.")
if den == 0:
raise ValueError("TransferFunction cannot have a zero denominator.")
if (((isinstance(num, Expr) and num.has(Symbol)) or num.is_number) and
((isinstance(den, Expr) and den.has(Symbol)) or den.is_number)):
obj = super(TransferFunction, cls).__new__(cls, num, den, var)
obj._num = num
obj._den = den
obj._var = var
return obj
else:
raise TypeError("Unsupported type for numerator or denominator of TransferFunction.")
@classmethod
def from_rational_expression(cls, expr, var=None):
r"""
Creates a new ``TransferFunction`` efficiently from a rational expression.
Parameters
==========
expr : Expr, Number
The rational expression representing the ``TransferFunction``.
var : Symbol, optional
Complex variable of the Laplace transform used by the
polynomials of the transfer function.
Raises
======
ValueError
When ``expr`` is of type ``Number`` and optional parameter ``var``
is not passed.
When ``expr`` has more than one variables and an optional parameter
``var`` is not passed.
ZeroDivisionError
When denominator of ``expr`` is zero or it has ``ComplexInfinity``
in its numerator.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> expr1 = (s + 5)/(3*s**2 + 2*s + 1)
>>> tf1 = TransferFunction.from_rational_expression(expr1)
>>> tf1
TransferFunction(s + 5, 3*s**2 + 2*s + 1, s)
>>> expr2 = (a*p**3 - a*p**2 + s*p)/(p + a**2) # Expr with more than one variables
>>> tf2 = TransferFunction.from_rational_expression(expr2, p)
>>> tf2
TransferFunction(a*p**3 - a*p**2 + p*s, a**2 + p, p)
In case of conflict between two or more variables in a expression, SymPy will
raise a ``ValueError``, if ``var`` is not passed by the user.
>>> tf = TransferFunction.from_rational_expression((a + a*s)/(s**2 + s + 1))
Traceback (most recent call last):
...
ValueError: Conflicting values found for positional argument `var` ({a, s}). Specify it manually.
This can be corrected by specifying the ``var`` parameter manually.
>>> tf = TransferFunction.from_rational_expression((a + a*s)/(s**2 + s + 1), s)
>>> tf
TransferFunction(a*s + a, s**2 + s + 1, s)
``var`` also need to be specified when ``expr`` is a ``Number``
>>> tf3 = TransferFunction.from_rational_expression(10, s)
>>> tf3
TransferFunction(10, 1, s)
"""
expr = _sympify(expr)
if var is None:
_free_symbols = expr.free_symbols
_len_free_symbols = len(_free_symbols)
if _len_free_symbols == 1:
var = list(_free_symbols)[0]
elif _len_free_symbols == 0:
raise ValueError("Positional argument `var` not found in the TransferFunction defined. Specify it manually.")
else:
raise ValueError("Conflicting values found for positional argument `var` ({}). Specify it manually.".format(_free_symbols))
_num, _den = expr.as_numer_denom()
if _den == 0 or _num.has(S.ComplexInfinity):
raise ZeroDivisionError("TransferFunction cannot have a zero denominator.")
return cls(_num, _den, var)
@property
def num(self):
"""
Returns the numerator polynomial of the transfer function.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction(s**2 + p*s + 3, s - 4, s)
>>> G1.num
p*s + s**2 + 3
>>> G2 = TransferFunction((p + 5)*(p - 3), (p - 3)*(p + 1), p)
>>> G2.num
(p - 3)*(p + 5)
"""
return self._num
@property
def den(self):
"""
Returns the denominator polynomial of the transfer function.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction(s + 4, p**3 - 2*p + 4, s)
>>> G1.den
p**3 - 2*p + 4
>>> G2 = TransferFunction(3, 4, s)
>>> G2.den
4
"""
return self._den
@property
def var(self):
"""
Returns the complex variable of the Laplace transform used by the polynomials of
the transfer function.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G1.var
p
>>> G2 = TransferFunction(0, s - 5, s)
>>> G2.var
s
"""
return self._var
def _eval_subs(self, old, new):
arg_num = self.num.subs(old, new)
arg_den = self.den.subs(old, new)
argnew = TransferFunction(arg_num, arg_den, self.var)
return self if old == self.var else argnew
def _eval_evalf(self, prec):
return TransferFunction(
self.num._eval_evalf(prec),
self.den._eval_evalf(prec),
self.var)
def _eval_simplify(self, **kwargs):
tf = cancel(Mul(self.num, 1/self.den, evaluate=False), expand=False).as_numer_denom()
num_, den_ = tf[0], tf[1]
return TransferFunction(num_, den_, self.var)
def expand(self):
"""
Returns the transfer function with numerator and denominator
in expanded form.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction((a - s)**2, (s**2 + a)**2, s)
>>> G1.expand()
TransferFunction(a**2 - 2*a*s + s**2, a**2 + 2*a*s**2 + s**4, s)
>>> G2 = TransferFunction((p + 3*b)*(p - b), (p - b)*(p + 2*b), p)
>>> G2.expand()
TransferFunction(-3*b**2 + 2*b*p + p**2, -2*b**2 + b*p + p**2, p)
"""
return TransferFunction(expand(self.num), expand(self.den), self.var)
def dc_gain(self):
"""
Computes the gain of the response as the frequency approaches zero.
The DC gain is infinite for systems with pure integrators.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(s + 3, s**2 - 9, s)
>>> tf1.dc_gain()
-1/3
>>> tf2 = TransferFunction(p**2, p - 3 + p**3, p)
>>> tf2.dc_gain()
0
>>> tf3 = TransferFunction(a*p**2 - b, s + b, s)
>>> tf3.dc_gain()
(a*p**2 - b)/b
>>> tf4 = TransferFunction(1, s, s)
>>> tf4.dc_gain()
oo
"""
m = Mul(self.num, Pow(self.den, -1, evaluate=False), evaluate=False)
return limit(m, self.var, 0)
def poles(self):
"""
Returns the poles of a transfer function.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
>>> tf1.poles()
[-5, 1]
>>> tf2 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
>>> tf2.poles()
[I, I, -I, -I]
>>> tf3 = TransferFunction(s**2, a*s + p, s)
>>> tf3.poles()
[-p/a]
"""
return _roots(Poly(self.den, self.var), self.var)
def zeros(self):
"""
Returns the zeros of a transfer function.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
>>> tf1.zeros()
[-3, 1]
>>> tf2 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
>>> tf2.zeros()
[1, 1]
>>> tf3 = TransferFunction(s**2, a*s + p, s)
>>> tf3.zeros()
[0, 0]
"""
return _roots(Poly(self.num, self.var), self.var)
def is_stable(self):
"""
Returns True if the transfer function is asymptotically stable; else False.
This would not check the marginal or conditional stability of the system.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy import symbols
>>> from sympy.physics.control.lti import TransferFunction
>>> q, r = symbols('q, r', negative=True)
>>> tf1 = TransferFunction((1 - s)**2, (s + 1)**2, s)
>>> tf1.is_stable()
True
>>> tf2 = TransferFunction((1 - p)**2, (s**2 + 1)**2, s)
>>> tf2.is_stable()
False
>>> tf3 = TransferFunction(4, q*s - r, s)
>>> tf3.is_stable()
False
>>> tf4 = TransferFunction(p + 1, a*p - s**2, p)
>>> tf4.is_stable() is None # Not enough info about the symbols to determine stability
True
"""
return fuzzy_and(pole.as_real_imag()[0].is_negative for pole in self.poles())
def __add__(self, other):
if isinstance(other, (TransferFunction, Series)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
return Parallel(self, other)
elif isinstance(other, Parallel):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
arg_list = list(other.args)
return Parallel(self, *arg_list)
else:
raise ValueError("TransferFunction cannot be added with {}.".
format(type(other)))
def __radd__(self, other):
return self + other
def __sub__(self, other):
if isinstance(other, (TransferFunction, Series)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
return Parallel(self, -other)
elif isinstance(other, Parallel):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
arg_list = [-i for i in list(other.args)]
return Parallel(self, *arg_list)
else:
raise ValueError("{} cannot be subtracted from a TransferFunction."
.format(type(other)))
def __rsub__(self, other):
return -self + other
def __mul__(self, other):
if isinstance(other, (TransferFunction, Parallel)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
return Series(self, other)
elif isinstance(other, Series):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
arg_list = list(other.args)
return Series(self, *arg_list)
else:
raise ValueError("TransferFunction cannot be multiplied with {}."
.format(type(other)))
__rmul__ = __mul__
def __truediv__(self, other):
if (isinstance(other, Parallel) and len(other.args) == 2 and isinstance(other.args[0], TransferFunction)
and isinstance(other.args[1], (Series, TransferFunction))):
if not self.var == other.var:
raise ValueError("Both TransferFunction and Parallel should use the"
" same complex variable of the Laplace transform.")
if other.args[1] == self:
# plant and controller with unit feedback.
return Feedback(self, other.args[0])
other_arg_list = list(other.args[1].args) if isinstance(other.args[1], Series) else other.args[1]
if other_arg_list == other.args[1]:
return Feedback(self, other_arg_list)
elif self in other_arg_list:
other_arg_list.remove(self)
else:
return Feedback(self, Series(*other_arg_list))
if len(other_arg_list) == 1:
return Feedback(self, *other_arg_list)
else:
return Feedback(self, Series(*other_arg_list))
else:
raise ValueError("TransferFunction cannot be divided by {}.".
format(type(other)))
__rtruediv__ = __truediv__
def __pow__(self, p):
p = sympify(p)
if not p.is_Integer:
raise ValueError("Exponent must be an integer.")
if p is S.Zero:
return TransferFunction(1, 1, self.var)
elif p > 0:
num_, den_ = self.num**p, self.den**p
else:
p = abs(p)
num_, den_ = self.den**p, self.num**p
return TransferFunction(num_, den_, self.var)
def __neg__(self):
return TransferFunction(-self.num, self.den, self.var)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial is less than
or equal to degree of the denominator polynomial, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf1.is_proper
False
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*p + 2, p)
>>> tf2.is_proper
True
"""
return degree(self.num, self.var) <= degree(self.den, self.var)
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial is strictly less
than degree of the denominator polynomial, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf1.is_strictly_proper
False
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf2.is_strictly_proper
True
"""
return degree(self.num, self.var) < degree(self.den, self.var)
@property
def is_biproper(self):
"""
Returns True if degree of the numerator polynomial is equal to
degree of the denominator polynomial, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf1.is_biproper
True
>>> tf2 = TransferFunction(p**2, p + a, p)
>>> tf2.is_biproper
False
"""
return degree(self.num, self.var) == degree(self.den, self.var)
def to_expr(self):
"""
Converts a ``TransferFunction`` object to SymPy Expr.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy import Expr
>>> tf1 = TransferFunction(s, a*s**2 + 1, s)
>>> tf1.to_expr()
s/(a*s**2 + 1)
>>> isinstance(_, Expr)
True
>>> tf2 = TransferFunction(1, (p + 3*b)*(b - p), p)
>>> tf2.to_expr()
1/((b - p)*(3*b + p))
>>> tf3 = TransferFunction((s - 2)*(s - 3), (s - 1)*(s - 2)*(s - 3), s)
>>> tf3.to_expr()
((s - 3)*(s - 2))/(((s - 3)*(s - 2)*(s - 1)))
"""
if self.num != 1:
return Mul(self.num, Pow(self.den, -1, evaluate=False), evaluate=False)
else:
return Pow(self.den, -1, evaluate=False)
def _flatten_args(args, _cls):
temp_args = []
for arg in args:
if isinstance(arg, _cls):
temp_args.extend(arg.args)
else:
temp_args.append(arg)
return tuple(temp_args)
def _dummify_args(_arg, var):
dummy_dict = {}
dummy_arg_list = []
for arg in _arg:
_s = Dummy()
dummy_dict[_s] = var
dummy_arg = arg.subs({var: _s})
dummy_arg_list.append(dummy_arg)
return dummy_arg_list, dummy_dict
class Series(SISOLinearTimeInvariant):
r"""
A class for representing a series configuration of SISO systems.
Parameters
==========
args : SISOLinearTimeInvariant
SISO systems in a series configuration.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``Series(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed, SISO in this case.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(p**2, p + s, s)
>>> S1 = Series(tf1, tf2)
>>> S1
Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s))
>>> S1.var
s
>>> S2 = Series(tf2, Parallel(tf3, -tf1))
>>> S2
Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Parallel(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s)))
>>> S2.var
s
>>> S3 = Series(Parallel(tf1, tf2), Parallel(tf2, tf3))
>>> S3
Series(Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s)))
>>> S3.var
s
You can get the resultant transfer function by using ``.doit()`` method:
>>> S3 = Series(tf1, tf2, -tf3)
>>> S3.doit()
TransferFunction(-p**2*(s**3 - 2)*(a*p**2 + b*s), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
>>> S4 = Series(tf2, Parallel(tf1, -tf3))
>>> S4.doit()
TransferFunction((s**3 - 2)*(-p**2*(-p + s) + (p + s)*(a*p**2 + b*s)), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
Notes
=====
All the transfer functions should use the same complex variable
``var`` of the Laplace transform.
See Also
========
MIMOSeries, Parallel, TransferFunction, Feedback
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, Series)
cls._check_args(args)
obj = super().__new__(cls, *args)
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Series, Parallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> Series(G1, G2).var
p
>>> Series(-G3, Parallel(G1, G2)).var
p
"""
return self.args[0].var
def doit(self, **hints):
"""
Returns the resultant transfer function obtained after evaluating
the transfer functions in series configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> Series(tf2, tf1).doit()
TransferFunction((s**3 - 2)*(a*p**2 + b*s), (-p + s)*(s**4 + 5*s + 6), s)
>>> Series(-tf1, -tf2).doit()
TransferFunction((2 - s**3)*(-a*p**2 - b*s), (-p + s)*(s**4 + 5*s + 6), s)
"""
_num_arg = (arg.doit().num for arg in self.args)
_den_arg = (arg.doit().den for arg in self.args)
res_num = Mul(*_num_arg, evaluate=True)
res_den = Mul(*_den_arg, evaluate=True)
return TransferFunction(res_num, res_den, self.var)
def _eval_rewrite_as_TransferFunction(self, *args, **kwargs):
return self.doit()
@_check_other_SISO
def __add__(self, other):
if isinstance(other, Parallel):
arg_list = list(other.args)
return Parallel(self, *arg_list)
return Parallel(self, other)
__radd__ = __add__
@_check_other_SISO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_SISO
def __mul__(self, other):
arg_list = list(self.args)
return Series(*arg_list, other)
def __truediv__(self, other):
if (isinstance(other, Parallel) and len(other.args) == 2
and isinstance(other.args[0], TransferFunction) and isinstance(other.args[1], Series)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
self_arg_list = set(list(self.args))
other_arg_list = set(list(other.args[1].args))
res = list(self_arg_list ^ other_arg_list)
if len(res) == 0:
return Feedback(self, other.args[0])
elif len(res) == 1:
return Feedback(self, *res)
else:
return Feedback(self, Series(*res))
else:
raise ValueError("This transfer function expression is invalid.")
def __neg__(self):
return Series(TransferFunction(-1, 1, self.var), self)
def to_expr(self):
"""Returns the equivalent ``Expr`` object."""
return Mul(*(arg.to_expr() for arg in self.args), evaluate=False)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is less than or equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> S1 = Series(-tf2, tf1)
>>> S1.is_proper
False
>>> S2 = Series(tf1, tf2, tf3)
>>> S2.is_proper
True
"""
return self.doit().is_proper
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is strictly less than degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**2 + 5*s + 6, s)
>>> tf3 = TransferFunction(1, s**2 + s + 1, s)
>>> S1 = Series(tf1, tf2)
>>> S1.is_strictly_proper
False
>>> S2 = Series(tf1, tf2, tf3)
>>> S2.is_strictly_proper
True
"""
return self.doit().is_strictly_proper
@property
def is_biproper(self):
r"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(p, s**2, s)
>>> tf3 = TransferFunction(s**2, 1, s)
>>> S1 = Series(tf1, -tf2)
>>> S1.is_biproper
False
>>> S2 = Series(tf2, tf3)
>>> S2.is_biproper
True
"""
return self.doit().is_biproper
def _mat_mul_compatible(*args):
"""To check whether shapes are compatible for matrix mul."""
return all(args[i].num_outputs == args[i+1].num_inputs for i in range(len(args)-1))
class MIMOSeries(MIMOLinearTimeInvariant):
r"""
A class for representing a series configuration of MIMO systems.
Parameters
==========
args : MIMOLinearTimeInvariant
MIMO systems in a series configuration.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``MIMOSeries(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
``num_outputs`` of the MIMO system is not equal to the
``num_inputs`` of its adjacent MIMO system. (Matrix
multiplication constraint, basically)
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed, MIMO in this case.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import MIMOSeries, TransferFunctionMatrix
>>> from sympy import Matrix, pprint
>>> mat_a = Matrix([[5*s], [5]]) # 2 Outputs 1 Input
>>> mat_b = Matrix([[5, 1/(6*s**2)]]) # 1 Output 2 Inputs
>>> mat_c = Matrix([[1, s], [5/s, 1]]) # 2 Outputs 2 Inputs
>>> tfm_a = TransferFunctionMatrix.from_Matrix(mat_a, s)
>>> tfm_b = TransferFunctionMatrix.from_Matrix(mat_b, s)
>>> tfm_c = TransferFunctionMatrix.from_Matrix(mat_c, s)
>>> MIMOSeries(tfm_c, tfm_b, tfm_a)
MIMOSeries(TransferFunctionMatrix(((TransferFunction(1, 1, s), TransferFunction(s, 1, s)), (TransferFunction(5, s, s), TransferFunction(1, 1, s)))), TransferFunctionMatrix(((TransferFunction(5, 1, s), TransferFunction(1, 6*s**2, s)),)), TransferFunctionMatrix(((TransferFunction(5*s, 1, s),), (TransferFunction(5, 1, s),))))
>>> pprint(_, use_unicode=False) # For Better Visualization
[5*s] [1 s]
[---] [5 1 ] [- -]
[ 1 ] [- ----] [1 1]
[ ] *[1 2] *[ ]
[ 5 ] [ 6*s ]{t} [5 1]
[ - ] [- -]
[ 1 ]{t} [s 1]{t}
>>> MIMOSeries(tfm_c, tfm_b, tfm_a).doit()
TransferFunctionMatrix(((TransferFunction(150*s**4 + 25*s, 6*s**3, s), TransferFunction(150*s**4 + 5*s, 6*s**2, s)), (TransferFunction(150*s**3 + 25, 6*s**3, s), TransferFunction(150*s**3 + 5, 6*s**2, s))))
>>> pprint(_, use_unicode=False) # (2 Inputs -A-> 2 Outputs) -> (2 Inputs -B-> 1 Output) -> (1 Input -C-> 2 Outputs) is equivalent to (2 Inputs -Series Equivalent-> 2 Outputs).
[ 4 4 ]
[150*s + 25*s 150*s + 5*s]
[------------- ------------]
[ 3 2 ]
[ 6*s 6*s ]
[ ]
[ 3 3 ]
[ 150*s + 25 150*s + 5 ]
[ ----------- ---------- ]
[ 3 2 ]
[ 6*s 6*s ]{t}
Notes
=====
All the transfer function matrices should use the same complex variable ``var`` of the Laplace transform.
``MIMOSeries(A, B)`` is not equivalent to ``A*B``. It is always in the reverse order, that is ``B*A``.
See Also
========
Series, MIMOParallel
"""
def __new__(cls, *args, evaluate=False):
cls._check_args(args)
if _mat_mul_compatible(*args):
obj = super().__new__(cls, *args)
else:
raise ValueError("Number of input signals do not match the number"
" of output signals of adjacent systems for some args.")
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, MIMOSeries, TransferFunctionMatrix
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> tfm_1 = TransferFunctionMatrix([[G1, G2, G3]])
>>> tfm_2 = TransferFunctionMatrix([[G1], [G2], [G3]])
>>> MIMOSeries(tfm_2, tfm_1).var
p
"""
return self.args[0].var
@property
def num_inputs(self):
"""Returns the number of input signals of the series system."""
return self.args[0].num_inputs
@property
def num_outputs(self):
"""Returns the number of output signals of the series system."""
return self.args[-1].num_outputs
@property
def shape(self):
"""Returns the shape of the equivalent MIMO system."""
return self.num_outputs, self.num_inputs
def doit(self, cancel=False, **kwargs):
"""
Returns the resultant transfer function matrix obtained after evaluating
the MIMO systems arranged in a series configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, MIMOSeries, TransferFunctionMatrix
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf2]])
>>> tfm2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf1]])
>>> MIMOSeries(tfm2, tfm1).doit()
TransferFunctionMatrix(((TransferFunction(2*(-p + s)*(s**3 - 2)*(a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)**2*(s**4 + 5*s + 6)**2, s), TransferFunction((-p + s)**2*(s**3 - 2)*(a*p**2 + b*s) + (-p + s)*(a*p**2 + b*s)**2*(s**4 + 5*s + 6), (-p + s)**3*(s**4 + 5*s + 6), s)), (TransferFunction((-p + s)*(s**3 - 2)**2*(s**4 + 5*s + 6) + (s**3 - 2)*(a*p**2 + b*s)*(s**4 + 5*s + 6)**2, (-p + s)*(s**4 + 5*s + 6)**3, s), TransferFunction(2*(s**3 - 2)*(a*p**2 + b*s), (-p + s)*(s**4 + 5*s + 6), s))))
"""
_arg = (arg.doit()._expr_mat for arg in reversed(self.args))
if cancel:
res = MatMul(*_arg, evaluate=True)
return TransferFunctionMatrix.from_Matrix(res, self.var)
_dummy_args, _dummy_dict = _dummify_args(_arg, self.var)
res = MatMul(*_dummy_args, evaluate=True)
temp_tfm = TransferFunctionMatrix.from_Matrix(res, self.var)
return temp_tfm.subs(_dummy_dict)
def _eval_rewrite_as_TransferFunctionMatrix(self, *args, **kwargs):
return self.doit()
@_check_other_MIMO
def __add__(self, other):
if isinstance(other, MIMOParallel):
arg_list = list(other.args)
return MIMOParallel(self, *arg_list)
return MIMOParallel(self, other)
__radd__ = __add__
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_MIMO
def __mul__(self, other):
if isinstance(other, MIMOSeries):
self_arg_list = list(self.args)
other_arg_list = list(other.args)
return MIMOSeries(*other_arg_list, *self_arg_list) # A*B = MIMOSeries(B, A)
arg_list = list(self.args)
return MIMOSeries(other, *arg_list)
def __neg__(self):
arg_list = list(self.args)
arg_list[0] = -arg_list[0]
return MIMOSeries(*arg_list)
class Parallel(SISOLinearTimeInvariant):
r"""
A class for representing a parallel configuration of SISO systems.
Parameters
==========
args : SISOLinearTimeInvariant
SISO systems in a parallel arrangement.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``Parallel(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(p**2, p + s, s)
>>> P1 = Parallel(tf1, tf2)
>>> P1
Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s))
>>> P1.var
s
>>> P2 = Parallel(tf2, Series(tf3, -tf1))
>>> P2
Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Series(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s)))
>>> P2.var
s
>>> P3 = Parallel(Series(tf1, tf2), Series(tf2, tf3))
>>> P3
Parallel(Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s)))
>>> P3.var
s
You can get the resultant transfer function by using ``.doit()`` method:
>>> Parallel(tf1, tf2, -tf3).doit()
TransferFunction(-p**2*(-p + s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2) + (p + s)*(a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
>>> Parallel(tf2, Series(tf1, -tf3)).doit()
TransferFunction(-p**2*(a*p**2 + b*s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
Notes
=====
All the transfer functions should use the same complex variable
``var`` of the Laplace transform.
See Also
========
Series, TransferFunction, Feedback
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, Parallel)
cls._check_args(args)
obj = super().__new__(cls, *args)
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Parallel, Series
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> Parallel(G1, G2).var
p
>>> Parallel(-G3, Series(G1, G2)).var
p
"""
return self.args[0].var
def doit(self, **hints):
"""
Returns the resultant transfer function obtained after evaluating
the transfer functions in parallel configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> Parallel(tf2, tf1).doit()
TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)
>>> Parallel(-tf1, -tf2).doit()
TransferFunction((2 - s**3)*(-p + s) + (-a*p**2 - b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)
"""
_arg = (arg.doit().to_expr() for arg in self.args)
res = Add(*_arg).as_numer_denom()
return TransferFunction(*res, self.var)
def _eval_rewrite_as_TransferFunction(self, *args, **kwargs):
return self.doit()
@_check_other_SISO
def __add__(self, other):
self_arg_list = list(self.args)
return Parallel(*self_arg_list, other)
__radd__ = __add__
@_check_other_SISO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_SISO
def __mul__(self, other):
if isinstance(other, Series):
arg_list = list(other.args)
return Series(self, *arg_list)
return Series(self, other)
def __neg__(self):
return Series(TransferFunction(-1, 1, self.var), self)
def to_expr(self):
"""Returns the equivalent ``Expr`` object."""
return Add(*(arg.to_expr() for arg in self.args), evaluate=False)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is less than or equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(-tf2, tf1)
>>> P1.is_proper
False
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_proper
True
"""
return self.doit().is_proper
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is strictly less than degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(tf1, tf2)
>>> P1.is_strictly_proper
False
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_strictly_proper
True
"""
return self.doit().is_strictly_proper
@property
def is_biproper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(p**2, p + s, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(tf1, -tf2)
>>> P1.is_biproper
True
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_biproper
False
"""
return self.doit().is_biproper
class MIMOParallel(MIMOLinearTimeInvariant):
r"""
A class for representing a parallel configuration of MIMO systems.
Parameters
==========
args : MIMOLinearTimeInvariant
MIMO Systems in a parallel arrangement.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``MIMOParallel(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
All MIMO systems passed do not have same shape.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed, MIMO in this case.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix, MIMOParallel
>>> from sympy import Matrix, pprint
>>> expr_1 = 1/s
>>> expr_2 = s/(s**2-1)
>>> expr_3 = (2 + s)/(s**2 - 1)
>>> expr_4 = 5
>>> tfm_a = TransferFunctionMatrix.from_Matrix(Matrix([[expr_1, expr_2], [expr_3, expr_4]]), s)
>>> tfm_b = TransferFunctionMatrix.from_Matrix(Matrix([[expr_2, expr_1], [expr_4, expr_3]]), s)
>>> tfm_c = TransferFunctionMatrix.from_Matrix(Matrix([[expr_3, expr_4], [expr_1, expr_2]]), s)
>>> MIMOParallel(tfm_a, tfm_b, tfm_c)
MIMOParallel(TransferFunctionMatrix(((TransferFunction(1, s, s), TransferFunction(s, s**2 - 1, s)), (TransferFunction(s + 2, s**2 - 1, s), TransferFunction(5, 1, s)))), TransferFunctionMatrix(((TransferFunction(s, s**2 - 1, s), TransferFunction(1, s, s)), (TransferFunction(5, 1, s), TransferFunction(s + 2, s**2 - 1, s)))), TransferFunctionMatrix(((TransferFunction(s + 2, s**2 - 1, s), TransferFunction(5, 1, s)), (TransferFunction(1, s, s), TransferFunction(s, s**2 - 1, s)))))
>>> pprint(_, use_unicode=False) # For Better Visualization
[ 1 s ] [ s 1 ] [s + 2 5 ]
[ - ------] [------ - ] [------ - ]
[ s 2 ] [ 2 s ] [ 2 1 ]
[ s - 1] [s - 1 ] [s - 1 ]
[ ] + [ ] + [ ]
[s + 2 5 ] [ 5 s + 2 ] [ 1 s ]
[------ - ] [ - ------] [ - ------]
[ 2 1 ] [ 1 2 ] [ s 2 ]
[s - 1 ]{t} [ s - 1]{t} [ s - 1]{t}
>>> MIMOParallel(tfm_a, tfm_b, tfm_c).doit()
TransferFunctionMatrix(((TransferFunction(s**2 + s*(2*s + 2) - 1, s*(s**2 - 1), s), TransferFunction(2*s**2 + 5*s*(s**2 - 1) - 1, s*(s**2 - 1), s)), (TransferFunction(s**2 + s*(s + 2) + 5*s*(s**2 - 1) - 1, s*(s**2 - 1), s), TransferFunction(5*s**2 + 2*s - 3, s**2 - 1, s))))
>>> pprint(_, use_unicode=False)
[ 2 2 / 2 \ ]
[ s + s*(2*s + 2) - 1 2*s + 5*s*\s - 1/ - 1]
[ -------------------- -----------------------]
[ / 2 \ / 2 \ ]
[ s*\s - 1/ s*\s - 1/ ]
[ ]
[ 2 / 2 \ 2 ]
[s + s*(s + 2) + 5*s*\s - 1/ - 1 5*s + 2*s - 3 ]
[--------------------------------- -------------- ]
[ / 2 \ 2 ]
[ s*\s - 1/ s - 1 ]{t}
Notes
=====
All the transfer function matrices should use the same complex variable
``var`` of the Laplace transform.
See Also
========
Parallel, MIMOSeries
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, MIMOParallel)
cls._check_args(args)
if any(arg.shape != args[0].shape for arg in args):
raise TypeError("Shape of all the args is not equal.")
obj = super().__new__(cls, *args)
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the systems.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOParallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> G4 = TransferFunction(p**2, p**2 - 1, p)
>>> tfm_a = TransferFunctionMatrix([[G1, G2], [G3, G4]])
>>> tfm_b = TransferFunctionMatrix([[G2, G1], [G4, G3]])
>>> MIMOParallel(tfm_a, tfm_b).var
p
"""
return self.args[0].var
@property
def num_inputs(self):
"""Returns the number of input signals of the parallel system."""
return self.args[0].num_inputs
@property
def num_outputs(self):
"""Returns the number of output signals of the parallel system."""
return self.args[0].num_outputs
@property
def shape(self):
"""Returns the shape of the equivalent MIMO system."""
return self.num_outputs, self.num_inputs
def doit(self, **hints):
"""
Returns the resultant transfer function matrix obtained after evaluating
the MIMO systems arranged in a parallel configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, MIMOParallel, TransferFunctionMatrix
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]])
>>> MIMOParallel(tfm_1, tfm_2).doit()
TransferFunctionMatrix(((TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s), TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)), (TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s), TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s))))
"""
_arg = (arg.doit()._expr_mat for arg in self.args)
res = MatAdd(*_arg, evaluate=True)
return TransferFunctionMatrix.from_Matrix(res, self.var)
def _eval_rewrite_as_TransferFunctionMatrix(self, *args, **kwargs):
return self.doit()
@_check_other_MIMO
def __add__(self, other):
self_arg_list = list(self.args)
return MIMOParallel(*self_arg_list, other)
__radd__ = __add__
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_MIMO
def __mul__(self, other):
if isinstance(other, MIMOSeries):
arg_list = list(other.args)
return MIMOSeries(*arg_list, self)
return MIMOSeries(other, self)
def __neg__(self):
arg_list = [-arg for arg in list(self.args)]
return MIMOParallel(*arg_list)
class Feedback(SISOLinearTimeInvariant):
r"""
A class for representing closed-loop feedback interconnection between two
SISO input/output systems.
The first argument, ``sys1``, is the feedforward part of the closed-loop
system or in simple words, the dynamical model representing the process
to be controlled. The second argument, ``sys2``, is the feedback system
and controls the fed back signal to ``sys1``. Both ``sys1`` and ``sys2``
can either be ``Series`` or ``TransferFunction`` objects.
Parameters
==========
sys1 : Series, TransferFunction
The feedforward path system.
sys2 : Series, TransferFunction, optional
The feedback path system (often a feedback controller).
It is the model sitting on the feedback path.
If not specified explicitly, the sys2 is
assumed to be unit (1.0) transfer function.
sign : int, optional
The sign of feedback. Can either be ``1``
(for positive feedback) or ``-1`` (for negative feedback).
Default value is `-1`.
Raises
======
ValueError
When ``sys1`` and ``sys2`` are not using the
same complex variable of the Laplace transform.
When a combination of ``sys1`` and ``sys2`` yields
zero denominator.
TypeError
When either ``sys1`` or ``sys2`` is not a ``Series`` or a
``TransferFunction`` object.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1
Feedback(TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s), -1)
>>> F1.var
s
>>> F1.args
(TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s), -1)
You can get the feedforward and feedback path systems by using ``.sys1`` and ``.sys2`` respectively.
>>> F1.sys1
TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> F1.sys2
TransferFunction(5*s - 10, s + 7, s)
You can get the resultant closed loop transfer function obtained by negative feedback
interconnection using ``.doit()`` method.
>>> F1.doit()
TransferFunction((s + 7)*(s**2 - 4*s + 2)*(3*s**2 + 7*s - 3), ((s + 7)*(s**2 - 4*s + 2) + (5*s - 10)*(3*s**2 + 7*s - 3))*(s**2 - 4*s + 2), s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s)
>>> C = TransferFunction(5*s + 10, s + 10, s)
>>> F2 = Feedback(G*C, TransferFunction(1, 1, s))
>>> F2.doit()
TransferFunction((s + 10)*(5*s + 10)*(s**2 + 2*s + 3)*(2*s**2 + 5*s + 1), (s + 10)*((s + 10)*(s**2 + 2*s + 3) + (5*s + 10)*(2*s**2 + 5*s + 1))*(s**2 + 2*s + 3), s)
To negate a ``Feedback`` object, the ``-`` operator can be prepended:
>>> -F1
Feedback(TransferFunction(-3*s**2 - 7*s + 3, s**2 - 4*s + 2, s), TransferFunction(10 - 5*s, s + 7, s), -1)
>>> -F2
Feedback(Series(TransferFunction(-1, 1, s), TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s), TransferFunction(5*s + 10, s + 10, s)), TransferFunction(-1, 1, s), -1)
See Also
========
MIMOFeedback, Series, Parallel
"""
def __new__(cls, sys1, sys2=None, sign=-1):
if not sys2:
sys2 = TransferFunction(1, 1, sys1.var)
if not (isinstance(sys1, (TransferFunction, Series))
and isinstance(sys2, (TransferFunction, Series))):
raise TypeError("Unsupported type for `sys1` or `sys2` of Feedback.")
if sign not in [-1, 1]:
raise ValueError("Unsupported type for feedback. `sign` arg should "
"either be 1 (positive feedback loop) or -1 (negative feedback loop).")
if Mul(sys1.to_expr(), sys2.to_expr()).simplify() == sign:
raise ValueError("The equivalent system will have zero denominator.")
if sys1.var != sys2.var:
raise ValueError("Both `sys1` and `sys2` should be using the"
" same complex variable.")
return super().__new__(cls, sys1, sys2, _sympify(sign))
@property
def sys1(self):
"""
Returns the feedforward system of the feedback interconnection.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.sys1
TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p)
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - s, p + 2, p)
>>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P)
>>> F2.sys1
TransferFunction(1, 1, p)
"""
return self.args[0]
@property
def sys2(self):
"""
Returns the feedback controller of the feedback interconnection.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.sys2
TransferFunction(5*s - 10, s + 7, s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p)
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - s, p + 2, p)
>>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P)
>>> F2.sys2
Series(TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p), TransferFunction(5*p + 10, p + 10, p), TransferFunction(1 - s, p + 2, p))
"""
return self.args[1]
@property
def var(self):
"""
Returns the complex variable of the Laplace transform used by all
the transfer functions involved in the feedback interconnection.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.var
s
>>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p)
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - s, p + 2, p)
>>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P)
>>> F2.var
p
"""
return self.sys1.var
@property
def sign(self):
"""
Returns the type of MIMO Feedback model. ``1``
for Positive and ``-1`` for Negative.
"""
return self.args[2]
@property
def sensitivity(self):
"""
Returns the sensitivity function of the feedback loop.
Sensitivity of a Feedback system is the ratio
of change in the open loop gain to the change in
the closed loop gain.
.. note::
This method would not return the complementary
sensitivity function.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - p, p + 2, p)
>>> F_1 = Feedback(P, C)
>>> F_1.sensitivity
1/((1 - p)*(5*p + 10)/((p + 2)*(p + 10)) + 1)
"""
return 1/(1 - self.sign*self.sys1.to_expr()*self.sys2.to_expr())
def doit(self, cancel=False, expand=False, **hints):
"""
Returns the resultant transfer function obtained by the
feedback interconnection.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.doit()
TransferFunction((s + 7)*(s**2 - 4*s + 2)*(3*s**2 + 7*s - 3), ((s + 7)*(s**2 - 4*s + 2) + (5*s - 10)*(3*s**2 + 7*s - 3))*(s**2 - 4*s + 2), s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s)
>>> F2 = Feedback(G, TransferFunction(1, 1, s))
>>> F2.doit()
TransferFunction((s**2 + 2*s + 3)*(2*s**2 + 5*s + 1), (s**2 + 2*s + 3)*(3*s**2 + 7*s + 4), s)
Use kwarg ``expand=True`` to expand the resultant transfer function.
Use ``cancel=True`` to cancel out the common terms in numerator and
denominator.
>>> F2.doit(cancel=True, expand=True)
TransferFunction(2*s**2 + 5*s + 1, 3*s**2 + 7*s + 4, s)
>>> F2.doit(expand=True)
TransferFunction(2*s**4 + 9*s**3 + 17*s**2 + 17*s + 3, 3*s**4 + 13*s**3 + 27*s**2 + 29*s + 12, s)
"""
arg_list = list(self.sys1.args) if isinstance(self.sys1, Series) else [self.sys1]
# F_n and F_d are resultant TFs of num and den of Feedback.
F_n, unit = self.sys1.doit(), TransferFunction(1, 1, self.sys1.var)
if self.sign == -1:
F_d = Parallel(unit, Series(self.sys2, *arg_list)).doit()
else:
F_d = Parallel(unit, -Series(self.sys2, *arg_list)).doit()
_resultant_tf = TransferFunction(F_n.num * F_d.den, F_n.den * F_d.num, F_n.var)
if cancel:
_resultant_tf = _resultant_tf.simplify()
if expand:
_resultant_tf = _resultant_tf.expand()
return _resultant_tf
def _eval_rewrite_as_TransferFunction(self, num, den, sign, **kwargs):
return self.doit()
def __neg__(self):
return Feedback(-self.sys1, -self.sys2, self.sign)
def _is_invertible(a, b, sign):
"""
Checks whether a given pair of MIMO
systems passed is invertible or not.
"""
_mat = eye(a.num_outputs) - sign*(a.doit()._expr_mat)*(b.doit()._expr_mat)
_det = _mat.det()
return _det != 0
class MIMOFeedback(MIMOLinearTimeInvariant):
r"""
A class for representing closed-loop feedback interconnection between two
MIMO input/output systems.
Parameters
==========
sys1 : MIMOSeries, TransferFunctionMatrix
The MIMO system placed on the feedforward path.
sys2 : MIMOSeries, TransferFunctionMatrix
The system placed on the feedback path
(often a feedback controller).
sign : int, optional
The sign of feedback. Can either be ``1``
(for positive feedback) or ``-1`` (for negative feedback).
Default value is `-1`.
Raises
======
ValueError
When ``sys1`` and ``sys2`` are not using the
same complex variable of the Laplace transform.
Forward path model should have an equal number of inputs/outputs
to the feedback path outputs/inputs.
When product of ``sys1`` and ``sys2`` is not a square matrix.
When the equivalent MIMO system is not invertible.
TypeError
When either ``sys1`` or ``sys2`` is not a ``MIMOSeries`` or a
``TransferFunctionMatrix`` object.
Examples
========
>>> from sympy import Matrix, pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix, MIMOFeedback
>>> plant_mat = Matrix([[1, 1/s], [0, 1]])
>>> controller_mat = Matrix([[10, 0], [0, 10]]) # Constant Gain
>>> plant = TransferFunctionMatrix.from_Matrix(plant_mat, s)
>>> controller = TransferFunctionMatrix.from_Matrix(controller_mat, s)
>>> feedback = MIMOFeedback(plant, controller) # Negative Feedback (default)
>>> pprint(feedback, use_unicode=False)
/ [1 1] [10 0 ] \-1 [1 1]
| [- -] [-- - ] | [- -]
| [1 s] [1 1 ] | [1 s]
|I + [ ] *[ ] | * [ ]
| [0 1] [0 10] | [0 1]
| [- -] [- --] | [- -]
\ [1 1]{t} [1 1 ]{t}/ [1 1]{t}
To get the equivalent system matrix, use either ``doit`` or ``rewrite`` method.
>>> pprint(feedback.doit(), use_unicode=False)
[1 1 ]
[-- -----]
[11 121*s]
[ ]
[0 1 ]
[- -- ]
[1 11 ]{t}
To negate the ``MIMOFeedback`` object, use ``-`` operator.
>>> neg_feedback = -feedback
>>> pprint(neg_feedback.doit(), use_unicode=False)
[-1 -1 ]
[--- -----]
[ 11 121*s]
[ ]
[ 0 -1 ]
[ - --- ]
[ 1 11 ]{t}
See Also
========
Feedback, MIMOSeries, MIMOParallel
"""
def __new__(cls, sys1, sys2, sign=-1):
if not (isinstance(sys1, (TransferFunctionMatrix, MIMOSeries))
and isinstance(sys2, (TransferFunctionMatrix, MIMOSeries))):
raise TypeError("Unsupported type for `sys1` or `sys2` of MIMO Feedback.")
if sys1.num_inputs != sys2.num_outputs or \
sys1.num_outputs != sys2.num_inputs:
raise ValueError("Product of `sys1` and `sys2` "
"must yield a square matrix.")
if sign not in (-1, 1):
raise ValueError("Unsupported type for feedback. `sign` arg should "
"either be 1 (positive feedback loop) or -1 (negative feedback loop).")
if not _is_invertible(sys1, sys2, sign):
raise ValueError("Non-Invertible system inputted.")
if sys1.var != sys2.var:
raise ValueError("Both `sys1` and `sys2` should be using the"
" same complex variable.")
return super().__new__(cls, sys1, sys2, _sympify(sign))
@property
def sys1(self):
r"""
Returns the system placed on the feedforward path of the MIMO feedback interconnection.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(s**2 + s + 1, s**2 - s + 1, s)
>>> tf2 = TransferFunction(1, s, s)
>>> tf3 = TransferFunction(1, 1, s)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf3, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1)
>>> F_1.sys1
TransferFunctionMatrix(((TransferFunction(s**2 + s + 1, s**2 - s + 1, s), TransferFunction(1, s, s)), (TransferFunction(1, s, s), TransferFunction(s**2 + s + 1, s**2 - s + 1, s))))
>>> pprint(_, use_unicode=False)
[ 2 ]
[s + s + 1 1 ]
[---------- - ]
[ 2 s ]
[s - s + 1 ]
[ ]
[ 2 ]
[ 1 s + s + 1]
[ - ----------]
[ s 2 ]
[ s - s + 1]{t}
"""
return self.args[0]
@property
def sys2(self):
r"""
Returns the feedback controller of the MIMO feedback interconnection.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(s**2, s**3 - s + 1, s)
>>> tf2 = TransferFunction(1, s, s)
>>> tf3 = TransferFunction(1, 1, s)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2)
>>> F_1.sys2
TransferFunctionMatrix(((TransferFunction(s**2, s**3 - s + 1, s), TransferFunction(1, 1, s)), (TransferFunction(1, 1, s), TransferFunction(1, s, s))))
>>> pprint(_, use_unicode=False)
[ 2 ]
[ s 1]
[---------- -]
[ 3 1]
[s - s + 1 ]
[ ]
[ 1 1]
[ - -]
[ 1 s]{t}
"""
return self.args[1]
@property
def var(self):
r"""
Returns the complex variable of the Laplace transform used by all
the transfer functions involved in the MIMO feedback loop.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(p, 1 - p, p)
>>> tf2 = TransferFunction(1, p, p)
>>> tf3 = TransferFunction(1, 1, p)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1) # Positive feedback
>>> F_1.var
p
"""
return self.sys1.var
@property
def sign(self):
r"""
Returns the type of feedback interconnection of two models. ``1``
for Positive and ``-1`` for Negative.
"""
return self.args[2]
@property
def sensitivity(self):
r"""
Returns the sensitivity function matrix of the feedback loop.
Sensitivity of a closed-loop system is the ratio of change
in the open loop gain to the change in the closed loop gain.
.. note::
This method would not return the complementary
sensitivity function.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(p, 1 - p, p)
>>> tf2 = TransferFunction(1, p, p)
>>> tf3 = TransferFunction(1, 1, p)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1) # Positive feedback
>>> F_2 = MIMOFeedback(sys1, sys2) # Negative feedback
>>> pprint(F_1.sensitivity, use_unicode=False)
[ 4 3 2 5 4 2 ]
[- p + 3*p - 4*p + 3*p - 1 p - 2*p + 3*p - 3*p + 1 ]
[---------------------------- -----------------------------]
[ 4 3 2 5 4 3 2 ]
[ p + 3*p - 8*p + 8*p - 3 p + 3*p - 8*p + 8*p - 3*p]
[ ]
[ 4 3 2 3 2 ]
[ p - p - p + p 3*p - 6*p + 4*p - 1 ]
[ -------------------------- -------------------------- ]
[ 4 3 2 4 3 2 ]
[ p + 3*p - 8*p + 8*p - 3 p + 3*p - 8*p + 8*p - 3 ]
>>> pprint(F_2.sensitivity, use_unicode=False)
[ 4 3 2 5 4 2 ]
[p - 3*p + 2*p + p - 1 p - 2*p + 3*p - 3*p + 1]
[------------------------ --------------------------]
[ 4 3 5 4 2 ]
[ p - 3*p + 2*p - 1 p - 3*p + 2*p - p ]
[ ]
[ 4 3 2 4 3 ]
[ p - p - p + p 2*p - 3*p + 2*p - 1 ]
[ ------------------- --------------------- ]
[ 4 3 4 3 ]
[ p - 3*p + 2*p - 1 p - 3*p + 2*p - 1 ]
"""
_sys1_mat = self.sys1.doit()._expr_mat
_sys2_mat = self.sys2.doit()._expr_mat
return (eye(self.sys1.num_inputs) - \
self.sign*_sys1_mat*_sys2_mat).inv()
def doit(self, cancel=True, expand=False, **hints):
r"""
Returns the resultant transfer function matrix obtained by the
feedback interconnection.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(s, 1 - s, s)
>>> tf2 = TransferFunction(1, s, s)
>>> tf3 = TransferFunction(5, 1, s)
>>> tf4 = TransferFunction(s - 1, s, s)
>>> tf5 = TransferFunction(0, 1, s)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
>>> sys2 = TransferFunctionMatrix([[tf3, tf5], [tf5, tf5]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1)
>>> pprint(F_1, use_unicode=False)
/ [ s 1 ] [5 0] \-1 [ s 1 ]
| [----- - ] [- -] | [----- - ]
| [1 - s s ] [1 1] | [1 - s s ]
|I - [ ] *[ ] | * [ ]
| [ 5 s - 1] [0 0] | [ 5 s - 1]
| [ - -----] [- -] | [ - -----]
\ [ 1 s ]{t} [1 1]{t}/ [ 1 s ]{t}
>>> pprint(F_1.doit(), use_unicode=False)
[ -s s - 1 ]
[------- ----------- ]
[6*s - 1 s*(6*s - 1) ]
[ ]
[5*s - 5 (s - 1)*(6*s + 24)]
[------- ------------------]
[6*s - 1 s*(6*s - 1) ]{t}
If the user wants the resultant ``TransferFunctionMatrix`` object without
canceling the common factors then the ``cancel`` kwarg should be passed ``False``.
>>> pprint(F_1.doit(cancel=False), use_unicode=False)
[ 25*s*(1 - s) 25 - 25*s ]
[ -------------------- -------------- ]
[ 25*(1 - 6*s)*(1 - s) 25*s*(1 - 6*s) ]
[ ]
[s*(25*s - 25) + 5*(1 - s)*(6*s - 1) s*(s - 1)*(6*s - 1) + s*(25*s - 25)]
[----------------------------------- -----------------------------------]
[ (1 - s)*(6*s - 1) 2 ]
[ s *(6*s - 1) ]{t}
If the user wants the expanded form of the resultant transfer function matrix,
the ``expand`` kwarg should be passed as ``True``.
>>> pprint(F_1.doit(expand=True), use_unicode=False)
[ -s s - 1 ]
[------- -------- ]
[6*s - 1 2 ]
[ 6*s - s ]
[ ]
[ 2 ]
[5*s - 5 6*s + 18*s - 24]
[------- ----------------]
[6*s - 1 2 ]
[ 6*s - s ]{t}
"""
_mat = self.sensitivity * self.sys1.doit()._expr_mat
_resultant_tfm = _to_TFM(_mat, self.var)
if cancel:
_resultant_tfm = _resultant_tfm.simplify()
if expand:
_resultant_tfm = _resultant_tfm.expand()
return _resultant_tfm
def _eval_rewrite_as_TransferFunctionMatrix(self, sys1, sys2, sign, **kwargs):
return self.doit()
def __neg__(self):
return MIMOFeedback(-self.sys1, -self.sys2, self.sign)
def _to_TFM(mat, var):
"""Private method to convert ImmutableMatrix to TransferFunctionMatrix efficiently"""
to_tf = lambda expr: TransferFunction.from_rational_expression(expr, var)
arg = [[to_tf(expr) for expr in row] for row in mat.tolist()]
return TransferFunctionMatrix(arg)
class TransferFunctionMatrix(MIMOLinearTimeInvariant):
r"""
A class for representing the MIMO (multiple-input and multiple-output)
generalization of the SISO (single-input and single-output) transfer function.
It is a matrix of transfer functions (``TransferFunction``, SISO-``Series`` or SISO-``Parallel``).
There is only one argument, ``arg`` which is also the compulsory argument.
``arg`` is expected to be strictly of the type list of lists
which holds the transfer functions or reducible to transfer functions.
Parameters
==========
arg : Nested ``List`` (strictly).
Users are expected to input a nested list of ``TransferFunction``, ``Series``
and/or ``Parallel`` objects.
Examples
========
.. note::
``pprint()`` can be used for better visualization of ``TransferFunctionMatrix`` objects.
>>> from sympy.abc import s, p, a
>>> from sympy import pprint
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, Series, Parallel
>>> tf_1 = TransferFunction(s + a, s**2 + s + 1, s)
>>> tf_2 = TransferFunction(p**4 - 3*p + 2, s + p, s)
>>> tf_3 = TransferFunction(3, s + 2, s)
>>> tf_4 = TransferFunction(-a + p, 9*s - 9, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1], [tf_2], [tf_3]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(3, s + 2, s),)))
>>> tfm_1.var
s
>>> tfm_1.num_inputs
1
>>> tfm_1.num_outputs
3
>>> tfm_1.shape
(3, 1)
>>> tfm_1.args
(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(3, s + 2, s),)),)
>>> tfm_2 = TransferFunctionMatrix([[tf_1, -tf_3], [tf_2, -tf_1], [tf_3, -tf_2]])
>>> tfm_2
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(p**4 - 3*p + 2, p + s, s), TransferFunction(-a - s, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-p**4 + 3*p - 2, p + s, s))))
>>> pprint(tfm_2, use_unicode=False) # pretty-printing for better visualization
[ a + s -3 ]
[ ---------- ----- ]
[ 2 s + 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[p - 3*p + 2 -a - s ]
[------------ ---------- ]
[ p + s 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[ 3 - p + 3*p - 2]
[ ----- --------------]
[ s + 2 p + s ]{t}
TransferFunctionMatrix can be transposed, if user wants to switch the input and output transfer functions
>>> tfm_2.transpose()
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(p**4 - 3*p + 2, p + s, s), TransferFunction(3, s + 2, s)), (TransferFunction(-3, s + 2, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(-p**4 + 3*p - 2, p + s, s))))
>>> pprint(_, use_unicode=False)
[ 4 ]
[ a + s p - 3*p + 2 3 ]
[---------- ------------ ----- ]
[ 2 p + s s + 2 ]
[s + s + 1 ]
[ ]
[ 4 ]
[ -3 -a - s - p + 3*p - 2]
[ ----- ---------- --------------]
[ s + 2 2 p + s ]
[ s + s + 1 ]{t}
>>> tf_5 = TransferFunction(5, s, s)
>>> tf_6 = TransferFunction(5*s, (2 + s**2), s)
>>> tf_7 = TransferFunction(5, (s*(2 + s**2)), s)
>>> tf_8 = TransferFunction(5, 1, s)
>>> tfm_3 = TransferFunctionMatrix([[tf_5, tf_6], [tf_7, tf_8]])
>>> tfm_3
TransferFunctionMatrix(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)), (TransferFunction(5, s*(s**2 + 2), s), TransferFunction(5, 1, s))))
>>> pprint(tfm_3, use_unicode=False)
[ 5 5*s ]
[ - ------]
[ s 2 ]
[ s + 2]
[ ]
[ 5 5 ]
[---------- - ]
[ / 2 \ 1 ]
[s*\s + 2/ ]{t}
>>> tfm_3.var
s
>>> tfm_3.shape
(2, 2)
>>> tfm_3.num_outputs
2
>>> tfm_3.num_inputs
2
>>> tfm_3.args
(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)), (TransferFunction(5, s*(s**2 + 2), s), TransferFunction(5, 1, s))),)
To access the ``TransferFunction`` at any index in the ``TransferFunctionMatrix``, use the index notation.
>>> tfm_3[1, 0] # gives the TransferFunction present at 2nd Row and 1st Col. Similar to that in Matrix classes
TransferFunction(5, s*(s**2 + 2), s)
>>> tfm_3[0, 0] # gives the TransferFunction present at 1st Row and 1st Col.
TransferFunction(5, s, s)
>>> tfm_3[:, 0] # gives the first column
TransferFunctionMatrix(((TransferFunction(5, s, s),), (TransferFunction(5, s*(s**2 + 2), s),)))
>>> pprint(_, use_unicode=False)
[ 5 ]
[ - ]
[ s ]
[ ]
[ 5 ]
[----------]
[ / 2 \]
[s*\s + 2/]{t}
>>> tfm_3[0, :] # gives the first row
TransferFunctionMatrix(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)),))
>>> pprint(_, use_unicode=False)
[5 5*s ]
[- ------]
[s 2 ]
[ s + 2]{t}
To negate a transfer function matrix, ``-`` operator can be prepended:
>>> tfm_4 = TransferFunctionMatrix([[tf_2], [-tf_1], [tf_3]])
>>> -tfm_4
TransferFunctionMatrix(((TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(-3, s + 2, s),)))
>>> tfm_5 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, -tf_1]])
>>> -tfm_5
TransferFunctionMatrix(((TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(-p**4 + 3*p - 2, p + s, s)), (TransferFunction(-3, s + 2, s), TransferFunction(a + s, s**2 + s + 1, s))))
``subs()`` returns the ``TransferFunctionMatrix`` object with the value substituted in the expression. This will not
mutate your original ``TransferFunctionMatrix``.
>>> tfm_2.subs(p, 2) # substituting p everywhere in tfm_2 with 2.
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(12, s + 2, s), TransferFunction(-a - s, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-12, s + 2, s))))
>>> pprint(_, use_unicode=False)
[ a + s -3 ]
[---------- ----- ]
[ 2 s + 2 ]
[s + s + 1 ]
[ ]
[ 12 -a - s ]
[ ----- ----------]
[ s + 2 2 ]
[ s + s + 1]
[ ]
[ 3 -12 ]
[ ----- ----- ]
[ s + 2 s + 2 ]{t}
>>> pprint(tfm_2, use_unicode=False) # State of tfm_2 is unchanged after substitution
[ a + s -3 ]
[ ---------- ----- ]
[ 2 s + 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[p - 3*p + 2 -a - s ]
[------------ ---------- ]
[ p + s 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[ 3 - p + 3*p - 2]
[ ----- --------------]
[ s + 2 p + s ]{t}
``subs()`` also supports multiple substitutions.
>>> tfm_2.subs({p: 2, a: 1}) # substituting p with 2 and a with 1
TransferFunctionMatrix(((TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(12, s + 2, s), TransferFunction(-s - 1, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-12, s + 2, s))))
>>> pprint(_, use_unicode=False)
[ s + 1 -3 ]
[---------- ----- ]
[ 2 s + 2 ]
[s + s + 1 ]
[ ]
[ 12 -s - 1 ]
[ ----- ----------]
[ s + 2 2 ]
[ s + s + 1]
[ ]
[ 3 -12 ]
[ ----- ----- ]
[ s + 2 s + 2 ]{t}
Users can reduce the ``Series`` and ``Parallel`` elements of the matrix to ``TransferFunction`` by using
``doit()``.
>>> tfm_6 = TransferFunctionMatrix([[Series(tf_3, tf_4), Parallel(tf_3, tf_4)]])
>>> tfm_6
TransferFunctionMatrix(((Series(TransferFunction(3, s + 2, s), TransferFunction(-a + p, 9*s - 9, s)), Parallel(TransferFunction(3, s + 2, s), TransferFunction(-a + p, 9*s - 9, s))),))
>>> pprint(tfm_6, use_unicode=False)
[ -a + p 3 -a + p 3 ]
[-------*----- ------- + -----]
[9*s - 9 s + 2 9*s - 9 s + 2]{t}
>>> tfm_6.doit()
TransferFunctionMatrix(((TransferFunction(-3*a + 3*p, (s + 2)*(9*s - 9), s), TransferFunction(27*s + (-a + p)*(s + 2) - 27, (s + 2)*(9*s - 9), s)),))
>>> pprint(_, use_unicode=False)
[ -3*a + 3*p 27*s + (-a + p)*(s + 2) - 27]
[----------------- ----------------------------]
[(s + 2)*(9*s - 9) (s + 2)*(9*s - 9) ]{t}
>>> tf_9 = TransferFunction(1, s, s)
>>> tf_10 = TransferFunction(1, s**2, s)
>>> tfm_7 = TransferFunctionMatrix([[Series(tf_9, tf_10), tf_9], [tf_10, Parallel(tf_9, tf_10)]])
>>> tfm_7
TransferFunctionMatrix(((Series(TransferFunction(1, s, s), TransferFunction(1, s**2, s)), TransferFunction(1, s, s)), (TransferFunction(1, s**2, s), Parallel(TransferFunction(1, s, s), TransferFunction(1, s**2, s)))))
>>> pprint(tfm_7, use_unicode=False)
[ 1 1 ]
[---- - ]
[ 2 s ]
[s*s ]
[ ]
[ 1 1 1]
[ -- -- + -]
[ 2 2 s]
[ s s ]{t}
>>> tfm_7.doit()
TransferFunctionMatrix(((TransferFunction(1, s**3, s), TransferFunction(1, s, s)), (TransferFunction(1, s**2, s), TransferFunction(s**2 + s, s**3, s))))
>>> pprint(_, use_unicode=False)
[1 1 ]
[-- - ]
[ 3 s ]
[s ]
[ ]
[ 2 ]
[1 s + s]
[-- ------]
[ 2 3 ]
[s s ]{t}
Addition, subtraction, and multiplication of transfer function matrices can form
unevaluated ``Series`` or ``Parallel`` objects.
- For addition and subtraction:
All the transfer function matrices must have the same shape.
- For multiplication (C = A * B):
The number of inputs of the first transfer function matrix (A) must be equal to the
number of outputs of the second transfer function matrix (B).
Also, use pretty-printing (``pprint``) to analyse better.
>>> tfm_8 = TransferFunctionMatrix([[tf_3], [tf_2], [-tf_1]])
>>> tfm_9 = TransferFunctionMatrix([[-tf_3]])
>>> tfm_10 = TransferFunctionMatrix([[tf_1], [tf_2], [tf_4]])
>>> tfm_11 = TransferFunctionMatrix([[tf_4], [-tf_1]])
>>> tfm_12 = TransferFunctionMatrix([[tf_4, -tf_1, tf_3], [-tf_2, -tf_4, -tf_3]])
>>> tfm_8 + tfm_10
MIMOParallel(TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a + p, 9*s - 9, s),))))
>>> pprint(_, use_unicode=False)
[ 3 ] [ a + s ]
[ ----- ] [ ---------- ]
[ s + 2 ] [ 2 ]
[ ] [ s + s + 1 ]
[ 4 ] [ ]
[p - 3*p + 2] [ 4 ]
[------------] + [p - 3*p + 2]
[ p + s ] [------------]
[ ] [ p + s ]
[ -a - s ] [ ]
[ ---------- ] [ -a + p ]
[ 2 ] [ ------- ]
[ s + s + 1 ]{t} [ 9*s - 9 ]{t}
>>> -tfm_10 - tfm_8
MIMOParallel(TransferFunctionMatrix(((TransferFunction(-a - s, s**2 + s + 1, s),), (TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a - p, 9*s - 9, s),))), TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),), (TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a + s, s**2 + s + 1, s),))))
>>> pprint(_, use_unicode=False)
[ -a - s ] [ -3 ]
[ ---------- ] [ ----- ]
[ 2 ] [ s + 2 ]
[ s + s + 1 ] [ ]
[ ] [ 4 ]
[ 4 ] [- p + 3*p - 2]
[- p + 3*p - 2] + [--------------]
[--------------] [ p + s ]
[ p + s ] [ ]
[ ] [ a + s ]
[ a - p ] [ ---------- ]
[ ------- ] [ 2 ]
[ 9*s - 9 ]{t} [ s + s + 1 ]{t}
>>> tfm_12 * tfm_8
MIMOSeries(TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(-a + p, 9*s - 9, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(3, s + 2, s)), (TransferFunction(-p**4 + 3*p - 2, p + s, s), TransferFunction(a - p, 9*s - 9, s), TransferFunction(-3, s + 2, s)))))
>>> pprint(_, use_unicode=False)
[ 3 ]
[ ----- ]
[ -a + p -a - s 3 ] [ s + 2 ]
[ ------- ---------- -----] [ ]
[ 9*s - 9 2 s + 2] [ 4 ]
[ s + s + 1 ] [p - 3*p + 2]
[ ] *[------------]
[ 4 ] [ p + s ]
[- p + 3*p - 2 a - p -3 ] [ ]
[-------------- ------- -----] [ -a - s ]
[ p + s 9*s - 9 s + 2]{t} [ ---------- ]
[ 2 ]
[ s + s + 1 ]{t}
>>> tfm_12 * tfm_8 * tfm_9
MIMOSeries(TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),),)), TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(-a + p, 9*s - 9, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(3, s + 2, s)), (TransferFunction(-p**4 + 3*p - 2, p + s, s), TransferFunction(a - p, 9*s - 9, s), TransferFunction(-3, s + 2, s)))))
>>> pprint(_, use_unicode=False)
[ 3 ]
[ ----- ]
[ -a + p -a - s 3 ] [ s + 2 ]
[ ------- ---------- -----] [ ]
[ 9*s - 9 2 s + 2] [ 4 ]
[ s + s + 1 ] [p - 3*p + 2] [ -3 ]
[ ] *[------------] *[-----]
[ 4 ] [ p + s ] [s + 2]{t}
[- p + 3*p - 2 a - p -3 ] [ ]
[-------------- ------- -----] [ -a - s ]
[ p + s 9*s - 9 s + 2]{t} [ ---------- ]
[ 2 ]
[ s + s + 1 ]{t}
>>> tfm_10 + tfm_8*tfm_9
MIMOParallel(TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a + p, 9*s - 9, s),))), MIMOSeries(TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),),)), TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),)))))
>>> pprint(_, use_unicode=False)
[ a + s ] [ 3 ]
[ ---------- ] [ ----- ]
[ 2 ] [ s + 2 ]
[ s + s + 1 ] [ ]
[ ] [ 4 ]
[ 4 ] [p - 3*p + 2] [ -3 ]
[p - 3*p + 2] + [------------] *[-----]
[------------] [ p + s ] [s + 2]{t}
[ p + s ] [ ]
[ ] [ -a - s ]
[ -a + p ] [ ---------- ]
[ ------- ] [ 2 ]
[ 9*s - 9 ]{t} [ s + s + 1 ]{t}
These unevaluated ``Series`` or ``Parallel`` objects can convert into the
resultant transfer function matrix using ``.doit()`` method or by
``.rewrite(TransferFunctionMatrix)``.
>>> (-tfm_8 + tfm_10 + tfm_8*tfm_9).doit()
TransferFunctionMatrix(((TransferFunction((a + s)*(s + 2)**3 - 3*(s + 2)**2*(s**2 + s + 1) - 9*(s + 2)*(s**2 + s + 1), (s + 2)**3*(s**2 + s + 1), s),), (TransferFunction((p + s)*(-3*p**4 + 9*p - 6), (p + s)**2*(s + 2), s),), (TransferFunction((-a + p)*(s + 2)*(s**2 + s + 1)**2 + (a + s)*(s + 2)*(9*s - 9)*(s**2 + s + 1) + (3*a + 3*s)*(9*s - 9)*(s**2 + s + 1), (s + 2)*(9*s - 9)*(s**2 + s + 1)**2, s),)))
>>> (-tfm_12 * -tfm_8 * -tfm_9).rewrite(TransferFunctionMatrix)
TransferFunctionMatrix(((TransferFunction(3*(-3*a + 3*p)*(p + s)*(s + 2)*(s**2 + s + 1)**2 + 3*(-3*a - 3*s)*(p + s)*(s + 2)*(9*s - 9)*(s**2 + s + 1) + 3*(a + s)*(s + 2)**2*(9*s - 9)*(-p**4 + 3*p - 2)*(s**2 + s + 1), (p + s)*(s + 2)**3*(9*s - 9)*(s**2 + s + 1)**2, s),), (TransferFunction(3*(-a + p)*(p + s)*(s + 2)**2*(-p**4 + 3*p - 2)*(s**2 + s + 1) + 3*(3*a + 3*s)*(p + s)**2*(s + 2)*(9*s - 9) + 3*(p + s)*(s + 2)*(9*s - 9)*(-3*p**4 + 9*p - 6)*(s**2 + s + 1), (p + s)**2*(s + 2)**3*(9*s - 9)*(s**2 + s + 1), s),)))
See Also
========
TransferFunction, MIMOSeries, MIMOParallel, Feedback
"""
def __new__(cls, arg):
expr_mat_arg = []
try:
var = arg[0][0].var
except TypeError:
raise ValueError("`arg` param in TransferFunctionMatrix should "
"strictly be a nested list containing TransferFunction objects.")
for row_index, row in enumerate(arg):
temp = []
for col_index, element in enumerate(row):
if not isinstance(element, SISOLinearTimeInvariant):
raise TypeError("Each element is expected to be of type `SISOLinearTimeInvariant`.")
if var != element.var:
raise ValueError("Conflicting value(s) found for `var`. All TransferFunction instances in "
"TransferFunctionMatrix should use the same complex variable in Laplace domain.")
temp.append(element.to_expr())
expr_mat_arg.append(temp)
if isinstance(arg, (tuple, list, Tuple)):
# Making nested Tuple (sympy.core.containers.Tuple) from nested list or nested Python tuple
arg = Tuple(*(Tuple(*r, sympify=False) for r in arg), sympify=False)
obj = super(TransferFunctionMatrix, cls).__new__(cls, arg)
obj._expr_mat = ImmutableMatrix(expr_mat_arg)
return obj
@classmethod
def from_Matrix(cls, matrix, var):
"""
Creates a new ``TransferFunctionMatrix`` efficiently from a SymPy Matrix of ``Expr`` objects.
Parameters
==========
matrix : ``ImmutableMatrix`` having ``Expr``/``Number`` elements.
var : Symbol
Complex variable of the Laplace transform which will be used by the
all the ``TransferFunction`` objects in the ``TransferFunctionMatrix``.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix
>>> from sympy import Matrix, pprint
>>> M = Matrix([[s, 1/s], [1/(s+1), s]])
>>> M_tf = TransferFunctionMatrix.from_Matrix(M, s)
>>> pprint(M_tf, use_unicode=False)
[ s 1]
[ - -]
[ 1 s]
[ ]
[ 1 s]
[----- -]
[s + 1 1]{t}
>>> M_tf.elem_poles()
[[[], [0]], [[-1], []]]
>>> M_tf.elem_zeros()
[[[0], []], [[], [0]]]
"""
return _to_TFM(matrix, var)
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions or
``Series``/``Parallel`` objects in a transfer function matrix.
Examples
========
>>> from sympy.abc import p, s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, Series, Parallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> G4 = TransferFunction(s + 1, s**2 + s + 1, s)
>>> S1 = Series(G1, G2)
>>> S2 = Series(-G3, Parallel(G2, -G1))
>>> tfm1 = TransferFunctionMatrix([[G1], [G2], [G3]])
>>> tfm1.var
p
>>> tfm2 = TransferFunctionMatrix([[-S1, -S2], [S1, S2]])
>>> tfm2.var
p
>>> tfm3 = TransferFunctionMatrix([[G4]])
>>> tfm3.var
s
"""
return self.args[0][0][0].var
@property
def num_inputs(self):
"""
Returns the number of inputs of the system.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> G1 = TransferFunction(s + 3, s**2 - 3, s)
>>> G2 = TransferFunction(4, s**2, s)
>>> G3 = TransferFunction(p**2 + s**2, p - 3, s)
>>> tfm_1 = TransferFunctionMatrix([[G2, -G1, G3], [-G2, -G1, -G3]])
>>> tfm_1.num_inputs
3
See Also
========
num_outputs
"""
return self._expr_mat.shape[1]
@property
def num_outputs(self):
"""
Returns the number of outputs of the system.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix
>>> from sympy import Matrix
>>> M_1 = Matrix([[s], [1/s]])
>>> TFM = TransferFunctionMatrix.from_Matrix(M_1, s)
>>> print(TFM)
TransferFunctionMatrix(((TransferFunction(s, 1, s),), (TransferFunction(1, s, s),)))
>>> TFM.num_outputs
2
See Also
========
num_inputs
"""
return self._expr_mat.shape[0]
@property
def shape(self):
"""
Returns the shape of the transfer function matrix, that is, ``(# of outputs, # of inputs)``.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf1 = TransferFunction(p**2 - 1, s**4 + s**3 - p, p)
>>> tf2 = TransferFunction(1 - p, p**2 - 3*p + 7, p)
>>> tf3 = TransferFunction(3, 4, p)
>>> tfm1 = TransferFunctionMatrix([[tf1, -tf2]])
>>> tfm1.shape
(1, 2)
>>> tfm2 = TransferFunctionMatrix([[-tf2, tf3], [tf1, -tf1]])
>>> tfm2.shape
(2, 2)
"""
return self._expr_mat.shape
def __neg__(self):
neg = -self._expr_mat
return _to_TFM(neg, self.var)
@_check_other_MIMO
def __add__(self, other):
if not isinstance(other, MIMOParallel):
return MIMOParallel(self, other)
other_arg_list = list(other.args)
return MIMOParallel(self, *other_arg_list)
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
@_check_other_MIMO
def __mul__(self, other):
if not isinstance(other, MIMOSeries):
return MIMOSeries(other, self)
other_arg_list = list(other.args)
return MIMOSeries(*other_arg_list, self)
def __getitem__(self, key):
trunc = self._expr_mat.__getitem__(key)
if isinstance(trunc, ImmutableMatrix):
return _to_TFM(trunc, self.var)
return TransferFunction.from_rational_expression(trunc, self.var)
def transpose(self):
"""Returns the transpose of the ``TransferFunctionMatrix`` (switched input and output layers)."""
transposed_mat = self._expr_mat.transpose()
return _to_TFM(transposed_mat, self.var)
def elem_poles(self):
"""
Returns the poles of each element of the ``TransferFunctionMatrix``.
.. note::
Actual poles of a MIMO system are NOT the poles of individual elements.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf_1 = TransferFunction(3, (s + 1), s)
>>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s)
>>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s)
>>> tf_4 = TransferFunction(s + 2, s**2 + 5*s - 10, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s + 2, s**2 + 5*s - 10, s))))
>>> tfm_1.elem_poles()
[[[-1], [-2, -1]], [[-2, -1], [-5/2 + sqrt(65)/2, -sqrt(65)/2 - 5/2]]]
See Also
========
elem_zeros
"""
return [[element.poles() for element in row] for row in self.doit().args[0]]
def elem_zeros(self):
"""
Returns the zeros of each element of the ``TransferFunctionMatrix``.
.. note::
Actual zeros of a MIMO system are NOT the zeros of individual elements.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf_1 = TransferFunction(3, (s + 1), s)
>>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s)
>>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s)
>>> tf_4 = TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s))))
>>> tfm_1.elem_zeros()
[[[], [-6]], [[-3], [4, 5]]]
See Also
========
elem_poles
"""
return [[element.zeros() for element in row] for row in self.doit().args[0]]
def _flat(self):
"""Returns flattened list of args in TransferFunctionMatrix"""
return [elem for tup in self.args[0] for elem in tup]
def _eval_evalf(self, prec):
"""Calls evalf() on each transfer function in the transfer function matrix"""
dps = prec_to_dps(prec)
mat = self._expr_mat.applyfunc(lambda a: a.evalf(n=dps))
return _to_TFM(mat, self.var)
def _eval_simplify(self, **kwargs):
"""Simplifies the transfer function matrix"""
simp_mat = self._expr_mat.applyfunc(lambda a: cancel(a, expand=False))
return _to_TFM(simp_mat, self.var)
def expand(self, **hints):
"""Expands the transfer function matrix"""
expand_mat = self._expr_mat.expand(**hints)
return _to_TFM(expand_mat, self.var)
|
436e5e803854b3ec6b961e68cb86419673aa179a49b50d52468dbcaf99e7b9d6 | from sympy.core.numbers import I, pi
from sympy.functions.elementary.exponential import (exp, log)
from sympy.polys.partfrac import apart
from sympy.core.symbol import Dummy
from sympy.external import import_module
from sympy.functions import arg, Abs
from sympy.integrals.laplace import _fast_inverse_laplace
from sympy.physics.control.lti import SISOLinearTimeInvariant
from sympy.plotting.plot import LineOver1DRangeSeries
from sympy.polys.polytools import Poly
from sympy.printing.latex import latex
__all__ = ['pole_zero_numerical_data', 'pole_zero_plot',
'step_response_numerical_data', 'step_response_plot',
'impulse_response_numerical_data', 'impulse_response_plot',
'ramp_response_numerical_data', 'ramp_response_plot',
'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot']
matplotlib = import_module(
'matplotlib', import_kwargs={'fromlist': ['pyplot']},
catch=(RuntimeError,))
numpy = import_module('numpy')
if matplotlib:
plt = matplotlib.pyplot
if numpy:
np = numpy # Matplotlib already has numpy as a compulsory dependency. No need to install it separately.
def _check_system(system):
"""Function to check whether the dynamical system passed for plots is
compatible or not."""
if not isinstance(system, SISOLinearTimeInvariant):
raise NotImplementedError("Only SISO LTI systems are currently supported.")
sys = system.to_expr()
len_free_symbols = len(sys.free_symbols)
if len_free_symbols > 1:
raise ValueError("Extra degree of freedom found. Make sure"
" that there are no free symbols in the dynamical system other"
" than the variable of Laplace transform.")
if sys.has(exp):
# Should test that exp is not part of a constant, in which case
# no exception is required, compare exp(s) with s*exp(1)
raise NotImplementedError("Time delay terms are not supported.")
def pole_zero_numerical_data(system):
"""
Returns the numerical data of poles and zeros of the system.
It is internally used by ``pole_zero_plot`` to get the data
for plotting poles and zeros. Users can use this data to further
analyse the dynamics of the system or plot using a different
backend/plotting-module.
Parameters
==========
system : SISOLinearTimeInvariant
The system for which the pole-zero data is to be computed.
Returns
=======
tuple : (zeros, poles)
zeros = Zeros of the system. NumPy array of complex numbers.
poles = Poles of the system. NumPy array of complex numbers.
Raises
======
NotImplementedError
When a SISO LTI system is not passed.
When time delay terms are present in the system.
ValueError
When more than one free symbol is present in the system.
The only variable in the transfer function should be
the variable of the Laplace transform.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import pole_zero_numerical_data
>>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
>>> pole_zero_numerical_data(tf1) # doctest: +SKIP
([-0.+1.j 0.-1.j], [-2. +0.j -0.5+0.8660254j -0.5-0.8660254j -1. +0.j ])
See Also
========
pole_zero_plot
"""
_check_system(system)
system = system.doit() # Get the equivalent TransferFunction object.
num_poly = Poly(system.num, system.var).all_coeffs()
den_poly = Poly(system.den, system.var).all_coeffs()
num_poly = np.array(num_poly, dtype=np.complex128)
den_poly = np.array(den_poly, dtype=np.complex128)
zeros = np.roots(num_poly)
poles = np.roots(den_poly)
return zeros, poles
def pole_zero_plot(system, pole_color='blue', pole_markersize=10,
zero_color='orange', zero_markersize=7, grid=True, show_axes=True,
show=True, **kwargs):
r"""
Returns the Pole-Zero plot (also known as PZ Plot or PZ Map) of a system.
A Pole-Zero plot is a graphical representation of a system's poles and
zeros. It is plotted on a complex plane, with circular markers representing
the system's zeros and 'x' shaped markers representing the system's poles.
Parameters
==========
system : SISOLinearTimeInvariant type systems
The system for which the pole-zero plot is to be computed.
pole_color : str, tuple, optional
The color of the pole points on the plot. Default color
is blue. The color can be provided as a matplotlib color string,
or a 3-tuple of floats each in the 0-1 range.
pole_markersize : Number, optional
The size of the markers used to mark the poles in the plot.
Default pole markersize is 10.
zero_color : str, tuple, optional
The color of the zero points on the plot. Default color
is orange. The color can be provided as a matplotlib color string,
or a 3-tuple of floats each in the 0-1 range.
zero_markersize : Number, optional
The size of the markers used to mark the zeros in the plot.
Default zero markersize is 7.
grid : boolean, optional
If ``True``, the plot will have a grid. Defaults to True.
show_axes : boolean, optional
If ``True``, the coordinate axes will be shown. Defaults to False.
show : boolean, optional
If ``True``, the plot will be displayed otherwise
the equivalent matplotlib ``plot`` object will be returned.
Defaults to True.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import pole_zero_plot
>>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
>>> pole_zero_plot(tf1) # doctest: +SKIP
See Also
========
pole_zero_numerical_data
References
==========
.. [1] https://en.wikipedia.org/wiki/Pole%E2%80%93zero_plot
"""
zeros, poles = pole_zero_numerical_data(system)
zero_real = np.real(zeros)
zero_imag = np.imag(zeros)
pole_real = np.real(poles)
pole_imag = np.imag(poles)
plt.plot(pole_real, pole_imag, 'x', mfc='none',
markersize=pole_markersize, color=pole_color)
plt.plot(zero_real, zero_imag, 'o', markersize=zero_markersize,
color=zero_color)
plt.xlabel('Real Axis')
plt.ylabel('Imaginary Axis')
plt.title(f'Poles and Zeros of ${latex(system)}$', pad=20)
if grid:
plt.grid()
if show_axes:
plt.axhline(0, color='black')
plt.axvline(0, color='black')
if show:
plt.show()
return
return plt
def step_response_numerical_data(system, prec=8, lower_limit=0,
upper_limit=10, **kwargs):
"""
Returns the numerical values of the points in the step response plot
of a SISO continuous-time system. By default, adaptive sampling
is used. If the user wants to instead get an uniformly
sampled response, then ``adaptive`` kwarg should be passed ``False``
and ``nb_of_points`` must be passed as additional kwargs.
Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries`
for more details.
Parameters
==========
system : SISOLinearTimeInvariant
The system for which the unit step response data is to be computed.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
lower_limit : Number, optional
The lower limit of the plot range. Defaults to 0.
upper_limit : Number, optional
The upper limit of the plot range. Defaults to 10.
kwargs :
Additional keyword arguments are passed to the underlying
:class:`sympy.plotting.plot.LineOver1DRangeSeries` class.
Returns
=======
tuple : (x, y)
x = Time-axis values of the points in the step response. NumPy array.
y = Amplitude-axis values of the points in the step response. NumPy array.
Raises
======
NotImplementedError
When a SISO LTI system is not passed.
When time delay terms are present in the system.
ValueError
When more than one free symbol is present in the system.
The only variable in the transfer function should be
the variable of the Laplace transform.
When ``lower_limit`` parameter is less than 0.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import step_response_numerical_data
>>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
>>> step_response_numerical_data(tf1) # doctest: +SKIP
([0.0, 0.025413462339411542, 0.0484508722725343, ... , 9.670250533855183, 9.844291913708725, 10.0],
[0.0, 0.023844582399907256, 0.042894276802320226, ..., 6.828770759094287e-12, 6.456457160755703e-12])
See Also
========
step_response_plot
"""
if lower_limit < 0:
raise ValueError("Lower limit of time must be greater "
"than or equal to zero.")
_check_system(system)
_x = Dummy("x")
expr = system.to_expr()/(system.var)
expr = apart(expr, system.var, full=True)
_y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
**kwargs).get_points()
def step_response_plot(system, color='b', prec=8, lower_limit=0,
upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
r"""
Returns the unit step response of a continuous-time system. It is
the response of the system when the input signal is a step function.
Parameters
==========
system : SISOLinearTimeInvariant type
The LTI SISO system for which the Step Response is to be computed.
color : str, tuple, optional
The color of the line. Default is Blue.
show : boolean, optional
If ``True``, the plot will be displayed otherwise
the equivalent matplotlib ``plot`` object will be returned.
Defaults to True.
lower_limit : Number, optional
The lower limit of the plot range. Defaults to 0.
upper_limit : Number, optional
The upper limit of the plot range. Defaults to 10.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
show_axes : boolean, optional
If ``True``, the coordinate axes will be shown. Defaults to False.
grid : boolean, optional
If ``True``, the plot will have a grid. Defaults to True.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import step_response_plot
>>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
>>> step_response_plot(tf1) # doctest: +SKIP
See Also
========
impulse_response_plot, ramp_response_plot
References
==========
.. [1] https://www.mathworks.com/help/control/ref/lti.step.html
"""
x, y = step_response_numerical_data(system, prec=prec,
lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
plt.plot(x, y, color=color)
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title(f'Unit Step Response of ${latex(system)}$', pad=20)
if grid:
plt.grid()
if show_axes:
plt.axhline(0, color='black')
plt.axvline(0, color='black')
if show:
plt.show()
return
return plt
def impulse_response_numerical_data(system, prec=8, lower_limit=0,
upper_limit=10, **kwargs):
"""
Returns the numerical values of the points in the impulse response plot
of a SISO continuous-time system. By default, adaptive sampling
is used. If the user wants to instead get an uniformly
sampled response, then ``adaptive`` kwarg should be passed ``False``
and ``nb_of_points`` must be passed as additional kwargs.
Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries`
for more details.
Parameters
==========
system : SISOLinearTimeInvariant
The system for which the impulse response data is to be computed.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
lower_limit : Number, optional
The lower limit of the plot range. Defaults to 0.
upper_limit : Number, optional
The upper limit of the plot range. Defaults to 10.
kwargs :
Additional keyword arguments are passed to the underlying
:class:`sympy.plotting.plot.LineOver1DRangeSeries` class.
Returns
=======
tuple : (x, y)
x = Time-axis values of the points in the impulse response. NumPy array.
y = Amplitude-axis values of the points in the impulse response. NumPy array.
Raises
======
NotImplementedError
When a SISO LTI system is not passed.
When time delay terms are present in the system.
ValueError
When more than one free symbol is present in the system.
The only variable in the transfer function should be
the variable of the Laplace transform.
When ``lower_limit`` parameter is less than 0.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import impulse_response_numerical_data
>>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
>>> impulse_response_numerical_data(tf1) # doctest: +SKIP
([0.0, 0.06616480200395854,... , 9.854500743565858, 10.0],
[0.9999999799999999, 0.7042848373025861,...,7.170748906965121e-13, -5.1901263495547205e-12])
See Also
========
impulse_response_plot
"""
if lower_limit < 0:
raise ValueError("Lower limit of time must be greater "
"than or equal to zero.")
_check_system(system)
_x = Dummy("x")
expr = system.to_expr()
expr = apart(expr, system.var, full=True)
_y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
**kwargs).get_points()
def impulse_response_plot(system, color='b', prec=8, lower_limit=0,
upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
r"""
Returns the unit impulse response (Input is the Dirac-Delta Function) of a
continuous-time system.
Parameters
==========
system : SISOLinearTimeInvariant type
The LTI SISO system for which the Impulse Response is to be computed.
color : str, tuple, optional
The color of the line. Default is Blue.
show : boolean, optional
If ``True``, the plot will be displayed otherwise
the equivalent matplotlib ``plot`` object will be returned.
Defaults to True.
lower_limit : Number, optional
The lower limit of the plot range. Defaults to 0.
upper_limit : Number, optional
The upper limit of the plot range. Defaults to 10.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
show_axes : boolean, optional
If ``True``, the coordinate axes will be shown. Defaults to False.
grid : boolean, optional
If ``True``, the plot will have a grid. Defaults to True.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import impulse_response_plot
>>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
>>> impulse_response_plot(tf1) # doctest: +SKIP
See Also
========
step_response_plot, ramp_response_plot
References
==========
.. [1] https://www.mathworks.com/help/control/ref/lti.impulse.html
"""
x, y = impulse_response_numerical_data(system, prec=prec,
lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
plt.plot(x, y, color=color)
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title(f'Impulse Response of ${latex(system)}$', pad=20)
if grid:
plt.grid()
if show_axes:
plt.axhline(0, color='black')
plt.axvline(0, color='black')
if show:
plt.show()
return
return plt
def ramp_response_numerical_data(system, slope=1, prec=8,
lower_limit=0, upper_limit=10, **kwargs):
"""
Returns the numerical values of the points in the ramp response plot
of a SISO continuous-time system. By default, adaptive sampling
is used. If the user wants to instead get an uniformly
sampled response, then ``adaptive`` kwarg should be passed ``False``
and ``nb_of_points`` must be passed as additional kwargs.
Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries`
for more details.
Parameters
==========
system : SISOLinearTimeInvariant
The system for which the ramp response data is to be computed.
slope : Number, optional
The slope of the input ramp function. Defaults to 1.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
lower_limit : Number, optional
The lower limit of the plot range. Defaults to 0.
upper_limit : Number, optional
The upper limit of the plot range. Defaults to 10.
kwargs :
Additional keyword arguments are passed to the underlying
:class:`sympy.plotting.plot.LineOver1DRangeSeries` class.
Returns
=======
tuple : (x, y)
x = Time-axis values of the points in the ramp response plot. NumPy array.
y = Amplitude-axis values of the points in the ramp response plot. NumPy array.
Raises
======
NotImplementedError
When a SISO LTI system is not passed.
When time delay terms are present in the system.
ValueError
When more than one free symbol is present in the system.
The only variable in the transfer function should be
the variable of the Laplace transform.
When ``lower_limit`` parameter is less than 0.
When ``slope`` is negative.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import ramp_response_numerical_data
>>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
>>> ramp_response_numerical_data(tf1) # doctest: +SKIP
(([0.0, 0.12166980856813935,..., 9.861246379582118, 10.0],
[1.4504508011325967e-09, 0.006046440489058766,..., 0.12499999999568202, 0.12499999999661349]))
See Also
========
ramp_response_plot
"""
if slope < 0:
raise ValueError("Slope must be greater than or equal"
" to zero.")
if lower_limit < 0:
raise ValueError("Lower limit of time must be greater "
"than or equal to zero.")
_check_system(system)
_x = Dummy("x")
expr = (slope*system.to_expr())/((system.var)**2)
expr = apart(expr, system.var, full=True)
_y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
**kwargs).get_points()
def ramp_response_plot(system, slope=1, color='b', prec=8, lower_limit=0,
upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
r"""
Returns the ramp response of a continuous-time system.
Ramp function is defined as the straight line
passing through origin ($f(x) = mx$). The slope of
the ramp function can be varied by the user and
the default value is 1.
Parameters
==========
system : SISOLinearTimeInvariant type
The LTI SISO system for which the Ramp Response is to be computed.
slope : Number, optional
The slope of the input ramp function. Defaults to 1.
color : str, tuple, optional
The color of the line. Default is Blue.
show : boolean, optional
If ``True``, the plot will be displayed otherwise
the equivalent matplotlib ``plot`` object will be returned.
Defaults to True.
lower_limit : Number, optional
The lower limit of the plot range. Defaults to 0.
upper_limit : Number, optional
The upper limit of the plot range. Defaults to 10.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
show_axes : boolean, optional
If ``True``, the coordinate axes will be shown. Defaults to False.
grid : boolean, optional
If ``True``, the plot will have a grid. Defaults to True.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import ramp_response_plot
>>> tf1 = TransferFunction(s, (s+4)*(s+8), s)
>>> ramp_response_plot(tf1, upper_limit=2) # doctest: +SKIP
See Also
========
step_response_plot, ramp_response_plot
References
==========
.. [1] https://en.wikipedia.org/wiki/Ramp_function
"""
x, y = ramp_response_numerical_data(system, slope=slope, prec=prec,
lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
plt.plot(x, y, color=color)
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title(f'Ramp Response of ${latex(system)}$ [Slope = {slope}]', pad=20)
if grid:
plt.grid()
if show_axes:
plt.axhline(0, color='black')
plt.axvline(0, color='black')
if show:
plt.show()
return
return plt
def bode_magnitude_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', **kwargs):
"""
Returns the numerical data of the Bode magnitude plot of the system.
It is internally used by ``bode_magnitude_plot`` to get the data
for plotting Bode magnitude plot. Users can use this data to further
analyse the dynamics of the system or plot using a different
backend/plotting-module.
Parameters
==========
system : SISOLinearTimeInvariant
The system for which the data is to be computed.
initial_exp : Number, optional
The initial exponent of 10 of the semilog plot. Defaults to -5.
final_exp : Number, optional
The final exponent of 10 of the semilog plot. Defaults to 5.
freq_unit : string, optional
User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units.
Returns
=======
tuple : (x, y)
x = x-axis values of the Bode magnitude plot.
y = y-axis values of the Bode magnitude plot.
Raises
======
NotImplementedError
When a SISO LTI system is not passed.
When time delay terms are present in the system.
ValueError
When more than one free symbol is present in the system.
The only variable in the transfer function should be
the variable of the Laplace transform.
When incorrect frequency units are given as input.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import bode_magnitude_numerical_data
>>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
>>> bode_magnitude_numerical_data(tf1) # doctest: +SKIP
([1e-05, 1.5148378120533502e-05,..., 68437.36188804005, 100000.0],
[-6.020599914256786, -6.0205999155219505,..., -193.4117304087953, -200.00000000260573])
See Also
========
bode_magnitude_plot, bode_phase_numerical_data
"""
_check_system(system)
expr = system.to_expr()
freq_units = ('rad/sec', 'Hz')
if freq_unit not in freq_units:
raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.')
_w = Dummy("w", real=True)
if freq_unit == 'Hz':
repl = I*_w*2*pi
else:
repl = I*_w
w_expr = expr.subs({system.var: repl})
mag = 20*log(Abs(w_expr), 10)
x, y = LineOver1DRangeSeries(mag,
(_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
return x, y
def bode_magnitude_plot(system, initial_exp=-5, final_exp=5,
color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', **kwargs):
r"""
Returns the Bode magnitude plot of a continuous-time system.
See ``bode_plot`` for all the parameters.
"""
x, y = bode_magnitude_numerical_data(system, initial_exp=initial_exp,
final_exp=final_exp, freq_unit=freq_unit)
plt.plot(x, y, color=color, **kwargs)
plt.xscale('log')
plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit)
plt.ylabel('Magnitude (dB)')
plt.title(f'Bode Plot (Magnitude) of ${latex(system)}$', pad=20)
if grid:
plt.grid(True)
if show_axes:
plt.axhline(0, color='black')
plt.axvline(0, color='black')
if show:
plt.show()
return
return plt
def bode_phase_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', phase_unit='rad', **kwargs):
"""
Returns the numerical data of the Bode phase plot of the system.
It is internally used by ``bode_phase_plot`` to get the data
for plotting Bode phase plot. Users can use this data to further
analyse the dynamics of the system or plot using a different
backend/plotting-module.
Parameters
==========
system : SISOLinearTimeInvariant
The system for which the Bode phase plot data is to be computed.
initial_exp : Number, optional
The initial exponent of 10 of the semilog plot. Defaults to -5.
final_exp : Number, optional
The final exponent of 10 of the semilog plot. Defaults to 5.
freq_unit : string, optional
User can choose between ``'rad/sec'`` (radians/second) and '``'Hz'`` (Hertz) as frequency units.
phase_unit : string, optional
User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units.
Returns
=======
tuple : (x, y)
x = x-axis values of the Bode phase plot.
y = y-axis values of the Bode phase plot.
Raises
======
NotImplementedError
When a SISO LTI system is not passed.
When time delay terms are present in the system.
ValueError
When more than one free symbol is present in the system.
The only variable in the transfer function should be
the variable of the Laplace transform.
When incorrect frequency or phase units are given as input.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import bode_phase_numerical_data
>>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
>>> bode_phase_numerical_data(tf1) # doctest: +SKIP
([1e-05, 1.4472354033813751e-05, 2.035581932165858e-05,..., 47577.3248186011, 67884.09326036123, 100000.0],
[-2.5000000000291665e-05, -3.6180885085e-05, -5.08895483066e-05,...,-3.1415085799262523, -3.14155265358979])
See Also
========
bode_magnitude_plot, bode_phase_numerical_data
"""
_check_system(system)
expr = system.to_expr()
freq_units = ('rad/sec', 'Hz')
phase_units = ('rad', 'deg')
if freq_unit not in freq_units:
raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.')
if phase_unit not in phase_units:
raise ValueError('Only "rad" and "deg" are accepted phase units.')
_w = Dummy("w", real=True)
if freq_unit == 'Hz':
repl = I*_w*2*pi
else:
repl = I*_w
w_expr = expr.subs({system.var: repl})
if phase_unit == 'deg':
phase = arg(w_expr)*180/pi
else:
phase = arg(w_expr)
x, y = LineOver1DRangeSeries(phase,
(_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
return x, y
def bode_phase_plot(system, initial_exp=-5, final_exp=5,
color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', phase_unit='rad', **kwargs):
r"""
Returns the Bode phase plot of a continuous-time system.
See ``bode_plot`` for all the parameters.
"""
x, y = bode_phase_numerical_data(system, initial_exp=initial_exp,
final_exp=final_exp, freq_unit=freq_unit, phase_unit=phase_unit)
plt.plot(x, y, color=color, **kwargs)
plt.xscale('log')
plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit)
plt.ylabel('Phase (%s)' % phase_unit)
plt.title(f'Bode Plot (Phase) of ${latex(system)}$', pad=20)
if grid:
plt.grid(True)
if show_axes:
plt.axhline(0, color='black')
plt.axvline(0, color='black')
if show:
plt.show()
return
return plt
def bode_plot(system, initial_exp=-5, final_exp=5,
grid=True, show_axes=False, show=True, freq_unit='rad/sec', phase_unit='rad', **kwargs):
r"""
Returns the Bode phase and magnitude plots of a continuous-time system.
Parameters
==========
system : SISOLinearTimeInvariant type
The LTI SISO system for which the Bode Plot is to be computed.
initial_exp : Number, optional
The initial exponent of 10 of the semilog plot. Defaults to -5.
final_exp : Number, optional
The final exponent of 10 of the semilog plot. Defaults to 5.
show : boolean, optional
If ``True``, the plot will be displayed otherwise
the equivalent matplotlib ``plot`` object will be returned.
Defaults to True.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
grid : boolean, optional
If ``True``, the plot will have a grid. Defaults to True.
show_axes : boolean, optional
If ``True``, the coordinate axes will be shown. Defaults to False.
freq_unit : string, optional
User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units.
phase_unit : string, optional
User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import bode_plot
>>> tf1 = TransferFunction(1*s**2 + 0.1*s + 7.5, 1*s**4 + 0.12*s**3 + 9*s**2, s)
>>> bode_plot(tf1, initial_exp=0.2, final_exp=0.7) # doctest: +SKIP
See Also
========
bode_magnitude_plot, bode_phase_plot
"""
plt.subplot(211)
mag = bode_magnitude_plot(system, initial_exp=initial_exp, final_exp=final_exp,
show=False, grid=grid, show_axes=show_axes,
freq_unit=freq_unit, **kwargs)
mag.title(f'Bode Plot of ${latex(system)}$', pad=20)
mag.xlabel(None)
plt.subplot(212)
bode_phase_plot(system, initial_exp=initial_exp, final_exp=final_exp,
show=False, grid=grid, show_axes=show_axes, freq_unit=freq_unit, phase_unit=phase_unit, **kwargs).title(None)
if show:
plt.show()
return
return plt
|
661fe38b927461e032d807b3b1070757d5b689c5a869add9c136df8c2090989a | from collections import deque
from sympy.core.random import randint
from sympy.external import import_module
from sympy.core.basic import Basic
from sympy.core.mul import Mul
from sympy.core.numbers import Number, equal_valued
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.dagger import Dagger
__all__ = [
# Public interfaces
'generate_gate_rules',
'generate_equivalent_ids',
'GateIdentity',
'bfs_identity_search',
'random_identity_search',
# "Private" functions
'is_scalar_sparse_matrix',
'is_scalar_nonsparse_matrix',
'is_degenerate',
'is_reducible',
]
np = import_module('numpy')
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
def is_scalar_sparse_matrix(circuit, nqubits, identity_only, eps=1e-11):
"""Checks if a given scipy.sparse matrix is a scalar matrix.
A scalar matrix is such that B = bI, where B is the scalar
matrix, b is some scalar multiple, and I is the identity
matrix. A scalar matrix would have only the element b along
it's main diagonal and zeroes elsewhere.
Parameters
==========
circuit : Gate tuple
Sequence of quantum gates representing a quantum circuit
nqubits : int
Number of qubits in the circuit
identity_only : bool
Check for only identity matrices
eps : number
The tolerance value for zeroing out elements in the matrix.
Values in the range [-eps, +eps] will be changed to a zero.
"""
if not np or not scipy:
pass
matrix = represent(Mul(*circuit), nqubits=nqubits,
format='scipy.sparse')
# In some cases, represent returns a 1D scalar value in place
# of a multi-dimensional scalar matrix
if (isinstance(matrix, int)):
return matrix == 1 if identity_only else True
# If represent returns a matrix, check if the matrix is diagonal
# and if every item along the diagonal is the same
else:
# Due to floating pointing operations, must zero out
# elements that are "very" small in the dense matrix
# See parameter for default value.
# Get the ndarray version of the dense matrix
dense_matrix = matrix.todense().getA()
# Since complex values can't be compared, must split
# the matrix into real and imaginary components
# Find the real values in between -eps and eps
bool_real = np.logical_and(dense_matrix.real > -eps,
dense_matrix.real < eps)
# Find the imaginary values between -eps and eps
bool_imag = np.logical_and(dense_matrix.imag > -eps,
dense_matrix.imag < eps)
# Replaces values between -eps and eps with 0
corrected_real = np.where(bool_real, 0.0, dense_matrix.real)
corrected_imag = np.where(bool_imag, 0.0, dense_matrix.imag)
# Convert the matrix with real values into imaginary values
corrected_imag = corrected_imag * complex(1j)
# Recombine the real and imaginary components
corrected_dense = corrected_real + corrected_imag
# Check if it's diagonal
row_indices = corrected_dense.nonzero()[0]
col_indices = corrected_dense.nonzero()[1]
# Check if the rows indices and columns indices are the same
# If they match, then matrix only contains elements along diagonal
bool_indices = row_indices == col_indices
is_diagonal = bool_indices.all()
first_element = corrected_dense[0][0]
# If the first element is a zero, then can't rescale matrix
# and definitely not diagonal
if (first_element == 0.0 + 0.0j):
return False
# The dimensions of the dense matrix should still
# be 2^nqubits if there are elements all along the
# the main diagonal
trace_of_corrected = (corrected_dense/first_element).trace()
expected_trace = pow(2, nqubits)
has_correct_trace = trace_of_corrected == expected_trace
# If only looking for identity matrices
# first element must be a 1
real_is_one = abs(first_element.real - 1.0) < eps
imag_is_zero = abs(first_element.imag) < eps
is_one = real_is_one and imag_is_zero
is_identity = is_one if identity_only else True
return bool(is_diagonal and has_correct_trace and is_identity)
def is_scalar_nonsparse_matrix(circuit, nqubits, identity_only, eps=None):
"""Checks if a given circuit, in matrix form, is equivalent to
a scalar value.
Parameters
==========
circuit : Gate tuple
Sequence of quantum gates representing a quantum circuit
nqubits : int
Number of qubits in the circuit
identity_only : bool
Check for only identity matrices
eps : number
This argument is ignored. It is just for signature compatibility with
is_scalar_sparse_matrix.
Note: Used in situations when is_scalar_sparse_matrix has bugs
"""
matrix = represent(Mul(*circuit), nqubits=nqubits)
# In some cases, represent returns a 1D scalar value in place
# of a multi-dimensional scalar matrix
if (isinstance(matrix, Number)):
return matrix == 1 if identity_only else True
# If represent returns a matrix, check if the matrix is diagonal
# and if every item along the diagonal is the same
else:
# Added up the diagonal elements
matrix_trace = matrix.trace()
# Divide the trace by the first element in the matrix
# if matrix is not required to be the identity matrix
adjusted_matrix_trace = (matrix_trace/matrix[0]
if not identity_only
else matrix_trace)
is_identity = equal_valued(matrix[0], 1) if identity_only else True
has_correct_trace = adjusted_matrix_trace == pow(2, nqubits)
# The matrix is scalar if it's diagonal and the adjusted trace
# value is equal to 2^nqubits
return bool(
matrix.is_diagonal() and has_correct_trace and is_identity)
if np and scipy:
is_scalar_matrix = is_scalar_sparse_matrix
else:
is_scalar_matrix = is_scalar_nonsparse_matrix
def _get_min_qubits(a_gate):
if isinstance(a_gate, Pow):
return a_gate.base.min_qubits
else:
return a_gate.min_qubits
def ll_op(left, right):
"""Perform a LL operation.
A LL operation multiplies both left and right circuits
with the dagger of the left circuit's leftmost gate, and
the dagger is multiplied on the left side of both circuits.
If a LL is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a LL is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a LL operation:
>>> from sympy.physics.quantum.identitysearch import ll_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> ll_op((x, y, z), ())
((Y(0), Z(0)), (X(0),))
>>> ll_op((y, z), (x,))
((Z(0),), (Y(0), X(0)))
"""
if (len(left) > 0):
ll_gate = left[0]
ll_gate_is_unitary = is_scalar_matrix(
(Dagger(ll_gate), ll_gate), _get_min_qubits(ll_gate), True)
if (len(left) > 0 and ll_gate_is_unitary):
# Get the new left side w/o the leftmost gate
new_left = left[1:len(left)]
# Add the leftmost gate to the left position on the right side
new_right = (Dagger(ll_gate),) + right
# Return the new gate rule
return (new_left, new_right)
return None
def lr_op(left, right):
"""Perform a LR operation.
A LR operation multiplies both left and right circuits
with the dagger of the left circuit's rightmost gate, and
the dagger is multiplied on the right side of both circuits.
If a LR is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a LR is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a LR operation:
>>> from sympy.physics.quantum.identitysearch import lr_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> lr_op((x, y, z), ())
((X(0), Y(0)), (Z(0),))
>>> lr_op((x, y), (z,))
((X(0),), (Z(0), Y(0)))
"""
if (len(left) > 0):
lr_gate = left[len(left) - 1]
lr_gate_is_unitary = is_scalar_matrix(
(Dagger(lr_gate), lr_gate), _get_min_qubits(lr_gate), True)
if (len(left) > 0 and lr_gate_is_unitary):
# Get the new left side w/o the rightmost gate
new_left = left[0:len(left) - 1]
# Add the rightmost gate to the right position on the right side
new_right = right + (Dagger(lr_gate),)
# Return the new gate rule
return (new_left, new_right)
return None
def rl_op(left, right):
"""Perform a RL operation.
A RL operation multiplies both left and right circuits
with the dagger of the right circuit's leftmost gate, and
the dagger is multiplied on the left side of both circuits.
If a RL is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a RL is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a RL operation:
>>> from sympy.physics.quantum.identitysearch import rl_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> rl_op((x,), (y, z))
((Y(0), X(0)), (Z(0),))
>>> rl_op((x, y), (z,))
((Z(0), X(0), Y(0)), ())
"""
if (len(right) > 0):
rl_gate = right[0]
rl_gate_is_unitary = is_scalar_matrix(
(Dagger(rl_gate), rl_gate), _get_min_qubits(rl_gate), True)
if (len(right) > 0 and rl_gate_is_unitary):
# Get the new right side w/o the leftmost gate
new_right = right[1:len(right)]
# Add the leftmost gate to the left position on the left side
new_left = (Dagger(rl_gate),) + left
# Return the new gate rule
return (new_left, new_right)
return None
def rr_op(left, right):
"""Perform a RR operation.
A RR operation multiplies both left and right circuits
with the dagger of the right circuit's rightmost gate, and
the dagger is multiplied on the right side of both circuits.
If a RR is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a RR is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a RR operation:
>>> from sympy.physics.quantum.identitysearch import rr_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> rr_op((x, y), (z,))
((X(0), Y(0), Z(0)), ())
>>> rr_op((x,), (y, z))
((X(0), Z(0)), (Y(0),))
"""
if (len(right) > 0):
rr_gate = right[len(right) - 1]
rr_gate_is_unitary = is_scalar_matrix(
(Dagger(rr_gate), rr_gate), _get_min_qubits(rr_gate), True)
if (len(right) > 0 and rr_gate_is_unitary):
# Get the new right side w/o the rightmost gate
new_right = right[0:len(right) - 1]
# Add the rightmost gate to the right position on the right side
new_left = left + (Dagger(rr_gate),)
# Return the new gate rule
return (new_left, new_right)
return None
def generate_gate_rules(gate_seq, return_as_muls=False):
"""Returns a set of gate rules. Each gate rules is represented
as a 2-tuple of tuples or Muls. An empty tuple represents an arbitrary
scalar value.
This function uses the four operations (LL, LR, RL, RR)
to generate the gate rules.
A gate rule is an expression such as ABC = D or AB = CD, where
A, B, C, and D are gates. Each value on either side of the
equal sign represents a circuit. The four operations allow
one to find a set of equivalent circuits from a gate identity.
The letters denoting the operation tell the user what
activities to perform on each expression. The first letter
indicates which side of the equal sign to focus on. The
second letter indicates which gate to focus on given the
side. Once this information is determined, the inverse
of the gate is multiplied on both circuits to create a new
gate rule.
For example, given the identity, ABCD = 1, a LL operation
means look at the left value and multiply both left sides by the
inverse of the leftmost gate A. If A is Hermitian, the inverse
of A is still A. The resulting new rule is BCD = A.
The following is a summary of the four operations. Assume
that in the examples, all gates are Hermitian.
LL : left circuit, left multiply
ABCD = E -> AABCD = AE -> BCD = AE
LR : left circuit, right multiply
ABCD = E -> ABCDD = ED -> ABC = ED
RL : right circuit, left multiply
ABC = ED -> EABC = EED -> EABC = D
RR : right circuit, right multiply
AB = CD -> ABD = CDD -> ABD = C
The number of gate rules generated is n*(n+1), where n
is the number of gates in the sequence (unproven).
Parameters
==========
gate_seq : Gate tuple, Mul, or Number
A variable length tuple or Mul of Gates whose product is equal to
a scalar matrix
return_as_muls : bool
True to return a set of Muls; False to return a set of tuples
Examples
========
Find the gate rules of the current circuit using tuples:
>>> from sympy.physics.quantum.identitysearch import generate_gate_rules
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> generate_gate_rules((x, x))
{((X(0),), (X(0),)), ((X(0), X(0)), ())}
>>> generate_gate_rules((x, y, z))
{((), (X(0), Z(0), Y(0))), ((), (Y(0), X(0), Z(0))),
((), (Z(0), Y(0), X(0))), ((X(0),), (Z(0), Y(0))),
((Y(0),), (X(0), Z(0))), ((Z(0),), (Y(0), X(0))),
((X(0), Y(0)), (Z(0),)), ((Y(0), Z(0)), (X(0),)),
((Z(0), X(0)), (Y(0),)), ((X(0), Y(0), Z(0)), ()),
((Y(0), Z(0), X(0)), ()), ((Z(0), X(0), Y(0)), ())}
Find the gate rules of the current circuit using Muls:
>>> generate_gate_rules(x*x, return_as_muls=True)
{(1, 1)}
>>> generate_gate_rules(x*y*z, return_as_muls=True)
{(1, X(0)*Z(0)*Y(0)), (1, Y(0)*X(0)*Z(0)),
(1, Z(0)*Y(0)*X(0)), (X(0)*Y(0), Z(0)),
(Y(0)*Z(0), X(0)), (Z(0)*X(0), Y(0)),
(X(0)*Y(0)*Z(0), 1), (Y(0)*Z(0)*X(0), 1),
(Z(0)*X(0)*Y(0), 1), (X(0), Z(0)*Y(0)),
(Y(0), X(0)*Z(0)), (Z(0), Y(0)*X(0))}
"""
if isinstance(gate_seq, Number):
if return_as_muls:
return {(S.One, S.One)}
else:
return {((), ())}
elif isinstance(gate_seq, Mul):
gate_seq = gate_seq.args
# Each item in queue is a 3-tuple:
# i) first item is the left side of an equality
# ii) second item is the right side of an equality
# iii) third item is the number of operations performed
# The argument, gate_seq, will start on the left side, and
# the right side will be empty, implying the presence of an
# identity.
queue = deque()
# A set of gate rules
rules = set()
# Maximum number of operations to perform
max_ops = len(gate_seq)
def process_new_rule(new_rule, ops):
if new_rule is not None:
new_left, new_right = new_rule
if new_rule not in rules and (new_right, new_left) not in rules:
rules.add(new_rule)
# If haven't reached the max limit on operations
if ops + 1 < max_ops:
queue.append(new_rule + (ops + 1,))
queue.append((gate_seq, (), 0))
rules.add((gate_seq, ()))
while len(queue) > 0:
left, right, ops = queue.popleft()
# Do a LL
new_rule = ll_op(left, right)
process_new_rule(new_rule, ops)
# Do a LR
new_rule = lr_op(left, right)
process_new_rule(new_rule, ops)
# Do a RL
new_rule = rl_op(left, right)
process_new_rule(new_rule, ops)
# Do a RR
new_rule = rr_op(left, right)
process_new_rule(new_rule, ops)
if return_as_muls:
# Convert each rule as tuples into a rule as muls
mul_rules = set()
for rule in rules:
left, right = rule
mul_rules.add((Mul(*left), Mul(*right)))
rules = mul_rules
return rules
def generate_equivalent_ids(gate_seq, return_as_muls=False):
"""Returns a set of equivalent gate identities.
A gate identity is a quantum circuit such that the product
of the gates in the circuit is equal to a scalar value.
For example, XYZ = i, where X, Y, Z are the Pauli gates and
i is the imaginary value, is considered a gate identity.
This function uses the four operations (LL, LR, RL, RR)
to generate the gate rules and, subsequently, to locate equivalent
gate identities.
Note that all equivalent identities are reachable in n operations
from the starting gate identity, where n is the number of gates
in the sequence.
The max number of gate identities is 2n, where n is the number
of gates in the sequence (unproven).
Parameters
==========
gate_seq : Gate tuple, Mul, or Number
A variable length tuple or Mul of Gates whose product is equal to
a scalar matrix.
return_as_muls: bool
True to return as Muls; False to return as tuples
Examples
========
Find equivalent gate identities from the current circuit with tuples:
>>> from sympy.physics.quantum.identitysearch import generate_equivalent_ids
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> generate_equivalent_ids((x, x))
{(X(0), X(0))}
>>> generate_equivalent_ids((x, y, z))
{(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
(Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
Find equivalent gate identities from the current circuit with Muls:
>>> generate_equivalent_ids(x*x, return_as_muls=True)
{1}
>>> generate_equivalent_ids(x*y*z, return_as_muls=True)
{X(0)*Y(0)*Z(0), X(0)*Z(0)*Y(0), Y(0)*X(0)*Z(0),
Y(0)*Z(0)*X(0), Z(0)*X(0)*Y(0), Z(0)*Y(0)*X(0)}
"""
if isinstance(gate_seq, Number):
return {S.One}
elif isinstance(gate_seq, Mul):
gate_seq = gate_seq.args
# Filter through the gate rules and keep the rules
# with an empty tuple either on the left or right side
# A set of equivalent gate identities
eq_ids = set()
gate_rules = generate_gate_rules(gate_seq)
for rule in gate_rules:
l, r = rule
if l == ():
eq_ids.add(r)
elif r == ():
eq_ids.add(l)
if return_as_muls:
convert_to_mul = lambda id_seq: Mul(*id_seq)
eq_ids = set(map(convert_to_mul, eq_ids))
return eq_ids
class GateIdentity(Basic):
"""Wrapper class for circuits that reduce to a scalar value.
A gate identity is a quantum circuit such that the product
of the gates in the circuit is equal to a scalar value.
For example, XYZ = i, where X, Y, Z are the Pauli gates and
i is the imaginary value, is considered a gate identity.
Parameters
==========
args : Gate tuple
A variable length tuple of Gates that form an identity.
Examples
========
Create a GateIdentity and look at its attributes:
>>> from sympy.physics.quantum.identitysearch import GateIdentity
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> an_identity = GateIdentity(x, y, z)
>>> an_identity.circuit
X(0)*Y(0)*Z(0)
>>> an_identity.equivalent_ids
{(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
(Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
"""
def __new__(cls, *args):
# args should be a tuple - a variable length argument list
obj = Basic.__new__(cls, *args)
obj._circuit = Mul(*args)
obj._rules = generate_gate_rules(args)
obj._eq_ids = generate_equivalent_ids(args)
return obj
@property
def circuit(self):
return self._circuit
@property
def gate_rules(self):
return self._rules
@property
def equivalent_ids(self):
return self._eq_ids
@property
def sequence(self):
return self.args
def __str__(self):
"""Returns the string of gates in a tuple."""
return str(self.circuit)
def is_degenerate(identity_set, gate_identity):
"""Checks if a gate identity is a permutation of another identity.
Parameters
==========
identity_set : set
A Python set with GateIdentity objects.
gate_identity : GateIdentity
The GateIdentity to check for existence in the set.
Examples
========
Check if the identity is a permutation of another identity:
>>> from sympy.physics.quantum.identitysearch import (
... GateIdentity, is_degenerate)
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> an_identity = GateIdentity(x, y, z)
>>> id_set = {an_identity}
>>> another_id = (y, z, x)
>>> is_degenerate(id_set, another_id)
True
>>> another_id = (x, x)
>>> is_degenerate(id_set, another_id)
False
"""
# For now, just iteratively go through the set and check if the current
# gate_identity is a permutation of an identity in the set
for an_id in identity_set:
if (gate_identity in an_id.equivalent_ids):
return True
return False
def is_reducible(circuit, nqubits, begin, end):
"""Determines if a circuit is reducible by checking
if its subcircuits are scalar values.
Parameters
==========
circuit : Gate tuple
A tuple of Gates representing a circuit. The circuit to check
if a gate identity is contained in a subcircuit.
nqubits : int
The number of qubits the circuit operates on.
begin : int
The leftmost gate in the circuit to include in a subcircuit.
end : int
The rightmost gate in the circuit to include in a subcircuit.
Examples
========
Check if the circuit can be reduced:
>>> from sympy.physics.quantum.identitysearch import is_reducible
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> is_reducible((x, y, z), 1, 0, 3)
True
Check if an interval in the circuit can be reduced:
>>> is_reducible((x, y, z), 1, 1, 3)
False
>>> is_reducible((x, y, y), 1, 1, 3)
True
"""
current_circuit = ()
# Start from the gate at "end" and go down to almost the gate at "begin"
for ndx in reversed(range(begin, end)):
next_gate = circuit[ndx]
current_circuit = (next_gate,) + current_circuit
# If a circuit as a matrix is equivalent to a scalar value
if (is_scalar_matrix(current_circuit, nqubits, False)):
return True
return False
def bfs_identity_search(gate_list, nqubits, max_depth=None,
identity_only=False):
"""Constructs a set of gate identities from the list of possible gates.
Performs a breadth first search over the space of gate identities.
This allows the finding of the shortest gate identities first.
Parameters
==========
gate_list : list, Gate
A list of Gates from which to search for gate identities.
nqubits : int
The number of qubits the quantum circuit operates on.
max_depth : int
The longest quantum circuit to construct from gate_list.
identity_only : bool
True to search for gate identities that reduce to identity;
False to search for gate identities that reduce to a scalar.
Examples
========
Find a list of gate identities:
>>> from sympy.physics.quantum.identitysearch import bfs_identity_search
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> bfs_identity_search([x], 1, max_depth=2)
{GateIdentity(X(0), X(0))}
>>> bfs_identity_search([x, y, z], 1)
{GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
GateIdentity(Z(0), Z(0)), GateIdentity(X(0), Y(0), Z(0))}
Find a list of identities that only equal to 1:
>>> bfs_identity_search([x, y, z], 1, identity_only=True)
{GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
GateIdentity(Z(0), Z(0))}
"""
if max_depth is None or max_depth <= 0:
max_depth = len(gate_list)
id_only = identity_only
# Start with an empty sequence (implicitly contains an IdentityGate)
queue = deque([()])
# Create an empty set of gate identities
ids = set()
# Begin searching for gate identities in given space.
while (len(queue) > 0):
current_circuit = queue.popleft()
for next_gate in gate_list:
new_circuit = current_circuit + (next_gate,)
# Determines if a (strict) subcircuit is a scalar matrix
circuit_reducible = is_reducible(new_circuit, nqubits,
1, len(new_circuit))
# In many cases when the matrix is a scalar value,
# the evaluated matrix will actually be an integer
if (is_scalar_matrix(new_circuit, nqubits, id_only) and
not is_degenerate(ids, new_circuit) and
not circuit_reducible):
ids.add(GateIdentity(*new_circuit))
elif (len(new_circuit) < max_depth and
not circuit_reducible):
queue.append(new_circuit)
return ids
def random_identity_search(gate_list, numgates, nqubits):
"""Randomly selects numgates from gate_list and checks if it is
a gate identity.
If the circuit is a gate identity, the circuit is returned;
Otherwise, None is returned.
"""
gate_size = len(gate_list)
circuit = ()
for i in range(numgates):
next_gate = gate_list[randint(0, gate_size - 1)]
circuit = circuit + (next_gate,)
is_scalar = is_scalar_matrix(circuit, nqubits, False)
return circuit if is_scalar else None
|
21256dc6642340bdbc9de01cbf22c30fa409b4b0053f0a2d081780acf983b857 | """Dirac notation for states."""
from sympy.core.cache import cacheit
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import Function
from sympy.core.numbers import oo, equal_valued
from sympy.core.singleton import S
from sympy.functions.elementary.complexes import conjugate
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.integrals.integrals import integrate
from sympy.printing.pretty.stringpict import stringPict
from sympy.physics.quantum.qexpr import QExpr, dispatch_method
__all__ = [
'KetBase',
'BraBase',
'StateBase',
'State',
'Ket',
'Bra',
'TimeDepState',
'TimeDepBra',
'TimeDepKet',
'OrthogonalKet',
'OrthogonalBra',
'OrthogonalState',
'Wavefunction'
]
#-----------------------------------------------------------------------------
# States, bras and kets.
#-----------------------------------------------------------------------------
# ASCII brackets
_lbracket = "<"
_rbracket = ">"
_straight_bracket = "|"
# Unicode brackets
# MATHEMATICAL ANGLE BRACKETS
_lbracket_ucode = "\N{MATHEMATICAL LEFT ANGLE BRACKET}"
_rbracket_ucode = "\N{MATHEMATICAL RIGHT ANGLE BRACKET}"
# LIGHT VERTICAL BAR
_straight_bracket_ucode = "\N{LIGHT VERTICAL BAR}"
# Other options for unicode printing of <, > and | for Dirac notation.
# LEFT-POINTING ANGLE BRACKET
# _lbracket = "\u2329"
# _rbracket = "\u232A"
# LEFT ANGLE BRACKET
# _lbracket = "\u3008"
# _rbracket = "\u3009"
# VERTICAL LINE
# _straight_bracket = "\u007C"
class StateBase(QExpr):
"""Abstract base class for general abstract states in quantum mechanics.
All other state classes defined will need to inherit from this class. It
carries the basic structure for all other states such as dual, _eval_adjoint
and label.
This is an abstract base class and you should not instantiate it directly,
instead use State.
"""
@classmethod
def _operators_to_state(self, ops, **options):
""" Returns the eigenstate instance for the passed operators.
This method should be overridden in subclasses. It will handle being
passed either an Operator instance or set of Operator instances. It
should return the corresponding state INSTANCE or simply raise a
NotImplementedError. See cartesian.py for an example.
"""
raise NotImplementedError("Cannot map operators to states in this class. Method not implemented!")
def _state_to_operators(self, op_classes, **options):
""" Returns the operators which this state instance is an eigenstate
of.
This method should be overridden in subclasses. It will be called on
state instances and be passed the operator classes that we wish to make
into instances. The state instance will then transform the classes
appropriately, or raise a NotImplementedError if it cannot return
operator instances. See cartesian.py for examples,
"""
raise NotImplementedError(
"Cannot map this state to operators. Method not implemented!")
@property
def operators(self):
"""Return the operator(s) that this state is an eigenstate of"""
from .operatorset import state_to_operators # import internally to avoid circular import errors
return state_to_operators(self)
def _enumerate_state(self, num_states, **options):
raise NotImplementedError("Cannot enumerate this state!")
def _represent_default_basis(self, **options):
return self._represent(basis=self.operators)
#-------------------------------------------------------------------------
# Dagger/dual
#-------------------------------------------------------------------------
@property
def dual(self):
"""Return the dual state of this one."""
return self.dual_class()._new_rawargs(self.hilbert_space, *self.args)
@classmethod
def dual_class(self):
"""Return the class used to construct the dual."""
raise NotImplementedError(
'dual_class must be implemented in a subclass'
)
def _eval_adjoint(self):
"""Compute the dagger of this state using the dual."""
return self.dual
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
def _pretty_brackets(self, height, use_unicode=True):
# Return pretty printed brackets for the state
# Ideally, this could be done by pform.parens but it does not support the angled < and >
# Setup for unicode vs ascii
if use_unicode:
lbracket, rbracket = getattr(self, 'lbracket_ucode', ""), getattr(self, 'rbracket_ucode', "")
slash, bslash, vert = '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT}', \
'\N{BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT}', \
'\N{BOX DRAWINGS LIGHT VERTICAL}'
else:
lbracket, rbracket = getattr(self, 'lbracket', ""), getattr(self, 'rbracket', "")
slash, bslash, vert = '/', '\\', '|'
# If height is 1, just return brackets
if height == 1:
return stringPict(lbracket), stringPict(rbracket)
# Make height even
height += (height % 2)
brackets = []
for bracket in lbracket, rbracket:
# Create left bracket
if bracket in {_lbracket, _lbracket_ucode}:
bracket_args = [ ' ' * (height//2 - i - 1) +
slash for i in range(height // 2)]
bracket_args.extend(
[' ' * i + bslash for i in range(height // 2)])
# Create right bracket
elif bracket in {_rbracket, _rbracket_ucode}:
bracket_args = [ ' ' * i + bslash for i in range(height // 2)]
bracket_args.extend([ ' ' * (
height//2 - i - 1) + slash for i in range(height // 2)])
# Create straight bracket
elif bracket in {_straight_bracket, _straight_bracket_ucode}:
bracket_args = [vert] * height
else:
raise ValueError(bracket)
brackets.append(
stringPict('\n'.join(bracket_args), baseline=height//2))
return brackets
def _sympystr(self, printer, *args):
contents = self._print_contents(printer, *args)
return '%s%s%s' % (getattr(self, 'lbracket', ""), contents, getattr(self, 'rbracket', ""))
def _pretty(self, printer, *args):
from sympy.printing.pretty.stringpict import prettyForm
# Get brackets
pform = self._print_contents_pretty(printer, *args)
lbracket, rbracket = self._pretty_brackets(
pform.height(), printer._use_unicode)
# Put together state
pform = prettyForm(*pform.left(lbracket))
pform = prettyForm(*pform.right(rbracket))
return pform
def _latex(self, printer, *args):
contents = self._print_contents_latex(printer, *args)
# The extra {} brackets are needed to get matplotlib's latex
# rendered to render this properly.
return '{%s%s%s}' % (getattr(self, 'lbracket_latex', ""), contents, getattr(self, 'rbracket_latex', ""))
class KetBase(StateBase):
"""Base class for Kets.
This class defines the dual property and the brackets for printing. This is
an abstract base class and you should not instantiate it directly, instead
use Ket.
"""
lbracket = _straight_bracket
rbracket = _rbracket
lbracket_ucode = _straight_bracket_ucode
rbracket_ucode = _rbracket_ucode
lbracket_latex = r'\left|'
rbracket_latex = r'\right\rangle '
@classmethod
def default_args(self):
return ("psi",)
@classmethod
def dual_class(self):
return BraBase
def __mul__(self, other):
"""KetBase*other"""
from sympy.physics.quantum.operator import OuterProduct
if isinstance(other, BraBase):
return OuterProduct(self, other)
else:
return Expr.__mul__(self, other)
def __rmul__(self, other):
"""other*KetBase"""
from sympy.physics.quantum.innerproduct import InnerProduct
if isinstance(other, BraBase):
return InnerProduct(other, self)
else:
return Expr.__rmul__(self, other)
#-------------------------------------------------------------------------
# _eval_* methods
#-------------------------------------------------------------------------
def _eval_innerproduct(self, bra, **hints):
"""Evaluate the inner product between this ket and a bra.
This is called to compute <bra|ket>, where the ket is ``self``.
This method will dispatch to sub-methods having the format::
``def _eval_innerproduct_BraClass(self, **hints):``
Subclasses should define these methods (one for each BraClass) to
teach the ket how to take inner products with bras.
"""
return dispatch_method(self, '_eval_innerproduct', bra, **hints)
def _apply_from_right_to(self, op, **options):
"""Apply an Operator to this Ket as Operator*Ket
This method will dispatch to methods having the format::
``def _apply_from_right_to_OperatorName(op, **options):``
Subclasses should define these methods (one for each OperatorName) to
teach the Ket how to implement OperatorName*Ket
Parameters
==========
op : Operator
The Operator that is acting on the Ket as op*Ket
options : dict
A dict of key/value pairs that control how the operator is applied
to the Ket.
"""
return dispatch_method(self, '_apply_from_right_to', op, **options)
class BraBase(StateBase):
"""Base class for Bras.
This class defines the dual property and the brackets for printing. This
is an abstract base class and you should not instantiate it directly,
instead use Bra.
"""
lbracket = _lbracket
rbracket = _straight_bracket
lbracket_ucode = _lbracket_ucode
rbracket_ucode = _straight_bracket_ucode
lbracket_latex = r'\left\langle '
rbracket_latex = r'\right|'
@classmethod
def _operators_to_state(self, ops, **options):
state = self.dual_class()._operators_to_state(ops, **options)
return state.dual
def _state_to_operators(self, op_classes, **options):
return self.dual._state_to_operators(op_classes, **options)
def _enumerate_state(self, num_states, **options):
dual_states = self.dual._enumerate_state(num_states, **options)
return [x.dual for x in dual_states]
@classmethod
def default_args(self):
return self.dual_class().default_args()
@classmethod
def dual_class(self):
return KetBase
def __mul__(self, other):
"""BraBase*other"""
from sympy.physics.quantum.innerproduct import InnerProduct
if isinstance(other, KetBase):
return InnerProduct(self, other)
else:
return Expr.__mul__(self, other)
def __rmul__(self, other):
"""other*BraBase"""
from sympy.physics.quantum.operator import OuterProduct
if isinstance(other, KetBase):
return OuterProduct(other, self)
else:
return Expr.__rmul__(self, other)
def _represent(self, **options):
"""A default represent that uses the Ket's version."""
from sympy.physics.quantum.dagger import Dagger
return Dagger(self.dual._represent(**options))
class State(StateBase):
"""General abstract quantum state used as a base class for Ket and Bra."""
pass
class Ket(State, KetBase):
"""A general time-independent Ket in quantum mechanics.
Inherits from State and KetBase. This class should be used as the base
class for all physical, time-independent Kets in a system. This class
and its subclasses will be the main classes that users will use for
expressing Kets in Dirac notation [1]_.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
ket. This will usually be its symbol or its quantum numbers. For
time-dependent state, this will include the time.
Examples
========
Create a simple Ket and looking at its properties::
>>> from sympy.physics.quantum import Ket
>>> from sympy import symbols, I
>>> k = Ket('psi')
>>> k
|psi>
>>> k.hilbert_space
H
>>> k.is_commutative
False
>>> k.label
(psi,)
Ket's know about their associated bra::
>>> k.dual
<psi|
>>> k.dual_class()
<class 'sympy.physics.quantum.state.Bra'>
Take a linear combination of two kets::
>>> k0 = Ket(0)
>>> k1 = Ket(1)
>>> 2*I*k0 - 4*k1
2*I*|0> - 4*|1>
Compound labels are passed as tuples::
>>> n, m = symbols('n,m')
>>> k = Ket(n,m)
>>> k
|nm>
References
==========
.. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
"""
@classmethod
def dual_class(self):
return Bra
class Bra(State, BraBase):
"""A general time-independent Bra in quantum mechanics.
Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This
class and its subclasses will be the main classes that users will use for
expressing Bras in Dirac notation.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
ket. This will usually be its symbol or its quantum numbers. For
time-dependent state, this will include the time.
Examples
========
Create a simple Bra and look at its properties::
>>> from sympy.physics.quantum import Bra
>>> from sympy import symbols, I
>>> b = Bra('psi')
>>> b
<psi|
>>> b.hilbert_space
H
>>> b.is_commutative
False
Bra's know about their dual Ket's::
>>> b.dual
|psi>
>>> b.dual_class()
<class 'sympy.physics.quantum.state.Ket'>
Like Kets, Bras can have compound labels and be manipulated in a similar
manner::
>>> n, m = symbols('n,m')
>>> b = Bra(n,m) - I*Bra(m,n)
>>> b
-I*<mn| + <nm|
Symbols in a Bra can be substituted using ``.subs``::
>>> b.subs(n,m)
<mm| - I*<mm|
References
==========
.. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
"""
@classmethod
def dual_class(self):
return Ket
#-----------------------------------------------------------------------------
# Time dependent states, bras and kets.
#-----------------------------------------------------------------------------
class TimeDepState(StateBase):
"""Base class for a general time-dependent quantum state.
This class is used as a base class for any time-dependent state. The main
difference between this class and the time-independent state is that this
class takes a second argument that is the time in addition to the usual
label argument.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket. This
will usually be its symbol or its quantum numbers. For time-dependent
state, this will include the time as the final argument.
"""
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def default_args(self):
return ("psi", "t")
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def label(self):
"""The label of the state."""
return self.args[:-1]
@property
def time(self):
"""The time of the state."""
return self.args[-1]
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
def _print_time(self, printer, *args):
return printer._print(self.time, *args)
_print_time_repr = _print_time
_print_time_latex = _print_time
def _print_time_pretty(self, printer, *args):
pform = printer._print(self.time, *args)
return pform
def _print_contents(self, printer, *args):
label = self._print_label(printer, *args)
time = self._print_time(printer, *args)
return '%s;%s' % (label, time)
def _print_label_repr(self, printer, *args):
label = self._print_sequence(self.label, ',', printer, *args)
time = self._print_time_repr(printer, *args)
return '%s,%s' % (label, time)
def _print_contents_pretty(self, printer, *args):
label = self._print_label_pretty(printer, *args)
time = self._print_time_pretty(printer, *args)
return printer._print_seq((label, time), delimiter=';')
def _print_contents_latex(self, printer, *args):
label = self._print_sequence(
self.label, self._label_separator, printer, *args)
time = self._print_time_latex(printer, *args)
return '%s;%s' % (label, time)
class TimeDepKet(TimeDepState, KetBase):
"""General time-dependent Ket in quantum mechanics.
This inherits from ``TimeDepState`` and ``KetBase`` and is the main class
that should be used for Kets that vary with time. Its dual is a
``TimeDepBra``.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket. This
will usually be its symbol or its quantum numbers. For time-dependent
state, this will include the time as the final argument.
Examples
========
Create a TimeDepKet and look at its attributes::
>>> from sympy.physics.quantum import TimeDepKet
>>> k = TimeDepKet('psi', 't')
>>> k
|psi;t>
>>> k.time
t
>>> k.label
(psi,)
>>> k.hilbert_space
H
TimeDepKets know about their dual bra::
>>> k.dual
<psi;t|
>>> k.dual_class()
<class 'sympy.physics.quantum.state.TimeDepBra'>
"""
@classmethod
def dual_class(self):
return TimeDepBra
class TimeDepBra(TimeDepState, BraBase):
"""General time-dependent Bra in quantum mechanics.
This inherits from TimeDepState and BraBase and is the main class that
should be used for Bras that vary with time. Its dual is a TimeDepBra.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket. This
will usually be its symbol or its quantum numbers. For time-dependent
state, this will include the time as the final argument.
Examples
========
>>> from sympy.physics.quantum import TimeDepBra
>>> b = TimeDepBra('psi', 't')
>>> b
<psi;t|
>>> b.time
t
>>> b.label
(psi,)
>>> b.hilbert_space
H
>>> b.dual
|psi;t>
"""
@classmethod
def dual_class(self):
return TimeDepKet
class OrthogonalState(State, StateBase):
"""General abstract quantum state used as a base class for Ket and Bra."""
pass
class OrthogonalKet(OrthogonalState, KetBase):
"""Orthogonal Ket in quantum mechanics.
The inner product of two states with different labels will give zero,
states with the same label will give one.
>>> from sympy.physics.quantum import OrthogonalBra, OrthogonalKet
>>> from sympy.abc import m, n
>>> (OrthogonalBra(n)*OrthogonalKet(n)).doit()
1
>>> (OrthogonalBra(n)*OrthogonalKet(n+1)).doit()
0
>>> (OrthogonalBra(n)*OrthogonalKet(m)).doit()
<n|m>
"""
@classmethod
def dual_class(self):
return OrthogonalBra
def _eval_innerproduct(self, bra, **hints):
if len(self.args) != len(bra.args):
raise ValueError('Cannot multiply a ket that has a different number of labels.')
for arg, bra_arg in zip(self.args, bra.args):
diff = arg - bra_arg
diff = diff.expand()
is_zero = diff.is_zero
if is_zero is False:
return S.Zero # i.e. Integer(0)
if is_zero is None:
return None
return S.One # i.e. Integer(1)
class OrthogonalBra(OrthogonalState, BraBase):
"""Orthogonal Bra in quantum mechanics.
"""
@classmethod
def dual_class(self):
return OrthogonalKet
class Wavefunction(Function):
"""Class for representations in continuous bases
This class takes an expression and coordinates in its constructor. It can
be used to easily calculate normalizations and probabilities.
Parameters
==========
expr : Expr
The expression representing the functional form of the w.f.
coords : Symbol or tuple
The coordinates to be integrated over, and their bounds
Examples
========
Particle in a box, specifying bounds in the more primitive way of using
Piecewise:
>>> from sympy import Symbol, Piecewise, pi, N
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x = Symbol('x', real=True)
>>> n = 1
>>> L = 1
>>> g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))
>>> f = Wavefunction(g, x)
>>> f.norm
1
>>> f.is_normalized
True
>>> p = f.prob()
>>> p(0)
0
>>> p(L)
0
>>> p(0.5)
2
>>> p(0.85*L)
2*sin(0.85*pi)**2
>>> N(p(0.85*L))
0.412214747707527
Additionally, you can specify the bounds of the function and the indices in
a more compact way:
>>> from sympy import symbols, pi, diff
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sqrt(2/L)*sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.norm
1
>>> f(L+1)
0
>>> f(L-1)
sqrt(2)*sin(pi*n*(L - 1)/L)/sqrt(L)
>>> f(-1)
0
>>> f(0.85)
sqrt(2)*sin(0.85*pi*n/L)/sqrt(L)
>>> f(0.85, n=1, L=1)
sqrt(2)*sin(0.85*pi)
>>> f.is_commutative
False
All arguments are automatically sympified, so you can define the variables
as strings rather than symbols:
>>> expr = x**2
>>> f = Wavefunction(expr, 'x')
>>> type(f.variables[0])
<class 'sympy.core.symbol.Symbol'>
Derivatives of Wavefunctions will return Wavefunctions:
>>> diff(f, x)
Wavefunction(2*x, x)
"""
#Any passed tuples for coordinates and their bounds need to be
#converted to Tuples before Function's constructor is called, to
#avoid errors from calling is_Float in the constructor
def __new__(cls, *args, **options):
new_args = [None for i in args]
ct = 0
for arg in args:
if isinstance(arg, tuple):
new_args[ct] = Tuple(*arg)
else:
new_args[ct] = arg
ct += 1
return super().__new__(cls, *new_args, **options)
def __call__(self, *args, **options):
var = self.variables
if len(args) != len(var):
raise NotImplementedError(
"Incorrect number of arguments to function!")
ct = 0
#If the passed value is outside the specified bounds, return 0
for v in var:
lower, upper = self.limits[v]
#Do the comparison to limits only if the passed symbol is actually
#a symbol present in the limits;
#Had problems with a comparison of x > L
if isinstance(args[ct], Expr) and \
not (lower in args[ct].free_symbols
or upper in args[ct].free_symbols):
continue
if (args[ct] < lower) == True or (args[ct] > upper) == True:
return S.Zero
ct += 1
expr = self.expr
#Allows user to make a call like f(2, 4, m=1, n=1)
for symbol in list(expr.free_symbols):
if str(symbol) in options.keys():
val = options[str(symbol)]
expr = expr.subs(symbol, val)
return expr.subs(zip(var, args))
def _eval_derivative(self, symbol):
expr = self.expr
deriv = expr._eval_derivative(symbol)
return Wavefunction(deriv, *self.args[1:])
def _eval_conjugate(self):
return Wavefunction(conjugate(self.expr), *self.args[1:])
def _eval_transpose(self):
return self
@property
def free_symbols(self):
return self.expr.free_symbols
@property
def is_commutative(self):
"""
Override Function's is_commutative so that order is preserved in
represented expressions
"""
return False
@classmethod
def eval(self, *args):
return None
@property
def variables(self):
"""
Return the coordinates which the wavefunction depends on
Examples
========
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy import symbols
>>> x,y = symbols('x,y')
>>> f = Wavefunction(x*y, x, y)
>>> f.variables
(x, y)
>>> g = Wavefunction(x*y, x)
>>> g.variables
(x,)
"""
var = [g[0] if isinstance(g, Tuple) else g for g in self._args[1:]]
return tuple(var)
@property
def limits(self):
"""
Return the limits of the coordinates which the w.f. depends on If no
limits are specified, defaults to ``(-oo, oo)``.
Examples
========
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy import symbols
>>> x, y = symbols('x, y')
>>> f = Wavefunction(x**2, (x, 0, 1))
>>> f.limits
{x: (0, 1)}
>>> f = Wavefunction(x**2, x)
>>> f.limits
{x: (-oo, oo)}
>>> f = Wavefunction(x**2 + y**2, x, (y, -1, 2))
>>> f.limits
{x: (-oo, oo), y: (-1, 2)}
"""
limits = [(g[1], g[2]) if isinstance(g, Tuple) else (-oo, oo)
for g in self._args[1:]]
return dict(zip(self.variables, tuple(limits)))
@property
def expr(self):
"""
Return the expression which is the functional form of the Wavefunction
Examples
========
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy import symbols
>>> x, y = symbols('x, y')
>>> f = Wavefunction(x**2, x)
>>> f.expr
x**2
"""
return self._args[0]
@property
def is_normalized(self):
"""
Returns true if the Wavefunction is properly normalized
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sqrt(2/L)*sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.is_normalized
True
"""
return equal_valued(self.norm, 1)
@property # type: ignore
@cacheit
def norm(self):
"""
Return the normalization of the specified functional form.
This function integrates over the coordinates of the Wavefunction, with
the bounds specified.
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sqrt(2/L)*sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.norm
1
>>> g = sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.norm
sqrt(2)*sqrt(L)/2
"""
exp = self.expr*conjugate(self.expr)
var = self.variables
limits = self.limits
for v in var:
curr_limits = limits[v]
exp = integrate(exp, (v, curr_limits[0], curr_limits[1]))
return sqrt(exp)
def normalize(self):
"""
Return a normalized version of the Wavefunction
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x = symbols('x', real=True)
>>> L = symbols('L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.normalize()
Wavefunction(sqrt(2)*sin(pi*n*x/L)/sqrt(L), (x, 0, L))
"""
const = self.norm
if const is oo:
raise NotImplementedError("The function is not normalizable!")
else:
return Wavefunction((const)**(-1)*self.expr, *self.args[1:])
def prob(self):
r"""
Return the absolute magnitude of the w.f., `|\psi(x)|^2`
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', real=True)
>>> n = symbols('n', integer=True)
>>> g = sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.prob()
Wavefunction(sin(pi*n*x/L)**2, x)
"""
return Wavefunction(self.expr*conjugate(self.expr), *self.variables)
|
cf13e8873ba8e07fef7aaa3f2e4c2cd6637998ab9f2a52b9259ae0a714170013 | """Quantum mechanical operators.
TODO:
* Fix early 0 in apply_operators.
* Debug and test apply_operators.
* Get cse working with classes in this file.
* Doctests and documentation of special methods for InnerProduct, Commutator,
AntiCommutator, represent, apply_operators.
"""
from sympy.core.add import Add
from sympy.core.expr import Expr
from sympy.core.function import (Derivative, expand)
from sympy.core.mul import Mul
from sympy.core.numbers import oo
from sympy.core.singleton import S
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.qexpr import QExpr, dispatch_method
from sympy.matrices import eye
__all__ = [
'Operator',
'HermitianOperator',
'UnitaryOperator',
'IdentityOperator',
'OuterProduct',
'DifferentialOperator'
]
#-----------------------------------------------------------------------------
# Operators and outer products
#-----------------------------------------------------------------------------
class Operator(QExpr):
"""Base class for non-commuting quantum operators.
An operator maps between quantum states [1]_. In quantum mechanics,
observables (including, but not limited to, measured physical values) are
represented as Hermitian operators [2]_.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
operator. For time-dependent operators, this will include the time.
Examples
========
Create an operator and examine its attributes::
>>> from sympy.physics.quantum import Operator
>>> from sympy import I
>>> A = Operator('A')
>>> A
A
>>> A.hilbert_space
H
>>> A.label
(A,)
>>> A.is_commutative
False
Create another operator and do some arithmetic operations::
>>> B = Operator('B')
>>> C = 2*A*A + I*B
>>> C
2*A**2 + I*B
Operators do not commute::
>>> A.is_commutative
False
>>> B.is_commutative
False
>>> A*B == B*A
False
Polymonials of operators respect the commutation properties::
>>> e = (A+B)**3
>>> e.expand()
A*B*A + A*B**2 + A**2*B + A**3 + B*A*B + B*A**2 + B**2*A + B**3
Operator inverses are handle symbolically::
>>> A.inv()
A**(-1)
>>> A*A.inv()
1
References
==========
.. [1] https://en.wikipedia.org/wiki/Operator_%28physics%29
.. [2] https://en.wikipedia.org/wiki/Observable
"""
@classmethod
def default_args(self):
return ("O",)
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
_label_separator = ','
def _print_operator_name(self, printer, *args):
return self.__class__.__name__
_print_operator_name_latex = _print_operator_name
def _print_operator_name_pretty(self, printer, *args):
return prettyForm(self.__class__.__name__)
def _print_contents(self, printer, *args):
if len(self.label) == 1:
return self._print_label(printer, *args)
else:
return '%s(%s)' % (
self._print_operator_name(printer, *args),
self._print_label(printer, *args)
)
def _print_contents_pretty(self, printer, *args):
if len(self.label) == 1:
return self._print_label_pretty(printer, *args)
else:
pform = self._print_operator_name_pretty(printer, *args)
label_pform = self._print_label_pretty(printer, *args)
label_pform = prettyForm(
*label_pform.parens(left='(', right=')')
)
pform = prettyForm(*pform.right(label_pform))
return pform
def _print_contents_latex(self, printer, *args):
if len(self.label) == 1:
return self._print_label_latex(printer, *args)
else:
return r'%s\left(%s\right)' % (
self._print_operator_name_latex(printer, *args),
self._print_label_latex(printer, *args)
)
#-------------------------------------------------------------------------
# _eval_* methods
#-------------------------------------------------------------------------
def _eval_commutator(self, other, **options):
"""Evaluate [self, other] if known, return None if not known."""
return dispatch_method(self, '_eval_commutator', other, **options)
def _eval_anticommutator(self, other, **options):
"""Evaluate [self, other] if known."""
return dispatch_method(self, '_eval_anticommutator', other, **options)
#-------------------------------------------------------------------------
# Operator application
#-------------------------------------------------------------------------
def _apply_operator(self, ket, **options):
return dispatch_method(self, '_apply_operator', ket, **options)
def matrix_element(self, *args):
raise NotImplementedError('matrix_elements is not defined')
def inverse(self):
return self._eval_inverse()
inv = inverse
def _eval_inverse(self):
return self**(-1)
def __mul__(self, other):
if isinstance(other, IdentityOperator):
return self
return Mul(self, other)
class HermitianOperator(Operator):
"""A Hermitian operator that satisfies H == Dagger(H).
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
operator. For time-dependent operators, this will include the time.
Examples
========
>>> from sympy.physics.quantum import Dagger, HermitianOperator
>>> H = HermitianOperator('H')
>>> Dagger(H)
H
"""
is_hermitian = True
def _eval_inverse(self):
if isinstance(self, UnitaryOperator):
return self
else:
return Operator._eval_inverse(self)
def _eval_power(self, exp):
if isinstance(self, UnitaryOperator):
# so all eigenvalues of self are 1 or -1
if exp.is_even:
from sympy.core.singleton import S
return S.One # is identity, see Issue 24153.
elif exp.is_odd:
return self
# No simplification in all other cases
return Operator._eval_power(self, exp)
class UnitaryOperator(Operator):
"""A unitary operator that satisfies U*Dagger(U) == 1.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
operator. For time-dependent operators, this will include the time.
Examples
========
>>> from sympy.physics.quantum import Dagger, UnitaryOperator
>>> U = UnitaryOperator('U')
>>> U*Dagger(U)
1
"""
def _eval_adjoint(self):
return self._eval_inverse()
class IdentityOperator(Operator):
"""An identity operator I that satisfies op * I == I * op == op for any
operator op.
Parameters
==========
N : Integer
Optional parameter that specifies the dimension of the Hilbert space
of operator. This is used when generating a matrix representation.
Examples
========
>>> from sympy.physics.quantum import IdentityOperator
>>> IdentityOperator()
I
"""
@property
def dimension(self):
return self.N
@classmethod
def default_args(self):
return (oo,)
def __init__(self, *args, **hints):
if not len(args) in (0, 1):
raise ValueError('0 or 1 parameters expected, got %s' % args)
self.N = args[0] if (len(args) == 1 and args[0]) else oo
def _eval_commutator(self, other, **hints):
return S.Zero
def _eval_anticommutator(self, other, **hints):
return 2 * other
def _eval_inverse(self):
return self
def _eval_adjoint(self):
return self
def _apply_operator(self, ket, **options):
return ket
def _apply_from_right_to(self, bra, **options):
return bra
def _eval_power(self, exp):
return self
def _print_contents(self, printer, *args):
return 'I'
def _print_contents_pretty(self, printer, *args):
return prettyForm('I')
def _print_contents_latex(self, printer, *args):
return r'{\mathcal{I}}'
def __mul__(self, other):
if isinstance(other, (Operator, Dagger)):
return other
return Mul(self, other)
def _represent_default_basis(self, **options):
if not self.N or self.N == oo:
raise NotImplementedError('Cannot represent infinite dimensional' +
' identity operator as a matrix')
format = options.get('format', 'sympy')
if format != 'sympy':
raise NotImplementedError('Representation in format ' +
'%s not implemented.' % format)
return eye(self.N)
class OuterProduct(Operator):
"""An unevaluated outer product between a ket and bra.
This constructs an outer product between any subclass of ``KetBase`` and
``BraBase`` as ``|a><b|``. An ``OuterProduct`` inherits from Operator as they act as
operators in quantum expressions. For reference see [1]_.
Parameters
==========
ket : KetBase
The ket on the left side of the outer product.
bar : BraBase
The bra on the right side of the outer product.
Examples
========
Create a simple outer product by hand and take its dagger::
>>> from sympy.physics.quantum import Ket, Bra, OuterProduct, Dagger
>>> from sympy.physics.quantum import Operator
>>> k = Ket('k')
>>> b = Bra('b')
>>> op = OuterProduct(k, b)
>>> op
|k><b|
>>> op.hilbert_space
H
>>> op.ket
|k>
>>> op.bra
<b|
>>> Dagger(op)
|b><k|
In simple products of kets and bras outer products will be automatically
identified and created::
>>> k*b
|k><b|
But in more complex expressions, outer products are not automatically
created::
>>> A = Operator('A')
>>> A*k*b
A*|k>*<b|
A user can force the creation of an outer product in a complex expression
by using parentheses to group the ket and bra::
>>> A*(k*b)
A*|k><b|
References
==========
.. [1] https://en.wikipedia.org/wiki/Outer_product
"""
is_commutative = False
def __new__(cls, *args, **old_assumptions):
from sympy.physics.quantum.state import KetBase, BraBase
if len(args) != 2:
raise ValueError('2 parameters expected, got %d' % len(args))
ket_expr = expand(args[0])
bra_expr = expand(args[1])
if (isinstance(ket_expr, (KetBase, Mul)) and
isinstance(bra_expr, (BraBase, Mul))):
ket_c, kets = ket_expr.args_cnc()
bra_c, bras = bra_expr.args_cnc()
if len(kets) != 1 or not isinstance(kets[0], KetBase):
raise TypeError('KetBase subclass expected'
', got: %r' % Mul(*kets))
if len(bras) != 1 or not isinstance(bras[0], BraBase):
raise TypeError('BraBase subclass expected'
', got: %r' % Mul(*bras))
if not kets[0].dual_class() == bras[0].__class__:
raise TypeError(
'ket and bra are not dual classes: %r, %r' %
(kets[0].__class__, bras[0].__class__)
)
# TODO: make sure the hilbert spaces of the bra and ket are
# compatible
obj = Expr.__new__(cls, *(kets[0], bras[0]), **old_assumptions)
obj.hilbert_space = kets[0].hilbert_space
return Mul(*(ket_c + bra_c)) * obj
op_terms = []
if isinstance(ket_expr, Add) and isinstance(bra_expr, Add):
for ket_term in ket_expr.args:
for bra_term in bra_expr.args:
op_terms.append(OuterProduct(ket_term, bra_term,
**old_assumptions))
elif isinstance(ket_expr, Add):
for ket_term in ket_expr.args:
op_terms.append(OuterProduct(ket_term, bra_expr,
**old_assumptions))
elif isinstance(bra_expr, Add):
for bra_term in bra_expr.args:
op_terms.append(OuterProduct(ket_expr, bra_term,
**old_assumptions))
else:
raise TypeError(
'Expected ket and bra expression, got: %r, %r' %
(ket_expr, bra_expr)
)
return Add(*op_terms)
@property
def ket(self):
"""Return the ket on the left side of the outer product."""
return self.args[0]
@property
def bra(self):
"""Return the bra on the right side of the outer product."""
return self.args[1]
def _eval_adjoint(self):
return OuterProduct(Dagger(self.bra), Dagger(self.ket))
def _sympystr(self, printer, *args):
return printer._print(self.ket) + printer._print(self.bra)
def _sympyrepr(self, printer, *args):
return '%s(%s,%s)' % (self.__class__.__name__,
printer._print(self.ket, *args), printer._print(self.bra, *args))
def _pretty(self, printer, *args):
pform = self.ket._pretty(printer, *args)
return prettyForm(*pform.right(self.bra._pretty(printer, *args)))
def _latex(self, printer, *args):
k = printer._print(self.ket, *args)
b = printer._print(self.bra, *args)
return k + b
def _represent(self, **options):
k = self.ket._represent(**options)
b = self.bra._represent(**options)
return k*b
def _eval_trace(self, **kwargs):
# TODO if operands are tensorproducts this may be will be handled
# differently.
return self.ket._eval_trace(self.bra, **kwargs)
class DifferentialOperator(Operator):
"""An operator for representing the differential operator, i.e. d/dx
It is initialized by passing two arguments. The first is an arbitrary
expression that involves a function, such as ``Derivative(f(x), x)``. The
second is the function (e.g. ``f(x)``) which we are to replace with the
``Wavefunction`` that this ``DifferentialOperator`` is applied to.
Parameters
==========
expr : Expr
The arbitrary expression which the appropriate Wavefunction is to be
substituted into
func : Expr
A function (e.g. f(x)) which is to be replaced with the appropriate
Wavefunction when this DifferentialOperator is applied
Examples
========
You can define a completely arbitrary expression and specify where the
Wavefunction is to be substituted
>>> from sympy import Derivative, Function, Symbol
>>> from sympy.physics.quantum.operator import DifferentialOperator
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy.physics.quantum.qapply import qapply
>>> f = Function('f')
>>> x = Symbol('x')
>>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
>>> w = Wavefunction(x**2, x)
>>> d.function
f(x)
>>> d.variables
(x,)
>>> qapply(d*w)
Wavefunction(2, x)
"""
@property
def variables(self):
"""
Returns the variables with which the function in the specified
arbitrary expression is evaluated
Examples
========
>>> from sympy.physics.quantum.operator import DifferentialOperator
>>> from sympy import Symbol, Function, Derivative
>>> x = Symbol('x')
>>> f = Function('f')
>>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
>>> d.variables
(x,)
>>> y = Symbol('y')
>>> d = DifferentialOperator(Derivative(f(x, y), x) +
... Derivative(f(x, y), y), f(x, y))
>>> d.variables
(x, y)
"""
return self.args[-1].args
@property
def function(self):
"""
Returns the function which is to be replaced with the Wavefunction
Examples
========
>>> from sympy.physics.quantum.operator import DifferentialOperator
>>> from sympy import Function, Symbol, Derivative
>>> x = Symbol('x')
>>> f = Function('f')
>>> d = DifferentialOperator(Derivative(f(x), x), f(x))
>>> d.function
f(x)
>>> y = Symbol('y')
>>> d = DifferentialOperator(Derivative(f(x, y), x) +
... Derivative(f(x, y), y), f(x, y))
>>> d.function
f(x, y)
"""
return self.args[-1]
@property
def expr(self):
"""
Returns the arbitrary expression which is to have the Wavefunction
substituted into it
Examples
========
>>> from sympy.physics.quantum.operator import DifferentialOperator
>>> from sympy import Function, Symbol, Derivative
>>> x = Symbol('x')
>>> f = Function('f')
>>> d = DifferentialOperator(Derivative(f(x), x), f(x))
>>> d.expr
Derivative(f(x), x)
>>> y = Symbol('y')
>>> d = DifferentialOperator(Derivative(f(x, y), x) +
... Derivative(f(x, y), y), f(x, y))
>>> d.expr
Derivative(f(x, y), x) + Derivative(f(x, y), y)
"""
return self.args[0]
@property
def free_symbols(self):
"""
Return the free symbols of the expression.
"""
return self.expr.free_symbols
def _apply_operator_Wavefunction(self, func, **options):
from sympy.physics.quantum.state import Wavefunction
var = self.variables
wf_vars = func.args[1:]
f = self.function
new_expr = self.expr.subs(f, func(*var))
new_expr = new_expr.doit()
return Wavefunction(new_expr, *wf_vars)
def _eval_derivative(self, symbol):
new_expr = Derivative(self.expr, symbol)
return DifferentialOperator(new_expr, self.args[-1])
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
def _print(self, printer, *args):
return '%s(%s)' % (
self._print_operator_name(printer, *args),
self._print_label(printer, *args)
)
def _print_pretty(self, printer, *args):
pform = self._print_operator_name_pretty(printer, *args)
label_pform = self._print_label_pretty(printer, *args)
label_pform = prettyForm(
*label_pform.parens(left='(', right=')')
)
pform = prettyForm(*pform.right(label_pform))
return pform
|
77538f7836c569b5183626a02ad706f0ed08bfdc81c5190df7e363f04fa0533d | """Matplotlib based plotting of quantum circuits.
Todo:
* Optimize printing of large circuits.
* Get this to work with single gates.
* Do a better job checking the form of circuits to make sure it is a Mul of
Gates.
* Get multi-target gates plotting.
* Get initial and final states to plot.
* Get measurements to plot. Might need to rethink measurement as a gate
issue.
* Get scale and figsize to be handled in a better way.
* Write some tests/examples!
"""
from __future__ import annotations
from sympy.core.mul import Mul
from sympy.external import import_module
from sympy.physics.quantum.gate import Gate, OneQubitGate, CGate, CGateS
from sympy.core.assumptions import ManagedProperties
__all__ = [
'CircuitPlot',
'circuit_plot',
'labeller',
'Mz',
'Mx',
'CreateOneQubitGate',
'CreateCGate',
]
np = import_module('numpy')
matplotlib = import_module(
'matplotlib', import_kwargs={'fromlist': ['pyplot']},
catch=(RuntimeError,)) # This is raised in environments that have no display.
if np and matplotlib:
pyplot = matplotlib.pyplot
Line2D = matplotlib.lines.Line2D
Circle = matplotlib.patches.Circle
#from matplotlib import rc
#rc('text',usetex=True)
class CircuitPlot:
"""A class for managing a circuit plot."""
scale = 1.0
fontsize = 20.0
linewidth = 1.0
control_radius = 0.05
not_radius = 0.15
swap_delta = 0.05
labels: list[str] = []
inits: dict[str, str] = {}
label_buffer = 0.5
def __init__(self, c, nqubits, **kwargs):
if not np or not matplotlib:
raise ImportError('numpy or matplotlib not available.')
self.circuit = c
self.ngates = len(self.circuit.args)
self.nqubits = nqubits
self.update(kwargs)
self._create_grid()
self._create_figure()
self._plot_wires()
self._plot_gates()
self._finish()
def update(self, kwargs):
"""Load the kwargs into the instance dict."""
self.__dict__.update(kwargs)
def _create_grid(self):
"""Create the grid of wires."""
scale = self.scale
wire_grid = np.arange(0.0, self.nqubits*scale, scale, dtype=float)
gate_grid = np.arange(0.0, self.ngates*scale, scale, dtype=float)
self._wire_grid = wire_grid
self._gate_grid = gate_grid
def _create_figure(self):
"""Create the main matplotlib figure."""
self._figure = pyplot.figure(
figsize=(self.ngates*self.scale, self.nqubits*self.scale),
facecolor='w',
edgecolor='w'
)
ax = self._figure.add_subplot(
1, 1, 1,
frameon=True
)
ax.set_axis_off()
offset = 0.5*self.scale
ax.set_xlim(self._gate_grid[0] - offset, self._gate_grid[-1] + offset)
ax.set_ylim(self._wire_grid[0] - offset, self._wire_grid[-1] + offset)
ax.set_aspect('equal')
self._axes = ax
def _plot_wires(self):
"""Plot the wires of the circuit diagram."""
xstart = self._gate_grid[0]
xstop = self._gate_grid[-1]
xdata = (xstart - self.scale, xstop + self.scale)
for i in range(self.nqubits):
ydata = (self._wire_grid[i], self._wire_grid[i])
line = Line2D(
xdata, ydata,
color='k',
lw=self.linewidth
)
self._axes.add_line(line)
if self.labels:
init_label_buffer = 0
if self.inits.get(self.labels[i]): init_label_buffer = 0.25
self._axes.text(
xdata[0]-self.label_buffer-init_label_buffer,ydata[0],
render_label(self.labels[i],self.inits),
size=self.fontsize,
color='k',ha='center',va='center')
self._plot_measured_wires()
def _plot_measured_wires(self):
ismeasured = self._measurements()
xstop = self._gate_grid[-1]
dy = 0.04 # amount to shift wires when doubled
# Plot doubled wires after they are measured
for im in ismeasured:
xdata = (self._gate_grid[ismeasured[im]],xstop+self.scale)
ydata = (self._wire_grid[im]+dy,self._wire_grid[im]+dy)
line = Line2D(
xdata, ydata,
color='k',
lw=self.linewidth
)
self._axes.add_line(line)
# Also double any controlled lines off these wires
for i,g in enumerate(self._gates()):
if isinstance(g, (CGate, CGateS)):
wires = g.controls + g.targets
for wire in wires:
if wire in ismeasured and \
self._gate_grid[i] > self._gate_grid[ismeasured[wire]]:
ydata = min(wires), max(wires)
xdata = self._gate_grid[i]-dy, self._gate_grid[i]-dy
line = Line2D(
xdata, ydata,
color='k',
lw=self.linewidth
)
self._axes.add_line(line)
def _gates(self):
"""Create a list of all gates in the circuit plot."""
gates = []
if isinstance(self.circuit, Mul):
for g in reversed(self.circuit.args):
if isinstance(g, Gate):
gates.append(g)
elif isinstance(self.circuit, Gate):
gates.append(self.circuit)
return gates
def _plot_gates(self):
"""Iterate through the gates and plot each of them."""
for i, gate in enumerate(self._gates()):
gate.plot_gate(self, i)
def _measurements(self):
"""Return a dict ``{i:j}`` where i is the index of the wire that has
been measured, and j is the gate where the wire is measured.
"""
ismeasured = {}
for i,g in enumerate(self._gates()):
if getattr(g,'measurement',False):
for target in g.targets:
if target in ismeasured:
if ismeasured[target] > i:
ismeasured[target] = i
else:
ismeasured[target] = i
return ismeasured
def _finish(self):
# Disable clipping to make panning work well for large circuits.
for o in self._figure.findobj():
o.set_clip_on(False)
def one_qubit_box(self, t, gate_idx, wire_idx):
"""Draw a box for a single qubit gate."""
x = self._gate_grid[gate_idx]
y = self._wire_grid[wire_idx]
self._axes.text(
x, y, t,
color='k',
ha='center',
va='center',
bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth),
size=self.fontsize
)
def two_qubit_box(self, t, gate_idx, wire_idx):
"""Draw a box for a two qubit gate. Does not work yet.
"""
# x = self._gate_grid[gate_idx]
# y = self._wire_grid[wire_idx]+0.5
print(self._gate_grid)
print(self._wire_grid)
# unused:
# obj = self._axes.text(
# x, y, t,
# color='k',
# ha='center',
# va='center',
# bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth),
# size=self.fontsize
# )
def control_line(self, gate_idx, min_wire, max_wire):
"""Draw a vertical control line."""
xdata = (self._gate_grid[gate_idx], self._gate_grid[gate_idx])
ydata = (self._wire_grid[min_wire], self._wire_grid[max_wire])
line = Line2D(
xdata, ydata,
color='k',
lw=self.linewidth
)
self._axes.add_line(line)
def control_point(self, gate_idx, wire_idx):
"""Draw a control point."""
x = self._gate_grid[gate_idx]
y = self._wire_grid[wire_idx]
radius = self.control_radius
c = Circle(
(x, y),
radius*self.scale,
ec='k',
fc='k',
fill=True,
lw=self.linewidth
)
self._axes.add_patch(c)
def not_point(self, gate_idx, wire_idx):
"""Draw a NOT gates as the circle with plus in the middle."""
x = self._gate_grid[gate_idx]
y = self._wire_grid[wire_idx]
radius = self.not_radius
c = Circle(
(x, y),
radius,
ec='k',
fc='w',
fill=False,
lw=self.linewidth
)
self._axes.add_patch(c)
l = Line2D(
(x, x), (y - radius, y + radius),
color='k',
lw=self.linewidth
)
self._axes.add_line(l)
def swap_point(self, gate_idx, wire_idx):
"""Draw a swap point as a cross."""
x = self._gate_grid[gate_idx]
y = self._wire_grid[wire_idx]
d = self.swap_delta
l1 = Line2D(
(x - d, x + d),
(y - d, y + d),
color='k',
lw=self.linewidth
)
l2 = Line2D(
(x - d, x + d),
(y + d, y - d),
color='k',
lw=self.linewidth
)
self._axes.add_line(l1)
self._axes.add_line(l2)
def circuit_plot(c, nqubits, **kwargs):
"""Draw the circuit diagram for the circuit with nqubits.
Parameters
==========
c : circuit
The circuit to plot. Should be a product of Gate instances.
nqubits : int
The number of qubits to include in the circuit. Must be at least
as big as the largest ``min_qubits`` of the gates.
"""
return CircuitPlot(c, nqubits, **kwargs)
def render_label(label, inits={}):
"""Slightly more flexible way to render labels.
>>> from sympy.physics.quantum.circuitplot import render_label
>>> render_label('q0')
'$\\\\left|q0\\\\right\\\\rangle$'
>>> render_label('q0', {'q0':'0'})
'$\\\\left|q0\\\\right\\\\rangle=\\\\left|0\\\\right\\\\rangle$'
"""
init = inits.get(label)
if init:
return r'$\left|%s\right\rangle=\left|%s\right\rangle$' % (label, init)
return r'$\left|%s\right\rangle$' % label
def labeller(n, symbol='q'):
"""Autogenerate labels for wires of quantum circuits.
Parameters
==========
n : int
number of qubits in the circuit.
symbol : string
A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc.
>>> from sympy.physics.quantum.circuitplot import labeller
>>> labeller(2)
['q_1', 'q_0']
>>> labeller(3,'j')
['j_2', 'j_1', 'j_0']
"""
return ['%s_%d' % (symbol,n-i-1) for i in range(n)]
class Mz(OneQubitGate):
"""Mock-up of a z measurement gate.
This is in circuitplot rather than gate.py because it's not a real
gate, it just draws one.
"""
measurement = True
gate_name='Mz'
gate_name_latex='M_z'
class Mx(OneQubitGate):
"""Mock-up of an x measurement gate.
This is in circuitplot rather than gate.py because it's not a real
gate, it just draws one.
"""
measurement = True
gate_name='Mx'
gate_name_latex='M_x'
class CreateOneQubitGate(ManagedProperties):
def __new__(mcl, name, latexname=None):
if not latexname:
latexname = name
return ManagedProperties.__new__(
mcl, name + "Gate", (OneQubitGate,),
{'gate_name': name, 'gate_name_latex': latexname})
def CreateCGate(name, latexname=None):
"""Use a lexical closure to make a controlled gate.
"""
if not latexname:
latexname = name
onequbitgate = CreateOneQubitGate(name, latexname)
def ControlledGate(ctrls,target):
return CGate(tuple(ctrls),onequbitgate(target))
return ControlledGate
|
b32d8dde8cec15aa21df0df5f1dbeca75caf0a53212f767a43c7d44dcef6f4cc | from sympy.utilities import dict_merge
from sympy.utilities.iterables import iterable
from sympy.physics.vector import (Dyadic, Vector, ReferenceFrame,
Point, dynamicsymbols)
from sympy.physics.vector.printing import (vprint, vsprint, vpprint, vlatex,
init_vprinting)
from sympy.physics.mechanics.particle import Particle
from sympy.physics.mechanics.rigidbody import RigidBody
from sympy.simplify.simplify import simplify
from sympy.core.backend import (Matrix, sympify, Mul, Derivative, sin, cos,
tan, AppliedUndef, S)
__all__ = ['inertia',
'inertia_of_point_mass',
'linear_momentum',
'angular_momentum',
'kinetic_energy',
'potential_energy',
'Lagrangian',
'mechanics_printing',
'mprint',
'msprint',
'mpprint',
'mlatex',
'msubs',
'find_dynamicsymbols']
# These are functions that we've moved and renamed during extracting the
# basic vector calculus code from the mechanics packages.
mprint = vprint
msprint = vsprint
mpprint = vpprint
mlatex = vlatex
def mechanics_printing(**kwargs):
"""
Initializes time derivative printing for all SymPy objects in
mechanics module.
"""
init_vprinting(**kwargs)
mechanics_printing.__doc__ = init_vprinting.__doc__
def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0):
"""Simple way to create inertia Dyadic object.
Explanation
===========
If you do not know what a Dyadic is, just treat this like the inertia
tensor. Then, do the easy thing and define it in a body-fixed frame.
Parameters
==========
frame : ReferenceFrame
The frame the inertia is defined in
ixx : Sympifyable
the xx element in the inertia dyadic
iyy : Sympifyable
the yy element in the inertia dyadic
izz : Sympifyable
the zz element in the inertia dyadic
ixy : Sympifyable
the xy element in the inertia dyadic
iyz : Sympifyable
the yz element in the inertia dyadic
izx : Sympifyable
the zx element in the inertia dyadic
Examples
========
>>> from sympy.physics.mechanics import ReferenceFrame, inertia
>>> N = ReferenceFrame('N')
>>> inertia(N, 1, 2, 3)
(N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z)
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Need to define the inertia in a frame')
ixx = sympify(ixx)
ixy = sympify(ixy)
iyy = sympify(iyy)
iyz = sympify(iyz)
izx = sympify(izx)
izz = sympify(izz)
ol = ixx * (frame.x | frame.x)
ol += ixy * (frame.x | frame.y)
ol += izx * (frame.x | frame.z)
ol += ixy * (frame.y | frame.x)
ol += iyy * (frame.y | frame.y)
ol += iyz * (frame.y | frame.z)
ol += izx * (frame.z | frame.x)
ol += iyz * (frame.z | frame.y)
ol += izz * (frame.z | frame.z)
return ol
def inertia_of_point_mass(mass, pos_vec, frame):
"""Inertia dyadic of a point mass relative to point O.
Parameters
==========
mass : Sympifyable
Mass of the point mass
pos_vec : Vector
Position from point O to point mass
frame : ReferenceFrame
Reference frame to express the dyadic in
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass
>>> N = ReferenceFrame('N')
>>> r, m = symbols('r m')
>>> px = r * N.x
>>> inertia_of_point_mass(m, px, N)
m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z)
"""
return mass * (((frame.x | frame.x) + (frame.y | frame.y) +
(frame.z | frame.z)) * (pos_vec & pos_vec) -
(pos_vec | pos_vec))
def linear_momentum(frame, *body):
"""Linear momentum of the system.
Explanation
===========
This function returns the linear momentum of a system of Particle's and/or
RigidBody's. The linear momentum of a system is equal to the vector sum of
the linear momentum of its constituents. Consider a system, S, comprised of
a rigid body, A, and a particle, P. The linear momentum of the system, L,
is equal to the vector sum of the linear momentum of the particle, L1, and
the linear momentum of the rigid body, L2, i.e.
L = L1 + L2
Parameters
==========
frame : ReferenceFrame
The frame in which linear momentum is desired.
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose linear momentum is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, linear_momentum
>>> N = ReferenceFrame('N')
>>> P = Point('P')
>>> P.set_vel(N, 10 * N.x)
>>> Pa = Particle('Pa', P, 1)
>>> Ac = Point('Ac')
>>> Ac.set_vel(N, 25 * N.y)
>>> I = outer(N.x, N.x)
>>> A = RigidBody('A', Ac, N, 20, (I, Ac))
>>> linear_momentum(N, A, Pa)
10*N.x + 500*N.y
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Please specify a valid ReferenceFrame')
else:
linear_momentum_sys = Vector(0)
for e in body:
if isinstance(e, (RigidBody, Particle)):
linear_momentum_sys += e.linear_momentum(frame)
else:
raise TypeError('*body must have only Particle or RigidBody')
return linear_momentum_sys
def angular_momentum(point, frame, *body):
"""Angular momentum of a system.
Explanation
===========
This function returns the angular momentum of a system of Particle's and/or
RigidBody's. The angular momentum of such a system is equal to the vector
sum of the angular momentum of its constituents. Consider a system, S,
comprised of a rigid body, A, and a particle, P. The angular momentum of
the system, H, is equal to the vector sum of the angular momentum of the
particle, H1, and the angular momentum of the rigid body, H2, i.e.
H = H1 + H2
Parameters
==========
point : Point
The point about which angular momentum of the system is desired.
frame : ReferenceFrame
The frame in which angular momentum is desired.
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose angular momentum is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, angular_momentum
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> O.set_vel(N, 0 * N.x)
>>> P = O.locatenew('P', 1 * N.x)
>>> P.set_vel(N, 10 * N.x)
>>> Pa = Particle('Pa', P, 1)
>>> Ac = O.locatenew('Ac', 2 * N.y)
>>> Ac.set_vel(N, 5 * N.y)
>>> a = ReferenceFrame('a')
>>> a.set_ang_vel(N, 10 * N.z)
>>> I = outer(N.z, N.z)
>>> A = RigidBody('A', Ac, a, 20, (I, Ac))
>>> angular_momentum(O, N, Pa, A)
10*N.z
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Please enter a valid ReferenceFrame')
if not isinstance(point, Point):
raise TypeError('Please specify a valid Point')
else:
angular_momentum_sys = Vector(0)
for e in body:
if isinstance(e, (RigidBody, Particle)):
angular_momentum_sys += e.angular_momentum(point, frame)
else:
raise TypeError('*body must have only Particle or RigidBody')
return angular_momentum_sys
def kinetic_energy(frame, *body):
"""Kinetic energy of a multibody system.
Explanation
===========
This function returns the kinetic energy of a system of Particle's and/or
RigidBody's. The kinetic energy of such a system is equal to the sum of
the kinetic energies of its constituents. Consider a system, S, comprising
a rigid body, A, and a particle, P. The kinetic energy of the system, T,
is equal to the vector sum of the kinetic energy of the particle, T1, and
the kinetic energy of the rigid body, T2, i.e.
T = T1 + T2
Kinetic energy is a scalar.
Parameters
==========
frame : ReferenceFrame
The frame in which the velocity or angular velocity of the body is
defined.
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose kinetic energy is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, kinetic_energy
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> O.set_vel(N, 0 * N.x)
>>> P = O.locatenew('P', 1 * N.x)
>>> P.set_vel(N, 10 * N.x)
>>> Pa = Particle('Pa', P, 1)
>>> Ac = O.locatenew('Ac', 2 * N.y)
>>> Ac.set_vel(N, 5 * N.y)
>>> a = ReferenceFrame('a')
>>> a.set_ang_vel(N, 10 * N.z)
>>> I = outer(N.z, N.z)
>>> A = RigidBody('A', Ac, a, 20, (I, Ac))
>>> kinetic_energy(N, Pa, A)
350
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Please enter a valid ReferenceFrame')
ke_sys = S.Zero
for e in body:
if isinstance(e, (RigidBody, Particle)):
ke_sys += e.kinetic_energy(frame)
else:
raise TypeError('*body must have only Particle or RigidBody')
return ke_sys
def potential_energy(*body):
"""Potential energy of a multibody system.
Explanation
===========
This function returns the potential energy of a system of Particle's and/or
RigidBody's. The potential energy of such a system is equal to the sum of
the potential energy of its constituents. Consider a system, S, comprising
a rigid body, A, and a particle, P. The potential energy of the system, V,
is equal to the vector sum of the potential energy of the particle, V1, and
the potential energy of the rigid body, V2, i.e.
V = V1 + V2
Potential energy is a scalar.
Parameters
==========
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose potential energy is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, potential_energy
>>> from sympy import symbols
>>> M, m, g, h = symbols('M m g h')
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> O.set_vel(N, 0 * N.x)
>>> P = O.locatenew('P', 1 * N.x)
>>> Pa = Particle('Pa', P, m)
>>> Ac = O.locatenew('Ac', 2 * N.y)
>>> a = ReferenceFrame('a')
>>> I = outer(N.z, N.z)
>>> A = RigidBody('A', Ac, a, M, (I, Ac))
>>> Pa.potential_energy = m * g * h
>>> A.potential_energy = M * g * h
>>> potential_energy(Pa, A)
M*g*h + g*h*m
"""
pe_sys = S.Zero
for e in body:
if isinstance(e, (RigidBody, Particle)):
pe_sys += e.potential_energy
else:
raise TypeError('*body must have only Particle or RigidBody')
return pe_sys
def gravity(acceleration, *bodies):
"""
Returns a list of gravity forces given the acceleration
due to gravity and any number of particles or rigidbodies.
Example
=======
>>> from sympy.physics.mechanics import ReferenceFrame, Point, Particle, outer, RigidBody
>>> from sympy.physics.mechanics.functions import gravity
>>> from sympy import symbols
>>> N = ReferenceFrame('N')
>>> m, M, g = symbols('m M g')
>>> F1, F2 = symbols('F1 F2')
>>> po = Point('po')
>>> pa = Particle('pa', po, m)
>>> A = ReferenceFrame('A')
>>> P = Point('P')
>>> I = outer(A.x, A.x)
>>> B = RigidBody('B', P, A, M, (I, P))
>>> forceList = [(po, F1), (P, F2)]
>>> forceList.extend(gravity(g*N.y, pa, B))
>>> forceList
[(po, F1), (P, F2), (po, g*m*N.y), (P, M*g*N.y)]
"""
gravity_force = []
if not bodies:
raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.")
for e in bodies:
point = getattr(e, 'masscenter', None)
if point is None:
point = e.point
gravity_force.append((point, e.mass*acceleration))
return gravity_force
def center_of_mass(point, *bodies):
"""
Returns the position vector from the given point to the center of mass
of the given bodies(particles or rigidbodies).
Example
=======
>>> from sympy import symbols, S
>>> from sympy.physics.vector import Point
>>> from sympy.physics.mechanics import Particle, ReferenceFrame, RigidBody, outer
>>> from sympy.physics.mechanics.functions import center_of_mass
>>> a = ReferenceFrame('a')
>>> m = symbols('m', real=True)
>>> p1 = Particle('p1', Point('p1_pt'), S(1))
>>> p2 = Particle('p2', Point('p2_pt'), S(2))
>>> p3 = Particle('p3', Point('p3_pt'), S(3))
>>> p4 = Particle('p4', Point('p4_pt'), m)
>>> b_f = ReferenceFrame('b_f')
>>> b_cm = Point('b_cm')
>>> mb = symbols('mb')
>>> b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm))
>>> p2.point.set_pos(p1.point, a.x)
>>> p3.point.set_pos(p1.point, a.x + a.y)
>>> p4.point.set_pos(p1.point, a.y)
>>> b.masscenter.set_pos(p1.point, a.y + a.z)
>>> point_o=Point('o')
>>> point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b))
>>> expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
>>> point_o.pos_from(p1.point)
5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
"""
if not bodies:
raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.")
total_mass = 0
vec = Vector(0)
for i in bodies:
total_mass += i.mass
masscenter = getattr(i, 'masscenter', None)
if masscenter is None:
masscenter = i.point
vec += i.mass*masscenter.pos_from(point)
return vec/total_mass
def Lagrangian(frame, *body):
"""Lagrangian of a multibody system.
Explanation
===========
This function returns the Lagrangian of a system of Particle's and/or
RigidBody's. The Lagrangian of such a system is equal to the difference
between the kinetic energies and potential energies of its constituents. If
T and V are the kinetic and potential energies of a system then it's
Lagrangian, L, is defined as
L = T - V
The Lagrangian is a scalar.
Parameters
==========
frame : ReferenceFrame
The frame in which the velocity or angular velocity of the body is
defined to determine the kinetic energy.
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose Lagrangian is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, Lagrangian
>>> from sympy import symbols
>>> M, m, g, h = symbols('M m g h')
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> O.set_vel(N, 0 * N.x)
>>> P = O.locatenew('P', 1 * N.x)
>>> P.set_vel(N, 10 * N.x)
>>> Pa = Particle('Pa', P, 1)
>>> Ac = O.locatenew('Ac', 2 * N.y)
>>> Ac.set_vel(N, 5 * N.y)
>>> a = ReferenceFrame('a')
>>> a.set_ang_vel(N, 10 * N.z)
>>> I = outer(N.z, N.z)
>>> A = RigidBody('A', Ac, a, 20, (I, Ac))
>>> Pa.potential_energy = m * g * h
>>> A.potential_energy = M * g * h
>>> Lagrangian(N, Pa, A)
-M*g*h - g*h*m + 350
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Please supply a valid ReferenceFrame')
for e in body:
if not isinstance(e, (RigidBody, Particle)):
raise TypeError('*body must have only Particle or RigidBody')
return kinetic_energy(frame, *body) - potential_energy(*body)
def find_dynamicsymbols(expression, exclude=None, reference_frame=None):
"""Find all dynamicsymbols in expression.
Explanation
===========
If the optional ``exclude`` kwarg is used, only dynamicsymbols
not in the iterable ``exclude`` are returned.
If we intend to apply this function on a vector, the optional
``reference_frame`` is also used to inform about the corresponding frame
with respect to which the dynamic symbols of the given vector is to be
determined.
Parameters
==========
expression : SymPy expression
exclude : iterable of dynamicsymbols, optional
reference_frame : ReferenceFrame, optional
The frame with respect to which the dynamic symbols of the
given vector is to be determined.
Examples
========
>>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols
>>> from sympy.physics.mechanics import ReferenceFrame
>>> x, y = dynamicsymbols('x, y')
>>> expr = x + x.diff()*y
>>> find_dynamicsymbols(expr)
{x(t), y(t), Derivative(x(t), t)}
>>> find_dynamicsymbols(expr, exclude=[x, y])
{Derivative(x(t), t)}
>>> a, b, c = dynamicsymbols('a, b, c')
>>> A = ReferenceFrame('A')
>>> v = a * A.x + b * A.y + c * A.z
>>> find_dynamicsymbols(v, reference_frame=A)
{a(t), b(t), c(t)}
"""
t_set = {dynamicsymbols._t}
if exclude:
if iterable(exclude):
exclude_set = set(exclude)
else:
raise TypeError("exclude kwarg must be iterable")
else:
exclude_set = set()
if isinstance(expression, Vector):
if reference_frame is None:
raise ValueError("You must provide reference_frame when passing a "
"vector expression, got %s." % reference_frame)
else:
expression = expression.to_matrix(reference_frame)
return {i for i in expression.atoms(AppliedUndef, Derivative) if
i.free_symbols == t_set} - exclude_set
def msubs(expr, *sub_dicts, smart=False, **kwargs):
"""A custom subs for use on expressions derived in physics.mechanics.
Traverses the expression tree once, performing the subs found in sub_dicts.
Terms inside ``Derivative`` expressions are ignored:
Examples
========
>>> from sympy.physics.mechanics import dynamicsymbols, msubs
>>> x = dynamicsymbols('x')
>>> msubs(x.diff() + x, {x: 1})
Derivative(x(t), t) + 1
Note that sub_dicts can be a single dictionary, or several dictionaries:
>>> x, y, z = dynamicsymbols('x, y, z')
>>> sub1 = {x: 1, y: 2}
>>> sub2 = {z: 3, x.diff(): 4}
>>> msubs(x.diff() + x + y + z, sub1, sub2)
10
If smart=True (default False), also checks for conditions that may result
in ``nan``, but if simplified would yield a valid expression. For example:
>>> from sympy import sin, tan
>>> (sin(x)/tan(x)).subs(x, 0)
nan
>>> msubs(sin(x)/tan(x), {x: 0}, smart=True)
1
It does this by first replacing all ``tan`` with ``sin/cos``. Then each
node is traversed. If the node is a fraction, subs is first evaluated on
the denominator. If this results in 0, simplification of the entire
fraction is attempted. Using this selective simplification, only
subexpressions that result in 1/0 are targeted, resulting in faster
performance.
"""
sub_dict = dict_merge(*sub_dicts)
if smart:
func = _smart_subs
elif hasattr(expr, 'msubs'):
return expr.msubs(sub_dict)
else:
func = lambda expr, sub_dict: _crawl(expr, _sub_func, sub_dict)
if isinstance(expr, (Matrix, Vector, Dyadic)):
return expr.applyfunc(lambda x: func(x, sub_dict))
else:
return func(expr, sub_dict)
def _crawl(expr, func, *args, **kwargs):
"""Crawl the expression tree, and apply func to every node."""
val = func(expr, *args, **kwargs)
if val is not None:
return val
new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args)
return expr.func(*new_args)
def _sub_func(expr, sub_dict):
"""Perform direct matching substitution, ignoring derivatives."""
if expr in sub_dict:
return sub_dict[expr]
elif not expr.args or expr.is_Derivative:
return expr
def _tan_repl_func(expr):
"""Replace tan with sin/cos."""
if isinstance(expr, tan):
return sin(*expr.args) / cos(*expr.args)
elif not expr.args or expr.is_Derivative:
return expr
def _smart_subs(expr, sub_dict):
"""Performs subs, checking for conditions that may result in `nan` or
`oo`, and attempts to simplify them out.
The expression tree is traversed twice, and the following steps are
performed on each expression node:
- First traverse:
Replace all `tan` with `sin/cos`.
- Second traverse:
If node is a fraction, check if the denominator evaluates to 0.
If so, attempt to simplify it out. Then if node is in sub_dict,
sub in the corresponding value.
"""
expr = _crawl(expr, _tan_repl_func)
def _recurser(expr, sub_dict):
# Decompose the expression into num, den
num, den = _fraction_decomp(expr)
if den != 1:
# If there is a non trivial denominator, we need to handle it
denom_subbed = _recurser(den, sub_dict)
if denom_subbed.evalf() == 0:
# If denom is 0 after this, attempt to simplify the bad expr
expr = simplify(expr)
else:
# Expression won't result in nan, find numerator
num_subbed = _recurser(num, sub_dict)
return num_subbed / denom_subbed
# We have to crawl the tree manually, because `expr` may have been
# modified in the simplify step. First, perform subs as normal:
val = _sub_func(expr, sub_dict)
if val is not None:
return val
new_args = (_recurser(arg, sub_dict) for arg in expr.args)
return expr.func(*new_args)
return _recurser(expr, sub_dict)
def _fraction_decomp(expr):
"""Return num, den such that expr = num/den."""
if not isinstance(expr, Mul):
return expr, 1
num = []
den = []
for a in expr.args:
if a.is_Pow and a.args[1] < 0:
den.append(1 / a)
else:
num.append(a)
if not den:
return expr, 1
num = Mul(*num)
den = Mul(*den)
return num, den
def _f_list_parser(fl, ref_frame):
"""Parses the provided forcelist composed of items
of the form (obj, force).
Returns a tuple containing:
vel_list: The velocity (ang_vel for Frames, vel for Points) in
the provided reference frame.
f_list: The forces.
Used internally in the KanesMethod and LagrangesMethod classes.
"""
def flist_iter():
for pair in fl:
obj, force = pair
if isinstance(obj, ReferenceFrame):
yield obj.ang_vel_in(ref_frame), force
elif isinstance(obj, Point):
yield obj.vel(ref_frame), force
else:
raise TypeError('First entry in each forcelist pair must '
'be a point or frame.')
if not fl:
vel_list, f_list = (), ()
else:
unzip = lambda l: list(zip(*l)) if l[0] else [(), ()]
vel_list, f_list = unzip(list(flist_iter()))
return vel_list, f_list
def _validate_coordinates(coordinates=None, speeds=None, check_duplicates=True,
is_dynamicsymbols=True):
t_set = {dynamicsymbols._t}
# Convert input to iterables
if coordinates is None:
coordinates = []
elif not iterable(coordinates):
coordinates = [coordinates]
if speeds is None:
speeds = []
elif not iterable(speeds):
speeds = [speeds]
if check_duplicates: # Check for duplicates
if len(coordinates) != len(set(coordinates)):
raise ValueError('Duplicate generalized coordinates found, all '
'generalized coordinates should be unique.')
if len(speeds) != len(set(speeds)):
raise ValueError('Duplicate generalized speeds found, all '
'generalized speeds should be unique.')
if is_dynamicsymbols: # Check whether all coordinates are dynamicsymbols
for coordinate in coordinates:
if not (isinstance(coordinate, (AppliedUndef, Derivative)) and
coordinate.free_symbols == t_set):
raise ValueError(f'Generalized coordinate "{coordinate}" is not'
f' a dynamicsymbol.')
for speed in speeds:
if not (isinstance(speed, (AppliedUndef, Derivative)) and
speed.free_symbols == t_set):
raise ValueError(f'Generalized speed "{speed}" is not a '
f'dynamicsymbol.')
|
16671c5bce36f492df83df86c5ce2879e92b3e2da283bee0619276c7ba95ccc0 | from sympy.physics.mechanics import (Body, Lagrangian, KanesMethod, LagrangesMethod,
RigidBody, Particle)
from sympy.physics.mechanics.method import _Methods
from sympy.core.backend import Matrix
__all__ = ['JointsMethod']
class JointsMethod(_Methods):
"""Method for formulating the equations of motion using a set of interconnected bodies with joints.
Parameters
==========
newtonion : Body or ReferenceFrame
The newtonion(inertial) frame.
*joints : Joint
The joints in the system
Attributes
==========
q, u : iterable
Iterable of the generalized coordinates and speeds
bodies : iterable
Iterable of Body objects in the system.
loads : iterable
Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
describing the forces on the system.
mass_matrix : Matrix, shape(n, n)
The system's mass matrix
forcing : Matrix, shape(n, 1)
The system's forcing vector
mass_matrix_full : Matrix, shape(2*n, 2*n)
The "mass matrix" for the u's and q's
forcing_full : Matrix, shape(2*n, 1)
The "forcing vector" for the u's and q's
method : KanesMethod or Lagrange's method
Method's object.
kdes : iterable
Iterable of kde in they system.
Examples
========
This is a simple example for a one degree of freedom translational
spring-mass-damper.
>>> from sympy import symbols
>>> from sympy.physics.mechanics import Body, JointsMethod, PrismaticJoint
>>> from sympy.physics.vector import dynamicsymbols
>>> c, k = symbols('c k')
>>> x, v = dynamicsymbols('x v')
>>> wall = Body('W')
>>> body = Body('B')
>>> J = PrismaticJoint('J', wall, body, coordinates=x, speeds=v)
>>> wall.apply_force(c*v*wall.x, reaction_body=body)
>>> wall.apply_force(k*x*wall.x, reaction_body=body)
>>> method = JointsMethod(wall, J)
>>> method.form_eoms()
Matrix([[-B_mass*Derivative(v(t), t) - c*v(t) - k*x(t)]])
>>> M = method.mass_matrix_full
>>> F = method.forcing_full
>>> rhs = M.LUsolve(F)
>>> rhs
Matrix([
[ v(t)],
[(-c*v(t) - k*x(t))/B_mass]])
Notes
=====
``JointsMethod`` currently only works with systems that do not have any
configuration or motion constraints.
"""
def __init__(self, newtonion, *joints):
if isinstance(newtonion, Body):
self.frame = newtonion.frame
else:
self.frame = newtonion
self._joints = joints
self._bodies = self._generate_bodylist()
self._loads = self._generate_loadlist()
self._q = self._generate_q()
self._u = self._generate_u()
self._kdes = self._generate_kdes()
self._method = None
@property
def bodies(self):
"""List of bodies in they system."""
return self._bodies
@property
def loads(self):
"""List of loads on the system."""
return self._loads
@property
def q(self):
"""List of the generalized coordinates."""
return self._q
@property
def u(self):
"""List of the generalized speeds."""
return self._u
@property
def kdes(self):
"""List of the generalized coordinates."""
return self._kdes
@property
def forcing_full(self):
"""The "forcing vector" for the u's and q's."""
return self.method.forcing_full
@property
def mass_matrix_full(self):
"""The "mass matrix" for the u's and q's."""
return self.method.mass_matrix_full
@property
def mass_matrix(self):
"""The system's mass matrix."""
return self.method.mass_matrix
@property
def forcing(self):
"""The system's forcing vector."""
return self.method.forcing
@property
def method(self):
"""Object of method used to form equations of systems."""
return self._method
def _generate_bodylist(self):
bodies = []
for joint in self._joints:
if joint.child not in bodies:
bodies.append(joint.child)
if joint.parent not in bodies:
bodies.append(joint.parent)
return bodies
def _generate_loadlist(self):
load_list = []
for body in self.bodies:
load_list.extend(body.loads)
return load_list
def _generate_q(self):
q_ind = []
for joint in self._joints:
for coordinate in joint.coordinates:
if coordinate in q_ind:
raise ValueError('Coordinates of joints should be unique.')
q_ind.append(coordinate)
return Matrix(q_ind)
def _generate_u(self):
u_ind = []
for joint in self._joints:
for speed in joint.speeds:
if speed in u_ind:
raise ValueError('Speeds of joints should be unique.')
u_ind.append(speed)
return Matrix(u_ind)
def _generate_kdes(self):
kd_ind = Matrix(1, 0, []).T
for joint in self._joints:
kd_ind = kd_ind.col_join(joint.kdes)
return kd_ind
def _convert_bodies(self):
# Convert `Body` to `Particle` and `RigidBody`
bodylist = []
for body in self.bodies:
if body.is_rigidbody:
rb = RigidBody(body.name, body.masscenter, body.frame, body.mass,
(body.central_inertia, body.masscenter))
rb.potential_energy = body.potential_energy
bodylist.append(rb)
else:
part = Particle(body.name, body.masscenter, body.mass)
part.potential_energy = body.potential_energy
bodylist.append(part)
return bodylist
def form_eoms(self, method=KanesMethod):
"""Method to form system's equation of motions.
Parameters
==========
method : Class
Class name of method.
Returns
========
Matrix
Vector of equations of motions.
Examples
========
This is a simple example for a one degree of freedom translational
spring-mass-damper.
>>> from sympy import S, symbols
>>> from sympy.physics.mechanics import LagrangesMethod, dynamicsymbols, Body
>>> from sympy.physics.mechanics import PrismaticJoint, JointsMethod
>>> q = dynamicsymbols('q')
>>> qd = dynamicsymbols('q', 1)
>>> m, k, b = symbols('m k b')
>>> wall = Body('W')
>>> part = Body('P', mass=m)
>>> part.potential_energy = k * q**2 / S(2)
>>> J = PrismaticJoint('J', wall, part, coordinates=q, speeds=qd)
>>> wall.apply_force(b * qd * wall.x, reaction_body=part)
>>> method = JointsMethod(wall, J)
>>> method.form_eoms(LagrangesMethod)
Matrix([[b*Derivative(q(t), t) + k*q(t) + m*Derivative(q(t), (t, 2))]])
We can also solve for the states using the 'rhs' method.
>>> method.rhs()
Matrix([
[ Derivative(q(t), t)],
[(-b*Derivative(q(t), t) - k*q(t))/m]])
"""
bodylist = self._convert_bodies()
if issubclass(method, LagrangesMethod): #LagrangesMethod or similar
L = Lagrangian(self.frame, *bodylist)
self._method = method(L, self.q, self.loads, bodylist, self.frame)
else: #KanesMethod or similar
self._method = method(self.frame, q_ind=self.q, u_ind=self.u, kd_eqs=self.kdes,
forcelist=self.loads, bodies=bodylist)
soln = self.method._form_eoms()
return soln
def rhs(self, inv_method=None):
"""Returns equations that can be solved numerically.
Parameters
==========
inv_method : str
The specific sympy inverse matrix calculation method to use. For a
list of valid methods, see
:meth:`~sympy.matrices.matrices.MatrixBase.inv`
Returns
========
Matrix
Numerically solvable equations.
See Also
========
sympy.physics.mechanics.kane.KanesMethod.rhs:
KanesMethod's rhs function.
sympy.physics.mechanics.lagrange.LagrangesMethod.rhs:
LagrangesMethod's rhs function.
"""
return self.method.rhs(inv_method=inv_method)
|
0d5bd6cbda8d466ef8d8d146701a726c5636d192b7054ec358d6cb3135d8885a | # isort:skip_file
"""
Dimensional analysis and unit systems.
This module defines dimension/unit systems and physical quantities. It is
based on a group-theoretical construction where dimensions are represented as
vectors (coefficients being the exponents), and units are defined as a dimension
to which we added a scale.
Quantities are built from a factor and a unit, and are the basic objects that
one will use when doing computations.
All objects except systems and prefixes can be used in SymPy expressions.
Note that as part of a CAS, various objects do not combine automatically
under operations.
Details about the implementation can be found in the documentation, and we
will not repeat all the explanations we gave there concerning our approach.
Ideas about future developments can be found on the `Github wiki
<https://github.com/sympy/sympy/wiki/Unit-systems>`_, and you should consult
this page if you are willing to help.
Useful functions:
- ``find_unit``: easily lookup pre-defined units.
- ``convert_to(expr, newunit)``: converts an expression into the same
expression expressed in another unit.
"""
from .dimensions import Dimension, DimensionSystem
from .unitsystem import UnitSystem
from .util import convert_to
from .quantities import Quantity
from .definitions.dimension_definitions import (
amount_of_substance, acceleration, action, area,
capacitance, charge, conductance, current, energy,
force, frequency, impedance, inductance, length,
luminous_intensity, magnetic_density,
magnetic_flux, mass, momentum, power, pressure, temperature, time,
velocity, voltage, volume
)
Unit = Quantity
speed = velocity
luminosity = luminous_intensity
magnetic_flux_density = magnetic_density
amount = amount_of_substance
from .prefixes import (
# 10-power based:
yotta,
zetta,
exa,
peta,
tera,
giga,
mega,
kilo,
hecto,
deca,
deci,
centi,
milli,
micro,
nano,
pico,
femto,
atto,
zepto,
yocto,
# 2-power based:
kibi,
mebi,
gibi,
tebi,
pebi,
exbi,
)
from .definitions import (
percent, percents,
permille,
rad, radian, radians,
deg, degree, degrees,
sr, steradian, steradians,
mil, angular_mil, angular_mils,
m, meter, meters,
kg, kilogram, kilograms,
s, second, seconds,
A, ampere, amperes,
K, kelvin, kelvins,
mol, mole, moles,
cd, candela, candelas,
g, gram, grams,
mg, milligram, milligrams,
ug, microgram, micrograms,
t, tonne, metric_ton,
newton, newtons, N,
joule, joules, J,
watt, watts, W,
pascal, pascals, Pa, pa,
hertz, hz, Hz,
coulomb, coulombs, C,
volt, volts, v, V,
ohm, ohms,
siemens, S, mho, mhos,
farad, farads, F,
henry, henrys, H,
tesla, teslas, T,
weber, webers, Wb, wb,
optical_power, dioptre, D,
lux, lx,
katal, kat,
gray, Gy,
becquerel, Bq,
km, kilometer, kilometers,
dm, decimeter, decimeters,
cm, centimeter, centimeters,
mm, millimeter, millimeters,
um, micrometer, micrometers, micron, microns,
nm, nanometer, nanometers,
pm, picometer, picometers,
ft, foot, feet,
inch, inches,
yd, yard, yards,
mi, mile, miles,
nmi, nautical_mile, nautical_miles,
angstrom, angstroms,
ha, hectare,
l, L, liter, liters,
dl, dL, deciliter, deciliters,
cl, cL, centiliter, centiliters,
ml, mL, milliliter, milliliters,
ms, millisecond, milliseconds,
us, microsecond, microseconds,
ns, nanosecond, nanoseconds,
ps, picosecond, picoseconds,
minute, minutes,
h, hour, hours,
day, days,
anomalistic_year, anomalistic_years,
sidereal_year, sidereal_years,
tropical_year, tropical_years,
common_year, common_years,
julian_year, julian_years,
draconic_year, draconic_years,
gaussian_year, gaussian_years,
full_moon_cycle, full_moon_cycles,
year, years,
G, gravitational_constant,
c, speed_of_light,
elementary_charge,
hbar,
planck,
eV, electronvolt, electronvolts,
avogadro_number,
avogadro, avogadro_constant,
boltzmann, boltzmann_constant,
stefan, stefan_boltzmann_constant,
R, molar_gas_constant,
faraday_constant,
josephson_constant,
von_klitzing_constant,
Da, dalton, amu, amus, atomic_mass_unit, atomic_mass_constant,
me, electron_rest_mass,
gee, gees, acceleration_due_to_gravity,
u0, magnetic_constant, vacuum_permeability,
e0, electric_constant, vacuum_permittivity,
Z0, vacuum_impedance,
coulomb_constant, electric_force_constant,
atmosphere, atmospheres, atm,
kPa,
bar, bars,
pound, pounds,
psi,
dHg0,
mmHg, torr,
mmu, mmus, milli_mass_unit,
quart, quarts,
ly, lightyear, lightyears,
au, astronomical_unit, astronomical_units,
planck_mass,
planck_time,
planck_temperature,
planck_length,
planck_charge,
planck_area,
planck_volume,
planck_momentum,
planck_energy,
planck_force,
planck_power,
planck_density,
planck_energy_density,
planck_intensity,
planck_angular_frequency,
planck_pressure,
planck_current,
planck_voltage,
planck_impedance,
planck_acceleration,
bit, bits,
byte,
kibibyte, kibibytes,
mebibyte, mebibytes,
gibibyte, gibibytes,
tebibyte, tebibytes,
pebibyte, pebibytes,
exbibyte, exbibytes,
)
from .systems import (
mks, mksa, si
)
def find_unit(quantity, unit_system="SI"):
"""
Return a list of matching units or dimension names.
- If ``quantity`` is a string -- units/dimensions containing the string
`quantity`.
- If ``quantity`` is a unit or dimension -- units having matching base
units or dimensions.
Examples
========
>>> from sympy.physics import units as u
>>> u.find_unit('charge')
['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
>>> u.find_unit(u.charge)
['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
>>> u.find_unit("ampere")
['ampere', 'amperes']
>>> u.find_unit('angstrom')
['angstrom', 'angstroms']
>>> u.find_unit('volt')
['volt', 'volts', 'electronvolt', 'electronvolts', 'planck_voltage']
>>> u.find_unit(u.inch**3)[:9]
['L', 'l', 'cL', 'cl', 'dL', 'dl', 'mL', 'ml', 'liter']
"""
unit_system = UnitSystem.get_unit_system(unit_system)
import sympy.physics.units as u
rv = []
if isinstance(quantity, str):
rv = [i for i in dir(u) if quantity in i and isinstance(getattr(u, i), Quantity)]
dim = getattr(u, quantity)
if isinstance(dim, Dimension):
rv.extend(find_unit(dim))
else:
for i in sorted(dir(u)):
other = getattr(u, i)
if not isinstance(other, Quantity):
continue
if isinstance(quantity, Quantity):
if quantity.dimension == other.dimension:
rv.append(str(i))
elif isinstance(quantity, Dimension):
if other.dimension == quantity:
rv.append(str(i))
elif other.dimension == Dimension(unit_system.get_dimensional_expr(quantity)):
rv.append(str(i))
return sorted(set(rv), key=lambda x: (len(x), x))
# NOTE: the old units module had additional variables:
# 'density', 'illuminance', 'resistance'.
# They were not dimensions, but units (old Unit class).
__all__ = [
'Dimension', 'DimensionSystem',
'UnitSystem',
'convert_to',
'Quantity',
'amount_of_substance', 'acceleration', 'action', 'area',
'capacitance', 'charge', 'conductance', 'current', 'energy',
'force', 'frequency', 'impedance', 'inductance', 'length',
'luminous_intensity', 'magnetic_density',
'magnetic_flux', 'mass', 'momentum', 'power', 'pressure', 'temperature', 'time',
'velocity', 'voltage', 'volume',
'Unit',
'speed',
'luminosity',
'magnetic_flux_density',
'amount',
'yotta',
'zetta',
'exa',
'peta',
'tera',
'giga',
'mega',
'kilo',
'hecto',
'deca',
'deci',
'centi',
'milli',
'micro',
'nano',
'pico',
'femto',
'atto',
'zepto',
'yocto',
'kibi',
'mebi',
'gibi',
'tebi',
'pebi',
'exbi',
'percent', 'percents',
'permille',
'rad', 'radian', 'radians',
'deg', 'degree', 'degrees',
'sr', 'steradian', 'steradians',
'mil', 'angular_mil', 'angular_mils',
'm', 'meter', 'meters',
'kg', 'kilogram', 'kilograms',
's', 'second', 'seconds',
'A', 'ampere', 'amperes',
'K', 'kelvin', 'kelvins',
'mol', 'mole', 'moles',
'cd', 'candela', 'candelas',
'g', 'gram', 'grams',
'mg', 'milligram', 'milligrams',
'ug', 'microgram', 'micrograms',
't', 'tonne', 'metric_ton',
'newton', 'newtons', 'N',
'joule', 'joules', 'J',
'watt', 'watts', 'W',
'pascal', 'pascals', 'Pa', 'pa',
'hertz', 'hz', 'Hz',
'coulomb', 'coulombs', 'C',
'volt', 'volts', 'v', 'V',
'ohm', 'ohms',
'siemens', 'S', 'mho', 'mhos',
'farad', 'farads', 'F',
'henry', 'henrys', 'H',
'tesla', 'teslas', 'T',
'weber', 'webers', 'Wb', 'wb',
'optical_power', 'dioptre', 'D',
'lux', 'lx',
'katal', 'kat',
'gray', 'Gy',
'becquerel', 'Bq',
'km', 'kilometer', 'kilometers',
'dm', 'decimeter', 'decimeters',
'cm', 'centimeter', 'centimeters',
'mm', 'millimeter', 'millimeters',
'um', 'micrometer', 'micrometers', 'micron', 'microns',
'nm', 'nanometer', 'nanometers',
'pm', 'picometer', 'picometers',
'ft', 'foot', 'feet',
'inch', 'inches',
'yd', 'yard', 'yards',
'mi', 'mile', 'miles',
'nmi', 'nautical_mile', 'nautical_miles',
'angstrom', 'angstroms',
'ha', 'hectare',
'l', 'L', 'liter', 'liters',
'dl', 'dL', 'deciliter', 'deciliters',
'cl', 'cL', 'centiliter', 'centiliters',
'ml', 'mL', 'milliliter', 'milliliters',
'ms', 'millisecond', 'milliseconds',
'us', 'microsecond', 'microseconds',
'ns', 'nanosecond', 'nanoseconds',
'ps', 'picosecond', 'picoseconds',
'minute', 'minutes',
'h', 'hour', 'hours',
'day', 'days',
'anomalistic_year', 'anomalistic_years',
'sidereal_year', 'sidereal_years',
'tropical_year', 'tropical_years',
'common_year', 'common_years',
'julian_year', 'julian_years',
'draconic_year', 'draconic_years',
'gaussian_year', 'gaussian_years',
'full_moon_cycle', 'full_moon_cycles',
'year', 'years',
'G', 'gravitational_constant',
'c', 'speed_of_light',
'elementary_charge',
'hbar',
'planck',
'eV', 'electronvolt', 'electronvolts',
'avogadro_number',
'avogadro', 'avogadro_constant',
'boltzmann', 'boltzmann_constant',
'stefan', 'stefan_boltzmann_constant',
'R', 'molar_gas_constant',
'faraday_constant',
'josephson_constant',
'von_klitzing_constant',
'Da', 'dalton', 'amu', 'amus', 'atomic_mass_unit', 'atomic_mass_constant',
'me', 'electron_rest_mass',
'gee', 'gees', 'acceleration_due_to_gravity',
'u0', 'magnetic_constant', 'vacuum_permeability',
'e0', 'electric_constant', 'vacuum_permittivity',
'Z0', 'vacuum_impedance',
'coulomb_constant', 'electric_force_constant',
'atmosphere', 'atmospheres', 'atm',
'kPa',
'bar', 'bars',
'pound', 'pounds',
'psi',
'dHg0',
'mmHg', 'torr',
'mmu', 'mmus', 'milli_mass_unit',
'quart', 'quarts',
'ly', 'lightyear', 'lightyears',
'au', 'astronomical_unit', 'astronomical_units',
'planck_mass',
'planck_time',
'planck_temperature',
'planck_length',
'planck_charge',
'planck_area',
'planck_volume',
'planck_momentum',
'planck_energy',
'planck_force',
'planck_power',
'planck_density',
'planck_energy_density',
'planck_intensity',
'planck_angular_frequency',
'planck_pressure',
'planck_current',
'planck_voltage',
'planck_impedance',
'planck_acceleration',
'bit', 'bits',
'byte',
'kibibyte', 'kibibytes',
'mebibyte', 'mebibytes',
'gibibyte', 'gibibytes',
'tebibyte', 'tebibytes',
'pebibyte', 'pebibytes',
'exbibyte', 'exbibytes',
'mks', 'mksa', 'si',
]
|
0768d3ec112cc82499994c47e9162b3fd81519e5cb9f49cb860313f6014e0d6e | """
Definition of physical dimensions.
Unit systems will be constructed on top of these dimensions.
Most of the examples in the doc use MKS system and are presented from the
computer point of view: from a human point, adding length to time is not legal
in MKS but it is in natural system; for a computer in natural system there is
no time dimension (but a velocity dimension instead) - in the basis - so the
question of adding time to length has no meaning.
"""
from __future__ import annotations
import collections
from functools import reduce
from sympy.core.basic import Basic
from sympy.core.containers import (Dict, Tuple)
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.matrices.dense import Matrix
from sympy.functions.elementary.trigonometric import TrigonometricFunction
from sympy.core.expr import Expr
from sympy.core.power import Pow
class _QuantityMapper:
_quantity_scale_factors_global: dict[Expr, Expr] = {}
_quantity_dimensional_equivalence_map_global: dict[Expr, Expr] = {}
_quantity_dimension_global: dict[Expr, Expr] = {}
def __init__(self, *args, **kwargs):
self._quantity_dimension_map = {}
self._quantity_scale_factors = {}
def set_quantity_dimension(self, quantity, dimension):
"""
Set the dimension for the quantity in a unit system.
If this relation is valid in every unit system, use
``quantity.set_global_dimension(dimension)`` instead.
"""
from sympy.physics.units import Quantity
dimension = sympify(dimension)
if not isinstance(dimension, Dimension):
if dimension == 1:
dimension = Dimension(1)
else:
raise ValueError("expected dimension or 1")
elif isinstance(dimension, Quantity):
dimension = self.get_quantity_dimension(dimension)
self._quantity_dimension_map[quantity] = dimension
def set_quantity_scale_factor(self, quantity, scale_factor):
"""
Set the scale factor of a quantity relative to another quantity.
It should be used only once per quantity to just one other quantity,
the algorithm will then be able to compute the scale factors to all
other quantities.
In case the scale factor is valid in every unit system, please use
``quantity.set_global_relative_scale_factor(scale_factor)`` instead.
"""
from sympy.physics.units import Quantity
from sympy.physics.units.prefixes import Prefix
scale_factor = sympify(scale_factor)
# replace all prefixes by their ratio to canonical units:
scale_factor = scale_factor.replace(
lambda x: isinstance(x, Prefix),
lambda x: x.scale_factor
)
# replace all quantities by their ratio to canonical units:
scale_factor = scale_factor.replace(
lambda x: isinstance(x, Quantity),
lambda x: self.get_quantity_scale_factor(x)
)
self._quantity_scale_factors[quantity] = scale_factor
def get_quantity_dimension(self, unit):
from sympy.physics.units import Quantity
# First look-up the local dimension map, then the global one:
if unit in self._quantity_dimension_map:
return self._quantity_dimension_map[unit]
if unit in self._quantity_dimension_global:
return self._quantity_dimension_global[unit]
if unit in self._quantity_dimensional_equivalence_map_global:
dep_unit = self._quantity_dimensional_equivalence_map_global[unit]
if isinstance(dep_unit, Quantity):
return self.get_quantity_dimension(dep_unit)
else:
return Dimension(self.get_dimensional_expr(dep_unit))
if isinstance(unit, Quantity):
return Dimension(unit.name)
else:
return Dimension(1)
def get_quantity_scale_factor(self, unit):
if unit in self._quantity_scale_factors:
return self._quantity_scale_factors[unit]
if unit in self._quantity_scale_factors_global:
mul_factor, other_unit = self._quantity_scale_factors_global[unit]
return mul_factor*self.get_quantity_scale_factor(other_unit)
return S.One
class Dimension(Expr):
"""
This class represent the dimension of a physical quantities.
The ``Dimension`` constructor takes as parameters a name and an optional
symbol.
For example, in classical mechanics we know that time is different from
temperature and dimensions make this difference (but they do not provide
any measure of these quantites.
>>> from sympy.physics.units import Dimension
>>> length = Dimension('length')
>>> length
Dimension(length)
>>> time = Dimension('time')
>>> time
Dimension(time)
Dimensions can be composed using multiplication, division and
exponentiation (by a number) to give new dimensions. Addition and
subtraction is defined only when the two objects are the same dimension.
>>> velocity = length / time
>>> velocity
Dimension(length/time)
It is possible to use a dimension system object to get the dimensionsal
dependencies of a dimension, for example the dimension system used by the
SI units convention can be used:
>>> from sympy.physics.units.systems.si import dimsys_SI
>>> dimsys_SI.get_dimensional_dependencies(velocity)
{Dimension(length, L): 1, Dimension(time, T): -1}
>>> length + length
Dimension(length)
>>> l2 = length**2
>>> l2
Dimension(length**2)
>>> dimsys_SI.get_dimensional_dependencies(l2)
{Dimension(length, L): 2}
"""
_op_priority = 13.0
# XXX: This doesn't seem to be used anywhere...
_dimensional_dependencies = {} # type: ignore
is_commutative = True
is_number = False
# make sqrt(M**2) --> M
is_positive = True
is_real = True
def __new__(cls, name, symbol=None):
if isinstance(name, str):
name = Symbol(name)
else:
name = sympify(name)
if not isinstance(name, Expr):
raise TypeError("Dimension name needs to be a valid math expression")
if isinstance(symbol, str):
symbol = Symbol(symbol)
elif symbol is not None:
assert isinstance(symbol, Symbol)
obj = Expr.__new__(cls, name)
obj._name = name
obj._symbol = symbol
return obj
@property
def name(self):
return self._name
@property
def symbol(self):
return self._symbol
def __str__(self):
"""
Display the string representation of the dimension.
"""
if self.symbol is None:
return "Dimension(%s)" % (self.name)
else:
return "Dimension(%s, %s)" % (self.name, self.symbol)
def __repr__(self):
return self.__str__()
def __neg__(self):
return self
def __add__(self, other):
from sympy.physics.units.quantities import Quantity
other = sympify(other)
if isinstance(other, Basic):
if other.has(Quantity):
raise TypeError("cannot sum dimension and quantity")
if isinstance(other, Dimension) and self == other:
return self
return super().__add__(other)
return self
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
# there is no notion of ordering (or magnitude) among dimension,
# subtraction is equivalent to addition when the operation is legal
return self + other
def __rsub__(self, other):
# there is no notion of ordering (or magnitude) among dimension,
# subtraction is equivalent to addition when the operation is legal
return self + other
def __pow__(self, other):
return self._eval_power(other)
def _eval_power(self, other):
other = sympify(other)
return Dimension(self.name**other)
def __mul__(self, other):
from sympy.physics.units.quantities import Quantity
if isinstance(other, Basic):
if other.has(Quantity):
raise TypeError("cannot sum dimension and quantity")
if isinstance(other, Dimension):
return Dimension(self.name*other.name)
if not other.free_symbols: # other.is_number cannot be used
return self
return super().__mul__(other)
return self
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
return self*Pow(other, -1)
def __rtruediv__(self, other):
return other * pow(self, -1)
@classmethod
def _from_dimensional_dependencies(cls, dependencies):
return reduce(lambda x, y: x * y, (
d**e for d, e in dependencies.items()
), 1)
def has_integer_powers(self, dim_sys):
"""
Check if the dimension object has only integer powers.
All the dimension powers should be integers, but rational powers may
appear in intermediate steps. This method may be used to check that the
final result is well-defined.
"""
return all(dpow.is_Integer for dpow in dim_sys.get_dimensional_dependencies(self).values())
# Create dimensions according to the base units in MKSA.
# For other unit systems, they can be derived by transforming the base
# dimensional dependency dictionary.
class DimensionSystem(Basic, _QuantityMapper):
r"""
DimensionSystem represents a coherent set of dimensions.
The constructor takes three parameters:
- base dimensions;
- derived dimensions: these are defined in terms of the base dimensions
(for example velocity is defined from the division of length by time);
- dependency of dimensions: how the derived dimensions depend
on the base dimensions.
Optionally either the ``derived_dims`` or the ``dimensional_dependencies``
may be omitted.
"""
def __new__(cls, base_dims, derived_dims=(), dimensional_dependencies={}):
dimensional_dependencies = dict(dimensional_dependencies)
def parse_dim(dim):
if isinstance(dim, str):
dim = Dimension(Symbol(dim))
elif isinstance(dim, Dimension):
pass
elif isinstance(dim, Symbol):
dim = Dimension(dim)
else:
raise TypeError("%s wrong type" % dim)
return dim
base_dims = [parse_dim(i) for i in base_dims]
derived_dims = [parse_dim(i) for i in derived_dims]
for dim in base_dims:
if (dim in dimensional_dependencies
and (len(dimensional_dependencies[dim]) != 1 or
dimensional_dependencies[dim].get(dim, None) != 1)):
raise IndexError("Repeated value in base dimensions")
dimensional_dependencies[dim] = Dict({dim: 1})
def parse_dim_name(dim):
if isinstance(dim, Dimension):
return dim
elif isinstance(dim, str):
return Dimension(Symbol(dim))
elif isinstance(dim, Symbol):
return Dimension(dim)
else:
raise TypeError("unrecognized type %s for %s" % (type(dim), dim))
for dim in dimensional_dependencies.keys():
dim = parse_dim(dim)
if (dim not in derived_dims) and (dim not in base_dims):
derived_dims.append(dim)
def parse_dict(d):
return Dict({parse_dim_name(i): j for i, j in d.items()})
# Make sure everything is a SymPy type:
dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in
dimensional_dependencies.items()}
for dim in derived_dims:
if dim in base_dims:
raise ValueError("Dimension %s both in base and derived" % dim)
if dim not in dimensional_dependencies:
# TODO: should this raise a warning?
dimensional_dependencies[dim] = Dict({dim: 1})
base_dims.sort(key=default_sort_key)
derived_dims.sort(key=default_sort_key)
base_dims = Tuple(*base_dims)
derived_dims = Tuple(*derived_dims)
dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()})
obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies)
return obj
@property
def base_dims(self):
return self.args[0]
@property
def derived_dims(self):
return self.args[1]
@property
def dimensional_dependencies(self):
return self.args[2]
def _get_dimensional_dependencies_for_name(self, dimension):
if isinstance(dimension, str):
dimension = Dimension(Symbol(dimension))
elif not isinstance(dimension, Dimension):
dimension = Dimension(dimension)
if dimension.name.is_Symbol:
# Dimensions not included in the dependencies are considered
# as base dimensions:
return dict(self.dimensional_dependencies.get(dimension, {dimension: 1}))
if dimension.name.is_number or dimension.name.is_NumberSymbol:
return {}
get_for_name = self._get_dimensional_dependencies_for_name
if dimension.name.is_Mul:
ret = collections.defaultdict(int)
dicts = [get_for_name(i) for i in dimension.name.args]
for d in dicts:
for k, v in d.items():
ret[k] += v
return {k: v for (k, v) in ret.items() if v != 0}
if dimension.name.is_Add:
dicts = [get_for_name(i) for i in dimension.name.args]
if all(d == dicts[0] for d in dicts[1:]):
return dicts[0]
raise TypeError("Only equivalent dimensions can be added or subtracted.")
if dimension.name.is_Pow:
dim_base = get_for_name(dimension.name.base)
dim_exp = get_for_name(dimension.name.exp)
if dim_exp == {} or dimension.name.exp.is_Symbol:
return {k: v * dimension.name.exp for (k, v) in dim_base.items()}
else:
raise TypeError("The exponent for the power operator must be a Symbol or dimensionless.")
if dimension.name.is_Function:
args = (Dimension._from_dimensional_dependencies(
get_for_name(arg)) for arg in dimension.name.args)
result = dimension.name.func(*args)
dicts = [get_for_name(i) for i in dimension.name.args]
if isinstance(result, Dimension):
return self.get_dimensional_dependencies(result)
elif result.func == dimension.name.func:
if isinstance(dimension.name, TrigonometricFunction):
if dicts[0] in ({}, {Dimension('angle'): 1}):
return {}
else:
raise TypeError("The input argument for the function {} must be dimensionless or have dimensions of angle.".format(dimension.func))
else:
if all(item == {} for item in dicts):
return {}
else:
raise TypeError("The input arguments for the function {} must be dimensionless.".format(dimension.func))
else:
return get_for_name(result)
raise TypeError("Type {} not implemented for get_dimensional_dependencies".format(type(dimension.name)))
def get_dimensional_dependencies(self, name, mark_dimensionless=False):
dimdep = self._get_dimensional_dependencies_for_name(name)
if mark_dimensionless and dimdep == {}:
return {Dimension(1): 1}
return {k: v for k, v in dimdep.items()}
def equivalent_dims(self, dim1, dim2):
deps1 = self.get_dimensional_dependencies(dim1)
deps2 = self.get_dimensional_dependencies(dim2)
return deps1 == deps2
def extend(self, new_base_dims, new_derived_dims=(), new_dim_deps=None):
deps = dict(self.dimensional_dependencies)
if new_dim_deps:
deps.update(new_dim_deps)
new_dim_sys = DimensionSystem(
tuple(self.base_dims) + tuple(new_base_dims),
tuple(self.derived_dims) + tuple(new_derived_dims),
deps
)
new_dim_sys._quantity_dimension_map.update(self._quantity_dimension_map)
new_dim_sys._quantity_scale_factors.update(self._quantity_scale_factors)
return new_dim_sys
def is_dimensionless(self, dimension):
"""
Check if the dimension object really has a dimension.
A dimension should have at least one component with non-zero power.
"""
if dimension.name == 1:
return True
return self.get_dimensional_dependencies(dimension) == {}
@property
def list_can_dims(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
List all canonical dimension names.
"""
dimset = set()
for i in self.base_dims:
dimset.update(set(self.get_dimensional_dependencies(i).keys()))
return tuple(sorted(dimset, key=str))
@property
def inv_can_transf_matrix(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Compute the inverse transformation matrix from the base to the
canonical dimension basis.
It corresponds to the matrix where columns are the vector of base
dimensions in canonical basis.
This matrix will almost never be used because dimensions are always
defined with respect to the canonical basis, so no work has to be done
to get them in this basis. Nonetheless if this matrix is not square
(or not invertible) it means that we have chosen a bad basis.
"""
matrix = reduce(lambda x, y: x.row_join(y),
[self.dim_can_vector(d) for d in self.base_dims])
return matrix
@property
def can_transf_matrix(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Return the canonical transformation matrix from the canonical to the
base dimension basis.
It is the inverse of the matrix computed with inv_can_transf_matrix().
"""
#TODO: the inversion will fail if the system is inconsistent, for
# example if the matrix is not a square
return reduce(lambda x, y: x.row_join(y),
[self.dim_can_vector(d) for d in sorted(self.base_dims, key=str)]
).inv()
def dim_can_vector(self, dim):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Dimensional representation in terms of the canonical base dimensions.
"""
vec = []
for d in self.list_can_dims:
vec.append(self.get_dimensional_dependencies(dim).get(d, 0))
return Matrix(vec)
def dim_vector(self, dim):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Vector representation in terms of the base dimensions.
"""
return self.can_transf_matrix * Matrix(self.dim_can_vector(dim))
def print_dim_base(self, dim):
"""
Give the string expression of a dimension in term of the basis symbols.
"""
dims = self.dim_vector(dim)
symbols = [i.symbol if i.symbol is not None else i.name for i in self.base_dims]
res = S.One
for (s, p) in zip(symbols, dims):
res *= s**p
return res
@property
def dim(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Give the dimension of the system.
That is return the number of dimensions forming the basis.
"""
return len(self.base_dims)
@property
def is_consistent(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Check if the system is well defined.
"""
# not enough or too many base dimensions compared to independent
# dimensions
# in vector language: the set of vectors do not form a basis
return self.inv_can_transf_matrix.is_square
|
245e4a480267728f282889cf0b77190912597f191cb55b1b885f26c64e77ef8c | from sympy.core.add import Add
from sympy.core.function import Function
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Rational, oo)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices.dense import eye
from sympy.polys.polytools import factor
from sympy.polys.rootoftools import CRootOf
from sympy.simplify.simplify import simplify
from sympy.core.containers import Tuple
from sympy.matrices import ImmutableMatrix, Matrix
from sympy.physics.control import (TransferFunction, Series, Parallel,
Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback, bilinear)
from sympy.testing.pytest import raises
a, x, b, s, g, d, p, k, a0, a1, a2, b0, b1, b2, tau, zeta, wn, T = symbols('a, x, b, s, g, d, p, k,\
a0:3, b0:3, tau, zeta, wn, T')
TF1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
TF2 = TransferFunction(k, 1, s)
TF3 = TransferFunction(a2*p - s, a2*s + p, s)
def test_TransferFunction_construction():
tf = TransferFunction(s + 1, s**2 + s + 1, s)
assert tf.num == (s + 1)
assert tf.den == (s**2 + s + 1)
assert tf.args == (s + 1, s**2 + s + 1, s)
tf1 = TransferFunction(s + 4, s - 5, s)
assert tf1.num == (s + 4)
assert tf1.den == (s - 5)
assert tf1.args == (s + 4, s - 5, s)
# using different polynomial variables.
tf2 = TransferFunction(p + 3, p**2 - 9, p)
assert tf2.num == (p + 3)
assert tf2.den == (p**2 - 9)
assert tf2.args == (p + 3, p**2 - 9, p)
tf3 = TransferFunction(p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p)
assert tf3.args == (p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p)
# no pole-zero cancellation on its own.
tf4 = TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)
assert tf4.den == (s - 1)*(s + 5)
assert tf4.args == ((s + 3)*(s - 1), (s - 1)*(s + 5), s)
tf4_ = TransferFunction(p + 2, p + 2, p)
assert tf4_.args == (p + 2, p + 2, p)
tf5 = TransferFunction(s - 1, 4 - p, s)
assert tf5.args == (s - 1, 4 - p, s)
tf5_ = TransferFunction(s - 1, s - 1, s)
assert tf5_.args == (s - 1, s - 1, s)
tf6 = TransferFunction(5, 6, s)
assert tf6.num == 5
assert tf6.den == 6
assert tf6.args == (5, 6, s)
tf6_ = TransferFunction(1/2, 4, s)
assert tf6_.num == 0.5
assert tf6_.den == 4
assert tf6_.args == (0.500000000000000, 4, s)
tf7 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, s)
tf8 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, p)
assert not tf7 == tf8
tf7_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s)
tf8_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s)
assert tf7_ == tf8_
assert -(-tf7_) == tf7_ == -(-(-(-tf7_)))
tf9 = TransferFunction(a*s**3 + b*s**2 + g*s + d, d*p + g*p**2 + g*s, s)
assert tf9.args == (a*s**3 + b*s**2 + d + g*s, d*p + g*p**2 + g*s, s)
tf10 = TransferFunction(p**3 + d, g*s**2 + d*s + a, p)
tf10_ = TransferFunction(p**3 + d, g*s**2 + d*s + a, p)
assert tf10.args == (d + p**3, a + d*s + g*s**2, p)
assert tf10_ == tf10
tf11 = TransferFunction(a1*s + a0, b2*s**2 + b1*s + b0, s)
assert tf11.num == (a0 + a1*s)
assert tf11.den == (b0 + b1*s + b2*s**2)
assert tf11.args == (a0 + a1*s, b0 + b1*s + b2*s**2, s)
# when just the numerator is 0, leave the denominator alone.
tf12 = TransferFunction(0, p**2 - p + 1, p)
assert tf12.args == (0, p**2 - p + 1, p)
tf13 = TransferFunction(0, 1, s)
assert tf13.args == (0, 1, s)
# float exponents
tf14 = TransferFunction(a0*s**0.5 + a2*s**0.6 - a1, a1*p**(-8.7), s)
assert tf14.args == (a0*s**0.5 - a1 + a2*s**0.6, a1*p**(-8.7), s)
tf15 = TransferFunction(a2**2*p**(1/4) + a1*s**(-4/5), a0*s - p, p)
assert tf15.args == (a1*s**(-0.8) + a2**2*p**0.25, a0*s - p, p)
omega_o, k_p, k_o, k_i = symbols('omega_o, k_p, k_o, k_i')
tf18 = TransferFunction((k_p + k_o*s + k_i/s), s**2 + 2*omega_o*s + omega_o**2, s)
assert tf18.num == k_i/s + k_o*s + k_p
assert tf18.args == (k_i/s + k_o*s + k_p, omega_o**2 + 2*omega_o*s + s**2, s)
# ValueError when denominator is zero.
raises(ValueError, lambda: TransferFunction(4, 0, s))
raises(ValueError, lambda: TransferFunction(s, 0, s))
raises(ValueError, lambda: TransferFunction(0, 0, s))
raises(TypeError, lambda: TransferFunction(Matrix([1, 2, 3]), s, s))
raises(TypeError, lambda: TransferFunction(s**2 + 2*s - 1, s + 3, 3))
raises(TypeError, lambda: TransferFunction(p + 1, 5 - p, 4))
raises(TypeError, lambda: TransferFunction(3, 4, 8))
def test_TransferFunction_functions():
# classmethod from_rational_expression
expr_1 = Mul(0, Pow(s, -1, evaluate=False), evaluate=False)
expr_2 = s/0
expr_3 = (p*s**2 + 5*s)/(s + 1)**3
expr_4 = 6
expr_5 = ((2 + 3*s)*(5 + 2*s))/((9 + 3*s)*(5 + 2*s**2))
expr_6 = (9*s**4 + 4*s**2 + 8)/((s + 1)*(s + 9))
tf = TransferFunction(s + 1, s**2 + 2, s)
delay = exp(-s/tau)
expr_7 = delay*tf.to_expr()
H1 = TransferFunction.from_rational_expression(expr_7, s)
H2 = TransferFunction(s + 1, (s**2 + 2)*exp(s/tau), s)
expr_8 = Add(2, 3*s/(s**2 + 1), evaluate=False)
assert TransferFunction.from_rational_expression(expr_1) == TransferFunction(0, s, s)
raises(ZeroDivisionError, lambda: TransferFunction.from_rational_expression(expr_2))
raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_3))
assert TransferFunction.from_rational_expression(expr_3, s) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, s)
assert TransferFunction.from_rational_expression(expr_3, p) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, p)
raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_4))
assert TransferFunction.from_rational_expression(expr_4, s) == TransferFunction(6, 1, s)
assert TransferFunction.from_rational_expression(expr_5, s) == \
TransferFunction((2 + 3*s)*(5 + 2*s), (9 + 3*s)*(5 + 2*s**2), s)
assert TransferFunction.from_rational_expression(expr_6, s) == \
TransferFunction((9*s**4 + 4*s**2 + 8), (s + 1)*(s + 9), s)
assert H1 == H2
assert TransferFunction.from_rational_expression(expr_8, s) == \
TransferFunction(2*s**2 + 3*s + 2, s**2 + 1, s)
# explicitly cancel poles and zeros.
tf0 = TransferFunction(s**5 + s**3 + s, s - s**2, s)
a = TransferFunction(-(s**4 + s**2 + 1), s - 1, s)
assert tf0.simplify() == simplify(tf0) == a
tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
b = TransferFunction(p + 3, p + 5, p)
assert tf1.simplify() == simplify(tf1) == b
# expand the numerator and the denominator.
G1 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
G2 = TransferFunction(1, -3, p)
c = (a2*s**p + a1*s**s + a0*p**p)*(p**s + s**p)
d = (b0*s**s + b1*p**s)*(b2*s*p + p**p)
e = a0*p**p*p**s + a0*p**p*s**p + a1*p**s*s**s + a1*s**p*s**s + a2*p**s*s**p + a2*s**(2*p)
f = b0*b2*p*s*s**s + b0*p**p*s**s + b1*b2*p*p**s*s + b1*p**p*p**s
g = a1*a2*s*s**p + a1*p*s + a2*b1*p*s*s**p + b1*p**2*s
G3 = TransferFunction(c, d, s)
G4 = TransferFunction(a0*s**s - b0*p**p, (a1*s + b1*s*p)*(a2*s**p + p), p)
assert G1.expand() == TransferFunction(s**2 - 2*s + 1, s**4 + 2*s**2 + 1, s)
assert tf1.expand() == TransferFunction(p**2 + 2*p - 3, p**2 + 4*p - 5, p)
assert G2.expand() == G2
assert G3.expand() == TransferFunction(e, f, s)
assert G4.expand() == TransferFunction(a0*s**s - b0*p**p, g, p)
# purely symbolic polynomials.
p1 = a1*s + a0
p2 = b2*s**2 + b1*s + b0
SP1 = TransferFunction(p1, p2, s)
expect1 = TransferFunction(2.0*s + 1.0, 5.0*s**2 + 4.0*s + 3.0, s)
expect1_ = TransferFunction(2*s + 1, 5*s**2 + 4*s + 3, s)
assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}) == expect1_
assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}).evalf() == expect1
assert expect1_.evalf() == expect1
c1, d0, d1, d2 = symbols('c1, d0:3')
p3, p4 = c1*p, d2*p**3 + d1*p**2 - d0
SP2 = TransferFunction(p3, p4, p)
expect2 = TransferFunction(2.0*p, 5.0*p**3 + 2.0*p**2 - 3.0, p)
expect2_ = TransferFunction(2*p, 5*p**3 + 2*p**2 - 3, p)
assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}) == expect2_
assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}).evalf() == expect2
assert expect2_.evalf() == expect2
SP3 = TransferFunction(a0*p**3 + a1*s**2 - b0*s + b1, a1*s + p, s)
expect3 = TransferFunction(2.0*p**3 + 4.0*s**2 - s + 5.0, p + 4.0*s, s)
expect3_ = TransferFunction(2*p**3 + 4*s**2 - s + 5, p + 4*s, s)
assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}) == expect3_
assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}).evalf() == expect3
assert expect3_.evalf() == expect3
SP4 = TransferFunction(s - a1*p**3, a0*s + p, p)
expect4 = TransferFunction(7.0*p**3 + s, p - s, p)
expect4_ = TransferFunction(7*p**3 + s, p - s, p)
assert SP4.subs({a0: -1, a1: -7}) == expect4_
assert SP4.subs({a0: -1, a1: -7}).evalf() == expect4
assert expect4_.evalf() == expect4
# Low-frequency (or DC) gain.
assert tf0.dc_gain() == 1
assert tf1.dc_gain() == Rational(3, 5)
assert SP2.dc_gain() == 0
assert expect4.dc_gain() == -1
assert expect2_.dc_gain() == 0
assert TransferFunction(1, s, s).dc_gain() == oo
# Poles of a transfer function.
tf_ = TransferFunction(x**3 - k, k, x)
_tf = TransferFunction(k, x**4 - k, x)
TF_ = TransferFunction(x**2, x**10 + x + x**2, x)
_TF = TransferFunction(x**10 + x + x**2, x**2, x)
assert G1.poles() == [I, I, -I, -I]
assert G2.poles() == []
assert tf1.poles() == [-5, 1]
assert expect4_.poles() == [s]
assert SP4.poles() == [-a0*s]
assert expect3.poles() == [-0.25*p]
assert str(expect2.poles()) == str([0.729001428685125, -0.564500714342563 - 0.710198984796332*I, -0.564500714342563 + 0.710198984796332*I])
assert str(expect1.poles()) == str([-0.4 - 0.66332495807108*I, -0.4 + 0.66332495807108*I])
assert _tf.poles() == [k**(Rational(1, 4)), -k**(Rational(1, 4)), I*k**(Rational(1, 4)), -I*k**(Rational(1, 4))]
assert TF_.poles() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2),
CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6),
CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)]
raises(NotImplementedError, lambda: TransferFunction(x**2, a0*x**10 + x + x**2, x).poles())
# Stability of a transfer function.
q, r = symbols('q, r', negative=True)
t = symbols('t', positive=True)
TF_ = TransferFunction(s**2 + a0 - a1*p, q*s - r, s)
stable_tf = TransferFunction(s**2 + a0 - a1*p, q*s - 1, s)
stable_tf_ = TransferFunction(s**2 + a0 - a1*p, q*s - t, s)
assert G1.is_stable() is False
assert G2.is_stable() is True
assert tf1.is_stable() is False # as one pole is +ve, and the other is -ve.
assert expect2.is_stable() is False
assert expect1.is_stable() is True
assert stable_tf.is_stable() is True
assert stable_tf_.is_stable() is True
assert TF_.is_stable() is False
assert expect4_.is_stable() is None # no assumption provided for the only pole 's'.
assert SP4.is_stable() is None
# Zeros of a transfer function.
assert G1.zeros() == [1, 1]
assert G2.zeros() == []
assert tf1.zeros() == [-3, 1]
assert expect4_.zeros() == [7**(Rational(2, 3))*(-s)**(Rational(1, 3))/7, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 -
sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 + sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14]
assert SP4.zeros() == [(s/a1)**(Rational(1, 3)), -(s/a1)**(Rational(1, 3))/2 - sqrt(3)*I*(s/a1)**(Rational(1, 3))/2,
-(s/a1)**(Rational(1, 3))/2 + sqrt(3)*I*(s/a1)**(Rational(1, 3))/2]
assert str(expect3.zeros()) == str([0.125 - 1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0),
1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0) + 0.125])
assert tf_.zeros() == [k**(Rational(1, 3)), -k**(Rational(1, 3))/2 - sqrt(3)*I*k**(Rational(1, 3))/2,
-k**(Rational(1, 3))/2 + sqrt(3)*I*k**(Rational(1, 3))/2]
assert _TF.zeros() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2),
CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6),
CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)]
raises(NotImplementedError, lambda: TransferFunction(a0*x**10 + x + x**2, x**2, x).zeros())
# negation of TF.
tf2 = TransferFunction(s + 3, s**2 - s**3 + 9, s)
tf3 = TransferFunction(-3*p + 3, 1 - p, p)
assert -tf2 == TransferFunction(-s - 3, s**2 - s**3 + 9, s)
assert -tf3 == TransferFunction(3*p - 3, 1 - p, p)
# taking power of a TF.
tf4 = TransferFunction(p + 4, p - 3, p)
tf5 = TransferFunction(s**2 + 1, 1 - s, s)
expect2 = TransferFunction((s**2 + 1)**3, (1 - s)**3, s)
expect1 = TransferFunction((p + 4)**2, (p - 3)**2, p)
assert (tf4*tf4).doit() == tf4**2 == pow(tf4, 2) == expect1
assert (tf5*tf5*tf5).doit() == tf5**3 == pow(tf5, 3) == expect2
assert tf5**0 == pow(tf5, 0) == TransferFunction(1, 1, s)
assert Series(tf4).doit()**-1 == tf4**-1 == pow(tf4, -1) == TransferFunction(p - 3, p + 4, p)
assert (tf5*tf5).doit()**-1 == tf5**-2 == pow(tf5, -2) == TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
raises(ValueError, lambda: tf4**(s**2 + s - 1))
raises(ValueError, lambda: tf5**s)
raises(ValueError, lambda: tf4**tf5)
# SymPy's own functions.
tf = TransferFunction(s - 1, s**2 - 2*s + 1, s)
tf6 = TransferFunction(s + p, p**2 - 5, s)
assert factor(tf) == TransferFunction(s - 1, (s - 1)**2, s)
assert tf.num.subs(s, 2) == tf.den.subs(s, 2) == 1
# subs & xreplace
assert tf.subs(s, 2) == TransferFunction(s - 1, s**2 - 2*s + 1, s)
assert tf6.subs(p, 3) == TransferFunction(s + 3, 4, s)
assert tf3.xreplace({p: s}) == TransferFunction(-3*s + 3, 1 - s, s)
raises(TypeError, lambda: tf3.xreplace({p: exp(2)}))
assert tf3.subs(p, exp(2)) == tf3
tf7 = TransferFunction(a0*s**p + a1*p**s, a2*p - s, s)
assert tf7.xreplace({s: k}) == TransferFunction(a0*k**p + a1*p**k, a2*p - k, k)
assert tf7.subs(s, k) == TransferFunction(a0*s**p + a1*p**s, a2*p - s, s)
# Conversion to Expr with to_expr()
tf8 = TransferFunction(a0*s**5 + 5*s**2 + 3, s**6 - 3, s)
tf9 = TransferFunction((5 + s), (5 + s)*(6 + s), s)
tf10 = TransferFunction(0, 1, s)
tf11 = TransferFunction(1, 1, s)
assert tf8.to_expr() == Mul((a0*s**5 + 5*s**2 + 3), Pow((s**6 - 3), -1, evaluate=False), evaluate=False)
assert tf9.to_expr() == Mul((s + 5), Pow((5 + s)*(6 + s), -1, evaluate=False), evaluate=False)
assert tf10.to_expr() == Mul(S(0), Pow(1, -1, evaluate=False), evaluate=False)
assert tf11.to_expr() == Pow(1, -1, evaluate=False)
def test_TransferFunction_addition_and_subtraction():
tf1 = TransferFunction(s + 6, s - 5, s)
tf2 = TransferFunction(s + 3, s + 1, s)
tf3 = TransferFunction(s + 1, s**2 + s + 1, s)
tf4 = TransferFunction(p, 2 - p, p)
# addition
assert tf1 + tf2 == Parallel(tf1, tf2)
assert tf3 + tf1 == Parallel(tf3, tf1)
assert -tf1 + tf2 + tf3 == Parallel(-tf1, tf2, tf3)
assert tf1 + (tf2 + tf3) == Parallel(tf1, tf2, tf3)
c = symbols("c", commutative=False)
raises(ValueError, lambda: tf1 + Matrix([1, 2, 3]))
raises(ValueError, lambda: tf2 + c)
raises(ValueError, lambda: tf3 + tf4)
raises(ValueError, lambda: tf1 + (s - 1))
raises(ValueError, lambda: tf1 + 8)
raises(ValueError, lambda: (1 - p**3) + tf1)
# subtraction
assert tf1 - tf2 == Parallel(tf1, -tf2)
assert tf3 - tf2 == Parallel(tf3, -tf2)
assert -tf1 - tf3 == Parallel(-tf1, -tf3)
assert tf1 - tf2 + tf3 == Parallel(tf1, -tf2, tf3)
raises(ValueError, lambda: tf1 - Matrix([1, 2, 3]))
raises(ValueError, lambda: tf3 - tf4)
raises(ValueError, lambda: tf1 - (s - 1))
raises(ValueError, lambda: tf1 - 8)
raises(ValueError, lambda: (s + 5) - tf2)
raises(ValueError, lambda: (1 + p**4) - tf1)
def test_TransferFunction_multiplication_and_division():
G1 = TransferFunction(s + 3, -s**3 + 9, s)
G2 = TransferFunction(s + 1, s - 5, s)
G3 = TransferFunction(p, p**4 - 6, p)
G4 = TransferFunction(p + 4, p - 5, p)
G5 = TransferFunction(s + 6, s - 5, s)
G6 = TransferFunction(s + 3, s + 1, s)
G7 = TransferFunction(1, 1, s)
# multiplication
assert G1*G2 == Series(G1, G2)
assert -G1*G5 == Series(-G1, G5)
assert -G2*G5*-G6 == Series(-G2, G5, -G6)
assert -G1*-G2*-G5*-G6 == Series(-G1, -G2, -G5, -G6)
assert G3*G4 == Series(G3, G4)
assert (G1*G2)*-(G5*G6) == \
Series(G1, G2, TransferFunction(-1, 1, s), Series(G5, G6))
assert G1*G2*(G5 + G6) == Series(G1, G2, Parallel(G5, G6))
c = symbols("c", commutative=False)
raises(ValueError, lambda: G3 * Matrix([1, 2, 3]))
raises(ValueError, lambda: G1 * c)
raises(ValueError, lambda: G3 * G5)
raises(ValueError, lambda: G5 * (s - 1))
raises(ValueError, lambda: 9 * G5)
raises(ValueError, lambda: G3 / Matrix([1, 2, 3]))
raises(ValueError, lambda: G6 / 0)
raises(ValueError, lambda: G3 / G5)
raises(ValueError, lambda: G5 / 2)
raises(ValueError, lambda: G5 / s**2)
raises(ValueError, lambda: (s - 4*s**2) / G2)
raises(ValueError, lambda: 0 / G4)
raises(ValueError, lambda: G5 / G6)
raises(ValueError, lambda: -G3 /G4)
raises(ValueError, lambda: G7 / (1 + G6))
raises(ValueError, lambda: G7 / (G5 * G6))
raises(ValueError, lambda: G7 / (G7 + (G5 + G6)))
def test_TransferFunction_is_proper():
omega_o, zeta, tau = symbols('omega_o, zeta, tau')
G1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
G2 = TransferFunction(tau - s**3, tau + p**4, tau)
G3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
G4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
assert G1.is_proper
assert G2.is_proper
assert G3.is_proper
assert not G4.is_proper
def test_TransferFunction_is_strictly_proper():
omega_o, zeta, tau = symbols('omega_o, zeta, tau')
tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
tf2 = TransferFunction(tau - s**3, tau + p**4, tau)
tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
assert not tf1.is_strictly_proper
assert not tf2.is_strictly_proper
assert tf3.is_strictly_proper
assert not tf4.is_strictly_proper
def test_TransferFunction_is_biproper():
tau, omega_o, zeta = symbols('tau, omega_o, zeta')
tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
tf2 = TransferFunction(tau - s**3, tau + p**4, tau)
tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
assert tf1.is_biproper
assert tf2.is_biproper
assert not tf3.is_biproper
assert not tf4.is_biproper
def test_Series_construction():
tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
tf2 = TransferFunction(a2*p - s, a2*s + p, s)
tf3 = TransferFunction(a0*p + p**a1 - s, p, p)
tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
inp = Function('X_d')(s)
out = Function('X')(s)
s0 = Series(tf, tf2)
assert s0.args == (tf, tf2)
assert s0.var == s
s1 = Series(Parallel(tf, -tf2), tf2)
assert s1.args == (Parallel(tf, -tf2), tf2)
assert s1.var == s
tf3_ = TransferFunction(inp, 1, s)
tf4_ = TransferFunction(-out, 1, s)
s2 = Series(tf, Parallel(tf3_, tf4_), tf2)
assert s2.args == (tf, Parallel(tf3_, tf4_), tf2)
s3 = Series(tf, tf2, tf4)
assert s3.args == (tf, tf2, tf4)
s4 = Series(tf3_, tf4_)
assert s4.args == (tf3_, tf4_)
assert s4.var == s
s6 = Series(tf2, tf4, Parallel(tf2, -tf), tf4)
assert s6.args == (tf2, tf4, Parallel(tf2, -tf), tf4)
s7 = Series(tf, tf2)
assert s0 == s7
assert not s0 == s2
raises(ValueError, lambda: Series(tf, tf3))
raises(ValueError, lambda: Series(tf, tf2, tf3, tf4))
raises(ValueError, lambda: Series(-tf3, tf2))
raises(TypeError, lambda: Series(2, tf, tf4))
raises(TypeError, lambda: Series(s**2 + p*s, tf3, tf2))
raises(TypeError, lambda: Series(tf3, Matrix([1, 2, 3, 4])))
def test_MIMOSeries_construction():
tf_1 = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
tf_2 = TransferFunction(a2*p - s, a2*s + p, s)
tf_3 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tfm_1 = TransferFunctionMatrix([[tf_1, tf_2, tf_3], [-tf_3, -tf_2, tf_1]])
tfm_2 = TransferFunctionMatrix([[-tf_2], [-tf_2], [-tf_3]])
tfm_3 = TransferFunctionMatrix([[-tf_3]])
tfm_4 = TransferFunctionMatrix([[TF3], [TF2], [-TF1]])
tfm_5 = TransferFunctionMatrix.from_Matrix(Matrix([1/p]), p)
s8 = MIMOSeries(tfm_2, tfm_1)
assert s8.args == (tfm_2, tfm_1)
assert s8.var == s
assert s8.shape == (s8.num_outputs, s8.num_inputs) == (2, 1)
s9 = MIMOSeries(tfm_3, tfm_2, tfm_1)
assert s9.args == (tfm_3, tfm_2, tfm_1)
assert s9.var == s
assert s9.shape == (s9.num_outputs, s9.num_inputs) == (2, 1)
s11 = MIMOSeries(tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1)
assert s11.args == (tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1)
assert s11.shape == (s11.num_outputs, s11.num_inputs) == (2, 1)
# arg cannot be empty tuple.
raises(ValueError, lambda: MIMOSeries())
# arg cannot contain SISO as well as MIMO systems.
raises(TypeError, lambda: MIMOSeries(tfm_1, tf_1))
# for all the adjacent transfer function matrices:
# no. of inputs of first TFM must be equal to the no. of outputs of the second TFM.
raises(ValueError, lambda: MIMOSeries(tfm_1, tfm_2, -tfm_1))
# all the TFMs must use the same complex variable.
raises(ValueError, lambda: MIMOSeries(tfm_3, tfm_5))
# Number or expression not allowed in the arguments.
raises(TypeError, lambda: MIMOSeries(2, tfm_2, tfm_3))
raises(TypeError, lambda: MIMOSeries(s**2 + p*s, -tfm_2, tfm_3))
raises(TypeError, lambda: MIMOSeries(Matrix([1/p]), tfm_3))
def test_Series_functions():
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tf2 = TransferFunction(k, 1, s)
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
assert tf1*tf2*tf3 == Series(tf1, tf2, tf3) == Series(Series(tf1, tf2), tf3) \
== Series(tf1, Series(tf2, tf3))
assert tf1*(tf2 + tf3) == Series(tf1, Parallel(tf2, tf3))
assert tf1*tf2 + tf5 == Parallel(Series(tf1, tf2), tf5)
assert tf1*tf2 - tf5 == Parallel(Series(tf1, tf2), -tf5)
assert tf1*tf2 + tf3 + tf5 == Parallel(Series(tf1, tf2), tf3, tf5)
assert tf1*tf2 - tf3 - tf5 == Parallel(Series(tf1, tf2), -tf3, -tf5)
assert tf1*tf2 - tf3 + tf5 == Parallel(Series(tf1, tf2), -tf3, tf5)
assert tf1*tf2 + tf3*tf5 == Parallel(Series(tf1, tf2), Series(tf3, tf5))
assert tf1*tf2 - tf3*tf5 == Parallel(Series(tf1, tf2), Series(TransferFunction(-1, 1, s), Series(tf3, tf5)))
assert tf2*tf3*(tf2 - tf1)*tf3 == Series(tf2, tf3, Parallel(tf2, -tf1), tf3)
assert -tf1*tf2 == Series(-tf1, tf2)
assert -(tf1*tf2) == Series(TransferFunction(-1, 1, s), Series(tf1, tf2))
raises(ValueError, lambda: tf1*tf2*tf4)
raises(ValueError, lambda: tf1*(tf2 - tf4))
raises(ValueError, lambda: tf3*Matrix([1, 2, 3]))
# evaluate=True -> doit()
assert Series(tf1, tf2, evaluate=True) == Series(tf1, tf2).doit() == \
TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s)
assert Series(tf1, tf2, Parallel(tf1, -tf3), evaluate=True) == Series(tf1, tf2, Parallel(tf1, -tf3)).doit() == \
TransferFunction(k*(a2*s + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2, s)
assert Series(tf2, tf1, -tf3, evaluate=True) == Series(tf2, tf1, -tf3).doit() == \
TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert not Series(tf1, -tf2, evaluate=False) == Series(tf1, -tf2).doit()
assert Series(Parallel(tf1, tf2), Parallel(tf2, -tf3)).doit() == \
TransferFunction((k*(s**2 + 2*s*wn*zeta + wn**2) + 1)*(-a2*p + k*(a2*s + p) + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Series(-tf1, -tf2, -tf3).doit() == \
TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert -Series(tf1, tf2, tf3).doit() == \
TransferFunction(-k*(a2*p - s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Series(tf2, tf3, Parallel(tf2, -tf1), tf3).doit() == \
TransferFunction(k*(a2*p - s)**2*(k*(s**2 + 2*s*wn*zeta + wn**2) - 1), (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Series(tf1, tf2).rewrite(TransferFunction) == TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s)
assert Series(tf2, tf1, -tf3).rewrite(TransferFunction) == \
TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
S1 = Series(Parallel(tf1, tf2), Parallel(tf2, -tf3))
assert S1.is_proper
assert not S1.is_strictly_proper
assert S1.is_biproper
S2 = Series(tf1, tf2, tf3)
assert S2.is_proper
assert S2.is_strictly_proper
assert not S2.is_biproper
S3 = Series(tf1, -tf2, Parallel(tf1, -tf3))
assert S3.is_proper
assert S3.is_strictly_proper
assert not S3.is_biproper
def test_MIMOSeries_functions():
tfm1 = TransferFunctionMatrix([[TF1, TF2, TF3], [-TF3, -TF2, TF1]])
tfm2 = TransferFunctionMatrix([[-TF1], [-TF2], [-TF3]])
tfm3 = TransferFunctionMatrix([[-TF1]])
tfm4 = TransferFunctionMatrix([[-TF2, -TF3], [-TF1, TF2]])
tfm5 = TransferFunctionMatrix([[TF2, -TF2], [-TF3, -TF2]])
tfm6 = TransferFunctionMatrix([[-TF3], [TF1]])
tfm7 = TransferFunctionMatrix([[TF1], [-TF2]])
assert tfm1*tfm2 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm6)
assert tfm1*tfm2 + tfm7 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm7, tfm6)
assert tfm1*tfm2 - tfm6 - tfm7 == MIMOParallel(MIMOSeries(tfm2, tfm1), -tfm6, -tfm7)
assert tfm4*tfm5 + (tfm4 - tfm5) == MIMOParallel(MIMOSeries(tfm5, tfm4), tfm4, -tfm5)
assert tfm4*-tfm6 + (-tfm4*tfm6) == MIMOParallel(MIMOSeries(-tfm6, tfm4), MIMOSeries(tfm6, -tfm4))
raises(ValueError, lambda: tfm1*tfm2 + TF1)
raises(TypeError, lambda: tfm1*tfm2 + a0)
raises(TypeError, lambda: tfm4*tfm6 - (s - 1))
raises(TypeError, lambda: tfm4*-tfm6 - 8)
raises(TypeError, lambda: (-1 + p**5) + tfm1*tfm2)
# Shape criteria.
raises(TypeError, lambda: -tfm1*tfm2 + tfm4)
raises(TypeError, lambda: tfm1*tfm2 - tfm4 + tfm5)
raises(TypeError, lambda: tfm1*tfm2 - tfm4*tfm5)
assert tfm1*tfm2*-tfm3 == MIMOSeries(-tfm3, tfm2, tfm1)
assert (tfm1*-tfm2)*tfm3 == MIMOSeries(tfm3, -tfm2, tfm1)
# Multiplication of a Series object with a SISO TF not allowed.
raises(ValueError, lambda: tfm4*tfm5*TF1)
raises(TypeError, lambda: tfm4*tfm5*a1)
raises(TypeError, lambda: tfm4*-tfm5*(s - 2))
raises(TypeError, lambda: tfm5*tfm4*9)
raises(TypeError, lambda: (-p**3 + 1)*tfm5*tfm4)
# Transfer function matrix in the arguments.
assert (MIMOSeries(tfm2, tfm1, evaluate=True) == MIMOSeries(tfm2, tfm1).doit()
== TransferFunctionMatrix(((TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2)**2 - (a2*s + p)**2,
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),),
(TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2),
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),))))
# doit() should not cancel poles and zeros.
mat_1 = Matrix([[1/(1+s), (1+s)/(1+s**2+2*s)**3]])
mat_2 = Matrix([[(1+s)], [(1+s**2+2*s)**3/(1+s)]])
tm_1, tm_2 = TransferFunctionMatrix.from_Matrix(mat_1, s), TransferFunctionMatrix.from_Matrix(mat_2, s)
assert (MIMOSeries(tm_2, tm_1).doit()
== TransferFunctionMatrix(((TransferFunction(2*(s + 1)**2*(s**2 + 2*s + 1)**3, (s + 1)**2*(s**2 + 2*s + 1)**3, s),),)))
assert MIMOSeries(tm_2, tm_1).doit().simplify() == TransferFunctionMatrix(((TransferFunction(2, 1, s),),))
# calling doit() will expand the internal Series and Parallel objects.
assert (MIMOSeries(-tfm3, -tfm2, tfm1, evaluate=True)
== MIMOSeries(-tfm3, -tfm2, tfm1).doit()
== TransferFunctionMatrix(((TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*p - s)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*s + p)**2,
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),),
(TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2),
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),))))
assert (MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5, evaluate=True)
== MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).doit()
== TransferFunctionMatrix(((TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), TransferFunction(k*(-a2*p - \
k*(a2*s + p) + s), a2*s + p, s)), (TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), \
TransferFunction((-a2*p + s)*(-a2*p - k*(a2*s + p) + s), (a2*s + p)**2, s)))) == MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).rewrite(TransferFunctionMatrix))
def test_Parallel_construction():
tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
tf2 = TransferFunction(a2*p - s, a2*s + p, s)
tf3 = TransferFunction(a0*p + p**a1 - s, p, p)
tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
inp = Function('X_d')(s)
out = Function('X')(s)
p0 = Parallel(tf, tf2)
assert p0.args == (tf, tf2)
assert p0.var == s
p1 = Parallel(Series(tf, -tf2), tf2)
assert p1.args == (Series(tf, -tf2), tf2)
assert p1.var == s
tf3_ = TransferFunction(inp, 1, s)
tf4_ = TransferFunction(-out, 1, s)
p2 = Parallel(tf, Series(tf3_, -tf4_), tf2)
assert p2.args == (tf, Series(tf3_, -tf4_), tf2)
p3 = Parallel(tf, tf2, tf4)
assert p3.args == (tf, tf2, tf4)
p4 = Parallel(tf3_, tf4_)
assert p4.args == (tf3_, tf4_)
assert p4.var == s
p5 = Parallel(tf, tf2)
assert p0 == p5
assert not p0 == p1
p6 = Parallel(tf2, tf4, Series(tf2, -tf4))
assert p6.args == (tf2, tf4, Series(tf2, -tf4))
p7 = Parallel(tf2, tf4, Series(tf2, -tf), tf4)
assert p7.args == (tf2, tf4, Series(tf2, -tf), tf4)
raises(ValueError, lambda: Parallel(tf, tf3))
raises(ValueError, lambda: Parallel(tf, tf2, tf3, tf4))
raises(ValueError, lambda: Parallel(-tf3, tf4))
raises(TypeError, lambda: Parallel(2, tf, tf4))
raises(TypeError, lambda: Parallel(s**2 + p*s, tf3, tf2))
raises(TypeError, lambda: Parallel(tf3, Matrix([1, 2, 3, 4])))
def test_MIMOParallel_construction():
tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]])
tfm2 = TransferFunctionMatrix([[-TF3], [TF2], [TF1]])
tfm3 = TransferFunctionMatrix([[TF1]])
tfm4 = TransferFunctionMatrix([[TF2], [TF1], [TF3]])
tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF2, TF1]])
tfm6 = TransferFunctionMatrix([[TF2, TF1], [TF1, TF2]])
tfm7 = TransferFunctionMatrix.from_Matrix(Matrix([[1/p]]), p)
p8 = MIMOParallel(tfm1, tfm2)
assert p8.args == (tfm1, tfm2)
assert p8.var == s
assert p8.shape == (p8.num_outputs, p8.num_inputs) == (3, 1)
p9 = MIMOParallel(MIMOSeries(tfm3, tfm1), tfm2)
assert p9.args == (MIMOSeries(tfm3, tfm1), tfm2)
assert p9.var == s
assert p9.shape == (p9.num_outputs, p9.num_inputs) == (3, 1)
p10 = MIMOParallel(tfm1, MIMOSeries(tfm3, tfm4), tfm2)
assert p10.args == (tfm1, MIMOSeries(tfm3, tfm4), tfm2)
assert p10.var == s
assert p10.shape == (p10.num_outputs, p10.num_inputs) == (3, 1)
p11 = MIMOParallel(tfm2, tfm1, tfm4)
assert p11.args == (tfm2, tfm1, tfm4)
assert p11.shape == (p11.num_outputs, p11.num_inputs) == (3, 1)
p12 = MIMOParallel(tfm6, tfm5)
assert p12.args == (tfm6, tfm5)
assert p12.shape == (p12.num_outputs, p12.num_inputs) == (2, 2)
p13 = MIMOParallel(tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4)
assert p13.args == (tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4)
assert p13.shape == (p13.num_outputs, p13.num_inputs) == (3, 1)
# arg cannot be empty tuple.
raises(TypeError, lambda: MIMOParallel(()))
# arg cannot contain SISO as well as MIMO systems.
raises(TypeError, lambda: MIMOParallel(tfm1, tfm2, TF1))
# all TFMs must have same shapes.
raises(TypeError, lambda: MIMOParallel(tfm1, tfm3, tfm4))
# all TFMs must be using the same complex variable.
raises(ValueError, lambda: MIMOParallel(tfm3, tfm7))
# Number or expression not allowed in the arguments.
raises(TypeError, lambda: MIMOParallel(2, tfm1, tfm4))
raises(TypeError, lambda: MIMOParallel(s**2 + p*s, -tfm4, tfm2))
def test_Parallel_functions():
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tf2 = TransferFunction(k, 1, s)
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
assert tf1 + tf2 + tf3 == Parallel(tf1, tf2, tf3)
assert tf1 + tf2 + tf3 + tf5 == Parallel(tf1, tf2, tf3, tf5)
assert tf1 + tf2 - tf3 - tf5 == Parallel(tf1, tf2, -tf3, -tf5)
assert tf1 + tf2*tf3 == Parallel(tf1, Series(tf2, tf3))
assert tf1 - tf2*tf3 == Parallel(tf1, -Series(tf2,tf3))
assert -tf1 - tf2 == Parallel(-tf1, -tf2)
assert -(tf1 + tf2) == Series(TransferFunction(-1, 1, s), Parallel(tf1, tf2))
assert (tf2 + tf3)*tf1 == Series(Parallel(tf2, tf3), tf1)
assert (tf1 + tf2)*(tf3*tf5) == Series(Parallel(tf1, tf2), tf3, tf5)
assert -(tf2 + tf3)*-tf5 == Series(TransferFunction(-1, 1, s), Parallel(tf2, tf3), -tf5)
assert tf2 + tf3 + tf2*tf1 + tf5 == Parallel(tf2, tf3, Series(tf2, tf1), tf5)
assert tf2 + tf3 + tf2*tf1 - tf3 == Parallel(tf2, tf3, Series(tf2, tf1), -tf3)
assert (tf1 + tf2 + tf5)*(tf3 + tf5) == Series(Parallel(tf1, tf2, tf5), Parallel(tf3, tf5))
raises(ValueError, lambda: tf1 + tf2 + tf4)
raises(ValueError, lambda: tf1 - tf2*tf4)
raises(ValueError, lambda: tf3 + Matrix([1, 2, 3]))
# evaluate=True -> doit()
assert Parallel(tf1, tf2, evaluate=True) == Parallel(tf1, tf2).doit() == \
TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s)
assert Parallel(tf1, tf2, Series(-tf1, tf3), evaluate=True) == \
Parallel(tf1, tf2, Series(-tf1, tf3)).doit() == TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2 + \
(-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + \
2*s*wn*zeta + wn**2)**2, s)
assert Parallel(tf2, tf1, -tf3, evaluate=True) == Parallel(tf2, tf1, -tf3).doit() == \
TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) \
, (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert not Parallel(tf1, -tf2, evaluate=False) == Parallel(tf1, -tf2).doit()
assert Parallel(Series(tf1, tf2), Series(tf2, tf3)).doit() == \
TransferFunction(k*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2) + k*(a2*s + p), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Parallel(-tf1, -tf2, -tf3).doit() == \
TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2), \
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert -Parallel(tf1, tf2, tf3).doit() == \
TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p - (a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2), \
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Parallel(tf2, tf3, Series(tf2, -tf1), tf3).doit() == \
TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - k*(a2*s + p) + (2*a2*p - 2*s)*(s**2 + 2*s*wn*zeta \
+ wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Parallel(tf1, tf2).rewrite(TransferFunction) == \
TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s)
assert Parallel(tf2, tf1, -tf3).rewrite(TransferFunction) == \
TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + \
wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Parallel(tf1, Parallel(tf2, tf3)) == Parallel(tf1, tf2, tf3) == Parallel(Parallel(tf1, tf2), tf3)
P1 = Parallel(Series(tf1, tf2), Series(tf2, tf3))
assert P1.is_proper
assert not P1.is_strictly_proper
assert P1.is_biproper
P2 = Parallel(tf1, -tf2, -tf3)
assert P2.is_proper
assert not P2.is_strictly_proper
assert P2.is_biproper
P3 = Parallel(tf1, -tf2, Series(tf1, tf3))
assert P3.is_proper
assert not P3.is_strictly_proper
assert P3.is_biproper
def test_MIMOParallel_functions():
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]])
tfm2 = TransferFunctionMatrix([[-TF2], [tf5], [-TF1]])
tfm3 = TransferFunctionMatrix([[tf5], [-tf5], [TF2]])
tfm4 = TransferFunctionMatrix([[TF2, -tf5], [TF1, tf5]])
tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5]])
tfm6 = TransferFunctionMatrix([[-TF2]])
tfm7 = TransferFunctionMatrix([[tf4], [-tf4], [tf4]])
assert tfm1 + tfm2 + tfm3 == MIMOParallel(tfm1, tfm2, tfm3) == MIMOParallel(MIMOParallel(tfm1, tfm2), tfm3)
assert tfm2 - tfm1 - tfm3 == MIMOParallel(tfm2, -tfm1, -tfm3)
assert tfm2 - tfm3 + (-tfm1*tfm6*-tfm6) == MIMOParallel(tfm2, -tfm3, MIMOSeries(-tfm6, tfm6, -tfm1))
assert tfm1 + tfm1 - (-tfm1*tfm6) == MIMOParallel(tfm1, tfm1, -MIMOSeries(tfm6, -tfm1))
assert tfm2 - tfm3 - tfm1 + tfm2 == MIMOParallel(tfm2, -tfm3, -tfm1, tfm2)
assert tfm1 + tfm2 - tfm3 - tfm1 == MIMOParallel(tfm1, tfm2, -tfm3, -tfm1)
raises(ValueError, lambda: tfm1 + tfm2 + TF2)
raises(TypeError, lambda: tfm1 - tfm2 - a1)
raises(TypeError, lambda: tfm2 - tfm3 - (s - 1))
raises(TypeError, lambda: -tfm3 - tfm2 - 9)
raises(TypeError, lambda: (1 - p**3) - tfm3 - tfm2)
# All TFMs must use the same complex var. tfm7 uses 'p'.
raises(ValueError, lambda: tfm3 - tfm2 - tfm7)
raises(ValueError, lambda: tfm2 - tfm1 + tfm7)
# (tfm1 +/- tfm2) has (3, 1) shape while tfm4 has (2, 2) shape.
raises(TypeError, lambda: tfm1 + tfm2 + tfm4)
raises(TypeError, lambda: (tfm1 - tfm2) - tfm4)
assert (tfm1 + tfm2)*tfm6 == MIMOSeries(tfm6, MIMOParallel(tfm1, tfm2))
assert (tfm2 - tfm3)*tfm6*-tfm6 == MIMOSeries(-tfm6, tfm6, MIMOParallel(tfm2, -tfm3))
assert (tfm2 - tfm1 - tfm3)*(tfm6 + tfm6) == MIMOSeries(MIMOParallel(tfm6, tfm6), MIMOParallel(tfm2, -tfm1, -tfm3))
raises(ValueError, lambda: (tfm4 + tfm5)*TF1)
raises(TypeError, lambda: (tfm2 - tfm3)*a2)
raises(TypeError, lambda: (tfm3 + tfm2)*(s - 6))
raises(TypeError, lambda: (tfm1 + tfm2 + tfm3)*0)
raises(TypeError, lambda: (1 - p**3)*(tfm1 + tfm3))
# (tfm3 - tfm2) has (3, 1) shape while tfm4*tfm5 has (2, 2) shape.
raises(ValueError, lambda: (tfm3 - tfm2)*tfm4*tfm5)
# (tfm1 - tfm2) has (3, 1) shape while tfm5 has (2, 2) shape.
raises(ValueError, lambda: (tfm1 - tfm2)*tfm5)
# TFM in the arguments.
assert (MIMOParallel(tfm1, tfm2, evaluate=True) == MIMOParallel(tfm1, tfm2).doit()
== MIMOParallel(tfm1, tfm2).rewrite(TransferFunctionMatrix)
== TransferFunctionMatrix(((TransferFunction(-k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s),), \
(TransferFunction(-a0 + a1*s**2 + a2*s + k*(a0 + s), a0 + s, s),), (TransferFunction(-a2*s - p + (a2*p - s)* \
(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s),))))
def test_Feedback_construction():
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tf2 = TransferFunction(k, 1, s)
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
tf6 = TransferFunction(s - p, p + s, p)
f1 = Feedback(TransferFunction(1, 1, s), tf1*tf2*tf3)
assert f1.args == (TransferFunction(1, 1, s), Series(tf1, tf2, tf3), -1)
assert f1.sys1 == TransferFunction(1, 1, s)
assert f1.sys2 == Series(tf1, tf2, tf3)
assert f1.var == s
f2 = Feedback(tf1, tf2*tf3)
assert f2.args == (tf1, Series(tf2, tf3), -1)
assert f2.sys1 == tf1
assert f2.sys2 == Series(tf2, tf3)
assert f2.var == s
f3 = Feedback(tf1*tf2, tf5)
assert f3.args == (Series(tf1, tf2), tf5, -1)
assert f3.sys1 == Series(tf1, tf2)
f4 = Feedback(tf4, tf6)
assert f4.args == (tf4, tf6, -1)
assert f4.sys1 == tf4
assert f4.var == p
f5 = Feedback(tf5, TransferFunction(1, 1, s))
assert f5.args == (tf5, TransferFunction(1, 1, s), -1)
assert f5.var == s
assert f5 == Feedback(tf5) # When sys2 is not passed explicitly, it is assumed to be unit tf.
f6 = Feedback(TransferFunction(1, 1, p), tf4)
assert f6.args == (TransferFunction(1, 1, p), tf4, -1)
assert f6.var == p
f7 = -Feedback(tf4*tf6, TransferFunction(1, 1, p))
assert f7.args == (Series(TransferFunction(-1, 1, p), Series(tf4, tf6)), -TransferFunction(1, 1, p), -1)
assert f7.sys1 == Series(TransferFunction(-1, 1, p), Series(tf4, tf6))
# denominator can't be a Parallel instance
raises(TypeError, lambda: Feedback(tf1, tf2 + tf3))
raises(TypeError, lambda: Feedback(tf1, Matrix([1, 2, 3])))
raises(TypeError, lambda: Feedback(TransferFunction(1, 1, s), s - 1))
raises(TypeError, lambda: Feedback(1, 1))
# raises(ValueError, lambda: Feedback(TransferFunction(1, 1, s), TransferFunction(1, 1, s)))
raises(ValueError, lambda: Feedback(tf2, tf4*tf5))
raises(ValueError, lambda: Feedback(tf2, tf1, 1.5)) # `sign` can only be -1 or 1
raises(ValueError, lambda: Feedback(tf1, -tf1**-1)) # denominator can't be zero
raises(ValueError, lambda: Feedback(tf4, tf5)) # Both systems should use the same `var`
def test_Feedback_functions():
tf = TransferFunction(1, 1, s)
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tf2 = TransferFunction(k, 1, s)
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
tf6 = TransferFunction(s - p, p + s, p)
assert tf / (tf + tf1) == Feedback(tf, tf1)
assert tf / (tf + tf1*tf2*tf3) == Feedback(tf, tf1*tf2*tf3)
assert tf1 / (tf + tf1*tf2*tf3) == Feedback(tf1, tf2*tf3)
assert (tf1*tf2) / (tf + tf1*tf2) == Feedback(tf1*tf2, tf)
assert (tf1*tf2) / (tf + tf1*tf2*tf5) == Feedback(tf1*tf2, tf5)
assert (tf1*tf2) / (tf + tf1*tf2*tf5*tf3) in (Feedback(tf1*tf2, tf5*tf3), Feedback(tf1*tf2, tf3*tf5))
assert tf4 / (TransferFunction(1, 1, p) + tf4*tf6) == Feedback(tf4, tf6)
assert tf5 / (tf + tf5) == Feedback(tf5, tf)
raises(TypeError, lambda: tf1*tf2*tf3 / (1 + tf1*tf2*tf3))
raises(ValueError, lambda: tf1*tf2*tf3 / tf3*tf5)
raises(ValueError, lambda: tf2*tf3 / (tf + tf2*tf3*tf4))
assert Feedback(tf, tf1*tf2*tf3).doit() == \
TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), k*(a2*p - s) + \
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Feedback(tf, tf1*tf2*tf3).sensitivity == \
1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
assert Feedback(tf1, tf2*tf3).doit() == \
TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (k*(a2*p - s) + \
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Feedback(tf1, tf2*tf3).sensitivity == \
1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
assert Feedback(tf1*tf2, tf5).doit() == \
TransferFunction(k*(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \
(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Feedback(tf1*tf2, tf5, 1).sensitivity == \
1/(-k*(-a0 + a1*s**2 + a2*s)/((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
assert Feedback(tf4, tf6).doit() == \
TransferFunction(p*(p + s)*(a0*p + p**a1 - s), p*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p)
assert -Feedback(tf4*tf6, TransferFunction(1, 1, p)).doit() == \
TransferFunction(-p*(-p + s)*(p + s)*(a0*p + p**a1 - s), p*(p + s)*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p)
assert Feedback(tf, tf).doit() == TransferFunction(1, 2, s)
assert Feedback(tf1, tf2*tf5).rewrite(TransferFunction) == \
TransferFunction((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \
(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Feedback(TransferFunction(1, 1, p), tf4).rewrite(TransferFunction) == \
TransferFunction(p, a0*p + p + p**a1 - s, p)
def test_MIMOFeedback_construction():
tf1 = TransferFunction(1, s, s)
tf2 = TransferFunction(s, s**3 - 1, s)
tf3 = TransferFunction(s, s + 1, s)
tf4 = TransferFunction(s, s**2 + 1, s)
tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]])
tfm_3 = TransferFunctionMatrix([[tf3, tf4], [tf1, tf2]])
f1 = MIMOFeedback(tfm_1, tfm_2)
assert f1.args == (tfm_1, tfm_2, -1)
assert f1.sys1 == tfm_1
assert f1.sys2 == tfm_2
assert f1.var == s
assert f1.sign == -1
assert -(-f1) == f1
f2 = MIMOFeedback(tfm_2, tfm_1, 1)
assert f2.args == (tfm_2, tfm_1, 1)
assert f2.sys1 == tfm_2
assert f2.sys2 == tfm_1
assert f2.var == s
assert f2.sign == 1
f3 = MIMOFeedback(tfm_1, MIMOSeries(tfm_3, tfm_2))
assert f3.args == (tfm_1, MIMOSeries(tfm_3, tfm_2), -1)
assert f3.sys1 == tfm_1
assert f3.sys2 == MIMOSeries(tfm_3, tfm_2)
assert f3.var == s
assert f3.sign == -1
mat = Matrix([[1, 1/s], [0, 1]])
sys1 = controller = TransferFunctionMatrix.from_Matrix(mat, s)
f4 = MIMOFeedback(sys1, controller)
assert f4.args == (sys1, controller, -1)
assert f4.sys1 == f4.sys2 == sys1
def test_MIMOFeedback_errors():
tf1 = TransferFunction(1, s, s)
tf2 = TransferFunction(s, s**3 - 1, s)
tf3 = TransferFunction(s, s - 1, s)
tf4 = TransferFunction(s, s**2 + 1, s)
tf5 = TransferFunction(1, 1, s)
tf6 = TransferFunction(-1, s - 1, s)
tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]])
tfm_3 = TransferFunctionMatrix.from_Matrix(eye(2), var=s)
tfm_4 = TransferFunctionMatrix([[tf1, tf5], [tf5, tf5]])
tfm_5 = TransferFunctionMatrix([[-tf3, tf3], [tf3, tf6]])
# tfm_4 is inverse of tfm_5. Therefore tfm_5*tfm_4 = I
tfm_6 = TransferFunctionMatrix([[-tf3]])
tfm_7 = TransferFunctionMatrix([[tf3, tf4]])
# Unsupported Types
raises(TypeError, lambda: MIMOFeedback(tf1, tf2))
raises(TypeError, lambda: MIMOFeedback(MIMOParallel(tfm_1, tfm_2), tfm_3))
# Shape Errors
raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_6, 1))
raises(ValueError, lambda: MIMOFeedback(tfm_7, tfm_7))
# sign not 1/-1
raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_2, -2))
# Non-Invertible Systems
raises(ValueError, lambda: MIMOFeedback(tfm_5, tfm_4, 1))
raises(ValueError, lambda: MIMOFeedback(tfm_4, -tfm_5))
raises(ValueError, lambda: MIMOFeedback(tfm_3, tfm_3, 1))
# Variable not same in both the systems
tfm_8 = TransferFunctionMatrix.from_Matrix(eye(2), var=p)
raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_8, 1))
def test_MIMOFeedback_functions():
tf1 = TransferFunction(1, s, s)
tf2 = TransferFunction(s, s - 1, s)
tf3 = TransferFunction(1, 1, s)
tf4 = TransferFunction(-1, s - 1, s)
tfm_1 = TransferFunctionMatrix.from_Matrix(eye(2), var=s)
tfm_2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf3]])
tfm_3 = TransferFunctionMatrix([[-tf2, tf2], [tf2, tf4]])
tfm_4 = TransferFunctionMatrix([[tf1, tf2], [-tf2, tf1]])
# sensitivity, doit(), rewrite()
F_1 = MIMOFeedback(tfm_2, tfm_3)
F_2 = MIMOFeedback(tfm_2, MIMOSeries(tfm_4, -tfm_1), 1)
assert F_1.sensitivity == Matrix([[S.Half, 0], [0, S.Half]])
assert F_2.sensitivity == Matrix([[(-2*s**4 + s**2)/(s**2 - s + 1),
(2*s**3 - s**2)/(s**2 - s + 1)], [-s**2, s]])
assert F_1.doit() == \
TransferFunctionMatrix(((TransferFunction(1, 2*s, s),
TransferFunction(1, 2, s)), (TransferFunction(1, 2, s),
TransferFunction(1, 2, s)))) == F_1.rewrite(TransferFunctionMatrix)
assert F_2.doit(cancel=False, expand=True) == \
TransferFunctionMatrix(((TransferFunction(-s**5 + 2*s**4 - 2*s**3 + s**2, s**5 - 2*s**4 + 3*s**3 - 2*s**2 + s, s),
TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
assert F_2.doit(cancel=False) == \
TransferFunctionMatrix(((TransferFunction(s*(2*s**3 - s**2)*(s**2 - s + 1) + \
(-2*s**4 + s**2)*(s**2 - s + 1), s*(s**2 - s + 1)**2, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)),
(TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
assert F_2.doit() == \
TransferFunctionMatrix(((TransferFunction(s*(-2*s**2 + s*(2*s - 1) + 1), s**2 - s + 1, s),
TransferFunction(-2*s**3*(s - 1), s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(s*(1 - s), 1, s))))
assert F_2.doit(expand=True) == \
TransferFunctionMatrix(((TransferFunction(-s**2 + s, s**2 - s + 1, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)),
(TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
assert -(F_1.doit()) == (-F_1).doit() # First negating then calculating vs calculating then negating.
def test_TransferFunctionMatrix_construction():
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tfm3_ = TransferFunctionMatrix([[-TF3]])
assert tfm3_.shape == (tfm3_.num_outputs, tfm3_.num_inputs) == (1, 1)
assert tfm3_.args == Tuple(Tuple(Tuple(-TF3)))
assert tfm3_.var == s
tfm5 = TransferFunctionMatrix([[TF1, -TF2], [TF3, tf5]])
assert tfm5.shape == (tfm5.num_outputs, tfm5.num_inputs) == (2, 2)
assert tfm5.args == Tuple(Tuple(Tuple(TF1, -TF2), Tuple(TF3, tf5)))
assert tfm5.var == s
tfm7 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5], [-tf5, TF2]])
assert tfm7.shape == (tfm7.num_outputs, tfm7.num_inputs) == (3, 2)
assert tfm7.args == Tuple(Tuple(Tuple(TF1, TF2), Tuple(TF3, -tf5), Tuple(-tf5, TF2)))
assert tfm7.var == s
# all transfer functions will use the same complex variable. tf4 uses 'p'.
raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF2], [tf4]]))
raises(ValueError, lambda: TransferFunctionMatrix([[TF1, tf4], [TF3, tf5]]))
# length of all the lists in the TFM should be equal.
raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF3, tf5]]))
raises(ValueError, lambda: TransferFunctionMatrix([[TF1, TF3], [tf5]]))
# lists should only support transfer functions in them.
raises(TypeError, lambda: TransferFunctionMatrix([[TF1, TF2], [TF3, Matrix([1, 2])]]))
raises(TypeError, lambda: TransferFunctionMatrix([[TF1, Matrix([1, 2])], [TF3, TF2]]))
# `arg` should strictly be nested list of TransferFunction
raises(ValueError, lambda: TransferFunctionMatrix([TF1, TF2, tf5]))
raises(ValueError, lambda: TransferFunctionMatrix([TF1]))
def test_TransferFunctionMatrix_functions():
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
# Classmethod (from_matrix)
mat_1 = ImmutableMatrix([
[s*(s + 1)*(s - 3)/(s**4 + 1), 2],
[p, p*(s + 1)/(s*(s**1 + 1))]
])
mat_2 = ImmutableMatrix([[(2*s + 1)/(s**2 - 9)]])
mat_3 = ImmutableMatrix([[1, 2], [3, 4]])
assert TransferFunctionMatrix.from_Matrix(mat_1, s) == \
TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)],
[TransferFunction(p, 1, s), TransferFunction(p, s, s)]])
assert TransferFunctionMatrix.from_Matrix(mat_2, s) == \
TransferFunctionMatrix([[TransferFunction(2*s + 1, s**2 - 9, s)]])
assert TransferFunctionMatrix.from_Matrix(mat_3, p) == \
TransferFunctionMatrix([[TransferFunction(1, 1, p), TransferFunction(2, 1, p)],
[TransferFunction(3, 1, p), TransferFunction(4, 1, p)]])
# Negating a TFM
tfm1 = TransferFunctionMatrix([[TF1], [TF2]])
assert -tfm1 == TransferFunctionMatrix([[-TF1], [-TF2]])
tfm2 = TransferFunctionMatrix([[TF1, TF2, TF3], [tf5, -TF1, -TF3]])
assert -tfm2 == TransferFunctionMatrix([[-TF1, -TF2, -TF3], [-tf5, TF1, TF3]])
# subs()
H_1 = TransferFunctionMatrix.from_Matrix(mat_1, s)
H_2 = TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(s**2 - a), s)]])
assert H_1.subs(p, 1) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]])
assert H_1.subs({p: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]])
assert H_1.subs({p: 1, s: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]]) # This should ignore `s` as it is `var`
assert H_2.subs(p, 2) == TransferFunctionMatrix([[TransferFunction(2*a*s, k*s**2, s), TransferFunction(2*s, k*(-a + s**2), s)]])
assert H_2.subs(k, 1) == TransferFunctionMatrix([[TransferFunction(a*p*s, s**2, s), TransferFunction(p*s, -a + s**2, s)]])
assert H_2.subs(a, 0) == TransferFunctionMatrix([[TransferFunction(0, k*s**2, s), TransferFunction(p*s, k*s**2, s)]])
assert H_2.subs({p: 1, k: 1, a: a0}) == TransferFunctionMatrix([[TransferFunction(a0*s, s**2, s), TransferFunction(s, -a0 + s**2, s)]])
# transpose()
assert H_1.transpose() == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(p, 1, s)], [TransferFunction(2, 1, s), TransferFunction(p, s, s)]])
assert H_2.transpose() == TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s)], [TransferFunction(p*s, k*(-a + s**2), s)]])
assert H_1.transpose().transpose() == H_1
assert H_2.transpose().transpose() == H_2
# elem_poles()
assert H_1.elem_poles() == [[[-sqrt(2)/2 - sqrt(2)*I/2, -sqrt(2)/2 + sqrt(2)*I/2, sqrt(2)/2 - sqrt(2)*I/2, sqrt(2)/2 + sqrt(2)*I/2], []],
[[], [0]]]
assert H_2.elem_poles() == [[[0, 0], [sqrt(a), -sqrt(a)]]]
assert tfm2.elem_poles() == [[[wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [], [-p/a2]],
[[-a0], [wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [-p/a2]]]
# elem_zeros()
assert H_1.elem_zeros() == [[[-1, 0, 3], []], [[], []]]
assert H_2.elem_zeros() == [[[0], [0]]]
assert tfm2.elem_zeros() == [[[], [], [a2*p]],
[[-a2/(2*a1) - sqrt(4*a0*a1 + a2**2)/(2*a1), -a2/(2*a1) + sqrt(4*a0*a1 + a2**2)/(2*a1)], [], [a2*p]]]
# doit()
H_3 = TransferFunctionMatrix([[Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]])
H_4 = TransferFunctionMatrix([[Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]])
assert H_3.doit() == TransferFunctionMatrix([[TransferFunction(s**2 - 2*s + 5, s*(s**3 - 3), s)]])
assert H_4.doit() == TransferFunctionMatrix([[TransferFunction(1, 4*s**4 - s**2 - 2*s + 5, s)]])
# _flat()
assert H_1._flat() == [TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s), TransferFunction(p, 1, s), TransferFunction(p, s, s)]
assert H_2._flat() == [TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(-a + s**2), s)]
assert H_3._flat() == [Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]
assert H_4._flat() == [Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]
# evalf()
assert H_1.evalf() == \
TransferFunctionMatrix(((TransferFunction(s*(s - 3.0)*(s + 1.0), s**4 + 1.0, s), TransferFunction(2.0, 1, s)), (TransferFunction(1.0*p, 1, s), TransferFunction(p, s, s))))
assert H_2.subs({a:3.141, p:2.88, k:2}).evalf() == \
TransferFunctionMatrix(((TransferFunction(4.5230399999999999494093572138808667659759521484375, s, s),
TransferFunction(2.87999999999999989341858963598497211933135986328125*s, 2.0*s**2 - 6.282000000000000028421709430404007434844970703125, s)),))
# simplify()
H_5 = TransferFunctionMatrix([[TransferFunction(s**5 + s**3 + s, s - s**2, s),
TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)]])
assert H_5.simplify() == simplify(H_5) == \
TransferFunctionMatrix(((TransferFunction(-s**4 - s**2 - 1, s - 1, s), TransferFunction(s + 3, s + 5, s)),))
# expand()
assert (H_1.expand()
== TransferFunctionMatrix(((TransferFunction(s**3 - 2*s**2 - 3*s, s**4 + 1, s), TransferFunction(2, 1, s)),
(TransferFunction(p, 1, s), TransferFunction(p, s, s)))))
assert H_5.expand() == \
TransferFunctionMatrix(((TransferFunction(s**5 + s**3 + s, -s**2 + s, s), TransferFunction(s**2 + 2*s - 3, s**2 + 4*s - 5, s)),))
def test_TransferFunction_bilinear():
# simple transfer function, e.g. ohms law
tf = TransferFunction(1, a*s+b, s)
numZ, denZ = bilinear(tf, T)
# discretized transfer function with coefs from tf.bilinear()
tf_test_bilinear = TransferFunction(s*numZ[0]+numZ[1], s*denZ[0]+denZ[1], s)
# corresponding tf with manually calculated coefs
tf_test_manual = TransferFunction(s*T+T, s*(T*b+2*a)+T*b-2*a, s)
assert S.Zero == (tf_test_bilinear-tf_test_manual).simplify().num
|
132c62120c9cd270d2c1e270234254c2d6bb819f354d51c297b603128b13aef2 | from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import log
from sympy.external import import_module
from sympy.physics.quantum.density import Density, entropy, fidelity
from sympy.physics.quantum.state import Ket, TimeDepKet
from sympy.physics.quantum.qubit import Qubit
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.cartesian import XKet, PxKet, PxOp, XOp
from sympy.physics.quantum.spin import JzKet
from sympy.physics.quantum.operator import OuterProduct
from sympy.physics.quantum.trace import Tr
from sympy.functions import sqrt
from sympy.testing.pytest import raises
from sympy.physics.quantum.matrixutils import scipy_sparse_matrix
from sympy.physics.quantum.tensorproduct import TensorProduct
def test_eval_args():
# check instance created
assert isinstance(Density([Ket(0), 0.5], [Ket(1), 0.5]), Density)
assert isinstance(Density([Qubit('00'), 1/sqrt(2)],
[Qubit('11'), 1/sqrt(2)]), Density)
#test if Qubit object type preserved
d = Density([Qubit('00'), 1/sqrt(2)], [Qubit('11'), 1/sqrt(2)])
for (state, prob) in d.args:
assert isinstance(state, Qubit)
# check for value error, when prob is not provided
raises(ValueError, lambda: Density([Ket(0)], [Ket(1)]))
def test_doit():
x, y = symbols('x y')
A, B, C, D, E, F = symbols('A B C D E F', commutative=False)
d = Density([XKet(), 0.5], [PxKet(), 0.5])
assert (0.5*(PxKet()*Dagger(PxKet())) +
0.5*(XKet()*Dagger(XKet()))) == d.doit()
# check for kets with expr in them
d_with_sym = Density([XKet(x*y), 0.5], [PxKet(x*y), 0.5])
assert (0.5*(PxKet(x*y)*Dagger(PxKet(x*y))) +
0.5*(XKet(x*y)*Dagger(XKet(x*y)))) == d_with_sym.doit()
d = Density([(A + B)*C, 1.0])
assert d.doit() == (1.0*A*C*Dagger(C)*Dagger(A) +
1.0*A*C*Dagger(C)*Dagger(B) +
1.0*B*C*Dagger(C)*Dagger(A) +
1.0*B*C*Dagger(C)*Dagger(B))
# With TensorProducts as args
# Density with simple tensor products as args
t = TensorProduct(A, B, C)
d = Density([t, 1.0])
assert d.doit() == \
1.0 * TensorProduct(A*Dagger(A), B*Dagger(B), C*Dagger(C))
# Density with multiple Tensorproducts as states
t2 = TensorProduct(A, B)
t3 = TensorProduct(C, D)
d = Density([t2, 0.5], [t3, 0.5])
assert d.doit() == (0.5 * TensorProduct(A*Dagger(A), B*Dagger(B)) +
0.5 * TensorProduct(C*Dagger(C), D*Dagger(D)))
#Density with mixed states
d = Density([t2 + t3, 1.0])
assert d.doit() == (1.0 * TensorProduct(A*Dagger(A), B*Dagger(B)) +
1.0 * TensorProduct(A*Dagger(C), B*Dagger(D)) +
1.0 * TensorProduct(C*Dagger(A), D*Dagger(B)) +
1.0 * TensorProduct(C*Dagger(C), D*Dagger(D)))
#Density operators with spin states
tp1 = TensorProduct(JzKet(1, 1), JzKet(1, -1))
d = Density([tp1, 1])
# full trace
t = Tr(d)
assert t.doit() == 1
#Partial trace on density operators with spin states
t = Tr(d, [0])
assert t.doit() == JzKet(1, -1) * Dagger(JzKet(1, -1))
t = Tr(d, [1])
assert t.doit() == JzKet(1, 1) * Dagger(JzKet(1, 1))
# with another spin state
tp2 = TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))
d = Density([tp2, 1])
#full trace
t = Tr(d)
assert t.doit() == 1
#Partial trace on density operators with spin states
t = Tr(d, [0])
assert t.doit() == JzKet(S.Half, Rational(-1, 2)) * Dagger(JzKet(S.Half, Rational(-1, 2)))
t = Tr(d, [1])
assert t.doit() == JzKet(S.Half, S.Half) * Dagger(JzKet(S.Half, S.Half))
def test_apply_op():
d = Density([Ket(0), 0.5], [Ket(1), 0.5])
assert d.apply_op(XOp()) == Density([XOp()*Ket(0), 0.5],
[XOp()*Ket(1), 0.5])
def test_represent():
x, y = symbols('x y')
d = Density([XKet(), 0.5], [PxKet(), 0.5])
assert (represent(0.5*(PxKet()*Dagger(PxKet()))) +
represent(0.5*(XKet()*Dagger(XKet())))) == represent(d)
# check for kets with expr in them
d_with_sym = Density([XKet(x*y), 0.5], [PxKet(x*y), 0.5])
assert (represent(0.5*(PxKet(x*y)*Dagger(PxKet(x*y)))) +
represent(0.5*(XKet(x*y)*Dagger(XKet(x*y))))) == \
represent(d_with_sym)
# check when given explicit basis
assert (represent(0.5*(XKet()*Dagger(XKet())), basis=PxOp()) +
represent(0.5*(PxKet()*Dagger(PxKet())), basis=PxOp())) == \
represent(d, basis=PxOp())
def test_states():
d = Density([Ket(0), 0.5], [Ket(1), 0.5])
states = d.states()
assert states[0] == Ket(0) and states[1] == Ket(1)
def test_probs():
d = Density([Ket(0), .75], [Ket(1), 0.25])
probs = d.probs()
assert probs[0] == 0.75 and probs[1] == 0.25
#probs can be symbols
x, y = symbols('x y')
d = Density([Ket(0), x], [Ket(1), y])
probs = d.probs()
assert probs[0] == x and probs[1] == y
def test_get_state():
x, y = symbols('x y')
d = Density([Ket(0), x], [Ket(1), y])
states = (d.get_state(0), d.get_state(1))
assert states[0] == Ket(0) and states[1] == Ket(1)
def test_get_prob():
x, y = symbols('x y')
d = Density([Ket(0), x], [Ket(1), y])
probs = (d.get_prob(0), d.get_prob(1))
assert probs[0] == x and probs[1] == y
def test_entropy():
up = JzKet(S.Half, S.Half)
down = JzKet(S.Half, Rational(-1, 2))
d = Density((up, S.Half), (down, S.Half))
# test for density object
ent = entropy(d)
assert entropy(d) == log(2)/2
assert d.entropy() == log(2)/2
np = import_module('numpy', min_module_version='1.4.0')
if np:
#do this test only if 'numpy' is available on test machine
np_mat = represent(d, format='numpy')
ent = entropy(np_mat)
assert isinstance(np_mat, np.ndarray)
assert ent.real == 0.69314718055994529
assert ent.imag == 0
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
if scipy and np:
#do this test only if numpy and scipy are available
mat = represent(d, format="scipy.sparse")
assert isinstance(mat, scipy_sparse_matrix)
assert ent.real == 0.69314718055994529
assert ent.imag == 0
def test_eval_trace():
up = JzKet(S.Half, S.Half)
down = JzKet(S.Half, Rational(-1, 2))
d = Density((up, 0.5), (down, 0.5))
t = Tr(d)
assert t.doit() == 1.0
#test dummy time dependent states
class TestTimeDepKet(TimeDepKet):
def _eval_trace(self, bra, **options):
return 1
x, t = symbols('x t')
k1 = TestTimeDepKet(0, 0.5)
k2 = TestTimeDepKet(0, 1)
d = Density([k1, 0.5], [k2, 0.5])
assert d.doit() == (0.5 * OuterProduct(k1, k1.dual) +
0.5 * OuterProduct(k2, k2.dual))
t = Tr(d)
assert t.doit() == 1.0
def test_fidelity():
#test with kets
up = JzKet(S.Half, S.Half)
down = JzKet(S.Half, Rational(-1, 2))
updown = (S.One/sqrt(2))*up + (S.One/sqrt(2))*down
#check with matrices
up_dm = represent(up * Dagger(up))
down_dm = represent(down * Dagger(down))
updown_dm = represent(updown * Dagger(updown))
assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3
assert fidelity(up_dm, down_dm) < 1e-3
assert abs(fidelity(up_dm, updown_dm) - (S.One/sqrt(2))) < 1e-3
assert abs(fidelity(updown_dm, down_dm) - (S.One/sqrt(2))) < 1e-3
#check with density
up_dm = Density([up, 1.0])
down_dm = Density([down, 1.0])
updown_dm = Density([updown, 1.0])
assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3
assert abs(fidelity(up_dm, down_dm)) < 1e-3
assert abs(fidelity(up_dm, updown_dm) - (S.One/sqrt(2))) < 1e-3
assert abs(fidelity(updown_dm, down_dm) - (S.One/sqrt(2))) < 1e-3
#check mixed states with density
updown2 = sqrt(3)/2*up + S.Half*down
d1 = Density([updown, 0.25], [updown2, 0.75])
d2 = Density([updown, 0.75], [updown2, 0.25])
assert abs(fidelity(d1, d2) - 0.991) < 1e-3
assert abs(fidelity(d2, d1) - fidelity(d1, d2)) < 1e-3
#using qubits/density(pure states)
state1 = Qubit('0')
state2 = Qubit('1')
state3 = S.One/sqrt(2)*state1 + S.One/sqrt(2)*state2
state4 = sqrt(Rational(2, 3))*state1 + S.One/sqrt(3)*state2
state1_dm = Density([state1, 1])
state2_dm = Density([state2, 1])
state3_dm = Density([state3, 1])
assert fidelity(state1_dm, state1_dm) == 1
assert fidelity(state1_dm, state2_dm) == 0
assert abs(fidelity(state1_dm, state3_dm) - 1/sqrt(2)) < 1e-3
assert abs(fidelity(state3_dm, state2_dm) - 1/sqrt(2)) < 1e-3
#using qubits/density(mixed states)
d1 = Density([state3, 0.70], [state4, 0.30])
d2 = Density([state3, 0.20], [state4, 0.80])
assert abs(fidelity(d1, d1) - 1) < 1e-3
assert abs(fidelity(d1, d2) - 0.996) < 1e-3
assert abs(fidelity(d1, d2) - fidelity(d2, d1)) < 1e-3
#TODO: test for invalid arguments
# non-square matrix
mat1 = [[0, 0],
[0, 0],
[0, 0]]
mat2 = [[0, 0],
[0, 0]]
raises(ValueError, lambda: fidelity(mat1, mat2))
# unequal dimensions
mat1 = [[0, 0],
[0, 0]]
mat2 = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
raises(ValueError, lambda: fidelity(mat1, mat2))
# unsupported data-type
x, y = 1, 2 # random values that is not a matrix
raises(ValueError, lambda: fidelity(x, y))
|
05935800d1f6c36c5f3a4a85037a084bf2a5d4a9f09c352ba15eddf6543721d6 | from sympy.core.function import (Derivative, Function, diff)
from sympy.core.mul import Mul
from sympy.core.numbers import (Integer, pi)
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.trigonometric import sin
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.hilbert import HilbertSpace
from sympy.physics.quantum.operator import (Operator, UnitaryOperator,
HermitianOperator, OuterProduct,
DifferentialOperator,
IdentityOperator)
from sympy.physics.quantum.state import Ket, Bra, Wavefunction
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.spin import JzKet, JzBra
from sympy.physics.quantum.trace import Tr
from sympy.matrices import eye
class CustomKet(Ket):
@classmethod
def default_args(self):
return ("t",)
class CustomOp(HermitianOperator):
@classmethod
def default_args(self):
return ("T",)
t_ket = CustomKet()
t_op = CustomOp()
def test_operator():
A = Operator('A')
B = Operator('B')
C = Operator('C')
assert isinstance(A, Operator)
assert isinstance(A, QExpr)
assert A.label == (Symbol('A'),)
assert A.is_commutative is False
assert A.hilbert_space == HilbertSpace()
assert A*B != B*A
assert (A*(B + C)).expand() == A*B + A*C
assert ((A + B)**2).expand() == A**2 + A*B + B*A + B**2
assert t_op.label[0] == Symbol(t_op.default_args()[0])
assert Operator() == Operator("O")
assert A*IdentityOperator() == A
def test_operator_inv():
A = Operator('A')
assert A*A.inv() == 1
assert A.inv()*A == 1
def test_hermitian():
H = HermitianOperator('H')
assert isinstance(H, HermitianOperator)
assert isinstance(H, Operator)
assert Dagger(H) == H
assert H.inv() != H
assert H.is_commutative is False
assert Dagger(H).is_commutative is False
def test_unitary():
U = UnitaryOperator('U')
assert isinstance(U, UnitaryOperator)
assert isinstance(U, Operator)
assert U.inv() == Dagger(U)
assert U*Dagger(U) == 1
assert Dagger(U)*U == 1
assert U.is_commutative is False
assert Dagger(U).is_commutative is False
def test_identity():
I = IdentityOperator()
O = Operator('O')
x = Symbol("x")
assert isinstance(I, IdentityOperator)
assert isinstance(I, Operator)
assert I * O == O
assert O * I == O
assert I * Dagger(O) == Dagger(O)
assert Dagger(O) * I == Dagger(O)
assert isinstance(I * I, IdentityOperator)
assert isinstance(3 * I, Mul)
assert isinstance(I * x, Mul)
assert I.inv() == I
assert Dagger(I) == I
assert qapply(I * O) == O
assert qapply(O * I) == O
for n in [2, 3, 5]:
assert represent(IdentityOperator(n)) == eye(n)
def test_outer_product():
k = Ket('k')
b = Bra('b')
op = OuterProduct(k, b)
assert isinstance(op, OuterProduct)
assert isinstance(op, Operator)
assert op.ket == k
assert op.bra == b
assert op.label == (k, b)
assert op.is_commutative is False
op = k*b
assert isinstance(op, OuterProduct)
assert isinstance(op, Operator)
assert op.ket == k
assert op.bra == b
assert op.label == (k, b)
assert op.is_commutative is False
op = 2*k*b
assert op == Mul(Integer(2), k, b)
op = 2*(k*b)
assert op == Mul(Integer(2), OuterProduct(k, b))
assert Dagger(k*b) == OuterProduct(Dagger(b), Dagger(k))
assert Dagger(k*b).is_commutative is False
#test the _eval_trace
assert Tr(OuterProduct(JzKet(1, 1), JzBra(1, 1))).doit() == 1
# test scaled kets and bras
assert OuterProduct(2 * k, b) == 2 * OuterProduct(k, b)
assert OuterProduct(k, 2 * b) == 2 * OuterProduct(k, b)
# test sums of kets and bras
k1, k2 = Ket('k1'), Ket('k2')
b1, b2 = Bra('b1'), Bra('b2')
assert (OuterProduct(k1 + k2, b1) ==
OuterProduct(k1, b1) + OuterProduct(k2, b1))
assert (OuterProduct(k1, b1 + b2) ==
OuterProduct(k1, b1) + OuterProduct(k1, b2))
assert (OuterProduct(1 * k1 + 2 * k2, 3 * b1 + 4 * b2) ==
3 * OuterProduct(k1, b1) +
4 * OuterProduct(k1, b2) +
6 * OuterProduct(k2, b1) +
8 * OuterProduct(k2, b2))
def test_operator_dagger():
A = Operator('A')
B = Operator('B')
assert Dagger(A*B) == Dagger(B)*Dagger(A)
assert Dagger(A + B) == Dagger(A) + Dagger(B)
assert Dagger(A**2) == Dagger(A)**2
def test_differential_operator():
x = Symbol('x')
f = Function('f')
d = DifferentialOperator(Derivative(f(x), x), f(x))
g = Wavefunction(x**2, x)
assert qapply(d*g) == Wavefunction(2*x, x)
assert d.expr == Derivative(f(x), x)
assert d.function == f(x)
assert d.variables == (x,)
assert diff(d, x) == DifferentialOperator(Derivative(f(x), x, 2), f(x))
d = DifferentialOperator(Derivative(f(x), x, 2), f(x))
g = Wavefunction(x**3, x)
assert qapply(d*g) == Wavefunction(6*x, x)
assert d.expr == Derivative(f(x), x, 2)
assert d.function == f(x)
assert d.variables == (x,)
assert diff(d, x) == DifferentialOperator(Derivative(f(x), x, 3), f(x))
d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
assert d.expr == 1/x*Derivative(f(x), x)
assert d.function == f(x)
assert d.variables == (x,)
assert diff(d, x) == \
DifferentialOperator(Derivative(1/x*Derivative(f(x), x), x), f(x))
assert qapply(d*g) == Wavefunction(3*x, x)
# 2D cartesian Laplacian
y = Symbol('y')
d = DifferentialOperator(Derivative(f(x, y), x, 2) +
Derivative(f(x, y), y, 2), f(x, y))
w = Wavefunction(x**3*y**2 + y**3*x**2, x, y)
assert d.expr == Derivative(f(x, y), x, 2) + Derivative(f(x, y), y, 2)
assert d.function == f(x, y)
assert d.variables == (x, y)
assert diff(d, x) == \
DifferentialOperator(Derivative(d.expr, x), f(x, y))
assert diff(d, y) == \
DifferentialOperator(Derivative(d.expr, y), f(x, y))
assert qapply(d*w) == Wavefunction(2*x**3 + 6*x*y**2 + 6*x**2*y + 2*y**3,
x, y)
# 2D polar Laplacian (th = theta)
r, th = symbols('r th')
d = DifferentialOperator(1/r*Derivative(r*Derivative(f(r, th), r), r) +
1/(r**2)*Derivative(f(r, th), th, 2), f(r, th))
w = Wavefunction(r**2*sin(th), r, (th, 0, pi))
assert d.expr == \
1/r*Derivative(r*Derivative(f(r, th), r), r) + \
1/(r**2)*Derivative(f(r, th), th, 2)
assert d.function == f(r, th)
assert d.variables == (r, th)
assert diff(d, r) == \
DifferentialOperator(Derivative(d.expr, r), f(r, th))
assert diff(d, th) == \
DifferentialOperator(Derivative(d.expr, th), f(r, th))
assert qapply(d*w) == Wavefunction(3*sin(th), r, (th, 0, pi))
def test_eval_power():
from sympy.core import Pow
from sympy.core.expr import unchanged
O = Operator('O')
U = UnitaryOperator('U')
H = HermitianOperator('H')
assert O**-1 == O.inv() # same as doc test
assert U**-1 == U.inv()
assert H**-1 == H.inv()
x = symbols("x", commutative = True)
assert unchanged(Pow, H, x) # verify Pow(H,x)=="X^n"
assert H**x == Pow(H, x)
assert Pow(H,x) == Pow(H, x, evaluate=False) # Just check
from sympy.physics.quantum.gate import XGate
X = XGate(0) # is hermitian and unitary
assert unchanged(Pow, X, x) # verify Pow(X,x)=="X^x"
assert X**x == Pow(X, x)
assert Pow(X, x, evaluate=False) == Pow(X, x) # Just check
n = symbols("n", integer=True, even=True)
assert X**n == 1
n = symbols("n", integer=True, odd=True)
assert X**n == X
n = symbols("n", integer=True)
assert unchanged(Pow, X, n) # verify Pow(X,n)=="X^n"
assert X**n == Pow(X, n)
assert Pow(X, n, evaluate=False)==Pow(X, n) # Just check
assert X**4 == 1
assert X**7 == X
|
2d035a3aebd773e8254627d0065b176adb40401fb2287be634cc3af3f26833f7 | import random
from sympy.core.numbers import (Integer, Rational)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices.dense import Matrix
from sympy.physics.quantum.qubit import (measure_all, measure_partial,
matrix_to_qubit, matrix_to_density,
qubit_to_matrix, IntQubit,
IntQubitBra, QubitBra)
from sympy.physics.quantum.gate import (HadamardGate, CNOT, XGate, YGate,
ZGate, PhaseGate)
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.shor import Qubit
from sympy.testing.pytest import raises
from sympy.physics.quantum.density import Density
from sympy.physics.quantum.trace import Tr
x, y = symbols('x,y')
epsilon = .000001
def test_Qubit():
array = [0, 0, 1, 1, 0]
qb = Qubit('00110')
assert qb.flip(0) == Qubit('00111')
assert qb.flip(1) == Qubit('00100')
assert qb.flip(4) == Qubit('10110')
assert qb.qubit_values == (0, 0, 1, 1, 0)
assert qb.dimension == 5
for i in range(5):
assert qb[i] == array[4 - i]
assert len(qb) == 5
qb = Qubit('110')
def test_QubitBra():
qb = Qubit(0)
qb_bra = QubitBra(0)
assert qb.dual_class() == QubitBra
assert qb_bra.dual_class() == Qubit
qb = Qubit(1, 1, 0)
qb_bra = QubitBra(1, 1, 0)
assert represent(qb, nqubits=3).H == represent(qb_bra, nqubits=3)
qb = Qubit(0, 1)
qb_bra = QubitBra(1,0)
assert qb._eval_innerproduct_QubitBra(qb_bra) == Integer(0)
qb_bra = QubitBra(0, 1)
assert qb._eval_innerproduct_QubitBra(qb_bra) == Integer(1)
def test_IntQubit():
# issue 9136
iqb = IntQubit(0, nqubits=1)
assert qubit_to_matrix(Qubit('0')) == qubit_to_matrix(iqb)
qb = Qubit('1010')
assert qubit_to_matrix(IntQubit(qb)) == qubit_to_matrix(qb)
iqb = IntQubit(1, nqubits=1)
assert qubit_to_matrix(Qubit('1')) == qubit_to_matrix(iqb)
assert qubit_to_matrix(IntQubit(1)) == qubit_to_matrix(iqb)
iqb = IntQubit(7, nqubits=4)
assert qubit_to_matrix(Qubit('0111')) == qubit_to_matrix(iqb)
assert qubit_to_matrix(IntQubit(7, 4)) == qubit_to_matrix(iqb)
iqb = IntQubit(8)
assert iqb.as_int() == 8
assert iqb.qubit_values == (1, 0, 0, 0)
iqb = IntQubit(7, 4)
assert iqb.qubit_values == (0, 1, 1, 1)
assert IntQubit(3) == IntQubit(3, 2)
#test Dual Classes
iqb = IntQubit(3)
iqb_bra = IntQubitBra(3)
assert iqb.dual_class() == IntQubitBra
assert iqb_bra.dual_class() == IntQubit
iqb = IntQubit(5)
iqb_bra = IntQubitBra(5)
assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(1)
iqb = IntQubit(4)
iqb_bra = IntQubitBra(5)
assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(0)
raises(ValueError, lambda: IntQubit(4, 1))
raises(ValueError, lambda: IntQubit('5'))
raises(ValueError, lambda: IntQubit(5, '5'))
raises(ValueError, lambda: IntQubit(5, nqubits='5'))
raises(TypeError, lambda: IntQubit(5, bad_arg=True))
def test_superposition_of_states():
state = 1/sqrt(2)*Qubit('01') + 1/sqrt(2)*Qubit('10')
state_gate = CNOT(0, 1)*HadamardGate(0)*state
state_expanded = Qubit('01')/2 + Qubit('00')/2 - Qubit('11')/2 + Qubit('10')/2
assert qapply(state_gate).expand() == state_expanded
assert matrix_to_qubit(represent(state_gate, nqubits=2)) == state_expanded
#test apply methods
def test_apply_represent_equality():
gates = [HadamardGate(int(3*random.random())),
XGate(int(3*random.random())), ZGate(int(3*random.random())),
YGate(int(3*random.random())), ZGate(int(3*random.random())),
PhaseGate(int(3*random.random()))]
circuit = Qubit(int(random.random()*2), int(random.random()*2),
int(random.random()*2), int(random.random()*2), int(random.random()*2),
int(random.random()*2))
for i in range(int(random.random()*6)):
circuit = gates[int(random.random()*6)]*circuit
mat = represent(circuit, nqubits=6)
states = qapply(circuit)
state_rep = matrix_to_qubit(mat)
states = states.expand()
state_rep = state_rep.expand()
assert state_rep == states
def test_matrix_to_qubits():
qb = Qubit(0, 0, 0, 0)
mat = Matrix([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
assert matrix_to_qubit(mat) == qb
assert qubit_to_matrix(qb) == mat
state = 2*sqrt(2)*(Qubit(0, 0, 0) + Qubit(0, 0, 1) + Qubit(0, 1, 0) +
Qubit(0, 1, 1) + Qubit(1, 0, 0) + Qubit(1, 0, 1) +
Qubit(1, 1, 0) + Qubit(1, 1, 1))
ones = sqrt(2)*2*Matrix([1, 1, 1, 1, 1, 1, 1, 1])
assert matrix_to_qubit(ones) == state.expand()
assert qubit_to_matrix(state) == ones
def test_measure_normalize():
a, b = symbols('a b')
state = a*Qubit('110') + b*Qubit('111')
assert measure_partial(state, (0,), normalize=False) == \
[(a*Qubit('110'), a*a.conjugate()), (b*Qubit('111'), b*b.conjugate())]
assert measure_all(state, normalize=False) == \
[(Qubit('110'), a*a.conjugate()), (Qubit('111'), b*b.conjugate())]
def test_measure_partial():
#Basic test of collapse of entangled two qubits (Bell States)
state = Qubit('01') + Qubit('10')
assert measure_partial(state, (0,)) == \
[(Qubit('10'), S.Half), (Qubit('01'), S.Half)]
assert measure_partial(state, int(0)) == \
[(Qubit('10'), S.Half), (Qubit('01'), S.Half)]
assert measure_partial(state, (0,)) == \
measure_partial(state, (1,))[::-1]
#Test of more complex collapse and probability calculation
state1 = sqrt(2)/sqrt(3)*Qubit('00001') + 1/sqrt(3)*Qubit('11111')
assert measure_partial(state1, (0,)) == \
[(sqrt(2)/sqrt(3)*Qubit('00001') + 1/sqrt(3)*Qubit('11111'), 1)]
assert measure_partial(state1, (1, 2)) == measure_partial(state1, (3, 4))
assert measure_partial(state1, (1, 2, 3)) == \
[(Qubit('00001'), Rational(2, 3)), (Qubit('11111'), Rational(1, 3))]
#test of measuring multiple bits at once
state2 = Qubit('1111') + Qubit('1101') + Qubit('1011') + Qubit('1000')
assert measure_partial(state2, (0, 1, 3)) == \
[(Qubit('1000'), Rational(1, 4)), (Qubit('1101'), Rational(1, 4)),
(Qubit('1011')/sqrt(2) + Qubit('1111')/sqrt(2), S.Half)]
assert measure_partial(state2, (0,)) == \
[(Qubit('1000'), Rational(1, 4)),
(Qubit('1111')/sqrt(3) + Qubit('1101')/sqrt(3) +
Qubit('1011')/sqrt(3), Rational(3, 4))]
def test_measure_all():
assert measure_all(Qubit('11')) == [(Qubit('11'), 1)]
state = Qubit('11') + Qubit('10')
assert measure_all(state) == [(Qubit('10'), S.Half),
(Qubit('11'), S.Half)]
state2 = Qubit('11')/sqrt(5) + 2*Qubit('00')/sqrt(5)
assert measure_all(state2) == \
[(Qubit('00'), Rational(4, 5)), (Qubit('11'), Rational(1, 5))]
# from issue #12585
assert measure_all(qapply(Qubit('0'))) == [(Qubit('0'), 1)]
def test_eval_trace():
q1 = Qubit('10110')
q2 = Qubit('01010')
d = Density([q1, 0.6], [q2, 0.4])
t = Tr(d)
assert t.doit() == 1.0
# extreme bits
t = Tr(d, 0)
assert t.doit() == (0.4*Density([Qubit('0101'), 1]) +
0.6*Density([Qubit('1011'), 1]))
t = Tr(d, 4)
assert t.doit() == (0.4*Density([Qubit('1010'), 1]) +
0.6*Density([Qubit('0110'), 1]))
# index somewhere in between
t = Tr(d, 2)
assert t.doit() == (0.4*Density([Qubit('0110'), 1]) +
0.6*Density([Qubit('1010'), 1]))
#trace all indices
t = Tr(d, [0, 1, 2, 3, 4])
assert t.doit() == 1.0
# trace some indices, initialized in
# non-canonical order
t = Tr(d, [2, 1, 3])
assert t.doit() == (0.4*Density([Qubit('00'), 1]) +
0.6*Density([Qubit('10'), 1]))
# mixed states
q = (1/sqrt(2)) * (Qubit('00') + Qubit('11'))
d = Density( [q, 1.0] )
t = Tr(d, 0)
assert t.doit() == (0.5*Density([Qubit('0'), 1]) +
0.5*Density([Qubit('1'), 1]))
def test_matrix_to_density():
mat = Matrix([[0, 0], [0, 1]])
assert matrix_to_density(mat) == Density([Qubit('1'), 1])
mat = Matrix([[1, 0], [0, 0]])
assert matrix_to_density(mat) == Density([Qubit('0'), 1])
mat = Matrix([[0, 0], [0, 0]])
assert matrix_to_density(mat) == 0
mat = Matrix([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 0]])
assert matrix_to_density(mat) == Density([Qubit('10'), 1])
mat = Matrix([[1, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
assert matrix_to_density(mat) == Density([Qubit('00'), 1])
|
aeffe40854b5a76fbf78d8d7133755096e1fefcce98d374b3a0685a34668d037 | from sympy.core.backend import sin, cos, tan, pi, symbols, Matrix, S, Function
from sympy.physics.mechanics import (Particle, Point, ReferenceFrame,
RigidBody)
from sympy.physics.mechanics import (angular_momentum, dynamicsymbols,
inertia, inertia_of_point_mass,
kinetic_energy, linear_momentum,
outer, potential_energy, msubs,
find_dynamicsymbols, Lagrangian)
from sympy.physics.mechanics.functions import (gravity, center_of_mass,
_validate_coordinates)
from sympy.testing.pytest import raises
q1, q2, q3, q4, q5 = symbols('q1 q2 q3 q4 q5')
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [q1, N.z])
B = A.orientnew('B', 'Axis', [q2, A.x])
C = B.orientnew('C', 'Axis', [q3, B.y])
def test_inertia():
N = ReferenceFrame('N')
ixx, iyy, izz = symbols('ixx iyy izz')
ixy, iyz, izx = symbols('ixy iyz izx')
assert inertia(N, ixx, iyy, izz) == (ixx * (N.x | N.x) + iyy *
(N.y | N.y) + izz * (N.z | N.z))
assert inertia(N, 0, 0, 0) == 0 * (N.x | N.x)
raises(TypeError, lambda: inertia(0, 0, 0, 0))
assert inertia(N, ixx, iyy, izz, ixy, iyz, izx) == (ixx * (N.x | N.x) +
ixy * (N.x | N.y) + izx * (N.x | N.z) + ixy * (N.y | N.x) + iyy *
(N.y | N.y) + iyz * (N.y | N.z) + izx * (N.z | N.x) + iyz * (N.z |
N.y) + izz * (N.z | N.z))
def test_inertia_of_point_mass():
r, s, t, m = symbols('r s t m')
N = ReferenceFrame('N')
px = r * N.x
I = inertia_of_point_mass(m, px, N)
assert I == m * r**2 * (N.y | N.y) + m * r**2 * (N.z | N.z)
py = s * N.y
I = inertia_of_point_mass(m, py, N)
assert I == m * s**2 * (N.x | N.x) + m * s**2 * (N.z | N.z)
pz = t * N.z
I = inertia_of_point_mass(m, pz, N)
assert I == m * t**2 * (N.x | N.x) + m * t**2 * (N.y | N.y)
p = px + py + pz
I = inertia_of_point_mass(m, p, N)
assert I == (m * (s**2 + t**2) * (N.x | N.x) -
m * r * s * (N.x | N.y) -
m * r * t * (N.x | N.z) -
m * r * s * (N.y | N.x) +
m * (r**2 + t**2) * (N.y | N.y) -
m * s * t * (N.y | N.z) -
m * r * t * (N.z | N.x) -
m * s * t * (N.z | N.y) +
m * (r**2 + s**2) * (N.z | N.z))
def test_linear_momentum():
N = ReferenceFrame('N')
Ac = Point('Ac')
Ac.set_vel(N, 25 * N.y)
I = outer(N.x, N.x)
A = RigidBody('A', Ac, N, 20, (I, Ac))
P = Point('P')
Pa = Particle('Pa', P, 1)
Pa.point.set_vel(N, 10 * N.x)
raises(TypeError, lambda: linear_momentum(A, A, Pa))
raises(TypeError, lambda: linear_momentum(N, N, Pa))
assert linear_momentum(N, A, Pa) == 10 * N.x + 500 * N.y
def test_angular_momentum_and_linear_momentum():
"""A rod with length 2l, centroidal inertia I, and mass M along with a
particle of mass m fixed to the end of the rod rotate with an angular rate
of omega about point O which is fixed to the non-particle end of the rod.
The rod's reference frame is A and the inertial frame is N."""
m, M, l, I = symbols('m, M, l, I')
omega = dynamicsymbols('omega')
N = ReferenceFrame('N')
a = ReferenceFrame('a')
O = Point('O')
Ac = O.locatenew('Ac', l * N.x)
P = Ac.locatenew('P', l * N.x)
O.set_vel(N, 0 * N.x)
a.set_ang_vel(N, omega * N.z)
Ac.v2pt_theory(O, N, a)
P.v2pt_theory(O, N, a)
Pa = Particle('Pa', P, m)
A = RigidBody('A', Ac, a, M, (I * outer(N.z, N.z), Ac))
expected = 2 * m * omega * l * N.y + M * l * omega * N.y
assert linear_momentum(N, A, Pa) == expected
raises(TypeError, lambda: angular_momentum(N, N, A, Pa))
raises(TypeError, lambda: angular_momentum(O, O, A, Pa))
raises(TypeError, lambda: angular_momentum(O, N, O, Pa))
expected = (I + M * l**2 + 4 * m * l**2) * omega * N.z
assert angular_momentum(O, N, A, Pa) == expected
def test_kinetic_energy():
m, M, l1 = symbols('m M l1')
omega = dynamicsymbols('omega')
N = ReferenceFrame('N')
O = Point('O')
O.set_vel(N, 0 * N.x)
Ac = O.locatenew('Ac', l1 * N.x)
P = Ac.locatenew('P', l1 * N.x)
a = ReferenceFrame('a')
a.set_ang_vel(N, omega * N.z)
Ac.v2pt_theory(O, N, a)
P.v2pt_theory(O, N, a)
Pa = Particle('Pa', P, m)
I = outer(N.z, N.z)
A = RigidBody('A', Ac, a, M, (I, Ac))
raises(TypeError, lambda: kinetic_energy(Pa, Pa, A))
raises(TypeError, lambda: kinetic_energy(N, N, A))
assert 0 == (kinetic_energy(N, Pa, A) - (M*l1**2*omega**2/2
+ 2*l1**2*m*omega**2 + omega**2/2)).expand()
def test_potential_energy():
m, M, l1, g, h, H = symbols('m M l1 g h H')
omega = dynamicsymbols('omega')
N = ReferenceFrame('N')
O = Point('O')
O.set_vel(N, 0 * N.x)
Ac = O.locatenew('Ac', l1 * N.x)
P = Ac.locatenew('P', l1 * N.x)
a = ReferenceFrame('a')
a.set_ang_vel(N, omega * N.z)
Ac.v2pt_theory(O, N, a)
P.v2pt_theory(O, N, a)
Pa = Particle('Pa', P, m)
I = outer(N.z, N.z)
A = RigidBody('A', Ac, a, M, (I, Ac))
Pa.potential_energy = m * g * h
A.potential_energy = M * g * H
assert potential_energy(A, Pa) == m * g * h + M * g * H
def test_Lagrangian():
M, m, g, h = symbols('M m g h')
N = ReferenceFrame('N')
O = Point('O')
O.set_vel(N, 0 * N.x)
P = O.locatenew('P', 1 * N.x)
P.set_vel(N, 10 * N.x)
Pa = Particle('Pa', P, 1)
Ac = O.locatenew('Ac', 2 * N.y)
Ac.set_vel(N, 5 * N.y)
a = ReferenceFrame('a')
a.set_ang_vel(N, 10 * N.z)
I = outer(N.z, N.z)
A = RigidBody('A', Ac, a, 20, (I, Ac))
Pa.potential_energy = m * g * h
A.potential_energy = M * g * h
raises(TypeError, lambda: Lagrangian(A, A, Pa))
raises(TypeError, lambda: Lagrangian(N, N, Pa))
def test_msubs():
a, b = symbols('a, b')
x, y, z = dynamicsymbols('x, y, z')
# Test simple substitution
expr = Matrix([[a*x + b, x*y.diff() + y],
[x.diff().diff(), z + sin(z.diff())]])
sol = Matrix([[a + b, y],
[x.diff().diff(), 1]])
sd = {x: 1, z: 1, z.diff(): 0, y.diff(): 0}
assert msubs(expr, sd) == sol
# Test smart substitution
expr = cos(x + y)*tan(x + y) + b*x.diff()
sd = {x: 0, y: pi/2, x.diff(): 1}
assert msubs(expr, sd, smart=True) == b + 1
N = ReferenceFrame('N')
v = x*N.x + y*N.y
d = x*(N.x|N.x) + y*(N.y|N.y)
v_sol = 1*N.y
d_sol = 1*(N.y|N.y)
sd = {x: 0, y: 1}
assert msubs(v, sd) == v_sol
assert msubs(d, sd) == d_sol
def test_find_dynamicsymbols():
a, b = symbols('a, b')
x, y, z = dynamicsymbols('x, y, z')
expr = Matrix([[a*x + b, x*y.diff() + y],
[x.diff().diff(), z + sin(z.diff())]])
# Test finding all dynamicsymbols
sol = {x, y.diff(), y, x.diff().diff(), z, z.diff()}
assert find_dynamicsymbols(expr) == sol
# Test finding all but those in sym_list
exclude_list = [x, y, z]
sol = {y.diff(), x.diff().diff(), z.diff()}
assert find_dynamicsymbols(expr, exclude=exclude_list) == sol
# Test finding all dynamicsymbols in a vector with a given reference frame
d, e, f = dynamicsymbols('d, e, f')
A = ReferenceFrame('A')
v = d * A.x + e * A.y + f * A.z
sol = {d, e, f}
assert find_dynamicsymbols(v, reference_frame=A) == sol
# Test if a ValueError is raised on supplying only a vector as input
raises(ValueError, lambda: find_dynamicsymbols(v))
def test_gravity():
N = ReferenceFrame('N')
m, M, g = symbols('m M g')
F1, F2 = dynamicsymbols('F1 F2')
po = Point('po')
pa = Particle('pa', po, m)
A = ReferenceFrame('A')
P = Point('P')
I = outer(A.x, A.x)
B = RigidBody('B', P, A, M, (I, P))
forceList = [(po, F1), (P, F2)]
forceList.extend(gravity(g*N.y, pa, B))
l = [(po, F1), (P, F2), (po, g*m*N.y), (P, g*M*N.y)]
for i in range(len(l)):
for j in range(len(l[i])):
assert forceList[i][j] == l[i][j]
# This function tests the center_of_mass() function
# that was added in PR #14758 to compute the center of
# mass of a system of bodies.
def test_center_of_mass():
a = ReferenceFrame('a')
m = symbols('m', real=True)
p1 = Particle('p1', Point('p1_pt'), S.One)
p2 = Particle('p2', Point('p2_pt'), S(2))
p3 = Particle('p3', Point('p3_pt'), S(3))
p4 = Particle('p4', Point('p4_pt'), m)
b_f = ReferenceFrame('b_f')
b_cm = Point('b_cm')
mb = symbols('mb')
b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm))
p2.point.set_pos(p1.point, a.x)
p3.point.set_pos(p1.point, a.x + a.y)
p4.point.set_pos(p1.point, a.y)
b.masscenter.set_pos(p1.point, a.y + a.z)
point_o=Point('o')
point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b))
expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
assert point_o.pos_from(p1.point)-expr == 0
def test_validate_coordinates():
q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1:4 u1:4')
s1, s2, s3 = symbols('s1:4')
# Test normal
_validate_coordinates([q1, q2, q3], [u1, u2, u3])
# Test not equal number of coordinates and speeds
_validate_coordinates([q1, q2])
_validate_coordinates([q1, q2], [u1])
_validate_coordinates(speeds=[u1, u2])
# Test duplicate
_validate_coordinates([q1, q2, q2], [u1, u2, u3], check_duplicates=False)
raises(ValueError, lambda: _validate_coordinates(
[q1, q2, q2], [u1, u2, u3]))
_validate_coordinates([q1, q2, q3], [u1, u2, u2], check_duplicates=False)
raises(ValueError, lambda: _validate_coordinates(
[q1, q2, q3], [u1, u2, u2], check_duplicates=True))
# Test is_dynamicsymbols
_validate_coordinates([q1 + q2, q3], is_dynamicsymbols=False)
raises(ValueError, lambda: _validate_coordinates([q1 + q2, q3]))
_validate_coordinates([s1, q1, q2], [0, u1, u2], is_dynamicsymbols=False)
raises(ValueError, lambda: _validate_coordinates(
[s1, q1, q2], [0, u1, u2], is_dynamicsymbols=True))
_validate_coordinates([s1 + s2 + s3, q1], [0, u1], is_dynamicsymbols=False)
raises(ValueError, lambda: _validate_coordinates(
[s1 + s2 + s3, q1], [0, u1], is_dynamicsymbols=True))
# Test normal function
t = dynamicsymbols._t
a = symbols('a')
f1, f2 = symbols('f1:3', cls=Function)
_validate_coordinates([f1(a), f2(a)], is_dynamicsymbols=False)
raises(ValueError, lambda: _validate_coordinates([f1(a), f2(a)]))
raises(ValueError, lambda: _validate_coordinates(speeds=[f1(a), f2(a)]))
dynamicsymbols._t = a
_validate_coordinates([f1(a), f2(a)])
raises(ValueError, lambda: _validate_coordinates([f1(t), f2(t)]))
dynamicsymbols._t = t
|
17747265cd408ccd828796f6ed3b7e558759d470085af860b504104df32237ac | from .unit_definitions import (
percent, percents,
permille,
rad, radian, radians,
deg, degree, degrees,
sr, steradian, steradians,
mil, angular_mil, angular_mils,
m, meter, meters,
kg, kilogram, kilograms,
s, second, seconds,
A, ampere, amperes,
K, kelvin, kelvins,
mol, mole, moles,
cd, candela, candelas,
g, gram, grams,
mg, milligram, milligrams,
ug, microgram, micrograms,
t, tonne, metric_ton,
newton, newtons, N,
joule, joules, J,
watt, watts, W,
pascal, pascals, Pa, pa,
hertz, hz, Hz,
coulomb, coulombs, C,
volt, volts, v, V,
ohm, ohms,
siemens, S, mho, mhos,
farad, farads, F,
henry, henrys, H,
tesla, teslas, T,
weber, webers, Wb, wb,
optical_power, dioptre, D,
lux, lx,
katal, kat,
gray, Gy,
becquerel, Bq,
km, kilometer, kilometers,
dm, decimeter, decimeters,
cm, centimeter, centimeters,
mm, millimeter, millimeters,
um, micrometer, micrometers, micron, microns,
nm, nanometer, nanometers,
pm, picometer, picometers,
ft, foot, feet,
inch, inches,
yd, yard, yards,
mi, mile, miles,
nmi, nautical_mile, nautical_miles,
ha, hectare,
l, L, liter, liters,
dl, dL, deciliter, deciliters,
cl, cL, centiliter, centiliters,
ml, mL, milliliter, milliliters,
ms, millisecond, milliseconds,
us, microsecond, microseconds,
ns, nanosecond, nanoseconds,
ps, picosecond, picoseconds,
minute, minutes,
h, hour, hours,
day, days,
anomalistic_year, anomalistic_years,
sidereal_year, sidereal_years,
tropical_year, tropical_years,
common_year, common_years,
julian_year, julian_years,
draconic_year, draconic_years,
gaussian_year, gaussian_years,
full_moon_cycle, full_moon_cycles,
year, years,
G, gravitational_constant,
c, speed_of_light,
elementary_charge,
hbar,
planck,
eV, electronvolt, electronvolts,
avogadro_number,
avogadro, avogadro_constant,
boltzmann, boltzmann_constant,
stefan, stefan_boltzmann_constant,
R, molar_gas_constant,
faraday_constant,
josephson_constant,
von_klitzing_constant,
Da, dalton, amu, amus, atomic_mass_unit, atomic_mass_constant,
me, electron_rest_mass,
gee, gees, acceleration_due_to_gravity,
u0, magnetic_constant, vacuum_permeability,
e0, electric_constant, vacuum_permittivity,
Z0, vacuum_impedance,
coulomb_constant, coulombs_constant, electric_force_constant,
atmosphere, atmospheres, atm,
kPa, kilopascal,
bar, bars,
pound, pounds,
psi,
dHg0,
mmHg, torr,
mmu, mmus, milli_mass_unit,
quart, quarts,
angstrom, angstroms,
ly, lightyear, lightyears,
au, astronomical_unit, astronomical_units,
planck_mass,
planck_time,
planck_temperature,
planck_length,
planck_charge,
planck_area,
planck_volume,
planck_momentum,
planck_energy,
planck_force,
planck_power,
planck_density,
planck_energy_density,
planck_intensity,
planck_angular_frequency,
planck_pressure,
planck_current,
planck_voltage,
planck_impedance,
planck_acceleration,
bit, bits,
byte,
kibibyte, kibibytes,
mebibyte, mebibytes,
gibibyte, gibibytes,
tebibyte, tebibytes,
pebibyte, pebibytes,
exbibyte, exbibytes,
curie, rutherford
)
__all__ = [
'percent', 'percents',
'permille',
'rad', 'radian', 'radians',
'deg', 'degree', 'degrees',
'sr', 'steradian', 'steradians',
'mil', 'angular_mil', 'angular_mils',
'm', 'meter', 'meters',
'kg', 'kilogram', 'kilograms',
's', 'second', 'seconds',
'A', 'ampere', 'amperes',
'K', 'kelvin', 'kelvins',
'mol', 'mole', 'moles',
'cd', 'candela', 'candelas',
'g', 'gram', 'grams',
'mg', 'milligram', 'milligrams',
'ug', 'microgram', 'micrograms',
't', 'tonne', 'metric_ton',
'newton', 'newtons', 'N',
'joule', 'joules', 'J',
'watt', 'watts', 'W',
'pascal', 'pascals', 'Pa', 'pa',
'hertz', 'hz', 'Hz',
'coulomb', 'coulombs', 'C',
'volt', 'volts', 'v', 'V',
'ohm', 'ohms',
'siemens', 'S', 'mho', 'mhos',
'farad', 'farads', 'F',
'henry', 'henrys', 'H',
'tesla', 'teslas', 'T',
'weber', 'webers', 'Wb', 'wb',
'optical_power', 'dioptre', 'D',
'lux', 'lx',
'katal', 'kat',
'gray', 'Gy',
'becquerel', 'Bq',
'km', 'kilometer', 'kilometers',
'dm', 'decimeter', 'decimeters',
'cm', 'centimeter', 'centimeters',
'mm', 'millimeter', 'millimeters',
'um', 'micrometer', 'micrometers', 'micron', 'microns',
'nm', 'nanometer', 'nanometers',
'pm', 'picometer', 'picometers',
'ft', 'foot', 'feet',
'inch', 'inches',
'yd', 'yard', 'yards',
'mi', 'mile', 'miles',
'nmi', 'nautical_mile', 'nautical_miles',
'ha', 'hectare',
'l', 'L', 'liter', 'liters',
'dl', 'dL', 'deciliter', 'deciliters',
'cl', 'cL', 'centiliter', 'centiliters',
'ml', 'mL', 'milliliter', 'milliliters',
'ms', 'millisecond', 'milliseconds',
'us', 'microsecond', 'microseconds',
'ns', 'nanosecond', 'nanoseconds',
'ps', 'picosecond', 'picoseconds',
'minute', 'minutes',
'h', 'hour', 'hours',
'day', 'days',
'anomalistic_year', 'anomalistic_years',
'sidereal_year', 'sidereal_years',
'tropical_year', 'tropical_years',
'common_year', 'common_years',
'julian_year', 'julian_years',
'draconic_year', 'draconic_years',
'gaussian_year', 'gaussian_years',
'full_moon_cycle', 'full_moon_cycles',
'year', 'years',
'G', 'gravitational_constant',
'c', 'speed_of_light',
'elementary_charge',
'hbar',
'planck',
'eV', 'electronvolt', 'electronvolts',
'avogadro_number',
'avogadro', 'avogadro_constant',
'boltzmann', 'boltzmann_constant',
'stefan', 'stefan_boltzmann_constant',
'R', 'molar_gas_constant',
'faraday_constant',
'josephson_constant',
'von_klitzing_constant',
'Da', 'dalton', 'amu', 'amus', 'atomic_mass_unit', 'atomic_mass_constant',
'me', 'electron_rest_mass',
'gee', 'gees', 'acceleration_due_to_gravity',
'u0', 'magnetic_constant', 'vacuum_permeability',
'e0', 'electric_constant', 'vacuum_permittivity',
'Z0', 'vacuum_impedance',
'coulomb_constant', 'coulombs_constant', 'electric_force_constant',
'atmosphere', 'atmospheres', 'atm',
'kPa', 'kilopascal',
'bar', 'bars',
'pound', 'pounds',
'psi',
'dHg0',
'mmHg', 'torr',
'mmu', 'mmus', 'milli_mass_unit',
'quart', 'quarts',
'angstrom', 'angstroms',
'ly', 'lightyear', 'lightyears',
'au', 'astronomical_unit', 'astronomical_units',
'planck_mass',
'planck_time',
'planck_temperature',
'planck_length',
'planck_charge',
'planck_area',
'planck_volume',
'planck_momentum',
'planck_energy',
'planck_force',
'planck_power',
'planck_density',
'planck_energy_density',
'planck_intensity',
'planck_angular_frequency',
'planck_pressure',
'planck_current',
'planck_voltage',
'planck_impedance',
'planck_acceleration',
'bit', 'bits',
'byte',
'kibibyte', 'kibibytes',
'mebibyte', 'mebibytes',
'gibibyte', 'gibibytes',
'tebibyte', 'tebibytes',
'pebibyte', 'pebibytes',
'exbibyte', 'exbibytes',
'curie', 'rutherford',
]
|
92575f32384e15d2406d88198893d416dc94548368bc37f85d34c2d269288835 | from sympy.physics.units.definitions.dimension_definitions import current, temperature, amount_of_substance, \
luminous_intensity, angle, charge, voltage, impedance, conductance, capacitance, inductance, magnetic_density, \
magnetic_flux, information
from sympy.core.numbers import (Rational, pi)
from sympy.core.singleton import S as S_singleton
from sympy.physics.units.prefixes import kilo, mega, milli, micro, deci, centi, nano, pico, kibi, mebi, gibi, tebi, pebi, exbi
from sympy.physics.units.quantities import PhysicalConstant, Quantity
One = S_singleton.One
#### UNITS ####
# Dimensionless:
percent = percents = Quantity("percent", latex_repr=r"\%")
percent.set_global_relative_scale_factor(Rational(1, 100), One)
permille = Quantity("permille")
permille.set_global_relative_scale_factor(Rational(1, 1000), One)
# Angular units (dimensionless)
rad = radian = radians = Quantity("radian", abbrev="rad")
radian.set_global_dimension(angle)
deg = degree = degrees = Quantity("degree", abbrev="deg", latex_repr=r"^\circ")
degree.set_global_relative_scale_factor(pi/180, radian)
sr = steradian = steradians = Quantity("steradian", abbrev="sr")
mil = angular_mil = angular_mils = Quantity("angular_mil", abbrev="mil")
# Base units:
m = meter = meters = Quantity("meter", abbrev="m")
# gram; used to define its prefixed units
g = gram = grams = Quantity("gram", abbrev="g")
# NOTE: the `kilogram` has scale factor 1000. In SI, kg is a base unit, but
# nonetheless we are trying to be compatible with the `kilo` prefix. In a
# similar manner, people using CGS or gaussian units could argue that the
# `centimeter` rather than `meter` is the fundamental unit for length, but the
# scale factor of `centimeter` will be kept as 1/100 to be compatible with the
# `centi` prefix. The current state of the code assumes SI unit dimensions, in
# the future this module will be modified in order to be unit system-neutral
# (that is, support all kinds of unit systems).
kg = kilogram = kilograms = Quantity("kilogram", abbrev="kg")
kg.set_global_relative_scale_factor(kilo, gram)
s = second = seconds = Quantity("second", abbrev="s")
A = ampere = amperes = Quantity("ampere", abbrev='A')
ampere.set_global_dimension(current)
K = kelvin = kelvins = Quantity("kelvin", abbrev='K')
kelvin.set_global_dimension(temperature)
mol = mole = moles = Quantity("mole", abbrev="mol")
mole.set_global_dimension(amount_of_substance)
cd = candela = candelas = Quantity("candela", abbrev="cd")
candela.set_global_dimension(luminous_intensity)
# derived units
newton = newtons = N = Quantity("newton", abbrev="N")
joule = joules = J = Quantity("joule", abbrev="J")
watt = watts = W = Quantity("watt", abbrev="W")
pascal = pascals = Pa = pa = Quantity("pascal", abbrev="Pa")
hertz = hz = Hz = Quantity("hertz", abbrev="Hz")
# CGS derived units:
dyne = Quantity("dyne")
dyne.set_global_relative_scale_factor(One/10**5, newton)
erg = Quantity("erg")
erg.set_global_relative_scale_factor(One/10**7, joule)
# MKSA extension to MKS: derived units
coulomb = coulombs = C = Quantity("coulomb", abbrev='C')
coulomb.set_global_dimension(charge)
volt = volts = v = V = Quantity("volt", abbrev='V')
volt.set_global_dimension(voltage)
ohm = ohms = Quantity("ohm", abbrev='ohm', latex_repr=r"\Omega")
ohm.set_global_dimension(impedance)
siemens = S = mho = mhos = Quantity("siemens", abbrev='S')
siemens.set_global_dimension(conductance)
farad = farads = F = Quantity("farad", abbrev='F')
farad.set_global_dimension(capacitance)
henry = henrys = H = Quantity("henry", abbrev='H')
henry.set_global_dimension(inductance)
tesla = teslas = T = Quantity("tesla", abbrev='T')
tesla.set_global_dimension(magnetic_density)
weber = webers = Wb = wb = Quantity("weber", abbrev='Wb')
weber.set_global_dimension(magnetic_flux)
# CGS units for electromagnetic quantities:
statampere = Quantity("statampere")
statcoulomb = statC = franklin = Quantity("statcoulomb", abbrev="statC")
statvolt = Quantity("statvolt")
gauss = Quantity("gauss")
maxwell = Quantity("maxwell")
debye = Quantity("debye")
oersted = Quantity("oersted")
# Other derived units:
optical_power = dioptre = diopter = D = Quantity("dioptre")
lux = lx = Quantity("lux", abbrev="lx")
# katal is the SI unit of catalytic activity
katal = kat = Quantity("katal", abbrev="kat")
# gray is the SI unit of absorbed dose
gray = Gy = Quantity("gray")
# becquerel is the SI unit of radioactivity
becquerel = Bq = Quantity("becquerel", abbrev="Bq")
# Common mass units
mg = milligram = milligrams = Quantity("milligram", abbrev="mg")
mg.set_global_relative_scale_factor(milli, gram)
ug = microgram = micrograms = Quantity("microgram", abbrev="ug", latex_repr=r"\mu\text{g}")
ug.set_global_relative_scale_factor(micro, gram)
# Atomic mass constant
Da = dalton = amu = amus = atomic_mass_unit = atomic_mass_constant = PhysicalConstant("atomic_mass_constant")
t = metric_ton = tonne = Quantity("tonne", abbrev="t")
tonne.set_global_relative_scale_factor(mega, gram)
# Electron rest mass
me = electron_rest_mass = Quantity("electron_rest_mass", abbrev="me")
# Common length units
km = kilometer = kilometers = Quantity("kilometer", abbrev="km")
km.set_global_relative_scale_factor(kilo, meter)
dm = decimeter = decimeters = Quantity("decimeter", abbrev="dm")
dm.set_global_relative_scale_factor(deci, meter)
cm = centimeter = centimeters = Quantity("centimeter", abbrev="cm")
cm.set_global_relative_scale_factor(centi, meter)
mm = millimeter = millimeters = Quantity("millimeter", abbrev="mm")
mm.set_global_relative_scale_factor(milli, meter)
um = micrometer = micrometers = micron = microns = \
Quantity("micrometer", abbrev="um", latex_repr=r'\mu\text{m}')
um.set_global_relative_scale_factor(micro, meter)
nm = nanometer = nanometers = Quantity("nanometer", abbrev="nm")
nm.set_global_relative_scale_factor(nano, meter)
pm = picometer = picometers = Quantity("picometer", abbrev="pm")
pm.set_global_relative_scale_factor(pico, meter)
ft = foot = feet = Quantity("foot", abbrev="ft")
ft.set_global_relative_scale_factor(Rational(3048, 10000), meter)
inch = inches = Quantity("inch")
inch.set_global_relative_scale_factor(Rational(1, 12), foot)
yd = yard = yards = Quantity("yard", abbrev="yd")
yd.set_global_relative_scale_factor(3, feet)
mi = mile = miles = Quantity("mile")
mi.set_global_relative_scale_factor(5280, feet)
nmi = nautical_mile = nautical_miles = Quantity("nautical_mile")
nmi.set_global_relative_scale_factor(6076, feet)
angstrom = angstroms = Quantity("angstrom", latex_repr=r'\r{A}')
angstrom.set_global_relative_scale_factor(Rational(1, 10**10), meter)
# Common volume and area units
ha = hectare = Quantity("hectare", abbrev="ha")
l = L = liter = liters = Quantity("liter")
dl = dL = deciliter = deciliters = Quantity("deciliter")
dl.set_global_relative_scale_factor(Rational(1, 10), liter)
cl = cL = centiliter = centiliters = Quantity("centiliter")
cl.set_global_relative_scale_factor(Rational(1, 100), liter)
ml = mL = milliliter = milliliters = Quantity("milliliter")
ml.set_global_relative_scale_factor(Rational(1, 1000), liter)
# Common time units
ms = millisecond = milliseconds = Quantity("millisecond", abbrev="ms")
millisecond.set_global_relative_scale_factor(milli, second)
us = microsecond = microseconds = Quantity("microsecond", abbrev="us", latex_repr=r'\mu\text{s}')
microsecond.set_global_relative_scale_factor(micro, second)
ns = nanosecond = nanoseconds = Quantity("nanosecond", abbrev="ns")
nanosecond.set_global_relative_scale_factor(nano, second)
ps = picosecond = picoseconds = Quantity("picosecond", abbrev="ps")
picosecond.set_global_relative_scale_factor(pico, second)
minute = minutes = Quantity("minute")
minute.set_global_relative_scale_factor(60, second)
h = hour = hours = Quantity("hour")
hour.set_global_relative_scale_factor(60, minute)
day = days = Quantity("day")
day.set_global_relative_scale_factor(24, hour)
anomalistic_year = anomalistic_years = Quantity("anomalistic_year")
anomalistic_year.set_global_relative_scale_factor(365.259636, day)
sidereal_year = sidereal_years = Quantity("sidereal_year")
sidereal_year.set_global_relative_scale_factor(31558149.540, seconds)
tropical_year = tropical_years = Quantity("tropical_year")
tropical_year.set_global_relative_scale_factor(365.24219, day)
common_year = common_years = Quantity("common_year")
common_year.set_global_relative_scale_factor(365, day)
julian_year = julian_years = Quantity("julian_year")
julian_year.set_global_relative_scale_factor((365 + One/4), day)
draconic_year = draconic_years = Quantity("draconic_year")
draconic_year.set_global_relative_scale_factor(346.62, day)
gaussian_year = gaussian_years = Quantity("gaussian_year")
gaussian_year.set_global_relative_scale_factor(365.2568983, day)
full_moon_cycle = full_moon_cycles = Quantity("full_moon_cycle")
full_moon_cycle.set_global_relative_scale_factor(411.78443029, day)
year = years = tropical_year
#### CONSTANTS ####
# Newton constant
G = gravitational_constant = PhysicalConstant("gravitational_constant", abbrev="G")
# speed of light
c = speed_of_light = PhysicalConstant("speed_of_light", abbrev="c")
# elementary charge
elementary_charge = PhysicalConstant("elementary_charge", abbrev="e")
# Planck constant
planck = PhysicalConstant("planck", abbrev="h")
# Reduced Planck constant
hbar = PhysicalConstant("hbar", abbrev="hbar")
# Electronvolt
eV = electronvolt = electronvolts = PhysicalConstant("electronvolt", abbrev="eV")
# Avogadro number
avogadro_number = PhysicalConstant("avogadro_number")
# Avogadro constant
avogadro = avogadro_constant = PhysicalConstant("avogadro_constant")
# Boltzmann constant
boltzmann = boltzmann_constant = PhysicalConstant("boltzmann_constant")
# Stefan-Boltzmann constant
stefan = stefan_boltzmann_constant = PhysicalConstant("stefan_boltzmann_constant")
# Molar gas constant
R = molar_gas_constant = PhysicalConstant("molar_gas_constant", abbrev="R")
# Faraday constant
faraday_constant = PhysicalConstant("faraday_constant")
# Josephson constant
josephson_constant = PhysicalConstant("josephson_constant", abbrev="K_j")
# Von Klitzing constant
von_klitzing_constant = PhysicalConstant("von_klitzing_constant", abbrev="R_k")
# Acceleration due to gravity (on the Earth surface)
gee = gees = acceleration_due_to_gravity = PhysicalConstant("acceleration_due_to_gravity", abbrev="g")
# magnetic constant:
u0 = magnetic_constant = vacuum_permeability = PhysicalConstant("magnetic_constant")
# electric constat:
e0 = electric_constant = vacuum_permittivity = PhysicalConstant("vacuum_permittivity")
# vacuum impedance:
Z0 = vacuum_impedance = PhysicalConstant("vacuum_impedance", abbrev='Z_0', latex_repr=r'Z_{0}')
# Coulomb's constant:
coulomb_constant = coulombs_constant = electric_force_constant = \
PhysicalConstant("coulomb_constant", abbrev="k_e")
atmosphere = atmospheres = atm = Quantity("atmosphere", abbrev="atm")
kPa = kilopascal = Quantity("kilopascal", abbrev="kPa")
kilopascal.set_global_relative_scale_factor(kilo, Pa)
bar = bars = Quantity("bar", abbrev="bar")
pound = pounds = Quantity("pound") # exact
psi = Quantity("psi")
dHg0 = 13.5951 # approx value at 0 C
mmHg = torr = Quantity("mmHg")
atmosphere.set_global_relative_scale_factor(101325, pascal)
bar.set_global_relative_scale_factor(100, kPa)
pound.set_global_relative_scale_factor(Rational(45359237, 100000000), kg)
mmu = mmus = milli_mass_unit = Quantity("milli_mass_unit")
quart = quarts = Quantity("quart")
# Other convenient units and magnitudes
ly = lightyear = lightyears = Quantity("lightyear", abbrev="ly")
au = astronomical_unit = astronomical_units = Quantity("astronomical_unit", abbrev="AU")
# Fundamental Planck units:
planck_mass = Quantity("planck_mass", abbrev="m_P", latex_repr=r'm_\text{P}')
planck_time = Quantity("planck_time", abbrev="t_P", latex_repr=r't_\text{P}')
planck_temperature = Quantity("planck_temperature", abbrev="T_P",
latex_repr=r'T_\text{P}')
planck_length = Quantity("planck_length", abbrev="l_P", latex_repr=r'l_\text{P}')
planck_charge = Quantity("planck_charge", abbrev="q_P", latex_repr=r'q_\text{P}')
# Derived Planck units:
planck_area = Quantity("planck_area")
planck_volume = Quantity("planck_volume")
planck_momentum = Quantity("planck_momentum")
planck_energy = Quantity("planck_energy", abbrev="E_P", latex_repr=r'E_\text{P}')
planck_force = Quantity("planck_force", abbrev="F_P", latex_repr=r'F_\text{P}')
planck_power = Quantity("planck_power", abbrev="P_P", latex_repr=r'P_\text{P}')
planck_density = Quantity("planck_density", abbrev="rho_P", latex_repr=r'\rho_\text{P}')
planck_energy_density = Quantity("planck_energy_density", abbrev="rho^E_P")
planck_intensity = Quantity("planck_intensity", abbrev="I_P", latex_repr=r'I_\text{P}')
planck_angular_frequency = Quantity("planck_angular_frequency", abbrev="omega_P",
latex_repr=r'\omega_\text{P}')
planck_pressure = Quantity("planck_pressure", abbrev="p_P", latex_repr=r'p_\text{P}')
planck_current = Quantity("planck_current", abbrev="I_P", latex_repr=r'I_\text{P}')
planck_voltage = Quantity("planck_voltage", abbrev="V_P", latex_repr=r'V_\text{P}')
planck_impedance = Quantity("planck_impedance", abbrev="Z_P", latex_repr=r'Z_\text{P}')
planck_acceleration = Quantity("planck_acceleration", abbrev="a_P",
latex_repr=r'a_\text{P}')
# Information theory units:
bit = bits = Quantity("bit")
bit.set_global_dimension(information)
byte = bytes = Quantity("byte")
kibibyte = kibibytes = Quantity("kibibyte")
mebibyte = mebibytes = Quantity("mebibyte")
gibibyte = gibibytes = Quantity("gibibyte")
tebibyte = tebibytes = Quantity("tebibyte")
pebibyte = pebibytes = Quantity("pebibyte")
exbibyte = exbibytes = Quantity("exbibyte")
byte.set_global_relative_scale_factor(8, bit)
kibibyte.set_global_relative_scale_factor(kibi, byte)
mebibyte.set_global_relative_scale_factor(mebi, byte)
gibibyte.set_global_relative_scale_factor(gibi, byte)
tebibyte.set_global_relative_scale_factor(tebi, byte)
pebibyte.set_global_relative_scale_factor(pebi, byte)
exbibyte.set_global_relative_scale_factor(exbi, byte)
# Older units for radioactivity
curie = Ci = Quantity("curie", abbrev="Ci")
rutherford = Rd = Quantity("rutherford", abbrev="Rd")
|
d95a2f65c64fb7034c9d6a591c87cca9acfd0a8628ff850506e7b4f6a6df1d64 | from sympy.core.singleton import S
from sympy.core.numbers import pi
from sympy.physics.units import DimensionSystem, hertz, kilogram
from sympy.physics.units.definitions import (
G, Hz, J, N, Pa, W, c, g, kg, m, s, meter, gram, second, newton,
joule, watt, pascal)
from sympy.physics.units.definitions.dimension_definitions import (
acceleration, action, energy, force, frequency, momentum,
power, pressure, velocity, length, mass, time)
from sympy.physics.units.prefixes import PREFIXES, prefix_unit
from sympy.physics.units.prefixes import (
kibi, mebi, gibi, tebi, pebi, exbi
)
from sympy.physics.units.definitions import (
cd, K, coulomb, volt, ohm, siemens, farad, henry, tesla, weber, dioptre,
lux, katal, gray, becquerel, inch, hectare, liter, julian_year,
gravitational_constant, speed_of_light, elementary_charge, planck, hbar,
electronvolt, avogadro_number, avogadro_constant, boltzmann_constant,
stefan_boltzmann_constant, atomic_mass_constant, molar_gas_constant,
faraday_constant, josephson_constant, von_klitzing_constant,
acceleration_due_to_gravity, magnetic_constant, vacuum_permittivity,
vacuum_impedance, coulomb_constant, atmosphere, bar, pound, psi, mmHg,
milli_mass_unit, quart, lightyear, astronomical_unit, planck_mass,
planck_time, planck_temperature, planck_length, planck_charge,
planck_area, planck_volume, planck_momentum, planck_energy, planck_force,
planck_power, planck_density, planck_energy_density, planck_intensity,
planck_angular_frequency, planck_pressure, planck_current, planck_voltage,
planck_impedance, planck_acceleration, bit, byte, kibibyte, mebibyte,
gibibyte, tebibyte, pebibyte, exbibyte, curie, rutherford, radian, degree,
steradian, angular_mil, atomic_mass_unit, gee, kPa, ampere, u0, kelvin,
mol, mole, candela, electric_constant, boltzmann, angstrom
)
dimsys_length_weight_time = DimensionSystem([
# Dimensional dependencies for MKS base dimensions
length,
mass,
time,
], dimensional_dependencies=dict(
# Dimensional dependencies for derived dimensions
velocity=dict(length=1, time=-1),
acceleration=dict(length=1, time=-2),
momentum=dict(mass=1, length=1, time=-1),
force=dict(mass=1, length=1, time=-2),
energy=dict(mass=1, length=2, time=-2),
power=dict(length=2, mass=1, time=-3),
pressure=dict(mass=1, length=-1, time=-2),
frequency=dict(time=-1),
action=dict(length=2, mass=1, time=-1),
area=dict(length=2),
volume=dict(length=3),
))
One = S.One
# Base units:
dimsys_length_weight_time.set_quantity_dimension(meter, length)
dimsys_length_weight_time.set_quantity_scale_factor(meter, One)
# gram; used to define its prefixed units
dimsys_length_weight_time.set_quantity_dimension(gram, mass)
dimsys_length_weight_time.set_quantity_scale_factor(gram, One)
dimsys_length_weight_time.set_quantity_dimension(second, time)
dimsys_length_weight_time.set_quantity_scale_factor(second, One)
# derived units
dimsys_length_weight_time.set_quantity_dimension(newton, force)
dimsys_length_weight_time.set_quantity_scale_factor(newton, kilogram*meter/second**2)
dimsys_length_weight_time.set_quantity_dimension(joule, energy)
dimsys_length_weight_time.set_quantity_scale_factor(joule, newton*meter)
dimsys_length_weight_time.set_quantity_dimension(watt, power)
dimsys_length_weight_time.set_quantity_scale_factor(watt, joule/second)
dimsys_length_weight_time.set_quantity_dimension(pascal, pressure)
dimsys_length_weight_time.set_quantity_scale_factor(pascal, newton/meter**2)
dimsys_length_weight_time.set_quantity_dimension(hertz, frequency)
dimsys_length_weight_time.set_quantity_scale_factor(hertz, One)
# Other derived units:
dimsys_length_weight_time.set_quantity_dimension(dioptre, 1 / length)
dimsys_length_weight_time.set_quantity_scale_factor(dioptre, 1/meter)
# Common volume and area units
dimsys_length_weight_time.set_quantity_dimension(hectare, length**2)
dimsys_length_weight_time.set_quantity_scale_factor(hectare, (meter**2)*(10000))
dimsys_length_weight_time.set_quantity_dimension(liter, length**3)
dimsys_length_weight_time.set_quantity_scale_factor(liter, meter**3/1000)
# Newton constant
# REF: NIST SP 959 (June 2019)
dimsys_length_weight_time.set_quantity_dimension(gravitational_constant, length ** 3 * mass ** -1 * time ** -2)
dimsys_length_weight_time.set_quantity_scale_factor(gravitational_constant, 6.67430e-11*m**3/(kg*s**2))
# speed of light
dimsys_length_weight_time.set_quantity_dimension(speed_of_light, velocity)
dimsys_length_weight_time.set_quantity_scale_factor(speed_of_light, 299792458*meter/second)
# Planck constant
# REF: NIST SP 959 (June 2019)
dimsys_length_weight_time.set_quantity_dimension(planck, action)
dimsys_length_weight_time.set_quantity_scale_factor(planck, 6.62607015e-34*joule*second)
# Reduced Planck constant
# REF: NIST SP 959 (June 2019)
dimsys_length_weight_time.set_quantity_dimension(hbar, action)
dimsys_length_weight_time.set_quantity_scale_factor(hbar, planck / (2 * pi))
__all__ = [
'mmHg', 'atmosphere', 'newton', 'meter', 'vacuum_permittivity', 'pascal',
'magnetic_constant', 'angular_mil', 'julian_year', 'weber', 'exbibyte',
'liter', 'molar_gas_constant', 'faraday_constant', 'avogadro_constant',
'planck_momentum', 'planck_density', 'gee', 'mol', 'bit', 'gray', 'kibi',
'bar', 'curie', 'prefix_unit', 'PREFIXES', 'planck_time', 'gram',
'candela', 'force', 'planck_intensity', 'energy', 'becquerel',
'planck_acceleration', 'speed_of_light', 'dioptre', 'second', 'frequency',
'Hz', 'power', 'lux', 'planck_current', 'momentum', 'tebibyte',
'planck_power', 'degree', 'mebi', 'K', 'planck_volume',
'quart', 'pressure', 'W', 'joule', 'boltzmann_constant', 'c', 'g',
'planck_force', 'exbi', 's', 'watt', 'action', 'hbar', 'gibibyte',
'DimensionSystem', 'cd', 'volt', 'planck_charge', 'angstrom',
'dimsys_length_weight_time', 'pebi', 'vacuum_impedance', 'planck',
'farad', 'gravitational_constant', 'u0', 'hertz', 'tesla', 'steradian',
'josephson_constant', 'planck_area', 'stefan_boltzmann_constant',
'astronomical_unit', 'J', 'N', 'planck_voltage', 'planck_energy',
'atomic_mass_constant', 'rutherford', 'elementary_charge', 'Pa',
'planck_mass', 'henry', 'planck_angular_frequency', 'ohm', 'pound',
'planck_pressure', 'G', 'avogadro_number', 'psi', 'von_klitzing_constant',
'planck_length', 'radian', 'mole', 'acceleration',
'planck_energy_density', 'mebibyte', 'length',
'acceleration_due_to_gravity', 'planck_temperature', 'tebi', 'inch',
'electronvolt', 'coulomb_constant', 'kelvin', 'kPa', 'boltzmann',
'milli_mass_unit', 'gibi', 'planck_impedance', 'electric_constant', 'kg',
'coulomb', 'siemens', 'byte', 'atomic_mass_unit', 'm', 'kibibyte',
'kilogram', 'lightyear', 'mass', 'time', 'pebibyte', 'velocity',
'ampere', 'katal',
]
|
fce990d6a04fb9df3e9557acbd536140baf0461f6aa7bad73121b3a93b6a0abd | import warnings
from sympy.core.add import Add
from sympy.core.function import (Function, diff)
from sympy.core.numbers import (Number, Rational)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin
from sympy.integrals.integrals import integrate
from sympy.physics.units import (amount_of_substance, area, convert_to, find_unit,
volume, kilometer, joule, molar_gas_constant,
vacuum_permittivity, elementary_charge, volt,
ohm)
from sympy.physics.units.definitions import (amu, au, centimeter, coulomb,
day, foot, grams, hour, inch, kg, km, m, meter, millimeter,
minute, quart, s, second, speed_of_light, bit,
byte, kibibyte, mebibyte, gibibyte, tebibyte, pebibyte, exbibyte,
kilogram, gravitational_constant, electron_rest_mass)
from sympy.physics.units.definitions.dimension_definitions import (
Dimension, charge, length, time, temperature, pressure,
energy, mass
)
from sympy.physics.units.prefixes import PREFIXES, kilo
from sympy.physics.units.quantities import PhysicalConstant, Quantity
from sympy.physics.units.systems import SI
from sympy.testing.pytest import raises
k = PREFIXES["k"]
def test_str_repr():
assert str(kg) == "kilogram"
def test_eq():
# simple test
assert 10*m == 10*m
assert 10*m != 10*s
def test_convert_to():
q = Quantity("q1")
q.set_global_relative_scale_factor(S(5000), meter)
assert q.convert_to(m) == 5000*m
assert speed_of_light.convert_to(m / s) == 299792458 * m / s
# TODO: eventually support this kind of conversion:
# assert (2*speed_of_light).convert_to(m / s) == 2 * 299792458 * m / s
assert day.convert_to(s) == 86400*s
# Wrong dimension to convert:
assert q.convert_to(s) == q
assert speed_of_light.convert_to(m) == speed_of_light
expr = joule*second
conv = convert_to(expr, joule)
assert conv == joule*second
def test_Quantity_definition():
q = Quantity("s10", abbrev="sabbr")
q.set_global_relative_scale_factor(10, second)
u = Quantity("u", abbrev="dam")
u.set_global_relative_scale_factor(10, meter)
km = Quantity("km")
km.set_global_relative_scale_factor(kilo, meter)
v = Quantity("u")
v.set_global_relative_scale_factor(5*kilo, meter)
assert q.scale_factor == 10
assert q.dimension == time
assert q.abbrev == Symbol("sabbr")
assert u.dimension == length
assert u.scale_factor == 10
assert u.abbrev == Symbol("dam")
assert km.scale_factor == 1000
assert km.func(*km.args) == km
assert km.func(*km.args).args == km.args
assert v.dimension == length
assert v.scale_factor == 5000
def test_abbrev():
u = Quantity("u")
u.set_global_relative_scale_factor(S.One, meter)
assert u.name == Symbol("u")
assert u.abbrev == Symbol("u")
u = Quantity("u", abbrev="om")
u.set_global_relative_scale_factor(S(2), meter)
assert u.name == Symbol("u")
assert u.abbrev == Symbol("om")
assert u.scale_factor == 2
assert isinstance(u.scale_factor, Number)
u = Quantity("u", abbrev="ikm")
u.set_global_relative_scale_factor(3*kilo, meter)
assert u.abbrev == Symbol("ikm")
assert u.scale_factor == 3000
def test_print():
u = Quantity("unitname", abbrev="dam")
assert repr(u) == "unitname"
assert str(u) == "unitname"
def test_Quantity_eq():
u = Quantity("u", abbrev="dam")
v = Quantity("v1")
assert u != v
v = Quantity("v2", abbrev="ds")
assert u != v
v = Quantity("v3", abbrev="dm")
assert u != v
def test_add_sub():
u = Quantity("u")
v = Quantity("v")
w = Quantity("w")
u.set_global_relative_scale_factor(S(10), meter)
v.set_global_relative_scale_factor(S(5), meter)
w.set_global_relative_scale_factor(S(2), second)
assert isinstance(u + v, Add)
assert (u + v.convert_to(u)) == (1 + S.Half)*u
# TODO: eventually add this:
# assert (u + v).convert_to(u) == (1 + S.Half)*u
assert isinstance(u - v, Add)
assert (u - v.convert_to(u)) == S.Half*u
# TODO: eventually add this:
# assert (u - v).convert_to(u) == S.Half*u
def test_quantity_abs():
v_w1 = Quantity('v_w1')
v_w2 = Quantity('v_w2')
v_w3 = Quantity('v_w3')
v_w1.set_global_relative_scale_factor(1, meter/second)
v_w2.set_global_relative_scale_factor(1, meter/second)
v_w3.set_global_relative_scale_factor(1, meter/second)
expr = v_w3 - Abs(v_w1 - v_w2)
assert SI.get_dimensional_expr(v_w1) == (length/time).name
Dq = Dimension(SI.get_dimensional_expr(expr))
assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == {
length: 1,
time: -1,
}
assert meter == sqrt(meter**2)
def test_check_unit_consistency():
u = Quantity("u")
v = Quantity("v")
w = Quantity("w")
u.set_global_relative_scale_factor(S(10), meter)
v.set_global_relative_scale_factor(S(5), meter)
w.set_global_relative_scale_factor(S(2), second)
def check_unit_consistency(expr):
SI._collect_factor_and_dimension(expr)
raises(ValueError, lambda: check_unit_consistency(u + w))
raises(ValueError, lambda: check_unit_consistency(u - w))
raises(ValueError, lambda: check_unit_consistency(u + 1))
raises(ValueError, lambda: check_unit_consistency(u - 1))
raises(ValueError, lambda: check_unit_consistency(1 - exp(u / w)))
def test_mul_div():
u = Quantity("u")
v = Quantity("v")
t = Quantity("t")
ut = Quantity("ut")
v2 = Quantity("v")
u.set_global_relative_scale_factor(S(10), meter)
v.set_global_relative_scale_factor(S(5), meter)
t.set_global_relative_scale_factor(S(2), second)
ut.set_global_relative_scale_factor(S(20), meter*second)
v2.set_global_relative_scale_factor(S(5), meter/second)
assert 1 / u == u**(-1)
assert u / 1 == u
v1 = u / t
v2 = v
# Pow only supports structural equality:
assert v1 != v2
assert v1 == v2.convert_to(v1)
# TODO: decide whether to allow such expression in the future
# (requires somehow manipulating the core).
# assert u / Quantity('l2', dimension=length, scale_factor=2) == 5
assert u * 1 == u
ut1 = u * t
ut2 = ut
# Mul only supports structural equality:
assert ut1 != ut2
assert ut1 == ut2.convert_to(ut1)
# Mul only supports structural equality:
lp1 = Quantity("lp1")
lp1.set_global_relative_scale_factor(S(2), 1/meter)
assert u * lp1 != 20
assert u**0 == 1
assert u**1 == u
# TODO: Pow only support structural equality:
u2 = Quantity("u2")
u3 = Quantity("u3")
u2.set_global_relative_scale_factor(S(100), meter**2)
u3.set_global_relative_scale_factor(Rational(1, 10), 1/meter)
assert u ** 2 != u2
assert u ** -1 != u3
assert u ** 2 == u2.convert_to(u)
assert u ** -1 == u3.convert_to(u)
def test_units():
assert convert_to((5*m/s * day) / km, 1) == 432
assert convert_to(foot / meter, meter) == Rational(3048, 10000)
# amu is a pure mass so mass/mass gives a number, not an amount (mol)
# TODO: need better simplification routine:
assert str(convert_to(grams/amu, grams).n(2)) == '6.0e+23'
# Light from the sun needs about 8.3 minutes to reach earth
t = (1*au / speed_of_light) / minute
# TODO: need a better way to simplify expressions containing units:
t = convert_to(convert_to(t, meter / minute), meter)
assert t.simplify() == Rational(49865956897, 5995849160)
# TODO: fix this, it should give `m` without `Abs`
assert sqrt(m**2) == m
assert (sqrt(m))**2 == m
t = Symbol('t')
assert integrate(t*m/s, (t, 1*s, 5*s)) == 12*m*s
assert (t * m/s).integrate((t, 1*s, 5*s)) == 12*m*s
def test_issue_quart():
assert convert_to(4 * quart / inch ** 3, meter) == 231
assert convert_to(4 * quart / inch ** 3, millimeter) == 231
def test_electron_rest_mass():
assert convert_to(electron_rest_mass, kilogram) == 9.1093837015e-31*kilogram
assert convert_to(electron_rest_mass, grams) == 9.1093837015e-28*grams
def test_issue_5565():
assert (m < s).is_Relational
def test_find_unit():
assert find_unit('coulomb') == ['coulomb', 'coulombs', 'coulomb_constant']
assert find_unit(coulomb) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
assert find_unit(charge) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
assert find_unit(inch) == [
'm', 'au', 'cm', 'dm', 'ft', 'km', 'ly', 'mi', 'mm', 'nm', 'pm', 'um', 'yd',
'nmi', 'feet', 'foot', 'inch', 'mile', 'yard', 'meter', 'miles', 'yards',
'inches', 'meters', 'micron', 'microns', 'angstrom', 'angstroms', 'decimeter',
'kilometer', 'lightyear', 'nanometer', 'picometer', 'centimeter', 'decimeters',
'kilometers', 'lightyears', 'micrometer', 'millimeter', 'nanometers', 'picometers',
'centimeters', 'micrometers', 'millimeters', 'nautical_mile', 'planck_length',
'nautical_miles', 'astronomical_unit', 'astronomical_units']
assert find_unit(inch**-1) == ['D', 'dioptre', 'optical_power']
assert find_unit(length**-1) == ['D', 'dioptre', 'optical_power']
assert find_unit(inch ** 2) == ['ha', 'hectare', 'planck_area']
assert find_unit(inch ** 3) == [
'L', 'l', 'cL', 'cl', 'dL', 'dl', 'mL', 'ml', 'liter', 'quart', 'liters', 'quarts',
'deciliter', 'centiliter', 'deciliters', 'milliliter',
'centiliters', 'milliliters', 'planck_volume']
assert find_unit('voltage') == ['V', 'v', 'volt', 'volts', 'planck_voltage']
assert find_unit(grams) == ['g', 't', 'Da', 'kg', 'me', 'mg', 'ug', 'amu', 'mmu', 'amus',
'gram', 'mmus', 'grams', 'pound', 'tonne', 'dalton', 'pounds',
'kilogram', 'kilograms', 'microgram', 'milligram', 'metric_ton',
'micrograms', 'milligrams', 'planck_mass', 'milli_mass_unit', 'atomic_mass_unit',
'electron_rest_mass', 'atomic_mass_constant']
def test_Quantity_derivative():
x = symbols("x")
assert diff(x*meter, x) == meter
assert diff(x**3*meter**2, x) == 3*x**2*meter**2
assert diff(meter, meter) == 1
assert diff(meter**2, meter) == 2*meter
def test_quantity_postprocessing():
q1 = Quantity('q1')
q2 = Quantity('q2')
SI.set_quantity_dimension(q1, length*pressure**2*temperature/time)
SI.set_quantity_dimension(q2, energy*pressure*temperature/(length**2*time))
assert q1 + q2
q = q1 + q2
Dq = Dimension(SI.get_dimensional_expr(q))
assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == {
length: -1,
mass: 2,
temperature: 1,
time: -5,
}
def test_factor_and_dimension():
assert (3000, Dimension(1)) == SI._collect_factor_and_dimension(3000)
assert (1001, length) == SI._collect_factor_and_dimension(meter + km)
assert (2, length/time) == SI._collect_factor_and_dimension(
meter/second + 36*km/(10*hour))
x, y = symbols('x y')
assert (x + y/100, length) == SI._collect_factor_and_dimension(
x*m + y*centimeter)
cH = Quantity('cH')
SI.set_quantity_dimension(cH, amount_of_substance/volume)
pH = -log(cH)
assert (1, volume/amount_of_substance) == SI._collect_factor_and_dimension(
exp(pH))
v_w1 = Quantity('v_w1')
v_w2 = Quantity('v_w2')
v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second)
v_w2.set_global_relative_scale_factor(2, meter/second)
expr = Abs(v_w1/2 - v_w2)
assert (Rational(5, 4), length/time) == \
SI._collect_factor_and_dimension(expr)
expr = Rational(5, 2)*second/meter*v_w1 - 3000
assert (-(2996 + Rational(1, 4)), Dimension(1)) == \
SI._collect_factor_and_dimension(expr)
expr = v_w1**(v_w2/v_w1)
assert ((Rational(3, 2))**Rational(4, 3), (length/time)**Rational(4, 3)) == \
SI._collect_factor_and_dimension(expr)
def test_dimensional_expr_of_derivative():
l = Quantity('l')
t = Quantity('t')
t1 = Quantity('t1')
l.set_global_relative_scale_factor(36, km)
t.set_global_relative_scale_factor(1, hour)
t1.set_global_relative_scale_factor(1, second)
x = Symbol('x')
y = Symbol('y')
f = Function('f')
dfdx = f(x, y).diff(x, y)
dl_dt = dfdx.subs({f(x, y): l, x: t, y: t1})
assert SI.get_dimensional_expr(dl_dt) ==\
SI.get_dimensional_expr(l / t / t1) ==\
Symbol("length")/Symbol("time")**2
assert SI._collect_factor_and_dimension(dl_dt) ==\
SI._collect_factor_and_dimension(l / t / t1) ==\
(10, length/time**2)
def test_get_dimensional_expr_with_function():
v_w1 = Quantity('v_w1')
v_w2 = Quantity('v_w2')
v_w1.set_global_relative_scale_factor(1, meter/second)
v_w2.set_global_relative_scale_factor(1, meter/second)
assert SI.get_dimensional_expr(sin(v_w1)) == \
sin(SI.get_dimensional_expr(v_w1))
assert SI.get_dimensional_expr(sin(v_w1/v_w2)) == 1
def test_binary_information():
assert convert_to(kibibyte, byte) == 1024*byte
assert convert_to(mebibyte, byte) == 1024**2*byte
assert convert_to(gibibyte, byte) == 1024**3*byte
assert convert_to(tebibyte, byte) == 1024**4*byte
assert convert_to(pebibyte, byte) == 1024**5*byte
assert convert_to(exbibyte, byte) == 1024**6*byte
assert kibibyte.convert_to(bit) == 8*1024*bit
assert byte.convert_to(bit) == 8*bit
a = 10*kibibyte*hour
assert convert_to(a, byte) == 10240*byte*hour
assert convert_to(a, minute) == 600*kibibyte*minute
assert convert_to(a, [byte, minute]) == 614400*byte*minute
def test_conversion_with_2_nonstandard_dimensions():
good_grade = Quantity("good_grade")
kilo_good_grade = Quantity("kilo_good_grade")
centi_good_grade = Quantity("centi_good_grade")
kilo_good_grade.set_global_relative_scale_factor(1000, good_grade)
centi_good_grade.set_global_relative_scale_factor(S.One/10**5, kilo_good_grade)
charity_points = Quantity("charity_points")
milli_charity_points = Quantity("milli_charity_points")
missions = Quantity("missions")
milli_charity_points.set_global_relative_scale_factor(S.One/1000, charity_points)
missions.set_global_relative_scale_factor(251, charity_points)
assert convert_to(
kilo_good_grade*milli_charity_points*millimeter,
[centi_good_grade, missions, centimeter]
) == S.One * 10**5 / (251*1000) / 10 * centi_good_grade*missions*centimeter
def test_eval_subs():
energy, mass, force = symbols('energy mass force')
expr1 = energy/mass
units = {energy: kilogram*meter**2/second**2, mass: kilogram}
assert expr1.subs(units) == meter**2/second**2
expr2 = force/mass
units = {force:gravitational_constant*kilogram**2/meter**2, mass:kilogram}
assert expr2.subs(units) == gravitational_constant*kilogram/meter**2
def test_issue_14932():
assert (log(inch) - log(2)).simplify() == log(inch/2)
assert (log(inch) - log(foot)).simplify() == -log(12)
p = symbols('p', positive=True)
assert (log(inch) - log(p)).simplify() == log(inch/p)
def test_issue_14547():
# the root issue is that an argument with dimensions should
# not raise an error when the `arg - 1` calculation is
# performed in the assumptions system
from sympy.physics.units import foot, inch
from sympy.core.relational import Eq
assert log(foot).is_zero is None
assert log(foot).is_positive is None
assert log(foot).is_nonnegative is None
assert log(foot).is_negative is None
assert log(foot).is_algebraic is None
assert log(foot).is_rational is None
# doesn't raise error
assert Eq(log(foot), log(inch)) is not None # might be False or unevaluated
x = Symbol('x')
e = foot + x
assert e.is_Add and set(e.args) == {foot, x}
e = foot + 1
assert e.is_Add and set(e.args) == {foot, 1}
def test_issue_22164():
warnings.simplefilter("error")
dm = Quantity("dm")
SI.set_quantity_dimension(dm, length)
SI.set_quantity_scale_factor(dm, 1)
bad_exp = Quantity("bad_exp")
SI.set_quantity_dimension(bad_exp, length)
SI.set_quantity_scale_factor(bad_exp, 1)
expr = dm ** bad_exp
# deprecation warning is not expected here
SI._collect_factor_and_dimension(expr)
def test_issue_22819():
from sympy.physics.units import tonne, gram, Da
from sympy.physics.units.systems.si import dimsys_SI
assert tonne.convert_to(gram) == 1000000*gram
assert dimsys_SI.get_dimensional_dependencies(area) == {length: 2}
assert Da.scale_factor == 1.66053906660000e-24
def test_issue_20288():
from sympy.core.numbers import E
from sympy.physics.units import energy
u = Quantity('u')
v = Quantity('v')
SI.set_quantity_dimension(u, energy)
SI.set_quantity_dimension(v, energy)
u.set_global_relative_scale_factor(1, joule)
v.set_global_relative_scale_factor(1, joule)
expr = 1 + exp(u**2/v**2)
assert SI._collect_factor_and_dimension(expr) == (1 + E, Dimension(1))
def test_issue_24062():
from sympy.core.numbers import E
from sympy.physics.units import impedance, capacitance, time, ohm, farad, second
R = Quantity('R')
C = Quantity('C')
T = Quantity('T')
SI.set_quantity_dimension(R, impedance)
SI.set_quantity_dimension(C, capacitance)
SI.set_quantity_dimension(T, time)
R.set_global_relative_scale_factor(1, ohm)
C.set_global_relative_scale_factor(1, farad)
T.set_global_relative_scale_factor(1, second)
expr = T / (R * C)
dim = SI._collect_factor_and_dimension(expr)[1]
assert SI.get_dimension_system().is_dimensionless(dim)
exp_expr = 1 + exp(expr)
assert SI._collect_factor_and_dimension(exp_expr) == (1 + E, Dimension(1))
def test_issue_24211():
from sympy.physics.units import time, velocity, acceleration, second, meter
V1 = Quantity('V1')
SI.set_quantity_dimension(V1, velocity)
SI.set_quantity_scale_factor(V1, 1 * meter / second)
A1 = Quantity('A1')
SI.set_quantity_dimension(A1, acceleration)
SI.set_quantity_scale_factor(A1, 1 * meter / second**2)
T1 = Quantity('T1')
SI.set_quantity_dimension(T1, time)
SI.set_quantity_scale_factor(T1, 1 * second)
expr = A1*T1 + V1
# should not throw ValueError here
SI._collect_factor_and_dimension(expr)
def test_prefixed_property():
assert not meter.is_prefixed
assert not joule.is_prefixed
assert not day.is_prefixed
assert not second.is_prefixed
assert not volt.is_prefixed
assert not ohm.is_prefixed
assert centimeter.is_prefixed
assert kilometer.is_prefixed
assert kilogram.is_prefixed
assert pebibyte.is_prefixed
def test_physics_constant():
from sympy.physics.units import definitions
for name in dir(definitions):
quantity = getattr(definitions, name)
if not isinstance(quantity, Quantity):
continue
if name.endswith('_constant'):
assert isinstance(quantity, PhysicalConstant), f"{quantity} must be PhysicalConstant, but is {type(quantity)}"
assert quantity.is_physical_constant, f"{name} is not marked as physics constant when it should be"
for const in [gravitational_constant, molar_gas_constant, vacuum_permittivity, speed_of_light, elementary_charge]:
assert isinstance(const, PhysicalConstant), f"{const} must be PhysicalConstant, but is {type(const)}"
assert const.is_physical_constant, f"{const} is not marked as physics constant when it should be"
assert not meter.is_physical_constant
assert not joule.is_physical_constant
|
25ea535adf3219db6fe5d43600a50a6fd7f1a6e62a2d63a9d283a6ce8bfdbdf6 | from sympy.concrete.tests.test_sums_products import NS
from sympy.core.singleton import S
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.units import convert_to, coulomb_constant, elementary_charge, gravitational_constant, planck
from sympy.physics.units.definitions.unit_definitions import angstrom, statcoulomb, coulomb, second, gram, centimeter, erg, \
newton, joule, dyne, speed_of_light, meter, farad, henry, statvolt, volt, ohm
from sympy.physics.units.systems import SI
from sympy.physics.units.systems.cgs import cgs_gauss
def test_conversion_to_from_si():
assert convert_to(statcoulomb, coulomb, cgs_gauss) == coulomb/2997924580
assert convert_to(coulomb, statcoulomb, cgs_gauss) == 2997924580*statcoulomb
assert convert_to(statcoulomb, sqrt(gram*centimeter**3)/second, cgs_gauss) == centimeter**(S(3)/2)*sqrt(gram)/second
assert convert_to(coulomb, sqrt(gram*centimeter**3)/second, cgs_gauss) == 2997924580*centimeter**(S(3)/2)*sqrt(gram)/second
# SI units have an additional base unit, no conversion in case of electromagnetism:
assert convert_to(coulomb, statcoulomb, SI) == coulomb
assert convert_to(statcoulomb, coulomb, SI) == statcoulomb
# SI without electromagnetism:
assert convert_to(erg, joule, SI) == joule/10**7
assert convert_to(erg, joule, cgs_gauss) == joule/10**7
assert convert_to(joule, erg, SI) == 10**7*erg
assert convert_to(joule, erg, cgs_gauss) == 10**7*erg
assert convert_to(dyne, newton, SI) == newton/10**5
assert convert_to(dyne, newton, cgs_gauss) == newton/10**5
assert convert_to(newton, dyne, SI) == 10**5*dyne
assert convert_to(newton, dyne, cgs_gauss) == 10**5*dyne
def test_cgs_gauss_convert_constants():
assert convert_to(speed_of_light, centimeter/second, cgs_gauss) == 29979245800*centimeter/second
assert convert_to(coulomb_constant, 1, cgs_gauss) == 1
assert convert_to(coulomb_constant, newton*meter**2/coulomb**2, cgs_gauss) == 22468879468420441*meter**2*newton/(2500000*coulomb**2)
assert convert_to(coulomb_constant, newton*meter**2/coulomb**2, SI) == 22468879468420441*meter**2*newton/(2500000*coulomb**2)
assert convert_to(coulomb_constant, dyne*centimeter**2/statcoulomb**2, cgs_gauss) == centimeter**2*dyne/statcoulomb**2
assert convert_to(coulomb_constant, 1, SI) == coulomb_constant
assert NS(convert_to(coulomb_constant, newton*meter**2/coulomb**2, SI)) == '8987551787.36818*meter**2*newton/coulomb**2'
assert convert_to(elementary_charge, statcoulomb, cgs_gauss)
assert convert_to(angstrom, centimeter, cgs_gauss) == 1*centimeter/10**8
assert convert_to(gravitational_constant, dyne*centimeter**2/gram**2, cgs_gauss)
assert NS(convert_to(planck, erg*second, cgs_gauss)) == '6.62607015e-27*erg*second'
spc = 25000*second/(22468879468420441*centimeter)
assert convert_to(ohm, second/centimeter, cgs_gauss) == spc
assert convert_to(henry, second**2/centimeter, cgs_gauss) == spc*second
assert convert_to(volt, statvolt, cgs_gauss) == 10**6*statvolt/299792458
assert convert_to(farad, centimeter, cgs_gauss) == 299792458**2*centimeter/10**5
|
9534f5130579b5bdd602f9a64bf9888e10925922e207434d3d6e27f7fddfbb49 | r"""
N-dim array module for SymPy.
Four classes are provided to handle N-dim arrays, given by the combinations
dense/sparse (i.e. whether to store all elements or only the non-zero ones in
memory) and mutable/immutable (immutable classes are SymPy objects, but cannot
change after they have been created).
Examples
========
The following examples show the usage of ``Array``. This is an abbreviation for
``ImmutableDenseNDimArray``, that is an immutable and dense N-dim array, the
other classes are analogous. For mutable classes it is also possible to change
element values after the object has been constructed.
Array construction can detect the shape of nested lists and tuples:
>>> from sympy import Array
>>> a1 = Array([[1, 2], [3, 4], [5, 6]])
>>> a1
[[1, 2], [3, 4], [5, 6]]
>>> a1.shape
(3, 2)
>>> a1.rank()
2
>>> from sympy.abc import x, y, z
>>> a2 = Array([[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]])
>>> a2
[[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]]
>>> a2.shape
(2, 2, 2)
>>> a2.rank()
3
Otherwise one could pass a 1-dim array followed by a shape tuple:
>>> m1 = Array(range(12), (3, 4))
>>> m1
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
>>> m2 = Array(range(12), (3, 2, 2))
>>> m2
[[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]]
>>> m2[1,1,1]
7
>>> m2.reshape(4, 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
Slice support:
>>> m2[:, 1, 1]
[3, 7, 11]
Elementwise derivative:
>>> from sympy.abc import x, y, z
>>> m3 = Array([x**3, x*y, z])
>>> m3.diff(x)
[3*x**2, y, 0]
>>> m3.diff(z)
[0, 0, 1]
Multiplication with other SymPy expressions is applied elementwisely:
>>> (1+x)*m3
[x**3*(x + 1), x*y*(x + 1), z*(x + 1)]
To apply a function to each element of the N-dim array, use ``applyfunc``:
>>> m3.applyfunc(lambda x: x/2)
[x**3/2, x*y/2, z/2]
N-dim arrays can be converted to nested lists by the ``tolist()`` method:
>>> m2.tolist()
[[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]]
>>> isinstance(m2.tolist(), list)
True
If the rank is 2, it is possible to convert them to matrices with ``tomatrix()``:
>>> m1.tomatrix()
Matrix([
[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]])
Products and contractions
-------------------------
Tensor product between arrays `A_{i_1,\ldots,i_n}` and `B_{j_1,\ldots,j_m}`
creates the combined array `P = A \otimes B` defined as
`P_{i_1,\ldots,i_n,j_1,\ldots,j_m} := A_{i_1,\ldots,i_n}\cdot B_{j_1,\ldots,j_m}.`
It is available through ``tensorproduct(...)``:
>>> from sympy import Array, tensorproduct
>>> from sympy.abc import x,y,z,t
>>> A = Array([x, y, z, t])
>>> B = Array([1, 2, 3, 4])
>>> tensorproduct(A, B)
[[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]]
In case you don't want to evaluate the tensor product immediately, you can use
``ArrayTensorProduct``, which creates an unevaluated tensor product expression:
>>> from sympy.tensor.array.expressions import ArrayTensorProduct
>>> ArrayTensorProduct(A, B)
ArrayTensorProduct([x, y, z, t], [1, 2, 3, 4])
Calling ``.as_explicit()`` on ``ArrayTensorProduct`` is equivalent to just calling
``tensorproduct(...)``:
>>> ArrayTensorProduct(A, B).as_explicit()
[[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]]
Tensor product between a rank-1 array and a matrix creates a rank-3 array:
>>> from sympy import eye
>>> p1 = tensorproduct(A, eye(4))
>>> p1
[[[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]], [[y, 0, 0, 0], [0, y, 0, 0], [0, 0, y, 0], [0, 0, 0, y]], [[z, 0, 0, 0], [0, z, 0, 0], [0, 0, z, 0], [0, 0, 0, z]], [[t, 0, 0, 0], [0, t, 0, 0], [0, 0, t, 0], [0, 0, 0, t]]]
Now, to get back `A_0 \otimes \mathbf{1}` one can access `p_{0,m,n}` by slicing:
>>> p1[0,:,:]
[[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]]
Tensor contraction sums over the specified axes, for example contracting
positions `a` and `b` means
`A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies \sum_k A_{i_1,\ldots,k,\ldots,k,\ldots,i_n}`
Remember that Python indexing is zero starting, to contract the a-th and b-th
axes it is therefore necessary to specify `a-1` and `b-1`
>>> from sympy import tensorcontraction
>>> C = Array([[x, y], [z, t]])
The matrix trace is equivalent to the contraction of a rank-2 array:
`A_{m,n} \implies \sum_k A_{k,k}`
>>> tensorcontraction(C, (0, 1))
t + x
To create an expression representing a tensor contraction that does not get
evaluated immediately, use ``ArrayContraction``, which is equivalent to
``tensorcontraction(...)`` if it is followed by ``.as_explicit()``:
>>> from sympy.tensor.array.expressions import ArrayContraction
>>> ArrayContraction(C, (0, 1))
ArrayContraction([[x, y], [z, t]], (0, 1))
>>> ArrayContraction(C, (0, 1)).as_explicit()
t + x
Matrix product is equivalent to a tensor product of two rank-2 arrays, followed
by a contraction of the 2nd and 3rd axes (in Python indexing axes number 1, 2).
`A_{m,n}\cdot B_{i,j} \implies \sum_k A_{m, k}\cdot B_{k, j}`
>>> D = Array([[2, 1], [0, -1]])
>>> tensorcontraction(tensorproduct(C, D), (1, 2))
[[2*x, x - y], [2*z, -t + z]]
One may verify that the matrix product is equivalent:
>>> from sympy import Matrix
>>> Matrix([[x, y], [z, t]])*Matrix([[2, 1], [0, -1]])
Matrix([
[2*x, x - y],
[2*z, -t + z]])
or equivalently
>>> C.tomatrix()*D.tomatrix()
Matrix([
[2*x, x - y],
[2*z, -t + z]])
Diagonal operator
-----------------
The ``tensordiagonal`` function acts in a similar manner as ``tensorcontraction``,
but the joined indices are not summed over, for example diagonalizing
positions `a` and `b` means
`A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies A_{i_1,\ldots,k,\ldots,k,\ldots,i_n}
\implies \tilde{A}_{i_1,\ldots,i_{a-1},i_{a+1},\ldots,i_{b-1},i_{b+1},\ldots,i_n,k}`
where `\tilde{A}` is the array equivalent to the diagonal of `A` at positions
`a` and `b` moved to the last index slot.
Compare the difference between contraction and diagonal operators:
>>> from sympy import tensordiagonal
>>> from sympy.abc import a, b, c, d
>>> m = Matrix([[a, b], [c, d]])
>>> tensorcontraction(m, [0, 1])
a + d
>>> tensordiagonal(m, [0, 1])
[a, d]
In short, no summation occurs with ``tensordiagonal``.
Derivatives by array
--------------------
The usual derivative operation may be extended to support derivation with
respect to arrays, provided that all elements in the that array are symbols or
expressions suitable for derivations.
The definition of a derivative by an array is as follows: given the array
`A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
the derivative of arrays will return a new array `B` defined by
`B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
The function ``derive_by_array`` performs such an operation:
>>> from sympy import derive_by_array
>>> from sympy.abc import x, y, z, t
>>> from sympy import sin, exp
With scalars, it behaves exactly as the ordinary derivative:
>>> derive_by_array(sin(x*y), x)
y*cos(x*y)
Scalar derived by an array basis:
>>> derive_by_array(sin(x*y), [x, y, z])
[y*cos(x*y), x*cos(x*y), 0]
Deriving array by an array basis: `B^{nm} := \frac{\partial A^m}{\partial x^n}`
>>> basis = [x, y, z]
>>> ax = derive_by_array([exp(x), sin(y*z), t], basis)
>>> ax
[[exp(x), 0, 0], [0, z*cos(y*z), 0], [0, y*cos(y*z), 0]]
Contraction of the resulting array: `\sum_m \frac{\partial A^m}{\partial x^m}`
>>> tensorcontraction(ax, (0, 1))
z*cos(y*z) + exp(x)
"""
from .dense_ndim_array import MutableDenseNDimArray, ImmutableDenseNDimArray, DenseNDimArray
from .sparse_ndim_array import MutableSparseNDimArray, ImmutableSparseNDimArray, SparseNDimArray
from .ndim_array import NDimArray, ArrayKind
from .arrayop import tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, permutedims
from .array_comprehension import ArrayComprehension, ArrayComprehensionMap
Array = ImmutableDenseNDimArray
__all__ = [
'MutableDenseNDimArray', 'ImmutableDenseNDimArray', 'DenseNDimArray',
'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'SparseNDimArray',
'NDimArray', 'ArrayKind',
'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array',
'permutedims', 'ArrayComprehension', 'ArrayComprehensionMap',
'Array',
]
|
51829d2906600ec5ed0e8a729964bc40cec565cc51d4ed03fdc6edf8a8f1ef23 | import itertools
from collections.abc import Iterable
from sympy.core._print_helpers import Printable
from sympy.core.containers import Tuple
from sympy.core.function import diff
from sympy.core.singleton import S
from sympy.core.sympify import _sympify
from sympy.tensor.array.ndim_array import NDimArray
from sympy.tensor.array.dense_ndim_array import DenseNDimArray, ImmutableDenseNDimArray
from sympy.tensor.array.sparse_ndim_array import SparseNDimArray
def _arrayfy(a):
from sympy.matrices import MatrixBase
if isinstance(a, NDimArray):
return a
if isinstance(a, (MatrixBase, list, tuple, Tuple)):
return ImmutableDenseNDimArray(a)
return a
def tensorproduct(*args):
"""
Tensor product among scalars or array-like objects.
The equivalent operator for array expressions is ``ArrayTensorProduct``,
which can be used to keep the expression unevaluated.
Examples
========
>>> from sympy.tensor.array import tensorproduct, Array
>>> from sympy.abc import x, y, z, t
>>> A = Array([[1, 2], [3, 4]])
>>> B = Array([x, y])
>>> tensorproduct(A, B)
[[[x, y], [2*x, 2*y]], [[3*x, 3*y], [4*x, 4*y]]]
>>> tensorproduct(A, x)
[[x, 2*x], [3*x, 4*x]]
>>> tensorproduct(A, B, B)
[[[[x**2, x*y], [x*y, y**2]], [[2*x**2, 2*x*y], [2*x*y, 2*y**2]]], [[[3*x**2, 3*x*y], [3*x*y, 3*y**2]], [[4*x**2, 4*x*y], [4*x*y, 4*y**2]]]]
Applying this function on two matrices will result in a rank 4 array.
>>> from sympy import Matrix, eye
>>> m = Matrix([[x, y], [z, t]])
>>> p = tensorproduct(eye(3), m)
>>> p
[[[[x, y], [z, t]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[x, y], [z, t]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[x, y], [z, t]]]]
See Also
========
sympy.tensor.array.expressions.array_expressions.ArrayTensorProduct
"""
from sympy.tensor.array import SparseNDimArray, ImmutableSparseNDimArray
if len(args) == 0:
return S.One
if len(args) == 1:
return _arrayfy(args[0])
from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
from sympy.matrices.expressions.matexpr import MatrixSymbol
if any(isinstance(arg, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)) for arg in args):
return ArrayTensorProduct(*args)
if len(args) > 2:
return tensorproduct(tensorproduct(args[0], args[1]), *args[2:])
# length of args is 2:
a, b = map(_arrayfy, args)
if not isinstance(a, NDimArray) or not isinstance(b, NDimArray):
return a*b
if isinstance(a, SparseNDimArray) and isinstance(b, SparseNDimArray):
lp = len(b)
new_array = {k1*lp + k2: v1*v2 for k1, v1 in a._sparse_array.items() for k2, v2 in b._sparse_array.items()}
return ImmutableSparseNDimArray(new_array, a.shape + b.shape)
product_list = [i*j for i in Flatten(a) for j in Flatten(b)]
return ImmutableDenseNDimArray(product_list, a.shape + b.shape)
def _util_contraction_diagonal(array, *contraction_or_diagonal_axes):
array = _arrayfy(array)
# Verify contraction_axes:
taken_dims = set()
for axes_group in contraction_or_diagonal_axes:
if not isinstance(axes_group, Iterable):
raise ValueError("collections of contraction/diagonal axes expected")
dim = array.shape[axes_group[0]]
for d in axes_group:
if d in taken_dims:
raise ValueError("dimension specified more than once")
if dim != array.shape[d]:
raise ValueError("cannot contract or diagonalize between axes of different dimension")
taken_dims.add(d)
rank = array.rank()
remaining_shape = [dim for i, dim in enumerate(array.shape) if i not in taken_dims]
cum_shape = [0]*rank
_cumul = 1
for i in range(rank):
cum_shape[rank - i - 1] = _cumul
_cumul *= int(array.shape[rank - i - 1])
# DEFINITION: by absolute position it is meant the position along the one
# dimensional array containing all the tensor components.
# Possible future work on this module: move computation of absolute
# positions to a class method.
# Determine absolute positions of the uncontracted indices:
remaining_indices = [[cum_shape[i]*j for j in range(array.shape[i])]
for i in range(rank) if i not in taken_dims]
# Determine absolute positions of the contracted indices:
summed_deltas = []
for axes_group in contraction_or_diagonal_axes:
lidx = []
for js in range(array.shape[axes_group[0]]):
lidx.append(sum([cum_shape[ig] * js for ig in axes_group]))
summed_deltas.append(lidx)
return array, remaining_indices, remaining_shape, summed_deltas
def tensorcontraction(array, *contraction_axes):
"""
Contraction of an array-like object on the specified axes.
The equivalent operator for array expressions is ``ArrayContraction``,
which can be used to keep the expression unevaluated.
Examples
========
>>> from sympy import Array, tensorcontraction
>>> from sympy import Matrix, eye
>>> tensorcontraction(eye(3), (0, 1))
3
>>> A = Array(range(18), (3, 2, 3))
>>> A
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
>>> tensorcontraction(A, (0, 2))
[21, 30]
Matrix multiplication may be emulated with a proper combination of
``tensorcontraction`` and ``tensorproduct``
>>> from sympy import tensorproduct
>>> from sympy.abc import a,b,c,d,e,f,g,h
>>> m1 = Matrix([[a, b], [c, d]])
>>> m2 = Matrix([[e, f], [g, h]])
>>> p = tensorproduct(m1, m2)
>>> p
[[[[a*e, a*f], [a*g, a*h]], [[b*e, b*f], [b*g, b*h]]], [[[c*e, c*f], [c*g, c*h]], [[d*e, d*f], [d*g, d*h]]]]
>>> tensorcontraction(p, (1, 2))
[[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]]
>>> m1*m2
Matrix([
[a*e + b*g, a*f + b*h],
[c*e + d*g, c*f + d*h]])
See Also
========
sympy.tensor.array.expressions.array_expressions.ArrayContraction
"""
from sympy.tensor.array.expressions.array_expressions import _array_contraction
from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
from sympy.matrices.expressions.matexpr import MatrixSymbol
if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
return _array_contraction(array, *contraction_axes)
array, remaining_indices, remaining_shape, summed_deltas = _util_contraction_diagonal(array, *contraction_axes)
# Compute the contracted array:
#
# 1. external for loops on all uncontracted indices.
# Uncontracted indices are determined by the combinatorial product of
# the absolute positions of the remaining indices.
# 2. internal loop on all contracted indices.
# It sums the values of the absolute contracted index and the absolute
# uncontracted index for the external loop.
contracted_array = []
for icontrib in itertools.product(*remaining_indices):
index_base_position = sum(icontrib)
isum = S.Zero
for sum_to_index in itertools.product(*summed_deltas):
idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
isum += array[idx]
contracted_array.append(isum)
if len(remaining_indices) == 0:
assert len(contracted_array) == 1
return contracted_array[0]
return type(array)(contracted_array, remaining_shape)
def tensordiagonal(array, *diagonal_axes):
"""
Diagonalization of an array-like object on the specified axes.
This is equivalent to multiplying the expression by Kronecker deltas
uniting the axes.
The diagonal indices are put at the end of the axes.
The equivalent operator for array expressions is ``ArrayDiagonal``, which
can be used to keep the expression unevaluated.
Examples
========
``tensordiagonal`` acting on a 2-dimensional array by axes 0 and 1 is
equivalent to the diagonal of the matrix:
>>> from sympy import Array, tensordiagonal
>>> from sympy import Matrix, eye
>>> tensordiagonal(eye(3), (0, 1))
[1, 1, 1]
>>> from sympy.abc import a,b,c,d
>>> m1 = Matrix([[a, b], [c, d]])
>>> tensordiagonal(m1, [0, 1])
[a, d]
In case of higher dimensional arrays, the diagonalized out dimensions
are appended removed and appended as a single dimension at the end:
>>> A = Array(range(18), (3, 2, 3))
>>> A
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
>>> tensordiagonal(A, (0, 2))
[[0, 7, 14], [3, 10, 17]]
>>> from sympy import permutedims
>>> tensordiagonal(A, (0, 2)) == permutedims(Array([A[0, :, 0], A[1, :, 1], A[2, :, 2]]), [1, 0])
True
See Also
========
sympy.tensor.array.expressions.array_expressions.ArrayDiagonal
"""
if any(len(i) <= 1 for i in diagonal_axes):
raise ValueError("need at least two axes to diagonalize")
from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal, _array_diagonal
from sympy.matrices.expressions.matexpr import MatrixSymbol
if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
return _array_diagonal(array, *diagonal_axes)
ArrayDiagonal._validate(array, *diagonal_axes)
array, remaining_indices, remaining_shape, diagonal_deltas = _util_contraction_diagonal(array, *diagonal_axes)
# Compute the diagonalized array:
#
# 1. external for loops on all undiagonalized indices.
# Undiagonalized indices are determined by the combinatorial product of
# the absolute positions of the remaining indices.
# 2. internal loop on all diagonal indices.
# It appends the values of the absolute diagonalized index and the absolute
# undiagonalized index for the external loop.
diagonalized_array = []
diagonal_shape = [len(i) for i in diagonal_deltas]
for icontrib in itertools.product(*remaining_indices):
index_base_position = sum(icontrib)
isum = []
for sum_to_index in itertools.product(*diagonal_deltas):
idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
isum.append(array[idx])
isum = type(array)(isum).reshape(*diagonal_shape)
diagonalized_array.append(isum)
return type(array)(diagonalized_array, remaining_shape + diagonal_shape)
def derive_by_array(expr, dx):
r"""
Derivative by arrays. Supports both arrays and scalars.
The equivalent operator for array expressions is ``array_derive``.
Explanation
===========
Given the array `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
this function will return a new array `B` defined by
`B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
Examples
========
>>> from sympy import derive_by_array
>>> from sympy.abc import x, y, z, t
>>> from sympy import cos
>>> derive_by_array(cos(x*t), x)
-t*sin(t*x)
>>> derive_by_array(cos(x*t), [x, y, z, t])
[-t*sin(t*x), 0, 0, -x*sin(t*x)]
>>> derive_by_array([x, y**2*z], [[x, y], [z, t]])
[[[1, 0], [0, 2*y*z]], [[0, y**2], [0, 0]]]
"""
from sympy.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
array_types = (Iterable, MatrixBase, NDimArray)
if isinstance(dx, array_types):
dx = ImmutableDenseNDimArray(dx)
for i in dx:
if not i._diff_wrt:
raise ValueError("cannot derive by this array")
if isinstance(expr, array_types):
if isinstance(expr, NDimArray):
expr = expr.as_immutable()
else:
expr = ImmutableDenseNDimArray(expr)
if isinstance(dx, array_types):
if isinstance(expr, SparseNDimArray):
lp = len(expr)
new_array = {k + i*lp: v
for i, x in enumerate(Flatten(dx))
for k, v in expr.diff(x)._sparse_array.items()}
else:
new_array = [[y.diff(x) for y in Flatten(expr)] for x in Flatten(dx)]
return type(expr)(new_array, dx.shape + expr.shape)
else:
return expr.diff(dx)
else:
expr = _sympify(expr)
if isinstance(dx, array_types):
return ImmutableDenseNDimArray([expr.diff(i) for i in Flatten(dx)], dx.shape)
else:
dx = _sympify(dx)
return diff(expr, dx)
def permutedims(expr, perm=None, index_order_old=None, index_order_new=None):
"""
Permutes the indices of an array.
Parameter specifies the permutation of the indices.
The equivalent operator for array expressions is ``PermuteDims``, which can
be used to keep the expression unevaluated.
Examples
========
>>> from sympy.abc import x, y, z, t
>>> from sympy import sin
>>> from sympy import Array, permutedims
>>> a = Array([[x, y, z], [t, sin(x), 0]])
>>> a
[[x, y, z], [t, sin(x), 0]]
>>> permutedims(a, (1, 0))
[[x, t], [y, sin(x)], [z, 0]]
If the array is of second order, ``transpose`` can be used:
>>> from sympy import transpose
>>> transpose(a)
[[x, t], [y, sin(x)], [z, 0]]
Examples on higher dimensions:
>>> b = Array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
>>> permutedims(b, (2, 1, 0))
[[[1, 5], [3, 7]], [[2, 6], [4, 8]]]
>>> permutedims(b, (1, 2, 0))
[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
An alternative way to specify the same permutations as in the previous
lines involves passing the *old* and *new* indices, either as a list or as
a string:
>>> permutedims(b, index_order_old="cba", index_order_new="abc")
[[[1, 5], [3, 7]], [[2, 6], [4, 8]]]
>>> permutedims(b, index_order_old="cab", index_order_new="abc")
[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
``Permutation`` objects are also allowed:
>>> from sympy.combinatorics import Permutation
>>> permutedims(b, Permutation([1, 2, 0]))
[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
See Also
========
sympy.tensor.array.expressions.array_expressions.PermuteDims
"""
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
from sympy.tensor.array.expressions.array_expressions import _permute_dims
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.tensor.array.expressions import PermuteDims
from sympy.tensor.array.expressions.array_expressions import get_rank
perm = PermuteDims._get_permutation_from_arguments(perm, index_order_old, index_order_new, get_rank(expr))
if isinstance(expr, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
return _permute_dims(expr, perm)
if not isinstance(expr, NDimArray):
expr = ImmutableDenseNDimArray(expr)
from sympy.combinatorics import Permutation
if not isinstance(perm, Permutation):
perm = Permutation(list(perm))
if perm.size != expr.rank():
raise ValueError("wrong permutation size")
# Get the inverse permutation:
iperm = ~perm
new_shape = perm(expr.shape)
if isinstance(expr, SparseNDimArray):
return type(expr)({tuple(perm(expr._get_tuple_index(k))): v
for k, v in expr._sparse_array.items()}, new_shape)
indices_span = perm([range(i) for i in expr.shape])
new_array = [None]*len(expr)
for i, idx in enumerate(itertools.product(*indices_span)):
t = iperm(idx)
new_array[i] = expr[t]
return type(expr)(new_array, new_shape)
class Flatten(Printable):
"""
Flatten an iterable object to a list in a lazy-evaluation way.
Notes
=====
This class is an iterator with which the memory cost can be economised.
Optimisation has been considered to ameliorate the performance for some
specific data types like DenseNDimArray and SparseNDimArray.
Examples
========
>>> from sympy.tensor.array.arrayop import Flatten
>>> from sympy.tensor.array import Array
>>> A = Array(range(6)).reshape(2, 3)
>>> Flatten(A)
Flatten([[0, 1, 2], [3, 4, 5]])
>>> [i for i in Flatten(A)]
[0, 1, 2, 3, 4, 5]
"""
def __init__(self, iterable):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import NDimArray
if not isinstance(iterable, (Iterable, MatrixBase)):
raise NotImplementedError("Data type not yet supported")
if isinstance(iterable, list):
iterable = NDimArray(iterable)
self._iter = iterable
self._idx = 0
def __iter__(self):
return self
def __next__(self):
from sympy.matrices.matrices import MatrixBase
if len(self._iter) > self._idx:
if isinstance(self._iter, DenseNDimArray):
result = self._iter._array[self._idx]
elif isinstance(self._iter, SparseNDimArray):
if self._idx in self._iter._sparse_array:
result = self._iter._sparse_array[self._idx]
else:
result = 0
elif isinstance(self._iter, MatrixBase):
result = self._iter[self._idx]
elif hasattr(self._iter, '__next__'):
result = next(self._iter)
else:
result = self._iter[self._idx]
else:
raise StopIteration
self._idx += 1
return result
def next(self):
return self.__next__()
def _sympystr(self, printer):
return type(self).__name__ + '(' + printer._print(self._iter) + ')'
|
b38ff5b88269a7dd647aa5b1cfdee784fb55f9337d0641ef0aead9b38e0d49fa | from sympy.core.basic import Basic
from sympy.core.containers import (Dict, Tuple)
from sympy.core.expr import Expr
from sympy.core.kind import Kind, NumberKind, UndefinedKind
from sympy.core.numbers import Integer
from sympy.core.singleton import S
from sympy.core.sympify import sympify
from sympy.external.gmpy import SYMPY_INTS
from sympy.printing.defaults import Printable
import itertools
from collections.abc import Iterable
class ArrayKind(Kind):
"""
Kind for N-dimensional array in SymPy.
This kind represents the multidimensional array that algebraic
operations are defined. Basic class for this kind is ``NDimArray``,
but any expression representing the array can have this.
Parameters
==========
element_kind : Kind
Kind of the element. Default is :obj:NumberKind `<sympy.core.kind.NumberKind>`,
which means that the array contains only numbers.
Examples
========
Any instance of array class has ``ArrayKind``.
>>> from sympy import NDimArray
>>> NDimArray([1,2,3]).kind
ArrayKind(NumberKind)
Although expressions representing an array may be not instance of
array class, it will have ``ArrayKind`` as well.
>>> from sympy import Integral
>>> from sympy.tensor.array import NDimArray
>>> from sympy.abc import x
>>> intA = Integral(NDimArray([1,2,3]), x)
>>> isinstance(intA, NDimArray)
False
>>> intA.kind
ArrayKind(NumberKind)
Use ``isinstance()`` to check for ``ArrayKind` without specifying
the element kind. Use ``is`` with specifying the element kind.
>>> from sympy.tensor.array import ArrayKind
>>> from sympy.core import NumberKind
>>> boolA = NDimArray([True, False])
>>> isinstance(boolA.kind, ArrayKind)
True
>>> boolA.kind is ArrayKind(NumberKind)
False
See Also
========
shape : Function to return the shape of objects with ``MatrixKind``.
"""
def __new__(cls, element_kind=NumberKind):
obj = super().__new__(cls, element_kind)
obj.element_kind = element_kind
return obj
def __repr__(self):
return "ArrayKind(%s)" % self.element_kind
@classmethod
def _union(cls, kinds) -> 'ArrayKind':
elem_kinds = set(e.kind for e in kinds)
if len(elem_kinds) == 1:
elemkind, = elem_kinds
else:
elemkind = UndefinedKind
return ArrayKind(elemkind)
class NDimArray(Printable):
"""N-dimensional array.
Examples
========
Create an N-dim array of zeros:
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 3, 4)
>>> a
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
Create an N-dim array from a list;
>>> a = MutableDenseNDimArray([[2, 3], [4, 5]])
>>> a
[[2, 3], [4, 5]]
>>> b = MutableDenseNDimArray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
>>> b
[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]
Create an N-dim array from a flat list with dimension shape:
>>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
>>> a
[[1, 2, 3], [4, 5, 6]]
Create an N-dim array from a matrix:
>>> from sympy import Matrix
>>> a = Matrix([[1,2],[3,4]])
>>> a
Matrix([
[1, 2],
[3, 4]])
>>> b = MutableDenseNDimArray(a)
>>> b
[[1, 2], [3, 4]]
Arithmetic operations on N-dim arrays
>>> a = MutableDenseNDimArray([1, 1, 1, 1], (2, 2))
>>> b = MutableDenseNDimArray([4, 4, 4, 4], (2, 2))
>>> c = a + b
>>> c
[[5, 5], [5, 5]]
>>> a - b
[[-3, -3], [-3, -3]]
"""
_diff_wrt = True
is_scalar = False
def __new__(cls, iterable, shape=None, **kwargs):
from sympy.tensor.array import ImmutableDenseNDimArray
return ImmutableDenseNDimArray(iterable, shape, **kwargs)
def __getitem__(self, index):
raise NotImplementedError("A subclass of NDimArray should implement __getitem__")
def _parse_index(self, index):
if isinstance(index, (SYMPY_INTS, Integer)):
if index >= self._loop_size:
raise ValueError("Only a tuple index is accepted")
return index
if self._loop_size == 0:
raise ValueError("Index not valid with an empty array")
if len(index) != self._rank:
raise ValueError('Wrong number of array axes')
real_index = 0
# check if input index can exist in current indexing
for i in range(self._rank):
if (index[i] >= self.shape[i]) or (index[i] < -self.shape[i]):
raise ValueError('Index ' + str(index) + ' out of border')
if index[i] < 0:
real_index += 1
real_index = real_index*self.shape[i] + index[i]
return real_index
def _get_tuple_index(self, integer_index):
index = []
for i, sh in enumerate(reversed(self.shape)):
index.append(integer_index % sh)
integer_index //= sh
index.reverse()
return tuple(index)
def _check_symbolic_index(self, index):
# Check if any index is symbolic:
tuple_index = (index if isinstance(index, tuple) else (index,))
if any((isinstance(i, Expr) and (not i.is_number)) for i in tuple_index):
for i, nth_dim in zip(tuple_index, self.shape):
if ((i < 0) == True) or ((i >= nth_dim) == True):
raise ValueError("index out of range")
from sympy.tensor import Indexed
return Indexed(self, *tuple_index)
return None
def _setter_iterable_check(self, value):
from sympy.matrices.matrices import MatrixBase
if isinstance(value, (Iterable, MatrixBase, NDimArray)):
raise NotImplementedError
@classmethod
def _scan_iterable_shape(cls, iterable):
def f(pointer):
if not isinstance(pointer, Iterable):
return [pointer], ()
if len(pointer) == 0:
return [], (0,)
result = []
elems, shapes = zip(*[f(i) for i in pointer])
if len(set(shapes)) != 1:
raise ValueError("could not determine shape unambiguously")
for i in elems:
result.extend(i)
return result, (len(shapes),)+shapes[0]
return f(iterable)
@classmethod
def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
if shape is None:
if iterable is None:
shape = ()
iterable = ()
# Construction of a sparse array from a sparse array
elif isinstance(iterable, SparseNDimArray):
return iterable._shape, iterable._sparse_array
# Construct N-dim array from another N-dim array:
elif isinstance(iterable, NDimArray):
shape = iterable.shape
# Construct N-dim array from an iterable (numpy arrays included):
elif isinstance(iterable, Iterable):
iterable, shape = cls._scan_iterable_shape(iterable)
# Construct N-dim array from a Matrix:
elif isinstance(iterable, MatrixBase):
shape = iterable.shape
else:
shape = ()
iterable = (iterable,)
if isinstance(iterable, (Dict, dict)) and shape is not None:
new_dict = iterable.copy()
for k, v in new_dict.items():
if isinstance(k, (tuple, Tuple)):
new_key = 0
for i, idx in enumerate(k):
new_key = new_key * shape[i] + idx
iterable[new_key] = iterable[k]
del iterable[k]
if isinstance(shape, (SYMPY_INTS, Integer)):
shape = (shape,)
if not all(isinstance(dim, (SYMPY_INTS, Integer)) for dim in shape):
raise TypeError("Shape should contain integers only.")
return tuple(shape), iterable
def __len__(self):
"""Overload common function len(). Returns number of elements in array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3, 3)
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> len(a)
9
"""
return self._loop_size
@property
def shape(self):
"""
Returns array shape (dimension).
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3, 3)
>>> a.shape
(3, 3)
"""
return self._shape
def rank(self):
"""
Returns rank of array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3,4,5,6,3)
>>> a.rank()
5
"""
return self._rank
def diff(self, *args, **kwargs):
"""
Calculate the derivative of each element in the array.
Examples
========
>>> from sympy import ImmutableDenseNDimArray
>>> from sympy.abc import x, y
>>> M = ImmutableDenseNDimArray([[x, y], [1, x*y]])
>>> M.diff(x)
[[1, 0], [0, y]]
"""
from sympy.tensor.array.array_derivatives import ArrayDerivative
kwargs.setdefault('evaluate', True)
return ArrayDerivative(self.as_immutable(), *args, **kwargs)
def _eval_derivative(self, base):
# Types are (base: scalar, self: array)
return self.applyfunc(lambda x: base.diff(x))
def _eval_derivative_n_times(self, s, n):
return Basic._eval_derivative_n_times(self, s, n)
def applyfunc(self, f):
"""Apply a function to each element of the N-dim array.
Examples
========
>>> from sympy import ImmutableDenseNDimArray
>>> m = ImmutableDenseNDimArray([i*2+j for i in range(2) for j in range(2)], (2, 2))
>>> m
[[0, 1], [2, 3]]
>>> m.applyfunc(lambda i: 2*i)
[[0, 2], [4, 6]]
"""
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(self, SparseNDimArray) and f(S.Zero) == 0:
return type(self)({k: f(v) for k, v in self._sparse_array.items() if f(v) != 0}, self.shape)
return type(self)(map(f, Flatten(self)), self.shape)
def _sympystr(self, printer):
def f(sh, shape_left, i, j):
if len(shape_left) == 1:
return "["+", ".join([printer._print(self[self._get_tuple_index(e)]) for e in range(i, j)])+"]"
sh //= shape_left[0]
return "[" + ", ".join([f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh) for e in range(shape_left[0])]) + "]" # + "\n"*len(shape_left)
if self.rank() == 0:
return printer._print(self[()])
return f(self._loop_size, self.shape, 0, self._loop_size)
def tolist(self):
"""
Converting MutableDenseNDimArray to one-dim list
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
>>> a
[[1, 2], [3, 4]]
>>> b = a.tolist()
>>> b
[[1, 2], [3, 4]]
"""
def f(sh, shape_left, i, j):
if len(shape_left) == 1:
return [self[self._get_tuple_index(e)] for e in range(i, j)]
result = []
sh //= shape_left[0]
for e in range(shape_left[0]):
result.append(f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh))
return result
return f(self._loop_size, self.shape, 0, self._loop_size)
def __add__(self, other):
from sympy.tensor.array.arrayop import Flatten
if not isinstance(other, NDimArray):
return NotImplemented
if self.shape != other.shape:
raise ValueError("array shape mismatch")
result_list = [i+j for i,j in zip(Flatten(self), Flatten(other))]
return type(self)(result_list, self.shape)
def __sub__(self, other):
from sympy.tensor.array.arrayop import Flatten
if not isinstance(other, NDimArray):
return NotImplemented
if self.shape != other.shape:
raise ValueError("array shape mismatch")
result_list = [i-j for i,j in zip(Flatten(self), Flatten(other))]
return type(self)(result_list, self.shape)
def __mul__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
other = sympify(other)
if isinstance(self, SparseNDimArray):
if other.is_zero:
return type(self)({}, self.shape)
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [i*other for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __rmul__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
other = sympify(other)
if isinstance(self, SparseNDimArray):
if other.is_zero:
return type(self)({}, self.shape)
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [other*i for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __truediv__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected")
other = sympify(other)
if isinstance(self, SparseNDimArray) and other != S.Zero:
return type(self)({k: v/other for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [i/other for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __rtruediv__(self, other):
raise NotImplementedError('unsupported operation on NDimArray')
def __neg__(self):
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(self, SparseNDimArray):
return type(self)({k: -v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [-i for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __iter__(self):
def iterator():
if self._shape:
for i in range(self._shape[0]):
yield self[i]
else:
yield self[()]
return iterator()
def __eq__(self, other):
"""
NDimArray instances can be compared to each other.
Instances equal if they have same shape and data.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 3)
>>> b = MutableDenseNDimArray.zeros(2, 3)
>>> a == b
True
>>> c = a.reshape(3, 2)
>>> c == b
False
>>> a[0,0] = 1
>>> b[0,0] = 2
>>> a == b
False
"""
from sympy.tensor.array import SparseNDimArray
if not isinstance(other, NDimArray):
return False
if not self.shape == other.shape:
return False
if isinstance(self, SparseNDimArray) and isinstance(other, SparseNDimArray):
return dict(self._sparse_array) == dict(other._sparse_array)
return list(self) == list(other)
def __ne__(self, other):
return not self == other
def _eval_transpose(self):
if self.rank() != 2:
raise ValueError("array rank not 2")
from .arrayop import permutedims
return permutedims(self, (1, 0))
def transpose(self):
return self._eval_transpose()
def _eval_conjugate(self):
from sympy.tensor.array.arrayop import Flatten
return self.func([i.conjugate() for i in Flatten(self)], self.shape)
def conjugate(self):
return self._eval_conjugate()
def _eval_adjoint(self):
return self.transpose().conjugate()
def adjoint(self):
return self._eval_adjoint()
def _slice_expand(self, s, dim):
if not isinstance(s, slice):
return (s,)
start, stop, step = s.indices(dim)
return [start + i*step for i in range((stop-start)//step)]
def _get_slice_data_for_array_access(self, index):
sl_factors = [self._slice_expand(i, dim) for (i, dim) in zip(index, self.shape)]
eindices = itertools.product(*sl_factors)
return sl_factors, eindices
def _get_slice_data_for_array_assignment(self, index, value):
if not isinstance(value, NDimArray):
value = type(self)(value)
sl_factors, eindices = self._get_slice_data_for_array_access(index)
slice_offsets = [min(i) if isinstance(i, list) else None for i in sl_factors]
# TODO: add checks for dimensions for `value`?
return value, eindices, slice_offsets
@classmethod
def _check_special_bounds(cls, flat_list, shape):
if shape == () and len(flat_list) != 1:
raise ValueError("arrays without shape need one scalar value")
if shape == (0,) and len(flat_list) > 0:
raise ValueError("if array shape is (0,) there cannot be elements")
def _check_index_for_getitem(self, index):
if isinstance(index, (SYMPY_INTS, Integer, slice)):
index = (index,)
if len(index) < self.rank():
index = tuple(index) + \
tuple(slice(None) for i in range(len(index), self.rank()))
if len(index) > self.rank():
raise ValueError('Dimension of index greater than rank of array')
return index
class ImmutableNDimArray(NDimArray, Basic):
_op_priority = 11.0
def __hash__(self):
return Basic.__hash__(self)
def as_immutable(self):
return self
def as_mutable(self):
raise NotImplementedError("abstract method")
|
21ef2a54c272a764ecabb6958666693d7f17f8a4e517db9ac6441f4f3099f73f | import functools
from typing import List
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.singleton import S
from sympy.core.sympify import _sympify
from sympy.tensor.array.mutable_ndim_array import MutableNDimArray
from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray, ArrayKind
from sympy.utilities.iterables import flatten
class DenseNDimArray(NDimArray):
_array: List[Basic]
def __new__(self, *args, **kwargs):
return ImmutableDenseNDimArray(*args, **kwargs)
@property
def kind(self) -> ArrayKind:
return ArrayKind._union(self._array)
def __getitem__(self, index):
"""
Allows to get items from N-dim array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([0, 1, 2, 3], (2, 2))
>>> a
[[0, 1], [2, 3]]
>>> a[0, 0]
0
>>> a[1, 1]
3
>>> a[0]
[0, 1]
>>> a[1]
[2, 3]
Symbolic index:
>>> from sympy.abc import i, j
>>> a[i, j]
[[0, 1], [2, 3]][i, j]
Replace `i` and `j` to get element `(1, 1)`:
>>> a[i, j].subs({i: 1, j: 1})
3
"""
syindex = self._check_symbolic_index(index)
if syindex is not None:
return syindex
index = self._check_index_for_getitem(index)
if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
sl_factors, eindices = self._get_slice_data_for_array_access(index)
array = [self._array[self._parse_index(i)] for i in eindices]
nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)]
return type(self)(array, nshape)
else:
index = self._parse_index(index)
return self._array[index]
@classmethod
def zeros(cls, *shape):
list_length = functools.reduce(lambda x, y: x*y, shape, S.One)
return cls._new(([0]*list_length,), shape)
def tomatrix(self):
"""
Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([1 for i in range(9)], (3, 3))
>>> b = a.tomatrix()
>>> b
Matrix([
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
"""
from sympy.matrices import Matrix
if self.rank() != 2:
raise ValueError('Dimensions must be of size of 2')
return Matrix(self.shape[0], self.shape[1], self._array)
def reshape(self, *newshape):
"""
Returns MutableDenseNDimArray instance with new shape. Elements number
must be suitable to new shape. The only argument of method sets
new shape.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
>>> a.shape
(2, 3)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b = a.reshape(3, 2)
>>> b.shape
(3, 2)
>>> b
[[1, 2], [3, 4], [5, 6]]
"""
new_total_size = functools.reduce(lambda x,y: x*y, newshape)
if new_total_size != self._loop_size:
raise ValueError('Expecting reshape size to %d but got prod(%s) = %d' % (
self._loop_size, str(newshape), new_total_size))
# there is no `.func` as this class does not subtype `Basic`:
return type(self)(self._array, newshape)
class ImmutableDenseNDimArray(DenseNDimArray, ImmutableNDimArray): # type: ignore
def __new__(cls, iterable, shape=None, **kwargs):
return cls._new(iterable, shape, **kwargs)
@classmethod
def _new(cls, iterable, shape, **kwargs):
shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
shape = Tuple(*map(_sympify, shape))
cls._check_special_bounds(flat_list, shape)
flat_list = flatten(flat_list)
flat_list = Tuple(*flat_list)
self = Basic.__new__(cls, flat_list, shape, **kwargs)
self._shape = shape
self._array = list(flat_list)
self._rank = len(shape)
self._loop_size = functools.reduce(lambda x,y: x*y, shape, 1)
return self
def __setitem__(self, index, value):
raise TypeError('immutable N-dim array')
def as_mutable(self):
return MutableDenseNDimArray(self)
def _eval_simplify(self, **kwargs):
from sympy.simplify.simplify import simplify
return self.applyfunc(simplify)
class MutableDenseNDimArray(DenseNDimArray, MutableNDimArray):
def __new__(cls, iterable=None, shape=None, **kwargs):
return cls._new(iterable, shape, **kwargs)
@classmethod
def _new(cls, iterable, shape, **kwargs):
shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
flat_list = flatten(flat_list)
self = object.__new__(cls)
self._shape = shape
self._array = list(flat_list)
self._rank = len(shape)
self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
return self
def __setitem__(self, index, value):
"""Allows to set items to MutableDenseNDimArray.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 2)
>>> a[0,0] = 1
>>> a[1,1] = 1
>>> a
[[1, 0], [0, 1]]
"""
if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value)
for i in eindices:
other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None]
self._array[self._parse_index(i)] = value[other_i]
else:
index = self._parse_index(index)
self._setter_iterable_check(value)
value = _sympify(value)
self._array[index] = value
def as_immutable(self):
return ImmutableDenseNDimArray(self)
@property
def free_symbols(self):
return {i for j in self._array for i in j.free_symbols}
|
2726c7d8001b1063686f8e08eaf97bba28b2fd5a664783b880a09939fc033d61 | from sympy.concrete.summations import Sum
from sympy.core.function import expand
from sympy.core.numbers import Integer
from sympy.matrices.dense import (Matrix, eye)
from sympy.tensor.indexed import Indexed
from sympy.combinatorics import Permutation
from sympy.core import S, Rational, Symbol, Basic, Add
from sympy.core.containers import Tuple
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.tensor.array import Array
from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, \
get_symmetric_group_sgs, TensorIndex, tensor_mul, TensAdd, \
riemann_cyclic_replace, riemann_cyclic, TensMul, tensor_heads, \
TensorManager, TensExpr, TensorHead, canon_bp, \
tensorhead, tensorsymmetry, TensorType, substitute_indices, \
WildTensorIndex, WildTensorHead, _WildTensExpr
from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy
from sympy.matrices import diag
def _is_equal(arg1, arg2):
if isinstance(arg1, TensExpr):
return arg1.equals(arg2)
elif isinstance(arg2, TensExpr):
return arg2.equals(arg1)
return arg1 == arg2
#################### Tests from tensor_can.py #######################
def test_canonicalize_no_slot_sym():
# A_d0 * B^d0; T_c = A^d0*B_d0
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, d0, d1 = tensor_indices('a,b,d0,d1', Lorentz)
A, B = tensor_heads('A,B', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(-d0)*B(d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0)*B(-L_0)'
# A^a * B^b; T_c = T
t = A(a)*B(b)
tc = t.canon_bp()
assert tc == t
# B^b * A^a
t1 = B(b)*A(a)
tc = t1.canon_bp()
assert str(tc) == 'A(a)*B(b)'
# A symmetric
# A^{b}_{d0}*A^{d0, a}; T_c = A^{a d0}*A{b}_{d0}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(b, -d0)*A(d0, a)
tc = t.canon_bp()
assert str(tc) == 'A(a, L_0)*A(b, -L_0)'
# A^{d1}_{d0}*B^d0*C_d1
# T_c = A^{d0 d1}*B_d0*C_d1
B, C = tensor_heads('B,C', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(d1, -d0)*B(d0)*C(-d1)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_0)*C(-L_1)'
# A without symmetry
# A^{d1}_{d0}*B^d0*C_d1 ord=[d0,-d0,d1,-d1]; g = [2,1,0,3,4,5]
# T_c = A^{d0 d1}*B_d1*C_d0; can = [0,2,3,1,4,5]
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, -d0)*B(d0)*C(-d1)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_1)*C(-L_0)'
# A, B without symmetry
# A^{d1}_{d0}*B_{d1}^{d0}
# T_c = A^{d0 d1}*B_{d0 d1}
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, -d0)*B(-d1, d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_0, -L_1)'
# A_{d0}^{d1}*B_{d1}^{d0}
# T_c = A^{d0 d1}*B_{d1 d0}
t = A(-d0, d1)*B(-d1, d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_1, -L_0)'
# A, B, C without symmetry
# A^{d1 d0}*B_{a d0}*C_{d1 b}
# T_c=A^{d0 d1}*B_{a d1}*C_{d0 b}
C = TensorHead('C', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-a, -L_1)*C(-L_0, -b)'
# A symmetric, B and C without symmetry
# A^{d1 d0}*B_{a d0}*C_{d1 b}
# T_c = A^{d0 d1}*B_{a d0}*C_{d1 b}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-L_1, -b)'
# A and C symmetric, B without symmetry
# A^{d1 d0}*B_{a d0}*C_{d1 b} ord=[a,b,d0,-d0,d1,-d1]
# T_c = A^{d0 d1}*B_{a d0}*C_{b d1}
C = TensorHead('C', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-b, -L_1)'
def test_canonicalize_no_dummies():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a, b, c, d', Lorentz)
# A commuting
# A^c A^b A^a
# T_c = A^a A^b A^c
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(c)*A(b)*A(a)
tc = t.canon_bp()
assert str(tc) == 'A(a)*A(b)*A(c)'
# A anticommuting
# A^c A^b A^a
# T_c = -A^a A^b A^c
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1)
t = A(c)*A(b)*A(a)
tc = t.canon_bp()
assert str(tc) == '-A(a)*A(b)*A(c)'
# A commuting and symmetric
# A^{b,d}*A^{c,a}
# T_c = A^{a c}*A^{b d}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(b, d)*A(c, a)
tc = t.canon_bp()
assert str(tc) == 'A(a, c)*A(b, d)'
# A anticommuting and symmetric
# A^{b,d}*A^{c,a}
# T_c = -A^{a c}*A^{b d}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2), 1)
t = A(b, d)*A(c, a)
tc = t.canon_bp()
assert str(tc) == '-A(a, c)*A(b, d)'
# A^{c,a}*A^{b,d}
# T_c = A^{a c}*A^{b d}
t = A(c, a)*A(b, d)
tc = t.canon_bp()
assert str(tc) == 'A(a, c)*A(b, d)'
def test_tensorhead_construction_without_symmetry():
L = TensorIndexType('Lorentz')
A1 = TensorHead('A', [L, L])
A2 = TensorHead('A', [L, L], TensorSymmetry.no_symmetry(2))
assert A1 == A2
A3 = TensorHead('A', [L, L], TensorSymmetry.fully_symmetric(2)) # Symmetric
assert A1 != A3
def test_no_metric_symmetry():
# no metric symmetry; A no symmetry
# A^d1_d0 * A^d0_d1
# T_c = A^d0_d1 * A^d1_d0
Lorentz = TensorIndexType('Lorentz', dummy_name='L', metric_symmetry=0)
d0, d1, d2, d3 = tensor_indices('d:4', Lorentz)
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, -d0)*A(d0, -d1)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)'
# A^d1_d2 * A^d0_d3 * A^d2_d1 * A^d3_d0
# T_c = A^d0_d1 * A^d1_d0 * A^d2_d3 * A^d3_d2
t = A(d1, -d2)*A(d0, -d3)*A(d2, -d1)*A(d3, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)*A(L_2, -L_3)*A(L_3, -L_2)'
# A^d0_d2 * A^d1_d3 * A^d3_d0 * A^d2_d1
# T_c = A^d0_d1 * A^d1_d2 * A^d2_d3 * A^d3_d0
t = A(d0, -d1)*A(d1, -d2)*A(d2, -d3)*A(d3, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_2)*A(L_2, -L_3)*A(L_3, -L_0)'
def test_canonicalize1():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Lorentz)
# A_d0*A^d0; ord = [d0,-d0]
# T_c = A^d0*A_d0
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(-d0)*A(d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0)*A(-L_0)'
# A commuting
# A_d0*A_d1*A_d2*A^d2*A^d1*A^d0
# T_c = A^d0*A_d0*A^d1*A_d1*A^d2*A_d2
t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0)*A(-L_0)*A(L_1)*A(-L_1)*A(L_2)*A(-L_2)'
# A anticommuting
# A_d0*A_d1*A_d2*A^d2*A^d1*A^d0
# T_c 0
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1)
t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0)
tc = t.canon_bp()
assert tc == 0
# A commuting symmetric
# A^{d0 b}*A^a_d1*A^d1_d0
# T_c = A^{a d0}*A^{b d1}*A_{d0 d1}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d0, b)*A(a, -d1)*A(d1, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(a, L_0)*A(b, L_1)*A(-L_0, -L_1)'
# A, B commuting symmetric
# A^{d0 b}*A^d1_d0*B^a_d1
# T_c = A^{b d0}*A_d0^d1*B^a_d1
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d0, b)*A(d1, -d0)*B(a, -d1)
tc = t.canon_bp()
assert str(tc) == 'A(b, L_0)*A(-L_0, L_1)*B(a, -L_1)'
# A commuting symmetric
# A^{d1 d0 b}*A^{a}_{d1 d0}; ord=[a,b, d0,-d0,d1,-d1]
# T_c = A^{a d0 d1}*A^{b}_{d0 d1}
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3))
t = A(d1, d0, b)*A(a, -d1, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(a, L_0, L_1)*A(b, -L_0, -L_1)'
# A^{d3 d0 d2}*A^a0_{d1 d2}*A^d1_d3^a1*A^{a2 a3}_d0
# T_c = A^{a0 d0 d1}*A^a1_d0^d2*A^{a2 a3 d3}*A_{d1 d2 d3}
t = A(d3, d0, d2)*A(a0, -d1, -d2)*A(d1, -d3, a1)*A(a2, a3, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(a0, L_0, L_1)*A(a1, -L_0, L_2)*A(a2, a3, L_3)*A(-L_1, -L_2, -L_3)'
# A commuting symmetric, B antisymmetric
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# in this esxample and in the next three,
# renaming dummy indices and using symmetry of A,
# T = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3
# can = 0
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3))
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert tc == 0
# A anticommuting symmetric, B antisymmetric
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# T_c = A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3}
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3), 1)
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1, L_2)*A(-L_0, -L_1, L_3)*B(-L_2, -L_3)'
# A anticommuting symmetric, B antisymmetric commuting, antisymmetric metric
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# T_c = -A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3}
Spinor = TensorIndexType('Spinor', dummy_name='S', metric_symmetry=-1)
a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Spinor)
A = TensorHead('A', [Spinor]*3, TensorSymmetry.fully_symmetric(3), 1)
B = TensorHead('B', [Spinor]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert str(tc) == '-A(S_0, S_1, S_2)*A(-S_0, -S_1, S_3)*B(-S_2, -S_3)'
# A anticommuting symmetric, B antisymmetric anticommuting,
# no metric symmetry
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# T_c = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3
Mat = TensorIndexType('Mat', metric_symmetry=0, dummy_name='M')
a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Mat)
A = TensorHead('A', [Mat]*3, TensorSymmetry.fully_symmetric(3), 1)
B = TensorHead('B', [Mat]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert str(tc) == 'A(M_0, M_1, M_2)*A(-M_0, -M_1, -M_3)*B(-M_2, M_3)'
# Gamma anticommuting
# Gamma_{mu nu} * gamma^rho * Gamma^{nu mu alpha}
# T_c = -Gamma^{mu nu} * gamma^rho * Gamma_{alpha mu nu}
alpha, beta, gamma, mu, nu, rho = \
tensor_indices('alpha,beta,gamma,mu,nu,rho', Lorentz)
Gamma = TensorHead('Gamma', [Lorentz],
TensorSymmetry.fully_symmetric(1), 2)
Gamma2 = TensorHead('Gamma', [Lorentz]*2,
TensorSymmetry.fully_symmetric(-2), 2)
Gamma3 = TensorHead('Gamma', [Lorentz]*3,
TensorSymmetry.fully_symmetric(-3), 2)
t = Gamma2(-mu, -nu)*Gamma(rho)*Gamma3(nu, mu, alpha)
tc = t.canon_bp()
assert str(tc) == '-Gamma(L_0, L_1)*Gamma(rho)*Gamma(alpha, -L_0, -L_1)'
# Gamma_{mu nu} * Gamma^{gamma beta} * gamma_rho * Gamma^{nu mu alpha}
# T_c = Gamma^{mu nu} * Gamma^{beta gamma} * gamma_rho * Gamma^alpha_{mu nu}
t = Gamma2(mu, nu)*Gamma2(beta, gamma)*Gamma(-rho)*Gamma3(alpha, -mu, -nu)
tc = t.canon_bp()
assert str(tc) == 'Gamma(L_0, L_1)*Gamma(beta, gamma)*Gamma(-rho)*Gamma(alpha, -L_0, -L_1)'
# f^a_{b,c} antisymmetric in b,c; A_mu^a no symmetry
# f^c_{d a} * f_{c e b} * A_mu^d * A_nu^a * A^{nu e} * A^{mu b}
# g = [8,11,5, 9,13,7, 1,10, 3,4, 2,12, 0,6, 14,15]
# T_c = -f^{a b c} * f_a^{d e} * A^mu_b * A_{mu d} * A^nu_c * A_{nu e}
Flavor = TensorIndexType('Flavor', dummy_name='F')
a, b, c, d, e, ff = tensor_indices('a,b,c,d,e,f', Flavor)
mu, nu = tensor_indices('mu,nu', Lorentz)
f = TensorHead('f', [Flavor]*3, TensorSymmetry.direct_product(1, -2))
A = TensorHead('A', [Lorentz, Flavor], TensorSymmetry.no_symmetry(2))
t = f(c, -d, -a)*f(-c, -e, -b)*A(-mu, d)*A(-nu, a)*A(nu, e)*A(mu, b)
tc = t.canon_bp()
assert str(tc) == '-f(F_0, F_1, F_2)*f(-F_0, F_3, F_4)*A(L_0, -F_1)*A(-L_0, -F_3)*A(L_1, -F_2)*A(-L_1, -F_4)'
def test_bug_correction_tensor_indices():
# to make sure that tensor_indices does not return a list if creating
# only one index:
A = TensorIndexType("A")
i = tensor_indices('i', A)
assert not isinstance(i, (tuple, list))
assert isinstance(i, TensorIndex)
def test_riemann_invariants():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11 = \
tensor_indices('d0:12', Lorentz)
# R^{d0 d1}_{d1 d0}; ord = [d0,-d0,d1,-d1]
# T_c = -R^{d0 d1}_{d0 d1}
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(d0, d1, -d1, -d0)
tc = t.canon_bp()
assert str(tc) == '-R(L_0, L_1, -L_0, -L_1)'
# R_d11^d1_d0^d5 * R^{d6 d4 d0}_d5 * R_{d7 d2 d8 d9} *
# R_{d10 d3 d6 d4} * R^{d2 d7 d11}_d1 * R^{d8 d9 d3 d10}
# can = [0,2,4,6, 1,3,8,10, 5,7,12,14, 9,11,16,18, 13,15,20,22,
# 17,19,21<F10,23, 24,25]
# T_c = R^{d0 d1 d2 d3} * R_{d0 d1}^{d4 d5} * R_{d2 d3}^{d6 d7} *
# R_{d4 d5}^{d8 d9} * R_{d6 d7}^{d10 d11} * R_{d8 d9 d10 d11}
t = R(-d11,d1,-d0,d5)*R(d6,d4,d0,-d5)*R(-d7,-d2,-d8,-d9)* \
R(-d10,-d3,-d6,-d4)*R(d2,d7,d11,-d1)*R(d8,d9,d3,d10)
tc = t.canon_bp()
assert str(tc) == 'R(L_0, L_1, L_2, L_3)*R(-L_0, -L_1, L_4, L_5)*R(-L_2, -L_3, L_6, L_7)*R(-L_4, -L_5, L_8, L_9)*R(-L_6, -L_7, L_10, L_11)*R(-L_8, -L_9, -L_10, -L_11)'
def test_riemann_products():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
d0, d1, d2, d3, d4, d5, d6 = tensor_indices('d0:7', Lorentz)
a0, a1, a2, a3, a4, a5 = tensor_indices('a0:6', Lorentz)
a, b = tensor_indices('a,b', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
# R^{a b d0}_d0 = 0
t = R(a, b, d0, -d0)
tc = t.canon_bp()
assert tc == 0
# R^{d0 b a}_d0
# T_c = -R^{a d0 b}_d0
t = R(d0, b, a, -d0)
tc = t.canon_bp()
assert str(tc) == '-R(a, L_0, b, -L_0)'
# R^d1_d2^b_d0 * R^{d0 a}_d1^d2; ord=[a,b,d0,-d0,d1,-d1,d2,-d2]
# T_c = -R^{a d0 d1 d2}* R^b_{d0 d1 d2}
t = R(d1, -d2, b, -d0)*R(d0, a, -d1, d2)
tc = t.canon_bp()
assert str(tc) == '-R(a, L_0, L_1, L_2)*R(b, -L_0, -L_1, -L_2)'
# A symmetric commuting
# R^{d6 d5}_d2^d1 * R^{d4 d0 d2 d3} * A_{d6 d0} A_{d3 d1} * A_{d4 d5}
# g = [12,10,5,2, 8,0,4,6, 13,1, 7,3, 9,11,14,15]
# T_c = -R^{d0 d1 d2 d3} * R_d0^{d4 d5 d6} * A_{d1 d4}*A_{d2 d5}*A_{d3 d6}
V = TensorHead('V', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = R(d6, d5, -d2, d1)*R(d4, d0, d2, d3)*V(-d6, -d0)*V(-d3, -d1)*V(-d4, -d5)
tc = t.canon_bp()
assert str(tc) == '-R(L_0, L_1, L_2, L_3)*R(-L_0, L_4, L_5, L_6)*V(-L_1, -L_4)*V(-L_2, -L_5)*V(-L_3, -L_6)'
# R^{d2 a0 a2 d0} * R^d1_d2^{a1 a3} * R^{a4 a5}_{d0 d1}
# T_c = R^{a0 d0 a2 d1}*R^{a1 a3}_d0^d2*R^{a4 a5}_{d1 d2}
t = R(d2, a0, a2, d0)*R(d1, -d2, a1, a3)*R(a4, a5, -d0, -d1)
tc = t.canon_bp()
assert str(tc) == 'R(a0, L_0, a2, L_1)*R(a1, a3, -L_0, L_2)*R(a4, a5, -L_1, -L_2)'
######################################################################
def test_canonicalize2():
D = Symbol('D')
Eucl = TensorIndexType('Eucl', metric_symmetry=1, dim=D, dummy_name='E')
i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14 = \
tensor_indices('i0:15', Eucl)
A = TensorHead('A', [Eucl]*3, TensorSymmetry.fully_symmetric(-3))
# two examples from Cvitanovic, Group Theory page 59
# of identities for antisymmetric tensors of rank 3
# contracted according to the Kuratowski graph eq.(6.59)
t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i3,i7,i5)*A(-i2,-i5,i6)*A(-i4,-i6,i8)
t1 = t.canon_bp()
assert t1 == 0
# eq.(6.60)
#t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i2,i5,i6)*A(-i3,i7,i8)*A(-i6,-i7,i9)*
# A(-i8,i10,i13)*A(-i5,-i10,i11)*A(-i4,-i11,i12)*A(-i3,-i12,i14)
t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i2,i5,i6)*A(-i3,i7,i8)*A(-i6,-i7,i9)*\
A(-i8,i10,i13)*A(-i5,-i10,i11)*A(-i4,-i11,i12)*A(-i9,-i12,i14)
t1 = t.canon_bp()
assert t1 == 0
def test_canonicalize3():
D = Symbol('D')
Spinor = TensorIndexType('Spinor', dim=D, metric_symmetry=-1, dummy_name='S')
a0,a1,a2,a3,a4 = tensor_indices('a0:5', Spinor)
chi, psi = tensor_heads('chi,psi', [Spinor], TensorSymmetry.no_symmetry(1), 1)
t = chi(a1)*psi(a0)
t1 = t.canon_bp()
assert t1 == t
t = psi(a1)*chi(a0)
t1 = t.canon_bp()
assert t1 == -chi(a0)*psi(a1)
def test_TensorIndexType():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', metric_name='g', metric_symmetry=1,
dim=D, dummy_name='L')
m0, m1, m2, m3, m4 = tensor_indices('m0:5', Lorentz)
sym2 = TensorSymmetry.fully_symmetric(2)
sym2n = TensorSymmetry(*get_symmetric_group_sgs(2))
assert sym2 == sym2n
g = Lorentz.metric
assert str(g) == 'g(Lorentz,Lorentz)'
assert Lorentz.eps_dim == Lorentz.dim
TSpace = TensorIndexType('TSpace', dummy_name = 'TSpace')
i0, i1 = tensor_indices('i0 i1', TSpace)
g = TSpace.metric
A = TensorHead('A', [TSpace]*2, sym2)
assert str(A(i0,-i0).canon_bp()) == 'A(TSpace_0, -TSpace_0)'
def test_indices():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
assert a.tensor_index_type == Lorentz
assert a != -a
A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(a,b)*B(-b,c)
indices = t.get_indices()
L_0 = TensorIndex('L_0', Lorentz)
assert indices == [a, L_0, -L_0, c]
raises(ValueError, lambda: tensor_indices(3, Lorentz))
raises(ValueError, lambda: A(a,b,c))
A = TensorHead('A', [Lorentz, Lorentz])
assert A('a', 'b') == A(TensorIndex('a', Lorentz),
TensorIndex('b', Lorentz))
assert A('a', '-b') == A(TensorIndex('a', Lorentz),
TensorIndex('b', Lorentz, is_up=False))
assert A('a', TensorIndex('b', Lorentz)) == A(TensorIndex('a', Lorentz),
TensorIndex('b', Lorentz))
def test_TensorSymmetry():
assert TensorSymmetry.fully_symmetric(2) == \
TensorSymmetry(get_symmetric_group_sgs(2))
assert TensorSymmetry.fully_symmetric(-3) == \
TensorSymmetry(get_symmetric_group_sgs(3, True))
assert TensorSymmetry.direct_product(-4) == \
TensorSymmetry.fully_symmetric(-4)
assert TensorSymmetry.fully_symmetric(-1) == \
TensorSymmetry.fully_symmetric(1)
assert TensorSymmetry.direct_product(1, -1, 1) == \
TensorSymmetry.no_symmetry(3)
assert TensorSymmetry(get_symmetric_group_sgs(2)) == \
TensorSymmetry(*get_symmetric_group_sgs(2))
# TODO: add check for *get_symmetric_group_sgs(0)
sym = TensorSymmetry.fully_symmetric(-3)
assert sym.rank == 3
assert sym.base == Tuple(0, 1)
assert sym.generators == Tuple(Permutation(0, 1)(3, 4), Permutation(1, 2)(3, 4))
def test_TensExpr():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
g = Lorentz.metric
A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
raises(ValueError, lambda: g(c, d)/g(a, b))
raises(ValueError, lambda: S.One/g(a, b))
raises(ValueError, lambda: (A(c, d) + g(c, d))/g(a, b))
raises(ValueError, lambda: S.One/(A(c, d) + g(c, d)))
raises(ValueError, lambda: A(a, b) + A(a, c))
#t = A(a, b) + B(a, b) # assigned to t for below
#raises(NotImplementedError, lambda: TensExpr.__mul__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__add__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__radd__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__sub__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__rsub__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__truediv__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__rtruediv__(t, 'a'))
with warns_deprecated_sympy():
# DO NOT REMOVE THIS AFTER DEPRECATION REMOVED:
raises(ValueError, lambda: A(a, b)**2)
raises(NotImplementedError, lambda: 2**A(a, b))
raises(NotImplementedError, lambda: abs(A(a, b)))
def test_TensorHead():
# simple example of algebraic expression
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
A = TensorHead('A', [Lorentz]*2)
assert A.name == 'A'
assert A.index_types == [Lorentz, Lorentz]
assert A.rank == 2
assert A.symmetry == TensorSymmetry.no_symmetry(2)
assert A.comm == 0
def test_add1():
assert TensAdd().args == ()
assert TensAdd().doit() == 0
# simple example of algebraic expression
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a,b,d0,d1,i,j,k = tensor_indices('a,b,d0,d1,i,j,k', Lorentz)
# A, B symmetric
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t1 = A(b, -d0)*B(d0, a)
assert TensAdd(t1).equals(t1)
t2a = B(d0, a) + A(d0, a)
t2 = A(b, -d0)*t2a
assert str(t2) == 'A(b, -L_0)*(A(L_0, a) + B(L_0, a))'
t2 = t2.expand()
assert str(t2) == 'A(b, -L_0)*A(L_0, a) + A(b, -L_0)*B(L_0, a)'
t2 = t2.canon_bp()
assert str(t2) == 'A(a, L_0)*A(b, -L_0) + A(b, L_0)*B(a, -L_0)'
t2b = t2 + t1
assert str(t2b) == 'A(a, L_0)*A(b, -L_0) + A(b, -L_0)*B(L_0, a) + A(b, L_0)*B(a, -L_0)'
t2b = t2b.canon_bp()
assert str(t2b) == 'A(a, L_0)*A(b, -L_0) + 2*A(b, L_0)*B(a, -L_0)'
p, q, r = tensor_heads('p,q,r', [Lorentz])
t = q(d0)*2
assert str(t) == '2*q(d0)'
t = 2*q(d0)
assert str(t) == '2*q(d0)'
t1 = p(d0) + 2*q(d0)
assert str(t1) == '2*q(d0) + p(d0)'
t2 = p(-d0) + 2*q(-d0)
assert str(t2) == '2*q(-d0) + p(-d0)'
t1 = p(d0)
t3 = t1*t2
assert str(t3) == 'p(L_0)*(2*q(-L_0) + p(-L_0))'
t3 = t3.expand()
assert str(t3) == 'p(L_0)*p(-L_0) + 2*p(L_0)*q(-L_0)'
t3 = t2*t1
t3 = t3.expand()
assert str(t3) == 'p(-L_0)*p(L_0) + 2*q(-L_0)*p(L_0)'
t3 = t3.canon_bp()
assert str(t3) == 'p(L_0)*p(-L_0) + 2*p(L_0)*q(-L_0)'
t1 = p(d0) + 2*q(d0)
t3 = t1*t2
t3 = t3.canon_bp()
assert str(t3) == 'p(L_0)*p(-L_0) + 4*p(L_0)*q(-L_0) + 4*q(L_0)*q(-L_0)'
t1 = p(d0) - 2*q(d0)
assert str(t1) == '-2*q(d0) + p(d0)'
t2 = p(-d0) + 2*q(-d0)
t3 = t1*t2
t3 = t3.canon_bp()
assert t3 == p(d0)*p(-d0) - 4*q(d0)*q(-d0)
t = p(i)*p(j)*(p(k) + q(k)) + p(i)*(p(j) + q(j))*(p(k) - 3*q(k))
t = t.canon_bp()
assert t == 2*p(i)*p(j)*p(k) - 2*p(i)*p(j)*q(k) + p(i)*p(k)*q(j) - 3*p(i)*q(j)*q(k)
t1 = (p(i) + q(i) + 2*r(i))*(p(j) - q(j))
t2 = (p(j) + q(j) + 2*r(j))*(p(i) - q(i))
t = t1 + t2
t = t.canon_bp()
assert t == 2*p(i)*p(j) + 2*p(i)*r(j) + 2*p(j)*r(i) - 2*q(i)*q(j) - 2*q(i)*r(j) - 2*q(j)*r(i)
t = p(i)*q(j)/2
assert 2*t == p(i)*q(j)
t = (p(i) + q(i))/2
assert 2*t == p(i) + q(i)
t = S.One - p(i)*p(-i)
t = t.canon_bp()
tz1 = t + p(-j)*p(j)
assert tz1 != 1
tz1 = tz1.canon_bp()
assert tz1.equals(1)
t = S.One + p(i)*p(-i)
assert (t - p(-j)*p(j)).canon_bp().equals(1)
t = A(a, b) + B(a, b)
assert t.rank == 2
t1 = t - A(a, b) - B(a, b)
assert t1 == 0
t = 1 - (A(a, -a) + B(a, -a))
t1 = 1 + (A(a, -a) + B(a, -a))
assert (t + t1).expand().equals(2)
t2 = 1 + A(a, -a)
assert t1 != t2
assert t2 != TensMul.from_data(0, [], [], [])
#Test whether TensAdd.doit chokes on subterms that are zero.
assert TensAdd(p(a), TensMul(0, p(a)) ).doit() == p(a)
def test_special_eq_ne():
# test special equality cases:
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, d0, d1, i, j, k = tensor_indices('a,b,d0,d1,i,j,k', Lorentz)
# A, B symmetric
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
p, q, r = tensor_heads('p,q,r', [Lorentz])
t = 0*A(a, b)
assert _is_equal(t, 0)
assert _is_equal(t, S.Zero)
assert p(i) != A(a, b)
assert A(a, -a) != A(a, b)
assert 0*(A(a, b) + B(a, b)) == 0
assert 0*(A(a, b) + B(a, b)) is S.Zero
assert 3*(A(a, b) - A(a, b)) is S.Zero
assert p(i) + q(i) != A(a, b)
assert p(i) + q(i) != A(a, b) + B(a, b)
assert p(i) - p(i) == 0
assert p(i) - p(i) is S.Zero
assert _is_equal(A(a, b), A(b, a))
def test_add2():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
m, n, p, q = tensor_indices('m,n,p,q', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(-3))
t1 = 2*R(m, n, p, q) - R(m, q, n, p) + R(m, p, n, q)
t2 = t1*A(-n, -p, -q)
t2 = t2.canon_bp()
assert t2 == 0
t1 = Rational(2, 3)*R(m,n,p,q) - Rational(1, 3)*R(m,q,n,p) + Rational(1, 3)*R(m,p,n,q)
t2 = t1*A(-n, -p, -q)
t2 = t2.canon_bp()
assert t2 == 0
t = A(m, -m, n) + A(n, p, -p)
t = t.canon_bp()
assert t == 0
def test_add3():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
i0, i1 = tensor_indices('i0:2', Lorentz)
E, px, py, pz = symbols('E px py pz')
A = TensorHead('A', [Lorentz])
B = TensorHead('B', [Lorentz])
expr1 = A(i0)*A(-i0) - (E**2 - px**2 - py**2 - pz**2)
assert expr1.args == (-E**2, px**2, py**2, pz**2, A(i0)*A(-i0))
expr2 = E**2 - px**2 - py**2 - pz**2 - A(i0)*A(-i0)
assert expr2.args == (E**2, -px**2, -py**2, -pz**2, -A(i0)*A(-i0))
expr3 = A(i0)*A(-i0) - E**2 + px**2 + py**2 + pz**2
assert expr3.args == (-E**2, px**2, py**2, pz**2, A(i0)*A(-i0))
expr4 = B(i1)*B(-i1) + 2*E**2 - 2*px**2 - 2*py**2 - 2*pz**2 - A(i0)*A(-i0)
assert expr4.args == (2*E**2, -2*px**2, -2*py**2, -2*pz**2, B(i1)*B(-i1), -A(i0)*A(-i0))
def test_mul():
from sympy.abc import x
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
t = TensMul.from_data(S.One, [], [], [])
assert str(t) == '1'
A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = (1 + x)*A(a, b)
assert str(t) == '(x + 1)*A(a, b)'
assert t.index_types == [Lorentz, Lorentz]
assert t.rank == 2
assert t.dum == []
assert t.coeff == 1 + x
assert sorted(t.free) == [(a, 0), (b, 1)]
assert t.components == [A]
ts = A(a, b)
assert str(ts) == 'A(a, b)'
assert ts.index_types == [Lorentz, Lorentz]
assert ts.rank == 2
assert ts.dum == []
assert ts.coeff == 1
assert sorted(ts.free) == [(a, 0), (b, 1)]
assert ts.components == [A]
t = A(-b, a)*B(-a, c)*A(-c, d)
t1 = tensor_mul(*t.split())
assert t == t1
assert tensor_mul(*[]) == TensMul.from_data(S.One, [], [], [])
t = TensMul.from_data(1, [], [], [])
C = TensorHead('C', [])
assert str(C()) == 'C'
assert str(t) == '1'
assert t == 1
raises(ValueError, lambda: A(a, b)*A(a, c))
def test_substitute_indices():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
i, j, k, l, m, n, p, q = tensor_indices('i,j,k,l,m,n,p,q', Lorentz)
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
p = TensorHead('p', [Lorentz])
t = p(i)
t1 = t.substitute_indices((j, k))
assert t1 == t
t1 = t.substitute_indices((i, j))
assert t1 == p(j)
t1 = t.substitute_indices((i, -j))
assert t1 == p(-j)
t1 = t.substitute_indices((-i, j))
assert t1 == p(-j)
t1 = t.substitute_indices((-i, -j))
assert t1 == p(j)
t = A(m, n)
t1 = t.substitute_indices((m, i), (n, -i))
assert t1 == A(n, -n)
t1 = substitute_indices(t, (m, i), (n, -i))
assert t1 == A(n, -n)
t = A(i, k)*B(-k, -j)
t1 = t.substitute_indices((i, j), (j, k))
t1a = A(j, l)*B(-l, -k)
assert t1 == t1a
t1 = substitute_indices(t, (i, j), (j, k))
assert t1 == t1a
t = A(i, j) + B(i, j)
t1 = t.substitute_indices((j, -i))
t1a = A(i, -i) + B(i, -i)
assert t1 == t1a
t1 = substitute_indices(t, (j, -i))
assert t1 == t1a
def test_riemann_cyclic_replace():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
m0, m1, m2, m3 = tensor_indices('m:4', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(m0, m2, m1, m3)
t1 = riemann_cyclic_replace(t)
t1a = Rational(-1, 3)*R(m0, m3, m2, m1) + Rational(1, 3)*R(m0, m1, m2, m3) + Rational(2, 3)*R(m0, m2, m1, m3)
assert t1 == t1a
def test_riemann_cyclic():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
i, j, k, l, m, n, p, q = tensor_indices('i,j,k,l,m,n,p,q', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(i,j,k,l) + R(i,l,j,k) + R(i,k,l,j) - \
R(i,j,l,k) - R(i,l,k,j) - R(i,k,j,l)
t2 = t*R(-i,-j,-k,-l)
t3 = riemann_cyclic(t2)
assert t3 == 0
t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l))
t1 = riemann_cyclic(t)
assert t1 == 0
t = R(i,j,k,l)
t1 = riemann_cyclic(t)
assert t1 == Rational(-1, 3)*R(i, l, j, k) + Rational(1, 3)*R(i, k, j, l) + Rational(2, 3)*R(i, j, k, l)
t = R(i,j,k,l)*R(-k,-l,m,n)*(R(-m,-n,-i,-j) + 2*R(-m,-j,-n,-i))
t1 = riemann_cyclic(t)
assert t1 == 0
@XFAIL
def test_div():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
m0, m1, m2, m3 = tensor_indices('m0:4', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(m0,m1,-m1,m3)
t1 = t/S(4)
assert str(t1) == '(1/4)*R(m0, L_0, -L_0, m3)'
t = t.canon_bp()
assert not t1._is_canon_bp
t1 = t*4
assert t1._is_canon_bp
t1 = t1/4
assert t1._is_canon_bp
def test_contract_metric1():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
g = Lorentz.metric
p = TensorHead('p', [Lorentz])
t = g(a, b)*p(-b)
t1 = t.contract_metric(g)
assert t1 == p(a)
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
# case with g with all free indices
t1 = A(a,b)*B(-b,c)*g(d, e)
t2 = t1.contract_metric(g)
assert t1 == t2
# case of g(d, -d)
t1 = A(a,b)*B(-b,c)*g(-d, d)
t2 = t1.contract_metric(g)
assert t2 == D*A(a, d)*B(-d, c)
# g with one free index
t1 = A(a,b)*B(-b,-c)*g(c, d)
t2 = t1.contract_metric(g)
assert t2 == A(a, c)*B(-c, d)
# g with both indices contracted with another tensor
t1 = A(a,b)*B(-b,-c)*g(c, -a)
t2 = t1.contract_metric(g)
assert _is_equal(t2, A(a, b)*B(-b, -a))
t1 = A(a,b)*B(-b,-c)*g(c, d)*g(-a, -d)
t2 = t1.contract_metric(g)
assert _is_equal(t2, A(a,b)*B(-b,-a))
t1 = A(a,b)*g(-a,-b)
t2 = t1.contract_metric(g)
assert _is_equal(t2, A(a, -a))
assert not t2.free
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
g = Lorentz.metric
assert _is_equal(g(a, -a).contract_metric(g), Lorentz.dim) # no dim
def test_contract_metric2():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e, L_0 = tensor_indices('a,b,c,d,e,L_0', Lorentz)
g = Lorentz.metric
p, q = tensor_heads('p,q', [Lorentz])
t1 = g(a,b)*p(c)*p(-c)
t2 = 3*g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
assert t == 3*D*p(a)*p(-a)*q(b)*q(-b)
t1 = g(a,b)*p(c)*p(-c)
t2 = 3*q(-a)*q(-b)
t = t1*t2
t = t.contract_metric(g)
t = t.canon_bp()
assert t == 3*p(a)*p(-a)*q(b)*q(-b)
t1 = 2*g(a,b)*p(c)*p(-c)
t2 = - 3*g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
t = 6*g(a,b)*g(-a,-b)*p(c)*p(-c)*q(d)*q(-d)
t = t.contract_metric(g)
t1 = 2*g(a,b)*p(c)*p(-c)
t2 = q(-a)*q(-b) + 3*g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
assert t == (2 + 6*D)*p(a)*p(-a)*q(b)*q(-b)
t1 = p(a)*p(b) + p(a)*q(b) + 2*g(a,b)*p(c)*p(-c)
t2 = q(-a)*q(-b) - g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
t1 = (1 - 2*D)*p(a)*p(-a)*q(b)*q(-b) + p(a)*q(-a)*p(b)*q(-b)
assert canon_bp(t - t1) == 0
t = g(a,b)*g(c,d)*g(-b,-c)
t1 = t.contract_metric(g)
assert t1 == g(a, d)
t1 = g(a,b)*g(c,d) + g(a,c)*g(b,d) + g(a,d)*g(b,c)
t2 = t1.substitute_indices((a,-a),(b,-b),(c,-c),(d,-d))
t = t1*t2
t = t.contract_metric(g)
assert t.equals(3*D**2 + 6*D)
t = 2*p(a)*g(b,-b)
t1 = t.contract_metric(g)
assert t1.equals(2*D*p(a))
t = 2*p(a)*g(b,-a)
t1 = t.contract_metric(g)
assert t1 == 2*p(b)
M = Symbol('M')
t = (p(a)*p(b) + g(a, b)*M**2)*g(-a, -b) - D*M**2
t1 = t.contract_metric(g)
assert t1 == p(a)*p(-a)
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(a, b)*p(L_0)*g(-a, -b)
t1 = t.contract_metric(g)
assert str(t1) == 'A(L_1, -L_1)*p(L_0)' or str(t1) == 'A(-L_1, L_1)*p(L_0)'
def test_metric_contract3():
D = Symbol('D')
Spinor = TensorIndexType('Spinor', dim=D, metric_symmetry=-1, dummy_name='S')
a0, a1, a2, a3, a4 = tensor_indices('a0:5', Spinor)
C = Spinor.metric
chi, psi = tensor_heads('chi,psi', [Spinor], TensorSymmetry.no_symmetry(1), 1)
B = TensorHead('B', [Spinor]*2, TensorSymmetry.no_symmetry(2))
t = C(a0,-a0)
t1 = t.contract_metric(C)
assert t1.equals(-D)
t = C(-a0,a0)
t1 = t.contract_metric(C)
assert t1.equals(D)
t = C(a0,a1)*C(-a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(D)
t = C(a1,a0)*C(-a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(-D)
t = C(-a0,a1)*C(a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(-D)
t = C(a1,-a0)*C(a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(D)
t = C(a0,a1)*B(-a1,-a0)
t1 = t.contract_metric(C)
t1 = t1.canon_bp()
assert _is_equal(t1, B(a0,-a0))
t = C(a1,a0)*B(-a1,-a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(a0,-a0))
t = C(a0,-a1)*B(a1,-a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(a0,-a0))
t = C(-a0,a1)*B(-a1,a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(a0,-a0))
t = C(-a0,-a1)*B(a1,a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, B(a0,-a0))
t = C(-a1, a0)*B(a1,-a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, B(a0,-a0))
t = C(a0,a1)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, psi(a0))
t = C(a1,a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -psi(a0))
t = C(a0,a1)*chi(-a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -chi(a1)*psi(-a1))
t = C(a1,a0)*chi(-a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, chi(a1)*psi(-a1))
t = C(-a1,a0)*chi(-a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, chi(-a1)*psi(a1))
t = C(a0,-a1)*chi(-a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -chi(-a1)*psi(a1))
t = C(-a0,-a1)*chi(a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, chi(-a1)*psi(a1))
t = C(-a1,-a0)*chi(a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -chi(-a1)*psi(a1))
t = C(-a1,-a0)*B(a0,a2)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(-a1,a2)*psi(a1))
t = C(a1,a0)*B(-a2,-a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, B(-a2,a1)*psi(-a1))
def test_contract_metric4():
R3 = TensorIndexType('R3', dim=3)
p, q, r = tensor_indices("p q r", R3)
delta = R3.delta
eps = R3.epsilon
K = TensorHead("K", [R3])
#Check whether contract_metric chokes on an expandable expression which becomes zero on canonicalization (issue #24354)
expr = eps(p,q,r)*( K(-p)*K(-q) + delta(-p,-q) )
assert expr.contract_metric(delta) == 0
def test_epsilon():
Lorentz = TensorIndexType('Lorentz', dim=4, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
epsilon = Lorentz.epsilon
p, q, r, s = tensor_heads('p,q,r,s', [Lorentz])
t = epsilon(b,a,c,d)
t1 = t.canon_bp()
assert t1 == -epsilon(a,b,c,d)
t = epsilon(c,b,d,a)
t1 = t.canon_bp()
assert t1 == epsilon(a,b,c,d)
t = epsilon(c,a,d,b)
t1 = t.canon_bp()
assert t1 == -epsilon(a,b,c,d)
t = epsilon(a,b,c,d)*p(-a)*q(-b)
t1 = t.canon_bp()
assert t1 == epsilon(c,d,a,b)*p(-a)*q(-b)
t = epsilon(c,b,d,a)*p(-a)*q(-b)
t1 = t.canon_bp()
assert t1 == epsilon(c,d,a,b)*p(-a)*q(-b)
t = epsilon(c,a,d,b)*p(-a)*q(-b)
t1 = t.canon_bp()
assert t1 == -epsilon(c,d,a,b)*p(-a)*q(-b)
t = epsilon(c,a,d,b)*p(-a)*p(-b)
t1 = t.canon_bp()
assert t1 == 0
t = epsilon(c,a,d,b)*p(-a)*q(-b) + epsilon(a,b,c,d)*p(-b)*q(-a)
t1 = t.canon_bp()
assert t1 == -2*epsilon(c,d,a,b)*p(-a)*q(-b)
# Test that epsilon can be create with a SymPy integer:
Lorentz = TensorIndexType('Lorentz', dim=Integer(4), dummy_name='L')
epsilon = Lorentz.epsilon
assert isinstance(epsilon, TensorHead)
def test_contract_delta1():
# see Group Theory by Cvitanovic page 9
n = Symbol('n')
Color = TensorIndexType('Color', dim=n, dummy_name='C')
a, b, c, d, e, f = tensor_indices('a,b,c,d,e,f', Color)
delta = Color.delta
def idn(a, b, d, c):
assert a.is_up and d.is_up
assert not (b.is_up or c.is_up)
return delta(a,c)*delta(d,b)
def T(a, b, d, c):
assert a.is_up and d.is_up
assert not (b.is_up or c.is_up)
return delta(a,b)*delta(d,c)
def P1(a, b, c, d):
return idn(a,b,c,d) - 1/n*T(a,b,c,d)
def P2(a, b, c, d):
return 1/n*T(a,b,c,d)
t = P1(a, -b, e, -f)*P1(f, -e, d, -c)
t1 = t.contract_delta(delta)
assert canon_bp(t1 - P1(a, -b, d, -c)) == 0
t = P2(a, -b, e, -f)*P2(f, -e, d, -c)
t1 = t.contract_delta(delta)
assert t1 == P2(a, -b, d, -c)
t = P1(a, -b, e, -f)*P2(f, -e, d, -c)
t1 = t.contract_delta(delta)
assert t1 == 0
t = P1(a, -b, b, -a)
t1 = t.contract_delta(delta)
assert t1.equals(n**2 - 1)
def test_fun():
with warns_deprecated_sympy():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
g = Lorentz.metric
p, q = tensor_heads('p q', [Lorentz])
t = q(c)*p(a)*q(b) + g(a,b)*g(c,d)*q(-d)
assert t(a,b,c) == t
assert canon_bp(t - t(b,a,c) - q(c)*p(a)*q(b) + q(c)*p(b)*q(a)) == 0
assert t(b,c,d) == q(d)*p(b)*q(c) + g(b,c)*g(d,e)*q(-e)
t1 = t.substitute_indices((a,b),(b,a))
assert canon_bp(t1 - q(c)*p(b)*q(a) - g(a,b)*g(c,d)*q(-d)) == 0
# check that g_{a b; c} = 0
# example taken from L. Brewin
# "A brief introduction to Cadabra" arxiv:0903.2085
# dg_{a b c} = \partial_{a} g_{b c} is symmetric in b, c
dg = TensorHead('dg', [Lorentz]*3, TensorSymmetry.direct_product(1, 2))
# gamma^a_{b c} is the Christoffel symbol
gamma = S.Half*g(a,d)*(dg(-b,-d,-c) + dg(-c,-b,-d) - dg(-d,-b,-c))
# t = g_{a b; c}
t = dg(-c,-a,-b) - g(-a,-d)*gamma(d,-b,-c) - g(-b,-d)*gamma(d,-a,-c)
t = t.contract_metric(g)
assert t == 0
t = q(c)*p(a)*q(b)
assert t(b,c,d) == q(d)*p(b)*q(c)
def test_TensorManager():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
LorentzH = TensorIndexType('LorentzH', dummy_name='LH')
i, j = tensor_indices('i,j', Lorentz)
ih, jh = tensor_indices('ih,jh', LorentzH)
p, q = tensor_heads('p q', [Lorentz])
ph, qh = tensor_heads('ph qh', [LorentzH])
Gsymbol = Symbol('Gsymbol')
GHsymbol = Symbol('GHsymbol')
TensorManager.set_comm(Gsymbol, GHsymbol, 0)
G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), Gsymbol)
assert TensorManager._comm_i2symbol[G.comm] == Gsymbol
GH = TensorHead('GH', [LorentzH], TensorSymmetry.no_symmetry(1), GHsymbol)
ps = G(i)*p(-i)
psh = GH(ih)*ph(-ih)
t = ps + psh
t1 = t*t
assert canon_bp(t1 - ps*ps - 2*ps*psh - psh*psh) == 0
qs = G(i)*q(-i)
qsh = GH(ih)*qh(-ih)
assert _is_equal(ps*qsh, qsh*ps)
assert not _is_equal(ps*qs, qs*ps)
n = TensorManager.comm_symbols2i(Gsymbol)
assert TensorManager.comm_i2symbol(n) == Gsymbol
assert GHsymbol in TensorManager._comm_symbols2i
raises(ValueError, lambda: TensorManager.set_comm(GHsymbol, 1, 2))
TensorManager.set_comms((Gsymbol,GHsymbol,0),(Gsymbol,1,1))
assert TensorManager.get_comm(n, 1) == TensorManager.get_comm(1, n) == 1
TensorManager.clear()
assert TensorManager.comm == [{0:0, 1:0, 2:0}, {0:0, 1:1, 2:None}, {0:0, 1:None}]
assert GHsymbol not in TensorManager._comm_symbols2i
nh = TensorManager.comm_symbols2i(GHsymbol)
assert TensorManager.comm_i2symbol(nh) == GHsymbol
assert GHsymbol in TensorManager._comm_symbols2i
def test_hash():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
g = Lorentz.metric
p, q = tensor_heads('p q', [Lorentz])
p_type = p.args[1]
t1 = p(a)*q(b)
t2 = p(a)*p(b)
assert hash(t1) != hash(t2)
t3 = p(a)*p(b) + g(a,b)
t4 = p(a)*p(b) - g(a,b)
assert hash(t3) != hash(t4)
assert a.func(*a.args) == a
assert Lorentz.func(*Lorentz.args) == Lorentz
assert g.func(*g.args) == g
assert p.func(*p.args) == p
assert p_type.func(*p_type.args) == p_type
assert p(a).func(*(p(a)).args) == p(a)
assert t1.func(*t1.args) == t1
assert t2.func(*t2.args) == t2
assert t3.func(*t3.args) == t3
assert t4.func(*t4.args) == t4
assert hash(a.func(*a.args)) == hash(a)
assert hash(Lorentz.func(*Lorentz.args)) == hash(Lorentz)
assert hash(g.func(*g.args)) == hash(g)
assert hash(p.func(*p.args)) == hash(p)
assert hash(p_type.func(*p_type.args)) == hash(p_type)
assert hash(p(a).func(*(p(a)).args)) == hash(p(a))
assert hash(t1.func(*t1.args)) == hash(t1)
assert hash(t2.func(*t2.args)) == hash(t2)
assert hash(t3.func(*t3.args)) == hash(t3)
assert hash(t4.func(*t4.args)) == hash(t4)
def check_all(obj):
return all([isinstance(_, Basic) for _ in obj.args])
assert check_all(a)
assert check_all(Lorentz)
assert check_all(g)
assert check_all(p)
assert check_all(p_type)
assert check_all(p(a))
assert check_all(t1)
assert check_all(t2)
assert check_all(t3)
assert check_all(t4)
tsymmetry = TensorSymmetry.direct_product(-2, 1, 3)
assert tsymmetry.func(*tsymmetry.args) == tsymmetry
assert hash(tsymmetry.func(*tsymmetry.args)) == hash(tsymmetry)
assert check_all(tsymmetry)
### TEST VALUED TENSORS ###
def _get_valued_base_test_variables():
minkowski = Matrix((
(1, 0, 0, 0),
(0, -1, 0, 0),
(0, 0, -1, 0),
(0, 0, 0, -1),
))
Lorentz = TensorIndexType('Lorentz', dim=4)
Lorentz.data = minkowski
i0, i1, i2, i3, i4 = tensor_indices('i0:5', Lorentz)
E, px, py, pz = symbols('E px py pz')
A = TensorHead('A', [Lorentz])
A.data = [E, px, py, pz]
B = TensorHead('B', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm')
B.data = range(4)
AB = TensorHead("AB", [Lorentz]*2)
AB.data = minkowski
ba_matrix = Matrix((
(1, 2, 3, 4),
(5, 6, 7, 8),
(9, 0, -1, -2),
(-3, -4, -5, -6),
))
BA = TensorHead("BA", [Lorentz]*2)
BA.data = ba_matrix
# Let's test the diagonal metric, with inverted Minkowski metric:
LorentzD = TensorIndexType('LorentzD')
LorentzD.data = [-1, 1, 1, 1]
mu0, mu1, mu2 = tensor_indices('mu0:3', LorentzD)
C = TensorHead('C', [LorentzD])
C.data = [E, px, py, pz]
### non-diagonal metric ###
ndm_matrix = (
(1, 1, 0,),
(1, 0, 1),
(0, 1, 0,),
)
ndm = TensorIndexType("ndm")
ndm.data = ndm_matrix
n0, n1, n2 = tensor_indices('n0:3', ndm)
NA = TensorHead('NA', [ndm])
NA.data = range(10, 13)
NB = TensorHead('NB', [ndm]*2)
NB.data = [[i+j for j in range(10, 13)] for i in range(10, 13)]
NC = TensorHead('NC', [ndm]*3)
NC.data = [[[i+j+k for k in range(4, 7)] for j in range(1, 4)] for i in range(2, 5)]
return (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4)
def test_valued_tensor_iter():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
list_BA = [Array([1, 2, 3, 4]), Array([5, 6, 7, 8]), Array([9, 0, -1, -2]), Array([-3, -4, -5, -6])]
# iteration on VTensorHead
assert list(A) == [E, px, py, pz]
assert list(ba_matrix) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, -1, -2, -3, -4, -5, -6]
assert list(BA) == list_BA
# iteration on VTensMul
assert list(A(i1)) == [E, px, py, pz]
assert list(BA(i1, i2)) == list_BA
assert list(3 * BA(i1, i2)) == [3 * i for i in list_BA]
assert list(-5 * BA(i1, i2)) == [-5 * i for i in list_BA]
# iteration on VTensAdd
# A(i1) + A(i1)
assert list(A(i1) + A(i1)) == [2*E, 2*px, 2*py, 2*pz]
assert BA(i1, i2) - BA(i1, i2) == 0
assert list(BA(i1, i2) - 2 * BA(i1, i2)) == [-i for i in list_BA]
def test_valued_tensor_covariant_contravariant_elements():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert A(-i0)[0] == A(i0)[0]
assert A(-i0)[1] == -A(i0)[1]
assert AB(i0, i1)[1, 1] == -1
assert AB(i0, -i1)[1, 1] == 1
assert AB(-i0, -i1)[1, 1] == -1
assert AB(-i0, i1)[1, 1] == 1
def test_valued_tensor_get_matrix():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
matab = AB(i0, i1).get_matrix()
assert matab == Matrix([
[1, 0, 0, 0],
[0, -1, 0, 0],
[0, 0, -1, 0],
[0, 0, 0, -1],
])
# when alternating contravariant/covariant with [1, -1, -1, -1] metric
# it becomes the identity matrix:
assert AB(i0, -i1).get_matrix() == eye(4)
# covariant and contravariant forms:
assert A(i0).get_matrix() == Matrix([E, px, py, pz])
assert A(-i0).get_matrix() == Matrix([E, -px, -py, -pz])
def test_valued_tensor_contraction():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert (A(i0) * A(-i0)).data == E ** 2 - px ** 2 - py ** 2 - pz ** 2
assert (A(i0) * A(-i0)).data == A ** 2
assert (A(i0) * A(-i0)).data == A(i0) ** 2
assert (A(i0) * B(-i0)).data == -px - 2 * py - 3 * pz
for i in range(4):
for j in range(4):
assert (A(i0) * B(-i1))[i, j] == [E, px, py, pz][i] * [0, -1, -2, -3][j]
# test contraction on the alternative Minkowski metric: [-1, 1, 1, 1]
assert (C(mu0) * C(-mu0)).data == -E ** 2 + px ** 2 + py ** 2 + pz ** 2
contrexp = A(i0) * AB(i1, -i0)
assert A(i0).rank == 1
assert AB(i1, -i0).rank == 2
assert contrexp.rank == 1
for i in range(4):
assert contrexp[i] == [E, px, py, pz][i]
def test_valued_tensor_self_contraction():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert AB(i0, -i0).data == 4
assert BA(i0, -i0).data == 2
def test_valued_tensor_pow():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert C**2 == -E**2 + px**2 + py**2 + pz**2
assert C**1 == sqrt(-E**2 + px**2 + py**2 + pz**2)
assert C(mu0)**2 == C**2
assert C(mu0)**1 == C**1
def test_valued_tensor_expressions():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
x1, x2, x3 = symbols('x1:4')
# test coefficient in contraction:
rank2coeff = x1 * A(i3) * B(i2)
assert rank2coeff[1, 1] == x1 * px
assert rank2coeff[3, 3] == 3 * pz * x1
coeff_expr = ((x1 * A(i4)) * (B(-i4) / x2)).data
assert coeff_expr.expand() == -px*x1/x2 - 2*py*x1/x2 - 3*pz*x1/x2
add_expr = A(i0) + B(i0)
assert add_expr[0] == E
assert add_expr[1] == px + 1
assert add_expr[2] == py + 2
assert add_expr[3] == pz + 3
sub_expr = A(i0) - B(i0)
assert sub_expr[0] == E
assert sub_expr[1] == px - 1
assert sub_expr[2] == py - 2
assert sub_expr[3] == pz - 3
assert (add_expr * B(-i0)).data == -px - 2*py - 3*pz - 14
expr1 = x1*A(i0) + x2*B(i0)
expr2 = expr1 * B(i1) * (-4)
expr3 = expr2 + 3*x3*AB(i0, i1)
expr4 = expr3 / 2
assert expr4 * 2 == expr3
expr5 = (expr4 * BA(-i1, -i0))
assert expr5.data.expand() == 28*E*x1 + 12*px*x1 + 20*py*x1 + 28*pz*x1 + 136*x2 + 3*x3
def test_valued_tensor_add_scalar():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
# one scalar summand after the contracted tensor
expr1 = A(i0)*A(-i0) - (E**2 - px**2 - py**2 - pz**2)
assert expr1.data == 0
# multiple scalar summands in front of the contracted tensor
expr2 = E**2 - px**2 - py**2 - pz**2 - A(i0)*A(-i0)
assert expr2.data == 0
# multiple scalar summands after the contracted tensor
expr3 = A(i0)*A(-i0) - E**2 + px**2 + py**2 + pz**2
assert expr3.data == 0
# multiple scalar summands and multiple tensors
expr4 = C(mu0)*C(-mu0) + 2*E**2 - 2*px**2 - 2*py**2 - 2*pz**2 - A(i0)*A(-i0)
assert expr4.data == 0
def test_noncommuting_components():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
euclid = TensorIndexType('Euclidean')
euclid.data = [1, 1]
i1, i2, i3 = tensor_indices('i1:4', euclid)
a, b, c, d = symbols('a b c d', commutative=False)
V1 = TensorHead('V1', [euclid]*2)
V1.data = [[a, b], (c, d)]
V2 = TensorHead('V2', [euclid]*2)
V2.data = [[a, c], [b, d]]
vtp = V1(i1, i2) * V2(-i2, -i1)
assert vtp.data == a**2 + b**2 + c**2 + d**2
assert vtp.data != a**2 + 2*b*c + d**2
vtp2 = V1(i1, i2)*V1(-i2, -i1)
assert vtp2.data == a**2 + b*c + c*b + d**2
assert vtp2.data != a**2 + 2*b*c + d**2
Vc = (b * V1(i1, -i1)).data
assert Vc.expand() == b * a + b * d
def test_valued_non_diagonal_metric():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
mmatrix = Matrix(ndm_matrix)
assert (NA(n0)*NA(-n0)).data == (NA(n0).get_matrix().T * mmatrix * NA(n0).get_matrix())[0, 0]
def test_valued_assign_numpy_ndarray():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
# this is needed to make sure that a numpy.ndarray can be assigned to a
# tensor.
arr = [E+1, px-1, py, pz]
A.data = Array(arr)
for i in range(4):
assert A(i0).data[i] == arr[i]
qx, qy, qz = symbols('qx qy qz')
A(-i0).data = Array([E, qx, qy, qz])
for i in range(4):
assert A(i0).data[i] == [E, -qx, -qy, -qz][i]
assert A.data[i] == [E, -qx, -qy, -qz][i]
# test on multi-indexed tensors.
random_4x4_data = [[(i**3-3*i**2)%(j+7) for i in range(4)] for j in range(4)]
AB(-i0, -i1).data = random_4x4_data
for i in range(4):
for j in range(4):
assert AB(i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)*(-1 if j else 1)
assert AB(-i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if j else 1)
assert AB(i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)
assert AB(-i0, -i1).data[i, j] == random_4x4_data[i][j]
AB(-i0, i1).data = random_4x4_data
for i in range(4):
for j in range(4):
assert AB(i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)
assert AB(-i0, i1).data[i, j] == random_4x4_data[i][j]
assert AB(i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)*(-1 if j else 1)
assert AB(-i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if j else 1)
def test_valued_metric_inverse():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
# let's assign some fancy matrix, just to verify it:
# (this has no physical sense, it's just testing sympy);
# it is symmetrical:
md = [[2, 2, 2, 1], [2, 3, 1, 0], [2, 1, 2, 3], [1, 0, 3, 2]]
Lorentz.data = md
m = Matrix(md)
metric = Lorentz.metric
minv = m.inv()
meye = eye(4)
# the Kronecker Delta:
KD = Lorentz.get_kronecker_delta()
for i in range(4):
for j in range(4):
assert metric(i0, i1).data[i, j] == m[i, j]
assert metric(-i0, -i1).data[i, j] == minv[i, j]
assert metric(i0, -i1).data[i, j] == meye[i, j]
assert metric(-i0, i1).data[i, j] == meye[i, j]
assert metric(i0, i1)[i, j] == m[i, j]
assert metric(-i0, -i1)[i, j] == minv[i, j]
assert metric(i0, -i1)[i, j] == meye[i, j]
assert metric(-i0, i1)[i, j] == meye[i, j]
assert KD(i0, -i1)[i, j] == meye[i, j]
def test_valued_canon_bp_swapaxes():
with warns_deprecated_sympy():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
e1 = A(i1)*A(i0)
e2 = e1.canon_bp()
assert e2 == A(i0)*A(i1)
for i in range(4):
for j in range(4):
assert e1[i, j] == e2[j, i]
o1 = B(i2)*A(i1)*B(i0)
o2 = o1.canon_bp()
for i in range(4):
for j in range(4):
for k in range(4):
assert o1[i, j, k] == o2[j, i, k]
def test_valued_components_with_wrong_symmetry():
with warns_deprecated_sympy():
IT = TensorIndexType('IT', dim=3)
i0, i1, i2, i3 = tensor_indices('i0:4', IT)
IT.data = [1, 1, 1]
A_nosym = TensorHead('A', [IT]*2)
A_sym = TensorHead('A', [IT]*2, TensorSymmetry.fully_symmetric(2))
A_antisym = TensorHead('A', [IT]*2, TensorSymmetry.fully_symmetric(-2))
mat_nosym = Matrix([[1,2,3],[4,5,6],[7,8,9]])
mat_sym = mat_nosym + mat_nosym.T
mat_antisym = mat_nosym - mat_nosym.T
A_nosym.data = mat_nosym
A_nosym.data = mat_sym
A_nosym.data = mat_antisym
def assign(A, dat):
A.data = dat
A_sym.data = mat_sym
raises(ValueError, lambda: assign(A_sym, mat_nosym))
raises(ValueError, lambda: assign(A_sym, mat_antisym))
A_antisym.data = mat_antisym
raises(ValueError, lambda: assign(A_antisym, mat_sym))
raises(ValueError, lambda: assign(A_antisym, mat_nosym))
A_sym.data = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
A_antisym.data = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
def test_issue_10972_TensMul_data():
with warns_deprecated_sympy():
Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='i', dim=2)
Lorentz.data = [-1, 1]
mu, nu, alpha, beta = tensor_indices('\\mu, \\nu, \\alpha, \\beta',
Lorentz)
u = TensorHead('u', [Lorentz])
u.data = [1, 0]
F = TensorHead('F', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
F.data = [[0, 1],
[-1, 0]]
mul_1 = F(mu, alpha) * u(-alpha) * F(nu, beta) * u(-beta)
assert (mul_1.data == Array([[0, 0], [0, 1]]))
mul_2 = F(mu, alpha) * F(nu, beta) * u(-alpha) * u(-beta)
assert (mul_2.data == mul_1.data)
assert ((mul_1 + mul_1).data == 2 * mul_1.data)
def test_TensMul_data():
with warns_deprecated_sympy():
Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='L', dim=4)
Lorentz.data = [-1, 1, 1, 1]
mu, nu, alpha, beta = tensor_indices('\\mu, \\nu, \\alpha, \\beta',
Lorentz)
u = TensorHead('u', [Lorentz])
u.data = [1, 0, 0, 0]
F = TensorHead('F', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z')
F.data = [
[0, Ex, Ey, Ez],
[-Ex, 0, Bz, -By],
[-Ey, -Bz, 0, Bx],
[-Ez, By, -Bx, 0]]
E = F(mu, nu) * u(-nu)
assert ((E(mu) * E(nu)).data ==
Array([[0, 0, 0, 0],
[0, Ex ** 2, Ex * Ey, Ex * Ez],
[0, Ex * Ey, Ey ** 2, Ey * Ez],
[0, Ex * Ez, Ey * Ez, Ez ** 2]])
)
assert ((E(mu) * E(nu)).canon_bp().data == (E(mu) * E(nu)).data)
assert ((F(mu, alpha) * F(beta, nu) * u(-alpha) * u(-beta)).data ==
- (E(mu) * E(nu)).data
)
assert ((F(alpha, mu) * F(beta, nu) * u(-alpha) * u(-beta)).data ==
(E(mu) * E(nu)).data
)
g = TensorHead('g', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
g.data = Lorentz.data
# tensor 'perp' is orthogonal to vector 'u'
perp = u(mu) * u(nu) + g(mu, nu)
mul_1 = u(-mu) * perp(mu, nu)
assert (mul_1.data == Array([0, 0, 0, 0]))
mul_2 = u(-mu) * perp(mu, alpha) * perp(nu, beta)
assert (mul_2.data == Array.zeros(4, 4, 4))
Fperp = perp(mu, alpha) * perp(nu, beta) * F(-alpha, -beta)
assert (Fperp.data[0, :] == Array([0, 0, 0, 0]))
assert (Fperp.data[:, 0] == Array([0, 0, 0, 0]))
mul_3 = u(-mu) * Fperp(mu, nu)
assert (mul_3.data == Array([0, 0, 0, 0]))
# Test the deleter
del g.data
def test_issue_11020_TensAdd_data():
with warns_deprecated_sympy():
Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='i', dim=2)
Lorentz.data = [-1, 1]
a, b, c, d = tensor_indices('a, b, c, d', Lorentz)
i0, i1 = tensor_indices('i_0:2', Lorentz)
# metric tensor
g = TensorHead('g', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
g.data = Lorentz.data
u = TensorHead('u', [Lorentz])
u.data = [1, 0]
add_1 = g(b, c) * g(d, i0) * u(-i0) - g(b, c) * u(d)
assert (add_1.data == Array.zeros(2, 2, 2))
# Now let us replace index `d` with `a`:
add_2 = g(b, c) * g(a, i0) * u(-i0) - g(b, c) * u(a)
assert (add_2.data == Array.zeros(2, 2, 2))
# some more tests
# perp is tensor orthogonal to u^\mu
perp = u(a) * u(b) + g(a, b)
mul_1 = u(-a) * perp(a, b)
assert (mul_1.data == Array([0, 0]))
mul_2 = u(-c) * perp(c, a) * perp(d, b)
assert (mul_2.data == Array.zeros(2, 2, 2))
def test_index_iteration():
L = TensorIndexType("Lorentz", dummy_name="L")
i0, i1, i2, i3, i4 = tensor_indices('i0:5', L)
L0 = tensor_indices('L_0', L)
L1 = tensor_indices('L_1', L)
A = TensorHead("A", [L, L])
B = TensorHead("B", [L, L], TensorSymmetry.fully_symmetric(2))
e1 = A(i0,i2)
e2 = A(i0,-i0)
e3 = A(i0,i1)*B(i2,i3)
e4 = A(i0,i1)*B(i2,-i1)
e5 = A(i0,i1)*B(-i0,-i1)
e6 = e1 + e4
assert list(e1._iterate_free_indices) == [(i0, (1, 0)), (i2, (1, 1))]
assert list(e1._iterate_dummy_indices) == []
assert list(e1._iterate_indices) == [(i0, (1, 0)), (i2, (1, 1))]
assert list(e2._iterate_free_indices) == []
assert list(e2._iterate_dummy_indices) == [(L0, (1, 0)), (-L0, (1, 1))]
assert list(e2._iterate_indices) == [(L0, (1, 0)), (-L0, (1, 1))]
assert list(e3._iterate_free_indices) == [(i0, (0, 1, 0)), (i1, (0, 1, 1)), (i2, (1, 1, 0)), (i3, (1, 1, 1))]
assert list(e3._iterate_dummy_indices) == []
assert list(e3._iterate_indices) == [(i0, (0, 1, 0)), (i1, (0, 1, 1)), (i2, (1, 1, 0)), (i3, (1, 1, 1))]
assert list(e4._iterate_free_indices) == [(i0, (0, 1, 0)), (i2, (1, 1, 0))]
assert list(e4._iterate_dummy_indices) == [(L0, (0, 1, 1)), (-L0, (1, 1, 1))]
assert list(e4._iterate_indices) == [(i0, (0, 1, 0)), (L0, (0, 1, 1)), (i2, (1, 1, 0)), (-L0, (1, 1, 1))]
assert list(e5._iterate_free_indices) == []
assert list(e5._iterate_dummy_indices) == [(L0, (0, 1, 0)), (L1, (0, 1, 1)), (-L0, (1, 1, 0)), (-L1, (1, 1, 1))]
assert list(e5._iterate_indices) == [(L0, (0, 1, 0)), (L1, (0, 1, 1)), (-L0, (1, 1, 0)), (-L1, (1, 1, 1))]
assert list(e6._iterate_free_indices) == [(i0, (0, 0, 1, 0)), (i2, (0, 1, 1, 0)), (i0, (1, 1, 0)), (i2, (1, 1, 1))]
assert list(e6._iterate_dummy_indices) == [(L0, (0, 0, 1, 1)), (-L0, (0, 1, 1, 1))]
assert list(e6._iterate_indices) == [(i0, (0, 0, 1, 0)), (L0, (0, 0, 1, 1)), (i2, (0, 1, 1, 0)), (-L0, (0, 1, 1, 1)), (i0, (1, 1, 0)), (i2, (1, 1, 1))]
assert e1.get_indices() == [i0, i2]
assert e1.get_free_indices() == [i0, i2]
assert e2.get_indices() == [L0, -L0]
assert e2.get_free_indices() == []
assert e3.get_indices() == [i0, i1, i2, i3]
assert e3.get_free_indices() == [i0, i1, i2, i3]
assert e4.get_indices() == [i0, L0, i2, -L0]
assert e4.get_free_indices() == [i0, i2]
assert e5.get_indices() == [L0, L1, -L0, -L1]
assert e5.get_free_indices() == []
def test_tensor_expand():
L = TensorIndexType("L")
i, j, k = tensor_indices("i j k", L)
L_0 = TensorIndex("L_0", L)
A, B, C, D = tensor_heads("A B C D", [L])
assert isinstance(Add(A(i), B(i)), TensAdd)
assert isinstance(expand(A(i)+B(i)), TensAdd)
expr = A(i)*(A(-i)+B(-i))
assert expr.args == (A(L_0), A(-L_0) + B(-L_0))
assert expr != A(i)*A(-i) + A(i)*B(-i)
assert expr.expand() == A(i)*A(-i) + A(i)*B(-i)
assert str(expr) == "A(L_0)*(A(-L_0) + B(-L_0))"
expr = A(i)*A(j) + A(i)*B(j)
assert str(expr) == "A(i)*A(j) + A(i)*B(j)"
expr = A(-i)*(A(i)*A(j) + A(i)*B(j)*C(k)*C(-k))
assert expr != A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)*C(k)*C(-k)
assert expr.expand() == A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)*C(k)*C(-k)
assert str(expr) == "A(-L_0)*(A(L_0)*A(j) + A(L_0)*B(j)*C(L_1)*C(-L_1))"
assert str(expr.canon_bp()) == 'A(j)*A(L_0)*A(-L_0) + A(L_0)*A(-L_0)*B(j)*C(L_1)*C(-L_1)'
expr = A(-i)*(2*A(i)*A(j) + A(i)*B(j))
assert expr.expand() == 2*A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)
expr = 2*A(i)*A(-i)
assert expr.coeff == 2
expr = A(i)*(B(j)*C(k) + C(j)*(A(k) + D(k)))
assert str(expr) == "A(i)*(B(j)*C(k) + C(j)*(A(k) + D(k)))"
assert str(expr.expand()) == "A(i)*B(j)*C(k) + A(i)*C(j)*A(k) + A(i)*C(j)*D(k)"
assert isinstance(TensMul(3), TensMul)
tm = TensMul(3).doit()
assert tm == 3
assert isinstance(tm, Integer)
p1 = B(j)*B(-j) + B(j)*C(-j)
p2 = C(-i)*p1
p3 = A(i)*p2
assert p3.expand() == A(i)*C(-i)*B(j)*B(-j) + A(i)*C(-i)*B(j)*C(-j)
expr = A(i)*(B(-i) + C(-i)*(B(j)*B(-j) + B(j)*C(-j)))
assert expr.expand() == A(i)*B(-i) + A(i)*C(-i)*B(j)*B(-j) + A(i)*C(-i)*B(j)*C(-j)
expr = C(-i)*(B(j)*B(-j) + B(j)*C(-j))
assert expr.expand() == C(-i)*B(j)*B(-j) + C(-i)*B(j)*C(-j)
def test_tensor_alternative_construction():
L = TensorIndexType("L")
i0, i1, i2, i3 = tensor_indices('i0:4', L)
A = TensorHead("A", [L])
x, y = symbols("x y")
assert A(i0) == A(Symbol("i0"))
assert A(-i0) == A(-Symbol("i0"))
raises(TypeError, lambda: A(x+y))
raises(ValueError, lambda: A(2*x))
def test_tensor_replacement():
L = TensorIndexType("L")
L2 = TensorIndexType("L2", dim=2)
i, j, k, l = tensor_indices("i j k l", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
K = TensorHead("K", [L]*4)
expr = H(i, j)
repl = {H(i,-j): [[1,2],[3,4]], L: diag(1, -1)}
assert expr._extract_data(repl) == ([i, j], Array([[1, -2], [3, -4]]))
assert expr.replace_with_arrays(repl) == Array([[1, -2], [3, -4]])
assert expr.replace_with_arrays(repl, [i, j]) == Array([[1, -2], [3, -4]])
assert expr.replace_with_arrays(repl, [i, -j]) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [Symbol("i"), -Symbol("j")]) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [-i, j]) == Array([[1, -2], [-3, 4]])
assert expr.replace_with_arrays(repl, [-i, -j]) == Array([[1, 2], [-3, -4]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[1, 3], [-2, -4]])
assert expr.replace_with_arrays(repl, [j, -i]) == Array([[1, -3], [-2, 4]])
assert expr.replace_with_arrays(repl, [-j, i]) == Array([[1, 3], [2, 4]])
assert expr.replace_with_arrays(repl, [-j, -i]) == Array([[1, -3], [2, -4]])
# Test stability of optional parameter 'indices'
assert expr.replace_with_arrays(repl) == Array([[1, -2], [3, -4]])
expr = H(i,j)
repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)}
assert expr._extract_data(repl) == ([i, j], Array([[1, 2], [3, 4]]))
assert expr.replace_with_arrays(repl) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [i, j]) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [i, -j]) == Array([[1, -2], [3, -4]])
assert expr.replace_with_arrays(repl, [-i, j]) == Array([[1, 2], [-3, -4]])
assert expr.replace_with_arrays(repl, [-i, -j]) == Array([[1, -2], [-3, 4]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[1, 3], [2, 4]])
assert expr.replace_with_arrays(repl, [j, -i]) == Array([[1, -3], [2, -4]])
assert expr.replace_with_arrays(repl, [-j, i]) == Array([[1, 3], [-2, -4]])
assert expr.replace_with_arrays(repl, [-j, -i]) == Array([[1, -3], [-2, 4]])
# Not the same indices:
expr = H(i,k)
repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)}
assert expr._extract_data(repl) == ([i, k], Array([[1, 2], [3, 4]]))
expr = A(i)*A(-i)
repl = {A(i): [1,2], L: diag(1, -1)}
assert expr._extract_data(repl) == ([], -3)
assert expr.replace_with_arrays(repl, []) == -3
expr = K(i, j, -j, k)*A(-i)*A(-k)
repl = {A(i): [1, 2], K(i,j,k,l): Array([1]*2**4).reshape(2,2,2,2), L: diag(1, -1)}
assert expr._extract_data(repl)
expr = H(j, k)
repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)}
raises(ValueError, lambda: expr._extract_data(repl))
expr = A(i)
repl = {B(i): [1, 2]}
raises(ValueError, lambda: expr._extract_data(repl))
expr = A(i)
repl = {A(i): [[1, 2], [3, 4]]}
raises(ValueError, lambda: expr._extract_data(repl))
# TensAdd:
expr = A(k)*H(i, j) + B(k)*H(i, j)
repl = {A(k): [1], B(k): [1], H(i, j): [[1, 2],[3,4]], L:diag(1,1)}
assert expr._extract_data(repl) == ([k, i, j], Array([[[2, 4], [6, 8]]]))
assert expr.replace_with_arrays(repl, [k, i, j]) == Array([[[2, 4], [6, 8]]])
assert expr.replace_with_arrays(repl, [k, j, i]) == Array([[[2, 6], [4, 8]]])
expr = A(k)*A(-k) + 100
repl = {A(k): [2, 3], L: diag(1, 1)}
assert expr.replace_with_arrays(repl, []) == 113
## Symmetrization:
expr = H(i, j) + H(j, i)
repl = {H(i, j): [[1, 2], [3, 4]]}
assert expr._extract_data(repl) == ([i, j], Array([[2, 5], [5, 8]]))
assert expr.replace_with_arrays(repl, [i, j]) == Array([[2, 5], [5, 8]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[2, 5], [5, 8]])
## Anti-symmetrization:
expr = H(i, j) - H(j, i)
repl = {H(i, j): [[1, 2], [3, 4]]}
assert expr.replace_with_arrays(repl, [i, j]) == Array([[0, -1], [1, 0]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[0, 1], [-1, 0]])
# Tensors with contractions in replacements:
expr = K(i, j, k, -k)
repl = {K(i, j, k, -k): [[1, 2], [3, 4]]}
assert expr._extract_data(repl) == ([i, j], Array([[1, 2], [3, 4]]))
expr = H(i, -i)
repl = {H(i, -i): 42}
assert expr._extract_data(repl) == ([], 42)
expr = H(i, -i)
repl = {
H(-i, -j): Array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]),
L: Array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]),
}
assert expr._extract_data(repl) == ([], 4)
# Replace with array, raise exception if indices are not compatible:
expr = A(i)*A(j)
repl = {A(i): [1, 2]}
raises(ValueError, lambda: expr.replace_with_arrays(repl, [j]))
# Raise exception if array dimension is not compatible:
expr = A(i)
repl = {A(i): [[1, 2]]}
raises(ValueError, lambda: expr.replace_with_arrays(repl, [i]))
# TensorIndexType with dimension, wrong dimension in replacement array:
u1, u2, u3 = tensor_indices("u1:4", L2)
U = TensorHead("U", [L2])
expr = U(u1)*U(-u2)
repl = {U(u1): [[1]]}
raises(ValueError, lambda: expr.replace_with_arrays(repl, [u1, -u2]))
def test_rewrite_tensor_to_Indexed():
L = TensorIndexType("L", dim=4)
A = TensorHead("A", [L]*4)
B = TensorHead("B", [L])
i0, i1, i2, i3 = symbols("i0:4")
L_0, L_1 = symbols("L_0:2")
a1 = A(i0, i1, i2, i3)
assert a1.rewrite(Indexed) == Indexed(Symbol("A"), i0, i1, i2, i3)
a2 = A(i0, -i0, i2, i3)
assert a2.rewrite(Indexed) == Sum(Indexed(Symbol("A"), L_0, L_0, i2, i3), (L_0, 0, 3))
a3 = a2 + A(i2, i3, i0, -i0)
assert a3.rewrite(Indexed) == \
Sum(Indexed(Symbol("A"), L_0, L_0, i2, i3), (L_0, 0, 3)) +\
Sum(Indexed(Symbol("A"), i2, i3, L_0, L_0), (L_0, 0, 3))
b1 = B(-i0)*a1
assert b1.rewrite(Indexed) == Sum(Indexed(Symbol("B"), L_0)*Indexed(Symbol("A"), L_0, i1, i2, i3), (L_0, 0, 3))
b2 = B(-i3)*a2
assert b2.rewrite(Indexed) == Sum(Indexed(Symbol("B"), L_1)*Indexed(Symbol("A"), L_0, L_0, i2, L_1), (L_0, 0, 3), (L_1, 0, 3))
def test_tensor_matching():
"""
Test match and replace with the pattern being a WildTensor or a WildTensorIndex
"""
R3 = TensorIndexType('R3', dim=3)
p, q, r = tensor_indices("p q r", R3)
a,b,c = symbols("a b c", cls = WildTensorIndex, tensor_index_type=R3, ignore_updown=True)
g = WildTensorIndex("g", R3)
eps = R3.epsilon
K = TensorHead("K", [R3])
V = TensorHead("V", [R3])
A = TensorHead("A", [R3, R3])
W = WildTensorHead('W', unordered_indices=True)
U = WildTensorHead('U')
assert a.matches(q) == {a:q}
assert a.matches(-q) == {a:-q}
assert g.matches(-q) == None
assert g.matches(q) == {g:q}
assert eps(p,-a,a).matches( eps(p,q,r) ) == None
assert eps(p,-b,a).matches( eps(p,q,r) ) == {a: r, -b: q}
assert eps(p,-q,r).replace(eps(a,b,c), 1) == 1
assert W().matches( K(p)*V(q) ) == {W(): K(p)*V(q)}
assert W(a).matches( K(p) ) == {a:p, W(a).head: _WildTensExpr(K(p))}
assert W(a,p).matches( K(p)*V(q) ) == {a:q, W(a,p).head: _WildTensExpr(K(p)*V(q))}
assert W(p,q).matches( K(p)*V(q) ) == {W(p,q).head: _WildTensExpr(K(p)*V(q))}
assert W(p,q).matches( A(q,p) ) == {W(p,q).head: _WildTensExpr(A(q, p))}
assert U(p,q).matches( A(q,p) ) == None
assert ( K(q)*K(p) ).replace( W(q,p), 1) == 1
def test_TensMul_subs():
"""
Test subs and xreplace in TensMul. See bug #24337
"""
R3 = TensorIndexType('R3', dim=3)
p, q, r = tensor_indices("p q r", R3)
K = TensorHead("K", [R3])
V = TensorHead("V", [R3])
A = TensorHead("A", [R3, R3])
C0 = TensorIndex(R3.dummy_name + "_0", R3, True)
assert ( K(p)*V(r)*K(-p) ).subs({V(r): K(q)*K(-q)}) == K(p)*K(q)*K(-q)*K(-p)
assert ( K(p)*V(r)*K(-p) ).xreplace({V(r): K(q)*K(-q)}) == K(p)*K(q)*K(-q)*K(-p)
assert ( K(p)*V(r) ).xreplace({p: C0, V(r): K(q)*K(-q)}) == K(C0)*K(q)*K(-q)
assert ( K(p)*A(q,-q)*K(-p) ).doit() == K(p)*A(q,-q)*K(-p)
def test_tensorsymmetry():
with warns_deprecated_sympy():
tensorsymmetry([1]*2)
def test_tensorhead():
with warns_deprecated_sympy():
tensorhead('A', [])
def test_TensorType():
with warns_deprecated_sympy():
sym2 = TensorSymmetry.fully_symmetric(2)
Lorentz = TensorIndexType('Lorentz')
S2 = TensorType([Lorentz]*2, sym2)
assert isinstance(S2, TensorType)
def test_dummy_fmt():
with warns_deprecated_sympy():
TensorIndexType('Lorentz', dummy_fmt='L')
|
7a930c86f44922191839fde656fdd6ce77078b2261c78a8ed7b7d2e1755c0054 | import operator
from functools import reduce, singledispatch
from sympy.core.expr import Expr
from sympy.core.singleton import S
from sympy.matrices.expressions.hadamard import HadamardProduct
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions.matexpr import (MatrixExpr, MatrixSymbol)
from sympy.matrices.expressions.special import Identity, OneMatrix
from sympy.matrices.expressions.transpose import Transpose
from sympy.combinatorics.permutations import _af_invert
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
from sympy.tensor.array.expressions.array_expressions import (
_ArrayExpr, ZeroArray, ArraySymbol, ArrayTensorProduct, ArrayAdd,
PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, get_rank,
get_shape, ArrayContraction, _array_tensor_product, _array_contraction,
_array_diagonal, _array_add, _permute_dims, Reshape)
from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
@singledispatch
def array_derive(expr, x):
"""
Derivatives (gradients) for array expressions.
"""
raise NotImplementedError(f"not implemented for type {type(expr)}")
@array_derive.register(Expr)
def _(expr: Expr, x: _ArrayExpr):
return ZeroArray(*x.shape)
@array_derive.register(ArrayTensorProduct)
def _(expr: ArrayTensorProduct, x: Expr):
args = expr.args
addend_list = []
for i, arg in enumerate(expr.args):
darg = array_derive(arg, x)
if darg == 0:
continue
args_prev = args[:i]
args_succ = args[i+1:]
shape_prev = reduce(operator.add, map(get_shape, args_prev), ())
shape_succ = reduce(operator.add, map(get_shape, args_succ), ())
addend = _array_tensor_product(*args_prev, darg, *args_succ)
tot1 = len(get_shape(x))
tot2 = tot1 + len(shape_prev)
tot3 = tot2 + len(get_shape(arg))
tot4 = tot3 + len(shape_succ)
perm = [i for i in range(tot1, tot2)] + \
[i for i in range(tot1)] + [i for i in range(tot2, tot3)] + \
[i for i in range(tot3, tot4)]
addend = _permute_dims(addend, _af_invert(perm))
addend_list.append(addend)
if len(addend_list) == 1:
return addend_list[0]
elif len(addend_list) == 0:
return S.Zero
else:
return _array_add(*addend_list)
@array_derive.register(ArraySymbol)
def _(expr: ArraySymbol, x: _ArrayExpr):
if expr == x:
return _permute_dims(
ArrayTensorProduct.fromiter(Identity(i) for i in expr.shape),
[2*i for i in range(len(expr.shape))] + [2*i+1 for i in range(len(expr.shape))]
)
return ZeroArray(*(x.shape + expr.shape))
@array_derive.register(MatrixSymbol)
def _(expr: MatrixSymbol, x: _ArrayExpr):
m, n = expr.shape
if expr == x:
return _permute_dims(
_array_tensor_product(Identity(m), Identity(n)),
[0, 2, 1, 3]
)
return ZeroArray(*(x.shape + expr.shape))
@array_derive.register(Identity)
def _(expr: Identity, x: _ArrayExpr):
return ZeroArray(*(x.shape + expr.shape))
@array_derive.register(OneMatrix)
def _(expr: OneMatrix, x: _ArrayExpr):
return ZeroArray(*(x.shape + expr.shape))
@array_derive.register(Transpose)
def _(expr: Transpose, x: Expr):
# D(A.T, A) ==> (m,n,i,j) ==> D(A_ji, A_mn) = d_mj d_ni
# D(B.T, A) ==> (m,n,i,j) ==> D(B_ji, A_mn)
fd = array_derive(expr.arg, x)
return _permute_dims(fd, [0, 1, 3, 2])
@array_derive.register(Inverse)
def _(expr: Inverse, x: Expr):
mat = expr.I
dexpr = array_derive(mat, x)
tp = _array_tensor_product(-expr, dexpr, expr)
mp = _array_contraction(tp, (1, 4), (5, 6))
pp = _permute_dims(mp, [1, 2, 0, 3])
return pp
@array_derive.register(ElementwiseApplyFunction)
def _(expr: ElementwiseApplyFunction, x: Expr):
assert get_rank(expr) == 2
assert get_rank(x) == 2
fdiff = expr._get_function_fdiff()
dexpr = array_derive(expr.expr, x)
tp = _array_tensor_product(
ElementwiseApplyFunction(fdiff, expr.expr),
dexpr
)
td = _array_diagonal(
tp, (0, 4), (1, 5)
)
return td
@array_derive.register(ArrayElementwiseApplyFunc)
def _(expr: ArrayElementwiseApplyFunc, x: Expr):
fdiff = expr._get_function_fdiff()
subexpr = expr.expr
dsubexpr = array_derive(subexpr, x)
tp = _array_tensor_product(
dsubexpr,
ArrayElementwiseApplyFunc(fdiff, subexpr)
)
b = get_rank(x)
c = get_rank(expr)
diag_indices = [(b + i, b + c + i) for i in range(c)]
return _array_diagonal(tp, *diag_indices)
@array_derive.register(MatrixExpr)
def _(expr: MatrixExpr, x: Expr):
cg = convert_matrix_to_array(expr)
return array_derive(cg, x)
@array_derive.register(HadamardProduct)
def _(expr: HadamardProduct, x: Expr):
raise NotImplementedError()
@array_derive.register(ArrayContraction)
def _(expr: ArrayContraction, x: Expr):
fd = array_derive(expr.expr, x)
rank_x = len(get_shape(x))
contraction_indices = expr.contraction_indices
new_contraction_indices = [tuple(j + rank_x for j in i) for i in contraction_indices]
return _array_contraction(fd, *new_contraction_indices)
@array_derive.register(ArrayDiagonal)
def _(expr: ArrayDiagonal, x: Expr):
dsubexpr = array_derive(expr.expr, x)
rank_x = len(get_shape(x))
diag_indices = [[j + rank_x for j in i] for i in expr.diagonal_indices]
return _array_diagonal(dsubexpr, *diag_indices)
@array_derive.register(ArrayAdd)
def _(expr: ArrayAdd, x: Expr):
return _array_add(*[array_derive(arg, x) for arg in expr.args])
@array_derive.register(PermuteDims)
def _(expr: PermuteDims, x: Expr):
de = array_derive(expr.expr, x)
perm = [0, 1] + [i + 2 for i in expr.permutation.array_form]
return _permute_dims(de, perm)
@array_derive.register(Reshape)
def _(expr: Reshape, x: Expr):
de = array_derive(expr.expr, x)
return Reshape(de, get_shape(x) + expr.shape)
def matrix_derive(expr, x):
from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
ce = convert_matrix_to_array(expr)
dce = array_derive(ce, x)
return convert_array_to_matrix(dce).doit()
|
69b88165a2904506278b1fb935b6028e23ae1e82a3f59e18d18288895d47ee85 | import random
import concurrent.futures
from collections.abc import Hashable
from sympy.core.add import Add
from sympy.core.function import (Function, diff, expand)
from sympy.core.numbers import (E, Float, I, Integer, Rational, nan, oo, pi)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
from sympy.integrals.integrals import integrate
from sympy.polys.polytools import (Poly, PurePoly)
from sympy.printing.str import sstr
from sympy.sets.sets import FiniteSet
from sympy.simplify.simplify import (signsimp, simplify)
from sympy.simplify.trigsimp import trigsimp
from sympy.matrices.matrices import (ShapeError, MatrixError,
NonSquareMatrixError, DeferredVector, _find_reasonable_pivot_naive,
_simplify)
from sympy.matrices import (
GramSchmidt, ImmutableMatrix, ImmutableSparseMatrix, Matrix,
SparseMatrix, casoratian, diag, eye, hessian,
matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2,
rot_axis3, wronskian, zeros, MutableDenseMatrix, ImmutableDenseMatrix,
MatrixSymbol, dotprodsimp, rot_ccw_axis1, rot_ccw_axis2, rot_ccw_axis3)
from sympy.matrices.utilities import _dotprodsimp_state
from sympy.core import Tuple, Wild
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.utilities.iterables import flatten, capture, iterable
from sympy.utilities.exceptions import ignore_warnings, SymPyDeprecationWarning
from sympy.testing.pytest import (raises, XFAIL, slow, skip,
warns_deprecated_sympy, warns)
from sympy.assumptions import Q
from sympy.tensor.array import Array
from sympy.matrices.expressions import MatPow
from sympy.external import import_module
from sympy.algebras import Quaternion
from sympy.abc import a, b, c, d, x, y, z, t
pyodide_js = import_module('pyodide_js')
# don't re-order this list
classes = (Matrix, SparseMatrix, ImmutableMatrix, ImmutableSparseMatrix)
def test_args():
for n, cls in enumerate(classes):
m = cls.zeros(3, 2)
# all should give back the same type of arguments, e.g. ints for shape
assert m.shape == (3, 2) and all(type(i) is int for i in m.shape)
assert m.rows == 3 and type(m.rows) is int
assert m.cols == 2 and type(m.cols) is int
if not n % 2:
assert type(m.flat()) in (list, tuple, Tuple)
else:
assert type(m.todok()) is dict
def test_deprecated_mat_smat():
for cls in Matrix, ImmutableMatrix:
m = cls.zeros(3, 2)
with warns_deprecated_sympy():
mat = m._mat
assert mat == m.flat()
for cls in SparseMatrix, ImmutableSparseMatrix:
m = cls.zeros(3, 2)
with warns_deprecated_sympy():
smat = m._smat
assert smat == m.todok()
def test_division():
v = Matrix(1, 2, [x, y])
assert v/z == Matrix(1, 2, [x/z, y/z])
def test_sum():
m = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
assert m + m == Matrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]])
n = Matrix(1, 2, [1, 2])
raises(ShapeError, lambda: m + n)
def test_abs():
m = Matrix(1, 2, [-3, x])
n = Matrix(1, 2, [3, Abs(x)])
assert abs(m) == n
def test_addition():
a = Matrix((
(1, 2),
(3, 1),
))
b = Matrix((
(1, 2),
(3, 0),
))
assert a + b == a.add(b) == Matrix([[2, 4], [6, 1]])
def test_fancy_index_matrix():
for M in (Matrix, SparseMatrix):
a = M(3, 3, range(9))
assert a == a[:, :]
assert a[1, :] == Matrix(1, 3, [3, 4, 5])
assert a[:, 1] == Matrix([1, 4, 7])
assert a[[0, 1], :] == Matrix([[0, 1, 2], [3, 4, 5]])
assert a[[0, 1], 2] == a[[0, 1], [2]]
assert a[2, [0, 1]] == a[[2], [0, 1]]
assert a[:, [0, 1]] == Matrix([[0, 1], [3, 4], [6, 7]])
assert a[0, 0] == 0
assert a[0:2, :] == Matrix([[0, 1, 2], [3, 4, 5]])
assert a[:, 0:2] == Matrix([[0, 1], [3, 4], [6, 7]])
assert a[::2, 1] == a[[0, 2], 1]
assert a[1, ::2] == a[1, [0, 2]]
a = M(3, 3, range(9))
assert a[[0, 2, 1, 2, 1], :] == Matrix([
[0, 1, 2],
[6, 7, 8],
[3, 4, 5],
[6, 7, 8],
[3, 4, 5]])
assert a[:, [0,2,1,2,1]] == Matrix([
[0, 2, 1, 2, 1],
[3, 5, 4, 5, 4],
[6, 8, 7, 8, 7]])
a = SparseMatrix.zeros(3)
a[1, 2] = 2
a[0, 1] = 3
a[2, 0] = 4
assert a.extract([1, 1], [2]) == Matrix([
[2],
[2]])
assert a.extract([1, 0], [2, 2, 2]) == Matrix([
[2, 2, 2],
[0, 0, 0]])
assert a.extract([1, 0, 1, 2], [2, 0, 1, 0]) == Matrix([
[2, 0, 0, 0],
[0, 0, 3, 0],
[2, 0, 0, 0],
[0, 4, 0, 4]])
def test_multiplication():
a = Matrix((
(1, 2),
(3, 1),
(0, 6),
))
b = Matrix((
(1, 2),
(3, 0),
))
c = a*b
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
try:
eval('c = a @ b')
except SyntaxError:
pass
else:
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
h = matrix_multiply_elementwise(a, c)
assert h == a.multiply_elementwise(c)
assert h[0, 0] == 7
assert h[0, 1] == 4
assert h[1, 0] == 18
assert h[1, 1] == 6
assert h[2, 0] == 0
assert h[2, 1] == 0
raises(ShapeError, lambda: matrix_multiply_elementwise(a, b))
c = b * Symbol("x")
assert isinstance(c, Matrix)
assert c[0, 0] == x
assert c[0, 1] == 2*x
assert c[1, 0] == 3*x
assert c[1, 1] == 0
c2 = x * b
assert c == c2
c = 5 * b
assert isinstance(c, Matrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
try:
eval('c = 5 @ b')
except SyntaxError:
pass
else:
assert isinstance(c, Matrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
M = Matrix([[oo, 0], [0, oo]])
assert M ** 2 == M
M = Matrix([[oo, oo], [0, 0]])
assert M ** 2 == Matrix([[nan, nan], [nan, nan]])
def test_power():
raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2)
R = Rational
A = Matrix([[2, 3], [4, 5]])
assert (A**-3)[:] == [R(-269)/8, R(153)/8, R(51)/2, R(-29)/2]
assert (A**5)[:] == [6140, 8097, 10796, 14237]
A = Matrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433]
assert A**0 == eye(3)
assert A**1 == A
assert (Matrix([[2]]) ** 100)[0, 0] == 2**100
assert eye(2)**10000000 == eye(2)
assert Matrix([[1, 2], [3, 4]])**Integer(2) == Matrix([[7, 10], [15, 22]])
A = Matrix([[33, 24], [48, 57]])
assert (A**S.Half)[:] == [5, 2, 4, 7]
A = Matrix([[0, 4], [-1, 5]])
assert (A**S.Half)**2 == A
assert Matrix([[1, 0], [1, 1]])**S.Half == Matrix([[1, 0], [S.Half, 1]])
assert Matrix([[1, 0], [1, 1]])**0.5 == Matrix([[1, 0], [0.5, 1]])
from sympy.abc import n
assert Matrix([[1, a], [0, 1]])**n == Matrix([[1, a*n], [0, 1]])
assert Matrix([[b, a], [0, b]])**n == Matrix([[b**n, a*b**(n-1)*n], [0, b**n]])
assert Matrix([
[a**n, a**(n - 1)*n, (a**n*n**2 - a**n*n)/(2*a**2)],
[ 0, a**n, a**(n - 1)*n],
[ 0, 0, a**n]])
assert Matrix([[a, 1, 0], [0, a, 0], [0, 0, b]])**n == Matrix([
[a**n, a**(n-1)*n, 0],
[0, a**n, 0],
[0, 0, b**n]])
A = Matrix([[1, 0], [1, 7]])
assert A._matrix_pow_by_jordan_blocks(S(3)) == A._eval_pow_by_recursion(3)
A = Matrix([[2]])
assert A**10 == Matrix([[2**10]]) == A._matrix_pow_by_jordan_blocks(S(10)) == \
A._eval_pow_by_recursion(10)
# testing a matrix that cannot be jordan blocked issue 11766
m = Matrix([[3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]])
raises(MatrixError, lambda: m._matrix_pow_by_jordan_blocks(S(10)))
# test issue 11964
raises(MatrixError, lambda: Matrix([[1, 1], [3, 3]])._matrix_pow_by_jordan_blocks(S(-10)))
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) # Nilpotent jordan block size 3
assert A**10.0 == Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
raises(ValueError, lambda: A**2.1)
raises(ValueError, lambda: A**Rational(3, 2))
A = Matrix([[8, 1], [3, 2]])
assert A**10.0 == Matrix([[1760744107, 272388050], [817164150, 126415807]])
A = Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 1
assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 2
assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
n = Symbol('n', integer=True)
assert isinstance(A**n, MatPow)
n = Symbol('n', integer=True, negative=True)
raises(ValueError, lambda: A**n)
n = Symbol('n', integer=True, nonnegative=True)
assert A**n == Matrix([
[KroneckerDelta(0, n), KroneckerDelta(1, n), -KroneckerDelta(0, n) - KroneckerDelta(1, n) + 1],
[ 0, KroneckerDelta(0, n), 1 - KroneckerDelta(0, n)],
[ 0, 0, 1]])
assert A**(n + 2) == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
raises(ValueError, lambda: A**Rational(3, 2))
A = Matrix([[0, 0, 1], [3, 0, 1], [4, 3, 1]])
assert A**5.0 == Matrix([[168, 72, 89], [291, 144, 161], [572, 267, 329]])
assert A**5.0 == A**5
A = Matrix([[0, 1, 0],[-1, 0, 0],[0, 0, 0]])
n = Symbol("n")
An = A**n
assert An.subs(n, 2).doit() == A**2
raises(ValueError, lambda: An.subs(n, -2).doit())
assert An * An == A**(2*n)
# concretizing behavior for non-integer and complex powers
A = Matrix([[0,0,0],[0,0,0],[0,0,0]])
n = Symbol('n', integer=True, positive=True)
assert A**n == A
n = Symbol('n', integer=True, nonnegative=True)
assert A**n == diag(0**n, 0**n, 0**n)
assert (A**n).subs(n, 0) == eye(3)
assert (A**n).subs(n, 1) == zeros(3)
A = Matrix ([[2,0,0],[0,2,0],[0,0,2]])
assert A**2.1 == diag (2**2.1, 2**2.1, 2**2.1)
assert A**I == diag (2**I, 2**I, 2**I)
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]])
raises(ValueError, lambda: A**2.1)
raises(ValueError, lambda: A**I)
A = Matrix([[S.Half, S.Half], [S.Half, S.Half]])
assert A**S.Half == A
A = Matrix([[1, 1],[3, 3]])
assert A**S.Half == Matrix ([[S.Half, S.Half], [3*S.Half, 3*S.Half]])
def test_issue_17247_expression_blowup_1():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
with dotprodsimp(True):
assert M.exp().expand() == Matrix([
[ (exp(2*x) + exp(2))/2, (-exp(2*x) + exp(2))/2],
[(-exp(2*x) + exp(2))/2, (exp(2*x) + exp(2))/2]])
def test_issue_17247_expression_blowup_2():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
with dotprodsimp(True):
P, J = M.jordan_form ()
assert P*J*P.inv()
def test_issue_17247_expression_blowup_3():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
with dotprodsimp(True):
assert M**100 == Matrix([
[633825300114114700748351602688*x**100 + 633825300114114700748351602688, 633825300114114700748351602688 - 633825300114114700748351602688*x**100],
[633825300114114700748351602688 - 633825300114114700748351602688*x**100, 633825300114114700748351602688*x**100 + 633825300114114700748351602688]])
def test_issue_17247_expression_blowup_4():
# This matrix takes extremely long on current master even with intermediate simplification so an abbreviated version is used. It is left here for test in case of future optimizations.
# M = Matrix(S('''[
# [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256, 15/128 - 3*I/32, 19/256 + 551*I/1024],
# [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096, 129/256 - 549*I/512, 42533/16384 + 29103*I/8192],
# [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256],
# [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096],
# [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128],
# [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024],
# [ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
# [ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
# [ -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
# [ 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
# [ -4, 9 - 5*I, -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
# [ -2*I, 119/8 + 29*I/4, 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
# assert M**10 == Matrix([
# [ 7*(-221393644768594642173548179825793834595 - 1861633166167425978847110897013541127952*I)/9671406556917033397649408, 15*(31670992489131684885307005100073928751695 + 10329090958303458811115024718207404523808*I)/77371252455336267181195264, 7*(-3710978679372178839237291049477017392703 + 1377706064483132637295566581525806894169*I)/19342813113834066795298816, (9727707023582419994616144751727760051598 - 59261571067013123836477348473611225724433*I)/9671406556917033397649408, (31896723509506857062605551443641668183707 + 54643444538699269118869436271152084599580*I)/38685626227668133590597632, (-2024044860947539028275487595741003997397402 + 130959428791783397562960461903698670485863*I)/309485009821345068724781056, 3*(26190251453797590396533756519358368860907 - 27221191754180839338002754608545400941638*I)/77371252455336267181195264, (1154643595139959842768960128434994698330461 + 3385496216250226964322872072260446072295634*I)/618970019642690137449562112, 3*(-31849347263064464698310044805285774295286 - 11877437776464148281991240541742691164309*I)/77371252455336267181195264, (4661330392283532534549306589669150228040221 - 4171259766019818631067810706563064103956871*I)/1237940039285380274899124224, (9598353794289061833850770474812760144506 + 358027153990999990968244906482319780943983*I)/309485009821345068724781056, (-9755135335127734571547571921702373498554177 - 4837981372692695195747379349593041939686540*I)/2475880078570760549798248448],
# [(-379516731607474268954110071392894274962069 - 422272153179747548473724096872271700878296*I)/77371252455336267181195264, (41324748029613152354787280677832014263339501 - 12715121258662668420833935373453570749288074*I)/1237940039285380274899124224, (-339216903907423793947110742819264306542397 + 494174755147303922029979279454787373566517*I)/77371252455336267181195264, (-18121350839962855576667529908850640619878381 - 37413012454129786092962531597292531089199003*I)/1237940039285380274899124224, (2489661087330511608618880408199633556675926 + 1137821536550153872137379935240732287260863*I)/309485009821345068724781056, (-136644109701594123227587016790354220062972119 + 110130123468183660555391413889600443583585272*I)/4951760157141521099596496896, (1488043981274920070468141664150073426459593 - 9691968079933445130866371609614474474327650*I)/1237940039285380274899124224, 27*(4636797403026872518131756991410164760195942 + 3369103221138229204457272860484005850416533*I)/4951760157141521099596496896, (-8534279107365915284081669381642269800472363 + 2241118846262661434336333368511372725482742*I)/1237940039285380274899124224, (60923350128174260992536531692058086830950875 - 263673488093551053385865699805250505661590126*I)/9903520314283042199192993792, (18520943561240714459282253753348921824172569 + 24846649186468656345966986622110971925703604*I)/4951760157141521099596496896, (-232781130692604829085973604213529649638644431 + 35981505277760667933017117949103953338570617*I)/9903520314283042199192993792],
# [ (8742968295129404279528270438201520488950 + 3061473358639249112126847237482570858327*I)/4835703278458516698824704, (-245657313712011778432792959787098074935273 + 253113767861878869678042729088355086740856*I)/38685626227668133590597632, (1947031161734702327107371192008011621193 - 19462330079296259148177542369999791122762*I)/9671406556917033397649408, (552856485625209001527688949522750288619217 + 392928441196156725372494335248099016686580*I)/77371252455336267181195264, (-44542866621905323121630214897126343414629 + 3265340021421335059323962377647649632959*I)/19342813113834066795298816, (136272594005759723105646069956434264218730 - 330975364731707309489523680957584684763587*I)/38685626227668133590597632, (27392593965554149283318732469825168894401 + 75157071243800133880129376047131061115278*I)/38685626227668133590597632, 7*(-357821652913266734749960136017214096276154 - 45509144466378076475315751988405961498243*I)/309485009821345068724781056, (104485001373574280824835174390219397141149 - 99041000529599568255829489765415726168162*I)/77371252455336267181195264, (1198066993119982409323525798509037696321291 + 4249784165667887866939369628840569844519936*I)/618970019642690137449562112, (-114985392587849953209115599084503853611014 - 52510376847189529234864487459476242883449*I)/77371252455336267181195264, (6094620517051332877965959223269600650951573 - 4683469779240530439185019982269137976201163*I)/1237940039285380274899124224],
# [ (611292255597977285752123848828590587708323 - 216821743518546668382662964473055912169502*I)/77371252455336267181195264, (-1144023204575811464652692396337616594307487 + 12295317806312398617498029126807758490062855*I)/309485009821345068724781056, (-374093027769390002505693378578475235158281 - 573533923565898290299607461660384634333639*I)/77371252455336267181195264, (47405570632186659000138546955372796986832987 - 2837476058950808941605000274055970055096534*I)/1237940039285380274899124224, (-571573207393621076306216726219753090535121 + 533381457185823100878764749236639320783831*I)/77371252455336267181195264, (-7096548151856165056213543560958582513797519 - 24035731898756040059329175131592138642195366*I)/618970019642690137449562112, (2396762128833271142000266170154694033849225 + 1448501087375679588770230529017516492953051*I)/309485009821345068724781056, (-150609293845161968447166237242456473262037053 + 92581148080922977153207018003184520294188436*I)/4951760157141521099596496896, 5*(270278244730804315149356082977618054486347 - 1997830155222496880429743815321662710091562*I)/1237940039285380274899124224, (62978424789588828258068912690172109324360330 + 44803641177219298311493356929537007630129097*I)/2475880078570760549798248448, 19*(-451431106327656743945775812536216598712236 + 114924966793632084379437683991151177407937*I)/1237940039285380274899124224, (63417747628891221594106738815256002143915995 - 261508229397507037136324178612212080871150958*I)/9903520314283042199192993792],
# [ (-2144231934021288786200752920446633703357 + 2305614436009705803670842248131563850246*I)/1208925819614629174706176, (-90720949337459896266067589013987007078153 - 221951119475096403601562347412753844534569*I)/19342813113834066795298816, (11590973613116630788176337262688659880376 + 6514520676308992726483494976339330626159*I)/4835703278458516698824704, 3*(-131776217149000326618649542018343107657237 + 79095042939612668486212006406818285287004*I)/38685626227668133590597632, (10100577916793945997239221374025741184951 - 28631383488085522003281589065994018550748*I)/9671406556917033397649408, 67*(10090295594251078955008130473573667572549 + 10449901522697161049513326446427839676762*I)/77371252455336267181195264, (-54270981296988368730689531355811033930513 - 3413683117592637309471893510944045467443*I)/19342813113834066795298816, (440372322928679910536575560069973699181278 - 736603803202303189048085196176918214409081*I)/77371252455336267181195264, (33220374714789391132887731139763250155295 + 92055083048787219934030779066298919603554*I)/38685626227668133590597632, 5*(-594638554579967244348856981610805281527116 - 82309245323128933521987392165716076704057*I)/309485009821345068724781056, (128056368815300084550013708313312073721955 - 114619107488668120303579745393765245911404*I)/77371252455336267181195264, 21*(59839959255173222962789517794121843393573 + 241507883613676387255359616163487405826334*I)/618970019642690137449562112],
# [ (-13454485022325376674626653802541391955147 + 184471402121905621396582628515905949793486*I)/19342813113834066795298816, (-6158730123400322562149780662133074862437105 - 3416173052604643794120262081623703514107476*I)/154742504910672534362390528, (770558003844914708453618983120686116100419 - 127758381209767638635199674005029818518766*I)/77371252455336267181195264, (-4693005771813492267479835161596671660631703 + 12703585094750991389845384539501921531449948*I)/309485009821345068724781056, (-295028157441149027913545676461260860036601 - 841544569970643160358138082317324743450770*I)/77371252455336267181195264, (56716442796929448856312202561538574275502893 + 7216818824772560379753073185990186711454778*I)/1237940039285380274899124224, 15*(-87061038932753366532685677510172566368387 + 61306141156647596310941396434445461895538*I)/154742504910672534362390528, (-3455315109680781412178133042301025723909347 - 24969329563196972466388460746447646686670670*I)/618970019642690137449562112, (2453418854160886481106557323699250865361849 + 1497886802326243014471854112161398141242514*I)/309485009821345068724781056, (-151343224544252091980004429001205664193082173 + 90471883264187337053549090899816228846836628*I)/4951760157141521099596496896, (1652018205533026103358164026239417416432989 - 9959733619236515024261775397109724431400162*I)/1237940039285380274899124224, 3*(40676374242956907656984876692623172736522006 + 31023357083037817469535762230872667581366205*I)/4951760157141521099596496896],
# [ (-1226990509403328460274658603410696548387 - 4131739423109992672186585941938392788458*I)/1208925819614629174706176, (162392818524418973411975140074368079662703 + 23706194236915374831230612374344230400704*I)/9671406556917033397649408, (-3935678233089814180000602553655565621193 + 2283744757287145199688061892165659502483*I)/1208925819614629174706176, (-2400210250844254483454290806930306285131 - 315571356806370996069052930302295432758205*I)/19342813113834066795298816, (13365917938215281056563183751673390817910 + 15911483133819801118348625831132324863881*I)/4835703278458516698824704, 3*(-215950551370668982657516660700301003897855 + 51684341999223632631602864028309400489378*I)/38685626227668133590597632, (20886089946811765149439844691320027184765 - 30806277083146786592790625980769214361844*I)/9671406556917033397649408, (562180634592713285745940856221105667874855 + 1031543963988260765153550559766662245114916*I)/77371252455336267181195264, (-65820625814810177122941758625652476012867 - 12429918324787060890804395323920477537595*I)/19342813113834066795298816, (319147848192012911298771180196635859221089 - 402403304933906769233365689834404519960394*I)/38685626227668133590597632, (23035615120921026080284733394359587955057 + 115351677687031786114651452775242461310624*I)/38685626227668133590597632, (-3426830634881892756966440108592579264936130 - 1022954961164128745603407283836365128598559*I)/309485009821345068724781056],
# [ (-192574788060137531023716449082856117537757 - 69222967328876859586831013062387845780692*I)/19342813113834066795298816, (2736383768828013152914815341491629299773262 - 2773252698016291897599353862072533475408743*I)/77371252455336267181195264, (-23280005281223837717773057436155921656805 + 214784953368021840006305033048142888879224*I)/19342813113834066795298816, (-3035247484028969580570400133318947903462326 - 2195168903335435855621328554626336958674325*I)/77371252455336267181195264, (984552428291526892214541708637840971548653 - 64006622534521425620714598573494988589378*I)/77371252455336267181195264, (-3070650452470333005276715136041262898509903 + 7286424705750810474140953092161794621989080*I)/154742504910672534362390528, (-147848877109756404594659513386972921139270 - 416306113044186424749331418059456047650861*I)/38685626227668133590597632, (55272118474097814260289392337160619494260781 + 7494019668394781211907115583302403519488058*I)/1237940039285380274899124224, (-581537886583682322424771088996959213068864 + 542191617758465339135308203815256798407429*I)/77371252455336267181195264, (-6422548983676355789975736799494791970390991 - 23524183982209004826464749309156698827737702*I)/618970019642690137449562112, 7*(180747195387024536886923192475064903482083 + 84352527693562434817771649853047924991804*I)/154742504910672534362390528, (-135485179036717001055310712747643466592387031 + 102346575226653028836678855697782273460527608*I)/4951760157141521099596496896],
# [ (3384238362616083147067025892852431152105 + 156724444932584900214919898954874618256*I)/604462909807314587353088, (-59558300950677430189587207338385764871866 + 114427143574375271097298201388331237478857*I)/4835703278458516698824704, (-1356835789870635633517710130971800616227 - 7023484098542340388800213478357340875410*I)/1208925819614629174706176, (234884918567993750975181728413524549575881 + 79757294640629983786895695752733890213506*I)/9671406556917033397649408, (-7632732774935120473359202657160313866419 + 2905452608512927560554702228553291839465*I)/1208925819614629174706176, (52291747908702842344842889809762246649489 - 520996778817151392090736149644507525892649*I)/19342813113834066795298816, (17472406829219127839967951180375981717322 + 23464704213841582137898905375041819568669*I)/4835703278458516698824704, (-911026971811893092350229536132730760943307 + 150799318130900944080399439626714846752360*I)/38685626227668133590597632, (26234457233977042811089020440646443590687 - 45650293039576452023692126463683727692890*I)/9671406556917033397649408, 3*(288348388717468992528382586652654351121357 + 454526517721403048270274049572136109264668*I)/77371252455336267181195264, (-91583492367747094223295011999405657956347 - 12704691128268298435362255538069612411331*I)/19342813113834066795298816, (411208730251327843849027957710164064354221 - 569898526380691606955496789378230959965898*I)/38685626227668133590597632],
# [ (27127513117071487872628354831658811211795 - 37765296987901990355760582016892124833857*I)/4835703278458516698824704, (1741779916057680444272938534338833170625435 + 3083041729779495966997526404685535449810378*I)/77371252455336267181195264, 3*(-60642236251815783728374561836962709533401 - 24630301165439580049891518846174101510744*I)/19342813113834066795298816, 3*(445885207364591681637745678755008757483408 - 350948497734812895032502179455610024541643*I)/38685626227668133590597632, (-47373295621391195484367368282471381775684 + 219122969294089357477027867028071400054973*I)/19342813113834066795298816, (-2801565819673198722993348253876353741520438 - 2250142129822658548391697042460298703335701*I)/77371252455336267181195264, (801448252275607253266997552356128790317119 - 50890367688077858227059515894356594900558*I)/77371252455336267181195264, (-5082187758525931944557763799137987573501207 + 11610432359082071866576699236013484487676124*I)/309485009821345068724781056, (-328925127096560623794883760398247685166830 - 643447969697471610060622160899409680422019*I)/77371252455336267181195264, 15*(2954944669454003684028194956846659916299765 + 33434406416888505837444969347824812608566*I)/1237940039285380274899124224, (-415749104352001509942256567958449835766827 + 479330966144175743357171151440020955412219*I)/77371252455336267181195264, 3*(-4639987285852134369449873547637372282914255 - 11994411888966030153196659207284951579243273*I)/1237940039285380274899124224],
# [ (-478846096206269117345024348666145495601 + 1249092488629201351470551186322814883283*I)/302231454903657293676544, (-17749319421930878799354766626365926894989 - 18264580106418628161818752318217357231971*I)/1208925819614629174706176, (2801110795431528876849623279389579072819 + 363258850073786330770713557775566973248*I)/604462909807314587353088, (-59053496693129013745775512127095650616252 + 78143588734197260279248498898321500167517*I)/4835703278458516698824704, (-283186724922498212468162690097101115349 - 6443437753863179883794497936345437398276*I)/1208925819614629174706176, (188799118826748909206887165661384998787543 + 84274736720556630026311383931055307398820*I)/9671406556917033397649408, (-5482217151670072904078758141270295025989 + 1818284338672191024475557065444481298568*I)/1208925819614629174706176, (56564463395350195513805521309731217952281 - 360208541416798112109946262159695452898431*I)/19342813113834066795298816, 11*(1259539805728870739006416869463689438068 + 1409136581547898074455004171305324917387*I)/4835703278458516698824704, 5*(-123701190701414554945251071190688818343325 + 30997157322590424677294553832111902279712*I)/38685626227668133590597632, (16130917381301373033736295883982414239781 - 32752041297570919727145380131926943374516*I)/9671406556917033397649408, (650301385108223834347093740500375498354925 + 899526407681131828596801223402866051809258*I)/77371252455336267181195264],
# [ (9011388245256140876590294262420614839483 + 8167917972423946282513000869327525382672*I)/1208925819614629174706176, (-426393174084720190126376382194036323028924 + 180692224825757525982858693158209545430621*I)/9671406556917033397649408, (24588556702197802674765733448108154175535 - 45091766022876486566421953254051868331066*I)/4835703278458516698824704, (1872113939365285277373877183750416985089691 + 3030392393733212574744122057679633775773130*I)/77371252455336267181195264, (-222173405538046189185754954524429864167549 - 75193157893478637039381059488387511299116*I)/19342813113834066795298816, (2670821320766222522963689317316937579844558 - 2645837121493554383087981511645435472169191*I)/77371252455336267181195264, 5*(-2100110309556476773796963197283876204940 + 41957457246479840487980315496957337371937*I)/19342813113834066795298816, (-5733743755499084165382383818991531258980593 - 3328949988392698205198574824396695027195732*I)/154742504910672534362390528, (707827994365259025461378911159398206329247 - 265730616623227695108042528694302299777294*I)/77371252455336267181195264, (-1442501604682933002895864804409322823788319 + 11504137805563265043376405214378288793343879*I)/309485009821345068724781056, (-56130472299445561499538726459719629522285 - 61117552419727805035810982426639329818864*I)/9671406556917033397649408, (39053692321126079849054272431599539429908717 - 10209127700342570953247177602860848130710666*I)/1237940039285380274899124224]])
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
[ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
[ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
[ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
[ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M**10 == Matrix(S('''[
[ 7369525394972778926719607798014571861/604462909807314587353088 - 229284202061790301477392339912557559*I/151115727451828646838272, -19704281515163975949388435612632058035/1208925819614629174706176 + 14319858347987648723768698170712102887*I/302231454903657293676544, -3623281909451783042932142262164941211/604462909807314587353088 - 6039240602494288615094338643452320495*I/604462909807314587353088, 109260497799140408739847239685705357695/2417851639229258349412352 - 7427566006564572463236368211555511431*I/2417851639229258349412352, -16095803767674394244695716092817006641/2417851639229258349412352 + 10336681897356760057393429626719177583*I/1208925819614629174706176, -42207883340488041844332828574359769743/2417851639229258349412352 - 182332262671671273188016400290188468499*I/4835703278458516698824704],
[50566491050825573392726324995779608259/1208925819614629174706176 - 90047007594468146222002432884052362145*I/2417851639229258349412352, 74273703462900000967697427843983822011/1208925819614629174706176 + 265947522682943571171988741842776095421*I/1208925819614629174706176, -116900341394390200556829767923360888429/2417851639229258349412352 - 53153263356679268823910621474478756845*I/2417851639229258349412352, 195407378023867871243426523048612490249/1208925819614629174706176 - 1242417915995360200584837585002906728929*I/9671406556917033397649408, -863597594389821970177319682495878193/302231454903657293676544 + 476936100741548328800725360758734300481*I/9671406556917033397649408, -3154451590535653853562472176601754835575/19342813113834066795298816 - 232909875490506237386836489998407329215*I/2417851639229258349412352],
[ -1715444997702484578716037230949868543/302231454903657293676544 + 5009695651321306866158517287924120777*I/302231454903657293676544, -30551582497996879620371947949342101301/604462909807314587353088 - 7632518367986526187139161303331519629*I/151115727451828646838272, 312680739924495153190604170938220575/18889465931478580854784 - 108664334509328818765959789219208459*I/75557863725914323419136, -14693696966703036206178521686918865509/604462909807314587353088 + 72345386220900843930147151999899692401*I/1208925819614629174706176, -8218872496728882299722894680635296519/1208925819614629174706176 - 16776782833358893712645864791807664983*I/1208925819614629174706176, 143237839169380078671242929143670635137/2417851639229258349412352 + 2883817094806115974748882735218469447*I/2417851639229258349412352],
[ 3087979417831061365023111800749855987/151115727451828646838272 + 34441942370802869368851419102423997089*I/604462909807314587353088, -148309181940158040917731426845476175667/604462909807314587353088 - 263987151804109387844966835369350904919*I/9671406556917033397649408, 50259518594816377378747711930008883165/1208925819614629174706176 - 95713974916869240305450001443767979653*I/2417851639229258349412352, 153466447023875527996457943521467271119/2417851639229258349412352 + 517285524891117105834922278517084871349*I/2417851639229258349412352, -29184653615412989036678939366291205575/604462909807314587353088 - 27551322282526322041080173287022121083*I/1208925819614629174706176, 196404220110085511863671393922447671649/1208925819614629174706176 - 1204712019400186021982272049902206202145*I/9671406556917033397649408],
[ -2632581805949645784625606590600098779/151115727451828646838272 - 589957435912868015140272627522612771*I/37778931862957161709568, 26727850893953715274702844733506310247/302231454903657293676544 - 10825791956782128799168209600694020481*I/302231454903657293676544, -1036348763702366164044671908440791295/151115727451828646838272 + 3188624571414467767868303105288107375*I/151115727451828646838272, -36814959939970644875593411585393242449/604462909807314587353088 - 18457555789119782404850043842902832647*I/302231454903657293676544, 12454491297984637815063964572803058647/604462909807314587353088 - 340489532842249733975074349495329171*I/302231454903657293676544, -19547211751145597258386735573258916681/604462909807314587353088 + 87299583775782199663414539883938008933*I/1208925819614629174706176],
[ -40281994229560039213253423262678393183/604462909807314587353088 - 2939986850065527327299273003299736641*I/604462909807314587353088, 331940684638052085845743020267462794181/2417851639229258349412352 - 284574901963624403933361315517248458969*I/1208925819614629174706176, 6453843623051745485064693628073010961/302231454903657293676544 + 36062454107479732681350914931391590957*I/604462909807314587353088, -147665869053634695632880753646441962067/604462909807314587353088 - 305987938660447291246597544085345123927*I/9671406556917033397649408, 107821369195275772166593879711259469423/2417851639229258349412352 - 11645185518211204108659001435013326687*I/302231454903657293676544, 64121228424717666402009446088588091619/1208925819614629174706176 + 265557133337095047883844369272389762133*I/1208925819614629174706176]]'''))
def test_issue_17247_expression_blowup_5():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.charpoly('x') == PurePoly(x**6 + (-6 - 6*I)*x**5 + 36*I*x**4, x, domain='EX')
def test_issue_17247_expression_blowup_6():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.det('bareiss') == 0
def test_issue_17247_expression_blowup_7():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.det('berkowitz') == 0
def test_issue_17247_expression_blowup_8():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.det('lu') == 0
def test_issue_17247_expression_blowup_9():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.rref() == (Matrix([
[1, 0, -1, -2, -3, -4, -5, -6],
[0, 1, 2, 3, 4, 5, 6, 7],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]]), (0, 1))
def test_issue_17247_expression_blowup_10():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.cofactor(0, 0) == 0
def test_issue_17247_expression_blowup_11():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.cofactor_matrix() == Matrix(6, 6, [0]*36)
def test_issue_17247_expression_blowup_12():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.eigenvals() == {6: 1, 6*I: 1, 0: 4}
def test_issue_17247_expression_blowup_13():
M = Matrix([
[ 0, 1 - x, x + 1, 1 - x],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 1 - x],
[ 0, 0, 1 - x, 0]])
ev = M.eigenvects()
assert ev[0] == (0, 2, [Matrix([0, -1, 0, 1])])
assert ev[1][0] == x - sqrt(2)*(x - 1) + 1
assert ev[1][1] == 1
assert ev[1][2][0].expand(deep=False, numer=True) == Matrix([
[(-x + sqrt(2)*(x - 1) - 1)/(x - 1)],
[-4*x/(x**2 - 2*x + 1) + (x + 1)*(x - sqrt(2)*(x - 1) + 1)/(x**2 - 2*x + 1)],
[(-x + sqrt(2)*(x - 1) - 1)/(x - 1)],
[1]
])
assert ev[2][0] == x + sqrt(2)*(x - 1) + 1
assert ev[2][1] == 1
assert ev[2][2][0].expand(deep=False, numer=True) == Matrix([
[(-x - sqrt(2)*(x - 1) - 1)/(x - 1)],
[-4*x/(x**2 - 2*x + 1) + (x + 1)*(x + sqrt(2)*(x - 1) + 1)/(x**2 - 2*x + 1)],
[(-x - sqrt(2)*(x - 1) - 1)/(x - 1)],
[1]
])
def test_issue_17247_expression_blowup_14():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
with dotprodsimp(True):
assert M.echelon_form() == Matrix([
[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x],
[ 0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0]])
def test_issue_17247_expression_blowup_15():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
with dotprodsimp(True):
assert M.rowspace() == [Matrix([[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x]]), Matrix([[0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x]])]
def test_issue_17247_expression_blowup_16():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
with dotprodsimp(True):
assert M.columnspace() == [Matrix([[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x]]), Matrix([[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1]])]
def test_issue_17247_expression_blowup_17():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.nullspace() == [
Matrix([[1],[-2],[1],[0],[0],[0],[0],[0]]),
Matrix([[2],[-3],[0],[1],[0],[0],[0],[0]]),
Matrix([[3],[-4],[0],[0],[1],[0],[0],[0]]),
Matrix([[4],[-5],[0],[0],[0],[1],[0],[0]]),
Matrix([[5],[-6],[0],[0],[0],[0],[1],[0]]),
Matrix([[6],[-7],[0],[0],[0],[0],[0],[1]])]
def test_issue_17247_expression_blowup_18():
M = Matrix(6, 6, ([1+x, 1-x]*3 + [1-x, 1+x]*3)*3)
with dotprodsimp(True):
assert not M.is_nilpotent()
def test_issue_17247_expression_blowup_19():
M = Matrix(S('''[
[ -3/4, 0, 1/4 + I/2, 0],
[ 0, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 1/2 - I, 0, 0, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert not M.is_diagonalizable()
def test_issue_17247_expression_blowup_20():
M = Matrix([
[x + 1, 1 - x, 0, 0],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 0],
[ 0, 0, 0, x + 1]])
with dotprodsimp(True):
assert M.diagonalize() == (Matrix([
[1, 1, 0, (x + 1)/(x - 1)],
[1, -1, 0, 0],
[1, 1, 1, 0],
[0, 0, 0, 1]]),
Matrix([
[2, 0, 0, 0],
[0, 2*x, 0, 0],
[0, 0, x + 1, 0],
[0, 0, 0, x + 1]]))
def test_issue_17247_expression_blowup_21():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='GE') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_22():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='LU') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_23():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='ADJ').expand() == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_24():
M = SparseMatrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='CH') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_25():
M = SparseMatrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='LDL') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_26():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024],
[ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
[ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
[ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
[ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
[ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
[ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.rank() == 4
def test_issue_17247_expression_blowup_27():
M = Matrix([
[ 0, 1 - x, x + 1, 1 - x],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 1 - x],
[ 0, 0, 1 - x, 0]])
with dotprodsimp(True):
P, J = M.jordan_form()
assert P.expand() == Matrix(S('''[
[ 0, 4*x/(x**2 - 2*x + 1), -(-17*x**4 + 12*sqrt(2)*x**4 - 4*sqrt(2)*x**3 + 6*x**3 - 6*x - 4*sqrt(2)*x + 12*sqrt(2) + 17)/(-7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 + 8*x**3 - 2*x**2 + 8*x + 6*sqrt(2)*x - 5*sqrt(2) - 7), -(12*sqrt(2)*x**4 + 17*x**4 - 6*x**3 - 4*sqrt(2)*x**3 - 4*sqrt(2)*x + 6*x - 17 + 12*sqrt(2))/(7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 - 8*x**3 + 2*x**2 - 8*x + 6*sqrt(2)*x - 5*sqrt(2) + 7)],
[x - 1, x/(x - 1) + 1/(x - 1), (-7*x**3 + 5*sqrt(2)*x**3 - x**2 + sqrt(2)*x**2 - sqrt(2)*x - x - 5*sqrt(2) - 7)/(-3*x**3 + 2*sqrt(2)*x**3 - 2*sqrt(2)*x**2 + 3*x**2 + 2*sqrt(2)*x + 3*x - 3 - 2*sqrt(2)), (7*x**3 + 5*sqrt(2)*x**3 + x**2 + sqrt(2)*x**2 - sqrt(2)*x + x - 5*sqrt(2) + 7)/(2*sqrt(2)*x**3 + 3*x**3 - 3*x**2 - 2*sqrt(2)*x**2 - 3*x + 2*sqrt(2)*x - 2*sqrt(2) + 3)],
[ 0, 1, -(-3*x**2 + 2*sqrt(2)*x**2 + 2*x - 3 - 2*sqrt(2))/(-x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x + 1 + sqrt(2)), -(2*sqrt(2)*x**2 + 3*x**2 - 2*x - 2*sqrt(2) + 3)/(x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x - 1 + sqrt(2))],
[1 - x, 0, 1, 1]]''')).expand()
assert J == Matrix(S('''[
[0, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, x - sqrt(2)*(x - 1) + 1, 0],
[0, 0, 0, x + sqrt(2)*(x - 1) + 1]]'''))
def test_issue_17247_expression_blowup_28():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.singular_values() == S('''[
sqrt(14609315/131072 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2),
sqrt(14609315/131072 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2),
sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2),
sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2)]''')
def test_issue_16823():
# This still needs to be fixed if not using dotprodsimp.
M = Matrix(S('''[
[1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I,15/128-3/32*I,19/256+551/1024*I],
[21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I,129/256-549/512*I,42533/16384+29103/8192*I],
[-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I],
[1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I],
[-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I],
[1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I],
[-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I],
[-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I],
[0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I],
[1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I],
[0,-4*I,0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I],
[0,1/4+1/2*I,1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I]]'''))
with dotprodsimp(True):
assert M.rank() == 8
def test_issue_18531():
# solve_linear_system still needs fixing but the rref works.
M = Matrix([
[1, 1, 1, 1, 1, 0, 1, 0, 0],
[1 + sqrt(2), -1 + sqrt(2), 1 - sqrt(2), -sqrt(2) - 1, 1, 1, -1, 1, 1],
[-5 + 2*sqrt(2), -5 - 2*sqrt(2), -5 - 2*sqrt(2), -5 + 2*sqrt(2), -7, 2, -7, -2, 0],
[-3*sqrt(2) - 1, 1 - 3*sqrt(2), -1 + 3*sqrt(2), 1 + 3*sqrt(2), -7, -5, 7, -5, 3],
[7 - 4*sqrt(2), 4*sqrt(2) + 7, 4*sqrt(2) + 7, 7 - 4*sqrt(2), 7, -12, 7, 12, 0],
[-1 + 3*sqrt(2), 1 + 3*sqrt(2), -3*sqrt(2) - 1, 1 - 3*sqrt(2), 7, -5, -7, -5, 3],
[-3 + 2*sqrt(2), -3 - 2*sqrt(2), -3 - 2*sqrt(2), -3 + 2*sqrt(2), -1, 2, -1, -2, 0],
[1 - sqrt(2), -sqrt(2) - 1, 1 + sqrt(2), -1 + sqrt(2), -1, 1, 1, 1, 1]
])
with dotprodsimp(True):
assert M.rref() == (Matrix([
[1, 0, 0, 0, 0, 0, 0, 0, S(1)/2],
[0, 1, 0, 0, 0, 0, 0, 0, -S(1)/2],
[0, 0, 1, 0, 0, 0, 0, 0, S(1)/2],
[0, 0, 0, 1, 0, 0, 0, 0, -S(1)/2],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, -S(1)/2],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, -S(1)/2]]), (0, 1, 2, 3, 4, 5, 6, 7))
def test_creation():
raises(ValueError, lambda: Matrix(5, 5, range(20)))
raises(ValueError, lambda: Matrix(5, -1, []))
raises(IndexError, lambda: Matrix((1, 2))[2])
with raises(IndexError):
Matrix((1, 2))[3] = 5
assert Matrix() == Matrix([]) == Matrix([[]]) == Matrix(0, 0, [])
# anything used to be allowed in a matrix
with warns_deprecated_sympy():
assert Matrix([[[1], (2,)]]).tolist() == [[[1], (2,)]]
with warns_deprecated_sympy():
assert Matrix([[[1], (2,)]]).T.tolist() == [[[1]], [(2,)]]
M = Matrix([[0]])
with warns_deprecated_sympy():
M[0, 0] = S.EmptySet
a = Matrix([[x, 0], [0, 0]])
m = a
assert m.cols == m.rows
assert m.cols == 2
assert m[:] == [x, 0, 0, 0]
b = Matrix(2, 2, [x, 0, 0, 0])
m = b
assert m.cols == m.rows
assert m.cols == 2
assert m[:] == [x, 0, 0, 0]
assert a == b
assert Matrix(b) == b
c23 = Matrix(2, 3, range(1, 7))
c13 = Matrix(1, 3, range(7, 10))
c = Matrix([c23, c13])
assert c.cols == 3
assert c.rows == 3
assert c[:] == [1, 2, 3, 4, 5, 6, 7, 8, 9]
assert Matrix(eye(2)) == eye(2)
assert ImmutableMatrix(ImmutableMatrix(eye(2))) == ImmutableMatrix(eye(2))
assert ImmutableMatrix(c) == c.as_immutable()
assert Matrix(ImmutableMatrix(c)) == ImmutableMatrix(c).as_mutable()
assert c is not Matrix(c)
dat = [[ones(3,2), ones(3,3)*2], [ones(2,3)*3, ones(2,2)*4]]
M = Matrix(dat)
assert M == Matrix([
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[3, 3, 3, 4, 4],
[3, 3, 3, 4, 4]])
assert M.tolist() != dat
# keep block form if evaluate=False
assert Matrix(dat, evaluate=False).tolist() == dat
A = MatrixSymbol("A", 2, 2)
dat = [ones(2), A]
assert Matrix(dat) == Matrix([
[ 1, 1],
[ 1, 1],
[A[0, 0], A[0, 1]],
[A[1, 0], A[1, 1]]])
with warns_deprecated_sympy():
assert Matrix(dat, evaluate=False).tolist() == [[i] for i in dat]
# 0-dim tolerance
assert Matrix([ones(2), ones(0)]) == Matrix([ones(2)])
raises(ValueError, lambda: Matrix([ones(2), ones(0, 3)]))
raises(ValueError, lambda: Matrix([ones(2), ones(3, 0)]))
# mix of Matrix and iterable
M = Matrix([[1, 2], [3, 4]])
M2 = Matrix([M, (5, 6)])
assert M2 == Matrix([[1, 2], [3, 4], [5, 6]])
def test_irregular_block():
assert Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3,
ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7) == Matrix([
[1, 2, 2, 2, 3, 3],
[1, 2, 2, 2, 3, 3],
[4, 2, 2, 2, 5, 5],
[6, 6, 7, 7, 5, 5]])
def test_tolist():
lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]]
m = Matrix(lst)
assert m.tolist() == lst
def test_as_mutable():
assert zeros(0, 3).as_mutable() == zeros(0, 3)
assert zeros(0, 3).as_immutable() == ImmutableMatrix(zeros(0, 3))
assert zeros(3, 0).as_immutable() == ImmutableMatrix(zeros(3, 0))
def test_slicing():
m0 = eye(4)
assert m0[:3, :3] == eye(3)
assert m0[2:4, 0:2] == zeros(2)
m1 = Matrix(3, 3, lambda i, j: i + j)
assert m1[0, :] == Matrix(1, 3, (0, 1, 2))
assert m1[1:3, 1] == Matrix(2, 1, (2, 3))
m2 = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
assert m2[:, -1] == Matrix(4, 1, [3, 7, 11, 15])
assert m2[-2:, :] == Matrix([[8, 9, 10, 11], [12, 13, 14, 15]])
def test_submatrix_assignment():
m = zeros(4)
m[2:4, 2:4] = eye(2)
assert m == Matrix(((0, 0, 0, 0),
(0, 0, 0, 0),
(0, 0, 1, 0),
(0, 0, 0, 1)))
m[:2, :2] = eye(2)
assert m == eye(4)
m[:, 0] = Matrix(4, 1, (1, 2, 3, 4))
assert m == Matrix(((1, 0, 0, 0),
(2, 1, 0, 0),
(3, 0, 1, 0),
(4, 0, 0, 1)))
m[:, :] = zeros(4)
assert m == zeros(4)
m[:, :] = [(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)]
assert m == Matrix(((1, 2, 3, 4),
(5, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 16)))
m[:2, 0] = [0, 0]
assert m == Matrix(((0, 2, 3, 4),
(0, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 16)))
def test_extract():
m = Matrix(4, 3, lambda i, j: i*3 + j)
assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10])
assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11])
assert m.extract(range(4), range(3)) == m
raises(IndexError, lambda: m.extract([4], [0]))
raises(IndexError, lambda: m.extract([0], [3]))
def test_reshape():
m0 = eye(3)
assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
m1 = Matrix(3, 4, lambda i, j: i + j)
assert m1.reshape(
4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)))
assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)))
def test_applyfunc():
m0 = eye(3)
assert m0.applyfunc(lambda x: 2*x) == eye(3)*2
assert m0.applyfunc(lambda x: 0) == zeros(3)
def test_expand():
m0 = Matrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]])
# Test if expand() returns a matrix
m1 = m0.expand()
assert m1 == Matrix(
[[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]])
a = Symbol('a', real=True)
assert Matrix([exp(I*a)]).expand(complex=True) == \
Matrix([cos(a) + I*sin(a)])
assert Matrix([[0, 1, 2], [0, 0, -1], [0, 0, 0]]).exp() == Matrix([
[1, 1, Rational(3, 2)],
[0, 1, -1],
[0, 0, 1]]
)
def test_refine():
m0 = Matrix([[Abs(x)**2, sqrt(x**2)],
[sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]])
m1 = m0.refine(Q.real(x) & Q.real(y))
assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]])
m1 = m0.refine(Q.positive(x) & Q.positive(y))
assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]])
m1 = m0.refine(Q.negative(x) & Q.negative(y))
assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]])
def test_random():
M = randMatrix(3, 3)
M = randMatrix(3, 3, seed=3)
assert M == randMatrix(3, 3, seed=3)
M = randMatrix(3, 4, 0, 150)
M = randMatrix(3, seed=4, symmetric=True)
assert M == randMatrix(3, seed=4, symmetric=True)
S = M.copy()
S.simplify()
assert S == M # doesn't fail when elements are Numbers, not int
rng = random.Random(4)
assert M == randMatrix(3, symmetric=True, prng=rng)
# Ensure symmetry
for size in (10, 11): # Test odd and even
for percent in (100, 70, 30):
M = randMatrix(size, symmetric=True, percent=percent, prng=rng)
assert M == M.T
M = randMatrix(10, min=1, percent=70)
zero_count = 0
for i in range(M.shape[0]):
for j in range(M.shape[1]):
if M[i, j] == 0:
zero_count += 1
assert zero_count == 30
def test_inverse():
A = eye(4)
assert A.inv() == eye(4)
assert A.inv(method="LU") == eye(4)
assert A.inv(method="ADJ") == eye(4)
assert A.inv(method="CH") == eye(4)
assert A.inv(method="LDL") == eye(4)
assert A.inv(method="QR") == eye(4)
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
Ainv = A.inv()
assert A*Ainv == eye(3)
assert A.inv(method="LU") == Ainv
assert A.inv(method="ADJ") == Ainv
assert A.inv(method="CH") == Ainv
assert A.inv(method="LDL") == Ainv
assert A.inv(method="QR") == Ainv
AA = Matrix([[0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
[1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0],
[1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],
[1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1],
[0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0],
[1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1],
[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0],
[1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1],
[1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0],
[1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1],
[0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1],
[1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0]])
assert AA.inv(method="BLOCK") * AA == eye(AA.shape[0])
# test that immutability is not a problem
cls = ImmutableMatrix
m = cls([[48, 49, 31],
[ 9, 71, 94],
[59, 28, 65]])
assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split())
cls = ImmutableSparseMatrix
m = cls([[48, 49, 31],
[ 9, 71, 94],
[59, 28, 65]])
assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split())
def test_matrix_inverse_mod():
A = Matrix(2, 1, [1, 0])
raises(NonSquareMatrixError, lambda: A.inv_mod(2))
A = Matrix(2, 2, [1, 0, 0, 0])
raises(ValueError, lambda: A.inv_mod(2))
A = Matrix(2, 2, [1, 2, 3, 4])
Ai = Matrix(2, 2, [1, 1, 0, 1])
assert A.inv_mod(3) == Ai
A = Matrix(2, 2, [1, 0, 0, 1])
assert A.inv_mod(2) == A
A = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
raises(ValueError, lambda: A.inv_mod(5))
A = Matrix(3, 3, [5, 1, 3, 2, 6, 0, 2, 1, 1])
Ai = Matrix(3, 3, [6, 8, 0, 1, 5, 6, 5, 6, 4])
assert A.inv_mod(9) == Ai
A = Matrix(3, 3, [1, 6, -3, 4, 1, -5, 3, -5, 5])
Ai = Matrix(3, 3, [4, 3, 3, 1, 2, 5, 1, 5, 1])
assert A.inv_mod(6) == Ai
A = Matrix(3, 3, [1, 6, 1, 4, 1, 5, 3, 2, 5])
Ai = Matrix(3, 3, [6, 0, 3, 6, 6, 4, 1, 6, 1])
assert A.inv_mod(7) == Ai
def test_jacobian_hessian():
L = Matrix(1, 2, [x**2*y, 2*y**2 + x*y])
syms = [x, y]
assert L.jacobian(syms) == Matrix([[2*x*y, x**2], [y, 4*y + x]])
L = Matrix(1, 2, [x, x**2*y**3])
assert L.jacobian(syms) == Matrix([[1, 0], [2*x*y**3, x**2*3*y**2]])
f = x**2*y
syms = [x, y]
assert hessian(f, syms) == Matrix([[2*y, 2*x], [2*x, 0]])
f = x**2*y**3
assert hessian(f, syms) == \
Matrix([[2*y**3, 6*x*y**2], [6*x*y**2, 6*x**2*y]])
f = z + x*y**2
g = x**2 + 2*y**3
ans = Matrix([[0, 2*y],
[2*y, 2*x]])
assert ans == hessian(f, Matrix([x, y]))
assert ans == hessian(f, Matrix([x, y]).T)
assert hessian(f, (y, x), [g]) == Matrix([
[ 0, 6*y**2, 2*x],
[6*y**2, 2*x, 2*y],
[ 2*x, 2*y, 0]])
def test_wronskian():
assert wronskian([cos(x), sin(x)], x) == cos(x)**2 + sin(x)**2
assert wronskian([exp(x), exp(2*x)], x) == exp(3*x)
assert wronskian([exp(x), x], x) == exp(x) - x*exp(x)
assert wronskian([1, x, x**2], x) == 2
w1 = -6*exp(x)*sin(x)*x + 6*cos(x)*exp(x)*x**2 - 6*exp(x)*cos(x)*x - \
exp(x)*cos(x)*x**3 + exp(x)*sin(x)*x**3
assert wronskian([exp(x), cos(x), x**3], x).expand() == w1
assert wronskian([exp(x), cos(x), x**3], x, method='berkowitz').expand() \
== w1
w2 = -x**3*cos(x)**2 - x**3*sin(x)**2 - 6*x*cos(x)**2 - 6*x*sin(x)**2
assert wronskian([sin(x), cos(x), x**3], x).expand() == w2
assert wronskian([sin(x), cos(x), x**3], x, method='berkowitz').expand() \
== w2
assert wronskian([], x) == 1
def test_subs():
assert Matrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([x*y]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \
Matrix([(x - 1)*(y - 1)])
for cls in classes:
assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).subs(1, 2)
def test_xreplace():
assert Matrix([[1, x], [x, 4]]).xreplace({x: 5}) == \
Matrix([[1, 5], [5, 4]])
assert Matrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
for cls in classes:
assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).xreplace({1: 2})
def test_simplify():
n = Symbol('n')
f = Function('f')
M = Matrix([[ 1/x + 1/y, (x + x*y) / x ],
[ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]])
M.simplify()
assert M == Matrix([[ (x + y)/(x * y), 1 + y ],
[ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]])
eq = (1 + x)**2
M = Matrix([[eq]])
M.simplify()
assert M == Matrix([[eq]])
M.simplify(ratio=oo)
assert M == Matrix([[eq.simplify(ratio=oo)]])
def test_transpose():
M = Matrix([[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]])
assert M.T == Matrix( [ [1, 1],
[2, 2],
[3, 3],
[4, 4],
[5, 5],
[6, 6],
[7, 7],
[8, 8],
[9, 9],
[0, 0] ])
assert M.T.T == M
assert M.T == M.transpose()
def test_conjugate():
M = Matrix([[0, I, 5],
[1, 2, 0]])
assert M.T == Matrix([[0, 1],
[I, 2],
[5, 0]])
assert M.C == Matrix([[0, -I, 5],
[1, 2, 0]])
assert M.C == M.conjugate()
assert M.H == M.T.C
assert M.H == Matrix([[ 0, 1],
[-I, 2],
[ 5, 0]])
def test_conj_dirac():
raises(AttributeError, lambda: eye(3).D)
M = Matrix([[1, I, I, I],
[0, 1, I, I],
[0, 0, 1, I],
[0, 0, 0, 1]])
assert M.D == Matrix([[ 1, 0, 0, 0],
[-I, 1, 0, 0],
[-I, -I, -1, 0],
[-I, -I, I, -1]])
def test_trace():
M = Matrix([[1, 0, 0],
[0, 5, 0],
[0, 0, 8]])
assert M.trace() == 14
def test_shape():
M = Matrix([[x, 0, 0],
[0, y, 0]])
assert M.shape == (2, 3)
def test_col_row_op():
M = Matrix([[x, 0, 0],
[0, y, 0]])
M.row_op(1, lambda r, j: r + j + 1)
assert M == Matrix([[x, 0, 0],
[1, y + 2, 3]])
M.col_op(0, lambda c, j: c + y**j)
assert M == Matrix([[x + 1, 0, 0],
[1 + y, y + 2, 3]])
# neither row nor slice give copies that allow the original matrix to
# be changed
assert M.row(0) == Matrix([[x + 1, 0, 0]])
r1 = M.row(0)
r1[0] = 42
assert M[0, 0] == x + 1
r1 = M[0, :-1] # also testing negative slice
r1[0] = 42
assert M[0, 0] == x + 1
c1 = M.col(0)
assert c1 == Matrix([x + 1, 1 + y])
c1[0] = 0
assert M[0, 0] == x + 1
c1 = M[:, 0]
c1[0] = 42
assert M[0, 0] == x + 1
def test_zip_row_op():
for cls in classes[:2]: # XXX: immutable matrices don't support row ops
M = cls.eye(3)
M.zip_row_op(1, 0, lambda v, u: v + 2*u)
assert M == cls([[1, 0, 0],
[2, 1, 0],
[0, 0, 1]])
M = cls.eye(3)*2
M[0, 1] = -1
M.zip_row_op(1, 0, lambda v, u: v + 2*u); M
assert M == cls([[2, -1, 0],
[4, 0, 0],
[0, 0, 2]])
def test_issue_3950():
m = Matrix([1, 2, 3])
a = Matrix([1, 2, 3])
b = Matrix([2, 2, 3])
assert not (m in [])
assert not (m in [1])
assert m != 1
assert m == a
assert m != b
def test_issue_3981():
class Index1:
def __index__(self):
return 1
class Index2:
def __index__(self):
return 2
index1 = Index1()
index2 = Index2()
m = Matrix([1, 2, 3])
assert m[index2] == 3
m[index2] = 5
assert m[2] == 5
m = Matrix([[1, 2, 3], [4, 5, 6]])
assert m[index1, index2] == 6
assert m[1, index2] == 6
assert m[index1, 2] == 6
m[index1, index2] = 4
assert m[1, 2] == 4
m[1, index2] = 6
assert m[1, 2] == 6
m[index1, 2] = 8
assert m[1, 2] == 8
def test_evalf():
a = Matrix([sqrt(5), 6])
assert all(a.evalf()[i] == a[i].evalf() for i in range(2))
assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2))
assert all(a.n(2)[i] == a[i].n(2) for i in range(2))
def test_is_symbolic():
a = Matrix([[x, x], [x, x]])
assert a.is_symbolic() is True
a = Matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
assert a.is_symbolic() is False
a = Matrix([[1, 2, 3, 4], [5, 6, x, 8]])
assert a.is_symbolic() is True
a = Matrix([[1, x, 3]])
assert a.is_symbolic() is True
a = Matrix([[1, 2, 3]])
assert a.is_symbolic() is False
a = Matrix([[1], [x], [3]])
assert a.is_symbolic() is True
a = Matrix([[1], [2], [3]])
assert a.is_symbolic() is False
def test_is_upper():
a = Matrix([[1, 2, 3]])
assert a.is_upper is True
a = Matrix([[1], [2], [3]])
assert a.is_upper is False
a = zeros(4, 2)
assert a.is_upper is True
def test_is_lower():
a = Matrix([[1, 2, 3]])
assert a.is_lower is False
a = Matrix([[1], [2], [3]])
assert a.is_lower is True
def test_is_nilpotent():
a = Matrix(4, 4, [0, 2, 1, 6, 0, 0, 1, 2, 0, 0, 0, 3, 0, 0, 0, 0])
assert a.is_nilpotent()
a = Matrix([[1, 0], [0, 1]])
assert not a.is_nilpotent()
a = Matrix([])
assert a.is_nilpotent()
def test_zeros_ones_fill():
n, m = 3, 5
a = zeros(n, m)
a.fill( 5 )
b = 5 * ones(n, m)
assert a == b
assert a.rows == b.rows == 3
assert a.cols == b.cols == 5
assert a.shape == b.shape == (3, 5)
assert zeros(2) == zeros(2, 2)
assert ones(2) == ones(2, 2)
assert zeros(2, 3) == Matrix(2, 3, [0]*6)
assert ones(2, 3) == Matrix(2, 3, [1]*6)
a.fill(0)
assert a == zeros(n, m)
def test_empty_zeros():
a = zeros(0)
assert a == Matrix()
a = zeros(0, 2)
assert a.rows == 0
assert a.cols == 2
a = zeros(2, 0)
assert a.rows == 2
assert a.cols == 0
def test_issue_3749():
a = Matrix([[x**2, x*y], [x*sin(y), x*cos(y)]])
assert a.diff(x) == Matrix([[2*x, y], [sin(y), cos(y)]])
assert Matrix([
[x, -x, x**2],
[exp(x), 1/x - exp(-x), x + 1/x]]).limit(x, oo) == \
Matrix([[oo, -oo, oo], [oo, 0, oo]])
assert Matrix([
[(exp(x) - 1)/x, 2*x + y*x, x**x ],
[1/x, abs(x), abs(sin(x + 1))]]).limit(x, 0) == \
Matrix([[1, 0, 1], [oo, 0, sin(1)]])
assert a.integrate(x) == Matrix([
[Rational(1, 3)*x**3, y*x**2/2],
[x**2*sin(y)/2, x**2*cos(y)/2]])
def test_inv_iszerofunc():
A = eye(4)
A.col_swap(0, 1)
for method in "GE", "LU":
assert A.inv(method=method, iszerofunc=lambda x: x == 0) == \
A.inv(method="ADJ")
def test_jacobian_metrics():
rho, phi = symbols("rho,phi")
X = Matrix([rho*cos(phi), rho*sin(phi)])
Y = Matrix([rho, phi])
J = X.jacobian(Y)
assert J == X.jacobian(Y.T)
assert J == (X.T).jacobian(Y)
assert J == (X.T).jacobian(Y.T)
g = J.T*eye(J.shape[0])*J
g = g.applyfunc(trigsimp)
assert g == Matrix([[1, 0], [0, rho**2]])
def test_jacobian2():
rho, phi = symbols("rho,phi")
X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
Y = Matrix([rho, phi])
J = Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi), rho*cos(phi)],
[ 2*rho, 0],
])
assert X.jacobian(Y) == J
def test_issue_4564():
X = Matrix([exp(x + y + z), exp(x + y + z), exp(x + y + z)])
Y = Matrix([x, y, z])
for i in range(1, 3):
for j in range(1, 3):
X_slice = X[:i, :]
Y_slice = Y[:j, :]
J = X_slice.jacobian(Y_slice)
assert J.rows == i
assert J.cols == j
for k in range(j):
assert J[:, k] == X_slice
def test_nonvectorJacobian():
X = Matrix([[exp(x + y + z), exp(x + y + z)],
[exp(x + y + z), exp(x + y + z)]])
raises(TypeError, lambda: X.jacobian(Matrix([x, y, z])))
X = X[0, :]
Y = Matrix([[x, y], [x, z]])
raises(TypeError, lambda: X.jacobian(Y))
raises(TypeError, lambda: X.jacobian(Matrix([ [x, y], [x, z] ])))
def test_vec():
m = Matrix([[1, 3], [2, 4]])
m_vec = m.vec()
assert m_vec.cols == 1
for i in range(4):
assert m_vec[i] == i + 1
def test_vech():
m = Matrix([[1, 2], [2, 3]])
m_vech = m.vech()
assert m_vech.cols == 1
for i in range(3):
assert m_vech[i] == i + 1
m_vech = m.vech(diagonal=False)
assert m_vech[0] == 2
m = Matrix([[1, x*(x + y)], [y*x + x**2, 1]])
m_vech = m.vech(diagonal=False)
assert m_vech[0] == y*x + x**2
m = Matrix([[1, x*(x + y)], [y*x, 1]])
m_vech = m.vech(diagonal=False, check_symmetry=False)
assert m_vech[0] == y*x
raises(ShapeError, lambda: Matrix([[1, 3]]).vech())
raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech())
raises(ShapeError, lambda: Matrix([[1, 3]]).vech())
raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech())
def test_diag():
# mostly tested in testcommonmatrix.py
assert diag([1, 2, 3]) == Matrix([1, 2, 3])
m = [1, 2, [3]]
raises(ValueError, lambda: diag(m))
assert diag(m, strict=False) == Matrix([1, 2, 3])
def test_get_diag_blocks1():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert a.get_diag_blocks() == [a]
assert b.get_diag_blocks() == [b]
assert c.get_diag_blocks() == [c]
def test_get_diag_blocks2():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert diag(a, b, b).get_diag_blocks() == [a, b, b]
assert diag(a, b, c).get_diag_blocks() == [a, b, c]
assert diag(a, c, b).get_diag_blocks() == [a, c, b]
assert diag(c, c, b).get_diag_blocks() == [c, c, b]
def test_inv_block():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
A = diag(a, b, b)
assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), b.inv())
A = diag(a, b, c)
assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), c.inv())
A = diag(a, c, b)
assert A.inv(try_block_diag=True) == diag(a.inv(), c.inv(), b.inv())
A = diag(a, a, b, a, c, a)
assert A.inv(try_block_diag=True) == diag(
a.inv(), a.inv(), b.inv(), a.inv(), c.inv(), a.inv())
assert A.inv(try_block_diag=True, method="ADJ") == diag(
a.inv(method="ADJ"), a.inv(method="ADJ"), b.inv(method="ADJ"),
a.inv(method="ADJ"), c.inv(method="ADJ"), a.inv(method="ADJ"))
def test_creation_args():
"""
Check that matrix dimensions can be specified using any reasonable type
(see issue 4614).
"""
raises(ValueError, lambda: zeros(3, -1))
raises(TypeError, lambda: zeros(1, 2, 3, 4))
assert zeros(int(3)) == zeros(3)
assert zeros(Integer(3)) == zeros(3)
raises(ValueError, lambda: zeros(3.))
assert eye(int(3)) == eye(3)
assert eye(Integer(3)) == eye(3)
raises(ValueError, lambda: eye(3.))
assert ones(int(3), Integer(4)) == ones(3, 4)
raises(TypeError, lambda: Matrix(5))
raises(TypeError, lambda: Matrix(1, 2))
raises(ValueError, lambda: Matrix([1, [2]]))
def test_diagonal_symmetrical():
m = Matrix(2, 2, [0, 1, 1, 0])
assert not m.is_diagonal()
assert m.is_symmetric()
assert m.is_symmetric(simplify=False)
m = Matrix(2, 2, [1, 0, 0, 1])
assert m.is_diagonal()
m = diag(1, 2, 3)
assert m.is_diagonal()
assert m.is_symmetric()
m = Matrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3])
assert m == diag(1, 2, 3)
m = Matrix(2, 3, zeros(2, 3))
assert not m.is_symmetric()
assert m.is_diagonal()
m = Matrix(((5, 0), (0, 6), (0, 0)))
assert m.is_diagonal()
m = Matrix(((5, 0, 0), (0, 6, 0)))
assert m.is_diagonal()
m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
assert m.is_symmetric()
assert not m.is_symmetric(simplify=False)
assert m.expand().is_symmetric(simplify=False)
def test_diagonalization():
m = Matrix([[1, 2+I], [2-I, 3]])
assert m.is_diagonalizable()
m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
assert not m.is_diagonalizable()
assert not m.is_symmetric()
raises(NonSquareMatrixError, lambda: m.diagonalize())
# diagonalizable
m = diag(1, 2, 3)
(P, D) = m.diagonalize()
assert P == eye(3)
assert D == m
m = Matrix(2, 2, [0, 1, 1, 0])
assert m.is_symmetric()
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
m = Matrix(2, 2, [1, 0, 0, 3])
assert m.is_symmetric()
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
assert P == eye(2)
assert D == m
m = Matrix(2, 2, [1, 1, 0, 0])
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
for i in P:
assert i.as_numer_denom()[1] == 1
m = Matrix(2, 2, [1, 0, 0, 0])
assert m.is_diagonal()
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
assert P == Matrix([[0, 1], [1, 0]])
# diagonalizable, complex only
m = Matrix(2, 2, [0, 1, -1, 0])
assert not m.is_diagonalizable(True)
raises(MatrixError, lambda: m.diagonalize(True))
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
# not diagonalizable
m = Matrix(2, 2, [0, 1, 0, 0])
assert not m.is_diagonalizable()
raises(MatrixError, lambda: m.diagonalize())
m = Matrix(3, 3, [-3, 1, -3, 20, 3, 10, 2, -2, 4])
assert not m.is_diagonalizable()
raises(MatrixError, lambda: m.diagonalize())
# symbolic
a, b, c, d = symbols('a b c d')
m = Matrix(2, 2, [a, c, c, b])
assert m.is_symmetric()
assert m.is_diagonalizable()
def test_issue_15887():
# Mutable matrix should not use cache
a = MutableDenseMatrix([[0, 1], [1, 0]])
assert a.is_diagonalizable() is True
a[1, 0] = 0
assert a.is_diagonalizable() is False
a = MutableDenseMatrix([[0, 1], [1, 0]])
a.diagonalize()
a[1, 0] = 0
raises(MatrixError, lambda: a.diagonalize())
def test_jordan_form():
m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
raises(NonSquareMatrixError, lambda: m.jordan_form())
# diagonalizable
m = Matrix(3, 3, [7, -12, 6, 10, -19, 10, 12, -24, 13])
Jmust = Matrix(3, 3, [-1, 0, 0, 0, 1, 0, 0, 0, 1])
P, J = m.jordan_form()
assert Jmust == J
assert Jmust == m.diagonalize()[1]
# m = Matrix(3, 3, [0, 6, 3, 1, 3, 1, -2, 2, 1])
# m.jordan_form() # very long
# m.jordan_form() #
# diagonalizable, complex only
# Jordan cells
# complexity: one of eigenvalues is zero
m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2])
# The blocks are ordered according to the value of their eigenvalues,
# in order to make the matrix compatible with .diagonalize()
Jmust = Matrix(3, 3, [2, 1, 0, 0, 2, 0, 0, 0, 2])
P, J = m.jordan_form()
assert Jmust == J
# complexity: all of eigenvalues are equal
m = Matrix(3, 3, [2, 6, -15, 1, 1, -5, 1, 2, -6])
# Jmust = Matrix(3, 3, [-1, 0, 0, 0, -1, 1, 0, 0, -1])
# same here see 1456ff
Jmust = Matrix(3, 3, [-1, 1, 0, 0, -1, 0, 0, 0, -1])
P, J = m.jordan_form()
assert Jmust == J
# complexity: two of eigenvalues are zero
m = Matrix(3, 3, [4, -5, 2, 5, -7, 3, 6, -9, 4])
Jmust = Matrix(3, 3, [0, 1, 0, 0, 0, 0, 0, 0, 1])
P, J = m.jordan_form()
assert Jmust == J
m = Matrix(4, 4, [6, 5, -2, -3, -3, -1, 3, 3, 2, 1, -2, -3, -1, 1, 5, 5])
Jmust = Matrix(4, 4, [2, 1, 0, 0,
0, 2, 0, 0,
0, 0, 2, 1,
0, 0, 0, 2]
)
P, J = m.jordan_form()
assert Jmust == J
m = Matrix(4, 4, [6, 2, -8, -6, -3, 2, 9, 6, 2, -2, -8, -6, -1, 0, 3, 4])
# Jmust = Matrix(4, 4, [2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, -2])
# same here see 1456ff
Jmust = Matrix(4, 4, [-2, 0, 0, 0,
0, 2, 1, 0,
0, 0, 2, 0,
0, 0, 0, 2])
P, J = m.jordan_form()
assert Jmust == J
m = Matrix(4, 4, [5, 4, 2, 1, 0, 1, -1, -1, -1, -1, 3, 0, 1, 1, -1, 2])
assert not m.is_diagonalizable()
Jmust = Matrix(4, 4, [1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 4, 1, 0, 0, 0, 4])
P, J = m.jordan_form()
assert Jmust == J
# checking for maximum precision to remain unchanged
m = Matrix([[Float('1.0', precision=110), Float('2.0', precision=110)],
[Float('3.14159265358979323846264338327', precision=110), Float('4.0', precision=110)]])
P, J = m.jordan_form()
for term in J.values():
if isinstance(term, Float):
assert term._prec == 110
def test_jordan_form_complex_issue_9274():
A = Matrix([[ 2, 4, 1, 0],
[-4, 2, 0, 1],
[ 0, 0, 2, 4],
[ 0, 0, -4, 2]])
p = 2 - 4*I;
q = 2 + 4*I;
Jmust1 = Matrix([[p, 1, 0, 0],
[0, p, 0, 0],
[0, 0, q, 1],
[0, 0, 0, q]])
Jmust2 = Matrix([[q, 1, 0, 0],
[0, q, 0, 0],
[0, 0, p, 1],
[0, 0, 0, p]])
P, J = A.jordan_form()
assert J == Jmust1 or J == Jmust2
assert simplify(P*J*P.inv()) == A
def test_issue_10220():
# two non-orthogonal Jordan blocks with eigenvalue 1
M = Matrix([[1, 0, 0, 1],
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]])
P, J = M.jordan_form()
assert P == Matrix([[0, 1, 0, 1],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])
assert J == Matrix([
[1, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
def test_jordan_form_issue_15858():
A = Matrix([
[1, 1, 1, 0],
[-2, -1, 0, -1],
[0, 0, -1, -1],
[0, 0, 2, 1]])
(P, J) = A.jordan_form()
assert P.expand() == Matrix([
[ -I, -I/2, I, I/2],
[-1 + I, 0, -1 - I, 0],
[ 0, -S(1)/2 - I/2, 0, -S(1)/2 + I/2],
[ 0, 1, 0, 1]])
assert J == Matrix([
[-I, 1, 0, 0],
[0, -I, 0, 0],
[0, 0, I, 1],
[0, 0, 0, I]])
def test_Matrix_berkowitz_charpoly():
UA, K_i, K_w = symbols('UA K_i K_w')
A = Matrix([[-K_i - UA + K_i**2/(K_i + K_w), K_i*K_w/(K_i + K_w)],
[ K_i*K_w/(K_i + K_w), -K_w + K_w**2/(K_i + K_w)]])
charpoly = A.charpoly(x)
assert charpoly == \
Poly(x**2 + (K_i*UA + K_w*UA + 2*K_i*K_w)/(K_i + K_w)*x +
K_i*K_w*UA/(K_i + K_w), x, domain='ZZ(K_i,K_w,UA)')
assert type(charpoly) is PurePoly
A = Matrix([[1, 3], [2, 0]])
assert A.charpoly() == A.charpoly(x) == PurePoly(x**2 - x - 6)
A = Matrix([[1, 2], [x, 0]])
p = A.charpoly(x)
assert p.gen != x
assert p.as_expr().subs(p.gen, x) == x**2 - 3*x
def test_exp_jordan_block():
l = Symbol('lamda')
m = Matrix.jordan_block(1, l)
assert m._eval_matrix_exp_jblock() == Matrix([[exp(l)]])
m = Matrix.jordan_block(3, l)
assert m._eval_matrix_exp_jblock() == \
Matrix([
[exp(l), exp(l), exp(l)/2],
[0, exp(l), exp(l)],
[0, 0, exp(l)]])
def test_exp():
m = Matrix([[3, 4], [0, -2]])
m_exp = Matrix([[exp(3), -4*exp(-2)/5 + 4*exp(3)/5], [0, exp(-2)]])
assert m.exp() == m_exp
assert exp(m) == m_exp
m = Matrix([[1, 0], [0, 1]])
assert m.exp() == Matrix([[E, 0], [0, E]])
assert exp(m) == Matrix([[E, 0], [0, E]])
m = Matrix([[1, -1], [1, 1]])
assert m.exp() == Matrix([[E*cos(1), -E*sin(1)], [E*sin(1), E*cos(1)]])
def test_log():
l = Symbol('lamda')
m = Matrix.jordan_block(1, l)
assert m._eval_matrix_log_jblock() == Matrix([[log(l)]])
m = Matrix.jordan_block(4, l)
assert m._eval_matrix_log_jblock() == \
Matrix(
[
[log(l), 1/l, -1/(2*l**2), 1/(3*l**3)],
[0, log(l), 1/l, -1/(2*l**2)],
[0, 0, log(l), 1/l],
[0, 0, 0, log(l)]
]
)
m = Matrix(
[[0, 0, 1],
[0, 0, 0],
[-1, 0, 0]]
)
raises(MatrixError, lambda: m.log())
def test_has():
A = Matrix(((x, y), (2, 3)))
assert A.has(x)
assert not A.has(z)
assert A.has(Symbol)
A = A.subs(x, 2)
assert not A.has(x)
def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero1():
# Test if matrices._find_reasonable_pivot_naive()
# finds a guaranteed non-zero pivot when the
# some of the candidate pivots are symbolic expressions.
# Keyword argument: simpfunc=None indicates that no simplifications
# should be performed during the search.
x = Symbol('x')
column = Matrix(3, 1, [x, cos(x)**2 + sin(x)**2, S.Half])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column)
assert pivot_val == S.Half
def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero2():
# Test if matrices._find_reasonable_pivot_naive()
# finds a guaranteed non-zero pivot when the
# some of the candidate pivots are symbolic expressions.
# Keyword argument: simpfunc=_simplify indicates that the search
# should attempt to simplify candidate pivots.
x = Symbol('x')
column = Matrix(3, 1,
[x,
cos(x)**2+sin(x)**2+x**2,
cos(x)**2+sin(x)**2])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column, simpfunc=_simplify)
assert pivot_val == 1
def test_find_reasonable_pivot_naive_simplifies():
# Test if matrices._find_reasonable_pivot_naive()
# simplifies candidate pivots, and reports
# their offsets correctly.
x = Symbol('x')
column = Matrix(3, 1,
[x,
cos(x)**2+sin(x)**2+x,
cos(x)**2+sin(x)**2])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column, simpfunc=_simplify)
assert len(simplified) == 2
assert simplified[0][0] == 1
assert simplified[0][1] == 1+x
assert simplified[1][0] == 2
assert simplified[1][1] == 1
def test_errors():
raises(ValueError, lambda: Matrix([[1, 2], [1]]))
raises(IndexError, lambda: Matrix([[1, 2]])[1.2, 5])
raises(IndexError, lambda: Matrix([[1, 2]])[1, 5.2])
raises(ValueError, lambda: randMatrix(3, c=4, symmetric=True))
raises(ValueError, lambda: Matrix([1, 2]).reshape(4, 6))
raises(ShapeError,
lambda: Matrix([[1, 2], [3, 4]]).copyin_matrix([1, 0], Matrix([1, 2])))
raises(TypeError, lambda: Matrix([[1, 2], [3, 4]]).copyin_list([0,
1], set()))
raises(NonSquareMatrixError, lambda: Matrix([[1, 2, 3], [2, 3, 0]]).inv())
raises(ShapeError,
lambda: Matrix(1, 2, [1, 2]).row_join(Matrix([[1, 2], [3, 4]])))
raises(
ShapeError, lambda: Matrix([1, 2]).col_join(Matrix([[1, 2], [3, 4]])))
raises(ShapeError, lambda: Matrix([1]).row_insert(1, Matrix([[1,
2], [3, 4]])))
raises(ShapeError, lambda: Matrix([1]).col_insert(1, Matrix([[1,
2], [3, 4]])))
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).trace())
raises(TypeError, lambda: Matrix([1]).applyfunc(1))
raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor(4, 5))
raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor_submatrix(4, 5))
raises(TypeError, lambda: Matrix([1, 2, 3]).cross(1))
raises(TypeError, lambda: Matrix([1, 2, 3]).dot(1))
raises(ShapeError, lambda: Matrix([1, 2, 3]).dot(Matrix([1, 2])))
raises(ShapeError, lambda: Matrix([1, 2]).dot([]))
raises(TypeError, lambda: Matrix([1, 2]).dot('a'))
raises(ShapeError, lambda: Matrix([1, 2]).dot([1, 2, 3]))
raises(NonSquareMatrixError, lambda: Matrix([1, 2, 3]).exp())
raises(ShapeError, lambda: Matrix([[1, 2], [3, 4]]).normalized())
raises(ValueError, lambda: Matrix([1, 2]).inv(method='not a method'))
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_GE())
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_GE())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_ADJ())
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_ADJ())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_LU())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).is_nilpotent())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).det())
raises(ValueError,
lambda: Matrix([[1, 2], [3, 4]]).det(method='Not a real method'))
raises(ValueError,
lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8],
[9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc="Not function"))
raises(ValueError,
lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8],
[9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc=False))
raises(ValueError,
lambda: hessian(Matrix([[1, 2], [3, 4]]), Matrix([[1, 2], [2, 1]])))
raises(ValueError, lambda: hessian(Matrix([[1, 2], [3, 4]]), []))
raises(ValueError, lambda: hessian(Symbol('x')**2, 'a'))
raises(IndexError, lambda: eye(3)[5, 2])
raises(IndexError, lambda: eye(3)[2, 5])
M = Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))
raises(ValueError, lambda: M.det('method=LU_decomposition()'))
V = Matrix([[10, 10, 10]])
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(ValueError, lambda: M.row_insert(4.7, V))
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(ValueError, lambda: M.col_insert(-4.2, V))
def test_len():
assert len(Matrix()) == 0
assert len(Matrix([[1, 2]])) == len(Matrix([[1], [2]])) == 2
assert len(Matrix(0, 2, lambda i, j: 0)) == \
len(Matrix(2, 0, lambda i, j: 0)) == 0
assert len(Matrix([[0, 1, 2], [3, 4, 5]])) == 6
assert Matrix([1]) == Matrix([[1]])
assert not Matrix()
assert Matrix() == Matrix([])
def test_integrate():
A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2)))
assert A.integrate(x) == \
Matrix(((x, 4*x, x**2/2), (x*y, 2*x, 4*x), (10*x, 5*x, x**3/3)))
assert A.integrate(y) == \
Matrix(((y, 4*y, x*y), (y**2/2, 2*y, 4*y), (10*y, 5*y, y*x**2)))
def test_limit():
A = Matrix(((1, 4, sin(x)/x), (y, 2, 4), (10, 5, x**2 + 1)))
assert A.limit(x, 0) == Matrix(((1, 4, 1), (y, 2, 4), (10, 5, 1)))
def test_diff():
A = MutableDenseMatrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1)))
assert isinstance(A.diff(x), type(A))
assert A.diff(x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert A.diff(y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
assert diff(A, x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert diff(A, y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
A_imm = A.as_immutable()
assert isinstance(A_imm.diff(x), type(A_imm))
assert A_imm.diff(x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert A_imm.diff(y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
assert diff(A_imm, x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert diff(A_imm, y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
def test_diff_by_matrix():
# Derive matrix by matrix:
A = MutableDenseMatrix([[x, y], [z, t]])
assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(A, A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
A_imm = A.as_immutable()
assert A_imm.diff(A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(A_imm, A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# Derive a constant matrix:
assert A.diff(a) == MutableDenseMatrix([[0, 0], [0, 0]])
B = ImmutableDenseMatrix([a, b])
assert A.diff(B) == Array.zeros(2, 1, 2, 2)
assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# Test diff with tuples:
dB = B.diff([[a, b]])
assert dB.shape == (2, 2, 1)
assert dB == Array([[[1], [0]], [[0], [1]]])
f = Function("f")
fxyz = f(x, y, z)
assert fxyz.diff([[x, y, z]]) == Array([fxyz.diff(x), fxyz.diff(y), fxyz.diff(z)])
assert fxyz.diff(([x, y, z], 2)) == Array([
[fxyz.diff(x, 2), fxyz.diff(x, y), fxyz.diff(x, z)],
[fxyz.diff(x, y), fxyz.diff(y, 2), fxyz.diff(y, z)],
[fxyz.diff(x, z), fxyz.diff(z, y), fxyz.diff(z, 2)],
])
expr = sin(x)*exp(y)
assert expr.diff([[x, y]]) == Array([cos(x)*exp(y), sin(x)*exp(y)])
assert expr.diff(y, ((x, y),)) == Array([cos(x)*exp(y), sin(x)*exp(y)])
assert expr.diff(x, ((x, y),)) == Array([-sin(x)*exp(y), cos(x)*exp(y)])
assert expr.diff(((y, x),), [[x, y]]) == Array([[cos(x)*exp(y), -sin(x)*exp(y)], [sin(x)*exp(y), cos(x)*exp(y)]])
# Test different notations:
assert fxyz.diff(x).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[0, 1, 0]
assert fxyz.diff(z).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[2, 1, 0]
assert fxyz.diff([[x, y, z]], ((z, y, x),)) == Array([[fxyz.diff(i).diff(j) for i in (x, y, z)] for j in (z, y, x)])
# Test scalar derived by matrix remains matrix:
res = x.diff(Matrix([[x, y]]))
assert isinstance(res, ImmutableDenseMatrix)
assert res == Matrix([[1, 0]])
res = (x**3).diff(Matrix([[x, y]]))
assert isinstance(res, ImmutableDenseMatrix)
assert res == Matrix([[3*x**2, 0]])
def test_getattr():
A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1)))
raises(AttributeError, lambda: A.nonexistantattribute)
assert getattr(A, 'diff')(x) == Matrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
def test_hessenberg():
A = Matrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]])
assert A.is_upper_hessenberg
A = A.T
assert A.is_lower_hessenberg
A[0, -1] = 1
assert A.is_lower_hessenberg is False
A = Matrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]])
assert not A.is_upper_hessenberg
A = zeros(5, 2)
assert A.is_upper_hessenberg
def test_cholesky():
raises(NonSquareMatrixError, lambda: Matrix((1, 2)).cholesky())
raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky())
raises(ValueError, lambda: Matrix(((5 + I, 0), (0, 1))).cholesky())
raises(ValueError, lambda: Matrix(((1, 5), (5, 1))).cholesky())
raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky(hermitian=False))
assert Matrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([
[sqrt(5 + I), 0], [0, 1]])
A = Matrix(((1, 5), (5, 1)))
L = A.cholesky(hermitian=False)
assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]])
assert L*L.T == A
A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L = A.cholesky()
assert L * L.T == A
assert L.is_lower
assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]])
A = Matrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
assert A.cholesky().expand() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3)))
raises(NonSquareMatrixError, lambda: SparseMatrix((1, 2)).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky())
raises(ValueError, lambda: SparseMatrix(((5 + I, 0), (0, 1))).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 5), (5, 1))).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky(hermitian=False))
assert SparseMatrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([
[sqrt(5 + I), 0], [0, 1]])
A = SparseMatrix(((1, 5), (5, 1)))
L = A.cholesky(hermitian=False)
assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]])
assert L*L.T == A
A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L = A.cholesky()
assert L * L.T == A
assert L.is_lower
assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]])
A = SparseMatrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
assert A.cholesky() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3)))
def test_matrix_norm():
# Vector Tests
# Test columns and symbols
x = Symbol('x', real=True)
v = Matrix([cos(x), sin(x)])
assert trigsimp(v.norm(2)) == 1
assert v.norm(10) == Pow(cos(x)**10 + sin(x)**10, Rational(1, 10))
# Test Rows
A = Matrix([[5, Rational(3, 2)]])
assert A.norm() == Pow(25 + Rational(9, 4), S.Half)
assert A.norm(oo) == max(A)
assert A.norm(-oo) == min(A)
# Matrix Tests
# Intuitive test
A = Matrix([[1, 1], [1, 1]])
assert A.norm(2) == 2
assert A.norm(-2) == 0
assert A.norm('frobenius') == 2
assert eye(10).norm(2) == eye(10).norm(-2) == 1
assert A.norm(oo) == 2
# Test with Symbols and more complex entries
A = Matrix([[3, y, y], [x, S.Half, -pi]])
assert (A.norm('fro')
== sqrt(Rational(37, 4) + 2*abs(y)**2 + pi**2 + x**2))
# Check non-square
A = Matrix([[1, 2, -3], [4, 5, Rational(13, 2)]])
assert A.norm(2) == sqrt(Rational(389, 8) + sqrt(78665)/8)
assert A.norm(-2) is S.Zero
assert A.norm('frobenius') == sqrt(389)/2
# Test properties of matrix norms
# https://en.wikipedia.org/wiki/Matrix_norm#Definition
# Two matrices
A = Matrix([[1, 2], [3, 4]])
B = Matrix([[5, 5], [-2, 2]])
C = Matrix([[0, -I], [I, 0]])
D = Matrix([[1, 0], [0, -1]])
L = [A, B, C, D]
alpha = Symbol('alpha', real=True)
for order in ['fro', 2, -2]:
# Zero Check
assert zeros(3).norm(order) is S.Zero
# Check Triangle Inequality for all Pairs of Matrices
for X in L:
for Y in L:
dif = (X.norm(order) + Y.norm(order) -
(X + Y).norm(order))
assert (dif >= 0)
# Scalar multiplication linearity
for M in [A, B, C, D]:
dif = simplify((alpha*M).norm(order) -
abs(alpha) * M.norm(order))
assert dif == 0
# Test Properties of Vector Norms
# https://en.wikipedia.org/wiki/Vector_norm
# Two column vectors
a = Matrix([1, 1 - 1*I, -3])
b = Matrix([S.Half, 1*I, 1])
c = Matrix([-1, -1, -1])
d = Matrix([3, 2, I])
e = Matrix([Integer(1e2), Rational(1, 1e2), 1])
L = [a, b, c, d, e]
alpha = Symbol('alpha', real=True)
for order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity, pi]:
# Zero Check
if order > 0:
assert Matrix([0, 0, 0]).norm(order) is S.Zero
# Triangle inequality on all pairs
if order >= 1: # Triangle InEq holds only for these norms
for X in L:
for Y in L:
dif = (X.norm(order) + Y.norm(order) -
(X + Y).norm(order))
assert simplify(dif >= 0) is S.true
# Linear to scalar multiplication
if order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity]:
for X in L:
dif = simplify((alpha*X).norm(order) -
(abs(alpha) * X.norm(order)))
assert dif == 0
# ord=1
M = Matrix(3, 3, [1, 3, 0, -2, -1, 0, 3, 9, 6])
assert M.norm(1) == 13
def test_condition_number():
x = Symbol('x', real=True)
A = eye(3)
A[0, 0] = 10
A[2, 2] = Rational(1, 10)
assert A.condition_number() == 100
A[1, 1] = x
assert A.condition_number() == Max(10, Abs(x)) / Min(Rational(1, 10), Abs(x))
M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]])
Mc = M.condition_number()
assert all(Float(1.).epsilon_eq(Mc.subs(x, val).evalf()) for val in
[Rational(1, 5), S.Half, Rational(1, 10), pi/2, pi, pi*Rational(7, 4) ])
#issue 10782
assert Matrix([]).condition_number() == 0
def test_equality():
A = Matrix(((1, 2, 3), (4, 5, 6), (7, 8, 9)))
B = Matrix(((9, 8, 7), (6, 5, 4), (3, 2, 1)))
assert A == A[:, :]
assert not A != A[:, :]
assert not A == B
assert A != B
assert A != 10
assert not A == 10
# A SparseMatrix can be equal to a Matrix
C = SparseMatrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
D = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
assert C == D
assert not C != D
def test_col_join():
assert eye(3).col_join(Matrix([[7, 7, 7]])) == \
Matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[7, 7, 7]])
def test_row_insert():
r4 = Matrix([[4, 4, 4]])
for i in range(-4, 5):
l = [1, 0, 0]
l.insert(i, 4)
assert flatten(eye(3).row_insert(i, r4).col(0).tolist()) == l
def test_col_insert():
c4 = Matrix([4, 4, 4])
for i in range(-4, 5):
l = [0, 0, 0]
l.insert(i, 4)
assert flatten(zeros(3).col_insert(i, c4).row(0).tolist()) == l
def test_normalized():
assert Matrix([3, 4]).normalized() == \
Matrix([Rational(3, 5), Rational(4, 5)])
# Zero vector trivial cases
assert Matrix([0, 0, 0]).normalized() == Matrix([0, 0, 0])
# Machine precision error truncation trivial cases
m = Matrix([0,0,1.e-100])
assert m.normalized(
iszerofunc=lambda x: x.evalf(n=10, chop=True).is_zero
) == Matrix([0, 0, 0])
def test_print_nonzero():
assert capture(lambda: eye(3).print_nonzero()) == \
'[X ]\n[ X ]\n[ X]\n'
assert capture(lambda: eye(3).print_nonzero('.')) == \
'[. ]\n[ . ]\n[ .]\n'
def test_zeros_eye():
assert Matrix.eye(3) == eye(3)
assert Matrix.zeros(3) == zeros(3)
assert ones(3, 4) == Matrix(3, 4, [1]*12)
i = Matrix([[1, 0], [0, 1]])
z = Matrix([[0, 0], [0, 0]])
for cls in classes:
m = cls.eye(2)
assert i == m # but m == i will fail if m is immutable
assert i == eye(2, cls=cls)
assert type(m) == cls
m = cls.zeros(2)
assert z == m
assert z == zeros(2, cls=cls)
assert type(m) == cls
def test_is_zero():
assert Matrix().is_zero_matrix
assert Matrix([[0, 0], [0, 0]]).is_zero_matrix
assert zeros(3, 4).is_zero_matrix
assert not eye(3).is_zero_matrix
assert Matrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert SparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert ImmutableMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert ImmutableSparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert Matrix([[x, 1], [0, 0]]).is_zero_matrix == False
a = Symbol('a', nonzero=True)
assert Matrix([[a, 0], [0, 0]]).is_zero_matrix == False
def test_rotation_matrices():
# This tests the rotation matrices by rotating about an axis and back.
theta = pi/3
r3_plus = rot_axis3(theta)
r3_minus = rot_axis3(-theta)
r2_plus = rot_axis2(theta)
r2_minus = rot_axis2(-theta)
r1_plus = rot_axis1(theta)
r1_minus = rot_axis1(-theta)
assert r3_minus*r3_plus*eye(3) == eye(3)
assert r2_minus*r2_plus*eye(3) == eye(3)
assert r1_minus*r1_plus*eye(3) == eye(3)
# Check the correctness of the trace of the rotation matrix
assert r1_plus.trace() == 1 + 2*cos(theta)
assert r2_plus.trace() == 1 + 2*cos(theta)
assert r3_plus.trace() == 1 + 2*cos(theta)
# Check that a rotation with zero angle doesn't change anything.
assert rot_axis1(0) == eye(3)
assert rot_axis2(0) == eye(3)
assert rot_axis3(0) == eye(3)
# Check left-hand convention
# see Issue #24529
q1 = Quaternion.from_axis_angle([1, 0, 0], pi / 2)
q2 = Quaternion.from_axis_angle([0, 1, 0], pi / 2)
q3 = Quaternion.from_axis_angle([0, 0, 1], pi / 2)
assert rot_axis1(- pi / 2) == q1.to_rotation_matrix()
assert rot_axis2(- pi / 2) == q2.to_rotation_matrix()
assert rot_axis3(- pi / 2) == q3.to_rotation_matrix()
# Check right-hand convention
assert rot_ccw_axis1(+ pi / 2) == q1.to_rotation_matrix()
assert rot_ccw_axis2(+ pi / 2) == q2.to_rotation_matrix()
assert rot_ccw_axis3(+ pi / 2) == q3.to_rotation_matrix()
def test_DeferredVector():
assert str(DeferredVector("vector")[4]) == "vector[4]"
assert sympify(DeferredVector("d")) == DeferredVector("d")
raises(IndexError, lambda: DeferredVector("d")[-1])
assert str(DeferredVector("d")) == "d"
assert repr(DeferredVector("test")) == "DeferredVector('test')"
def test_DeferredVector_not_iterable():
assert not iterable(DeferredVector('X'))
def test_DeferredVector_Matrix():
raises(TypeError, lambda: Matrix(DeferredVector("V")))
def test_GramSchmidt():
R = Rational
m1 = Matrix(1, 2, [1, 2])
m2 = Matrix(1, 2, [2, 3])
assert GramSchmidt([m1, m2]) == \
[Matrix(1, 2, [1, 2]), Matrix(1, 2, [R(2)/5, R(-1)/5])]
assert GramSchmidt([m1.T, m2.T]) == \
[Matrix(2, 1, [1, 2]), Matrix(2, 1, [R(2)/5, R(-1)/5])]
# from wikipedia
assert GramSchmidt([Matrix([3, 1]), Matrix([2, 2])], True) == [
Matrix([3*sqrt(10)/10, sqrt(10)/10]),
Matrix([-sqrt(10)/10, 3*sqrt(10)/10])]
# https://github.com/sympy/sympy/issues/9488
L = FiniteSet(Matrix([1]))
assert GramSchmidt(L) == [Matrix([[1]])]
def test_casoratian():
assert casoratian([1, 2, 3, 4], 1) == 0
assert casoratian([1, 2, 3, 4], 1, zero=False) == 0
def test_zero_dimension_multiply():
assert (Matrix()*zeros(0, 3)).shape == (0, 3)
assert zeros(3, 0)*zeros(0, 3) == zeros(3, 3)
assert zeros(0, 3)*zeros(3, 0) == Matrix()
def test_slice_issue_2884():
m = Matrix(2, 2, range(4))
assert m[1, :] == Matrix([[2, 3]])
assert m[-1, :] == Matrix([[2, 3]])
assert m[:, 1] == Matrix([[1, 3]]).T
assert m[:, -1] == Matrix([[1, 3]]).T
raises(IndexError, lambda: m[2, :])
raises(IndexError, lambda: m[2, 2])
def test_slice_issue_3401():
assert zeros(0, 3)[:, -1].shape == (0, 1)
assert zeros(3, 0)[0, :] == Matrix(1, 0, [])
def test_copyin():
s = zeros(3, 3)
s[3] = 1
assert s[:, 0] == Matrix([0, 1, 0])
assert s[3] == 1
assert s[3: 4] == [1]
s[1, 1] = 42
assert s[1, 1] == 42
assert s[1, 1:] == Matrix([[42, 0]])
s[1, 1:] = Matrix([[5, 6]])
assert s[1, :] == Matrix([[1, 5, 6]])
s[1, 1:] = [[42, 43]]
assert s[1, :] == Matrix([[1, 42, 43]])
s[0, 0] = 17
assert s[:, :1] == Matrix([17, 1, 0])
s[0, 0] = [1, 1, 1]
assert s[:, 0] == Matrix([1, 1, 1])
s[0, 0] = Matrix([1, 1, 1])
assert s[:, 0] == Matrix([1, 1, 1])
s[0, 0] = SparseMatrix([1, 1, 1])
assert s[:, 0] == Matrix([1, 1, 1])
def test_invertible_check():
# sometimes a singular matrix will have a pivot vector shorter than
# the number of rows in a matrix...
assert Matrix([[1, 2], [1, 2]]).rref() == (Matrix([[1, 2], [0, 0]]), (0,))
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inv())
m = Matrix([
[-1, -1, 0],
[ x, 1, 1],
[ 1, x, -1],
])
assert len(m.rref()[1]) != m.rows
# in addition, unless simplify=True in the call to rref, the identity
# matrix will be returned even though m is not invertible
assert m.rref()[0] != eye(3)
assert m.rref(simplify=signsimp)[0] != eye(3)
raises(ValueError, lambda: m.inv(method="ADJ"))
raises(ValueError, lambda: m.inv(method="GE"))
raises(ValueError, lambda: m.inv(method="LU"))
def test_issue_3959():
x, y = symbols('x, y')
e = x*y
assert e.subs(x, Matrix([3, 5, 3])) == Matrix([3, 5, 3])*y
def test_issue_5964():
assert str(Matrix([[1, 2], [3, 4]])) == 'Matrix([[1, 2], [3, 4]])'
def test_issue_7604():
x, y = symbols("x y")
assert sstr(Matrix([[x, 2*y], [y**2, x + 3]])) == \
'Matrix([\n[ x, 2*y],\n[y**2, x + 3]])'
def test_is_Identity():
assert eye(3).is_Identity
assert eye(3).as_immutable().is_Identity
assert not zeros(3).is_Identity
assert not ones(3).is_Identity
# issue 6242
assert not Matrix([[1, 0, 0]]).is_Identity
# issue 8854
assert SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1}).is_Identity
assert not SparseMatrix(2,3, range(6)).is_Identity
assert not SparseMatrix(3,3, {(0,0):1, (1,1):1}).is_Identity
assert not SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1, (0,1):2, (0,2):3}).is_Identity
def test_dot():
assert ones(1, 3).dot(ones(3, 1)) == 3
assert ones(1, 3).dot([1, 1, 1]) == 3
assert Matrix([1, 2, 3]).dot(Matrix([1, 2, 3])) == 14
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I])) == -5 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=False) == -5 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True) == 13 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True, conjugate_convention="physics") == 13 - I
assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="right") == 4 + 8*I
assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="left") == 4 - 8*I
assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), hermitian=False, conjugate_convention="left") == -5
assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), conjugate_convention="left") == 5
raises(ValueError, lambda: Matrix([1, 2]).dot(Matrix([3, 4]), hermitian=True, conjugate_convention="test"))
def test_dual():
B_x, B_y, B_z, E_x, E_y, E_z = symbols(
'B_x B_y B_z E_x E_y E_z', real=True)
F = Matrix((
( 0, E_x, E_y, E_z),
(-E_x, 0, B_z, -B_y),
(-E_y, -B_z, 0, B_x),
(-E_z, B_y, -B_x, 0)
))
Fd = Matrix((
( 0, -B_x, -B_y, -B_z),
(B_x, 0, E_z, -E_y),
(B_y, -E_z, 0, E_x),
(B_z, E_y, -E_x, 0)
))
assert F.dual().equals(Fd)
assert eye(3).dual().equals(zeros(3))
assert F.dual().dual().equals(-F)
def test_anti_symmetric():
assert Matrix([1, 2]).is_anti_symmetric() is False
m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0])
assert m.is_anti_symmetric() is True
assert m.is_anti_symmetric(simplify=False) is False
assert m.is_anti_symmetric(simplify=lambda x: x) is False
# tweak to fail
m[2, 1] = -m[2, 1]
assert m.is_anti_symmetric() is False
# untweak
m[2, 1] = -m[2, 1]
m = m.expand()
assert m.is_anti_symmetric(simplify=False) is True
m[0, 0] = 1
assert m.is_anti_symmetric() is False
def test_normalize_sort_diogonalization():
A = Matrix(((1, 2), (2, 1)))
P, Q = A.diagonalize(normalize=True)
assert P*P.T == P.T*P == eye(P.cols)
P, Q = A.diagonalize(normalize=True, sort=True)
assert P*P.T == P.T*P == eye(P.cols)
assert P*Q*P.inv() == A
def test_issue_5321():
raises(ValueError, lambda: Matrix([[1, 2, 3], Matrix(0, 1, [])]))
def test_issue_5320():
assert Matrix.hstack(eye(2), 2*eye(2)) == Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]
])
assert Matrix.vstack(eye(2), 2*eye(2)) == Matrix([
[1, 0],
[0, 1],
[2, 0],
[0, 2]
])
cls = SparseMatrix
assert cls.hstack(cls(eye(2)), cls(2*eye(2))) == Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]
])
def test_issue_11944():
A = Matrix([[1]])
AIm = sympify(A)
assert Matrix.hstack(AIm, A) == Matrix([[1, 1]])
assert Matrix.vstack(AIm, A) == Matrix([[1], [1]])
def test_cross():
a = [1, 2, 3]
b = [3, 4, 5]
col = Matrix([-2, 4, -2])
row = col.T
def test(M, ans):
assert ans == M
assert type(M) == cls
for cls in classes:
A = cls(a)
B = cls(b)
test(A.cross(B), col)
test(A.cross(B.T), col)
test(A.T.cross(B.T), row)
test(A.T.cross(B), row)
raises(ShapeError, lambda:
Matrix(1, 2, [1, 1]).cross(Matrix(1, 2, [1, 1])))
def test_hash():
for cls in classes[-2:]:
s = {cls.eye(1), cls.eye(1)}
assert len(s) == 1 and s.pop() == cls.eye(1)
# issue 3979
for cls in classes[:2]:
assert not isinstance(cls.eye(1), Hashable)
@XFAIL
def test_issue_3979():
# when this passes, delete this and change the [1:2]
# to [:2] in the test_hash above for issue 3979
cls = classes[0]
raises(AttributeError, lambda: hash(cls.eye(1)))
def test_adjoint():
dat = [[0, I], [1, 0]]
ans = Matrix([[0, 1], [-I, 0]])
for cls in classes:
assert ans == cls(dat).adjoint()
def test_simplify_immutable():
assert simplify(ImmutableMatrix([[sin(x)**2 + cos(x)**2]])) == \
ImmutableMatrix([[1]])
def test_replace():
F, G = symbols('F, G', cls=Function)
K = Matrix(2, 2, lambda i, j: G(i+j))
M = Matrix(2, 2, lambda i, j: F(i+j))
N = M.replace(F, G)
assert N == K
def test_replace_map():
F, G = symbols('F, G', cls=Function)
with warns_deprecated_sympy():
K = Matrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}),
(G(1), {F(1): G(1)}), (G(2), {F(2): G(2)})])
M = Matrix(2, 2, lambda i, j: F(i+j))
with warns(SymPyDeprecationWarning, test_stacklevel=False):
N = M.replace(F, G, True)
assert N == K
def test_atoms():
m = Matrix([[1, 2], [x, 1 - 1/x]])
assert m.atoms() == {S.One,S(2),S.NegativeOne, x}
assert m.atoms(Symbol) == {x}
def test_pinv():
# Pseudoinverse of an invertible matrix is the inverse.
A1 = Matrix([[a, b], [c, d]])
assert simplify(A1.pinv(method="RD")) == simplify(A1.inv())
# Test the four properties of the pseudoinverse for various matrices.
As = [Matrix([[13, 104], [2212, 3], [-3, 5]]),
Matrix([[1, 7, 9], [11, 17, 19]]),
Matrix([a, b])]
for A in As:
A_pinv = A.pinv(method="RD")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# XXX Pinv with diagonalization makes expression too complicated.
for A in As:
A_pinv = simplify(A.pinv(method="ED"))
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# XXX Computing pinv using diagonalization makes an expression that
# is too complicated to simplify.
# A1 = Matrix([[a, b], [c, d]])
# assert simplify(A1.pinv(method="ED")) == simplify(A1.inv())
# so this is tested numerically at a fixed random point
from sympy.core.numbers import comp
q = A1.pinv(method="ED")
w = A1.inv()
reps = {a: -73633, b: 11362, c: 55486, d: 62570}
assert all(
comp(i.n(), j.n())
for i, j in zip(q.subs(reps), w.subs(reps))
)
@slow
@XFAIL
def test_pinv_rank_deficient_when_diagonalization_fails():
# Test the four properties of the pseudoinverse for matrices when
# diagonalization of A.H*A fails.
As = [
Matrix([
[61, 89, 55, 20, 71, 0],
[62, 96, 85, 85, 16, 0],
[69, 56, 17, 4, 54, 0],
[10, 54, 91, 41, 71, 0],
[ 7, 30, 10, 48, 90, 0],
[0, 0, 0, 0, 0, 0]])
]
for A in As:
A_pinv = A.pinv(method="ED")
AAp = A * A_pinv
ApA = A_pinv * A
assert AAp.H == AAp
assert ApA.H == ApA
def test_issue_7201():
assert ones(0, 1) + ones(0, 1) == Matrix(0, 1, [])
assert ones(1, 0) + ones(1, 0) == Matrix(1, 0, [])
def test_free_symbols():
for M in ImmutableMatrix, ImmutableSparseMatrix, Matrix, SparseMatrix:
assert M([[x], [0]]).free_symbols == {x}
def test_from_ndarray():
"""See issue 7465."""
try:
from numpy import array
except ImportError:
skip('NumPy must be available to test creating matrices from ndarrays')
assert Matrix(array([1, 2, 3])) == Matrix([1, 2, 3])
assert Matrix(array([[1, 2, 3]])) == Matrix([[1, 2, 3]])
assert Matrix(array([[1, 2, 3], [4, 5, 6]])) == \
Matrix([[1, 2, 3], [4, 5, 6]])
assert Matrix(array([x, y, z])) == Matrix([x, y, z])
raises(NotImplementedError,
lambda: Matrix(array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])))
assert Matrix([array([1, 2]), array([3, 4])]) == Matrix([[1, 2], [3, 4]])
assert Matrix([array([1, 2]), [3, 4]]) == Matrix([[1, 2], [3, 4]])
assert Matrix([array([]), array([])]) == Matrix([])
def test_17522_numpy():
from sympy.matrices.common import _matrixify
try:
from numpy import array, matrix
except ImportError:
skip('NumPy must be available to test indexing matrixified NumPy ndarrays and matrices')
m = _matrixify(array([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
with ignore_warnings(PendingDeprecationWarning):
m = _matrixify(matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_17522_mpmath():
from sympy.matrices.common import _matrixify
try:
from mpmath import matrix
except ImportError:
skip('mpmath must be available to test indexing matrixified mpmath matrices')
m = _matrixify(matrix([[1, 2], [3, 4]]))
assert m[3] == 4.0
assert list(m) == [1.0, 2.0, 3.0, 4.0]
def test_17522_scipy():
from sympy.matrices.common import _matrixify
try:
from scipy.sparse import csr_matrix
except ImportError:
skip('SciPy must be available to test indexing matrixified SciPy sparse matrices')
m = _matrixify(csr_matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_hermitian():
a = Matrix([[1, I], [-I, 1]])
assert a.is_hermitian
a[0, 0] = 2*I
assert a.is_hermitian is False
a[0, 0] = x
assert a.is_hermitian is None
a[0, 1] = a[1, 0]*I
assert a.is_hermitian is False
def test_doit():
a = Matrix([[Add(x,x, evaluate=False)]])
assert a[0] != 2*x
assert a.doit() == Matrix([[2*x]])
def test_issue_9457_9467_9876():
# for row_del(index)
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
M.row_del(1)
assert M == Matrix([[1, 2, 3], [3, 4, 5]])
N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
N.row_del(-2)
assert N == Matrix([[1, 2, 3], [3, 4, 5]])
O = Matrix([[1, 2, 3], [5, 6, 7], [9, 10, 11]])
O.row_del(-1)
assert O == Matrix([[1, 2, 3], [5, 6, 7]])
P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: P.row_del(10))
Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: Q.row_del(-10))
# for col_del(index)
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
M.col_del(1)
assert M == Matrix([[1, 3], [2, 4], [3, 5]])
N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
N.col_del(-2)
assert N == Matrix([[1, 3], [2, 4], [3, 5]])
P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: P.col_del(10))
Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: Q.col_del(-10))
def test_issue_9422():
x, y = symbols('x y', commutative=False)
a, b = symbols('a b')
M = eye(2)
M1 = Matrix(2, 2, [x, y, y, z])
assert y*x*M != x*y*M
assert b*a*M == a*b*M
assert x*M1 != M1*x
assert a*M1 == M1*a
assert y*x*M == Matrix([[y*x, 0], [0, y*x]])
def test_issue_10770():
M = Matrix([])
a = ['col_insert', 'row_join'], Matrix([9, 6, 3])
b = ['row_insert', 'col_join'], a[1].T
c = ['row_insert', 'col_insert'], Matrix([[1, 2], [3, 4]])
for ops, m in (a, b, c):
for op in ops:
f = getattr(M, op)
new = f(m) if 'join' in op else f(42, m)
assert new == m and id(new) != id(m)
def test_issue_10658():
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert A.extract([0, 1, 2], [True, True, False]) == \
Matrix([[1, 2], [4, 5], [7, 8]])
assert A.extract([0, 1, 2], [True, False, False]) == Matrix([[1], [4], [7]])
assert A.extract([True, False, False], [0, 1, 2]) == Matrix([[1, 2, 3]])
assert A.extract([True, False, True], [0, 1, 2]) == \
Matrix([[1, 2, 3], [7, 8, 9]])
assert A.extract([0, 1, 2], [False, False, False]) == Matrix(3, 0, [])
assert A.extract([False, False, False], [0, 1, 2]) == Matrix(0, 3, [])
assert A.extract([True, False, True], [False, True, False]) == \
Matrix([[2], [8]])
def test_opportunistic_simplification():
# this test relates to issue #10718, #9480, #11434
# issue #9480
m = Matrix([[-5 + 5*sqrt(2), -5], [-5*sqrt(2)/2 + 5, -5*sqrt(2)/2]])
assert m.rank() == 1
# issue #10781
m = Matrix([[3+3*sqrt(3)*I, -9],[4,-3+3*sqrt(3)*I]])
assert simplify(m.rref()[0] - Matrix([[1, -9/(3 + 3*sqrt(3)*I)], [0, 0]])) == zeros(2, 2)
# issue #11434
ax,ay,bx,by,cx,cy,dx,dy,ex,ey,t0,t1 = symbols('a_x a_y b_x b_y c_x c_y d_x d_y e_x e_y t_0 t_1')
m = Matrix([[ax,ay,ax*t0,ay*t0,0],[bx,by,bx*t0,by*t0,0],[cx,cy,cx*t0,cy*t0,1],[dx,dy,dx*t0,dy*t0,1],[ex,ey,2*ex*t1-ex*t0,2*ey*t1-ey*t0,0]])
assert m.rank() == 4
def test_partial_pivoting():
# example from https://en.wikipedia.org/wiki/Pivot_element
# partial pivoting with back substitution gives a perfect result
# naive pivoting give an error ~1e-13, so anything better than
# 1e-15 is good
mm=Matrix([[0.003, 59.14, 59.17], [5.291, -6.13, 46.78]])
assert (mm.rref()[0] - Matrix([[1.0, 0, 10.0],
[ 0, 1.0, 1.0]])).norm() < 1e-15
# issue #11549
m_mixed = Matrix([[6e-17, 1.0, 4],
[ -1.0, 0, 8],
[ 0, 0, 1]])
m_float = Matrix([[6e-17, 1.0, 4.],
[ -1.0, 0., 8.],
[ 0., 0., 1.]])
m_inv = Matrix([[ 0, -1.0, 8.0],
[1.0, 6.0e-17, -4.0],
[ 0, 0, 1]])
# this example is numerically unstable and involves a matrix with a norm >= 8,
# this comparing the difference of the results with 1e-15 is numerically sound.
assert (m_mixed.inv() - m_inv).norm() < 1e-15
assert (m_float.inv() - m_inv).norm() < 1e-15
def test_iszero_substitution():
""" When doing numerical computations, all elements that pass
the iszerofunc test should be set to numerically zero if they
aren't already. """
# Matrix from issue #9060
m = Matrix([[0.9, -0.1, -0.2, 0],[-0.8, 0.9, -0.4, 0],[-0.1, -0.8, 0.6, 0]])
m_rref = m.rref(iszerofunc=lambda x: abs(x)<6e-15)[0]
m_correct = Matrix([[1.0, 0, -0.301369863013699, 0],[ 0, 1.0, -0.712328767123288, 0],[ 0, 0, 0, 0]])
m_diff = m_rref - m_correct
assert m_diff.norm() < 1e-15
# if a zero-substitution wasn't made, this entry will be -1.11022302462516e-16
assert m_rref[2,2] == 0
def test_issue_11238():
from sympy.geometry.point import Point
xx = 8*tan(pi*Rational(13, 45))/(tan(pi*Rational(13, 45)) + sqrt(3))
yy = (-8*sqrt(3)*tan(pi*Rational(13, 45))**2 + 24*tan(pi*Rational(13, 45)))/(-3 + tan(pi*Rational(13, 45))**2)
p1 = Point(0, 0)
p2 = Point(1, -sqrt(3))
p0 = Point(xx,yy)
m1 = Matrix([p1 - simplify(p0), p2 - simplify(p0)])
m2 = Matrix([p1 - p0, p2 - p0])
m3 = Matrix([simplify(p1 - p0), simplify(p2 - p0)])
# This system has expressions which are zero and
# cannot be easily proved to be such, so without
# numerical testing, these assertions will fail.
Z = lambda x: abs(x.n()) < 1e-20
assert m1.rank(simplify=True, iszerofunc=Z) == 1
assert m2.rank(simplify=True, iszerofunc=Z) == 1
assert m3.rank(simplify=True, iszerofunc=Z) == 1
def test_as_real_imag():
m1 = Matrix(2,2,[1,2,3,4])
m2 = m1*S.ImaginaryUnit
m3 = m1 + m2
for kls in classes:
a,b = kls(m3).as_real_imag()
assert list(a) == list(m1)
assert list(b) == list(m1)
def test_deprecated():
# Maintain tests for deprecated functions. We must capture
# the deprecation warnings. When the deprecated functionality is
# removed, the corresponding tests should be removed.
m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2])
P, Jcells = m.jordan_cells()
assert Jcells[1] == Matrix(1, 1, [2])
assert Jcells[0] == Matrix(2, 2, [2, 1, 0, 2])
def test_issue_14489():
from sympy.core.mod import Mod
A = Matrix([-1, 1, 2])
B = Matrix([10, 20, -15])
assert Mod(A, 3) == Matrix([2, 1, 2])
assert Mod(B, 4) == Matrix([2, 0, 1])
def test_issue_14943():
# Test that __array__ accepts the optional dtype argument
try:
from numpy import array
except ImportError:
skip('NumPy must be available to test creating matrices from ndarrays')
M = Matrix([[1,2], [3,4]])
assert array(M, dtype=float).dtype.name == 'float64'
def test_case_6913():
m = MatrixSymbol('m', 1, 1)
a = Symbol("a")
a = m[0, 0]>0
assert str(a) == 'm[0, 0] > 0'
def test_issue_11948():
A = MatrixSymbol('A', 3, 3)
a = Wild('a')
assert A.match(a) == {a: A}
def test_gramschmidt_conjugate_dot():
vecs = [Matrix([1, I]), Matrix([1, -I])]
assert Matrix.orthogonalize(*vecs) == \
[Matrix([[1], [I]]), Matrix([[1], [-I]])]
vecs = [Matrix([1, I, 0]), Matrix([I, 0, -I])]
assert Matrix.orthogonalize(*vecs) == \
[Matrix([[1], [I], [0]]), Matrix([[I/2], [S(1)/2], [-I]])]
mat = Matrix([[1, I], [1, -I]])
Q, R = mat.QRdecomposition()
assert Q * Q.H == Matrix.eye(2)
def test_issue_8207():
a = Matrix(MatrixSymbol('a', 3, 1))
b = Matrix(MatrixSymbol('b', 3, 1))
c = a.dot(b)
d = diff(c, a[0, 0])
e = diff(d, a[0, 0])
assert d == b[0, 0]
assert e == 0
def test_func():
from sympy.simplify.simplify import nthroot
A = Matrix([[1, 2],[0, 3]])
assert A.analytic_func(sin(x*t), x) == Matrix([[sin(t), sin(3*t) - sin(t)], [0, sin(3*t)]])
A = Matrix([[2, 1],[1, 2]])
assert (pi * A / 6).analytic_func(cos(x), x) == Matrix([[sqrt(3)/4, -sqrt(3)/4], [-sqrt(3)/4, sqrt(3)/4]])
raises(ValueError, lambda : zeros(5).analytic_func(log(x), x))
raises(ValueError, lambda : (A*x).analytic_func(log(x), x))
A = Matrix([[0, -1, -2, 3], [0, -1, -2, 3], [0, 1, 0, -1], [0, 0, -1, 1]])
assert A.analytic_func(exp(x), x) == A.exp()
raises(ValueError, lambda : A.analytic_func(sqrt(x), x))
A = Matrix([[41, 12],[12, 34]])
assert simplify(A.analytic_func(sqrt(x), x)**2) == A
A = Matrix([[3, -12, 4], [-1, 0, -2], [-1, 5, -1]])
assert simplify(A.analytic_func(nthroot(x, 3), x)**3) == A
A = Matrix([[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]])
assert A.analytic_func(exp(x), x) == A.exp()
A = Matrix([[0, 2, 1, 6], [0, 0, 1, 2], [0, 0, 0, 3], [0, 0, 0, 0]])
assert A.analytic_func(exp(x*t), x) == expand(simplify((A*t).exp()))
def test_issue_19809():
if pyodide_js:
skip("can't run on pyodide")
def f():
assert _dotprodsimp_state.state == None
m = Matrix([[1]])
m = m * m
return True
with dotprodsimp(True):
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(f)
assert future.result()
def test_issue_23276():
M = Matrix([x, y])
assert integrate(M, (x, 0, 1), (y, 0, 1)) == Matrix([
[S.Half],
[S.Half]])
|
c43674d1bb60a6385e584b79e7b21472834a6595477f08787304942a481ad52a | from __future__ import annotations
from functools import wraps
from sympy.core import S, Integer, Basic, Mul, Add
from sympy.core.assumptions import check_assumptions
from sympy.core.decorators import call_highest_priority
from sympy.core.expr import Expr, ExprBuilder
from sympy.core.logic import FuzzyBool
from sympy.core.symbol import Str, Dummy, symbols, Symbol
from sympy.core.sympify import SympifyError, _sympify
from sympy.external.gmpy import SYMPY_INTS
from sympy.functions import conjugate, adjoint
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.matrices.common import NonSquareMatrixError
from sympy.matrices.matrices import MatrixKind, MatrixBase
from sympy.multipledispatch import dispatch
from sympy.utilities.misc import filldedent
def _sympifyit(arg, retval=None):
# This version of _sympifyit sympifies MutableMatrix objects
def deco(func):
@wraps(func)
def __sympifyit_wrapper(a, b):
try:
b = _sympify(b)
return func(a, b)
except SympifyError:
return retval
return __sympifyit_wrapper
return deco
class MatrixExpr(Expr):
"""Superclass for Matrix Expressions
MatrixExprs represent abstract matrices, linear transformations represented
within a particular basis.
Examples
========
>>> from sympy import MatrixSymbol
>>> A = MatrixSymbol('A', 3, 3)
>>> y = MatrixSymbol('y', 3, 1)
>>> x = (A.T*A).I * A * y
See Also
========
MatrixSymbol, MatAdd, MatMul, Transpose, Inverse
"""
__slots__: tuple[str, ...] = ()
# Should not be considered iterable by the
# sympy.utilities.iterables.iterable function. Subclass that actually are
# iterable (i.e., explicit matrices) should set this to True.
_iterable = False
_op_priority = 11.0
is_Matrix: bool = True
is_MatrixExpr: bool = True
is_Identity: FuzzyBool = None
is_Inverse = False
is_Transpose = False
is_ZeroMatrix = False
is_MatAdd = False
is_MatMul = False
is_commutative = False
is_number = False
is_symbol = False
is_scalar = False
kind: MatrixKind = MatrixKind()
def __new__(cls, *args, **kwargs):
args = map(_sympify, args)
return Basic.__new__(cls, *args, **kwargs)
# The following is adapted from the core Expr object
@property
def shape(self) -> tuple[Expr, Expr]:
raise NotImplementedError
@property
def _add_handler(self):
return MatAdd
@property
def _mul_handler(self):
return MatMul
def __neg__(self):
return MatMul(S.NegativeOne, self).doit()
def __abs__(self):
raise NotImplementedError
@_sympifyit('other', NotImplemented)
@call_highest_priority('__radd__')
def __add__(self, other):
return MatAdd(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__add__')
def __radd__(self, other):
return MatAdd(other, self).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rsub__')
def __sub__(self, other):
return MatAdd(self, -other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__sub__')
def __rsub__(self, other):
return MatAdd(other, -self).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rmul__')
def __mul__(self, other):
return MatMul(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rmul__')
def __matmul__(self, other):
return MatMul(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return MatMul(other, self).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__mul__')
def __rmatmul__(self, other):
return MatMul(other, self).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rpow__')
def __pow__(self, other):
return MatPow(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__pow__')
def __rpow__(self, other):
raise NotImplementedError("Matrix Power not defined")
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rtruediv__')
def __truediv__(self, other):
return self * other**S.NegativeOne
@_sympifyit('other', NotImplemented)
@call_highest_priority('__truediv__')
def __rtruediv__(self, other):
raise NotImplementedError()
#return MatMul(other, Pow(self, S.NegativeOne))
@property
def rows(self):
return self.shape[0]
@property
def cols(self):
return self.shape[1]
@property
def is_square(self) -> bool | None:
rows, cols = self.shape
if isinstance(rows, Integer) and isinstance(cols, Integer):
return rows == cols
if rows == cols:
return True
return None
def _eval_conjugate(self):
from sympy.matrices.expressions.adjoint import Adjoint
return Adjoint(Transpose(self))
def as_real_imag(self, deep=True, **hints):
return self._eval_as_real_imag()
def _eval_as_real_imag(self):
real = S.Half * (self + self._eval_conjugate())
im = (self - self._eval_conjugate())/(2*S.ImaginaryUnit)
return (real, im)
def _eval_inverse(self):
return Inverse(self)
def _eval_determinant(self):
return Determinant(self)
def _eval_transpose(self):
return Transpose(self)
def _eval_power(self, exp):
"""
Override this in sub-classes to implement simplification of powers. The cases where the exponent
is -1, 0, 1 are already covered in MatPow.doit(), so implementations can exclude these cases.
"""
return MatPow(self, exp)
def _eval_simplify(self, **kwargs):
if self.is_Atom:
return self
else:
from sympy.simplify import simplify
return self.func(*[simplify(x, **kwargs) for x in self.args])
def _eval_adjoint(self):
from sympy.matrices.expressions.adjoint import Adjoint
return Adjoint(self)
def _eval_derivative_n_times(self, x, n):
return Basic._eval_derivative_n_times(self, x, n)
def _eval_derivative(self, x):
# `x` is a scalar:
if self.has(x):
# See if there are other methods using it:
return super()._eval_derivative(x)
else:
return ZeroMatrix(*self.shape)
@classmethod
def _check_dim(cls, dim):
"""Helper function to check invalid matrix dimensions"""
ok = check_assumptions(dim, integer=True, nonnegative=True)
if ok is False:
raise ValueError(
"The dimension specification {} should be "
"a nonnegative integer.".format(dim))
def _entry(self, i, j, **kwargs):
raise NotImplementedError(
"Indexing not implemented for %s" % self.__class__.__name__)
def adjoint(self):
return adjoint(self)
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product."""
return S.One, self
def conjugate(self):
return conjugate(self)
def transpose(self):
from sympy.matrices.expressions.transpose import transpose
return transpose(self)
@property
def T(self):
'''Matrix transposition'''
return self.transpose()
def inverse(self):
if self.is_square is False:
raise NonSquareMatrixError('Inverse of non-square matrix')
return self._eval_inverse()
def inv(self):
return self.inverse()
def det(self):
from sympy.matrices.expressions.determinant import det
return det(self)
@property
def I(self):
return self.inverse()
def valid_index(self, i, j):
def is_valid(idx):
return isinstance(idx, (int, Integer, Symbol, Expr))
return (is_valid(i) and is_valid(j) and
(self.rows is None or
(i >= -self.rows) != False and (i < self.rows) != False) and
(j >= -self.cols) != False and (j < self.cols) != False)
def __getitem__(self, key):
if not isinstance(key, tuple) and isinstance(key, slice):
from sympy.matrices.expressions.slice import MatrixSlice
return MatrixSlice(self, key, (0, None, 1))
if isinstance(key, tuple) and len(key) == 2:
i, j = key
if isinstance(i, slice) or isinstance(j, slice):
from sympy.matrices.expressions.slice import MatrixSlice
return MatrixSlice(self, i, j)
i, j = _sympify(i), _sympify(j)
if self.valid_index(i, j) != False:
return self._entry(i, j)
else:
raise IndexError("Invalid indices (%s, %s)" % (i, j))
elif isinstance(key, (SYMPY_INTS, Integer)):
# row-wise decomposition of matrix
rows, cols = self.shape
# allow single indexing if number of columns is known
if not isinstance(cols, Integer):
raise IndexError(filldedent('''
Single indexing is only supported when the number
of columns is known.'''))
key = _sympify(key)
i = key // cols
j = key % cols
if self.valid_index(i, j) != False:
return self._entry(i, j)
else:
raise IndexError("Invalid index %s" % key)
elif isinstance(key, (Symbol, Expr)):
raise IndexError(filldedent('''
Only integers may be used when addressing the matrix
with a single index.'''))
raise IndexError("Invalid index, wanted %s[i,j]" % self)
def _is_shape_symbolic(self) -> bool:
return (not isinstance(self.rows, (SYMPY_INTS, Integer))
or not isinstance(self.cols, (SYMPY_INTS, Integer)))
def as_explicit(self):
"""
Returns a dense Matrix with elements represented explicitly
Returns an object of type ImmutableDenseMatrix.
Examples
========
>>> from sympy import Identity
>>> I = Identity(3)
>>> I
I
>>> I.as_explicit()
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
See Also
========
as_mutable: returns mutable Matrix type
"""
if self._is_shape_symbolic():
raise ValueError(
'Matrix with symbolic shape '
'cannot be represented explicitly.')
from sympy.matrices.immutable import ImmutableDenseMatrix
return ImmutableDenseMatrix([[self[i, j]
for j in range(self.cols)]
for i in range(self.rows)])
def as_mutable(self):
"""
Returns a dense, mutable matrix with elements represented explicitly
Examples
========
>>> from sympy import Identity
>>> I = Identity(3)
>>> I
I
>>> I.shape
(3, 3)
>>> I.as_mutable()
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
See Also
========
as_explicit: returns ImmutableDenseMatrix
"""
return self.as_explicit().as_mutable()
def __array__(self):
from numpy import empty
a = empty(self.shape, dtype=object)
for i in range(self.rows):
for j in range(self.cols):
a[i, j] = self[i, j]
return a
def equals(self, other):
"""
Test elementwise equality between matrices, potentially of different
types
>>> from sympy import Identity, eye
>>> Identity(3).equals(eye(3))
True
"""
return self.as_explicit().equals(other)
def canonicalize(self):
return self
def as_coeff_mmul(self):
return S.One, MatMul(self)
@staticmethod
def from_index_summation(expr, first_index=None, last_index=None, dimensions=None):
r"""
Parse expression of matrices with explicitly summed indices into a
matrix expression without indices, if possible.
This transformation expressed in mathematical notation:
`\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}`
Optional parameter ``first_index``: specify which free index to use as
the index starting the expression.
Examples
========
>>> from sympy import MatrixSymbol, MatrixExpr, Sum
>>> from sympy.abc import i, j, k, l, N
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
A*B
Transposition is detected:
>>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
A.T*B
Detect the trace:
>>> expr = Sum(A[i, i], (i, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
Trace(A)
More complicated expressions:
>>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
A*B.T*A.T
"""
from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array
from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
first_indices = []
if first_index is not None:
first_indices.append(first_index)
if last_index is not None:
first_indices.append(last_index)
arr = convert_indexed_to_array(expr, first_indices=first_indices)
return convert_array_to_matrix(arr)
def applyfunc(self, func):
from .applyfunc import ElementwiseApplyFunction
return ElementwiseApplyFunction(func, self)
@dispatch(MatrixExpr, Expr)
def _eval_is_eq(lhs, rhs): # noqa:F811
return False
@dispatch(MatrixExpr, MatrixExpr) # type: ignore
def _eval_is_eq(lhs, rhs): # noqa:F811
if lhs.shape != rhs.shape:
return False
if (lhs - rhs).is_ZeroMatrix:
return True
def get_postprocessor(cls):
def _postprocessor(expr):
# To avoid circular imports, we can't have MatMul/MatAdd on the top level
mat_class = {Mul: MatMul, Add: MatAdd}[cls]
nonmatrices = []
matrices = []
for term in expr.args:
if isinstance(term, MatrixExpr):
matrices.append(term)
else:
nonmatrices.append(term)
if not matrices:
return cls._from_args(nonmatrices)
if nonmatrices:
if cls == Mul:
for i in range(len(matrices)):
if not matrices[i].is_MatrixExpr:
# If one of the matrices explicit, absorb the scalar into it
# (doit will combine all explicit matrices into one, so it
# doesn't matter which)
matrices[i] = matrices[i].__mul__(cls._from_args(nonmatrices))
nonmatrices = []
break
else:
# Maintain the ability to create Add(scalar, matrix) without
# raising an exception. That way different algorithms can
# replace matrix expressions with non-commutative symbols to
# manipulate them like non-commutative scalars.
return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)])
if mat_class == MatAdd:
return mat_class(*matrices).doit(deep=False)
return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False)
return _postprocessor
Basic._constructor_postprocessor_mapping[MatrixExpr] = {
"Mul": [get_postprocessor(Mul)],
"Add": [get_postprocessor(Add)],
}
def _matrix_derivative(expr, x, old_algorithm=False):
if isinstance(expr, MatrixBase) or isinstance(x, MatrixBase):
# Do not use array expressions for explicit matrices:
old_algorithm = True
if old_algorithm:
return _matrix_derivative_old_algorithm(expr, x)
from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive
from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
array_expr = convert_matrix_to_array(expr)
diff_array_expr = array_derive(array_expr, x)
diff_matrix_expr = convert_array_to_matrix(diff_array_expr)
return diff_matrix_expr
def _matrix_derivative_old_algorithm(expr, x):
from sympy.tensor.array.array_derivatives import ArrayDerivative
lines = expr._eval_derivative_matrix_lines(x)
parts = [i.build() for i in lines]
from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
parts = [[convert_array_to_matrix(j) for j in i] for i in parts]
def _get_shape(elem):
if isinstance(elem, MatrixExpr):
return elem.shape
return 1, 1
def get_rank(parts):
return sum([j not in (1, None) for i in parts for j in _get_shape(i)])
ranks = [get_rank(i) for i in parts]
rank = ranks[0]
def contract_one_dims(parts):
if len(parts) == 1:
return parts[0]
else:
p1, p2 = parts[:2]
if p2.is_Matrix:
p2 = p2.T
if p1 == Identity(1):
pbase = p2
elif p2 == Identity(1):
pbase = p1
else:
pbase = p1*p2
if len(parts) == 2:
return pbase
else: # len(parts) > 2
if pbase.is_Matrix:
raise ValueError("")
return pbase*Mul.fromiter(parts[2:])
if rank <= 2:
return Add.fromiter([contract_one_dims(i) for i in parts])
return ArrayDerivative(expr, x)
class MatrixElement(Expr):
parent = property(lambda self: self.args[0])
i = property(lambda self: self.args[1])
j = property(lambda self: self.args[2])
_diff_wrt = True
is_symbol = True
is_commutative = True
def __new__(cls, name, n, m):
n, m = map(_sympify, (n, m))
from sympy.matrices.matrices import MatrixBase
if isinstance(name, str):
name = Symbol(name)
else:
if isinstance(name, MatrixBase):
if n.is_Integer and m.is_Integer:
return name[n, m]
name = _sympify(name) # change mutable into immutable
else:
name = _sympify(name)
if not isinstance(name.kind, MatrixKind):
raise TypeError("First argument of MatrixElement should be a matrix")
if not getattr(name, 'valid_index', lambda n, m: True)(n, m):
raise IndexError('indices out of range')
obj = Expr.__new__(cls, name, n, m)
return obj
@property
def symbol(self):
return self.args[0]
def doit(self, **hints):
deep = hints.get('deep', True)
if deep:
args = [arg.doit(**hints) for arg in self.args]
else:
args = self.args
return args[0][args[1], args[2]]
@property
def indices(self):
return self.args[1:]
def _eval_derivative(self, v):
if not isinstance(v, MatrixElement):
from sympy.matrices.matrices import MatrixBase
if isinstance(self.parent, MatrixBase):
return self.parent.diff(v)[self.i, self.j]
return S.Zero
M = self.args[0]
m, n = self.parent.shape
if M == v.args[0]:
return KroneckerDelta(self.args[1], v.args[1], (0, m-1)) * \
KroneckerDelta(self.args[2], v.args[2], (0, n-1))
if isinstance(M, Inverse):
from sympy.concrete.summations import Sum
i, j = self.args[1:]
i1, i2 = symbols("z1, z2", cls=Dummy)
Y = M.args[0]
r1, r2 = Y.shape
return -Sum(M[i, i1]*Y[i1, i2].diff(v)*M[i2, j], (i1, 0, r1-1), (i2, 0, r2-1))
if self.has(v.args[0]):
return None
return S.Zero
class MatrixSymbol(MatrixExpr):
"""Symbolic representation of a Matrix object
Creates a SymPy Symbol to represent a Matrix. This matrix has a shape and
can be included in Matrix Expressions
Examples
========
>>> from sympy import MatrixSymbol, Identity
>>> A = MatrixSymbol('A', 3, 4) # A 3 by 4 Matrix
>>> B = MatrixSymbol('B', 4, 3) # A 4 by 3 Matrix
>>> A.shape
(3, 4)
>>> 2*A*B + Identity(3)
I + 2*A*B
"""
is_commutative = False
is_symbol = True
_diff_wrt = True
def __new__(cls, name, n, m):
n, m = _sympify(n), _sympify(m)
cls._check_dim(m)
cls._check_dim(n)
if isinstance(name, str):
name = Str(name)
obj = Basic.__new__(cls, name, n, m)
return obj
@property
def shape(self):
return self.args[1], self.args[2]
@property
def name(self):
return self.args[0].name
def _entry(self, i, j, **kwargs):
return MatrixElement(self, i, j)
@property
def free_symbols(self):
return {self}
def _eval_simplify(self, **kwargs):
return self
def _eval_derivative(self, x):
# x is a scalar:
return ZeroMatrix(self.shape[0], self.shape[1])
def _eval_derivative_matrix_lines(self, x):
if self != x:
first = ZeroMatrix(x.shape[0], self.shape[0]) if self.shape[0] != 1 else S.Zero
second = ZeroMatrix(x.shape[1], self.shape[1]) if self.shape[1] != 1 else S.Zero
return [_LeftRightArgs(
[first, second],
)]
else:
first = Identity(self.shape[0]) if self.shape[0] != 1 else S.One
second = Identity(self.shape[1]) if self.shape[1] != 1 else S.One
return [_LeftRightArgs(
[first, second],
)]
def matrix_symbols(expr):
return [sym for sym in expr.free_symbols if sym.is_Matrix]
class _LeftRightArgs:
r"""
Helper class to compute matrix derivatives.
The logic: when an expression is derived by a matrix `X_{mn}`, two lines of
matrix multiplications are created: the one contracted to `m` (first line),
and the one contracted to `n` (second line).
Transposition flips the side by which new matrices are connected to the
lines.
The trace connects the end of the two lines.
"""
def __init__(self, lines, higher=S.One):
self._lines = [i for i in lines]
self._first_pointer_parent = self._lines
self._first_pointer_index = 0
self._first_line_index = 0
self._second_pointer_parent = self._lines
self._second_pointer_index = 1
self._second_line_index = 1
self.higher = higher
@property
def first_pointer(self):
return self._first_pointer_parent[self._first_pointer_index]
@first_pointer.setter
def first_pointer(self, value):
self._first_pointer_parent[self._first_pointer_index] = value
@property
def second_pointer(self):
return self._second_pointer_parent[self._second_pointer_index]
@second_pointer.setter
def second_pointer(self, value):
self._second_pointer_parent[self._second_pointer_index] = value
def __repr__(self):
built = [self._build(i) for i in self._lines]
return "_LeftRightArgs(lines=%s, higher=%s)" % (
built,
self.higher,
)
def transpose(self):
self._first_pointer_parent, self._second_pointer_parent = self._second_pointer_parent, self._first_pointer_parent
self._first_pointer_index, self._second_pointer_index = self._second_pointer_index, self._first_pointer_index
self._first_line_index, self._second_line_index = self._second_line_index, self._first_line_index
return self
@staticmethod
def _build(expr):
if isinstance(expr, ExprBuilder):
return expr.build()
if isinstance(expr, list):
if len(expr) == 1:
return expr[0]
else:
return expr[0](*[_LeftRightArgs._build(i) for i in expr[1]])
else:
return expr
def build(self):
data = [self._build(i) for i in self._lines]
if self.higher != 1:
data += [self._build(self.higher)]
data = [i for i in data]
return data
def matrix_form(self):
if self.first != 1 and self.higher != 1:
raise ValueError("higher dimensional array cannot be represented")
def _get_shape(elem):
if isinstance(elem, MatrixExpr):
return elem.shape
return (None, None)
if _get_shape(self.first)[1] != _get_shape(self.second)[1]:
# Remove one-dimensional identity matrices:
# (this is needed by `a.diff(a)` where `a` is a vector)
if _get_shape(self.second) == (1, 1):
return self.first*self.second[0, 0]
if _get_shape(self.first) == (1, 1):
return self.first[1, 1]*self.second.T
raise ValueError("incompatible shapes")
if self.first != 1:
return self.first*self.second.T
else:
return self.higher
def rank(self):
"""
Number of dimensions different from trivial (warning: not related to
matrix rank).
"""
rank = 0
if self.first != 1:
rank += sum([i != 1 for i in self.first.shape])
if self.second != 1:
rank += sum([i != 1 for i in self.second.shape])
if self.higher != 1:
rank += 2
return rank
def _multiply_pointer(self, pointer, other):
from ...tensor.array.expressions.array_expressions import ArrayTensorProduct
from ...tensor.array.expressions.array_expressions import ArrayContraction
subexpr = ExprBuilder(
ArrayContraction,
[
ExprBuilder(
ArrayTensorProduct,
[
pointer,
other
]
),
(1, 2)
],
validator=ArrayContraction._validate
)
return subexpr
def append_first(self, other):
self.first_pointer *= other
def append_second(self, other):
self.second_pointer *= other
def _make_matrix(x):
from sympy.matrices.immutable import ImmutableDenseMatrix
if isinstance(x, MatrixExpr):
return x
return ImmutableDenseMatrix([[x]])
from .matmul import MatMul
from .matadd import MatAdd
from .matpow import MatPow
from .transpose import Transpose
from .inverse import Inverse
from .special import ZeroMatrix, Identity
from .determinant import Determinant
|
f6605e6806435fbf896d8b3ab4c0a536e183ca011354dfdd0974a51e6c808708 | """
Some examples have been taken from:
http://www.math.uwaterloo.ca/~hwolkowi//matrixcookbook.pdf
"""
from sympy import KroneckerProduct
from sympy.combinatorics import Permutation
from sympy.concrete.summations import Sum
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, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.matrices.expressions.determinant import Determinant
from sympy.matrices.expressions.diagonal import DiagMatrix
from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct, hadamard_product)
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import OneMatrix
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions.matadd import MatAdd
from sympy.matrices.expressions.matmul import MatMul
from sympy.matrices.expressions.special import (Identity, ZeroMatrix)
from sympy.tensor.array.array_derivatives import ArrayDerivative
from sympy.matrices.expressions import hadamard_power
from sympy.tensor.array.expressions.array_expressions import ArrayAdd, ArrayTensorProduct, PermuteDims
i, j, k = symbols("i j k")
m, n = symbols("m n")
X = MatrixSymbol("X", k, k)
x = MatrixSymbol("x", k, 1)
y = MatrixSymbol("y", k, 1)
A = MatrixSymbol("A", k, k)
B = MatrixSymbol("B", k, k)
C = MatrixSymbol("C", k, k)
D = MatrixSymbol("D", k, k)
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
c = MatrixSymbol("c", k, 1)
d = MatrixSymbol("d", k, 1)
KDelta = lambda i, j: KroneckerDelta(i, j, (0, k-1))
def _check_derivative_with_explicit_matrix(expr, x, diffexpr, dim=2):
# TODO: this is commented because it slows down the tests.
return
expr = expr.xreplace({k: dim})
x = x.xreplace({k: dim})
diffexpr = diffexpr.xreplace({k: dim})
expr = expr.as_explicit()
x = x.as_explicit()
diffexpr = diffexpr.as_explicit()
assert expr.diff(x).reshape(*diffexpr.shape).tomatrix() == diffexpr
def test_matrix_derivative_by_scalar():
assert A.diff(i) == ZeroMatrix(k, k)
assert (A*(X + B)*c).diff(i) == ZeroMatrix(k, 1)
assert x.diff(i) == ZeroMatrix(k, 1)
assert (x.T*y).diff(i) == ZeroMatrix(1, 1)
assert (x*x.T).diff(i) == ZeroMatrix(k, k)
assert (x + y).diff(i) == ZeroMatrix(k, 1)
assert hadamard_power(x, 2).diff(i) == ZeroMatrix(k, 1)
assert hadamard_power(x, i).diff(i).dummy_eq(
HadamardProduct(x.applyfunc(log), HadamardPower(x, i)))
assert hadamard_product(x, y).diff(i) == ZeroMatrix(k, 1)
assert hadamard_product(i*OneMatrix(k, 1), x, y).diff(i) == hadamard_product(x, y)
assert (i*x).diff(i) == x
assert (sin(i)*A*B*x).diff(i) == cos(i)*A*B*x
assert x.applyfunc(sin).diff(i) == ZeroMatrix(k, 1)
assert Trace(i**2*X).diff(i) == 2*i*Trace(X)
mu = symbols("mu")
expr = (2*mu*x)
assert expr.diff(x) == 2*mu*Identity(k)
def test_one_matrix():
assert MatMul(x.T, OneMatrix(k, 1)).diff(x) == OneMatrix(k, 1)
def test_matrix_derivative_non_matrix_result():
# This is a 4-dimensional array:
I = Identity(k)
AdA = PermuteDims(ArrayTensorProduct(I, I), Permutation(3)(1, 2))
assert A.diff(A) == AdA
assert A.T.diff(A) == PermuteDims(ArrayTensorProduct(I, I), Permutation(3)(1, 2, 3))
assert (2*A).diff(A) == PermuteDims(ArrayTensorProduct(2*I, I), Permutation(3)(1, 2))
assert MatAdd(A, A).diff(A) == ArrayAdd(AdA, AdA)
assert (A + B).diff(A) == AdA
def test_matrix_derivative_trivial_cases():
# Cookbook example 33:
# TODO: find a way to represent a four-dimensional zero-array:
assert X.diff(A) == ArrayDerivative(X, A)
def test_matrix_derivative_with_inverse():
# Cookbook example 61:
expr = a.T*Inverse(X)*b
assert expr.diff(X) == -Inverse(X).T*a*b.T*Inverse(X).T
# Cookbook example 62:
expr = Determinant(Inverse(X))
# Not implemented yet:
# assert expr.diff(X) == -Determinant(X.inv())*(X.inv()).T
# Cookbook example 63:
expr = Trace(A*Inverse(X)*B)
assert expr.diff(X) == -(X**(-1)*B*A*X**(-1)).T
# Cookbook example 64:
expr = Trace(Inverse(X + A))
assert expr.diff(X) == -(Inverse(X + A)).T**2
def test_matrix_derivative_vectors_and_scalars():
assert x.diff(x) == Identity(k)
assert x[i, 0].diff(x[m, 0]).doit() == KDelta(m, i)
assert x.T.diff(x) == Identity(k)
# Cookbook example 69:
expr = x.T*a
assert expr.diff(x) == a
assert expr[0, 0].diff(x[m, 0]).doit() == a[m, 0]
expr = a.T*x
assert expr.diff(x) == a
# Cookbook example 70:
expr = a.T*X*b
assert expr.diff(X) == a*b.T
# Cookbook example 71:
expr = a.T*X.T*b
assert expr.diff(X) == b*a.T
# Cookbook example 72:
expr = a.T*X*a
assert expr.diff(X) == a*a.T
expr = a.T*X.T*a
assert expr.diff(X) == a*a.T
# Cookbook example 77:
expr = b.T*X.T*X*c
assert expr.diff(X) == X*b*c.T + X*c*b.T
# Cookbook example 78:
expr = (B*x + b).T*C*(D*x + d)
assert expr.diff(x) == B.T*C*(D*x + d) + D.T*C.T*(B*x + b)
# Cookbook example 81:
expr = x.T*B*x
assert expr.diff(x) == B*x + B.T*x
# Cookbook example 82:
expr = b.T*X.T*D*X*c
assert expr.diff(X) == D.T*X*b*c.T + D*X*c*b.T
# Cookbook example 83:
expr = (X*b + c).T*D*(X*b + c)
assert expr.diff(X) == D*(X*b + c)*b.T + D.T*(X*b + c)*b.T
assert str(expr[0, 0].diff(X[m, n]).doit()) == \
'b[n, 0]*Sum((c[_i_1, 0] + Sum(X[_i_1, _i_3]*b[_i_3, 0], (_i_3, 0, k - 1)))*D[_i_1, m], (_i_1, 0, k - 1)) + Sum((c[_i_2, 0] + Sum(X[_i_2, _i_4]*b[_i_4, 0], (_i_4, 0, k - 1)))*D[m, _i_2]*b[n, 0], (_i_2, 0, k - 1))'
# See https://github.com/sympy/sympy/issues/16504#issuecomment-1018339957
expr = x*x.T*x
I = Identity(k)
assert expr.diff(x) == KroneckerProduct(I, x.T*x) + 2*x*x.T
def test_matrix_derivatives_of_traces():
expr = Trace(A)*A
I = Identity(k)
assert expr.diff(A) == ArrayAdd(ArrayTensorProduct(I, A), PermuteDims(ArrayTensorProduct(Trace(A)*I, I), Permutation(3)(1, 2)))
assert expr[i, j].diff(A[m, n]).doit() == (
KDelta(i, m)*KDelta(j, n)*Trace(A) +
KDelta(m, n)*A[i, j]
)
## First order:
# Cookbook example 99:
expr = Trace(X)
assert expr.diff(X) == Identity(k)
assert expr.rewrite(Sum).diff(X[m, n]).doit() == KDelta(m, n)
# Cookbook example 100:
expr = Trace(X*A)
assert expr.diff(X) == A.T
assert expr.rewrite(Sum).diff(X[m, n]).doit() == A[n, m]
# Cookbook example 101:
expr = Trace(A*X*B)
assert expr.diff(X) == A.T*B.T
assert expr.rewrite(Sum).diff(X[m, n]).doit().dummy_eq((A.T*B.T)[m, n])
# Cookbook example 102:
expr = Trace(A*X.T*B)
assert expr.diff(X) == B*A
# Cookbook example 103:
expr = Trace(X.T*A)
assert expr.diff(X) == A
# Cookbook example 104:
expr = Trace(A*X.T)
assert expr.diff(X) == A
# Cookbook example 105:
# TODO: TensorProduct is not supported
#expr = Trace(TensorProduct(A, X))
#assert expr.diff(X) == Trace(A)*Identity(k)
## Second order:
# Cookbook example 106:
expr = Trace(X**2)
assert expr.diff(X) == 2*X.T
# Cookbook example 107:
expr = Trace(X**2*B)
assert expr.diff(X) == (X*B + B*X).T
expr = Trace(MatMul(X, X, B))
assert expr.diff(X) == (X*B + B*X).T
# Cookbook example 108:
expr = Trace(X.T*B*X)
assert expr.diff(X) == B*X + B.T*X
# Cookbook example 109:
expr = Trace(B*X*X.T)
assert expr.diff(X) == B*X + B.T*X
# Cookbook example 110:
expr = Trace(X*X.T*B)
assert expr.diff(X) == B*X + B.T*X
# Cookbook example 111:
expr = Trace(X*B*X.T)
assert expr.diff(X) == X*B.T + X*B
# Cookbook example 112:
expr = Trace(B*X.T*X)
assert expr.diff(X) == X*B.T + X*B
# Cookbook example 113:
expr = Trace(X.T*X*B)
assert expr.diff(X) == X*B.T + X*B
# Cookbook example 114:
expr = Trace(A*X*B*X)
assert expr.diff(X) == A.T*X.T*B.T + B.T*X.T*A.T
# Cookbook example 115:
expr = Trace(X.T*X)
assert expr.diff(X) == 2*X
expr = Trace(X*X.T)
assert expr.diff(X) == 2*X
# Cookbook example 116:
expr = Trace(B.T*X.T*C*X*B)
assert expr.diff(X) == C.T*X*B*B.T + C*X*B*B.T
# Cookbook example 117:
expr = Trace(X.T*B*X*C)
assert expr.diff(X) == B*X*C + B.T*X*C.T
# Cookbook example 118:
expr = Trace(A*X*B*X.T*C)
assert expr.diff(X) == A.T*C.T*X*B.T + C*A*X*B
# Cookbook example 119:
expr = Trace((A*X*B + C)*(A*X*B + C).T)
assert expr.diff(X) == 2*A.T*(A*X*B + C)*B.T
# Cookbook example 120:
# TODO: no support for TensorProduct.
# expr = Trace(TensorProduct(X, X))
# expr = Trace(X)*Trace(X)
# expr.diff(X) == 2*Trace(X)*Identity(k)
# Higher Order
# Cookbook example 121:
expr = Trace(X**k)
#assert expr.diff(X) == k*(X**(k-1)).T
# Cookbook example 122:
expr = Trace(A*X**k)
#assert expr.diff(X) == # Needs indices
# Cookbook example 123:
expr = Trace(B.T*X.T*C*X*X.T*C*X*B)
assert expr.diff(X) == C*X*X.T*C*X*B*B.T + C.T*X*B*B.T*X.T*C.T*X + C*X*B*B.T*X.T*C*X + C.T*X*X.T*C.T*X*B*B.T
# Other
# Cookbook example 124:
expr = Trace(A*X**(-1)*B)
assert expr.diff(X) == -Inverse(X).T*A.T*B.T*Inverse(X).T
# Cookbook example 125:
expr = Trace(Inverse(X.T*C*X)*A)
# Warning: result in the cookbook is equivalent if B and C are symmetric:
assert expr.diff(X) == - X.inv().T*A.T*X.inv()*C.inv().T*X.inv().T - X.inv().T*A*X.inv()*C.inv()*X.inv().T
# Cookbook example 126:
expr = Trace((X.T*C*X).inv()*(X.T*B*X))
assert expr.diff(X) == -2*C*X*(X.T*C*X).inv()*X.T*B*X*(X.T*C*X).inv() + 2*B*X*(X.T*C*X).inv()
# Cookbook example 127:
expr = Trace((A + X.T*C*X).inv()*(X.T*B*X))
# Warning: result in the cookbook is equivalent if B and C are symmetric:
assert expr.diff(X) == B*X*Inverse(A + X.T*C*X) - C*X*Inverse(A + X.T*C*X)*X.T*B*X*Inverse(A + X.T*C*X) - C.T*X*Inverse(A.T + (C*X).T*X)*X.T*B.T*X*Inverse(A.T + (C*X).T*X) + B.T*X*Inverse(A.T + (C*X).T*X)
def test_derivatives_of_complicated_matrix_expr():
expr = a.T*(A*X*(X.T*B + X*A) + B.T*X.T*(a*b.T*(X*D*X.T + X*(X.T*B + A*X)*D*B - X.T*C.T*A)*B + B*(X*D.T + B*A*X*A.T - 3*X*D))*B + 42*X*B*X.T*A.T*(X + X.T))*b
result = (B*(B*A*X*A.T - 3*X*D + X*D.T) + a*b.T*(X*(A*X + X.T*B)*D*B + X*D*X.T - X.T*C.T*A)*B)*B*b*a.T*B.T + B**2*b*a.T*B.T*X.T*a*b.T*X*D + 42*A*X*B.T*X.T*a*b.T + B*D*B**3*b*a.T*B.T*X.T*a*b.T*X + B*b*a.T*A*X + a*b.T*(42*X + 42*X.T)*A*X*B.T + b*a.T*X*B*a*b.T*B.T**2*X*D.T + b*a.T*X*B*a*b.T*B.T**3*D.T*(B.T*X + X.T*A.T) + 42*b*a.T*X*B*X.T*A.T + A.T*(42*X + 42*X.T)*b*a.T*X*B + A.T*B.T**2*X*B*a*b.T*B.T*A + A.T*a*b.T*(A.T*X.T + B.T*X) + A.T*X.T*b*a.T*X*B*a*b.T*B.T**3*D.T + B.T*X*B*a*b.T*B.T*D - 3*B.T*X*B*a*b.T*B.T*D.T - C.T*A*B**2*b*a.T*B.T*X.T*a*b.T + X.T*A.T*a*b.T*A.T
assert expr.diff(X) == result
def test_mixed_deriv_mixed_expressions():
expr = 3*Trace(A)
assert expr.diff(A) == 3*Identity(k)
expr = k
deriv = expr.diff(A)
assert isinstance(deriv, ZeroMatrix)
assert deriv == ZeroMatrix(k, k)
expr = Trace(A)**2
assert expr.diff(A) == (2*Trace(A))*Identity(k)
expr = Trace(A)*A
I = Identity(k)
assert expr.diff(A) == ArrayAdd(ArrayTensorProduct(I, A), PermuteDims(ArrayTensorProduct(Trace(A)*I, I), Permutation(3)(1, 2)))
expr = Trace(Trace(A)*A)
assert expr.diff(A) == (2*Trace(A))*Identity(k)
expr = Trace(Trace(Trace(A)*A)*A)
assert expr.diff(A) == (3*Trace(A)**2)*Identity(k)
def test_derivatives_matrix_norms():
expr = x.T*y
assert expr.diff(x) == y
assert expr[0, 0].diff(x[m, 0]).doit() == y[m, 0]
expr = (x.T*y)**S.Half
assert expr.diff(x) == y/(2*sqrt(x.T*y))
expr = (x.T*x)**S.Half
assert expr.diff(x) == x*(x.T*x)**Rational(-1, 2)
expr = (c.T*a*x.T*b)**S.Half
assert expr.diff(x) == b*a.T*c/sqrt(c.T*a*x.T*b)/2
expr = (c.T*a*x.T*b)**Rational(1, 3)
assert expr.diff(x) == b*a.T*c*(c.T*a*x.T*b)**Rational(-2, 3)/3
expr = (a.T*X*b)**S.Half
assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*b.T
expr = d.T*x*(a.T*X*b)**S.Half*y.T*c
assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*x.T*d*y.T*c*b.T
def test_derivatives_elementwise_applyfunc():
expr = x.applyfunc(tan)
assert expr.diff(x).dummy_eq(
DiagMatrix(x.applyfunc(lambda x: tan(x)**2 + 1)))
assert expr[i, 0].diff(x[m, 0]).doit() == (tan(x[i, 0])**2 + 1)*KDelta(i, m)
_check_derivative_with_explicit_matrix(expr, x, expr.diff(x))
expr = (i**2*x).applyfunc(sin)
assert expr.diff(i).dummy_eq(
HadamardProduct((2*i)*x, (i**2*x).applyfunc(cos)))
assert expr[i, 0].diff(i).doit() == 2*i*x[i, 0]*cos(i**2*x[i, 0])
_check_derivative_with_explicit_matrix(expr, i, expr.diff(i))
expr = (log(i)*A*B).applyfunc(sin)
assert expr.diff(i).dummy_eq(
HadamardProduct(A*B/i, (log(i)*A*B).applyfunc(cos)))
_check_derivative_with_explicit_matrix(expr, i, expr.diff(i))
expr = A*x.applyfunc(exp)
# TODO: restore this result (currently returning the transpose):
# assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(exp))*A.T)
_check_derivative_with_explicit_matrix(expr, x, expr.diff(x))
expr = x.T*A*x + k*y.applyfunc(sin).T*x
assert expr.diff(x).dummy_eq(A.T*x + A*x + k*y.applyfunc(sin))
_check_derivative_with_explicit_matrix(expr, x, expr.diff(x))
expr = x.applyfunc(sin).T*y
# TODO: restore (currently returning the transpose):
# assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(cos))*y)
_check_derivative_with_explicit_matrix(expr, x, expr.diff(x))
expr = (a.T * X * b).applyfunc(sin)
assert expr.diff(X).dummy_eq(a*(a.T*X*b).applyfunc(cos)*b.T)
_check_derivative_with_explicit_matrix(expr, X, expr.diff(X))
expr = a.T * X.applyfunc(sin) * b
assert expr.diff(X).dummy_eq(
DiagMatrix(a)*X.applyfunc(cos)*DiagMatrix(b))
_check_derivative_with_explicit_matrix(expr, X, expr.diff(X))
expr = a.T * (A*X*B).applyfunc(sin) * b
assert expr.diff(X).dummy_eq(
A.T*DiagMatrix(a)*(A*X*B).applyfunc(cos)*DiagMatrix(b)*B.T)
_check_derivative_with_explicit_matrix(expr, X, expr.diff(X))
expr = a.T * (A*X*b).applyfunc(sin) * b.T
# TODO: not implemented
#assert expr.diff(X) == ...
#_check_derivative_with_explicit_matrix(expr, X, expr.diff(X))
expr = a.T*A*X.applyfunc(sin)*B*b
assert expr.diff(X).dummy_eq(
HadamardProduct(A.T * a * b.T * B.T, X.applyfunc(cos)))
expr = a.T * (A*X.applyfunc(sin)*B).applyfunc(log) * b
# TODO: wrong
# assert expr.diff(X) == A.T*DiagMatrix(a)*(A*X.applyfunc(sin)*B).applyfunc(Lambda(k, 1/k))*DiagMatrix(b)*B.T
expr = a.T * (X.applyfunc(sin)).applyfunc(log) * b
# TODO: wrong
# assert expr.diff(X) == DiagMatrix(a)*X.applyfunc(sin).applyfunc(Lambda(k, 1/k))*DiagMatrix(b)
def test_derivatives_of_hadamard_expressions():
# Hadamard Product
expr = hadamard_product(a, x, b)
assert expr.diff(x) == DiagMatrix(hadamard_product(b, a))
expr = a.T*hadamard_product(A, X, B)*b
assert expr.diff(X) == HadamardProduct(a*b.T, A, B)
# Hadamard Power
expr = hadamard_power(x, 2)
assert expr.diff(x).doit() == 2*DiagMatrix(x)
expr = hadamard_power(x.T, 2)
assert expr.diff(x).doit() == 2*DiagMatrix(x)
expr = hadamard_power(x, S.Half)
assert expr.diff(x) == S.Half*DiagMatrix(hadamard_power(x, Rational(-1, 2)))
expr = hadamard_power(a.T*X*b, 2)
assert expr.diff(X) == 2*a*a.T*X*b*b.T
expr = hadamard_power(a.T*X*b, S.Half)
assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*b.T
|