hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
e42b60b08492a9df154730f7a64dc468fad5780b463f1d7e268487ebd1d4aba2 | from sympy import S, Basic, exp, multigamma, pi
from sympy.core.sympify import sympify, _sympify
from sympy.matrices import (ImmutableMatrix, Inverse, Trace, Determinant,
MatrixSymbol, MatrixBase, Transpose, MatrixSet,
matrix2numpy)
from sympy.stats.rv import (_value_check, RandomMatrixSymbol, NamedArgsMixin, PSpace,
_symbol_converter, MatrixDomain, Distribution)
from sympy.external import import_module
################################################################################
#------------------------Matrix Probability Space------------------------------#
################################################################################
class MatrixPSpace(PSpace):
"""
Represents probability space for
Matrix Distributions.
"""
def __new__(cls, sym, distribution, dim_n, dim_m):
sym = _symbol_converter(sym)
dim_n, dim_m = _sympify(dim_n), _sympify(dim_m)
if not (dim_n.is_integer and dim_m.is_integer):
raise ValueError("Dimensions should be integers")
return Basic.__new__(cls, sym, distribution, dim_n, dim_m)
distribution = property(lambda self: self.args[1])
symbol = property(lambda self: self.args[0])
@property
def domain(self):
return MatrixDomain(self.symbol, self.distribution.set)
@property
def value(self):
return RandomMatrixSymbol(self.symbol, self.args[2], self.args[3], self)
@property
def values(self):
return {self.value}
def compute_density(self, expr, *args):
rms = expr.atoms(RandomMatrixSymbol)
if len(rms) > 1 or (not isinstance(expr, RandomMatrixSymbol)):
raise NotImplementedError("Currently, no algorithm has been "
"implemented to handle general expressions containing "
"multiple matrix distributions.")
return self.distribution.pdf(expr)
def sample(self, size=(), library='scipy', seed=None):
"""
Internal sample method
Returns dictionary mapping RandomMatrixSymbol to realization value.
"""
return {self.value: self.distribution.sample(size, library=library, seed=seed)}
def rv(symbol, cls, args):
args = list(map(sympify, args))
dist = cls(*args)
dist.check(*args)
dim = dist.dimension
pspace = MatrixPSpace(symbol, dist, dim[0], dim[1])
return pspace.value
class SampleMatrixScipy:
"""Returns the sample from scipy of the given distribution"""
def __new__(cls, dist, size, seed=None):
return cls._sample_scipy(dist, size, seed)
@classmethod
def _sample_scipy(cls, dist, size, seed):
"""Sample from SciPy."""
from scipy import stats as scipy_stats
import numpy
scipy_rv_map = {
'WishartDistribution': lambda dist, size, rand_state: scipy_stats.wishart.rvs(
df=int(dist.n), scale=matrix2numpy(dist.scale_matrix, float), size=size),
'MatrixNormalDistribution': lambda dist, size, rand_state: scipy_stats.matrix_normal.rvs(
mean=matrix2numpy(dist.location_matrix, float),
rowcov=matrix2numpy(dist.scale_matrix_1, float),
colcov=matrix2numpy(dist.scale_matrix_2, float), size=size, random_state=rand_state)
}
dist_list = scipy_rv_map.keys()
if dist.__class__.__name__ not in dist_list:
return None
samples = []
if seed is None or isinstance(seed, int):
rand_state = numpy.random.default_rng(seed=seed)
else:
rand_state = seed
for _ in range(size[0]):
samp = scipy_rv_map[dist.__class__.__name__](dist, size[1] if len(size) > 1 else 1, rand_state)
samples.append(samp)
return samples
class SampleMatrixNumpy:
"""Returns the sample from numpy of the given distribution"""
### TODO: Add tests after adding matrix distributions in numpy_rv_map
def __new__(cls, dist, size, seed=None):
return cls._sample_numpy(dist, size, seed)
@classmethod
def _sample_numpy(cls, dist, size, seed):
"""Sample from NumPy."""
numpy_rv_map = {
}
dist_list = numpy_rv_map.keys()
if dist.__class__.__name__ not in dist_list:
return None
samples = []
import numpy
if seed is None or isinstance(seed, int):
rand_state = numpy.random.default_rng(seed=seed)
else:
rand_state = seed
for _ in range(size[0]):
samp = numpy_rv_map[dist.__class__.__name__](dist, size[1], rand_state)
samples.append(samp)
return samples
class SampleMatrixPymc:
"""Returns the sample from pymc3 of the given distribution"""
def __new__(cls, dist, size, seed=None):
return cls._sample_pymc3(dist, size, seed)
@classmethod
def _sample_pymc3(cls, dist, size, seed):
"""Sample from PyMC3."""
import pymc3
pymc3_rv_map = {
'MatrixNormalDistribution': lambda dist: pymc3.MatrixNormal('X',
mu=matrix2numpy(dist.location_matrix, float),
rowcov=matrix2numpy(dist.scale_matrix_1, float),
colcov=matrix2numpy(dist.scale_matrix_2, float),
shape=dist.location_matrix.shape),
'WishartDistribution': lambda dist: pymc3.WishartBartlett('X',
nu=int(dist.n), S=matrix2numpy(dist.scale_matrix, float))
}
dist_list = pymc3_rv_map.keys()
if dist.__class__.__name__ not in dist_list:
return None
with pymc3.Model():
pymc3_rv_map[dist.__class__.__name__](dist)
return pymc3.sample(size, chains=1, progressbar=False)[:]['X']
_get_sample_class_matrixrv = {
'scipy': SampleMatrixScipy,
'pymc3': SampleMatrixPymc,
'numpy': SampleMatrixNumpy
}
################################################################################
#-------------------------Matrix Distribution----------------------------------#
################################################################################
class MatrixDistribution(Distribution, NamedArgsMixin):
"""
Abstract class for Matrix Distribution.
"""
def __new__(cls, *args):
args = list(map(sympify, args))
return Basic.__new__(cls, *args)
@staticmethod
def check(*args):
pass
def __call__(self, expr):
if isinstance(expr, list):
expr = ImmutableMatrix(expr)
return self.pdf(expr)
def sample(self, size=(), library='scipy', seed=None):
"""
Internal sample method
Returns dictionary mapping RandomSymbol to realization value.
"""
libraries = ['scipy', 'numpy', 'pymc3']
if library not in libraries:
raise NotImplementedError("Sampling from %s is not supported yet."
% str(library))
if not import_module(library):
raise ValueError("Failed to import %s" % library)
samps = _get_sample_class_matrixrv[library](self, size, seed)
if samps is not None:
return samps
raise NotImplementedError(
"Sampling for %s is not currently implemented from %s"
% (self.__class__.__name__, library)
)
################################################################################
#------------------------Matrix Distribution Types-----------------------------#
################################################################################
#-------------------------------------------------------------------------------
# Matrix Gamma distribution ----------------------------------------------------
class MatrixGammaDistribution(MatrixDistribution):
_argnames = ('alpha', 'beta', 'scale_matrix')
@staticmethod
def check(alpha, beta, scale_matrix):
if not isinstance(scale_matrix , MatrixSymbol):
_value_check(scale_matrix.is_positive_definite, "The shape "
"matrix must be positive definite.")
_value_check(scale_matrix.is_square, "Should "
"be square matrix")
_value_check(alpha.is_positive, "Shape parameter should be positive.")
_value_check(beta.is_positive, "Scale parameter should be positive.")
@property
def set(self):
k = self.scale_matrix.shape[0]
return MatrixSet(k, k, S.Reals)
@property
def dimension(self):
return self.scale_matrix.shape
def pdf(self, x):
alpha , beta , scale_matrix = self.alpha, self.beta, self.scale_matrix
p = scale_matrix.shape[0]
if isinstance(x, list):
x = ImmutableMatrix(x)
if not isinstance(x, (MatrixBase, MatrixSymbol)):
raise ValueError("%s should be an isinstance of Matrix "
"or MatrixSymbol" % str(x))
sigma_inv_x = - Inverse(scale_matrix)*x / beta
term1 = exp(Trace(sigma_inv_x))/((beta**(p*alpha)) * multigamma(alpha, p))
term2 = (Determinant(scale_matrix))**(-alpha)
term3 = (Determinant(x))**(alpha - S(p + 1)/2)
return term1 * term2 * term3
def MatrixGamma(symbol, alpha, beta, scale_matrix):
"""
Creates a random variable with Matrix Gamma Distribution.
The density of the said distribution can be found at [1].
Parameters
==========
alpha: Positive Real number
Shape Parameter
beta: Positive Real number
Scale Parameter
scale_matrix: Positive definite real square matrix
Scale Matrix
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, MatrixGamma
>>> from sympy import MatrixSymbol, symbols
>>> a, b = symbols('a b', positive=True)
>>> M = MatrixGamma('M', a, b, [[2, 1], [1, 2]])
>>> X = MatrixSymbol('X', 2, 2)
>>> density(M)(X).doit()
exp(Trace(Matrix([
[-2/3, 1/3],
[ 1/3, -2/3]])*X)/b)*Determinant(X)**(a - 3/2)/(3**a*sqrt(pi)*b**(2*a)*gamma(a)*gamma(a - 1/2))
>>> density(M)([[1, 0], [0, 1]]).doit()
exp(-4/(3*b))/(3**a*sqrt(pi)*b**(2*a)*gamma(a)*gamma(a - 1/2))
References
==========
.. [1] https://en.wikipedia.org/wiki/Matrix_gamma_distribution
"""
if isinstance(scale_matrix, list):
scale_matrix = ImmutableMatrix(scale_matrix)
return rv(symbol, MatrixGammaDistribution, (alpha, beta, scale_matrix))
#-------------------------------------------------------------------------------
# Wishart Distribution ---------------------------------------------------------
class WishartDistribution(MatrixDistribution):
_argnames = ('n', 'scale_matrix')
@staticmethod
def check(n, scale_matrix):
if not isinstance(scale_matrix , MatrixSymbol):
_value_check(scale_matrix.is_positive_definite, "The shape "
"matrix must be positive definite.")
_value_check(scale_matrix.is_square, "Should "
"be square matrix")
_value_check(n.is_positive, "Shape parameter should be positive.")
@property
def set(self):
k = self.scale_matrix.shape[0]
return MatrixSet(k, k, S.Reals)
@property
def dimension(self):
return self.scale_matrix.shape
def pdf(self, x):
n, scale_matrix = self.n, self.scale_matrix
p = scale_matrix.shape[0]
if isinstance(x, list):
x = ImmutableMatrix(x)
if not isinstance(x, (MatrixBase, MatrixSymbol)):
raise ValueError("%s should be an isinstance of Matrix "
"or MatrixSymbol" % str(x))
sigma_inv_x = - Inverse(scale_matrix)*x / S(2)
term1 = exp(Trace(sigma_inv_x))/((2**(p*n/S(2))) * multigamma(n/S(2), p))
term2 = (Determinant(scale_matrix))**(-n/S(2))
term3 = (Determinant(x))**(S(n - p - 1)/2)
return term1 * term2 * term3
def Wishart(symbol, n, scale_matrix):
"""
Creates a random variable with Wishart Distribution.
The density of the said distribution can be found at [1].
Parameters
==========
n: Positive Real number
Represents degrees of freedom
scale_matrix: Positive definite real square matrix
Scale Matrix
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, Wishart
>>> from sympy import MatrixSymbol, symbols
>>> n = symbols('n', positive=True)
>>> W = Wishart('W', n, [[2, 1], [1, 2]])
>>> X = MatrixSymbol('X', 2, 2)
>>> density(W)(X).doit()
exp(Trace(Matrix([
[-1/3, 1/6],
[ 1/6, -1/3]])*X))*Determinant(X)**(n/2 - 3/2)/(2**n*3**(n/2)*sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2))
>>> density(W)([[1, 0], [0, 1]]).doit()
exp(-2/3)/(2**n*3**(n/2)*sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2))
References
==========
.. [1] https://en.wikipedia.org/wiki/Wishart_distribution
"""
if isinstance(scale_matrix, list):
scale_matrix = ImmutableMatrix(scale_matrix)
return rv(symbol, WishartDistribution, (n, scale_matrix))
#-------------------------------------------------------------------------------
# Matrix Normal distribution ---------------------------------------------------
class MatrixNormalDistribution(MatrixDistribution):
_argnames = ('location_matrix', 'scale_matrix_1', 'scale_matrix_2')
@staticmethod
def check(location_matrix, scale_matrix_1, scale_matrix_2):
if not isinstance(scale_matrix_1 , MatrixSymbol):
_value_check(scale_matrix_1.is_positive_definite, "The shape "
"matrix must be positive definite.")
if not isinstance(scale_matrix_2 , MatrixSymbol):
_value_check(scale_matrix_2.is_positive_definite, "The shape "
"matrix must be positive definite.")
_value_check(scale_matrix_1.is_square, "Scale matrix 1 should be "
"be square matrix")
_value_check(scale_matrix_2.is_square, "Scale matrix 2 should be "
"be square matrix")
n = location_matrix.shape[0]
p = location_matrix.shape[1]
_value_check(scale_matrix_1.shape[0] == n, "Scale matrix 1 should be"
" of shape %s x %s"% (str(n), str(n)))
_value_check(scale_matrix_2.shape[0] == p, "Scale matrix 2 should be"
" of shape %s x %s"% (str(p), str(p)))
@property
def set(self):
n, p = self.location_matrix.shape
return MatrixSet(n, p, S.Reals)
@property
def dimension(self):
return self.location_matrix.shape
def pdf(self, x):
M , U , V = self.location_matrix, self.scale_matrix_1, self.scale_matrix_2
n, p = M.shape
if isinstance(x, list):
x = ImmutableMatrix(x)
if not isinstance(x, (MatrixBase, MatrixSymbol)):
raise ValueError("%s should be an isinstance of Matrix "
"or MatrixSymbol" % str(x))
term1 = Inverse(V)*Transpose(x - M)*Inverse(U)*(x - M)
num = exp(-Trace(term1)/S(2))
den = (2*pi)**(S(n*p)/2) * Determinant(U)**S(p)/2 * Determinant(V)**S(n)/2
return num/den
def MatrixNormal(symbol, location_matrix, scale_matrix_1, scale_matrix_2):
"""
Creates a random variable with Matrix Normal Distribution.
The density of the said distribution can be found at [1].
Parameters
==========
location_matrix: Real ``n x p`` matrix
Represents degrees of freedom
scale_matrix_1: Positive definite matrix
Scale Matrix of shape ``n x n``
scale_matrix_2: Positive definite matrix
Scale Matrix of shape ``p x p``
Returns
=======
RandomSymbol
Examples
========
>>> from sympy import MatrixSymbol
>>> from sympy.stats import density, MatrixNormal
>>> M = MatrixNormal('M', [[1, 2]], [1], [[1, 0], [0, 1]])
>>> X = MatrixSymbol('X', 1, 2)
>>> density(M)(X).doit()
2*exp(-Trace((Matrix([
[-1],
[-2]]) + X.T)*(Matrix([[-1, -2]]) + X))/2)/pi
>>> density(M)([[3, 4]]).doit()
2*exp(-4)/pi
References
==========
.. [1] https://en.wikipedia.org/wiki/Matrix_normal_distribution
"""
if isinstance(location_matrix, list):
location_matrix = ImmutableMatrix(location_matrix)
if isinstance(scale_matrix_1, list):
scale_matrix_1 = ImmutableMatrix(scale_matrix_1)
if isinstance(scale_matrix_2, list):
scale_matrix_2 = ImmutableMatrix(scale_matrix_2)
args = (location_matrix, scale_matrix_1, scale_matrix_2)
return rv(symbol, MatrixNormalDistribution, args)
#-------------------------------------------------------------------------------
# Matrix Student's T distribution ---------------------------------------------------
class MatrixStudentTDistribution(MatrixDistribution):
_argnames = ('nu', 'location_matrix', 'scale_matrix_1', 'scale_matrix_2')
@staticmethod
def check(nu, location_matrix, scale_matrix_1, scale_matrix_2):
if not isinstance(scale_matrix_1, MatrixSymbol):
_value_check(scale_matrix_1.is_positive_definite != False, "The shape "
"matrix must be positive definite.")
if not isinstance(scale_matrix_2, MatrixSymbol):
_value_check(scale_matrix_2.is_positive_definite != False, "The shape "
"matrix must be positive definite.")
_value_check(scale_matrix_1.is_square != False, "Scale matrix 1 should be "
"be square matrix")
_value_check(scale_matrix_2.is_square != False, "Scale matrix 2 should be "
"be square matrix")
n = location_matrix.shape[0]
p = location_matrix.shape[1]
_value_check(scale_matrix_1.shape[0] == p, "Scale matrix 1 should be"
" of shape %s x %s" % (str(p), str(p)))
_value_check(scale_matrix_2.shape[0] == n, "Scale matrix 2 should be"
" of shape %s x %s" % (str(n), str(n)))
_value_check(nu.is_positive != False, "Degrees of freedom must be positive")
@property
def set(self):
n, p = self.location_matrix.shape
return MatrixSet(n, p, S.Reals)
@property
def dimension(self):
return self.location_matrix.shape
def pdf(self, x):
from sympy import eye
if isinstance(x, list):
x = ImmutableMatrix(x)
if not isinstance(x, (MatrixBase, MatrixSymbol)):
raise ValueError("%s should be an isinstance of Matrix "
"or MatrixSymbol" % str(x))
nu, M, Omega, Sigma = self.nu, self.location_matrix, self.scale_matrix_1, self.scale_matrix_2
n, p = M.shape
K = multigamma((nu + n + p - 1)/2, p) * Determinant(Omega)**(-n/2) * Determinant(Sigma)**(-p/2) \
/ ((pi)**(n*p/2) * multigamma((nu + p - 1)/2, p))
return K * (Determinant(eye(n) + Inverse(Sigma)*(x - M)*Inverse(Omega)*Transpose(x - M))) \
**(-(nu + n + p -1)/2)
def MatrixStudentT(symbol, nu, location_matrix, scale_matrix_1, scale_matrix_2):
"""
Creates a random variable with Matrix Gamma Distribution.
The density of the said distribution can be found at [1].
Parameters
==========
nu: Positive Real number
degrees of freedom
location_matrix: Positive definite real square matrix
Location Matrix of shape ``n x p``
scale_matrix_1: Positive definite real square matrix
Scale Matrix of shape ``p x p``
scale_matrix_2: Positive definite real square matrix
Scale Matrix of shape ``n x n``
Returns
=======
RandomSymbol
Examples
========
>>> from sympy import MatrixSymbol,symbols
>>> from sympy.stats import density, MatrixStudentT
>>> v = symbols('v',positive=True)
>>> M = MatrixStudentT('M', v, [[1, 2]], [[1, 0], [0, 1]], [1])
>>> X = MatrixSymbol('X', 1, 2)
>>> density(M)(X)
gamma(v/2 + 1)*Determinant((Matrix([[-1, -2]]) + X)*(Matrix([
[-1],
[-2]]) + X.T) + Matrix([[1]]))**(-v/2 - 1)/(pi**1.0*gamma(v/2)*Determinant(Matrix([[1]]))**1.0*Determinant(Matrix([
[1, 0],
[0, 1]]))**0.5)
References
==========
.. [1] https://en.wikipedia.org/wiki/Matrix_t-distribution
"""
if isinstance(location_matrix, list):
location_matrix = ImmutableMatrix(location_matrix)
if isinstance(scale_matrix_1, list):
scale_matrix_1 = ImmutableMatrix(scale_matrix_1)
if isinstance(scale_matrix_2, list):
scale_matrix_2 = ImmutableMatrix(scale_matrix_2)
args = (nu, location_matrix, scale_matrix_1, scale_matrix_2)
return rv(symbol, MatrixStudentTDistribution, args)
|
3d5593a9be4309284cac0f879859a83f81748120233a6ec9ff6bd8166ad9a29e | from sympy import (sympify, S, pi, sqrt, exp, Lambda, Indexed, besselk, gamma, Interval,
Range, factorial, Mul, Integer,
Add, rf, Eq, Piecewise, ones, Symbol, Pow, Rational, Sum,
Intersection, Matrix, symbols, Product, IndexedBase)
from sympy.matrices import ImmutableMatrix, MatrixSymbol
from sympy.matrices.expressions.determinant import det
from sympy.stats.joint_rv import JointDistribution, JointPSpace, MarginalDistribution
from sympy.stats.rv import _value_check, random_symbols
__all__ = ['JointRV',
'MultivariateNormal',
'MultivariateLaplace',
'Dirichlet',
'GeneralizedMultivariateLogGamma',
'GeneralizedMultivariateLogGammaOmega',
'Multinomial',
'MultivariateBeta',
'MultivariateEwens',
'MultivariateT',
'NegativeMultinomial',
'NormalGamma'
]
def multivariate_rv(cls, sym, *args):
args = list(map(sympify, args))
dist = cls(*args)
args = dist.args
dist.check(*args)
return JointPSpace(sym, dist).value
def marginal_distribution(rv, *indices):
"""
Marginal distribution function of a joint random variable.
Parameters
==========
rv: A random variable with a joint probability distribution.
indices: component indices or the indexed random symbol
for whom the joint distribution is to be calculated
Returns
=======
A Lambda expression in `sym`.
Examples
========
>>> from sympy.stats import MultivariateNormal, marginal_distribution
>>> m = MultivariateNormal('X', [1, 2], [[2, 1], [1, 2]])
>>> marginal_distribution(m, m[0])(1)
1/(2*sqrt(pi))
"""
indices = list(indices)
for i in range(len(indices)):
if isinstance(indices[i], Indexed):
indices[i] = indices[i].args[1]
prob_space = rv.pspace
if not indices:
raise ValueError(
"At least one component for marginal density is needed.")
if hasattr(prob_space.distribution, '_marginal_distribution'):
return prob_space.distribution._marginal_distribution(indices, rv.symbol)
return prob_space.marginal_distribution(*indices)
class JointDistributionHandmade(JointDistribution):
_argnames = ('pdf',)
is_Continuous = True
@property
def set(self):
return self.args[1]
def JointRV(symbol, pdf, _set=None):
"""
Create a Joint Random Variable where each of its component is conitinuous,
given the following:
-- a symbol
-- a PDF in terms of indexed symbols of the symbol given
as the first argument
NOTE: As of now, the set for each component for a `JointRV` is
equal to the set of all integers, which can not be changed.
Examples
========
>>> from sympy import exp, pi, Indexed, S
>>> from sympy.stats import density, JointRV
>>> x1, x2 = (Indexed('x', i) for i in (1, 2))
>>> pdf = exp(-x1**2/2 + x1 - x2**2/2 - S(1)/2)/(2*pi)
>>> N1 = JointRV('x', pdf) #Multivariate Normal distribution
>>> density(N1)(1, 2)
exp(-2)/(2*pi)
Returns
=======
RandomSymbol
"""
#TODO: Add support for sets provided by the user
symbol = sympify(symbol)
syms = list(i for i in pdf.free_symbols if isinstance(i, Indexed)
and i.base == IndexedBase(symbol))
syms = tuple(sorted(syms, key = lambda index: index.args[1]))
_set = S.Reals**len(syms)
pdf = Lambda(syms, pdf)
dist = JointDistributionHandmade(pdf, _set)
jrv = JointPSpace(symbol, dist).value
rvs = random_symbols(pdf)
if len(rvs) != 0:
dist = MarginalDistribution(dist, (jrv,))
return JointPSpace(symbol, dist).value
return jrv
#-------------------------------------------------------------------------------
# Multivariate Normal distribution ---------------------------------------------
class MultivariateNormalDistribution(JointDistribution):
_argnames = ('mu', 'sigma')
is_Continuous=True
@property
def set(self):
k = self.mu.shape[0]
return S.Reals**k
@staticmethod
def check(mu, sigma):
_value_check(mu.shape[0] == sigma.shape[0],
"Size of the mean vector and covariance matrix are incorrect.")
#check if covariance matrix is positive definite or not.
if not isinstance(sigma, MatrixSymbol):
_value_check(sigma.is_positive_definite,
"The covariance matrix must be positive definite. ")
def pdf(self, *args):
mu, sigma = self.mu, self.sigma
k = mu.shape[0]
args = ImmutableMatrix(args)
x = args - mu
return S.One/sqrt((2*pi)**(k)*det(sigma))*exp(
Rational(-1, 2)*x.transpose()*(sigma.inv()*\
x))[0]
def _marginal_distribution(self, indices, sym):
sym = ImmutableMatrix([Indexed(sym, i) for i in indices])
_mu, _sigma = self.mu, self.sigma
k = self.mu.shape[0]
for i in range(k):
if i not in indices:
_mu = _mu.row_del(i)
_sigma = _sigma.col_del(i)
_sigma = _sigma.row_del(i)
return Lambda(tuple(sym), S.One/sqrt((2*pi)**(len(_mu))*det(_sigma))*exp(
Rational(-1, 2)*(_mu - sym).transpose()*(_sigma.inv()*\
(_mu - sym)))[0])
def MultivariateNormal(name, mu, sigma):
"""
Creates a continuous random variable with Multivariate Normal
Distribution.
The density of the multivariate normal distribution can be found at [1].
Parameters
==========
mu : List representing the mean or the mean vector
sigma : Positive definite square matrix
Represents covariance Matrix
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import MultivariateNormal, density, marginal_distribution
>>> from sympy import symbols
>>> X = MultivariateNormal('X', [3, 4], [[2, 1], [1, 2]])
>>> y, z = symbols('y z')
>>> density(X)(y, z)
sqrt(3)*exp(-y**2/3 + y*z/3 + 2*y/3 - z**2/3 + 5*z/3 - 13/3)/(6*pi)
>>> density(X)(1, 2)
sqrt(3)*exp(-4/3)/(6*pi)
>>> marginal_distribution(X, X[1])(y)
exp(-(y - 4)**2/4)/(2*sqrt(pi))
>>> marginal_distribution(X, X[0])(y)
exp(-(y - 3)**2/4)/(2*sqrt(pi))
References
==========
.. [1] https://en.wikipedia.org/wiki/Multivariate_normal_distribution
"""
return multivariate_rv(MultivariateNormalDistribution, name, mu, sigma)
#-------------------------------------------------------------------------------
# Multivariate Laplace distribution --------------------------------------------
class MultivariateLaplaceDistribution(JointDistribution):
_argnames = ('mu', 'sigma')
is_Continuous=True
@property
def set(self):
k = self.mu.shape[0]
return S.Reals**k
@staticmethod
def check(mu, sigma):
_value_check(mu.shape[0] == sigma.shape[0],
"Size of the mean vector and covariance matrix are incorrect.")
# check if covariance matrix is positive definite or not.
if not isinstance(sigma, MatrixSymbol):
_value_check(sigma.is_positive_definite,
"The covariance matrix must be positive definite. ")
def pdf(self, *args):
mu, sigma = self.mu, self.sigma
mu_T = mu.transpose()
k = S(mu.shape[0])
sigma_inv = sigma.inv()
args = ImmutableMatrix(args)
args_T = args.transpose()
x = (mu_T*sigma_inv*mu)[0]
y = (args_T*sigma_inv*args)[0]
v = 1 - k/2
return S(2)/((2*pi)**(S(k)/2)*sqrt(det(sigma)))\
*(y/(2 + x))**(S(v)/2)*besselk(v, sqrt((2 + x)*(y)))\
*exp((args_T*sigma_inv*mu)[0])
def MultivariateLaplace(name, mu, sigma):
"""
Creates a continuous random variable with Multivariate Laplace
Distribution.
The density of the multivariate Laplace distribution can be found at [1].
Parameters
==========
mu : List representing the mean or the mean vector
sigma : Positive definite square matrix
Represents covariance Matrix
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import MultivariateLaplace, density
>>> from sympy import symbols
>>> y, z = symbols('y z')
>>> X = MultivariateLaplace('X', [2, 4], [[3, 1], [1, 3]])
>>> density(X)(y, z)
sqrt(2)*exp(y/4 + 5*z/4)*besselk(0, sqrt(15*y*(3*y/8 - z/8)/2 + 15*z*(-y/8 + 3*z/8)/2))/(4*pi)
>>> density(X)(1, 2)
sqrt(2)*exp(11/4)*besselk(0, sqrt(165)/4)/(4*pi)
References
==========
.. [1] https://en.wikipedia.org/wiki/Multivariate_Laplace_distribution
"""
return multivariate_rv(MultivariateLaplaceDistribution, name, mu, sigma)
#-------------------------------------------------------------------------------
# Multivariate StudentT distribution -------------------------------------------
class MultivariateTDistribution(JointDistribution):
_argnames = ('mu', 'shape_mat', 'dof')
is_Continuous=True
@property
def set(self):
k = self.mu.shape[0]
return S.Reals**k
@staticmethod
def check(mu, sigma, v):
_value_check(mu.shape[0] == sigma.shape[0],
"Size of the location vector and shape matrix are incorrect.")
# check if covariance matrix is positive definite or not.
if not isinstance(sigma, MatrixSymbol):
_value_check(sigma.is_positive_definite,
"The shape matrix must be positive definite. ")
def pdf(self, *args):
mu, sigma = self.mu, self.shape_mat
v = S(self.dof)
k = S(mu.shape[0])
sigma_inv = sigma.inv()
args = ImmutableMatrix(args)
x = args - mu
return gamma((k + v)/2)/(gamma(v/2)*(v*pi)**(k/2)*sqrt(det(sigma)))\
*(1 + 1/v*(x.transpose()*sigma_inv*x)[0])**((-v - k)/2)
def MultivariateT(syms, mu, sigma, v):
"""
Creates a joint random variable with multivariate T-distribution.
Parameters
==========
syms: A symbol/str
For identifying the random variable.
mu: A list/matrix
Representing the location vector
sigma: The shape matrix for the distribution
Examples
========
>>> from sympy.stats import density, MultivariateT
>>> from sympy import Symbol
>>> x = Symbol("x")
>>> X = MultivariateT("x", [1, 1], [[1, 0], [0, 1]], 2)
>>> density(X)(1, 2)
2/(9*pi)
Returns
=======
RandomSymbol
"""
return multivariate_rv(MultivariateTDistribution, syms, mu, sigma, v)
#-------------------------------------------------------------------------------
# Multivariate Normal Gamma distribution ---------------------------------------
class NormalGammaDistribution(JointDistribution):
_argnames = ('mu', 'lamda', 'alpha', 'beta')
is_Continuous=True
@staticmethod
def check(mu, lamda, alpha, beta):
_value_check(mu.is_real, "Location must be real.")
_value_check(lamda > 0, "Lambda must be positive")
_value_check(alpha > 0, "alpha must be positive")
_value_check(beta > 0, "beta must be positive")
@property
def set(self):
return S.Reals*Interval(0, S.Infinity)
def pdf(self, x, tau):
beta, alpha, lamda = self.beta, self.alpha, self.lamda
mu = self.mu
return beta**alpha*sqrt(lamda)/(gamma(alpha)*sqrt(2*pi))*\
tau**(alpha - S.Half)*exp(-1*beta*tau)*\
exp(-1*(lamda*tau*(x - mu)**2)/S(2))
def _marginal_distribution(self, indices, *sym):
if len(indices) == 2:
return self.pdf(*sym)
if indices[0] == 0:
#For marginal over `x`, return non-standardized Student-T's
#distribution
x = sym[0]
v, mu, sigma = self.alpha - S.Half, self.mu, \
S(self.beta)/(self.lamda * self.alpha)
return Lambda(sym, gamma((v + 1)/2)/(gamma(v/2)*sqrt(pi*v)*sigma)*\
(1 + 1/v*((x - mu)/sigma)**2)**((-v -1)/2))
#For marginal over `tau`, return Gamma distribution as per construction
from sympy.stats.crv_types import GammaDistribution
return Lambda(sym, GammaDistribution(self.alpha, self.beta)(sym[0]))
def NormalGamma(sym, mu, lamda, alpha, beta):
"""
Creates a bivariate joint random variable with multivariate Normal gamma
distribution.
Parameters
==========
sym: A symbol/str
For identifying the random variable.
mu: A real number
The mean of the normal distribution
lamda: A positive integer
Parameter of joint distribution
alpha: A positive integer
Parameter of joint distribution
beta: A positive integer
Parameter of joint distribution
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, NormalGamma
>>> from sympy import symbols
>>> X = NormalGamma('x', 0, 1, 2, 3)
>>> y, z = symbols('y z')
>>> density(X)(y, z)
9*sqrt(2)*z**(3/2)*exp(-3*z)*exp(-y**2*z/2)/(2*sqrt(pi))
References
==========
.. [1] https://en.wikipedia.org/wiki/Normal-gamma_distribution
"""
return multivariate_rv(NormalGammaDistribution, sym, mu, lamda, alpha, beta)
#-------------------------------------------------------------------------------
# Multivariate Beta/Dirichlet distribution -------------------------------------
class MultivariateBetaDistribution(JointDistribution):
_argnames = ('alpha',)
is_Continuous = True
@staticmethod
def check(alpha):
_value_check(len(alpha) >= 2, "At least two categories should be passed.")
for a_k in alpha:
_value_check((a_k > 0) != False, "Each concentration parameter"
" should be positive.")
@property
def set(self):
k = len(self.alpha)
return Interval(0, 1)**k
def pdf(self, *syms):
alpha = self.alpha
B = Mul.fromiter(map(gamma, alpha))/gamma(Add(*alpha))
return Mul.fromiter(sym**(a_k - 1) for a_k, sym in zip(alpha, syms))/B
def MultivariateBeta(syms, *alpha):
"""
Creates a continuous random variable with Dirichlet/Multivariate Beta
Distribution.
The density of the dirichlet distribution can be found at [1].
Parameters
==========
alpha: Positive real numbers
Signifies concentration numbers.
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, MultivariateBeta, marginal_distribution
>>> from sympy import Symbol
>>> a1 = Symbol('a1', positive=True)
>>> a2 = Symbol('a2', positive=True)
>>> B = MultivariateBeta('B', [a1, a2])
>>> C = MultivariateBeta('C', a1, a2)
>>> x = Symbol('x')
>>> y = Symbol('y')
>>> density(B)(x, y)
x**(a1 - 1)*y**(a2 - 1)*gamma(a1 + a2)/(gamma(a1)*gamma(a2))
>>> marginal_distribution(C, C[0])(x)
x**(a1 - 1)*gamma(a1 + a2)/(a2*gamma(a1)*gamma(a2))
References
==========
.. [1] https://en.wikipedia.org/wiki/Dirichlet_distribution
.. [2] http://mathworld.wolfram.com/DirichletDistribution.html
"""
if not isinstance(alpha[0], list):
alpha = (list(alpha),)
return multivariate_rv(MultivariateBetaDistribution, syms, alpha[0])
Dirichlet = MultivariateBeta
#-------------------------------------------------------------------------------
# Multivariate Ewens distribution ----------------------------------------------
class MultivariateEwensDistribution(JointDistribution):
_argnames = ('n', 'theta')
is_Discrete = True
is_Continuous = False
@staticmethod
def check(n, theta):
_value_check((n > 0),
"sample size should be positive integer.")
_value_check(theta.is_positive, "mutation rate should be positive.")
@property
def set(self):
if not isinstance(self.n, Integer):
i = Symbol('i', integer=True, positive=True)
return Product(Intersection(S.Naturals0, Interval(0, self.n//i)),
(i, 1, self.n))
prod_set = Range(0, self.n + 1)
for i in range(2, self.n + 1):
prod_set *= Range(0, self.n//i + 1)
return prod_set.flatten()
def pdf(self, *syms):
n, theta = self.n, self.theta
condi = isinstance(self.n, Integer)
if not (isinstance(syms[0], IndexedBase) or condi):
raise ValueError("Please use IndexedBase object for syms as "
"the dimension is symbolic")
term_1 = factorial(n)/rf(theta, n)
if condi:
term_2 = Mul.fromiter(theta**syms[j]/((j+1)**syms[j]*factorial(syms[j]))
for j in range(n))
cond = Eq(sum([(k + 1)*syms[k] for k in range(n)]), n)
return Piecewise((term_1 * term_2, cond), (0, True))
syms = syms[0]
j, k = symbols('j, k', positive=True, integer=True)
term_2 = Product(theta**syms[j]/((j+1)**syms[j]*factorial(syms[j])),
(j, 0, n - 1))
cond = Eq(Sum((k + 1)*syms[k], (k, 0, n - 1)), n)
return Piecewise((term_1 * term_2, cond), (0, True))
def MultivariateEwens(syms, n, theta):
"""
Creates a discrete random variable with Multivariate Ewens
Distribution.
The density of the said distribution can be found at [1].
Parameters
==========
n: Positive integer
Size of the sample or the integer whose partitions are considered
theta: Positive real number
Denotes Mutation rate
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, marginal_distribution, MultivariateEwens
>>> from sympy import Symbol
>>> a1 = Symbol('a1', positive=True)
>>> a2 = Symbol('a2', positive=True)
>>> ed = MultivariateEwens('E', 2, 1)
>>> density(ed)(a1, a2)
Piecewise((1/(2**a2*factorial(a1)*factorial(a2)), Eq(a1 + 2*a2, 2)), (0, True))
>>> marginal_distribution(ed, ed[0])(a1)
Piecewise((1/factorial(a1), Eq(a1, 2)), (0, True))
References
==========
.. [1] https://en.wikipedia.org/wiki/Ewens%27s_sampling_formula
.. [2] http://www.stat.rutgers.edu/home/hcrane/Papers/STS529.pdf
"""
return multivariate_rv(MultivariateEwensDistribution, syms, n, theta)
#-------------------------------------------------------------------------------
# Generalized Multivariate Log Gamma distribution ------------------------------
class GeneralizedMultivariateLogGammaDistribution(JointDistribution):
_argnames = ('delta', 'v', 'lamda', 'mu')
is_Continuous=True
def check(self, delta, v, l, mu):
_value_check((delta >= 0, delta <= 1), "delta must be in range [0, 1].")
_value_check((v > 0), "v must be positive")
for lk in l:
_value_check((lk > 0), "lamda must be a positive vector.")
for muk in mu:
_value_check((muk > 0), "mu must be a positive vector.")
_value_check(len(l) > 1,"the distribution should have at least"
" two random variables.")
@property
def set(self):
return S.Reals**len(self.lamda)
def pdf(self, *y):
from sympy.functions.special.gamma_functions import gamma
d, v, l, mu = self.delta, self.v, self.lamda, self.mu
n = Symbol('n', negative=False, integer=True)
k = len(l)
sterm1 = Pow((1 - d), n)/\
((gamma(v + n)**(k - 1))*gamma(v)*gamma(n + 1))
sterm2 = Mul.fromiter(mui*li**(-v - n) for mui, li in zip(mu, l))
term1 = sterm1 * sterm2
sterm3 = (v + n) * sum([mui * yi for mui, yi in zip(mu, y)])
sterm4 = sum([exp(mui * yi)/li for (mui, yi, li) in zip(mu, y, l)])
term2 = exp(sterm3 - sterm4)
return Pow(d, v) * Sum(term1 * term2, (n, 0, S.Infinity))
def GeneralizedMultivariateLogGamma(syms, delta, v, lamda, mu):
"""
Creates a joint random variable with generalized multivariate log gamma
distribution.
The joint pdf can be found at [1].
Parameters
==========
syms: list/tuple/set of symbols for identifying each component
delta: A constant in range [0, 1]
v: Positive real number
lamda: List of positive real numbers
mu: List of positive real numbers
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density
>>> from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGamma
>>> from sympy import symbols, S
>>> v = 1
>>> l, mu = [1, 1, 1], [1, 1, 1]
>>> d = S.Half
>>> y = symbols('y_1:4', positive=True)
>>> Gd = GeneralizedMultivariateLogGamma('G', d, v, l, mu)
>>> density(Gd)(y[0], y[1], y[2])
Sum(exp((n + 1)*(y_1 + y_2 + y_3) - exp(y_1) - exp(y_2) -
exp(y_3))/(2**n*gamma(n + 1)**3), (n, 0, oo))/2
References
==========
.. [1] https://en.wikipedia.org/wiki/Generalized_multivariate_log-gamma_distribution
.. [2] https://www.researchgate.net/publication/234137346_On_a_multivariate_log-gamma_distribution_and_the_use_of_the_distribution_in_the_Bayesian_analysis
Note
====
If the GeneralizedMultivariateLogGamma is too long to type use,
`from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGamma as GMVLG`
If you want to pass the matrix omega instead of the constant delta, then use,
GeneralizedMultivariateLogGammaOmega.
"""
return multivariate_rv(GeneralizedMultivariateLogGammaDistribution,
syms, delta, v, lamda, mu)
def GeneralizedMultivariateLogGammaOmega(syms, omega, v, lamda, mu):
"""
Extends GeneralizedMultivariateLogGamma.
Parameters
==========
syms: list/tuple/set of symbols
For identifying each component
omega: A square matrix
Every element of square matrix must be absolute value of
square root of correlation coefficient
v: Positive real number
lamda: List of positive real numbers
mu: List of positive real numbers
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density
>>> from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaOmega
>>> from sympy import Matrix, symbols, S
>>> omega = Matrix([[1, S.Half, S.Half], [S.Half, 1, S.Half], [S.Half, S.Half, 1]])
>>> v = 1
>>> l, mu = [1, 1, 1], [1, 1, 1]
>>> G = GeneralizedMultivariateLogGammaOmega('G', omega, v, l, mu)
>>> y = symbols('y_1:4', positive=True)
>>> density(G)(y[0], y[1], y[2])
sqrt(2)*Sum((1 - sqrt(2)/2)**n*exp((n + 1)*(y_1 + y_2 + y_3) - exp(y_1) -
exp(y_2) - exp(y_3))/gamma(n + 1)**3, (n, 0, oo))/2
References
==========
.. [1] https://en.wikipedia.org/wiki/Generalized_multivariate_log-gamma_distribution
.. [2] https://www.researchgate.net/publication/234137346_On_a_multivariate_log-gamma_distribution_and_the_use_of_the_distribution_in_the_Bayesian_analysis
Notes
=====
If the GeneralizedMultivariateLogGammaOmega is too long to type use,
`from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaOmega as GMVLGO`
"""
_value_check((omega.is_square, isinstance(omega, Matrix)), "omega must be a"
" square matrix")
for val in omega.values():
_value_check((val >= 0, val <= 1),
"all values in matrix must be between 0 and 1(both inclusive).")
_value_check(omega.diagonal().equals(ones(1, omega.shape[0])),
"all the elements of diagonal should be 1.")
_value_check((omega.shape[0] == len(lamda), len(lamda) == len(mu)),
"lamda, mu should be of same length and omega should "
" be of shape (length of lamda, length of mu)")
_value_check(len(lamda) > 1,"the distribution should have at least"
" two random variables.")
delta = Pow(Rational(omega.det()), Rational(1, len(lamda) - 1))
return GeneralizedMultivariateLogGamma(syms, delta, v, lamda, mu)
#-------------------------------------------------------------------------------
# Multinomial distribution -----------------------------------------------------
class MultinomialDistribution(JointDistribution):
_argnames = ('n', 'p')
is_Continuous=False
is_Discrete = True
@staticmethod
def check(n, p):
_value_check(n > 0,
"number of trials must be a positive integer")
for p_k in p:
_value_check((p_k >= 0, p_k <= 1),
"probability must be in range [0, 1]")
_value_check(Eq(sum(p), 1),
"probabilities must sum to 1")
@property
def set(self):
return Intersection(S.Naturals0, Interval(0, self.n))**len(self.p)
def pdf(self, *x):
n, p = self.n, self.p
term_1 = factorial(n)/Mul.fromiter(factorial(x_k) for x_k in x)
term_2 = Mul.fromiter(p_k**x_k for p_k, x_k in zip(p, x))
return Piecewise((term_1 * term_2, Eq(sum(x), n)), (0, True))
def Multinomial(syms, n, *p):
"""
Creates a discrete random variable with Multinomial Distribution.
The density of the said distribution can be found at [1].
Parameters
==========
n: Positive integer
Represents number of trials
p: List of event probabilites
Must be in the range of [0, 1]
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, Multinomial, marginal_distribution
>>> from sympy import symbols
>>> x1, x2, x3 = symbols('x1, x2, x3', nonnegative=True, integer=True)
>>> p1, p2, p3 = symbols('p1, p2, p3', positive=True)
>>> M = Multinomial('M', 3, p1, p2, p3)
>>> density(M)(x1, x2, x3)
Piecewise((6*p1**x1*p2**x2*p3**x3/(factorial(x1)*factorial(x2)*factorial(x3)),
Eq(x1 + x2 + x3, 3)), (0, True))
>>> marginal_distribution(M, M[0])(x1).subs(x1, 1)
3*p1*p2**2 + 6*p1*p2*p3 + 3*p1*p3**2
References
==========
.. [1] https://en.wikipedia.org/wiki/Multinomial_distribution
.. [2] http://mathworld.wolfram.com/MultinomialDistribution.html
"""
if not isinstance(p[0], list):
p = (list(p), )
return multivariate_rv(MultinomialDistribution, syms, n, p[0])
#-------------------------------------------------------------------------------
# Negative Multinomial Distribution --------------------------------------------
class NegativeMultinomialDistribution(JointDistribution):
_argnames = ('k0', 'p')
is_Continuous=False
is_Discrete = True
@staticmethod
def check(k0, p):
_value_check(k0 > 0,
"number of failures must be a positive integer")
for p_k in p:
_value_check((p_k >= 0, p_k <= 1),
"probability must be in range [0, 1].")
_value_check(sum(p) <= 1,
"success probabilities must not be greater than 1.")
@property
def set(self):
return Range(0, S.Infinity)**len(self.p)
def pdf(self, *k):
k0, p = self.k0, self.p
term_1 = (gamma(k0 + sum(k))*(1 - sum(p))**k0)/gamma(k0)
term_2 = Mul.fromiter(pi**ki/factorial(ki) for pi, ki in zip(p, k))
return term_1 * term_2
def NegativeMultinomial(syms, k0, *p):
"""
Creates a discrete random variable with Negative Multinomial Distribution.
The density of the said distribution can be found at [1].
Parameters
==========
k0: positive integer
Represents number of failures before the experiment is stopped
p: List of event probabilites
Must be in the range of [0, 1]
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, NegativeMultinomial, marginal_distribution
>>> from sympy import symbols
>>> x1, x2, x3 = symbols('x1, x2, x3', nonnegative=True, integer=True)
>>> p1, p2, p3 = symbols('p1, p2, p3', positive=True)
>>> N = NegativeMultinomial('M', 3, p1, p2, p3)
>>> N_c = NegativeMultinomial('M', 3, 0.1, 0.1, 0.1)
>>> density(N)(x1, x2, x3)
p1**x1*p2**x2*p3**x3*(-p1 - p2 - p3 + 1)**3*gamma(x1 + x2 +
x3 + 3)/(2*factorial(x1)*factorial(x2)*factorial(x3))
>>> marginal_distribution(N_c, N_c[0])(1).evalf().round(2)
0.25
References
==========
.. [1] https://en.wikipedia.org/wiki/Negative_multinomial_distribution
.. [2] http://mathworld.wolfram.com/NegativeBinomialDistribution.html
"""
if not isinstance(p[0], list):
p = (list(p), )
return multivariate_rv(NegativeMultinomialDistribution, syms, k0, p[0])
|
6f8738f5845ee6faaf500afd29c652f48ad818d91c197585aa905437e083384a | """
Contains
========
FlorySchulz
Geometric
Hermite
Logarithmic
NegativeBinomial
Poisson
Skellam
YuleSimon
Zeta
"""
from sympy import (Basic, factorial, exp, S, sympify, I, zeta, polylog, log, beta,
hyper, binomial, Piecewise, floor, besseli, sqrt, Sum, Dummy,
Lambda, Eq)
from sympy.stats.drv import SingleDiscreteDistribution, SingleDiscretePSpace
from sympy.stats.rv import _value_check, is_random
__all__ = ['FlorySchulz',
'Geometric',
'Hermite',
'Logarithmic',
'NegativeBinomial',
'Poisson',
'Skellam',
'YuleSimon',
'Zeta'
]
def rv(symbol, cls, *args, **kwargs):
args = list(map(sympify, args))
dist = cls(*args)
if kwargs.pop('check', True):
dist.check(*args)
pspace = SingleDiscretePSpace(symbol, dist)
if any(is_random(arg) for arg in args):
from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution
pspace = CompoundPSpace(symbol, CompoundDistribution(dist))
return pspace.value
class DiscreteDistributionHandmade(SingleDiscreteDistribution):
_argnames = ('pdf',)
def __new__(cls, pdf, set=S.Integers):
return Basic.__new__(cls, pdf, set)
@property
def set(self):
return self.args[1]
@staticmethod
def check(pdf, set):
x = Dummy('x')
val = Sum(pdf(x), (x, set._inf, set._sup)).doit()
_value_check(Eq(val, 1) != S.false, "The pdf is incorrect on the given set.")
def DiscreteRV(symbol, density, set=S.Integers, **kwargs):
"""
Create a Discrete Random Variable given the following:
Parameters
==========
symbol : Symbol
Represents name of the random variable.
density : Expression containing symbol
Represents probability density function.
set : set
Represents the region where the pdf is valid, by default is real line.
check : bool
If True, it will check whether the given density
integrates to 1 over the given set. If False, it
will not perform this check. Default is False.
Examples
========
>>> from sympy.stats import DiscreteRV, P, E
>>> from sympy import Rational, Symbol
>>> x = Symbol('x')
>>> n = 10
>>> density = Rational(1, 10)
>>> X = DiscreteRV(x, density, set=set(range(n)))
>>> E(X)
9/2
>>> P(X>3)
3/5
Returns
=======
RandomSymbol
"""
set = sympify(set)
pdf = Piecewise((density, set.as_relational(symbol)), (0, True))
pdf = Lambda(symbol, pdf)
# have a default of False while `rv` should have a default of True
kwargs['check'] = kwargs.pop('check', False)
return rv(symbol.name, DiscreteDistributionHandmade, pdf, set, **kwargs)
#-------------------------------------------------------------------------------
# Flory-Schulz distribution ------------------------------------------------------------
class FlorySchulzDistribution(SingleDiscreteDistribution):
_argnames = ('a',)
set = S.Naturals
@staticmethod
def check(a):
_value_check((0 < a, a < 1), "a must be between 0 and 1")
def pdf(self, k):
a = self.a
return (a**2 * k * (1 - a)**(k - 1))
def _characteristic_function(self, t):
a = self.a
return a**2*exp(I*t)/((1 + (a - 1)*exp(I*t))**2)
def _moment_generating_function(self, t):
a = self.a
return a**2*exp(t)/((1 + (a - 1)*exp(t))**2)
def FlorySchulz(name, a):
r"""
Create a discrete random variable with a FlorySchulz distribution.
The density of the FlorySchulz distribution is given by
.. math::
f(k) := (a^2) k (1 - a)^{k-1}
Parameters
==========
a
A real number between 0 and 1
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, E, variance, FlorySchulz
>>> from sympy import Symbol, S
>>> a = S.One / 5
>>> z = Symbol("z")
>>> X = FlorySchulz("x", a)
>>> density(X)(z)
(4/5)**(z - 1)*z/25
>>> E(X)
9
>>> variance(X)
40
References
==========
https://en.wikipedia.org/wiki/Flory%E2%80%93Schulz_distribution
"""
return rv(name, FlorySchulzDistribution, a)
#-------------------------------------------------------------------------------
# Geometric distribution ------------------------------------------------------------
class GeometricDistribution(SingleDiscreteDistribution):
_argnames = ('p',)
set = S.Naturals
@staticmethod
def check(p):
_value_check((0 < p, p <= 1), "p must be between 0 and 1")
def pdf(self, k):
return (1 - self.p)**(k - 1) * self.p
def _characteristic_function(self, t):
p = self.p
return p * exp(I*t) / (1 - (1 - p)*exp(I*t))
def _moment_generating_function(self, t):
p = self.p
return p * exp(t) / (1 - (1 - p) * exp(t))
def Geometric(name, p):
r"""
Create a discrete random variable with a Geometric distribution.
Explanation
===========
The density of the Geometric distribution is given by
.. math::
f(k) := p (1 - p)^{k - 1}
Parameters
==========
p: A probability between 0 and 1
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Geometric, density, E, variance
>>> from sympy import Symbol, S
>>> p = S.One / 5
>>> z = Symbol("z")
>>> X = Geometric("x", p)
>>> density(X)(z)
(4/5)**(z - 1)/5
>>> E(X)
5
>>> variance(X)
20
References
==========
.. [1] https://en.wikipedia.org/wiki/Geometric_distribution
.. [2] http://mathworld.wolfram.com/GeometricDistribution.html
"""
return rv(name, GeometricDistribution, p)
#-------------------------------------------------------------------------------
# Hermite distribution ---------------------------------------------------------
class HermiteDistribution(SingleDiscreteDistribution):
_argnames = ('a1', 'a2')
set = S.Naturals0
@staticmethod
def check(a1, a2):
_value_check(a1.is_nonnegative, 'Parameter a1 must be >= 0.')
_value_check(a2.is_nonnegative, 'Parameter a2 must be >= 0.')
def pdf(self, k):
a1, a2 = self.a1, self.a2
term1 = exp(-(a1 + a2))
j = Dummy("j", integer=True)
num = a1**(k - 2*j) * a2**j
den = factorial(k - 2*j) * factorial(j)
return term1 * Sum(num/den, (j, 0, k//2)).doit()
def _moment_generating_function(self, t):
a1, a2 = self.a1, self.a2
term1 = a1 * (exp(t) - 1)
term2 = a2 * (exp(2*t) - 1)
return exp(term1 + term2)
def _characteristic_function(self, t):
a1, a2 = self.a1, self.a2
term1 = a1 * (exp(I*t) - 1)
term2 = a2 * (exp(2*I*t) - 1)
return exp(term1 + term2)
def Hermite(name, a1, a2):
r"""
Create a discrete random variable with a Hermite distribution.
Explanation
===========
The density of the Hermite distribution is given by
.. math::
f(x):= e^{-a_1 -a_2}\sum_{j=0}^{\left \lfloor x/2 \right \rfloor}
\frac{a_{1}^{x-2j}a_{2}^{j}}{(x-2j)!j!}
Parameters
==========
a1: A Positive number greater than equal to 0.
a2: A Positive number greater than equal to 0.
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Hermite, density, E, variance
>>> from sympy import Symbol
>>> a1 = Symbol("a1", positive=True)
>>> a2 = Symbol("a2", positive=True)
>>> x = Symbol("x")
>>> H = Hermite("H", a1=5, a2=4)
>>> density(H)(2)
33*exp(-9)/2
>>> E(H)
13
>>> variance(H)
21
References
==========
.. [1] https://en.wikipedia.org/wiki/Hermite_distribution
"""
return rv(name, HermiteDistribution, a1, a2)
#-------------------------------------------------------------------------------
# Logarithmic distribution ------------------------------------------------------------
class LogarithmicDistribution(SingleDiscreteDistribution):
_argnames = ('p',)
set = S.Naturals
@staticmethod
def check(p):
_value_check((p > 0, p < 1), "p should be between 0 and 1")
def pdf(self, k):
p = self.p
return (-1) * p**k / (k * log(1 - p))
def _characteristic_function(self, t):
p = self.p
return log(1 - p * exp(I*t)) / log(1 - p)
def _moment_generating_function(self, t):
p = self.p
return log(1 - p * exp(t)) / log(1 - p)
def Logarithmic(name, p):
r"""
Create a discrete random variable with a Logarithmic distribution.
Explanation
===========
The density of the Logarithmic distribution is given by
.. math::
f(k) := \frac{-p^k}{k \ln{(1 - p)}}
Parameters
==========
p: A value between 0 and 1
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Logarithmic, density, E, variance
>>> from sympy import Symbol, S
>>> p = S.One / 5
>>> z = Symbol("z")
>>> X = Logarithmic("x", p)
>>> density(X)(z)
-1/(5**z*z*log(4/5))
>>> E(X)
-1/(-4*log(5) + 8*log(2))
>>> variance(X)
-1/((-4*log(5) + 8*log(2))*(-2*log(5) + 4*log(2))) + 1/(-64*log(2)*log(5) + 64*log(2)**2 + 16*log(5)**2) - 10/(-32*log(5) + 64*log(2))
References
==========
.. [1] https://en.wikipedia.org/wiki/Logarithmic_distribution
.. [2] http://mathworld.wolfram.com/LogarithmicDistribution.html
"""
return rv(name, LogarithmicDistribution, p)
#-------------------------------------------------------------------------------
# Negative binomial distribution ------------------------------------------------------------
class NegativeBinomialDistribution(SingleDiscreteDistribution):
_argnames = ('r', 'p')
set = S.Naturals0
@staticmethod
def check(r, p):
_value_check(r > 0, 'r should be positive')
_value_check((p > 0, p < 1), 'p should be between 0 and 1')
def pdf(self, k):
r = self.r
p = self.p
return binomial(k + r - 1, k) * (1 - p)**r * p**k
def _characteristic_function(self, t):
r = self.r
p = self.p
return ((1 - p) / (1 - p * exp(I*t)))**r
def _moment_generating_function(self, t):
r = self.r
p = self.p
return ((1 - p) / (1 - p * exp(t)))**r
def NegativeBinomial(name, r, p):
r"""
Create a discrete random variable with a Negative Binomial distribution.
Explanation
===========
The density of the Negative Binomial distribution is given by
.. math::
f(k) := \binom{k + r - 1}{k} (1 - p)^r p^k
Parameters
==========
r: A positive value
p: A value between 0 and 1
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import NegativeBinomial, density, E, variance
>>> from sympy import Symbol, S
>>> r = 5
>>> p = S.One / 5
>>> z = Symbol("z")
>>> X = NegativeBinomial("x", r, p)
>>> density(X)(z)
1024*binomial(z + 4, z)/(3125*5**z)
>>> E(X)
5/4
>>> variance(X)
25/16
References
==========
.. [1] https://en.wikipedia.org/wiki/Negative_binomial_distribution
.. [2] http://mathworld.wolfram.com/NegativeBinomialDistribution.html
"""
return rv(name, NegativeBinomialDistribution, r, p)
#-------------------------------------------------------------------------------
# Poisson distribution ------------------------------------------------------------
class PoissonDistribution(SingleDiscreteDistribution):
_argnames = ('lamda',)
set = S.Naturals0
@staticmethod
def check(lamda):
_value_check(lamda > 0, "Lambda must be positive")
def pdf(self, k):
return self.lamda**k / factorial(k) * exp(-self.lamda)
def _characteristic_function(self, t):
return exp(self.lamda * (exp(I*t) - 1))
def _moment_generating_function(self, t):
return exp(self.lamda * (exp(t) - 1))
def Poisson(name, lamda):
r"""
Create a discrete random variable with a Poisson distribution.
Explanation
===========
The density of the Poisson distribution is given by
.. math::
f(k) := \frac{\lambda^{k} e^{- \lambda}}{k!}
Parameters
==========
lamda: Positive number, a rate
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Poisson, density, E, variance
>>> from sympy import Symbol, simplify
>>> rate = Symbol("lambda", positive=True)
>>> z = Symbol("z")
>>> X = Poisson("x", rate)
>>> density(X)(z)
lambda**z*exp(-lambda)/factorial(z)
>>> E(X)
lambda
>>> simplify(variance(X))
lambda
References
==========
.. [1] https://en.wikipedia.org/wiki/Poisson_distribution
.. [2] http://mathworld.wolfram.com/PoissonDistribution.html
"""
return rv(name, PoissonDistribution, lamda)
# -----------------------------------------------------------------------------
# Skellam distribution --------------------------------------------------------
class SkellamDistribution(SingleDiscreteDistribution):
_argnames = ('mu1', 'mu2')
set = S.Integers
@staticmethod
def check(mu1, mu2):
_value_check(mu1 >= 0, 'Parameter mu1 must be >= 0')
_value_check(mu2 >= 0, 'Parameter mu2 must be >= 0')
def pdf(self, k):
(mu1, mu2) = (self.mu1, self.mu2)
term1 = exp(-(mu1 + mu2)) * (mu1 / mu2) ** (k / 2)
term2 = besseli(k, 2 * sqrt(mu1 * mu2))
return term1 * term2
def _cdf(self, x):
raise NotImplementedError(
"Skellam doesn't have closed form for the CDF.")
def _characteristic_function(self, t):
(mu1, mu2) = (self.mu1, self.mu2)
return exp(-(mu1 + mu2) + mu1 * exp(I * t) + mu2 * exp(-I * t))
def _moment_generating_function(self, t):
(mu1, mu2) = (self.mu1, self.mu2)
return exp(-(mu1 + mu2) + mu1 * exp(t) + mu2 * exp(-t))
def Skellam(name, mu1, mu2):
r"""
Create a discrete random variable with a Skellam distribution.
Explanation
===========
The Skellam is the distribution of the difference N1 - N2
of two statistically independent random variables N1 and N2
each Poisson-distributed with respective expected values mu1 and mu2.
The density of the Skellam distribution is given by
.. math::
f(k) := e^{-(\mu_1+\mu_2)}(\frac{\mu_1}{\mu_2})^{k/2}I_k(2\sqrt{\mu_1\mu_2})
Parameters
==========
mu1: A non-negative value
mu2: A non-negative value
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Skellam, density, E, variance
>>> from sympy import Symbol, pprint
>>> z = Symbol("z", integer=True)
>>> mu1 = Symbol("mu1", positive=True)
>>> mu2 = Symbol("mu2", positive=True)
>>> X = Skellam("x", mu1, mu2)
>>> pprint(density(X)(z), use_unicode=False)
z
-
2
/mu1\ -mu1 - mu2 / _____ _____\
|---| *e *besseli\z, 2*\/ mu1 *\/ mu2 /
\mu2/
>>> E(X)
mu1 - mu2
>>> variance(X).expand()
mu1 + mu2
References
==========
.. [1] https://en.wikipedia.org/wiki/Skellam_distribution
"""
return rv(name, SkellamDistribution, mu1, mu2)
#-------------------------------------------------------------------------------
# Yule-Simon distribution ------------------------------------------------------------
class YuleSimonDistribution(SingleDiscreteDistribution):
_argnames = ('rho',)
set = S.Naturals
@staticmethod
def check(rho):
_value_check(rho > 0, 'rho should be positive')
def pdf(self, k):
rho = self.rho
return rho * beta(k, rho + 1)
def _cdf(self, x):
return Piecewise((1 - floor(x) * beta(floor(x), self.rho + 1), x >= 1), (0, True))
def _characteristic_function(self, t):
rho = self.rho
return rho * hyper((1, 1), (rho + 2,), exp(I*t)) * exp(I*t) / (rho + 1)
def _moment_generating_function(self, t):
rho = self.rho
return rho * hyper((1, 1), (rho + 2,), exp(t)) * exp(t) / (rho + 1)
def YuleSimon(name, rho):
r"""
Create a discrete random variable with a Yule-Simon distribution.
Explanation
===========
The density of the Yule-Simon distribution is given by
.. math::
f(k) := \rho B(k, \rho + 1)
Parameters
==========
rho: A positive value
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import YuleSimon, density, E, variance
>>> from sympy import Symbol, simplify
>>> p = 5
>>> z = Symbol("z")
>>> X = YuleSimon("x", p)
>>> density(X)(z)
5*beta(z, 6)
>>> simplify(E(X))
5/4
>>> simplify(variance(X))
25/48
References
==========
.. [1] https://en.wikipedia.org/wiki/Yule%E2%80%93Simon_distribution
"""
return rv(name, YuleSimonDistribution, rho)
#-------------------------------------------------------------------------------
# Zeta distribution ------------------------------------------------------------
class ZetaDistribution(SingleDiscreteDistribution):
_argnames = ('s',)
set = S.Naturals
@staticmethod
def check(s):
_value_check(s > 1, 's should be greater than 1')
def pdf(self, k):
s = self.s
return 1 / (k**s * zeta(s))
def _characteristic_function(self, t):
return polylog(self.s, exp(I*t)) / zeta(self.s)
def _moment_generating_function(self, t):
return polylog(self.s, exp(t)) / zeta(self.s)
def Zeta(name, s):
r"""
Create a discrete random variable with a Zeta distribution.
Explanation
===========
The density of the Zeta distribution is given by
.. math::
f(k) := \frac{1}{k^s \zeta{(s)}}
Parameters
==========
s: A value greater than 1
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Zeta, density, E, variance
>>> from sympy import Symbol
>>> s = 5
>>> z = Symbol("z")
>>> X = Zeta("x", s)
>>> density(X)(z)
1/(z**5*zeta(5))
>>> E(X)
pi**4/(90*zeta(5))
>>> variance(X)
-pi**8/(8100*zeta(5)**2) + zeta(3)/zeta(5)
References
==========
.. [1] https://en.wikipedia.org/wiki/Zeta_distribution
"""
return rv(name, ZetaDistribution, s)
|
ec0f177855033c42e82cc9060a41c3b4697a22d7bf0ddca95eb8eebadfd5c511 | """Finitely Presented Groups and its algorithms. """
from sympy import S
from sympy.combinatorics.free_groups import (FreeGroup, FreeGroupElement,
free_group)
from sympy.combinatorics.rewritingsystem import RewritingSystem
from sympy.combinatorics.coset_table import (CosetTable,
coset_enumeration_r,
coset_enumeration_c)
from sympy.combinatorics import PermutationGroup
from sympy.printing.defaults import DefaultPrinting
from sympy.utilities import public
from sympy.utilities.magic import pollute
from sympy import symbols
from itertools import product
@public
def fp_group(fr_grp, relators=[]):
_fp_group = FpGroup(fr_grp, relators)
return (_fp_group,) + tuple(_fp_group._generators)
@public
def xfp_group(fr_grp, relators=[]):
_fp_group = FpGroup(fr_grp, relators)
return (_fp_group, _fp_group._generators)
# Does not work. Both symbols and pollute are undefined. Never tested.
@public
def vfp_group(fr_grpm, relators):
_fp_group = FpGroup(symbols, relators)
pollute([sym.name for sym in _fp_group.symbols], _fp_group.generators)
return _fp_group
def _parse_relators(rels):
"""Parse the passed relators."""
return rels
###############################################################################
# FINITELY PRESENTED GROUPS #
###############################################################################
class FpGroup(DefaultPrinting):
"""
The FpGroup would take a FreeGroup and a list/tuple of relators, the
relators would be specified in such a way that each of them be equal to the
identity of the provided free group.
"""
is_group = True
is_FpGroup = True
is_PermutationGroup = False
def __init__(self, fr_grp, relators):
relators = _parse_relators(relators)
self.free_group = fr_grp
self.relators = relators
self.generators = self._generators()
self.dtype = type("FpGroupElement", (FpGroupElement,), {"group": self})
# CosetTable instance on identity subgroup
self._coset_table = None
# returns whether coset table on identity subgroup
# has been standardized
self._is_standardized = False
self._order = None
self._center = None
self._rewriting_system = RewritingSystem(self)
self._perm_isomorphism = None
return
def _generators(self):
return self.free_group.generators
def make_confluent(self):
'''
Try to make the group's rewriting system confluent
'''
self._rewriting_system.make_confluent()
return
def reduce(self, word):
'''
Return the reduced form of `word` in `self` according to the group's
rewriting system. If it's confluent, the reduced form is the unique normal
form of the word in the group.
'''
return self._rewriting_system.reduce(word)
def equals(self, word1, word2):
'''
Compare `word1` and `word2` for equality in the group
using the group's rewriting system. If the system is
confluent, the returned answer is necessarily correct.
(If it isn't, `False` could be returned in some cases
where in fact `word1 == word2`)
'''
if self.reduce(word1*word2**-1) == self.identity:
return True
elif self._rewriting_system.is_confluent:
return False
return None
@property
def identity(self):
return self.free_group.identity
def __contains__(self, g):
return g in self.free_group
def subgroup(self, gens, C=None, homomorphism=False):
'''
Return the subgroup generated by `gens` using the
Reidemeister-Schreier algorithm
homomorphism -- When set to True, return a dictionary containing the images
of the presentation generators in the original group.
Examples
========
>>> from sympy.combinatorics.fp_groups import FpGroup
>>> from sympy.combinatorics.free_groups import free_group
>>> F, x, y = free_group("x, y")
>>> f = FpGroup(F, [x**3, y**5, (x*y)**2])
>>> H = [x*y, x**-1*y**-1*x*y*x]
>>> K, T = f.subgroup(H, homomorphism=True)
>>> T(K.generators)
[x*y, x**-1*y**2*x**-1]
'''
if not all([isinstance(g, FreeGroupElement) for g in gens]):
raise ValueError("Generators must be `FreeGroupElement`s")
if not all([g.group == self.free_group for g in gens]):
raise ValueError("Given generators are not members of the group")
if homomorphism:
g, rels, _gens = reidemeister_presentation(self, gens, C=C, homomorphism=True)
else:
g, rels = reidemeister_presentation(self, gens, C=C)
if g:
g = FpGroup(g[0].group, rels)
else:
g = FpGroup(free_group('')[0], [])
if homomorphism:
from sympy.combinatorics.homomorphisms import homomorphism
return g, homomorphism(g, self, g.generators, _gens, check=False)
return g
def coset_enumeration(self, H, strategy="relator_based", max_cosets=None,
draft=None, incomplete=False):
"""
Return an instance of ``coset table``, when Todd-Coxeter algorithm is
run over the ``self`` with ``H`` as subgroup, using ``strategy``
argument as strategy. The returned coset table is compressed but not
standardized.
An instance of `CosetTable` for `fp_grp` can be passed as the keyword
argument `draft` in which case the coset enumeration will start with
that instance and attempt to complete it.
When `incomplete` is `True` and the function is unable to complete for
some reason, the partially complete table will be returned.
"""
if not max_cosets:
max_cosets = CosetTable.coset_table_max_limit
if strategy == 'relator_based':
C = coset_enumeration_r(self, H, max_cosets=max_cosets,
draft=draft, incomplete=incomplete)
else:
C = coset_enumeration_c(self, H, max_cosets=max_cosets,
draft=draft, incomplete=incomplete)
if C.is_complete():
C.compress()
return C
def standardize_coset_table(self):
"""
Standardized the coset table ``self`` and makes the internal variable
``_is_standardized`` equal to ``True``.
"""
self._coset_table.standardize()
self._is_standardized = True
def coset_table(self, H, strategy="relator_based", max_cosets=None,
draft=None, incomplete=False):
"""
Return the mathematical coset table of ``self`` in ``H``.
"""
if not H:
if self._coset_table is not None:
if not self._is_standardized:
self.standardize_coset_table()
else:
C = self.coset_enumeration([], strategy, max_cosets=max_cosets,
draft=draft, incomplete=incomplete)
self._coset_table = C
self.standardize_coset_table()
return self._coset_table.table
else:
C = self.coset_enumeration(H, strategy, max_cosets=max_cosets,
draft=draft, incomplete=incomplete)
C.standardize()
return C.table
def order(self, strategy="relator_based"):
"""
Returns the order of the finitely presented group ``self``. It uses
the coset enumeration with identity group as subgroup, i.e ``H=[]``.
Examples
========
>>> from sympy.combinatorics.free_groups import free_group
>>> from sympy.combinatorics.fp_groups import FpGroup
>>> F, x, y = free_group("x, y")
>>> f = FpGroup(F, [x, y**2])
>>> f.order(strategy="coset_table_based")
2
"""
from sympy import S, gcd
if self._order is not None:
return self._order
if self._coset_table is not None:
self._order = len(self._coset_table.table)
elif len(self.relators) == 0:
self._order = self.free_group.order()
elif len(self.generators) == 1:
self._order = abs(gcd([r.array_form[0][1] for r in self.relators]))
elif self._is_infinite():
self._order = S.Infinity
else:
gens, C = self._finite_index_subgroup()
if C:
ind = len(C.table)
self._order = ind*self.subgroup(gens, C=C).order()
else:
self._order = self.index([])
return self._order
def _is_infinite(self):
'''
Test if the group is infinite. Return `True` if the test succeeds
and `None` otherwise
'''
used_gens = set()
for r in self.relators:
used_gens.update(r.contains_generators())
if any([g not in used_gens for g in self.generators]):
return True
# Abelianisation test: check is the abelianisation is infinite
abelian_rels = []
from sympy.matrices.normalforms import invariant_factors
from sympy.matrices import Matrix
for rel in self.relators:
abelian_rels.append([rel.exponent_sum(g) for g in self.generators])
m = Matrix(Matrix(abelian_rels))
if 0 in invariant_factors(m):
return True
else:
return None
def _finite_index_subgroup(self, s=[]):
'''
Find the elements of `self` that generate a finite index subgroup
and, if found, return the list of elements and the coset table of `self` by
the subgroup, otherwise return `(None, None)`
'''
gen = self.most_frequent_generator()
rels = list(self.generators)
rels.extend(self.relators)
if not s:
if len(self.generators) == 2:
s = [gen] + [g for g in self.generators if g != gen]
else:
rand = self.free_group.identity
i = 0
while ((rand in rels or rand**-1 in rels or rand.is_identity)
and i<10):
rand = self.random()
i += 1
s = [gen, rand] + [g for g in self.generators if g != gen]
mid = (len(s)+1)//2
half1 = s[:mid]
half2 = s[mid:]
draft1 = None
draft2 = None
m = 200
C = None
while not C and (m/2 < CosetTable.coset_table_max_limit):
m = min(m, CosetTable.coset_table_max_limit)
draft1 = self.coset_enumeration(half1, max_cosets=m,
draft=draft1, incomplete=True)
if draft1.is_complete():
C = draft1
half = half1
else:
draft2 = self.coset_enumeration(half2, max_cosets=m,
draft=draft2, incomplete=True)
if draft2.is_complete():
C = draft2
half = half2
if not C:
m *= 2
if not C:
return None, None
C.compress()
return half, C
def most_frequent_generator(self):
gens = self.generators
rels = self.relators
freqs = [sum([r.generator_count(g) for r in rels]) for g in gens]
return gens[freqs.index(max(freqs))]
def random(self):
import random
r = self.free_group.identity
for i in range(random.randint(2,3)):
r = r*random.choice(self.generators)**random.choice([1,-1])
return r
def index(self, H, strategy="relator_based"):
"""
Return the index of subgroup ``H`` in group ``self``.
Examples
========
>>> from sympy.combinatorics.free_groups import free_group
>>> from sympy.combinatorics.fp_groups import FpGroup
>>> F, x, y = free_group("x, y")
>>> f = FpGroup(F, [x**5, y**4, y*x*y**3*x**3])
>>> f.index([x])
4
"""
# TODO: use |G:H| = |G|/|H| (currently H can't be made into a group)
# when we know |G| and |H|
if H == []:
return self.order()
else:
C = self.coset_enumeration(H, strategy)
return len(C.table)
def __str__(self):
if self.free_group.rank > 30:
str_form = "<fp group with %s generators>" % self.free_group.rank
else:
str_form = "<fp group on the generators %s>" % str(self.generators)
return str_form
__repr__ = __str__
#==============================================================================
# PERMUTATION GROUP METHODS
#==============================================================================
def _to_perm_group(self):
'''
Return an isomorphic permutation group and the isomorphism.
The implementation is dependent on coset enumeration so
will only terminate for finite groups.
'''
from sympy.combinatorics import Permutation, PermutationGroup
from sympy.combinatorics.homomorphisms import homomorphism
if self.order() is S.Infinity:
raise NotImplementedError("Permutation presentation of infinite "
"groups is not implemented")
if self._perm_isomorphism:
T = self._perm_isomorphism
P = T.image()
else:
C = self.coset_table([])
gens = self.generators
images = [[C[i][2*gens.index(g)] for i in range(len(C))] for g in gens]
images = [Permutation(i) for i in images]
P = PermutationGroup(images)
T = homomorphism(self, P, gens, images, check=False)
self._perm_isomorphism = T
return P, T
def _perm_group_list(self, method_name, *args):
'''
Given the name of a `PermutationGroup` method (returning a subgroup
or a list of subgroups) and (optionally) additional arguments it takes,
return a list or a list of lists containing the generators of this (or
these) subgroups in terms of the generators of `self`.
'''
P, T = self._to_perm_group()
perm_result = getattr(P, method_name)(*args)
single = False
if isinstance(perm_result, PermutationGroup):
perm_result, single = [perm_result], True
result = []
for group in perm_result:
gens = group.generators
result.append(T.invert(gens))
return result[0] if single else result
def derived_series(self):
'''
Return the list of lists containing the generators
of the subgroups in the derived series of `self`.
'''
return self._perm_group_list('derived_series')
def lower_central_series(self):
'''
Return the list of lists containing the generators
of the subgroups in the lower central series of `self`.
'''
return self._perm_group_list('lower_central_series')
def center(self):
'''
Return the list of generators of the center of `self`.
'''
return self._perm_group_list('center')
def derived_subgroup(self):
'''
Return the list of generators of the derived subgroup of `self`.
'''
return self._perm_group_list('derived_subgroup')
def centralizer(self, other):
'''
Return the list of generators of the centralizer of `other`
(a list of elements of `self`) in `self`.
'''
T = self._to_perm_group()[1]
other = T(other)
return self._perm_group_list('centralizer', other)
def normal_closure(self, other):
'''
Return the list of generators of the normal closure of `other`
(a list of elements of `self`) in `self`.
'''
T = self._to_perm_group()[1]
other = T(other)
return self._perm_group_list('normal_closure', other)
def _perm_property(self, attr):
'''
Given an attribute of a `PermutationGroup`, return
its value for a permutation group isomorphic to `self`.
'''
P = self._to_perm_group()[0]
return getattr(P, attr)
@property
def is_abelian(self):
'''
Check if `self` is abelian.
'''
return self._perm_property("is_abelian")
@property
def is_nilpotent(self):
'''
Check if `self` is nilpotent.
'''
return self._perm_property("is_nilpotent")
@property
def is_solvable(self):
'''
Check if `self` is solvable.
'''
return self._perm_property("is_solvable")
@property
def elements(self):
'''
List the elements of `self`.
'''
P, T = self._to_perm_group()
return T.invert(P._elements)
@property
def is_cyclic(self):
"""
Return ``True`` if group is Cyclic.
"""
if len(self.generators) <= 1:
return True
try:
P, T = self._to_perm_group()
except NotImplementedError:
raise NotImplementedError("Check for infinite Cyclic group "
"is not implemented")
return P.is_cyclic
def abelian_invariants(self):
"""
Return Abelian Invariants of a group.
"""
try:
P, T = self._to_perm_group()
except NotImplementedError:
raise NotImplementedError("abelian invariants is not implemented"
"for infinite group")
return P.abelian_invariants()
def composition_series(self):
"""
Return subnormal series of maximum length for a group.
"""
try:
P, T = self._to_perm_group()
except NotImplementedError:
raise NotImplementedError("composition series is not implemented"
"for infinite group")
return P.composition_series()
class FpSubgroup(DefaultPrinting):
'''
The class implementing a subgroup of an FpGroup or a FreeGroup
(only finite index subgroups are supported at this point). This
is to be used if one wishes to check if an element of the original
group belongs to the subgroup
'''
def __init__(self, G, gens, normal=False):
super().__init__()
self.parent = G
self.generators = list({g for g in gens if g != G.identity})
self._min_words = None #for use in __contains__
self.C = None
self.normal = normal
def __contains__(self, g):
if isinstance(self.parent, FreeGroup):
if self._min_words is None:
# make _min_words - a list of subwords such that
# g is in the subgroup if and only if it can be
# partitioned into these subwords. Infinite families of
# subwords are presented by tuples, e.g. (r, w)
# stands for the family of subwords r*w**n*r**-1
def _process(w):
# this is to be used before adding new words
# into _min_words; if the word w is not cyclically
# reduced, it will generate an infinite family of
# subwords so should be written as a tuple;
# if it is, w**-1 should be added to the list
# as well
p, r = w.cyclic_reduction(removed=True)
if not r.is_identity:
return [(r, p)]
else:
return [w, w**-1]
# make the initial list
gens = []
for w in self.generators:
if self.normal:
w = w.cyclic_reduction()
gens.extend(_process(w))
for w1 in gens:
for w2 in gens:
# if w1 and w2 are equal or are inverses, continue
if w1 == w2 or (not isinstance(w1, tuple)
and w1**-1 == w2):
continue
# if the start of one word is the inverse of the
# end of the other, their multiple should be added
# to _min_words because of cancellation
if isinstance(w1, tuple):
# start, end
s1, s2 = w1[0][0], w1[0][0]**-1
else:
s1, s2 = w1[0], w1[len(w1)-1]
if isinstance(w2, tuple):
# start, end
r1, r2 = w2[0][0], w2[0][0]**-1
else:
r1, r2 = w2[0], w2[len(w1)-1]
# p1 and p2 are w1 and w2 or, in case when
# w1 or w2 is an infinite family, a representative
p1, p2 = w1, w2
if isinstance(w1, tuple):
p1 = w1[0]*w1[1]*w1[0]**-1
if isinstance(w2, tuple):
p2 = w2[0]*w2[1]*w2[0]**-1
# add the product of the words to the list is necessary
if r1**-1 == s2 and not (p1*p2).is_identity:
new = _process(p1*p2)
if not new in gens:
gens.extend(new)
if r2**-1 == s1 and not (p2*p1).is_identity:
new = _process(p2*p1)
if not new in gens:
gens.extend(new)
self._min_words = gens
min_words = self._min_words
def _is_subword(w):
# check if w is a word in _min_words or one of
# the infinite families in it
w, r = w.cyclic_reduction(removed=True)
if r.is_identity or self.normal:
return w in min_words
else:
t = [s[1] for s in min_words if isinstance(s, tuple)
and s[0] == r]
return [s for s in t if w.power_of(s)] != []
# store the solution of words for which the result of
# _word_break (below) is known
known = {}
def _word_break(w):
# check if w can be written as a product of words
# in min_words
if len(w) == 0:
return True
i = 0
while i < len(w):
i += 1
prefix = w.subword(0, i)
if not _is_subword(prefix):
continue
rest = w.subword(i, len(w))
if rest not in known:
known[rest] = _word_break(rest)
if known[rest]:
return True
return False
if self.normal:
g = g.cyclic_reduction()
return _word_break(g)
else:
if self.C is None:
C = self.parent.coset_enumeration(self.generators)
self.C = C
i = 0
C = self.C
for j in range(len(g)):
i = C.table[i][C.A_dict[g[j]]]
return i == 0
def order(self):
from sympy import S
if not self.generators:
return 1
if isinstance(self.parent, FreeGroup):
return S.Infinity
if self.C is None:
C = self.parent.coset_enumeration(self.generators)
self.C = C
# This is valid because `len(self.C.table)` (the index of the subgroup)
# will always be finite - otherwise coset enumeration doesn't terminate
return self.parent.order()/len(self.C.table)
def to_FpGroup(self):
if isinstance(self.parent, FreeGroup):
gen_syms = [('x_%d'%i) for i in range(len(self.generators))]
return free_group(', '.join(gen_syms))[0]
return self.parent.subgroup(C=self.C)
def __str__(self):
if len(self.generators) > 30:
str_form = "<fp subgroup with %s generators>" % len(self.generators)
else:
str_form = "<fp subgroup on the generators %s>" % str(self.generators)
return str_form
__repr__ = __str__
###############################################################################
# LOW INDEX SUBGROUPS #
###############################################################################
def low_index_subgroups(G, N, Y=[]):
"""
Implements the Low Index Subgroups algorithm, i.e find all subgroups of
``G`` upto a given index ``N``. This implements the method described in
[Sim94]. This procedure involves a backtrack search over incomplete Coset
Tables, rather than over forced coincidences.
Parameters
==========
G: An FpGroup < X|R >
N: positive integer, representing the maximum index value for subgroups
Y: (an optional argument) specifying a list of subgroup generators, such
that each of the resulting subgroup contains the subgroup generated by Y.
Examples
========
>>> from sympy.combinatorics.free_groups import free_group
>>> from sympy.combinatorics.fp_groups import FpGroup, low_index_subgroups
>>> F, x, y = free_group("x, y")
>>> f = FpGroup(F, [x**2, y**3, (x*y)**4])
>>> L = low_index_subgroups(f, 4)
>>> for coset_table in L:
... print(coset_table.table)
[[0, 0, 0, 0]]
[[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 3, 3]]
[[0, 0, 1, 2], [2, 2, 2, 0], [1, 1, 0, 1]]
[[1, 1, 0, 0], [0, 0, 1, 1]]
References
==========
.. [1] Holt, D., Eick, B., O'Brien, E.
"Handbook of Computational Group Theory"
Section 5.4
.. [2] Marston Conder and Peter Dobcsanyi
"Applications and Adaptions of the Low Index Subgroups Procedure"
"""
C = CosetTable(G, [])
R = G.relators
# length chosen for the length of the short relators
len_short_rel = 5
# elements of R2 only checked at the last step for complete
# coset tables
R2 = {rel for rel in R if len(rel) > len_short_rel}
# elements of R1 are used in inner parts of the process to prune
# branches of the search tree,
R1 = {rel.identity_cyclic_reduction() for rel in set(R) - R2}
R1_c_list = C.conjugates(R1)
S = []
descendant_subgroups(S, C, R1_c_list, C.A[0], R2, N, Y)
return S
def descendant_subgroups(S, C, R1_c_list, x, R2, N, Y):
A_dict = C.A_dict
A_dict_inv = C.A_dict_inv
if C.is_complete():
# if C is complete then it only needs to test
# whether the relators in R2 are satisfied
for w, alpha in product(R2, C.omega):
if not C.scan_check(alpha, w):
return
# relators in R2 are satisfied, append the table to list
S.append(C)
else:
# find the first undefined entry in Coset Table
for alpha, x in product(range(len(C.table)), C.A):
if C.table[alpha][A_dict[x]] is None:
# this is "x" in pseudo-code (using "y" makes it clear)
undefined_coset, undefined_gen = alpha, x
break
# for filling up the undefine entry we try all possible values
# of beta in Omega or beta = n where beta^(undefined_gen^-1) is undefined
reach = C.omega + [C.n]
for beta in reach:
if beta < N:
if beta == C.n or C.table[beta][A_dict_inv[undefined_gen]] is None:
try_descendant(S, C, R1_c_list, R2, N, undefined_coset, \
undefined_gen, beta, Y)
def try_descendant(S, C, R1_c_list, R2, N, alpha, x, beta, Y):
r"""
Solves the problem of trying out each individual possibility
for `\alpha^x.
"""
D = C.copy()
if beta == D.n and beta < N:
D.table.append([None]*len(D.A))
D.p.append(beta)
D.table[alpha][D.A_dict[x]] = beta
D.table[beta][D.A_dict_inv[x]] = alpha
D.deduction_stack.append((alpha, x))
if not D.process_deductions_check(R1_c_list[D.A_dict[x]], \
R1_c_list[D.A_dict_inv[x]]):
return
for w in Y:
if not D.scan_check(0, w):
return
if first_in_class(D, Y):
descendant_subgroups(S, D, R1_c_list, x, R2, N, Y)
def first_in_class(C, Y=[]):
"""
Checks whether the subgroup ``H=G1`` corresponding to the Coset Table
could possibly be the canonical representative of its conjugacy class.
Parameters
==========
C: CosetTable
Returns
=======
bool: True/False
If this returns False, then no descendant of C can have that property, and
so we can abandon C. If it returns True, then we need to process further
the node of the search tree corresponding to C, and so we call
``descendant_subgroups`` recursively on C.
Examples
========
>>> from sympy.combinatorics.free_groups import free_group
>>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, first_in_class
>>> F, x, y = free_group("x, y")
>>> f = FpGroup(F, [x**2, y**3, (x*y)**4])
>>> C = CosetTable(f, [])
>>> C.table = [[0, 0, None, None]]
>>> first_in_class(C)
True
>>> C.table = [[1, 1, 1, None], [0, 0, None, 1]]; C.p = [0, 1]
>>> first_in_class(C)
True
>>> C.table = [[1, 1, 2, 1], [0, 0, 0, None], [None, None, None, 0]]
>>> C.p = [0, 1, 2]
>>> first_in_class(C)
False
>>> C.table = [[1, 1, 1, 2], [0, 0, 2, 0], [2, None, 0, 1]]
>>> first_in_class(C)
False
# TODO:: Sims points out in [Sim94] that performance can be improved by
# remembering some of the information computed by ``first_in_class``. If
# the ``continue alpha`` statement is executed at line 14, then the same thing
# will happen for that value of alpha in any descendant of the table C, and so
# the values the values of alpha for which this occurs could profitably be
# stored and passed through to the descendants of C. Of course this would
# make the code more complicated.
# The code below is taken directly from the function on page 208 of [Sim94]
# nu[alpha]
"""
n = C.n
# lamda is the largest numbered point in Omega_c_alpha which is currently defined
lamda = -1
# for alpha in Omega_c, nu[alpha] is the point in Omega_c_alpha corresponding to alpha
nu = [None]*n
# for alpha in Omega_c_alpha, mu[alpha] is the point in Omega_c corresponding to alpha
mu = [None]*n
# mutually nu and mu are the mutually-inverse equivalence maps between
# Omega_c_alpha and Omega_c
next_alpha = False
# For each 0!=alpha in [0 .. nc-1], we start by constructing the equivalent
# standardized coset table C_alpha corresponding to H_alpha
for alpha in range(1, n):
# reset nu to "None" after previous value of alpha
for beta in range(lamda+1):
nu[mu[beta]] = None
# we only want to reject our current table in favour of a preceding
# table in the ordering in which 1 is replaced by alpha, if the subgroup
# G_alpha corresponding to this preceding table definitely contains the
# given subgroup
for w in Y:
# TODO: this should support input of a list of general words
# not just the words which are in "A" (i.e gen and gen^-1)
if C.table[alpha][C.A_dict[w]] != alpha:
# continue with alpha
next_alpha = True
break
if next_alpha:
next_alpha = False
continue
# try alpha as the new point 0 in Omega_C_alpha
mu[0] = alpha
nu[alpha] = 0
# compare corresponding entries in C and C_alpha
lamda = 0
for beta in range(n):
for x in C.A:
gamma = C.table[beta][C.A_dict[x]]
delta = C.table[mu[beta]][C.A_dict[x]]
# if either of the entries is undefined,
# we move with next alpha
if gamma is None or delta is None:
# continue with alpha
next_alpha = True
break
if nu[delta] is None:
# delta becomes the next point in Omega_C_alpha
lamda += 1
nu[delta] = lamda
mu[lamda] = delta
if nu[delta] < gamma:
return False
if nu[delta] > gamma:
# continue with alpha
next_alpha = True
break
if next_alpha:
next_alpha = False
break
return True
#========================================================================
# Simplifying Presentation
#========================================================================
def simplify_presentation(*args, change_gens=False):
'''
For an instance of `FpGroup`, return a simplified isomorphic copy of
the group (e.g. remove redundant generators or relators). Alternatively,
a list of generators and relators can be passed in which case the
simplified lists will be returned.
By default, the generators of the group are unchanged. If you would
like to remove redundant generators, set the keyword argument
`change_gens = True`.
'''
if len(args) == 1:
if not isinstance(args[0], FpGroup):
raise TypeError("The argument must be an instance of FpGroup")
G = args[0]
gens, rels = simplify_presentation(G.generators, G.relators,
change_gens=change_gens)
if gens:
return FpGroup(gens[0].group, rels)
return FpGroup(FreeGroup([]), [])
elif len(args) == 2:
gens, rels = args[0][:], args[1][:]
if not gens:
return gens, rels
identity = gens[0].group.identity
else:
if len(args) == 0:
m = "Not enough arguments"
else:
m = "Too many arguments"
raise RuntimeError(m)
prev_gens = []
prev_rels = []
while not set(prev_rels) == set(rels):
prev_rels = rels
while change_gens and not set(prev_gens) == set(gens):
prev_gens = gens
gens, rels = elimination_technique_1(gens, rels, identity)
rels = _simplify_relators(rels, identity)
if change_gens:
syms = [g.array_form[0][0] for g in gens]
F = free_group(syms)[0]
identity = F.identity
gens = F.generators
subs = dict(zip(syms, gens))
for j, r in enumerate(rels):
a = r.array_form
rel = identity
for sym, p in a:
rel = rel*subs[sym]**p
rels[j] = rel
return gens, rels
def _simplify_relators(rels, identity):
"""Relies upon ``_simplification_technique_1`` for its functioning. """
rels = rels[:]
rels = list(set(_simplification_technique_1(rels)))
rels.sort()
rels = [r.identity_cyclic_reduction() for r in rels]
try:
rels.remove(identity)
except ValueError:
pass
return rels
# Pg 350, section 2.5.1 from [2]
def elimination_technique_1(gens, rels, identity):
rels = rels[:]
# the shorter relators are examined first so that generators selected for
# elimination will have shorter strings as equivalent
rels.sort()
gens = gens[:]
redundant_gens = {}
redundant_rels = []
used_gens = set()
# examine each relator in relator list for any generator occurring exactly
# once
for rel in rels:
# don't look for a redundant generator in a relator which
# depends on previously found ones
contained_gens = rel.contains_generators()
if any([g in contained_gens for g in redundant_gens]):
continue
contained_gens = list(contained_gens)
contained_gens.sort(reverse = True)
for gen in contained_gens:
if rel.generator_count(gen) == 1 and gen not in used_gens:
k = rel.exponent_sum(gen)
gen_index = rel.index(gen**k)
bk = rel.subword(gen_index + 1, len(rel))
fw = rel.subword(0, gen_index)
chi = bk*fw
redundant_gens[gen] = chi**(-1*k)
used_gens.update(chi.contains_generators())
redundant_rels.append(rel)
break
rels = [r for r in rels if r not in redundant_rels]
# eliminate the redundant generators from remaining relators
rels = [r.eliminate_words(redundant_gens, _all = True).identity_cyclic_reduction() for r in rels]
rels = list(set(rels))
try:
rels.remove(identity)
except ValueError:
pass
gens = [g for g in gens if g not in redundant_gens]
return gens, rels
def _simplification_technique_1(rels):
"""
All relators are checked to see if they are of the form `gen^n`. If any
such relators are found then all other relators are processed for strings
in the `gen` known order.
Examples
========
>>> from sympy.combinatorics.free_groups import free_group
>>> from sympy.combinatorics.fp_groups import _simplification_technique_1
>>> F, x, y = free_group("x, y")
>>> w1 = [x**2*y**4, x**3]
>>> _simplification_technique_1(w1)
[x**-1*y**4, x**3]
>>> w2 = [x**2*y**-4*x**5, x**3, x**2*y**8, y**5]
>>> _simplification_technique_1(w2)
[x**-1*y*x**-1, x**3, x**-1*y**-2, y**5]
>>> w3 = [x**6*y**4, x**4]
>>> _simplification_technique_1(w3)
[x**2*y**4, x**4]
"""
from sympy import gcd
rels = rels[:]
# dictionary with "gen: n" where gen^n is one of the relators
exps = {}
for i in range(len(rels)):
rel = rels[i]
if rel.number_syllables() == 1:
g = rel[0]
exp = abs(rel.array_form[0][1])
if rel.array_form[0][1] < 0:
rels[i] = rels[i]**-1
g = g**-1
if g in exps:
exp = gcd(exp, exps[g].array_form[0][1])
exps[g] = g**exp
one_syllables_words = exps.values()
# decrease some of the exponents in relators, making use of the single
# syllable relators
for i in range(len(rels)):
rel = rels[i]
if rel in one_syllables_words:
continue
rel = rel.eliminate_words(one_syllables_words, _all = True)
# if rels[i] contains g**n where abs(n) is greater than half of the power p
# of g in exps, g**n can be replaced by g**(n-p) (or g**(p-n) if n<0)
for g in rel.contains_generators():
if g in exps:
exp = exps[g].array_form[0][1]
max_exp = (exp + 1)//2
rel = rel.eliminate_word(g**(max_exp), g**(max_exp-exp), _all = True)
rel = rel.eliminate_word(g**(-max_exp), g**(-(max_exp-exp)), _all = True)
rels[i] = rel
rels = [r.identity_cyclic_reduction() for r in rels]
return rels
###############################################################################
# SUBGROUP PRESENTATIONS #
###############################################################################
# Pg 175 [1]
def define_schreier_generators(C, homomorphism=False):
'''
Parameters
==========
C -- Coset table.
homomorphism -- When set to True, return a dictionary containing the images
of the presentation generators in the original group.
'''
y = []
gamma = 1
f = C.fp_group
X = f.generators
if homomorphism:
# `_gens` stores the elements of the parent group to
# to which the schreier generators correspond to.
_gens = {}
# compute the schreier Traversal
tau = {}
tau[0] = f.identity
C.P = [[None]*len(C.A) for i in range(C.n)]
for alpha, x in product(C.omega, C.A):
beta = C.table[alpha][C.A_dict[x]]
if beta == gamma:
C.P[alpha][C.A_dict[x]] = "<identity>"
C.P[beta][C.A_dict_inv[x]] = "<identity>"
gamma += 1
if homomorphism:
tau[beta] = tau[alpha]*x
elif x in X and C.P[alpha][C.A_dict[x]] is None:
y_alpha_x = '%s_%s' % (x, alpha)
y.append(y_alpha_x)
C.P[alpha][C.A_dict[x]] = y_alpha_x
if homomorphism:
_gens[y_alpha_x] = tau[alpha]*x*tau[beta]**-1
grp_gens = list(free_group(', '.join(y)))
C._schreier_free_group = grp_gens.pop(0)
C._schreier_generators = grp_gens
if homomorphism:
C._schreier_gen_elem = _gens
# replace all elements of P by, free group elements
for i, j in product(range(len(C.P)), range(len(C.A))):
# if equals "<identity>", replace by identity element
if C.P[i][j] == "<identity>":
C.P[i][j] = C._schreier_free_group.identity
elif isinstance(C.P[i][j], str):
r = C._schreier_generators[y.index(C.P[i][j])]
C.P[i][j] = r
beta = C.table[i][j]
C.P[beta][j + 1] = r**-1
def reidemeister_relators(C):
R = C.fp_group.relators
rels = [rewrite(C, coset, word) for word in R for coset in range(C.n)]
order_1_gens = {i for i in rels if len(i) == 1}
# remove all the order 1 generators from relators
rels = list(filter(lambda rel: rel not in order_1_gens, rels))
# replace order 1 generators by identity element in reidemeister relators
for i in range(len(rels)):
w = rels[i]
w = w.eliminate_words(order_1_gens, _all=True)
rels[i] = w
C._schreier_generators = [i for i in C._schreier_generators
if not (i in order_1_gens or i**-1 in order_1_gens)]
# Tietze transformation 1 i.e TT_1
# remove cyclic conjugate elements from relators
i = 0
while i < len(rels):
w = rels[i]
j = i + 1
while j < len(rels):
if w.is_cyclic_conjugate(rels[j]):
del rels[j]
else:
j += 1
i += 1
C._reidemeister_relators = rels
def rewrite(C, alpha, w):
"""
Parameters
==========
C: CosetTable
alpha: A live coset
w: A word in `A*`
Returns
=======
rho(tau(alpha), w)
Examples
========
>>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, define_schreier_generators, rewrite
>>> from sympy.combinatorics.free_groups import free_group
>>> F, x, y = free_group("x ,y")
>>> f = FpGroup(F, [x**2, y**3, (x*y)**6])
>>> C = CosetTable(f, [])
>>> C.table = [[1, 1, 2, 3], [0, 0, 4, 5], [4, 4, 3, 0], [5, 5, 0, 2], [2, 2, 5, 1], [3, 3, 1, 4]]
>>> C.p = [0, 1, 2, 3, 4, 5]
>>> define_schreier_generators(C)
>>> rewrite(C, 0, (x*y)**6)
x_4*y_2*x_3*x_1*x_2*y_4*x_5
"""
v = C._schreier_free_group.identity
for i in range(len(w)):
x_i = w[i]
v = v*C.P[alpha][C.A_dict[x_i]]
alpha = C.table[alpha][C.A_dict[x_i]]
return v
# Pg 350, section 2.5.2 from [2]
def elimination_technique_2(C):
"""
This technique eliminates one generator at a time. Heuristically this
seems superior in that we may select for elimination the generator with
shortest equivalent string at each stage.
>>> from sympy.combinatorics.free_groups import free_group
>>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r, \
reidemeister_relators, define_schreier_generators, elimination_technique_2
>>> F, x, y = free_group("x, y")
>>> f = FpGroup(F, [x**3, y**5, (x*y)**2]); H = [x*y, x**-1*y**-1*x*y*x]
>>> C = coset_enumeration_r(f, H)
>>> C.compress(); C.standardize()
>>> define_schreier_generators(C)
>>> reidemeister_relators(C)
>>> elimination_technique_2(C)
([y_1, y_2], [y_2**-3, y_2*y_1*y_2*y_1*y_2*y_1, y_1**2])
"""
rels = C._reidemeister_relators
rels.sort(reverse=True)
gens = C._schreier_generators
for i in range(len(gens) - 1, -1, -1):
rel = rels[i]
for j in range(len(gens) - 1, -1, -1):
gen = gens[j]
if rel.generator_count(gen) == 1:
k = rel.exponent_sum(gen)
gen_index = rel.index(gen**k)
bk = rel.subword(gen_index + 1, len(rel))
fw = rel.subword(0, gen_index)
rep_by = (bk*fw)**(-1*k)
del rels[i]; del gens[j]
for l in range(len(rels)):
rels[l] = rels[l].eliminate_word(gen, rep_by)
break
C._reidemeister_relators = rels
C._schreier_generators = gens
return C._schreier_generators, C._reidemeister_relators
def reidemeister_presentation(fp_grp, H, C=None, homomorphism=False):
"""
Parameters
==========
fp_group: A finitely presented group, an instance of FpGroup
H: A subgroup whose presentation is to be found, given as a list
of words in generators of `fp_grp`
homomorphism: When set to True, return a homomorphism from the subgroup
to the parent group
Examples
========
>>> from sympy.combinatorics.free_groups import free_group
>>> from sympy.combinatorics.fp_groups import FpGroup, reidemeister_presentation
>>> F, x, y = free_group("x, y")
Example 5.6 Pg. 177 from [1]
>>> f = FpGroup(F, [x**3, y**5, (x*y)**2])
>>> H = [x*y, x**-1*y**-1*x*y*x]
>>> reidemeister_presentation(f, H)
((y_1, y_2), (y_1**2, y_2**3, y_2*y_1*y_2*y_1*y_2*y_1))
Example 5.8 Pg. 183 from [1]
>>> f = FpGroup(F, [x**3, y**3, (x*y)**3])
>>> H = [x*y, x*y**-1]
>>> reidemeister_presentation(f, H)
((x_0, y_0), (x_0**3, y_0**3, x_0*y_0*x_0*y_0*x_0*y_0))
Exercises Q2. Pg 187 from [1]
>>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3])
>>> H = [x]
>>> reidemeister_presentation(f, H)
((x_0,), (x_0**4,))
Example 5.9 Pg. 183 from [1]
>>> f = FpGroup(F, [x**3*y**-3, (x*y)**3, (x*y**-1)**2])
>>> H = [x]
>>> reidemeister_presentation(f, H)
((x_0,), (x_0**6,))
"""
if not C:
C = coset_enumeration_r(fp_grp, H)
C.compress(); C.standardize()
define_schreier_generators(C, homomorphism=homomorphism)
reidemeister_relators(C)
gens, rels = C._schreier_generators, C._reidemeister_relators
gens, rels = simplify_presentation(gens, rels, change_gens=True)
C.schreier_generators = tuple(gens)
C.reidemeister_relators = tuple(rels)
if homomorphism:
_gens = []
for gen in gens:
_gens.append(C._schreier_gen_elem[str(gen)])
return C.schreier_generators, C.reidemeister_relators, _gens
return C.schreier_generators, C.reidemeister_relators
FpGroupElement = FreeGroupElement
|
1a0f59bccab01cb2d123844f2026223bb5e0465198f459f2caf50108ccedd878 | from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.concrete.expr_with_intlimits import ExprWithIntLimits
from sympy.core.exprtools import factor_terms
from sympy.functions.elementary.exponential import exp, log
from sympy.polys import quo, roots
from sympy.simplify import powsimp
from sympy.core.function import Derivative
from sympy.core.symbol import Dummy, Symbol
class Product(ExprWithIntLimits):
r"""
Represents unevaluated products.
Explanation
===========
``Product`` represents a finite or infinite product, with the first
argument being the general form of terms in the series, and the second
argument being ``(dummy_variable, start, end)``, with ``dummy_variable``
taking all integer values from ``start`` through ``end``. In accordance
with long-standing mathematical convention, the end term is included in
the product.
Finite products
===============
For finite products (and products with symbolic limits assumed to be finite)
we follow the analogue of the summation convention described by Karr [1],
especially definition 3 of section 1.4. The product:
.. math::
\prod_{m \leq i < n} f(i)
has *the obvious meaning* for `m < n`, namely:
.. math::
\prod_{m \leq i < n} f(i) = f(m) f(m+1) \cdot \ldots \cdot f(n-2) f(n-1)
with the upper limit value `f(n)` excluded. The product over an empty set is
one if and only if `m = n`:
.. math::
\prod_{m \leq i < n} f(i) = 1 \quad \mathrm{for} \quad m = n
Finally, for all other products over empty sets we assume the following
definition:
.. math::
\prod_{m \leq i < n} f(i) = \frac{1}{\prod_{n \leq i < m} f(i)} \quad \mathrm{for} \quad m > n
It is important to note that above we define all products with the upper
limit being exclusive. This is in contrast to the usual mathematical notation,
but does not affect the product convention. Indeed we have:
.. math::
\prod_{m \leq i < n} f(i) = \prod_{i = m}^{n - 1} f(i)
where the difference in notation is intentional to emphasize the meaning,
with limits typeset on the top being inclusive.
Examples
========
>>> from sympy.abc import a, b, i, k, m, n, x
>>> from sympy import Product, oo
>>> Product(k, (k, 1, m))
Product(k, (k, 1, m))
>>> Product(k, (k, 1, m)).doit()
factorial(m)
>>> Product(k**2,(k, 1, m))
Product(k**2, (k, 1, m))
>>> Product(k**2,(k, 1, m)).doit()
factorial(m)**2
Wallis' product for pi:
>>> W = Product(2*i/(2*i-1) * 2*i/(2*i+1), (i, 1, oo))
>>> W
Product(4*i**2/((2*i - 1)*(2*i + 1)), (i, 1, oo))
Direct computation currently fails:
>>> W.doit()
Product(4*i**2/((2*i - 1)*(2*i + 1)), (i, 1, oo))
But we can approach the infinite product by a limit of finite products:
>>> from sympy import limit
>>> W2 = Product(2*i/(2*i-1)*2*i/(2*i+1), (i, 1, n))
>>> W2
Product(4*i**2/((2*i - 1)*(2*i + 1)), (i, 1, n))
>>> W2e = W2.doit()
>>> W2e
4**n*factorial(n)**2/(2**(2*n)*RisingFactorial(1/2, n)*RisingFactorial(3/2, n))
>>> limit(W2e, n, oo)
pi/2
By the same formula we can compute sin(pi/2):
>>> from sympy import combsimp, pi, gamma, simplify
>>> P = pi * x * Product(1 - x**2/k**2, (k, 1, n))
>>> P = P.subs(x, pi/2)
>>> P
pi**2*Product(1 - pi**2/(4*k**2), (k, 1, n))/2
>>> Pe = P.doit()
>>> Pe
pi**2*RisingFactorial(1 - pi/2, n)*RisingFactorial(1 + pi/2, n)/(2*factorial(n)**2)
>>> limit(Pe, n, oo).gammasimp()
sin(pi**2/2)
>>> Pe.rewrite(gamma)
(-1)**n*pi**2*gamma(pi/2)*gamma(n + 1 + pi/2)/(2*gamma(1 + pi/2)*gamma(-n + pi/2)*gamma(n + 1)**2)
Products with the lower limit being larger than the upper one:
>>> Product(1/i, (i, 6, 1)).doit()
120
>>> Product(i, (i, 2, 5)).doit()
120
The empty product:
>>> Product(i, (i, n, n-1)).doit()
1
An example showing that the symbolic result of a product is still
valid for seemingly nonsensical values of the limits. Then the Karr
convention allows us to give a perfectly valid interpretation to
those products by interchanging the limits according to the above rules:
>>> P = Product(2, (i, 10, n)).doit()
>>> P
2**(n - 9)
>>> P.subs(n, 5)
1/16
>>> Product(2, (i, 10, 5)).doit()
1/16
>>> 1/Product(2, (i, 6, 9)).doit()
1/16
An explicit example of the Karr summation convention applied to products:
>>> P1 = Product(x, (i, a, b)).doit()
>>> P1
x**(-a + b + 1)
>>> P2 = Product(x, (i, b+1, a-1)).doit()
>>> P2
x**(a - b - 1)
>>> simplify(P1 * P2)
1
And another one:
>>> P1 = Product(i, (i, b, a)).doit()
>>> P1
RisingFactorial(b, a - b + 1)
>>> P2 = Product(i, (i, a+1, b-1)).doit()
>>> P2
RisingFactorial(a + 1, -a + b - 1)
>>> P1 * P2
RisingFactorial(b, a - b + 1)*RisingFactorial(a + 1, -a + b - 1)
>>> combsimp(P1 * P2)
1
See Also
========
Sum, summation
product
References
==========
.. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
Volume 28 Issue 2, April 1981, Pages 305-350
http://dl.acm.org/citation.cfm?doid=322248.322255
.. [2] https://en.wikipedia.org/wiki/Multiplication#Capital_Pi_notation
.. [3] https://en.wikipedia.org/wiki/Empty_product
"""
__slots__ = ('is_commutative',)
def __new__(cls, function, *symbols, **assumptions):
obj = ExprWithIntLimits.__new__(cls, function, *symbols, **assumptions)
return obj
def _eval_rewrite_as_Sum(self, *args, **kwargs):
from sympy.concrete.summations import Sum
return exp(Sum(log(self.function), *self.limits))
@property
def term(self):
return self._args[0]
function = term
def _eval_is_zero(self):
if self.has_empty_sequence:
return False
z = self.term.is_zero
if z is True:
return True
if self.has_finite_limits:
# A Product is zero only if its term is zero assuming finite limits.
return z
def _eval_is_extended_real(self):
if self.has_empty_sequence:
return True
return self.function.is_extended_real
def _eval_is_positive(self):
if self.has_empty_sequence:
return True
if self.function.is_positive and self.has_finite_limits:
return True
def _eval_is_nonnegative(self):
if self.has_empty_sequence:
return True
if self.function.is_nonnegative and self.has_finite_limits:
return True
def _eval_is_extended_nonnegative(self):
if self.has_empty_sequence:
return True
if self.function.is_extended_nonnegative:
return True
def _eval_is_extended_nonpositive(self):
if self.has_empty_sequence:
return True
def _eval_is_finite(self):
if self.has_finite_limits and self.function.is_finite:
return True
def doit(self, **hints):
# first make sure any definite limits have product
# variables with matching assumptions
reps = {}
for xab in self.limits:
# Must be imported here to avoid circular imports
from .summations import _dummy_with_inherited_properties_concrete
d = _dummy_with_inherited_properties_concrete(xab)
if d:
reps[xab[0]] = d
if reps:
undo = {v: k for k, v in reps.items()}
did = self.xreplace(reps).doit(**hints)
if type(did) is tuple: # when separate=True
did = tuple([i.xreplace(undo) for i in did])
else:
did = did.xreplace(undo)
return did
f = self.function
for index, limit in enumerate(self.limits):
i, a, b = limit
dif = b - a
if dif.is_integer and dif.is_negative:
a, b = b + 1, a - 1
f = 1 / f
g = self._eval_product(f, (i, a, b))
if g in (None, S.NaN):
return self.func(powsimp(f), *self.limits[index:])
else:
f = g
if hints.get('deep', True):
return f.doit(**hints)
else:
return powsimp(f)
def _eval_adjoint(self):
if self.is_commutative:
return self.func(self.function.adjoint(), *self.limits)
return None
def _eval_conjugate(self):
return self.func(self.function.conjugate(), *self.limits)
def _eval_product(self, term, limits):
from sympy.concrete.delta import deltaproduct, _has_simple_delta
from sympy.concrete.summations import summation
from sympy.functions import KroneckerDelta, RisingFactorial
(k, a, n) = limits
if k not in term.free_symbols:
if (term - 1).is_zero:
return S.One
return term**(n - a + 1)
if a == n:
return term.subs(k, a)
if term.has(KroneckerDelta) and _has_simple_delta(term, limits[0]):
return deltaproduct(term, limits)
dif = n - a
definite = dif.is_Integer
if definite and (dif < 100):
return self._eval_product_direct(term, limits)
elif term.is_polynomial(k):
poly = term.as_poly(k)
A = B = Q = S.One
all_roots = roots(poly)
M = 0
for r, m in all_roots.items():
M += m
A *= RisingFactorial(a - r, n - a + 1)**m
Q *= (n - r)**m
if M < poly.degree():
arg = quo(poly, Q.as_poly(k))
B = self.func(arg, (k, a, n)).doit()
return poly.LC()**(n - a + 1) * A * B
elif term.is_Add:
factored = factor_terms(term, fraction=True)
if factored.is_Mul:
return self._eval_product(factored, (k, a, n))
elif term.is_Mul:
# Factor in part without the summation variable and part with
without_k, with_k = term.as_coeff_mul(k)
if len(with_k) >= 2:
# More than one term including k, so still a multiplication
exclude, include = [], []
for t in with_k:
p = self._eval_product(t, (k, a, n))
if p is not None:
exclude.append(p)
else:
include.append(t)
if not exclude:
return None
else:
arg = term._new_rawargs(*include)
A = Mul(*exclude)
B = self.func(arg, (k, a, n)).doit()
return without_k**(n - a + 1)*A * B
else:
# Just a single term
p = self._eval_product(with_k[0], (k, a, n))
if p is None:
p = self.func(with_k[0], (k, a, n)).doit()
return without_k**(n - a + 1)*p
elif term.is_Pow:
if not term.base.has(k):
s = summation(term.exp, (k, a, n))
return term.base**s
elif not term.exp.has(k):
p = self._eval_product(term.base, (k, a, n))
if p is not None:
return p**term.exp
elif isinstance(term, Product):
evaluated = term.doit()
f = self._eval_product(evaluated, limits)
if f is None:
return self.func(evaluated, limits)
else:
return f
if definite:
return self._eval_product_direct(term, limits)
def _eval_simplify(self, **kwargs):
from sympy.simplify.simplify import product_simplify
rv = product_simplify(self)
return rv.doit() if kwargs['doit'] else rv
def _eval_transpose(self):
if self.is_commutative:
return self.func(self.function.transpose(), *self.limits)
return None
def _eval_product_direct(self, term, limits):
(k, a, n) = limits
return Mul(*[term.subs(k, a + i) for i in range(n - a + 1)])
def _eval_derivative(self, x):
from sympy.concrete.summations import Sum
if isinstance(x, Symbol) and x not in self.free_symbols:
return S.Zero
f, limits = self.function, list(self.limits)
limit = limits.pop(-1)
if limits:
f = self.func(f, *limits)
i, a, b = limit
if x in a.free_symbols or x in b.free_symbols:
return None
h = Dummy()
rv = Sum( Product(f, (i, a, h - 1)) * Product(f, (i, h + 1, b)) * Derivative(f, x, evaluate=True).subs(i, h), (h, a, b))
return rv
def is_convergent(self):
r"""
See docs of :obj:`.Sum.is_convergent()` for explanation of convergence
in SymPy.
Explanation
===========
The infinite product:
.. math::
\prod_{1 \leq i < \infty} f(i)
is defined by the sequence of partial products:
.. math::
\prod_{i=1}^{n} f(i) = f(1) f(2) \cdots f(n)
as n increases without bound. The product converges to a non-zero
value if and only if the sum:
.. math::
\sum_{1 \leq i < \infty} \log{f(n)}
converges.
Examples
========
>>> from sympy import Product, Symbol, cos, pi, exp, oo
>>> n = Symbol('n', integer=True)
>>> Product(n/(n + 1), (n, 1, oo)).is_convergent()
False
>>> Product(1/n**2, (n, 1, oo)).is_convergent()
False
>>> Product(cos(pi/n), (n, 1, oo)).is_convergent()
True
>>> Product(exp(-n**2), (n, 1, oo)).is_convergent()
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Infinite_product
"""
from sympy.concrete.summations import Sum
sequence_term = self.function
log_sum = log(sequence_term)
lim = self.limits
try:
is_conv = Sum(log_sum, *lim).is_convergent()
except NotImplementedError:
if Sum(sequence_term - 1, *lim).is_absolutely_convergent() is S.true:
return S.true
raise NotImplementedError("The algorithm to find the product convergence of %s "
"is not yet implemented" % (sequence_term))
return is_conv
def reverse_order(expr, *indices):
"""
Reverse the order of a limit in a Product.
Explanation
===========
``reverse_order(expr, *indices)`` reverses some limits in the expression
``expr`` which can be either a ``Sum`` or a ``Product``. The selectors in
the argument ``indices`` specify some indices whose limits get reversed.
These selectors are either variable names or numerical indices counted
starting from the inner-most limit tuple.
Examples
========
>>> from sympy import gamma, Product, simplify, Sum
>>> from sympy.abc import x, y, a, b, c, d
>>> P = Product(x, (x, a, b))
>>> Pr = P.reverse_order(x)
>>> Pr
Product(1/x, (x, b + 1, a - 1))
>>> Pr = Pr.doit()
>>> Pr
1/RisingFactorial(b + 1, a - b - 1)
>>> simplify(Pr.rewrite(gamma))
Piecewise((gamma(b + 1)/gamma(a), b > -1), ((-1)**(-a + b + 1)*gamma(1 - a)/gamma(-b), True))
>>> P = P.doit()
>>> P
RisingFactorial(a, -a + b + 1)
>>> simplify(P.rewrite(gamma))
Piecewise((gamma(b + 1)/gamma(a), a > 0), ((-1)**(-a + b + 1)*gamma(1 - a)/gamma(-b), True))
While one should prefer variable names when specifying which limits
to reverse, the index counting notation comes in handy in case there
are several symbols with the same name.
>>> S = Sum(x*y, (x, a, b), (y, c, d))
>>> S
Sum(x*y, (x, a, b), (y, c, d))
>>> S0 = S.reverse_order(0)
>>> S0
Sum(-x*y, (x, b + 1, a - 1), (y, c, d))
>>> S1 = S0.reverse_order(1)
>>> S1
Sum(x*y, (x, b + 1, a - 1), (y, d + 1, c - 1))
Of course we can mix both notations:
>>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1)
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
>>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x)
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
See Also
========
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index,
reorder_limit,
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder
References
==========
.. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
Volume 28 Issue 2, April 1981, Pages 305-350
http://dl.acm.org/citation.cfm?doid=322248.322255
"""
l_indices = list(indices)
for i, indx in enumerate(l_indices):
if not isinstance(indx, int):
l_indices[i] = expr.index(indx)
e = 1
limits = []
for i, limit in enumerate(expr.limits):
l = limit
if i in l_indices:
e = -e
l = (limit[0], limit[2] + 1, limit[1] - 1)
limits.append(l)
return Product(expr.function ** e, *limits)
def product(*args, **kwargs):
r"""
Compute the product.
Explanation
===========
The notation for symbols is similar to the notation used in Sum or
Integral. product(f, (i, a, b)) computes the product of f with
respect to i from a to b, i.e.,
::
b
_____
product(f(n), (i, a, b)) = | | f(n)
| |
i = a
If it cannot compute the product, it returns an unevaluated Product object.
Repeated products can be computed by introducing additional symbols tuples::
Examples
========
>>> from sympy import product, symbols
>>> i, n, m, k = symbols('i n m k', integer=True)
>>> product(i, (i, 1, k))
factorial(k)
>>> product(m, (i, 1, k))
m**k
>>> product(i, (i, 1, k), (k, 1, n))
Product(factorial(k), (k, 1, n))
"""
prod = Product(*args, **kwargs)
if isinstance(prod, Product):
return prod.doit(deep=False)
else:
return prod
|
fe60b0ac147a4082bbb839b3f1b5aaad237b91b93e98f27754961d424c14bed8 | """Formal Power Series"""
from collections import defaultdict
from sympy import oo, zoo, nan
from sympy.core.add import Add
from sympy.core.compatibility import iterable
from sympy.core.expr import Expr
from sympy.core.function import Derivative, Function, expand
from sympy.core.mul import Mul
from sympy.core.numbers import Rational
from sympy.core.relational import Eq
from sympy.sets.sets import Interval
from sympy.core.singleton import S
from sympy.core.symbol import Wild, Dummy, symbols, Symbol
from sympy.core.sympify import sympify
from sympy.discrete.convolutions import convolution
from sympy.functions.combinatorial.factorials import binomial, factorial, rf
from sympy.functions.combinatorial.numbers import bell
from sympy.functions.elementary.integers import floor, frac, ceiling
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.functions.elementary.piecewise import Piecewise
from sympy.series.limits import Limit
from sympy.series.order import Order
from sympy.simplify.powsimp import powsimp
from sympy.series.sequences import sequence
from sympy.series.series_class import SeriesBase
def rational_algorithm(f, x, k, order=4, full=False):
"""
Rational algorithm for computing
formula of coefficients of Formal Power Series
of a function.
Explanation
===========
Applicable when f(x) or some derivative of f(x)
is a rational function in x.
:func:`rational_algorithm` uses :func:`~.apart` function for partial fraction
decomposition. :func:`~.apart` by default uses 'undetermined coefficients
method'. By setting ``full=True``, 'Bronstein's algorithm' can be used
instead.
Looks for derivative of a function up to 4'th order (by default).
This can be overridden using order option.
Parameters
==========
x : Symbol
order : int, optional
Order of the derivative of ``f``, Default is 4.
full : bool
Returns
=======
formula : Expr
ind : Expr
Independent terms.
order : int
full : bool
Examples
========
>>> from sympy import log, atan
>>> from sympy.series.formal import rational_algorithm as ra
>>> from sympy.abc import x, k
>>> ra(1 / (1 - x), x, k)
(1, 0, 0)
>>> ra(log(1 + x), x, k)
(-1/((-1)**k*k), 0, 1)
>>> ra(atan(x), x, k, full=True)
((-I/(2*(-I)**k) + I/(2*I**k))/k, 0, 1)
Notes
=====
By setting ``full=True``, range of admissible functions to be solved using
``rational_algorithm`` can be increased. This option should be used
carefully as it can significantly slow down the computation as ``doit`` is
performed on the :class:`~.RootSum` object returned by the :func:`~.apart`
function. Use ``full=False`` whenever possible.
See Also
========
sympy.polys.partfrac.apart
References
==========
.. [1] Formal Power Series - Dominik Gruntz, Wolfram Koepf
.. [2] Power Series in Computer Algebra - Wolfram Koepf
"""
from sympy.polys import RootSum, apart
from sympy.integrals import integrate
diff = f
ds = [] # list of diff
for i in range(order + 1):
if i:
diff = diff.diff(x)
if diff.is_rational_function(x):
coeff, sep = S.Zero, S.Zero
terms = apart(diff, x, full=full)
if terms.has(RootSum):
terms = terms.doit()
for t in Add.make_args(terms):
num, den = t.as_numer_denom()
if not den.has(x):
sep += t
else:
if isinstance(den, Mul):
# m*(n*x - a)**j -> (n*x - a)**j
ind = den.as_independent(x)
den = ind[1]
num /= ind[0]
# (n*x - a)**j -> (x - b)
den, j = den.as_base_exp()
a, xterm = den.as_coeff_add(x)
# term -> m/x**n
if not a:
sep += t
continue
xc = xterm[0].coeff(x)
a /= -xc
num /= xc**j
ak = ((-1)**j * num *
binomial(j + k - 1, k).rewrite(factorial) /
a**(j + k))
coeff += ak
# Hacky, better way?
if coeff.is_zero:
return None
if (coeff.has(x) or coeff.has(zoo) or coeff.has(oo) or
coeff.has(nan)):
return None
for j in range(i):
coeff = (coeff / (k + j + 1))
sep = integrate(sep, x)
sep += (ds.pop() - sep).limit(x, 0) # constant of integration
return (coeff.subs(k, k - i), sep, i)
else:
ds.append(diff)
return None
def rational_independent(terms, x):
"""
Returns a list of all the rationally independent terms.
Examples
========
>>> from sympy import sin, cos
>>> from sympy.series.formal import rational_independent
>>> from sympy.abc import x
>>> rational_independent([cos(x), sin(x)], x)
[cos(x), sin(x)]
>>> rational_independent([x**2, sin(x), x*sin(x), x**3], x)
[x**3 + x**2, x*sin(x) + sin(x)]
"""
if not terms:
return []
ind = terms[0:1]
for t in terms[1:]:
n = t.as_independent(x)[1]
for i, term in enumerate(ind):
d = term.as_independent(x)[1]
q = (n / d).cancel()
if q.is_rational_function(x):
ind[i] += t
break
else:
ind.append(t)
return ind
def simpleDE(f, x, g, order=4):
r"""
Generates simple DE.
Explanation
===========
DE is of the form
.. math::
f^k(x) + \sum\limits_{j=0}^{k-1} A_j f^j(x) = 0
where :math:`A_j` should be rational function in x.
Generates DE's upto order 4 (default). DE's can also have free parameters.
By increasing order, higher order DE's can be found.
Yields a tuple of (DE, order).
"""
from sympy.solvers.solveset import linsolve
a = symbols('a:%d' % (order))
def _makeDE(k):
eq = f.diff(x, k) + Add(*[a[i]*f.diff(x, i) for i in range(0, k)])
DE = g(x).diff(x, k) + Add(*[a[i]*g(x).diff(x, i) for i in range(0, k)])
return eq, DE
found = False
for k in range(1, order + 1):
eq, DE = _makeDE(k)
eq = eq.expand()
terms = eq.as_ordered_terms()
ind = rational_independent(terms, x)
if found or len(ind) == k:
sol = dict(zip(a, (i for s in linsolve(ind, a[:k]) for i in s)))
if sol:
found = True
DE = DE.subs(sol)
DE = DE.as_numer_denom()[0]
DE = DE.factor().as_coeff_mul(Derivative)[1][0]
yield DE.collect(Derivative(g(x))), k
def exp_re(DE, r, k):
"""Converts a DE with constant coefficients (explike) into a RE.
Explanation
===========
Performs the substitution:
.. math::
f^j(x) \\to r(k + j)
Normalises the terms so that lowest order of a term is always r(k).
Examples
========
>>> from sympy import Function, Derivative
>>> from sympy.series.formal import exp_re
>>> from sympy.abc import x, k
>>> f, r = Function('f'), Function('r')
>>> exp_re(-f(x) + Derivative(f(x)), r, k)
-r(k) + r(k + 1)
>>> exp_re(Derivative(f(x), x) + Derivative(f(x), (x, 2)), r, k)
r(k) + r(k + 1)
See Also
========
sympy.series.formal.hyper_re
"""
RE = S.Zero
g = DE.atoms(Function).pop()
mini = None
for t in Add.make_args(DE):
coeff, d = t.as_independent(g)
if isinstance(d, Derivative):
j = d.derivative_count
else:
j = 0
if mini is None or j < mini:
mini = j
RE += coeff * r(k + j)
if mini:
RE = RE.subs(k, k - mini)
return RE
def hyper_re(DE, r, k):
"""
Converts a DE into a RE.
Explanation
===========
Performs the substitution:
.. math::
x^l f^j(x) \\to (k + 1 - l)_j . a_{k + j - l}
Normalises the terms so that lowest order of a term is always r(k).
Examples
========
>>> from sympy import Function, Derivative
>>> from sympy.series.formal import hyper_re
>>> from sympy.abc import x, k
>>> f, r = Function('f'), Function('r')
>>> hyper_re(-f(x) + Derivative(f(x)), r, k)
(k + 1)*r(k + 1) - r(k)
>>> hyper_re(-x*f(x) + Derivative(f(x), (x, 2)), r, k)
(k + 2)*(k + 3)*r(k + 3) - r(k)
See Also
========
sympy.series.formal.exp_re
"""
RE = S.Zero
g = DE.atoms(Function).pop()
x = g.atoms(Symbol).pop()
mini = None
for t in Add.make_args(DE.expand()):
coeff, d = t.as_independent(g)
c, v = coeff.as_independent(x)
l = v.as_coeff_exponent(x)[1]
if isinstance(d, Derivative):
j = d.derivative_count
else:
j = 0
RE += c * rf(k + 1 - l, j) * r(k + j - l)
if mini is None or j - l < mini:
mini = j - l
RE = RE.subs(k, k - mini)
m = Wild('m')
return RE.collect(r(k + m))
def _transformation_a(f, x, P, Q, k, m, shift):
f *= x**(-shift)
P = P.subs(k, k + shift)
Q = Q.subs(k, k + shift)
return f, P, Q, m
def _transformation_c(f, x, P, Q, k, m, scale):
f = f.subs(x, x**scale)
P = P.subs(k, k / scale)
Q = Q.subs(k, k / scale)
m *= scale
return f, P, Q, m
def _transformation_e(f, x, P, Q, k, m):
f = f.diff(x)
P = P.subs(k, k + 1) * (k + m + 1)
Q = Q.subs(k, k + 1) * (k + 1)
return f, P, Q, m
def _apply_shift(sol, shift):
return [(res, cond + shift) for res, cond in sol]
def _apply_scale(sol, scale):
return [(res, cond / scale) for res, cond in sol]
def _apply_integrate(sol, x, k):
return [(res / ((cond + 1)*(cond.as_coeff_Add()[1].coeff(k))), cond + 1)
for res, cond in sol]
def _compute_formula(f, x, P, Q, k, m, k_max):
"""Computes the formula for f."""
from sympy.polys import roots
sol = []
for i in range(k_max + 1, k_max + m + 1):
if (i < 0) == True:
continue
r = f.diff(x, i).limit(x, 0) / factorial(i)
if r.is_zero:
continue
kterm = m*k + i
res = r
p = P.subs(k, kterm)
q = Q.subs(k, kterm)
c1 = p.subs(k, 1/k).leadterm(k)[0]
c2 = q.subs(k, 1/k).leadterm(k)[0]
res *= (-c1 / c2)**k
for r, mul in roots(p, k).items():
res *= rf(-r, k)**mul
for r, mul in roots(q, k).items():
res /= rf(-r, k)**mul
sol.append((res, kterm))
return sol
def _rsolve_hypergeometric(f, x, P, Q, k, m):
"""
Recursive wrapper to rsolve_hypergeometric.
Explanation
===========
Returns a Tuple of (formula, series independent terms,
maximum power of x in independent terms) if successful
otherwise ``None``.
See :func:`rsolve_hypergeometric` for details.
"""
from sympy.polys import lcm, roots
from sympy.integrals import integrate
# transformation - c
proots, qroots = roots(P, k), roots(Q, k)
all_roots = dict(proots)
all_roots.update(qroots)
scale = lcm([r.as_numer_denom()[1] for r, t in all_roots.items()
if r.is_rational])
f, P, Q, m = _transformation_c(f, x, P, Q, k, m, scale)
# transformation - a
qroots = roots(Q, k)
if qroots:
k_min = Min(*qroots.keys())
else:
k_min = S.Zero
shift = k_min + m
f, P, Q, m = _transformation_a(f, x, P, Q, k, m, shift)
l = (x*f).limit(x, 0)
if not isinstance(l, Limit) and l != 0: # Ideally should only be l != 0
return None
qroots = roots(Q, k)
if qroots:
k_max = Max(*qroots.keys())
else:
k_max = S.Zero
ind, mp = S.Zero, -oo
for i in range(k_max + m + 1):
r = f.diff(x, i).limit(x, 0) / factorial(i)
if r.is_finite is False:
old_f = f
f, P, Q, m = _transformation_a(f, x, P, Q, k, m, i)
f, P, Q, m = _transformation_e(f, x, P, Q, k, m)
sol, ind, mp = _rsolve_hypergeometric(f, x, P, Q, k, m)
sol = _apply_integrate(sol, x, k)
sol = _apply_shift(sol, i)
ind = integrate(ind, x)
ind += (old_f - ind).limit(x, 0) # constant of integration
mp += 1
return sol, ind, mp
elif r:
ind += r*x**(i + shift)
pow_x = Rational((i + shift), scale)
if pow_x > mp:
mp = pow_x # maximum power of x
ind = ind.subs(x, x**(1/scale))
sol = _compute_formula(f, x, P, Q, k, m, k_max)
sol = _apply_shift(sol, shift)
sol = _apply_scale(sol, scale)
return sol, ind, mp
def rsolve_hypergeometric(f, x, P, Q, k, m):
"""
Solves RE of hypergeometric type.
Explanation
===========
Attempts to solve RE of the form
Q(k)*a(k + m) - P(k)*a(k)
Transformations that preserve Hypergeometric type:
a. x**n*f(x): b(k + m) = R(k - n)*b(k)
b. f(A*x): b(k + m) = A**m*R(k)*b(k)
c. f(x**n): b(k + n*m) = R(k/n)*b(k)
d. f(x**(1/m)): b(k + 1) = R(k*m)*b(k)
e. f'(x): b(k + m) = ((k + m + 1)/(k + 1))*R(k + 1)*b(k)
Some of these transformations have been used to solve the RE.
Returns
=======
formula : Expr
ind : Expr
Independent terms.
order : int
Examples
========
>>> from sympy import exp, ln, S
>>> from sympy.series.formal import rsolve_hypergeometric as rh
>>> from sympy.abc import x, k
>>> rh(exp(x), x, -S.One, (k + 1), k, 1)
(Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)
>>> rh(ln(1 + x), x, k**2, k*(k + 1), k, 1)
(Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
Eq(Mod(k, 1), 0)), (0, True)), x, 2)
References
==========
.. [1] Formal Power Series - Dominik Gruntz, Wolfram Koepf
.. [2] Power Series in Computer Algebra - Wolfram Koepf
"""
result = _rsolve_hypergeometric(f, x, P, Q, k, m)
if result is None:
return None
sol_list, ind, mp = result
sol_dict = defaultdict(lambda: S.Zero)
for res, cond in sol_list:
j, mk = cond.as_coeff_Add()
c = mk.coeff(k)
if j.is_integer is False:
res *= x**frac(j)
j = floor(j)
res = res.subs(k, (k - j) / c)
cond = Eq(k % c, j % c)
sol_dict[cond] += res # Group together formula for same conditions
sol = []
for cond, res in sol_dict.items():
sol.append((res, cond))
sol.append((S.Zero, True))
sol = Piecewise(*sol)
if mp is -oo:
s = S.Zero
elif mp.is_integer is False:
s = ceiling(mp)
else:
s = mp + 1
# save all the terms of
# form 1/x**k in ind
if s < 0:
ind += sum(sequence(sol * x**k, (k, s, -1)))
s = S.Zero
return (sol, ind, s)
def _solve_hyper_RE(f, x, RE, g, k):
"""See docstring of :func:`rsolve_hypergeometric` for details."""
terms = Add.make_args(RE)
if len(terms) == 2:
gs = list(RE.atoms(Function))
P, Q = map(RE.coeff, gs)
m = gs[1].args[0] - gs[0].args[0]
if m < 0:
P, Q = Q, P
m = abs(m)
return rsolve_hypergeometric(f, x, P, Q, k, m)
def _solve_explike_DE(f, x, DE, g, k):
"""Solves DE with constant coefficients."""
from sympy.solvers import rsolve
for t in Add.make_args(DE):
coeff, d = t.as_independent(g)
if coeff.free_symbols:
return
RE = exp_re(DE, g, k)
init = {}
for i in range(len(Add.make_args(RE))):
if i:
f = f.diff(x)
init[g(k).subs(k, i)] = f.limit(x, 0)
sol = rsolve(RE, g(k), init)
if sol:
return (sol / factorial(k), S.Zero, S.Zero)
def _solve_simple(f, x, DE, g, k):
"""Converts DE into RE and solves using :func:`rsolve`."""
from sympy.solvers import rsolve
RE = hyper_re(DE, g, k)
init = {}
for i in range(len(Add.make_args(RE))):
if i:
f = f.diff(x)
init[g(k).subs(k, i)] = f.limit(x, 0) / factorial(i)
sol = rsolve(RE, g(k), init)
if sol:
return (sol, S.Zero, S.Zero)
def _transform_explike_DE(DE, g, x, order, syms):
"""Converts DE with free parameters into DE with constant coefficients."""
from sympy.solvers.solveset import linsolve
eq = []
highest_coeff = DE.coeff(Derivative(g(x), x, order))
for i in range(order):
coeff = DE.coeff(Derivative(g(x), x, i))
coeff = (coeff / highest_coeff).expand().collect(x)
for t in Add.make_args(coeff):
eq.append(t)
temp = []
for e in eq:
if e.has(x):
break
elif e.has(Symbol):
temp.append(e)
else:
eq = temp
if eq:
sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
if sol:
DE = DE.subs(sol)
DE = DE.factor().as_coeff_mul(Derivative)[1][0]
DE = DE.collect(Derivative(g(x)))
return DE
def _transform_DE_RE(DE, g, k, order, syms):
"""Converts DE with free parameters into RE of hypergeometric type."""
from sympy.solvers.solveset import linsolve
RE = hyper_re(DE, g, k)
eq = []
for i in range(1, order):
coeff = RE.coeff(g(k + i))
eq.append(coeff)
sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
if sol:
m = Wild('m')
RE = RE.subs(sol)
RE = RE.factor().as_numer_denom()[0].collect(g(k + m))
RE = RE.as_coeff_mul(g)[1][0]
for i in range(order): # smallest order should be g(k)
if RE.coeff(g(k + i)) and i:
RE = RE.subs(k, k - i)
break
return RE
def solve_de(f, x, DE, order, g, k):
"""
Solves the DE.
Explanation
===========
Tries to solve DE by either converting into a RE containing two terms or
converting into a DE having constant coefficients.
Returns
=======
formula : Expr
ind : Expr
Independent terms.
order : int
Examples
========
>>> from sympy import Derivative as D, Function
>>> from sympy import exp, ln
>>> from sympy.series.formal import solve_de
>>> from sympy.abc import x, k
>>> f = Function('f')
>>> solve_de(exp(x), x, D(f(x), x) - f(x), 1, f, k)
(Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)
>>> solve_de(ln(1 + x), x, (x + 1)*D(f(x), x, 2) + D(f(x)), 2, f, k)
(Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
Eq(Mod(k, 1), 0)), (0, True)), x, 2)
"""
sol = None
syms = DE.free_symbols.difference({g, x})
if syms:
RE = _transform_DE_RE(DE, g, k, order, syms)
else:
RE = hyper_re(DE, g, k)
if not RE.free_symbols.difference({k}):
sol = _solve_hyper_RE(f, x, RE, g, k)
if sol:
return sol
if syms:
DE = _transform_explike_DE(DE, g, x, order, syms)
if not DE.free_symbols.difference({x}):
sol = _solve_explike_DE(f, x, DE, g, k)
if sol:
return sol
def hyper_algorithm(f, x, k, order=4):
"""
Hypergeometric algorithm for computing Formal Power Series.
Explanation
===========
Steps:
* Generates DE
* Convert the DE into RE
* Solves the RE
Examples
========
>>> from sympy import exp, ln
>>> from sympy.series.formal import hyper_algorithm
>>> from sympy.abc import x, k
>>> hyper_algorithm(exp(x), x, k)
(Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)
>>> hyper_algorithm(ln(1 + x), x, k)
(Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
Eq(Mod(k, 1), 0)), (0, True)), x, 2)
See Also
========
sympy.series.formal.simpleDE
sympy.series.formal.solve_de
"""
g = Function('g')
des = [] # list of DE's
sol = None
for DE, i in simpleDE(f, x, g, order):
if DE is not None:
sol = solve_de(f, x, DE, i, g, k)
if sol:
return sol
if not DE.free_symbols.difference({x}):
des.append(DE)
# If nothing works
# Try plain rsolve
for DE in des:
sol = _solve_simple(f, x, DE, g, k)
if sol:
return sol
def _compute_fps(f, x, x0, dir, hyper, order, rational, full):
"""Recursive wrapper to compute fps.
See :func:`compute_fps` for details.
"""
if x0 in [S.Infinity, S.NegativeInfinity]:
dir = S.One if x0 is S.Infinity else -S.One
temp = f.subs(x, 1/x)
result = _compute_fps(temp, x, 0, dir, hyper, order, rational, full)
if result is None:
return None
return (result[0], result[1].subs(x, 1/x), result[2].subs(x, 1/x))
elif x0 or dir == -S.One:
if dir == -S.One:
rep = -x + x0
rep2 = -x
rep2b = x0
else:
rep = x + x0
rep2 = x
rep2b = -x0
temp = f.subs(x, rep)
result = _compute_fps(temp, x, 0, S.One, hyper, order, rational, full)
if result is None:
return None
return (result[0], result[1].subs(x, rep2 + rep2b),
result[2].subs(x, rep2 + rep2b))
if f.is_polynomial(x):
k = Dummy('k')
ak = sequence(Coeff(f, x, k), (k, 1, oo))
xk = sequence(x**k, (k, 0, oo))
ind = f.coeff(x, 0)
return ak, xk, ind
# Break instances of Add
# this allows application of different
# algorithms on different terms increasing the
# range of admissible functions.
if isinstance(f, Add):
result = False
ak = sequence(S.Zero, (0, oo))
ind, xk = S.Zero, None
for t in Add.make_args(f):
res = _compute_fps(t, x, 0, S.One, hyper, order, rational, full)
if res:
if not result:
result = True
xk = res[1]
if res[0].start > ak.start:
seq = ak
s, f = ak.start, res[0].start
else:
seq = res[0]
s, f = res[0].start, ak.start
save = Add(*[z[0]*z[1] for z in zip(seq[0:(f - s)], xk[s:f])])
ak += res[0]
ind += res[2] + save
else:
ind += t
if result:
return ak, xk, ind
return None
# The symbolic term - symb, if present, is being separated from the function
# Otherwise symb is being set to S.One
syms = f.free_symbols.difference({x})
(f, symb) = expand(f).as_independent(*syms)
if symb.is_zero:
symb = S.One
symb = powsimp(symb)
result = None
# from here on it's x0=0 and dir=1 handling
k = Dummy('k')
if rational:
result = rational_algorithm(f, x, k, order, full)
if result is None and hyper:
result = hyper_algorithm(f, x, k, order)
if result is None:
return None
ak = sequence(result[0], (k, result[2], oo))
xk_formula = powsimp(x**k * symb)
xk = sequence(xk_formula, (k, 0, oo))
ind = powsimp(result[1] * symb)
return ak, xk, ind
def compute_fps(f, x, x0=0, dir=1, hyper=True, order=4, rational=True,
full=False):
"""
Computes the formula for Formal Power Series of a function.
Explanation
===========
Tries to compute the formula by applying the following techniques
(in order):
* rational_algorithm
* Hypergeometric algorithm
Parameters
==========
x : Symbol
x0 : number, optional
Point to perform series expansion about. Default is 0.
dir : {1, -1, '+', '-'}, optional
If dir is 1 or '+' the series is calculated from the right and
for -1 or '-' the series is calculated from the left. For smooth
functions this flag will not alter the results. Default is 1.
hyper : {True, False}, optional
Set hyper to False to skip the hypergeometric algorithm.
By default it is set to False.
order : int, optional
Order of the derivative of ``f``, Default is 4.
rational : {True, False}, optional
Set rational to False to skip rational algorithm. By default it is set
to True.
full : {True, False}, optional
Set full to True to increase the range of rational algorithm.
See :func:`rational_algorithm` for details. By default it is set to
False.
Returns
=======
ak : sequence
Sequence of coefficients.
xk : sequence
Sequence of powers of x.
ind : Expr
Independent terms.
mul : Pow
Common terms.
See Also
========
sympy.series.formal.rational_algorithm
sympy.series.formal.hyper_algorithm
"""
f = sympify(f)
x = sympify(x)
if not f.has(x):
return None
x0 = sympify(x0)
if dir == '+':
dir = S.One
elif dir == '-':
dir = -S.One
elif dir not in [S.One, -S.One]:
raise ValueError("Dir must be '+' or '-'")
else:
dir = sympify(dir)
return _compute_fps(f, x, x0, dir, hyper, order, rational, full)
class Coeff(Function):
"""
Coeff(p, x, n) represents the nth coefficient of the polynomial p in x
"""
@classmethod
def eval(cls, p, x, n):
if p.is_polynomial(x) and n.is_integer:
return p.coeff(x, n)
class FormalPowerSeries(SeriesBase):
"""
Represents Formal Power Series of a function.
Explanation
===========
No computation is performed. This class should only to be used to represent
a series. No checks are performed.
For computing a series use :func:`fps`.
See Also
========
sympy.series.formal.fps
"""
def __new__(cls, *args):
args = map(sympify, args)
return Expr.__new__(cls, *args)
def __init__(self, *args):
ak = args[4][0]
k = ak.variables[0]
self.ak_seq = sequence(ak.formula, (k, 1, oo))
self.fact_seq = sequence(factorial(k), (k, 1, oo))
self.bell_coeff_seq = self.ak_seq * self.fact_seq
self.sign_seq = sequence((-1, 1), (k, 1, oo))
@property
def function(self):
return self.args[0]
@property
def x(self):
return self.args[1]
@property
def x0(self):
return self.args[2]
@property
def dir(self):
return self.args[3]
@property
def ak(self):
return self.args[4][0]
@property
def xk(self):
return self.args[4][1]
@property
def ind(self):
return self.args[4][2]
@property
def interval(self):
return Interval(0, oo)
@property
def start(self):
return self.interval.inf
@property
def stop(self):
return self.interval.sup
@property
def length(self):
return oo
@property
def infinite(self):
"""Returns an infinite representation of the series"""
from sympy.concrete import Sum
ak, xk = self.ak, self.xk
k = ak.variables[0]
inf_sum = Sum(ak.formula * xk.formula, (k, ak.start, ak.stop))
return self.ind + inf_sum
def _get_pow_x(self, term):
"""Returns the power of x in a term."""
xterm, pow_x = term.as_independent(self.x)[1].as_base_exp()
if not xterm.has(self.x):
return S.Zero
return pow_x
def polynomial(self, n=6):
"""
Truncated series as polynomial.
Explanation
===========
Returns series expansion of ``f`` upto order ``O(x**n)``
as a polynomial(without ``O`` term).
"""
terms = []
sym = self.free_symbols
for i, t in enumerate(self):
xp = self._get_pow_x(t)
if xp.has(*sym):
xp = xp.as_coeff_add(*sym)[0]
if xp >= n:
break
elif xp.is_integer is True and i == n + 1:
break
elif t is not S.Zero:
terms.append(t)
return Add(*terms)
def truncate(self, n=6):
"""
Truncated series.
Explanation
===========
Returns truncated series expansion of f upto
order ``O(x**n)``.
If n is ``None``, returns an infinite iterator.
"""
if n is None:
return iter(self)
x, x0 = self.x, self.x0
pt_xk = self.xk.coeff(n)
if x0 is S.NegativeInfinity:
x0 = S.Infinity
return self.polynomial(n) + Order(pt_xk, (x, x0))
def zero_coeff(self):
return self._eval_term(0)
def _eval_term(self, pt):
try:
pt_xk = self.xk.coeff(pt)
pt_ak = self.ak.coeff(pt).simplify() # Simplify the coefficients
except IndexError:
term = S.Zero
else:
term = (pt_ak * pt_xk)
if self.ind:
ind = S.Zero
sym = self.free_symbols
for t in Add.make_args(self.ind):
pow_x = self._get_pow_x(t)
if pow_x.has(*sym):
pow_x = pow_x.as_coeff_add(*sym)[0]
if pt == 0 and pow_x < 1:
ind += t
elif pow_x >= pt and pow_x < pt + 1:
ind += t
term += ind
return term.collect(self.x)
def _eval_subs(self, old, new):
x = self.x
if old.has(x):
return self
def _eval_as_leading_term(self, x, cdir=0):
for t in self:
if t is not S.Zero:
return t
def _eval_derivative(self, x):
f = self.function.diff(x)
ind = self.ind.diff(x)
pow_xk = self._get_pow_x(self.xk.formula)
ak = self.ak
k = ak.variables[0]
if ak.formula.has(x):
form = []
for e, c in ak.formula.args:
temp = S.Zero
for t in Add.make_args(e):
pow_x = self._get_pow_x(t)
temp += t * (pow_xk + pow_x)
form.append((temp, c))
form = Piecewise(*form)
ak = sequence(form.subs(k, k + 1), (k, ak.start - 1, ak.stop))
else:
ak = sequence((ak.formula * pow_xk).subs(k, k + 1),
(k, ak.start - 1, ak.stop))
return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
def integrate(self, x=None, **kwargs):
"""
Integrate Formal Power Series.
Examples
========
>>> from sympy import fps, sin, integrate
>>> from sympy.abc import x
>>> f = fps(sin(x))
>>> f.integrate(x).truncate()
-1 + x**2/2 - x**4/24 + O(x**6)
>>> integrate(f, (x, 0, 1))
1 - cos(1)
"""
from sympy.integrals import integrate
if x is None:
x = self.x
elif iterable(x):
return integrate(self.function, x)
f = integrate(self.function, x)
ind = integrate(self.ind, x)
ind += (f - ind).limit(x, 0) # constant of integration
pow_xk = self._get_pow_x(self.xk.formula)
ak = self.ak
k = ak.variables[0]
if ak.formula.has(x):
form = []
for e, c in ak.formula.args:
temp = S.Zero
for t in Add.make_args(e):
pow_x = self._get_pow_x(t)
temp += t / (pow_xk + pow_x + 1)
form.append((temp, c))
form = Piecewise(*form)
ak = sequence(form.subs(k, k - 1), (k, ak.start + 1, ak.stop))
else:
ak = sequence((ak.formula / (pow_xk + 1)).subs(k, k - 1),
(k, ak.start + 1, ak.stop))
return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
def product(self, other, x=None, n=6):
"""
Multiplies two Formal Power Series, using discrete convolution and
return the truncated terms upto specified order.
Parameters
==========
n : Number, optional
Specifies the order of the term up to which the polynomial should
be truncated.
Examples
========
>>> from sympy import fps, sin, exp
>>> from sympy.abc import x
>>> f1 = fps(sin(x))
>>> f2 = fps(exp(x))
>>> f1.product(f2, x).truncate(4)
x + x**2 + x**3/3 + O(x**4)
See Also
========
sympy.discrete.convolutions
sympy.series.formal.FormalPowerSeriesProduct
"""
if x is None:
x = self.x
if n is None:
return iter(self)
other = sympify(other)
if not isinstance(other, FormalPowerSeries):
raise ValueError("Both series should be an instance of FormalPowerSeries"
" class.")
if self.dir != other.dir:
raise ValueError("Both series should be calculated from the"
" same direction.")
elif self.x0 != other.x0:
raise ValueError("Both series should be calculated about the"
" same point.")
elif self.x != other.x:
raise ValueError("Both series should have the same symbol.")
return FormalPowerSeriesProduct(self, other)
def coeff_bell(self, n):
r"""
self.coeff_bell(n) returns a sequence of Bell polynomials of the second kind.
Note that ``n`` should be a integer.
The second kind of Bell polynomials (are sometimes called "partial" Bell
polynomials or incomplete Bell polynomials) are defined as
.. math::
B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) =
\sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n}
\frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!}
\left(\frac{x_1}{1!} \right)^{j_1}
\left(\frac{x_2}{2!} \right)^{j_2} \dotsb
\left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}.
* ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind,
`B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`.
See Also
========
sympy.functions.combinatorial.numbers.bell
"""
inner_coeffs = [bell(n, j, tuple(self.bell_coeff_seq[:n-j+1])) for j in range(1, n+1)]
k = Dummy('k')
return sequence(tuple(inner_coeffs), (k, 1, oo))
def compose(self, other, x=None, n=6):
r"""
Returns the truncated terms of the formal power series of the composed function,
up to specified ``n``.
Explanation
===========
If ``f`` and ``g`` are two formal power series of two different functions,
then the coefficient sequence ``ak`` of the composed formal power series `fp`
will be as follows.
.. math::
\sum\limits_{k=0}^{n} b_k B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})
Parameters
==========
n : Number, optional
Specifies the order of the term up to which the polynomial should
be truncated.
Examples
========
>>> from sympy import fps, sin, exp
>>> from sympy.abc import x
>>> f1 = fps(exp(x))
>>> f2 = fps(sin(x))
>>> f1.compose(f2, x).truncate()
1 + x + x**2/2 - x**4/8 - x**5/15 + O(x**6)
>>> f1.compose(f2, x).truncate(8)
1 + x + x**2/2 - x**4/8 - x**5/15 - x**6/240 + x**7/90 + O(x**8)
See Also
========
sympy.functions.combinatorial.numbers.bell
sympy.series.formal.FormalPowerSeriesCompose
References
==========
.. [1] Comtet, Louis: Advanced combinatorics; the art of finite and infinite expansions. Reidel, 1974.
"""
if x is None:
x = self.x
if n is None:
return iter(self)
other = sympify(other)
if not isinstance(other, FormalPowerSeries):
raise ValueError("Both series should be an instance of FormalPowerSeries"
" class.")
if self.dir != other.dir:
raise ValueError("Both series should be calculated from the"
" same direction.")
elif self.x0 != other.x0:
raise ValueError("Both series should be calculated about the"
" same point.")
elif self.x != other.x:
raise ValueError("Both series should have the same symbol.")
if other._eval_term(0).as_coeff_mul(other.x)[0] is not S.Zero:
raise ValueError("The formal power series of the inner function should not have any "
"constant coefficient term.")
return FormalPowerSeriesCompose(self, other)
def inverse(self, x=None, n=6):
r"""
Returns the truncated terms of the inverse of the formal power series,
up to specified ``n``.
Explanation
===========
If ``f`` and ``g`` are two formal power series of two different functions,
then the coefficient sequence ``ak`` of the composed formal power series ``fp``
will be as follows.
.. math::
\sum\limits_{k=0}^{n} (-1)^{k} x_0^{-k-1} B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})
Parameters
==========
n : Number, optional
Specifies the order of the term up to which the polynomial should
be truncated.
Examples
========
>>> from sympy import fps, exp, cos
>>> from sympy.abc import x
>>> f1 = fps(exp(x))
>>> f2 = fps(cos(x))
>>> f1.inverse(x).truncate()
1 - x + x**2/2 - x**3/6 + x**4/24 - x**5/120 + O(x**6)
>>> f2.inverse(x).truncate(8)
1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + O(x**8)
See Also
========
sympy.functions.combinatorial.numbers.bell
sympy.series.formal.FormalPowerSeriesInverse
References
==========
.. [1] Comtet, Louis: Advanced combinatorics; the art of finite and infinite expansions. Reidel, 1974.
"""
if x is None:
x = self.x
if n is None:
return iter(self)
if self._eval_term(0).is_zero:
raise ValueError("Constant coefficient should exist for an inverse of a formal"
" power series to exist.")
return FormalPowerSeriesInverse(self)
def __add__(self, other):
other = sympify(other)
if isinstance(other, FormalPowerSeries):
if self.dir != other.dir:
raise ValueError("Both series should be calculated from the"
" same direction.")
elif self.x0 != other.x0:
raise ValueError("Both series should be calculated about the"
" same point.")
x, y = self.x, other.x
f = self.function + other.function.subs(y, x)
if self.x not in f.free_symbols:
return f
ak = self.ak + other.ak
if self.ak.start > other.ak.start:
seq = other.ak
s, e = other.ak.start, self.ak.start
else:
seq = self.ak
s, e = self.ak.start, other.ak.start
save = Add(*[z[0]*z[1] for z in zip(seq[0:(e - s)], self.xk[s:e])])
ind = self.ind + other.ind + save
return self.func(f, x, self.x0, self.dir, (ak, self.xk, ind))
elif not other.has(self.x):
f = self.function + other
ind = self.ind + other
return self.func(f, self.x, self.x0, self.dir,
(self.ak, self.xk, ind))
return Add(self, other)
def __radd__(self, other):
return self.__add__(other)
def __neg__(self):
return self.func(-self.function, self.x, self.x0, self.dir,
(-self.ak, self.xk, -self.ind))
def __sub__(self, other):
return self.__add__(-other)
def __rsub__(self, other):
return (-self).__add__(other)
def __mul__(self, other):
other = sympify(other)
if other.has(self.x):
return Mul(self, other)
f = self.function * other
ak = self.ak.coeff_mul(other)
ind = self.ind * other
return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
def __rmul__(self, other):
return self.__mul__(other)
class FiniteFormalPowerSeries(FormalPowerSeries):
"""Base Class for Product, Compose and Inverse classes"""
def __init__(self, *args):
pass
@property
def ffps(self):
return self.args[0]
@property
def gfps(self):
return self.args[1]
@property
def f(self):
return self.ffps.function
@property
def g(self):
return self.gfps.function
@property
def infinite(self):
raise NotImplementedError("No infinite version for an object of"
" FiniteFormalPowerSeries class.")
def _eval_terms(self, n):
raise NotImplementedError("(%s)._eval_terms()" % self)
def _eval_term(self, pt):
raise NotImplementedError("By the current logic, one can get terms"
"upto a certain order, instead of getting term by term.")
def polynomial(self, n):
return self._eval_terms(n)
def truncate(self, n=6):
ffps = self.ffps
pt_xk = ffps.xk.coeff(n)
x, x0 = ffps.x, ffps.x0
return self.polynomial(n) + Order(pt_xk, (x, x0))
def _eval_derivative(self, x):
raise NotImplementedError
def integrate(self, x):
raise NotImplementedError
class FormalPowerSeriesProduct(FiniteFormalPowerSeries):
"""Represents the product of two formal power series of two functions.
Explanation
===========
No computation is performed. Terms are calculated using a term by term logic,
instead of a point by point logic.
There are two differences between a :obj:`FormalPowerSeries` object and a
:obj:`FormalPowerSeriesProduct` object. The first argument contains the two
functions involved in the product. Also, the coefficient sequence contains
both the coefficient sequence of the formal power series of the involved functions.
See Also
========
sympy.series.formal.FormalPowerSeries
sympy.series.formal.FiniteFormalPowerSeries
"""
def __init__(self, *args):
ffps, gfps = self.ffps, self.gfps
k = ffps.ak.variables[0]
self.coeff1 = sequence(ffps.ak.formula, (k, 0, oo))
k = gfps.ak.variables[0]
self.coeff2 = sequence(gfps.ak.formula, (k, 0, oo))
@property
def function(self):
"""Function of the product of two formal power series."""
return self.f * self.g
def _eval_terms(self, n):
"""
Returns the first ``n`` terms of the product formal power series.
Term by term logic is implemented here.
Examples
========
>>> from sympy import fps, sin, exp
>>> from sympy.abc import x
>>> f1 = fps(sin(x))
>>> f2 = fps(exp(x))
>>> fprod = f1.product(f2, x)
>>> fprod._eval_terms(4)
x**3/3 + x**2 + x
See Also
========
sympy.series.formal.FormalPowerSeries.product
"""
coeff1, coeff2 = self.coeff1, self.coeff2
aks = convolution(coeff1[:n], coeff2[:n])
terms = []
for i in range(0, n):
terms.append(aks[i] * self.ffps.xk.coeff(i))
return Add(*terms)
class FormalPowerSeriesCompose(FiniteFormalPowerSeries):
"""
Represents the composed formal power series of two functions.
Explanation
===========
No computation is performed. Terms are calculated using a term by term logic,
instead of a point by point logic.
There are two differences between a :obj:`FormalPowerSeries` object and a
:obj:`FormalPowerSeriesCompose` object. The first argument contains the outer
function and the inner function involved in the omposition. Also, the
coefficient sequence contains the generic sequence which is to be multiplied
by a custom ``bell_seq`` finite sequence. The finite terms will then be added up to
get the final terms.
See Also
========
sympy.series.formal.FormalPowerSeries
sympy.series.formal.FiniteFormalPowerSeries
"""
@property
def function(self):
"""Function for the composed formal power series."""
f, g, x = self.f, self.g, self.ffps.x
return f.subs(x, g)
def _eval_terms(self, n):
"""
Returns the first `n` terms of the composed formal power series.
Term by term logic is implemented here.
Explanation
===========
The coefficient sequence of the :obj:`FormalPowerSeriesCompose` object is the generic sequence.
It is multiplied by ``bell_seq`` to get a sequence, whose terms are added up to get
the final terms for the polynomial.
Examples
========
>>> from sympy import fps, sin, exp
>>> from sympy.abc import x
>>> f1 = fps(exp(x))
>>> f2 = fps(sin(x))
>>> fcomp = f1.compose(f2, x)
>>> fcomp._eval_terms(6)
-x**5/15 - x**4/8 + x**2/2 + x + 1
>>> fcomp._eval_terms(8)
x**7/90 - x**6/240 - x**5/15 - x**4/8 + x**2/2 + x + 1
See Also
========
sympy.series.formal.FormalPowerSeries.compose
sympy.series.formal.FormalPowerSeries.coeff_bell
"""
ffps, gfps = self.ffps, self.gfps
terms = [ffps.zero_coeff()]
for i in range(1, n):
bell_seq = gfps.coeff_bell(i)
seq = (ffps.bell_coeff_seq * bell_seq)
terms.append(Add(*(seq[:i])) / ffps.fact_seq[i-1] * ffps.xk.coeff(i))
return Add(*terms)
class FormalPowerSeriesInverse(FiniteFormalPowerSeries):
"""
Represents the Inverse of a formal power series.
Explanation
===========
No computation is performed. Terms are calculated using a term by term logic,
instead of a point by point logic.
There is a single difference between a :obj:`FormalPowerSeries` object and a
:obj:`FormalPowerSeriesInverse` object. The coefficient sequence contains the
generic sequence which is to be multiplied by a custom ``bell_seq`` finite sequence.
The finite terms will then be added up to get the final terms.
See Also
========
sympy.series.formal.FormalPowerSeries
sympy.series.formal.FiniteFormalPowerSeries
"""
def __init__(self, *args):
ffps = self.ffps
k = ffps.xk.variables[0]
inv = ffps.zero_coeff()
inv_seq = sequence(inv ** (-(k + 1)), (k, 1, oo))
self.aux_seq = ffps.sign_seq * ffps.fact_seq * inv_seq
@property
def function(self):
"""Function for the inverse of a formal power series."""
f = self.f
return 1 / f
@property
def g(self):
raise ValueError("Only one function is considered while performing"
"inverse of a formal power series.")
@property
def gfps(self):
raise ValueError("Only one function is considered while performing"
"inverse of a formal power series.")
def _eval_terms(self, n):
"""
Returns the first ``n`` terms of the composed formal power series.
Term by term logic is implemented here.
Explanation
===========
The coefficient sequence of the `FormalPowerSeriesInverse` object is the generic sequence.
It is multiplied by ``bell_seq`` to get a sequence, whose terms are added up to get
the final terms for the polynomial.
Examples
========
>>> from sympy import fps, exp, cos
>>> from sympy.abc import x
>>> f1 = fps(exp(x))
>>> f2 = fps(cos(x))
>>> finv1, finv2 = f1.inverse(), f2.inverse()
>>> finv1._eval_terms(6)
-x**5/120 + x**4/24 - x**3/6 + x**2/2 - x + 1
>>> finv2._eval_terms(8)
61*x**6/720 + 5*x**4/24 + x**2/2 + 1
See Also
========
sympy.series.formal.FormalPowerSeries.inverse
sympy.series.formal.FormalPowerSeries.coeff_bell
"""
ffps = self.ffps
terms = [ffps.zero_coeff()]
for i in range(1, n):
bell_seq = ffps.coeff_bell(i)
seq = (self.aux_seq * bell_seq)
terms.append(Add(*(seq[:i])) / ffps.fact_seq[i-1] * ffps.xk.coeff(i))
return Add(*terms)
def fps(f, x=None, x0=0, dir=1, hyper=True, order=4, rational=True, full=False):
"""
Generates Formal Power Series of ``f``.
Explanation
===========
Returns the formal series expansion of ``f`` around ``x = x0``
with respect to ``x`` in the form of a ``FormalPowerSeries`` object.
Formal Power Series is represented using an explicit formula
computed using different algorithms.
See :func:`compute_fps` for the more details regarding the computation
of formula.
Parameters
==========
x : Symbol, optional
If x is None and ``f`` is univariate, the univariate symbols will be
supplied, otherwise an error will be raised.
x0 : number, optional
Point to perform series expansion about. Default is 0.
dir : {1, -1, '+', '-'}, optional
If dir is 1 or '+' the series is calculated from the right and
for -1 or '-' the series is calculated from the left. For smooth
functions this flag will not alter the results. Default is 1.
hyper : {True, False}, optional
Set hyper to False to skip the hypergeometric algorithm.
By default it is set to False.
order : int, optional
Order of the derivative of ``f``, Default is 4.
rational : {True, False}, optional
Set rational to False to skip rational algorithm. By default it is set
to True.
full : {True, False}, optional
Set full to True to increase the range of rational algorithm.
See :func:`rational_algorithm` for details. By default it is set to
False.
Examples
========
>>> from sympy import fps, ln, atan, sin
>>> from sympy.abc import x, n
Rational Functions
>>> fps(ln(1 + x)).truncate()
x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
>>> fps(atan(x), full=True).truncate()
x - x**3/3 + x**5/5 + O(x**6)
Symbolic Functions
>>> fps(x**n*sin(x**2), x).truncate(8)
-x**(n + 6)/6 + x**(n + 2) + O(x**(n + 8))
See Also
========
sympy.series.formal.FormalPowerSeries
sympy.series.formal.compute_fps
"""
f = sympify(f)
if x is None:
free = f.free_symbols
if len(free) == 1:
x = free.pop()
elif not free:
return f
else:
raise NotImplementedError("multivariate formal power series")
result = compute_fps(f, x, x0, dir, hyper, order, rational, full)
if result is None:
return f
return FormalPowerSeries(f, x, x0, dir, result)
|
8f3f55a076e2616f855cb9fdc65b9f58583ad440f77f9738ca4ecd7fd1403f3c | from collections import defaultdict
from sympy.core.function import expand_log, count_ops
from sympy.core import sympify, Basic, Dummy, S, Add, Mul, Pow, expand_mul, factor_terms
from sympy.core.compatibility import ordered, default_sort_key, reduce
from sympy.core.numbers import Integer, Rational
from sympy.core.mul import prod, _keep_coeff
from sympy.core.rules import Transform
from sympy.functions import exp_polar, exp, log, root, polarify, unpolarify
from sympy.polys import lcm, gcd
from sympy.ntheory.factor_ import multiplicity
def powsimp(expr, deep=False, combine='all', force=False, measure=count_ops):
"""
reduces expression by combining powers with similar bases and exponents.
Explanation
===========
If ``deep`` is ``True`` then powsimp() will also simplify arguments of
functions. By default ``deep`` is set to ``False``.
If ``force`` is ``True`` then bases will be combined without checking for
assumptions, e.g. sqrt(x)*sqrt(y) -> sqrt(x*y) which is not true
if x and y are both negative.
You can make powsimp() only combine bases or only combine exponents by
changing combine='base' or combine='exp'. By default, combine='all',
which does both. combine='base' will only combine::
a a a 2x x
x * y => (x*y) as well as things like 2 => 4
and combine='exp' will only combine
::
a b (a + b)
x * x => x
combine='exp' will strictly only combine exponents in the way that used
to be automatic. Also use deep=True if you need the old behavior.
When combine='all', 'exp' is evaluated first. Consider the first
example below for when there could be an ambiguity relating to this.
This is done so things like the second example can be completely
combined. If you want 'base' combined first, do something like
powsimp(powsimp(expr, combine='base'), combine='exp').
Examples
========
>>> from sympy import powsimp, exp, log, symbols
>>> from sympy.abc import x, y, z, n
>>> powsimp(x**y*x**z*y**z, combine='all')
x**(y + z)*y**z
>>> powsimp(x**y*x**z*y**z, combine='exp')
x**(y + z)*y**z
>>> powsimp(x**y*x**z*y**z, combine='base', force=True)
x**y*(x*y)**z
>>> powsimp(x**z*x**y*n**z*n**y, combine='all', force=True)
(n*x)**(y + z)
>>> powsimp(x**z*x**y*n**z*n**y, combine='exp')
n**(y + z)*x**(y + z)
>>> powsimp(x**z*x**y*n**z*n**y, combine='base', force=True)
(n*x)**y*(n*x)**z
>>> x, y = symbols('x y', positive=True)
>>> powsimp(log(exp(x)*exp(y)))
log(exp(x)*exp(y))
>>> powsimp(log(exp(x)*exp(y)), deep=True)
x + y
Radicals with Mul bases will be combined if combine='exp'
>>> from sympy import sqrt
>>> x, y = symbols('x y')
Two radicals are automatically joined through Mul:
>>> a=sqrt(x*sqrt(y))
>>> a*a**3 == a**4
True
But if an integer power of that radical has been
autoexpanded then Mul does not join the resulting factors:
>>> a**4 # auto expands to a Mul, no longer a Pow
x**2*y
>>> _*a # so Mul doesn't combine them
x**2*y*sqrt(x*sqrt(y))
>>> powsimp(_) # but powsimp will
(x*sqrt(y))**(5/2)
>>> powsimp(x*y*a) # but won't when doing so would violate assumptions
x*y*sqrt(x*sqrt(y))
"""
from sympy.matrices.expressions.matexpr import MatrixSymbol
def recurse(arg, **kwargs):
_deep = kwargs.get('deep', deep)
_combine = kwargs.get('combine', combine)
_force = kwargs.get('force', force)
_measure = kwargs.get('measure', measure)
return powsimp(arg, _deep, _combine, _force, _measure)
expr = sympify(expr)
if (not isinstance(expr, Basic) or isinstance(expr, MatrixSymbol) or (
expr.is_Atom or expr in (exp_polar(0), exp_polar(1)))):
return expr
if deep or expr.is_Add or expr.is_Mul and _y not in expr.args:
expr = expr.func(*[recurse(w) for w in expr.args])
if expr.is_Pow:
return recurse(expr*_y, deep=False)/_y
if not expr.is_Mul:
return expr
# handle the Mul
if combine in ('exp', 'all'):
# Collect base/exp data, while maintaining order in the
# non-commutative parts of the product
c_powers = defaultdict(list)
nc_part = []
newexpr = []
coeff = S.One
for term in expr.args:
if term.is_Rational:
coeff *= term
continue
if term.is_Pow:
term = _denest_pow(term)
if term.is_commutative:
b, e = term.as_base_exp()
if deep:
b, e = [recurse(i) for i in [b, e]]
if b.is_Pow or isinstance(b, exp):
# don't let smthg like sqrt(x**a) split into x**a, 1/2
# or else it will be joined as x**(a/2) later
b, e = b**e, S.One
c_powers[b].append(e)
else:
# This is the logic that combines exponents for equal,
# but non-commutative bases: A**x*A**y == A**(x+y).
if nc_part:
b1, e1 = nc_part[-1].as_base_exp()
b2, e2 = term.as_base_exp()
if (b1 == b2 and
e1.is_commutative and e2.is_commutative):
nc_part[-1] = Pow(b1, Add(e1, e2))
continue
nc_part.append(term)
# add up exponents of common bases
for b, e in ordered(iter(c_powers.items())):
# allow 2**x/4 -> 2**(x - 2); don't do this when b and e are
# Numbers since autoevaluation will undo it, e.g.
# 2**(1/3)/4 -> 2**(1/3 - 2) -> 2**(1/3)/4
if (b and b.is_Rational and not all(ei.is_Number for ei in e) and \
coeff is not S.One and
b not in (S.One, S.NegativeOne)):
m = multiplicity(abs(b), abs(coeff))
if m:
e.append(m)
coeff /= b**m
c_powers[b] = Add(*e)
if coeff is not S.One:
if coeff in c_powers:
c_powers[coeff] += S.One
else:
c_powers[coeff] = S.One
# convert to plain dictionary
c_powers = dict(c_powers)
# check for base and inverted base pairs
be = list(c_powers.items())
skip = set() # skip if we already saw them
for b, e in be:
if b in skip:
continue
bpos = b.is_positive or b.is_polar
if bpos:
binv = 1/b
if b != binv and binv in c_powers:
if b.as_numer_denom()[0] is S.One:
c_powers.pop(b)
c_powers[binv] -= e
else:
skip.add(binv)
e = c_powers.pop(binv)
c_powers[b] -= e
# check for base and negated base pairs
be = list(c_powers.items())
_n = S.NegativeOne
for b, e in be:
if (b.is_Symbol or b.is_Add) and -b in c_powers and b in c_powers:
if (b.is_positive is not None or e.is_integer):
if e.is_integer or b.is_negative:
c_powers[-b] += c_powers.pop(b)
else: # (-b).is_positive so use its e
e = c_powers.pop(-b)
c_powers[b] += e
if _n in c_powers:
c_powers[_n] += e
else:
c_powers[_n] = e
# filter c_powers and convert to a list
c_powers = [(b, e) for b, e in c_powers.items() if e]
# ==============================================================
# check for Mul bases of Rational powers that can be combined with
# separated bases, e.g. x*sqrt(x*y)*sqrt(x*sqrt(x*y)) ->
# (x*sqrt(x*y))**(3/2)
# ---------------- helper functions
def ratq(x):
'''Return Rational part of x's exponent as it appears in the bkey.
'''
return bkey(x)[0][1]
def bkey(b, e=None):
'''Return (b**s, c.q), c.p where e -> c*s. If e is not given then
it will be taken by using as_base_exp() on the input b.
e.g.
x**3/2 -> (x, 2), 3
x**y -> (x**y, 1), 1
x**(2*y/3) -> (x**y, 3), 2
exp(x/2) -> (exp(a), 2), 1
'''
if e is not None: # coming from c_powers or from below
if e.is_Integer:
return (b, S.One), e
elif e.is_Rational:
return (b, Integer(e.q)), Integer(e.p)
else:
c, m = e.as_coeff_Mul(rational=True)
if c is not S.One:
if m.is_integer:
return (b, Integer(c.q)), m*Integer(c.p)
return (b**m, Integer(c.q)), Integer(c.p)
else:
return (b**e, S.One), S.One
else:
return bkey(*b.as_base_exp())
def update(b):
'''Decide what to do with base, b. If its exponent is now an
integer multiple of the Rational denominator, then remove it
and put the factors of its base in the common_b dictionary or
update the existing bases if necessary. If it has been zeroed
out, simply remove the base.
'''
newe, r = divmod(common_b[b], b[1])
if not r:
common_b.pop(b)
if newe:
for m in Mul.make_args(b[0]**newe):
b, e = bkey(m)
if b not in common_b:
common_b[b] = 0
common_b[b] += e
if b[1] != 1:
bases.append(b)
# ---------------- end of helper functions
# assemble a dictionary of the factors having a Rational power
common_b = {}
done = []
bases = []
for b, e in c_powers:
b, e = bkey(b, e)
if b in common_b:
common_b[b] = common_b[b] + e
else:
common_b[b] = e
if b[1] != 1 and b[0].is_Mul:
bases.append(b)
bases.sort(key=default_sort_key) # this makes tie-breaking canonical
bases.sort(key=measure, reverse=True) # handle longest first
for base in bases:
if base not in common_b: # it may have been removed already
continue
b, exponent = base
last = False # True when no factor of base is a radical
qlcm = 1 # the lcm of the radical denominators
while True:
bstart = b
qstart = qlcm
bb = [] # list of factors
ee = [] # (factor's expo. and it's current value in common_b)
for bi in Mul.make_args(b):
bib, bie = bkey(bi)
if bib not in common_b or common_b[bib] < bie:
ee = bb = [] # failed
break
ee.append([bie, common_b[bib]])
bb.append(bib)
if ee:
# find the number of integral extractions possible
# e.g. [(1, 2), (2, 2)] -> min(2/1, 2/2) -> 1
min1 = ee[0][1]//ee[0][0]
for i in range(1, len(ee)):
rat = ee[i][1]//ee[i][0]
if rat < 1:
break
min1 = min(min1, rat)
else:
# update base factor counts
# e.g. if ee = [(2, 5), (3, 6)] then min1 = 2
# and the new base counts will be 5-2*2 and 6-2*3
for i in range(len(bb)):
common_b[bb[i]] -= min1*ee[i][0]
update(bb[i])
# update the count of the base
# e.g. x**2*y*sqrt(x*sqrt(y)) the count of x*sqrt(y)
# will increase by 4 to give bkey (x*sqrt(y), 2, 5)
common_b[base] += min1*qstart*exponent
if (last # no more radicals in base
or len(common_b) == 1 # nothing left to join with
or all(k[1] == 1 for k in common_b) # no rad's in common_b
):
break
# see what we can exponentiate base by to remove any radicals
# so we know what to search for
# e.g. if base were x**(1/2)*y**(1/3) then we should
# exponentiate by 6 and look for powers of x and y in the ratio
# of 2 to 3
qlcm = lcm([ratq(bi) for bi in Mul.make_args(bstart)])
if qlcm == 1:
break # we are done
b = bstart**qlcm
qlcm *= qstart
if all(ratq(bi) == 1 for bi in Mul.make_args(b)):
last = True # we are going to be done after this next pass
# this base no longer can find anything to join with and
# since it was longer than any other we are done with it
b, q = base
done.append((b, common_b.pop(base)*Rational(1, q)))
# update c_powers and get ready to continue with powsimp
c_powers = done
# there may be terms still in common_b that were bases that were
# identified as needing processing, so remove those, too
for (b, q), e in common_b.items():
if (b.is_Pow or isinstance(b, exp)) and \
q is not S.One and not b.exp.is_Rational:
b, be = b.as_base_exp()
b = b**(be/q)
else:
b = root(b, q)
c_powers.append((b, e))
check = len(c_powers)
c_powers = dict(c_powers)
assert len(c_powers) == check # there should have been no duplicates
# ==============================================================
# rebuild the expression
newexpr = expr.func(*(newexpr + [Pow(b, e) for b, e in c_powers.items()]))
if combine == 'exp':
return expr.func(newexpr, expr.func(*nc_part))
else:
return recurse(expr.func(*nc_part), combine='base') * \
recurse(newexpr, combine='base')
elif combine == 'base':
# Build c_powers and nc_part. These must both be lists not
# dicts because exp's are not combined.
c_powers = []
nc_part = []
for term in expr.args:
if term.is_commutative:
c_powers.append(list(term.as_base_exp()))
else:
nc_part.append(term)
# Pull out numerical coefficients from exponent if assumptions allow
# e.g., 2**(2*x) => 4**x
for i in range(len(c_powers)):
b, e = c_powers[i]
if not (all(x.is_nonnegative for x in b.as_numer_denom()) or e.is_integer or force or b.is_polar):
continue
exp_c, exp_t = e.as_coeff_Mul(rational=True)
if exp_c is not S.One and exp_t is not S.One:
c_powers[i] = [Pow(b, exp_c), exp_t]
# Combine bases whenever they have the same exponent and
# assumptions allow
# first gather the potential bases under the common exponent
c_exp = defaultdict(list)
for b, e in c_powers:
if deep:
e = recurse(e)
c_exp[e].append(b)
del c_powers
# Merge back in the results of the above to form a new product
c_powers = defaultdict(list)
for e in c_exp:
bases = c_exp[e]
# calculate the new base for e
if len(bases) == 1:
new_base = bases[0]
elif e.is_integer or force:
new_base = expr.func(*bases)
else:
# see which ones can be joined
unk = []
nonneg = []
neg = []
for bi in bases:
if bi.is_negative:
neg.append(bi)
elif bi.is_nonnegative:
nonneg.append(bi)
elif bi.is_polar:
nonneg.append(
bi) # polar can be treated like non-negative
else:
unk.append(bi)
if len(unk) == 1 and not neg or len(neg) == 1 and not unk:
# a single neg or a single unk can join the rest
nonneg.extend(unk + neg)
unk = neg = []
elif neg:
# their negative signs cancel in groups of 2*q if we know
# that e = p/q else we have to treat them as unknown
israt = False
if e.is_Rational:
israt = True
else:
p, d = e.as_numer_denom()
if p.is_integer and d.is_integer:
israt = True
if israt:
neg = [-w for w in neg]
unk.extend([S.NegativeOne]*len(neg))
else:
unk.extend(neg)
neg = []
del israt
# these shouldn't be joined
for b in unk:
c_powers[b].append(e)
# here is a new joined base
new_base = expr.func(*(nonneg + neg))
# if there are positive parts they will just get separated
# again unless some change is made
def _terms(e):
# return the number of terms of this expression
# when multiplied out -- assuming no joining of terms
if e.is_Add:
return sum([_terms(ai) for ai in e.args])
if e.is_Mul:
return prod([_terms(mi) for mi in e.args])
return 1
xnew_base = expand_mul(new_base, deep=False)
if len(Add.make_args(xnew_base)) < _terms(new_base):
new_base = factor_terms(xnew_base)
c_powers[new_base].append(e)
# break out the powers from c_powers now
c_part = [Pow(b, ei) for b, e in c_powers.items() for ei in e]
# we're done
return expr.func(*(c_part + nc_part))
else:
raise ValueError("combine must be one of ('all', 'exp', 'base').")
def powdenest(eq, force=False, polar=False):
r"""
Collect exponents on powers as assumptions allow.
Explanation
===========
Given ``(bb**be)**e``, this can be simplified as follows:
* if ``bb`` is positive, or
* ``e`` is an integer, or
* ``|be| < 1`` then this simplifies to ``bb**(be*e)``
Given a product of powers raised to a power, ``(bb1**be1 *
bb2**be2...)**e``, simplification can be done as follows:
- if e is positive, the gcd of all bei can be joined with e;
- all non-negative bb can be separated from those that are negative
and their gcd can be joined with e; autosimplification already
handles this separation.
- integer factors from powers that have integers in the denominator
of the exponent can be removed from any term and the gcd of such
integers can be joined with e
Setting ``force`` to ``True`` will make symbols that are not explicitly
negative behave as though they are positive, resulting in more
denesting.
Setting ``polar`` to ``True`` will do simplifications on the Riemann surface of
the logarithm, also resulting in more denestings.
When there are sums of logs in exp() then a product of powers may be
obtained e.g. ``exp(3*(log(a) + 2*log(b)))`` - > ``a**3*b**6``.
Examples
========
>>> from sympy.abc import a, b, x, y, z
>>> from sympy import Symbol, exp, log, sqrt, symbols, powdenest
>>> powdenest((x**(2*a/3))**(3*x))
(x**(2*a/3))**(3*x)
>>> powdenest(exp(3*x*log(2)))
2**(3*x)
Assumptions may prevent expansion:
>>> powdenest(sqrt(x**2))
sqrt(x**2)
>>> p = symbols('p', positive=True)
>>> powdenest(sqrt(p**2))
p
No other expansion is done.
>>> i, j = symbols('i,j', integer=True)
>>> powdenest((x**x)**(i + j)) # -X-> (x**x)**i*(x**x)**j
x**(x*(i + j))
But exp() will be denested by moving all non-log terms outside of
the function; this may result in the collapsing of the exp to a power
with a different base:
>>> powdenest(exp(3*y*log(x)))
x**(3*y)
>>> powdenest(exp(y*(log(a) + log(b))))
(a*b)**y
>>> powdenest(exp(3*(log(a) + log(b))))
a**3*b**3
If assumptions allow, symbols can also be moved to the outermost exponent:
>>> i = Symbol('i', integer=True)
>>> powdenest(((x**(2*i))**(3*y))**x)
((x**(2*i))**(3*y))**x
>>> powdenest(((x**(2*i))**(3*y))**x, force=True)
x**(6*i*x*y)
>>> powdenest(((x**(2*a/3))**(3*y/i))**x)
((x**(2*a/3))**(3*y/i))**x
>>> powdenest((x**(2*i)*y**(4*i))**z, force=True)
(x*y**2)**(2*i*z)
>>> n = Symbol('n', negative=True)
>>> powdenest((x**i)**y, force=True)
x**(i*y)
>>> powdenest((n**i)**x, force=True)
(n**i)**x
"""
from sympy.simplify.simplify import posify
if force:
def _denest(b, e):
if not isinstance(b, (Pow, exp)):
return b.is_positive, Pow(b, e, evaluate=False)
return _denest(b.base, b.exp*e)
reps = []
for p in eq.atoms(Pow, exp):
if isinstance(p.base, (Pow, exp)):
ok, dp = _denest(*p.args)
if ok is not False:
reps.append((p, dp))
if reps:
eq = eq.subs(reps)
eq, reps = posify(eq)
return powdenest(eq, force=False, polar=polar).xreplace(reps)
if polar:
eq, rep = polarify(eq)
return unpolarify(powdenest(unpolarify(eq, exponents_only=True)), rep)
new = powsimp(sympify(eq))
return new.xreplace(Transform(
_denest_pow, filter=lambda m: m.is_Pow or isinstance(m, exp)))
_y = Dummy('y')
def _denest_pow(eq):
"""
Denest powers.
This is a helper function for powdenest that performs the actual
transformation.
"""
from sympy.simplify.simplify import logcombine
b, e = eq.as_base_exp()
if b.is_Pow or isinstance(b.func, exp) and e != 1:
new = b._eval_power(e)
if new is not None:
eq = new
b, e = new.as_base_exp()
# denest exp with log terms in exponent
if b is S.Exp1 and e.is_Mul:
logs = []
other = []
for ei in e.args:
if any(isinstance(ai, log) for ai in Add.make_args(ei)):
logs.append(ei)
else:
other.append(ei)
logs = logcombine(Mul(*logs))
return Pow(exp(logs), Mul(*other))
_, be = b.as_base_exp()
if be is S.One and not (b.is_Mul or
b.is_Rational and b.q != 1 or
b.is_positive):
return eq
# denest eq which is either pos**e or Pow**e or Mul**e or
# Mul(b1**e1, b2**e2)
# handle polar numbers specially
polars, nonpolars = [], []
for bb in Mul.make_args(b):
if bb.is_polar:
polars.append(bb.as_base_exp())
else:
nonpolars.append(bb)
if len(polars) == 1 and not polars[0][0].is_Mul:
return Pow(polars[0][0], polars[0][1]*e)*powdenest(Mul(*nonpolars)**e)
elif polars:
return Mul(*[powdenest(bb**(ee*e)) for (bb, ee) in polars]) \
*powdenest(Mul(*nonpolars)**e)
if b.is_Integer:
# use log to see if there is a power here
logb = expand_log(log(b))
if logb.is_Mul:
c, logb = logb.args
e *= c
base = logb.args[0]
return Pow(base, e)
# if b is not a Mul or any factor is an atom then there is nothing to do
if not b.is_Mul or any(s.is_Atom for s in Mul.make_args(b)):
return eq
# let log handle the case of the base of the argument being a Mul, e.g.
# sqrt(x**(2*i)*y**(6*i)) -> x**i*y**(3**i) if x and y are positive; we
# will take the log, expand it, and then factor out the common powers that
# now appear as coefficient. We do this manually since terms_gcd pulls out
# fractions, terms_gcd(x+x*y/2) -> x*(y + 2)/2 and we don't want the 1/2;
# gcd won't pull out numerators from a fraction: gcd(3*x, 9*x/2) -> x but
# we want 3*x. Neither work with noncommutatives.
def nc_gcd(aa, bb):
a, b = [i.as_coeff_Mul() for i in [aa, bb]]
c = gcd(a[0], b[0]).as_numer_denom()[0]
g = Mul(*(a[1].args_cnc(cset=True)[0] & b[1].args_cnc(cset=True)[0]))
return _keep_coeff(c, g)
glogb = expand_log(log(b))
if glogb.is_Add:
args = glogb.args
g = reduce(nc_gcd, args)
if g != 1:
cg, rg = g.as_coeff_Mul()
glogb = _keep_coeff(cg, rg*Add(*[a/g for a in args]))
# now put the log back together again
if isinstance(glogb, log) or not glogb.is_Mul:
if glogb.args[0].is_Pow or isinstance(glogb.args[0], exp):
glogb = _denest_pow(glogb.args[0])
if (abs(glogb.exp) < 1) == True:
return Pow(glogb.base, glogb.exp*e)
return eq
# the log(b) was a Mul so join any adds with logcombine
add = []
other = []
for a in glogb.args:
if a.is_Add:
add.append(a)
else:
other.append(a)
return Pow(exp(logcombine(Mul(*add))), e*Mul(*other))
|
96ccf843472ce6dc77951ce27639bdb82b41e369a7f231c6e69d8a09cbf8aac7 | """ Tools for doing common subexpression elimination.
"""
from sympy.core import Basic, Mul, Add, Pow, sympify, Symbol
from sympy.core.compatibility import iterable
from sympy.core.containers import Tuple, OrderedSet
from sympy.core.exprtools import factor_terms
from sympy.core.function import _coeff_isneg
from sympy.core.singleton import S
from sympy.utilities.iterables import numbered_symbols, sift, \
topological_sort, ordered
from . import cse_opts
# (preprocessor, postprocessor) pairs which are commonly useful. They should
# each take a sympy expression and return a possibly transformed expression.
# When used in the function ``cse()``, the target expressions will be transformed
# by each of the preprocessor functions in order. After the common
# subexpressions are eliminated, each resulting expression will have the
# postprocessor functions transform them in *reverse* order in order to undo the
# transformation if necessary. This allows the algorithm to operate on
# a representation of the expressions that allows for more optimization
# opportunities.
# ``None`` can be used to specify no transformation for either the preprocessor or
# postprocessor.
basic_optimizations = [(cse_opts.sub_pre, cse_opts.sub_post),
(factor_terms, None)]
# sometimes we want the output in a different format; non-trivial
# transformations can be put here for users
# ===============================================================
def reps_toposort(r):
"""Sort replacements ``r`` so (k1, v1) appears before (k2, v2)
if k2 is in v1's free symbols. This orders items in the
way that cse returns its results (hence, in order to use the
replacements in a substitution option it would make sense
to reverse the order).
Examples
========
>>> from sympy.simplify.cse_main import reps_toposort
>>> from sympy.abc import x, y
>>> from sympy import Eq
>>> for l, r in reps_toposort([(x, y + 1), (y, 2)]):
... print(Eq(l, r))
...
Eq(y, 2)
Eq(x, y + 1)
"""
r = sympify(r)
E = []
for c1, (k1, v1) in enumerate(r):
for c2, (k2, v2) in enumerate(r):
if k1 in v2.free_symbols:
E.append((c1, c2))
return [r[i] for i in topological_sort((range(len(r)), E))]
def cse_separate(r, e):
"""Move expressions that are in the form (symbol, expr) out of the
expressions and sort them into the replacements using the reps_toposort.
Examples
========
>>> from sympy.simplify.cse_main import cse_separate
>>> from sympy.abc import x, y, z
>>> from sympy import cos, exp, cse, Eq, symbols
>>> x0, x1 = symbols('x:2')
>>> eq = (x + 1 + exp((x + 1)/(y + 1)) + cos(y + 1))
>>> cse([eq, Eq(x, z + 1), z - 2], postprocess=cse_separate) in [
... [[(x0, y + 1), (x, z + 1), (x1, x + 1)],
... [x1 + exp(x1/x0) + cos(x0), z - 2]],
... [[(x1, y + 1), (x, z + 1), (x0, x + 1)],
... [x0 + exp(x0/x1) + cos(x1), z - 2]]]
...
True
"""
d = sift(e, lambda w: w.is_Equality and w.lhs.is_Symbol)
r = r + [w.args for w in d[True]]
e = d[False]
return [reps_toposort(r), e]
# ====end of cse postprocess idioms===========================
def preprocess_for_cse(expr, optimizations):
""" Preprocess an expression to optimize for common subexpression
elimination.
Parameters
==========
expr : sympy expression
The target expression to optimize.
optimizations : list of (callable, callable) pairs
The (preprocessor, postprocessor) pairs.
Returns
=======
expr : sympy expression
The transformed expression.
"""
for pre, post in optimizations:
if pre is not None:
expr = pre(expr)
return expr
def postprocess_for_cse(expr, optimizations):
""" Postprocess an expression after common subexpression elimination to
return the expression to canonical sympy form.
Parameters
==========
expr : sympy expression
The target expression to transform.
optimizations : list of (callable, callable) pairs, optional
The (preprocessor, postprocessor) pairs. The postprocessors will be
applied in reversed order to undo the effects of the preprocessors
correctly.
Returns
=======
expr : sympy expression
The transformed expression.
"""
for pre, post in reversed(optimizations):
if post is not None:
expr = post(expr)
return expr
class FuncArgTracker:
"""
A class which manages a mapping from functions to arguments and an inverse
mapping from arguments to functions.
"""
def __init__(self, funcs):
# To minimize the number of symbolic comparisons, all function arguments
# get assigned a value number.
self.value_numbers = {}
self.value_number_to_value = []
# Both of these maps use integer indices for arguments / functions.
self.arg_to_funcset = []
self.func_to_argset = []
for func_i, func in enumerate(funcs):
func_argset = OrderedSet()
for func_arg in func.args:
arg_number = self.get_or_add_value_number(func_arg)
func_argset.add(arg_number)
self.arg_to_funcset[arg_number].add(func_i)
self.func_to_argset.append(func_argset)
def get_args_in_value_order(self, argset):
"""
Return the list of arguments in sorted order according to their value
numbers.
"""
return [self.value_number_to_value[argn] for argn in sorted(argset)]
def get_or_add_value_number(self, value):
"""
Return the value number for the given argument.
"""
nvalues = len(self.value_numbers)
value_number = self.value_numbers.setdefault(value, nvalues)
if value_number == nvalues:
self.value_number_to_value.append(value)
self.arg_to_funcset.append(OrderedSet())
return value_number
def stop_arg_tracking(self, func_i):
"""
Remove the function func_i from the argument to function mapping.
"""
for arg in self.func_to_argset[func_i]:
self.arg_to_funcset[arg].remove(func_i)
def get_common_arg_candidates(self, argset, min_func_i=0):
"""Return a dict whose keys are function numbers. The entries of the dict are
the number of arguments said function has in common with
``argset``. Entries have at least 2 items in common. All keys have
value at least ``min_func_i``.
"""
from collections import defaultdict
count_map = defaultdict(lambda: 0)
if not argset:
return count_map
funcsets = [self.arg_to_funcset[arg] for arg in argset]
# As an optimization below, we handle the largest funcset separately from
# the others.
largest_funcset = max(funcsets, key=len)
for funcset in funcsets:
if largest_funcset is funcset:
continue
for func_i in funcset:
if func_i >= min_func_i:
count_map[func_i] += 1
# We pick the smaller of the two containers (count_map, largest_funcset)
# to iterate over to reduce the number of iterations needed.
(smaller_funcs_container,
larger_funcs_container) = sorted(
[largest_funcset, count_map],
key=len)
for func_i in smaller_funcs_container:
# Not already in count_map? It can't possibly be in the output, so
# skip it.
if count_map[func_i] < 1:
continue
if func_i in larger_funcs_container:
count_map[func_i] += 1
return {k: v for k, v in count_map.items() if v >= 2}
def get_subset_candidates(self, argset, restrict_to_funcset=None):
"""
Return a set of functions each of which whose argument list contains
``argset``, optionally filtered only to contain functions in
``restrict_to_funcset``.
"""
iarg = iter(argset)
indices = OrderedSet(
fi for fi in self.arg_to_funcset[next(iarg)])
if restrict_to_funcset is not None:
indices &= restrict_to_funcset
for arg in iarg:
indices &= self.arg_to_funcset[arg]
return indices
def update_func_argset(self, func_i, new_argset):
"""
Update a function with a new set of arguments.
"""
new_args = OrderedSet(new_argset)
old_args = self.func_to_argset[func_i]
for deleted_arg in old_args - new_args:
self.arg_to_funcset[deleted_arg].remove(func_i)
for added_arg in new_args - old_args:
self.arg_to_funcset[added_arg].add(func_i)
self.func_to_argset[func_i].clear()
self.func_to_argset[func_i].update(new_args)
class Unevaluated:
def __init__(self, func, args):
self.func = func
self.args = args
def __str__(self):
return "Uneval<{}>({})".format(
self.func, ", ".join(str(a) for a in self.args))
def as_unevaluated_basic(self):
return self.func(*self.args, evaluate=False)
@property
def free_symbols(self):
return set().union(*[a.free_symbols for a in self.args])
__repr__ = __str__
def match_common_args(func_class, funcs, opt_subs):
"""
Recognize and extract common subexpressions of function arguments within a
set of function calls. For instance, for the following function calls::
x + z + y
sin(x + y)
this will extract a common subexpression of `x + y`::
w = x + y
w + z
sin(w)
The function we work with is assumed to be associative and commutative.
Parameters
==========
func_class: class
The function class (e.g. Add, Mul)
funcs: list of functions
A list of function calls.
opt_subs: dict
A dictionary of substitutions which this function may update.
"""
# Sort to ensure that whole-function subexpressions come before the items
# that use them.
funcs = sorted(funcs, key=lambda f: len(f.args))
arg_tracker = FuncArgTracker(funcs)
changed = OrderedSet()
for i in range(len(funcs)):
common_arg_candidates_counts = arg_tracker.get_common_arg_candidates(
arg_tracker.func_to_argset[i], min_func_i=i + 1)
# Sort the candidates in order of match size.
# This makes us try combining smaller matches first.
common_arg_candidates = OrderedSet(sorted(
common_arg_candidates_counts.keys(),
key=lambda k: (common_arg_candidates_counts[k], k)))
while common_arg_candidates:
j = common_arg_candidates.pop(last=False)
com_args = arg_tracker.func_to_argset[i].intersection(
arg_tracker.func_to_argset[j])
if len(com_args) <= 1:
# This may happen if a set of common arguments was already
# combined in a previous iteration.
continue
# For all sets, replace the common symbols by the function
# over them, to allow recursive matches.
diff_i = arg_tracker.func_to_argset[i].difference(com_args)
if diff_i:
# com_func needs to be unevaluated to allow for recursive matches.
com_func = Unevaluated(
func_class, arg_tracker.get_args_in_value_order(com_args))
com_func_number = arg_tracker.get_or_add_value_number(com_func)
arg_tracker.update_func_argset(i, diff_i | OrderedSet([com_func_number]))
changed.add(i)
else:
# Treat the whole expression as a CSE.
#
# The reason this needs to be done is somewhat subtle. Within
# tree_cse(), to_eliminate only contains expressions that are
# seen more than once. The problem is unevaluated expressions
# do not compare equal to the evaluated equivalent. So
# tree_cse() won't mark funcs[i] as a CSE if we use an
# unevaluated version.
com_func_number = arg_tracker.get_or_add_value_number(funcs[i])
diff_j = arg_tracker.func_to_argset[j].difference(com_args)
arg_tracker.update_func_argset(j, diff_j | OrderedSet([com_func_number]))
changed.add(j)
for k in arg_tracker.get_subset_candidates(
com_args, common_arg_candidates):
diff_k = arg_tracker.func_to_argset[k].difference(com_args)
arg_tracker.update_func_argset(k, diff_k | OrderedSet([com_func_number]))
changed.add(k)
if i in changed:
opt_subs[funcs[i]] = Unevaluated(func_class,
arg_tracker.get_args_in_value_order(arg_tracker.func_to_argset[i]))
arg_tracker.stop_arg_tracking(i)
def opt_cse(exprs, order='canonical'):
"""Find optimization opportunities in Adds, Muls, Pows and negative
coefficient Muls.
Parameters
==========
exprs : list of sympy expressions
The expressions to optimize.
order : string, 'none' or 'canonical'
The order by which Mul and Add arguments are processed. For large
expressions where speed is a concern, use the setting order='none'.
Returns
=======
opt_subs : dictionary of expression substitutions
The expression substitutions which can be useful to optimize CSE.
Examples
========
>>> from sympy.simplify.cse_main import opt_cse
>>> from sympy.abc import x
>>> opt_subs = opt_cse([x**-2])
>>> k, v = list(opt_subs.keys())[0], list(opt_subs.values())[0]
>>> print((k, v.as_unevaluated_basic()))
(x**(-2), 1/(x**2))
"""
from sympy.matrices.expressions import MatAdd, MatMul, MatPow
opt_subs = dict()
adds = OrderedSet()
muls = OrderedSet()
seen_subexp = set()
def _find_opts(expr):
if not isinstance(expr, (Basic, Unevaluated)):
return
if expr.is_Atom or expr.is_Order:
return
if iterable(expr):
list(map(_find_opts, expr))
return
if expr in seen_subexp:
return expr
seen_subexp.add(expr)
list(map(_find_opts, expr.args))
if _coeff_isneg(expr):
neg_expr = -expr
if not neg_expr.is_Atom:
opt_subs[expr] = Unevaluated(Mul, (S.NegativeOne, neg_expr))
seen_subexp.add(neg_expr)
expr = neg_expr
if isinstance(expr, (Mul, MatMul)):
muls.add(expr)
elif isinstance(expr, (Add, MatAdd)):
adds.add(expr)
elif isinstance(expr, (Pow, MatPow)):
base, exp = expr.base, expr.exp
if _coeff_isneg(exp):
opt_subs[expr] = Unevaluated(Pow, (Pow(base, -exp), -1))
for e in exprs:
if isinstance(e, (Basic, Unevaluated)):
_find_opts(e)
# split muls into commutative
commutative_muls = OrderedSet()
for m in muls:
c, nc = m.args_cnc(cset=False)
if c:
c_mul = m.func(*c)
if nc:
if c_mul == 1:
new_obj = m.func(*nc)
else:
new_obj = m.func(c_mul, m.func(*nc), evaluate=False)
opt_subs[m] = new_obj
if len(c) > 1:
commutative_muls.add(c_mul)
match_common_args(Add, adds, opt_subs)
match_common_args(Mul, commutative_muls, opt_subs)
return opt_subs
def tree_cse(exprs, symbols, opt_subs=None, order='canonical', ignore=()):
"""Perform raw CSE on expression tree, taking opt_subs into account.
Parameters
==========
exprs : list of sympy expressions
The expressions to reduce.
symbols : infinite iterator yielding unique Symbols
The symbols used to label the common subexpressions which are pulled
out.
opt_subs : dictionary of expression substitutions
The expressions to be substituted before any CSE action is performed.
order : string, 'none' or 'canonical'
The order by which Mul and Add arguments are processed. For large
expressions where speed is a concern, use the setting order='none'.
ignore : iterable of Symbols
Substitutions containing any Symbol from ``ignore`` will be ignored.
"""
from sympy.matrices.expressions import MatrixExpr, MatrixSymbol, MatMul, MatAdd
from sympy.polys.rootoftools import RootOf
if opt_subs is None:
opt_subs = dict()
## Find repeated sub-expressions
to_eliminate = set()
seen_subexp = set()
excluded_symbols = set()
def _find_repeated(expr):
if not isinstance(expr, (Basic, Unevaluated)):
return
if isinstance(expr, RootOf):
return
if isinstance(expr, Basic) and (expr.is_Atom or expr.is_Order):
if expr.is_Symbol:
excluded_symbols.add(expr)
return
if iterable(expr):
args = expr
else:
if expr in seen_subexp:
for ign in ignore:
if ign in expr.free_symbols:
break
else:
to_eliminate.add(expr)
return
seen_subexp.add(expr)
if expr in opt_subs:
expr = opt_subs[expr]
args = expr.args
list(map(_find_repeated, args))
for e in exprs:
if isinstance(e, Basic):
_find_repeated(e)
## Rebuild tree
# Remove symbols from the generator that conflict with names in the expressions.
symbols = (symbol for symbol in symbols if symbol not in excluded_symbols)
replacements = []
subs = dict()
def _rebuild(expr):
if not isinstance(expr, (Basic, Unevaluated)):
return expr
if not expr.args:
return expr
if iterable(expr):
new_args = [_rebuild(arg) for arg in expr]
return expr.func(*new_args)
if expr in subs:
return subs[expr]
orig_expr = expr
if expr in opt_subs:
expr = opt_subs[expr]
# If enabled, parse Muls and Adds arguments by order to ensure
# replacement order independent from hashes
if order != 'none':
if isinstance(expr, (Mul, MatMul)):
c, nc = expr.args_cnc()
if c == [1]:
args = nc
else:
args = list(ordered(c)) + nc
elif isinstance(expr, (Add, MatAdd)):
args = list(ordered(expr.args))
else:
args = expr.args
else:
args = expr.args
new_args = list(map(_rebuild, args))
if isinstance(expr, Unevaluated) or new_args != args:
new_expr = expr.func(*new_args)
else:
new_expr = expr
if orig_expr in to_eliminate:
try:
sym = next(symbols)
except StopIteration:
raise ValueError("Symbols iterator ran out of symbols.")
if isinstance(orig_expr, MatrixExpr):
sym = MatrixSymbol(sym.name, orig_expr.rows,
orig_expr.cols)
subs[orig_expr] = sym
replacements.append((sym, new_expr))
return sym
else:
return new_expr
reduced_exprs = []
for e in exprs:
if isinstance(e, Basic):
reduced_e = _rebuild(e)
else:
reduced_e = e
reduced_exprs.append(reduced_e)
return replacements, reduced_exprs
def cse(exprs, symbols=None, optimizations=None, postprocess=None,
order='canonical', ignore=()):
""" Perform common subexpression elimination on an expression.
Parameters
==========
exprs : list of sympy expressions, or a single sympy expression
The expressions to reduce.
symbols : infinite iterator yielding unique Symbols
The symbols used to label the common subexpressions which are pulled
out. The ``numbered_symbols`` generator is useful. The default is a
stream of symbols of the form "x0", "x1", etc. This must be an
infinite iterator.
optimizations : list of (callable, callable) pairs
The (preprocessor, postprocessor) pairs of external optimization
functions. Optionally 'basic' can be passed for a set of predefined
basic optimizations. Such 'basic' optimizations were used by default
in old implementation, however they can be really slow on larger
expressions. Now, no pre or post optimizations are made by default.
postprocess : a function which accepts the two return values of cse and
returns the desired form of output from cse, e.g. if you want the
replacements reversed the function might be the following lambda:
lambda r, e: return reversed(r), e
order : string, 'none' or 'canonical'
The order by which Mul and Add arguments are processed. If set to
'canonical', arguments will be canonically ordered. If set to 'none',
ordering will be faster but dependent on expressions hashes, thus
machine dependent and variable. For large expressions where speed is a
concern, use the setting order='none'.
ignore : iterable of Symbols
Substitutions containing any Symbol from ``ignore`` will be ignored.
Returns
=======
replacements : list of (Symbol, expression) pairs
All of the common subexpressions that were replaced. Subexpressions
earlier in this list might show up in subexpressions later in this
list.
reduced_exprs : list of sympy expressions
The reduced expressions with all of the replacements above.
Examples
========
>>> from sympy import cse, SparseMatrix
>>> from sympy.abc import x, y, z, w
>>> cse(((w + x + y + z)*(w + y + z))/(w + x)**3)
([(x0, y + z), (x1, w + x)], [(w + x0)*(x0 + x1)/x1**3])
Note that currently, y + z will not get substituted if -y - z is used.
>>> cse(((w + x + y + z)*(w - y - z))/(w + x)**3)
([(x0, w + x)], [(w - y - z)*(x0 + y + z)/x0**3])
List of expressions with recursive substitutions:
>>> m = SparseMatrix([x + y, x + y + z])
>>> cse([(x+y)**2, x + y + z, y + z, x + z + y, m])
([(x0, x + y), (x1, x0 + z)], [x0**2, x1, y + z, x1, Matrix([
[x0],
[x1]])])
Note: the type and mutability of input matrices is retained.
>>> isinstance(_[1][-1], SparseMatrix)
True
The user may disallow substitutions containing certain symbols:
>>> cse([y**2*(x + 1), 3*y**2*(x + 1)], ignore=(y,))
([(x0, x + 1)], [x0*y**2, 3*x0*y**2])
"""
from sympy.matrices import (MatrixBase, Matrix, ImmutableMatrix,
SparseMatrix, ImmutableSparseMatrix)
if isinstance(exprs, (int, float)):
exprs = sympify(exprs)
# Handle the case if just one expression was passed.
if isinstance(exprs, (Basic, MatrixBase)):
exprs = [exprs]
copy = exprs
temp = []
for e in exprs:
if isinstance(e, (Matrix, ImmutableMatrix)):
temp.append(Tuple(*e._mat))
elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)):
temp.append(Tuple(*e._smat.items()))
else:
temp.append(e)
exprs = temp
del temp
if optimizations is None:
optimizations = list()
elif optimizations == 'basic':
optimizations = basic_optimizations
# Preprocess the expressions to give us better optimization opportunities.
reduced_exprs = [preprocess_for_cse(e, optimizations) for e in exprs]
if symbols is None:
symbols = numbered_symbols(cls=Symbol)
else:
# In case we get passed an iterable with an __iter__ method instead of
# an actual iterator.
symbols = iter(symbols)
# Find other optimization opportunities.
opt_subs = opt_cse(reduced_exprs, order)
# Main CSE algorithm.
replacements, reduced_exprs = tree_cse(reduced_exprs, symbols, opt_subs,
order, ignore)
# Postprocess the expressions to return the expressions to canonical form.
exprs = copy
for i, (sym, subtree) in enumerate(replacements):
subtree = postprocess_for_cse(subtree, optimizations)
replacements[i] = (sym, subtree)
reduced_exprs = [postprocess_for_cse(e, optimizations)
for e in reduced_exprs]
# Get the matrices back
for i, e in enumerate(exprs):
if isinstance(e, (Matrix, ImmutableMatrix)):
reduced_exprs[i] = Matrix(e.rows, e.cols, reduced_exprs[i])
if isinstance(e, ImmutableMatrix):
reduced_exprs[i] = reduced_exprs[i].as_immutable()
elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)):
m = SparseMatrix(e.rows, e.cols, {})
for k, v in reduced_exprs[i]:
m[k] = v
if isinstance(e, ImmutableSparseMatrix):
m = m.as_immutable()
reduced_exprs[i] = m
if postprocess is None:
return replacements, reduced_exprs
return postprocess(replacements, reduced_exprs)
|
a29533bd6b24725f9baf6592d5843319b85a590ae337d0fbccf551ab7bfc2d7d | from collections import defaultdict
from sympy.core.add import Add
from sympy.core.basic import S
from sympy.core.compatibility import ordered
from sympy.core.expr import Expr
from sympy.core.exprtools import Factors, gcd_terms, factor_terms
from sympy.core.function import expand_mul
from sympy.core.mul import Mul
from sympy.core.numbers import pi, I
from sympy.core.power import Pow
from sympy.core.symbol import Dummy
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import binomial
from sympy.functions.elementary.hyperbolic import (
cosh, sinh, tanh, coth, sech, csch, HyperbolicFunction)
from sympy.functions.elementary.trigonometric import (
cos, sin, tan, cot, sec, csc, sqrt, TrigonometricFunction)
from sympy.ntheory.factor_ import perfect_power
from sympy.polys.polytools import factor
from sympy.simplify.simplify import bottom_up
from sympy.strategies.tree import greedy
from sympy.strategies.core import identity, debug
from sympy import SYMPY_DEBUG
# ================== Fu-like tools ===========================
def TR0(rv):
"""Simplification of rational polynomials, trying to simplify
the expression, e.g. combine things like 3*x + 2*x, etc....
"""
# although it would be nice to use cancel, it doesn't work
# with noncommutatives
return rv.normal().factor().expand()
def TR1(rv):
"""Replace sec, csc with 1/cos, 1/sin
Examples
========
>>> from sympy.simplify.fu import TR1, sec, csc
>>> from sympy.abc import x
>>> TR1(2*csc(x) + sec(x))
1/cos(x) + 2/sin(x)
"""
def f(rv):
if isinstance(rv, sec):
a = rv.args[0]
return S.One/cos(a)
elif isinstance(rv, csc):
a = rv.args[0]
return S.One/sin(a)
return rv
return bottom_up(rv, f)
def TR2(rv):
"""Replace tan and cot with sin/cos and cos/sin
Examples
========
>>> from sympy.simplify.fu import TR2
>>> from sympy.abc import x
>>> from sympy import tan, cot, sin, cos
>>> TR2(tan(x))
sin(x)/cos(x)
>>> TR2(cot(x))
cos(x)/sin(x)
>>> TR2(tan(tan(x) - sin(x)/cos(x)))
0
"""
def f(rv):
if isinstance(rv, tan):
a = rv.args[0]
return sin(a)/cos(a)
elif isinstance(rv, cot):
a = rv.args[0]
return cos(a)/sin(a)
return rv
return bottom_up(rv, f)
def TR2i(rv, half=False):
"""Converts ratios involving sin and cos as follows::
sin(x)/cos(x) -> tan(x)
sin(x)/(cos(x) + 1) -> tan(x/2) if half=True
Examples
========
>>> from sympy.simplify.fu import TR2i
>>> from sympy.abc import x, a
>>> from sympy import sin, cos
>>> TR2i(sin(x)/cos(x))
tan(x)
Powers of the numerator and denominator are also recognized
>>> TR2i(sin(x)**2/(cos(x) + 1)**2, half=True)
tan(x/2)**2
The transformation does not take place unless assumptions allow
(i.e. the base must be positive or the exponent must be an integer
for both numerator and denominator)
>>> TR2i(sin(x)**a/(cos(x) + 1)**a)
sin(x)**a/(cos(x) + 1)**a
"""
def f(rv):
if not rv.is_Mul:
return rv
n, d = rv.as_numer_denom()
if n.is_Atom or d.is_Atom:
return rv
def ok(k, e):
# initial filtering of factors
return (
(e.is_integer or k.is_positive) and (
k.func in (sin, cos) or (half and
k.is_Add and
len(k.args) >= 2 and
any(any(isinstance(ai, cos) or ai.is_Pow and ai.base is cos
for ai in Mul.make_args(a)) for a in k.args))))
n = n.as_powers_dict()
ndone = [(k, n.pop(k)) for k in list(n.keys()) if not ok(k, n[k])]
if not n:
return rv
d = d.as_powers_dict()
ddone = [(k, d.pop(k)) for k in list(d.keys()) if not ok(k, d[k])]
if not d:
return rv
# factoring if necessary
def factorize(d, ddone):
newk = []
for k in d:
if k.is_Add and len(k.args) > 1:
knew = factor(k) if half else factor_terms(k)
if knew != k:
newk.append((k, knew))
if newk:
for i, (k, knew) in enumerate(newk):
del d[k]
newk[i] = knew
newk = Mul(*newk).as_powers_dict()
for k in newk:
v = d[k] + newk[k]
if ok(k, v):
d[k] = v
else:
ddone.append((k, v))
del newk
factorize(n, ndone)
factorize(d, ddone)
# joining
t = []
for k in n:
if isinstance(k, sin):
a = cos(k.args[0], evaluate=False)
if a in d and d[a] == n[k]:
t.append(tan(k.args[0])**n[k])
n[k] = d[a] = None
elif half:
a1 = 1 + a
if a1 in d and d[a1] == n[k]:
t.append((tan(k.args[0]/2))**n[k])
n[k] = d[a1] = None
elif isinstance(k, cos):
a = sin(k.args[0], evaluate=False)
if a in d and d[a] == n[k]:
t.append(tan(k.args[0])**-n[k])
n[k] = d[a] = None
elif half and k.is_Add and k.args[0] is S.One and \
isinstance(k.args[1], cos):
a = sin(k.args[1].args[0], evaluate=False)
if a in d and d[a] == n[k] and (d[a].is_integer or \
a.is_positive):
t.append(tan(a.args[0]/2)**-n[k])
n[k] = d[a] = None
if t:
rv = Mul(*(t + [b**e for b, e in n.items() if e]))/\
Mul(*[b**e for b, e in d.items() if e])
rv *= Mul(*[b**e for b, e in ndone])/Mul(*[b**e for b, e in ddone])
return rv
return bottom_up(rv, f)
def TR3(rv):
"""Induced formula: example sin(-a) = -sin(a)
Examples
========
>>> from sympy.simplify.fu import TR3
>>> from sympy.abc import x, y
>>> from sympy import pi
>>> from sympy import cos
>>> TR3(cos(y - x*(y - x)))
cos(x*(x - y) + y)
>>> cos(pi/2 + x)
-sin(x)
>>> cos(30*pi/2 + x)
-cos(x)
"""
from sympy.simplify.simplify import signsimp
# Negative argument (already automatic for funcs like sin(-x) -> -sin(x)
# but more complicated expressions can use it, too). Also, trig angles
# between pi/4 and pi/2 are not reduced to an angle between 0 and pi/4.
# The following are automatically handled:
# Argument of type: pi/2 +/- angle
# Argument of type: pi +/- angle
# Argument of type : 2k*pi +/- angle
def f(rv):
if not isinstance(rv, TrigonometricFunction):
return rv
rv = rv.func(signsimp(rv.args[0]))
if not isinstance(rv, TrigonometricFunction):
return rv
if (rv.args[0] - S.Pi/4).is_positive is (S.Pi/2 - rv.args[0]).is_positive is True:
fmap = {cos: sin, sin: cos, tan: cot, cot: tan, sec: csc, csc: sec}
rv = fmap[rv.func](S.Pi/2 - rv.args[0])
return rv
return bottom_up(rv, f)
def TR4(rv):
"""Identify values of special angles.
a= 0 pi/6 pi/4 pi/3 pi/2
----------------------------------------------------
cos(a) 0 1/2 sqrt(2)/2 sqrt(3)/2 1
sin(a) 1 sqrt(3)/2 sqrt(2)/2 1/2 0
tan(a) 0 sqt(3)/3 1 sqrt(3) --
Examples
========
>>> from sympy import pi
>>> from sympy import cos, sin, tan, cot
>>> for s in (0, pi/6, pi/4, pi/3, pi/2):
... print('%s %s %s %s' % (cos(s), sin(s), tan(s), cot(s)))
...
1 0 0 zoo
sqrt(3)/2 1/2 sqrt(3)/3 sqrt(3)
sqrt(2)/2 sqrt(2)/2 1 1
1/2 sqrt(3)/2 sqrt(3) sqrt(3)/3
0 1 zoo 0
"""
# special values at 0, pi/6, pi/4, pi/3, pi/2 already handled
return rv
def _TR56(rv, f, g, h, max, pow):
"""Helper for TR5 and TR6 to replace f**2 with h(g**2)
Options
=======
max : controls size of exponent that can appear on f
e.g. if max=4 then f**4 will be changed to h(g**2)**2.
pow : controls whether the exponent must be a perfect power of 2
e.g. if pow=True (and max >= 6) then f**6 will not be changed
but f**8 will be changed to h(g**2)**4
>>> from sympy.simplify.fu import _TR56 as T
>>> from sympy.abc import x
>>> from sympy import sin, cos
>>> h = lambda x: 1 - x
>>> T(sin(x)**3, sin, cos, h, 4, False)
(1 - cos(x)**2)*sin(x)
>>> T(sin(x)**6, sin, cos, h, 6, False)
(1 - cos(x)**2)**3
>>> T(sin(x)**6, sin, cos, h, 6, True)
sin(x)**6
>>> T(sin(x)**8, sin, cos, h, 10, True)
(1 - cos(x)**2)**4
"""
def _f(rv):
# I'm not sure if this transformation should target all even powers
# or only those expressible as powers of 2. Also, should it only
# make the changes in powers that appear in sums -- making an isolated
# change is not going to allow a simplification as far as I can tell.
if not (rv.is_Pow and rv.base.func == f):
return rv
if not rv.exp.is_real:
return rv
if (rv.exp < 0) == True:
return rv
if (rv.exp > max) == True:
return rv
if rv.exp == 1:
return rv
if rv.exp == 2:
return h(g(rv.base.args[0])**2)
else:
if rv.exp % 2 == 1:
e = rv.exp//2
return f(rv.base.args[0])*h(g(rv.base.args[0])**2)**e
elif rv.exp == 4:
e = 2
elif not pow:
if rv.exp % 2:
return rv
e = rv.exp//2
else:
p = perfect_power(rv.exp)
if not p:
return rv
e = rv.exp//2
return h(g(rv.base.args[0])**2)**e
return bottom_up(rv, _f)
def TR5(rv, max=4, pow=False):
"""Replacement of sin**2 with 1 - cos(x)**2.
See _TR56 docstring for advanced use of ``max`` and ``pow``.
Examples
========
>>> from sympy.simplify.fu import TR5
>>> from sympy.abc import x
>>> from sympy import sin
>>> TR5(sin(x)**2)
1 - cos(x)**2
>>> TR5(sin(x)**-2) # unchanged
sin(x)**(-2)
>>> TR5(sin(x)**4)
(1 - cos(x)**2)**2
"""
return _TR56(rv, sin, cos, lambda x: 1 - x, max=max, pow=pow)
def TR6(rv, max=4, pow=False):
"""Replacement of cos**2 with 1 - sin(x)**2.
See _TR56 docstring for advanced use of ``max`` and ``pow``.
Examples
========
>>> from sympy.simplify.fu import TR6
>>> from sympy.abc import x
>>> from sympy import cos
>>> TR6(cos(x)**2)
1 - sin(x)**2
>>> TR6(cos(x)**-2) #unchanged
cos(x)**(-2)
>>> TR6(cos(x)**4)
(1 - sin(x)**2)**2
"""
return _TR56(rv, cos, sin, lambda x: 1 - x, max=max, pow=pow)
def TR7(rv):
"""Lowering the degree of cos(x)**2.
Examples
========
>>> from sympy.simplify.fu import TR7
>>> from sympy.abc import x
>>> from sympy import cos
>>> TR7(cos(x)**2)
cos(2*x)/2 + 1/2
>>> TR7(cos(x)**2 + 1)
cos(2*x)/2 + 3/2
"""
def f(rv):
if not (rv.is_Pow and rv.base.func == cos and rv.exp == 2):
return rv
return (1 + cos(2*rv.base.args[0]))/2
return bottom_up(rv, f)
def TR8(rv, first=True):
"""Converting products of ``cos`` and/or ``sin`` to a sum or
difference of ``cos`` and or ``sin`` terms.
Examples
========
>>> from sympy.simplify.fu import TR8
>>> from sympy import cos, sin
>>> TR8(cos(2)*cos(3))
cos(5)/2 + cos(1)/2
>>> TR8(cos(2)*sin(3))
sin(5)/2 + sin(1)/2
>>> TR8(sin(2)*sin(3))
-cos(5)/2 + cos(1)/2
"""
def f(rv):
if not (
rv.is_Mul or
rv.is_Pow and
rv.base.func in (cos, sin) and
(rv.exp.is_integer or rv.base.is_positive)):
return rv
if first:
n, d = [expand_mul(i) for i in rv.as_numer_denom()]
newn = TR8(n, first=False)
newd = TR8(d, first=False)
if newn != n or newd != d:
rv = gcd_terms(newn/newd)
if rv.is_Mul and rv.args[0].is_Rational and \
len(rv.args) == 2 and rv.args[1].is_Add:
rv = Mul(*rv.as_coeff_Mul())
return rv
args = {cos: [], sin: [], None: []}
for a in ordered(Mul.make_args(rv)):
if a.func in (cos, sin):
args[a.func].append(a.args[0])
elif (a.is_Pow and a.exp.is_Integer and a.exp > 0 and \
a.base.func in (cos, sin)):
# XXX this is ok but pathological expression could be handled
# more efficiently as in TRmorrie
args[a.base.func].extend([a.base.args[0]]*a.exp)
else:
args[None].append(a)
c = args[cos]
s = args[sin]
if not (c and s or len(c) > 1 or len(s) > 1):
return rv
args = args[None]
n = min(len(c), len(s))
for i in range(n):
a1 = s.pop()
a2 = c.pop()
args.append((sin(a1 + a2) + sin(a1 - a2))/2)
while len(c) > 1:
a1 = c.pop()
a2 = c.pop()
args.append((cos(a1 + a2) + cos(a1 - a2))/2)
if c:
args.append(cos(c.pop()))
while len(s) > 1:
a1 = s.pop()
a2 = s.pop()
args.append((-cos(a1 + a2) + cos(a1 - a2))/2)
if s:
args.append(sin(s.pop()))
return TR8(expand_mul(Mul(*args)))
return bottom_up(rv, f)
def TR9(rv):
"""Sum of ``cos`` or ``sin`` terms as a product of ``cos`` or ``sin``.
Examples
========
>>> from sympy.simplify.fu import TR9
>>> from sympy import cos, sin
>>> TR9(cos(1) + cos(2))
2*cos(1/2)*cos(3/2)
>>> TR9(cos(1) + 2*sin(1) + 2*sin(2))
cos(1) + 4*sin(3/2)*cos(1/2)
If no change is made by TR9, no re-arrangement of the
expression will be made. For example, though factoring
of common term is attempted, if the factored expression
wasn't changed, the original expression will be returned:
>>> TR9(cos(3) + cos(3)*cos(2))
cos(3) + cos(2)*cos(3)
"""
def f(rv):
if not rv.is_Add:
return rv
def do(rv, first=True):
# cos(a)+/-cos(b) can be combined into a product of cosines and
# sin(a)+/-sin(b) can be combined into a product of cosine and
# sine.
#
# If there are more than two args, the pairs which "work" will
# have a gcd extractable and the remaining two terms will have
# the above structure -- all pairs must be checked to find the
# ones that work. args that don't have a common set of symbols
# are skipped since this doesn't lead to a simpler formula and
# also has the arbitrariness of combining, for example, the x
# and y term instead of the y and z term in something like
# cos(x) + cos(y) + cos(z).
if not rv.is_Add:
return rv
args = list(ordered(rv.args))
if len(args) != 2:
hit = False
for i in range(len(args)):
ai = args[i]
if ai is None:
continue
for j in range(i + 1, len(args)):
aj = args[j]
if aj is None:
continue
was = ai + aj
new = do(was)
if new != was:
args[i] = new # update in place
args[j] = None
hit = True
break # go to next i
if hit:
rv = Add(*[_f for _f in args if _f])
if rv.is_Add:
rv = do(rv)
return rv
# two-arg Add
split = trig_split(*args)
if not split:
return rv
gcd, n1, n2, a, b, iscos = split
# application of rule if possible
if iscos:
if n1 == n2:
return gcd*n1*2*cos((a + b)/2)*cos((a - b)/2)
if n1 < 0:
a, b = b, a
return -2*gcd*sin((a + b)/2)*sin((a - b)/2)
else:
if n1 == n2:
return gcd*n1*2*sin((a + b)/2)*cos((a - b)/2)
if n1 < 0:
a, b = b, a
return 2*gcd*cos((a + b)/2)*sin((a - b)/2)
return process_common_addends(rv, do) # DON'T sift by free symbols
return bottom_up(rv, f)
def TR10(rv, first=True):
"""Separate sums in ``cos`` and ``sin``.
Examples
========
>>> from sympy.simplify.fu import TR10
>>> from sympy.abc import a, b, c
>>> from sympy import cos, sin
>>> TR10(cos(a + b))
-sin(a)*sin(b) + cos(a)*cos(b)
>>> TR10(sin(a + b))
sin(a)*cos(b) + sin(b)*cos(a)
>>> TR10(sin(a + b + c))
(-sin(a)*sin(b) + cos(a)*cos(b))*sin(c) + \
(sin(a)*cos(b) + sin(b)*cos(a))*cos(c)
"""
def f(rv):
if not rv.func in (cos, sin):
return rv
f = rv.func
arg = rv.args[0]
if arg.is_Add:
if first:
args = list(ordered(arg.args))
else:
args = list(arg.args)
a = args.pop()
b = Add._from_args(args)
if b.is_Add:
if f == sin:
return sin(a)*TR10(cos(b), first=False) + \
cos(a)*TR10(sin(b), first=False)
else:
return cos(a)*TR10(cos(b), first=False) - \
sin(a)*TR10(sin(b), first=False)
else:
if f == sin:
return sin(a)*cos(b) + cos(a)*sin(b)
else:
return cos(a)*cos(b) - sin(a)*sin(b)
return rv
return bottom_up(rv, f)
def TR10i(rv):
"""Sum of products to function of sum.
Examples
========
>>> from sympy.simplify.fu import TR10i
>>> from sympy import cos, sin, sqrt
>>> from sympy.abc import x
>>> TR10i(cos(1)*cos(3) + sin(1)*sin(3))
cos(2)
>>> TR10i(cos(1)*sin(3) + sin(1)*cos(3) + cos(3))
cos(3) + sin(4)
>>> TR10i(sqrt(2)*cos(x)*x + sqrt(6)*sin(x)*x)
2*sqrt(2)*x*sin(x + pi/6)
"""
global _ROOT2, _ROOT3, _invROOT3
if _ROOT2 is None:
_roots()
def f(rv):
if not rv.is_Add:
return rv
def do(rv, first=True):
# args which can be expressed as A*(cos(a)*cos(b)+/-sin(a)*sin(b))
# or B*(cos(a)*sin(b)+/-cos(b)*sin(a)) can be combined into
# A*f(a+/-b) where f is either sin or cos.
#
# If there are more than two args, the pairs which "work" will have
# a gcd extractable and the remaining two terms will have the above
# structure -- all pairs must be checked to find the ones that
# work.
if not rv.is_Add:
return rv
args = list(ordered(rv.args))
if len(args) != 2:
hit = False
for i in range(len(args)):
ai = args[i]
if ai is None:
continue
for j in range(i + 1, len(args)):
aj = args[j]
if aj is None:
continue
was = ai + aj
new = do(was)
if new != was:
args[i] = new # update in place
args[j] = None
hit = True
break # go to next i
if hit:
rv = Add(*[_f for _f in args if _f])
if rv.is_Add:
rv = do(rv)
return rv
# two-arg Add
split = trig_split(*args, two=True)
if not split:
return rv
gcd, n1, n2, a, b, same = split
# identify and get c1 to be cos then apply rule if possible
if same: # coscos, sinsin
gcd = n1*gcd
if n1 == n2:
return gcd*cos(a - b)
return gcd*cos(a + b)
else: #cossin, cossin
gcd = n1*gcd
if n1 == n2:
return gcd*sin(a + b)
return gcd*sin(b - a)
rv = process_common_addends(
rv, do, lambda x: tuple(ordered(x.free_symbols)))
# need to check for inducible pairs in ratio of sqrt(3):1 that
# appeared in different lists when sorting by coefficient
while rv.is_Add:
byrad = defaultdict(list)
for a in rv.args:
hit = 0
if a.is_Mul:
for ai in a.args:
if ai.is_Pow and ai.exp is S.Half and \
ai.base.is_Integer:
byrad[ai].append(a)
hit = 1
break
if not hit:
byrad[S.One].append(a)
# no need to check all pairs -- just check for the onees
# that have the right ratio
args = []
for a in byrad:
for b in [_ROOT3*a, _invROOT3]:
if b in byrad:
for i in range(len(byrad[a])):
if byrad[a][i] is None:
continue
for j in range(len(byrad[b])):
if byrad[b][j] is None:
continue
was = Add(byrad[a][i] + byrad[b][j])
new = do(was)
if new != was:
args.append(new)
byrad[a][i] = None
byrad[b][j] = None
break
if args:
rv = Add(*(args + [Add(*[_f for _f in v if _f])
for v in byrad.values()]))
else:
rv = do(rv) # final pass to resolve any new inducible pairs
break
return rv
return bottom_up(rv, f)
def TR11(rv, base=None):
"""Function of double angle to product. The ``base`` argument can be used
to indicate what is the un-doubled argument, e.g. if 3*pi/7 is the base
then cosine and sine functions with argument 6*pi/7 will be replaced.
Examples
========
>>> from sympy.simplify.fu import TR11
>>> from sympy import cos, sin, pi
>>> from sympy.abc import x
>>> TR11(sin(2*x))
2*sin(x)*cos(x)
>>> TR11(cos(2*x))
-sin(x)**2 + cos(x)**2
>>> TR11(sin(4*x))
4*(-sin(x)**2 + cos(x)**2)*sin(x)*cos(x)
>>> TR11(sin(4*x/3))
4*(-sin(x/3)**2 + cos(x/3)**2)*sin(x/3)*cos(x/3)
If the arguments are simply integers, no change is made
unless a base is provided:
>>> TR11(cos(2))
cos(2)
>>> TR11(cos(4), 2)
-sin(2)**2 + cos(2)**2
There is a subtle issue here in that autosimplification will convert
some higher angles to lower angles
>>> cos(6*pi/7) + cos(3*pi/7)
-cos(pi/7) + cos(3*pi/7)
The 6*pi/7 angle is now pi/7 but can be targeted with TR11 by supplying
the 3*pi/7 base:
>>> TR11(_, 3*pi/7)
-sin(3*pi/7)**2 + cos(3*pi/7)**2 + cos(3*pi/7)
"""
def f(rv):
if not rv.func in (cos, sin):
return rv
if base:
f = rv.func
t = f(base*2)
co = S.One
if t.is_Mul:
co, t = t.as_coeff_Mul()
if not t.func in (cos, sin):
return rv
if rv.args[0] == t.args[0]:
c = cos(base)
s = sin(base)
if f is cos:
return (c**2 - s**2)/co
else:
return 2*c*s/co
return rv
elif not rv.args[0].is_Number:
# make a change if the leading coefficient's numerator is
# divisible by 2
c, m = rv.args[0].as_coeff_Mul(rational=True)
if c.p % 2 == 0:
arg = c.p//2*m/c.q
c = TR11(cos(arg))
s = TR11(sin(arg))
if rv.func == sin:
rv = 2*s*c
else:
rv = c**2 - s**2
return rv
return bottom_up(rv, f)
def _TR11(rv):
"""
Helper for TR11 to find half-arguments for sin in factors of
num/den that appear in cos or sin factors in the den/num.
Examples
========
>>> from sympy.simplify.fu import TR11, _TR11
>>> from sympy import cos, sin
>>> from sympy.abc import x
>>> TR11(sin(x/3)/(cos(x/6)))
sin(x/3)/cos(x/6)
>>> _TR11(sin(x/3)/(cos(x/6)))
2*sin(x/6)
>>> TR11(sin(x/6)/(sin(x/3)))
sin(x/6)/sin(x/3)
>>> _TR11(sin(x/6)/(sin(x/3)))
1/(2*cos(x/6))
"""
def f(rv):
if not isinstance(rv, Expr):
return rv
def sincos_args(flat):
# find arguments of sin and cos that
# appears as bases in args of flat
# and have Integer exponents
args = defaultdict(set)
for fi in Mul.make_args(flat):
b, e = fi.as_base_exp()
if e.is_Integer and e > 0:
if b.func in (cos, sin):
args[b.func].add(b.args[0])
return args
num_args, den_args = map(sincos_args, rv.as_numer_denom())
def handle_match(rv, num_args, den_args):
# for arg in sin args of num_args, look for arg/2
# in den_args and pass this half-angle to TR11
# for handling in rv
for narg in num_args[sin]:
half = narg/2
if half in den_args[cos]:
func = cos
elif half in den_args[sin]:
func = sin
else:
continue
rv = TR11(rv, half)
den_args[func].remove(half)
return rv
# sin in num, sin or cos in den
rv = handle_match(rv, num_args, den_args)
# sin in den, sin or cos in num
rv = handle_match(rv, den_args, num_args)
return rv
return bottom_up(rv, f)
def TR12(rv, first=True):
"""Separate sums in ``tan``.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import tan
>>> from sympy.simplify.fu import TR12
>>> TR12(tan(x + y))
(tan(x) + tan(y))/(-tan(x)*tan(y) + 1)
"""
def f(rv):
if not rv.func == tan:
return rv
arg = rv.args[0]
if arg.is_Add:
if first:
args = list(ordered(arg.args))
else:
args = list(arg.args)
a = args.pop()
b = Add._from_args(args)
if b.is_Add:
tb = TR12(tan(b), first=False)
else:
tb = tan(b)
return (tan(a) + tb)/(1 - tan(a)*tb)
return rv
return bottom_up(rv, f)
def TR12i(rv):
"""Combine tan arguments as
(tan(y) + tan(x))/(tan(x)*tan(y) - 1) -> -tan(x + y).
Examples
========
>>> from sympy.simplify.fu import TR12i
>>> from sympy import tan
>>> from sympy.abc import a, b, c
>>> ta, tb, tc = [tan(i) for i in (a, b, c)]
>>> TR12i((ta + tb)/(-ta*tb + 1))
tan(a + b)
>>> TR12i((ta + tb)/(ta*tb - 1))
-tan(a + b)
>>> TR12i((-ta - tb)/(ta*tb - 1))
tan(a + b)
>>> eq = (ta + tb)/(-ta*tb + 1)**2*(-3*ta - 3*tc)/(2*(ta*tc - 1))
>>> TR12i(eq.expand())
-3*tan(a + b)*tan(a + c)/(2*(tan(a) + tan(b) - 1))
"""
from sympy import factor
def f(rv):
if not (rv.is_Add or rv.is_Mul or rv.is_Pow):
return rv
n, d = rv.as_numer_denom()
if not d.args or not n.args:
return rv
dok = {}
def ok(di):
m = as_f_sign_1(di)
if m:
g, f, s = m
if s is S.NegativeOne and f.is_Mul and len(f.args) == 2 and \
all(isinstance(fi, tan) for fi in f.args):
return g, f
d_args = list(Mul.make_args(d))
for i, di in enumerate(d_args):
m = ok(di)
if m:
g, t = m
s = Add(*[_.args[0] for _ in t.args])
dok[s] = S.One
d_args[i] = g
continue
if di.is_Add:
di = factor(di)
if di.is_Mul:
d_args.extend(di.args)
d_args[i] = S.One
elif di.is_Pow and (di.exp.is_integer or di.base.is_positive):
m = ok(di.base)
if m:
g, t = m
s = Add(*[_.args[0] for _ in t.args])
dok[s] = di.exp
d_args[i] = g**di.exp
else:
di = factor(di)
if di.is_Mul:
d_args.extend(di.args)
d_args[i] = S.One
if not dok:
return rv
def ok(ni):
if ni.is_Add and len(ni.args) == 2:
a, b = ni.args
if isinstance(a, tan) and isinstance(b, tan):
return a, b
n_args = list(Mul.make_args(factor_terms(n)))
hit = False
for i, ni in enumerate(n_args):
m = ok(ni)
if not m:
m = ok(-ni)
if m:
n_args[i] = S.NegativeOne
else:
if ni.is_Add:
ni = factor(ni)
if ni.is_Mul:
n_args.extend(ni.args)
n_args[i] = S.One
continue
elif ni.is_Pow and (
ni.exp.is_integer or ni.base.is_positive):
m = ok(ni.base)
if m:
n_args[i] = S.One
else:
ni = factor(ni)
if ni.is_Mul:
n_args.extend(ni.args)
n_args[i] = S.One
continue
else:
continue
else:
n_args[i] = S.One
hit = True
s = Add(*[_.args[0] for _ in m])
ed = dok[s]
newed = ed.extract_additively(S.One)
if newed is not None:
if newed:
dok[s] = newed
else:
dok.pop(s)
n_args[i] *= -tan(s)
if hit:
rv = Mul(*n_args)/Mul(*d_args)/Mul(*[(Add(*[
tan(a) for a in i.args]) - 1)**e for i, e in dok.items()])
return rv
return bottom_up(rv, f)
def TR13(rv):
"""Change products of ``tan`` or ``cot``.
Examples
========
>>> from sympy.simplify.fu import TR13
>>> from sympy import tan, cot
>>> TR13(tan(3)*tan(2))
-tan(2)/tan(5) - tan(3)/tan(5) + 1
>>> TR13(cot(3)*cot(2))
cot(2)*cot(5) + 1 + cot(3)*cot(5)
"""
def f(rv):
if not rv.is_Mul:
return rv
# XXX handle products of powers? or let power-reducing handle it?
args = {tan: [], cot: [], None: []}
for a in ordered(Mul.make_args(rv)):
if a.func in (tan, cot):
args[a.func].append(a.args[0])
else:
args[None].append(a)
t = args[tan]
c = args[cot]
if len(t) < 2 and len(c) < 2:
return rv
args = args[None]
while len(t) > 1:
t1 = t.pop()
t2 = t.pop()
args.append(1 - (tan(t1)/tan(t1 + t2) + tan(t2)/tan(t1 + t2)))
if t:
args.append(tan(t.pop()))
while len(c) > 1:
t1 = c.pop()
t2 = c.pop()
args.append(1 + cot(t1)*cot(t1 + t2) + cot(t2)*cot(t1 + t2))
if c:
args.append(cot(c.pop()))
return Mul(*args)
return bottom_up(rv, f)
def TRmorrie(rv):
"""Returns cos(x)*cos(2*x)*...*cos(2**(k-1)*x) -> sin(2**k*x)/(2**k*sin(x))
Examples
========
>>> from sympy.simplify.fu import TRmorrie, TR8, TR3
>>> from sympy.abc import x
>>> from sympy import Mul, cos, pi
>>> TRmorrie(cos(x)*cos(2*x))
sin(4*x)/(4*sin(x))
>>> TRmorrie(7*Mul(*[cos(x) for x in range(10)]))
7*sin(12)*sin(16)*cos(5)*cos(7)*cos(9)/(64*sin(1)*sin(3))
Sometimes autosimplification will cause a power to be
not recognized. e.g. in the following, cos(4*pi/7) automatically
simplifies to -cos(3*pi/7) so only 2 of the 3 terms are
recognized:
>>> TRmorrie(cos(pi/7)*cos(2*pi/7)*cos(4*pi/7))
-sin(3*pi/7)*cos(3*pi/7)/(4*sin(pi/7))
A touch by TR8 resolves the expression to a Rational
>>> TR8(_)
-1/8
In this case, if eq is unsimplified, the answer is obtained
directly:
>>> eq = cos(pi/9)*cos(2*pi/9)*cos(3*pi/9)*cos(4*pi/9)
>>> TRmorrie(eq)
1/16
But if angles are made canonical with TR3 then the answer
is not simplified without further work:
>>> TR3(eq)
sin(pi/18)*cos(pi/9)*cos(2*pi/9)/2
>>> TRmorrie(_)
sin(pi/18)*sin(4*pi/9)/(8*sin(pi/9))
>>> TR8(_)
cos(7*pi/18)/(16*sin(pi/9))
>>> TR3(_)
1/16
The original expression would have resolve to 1/16 directly with TR8,
however:
>>> TR8(eq)
1/16
References
==========
.. [1] https://en.wikipedia.org/wiki/Morrie%27s_law
"""
def f(rv, first=True):
if not rv.is_Mul:
return rv
if first:
n, d = rv.as_numer_denom()
return f(n, 0)/f(d, 0)
args = defaultdict(list)
coss = {}
other = []
for c in rv.args:
b, e = c.as_base_exp()
if e.is_Integer and isinstance(b, cos):
co, a = b.args[0].as_coeff_Mul()
args[a].append(co)
coss[b] = e
else:
other.append(c)
new = []
for a in args:
c = args[a]
c.sort()
while c:
k = 0
cc = ci = c[0]
while cc in c:
k += 1
cc *= 2
if k > 1:
newarg = sin(2**k*ci*a)/2**k/sin(ci*a)
# see how many times this can be taken
take = None
ccs = []
for i in range(k):
cc /= 2
key = cos(a*cc, evaluate=False)
ccs.append(cc)
take = min(coss[key], take or coss[key])
# update exponent counts
for i in range(k):
cc = ccs.pop()
key = cos(a*cc, evaluate=False)
coss[key] -= take
if not coss[key]:
c.remove(cc)
new.append(newarg**take)
else:
b = cos(c.pop(0)*a)
other.append(b**coss[b])
if new:
rv = Mul(*(new + other + [
cos(k*a, evaluate=False) for a in args for k in args[a]]))
return rv
return bottom_up(rv, f)
def TR14(rv, first=True):
"""Convert factored powers of sin and cos identities into simpler
expressions.
Examples
========
>>> from sympy.simplify.fu import TR14
>>> from sympy.abc import x, y
>>> from sympy import cos, sin
>>> TR14((cos(x) - 1)*(cos(x) + 1))
-sin(x)**2
>>> TR14((sin(x) - 1)*(sin(x) + 1))
-cos(x)**2
>>> p1 = (cos(x) + 1)*(cos(x) - 1)
>>> p2 = (cos(y) - 1)*2*(cos(y) + 1)
>>> p3 = (3*(cos(y) - 1))*(3*(cos(y) + 1))
>>> TR14(p1*p2*p3*(x - 1))
-18*(x - 1)*sin(x)**2*sin(y)**4
"""
def f(rv):
if not rv.is_Mul:
return rv
if first:
# sort them by location in numerator and denominator
# so the code below can just deal with positive exponents
n, d = rv.as_numer_denom()
if d is not S.One:
newn = TR14(n, first=False)
newd = TR14(d, first=False)
if newn != n or newd != d:
rv = newn/newd
return rv
other = []
process = []
for a in rv.args:
if a.is_Pow:
b, e = a.as_base_exp()
if not (e.is_integer or b.is_positive):
other.append(a)
continue
a = b
else:
e = S.One
m = as_f_sign_1(a)
if not m or m[1].func not in (cos, sin):
if e is S.One:
other.append(a)
else:
other.append(a**e)
continue
g, f, si = m
process.append((g, e.is_Number, e, f, si, a))
# sort them to get like terms next to each other
process = list(ordered(process))
# keep track of whether there was any change
nother = len(other)
# access keys
keys = (g, t, e, f, si, a) = list(range(6))
while process:
A = process.pop(0)
if process:
B = process[0]
if A[e].is_Number and B[e].is_Number:
# both exponents are numbers
if A[f] == B[f]:
if A[si] != B[si]:
B = process.pop(0)
take = min(A[e], B[e])
# reinsert any remainder
# the B will likely sort after A so check it first
if B[e] != take:
rem = [B[i] for i in keys]
rem[e] -= take
process.insert(0, rem)
elif A[e] != take:
rem = [A[i] for i in keys]
rem[e] -= take
process.insert(0, rem)
if isinstance(A[f], cos):
t = sin
else:
t = cos
other.append((-A[g]*B[g]*t(A[f].args[0])**2)**take)
continue
elif A[e] == B[e]:
# both exponents are equal symbols
if A[f] == B[f]:
if A[si] != B[si]:
B = process.pop(0)
take = A[e]
if isinstance(A[f], cos):
t = sin
else:
t = cos
other.append((-A[g]*B[g]*t(A[f].args[0])**2)**take)
continue
# either we are done or neither condition above applied
other.append(A[a]**A[e])
if len(other) != nother:
rv = Mul(*other)
return rv
return bottom_up(rv, f)
def TR15(rv, max=4, pow=False):
"""Convert sin(x)**-2 to 1 + cot(x)**2.
See _TR56 docstring for advanced use of ``max`` and ``pow``.
Examples
========
>>> from sympy.simplify.fu import TR15
>>> from sympy.abc import x
>>> from sympy import sin
>>> TR15(1 - 1/sin(x)**2)
-cot(x)**2
"""
def f(rv):
if not (isinstance(rv, Pow) and isinstance(rv.base, sin)):
return rv
e = rv.exp
if e % 2 == 1:
return TR15(rv.base**(e + 1))/rv.base
ia = 1/rv
a = _TR56(ia, sin, cot, lambda x: 1 + x, max=max, pow=pow)
if a != ia:
rv = a
return rv
return bottom_up(rv, f)
def TR16(rv, max=4, pow=False):
"""Convert cos(x)**-2 to 1 + tan(x)**2.
See _TR56 docstring for advanced use of ``max`` and ``pow``.
Examples
========
>>> from sympy.simplify.fu import TR16
>>> from sympy.abc import x
>>> from sympy import cos
>>> TR16(1 - 1/cos(x)**2)
-tan(x)**2
"""
def f(rv):
if not (isinstance(rv, Pow) and isinstance(rv.base, cos)):
return rv
e = rv.exp
if e % 2 == 1:
return TR15(rv.base**(e + 1))/rv.base
ia = 1/rv
a = _TR56(ia, cos, tan, lambda x: 1 + x, max=max, pow=pow)
if a != ia:
rv = a
return rv
return bottom_up(rv, f)
def TR111(rv):
"""Convert f(x)**-i to g(x)**i where either ``i`` is an integer
or the base is positive and f, g are: tan, cot; sin, csc; or cos, sec.
Examples
========
>>> from sympy.simplify.fu import TR111
>>> from sympy.abc import x
>>> from sympy import tan
>>> TR111(1 - 1/tan(x)**2)
1 - cot(x)**2
"""
def f(rv):
if not (
isinstance(rv, Pow) and
(rv.base.is_positive or rv.exp.is_integer and rv.exp.is_negative)):
return rv
if isinstance(rv.base, tan):
return cot(rv.base.args[0])**-rv.exp
elif isinstance(rv.base, sin):
return csc(rv.base.args[0])**-rv.exp
elif isinstance(rv.base, cos):
return sec(rv.base.args[0])**-rv.exp
return rv
return bottom_up(rv, f)
def TR22(rv, max=4, pow=False):
"""Convert tan(x)**2 to sec(x)**2 - 1 and cot(x)**2 to csc(x)**2 - 1.
See _TR56 docstring for advanced use of ``max`` and ``pow``.
Examples
========
>>> from sympy.simplify.fu import TR22
>>> from sympy.abc import x
>>> from sympy import tan, cot
>>> TR22(1 + tan(x)**2)
sec(x)**2
>>> TR22(1 + cot(x)**2)
csc(x)**2
"""
def f(rv):
if not (isinstance(rv, Pow) and rv.base.func in (cot, tan)):
return rv
rv = _TR56(rv, tan, sec, lambda x: x - 1, max=max, pow=pow)
rv = _TR56(rv, cot, csc, lambda x: x - 1, max=max, pow=pow)
return rv
return bottom_up(rv, f)
def TRpower(rv):
"""Convert sin(x)**n and cos(x)**n with positive n to sums.
Examples
========
>>> from sympy.simplify.fu import TRpower
>>> from sympy.abc import x
>>> from sympy import cos, sin
>>> TRpower(sin(x)**6)
-15*cos(2*x)/32 + 3*cos(4*x)/16 - cos(6*x)/32 + 5/16
>>> TRpower(sin(x)**3*cos(2*x)**4)
(3*sin(x)/4 - sin(3*x)/4)*(cos(4*x)/2 + cos(8*x)/8 + 3/8)
References
==========
.. [1] https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Power-reduction_formulae
"""
def f(rv):
if not (isinstance(rv, Pow) and isinstance(rv.base, (sin, cos))):
return rv
b, n = rv.as_base_exp()
x = b.args[0]
if n.is_Integer and n.is_positive:
if n.is_odd and isinstance(b, cos):
rv = 2**(1-n)*Add(*[binomial(n, k)*cos((n - 2*k)*x)
for k in range((n + 1)/2)])
elif n.is_odd and isinstance(b, sin):
rv = 2**(1-n)*(-1)**((n-1)/2)*Add(*[binomial(n, k)*
(-1)**k*sin((n - 2*k)*x) for k in range((n + 1)/2)])
elif n.is_even and isinstance(b, cos):
rv = 2**(1-n)*Add(*[binomial(n, k)*cos((n - 2*k)*x)
for k in range(n/2)])
elif n.is_even and isinstance(b, sin):
rv = 2**(1-n)*(-1)**(n/2)*Add(*[binomial(n, k)*
(-1)**k*cos((n - 2*k)*x) for k in range(n/2)])
if n.is_even:
rv += 2**(-n)*binomial(n, n/2)
return rv
return bottom_up(rv, f)
def L(rv):
"""Return count of trigonometric functions in expression.
Examples
========
>>> from sympy.simplify.fu import L
>>> from sympy.abc import x
>>> from sympy import cos, sin
>>> L(cos(x)+sin(x))
2
"""
return S(rv.count(TrigonometricFunction))
# ============== end of basic Fu-like tools =====================
if SYMPY_DEBUG:
(TR0, TR1, TR2, TR3, TR4, TR5, TR6, TR7, TR8, TR9, TR10, TR11, TR12, TR13,
TR2i, TRmorrie, TR14, TR15, TR16, TR12i, TR111, TR22
)= list(map(debug,
(TR0, TR1, TR2, TR3, TR4, TR5, TR6, TR7, TR8, TR9, TR10, TR11, TR12, TR13,
TR2i, TRmorrie, TR14, TR15, TR16, TR12i, TR111, TR22)))
# tuples are chains -- (f, g) -> lambda x: g(f(x))
# lists are choices -- [f, g] -> lambda x: min(f(x), g(x), key=objective)
CTR1 = [(TR5, TR0), (TR6, TR0), identity]
CTR2 = (TR11, [(TR5, TR0), (TR6, TR0), TR0])
CTR3 = [(TRmorrie, TR8, TR0), (TRmorrie, TR8, TR10i, TR0), identity]
CTR4 = [(TR4, TR10i), identity]
RL1 = (TR4, TR3, TR4, TR12, TR4, TR13, TR4, TR0)
# XXX it's a little unclear how this one is to be implemented
# see Fu paper of reference, page 7. What is the Union symbol referring to?
# The diagram shows all these as one chain of transformations, but the
# text refers to them being applied independently. Also, a break
# if L starts to increase has not been implemented.
RL2 = [
(TR4, TR3, TR10, TR4, TR3, TR11),
(TR5, TR7, TR11, TR4),
(CTR3, CTR1, TR9, CTR2, TR4, TR9, TR9, CTR4),
identity,
]
def fu(rv, measure=lambda x: (L(x), x.count_ops())):
"""Attempt to simplify expression by using transformation rules given
in the algorithm by Fu et al.
:func:`fu` will try to minimize the objective function ``measure``.
By default this first minimizes the number of trig terms and then minimizes
the number of total operations.
Examples
========
>>> from sympy.simplify.fu import fu
>>> from sympy import cos, sin, tan, pi, S, sqrt
>>> from sympy.abc import x, y, a, b
>>> fu(sin(50)**2 + cos(50)**2 + sin(pi/6))
3/2
>>> fu(sqrt(6)*cos(x) + sqrt(2)*sin(x))
2*sqrt(2)*sin(x + pi/3)
CTR1 example
>>> eq = sin(x)**4 - cos(y)**2 + sin(y)**2 + 2*cos(x)**2
>>> fu(eq)
cos(x)**4 - 2*cos(y)**2 + 2
CTR2 example
>>> fu(S.Half - cos(2*x)/2)
sin(x)**2
CTR3 example
>>> fu(sin(a)*(cos(b) - sin(b)) + cos(a)*(sin(b) + cos(b)))
sqrt(2)*sin(a + b + pi/4)
CTR4 example
>>> fu(sqrt(3)*cos(x)/2 + sin(x)/2)
sin(x + pi/3)
Example 1
>>> fu(1-sin(2*x)**2/4-sin(y)**2-cos(x)**4)
-cos(x)**2 + cos(y)**2
Example 2
>>> fu(cos(4*pi/9))
sin(pi/18)
>>> fu(cos(pi/9)*cos(2*pi/9)*cos(3*pi/9)*cos(4*pi/9))
1/16
Example 3
>>> fu(tan(7*pi/18)+tan(5*pi/18)-sqrt(3)*tan(5*pi/18)*tan(7*pi/18))
-sqrt(3)
Objective function example
>>> fu(sin(x)/cos(x)) # default objective function
tan(x)
>>> fu(sin(x)/cos(x), measure=lambda x: -x.count_ops()) # maximize op count
sin(x)/cos(x)
References
==========
.. [1] https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.657.2478&rep=rep1&type=pdf
"""
fRL1 = greedy(RL1, measure)
fRL2 = greedy(RL2, measure)
was = rv
rv = sympify(rv)
if not isinstance(rv, Expr):
return rv.func(*[fu(a, measure=measure) for a in rv.args])
rv = TR1(rv)
if rv.has(tan, cot):
rv1 = fRL1(rv)
if (measure(rv1) < measure(rv)):
rv = rv1
if rv.has(tan, cot):
rv = TR2(rv)
if rv.has(sin, cos):
rv1 = fRL2(rv)
rv2 = TR8(TRmorrie(rv1))
rv = min([was, rv, rv1, rv2], key=measure)
return min(TR2i(rv), rv, key=measure)
def process_common_addends(rv, do, key2=None, key1=True):
"""Apply ``do`` to addends of ``rv`` that (if ``key1=True``) share at least
a common absolute value of their coefficient and the value of ``key2`` when
applied to the argument. If ``key1`` is False ``key2`` must be supplied and
will be the only key applied.
"""
# collect by absolute value of coefficient and key2
absc = defaultdict(list)
if key1:
for a in rv.args:
c, a = a.as_coeff_Mul()
if c < 0:
c = -c
a = -a # put the sign on `a`
absc[(c, key2(a) if key2 else 1)].append(a)
elif key2:
for a in rv.args:
absc[(S.One, key2(a))].append(a)
else:
raise ValueError('must have at least one key')
args = []
hit = False
for k in absc:
v = absc[k]
c, _ = k
if len(v) > 1:
e = Add(*v, evaluate=False)
new = do(e)
if new != e:
e = new
hit = True
args.append(c*e)
else:
args.append(c*v[0])
if hit:
rv = Add(*args)
return rv
fufuncs = '''
TR0 TR1 TR2 TR3 TR4 TR5 TR6 TR7 TR8 TR9 TR10 TR10i TR11
TR12 TR13 L TR2i TRmorrie TR12i
TR14 TR15 TR16 TR111 TR22'''.split()
FU = dict(list(zip(fufuncs, list(map(locals().get, fufuncs)))))
def _roots():
global _ROOT2, _ROOT3, _invROOT3
_ROOT2, _ROOT3 = sqrt(2), sqrt(3)
_invROOT3 = 1/_ROOT3
_ROOT2 = None
def trig_split(a, b, two=False):
"""Return the gcd, s1, s2, a1, a2, bool where
If two is False (default) then::
a + b = gcd*(s1*f(a1) + s2*f(a2)) where f = cos if bool else sin
else:
if bool, a + b was +/- cos(a1)*cos(a2) +/- sin(a1)*sin(a2) and equals
n1*gcd*cos(a - b) if n1 == n2 else
n1*gcd*cos(a + b)
else a + b was +/- cos(a1)*sin(a2) +/- sin(a1)*cos(a2) and equals
n1*gcd*sin(a + b) if n1 = n2 else
n1*gcd*sin(b - a)
Examples
========
>>> from sympy.simplify.fu import trig_split
>>> from sympy.abc import x, y, z
>>> from sympy import cos, sin, sqrt
>>> trig_split(cos(x), cos(y))
(1, 1, 1, x, y, True)
>>> trig_split(2*cos(x), -2*cos(y))
(2, 1, -1, x, y, True)
>>> trig_split(cos(x)*sin(y), cos(y)*sin(y))
(sin(y), 1, 1, x, y, True)
>>> trig_split(cos(x), -sqrt(3)*sin(x), two=True)
(2, 1, -1, x, pi/6, False)
>>> trig_split(cos(x), sin(x), two=True)
(sqrt(2), 1, 1, x, pi/4, False)
>>> trig_split(cos(x), -sin(x), two=True)
(sqrt(2), 1, -1, x, pi/4, False)
>>> trig_split(sqrt(2)*cos(x), -sqrt(6)*sin(x), two=True)
(2*sqrt(2), 1, -1, x, pi/6, False)
>>> trig_split(-sqrt(6)*cos(x), -sqrt(2)*sin(x), two=True)
(-2*sqrt(2), 1, 1, x, pi/3, False)
>>> trig_split(cos(x)/sqrt(6), sin(x)/sqrt(2), two=True)
(sqrt(6)/3, 1, 1, x, pi/6, False)
>>> trig_split(-sqrt(6)*cos(x)*sin(y), -sqrt(2)*sin(x)*sin(y), two=True)
(-2*sqrt(2)*sin(y), 1, 1, x, pi/3, False)
>>> trig_split(cos(x), sin(x))
>>> trig_split(cos(x), sin(z))
>>> trig_split(2*cos(x), -sin(x))
>>> trig_split(cos(x), -sqrt(3)*sin(x))
>>> trig_split(cos(x)*cos(y), sin(x)*sin(z))
>>> trig_split(cos(x)*cos(y), sin(x)*sin(y))
>>> trig_split(-sqrt(6)*cos(x), sqrt(2)*sin(x)*sin(y), two=True)
"""
global _ROOT2, _ROOT3, _invROOT3
if _ROOT2 is None:
_roots()
a, b = [Factors(i) for i in (a, b)]
ua, ub = a.normal(b)
gcd = a.gcd(b).as_expr()
n1 = n2 = 1
if S.NegativeOne in ua.factors:
ua = ua.quo(S.NegativeOne)
n1 = -n1
elif S.NegativeOne in ub.factors:
ub = ub.quo(S.NegativeOne)
n2 = -n2
a, b = [i.as_expr() for i in (ua, ub)]
def pow_cos_sin(a, two):
"""Return ``a`` as a tuple (r, c, s) such that
``a = (r or 1)*(c or 1)*(s or 1)``.
Three arguments are returned (radical, c-factor, s-factor) as
long as the conditions set by ``two`` are met; otherwise None is
returned. If ``two`` is True there will be one or two non-None
values in the tuple: c and s or c and r or s and r or s or c with c
being a cosine function (if possible) else a sine, and s being a sine
function (if possible) else oosine. If ``two`` is False then there
will only be a c or s term in the tuple.
``two`` also require that either two cos and/or sin be present (with
the condition that if the functions are the same the arguments are
different or vice versa) or that a single cosine or a single sine
be present with an optional radical.
If the above conditions dictated by ``two`` are not met then None
is returned.
"""
c = s = None
co = S.One
if a.is_Mul:
co, a = a.as_coeff_Mul()
if len(a.args) > 2 or not two:
return None
if a.is_Mul:
args = list(a.args)
else:
args = [a]
a = args.pop(0)
if isinstance(a, cos):
c = a
elif isinstance(a, sin):
s = a
elif a.is_Pow and a.exp is S.Half: # autoeval doesn't allow -1/2
co *= a
else:
return None
if args:
b = args[0]
if isinstance(b, cos):
if c:
s = b
else:
c = b
elif isinstance(b, sin):
if s:
c = b
else:
s = b
elif b.is_Pow and b.exp is S.Half:
co *= b
else:
return None
return co if co is not S.One else None, c, s
elif isinstance(a, cos):
c = a
elif isinstance(a, sin):
s = a
if c is None and s is None:
return
co = co if co is not S.One else None
return co, c, s
# get the parts
m = pow_cos_sin(a, two)
if m is None:
return
coa, ca, sa = m
m = pow_cos_sin(b, two)
if m is None:
return
cob, cb, sb = m
# check them
if (not ca) and cb or ca and isinstance(ca, sin):
coa, ca, sa, cob, cb, sb = cob, cb, sb, coa, ca, sa
n1, n2 = n2, n1
if not two: # need cos(x) and cos(y) or sin(x) and sin(y)
c = ca or sa
s = cb or sb
if not isinstance(c, s.func):
return None
return gcd, n1, n2, c.args[0], s.args[0], isinstance(c, cos)
else:
if not coa and not cob:
if (ca and cb and sa and sb):
if isinstance(ca, sa.func) is not isinstance(cb, sb.func):
return
args = {j.args for j in (ca, sa)}
if not all(i.args in args for i in (cb, sb)):
return
return gcd, n1, n2, ca.args[0], sa.args[0], isinstance(ca, sa.func)
if ca and sa or cb and sb or \
two and (ca is None and sa is None or cb is None and sb is None):
return
c = ca or sa
s = cb or sb
if c.args != s.args:
return
if not coa:
coa = S.One
if not cob:
cob = S.One
if coa is cob:
gcd *= _ROOT2
return gcd, n1, n2, c.args[0], pi/4, False
elif coa/cob == _ROOT3:
gcd *= 2*cob
return gcd, n1, n2, c.args[0], pi/3, False
elif coa/cob == _invROOT3:
gcd *= 2*coa
return gcd, n1, n2, c.args[0], pi/6, False
def as_f_sign_1(e):
"""If ``e`` is a sum that can be written as ``g*(a + s)`` where
``s`` is ``+/-1``, return ``g``, ``a``, and ``s`` where ``a`` does
not have a leading negative coefficient.
Examples
========
>>> from sympy.simplify.fu import as_f_sign_1
>>> from sympy.abc import x
>>> as_f_sign_1(x + 1)
(1, x, 1)
>>> as_f_sign_1(x - 1)
(1, x, -1)
>>> as_f_sign_1(-x + 1)
(-1, x, -1)
>>> as_f_sign_1(-x - 1)
(-1, x, 1)
>>> as_f_sign_1(2*x + 2)
(2, x, 1)
"""
if not e.is_Add or len(e.args) != 2:
return
# exact match
a, b = e.args
if a in (S.NegativeOne, S.One):
g = S.One
if b.is_Mul and b.args[0].is_Number and b.args[0] < 0:
a, b = -a, -b
g = -g
return g, b, a
# gcd match
a, b = [Factors(i) for i in e.args]
ua, ub = a.normal(b)
gcd = a.gcd(b).as_expr()
if S.NegativeOne in ua.factors:
ua = ua.quo(S.NegativeOne)
n1 = -1
n2 = 1
elif S.NegativeOne in ub.factors:
ub = ub.quo(S.NegativeOne)
n1 = 1
n2 = -1
else:
n1 = n2 = 1
a, b = [i.as_expr() for i in (ua, ub)]
if a is S.One:
a, b = b, a
n1, n2 = n2, n1
if n1 == -1:
gcd = -gcd
n2 = -n2
if b is S.One:
return gcd, a, n2
def _osborne(e, d):
"""Replace all hyperbolic functions with trig functions using
the Osborne rule.
Notes
=====
``d`` is a dummy variable to prevent automatic evaluation
of trigonometric/hyperbolic functions.
References
==========
.. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
"""
def f(rv):
if not isinstance(rv, HyperbolicFunction):
return rv
a = rv.args[0]
a = a*d if not a.is_Add else Add._from_args([i*d for i in a.args])
if isinstance(rv, sinh):
return I*sin(a)
elif isinstance(rv, cosh):
return cos(a)
elif isinstance(rv, tanh):
return I*tan(a)
elif isinstance(rv, coth):
return cot(a)/I
elif isinstance(rv, sech):
return sec(a)
elif isinstance(rv, csch):
return csc(a)/I
else:
raise NotImplementedError('unhandled %s' % rv.func)
return bottom_up(e, f)
def _osbornei(e, d):
"""Replace all trig functions with hyperbolic functions using
the Osborne rule.
Notes
=====
``d`` is a dummy variable to prevent automatic evaluation
of trigonometric/hyperbolic functions.
References
==========
.. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
"""
def f(rv):
if not isinstance(rv, TrigonometricFunction):
return rv
const, x = rv.args[0].as_independent(d, as_Add=True)
a = x.xreplace({d: S.One}) + const*I
if isinstance(rv, sin):
return sinh(a)/I
elif isinstance(rv, cos):
return cosh(a)
elif isinstance(rv, tan):
return tanh(a)/I
elif isinstance(rv, cot):
return coth(a)*I
elif isinstance(rv, sec):
return sech(a)
elif isinstance(rv, csc):
return csch(a)*I
else:
raise NotImplementedError('unhandled %s' % rv.func)
return bottom_up(e, f)
def hyper_as_trig(rv):
"""Return an expression containing hyperbolic functions in terms
of trigonometric functions. Any trigonometric functions initially
present are replaced with Dummy symbols and the function to undo
the masking and the conversion back to hyperbolics is also returned. It
should always be true that::
t, f = hyper_as_trig(expr)
expr == f(t)
Examples
========
>>> from sympy.simplify.fu import hyper_as_trig, fu
>>> from sympy.abc import x
>>> from sympy import cosh, sinh
>>> eq = sinh(x)**2 + cosh(x)**2
>>> t, f = hyper_as_trig(eq)
>>> f(fu(t))
cosh(2*x)
References
==========
.. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
"""
from sympy.simplify.simplify import signsimp
from sympy.simplify.radsimp import collect
# mask off trig functions
trigs = rv.atoms(TrigonometricFunction)
reps = [(t, Dummy()) for t in trigs]
masked = rv.xreplace(dict(reps))
# get inversion substitutions in place
reps = [(v, k) for k, v in reps]
d = Dummy()
return _osborne(masked, d), lambda x: collect(signsimp(
_osbornei(x, d).xreplace(dict(reps))), S.ImaginaryUnit)
def sincos_to_sum(expr):
"""Convert products and powers of sin and cos to sums.
Explanation
===========
Applied power reduction TRpower first, then expands products, and
converts products to sums with TR8.
Examples
========
>>> from sympy.simplify.fu import sincos_to_sum
>>> from sympy.abc import x
>>> from sympy import cos, sin
>>> sincos_to_sum(16*sin(x)**3*cos(2*x)**2)
7*sin(x) - 5*sin(3*x) + 3*sin(5*x) - sin(7*x)
"""
if not expr.has(cos, sin):
return expr
else:
return TR8(expand_mul(TRpower(expr)))
|
15a9e1f5f711de2ba02ce0d739745f6d4f6c730ea9ee0f376ecf910fa1924b4e | """Predefined R^n manifolds together with common coord. systems.
Coordinate systems are predefined as well as the transformation laws between
them.
Coordinate functions can be accessed as attributes of the manifold (eg `R2.x`),
as attributes of the coordinate systems (eg `R2_r.x` and `R2_p.theta`), or by
using the usual `coord_sys.coord_function(index, name)` interface.
"""
from typing import Any
import warnings
from sympy import sqrt, atan2, acos, sin, cos, symbols, Dummy
from .diffgeom import Manifold, Patch, CoordSystem
__all__ = [
'R2', 'R2_origin', 'relations_2d', 'R2_r', 'R2_p',
'R3', 'R3_origin', 'relations_3d', 'R3_r', 'R3_c', 'R3_s'
]
###############################################################################
# R2
###############################################################################
R2 = Manifold('R^2', 2) # type: Any
R2_origin = Patch('origin', R2) # type: Any
x, y = symbols('x y', real=True)
r, theta = symbols('rho theta', nonnegative=True)
relations_2d = {
('rectangular', 'polar'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))],
('polar', 'rectangular'): [(r, theta), (r*cos(theta), r*sin(theta))],
}
R2_r = CoordSystem('rectangular', R2_origin, (x, y), relations_2d) # type: Any
R2_p = CoordSystem('polar', R2_origin, (r, theta), relations_2d) # type: Any
# support deprecated feature
with warnings.catch_warnings():
warnings.simplefilter("ignore")
x, y, r, theta = symbols('x y r theta', cls=Dummy)
R2_r.connect_to(R2_p, [x, y],
[sqrt(x**2 + y**2), atan2(y, x)],
inverse=False, fill_in_gaps=False)
R2_p.connect_to(R2_r, [r, theta],
[r*cos(theta), r*sin(theta)],
inverse=False, fill_in_gaps=False)
# Defining the basis coordinate functions and adding shortcuts for them to the
# manifold and the patch.
R2.x, R2.y = R2_origin.x, R2_origin.y = R2_r.x, R2_r.y = R2_r.coord_functions()
R2.r, R2.theta = R2_origin.r, R2_origin.theta = R2_p.r, R2_p.theta = R2_p.coord_functions()
# Defining the basis vector fields and adding shortcuts for them to the
# manifold and the patch.
R2.e_x, R2.e_y = R2_origin.e_x, R2_origin.e_y = R2_r.e_x, R2_r.e_y = R2_r.base_vectors()
R2.e_r, R2.e_theta = R2_origin.e_r, R2_origin.e_theta = R2_p.e_r, R2_p.e_theta = R2_p.base_vectors()
# Defining the basis oneform fields and adding shortcuts for them to the
# manifold and the patch.
R2.dx, R2.dy = R2_origin.dx, R2_origin.dy = R2_r.dx, R2_r.dy = R2_r.base_oneforms()
R2.dr, R2.dtheta = R2_origin.dr, R2_origin.dtheta = R2_p.dr, R2_p.dtheta = R2_p.base_oneforms()
###############################################################################
# R3
###############################################################################
R3 = Manifold('R^3', 3) # type: Any
R3_origin = Patch('origin', R3) # type: Any
x, y, z = symbols('x y z', real=True)
rho, psi, r, theta, phi = symbols('rho psi r theta phi', nonnegative=True)
relations_3d = {
('rectangular', 'cylindrical'): [(x, y, z),
(sqrt(x**2 + y**2), atan2(y, x), z)],
('cylindrical', 'rectangular'): [(rho, psi, z),
(rho*cos(psi), rho*sin(psi), z)],
('rectangular', 'spherical'): [(x, y, z),
(sqrt(x**2 + y**2 + z**2),
acos(z/sqrt(x**2 + y**2 + z**2)),
atan2(y, x))],
('spherical', 'rectangular'): [(r, theta, phi),
(r*sin(theta)*cos(phi),
r*sin(theta)*sin(phi),
r*cos(theta))],
('cylindrical', 'spherical'): [(rho, psi, z),
(sqrt(rho**2 + z**2),
acos(z/sqrt(rho**2 + z**2)),
psi)],
('spherical', 'cylindrical'): [(r, theta, phi),
(r*sin(theta), phi, r*cos(theta))],
}
R3_r = CoordSystem('rectangular', R3_origin, (x, y, z), relations_3d) # type: Any
R3_c = CoordSystem('cylindrical', R3_origin, (rho, psi, z), relations_3d) # type: Any
R3_s = CoordSystem('spherical', R3_origin, (r, theta, phi), relations_3d) # type: Any
# support deprecated feature
with warnings.catch_warnings():
warnings.simplefilter("ignore")
x, y, z, rho, psi, r, theta, phi = symbols('x y z rho psi r theta phi', cls=Dummy)
R3_r.connect_to(R3_c, [x, y, z],
[sqrt(x**2 + y**2), atan2(y, x), z],
inverse=False, fill_in_gaps=False)
R3_c.connect_to(R3_r, [rho, psi, z],
[rho*cos(psi), rho*sin(psi), z],
inverse=False, fill_in_gaps=False)
## rectangular <-> spherical
R3_r.connect_to(R3_s, [x, y, z],
[sqrt(x**2 + y**2 + z**2), acos(z/
sqrt(x**2 + y**2 + z**2)), atan2(y, x)],
inverse=False, fill_in_gaps=False)
R3_s.connect_to(R3_r, [r, theta, phi],
[r*sin(theta)*cos(phi), r*sin(
theta)*sin(phi), r*cos(theta)],
inverse=False, fill_in_gaps=False)
## cylindrical <-> spherical
R3_c.connect_to(R3_s, [rho, psi, z],
[sqrt(rho**2 + z**2), acos(z/sqrt(rho**2 + z**2)), psi],
inverse=False, fill_in_gaps=False)
R3_s.connect_to(R3_c, [r, theta, phi],
[r*sin(theta), phi, r*cos(theta)],
inverse=False, fill_in_gaps=False)
# Defining the basis coordinate functions.
R3_r.x, R3_r.y, R3_r.z = R3_r.coord_functions()
R3_c.rho, R3_c.psi, R3_c.z = R3_c.coord_functions()
R3_s.r, R3_s.theta, R3_s.phi = R3_s.coord_functions()
# Defining the basis vector fields.
R3_r.e_x, R3_r.e_y, R3_r.e_z = R3_r.base_vectors()
R3_c.e_rho, R3_c.e_psi, R3_c.e_z = R3_c.base_vectors()
R3_s.e_r, R3_s.e_theta, R3_s.e_phi = R3_s.base_vectors()
# Defining the basis oneform fields.
R3_r.dx, R3_r.dy, R3_r.dz = R3_r.base_oneforms()
R3_c.drho, R3_c.dpsi, R3_c.dz = R3_c.base_oneforms()
R3_s.dr, R3_s.dtheta, R3_s.dphi = R3_s.base_oneforms()
|
11e1e67a3f3d297bf27d1a0770a8c266963787827889eae9d54c66ea6a7d6c65 | from typing import Any, Set
from functools import reduce
from itertools import permutations
from sympy.combinatorics import Permutation
from sympy.core import (
Basic, Expr, Function, diff,
Pow, Mul, Add, Lambda, S, Tuple, Dict
)
from sympy.core.cache import cacheit
from sympy.core.symbol import Symbol, Dummy
from sympy.core.symbol import Str
from sympy.core.sympify import _sympify
from sympy.functions import factorial
from sympy.matrices import ImmutableDenseMatrix as Matrix
from sympy.simplify import simplify
from sympy.solvers import solve
from sympy.utilities.exceptions import SymPyDeprecationWarning
# TODO you are a bit excessive in the use of Dummies
# TODO dummy point, literal field
# TODO too often one needs to call doit or simplify on the output, check the
# tests and find out why
from sympy.tensor.array import ImmutableDenseNDimArray
class Manifold(Basic):
"""
A mathematical manifold.
Explanation
===========
A manifold is a topological space that locally resembles
Euclidean space near each point [1].
This class does not provide any means to study the topological
characteristics of the manifold that it represents, though.
Parameters
==========
name : str
The name of the manifold.
dim : int
The dimension of the manifold.
Examples
========
>>> from sympy.diffgeom import Manifold
>>> m = Manifold('M', 2)
>>> m
M
>>> m.dim
2
References
==========
.. [1] https://en.wikipedia.org/wiki/Manifold
"""
def __new__(cls, name, dim, **kwargs):
if not isinstance(name, Str):
name = Str(name)
dim = _sympify(dim)
obj = super().__new__(cls, name, dim)
obj.patches = _deprecated_list(
"Manifold.patches",
"external container for registry",
19321,
"1.7",
[]
)
return obj
@property
def name(self):
return self.args[0]
@property
def dim(self):
return self.args[1]
class Patch(Basic):
"""
A patch on a manifold.
Explanation
===========
Coordinate patch, or patch in short, is a simply-connected open set around
a point in the manifold [1]. On a manifold one can have many patches that
do not always include the whole manifold. On these patches coordinate
charts can be defined that permit the parameterization of any point on the
patch in terms of a tuple of real numbers (the coordinates).
This class does not provide any means to study the topological
characteristics of the patch that it represents.
Parameters
==========
name : str
The name of the patch.
manifold : Manifold
The manifold on which the patch is defined.
Examples
========
>>> from sympy.diffgeom import Manifold, Patch
>>> m = Manifold('M', 2)
>>> p = Patch('P', m)
>>> p
P
>>> p.dim
2
References
==========
.. [1] G. Sussman, J. Wisdom, W. Farr, Functional Differential Geometry
(2013)
"""
def __new__(cls, name, manifold, **kwargs):
if not isinstance(name, Str):
name = Str(name)
obj = super().__new__(cls, name, manifold)
obj.manifold.patches.append(obj) # deprecated
obj.coord_systems = _deprecated_list(
"Patch.coord_systems",
"external container for registry",
19321,
"1.7",
[]
)
return obj
@property
def name(self):
return self.args[0]
@property
def manifold(self):
return self.args[1]
@property
def dim(self):
return self.manifold.dim
class CoordSystem(Basic):
"""
A coordinate system defined on the patch.
Explanation
===========
Coordinate system is a system that uses one or more coordinates to uniquely
determine the position of the points or other geometric elements on a
manifold [1].
By passing ``Symbols`` to *symbols* parameter, user can define the name and
assumptions of coordinate symbols of the coordinate system. If not passed,
these symbols are generated automatically and are assumed to be real valued.
By passing *relations* parameter, user can define the tranform relations of
coordinate systems. Inverse transformation and indirect transformation can
be found automatically. If this parameter is not passed, coordinate
transformation cannot be done.
Parameters
==========
name : str
The name of the coordinate system.
patch : Patch
The patch where the coordinate system is defined.
symbols : list of Symbols, optional
Defines the names and assumptions of coordinate symbols.
relations : dict, optional
Key is a tuple of two strings, who are the names of the systems where
the coordinates transform from and transform to.
Value is a tuple of the symbols before transformation and a tuple of
the expressions after transformation.
Examples
========
We define two-dimensional Cartesian coordinate system and polar coordinate
system.
>>> from sympy import symbols, pi, sqrt, atan2, cos, sin
>>> from sympy.diffgeom import Manifold, Patch, CoordSystem
>>> m = Manifold('M', 2)
>>> p = Patch('P', m)
>>> x, y = symbols('x y', real=True)
>>> r, theta = symbols('r theta', nonnegative=True)
>>> relation_dict = {
... ('Car2D', 'Pol'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))],
... ('Pol', 'Car2D'): [(r, theta), (r*cos(theta), r*sin(theta))]
... }
>>> Car2D = CoordSystem('Car2D', p, (x, y), relation_dict)
>>> Pol = CoordSystem('Pol', p, (r, theta), relation_dict)
``symbols`` property returns ``CoordinateSymbol`` instances. These symbols
are not same with the symbols used to construct the coordinate system.
>>> Car2D
Car2D
>>> Car2D.dim
2
>>> Car2D.symbols
(x, y)
>>> _[0].func
<class 'sympy.diffgeom.diffgeom.CoordinateSymbol'>
``transformation()`` method returns the transformation function from
one coordinate system to another. ``transform()`` method returns the
transformed coordinates.
>>> Car2D.transformation(Pol)
Lambda((x, y), Matrix([
[sqrt(x**2 + y**2)],
[ atan2(y, x)]]))
>>> Car2D.transform(Pol)
Matrix([
[sqrt(x**2 + y**2)],
[ atan2(y, x)]])
>>> Car2D.transform(Pol, [1, 2])
Matrix([
[sqrt(5)],
[atan(2)]])
``jacobian()`` method returns the Jacobian matrix of coordinate
transformation between two systems. ``jacobian_determinant()`` method
returns the Jacobian determinant of coordinate transformation between two
systems.
>>> Pol.jacobian(Car2D)
Matrix([
[cos(theta), -r*sin(theta)],
[sin(theta), r*cos(theta)]])
>>> Pol.jacobian(Car2D, [1, pi/2])
Matrix([
[0, -1],
[1, 0]])
>>> Car2D.jacobian_determinant(Pol)
1/sqrt(x**2 + y**2)
>>> Car2D.jacobian_determinant(Pol, [1,0])
1
References
==========
.. [1] https://en.wikipedia.org/wiki/Coordinate_system
"""
def __new__(cls, name, patch, symbols=None, relations={}, **kwargs):
if not isinstance(name, Str):
name = Str(name)
# canonicallize the symbols
if symbols is None:
names = kwargs.get('names', None)
if names is None:
symbols = Tuple(
*[Symbol('%s_%s' % (name.name, i), real=True)
for i in range(patch.dim)]
)
else:
SymPyDeprecationWarning(
feature="Class signature 'names' of CoordSystem",
useinstead="class signature 'symbols'",
issue=19321,
deprecated_since_version="1.7"
).warn()
symbols = Tuple(
*[Symbol(n, real=True) for n in names]
)
else:
syms = []
for s in symbols:
if isinstance(s, Symbol):
syms.append(Symbol(s.name, **s._assumptions.generator))
elif isinstance(s, str):
SymPyDeprecationWarning(
feature="Passing str as coordinate symbol's name",
useinstead="Symbol which contains the name and assumption for coordinate symbol",
issue=19321,
deprecated_since_version="1.7"
).warn()
syms.append(Symbol(s, real=True))
symbols = Tuple(*syms)
# canonicallize the relations
rel_temp = {}
for k,v in relations.items():
s1, s2 = k
if not isinstance(s1, Str):
s1 = Str(s1)
if not isinstance(s2, Str):
s2 = Str(s2)
key = Tuple(s1, s2)
# Old version used Lambda as a value.
if isinstance(v, Lambda):
v = (tuple(v.signature), tuple(v.expr))
else:
v = (tuple(v[0]), tuple(v[1]))
rel_temp[key] = v
relations = Dict(rel_temp)
# construct the object
obj = super().__new__(cls, name, patch, symbols, relations)
# Add deprecated attributes
obj.transforms = _deprecated_dict(
"Mutable CoordSystem.transforms",
"'relations' parameter in class signature",
19321,
"1.7",
{}
)
obj._names = [str(n) for n in symbols]
obj.patch.coord_systems.append(obj) # deprecated
obj._dummies = [Dummy(str(n)) for n in symbols] # deprecated
obj._dummy = Dummy()
return obj
@property
def name(self):
return self.args[0]
@property
def patch(self):
return self.args[1]
@property
def manifold(self):
return self.patch.manifold
@property
def symbols(self):
return tuple(CoordinateSymbol(self, i, **s._assumptions.generator)
for i,s in enumerate(self.args[2]))
@property
def relations(self):
return self.args[3]
@property
def dim(self):
return self.patch.dim
##########################################################################
# Finding transformation relation
##########################################################################
def transformation(self, sys):
"""
Return coordinate transformation function from *self* to *sys*.
Parameters
==========
sys : CoordSystem
Returns
=======
sympy.Lambda
Examples
========
>>> from sympy.diffgeom.rn import R2_r, R2_p
>>> R2_r.transformation(R2_p)
Lambda((x, y), Matrix([
[sqrt(x**2 + y**2)],
[ atan2(y, x)]]))
"""
signature = self.args[2]
key = Tuple(self.name, sys.name)
if self == sys:
expr = Matrix(self.symbols)
elif key in self.relations:
expr = Matrix(self.relations[key][1])
elif key[::-1] in self.relations:
expr = Matrix(self._inverse_transformation(sys, self))
else:
expr = Matrix(self._indirect_transformation(self, sys))
return Lambda(signature, expr)
@staticmethod
def _solve_inverse(sym1, sym2, exprs, sys1_name, sys2_name):
ret = solve(
[t[0] - t[1] for t in zip(sym2, exprs)],
list(sym1), dict=True)
if len(ret) == 0:
temp = "Cannot solve inverse relation from {} to {}."
raise NotImplementedError(temp.format(sys1_name, sys2_name))
elif len(ret) > 1:
temp = "Obtained multiple inverse relation from {} to {}."
raise ValueError(temp.format(sys1_name, sys2_name))
return ret[0]
@classmethod
def _inverse_transformation(cls, sys1, sys2):
# Find the transformation relation from sys2 to sys1
forward = sys1.transform(sys2)
inv_results = cls._solve_inverse(sys1.symbols, sys2.symbols, forward,
sys1.name, sys2.name)
signature = tuple(sys1.symbols)
return [inv_results[s] for s in signature]
@classmethod
@cacheit
def _indirect_transformation(cls, sys1, sys2):
# Find the transformation relation between two indirectly connected
# coordinate systems
rel = sys1.relations
path = cls._dijkstra(sys1, sys2)
transforms = []
for s1, s2 in zip(path, path[1:]):
if (s1, s2) in rel:
transforms.append(rel[(s1, s2)])
else:
sym2, inv_exprs = rel[(s2, s1)]
sym1 = tuple(Dummy() for i in sym2)
ret = cls._solve_inverse(sym2, sym1, inv_exprs, s2, s1)
ret = tuple(ret[s] for s in sym2)
transforms.append((sym1, ret))
syms = sys1.args[2]
exprs = syms
for newsyms, newexprs in transforms:
exprs = tuple(e.subs(zip(newsyms, exprs)) for e in newexprs)
return exprs
@staticmethod
def _dijkstra(sys1, sys2):
# Use Dijkstra algorithm to find the shortest path between two indirectly-connected
# coordinate systems
# return value is the list of the names of the systems.
relations = sys1.relations
graph = {}
for s1, s2 in relations.keys():
if s1 not in graph:
graph[s1] = {s2}
else:
graph[s1].add(s2)
if s2 not in graph:
graph[s2] = {s1}
else:
graph[s2].add(s1)
path_dict = {sys:[0, [], 0] for sys in graph} # minimum distance, path, times of visited
def visit(sys):
path_dict[sys][2] = 1
for newsys in graph[sys]:
distance = path_dict[sys][0] + 1
if path_dict[newsys][0] >= distance or not path_dict[newsys][1]:
path_dict[newsys][0] = distance
path_dict[newsys][1] = [i for i in path_dict[sys][1]]
path_dict[newsys][1].append(sys)
visit(sys1.name)
while True:
min_distance = max(path_dict.values(), key=lambda x:x[0])[0]
newsys = None
for sys, lst in path_dict.items():
if 0 < lst[0] <= min_distance and not lst[2]:
min_distance = lst[0]
newsys = sys
if newsys is None:
break
visit(newsys)
result = path_dict[sys2.name][1]
result.append(sys2.name)
if result == [sys2.name]:
raise KeyError("Two coordinate systems are not connected.")
return result
def connect_to(self, to_sys, from_coords, to_exprs, inverse=True, fill_in_gaps=False):
SymPyDeprecationWarning(
feature="CoordSystem.connect_to",
useinstead="new instance generated with new 'transforms' parameter",
issue=19321,
deprecated_since_version="1.7"
).warn()
from_coords, to_exprs = dummyfy(from_coords, to_exprs)
self.transforms[to_sys] = Matrix(from_coords), Matrix(to_exprs)
if inverse:
to_sys.transforms[self] = self._inv_transf(from_coords, to_exprs)
if fill_in_gaps:
self._fill_gaps_in_transformations()
@staticmethod
def _inv_transf(from_coords, to_exprs):
# Will be removed when connect_to is removed
inv_from = [i.as_dummy() for i in from_coords]
inv_to = solve(
[t[0] - t[1] for t in zip(inv_from, to_exprs)],
list(from_coords), dict=True)[0]
inv_to = [inv_to[fc] for fc in from_coords]
return Matrix(inv_from), Matrix(inv_to)
@staticmethod
def _fill_gaps_in_transformations():
# Will be removed when connect_to is removed
raise NotImplementedError
##########################################################################
# Coordinate transformations
##########################################################################
def transform(self, sys, coordinates=None):
"""
Return the result of coordinate transformation from *self* to *sys*.
If coordinates are not given, coordinate symbols of *self* are used.
Parameters
==========
sys : CoordSystem
coordinates : Any iterable, optional.
Returns
=======
sympy.ImmutableDenseMatrix containing CoordinateSymbol
Examples
========
>>> from sympy.diffgeom.rn import R2_r, R2_p
>>> R2_r.transform(R2_p)
Matrix([
[sqrt(x**2 + y**2)],
[ atan2(y, x)]])
>>> R2_r.transform(R2_p, [0, 1])
Matrix([
[ 1],
[pi/2]])
"""
if coordinates is None:
coordinates = self.symbols
if self != sys:
transf = self.transformation(sys)
coordinates = transf(*coordinates)
else:
coordinates = Matrix(coordinates)
return coordinates
def coord_tuple_transform_to(self, to_sys, coords):
"""Transform ``coords`` to coord system ``to_sys``."""
SymPyDeprecationWarning(
feature="CoordSystem.coord_tuple_transform_to",
useinstead="CoordSystem.transform",
issue=19321,
deprecated_since_version="1.7"
).warn()
coords = Matrix(coords)
if self != to_sys:
transf = self.transforms[to_sys]
coords = transf[1].subs(list(zip(transf[0], coords)))
return coords
def jacobian(self, sys, coordinates=None):
"""
Return the jacobian matrix of a transformation on given coordinates.
If coordinates are not given, coordinate symbols of *self* are used.
Parameters
==========
sys : CoordSystem
coordinates : Any iterable, optional.
Returns
=======
sympy.ImmutableDenseMatrix
Examples
========
>>> from sympy.diffgeom.rn import R2_r, R2_p
>>> R2_p.jacobian(R2_r)
Matrix([
[cos(theta), -rho*sin(theta)],
[sin(theta), rho*cos(theta)]])
>>> R2_p.jacobian(R2_r, [1, 0])
Matrix([
[1, 0],
[0, 1]])
"""
result = self.transform(sys).jacobian(self.symbols)
if coordinates is not None:
result = result.subs(list(zip(self.symbols, coordinates)))
return result
jacobian_matrix = jacobian
def jacobian_determinant(self, sys, coordinates=None):
"""
Return the jacobian determinant of a transformation on given
coordinates. If coordinates are not given, coordinate symbols of *self*
are used.
Parameters
==========
sys : CoordSystem
coordinates : Any iterable, optional.
Returns
=======
sympy.Expr
Examples
========
>>> from sympy.diffgeom.rn import R2_r, R2_p
>>> R2_r.jacobian_determinant(R2_p)
1/sqrt(x**2 + y**2)
>>> R2_r.jacobian_determinant(R2_p, [1, 0])
1
"""
return self.jacobian(sys, coordinates).det()
##########################################################################
# Points
##########################################################################
def point(self, coords):
"""Create a ``Point`` with coordinates given in this coord system."""
return Point(self, coords)
def point_to_coords(self, point):
"""Calculate the coordinates of a point in this coord system."""
return point.coords(self)
##########################################################################
# Base fields.
##########################################################################
def base_scalar(self, coord_index):
"""Return ``BaseScalarField`` that takes a point and returns one of the coordinates."""
return BaseScalarField(self, coord_index)
coord_function = base_scalar
def base_scalars(self):
"""Returns a list of all coordinate functions.
For more details see the ``base_scalar`` method of this class."""
return [self.base_scalar(i) for i in range(self.dim)]
coord_functions = base_scalars
def base_vector(self, coord_index):
"""Return a basis vector field.
The basis vector field for this coordinate system. It is also an
operator on scalar fields."""
return BaseVectorField(self, coord_index)
def base_vectors(self):
"""Returns a list of all base vectors.
For more details see the ``base_vector`` method of this class."""
return [self.base_vector(i) for i in range(self.dim)]
def base_oneform(self, coord_index):
"""Return a basis 1-form field.
The basis one-form field for this coordinate system. It is also an
operator on vector fields."""
return Differential(self.coord_function(coord_index))
def base_oneforms(self):
"""Returns a list of all base oneforms.
For more details see the ``base_oneform`` method of this class."""
return [self.base_oneform(i) for i in range(self.dim)]
class CoordinateSymbol(Symbol):
"""A symbol which denotes an abstract value of i-th coordinate of
the coordinate system with given context.
Explanation
===========
Each coordinates in coordinate system are represented by unique symbol,
such as x, y, z in Cartesian coordinate system.
You may not construct this class directly. Instead, use `symbols` method
of CoordSystem.
Parameters
==========
coord_sys : CoordSystem
index : integer
Examples
========
>>> from sympy import symbols
>>> from sympy.diffgeom import Manifold, Patch, CoordSystem
>>> m = Manifold('M', 2)
>>> p = Patch('P', m)
>>> _x, _y = symbols('x y', nonnegative=True)
>>> C = CoordSystem('C', p, [_x, _y])
>>> x, y = C.symbols
>>> x.name
'x'
>>> x.coord_sys == C
True
>>> x.index
0
>>> x.is_nonnegative
True
"""
def __new__(cls, coord_sys, index, **assumptions):
name = coord_sys.args[2][index].name
obj = super().__new__(cls, name, **assumptions)
obj.coord_sys = coord_sys
obj.index = index
return obj
def __getnewargs__(self):
return (self.coord_sys, self.index)
def _hashable_content(self):
return (
self.coord_sys, self.index
) + tuple(sorted(self.assumptions0.items()))
class Point(Basic):
"""Point defined in a coordinate system.
Explanation
===========
Mathematically, point is defined in the manifold and does not have any coordinates
by itself. Coordinate system is what imbues the coordinates to the point by coordinate
chart. However, due to the difficulty of realizing such logic, you must supply
a coordinate system and coordinates to define a Point here.
The usage of this object after its definition is independent of the
coordinate system that was used in order to define it, however due to
limitations in the simplification routines you can arrive at complicated
expressions if you use inappropriate coordinate systems.
Parameters
==========
coord_sys : CoordSystem
coords : list
The coordinates of the point.
Examples
========
>>> from sympy import pi
>>> from sympy.diffgeom import Point
>>> from sympy.diffgeom.rn import R2, R2_r, R2_p
>>> rho, theta = R2_p.symbols
>>> p = Point(R2_p, [rho, 3*pi/4])
>>> p.manifold == R2
True
>>> p.coords()
Matrix([
[ rho],
[3*pi/4]])
>>> p.coords(R2_r)
Matrix([
[-sqrt(2)*rho/2],
[ sqrt(2)*rho/2]])
"""
def __new__(cls, coord_sys, coords, **kwargs):
coords = Matrix(coords)
obj = super().__new__(cls, coord_sys, coords)
obj._coord_sys = coord_sys
obj._coords = coords
return obj
@property
def patch(self):
return self._coord_sys.patch
@property
def manifold(self):
return self._coord_sys.manifold
@property
def dim(self):
return self.manifold.dim
def coords(self, sys=None):
"""
Coordinates of the point in given coordinate system. If coordinate system
is not passed, it returns the coordinates in the coordinate system in which
the poin was defined.
"""
if sys is None:
return self._coords
else:
return self._coord_sys.transform(sys, self._coords)
@property
def free_symbols(self):
return self._coords.free_symbols
class BaseScalarField(Expr):
"""Base scalar field over a manifold for a given coordinate system.
Explanation
===========
A scalar field takes a point as an argument and returns a scalar.
A base scalar field of a coordinate system takes a point and returns one of
the coordinates of that point in the coordinate system in question.
To define a scalar field you need to choose the coordinate system and the
index of the coordinate.
The use of the scalar field after its definition is independent of the
coordinate system in which it was defined, however due to limitations in
the simplification routines you may arrive at more complicated
expression if you use unappropriate coordinate systems.
You can build complicated scalar fields by just building up SymPy
expressions containing ``BaseScalarField`` instances.
Parameters
==========
coord_sys : CoordSystem
index : integer
Examples
========
>>> from sympy import Function, pi
>>> from sympy.diffgeom import BaseScalarField
>>> from sympy.diffgeom.rn import R2_r, R2_p
>>> rho, _ = R2_p.symbols
>>> point = R2_p.point([rho, 0])
>>> fx, fy = R2_r.base_scalars()
>>> ftheta = BaseScalarField(R2_r, 1)
>>> fx(point)
rho
>>> fy(point)
0
>>> (fx**2+fy**2).rcall(point)
rho**2
>>> g = Function('g')
>>> fg = g(ftheta-pi)
>>> fg.rcall(point)
g(-pi)
"""
is_commutative = True
def __new__(cls, coord_sys, index, **kwargs):
index = _sympify(index)
obj = super().__new__(cls, coord_sys, index)
obj._coord_sys = coord_sys
obj._index = index
return obj
@property
def coord_sys(self):
return self.args[0]
@property
def index(self):
return self.args[1]
@property
def patch(self):
return self.coord_sys.patch
@property
def manifold(self):
return self.coord_sys.manifold
@property
def dim(self):
return self.manifold.dim
def __call__(self, *args):
"""Evaluating the field at a point or doing nothing.
If the argument is a ``Point`` instance, the field is evaluated at that
point. The field is returned itself if the argument is any other
object. It is so in order to have working recursive calling mechanics
for all fields (check the ``__call__`` method of ``Expr``).
"""
point = args[0]
if len(args) != 1 or not isinstance(point, Point):
return self
coords = point.coords(self._coord_sys)
# XXX Calling doit is necessary with all the Subs expressions
# XXX Calling simplify is necessary with all the trig expressions
return simplify(coords[self._index]).doit()
# XXX Workaround for limitations on the content of args
free_symbols = set() # type: Set[Any]
def doit(self):
return self
class BaseVectorField(Expr):
r"""Base vector field over a manifold for a given coordinate system.
Explanation
===========
A vector field is an operator taking a scalar field and returning a
directional derivative (which is also a scalar field).
A base vector field is the same type of operator, however the derivation is
specifically done with respect to a chosen coordinate.
To define a base vector field you need to choose the coordinate system and
the index of the coordinate.
The use of the vector field after its definition is independent of the
coordinate system in which it was defined, however due to limitations in the
simplification routines you may arrive at more complicated expression if you
use unappropriate coordinate systems.
Parameters
==========
coord_sys : CoordSystem
index : integer
Examples
========
>>> from sympy import Function
>>> from sympy.diffgeom.rn import R2_p, R2_r
>>> from sympy.diffgeom import BaseVectorField
>>> from sympy import pprint
>>> x, y = R2_r.symbols
>>> rho, theta = R2_p.symbols
>>> fx, fy = R2_r.base_scalars()
>>> point_p = R2_p.point([rho, theta])
>>> point_r = R2_r.point([x, y])
>>> g = Function('g')
>>> s_field = g(fx, fy)
>>> v = BaseVectorField(R2_r, 1)
>>> pprint(v(s_field))
/ d \|
|---(g(x, xi))||
\dxi /|xi=y
>>> pprint(v(s_field).rcall(point_r).doit())
d
--(g(x, y))
dy
>>> pprint(v(s_field).rcall(point_p))
/ d \|
|---(g(rho*cos(theta), xi))||
\dxi /|xi=rho*sin(theta)
"""
is_commutative = False
def __new__(cls, coord_sys, index, **kwargs):
index = _sympify(index)
obj = super().__new__(cls, coord_sys, index)
obj._coord_sys = coord_sys
obj._index = index
return obj
@property
def coord_sys(self):
return self.args[0]
@property
def index(self):
return self.args[1]
@property
def patch(self):
return self.coord_sys.patch
@property
def manifold(self):
return self.coord_sys.manifold
@property
def dim(self):
return self.manifold.dim
def __call__(self, scalar_field):
"""Apply on a scalar field.
The action of a vector field on a scalar field is a directional
differentiation.
If the argument is not a scalar field an error is raised.
"""
if covariant_order(scalar_field) or contravariant_order(scalar_field):
raise ValueError('Only scalar fields can be supplied as arguments to vector fields.')
if scalar_field is None:
return self
base_scalars = list(scalar_field.atoms(BaseScalarField))
# First step: e_x(x+r**2) -> e_x(x) + 2*r*e_x(r)
d_var = self._coord_sys._dummy
# TODO: you need a real dummy function for the next line
d_funcs = [Function('_#_%s' % i)(d_var) for i,
b in enumerate(base_scalars)]
d_result = scalar_field.subs(list(zip(base_scalars, d_funcs)))
d_result = d_result.diff(d_var)
# Second step: e_x(x) -> 1 and e_x(r) -> cos(atan2(x, y))
coords = self._coord_sys.symbols
d_funcs_deriv = [f.diff(d_var) for f in d_funcs]
d_funcs_deriv_sub = []
for b in base_scalars:
jac = self._coord_sys.jacobian(b._coord_sys, coords)
d_funcs_deriv_sub.append(jac[b._index, self._index])
d_result = d_result.subs(list(zip(d_funcs_deriv, d_funcs_deriv_sub)))
# Remove the dummies
result = d_result.subs(list(zip(d_funcs, base_scalars)))
result = result.subs(list(zip(coords, self._coord_sys.coord_functions())))
return result.doit()
def _find_coords(expr):
# Finds CoordinateSystems existing in expr
fields = expr.atoms(BaseScalarField, BaseVectorField)
result = set()
for f in fields:
result.add(f._coord_sys)
return result
class Commutator(Expr):
r"""Commutator of two vector fields.
Explanation
===========
The commutator of two vector fields `v_1` and `v_2` is defined as the
vector field `[v_1, v_2]` that evaluated on each scalar field `f` is equal
to `v_1(v_2(f)) - v_2(v_1(f))`.
Examples
========
>>> from sympy.diffgeom.rn import R2_p, R2_r
>>> from sympy.diffgeom import Commutator
>>> from sympy.simplify import simplify
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> e_r = R2_p.base_vector(0)
>>> c_xy = Commutator(e_x, e_y)
>>> c_xr = Commutator(e_x, e_r)
>>> c_xy
0
Unfortunately, the current code is not able to compute everything:
>>> c_xr
Commutator(e_x, e_rho)
>>> simplify(c_xr(fy**2))
-2*cos(theta)*y**2/(x**2 + y**2)
"""
def __new__(cls, v1, v2):
if (covariant_order(v1) or contravariant_order(v1) != 1
or covariant_order(v2) or contravariant_order(v2) != 1):
raise ValueError(
'Only commutators of vector fields are supported.')
if v1 == v2:
return S.Zero
coord_sys = set().union(*[_find_coords(v) for v in (v1, v2)])
if len(coord_sys) == 1:
# Only one coordinate systems is used, hence it is easy enough to
# actually evaluate the commutator.
if all(isinstance(v, BaseVectorField) for v in (v1, v2)):
return S.Zero
bases_1, bases_2 = [list(v.atoms(BaseVectorField))
for v in (v1, v2)]
coeffs_1 = [v1.expand().coeff(b) for b in bases_1]
coeffs_2 = [v2.expand().coeff(b) for b in bases_2]
res = 0
for c1, b1 in zip(coeffs_1, bases_1):
for c2, b2 in zip(coeffs_2, bases_2):
res += c1*b1(c2)*b2 - c2*b2(c1)*b1
return res
else:
obj = super().__new__(cls, v1, v2)
obj._v1 = v1 # deprecated assignment
obj._v2 = v2 # deprecated assignment
return obj
@property
def v1(self):
return self.args[0]
@property
def v2(self):
return self.args[1]
def __call__(self, scalar_field):
"""Apply on a scalar field.
If the argument is not a scalar field an error is raised.
"""
return self.v1(self.v2(scalar_field)) - self.v2(self.v1(scalar_field))
class Differential(Expr):
r"""Return the differential (exterior derivative) of a form field.
Explanation
===========
The differential of a form (i.e. the exterior derivative) has a complicated
definition in the general case.
The differential `df` of the 0-form `f` is defined for any vector field `v`
as `df(v) = v(f)`.
Examples
========
>>> from sympy import Function
>>> from sympy.diffgeom.rn import R2_r
>>> from sympy.diffgeom import Differential
>>> from sympy import pprint
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> g = Function('g')
>>> s_field = g(fx, fy)
>>> dg = Differential(s_field)
>>> dg
d(g(x, y))
>>> pprint(dg(e_x))
/ d \|
|---(g(xi, y))||
\dxi /|xi=x
>>> pprint(dg(e_y))
/ d \|
|---(g(x, xi))||
\dxi /|xi=y
Applying the exterior derivative operator twice always results in:
>>> Differential(dg)
0
"""
is_commutative = False
def __new__(cls, form_field):
if contravariant_order(form_field):
raise ValueError(
'A vector field was supplied as an argument to Differential.')
if isinstance(form_field, Differential):
return S.Zero
else:
obj = super().__new__(cls, form_field)
obj._form_field = form_field # deprecated assignment
return obj
@property
def form_field(self):
return self.args[0]
def __call__(self, *vector_fields):
"""Apply on a list of vector_fields.
Explanation
===========
If the number of vector fields supplied is not equal to 1 + the order of
the form field inside the differential the result is undefined.
For 1-forms (i.e. differentials of scalar fields) the evaluation is
done as `df(v)=v(f)`. However if `v` is ``None`` instead of a vector
field, the differential is returned unchanged. This is done in order to
permit partial contractions for higher forms.
In the general case the evaluation is done by applying the form field
inside the differential on a list with one less elements than the number
of elements in the original list. Lowering the number of vector fields
is achieved through replacing each pair of fields by their
commutator.
If the arguments are not vectors or ``None``s an error is raised.
"""
if any((contravariant_order(a) != 1 or covariant_order(a)) and a is not None
for a in vector_fields):
raise ValueError('The arguments supplied to Differential should be vector fields or Nones.')
k = len(vector_fields)
if k == 1:
if vector_fields[0]:
return vector_fields[0].rcall(self._form_field)
return self
else:
# For higher form it is more complicated:
# Invariant formula:
# https://en.wikipedia.org/wiki/Exterior_derivative#Invariant_formula
# df(v1, ... vn) = +/- vi(f(v1..no i..vn))
# +/- f([vi,vj],v1..no i, no j..vn)
f = self._form_field
v = vector_fields
ret = 0
for i in range(k):
t = v[i].rcall(f.rcall(*v[:i] + v[i + 1:]))
ret += (-1)**i*t
for j in range(i + 1, k):
c = Commutator(v[i], v[j])
if c: # TODO this is ugly - the Commutator can be Zero and
# this causes the next line to fail
t = f.rcall(*(c,) + v[:i] + v[i + 1:j] + v[j + 1:])
ret += (-1)**(i + j)*t
return ret
class TensorProduct(Expr):
"""Tensor product of forms.
Explanation
===========
The tensor product permits the creation of multilinear functionals (i.e.
higher order tensors) out of lower order fields (e.g. 1-forms and vector
fields). However, the higher tensors thus created lack the interesting
features provided by the other type of product, the wedge product, namely
they are not antisymmetric and hence are not form fields.
Examples
========
>>> from sympy.diffgeom.rn import R2_r
>>> from sympy.diffgeom import TensorProduct
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> dx, dy = R2_r.base_oneforms()
>>> TensorProduct(dx, dy)(e_x, e_y)
1
>>> TensorProduct(dx, dy)(e_y, e_x)
0
>>> TensorProduct(dx, fx*dy)(fx*e_x, e_y)
x**2
>>> TensorProduct(e_x, e_y)(fx**2, fy**2)
4*x*y
>>> TensorProduct(e_y, dx)(fy)
dx
You can nest tensor products.
>>> tp1 = TensorProduct(dx, dy)
>>> TensorProduct(tp1, dx)(e_x, e_y, e_x)
1
You can make partial contraction for instance when 'raising an index'.
Putting ``None`` in the second argument of ``rcall`` means that the
respective position in the tensor product is left as it is.
>>> TP = TensorProduct
>>> metric = TP(dx, dx) + 3*TP(dy, dy)
>>> metric.rcall(e_y, None)
3*dy
Or automatically pad the args with ``None`` without specifying them.
>>> metric.rcall(e_y)
3*dy
"""
def __new__(cls, *args):
scalar = Mul(*[m for m in args if covariant_order(m) + contravariant_order(m) == 0])
multifields = [m for m in args if covariant_order(m) + contravariant_order(m)]
if multifields:
if len(multifields) == 1:
return scalar*multifields[0]
return scalar*super().__new__(cls, *multifields)
else:
return scalar
def __call__(self, *fields):
"""Apply on a list of fields.
If the number of input fields supplied is not equal to the order of
the tensor product field, the list of arguments is padded with ``None``'s.
The list of arguments is divided in sublists depending on the order of
the forms inside the tensor product. The sublists are provided as
arguments to these forms and the resulting expressions are given to the
constructor of ``TensorProduct``.
"""
tot_order = covariant_order(self) + contravariant_order(self)
tot_args = len(fields)
if tot_args != tot_order:
fields = list(fields) + [None]*(tot_order - tot_args)
orders = [covariant_order(f) + contravariant_order(f) for f in self._args]
indices = [sum(orders[:i + 1]) for i in range(len(orders) - 1)]
fields = [fields[i:j] for i, j in zip([0] + indices, indices + [None])]
multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, fields)]
return TensorProduct(*multipliers)
class WedgeProduct(TensorProduct):
"""Wedge product of forms.
Explanation
===========
In the context of integration only completely antisymmetric forms make
sense. The wedge product permits the creation of such forms.
Examples
========
>>> from sympy.diffgeom.rn import R2_r
>>> from sympy.diffgeom import WedgeProduct
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> dx, dy = R2_r.base_oneforms()
>>> WedgeProduct(dx, dy)(e_x, e_y)
1
>>> WedgeProduct(dx, dy)(e_y, e_x)
-1
>>> WedgeProduct(dx, fx*dy)(fx*e_x, e_y)
x**2
>>> WedgeProduct(e_x, e_y)(fy, None)
-e_x
You can nest wedge products.
>>> wp1 = WedgeProduct(dx, dy)
>>> WedgeProduct(wp1, dx)(e_x, e_y, e_x)
0
"""
# TODO the calculation of signatures is slow
# TODO you do not need all these permutations (neither the prefactor)
def __call__(self, *fields):
"""Apply on a list of vector_fields.
The expression is rewritten internally in terms of tensor products and evaluated."""
orders = (covariant_order(e) + contravariant_order(e) for e in self.args)
mul = 1/Mul(*(factorial(o) for o in orders))
perms = permutations(fields)
perms_par = (Permutation(
p).signature() for p in permutations(list(range(len(fields)))))
tensor_prod = TensorProduct(*self.args)
return mul*Add(*[tensor_prod(*p[0])*p[1] for p in zip(perms, perms_par)])
class LieDerivative(Expr):
"""Lie derivative with respect to a vector field.
Explanation
===========
The transport operator that defines the Lie derivative is the pushforward of
the field to be derived along the integral curve of the field with respect
to which one derives.
Examples
========
>>> from sympy.diffgeom.rn import R2_r, R2_p
>>> from sympy.diffgeom import (LieDerivative, TensorProduct)
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> e_rho, e_theta = R2_p.base_vectors()
>>> dx, dy = R2_r.base_oneforms()
>>> LieDerivative(e_x, fy)
0
>>> LieDerivative(e_x, fx)
1
>>> LieDerivative(e_x, e_x)
0
The Lie derivative of a tensor field by another tensor field is equal to
their commutator:
>>> LieDerivative(e_x, e_rho)
Commutator(e_x, e_rho)
>>> LieDerivative(e_x + e_y, fx)
1
>>> tp = TensorProduct(dx, dy)
>>> LieDerivative(e_x, tp)
LieDerivative(e_x, TensorProduct(dx, dy))
>>> LieDerivative(e_x, tp)
LieDerivative(e_x, TensorProduct(dx, dy))
"""
def __new__(cls, v_field, expr):
expr_form_ord = covariant_order(expr)
if contravariant_order(v_field) != 1 or covariant_order(v_field):
raise ValueError('Lie derivatives are defined only with respect to'
' vector fields. The supplied argument was not a '
'vector field.')
if expr_form_ord > 0:
obj = super().__new__(cls, v_field, expr)
# deprecated assignments
obj._v_field = v_field
obj._expr = expr
return obj
if expr.atoms(BaseVectorField):
return Commutator(v_field, expr)
else:
return v_field.rcall(expr)
@property
def v_field(self):
return self.args[0]
@property
def expr(self):
return self.args[1]
def __call__(self, *args):
v = self.v_field
expr = self.expr
lead_term = v(expr(*args))
rest = Add(*[Mul(*args[:i] + (Commutator(v, args[i]),) + args[i + 1:])
for i in range(len(args))])
return lead_term - rest
class BaseCovarDerivativeOp(Expr):
"""Covariant derivative operator with respect to a base vector.
Examples
========
>>> from sympy.diffgeom.rn import R2_r
>>> from sympy.diffgeom import BaseCovarDerivativeOp
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
>>> TP = TensorProduct
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> dx, dy = R2_r.base_oneforms()
>>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy))
>>> ch
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
>>> cvd = BaseCovarDerivativeOp(R2_r, 0, ch)
>>> cvd(fx)
1
>>> cvd(fx*e_x)
e_x
"""
def __new__(cls, coord_sys, index, christoffel):
index = _sympify(index)
christoffel = ImmutableDenseNDimArray(christoffel)
obj = super().__new__(cls, coord_sys, index, christoffel)
# deprecated assignments
obj._coord_sys = coord_sys
obj._index = index
obj._christoffel = christoffel
return obj
@property
def coord_sys(self):
return self.args[0]
@property
def index(self):
return self.args[1]
@property
def christoffel(self):
return self.args[2]
def __call__(self, field):
"""Apply on a scalar field.
The action of a vector field on a scalar field is a directional
differentiation.
If the argument is not a scalar field the behaviour is undefined.
"""
if covariant_order(field) != 0:
raise NotImplementedError()
field = vectors_in_basis(field, self._coord_sys)
wrt_vector = self._coord_sys.base_vector(self._index)
wrt_scalar = self._coord_sys.coord_function(self._index)
vectors = list(field.atoms(BaseVectorField))
# First step: replace all vectors with something susceptible to
# derivation and do the derivation
# TODO: you need a real dummy function for the next line
d_funcs = [Function('_#_%s' % i)(wrt_scalar) for i,
b in enumerate(vectors)]
d_result = field.subs(list(zip(vectors, d_funcs)))
d_result = wrt_vector(d_result)
# Second step: backsubstitute the vectors in
d_result = d_result.subs(list(zip(d_funcs, vectors)))
# Third step: evaluate the derivatives of the vectors
derivs = []
for v in vectors:
d = Add(*[(self._christoffel[k, wrt_vector._index, v._index]
*v._coord_sys.base_vector(k))
for k in range(v._coord_sys.dim)])
derivs.append(d)
to_subs = [wrt_vector(d) for d in d_funcs]
# XXX: This substitution can fail when there are Dummy symbols and the
# cache is disabled: https://github.com/sympy/sympy/issues/17794
result = d_result.subs(list(zip(to_subs, derivs)))
# Remove the dummies
result = result.subs(list(zip(d_funcs, vectors)))
return result.doit()
class CovarDerivativeOp(Expr):
"""Covariant derivative operator.
Examples
========
>>> from sympy.diffgeom.rn import R2_r
>>> from sympy.diffgeom import CovarDerivativeOp
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
>>> TP = TensorProduct
>>> fx, fy = R2_r.base_scalars()
>>> e_x, e_y = R2_r.base_vectors()
>>> dx, dy = R2_r.base_oneforms()
>>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy))
>>> ch
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
>>> cvd = CovarDerivativeOp(fx*e_x, ch)
>>> cvd(fx)
x
>>> cvd(fx*e_x)
x*e_x
"""
def __new__(cls, wrt, christoffel):
if len({v._coord_sys for v in wrt.atoms(BaseVectorField)}) > 1:
raise NotImplementedError()
if contravariant_order(wrt) != 1 or covariant_order(wrt):
raise ValueError('Covariant derivatives are defined only with '
'respect to vector fields. The supplied argument '
'was not a vector field.')
obj = super().__new__(cls, wrt, christoffel)
# deprecated assigments
obj._wrt = wrt
obj._christoffel = christoffel
return obj
@property
def wrt(self):
return self.args[0]
@property
def christoffel(self):
return self.args[1]
def __call__(self, field):
vectors = list(self._wrt.atoms(BaseVectorField))
base_ops = [BaseCovarDerivativeOp(v._coord_sys, v._index, self._christoffel)
for v in vectors]
return self._wrt.subs(list(zip(vectors, base_ops))).rcall(field)
###############################################################################
# Integral curves on vector fields
###############################################################################
def intcurve_series(vector_field, param, start_point, n=6, coord_sys=None, coeffs=False):
r"""Return the series expansion for an integral curve of the field.
Explanation
===========
Integral curve is a function `\gamma` taking a parameter in `R` to a point
in the manifold. It verifies the equation:
`V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
where the given ``vector_field`` is denoted as `V`. This holds for any
value `t` for the parameter and any scalar field `f`.
This equation can also be decomposed of a basis of coordinate functions
`V(f_i)\big(\gamma(t)\big) = \frac{d}{dt}f_i\big(\gamma(t)\big) \quad \forall i`
This function returns a series expansion of `\gamma(t)` in terms of the
coordinate system ``coord_sys``. The equations and expansions are necessarily
done in coordinate-system-dependent way as there is no other way to
represent movement between points on the manifold (i.e. there is no such
thing as a difference of points for a general manifold).
Parameters
==========
vector_field
the vector field for which an integral curve will be given
param
the argument of the function `\gamma` from R to the curve
start_point
the point which corresponds to `\gamma(0)`
n
the order to which to expand
coord_sys
the coordinate system in which to expand
coeffs (default False) - if True return a list of elements of the expansion
Examples
========
Use the predefined R2 manifold:
>>> from sympy.abc import t, x, y
>>> from sympy.diffgeom.rn import R2_p, R2_r
>>> from sympy.diffgeom import intcurve_series
Specify a starting point and a vector field:
>>> start_point = R2_r.point([x, y])
>>> vector_field = R2_r.e_x
Calculate the series:
>>> intcurve_series(vector_field, t, start_point, n=3)
Matrix([
[t + x],
[ y]])
Or get the elements of the expansion in a list:
>>> series = intcurve_series(vector_field, t, start_point, n=3, coeffs=True)
>>> series[0]
Matrix([
[x],
[y]])
>>> series[1]
Matrix([
[t],
[0]])
>>> series[2]
Matrix([
[0],
[0]])
The series in the polar coordinate system:
>>> series = intcurve_series(vector_field, t, start_point,
... n=3, coord_sys=R2_p, coeffs=True)
>>> series[0]
Matrix([
[sqrt(x**2 + y**2)],
[ atan2(y, x)]])
>>> series[1]
Matrix([
[t*x/sqrt(x**2 + y**2)],
[ -t*y/(x**2 + y**2)]])
>>> series[2]
Matrix([
[t**2*(-x**2/(x**2 + y**2)**(3/2) + 1/sqrt(x**2 + y**2))/2],
[ t**2*x*y/(x**2 + y**2)**2]])
See Also
========
intcurve_diffequ
"""
if contravariant_order(vector_field) != 1 or covariant_order(vector_field):
raise ValueError('The supplied field was not a vector field.')
def iter_vfield(scalar_field, i):
"""Return ``vector_field`` called `i` times on ``scalar_field``."""
return reduce(lambda s, v: v.rcall(s), [vector_field, ]*i, scalar_field)
def taylor_terms_per_coord(coord_function):
"""Return the series for one of the coordinates."""
return [param**i*iter_vfield(coord_function, i).rcall(start_point)/factorial(i)
for i in range(n)]
coord_sys = coord_sys if coord_sys else start_point._coord_sys
coord_functions = coord_sys.coord_functions()
taylor_terms = [taylor_terms_per_coord(f) for f in coord_functions]
if coeffs:
return [Matrix(t) for t in zip(*taylor_terms)]
else:
return Matrix([sum(c) for c in taylor_terms])
def intcurve_diffequ(vector_field, param, start_point, coord_sys=None):
r"""Return the differential equation for an integral curve of the field.
Explanation
===========
Integral curve is a function `\gamma` taking a parameter in `R` to a point
in the manifold. It verifies the equation:
`V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
where the given ``vector_field`` is denoted as `V`. This holds for any
value `t` for the parameter and any scalar field `f`.
This function returns the differential equation of `\gamma(t)` in terms of the
coordinate system ``coord_sys``. The equations and expansions are necessarily
done in coordinate-system-dependent way as there is no other way to
represent movement between points on the manifold (i.e. there is no such
thing as a difference of points for a general manifold).
Parameters
==========
vector_field
the vector field for which an integral curve will be given
param
the argument of the function `\gamma` from R to the curve
start_point
the point which corresponds to `\gamma(0)`
coord_sys
the coordinate system in which to give the equations
Returns
=======
a tuple of (equations, initial conditions)
Examples
========
Use the predefined R2 manifold:
>>> from sympy.abc import t
>>> from sympy.diffgeom.rn import R2, R2_p, R2_r
>>> from sympy.diffgeom import intcurve_diffequ
Specify a starting point and a vector field:
>>> start_point = R2_r.point([0, 1])
>>> vector_field = -R2.y*R2.e_x + R2.x*R2.e_y
Get the equation:
>>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point)
>>> equations
[f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]
>>> init_cond
[f_0(0), f_1(0) - 1]
The series in the polar coordinate system:
>>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p)
>>> equations
[Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]
>>> init_cond
[f_0(0) - 1, f_1(0) - pi/2]
See Also
========
intcurve_series
"""
if contravariant_order(vector_field) != 1 or covariant_order(vector_field):
raise ValueError('The supplied field was not a vector field.')
coord_sys = coord_sys if coord_sys else start_point._coord_sys
gammas = [Function('f_%d' % i)(param) for i in range(
start_point._coord_sys.dim)]
arbitrary_p = Point(coord_sys, gammas)
coord_functions = coord_sys.coord_functions()
equations = [simplify(diff(cf.rcall(arbitrary_p), param) - vector_field.rcall(cf).rcall(arbitrary_p))
for cf in coord_functions]
init_cond = [simplify(cf.rcall(arbitrary_p).subs(param, 0) - cf.rcall(start_point))
for cf in coord_functions]
return equations, init_cond
###############################################################################
# Helpers
###############################################################################
def dummyfy(args, exprs):
# TODO Is this a good idea?
d_args = Matrix([s.as_dummy() for s in args])
reps = dict(zip(args, d_args))
d_exprs = Matrix([_sympify(expr).subs(reps) for expr in exprs])
return d_args, d_exprs
###############################################################################
# Helpers
###############################################################################
def contravariant_order(expr, _strict=False):
"""Return the contravariant order of an expression.
Examples
========
>>> from sympy.diffgeom import contravariant_order
>>> from sympy.diffgeom.rn import R2
>>> from sympy.abc import a
>>> contravariant_order(a)
0
>>> contravariant_order(a*R2.x + 2)
0
>>> contravariant_order(a*R2.x*R2.e_y + R2.e_x)
1
"""
# TODO move some of this to class methods.
# TODO rewrite using the .as_blah_blah methods
if isinstance(expr, Add):
orders = [contravariant_order(e) for e in expr.args]
if len(set(orders)) != 1:
raise ValueError('Misformed expression containing contravariant fields of varying order.')
return orders[0]
elif isinstance(expr, Mul):
orders = [contravariant_order(e) for e in expr.args]
not_zero = [o for o in orders if o != 0]
if len(not_zero) > 1:
raise ValueError('Misformed expression containing multiplication between vectors.')
return 0 if not not_zero else not_zero[0]
elif isinstance(expr, Pow):
if covariant_order(expr.base) or covariant_order(expr.exp):
raise ValueError(
'Misformed expression containing a power of a vector.')
return 0
elif isinstance(expr, BaseVectorField):
return 1
elif isinstance(expr, TensorProduct):
return sum(contravariant_order(a) for a in expr.args)
elif not _strict or expr.atoms(BaseScalarField):
return 0
else: # If it does not contain anything related to the diffgeom module and it is _strict
return -1
def covariant_order(expr, _strict=False):
"""Return the covariant order of an expression.
Examples
========
>>> from sympy.diffgeom import covariant_order
>>> from sympy.diffgeom.rn import R2
>>> from sympy.abc import a
>>> covariant_order(a)
0
>>> covariant_order(a*R2.x + 2)
0
>>> covariant_order(a*R2.x*R2.dy + R2.dx)
1
"""
# TODO move some of this to class methods.
# TODO rewrite using the .as_blah_blah methods
if isinstance(expr, Add):
orders = [covariant_order(e) for e in expr.args]
if len(set(orders)) != 1:
raise ValueError('Misformed expression containing form fields of varying order.')
return orders[0]
elif isinstance(expr, Mul):
orders = [covariant_order(e) for e in expr.args]
not_zero = [o for o in orders if o != 0]
if len(not_zero) > 1:
raise ValueError('Misformed expression containing multiplication between forms.')
return 0 if not not_zero else not_zero[0]
elif isinstance(expr, Pow):
if covariant_order(expr.base) or covariant_order(expr.exp):
raise ValueError(
'Misformed expression containing a power of a form.')
return 0
elif isinstance(expr, Differential):
return covariant_order(*expr.args) + 1
elif isinstance(expr, TensorProduct):
return sum(covariant_order(a) for a in expr.args)
elif not _strict or expr.atoms(BaseScalarField):
return 0
else: # If it does not contain anything related to the diffgeom module and it is _strict
return -1
###############################################################################
# Coordinate transformation functions
###############################################################################
def vectors_in_basis(expr, to_sys):
"""Transform all base vectors in base vectors of a specified coord basis.
While the new base vectors are in the new coordinate system basis, any
coefficients are kept in the old system.
Examples
========
>>> from sympy.diffgeom import vectors_in_basis
>>> from sympy.diffgeom.rn import R2_r, R2_p
>>> vectors_in_basis(R2_r.e_x, R2_p)
-y*e_theta/(x**2 + y**2) + x*e_rho/sqrt(x**2 + y**2)
>>> vectors_in_basis(R2_p.e_r, R2_r)
sin(theta)*e_y + cos(theta)*e_x
"""
vectors = list(expr.atoms(BaseVectorField))
new_vectors = []
for v in vectors:
cs = v._coord_sys
jac = cs.jacobian(to_sys, cs.coord_functions())
new = (jac.T*Matrix(to_sys.base_vectors()))[v._index]
new_vectors.append(new)
return expr.subs(list(zip(vectors, new_vectors)))
###############################################################################
# Coordinate-dependent functions
###############################################################################
def twoform_to_matrix(expr):
"""Return the matrix representing the twoform.
For the twoform `w` return the matrix `M` such that `M[i,j]=w(e_i, e_j)`,
where `e_i` is the i-th base vector field for the coordinate system in
which the expression of `w` is given.
Examples
========
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import twoform_to_matrix, TensorProduct
>>> TP = TensorProduct
>>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
Matrix([
[1, 0],
[0, 1]])
>>> twoform_to_matrix(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
Matrix([
[x, 0],
[0, 1]])
>>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy) - TP(R2.dx, R2.dy)/2)
Matrix([
[ 1, 0],
[-1/2, 1]])
"""
if covariant_order(expr) != 2 or contravariant_order(expr):
raise ValueError('The input expression is not a two-form.')
coord_sys = _find_coords(expr)
if len(coord_sys) != 1:
raise ValueError('The input expression concerns more than one '
'coordinate systems, hence there is no unambiguous '
'way to choose a coordinate system for the matrix.')
coord_sys = coord_sys.pop()
vectors = coord_sys.base_vectors()
expr = expr.expand()
matrix_content = [[expr.rcall(v1, v2) for v1 in vectors]
for v2 in vectors]
return Matrix(matrix_content)
def metric_to_Christoffel_1st(expr):
"""Return the nested list of Christoffel symbols for the given metric.
This returns the Christoffel symbol of first kind that represents the
Levi-Civita connection for the given metric.
Examples
========
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import metric_to_Christoffel_1st, TensorProduct
>>> TP = TensorProduct
>>> metric_to_Christoffel_1st(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
>>> metric_to_Christoffel_1st(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
[[[1/2, 0], [0, 0]], [[0, 0], [0, 0]]]
"""
matrix = twoform_to_matrix(expr)
if not matrix.is_symmetric():
raise ValueError(
'The two-form representing the metric is not symmetric.')
coord_sys = _find_coords(expr).pop()
deriv_matrices = [matrix.applyfunc(lambda a: d(a))
for d in coord_sys.base_vectors()]
indices = list(range(coord_sys.dim))
christoffel = [[[(deriv_matrices[k][i, j] + deriv_matrices[j][i, k] - deriv_matrices[i][j, k])/2
for k in indices]
for j in indices]
for i in indices]
return ImmutableDenseNDimArray(christoffel)
def metric_to_Christoffel_2nd(expr):
"""Return the nested list of Christoffel symbols for the given metric.
This returns the Christoffel symbol of second kind that represents the
Levi-Civita connection for the given metric.
Examples
========
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
>>> TP = TensorProduct
>>> metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
>>> metric_to_Christoffel_2nd(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
[[[1/(2*x), 0], [0, 0]], [[0, 0], [0, 0]]]
"""
ch_1st = metric_to_Christoffel_1st(expr)
coord_sys = _find_coords(expr).pop()
indices = list(range(coord_sys.dim))
# XXX workaround, inverting a matrix does not work if it contains non
# symbols
#matrix = twoform_to_matrix(expr).inv()
matrix = twoform_to_matrix(expr)
s_fields = set()
for e in matrix:
s_fields.update(e.atoms(BaseScalarField))
s_fields = list(s_fields)
dums = coord_sys.symbols
matrix = matrix.subs(list(zip(s_fields, dums))).inv().subs(list(zip(dums, s_fields)))
# XXX end of workaround
christoffel = [[[Add(*[matrix[i, l]*ch_1st[l, j, k] for l in indices])
for k in indices]
for j in indices]
for i in indices]
return ImmutableDenseNDimArray(christoffel)
def metric_to_Riemann_components(expr):
"""Return the components of the Riemann tensor expressed in a given basis.
Given a metric it calculates the components of the Riemann tensor in the
canonical basis of the coordinate system in which the metric expression is
given.
Examples
========
>>> from sympy import exp
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import metric_to_Riemann_components, TensorProduct
>>> TP = TensorProduct
>>> metric_to_Riemann_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
[[[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]
>>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \
R2.r**2*TP(R2.dtheta, R2.dtheta)
>>> non_trivial_metric
exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta)
>>> riemann = metric_to_Riemann_components(non_trivial_metric)
>>> riemann[0, :, :, :]
[[[0, 0], [0, 0]], [[0, exp(-2*rho)*rho], [-exp(-2*rho)*rho, 0]]]
>>> riemann[1, :, :, :]
[[[0, -1/rho], [1/rho, 0]], [[0, 0], [0, 0]]]
"""
ch_2nd = metric_to_Christoffel_2nd(expr)
coord_sys = _find_coords(expr).pop()
indices = list(range(coord_sys.dim))
deriv_ch = [[[[d(ch_2nd[i, j, k])
for d in coord_sys.base_vectors()]
for k in indices]
for j in indices]
for i in indices]
riemann_a = [[[[deriv_ch[rho][sig][nu][mu] - deriv_ch[rho][sig][mu][nu]
for nu in indices]
for mu in indices]
for sig in indices]
for rho in indices]
riemann_b = [[[[Add(*[ch_2nd[rho, l, mu]*ch_2nd[l, sig, nu] - ch_2nd[rho, l, nu]*ch_2nd[l, sig, mu] for l in indices])
for nu in indices]
for mu in indices]
for sig in indices]
for rho in indices]
riemann = [[[[riemann_a[rho][sig][mu][nu] + riemann_b[rho][sig][mu][nu]
for nu in indices]
for mu in indices]
for sig in indices]
for rho in indices]
return ImmutableDenseNDimArray(riemann)
def metric_to_Ricci_components(expr):
"""Return the components of the Ricci tensor expressed in a given basis.
Given a metric it calculates the components of the Ricci tensor in the
canonical basis of the coordinate system in which the metric expression is
given.
Examples
========
>>> from sympy import exp
>>> from sympy.diffgeom.rn import R2
>>> from sympy.diffgeom import metric_to_Ricci_components, TensorProduct
>>> TP = TensorProduct
>>> metric_to_Ricci_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
[[0, 0], [0, 0]]
>>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \
R2.r**2*TP(R2.dtheta, R2.dtheta)
>>> non_trivial_metric
exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta)
>>> metric_to_Ricci_components(non_trivial_metric)
[[1/rho, 0], [0, exp(-2*rho)*rho]]
"""
riemann = metric_to_Riemann_components(expr)
coord_sys = _find_coords(expr).pop()
indices = list(range(coord_sys.dim))
ricci = [[Add(*[riemann[k, i, k, j] for k in indices])
for j in indices]
for i in indices]
return ImmutableDenseNDimArray(ricci)
###############################################################################
# Classes for deprecation
###############################################################################
class _deprecated_container:
# This class gives deprecation warning.
# When deprecated features are completely deleted, this should be removed as well.
# See https://github.com/sympy/sympy/pull/19368
def __init__(self, feature, useinstead, issue, version, data):
super().__init__(data)
self.feature = feature
self.useinstead = useinstead
self.issue = issue
self.version = version
def warn(self):
SymPyDeprecationWarning(
feature=self.feature,
useinstead=self.useinstead,
issue=self.issue,
deprecated_since_version=self.version).warn()
def __iter__(self):
self.warn()
return super().__iter__()
def __getitem__(self, key):
self.warn()
return super().__getitem__(key)
def __contains__(self, key):
self.warn()
return super().__contains__(key)
class _deprecated_list(_deprecated_container, list):
pass
class _deprecated_dict(_deprecated_container, dict):
pass
|
f477a109fc06be8121cbcbca8b02736633974eef08c7454b9daaed0f89e67b4a | """
Classes and functions useful for rewriting expressions for optimized code
generation. Some languages (or standards thereof), e.g. C99, offer specialized
math functions for better performance and/or precision.
Using the ``optimize`` function in this module, together with a collection of
rules (represented as instances of ``Optimization``), one can rewrite the
expressions for this purpose::
>>> from sympy import Symbol, exp, log
>>> from sympy.codegen.rewriting import optimize, optims_c99
>>> x = Symbol('x')
>>> optimize(3*exp(2*x) - 3, optims_c99)
3*expm1(2*x)
>>> optimize(exp(2*x) - 3, optims_c99)
exp(2*x) - 3
>>> optimize(log(3*x + 3), optims_c99)
log1p(x) + log(3)
>>> optimize(log(2*x + 3), optims_c99)
log(2*x + 3)
The ``optims_c99`` imported above is tuple containing the following instances
(which may be imported from ``sympy.codegen.rewriting``):
- ``expm1_opt``
- ``log1p_opt``
- ``exp2_opt``
- ``log2_opt``
- ``log2const_opt``
"""
from itertools import chain
from sympy import cos, exp, log, Max, Min, Wild, expand_log, Dummy, sin, sinc
from sympy.assumptions import Q, ask
from sympy.codegen.cfunctions import log1p, log2, exp2, expm1
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.core.expr import UnevaluatedExpr
from sympy.core.power import Pow
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.codegen.scipy_nodes import cosm1
from sympy.core.mul import Mul
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.utilities.iterables import sift
class Optimization:
""" Abstract base class for rewriting optimization.
Subclasses should implement ``__call__`` taking an expression
as argument.
Parameters
==========
cost_function : callable returning number
priority : number
"""
def __init__(self, cost_function=None, priority=1):
self.cost_function = cost_function
self.priority=priority
class ReplaceOptim(Optimization):
""" Rewriting optimization calling replace on expressions.
Explanation
===========
The instance can be used as a function on expressions for which
it will apply the ``replace`` method (see
:meth:`sympy.core.basic.Basic.replace`).
Parameters
==========
query :
First argument passed to replace.
value :
Second argument passed to replace.
Examples
========
>>> from sympy import Symbol
>>> from sympy.codegen.rewriting import ReplaceOptim
>>> from sympy.codegen.cfunctions import exp2
>>> x = Symbol('x')
>>> exp2_opt = ReplaceOptim(lambda p: p.is_Pow and p.base == 2,
... lambda p: exp2(p.exp))
>>> exp2_opt(2**x)
exp2(x)
"""
def __init__(self, query, value, **kwargs):
super().__init__(**kwargs)
self.query = query
self.value = value
def __call__(self, expr):
return expr.replace(self.query, self.value)
def optimize(expr, optimizations):
""" Apply optimizations to an expression.
Parameters
==========
expr : expression
optimizations : iterable of ``Optimization`` instances
The optimizations will be sorted with respect to ``priority`` (highest first).
Examples
========
>>> from sympy import log, Symbol
>>> from sympy.codegen.rewriting import optims_c99, optimize
>>> x = Symbol('x')
>>> optimize(log(x+3)/log(2) + log(x**2 + 1), optims_c99)
log1p(x**2) + log2(x + 3)
"""
for optim in sorted(optimizations, key=lambda opt: opt.priority, reverse=True):
new_expr = optim(expr)
if optim.cost_function is None:
expr = new_expr
else:
before, after = map(lambda x: optim.cost_function(x), (expr, new_expr))
if before > after:
expr = new_expr
return expr
exp2_opt = ReplaceOptim(
lambda p: p.is_Pow and p.base == 2,
lambda p: exp2(p.exp)
)
_d = Wild('d', properties=[lambda x: x.is_Dummy])
_u = Wild('u', properties=[lambda x: not x.is_number and not x.is_Add])
_v = Wild('v')
_w = Wild('w')
_n = Wild('n', properties=[lambda x: x.is_number])
sinc_opt1 = ReplaceOptim(
sin(_w)/_w, sinc(_w)
)
sinc_opt2 = ReplaceOptim(
sin(_n*_w)/_w, _n*sinc(_n*_w)
)
sinc_opts = (sinc_opt1, sinc_opt2)
log2_opt = ReplaceOptim(_v*log(_w)/log(2), _v*log2(_w), cost_function=lambda expr: expr.count(
lambda e: ( # division & eval of transcendentals are expensive floating point operations...
e.is_Pow and e.exp.is_negative # division
or (isinstance(e, (log, log2)) and not e.args[0].is_number)) # transcendental
)
)
log2const_opt = ReplaceOptim(log(2)*log2(_w), log(_w))
logsumexp_2terms_opt = ReplaceOptim(
lambda l: (isinstance(l, log)
and l.args[0].is_Add
and len(l.args[0].args) == 2
and all(isinstance(t, exp) for t in l.args[0].args)),
lambda l: (
Max(*[e.args[0] for e in l.args[0].args]) +
log1p(exp(Min(*[e.args[0] for e in l.args[0].args])))
)
)
class _FuncMinusOne:
def __init__(self, func, func_m_1):
self.func = func
self.func_m_1 = func_m_1
def _try_func_m_1(self, expr):
old_new = {}
protected = expr.replace(self.func, lambda arg: old_new.setdefault(arg, Dummy()))
factored = protected.factor()
new_old = {v: self.func(k) for k, v in old_new.items()}
return factored.replace(_d - 1, lambda d: self.func_m_1(new_old[d].args[0])).xreplace(new_old)
def __call__(self, e):
numbers, non_num = sift(e.args, lambda arg: arg.is_number, binary=True)
non_num_func, non_num_other = sift(non_num, lambda arg: arg.has(self.func),
binary=True)
numsum = sum(numbers)
new_func_terms, done = [], False
for func_term in non_num_func:
if done:
new_func_terms.append(func_term)
else:
looking_at = func_term + numsum
attempt = self._try_func_m_1(looking_at)
if looking_at == attempt:
new_func_terms.append(func_term)
else:
done = True
new_func_terms.append(attempt)
if not done:
new_func_terms.append(numsum)
return e.func(*chain(new_func_terms, non_num_other))
expm1_opt = ReplaceOptim(lambda e: e.is_Add, _FuncMinusOne(exp, expm1))
cosm1_opt = ReplaceOptim(lambda e: e.is_Add, _FuncMinusOne(cos, cosm1))
log1p_opt = ReplaceOptim(
lambda e: isinstance(e, log),
lambda l: expand_log(l.replace(
log, lambda arg: log(arg.factor())
)).replace(log(_u+1), log1p(_u))
)
def create_expand_pow_optimization(limit, *, base_req=lambda b: b.is_symbol):
""" Creates an instance of :class:`ReplaceOptim` for expanding ``Pow``.
Explanation
===========
The requirements for expansions are that the base needs to be a symbol
and the exponent needs to be an Integer (and be less than or equal to
``limit``).
Parameters
==========
limit : int
The highest power which is expanded into multiplication.
base_req : function returning bool
Requirement on base for expansion to happen, default is to return
the ``is_symbol`` attribute of the base.
Examples
========
>>> from sympy import Symbol, sin
>>> from sympy.codegen.rewriting import create_expand_pow_optimization
>>> x = Symbol('x')
>>> expand_opt = create_expand_pow_optimization(3)
>>> expand_opt(x**5 + x**3)
x**5 + x*x*x
>>> expand_opt(x**5 + x**3 + sin(x)**3)
x**5 + sin(x)**3 + x*x*x
>>> opt2 = create_expand_pow_optimization(3 , base_req=lambda b: not b.is_Function)
>>> opt2((x+1)**2 + sin(x)**2)
sin(x)**2 + (x + 1)*(x + 1)
"""
return ReplaceOptim(
lambda e: e.is_Pow and base_req(e.base) and e.exp.is_Integer and abs(e.exp) <= limit,
lambda p: (
UnevaluatedExpr(Mul(*([p.base]*+p.exp), evaluate=False)) if p.exp > 0 else
1/UnevaluatedExpr(Mul(*([p.base]*-p.exp), evaluate=False))
))
# Optimization procedures for turning A**(-1) * x into MatrixSolve(A, x)
def _matinv_predicate(expr):
# TODO: We should be able to support more than 2 elements
if expr.is_MatMul and len(expr.args) == 2:
left, right = expr.args
if left.is_Inverse and right.shape[1] == 1:
inv_arg = left.arg
if isinstance(inv_arg, MatrixSymbol):
return bool(ask(Q.fullrank(left.arg)))
return False
def _matinv_transform(expr):
left, right = expr.args
inv_arg = left.arg
return MatrixSolve(inv_arg, right)
matinv_opt = ReplaceOptim(_matinv_predicate, _matinv_transform)
logaddexp_opt = ReplaceOptim(log(exp(_v)+exp(_w)), logaddexp(_v, _w))
logaddexp2_opt = ReplaceOptim(log(Pow(2, _v)+Pow(2, _w)), logaddexp2(_v, _w)*log(2))
# Collections of optimizations:
optims_c99 = (expm1_opt, log1p_opt, exp2_opt, log2_opt, log2const_opt)
optims_numpy = optims_c99 + (logaddexp_opt, logaddexp2_opt,) + sinc_opts
optims_scipy = (cosm1_opt,)
|
0d2b12192c235742b701232f5af6ad1445ef89829747ed713f0c923ec2cbf9ce | """
Do NOT manually edit this file.
Instead, run ./bin/ask_update.py.
"""
from sympy.assumptions.ask import Q
from sympy.assumptions.cnf import Literal
from sympy.core.cache import cacheit
@cacheit
def get_all_known_facts():
"""
Known facts between unary predicates as CNF clauses.
"""
return {
frozenset((Literal(Q.algebraic, False), Literal(Q.imaginary, True), Literal(Q.transcendental, False))),
frozenset((Literal(Q.algebraic, False), Literal(Q.negative, True), Literal(Q.transcendental, False))),
frozenset((Literal(Q.algebraic, False), Literal(Q.positive, True), Literal(Q.transcendental, False))),
frozenset((Literal(Q.algebraic, False), Literal(Q.rational, True))),
frozenset((Literal(Q.algebraic, False), Literal(Q.transcendental, False), Literal(Q.zero, True))),
frozenset((Literal(Q.algebraic, True), Literal(Q.finite, False))),
frozenset((Literal(Q.algebraic, True), Literal(Q.transcendental, True))),
frozenset((Literal(Q.antihermitian, False), Literal(Q.hermitian, False), Literal(Q.zero, True))),
frozenset((Literal(Q.antihermitian, False), Literal(Q.imaginary, True))),
frozenset((Literal(Q.commutative, False), Literal(Q.finite, True))),
frozenset((Literal(Q.commutative, False), Literal(Q.infinite, True))),
frozenset((Literal(Q.complex_elements, False), Literal(Q.real_elements, True))),
frozenset((Literal(Q.composite, False), Literal(Q.even, True), Literal(Q.positive, True), Literal(Q.prime, False))),
frozenset((Literal(Q.composite, True), Literal(Q.even, False), Literal(Q.odd, False))),
frozenset((Literal(Q.composite, True), Literal(Q.positive, False))),
frozenset((Literal(Q.composite, True), Literal(Q.prime, True))),
frozenset((Literal(Q.diagonal, False), Literal(Q.lower_triangular, True), Literal(Q.upper_triangular, True))),
frozenset((Literal(Q.diagonal, True), Literal(Q.lower_triangular, False))),
frozenset((Literal(Q.diagonal, True), Literal(Q.normal, False))),
frozenset((Literal(Q.diagonal, True), Literal(Q.symmetric, False))),
frozenset((Literal(Q.diagonal, True), Literal(Q.upper_triangular, False))),
frozenset((Literal(Q.even, False), Literal(Q.odd, False), Literal(Q.prime, True))),
frozenset((Literal(Q.even, False), Literal(Q.zero, True))),
frozenset((Literal(Q.even, True), Literal(Q.odd, True))),
frozenset((Literal(Q.even, True), Literal(Q.rational, False))),
frozenset((Literal(Q.finite, False), Literal(Q.transcendental, True))),
frozenset((Literal(Q.finite, True), Literal(Q.infinite, True))),
frozenset((Literal(Q.fullrank, False), Literal(Q.invertible, True))),
frozenset((Literal(Q.fullrank, True), Literal(Q.invertible, False), Literal(Q.square, True))),
frozenset((Literal(Q.hermitian, False), Literal(Q.negative, True))),
frozenset((Literal(Q.hermitian, False), Literal(Q.positive, True))),
frozenset((Literal(Q.hermitian, False), Literal(Q.zero, True))),
frozenset((Literal(Q.imaginary, True), Literal(Q.negative, True))),
frozenset((Literal(Q.imaginary, True), Literal(Q.positive, True))),
frozenset((Literal(Q.imaginary, True), Literal(Q.zero, True))),
frozenset((Literal(Q.infinite, False), Literal(Q.negative_infinite, True))),
frozenset((Literal(Q.infinite, False), Literal(Q.positive_infinite, True))),
frozenset((Literal(Q.integer_elements, True), Literal(Q.real_elements, False))),
frozenset((Literal(Q.invertible, False), Literal(Q.positive_definite, True))),
frozenset((Literal(Q.invertible, False), Literal(Q.singular, False))),
frozenset((Literal(Q.invertible, False), Literal(Q.unitary, True))),
frozenset((Literal(Q.invertible, True), Literal(Q.singular, True))),
frozenset((Literal(Q.invertible, True), Literal(Q.square, False))),
frozenset((Literal(Q.irrational, False), Literal(Q.negative, True), Literal(Q.rational, False))),
frozenset((Literal(Q.irrational, False), Literal(Q.positive, True), Literal(Q.rational, False))),
frozenset((Literal(Q.irrational, False), Literal(Q.rational, False), Literal(Q.zero, True))),
frozenset((Literal(Q.irrational, True), Literal(Q.negative, False), Literal(Q.positive, False), Literal(Q.zero, False))),
frozenset((Literal(Q.irrational, True), Literal(Q.rational, True))),
frozenset((Literal(Q.lower_triangular, False), Literal(Q.triangular, True), Literal(Q.upper_triangular, False))),
frozenset((Literal(Q.lower_triangular, True), Literal(Q.triangular, False))),
frozenset((Literal(Q.negative, False), Literal(Q.positive, False), Literal(Q.rational, True), Literal(Q.zero, False))),
frozenset((Literal(Q.negative, True), Literal(Q.negative_infinite, True))),
frozenset((Literal(Q.negative, True), Literal(Q.positive, True))),
frozenset((Literal(Q.negative, True), Literal(Q.positive_infinite, True))),
frozenset((Literal(Q.negative, True), Literal(Q.zero, True))),
frozenset((Literal(Q.negative_infinite, True), Literal(Q.positive, True))),
frozenset((Literal(Q.negative_infinite, True), Literal(Q.positive_infinite, True))),
frozenset((Literal(Q.negative_infinite, True), Literal(Q.zero, True))),
frozenset((Literal(Q.normal, False), Literal(Q.unitary, True))),
frozenset((Literal(Q.normal, True), Literal(Q.square, False))),
frozenset((Literal(Q.odd, True), Literal(Q.rational, False))),
frozenset((Literal(Q.orthogonal, False), Literal(Q.real_elements, True), Literal(Q.unitary, True))),
frozenset((Literal(Q.orthogonal, True), Literal(Q.positive_definite, False))),
frozenset((Literal(Q.orthogonal, True), Literal(Q.unitary, False))),
frozenset((Literal(Q.positive, False), Literal(Q.prime, True))),
frozenset((Literal(Q.positive, True), Literal(Q.positive_infinite, True))),
frozenset((Literal(Q.positive, True), Literal(Q.zero, True))),
frozenset((Literal(Q.positive_infinite, True), Literal(Q.zero, True))),
frozenset((Literal(Q.square, False), Literal(Q.symmetric, True))),
frozenset((Literal(Q.triangular, False), Literal(Q.unit_triangular, True))),
frozenset((Literal(Q.triangular, False), Literal(Q.upper_triangular, True)))
}
@cacheit
def get_known_facts_dict():
"""
Logical relations between unary predicates as dictionary.
Each key is a predicate, and item is two groups of predicates.
First group contains the predicates which are implied by the key, and
second group contains the predicates which are rejected by the key.
"""
return {
Q.algebraic: (set([Q.algebraic, Q.commutative, Q.complex, Q.finite]),
set([Q.infinite, Q.negative_infinite, Q.positive_infinite,
Q.transcendental])),
Q.antihermitian: (set([Q.antihermitian]), set([])),
Q.commutative: (set([Q.commutative]), set([])),
Q.complex: (set([Q.commutative, Q.complex, Q.finite]),
set([Q.infinite, Q.negative_infinite, Q.positive_infinite])),
Q.complex_elements: (set([Q.complex_elements]), set([])),
Q.composite: (set([Q.algebraic, Q.commutative, Q.complex, Q.composite,
Q.extended_nonnegative, Q.extended_nonzero,
Q.extended_positive, Q.extended_real, Q.finite, Q.hermitian,
Q.integer, Q.nonnegative, Q.nonzero, Q.positive, Q.rational,
Q.real]), set([Q.extended_negative, Q.extended_nonpositive,
Q.imaginary, Q.infinite, Q.irrational, Q.negative,
Q.negative_infinite, Q.nonpositive, Q.positive_infinite,
Q.prime, Q.transcendental, Q.zero])),
Q.diagonal: (set([Q.diagonal, Q.lower_triangular, Q.normal, Q.square,
Q.symmetric, Q.triangular, Q.upper_triangular]), set([])),
Q.even: (set([Q.algebraic, Q.commutative, Q.complex, Q.even,
Q.extended_real, Q.finite, Q.hermitian, Q.integer, Q.rational,
Q.real]), set([Q.imaginary, Q.infinite, Q.irrational,
Q.negative_infinite, Q.odd, Q.positive_infinite,
Q.transcendental])),
Q.extended_negative: (set([Q.commutative, Q.extended_negative,
Q.extended_nonpositive, Q.extended_nonzero, Q.extended_real]),
set([Q.composite, Q.extended_nonnegative, Q.extended_positive,
Q.imaginary, Q.nonnegative, Q.positive, Q.positive_infinite,
Q.prime, Q.zero])),
Q.extended_nonnegative: (set([Q.commutative, Q.extended_nonnegative,
Q.extended_real]), set([Q.extended_negative, Q.imaginary,
Q.negative, Q.negative_infinite])),
Q.extended_nonpositive: (set([Q.commutative, Q.extended_nonpositive,
Q.extended_real]), set([Q.composite, Q.extended_positive,
Q.imaginary, Q.positive, Q.positive_infinite, Q.prime])),
Q.extended_nonzero: (set([Q.commutative, Q.extended_nonzero,
Q.extended_real]), set([Q.imaginary, Q.zero])),
Q.extended_positive: (set([Q.commutative, Q.extended_nonnegative,
Q.extended_nonzero, Q.extended_positive, Q.extended_real]),
set([Q.extended_negative, Q.extended_nonpositive, Q.imaginary,
Q.negative, Q.negative_infinite, Q.nonpositive, Q.zero])),
Q.extended_real: (set([Q.commutative, Q.extended_real]),
set([Q.imaginary])),
Q.finite: (set([Q.commutative, Q.finite]), set([Q.infinite,
Q.negative_infinite, Q.positive_infinite])),
Q.fullrank: (set([Q.fullrank]), set([])),
Q.hermitian: (set([Q.hermitian]), set([])),
Q.imaginary: (set([Q.antihermitian, Q.commutative, Q.complex,
Q.finite, Q.imaginary]), set([Q.composite, Q.even,
Q.extended_negative, Q.extended_nonnegative,
Q.extended_nonpositive, Q.extended_nonzero,
Q.extended_positive, Q.extended_real, Q.infinite, Q.integer,
Q.irrational, Q.negative, Q.negative_infinite, Q.nonnegative,
Q.nonpositive, Q.nonzero, Q.odd, Q.positive,
Q.positive_infinite, Q.prime, Q.rational, Q.real, Q.zero])),
Q.infinite: (set([Q.commutative, Q.infinite]), set([Q.algebraic,
Q.complex, Q.composite, Q.even, Q.finite, Q.imaginary,
Q.integer, Q.irrational, Q.negative, Q.nonnegative,
Q.nonpositive, Q.nonzero, Q.odd, Q.positive, Q.prime,
Q.rational, Q.real, Q.transcendental, Q.zero])),
Q.integer: (set([Q.algebraic, Q.commutative, Q.complex,
Q.extended_real, Q.finite, Q.hermitian, Q.integer, Q.rational,
Q.real]), set([Q.imaginary, Q.infinite, Q.irrational,
Q.negative_infinite, Q.positive_infinite, Q.transcendental])),
Q.integer_elements: (set([Q.complex_elements, Q.integer_elements,
Q.real_elements]), set([])),
Q.invertible: (set([Q.fullrank, Q.invertible, Q.square]),
set([Q.singular])),
Q.irrational: (set([Q.commutative, Q.complex, Q.extended_nonzero,
Q.extended_real, Q.finite, Q.hermitian, Q.irrational,
Q.nonzero, Q.real]), set([Q.composite, Q.even, Q.imaginary,
Q.infinite, Q.integer, Q.negative_infinite, Q.odd,
Q.positive_infinite, Q.prime, Q.rational, Q.zero])),
Q.is_true: (set([Q.is_true]), set([])),
Q.lower_triangular: (set([Q.lower_triangular, Q.triangular]), set([])),
Q.negative: (set([Q.commutative, Q.complex, Q.extended_negative,
Q.extended_nonpositive, Q.extended_nonzero, Q.extended_real,
Q.finite, Q.hermitian, Q.negative, Q.nonpositive, Q.nonzero,
Q.real]), set([Q.composite, Q.extended_nonnegative,
Q.extended_positive, Q.imaginary, Q.infinite,
Q.negative_infinite, Q.nonnegative, Q.positive,
Q.positive_infinite, Q.prime, Q.zero])),
Q.negative_infinite: (set([Q.commutative, Q.extended_negative,
Q.extended_nonpositive, Q.extended_nonzero, Q.extended_real,
Q.infinite, Q.negative_infinite]), set([Q.algebraic,
Q.complex, Q.composite, Q.even, Q.extended_nonnegative,
Q.extended_positive, Q.finite, Q.imaginary, Q.integer,
Q.irrational, Q.negative, Q.nonnegative, Q.nonpositive,
Q.nonzero, Q.odd, Q.positive, Q.positive_infinite, Q.prime,
Q.rational, Q.real, Q.transcendental, Q.zero])),
Q.nonnegative: (set([Q.commutative, Q.complex, Q.extended_nonnegative,
Q.extended_real, Q.finite, Q.hermitian, Q.nonnegative,
Q.real]), set([Q.extended_negative, Q.imaginary, Q.infinite,
Q.negative, Q.negative_infinite, Q.positive_infinite])),
Q.nonpositive: (set([Q.commutative, Q.complex, Q.extended_nonpositive,
Q.extended_real, Q.finite, Q.hermitian, Q.nonpositive,
Q.real]), set([Q.composite, Q.extended_positive, Q.imaginary,
Q.infinite, Q.negative_infinite, Q.positive,
Q.positive_infinite, Q.prime])),
Q.nonzero: (set([Q.commutative, Q.complex, Q.extended_nonzero,
Q.extended_real, Q.finite, Q.hermitian, Q.nonzero, Q.real]),
set([Q.imaginary, Q.infinite, Q.negative_infinite,
Q.positive_infinite, Q.zero])),
Q.normal: (set([Q.normal, Q.square]), set([])),
Q.odd: (set([Q.algebraic, Q.commutative, Q.complex,
Q.extended_nonzero, Q.extended_real, Q.finite, Q.hermitian,
Q.integer, Q.nonzero, Q.odd, Q.rational, Q.real]),
set([Q.even, Q.imaginary, Q.infinite, Q.irrational,
Q.negative_infinite, Q.positive_infinite, Q.transcendental,
Q.zero])),
Q.orthogonal: (set([Q.fullrank, Q.invertible, Q.normal, Q.orthogonal,
Q.positive_definite, Q.square, Q.unitary]), set([Q.singular])),
Q.positive: (set([Q.commutative, Q.complex, Q.extended_nonnegative,
Q.extended_nonzero, Q.extended_positive, Q.extended_real,
Q.finite, Q.hermitian, Q.nonnegative, Q.nonzero, Q.positive,
Q.real]), set([Q.extended_negative, Q.extended_nonpositive,
Q.imaginary, Q.infinite, Q.negative, Q.negative_infinite,
Q.nonpositive, Q.positive_infinite, Q.zero])),
Q.positive_definite: (set([Q.fullrank, Q.invertible,
Q.positive_definite, Q.square]), set([Q.singular])),
Q.positive_infinite: (set([Q.commutative, Q.extended_nonnegative,
Q.extended_nonzero, Q.extended_positive, Q.extended_real,
Q.infinite, Q.positive_infinite]), set([Q.algebraic,
Q.complex, Q.composite, Q.even, Q.extended_negative,
Q.extended_nonpositive, Q.finite, Q.imaginary, Q.integer,
Q.irrational, Q.negative, Q.negative_infinite, Q.nonnegative,
Q.nonpositive, Q.nonzero, Q.odd, Q.positive, Q.prime,
Q.rational, Q.real, Q.transcendental, Q.zero])),
Q.prime: (set([Q.algebraic, Q.commutative, Q.complex,
Q.extended_nonnegative, Q.extended_nonzero,
Q.extended_positive, Q.extended_real, Q.finite, Q.hermitian,
Q.integer, Q.nonnegative, Q.nonzero, Q.positive, Q.prime,
Q.rational, Q.real]), set([Q.composite, Q.extended_negative,
Q.extended_nonpositive, Q.imaginary, Q.infinite, Q.irrational,
Q.negative, Q.negative_infinite, Q.nonpositive,
Q.positive_infinite, Q.transcendental, Q.zero])),
Q.rational: (set([Q.algebraic, Q.commutative, Q.complex,
Q.extended_real, Q.finite, Q.hermitian, Q.rational, Q.real]),
set([Q.imaginary, Q.infinite, Q.irrational,
Q.negative_infinite, Q.positive_infinite, Q.transcendental])),
Q.real: (set([Q.commutative, Q.complex, Q.extended_real, Q.finite,
Q.hermitian, Q.real]), set([Q.imaginary, Q.infinite,
Q.negative_infinite, Q.positive_infinite])),
Q.real_elements: (set([Q.complex_elements, Q.real_elements]), set([])),
Q.singular: (set([Q.singular]), set([Q.invertible, Q.orthogonal,
Q.positive_definite, Q.unitary])),
Q.square: (set([Q.square]), set([])),
Q.symmetric: (set([Q.square, Q.symmetric]), set([])),
Q.transcendental: (set([Q.commutative, Q.complex, Q.finite,
Q.transcendental]), set([Q.algebraic, Q.composite, Q.even,
Q.infinite, Q.integer, Q.negative_infinite, Q.odd,
Q.positive_infinite, Q.prime, Q.rational, Q.zero])),
Q.triangular: (set([Q.triangular]), set([])),
Q.unit_triangular: (set([Q.triangular, Q.unit_triangular]), set([])),
Q.unitary: (set([Q.fullrank, Q.invertible, Q.normal, Q.square,
Q.unitary]), set([Q.singular])),
Q.upper_triangular: (set([Q.triangular, Q.upper_triangular]), set([])),
Q.zero: (set([Q.algebraic, Q.commutative, Q.complex, Q.even,
Q.extended_nonnegative, Q.extended_nonpositive,
Q.extended_real, Q.finite, Q.hermitian, Q.integer,
Q.nonnegative, Q.nonpositive, Q.rational, Q.real, Q.zero]),
set([Q.composite, Q.extended_negative, Q.extended_nonzero,
Q.extended_positive, Q.imaginary, Q.infinite, Q.irrational,
Q.negative, Q.negative_infinite, Q.nonzero, Q.odd, Q.positive,
Q.positive_infinite, Q.prime, Q.transcendental])),
}
|
332dd6dea7cb3b1dc63ef7a81cc646150b1df5013b283f8377d726ff074e6ecb | """Module for querying SymPy objects about assumptions."""
from sympy.assumptions.assume import (global_assumptions, Predicate,
AppliedPredicate)
from sympy.assumptions.cnf import CNF, EncodedCNF, Literal
from sympy.core import sympify
from sympy.core.kind import BooleanKind
from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le
from sympy.logic.inference import satisfiable
from sympy.utilities.decorator import memoize_property
from sympy.utilities.exceptions import SymPyDeprecationWarning
# Memoization is necessary for the properties of AssumptionKeys to
# ensure that only one object of Predicate objects are created.
# This is because assumption handlers are registered on those objects.
class AssumptionKeys:
"""
This class contains all the supported keys by ``ask``.
It should be accessed via the instance ``sympy.Q``.
"""
# DO NOT add methods or properties other than predicate keys.
# SAT solver checks the properties of Q and use them to compute the
# fact system. Non-predicate attributes will break this.
@memoize_property
def hermitian(self):
from .handlers.sets import HermitianPredicate
return HermitianPredicate()
@memoize_property
def antihermitian(self):
from .handlers.sets import AntihermitianPredicate
return AntihermitianPredicate()
@memoize_property
def real(self):
from .handlers.sets import RealPredicate
return RealPredicate()
@memoize_property
def extended_real(self):
from .handlers.sets import ExtendedRealPredicate
return ExtendedRealPredicate()
@memoize_property
def imaginary(self):
from .handlers.sets import ImaginaryPredicate
return ImaginaryPredicate()
@memoize_property
def complex(self):
from .handlers.sets import ComplexPredicate
return ComplexPredicate()
@memoize_property
def algebraic(self):
from .handlers.sets import AlgebraicPredicate
return AlgebraicPredicate()
@memoize_property
def transcendental(self):
from .predicates.sets import TranscendentalPredicate
return TranscendentalPredicate()
@memoize_property
def integer(self):
from .handlers.sets import IntegerPredicate
return IntegerPredicate()
@memoize_property
def rational(self):
from .handlers.sets import RationalPredicate
return RationalPredicate()
@memoize_property
def irrational(self):
from .handlers.sets import IrrationalPredicate
return IrrationalPredicate()
@memoize_property
def finite(self):
from .handlers.calculus import FinitePredicate
return FinitePredicate()
@memoize_property
def infinite(self):
from .handlers.calculus import InfinitePredicate
return InfinitePredicate()
@memoize_property
def positive_infinite(self):
from .handlers.calculus import PositiveInfinitePredicate
return PositiveInfinitePredicate()
@memoize_property
def negative_infinite(self):
from .handlers.calculus import NegativeInfinitePredicate
return NegativeInfinitePredicate()
@memoize_property
def positive(self):
from .handlers.order import PositivePredicate
return PositivePredicate()
@memoize_property
def negative(self):
from .handlers.order import NegativePredicate
return NegativePredicate()
@memoize_property
def zero(self):
from .handlers.order import ZeroPredicate
return ZeroPredicate()
@memoize_property
def extended_positive(self):
from .handlers.order import ExtendedPositivePredicate
return ExtendedPositivePredicate()
@memoize_property
def extended_negative(self):
from .handlers.order import ExtendedNegativePredicate
return ExtendedNegativePredicate()
@memoize_property
def nonzero(self):
from .handlers.order import NonZeroPredicate
return NonZeroPredicate()
@memoize_property
def nonpositive(self):
from .handlers.order import NonPositivePredicate
return NonPositivePredicate()
@memoize_property
def nonnegative(self):
from .handlers.order import NonNegativePredicate
return NonNegativePredicate()
@memoize_property
def extended_nonzero(self):
from .handlers.order import ExtendedNonZeroPredicate
return ExtendedNonZeroPredicate()
@memoize_property
def extended_nonpositive(self):
from .handlers.order import ExtendedNonPositivePredicate
return ExtendedNonPositivePredicate()
@memoize_property
def extended_nonnegative(self):
from .handlers.order import ExtendedNonNegativePredicate
return ExtendedNonNegativePredicate()
@memoize_property
def even(self):
from .handlers.ntheory import EvenPredicate
return EvenPredicate()
@memoize_property
def odd(self):
from .handlers.ntheory import OddPredicate
return OddPredicate()
@memoize_property
def prime(self):
from .handlers.ntheory import PrimePredicate
return PrimePredicate()
@memoize_property
def composite(self):
from .handlers.ntheory import CompositePredicate
return CompositePredicate()
@memoize_property
def commutative(self):
from .handlers.common import CommutativePredicate
return CommutativePredicate()
@memoize_property
def is_true(self):
from .handlers.common import IsTruePredicate
return IsTruePredicate()
@memoize_property
def symmetric(self):
from .handlers.matrices import SymmetricPredicate
return SymmetricPredicate()
@memoize_property
def invertible(self):
from .handlers.matrices import InvertiblePredicate
return InvertiblePredicate()
@memoize_property
def orthogonal(self):
from .handlers.matrices import OrthogonalPredicate
return OrthogonalPredicate()
@memoize_property
def unitary(self):
from .handlers.matrices import UnitaryPredicate
return UnitaryPredicate()
@memoize_property
def positive_definite(self):
from .handlers.matrices import PositiveDefinitePredicate
return PositiveDefinitePredicate()
@memoize_property
def upper_triangular(self):
from .handlers.matrices import UpperTriangularPredicate
return UpperTriangularPredicate()
@memoize_property
def lower_triangular(self):
from .handlers.matrices import LowerTriangularPredicate
return LowerTriangularPredicate()
@memoize_property
def diagonal(self):
from .handlers.matrices import DiagonalPredicate
return DiagonalPredicate()
@memoize_property
def fullrank(self):
from .handlers.matrices import FullRankPredicate
return FullRankPredicate()
@memoize_property
def square(self):
from .handlers.matrices import SquarePredicate
return SquarePredicate()
@memoize_property
def integer_elements(self):
from .handlers.matrices import IntegerElementsPredicate
return IntegerElementsPredicate()
@memoize_property
def real_elements(self):
from .handlers.matrices import RealElementsPredicate
return RealElementsPredicate()
@memoize_property
def complex_elements(self):
from .handlers.matrices import ComplexElementsPredicate
return ComplexElementsPredicate()
@memoize_property
def singular(self):
from .predicates.matrices import SingularPredicate
return SingularPredicate()
@memoize_property
def normal(self):
from .predicates.matrices import NormalPredicate
return NormalPredicate()
@memoize_property
def triangular(self):
from .predicates.matrices import TriangularPredicate
return TriangularPredicate()
@memoize_property
def unit_triangular(self):
from .predicates.matrices import UnitTriangularPredicate
return UnitTriangularPredicate()
@memoize_property
def eq(self):
from .relation.equality import EqualityPredicate
return EqualityPredicate()
@memoize_property
def ne(self):
from .relation.equality import UnequalityPredicate
return UnequalityPredicate()
@memoize_property
def gt(self):
from .relation.equality import StrictGreaterThanPredicate
return StrictGreaterThanPredicate()
@memoize_property
def ge(self):
from .relation.equality import GreaterThanPredicate
return GreaterThanPredicate()
@memoize_property
def lt(self):
from .relation.equality import StrictLessThanPredicate
return StrictLessThanPredicate()
@memoize_property
def le(self):
from .relation.equality import LessThanPredicate
return LessThanPredicate()
Q = AssumptionKeys()
def _extract_all_facts(assump, exprs):
"""
Extract all relevant assumptions from *assump* with respect to given *exprs*.
Parameters
==========
assump : sympy.assumptions.cnf.CNF
exprs : tuple of expressions
Returns
=======
sympy.assumptions.cnf.CNF
Examples
========
>>> from sympy import Q
>>> from sympy.assumptions.cnf import CNF
>>> from sympy.assumptions.ask import _extract_all_facts
>>> from sympy.abc import x, y
>>> assump = CNF.from_prop(Q.positive(x) & Q.integer(y))
>>> exprs = (x,)
>>> cnf = _extract_all_facts(assump, exprs)
>>> cnf.clauses
{frozenset({Literal(Q.positive, False)})}
"""
facts = set()
for clause in assump.clauses:
args = []
for literal in clause:
if isinstance(literal.lit, AppliedPredicate) and len(literal.lit.arguments) == 1:
if literal.lit.arg in exprs:
# Add literal if it has matching in it
args.append(Literal(literal.lit.function, literal.is_Not))
else:
# If any of the literals doesn't have matching expr don't add the whole clause.
break
else:
if args:
facts.add(frozenset(args))
return CNF(facts)
def ask(proposition, assumptions=True, context=global_assumptions):
"""
Function to evaluate the proposition with assumptions.
Explanation
===========
This function evaluates the proposition to ``True`` or ``False`` if
the truth value can be determined. If not, it returns ``None``.
It should be discerned from :func:`~.refine()` which, when applied to a
proposition, simplifies the argument to symbolic ``Boolean`` instead of
Python built-in ``True``, ``False`` or ``None``.
**Syntax**
* ask(proposition)
Evaluate the *proposition* in global assumption context.
* ask(proposition, assumptions)
Evaluate the *proposition* with respect to *assumptions* in
global assumption context.
Parameters
==========
proposition : Any boolean expression.
Proposition which will be evaluated to boolean value. If this is
not ``AppliedPredicate``, it will be wrapped by ``Q.is_true``.
assumptions : Any boolean expression, optional.
Local assumptions to evaluate the *proposition*.
context : AssumptionsContext, optional.
Default assumptions to evaluate the *proposition*. By default,
this is ``sympy.assumptions.global_assumptions`` variable.
Returns
=======
``True``, ``False``, or ``None``
Raises
======
TypeError : *proposition* or *assumptions* is not valid logical expression.
ValueError : assumptions are inconsistent.
Examples
========
>>> from sympy import ask, Q, pi
>>> from sympy.abc import x, y
>>> ask(Q.rational(pi))
False
>>> ask(Q.even(x*y), Q.even(x) & Q.integer(y))
True
>>> ask(Q.prime(4*x), Q.integer(x))
False
If the truth value cannot be determined, ``None`` will be returned.
>>> print(ask(Q.odd(3*x))) # cannot determine unless we know x
None
``ValueError`` is raised if assumptions are inconsistent.
>>> ask(Q.integer(x), Q.even(x) & Q.odd(x))
Traceback (most recent call last):
...
ValueError: inconsistent assumptions Q.even(x) & Q.odd(x)
Notes
=====
Relations in assumptions are not implemented (yet), so the following
will not give a meaningful result.
>>> ask(Q.positive(x), x > 0)
It is however a work in progress.
See Also
========
sympy.assumptions.refine.refine : Simplification using assumptions.
Proposition is not reduced to ``None`` if the truth value cannot
be determined.
"""
from sympy.assumptions.satask import satask
proposition = sympify(proposition)
assumptions = sympify(assumptions)
if isinstance(proposition, Predicate) or proposition.kind is not BooleanKind:
raise TypeError("proposition must be a valid logical expression")
if isinstance(assumptions, Predicate) or assumptions.kind is not BooleanKind:
raise TypeError("assumptions must be a valid logical expression")
binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le}
if isinstance(proposition, AppliedPredicate):
key, args = proposition.function, proposition.arguments
elif proposition.func in binrelpreds:
key, args = binrelpreds[proposition.func], proposition.args
else:
key, args = Q.is_true, (proposition,)
# convert local and global assumptions to CNF
assump_cnf = CNF.from_prop(assumptions)
assump_cnf.extend(context)
# extract the relevant facts from assumptions with respect to args
local_facts = _extract_all_facts(assump_cnf, args)
# convert default facts and assumed facts to encoded CNF
known_facts_cnf = get_all_known_facts()
enc_cnf = EncodedCNF()
enc_cnf.from_cnf(CNF(known_facts_cnf))
enc_cnf.add_from_cnf(local_facts)
# check the satisfiability of given assumptions
if local_facts.clauses and satisfiable(enc_cnf) is False:
raise ValueError("inconsistent assumptions %s" % assumptions)
# quick computation for single fact
res = _ask_single_fact(key, local_facts)
if res is not None:
return res
# direct resolution method, no logic
res = key(*args)._eval_ask(assumptions)
if res is not None:
return bool(res)
# using satask (still costly)
res = satask(proposition, assumptions=assumptions, context=context)
return res
def _ask_single_fact(key, local_facts):
"""
Compute the truth value of single predicate using assumptions.
Parameters
==========
key : sympy.assumptions.assume.Predicate
Proposition predicate.
local_facts : sympy.assumptions.cnf.CNF
Local assumption in CNF form.
Returns
=======
``True``, ``False`` or ``None``
Examples
========
>>> from sympy import Q
>>> from sympy.assumptions.cnf import CNF
>>> from sympy.assumptions.ask import _ask_single_fact
If prerequisite of proposition is rejected by the assumption,
return ``False``.
>>> key, assump = Q.zero, ~Q.zero
>>> local_facts = CNF.from_prop(assump)
>>> _ask_single_fact(key, local_facts)
False
>>> key, assump = Q.zero, ~Q.even
>>> local_facts = CNF.from_prop(assump)
>>> _ask_single_fact(key, local_facts)
False
If assumption implies the proposition, return ``True``.
>>> key, assump = Q.even, Q.zero
>>> local_facts = CNF.from_prop(assump)
>>> _ask_single_fact(key, local_facts)
True
If proposition rejects the assumption, return ``False``.
>>> key, assump = Q.even, Q.odd
>>> local_facts = CNF.from_prop(assump)
>>> _ask_single_fact(key, local_facts)
False
"""
if local_facts.clauses:
known_facts_dict = get_known_facts_dict()
if len(local_facts.clauses) == 1:
cl, = local_facts.clauses
if len(cl) == 1:
f, = cl
prop_facts = known_facts_dict.get(key, None)
prop_req = prop_facts[0] if prop_facts is not None else set()
if f.is_Not and f.arg in prop_req:
# the prerequisite of proposition is rejected
return False
for clause in local_facts.clauses:
if len(clause) == 1:
f, = clause
prop_facts = known_facts_dict.get(f.arg, None) if not f.is_Not else None
if prop_facts is None:
continue
prop_req, prop_rej = prop_facts
if key in prop_req:
# assumption implies the proposition
return True
elif key in prop_rej:
# proposition rejects the assumption
return False
return None
def register_handler(key, handler):
"""
Register a handler in the ask system. key must be a string and handler a
class inheriting from AskHandler.
.. deprecated:: 1.8.
Use multipledispatch handler instead. See :obj:`~.Predicate`.
"""
SymPyDeprecationWarning(
feature="register_handler() function",
useinstead="multipledispatch handler of Predicate",
issue=20873,
deprecated_since_version="1.8"
).warn()
if isinstance(key, Predicate):
key = key.name.name
Qkey = getattr(Q, key, None)
if Qkey is not None:
Qkey.add_handler(handler)
else:
setattr(Q, key, Predicate(key, handlers=[handler]))
def remove_handler(key, handler):
"""
Removes a handler from the ask system. Same syntax as register_handler
.. deprecated:: 1.8.
Use multipledispatch handler instead. See :obj:`~.Predicate`.
"""
SymPyDeprecationWarning(
feature="remove_handler() function",
useinstead="multipledispatch handler of Predicate",
issue=20873,
deprecated_since_version="1.8"
).warn()
if isinstance(key, Predicate):
key = key.name.name
getattr(Q, key).remove_handler(handler)
from sympy.assumptions.ask_generated import (get_all_known_facts,
get_known_facts_dict)
|
0bff209047116a9eacd0ea0624da916318a72b0ee92e3de22c8ebfc00e670156 | """
Module to evaluate the proposition with assumptions using SAT algorithm.
"""
from sympy import Symbol, S
from sympy.assumptions.ask_generated import get_all_known_facts
from sympy.assumptions.assume import global_assumptions, AppliedPredicate
from sympy.assumptions.sathandlers import class_fact_registry
from sympy.core import oo
from sympy.logic.inference import satisfiable
from sympy.assumptions.cnf import CNF, EncodedCNF
def satask(proposition, assumptions=True, context=global_assumptions,
use_known_facts=True, iterations=oo):
"""
Function to evaluate the proposition with assumptions using SAT algorithm.
This function extracts every fact relevant to the expressions composing
proposition and assumptions. For example, if a predicate containing
``Abs(x)`` is proposed, then ``Q.zero(Abs(x)) | Q.positive(Abs(x))``
will be found and passed to SAT solver because ``Q.nonnegative`` is
registered as a fact for ``Abs``.
Proposition is evaluated to ``True`` or ``False`` if the truth value can be
determined. If not, ``None`` is returned.
Parameters
==========
proposition : Any boolean expression.
Proposition which will be evaluated to boolean value.
assumptions : Any boolean expression, optional.
Local assumptions to evaluate the *proposition*.
context : AssumptionsContext, optional.
Default assumptions to evaluate the *proposition*. By default,
this is ``sympy.assumptions.global_assumptions`` variable.
use_known_facts : bool, optional.
If ``True``, facts from ``sympy.assumptions.ask_generated``
module are passed to SAT solver as well.
iterations : int, optional.
Number of times that relevant facts are recursively extracted.
Default is infinite times until no new fact is found.
Returns
=======
``True``, ``False``, or ``None``
Examples
========
>>> from sympy import Abs, Q
>>> from sympy.assumptions.satask import satask
>>> from sympy.abc import x
>>> satask(Q.zero(Abs(x)), Q.zero(x))
True
"""
props = CNF.from_prop(proposition)
_props = CNF.from_prop(~proposition)
assumptions = CNF.from_prop(assumptions)
context_cnf = CNF()
if context:
context_cnf = context_cnf.extend(context)
sat = get_all_relevant_facts(props, assumptions, context_cnf,
use_known_facts=use_known_facts, iterations=iterations)
sat.add_from_cnf(assumptions)
if context:
sat.add_from_cnf(context_cnf)
return check_satisfiability(props, _props, sat)
def check_satisfiability(prop, _prop, factbase):
sat_true = factbase.copy()
sat_false = factbase.copy()
sat_true.add_from_cnf(prop)
sat_false.add_from_cnf(_prop)
can_be_true = satisfiable(sat_true)
can_be_false = satisfiable(sat_false)
if can_be_true and can_be_false:
return None
if can_be_true and not can_be_false:
return True
if not can_be_true and can_be_false:
return False
if not can_be_true and not can_be_false:
# TODO: Run additional checks to see which combination of the
# assumptions, global_assumptions, and relevant_facts are
# inconsistent.
raise ValueError("Inconsistent assumptions")
def extract_predargs(proposition, assumptions=None, context=None):
"""
Extract every expression in the argument of predicates from *proposition*,
*assumptions* and *context*.
Parameters
==========
proposition : sympy.assumptions.cnf.CNF
assumptions : sympy.assumptions.cnf.CNF, optional.
context : sympy.assumptions.cnf.CNF, optional.
CNF generated from assumptions context.
Examples
========
>>> from sympy import Q, Abs
>>> from sympy.assumptions.cnf import CNF
>>> from sympy.assumptions.satask import extract_predargs
>>> from sympy.abc import x, y
>>> props = CNF.from_prop(Q.zero(Abs(x*y)))
>>> assump = CNF.from_prop(Q.zero(x) & Q.zero(y))
>>> extract_predargs(props, assump)
{x, y, Abs(x*y)}
"""
req_keys = find_symbols(proposition)
keys = proposition.all_predicates()
# XXX: We need this since True/False are not Basic
lkeys = set()
if assumptions:
lkeys |= assumptions.all_predicates()
if context:
lkeys |= context.all_predicates()
lkeys = lkeys - {S.true, S.false}
tmp_keys = None
while tmp_keys != set():
tmp = set()
for l in lkeys:
syms = find_symbols(l)
if (syms & req_keys) != set():
tmp |= syms
tmp_keys = tmp - req_keys
req_keys |= tmp_keys
keys |= {l for l in lkeys if find_symbols(l) & req_keys != set()}
exprs = set()
for key in keys:
if isinstance(key, AppliedPredicate):
exprs |= set(key.arguments)
else:
exprs.add(key)
return exprs
def find_symbols(pred):
"""
Find every :obj:`~.Symbol` in *pred*.
Parameters
==========
pred : sympy.assumptions.cnf.CNF, or any Expr.
"""
if isinstance(pred, CNF):
symbols = set()
for a in pred.all_predicates():
symbols |= find_symbols(a)
return symbols
return pred.atoms(Symbol)
def get_relevant_clsfacts(exprs, relevant_facts=None):
"""
Extract relevant facts from the items in *exprs*. Facts are defined in
``assumptions.sathandlers`` module.
This function is recursively called by ``get_all_relevant_facts()``.
Parameters
==========
exprs : set
Expressions whose relevant facts are searched.
relevant_facts : sympy.assumptions.cnf.CNF, optional.
Pre-discovered relevant facts.
Returns
=======
exprs : set
Candidates for next relevant fact searching.
relevant_facts : sympy.assumptions.cnf.CNF
Updated relevant facts.
Examples
========
Here, we will see how facts relevant to ``Abs(x*y)`` are recursively
extracted. On the first run, set containing the expression is passed
without pre-discovered relevant facts. The result is a set containig
candidates for next run, and ``CNF()`` instance containing facts
which are relevant to ``Abs`` and its argument.
>>> from sympy import Abs
>>> from sympy.assumptions.satask import get_relevant_clsfacts
>>> from sympy.abc import x, y
>>> exprs = {Abs(x*y)}
>>> exprs, facts = get_relevant_clsfacts(exprs)
>>> exprs
{x*y}
>>> facts.clauses #doctest: +SKIP
{frozenset({Literal(Q.odd(Abs(x*y)), False), Literal(Q.odd(x*y), True)}),
frozenset({Literal(Q.zero(Abs(x*y)), False), Literal(Q.zero(x*y), True)}),
frozenset({Literal(Q.even(Abs(x*y)), False), Literal(Q.even(x*y), True)}),
frozenset({Literal(Q.zero(Abs(x*y)), True), Literal(Q.zero(x*y), False)}),
frozenset({Literal(Q.even(Abs(x*y)), False),
Literal(Q.odd(Abs(x*y)), False),
Literal(Q.odd(x*y), True)}),
frozenset({Literal(Q.even(Abs(x*y)), False),
Literal(Q.even(x*y), True),
Literal(Q.odd(Abs(x*y)), False)}),
frozenset({Literal(Q.positive(Abs(x*y)), False),
Literal(Q.zero(Abs(x*y)), False)})}
We pass the first run's results to the second run, and get the expressions
for next run and updated facts.
>>> exprs, facts = get_relevant_clsfacts(exprs, relevant_facts=facts)
>>> exprs
{x, y}
On final run, no more candidate is returned thus we know that all
relevant facts are successfully retrieved.
>>> exprs, facts = get_relevant_clsfacts(exprs, relevant_facts=facts)
>>> exprs
set()
"""
if not relevant_facts:
relevant_facts = CNF()
newexprs = set()
for expr in exprs:
for fact in class_fact_registry(expr):
newfact = CNF.to_CNF(fact)
relevant_facts = relevant_facts._and(newfact)
for key in newfact.all_predicates():
if isinstance(key, AppliedPredicate):
newexprs |= set(key.arguments)
return newexprs - exprs, relevant_facts
def get_all_relevant_facts(proposition, assumptions, context,
use_known_facts=True, iterations=oo):
"""
Extract all relevant facts from *proposition* and *assumptions*.
This function extracts the facts by recursively calling
``get_relevant_clsfacts()``. Extracted facts are converted to
``EncodedCNF`` and returned.
Parameters
==========
proposition : sympy.assumptions.cnf.CNF
CNF generated from proposition expression.
assumptions : sympy.assumptions.cnf.CNF
CNF generated from assumption expression.
context : sympy.assumptions.cnf.CNF
CNF generated from assumptions context.
use_known_facts : bool, optional.
If ``True``, facts from ``sympy.assumptions.ask_generated``
module are encoded as well.
iterations : int, optional.
Number of times that relevant facts are recursively extracted.
Default is infinite times until no new fact is found.
Returns
=======
sympy.assumptions.cnf.EncodedCNF
Examples
========
>>> from sympy import Q
>>> from sympy.assumptions.cnf import CNF
>>> from sympy.assumptions.satask import get_all_relevant_facts
>>> from sympy.abc import x, y
>>> props = CNF.from_prop(Q.nonzero(x*y))
>>> assump = CNF.from_prop(Q.nonzero(x))
>>> context = CNF.from_prop(Q.nonzero(y))
>>> get_all_relevant_facts(props, assump, context) #doctest: +SKIP
<sympy.assumptions.cnf.EncodedCNF at 0x7f09faa6ccd0>
"""
# The relevant facts might introduce new keys, e.g., Q.zero(x*y) will
# introduce the keys Q.zero(x) and Q.zero(y), so we need to run it until
# we stop getting new things. Hopefully this strategy won't lead to an
# infinite loop in the future.
i = 0
relevant_facts = CNF()
all_exprs = set()
while True:
if i == 0:
exprs = extract_predargs(proposition, assumptions, context)
all_exprs |= exprs
exprs, relevant_facts = get_relevant_clsfacts(exprs, relevant_facts)
i += 1
if i >= iterations:
break
if not exprs:
break
if use_known_facts:
known_facts_CNF = CNF()
known_facts_CNF.add_clauses(get_all_known_facts())
kf_encoded = EncodedCNF()
kf_encoded.from_cnf(known_facts_CNF)
def translate_literal(lit, delta):
if lit > 0:
return lit + delta
else:
return lit - delta
def translate_data(data, delta):
return [{translate_literal(i, delta) for i in clause} for clause in data]
data = []
symbols = []
n_lit = len(kf_encoded.symbols)
for i, expr in enumerate(all_exprs):
symbols += [pred(expr) for pred in kf_encoded.symbols]
data += translate_data(kf_encoded.data, i * n_lit)
encoding = dict(list(zip(symbols, range(1, len(symbols)+1))))
ctx = EncodedCNF(data, encoding)
else:
ctx = EncodedCNF()
ctx.add_from_cnf(relevant_facts)
return ctx
|
b5496422436c191a39957451fde67495d081f7476f25938e47a8d1d4fec9b52f | """
Known facts in assumptions module.
This module defines the facts between unary predicates in ``get_known_facts()``,
and supports functions to generate the contents in
``sympy.assumptions.ask_generated`` file.
"""
from sympy.assumptions import Q
from sympy.assumptions.assume import AppliedPredicate
from sympy.core.cache import cacheit
from sympy.core.symbol import Symbol
from sympy.logic.boolalg import (to_cnf, And, Not, Implies, Equivalent,
Exclusive,)
from sympy.logic.inference import satisfiable
@cacheit
def get_composite_predicates():
# To reduce the complexity of sat solver, these predicates are
# transformed into the combination of primitive predicates.
return {
Q.real : Q.negative | Q.zero | Q.positive,
Q.integer : Q.even | Q.odd,
Q.nonpositive : Q.negative | Q.zero,
Q.nonzero : Q.negative | Q.positive,
Q.nonnegative : Q.zero | Q.positive,
Q.extended_real : Q.negative_infinite | Q.negative | Q.zero | Q.positive | Q.positive_infinite,
Q.extended_positive: Q.positive | Q.positive_infinite,
Q.extended_negative: Q.negative | Q.negative_infinite,
Q.extended_nonzero: Q.negative_infinite | Q.negative | Q.positive | Q.positive_infinite,
Q.extended_nonpositive: Q.negative_infinite | Q.negative | Q.zero,
Q.extended_nonnegative: Q.zero | Q.positive | Q.positive_infinite,
Q.complex : Q.algebraic | Q.transcendental
}
@cacheit
def get_known_facts(x=None):
"""
Facts between unary predicates.
Parameters
==========
x : Symbol, optional
Placeholder symbol for unary facts. Default is ``Symbol('x')``.
Returns
=======
fact : Known facts in conjugated normal form.
"""
if x is None:
x = Symbol('x')
fact = And(
# primitive predicates for extended real exclude each other.
Exclusive(Q.negative_infinite(x), Q.negative(x), Q.zero(x),
Q.positive(x), Q.positive_infinite(x)),
# build complex plane
Exclusive(Q.real(x), Q.imaginary(x)),
Implies(Q.real(x) | Q.imaginary(x), Q.complex(x)),
# other subsets of complex
Exclusive(Q.transcendental(x), Q.algebraic(x)),
Equivalent(Q.real(x), Q.rational(x) | Q.irrational(x)),
Exclusive(Q.irrational(x), Q.rational(x)),
Implies(Q.rational(x), Q.algebraic(x)),
# integers
Exclusive(Q.even(x), Q.odd(x)),
Implies(Q.integer(x), Q.rational(x)),
Implies(Q.zero(x), Q.even(x)),
Exclusive(Q.composite(x), Q.prime(x)),
Implies(Q.composite(x) | Q.prime(x), Q.integer(x) & Q.positive(x)),
Implies(Q.even(x) & Q.positive(x) & ~Q.prime(x), Q.composite(x)),
# hermitian and antihermitian
Implies(Q.real(x), Q.hermitian(x)),
Implies(Q.imaginary(x), Q.antihermitian(x)),
Implies(Q.zero(x), Q.hermitian(x) | Q.antihermitian(x)),
# define finity and infinity, and build extended real line
Exclusive(Q.infinite(x), Q.finite(x)),
Implies(Q.complex(x), Q.finite(x)),
Implies(Q.negative_infinite(x) | Q.positive_infinite(x), Q.infinite(x)),
# commutativity
Implies(Q.finite(x) | Q.infinite(x), Q.commutative(x)),
# matrices
Implies(Q.orthogonal(x), Q.positive_definite(x)),
Implies(Q.orthogonal(x), Q.unitary(x)),
Implies(Q.unitary(x) & Q.real_elements(x), Q.orthogonal(x)),
Implies(Q.unitary(x), Q.normal(x)),
Implies(Q.unitary(x), Q.invertible(x)),
Implies(Q.normal(x), Q.square(x)),
Implies(Q.diagonal(x), Q.normal(x)),
Implies(Q.positive_definite(x), Q.invertible(x)),
Implies(Q.diagonal(x), Q.upper_triangular(x)),
Implies(Q.diagonal(x), Q.lower_triangular(x)),
Implies(Q.lower_triangular(x), Q.triangular(x)),
Implies(Q.upper_triangular(x), Q.triangular(x)),
Implies(Q.triangular(x), Q.upper_triangular(x) | Q.lower_triangular(x)),
Implies(Q.upper_triangular(x) & Q.lower_triangular(x), Q.diagonal(x)),
Implies(Q.diagonal(x), Q.symmetric(x)),
Implies(Q.unit_triangular(x), Q.triangular(x)),
Implies(Q.invertible(x), Q.fullrank(x)),
Implies(Q.invertible(x), Q.square(x)),
Implies(Q.symmetric(x), Q.square(x)),
Implies(Q.fullrank(x) & Q.square(x), Q.invertible(x)),
Equivalent(Q.invertible(x), ~Q.singular(x)),
Implies(Q.integer_elements(x), Q.real_elements(x)),
Implies(Q.real_elements(x), Q.complex_elements(x)),
)
return fact
def generate_known_facts_dict(keys, fact):
"""
Computes and returns a dictionary which contains the relations between
unary predicates.
Each key is a predicate, and item is two groups of predicates.
First group contains the predicates which are implied by the key, and
second group contains the predicates which are rejected by the key.
All predicates in *keys* and *fact* must be unary and have same placeholder
symbol.
Parameters
==========
keys : list of AppliedPredicate instances.
fact : Fact between predicates in conjugated normal form.
Examples
========
>>> from sympy import Q
>>> from sympy.assumptions.facts import generate_known_facts_dict
>>> from sympy.logic.boolalg import And, Implies
>>> from sympy.abc import x
>>> keys = [Q.even(x), Q.odd(x), Q.zero(x)]
>>> fact = And(Implies(Q.even(x), ~Q.odd(x)),
... Implies(Q.zero(x), Q.even(x)))
>>> generate_known_facts_dict(keys, fact)
{Q.even: ({Q.even}, {Q.odd}),
Q.odd: ({Q.odd}, {Q.even, Q.zero}),
Q.zero: ({Q.even, Q.zero}, {Q.odd})}
"""
fact_cnf = to_cnf(fact)
mapping = single_fact_lookup(keys, fact_cnf)
ret = {}
for key, value in mapping.items():
implied = set()
rejected = set()
for expr in value:
if isinstance(expr, AppliedPredicate):
implied.add(expr.function)
elif isinstance(expr, Not):
pred = expr.args[0]
rejected.add(pred.function)
ret[key.function] = (implied, rejected)
return ret
@cacheit
def get_known_facts_keys():
"""
Return every unary predicates registered to ``Q``.
This function is used to generate the keys for
``generate_known_facts_dict``.
"""
exclude = set()
for pred in [Q.eq, Q.ne, Q.gt, Q.lt, Q.ge, Q.le]:
# exclude polyadic predicates
exclude.add(pred)
result = []
for attr in Q.__class__.__dict__:
if attr.startswith('__'):
continue
pred = getattr(Q, attr)
if pred in exclude:
continue
result.append(pred)
return result
def single_fact_lookup(known_facts_keys, known_facts_cnf):
# Return the dictionary for quick lookup of single fact
mapping = {}
for key in known_facts_keys:
mapping[key] = {key}
for other_key in known_facts_keys:
if other_key != key:
if ask_full_inference(other_key, key, known_facts_cnf):
mapping[key].add(other_key)
if ask_full_inference(~other_key, key, known_facts_cnf):
mapping[key].add(~other_key)
return mapping
def ask_full_inference(proposition, assumptions, known_facts_cnf):
"""
Method for inferring properties about objects.
"""
if not satisfiable(And(known_facts_cnf, assumptions, proposition)):
return False
if not satisfiable(And(known_facts_cnf, assumptions, Not(proposition))):
return True
return None
|
14afec3c83945da0c6163f62eb3a883c90d4396707bad2449efe613cf9b71082 | from collections import defaultdict
from sympy.assumptions.ask import Q
from sympy.core import (Add, Mul, Pow, Number, NumberSymbol, Symbol)
from sympy.core.numbers import ImaginaryUnit
from sympy.functions.elementary.complexes import Abs
from sympy.logic.boolalg import (Equivalent, And, Or, Implies)
from sympy.matrices.expressions import MatMul
# APIs here may be subject to change
### Helper functions ###
def allargs(symbol, fact, expr):
"""
Apply all arguments of the expression to the fact structure.
Parameters
==========
symbol : Symbol
A placeholder symbol.
fact : Boolean
Resulting ``Boolean`` expression.
expr : Expr
Examples
========
>>> from sympy import Q
>>> from sympy.assumptions.sathandlers import allargs
>>> from sympy.abc import x, y
>>> allargs(x, Q.negative(x) | Q.positive(x), x*y)
(Q.negative(x) | Q.positive(x)) & (Q.negative(y) | Q.positive(y))
"""
return And(*[fact.subs(symbol, arg) for arg in expr.args])
def anyarg(symbol, fact, expr):
"""
Apply any argument of the expression to the fact structure.
Parameters
==========
symbol : Symbol
A placeholder symbol.
fact : Boolean
Resulting ``Boolean`` expression.
expr : Expr
Examples
========
>>> from sympy import Q
>>> from sympy.assumptions.sathandlers import anyarg
>>> from sympy.abc import x, y
>>> anyarg(x, Q.negative(x) & Q.positive(x), x*y)
(Q.negative(x) & Q.positive(x)) | (Q.negative(y) & Q.positive(y))
"""
return Or(*[fact.subs(symbol, arg) for arg in expr.args])
def exactlyonearg(symbol, fact, expr):
"""
Apply exactly one argument of the expression to the fact structure.
Parameters
==========
symbol : Symbol
A placeholder symbol.
fact : Boolean
Resulting ``Boolean`` expression.
expr : Expr
Examples
========
>>> from sympy import Q
>>> from sympy.assumptions.sathandlers import exactlyonearg
>>> from sympy.abc import x, y
>>> exactlyonearg(x, Q.positive(x), x*y)
(Q.positive(x) & ~Q.positive(y)) | (Q.positive(y) & ~Q.positive(x))
"""
pred_args = [fact.subs(symbol, arg) for arg in expr.args]
res = Or(*[And(pred_args[i], *[~lit for lit in pred_args[:i] +
pred_args[i+1:]]) for i in range(len(pred_args))])
return res
### Fact registry ###
class ClassFactRegistry:
"""
Register handlers against classes.
Explanation
===========
``register`` method registers the handler function for a class. Here,
handler function should return a single fact. ``multiregister`` method
registers the handler function for multiple classes. Here, handler function
should return a container of multiple facts.
``registry(expr)`` returns a set of facts for *expr*.
Examples
========
Here, we register the facts for ``Abs``.
>>> from sympy import Abs, Q
>>> from sympy.logic.boolalg import Equivalent
>>> from sympy.assumptions.sathandlers import ClassFactRegistry
>>> reg = ClassFactRegistry()
>>> @reg.register(Abs)
... def f1(expr):
... return Q.nonnegative(expr)
>>> @reg.register(Abs)
... def f2(expr):
... arg = expr.args[0]
... return Equivalent(~Q.zero(arg), ~Q.zero(expr))
Calling the registry with expression returns the defined facts for the
expression.
>>> from sympy.abc import x
>>> reg(Abs(x))
{Q.nonnegative(Abs(x)), Equivalent(~Q.zero(x), ~Q.zero(Abs(x)))}
Multiple facts can be registered at once by ``multiregister`` method.
>>> reg2 = ClassFactRegistry()
>>> @reg2.multiregister(Abs)
... def _(expr):
... arg = expr.args[0]
... return [Q.even(arg) >> Q.even(expr), Q.odd(arg) >> Q.odd(expr)]
>>> reg2(Abs(x))
{Implies(Q.even(x), Q.even(Abs(x))), Implies(Q.odd(x), Q.odd(Abs(x)))}
"""
def __init__(self):
self.singlefacts = defaultdict(frozenset)
self.multifacts = defaultdict(frozenset)
def register(self, cls):
def _(func):
self.singlefacts[cls] |= {func}
return func
return _
def multiregister(self, *classes):
def _(func):
for cls in classes:
self.multifacts[cls] |= {func}
return func
return _
def __getitem__(self, key):
ret1 = self.singlefacts[key]
for k in self.singlefacts:
if issubclass(key, k):
ret1 |= self.singlefacts[k]
ret2 = self.multifacts[key]
for k in self.multifacts:
if issubclass(key, k):
ret2 |= self.multifacts[k]
return ret1, ret2
def __call__(self, expr):
ret = set()
handlers1, handlers2 = self[expr.func]
for h in handlers1:
ret.add(h(expr))
for h in handlers2:
ret.update(h(expr))
return ret
class_fact_registry = ClassFactRegistry()
### Class fact registration ###
x = Symbol('x')
## Abs ##
@class_fact_registry.multiregister(Abs)
def _(expr):
arg = expr.args[0]
return [Q.nonnegative(expr),
Equivalent(~Q.zero(arg), ~Q.zero(expr)),
Q.even(arg) >> Q.even(expr),
Q.odd(arg) >> Q.odd(expr),
Q.integer(arg) >> Q.integer(expr),
]
### Add ##
@class_fact_registry.multiregister(Add)
def _(expr):
return [allargs(x, Q.positive(x), expr) >> Q.positive(expr),
allargs(x, Q.negative(x), expr) >> Q.negative(expr),
allargs(x, Q.real(x), expr) >> Q.real(expr),
allargs(x, Q.rational(x), expr) >> Q.rational(expr),
allargs(x, Q.integer(x), expr) >> Q.integer(expr),
exactlyonearg(x, ~Q.integer(x), expr) >> ~Q.integer(expr),
]
@class_fact_registry.register(Add)
def _(expr):
allargs_real = allargs(x, Q.real(x), expr)
onearg_irrational = exactlyonearg(x, Q.irrational(x), expr)
return Implies(allargs_real, Implies(onearg_irrational, Q.irrational(expr)))
### Mul ###
@class_fact_registry.multiregister(Mul)
def _(expr):
return [Equivalent(Q.zero(expr), anyarg(x, Q.zero(x), expr)),
allargs(x, Q.positive(x), expr) >> Q.positive(expr),
allargs(x, Q.real(x), expr) >> Q.real(expr),
allargs(x, Q.rational(x), expr) >> Q.rational(expr),
allargs(x, Q.integer(x), expr) >> Q.integer(expr),
exactlyonearg(x, ~Q.rational(x), expr) >> ~Q.integer(expr),
allargs(x, Q.commutative(x), expr) >> Q.commutative(expr),
]
@class_fact_registry.register(Mul)
def _(expr):
# Implicitly assumes Mul has more than one arg
# Would be allargs(x, Q.prime(x) | Q.composite(x)) except 1 is composite
# More advanced prime assumptions will require inequalities, as 1 provides
# a corner case.
allargs_prime = allargs(x, Q.prime(x), expr)
return Implies(allargs_prime, ~Q.prime(expr))
@class_fact_registry.register(Mul)
def _(expr):
# General Case: Odd number of imaginary args implies mul is imaginary(To be implemented)
allargs_imag_or_real = allargs(x, Q.imaginary(x) | Q.real(x), expr)
onearg_imaginary = exactlyonearg(x, Q.imaginary(x), expr)
return Implies(allargs_imag_or_real, Implies(onearg_imaginary, Q.imaginary(expr)))
@class_fact_registry.register(Mul)
def _(expr):
allargs_real = allargs(x, Q.real(x), expr)
onearg_irrational = exactlyonearg(x, Q.irrational(x), expr)
return Implies(allargs_real, Implies(onearg_irrational, Q.irrational(expr)))
@class_fact_registry.register(Mul)
def _(expr):
# Including the integer qualification means we don't need to add any facts
# for odd, since the assumptions already know that every integer is
# exactly one of even or odd.
allargs_integer = allargs(x, Q.integer(x), expr)
anyarg_even = anyarg(x, Q.even(x), expr)
return Implies(allargs_integer, Equivalent(anyarg_even, Q.even(expr)))
### MatMul ###
@class_fact_registry.register(MatMul)
def _(expr):
allargs_square = allargs(x, Q.square(x), expr)
allargs_invertible = allargs(x, Q.invertible(x), expr)
return Implies(allargs_square, Equivalent(Q.invertible(expr), allargs_invertible))
### Pow ###
@class_fact_registry.multiregister(Pow)
def _(expr):
base, exp = expr.base, expr.exp
return [
(Q.real(base) & Q.even(exp) & Q.nonnegative(exp)) >> Q.nonnegative(expr),
(Q.nonnegative(base) & Q.odd(exp) & Q.nonnegative(exp)) >> Q.nonnegative(expr),
(Q.nonpositive(base) & Q.odd(exp) & Q.nonnegative(exp)) >> Q.nonpositive(expr),
Equivalent(Q.zero(expr), Q.zero(base) & Q.positive(exp))
]
### Numbers ###
_old_assump_getters = {
Q.positive: lambda o: o.is_positive,
Q.zero: lambda o: o.is_zero,
Q.negative: lambda o: o.is_negative,
Q.rational: lambda o: o.is_rational,
Q.irrational: lambda o: o.is_irrational,
Q.even: lambda o: o.is_even,
Q.odd: lambda o: o.is_odd,
Q.imaginary: lambda o: o.is_imaginary,
Q.prime: lambda o: o.is_prime,
Q.composite: lambda o: o.is_composite,
}
@class_fact_registry.multiregister(Number, NumberSymbol, ImaginaryUnit)
def _(expr):
ret = []
for p, getter in _old_assump_getters.items():
pred = p(expr)
prop = getter(expr)
if prop is not None:
ret.append(Equivalent(pred, prop))
return ret
|
a1e60789a40c109b1632f74ca360a4af4be086b9dc3ce505a53190d0b462ef7f | from sympy import Order, S, log, limit, lcm_list, im, re, Dummy, Piecewise
from sympy.core import Add, Mul, Pow
from sympy.core.basic import Basic
from sympy.core.compatibility import iterable
from sympy.core.expr import AtomicExpr, Expr
from sympy.core.function import expand_mul
from sympy.core.numbers import _sympifyit, oo, zoo
from sympy.core.relational import is_le, is_lt, is_ge, is_gt
from sympy.core.sympify import _sympify
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.logic.boolalg import And
from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union,
Complement, EmptySet)
from sympy.sets.fancysets import ImageSet
from sympy.solvers.inequalities import solve_univariate_inequality
from sympy.utilities import filldedent
from sympy.multipledispatch import dispatch
def continuous_domain(f, symbol, domain):
"""
Returns the intervals in the given domain for which the function
is continuous.
This method is limited by the ability to determine the various
singularities and discontinuities of the given function.
Parameters
==========
f : Expr
The concerned function.
symbol : Symbol
The variable for which the intervals are to be determined.
domain : Interval
The domain over which the continuity of the symbol has to be checked.
Examples
========
>>> from sympy import Symbol, S, tan, log, pi, sqrt
>>> from sympy.sets import Interval
>>> from sympy.calculus.util import continuous_domain
>>> x = Symbol('x')
>>> continuous_domain(1/x, x, S.Reals)
Union(Interval.open(-oo, 0), Interval.open(0, oo))
>>> continuous_domain(tan(x), x, Interval(0, pi))
Union(Interval.Ropen(0, pi/2), Interval.Lopen(pi/2, pi))
>>> continuous_domain(sqrt(x - 2), x, Interval(-5, 5))
Interval(2, 5)
>>> continuous_domain(log(2*x - 1), x, S.Reals)
Interval.open(1/2, oo)
Returns
=======
Interval
Union of all intervals where the function is continuous.
Raises
======
NotImplementedError
If the method to determine continuity of such a function
has not yet been developed.
"""
from sympy.solvers.inequalities import solve_univariate_inequality
from sympy.calculus.singularities import singularities
if domain.is_subset(S.Reals):
constrained_interval = domain
for atom in f.atoms(Pow):
den = atom.exp.as_numer_denom()[1]
if den.is_even and den.is_nonzero:
constraint = solve_univariate_inequality(atom.base >= 0,
symbol).as_set()
constrained_interval = Intersection(constraint,
constrained_interval)
for atom in f.atoms(log):
constraint = solve_univariate_inequality(atom.args[0] > 0,
symbol).as_set()
constrained_interval = Intersection(constraint,
constrained_interval)
return constrained_interval - singularities(f, symbol, domain)
def function_range(f, symbol, domain):
"""
Finds the range of a function in a given domain.
This method is limited by the ability to determine the singularities and
determine limits.
Parameters
==========
f : Expr
The concerned function.
symbol : Symbol
The variable for which the range of function is to be determined.
domain : Interval
The domain under which the range of the function has to be found.
Examples
========
>>> from sympy import Symbol, S, exp, log, pi, sqrt, sin, tan
>>> from sympy.sets import Interval
>>> from sympy.calculus.util import function_range
>>> x = Symbol('x')
>>> function_range(sin(x), x, Interval(0, 2*pi))
Interval(-1, 1)
>>> function_range(tan(x), x, Interval(-pi/2, pi/2))
Interval(-oo, oo)
>>> function_range(1/x, x, S.Reals)
Union(Interval.open(-oo, 0), Interval.open(0, oo))
>>> function_range(exp(x), x, S.Reals)
Interval.open(0, oo)
>>> function_range(log(x), x, S.Reals)
Interval(-oo, oo)
>>> function_range(sqrt(x), x , Interval(-5, 9))
Interval(0, 3)
Returns
=======
Interval
Union of all ranges for all intervals under domain where function is
continuous.
Raises
======
NotImplementedError
If any of the intervals, in the given domain, for which function
is continuous are not finite or real,
OR if the critical points of the function on the domain can't be found.
"""
from sympy.solvers.solveset import solveset
if isinstance(domain, EmptySet):
return S.EmptySet
period = periodicity(f, symbol)
if period == S.Zero:
# the expression is constant wrt symbol
return FiniteSet(f.expand())
if period is not None:
if isinstance(domain, Interval):
if (domain.inf - domain.sup).is_infinite:
domain = Interval(0, period)
elif isinstance(domain, Union):
for sub_dom in domain.args:
if isinstance(sub_dom, Interval) and \
((sub_dom.inf - sub_dom.sup).is_infinite):
domain = Interval(0, period)
intervals = continuous_domain(f, symbol, domain)
range_int = S.EmptySet
if isinstance(intervals,(Interval, FiniteSet)):
interval_iter = (intervals,)
elif isinstance(intervals, Union):
interval_iter = intervals.args
else:
raise NotImplementedError(filldedent('''
Unable to find range for the given domain.
'''))
for interval in interval_iter:
if isinstance(interval, FiniteSet):
for singleton in interval:
if singleton in domain:
range_int += FiniteSet(f.subs(symbol, singleton))
elif isinstance(interval, Interval):
vals = S.EmptySet
critical_points = S.EmptySet
critical_values = S.EmptySet
bounds = ((interval.left_open, interval.inf, '+'),
(interval.right_open, interval.sup, '-'))
for is_open, limit_point, direction in bounds:
if is_open:
critical_values += FiniteSet(limit(f, symbol, limit_point, direction))
vals += critical_values
else:
vals += FiniteSet(f.subs(symbol, limit_point))
solution = solveset(f.diff(symbol), symbol, interval)
if not iterable(solution):
raise NotImplementedError(
'Unable to find critical points for {}'.format(f))
if isinstance(solution, ImageSet):
raise NotImplementedError(
'Infinite number of critical points for {}'.format(f))
critical_points += solution
for critical_point in critical_points:
vals += FiniteSet(f.subs(symbol, critical_point))
left_open, right_open = False, False
if critical_values is not S.EmptySet:
if critical_values.inf == vals.inf:
left_open = True
if critical_values.sup == vals.sup:
right_open = True
range_int += Interval(vals.inf, vals.sup, left_open, right_open)
else:
raise NotImplementedError(filldedent('''
Unable to find range for the given domain.
'''))
return range_int
def not_empty_in(finset_intersection, *syms):
"""
Finds the domain of the functions in `finite_set` in which the
`finite_set` is not-empty
Parameters
==========
finset_intersection : The unevaluated intersection of FiniteSet containing
real-valued functions with Union of Sets
syms : Tuple of symbols
Symbol for which domain is to be found
Raises
======
NotImplementedError
The algorithms to find the non-emptiness of the given FiniteSet are
not yet implemented.
ValueError
The input is not valid.
RuntimeError
It is a bug, please report it to the github issue tracker
(https://github.com/sympy/sympy/issues).
Examples
========
>>> from sympy import FiniteSet, Interval, not_empty_in, oo
>>> from sympy.abc import x
>>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x)
Interval(0, 2)
>>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x)
Union(Interval(1, 2), Interval(-sqrt(2), -1))
>>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x)
Union(Interval.Lopen(-2, -1), Interval(2, oo))
"""
# TODO: handle piecewise defined functions
# TODO: handle transcendental functions
# TODO: handle multivariate functions
if len(syms) == 0:
raise ValueError("One or more symbols must be given in syms.")
if finset_intersection is S.EmptySet:
return S.EmptySet
if isinstance(finset_intersection, Union):
elm_in_sets = finset_intersection.args[0]
return Union(not_empty_in(finset_intersection.args[1], *syms),
elm_in_sets)
if isinstance(finset_intersection, FiniteSet):
finite_set = finset_intersection
_sets = S.Reals
else:
finite_set = finset_intersection.args[1]
_sets = finset_intersection.args[0]
if not isinstance(finite_set, FiniteSet):
raise ValueError('A FiniteSet must be given, not %s: %s' %
(type(finite_set), finite_set))
if len(syms) == 1:
symb = syms[0]
else:
raise NotImplementedError('more than one variables %s not handled' %
(syms,))
def elm_domain(expr, intrvl):
""" Finds the domain of an expression in any given interval """
from sympy.solvers.solveset import solveset
_start = intrvl.start
_end = intrvl.end
_singularities = solveset(expr.as_numer_denom()[1], symb,
domain=S.Reals)
if intrvl.right_open:
if _end is S.Infinity:
_domain1 = S.Reals
else:
_domain1 = solveset(expr < _end, symb, domain=S.Reals)
else:
_domain1 = solveset(expr <= _end, symb, domain=S.Reals)
if intrvl.left_open:
if _start is S.NegativeInfinity:
_domain2 = S.Reals
else:
_domain2 = solveset(expr > _start, symb, domain=S.Reals)
else:
_domain2 = solveset(expr >= _start, symb, domain=S.Reals)
# domain in the interval
expr_with_sing = Intersection(_domain1, _domain2)
expr_domain = Complement(expr_with_sing, _singularities)
return expr_domain
if isinstance(_sets, Interval):
return Union(*[elm_domain(element, _sets) for element in finite_set])
if isinstance(_sets, Union):
_domain = S.EmptySet
for intrvl in _sets.args:
_domain_element = Union(*[elm_domain(element, intrvl)
for element in finite_set])
_domain = Union(_domain, _domain_element)
return _domain
def periodicity(f, symbol, check=False):
"""
Tests the given function for periodicity in the given symbol.
Parameters
==========
f : Expr.
The concerned function.
symbol : Symbol
The variable for which the period is to be determined.
check : Boolean, optional
The flag to verify whether the value being returned is a period or not.
Returns
=======
period
The period of the function is returned.
`None` is returned when the function is aperiodic or has a complex period.
The value of `0` is returned as the period of a constant function.
Raises
======
NotImplementedError
The value of the period computed cannot be verified.
Notes
=====
Currently, we do not support functions with a complex period.
The period of functions having complex periodic values such
as `exp`, `sinh` is evaluated to `None`.
The value returned might not be the "fundamental" period of the given
function i.e. it may not be the smallest periodic value of the function.
The verification of the period through the `check` flag is not reliable
due to internal simplification of the given expression. Hence, it is set
to `False` by default.
Examples
========
>>> from sympy import Symbol, sin, cos, tan, exp
>>> from sympy.calculus.util import periodicity
>>> x = Symbol('x')
>>> f = sin(x) + sin(2*x) + sin(3*x)
>>> periodicity(f, x)
2*pi
>>> periodicity(sin(x)*cos(x), x)
pi
>>> periodicity(exp(tan(2*x) - 1), x)
pi/2
>>> periodicity(sin(4*x)**cos(2*x), x)
pi
>>> periodicity(exp(x), x)
"""
from sympy.core.mod import Mod
from sympy.core.relational import Relational
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.trigonometric import (
TrigonometricFunction, sin, cos, csc, sec)
from sympy.simplify.simplify import simplify
from sympy.solvers.decompogen import decompogen
from sympy.polys.polytools import degree
temp = Dummy('x', real=True)
f = f.subs(symbol, temp)
symbol = temp
def _check(orig_f, period):
'''Return the checked period or raise an error.'''
new_f = orig_f.subs(symbol, symbol + period)
if new_f.equals(orig_f):
return period
else:
raise NotImplementedError(filldedent('''
The period of the given function cannot be verified.
When `%s` was replaced with `%s + %s` in `%s`, the result
was `%s` which was not recognized as being the same as
the original function.
So either the period was wrong or the two forms were
not recognized as being equal.
Set check=False to obtain the value.''' %
(symbol, symbol, period, orig_f, new_f)))
orig_f = f
period = None
if isinstance(f, Relational):
f = f.lhs - f.rhs
f = simplify(f)
if symbol not in f.free_symbols:
return S.Zero
if isinstance(f, TrigonometricFunction):
try:
period = f.period(symbol)
except NotImplementedError:
pass
if isinstance(f, Abs):
arg = f.args[0]
if isinstance(arg, (sec, csc, cos)):
# all but tan and cot might have a
# a period that is half as large
# so recast as sin
arg = sin(arg.args[0])
period = periodicity(arg, symbol)
if period is not None and isinstance(arg, sin):
# the argument of Abs was a trigonometric other than
# cot or tan; test to see if the half-period
# is valid. Abs(arg) has behaviour equivalent to
# orig_f, so use that for test:
orig_f = Abs(arg)
try:
return _check(orig_f, period/2)
except NotImplementedError as err:
if check:
raise NotImplementedError(err)
# else let new orig_f and period be
# checked below
if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1):
f = Pow(S.Exp1, expand_mul(f.exp))
if im(f) != 0:
period_real = periodicity(re(f), symbol)
period_imag = periodicity(im(f), symbol)
if period_real is not None and period_imag is not None:
period = lcim([period_real, period_imag])
if f.is_Pow and f.base != S.Exp1:
base, expo = f.args
base_has_sym = base.has(symbol)
expo_has_sym = expo.has(symbol)
if base_has_sym and not expo_has_sym:
period = periodicity(base, symbol)
elif expo_has_sym and not base_has_sym:
period = periodicity(expo, symbol)
else:
period = _periodicity(f.args, symbol)
elif f.is_Mul:
coeff, g = f.as_independent(symbol, as_Add=False)
if isinstance(g, TrigonometricFunction) or coeff is not S.One:
period = periodicity(g, symbol)
else:
period = _periodicity(g.args, symbol)
elif f.is_Add:
k, g = f.as_independent(symbol)
if k is not S.Zero:
return periodicity(g, symbol)
period = _periodicity(g.args, symbol)
elif isinstance(f, Mod):
a, n = f.args
if a == symbol:
period = n
elif isinstance(a, TrigonometricFunction):
period = periodicity(a, symbol)
#check if 'f' is linear in 'symbol'
elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and
symbol not in n.free_symbols):
period = Abs(n / a.diff(symbol))
elif isinstance(f, Piecewise):
pass # not handling Piecewise yet as the return type is not favorable
elif period is None:
from sympy.solvers.decompogen import compogen
g_s = decompogen(f, symbol)
num_of_gs = len(g_s)
if num_of_gs > 1:
for index, g in enumerate(reversed(g_s)):
start_index = num_of_gs - 1 - index
g = compogen(g_s[start_index:], symbol)
if g != orig_f and g != f: # Fix for issue 12620
period = periodicity(g, symbol)
if period is not None:
break
if period is not None:
if check:
return _check(orig_f, period)
return period
return None
def _periodicity(args, symbol):
"""
Helper for `periodicity` to find the period of a list of simpler
functions.
It uses the `lcim` method to find the least common period of
all the functions.
Parameters
==========
args : Tuple of Symbol
All the symbols present in a function.
symbol : Symbol
The symbol over which the function is to be evaluated.
Returns
=======
period
The least common period of the function for all the symbols
of the function.
None if for at least one of the symbols the function is aperiodic
"""
periods = []
for f in args:
period = periodicity(f, symbol)
if period is None:
return None
if period is not S.Zero:
periods.append(period)
if len(periods) > 1:
return lcim(periods)
if periods:
return periods[0]
def lcim(numbers):
"""Returns the least common integral multiple of a list of numbers.
The numbers can be rational or irrational or a mixture of both.
`None` is returned for incommensurable numbers.
Parameters
==========
numbers : list
Numbers (rational and/or irrational) for which lcim is to be found.
Returns
=======
number
lcim if it exists, otherwise `None` for incommensurable numbers.
Examples
========
>>> from sympy import S, pi
>>> from sympy.calculus.util import lcim
>>> lcim([S(1)/2, S(3)/4, S(5)/6])
15/2
>>> lcim([2*pi, 3*pi, pi, pi/2])
6*pi
>>> lcim([S(1), 2*pi])
"""
result = None
if all(num.is_irrational for num in numbers):
factorized_nums = list(map(lambda num: num.factor(), numbers))
factors_num = list(
map(lambda num: num.as_coeff_Mul(),
factorized_nums))
term = factors_num[0][1]
if all(factor == term for coeff, factor in factors_num):
common_term = term
coeffs = [coeff for coeff, factor in factors_num]
result = lcm_list(coeffs) * common_term
elif all(num.is_rational for num in numbers):
result = lcm_list(numbers)
else:
pass
return result
def is_convex(f, *syms, domain=S.Reals):
"""Determines the convexity of the function passed in the argument.
Parameters
==========
f : Expr
The concerned function.
syms : Tuple of symbols
The variables with respect to which the convexity is to be determined.
domain : Interval, optional
The domain over which the convexity of the function has to be checked.
If unspecified, S.Reals will be the default domain.
Returns
=======
Boolean
The method returns `True` if the function is convex otherwise it
returns `False`.
Raises
======
NotImplementedError
The check for the convexity of multivariate functions is not implemented yet.
Notes
=====
To determine concavity of a function pass `-f` as the concerned function.
To determine logarithmic convexity of a function pass log(f) as
concerned function.
To determine logartihmic concavity of a function pass -log(f) as
concerned function.
Currently, convexity check of multivariate functions is not handled.
Examples
========
>>> from sympy import symbols, exp, oo, Interval
>>> from sympy.calculus.util import is_convex
>>> x = symbols('x')
>>> is_convex(exp(x), x)
True
>>> is_convex(x**3, x, domain = Interval(-1, oo))
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Convex_function
.. [2] http://www.ifp.illinois.edu/~angelia/L3_convfunc.pdf
.. [3] https://en.wikipedia.org/wiki/Logarithmically_convex_function
.. [4] https://en.wikipedia.org/wiki/Logarithmically_concave_function
.. [5] https://en.wikipedia.org/wiki/Concave_function
"""
if len(syms) > 1:
raise NotImplementedError(
"The check for the convexity of multivariate functions is not implemented yet.")
f = _sympify(f)
var = syms[0]
condition = f.diff(var, 2) < 0
if solve_univariate_inequality(condition, var, False, domain):
return False
return True
def stationary_points(f, symbol, domain=S.Reals):
"""
Returns the stationary points of a function (where derivative of the
function is 0) in the given domain.
Parameters
==========
f : Expr
The concerned function.
symbol : Symbol
The variable for which the stationary points are to be determined.
domain : Interval
The domain over which the stationary points have to be checked.
If unspecified, S.Reals will be the default domain.
Returns
=======
Set
A set of stationary points for the function. If there are no
stationary point, an EmptySet is returned.
Examples
========
>>> from sympy import Symbol, S, sin, pi, pprint, stationary_points
>>> from sympy.sets import Interval
>>> x = Symbol('x')
>>> stationary_points(1/x, x, S.Reals)
EmptySet
>>> pprint(stationary_points(sin(x), x), use_unicode=False)
pi 3*pi
{2*n*pi + -- | n in Integers} U {2*n*pi + ---- | n in Integers}
2 2
>>> stationary_points(sin(x),x, Interval(0, 4*pi))
FiniteSet(pi/2, 3*pi/2, 5*pi/2, 7*pi/2)
"""
from sympy import solveset, diff
if isinstance(domain, EmptySet):
return S.EmptySet
domain = continuous_domain(f, symbol, domain)
set = solveset(diff(f, symbol), symbol, domain)
return set
def maximum(f, symbol, domain=S.Reals):
"""
Returns the maximum value of a function in the given domain.
Parameters
==========
f : Expr
The concerned function.
symbol : Symbol
The variable for maximum value needs to be determined.
domain : Interval
The domain over which the maximum have to be checked.
If unspecified, then Global maximum is returned.
Returns
=======
number
Maximum value of the function in given domain.
Examples
========
>>> from sympy import Symbol, S, sin, cos, pi, maximum
>>> from sympy.sets import Interval
>>> x = Symbol('x')
>>> f = -x**2 + 2*x + 5
>>> maximum(f, x, S.Reals)
6
>>> maximum(sin(x), x, Interval(-pi, pi/4))
sqrt(2)/2
>>> maximum(sin(x)*cos(x), x)
1/2
"""
from sympy import Symbol
if isinstance(symbol, Symbol):
if isinstance(domain, EmptySet):
raise ValueError("Maximum value not defined for empty domain.")
return function_range(f, symbol, domain).sup
else:
raise ValueError("%s is not a valid symbol." % symbol)
def minimum(f, symbol, domain=S.Reals):
"""
Returns the minimum value of a function in the given domain.
Parameters
==========
f : Expr
The concerned function.
symbol : Symbol
The variable for minimum value needs to be determined.
domain : Interval
The domain over which the minimum have to be checked.
If unspecified, then Global minimum is returned.
Returns
=======
number
Minimum value of the function in the given domain.
Examples
========
>>> from sympy import Symbol, S, sin, cos, minimum
>>> from sympy.sets import Interval
>>> x = Symbol('x')
>>> f = x**2 + 2*x + 5
>>> minimum(f, x, S.Reals)
4
>>> minimum(sin(x), x, Interval(2, 3))
sin(3)
>>> minimum(sin(x)*cos(x), x)
-1/2
"""
from sympy import Symbol
if isinstance(symbol, Symbol):
if isinstance(domain, EmptySet):
raise ValueError("Minimum value not defined for empty domain.")
return function_range(f, symbol, domain).inf
else:
raise ValueError("%s is not a valid symbol." % symbol)
class AccumulationBounds(AtomicExpr):
r"""
# Note AccumulationBounds has an alias: AccumBounds
AccumulationBounds represent an interval `[a, b]`, which is always closed
at the ends. Here `a` and `b` can be any value from extended real numbers.
The intended meaning of AccummulationBounds is to give an approximate
location of the accumulation points of a real function at a limit point.
Let `a` and `b` be reals such that a <= b.
`\left\langle a, b\right\rangle = \{x \in \mathbb{R} \mid a \le x \le b\}`
`\left\langle -\infty, b\right\rangle = \{x \in \mathbb{R} \mid x \le b\} \cup \{-\infty, \infty\}`
`\left\langle a, \infty \right\rangle = \{x \in \mathbb{R} \mid a \le x\} \cup \{-\infty, \infty\}`
`\left\langle -\infty, \infty \right\rangle = \mathbb{R} \cup \{-\infty, \infty\}`
`oo` and `-oo` are added to the second and third definition respectively,
since if either `-oo` or `oo` is an argument, then the other one should
be included (though not as an end point). This is forced, since we have,
for example, `1/AccumBounds(0, 1) = AccumBounds(1, oo)`, and the limit at
`0` is not one-sided. As x tends to `0-`, then `1/x -> -oo`, so `-oo`
should be interpreted as belonging to `AccumBounds(1, oo)` though it need
not appear explicitly.
In many cases it suffices to know that the limit set is bounded.
However, in some other cases more exact information could be useful.
For example, all accumulation values of cos(x) + 1 are non-negative.
(AccumBounds(-1, 1) + 1 = AccumBounds(0, 2))
A AccumulationBounds object is defined to be real AccumulationBounds,
if its end points are finite reals.
Let `X`, `Y` be real AccumulationBounds, then their sum, difference,
product are defined to be the following sets:
`X + Y = \{ x+y \mid x \in X \cap y \in Y\}`
`X - Y = \{ x-y \mid x \in X \cap y \in Y\}`
`X * Y = \{ x*y \mid x \in X \cap y \in Y\}`
When an AccumBounds is raised to a negative power, if 0 is contained
between the bounds then an infinite range is returned, otherwise if an
endpoint is 0 then a semi-infinite range with consistent sign will be returned.
AccumBounds in expressions behave a lot like Intervals but the
semantics are not necessarily the same. Division (or exponentiation
to a negative integer power) could be handled with *intervals* by
returning a union of the results obtained after splitting the
bounds between negatives and positives, but that is not done with
AccumBounds. In addition, bounds are assumed to be independent of
each other; if the same bound is used in more than one place in an
expression, the result may not be the supremum or infimum of the
expression (see below). Finally, when a boundary is ``1``,
exponentiation to the power of ``oo`` yields ``oo``, neither
``1`` nor ``nan``.
Examples
========
>>> from sympy import AccumBounds, sin, exp, log, pi, E, S, oo
>>> from sympy.abc import x
>>> AccumBounds(0, 1) + AccumBounds(1, 2)
AccumBounds(1, 3)
>>> AccumBounds(0, 1) - AccumBounds(0, 2)
AccumBounds(-2, 1)
>>> AccumBounds(-2, 3)*AccumBounds(-1, 1)
AccumBounds(-3, 3)
>>> AccumBounds(1, 2)*AccumBounds(3, 5)
AccumBounds(3, 10)
The exponentiation of AccumulationBounds is defined
as follows:
If 0 does not belong to `X` or `n > 0` then
`X^n = \{ x^n \mid x \in X\}`
>>> AccumBounds(1, 4)**(S(1)/2)
AccumBounds(1, 2)
otherwise, an infinite or semi-infinite result is obtained:
>>> 1/AccumBounds(-1, 1)
AccumBounds(-oo, oo)
>>> 1/AccumBounds(0, 2)
AccumBounds(1/2, oo)
>>> 1/AccumBounds(-oo, 0)
AccumBounds(-oo, 0)
A boundary of 1 will always generate all nonnegatives:
>>> AccumBounds(1, 2)**oo
AccumBounds(0, oo)
>>> AccumBounds(0, 1)**oo
AccumBounds(0, oo)
If the exponent is itself an AccumulationBounds or is not an
integer then unevaluated results will be returned unless the base
values are positive:
>>> AccumBounds(2, 3)**AccumBounds(-1, 2)
AccumBounds(1/3, 9)
>>> AccumBounds(-2, 3)**AccumBounds(-1, 2)
AccumBounds(-2, 3)**AccumBounds(-1, 2)
>>> AccumBounds(-2, -1)**(S(1)/2)
sqrt(AccumBounds(-2, -1))
Note: `<a, b>^2` is not same as `<a, b>*<a, b>`
>>> AccumBounds(-1, 1)**2
AccumBounds(0, 1)
>>> AccumBounds(1, 3) < 4
True
>>> AccumBounds(1, 3) < -1
False
Some elementary functions can also take AccumulationBounds as input.
A function `f` evaluated for some real AccumulationBounds `<a, b>`
is defined as `f(\left\langle a, b\right\rangle) = \{ f(x) \mid a \le x \le b \}`
>>> sin(AccumBounds(pi/6, pi/3))
AccumBounds(1/2, sqrt(3)/2)
>>> exp(AccumBounds(0, 1))
AccumBounds(1, E)
>>> log(AccumBounds(1, E))
AccumBounds(0, 1)
Some symbol in an expression can be substituted for a AccumulationBounds
object. But it doesn't necessarily evaluate the AccumulationBounds for
that expression.
The same expression can be evaluated to different values depending upon
the form it is used for substitution since each instance of an
AccumulationBounds is considered independent. For example:
>>> (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1))
AccumBounds(-1, 4)
>>> ((x + 1)**2).subs(x, AccumBounds(-1, 1))
AccumBounds(0, 4)
References
==========
.. [1] https://en.wikipedia.org/wiki/Interval_arithmetic
.. [2] http://fab.cba.mit.edu/classes/S62.12/docs/Hickey_interval.pdf
Notes
=====
Do not use ``AccumulationBounds`` for floating point interval arithmetic
calculations, use ``mpmath.iv`` instead.
"""
is_extended_real = True
def __new__(cls, min, max):
min = _sympify(min)
max = _sympify(max)
# Only allow real intervals (use symbols with 'is_extended_real=True').
if not min.is_extended_real or not max.is_extended_real:
raise ValueError("Only real AccumulationBounds are supported")
if max == min:
return max
# Make sure that the created AccumBounds object will be valid.
if max.is_number and min.is_number:
bad = max.is_comparable and min.is_comparable and max < min
else:
bad = (max - min).is_extended_negative
if bad:
raise ValueError(
"Lower limit should be smaller than upper limit")
return Basic.__new__(cls, min, max)
# setting the operation priority
_op_priority = 11.0
def _eval_is_real(self):
if self.min.is_real and self.max.is_real:
return True
@property
def min(self):
"""
Returns the minimum possible value attained by AccumulationBounds
object.
Examples
========
>>> from sympy import AccumBounds
>>> AccumBounds(1, 3).min
1
"""
return self.args[0]
@property
def max(self):
"""
Returns the maximum possible value attained by AccumulationBounds
object.
Examples
========
>>> from sympy import AccumBounds
>>> AccumBounds(1, 3).max
3
"""
return self.args[1]
@property
def delta(self):
"""
Returns the difference of maximum possible value attained by
AccumulationBounds object and minimum possible value attained
by AccumulationBounds object.
Examples
========
>>> from sympy import AccumBounds
>>> AccumBounds(1, 3).delta
2
"""
return self.max - self.min
@property
def mid(self):
"""
Returns the mean of maximum possible value attained by
AccumulationBounds object and minimum possible value
attained by AccumulationBounds object.
Examples
========
>>> from sympy import AccumBounds
>>> AccumBounds(1, 3).mid
2
"""
return (self.min + self.max) / 2
@_sympifyit('other', NotImplemented)
def _eval_power(self, other):
return self.__pow__(other)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Expr):
if isinstance(other, AccumBounds):
return AccumBounds(
Add(self.min, other.min),
Add(self.max, other.max))
if other is S.Infinity and self.min is S.NegativeInfinity or \
other is S.NegativeInfinity and self.max is S.Infinity:
return AccumBounds(-oo, oo)
elif other.is_extended_real:
if self.min is S.NegativeInfinity and self.max is S.Infinity:
return AccumBounds(-oo, oo)
elif self.min is S.NegativeInfinity:
return AccumBounds(-oo, self.max + other)
elif self.max is S.Infinity:
return AccumBounds(self.min + other, oo)
else:
return AccumBounds(Add(self.min, other), Add(self.max, other))
return Add(self, other, evaluate=False)
return NotImplemented
__radd__ = __add__
def __neg__(self):
return AccumBounds(-self.max, -self.min)
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Expr):
if isinstance(other, AccumBounds):
return AccumBounds(
Add(self.min, -other.max),
Add(self.max, -other.min))
if other is S.NegativeInfinity and self.min is S.NegativeInfinity or \
other is S.Infinity and self.max is S.Infinity:
return AccumBounds(-oo, oo)
elif other.is_extended_real:
if self.min is S.NegativeInfinity and self.max is S.Infinity:
return AccumBounds(-oo, oo)
elif self.min is S.NegativeInfinity:
return AccumBounds(-oo, self.max - other)
elif self.max is S.Infinity:
return AccumBounds(self.min - other, oo)
else:
return AccumBounds(
Add(self.min, -other),
Add(self.max, -other))
return Add(self, -other, evaluate=False)
return NotImplemented
@_sympifyit('other', NotImplemented)
def __rsub__(self, other):
return self.__neg__() + other
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if self.args == (-oo, oo):
return self
if isinstance(other, Expr):
if isinstance(other, AccumBounds):
if other.args == (-oo, oo):
return other
v = set()
for i in self.args:
vi = other*i
for i in vi.args or (vi,):
v.add(i)
return AccumBounds(Min(*v), Max(*v))
if other is S.Infinity:
if self.min.is_zero:
return AccumBounds(0, oo)
if self.max.is_zero:
return AccumBounds(-oo, 0)
if other is S.NegativeInfinity:
if self.min.is_zero:
return AccumBounds(-oo, 0)
if self.max.is_zero:
return AccumBounds(0, oo)
if other.is_extended_real:
if other.is_zero:
if self.max is S.Infinity:
return AccumBounds(0, oo)
if self.min is S.NegativeInfinity:
return AccumBounds(-oo, 0)
return S.Zero
if other.is_extended_positive:
return AccumBounds(
Mul(self.min, other),
Mul(self.max, other))
elif other.is_extended_negative:
return AccumBounds(
Mul(self.max, other),
Mul(self.min, other))
if isinstance(other, Order):
return other
return Mul(self, other, evaluate=False)
return NotImplemented
__rmul__ = __mul__
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Expr):
if isinstance(other, AccumBounds):
if other.min.is_positive or other.max.is_negative:
return self * AccumBounds(1/other.max, 1/other.min)
if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative and
other.min.is_extended_nonpositive and other.max.is_extended_nonnegative):
if self.min.is_zero and other.min.is_zero:
return AccumBounds(0, oo)
if self.max.is_zero and other.min.is_zero:
return AccumBounds(-oo, 0)
return AccumBounds(-oo, oo)
if self.max.is_extended_negative:
if other.min.is_extended_negative:
if other.max.is_zero:
return AccumBounds(self.max / other.min, oo)
if other.max.is_extended_positive:
# if we were dealing with intervals we would return
# Union(Interval(-oo, self.max/other.max),
# Interval(self.max/other.min, oo))
return AccumBounds(-oo, oo)
if other.min.is_zero and other.max.is_extended_positive:
return AccumBounds(-oo, self.max / other.max)
if self.min.is_extended_positive:
if other.min.is_extended_negative:
if other.max.is_zero:
return AccumBounds(-oo, self.min / other.min)
if other.max.is_extended_positive:
# if we were dealing with intervals we would return
# Union(Interval(-oo, self.min/other.min),
# Interval(self.min/other.max, oo))
return AccumBounds(-oo, oo)
if other.min.is_zero and other.max.is_extended_positive:
return AccumBounds(self.min / other.max, oo)
elif other.is_extended_real:
if other is S.Infinity or other is S.NegativeInfinity:
if self == AccumBounds(-oo, oo):
return AccumBounds(-oo, oo)
if self.max is S.Infinity:
return AccumBounds(Min(0, other), Max(0, other))
if self.min is S.NegativeInfinity:
return AccumBounds(Min(0, -other), Max(0, -other))
if other.is_extended_positive:
return AccumBounds(self.min / other, self.max / other)
elif other.is_extended_negative:
return AccumBounds(self.max / other, self.min / other)
if (1 / other) is S.ComplexInfinity:
return Mul(self, 1 / other, evaluate=False)
else:
return Mul(self, 1 / other)
return NotImplemented
@_sympifyit('other', NotImplemented)
def __rtruediv__(self, other):
if isinstance(other, Expr):
if other.is_extended_real:
if other.is_zero:
return S.Zero
if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative):
if self.min.is_zero:
if other.is_extended_positive:
return AccumBounds(Mul(other, 1 / self.max), oo)
if other.is_extended_negative:
return AccumBounds(-oo, Mul(other, 1 / self.max))
if self.max.is_zero:
if other.is_extended_positive:
return AccumBounds(-oo, Mul(other, 1 / self.min))
if other.is_extended_negative:
return AccumBounds(Mul(other, 1 / self.min), oo)
return AccumBounds(-oo, oo)
else:
return AccumBounds(Min(other / self.min, other / self.max),
Max(other / self.min, other / self.max))
return Mul(other, 1 / self, evaluate=False)
else:
return NotImplemented
@_sympifyit('other', NotImplemented)
def __pow__(self, other):
if isinstance(other, Expr):
if other is S.Infinity:
if self.min.is_extended_nonnegative:
if self.max < 1:
return S.Zero
if self.min > 1:
return S.Infinity
return AccumBounds(0, oo)
elif self.max.is_extended_negative:
if self.min > -1:
return S.Zero
if self.max < -1:
return zoo
return S.NaN
else:
if self.min > -1:
if self.max < 1:
return S.Zero
return AccumBounds(0, oo)
return AccumBounds(-oo, oo)
if other is S.NegativeInfinity:
return (1/self)**oo
# generically true
if (self.max - self.min).is_nonnegative:
# well defined
if self.min.is_nonnegative:
# no 0 to worry about
if other.is_nonnegative:
# no infinity to worry about
return self.func(self.min**other, self.max**other)
if other.is_zero:
return S.One # x**0 = 1
if other.is_Integer or other.is_integer:
if self.min.is_extended_positive:
return AccumBounds(
Min(self.min**other, self.max**other),
Max(self.min**other, self.max**other))
elif self.max.is_extended_negative:
return AccumBounds(
Min(self.max**other, self.min**other),
Max(self.max**other, self.min**other))
if other % 2 == 0:
if other.is_extended_negative:
if self.min.is_zero:
return AccumBounds(self.max**other, oo)
if self.max.is_zero:
return AccumBounds(self.min**other, oo)
return AccumBounds(0, oo)
return AccumBounds(
S.Zero, Max(self.min**other, self.max**other))
elif other % 2 == 1:
if other.is_extended_negative:
if self.min.is_zero:
return AccumBounds(self.max**other, oo)
if self.max.is_zero:
return AccumBounds(-oo, self.min**other)
return AccumBounds(-oo, oo)
return AccumBounds(self.min**other, self.max**other)
# non-integer exponent
# 0**neg or neg**frac yields complex
if (other.is_number or other.is_rational) and (
self.min.is_extended_nonnegative or (
other.is_extended_nonnegative and
self.min.is_extended_nonnegative)):
num, den = other.as_numer_denom()
if num is S.One:
return AccumBounds(*[i**(1/den) for i in self.args])
elif den is not S.One: # e.g. if other is not Float
return (self**num)**(1/den) # ok for non-negative base
if isinstance(other, AccumBounds):
if (self.min.is_extended_positive or
self.min.is_extended_nonnegative and
other.min.is_extended_nonnegative):
p = [self**i for i in other.args]
if not any(i.is_Pow for i in p):
a = [j for i in p for j in i.args or (i,)]
try:
return self.func(min(a), max(a))
except TypeError: # can't sort
pass
return Pow(self, other, evaluate=False)
return NotImplemented
@_sympifyit('other', NotImplemented)
def __rpow__(self, other):
if other.is_real and other.is_extended_nonnegative and (
self.max - self.min).is_extended_positive:
if other is S.One:
return S.One
if other.is_extended_positive:
a, b = [other**i for i in self.args]
if min(a, b) != a:
a, b = b, a
return self.func(a, b)
if other.is_zero:
if self.min.is_zero:
return self.func(0, 1)
if self.min.is_extended_positive:
return S.Zero
return Pow(other, self, evaluate=False)
def __abs__(self):
if self.max.is_extended_negative:
return self.__neg__()
elif self.min.is_extended_negative:
return AccumBounds(S.Zero, Max(abs(self.min), self.max))
else:
return self
def __contains__(self, other):
"""
Returns True if other is contained in self, where other
belongs to extended real numbers, False if not contained,
otherwise TypeError is raised.
Examples
========
>>> from sympy import AccumBounds, oo
>>> 1 in AccumBounds(-1, 3)
True
-oo and oo go together as limits (in AccumulationBounds).
>>> -oo in AccumBounds(1, oo)
True
>>> oo in AccumBounds(-oo, 0)
True
"""
other = _sympify(other)
if other is S.Infinity or other is S.NegativeInfinity:
if self.min is S.NegativeInfinity or self.max is S.Infinity:
return True
return False
rv = And(self.min <= other, self.max >= other)
if rv not in (True, False):
raise TypeError("input failed to evaluate")
return rv
def intersection(self, other):
"""
Returns the intersection of 'self' and 'other'.
Here other can be an instance of FiniteSet or AccumulationBounds.
Parameters
==========
other: AccumulationBounds
Another AccumulationBounds object with which the intersection
has to be computed.
Returns
=======
AccumulationBounds
Intersection of 'self' and 'other'.
Examples
========
>>> from sympy import AccumBounds, FiniteSet
>>> AccumBounds(1, 3).intersection(AccumBounds(2, 4))
AccumBounds(2, 3)
>>> AccumBounds(1, 3).intersection(AccumBounds(4, 6))
EmptySet
>>> AccumBounds(1, 4).intersection(FiniteSet(1, 2, 5))
FiniteSet(1, 2)
"""
if not isinstance(other, (AccumBounds, FiniteSet)):
raise TypeError(
"Input must be AccumulationBounds or FiniteSet object")
if isinstance(other, FiniteSet):
fin_set = S.EmptySet
for i in other:
if i in self:
fin_set = fin_set + FiniteSet(i)
return fin_set
if self.max < other.min or self.min > other.max:
return S.EmptySet
if self.min <= other.min:
if self.max <= other.max:
return AccumBounds(other.min, self.max)
if self.max > other.max:
return other
if other.min <= self.min:
if other.max < self.max:
return AccumBounds(self.min, other.max)
if other.max > self.max:
return self
def union(self, other):
# TODO : Devise a better method for Union of AccumBounds
# this method is not actually correct and
# can be made better
if not isinstance(other, AccumBounds):
raise TypeError(
"Input must be AccumulationBounds or FiniteSet object")
if self.min <= other.min and self.max >= other.min:
return AccumBounds(self.min, Max(self.max, other.max))
if other.min <= self.min and other.max >= self.min:
return AccumBounds(other.min, Max(self.max, other.max))
@dispatch(AccumulationBounds, AccumulationBounds) # type: ignore # noqa:F811
def _eval_is_le(lhs, rhs): # noqa:F811
if is_le(lhs.max, rhs.min):
return True
if is_gt(lhs.min, rhs.max):
return False
@dispatch(AccumulationBounds, Basic) # type: ignore # noqa:F811
def _eval_is_le(lhs, rhs): # noqa: F811
"""
Returns True if range of values attained by `self` AccumulationBounds
object is greater than the range of values attained by `other`,
where other may be any value of type AccumulationBounds object or
extended real number value, False if `other` satisfies
the same property, else an unevaluated Relational.
Examples
========
>>> from sympy import AccumBounds, oo
>>> AccumBounds(1, 3) > AccumBounds(4, oo)
False
>>> AccumBounds(1, 4) > AccumBounds(3, 4)
AccumBounds(1, 4) > AccumBounds(3, 4)
>>> AccumBounds(1, oo) > -1
True
"""
if not rhs.is_extended_real:
raise TypeError(
"Invalid comparison of %s %s" %
(type(rhs), rhs))
elif rhs.is_comparable:
if is_le(lhs.max, rhs):
return True
if is_gt(lhs.min, rhs):
return False
@dispatch(AccumulationBounds, AccumulationBounds)
def _eval_is_ge(lhs, rhs): # noqa:F811
if is_ge(lhs.min, rhs.max):
return True
if is_lt(lhs.max, rhs.min):
return False
@dispatch(AccumulationBounds, Expr) # type:ignore
def _eval_is_ge(lhs, rhs): # noqa: F811
"""
Returns True if range of values attained by `lhs` AccumulationBounds
object is less that the range of values attained by `rhs`, where
other may be any value of type AccumulationBounds object or extended
real number value, False if `rhs` satisfies the same
property, else an unevaluated Relational.
Examples
========
>>> from sympy import AccumBounds, oo
>>> AccumBounds(1, 3) >= AccumBounds(4, oo)
False
>>> AccumBounds(1, 4) >= AccumBounds(3, 4)
AccumBounds(1, 4) >= AccumBounds(3, 4)
>>> AccumBounds(1, oo) >= 1
True
"""
if not rhs.is_extended_real:
raise TypeError(
"Invalid comparison of %s %s" %
(type(rhs), rhs))
elif rhs.is_comparable:
if is_ge(lhs.min, rhs):
return True
if is_lt(lhs.max, rhs):
return False
@dispatch(Expr, AccumulationBounds) # type:ignore
def _eval_is_ge(lhs, rhs): # noqa:F811
if not lhs.is_extended_real:
raise TypeError(
"Invalid comparison of %s %s" %
(type(lhs), lhs))
elif lhs.is_comparable:
if is_le(rhs.max, lhs):
return True
if is_gt(rhs.min, lhs):
return False
@dispatch(AccumulationBounds, AccumulationBounds) # type:ignore
def _eval_is_ge(lhs, rhs): # noqa:F811
if is_ge(lhs.min, rhs.max):
return True
if is_lt(lhs.max, rhs.min):
return False
# setting an alias for AccumulationBounds
AccumBounds = AccumulationBounds
|
8a34a800662021b937ed64ec8c8b9ec58220a4aba1a96d047bf2aadbe9957abd | """
This module provides convenient functions to transform sympy expressions to
lambda functions which can be used to calculate numerical values very fast.
"""
from typing import Any, Dict, Iterable
import builtins
import inspect
import keyword
import textwrap
import linecache
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.core.compatibility import (is_sequence, iterable,
NotIterable)
from sympy.utilities.misc import filldedent
from sympy.utilities.decorator import doctest_depends_on
__doctest_requires__ = {('lambdify',): ['numpy', 'tensorflow']}
# Default namespaces, letting us define translations that can't be defined
# by simple variable maps, like I => 1j
MATH_DEFAULT = {} # type: Dict[str, Any]
MPMATH_DEFAULT = {} # type: Dict[str, Any]
NUMPY_DEFAULT = {"I": 1j} # type: Dict[str, Any]
SCIPY_DEFAULT = {"I": 1j} # type: Dict[str, Any]
CUPY_DEFAULT = {"I": 1j} # type: Dict[str, Any]
TENSORFLOW_DEFAULT = {} # type: Dict[str, Any]
SYMPY_DEFAULT = {} # type: Dict[str, Any]
NUMEXPR_DEFAULT = {} # type: Dict[str, Any]
# These are the namespaces the lambda functions will use.
# These are separate from the names above because they are modified
# throughout this file, whereas the defaults should remain unmodified.
MATH = MATH_DEFAULT.copy()
MPMATH = MPMATH_DEFAULT.copy()
NUMPY = NUMPY_DEFAULT.copy()
SCIPY = SCIPY_DEFAULT.copy()
CUPY = CUPY_DEFAULT.copy()
TENSORFLOW = TENSORFLOW_DEFAULT.copy()
SYMPY = SYMPY_DEFAULT.copy()
NUMEXPR = NUMEXPR_DEFAULT.copy()
# Mappings between sympy and other modules function names.
MATH_TRANSLATIONS = {
"ceiling": "ceil",
"E": "e",
"ln": "log",
}
# NOTE: This dictionary is reused in Function._eval_evalf to allow subclasses
# of Function to automatically evalf.
MPMATH_TRANSLATIONS = {
"Abs": "fabs",
"elliptic_k": "ellipk",
"elliptic_f": "ellipf",
"elliptic_e": "ellipe",
"elliptic_pi": "ellippi",
"ceiling": "ceil",
"chebyshevt": "chebyt",
"chebyshevu": "chebyu",
"E": "e",
"I": "j",
"ln": "log",
#"lowergamma":"lower_gamma",
"oo": "inf",
#"uppergamma":"upper_gamma",
"LambertW": "lambertw",
"MutableDenseMatrix": "matrix",
"ImmutableDenseMatrix": "matrix",
"conjugate": "conj",
"dirichlet_eta": "altzeta",
"Ei": "ei",
"Shi": "shi",
"Chi": "chi",
"Si": "si",
"Ci": "ci",
"RisingFactorial": "rf",
"FallingFactorial": "ff",
"betainc_regularized": "betainc",
}
NUMPY_TRANSLATIONS = {
"Heaviside": "heaviside",
} # type: Dict[str, str]
SCIPY_TRANSLATIONS = {} # type: Dict[str, str]
CUPY_TRANSLATIONS = {} # type: Dict[str, str]
TENSORFLOW_TRANSLATIONS = {} # type: Dict[str, str]
NUMEXPR_TRANSLATIONS = {} # type: Dict[str, str]
# Available modules:
MODULES = {
"math": (MATH, MATH_DEFAULT, MATH_TRANSLATIONS, ("from math import *",)),
"mpmath": (MPMATH, MPMATH_DEFAULT, MPMATH_TRANSLATIONS, ("from mpmath import *",)),
"numpy": (NUMPY, NUMPY_DEFAULT, NUMPY_TRANSLATIONS, ("import numpy; from numpy import *; from numpy.linalg import *",)),
"scipy": (SCIPY, SCIPY_DEFAULT, SCIPY_TRANSLATIONS, ("import numpy; import scipy; from scipy import *; from scipy.special import *",)),
"cupy": (CUPY, CUPY_DEFAULT, CUPY_TRANSLATIONS, ("import cupy",)),
"tensorflow": (TENSORFLOW, TENSORFLOW_DEFAULT, TENSORFLOW_TRANSLATIONS, ("import tensorflow",)),
"sympy": (SYMPY, SYMPY_DEFAULT, {}, (
"from sympy.functions import *",
"from sympy.matrices import *",
"from sympy import Integral, pi, oo, nan, zoo, E, I",)),
"numexpr" : (NUMEXPR, NUMEXPR_DEFAULT, NUMEXPR_TRANSLATIONS,
("import_module('numexpr')", )),
}
def _import(module, reload=False):
"""
Creates a global translation dictionary for module.
The argument module has to be one of the following strings: "math",
"mpmath", "numpy", "sympy", "tensorflow".
These dictionaries map names of python functions to their equivalent in
other modules.
"""
# Required despite static analysis claiming it is not used
from sympy.external import import_module # noqa:F401
try:
namespace, namespace_default, translations, import_commands = MODULES[
module]
except KeyError:
raise NameError(
"'%s' module can't be used for lambdification" % module)
# Clear namespace or exit
if namespace != namespace_default:
# The namespace was already generated, don't do it again if not forced.
if reload:
namespace.clear()
namespace.update(namespace_default)
else:
return
for import_command in import_commands:
if import_command.startswith('import_module'):
module = eval(import_command)
if module is not None:
namespace.update(module.__dict__)
continue
else:
try:
exec(import_command, {}, namespace)
continue
except ImportError:
pass
raise ImportError(
"can't import '%s' with '%s' command" % (module, import_command))
# Add translated names to namespace
for sympyname, translation in translations.items():
namespace[sympyname] = namespace[translation]
# For computing the modulus of a sympy expression we use the builtin abs
# function, instead of the previously used fabs function for all
# translation modules. This is because the fabs function in the math
# module does not accept complex valued arguments. (see issue 9474). The
# only exception, where we don't use the builtin abs function is the
# mpmath translation module, because mpmath.fabs returns mpf objects in
# contrast to abs().
if 'Abs' not in namespace:
namespace['Abs'] = abs
# Used for dynamically generated filenames that are inserted into the
# linecache.
_lambdify_generated_counter = 1
@doctest_depends_on(modules=('numpy', 'tensorflow', ), python_version=(3,))
def lambdify(args: Iterable, expr, modules=None, printer=None, use_imps=True,
dummify=False):
"""Convert a SymPy expression into a function that allows for fast
numeric evaluation.
.. warning::
This function uses ``exec``, and thus shouldn't be used on
unsanitized input.
.. versionchanged:: 1.7.0
Passing a set for the *args* parameter is deprecated as sets are
unordered. Use an ordered iterable such as a list or tuple.
Explanation
===========
For example, to convert the SymPy expression ``sin(x) + cos(x)`` to an
equivalent NumPy function that numerically evaluates it:
>>> from sympy import sin, cos, symbols, lambdify
>>> import numpy as np
>>> x = symbols('x')
>>> expr = sin(x) + cos(x)
>>> expr
sin(x) + cos(x)
>>> f = lambdify(x, expr, 'numpy')
>>> a = np.array([1, 2])
>>> f(a)
[1.38177329 0.49315059]
The primary purpose of this function is to provide a bridge from SymPy
expressions to numerical libraries such as NumPy, SciPy, NumExpr, mpmath,
and tensorflow. In general, SymPy functions do not work with objects from
other libraries, such as NumPy arrays, and functions from numeric
libraries like NumPy or mpmath do not work on SymPy expressions.
``lambdify`` bridges the two by converting a SymPy expression to an
equivalent numeric function.
The basic workflow with ``lambdify`` is to first create a SymPy expression
representing whatever mathematical function you wish to evaluate. This
should be done using only SymPy functions and expressions. Then, use
``lambdify`` to convert this to an equivalent function for numerical
evaluation. For instance, above we created ``expr`` using the SymPy symbol
``x`` and SymPy functions ``sin`` and ``cos``, then converted it to an
equivalent NumPy function ``f``, and called it on a NumPy array ``a``.
Parameters
==========
args : List[Symbol]
A variable or a list of variables whose nesting represents the
nesting of the arguments that will be passed to the function.
Variables can be symbols, undefined functions, or matrix symbols.
>>> from sympy import Eq
>>> from sympy.abc import x, y, z
The list of variables should match the structure of how the
arguments will be passed to the function. Simply enclose the
parameters as they will be passed in a list.
To call a function like ``f(x)`` then ``[x]``
should be the first argument to ``lambdify``; for this
case a single ``x`` can also be used:
>>> f = lambdify(x, x + 1)
>>> f(1)
2
>>> f = lambdify([x], x + 1)
>>> f(1)
2
To call a function like ``f(x, y)`` then ``[x, y]`` will
be the first argument of the ``lambdify``:
>>> f = lambdify([x, y], x + y)
>>> f(1, 1)
2
To call a function with a single 3-element tuple like
``f((x, y, z))`` then ``[(x, y, z)]`` will be the first
argument of the ``lambdify``:
>>> f = lambdify([(x, y, z)], Eq(z**2, x**2 + y**2))
>>> f((3, 4, 5))
True
If two args will be passed and the first is a scalar but
the second is a tuple with two arguments then the items
in the list should match that structure:
>>> f = lambdify([x, (y, z)], x + y + z)
>>> f(1, (2, 3))
6
expr : Expr
An expression, list of expressions, or matrix to be evaluated.
Lists may be nested.
If the expression is a list, the output will also be a list.
>>> f = lambdify(x, [x, [x + 1, x + 2]])
>>> f(1)
[1, [2, 3]]
If it is a matrix, an array will be returned (for the NumPy module).
>>> from sympy import Matrix
>>> f = lambdify(x, Matrix([x, x + 1]))
>>> f(1)
[[1]
[2]]
Note that the argument order here (variables then expression) is used
to emulate the Python ``lambda`` keyword. ``lambdify(x, expr)`` works
(roughly) like ``lambda x: expr``
(see :ref:`lambdify-how-it-works` below).
modules : str, optional
Specifies the numeric library to use.
If not specified, *modules* defaults to:
- ``["scipy", "numpy"]`` if SciPy is installed
- ``["numpy"]`` if only NumPy is installed
- ``["math", "mpmath", "sympy"]`` if neither is installed.
That is, SymPy functions are replaced as far as possible by
either ``scipy`` or ``numpy`` functions if available, and Python's
standard library ``math``, or ``mpmath`` functions otherwise.
*modules* can be one of the following types:
- The strings ``"math"``, ``"mpmath"``, ``"numpy"``, ``"numexpr"``,
``"scipy"``, ``"sympy"``, or ``"tensorflow"``. This uses the
corresponding printer and namespace mapping for that module.
- A module (e.g., ``math``). This uses the global namespace of the
module. If the module is one of the above known modules, it will
also use the corresponding printer and namespace mapping
(i.e., ``modules=numpy`` is equivalent to ``modules="numpy"``).
- A dictionary that maps names of SymPy functions to arbitrary
functions
(e.g., ``{'sin': custom_sin}``).
- A list that contains a mix of the arguments above, with higher
priority given to entries appearing first
(e.g., to use the NumPy module but override the ``sin`` function
with a custom version, you can use
``[{'sin': custom_sin}, 'numpy']``).
dummify : bool, optional
Whether or not the variables in the provided expression that are not
valid Python identifiers are substituted with dummy symbols.
This allows for undefined functions like ``Function('f')(t)`` to be
supplied as arguments. By default, the variables are only dummified
if they are not valid Python identifiers.
Set ``dummify=True`` to replace all arguments with dummy symbols
(if ``args`` is not a string) - for example, to ensure that the
arguments do not redefine any built-in names.
Examples
========
>>> from sympy.utilities.lambdify import implemented_function
>>> from sympy import sqrt, sin, Matrix
>>> from sympy import Function
>>> from sympy.abc import w, x, y, z
>>> f = lambdify(x, x**2)
>>> f(2)
4
>>> f = lambdify((x, y, z), [z, y, x])
>>> f(1,2,3)
[3, 2, 1]
>>> f = lambdify(x, sqrt(x))
>>> f(4)
2.0
>>> f = lambdify((x, y), sin(x*y)**2)
>>> f(0, 5)
0.0
>>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy')
>>> row(1, 2)
Matrix([[1, 3]])
``lambdify`` can be used to translate SymPy expressions into mpmath
functions. This may be preferable to using ``evalf`` (which uses mpmath on
the backend) in some cases.
>>> f = lambdify(x, sin(x), 'mpmath')
>>> f(1)
0.8414709848078965
Tuple arguments are handled and the lambdified function should
be called with the same type of arguments as were used to create
the function:
>>> f = lambdify((x, (y, z)), x + y)
>>> f(1, (2, 4))
3
The ``flatten`` function can be used to always work with flattened
arguments:
>>> from sympy.utilities.iterables import flatten
>>> args = w, (x, (y, z))
>>> vals = 1, (2, (3, 4))
>>> f = lambdify(flatten(args), w + x + y + z)
>>> f(*flatten(vals))
10
Functions present in ``expr`` can also carry their own numerical
implementations, in a callable attached to the ``_imp_`` attribute. This
can be used with undefined functions using the ``implemented_function``
factory:
>>> f = implemented_function(Function('f'), lambda x: x+1)
>>> func = lambdify(x, f(x))
>>> func(4)
5
``lambdify`` always prefers ``_imp_`` implementations to implementations
in other namespaces, unless the ``use_imps`` input parameter is False.
Usage with Tensorflow:
>>> import tensorflow as tf
>>> from sympy import Max, sin, lambdify
>>> from sympy.abc import x
>>> f = Max(x, sin(x))
>>> func = lambdify(x, f, 'tensorflow')
After tensorflow v2, eager execution is enabled by default.
If you want to get the compatible result across tensorflow v1 and v2
as same as this tutorial, run this line.
>>> tf.compat.v1.enable_eager_execution()
If you have eager execution enabled, you can get the result out
immediately as you can use numpy.
If you pass tensorflow objects, you may get an ``EagerTensor``
object instead of value.
>>> result = func(tf.constant(1.0))
>>> print(result)
tf.Tensor(1.0, shape=(), dtype=float32)
>>> print(result.__class__)
<class 'tensorflow.python.framework.ops.EagerTensor'>
You can use ``.numpy()`` to get the numpy value of the tensor.
>>> result.numpy()
1.0
>>> var = tf.Variable(2.0)
>>> result = func(var) # also works for tf.Variable and tf.Placeholder
>>> result.numpy()
2.0
And it works with any shape array.
>>> tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]])
>>> result = func(tensor)
>>> result.numpy()
[[1. 2.]
[3. 4.]]
Notes
=====
- For functions involving large array calculations, numexpr can provide a
significant speedup over numpy. Please note that the available functions
for numexpr are more limited than numpy but can be expanded with
``implemented_function`` and user defined subclasses of Function. If
specified, numexpr may be the only option in modules. The official list
of numexpr functions can be found at:
https://numexpr.readthedocs.io/en/latest/user_guide.html#supported-functions
- In previous versions of SymPy, ``lambdify`` replaced ``Matrix`` with
``numpy.matrix`` by default. As of SymPy 1.0 ``numpy.array`` is the
default. To get the old default behavior you must pass in
``[{'ImmutableDenseMatrix': numpy.matrix}, 'numpy']`` to the
``modules`` kwarg.
>>> from sympy import lambdify, Matrix
>>> from sympy.abc import x, y
>>> import numpy
>>> array2mat = [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy']
>>> f = lambdify((x, y), Matrix([x, y]), modules=array2mat)
>>> f(1, 2)
[[1]
[2]]
- In the above examples, the generated functions can accept scalar
values or numpy arrays as arguments. However, in some cases
the generated function relies on the input being a numpy array:
>>> from sympy import Piecewise
>>> from sympy.testing.pytest import ignore_warnings
>>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "numpy")
>>> with ignore_warnings(RuntimeWarning):
... f(numpy.array([-1, 0, 1, 2]))
[-1. 0. 1. 0.5]
>>> f(0)
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
In such cases, the input should be wrapped in a numpy array:
>>> with ignore_warnings(RuntimeWarning):
... float(f(numpy.array([0])))
0.0
Or if numpy functionality is not required another module can be used:
>>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "math")
>>> f(0)
0
.. _lambdify-how-it-works:
How it works
============
When using this function, it helps a great deal to have an idea of what it
is doing. At its core, lambdify is nothing more than a namespace
translation, on top of a special printer that makes some corner cases work
properly.
To understand lambdify, first we must properly understand how Python
namespaces work. Say we had two files. One called ``sin_cos_sympy.py``,
with
.. code:: python
# sin_cos_sympy.py
from sympy import sin, cos
def sin_cos(x):
return sin(x) + cos(x)
and one called ``sin_cos_numpy.py`` with
.. code:: python
# sin_cos_numpy.py
from numpy import sin, cos
def sin_cos(x):
return sin(x) + cos(x)
The two files define an identical function ``sin_cos``. However, in the
first file, ``sin`` and ``cos`` are defined as the SymPy ``sin`` and
``cos``. In the second, they are defined as the NumPy versions.
If we were to import the first file and use the ``sin_cos`` function, we
would get something like
>>> from sin_cos_sympy import sin_cos # doctest: +SKIP
>>> sin_cos(1) # doctest: +SKIP
cos(1) + sin(1)
On the other hand, if we imported ``sin_cos`` from the second file, we
would get
>>> from sin_cos_numpy import sin_cos # doctest: +SKIP
>>> sin_cos(1) # doctest: +SKIP
1.38177329068
In the first case we got a symbolic output, because it used the symbolic
``sin`` and ``cos`` functions from SymPy. In the second, we got a numeric
result, because ``sin_cos`` used the numeric ``sin`` and ``cos`` functions
from NumPy. But notice that the versions of ``sin`` and ``cos`` that were
used was not inherent to the ``sin_cos`` function definition. Both
``sin_cos`` definitions are exactly the same. Rather, it was based on the
names defined at the module where the ``sin_cos`` function was defined.
The key point here is that when function in Python references a name that
is not defined in the function, that name is looked up in the "global"
namespace of the module where that function is defined.
Now, in Python, we can emulate this behavior without actually writing a
file to disk using the ``exec`` function. ``exec`` takes a string
containing a block of Python code, and a dictionary that should contain
the global variables of the module. It then executes the code "in" that
dictionary, as if it were the module globals. The following is equivalent
to the ``sin_cos`` defined in ``sin_cos_sympy.py``:
>>> import sympy
>>> module_dictionary = {'sin': sympy.sin, 'cos': sympy.cos}
>>> exec('''
... def sin_cos(x):
... return sin(x) + cos(x)
... ''', module_dictionary)
>>> sin_cos = module_dictionary['sin_cos']
>>> sin_cos(1)
cos(1) + sin(1)
and similarly with ``sin_cos_numpy``:
>>> import numpy
>>> module_dictionary = {'sin': numpy.sin, 'cos': numpy.cos}
>>> exec('''
... def sin_cos(x):
... return sin(x) + cos(x)
... ''', module_dictionary)
>>> sin_cos = module_dictionary['sin_cos']
>>> sin_cos(1)
1.38177329068
So now we can get an idea of how ``lambdify`` works. The name "lambdify"
comes from the fact that we can think of something like ``lambdify(x,
sin(x) + cos(x), 'numpy')`` as ``lambda x: sin(x) + cos(x)``, where
``sin`` and ``cos`` come from the ``numpy`` namespace. This is also why
the symbols argument is first in ``lambdify``, as opposed to most SymPy
functions where it comes after the expression: to better mimic the
``lambda`` keyword.
``lambdify`` takes the input expression (like ``sin(x) + cos(x)``) and
1. Converts it to a string
2. Creates a module globals dictionary based on the modules that are
passed in (by default, it uses the NumPy module)
3. Creates the string ``"def func({vars}): return {expr}"``, where ``{vars}`` is the
list of variables separated by commas, and ``{expr}`` is the string
created in step 1., then ``exec``s that string with the module globals
namespace and returns ``func``.
In fact, functions returned by ``lambdify`` support inspection. So you can
see exactly how they are defined by using ``inspect.getsource``, or ``??`` if you
are using IPython or the Jupyter notebook.
>>> f = lambdify(x, sin(x) + cos(x))
>>> import inspect
>>> print(inspect.getsource(f))
def _lambdifygenerated(x):
return (sin(x) + cos(x))
This shows us the source code of the function, but not the namespace it
was defined in. We can inspect that by looking at the ``__globals__``
attribute of ``f``:
>>> f.__globals__['sin']
<ufunc 'sin'>
>>> f.__globals__['cos']
<ufunc 'cos'>
>>> f.__globals__['sin'] is numpy.sin
True
This shows us that ``sin`` and ``cos`` in the namespace of ``f`` will be
``numpy.sin`` and ``numpy.cos``.
Note that there are some convenience layers in each of these steps, but at
the core, this is how ``lambdify`` works. Step 1 is done using the
``LambdaPrinter`` printers defined in the printing module (see
:mod:`sympy.printing.lambdarepr`). This allows different SymPy expressions
to define how they should be converted to a string for different modules.
You can change which printer ``lambdify`` uses by passing a custom printer
in to the ``printer`` argument.
Step 2 is augmented by certain translations. There are default
translations for each module, but you can provide your own by passing a
list to the ``modules`` argument. For instance,
>>> def mysin(x):
... print('taking the sin of', x)
... return numpy.sin(x)
...
>>> f = lambdify(x, sin(x), [{'sin': mysin}, 'numpy'])
>>> f(1)
taking the sin of 1
0.8414709848078965
The globals dictionary is generated from the list by merging the
dictionary ``{'sin': mysin}`` and the module dictionary for NumPy. The
merging is done so that earlier items take precedence, which is why
``mysin`` is used above instead of ``numpy.sin``.
If you want to modify the way ``lambdify`` works for a given function, it
is usually easiest to do so by modifying the globals dictionary as such.
In more complicated cases, it may be necessary to create and pass in a
custom printer.
Finally, step 3 is augmented with certain convenience operations, such as
the addition of a docstring.
Understanding how ``lambdify`` works can make it easier to avoid certain
gotchas when using it. For instance, a common mistake is to create a
lambdified function for one module (say, NumPy), and pass it objects from
another (say, a SymPy expression).
For instance, say we create
>>> from sympy.abc import x
>>> f = lambdify(x, x + 1, 'numpy')
Now if we pass in a NumPy array, we get that array plus 1
>>> import numpy
>>> a = numpy.array([1, 2])
>>> f(a)
[2 3]
But what happens if you make the mistake of passing in a SymPy expression
instead of a NumPy array:
>>> f(x + 1)
x + 2
This worked, but it was only by accident. Now take a different lambdified
function:
>>> from sympy import sin
>>> g = lambdify(x, x + sin(x), 'numpy')
This works as expected on NumPy arrays:
>>> g(a)
[1.84147098 2.90929743]
But if we try to pass in a SymPy expression, it fails
>>> try:
... g(x + 1)
... # NumPy release after 1.17 raises TypeError instead of
... # AttributeError
... except (AttributeError, TypeError):
... raise AttributeError() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
AttributeError:
Now, let's look at what happened. The reason this fails is that ``g``
calls ``numpy.sin`` on the input expression, and ``numpy.sin`` does not
know how to operate on a SymPy object. **As a general rule, NumPy
functions do not know how to operate on SymPy expressions, and SymPy
functions do not know how to operate on NumPy arrays. This is why lambdify
exists: to provide a bridge between SymPy and NumPy.**
However, why is it that ``f`` did work? That's because ``f`` doesn't call
any functions, it only adds 1. So the resulting function that is created,
``def _lambdifygenerated(x): return x + 1`` does not depend on the globals
namespace it is defined in. Thus it works, but only by accident. A future
version of ``lambdify`` may remove this behavior.
Be aware that certain implementation details described here may change in
future versions of SymPy. The API of passing in custom modules and
printers will not change, but the details of how a lambda function is
created may change. However, the basic idea will remain the same, and
understanding it will be helpful to understanding the behavior of
lambdify.
**In general: you should create lambdified functions for one module (say,
NumPy), and only pass it input types that are compatible with that module
(say, NumPy arrays).** Remember that by default, if the ``module``
argument is not provided, ``lambdify`` creates functions using the NumPy
and SciPy namespaces.
"""
from sympy.core.symbol import Symbol
# If the user hasn't specified any modules, use what is available.
if modules is None:
try:
_import("scipy")
except ImportError:
try:
_import("numpy")
except ImportError:
# Use either numpy (if available) or python.math where possible.
# XXX: This leads to different behaviour on different systems and
# might be the reason for irreproducible errors.
modules = ["math", "mpmath", "sympy"]
else:
modules = ["numpy"]
else:
modules = ["numpy", "scipy"]
# Get the needed namespaces.
namespaces = []
# First find any function implementations
if use_imps:
namespaces.append(_imp_namespace(expr))
# Check for dict before iterating
if isinstance(modules, (dict, str)) or not hasattr(modules, '__iter__'):
namespaces.append(modules)
else:
# consistency check
if _module_present('numexpr', modules) and len(modules) > 1:
raise TypeError("numexpr must be the only item in 'modules'")
namespaces += list(modules)
# fill namespace with first having highest priority
namespace = {} # type: Dict[str, Any]
for m in namespaces[::-1]:
buf = _get_namespace(m)
namespace.update(buf)
if hasattr(expr, "atoms"):
#Try if you can extract symbols from the expression.
#Move on if expr.atoms in not implemented.
syms = expr.atoms(Symbol)
for term in syms:
namespace.update({str(term): term})
if printer is None:
if _module_present('mpmath', namespaces):
from sympy.printing.pycode import MpmathPrinter as Printer # type: ignore
elif _module_present('scipy', namespaces):
from sympy.printing.numpy import SciPyPrinter as Printer # type: ignore
elif _module_present('numpy', namespaces):
from sympy.printing.numpy import NumPyPrinter as Printer # type: ignore
elif _module_present('cupy', namespaces):
from sympy.printing.numpy import CuPyPrinter as Printer # type: ignore
elif _module_present('numexpr', namespaces):
from sympy.printing.lambdarepr import NumExprPrinter as Printer # type: ignore
elif _module_present('tensorflow', namespaces):
from sympy.printing.tensorflow import TensorflowPrinter as Printer # type: ignore
elif _module_present('sympy', namespaces):
from sympy.printing.pycode import SymPyPrinter as Printer # type: ignore
else:
from sympy.printing.pycode import PythonCodePrinter as Printer # type: ignore
user_functions = {}
for m in namespaces[::-1]:
if isinstance(m, dict):
for k in m:
user_functions[k] = k
printer = Printer({'fully_qualified_modules': False, 'inline': True,
'allow_unknown_functions': True,
'user_functions': user_functions})
if isinstance(args, set):
SymPyDeprecationWarning(
feature="The list of arguments is a `set`. This leads to unpredictable results",
useinstead=": Convert set into list or tuple",
issue=20013,
deprecated_since_version="1.6.3"
).warn()
# Get the names of the args, for creating a docstring
if not iterable(args):
args = (args,)
names = []
# Grab the callers frame, for getting the names by inspection (if needed)
callers_local_vars = inspect.currentframe().f_back.f_locals.items() # type: ignore
for n, var in enumerate(args):
if hasattr(var, 'name'):
names.append(var.name)
else:
# It's an iterable. Try to get name by inspection of calling frame.
name_list = [var_name for var_name, var_val in callers_local_vars
if var_val is var]
if len(name_list) == 1:
names.append(name_list[0])
else:
# Cannot infer name with certainty. arg_# will have to do.
names.append('arg_' + str(n))
# Create the function definition code and execute it
funcname = '_lambdifygenerated'
if _module_present('tensorflow', namespaces):
funcprinter = _TensorflowEvaluatorPrinter(printer, dummify) # type: _EvaluatorPrinter
else:
funcprinter = _EvaluatorPrinter(printer, dummify)
funcstr = funcprinter.doprint(funcname, args, expr)
# Collect the module imports from the code printers.
imp_mod_lines = []
for mod, keys in (getattr(printer, 'module_imports', None) or {}).items():
for k in keys:
if k not in namespace:
ln = "from %s import %s" % (mod, k)
try:
exec(ln, {}, namespace)
except ImportError:
# Tensorflow 2.0 has issues with importing a specific
# function from its submodule.
# https://github.com/tensorflow/tensorflow/issues/33022
ln = "%s = %s.%s" % (k, mod, k)
exec(ln, {}, namespace)
imp_mod_lines.append(ln)
# Provide lambda expression with builtins, and compatible implementation of range
namespace.update({'builtins':builtins, 'range':range})
funclocals = {} # type: Dict[str, Any]
global _lambdify_generated_counter
filename = '<lambdifygenerated-%s>' % _lambdify_generated_counter
_lambdify_generated_counter += 1
c = compile(funcstr, filename, 'exec')
exec(c, namespace, funclocals)
# mtime has to be None or else linecache.checkcache will remove it
linecache.cache[filename] = (len(funcstr), None, funcstr.splitlines(True), filename) # type: ignore
func = funclocals[funcname]
# Apply the docstring
sig = "func({})".format(", ".join(str(i) for i in names))
sig = textwrap.fill(sig, subsequent_indent=' '*8)
expr_str = str(expr)
if len(expr_str) > 78:
expr_str = textwrap.wrap(expr_str, 75)[0] + '...'
func.__doc__ = (
"Created with lambdify. Signature:\n\n"
"{sig}\n\n"
"Expression:\n\n"
"{expr}\n\n"
"Source code:\n\n"
"{src}\n\n"
"Imported modules:\n\n"
"{imp_mods}"
).format(sig=sig, expr=expr_str, src=funcstr, imp_mods='\n'.join(imp_mod_lines))
return func
def _module_present(modname, modlist):
if modname in modlist:
return True
for m in modlist:
if hasattr(m, '__name__') and m.__name__ == modname:
return True
return False
def _get_namespace(m):
"""
This is used by _lambdify to parse its arguments.
"""
if isinstance(m, str):
_import(m)
return MODULES[m][0]
elif isinstance(m, dict):
return m
elif hasattr(m, "__dict__"):
return m.__dict__
else:
raise TypeError("Argument must be either a string, dict or module but it is: %s" % m)
def lambdastr(args, expr, printer=None, dummify=None):
"""
Returns a string that can be evaluated to a lambda function.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.utilities.lambdify import lambdastr
>>> lambdastr(x, x**2)
'lambda x: (x**2)'
>>> lambdastr((x,y,z), [z,y,x])
'lambda x,y,z: ([z, y, x])'
Although tuples may not appear as arguments to lambda in Python 3,
lambdastr will create a lambda function that will unpack the original
arguments so that nested arguments can be handled:
>>> lambdastr((x, (y, z)), x + y)
'lambda _0,_1: (lambda x,y,z: (x + y))(_0,_1[0],_1[1])'
"""
# Transforming everything to strings.
from sympy.matrices import DeferredVector
from sympy import Dummy, sympify, Symbol, Function, flatten, Derivative, Basic
if printer is not None:
if inspect.isfunction(printer):
lambdarepr = printer
else:
if inspect.isclass(printer):
lambdarepr = lambda expr: printer().doprint(expr)
else:
lambdarepr = lambda expr: printer.doprint(expr)
else:
#XXX: This has to be done here because of circular imports
from sympy.printing.lambdarepr import lambdarepr
def sub_args(args, dummies_dict):
if isinstance(args, str):
return args
elif isinstance(args, DeferredVector):
return str(args)
elif iterable(args):
dummies = flatten([sub_args(a, dummies_dict) for a in args])
return ",".join(str(a) for a in dummies)
else:
# replace these with Dummy symbols
if isinstance(args, (Function, Symbol, Derivative)):
dummies = Dummy()
dummies_dict.update({args : dummies})
return str(dummies)
else:
return str(args)
def sub_expr(expr, dummies_dict):
expr = sympify(expr)
# dict/tuple are sympified to Basic
if isinstance(expr, Basic):
expr = expr.xreplace(dummies_dict)
# list is not sympified to Basic
elif isinstance(expr, list):
expr = [sub_expr(a, dummies_dict) for a in expr]
return expr
# Transform args
def isiter(l):
return iterable(l, exclude=(str, DeferredVector, NotIterable))
def flat_indexes(iterable):
n = 0
for el in iterable:
if isiter(el):
for ndeep in flat_indexes(el):
yield (n,) + ndeep
else:
yield (n,)
n += 1
if dummify is None:
dummify = any(isinstance(a, Basic) and
a.atoms(Function, Derivative) for a in (
args if isiter(args) else [args]))
if isiter(args) and any(isiter(i) for i in args):
dum_args = [str(Dummy(str(i))) for i in range(len(args))]
indexed_args = ','.join([
dum_args[ind[0]] + ''.join(["[%s]" % k for k in ind[1:]])
for ind in flat_indexes(args)])
lstr = lambdastr(flatten(args), expr, printer=printer, dummify=dummify)
return 'lambda %s: (%s)(%s)' % (','.join(dum_args), lstr, indexed_args)
dummies_dict = {}
if dummify:
args = sub_args(args, dummies_dict)
else:
if isinstance(args, str):
pass
elif iterable(args, exclude=DeferredVector):
args = ",".join(str(a) for a in args)
# Transform expr
if dummify:
if isinstance(expr, str):
pass
else:
expr = sub_expr(expr, dummies_dict)
expr = lambdarepr(expr)
return "lambda %s: (%s)" % (args, expr)
class _EvaluatorPrinter:
def __init__(self, printer=None, dummify=False):
self._dummify = dummify
#XXX: This has to be done here because of circular imports
from sympy.printing.lambdarepr import LambdaPrinter
if printer is None:
printer = LambdaPrinter()
if inspect.isfunction(printer):
self._exprrepr = printer
else:
if inspect.isclass(printer):
printer = printer()
self._exprrepr = printer.doprint
#if hasattr(printer, '_print_Symbol'):
# symbolrepr = printer._print_Symbol
#if hasattr(printer, '_print_Dummy'):
# dummyrepr = printer._print_Dummy
# Used to print the generated function arguments in a standard way
self._argrepr = LambdaPrinter().doprint
def doprint(self, funcname, args, expr):
"""Returns the function definition code as a string."""
from sympy import Dummy
funcbody = []
if not iterable(args):
args = [args]
argstrs, expr = self._preprocess(args, expr)
# Generate argument unpacking and final argument list
funcargs = []
unpackings = []
for argstr in argstrs:
if iterable(argstr):
funcargs.append(self._argrepr(Dummy()))
unpackings.extend(self._print_unpacking(argstr, funcargs[-1]))
else:
funcargs.append(argstr)
funcsig = 'def {}({}):'.format(funcname, ', '.join(funcargs))
# Wrap input arguments before unpacking
funcbody.extend(self._print_funcargwrapping(funcargs))
funcbody.extend(unpackings)
funcbody.append('return ({})'.format(self._exprrepr(expr)))
funclines = [funcsig]
funclines.extend(' ' + line for line in funcbody)
return '\n'.join(funclines) + '\n'
@classmethod
def _is_safe_ident(cls, ident):
return isinstance(ident, str) and ident.isidentifier() \
and not keyword.iskeyword(ident)
def _preprocess(self, args, expr):
"""Preprocess args, expr to replace arguments that do not map
to valid Python identifiers.
Returns string form of args, and updated expr.
"""
from sympy import Dummy, Function, flatten, Derivative, ordered, Basic
from sympy.matrices import DeferredVector
from sympy.core.symbol import uniquely_named_symbol
from sympy.core.expr import Expr
# Args of type Dummy can cause name collisions with args
# of type Symbol. Force dummify of everything in this
# situation.
dummify = self._dummify or any(
isinstance(arg, Dummy) for arg in flatten(args))
argstrs = [None]*len(args)
for arg, i in reversed(list(ordered(zip(args, range(len(args)))))):
if iterable(arg):
s, expr = self._preprocess(arg, expr)
elif isinstance(arg, DeferredVector):
s = str(arg)
elif isinstance(arg, Basic) and arg.is_symbol:
s = self._argrepr(arg)
if dummify or not self._is_safe_ident(s):
dummy = Dummy()
if isinstance(expr, Expr):
dummy = uniquely_named_symbol(
dummy.name, expr, modify=lambda s: '_' + s)
s = self._argrepr(dummy)
expr = self._subexpr(expr, {arg: dummy})
elif dummify or isinstance(arg, (Function, Derivative)):
dummy = Dummy()
s = self._argrepr(dummy)
expr = self._subexpr(expr, {arg: dummy})
else:
s = str(arg)
argstrs[i] = s
return argstrs, expr
def _subexpr(self, expr, dummies_dict):
from sympy.matrices import DeferredVector
from sympy import sympify
expr = sympify(expr)
xreplace = getattr(expr, 'xreplace', None)
if xreplace is not None:
expr = xreplace(dummies_dict)
else:
if isinstance(expr, DeferredVector):
pass
elif isinstance(expr, dict):
k = [self._subexpr(sympify(a), dummies_dict) for a in expr.keys()]
v = [self._subexpr(sympify(a), dummies_dict) for a in expr.values()]
expr = dict(zip(k, v))
elif isinstance(expr, tuple):
expr = tuple(self._subexpr(sympify(a), dummies_dict) for a in expr)
elif isinstance(expr, list):
expr = [self._subexpr(sympify(a), dummies_dict) for a in expr]
return expr
def _print_funcargwrapping(self, args):
"""Generate argument wrapping code.
args is the argument list of the generated function (strings).
Return value is a list of lines of code that will be inserted at
the beginning of the function definition.
"""
return []
def _print_unpacking(self, unpackto, arg):
"""Generate argument unpacking code.
arg is the function argument to be unpacked (a string), and
unpackto is a list or nested lists of the variable names (strings) to
unpack to.
"""
def unpack_lhs(lvalues):
return '[{}]'.format(', '.join(
unpack_lhs(val) if iterable(val) else val for val in lvalues))
return ['{} = {}'.format(unpack_lhs(unpackto), arg)]
class _TensorflowEvaluatorPrinter(_EvaluatorPrinter):
def _print_unpacking(self, lvalues, rvalue):
"""Generate argument unpacking code.
This method is used when the input value is not interable,
but can be indexed (see issue #14655).
"""
from sympy import flatten
def flat_indexes(elems):
n = 0
for el in elems:
if iterable(el):
for ndeep in flat_indexes(el):
yield (n,) + ndeep
else:
yield (n,)
n += 1
indexed = ', '.join('{}[{}]'.format(rvalue, ']['.join(map(str, ind)))
for ind in flat_indexes(lvalues))
return ['[{}] = [{}]'.format(', '.join(flatten(lvalues)), indexed)]
def _imp_namespace(expr, namespace=None):
""" Return namespace dict with function implementations
We need to search for functions in anything that can be thrown at
us - that is - anything that could be passed as ``expr``. Examples
include sympy expressions, as well as tuples, lists and dicts that may
contain sympy expressions.
Parameters
----------
expr : object
Something passed to lambdify, that will generate valid code from
``str(expr)``.
namespace : None or mapping
Namespace to fill. None results in new empty dict
Returns
-------
namespace : dict
dict with keys of implemented function names within ``expr`` and
corresponding values being the numerical implementation of
function
Examples
========
>>> from sympy.abc import x
>>> from sympy.utilities.lambdify import implemented_function, _imp_namespace
>>> from sympy import Function
>>> f = implemented_function(Function('f'), lambda x: x+1)
>>> g = implemented_function(Function('g'), lambda x: x*10)
>>> namespace = _imp_namespace(f(g(x)))
>>> sorted(namespace.keys())
['f', 'g']
"""
# Delayed import to avoid circular imports
from sympy.core.function import FunctionClass
if namespace is None:
namespace = {}
# tuples, lists, dicts are valid expressions
if is_sequence(expr):
for arg in expr:
_imp_namespace(arg, namespace)
return namespace
elif isinstance(expr, dict):
for key, val in expr.items():
# functions can be in dictionary keys
_imp_namespace(key, namespace)
_imp_namespace(val, namespace)
return namespace
# sympy expressions may be Functions themselves
func = getattr(expr, 'func', None)
if isinstance(func, FunctionClass):
imp = getattr(func, '_imp_', None)
if imp is not None:
name = expr.func.__name__
if name in namespace and namespace[name] != imp:
raise ValueError('We found more than one '
'implementation with name '
'"%s"' % name)
namespace[name] = imp
# and / or they may take Functions as arguments
if hasattr(expr, 'args'):
for arg in expr.args:
_imp_namespace(arg, namespace)
return namespace
def implemented_function(symfunc, implementation):
""" Add numerical ``implementation`` to function ``symfunc``.
``symfunc`` can be an ``UndefinedFunction`` instance, or a name string.
In the latter case we create an ``UndefinedFunction`` instance with that
name.
Be aware that this is a quick workaround, not a general method to create
special symbolic functions. If you want to create a symbolic function to be
used by all the machinery of SymPy you should subclass the ``Function``
class.
Parameters
----------
symfunc : ``str`` or ``UndefinedFunction`` instance
If ``str``, then create new ``UndefinedFunction`` with this as
name. If ``symfunc`` is an Undefined function, create a new function
with the same name and the implemented function attached.
implementation : callable
numerical implementation to be called by ``evalf()`` or ``lambdify``
Returns
-------
afunc : sympy.FunctionClass instance
function with attached implementation
Examples
========
>>> from sympy.abc import x
>>> from sympy.utilities.lambdify import lambdify, implemented_function
>>> f = implemented_function('f', lambda x: x+1)
>>> lam_f = lambdify(x, f(x))
>>> lam_f(4)
5
"""
# Delayed import to avoid circular imports
from sympy.core.function import UndefinedFunction
# if name, create function to hold implementation
kwargs = {}
if isinstance(symfunc, UndefinedFunction):
kwargs = symfunc._kwargs
symfunc = symfunc.__name__
if isinstance(symfunc, str):
# Keyword arguments to UndefinedFunction are added as attributes to
# the created class.
symfunc = UndefinedFunction(
symfunc, _imp_=staticmethod(implementation), **kwargs)
elif not isinstance(symfunc, UndefinedFunction):
raise ValueError(filldedent('''
symfunc should be either a string or
an UndefinedFunction instance.'''))
return symfunc
|
c2bb3b6e8e4425640e7c4f1306b209c64fa4a93b9b400417b7147cd012fd9eb9 | """
A Printer for generating readable representation of most sympy classes.
"""
from typing import Any, Dict
from sympy.core import S, Rational, Pow, Basic, Mul, Number
from sympy.core.mul import _keep_coeff
from sympy.core.function import _coeff_isneg
from .printer import Printer, print_function
from sympy.printing.precedence import precedence, PRECEDENCE
from mpmath.libmp import prec_to_dps, to_str as mlib_to_str
from sympy.utilities import default_sort_key, sift
class StrPrinter(Printer):
printmethod = "_sympystr"
_default_settings = {
"order": None,
"full_prec": "auto",
"sympy_integers": False,
"abbrev": False,
"perm_cyclic": True,
"min": None,
"max": None,
} # type: Dict[str, Any]
_relationals = dict() # type: Dict[str, str]
def parenthesize(self, item, level, strict=False):
if (precedence(item) < level) or ((not strict) and precedence(item) <= level):
return "(%s)" % self._print(item)
else:
return self._print(item)
def stringify(self, args, sep, level=0):
return sep.join([self.parenthesize(item, level) for item in args])
def emptyPrinter(self, expr):
if isinstance(expr, str):
return expr
elif isinstance(expr, Basic):
return repr(expr)
else:
return str(expr)
def _print_Add(self, expr, order=None):
terms = self._as_ordered_terms(expr, order=order)
PREC = precedence(expr)
l = []
for term in terms:
t = self._print(term)
if t.startswith('-'):
sign = "-"
t = t[1:]
else:
sign = "+"
if precedence(term) < PREC:
l.extend([sign, "(%s)" % t])
else:
l.extend([sign, t])
sign = l.pop(0)
if sign == '+':
sign = ""
return sign + ' '.join(l)
def _print_BooleanTrue(self, expr):
return "True"
def _print_BooleanFalse(self, expr):
return "False"
def _print_Not(self, expr):
return '~%s' %(self.parenthesize(expr.args[0],PRECEDENCE["Not"]))
def _print_And(self, expr):
return self.stringify(expr.args, " & ", PRECEDENCE["BitwiseAnd"])
def _print_Or(self, expr):
return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"])
def _print_Xor(self, expr):
return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"])
def _print_AppliedPredicate(self, expr):
return '%s(%s)' % (
self._print(expr.function), self.stringify(expr.arguments, ", "))
def _print_Basic(self, expr):
l = [self._print(o) for o in expr.args]
return expr.__class__.__name__ + "(%s)" % ", ".join(l)
def _print_BlockMatrix(self, B):
if B.blocks.shape == (1, 1):
self._print(B.blocks[0, 0])
return self._print(B.blocks)
def _print_Catalan(self, expr):
return 'Catalan'
def _print_ComplexInfinity(self, expr):
return 'zoo'
def _print_ConditionSet(self, s):
args = tuple([self._print(i) for i in (s.sym, s.condition)])
if s.base_set is S.UniversalSet:
return 'ConditionSet(%s, %s)' % args
args += (self._print(s.base_set),)
return 'ConditionSet(%s, %s, %s)' % args
def _print_Derivative(self, expr):
dexpr = expr.expr
dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count]
return 'Derivative(%s)' % ", ".join(map(lambda arg: self._print(arg), [dexpr] + dvars))
def _print_dict(self, d):
keys = sorted(d.keys(), key=default_sort_key)
items = []
for key in keys:
item = "%s: %s" % (self._print(key), self._print(d[key]))
items.append(item)
return "{%s}" % ", ".join(items)
def _print_Dict(self, expr):
return self._print_dict(expr)
def _print_RandomDomain(self, d):
if hasattr(d, 'as_boolean'):
return 'Domain: ' + self._print(d.as_boolean())
elif hasattr(d, 'set'):
return ('Domain: ' + self._print(d.symbols) + ' in ' +
self._print(d.set))
else:
return 'Domain on ' + self._print(d.symbols)
def _print_Dummy(self, expr):
return '_' + expr.name
def _print_EulerGamma(self, expr):
return 'EulerGamma'
def _print_Exp1(self, expr):
return 'E'
def _print_ExprCondPair(self, expr):
return '(%s, %s)' % (self._print(expr.expr), self._print(expr.cond))
def _print_Function(self, expr):
return expr.func.__name__ + "(%s)" % self.stringify(expr.args, ", ")
def _print_GoldenRatio(self, expr):
return 'GoldenRatio'
def _print_TribonacciConstant(self, expr):
return 'TribonacciConstant'
def _print_ImaginaryUnit(self, expr):
return 'I'
def _print_Infinity(self, expr):
return 'oo'
def _print_Integral(self, expr):
def _xab_tostr(xab):
if len(xab) == 1:
return self._print(xab[0])
else:
return self._print((xab[0],) + tuple(xab[1:]))
L = ', '.join([_xab_tostr(l) for l in expr.limits])
return 'Integral(%s, %s)' % (self._print(expr.function), L)
def _print_Interval(self, i):
fin = 'Interval{m}({a}, {b})'
a, b, l, r = i.args
if a.is_infinite and b.is_infinite:
m = ''
elif a.is_infinite and not r:
m = ''
elif b.is_infinite and not l:
m = ''
elif not l and not r:
m = ''
elif l and r:
m = '.open'
elif l:
m = '.Lopen'
else:
m = '.Ropen'
return fin.format(**{'a': a, 'b': b, 'm': m})
def _print_AccumulationBounds(self, i):
return "AccumBounds(%s, %s)" % (self._print(i.min),
self._print(i.max))
def _print_Inverse(self, I):
return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"])
def _print_Lambda(self, obj):
expr = obj.expr
sig = obj.signature
if len(sig) == 1 and sig[0].is_symbol:
sig = sig[0]
return "Lambda(%s, %s)" % (self._print(sig), self._print(expr))
def _print_LatticeOp(self, expr):
args = sorted(expr.args, key=default_sort_key)
return expr.func.__name__ + "(%s)" % ", ".join(self._print(arg) for arg in args)
def _print_Limit(self, expr):
e, z, z0, dir = expr.args
if str(dir) == "+":
return "Limit(%s, %s, %s)" % tuple(map(self._print, (e, z, z0)))
else:
return "Limit(%s, %s, %s, dir='%s')" % tuple(map(self._print,
(e, z, z0, dir)))
def _print_list(self, expr):
return "[%s]" % self.stringify(expr, ", ")
def _print_MatrixBase(self, expr):
return expr._format_str(self)
def _print_MatrixElement(self, expr):
return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \
+ '[%s, %s]' % (self._print(expr.i), self._print(expr.j))
def _print_MatrixSlice(self, expr):
def strslice(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 ':'.join(map(lambda arg: self._print(arg), x))
return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' +
strslice(expr.rowslice, expr.parent.rows) + ', ' +
strslice(expr.colslice, expr.parent.cols) + ']')
def _print_DeferredVector(self, expr):
return expr.name
def _print_Mul(self, expr):
prec = precedence(expr)
# 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 = expr.args
if args[0] is S.One or any(
isinstance(a, Number) or
a.is_Pow and all(ai.is_Integer for ai in a.args)
for a in args[1:]):
d, n = sift(args, lambda x:
isinstance(x, Pow) and bool(x.exp.as_coeff_Mul()[0] < 0),
binary=True)
for i, di in enumerate(d):
if di.exp.is_Number:
e = -di.exp
else:
dargs = list(di.exp.args)
dargs[0] = -dargs[0]
e = Mul._from_args(dargs)
d[i] = Pow(di.base, e, evaluate=False) if e - 1 else di.base
# don't parenthesize first factor if negative
if _coeff_isneg(n[0]):
pre = [str(n.pop(0))]
else:
pre = []
nfactors = pre + [self.parenthesize(a, prec, strict=False)
for a in n]
# don't parenthesize first of denominator unless singleton
if len(d) > 1 and _coeff_isneg(d[0]):
pre = [str(d.pop(0))]
else:
pre = []
dfactors = pre + [self.parenthesize(a, prec, strict=False)
for a in d]
n = '*'.join(nfactors)
d = '*'.join(dfactors)
if len(dfactors) > 1:
return '%s/(%s)' % (n, d)
elif dfactors:
return '%s/%s' % (n, d)
return n
c, e = expr.as_coeff_Mul()
if c < 0:
expr = _keep_coeff(-c, e)
sign = "-"
else:
sign = ""
a = [] # items in the numerator
b = [] # items that are in the denominator (if any)
pow_paren = [] # Will collect all pow with more than one base element and exp = -1
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
# use make_args in case expr was something like -x -> x
args = Mul.make_args(expr)
# Gather args for numerator/denominator
def apow(i):
b, e = i.as_base_exp()
eargs = list(Mul.make_args(e))
if eargs[0] is S.NegativeOne:
eargs = eargs[1:]
else:
eargs[0] = -eargs[0]
e = Mul._from_args(eargs)
if isinstance(i, Pow):
return i.func(b, e, evaluate=False)
return i.func(e, evaluate=False)
for item in args:
if (item.is_commutative and
isinstance(item, Pow) and
bool(item.exp.as_coeff_Mul()[0] < 0)):
if item.exp is not S.NegativeOne:
b.append(apow(item))
else:
if (len(item.args[0].args) != 1 and
isinstance(item.base, Mul)):
# To avoid situations like #14160
pow_paren.append(item)
b.append(item.base)
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)
a = a or [S.One]
a_str = [self.parenthesize(x, prec, strict=False) for x in a]
b_str = [self.parenthesize(x, prec, strict=False) for x in b]
# To parenthesize Pow with exp = -1 and having more than one Symbol
for item in pow_paren:
if item.base in b:
b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
if not b:
return sign + '*'.join(a_str)
elif len(b) == 1:
return sign + '*'.join(a_str) + "/" + b_str[0]
else:
return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str)
def _print_MatMul(self, expr):
c, m = expr.as_coeff_mmul()
sign = ""
if c.is_number:
re, im = c.as_real_imag()
if im.is_zero and re.is_negative:
expr = _keep_coeff(-c, m)
sign = "-"
elif re.is_zero and im.is_negative:
expr = _keep_coeff(-c, m)
sign = "-"
return sign + '*'.join(
[self.parenthesize(arg, precedence(expr)) for arg in expr.args]
)
def _print_ElementwiseApplyFunction(self, expr):
return "{}.({})".format(
expr.function,
self._print(expr.expr),
)
def _print_NaN(self, expr):
return 'nan'
def _print_NegativeInfinity(self, expr):
return '-oo'
def _print_Order(self, expr):
if not expr.variables or all(p is S.Zero for p in expr.point):
if len(expr.variables) <= 1:
return 'O(%s)' % self._print(expr.expr)
else:
return 'O(%s)' % self.stringify((expr.expr,) + expr.variables, ', ', 0)
else:
return 'O(%s)' % self.stringify(expr.args, ', ', 0)
def _print_Ordinal(self, expr):
return expr.__str__()
def _print_Cycle(self, expr):
return expr.__str__()
def _print_Permutation(self, expr):
from sympy.combinatorics.permutations import Permutation, Cycle
from sympy.utilities.exceptions import SymPyDeprecationWarning
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
SymPyDeprecationWarning(
feature="Permutation.print_cyclic = {}".format(perm_cyclic),
useinstead="init_printing(perm_cyclic={})"
.format(perm_cyclic),
issue=15201,
deprecated_since_version="1.6").warn()
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
if not expr.size:
return '()'
# before taking Cycle notation, see if the last element is
# a singleton and move it to the head of the string
s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):]
last = s.rfind('(')
if not last == 0 and ',' not in s[last:]:
s = s[last:] + s[:last]
s = s.replace(',', '')
return s
else:
s = expr.support()
if not s:
if expr.size < 5:
return 'Permutation(%s)' % self._print(expr.array_form)
return 'Permutation([], size=%s)' % self._print(expr.size)
trim = self._print(expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size)
use = full = self._print(expr.array_form)
if len(trim) < len(full):
use = trim
return 'Permutation(%s)' % use
def _print_Subs(self, obj):
expr, old, new = obj.args
if len(obj.point) == 1:
old = old[0]
new = new[0]
return "Subs(%s, %s, %s)" % (
self._print(expr), self._print(old), self._print(new))
def _print_TensorIndex(self, expr):
return expr._print()
def _print_TensorHead(self, expr):
return expr._print()
def _print_Tensor(self, expr):
return expr._print()
def _print_TensMul(self, expr):
# prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)"
sign, args = expr._get_args_for_traditional_printer()
return sign + "*".join(
[self.parenthesize(arg, precedence(expr)) for arg in args]
)
def _print_TensAdd(self, expr):
return expr._print()
def _print_ArraySymbol(self, expr):
return self._print(expr.name)
def _print_ArrayElement(self, expr):
return "%s[%s]" % (expr.name, ", ".join([self._print(i) for i in expr.indices]))
def _print_PermutationGroup(self, expr):
p = [' %s' % self._print(a) for a in expr.args]
return 'PermutationGroup([\n%s])' % ',\n'.join(p)
def _print_Pi(self, expr):
return 'pi'
def _print_PolyRing(self, ring):
return "Polynomial ring in %s over %s with %s order" % \
(", ".join(map(lambda rs: self._print(rs), ring.symbols)),
self._print(ring.domain), self._print(ring.order))
def _print_FracField(self, field):
return "Rational function field in %s over %s with %s order" % \
(", ".join(map(lambda fs: self._print(fs), field.symbols)),
self._print(field.domain), self._print(field.order))
def _print_FreeGroupElement(self, elm):
return elm.__str__()
def _print_GaussianElement(self, poly):
return "(%s + %s*I)" % (poly.x, poly.y)
def _print_PolyElement(self, poly):
return poly.str(self, PRECEDENCE, "%s**%s", "*")
def _print_FracElement(self, frac):
if frac.denom == 1:
return self._print(frac.numer)
else:
numer = self.parenthesize(frac.numer, PRECEDENCE["Mul"], strict=True)
denom = self.parenthesize(frac.denom, PRECEDENCE["Atom"], strict=True)
return numer + "/" + denom
def _print_Poly(self, expr):
ATOM_PREC = PRECEDENCE["Atom"] - 1
terms, gens = [], [ self.parenthesize(s, ATOM_PREC) for s in expr.gens ]
for monom, coeff in expr.terms():
s_monom = []
for i, e in enumerate(monom):
if e > 0:
if e == 1:
s_monom.append(gens[i])
else:
s_monom.append(gens[i] + "**%d" % e)
s_monom = "*".join(s_monom)
if coeff.is_Add:
if s_monom:
s_coeff = "(" + self._print(coeff) + ")"
else:
s_coeff = self._print(coeff)
else:
if s_monom:
if coeff is S.One:
terms.extend(['+', s_monom])
continue
if coeff is S.NegativeOne:
terms.extend(['-', s_monom])
continue
s_coeff = self._print(coeff)
if not s_monom:
s_term = s_coeff
else:
s_term = s_coeff + "*" + s_monom
if s_term.startswith('-'):
terms.extend(['-', s_term[1:]])
else:
terms.extend(['+', s_term])
if terms[0] in ['-', '+']:
modifier = terms.pop(0)
if modifier == '-':
terms[0] = '-' + terms[0]
format = expr.__class__.__name__ + "(%s, %s"
from sympy.polys.polyerrors import PolynomialError
try:
format += ", modulus=%s" % expr.get_modulus()
except PolynomialError:
format += ", domain='%s'" % expr.get_domain()
format += ")"
for index, item in enumerate(gens):
if len(item) > 2 and (item[:1] == "(" and item[len(item) - 1:] == ")"):
gens[index] = item[1:len(item) - 1]
return format % (' '.join(terms), ', '.join(gens))
def _print_UniversalSet(self, p):
return 'UniversalSet'
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_Pow(self, expr, rational=False):
"""Printing helper function for ``Pow``
Parameters
==========
rational : bool, optional
If ``True``, it will not attempt printing ``sqrt(x)`` or
``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)``
instead.
See examples for additional details
Examples
========
>>> from sympy.functions import sqrt
>>> from sympy.printing.str import StrPrinter
>>> from sympy.abc import x
How ``rational`` keyword works with ``sqrt``:
>>> printer = StrPrinter()
>>> printer._print_Pow(sqrt(x), rational=True)
'x**(1/2)'
>>> printer._print_Pow(sqrt(x), rational=False)
'sqrt(x)'
>>> printer._print_Pow(1/sqrt(x), rational=True)
'x**(-1/2)'
>>> printer._print_Pow(1/sqrt(x), rational=False)
'1/sqrt(x)'
Notes
=====
``sqrt(x)`` is canonicalized as ``Pow(x, S.Half)`` in SymPy,
so there is no need of defining a separate printer for ``sqrt``.
Instead, it should be handled here as well.
"""
PREC = precedence(expr)
if expr.exp is S.Half and not rational:
return "sqrt(%s)" % self._print(expr.base)
if expr.is_commutative:
if -expr.exp is S.Half and not rational:
# Note: Don't test "expr.exp == -S.Half" here, because that will
# match -0.5, which we don't want.
return "%s/sqrt(%s)" % tuple(map(lambda arg: self._print(arg), (S.One, expr.base)))
if expr.exp is -S.One:
# Similarly to the S.Half case, don't test with "==" here.
return '%s/%s' % (self._print(S.One),
self.parenthesize(expr.base, PREC, strict=False))
e = self.parenthesize(expr.exp, PREC, strict=False)
if self.printmethod == '_sympyrepr' and expr.exp.is_Rational and expr.exp.q != 1:
# the parenthesized exp should be '(Rational(a, b))' so strip parens,
# but just check to be sure.
if e.startswith('(Rational'):
return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e[1:-1])
return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e)
def _print_UnevaluatedExpr(self, expr):
return self._print(expr.args[0])
def _print_MatPow(self, expr):
PREC = precedence(expr)
return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False),
self.parenthesize(expr.exp, PREC, strict=False))
def _print_Integer(self, expr):
if self._settings.get("sympy_integers", False):
return "S(%s)" % (expr)
return str(expr.p)
def _print_Integers(self, expr):
return 'Integers'
def _print_Naturals(self, expr):
return 'Naturals'
def _print_Naturals0(self, expr):
return 'Naturals0'
def _print_Rationals(self, expr):
return 'Rationals'
def _print_Reals(self, expr):
return 'Reals'
def _print_Complexes(self, expr):
return 'Complexes'
def _print_EmptySet(self, expr):
return 'EmptySet'
def _print_EmptySequence(self, expr):
return 'EmptySequence'
def _print_int(self, expr):
return str(expr)
def _print_mpz(self, expr):
return str(expr)
def _print_Rational(self, expr):
if expr.q == 1:
return str(expr.p)
else:
if self._settings.get("sympy_integers", False):
return "S(%s)/%s" % (expr.p, expr.q)
return "%s/%s" % (expr.p, expr.q)
def _print_PythonRational(self, expr):
if expr.q == 1:
return str(expr.p)
else:
return "%d/%d" % (expr.p, expr.q)
def _print_Fraction(self, expr):
if expr.denominator == 1:
return str(expr.numerator)
else:
return "%s/%s" % (expr.numerator, expr.denominator)
def _print_mpq(self, expr):
if expr.denominator == 1:
return str(expr.numerator)
else:
return "%s/%s" % (expr.numerator, expr.denominator)
def _print_Float(self, expr):
prec = expr._prec
if prec < 5:
dps = 0
else:
dps = prec_to_dps(expr._prec)
if self._settings["full_prec"] is True:
strip = False
elif self._settings["full_prec"] is False:
strip = True
elif self._settings["full_prec"] == "auto":
strip = self._print_level > 1
low = self._settings["min"] if "min" in self._settings else None
high = self._settings["max"] if "max" in self._settings else None
rv = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high)
if rv.startswith('-.0'):
rv = '-0.' + rv[3:]
elif rv.startswith('.0'):
rv = '0.' + rv[2:]
if rv.startswith('+'):
# e.g., +inf -> inf
rv = rv[1:]
return rv
def _print_Relational(self, expr):
charmap = {
"==": "Eq",
"!=": "Ne",
":=": "Assignment",
'+=': "AddAugmentedAssignment",
"-=": "SubAugmentedAssignment",
"*=": "MulAugmentedAssignment",
"/=": "DivAugmentedAssignment",
"%=": "ModAugmentedAssignment",
}
if expr.rel_op in charmap:
return '%s(%s, %s)' % (charmap[expr.rel_op], self._print(expr.lhs),
self._print(expr.rhs))
return '%s %s %s' % (self.parenthesize(expr.lhs, precedence(expr)),
self._relationals.get(expr.rel_op) or expr.rel_op,
self.parenthesize(expr.rhs, precedence(expr)))
def _print_ComplexRootOf(self, expr):
return "CRootOf(%s, %d)" % (self._print_Add(expr.expr, order='lex'),
expr.index)
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))
return "RootSum(%s)" % ", ".join(args)
def _print_GroebnerBasis(self, basis):
cls = basis.__class__.__name__
exprs = [self._print_Add(arg, order=basis.order) for arg in basis.exprs]
exprs = "[%s]" % ", ".join(exprs)
gens = [ self._print(gen) for gen in basis.gens ]
domain = "domain='%s'" % self._print(basis.domain)
order = "order='%s'" % self._print(basis.order)
args = [exprs] + gens + [domain, order]
return "%s(%s)" % (cls, ", ".join(args))
def _print_set(self, s):
items = sorted(s, key=default_sort_key)
args = ', '.join(self._print(item) for item in items)
if not args:
return "set()"
return '{%s}' % args
def _print_frozenset(self, s):
if not s:
return "frozenset()"
return "frozenset(%s)" % self._print_set(s)
def _print_Sum(self, expr):
def _xab_tostr(xab):
if len(xab) == 1:
return self._print(xab[0])
else:
return self._print((xab[0],) + tuple(xab[1:]))
L = ', '.join([_xab_tostr(l) for l in expr.limits])
return 'Sum(%s, %s)' % (self._print(expr.function), L)
def _print_Symbol(self, expr):
return expr.name
_print_MatrixSymbol = _print_Symbol
_print_RandomSymbol = _print_Symbol
def _print_Identity(self, expr):
return "I"
def _print_ZeroMatrix(self, expr):
return "0"
def _print_OneMatrix(self, expr):
return "1"
def _print_Predicate(self, expr):
return "Q.%s" % expr.name
def _print_str(self, expr):
return str(expr)
def _print_tuple(self, expr):
if len(expr) == 1:
return "(%s,)" % self._print(expr[0])
else:
return "(%s)" % self.stringify(expr, ", ")
def _print_Tuple(self, expr):
return self._print_tuple(expr)
def _print_Transpose(self, T):
return "%s.T" % self.parenthesize(T.arg, PRECEDENCE["Pow"])
def _print_Uniform(self, expr):
return "Uniform(%s, %s)" % (self._print(expr.a), self._print(expr.b))
def _print_Quantity(self, expr):
if self._settings.get("abbrev", False):
return "%s" % expr.abbrev
return "%s" % expr.name
def _print_Quaternion(self, expr):
s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args]
a = [s[0]] + [i+"*"+j for i, j in zip(s[1:], "ijk")]
return " + ".join(a)
def _print_Dimension(self, expr):
return str(expr)
def _print_Wild(self, expr):
return expr.name + '_'
def _print_WildFunction(self, expr):
return expr.name + '_'
def _print_WildDot(self, expr):
return expr.name
def _print_WildPlus(self, expr):
return expr.name
def _print_WildStar(self, expr):
return expr.name
def _print_Zero(self, expr):
if self._settings.get("sympy_integers", False):
return "S(0)"
return "0"
def _print_DMP(self, p):
from sympy.core.sympify import SympifyError
try:
if p.ring is not None:
# TODO incorporate order
return self._print(p.ring.to_sympy(p))
except SympifyError:
pass
cls = p.__class__.__name__
rep = self._print(p.rep)
dom = self._print(p.dom)
ring = self._print(p.ring)
return "%s(%s, %s, %s)" % (cls, rep, dom, ring)
def _print_DMF(self, expr):
return self._print_DMP(expr)
def _print_Object(self, obj):
return 'Object("%s")' % obj.name
def _print_IdentityMorphism(self, morphism):
return 'IdentityMorphism(%s)' % morphism.domain
def _print_NamedMorphism(self, morphism):
return 'NamedMorphism(%s, %s, "%s")' % \
(morphism.domain, morphism.codomain, morphism.name)
def _print_Category(self, category):
return 'Category("%s")' % category.name
def _print_Manifold(self, manifold):
return manifold.name.name
def _print_Patch(self, patch):
return patch.name.name
def _print_CoordSystem(self, coords):
return coords.name.name
def _print_BaseScalarField(self, field):
return field._coord_sys.symbols[field._index].name
def _print_BaseVectorField(self, field):
return 'e_%s' % field._coord_sys.symbols[field._index].name
def _print_Differential(self, diff):
field = diff._form_field
if hasattr(field, '_coord_sys'):
return 'd%s' % field._coord_sys.symbols[field._index].name
else:
return 'd(%s)' % self._print(field)
def _print_Tr(self, expr):
#TODO : Handle indices
return "%s(%s)" % ("Tr", self._print(expr.args[0]))
def _print_Str(self, s):
return self._print(s.name)
def _print_AppliedBinaryRelation(self, expr):
rel, args = expr.function, expr.arguments
lhs, rhs = args
return '%s(%s, %s)' % (self._print(rel),
self._print(expr.lhs),
self._print(expr.rhs))
@print_function(StrPrinter)
def sstr(expr, **settings):
"""Returns the expression as a string.
For large expressions where speed is a concern, use the setting
order='none'. If abbrev=True setting is used then units are printed in
abbreviated form.
Examples
========
>>> from sympy import symbols, Eq, sstr
>>> a, b = symbols('a b')
>>> sstr(Eq(a + b, 0))
'Eq(a + b, 0)'
"""
p = StrPrinter(settings)
s = p.doprint(expr)
return s
class StrReprPrinter(StrPrinter):
"""(internal) -- see sstrrepr"""
def _print_str(self, s):
return repr(s)
def _print_Str(self, s):
# Str does not to be printed same as str here
return "%s(%s)" % (s.__class__.__name__, self._print(s.name))
@print_function(StrReprPrinter)
def sstrrepr(expr, **settings):
"""return expr in mixed str/repr form
i.e. strings are returned in repr form with quotes, and everything else
is returned in str form.
This function could be useful for hooking into sys.displayhook
"""
p = StrReprPrinter(settings)
s = p.doprint(expr)
return s
|
f079ebe4068a28b2faa3cb6afdbe7aa575be88d06aff80518546c1258ad1d19d | from .pycode import (
PythonCodePrinter,
MpmathPrinter, # MpmathPrinter is imported for backward compatibility
)
from .numpy import NumPyPrinter # NumPyPrinter is imported for backward compatibility
from sympy.utilities import default_sort_key
__all__ = [
'PythonCodePrinter',
'MpmathPrinter',
'NumPyPrinter',
'LambdaPrinter',
'NumPyPrinter',
'lambdarepr',
]
class LambdaPrinter(PythonCodePrinter):
"""
This printer converts expressions into strings that can be used by
lambdify.
"""
printmethod = "_lambdacode"
def _print_And(self, expr):
result = ['(']
for arg in sorted(expr.args, key=default_sort_key):
result.extend(['(', self._print(arg), ')'])
result.append(' and ')
result = result[:-1]
result.append(')')
return ''.join(result)
def _print_Or(self, expr):
result = ['(']
for arg in sorted(expr.args, key=default_sort_key):
result.extend(['(', self._print(arg), ')'])
result.append(' or ')
result = result[:-1]
result.append(')')
return ''.join(result)
def _print_Not(self, expr):
result = ['(', 'not (', self._print(expr.args[0]), '))']
return ''.join(result)
def _print_BooleanTrue(self, expr):
return "True"
def _print_BooleanFalse(self, expr):
return "False"
def _print_ITE(self, expr):
result = [
'((', self._print(expr.args[1]),
') if (', self._print(expr.args[0]),
') else (', self._print(expr.args[2]), '))'
]
return ''.join(result)
def _print_NumberSymbol(self, expr):
return str(expr)
def _print_Pow(self, expr, **kwargs):
# XXX Temporary workaround. Should python math printer be
# isolated from PythonCodePrinter?
return super(PythonCodePrinter, self)._print_Pow(expr, **kwargs)
# numexpr works by altering the string passed to numexpr.evaluate
# rather than by populating a namespace. Thus a special printer...
class NumExprPrinter(LambdaPrinter):
# key, value pairs correspond to sympy name and numexpr name
# functions not appearing in this dict will raise a TypeError
printmethod = "_numexprcode"
_numexpr_functions = {
'sin' : 'sin',
'cos' : 'cos',
'tan' : 'tan',
'asin': 'arcsin',
'acos': 'arccos',
'atan': 'arctan',
'atan2' : 'arctan2',
'sinh' : 'sinh',
'cosh' : 'cosh',
'tanh' : 'tanh',
'asinh': 'arcsinh',
'acosh': 'arccosh',
'atanh': 'arctanh',
'ln' : 'log',
'log': 'log',
'exp': 'exp',
'sqrt' : 'sqrt',
'Abs' : 'abs',
'conjugate' : 'conj',
'im' : 'imag',
're' : 'real',
'where' : 'where',
'complex' : 'complex',
'contains' : 'contains',
}
def _print_ImaginaryUnit(self, expr):
return '1j'
def _print_seq(self, seq, delimiter=', '):
# simplified _print_seq taken from pretty.py
s = [self._print(item) for item in seq]
if s:
return delimiter.join(s)
else:
return ""
def _print_Function(self, e):
func_name = e.func.__name__
nstr = self._numexpr_functions.get(func_name, None)
if nstr is None:
# check for implemented_function
if hasattr(e, '_imp_'):
return "(%s)" % self._print(e._imp_(*e.args))
else:
raise TypeError("numexpr does not support function '%s'" %
func_name)
return "%s(%s)" % (nstr, self._print_seq(e.args))
def _print_Piecewise(self, expr):
"Piecewise function printer"
exprs = [self._print(arg.expr) for arg in expr.args]
conds = [self._print(arg.cond) for arg in expr.args]
# If [default_value, True] is a (expr, cond) sequence in a Piecewise object
# it will behave the same as passing the 'default' kwarg to select()
# *as long as* it is the last element in expr.args.
# If this is not the case, it may be triggered prematurely.
ans = []
parenthesis_count = 0
is_last_cond_True = False
for cond, expr in zip(conds, exprs):
if cond == 'True':
ans.append(expr)
is_last_cond_True = True
break
else:
ans.append('where(%s, %s, ' % (cond, expr))
parenthesis_count += 1
if not is_last_cond_True:
# simplest way to put a nan but raises
# 'RuntimeWarning: invalid value encountered in log'
ans.append('log(-1)')
return ''.join(ans) + ')' * parenthesis_count
def _print_ITE(self, expr):
from sympy.functions.elementary.piecewise import Piecewise
return self._print(expr.rewrite(Piecewise))
def blacklisted(self, expr):
raise TypeError("numexpr cannot be used with %s" %
expr.__class__.__name__)
# blacklist all Matrix printing
_print_SparseMatrix = \
_print_MutableSparseMatrix = \
_print_ImmutableSparseMatrix = \
_print_Matrix = \
_print_DenseMatrix = \
_print_MutableDenseMatrix = \
_print_ImmutableMatrix = \
_print_ImmutableDenseMatrix = \
blacklisted
# blacklist some python expressions
_print_list = \
_print_tuple = \
_print_Tuple = \
_print_dict = \
_print_Dict = \
blacklisted
def doprint(self, expr):
lstr = super().doprint(expr)
return "evaluate('%s', truediv=True)" % lstr
for k in NumExprPrinter._numexpr_functions:
setattr(NumExprPrinter, '_print_%s' % k, NumExprPrinter._print_Function)
def lambdarepr(expr, **settings):
"""
Returns a string usable for lambdifying.
"""
return LambdaPrinter(settings).doprint(expr)
|
0d42fe9aa848c92b06be3280110a7ee696d17fb4cdfd5015246f291d0b04e467 | """
A Printer for generating executable code.
The most important function here is srepr that returns a string so that the
relation eval(srepr(expr))=expr holds in an appropriate environment.
"""
from typing import Any, Dict
from sympy.core.function import AppliedUndef
from sympy.core.mul import Mul
from mpmath.libmp import repr_dps, to_str as mlib_to_str
from .printer import Printer, print_function
class ReprPrinter(Printer):
printmethod = "_sympyrepr"
_default_settings = {
"order": None,
"perm_cyclic" : True,
} # type: Dict[str, Any]
def reprify(self, args, sep):
"""
Prints each item in `args` and joins them with `sep`.
"""
return sep.join([self.doprint(item) for item in args])
def emptyPrinter(self, expr):
"""
The fallback printer.
"""
if isinstance(expr, str):
return expr
elif hasattr(expr, "__srepr__"):
return expr.__srepr__()
elif hasattr(expr, "args") and hasattr(expr.args, "__iter__"):
l = []
for o in expr.args:
l.append(self._print(o))
return expr.__class__.__name__ + '(%s)' % ', '.join(l)
elif hasattr(expr, "__module__") and hasattr(expr, "__name__"):
return "<'%s.%s'>" % (expr.__module__, expr.__name__)
else:
return str(expr)
def _print_Add(self, expr, order=None):
args = self._as_ordered_terms(expr, order=order)
nargs = len(args)
args = map(self._print, args)
clsname = type(expr).__name__
if nargs > 255: # Issue #10259, Python < 3.7
return clsname + "(*[%s])" % ", ".join(args)
return clsname + "(%s)" % ", ".join(args)
def _print_Cycle(self, expr):
return expr.__repr__()
def _print_Permutation(self, expr):
from sympy.combinatorics.permutations import Permutation, Cycle
from sympy.utilities.exceptions import SymPyDeprecationWarning
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
SymPyDeprecationWarning(
feature="Permutation.print_cyclic = {}".format(perm_cyclic),
useinstead="init_printing(perm_cyclic={})"
.format(perm_cyclic),
issue=15201,
deprecated_since_version="1.6").warn()
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
if not expr.size:
return 'Permutation()'
# before taking Cycle notation, see if the last element is
# a singleton and move it to the head of the string
s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):]
last = s.rfind('(')
if not last == 0 and ',' not in s[last:]:
s = s[last:] + s[:last]
return 'Permutation%s' %s
else:
s = expr.support()
if not s:
if expr.size < 5:
return 'Permutation(%s)' % str(expr.array_form)
return 'Permutation([], size=%s)' % expr.size
trim = str(expr.array_form[:s[-1] + 1]) + ', size=%s' % expr.size
use = full = str(expr.array_form)
if len(trim) < len(full):
use = trim
return 'Permutation(%s)' % use
def _print_Function(self, expr):
r = self._print(expr.func)
r += '(%s)' % ', '.join([self._print(a) for a in expr.args])
return r
def _print_FunctionClass(self, expr):
if issubclass(expr, AppliedUndef):
return 'Function(%r)' % (expr.__name__)
else:
return expr.__name__
def _print_Half(self, expr):
return 'Rational(1, 2)'
def _print_RationalConstant(self, expr):
return str(expr)
def _print_AtomicExpr(self, expr):
return str(expr)
def _print_NumberSymbol(self, expr):
return str(expr)
def _print_Integer(self, expr):
return 'Integer(%i)' % expr.p
def _print_Integers(self, expr):
return 'Integers'
def _print_Naturals(self, expr):
return 'Naturals'
def _print_Naturals0(self, expr):
return 'Naturals0'
def _print_Reals(self, expr):
return 'Reals'
def _print_EmptySet(self, expr):
return 'EmptySet'
def _print_EmptySequence(self, expr):
return 'EmptySequence'
def _print_list(self, expr):
return "[%s]" % self.reprify(expr, ", ")
def _print_dict(self, expr):
sep = ", "
dict_kvs = ["%s: %s" % (self.doprint(key), self.doprint(value)) for key, value in expr.items()]
return "{%s}" % sep.join(dict_kvs)
def _print_set(self, expr):
if not expr:
return "set()"
return "{%s}" % self.reprify(expr, ", ")
def _print_MatrixBase(self, expr):
# special case for some empty matrices
if (expr.rows == 0) ^ (expr.cols == 0):
return '%s(%s, %s, %s)' % (expr.__class__.__name__,
self._print(expr.rows),
self._print(expr.cols),
self._print([]))
l = []
for i in range(expr.rows):
l.append([])
for j in range(expr.cols):
l[-1].append(expr[i, j])
return '%s(%s)' % (expr.__class__.__name__, self._print(l))
def _print_BooleanTrue(self, expr):
return "true"
def _print_BooleanFalse(self, expr):
return "false"
def _print_NaN(self, expr):
return "nan"
def _print_Mul(self, expr, order=None):
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
# use make_args in case expr was something like -x -> x
args = Mul.make_args(expr)
nargs = len(args)
args = map(self._print, args)
clsname = type(expr).__name__
if nargs > 255: # Issue #10259, Python < 3.7
return clsname + "(*[%s])" % ", ".join(args)
return clsname + "(%s)" % ", ".join(args)
def _print_Rational(self, expr):
return 'Rational(%s, %s)' % (self._print(expr.p), self._print(expr.q))
def _print_PythonRational(self, expr):
return "%s(%d, %d)" % (expr.__class__.__name__, expr.p, expr.q)
def _print_Fraction(self, expr):
return 'Fraction(%s, %s)' % (self._print(expr.numerator), self._print(expr.denominator))
def _print_Float(self, expr):
r = mlib_to_str(expr._mpf_, repr_dps(expr._prec))
return "%s('%s', precision=%i)" % (expr.__class__.__name__, r, expr._prec)
def _print_Sum2(self, expr):
return "Sum2(%s, (%s, %s, %s))" % (self._print(expr.f), self._print(expr.i),
self._print(expr.a), self._print(expr.b))
def _print_Str(self, s):
return "%s(%s)" % (s.__class__.__name__, self._print(s.name))
def _print_Symbol(self, expr):
d = expr._assumptions.generator
# print the dummy_index like it was an assumption
if expr.is_Dummy:
d['dummy_index'] = expr.dummy_index
if d == {}:
return "%s(%s)" % (expr.__class__.__name__, self._print(expr.name))
else:
attr = ['%s=%s' % (k, v) for k, v in d.items()]
return "%s(%s, %s)" % (expr.__class__.__name__,
self._print(expr.name), ', '.join(attr))
def _print_CoordinateSymbol(self, expr):
d = expr._assumptions.generator
if d == {}:
return "%s(%s, %s)" % (
expr.__class__.__name__,
self._print(expr.coord_sys),
self._print(expr.index)
)
else:
attr = ['%s=%s' % (k, v) for k, v in d.items()]
return "%s(%s, %s, %s)" % (
expr.__class__.__name__,
self._print(expr.coord_sys),
self._print(expr.index),
', '.join(attr)
)
def _print_Predicate(self, expr):
return "Q.%s" % expr.name
def _print_AppliedPredicate(self, expr):
# will be changed to just expr.args when args overriding is removed
args = expr._args
return "%s(%s)" % (expr.__class__.__name__, self.reprify(args, ", "))
def _print_str(self, expr):
return repr(expr)
def _print_tuple(self, expr):
if len(expr) == 1:
return "(%s,)" % self._print(expr[0])
else:
return "(%s)" % self.reprify(expr, ", ")
def _print_WildFunction(self, expr):
return "%s('%s')" % (expr.__class__.__name__, expr.name)
def _print_AlgebraicNumber(self, expr):
return "%s(%s, %s)" % (expr.__class__.__name__,
self._print(expr.root), self._print(expr.coeffs()))
def _print_PolyRing(self, ring):
return "%s(%s, %s, %s)" % (ring.__class__.__name__,
self._print(ring.symbols), self._print(ring.domain), self._print(ring.order))
def _print_FracField(self, field):
return "%s(%s, %s, %s)" % (field.__class__.__name__,
self._print(field.symbols), self._print(field.domain), self._print(field.order))
def _print_PolyElement(self, poly):
terms = list(poly.terms())
terms.sort(key=poly.ring.order, reverse=True)
return "%s(%s, %s)" % (poly.__class__.__name__, self._print(poly.ring), self._print(terms))
def _print_FracElement(self, frac):
numer_terms = list(frac.numer.terms())
numer_terms.sort(key=frac.field.order, reverse=True)
denom_terms = list(frac.denom.terms())
denom_terms.sort(key=frac.field.order, reverse=True)
numer = self._print(numer_terms)
denom = self._print(denom_terms)
return "%s(%s, %s, %s)" % (frac.__class__.__name__, self._print(frac.field), numer, denom)
def _print_FractionField(self, domain):
cls = domain.__class__.__name__
field = self._print(domain.field)
return "%s(%s)" % (cls, field)
def _print_PolynomialRingBase(self, ring):
cls = ring.__class__.__name__
dom = self._print(ring.domain)
gens = ', '.join(map(self._print, ring.gens))
order = str(ring.order)
if order != ring.default_order:
orderstr = ", order=" + order
else:
orderstr = ""
return "%s(%s, %s%s)" % (cls, dom, gens, orderstr)
def _print_DMP(self, p):
cls = p.__class__.__name__
rep = self._print(p.rep)
dom = self._print(p.dom)
if p.ring is not None:
ringstr = ", ring=" + self._print(p.ring)
else:
ringstr = ""
return "%s(%s, %s%s)" % (cls, rep, dom, ringstr)
def _print_MonogenicFiniteExtension(self, ext):
# The expanded tree shown by srepr(ext.modulus)
# is not practical.
return "FiniteExtension(%s)" % str(ext.modulus)
def _print_ExtensionElement(self, f):
rep = self._print(f.rep)
ext = self._print(f.ext)
return "ExtElem(%s, %s)" % (rep, ext)
@print_function(ReprPrinter)
def srepr(expr, **settings):
"""return expr in repr form"""
return ReprPrinter(settings).doprint(expr)
|
67edc03ba2b60650c9a1c92bc4ce4e5325cb63cb3e6f4e70e0119e81a71f61c9 | """ Integral Transforms """
from functools import reduce
from sympy.core import S
from sympy.core.compatibility import iterable, ordered
from sympy.core.function import Function
from sympy.core.relational import _canonical, Ge, Gt
from sympy.core.numbers import oo
from sympy.core.symbol import Dummy
from sympy.functions import DiracDelta
from sympy.functions.elementary.miscellaneous import Max
from sympy.integrals import integrate, Integral
from sympy.integrals.meijerint import _dummy
from sympy.logic.boolalg import to_cnf, conjuncts, disjuncts, Or, And
from sympy.simplify import simplify
from sympy.utilities import default_sort_key
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.matrices.matrices import MatrixBase
from sympy.polys.matrices.linsolve import _lin_eq2dict, PolyNonlinearError
##########################################################################
# Helpers / Utilities
##########################################################################
class IntegralTransformError(NotImplementedError):
"""
Exception raised in relation to problems computing transforms.
Explanation
===========
This class is mostly used internally; if integrals cannot be computed
objects representing unevaluated transforms are usually returned.
The hint ``needeval=True`` can be used to disable returning transform
objects, and instead raise this exception if an integral cannot be
computed.
"""
def __init__(self, transform, function, msg):
super().__init__(
"%s Transform could not be computed: %s." % (transform, msg))
self.function = function
class IntegralTransform(Function):
"""
Base class for integral transforms.
Explanation
===========
This class represents unevaluated transforms.
To implement a concrete transform, derive from this class and implement
the ``_compute_transform(f, x, s, **hints)`` and ``_as_integral(f, x, s)``
functions. If the transform cannot be computed, raise :obj:`IntegralTransformError`.
Also set ``cls._name``. For instance,
>>> from sympy.integrals.transforms import LaplaceTransform
>>> LaplaceTransform._name
'Laplace'
Implement ``self._collapse_extra`` if your function returns more than just a
number and possibly a convergence condition.
"""
@property
def function(self):
""" The function to be transformed. """
return self.args[0]
@property
def function_variable(self):
""" The dependent variable of the function to be transformed. """
return self.args[1]
@property
def transform_variable(self):
""" The independent transform variable. """
return self.args[2]
@property
def free_symbols(self):
"""
This method returns the symbols that will exist when the transform
is evaluated.
"""
return self.function.free_symbols.union({self.transform_variable}) \
- {self.function_variable}
def _compute_transform(self, f, x, s, **hints):
raise NotImplementedError
def _as_integral(self, f, x, s):
raise NotImplementedError
def _collapse_extra(self, extra):
cond = And(*extra)
if cond == False:
raise IntegralTransformError(self.__class__.name, None, '')
return cond
def doit(self, **hints):
"""
Try to evaluate the transform in closed form.
Explanation
===========
This general function handles linearity, but apart from that leaves
pretty much everything to _compute_transform.
Standard hints are the following:
- ``simplify``: whether or not to simplify the result
- ``noconds``: if True, don't return convergence conditions
- ``needeval``: if True, raise IntegralTransformError instead of
returning IntegralTransform objects
The default values of these hints depend on the concrete transform,
usually the default is
``(simplify, noconds, needeval) = (True, False, False)``.
"""
from sympy import Add, expand_mul, Mul
from sympy.core.function import AppliedUndef
needeval = hints.pop('needeval', False)
try_directly = not any(func.has(self.function_variable)
for func in self.function.atoms(AppliedUndef))
if try_directly:
try:
return self._compute_transform(self.function,
self.function_variable, self.transform_variable, **hints)
except IntegralTransformError:
pass
fn = self.function
if not fn.is_Add:
fn = expand_mul(fn)
if fn.is_Add:
hints['needeval'] = needeval
res = [self.__class__(*([x] + list(self.args[1:]))).doit(**hints)
for x in fn.args]
extra = []
ress = []
for x in res:
if not isinstance(x, tuple):
x = [x]
ress.append(x[0])
if len(x) == 2:
# only a condition
extra.append(x[1])
elif len(x) > 2:
# some region parameters and a condition (Mellin, Laplace)
extra += [x[1:]]
res = Add(*ress)
if not extra:
return res
try:
extra = self._collapse_extra(extra)
if iterable(extra):
return tuple([res]) + tuple(extra)
else:
return (res, extra)
except IntegralTransformError:
pass
if needeval:
raise IntegralTransformError(
self.__class__._name, self.function, 'needeval')
# TODO handle derivatives etc
# pull out constant coefficients
coeff, rest = fn.as_coeff_mul(self.function_variable)
return coeff*self.__class__(*([Mul(*rest)] + list(self.args[1:])))
@property
def as_integral(self):
return self._as_integral(self.function, self.function_variable,
self.transform_variable)
def _eval_rewrite_as_Integral(self, *args, **kwargs):
return self.as_integral
from sympy.solvers.inequalities import _solve_inequality
def _simplify(expr, doit):
from sympy import powdenest, piecewise_fold
if doit:
return simplify(powdenest(piecewise_fold(expr), polar=True))
return expr
def _noconds_(default):
"""
This is a decorator generator for dropping convergence conditions.
Explanation
===========
Suppose you define a function ``transform(*args)`` which returns a tuple of
the form ``(result, cond1, cond2, ...)``.
Decorating it ``@_noconds_(default)`` will add a new keyword argument
``noconds`` to it. If ``noconds=True``, the return value will be altered to
be only ``result``, whereas if ``noconds=False`` the return value will not
be altered.
The default value of the ``noconds`` keyword will be ``default`` (i.e. the
argument of this function).
"""
def make_wrapper(func):
from sympy.core.decorators import wraps
@wraps(func)
def wrapper(*args, noconds=default, **kwargs):
res = func(*args, **kwargs)
if noconds:
return res[0]
return res
return wrapper
return make_wrapper
_noconds = _noconds_(False)
##########################################################################
# Mellin Transform
##########################################################################
def _default_integrator(f, x):
return integrate(f, (x, 0, oo))
@_noconds
def _mellin_transform(f, x, s_, integrator=_default_integrator, simplify=True):
""" Backend function to compute Mellin transforms. """
from sympy import re, Max, Min, count_ops
# We use a fresh dummy, because assumptions on s might drop conditions on
# convergence of the integral.
s = _dummy('s', 'mellin-transform', f)
F = integrator(x**(s - 1) * f, x)
if not F.has(Integral):
return _simplify(F.subs(s, s_), simplify), (-oo, oo), S.true
if not F.is_Piecewise: # XXX can this work if integration gives continuous result now?
raise IntegralTransformError('Mellin', f, 'could not compute integral')
F, cond = F.args[0]
if F.has(Integral):
raise IntegralTransformError(
'Mellin', f, 'integral in unexpected form')
def process_conds(cond):
"""
Turn ``cond`` into a strip (a, b), and auxiliary conditions.
"""
a = -oo
b = oo
aux = S.true
conds = conjuncts(to_cnf(cond))
t = Dummy('t', real=True)
for c in conds:
a_ = oo
b_ = -oo
aux_ = []
for d in disjuncts(c):
d_ = d.replace(
re, lambda x: x.as_real_imag()[0]).subs(re(s), t)
if not d.is_Relational or \
d.rel_op in ('==', '!=') \
or d_.has(s) or not d_.has(t):
aux_ += [d]
continue
soln = _solve_inequality(d_, t)
if not soln.is_Relational or \
soln.rel_op in ('==', '!='):
aux_ += [d]
continue
if soln.lts == t:
b_ = Max(soln.gts, b_)
else:
a_ = Min(soln.lts, a_)
if a_ != oo and a_ != b:
a = Max(a_, a)
elif b_ != -oo and b_ != a:
b = Min(b_, b)
else:
aux = And(aux, Or(*aux_))
return a, b, aux
conds = [process_conds(c) for c in disjuncts(cond)]
conds = [x for x in conds if x[2] != False]
conds.sort(key=lambda x: (x[0] - x[1], count_ops(x[2])))
if not conds:
raise IntegralTransformError('Mellin', f, 'no convergence found')
a, b, aux = conds[0]
return _simplify(F.subs(s, s_), simplify), (a, b), aux
class MellinTransform(IntegralTransform):
"""
Class representing unevaluated Mellin transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute Mellin transforms, see the :func:`mellin_transform`
docstring.
"""
_name = 'Mellin'
def _compute_transform(self, f, x, s, **hints):
return _mellin_transform(f, x, s, **hints)
def _as_integral(self, f, x, s):
return Integral(f*x**(s - 1), (x, 0, oo))
def _collapse_extra(self, extra):
from sympy import Max, Min
a = []
b = []
cond = []
for (sa, sb), c in extra:
a += [sa]
b += [sb]
cond += [c]
res = (Max(*a), Min(*b)), And(*cond)
if (res[0][0] >= res[0][1]) == True or res[1] == False:
raise IntegralTransformError(
'Mellin', None, 'no combined convergence.')
return res
def mellin_transform(f, x, s, **hints):
r"""
Compute the Mellin transform `F(s)` of `f(x)`,
.. math :: F(s) = \int_0^\infty x^{s-1} f(x) \mathrm{d}x.
For all "sensible" functions, this converges absolutely in a strip
`a < \operatorname{Re}(s) < b`.
Explanation
===========
The Mellin transform is related via change of variables to the Fourier
transform, and also to the (bilateral) Laplace transform.
This function returns ``(F, (a, b), cond)``
where ``F`` is the Mellin transform of ``f``, ``(a, b)`` is the fundamental strip
(as above), and ``cond`` are auxiliary convergence conditions.
If the integral cannot be computed in closed form, this function returns
an unevaluated :class:`MellinTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`. If ``noconds=False``,
then only `F` will be returned (i.e. not ``cond``, and also not the strip
``(a, b)``).
Examples
========
>>> from sympy.integrals.transforms import mellin_transform
>>> from sympy import exp
>>> from sympy.abc import x, s
>>> mellin_transform(exp(-x), x, s)
(gamma(s), (0, oo), True)
See Also
========
inverse_mellin_transform, laplace_transform, fourier_transform
hankel_transform, inverse_hankel_transform
"""
return MellinTransform(f, x, s).doit(**hints)
def _rewrite_sin(m_n, s, a, b):
"""
Re-write the sine function ``sin(m*s + n)`` as gamma functions, compatible
with the strip (a, b).
Return ``(gamma1, gamma2, fac)`` so that ``f == fac/(gamma1 * gamma2)``.
Examples
========
>>> from sympy.integrals.transforms import _rewrite_sin
>>> from sympy import pi, S
>>> from sympy.abc import s
>>> _rewrite_sin((pi, 0), s, 0, 1)
(gamma(s), gamma(1 - s), pi)
>>> _rewrite_sin((pi, 0), s, 1, 0)
(gamma(s - 1), gamma(2 - s), -pi)
>>> _rewrite_sin((pi, 0), s, -1, 0)
(gamma(s + 1), gamma(-s), -pi)
>>> _rewrite_sin((pi, pi/2), s, S(1)/2, S(3)/2)
(gamma(s - 1/2), gamma(3/2 - s), -pi)
>>> _rewrite_sin((pi, pi), s, 0, 1)
(gamma(s), gamma(1 - s), -pi)
>>> _rewrite_sin((2*pi, 0), s, 0, S(1)/2)
(gamma(2*s), gamma(1 - 2*s), pi)
>>> _rewrite_sin((2*pi, 0), s, S(1)/2, 1)
(gamma(2*s - 1), gamma(2 - 2*s), -pi)
"""
# (This is a separate function because it is moderately complicated,
# and I want to doctest it.)
# We want to use pi/sin(pi*x) = gamma(x)*gamma(1-x).
# But there is one comlication: the gamma functions determine the
# inegration contour in the definition of the G-function. Usually
# it would not matter if this is slightly shifted, unless this way
# we create an undefined function!
# So we try to write this in such a way that the gammas are
# eminently on the right side of the strip.
from sympy import expand_mul, pi, ceiling, gamma
m, n = m_n
m = expand_mul(m/pi)
n = expand_mul(n/pi)
r = ceiling(-m*a - n.as_real_imag()[0]) # Don't use re(n), does not expand
return gamma(m*s + n + r), gamma(1 - n - r - m*s), (-1)**r*pi
class MellinTransformStripError(ValueError):
"""
Exception raised by _rewrite_gamma. Mainly for internal use.
"""
pass
def _rewrite_gamma(f, s, a, b):
"""
Try to rewrite the product f(s) as a product of gamma functions,
so that the inverse Mellin transform of f can be expressed as a meijer
G function.
Explanation
===========
Return (an, ap), (bm, bq), arg, exp, fac such that
G((an, ap), (bm, bq), arg/z**exp)*fac is the inverse Mellin transform of f(s).
Raises IntegralTransformError or MellinTransformStripError on failure.
It is asserted that f has no poles in the fundamental strip designated by
(a, b). One of a and b is allowed to be None. The fundamental strip is
important, because it determines the inversion contour.
This function can handle exponentials, linear factors, trigonometric
functions.
This is a helper function for inverse_mellin_transform that will not
attempt any transformations on f.
Examples
========
>>> from sympy.integrals.transforms import _rewrite_gamma
>>> from sympy.abc import s
>>> from sympy import oo
>>> _rewrite_gamma(s*(s+3)*(s-1), s, -oo, oo)
(([], [-3, 0, 1]), ([-2, 1, 2], []), 1, 1, -1)
>>> _rewrite_gamma((s-1)**2, s, -oo, oo)
(([], [1, 1]), ([2, 2], []), 1, 1, 1)
Importance of the fundamental strip:
>>> _rewrite_gamma(1/s, s, 0, oo)
(([1], []), ([], [0]), 1, 1, 1)
>>> _rewrite_gamma(1/s, s, None, oo)
(([1], []), ([], [0]), 1, 1, 1)
>>> _rewrite_gamma(1/s, s, 0, None)
(([1], []), ([], [0]), 1, 1, 1)
>>> _rewrite_gamma(1/s, s, -oo, 0)
(([], [1]), ([0], []), 1, 1, -1)
>>> _rewrite_gamma(1/s, s, None, 0)
(([], [1]), ([0], []), 1, 1, -1)
>>> _rewrite_gamma(1/s, s, -oo, None)
(([], [1]), ([0], []), 1, 1, -1)
>>> _rewrite_gamma(2**(-s+3), s, -oo, oo)
(([], []), ([], []), 1/2, 1, 8)
"""
from itertools import repeat
from sympy import (Poly, gamma, Mul, re, CRootOf, exp as exp_, expand,
roots, ilcm, pi, sin, cos, tan, cot, igcd, exp_polar)
# Our strategy will be as follows:
# 1) Guess a constant c such that the inversion integral should be
# performed wrt s'=c*s (instead of plain s). Write s for s'.
# 2) Process all factors, rewrite them independently as gamma functions in
# argument s, or exponentials of s.
# 3) Try to transform all gamma functions s.t. they have argument
# a+s or a-s.
# 4) Check that the resulting G function parameters are valid.
# 5) Combine all the exponentials.
a_, b_ = S([a, b])
def left(c, is_numer):
"""
Decide whether pole at c lies to the left of the fundamental strip.
"""
# heuristically, this is the best chance for us to solve the inequalities
c = expand(re(c))
if a_ is None and b_ is oo:
return True
if a_ is None:
return c < b_
if b_ is None:
return c <= a_
if (c >= b_) == True:
return False
if (c <= a_) == True:
return True
if is_numer:
return None
if a_.free_symbols or b_.free_symbols or c.free_symbols:
return None # XXX
#raise IntegralTransformError('Inverse Mellin', f,
# 'Could not determine position of singularity %s'
# ' relative to fundamental strip' % c)
raise MellinTransformStripError('Pole inside critical strip?')
# 1)
s_multipliers = []
for g in f.atoms(gamma):
if not g.has(s):
continue
arg = g.args[0]
if arg.is_Add:
arg = arg.as_independent(s)[1]
coeff, _ = arg.as_coeff_mul(s)
s_multipliers += [coeff]
for g in f.atoms(sin, cos, tan, cot):
if not g.has(s):
continue
arg = g.args[0]
if arg.is_Add:
arg = arg.as_independent(s)[1]
coeff, _ = arg.as_coeff_mul(s)
s_multipliers += [coeff/pi]
s_multipliers = [abs(x) if x.is_extended_real else x for x in s_multipliers]
common_coefficient = S.One
for x in s_multipliers:
if not x.is_Rational:
common_coefficient = x
break
s_multipliers = [x/common_coefficient for x in s_multipliers]
if (any(not x.is_Rational for x in s_multipliers) or
not common_coefficient.is_extended_real):
raise IntegralTransformError("Gamma", None, "Nonrational multiplier")
s_multiplier = common_coefficient/reduce(ilcm, [S(x.q)
for x in s_multipliers], S.One)
if s_multiplier == common_coefficient:
if len(s_multipliers) == 0:
s_multiplier = common_coefficient
else:
s_multiplier = common_coefficient \
*reduce(igcd, [S(x.p) for x in s_multipliers])
f = f.subs(s, s/s_multiplier)
fac = S.One/s_multiplier
exponent = S.One/s_multiplier
if a_ is not None:
a_ *= s_multiplier
if b_ is not None:
b_ *= s_multiplier
# 2)
numer, denom = f.as_numer_denom()
numer = Mul.make_args(numer)
denom = Mul.make_args(denom)
args = list(zip(numer, repeat(True))) + list(zip(denom, repeat(False)))
facs = []
dfacs = []
# *_gammas will contain pairs (a, c) representing Gamma(a*s + c)
numer_gammas = []
denom_gammas = []
# exponentials will contain bases for exponentials of s
exponentials = []
def exception(fact):
return IntegralTransformError("Inverse Mellin", f, "Unrecognised form '%s'." % fact)
while args:
fact, is_numer = args.pop()
if is_numer:
ugammas, lgammas = numer_gammas, denom_gammas
ufacs = facs
else:
ugammas, lgammas = denom_gammas, numer_gammas
ufacs = dfacs
def linear_arg(arg):
""" Test if arg is of form a*s+b, raise exception if not. """
if not arg.is_polynomial(s):
raise exception(fact)
p = Poly(arg, s)
if p.degree() != 1:
raise exception(fact)
return p.all_coeffs()
# constants
if not fact.has(s):
ufacs += [fact]
# exponentials
elif fact.is_Pow or isinstance(fact, exp_):
if fact.is_Pow:
base = fact.base
exp = fact.exp
else:
base = exp_polar(1)
exp = fact.exp
if exp.is_Integer:
cond = is_numer
if exp < 0:
cond = not cond
args += [(base, cond)]*abs(exp)
continue
elif not base.has(s):
a, b = linear_arg(exp)
if not is_numer:
base = 1/base
exponentials += [base**a]
facs += [base**b]
else:
raise exception(fact)
# linear factors
elif fact.is_polynomial(s):
p = Poly(fact, s)
if p.degree() != 1:
# We completely factor the poly. For this we need the roots.
# Now roots() only works in some cases (low degree), and CRootOf
# only works without parameters. So try both...
coeff = p.LT()[1]
rs = roots(p, s)
if len(rs) != p.degree():
rs = CRootOf.all_roots(p)
ufacs += [coeff]
args += [(s - c, is_numer) for c in rs]
continue
a, c = p.all_coeffs()
ufacs += [a]
c /= -a
# Now need to convert s - c
if left(c, is_numer):
ugammas += [(S.One, -c + 1)]
lgammas += [(S.One, -c)]
else:
ufacs += [-1]
ugammas += [(S.NegativeOne, c + 1)]
lgammas += [(S.NegativeOne, c)]
elif isinstance(fact, gamma):
a, b = linear_arg(fact.args[0])
if is_numer:
if (a > 0 and (left(-b/a, is_numer) == False)) or \
(a < 0 and (left(-b/a, is_numer) == True)):
raise NotImplementedError(
'Gammas partially over the strip.')
ugammas += [(a, b)]
elif isinstance(fact, sin):
# We try to re-write all trigs as gammas. This is not in
# general the best strategy, since sometimes this is impossible,
# but rewriting as exponentials would work. However trig functions
# in inverse mellin transforms usually all come from simplifying
# gamma terms, so this should work.
a = fact.args[0]
if is_numer:
# No problem with the poles.
gamma1, gamma2, fac_ = gamma(a/pi), gamma(1 - a/pi), pi
else:
gamma1, gamma2, fac_ = _rewrite_sin(linear_arg(a), s, a_, b_)
args += [(gamma1, not is_numer), (gamma2, not is_numer)]
ufacs += [fac_]
elif isinstance(fact, tan):
a = fact.args[0]
args += [(sin(a, evaluate=False), is_numer),
(sin(pi/2 - a, evaluate=False), not is_numer)]
elif isinstance(fact, cos):
a = fact.args[0]
args += [(sin(pi/2 - a, evaluate=False), is_numer)]
elif isinstance(fact, cot):
a = fact.args[0]
args += [(sin(pi/2 - a, evaluate=False), is_numer),
(sin(a, evaluate=False), not is_numer)]
else:
raise exception(fact)
fac *= Mul(*facs)/Mul(*dfacs)
# 3)
an, ap, bm, bq = [], [], [], []
for gammas, plus, minus, is_numer in [(numer_gammas, an, bm, True),
(denom_gammas, bq, ap, False)]:
while gammas:
a, c = gammas.pop()
if a != -1 and a != +1:
# We use the gamma function multiplication theorem.
p = abs(S(a))
newa = a/p
newc = c/p
if not a.is_Integer:
raise TypeError("a is not an integer")
for k in range(p):
gammas += [(newa, newc + k/p)]
if is_numer:
fac *= (2*pi)**((1 - p)/2) * p**(c - S.Half)
exponentials += [p**a]
else:
fac /= (2*pi)**((1 - p)/2) * p**(c - S.Half)
exponentials += [p**(-a)]
continue
if a == +1:
plus.append(1 - c)
else:
minus.append(c)
# 4)
# TODO
# 5)
arg = Mul(*exponentials)
# for testability, sort the arguments
an.sort(key=default_sort_key)
ap.sort(key=default_sort_key)
bm.sort(key=default_sort_key)
bq.sort(key=default_sort_key)
return (an, ap), (bm, bq), arg, exponent, fac
@_noconds_(True)
def _inverse_mellin_transform(F, s, x_, strip, as_meijerg=False):
""" A helper for the real inverse_mellin_transform function, this one here
assumes x to be real and positive. """
from sympy import (expand, expand_mul, hyperexpand, meijerg,
arg, pi, re, factor, Heaviside, gamma, Add)
x = _dummy('t', 'inverse-mellin-transform', F, positive=True)
# Actually, we won't try integration at all. Instead we use the definition
# of the Meijer G function as a fairly general inverse mellin transform.
F = F.rewrite(gamma)
for g in [factor(F), expand_mul(F), expand(F)]:
if g.is_Add:
# do all terms separately
ress = [_inverse_mellin_transform(G, s, x, strip, as_meijerg,
noconds=False)
for G in g.args]
conds = [p[1] for p in ress]
ress = [p[0] for p in ress]
res = Add(*ress)
if not as_meijerg:
res = factor(res, gens=res.atoms(Heaviside))
return res.subs(x, x_), And(*conds)
try:
a, b, C, e, fac = _rewrite_gamma(g, s, strip[0], strip[1])
except IntegralTransformError:
continue
try:
G = meijerg(a, b, C/x**e)
except ValueError:
continue
if as_meijerg:
h = G
else:
try:
h = hyperexpand(G)
except NotImplementedError:
raise IntegralTransformError(
'Inverse Mellin', F, 'Could not calculate integral')
if h.is_Piecewise and len(h.args) == 3:
# XXX we break modularity here!
h = Heaviside(x - abs(C))*h.args[0].args[0] \
+ Heaviside(abs(C) - x)*h.args[1].args[0]
# We must ensure that the integral along the line we want converges,
# and return that value.
# See [L], 5.2
cond = [abs(arg(G.argument)) < G.delta*pi]
# Note: we allow ">=" here, this corresponds to convergence if we let
# limits go to oo symmetrically. ">" corresponds to absolute convergence.
cond += [And(Or(len(G.ap) != len(G.bq), 0 >= re(G.nu) + 1),
abs(arg(G.argument)) == G.delta*pi)]
cond = Or(*cond)
if cond == False:
raise IntegralTransformError(
'Inverse Mellin', F, 'does not converge')
return (h*fac).subs(x, x_), cond
raise IntegralTransformError('Inverse Mellin', F, '')
_allowed = None
class InverseMellinTransform(IntegralTransform):
"""
Class representing unevaluated inverse Mellin transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse Mellin transforms, see the
:func:`inverse_mellin_transform` docstring.
"""
_name = 'Inverse Mellin'
_none_sentinel = Dummy('None')
_c = Dummy('c')
def __new__(cls, F, s, x, a, b, **opts):
if a is None:
a = InverseMellinTransform._none_sentinel
if b is None:
b = InverseMellinTransform._none_sentinel
return IntegralTransform.__new__(cls, F, s, x, a, b, **opts)
@property
def fundamental_strip(self):
a, b = self.args[3], self.args[4]
if a is InverseMellinTransform._none_sentinel:
a = None
if b is InverseMellinTransform._none_sentinel:
b = None
return a, b
def _compute_transform(self, F, s, x, **hints):
from sympy import postorder_traversal
global _allowed
if _allowed is None:
from sympy import (
exp, gamma, sin, cos, tan, cot, cosh, sinh, tanh,
coth, factorial, rf)
_allowed = {
exp, gamma, sin, cos, tan, cot, cosh, sinh, tanh, coth,
factorial, rf}
for f in postorder_traversal(F):
if f.is_Function and f.has(s) and f.func not in _allowed:
raise IntegralTransformError('Inverse Mellin', F,
'Component %s not recognised.' % f)
strip = self.fundamental_strip
return _inverse_mellin_transform(F, s, x, strip, **hints)
def _as_integral(self, F, s, x):
from sympy import I
c = self.__class__._c
return Integral(F*x**(-s), (s, c - I*oo, c + I*oo))/(2*S.Pi*S.ImaginaryUnit)
def inverse_mellin_transform(F, s, x, strip, **hints):
r"""
Compute the inverse Mellin transform of `F(s)` over the fundamental
strip given by ``strip=(a, b)``.
Explanation
===========
This can be defined as
.. math:: f(x) = \frac{1}{2\pi i} \int_{c - i\infty}^{c + i\infty} x^{-s} F(s) \mathrm{d}s,
for any `c` in the fundamental strip. Under certain regularity
conditions on `F` and/or `f`,
this recovers `f` from its Mellin transform `F`
(and vice versa), for positive real `x`.
One of `a` or `b` may be passed as ``None``; a suitable `c` will be
inferred.
If the integral cannot be computed in closed form, this function returns
an unevaluated :class:`InverseMellinTransform` object.
Note that this function will assume x to be positive and real, regardless
of the sympy assumptions!
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Examples
========
>>> from sympy.integrals.transforms import inverse_mellin_transform
>>> from sympy import oo, gamma
>>> from sympy.abc import x, s
>>> inverse_mellin_transform(gamma(s), s, x, (0, oo))
exp(-x)
The fundamental strip matters:
>>> f = 1/(s**2 - 1)
>>> inverse_mellin_transform(f, s, x, (-oo, -1))
x*(1 - 1/x**2)*Heaviside(x - 1, 1/2)/2
>>> inverse_mellin_transform(f, s, x, (-1, 1))
-x*Heaviside(1 - x, 1/2)/2 - Heaviside(x - 1, 1/2)/(2*x)
>>> inverse_mellin_transform(f, s, x, (1, oo))
(1/2 - x**2/2)*Heaviside(1 - x, 1/2)/x
See Also
========
mellin_transform
hankel_transform, inverse_hankel_transform
"""
return InverseMellinTransform(F, s, x, strip[0], strip[1]).doit(**hints)
##########################################################################
# Laplace Transform
##########################################################################
def _simplifyconds(expr, s, a):
r"""
Naively simplify some conditions occurring in ``expr``, given that `\operatorname{Re}(s) > a`.
Examples
========
>>> from sympy.integrals.transforms import _simplifyconds as simp
>>> from sympy.abc import x
>>> from sympy import sympify as S
>>> simp(abs(x**2) < 1, x, 1)
False
>>> simp(abs(x**2) < 1, x, 2)
False
>>> simp(abs(x**2) < 1, x, 0)
Abs(x**2) < 1
>>> simp(abs(1/x**2) < 1, x, 1)
True
>>> simp(S(1) < abs(x), x, 1)
True
>>> simp(S(1) < abs(1/x), x, 1)
False
>>> from sympy import Ne
>>> simp(Ne(1, x**3), x, 1)
True
>>> simp(Ne(1, x**3), x, 2)
True
>>> simp(Ne(1, x**3), x, 0)
Ne(1, x**3)
"""
from sympy.core.relational import ( StrictGreaterThan, StrictLessThan,
Unequality )
from sympy import Abs
def power(ex):
if ex == s:
return 1
if ex.is_Pow and ex.base == s:
return ex.exp
return None
def bigger(ex1, ex2):
""" Return True only if |ex1| > |ex2|, False only if |ex1| < |ex2|.
Else return None. """
if ex1.has(s) and ex2.has(s):
return None
if isinstance(ex1, Abs):
ex1 = ex1.args[0]
if isinstance(ex2, Abs):
ex2 = ex2.args[0]
if ex1.has(s):
return bigger(1/ex2, 1/ex1)
n = power(ex2)
if n is None:
return None
try:
if n > 0 and (abs(ex1) <= abs(a)**n) == True:
return False
if n < 0 and (abs(ex1) >= abs(a)**n) == True:
return True
except TypeError:
pass
def replie(x, y):
""" simplify x < y """
if not (x.is_positive or isinstance(x, Abs)) \
or not (y.is_positive or isinstance(y, Abs)):
return (x < y)
r = bigger(x, y)
if r is not None:
return not r
return (x < y)
def replue(x, y):
b = bigger(x, y)
if b == True or b == False:
return True
return Unequality(x, y)
def repl(ex, *args):
if ex == True or ex == False:
return bool(ex)
return ex.replace(*args)
from sympy.simplify.radsimp import collect_abs
expr = collect_abs(expr)
expr = repl(expr, StrictLessThan, replie)
expr = repl(expr, StrictGreaterThan, lambda x, y: replie(y, x))
expr = repl(expr, Unequality, replue)
return S(expr)
def expand_dirac_delta(expr):
"""
Expand an expression involving DiractDelta to get it as a linear
combination of DiracDelta functions.
"""
return _lin_eq2dict(expr, expr.atoms(DiracDelta))
@_noconds
def _laplace_transform(f, t, s_, simplify=True):
""" The backend function for Laplace transforms. """
from sympy import (re, Max, exp, pi, Min, periodic_argument as arg_,
arg, cos, Wild, symbols, polar_lift, Add)
s = Dummy('s')
a = Wild('a', exclude=[t])
deltazero = []
deltanonzero = []
try:
integratable, deltadict = expand_dirac_delta(f)
except PolyNonlinearError:
raise IntegralTransformError(
'Laplace', f, 'could not expand DiracDelta expressions')
for dirac_func, dirac_coeff in deltadict.items():
p = dirac_func.match(DiracDelta(a*t))
if p:
deltazero.append(dirac_coeff.subs(t,0)/p[a])
else:
if dirac_func.args[0].subs(t,0).is_zero:
raise IntegralTransformError('Laplace', f,\
'not implemented yet.')
else:
deltanonzero.append(dirac_func*dirac_coeff)
F = Add(integrate(exp(-s*t) * Add(integratable, *deltanonzero), (t, 0, oo)),
Add(*deltazero))
if not F.has(Integral):
return _simplify(F.subs(s, s_), simplify), -oo, S.true
if not F.is_Piecewise:
raise IntegralTransformError(
'Laplace', f, 'could not compute integral')
F, cond = F.args[0]
if F.has(Integral):
raise IntegralTransformError(
'Laplace', f, 'integral in unexpected form')
def process_conds(conds):
""" Turn ``conds`` into a strip and auxiliary conditions. """
a = -oo
aux = S.true
conds = conjuncts(to_cnf(conds))
p, q, w1, w2, w3, w4, w5 = symbols(
'p q w1 w2 w3 w4 w5', cls=Wild, exclude=[s])
patterns = (
p*abs(arg((s + w3)*q)) < w2,
p*abs(arg((s + w3)*q)) <= w2,
abs(arg_((s + w3)**p*q, w1)) < w2,
abs(arg_((s + w3)**p*q, w1)) <= w2,
abs(arg_((polar_lift(s + w3))**p*q, w1)) < w2,
abs(arg_((polar_lift(s + w3))**p*q, w1)) <= w2)
for c in conds:
a_ = oo
aux_ = []
for d in disjuncts(c):
if d.is_Relational and s in d.rhs.free_symbols:
d = d.reversed
if d.is_Relational and isinstance(d, (Ge, Gt)):
d = d.reversedsign
for pat in patterns:
m = d.match(pat)
if m:
break
if m:
if m[q].is_positive and m[w2]/m[p] == pi/2:
d = -re(s + m[w3]) < 0
m = d.match(p - cos(w1*abs(arg(s*w5))*w2)*abs(s**w3)**w4 < 0)
if not m:
m = d.match(
cos(p - abs(arg_(s**w1*w5, q))*w2)*abs(s**w3)**w4 < 0)
if not m:
m = d.match(
p - cos(abs(arg_(polar_lift(s)**w1*w5, q))*w2
)*abs(s**w3)**w4 < 0)
if m and all(m[wild].is_positive for wild in [w1, w2, w3, w4, w5]):
d = re(s) > m[p]
d_ = d.replace(
re, lambda x: x.expand().as_real_imag()[0]).subs(re(s), t)
if not d.is_Relational or \
d.rel_op in ('==', '!=') \
or d_.has(s) or not d_.has(t):
aux_ += [d]
continue
soln = _solve_inequality(d_, t)
if not soln.is_Relational or \
soln.rel_op in ('==', '!='):
aux_ += [d]
continue
if soln.lts == t:
raise IntegralTransformError('Laplace', f,
'convergence not in half-plane?')
else:
a_ = Min(soln.lts, a_)
if a_ != oo:
a = Max(a_, a)
else:
aux = And(aux, Or(*aux_))
return a, aux.canonical if aux.is_Relational else aux
conds = [process_conds(c) for c in disjuncts(cond)]
conds2 = [x for x in conds if x[1] != False and x[0] != -oo]
if not conds2:
conds2 = [x for x in conds if x[1] != False]
conds = list(ordered(conds2))
def cnt(expr):
if expr == True or expr == False:
return 0
return expr.count_ops()
conds.sort(key=lambda x: (-x[0], cnt(x[1])))
if not conds:
raise IntegralTransformError('Laplace', f, 'no convergence found')
a, aux = conds[0] # XXX is [0] always the right one?
def sbs(expr):
return expr.subs(s, s_)
if simplify:
F = _simplifyconds(F, s, a)
aux = _simplifyconds(aux, s, a)
return _simplify(F.subs(s, s_), simplify), sbs(a), _canonical(sbs(aux))
class LaplaceTransform(IntegralTransform):
"""
Class representing unevaluated Laplace transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute Laplace transforms, see the :func:`laplace_transform`
docstring.
"""
_name = 'Laplace'
def _compute_transform(self, f, t, s, **hints):
return _laplace_transform(f, t, s, **hints)
def _as_integral(self, f, t, s):
from sympy import exp
return Integral(f*exp(-s*t), (t, 0, oo))
def _collapse_extra(self, extra):
from sympy import Max
conds = []
planes = []
for plane, cond in extra:
conds.append(cond)
planes.append(plane)
cond = And(*conds)
plane = Max(*planes)
if cond == False:
raise IntegralTransformError(
'Laplace', None, 'No combined convergence.')
return plane, cond
def laplace_transform(f, t, s, legacy_matrix=True, **hints):
r"""
Compute the Laplace Transform `F(s)` of `f(t)`,
.. math :: F(s) = \int_{0^{-}}^\infty e^{-st} f(t) \mathrm{d}t.
Explanation
===========
For all sensible functions, this converges absolutely in a
half plane `a < \operatorname{Re}(s)`.
This function returns ``(F, a, cond)`` where ``F`` is the Laplace
transform of ``f``, `\operatorname{Re}(s) > a` is the half-plane
of convergence, and ``cond`` are auxiliary convergence conditions.
The lower bound is `0^{-}`, meaning that this bound should be approached
from the lower side. This is only necessary if distributions are involved.
At present, it is only done if `f(t)` contains ``DiracDelta``, in which
case the Laplace transform is computed as
.. math :: F(s) = \lim_{\tau\to 0^{-}} \int_{\tau}^\infty e^{-st} f(t) \mathrm{d}t.
If the integral cannot be computed in closed form, this function returns
an unevaluated :class:`LaplaceTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`. If ``noconds=True``,
only `F` will be returned (i.e. not ``cond``, and also not the plane ``a``).
.. deprecated:: 1.9
Legacy behavior for matrices where ``laplace_transform`` with
``noconds=False`` (the default) returns a Matrix whose elements are
tuples. The behavior of ``laplace_transform`` for matrices will change
in a future release of SymPy to return a tuple of the transformed
Matrix and the convergence conditions for the matrix as a whole. Use
``legacy_matrix=False`` to enable the new behavior.
Examples
========
>>> from sympy.integrals import laplace_transform
>>> from sympy.abc import t, s, a
>>> from sympy.functions import DiracDelta, exp
>>> laplace_transform(t**a, t, s)
(gamma(a + 1)/(s*s**a), 0, re(a) > -1)
>>> laplace_transform(DiracDelta(t)-a*exp(-a*t),t,s)
(-a/(a + s) + 1, 0, Abs(arg(a)) <= pi/2)
See Also
========
inverse_laplace_transform, mellin_transform, fourier_transform
hankel_transform, inverse_hankel_transform
"""
if isinstance(f, MatrixBase) and hasattr(f, 'applyfunc'):
conds = not hints.get('noconds', False)
if conds and legacy_matrix:
SymPyDeprecationWarning(
feature="laplace_transform of a Matrix with noconds=False (default)",
useinstead="the option legacy_matrix=False to get the new behaviour",
issue=21504,
deprecated_since_version="1.9"
).warn()
return f.applyfunc(lambda fij: laplace_transform(fij, t, s, **hints))
else:
elements_trans = [laplace_transform(fij, t, s, **hints) for fij in f]
if conds:
elements, avals, conditions = zip(*elements_trans)
f_laplace = type(f)(*f.shape, elements)
return f_laplace, Max(*avals), And(*conditions)
else:
return type(f)(*f.shape, elements_trans)
return LaplaceTransform(f, t, s).doit(**hints)
@_noconds_(True)
def _inverse_laplace_transform(F, s, t_, plane, simplify=True):
""" The backend function for inverse Laplace transforms. """
from sympy import exp, Heaviside, log, expand_complex, Integral,\
Piecewise, Add
from sympy.integrals.meijerint import meijerint_inversion, _get_coeff_exp
# There are two strategies we can try:
# 1) Use inverse mellin transforms - related by a simple change of variables.
# 2) Use the inversion integral.
t = Dummy('t', real=True)
def pw_simp(*args):
""" Simplify a piecewise expression from hyperexpand. """
# XXX we break modularity here!
if len(args) != 3:
return Piecewise(*args)
arg = args[2].args[0].argument
coeff, exponent = _get_coeff_exp(arg, t)
e1 = args[0].args[0]
e2 = args[1].args[0]
return Heaviside(1/abs(coeff) - t**exponent)*e1 \
+ Heaviside(t**exponent - 1/abs(coeff))*e2
if F.is_rational_function(s):
F = F.apart(s)
if F.is_Add:
f = Add(*[_inverse_laplace_transform(X, s, t, plane, simplify)\
for X in F.args])
return _simplify(f.subs(t, t_), simplify), True
try:
f, cond = inverse_mellin_transform(F, s, exp(-t), (None, oo),
needeval=True, noconds=False)
except IntegralTransformError:
f = None
if f is None:
f = meijerint_inversion(F, s, t)
if f is None:
raise IntegralTransformError('Inverse Laplace', f, '')
if f.is_Piecewise:
f, cond = f.args[0]
if f.has(Integral):
raise IntegralTransformError('Inverse Laplace', f,
'inversion integral of unrecognised form.')
else:
cond = S.true
f = f.replace(Piecewise, pw_simp)
if f.is_Piecewise:
# many of the functions called below can't work with piecewise
# (b/c it has a bool in args)
return f.subs(t, t_), cond
u = Dummy('u')
def simp_heaviside(arg, H0=S.Half):
a = arg.subs(exp(-t), u)
if a.has(t):
return Heaviside(arg, H0)
rel = _solve_inequality(a > 0, u)
if rel.lts == u:
k = log(rel.gts)
return Heaviside(t + k, H0)
else:
k = log(rel.lts)
return Heaviside(-(t + k), H0)
f = f.replace(Heaviside, simp_heaviside)
def simp_exp(arg):
return expand_complex(exp(arg))
f = f.replace(exp, simp_exp)
# TODO it would be nice to fix cosh and sinh ... simplify messes these
# exponentials up
return _simplify(f.subs(t, t_), simplify), cond
class InverseLaplaceTransform(IntegralTransform):
"""
Class representing unevaluated inverse Laplace transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse Laplace transforms, see the
:func:`inverse_laplace_transform` docstring.
"""
_name = 'Inverse Laplace'
_none_sentinel = Dummy('None')
_c = Dummy('c')
def __new__(cls, F, s, x, plane, **opts):
if plane is None:
plane = InverseLaplaceTransform._none_sentinel
return IntegralTransform.__new__(cls, F, s, x, plane, **opts)
@property
def fundamental_plane(self):
plane = self.args[3]
if plane is InverseLaplaceTransform._none_sentinel:
plane = None
return plane
def _compute_transform(self, F, s, t, **hints):
return _inverse_laplace_transform(F, s, t, self.fundamental_plane, **hints)
def _as_integral(self, F, s, t):
from sympy import I, exp
c = self.__class__._c
return Integral(exp(s*t)*F, (s, c - I*oo, c + I*oo))/(2*S.Pi*S.ImaginaryUnit)
def inverse_laplace_transform(F, s, t, plane=None, **hints):
r"""
Compute the inverse Laplace transform of `F(s)`, defined as
.. math :: f(t) = \frac{1}{2\pi i} \int_{c-i\infty}^{c+i\infty} e^{st} F(s) \mathrm{d}s,
for `c` so large that `F(s)` has no singularites in the
half-plane `\operatorname{Re}(s) > c-\epsilon`.
Explanation
===========
The plane can be specified by
argument ``plane``, but will be inferred if passed as None.
Under certain regularity conditions, this recovers `f(t)` from its
Laplace Transform `F(s)`, for non-negative `t`, and vice
versa.
If the integral cannot be computed in closed form, this function returns
an unevaluated :class:`InverseLaplaceTransform` object.
Note that this function will always assume `t` to be real,
regardless of the sympy assumption on `t`.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Examples
========
>>> from sympy.integrals.transforms import inverse_laplace_transform
>>> from sympy import exp, Symbol
>>> from sympy.abc import s, t
>>> a = Symbol('a', positive=True)
>>> inverse_laplace_transform(exp(-a*s)/s, s, t)
Heaviside(-a + t, 1/2)
See Also
========
laplace_transform
hankel_transform, inverse_hankel_transform
"""
if isinstance(F, MatrixBase) and hasattr(F, 'applyfunc'):
return F.applyfunc(lambda Fij: inverse_laplace_transform(Fij, s, t, plane, **hints))
return InverseLaplaceTransform(F, s, t, plane).doit(**hints)
##########################################################################
# Fourier Transform
##########################################################################
@_noconds_(True)
def _fourier_transform(f, x, k, a, b, name, simplify=True):
r"""
Compute a general Fourier-type transform
.. math::
F(k) = a \int_{-\infty}^{\infty} e^{bixk} f(x)\, dx.
For suitable choice of *a* and *b*, this reduces to the standard Fourier
and inverse Fourier transforms.
"""
from sympy import exp, I
F = integrate(a*f*exp(b*I*x*k), (x, -oo, oo))
if not F.has(Integral):
return _simplify(F, simplify), S.true
integral_f = integrate(f, (x, -oo, oo))
if integral_f in (-oo, oo, S.NaN) or integral_f.has(Integral):
raise IntegralTransformError(name, f, 'function not integrable on real axis')
if not F.is_Piecewise:
raise IntegralTransformError(name, f, 'could not compute integral')
F, cond = F.args[0]
if F.has(Integral):
raise IntegralTransformError(name, f, 'integral in unexpected form')
return _simplify(F, simplify), cond
class FourierTypeTransform(IntegralTransform):
""" Base class for Fourier transforms."""
def a(self):
raise NotImplementedError(
"Class %s must implement a(self) but does not" % self.__class__)
def b(self):
raise NotImplementedError(
"Class %s must implement b(self) but does not" % self.__class__)
def _compute_transform(self, f, x, k, **hints):
return _fourier_transform(f, x, k,
self.a(), self.b(),
self.__class__._name, **hints)
def _as_integral(self, f, x, k):
from sympy import exp, I
a = self.a()
b = self.b()
return Integral(a*f*exp(b*I*x*k), (x, -oo, oo))
class FourierTransform(FourierTypeTransform):
"""
Class representing unevaluated Fourier transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute Fourier transforms, see the :func:`fourier_transform`
docstring.
"""
_name = 'Fourier'
def a(self):
return 1
def b(self):
return -2*S.Pi
def fourier_transform(f, x, k, **hints):
r"""
Compute the unitary, ordinary-frequency Fourier transform of ``f``, defined
as
.. math:: F(k) = \int_{-\infty}^\infty f(x) e^{-2\pi i x k} \mathrm{d} x.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`FourierTransform` object.
For other Fourier transform conventions, see the function
:func:`sympy.integrals.transforms._fourier_transform`.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import fourier_transform, exp
>>> from sympy.abc import x, k
>>> fourier_transform(exp(-x**2), x, k)
sqrt(pi)*exp(-pi**2*k**2)
>>> fourier_transform(exp(-x**2), x, k, noconds=False)
(sqrt(pi)*exp(-pi**2*k**2), True)
See Also
========
inverse_fourier_transform
sine_transform, inverse_sine_transform
cosine_transform, inverse_cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return FourierTransform(f, x, k).doit(**hints)
class InverseFourierTransform(FourierTypeTransform):
"""
Class representing unevaluated inverse Fourier transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse Fourier transforms, see the
:func:`inverse_fourier_transform` docstring.
"""
_name = 'Inverse Fourier'
def a(self):
return 1
def b(self):
return 2*S.Pi
def inverse_fourier_transform(F, k, x, **hints):
r"""
Compute the unitary, ordinary-frequency inverse Fourier transform of `F`,
defined as
.. math:: f(x) = \int_{-\infty}^\infty F(k) e^{2\pi i x k} \mathrm{d} k.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`InverseFourierTransform` object.
For other Fourier transform conventions, see the function
:func:`sympy.integrals.transforms._fourier_transform`.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import inverse_fourier_transform, exp, sqrt, pi
>>> from sympy.abc import x, k
>>> inverse_fourier_transform(sqrt(pi)*exp(-(pi*k)**2), k, x)
exp(-x**2)
>>> inverse_fourier_transform(sqrt(pi)*exp(-(pi*k)**2), k, x, noconds=False)
(exp(-x**2), True)
See Also
========
fourier_transform
sine_transform, inverse_sine_transform
cosine_transform, inverse_cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return InverseFourierTransform(F, k, x).doit(**hints)
##########################################################################
# Fourier Sine and Cosine Transform
##########################################################################
from sympy import sin, cos, sqrt, pi
@_noconds_(True)
def _sine_cosine_transform(f, x, k, a, b, K, name, simplify=True):
"""
Compute a general sine or cosine-type transform
F(k) = a int_0^oo b*sin(x*k) f(x) dx.
F(k) = a int_0^oo b*cos(x*k) f(x) dx.
For suitable choice of a and b, this reduces to the standard sine/cosine
and inverse sine/cosine transforms.
"""
F = integrate(a*f*K(b*x*k), (x, 0, oo))
if not F.has(Integral):
return _simplify(F, simplify), S.true
if not F.is_Piecewise:
raise IntegralTransformError(name, f, 'could not compute integral')
F, cond = F.args[0]
if F.has(Integral):
raise IntegralTransformError(name, f, 'integral in unexpected form')
return _simplify(F, simplify), cond
class SineCosineTypeTransform(IntegralTransform):
"""
Base class for sine and cosine transforms.
Specify cls._kern.
"""
def a(self):
raise NotImplementedError(
"Class %s must implement a(self) but does not" % self.__class__)
def b(self):
raise NotImplementedError(
"Class %s must implement b(self) but does not" % self.__class__)
def _compute_transform(self, f, x, k, **hints):
return _sine_cosine_transform(f, x, k,
self.a(), self.b(),
self.__class__._kern,
self.__class__._name, **hints)
def _as_integral(self, f, x, k):
a = self.a()
b = self.b()
K = self.__class__._kern
return Integral(a*f*K(b*x*k), (x, 0, oo))
class SineTransform(SineCosineTypeTransform):
"""
Class representing unevaluated sine transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute sine transforms, see the :func:`sine_transform`
docstring.
"""
_name = 'Sine'
_kern = sin
def a(self):
return sqrt(2)/sqrt(pi)
def b(self):
return 1
def sine_transform(f, x, k, **hints):
r"""
Compute the unitary, ordinary-frequency sine transform of `f`, defined
as
.. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \sin(2\pi x k) \mathrm{d} x.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`SineTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import sine_transform, exp
>>> from sympy.abc import x, k, a
>>> sine_transform(x*exp(-a*x**2), x, k)
sqrt(2)*k*exp(-k**2/(4*a))/(4*a**(3/2))
>>> sine_transform(x**(-a), x, k)
2**(1/2 - a)*k**(a - 1)*gamma(1 - a/2)/gamma(a/2 + 1/2)
See Also
========
fourier_transform, inverse_fourier_transform
inverse_sine_transform
cosine_transform, inverse_cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return SineTransform(f, x, k).doit(**hints)
class InverseSineTransform(SineCosineTypeTransform):
"""
Class representing unevaluated inverse sine transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse sine transforms, see the
:func:`inverse_sine_transform` docstring.
"""
_name = 'Inverse Sine'
_kern = sin
def a(self):
return sqrt(2)/sqrt(pi)
def b(self):
return 1
def inverse_sine_transform(F, k, x, **hints):
r"""
Compute the unitary, ordinary-frequency inverse sine transform of `F`,
defined as
.. math:: f(x) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty F(k) \sin(2\pi x k) \mathrm{d} k.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`InverseSineTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import inverse_sine_transform, exp, sqrt, gamma
>>> from sympy.abc import x, k, a
>>> inverse_sine_transform(2**((1-2*a)/2)*k**(a - 1)*
... gamma(-a/2 + 1)/gamma((a+1)/2), k, x)
x**(-a)
>>> inverse_sine_transform(sqrt(2)*k*exp(-k**2/(4*a))/(4*sqrt(a)**3), k, x)
x*exp(-a*x**2)
See Also
========
fourier_transform, inverse_fourier_transform
sine_transform
cosine_transform, inverse_cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return InverseSineTransform(F, k, x).doit(**hints)
class CosineTransform(SineCosineTypeTransform):
"""
Class representing unevaluated cosine transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute cosine transforms, see the :func:`cosine_transform`
docstring.
"""
_name = 'Cosine'
_kern = cos
def a(self):
return sqrt(2)/sqrt(pi)
def b(self):
return 1
def cosine_transform(f, x, k, **hints):
r"""
Compute the unitary, ordinary-frequency cosine transform of `f`, defined
as
.. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \cos(2\pi x k) \mathrm{d} x.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`CosineTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import cosine_transform, exp, sqrt, cos
>>> from sympy.abc import x, k, a
>>> cosine_transform(exp(-a*x), x, k)
sqrt(2)*a/(sqrt(pi)*(a**2 + k**2))
>>> cosine_transform(exp(-a*sqrt(x))*cos(a*sqrt(x)), x, k)
a*exp(-a**2/(2*k))/(2*k**(3/2))
See Also
========
fourier_transform, inverse_fourier_transform,
sine_transform, inverse_sine_transform
inverse_cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return CosineTransform(f, x, k).doit(**hints)
class InverseCosineTransform(SineCosineTypeTransform):
"""
Class representing unevaluated inverse cosine transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse cosine transforms, see the
:func:`inverse_cosine_transform` docstring.
"""
_name = 'Inverse Cosine'
_kern = cos
def a(self):
return sqrt(2)/sqrt(pi)
def b(self):
return 1
def inverse_cosine_transform(F, k, x, **hints):
r"""
Compute the unitary, ordinary-frequency inverse cosine transform of `F`,
defined as
.. math:: f(x) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty F(k) \cos(2\pi x k) \mathrm{d} k.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`InverseCosineTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import inverse_cosine_transform, sqrt, pi
>>> from sympy.abc import x, k, a
>>> inverse_cosine_transform(sqrt(2)*a/(sqrt(pi)*(a**2 + k**2)), k, x)
exp(-a*x)
>>> inverse_cosine_transform(1/sqrt(k), k, x)
1/sqrt(x)
See Also
========
fourier_transform, inverse_fourier_transform,
sine_transform, inverse_sine_transform
cosine_transform
hankel_transform, inverse_hankel_transform
mellin_transform, laplace_transform
"""
return InverseCosineTransform(F, k, x).doit(**hints)
##########################################################################
# Hankel Transform
##########################################################################
@_noconds_(True)
def _hankel_transform(f, r, k, nu, name, simplify=True):
r"""
Compute a general Hankel transform
.. math:: F_\nu(k) = \int_{0}^\infty f(r) J_\nu(k r) r \mathrm{d} r.
"""
from sympy import besselj
F = integrate(f*besselj(nu, k*r)*r, (r, 0, oo))
if not F.has(Integral):
return _simplify(F, simplify), S.true
if not F.is_Piecewise:
raise IntegralTransformError(name, f, 'could not compute integral')
F, cond = F.args[0]
if F.has(Integral):
raise IntegralTransformError(name, f, 'integral in unexpected form')
return _simplify(F, simplify), cond
class HankelTypeTransform(IntegralTransform):
"""
Base class for Hankel transforms.
"""
def doit(self, **hints):
return self._compute_transform(self.function,
self.function_variable,
self.transform_variable,
self.args[3],
**hints)
def _compute_transform(self, f, r, k, nu, **hints):
return _hankel_transform(f, r, k, nu, self._name, **hints)
def _as_integral(self, f, r, k, nu):
from sympy import besselj
return Integral(f*besselj(nu, k*r)*r, (r, 0, oo))
@property
def as_integral(self):
return self._as_integral(self.function,
self.function_variable,
self.transform_variable,
self.args[3])
class HankelTransform(HankelTypeTransform):
"""
Class representing unevaluated Hankel transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute Hankel transforms, see the :func:`hankel_transform`
docstring.
"""
_name = 'Hankel'
def hankel_transform(f, r, k, nu, **hints):
r"""
Compute the Hankel transform of `f`, defined as
.. math:: F_\nu(k) = \int_{0}^\infty f(r) J_\nu(k r) r \mathrm{d} r.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`HankelTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import hankel_transform, inverse_hankel_transform
>>> from sympy import exp
>>> from sympy.abc import r, k, m, nu, a
>>> ht = hankel_transform(1/r**m, r, k, nu)
>>> ht
2*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/(2**m*gamma(m/2 + nu/2))
>>> inverse_hankel_transform(ht, k, r, nu)
r**(-m)
>>> ht = hankel_transform(exp(-a*r), r, k, 0)
>>> ht
a/(k**3*(a**2/k**2 + 1)**(3/2))
>>> inverse_hankel_transform(ht, k, r, 0)
exp(-a*r)
See Also
========
fourier_transform, inverse_fourier_transform
sine_transform, inverse_sine_transform
cosine_transform, inverse_cosine_transform
inverse_hankel_transform
mellin_transform, laplace_transform
"""
return HankelTransform(f, r, k, nu).doit(**hints)
class InverseHankelTransform(HankelTypeTransform):
"""
Class representing unevaluated inverse Hankel transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse Hankel transforms, see the
:func:`inverse_hankel_transform` docstring.
"""
_name = 'Inverse Hankel'
def inverse_hankel_transform(F, k, r, nu, **hints):
r"""
Compute the inverse Hankel transform of `F` defined as
.. math:: f(r) = \int_{0}^\infty F_\nu(k) J_\nu(k r) k \mathrm{d} k.
Explanation
===========
If the transform cannot be computed in closed form, this
function returns an unevaluated :class:`InverseHankelTransform` object.
For a description of possible hints, refer to the docstring of
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
Note that for this transform, by default ``noconds=True``.
Examples
========
>>> from sympy import hankel_transform, inverse_hankel_transform
>>> from sympy import exp
>>> from sympy.abc import r, k, m, nu, a
>>> ht = hankel_transform(1/r**m, r, k, nu)
>>> ht
2*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/(2**m*gamma(m/2 + nu/2))
>>> inverse_hankel_transform(ht, k, r, nu)
r**(-m)
>>> ht = hankel_transform(exp(-a*r), r, k, 0)
>>> ht
a/(k**3*(a**2/k**2 + 1)**(3/2))
>>> inverse_hankel_transform(ht, k, r, 0)
exp(-a*r)
See Also
========
fourier_transform, inverse_fourier_transform
sine_transform, inverse_sine_transform
cosine_transform, inverse_cosine_transform
hankel_transform
mellin_transform, laplace_transform
"""
return InverseHankelTransform(F, k, r, nu).doit(**hints)
|
7f6df8b4df86c59761e5056ec8c19f01bd5283067f706ee41fb2a1f35ead6c0c | from typing import Dict, List
from itertools import permutations
from functools import reduce
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.mul import Mul
from sympy.core.symbol import Wild, Dummy
from sympy.core.basic import sympify
from sympy.core.numbers import Rational, pi, I
from sympy.core.relational import Eq, Ne
from sympy.core.singleton import S
from sympy.functions import exp, sin, cos, tan, cot, asin, atan
from sympy.functions import log, sinh, cosh, tanh, coth, asinh, acosh
from sympy.functions import sqrt, erf, erfi, li, Ei
from sympy.functions import besselj, bessely, besseli, besselk
from sympy.functions import hankel1, hankel2, jn, yn
from sympy.functions.elementary.complexes import Abs, re, im, sign, arg
from sympy.functions.elementary.exponential import LambertW
from sympy.functions.elementary.integers import floor, ceiling
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.special.delta_functions import Heaviside, DiracDelta
from sympy.simplify.radsimp import collect
from sympy.logic.boolalg import And, Or
from sympy.utilities.iterables import uniq
from sympy.polys import quo, gcd, lcm, factor, cancel, PolynomialError
from sympy.polys.monomials import itermonomials
from sympy.polys.polyroots import root_factors
from sympy.polys.rings import PolyRing
from sympy.polys.solvers import solve_lin_sys
from sympy.polys.constructor import construct_domain
from sympy.core.compatibility import ordered
from sympy.integrals.integrals import integrate
def components(f, x):
"""
Returns a set of all functional components of the given expression
which includes symbols, function applications and compositions and
non-integer powers. Fractional powers are collected with
minimal, positive exponents.
Examples
========
>>> from sympy import cos, sin
>>> from sympy.abc import x
>>> from sympy.integrals.heurisch import components
>>> components(sin(x)*cos(x)**2, x)
{x, sin(x), cos(x)}
See Also
========
heurisch
"""
result = set()
if x in f.free_symbols:
if f.is_symbol and f.is_commutative:
result.add(f)
elif f.is_Function or f.is_Derivative:
for g in f.args:
result |= components(g, x)
result.add(f)
elif f.is_Pow:
result |= components(f.base, x)
if not f.exp.is_Integer:
if f.exp.is_Rational:
result.add(f.base**Rational(1, f.exp.q))
else:
result |= components(f.exp, x) | {f}
else:
for g in f.args:
result |= components(g, x)
return result
# name -> [] of symbols
_symbols_cache = {} # type: Dict[str, List[Dummy]]
# NB @cacheit is not convenient here
def _symbols(name, n):
"""get vector of symbols local to this module"""
try:
lsyms = _symbols_cache[name]
except KeyError:
lsyms = []
_symbols_cache[name] = lsyms
while len(lsyms) < n:
lsyms.append( Dummy('%s%i' % (name, len(lsyms))) )
return lsyms[:n]
def heurisch_wrapper(f, x, rewrite=False, hints=None, mappings=None, retries=3,
degree_offset=0, unnecessary_permutations=None,
_try_heurisch=None):
"""
A wrapper around the heurisch integration algorithm.
Explanation
===========
This method takes the result from heurisch and checks for poles in the
denominator. For each of these poles, the integral is reevaluated, and
the final integration result is given in terms of a Piecewise.
Examples
========
>>> from sympy.core import symbols
>>> from sympy.functions import cos
>>> from sympy.integrals.heurisch import heurisch, heurisch_wrapper
>>> n, x = symbols('n x')
>>> heurisch(cos(n*x), x)
sin(n*x)/n
>>> heurisch_wrapper(cos(n*x), x)
Piecewise((sin(n*x)/n, Ne(n, 0)), (x, True))
See Also
========
heurisch
"""
from sympy.solvers.solvers import solve, denoms
f = sympify(f)
if x not in f.free_symbols:
return f*x
res = heurisch(f, x, rewrite, hints, mappings, retries, degree_offset,
unnecessary_permutations, _try_heurisch)
if not isinstance(res, Basic):
return res
# We consider each denominator in the expression, and try to find
# cases where one or more symbolic denominator might be zero. The
# conditions for these cases are stored in the list slns.
slns = []
for d in denoms(res):
try:
slns += solve(d, dict=True, exclude=(x,))
except NotImplementedError:
pass
if not slns:
return res
slns = list(uniq(slns))
# Remove the solutions corresponding to poles in the original expression.
slns0 = []
for d in denoms(f):
try:
slns0 += solve(d, dict=True, exclude=(x,))
except NotImplementedError:
pass
slns = [s for s in slns if s not in slns0]
if not slns:
return res
if len(slns) > 1:
eqs = []
for sub_dict in slns:
eqs.extend([Eq(key, value) for key, value in sub_dict.items()])
slns = solve(eqs, dict=True, exclude=(x,)) + slns
# For each case listed in the list slns, we reevaluate the integral.
pairs = []
for sub_dict in slns:
expr = heurisch(f.subs(sub_dict), x, rewrite, hints, mappings, retries,
degree_offset, unnecessary_permutations,
_try_heurisch)
cond = And(*[Eq(key, value) for key, value in sub_dict.items()])
generic = Or(*[Ne(key, value) for key, value in sub_dict.items()])
if expr is None:
expr = integrate(f.subs(sub_dict),x)
pairs.append((expr, cond))
# If there is one condition, put the generic case first. Otherwise,
# doing so may lead to longer Piecewise formulas
if len(pairs) == 1:
pairs = [(heurisch(f, x, rewrite, hints, mappings, retries,
degree_offset, unnecessary_permutations,
_try_heurisch),
generic),
(pairs[0][0], True)]
else:
pairs.append((heurisch(f, x, rewrite, hints, mappings, retries,
degree_offset, unnecessary_permutations,
_try_heurisch),
True))
return Piecewise(*pairs)
class BesselTable:
"""
Derivatives of Bessel functions of orders n and n-1
in terms of each other.
See the docstring of DiffCache.
"""
def __init__(self):
self.table = {}
self.n = Dummy('n')
self.z = Dummy('z')
self._create_table()
def _create_table(t):
table, n, z = t.table, t.n, t.z
for f in (besselj, bessely, hankel1, hankel2):
table[f] = (f(n-1, z) - n*f(n, z)/z,
(n-1)*f(n-1, z)/z - f(n, z))
f = besseli
table[f] = (f(n-1, z) - n*f(n, z)/z,
(n-1)*f(n-1, z)/z + f(n, z))
f = besselk
table[f] = (-f(n-1, z) - n*f(n, z)/z,
(n-1)*f(n-1, z)/z - f(n, z))
for f in (jn, yn):
table[f] = (f(n-1, z) - (n+1)*f(n, z)/z,
(n-1)*f(n-1, z)/z - f(n, z))
def diffs(t, f, n, z):
if f in t.table:
diff0, diff1 = t.table[f]
repl = [(t.n, n), (t.z, z)]
return (diff0.subs(repl), diff1.subs(repl))
def has(t, f):
return f in t.table
_bessel_table = None
class DiffCache:
"""
Store for derivatives of expressions.
Explanation
===========
The standard form of the derivative of a Bessel function of order n
contains two Bessel functions of orders n-1 and n+1, respectively.
Such forms cannot be used in parallel Risch algorithm, because
there is a linear recurrence relation between the three functions
while the algorithm expects that functions and derivatives are
represented in terms of algebraically independent transcendentals.
The solution is to take two of the functions, e.g., those of orders
n and n-1, and to express the derivatives in terms of the pair.
To guarantee that the proper form is used the two derivatives are
cached as soon as one is encountered.
Derivatives of other functions are also cached at no extra cost.
All derivatives are with respect to the same variable `x`.
"""
def __init__(self, x):
self.cache = {}
self.x = x
global _bessel_table
if not _bessel_table:
_bessel_table = BesselTable()
def get_diff(self, f):
cache = self.cache
if f in cache:
pass
elif (not hasattr(f, 'func') or
not _bessel_table.has(f.func)):
cache[f] = cancel(f.diff(self.x))
else:
n, z = f.args
d0, d1 = _bessel_table.diffs(f.func, n, z)
dz = self.get_diff(z)
cache[f] = d0*dz
cache[f.func(n-1, z)] = d1*dz
return cache[f]
def heurisch(f, x, rewrite=False, hints=None, mappings=None, retries=3,
degree_offset=0, unnecessary_permutations=None,
_try_heurisch=None):
"""
Compute indefinite integral using heuristic Risch algorithm.
Explanation
===========
This is a heuristic approach to indefinite integration in finite
terms using the extended heuristic (parallel) Risch algorithm, based
on Manuel Bronstein's "Poor Man's Integrator".
The algorithm supports various classes of functions including
transcendental elementary or special functions like Airy,
Bessel, Whittaker and Lambert.
Note that this algorithm is not a decision procedure. If it isn't
able to compute the antiderivative for a given function, then this is
not a proof that such a functions does not exist. One should use
recursive Risch algorithm in such case. It's an open question if
this algorithm can be made a full decision procedure.
This is an internal integrator procedure. You should use toplevel
'integrate' function in most cases, as this procedure needs some
preprocessing steps and otherwise may fail.
Specification
=============
heurisch(f, x, rewrite=False, hints=None)
where
f : expression
x : symbol
rewrite -> force rewrite 'f' in terms of 'tan' and 'tanh'
hints -> a list of functions that may appear in anti-derivate
- hints = None --> no suggestions at all
- hints = [ ] --> try to figure out
- hints = [f1, ..., fn] --> we know better
Examples
========
>>> from sympy import tan
>>> from sympy.integrals.heurisch import heurisch
>>> from sympy.abc import x, y
>>> heurisch(y*tan(x), x)
y*log(tan(x)**2 + 1)/2
See Manuel Bronstein's "Poor Man's Integrator":
References
==========
.. [1] http://www-sop.inria.fr/cafe/Manuel.Bronstein/pmint/index.html
For more information on the implemented algorithm refer to:
.. [2] K. Geddes, L. Stefanus, On the Risch-Norman Integration
Method and its Implementation in Maple, Proceedings of
ISSAC'89, ACM Press, 212-217.
.. [3] J. H. Davenport, On the Parallel Risch Algorithm (I),
Proceedings of EUROCAM'82, LNCS 144, Springer, 144-157.
.. [4] J. H. Davenport, On the Parallel Risch Algorithm (III):
Use of Tangents, SIGSAM Bulletin 16 (1982), 3-6.
.. [5] J. H. Davenport, B. M. Trager, On the Parallel Risch
Algorithm (II), ACM Transactions on Mathematical
Software 11 (1985), 356-362.
See Also
========
sympy.integrals.integrals.Integral.doit
sympy.integrals.integrals.Integral
sympy.integrals.heurisch.components
"""
f = sympify(f)
# There are some functions that Heurisch cannot currently handle,
# so do not even try.
# Set _try_heurisch=True to skip this check
if _try_heurisch is not True:
if f.has(Abs, re, im, sign, Heaviside, DiracDelta, floor, ceiling, arg):
return
if x not in f.free_symbols:
return f*x
if not f.is_Add:
indep, f = f.as_independent(x)
else:
indep = S.One
rewritables = {
(sin, cos, cot): tan,
(sinh, cosh, coth): tanh,
}
if rewrite:
for candidates, rule in rewritables.items():
f = f.rewrite(candidates, rule)
else:
for candidates in rewritables.keys():
if f.has(*candidates):
break
else:
rewrite = True
terms = components(f, x)
if hints is not None:
if not hints:
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
c = Wild('c', exclude=[x])
for g in set(terms): # using copy of terms
if g.is_Function:
if isinstance(g, li):
M = g.args[0].match(a*x**b)
if M is not None:
terms.add( x*(li(M[a]*x**M[b]) - (M[a]*x**M[b])**(-1/M[b])*Ei((M[b]+1)*log(M[a]*x**M[b])/M[b])) )
#terms.add( x*(li(M[a]*x**M[b]) - (x**M[b])**(-1/M[b])*Ei((M[b]+1)*log(M[a]*x**M[b])/M[b])) )
#terms.add( x*(li(M[a]*x**M[b]) - x*Ei((M[b]+1)*log(M[a]*x**M[b])/M[b])) )
#terms.add( li(M[a]*x**M[b]) - Ei((M[b]+1)*log(M[a]*x**M[b])/M[b]) )
elif isinstance(g, exp):
M = g.args[0].match(a*x**2)
if M is not None:
if M[a].is_positive:
terms.add(erfi(sqrt(M[a])*x))
else: # M[a].is_negative or unknown
terms.add(erf(sqrt(-M[a])*x))
M = g.args[0].match(a*x**2 + b*x + c)
if M is not None:
if M[a].is_positive:
terms.add(sqrt(pi/4*(-M[a]))*exp(M[c] - M[b]**2/(4*M[a]))*
erfi(sqrt(M[a])*x + M[b]/(2*sqrt(M[a]))))
elif M[a].is_negative:
terms.add(sqrt(pi/4*(-M[a]))*exp(M[c] - M[b]**2/(4*M[a]))*
erf(sqrt(-M[a])*x - M[b]/(2*sqrt(-M[a]))))
M = g.args[0].match(a*log(x)**2)
if M is not None:
if M[a].is_positive:
terms.add(erfi(sqrt(M[a])*log(x) + 1/(2*sqrt(M[a]))))
if M[a].is_negative:
terms.add(erf(sqrt(-M[a])*log(x) - 1/(2*sqrt(-M[a]))))
elif g.is_Pow:
if g.exp.is_Rational and g.exp.q == 2:
M = g.base.match(a*x**2 + b)
if M is not None and M[b].is_positive:
if M[a].is_positive:
terms.add(asinh(sqrt(M[a]/M[b])*x))
elif M[a].is_negative:
terms.add(asin(sqrt(-M[a]/M[b])*x))
M = g.base.match(a*x**2 - b)
if M is not None and M[b].is_positive:
if M[a].is_positive:
terms.add(acosh(sqrt(M[a]/M[b])*x))
elif M[a].is_negative:
terms.add(-M[b]/2*sqrt(-M[a])*
atan(sqrt(-M[a])*x/sqrt(M[a]*x**2 - M[b])))
else:
terms |= set(hints)
dcache = DiffCache(x)
for g in set(terms): # using copy of terms
terms |= components(dcache.get_diff(g), x)
# TODO: caching is significant factor for why permutations work at all. Change this.
V = _symbols('x', len(terms))
# sort mapping expressions from largest to smallest (last is always x).
mapping = list(reversed(list(zip(*ordered( #
[(a[0].as_independent(x)[1], a) for a in zip(terms, V)])))[1])) #
rev_mapping = {v: k for k, v in mapping} #
if mappings is None: #
# optimizing the number of permutations of mapping #
assert mapping[-1][0] == x # if not, find it and correct this comment
unnecessary_permutations = [mapping.pop(-1)]
mappings = permutations(mapping)
else:
unnecessary_permutations = unnecessary_permutations or []
def _substitute(expr):
return expr.subs(mapping)
for mapping in mappings:
mapping = list(mapping)
mapping = mapping + unnecessary_permutations
diffs = [ _substitute(dcache.get_diff(g)) for g in terms ]
denoms = [ g.as_numer_denom()[1] for g in diffs ]
if all(h.is_polynomial(*V) for h in denoms) and _substitute(f).is_rational_function(*V):
denom = reduce(lambda p, q: lcm(p, q, *V), denoms)
break
else:
if not rewrite:
result = heurisch(f, x, rewrite=True, hints=hints,
unnecessary_permutations=unnecessary_permutations)
if result is not None:
return indep*result
return None
numers = [ cancel(denom*g) for g in diffs ]
def _derivation(h):
return Add(*[ d * h.diff(v) for d, v in zip(numers, V) ])
def _deflation(p):
for y in V:
if not p.has(y):
continue
if _derivation(p) is not S.Zero:
c, q = p.as_poly(y).primitive()
return _deflation(c)*gcd(q, q.diff(y)).as_expr()
return p
def _splitter(p):
for y in V:
if not p.has(y):
continue
if _derivation(y) is not S.Zero:
c, q = p.as_poly(y).primitive()
q = q.as_expr()
h = gcd(q, _derivation(q), y)
s = quo(h, gcd(q, q.diff(y), y), y)
c_split = _splitter(c)
if s.as_poly(y).degree() == 0:
return (c_split[0], q * c_split[1])
q_split = _splitter(cancel(q / s))
return (c_split[0]*q_split[0]*s, c_split[1]*q_split[1])
return (S.One, p)
special = {}
for term in terms:
if term.is_Function:
if isinstance(term, tan):
special[1 + _substitute(term)**2] = False
elif isinstance(term, tanh):
special[1 + _substitute(term)] = False
special[1 - _substitute(term)] = False
elif isinstance(term, LambertW):
special[_substitute(term)] = True
F = _substitute(f)
P, Q = F.as_numer_denom()
u_split = _splitter(denom)
v_split = _splitter(Q)
polys = set(list(v_split) + [ u_split[0] ] + list(special.keys()))
s = u_split[0] * Mul(*[ k for k, v in special.items() if v ])
polified = [ p.as_poly(*V) for p in [s, P, Q] ]
if None in polified:
return None
#--- definitions for _integrate
a, b, c = [ p.total_degree() for p in polified ]
poly_denom = (s * v_split[0] * _deflation(v_split[1])).as_expr()
def _exponent(g):
if g.is_Pow:
if g.exp.is_Rational and g.exp.q != 1:
if g.exp.p > 0:
return g.exp.p + g.exp.q - 1
else:
return abs(g.exp.p + g.exp.q)
else:
return 1
elif not g.is_Atom and g.args:
return max([ _exponent(h) for h in g.args ])
else:
return 1
A, B = _exponent(f), a + max(b, c)
if A > 1 and B > 1:
monoms = tuple(ordered(itermonomials(V, A + B - 1 + degree_offset)))
else:
monoms = tuple(ordered(itermonomials(V, A + B + degree_offset)))
poly_coeffs = _symbols('A', len(monoms))
poly_part = Add(*[ poly_coeffs[i]*monomial
for i, monomial in enumerate(monoms) ])
reducibles = set()
for poly in polys:
if poly.has(*V):
try:
factorization = factor(poly, greedy=True)
except PolynomialError:
factorization = poly
if factorization.is_Mul:
factors = factorization.args
else:
factors = (factorization, )
for fact in factors:
if fact.is_Pow:
reducibles.add(fact.base)
else:
reducibles.add(fact)
def _integrate(field=None):
irreducibles = set()
atans = set()
pairs = set()
for poly in reducibles:
for z in poly.free_symbols:
if z in V:
break # should this be: `irreducibles |= \
else: # set(root_factors(poly, z, filter=field))`
continue # and the line below deleted?
# |
# V
irreducibles |= set(root_factors(poly, z, filter=field))
log_part, atan_part = [], []
for poly in list(irreducibles):
m = collect(poly, I, evaluate=False)
y = m.get(I, S.Zero)
if y:
x = m.get(S.One, S.Zero)
if x.has(I) or y.has(I):
continue # nontrivial x + I*y
pairs.add((x, y))
irreducibles.remove(poly)
while pairs:
x, y = pairs.pop()
if (x, -y) in pairs:
pairs.remove((x, -y))
# Choosing b with no minus sign
if y.could_extract_minus_sign():
y = -y
irreducibles.add(x*x + y*y)
atans.add(atan(x/y))
else:
irreducibles.add(x + I*y)
B = _symbols('B', len(irreducibles))
C = _symbols('C', len(atans))
# Note: the ordering matters here
for poly, b in reversed(list(zip(ordered(irreducibles), B))):
if poly.has(*V):
poly_coeffs.append(b)
log_part.append(b * log(poly))
for poly, c in reversed(list(zip(ordered(atans), C))):
if poly.has(*V):
poly_coeffs.append(c)
atan_part.append(c * poly)
# TODO: Currently it's better to use symbolic expressions here instead
# of rational functions, because it's simpler and FracElement doesn't
# give big speed improvement yet. This is because cancellation is slow
# due to slow polynomial GCD algorithms. If this gets improved then
# revise this code.
candidate = poly_part/poly_denom + Add(*log_part) + Add(*atan_part)
h = F - _derivation(candidate) / denom
raw_numer = h.as_numer_denom()[0]
# Rewrite raw_numer as a polynomial in K[coeffs][V] where K is a field
# that we have to determine. We can't use simply atoms() because log(3),
# sqrt(y) and similar expressions can appear, leading to non-trivial
# domains.
syms = set(poly_coeffs) | set(V)
non_syms = set()
def find_non_syms(expr):
if expr.is_Integer or expr.is_Rational:
pass # ignore trivial numbers
elif expr in syms:
pass # ignore variables
elif not expr.free_symbols & syms:
non_syms.add(expr)
elif expr.is_Add or expr.is_Mul or expr.is_Pow:
list(map(find_non_syms, expr.args))
else:
# TODO: Non-polynomial expression. This should have been
# filtered out at an earlier stage.
raise PolynomialError
try:
find_non_syms(raw_numer)
except PolynomialError:
return None
else:
ground, _ = construct_domain(non_syms, field=True)
coeff_ring = PolyRing(poly_coeffs, ground)
ring = PolyRing(V, coeff_ring)
try:
numer = ring.from_expr(raw_numer)
except ValueError:
raise PolynomialError
solution = solve_lin_sys(numer.coeffs(), coeff_ring, _raw=False)
if solution is None:
return None
else:
return candidate.xreplace(solution).xreplace(
dict(zip(poly_coeffs, [S.Zero]*len(poly_coeffs))))
if not (F.free_symbols - set(V)):
solution = _integrate('Q')
if solution is None:
solution = _integrate()
else:
solution = _integrate()
if solution is not None:
antideriv = solution.subs(rev_mapping)
antideriv = cancel(antideriv).expand()
if antideriv.is_Add:
antideriv = antideriv.as_independent(x)[1]
return indep*antideriv
else:
if retries >= 0:
result = heurisch(f, x, mappings=mappings, rewrite=rewrite, hints=hints, retries=retries - 1, unnecessary_permutations=unnecessary_permutations)
if result is not None:
return indep*result
return None
|
17f7018f340f5ebb1b5a4b58104b3537ee508540a06d4f9bc3434efbe4f3db93 | """
Algorithms for solving the Risch differential equation.
Given a differential field K of characteristic 0 that is a simple
monomial extension of a base field k and f, g in K, the Risch
Differential Equation problem is to decide if there exist y in K such
that Dy + f*y == g and to find one if there are some. If t is a
monomial over k and the coefficients of f and g are in k(t), then y is
in k(t), and the outline of the algorithm here is given as:
1. Compute the normal part n of the denominator of y. The problem is
then reduced to finding y' in k<t>, where y == y'/n.
2. Compute the special part s of the denominator of y. The problem is
then reduced to finding y'' in k[t], where y == y''/(n*s)
3. Bound the degree of y''.
4. Reduce the equation Dy + f*y == g to a similar equation with f, g in
k[t].
5. Find the solutions in k[t] of bounded degree of the reduced equation.
See Chapter 6 of "Symbolic Integration I: Transcendental Functions" by
Manuel Bronstein. See also the docstring of risch.py.
"""
from operator import mul
from functools import reduce
from sympy.core import oo
from sympy.core.symbol import Dummy
from sympy.polys import Poly, gcd, ZZ, cancel
from sympy import sqrt, re, im
from sympy.integrals.risch import (gcdex_diophantine, frac_in, derivation,
splitfactor, NonElementaryIntegralException, DecrementLevel, recognize_log_derivative)
# TODO: Add messages to NonElementaryIntegralException errors
def order_at(a, p, t):
"""
Computes the order of a at p, with respect to t.
Explanation
===========
For a, p in k[t], the order of a at p is defined as nu_p(a) = max({n
in Z+ such that p**n|a}), where a != 0. If a == 0, nu_p(a) = +oo.
To compute the order at a rational function, a/b, use the fact that
nu_p(a/b) == nu_p(a) - nu_p(b).
"""
if a.is_zero:
return oo
if p == Poly(t, t):
return a.as_poly(t).ET()[0][0]
# Uses binary search for calculating the power. power_list collects the tuples
# (p^k,k) where each k is some power of 2. After deciding the largest k
# such that k is power of 2 and p^k|a the loop iteratively calculates
# the actual power.
power_list = []
p1 = p
r = a.rem(p1)
tracks_power = 1
while r.is_zero:
power_list.append((p1,tracks_power))
p1 = p1*p1
tracks_power *= 2
r = a.rem(p1)
n = 0
product = Poly(1, t)
while len(power_list) != 0:
final = power_list.pop()
productf = product*final[0]
r = a.rem(productf)
if r.is_zero:
n += final[1]
product = productf
return n
def order_at_oo(a, d, t):
"""
Computes the order of a/d at oo (infinity), with respect to t.
For f in k(t), the order or f at oo is defined as deg(d) - deg(a), where
f == a/d.
"""
if a.is_zero:
return oo
return d.degree(t) - a.degree(t)
def weak_normalizer(a, d, DE, z=None):
"""
Weak normalization.
Explanation
===========
Given a derivation D on k[t] and f == a/d in k(t), return q in k[t]
such that f - Dq/q is weakly normalized with respect to t.
f in k(t) is said to be "weakly normalized" with respect to t if
residue_p(f) is not a positive integer for any normal irreducible p
in k[t] such that f is in R_p (Definition 6.1.1). If f has an
elementary integral, this is equivalent to no logarithm of
integral(f) whose argument depends on t has a positive integer
coefficient, where the arguments of the logarithms not in k(t) are
in k[t].
Returns (q, f - Dq/q)
"""
z = z or Dummy('z')
dn, ds = splitfactor(d, DE)
# Compute d1, where dn == d1*d2**2*...*dn**n is a square-free
# factorization of d.
g = gcd(dn, dn.diff(DE.t))
d_sqf_part = dn.quo(g)
d1 = d_sqf_part.quo(gcd(d_sqf_part, g))
a1, b = gcdex_diophantine(d.quo(d1).as_poly(DE.t), d1.as_poly(DE.t),
a.as_poly(DE.t))
r = (a - Poly(z, DE.t)*derivation(d1, DE)).as_poly(DE.t).resultant(
d1.as_poly(DE.t))
r = Poly(r, z)
if not r.expr.has(z):
return (Poly(1, DE.t), (a, d))
N = [i for i in r.real_roots() if i in ZZ and i > 0]
q = reduce(mul, [gcd(a - Poly(n, DE.t)*derivation(d1, DE), d1) for n in N],
Poly(1, DE.t))
dq = derivation(q, DE)
sn = q*a - d*dq
sd = q*d
sn, sd = sn.cancel(sd, include=True)
return (q, (sn, sd))
def normal_denom(fa, fd, ga, gd, DE):
"""
Normal part of the denominator.
Explanation
===========
Given a derivation D on k[t] and f, g in k(t) with f weakly
normalized with respect to t, either raise NonElementaryIntegralException,
in which case the equation Dy + f*y == g has no solution in k(t), or the
quadruplet (a, b, c, h) such that a, h in k[t], b, c in k<t>, and for any
solution y in k(t) of Dy + f*y == g, q = y*h in k<t> satisfies
a*Dq + b*q == c.
This constitutes step 1 in the outline given in the rde.py docstring.
"""
dn, ds = splitfactor(fd, DE)
en, es = splitfactor(gd, DE)
p = dn.gcd(en)
h = en.gcd(en.diff(DE.t)).quo(p.gcd(p.diff(DE.t)))
a = dn*h
c = a*h
if c.div(en)[1]:
# en does not divide dn*h**2
raise NonElementaryIntegralException
ca = c*ga
ca, cd = ca.cancel(gd, include=True)
ba = a*fa - dn*derivation(h, DE)*fd
ba, bd = ba.cancel(fd, include=True)
# (dn*h, dn*h*f - dn*Dh, dn*h**2*g, h)
return (a, (ba, bd), (ca, cd), h)
def special_denom(a, ba, bd, ca, cd, DE, case='auto'):
"""
Special part of the denominator.
Explanation
===========
case is one of {'exp', 'tan', 'primitive'} for the hyperexponential,
hypertangent, and primitive cases, respectively. For the
hyperexponential (resp. hypertangent) case, given a derivation D on
k[t] and a in k[t], b, c, in k<t> with Dt/t in k (resp. Dt/(t**2 + 1) in
k, sqrt(-1) not in k), a != 0, and gcd(a, t) == 1 (resp.
gcd(a, t**2 + 1) == 1), return the quadruplet (A, B, C, 1/h) such that
A, B, C, h in k[t] and for any solution q in k<t> of a*Dq + b*q == c,
r = qh in k[t] satisfies A*Dr + B*r == C.
For ``case == 'primitive'``, k<t> == k[t], so it returns (a, b, c, 1) in
this case.
This constitutes step 2 of the outline given in the rde.py docstring.
"""
from sympy.integrals.prde import parametric_log_deriv
# TODO: finish writing this and write tests
if case == 'auto':
case = DE.case
if case == 'exp':
p = Poly(DE.t, DE.t)
elif case == 'tan':
p = Poly(DE.t**2 + 1, DE.t)
elif case in ['primitive', 'base']:
B = ba.to_field().quo(bd)
C = ca.to_field().quo(cd)
return (a, B, C, Poly(1, DE.t))
else:
raise ValueError("case must be one of {'exp', 'tan', 'primitive', "
"'base'}, not %s." % case)
nb = order_at(ba, p, DE.t) - order_at(bd, p, DE.t)
nc = order_at(ca, p, DE.t) - order_at(cd, p, DE.t)
n = min(0, nc - min(0, nb))
if not nb:
# Possible cancellation.
if case == 'exp':
dcoeff = DE.d.quo(Poly(DE.t, DE.t))
with DecrementLevel(DE): # We are guaranteed to not have problems,
# because case != 'base'.
alphaa, alphad = frac_in(-ba.eval(0)/bd.eval(0)/a.eval(0), DE.t)
etaa, etad = frac_in(dcoeff, DE.t)
A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
if A is not None:
Q, m, z = A
if Q == 1:
n = min(n, m)
elif case == 'tan':
dcoeff = DE.d.quo(Poly(DE.t**2+1, DE.t))
with DecrementLevel(DE): # We are guaranteed to not have problems,
# because case != 'base'.
alphaa, alphad = frac_in(im(-ba.eval(sqrt(-1))/bd.eval(sqrt(-1))/a.eval(sqrt(-1))), DE.t)
betaa, betad = frac_in(re(-ba.eval(sqrt(-1))/bd.eval(sqrt(-1))/a.eval(sqrt(-1))), DE.t)
etaa, etad = frac_in(dcoeff, DE.t)
if recognize_log_derivative(Poly(2, DE.t)*betaa, betad, DE):
A = parametric_log_deriv(alphaa*Poly(sqrt(-1), DE.t)*betad+alphad*betaa, alphad*betad, etaa, etad, DE)
if A is not None:
Q, m, z = A
if Q == 1:
n = min(n, m)
N = max(0, -nb, n - nc)
pN = p**N
pn = p**-n
A = a*pN
B = ba*pN.quo(bd) + Poly(n, DE.t)*a*derivation(p, DE).quo(p)*pN
C = (ca*pN*pn).quo(cd)
h = pn
# (a*p**N, (b + n*a*Dp/p)*p**N, c*p**(N - n), p**-n)
return (A, B, C, h)
def bound_degree(a, b, cQ, DE, case='auto', parametric=False):
"""
Bound on polynomial solutions.
Explanation
===========
Given a derivation D on k[t] and ``a``, ``b``, ``c`` in k[t] with ``a != 0``, return
n in ZZ such that deg(q) <= n for any solution q in k[t] of
a*Dq + b*q == c, when parametric=False, or deg(q) <= n for any solution
c1, ..., cm in Const(k) and q in k[t] of a*Dq + b*q == Sum(ci*gi, (i, 1, m))
when parametric=True.
For ``parametric=False``, ``cQ`` is ``c``, a ``Poly``; for ``parametric=True``, ``cQ`` is Q ==
[q1, ..., qm], a list of Polys.
This constitutes step 3 of the outline given in the rde.py docstring.
"""
from sympy.integrals.prde import (parametric_log_deriv, limited_integrate,
is_log_deriv_k_t_radical_in_field)
# TODO: finish writing this and write tests
if case == 'auto':
case = DE.case
da = a.degree(DE.t)
db = b.degree(DE.t)
# The parametric and regular cases are identical, except for this part
if parametric:
dc = max([i.degree(DE.t) for i in cQ])
else:
dc = cQ.degree(DE.t)
alpha = cancel(-b.as_poly(DE.t).LC().as_expr()/
a.as_poly(DE.t).LC().as_expr())
if case == 'base':
n = max(0, dc - max(db, da - 1))
if db == da - 1 and alpha.is_Integer:
n = max(0, alpha, dc - db)
elif case == 'primitive':
if db > da:
n = max(0, dc - db)
else:
n = max(0, dc - da + 1)
etaa, etad = frac_in(DE.d, DE.T[DE.level - 1])
t1 = DE.t
with DecrementLevel(DE):
alphaa, alphad = frac_in(alpha, DE.t)
if db == da - 1:
# if alpha == m*Dt + Dz for z in k and m in ZZ:
try:
(za, zd), m = limited_integrate(alphaa, alphad, [(etaa, etad)],
DE)
except NonElementaryIntegralException:
pass
else:
if len(m) != 1:
raise ValueError("Length of m should be 1")
n = max(n, m[0])
elif db == da:
# if alpha == Dz/z for z in k*:
# beta = -lc(a*Dz + b*z)/(z*lc(a))
# if beta == m*Dt + Dw for w in k and m in ZZ:
# n = max(n, m)
A = is_log_deriv_k_t_radical_in_field(alphaa, alphad, DE)
if A is not None:
aa, z = A
if aa == 1:
beta = -(a*derivation(z, DE).as_poly(t1) +
b*z.as_poly(t1)).LC()/(z.as_expr()*a.LC())
betaa, betad = frac_in(beta, DE.t)
try:
(za, zd), m = limited_integrate(betaa, betad,
[(etaa, etad)], DE)
except NonElementaryIntegralException:
pass
else:
if len(m) != 1:
raise ValueError("Length of m should be 1")
n = max(n, m[0].as_expr())
elif case == 'exp':
n = max(0, dc - max(db, da))
if da == db:
etaa, etad = frac_in(DE.d.quo(Poly(DE.t, DE.t)), DE.T[DE.level - 1])
with DecrementLevel(DE):
alphaa, alphad = frac_in(alpha, DE.t)
A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
if A is not None:
# if alpha == m*Dt/t + Dz/z for z in k* and m in ZZ:
# n = max(n, m)
a, m, z = A
if a == 1:
n = max(n, m)
elif case in ['tan', 'other_nonlinear']:
delta = DE.d.degree(DE.t)
lam = DE.d.LC()
alpha = cancel(alpha/lam)
n = max(0, dc - max(da + delta - 1, db))
if db == da + delta - 1 and alpha.is_Integer:
n = max(0, alpha, dc - db)
else:
raise ValueError("case must be one of {'exp', 'tan', 'primitive', "
"'other_nonlinear', 'base'}, not %s." % case)
return n
def spde(a, b, c, n, DE):
"""
Rothstein's Special Polynomial Differential Equation algorithm.
Explanation
===========
Given a derivation D on k[t], an integer n and ``a``,``b``,``c`` in k[t] with
``a != 0``, either raise NonElementaryIntegralException, in which case the
equation a*Dq + b*q == c has no solution of degree at most ``n`` in
k[t], or return the tuple (B, C, m, alpha, beta) such that B, C,
alpha, beta in k[t], m in ZZ, and any solution q in k[t] of degree
at most n of a*Dq + b*q == c must be of the form
q == alpha*h + beta, where h in k[t], deg(h) <= m, and Dh + B*h == C.
This constitutes step 4 of the outline given in the rde.py docstring.
"""
zero = Poly(0, DE.t)
alpha = Poly(1, DE.t)
beta = Poly(0, DE.t)
while True:
if c.is_zero:
return (zero, zero, 0, zero, beta) # -1 is more to the point
if (n < 0) is True:
raise NonElementaryIntegralException
g = a.gcd(b)
if not c.rem(g).is_zero: # g does not divide c
raise NonElementaryIntegralException
a, b, c = a.quo(g), b.quo(g), c.quo(g)
if a.degree(DE.t) == 0:
b = b.to_field().quo(a)
c = c.to_field().quo(a)
return (b, c, n, alpha, beta)
r, z = gcdex_diophantine(b, a, c)
b += derivation(a, DE)
c = z - derivation(r, DE)
n -= a.degree(DE.t)
beta += alpha * r
alpha *= a
def no_cancel_b_large(b, c, n, DE):
"""
Poly Risch Differential Equation - No cancellation: deg(b) large enough.
Explanation
===========
Given a derivation D on k[t], ``n`` either an integer or +oo, and ``b``,``c``
in k[t] with ``b != 0`` and either D == d/dt or
deg(b) > max(0, deg(D) - 1), either raise NonElementaryIntegralException, in
which case the equation ``Dq + b*q == c`` has no solution of degree at
most n in k[t], or a solution q in k[t] of this equation with
``deg(q) < n``.
"""
q = Poly(0, DE.t)
while not c.is_zero:
m = c.degree(DE.t) - b.degree(DE.t)
if not 0 <= m <= n: # n < 0 or m < 0 or m > n
raise NonElementaryIntegralException
p = Poly(c.as_poly(DE.t).LC()/b.as_poly(DE.t).LC()*DE.t**m, DE.t,
expand=False)
q = q + p
n = m - 1
c = c - derivation(p, DE) - b*p
return q
def no_cancel_b_small(b, c, n, DE):
"""
Poly Risch Differential Equation - No cancellation: deg(b) small enough.
Explanation
===========
Given a derivation D on k[t], ``n`` either an integer or +oo, and ``b``,``c``
in k[t] with deg(b) < deg(D) - 1 and either D == d/dt or
deg(D) >= 2, either raise NonElementaryIntegralException, in which case the
equation Dq + b*q == c has no solution of degree at most n in k[t],
or a solution q in k[t] of this equation with deg(q) <= n, or the
tuple (h, b0, c0) such that h in k[t], b0, c0, in k, and for any
solution q in k[t] of degree at most n of Dq + bq == c, y == q - h
is a solution in k of Dy + b0*y == c0.
"""
q = Poly(0, DE.t)
while not c.is_zero:
if n == 0:
m = 0
else:
m = c.degree(DE.t) - DE.d.degree(DE.t) + 1
if not 0 <= m <= n: # n < 0 or m < 0 or m > n
raise NonElementaryIntegralException
if m > 0:
p = Poly(c.as_poly(DE.t).LC()/(m*DE.d.as_poly(DE.t).LC())*DE.t**m,
DE.t, expand=False)
else:
if b.degree(DE.t) != c.degree(DE.t):
raise NonElementaryIntegralException
if b.degree(DE.t) == 0:
return (q, b.as_poly(DE.T[DE.level - 1]),
c.as_poly(DE.T[DE.level - 1]))
p = Poly(c.as_poly(DE.t).LC()/b.as_poly(DE.t).LC(), DE.t,
expand=False)
q = q + p
n = m - 1
c = c - derivation(p, DE) - b*p
return q
# TODO: better name for this function
def no_cancel_equal(b, c, n, DE):
"""
Poly Risch Differential Equation - No cancellation: deg(b) == deg(D) - 1
Explanation
===========
Given a derivation D on k[t] with deg(D) >= 2, n either an integer
or +oo, and b, c in k[t] with deg(b) == deg(D) - 1, either raise
NonElementaryIntegralException, in which case the equation Dq + b*q == c has
no solution of degree at most n in k[t], or a solution q in k[t] of
this equation with deg(q) <= n, or the tuple (h, m, C) such that h
in k[t], m in ZZ, and C in k[t], and for any solution q in k[t] of
degree at most n of Dq + b*q == c, y == q - h is a solution in k[t]
of degree at most m of Dy + b*y == C.
"""
q = Poly(0, DE.t)
lc = cancel(-b.as_poly(DE.t).LC()/DE.d.as_poly(DE.t).LC())
if lc.is_Integer and lc.is_positive:
M = lc
else:
M = -1
while not c.is_zero:
m = max(M, c.degree(DE.t) - DE.d.degree(DE.t) + 1)
if not 0 <= m <= n: # n < 0 or m < 0 or m > n
raise NonElementaryIntegralException
u = cancel(m*DE.d.as_poly(DE.t).LC() + b.as_poly(DE.t).LC())
if u.is_zero:
return (q, m, c)
if m > 0:
p = Poly(c.as_poly(DE.t).LC()/u*DE.t**m, DE.t, expand=False)
else:
if c.degree(DE.t) != DE.d.degree(DE.t) - 1:
raise NonElementaryIntegralException
else:
p = c.as_poly(DE.t).LC()/b.as_poly(DE.t).LC()
q = q + p
n = m - 1
c = c - derivation(p, DE) - b*p
return q
def cancel_primitive(b, c, n, DE):
"""
Poly Risch Differential Equation - Cancellation: Primitive case.
Explanation
===========
Given a derivation D on k[t], n either an integer or +oo, ``b`` in k, and
``c`` in k[t] with Dt in k and ``b != 0``, either raise
NonElementaryIntegralException, in which case the equation Dq + b*q == c
has no solution of degree at most n in k[t], or a solution q in k[t] of
this equation with deg(q) <= n.
"""
from sympy.integrals.prde import is_log_deriv_k_t_radical_in_field
with DecrementLevel(DE):
ba, bd = frac_in(b, DE.t)
A = is_log_deriv_k_t_radical_in_field(ba, bd, DE)
if A is not None:
n, z = A
if n == 1: # b == Dz/z
raise NotImplementedError("is_deriv_in_field() is required to "
" solve this problem.")
# if z*c == Dp for p in k[t] and deg(p) <= n:
# return p/z
# else:
# raise NonElementaryIntegralException
if c.is_zero:
return c # return 0
if n < c.degree(DE.t):
raise NonElementaryIntegralException
q = Poly(0, DE.t)
while not c.is_zero:
m = c.degree(DE.t)
if n < m:
raise NonElementaryIntegralException
with DecrementLevel(DE):
a2a, a2d = frac_in(c.LC(), DE.t)
sa, sd = rischDE(ba, bd, a2a, a2d, DE)
stm = Poly(sa.as_expr()/sd.as_expr()*DE.t**m, DE.t, expand=False)
q += stm
n = m - 1
c -= b*stm + derivation(stm, DE)
return q
def cancel_exp(b, c, n, DE):
"""
Poly Risch Differential Equation - Cancellation: Hyperexponential case.
Explanation
===========
Given a derivation D on k[t], n either an integer or +oo, ``b`` in k, and
``c`` in k[t] with Dt/t in k and ``b != 0``, either raise
NonElementaryIntegralException, in which case the equation Dq + b*q == c
has no solution of degree at most n in k[t], or a solution q in k[t] of
this equation with deg(q) <= n.
"""
from sympy.integrals.prde import parametric_log_deriv
eta = DE.d.quo(Poly(DE.t, DE.t)).as_expr()
with DecrementLevel(DE):
etaa, etad = frac_in(eta, DE.t)
ba, bd = frac_in(b, DE.t)
A = parametric_log_deriv(ba, bd, etaa, etad, DE)
if A is not None:
a, m, z = A
if a == 1:
raise NotImplementedError("is_deriv_in_field() is required to "
"solve this problem.")
# if c*z*t**m == Dp for p in k<t> and q = p/(z*t**m) in k[t] and
# deg(q) <= n:
# return q
# else:
# raise NonElementaryIntegralException
if c.is_zero:
return c # return 0
if n < c.degree(DE.t):
raise NonElementaryIntegralException
q = Poly(0, DE.t)
while not c.is_zero:
m = c.degree(DE.t)
if n < m:
raise NonElementaryIntegralException
# a1 = b + m*Dt/t
a1 = b.as_expr()
with DecrementLevel(DE):
# TODO: Write a dummy function that does this idiom
a1a, a1d = frac_in(a1, DE.t)
a1a = a1a*etad + etaa*a1d*Poly(m, DE.t)
a1d = a1d*etad
a2a, a2d = frac_in(c.LC(), DE.t)
sa, sd = rischDE(a1a, a1d, a2a, a2d, DE)
stm = Poly(sa.as_expr()/sd.as_expr()*DE.t**m, DE.t, expand=False)
q += stm
n = m - 1
c -= b*stm + derivation(stm, DE) # deg(c) becomes smaller
return q
def solve_poly_rde(b, cQ, n, DE, parametric=False):
"""
Solve a Polynomial Risch Differential Equation with degree bound ``n``.
This constitutes step 4 of the outline given in the rde.py docstring.
For parametric=False, cQ is c, a Poly; for parametric=True, cQ is Q ==
[q1, ..., qm], a list of Polys.
"""
from sympy.integrals.prde import (prde_no_cancel_b_large,
prde_no_cancel_b_small)
# No cancellation
if not b.is_zero and (DE.case == 'base' or
b.degree(DE.t) > max(0, DE.d.degree(DE.t) - 1)):
if parametric:
return prde_no_cancel_b_large(b, cQ, n, DE)
return no_cancel_b_large(b, cQ, n, DE)
elif (b.is_zero or b.degree(DE.t) < DE.d.degree(DE.t) - 1) and \
(DE.case == 'base' or DE.d.degree(DE.t) >= 2):
if parametric:
return prde_no_cancel_b_small(b, cQ, n, DE)
R = no_cancel_b_small(b, cQ, n, DE)
if isinstance(R, Poly):
return R
else:
# XXX: Might k be a field? (pg. 209)
h, b0, c0 = R
with DecrementLevel(DE):
b0, c0 = b0.as_poly(DE.t), c0.as_poly(DE.t)
if b0 is None: # See above comment
raise ValueError("b0 should be a non-Null value")
if c0 is None:
raise ValueError("c0 should be a non-Null value")
y = solve_poly_rde(b0, c0, n, DE).as_poly(DE.t)
return h + y
elif DE.d.degree(DE.t) >= 2 and b.degree(DE.t) == DE.d.degree(DE.t) - 1 and \
n > -b.as_poly(DE.t).LC()/DE.d.as_poly(DE.t).LC():
# TODO: Is this check necessary, and if so, what should it do if it fails?
# b comes from the first element returned from spde()
if not b.as_poly(DE.t).LC().is_number:
raise TypeError("Result should be a number")
if parametric:
raise NotImplementedError("prde_no_cancel_b_equal() is not yet "
"implemented.")
R = no_cancel_equal(b, cQ, n, DE)
if isinstance(R, Poly):
return R
else:
h, m, C = R
# XXX: Or should it be rischDE()?
y = solve_poly_rde(b, C, m, DE)
return h + y
else:
# Cancellation
if b.is_zero:
raise NotImplementedError("Remaining cases for Poly (P)RDE are "
"not yet implemented (is_deriv_in_field() required).")
else:
if DE.case == 'exp':
if parametric:
raise NotImplementedError("Parametric RDE cancellation "
"hyperexponential case is not yet implemented.")
return cancel_exp(b, cQ, n, DE)
elif DE.case == 'primitive':
if parametric:
raise NotImplementedError("Parametric RDE cancellation "
"primitive case is not yet implemented.")
return cancel_primitive(b, cQ, n, DE)
else:
raise NotImplementedError("Other Poly (P)RDE cancellation "
"cases are not yet implemented (%s)." % DE.case)
if parametric:
raise NotImplementedError("Remaining cases for Poly PRDE not yet "
"implemented.")
raise NotImplementedError("Remaining cases for Poly RDE not yet "
"implemented.")
def rischDE(fa, fd, ga, gd, DE):
"""
Solve a Risch Differential Equation: Dy + f*y == g.
Explanation
===========
See the outline in the docstring of rde.py for more information
about the procedure used. Either raise NonElementaryIntegralException, in
which case there is no solution y in the given differential field,
or return y in k(t) satisfying Dy + f*y == g, or raise
NotImplementedError, in which case, the algorithms necessary to
solve the given Risch Differential Equation have not yet been
implemented.
"""
_, (fa, fd) = weak_normalizer(fa, fd, DE)
a, (ba, bd), (ca, cd), hn = normal_denom(fa, fd, ga, gd, DE)
A, B, C, hs = special_denom(a, ba, bd, ca, cd, DE)
try:
# Until this is fully implemented, use oo. Note that this will almost
# certainly cause non-termination in spde() (unless A == 1), and
# *might* lead to non-termination in the next step for a nonelementary
# integral (I don't know for certain yet). Fortunately, spde() is
# currently written recursively, so this will just give
# RuntimeError: maximum recursion depth exceeded.
n = bound_degree(A, B, C, DE)
except NotImplementedError:
# Useful for debugging:
# import warnings
# warnings.warn("rischDE: Proceeding with n = oo; may cause "
# "non-termination.")
n = oo
B, C, m, alpha, beta = spde(A, B, C, n, DE)
if C.is_zero:
y = C
else:
y = solve_poly_rde(B, C, m, DE)
return (alpha*y + beta, hn*hs)
|
dc59df2fae0afb2c8e5e245c9d017316f41487cb57d2ef0bd383fda4f401dd3f | from sympy.core import Mul
from sympy.functions import DiracDelta, Heaviside
from sympy.core.compatibility import default_sort_key
from sympy.core.singleton import S
def change_mul(node, x):
"""change_mul(node, x)
Rearranges the operands of a product, bringing to front any simple
DiracDelta expression.
Explanation
===========
If no simple DiracDelta expression was found, then all the DiracDelta
expressions are simplified (using DiracDelta.expand(diracdelta=True, wrt=x)).
Return: (dirac, new node)
Where:
o dirac is either a simple DiracDelta expression or None (if no simple
expression was found);
o new node is either a simplified DiracDelta expressions or None (if it
could not be simplified).
Examples
========
>>> from sympy import DiracDelta, cos
>>> from sympy.integrals.deltafunctions import change_mul
>>> from sympy.abc import x, y
>>> change_mul(x*y*DiracDelta(x)*cos(x), x)
(DiracDelta(x), x*y*cos(x))
>>> change_mul(x*y*DiracDelta(x**2 - 1)*cos(x), x)
(None, x*y*cos(x)*DiracDelta(x - 1)/2 + x*y*cos(x)*DiracDelta(x + 1)/2)
>>> change_mul(x*y*DiracDelta(cos(x))*cos(x), x)
(None, None)
See Also
========
sympy.functions.special.delta_functions.DiracDelta
deltaintegrate
"""
new_args = []
dirac = None
#Sorting is needed so that we consistently collapse the same delta;
#However, we must preserve the ordering of non-commutative terms
c, nc = node.args_cnc()
sorted_args = sorted(c, key=default_sort_key)
sorted_args.extend(nc)
for arg in sorted_args:
if arg.is_Pow and isinstance(arg.base, DiracDelta):
new_args.append(arg.func(arg.base, arg.exp - 1))
arg = arg.base
if dirac is None and (isinstance(arg, DiracDelta) and arg.is_simple(x)):
dirac = arg
else:
new_args.append(arg)
if not dirac: # there was no simple dirac
new_args = []
for arg in sorted_args:
if isinstance(arg, DiracDelta):
new_args.append(arg.expand(diracdelta=True, wrt=x))
elif arg.is_Pow and isinstance(arg.base, DiracDelta):
new_args.append(arg.func(arg.base.expand(diracdelta=True, wrt=x), arg.exp))
else:
new_args.append(arg)
if new_args != sorted_args:
nnode = Mul(*new_args).expand()
else: # if the node didn't change there is nothing to do
nnode = None
return (None, nnode)
return (dirac, Mul(*new_args))
def deltaintegrate(f, x):
"""
deltaintegrate(f, x)
Explanation
===========
The idea for integration is the following:
- If we are dealing with a DiracDelta expression, i.e. DiracDelta(g(x)),
we try to simplify it.
If we could simplify it, then we integrate the resulting expression.
We already know we can integrate a simplified expression, because only
simple DiracDelta expressions are involved.
If we couldn't simplify it, there are two cases:
1) The expression is a simple expression: we return the integral,
taking care if we are dealing with a Derivative or with a proper
DiracDelta.
2) The expression is not simple (i.e. DiracDelta(cos(x))): we can do
nothing at all.
- If the node is a multiplication node having a DiracDelta term:
First we expand it.
If the expansion did work, then we try to integrate the expansion.
If not, we try to extract a simple DiracDelta term, then we have two
cases:
1) We have a simple DiracDelta term, so we return the integral.
2) We didn't have a simple term, but we do have an expression with
simplified DiracDelta terms, so we integrate this expression.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.integrals.deltafunctions import deltaintegrate
>>> from sympy import sin, cos, DiracDelta
>>> deltaintegrate(x*sin(x)*cos(x)*DiracDelta(x - 1), x)
sin(1)*cos(1)*Heaviside(x - 1, 1/2)
>>> deltaintegrate(y**2*DiracDelta(x - z)*DiracDelta(y - z), y)
z**2*DiracDelta(x - z)*Heaviside(y - z, 1/2)
See Also
========
sympy.functions.special.delta_functions.DiracDelta
sympy.integrals.integrals.Integral
"""
if not f.has(DiracDelta):
return None
from sympy.integrals import Integral, integrate
from sympy.solvers import solve
# g(x) = DiracDelta(h(x))
if f.func == DiracDelta:
h = f.expand(diracdelta=True, wrt=x)
if h == f: # can't simplify the expression
#FIXME: the second term tells whether is DeltaDirac or Derivative
#For integrating derivatives of DiracDelta we need the chain rule
if f.is_simple(x):
if (len(f.args) <= 1 or f.args[1] == 0):
return Heaviside(f.args[0])
else:
return (DiracDelta(f.args[0], f.args[1] - 1) /
f.args[0].as_poly().LC())
else: # let's try to integrate the simplified expression
fh = integrate(h, x)
return fh
elif f.is_Mul or f.is_Pow: # g(x) = a*b*c*f(DiracDelta(h(x)))*d*e
g = f.expand()
if f != g: # the expansion worked
fh = integrate(g, x)
if fh is not None and not isinstance(fh, Integral):
return fh
else:
# no expansion performed, try to extract a simple DiracDelta term
deltaterm, rest_mult = change_mul(f, x)
if not deltaterm:
if rest_mult:
fh = integrate(rest_mult, x)
return fh
else:
deltaterm = deltaterm.expand(diracdelta=True, wrt=x)
if deltaterm.is_Mul: # Take out any extracted factors
deltaterm, rest_mult_2 = change_mul(deltaterm, x)
rest_mult = rest_mult*rest_mult_2
point = solve(deltaterm.args[0], x)[0]
# Return the largest hyperreal term left after
# repeated integration by parts. For example,
#
# integrate(y*DiracDelta(x, 1),x) == y*DiracDelta(x,0), not 0
#
# This is so Integral(y*DiracDelta(x).diff(x),x).doit()
# will return y*DiracDelta(x) instead of 0 or DiracDelta(x),
# both of which are correct everywhere the value is defined
# but give wrong answers for nested integration.
n = (0 if len(deltaterm.args)==1 else deltaterm.args[1])
m = 0
while n >= 0:
r = (-1)**n*rest_mult.diff(x, n).subs(x, point)
if r.is_zero:
n -= 1
m += 1
else:
if m == 0:
return r*Heaviside(x - point)
else:
return r*DiracDelta(x,m-1)
# In some very weak sense, x=0 is still a singularity,
# but we hope will not be of any practical consequence.
return S.Zero
return None
|
a6b89db7633076440ff98de32db7dfad0d5d732fe87c2e8a702350bef3d5de6d | """
Algorithms for solving Parametric Risch Differential Equations.
The methods used for solving Parametric Risch Differential Equations parallel
those for solving Risch Differential Equations. See the outline in the
docstring of rde.py for more information.
The Parametric Risch Differential Equation problem is, given f, g1, ..., gm in
K(t), to determine if there exist y in K(t) and c1, ..., cm in Const(K) such
that Dy + f*y == Sum(ci*gi, (i, 1, m)), and to find such y and ci if they exist.
For the algorithms here G is a list of tuples of factions of the terms on the
right hand side of the equation (i.e., gi in k(t)), and Q is a list of terms on
the right hand side of the equation (i.e., qi in k[t]). See the docstring of
each function for more information.
"""
from functools import reduce
from sympy.core import Dummy, ilcm, Add, Mul, Pow, S
from sympy.integrals.rde import (order_at, order_at_oo, weak_normalizer,
bound_degree)
from sympy.integrals.risch import (gcdex_diophantine, frac_in, derivation,
residue_reduce, splitfactor, residue_reduce_derivation, DecrementLevel,
recognize_log_derivative)
from sympy.polys import Poly, lcm, cancel, sqf_list
from sympy.polys.polymatrix import PolyMatrix as Matrix
from sympy.solvers import solve
zeros = Matrix.zeros
eye = Matrix.eye
def prde_normal_denom(fa, fd, G, DE):
"""
Parametric Risch Differential Equation - Normal part of the denominator.
Explanation
===========
Given a derivation D on k[t] and f, g1, ..., gm in k(t) with f weakly
normalized with respect to t, return the tuple (a, b, G, h) such that
a, h in k[t], b in k<t>, G = [g1, ..., gm] in k(t)^m, and for any solution
c1, ..., cm in Const(k) and y in k(t) of Dy + f*y == Sum(ci*gi, (i, 1, m)),
q == y*h in k<t> satisfies a*Dq + b*q == Sum(ci*Gi, (i, 1, m)).
"""
dn, ds = splitfactor(fd, DE)
Gas, Gds = list(zip(*G))
gd = reduce(lambda i, j: i.lcm(j), Gds, Poly(1, DE.t))
en, es = splitfactor(gd, DE)
p = dn.gcd(en)
h = en.gcd(en.diff(DE.t)).quo(p.gcd(p.diff(DE.t)))
a = dn*h
c = a*h
ba = a*fa - dn*derivation(h, DE)*fd
ba, bd = ba.cancel(fd, include=True)
G = [(c*A).cancel(D, include=True) for A, D in G]
return (a, (ba, bd), G, h)
def real_imag(ba, bd, gen):
"""
Helper function, to get the real and imaginary part of a rational function
evaluated at sqrt(-1) without actually evaluating it at sqrt(-1).
Explanation
===========
Separates the even and odd power terms by checking the degree of terms wrt
mod 4. Returns a tuple (ba[0], ba[1], bd) where ba[0] is real part
of the numerator ba[1] is the imaginary part and bd is the denominator
of the rational function.
"""
bd = bd.as_poly(gen).as_dict()
ba = ba.as_poly(gen).as_dict()
denom_real = [value if key[0] % 4 == 0 else -value if key[0] % 4 == 2 else 0 for key, value in bd.items()]
denom_imag = [value if key[0] % 4 == 1 else -value if key[0] % 4 == 3 else 0 for key, value in bd.items()]
bd_real = sum(r for r in denom_real)
bd_imag = sum(r for r in denom_imag)
num_real = [value if key[0] % 4 == 0 else -value if key[0] % 4 == 2 else 0 for key, value in ba.items()]
num_imag = [value if key[0] % 4 == 1 else -value if key[0] % 4 == 3 else 0 for key, value in ba.items()]
ba_real = sum(r for r in num_real)
ba_imag = sum(r for r in num_imag)
ba = ((ba_real*bd_real + ba_imag*bd_imag).as_poly(gen), (ba_imag*bd_real - ba_real*bd_imag).as_poly(gen))
bd = (bd_real*bd_real + bd_imag*bd_imag).as_poly(gen)
return (ba[0], ba[1], bd)
def prde_special_denom(a, ba, bd, G, DE, case='auto'):
"""
Parametric Risch Differential Equation - Special part of the denominator.
Explanation
===========
Case is one of {'exp', 'tan', 'primitive'} for the hyperexponential,
hypertangent, and primitive cases, respectively. For the hyperexponential
(resp. hypertangent) case, given a derivation D on k[t] and a in k[t],
b in k<t>, and g1, ..., gm in k(t) with Dt/t in k (resp. Dt/(t**2 + 1) in
k, sqrt(-1) not in k), a != 0, and gcd(a, t) == 1 (resp.
gcd(a, t**2 + 1) == 1), return the tuple (A, B, GG, h) such that A, B, h in
k[t], GG = [gg1, ..., ggm] in k(t)^m, and for any solution c1, ..., cm in
Const(k) and q in k<t> of a*Dq + b*q == Sum(ci*gi, (i, 1, m)), r == q*h in
k[t] satisfies A*Dr + B*r == Sum(ci*ggi, (i, 1, m)).
For case == 'primitive', k<t> == k[t], so it returns (a, b, G, 1) in this
case.
"""
# TODO: Merge this with the very similar special_denom() in rde.py
if case == 'auto':
case = DE.case
if case == 'exp':
p = Poly(DE.t, DE.t)
elif case == 'tan':
p = Poly(DE.t**2 + 1, DE.t)
elif case in ['primitive', 'base']:
B = ba.quo(bd)
return (a, B, G, Poly(1, DE.t))
else:
raise ValueError("case must be one of {'exp', 'tan', 'primitive', "
"'base'}, not %s." % case)
nb = order_at(ba, p, DE.t) - order_at(bd, p, DE.t)
nc = min([order_at(Ga, p, DE.t) - order_at(Gd, p, DE.t) for Ga, Gd in G])
n = min(0, nc - min(0, nb))
if not nb:
# Possible cancellation.
if case == 'exp':
dcoeff = DE.d.quo(Poly(DE.t, DE.t))
with DecrementLevel(DE): # We are guaranteed to not have problems,
# because case != 'base'.
alphaa, alphad = frac_in(-ba.eval(0)/bd.eval(0)/a.eval(0), DE.t)
etaa, etad = frac_in(dcoeff, DE.t)
A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
if A is not None:
Q, m, z = A
if Q == 1:
n = min(n, m)
elif case == 'tan':
dcoeff = DE.d.quo(Poly(DE.t**2 + 1, DE.t))
with DecrementLevel(DE): # We are guaranteed to not have problems,
# because case != 'base'.
betaa, alphaa, alphad = real_imag(ba, bd*a, DE.t)
betad = alphad
etaa, etad = frac_in(dcoeff, DE.t)
if recognize_log_derivative(Poly(2, DE.t)*betaa, betad, DE):
A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
B = parametric_log_deriv(betaa, betad, etaa, etad, DE)
if A is not None and B is not None:
Q, s, z = A
# TODO: Add test
if Q == 1:
n = min(n, s/2)
N = max(0, -nb)
pN = p**N
pn = p**-n # This is 1/h
A = a*pN
B = ba*pN.quo(bd) + Poly(n, DE.t)*a*derivation(p, DE).quo(p)*pN
G = [(Ga*pN*pn).cancel(Gd, include=True) for Ga, Gd in G]
h = pn
# (a*p**N, (b + n*a*Dp/p)*p**N, g1*p**(N - n), ..., gm*p**(N - n), p**-n)
return (A, B, G, h)
def prde_linear_constraints(a, b, G, DE):
"""
Parametric Risch Differential Equation - Generate linear constraints on the constants.
Explanation
===========
Given a derivation D on k[t], a, b, in k[t] with gcd(a, b) == 1, and
G = [g1, ..., gm] in k(t)^m, return Q = [q1, ..., qm] in k[t]^m and a
matrix M with entries in k(t) such that for any solution c1, ..., cm in
Const(k) and p in k[t] of a*Dp + b*p == Sum(ci*gi, (i, 1, m)),
(c1, ..., cm) is a solution of Mx == 0, and p and the ci satisfy
a*Dp + b*p == Sum(ci*qi, (i, 1, m)).
Because M has entries in k(t), and because Matrix doesn't play well with
Poly, M will be a Matrix of Basic expressions.
"""
m = len(G)
Gns, Gds = list(zip(*G))
d = reduce(lambda i, j: i.lcm(j), Gds)
d = Poly(d, field=True)
Q = [(ga*(d).quo(gd)).div(d) for ga, gd in G]
if not all([ri.is_zero for _, ri in Q]):
N = max([ri.degree(DE.t) for _, ri in Q])
M = Matrix(N + 1, m, lambda i, j: Q[j][1].nth(i), DE.t)
else:
M = Matrix(0, m, [], DE.t) # No constraints, return the empty matrix.
qs, _ = list(zip(*Q))
return (qs, M)
def poly_linear_constraints(p, d):
"""
Given p = [p1, ..., pm] in k[t]^m and d in k[t], return
q = [q1, ..., qm] in k[t]^m and a matrix M with entries in k such
that Sum(ci*pi, (i, 1, m)), for c1, ..., cm in k, is divisible
by d if and only if (c1, ..., cm) is a solution of Mx = 0, in
which case the quotient is Sum(ci*qi, (i, 1, m)).
"""
m = len(p)
q, r = zip(*[pi.div(d) for pi in p])
if not all([ri.is_zero for ri in r]):
n = max([ri.degree() for ri in r])
M = Matrix(n + 1, m, lambda i, j: r[j].nth(i), d.gens)
else:
M = Matrix(0, m, [], d.gens) # No constraints.
return q, M
def constant_system(A, u, DE):
"""
Generate a system for the constant solutions.
Explanation
===========
Given a differential field (K, D) with constant field C = Const(K), a Matrix
A, and a vector (Matrix) u with coefficients in K, returns the tuple
(B, v, s), where B is a Matrix with coefficients in C and v is a vector
(Matrix) such that either v has coefficients in C, in which case s is True
and the solutions in C of Ax == u are exactly all the solutions of Bx == v,
or v has a non-constant coefficient, in which case s is False Ax == u has no
constant solution.
This algorithm is used both in solving parametric problems and in
determining if an element a of K is a derivative of an element of K or the
logarithmic derivative of a K-radical using the structure theorem approach.
Because Poly does not play well with Matrix yet, this algorithm assumes that
all matrix entries are Basic expressions.
"""
if not A:
return A, u
Au = A.row_join(u)
Au, _ = Au.rref()
# Warning: This will NOT return correct results if cancel() cannot reduce
# an identically zero expression to 0. The danger is that we might
# incorrectly prove that an integral is nonelementary (such as
# risch_integrate(exp((sin(x)**2 + cos(x)**2 - 1)*x**2), x).
# But this is a limitation in computer algebra in general, and implicit
# in the correctness of the Risch Algorithm is the computability of the
# constant field (actually, this same correctness problem exists in any
# algorithm that uses rref()).
#
# We therefore limit ourselves to constant fields that are computable
# via the cancel() function, in order to prevent a speed bottleneck from
# calling some more complex simplification function (rational function
# coefficients will fall into this class). Furthermore, (I believe) this
# problem will only crop up if the integral explicitly contains an
# expression in the constant field that is identically zero, but cannot
# be reduced to such by cancel(). Therefore, a careful user can avoid this
# problem entirely by being careful with the sorts of expressions that
# appear in his integrand in the variables other than the integration
# variable (the structure theorems should be able to completely decide these
# problems in the integration variable).
A, u = Au[:, :-1], Au[:, -1]
D = lambda x: derivation(x, DE, basic=True)
for j in range(A.cols):
for i in range(A.rows):
if A[i, j].expr.has(*DE.T):
# This assumes that const(F(t0, ..., tn) == const(K) == F
Ri = A[i, :]
# Rm+1; m = A.rows
DAij = D(A[i, j])
Rm1 = Ri.applyfunc(lambda x: D(x) / DAij)
um1 = D(u[i]) / DAij
Aj = A[:, j]
A = A - Aj * Rm1
u = u - Aj * um1
A = A.col_join(Rm1)
u = u.col_join(Matrix([um1], u.gens))
return (A, u)
def prde_spde(a, b, Q, n, DE):
"""
Special Polynomial Differential Equation algorithm: Parametric Version.
Explanation
===========
Given a derivation D on k[t], an integer n, and a, b, q1, ..., qm in k[t]
with deg(a) > 0 and gcd(a, b) == 1, return (A, B, Q, R, n1), with
Qq = [q1, ..., qm] and R = [r1, ..., rm], such that for any solution
c1, ..., cm in Const(k) and q in k[t] of degree at most n of
a*Dq + b*q == Sum(ci*gi, (i, 1, m)), p = (q - Sum(ci*ri, (i, 1, m)))/a has
degree at most n1 and satisfies A*Dp + B*p == Sum(ci*qi, (i, 1, m))
"""
R, Z = list(zip(*[gcdex_diophantine(b, a, qi) for qi in Q]))
A = a
B = b + derivation(a, DE)
Qq = [zi - derivation(ri, DE) for ri, zi in zip(R, Z)]
R = list(R)
n1 = n - a.degree(DE.t)
return (A, B, Qq, R, n1)
def prde_no_cancel_b_large(b, Q, n, DE):
"""
Parametric Poly Risch Differential Equation - No cancellation: deg(b) large enough.
Explanation
===========
Given a derivation D on k[t], n in ZZ, and b, q1, ..., qm in k[t] with
b != 0 and either D == d/dt or deg(b) > max(0, deg(D) - 1), returns
h1, ..., hr in k[t] and a matrix A with coefficients in Const(k) such that
if c1, ..., cm in Const(k) and q in k[t] satisfy deg(q) <= n and
Dq + b*q == Sum(ci*qi, (i, 1, m)), then q = Sum(dj*hj, (j, 1, r)), where
d1, ..., dr in Const(k) and A*Matrix([[c1, ..., cm, d1, ..., dr]]).T == 0.
"""
db = b.degree(DE.t)
m = len(Q)
H = [Poly(0, DE.t)]*m
for N in range(n, -1, -1): # [n, ..., 0]
for i in range(m):
si = Q[i].nth(N + db)/b.LC()
sitn = Poly(si*DE.t**N, DE.t)
H[i] = H[i] + sitn
Q[i] = Q[i] - derivation(sitn, DE) - b*sitn
if all(qi.is_zero for qi in Q):
dc = -1
M = zeros(0, 2, DE.t)
else:
dc = max([qi.degree(DE.t) for qi in Q])
M = Matrix(dc + 1, m, lambda i, j: Q[j].nth(i), DE.t)
A, u = constant_system(M, zeros(dc + 1, 1, DE.t), DE)
c = eye(m, DE.t)
A = A.row_join(zeros(A.rows, m, DE.t)).col_join(c.row_join(-c))
return (H, A)
def prde_no_cancel_b_small(b, Q, n, DE):
"""
Parametric Poly Risch Differential Equation - No cancellation: deg(b) small enough.
Explanation
===========
Given a derivation D on k[t], n in ZZ, and b, q1, ..., qm in k[t] with
deg(b) < deg(D) - 1 and either D == d/dt or deg(D) >= 2, returns
h1, ..., hr in k[t] and a matrix A with coefficients in Const(k) such that
if c1, ..., cm in Const(k) and q in k[t] satisfy deg(q) <= n and
Dq + b*q == Sum(ci*qi, (i, 1, m)) then q = Sum(dj*hj, (j, 1, r)) where
d1, ..., dr in Const(k) and A*Matrix([[c1, ..., cm, d1, ..., dr]]).T == 0.
"""
m = len(Q)
H = [Poly(0, DE.t)]*m
for N in range(n, 0, -1): # [n, ..., 1]
for i in range(m):
si = Q[i].nth(N + DE.d.degree(DE.t) - 1)/(N*DE.d.LC())
sitn = Poly(si*DE.t**N, DE.t)
H[i] = H[i] + sitn
Q[i] = Q[i] - derivation(sitn, DE) - b*sitn
if b.degree(DE.t) > 0:
for i in range(m):
si = Poly(Q[i].nth(b.degree(DE.t))/b.LC(), DE.t)
H[i] = H[i] + si
Q[i] = Q[i] - derivation(si, DE) - b*si
if all(qi.is_zero for qi in Q):
dc = -1
M = Matrix()
else:
dc = max([qi.degree(DE.t) for qi in Q])
M = Matrix(dc + 1, m, lambda i, j: Q[j].nth(i), DE.t)
A, u = constant_system(M, zeros(dc + 1, 1, DE.t), DE)
c = eye(m, DE.t)
A = A.row_join(zeros(A.rows, m, DE.t)).col_join(c.row_join(-c))
return (H, A)
# else: b is in k, deg(qi) < deg(Dt)
t = DE.t
if DE.case != 'base':
with DecrementLevel(DE):
t0 = DE.t # k = k0(t0)
ba, bd = frac_in(b, t0, field=True)
Q0 = [frac_in(qi.TC(), t0, field=True) for qi in Q]
f, B = param_rischDE(ba, bd, Q0, DE)
# f = [f1, ..., fr] in k^r and B is a matrix with
# m + r columns and entries in Const(k) = Const(k0)
# such that Dy0 + b*y0 = Sum(ci*qi, (i, 1, m)) has
# a solution y0 in k with c1, ..., cm in Const(k)
# if and only y0 = Sum(dj*fj, (j, 1, r)) where
# d1, ..., dr ar in Const(k) and
# B*Matrix([c1, ..., cm, d1, ..., dr]) == 0.
# Transform fractions (fa, fd) in f into constant
# polynomials fa/fd in k[t].
# (Is there a better way?)
f = [Poly(fa.as_expr()/fd.as_expr(), t, field=True)
for fa, fd in f]
B = Matrix.from_Matrix(B.to_Matrix(), t)
else:
# Base case. Dy == 0 for all y in k and b == 0.
# Dy + b*y = Sum(ci*qi) is solvable if and only if
# Sum(ci*qi) == 0 in which case the solutions are
# y = d1*f1 for f1 = 1 and any d1 in Const(k) = k.
f = [Poly(1, t, field=True)] # r = 1
B = Matrix([[qi.TC() for qi in Q] + [S.Zero]], DE.t)
# The condition for solvability is
# B*Matrix([c1, ..., cm, d1]) == 0
# There are no constraints on d1.
# Coefficients of t^j (j > 0) in Sum(ci*qi) must be zero.
d = max([qi.degree(DE.t) for qi in Q])
if d > 0:
M = Matrix(d, m, lambda i, j: Q[j].nth(i + 1), DE.t)
A, _ = constant_system(M, zeros(d, 1, DE.t), DE)
else:
# No constraints on the hj.
A = Matrix(0, m, [], DE.t)
# Solutions of the original equation are
# y = Sum(dj*fj, (j, 1, r) + Sum(ei*hi, (i, 1, m)),
# where ei == ci (i = 1, ..., m), when
# A*Matrix([c1, ..., cm]) == 0 and
# B*Matrix([c1, ..., cm, d1, ..., dr]) == 0
# Build combined constraint matrix with m + r + m columns.
r = len(f)
I = eye(m, DE.t)
A = A.row_join(zeros(A.rows, r + m, DE.t))
B = B.row_join(zeros(B.rows, m, DE.t))
C = I.row_join(zeros(m, r, DE.t)).row_join(-I)
return f + H, A.col_join(B).col_join(C)
def prde_cancel_liouvillian(b, Q, n, DE):
"""
Pg, 237.
"""
H = []
# Why use DecrementLevel? Below line answers that:
# Assuming that we can solve such problems over 'k' (not k[t])
if DE.case == 'primitive':
with DecrementLevel(DE):
ba, bd = frac_in(b, DE.t, field=True)
for i in range(n, -1, -1):
if DE.case == 'exp': # this re-checking can be avoided
with DecrementLevel(DE):
ba, bd = frac_in(b + (i*(derivation(DE.t, DE)/DE.t)).as_poly(b.gens),
DE.t, field=True)
with DecrementLevel(DE):
Qy = [frac_in(q.nth(i), DE.t, field=True) for q in Q]
fi, Ai = param_rischDE(ba, bd, Qy, DE)
fi = [Poly(fa.as_expr()/fd.as_expr(), DE.t, field=True)
for fa, fd in fi]
Ai = Ai.set_gens(DE.t)
ri = len(fi)
if i == n:
M = Ai
else:
M = Ai.col_join(M.row_join(zeros(M.rows, ri, DE.t)))
Fi, hi = [None]*ri, [None]*ri
# from eq. on top of p.238 (unnumbered)
for j in range(ri):
hji = fi[j] * (DE.t**i).as_poly(fi[j].gens)
hi[j] = hji
# building up Sum(djn*(D(fjn*t^n) - b*fjnt^n))
Fi[j] = -(derivation(hji, DE) - b*hji)
H += hi
# in the next loop instead of Q it has
# to be Q + Fi taking its place
Q = Q + Fi
return (H, M)
def param_poly_rischDE(a, b, q, n, DE):
"""Polynomial solutions of a parametric Risch differential equation.
Explanation
===========
Given a derivation D in k[t], a, b in k[t] relatively prime, and q
= [q1, ..., qm] in k[t]^m, return h = [h1, ..., hr] in k[t]^r and
a matrix A with m + r columns and entries in Const(k) such that
a*Dp + b*p = Sum(ci*qi, (i, 1, m)) has a solution p of degree <= n
in k[t] with c1, ..., cm in Const(k) if and only if p = Sum(dj*hj,
(j, 1, r)) where d1, ..., dr are in Const(k) and (c1, ..., cm,
d1, ..., dr) is a solution of Ax == 0.
"""
m = len(q)
if n < 0:
# Only the trivial zero solution is possible.
# Find relations between the qi.
if all([qi.is_zero for qi in q]):
return [], zeros(1, m, DE.t) # No constraints.
N = max([qi.degree(DE.t) for qi in q])
M = Matrix(N + 1, m, lambda i, j: q[j].nth(i), DE.t)
A, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE)
return [], A
if a.is_ground:
# Normalization: a = 1.
a = a.LC()
b, q = b.quo_ground(a), [qi.quo_ground(a) for qi in q]
if not b.is_zero and (DE.case == 'base' or
b.degree() > max(0, DE.d.degree() - 1)):
return prde_no_cancel_b_large(b, q, n, DE)
elif ((b.is_zero or b.degree() < DE.d.degree() - 1)
and (DE.case == 'base' or DE.d.degree() >= 2)):
return prde_no_cancel_b_small(b, q, n, DE)
elif (DE.d.degree() >= 2 and
b.degree() == DE.d.degree() - 1 and
n > -b.as_poly().LC()/DE.d.as_poly().LC()):
raise NotImplementedError("prde_no_cancel_b_equal() is "
"not yet implemented.")
else:
# Liouvillian cases
if DE.case == 'primitive' or DE.case == 'exp':
return prde_cancel_liouvillian(b, q, n, DE)
else:
raise NotImplementedError("non-linear and hypertangent "
"cases have not yet been implemented")
# else: deg(a) > 0
# Iterate SPDE as long as possible cumulating coefficient
# and terms for the recovery of original solutions.
alpha, beta = a.one, [a.zero]*m
while n >= 0: # and a, b relatively prime
a, b, q, r, n = prde_spde(a, b, q, n, DE)
beta = [betai + alpha*ri for betai, ri in zip(beta, r)]
alpha *= a
# Solutions p of a*Dp + b*p = Sum(ci*qi) correspond to
# solutions alpha*p + Sum(ci*betai) of the initial equation.
d = a.gcd(b)
if not d.is_ground:
break
# a*Dp + b*p = Sum(ci*qi) may have a polynomial solution
# only if the sum is divisible by d.
qq, M = poly_linear_constraints(q, d)
# qq = [qq1, ..., qqm] where qqi = qi.quo(d).
# M is a matrix with m columns an entries in k.
# Sum(fi*qi, (i, 1, m)), where f1, ..., fm are elements of k, is
# divisible by d if and only if M*Matrix([f1, ..., fm]) == 0,
# in which case the quotient is Sum(fi*qqi).
A, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE)
# A is a matrix with m columns and entries in Const(k).
# Sum(ci*qqi) is Sum(ci*qi).quo(d), and the remainder is zero
# for c1, ..., cm in Const(k) if and only if
# A*Matrix([c1, ...,cm]) == 0.
V = A.nullspace()
# V = [v1, ..., vu] where each vj is a column matrix with
# entries aj1, ..., ajm in Const(k).
# Sum(aji*qi) is divisible by d with exact quotient Sum(aji*qqi).
# Sum(ci*qi) is divisible by d if and only if ci = Sum(dj*aji)
# (i = 1, ..., m) for some d1, ..., du in Const(k).
# In that case, solutions of
# a*Dp + b*p = Sum(ci*qi) = Sum(dj*Sum(aji*qi))
# are the same as those of
# (a/d)*Dp + (b/d)*p = Sum(dj*rj)
# where rj = Sum(aji*qqi).
if not V: # No non-trivial solution.
return [], eye(m, DE.t) # Could return A, but this has
# the minimum number of rows.
Mqq = Matrix([qq]) # A single row.
r = [(Mqq*vj)[0] for vj in V] # [r1, ..., ru]
# Solutions of (a/d)*Dp + (b/d)*p = Sum(dj*rj) correspond to
# solutions alpha*p + Sum(Sum(dj*aji)*betai) of the initial
# equation. These are equal to alpha*p + Sum(dj*fj) where
# fj = Sum(aji*betai).
Mbeta = Matrix([beta])
f = [(Mbeta*vj)[0] for vj in V] # [f1, ..., fu]
#
# Solve the reduced equation recursively.
#
g, B = param_poly_rischDE(a.quo(d), b.quo(d), r, n, DE)
# g = [g1, ..., gv] in k[t]^v and and B is a matrix with u + v
# columns and entries in Const(k) such that
# (a/d)*Dp + (b/d)*p = Sum(dj*rj) has a solution p of degree <= n
# in k[t] if and only if p = Sum(ek*gk) where e1, ..., ev are in
# Const(k) and B*Matrix([d1, ..., du, e1, ..., ev]) == 0.
# The solutions of the original equation are then
# Sum(dj*fj, (j, 1, u)) + alpha*Sum(ek*gk, (k, 1, v)).
# Collect solution components.
h = f + [alpha*gk for gk in g]
# Build combined relation matrix.
A = -eye(m, DE.t)
for vj in V:
A = A.row_join(vj)
A = A.row_join(zeros(m, len(g), DE.t))
A = A.col_join(zeros(B.rows, m, DE.t).row_join(B))
return h, A
def param_rischDE(fa, fd, G, DE):
"""
Solve a Parametric Risch Differential Equation: Dy + f*y == Sum(ci*Gi, (i, 1, m)).
Explanation
===========
Given a derivation D in k(t), f in k(t), and G
= [G1, ..., Gm] in k(t)^m, return h = [h1, ..., hr] in k(t)^r and
a matrix A with m + r columns and entries in Const(k) such that
Dy + f*y = Sum(ci*Gi, (i, 1, m)) has a solution y
in k(t) with c1, ..., cm in Const(k) if and only if y = Sum(dj*hj,
(j, 1, r)) where d1, ..., dr are in Const(k) and (c1, ..., cm,
d1, ..., dr) is a solution of Ax == 0.
Elements of k(t) are tuples (a, d) with a and d in k[t].
"""
m = len(G)
q, (fa, fd) = weak_normalizer(fa, fd, DE)
# Solutions of the weakly normalized equation Dz + f*z = q*Sum(ci*Gi)
# correspond to solutions y = z/q of the original equation.
gamma = q
G = [(q*ga).cancel(gd, include=True) for ga, gd in G]
a, (ba, bd), G, hn = prde_normal_denom(fa, fd, G, DE)
# Solutions q in k<t> of a*Dq + b*q = Sum(ci*Gi) correspond
# to solutions z = q/hn of the weakly normalized equation.
gamma *= hn
A, B, G, hs = prde_special_denom(a, ba, bd, G, DE)
# Solutions p in k[t] of A*Dp + B*p = Sum(ci*Gi) correspond
# to solutions q = p/hs of the previous equation.
gamma *= hs
g = A.gcd(B)
a, b, g = A.quo(g), B.quo(g), [gia.cancel(gid*g, include=True) for
gia, gid in G]
# a*Dp + b*p = Sum(ci*gi) may have a polynomial solution
# only if the sum is in k[t].
q, M = prde_linear_constraints(a, b, g, DE)
# q = [q1, ..., qm] where qi in k[t] is the polynomial component
# of the partial fraction expansion of gi.
# M is a matrix with m columns and entries in k.
# Sum(fi*gi, (i, 1, m)), where f1, ..., fm are elements of k,
# is a polynomial if and only if M*Matrix([f1, ..., fm]) == 0,
# in which case the sum is equal to Sum(fi*qi).
M, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE)
# M is a matrix with m columns and entries in Const(k).
# Sum(ci*gi) is in k[t] for c1, ..., cm in Const(k)
# if and only if M*Matrix([c1, ..., cm]) == 0,
# in which case the sum is Sum(ci*qi).
## Reduce number of constants at this point
V = M.nullspace()
# V = [v1, ..., vu] where each vj is a column matrix with
# entries aj1, ..., ajm in Const(k).
# Sum(aji*gi) is in k[t] and equal to Sum(aji*qi) (j = 1, ..., u).
# Sum(ci*gi) is in k[t] if and only is ci = Sum(dj*aji)
# (i = 1, ..., m) for some d1, ..., du in Const(k).
# In that case,
# Sum(ci*gi) = Sum(ci*qi) = Sum(dj*Sum(aji*qi)) = Sum(dj*rj)
# where rj = Sum(aji*qi) (j = 1, ..., u) in k[t].
if not V: # No non-trivial solution
return [], eye(m, DE.t)
Mq = Matrix([q]) # A single row.
r = [(Mq*vj)[0] for vj in V] # [r1, ..., ru]
# Solutions of a*Dp + b*p = Sum(dj*rj) correspond to solutions
# y = p/gamma of the initial equation with ci = Sum(dj*aji).
try:
# We try n=5. At least for prde_spde, it will always
# terminate no matter what n is.
n = bound_degree(a, b, r, DE, parametric=True)
except NotImplementedError:
# A temporary bound is set. Eventually, it will be removed.
# the currently added test case takes large time
# even with n=5, and much longer with large n's.
n = 5
h, B = param_poly_rischDE(a, b, r, n, DE)
# h = [h1, ..., hv] in k[t]^v and and B is a matrix with u + v
# columns and entries in Const(k) such that
# a*Dp + b*p = Sum(dj*rj) has a solution p of degree <= n
# in k[t] if and only if p = Sum(ek*hk) where e1, ..., ev are in
# Const(k) and B*Matrix([d1, ..., du, e1, ..., ev]) == 0.
# The solutions of the original equation for ci = Sum(dj*aji)
# (i = 1, ..., m) are then y = Sum(ek*hk, (k, 1, v))/gamma.
## Build combined relation matrix with m + u + v columns.
A = -eye(m, DE.t)
for vj in V:
A = A.row_join(vj)
A = A.row_join(zeros(m, len(h), DE.t))
A = A.col_join(zeros(B.rows, m, DE.t).row_join(B))
## Eliminate d1, ..., du.
W = A.nullspace()
# W = [w1, ..., wt] where each wl is a column matrix with
# entries blk (k = 1, ..., m + u + v) in Const(k).
# The vectors (bl1, ..., blm) generate the space of those
# constant families (c1, ..., cm) for which a solution of
# the equation Dy + f*y == Sum(ci*Gi) exists. They generate
# the space and form a basis except possibly when Dy + f*y == 0
# is solvable in k(t}. The corresponding solutions are
# y = Sum(blk'*hk, (k, 1, v))/gamma, where k' = k + m + u.
v = len(h)
M = Matrix([wl[:m] + wl[-v:] for wl in W]) # excise dj's.
N = M.nullspace()
# N = [n1, ..., ns] where the ni in Const(k)^(m + v) are column
# vectors generating the space of linear relations between
# c1, ..., cm, e1, ..., ev.
C = Matrix([ni[:] for ni in N], DE.t) # rows n1, ..., ns.
return [hk.cancel(gamma, include=True) for hk in h], C
def limited_integrate_reduce(fa, fd, G, DE):
"""
Simpler version of step 1 & 2 for the limited integration problem.
Explanation
===========
Given a derivation D on k(t) and f, g1, ..., gn in k(t), return
(a, b, h, N, g, V) such that a, b, h in k[t], N is a non-negative integer,
g in k(t), V == [v1, ..., vm] in k(t)^m, and for any solution v in k(t),
c1, ..., cm in C of f == Dv + Sum(ci*wi, (i, 1, m)), p = v*h is in k<t>, and
p and the ci satisfy a*Dp + b*p == g + Sum(ci*vi, (i, 1, m)). Furthermore,
if S1irr == Sirr, then p is in k[t], and if t is nonlinear or Liouvillian
over k, then deg(p) <= N.
So that the special part is always computed, this function calls the more
general prde_special_denom() automatically if it cannot determine that
S1irr == Sirr. Furthermore, it will automatically call bound_degree() when
t is linear and non-Liouvillian, which for the transcendental case, implies
that Dt == a*t + b with for some a, b in k*.
"""
dn, ds = splitfactor(fd, DE)
E = [splitfactor(gd, DE) for _, gd in G]
En, Es = list(zip(*E))
c = reduce(lambda i, j: i.lcm(j), (dn,) + En) # lcm(dn, en1, ..., enm)
hn = c.gcd(c.diff(DE.t))
a = hn
b = -derivation(hn, DE)
N = 0
# These are the cases where we know that S1irr = Sirr, but there could be
# others, and this algorithm will need to be extended to handle them.
if DE.case in ['base', 'primitive', 'exp', 'tan']:
hs = reduce(lambda i, j: i.lcm(j), (ds,) + Es) # lcm(ds, es1, ..., esm)
a = hn*hs
b -= (hn*derivation(hs, DE)).quo(hs)
mu = min(order_at_oo(fa, fd, DE.t), min([order_at_oo(ga, gd, DE.t) for
ga, gd in G]))
# So far, all the above are also nonlinear or Liouvillian, but if this
# changes, then this will need to be updated to call bound_degree()
# as per the docstring of this function (DE.case == 'other_linear').
N = hn.degree(DE.t) + hs.degree(DE.t) + max(0, 1 - DE.d.degree(DE.t) - mu)
else:
# TODO: implement this
raise NotImplementedError
V = [(-a*hn*ga).cancel(gd, include=True) for ga, gd in G]
return (a, b, a, N, (a*hn*fa).cancel(fd, include=True), V)
def limited_integrate(fa, fd, G, DE):
"""
Solves the limited integration problem: f = Dv + Sum(ci*wi, (i, 1, n))
"""
fa, fd = fa*Poly(1/fd.LC(), DE.t), fd.monic()
# interpreting limited integration problem as a
# parametric Risch DE problem
Fa = Poly(0, DE.t)
Fd = Poly(1, DE.t)
G = [(fa, fd)] + G
h, A = param_rischDE(Fa, Fd, G, DE)
V = A.nullspace()
V = [v for v in V if v[0] != 0]
if not V:
return None
else:
# we can take any vector from V, we take V[0]
c0 = V[0][0]
# v = [-1, c1, ..., cm, d1, ..., dr]
v = V[0]/(-c0)
r = len(h)
m = len(v) - r - 1
C = list(v[1: m + 1])
y = -sum([v[m + 1 + i]*h[i][0].as_expr()/h[i][1].as_expr() \
for i in range(r)])
y_num, y_den = y.as_numer_denom()
Ya, Yd = Poly(y_num, DE.t), Poly(y_den, DE.t)
Y = Ya*Poly(1/Yd.LC(), DE.t), Yd.monic()
return Y, C
def parametric_log_deriv_heu(fa, fd, wa, wd, DE, c1=None):
"""
Parametric logarithmic derivative heuristic.
Explanation
===========
Given a derivation D on k[t], f in k(t), and a hyperexponential monomial
theta over k(t), raises either NotImplementedError, in which case the
heuristic failed, or returns None, in which case it has proven that no
solution exists, or returns a solution (n, m, v) of the equation
n*f == Dv/v + m*Dtheta/theta, with v in k(t)* and n, m in ZZ with n != 0.
If this heuristic fails, the structure theorem approach will need to be
used.
The argument w == Dtheta/theta
"""
# TODO: finish writing this and write tests
c1 = c1 or Dummy('c1')
p, a = fa.div(fd)
q, b = wa.div(wd)
B = max(0, derivation(DE.t, DE).degree(DE.t) - 1)
C = max(p.degree(DE.t), q.degree(DE.t))
if q.degree(DE.t) > B:
eqs = [p.nth(i) - c1*q.nth(i) for i in range(B + 1, C + 1)]
s = solve(eqs, c1)
if not s or not s[c1].is_Rational:
# deg(q) > B, no solution for c.
return None
M, N = s[c1].as_numer_denom()
M_poly = M.as_poly(q.gens)
N_poly = N.as_poly(q.gens)
nfmwa = N_poly*fa*wd - M_poly*wa*fd
nfmwd = fd*wd
Qv = is_log_deriv_k_t_radical_in_field(nfmwa, nfmwd, DE, 'auto')
if Qv is None:
# (N*f - M*w) is not the logarithmic derivative of a k(t)-radical.
return None
Q, v = Qv
if Q.is_zero or v.is_zero:
return None
return (Q*N, Q*M, v)
if p.degree(DE.t) > B:
return None
c = lcm(fd.as_poly(DE.t).LC(), wd.as_poly(DE.t).LC())
l = fd.monic().lcm(wd.monic())*Poly(c, DE.t)
ln, ls = splitfactor(l, DE)
z = ls*ln.gcd(ln.diff(DE.t))
if not z.has(DE.t):
# TODO: We treat this as 'no solution', until the structure
# theorem version of parametric_log_deriv is implemented.
return None
u1, r1 = (fa*l.quo(fd)).div(z) # (l*f).div(z)
u2, r2 = (wa*l.quo(wd)).div(z) # (l*w).div(z)
eqs = [r1.nth(i) - c1*r2.nth(i) for i in range(z.degree(DE.t))]
s = solve(eqs, c1)
if not s or not s[c1].is_Rational:
# deg(q) <= B, no solution for c.
return None
M, N = s[c1].as_numer_denom()
nfmwa = N.as_poly(DE.t)*fa*wd - M.as_poly(DE.t)*wa*fd
nfmwd = fd*wd
Qv = is_log_deriv_k_t_radical_in_field(nfmwa, nfmwd, DE)
if Qv is None:
# (N*f - M*w) is not the logarithmic derivative of a k(t)-radical.
return None
Q, v = Qv
if Q.is_zero or v.is_zero:
return None
return (Q*N, Q*M, v)
def parametric_log_deriv(fa, fd, wa, wd, DE):
# TODO: Write the full algorithm using the structure theorems.
# try:
A = parametric_log_deriv_heu(fa, fd, wa, wd, DE)
# except NotImplementedError:
# Heuristic failed, we have to use the full method.
# TODO: This could be implemented more efficiently.
# It isn't too worrisome, because the heuristic handles most difficult
# cases.
return A
def is_deriv_k(fa, fd, DE):
r"""
Checks if Df/f is the derivative of an element of k(t).
Explanation
===========
a in k(t) is the derivative of an element of k(t) if there exists b in k(t)
such that a = Db. Either returns (ans, u), such that Df/f == Du, or None,
which means that Df/f is not the derivative of an element of k(t). ans is
a list of tuples such that Add(*[i*j for i, j in ans]) == u. This is useful
for seeing exactly which elements of k(t) produce u.
This function uses the structure theorem approach, which says that for any
f in K, Df/f is the derivative of a element of K if and only if there are ri
in QQ such that::
--- --- Dt
\ r * Dt + \ r * i Df
/ i i / i --- = --.
--- --- t f
i in L i in E i
K/C(x) K/C(x)
Where C = Const(K), L_K/C(x) = { i in {1, ..., n} such that t_i is
transcendental over C(x)(t_1, ..., t_i-1) and Dt_i = Da_i/a_i, for some a_i
in C(x)(t_1, ..., t_i-1)* } (i.e., the set of all indices of logarithmic
monomials of K over C(x)), and E_K/C(x) = { i in {1, ..., n} such that t_i
is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i/t_i = Da_i, for some
a_i in C(x)(t_1, ..., t_i-1) } (i.e., the set of all indices of
hyperexponential monomials of K over C(x)). If K is an elementary extension
over C(x), then the cardinality of L_K/C(x) U E_K/C(x) is exactly the
transcendence degree of K over C(x). Furthermore, because Const_D(K) ==
Const_D(C(x)) == C, deg(Dt_i) == 1 when t_i is in E_K/C(x) and
deg(Dt_i) == 0 when t_i is in L_K/C(x), implying in particular that E_K/C(x)
and L_K/C(x) are disjoint.
The sets L_K/C(x) and E_K/C(x) must, by their nature, be computed
recursively using this same function. Therefore, it is required to pass
them as indices to D (or T). E_args are the arguments of the
hyperexponentials indexed by E_K (i.e., if i is in E_K, then T[i] ==
exp(E_args[i])). This is needed to compute the final answer u such that
Df/f == Du.
log(f) will be the same as u up to a additive constant. This is because
they will both behave the same as monomials. For example, both log(x) and
log(2*x) == log(x) + log(2) satisfy Dt == 1/x, because log(2) is constant.
Therefore, the term const is returned. const is such that
log(const) + f == u. This is calculated by dividing the arguments of one
logarithm from the other. Therefore, it is necessary to pass the arguments
of the logarithmic terms in L_args.
To handle the case where we are given Df/f, not f, use is_deriv_k_in_field().
See also
========
is_log_deriv_k_t_radical_in_field, is_log_deriv_k_t_radical
"""
# Compute Df/f
dfa, dfd = (fd*derivation(fa, DE) - fa*derivation(fd, DE)), fd*fa
dfa, dfd = dfa.cancel(dfd, include=True)
# Our assumption here is that each monomial is recursively transcendental
if len(DE.exts) != len(DE.D):
if [i for i in DE.cases if i == 'tan'] or \
({i for i in DE.cases if i == 'primitive'} -
set(DE.indices('log'))):
raise NotImplementedError("Real version of the structure "
"theorems with hypertangent support is not yet implemented.")
# TODO: What should really be done in this case?
raise NotImplementedError("Nonelementary extensions not supported "
"in the structure theorems.")
E_part = [DE.D[i].quo(Poly(DE.T[i], DE.T[i])).as_expr() for i in DE.indices('exp')]
L_part = [DE.D[i].as_expr() for i in DE.indices('log')]
# The expression dfa/dfd might not be polynomial in any of its symbols so we
# use a Dummy as the generator for PolyMatrix.
dum = Dummy()
lhs = Matrix([E_part + L_part], dum)
rhs = Matrix([dfa.as_expr()/dfd.as_expr()], dum)
A, u = constant_system(lhs, rhs, DE)
u = u.to_Matrix() # Poly to Expr
if not all(derivation(i, DE, basic=True).is_zero for i in u) or not A:
# If the elements of u are not all constant
# Note: See comment in constant_system
# Also note: derivation(basic=True) calls cancel()
return None
else:
if not all(i.is_Rational for i in u):
raise NotImplementedError("Cannot work with non-rational "
"coefficients in this case.")
else:
terms = ([DE.extargs[i] for i in DE.indices('exp')] +
[DE.T[i] for i in DE.indices('log')])
ans = list(zip(terms, u))
result = Add(*[Mul(i, j) for i, j in ans])
argterms = ([DE.T[i] for i in DE.indices('exp')] +
[DE.extargs[i] for i in DE.indices('log')])
l = []
ld = []
for i, j in zip(argterms, u):
# We need to get around things like sqrt(x**2) != x
# and also sqrt(x**2 + 2*x + 1) != x + 1
# Issue 10798: i need not be a polynomial
i, d = i.as_numer_denom()
icoeff, iterms = sqf_list(i)
l.append(Mul(*([Pow(icoeff, j)] + [Pow(b, e*j) for b, e in iterms])))
dcoeff, dterms = sqf_list(d)
ld.append(Mul(*([Pow(dcoeff, j)] + [Pow(b, e*j) for b, e in dterms])))
const = cancel(fa.as_expr()/fd.as_expr()/Mul(*l)*Mul(*ld))
return (ans, result, const)
def is_log_deriv_k_t_radical(fa, fd, DE, Df=True):
r"""
Checks if Df is the logarithmic derivative of a k(t)-radical.
Explanation
===========
b in k(t) can be written as the logarithmic derivative of a k(t) radical if
there exist n in ZZ and u in k(t) with n, u != 0 such that n*b == Du/u.
Either returns (ans, u, n, const) or None, which means that Df cannot be
written as the logarithmic derivative of a k(t)-radical. ans is a list of
tuples such that Mul(*[i**j for i, j in ans]) == u. This is useful for
seeing exactly what elements of k(t) produce u.
This function uses the structure theorem approach, which says that for any
f in K, Df is the logarithmic derivative of a K-radical if and only if there
are ri in QQ such that::
--- --- Dt
\ r * Dt + \ r * i
/ i i / i --- = Df.
--- --- t
i in L i in E i
K/C(x) K/C(x)
Where C = Const(K), L_K/C(x) = { i in {1, ..., n} such that t_i is
transcendental over C(x)(t_1, ..., t_i-1) and Dt_i = Da_i/a_i, for some a_i
in C(x)(t_1, ..., t_i-1)* } (i.e., the set of all indices of logarithmic
monomials of K over C(x)), and E_K/C(x) = { i in {1, ..., n} such that t_i
is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i/t_i = Da_i, for some
a_i in C(x)(t_1, ..., t_i-1) } (i.e., the set of all indices of
hyperexponential monomials of K over C(x)). If K is an elementary extension
over C(x), then the cardinality of L_K/C(x) U E_K/C(x) is exactly the
transcendence degree of K over C(x). Furthermore, because Const_D(K) ==
Const_D(C(x)) == C, deg(Dt_i) == 1 when t_i is in E_K/C(x) and
deg(Dt_i) == 0 when t_i is in L_K/C(x), implying in particular that E_K/C(x)
and L_K/C(x) are disjoint.
The sets L_K/C(x) and E_K/C(x) must, by their nature, be computed
recursively using this same function. Therefore, it is required to pass
them as indices to D (or T). L_args are the arguments of the logarithms
indexed by L_K (i.e., if i is in L_K, then T[i] == log(L_args[i])). This is
needed to compute the final answer u such that n*f == Du/u.
exp(f) will be the same as u up to a multiplicative constant. This is
because they will both behave the same as monomials. For example, both
exp(x) and exp(x + 1) == E*exp(x) satisfy Dt == t. Therefore, the term const
is returned. const is such that exp(const)*f == u. This is calculated by
subtracting the arguments of one exponential from the other. Therefore, it
is necessary to pass the arguments of the exponential terms in E_args.
To handle the case where we are given Df, not f, use
is_log_deriv_k_t_radical_in_field().
See also
========
is_log_deriv_k_t_radical_in_field, is_deriv_k
"""
if Df:
dfa, dfd = (fd*derivation(fa, DE) - fa*derivation(fd, DE)).cancel(fd**2,
include=True)
else:
dfa, dfd = fa, fd
# Our assumption here is that each monomial is recursively transcendental
if len(DE.exts) != len(DE.D):
if [i for i in DE.cases if i == 'tan'] or \
({i for i in DE.cases if i == 'primitive'} -
set(DE.indices('log'))):
raise NotImplementedError("Real version of the structure "
"theorems with hypertangent support is not yet implemented.")
# TODO: What should really be done in this case?
raise NotImplementedError("Nonelementary extensions not supported "
"in the structure theorems.")
E_part = [DE.D[i].quo(Poly(DE.T[i], DE.T[i])).as_expr() for i in DE.indices('exp')]
L_part = [DE.D[i].as_expr() for i in DE.indices('log')]
# The expression dfa/dfd might not be polynomial in any of its symbols so we
# use a Dummy as the generator for PolyMatrix.
dum = Dummy()
lhs = Matrix([E_part + L_part], dum)
rhs = Matrix([dfa.as_expr()/dfd.as_expr()], dum)
A, u = constant_system(lhs, rhs, DE)
u = u.to_Matrix() # Poly to Expr
if not all(derivation(i, DE, basic=True).is_zero for i in u) or not A:
# If the elements of u are not all constant
# Note: See comment in constant_system
# Also note: derivation(basic=True) calls cancel()
return None
else:
if not all(i.is_Rational for i in u):
# TODO: But maybe we can tell if they're not rational, like
# log(2)/log(3). Also, there should be an option to continue
# anyway, even if the result might potentially be wrong.
raise NotImplementedError("Cannot work with non-rational "
"coefficients in this case.")
else:
n = reduce(ilcm, [i.as_numer_denom()[1] for i in u])
u *= n
terms = ([DE.T[i] for i in DE.indices('exp')] +
[DE.extargs[i] for i in DE.indices('log')])
ans = list(zip(terms, u))
result = Mul(*[Pow(i, j) for i, j in ans])
# exp(f) will be the same as result up to a multiplicative
# constant. We now find the log of that constant.
argterms = ([DE.extargs[i] for i in DE.indices('exp')] +
[DE.T[i] for i in DE.indices('log')])
const = cancel(fa.as_expr()/fd.as_expr() -
Add(*[Mul(i, j/n) for i, j in zip(argterms, u)]))
return (ans, result, n, const)
def is_log_deriv_k_t_radical_in_field(fa, fd, DE, case='auto', z=None):
"""
Checks if f can be written as the logarithmic derivative of a k(t)-radical.
Explanation
===========
It differs from is_log_deriv_k_t_radical(fa, fd, DE, Df=False)
for any given fa, fd, DE in that it finds the solution in the
given field not in some (possibly unspecified extension) and
"in_field" with the function name is used to indicate that.
f in k(t) can be written as the logarithmic derivative of a k(t) radical if
there exist n in ZZ and u in k(t) with n, u != 0 such that n*f == Du/u.
Either returns (n, u) or None, which means that f cannot be written as the
logarithmic derivative of a k(t)-radical.
case is one of {'primitive', 'exp', 'tan', 'auto'} for the primitive,
hyperexponential, and hypertangent cases, respectively. If case is 'auto',
it will attempt to determine the type of the derivation automatically.
See also
========
is_log_deriv_k_t_radical, is_deriv_k
"""
fa, fd = fa.cancel(fd, include=True)
# f must be simple
n, s = splitfactor(fd, DE)
if not s.is_one:
pass
z = z or Dummy('z')
H, b = residue_reduce(fa, fd, DE, z=z)
if not b:
# I will have to verify, but I believe that the answer should be
# None in this case. This should never happen for the
# functions given when solving the parametric logarithmic
# derivative problem when integration elementary functions (see
# Bronstein's book, page 255), so most likely this indicates a bug.
return None
roots = [(i, i.real_roots()) for i, _ in H]
if not all(len(j) == i.degree() and all(k.is_Rational for k in j) for
i, j in roots):
# If f is the logarithmic derivative of a k(t)-radical, then all the
# roots of the resultant must be rational numbers.
return None
# [(a, i), ...], where i*log(a) is a term in the log-part of the integral
# of f
respolys, residues = list(zip(*roots)) or [[], []]
# Note: this might be empty, but everything below should work find in that
# case (it should be the same as if it were [[1, 1]])
residueterms = [(H[j][1].subs(z, i), i) for j in range(len(H)) for
i in residues[j]]
# TODO: finish writing this and write tests
p = cancel(fa.as_expr()/fd.as_expr() - residue_reduce_derivation(H, DE, z))
p = p.as_poly(DE.t)
if p is None:
# f - Dg will be in k[t] if f is the logarithmic derivative of a k(t)-radical
return None
if p.degree(DE.t) >= max(1, DE.d.degree(DE.t)):
return None
if case == 'auto':
case = DE.case
if case == 'exp':
wa, wd = derivation(DE.t, DE).cancel(Poly(DE.t, DE.t), include=True)
with DecrementLevel(DE):
pa, pd = frac_in(p, DE.t, cancel=True)
wa, wd = frac_in((wa, wd), DE.t)
A = parametric_log_deriv(pa, pd, wa, wd, DE)
if A is None:
return None
n, e, u = A
u *= DE.t**e
elif case == 'primitive':
with DecrementLevel(DE):
pa, pd = frac_in(p, DE.t)
A = is_log_deriv_k_t_radical_in_field(pa, pd, DE, case='auto')
if A is None:
return None
n, u = A
elif case == 'base':
# TODO: we can use more efficient residue reduction from ratint()
if not fd.is_sqf or fa.degree() >= fd.degree():
# f is the logarithmic derivative in the base case if and only if
# f = fa/fd, fd is square-free, deg(fa) < deg(fd), and
# gcd(fa, fd) == 1. The last condition is handled by cancel() above.
return None
# Note: if residueterms = [], returns (1, 1)
# f had better be 0 in that case.
n = reduce(ilcm, [i.as_numer_denom()[1] for _, i in residueterms], S.One)
u = Mul(*[Pow(i, j*n) for i, j in residueterms])
return (n, u)
elif case == 'tan':
raise NotImplementedError("The hypertangent case is "
"not yet implemented for is_log_deriv_k_t_radical_in_field()")
elif case in ['other_linear', 'other_nonlinear']:
# XXX: If these are supported by the structure theorems, change to NotImplementedError.
raise ValueError("The %s case is not supported in this function." % case)
else:
raise ValueError("case must be one of {'primitive', 'exp', 'tan', "
"'base', 'auto'}, not %s" % case)
common_denom = reduce(ilcm, [i.as_numer_denom()[1] for i in [j for _, j in
residueterms]] + [n], S.One)
residueterms = [(i, j*common_denom) for i, j in residueterms]
m = common_denom//n
if common_denom != n*m: # Verify exact division
raise ValueError("Inexact division")
u = cancel(u**m*Mul(*[Pow(i, j) for i, j in residueterms]))
return (common_denom, u)
|
02690574f4a0d15e36fa0d842df1200c458c11118fa82f25c66a89de86c4a52b | """
Integrate functions by rewriting them as Meijer G-functions.
There are three user-visible functions that can be used by other parts of the
sympy library to solve various integration problems:
- meijerint_indefinite
- meijerint_definite
- meijerint_inversion
They can be used to compute, respectively, indefinite integrals, definite
integrals over intervals of the real line, and inverse laplace-type integrals
(from c-I*oo to c+I*oo). See the respective docstrings for details.
The main references for this are:
[L] Luke, Y. L. (1969), The Special Functions and Their Approximations,
Volume 1
[R] Kelly B. Roach. Meijer G Function Representations.
In: Proceedings of the 1997 International Symposium on Symbolic and
Algebraic Computation, pages 205-211, New York, 1997. ACM.
[P] A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990).
Integrals and Series: More Special Functions, Vol. 3,.
Gordon and Breach Science Publisher
"""
from typing import Dict, Tuple
from sympy.core import oo, S, pi, Expr
from sympy.core.exprtools import factor_terms
from sympy.core.function import expand, expand_mul, expand_power_base
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.numbers import Rational
from sympy.core.cache import cacheit
from sympy.core.symbol import Dummy, Wild
from sympy.simplify import hyperexpand, powdenest, collect
from sympy.simplify.fu import sincos_to_sum
from sympy.logic.boolalg import And, Or, BooleanAtom
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
from sympy.functions.elementary.hyperbolic import \
_rewrite_hyperbolics_as_exp, HyperbolicFunction
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.functions.special.hyper import meijerg
from sympy.utilities.iterables import multiset_partitions, ordered
from sympy.utilities.misc import debug as _debug
from sympy.utilities import default_sort_key
# keep this at top for easy reference
z = Dummy('z')
def _has(res, *f):
# return True if res has f; in the case of Piecewise
# only return True if *all* pieces have f
res = piecewise_fold(res)
if getattr(res, 'is_Piecewise', False):
return all(_has(i, *f) for i in res.args)
return res.has(*f)
def _create_lookup_table(table):
""" Add formulae for the function -> meijerg lookup table. """
def wild(n):
return Wild(n, exclude=[z])
p, q, a, b, c = list(map(wild, 'pqabc'))
n = Wild('n', properties=[lambda x: x.is_Integer and x > 0])
t = p*z**q
def add(formula, an, ap, bm, bq, arg=t, fac=S.One, cond=True, hint=True):
table.setdefault(_mytype(formula, z), []).append((formula,
[(fac, meijerg(an, ap, bm, bq, arg))], cond, hint))
def addi(formula, inst, cond, hint=True):
table.setdefault(
_mytype(formula, z), []).append((formula, inst, cond, hint))
def constant(a):
return [(a, meijerg([1], [], [], [0], z)),
(a, meijerg([], [1], [0], [], z))]
table[()] = [(a, constant(a), True, True)]
# [P], Section 8.
from sympy import unpolarify, Function, Not
class IsNonPositiveInteger(Function):
@classmethod
def eval(cls, arg):
arg = unpolarify(arg)
if arg.is_Integer is True:
return arg <= 0
# Section 8.4.2
from sympy import (gamma, pi, cos, exp, re, sin, sinc, sqrt, sinh, cosh,
factorial, log, erf, erfc, erfi, polar_lift)
# TODO this needs more polar_lift (c/f entry for exp)
add(Heaviside(t - b)*(t - b)**(a - 1), [a], [], [], [0], t/b,
gamma(a)*b**(a - 1), And(b > 0))
add(Heaviside(b - t)*(b - t)**(a - 1), [], [a], [0], [], t/b,
gamma(a)*b**(a - 1), And(b > 0))
add(Heaviside(z - (b/p)**(1/q))*(t - b)**(a - 1), [a], [], [], [0], t/b,
gamma(a)*b**(a - 1), And(b > 0))
add(Heaviside((b/p)**(1/q) - z)*(b - t)**(a - 1), [], [a], [0], [], t/b,
gamma(a)*b**(a - 1), And(b > 0))
add((b + t)**(-a), [1 - a], [], [0], [], t/b, b**(-a)/gamma(a),
hint=Not(IsNonPositiveInteger(a)))
add(abs(b - t)**(-a), [1 - a], [(1 - a)/2], [0], [(1 - a)/2], t/b,
2*sin(pi*a/2)*gamma(1 - a)*abs(b)**(-a), re(a) < 1)
add((t**a - b**a)/(t - b), [0, a], [], [0, a], [], t/b,
b**(a - 1)*sin(a*pi)/pi)
# 12
def A1(r, sign, nu):
return pi**Rational(-1, 2)*(-sign*nu/2)**(1 - 2*r)
def tmpadd(r, sgn):
# XXX the a**2 is bad for matching
add((sqrt(a**2 + t) + sgn*a)**b/(a**2 + t)**r,
[(1 + b)/2, 1 - 2*r + b/2], [],
[(b - sgn*b)/2], [(b + sgn*b)/2], t/a**2,
a**(b - 2*r)*A1(r, sgn, b))
tmpadd(0, 1)
tmpadd(0, -1)
tmpadd(S.Half, 1)
tmpadd(S.Half, -1)
# 13
def tmpadd(r, sgn):
add((sqrt(a + p*z**q) + sgn*sqrt(p)*z**(q/2))**b/(a + p*z**q)**r,
[1 - r + sgn*b/2], [1 - r - sgn*b/2], [0, S.Half], [],
p*z**q/a, a**(b/2 - r)*A1(r, sgn, b))
tmpadd(0, 1)
tmpadd(0, -1)
tmpadd(S.Half, 1)
tmpadd(S.Half, -1)
# (those after look obscure)
# Section 8.4.3
add(exp(polar_lift(-1)*t), [], [], [0], [])
# TODO can do sin^n, sinh^n by expansion ... where?
# 8.4.4 (hyperbolic functions)
add(sinh(t), [], [1], [S.Half], [1, 0], t**2/4, pi**Rational(3, 2))
add(cosh(t), [], [S.Half], [0], [S.Half, S.Half], t**2/4, pi**Rational(3, 2))
# Section 8.4.5
# TODO can do t + a. but can also do by expansion... (XXX not really)
add(sin(t), [], [], [S.Half], [0], t**2/4, sqrt(pi))
add(cos(t), [], [], [0], [S.Half], t**2/4, sqrt(pi))
# Section 8.4.6 (sinc function)
add(sinc(t), [], [], [0], [Rational(-1, 2)], t**2/4, sqrt(pi)/2)
# Section 8.5.5
def make_log1(subs):
N = subs[n]
return [((-1)**N*factorial(N),
meijerg([], [1]*(N + 1), [0]*(N + 1), [], t))]
def make_log2(subs):
N = subs[n]
return [(factorial(N),
meijerg([1]*(N + 1), [], [], [0]*(N + 1), t))]
# TODO these only hold for positive p, and can be made more general
# but who uses log(x)*Heaviside(a-x) anyway ...
# TODO also it would be nice to derive them recursively ...
addi(log(t)**n*Heaviside(1 - t), make_log1, True)
addi(log(t)**n*Heaviside(t - 1), make_log2, True)
def make_log3(subs):
return make_log1(subs) + make_log2(subs)
addi(log(t)**n, make_log3, True)
addi(log(t + a),
constant(log(a)) + [(S.One, meijerg([1, 1], [], [1], [0], t/a))],
True)
addi(log(abs(t - a)), constant(log(abs(a))) +
[(pi, meijerg([1, 1], [S.Half], [1], [0, S.Half], t/a))],
True)
# TODO log(x)/(x+a) and log(x)/(x-1) can also be done. should they
# be derivable?
# TODO further formulae in this section seem obscure
# Sections 8.4.9-10
# TODO
# Section 8.4.11
from sympy import Ei, I, expint, Si, Ci, Shi, Chi, fresnels, fresnelc
addi(Ei(t),
constant(-I*pi) + [(S.NegativeOne, meijerg([], [1], [0, 0], [],
t*polar_lift(-1)))],
True)
# Section 8.4.12
add(Si(t), [1], [], [S.Half], [0, 0], t**2/4, sqrt(pi)/2)
add(Ci(t), [], [1], [0, 0], [S.Half], t**2/4, -sqrt(pi)/2)
# Section 8.4.13
add(Shi(t), [S.Half], [], [0], [Rational(-1, 2), Rational(-1, 2)], polar_lift(-1)*t**2/4,
t*sqrt(pi)/4)
add(Chi(t), [], [S.Half, 1], [0, 0], [S.Half, S.Half], t**2/4, -
pi**S('3/2')/2)
# generalized exponential integral
add(expint(a, t), [], [a], [a - 1, 0], [], t)
# Section 8.4.14
add(erf(t), [1], [], [S.Half], [0], t**2, 1/sqrt(pi))
# TODO exp(-x)*erf(I*x) does not work
add(erfc(t), [], [1], [0, S.Half], [], t**2, 1/sqrt(pi))
# This formula for erfi(z) yields a wrong(?) minus sign
#add(erfi(t), [1], [], [S.Half], [0], -t**2, I/sqrt(pi))
add(erfi(t), [S.Half], [], [0], [Rational(-1, 2)], -t**2, t/sqrt(pi))
# Fresnel Integrals
add(fresnels(t), [1], [], [Rational(3, 4)], [0, Rational(1, 4)], pi**2*t**4/16, S.Half)
add(fresnelc(t), [1], [], [Rational(1, 4)], [0, Rational(3, 4)], pi**2*t**4/16, S.Half)
##### bessel-type functions #####
from sympy import besselj, bessely, besseli, besselk
# Section 8.4.19
add(besselj(a, t), [], [], [a/2], [-a/2], t**2/4)
# all of the following are derivable
#add(sin(t)*besselj(a, t), [Rational(1, 4), Rational(3, 4)], [], [(1+a)/2],
# [-a/2, a/2, (1-a)/2], t**2, 1/sqrt(2))
#add(cos(t)*besselj(a, t), [Rational(1, 4), Rational(3, 4)], [], [a/2],
# [-a/2, (1+a)/2, (1-a)/2], t**2, 1/sqrt(2))
#add(besselj(a, t)**2, [S.Half], [], [a], [-a, 0], t**2, 1/sqrt(pi))
#add(besselj(a, t)*besselj(b, t), [0, S.Half], [], [(a + b)/2],
# [-(a+b)/2, (a - b)/2, (b - a)/2], t**2, 1/sqrt(pi))
# Section 8.4.20
add(bessely(a, t), [], [-(a + 1)/2], [a/2, -a/2], [-(a + 1)/2], t**2/4)
# TODO all of the following should be derivable
#add(sin(t)*bessely(a, t), [Rational(1, 4), Rational(3, 4)], [(1 - a - 1)/2],
# [(1 + a)/2, (1 - a)/2], [(1 - a - 1)/2, (1 - 1 - a)/2, (1 - 1 + a)/2],
# t**2, 1/sqrt(2))
#add(cos(t)*bessely(a, t), [Rational(1, 4), Rational(3, 4)], [(0 - a - 1)/2],
# [(0 + a)/2, (0 - a)/2], [(0 - a - 1)/2, (1 - 0 - a)/2, (1 - 0 + a)/2],
# t**2, 1/sqrt(2))
#add(besselj(a, t)*bessely(b, t), [0, S.Half], [(a - b - 1)/2],
# [(a + b)/2, (a - b)/2], [(a - b - 1)/2, -(a + b)/2, (b - a)/2],
# t**2, 1/sqrt(pi))
#addi(bessely(a, t)**2,
# [(2/sqrt(pi), meijerg([], [S.Half, S.Half - a], [0, a, -a],
# [S.Half - a], t**2)),
# (1/sqrt(pi), meijerg([S.Half], [], [a], [-a, 0], t**2))],
# True)
#addi(bessely(a, t)*bessely(b, t),
# [(2/sqrt(pi), meijerg([], [0, S.Half, (1 - a - b)/2],
# [(a + b)/2, (a - b)/2, (b - a)/2, -(a + b)/2],
# [(1 - a - b)/2], t**2)),
# (1/sqrt(pi), meijerg([0, S.Half], [], [(a + b)/2],
# [-(a + b)/2, (a - b)/2, (b - a)/2], t**2))],
# True)
# Section 8.4.21 ?
# Section 8.4.22
add(besseli(a, t), [], [(1 + a)/2], [a/2], [-a/2, (1 + a)/2], t**2/4, pi)
# TODO many more formulas. should all be derivable
# Section 8.4.23
add(besselk(a, t), [], [], [a/2, -a/2], [], t**2/4, S.Half)
# TODO many more formulas. should all be derivable
# Complete elliptic integrals K(z) and E(z)
from sympy import elliptic_k, elliptic_e
add(elliptic_k(t), [S.Half, S.Half], [], [0], [0], -t, S.Half)
add(elliptic_e(t), [S.Half, 3*S.Half], [], [0], [0], -t, Rational(-1, 2)/2)
####################################################################
# First some helper functions.
####################################################################
from sympy.utilities.timeutils import timethis
timeit = timethis('meijerg')
def _mytype(f, x):
""" Create a hashable entity describing the type of f. """
if x not in f.free_symbols:
return ()
elif f.is_Function:
return (type(f),)
else:
types = [_mytype(a, x) for a in f.args]
res = []
for t in types:
res += list(t)
res.sort()
return tuple(res)
class _CoeffExpValueError(ValueError):
"""
Exception raised by _get_coeff_exp, for internal use only.
"""
pass
def _get_coeff_exp(expr, x):
"""
When expr is known to be of the form c*x**b, with c and/or b possibly 1,
return c, b.
Examples
========
>>> from sympy.abc import x, a, b
>>> from sympy.integrals.meijerint import _get_coeff_exp
>>> _get_coeff_exp(a*x**b, x)
(a, b)
>>> _get_coeff_exp(x, x)
(1, 1)
>>> _get_coeff_exp(2*x, x)
(2, 1)
>>> _get_coeff_exp(x**3, x)
(1, 3)
"""
from sympy import powsimp
(c, m) = expand_power_base(powsimp(expr)).as_coeff_mul(x)
if not m:
return c, S.Zero
[m] = m
if m.is_Pow:
if m.base != x:
raise _CoeffExpValueError('expr not of form a*x**b')
return c, m.exp
elif m == x:
return c, S.One
else:
raise _CoeffExpValueError('expr not of form a*x**b: %s' % expr)
def _exponents(expr, x):
"""
Find the exponents of ``x`` (not including zero) in ``expr``.
Examples
========
>>> from sympy.integrals.meijerint import _exponents
>>> from sympy.abc import x, y
>>> from sympy import sin
>>> _exponents(x, x)
{1}
>>> _exponents(x**2, x)
{2}
>>> _exponents(x**2 + x, x)
{1, 2}
>>> _exponents(x**3*sin(x + x**y) + 1/x, x)
{-1, 1, 3, y}
"""
def _exponents_(expr, x, res):
if expr == x:
res.update([1])
return
if expr.is_Pow and expr.base == x:
res.update([expr.exp])
return
for arg in expr.args:
_exponents_(arg, x, res)
res = set()
_exponents_(expr, x, res)
return res
def _functions(expr, x):
""" Find the types of functions in expr, to estimate the complexity. """
from sympy import Function
return {e.func for e in expr.atoms(Function) if x in e.free_symbols}
def _find_splitting_points(expr, x):
"""
Find numbers a such that a linear substitution x -> x + a would
(hopefully) simplify expr.
Examples
========
>>> from sympy.integrals.meijerint import _find_splitting_points as fsp
>>> from sympy import sin
>>> from sympy.abc import x
>>> fsp(x, x)
{0}
>>> fsp((x-1)**3, x)
{1}
>>> fsp(sin(x+3)*x, x)
{-3, 0}
"""
p, q = [Wild(n, exclude=[x]) for n in 'pq']
def compute_innermost(expr, res):
if not isinstance(expr, Expr):
return
m = expr.match(p*x + q)
if m and m[p] != 0:
res.add(-m[q]/m[p])
return
if expr.is_Atom:
return
for arg in expr.args:
compute_innermost(arg, res)
innermost = set()
compute_innermost(expr, innermost)
return innermost
def _split_mul(f, x):
"""
Split expression ``f`` into fac, po, g, where fac is a constant factor,
po = x**s for some s independent of s, and g is "the rest".
Examples
========
>>> from sympy.integrals.meijerint import _split_mul
>>> from sympy import sin
>>> from sympy.abc import s, x
>>> _split_mul((3*x)**s*sin(x**2)*x, x)
(3**s, x*x**s, sin(x**2))
"""
from sympy import polarify, unpolarify
fac = S.One
po = S.One
g = S.One
f = expand_power_base(f)
args = Mul.make_args(f)
for a in args:
if a == x:
po *= x
elif x not in a.free_symbols:
fac *= a
else:
if a.is_Pow and x not in a.exp.free_symbols:
c, t = a.base.as_coeff_mul(x)
if t != (x,):
c, t = expand_mul(a.base).as_coeff_mul(x)
if t == (x,):
po *= x**a.exp
fac *= unpolarify(polarify(c**a.exp, subs=False))
continue
g *= a
return fac, po, g
def _mul_args(f):
"""
Return a list ``L`` such that ``Mul(*L) == f``.
If ``f`` is not a ``Mul`` or ``Pow``, ``L=[f]``.
If ``f=g**n`` for an integer ``n``, ``L=[g]*n``.
If ``f`` is a ``Mul``, ``L`` comes from applying ``_mul_args`` to all factors of ``f``.
"""
args = Mul.make_args(f)
gs = []
for g in args:
if g.is_Pow and g.exp.is_Integer:
n = g.exp
base = g.base
if n < 0:
n = -n
base = 1/base
gs += [base]*n
else:
gs.append(g)
return gs
def _mul_as_two_parts(f):
"""
Find all the ways to split ``f`` into a product of two terms.
Return None on failure.
Explanation
===========
Although the order is canonical from multiset_partitions, this is
not necessarily the best order to process the terms. For example,
if the case of len(gs) == 2 is removed and multiset is allowed to
sort the terms, some tests fail.
Examples
========
>>> from sympy.integrals.meijerint import _mul_as_two_parts
>>> from sympy import sin, exp, ordered
>>> from sympy.abc import x
>>> list(ordered(_mul_as_two_parts(x*sin(x)*exp(x))))
[(x, exp(x)*sin(x)), (x*exp(x), sin(x)), (x*sin(x), exp(x))]
"""
gs = _mul_args(f)
if len(gs) < 2:
return None
if len(gs) == 2:
return [tuple(gs)]
return [(Mul(*x), Mul(*y)) for (x, y) in multiset_partitions(gs, 2)]
def _inflate_g(g, n):
""" Return C, h such that h is a G function of argument z**n and
g = C*h. """
# TODO should this be a method of meijerg?
# See: [L, page 150, equation (5)]
def inflate(params, n):
""" (a1, .., ak) -> (a1/n, (a1+1)/n, ..., (ak + n-1)/n) """
res = []
for a in params:
for i in range(n):
res.append((a + i)/n)
return res
v = S(len(g.ap) - len(g.bq))
C = n**(1 + g.nu + v/2)
C /= (2*pi)**((n - 1)*g.delta)
return C, meijerg(inflate(g.an, n), inflate(g.aother, n),
inflate(g.bm, n), inflate(g.bother, n),
g.argument**n * n**(n*v))
def _flip_g(g):
""" Turn the G function into one of inverse argument
(i.e. G(1/x) -> G'(x)) """
# See [L], section 5.2
def tr(l):
return [1 - a for a in l]
return meijerg(tr(g.bm), tr(g.bother), tr(g.an), tr(g.aother), 1/g.argument)
def _inflate_fox_h(g, a):
r"""
Let d denote the integrand in the definition of the G function ``g``.
Consider the function H which is defined in the same way, but with
integrand d/Gamma(a*s) (contour conventions as usual).
If ``a`` is rational, the function H can be written as C*G, for a constant C
and a G-function G.
This function returns C, G.
"""
if a < 0:
return _inflate_fox_h(_flip_g(g), -a)
p = S(a.p)
q = S(a.q)
# We use the substitution s->qs, i.e. inflate g by q. We are left with an
# extra factor of Gamma(p*s), for which we use Gauss' multiplication
# theorem.
D, g = _inflate_g(g, q)
z = g.argument
D /= (2*pi)**((1 - p)/2)*p**Rational(-1, 2)
z /= p**p
bs = [(n + 1)/p for n in range(p)]
return D, meijerg(g.an, g.aother, g.bm, list(g.bother) + bs, z)
_dummies = {} # type: Dict[Tuple[str, str], Dummy]
def _dummy(name, token, expr, **kwargs):
"""
Return a dummy. This will return the same dummy if the same token+name is
requested more than once, and it is not already in expr.
This is for being cache-friendly.
"""
d = _dummy_(name, token, **kwargs)
if d in expr.free_symbols:
return Dummy(name, **kwargs)
return d
def _dummy_(name, token, **kwargs):
"""
Return a dummy associated to name and token. Same effect as declaring
it globally.
"""
global _dummies
if not (name, token) in _dummies:
_dummies[(name, token)] = Dummy(name, **kwargs)
return _dummies[(name, token)]
def _is_analytic(f, x):
""" Check if f(x), when expressed using G functions on the positive reals,
will in fact agree with the G functions almost everywhere """
from sympy import Heaviside, Abs
return not any(x in expr.free_symbols for expr in f.atoms(Heaviside, Abs))
def _condsimp(cond):
"""
Do naive simplifications on ``cond``.
Explanation
===========
Note that this routine is completely ad-hoc, simplification rules being
added as need arises rather than following any logical pattern.
Examples
========
>>> from sympy.integrals.meijerint import _condsimp as simp
>>> from sympy import Or, Eq, And
>>> from sympy.abc import x, y, z
>>> simp(Or(x < y, z, Eq(x, y)))
z | (x <= y)
>>> simp(Or(x <= y, And(x < y, z)))
x <= y
"""
from sympy import (
symbols, Wild, Eq, unbranched_argument, exp_polar, pi, I,
arg, periodic_argument, oo, polar_lift)
from sympy.logic.boolalg import BooleanFunction
if not isinstance(cond, BooleanFunction):
return cond
cond = cond.func(*list(map(_condsimp, cond.args)))
change = True
p, q, r = symbols('p q r', cls=Wild)
rules = [
(Or(p < q, Eq(p, q)), p <= q),
# The next two obviously are instances of a general pattern, but it is
# easier to spell out the few cases we care about.
(And(abs(arg(p)) <= pi, abs(arg(p) - 2*pi) <= pi),
Eq(arg(p) - pi, 0)),
(And(abs(2*arg(p) + pi) <= pi, abs(2*arg(p) - pi) <= pi),
Eq(arg(p), 0)),
(And(abs(unbranched_argument(p)) <= pi,
abs(unbranched_argument(exp_polar(-2*pi*I)*p)) <= pi),
Eq(unbranched_argument(exp_polar(-I*pi)*p), 0)),
(And(abs(unbranched_argument(p)) <= pi/2,
abs(unbranched_argument(exp_polar(-pi*I)*p)) <= pi/2),
Eq(unbranched_argument(exp_polar(-I*pi/2)*p), 0)),
(Or(p <= q, And(p < q, r)), p <= q)
]
while change:
change = False
for fro, to in rules:
if fro.func != cond.func:
continue
for n, arg1 in enumerate(cond.args):
if r in fro.args[0].free_symbols:
m = arg1.match(fro.args[1])
num = 1
else:
num = 0
m = arg1.match(fro.args[0])
if not m:
continue
otherargs = [x.subs(m) for x in fro.args[:num] + fro.args[num + 1:]]
otherlist = [n]
for arg2 in otherargs:
for k, arg3 in enumerate(cond.args):
if k in otherlist:
continue
if arg2 == arg3:
otherlist += [k]
break
if isinstance(arg3, And) and arg2.args[1] == r and \
isinstance(arg2, And) and arg2.args[0] in arg3.args:
otherlist += [k]
break
if isinstance(arg3, And) and arg2.args[0] == r and \
isinstance(arg2, And) and arg2.args[1] in arg3.args:
otherlist += [k]
break
if len(otherlist) != len(otherargs) + 1:
continue
newargs = [arg_ for (k, arg_) in enumerate(cond.args)
if k not in otherlist] + [to.subs(m)]
cond = cond.func(*newargs)
change = True
break
# final tweak
def repl_eq(orig):
if orig.lhs == 0:
expr = orig.rhs
elif orig.rhs == 0:
expr = orig.lhs
else:
return orig
m = expr.match(arg(p)**q)
if not m:
m = expr.match(unbranched_argument(polar_lift(p)**q))
if not m:
if isinstance(expr, periodic_argument) and not expr.args[0].is_polar \
and expr.args[1] is oo:
return (expr.args[0] > 0)
return orig
return (m[p] > 0)
return cond.replace(
lambda expr: expr.is_Relational and expr.rel_op == '==',
repl_eq)
def _eval_cond(cond):
""" Re-evaluate the conditions. """
if isinstance(cond, bool):
return cond
return _condsimp(cond.doit())
####################################################################
# Now the "backbone" functions to do actual integration.
####################################################################
def _my_principal_branch(expr, period, full_pb=False):
""" Bring expr nearer to its principal branch by removing superfluous
factors.
This function does *not* guarantee to yield the principal branch,
to avoid introducing opaque principal_branch() objects,
unless full_pb=True. """
from sympy import principal_branch
res = principal_branch(expr, period)
if not full_pb:
res = res.replace(principal_branch, lambda x, y: x)
return res
def _rewrite_saxena_1(fac, po, g, x):
"""
Rewrite the integral fac*po*g dx, from zero to infinity, as
integral fac*G, where G has argument a*x. Note po=x**s.
Return fac, G.
"""
_, s = _get_coeff_exp(po, x)
a, b = _get_coeff_exp(g.argument, x)
period = g.get_period()
a = _my_principal_branch(a, period)
# We substitute t = x**b.
C = fac/(abs(b)*a**((s + 1)/b - 1))
# Absorb a factor of (at)**((1 + s)/b - 1).
def tr(l):
return [a + (1 + s)/b - 1 for a in l]
return C, meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother),
a*x)
def _check_antecedents_1(g, x, helper=False):
r"""
Return a condition under which the mellin transform of g exists.
Any power of x has already been absorbed into the G function,
so this is just $\int_0^\infty g\, dx$.
See [L, section 5.6.1]. (Note that s=1.)
If ``helper`` is True, only check if the MT exists at infinity, i.e. if
$\int_1^\infty g\, dx$ exists.
"""
# NOTE if you update these conditions, please update the documentation as well
from sympy import Eq, Not, ceiling, Ne, re, unbranched_argument as arg
delta = g.delta
eta, _ = _get_coeff_exp(g.argument, x)
m, n, p, q = S([len(g.bm), len(g.an), len(g.ap), len(g.bq)])
if p > q:
def tr(l):
return [1 - x for x in l]
return _check_antecedents_1(meijerg(tr(g.bm), tr(g.bother),
tr(g.an), tr(g.aother), x/eta),
x)
tmp = []
for b in g.bm:
tmp += [-re(b) < 1]
for a in g.an:
tmp += [1 < 1 - re(a)]
cond_3 = And(*tmp)
for b in g.bother:
tmp += [-re(b) < 1]
for a in g.aother:
tmp += [1 < 1 - re(a)]
cond_3_star = And(*tmp)
cond_4 = (-re(g.nu) + (q + 1 - p)/2 > q - p)
def debug(*msg):
_debug(*msg)
debug('Checking antecedents for 1 function:')
debug(' delta=%s, eta=%s, m=%s, n=%s, p=%s, q=%s'
% (delta, eta, m, n, p, q))
debug(' ap = %s, %s' % (list(g.an), list(g.aother)))
debug(' bq = %s, %s' % (list(g.bm), list(g.bother)))
debug(' cond_3=%s, cond_3*=%s, cond_4=%s' % (cond_3, cond_3_star, cond_4))
conds = []
# case 1
case1 = []
tmp1 = [1 <= n, p < q, 1 <= m]
tmp2 = [1 <= p, 1 <= m, Eq(q, p + 1), Not(And(Eq(n, 0), Eq(m, p + 1)))]
tmp3 = [1 <= p, Eq(q, p)]
for k in range(ceiling(delta/2) + 1):
tmp3 += [Ne(abs(arg(eta)), (delta - 2*k)*pi)]
tmp = [delta > 0, abs(arg(eta)) < delta*pi]
extra = [Ne(eta, 0), cond_3]
if helper:
extra = []
for t in [tmp1, tmp2, tmp3]:
case1 += [And(*(t + tmp + extra))]
conds += case1
debug(' case 1:', case1)
# case 2
extra = [cond_3]
if helper:
extra = []
case2 = [And(Eq(n, 0), p + 1 <= m, m <= q,
abs(arg(eta)) < delta*pi, *extra)]
conds += case2
debug(' case 2:', case2)
# case 3
extra = [cond_3, cond_4]
if helper:
extra = []
case3 = [And(p < q, 1 <= m, delta > 0, Eq(abs(arg(eta)), delta*pi),
*extra)]
case3 += [And(p <= q - 2, Eq(delta, 0), Eq(abs(arg(eta)), 0), *extra)]
conds += case3
debug(' case 3:', case3)
# TODO altered cases 4-7
# extra case from wofram functions site:
# (reproduced verbatim from Prudnikov, section 2.24.2)
# http://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/01/
case_extra = []
case_extra += [Eq(p, q), Eq(delta, 0), Eq(arg(eta), 0), Ne(eta, 0)]
if not helper:
case_extra += [cond_3]
s = []
for a, b in zip(g.ap, g.bq):
s += [b - a]
case_extra += [re(Add(*s)) < 0]
case_extra = And(*case_extra)
conds += [case_extra]
debug(' extra case:', [case_extra])
case_extra_2 = [And(delta > 0, abs(arg(eta)) < delta*pi)]
if not helper:
case_extra_2 += [cond_3]
case_extra_2 = And(*case_extra_2)
conds += [case_extra_2]
debug(' second extra case:', [case_extra_2])
# TODO This leaves only one case from the three listed by Prudnikov.
# Investigate if these indeed cover everything; if so, remove the rest.
return Or(*conds)
def _int0oo_1(g, x):
r"""
Evaluate $\int_0^\infty g\, dx$ using G functions,
assuming the necessary conditions are fulfilled.
Examples
========
>>> from sympy.abc import a, b, c, d, x, y
>>> from sympy import meijerg
>>> from sympy.integrals.meijerint import _int0oo_1
>>> _int0oo_1(meijerg([a], [b], [c], [d], x*y), x)
gamma(-a)*gamma(c + 1)/(y*gamma(-d)*gamma(b + 1))
"""
# See [L, section 5.6.1]. Note that s=1.
from sympy import gamma, gammasimp, unpolarify
eta, _ = _get_coeff_exp(g.argument, x)
res = 1/eta
# XXX TODO we should reduce order first
for b in g.bm:
res *= gamma(b + 1)
for a in g.an:
res *= gamma(1 - a - 1)
for b in g.bother:
res /= gamma(1 - b - 1)
for a in g.aother:
res /= gamma(a + 1)
return gammasimp(unpolarify(res))
def _rewrite_saxena(fac, po, g1, g2, x, full_pb=False):
"""
Rewrite the integral ``fac*po*g1*g2`` from 0 to oo in terms of G
functions with argument ``c*x``.
Explanation
===========
Return C, f1, f2 such that integral C f1 f2 from 0 to infinity equals
integral fac ``po``, ``g1``, ``g2`` from 0 to infinity.
Examples
========
>>> from sympy.integrals.meijerint import _rewrite_saxena
>>> from sympy.abc import s, t, m
>>> from sympy import meijerg
>>> g1 = meijerg([], [], [0], [], s*t)
>>> g2 = meijerg([], [], [m/2], [-m/2], t**2/4)
>>> r = _rewrite_saxena(1, t**0, g1, g2, t)
>>> r[0]
s/(4*sqrt(pi))
>>> r[1]
meijerg(((), ()), ((-1/2, 0), ()), s**2*t/4)
>>> r[2]
meijerg(((), ()), ((m/2,), (-m/2,)), t/4)
"""
from sympy.core.numbers import ilcm
def pb(g):
a, b = _get_coeff_exp(g.argument, x)
per = g.get_period()
return meijerg(g.an, g.aother, g.bm, g.bother,
_my_principal_branch(a, per, full_pb)*x**b)
_, s = _get_coeff_exp(po, x)
_, b1 = _get_coeff_exp(g1.argument, x)
_, b2 = _get_coeff_exp(g2.argument, x)
if (b1 < 0) == True:
b1 = -b1
g1 = _flip_g(g1)
if (b2 < 0) == True:
b2 = -b2
g2 = _flip_g(g2)
if not b1.is_Rational or not b2.is_Rational:
return
m1, n1 = b1.p, b1.q
m2, n2 = b2.p, b2.q
tau = ilcm(m1*n2, m2*n1)
r1 = tau//(m1*n2)
r2 = tau//(m2*n1)
C1, g1 = _inflate_g(g1, r1)
C2, g2 = _inflate_g(g2, r2)
g1 = pb(g1)
g2 = pb(g2)
fac *= C1*C2
a1, b = _get_coeff_exp(g1.argument, x)
a2, _ = _get_coeff_exp(g2.argument, x)
# arbitrarily tack on the x**s part to g1
# TODO should we try both?
exp = (s + 1)/b - 1
fac = fac/(abs(b) * a1**exp)
def tr(l):
return [a + exp for a in l]
g1 = meijerg(tr(g1.an), tr(g1.aother), tr(g1.bm), tr(g1.bother), a1*x)
g2 = meijerg(g2.an, g2.aother, g2.bm, g2.bother, a2*x)
return powdenest(fac, polar=True), g1, g2
def _check_antecedents(g1, g2, x):
""" Return a condition under which the integral theorem applies. """
from sympy import re, Eq, Ne, cos, I, exp, sin, sign, unpolarify
from sympy import arg as arg_, unbranched_argument as arg
# Yes, this is madness.
# XXX TODO this is a testing *nightmare*
# NOTE if you update these conditions, please update the documentation as well
# The following conditions are found in
# [P], Section 2.24.1
#
# They are also reproduced (verbatim!) at
# http://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/
#
# Note: k=l=r=alpha=1
sigma, _ = _get_coeff_exp(g1.argument, x)
omega, _ = _get_coeff_exp(g2.argument, x)
s, t, u, v = S([len(g1.bm), len(g1.an), len(g1.ap), len(g1.bq)])
m, n, p, q = S([len(g2.bm), len(g2.an), len(g2.ap), len(g2.bq)])
bstar = s + t - (u + v)/2
cstar = m + n - (p + q)/2
rho = g1.nu + (u - v)/2 + 1
mu = g2.nu + (p - q)/2 + 1
phi = q - p - (v - u)
eta = 1 - (v - u) - mu - rho
psi = (pi*(q - m - n) + abs(arg(omega)))/(q - p)
theta = (pi*(v - s - t) + abs(arg(sigma)))/(v - u)
_debug('Checking antecedents:')
_debug(' sigma=%s, s=%s, t=%s, u=%s, v=%s, b*=%s, rho=%s'
% (sigma, s, t, u, v, bstar, rho))
_debug(' omega=%s, m=%s, n=%s, p=%s, q=%s, c*=%s, mu=%s,'
% (omega, m, n, p, q, cstar, mu))
_debug(' phi=%s, eta=%s, psi=%s, theta=%s' % (phi, eta, psi, theta))
def _c1():
for g in [g1, g2]:
for i in g.an:
for j in g.bm:
diff = i - j
if diff.is_integer and diff.is_positive:
return False
return True
c1 = _c1()
c2 = And(*[re(1 + i + j) > 0 for i in g1.bm for j in g2.bm])
c3 = And(*[re(1 + i + j) < 1 + 1 for i in g1.an for j in g2.an])
c4 = And(*[(p - q)*re(1 + i - 1) - re(mu) > Rational(-3, 2) for i in g1.an])
c5 = And(*[(p - q)*re(1 + i) - re(mu) > Rational(-3, 2) for i in g1.bm])
c6 = And(*[(u - v)*re(1 + i - 1) - re(rho) > Rational(-3, 2) for i in g2.an])
c7 = And(*[(u - v)*re(1 + i) - re(rho) > Rational(-3, 2) for i in g2.bm])
c8 = (abs(phi) + 2*re((rho - 1)*(q - p) + (v - u)*(q - p) + (mu -
1)*(v - u)) > 0)
c9 = (abs(phi) - 2*re((rho - 1)*(q - p) + (v - u)*(q - p) + (mu -
1)*(v - u)) > 0)
c10 = (abs(arg(sigma)) < bstar*pi)
c11 = Eq(abs(arg(sigma)), bstar*pi)
c12 = (abs(arg(omega)) < cstar*pi)
c13 = Eq(abs(arg(omega)), cstar*pi)
# The following condition is *not* implemented as stated on the wolfram
# function site. In the book of Prudnikov there is an additional part
# (the And involving re()). However, I only have this book in russian, and
# I don't read any russian. The following condition is what other people
# have told me it means.
# Worryingly, it is different from the condition implemented in REDUCE.
# The REDUCE implementation:
# https://reduce-algebra.svn.sourceforge.net/svnroot/reduce-algebra/trunk/packages/defint/definta.red
# (search for tst14)
# The Wolfram alpha version:
# http://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/03/0014/
z0 = exp(-(bstar + cstar)*pi*I)
zos = unpolarify(z0*omega/sigma)
zso = unpolarify(z0*sigma/omega)
if zos == 1/zso:
c14 = And(Eq(phi, 0), bstar + cstar <= 1,
Or(Ne(zos, 1), re(mu + rho + v - u) < 1,
re(mu + rho + q - p) < 1))
else:
def _cond(z):
'''Returns True if abs(arg(1-z)) < pi, avoiding arg(0).
Explanation
===========
If ``z`` is 1 then arg is NaN. This raises a
TypeError on `NaN < pi`. Previously this gave `False` so
this behavior has been hardcoded here but someone should
check if this NaN is more serious! This NaN is triggered by
test_meijerint() in test_meijerint.py:
`meijerint_definite(exp(x), x, 0, I)`
'''
return z != 1 and abs(arg_(1 - z)) < pi
c14 = And(Eq(phi, 0), bstar - 1 + cstar <= 0,
Or(And(Ne(zos, 1), _cond(zos)),
And(re(mu + rho + v - u) < 1, Eq(zos, 1))))
c14_alt = And(Eq(phi, 0), cstar - 1 + bstar <= 0,
Or(And(Ne(zso, 1), _cond(zso)),
And(re(mu + rho + q - p) < 1, Eq(zso, 1))))
# Since r=k=l=1, in our case there is c14_alt which is the same as calling
# us with (g1, g2) = (g2, g1). The conditions below enumerate all cases
# (i.e. we don't have to try arguments reversed by hand), and indeed try
# all symmetric cases. (i.e. whenever there is a condition involving c14,
# there is also a dual condition which is exactly what we would get when g1,
# g2 were interchanged, *but c14 was unaltered*).
# Hence the following seems correct:
c14 = Or(c14, c14_alt)
'''
When `c15` is NaN (e.g. from `psi` being NaN as happens during
'test_issue_4992' and/or `theta` is NaN as in 'test_issue_6253',
both in `test_integrals.py`) the comparison to 0 formerly gave False
whereas now an error is raised. To keep the old behavior, the value
of NaN is replaced with False but perhaps a closer look at this condition
should be made: XXX how should conditions leading to c15=NaN be handled?
'''
try:
lambda_c = (q - p)*abs(omega)**(1/(q - p))*cos(psi) \
+ (v - u)*abs(sigma)**(1/(v - u))*cos(theta)
# the TypeError might be raised here, e.g. if lambda_c is NaN
if _eval_cond(lambda_c > 0) != False:
c15 = (lambda_c > 0)
else:
def lambda_s0(c1, c2):
return c1*(q - p)*abs(omega)**(1/(q - p))*sin(psi) \
+ c2*(v - u)*abs(sigma)**(1/(v - u))*sin(theta)
lambda_s = Piecewise(
((lambda_s0(+1, +1)*lambda_s0(-1, -1)),
And(Eq(arg(sigma), 0), Eq(arg(omega), 0))),
(lambda_s0(sign(arg(omega)), +1)*lambda_s0(sign(arg(omega)), -1),
And(Eq(arg(sigma), 0), Ne(arg(omega), 0))),
(lambda_s0(+1, sign(arg(sigma)))*lambda_s0(-1, sign(arg(sigma))),
And(Ne(arg(sigma), 0), Eq(arg(omega), 0))),
(lambda_s0(sign(arg(omega)), sign(arg(sigma))), True))
tmp = [lambda_c > 0,
And(Eq(lambda_c, 0), Ne(lambda_s, 0), re(eta) > -1),
And(Eq(lambda_c, 0), Eq(lambda_s, 0), re(eta) > 0)]
c15 = Or(*tmp)
except TypeError:
c15 = False
for cond, i in [(c1, 1), (c2, 2), (c3, 3), (c4, 4), (c5, 5), (c6, 6),
(c7, 7), (c8, 8), (c9, 9), (c10, 10), (c11, 11),
(c12, 12), (c13, 13), (c14, 14), (c15, 15)]:
_debug(' c%s:' % i, cond)
# We will return Or(*conds)
conds = []
def pr(count):
_debug(' case %s:' % count, conds[-1])
conds += [And(m*n*s*t != 0, bstar.is_positive is True, cstar.is_positive is True, c1, c2, c3, c10,
c12)] # 1
pr(1)
conds += [And(Eq(u, v), Eq(bstar, 0), cstar.is_positive is True, sigma.is_positive is True, re(rho) < 1,
c1, c2, c3, c12)] # 2
pr(2)
conds += [And(Eq(p, q), Eq(cstar, 0), bstar.is_positive is True, omega.is_positive is True, re(mu) < 1,
c1, c2, c3, c10)] # 3
pr(3)
conds += [And(Eq(p, q), Eq(u, v), Eq(bstar, 0), Eq(cstar, 0),
sigma.is_positive is True, omega.is_positive is True, re(mu) < 1, re(rho) < 1,
Ne(sigma, omega), c1, c2, c3)] # 4
pr(4)
conds += [And(Eq(p, q), Eq(u, v), Eq(bstar, 0), Eq(cstar, 0),
sigma.is_positive is True, omega.is_positive is True, re(mu + rho) < 1,
Ne(omega, sigma), c1, c2, c3)] # 5
pr(5)
conds += [And(p > q, s.is_positive is True, bstar.is_positive is True, cstar >= 0,
c1, c2, c3, c5, c10, c13)] # 6
pr(6)
conds += [And(p < q, t.is_positive is True, bstar.is_positive is True, cstar >= 0,
c1, c2, c3, c4, c10, c13)] # 7
pr(7)
conds += [And(u > v, m.is_positive is True, cstar.is_positive is True, bstar >= 0,
c1, c2, c3, c7, c11, c12)] # 8
pr(8)
conds += [And(u < v, n.is_positive is True, cstar.is_positive is True, bstar >= 0,
c1, c2, c3, c6, c11, c12)] # 9
pr(9)
conds += [And(p > q, Eq(u, v), Eq(bstar, 0), cstar >= 0, sigma.is_positive is True,
re(rho) < 1, c1, c2, c3, c5, c13)] # 10
pr(10)
conds += [And(p < q, Eq(u, v), Eq(bstar, 0), cstar >= 0, sigma.is_positive is True,
re(rho) < 1, c1, c2, c3, c4, c13)] # 11
pr(11)
conds += [And(Eq(p, q), u > v, bstar >= 0, Eq(cstar, 0), omega.is_positive is True,
re(mu) < 1, c1, c2, c3, c7, c11)] # 12
pr(12)
conds += [And(Eq(p, q), u < v, bstar >= 0, Eq(cstar, 0), omega.is_positive is True,
re(mu) < 1, c1, c2, c3, c6, c11)] # 13
pr(13)
conds += [And(p < q, u > v, bstar >= 0, cstar >= 0,
c1, c2, c3, c4, c7, c11, c13)] # 14
pr(14)
conds += [And(p > q, u < v, bstar >= 0, cstar >= 0,
c1, c2, c3, c5, c6, c11, c13)] # 15
pr(15)
conds += [And(p > q, u > v, bstar >= 0, cstar >= 0,
c1, c2, c3, c5, c7, c8, c11, c13, c14)] # 16
pr(16)
conds += [And(p < q, u < v, bstar >= 0, cstar >= 0,
c1, c2, c3, c4, c6, c9, c11, c13, c14)] # 17
pr(17)
conds += [And(Eq(t, 0), s.is_positive is True, bstar.is_positive is True, phi.is_positive is True, c1, c2, c10)] # 18
pr(18)
conds += [And(Eq(s, 0), t.is_positive is True, bstar.is_positive is True, phi.is_negative is True, c1, c3, c10)] # 19
pr(19)
conds += [And(Eq(n, 0), m.is_positive is True, cstar.is_positive is True, phi.is_negative is True, c1, c2, c12)] # 20
pr(20)
conds += [And(Eq(m, 0), n.is_positive is True, cstar.is_positive is True, phi.is_positive is True, c1, c3, c12)] # 21
pr(21)
conds += [And(Eq(s*t, 0), bstar.is_positive is True, cstar.is_positive is True,
c1, c2, c3, c10, c12)] # 22
pr(22)
conds += [And(Eq(m*n, 0), bstar.is_positive is True, cstar.is_positive is True,
c1, c2, c3, c10, c12)] # 23
pr(23)
# The following case is from [Luke1969]. As far as I can tell, it is *not*
# covered by Prudnikov's.
# Let G1 and G2 be the two G-functions. Suppose the integral exists from
# 0 to a > 0 (this is easy the easy part), that G1 is exponential decay at
# infinity, and that the mellin transform of G2 exists.
# Then the integral exists.
mt1_exists = _check_antecedents_1(g1, x, helper=True)
mt2_exists = _check_antecedents_1(g2, x, helper=True)
conds += [And(mt2_exists, Eq(t, 0), u < s, bstar.is_positive is True, c10, c1, c2, c3)]
pr('E1')
conds += [And(mt2_exists, Eq(s, 0), v < t, bstar.is_positive is True, c10, c1, c2, c3)]
pr('E2')
conds += [And(mt1_exists, Eq(n, 0), p < m, cstar.is_positive is True, c12, c1, c2, c3)]
pr('E3')
conds += [And(mt1_exists, Eq(m, 0), q < n, cstar.is_positive is True, c12, c1, c2, c3)]
pr('E4')
# Let's short-circuit if this worked ...
# the rest is corner-cases and terrible to read.
r = Or(*conds)
if _eval_cond(r) != False:
return r
conds += [And(m + n > p, Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True, cstar.is_negative is True,
abs(arg(omega)) < (m + n - p + 1)*pi,
c1, c2, c10, c14, c15)] # 24
pr(24)
conds += [And(m + n > q, Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar.is_negative is True,
abs(arg(omega)) < (m + n - q + 1)*pi,
c1, c3, c10, c14, c15)] # 25
pr(25)
conds += [And(Eq(p, q - 1), Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True,
cstar >= 0, cstar*pi < abs(arg(omega)),
c1, c2, c10, c14, c15)] # 26
pr(26)
conds += [And(Eq(p, q + 1), Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True,
cstar >= 0, cstar*pi < abs(arg(omega)),
c1, c3, c10, c14, c15)] # 27
pr(27)
conds += [And(p < q - 1, Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True,
cstar >= 0, cstar*pi < abs(arg(omega)),
abs(arg(omega)) < (m + n - p + 1)*pi,
c1, c2, c10, c14, c15)] # 28
pr(28)
conds += [And(
p > q + 1, Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar >= 0,
cstar*pi < abs(arg(omega)),
abs(arg(omega)) < (m + n - q + 1)*pi,
c1, c3, c10, c14, c15)] # 29
pr(29)
conds += [And(Eq(n, 0), Eq(phi, 0), s + t > 0, m.is_positive is True, cstar.is_positive is True, bstar.is_negative is True,
abs(arg(sigma)) < (s + t - u + 1)*pi,
c1, c2, c12, c14, c15)] # 30
pr(30)
conds += [And(Eq(m, 0), Eq(phi, 0), s + t > v, n.is_positive is True, cstar.is_positive is True, bstar.is_negative is True,
abs(arg(sigma)) < (s + t - v + 1)*pi,
c1, c3, c12, c14, c15)] # 31
pr(31)
conds += [And(Eq(n, 0), Eq(phi, 0), Eq(u, v - 1), m.is_positive is True, cstar.is_positive is True,
bstar >= 0, bstar*pi < abs(arg(sigma)),
abs(arg(sigma)) < (bstar + 1)*pi,
c1, c2, c12, c14, c15)] # 32
pr(32)
conds += [And(Eq(m, 0), Eq(phi, 0), Eq(u, v + 1), n.is_positive is True, cstar.is_positive is True,
bstar >= 0, bstar*pi < abs(arg(sigma)),
abs(arg(sigma)) < (bstar + 1)*pi,
c1, c3, c12, c14, c15)] # 33
pr(33)
conds += [And(
Eq(n, 0), Eq(phi, 0), u < v - 1, m.is_positive is True, cstar.is_positive is True, bstar >= 0,
bstar*pi < abs(arg(sigma)),
abs(arg(sigma)) < (s + t - u + 1)*pi,
c1, c2, c12, c14, c15)] # 34
pr(34)
conds += [And(
Eq(m, 0), Eq(phi, 0), u > v + 1, n.is_positive is True, cstar.is_positive is True, bstar >= 0,
bstar*pi < abs(arg(sigma)),
abs(arg(sigma)) < (s + t - v + 1)*pi,
c1, c3, c12, c14, c15)] # 35
pr(35)
return Or(*conds)
# NOTE An alternative, but as far as I can tell weaker, set of conditions
# can be found in [L, section 5.6.2].
def _int0oo(g1, g2, x):
"""
Express integral from zero to infinity g1*g2 using a G function,
assuming the necessary conditions are fulfilled.
Examples
========
>>> from sympy.integrals.meijerint import _int0oo
>>> from sympy.abc import s, t, m
>>> from sympy import meijerg, S
>>> g1 = meijerg([], [], [-S(1)/2, 0], [], s**2*t/4)
>>> g2 = meijerg([], [], [m/2], [-m/2], t/4)
>>> _int0oo(g1, g2, t)
4*meijerg(((1/2, 0), ()), ((m/2,), (-m/2,)), s**(-2))/s**2
"""
# See: [L, section 5.6.2, equation (1)]
eta, _ = _get_coeff_exp(g1.argument, x)
omega, _ = _get_coeff_exp(g2.argument, x)
def neg(l):
return [-x for x in l]
a1 = neg(g1.bm) + list(g2.an)
a2 = list(g2.aother) + neg(g1.bother)
b1 = neg(g1.an) + list(g2.bm)
b2 = list(g2.bother) + neg(g1.aother)
return meijerg(a1, a2, b1, b2, omega/eta)/eta
def _rewrite_inversion(fac, po, g, x):
""" Absorb ``po`` == x**s into g. """
_, s = _get_coeff_exp(po, x)
a, b = _get_coeff_exp(g.argument, x)
def tr(l):
return [t + s/b for t in l]
return (powdenest(fac/a**(s/b), polar=True),
meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother), g.argument))
def _check_antecedents_inversion(g, x):
""" Check antecedents for the laplace inversion integral. """
from sympy import re, im, Or, And, Eq, exp, I, Add, nan, Ne
_debug('Checking antecedents for inversion:')
z = g.argument
_, e = _get_coeff_exp(z, x)
if e < 0:
_debug(' Flipping G.')
# We want to assume that argument gets large as |x| -> oo
return _check_antecedents_inversion(_flip_g(g), x)
def statement_half(a, b, c, z, plus):
coeff, exponent = _get_coeff_exp(z, x)
a *= exponent
b *= coeff**c
c *= exponent
conds = []
wp = b*exp(I*re(c)*pi/2)
wm = b*exp(-I*re(c)*pi/2)
if plus:
w = wp
else:
w = wm
conds += [And(Or(Eq(b, 0), re(c) <= 0), re(a) <= -1)]
conds += [And(Ne(b, 0), Eq(im(c), 0), re(c) > 0, re(w) < 0)]
conds += [And(Ne(b, 0), Eq(im(c), 0), re(c) > 0, re(w) <= 0,
re(a) <= -1)]
return Or(*conds)
def statement(a, b, c, z):
""" Provide a convergence statement for z**a * exp(b*z**c),
c/f sphinx docs. """
return And(statement_half(a, b, c, z, True),
statement_half(a, b, c, z, False))
# Notations from [L], section 5.7-10
m, n, p, q = S([len(g.bm), len(g.an), len(g.ap), len(g.bq)])
tau = m + n - p
nu = q - m - n
rho = (tau - nu)/2
sigma = q - p
if sigma == 1:
epsilon = S.Half
elif sigma > 1:
epsilon = 1
else:
epsilon = nan
theta = ((1 - sigma)/2 + Add(*g.bq) - Add(*g.ap))/sigma
delta = g.delta
_debug(' m=%s, n=%s, p=%s, q=%s, tau=%s, nu=%s, rho=%s, sigma=%s' % (
m, n, p, q, tau, nu, rho, sigma))
_debug(' epsilon=%s, theta=%s, delta=%s' % (epsilon, theta, delta))
# First check if the computation is valid.
if not (g.delta >= e/2 or (p >= 1 and p >= q)):
_debug(' Computation not valid for these parameters.')
return False
# Now check if the inversion integral exists.
# Test "condition A"
for a in g.an:
for b in g.bm:
if (a - b).is_integer and a > b:
_debug(' Not a valid G function.')
return False
# There are two cases. If p >= q, we can directly use a slater expansion
# like [L], 5.2 (11). Note in particular that the asymptotics of such an
# expansion even hold when some of the parameters differ by integers, i.e.
# the formula itself would not be valid! (b/c G functions are cts. in their
# parameters)
# When p < q, we need to use the theorems of [L], 5.10.
if p >= q:
_debug(' Using asymptotic Slater expansion.')
return And(*[statement(a - 1, 0, 0, z) for a in g.an])
def E(z):
return And(*[statement(a - 1, 0, 0, z) for a in g.an])
def H(z):
return statement(theta, -sigma, 1/sigma, z)
def Hp(z):
return statement_half(theta, -sigma, 1/sigma, z, True)
def Hm(z):
return statement_half(theta, -sigma, 1/sigma, z, False)
# [L], section 5.10
conds = []
# Theorem 1 -- p < q from test above
conds += [And(1 <= n, 1 <= m, rho*pi - delta >= pi/2, delta > 0,
E(z*exp(I*pi*(nu + 1))))]
# Theorem 2, statements (2) and (3)
conds += [And(p + 1 <= m, m + 1 <= q, delta > 0, delta < pi/2, n == 0,
(m - p + 1)*pi - delta >= pi/2,
Hp(z*exp(I*pi*(q - m))), Hm(z*exp(-I*pi*(q - m))))]
# Theorem 2, statement (5) -- p < q from test above
conds += [And(m == q, n == 0, delta > 0,
(sigma + epsilon)*pi - delta >= pi/2, H(z))]
# Theorem 3, statements (6) and (7)
conds += [And(Or(And(p <= q - 2, 1 <= tau, tau <= sigma/2),
And(p + 1 <= m + n, m + n <= (p + q)/2)),
delta > 0, delta < pi/2, (tau + 1)*pi - delta >= pi/2,
Hp(z*exp(I*pi*nu)), Hm(z*exp(-I*pi*nu)))]
# Theorem 4, statements (10) and (11) -- p < q from test above
conds += [And(1 <= m, rho > 0, delta > 0, delta + rho*pi < pi/2,
(tau + epsilon)*pi - delta >= pi/2,
Hp(z*exp(I*pi*nu)), Hm(z*exp(-I*pi*nu)))]
# Trivial case
conds += [m == 0]
# TODO
# Theorem 5 is quite general
# Theorem 6 contains special cases for q=p+1
return Or(*conds)
def _int_inversion(g, x, t):
"""
Compute the laplace inversion integral, assuming the formula applies.
"""
b, a = _get_coeff_exp(g.argument, x)
C, g = _inflate_fox_h(meijerg(g.an, g.aother, g.bm, g.bother, b/t**a), -a)
return C/t*g
####################################################################
# Finally, the real meat.
####################################################################
_lookup_table = None
@cacheit
@timeit
def _rewrite_single(f, x, recursive=True):
"""
Try to rewrite f as a sum of single G functions of the form
C*x**s*G(a*x**b), where b is a rational number and C is independent of x.
We guarantee that result.argument.as_coeff_mul(x) returns (a, (x**b,))
or (a, ()).
Returns a list of tuples (C, s, G) and a condition cond.
Returns None on failure.
"""
from sympy import polarify, unpolarify, oo, zoo, Tuple
global _lookup_table
if not _lookup_table:
_lookup_table = {}
_create_lookup_table(_lookup_table)
if isinstance(f, meijerg):
from sympy import factor
coeff, m = factor(f.argument, x).as_coeff_mul(x)
if len(m) > 1:
return None
m = m[0]
if m.is_Pow:
if m.base != x or not m.exp.is_Rational:
return None
elif m != x:
return None
return [(1, 0, meijerg(f.an, f.aother, f.bm, f.bother, coeff*m))], True
f_ = f
f = f.subs(x, z)
t = _mytype(f, z)
if t in _lookup_table:
l = _lookup_table[t]
for formula, terms, cond, hint in l:
subs = f.match(formula, old=True)
if subs:
subs_ = {}
for fro, to in subs.items():
subs_[fro] = unpolarify(polarify(to, lift=True),
exponents_only=True)
subs = subs_
if not isinstance(hint, bool):
hint = hint.subs(subs)
if hint == False:
continue
if not isinstance(cond, (bool, BooleanAtom)):
cond = unpolarify(cond.subs(subs))
if _eval_cond(cond) == False:
continue
if not isinstance(terms, list):
terms = terms(subs)
res = []
for fac, g in terms:
r1 = _get_coeff_exp(unpolarify(fac.subs(subs).subs(z, x),
exponents_only=True), x)
try:
g = g.subs(subs).subs(z, x)
except ValueError:
continue
# NOTE these substitutions can in principle introduce oo,
# zoo and other absurdities. It shouldn't matter,
# but better be safe.
if Tuple(*(r1 + (g,))).has(oo, zoo, -oo):
continue
g = meijerg(g.an, g.aother, g.bm, g.bother,
unpolarify(g.argument, exponents_only=True))
res.append(r1 + (g,))
if res:
return res, cond
# try recursive mellin transform
if not recursive:
return None
_debug('Trying recursive Mellin transform method.')
from sympy.integrals.transforms import (mellin_transform,
inverse_mellin_transform, IntegralTransformError,
MellinTransformStripError)
from sympy import oo, nan, zoo, simplify, cancel
def my_imt(F, s, x, strip):
""" Calling simplify() all the time is slow and not helpful, since
most of the time it only factors things in a way that has to be
un-done anyway. But sometimes it can remove apparent poles. """
# XXX should this be in inverse_mellin_transform?
try:
return inverse_mellin_transform(F, s, x, strip,
as_meijerg=True, needeval=True)
except MellinTransformStripError:
return inverse_mellin_transform(
simplify(cancel(expand(F))), s, x, strip,
as_meijerg=True, needeval=True)
f = f_
s = _dummy('s', 'rewrite-single', f)
# to avoid infinite recursion, we have to force the two g functions case
def my_integrator(f, x):
from sympy import Integral, hyperexpand
r = _meijerint_definite_4(f, x, only_double=True)
if r is not None:
res, cond = r
res = _my_unpolarify(hyperexpand(res, rewrite='nonrepsmall'))
return Piecewise((res, cond),
(Integral(f, (x, 0, oo)), True))
return Integral(f, (x, 0, oo))
try:
F, strip, _ = mellin_transform(f, x, s, integrator=my_integrator,
simplify=False, needeval=True)
g = my_imt(F, s, x, strip)
except IntegralTransformError:
g = None
if g is None:
# We try to find an expression by analytic continuation.
# (also if the dummy is already in the expression, there is no point in
# putting in another one)
a = _dummy_('a', 'rewrite-single')
if a not in f.free_symbols and _is_analytic(f, x):
try:
F, strip, _ = mellin_transform(f.subs(x, a*x), x, s,
integrator=my_integrator,
needeval=True, simplify=False)
g = my_imt(F, s, x, strip).subs(a, 1)
except IntegralTransformError:
g = None
if g is None or g.has(oo, nan, zoo):
_debug('Recursive Mellin transform failed.')
return None
args = Add.make_args(g)
res = []
for f in args:
c, m = f.as_coeff_mul(x)
if len(m) > 1:
raise NotImplementedError('Unexpected form...')
g = m[0]
a, b = _get_coeff_exp(g.argument, x)
res += [(c, 0, meijerg(g.an, g.aother, g.bm, g.bother,
unpolarify(polarify(
a, lift=True), exponents_only=True)
*x**b))]
_debug('Recursive Mellin transform worked:', g)
return res, True
def _rewrite1(f, x, recursive=True):
"""
Try to rewrite ``f`` using a (sum of) single G functions with argument a*x**b.
Return fac, po, g such that f = fac*po*g, fac is independent of ``x``.
and po = x**s.
Here g is a result from _rewrite_single.
Return None on failure.
"""
fac, po, g = _split_mul(f, x)
g = _rewrite_single(g, x, recursive)
if g:
return fac, po, g[0], g[1]
def _rewrite2(f, x):
"""
Try to rewrite ``f`` as a product of two G functions of arguments a*x**b.
Return fac, po, g1, g2 such that f = fac*po*g1*g2, where fac is
independent of x and po is x**s.
Here g1 and g2 are results of _rewrite_single.
Returns None on failure.
"""
fac, po, g = _split_mul(f, x)
if any(_rewrite_single(expr, x, False) is None for expr in _mul_args(g)):
return None
l = _mul_as_two_parts(g)
if not l:
return None
l = list(ordered(l, [
lambda p: max(len(_exponents(p[0], x)), len(_exponents(p[1], x))),
lambda p: max(len(_functions(p[0], x)), len(_functions(p[1], x))),
lambda p: max(len(_find_splitting_points(p[0], x)),
len(_find_splitting_points(p[1], x)))]))
for recursive in [False, True]:
for fac1, fac2 in l:
g1 = _rewrite_single(fac1, x, recursive)
g2 = _rewrite_single(fac2, x, recursive)
if g1 and g2:
cond = And(g1[1], g2[1])
if cond != False:
return fac, po, g1[0], g2[0], cond
def meijerint_indefinite(f, x):
"""
Compute an indefinite integral of ``f`` by rewriting it as a G function.
Examples
========
>>> from sympy.integrals.meijerint import meijerint_indefinite
>>> from sympy import sin
>>> from sympy.abc import x
>>> meijerint_indefinite(sin(x), x)
-cos(x)
"""
from sympy import hyper, meijerg
results = []
for a in sorted(_find_splitting_points(f, x) | {S.Zero}, key=default_sort_key):
res = _meijerint_indefinite_1(f.subs(x, x + a), x)
if not res:
continue
res = res.subs(x, x - a)
if _has(res, hyper, meijerg):
results.append(res)
else:
return res
if f.has(HyperbolicFunction):
_debug('Try rewriting hyperbolics in terms of exp.')
rv = meijerint_indefinite(
_rewrite_hyperbolics_as_exp(f), x)
if rv:
if not type(rv) is list:
return collect(factor_terms(rv), rv.atoms(exp))
results.extend(rv)
if results:
return next(ordered(results))
def _meijerint_indefinite_1(f, x):
""" Helper that does not attempt any substitution. """
from sympy import Integral, piecewise_fold, nan, zoo
_debug('Trying to compute the indefinite integral of', f, 'wrt', x)
gs = _rewrite1(f, x)
if gs is None:
# Note: the code that calls us will do expand() and try again
return None
fac, po, gl, cond = gs
_debug(' could rewrite:', gs)
res = S.Zero
for C, s, g in gl:
a, b = _get_coeff_exp(g.argument, x)
_, c = _get_coeff_exp(po, x)
c += s
# we do a substitution t=a*x**b, get integrand fac*t**rho*g
fac_ = fac * C / (b*a**((1 + c)/b))
rho = (c + 1)/b - 1
# we now use t**rho*G(params, t) = G(params + rho, t)
# [L, page 150, equation (4)]
# and integral G(params, t) dt = G(1, params+1, 0, t)
# (or a similar expression with 1 and 0 exchanged ... pick the one
# which yields a well-defined function)
# [R, section 5]
# (Note that this dummy will immediately go away again, so we
# can safely pass S.One for ``expr``.)
t = _dummy('t', 'meijerint-indefinite', S.One)
def tr(p):
return [a + rho + 1 for a in p]
if any(b.is_integer and (b <= 0) == True for b in tr(g.bm)):
r = -meijerg(
tr(g.an), tr(g.aother) + [1], tr(g.bm) + [0], tr(g.bother), t)
else:
r = meijerg(
tr(g.an) + [1], tr(g.aother), tr(g.bm), tr(g.bother) + [0], t)
# The antiderivative is most often expected to be defined
# in the neighborhood of x = 0.
if b.is_extended_nonnegative and not f.subs(x, 0).has(nan, zoo):
place = 0 # Assume we can expand at zero
else:
place = None
r = hyperexpand(r.subs(t, a*x**b), place=place)
# now substitute back
# Note: we really do want the powers of x to combine.
res += powdenest(fac_*r, polar=True)
def _clean(res):
"""This multiplies out superfluous powers of x we created, and chops off
constants:
>> _clean(x*(exp(x)/x - 1/x) + 3)
exp(x)
cancel is used before mul_expand since it is possible for an
expression to have an additive constant that doesn't become isolated
with simple expansion. Such a situation was identified in issue 6369:
Examples
========
>>> from sympy import sqrt, cancel
>>> from sympy.abc import x
>>> a = sqrt(2*x + 1)
>>> bad = (3*x*a**5 + 2*x - a**5 + 1)/a**2
>>> bad.expand().as_independent(x)[0]
0
>>> cancel(bad).expand().as_independent(x)[0]
1
"""
from sympy import cancel
res = expand_mul(cancel(res), deep=False)
return Add._from_args(res.as_coeff_add(x)[1])
res = piecewise_fold(res)
if res.is_Piecewise:
newargs = []
for expr, cond in res.args:
expr = _my_unpolarify(_clean(expr))
newargs += [(expr, cond)]
res = Piecewise(*newargs)
else:
res = _my_unpolarify(_clean(res))
return Piecewise((res, _my_unpolarify(cond)), (Integral(f, x), True))
@timeit
def meijerint_definite(f, x, a, b):
"""
Integrate ``f`` over the interval [``a``, ``b``], by rewriting it as a product
of two G functions, or as a single G function.
Return res, cond, where cond are convergence conditions.
Examples
========
>>> from sympy.integrals.meijerint import meijerint_definite
>>> from sympy import exp, oo
>>> from sympy.abc import x
>>> meijerint_definite(exp(-x**2), x, -oo, oo)
(sqrt(pi), True)
This function is implemented as a succession of functions
meijerint_definite, _meijerint_definite_2, _meijerint_definite_3,
_meijerint_definite_4. Each function in the list calls the next one
(presumably) several times. This means that calling meijerint_definite
can be very costly.
"""
# This consists of three steps:
# 1) Change the integration limits to 0, oo
# 2) Rewrite in terms of G functions
# 3) Evaluate the integral
#
# There are usually several ways of doing this, and we want to try all.
# This function does (1), calls _meijerint_definite_2 for step (2).
from sympy import arg, exp, I, And, DiracDelta, SingularityFunction
_debug('Integrating', f, 'wrt %s from %s to %s.' % (x, a, b))
if f.has(DiracDelta):
_debug('Integrand has DiracDelta terms - giving up.')
return None
if f.has(SingularityFunction):
_debug('Integrand has Singularity Function terms - giving up.')
return None
f_, x_, a_, b_ = f, x, a, b
# Let's use a dummy in case any of the boundaries has x.
d = Dummy('x')
f = f.subs(x, d)
x = d
if a == b:
return (S.Zero, True)
results = []
if a is -oo and b is not oo:
return meijerint_definite(f.subs(x, -x), x, -b, -a)
elif a is -oo:
# Integrating -oo to oo. We need to find a place to split the integral.
_debug(' Integrating -oo to +oo.')
innermost = _find_splitting_points(f, x)
_debug(' Sensible splitting points:', innermost)
for c in sorted(innermost, key=default_sort_key, reverse=True) + [S.Zero]:
_debug(' Trying to split at', c)
if not c.is_extended_real:
_debug(' Non-real splitting point.')
continue
res1 = _meijerint_definite_2(f.subs(x, x + c), x)
if res1 is None:
_debug(' But could not compute first integral.')
continue
res2 = _meijerint_definite_2(f.subs(x, c - x), x)
if res2 is None:
_debug(' But could not compute second integral.')
continue
res1, cond1 = res1
res2, cond2 = res2
cond = _condsimp(And(cond1, cond2))
if cond == False:
_debug(' But combined condition is always false.')
continue
res = res1 + res2
return res, cond
elif a is oo:
res = meijerint_definite(f, x, b, oo)
return -res[0], res[1]
elif (a, b) == (0, oo):
# This is a common case - try it directly first.
res = _meijerint_definite_2(f, x)
if res:
if _has(res[0], meijerg):
results.append(res)
else:
return res
else:
if b is oo:
for split in _find_splitting_points(f, x):
if (a - split >= 0) == True:
_debug('Trying x -> x + %s' % split)
res = _meijerint_definite_2(f.subs(x, x + split)
*Heaviside(x + split - a), x)
if res:
if _has(res[0], meijerg):
results.append(res)
else:
return res
f = f.subs(x, x + a)
b = b - a
a = 0
if b != oo:
phi = exp(I*arg(b))
b = abs(b)
f = f.subs(x, phi*x)
f *= Heaviside(b - x)*phi
b = oo
_debug('Changed limits to', a, b)
_debug('Changed function to', f)
res = _meijerint_definite_2(f, x)
if res:
if _has(res[0], meijerg):
results.append(res)
else:
return res
if f_.has(HyperbolicFunction):
_debug('Try rewriting hyperbolics in terms of exp.')
rv = meijerint_definite(
_rewrite_hyperbolics_as_exp(f_), x_, a_, b_)
if rv:
if not type(rv) is list:
rv = (collect(factor_terms(rv[0]), rv[0].atoms(exp)),) + rv[1:]
return rv
results.extend(rv)
if results:
return next(ordered(results))
def _guess_expansion(f, x):
""" Try to guess sensible rewritings for integrand f(x). """
from sympy import expand_trig
from sympy.functions.elementary.trigonometric import TrigonometricFunction
res = [(f, 'original integrand')]
orig = res[-1][0]
saw = {orig}
expanded = expand_mul(orig)
if expanded not in saw:
res += [(expanded, 'expand_mul')]
saw.add(expanded)
expanded = expand(orig)
if expanded not in saw:
res += [(expanded, 'expand')]
saw.add(expanded)
if orig.has(TrigonometricFunction, HyperbolicFunction):
expanded = expand_mul(expand_trig(orig))
if expanded not in saw:
res += [(expanded, 'expand_trig, expand_mul')]
saw.add(expanded)
if orig.has(cos, sin):
reduced = sincos_to_sum(orig)
if reduced not in saw:
res += [(reduced, 'trig power reduction')]
saw.add(reduced)
return res
def _meijerint_definite_2(f, x):
"""
Try to integrate f dx from zero to infinity.
The body of this function computes various 'simplifications'
f1, f2, ... of f (e.g. by calling expand_mul(), trigexpand()
- see _guess_expansion) and calls _meijerint_definite_3 with each of
these in succession.
If _meijerint_definite_3 succeeds with any of the simplified functions,
returns this result.
"""
# This function does preparation for (2), calls
# _meijerint_definite_3 for (2) and (3) combined.
# use a positive dummy - we integrate from 0 to oo
# XXX if a nonnegative symbol is used there will be test failures
dummy = _dummy('x', 'meijerint-definite2', f, positive=True)
f = f.subs(x, dummy)
x = dummy
if f == 0:
return S.Zero, True
for g, explanation in _guess_expansion(f, x):
_debug('Trying', explanation)
res = _meijerint_definite_3(g, x)
if res:
return res
def _meijerint_definite_3(f, x):
"""
Try to integrate f dx from zero to infinity.
This function calls _meijerint_definite_4 to try to compute the
integral. If this fails, it tries using linearity.
"""
res = _meijerint_definite_4(f, x)
if res and res[1] != False:
return res
if f.is_Add:
_debug('Expanding and evaluating all terms.')
ress = [_meijerint_definite_4(g, x) for g in f.args]
if all(r is not None for r in ress):
conds = []
res = S.Zero
for r, c in ress:
res += r
conds += [c]
c = And(*conds)
if c != False:
return res, c
def _my_unpolarify(f):
from sympy import unpolarify
return _eval_cond(unpolarify(f))
@timeit
def _meijerint_definite_4(f, x, only_double=False):
"""
Try to integrate f dx from zero to infinity.
Explanation
===========
This function tries to apply the integration theorems found in literature,
i.e. it tries to rewrite f as either one or a product of two G-functions.
The parameter ``only_double`` is used internally in the recursive algorithm
to disable trying to rewrite f as a single G-function.
"""
# This function does (2) and (3)
_debug('Integrating', f)
# Try single G function.
if not only_double:
gs = _rewrite1(f, x, recursive=False)
if gs is not None:
fac, po, g, cond = gs
_debug('Could rewrite as single G function:', fac, po, g)
res = S.Zero
for C, s, f in g:
if C == 0:
continue
C, f = _rewrite_saxena_1(fac*C, po*x**s, f, x)
res += C*_int0oo_1(f, x)
cond = And(cond, _check_antecedents_1(f, x))
if cond == False:
break
cond = _my_unpolarify(cond)
if cond == False:
_debug('But cond is always False.')
else:
_debug('Result before branch substitutions is:', res)
return _my_unpolarify(hyperexpand(res)), cond
# Try two G functions.
gs = _rewrite2(f, x)
if gs is not None:
for full_pb in [False, True]:
fac, po, g1, g2, cond = gs
_debug('Could rewrite as two G functions:', fac, po, g1, g2)
res = S.Zero
for C1, s1, f1 in g1:
for C2, s2, f2 in g2:
r = _rewrite_saxena(fac*C1*C2, po*x**(s1 + s2),
f1, f2, x, full_pb)
if r is None:
_debug('Non-rational exponents.')
return
C, f1_, f2_ = r
_debug('Saxena subst for yielded:', C, f1_, f2_)
cond = And(cond, _check_antecedents(f1_, f2_, x))
if cond == False:
break
res += C*_int0oo(f1_, f2_, x)
else:
continue
break
cond = _my_unpolarify(cond)
if cond == False:
_debug('But cond is always False (full_pb=%s).' % full_pb)
else:
_debug('Result before branch substitutions is:', res)
if only_double:
return res, cond
return _my_unpolarify(hyperexpand(res)), cond
def meijerint_inversion(f, x, t):
r"""
Compute the inverse laplace transform
$\int_{c+i\infty}^{c-i\infty} f(x) e^{tx}\, dx$,
for real c larger than the real part of all singularities of ``f``.
Note that ``t`` is always assumed real and positive.
Return None if the integral does not exist or could not be evaluated.
Examples
========
>>> from sympy.abc import x, t
>>> from sympy.integrals.meijerint import meijerint_inversion
>>> meijerint_inversion(1/x, x, t)
Heaviside(t, 1/2)
"""
from sympy import exp, expand, log, Add, Mul, Heaviside
f_ = f
t_ = t
t = Dummy('t', polar=True) # We don't want sqrt(t**2) = abs(t) etc
f = f.subs(t_, t)
_debug('Laplace-inverting', f)
if not _is_analytic(f, x):
_debug('But expression is not analytic.')
return None
# Exponentials correspond to shifts; we filter them out and then
# shift the result later. If we are given an Add this will not
# work, but the calling code will take care of that.
shift = S.Zero
if f.is_Mul:
args = list(f.args)
elif isinstance(f, exp):
args = [f]
else:
args = None
if args:
newargs = []
exponentials = []
while args:
arg = args.pop()
if isinstance(arg, exp):
arg2 = expand(arg)
if arg2.is_Mul:
args += arg2.args
continue
try:
a, b = _get_coeff_exp(arg.args[0], x)
except _CoeffExpValueError:
b = 0
if b == 1:
exponentials.append(a)
else:
newargs.append(arg)
elif arg.is_Pow:
arg2 = expand(arg)
if arg2.is_Mul:
args += arg2.args
continue
if x not in arg.base.free_symbols:
try:
a, b = _get_coeff_exp(arg.exp, x)
except _CoeffExpValueError:
b = 0
if b == 1:
exponentials.append(a*log(arg.base))
newargs.append(arg)
else:
newargs.append(arg)
shift = Add(*exponentials)
f = Mul(*newargs)
if x not in f.free_symbols:
_debug('Expression consists of constant and exp shift:', f, shift)
from sympy import Eq, im
cond = Eq(im(shift), 0)
if cond == False:
_debug('but shift is nonreal, cannot be a Laplace transform')
return None
res = f*DiracDelta(t + shift)
_debug('Result is a delta function, possibly conditional:', res, cond)
# cond is True or Eq
return Piecewise((res.subs(t, t_), cond))
gs = _rewrite1(f, x)
if gs is not None:
fac, po, g, cond = gs
_debug('Could rewrite as single G function:', fac, po, g)
res = S.Zero
for C, s, f in g:
C, f = _rewrite_inversion(fac*C, po*x**s, f, x)
res += C*_int_inversion(f, x, t)
cond = And(cond, _check_antecedents_inversion(f, x))
if cond == False:
break
cond = _my_unpolarify(cond)
if cond == False:
_debug('But cond is always False.')
else:
_debug('Result before branch substitution:', res)
res = _my_unpolarify(hyperexpand(res))
if not res.has(Heaviside):
res *= Heaviside(t)
res = res.subs(t, t + shift)
if not isinstance(cond, bool):
cond = cond.subs(t, t + shift)
from sympy import InverseLaplaceTransform
return Piecewise((res.subs(t, t_), cond),
(InverseLaplaceTransform(f_.subs(t, t_), x, t_, None), True))
|
9396be3c9fdeda370c99e056a34c9abb4ebca3e1572ab0e7ca59f77be539e610 | """Base class for all the objects in SymPy"""
from collections import defaultdict
from collections.abc import Mapping
from itertools import chain, zip_longest
from .assumptions import BasicMeta, ManagedProperties
from .cache import cacheit
from .sympify import _sympify, sympify, SympifyError
from .compatibility import iterable, ordered
from .kind import UndefinedKind
from ._print_helpers import Printable
from inspect import getmro
def as_Basic(expr):
"""Return expr as a Basic instance using strict sympify
or raise a TypeError; this is just a wrapper to _sympify,
raising a TypeError instead of a SympifyError."""
from sympy.utilities.misc import func_name
try:
return _sympify(expr)
except SympifyError:
raise TypeError(
'Argument must be a Basic object, not `%s`' % func_name(
expr))
class Basic(Printable, metaclass=ManagedProperties):
"""
Base class for all SymPy objects.
Notes and conventions
=====================
1) Always use ``.args``, when accessing parameters of some instance:
>>> from sympy import cot
>>> from sympy.abc import x, y
>>> cot(x).args
(x,)
>>> cot(x).args[0]
x
>>> (x*y).args
(x, y)
>>> (x*y).args[1]
y
2) Never use internal methods or variables (the ones prefixed with ``_``):
>>> cot(x)._args # do not use this, use cot(x).args instead
(x,)
3) By "SymPy object" we mean something that can be returned by
``sympify``. But not all objects one encounters using SymPy are
subclasses of Basic. For example, mutable objects are not:
>>> from sympy import Basic, Matrix, sympify
>>> A = Matrix([[1, 2], [3, 4]]).as_mutable()
>>> isinstance(A, Basic)
False
>>> B = sympify(A)
>>> isinstance(B, Basic)
True
"""
__slots__ = ('_mhash', # hash value
'_args', # arguments
'_assumptions'
)
# To be overridden with True in the appropriate subclasses
is_number = False
is_Atom = False
is_Symbol = False
is_symbol = False
is_Indexed = False
is_Dummy = False
is_Wild = False
is_Function = False
is_Add = False
is_Mul = False
is_Pow = False
is_Number = False
is_Float = False
is_Rational = False
is_Integer = False
is_NumberSymbol = False
is_Order = False
is_Derivative = False
is_Piecewise = False
is_Poly = False
is_AlgebraicNumber = False
is_Relational = False
is_Equality = False
is_Boolean = False
is_Not = False
is_Matrix = False
is_Vector = False
is_Point = False
is_MatAdd = False
is_MatMul = False
kind = UndefinedKind
def __new__(cls, *args):
obj = object.__new__(cls)
obj._assumptions = cls.default_assumptions
obj._mhash = None # will be set by __hash__ method.
obj._args = args # all items in args must be Basic objects
return obj
def copy(self):
return self.func(*self.args)
def __getnewargs__(self):
return self.args
def __getstate__(self):
return None
def __reduce_ex__(self, protocol):
if protocol < 2:
msg = "Only pickle protocol 2 or higher is supported by sympy"
raise NotImplementedError(msg)
return super().__reduce_ex__(protocol)
def __hash__(self):
# hash cannot be cached using cache_it because infinite recurrence
# occurs as hash is needed for setting cache dictionary keys
h = self._mhash
if h is None:
h = hash((type(self).__name__,) + self._hashable_content())
self._mhash = h
return h
def _hashable_content(self):
"""Return a tuple of information about self that can be used to
compute the hash. If a class defines additional attributes,
like ``name`` in Symbol, then this method should be updated
accordingly to return such relevant attributes.
Defining more than _hashable_content is necessary if __eq__ has
been defined by a class. See note about this in Basic.__eq__."""
return self._args
@property
def assumptions0(self):
"""
Return object `type` assumptions.
For example:
Symbol('x', real=True)
Symbol('x', integer=True)
are different objects. In other words, besides Python type (Symbol in
this case), the initial assumptions are also forming their typeinfo.
Examples
========
>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{'commutative': True}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'extended_negative': False,
'extended_nonnegative': True, 'extended_nonpositive': False,
'extended_nonzero': True, 'extended_positive': True, 'extended_real':
True, 'finite': True, 'hermitian': True, 'imaginary': False,
'infinite': False, 'negative': False, 'nonnegative': True,
'nonpositive': False, 'nonzero': True, 'positive': True, 'real':
True, 'zero': False}
"""
return {}
def compare(self, other):
"""
Return -1, 0, 1 if the object is smaller, equal, or greater than other.
Not in the mathematical sense. If the object is of a different type
from the "other" then their classes are ordered according to
the sorted_classes list.
Examples
========
>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
"""
# all redefinitions of __cmp__ method should start with the
# following lines:
if self is other:
return 0
n1 = self.__class__
n2 = other.__class__
c = (n1 > n2) - (n1 < n2)
if c:
return c
#
st = self._hashable_content()
ot = other._hashable_content()
c = (len(st) > len(ot)) - (len(st) < len(ot))
if c:
return c
for l, r in zip(st, ot):
l = Basic(*l) if isinstance(l, frozenset) else l
r = Basic(*r) if isinstance(r, frozenset) else r
if isinstance(l, Basic):
c = l.compare(r)
else:
c = (l > r) - (l < r)
if c:
return c
return 0
@staticmethod
def _compare_pretty(a, b):
from sympy.series.order import Order
if isinstance(a, Order) and not isinstance(b, Order):
return 1
if not isinstance(a, Order) and isinstance(b, Order):
return -1
if a.is_Rational and b.is_Rational:
l = a.p * b.q
r = b.p * a.q
return (l > r) - (l < r)
else:
from sympy.core.symbol import Wild
p1, p2, p3 = Wild("p1"), Wild("p2"), Wild("p3")
r_a = a.match(p1 * p2**p3)
if r_a and p3 in r_a:
a3 = r_a[p3]
r_b = b.match(p1 * p2**p3)
if r_b and p3 in r_b:
b3 = r_b[p3]
c = Basic.compare(a3, b3)
if c != 0:
return c
return Basic.compare(a, b)
@classmethod
def fromiter(cls, args, **assumptions):
"""
Create a new object from an iterable.
This is a convenience function that allows one to create objects from
any iterable, without having to convert to a list or tuple first.
Examples
========
>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in range(5))
(0, 1, 2, 3, 4)
"""
return cls(*tuple(args), **assumptions)
@classmethod
def class_key(cls):
"""Nice order of classes. """
return 5, 0, cls.__name__
@cacheit
def sort_key(self, order=None):
"""
Return a sort key.
Examples
========
>>> from sympy.core import S, I
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
[1/2, -I, I]
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
[x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
>>> sorted(_, key=lambda x: x.sort_key())
[x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
"""
# XXX: remove this when issue 5169 is fixed
def inner_key(arg):
if isinstance(arg, Basic):
return arg.sort_key(order)
else:
return arg
args = self._sorted_args
args = len(args), tuple([inner_key(arg) for arg in args])
return self.class_key(), args, S.One.sort_key(), S.One
def __eq__(self, other):
"""Return a boolean indicating whether a == b on the basis of
their symbolic trees.
This is the same as a.compare(b) == 0 but faster.
Notes
=====
If a class that overrides __eq__() needs to retain the
implementation of __hash__() from a parent class, the
interpreter must be told this explicitly by setting __hash__ =
<ParentClass>.__hash__. Otherwise the inheritance of __hash__()
will be blocked, just as if __hash__ had been explicitly set to
None.
References
==========
from http://docs.python.org/dev/reference/datamodel.html#object.__hash__
"""
if self is other:
return True
tself = type(self)
tother = type(other)
if tself is not tother:
try:
other = _sympify(other)
tother = type(other)
except SympifyError:
return NotImplemented
# As long as we have the ordering of classes (sympy.core),
# comparing types will be slow in Python 2, because it uses
# __cmp__. Until we can remove it
# (https://github.com/sympy/sympy/issues/4269), we only compare
# types in Python 2 directly if they actually have __ne__.
if type(tself).__ne__ is not type.__ne__:
if tself != tother:
return False
elif tself is not tother:
return False
return self._hashable_content() == other._hashable_content()
def __ne__(self, other):
"""``a != b`` -> Compare two symbolic trees and see whether they are different
this is the same as:
``a.compare(b) != 0``
but faster
"""
return not self == other
def dummy_eq(self, other, symbol=None):
"""
Compare two expressions and handle dummy symbols.
Examples
========
>>> from sympy import Dummy
>>> from sympy.abc import x, y
>>> u = Dummy('u')
>>> (u**2 + 1).dummy_eq(x**2 + 1)
True
>>> (u**2 + 1) == (x**2 + 1)
False
>>> (u**2 + y).dummy_eq(x**2 + y, x)
True
>>> (u**2 + y).dummy_eq(x**2 + y, y)
False
"""
s = self.as_dummy()
o = _sympify(other)
o = o.as_dummy()
dummy_symbols = [i for i in s.free_symbols if i.is_Dummy]
if len(dummy_symbols) == 1:
dummy = dummy_symbols.pop()
else:
return s == o
if symbol is None:
symbols = o.free_symbols
if len(symbols) == 1:
symbol = symbols.pop()
else:
return s == o
tmp = dummy.__class__()
return s.xreplace({dummy: tmp}) == o.xreplace({symbol: tmp})
def atoms(self, *types):
"""Returns the atoms that form the current object.
By default, only objects that are truly atomic and can't
be divided into smaller pieces are returned: symbols, numbers,
and number symbols like I and pi. It is possible to request
atoms of any type, however, as demonstrated below.
Examples
========
>>> from sympy import I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
{1, 2, I, pi, x, y}
If one or more types are given, the results will contain only
those types of atoms.
>>> from sympy import Number, NumberSymbol, Symbol
>>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol)
{x, y}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number)
{1, 2}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol)
{1, 2, pi}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I)
{1, 2, I, pi}
Note that I (imaginary unit) and zoo (complex infinity) are special
types of number symbols and are not part of the NumberSymbol class.
The type can be given implicitly, too:
>>> (1 + x + 2*sin(y + I*pi)).atoms(x) # x is a Symbol
{x, y}
Be careful to check your assumptions when using the implicit option
since ``S(1).is_Integer = True`` but ``type(S(1))`` is ``One``, a special type
of sympy atom, while ``type(S(2))`` is type ``Integer`` and will find all
integers in an expression:
>>> from sympy import S
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(1))
{1}
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(2))
{1, 2}
Finally, arguments to atoms() can select more than atomic atoms: any
sympy type (loaded in core/__init__.py) can be listed as an argument
and those types of "atoms" as found in scanning the arguments of the
expression recursively:
>>> from sympy import Function, Mul
>>> from sympy.core.function import AppliedUndef
>>> f = Function('f')
>>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function)
{f(x), sin(y + I*pi)}
>>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef)
{f(x)}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
{I*pi, 2*sin(y + I*pi)}
"""
if types:
types = tuple(
[t if isinstance(t, type) else type(t) for t in types])
nodes = preorder_traversal(self)
if types:
result = {node for node in nodes if isinstance(node, types)}
else:
result = {node for node in nodes if not node.args}
return result
@property
def free_symbols(self):
"""Return from the atoms of self those which are free symbols.
For most expressions, all symbols are free symbols. For some classes
this is not true. e.g. Integrals use Symbols for the dummy variables
which are bound variables, so Integral has a method to return all
symbols except those. Derivative keeps track of symbols with respect
to which it will perform a derivative; those are
bound variables, too, so it has its own free_symbols method.
Any other method that uses bound variables should implement a
free_symbols method."""
return set().union(*[a.free_symbols for a in self.args])
@property
def expr_free_symbols(self):
from sympy.utilities.exceptions import SymPyDeprecationWarning
SymPyDeprecationWarning(feature="expr_free_symbols method",
issue=21494,
deprecated_since_version="1.9").warn()
return set()
def as_dummy(self):
"""Return the expression with any objects having structurally
bound symbols replaced with unique, canonical symbols within
the object in which they appear and having only the default
assumption for commutativity being True. When applied to a
symbol a new symbol having only the same commutativity will be
returned.
Examples
========
>>> from sympy import Integral, Symbol
>>> from sympy.abc import x
>>> r = Symbol('r', real=True)
>>> Integral(r, (r, x)).as_dummy()
Integral(_0, (_0, x))
>>> _.variables[0].is_real is None
True
>>> r.as_dummy()
_r
Notes
=====
Any object that has structurally bound variables should have
a property, `bound_symbols` that returns those symbols
appearing in the object.
"""
from sympy.core.symbol import Dummy, Symbol
def can(x):
# mask free that shadow bound
free = x.free_symbols
bound = set(x.bound_symbols)
d = {i: Dummy() for i in bound & free}
x = x.subs(d)
# replace bound with canonical names
x = x.xreplace(x.canonical_variables)
# return after undoing masking
return x.xreplace({v: k for k, v in d.items()})
if not self.has(Symbol):
return self
return self.replace(
lambda x: hasattr(x, 'bound_symbols'),
lambda x: can(x),
simultaneous=False)
@property
def canonical_variables(self):
"""Return a dictionary mapping any variable defined in
``self.bound_symbols`` to Symbols that do not clash
with any free symbols in the expression.
Examples
========
>>> from sympy import Lambda
>>> from sympy.abc import x
>>> Lambda(x, 2*x).canonical_variables
{x: _0}
"""
from sympy.utilities.iterables import numbered_symbols
if not hasattr(self, 'bound_symbols'):
return {}
dums = numbered_symbols('_')
reps = {}
# watch out for free symbol that are not in bound symbols;
# those that are in bound symbols are about to get changed
bound = self.bound_symbols
names = {i.name for i in self.free_symbols - set(bound)}
for b in bound:
d = next(dums)
if b.is_Symbol:
while d.name in names:
d = next(dums)
reps[b] = d
return reps
def rcall(self, *args):
"""Apply on the argument recursively through the expression tree.
This method is used to simulate a common abuse of notation for
operators. For instance in SymPy the the following will not work:
``(x+Lambda(y, 2*y))(z) == x+2*z``,
however you can use
>>> from sympy import Lambda
>>> from sympy.abc import x, y, z
>>> (x + Lambda(y, 2*y)).rcall(z)
x + 2*z
"""
return Basic._recursive_call(self, args)
@staticmethod
def _recursive_call(expr_to_call, on_args):
"""Helper for rcall method."""
from sympy import Symbol
def the_call_method_is_overridden(expr):
for cls in getmro(type(expr)):
if '__call__' in cls.__dict__:
return cls != Basic
if callable(expr_to_call) and the_call_method_is_overridden(expr_to_call):
if isinstance(expr_to_call, Symbol): # XXX When you call a Symbol it is
return expr_to_call # transformed into an UndefFunction
else:
return expr_to_call(*on_args)
elif expr_to_call.args:
args = [Basic._recursive_call(
sub, on_args) for sub in expr_to_call.args]
return type(expr_to_call)(*args)
else:
return expr_to_call
def is_hypergeometric(self, k):
from sympy.simplify import hypersimp
from sympy.functions import Piecewise
if self.has(Piecewise):
return None
return hypersimp(self, k) is not None
@property
def is_comparable(self):
"""Return True if self can be computed to a real number
(or already is a real number) with precision, else False.
Examples
========
>>> from sympy import exp_polar, pi, I
>>> (I*exp_polar(I*pi/2)).is_comparable
True
>>> (I*exp_polar(I*pi*2)).is_comparable
False
A False result does not mean that `self` cannot be rewritten
into a form that would be comparable. For example, the
difference computed below is zero but without simplification
it does not evaluate to a zero with precision:
>>> e = 2**pi*(1 + 2**pi)
>>> dif = e - e.expand()
>>> dif.is_comparable
False
>>> dif.n(2)._prec
1
"""
is_extended_real = self.is_extended_real
if is_extended_real is False:
return False
if not self.is_number:
return False
# don't re-eval numbers that are already evaluated since
# this will create spurious precision
n, i = [p.evalf(2) if not p.is_Number else p
for p in self.as_real_imag()]
if not (i.is_Number and n.is_Number):
return False
if i:
# if _prec = 1 we can't decide and if not,
# the answer is False because numbers with
# imaginary parts can't be compared
# so return False
return False
else:
return n._prec != 1
@property
def func(self):
"""
The top-level function in an expression.
The following should hold for all objects::
>> x == x.func(*x.args)
Examples
========
>>> from sympy.abc import x
>>> a = 2*x
>>> a.func
<class 'sympy.core.mul.Mul'>
>>> a.args
(2, x)
>>> a.func(*a.args)
2*x
>>> a == a.func(*a.args)
True
"""
return self.__class__
@property
def args(self):
"""Returns a tuple of arguments of 'self'.
Examples
========
>>> from sympy import cot
>>> from sympy.abc import x, y
>>> cot(x).args
(x,)
>>> cot(x).args[0]
x
>>> (x*y).args
(x, y)
>>> (x*y).args[1]
y
Notes
=====
Never use self._args, always use self.args.
Only use _args in __new__ when creating a new function.
Don't override .args() from Basic (so that it's easy to
change the interface in the future if needed).
"""
return self._args
@property
def _sorted_args(self):
"""
The same as ``args``. Derived classes which don't fix an
order on their arguments should override this method to
produce the sorted representation.
"""
return self.args
def as_content_primitive(self, radical=False, clear=True):
"""A stub to allow Basic args (like Tuple) to be skipped when computing
the content and primitive components of an expression.
See Also
========
sympy.core.expr.Expr.as_content_primitive
"""
return S.One, self
def subs(self, *args, **kwargs):
"""
Substitutes old for new in an expression after sympifying args.
`args` is either:
- two arguments, e.g. foo.subs(old, new)
- one iterable argument, e.g. foo.subs(iterable). The iterable may be
o an iterable container with (old, new) pairs. In this case the
replacements are processed in the order given with successive
patterns possibly affecting replacements already made.
o a dict or set whose key/value items correspond to old/new pairs.
In this case the old/new pairs will be sorted by op count and in
case of a tie, by number of args and the default_sort_key. The
resulting sorted list is then processed as an iterable container
(see previous).
If the keyword ``simultaneous`` is True, the subexpressions will not be
evaluated until all the substitutions have been made.
Examples
========
>>> from sympy import pi, exp, limit, oo
>>> from sympy.abc import x, y
>>> (1 + x*y).subs(x, pi)
pi*y + 1
>>> (1 + x*y).subs({x:pi, y:2})
1 + 2*pi
>>> (1 + x*y).subs([(x, pi), (y, 2)])
1 + 2*pi
>>> reps = [(y, x**2), (x, 2)]
>>> (x + y).subs(reps)
6
>>> (x + y).subs(reversed(reps))
x**2 + 2
>>> (x**2 + x**4).subs(x**2, y)
y**2 + y
To replace only the x**2 but not the x**4, use xreplace:
>>> (x**2 + x**4).xreplace({x**2: y})
x**4 + y
To delay evaluation until all substitutions have been made,
set the keyword ``simultaneous`` to True:
>>> (x/y).subs([(x, 0), (y, 0)])
0
>>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True)
nan
This has the added feature of not allowing subsequent substitutions
to affect those already made:
>>> ((x + y)/y).subs({x + y: y, y: x + y})
1
>>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True)
y/(x + y)
In order to obtain a canonical result, unordered iterables are
sorted by count_op length, number of arguments and by the
default_sort_key to break any ties. All other iterables are left
unsorted.
>>> from sympy import sqrt, sin, cos
>>> from sympy.abc import a, b, c, d, e
>>> A = (sqrt(sin(2*x)), a)
>>> B = (sin(2*x), b)
>>> C = (cos(2*x), c)
>>> D = (x, d)
>>> E = (exp(x), e)
>>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)
>>> expr.subs(dict([A, B, C, D, E]))
a*c*sin(d*e) + b
The resulting expression represents a literal replacement of the
old arguments with the new arguments. This may not reflect the
limiting behavior of the expression:
>>> (x**3 - 3*x).subs({x: oo})
nan
>>> limit(x**3 - 3*x, x, oo)
oo
If the substitution will be followed by numerical
evaluation, it is better to pass the substitution to
evalf as
>>> (1/x).evalf(subs={x: 3.0}, n=21)
0.333333333333333333333
rather than
>>> (1/x).subs({x: 3.0}).evalf(21)
0.333333333333333314830
as the former will ensure that the desired level of precision is
obtained.
See Also
========
replace: replacement capable of doing wildcard-like matching,
parsing of match, and conditional replacements
xreplace: exact node replacement in expr tree; also capable of
using matching rules
sympy.core.evalf.EvalfMixin.evalf: calculates the given formula to a desired level of precision
"""
from sympy.core.compatibility import _nodes, default_sort_key
from sympy.core.containers import Dict
from sympy.core.symbol import Dummy, Symbol
from sympy.utilities.misc import filldedent
unordered = False
if len(args) == 1:
sequence = args[0]
if isinstance(sequence, set):
unordered = True
elif isinstance(sequence, (Dict, Mapping)):
unordered = True
sequence = sequence.items()
elif not iterable(sequence):
raise ValueError(filldedent("""
When a single argument is passed to subs
it should be a dictionary of old: new pairs or an iterable
of (old, new) tuples."""))
elif len(args) == 2:
sequence = [args]
else:
raise ValueError("subs accepts either 1 or 2 arguments")
sequence = list(sequence)
for i, s in enumerate(sequence):
if isinstance(s[0], str):
# when old is a string we prefer Symbol
s = Symbol(s[0]), s[1]
try:
s = [sympify(_, strict=not isinstance(_, (str, type)))
for _ in s]
except SympifyError:
# if it can't be sympified, skip it
sequence[i] = None
continue
# skip if there is no change
sequence[i] = None if _aresame(*s) else tuple(s)
sequence = list(filter(None, sequence))
if unordered:
sequence = dict(sequence)
# order so more complex items are first and items
# of identical complexity are ordered so
# f(x) < f(y) < x < y
# \___ 2 __/ \_1_/ <- number of nodes
#
# For more complex ordering use an unordered sequence.
k = list(ordered(sequence, default=False, keys=(
lambda x: -_nodes(x),
lambda x: default_sort_key(x),
)))
sequence = [(k, sequence[k]) for k in k]
if kwargs.pop('simultaneous', False): # XXX should this be the default for dict subs?
reps = {}
rv = self
kwargs['hack2'] = True
m = Dummy('subs_m')
for old, new in sequence:
com = new.is_commutative
if com is None:
com = True
d = Dummy('subs_d', commutative=com)
# using d*m so Subs will be used on dummy variables
# in things like Derivative(f(x, y), x) in which x
# is both free and bound
rv = rv._subs(old, d*m, **kwargs)
if not isinstance(rv, Basic):
break
reps[d] = new
reps[m] = S.One # get rid of m
return rv.xreplace(reps)
else:
rv = self
for old, new in sequence:
rv = rv._subs(old, new, **kwargs)
if not isinstance(rv, Basic):
break
return rv
@cacheit
def _subs(self, old, new, **hints):
"""Substitutes an expression old -> new.
If self is not equal to old then _eval_subs is called.
If _eval_subs doesn't want to make any special replacement
then a None is received which indicates that the fallback
should be applied wherein a search for replacements is made
amongst the arguments of self.
>>> from sympy import Add
>>> from sympy.abc import x, y, z
Examples
========
Add's _eval_subs knows how to target x + y in the following
so it makes the change:
>>> (x + y + z).subs(x + y, 1)
z + 1
Add's _eval_subs doesn't need to know how to find x + y in
the following:
>>> Add._eval_subs(z*(x + y) + 3, x + y, 1) is None
True
The returned None will cause the fallback routine to traverse the args and
pass the z*(x + y) arg to Mul where the change will take place and the
substitution will succeed:
>>> (z*(x + y) + 3).subs(x + y, 1)
z + 3
** Developers Notes **
An _eval_subs routine for a class should be written if:
1) any arguments are not instances of Basic (e.g. bool, tuple);
2) some arguments should not be targeted (as in integration
variables);
3) if there is something other than a literal replacement
that should be attempted (as in Piecewise where the condition
may be updated without doing a replacement).
If it is overridden, here are some special cases that might arise:
1) If it turns out that no special change was made and all
the original sub-arguments should be checked for
replacements then None should be returned.
2) If it is necessary to do substitutions on a portion of
the expression then _subs should be called. _subs will
handle the case of any sub-expression being equal to old
(which usually would not be the case) while its fallback
will handle the recursion into the sub-arguments. For
example, after Add's _eval_subs removes some matching terms
it must process the remaining terms so it calls _subs
on each of the un-matched terms and then adds them
onto the terms previously obtained.
3) If the initial expression should remain unchanged then
the original expression should be returned. (Whenever an
expression is returned, modified or not, no further
substitution of old -> new is attempted.) Sum's _eval_subs
routine uses this strategy when a substitution is attempted
on any of its summation variables.
"""
def fallback(self, old, new):
"""
Try to replace old with new in any of self's arguments.
"""
hit = False
args = list(self.args)
for i, arg in enumerate(args):
if not hasattr(arg, '_eval_subs'):
continue
arg = arg._subs(old, new, **hints)
if not _aresame(arg, args[i]):
hit = True
args[i] = arg
if hit:
rv = self.func(*args)
hack2 = hints.get('hack2', False)
if hack2 and self.is_Mul and not rv.is_Mul: # 2-arg hack
coeff = S.One
nonnumber = []
for i in args:
if i.is_Number:
coeff *= i
else:
nonnumber.append(i)
nonnumber = self.func(*nonnumber)
if coeff is S.One:
return nonnumber
else:
return self.func(coeff, nonnumber, evaluate=False)
return rv
return self
if _aresame(self, old):
return new
rv = self._eval_subs(old, new)
if rv is None:
rv = fallback(self, old, new)
return rv
def _eval_subs(self, old, new):
"""Override this stub if you want to do anything more than
attempt a replacement of old with new in the arguments of self.
See also
========
_subs
"""
return None
def xreplace(self, rule):
"""
Replace occurrences of objects within the expression.
Parameters
==========
rule : dict-like
Expresses a replacement rule
Returns
=======
xreplace : the result of the replacement
Examples
========
>>> from sympy import symbols, pi, exp
>>> x, y, z = symbols('x y z')
>>> (1 + x*y).xreplace({x: pi})
pi*y + 1
>>> (1 + x*y).xreplace({x: pi, y: 2})
1 + 2*pi
Replacements occur only if an entire node in the expression tree is
matched:
>>> (x*y + z).xreplace({x*y: pi})
z + pi
>>> (x*y*z).xreplace({x*y: pi})
x*y*z
>>> (2*x).xreplace({2*x: y, x: z})
y
>>> (2*2*x).xreplace({2*x: y, x: z})
4*z
>>> (x + y + 2).xreplace({x + y: 2})
x + y + 2
>>> (x + 2 + exp(x + 2)).xreplace({x + 2: y})
x + exp(y) + 2
xreplace doesn't differentiate between free and bound symbols. In the
following, subs(x, y) would not change x since it is a bound symbol,
but xreplace does:
>>> from sympy import Integral
>>> Integral(x, (x, 1, 2*x)).xreplace({x: y})
Integral(y, (y, 1, 2*y))
Trying to replace x with an expression raises an error:
>>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) # doctest: +SKIP
ValueError: Invalid limits given: ((2*y, 1, 4*y),)
See Also
========
replace: replacement capable of doing wildcard-like matching,
parsing of match, and conditional replacements
subs: substitution of subexpressions as defined by the objects
themselves.
"""
value, _ = self._xreplace(rule)
return value
def _xreplace(self, rule):
"""
Helper for xreplace. Tracks whether a replacement actually occurred.
"""
if self in rule:
return rule[self], True
elif rule:
args = []
changed = False
for a in self.args:
_xreplace = getattr(a, '_xreplace', None)
if _xreplace is not None:
a_xr = _xreplace(rule)
args.append(a_xr[0])
changed |= a_xr[1]
else:
args.append(a)
args = tuple(args)
if changed:
return self.func(*args), True
return self, False
@cacheit
def has(self, *patterns):
"""
Test whether any subexpression matches any of the patterns.
Examples
========
>>> from sympy import sin
>>> from sympy.abc import x, y, z
>>> (x**2 + sin(x*y)).has(z)
False
>>> (x**2 + sin(x*y)).has(x, y, z)
True
>>> x.has(x)
True
Note ``has`` is a structural algorithm with no knowledge of
mathematics. Consider the following half-open interval:
>>> from sympy.sets import Interval
>>> i = Interval.Lopen(0, 5); i
Interval.Lopen(0, 5)
>>> i.args
(0, 5, True, False)
>>> i.has(4) # there is no "4" in the arguments
False
>>> i.has(0) # there *is* a "0" in the arguments
True
Instead, use ``contains`` to determine whether a number is in the
interval or not:
>>> i.contains(4)
True
>>> i.contains(0)
False
Note that ``expr.has(*patterns)`` is exactly equivalent to
``any(expr.has(p) for p in patterns)``. In particular, ``False`` is
returned when the list of patterns is empty.
>>> x.has()
False
"""
return any(self._has(pattern) for pattern in patterns)
def _has(self, pattern):
"""Helper for .has()"""
from sympy.core.function import UndefinedFunction, Function
if isinstance(pattern, UndefinedFunction):
return any(f.func == pattern or f == pattern
for f in self.atoms(Function, UndefinedFunction))
if isinstance(pattern, BasicMeta):
subtrees = preorder_traversal(self)
return any(isinstance(arg, pattern) for arg in subtrees)
pattern = _sympify(pattern)
_has_matcher = getattr(pattern, '_has_matcher', None)
if _has_matcher is not None:
match = _has_matcher()
return any(match(arg) for arg in preorder_traversal(self))
else:
return any(arg == pattern for arg in preorder_traversal(self))
def _has_matcher(self):
"""Helper for .has()"""
return lambda other: self == other
def replace(self, query, value, map=False, simultaneous=True, exact=None):
"""
Replace matching subexpressions of ``self`` with ``value``.
If ``map = True`` then also return the mapping {old: new} where ``old``
was a sub-expression found with query and ``new`` is the replacement
value for it. If the expression itself doesn't match the query, then
the returned value will be ``self.xreplace(map)`` otherwise it should
be ``self.subs(ordered(map.items()))``.
Traverses an expression tree and performs replacement of matching
subexpressions from the bottom to the top of the tree. The default
approach is to do the replacement in a simultaneous fashion so
changes made are targeted only once. If this is not desired or causes
problems, ``simultaneous`` can be set to False.
In addition, if an expression containing more than one Wild symbol
is being used to match subexpressions and the ``exact`` flag is None
it will be set to True so the match will only succeed if all non-zero
values are received for each Wild that appears in the match pattern.
Setting this to False accepts a match of 0; while setting it True
accepts all matches that have a 0 in them. See example below for
cautions.
The list of possible combinations of queries and replacement values
is listed below:
Examples
========
Initial setup
>>> from sympy import log, sin, cos, tan, Wild, Mul, Add
>>> from sympy.abc import x, y
>>> f = log(sin(x)) + tan(sin(x**2))
1.1. type -> type
obj.replace(type, newtype)
When object of type ``type`` is found, replace it with the
result of passing its argument(s) to ``newtype``.
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> (x*y).replace(Mul, Add)
x + y
1.2. type -> func
obj.replace(type, func)
When object of type ``type`` is found, apply ``func`` to its
argument(s). ``func`` must be written to handle the number
of arguments of ``type``.
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args)))
sin(2*x*y)
2.1. pattern -> expr
obj.replace(pattern(wild), expr(wild))
Replace subexpressions matching ``pattern`` with the expression
written in terms of the Wild symbols in ``pattern``.
>>> a, b = map(Wild, 'ab')
>>> f.replace(sin(a), tan(a))
log(tan(x)) + tan(tan(x**2))
>>> f.replace(sin(a), tan(a/2))
log(tan(x/2)) + tan(tan(x**2/2))
>>> f.replace(sin(a), a)
log(x) + tan(x**2)
>>> (x*y).replace(a*x, a)
y
Matching is exact by default when more than one Wild symbol
is used: matching fails unless the match gives non-zero
values for all Wild symbols:
>>> (2*x + y).replace(a*x + b, b - a)
y - 2
>>> (2*x).replace(a*x + b, b - a)
2*x
When set to False, the results may be non-intuitive:
>>> (2*x).replace(a*x + b, b - a, exact=False)
2/x
2.2. pattern -> func
obj.replace(pattern(wild), lambda wild: expr(wild))
All behavior is the same as in 2.1 but now a function in terms of
pattern variables is used rather than an expression:
>>> f.replace(sin(a), lambda a: sin(2*a))
log(sin(2*x)) + tan(sin(2*x**2))
3.1. func -> func
obj.replace(filter, func)
Replace subexpression ``e`` with ``func(e)`` if ``filter(e)``
is True.
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
The expression itself is also targeted by the query but is done in
such a fashion that changes are not made twice.
>>> e = x*(x*y + 1)
>>> e.replace(lambda x: x.is_Mul, lambda x: 2*x)
2*x*(2*x*y + 1)
When matching a single symbol, `exact` will default to True, but
this may or may not be the behavior that is desired:
Here, we want `exact=False`:
>>> from sympy import Function
>>> f = Function('f')
>>> e = f(1) + f(0)
>>> q = f(a), lambda a: f(a + 1)
>>> e.replace(*q, exact=False)
f(1) + f(2)
>>> e.replace(*q, exact=True)
f(0) + f(2)
But here, the nature of matching makes selecting
the right setting tricky:
>>> e = x**(1 + y)
>>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=False)
x
>>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=True)
x**(-x - y + 1)
>>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=False)
x
>>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=True)
x**(1 - y)
It is probably better to use a different form of the query
that describes the target expression more precisely:
>>> (1 + x**(1 + y)).replace(
... lambda x: x.is_Pow and x.exp.is_Add and x.exp.args[0] == 1,
... lambda x: x.base**(1 - (x.exp - 1)))
...
x**(1 - y) + 1
See Also
========
subs: substitution of subexpressions as defined by the objects
themselves.
xreplace: exact node replacement in expr tree; also capable of
using matching rules
"""
from sympy.core.symbol import Wild
try:
query = _sympify(query)
except SympifyError:
pass
try:
value = _sympify(value)
except SympifyError:
pass
if isinstance(query, type):
_query = lambda expr: isinstance(expr, query)
if isinstance(value, type):
_value = lambda expr, result: value(*expr.args)
elif callable(value):
_value = lambda expr, result: value(*expr.args)
else:
raise TypeError(
"given a type, replace() expects another "
"type or a callable")
elif isinstance(query, Basic):
_query = lambda expr: expr.match(query)
if exact is None:
exact = (len(query.atoms(Wild)) > 1)
if isinstance(value, Basic):
if exact:
_value = lambda expr, result: (value.subs(result)
if all(result.values()) else expr)
else:
_value = lambda expr, result: value.subs(result)
elif callable(value):
# match dictionary keys get the trailing underscore stripped
# from them and are then passed as keywords to the callable;
# if ``exact`` is True, only accept match if there are no null
# values amongst those matched.
if exact:
_value = lambda expr, result: (value(**
{str(k)[:-1]: v for k, v in result.items()})
if all(val for val in result.values()) else expr)
else:
_value = lambda expr, result: value(**
{str(k)[:-1]: v for k, v in result.items()})
else:
raise TypeError(
"given an expression, replace() expects "
"another expression or a callable")
elif callable(query):
_query = query
if callable(value):
_value = lambda expr, result: value(expr)
else:
raise TypeError(
"given a callable, replace() expects "
"another callable")
else:
raise TypeError(
"first argument to replace() must be a "
"type, an expression or a callable")
def walk(rv, F):
"""Apply ``F`` to args and then to result.
"""
args = getattr(rv, 'args', None)
if args is not None:
if args:
newargs = tuple([walk(a, F) for a in args])
if args != newargs:
rv = rv.func(*newargs)
if simultaneous:
# if rv is something that was already
# matched (that was changed) then skip
# applying F again
for i, e in enumerate(args):
if rv == e and e != newargs[i]:
return rv
rv = F(rv)
return rv
mapping = {} # changes that took place
def rec_replace(expr):
result = _query(expr)
if result or result == {}:
v = _value(expr, result)
if v is not None and v != expr:
if map:
mapping[expr] = v
expr = v
return expr
rv = walk(self, rec_replace)
return (rv, mapping) if map else rv
def find(self, query, group=False):
"""Find all subexpressions matching a query. """
query = _make_find_query(query)
results = list(filter(query, preorder_traversal(self)))
if not group:
return set(results)
else:
groups = {}
for result in results:
if result in groups:
groups[result] += 1
else:
groups[result] = 1
return groups
def count(self, query):
"""Count the number of matching subexpressions. """
query = _make_find_query(query)
return sum(bool(query(sub)) for sub in preorder_traversal(self))
def matches(self, expr, repl_dict={}, old=False):
"""
Helper method for match() that looks for a match between Wild symbols
in self and expressions in expr.
Examples
========
>>> from sympy import symbols, Wild, Basic
>>> a, b, c = symbols('a b c')
>>> x = Wild('x')
>>> Basic(a + x, x).matches(Basic(a + b, c)) is None
True
>>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
{x_: b + c}
"""
repl_dict = repl_dict.copy()
expr = sympify(expr)
if not isinstance(expr, self.__class__):
return None
if self == expr:
return repl_dict
if len(self.args) != len(expr.args):
return None
d = repl_dict.copy()
for arg, other_arg in zip(self.args, expr.args):
if arg == other_arg:
continue
d = arg.xreplace(d).matches(other_arg, d, old=old)
if d is None:
return None
return d
def match(self, pattern, old=False):
"""
Pattern matching.
Wild symbols match all.
Return ``None`` when expression (self) does not match
with pattern. Otherwise return a dictionary such that::
pattern.xreplace(self.match(pattern)) == self
Examples
========
>>> from sympy import Wild, Sum
>>> from sympy.abc import x, y
>>> p = Wild("p")
>>> q = Wild("q")
>>> r = Wild("r")
>>> e = (x+y)**(x+y)
>>> e.match(p**p)
{p_: x + y}
>>> e.match(p**q)
{p_: x + y, q_: x + y}
>>> e = (2*x)**2
>>> e.match(p*q**r)
{p_: 4, q_: x, r_: 2}
>>> (p*q**r).xreplace(e.match(p*q**r))
4*x**2
Structurally bound symbols are ignored during matching:
>>> Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, p)))
{p_: 2}
But they can be identified if desired:
>>> Sum(x, (x, 1, 2)).match(Sum(q, (q, 1, p)))
{p_: 2, q_: x}
The ``old`` flag will give the old-style pattern matching where
expressions and patterns are essentially solved to give the
match. Both of the following give None unless ``old=True``:
>>> (x - 2).match(p - x, old=True)
{p_: 2*x - 2}
>>> (2/x).match(p*x, old=True)
{p_: 2/x**2}
"""
from sympy.core.symbol import Wild
from sympy.core.function import WildFunction
from sympy.utilities.misc import filldedent
pattern = sympify(pattern)
# match non-bound symbols
canonical = lambda x: x if x.is_Symbol else x.as_dummy()
m = canonical(pattern).matches(canonical(self), old=old)
if m is None:
return m
wild = pattern.atoms(Wild, WildFunction)
# sanity check
if set(m) - wild:
raise ValueError(filldedent('''
Some `matches` routine did not use a copy of repl_dict
and injected unexpected symbols. Report this as an
error at https://github.com/sympy/sympy/issues'''))
# now see if bound symbols were requested
bwild = wild - set(m)
if not bwild:
return m
# replace free-Wild symbols in pattern with match result
# so they will match but not be in the next match
wpat = pattern.xreplace(m)
# identify remaining bound wild
w = wpat.matches(self, old=old)
# add them to m
if w:
m.update(w)
# done
return m
def count_ops(self, visual=None):
"""wrapper for count_ops that returns the operation count."""
from sympy import count_ops
return count_ops(self, visual)
def doit(self, **hints):
"""Evaluate objects that are not evaluated by default like limits,
integrals, sums and products. All objects of this kind will be
evaluated recursively, unless some species were excluded via 'hints'
or unless the 'deep' hint was set to 'False'.
>>> from sympy import Integral
>>> from sympy.abc import x
>>> 2*Integral(x, x)
2*Integral(x, x)
>>> (2*Integral(x, x)).doit()
x**2
>>> (2*Integral(x, x)).doit(deep=False)
2*Integral(x, x)
"""
if hints.get('deep', True):
terms = [term.doit(**hints) if isinstance(term, Basic) else term
for term in self.args]
return self.func(*terms)
else:
return self
def simplify(self, **kwargs):
"""See the simplify function in sympy.simplify"""
from sympy.simplify import simplify
return simplify(self, **kwargs)
def refine(self, assumption=True):
"""See the refine function in sympy.assumptions"""
from sympy.assumptions import refine
return refine(self, assumption)
def _eval_rewrite(self, pattern, rule, **hints):
if self.is_Atom:
if hasattr(self, rule):
return getattr(self, rule)()
return self
if hints.get('deep', True):
args = [a._eval_rewrite(pattern, rule, **hints)
if isinstance(a, Basic) else a
for a in self.args]
else:
args = self.args
if pattern is None or isinstance(self, pattern):
if hasattr(self, rule):
rewritten = getattr(self, rule)(*args, **hints)
if rewritten is not None:
return rewritten
return self.func(*args) if hints.get('evaluate', True) else self
def _eval_derivative_n_times(self, s, n):
# This is the default evaluator for derivatives (as called by `diff`
# and `Derivative`), it will attempt a loop to derive the expression
# `n` times by calling the corresponding `_eval_derivative` method,
# while leaving the derivative unevaluated if `n` is symbolic. This
# method should be overridden if the object has a closed form for its
# symbolic n-th derivative.
from sympy import Integer
if isinstance(n, (int, Integer)):
obj = self
for i in range(n):
obj2 = obj._eval_derivative(s)
if obj == obj2 or obj2 is None:
break
obj = obj2
return obj2
else:
return None
def rewrite(self, *args, **hints):
""" Rewrite functions in terms of other functions.
Rewrites expression containing applications of functions
of one kind in terms of functions of different kind. For
example you can rewrite trigonometric functions as complex
exponentials or combinatorial functions as gamma function.
As a pattern this function accepts a list of functions to
to rewrite (instances of DefinedFunction class). As rule
you can use string or a destination function instance (in
this case rewrite() will use the str() function).
There is also the possibility to pass hints on how to rewrite
the given expressions. For now there is only one such hint
defined called 'deep'. When 'deep' is set to False it will
forbid functions to rewrite their contents.
Examples
========
>>> from sympy import sin, exp
>>> from sympy.abc import x
Unspecified pattern:
>>> sin(x).rewrite(exp)
-I*(exp(I*x) - exp(-I*x))/2
Pattern as a single function:
>>> sin(x).rewrite(sin, exp)
-I*(exp(I*x) - exp(-I*x))/2
Pattern as a list of functions:
>>> sin(x).rewrite([sin, ], exp)
-I*(exp(I*x) - exp(-I*x))/2
"""
if not args:
return self
else:
pattern = args[:-1]
if isinstance(args[-1], str):
rule = '_eval_rewrite_as_' + args[-1]
else:
# rewrite arg is usually a class but can also be a
# singleton (e.g. GoldenRatio) so we check
# __name__ or __class__.__name__
clsname = getattr(args[-1], "__name__", None)
if clsname is None:
clsname = args[-1].__class__.__name__
rule = '_eval_rewrite_as_' + clsname
if not pattern:
return self._eval_rewrite(None, rule, **hints)
else:
if iterable(pattern[0]):
pattern = pattern[0]
pattern = [p for p in pattern if self.has(p)]
if pattern:
return self._eval_rewrite(tuple(pattern), rule, **hints)
else:
return self
_constructor_postprocessor_mapping = {} # type: ignore
@classmethod
def _exec_constructor_postprocessors(cls, obj):
# WARNING: This API is experimental.
# This is an experimental API that introduces constructor
# postprosessors for SymPy Core elements. If an argument of a SymPy
# expression has a `_constructor_postprocessor_mapping` attribute, it will
# be interpreted as a dictionary containing lists of postprocessing
# functions for matching expression node names.
clsname = obj.__class__.__name__
postprocessors = defaultdict(list)
for i in obj.args:
try:
postprocessor_mappings = (
Basic._constructor_postprocessor_mapping[cls].items()
for cls in type(i).mro()
if cls in Basic._constructor_postprocessor_mapping
)
for k, v in chain.from_iterable(postprocessor_mappings):
postprocessors[k].extend([j for j in v if j not in postprocessors[k]])
except TypeError:
pass
for f in postprocessors.get(clsname, []):
obj = f(obj)
return obj
class Atom(Basic):
"""
A parent class for atomic things. An atom is an expression with no subexpressions.
Examples
========
Symbol, Number, Rational, Integer, ...
But not: Add, Mul, Pow, ...
"""
is_Atom = True
__slots__ = ()
def matches(self, expr, repl_dict={}, old=False):
if self == expr:
return repl_dict.copy()
def xreplace(self, rule, hack2=False):
return rule.get(self, self)
def doit(self, **hints):
return self
@classmethod
def class_key(cls):
return 2, 0, cls.__name__
@cacheit
def sort_key(self, order=None):
return self.class_key(), (1, (str(self),)), S.One.sort_key(), S.One
def _eval_simplify(self, **kwargs):
return self
@property
def _sorted_args(self):
# this is here as a safeguard against accidentally using _sorted_args
# on Atoms -- they cannot be rebuilt as atom.func(*atom._sorted_args)
# since there are no args. So the calling routine should be checking
# to see that this property is not called for Atoms.
raise AttributeError('Atoms have no args. It might be necessary'
' to make a check for Atoms in the calling code.')
def _aresame(a, b):
"""Return True if a and b are structurally the same, else False.
Examples
========
In SymPy (as in Python) two numbers compare the same if they
have the same underlying base-2 representation even though
they may not be the same type:
>>> from sympy import S
>>> 2.0 == S(2)
True
>>> 0.5 == S.Half
True
This routine was written to provide a query for such cases that
would give false when the types do not match:
>>> from sympy.core.basic import _aresame
>>> _aresame(S(2.0), S(2))
False
"""
from .numbers import Number
from .function import AppliedUndef, UndefinedFunction as UndefFunc
if isinstance(a, Number) and isinstance(b, Number):
return a == b and a.__class__ == b.__class__
for i, j in zip_longest(preorder_traversal(a), preorder_traversal(b)):
if i != j or type(i) != type(j):
if ((isinstance(i, UndefFunc) and isinstance(j, UndefFunc)) or
(isinstance(i, AppliedUndef) and isinstance(j, AppliedUndef))):
if i.class_key() != j.class_key():
return False
else:
return False
return True
def _ne(a, b):
# use this as a second test after `a != b` if you want to make
# sure that things are truly equal, e.g.
# a, b = 0.5, S.Half
# a !=b or _ne(a, b) -> True
from .numbers import Number
# 0.5 == S.Half
if isinstance(a, Number) and isinstance(b, Number):
return a.__class__ != b.__class__
def _atomic(e, recursive=False):
"""Return atom-like quantities as far as substitution is
concerned: Derivatives, Functions and Symbols. Don't
return any 'atoms' that are inside such quantities unless
they also appear outside, too, unless `recursive` is True.
Examples
========
>>> from sympy import Derivative, Function, cos
>>> from sympy.abc import x, y
>>> from sympy.core.basic import _atomic
>>> f = Function('f')
>>> _atomic(x + y)
{x, y}
>>> _atomic(x + f(y))
{x, f(y)}
>>> _atomic(Derivative(f(x), x) + cos(x) + y)
{y, cos(x), Derivative(f(x), x)}
"""
from sympy import Derivative, Function, Symbol
pot = preorder_traversal(e)
seen = set()
if isinstance(e, Basic):
free = getattr(e, "free_symbols", None)
if free is None:
return {e}
else:
return set()
atoms = set()
for p in pot:
if p in seen:
pot.skip()
continue
seen.add(p)
if isinstance(p, Symbol) and p in free:
atoms.add(p)
elif isinstance(p, (Derivative, Function)):
if not recursive:
pot.skip()
atoms.add(p)
return atoms
class preorder_traversal:
"""
Do a pre-order traversal of a tree.
This iterator recursively yields nodes that it has visited in a pre-order
fashion. That is, it yields the current node then descends through the
tree breadth-first to yield all of a node's children's pre-order
traversal.
For an expression, the order of the traversal depends on the order of
.args, which in many cases can be arbitrary.
Parameters
==========
node : sympy expression
The expression to traverse.
keys : (default None) sort key(s)
The key(s) used to sort args of Basic objects. When None, args of Basic
objects are processed in arbitrary order. If key is defined, it will
be passed along to ordered() as the only key(s) to use to sort the
arguments; if ``key`` is simply True then the default keys of ordered
will be used.
Yields
======
subtree : sympy expression
All of the subtrees in the tree.
Examples
========
>>> from sympy import symbols
>>> from sympy.core.basic import preorder_traversal
>>> x, y, z = symbols('x y z')
The nodes are returned in the order that they are encountered unless key
is given; simply passing key=True will guarantee that the traversal is
unique.
>>> list(preorder_traversal((x + y)*z, keys=None)) # doctest: +SKIP
[z*(x + y), z, x + y, y, x]
>>> list(preorder_traversal((x + y)*z, keys=True))
[z*(x + y), z, x + y, x, y]
"""
def __init__(self, node, keys=None):
self._skip_flag = False
self._pt = self._preorder_traversal(node, keys)
def _preorder_traversal(self, node, keys):
yield node
if self._skip_flag:
self._skip_flag = False
return
if isinstance(node, Basic):
if not keys and hasattr(node, '_argset'):
# LatticeOp keeps args as a set. We should use this if we
# don't care about the order, to prevent unnecessary sorting.
args = node._argset
else:
args = node.args
if keys:
if keys != True:
args = ordered(args, keys, default=False)
else:
args = ordered(args)
for arg in args:
yield from self._preorder_traversal(arg, keys)
elif iterable(node):
for item in node:
yield from self._preorder_traversal(item, keys)
def skip(self):
"""
Skip yielding current node's (last yielded node's) subtrees.
Examples
========
>>> from sympy.core import symbols
>>> from sympy.core.basic import preorder_traversal
>>> x, y, z = symbols('x y z')
>>> pt = preorder_traversal((x+y*z)*z)
>>> for i in pt:
... print(i)
... if i == x+y*z:
... pt.skip()
z*(x + y*z)
z
x + y*z
"""
self._skip_flag = True
def __next__(self):
return next(self._pt)
def __iter__(self):
return self
def _make_find_query(query):
"""Convert the argument of Basic.find() into a callable"""
try:
query = _sympify(query)
except SympifyError:
pass
if isinstance(query, type):
return lambda expr: isinstance(expr, query)
elif isinstance(query, Basic):
return lambda expr: expr.match(query) is not None
return query
# Delayed to avoid cyclic import
from .singleton import S
|
8886e8e825da595d9aa54779a070a900aebac2f7510a760e9f87151c6dcedd09 | from typing import Callable
from math import log as _log
from .sympify import _sympify
from .cache import cacheit
from .singleton import S
from .expr import Expr
from .evalf import PrecisionExhausted
from .function import (_coeff_isneg, expand_complex, expand_multinomial,
expand_mul, _mexpand)
from .logic import fuzzy_bool, fuzzy_not, fuzzy_and, fuzzy_or
from .compatibility import as_int, HAS_GMPY, gmpy
from .parameters import global_parameters
from sympy.utilities.iterables import sift
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.multipledispatch import Dispatcher
from mpmath.libmp import sqrtrem as mpmath_sqrtrem
from math import sqrt as _sqrt
def isqrt(n):
"""Return the largest integer less than or equal to sqrt(n)."""
if n < 0:
raise ValueError("n must be nonnegative")
n = int(n)
# Fast path: with IEEE 754 binary64 floats and a correctly-rounded
# math.sqrt, int(math.sqrt(n)) works for any integer n satisfying 0 <= n <
# 4503599761588224 = 2**52 + 2**27. But Python doesn't guarantee either
# IEEE 754 format floats *or* correct rounding of math.sqrt, so check the
# answer and fall back to the slow method if necessary.
if n < 4503599761588224:
s = int(_sqrt(n))
if 0 <= n - s*s <= 2*s:
return s
return integer_nthroot(n, 2)[0]
def integer_nthroot(y, n):
"""
Return a tuple containing x = floor(y**(1/n))
and a boolean indicating whether the result is exact (that is,
whether x**n == y).
Examples
========
>>> from sympy import integer_nthroot
>>> integer_nthroot(16, 2)
(4, True)
>>> integer_nthroot(26, 2)
(5, False)
To simply determine if a number is a perfect square, the is_square
function should be used:
>>> from sympy.ntheory.primetest import is_square
>>> is_square(26)
False
See Also
========
sympy.ntheory.primetest.is_square
integer_log
"""
y, n = as_int(y), as_int(n)
if y < 0:
raise ValueError("y must be nonnegative")
if n < 1:
raise ValueError("n must be positive")
if HAS_GMPY and n < 2**63:
# Currently it works only for n < 2**63, else it produces TypeError
# sympy issue: https://github.com/sympy/sympy/issues/18374
# gmpy2 issue: https://github.com/aleaxit/gmpy/issues/257
if HAS_GMPY >= 2:
x, t = gmpy.iroot(y, n)
else:
x, t = gmpy.root(y, n)
return as_int(x), bool(t)
return _integer_nthroot_python(y, n)
def _integer_nthroot_python(y, n):
if y in (0, 1):
return y, True
if n == 1:
return y, True
if n == 2:
x, rem = mpmath_sqrtrem(y)
return int(x), not rem
if n > y:
return 1, False
# Get initial estimate for Newton's method. Care must be taken to
# avoid overflow
try:
guess = int(y**(1./n) + 0.5)
except OverflowError:
exp = _log(y, 2)/n
if exp > 53:
shift = int(exp - 53)
guess = int(2.0**(exp - shift) + 1) << shift
else:
guess = int(2.0**exp)
if guess > 2**50:
# Newton iteration
xprev, x = -1, guess
while 1:
t = x**(n - 1)
xprev, x = x, ((n - 1)*x + y//t)//n
if abs(x - xprev) < 2:
break
else:
x = guess
# Compensate
t = x**n
while t < y:
x += 1
t = x**n
while t > y:
x -= 1
t = x**n
return int(x), t == y # int converts long to int if possible
def integer_log(y, x):
r"""
Returns ``(e, bool)`` where e is the largest nonnegative integer
such that :math:`|y| \geq |x^e|` and ``bool`` is True if $y = x^e$.
Examples
========
>>> from sympy import integer_log
>>> integer_log(125, 5)
(3, True)
>>> integer_log(17, 9)
(1, False)
>>> integer_log(4, -2)
(2, True)
>>> integer_log(-125,-5)
(3, True)
See Also
========
integer_nthroot
sympy.ntheory.primetest.is_square
sympy.ntheory.factor_.multiplicity
sympy.ntheory.factor_.perfect_power
"""
if x == 1:
raise ValueError('x cannot take value as 1')
if y == 0:
raise ValueError('y cannot take value as 0')
if x in (-2, 2):
x = int(x)
y = as_int(y)
e = y.bit_length() - 1
return e, x**e == y
if x < 0:
n, b = integer_log(y if y > 0 else -y, -x)
return n, b and bool(n % 2 if y < 0 else not n % 2)
x = as_int(x)
y = as_int(y)
r = e = 0
while y >= x:
d = x
m = 1
while y >= d:
y, rem = divmod(y, d)
r = r or rem
e += m
if y > d:
d *= d
m *= 2
return e, r == 0 and y == 1
class Pow(Expr):
"""
Defines the expression x**y as "x raised to a power y"
Singleton definitions involving (0, 1, -1, oo, -oo, I, -I):
+--------------+---------+-----------------------------------------------+
| expr | value | reason |
+==============+=========+===============================================+
| z**0 | 1 | Although arguments over 0**0 exist, see [2]. |
+--------------+---------+-----------------------------------------------+
| z**1 | z | |
+--------------+---------+-----------------------------------------------+
| (-oo)**(-1) | 0 | |
+--------------+---------+-----------------------------------------------+
| (-1)**-1 | -1 | |
+--------------+---------+-----------------------------------------------+
| S.Zero**-1 | zoo | This is not strictly true, as 0**-1 may be |
| | | undefined, but is convenient in some contexts |
| | | where the base is assumed to be positive. |
+--------------+---------+-----------------------------------------------+
| 1**-1 | 1 | |
+--------------+---------+-----------------------------------------------+
| oo**-1 | 0 | |
+--------------+---------+-----------------------------------------------+
| 0**oo | 0 | Because for all complex numbers z near |
| | | 0, z**oo -> 0. |
+--------------+---------+-----------------------------------------------+
| 0**-oo | zoo | This is not strictly true, as 0**oo may be |
| | | oscillating between positive and negative |
| | | values or rotating in the complex plane. |
| | | It is convenient, however, when the base |
| | | is positive. |
+--------------+---------+-----------------------------------------------+
| 1**oo | nan | Because there are various cases where |
| 1**-oo | | lim(x(t),t)=1, lim(y(t),t)=oo (or -oo), |
| | | but lim( x(t)**y(t), t) != 1. See [3]. |
+--------------+---------+-----------------------------------------------+
| b**zoo | nan | Because b**z has no limit as z -> zoo |
+--------------+---------+-----------------------------------------------+
| (-1)**oo | nan | Because of oscillations in the limit. |
| (-1)**(-oo) | | |
+--------------+---------+-----------------------------------------------+
| oo**oo | oo | |
+--------------+---------+-----------------------------------------------+
| oo**-oo | 0 | |
+--------------+---------+-----------------------------------------------+
| (-oo)**oo | nan | |
| (-oo)**-oo | | |
+--------------+---------+-----------------------------------------------+
| oo**I | nan | oo**e could probably be best thought of as |
| (-oo)**I | | the limit of x**e for real x as x tends to |
| | | oo. If e is I, then the limit does not exist |
| | | and nan is used to indicate that. |
+--------------+---------+-----------------------------------------------+
| oo**(1+I) | zoo | If the real part of e is positive, then the |
| (-oo)**(1+I) | | limit of abs(x**e) is oo. So the limit value |
| | | is zoo. |
+--------------+---------+-----------------------------------------------+
| oo**(-1+I) | 0 | If the real part of e is negative, then the |
| -oo**(-1+I) | | limit is 0. |
+--------------+---------+-----------------------------------------------+
Because symbolic computations are more flexible that floating point
calculations and we prefer to never return an incorrect answer,
we choose not to conform to all IEEE 754 conventions. This helps
us avoid extra test-case code in the calculation of limits.
See Also
========
sympy.core.numbers.Infinity
sympy.core.numbers.NegativeInfinity
sympy.core.numbers.NaN
References
==========
.. [1] https://en.wikipedia.org/wiki/Exponentiation
.. [2] https://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_power_of_zero
.. [3] https://en.wikipedia.org/wiki/Indeterminate_forms
"""
is_Pow = True
__slots__ = ('is_commutative',)
@cacheit
def __new__(cls, b, e, evaluate=None):
if evaluate is None:
evaluate = global_parameters.evaluate
from sympy.functions.elementary.exponential import exp_polar
b = _sympify(b)
e = _sympify(e)
# XXX: This can be removed when non-Expr args are disallowed rather
# than deprecated.
from sympy.core.relational import Relational
if isinstance(b, Relational) or isinstance(e, Relational):
raise TypeError('Relational can not be used in Pow')
# XXX: This should raise TypeError once deprecation period is over:
if not (isinstance(b, Expr) and isinstance(e, Expr)):
SymPyDeprecationWarning(
feature="Pow with non-Expr args",
useinstead="Expr args",
issue=19445,
deprecated_since_version="1.7"
).warn()
if evaluate:
if b is S.Zero and e is S.NegativeInfinity:
return S.ComplexInfinity
if e is S.ComplexInfinity:
return S.NaN
if e is S.Zero:
return S.One
elif e is S.One:
return b
elif e == -1 and not b:
return S.ComplexInfinity
elif e.__class__.__name__ == "AccumulationBounds":
if b == S.Exp1:
from sympy import AccumBounds
return AccumBounds(Pow(b, e.min), Pow(b, e.max))
# Only perform autosimplification if exponent or base is a Symbol or number
elif (b.is_Symbol or b.is_number) and (e.is_Symbol or e.is_number) and\
e.is_integer and _coeff_isneg(b):
if e.is_even:
b = -b
elif e.is_odd:
return -Pow(-b, e)
if S.NaN in (b, e): # XXX S.NaN**x -> S.NaN under assumption that x != 0
return S.NaN
elif b is S.One:
if abs(e).is_infinite:
return S.NaN
return S.One
else:
# recognize base as E
if not e.is_Atom and b is not S.Exp1 and not isinstance(b, exp_polar):
from sympy import numer, denom, log, sign, im, factor_terms
c, ex = factor_terms(e, sign=False).as_coeff_Mul()
den = denom(ex)
if isinstance(den, log) and den.args[0] == b:
return S.Exp1**(c*numer(ex))
elif den.is_Add:
s = sign(im(b))
if s.is_Number and s and den == \
log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi:
return S.Exp1**(c*numer(ex))
obj = b._eval_power(e)
if obj is not None:
return obj
obj = Expr.__new__(cls, b, e)
obj = cls._exec_constructor_postprocessors(obj)
if not isinstance(obj, Pow):
return obj
obj.is_commutative = (b.is_commutative and e.is_commutative)
return obj
def inverse(self, argindex=1):
if self.base == S.Exp1:
from sympy import log
return log
return None
@property
def base(self):
return self._args[0]
@property
def exp(self):
return self._args[1]
@classmethod
def class_key(cls):
return 3, 2, cls.__name__
def _eval_refine(self, assumptions):
from sympy.assumptions.ask import ask, Q
b, e = self.as_base_exp()
if ask(Q.integer(e), assumptions) and _coeff_isneg(b):
if ask(Q.even(e), assumptions):
return Pow(-b, e)
elif ask(Q.odd(e), assumptions):
return -Pow(-b, e)
def _eval_power(self, other):
from sympy import arg, exp, floor, im, log, re, sign
b, e = self.as_base_exp()
if b is S.NaN:
return (b**e)**other # let __new__ handle it
s = None
if other.is_integer:
s = 1
elif b.is_polar: # e.g. exp_polar, besselj, var('p', polar=True)...
s = 1
elif e.is_extended_real is not None:
# helper functions ===========================
def _half(e):
"""Return True if the exponent has a literal 2 as the
denominator, else None."""
if getattr(e, 'q', None) == 2:
return True
n, d = e.as_numer_denom()
if n.is_integer and d == 2:
return True
def _n2(e):
"""Return ``e`` evaluated to a Number with 2 significant
digits, else None."""
try:
rv = e.evalf(2, strict=True)
if rv.is_Number:
return rv
except PrecisionExhausted:
pass
# ===================================================
if e.is_extended_real:
# we need _half(other) with constant floor or
# floor(S.Half - e*arg(b)/2/pi) == 0
# handle -1 as special case
if e == -1:
# floor arg. is 1/2 + arg(b)/2/pi
if _half(other):
if b.is_negative is True:
return S.NegativeOne**other*Pow(-b, e*other)
elif b.is_negative is False:
return Pow(b, -other)
elif e.is_even:
if b.is_extended_real:
b = abs(b)
if b.is_imaginary:
b = abs(im(b))*S.ImaginaryUnit
if (abs(e) < 1) == True or e == 1:
s = 1 # floor = 0
elif b.is_extended_nonnegative:
s = 1 # floor = 0
elif re(b).is_extended_nonnegative and (abs(e) < 2) == True:
s = 1 # floor = 0
elif fuzzy_not(im(b).is_zero) and abs(e) == 2:
s = 1 # floor = 0
elif _half(other):
s = exp(2*S.Pi*S.ImaginaryUnit*other*floor(
S.Half - e*arg(b)/(2*S.Pi)))
if s.is_extended_real and _n2(sign(s) - s) == 0:
s = sign(s)
else:
s = None
else:
# e.is_extended_real is False requires:
# _half(other) with constant floor or
# floor(S.Half - im(e*log(b))/2/pi) == 0
try:
s = exp(2*S.ImaginaryUnit*S.Pi*other*
floor(S.Half - im(e*log(b))/2/S.Pi))
# be careful to test that s is -1 or 1 b/c sign(I) == I:
# so check that s is real
if s.is_extended_real and _n2(sign(s) - s) == 0:
s = sign(s)
else:
s = None
except PrecisionExhausted:
s = None
if s is not None:
return s*Pow(b, e*other)
def _eval_Mod(self, q):
r"""A dispatched function to compute `b^e \bmod q`, dispatched
by ``Mod``.
Notes
=====
Algorithms:
1. For unevaluated integer power, use built-in ``pow`` function
with 3 arguments, if powers are not too large wrt base.
2. For very large powers, use totient reduction if e >= lg(m).
Bound on m, is for safe factorization memory wise ie m^(1/4).
For pollard-rho to be faster than built-in pow lg(e) > m^(1/4)
check is added.
3. For any unevaluated power found in `b` or `e`, the step 2
will be recursed down to the base and the exponent
such that the `b \bmod q` becomes the new base and
``\phi(q) + e \bmod \phi(q)`` becomes the new exponent, and then
the computation for the reduced expression can be done.
"""
from sympy.ntheory import totient
from .mod import Mod
base, exp = self.base, self.exp
if exp.is_integer and exp.is_positive:
if q.is_integer and base % q == 0:
return S.Zero
if base.is_Integer and exp.is_Integer and q.is_Integer:
b, e, m = int(base), int(exp), int(q)
mb = m.bit_length()
if mb <= 80 and e >= mb and e.bit_length()**4 >= m:
phi = totient(m)
return Integer(pow(b, phi + e%phi, m))
return Integer(pow(b, e, m))
if isinstance(base, Pow) and base.is_integer and base.is_number:
base = Mod(base, q)
return Mod(Pow(base, exp, evaluate=False), q)
if isinstance(exp, Pow) and exp.is_integer and exp.is_number:
bit_length = int(q).bit_length()
# XXX Mod-Pow actually attempts to do a hanging evaluation
# if this dispatched function returns None.
# May need some fixes in the dispatcher itself.
if bit_length <= 80:
phi = totient(q)
exp = phi + Mod(exp, phi)
return Mod(Pow(base, exp, evaluate=False), q)
def _eval_is_even(self):
if self.exp.is_integer and self.exp.is_positive:
return self.base.is_even
def _eval_is_negative(self):
ext_neg = Pow._eval_is_extended_negative(self)
if ext_neg is True:
return self.is_finite
return ext_neg
def _eval_is_positive(self):
ext_pos = Pow._eval_is_extended_positive(self)
if ext_pos is True:
return self.is_finite
return ext_pos
def _eval_is_extended_positive(self):
from sympy import log
if self.base == self.exp:
if self.base.is_extended_nonnegative:
return True
elif self.base.is_positive:
if self.exp.is_real:
return True
elif self.base.is_extended_negative:
if self.exp.is_even:
return True
if self.exp.is_odd:
return False
elif self.base.is_zero:
if self.exp.is_extended_real:
return self.exp.is_zero
elif self.base.is_extended_nonpositive:
if self.exp.is_odd:
return False
elif self.base.is_imaginary:
if self.exp.is_integer:
m = self.exp % 4
if m.is_zero:
return True
if m.is_integer and m.is_zero is False:
return False
if self.exp.is_imaginary:
return log(self.base).is_imaginary
def _eval_is_extended_negative(self):
if self.exp is S(1)/2:
if self.base.is_complex or self.base.is_extended_real:
return False
if self.base.is_extended_negative:
if self.exp.is_odd and self.base.is_finite:
return True
if self.exp.is_even:
return False
elif self.base.is_extended_positive:
if self.exp.is_extended_real:
return False
elif self.base.is_zero:
if self.exp.is_extended_real:
return False
elif self.base.is_extended_nonnegative:
if self.exp.is_extended_nonnegative:
return False
elif self.base.is_extended_nonpositive:
if self.exp.is_even:
return False
elif self.base.is_extended_real:
if self.exp.is_even:
return False
def _eval_is_zero(self):
if self.base.is_zero:
if self.exp.is_extended_positive:
return True
elif self.exp.is_extended_nonpositive:
return False
elif self.base == S.Exp1:
return self.exp is S.NegativeInfinity
elif self.base.is_zero is False:
if self.base.is_finite and self.exp.is_finite:
return False
elif self.exp.is_negative:
return self.base.is_infinite
elif self.exp.is_nonnegative:
return False
elif self.exp.is_infinite and self.exp.is_extended_real:
if (1 - abs(self.base)).is_extended_positive:
return self.exp.is_extended_positive
elif (1 - abs(self.base)).is_extended_negative:
return self.exp.is_extended_negative
elif self.base.is_finite and self.exp.is_negative:
# when self.base.is_zero is None
return False
def _eval_is_integer(self):
b, e = self.args
if b.is_rational:
if b.is_integer is False and e.is_positive:
return False # rat**nonneg
if b.is_integer and e.is_integer:
if b is S.NegativeOne:
return True
if e.is_nonnegative or e.is_positive:
return True
if b.is_integer and e.is_negative and (e.is_finite or e.is_integer):
if fuzzy_not((b - 1).is_zero) and fuzzy_not((b + 1).is_zero):
return False
if b.is_Number and e.is_Number:
check = self.func(*self.args)
return check.is_Integer
if e.is_negative and b.is_positive and (b - 1).is_positive:
return False
if e.is_negative and b.is_negative and (b + 1).is_negative:
return False
def _eval_is_extended_real(self):
from ..functions import arg, log, exp
from .mul import Mul
if self.base is S.Exp1:
if self.exp.is_extended_real:
return True
elif self.exp.is_imaginary:
return (2*S.ImaginaryUnit*self.exp/S.Pi).is_even
real_b = self.base.is_extended_real
if real_b is None:
if self.base.func == exp and self.base.exp.is_imaginary:
return self.exp.is_imaginary
if self.base.func == Pow and self.base.base is S.Exp1 and self.base.exp.is_imaginary:
return self.exp.is_imaginary
return
real_e = self.exp.is_extended_real
if real_e is None:
return
if real_b and real_e:
if self.base.is_extended_positive:
return True
elif self.base.is_extended_nonnegative and self.exp.is_extended_nonnegative:
return True
elif self.exp.is_integer and self.base.is_extended_nonzero:
return True
elif self.exp.is_integer and self.exp.is_nonnegative:
return True
elif self.base.is_extended_negative:
if self.exp.is_Rational:
return False
if real_e and self.exp.is_extended_negative and self.base.is_zero is False:
return Pow(self.base, -self.exp).is_extended_real
im_b = self.base.is_imaginary
im_e = self.exp.is_imaginary
if im_b:
if self.exp.is_integer:
if self.exp.is_even:
return True
elif self.exp.is_odd:
return False
elif im_e and log(self.base).is_imaginary:
return True
elif self.exp.is_Add:
c, a = self.exp.as_coeff_Add()
if c and c.is_Integer:
return Mul(
self.base**c, self.base**a, evaluate=False).is_extended_real
elif self.base in (-S.ImaginaryUnit, S.ImaginaryUnit):
if (self.exp/2).is_integer is False:
return False
if real_b and im_e:
if self.base is S.NegativeOne:
return True
c = self.exp.coeff(S.ImaginaryUnit)
if c:
if self.base.is_rational and c.is_rational:
if self.base.is_nonzero and (self.base - 1).is_nonzero and c.is_nonzero:
return False
ok = (c*log(self.base)/S.Pi).is_integer
if ok is not None:
return ok
if real_b is False: # we already know it's not imag
i = arg(self.base)*self.exp/S.Pi
if i.is_complex: # finite
return i.is_integer
def _eval_is_complex(self):
if self.base == S.Exp1:
return fuzzy_or([self.exp.is_complex, self.exp.is_extended_negative])
if all(a.is_complex for a in self.args) and self._eval_is_finite():
return True
def _eval_is_imaginary(self):
from sympy import arg, log
if self.base.is_imaginary:
if self.exp.is_integer:
odd = self.exp.is_odd
if odd is not None:
return odd
return
if self.base == S.Exp1:
f = 2 * self.exp / (S.Pi*S.ImaginaryUnit)
# exp(pi*integer) = 1 or -1, so not imaginary
if f.is_even:
return False
# exp(pi*integer + pi/2) = I or -I, so it is imaginary
if f.is_odd:
return True
return None
if self.exp.is_imaginary:
imlog = log(self.base).is_imaginary
if imlog is not None:
return False # I**i -> real; (2*I)**i -> complex ==> not imaginary
if self.base.is_extended_real and self.exp.is_extended_real:
if self.base.is_positive:
return False
else:
rat = self.exp.is_rational
if not rat:
return rat
if self.exp.is_integer:
return False
else:
half = (2*self.exp).is_integer
if half:
return self.base.is_negative
return half
if self.base.is_extended_real is False: # we already know it's not imag
i = arg(self.base)*self.exp/S.Pi
isodd = (2*i).is_odd
if isodd is not None:
return isodd
def _eval_is_odd(self):
if self.exp.is_integer:
if self.exp.is_positive:
return self.base.is_odd
elif self.exp.is_nonnegative and self.base.is_odd:
return True
elif self.base is S.NegativeOne:
return True
def _eval_is_finite(self):
if self.exp.is_negative:
if self.base.is_zero:
return False
if self.base.is_infinite or self.base.is_nonzero:
return True
c1 = self.base.is_finite
if c1 is None:
return
c2 = self.exp.is_finite
if c2 is None:
return
if c1 and c2:
if self.exp.is_nonnegative or fuzzy_not(self.base.is_zero):
return True
def _eval_is_prime(self):
'''
An integer raised to the n(>=2)-th power cannot be a prime.
'''
if self.base.is_integer and self.exp.is_integer and (self.exp - 1).is_positive:
return False
def _eval_is_composite(self):
"""
A power is composite if both base and exponent are greater than 1
"""
if (self.base.is_integer and self.exp.is_integer and
((self.base - 1).is_positive and (self.exp - 1).is_positive or
(self.base + 1).is_negative and self.exp.is_positive and self.exp.is_even)):
return True
def _eval_is_polar(self):
return self.base.is_polar
def _eval_subs(self, old, new):
from sympy import exp, log, Symbol, AccumBounds
if isinstance(self.exp, AccumBounds):
b = self.base.subs(old, new)
e = self.exp.subs(old, new)
if isinstance(e, AccumBounds):
return e.__rpow__(b)
return self.func(b, e)
def _check(ct1, ct2, old):
"""Return (bool, pow, remainder_pow) where, if bool is True, then the
exponent of Pow `old` will combine with `pow` so the substitution
is valid, otherwise bool will be False.
For noncommutative objects, `pow` will be an integer, and a factor
`Pow(old.base, remainder_pow)` needs to be included. If there is
no such factor, None is returned. For commutative objects,
remainder_pow is always None.
cti are the coefficient and terms of an exponent of self or old
In this _eval_subs routine a change like (b**(2*x)).subs(b**x, y)
will give y**2 since (b**x)**2 == b**(2*x); if that equality does
not hold then the substitution should not occur so `bool` will be
False.
"""
coeff1, terms1 = ct1
coeff2, terms2 = ct2
if terms1 == terms2:
if old.is_commutative:
# Allow fractional powers for commutative objects
pow = coeff1/coeff2
try:
as_int(pow, strict=False)
combines = True
except ValueError:
combines = isinstance(Pow._eval_power(
Pow(*old.as_base_exp(), evaluate=False),
pow), (Pow, exp, Symbol))
return combines, pow, None
else:
# With noncommutative symbols, substitute only integer powers
if not isinstance(terms1, tuple):
terms1 = (terms1,)
if not all(term.is_integer for term in terms1):
return False, None, None
try:
# Round pow toward zero
pow, remainder = divmod(as_int(coeff1), as_int(coeff2))
if pow < 0 and remainder != 0:
pow += 1
remainder -= as_int(coeff2)
if remainder == 0:
remainder_pow = None
else:
remainder_pow = Mul(remainder, *terms1)
return True, pow, remainder_pow
except ValueError:
# Can't substitute
pass
return False, None, None
if old == self.base or (old == exp and self.base == S.Exp1):
if new.is_Function and isinstance(new, Callable):
return new(self.exp._subs(old, new))
else:
return new**self.exp._subs(old, new)
# issue 10829: (4**x - 3*y + 2).subs(2**x, y) -> y**2 - 3*y + 2
if isinstance(old, self.func) and self.exp == old.exp:
l = log(self.base, old.base)
if l.is_Number:
return Pow(new, l)
if isinstance(old, self.func) and self.base == old.base:
if self.exp.is_Add is False:
ct1 = self.exp.as_independent(Symbol, as_Add=False)
ct2 = old.exp.as_independent(Symbol, as_Add=False)
ok, pow, remainder_pow = _check(ct1, ct2, old)
if ok:
# issue 5180: (x**(6*y)).subs(x**(3*y),z)->z**2
result = self.func(new, pow)
if remainder_pow is not None:
result = Mul(result, Pow(old.base, remainder_pow))
return result
else: # b**(6*x + a).subs(b**(3*x), y) -> y**2 * b**a
# exp(exp(x) + exp(x**2)).subs(exp(exp(x)), w) -> w * exp(exp(x**2))
oarg = old.exp
new_l = []
o_al = []
ct2 = oarg.as_coeff_mul()
for a in self.exp.args:
newa = a._subs(old, new)
ct1 = newa.as_coeff_mul()
ok, pow, remainder_pow = _check(ct1, ct2, old)
if ok:
new_l.append(new**pow)
if remainder_pow is not None:
o_al.append(remainder_pow)
continue
elif not old.is_commutative and not newa.is_integer:
# If any term in the exponent is non-integer,
# we do not do any substitutions in the noncommutative case
return
o_al.append(newa)
if new_l:
expo = Add(*o_al)
new_l.append(Pow(self.base, expo, evaluate=False) if expo != 1 else self.base)
return Mul(*new_l)
if (isinstance(old, exp) or (old.is_Pow and old.base is S.Exp1)) and self.exp.is_extended_real and self.base.is_positive:
ct1 = old.exp.as_independent(Symbol, as_Add=False)
ct2 = (self.exp*log(self.base)).as_independent(
Symbol, as_Add=False)
ok, pow, remainder_pow = _check(ct1, ct2, old)
if ok:
result = self.func(new, pow) # (2**x).subs(exp(x*log(2)), z) -> z
if remainder_pow is not None:
result = Mul(result, Pow(old.base, remainder_pow))
return result
def as_base_exp(self):
"""Return base and exp of self.
Explnation
==========
If base is 1/Integer, then return Integer, -exp. If this extra
processing is not needed, the base and exp properties will
give the raw arguments
Examples
========
>>> from sympy import Pow, S
>>> p = Pow(S.Half, 2, evaluate=False)
>>> p.as_base_exp()
(2, -2)
>>> p.args
(1/2, 2)
"""
b, e = self.args
if b.is_Rational and b.p == 1 and b.q != 1:
return Integer(b.q), -e
return b, e
def _eval_adjoint(self):
from sympy.functions.elementary.complexes import adjoint
i, p = self.exp.is_integer, self.base.is_positive
if i:
return adjoint(self.base)**self.exp
if p:
return self.base**adjoint(self.exp)
if i is False and p is False:
expanded = expand_complex(self)
if expanded != self:
return adjoint(expanded)
def _eval_conjugate(self):
from sympy.functions.elementary.complexes import conjugate as c
i, p = self.exp.is_integer, self.base.is_positive
if i:
return c(self.base)**self.exp
if p:
return self.base**c(self.exp)
if i is False and p is False:
expanded = expand_complex(self)
if expanded != self:
return c(expanded)
if self.is_extended_real:
return self
def _eval_transpose(self):
from sympy.functions.elementary.complexes import transpose
if self.base == S.Exp1:
return self.func(S.Exp1, self.exp.transpose())
i, p = self.exp.is_integer, (self.base.is_complex or self.base.is_infinite)
if p:
return self.base**self.exp
if i:
return transpose(self.base)**self.exp
if i is False and p is False:
expanded = expand_complex(self)
if expanded != self:
return transpose(expanded)
def _eval_expand_power_exp(self, **hints):
"""a**(n + m) -> a**n*a**m"""
b = self.base
e = self.exp
if b == S.Exp1:
from sympy import Sum, Product
if isinstance(e, Sum) and e.is_commutative:
return Product(self.func(b, e.function), *e.limits)
if e.is_Add and e.is_commutative:
expr = []
for x in e.args:
expr.append(self.func(b, x))
return Mul(*expr)
return self.func(b, e)
def _eval_expand_power_base(self, **hints):
"""(a*b)**n -> a**n * b**n"""
force = hints.get('force', False)
b = self.base
e = self.exp
if not b.is_Mul:
return self
cargs, nc = b.args_cnc(split_1=False)
# expand each term - this is top-level-only
# expansion but we have to watch out for things
# that don't have an _eval_expand method
if nc:
nc = [i._eval_expand_power_base(**hints)
if hasattr(i, '_eval_expand_power_base') else i
for i in nc]
if e.is_Integer:
if e.is_positive:
rv = Mul(*nc*e)
else:
rv = Mul(*[i**-1 for i in nc[::-1]]*-e)
if cargs:
rv *= Mul(*cargs)**e
return rv
if not cargs:
return self.func(Mul(*nc), e, evaluate=False)
nc = [Mul(*nc)]
# sift the commutative bases
other, maybe_real = sift(cargs, lambda x: x.is_extended_real is False,
binary=True)
def pred(x):
if x is S.ImaginaryUnit:
return S.ImaginaryUnit
polar = x.is_polar
if polar:
return True
if polar is None:
return fuzzy_bool(x.is_extended_nonnegative)
sifted = sift(maybe_real, pred)
nonneg = sifted[True]
other += sifted[None]
neg = sifted[False]
imag = sifted[S.ImaginaryUnit]
if imag:
I = S.ImaginaryUnit
i = len(imag) % 4
if i == 0:
pass
elif i == 1:
other.append(I)
elif i == 2:
if neg:
nonn = -neg.pop()
if nonn is not S.One:
nonneg.append(nonn)
else:
neg.append(S.NegativeOne)
else:
if neg:
nonn = -neg.pop()
if nonn is not S.One:
nonneg.append(nonn)
else:
neg.append(S.NegativeOne)
other.append(I)
del imag
# bring out the bases that can be separated from the base
if force or e.is_integer:
# treat all commutatives the same and put nc in other
cargs = nonneg + neg + other
other = nc
else:
# this is just like what is happening automatically, except
# that now we are doing it for an arbitrary exponent for which
# no automatic expansion is done
assert not e.is_Integer
# handle negatives by making them all positive and putting
# the residual -1 in other
if len(neg) > 1:
o = S.One
if not other and neg[0].is_Number:
o *= neg.pop(0)
if len(neg) % 2:
o = -o
for n in neg:
nonneg.append(-n)
if o is not S.One:
other.append(o)
elif neg and other:
if neg[0].is_Number and neg[0] is not S.NegativeOne:
other.append(S.NegativeOne)
nonneg.append(-neg[0])
else:
other.extend(neg)
else:
other.extend(neg)
del neg
cargs = nonneg
other += nc
rv = S.One
if cargs:
if e.is_Rational:
npow, cargs = sift(cargs, lambda x: x.is_Pow and
x.exp.is_Rational and x.base.is_number,
binary=True)
rv = Mul(*[self.func(b.func(*b.args), e) for b in npow])
rv *= Mul(*[self.func(b, e, evaluate=False) for b in cargs])
if other:
rv *= self.func(Mul(*other), e, evaluate=False)
return rv
def _eval_expand_multinomial(self, **hints):
"""(a + b + ..)**n -> a**n + n*a**(n-1)*b + .., n is nonzero integer"""
base, exp = self.args
result = self
if exp.is_Rational and exp.p > 0 and base.is_Add:
if not exp.is_Integer:
n = Integer(exp.p // exp.q)
if not n:
return result
else:
radical, result = self.func(base, exp - n), []
expanded_base_n = self.func(base, n)
if expanded_base_n.is_Pow:
expanded_base_n = \
expanded_base_n._eval_expand_multinomial()
for term in Add.make_args(expanded_base_n):
result.append(term*radical)
return Add(*result)
n = int(exp)
if base.is_commutative:
order_terms, other_terms = [], []
for b in base.args:
if b.is_Order:
order_terms.append(b)
else:
other_terms.append(b)
if order_terms:
# (f(x) + O(x^n))^m -> f(x)^m + m*f(x)^{m-1} *O(x^n)
f = Add(*other_terms)
o = Add(*order_terms)
if n == 2:
return expand_multinomial(f**n, deep=False) + n*f*o
else:
g = expand_multinomial(f**(n - 1), deep=False)
return expand_mul(f*g, deep=False) + n*g*o
if base.is_number:
# Efficiently expand expressions of the form (a + b*I)**n
# where 'a' and 'b' are real numbers and 'n' is integer.
a, b = base.as_real_imag()
if a.is_Rational and b.is_Rational:
if not a.is_Integer:
if not b.is_Integer:
k = self.func(a.q * b.q, n)
a, b = a.p*b.q, a.q*b.p
else:
k = self.func(a.q, n)
a, b = a.p, a.q*b
elif not b.is_Integer:
k = self.func(b.q, n)
a, b = a*b.q, b.p
else:
k = 1
a, b, c, d = int(a), int(b), 1, 0
while n:
if n & 1:
c, d = a*c - b*d, b*c + a*d
n -= 1
a, b = a*a - b*b, 2*a*b
n //= 2
I = S.ImaginaryUnit
if k == 1:
return c + I*d
else:
return Integer(c)/k + I*d/k
p = other_terms
# (x + y)**3 -> x**3 + 3*x**2*y + 3*x*y**2 + y**3
# in this particular example:
# p = [x,y]; n = 3
# so now it's easy to get the correct result -- we get the
# coefficients first:
from sympy import multinomial_coefficients
from sympy.polys.polyutils import basic_from_dict
expansion_dict = multinomial_coefficients(len(p), n)
# in our example: {(3, 0): 1, (1, 2): 3, (0, 3): 1, (2, 1): 3}
# and now construct the expression.
return basic_from_dict(expansion_dict, *p)
else:
if n == 2:
return Add(*[f*g for f in base.args for g in base.args])
else:
multi = (base**(n - 1))._eval_expand_multinomial()
if multi.is_Add:
return Add(*[f*g for f in base.args
for g in multi.args])
else:
# XXX can this ever happen if base was an Add?
return Add(*[f*multi for f in base.args])
elif (exp.is_Rational and exp.p < 0 and base.is_Add and
abs(exp.p) > exp.q):
return 1 / self.func(base, -exp)._eval_expand_multinomial()
elif exp.is_Add and base.is_Number:
# a + b a b
# n --> n n , where n, a, b are Numbers
coeff, tail = S.One, S.Zero
for term in exp.args:
if term.is_Number:
coeff *= self.func(base, term)
else:
tail += term
return coeff * self.func(base, tail)
else:
return result
def as_real_imag(self, deep=True, **hints):
from sympy import atan2, cos, im, re, sin
from sympy.polys.polytools import poly
if self.exp.is_Integer:
exp = self.exp
re_e, im_e = self.base.as_real_imag(deep=deep)
if not im_e:
return self, S.Zero
a, b = symbols('a b', cls=Dummy)
if exp >= 0:
if re_e.is_Number and im_e.is_Number:
# We can be more efficient in this case
expr = expand_multinomial(self.base**exp)
if expr != self:
return expr.as_real_imag()
expr = poly(
(a + b)**exp) # a = re, b = im; expr = (a + b*I)**exp
else:
mag = re_e**2 + im_e**2
re_e, im_e = re_e/mag, -im_e/mag
if re_e.is_Number and im_e.is_Number:
# We can be more efficient in this case
expr = expand_multinomial((re_e + im_e*S.ImaginaryUnit)**-exp)
if expr != self:
return expr.as_real_imag()
expr = poly((a + b)**-exp)
# Terms with even b powers will be real
r = [i for i in expr.terms() if not i[0][1] % 2]
re_part = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
# Terms with odd b powers will be imaginary
r = [i for i in expr.terms() if i[0][1] % 4 == 1]
im_part1 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
r = [i for i in expr.terms() if i[0][1] % 4 == 3]
im_part3 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
return (re_part.subs({a: re_e, b: S.ImaginaryUnit*im_e}),
im_part1.subs({a: re_e, b: im_e}) + im_part3.subs({a: re_e, b: -im_e}))
elif self.exp.is_Rational:
re_e, im_e = self.base.as_real_imag(deep=deep)
if im_e.is_zero and self.exp is S.Half:
if re_e.is_extended_nonnegative:
return self, S.Zero
if re_e.is_extended_nonpositive:
return S.Zero, (-self.base)**self.exp
# XXX: This is not totally correct since for x**(p/q) with
# x being imaginary there are actually q roots, but
# only a single one is returned from here.
r = self.func(self.func(re_e, 2) + self.func(im_e, 2), S.Half)
t = atan2(im_e, re_e)
rp, tp = self.func(r, self.exp), t*self.exp
return rp*cos(tp), rp*sin(tp)
elif self.base is S.Exp1:
from ..functions import exp
re_e, im_e = self.exp.as_real_imag()
if deep:
re_e = re_e.expand(deep, **hints)
im_e = im_e.expand(deep, **hints)
c, s = cos(im_e), sin(im_e)
return exp(re_e)*c, exp(re_e)*s
else:
if deep:
hints['complex'] = False
expanded = self.expand(deep, **hints)
if hints.get('ignore') == expanded:
return None
else:
return (re(expanded), im(expanded))
else:
return re(self), im(self)
def _eval_derivative(self, s):
from sympy import log
dbase = self.base.diff(s)
dexp = self.exp.diff(s)
return self * (dexp * log(self.base) + dbase * self.exp/self.base)
def _eval_evalf(self, prec):
base, exp = self.as_base_exp()
if base == S.Exp1:
# Use mpmath function associated to class "exp":
from sympy import exp as exp_function
return exp_function(self.exp, evaluate=False)._eval_evalf(prec)
base = base._evalf(prec)
if not exp.is_Integer:
exp = exp._evalf(prec)
if exp.is_negative and base.is_number and base.is_extended_real is False:
base = base.conjugate() / (base * base.conjugate())._evalf(prec)
exp = -exp
return self.func(base, exp).expand()
return self.func(base, exp)
def _eval_is_polynomial(self, syms):
if self.exp.has(*syms):
return False
if self.base.has(*syms):
return bool(self.base._eval_is_polynomial(syms) and
self.exp.is_Integer and (self.exp >= 0))
else:
return True
def _eval_is_rational(self):
# The evaluation of self.func below can be very expensive in the case
# of integer**integer if the exponent is large. We should try to exit
# before that if possible:
if (self.exp.is_integer and self.base.is_rational
and fuzzy_not(fuzzy_and([self.exp.is_negative, self.base.is_zero]))):
return True
p = self.func(*self.as_base_exp()) # in case it's unevaluated
if not p.is_Pow:
return p.is_rational
b, e = p.as_base_exp()
if e.is_Rational and b.is_Rational:
# we didn't check that e is not an Integer
# because Rational**Integer autosimplifies
return False
if e.is_integer:
if b.is_rational:
if fuzzy_not(b.is_zero) or e.is_nonnegative:
return True
if b == e: # always rational, even for 0**0
return True
elif b.is_irrational:
return e.is_zero
if b is S.Exp1:
if e.is_rational and e.is_nonzero:
return False
def _eval_is_algebraic(self):
def _is_one(expr):
try:
return (expr - 1).is_zero
except ValueError:
# when the operation is not allowed
return False
if self.base.is_zero or _is_one(self.base):
return True
elif self.base is S.Exp1:
s = self.func(*self.args)
if s.func == self.func:
if self.exp.is_nonzero:
if self.exp.is_algebraic:
return False
elif (self.exp/S.Pi).is_rational:
return False
elif (self.exp/(S.ImaginaryUnit*S.Pi)).is_rational:
return True
else:
return s.is_algebraic
elif self.exp.is_rational:
if self.base.is_algebraic is False:
return self.exp.is_zero
if self.base.is_zero is False:
if self.exp.is_nonzero:
return self.base.is_algebraic
elif self.base.is_algebraic:
return True
if self.exp.is_positive:
return self.base.is_algebraic
elif self.base.is_algebraic and self.exp.is_algebraic:
if ((fuzzy_not(self.base.is_zero)
and fuzzy_not(_is_one(self.base)))
or self.base.is_integer is False
or self.base.is_irrational):
return self.exp.is_rational
def _eval_is_rational_function(self, syms):
if self.exp.has(*syms):
return False
if self.base.has(*syms):
return self.base._eval_is_rational_function(syms) and \
self.exp.is_Integer
else:
return True
def _eval_is_meromorphic(self, x, a):
# f**g is meromorphic if g is an integer and f is meromorphic.
# E**(log(f)*g) is meromorphic if log(f)*g is meromorphic
# and finite.
base_merom = self.base._eval_is_meromorphic(x, a)
exp_integer = self.exp.is_Integer
if exp_integer:
return base_merom
exp_merom = self.exp._eval_is_meromorphic(x, a)
if base_merom is False:
# f**g = E**(log(f)*g) may be meromorphic if the
# singularities of log(f) and g cancel each other,
# for example, if g = 1/log(f). Hence,
return False if exp_merom else None
elif base_merom is None:
return None
b = self.base.subs(x, a)
# b is extended complex as base is meromorphic.
# log(base) is finite and meromorphic when b != 0, zoo.
b_zero = b.is_zero
if b_zero:
log_defined = False
else:
log_defined = fuzzy_and((b.is_finite, fuzzy_not(b_zero)))
if log_defined is False: # zero or pole of base
return exp_integer # False or None
elif log_defined is None:
return None
if not exp_merom:
return exp_merom # False or None
return self.exp.subs(x, a).is_finite
def _eval_is_algebraic_expr(self, syms):
if self.exp.has(*syms):
return False
if self.base.has(*syms):
return self.base._eval_is_algebraic_expr(syms) and \
self.exp.is_Rational
else:
return True
def _eval_rewrite_as_exp(self, base, expo, **kwargs):
from sympy import exp, log, I, arg
if base.is_zero or base.has(exp) or expo.has(exp):
return base**expo
if base.has(Symbol):
# delay evaluation if expo is non symbolic
# (as exp(x*log(5)) automatically reduces to x**5)
if global_parameters.exp_is_pow:
return Pow(S.Exp1, log(base)*expo, evaluate=expo.has(Symbol))
else:
return exp(log(base)*expo, evaluate=expo.has(Symbol))
else:
return exp((log(abs(base)) + I*arg(base))*expo)
def as_numer_denom(self):
if not self.is_commutative:
return self, S.One
base, exp = self.as_base_exp()
n, d = base.as_numer_denom()
# this should be the same as ExpBase.as_numer_denom wrt
# exponent handling
neg_exp = exp.is_negative
if not neg_exp and not (-exp).is_negative:
neg_exp = _coeff_isneg(exp)
int_exp = exp.is_integer
# the denominator cannot be separated from the numerator if
# its sign is unknown unless the exponent is an integer, e.g.
# sqrt(a/b) != sqrt(a)/sqrt(b) when a=1 and b=-1. But if the
# denominator is negative the numerator and denominator can
# be negated and the denominator (now positive) separated.
if not (d.is_extended_real or int_exp):
n = base
d = S.One
dnonpos = d.is_nonpositive
if dnonpos:
n, d = -n, -d
elif dnonpos is None and not int_exp:
n = base
d = S.One
if neg_exp:
n, d = d, n
exp = -exp
if exp.is_infinite:
if n is S.One and d is not S.One:
return n, self.func(d, exp)
if n is not S.One and d is S.One:
return self.func(n, exp), d
return self.func(n, exp), self.func(d, exp)
def matches(self, expr, repl_dict={}, old=False):
expr = _sympify(expr)
repl_dict = repl_dict.copy()
# special case, pattern = 1 and expr.exp can match to 0
if expr is S.One:
d = self.exp.matches(S.Zero, repl_dict)
if d is not None:
return d
# make sure the expression to be matched is an Expr
if not isinstance(expr, Expr):
return None
b, e = expr.as_base_exp()
# special case number
sb, se = self.as_base_exp()
if sb.is_Symbol and se.is_Integer and expr:
if e.is_rational:
return sb.matches(b**(e/se), repl_dict)
return sb.matches(expr**(1/se), repl_dict)
d = repl_dict.copy()
d = self.base.matches(b, d)
if d is None:
return None
d = self.exp.xreplace(d).matches(e, d)
if d is None:
return Expr.matches(self, expr, repl_dict)
return d
def _eval_nseries(self, x, n, logx, cdir=0):
# NOTE! This function is an important part of the gruntz algorithm
# for computing limits. It has to return a generalized power
# series with coefficients in C(log, log(x)). In more detail:
# It has to return an expression
# c_0*x**e_0 + c_1*x**e_1 + ... (finitely many terms)
# where e_i are numbers (not necessarily integers) and c_i are
# expressions involving only numbers, the log function, and log(x).
# The series expansion of b**e is computed as follows:
# 1) We express b as f*(1 + g) where f is the leading term of b.
# g has order O(x**d) where d is strictly positive.
# 2) Then b**e = (f**e)*((1 + g)**e).
# (1 + g)**e is computed using binomial series.
from sympy import im, I, ceiling, polygamma, logcombine, EulerGamma, nan, zoo, factorial, ff, PoleError, O, powdenest, Wild
from itertools import product
from ..functions import exp, log
from ..series import Order, limit
from ..simplify import powsimp
if self.base is S.Exp1:
e_series = self.exp.nseries(x, n=n, logx=logx)
if e_series.is_Order:
return 1 + e_series
e0 = limit(e_series.removeO(), x, 0)
if e0 in (-S.NegativeInfinity, S.Infinity):
return self
t = e_series - e0
exp_series = term = exp(e0)
# series of exp(e0 + t) in t
for i in range(1, n):
term *= t/i
term = term.nseries(x, n=n, logx=logx)
exp_series += term
exp_series += Order(t**n, x)
return powsimp(exp_series, deep=True, combine='exp')
self = powdenest(self, force=True).trigsimp()
b, e = self.as_base_exp()
if e.has(S.Infinity, S.NegativeInfinity, S.ComplexInfinity, S.NaN):
raise PoleError()
if e.has(x):
return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
if logx is not None and b.has(log):
c, ex = symbols('c, ex', cls=Wild, exclude=[x])
b = b.replace(log(c*x**ex), log(c) + ex*logx)
self = b**e
b = b.removeO()
try:
if b.has(polygamma, EulerGamma) and logx is not None:
raise ValueError()
_, m = b.leadterm(x)
except (ValueError, NotImplementedError):
b = b._eval_nseries(x, n=max(2, n), logx=logx, cdir=cdir).removeO()
if b.has(nan, zoo):
raise NotImplementedError()
_, m = b.leadterm(x)
if e.has(log):
e = logcombine(e).cancel()
if not (m.is_zero or e.is_number and e.is_real):
return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
f = b.as_leading_term(x)
g = (b/f - S.One).cancel()
maxpow = n - m*e
if maxpow.is_negative:
return O(x**(m*e), x)
if g.is_zero:
return f**e
def coeff_exp(term, x):
coeff, exp = S.One, S.Zero
for factor in Mul.make_args(term):
if factor.has(x):
base, exp = factor.as_base_exp()
if base != x:
try:
return term.leadterm(x)
except ValueError:
return term, S.Zero
else:
coeff *= factor
return coeff, exp
def mul(d1, d2):
res = {}
for e1, e2 in product(d1, d2):
ex = e1 + e2
if ex < maxpow:
res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
return res
try:
_, d = g.leadterm(x)
except (ValueError, NotImplementedError):
if limit(g/x**maxpow, x, 0) == 0:
# g has higher order zero
return f**e + e*f**e*g # first term of binomial series
else:
raise NotImplementedError()
if not d.is_positive:
g = g.simplify()
_, d = g.leadterm(x)
if not d.is_positive:
raise NotImplementedError()
gpoly = g._eval_nseries(x, n=ceiling(maxpow), logx=logx, cdir=cdir).removeO()
gterms = {}
for term in Add.make_args(gpoly):
co1, e1 = coeff_exp(term, x)
gterms[e1] = gterms.get(e1, S.Zero) + co1
k = S.One
terms = {S.Zero: S.One}
tk = gterms
while (k*d - maxpow).is_negative:
coeff = ff(e, k)/factorial(k)
for ex in tk:
terms[ex] = terms.get(ex, S.Zero) + coeff*tk[ex]
tk = mul(tk, gterms)
k += S.One
if (not e.is_integer and m.is_zero and f.is_real
and f.is_negative and im((b - f).dir(x, cdir)) < 0):
inco, inex = coeff_exp(f**e*exp(-2*e*S.Pi*I), x)
else:
inco, inex = coeff_exp(f**e, x)
res = S.Zero
for e1 in terms:
ex = e1 + inex
res += terms[e1]*inco*x**(ex)
if not (e.is_integer and e.is_positive and (e*d - n).is_nonpositive and
res == _mexpand(self)):
res += O(x**n, x)
return _mexpand(res)
def _eval_as_leading_term(self, x, cdir=0):
from ..series import Order
from sympy import exp, I, im, log
e = self.exp
b = self.base
if self.base is S.Exp1:
arg = self.exp
if arg.is_Add:
return Mul(*[(S.Exp1**f).as_leading_term(x) for f in arg.args])
arg_1 = arg.as_leading_term(x)
if Order(x, x).contains(arg_1):
return S.One
if Order(1, x).contains(arg_1):
return S.Exp1**arg_1
####################################################
# The correct result here should be 'None'. #
# Indeed arg in not bounded as x tends to 0. #
# Consequently the series expansion does not admit #
# the leading term. #
# For compatibility reasons, the return value here #
# is the original function, i.e. exp(arg), #
# instead of None. #
####################################################
return S.Exp1**arg
elif e.has(x):
return exp(e * log(b)).as_leading_term(x, cdir=cdir)
else:
f = b.as_leading_term(x, cdir=cdir)
if (not e.is_integer and f.is_constant() and f.is_real
and f.is_negative and im((b - f).dir(x, cdir)) < 0):
return self.func(f, e) * exp(-2 * e * S.Pi * I)
return self.func(f, e)
@cacheit
def _taylor_term(self, n, x, *previous_terms): # of (1 + x)**e
from sympy import binomial
return binomial(self.exp, n) * self.func(x, n)
def taylor_term(self, n, x, *previous_terms):
if self.base is not S.Exp1:
return super().taylor_term(n, x, *previous_terms)
from sympy import sympify, factorial
if n < 0:
return S.Zero
if n == 0:
return S.One
x = sympify(x)
if previous_terms:
p = previous_terms[-1]
if p is not None:
return p * x / n
return x**n/factorial(n)
def _sage_(self):
return self.args[0]._sage_()**self.args[1]._sage_()
def _eval_rewrite_as_sin(self, base, exp):
from ..functions import sin
if self.base is S.Exp1:
return sin(S.ImaginaryUnit*self.exp + S.Pi/2) - S.ImaginaryUnit*sin(S.ImaginaryUnit*self.exp)
def _eval_rewrite_as_cos(self, base, exp):
from ..functions import cos
if self.base is S.Exp1:
return cos(S.ImaginaryUnit*self.exp) + S.ImaginaryUnit*cos(S.ImaginaryUnit*self.exp + S.Pi/2)
def _eval_rewrite_as_tanh(self, base, exp):
from ..functions import tanh
if self.base is S.Exp1:
return (1 + tanh(self.exp/2))/(1 - tanh(self.exp/2))
def _eval_rewrite_as_sqrt(self, base, exp, **kwargs):
from sympy.functions.elementary.trigonometric import sin, cos
if base is not S.Exp1:
return None
if exp.is_Mul:
coeff = exp.coeff(S.Pi * S.ImaginaryUnit)
if coeff and coeff.is_number:
cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff)
if not isinstance(cosine, cos) and not isinstance (sine, sin):
return cosine + S.ImaginaryUnit*sine
def as_content_primitive(self, radical=False, clear=True):
"""Return the tuple (R, self/R) where R is the positive Rational
extracted from self.
Examples
========
>>> from sympy import sqrt
>>> sqrt(4 + 4*sqrt(2)).as_content_primitive()
(2, sqrt(1 + sqrt(2)))
>>> sqrt(3 + 3*sqrt(2)).as_content_primitive()
(1, sqrt(3)*sqrt(1 + sqrt(2)))
>>> from sympy import expand_power_base, powsimp, Mul
>>> from sympy.abc import x, y
>>> ((2*x + 2)**2).as_content_primitive()
(4, (x + 1)**2)
>>> (4**((1 + y)/2)).as_content_primitive()
(2, 4**(y/2))
>>> (3**((1 + y)/2)).as_content_primitive()
(1, 3**((y + 1)/2))
>>> (3**((5 + y)/2)).as_content_primitive()
(9, 3**((y + 1)/2))
>>> eq = 3**(2 + 2*x)
>>> powsimp(eq) == eq
True
>>> eq.as_content_primitive()
(9, 3**(2*x))
>>> powsimp(Mul(*_))
3**(2*x + 2)
>>> eq = (2 + 2*x)**y
>>> s = expand_power_base(eq); s.is_Mul, s
(False, (2*x + 2)**y)
>>> eq.as_content_primitive()
(1, (2*(x + 1))**y)
>>> s = expand_power_base(_[1]); s.is_Mul, s
(True, 2**y*(x + 1)**y)
See docstring of Expr.as_content_primitive for more examples.
"""
b, e = self.as_base_exp()
b = _keep_coeff(*b.as_content_primitive(radical=radical, clear=clear))
ce, pe = e.as_content_primitive(radical=radical, clear=clear)
if b.is_Rational:
#e
#= ce*pe
#= ce*(h + t)
#= ce*h + ce*t
#=> self
#= b**(ce*h)*b**(ce*t)
#= b**(cehp/cehq)*b**(ce*t)
#= b**(iceh + r/cehq)*b**(ce*t)
#= b**(iceh)*b**(r/cehq)*b**(ce*t)
#= b**(iceh)*b**(ce*t + r/cehq)
h, t = pe.as_coeff_Add()
if h.is_Rational:
ceh = ce*h
c = self.func(b, ceh)
r = S.Zero
if not c.is_Rational:
iceh, r = divmod(ceh.p, ceh.q)
c = self.func(b, iceh)
return c, self.func(b, _keep_coeff(ce, t + r/ce/ceh.q))
e = _keep_coeff(ce, pe)
# b**e = (h*t)**e = h**e*t**e = c*m*t**e
if e.is_Rational and b.is_Mul:
h, t = b.as_content_primitive(radical=radical, clear=clear) # h is positive
c, m = self.func(h, e).as_coeff_Mul() # so c is positive
m, me = m.as_base_exp()
if m is S.One or me == e: # probably always true
# return the following, not return c, m*Pow(t, e)
# which would change Pow into Mul; we let sympy
# decide what to do by using the unevaluated Mul, e.g
# should it stay as sqrt(2 + 2*sqrt(5)) or become
# sqrt(2)*sqrt(1 + sqrt(5))
return c, self.func(_keep_coeff(m, t), e)
return S.One, self.func(b, e)
def is_constant(self, *wrt, **flags):
expr = self
if flags.get('simplify', True):
expr = expr.simplify()
b, e = expr.as_base_exp()
bz = b.equals(0)
if bz: # recalculate with assumptions in case it's unevaluated
new = b**e
if new != expr:
return new.is_constant()
econ = e.is_constant(*wrt)
bcon = b.is_constant(*wrt)
if bcon:
if econ:
return True
bz = b.equals(0)
if bz is False:
return False
elif bcon is None:
return None
return e.equals(0)
def _eval_difference_delta(self, n, step):
b, e = self.args
if e.has(n) and not b.has(n):
new_e = e.subs(n, n + step)
return (b**(new_e - e) - 1) * self
power = Dispatcher('power')
power.add((object, object), Pow)
from .add import Add
from .numbers import Integer
from .mul import Mul, _keep_coeff
from .symbol import Symbol, Dummy, symbols
|
ee34256ef1fb2a232f8ea1a97ea8026d527656899c3ab883c552fee3cc4bded8 | """Tools for manipulating of large commutative expressions. """
from sympy.core.add import Add
from sympy.core.compatibility import iterable, is_sequence, SYMPY_INTS
from sympy.core.mul import Mul, _keep_coeff
from sympy.core.power import Pow
from sympy.core.basic import Basic, preorder_traversal
from sympy.core.expr import Expr
from sympy.core.sympify import sympify
from sympy.core.numbers import Rational, Integer, Number, I
from sympy.core.singleton import S
from sympy.core.symbol import Dummy
from sympy.core.coreerrors import NonCommutativeExpression
from sympy.core.containers import Tuple, Dict
from sympy.utilities import default_sort_key
from sympy.utilities.iterables import (common_prefix, common_suffix,
variations, ordered)
from collections import defaultdict
_eps = Dummy(positive=True)
def _isnumber(i):
return isinstance(i, (SYMPY_INTS, float)) or i.is_Number
def _monotonic_sign(self):
"""Return the value closest to 0 that ``self`` may have if all symbols
are signed and the result is uniformly the same sign for all values of symbols.
If a symbol is only signed but not known to be an
integer or the result is 0 then a symbol representative of the sign of self
will be returned. Otherwise, None is returned if a) the sign could be positive
or negative or b) self is not in one of the following forms:
- L(x, y, ...) + A: a function linear in all symbols x, y, ... with an
additive constant; if A is zero then the function can be a monomial whose
sign is monotonic over the range of the variables, e.g. (x + 1)**3 if x is
nonnegative.
- A/L(x, y, ...) + B: the inverse of a function linear in all symbols x, y, ...
that does not have a sign change from positive to negative for any set
of values for the variables.
- M(x, y, ...) + A: a monomial M whose factors are all signed and a constant, A.
- A/M(x, y, ...) + B: the inverse of a monomial and constants A and B.
- P(x): a univariate polynomial
Examples
========
>>> from sympy.core.exprtools import _monotonic_sign as F
>>> from sympy import Dummy
>>> nn = Dummy(integer=True, nonnegative=True)
>>> p = Dummy(integer=True, positive=True)
>>> p2 = Dummy(integer=True, positive=True)
>>> F(nn + 1)
1
>>> F(p - 1)
_nneg
>>> F(nn*p + 1)
1
>>> F(p2*p + 1)
2
>>> F(nn - 1) # could be negative, zero or positive
"""
if not self.is_extended_real:
return
if (-self).is_Symbol:
rv = _monotonic_sign(-self)
return rv if rv is None else -rv
if not self.is_Add and self.as_numer_denom()[1].is_number:
s = self
if s.is_prime:
if s.is_odd:
return S(3)
else:
return S(2)
elif s.is_composite:
if s.is_odd:
return S(9)
else:
return S(4)
elif s.is_positive:
if s.is_even:
if s.is_prime is False:
return S(4)
else:
return S(2)
elif s.is_integer:
return S.One
else:
return _eps
elif s.is_extended_negative:
if s.is_even:
return S(-2)
elif s.is_integer:
return S.NegativeOne
else:
return -_eps
if s.is_zero or s.is_extended_nonpositive or s.is_extended_nonnegative:
return S.Zero
return None
# univariate polynomial
free = self.free_symbols
if len(free) == 1:
if self.is_polynomial():
from sympy.polys.polytools import real_roots
from sympy.polys.polyroots import roots
from sympy.polys.polyerrors import PolynomialError
x = free.pop()
x0 = _monotonic_sign(x)
if x0 == _eps or x0 == -_eps:
x0 = S.Zero
if x0 is not None:
d = self.diff(x)
if d.is_number:
currentroots = []
else:
try:
currentroots = real_roots(d)
except (PolynomialError, NotImplementedError):
currentroots = [r for r in roots(d, x) if r.is_extended_real]
y = self.subs(x, x0)
if x.is_nonnegative and all(r <= x0 for r in currentroots):
if y.is_nonnegative and d.is_positive:
if y:
return y if y.is_positive else Dummy('pos', positive=True)
else:
return Dummy('nneg', nonnegative=True)
if y.is_nonpositive and d.is_negative:
if y:
return y if y.is_negative else Dummy('neg', negative=True)
else:
return Dummy('npos', nonpositive=True)
elif x.is_nonpositive and all(r >= x0 for r in currentroots):
if y.is_nonnegative and d.is_negative:
if y:
return Dummy('pos', positive=True)
else:
return Dummy('nneg', nonnegative=True)
if y.is_nonpositive and d.is_positive:
if y:
return Dummy('neg', negative=True)
else:
return Dummy('npos', nonpositive=True)
else:
n, d = self.as_numer_denom()
den = None
if n.is_number:
den = _monotonic_sign(d)
elif not d.is_number:
if _monotonic_sign(n) is not None:
den = _monotonic_sign(d)
if den is not None and (den.is_positive or den.is_negative):
v = n*den
if v.is_positive:
return Dummy('pos', positive=True)
elif v.is_nonnegative:
return Dummy('nneg', nonnegative=True)
elif v.is_negative:
return Dummy('neg', negative=True)
elif v.is_nonpositive:
return Dummy('npos', nonpositive=True)
return None
# multivariate
c, a = self.as_coeff_Add()
v = None
if not a.is_polynomial():
# F/A or A/F where A is a number and F is a signed, rational monomial
n, d = a.as_numer_denom()
if not (n.is_number or d.is_number):
return
if (
a.is_Mul or a.is_Pow) and \
a.is_rational and \
all(p.exp.is_Integer for p in a.atoms(Pow) if p.is_Pow) and \
(a.is_positive or a.is_negative):
v = S.One
for ai in Mul.make_args(a):
if ai.is_number:
v *= ai
continue
reps = {}
for x in ai.free_symbols:
reps[x] = _monotonic_sign(x)
if reps[x] is None:
return
v *= ai.subs(reps)
elif c:
# signed linear expression
if not any(p for p in a.atoms(Pow) if not p.is_number) and (a.is_nonpositive or a.is_nonnegative):
free = list(a.free_symbols)
p = {}
for i in free:
v = _monotonic_sign(i)
if v is None:
return
p[i] = v or (_eps if i.is_nonnegative else -_eps)
v = a.xreplace(p)
if v is not None:
rv = v + c
if v.is_nonnegative and rv.is_positive:
return rv.subs(_eps, 0)
if v.is_nonpositive and rv.is_negative:
return rv.subs(_eps, 0)
def decompose_power(expr):
"""
Decompose power into symbolic base and integer exponent.
Explanation
===========
This is strictly only valid if the exponent from which
the integer is extracted is itself an integer or the
base is positive. These conditions are assumed and not
checked here.
Examples
========
>>> from sympy.core.exprtools import decompose_power
>>> from sympy.abc import x, y
>>> decompose_power(x)
(x, 1)
>>> decompose_power(x**2)
(x, 2)
>>> decompose_power(x**(2*y))
(x**y, 2)
>>> decompose_power(x**(2*y/3))
(x**(y/3), 2)
"""
base, exp = expr.as_base_exp()
if exp.is_Number:
if exp.is_Rational:
if not exp.is_Integer:
base = Pow(base, Rational(1, exp.q))
exp = exp.p
else:
base, exp = expr, 1
else:
exp, tail = exp.as_coeff_Mul(rational=True)
if exp is S.NegativeOne:
base, exp = Pow(base, tail), -1
elif exp is not S.One:
tail = _keep_coeff(Rational(1, exp.q), tail)
base, exp = Pow(base, tail), exp.p
else:
base, exp = expr, 1
return base, exp
def decompose_power_rat(expr):
"""
Decompose power into symbolic base and rational exponent.
"""
base, exp = expr.as_base_exp()
if exp.is_Number:
if not exp.is_Rational:
base, exp = expr, 1
else:
exp, tail = exp.as_coeff_Mul(rational=True)
if exp is S.NegativeOne:
base, exp = Pow(base, tail), -1
elif exp is not S.One:
tail = _keep_coeff(Rational(1, exp.q), tail)
base, exp = Pow(base, tail), exp.p
else:
base, exp = expr, 1
return base, exp
class Factors:
"""Efficient representation of ``f_1*f_2*...*f_n``."""
__slots__ = ('factors', 'gens')
def __init__(self, factors=None): # Factors
"""Initialize Factors from dict or expr.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x
>>> from sympy import I
>>> e = 2*x**3
>>> Factors(e)
Factors({2: 1, x: 3})
>>> Factors(e.as_powers_dict())
Factors({2: 1, x: 3})
>>> f = _
>>> f.factors # underlying dictionary
{2: 1, x: 3}
>>> f.gens # base of each factor
frozenset({2, x})
>>> Factors(0)
Factors({0: 1})
>>> Factors(I)
Factors({I: 1})
Notes
=====
Although a dictionary can be passed, only minimal checking is
performed: powers of -1 and I are made canonical.
"""
if isinstance(factors, (SYMPY_INTS, float)):
factors = S(factors)
if isinstance(factors, Factors):
factors = factors.factors.copy()
elif factors is None or factors is S.One:
factors = {}
elif factors is S.Zero or factors == 0:
factors = {S.Zero: S.One}
elif isinstance(factors, Number):
n = factors
factors = {}
if n < 0:
factors[S.NegativeOne] = S.One
n = -n
if n is not S.One:
if n.is_Float or n.is_Integer or n is S.Infinity:
factors[n] = S.One
elif n.is_Rational:
# since we're processing Numbers, the denominator is
# stored with a negative exponent; all other factors
# are left .
if n.p != 1:
factors[Integer(n.p)] = S.One
factors[Integer(n.q)] = S.NegativeOne
else:
raise ValueError('Expected Float|Rational|Integer, not %s' % n)
elif isinstance(factors, Basic) and not factors.args:
factors = {factors: S.One}
elif isinstance(factors, Expr):
c, nc = factors.args_cnc()
i = c.count(I)
for _ in range(i):
c.remove(I)
factors = dict(Mul._from_args(c).as_powers_dict())
# Handle all rational Coefficients
for f in list(factors.keys()):
if isinstance(f, Rational) and not isinstance(f, Integer):
p, q = Integer(f.p), Integer(f.q)
factors[p] = (factors[p] if p in factors else S.Zero) + factors[f]
factors[q] = (factors[q] if q in factors else S.Zero) - factors[f]
factors.pop(f)
if i:
factors[I] = factors.get(I, S.Zero) + i
if nc:
factors[Mul(*nc, evaluate=False)] = S.One
else:
factors = factors.copy() # /!\ should be dict-like
# tidy up -/+1 and I exponents if Rational
handle = []
for k in factors:
if k is I or k in (-1, 1):
handle.append(k)
if handle:
i1 = S.One
for k in handle:
if not _isnumber(factors[k]):
continue
i1 *= k**factors.pop(k)
if i1 is not S.One:
for a in i1.args if i1.is_Mul else [i1]: # at worst, -1.0*I*(-1)**e
if a is S.NegativeOne:
factors[a] = S.One
elif a is I:
factors[I] = S.One
elif a.is_Pow:
factors[a.base] = factors.get(a.base, S.Zero) + a.exp
elif a == 1:
factors[a] = S.One
elif a == -1:
factors[-a] = S.One
factors[S.NegativeOne] = S.One
else:
raise ValueError('unexpected factor in i1: %s' % a)
self.factors = factors
keys = getattr(factors, 'keys', None)
if keys is None:
raise TypeError('expecting Expr or dictionary')
self.gens = frozenset(keys())
def __hash__(self): # Factors
keys = tuple(ordered(self.factors.keys()))
values = [self.factors[k] for k in keys]
return hash((keys, values))
def __repr__(self): # Factors
return "Factors({%s})" % ', '.join(
['%s: %s' % (k, v) for k, v in ordered(self.factors.items())])
@property
def is_zero(self): # Factors
"""
>>> from sympy.core.exprtools import Factors
>>> Factors(0).is_zero
True
"""
f = self.factors
return len(f) == 1 and S.Zero in f
@property
def is_one(self): # Factors
"""
>>> from sympy.core.exprtools import Factors
>>> Factors(1).is_one
True
"""
return not self.factors
def as_expr(self): # Factors
"""Return the underlying expression.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y
>>> Factors((x*y**2).as_powers_dict()).as_expr()
x*y**2
"""
args = []
for factor, exp in self.factors.items():
if exp != 1:
if isinstance(exp, Integer):
b, e = factor.as_base_exp()
e = _keep_coeff(exp, e)
args.append(b**e)
else:
args.append(factor**exp)
else:
args.append(factor)
return Mul(*args)
def mul(self, other): # Factors
"""Return Factors of ``self * other``.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.mul(b)
Factors({x: 2, y: 3, z: -1})
>>> a*b
Factors({x: 2, y: 3, z: -1})
"""
if not isinstance(other, Factors):
other = Factors(other)
if any(f.is_zero for f in (self, other)):
return Factors(S.Zero)
factors = dict(self.factors)
for factor, exp in other.factors.items():
if factor in factors:
exp = factors[factor] + exp
if not exp:
del factors[factor]
continue
factors[factor] = exp
return Factors(factors)
def normal(self, other):
"""Return ``self`` and ``other`` with ``gcd`` removed from each.
The only differences between this and method ``div`` is that this
is 1) optimized for the case when there are few factors in common and
2) this does not raise an error if ``other`` is zero.
See Also
========
div
"""
if not isinstance(other, Factors):
other = Factors(other)
if other.is_zero:
return (Factors(), Factors(S.Zero))
if self.is_zero:
return (Factors(S.Zero), Factors())
self_factors = dict(self.factors)
other_factors = dict(other.factors)
for factor, self_exp in self.factors.items():
try:
other_exp = other.factors[factor]
except KeyError:
continue
exp = self_exp - other_exp
if not exp:
del self_factors[factor]
del other_factors[factor]
elif _isnumber(exp):
if exp > 0:
self_factors[factor] = exp
del other_factors[factor]
else:
del self_factors[factor]
other_factors[factor] = -exp
else:
r = self_exp.extract_additively(other_exp)
if r is not None:
if r:
self_factors[factor] = r
del other_factors[factor]
else: # should be handled already
del self_factors[factor]
del other_factors[factor]
else:
sc, sa = self_exp.as_coeff_Add()
if sc:
oc, oa = other_exp.as_coeff_Add()
diff = sc - oc
if diff > 0:
self_factors[factor] -= oc
other_exp = oa
elif diff < 0:
self_factors[factor] -= sc
other_factors[factor] -= sc
other_exp = oa - diff
else:
self_factors[factor] = sa
other_exp = oa
if other_exp:
other_factors[factor] = other_exp
else:
del other_factors[factor]
return Factors(self_factors), Factors(other_factors)
def div(self, other): # Factors
"""Return ``self`` and ``other`` with ``gcd`` removed from each.
This is optimized for the case when there are many factors in common.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> from sympy import S
>>> a = Factors((x*y**2).as_powers_dict())
>>> a.div(a)
(Factors({}), Factors({}))
>>> a.div(x*z)
(Factors({y: 2}), Factors({z: 1}))
The ``/`` operator only gives ``quo``:
>>> a/x
Factors({y: 2})
Factors treats its factors as though they are all in the numerator, so
if you violate this assumption the results will be correct but will
not strictly correspond to the numerator and denominator of the ratio:
>>> a.div(x/z)
(Factors({y: 2}), Factors({z: -1}))
Factors is also naive about bases: it does not attempt any denesting
of Rational-base terms, for example the following does not become
2**(2*x)/2.
>>> Factors(2**(2*x + 2)).div(S(8))
(Factors({2: 2*x + 2}), Factors({8: 1}))
factor_terms can clean up such Rational-bases powers:
>>> from sympy.core.exprtools import factor_terms
>>> n, d = Factors(2**(2*x + 2)).div(S(8))
>>> n.as_expr()/d.as_expr()
2**(2*x + 2)/8
>>> factor_terms(_)
2**(2*x)/2
"""
quo, rem = dict(self.factors), {}
if not isinstance(other, Factors):
other = Factors(other)
if other.is_zero:
raise ZeroDivisionError
if self.is_zero:
return (Factors(S.Zero), Factors())
for factor, exp in other.factors.items():
if factor in quo:
d = quo[factor] - exp
if _isnumber(d):
if d <= 0:
del quo[factor]
if d >= 0:
if d:
quo[factor] = d
continue
exp = -d
else:
r = quo[factor].extract_additively(exp)
if r is not None:
if r:
quo[factor] = r
else: # should be handled already
del quo[factor]
else:
other_exp = exp
sc, sa = quo[factor].as_coeff_Add()
if sc:
oc, oa = other_exp.as_coeff_Add()
diff = sc - oc
if diff > 0:
quo[factor] -= oc
other_exp = oa
elif diff < 0:
quo[factor] -= sc
other_exp = oa - diff
else:
quo[factor] = sa
other_exp = oa
if other_exp:
rem[factor] = other_exp
else:
assert factor not in rem
continue
rem[factor] = exp
return Factors(quo), Factors(rem)
def quo(self, other): # Factors
"""Return numerator Factor of ``self / other``.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.quo(b) # same as a/b
Factors({y: 1})
"""
return self.div(other)[0]
def rem(self, other): # Factors
"""Return denominator Factors of ``self / other``.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.rem(b)
Factors({z: -1})
>>> a.rem(a)
Factors({})
"""
return self.div(other)[1]
def pow(self, other): # Factors
"""Return self raised to a non-negative integer power.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y
>>> a = Factors((x*y**2).as_powers_dict())
>>> a**2
Factors({x: 2, y: 4})
"""
if isinstance(other, Factors):
other = other.as_expr()
if other.is_Integer:
other = int(other)
if isinstance(other, SYMPY_INTS) and other >= 0:
factors = {}
if other:
for factor, exp in self.factors.items():
factors[factor] = exp*other
return Factors(factors)
else:
raise ValueError("expected non-negative integer, got %s" % other)
def gcd(self, other): # Factors
"""Return Factors of ``gcd(self, other)``. The keys are
the intersection of factors with the minimum exponent for
each factor.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.gcd(b)
Factors({x: 1, y: 1})
"""
if not isinstance(other, Factors):
other = Factors(other)
if other.is_zero:
return Factors(self.factors)
factors = {}
for factor, exp in self.factors.items():
factor, exp = sympify(factor), sympify(exp)
if factor in other.factors:
lt = (exp - other.factors[factor]).is_negative
if lt == True:
factors[factor] = exp
elif lt == False:
factors[factor] = other.factors[factor]
return Factors(factors)
def lcm(self, other): # Factors
"""Return Factors of ``lcm(self, other)`` which are
the union of factors with the maximum exponent for
each factor.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.lcm(b)
Factors({x: 1, y: 2, z: -1})
"""
if not isinstance(other, Factors):
other = Factors(other)
if any(f.is_zero for f in (self, other)):
return Factors(S.Zero)
factors = dict(self.factors)
for factor, exp in other.factors.items():
if factor in factors:
exp = max(exp, factors[factor])
factors[factor] = exp
return Factors(factors)
def __mul__(self, other): # Factors
return self.mul(other)
def __divmod__(self, other): # Factors
return self.div(other)
def __truediv__(self, other): # Factors
return self.quo(other)
def __mod__(self, other): # Factors
return self.rem(other)
def __pow__(self, other): # Factors
return self.pow(other)
def __eq__(self, other): # Factors
if not isinstance(other, Factors):
other = Factors(other)
return self.factors == other.factors
def __ne__(self, other): # Factors
return not self == other
class Term:
"""Efficient representation of ``coeff*(numer/denom)``. """
__slots__ = ('coeff', 'numer', 'denom')
def __init__(self, term, numer=None, denom=None): # Term
if numer is None and denom is None:
if not term.is_commutative:
raise NonCommutativeExpression(
'commutative expression expected')
coeff, factors = term.as_coeff_mul()
numer, denom = defaultdict(int), defaultdict(int)
for factor in factors:
base, exp = decompose_power(factor)
if base.is_Add:
cont, base = base.primitive()
coeff *= cont**exp
if exp > 0:
numer[base] += exp
else:
denom[base] += -exp
numer = Factors(numer)
denom = Factors(denom)
else:
coeff = term
if numer is None:
numer = Factors()
if denom is None:
denom = Factors()
self.coeff = coeff
self.numer = numer
self.denom = denom
def __hash__(self): # Term
return hash((self.coeff, self.numer, self.denom))
def __repr__(self): # Term
return "Term(%s, %s, %s)" % (self.coeff, self.numer, self.denom)
def as_expr(self): # Term
return self.coeff*(self.numer.as_expr()/self.denom.as_expr())
def mul(self, other): # Term
coeff = self.coeff*other.coeff
numer = self.numer.mul(other.numer)
denom = self.denom.mul(other.denom)
numer, denom = numer.normal(denom)
return Term(coeff, numer, denom)
def inv(self): # Term
return Term(1/self.coeff, self.denom, self.numer)
def quo(self, other): # Term
return self.mul(other.inv())
def pow(self, other): # Term
if other < 0:
return self.inv().pow(-other)
else:
return Term(self.coeff ** other,
self.numer.pow(other),
self.denom.pow(other))
def gcd(self, other): # Term
return Term(self.coeff.gcd(other.coeff),
self.numer.gcd(other.numer),
self.denom.gcd(other.denom))
def lcm(self, other): # Term
return Term(self.coeff.lcm(other.coeff),
self.numer.lcm(other.numer),
self.denom.lcm(other.denom))
def __mul__(self, other): # Term
if isinstance(other, Term):
return self.mul(other)
else:
return NotImplemented
def __truediv__(self, other): # Term
if isinstance(other, Term):
return self.quo(other)
else:
return NotImplemented
def __pow__(self, other): # Term
if isinstance(other, SYMPY_INTS):
return self.pow(other)
else:
return NotImplemented
def __eq__(self, other): # Term
return (self.coeff == other.coeff and
self.numer == other.numer and
self.denom == other.denom)
def __ne__(self, other): # Term
return not self == other
def _gcd_terms(terms, isprimitive=False, fraction=True):
"""Helper function for :func:`gcd_terms`.
Parameters
==========
isprimitive : boolean, optional
If ``isprimitive`` is True then the call to primitive
for an Add will be skipped. This is useful when the
content has already been extrated.
fraction : boolean, optional
If ``fraction`` is True then the expression will appear over a common
denominator, the lcm of all term denominators.
"""
if isinstance(terms, Basic) and not isinstance(terms, Tuple):
terms = Add.make_args(terms)
terms = list(map(Term, [t for t in terms if t]))
# there is some simplification that may happen if we leave this
# here rather than duplicate it before the mapping of Term onto
# the terms
if len(terms) == 0:
return S.Zero, S.Zero, S.One
if len(terms) == 1:
cont = terms[0].coeff
numer = terms[0].numer.as_expr()
denom = terms[0].denom.as_expr()
else:
cont = terms[0]
for term in terms[1:]:
cont = cont.gcd(term)
for i, term in enumerate(terms):
terms[i] = term.quo(cont)
if fraction:
denom = terms[0].denom
for term in terms[1:]:
denom = denom.lcm(term.denom)
numers = []
for term in terms:
numer = term.numer.mul(denom.quo(term.denom))
numers.append(term.coeff*numer.as_expr())
else:
numers = [t.as_expr() for t in terms]
denom = Term(S.One).numer
cont = cont.as_expr()
numer = Add(*numers)
denom = denom.as_expr()
if not isprimitive and numer.is_Add:
_cont, numer = numer.primitive()
cont *= _cont
return cont, numer, denom
def gcd_terms(terms, isprimitive=False, clear=True, fraction=True):
"""Compute the GCD of ``terms`` and put them together.
Parameters
==========
terms : Expr
Can be an expression or a non-Basic sequence of expressions
which will be handled as though they are terms from a sum.
isprimitive : bool, optional
If ``isprimitive`` is True the _gcd_terms will not run the primitive
method on the terms.
clear : bool, optional
It controls the removal of integers from the denominator of an Add
expression. When True (default), all numerical denominator will be cleared;
when False the denominators will be cleared only if all terms had numerical
denominators other than 1.
fraction : bool, optional
When True (default), will put the expression over a common
denominator.
Examples
========
>>> from sympy.core import gcd_terms
>>> from sympy.abc import x, y
>>> gcd_terms((x + 1)**2*y + (x + 1)*y**2)
y*(x + 1)*(x + y + 1)
>>> gcd_terms(x/2 + 1)
(x + 2)/2
>>> gcd_terms(x/2 + 1, clear=False)
x/2 + 1
>>> gcd_terms(x/2 + y/2, clear=False)
(x + y)/2
>>> gcd_terms(x/2 + 1/x)
(x**2 + 2)/(2*x)
>>> gcd_terms(x/2 + 1/x, fraction=False)
(x + 2/x)/2
>>> gcd_terms(x/2 + 1/x, fraction=False, clear=False)
x/2 + 1/x
>>> gcd_terms(x/2/y + 1/x/y)
(x**2 + 2)/(2*x*y)
>>> gcd_terms(x/2/y + 1/x/y, clear=False)
(x**2/2 + 1)/(x*y)
>>> gcd_terms(x/2/y + 1/x/y, clear=False, fraction=False)
(x/2 + 1/x)/y
The ``clear`` flag was ignored in this case because the returned
expression was a rational expression, not a simple sum.
See Also
========
factor_terms, sympy.polys.polytools.terms_gcd
"""
def mask(terms):
"""replace nc portions of each term with a unique Dummy symbols
and return the replacements to restore them"""
args = [(a, []) if a.is_commutative else a.args_cnc() for a in terms]
reps = []
for i, (c, nc) in enumerate(args):
if nc:
nc = Mul(*nc)
d = Dummy()
reps.append((d, nc))
c.append(d)
args[i] = Mul(*c)
else:
args[i] = c
return args, dict(reps)
isadd = isinstance(terms, Add)
addlike = isadd or not isinstance(terms, Basic) and \
is_sequence(terms, include=set) and \
not isinstance(terms, Dict)
if addlike:
if isadd: # i.e. an Add
terms = list(terms.args)
else:
terms = sympify(terms)
terms, reps = mask(terms)
cont, numer, denom = _gcd_terms(terms, isprimitive, fraction)
numer = numer.xreplace(reps)
coeff, factors = cont.as_coeff_Mul()
if not clear:
c, _coeff = coeff.as_coeff_Mul()
if not c.is_Integer and not clear and numer.is_Add:
n, d = c.as_numer_denom()
_numer = numer/d
if any(a.as_coeff_Mul()[0].is_Integer
for a in _numer.args):
numer = _numer
coeff = n*_coeff
return _keep_coeff(coeff, factors*numer/denom, clear=clear)
if not isinstance(terms, Basic):
return terms
if terms.is_Atom:
return terms
if terms.is_Mul:
c, args = terms.as_coeff_mul()
return _keep_coeff(c, Mul(*[gcd_terms(i, isprimitive, clear, fraction)
for i in args]), clear=clear)
def handle(a):
# don't treat internal args like terms of an Add
if not isinstance(a, Expr):
if isinstance(a, Basic):
return a.func(*[handle(i) for i in a.args])
return type(a)([handle(i) for i in a])
return gcd_terms(a, isprimitive, clear, fraction)
if isinstance(terms, Dict):
return Dict(*[(k, handle(v)) for k, v in terms.args])
return terms.func(*[handle(i) for i in terms.args])
def _factor_sum_int(expr, **kwargs):
"""Return Sum or Integral object with factors that are not
in the wrt variables removed. In cases where there are additive
terms in the function of the object that are independent, the
object will be separated into two objects.
Examples
========
>>> from sympy import Sum, factor_terms
>>> from sympy.abc import x, y
>>> factor_terms(Sum(x + y, (x, 1, 3)))
y*Sum(1, (x, 1, 3)) + Sum(x, (x, 1, 3))
>>> factor_terms(Sum(x*y, (x, 1, 3)))
y*Sum(x, (x, 1, 3))
Notes
=====
If a function in the summand or integrand is replaced
with a symbol, then this simplification should not be
done or else an incorrect result will be obtained when
the symbol is replaced with an expression that depends
on the variables of summation/integration:
>>> eq = Sum(y, (x, 1, 3))
>>> factor_terms(eq).subs(y, x).doit()
3*x
>>> eq.subs(y, x).doit()
6
"""
result = expr.function
if result == 0:
return S.Zero
limits = expr.limits
# get the wrt variables
wrt = {i.args[0] for i in limits}
# factor out any common terms that are independent of wrt
f = factor_terms(result, **kwargs)
i, d = f.as_independent(*wrt)
if isinstance(f, Add):
return i * expr.func(1, *limits) + expr.func(d, *limits)
else:
return i * expr.func(d, *limits)
def factor_terms(expr, radical=False, clear=False, fraction=False, sign=True):
"""Remove common factors from terms in all arguments without
changing the underlying structure of the expr. No expansion or
simplification (and no processing of non-commutatives) is performed.
Parameters
==========
radical: bool, optional
If radical=True then a radical common to all terms will be factored
out of any Add sub-expressions of the expr.
clear : bool, optional
If clear=False (default) then coefficients will not be separated
from a single Add if they can be distributed to leave one or more
terms with integer coefficients.
fraction : bool, optional
If fraction=True (default is False) then a common denominator will be
constructed for the expression.
sign : bool, optional
If sign=True (default) then even if the only factor in common is a -1,
it will be factored out of the expression.
Examples
========
>>> from sympy import factor_terms, Symbol
>>> from sympy.abc import x, y
>>> factor_terms(x + x*(2 + 4*y)**3)
x*(8*(2*y + 1)**3 + 1)
>>> A = Symbol('A', commutative=False)
>>> factor_terms(x*A + x*A + x*y*A)
x*(y*A + 2*A)
When ``clear`` is False, a rational will only be factored out of an
Add expression if all terms of the Add have coefficients that are
fractions:
>>> factor_terms(x/2 + 1, clear=False)
x/2 + 1
>>> factor_terms(x/2 + 1, clear=True)
(x + 2)/2
If a -1 is all that can be factored out, to *not* factor it out, the
flag ``sign`` must be False:
>>> factor_terms(-x - y)
-(x + y)
>>> factor_terms(-x - y, sign=False)
-x - y
>>> factor_terms(-2*x - 2*y, sign=False)
-2*(x + y)
See Also
========
gcd_terms, sympy.polys.polytools.terms_gcd
"""
def do(expr):
from sympy.concrete.summations import Sum
from sympy.integrals.integrals import Integral
is_iterable = iterable(expr)
if not isinstance(expr, Basic) or expr.is_Atom:
if is_iterable:
return type(expr)([do(i) for i in expr])
return expr
if expr.is_Pow or expr.is_Function or \
is_iterable or not hasattr(expr, 'args_cnc'):
args = expr.args
newargs = tuple([do(i) for i in args])
if newargs == args:
return expr
return expr.func(*newargs)
if isinstance(expr, (Sum, Integral)):
return _factor_sum_int(expr,
radical=radical, clear=clear,
fraction=fraction, sign=sign)
cont, p = expr.as_content_primitive(radical=radical, clear=clear)
if p.is_Add:
list_args = [do(a) for a in Add.make_args(p)]
# get a common negative (if there) which gcd_terms does not remove
if all(a.as_coeff_Mul()[0].extract_multiplicatively(-1) is not None
for a in list_args):
cont = -cont
list_args = [-a for a in list_args]
# watch out for exp(-(x+2)) which gcd_terms will change to exp(-x-2)
special = {}
for i, a in enumerate(list_args):
b, e = a.as_base_exp()
if e.is_Mul and e != Mul(*e.args):
list_args[i] = Dummy()
special[list_args[i]] = a
# rebuild p not worrying about the order which gcd_terms will fix
p = Add._from_args(list_args)
p = gcd_terms(p,
isprimitive=True,
clear=clear,
fraction=fraction).xreplace(special)
elif p.args:
p = p.func(
*[do(a) for a in p.args])
rv = _keep_coeff(cont, p, clear=clear, sign=sign)
return rv
expr = sympify(expr)
return do(expr)
def _mask_nc(eq, name=None):
"""
Return ``eq`` with non-commutative objects replaced with Dummy
symbols. A dictionary that can be used to restore the original
values is returned: if it is None, the expression is noncommutative
and cannot be made commutative. The third value returned is a list
of any non-commutative symbols that appear in the returned equation.
Explanation
===========
All non-commutative objects other than Symbols are replaced with
a non-commutative Symbol. Identical objects will be identified
by identical symbols.
If there is only 1 non-commutative object in an expression it will
be replaced with a commutative symbol. Otherwise, the non-commutative
entities are retained and the calling routine should handle
replacements in this case since some care must be taken to keep
track of the ordering of symbols when they occur within Muls.
Parameters
==========
name : str
``name``, if given, is the name that will be used with numbered Dummy
variables that will replace the non-commutative objects and is mainly
used for doctesting purposes.
Examples
========
>>> from sympy.physics.secondquant import Commutator, NO, F, Fd
>>> from sympy import symbols
>>> from sympy.core.exprtools import _mask_nc
>>> from sympy.abc import x, y
>>> A, B, C = symbols('A,B,C', commutative=False)
One nc-symbol:
>>> _mask_nc(A**2 - x**2, 'd')
(_d0**2 - x**2, {_d0: A}, [])
Multiple nc-symbols:
>>> _mask_nc(A**2 - B**2, 'd')
(A**2 - B**2, {}, [A, B])
An nc-object with nc-symbols but no others outside of it:
>>> _mask_nc(1 + x*Commutator(A, B), 'd')
(_d0*x + 1, {_d0: Commutator(A, B)}, [])
>>> _mask_nc(NO(Fd(x)*F(y)), 'd')
(_d0, {_d0: NO(CreateFermion(x)*AnnihilateFermion(y))}, [])
Multiple nc-objects:
>>> eq = x*Commutator(A, B) + x*Commutator(A, C)*Commutator(A, B)
>>> _mask_nc(eq, 'd')
(x*_d0 + x*_d1*_d0, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1])
Multiple nc-objects and nc-symbols:
>>> eq = A*Commutator(A, B) + B*Commutator(A, C)
>>> _mask_nc(eq, 'd')
(A*_d0 + B*_d1, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1, A, B])
"""
name = name or 'mask'
# Make Dummy() append sequential numbers to the name
def numbered_names():
i = 0
while True:
yield name + str(i)
i += 1
names = numbered_names()
def Dummy(*args, **kwargs):
from sympy import Dummy
return Dummy(next(names), *args, **kwargs)
expr = eq
if expr.is_commutative:
return eq, {}, []
# identify nc-objects; symbols and other
rep = []
nc_obj = set()
nc_syms = set()
pot = preorder_traversal(expr, keys=default_sort_key)
for i, a in enumerate(pot):
if any(a == r[0] for r in rep):
pot.skip()
elif not a.is_commutative:
if a.is_symbol:
nc_syms.add(a)
pot.skip()
elif not (a.is_Add or a.is_Mul or a.is_Pow):
nc_obj.add(a)
pot.skip()
# If there is only one nc symbol or object, it can be factored regularly
# but polys is going to complain, so replace it with a Dummy.
if len(nc_obj) == 1 and not nc_syms:
rep.append((nc_obj.pop(), Dummy()))
elif len(nc_syms) == 1 and not nc_obj:
rep.append((nc_syms.pop(), Dummy()))
# Any remaining nc-objects will be replaced with an nc-Dummy and
# identified as an nc-Symbol to watch out for
nc_obj = sorted(nc_obj, key=default_sort_key)
for n in nc_obj:
nc = Dummy(commutative=False)
rep.append((n, nc))
nc_syms.add(nc)
expr = expr.subs(rep)
nc_syms = list(nc_syms)
nc_syms.sort(key=default_sort_key)
return expr, {v: k for k, v in rep}, nc_syms
def factor_nc(expr):
"""Return the factored form of ``expr`` while handling non-commutative
expressions.
Examples
========
>>> from sympy.core.exprtools import factor_nc
>>> from sympy import Symbol
>>> from sympy.abc import x
>>> A = Symbol('A', commutative=False)
>>> B = Symbol('B', commutative=False)
>>> factor_nc((x**2 + 2*A*x + A**2).expand())
(x + A)**2
>>> factor_nc(((x + A)*(x + B)).expand())
(x + A)*(x + B)
"""
from sympy.simplify.simplify import powsimp
from sympy.polys import gcd, factor
def _pemexpand(expr):
"Expand with the minimal set of hints necessary to check the result."
return expr.expand(deep=True, mul=True, power_exp=True,
power_base=False, basic=False, multinomial=True, log=False)
expr = sympify(expr)
if not isinstance(expr, Expr) or not expr.args:
return expr
if not expr.is_Add:
return expr.func(*[factor_nc(a) for a in expr.args])
expr, rep, nc_symbols = _mask_nc(expr)
if rep:
return factor(expr).subs(rep)
else:
args = [a.args_cnc() for a in Add.make_args(expr)]
c = g = l = r = S.One
hit = False
# find any commutative gcd term
for i, a in enumerate(args):
if i == 0:
c = Mul._from_args(a[0])
elif a[0]:
c = gcd(c, Mul._from_args(a[0]))
else:
c = S.One
if c is not S.One:
hit = True
c, g = c.as_coeff_Mul()
if g is not S.One:
for i, (cc, _) in enumerate(args):
cc = list(Mul.make_args(Mul._from_args(list(cc))/g))
args[i][0] = cc
for i, (cc, _) in enumerate(args):
cc[0] = cc[0]/c
args[i][0] = cc
# find any noncommutative common prefix
for i, a in enumerate(args):
if i == 0:
n = a[1][:]
else:
n = common_prefix(n, a[1])
if not n:
# is there a power that can be extracted?
if not args[0][1]:
break
b, e = args[0][1][0].as_base_exp()
ok = False
if e.is_Integer:
for t in args:
if not t[1]:
break
bt, et = t[1][0].as_base_exp()
if et.is_Integer and bt == b:
e = min(e, et)
else:
break
else:
ok = hit = True
l = b**e
il = b**-e
for _ in args:
_[1][0] = il*_[1][0]
break
if not ok:
break
else:
hit = True
lenn = len(n)
l = Mul(*n)
for _ in args:
_[1] = _[1][lenn:]
# find any noncommutative common suffix
for i, a in enumerate(args):
if i == 0:
n = a[1][:]
else:
n = common_suffix(n, a[1])
if not n:
# is there a power that can be extracted?
if not args[0][1]:
break
b, e = args[0][1][-1].as_base_exp()
ok = False
if e.is_Integer:
for t in args:
if not t[1]:
break
bt, et = t[1][-1].as_base_exp()
if et.is_Integer and bt == b:
e = min(e, et)
else:
break
else:
ok = hit = True
r = b**e
il = b**-e
for _ in args:
_[1][-1] = _[1][-1]*il
break
if not ok:
break
else:
hit = True
lenn = len(n)
r = Mul(*n)
for _ in args:
_[1] = _[1][:len(_[1]) - lenn]
if hit:
mid = Add(*[Mul(*cc)*Mul(*nc) for cc, nc in args])
else:
mid = expr
# sort the symbols so the Dummys would appear in the same
# order as the original symbols, otherwise you may introduce
# a factor of -1, e.g. A**2 - B**2) -- {A:y, B:x} --> y**2 - x**2
# and the former factors into two terms, (A - B)*(A + B) while the
# latter factors into 3 terms, (-1)*(x - y)*(x + y)
rep1 = [(n, Dummy()) for n in sorted(nc_symbols, key=default_sort_key)]
unrep1 = [(v, k) for k, v in rep1]
unrep1.reverse()
new_mid, r2, _ = _mask_nc(mid.subs(rep1))
new_mid = powsimp(factor(new_mid))
new_mid = new_mid.subs(r2).subs(unrep1)
if new_mid.is_Pow:
return _keep_coeff(c, g*l*new_mid*r)
if new_mid.is_Mul:
# XXX TODO there should be a way to inspect what order the terms
# must be in and just select the plausible ordering without
# checking permutations
cfac = []
ncfac = []
for f in new_mid.args:
if f.is_commutative:
cfac.append(f)
else:
b, e = f.as_base_exp()
if e.is_Integer:
ncfac.extend([b]*e)
else:
ncfac.append(f)
pre_mid = g*Mul(*cfac)*l
target = _pemexpand(expr/c)
for s in variations(ncfac, len(ncfac)):
ok = pre_mid*Mul(*s)*r
if _pemexpand(ok) == target:
return _keep_coeff(c, ok)
# mid was an Add that didn't factor successfully
return _keep_coeff(c, g*l*mid*r)
|
88dad447e3bce8f83cdfda2392a5b08c8dfba5ffabf3dadd7343e6ce9485c386 | """
This module contains the machinery handling assumptions.
All symbolic objects have assumption attributes that can be accessed via
.is_<assumption name> attribute.
Assumptions determine certain properties of symbolic objects and can
have 3 possible values: True, False, None. True is returned if the
object has the property and False is returned if it doesn't or can't
(i.e. doesn't make sense):
>>> from sympy import I
>>> I.is_algebraic
True
>>> I.is_real
False
>>> I.is_prime
False
When the property cannot be determined (or when a method is not
implemented) None will be returned, e.g. a generic symbol, x, may or
may not be positive so a value of None is returned for x.is_positive.
By default, all symbolic values are in the largest set in the given context
without specifying the property. For example, a symbol that has a property
being integer, is also real, complex, etc.
Here follows a list of possible assumption names:
.. glossary::
commutative
object commutes with any other object with
respect to multiplication operation.
complex
object can have only values from the set
of complex numbers.
imaginary
object value is a number that can be written as a real
number multiplied by the imaginary unit ``I``. See
[3]_. Please note, that ``0`` is not considered to be an
imaginary number, see
`issue #7649 <https://github.com/sympy/sympy/issues/7649>`_.
real
object can have only values from the set
of real numbers.
integer
object can have only values from the set
of integers.
odd
even
object can have only values from the set of
odd (even) integers [2]_.
prime
object is a natural number greater than ``1`` that has
no positive divisors other than ``1`` and itself. See [6]_.
composite
object is a positive integer that has at least one positive
divisor other than ``1`` or the number itself. See [4]_.
zero
object has the value of ``0``.
nonzero
object is a real number that is not zero.
rational
object can have only values from the set
of rationals.
algebraic
object can have only values from the set
of algebraic numbers [11]_.
transcendental
object can have only values from the set
of transcendental numbers [10]_.
irrational
object value cannot be represented exactly by Rational, see [5]_.
finite
infinite
object absolute value is bounded (arbitrarily large).
See [7]_, [8]_, [9]_.
negative
nonnegative
object can have only negative (nonnegative)
values [1]_.
positive
nonpositive
object can have only positive (only
nonpositive) values.
hermitian
antihermitian
object belongs to the field of hermitian
(antihermitian) operators.
Examples
========
>>> from sympy import Symbol
>>> x = Symbol('x', real=True); x
x
>>> x.is_real
True
>>> x.is_complex
True
See Also
========
.. seealso::
:py:class:`sympy.core.numbers.ImaginaryUnit`
:py:class:`sympy.core.numbers.Zero`
:py:class:`sympy.core.numbers.One`
Notes
=====
The fully-resolved assumptions for any SymPy expression
can be obtained as follows:
>>> from sympy.core.assumptions import assumptions
>>> x = Symbol('x',positive=True)
>>> assumptions(x + I)
{'commutative': True, 'complex': True, 'composite': False, 'even':
False, 'extended_negative': False, 'extended_nonnegative': False,
'extended_nonpositive': False, 'extended_nonzero': False,
'extended_positive': False, 'extended_real': False, 'finite': True,
'imaginary': False, 'infinite': False, 'integer': False, 'irrational':
False, 'negative': False, 'noninteger': False, 'nonnegative': False,
'nonpositive': False, 'nonzero': False, 'odd': False, 'positive':
False, 'prime': False, 'rational': False, 'real': False, 'zero':
False}
Developers Notes
================
The current (and possibly incomplete) values are stored
in the ``obj._assumptions dictionary``; queries to getter methods
(with property decorators) or attributes of objects/classes
will return values and update the dictionary.
>>> eq = x**2 + I
>>> eq._assumptions
{}
>>> eq.is_finite
True
>>> eq._assumptions
{'finite': True, 'infinite': False}
For a Symbol, there are two locations for assumptions that may
be of interest. The ``assumptions0`` attribute gives the full set of
assumptions derived from a given set of initial assumptions. The
latter assumptions are stored as ``Symbol._assumptions.generator``
>>> Symbol('x', prime=True, even=True)._assumptions.generator
{'even': True, 'prime': True}
The ``generator`` is not necessarily canonical nor is it filtered
in any way: it records the assumptions used to instantiate a Symbol
and (for storage purposes) represents a more compact representation
of the assumptions needed to recreate the full set in
`Symbol.assumptions0`.
References
==========
.. [1] https://en.wikipedia.org/wiki/Negative_number
.. [2] https://en.wikipedia.org/wiki/Parity_%28mathematics%29
.. [3] https://en.wikipedia.org/wiki/Imaginary_number
.. [4] https://en.wikipedia.org/wiki/Composite_number
.. [5] https://en.wikipedia.org/wiki/Irrational_number
.. [6] https://en.wikipedia.org/wiki/Prime_number
.. [7] https://en.wikipedia.org/wiki/Finite
.. [8] https://docs.python.org/3/library/math.html#math.isfinite
.. [9] http://docs.scipy.org/doc/numpy/reference/generated/numpy.isfinite.html
.. [10] https://en.wikipedia.org/wiki/Transcendental_number
.. [11] https://en.wikipedia.org/wiki/Algebraic_number
"""
from sympy.core.facts import FactRules, FactKB
from sympy.core.core import BasicMeta
from sympy.core.sympify import sympify
from random import shuffle
_assume_rules = FactRules([
'integer -> rational',
'rational -> real',
'rational -> algebraic',
'algebraic -> complex',
'transcendental == complex & !algebraic',
'real -> hermitian',
'imaginary -> complex',
'imaginary -> antihermitian',
'extended_real -> commutative',
'complex -> commutative',
'complex -> finite',
'odd == integer & !even',
'even == integer & !odd',
'real -> complex',
'extended_real -> real | infinite',
'real == extended_real & finite',
'extended_real == extended_negative | zero | extended_positive',
'extended_negative == extended_nonpositive & extended_nonzero',
'extended_positive == extended_nonnegative & extended_nonzero',
'extended_nonpositive == extended_real & !extended_positive',
'extended_nonnegative == extended_real & !extended_negative',
'real == negative | zero | positive',
'negative == nonpositive & nonzero',
'positive == nonnegative & nonzero',
'nonpositive == real & !positive',
'nonnegative == real & !negative',
'positive == extended_positive & finite',
'negative == extended_negative & finite',
'nonpositive == extended_nonpositive & finite',
'nonnegative == extended_nonnegative & finite',
'nonzero == extended_nonzero & finite',
'zero -> even & finite',
'zero == extended_nonnegative & extended_nonpositive',
'zero == nonnegative & nonpositive',
'nonzero -> real',
'prime -> integer & positive',
'composite -> integer & positive & !prime',
'!composite -> !positive | !even | prime',
'irrational == real & !rational',
'imaginary -> !extended_real',
'infinite == !finite',
'noninteger == extended_real & !integer',
'extended_nonzero == extended_real & !zero',
])
_assume_defined = _assume_rules.defined_facts.copy()
_assume_defined.add('polar')
_assume_defined = frozenset(_assume_defined)
def assumptions(expr, _check=None):
"""return the T/F assumptions of ``expr``"""
n = sympify(expr)
if n.is_Symbol:
rv = n.assumptions0 # are any important ones missing?
if _check is not None:
rv = {k: rv[k] for k in set(rv) & set(_check)}
return rv
rv = {}
for k in _assume_defined if _check is None else _check:
v = getattr(n, 'is_{}'.format(k))
if v is not None:
rv[k] = v
return rv
def common_assumptions(exprs, check=None):
"""return those assumptions which have the same True or False
value for all the given expressions.
Examples
========
>>> from sympy.core.assumptions import common_assumptions
>>> from sympy import oo, pi, sqrt
>>> common_assumptions([-4, 0, sqrt(2), 2, pi, oo])
{'commutative': True, 'composite': False,
'extended_real': True, 'imaginary': False, 'odd': False}
By default, all assumptions are tested; pass an iterable of the
assumptions to limit those that are reported:
>>> common_assumptions([0, 1, 2], ['positive', 'integer'])
{'integer': True}
"""
check = _assume_defined if check is None else set(check)
if not check or not exprs:
return {}
# get all assumptions for each
assume = [assumptions(i, _check=check) for i in sympify(exprs)]
# focus on those of interest that are True
for i, e in enumerate(assume):
assume[i] = {k: e[k] for k in set(e) & check}
# what assumptions are in common?
common = set.intersection(*[set(i) for i in assume])
# which ones hold the same value
a = assume[0]
return {k: a[k] for k in common if all(a[k] == b[k]
for b in assume)}
def failing_assumptions(expr, **assumptions):
"""
Return a dictionary containing assumptions with values not
matching those of the passed assumptions.
Examples
========
>>> from sympy import failing_assumptions, Symbol
>>> x = Symbol('x', real=True, positive=True)
>>> y = Symbol('y')
>>> failing_assumptions(6*x + y, real=True, positive=True)
{'positive': None, 'real': None}
>>> failing_assumptions(x**2 - 1, positive=True)
{'positive': None}
If *expr* satisfies all of the assumptions, an empty dictionary is returned.
>>> failing_assumptions(x**2, positive=True)
{}
"""
expr = sympify(expr)
failed = {}
for k in assumptions:
test = getattr(expr, 'is_%s' % k, None)
if test is not assumptions[k]:
failed[k] = test
return failed # {} or {assumption: value != desired}
def check_assumptions(expr, against=None, **assume):
"""
Checks whether assumptions of ``expr`` match the T/F assumptions
given (or possessed by ``against``). True is returned if all
assumptions match; False is returned if there is a mismatch and
the assumption in ``expr`` is not None; else None is returned.
Explanation
===========
*assume* is a dict of assumptions with True or False values
Examples
========
>>> from sympy import Symbol, pi, I, exp, check_assumptions
>>> check_assumptions(-5, integer=True)
True
>>> check_assumptions(pi, real=True, integer=False)
True
>>> check_assumptions(pi, real=True, negative=True)
False
>>> check_assumptions(exp(I*pi/7), real=False)
True
>>> x = Symbol('x', real=True, positive=True)
>>> check_assumptions(2*x + 1, real=True, positive=True)
True
>>> check_assumptions(-2*x - 5, real=True, positive=True)
False
To check assumptions of *expr* against another variable or expression,
pass the expression or variable as ``against``.
>>> check_assumptions(2*x + 1, x)
True
To see if a number matches the assumptions of an expression, pass
the number as the first argument, else its specific assumptions
may not have a non-None value in the expression:
>>> check_assumptions(x, 3)
>>> check_assumptions(3, x)
True
``None`` is returned if ``check_assumptions()`` could not conclude.
>>> check_assumptions(2*x - 1, x)
>>> z = Symbol('z')
>>> check_assumptions(z, real=True)
See Also
========
failing_assumptions
"""
expr = sympify(expr)
if against is not None:
if assume:
raise ValueError(
'Expecting `against` or `assume`, not both.')
assume = assumptions(against)
known = True
for k, v in assume.items():
if v is None:
continue
e = getattr(expr, 'is_' + k, None)
if e is None:
known = None
elif v != e:
return False
return known
class StdFactKB(FactKB):
"""A FactKB specialized for the built-in rules
This is the only kind of FactKB that Basic objects should use.
"""
def __init__(self, facts=None):
super().__init__(_assume_rules)
# save a copy of the facts dict
if not facts:
self._generator = {}
elif not isinstance(facts, FactKB):
self._generator = facts.copy()
else:
self._generator = facts.generator
if facts:
self.deduce_all_facts(facts)
def copy(self):
return self.__class__(self)
@property
def generator(self):
return self._generator.copy()
def as_property(fact):
"""Convert a fact name to the name of the corresponding property"""
return 'is_%s' % fact
def make_property(fact):
"""Create the automagic property corresponding to a fact."""
def getit(self):
try:
return self._assumptions[fact]
except KeyError:
if self._assumptions is self.default_assumptions:
self._assumptions = self.default_assumptions.copy()
return _ask(fact, self)
getit.func_name = as_property(fact)
return property(getit)
def _ask(fact, obj):
"""
Find the truth value for a property of an object.
This function is called when a request is made to see what a fact
value is.
For this we use several techniques:
First, the fact-evaluation function is tried, if it exists (for
example _eval_is_integer). Then we try related facts. For example
rational --> integer
another example is joined rule:
integer & !odd --> even
so in the latter case if we are looking at what 'even' value is,
'integer' and 'odd' facts will be asked.
In all cases, when we settle on some fact value, its implications are
deduced, and the result is cached in ._assumptions.
"""
assumptions = obj._assumptions
handler_map = obj._prop_handler
# Store None into the assumptions so that recursive attempts at
# evaluating the same fact don't trigger infinite recursion.
assumptions._tell(fact, None)
# First try the assumption evaluation function if it exists
try:
evaluate = handler_map[fact]
except KeyError:
pass
else:
a = evaluate(obj)
if a is not None:
assumptions.deduce_all_facts(((fact, a),))
return a
# Try assumption's prerequisites
prereq = list(_assume_rules.prereq[fact])
shuffle(prereq)
for pk in prereq:
if pk in assumptions:
continue
if pk in handler_map:
_ask(pk, obj)
# we might have found the value of fact
ret_val = assumptions.get(fact)
if ret_val is not None:
return ret_val
# Note: the result has already been cached
return None
class ManagedProperties(BasicMeta):
"""Metaclass for classes with old-style assumptions"""
def __init__(cls, *args, **kws):
BasicMeta.__init__(cls, *args, **kws)
local_defs = {}
for k in _assume_defined:
attrname = as_property(k)
v = cls.__dict__.get(attrname, '')
if isinstance(v, (bool, int, type(None))):
if v is not None:
v = bool(v)
local_defs[k] = v
defs = {}
for base in reversed(cls.__bases__):
assumptions = getattr(base, '_explicit_class_assumptions', None)
if assumptions is not None:
defs.update(assumptions)
defs.update(local_defs)
cls._explicit_class_assumptions = defs
cls.default_assumptions = StdFactKB(defs)
cls._prop_handler = {}
for k in _assume_defined:
eval_is_meth = getattr(cls, '_eval_is_%s' % k, None)
if eval_is_meth is not None:
cls._prop_handler[k] = eval_is_meth
# Put definite results directly into the class dict, for speed
for k, v in cls.default_assumptions.items():
setattr(cls, as_property(k), v)
# protection e.g. for Integer.is_even=F <- (Rational.is_integer=F)
derived_from_bases = set()
for base in cls.__bases__:
default_assumptions = getattr(base, 'default_assumptions', None)
# is an assumption-aware class
if default_assumptions is not None:
derived_from_bases.update(default_assumptions)
for fact in derived_from_bases - set(cls.default_assumptions):
pname = as_property(fact)
if pname not in cls.__dict__:
setattr(cls, pname, make_property(fact))
# Finally, add any missing automagic property (e.g. for Basic)
for fact in _assume_defined:
pname = as_property(fact)
if not hasattr(cls, pname):
setattr(cls, pname, make_property(fact))
|
2cad2e22c4d8ba8a0b41c34afc4f84468315cf4152f061a290b3a05e2d630657 | """
There are three types of functions implemented in SymPy:
1) defined functions (in the sense that they can be evaluated) like
exp or sin; they have a name and a body:
f = exp
2) undefined function which have a name but no body. Undefined
functions can be defined using a Function class as follows:
f = Function('f')
(the result will be a Function instance)
3) anonymous function (or lambda function) which have a body (defined
with dummy variables) but have no name:
f = Lambda(x, exp(x)*x)
f = Lambda((x, y), exp(x)*y)
The fourth type of functions are composites, like (sin + cos)(x); these work in
SymPy core, but are not yet part of SymPy.
Examples
========
>>> import sympy
>>> f = sympy.Function("f")
>>> from sympy.abc import x
>>> f(x)
f(x)
>>> print(sympy.srepr(f(x).func))
Function('f')
>>> f(x).args
(x,)
"""
from typing import Any, Dict as tDict, Optional, Set as tSet, Tuple as tTuple, Union
from .add import Add
from .assumptions import ManagedProperties
from .basic import Basic, _atomic
from .cache import cacheit
from .compatibility import iterable, is_sequence, as_int, ordered, Iterable
from .decorators import _sympifyit
from .expr import Expr, AtomicExpr
from .numbers import Rational, Float
from .operations import LatticeOp
from .rules import Transform
from .singleton import S
from .sympify import sympify
from sympy.core.containers import Tuple, Dict
from sympy.core.parameters import global_parameters
from sympy.core.logic import fuzzy_and, fuzzy_or, fuzzy_not, FuzzyBool
from sympy.utilities import default_sort_key
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.iterables import has_dups, sift
from sympy.utilities.misc import filldedent
import mpmath
import mpmath.libmp as mlib
import inspect
from collections import Counter
def _coeff_isneg(a):
"""Return True if the leading Number is negative.
Examples
========
>>> from sympy.core.function import _coeff_isneg
>>> from sympy import S, Symbol, oo, pi
>>> _coeff_isneg(-3*pi)
True
>>> _coeff_isneg(S(3))
False
>>> _coeff_isneg(-oo)
True
>>> _coeff_isneg(Symbol('n', negative=True)) # coeff is 1
False
For matrix expressions:
>>> from sympy import MatrixSymbol, sqrt
>>> A = MatrixSymbol("A", 3, 3)
>>> _coeff_isneg(-sqrt(2)*A)
True
>>> _coeff_isneg(sqrt(2)*A)
False
"""
if a.is_MatMul:
a = a.args[0]
if a.is_Mul:
a = a.args[0]
return a.is_Number and a.is_extended_negative
class PoleError(Exception):
pass
class ArgumentIndexError(ValueError):
def __str__(self):
return ("Invalid operation with argument number %s for Function %s" %
(self.args[1], self.args[0]))
class BadSignatureError(TypeError):
'''Raised when a Lambda is created with an invalid signature'''
pass
class BadArgumentsError(TypeError):
'''Raised when a Lambda is called with an incorrect number of arguments'''
pass
# Python 2/3 version that does not raise a Deprecation warning
def arity(cls):
"""Return the arity of the function if it is known, else None.
Explanation
===========
When default values are specified for some arguments, they are
optional and the arity is reported as a tuple of possible values.
Examples
========
>>> from sympy.core.function import arity
>>> from sympy import log
>>> arity(lambda x: x)
1
>>> arity(log)
(1, 2)
>>> arity(lambda *x: sum(x)) is None
True
"""
eval_ = getattr(cls, 'eval', cls)
parameters = inspect.signature(eval_).parameters.items()
if [p for _, p in parameters if p.kind == p.VAR_POSITIONAL]:
return
p_or_k = [p for _, p in parameters if p.kind == p.POSITIONAL_OR_KEYWORD]
# how many have no default and how many have a default value
no, yes = map(len, sift(p_or_k,
lambda p:p.default == p.empty, binary=True))
return no if not yes else tuple(range(no, no + yes + 1))
class FunctionClass(ManagedProperties):
"""
Base class for function classes. FunctionClass is a subclass of type.
Use Function('<function name>' [ , signature ]) to create
undefined function classes.
"""
_new = type.__new__
def __init__(cls, *args, **kwargs):
# honor kwarg value or class-defined value before using
# the number of arguments in the eval function (if present)
nargs = kwargs.pop('nargs', cls.__dict__.get('nargs', arity(cls)))
if nargs is None and 'nargs' not in cls.__dict__:
for supcls in cls.__mro__:
if hasattr(supcls, '_nargs'):
nargs = supcls._nargs
break
else:
continue
# Canonicalize nargs here; change to set in nargs.
if is_sequence(nargs):
if not nargs:
raise ValueError(filldedent('''
Incorrectly specified nargs as %s:
if there are no arguments, it should be
`nargs = 0`;
if there are any number of arguments,
it should be
`nargs = None`''' % str(nargs)))
nargs = tuple(ordered(set(nargs)))
elif nargs is not None:
nargs = (as_int(nargs),)
cls._nargs = nargs
super().__init__(*args, **kwargs)
@property
def __signature__(self):
"""
Allow Python 3's inspect.signature to give a useful signature for
Function subclasses.
"""
# Python 3 only, but backports (like the one in IPython) still might
# call this.
try:
from inspect import signature
except ImportError:
return None
# TODO: Look at nargs
return signature(self.eval)
@property
def free_symbols(self):
return set()
@property
def xreplace(self):
# Function needs args so we define a property that returns
# a function that takes args...and then use that function
# to return the right value
return lambda rule, **_: rule.get(self, self)
@property
def nargs(self):
"""Return a set of the allowed number of arguments for the function.
Examples
========
>>> from sympy.core.function import Function
>>> f = Function('f')
If the function can take any number of arguments, the set of whole
numbers is returned:
>>> Function('f').nargs
Naturals0
If the function was initialized to accept one or more arguments, a
corresponding set will be returned:
>>> Function('f', nargs=1).nargs
FiniteSet(1)
>>> Function('f', nargs=(2, 1)).nargs
FiniteSet(1, 2)
The undefined function, after application, also has the nargs
attribute; the actual number of arguments is always available by
checking the ``args`` attribute:
>>> f = Function('f')
>>> f(1).nargs
Naturals0
>>> len(f(1).args)
1
"""
from sympy.sets.sets import FiniteSet
# XXX it would be nice to handle this in __init__ but there are import
# problems with trying to import FiniteSet there
return FiniteSet(*self._nargs) if self._nargs else S.Naturals0
def __repr__(cls):
return cls.__name__
class Application(Basic, metaclass=FunctionClass):
"""
Base class for applied functions.
Explanation
===========
Instances of Application represent the result of applying an application of
any type to any object.
"""
is_Function = True
@cacheit
def __new__(cls, *args, **options):
from sympy.sets.fancysets import Naturals0
from sympy.sets.sets import FiniteSet
args = list(map(sympify, args))
evaluate = options.pop('evaluate', global_parameters.evaluate)
# WildFunction (and anything else like it) may have nargs defined
# and we throw that value away here
options.pop('nargs', None)
if options:
raise ValueError("Unknown options: %s" % options)
if evaluate:
evaluated = cls.eval(*args)
if evaluated is not None:
return evaluated
obj = super().__new__(cls, *args, **options)
# make nargs uniform here
sentinel = object()
objnargs = getattr(obj, "nargs", sentinel)
if objnargs is not sentinel:
# things passing through here:
# - functions subclassed from Function (e.g. myfunc(1).nargs)
# - functions like cos(1).nargs
# - AppliedUndef with given nargs like Function('f', nargs=1)(1).nargs
# Canonicalize nargs here
if is_sequence(objnargs):
nargs = tuple(ordered(set(objnargs)))
elif objnargs is not None:
nargs = (as_int(objnargs),)
else:
nargs = None
else:
# things passing through here:
# - WildFunction('f').nargs
# - AppliedUndef with no nargs like Function('f')(1).nargs
nargs = obj._nargs # note the underscore here
# convert to FiniteSet
obj.nargs = FiniteSet(*nargs) if nargs else Naturals0()
return obj
@classmethod
def eval(cls, *args):
"""
Returns a canonical form of cls applied to arguments args.
Explanation
===========
The eval() method is called when the class cls is about to be
instantiated and it should return either some simplified instance
(possible of some other class), or if the class cls should be
unmodified, return None.
Examples of eval() for the function "sign"
---------------------------------------------
.. code-block:: python
@classmethod
def eval(cls, arg):
if arg is S.NaN:
return S.NaN
if arg.is_zero: return S.Zero
if arg.is_positive: return S.One
if arg.is_negative: return S.NegativeOne
if isinstance(arg, Mul):
coeff, terms = arg.as_coeff_Mul(rational=True)
if coeff is not S.One:
return cls(coeff) * cls(terms)
"""
return
@property
def func(self):
return self.__class__
def _eval_subs(self, old, new):
if (old.is_Function and new.is_Function and
callable(old) and callable(new) and
old == self.func and len(self.args) in new.nargs):
return new(*[i._subs(old, new) for i in self.args])
class Function(Application, Expr):
"""
Base class for applied mathematical functions.
It also serves as a constructor for undefined function classes.
Examples
========
First example shows how to use Function as a constructor for undefined
function classes:
>>> from sympy import Function, Symbol
>>> x = Symbol('x')
>>> f = Function('f')
>>> g = Function('g')(x)
>>> f
f
>>> f(x)
f(x)
>>> g
g(x)
>>> f(x).diff(x)
Derivative(f(x), x)
>>> g.diff(x)
Derivative(g(x), x)
Assumptions can be passed to Function, and if function is initialized with a
Symbol, the function inherits the name and assumptions associated with the Symbol:
>>> f_real = Function('f', real=True)
>>> f_real(x).is_real
True
>>> f_real_inherit = Function(Symbol('f', real=True))
>>> f_real_inherit(x).is_real
True
Note that assumptions on a function are unrelated to the assumptions on
the variable it is called on. If you want to add a relationship, subclass
Function and define the appropriate ``_eval_is_assumption`` methods.
In the following example Function is used as a base class for
``my_func`` that represents a mathematical function *my_func*. Suppose
that it is well known, that *my_func(0)* is *1* and *my_func* at infinity
goes to *0*, so we want those two simplifications to occur automatically.
Suppose also that *my_func(x)* is real exactly when *x* is real. Here is
an implementation that honours those requirements:
>>> from sympy import Function, S, oo, I, sin
>>> class my_func(Function):
...
... @classmethod
... def eval(cls, x):
... if x.is_Number:
... if x.is_zero:
... return S.One
... elif x is S.Infinity:
... return S.Zero
...
... def _eval_is_real(self):
... return self.args[0].is_real
...
>>> x = S('x')
>>> my_func(0) + sin(0)
1
>>> my_func(oo)
0
>>> my_func(3.54).n() # Not yet implemented for my_func.
my_func(3.54)
>>> my_func(I).is_real
False
In order for ``my_func`` to become useful, several other methods would
need to be implemented. See source code of some of the already
implemented functions for more complete examples.
Also, if the function can take more than one argument, then ``nargs``
must be defined, e.g. if ``my_func`` can take one or two arguments
then,
>>> class my_func(Function):
... nargs = (1, 2)
...
>>>
"""
@property
def _diff_wrt(self):
return False
@cacheit
def __new__(cls, *args, **options):
# Handle calls like Function('f')
if cls is Function:
return UndefinedFunction(*args, **options)
n = len(args)
if n not in cls.nargs:
# XXX: exception message must be in exactly this format to
# make it work with NumPy's functions like vectorize(). See,
# for example, https://github.com/numpy/numpy/issues/1697.
# The ideal solution would be just to attach metadata to
# the exception and change NumPy to take advantage of this.
temp = ('%(name)s takes %(qual)s %(args)s '
'argument%(plural)s (%(given)s given)')
raise TypeError(temp % {
'name': cls,
'qual': 'exactly' if len(cls.nargs) == 1 else 'at least',
'args': min(cls.nargs),
'plural': 's'*(min(cls.nargs) != 1),
'given': n})
evaluate = options.get('evaluate', global_parameters.evaluate)
result = super().__new__(cls, *args, **options)
if evaluate and isinstance(result, cls) and result.args:
pr2 = min(cls._should_evalf(a) for a in result.args)
if pr2 > 0:
pr = max(cls._should_evalf(a) for a in result.args)
result = result.evalf(mlib.libmpf.prec_to_dps(pr))
return result
@classmethod
def _should_evalf(cls, arg):
"""
Decide if the function should automatically evalf().
Explanation
===========
By default (in this implementation), this happens if (and only if) the
ARG is a floating point number.
This function is used by __new__.
Returns the precision to evalf to, or -1 if it shouldn't evalf.
"""
from sympy.core.evalf import pure_complex
if arg.is_Float:
return arg._prec
if not arg.is_Add:
return -1
m = pure_complex(arg)
if m is None or not (m[0].is_Float or m[1].is_Float):
return -1
l = [i._prec for i in m if i.is_Float]
l.append(-1)
return max(l)
@classmethod
def class_key(cls):
from sympy.sets.fancysets import Naturals0
funcs = {
'exp': 10,
'log': 11,
'sin': 20,
'cos': 21,
'tan': 22,
'cot': 23,
'sinh': 30,
'cosh': 31,
'tanh': 32,
'coth': 33,
'conjugate': 40,
're': 41,
'im': 42,
'arg': 43,
}
name = cls.__name__
try:
i = funcs[name]
except KeyError:
i = 0 if isinstance(cls.nargs, Naturals0) else 10000
return 4, i, name
def _eval_evalf(self, prec):
def _get_mpmath_func(fname):
"""Lookup mpmath function based on name"""
if isinstance(self, AppliedUndef):
# Shouldn't lookup in mpmath but might have ._imp_
return None
if not hasattr(mpmath, fname):
from sympy.utilities.lambdify import MPMATH_TRANSLATIONS
fname = MPMATH_TRANSLATIONS.get(fname, None)
if fname is None:
return None
return getattr(mpmath, fname)
_eval_mpmath = getattr(self, '_eval_mpmath', None)
if _eval_mpmath is None:
func = _get_mpmath_func(self.func.__name__)
args = self.args
else:
func, args = _eval_mpmath()
# Fall-back evaluation
if func is None:
imp = getattr(self, '_imp_', None)
if imp is None:
return None
try:
return Float(imp(*[i.evalf(prec) for i in self.args]), prec)
except (TypeError, ValueError):
return None
# Convert all args to mpf or mpc
# Convert the arguments to *higher* precision than requested for the
# final result.
# XXX + 5 is a guess, it is similar to what is used in evalf.py. Should
# we be more intelligent about it?
try:
args = [arg._to_mpmath(prec + 5) for arg in args]
def bad(m):
from mpmath import mpf, mpc
# the precision of an mpf value is the last element
# if that is 1 (and m[1] is not 1 which would indicate a
# power of 2), then the eval failed; so check that none of
# the arguments failed to compute to a finite precision.
# Note: An mpc value has two parts, the re and imag tuple;
# check each of those parts, too. Anything else is allowed to
# pass
if isinstance(m, mpf):
m = m._mpf_
return m[1] !=1 and m[-1] == 1
elif isinstance(m, mpc):
m, n = m._mpc_
return m[1] !=1 and m[-1] == 1 and \
n[1] !=1 and n[-1] == 1
else:
return False
if any(bad(a) for a in args):
raise ValueError # one or more args failed to compute with significance
except ValueError:
return
with mpmath.workprec(prec):
v = func(*args)
return Expr._from_mpmath(v, prec)
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_is_commutative(self):
return fuzzy_and(a.is_commutative for a in self.args)
def _eval_is_meromorphic(self, x, a):
if not self.args:
return True
if any(arg.has(x) for arg in self.args[1:]):
return False
arg = self.args[0]
if not arg._eval_is_meromorphic(x, a):
return None
return fuzzy_not(type(self).is_singular(arg.subs(x, a)))
_singularities = None # type: Union[FuzzyBool, tTuple[Expr, ...]]
@classmethod
def is_singular(cls, a):
"""
Tests whether the argument is an essential singularity
or a branch point, or the functions is non-holomorphic.
"""
ss = cls._singularities
if ss in (True, None, False):
return ss
return fuzzy_or(a.is_infinite if s is S.ComplexInfinity
else (a - s).is_zero for s in ss)
def as_base_exp(self):
"""
Returns the method as the 2-tuple (base, exponent).
"""
return self, S.One
def _eval_aseries(self, n, args0, x, logx):
"""
Compute an asymptotic expansion around args0, in terms of self.args.
This function is only used internally by _eval_nseries and should not
be called directly; derived classes can overwrite this to implement
asymptotic expansions.
"""
from sympy.utilities.misc import filldedent
raise PoleError(filldedent('''
Asymptotic expansion of %s around %s is
not implemented.''' % (type(self), args0)))
def _eval_nseries(self, x, n, logx, cdir=0):
"""
This function does compute series for multivariate functions,
but the expansion is always in terms of *one* variable.
Examples
========
>>> from sympy import atan2
>>> from sympy.abc import x, y
>>> atan2(x, y).series(x, n=2)
atan2(0, y) + x/y + O(x**2)
>>> atan2(x, y).series(y, n=2)
-y/x + atan2(x, 0) + O(y**2)
This function also computes asymptotic expansions, if necessary
and possible:
>>> from sympy import loggamma
>>> loggamma(1/x)._eval_nseries(x,0,None)
-1/x - log(x)/x + log(x)/2 + O(1)
"""
from sympy import Order
from sympy.core.symbol import uniquely_named_symbol
from sympy.sets.sets import FiniteSet
args = self.args
args0 = [t.limit(x, 0) for t in args]
if any(t.is_finite is False for t in args0):
from sympy import oo, zoo, nan
# XXX could use t.as_leading_term(x) here but it's a little
# slower
a = [t.compute_leading_term(x, logx=logx) for t in args]
a0 = [t.limit(x, 0) for t in a]
if any([t.has(oo, -oo, zoo, nan) for t in a0]):
return self._eval_aseries(n, args0, x, logx)
# Careful: the argument goes to oo, but only logarithmically so. We
# are supposed to do a power series expansion "around the
# logarithmic term". e.g.
# f(1+x+log(x))
# -> f(1+logx) + x*f'(1+logx) + O(x**2)
# where 'logx' is given in the argument
a = [t._eval_nseries(x, n, logx) for t in args]
z = [r - r0 for (r, r0) in zip(a, a0)]
p = [Dummy() for _ in z]
q = []
v = None
for ai, zi, pi in zip(a0, z, p):
if zi.has(x):
if v is not None:
raise NotImplementedError
q.append(ai + pi)
v = pi
else:
q.append(ai)
e1 = self.func(*q)
if v is None:
return e1
s = e1._eval_nseries(v, n, logx)
o = s.getO()
s = s.removeO()
s = s.subs(v, zi).expand() + Order(o.expr.subs(v, zi), x)
return s
if (self.func.nargs is S.Naturals0
or (self.func.nargs == FiniteSet(1) and args0[0])
or any(c > 1 for c in self.func.nargs)):
e = self
e1 = e.expand()
if e == e1:
#for example when e = sin(x+1) or e = sin(cos(x))
#let's try the general algorithm
if len(e.args) == 1:
# issue 14411
e = e.func(e.args[0].cancel())
term = e.subs(x, S.Zero)
if term.is_finite is False or term is S.NaN:
raise PoleError("Cannot expand %s around 0" % (self))
series = term
fact = S.One
_x = uniquely_named_symbol('xi', self)
e = e.subs(x, _x)
for i in range(n - 1):
i += 1
fact *= Rational(i)
e = e.diff(_x)
subs = e.subs(_x, S.Zero)
if subs is S.NaN:
# try to evaluate a limit if we have to
subs = e.limit(_x, S.Zero)
if subs.is_finite is False:
raise PoleError("Cannot expand %s around 0" % (self))
term = subs*(x**i)/fact
term = term.expand()
series += term
return series + Order(x**n, x)
return e1.nseries(x, n=n, logx=logx)
arg = self.args[0]
l = []
g = None
# try to predict a number of terms needed
nterms = n + 2
cf = Order(arg.as_leading_term(x), x).getn()
if cf != 0:
nterms = (n/cf).ceiling()
for i in range(nterms):
g = self.taylor_term(i, arg, g)
g = g.nseries(x, n=n, logx=logx)
l.append(g)
return Add(*l) + Order(x**n, x)
def fdiff(self, argindex=1):
"""
Returns the first derivative of the function.
"""
if not (1 <= argindex <= len(self.args)):
raise ArgumentIndexError(self, argindex)
ix = argindex - 1
A = self.args[ix]
if A._diff_wrt:
if len(self.args) == 1 or not A.is_Symbol:
return _derivative_dispatch(self, A)
for i, v in enumerate(self.args):
if i != ix and A in v.free_symbols:
# it can't be in any other argument's free symbols
# issue 8510
break
else:
return _derivative_dispatch(self, A)
# See issue 4624 and issue 4719, 5600 and 8510
D = Dummy('xi_%i' % argindex, dummy_index=hash(A))
args = self.args[:ix] + (D,) + self.args[ix + 1:]
return Subs(Derivative(self.func(*args), D), D, A)
def _eval_as_leading_term(self, x, cdir=0):
"""Stub that should be overridden by new Functions to return
the first non-zero term in a series if ever an x-dependent
argument whose leading term vanishes as x -> 0 might be encountered.
See, for example, cos._eval_as_leading_term.
"""
from sympy import Order
args = [a.as_leading_term(x) for a in self.args]
o = Order(1, x)
if any(x in a.free_symbols and o.contains(a) for a in args):
# Whereas x and any finite number are contained in O(1, x),
# expressions like 1/x are not. If any arg simplified to a
# vanishing expression as x -> 0 (like x or x**2, but not
# 3, 1/x, etc...) then the _eval_as_leading_term is needed
# to supply the first non-zero term of the series,
#
# e.g. expression leading term
# ---------- ------------
# cos(1/x) cos(1/x)
# cos(cos(x)) cos(1)
# cos(x) 1 <- _eval_as_leading_term needed
# sin(x) x <- _eval_as_leading_term needed
#
raise NotImplementedError(
'%s has no _eval_as_leading_term routine' % self.func)
else:
return self.func(*args)
def _sage_(self):
import sage.all as sage
fname = self.func.__name__
func = getattr(sage, fname, None)
args = [arg._sage_() for arg in self.args]
# In the case the function is not known in sage:
if func is None:
import sympy
if getattr(sympy, fname, None) is None:
# abstract function
return sage.function(fname)(*args)
else:
# the function defined in sympy is not known in sage
# this exception is caught in sage
raise AttributeError
return func(*args)
class AppliedUndef(Function):
"""
Base class for expressions resulting from the application of an undefined
function.
"""
is_number = False
def __new__(cls, *args, **options):
args = list(map(sympify, args))
u = [a.name for a in args if isinstance(a, UndefinedFunction)]
if u:
raise TypeError('Invalid argument: expecting an expression, not UndefinedFunction%s: %s' % (
's'*(len(u) > 1), ', '.join(u)))
obj = super().__new__(cls, *args, **options)
return obj
def _eval_as_leading_term(self, x, cdir=0):
return self
def _sage_(self):
import sage.all as sage
fname = str(self.func)
args = [arg._sage_() for arg in self.args]
func = sage.function(fname)(*args)
return func
@property
def _diff_wrt(self):
"""
Allow derivatives wrt to undefined functions.
Examples
========
>>> from sympy import Function, Symbol
>>> f = Function('f')
>>> x = Symbol('x')
>>> f(x)._diff_wrt
True
>>> f(x).diff(x)
Derivative(f(x), x)
"""
return True
class UndefSageHelper:
"""
Helper to facilitate Sage conversion.
"""
def __get__(self, ins, typ):
import sage.all as sage
if ins is None:
return lambda: sage.function(typ.__name__)
else:
args = [arg._sage_() for arg in ins.args]
return lambda : sage.function(ins.__class__.__name__)(*args)
_undef_sage_helper = UndefSageHelper()
class UndefinedFunction(FunctionClass):
"""
The (meta)class of undefined functions.
"""
def __new__(mcl, name, bases=(AppliedUndef,), __dict__=None, **kwargs):
from .symbol import _filter_assumptions
# Allow Function('f', real=True)
# and/or Function(Symbol('f', real=True))
assumptions, kwargs = _filter_assumptions(kwargs)
if isinstance(name, Symbol):
assumptions = name._merge(assumptions)
name = name.name
elif not isinstance(name, str):
raise TypeError('expecting string or Symbol for name')
else:
commutative = assumptions.get('commutative', None)
assumptions = Symbol(name, **assumptions).assumptions0
if commutative is None:
assumptions.pop('commutative')
__dict__ = __dict__ or {}
# put the `is_*` for into __dict__
__dict__.update({'is_%s' % k: v for k, v in assumptions.items()})
# You can add other attributes, although they do have to be hashable
# (but seriously, if you want to add anything other than assumptions,
# just subclass Function)
__dict__.update(kwargs)
# add back the sanitized assumptions without the is_ prefix
kwargs.update(assumptions)
# Save these for __eq__
__dict__.update({'_kwargs': kwargs})
# do this for pickling
__dict__['__module__'] = None
obj = super().__new__(mcl, name, bases, __dict__)
obj.name = name
obj._sage_ = _undef_sage_helper
return obj
def __instancecheck__(cls, instance):
return cls in type(instance).__mro__
_kwargs = {} # type: tDict[str, Optional[bool]]
def __hash__(self):
return hash((self.class_key(), frozenset(self._kwargs.items())))
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.class_key() == other.class_key() and
self._kwargs == other._kwargs)
def __ne__(self, other):
return not self == other
@property
def _diff_wrt(self):
return False
# XXX: The type: ignore on WildFunction is because mypy complains:
#
# sympy/core/function.py:939: error: Cannot determine type of 'sort_key' in
# base class 'Expr'
#
# Somehow this is because of the @cacheit decorator but it is not clear how to
# fix it.
class WildFunction(Function, AtomicExpr): # type: ignore
"""
A WildFunction function matches any function (with its arguments).
Examples
========
>>> from sympy import WildFunction, Function, cos
>>> from sympy.abc import x, y
>>> F = WildFunction('F')
>>> f = Function('f')
>>> F.nargs
Naturals0
>>> x.match(F)
>>> F.match(F)
{F_: F_}
>>> f(x).match(F)
{F_: f(x)}
>>> cos(x).match(F)
{F_: cos(x)}
>>> f(x, y).match(F)
{F_: f(x, y)}
To match functions with a given number of arguments, set ``nargs`` to the
desired value at instantiation:
>>> F = WildFunction('F', nargs=2)
>>> F.nargs
FiniteSet(2)
>>> f(x).match(F)
>>> f(x, y).match(F)
{F_: f(x, y)}
To match functions with a range of arguments, set ``nargs`` to a tuple
containing the desired number of arguments, e.g. if ``nargs = (1, 2)``
then functions with 1 or 2 arguments will be matched.
>>> F = WildFunction('F', nargs=(1, 2))
>>> F.nargs
FiniteSet(1, 2)
>>> f(x).match(F)
{F_: f(x)}
>>> f(x, y).match(F)
{F_: f(x, y)}
>>> f(x, y, 1).match(F)
"""
# XXX: What is this class attribute used for?
include = set() # type: tSet[Any]
def __init__(cls, name, **assumptions):
from sympy.sets.sets import Set, FiniteSet
cls.name = name
nargs = assumptions.pop('nargs', S.Naturals0)
if not isinstance(nargs, Set):
# Canonicalize nargs here. See also FunctionClass.
if is_sequence(nargs):
nargs = tuple(ordered(set(nargs)))
elif nargs is not None:
nargs = (as_int(nargs),)
nargs = FiniteSet(*nargs)
cls.nargs = nargs
def matches(self, expr, repl_dict={}, old=False):
if not isinstance(expr, (AppliedUndef, Function)):
return None
if len(expr.args) not in self.nargs:
return None
repl_dict = repl_dict.copy()
repl_dict[self] = expr
return repl_dict
class Derivative(Expr):
"""
Carries out differentiation of the given expression with respect to symbols.
Examples
========
>>> from sympy import Derivative, Function, symbols, Subs
>>> from sympy.abc import x, y
>>> f, g = symbols('f g', cls=Function)
>>> Derivative(x**2, x, evaluate=True)
2*x
Denesting of derivatives retains the ordering of variables:
>>> Derivative(Derivative(f(x, y), y), x)
Derivative(f(x, y), y, x)
Contiguously identical symbols are merged into a tuple giving
the symbol and the count:
>>> Derivative(f(x), x, x, y, x)
Derivative(f(x), (x, 2), y, x)
If the derivative cannot be performed, and evaluate is True, the
order of the variables of differentiation will be made canonical:
>>> Derivative(f(x, y), y, x, evaluate=True)
Derivative(f(x, y), x, y)
Derivatives with respect to undefined functions can be calculated:
>>> Derivative(f(x)**2, f(x), evaluate=True)
2*f(x)
Such derivatives will show up when the chain rule is used to
evalulate a derivative:
>>> f(g(x)).diff(x)
Derivative(f(g(x)), g(x))*Derivative(g(x), x)
Substitution is used to represent derivatives of functions with
arguments that are not symbols or functions:
>>> f(2*x + 3).diff(x) == 2*Subs(f(y).diff(y), y, 2*x + 3)
True
Notes
=====
Simplification of high-order derivatives:
Because there can be a significant amount of simplification that can be
done when multiple differentiations are performed, results will be
automatically simplified in a fairly conservative fashion unless the
keyword ``simplify`` is set to False.
>>> from sympy import sqrt, diff, Function, symbols
>>> from sympy.abc import x, y, z
>>> f, g = symbols('f,g', cls=Function)
>>> e = sqrt((x + 1)**2 + x)
>>> diff(e, (x, 5), simplify=False).count_ops()
136
>>> diff(e, (x, 5)).count_ops()
30
Ordering of variables:
If evaluate is set to True and the expression cannot be evaluated, the
list of differentiation symbols will be sorted, that is, the expression is
assumed to have continuous derivatives up to the order asked.
Derivative wrt non-Symbols:
For the most part, one may not differentiate wrt non-symbols.
For example, we do not allow differentiation wrt `x*y` because
there are multiple ways of structurally defining where x*y appears
in an expression: a very strict definition would make
(x*y*z).diff(x*y) == 0. Derivatives wrt defined functions (like
cos(x)) are not allowed, either:
>>> (x*y*z).diff(x*y)
Traceback (most recent call last):
...
ValueError: Can't calculate derivative wrt x*y.
To make it easier to work with variational calculus, however,
derivatives wrt AppliedUndef and Derivatives are allowed.
For example, in the Euler-Lagrange method one may write
F(t, u, v) where u = f(t) and v = f'(t). These variables can be
written explicitly as functions of time::
>>> from sympy.abc import t
>>> F = Function('F')
>>> U = f(t)
>>> V = U.diff(t)
The derivative wrt f(t) can be obtained directly:
>>> direct = F(t, U, V).diff(U)
When differentiation wrt a non-Symbol is attempted, the non-Symbol
is temporarily converted to a Symbol while the differentiation
is performed and the same answer is obtained:
>>> indirect = F(t, U, V).subs(U, x).diff(x).subs(x, U)
>>> assert direct == indirect
The implication of this non-symbol replacement is that all
functions are treated as independent of other functions and the
symbols are independent of the functions that contain them::
>>> x.diff(f(x))
0
>>> g(x).diff(f(x))
0
It also means that derivatives are assumed to depend only
on the variables of differentiation, not on anything contained
within the expression being differentiated::
>>> F = f(x)
>>> Fx = F.diff(x)
>>> Fx.diff(F) # derivative depends on x, not F
0
>>> Fxx = Fx.diff(x)
>>> Fxx.diff(Fx) # derivative depends on x, not Fx
0
The last example can be made explicit by showing the replacement
of Fx in Fxx with y:
>>> Fxx.subs(Fx, y)
Derivative(y, x)
Since that in itself will evaluate to zero, differentiating
wrt Fx will also be zero:
>>> _.doit()
0
Replacing undefined functions with concrete expressions
One must be careful to replace undefined functions with expressions
that contain variables consistent with the function definition and
the variables of differentiation or else insconsistent result will
be obtained. Consider the following example:
>>> eq = f(x)*g(y)
>>> eq.subs(f(x), x*y).diff(x, y).doit()
y*Derivative(g(y), y) + g(y)
>>> eq.diff(x, y).subs(f(x), x*y).doit()
y*Derivative(g(y), y)
The results differ because `f(x)` was replaced with an expression
that involved both variables of differentiation. In the abstract
case, differentiation of `f(x)` by `y` is 0; in the concrete case,
the presence of `y` made that derivative nonvanishing and produced
the extra `g(y)` term.
Defining differentiation for an object
An object must define ._eval_derivative(symbol) method that returns
the differentiation result. This function only needs to consider the
non-trivial case where expr contains symbol and it should call the diff()
method internally (not _eval_derivative); Derivative should be the only
one to call _eval_derivative.
Any class can allow derivatives to be taken with respect to
itself (while indicating its scalar nature). See the
docstring of Expr._diff_wrt.
See Also
========
_sort_variable_count
"""
is_Derivative = True
@property
def _diff_wrt(self):
"""An expression may be differentiated wrt a Derivative if
it is in elementary form.
Examples
========
>>> from sympy import Function, Derivative, cos
>>> from sympy.abc import x
>>> f = Function('f')
>>> Derivative(f(x), x)._diff_wrt
True
>>> Derivative(cos(x), x)._diff_wrt
False
>>> Derivative(x + 1, x)._diff_wrt
False
A Derivative might be an unevaluated form of what will not be
a valid variable of differentiation if evaluated. For example,
>>> Derivative(f(f(x)), x).doit()
Derivative(f(x), x)*Derivative(f(f(x)), f(x))
Such an expression will present the same ambiguities as arise
when dealing with any other product, like ``2*x``, so ``_diff_wrt``
is False:
>>> Derivative(f(f(x)), x)._diff_wrt
False
"""
return self.expr._diff_wrt and isinstance(self.doit(), Derivative)
def __new__(cls, expr, *variables, **kwargs):
from sympy.matrices.common import MatrixCommon
from sympy import Integer, MatrixExpr
from sympy.tensor.array import Array, NDimArray
from sympy.utilities.misc import filldedent
expr = sympify(expr)
symbols_or_none = getattr(expr, "free_symbols", None)
has_symbol_set = isinstance(symbols_or_none, set)
if not has_symbol_set:
raise ValueError(filldedent('''
Since there are no variables in the expression %s,
it cannot be differentiated.''' % expr))
# determine value for variables if it wasn't given
if not variables:
variables = expr.free_symbols
if len(variables) != 1:
if expr.is_number:
return S.Zero
if len(variables) == 0:
raise ValueError(filldedent('''
Since there are no variables in the expression,
the variable(s) of differentiation must be supplied
to differentiate %s''' % expr))
else:
raise ValueError(filldedent('''
Since there is more than one variable in the
expression, the variable(s) of differentiation
must be supplied to differentiate %s''' % expr))
# Standardize the variables by sympifying them:
variables = list(sympify(variables))
# Split the list of variables into a list of the variables we are diff
# wrt, where each element of the list has the form (s, count) where
# s is the entity to diff wrt and count is the order of the
# derivative.
variable_count = []
array_likes = (tuple, list, Tuple)
for i, v in enumerate(variables):
if isinstance(v, Integer):
if i == 0:
raise ValueError("First variable cannot be a number: %i" % v)
count = v
prev, prevcount = variable_count[-1]
if prevcount != 1:
raise TypeError("tuple {} followed by number {}".format((prev, prevcount), v))
if count == 0:
variable_count.pop()
else:
variable_count[-1] = Tuple(prev, count)
else:
if isinstance(v, array_likes):
if len(v) == 0:
# Ignore empty tuples: Derivative(expr, ... , (), ... )
continue
if isinstance(v[0], array_likes):
# Derive by array: Derivative(expr, ... , [[x, y, z]], ... )
if len(v) == 1:
v = Array(v[0])
count = 1
else:
v, count = v
v = Array(v)
else:
v, count = v
if count == 0:
continue
elif isinstance(v, UndefinedFunction):
raise TypeError(
"cannot differentiate wrt "
"UndefinedFunction: %s" % v)
else:
count = 1
variable_count.append(Tuple(v, count))
# light evaluation of contiguous, identical
# items: (x, 1), (x, 1) -> (x, 2)
merged = []
for t in variable_count:
v, c = t
if c.is_negative:
raise ValueError(
'order of differentiation must be nonnegative')
if merged and merged[-1][0] == v:
c += merged[-1][1]
if not c:
merged.pop()
else:
merged[-1] = Tuple(v, c)
else:
merged.append(t)
variable_count = merged
# sanity check of variables of differentation; we waited
# until the counts were computed since some variables may
# have been removed because the count was 0
for v, c in variable_count:
# v must have _diff_wrt True
if not v._diff_wrt:
__ = '' # filler to make error message neater
raise ValueError(filldedent('''
Can't calculate derivative wrt %s.%s''' % (v,
__)))
# We make a special case for 0th derivative, because there is no
# good way to unambiguously print this.
if len(variable_count) == 0:
return expr
evaluate = kwargs.get('evaluate', False)
if evaluate:
if isinstance(expr, Derivative):
expr = expr.canonical
variable_count = [
(v.canonical if isinstance(v, Derivative) else v, c)
for v, c in variable_count]
# Look for a quick exit if there are symbols that don't appear in
# expression at all. Note, this cannot check non-symbols like
# Derivatives as those can be created by intermediate
# derivatives.
zero = False
free = expr.free_symbols
for v, c in variable_count:
vfree = v.free_symbols
if c.is_positive and vfree:
if isinstance(v, AppliedUndef):
# these match exactly since
# x.diff(f(x)) == g(x).diff(f(x)) == 0
# and are not created by differentiation
D = Dummy()
if not expr.xreplace({v: D}).has(D):
zero = True
break
elif isinstance(v, MatrixExpr):
zero = False
break
elif isinstance(v, Symbol) and v not in free:
zero = True
break
else:
if not free & vfree:
# e.g. v is IndexedBase or Matrix
zero = True
break
if zero:
return cls._get_zero_with_shape_like(expr)
# make the order of symbols canonical
#TODO: check if assumption of discontinuous derivatives exist
variable_count = cls._sort_variable_count(variable_count)
# denest
if isinstance(expr, Derivative):
variable_count = list(expr.variable_count) + variable_count
expr = expr.expr
return _derivative_dispatch(expr, *variable_count, **kwargs)
# we return here if evaluate is False or if there is no
# _eval_derivative method
if not evaluate or not hasattr(expr, '_eval_derivative'):
# return an unevaluated Derivative
if evaluate and variable_count == [(expr, 1)] and expr.is_scalar:
# special hack providing evaluation for classes
# that have defined is_scalar=True but have no
# _eval_derivative defined
return S.One
return Expr.__new__(cls, expr, *variable_count)
# evaluate the derivative by calling _eval_derivative method
# of expr for each variable
# -------------------------------------------------------------
nderivs = 0 # how many derivatives were performed
unhandled = []
for i, (v, count) in enumerate(variable_count):
old_expr = expr
old_v = None
is_symbol = v.is_symbol or isinstance(v,
(Iterable, Tuple, MatrixCommon, NDimArray))
if not is_symbol:
old_v = v
v = Dummy('xi')
expr = expr.xreplace({old_v: v})
# Derivatives and UndefinedFunctions are independent
# of all others
clashing = not (isinstance(old_v, Derivative) or \
isinstance(old_v, AppliedUndef))
if not v in expr.free_symbols and not clashing:
return expr.diff(v) # expr's version of 0
if not old_v.is_scalar and not hasattr(
old_v, '_eval_derivative'):
# special hack providing evaluation for classes
# that have defined is_scalar=True but have no
# _eval_derivative defined
expr *= old_v.diff(old_v)
obj = cls._dispatch_eval_derivative_n_times(expr, v, count)
if obj is not None and obj.is_zero:
return obj
nderivs += count
if old_v is not None:
if obj is not None:
# remove the dummy that was used
obj = obj.subs(v, old_v)
# restore expr
expr = old_expr
if obj is None:
# we've already checked for quick-exit conditions
# that give 0 so the remaining variables
# are contained in the expression but the expression
# did not compute a derivative so we stop taking
# derivatives
unhandled = variable_count[i:]
break
expr = obj
# what we have so far can be made canonical
expr = expr.replace(
lambda x: isinstance(x, Derivative),
lambda x: x.canonical)
if unhandled:
if isinstance(expr, Derivative):
unhandled = list(expr.variable_count) + unhandled
expr = expr.expr
expr = Expr.__new__(cls, expr, *unhandled)
if (nderivs > 1) == True and kwargs.get('simplify', True):
from sympy.core.exprtools import factor_terms
from sympy.simplify.simplify import signsimp
expr = factor_terms(signsimp(expr))
return expr
@property
def canonical(cls):
return cls.func(cls.expr,
*Derivative._sort_variable_count(cls.variable_count))
@classmethod
def _sort_variable_count(cls, vc):
"""
Sort (variable, count) pairs into canonical order while
retaining order of variables that do not commute during
differentiation:
* symbols and functions commute with each other
* derivatives commute with each other
* a derivative doesn't commute with anything it contains
* any other object is not allowed to commute if it has
free symbols in common with another object
Examples
========
>>> from sympy import Derivative, Function, symbols
>>> vsort = Derivative._sort_variable_count
>>> x, y, z = symbols('x y z')
>>> f, g, h = symbols('f g h', cls=Function)
Contiguous items are collapsed into one pair:
>>> vsort([(x, 1), (x, 1)])
[(x, 2)]
>>> vsort([(y, 1), (f(x), 1), (y, 1), (f(x), 1)])
[(y, 2), (f(x), 2)]
Ordering is canonical.
>>> def vsort0(*v):
... # docstring helper to
... # change vi -> (vi, 0), sort, and return vi vals
... return [i[0] for i in vsort([(i, 0) for i in v])]
>>> vsort0(y, x)
[x, y]
>>> vsort0(g(y), g(x), f(y))
[f(y), g(x), g(y)]
Symbols are sorted as far to the left as possible but never
move to the left of a derivative having the same symbol in
its variables; the same applies to AppliedUndef which are
always sorted after Symbols:
>>> dfx = f(x).diff(x)
>>> assert vsort0(dfx, y) == [y, dfx]
>>> assert vsort0(dfx, x) == [dfx, x]
"""
from sympy.utilities.iterables import uniq, topological_sort
if not vc:
return []
vc = list(vc)
if len(vc) == 1:
return [Tuple(*vc[0])]
V = list(range(len(vc)))
E = []
v = lambda i: vc[i][0]
D = Dummy()
def _block(d, v, wrt=False):
# return True if v should not come before d else False
if d == v:
return wrt
if d.is_Symbol:
return False
if isinstance(d, Derivative):
# a derivative blocks if any of it's variables contain
# v; the wrt flag will return True for an exact match
# and will cause an AppliedUndef to block if v is in
# the arguments
if any(_block(k, v, wrt=True)
for k in d._wrt_variables):
return True
return False
if not wrt and isinstance(d, AppliedUndef):
return False
if v.is_Symbol:
return v in d.free_symbols
if isinstance(v, AppliedUndef):
return _block(d.xreplace({v: D}), D)
return d.free_symbols & v.free_symbols
for i in range(len(vc)):
for j in range(i):
if _block(v(j), v(i)):
E.append((j,i))
# this is the default ordering to use in case of ties
O = dict(zip(ordered(uniq([i for i, c in vc])), range(len(vc))))
ix = topological_sort((V, E), key=lambda i: O[v(i)])
# merge counts of contiguously identical items
merged = []
for v, c in [vc[i] for i in ix]:
if merged and merged[-1][0] == v:
merged[-1][1] += c
else:
merged.append([v, c])
return [Tuple(*i) for i in merged]
def _eval_is_commutative(self):
return self.expr.is_commutative
def _eval_derivative(self, v):
# If v (the variable of differentiation) is not in
# self.variables, we might be able to take the derivative.
if v not in self._wrt_variables:
dedv = self.expr.diff(v)
if isinstance(dedv, Derivative):
return dedv.func(dedv.expr, *(self.variable_count + dedv.variable_count))
# dedv (d(self.expr)/dv) could have simplified things such that the
# derivative wrt things in self.variables can now be done. Thus,
# we set evaluate=True to see if there are any other derivatives
# that can be done. The most common case is when dedv is a simple
# number so that the derivative wrt anything else will vanish.
return self.func(dedv, *self.variables, evaluate=True)
# In this case v was in self.variables so the derivative wrt v has
# already been attempted and was not computed, either because it
# couldn't be or evaluate=False originally.
variable_count = list(self.variable_count)
variable_count.append((v, 1))
return self.func(self.expr, *variable_count, evaluate=False)
def doit(self, **hints):
expr = self.expr
if hints.get('deep', True):
expr = expr.doit(**hints)
hints['evaluate'] = True
rv = self.func(expr, *self.variable_count, **hints)
if rv!= self and rv.has(Derivative):
rv = rv.doit(**hints)
return rv
@_sympifyit('z0', NotImplementedError)
def doit_numerically(self, z0):
"""
Evaluate the derivative at z numerically.
When we can represent derivatives at a point, this should be folded
into the normal evalf. For now, we need a special method.
"""
if len(self.free_symbols) != 1 or len(self.variables) != 1:
raise NotImplementedError('partials and higher order derivatives')
z = list(self.free_symbols)[0]
def eval(x):
f0 = self.expr.subs(z, Expr._from_mpmath(x, prec=mpmath.mp.prec))
f0 = f0.evalf(mlib.libmpf.prec_to_dps(mpmath.mp.prec))
return f0._to_mpmath(mpmath.mp.prec)
return Expr._from_mpmath(mpmath.diff(eval,
z0._to_mpmath(mpmath.mp.prec)),
mpmath.mp.prec)
@property
def expr(self):
return self._args[0]
@property
def _wrt_variables(self):
# return the variables of differentiation without
# respect to the type of count (int or symbolic)
return [i[0] for i in self.variable_count]
@property
def variables(self):
# TODO: deprecate? YES, make this 'enumerated_variables' and
# name _wrt_variables as variables
# TODO: support for `d^n`?
rv = []
for v, count in self.variable_count:
if not count.is_Integer:
raise TypeError(filldedent('''
Cannot give expansion for symbolic count. If you just
want a list of all variables of differentiation, use
_wrt_variables.'''))
rv.extend([v]*count)
return tuple(rv)
@property
def variable_count(self):
return self._args[1:]
@property
def derivative_count(self):
return sum([count for var, count in self.variable_count], 0)
@property
def free_symbols(self):
ret = self.expr.free_symbols
# Add symbolic counts to free_symbols
for var, count in self.variable_count:
ret.update(count.free_symbols)
return ret
def _eval_subs(self, old, new):
# The substitution (old, new) cannot be done inside
# Derivative(expr, vars) for a variety of reasons
# as handled below.
if old in self._wrt_variables:
# first handle the counts
expr = self.func(self.expr, *[(v, c.subs(old, new))
for v, c in self.variable_count])
if expr != self:
return expr._eval_subs(old, new)
# quick exit case
if not getattr(new, '_diff_wrt', False):
# case (0): new is not a valid variable of
# differentiation
if isinstance(old, Symbol):
# don't introduce a new symbol if the old will do
return Subs(self, old, new)
else:
xi = Dummy('xi')
return Subs(self.xreplace({old: xi}), xi, new)
# If both are Derivatives with the same expr, check if old is
# equivalent to self or if old is a subderivative of self.
if old.is_Derivative and old.expr == self.expr:
if self.canonical == old.canonical:
return new
# collections.Counter doesn't have __le__
def _subset(a, b):
return all((a[i] <= b[i]) == True for i in a)
old_vars = Counter(dict(reversed(old.variable_count)))
self_vars = Counter(dict(reversed(self.variable_count)))
if _subset(old_vars, self_vars):
return _derivative_dispatch(new, *(self_vars - old_vars).items()).canonical
args = list(self.args)
newargs = list(x._subs(old, new) for x in args)
if args[0] == old:
# complete replacement of self.expr
# we already checked that the new is valid so we know
# it won't be a problem should it appear in variables
return _derivative_dispatch(*newargs)
if newargs[0] != args[0]:
# case (1) can't change expr by introducing something that is in
# the _wrt_variables if it was already in the expr
# e.g.
# for Derivative(f(x, g(y)), y), x cannot be replaced with
# anything that has y in it; for f(g(x), g(y)).diff(g(y))
# g(x) cannot be replaced with anything that has g(y)
syms = {vi: Dummy() for vi in self._wrt_variables
if not vi.is_Symbol}
wrt = {syms.get(vi, vi) for vi in self._wrt_variables}
forbidden = args[0].xreplace(syms).free_symbols & wrt
nfree = new.xreplace(syms).free_symbols
ofree = old.xreplace(syms).free_symbols
if (nfree - ofree) & forbidden:
return Subs(self, old, new)
viter = ((i, j) for ((i, _), (j, _)) in zip(newargs[1:], args[1:]))
if any(i != j for i, j in viter): # a wrt-variable change
# case (2) can't change vars by introducing a variable
# that is contained in expr, e.g.
# for Derivative(f(z, g(h(x), y)), y), y cannot be changed to
# x, h(x), or g(h(x), y)
for a in _atomic(self.expr, recursive=True):
for i in range(1, len(newargs)):
vi, _ = newargs[i]
if a == vi and vi != args[i][0]:
return Subs(self, old, new)
# more arg-wise checks
vc = newargs[1:]
oldv = self._wrt_variables
newe = self.expr
subs = []
for i, (vi, ci) in enumerate(vc):
if not vi._diff_wrt:
# case (3) invalid differentiation expression so
# create a replacement dummy
xi = Dummy('xi_%i' % i)
# replace the old valid variable with the dummy
# in the expression
newe = newe.xreplace({oldv[i]: xi})
# and replace the bad variable with the dummy
vc[i] = (xi, ci)
# and record the dummy with the new (invalid)
# differentiation expression
subs.append((xi, vi))
if subs:
# handle any residual substitution in the expression
newe = newe._subs(old, new)
# return the Subs-wrapped derivative
return Subs(Derivative(newe, *vc), *zip(*subs))
# everything was ok
return _derivative_dispatch(*newargs)
def _eval_lseries(self, x, logx, cdir=0):
dx = self.variables
for term in self.expr.lseries(x, logx=logx, cdir=cdir):
yield self.func(term, *dx)
def _eval_nseries(self, x, n, logx, cdir=0):
arg = self.expr.nseries(x, n=n, logx=logx)
o = arg.getO()
dx = self.variables
rv = [self.func(a, *dx) for a in Add.make_args(arg.removeO())]
if o:
rv.append(o/x)
return Add(*rv)
def _eval_as_leading_term(self, x, cdir=0):
series_gen = self.expr.lseries(x)
d = S.Zero
for leading_term in series_gen:
d = diff(leading_term, *self.variables)
if d != 0:
break
return d
def _sage_(self):
import sage.all as sage
args = [arg._sage_() for arg in self.args]
return sage.derivative(*args)
def as_finite_difference(self, points=1, x0=None, wrt=None):
""" Expresses a Derivative instance as a finite difference.
Parameters
==========
points : sequence or coefficient, optional
If sequence: discrete values (length >= order+1) of the
independent variable used for generating the finite
difference weights.
If it is a coefficient, it will be used as the step-size
for generating an equidistant sequence of length order+1
centered around ``x0``. Default: 1 (step-size 1)
x0 : number or Symbol, optional
the value of the independent variable (``wrt``) at which the
derivative is to be approximated. Default: same as ``wrt``.
wrt : Symbol, optional
"with respect to" the variable for which the (partial)
derivative is to be approximated for. If not provided it
is required that the derivative is ordinary. Default: ``None``.
Examples
========
>>> from sympy import symbols, Function, exp, sqrt, Symbol
>>> x, h = symbols('x h')
>>> f = Function('f')
>>> f(x).diff(x).as_finite_difference()
-f(x - 1/2) + f(x + 1/2)
The default step size and number of points are 1 and
``order + 1`` respectively. We can change the step size by
passing a symbol as a parameter:
>>> f(x).diff(x).as_finite_difference(h)
-f(-h/2 + x)/h + f(h/2 + x)/h
We can also specify the discretized values to be used in a
sequence:
>>> f(x).diff(x).as_finite_difference([x, x+h, x+2*h])
-3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h)
The algorithm is not restricted to use equidistant spacing, nor
do we need to make the approximation around ``x0``, but we can get
an expression estimating the derivative at an offset:
>>> e, sq2 = exp(1), sqrt(2)
>>> xl = [x-h, x+h, x+e*h]
>>> f(x).diff(x, 1).as_finite_difference(xl, x+h*sq2) # doctest: +ELLIPSIS
2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/...
To approximate ``Derivative`` around ``x0`` using a non-equidistant
spacing step, the algorithm supports assignment of undefined
functions to ``points``:
>>> dx = Function('dx')
>>> f(x).diff(x).as_finite_difference(points=dx(x), x0=x-h)
-f(-h + x - dx(-h + x)/2)/dx(-h + x) + f(-h + x + dx(-h + x)/2)/dx(-h + x)
Partial derivatives are also supported:
>>> y = Symbol('y')
>>> d2fdxdy=f(x,y).diff(x,y)
>>> d2fdxdy.as_finite_difference(wrt=x)
-Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y)
We can apply ``as_finite_difference`` to ``Derivative`` instances in
compound expressions using ``replace``:
>>> (1 + 42**f(x).diff(x)).replace(lambda arg: arg.is_Derivative,
... lambda arg: arg.as_finite_difference())
42**(-f(x - 1/2) + f(x + 1/2)) + 1
See also
========
sympy.calculus.finite_diff.apply_finite_diff
sympy.calculus.finite_diff.differentiate_finite
sympy.calculus.finite_diff.finite_diff_weights
"""
from ..calculus.finite_diff import _as_finite_diff
return _as_finite_diff(self, points, x0, wrt)
@classmethod
def _get_zero_with_shape_like(cls, expr):
return S.Zero
@classmethod
def _dispatch_eval_derivative_n_times(cls, expr, v, count):
# Evaluate the derivative `n` times. If
# `_eval_derivative_n_times` is not overridden by the current
# object, the default in `Basic` will call a loop over
# `_eval_derivative`:
return expr._eval_derivative_n_times(v, count)
def _derivative_dispatch(expr, *variables, **kwargs):
from sympy.matrices.common import MatrixCommon
from sympy import MatrixExpr
from sympy import NDimArray
array_types = (MatrixCommon, MatrixExpr, NDimArray, list, tuple, Tuple)
if isinstance(expr, array_types) or any(isinstance(i[0], array_types) if isinstance(i, (tuple, list, Tuple)) else isinstance(i, array_types) for i in variables):
from sympy.tensor.array.array_derivatives import ArrayDerivative
return ArrayDerivative(expr, *variables, **kwargs)
return Derivative(expr, *variables, **kwargs)
class Lambda(Expr):
"""
Lambda(x, expr) represents a lambda function similar to Python's
'lambda x: expr'. A function of several variables is written as
Lambda((x, y, ...), expr).
Examples
========
A simple example:
>>> from sympy import Lambda
>>> from sympy.abc import x
>>> f = Lambda(x, x**2)
>>> f(4)
16
For multivariate functions, use:
>>> from sympy.abc import y, z, t
>>> f2 = Lambda((x, y, z, t), x + y**z + t**z)
>>> f2(1, 2, 3, 4)
73
It is also possible to unpack tuple arguments:
>>> f = Lambda( ((x, y), z) , x + y + z)
>>> f((1, 2), 3)
6
A handy shortcut for lots of arguments:
>>> p = x, y, z
>>> f = Lambda(p, x + y*z)
>>> f(*p)
x + y*z
"""
is_Function = True
def __new__(cls, signature, expr):
if iterable(signature) and not isinstance(signature, (tuple, Tuple)):
SymPyDeprecationWarning(
feature="non tuple iterable of argument symbols to Lambda",
useinstead="tuple of argument symbols",
issue=17474,
deprecated_since_version="1.5").warn()
signature = tuple(signature)
sig = signature if iterable(signature) else (signature,)
sig = sympify(sig)
cls._check_signature(sig)
if len(sig) == 1 and sig[0] == expr:
return S.IdentityFunction
return Expr.__new__(cls, sig, sympify(expr))
@classmethod
def _check_signature(cls, sig):
syms = set()
def rcheck(args):
for a in args:
if a.is_symbol:
if a in syms:
raise BadSignatureError("Duplicate symbol %s" % a)
syms.add(a)
elif isinstance(a, Tuple):
rcheck(a)
else:
raise BadSignatureError("Lambda signature should be only tuples"
" and symbols, not %s" % a)
if not isinstance(sig, Tuple):
raise BadSignatureError("Lambda signature should be a tuple not %s" % sig)
# Recurse through the signature:
rcheck(sig)
@property
def signature(self):
"""The expected form of the arguments to be unpacked into variables"""
return self._args[0]
@property
def expr(self):
"""The return value of the function"""
return self._args[1]
@property
def variables(self):
"""The variables used in the internal representation of the function"""
def _variables(args):
if isinstance(args, Tuple):
for arg in args:
yield from _variables(arg)
else:
yield args
return tuple(_variables(self.signature))
@property
def nargs(self):
from sympy.sets.sets import FiniteSet
return FiniteSet(len(self.signature))
bound_symbols = variables
@property
def free_symbols(self):
return self.expr.free_symbols - set(self.variables)
def __call__(self, *args):
n = len(args)
if n not in self.nargs: # Lambda only ever has 1 value in nargs
# XXX: exception message must be in exactly this format to
# make it work with NumPy's functions like vectorize(). See,
# for example, https://github.com/numpy/numpy/issues/1697.
# The ideal solution would be just to attach metadata to
# the exception and change NumPy to take advantage of this.
## XXX does this apply to Lambda? If not, remove this comment.
temp = ('%(name)s takes exactly %(args)s '
'argument%(plural)s (%(given)s given)')
raise BadArgumentsError(temp % {
'name': self,
'args': list(self.nargs)[0],
'plural': 's'*(list(self.nargs)[0] != 1),
'given': n})
d = self._match_signature(self.signature, args)
return self.expr.xreplace(d)
def _match_signature(self, sig, args):
symargmap = {}
def rmatch(pars, args):
for par, arg in zip(pars, args):
if par.is_symbol:
symargmap[par] = arg
elif isinstance(par, Tuple):
if not isinstance(arg, (tuple, Tuple)) or len(args) != len(pars):
raise BadArgumentsError("Can't match %s and %s" % (args, pars))
rmatch(par, arg)
rmatch(sig, args)
return symargmap
@property
def is_identity(self):
"""Return ``True`` if this ``Lambda`` is an identity function. """
return self.signature == self.expr
def _eval_evalf(self, prec):
from sympy.core.evalf import prec_to_dps
return self.func(self.args[0], self.args[1].evalf(n=prec_to_dps(prec)))
class Subs(Expr):
"""
Represents unevaluated substitutions of an expression.
``Subs(expr, x, x0)`` represents the expression resulting
from substituting x with x0 in expr.
Parameters
==========
expr : Expr
An expression.
x : tuple, variable
A variable or list of distinct variables.
x0 : tuple or list of tuples
A point or list of evaluation points
corresponding to those variables.
Notes
=====
``Subs`` objects are generally useful to represent unevaluated derivatives
calculated at a point.
The variables may be expressions, but they are subjected to the limitations
of subs(), so it is usually a good practice to use only symbols for
variables, since in that case there can be no ambiguity.
There's no automatic expansion - use the method .doit() to effect all
possible substitutions of the object and also of objects inside the
expression.
When evaluating derivatives at a point that is not a symbol, a Subs object
is returned. One is also able to calculate derivatives of Subs objects - in
this case the expression is always expanded (for the unevaluated form, use
Derivative()).
Examples
========
>>> from sympy import Subs, Function, sin, cos
>>> from sympy.abc import x, y, z
>>> f = Function('f')
Subs are created when a particular substitution cannot be made. The
x in the derivative cannot be replaced with 0 because 0 is not a
valid variables of differentiation:
>>> f(x).diff(x).subs(x, 0)
Subs(Derivative(f(x), x), x, 0)
Once f is known, the derivative and evaluation at 0 can be done:
>>> _.subs(f, sin).doit() == sin(x).diff(x).subs(x, 0) == cos(0)
True
Subs can also be created directly with one or more variables:
>>> Subs(f(x)*sin(y) + z, (x, y), (0, 1))
Subs(z + f(x)*sin(y), (x, y), (0, 1))
>>> _.doit()
z + f(0)*sin(1)
Notes
=====
In order to allow expressions to combine before doit is done, a
representation of the Subs expression is used internally to make
expressions that are superficially different compare the same:
>>> a, b = Subs(x, x, 0), Subs(y, y, 0)
>>> a + b
2*Subs(x, x, 0)
This can lead to unexpected consequences when using methods
like `has` that are cached:
>>> s = Subs(x, x, 0)
>>> s.has(x), s.has(y)
(True, False)
>>> ss = s.subs(x, y)
>>> ss.has(x), ss.has(y)
(True, False)
>>> s, ss
(Subs(x, x, 0), Subs(y, y, 0))
"""
def __new__(cls, expr, variables, point, **assumptions):
from sympy import Symbol
if not is_sequence(variables, Tuple):
variables = [variables]
variables = Tuple(*variables)
if has_dups(variables):
repeated = [str(v) for v, i in Counter(variables).items() if i > 1]
__ = ', '.join(repeated)
raise ValueError(filldedent('''
The following expressions appear more than once: %s
''' % __))
point = Tuple(*(point if is_sequence(point, Tuple) else [point]))
if len(point) != len(variables):
raise ValueError('Number of point values must be the same as '
'the number of variables.')
if not point:
return sympify(expr)
# denest
if isinstance(expr, Subs):
variables = expr.variables + variables
point = expr.point + point
expr = expr.expr
else:
expr = sympify(expr)
# use symbols with names equal to the point value (with prepended _)
# to give a variable-independent expression
pre = "_"
pts = sorted(set(point), key=default_sort_key)
from sympy.printing import StrPrinter
class CustomStrPrinter(StrPrinter):
def _print_Dummy(self, expr):
return str(expr) + str(expr.dummy_index)
def mystr(expr, **settings):
p = CustomStrPrinter(settings)
return p.doprint(expr)
while 1:
s_pts = {p: Symbol(pre + mystr(p)) for p in pts}
reps = [(v, s_pts[p])
for v, p in zip(variables, point)]
# if any underscore-prepended symbol is already a free symbol
# and is a variable with a different point value, then there
# is a clash, e.g. _0 clashes in Subs(_0 + _1, (_0, _1), (1, 0))
# because the new symbol that would be created is _1 but _1
# is already mapped to 0 so __0 and __1 are used for the new
# symbols
if any(r in expr.free_symbols and
r in variables and
Symbol(pre + mystr(point[variables.index(r)])) != r
for _, r in reps):
pre += "_"
continue
break
obj = Expr.__new__(cls, expr, Tuple(*variables), point)
obj._expr = expr.xreplace(dict(reps))
return obj
def _eval_is_commutative(self):
return self.expr.is_commutative
def doit(self, **hints):
e, v, p = self.args
# remove self mappings
for i, (vi, pi) in enumerate(zip(v, p)):
if vi == pi:
v = v[:i] + v[i + 1:]
p = p[:i] + p[i + 1:]
if not v:
return self.expr
if isinstance(e, Derivative):
# apply functions first, e.g. f -> cos
undone = []
for i, vi in enumerate(v):
if isinstance(vi, FunctionClass):
e = e.subs(vi, p[i])
else:
undone.append((vi, p[i]))
if not isinstance(e, Derivative):
e = e.doit()
if isinstance(e, Derivative):
# do Subs that aren't related to differentiation
undone2 = []
D = Dummy()
arg = e.args[0]
for vi, pi in undone:
if D not in e.xreplace({vi: D}).free_symbols:
if arg.has(vi):
e = e.subs(vi, pi)
else:
undone2.append((vi, pi))
undone = undone2
# differentiate wrt variables that are present
wrt = []
D = Dummy()
expr = e.expr
free = expr.free_symbols
for vi, ci in e.variable_count:
if isinstance(vi, Symbol) and vi in free:
expr = expr.diff((vi, ci))
elif D in expr.subs(vi, D).free_symbols:
expr = expr.diff((vi, ci))
else:
wrt.append((vi, ci))
# inject remaining subs
rv = expr.subs(undone)
# do remaining differentiation *in order given*
for vc in wrt:
rv = rv.diff(vc)
else:
# inject remaining subs
rv = e.subs(undone)
else:
rv = e.doit(**hints).subs(list(zip(v, p)))
if hints.get('deep', True) and rv != self:
rv = rv.doit(**hints)
return rv
def evalf(self, prec=None, **options):
return self.doit().evalf(prec, **options)
n = evalf
@property
def variables(self):
"""The variables to be evaluated"""
return self._args[1]
bound_symbols = variables
@property
def expr(self):
"""The expression on which the substitution operates"""
return self._args[0]
@property
def point(self):
"""The values for which the variables are to be substituted"""
return self._args[2]
@property
def free_symbols(self):
return (self.expr.free_symbols - set(self.variables) |
set(self.point.free_symbols))
@property
def expr_free_symbols(self):
from sympy.utilities.exceptions import SymPyDeprecationWarning
SymPyDeprecationWarning(feature="expr_free_symbols method",
issue=21494,
deprecated_since_version="1.9").warn()
return (self.expr.expr_free_symbols - set(self.variables) |
set(self.point.expr_free_symbols))
def __eq__(self, other):
if not isinstance(other, Subs):
return False
return self._hashable_content() == other._hashable_content()
def __ne__(self, other):
return not(self == other)
def __hash__(self):
return super().__hash__()
def _hashable_content(self):
return (self._expr.xreplace(self.canonical_variables),
) + tuple(ordered([(v, p) for v, p in
zip(self.variables, self.point) if not self.expr.has(v)]))
def _eval_subs(self, old, new):
# Subs doit will do the variables in order; the semantics
# of subs for Subs is have the following invariant for
# Subs object foo:
# foo.doit().subs(reps) == foo.subs(reps).doit()
pt = list(self.point)
if old in self.variables:
if _atomic(new) == {new} and not any(
i.has(new) for i in self.args):
# the substitution is neutral
return self.xreplace({old: new})
# any occurrence of old before this point will get
# handled by replacements from here on
i = self.variables.index(old)
for j in range(i, len(self.variables)):
pt[j] = pt[j]._subs(old, new)
return self.func(self.expr, self.variables, pt)
v = [i._subs(old, new) for i in self.variables]
if v != list(self.variables):
return self.func(self.expr, self.variables + (old,), pt + [new])
expr = self.expr._subs(old, new)
pt = [i._subs(old, new) for i in self.point]
return self.func(expr, v, pt)
def _eval_derivative(self, s):
# Apply the chain rule of the derivative on the substitution variables:
f = self.expr
vp = V, P = self.variables, self.point
val = Add.fromiter(p.diff(s)*Subs(f.diff(v), *vp).doit()
for v, p in zip(V, P))
# these are all the free symbols in the expr
efree = f.free_symbols
# some symbols like IndexedBase include themselves and args
# as free symbols
compound = {i for i in efree if len(i.free_symbols) > 1}
# hide them and see what independent free symbols remain
dums = {Dummy() for i in compound}
masked = f.xreplace(dict(zip(compound, dums)))
ifree = masked.free_symbols - dums
# include the compound symbols
free = ifree | compound
# remove the variables already handled
free -= set(V)
# add back any free symbols of remaining compound symbols
free |= {i for j in free & compound for i in j.free_symbols}
# if symbols of s are in free then there is more to do
if free & s.free_symbols:
val += Subs(f.diff(s), self.variables, self.point).doit()
return val
def _eval_nseries(self, x, n, logx, cdir=0):
if x in self.point:
# x is the variable being substituted into
apos = self.point.index(x)
other = self.variables[apos]
else:
other = x
arg = self.expr.nseries(other, n=n, logx=logx)
o = arg.getO()
terms = Add.make_args(arg.removeO())
rv = Add(*[self.func(a, *self.args[1:]) for a in terms])
if o:
rv += o.subs(other, x)
return rv
def _eval_as_leading_term(self, x, cdir=0):
if x in self.point:
ipos = self.point.index(x)
xvar = self.variables[ipos]
return self.expr.as_leading_term(xvar)
if x in self.variables:
# if `x` is a dummy variable, it means it won't exist after the
# substitution has been performed:
return self
# The variable is independent of the substitution:
return self.expr.as_leading_term(x)
def diff(f, *symbols, **kwargs):
"""
Differentiate f with respect to symbols.
Explanation
===========
This is just a wrapper to unify .diff() and the Derivative class; its
interface is similar to that of integrate(). You can use the same
shortcuts for multiple variables as with Derivative. For example,
diff(f(x), x, x, x) and diff(f(x), x, 3) both return the third derivative
of f(x).
You can pass evaluate=False to get an unevaluated Derivative class. Note
that if there are 0 symbols (such as diff(f(x), x, 0), then the result will
be the function (the zeroth derivative), even if evaluate=False.
Examples
========
>>> from sympy import sin, cos, Function, diff
>>> from sympy.abc import x, y
>>> f = Function('f')
>>> diff(sin(x), x)
cos(x)
>>> diff(f(x), x, x, x)
Derivative(f(x), (x, 3))
>>> diff(f(x), x, 3)
Derivative(f(x), (x, 3))
>>> diff(sin(x)*cos(y), x, 2, y, 2)
sin(x)*cos(y)
>>> type(diff(sin(x), x))
cos
>>> type(diff(sin(x), x, evaluate=False))
<class 'sympy.core.function.Derivative'>
>>> type(diff(sin(x), x, 0))
sin
>>> type(diff(sin(x), x, 0, evaluate=False))
sin
>>> diff(sin(x))
cos(x)
>>> diff(sin(x*y))
Traceback (most recent call last):
...
ValueError: specify differentiation variables to differentiate sin(x*y)
Note that ``diff(sin(x))`` syntax is meant only for convenience
in interactive sessions and should be avoided in library code.
References
==========
http://reference.wolfram.com/legacy/v5_2/Built-inFunctions/AlgebraicComputation/Calculus/D.html
See Also
========
Derivative
idiff: computes the derivative implicitly
"""
if hasattr(f, 'diff'):
return f.diff(*symbols, **kwargs)
kwargs.setdefault('evaluate', True)
return _derivative_dispatch(f, *symbols, **kwargs)
def expand(e, deep=True, modulus=None, power_base=True, power_exp=True,
mul=True, log=True, multinomial=True, basic=True, **hints):
r"""
Expand an expression using methods given as hints.
Explanation
===========
Hints evaluated unless explicitly set to False are: ``basic``, ``log``,
``multinomial``, ``mul``, ``power_base``, and ``power_exp`` The following
hints are supported but not applied unless set to True: ``complex``,
``func``, and ``trig``. In addition, the following meta-hints are
supported by some or all of the other hints: ``frac``, ``numer``,
``denom``, ``modulus``, and ``force``. ``deep`` is supported by all
hints. Additionally, subclasses of Expr may define their own hints or
meta-hints.
The ``basic`` hint is used for any special rewriting of an object that
should be done automatically (along with the other hints like ``mul``)
when expand is called. This is a catch-all hint to handle any sort of
expansion that may not be described by the existing hint names. To use
this hint an object should override the ``_eval_expand_basic`` method.
Objects may also define their own expand methods, which are not run by
default. See the API section below.
If ``deep`` is set to ``True`` (the default), things like arguments of
functions are recursively expanded. Use ``deep=False`` to only expand on
the top level.
If the ``force`` hint is used, assumptions about variables will be ignored
in making the expansion.
Hints
=====
These hints are run by default
mul
---
Distributes multiplication over addition:
>>> from sympy import cos, exp, sin
>>> from sympy.abc import x, y, z
>>> (y*(x + z)).expand(mul=True)
x*y + y*z
multinomial
-----------
Expand (x + y + ...)**n where n is a positive integer.
>>> ((x + y + z)**2).expand(multinomial=True)
x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2
power_exp
---------
Expand addition in exponents into multiplied bases.
>>> exp(x + y).expand(power_exp=True)
exp(x)*exp(y)
>>> (2**(x + y)).expand(power_exp=True)
2**x*2**y
power_base
----------
Split powers of multiplied bases.
This only happens by default if assumptions allow, or if the
``force`` meta-hint is used:
>>> ((x*y)**z).expand(power_base=True)
(x*y)**z
>>> ((x*y)**z).expand(power_base=True, force=True)
x**z*y**z
>>> ((2*y)**z).expand(power_base=True)
2**z*y**z
Note that in some cases where this expansion always holds, SymPy performs
it automatically:
>>> (x*y)**2
x**2*y**2
log
---
Pull out power of an argument as a coefficient and split logs products
into sums of logs.
Note that these only work if the arguments of the log function have the
proper assumptions--the arguments must be positive and the exponents must
be real--or else the ``force`` hint must be True:
>>> from sympy import log, symbols
>>> log(x**2*y).expand(log=True)
log(x**2*y)
>>> log(x**2*y).expand(log=True, force=True)
2*log(x) + log(y)
>>> x, y = symbols('x,y', positive=True)
>>> log(x**2*y).expand(log=True)
2*log(x) + log(y)
basic
-----
This hint is intended primarily as a way for custom subclasses to enable
expansion by default.
These hints are not run by default:
complex
-------
Split an expression into real and imaginary parts.
>>> x, y = symbols('x,y')
>>> (x + y).expand(complex=True)
re(x) + re(y) + I*im(x) + I*im(y)
>>> cos(x).expand(complex=True)
-I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x))
Note that this is just a wrapper around ``as_real_imag()``. Most objects
that wish to redefine ``_eval_expand_complex()`` should consider
redefining ``as_real_imag()`` instead.
func
----
Expand other functions.
>>> from sympy import gamma
>>> gamma(x + 1).expand(func=True)
x*gamma(x)
trig
----
Do trigonometric expansions.
>>> cos(x + y).expand(trig=True)
-sin(x)*sin(y) + cos(x)*cos(y)
>>> sin(2*x).expand(trig=True)
2*sin(x)*cos(x)
Note that the forms of ``sin(n*x)`` and ``cos(n*x)`` in terms of ``sin(x)``
and ``cos(x)`` are not unique, due to the identity `\sin^2(x) + \cos^2(x)
= 1`. The current implementation uses the form obtained from Chebyshev
polynomials, but this may change. See `this MathWorld article
<http://mathworld.wolfram.com/Multiple-AngleFormulas.html>`_ for more
information.
Notes
=====
- You can shut off unwanted methods::
>>> (exp(x + y)*(x + y)).expand()
x*exp(x)*exp(y) + y*exp(x)*exp(y)
>>> (exp(x + y)*(x + y)).expand(power_exp=False)
x*exp(x + y) + y*exp(x + y)
>>> (exp(x + y)*(x + y)).expand(mul=False)
(x + y)*exp(x)*exp(y)
- Use deep=False to only expand on the top level::
>>> exp(x + exp(x + y)).expand()
exp(x)*exp(exp(x)*exp(y))
>>> exp(x + exp(x + y)).expand(deep=False)
exp(x)*exp(exp(x + y))
- Hints are applied in an arbitrary, but consistent order (in the current
implementation, they are applied in alphabetical order, except
multinomial comes before mul, but this may change). Because of this,
some hints may prevent expansion by other hints if they are applied
first. For example, ``mul`` may distribute multiplications and prevent
``log`` and ``power_base`` from expanding them. Also, if ``mul`` is
applied before ``multinomial`, the expression might not be fully
distributed. The solution is to use the various ``expand_hint`` helper
functions or to use ``hint=False`` to this function to finely control
which hints are applied. Here are some examples::
>>> from sympy import expand, expand_mul, expand_power_base
>>> x, y, z = symbols('x,y,z', positive=True)
>>> expand(log(x*(y + z)))
log(x) + log(y + z)
Here, we see that ``log`` was applied before ``mul``. To get the mul
expanded form, either of the following will work::
>>> expand_mul(log(x*(y + z)))
log(x*y + x*z)
>>> expand(log(x*(y + z)), log=False)
log(x*y + x*z)
A similar thing can happen with the ``power_base`` hint::
>>> expand((x*(y + z))**x)
(x*y + x*z)**x
To get the ``power_base`` expanded form, either of the following will
work::
>>> expand((x*(y + z))**x, mul=False)
x**x*(y + z)**x
>>> expand_power_base((x*(y + z))**x)
x**x*(y + z)**x
>>> expand((x + y)*y/x)
y + y**2/x
The parts of a rational expression can be targeted::
>>> expand((x + y)*y/x/(x + 1), frac=True)
(x*y + y**2)/(x**2 + x)
>>> expand((x + y)*y/x/(x + 1), numer=True)
(x*y + y**2)/(x*(x + 1))
>>> expand((x + y)*y/x/(x + 1), denom=True)
y*(x + y)/(x**2 + x)
- The ``modulus`` meta-hint can be used to reduce the coefficients of an
expression post-expansion::
>>> expand((3*x + 1)**2)
9*x**2 + 6*x + 1
>>> expand((3*x + 1)**2, modulus=5)
4*x**2 + x + 1
- Either ``expand()`` the function or ``.expand()`` the method can be
used. Both are equivalent::
>>> expand((x + 1)**2)
x**2 + 2*x + 1
>>> ((x + 1)**2).expand()
x**2 + 2*x + 1
API
===
Objects can define their own expand hints by defining
``_eval_expand_hint()``. The function should take the form::
def _eval_expand_hint(self, **hints):
# Only apply the method to the top-level expression
...
See also the example below. Objects should define ``_eval_expand_hint()``
methods only if ``hint`` applies to that specific object. The generic
``_eval_expand_hint()`` method defined in Expr will handle the no-op case.
Each hint should be responsible for expanding that hint only.
Furthermore, the expansion should be applied to the top-level expression
only. ``expand()`` takes care of the recursion that happens when
``deep=True``.
You should only call ``_eval_expand_hint()`` methods directly if you are
100% sure that the object has the method, as otherwise you are liable to
get unexpected ``AttributeError``s. Note, again, that you do not need to
recursively apply the hint to args of your object: this is handled
automatically by ``expand()``. ``_eval_expand_hint()`` should
generally not be used at all outside of an ``_eval_expand_hint()`` method.
If you want to apply a specific expansion from within another method, use
the public ``expand()`` function, method, or ``expand_hint()`` functions.
In order for expand to work, objects must be rebuildable by their args,
i.e., ``obj.func(*obj.args) == obj`` must hold.
Expand methods are passed ``**hints`` so that expand hints may use
'metahints'--hints that control how different expand methods are applied.
For example, the ``force=True`` hint described above that causes
``expand(log=True)`` to ignore assumptions is such a metahint. The
``deep`` meta-hint is handled exclusively by ``expand()`` and is not
passed to ``_eval_expand_hint()`` methods.
Note that expansion hints should generally be methods that perform some
kind of 'expansion'. For hints that simply rewrite an expression, use the
.rewrite() API.
Examples
========
>>> from sympy import Expr, sympify
>>> class MyClass(Expr):
... def __new__(cls, *args):
... args = sympify(args)
... return Expr.__new__(cls, *args)
...
... def _eval_expand_double(self, *, force=False, **hints):
... '''
... Doubles the args of MyClass.
...
... If there more than four args, doubling is not performed,
... unless force=True is also used (False by default).
... '''
... if not force and len(self.args) > 4:
... return self
... return self.func(*(self.args + self.args))
...
>>> a = MyClass(1, 2, MyClass(3, 4))
>>> a
MyClass(1, 2, MyClass(3, 4))
>>> a.expand(double=True)
MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4))
>>> a.expand(double=True, deep=False)
MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4))
>>> b = MyClass(1, 2, 3, 4, 5)
>>> b.expand(double=True)
MyClass(1, 2, 3, 4, 5)
>>> b.expand(double=True, force=True)
MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
See Also
========
expand_log, expand_mul, expand_multinomial, expand_complex, expand_trig,
expand_power_base, expand_power_exp, expand_func, sympy.simplify.hyperexpand.hyperexpand
"""
# don't modify this; modify the Expr.expand method
hints['power_base'] = power_base
hints['power_exp'] = power_exp
hints['mul'] = mul
hints['log'] = log
hints['multinomial'] = multinomial
hints['basic'] = basic
return sympify(e).expand(deep=deep, modulus=modulus, **hints)
# This is a special application of two hints
def _mexpand(expr, recursive=False):
# expand multinomials and then expand products; this may not always
# be sufficient to give a fully expanded expression (see
# test_issue_8247_8354 in test_arit)
if expr is None:
return
was = None
while was != expr:
was, expr = expr, expand_mul(expand_multinomial(expr))
if not recursive:
break
return expr
# These are simple wrappers around single hints.
def expand_mul(expr, deep=True):
"""
Wrapper around expand that only uses the mul hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import symbols, expand_mul, exp, log
>>> x, y = symbols('x,y', positive=True)
>>> expand_mul(exp(x+y)*(x+y)*log(x*y**2))
x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2)
"""
return sympify(expr).expand(deep=deep, mul=True, power_exp=False,
power_base=False, basic=False, multinomial=False, log=False)
def expand_multinomial(expr, deep=True):
"""
Wrapper around expand that only uses the multinomial hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import symbols, expand_multinomial, exp
>>> x, y = symbols('x y', positive=True)
>>> expand_multinomial((x + exp(x + 1))**2)
x**2 + 2*x*exp(x + 1) + exp(2*x + 2)
"""
return sympify(expr).expand(deep=deep, mul=False, power_exp=False,
power_base=False, basic=False, multinomial=True, log=False)
def expand_log(expr, deep=True, force=False, factor=False):
"""
Wrapper around expand that only uses the log hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import symbols, expand_log, exp, log
>>> x, y = symbols('x,y', positive=True)
>>> expand_log(exp(x+y)*(x+y)*log(x*y**2))
(x + y)*(log(x) + 2*log(y))*exp(x + y)
"""
from sympy import Mul, log
if factor is False:
def _handle(x):
x1 = expand_mul(expand_log(x, deep=deep, force=force, factor=True))
if x1.count(log) <= x.count(log):
return x1
return x
expr = expr.replace(
lambda x: x.is_Mul and all(any(isinstance(i, log) and i.args[0].is_Rational
for i in Mul.make_args(j)) for j in x.as_numer_denom()),
lambda x: _handle(x))
return sympify(expr).expand(deep=deep, log=True, mul=False,
power_exp=False, power_base=False, multinomial=False,
basic=False, force=force, factor=factor)
def expand_func(expr, deep=True):
"""
Wrapper around expand that only uses the func hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import expand_func, gamma
>>> from sympy.abc import x
>>> expand_func(gamma(x + 2))
x*(x + 1)*gamma(x)
"""
return sympify(expr).expand(deep=deep, func=True, basic=False,
log=False, mul=False, power_exp=False, power_base=False, multinomial=False)
def expand_trig(expr, deep=True):
"""
Wrapper around expand that only uses the trig hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import expand_trig, sin
>>> from sympy.abc import x, y
>>> expand_trig(sin(x+y)*(x+y))
(x + y)*(sin(x)*cos(y) + sin(y)*cos(x))
"""
return sympify(expr).expand(deep=deep, trig=True, basic=False,
log=False, mul=False, power_exp=False, power_base=False, multinomial=False)
def expand_complex(expr, deep=True):
"""
Wrapper around expand that only uses the complex hint. See the expand
docstring for more information.
Examples
========
>>> from sympy import expand_complex, exp, sqrt, I
>>> from sympy.abc import z
>>> expand_complex(exp(z))
I*exp(re(z))*sin(im(z)) + exp(re(z))*cos(im(z))
>>> expand_complex(sqrt(I))
sqrt(2)/2 + sqrt(2)*I/2
See Also
========
sympy.core.expr.Expr.as_real_imag
"""
return sympify(expr).expand(deep=deep, complex=True, basic=False,
log=False, mul=False, power_exp=False, power_base=False, multinomial=False)
def expand_power_base(expr, deep=True, force=False):
"""
Wrapper around expand that only uses the power_base hint.
A wrapper to expand(power_base=True) which separates a power with a base
that is a Mul into a product of powers, without performing any other
expansions, provided that assumptions about the power's base and exponent
allow.
deep=False (default is True) will only apply to the top-level expression.
force=True (default is False) will cause the expansion to ignore
assumptions about the base and exponent. When False, the expansion will
only happen if the base is non-negative or the exponent is an integer.
>>> from sympy.abc import x, y, z
>>> from sympy import expand_power_base, sin, cos, exp
>>> (x*y)**2
x**2*y**2
>>> (2*x)**y
(2*x)**y
>>> expand_power_base(_)
2**y*x**y
>>> expand_power_base((x*y)**z)
(x*y)**z
>>> expand_power_base((x*y)**z, force=True)
x**z*y**z
>>> expand_power_base(sin((x*y)**z), deep=False)
sin((x*y)**z)
>>> expand_power_base(sin((x*y)**z), force=True)
sin(x**z*y**z)
>>> expand_power_base((2*sin(x))**y + (2*cos(x))**y)
2**y*sin(x)**y + 2**y*cos(x)**y
>>> expand_power_base((2*exp(y))**x)
2**x*exp(y)**x
>>> expand_power_base((2*cos(x))**y)
2**y*cos(x)**y
Notice that sums are left untouched. If this is not the desired behavior,
apply full ``expand()`` to the expression:
>>> expand_power_base(((x+y)*z)**2)
z**2*(x + y)**2
>>> (((x+y)*z)**2).expand()
x**2*z**2 + 2*x*y*z**2 + y**2*z**2
>>> expand_power_base((2*y)**(1+z))
2**(z + 1)*y**(z + 1)
>>> ((2*y)**(1+z)).expand()
2*2**z*y*y**z
See Also
========
expand
"""
return sympify(expr).expand(deep=deep, log=False, mul=False,
power_exp=False, power_base=True, multinomial=False,
basic=False, force=force)
def expand_power_exp(expr, deep=True):
"""
Wrapper around expand that only uses the power_exp hint.
See the expand docstring for more information.
Examples
========
>>> from sympy import expand_power_exp
>>> from sympy.abc import x, y
>>> expand_power_exp(x**(y + 2))
x**2*x**y
"""
return sympify(expr).expand(deep=deep, complex=False, basic=False,
log=False, mul=False, power_exp=True, power_base=False, multinomial=False)
def count_ops(expr, visual=False):
"""
Return a representation (integer or expression) of the operations in expr.
Parameters
==========
expr : Expr
If expr is an iterable, the sum of the op counts of the
items will be returned.
visual : bool, optional
If ``False`` (default) then the sum of the coefficients of the
visual expression will be returned.
If ``True`` then the number of each type of operation is shown
with the core class types (or their virtual equivalent) multiplied by the
number of times they occur.
Examples
========
>>> from sympy.abc import a, b, x, y
>>> from sympy import sin, count_ops
Although there isn't a SUB object, minus signs are interpreted as
either negations or subtractions:
>>> (x - y).count_ops(visual=True)
SUB
>>> (-x).count_ops(visual=True)
NEG
Here, there are two Adds and a Pow:
>>> (1 + a + b**2).count_ops(visual=True)
2*ADD + POW
In the following, an Add, Mul, Pow and two functions:
>>> (sin(x)*x + sin(x)**2).count_ops(visual=True)
ADD + MUL + POW + 2*SIN
for a total of 5:
>>> (sin(x)*x + sin(x)**2).count_ops(visual=False)
5
Note that "what you type" is not always what you get. The expression
1/x/y is translated by sympy into 1/(x*y) so it gives a DIV and MUL rather
than two DIVs:
>>> (1/x/y).count_ops(visual=True)
DIV + MUL
The visual option can be used to demonstrate the difference in
operations for expressions in different forms. Here, the Horner
representation is compared with the expanded form of a polynomial:
>>> eq=x*(1 + x*(2 + x*(3 + x)))
>>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True)
-MUL + 3*POW
The count_ops function also handles iterables:
>>> count_ops([x, sin(x), None, True, x + 2], visual=False)
2
>>> count_ops([x, sin(x), None, True, x + 2], visual=True)
ADD + SIN
>>> count_ops({x: sin(x), x + 2: y + 1}, visual=True)
2*ADD + SIN
"""
from sympy import Integral, Sum, Symbol
from sympy.core.relational import Relational
from sympy.simplify.radsimp import fraction
from sympy.logic.boolalg import BooleanFunction
from sympy.utilities.misc import func_name
expr = sympify(expr)
if isinstance(expr, Expr) and not expr.is_Relational:
ops = []
args = [expr]
NEG = Symbol('NEG')
DIV = Symbol('DIV')
SUB = Symbol('SUB')
ADD = Symbol('ADD')
EXP = Symbol('EXP')
while args:
a = args.pop()
if a.is_Rational:
#-1/3 = NEG + DIV
if a is not S.One:
if a.p < 0:
ops.append(NEG)
if a.q != 1:
ops.append(DIV)
continue
elif a.is_Mul or a.is_MatMul:
if _coeff_isneg(a):
ops.append(NEG)
if a.args[0] is S.NegativeOne:
a = a.as_two_terms()[1]
else:
a = -a
n, d = fraction(a)
if n.is_Integer:
ops.append(DIV)
if n < 0:
ops.append(NEG)
args.append(d)
continue # won't be -Mul but could be Add
elif d is not S.One:
if not d.is_Integer:
args.append(d)
ops.append(DIV)
args.append(n)
continue # could be -Mul
elif a.is_Add or a.is_MatAdd:
aargs = list(a.args)
negs = 0
for i, ai in enumerate(aargs):
if _coeff_isneg(ai):
negs += 1
args.append(-ai)
if i > 0:
ops.append(SUB)
else:
args.append(ai)
if i > 0:
ops.append(ADD)
if negs == len(aargs): # -x - y = NEG + SUB
ops.append(NEG)
elif _coeff_isneg(aargs[0]): # -x + y = SUB, but already recorded ADD
ops.append(SUB - ADD)
continue
if a.is_Pow and a.exp is S.NegativeOne:
ops.append(DIV)
args.append(a.base) # won't be -Mul but could be Add
continue
if a == S.Exp1:
ops.append(EXP)
continue
if a.is_Pow and a.base == S.Exp1:
ops.append(EXP)
args.append(a.exp)
continue
if a.is_Mul or isinstance(a, LatticeOp):
o = Symbol(a.func.__name__.upper())
# count the args
ops.append(o*(len(a.args) - 1))
elif a.args and (
a.is_Pow or
a.is_Function or
isinstance(a, Derivative) or
isinstance(a, Integral) or
isinstance(a, Sum)):
# if it's not in the list above we don't
# consider a.func something to count, e.g.
# Tuple, MatrixSymbol, etc...
o = Symbol(a.func.__name__.upper())
ops.append(o)
if not a.is_Symbol:
args.extend(a.args)
elif isinstance(expr, Dict):
ops = [count_ops(k, visual=visual) +
count_ops(v, visual=visual) for k, v in expr.items()]
elif iterable(expr):
ops = [count_ops(i, visual=visual) for i in expr]
elif isinstance(expr, (Relational, BooleanFunction)):
ops = []
for arg in expr.args:
ops.append(count_ops(arg, visual=True))
o = Symbol(func_name(expr, short=True).upper())
ops.append(o)
elif not isinstance(expr, Basic):
ops = []
else: # it's Basic not isinstance(expr, Expr):
if not isinstance(expr, Basic):
raise TypeError("Invalid type of expr")
else:
ops = []
args = [expr]
while args:
a = args.pop()
if a.args:
o = Symbol(type(a).__name__.upper())
if a.is_Boolean:
ops.append(o*(len(a.args)-1))
else:
ops.append(o)
args.extend(a.args)
if not ops:
if visual:
return S.Zero
return 0
ops = Add(*ops)
if visual:
return ops
if ops.is_Number:
return int(ops)
return sum(int((a.args or [1])[0]) for a in Add.make_args(ops))
def nfloat(expr, n=15, exponent=False, dkeys=False):
"""Make all Rationals in expr Floats except those in exponents
(unless the exponents flag is set to True). When processing
dictionaries, don't modify the keys unless ``dkeys=True``.
Examples
========
>>> from sympy.core.function import nfloat
>>> from sympy.abc import x, y
>>> from sympy import cos, pi, sqrt
>>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y))
x**4 + 0.5*x + sqrt(y) + 1.5
>>> nfloat(x**4 + sqrt(y), exponent=True)
x**4.0 + y**0.5
Container types are not modified:
>>> type(nfloat((1, 2))) is tuple
True
"""
from sympy.core.power import Pow
from sympy.polys.rootoftools import RootOf
from sympy import MatrixBase
kw = dict(n=n, exponent=exponent, dkeys=dkeys)
if isinstance(expr, MatrixBase):
return expr.applyfunc(lambda e: nfloat(e, **kw))
# handling of iterable containers
if iterable(expr, exclude=str):
if isinstance(expr, (dict, Dict)):
if dkeys:
args = [tuple(map(lambda i: nfloat(i, **kw), a))
for a in expr.items()]
else:
args = [(k, nfloat(v, **kw)) for k, v in expr.items()]
if isinstance(expr, dict):
return type(expr)(args)
else:
return expr.func(*args)
elif isinstance(expr, Basic):
return expr.func(*[nfloat(a, **kw) for a in expr.args])
return type(expr)([nfloat(a, **kw) for a in expr])
rv = sympify(expr)
if rv.is_Number:
return Float(rv, n)
elif rv.is_number:
# evalf doesn't always set the precision
rv = rv.n(n)
if rv.is_Number:
rv = Float(rv.n(n), n)
else:
pass # pure_complex(rv) is likely True
return rv
elif rv.is_Atom:
return rv
elif rv.is_Relational:
args_nfloat = (nfloat(arg, **kw) for arg in rv.args)
return rv.func(*args_nfloat)
# watch out for RootOf instances that don't like to have
# their exponents replaced with Dummies and also sometimes have
# problems with evaluating at low precision (issue 6393)
rv = rv.xreplace({ro: ro.n(n) for ro in rv.atoms(RootOf)})
if not exponent:
reps = [(p, Pow(p.base, Dummy())) for p in rv.atoms(Pow)]
rv = rv.xreplace(dict(reps))
rv = rv.n(n)
if not exponent:
rv = rv.xreplace({d.exp: p.exp for p, d in reps})
else:
# Pow._eval_evalf special cases Integer exponents so if
# exponent is suppose to be handled we have to do so here
rv = rv.xreplace(Transform(
lambda x: Pow(x.base, Float(x.exp, n)),
lambda x: x.is_Pow and x.exp.is_Integer))
return rv.xreplace(Transform(
lambda x: x.func(*nfloat(x.args, n, exponent)),
lambda x: isinstance(x, Function)))
from sympy.core.symbol import Dummy, Symbol
|
789b5114213cd9e471ad581864f55d086311f99f39733512183da98e3d90b268 | from collections import defaultdict
from functools import cmp_to_key, reduce
from operator import attrgetter
from .basic import Basic
from .compatibility import is_sequence
from .parameters import global_parameters
from .logic import _fuzzy_group, fuzzy_or, fuzzy_not
from .singleton import S
from .operations import AssocOp, AssocOpDispatcher
from .cache import cacheit
from .numbers import ilcm, igcd
from .expr import Expr
from .kind import UndefinedKind
# Key for sorting commutative args in canonical order
_args_sortkey = cmp_to_key(Basic.compare)
def _addsort(args):
# in-place sorting of args
args.sort(key=_args_sortkey)
def _unevaluated_Add(*args):
"""Return a well-formed unevaluated Add: Numbers are collected and
put in slot 0 and args are sorted. Use this when args have changed
but you still want to return an unevaluated Add.
Examples
========
>>> from sympy.core.add import _unevaluated_Add as uAdd
>>> from sympy import S, Add
>>> from sympy.abc import x, y
>>> a = uAdd(*[S(1.0), x, S(2)])
>>> a.args[0]
3.00000000000000
>>> a.args[1]
x
Beyond the Number being in slot 0, there is no other assurance of
order for the arguments since they are hash sorted. So, for testing
purposes, output produced by this in some other function can only
be tested against the output of this function or as one of several
options:
>>> opts = (Add(x, y, evaluate=False), Add(y, x, evaluate=False))
>>> a = uAdd(x, y)
>>> assert a in opts and a == uAdd(x, y)
>>> uAdd(x + 1, x + 2)
x + x + 3
"""
args = list(args)
newargs = []
co = S.Zero
while args:
a = args.pop()
if a.is_Add:
# this will keep nesting from building up
# so that x + (x + 1) -> x + x + 1 (3 args)
args.extend(a.args)
elif a.is_Number:
co += a
else:
newargs.append(a)
_addsort(newargs)
if co:
newargs.insert(0, co)
return Add._from_args(newargs)
class Add(Expr, AssocOp):
"""
Expression representing addition operation for algebraic group.
Every argument of ``Add()`` must be ``Expr``. Infix operator ``+``
on most scalar objects in SymPy calls this class.
Another use of ``Add()`` is to represent the structure of abstract
addition so that its arguments can be substituted to return different
class. Refer to examples section for this.
``Add()`` evaluates the argument unless ``evaluate=False`` is passed.
The evaluation logic includes:
1. Flattening
``Add(x, Add(y, z))`` -> ``Add(x, y, z)``
2. Identity removing
``Add(x, 0, y)`` -> ``Add(x, y)``
3. Coefficient collecting by ``.as_coeff_Mul()``
``Add(x, 2*x)`` -> ``Mul(3, x)``
4. Term sorting
``Add(y, x, 2)`` -> ``Add(2, x, y)``
If no argument is passed, identity element 0 is returned. If single
element is passed, that element is returned.
Note that ``Add(*args)`` is more efficient than ``sum(args)`` because
it flattens the arguments. ``sum(a, b, c, ...)`` recursively adds the
arguments as ``a + (b + (c + ...))``, which has quadratic complexity.
On the other hand, ``Add(a, b, c, d)`` does not assume nested
structure, making the complexity linear.
Since addition is group operation, every argument should have the
same :obj:`sympy.core.kind.Kind()`.
Examples
========
>>> from sympy import Add, I
>>> from sympy.abc import x, y
>>> Add(x, 1)
x + 1
>>> Add(x, x)
2*x
>>> 2*x**2 + 3*x + I*y + 2*y + 2*x/5 + 1.0*y + 1
2*x**2 + 17*x/5 + 3.0*y + I*y + 1
If ``evaluate=False`` is passed, result is not evaluated.
>>> Add(1, 2, evaluate=False)
1 + 2
>>> Add(x, x, evaluate=False)
x + x
``Add()`` also represents the general structure of addition operation.
>>> from sympy import MatrixSymbol
>>> A,B = MatrixSymbol('A', 2,2), MatrixSymbol('B', 2,2)
>>> expr = Add(x,y).subs({x:A, y:B})
>>> expr
A + B
>>> type(expr)
<class 'sympy.matrices.expressions.matadd.MatAdd'>
Note that the printers don't display in args order.
>>> Add(x, 1)
x + 1
>>> Add(x, 1).args
(1, x)
See Also
========
MatAdd
"""
__slots__ = ()
is_Add = True
_args_type = Expr
@classmethod
def flatten(cls, seq):
"""
Takes the sequence "seq" of nested Adds and returns a flatten list.
Returns: (commutative_part, noncommutative_part, order_symbols)
Applies associativity, all terms are commutable with respect to
addition.
NB: the removal of 0 is already handled by AssocOp.__new__
See also
========
sympy.core.mul.Mul.flatten
"""
from sympy.calculus.util import AccumBounds
from sympy.matrices.expressions import MatrixExpr
from sympy.tensor.tensor import TensExpr
rv = None
if len(seq) == 2:
a, b = seq
if b.is_Rational:
a, b = b, a
if a.is_Rational:
if b.is_Mul:
rv = [a, b], [], None
if rv:
if all(s.is_commutative for s in rv[0]):
return rv
return [], rv[0], None
terms = {} # term -> coeff
# e.g. x**2 -> 5 for ... + 5*x**2 + ...
coeff = S.Zero # coefficient (Number or zoo) to always be in slot 0
# e.g. 3 + ...
order_factors = []
extra = []
for o in seq:
# O(x)
if o.is_Order:
if o.expr.is_zero:
continue
for o1 in order_factors:
if o1.contains(o):
o = None
break
if o is None:
continue
order_factors = [o] + [
o1 for o1 in order_factors if not o.contains(o1)]
continue
# 3 or NaN
elif o.is_Number:
if (o is S.NaN or coeff is S.ComplexInfinity and
o.is_finite is False) and not extra:
# we know for sure the result will be nan
return [S.NaN], [], None
if coeff.is_Number or isinstance(coeff, AccumBounds):
coeff += o
if coeff is S.NaN and not extra:
# we know for sure the result will be nan
return [S.NaN], [], None
continue
elif isinstance(o, AccumBounds):
coeff = o.__add__(coeff)
continue
elif isinstance(o, MatrixExpr):
# can't add 0 to Matrix so make sure coeff is not 0
extra.append(o)
continue
elif isinstance(o, TensExpr):
coeff = o.__add__(coeff) if coeff else o
continue
elif o is S.ComplexInfinity:
if coeff.is_finite is False and not extra:
# we know for sure the result will be nan
return [S.NaN], [], None
coeff = S.ComplexInfinity
continue
# Add([...])
elif o.is_Add:
# NB: here we assume Add is always commutative
seq.extend(o.args) # TODO zerocopy?
continue
# Mul([...])
elif o.is_Mul:
c, s = o.as_coeff_Mul()
# check for unevaluated Pow, e.g. 2**3 or 2**(-1/2)
elif o.is_Pow:
b, e = o.as_base_exp()
if b.is_Number and (e.is_Integer or
(e.is_Rational and e.is_negative)):
seq.append(b**e)
continue
c, s = S.One, o
else:
# everything else
c = S.One
s = o
# now we have:
# o = c*s, where
#
# c is a Number
# s is an expression with number factor extracted
# let's collect terms with the same s, so e.g.
# 2*x**2 + 3*x**2 -> 5*x**2
if s in terms:
terms[s] += c
if terms[s] is S.NaN and not extra:
# we know for sure the result will be nan
return [S.NaN], [], None
else:
terms[s] = c
# now let's construct new args:
# [2*x**2, x**3, 7*x**4, pi, ...]
newseq = []
noncommutative = False
for s, c in terms.items():
# 0*s
if c.is_zero:
continue
# 1*s
elif c is S.One:
newseq.append(s)
# c*s
else:
if s.is_Mul:
# Mul, already keeps its arguments in perfect order.
# so we can simply put c in slot0 and go the fast way.
cs = s._new_rawargs(*((c,) + s.args))
newseq.append(cs)
elif s.is_Add:
# we just re-create the unevaluated Mul
newseq.append(Mul(c, s, evaluate=False))
else:
# alternatively we have to call all Mul's machinery (slow)
newseq.append(Mul(c, s))
noncommutative = noncommutative or not s.is_commutative
# oo, -oo
if coeff is S.Infinity:
newseq = [f for f in newseq if not (f.is_extended_nonnegative or f.is_real)]
elif coeff is S.NegativeInfinity:
newseq = [f for f in newseq if not (f.is_extended_nonpositive or f.is_real)]
if coeff is S.ComplexInfinity:
# zoo might be
# infinite_real + finite_im
# finite_real + infinite_im
# infinite_real + infinite_im
# addition of a finite real or imaginary number won't be able to
# change the zoo nature; adding an infinite qualtity would result
# in a NaN condition if it had sign opposite of the infinite
# portion of zoo, e.g., infinite_real - infinite_real.
newseq = [c for c in newseq if not (c.is_finite and
c.is_extended_real is not None)]
# process O(x)
if order_factors:
newseq2 = []
for t in newseq:
for o in order_factors:
# x + O(x) -> O(x)
if o.contains(t):
t = None
break
# x + O(x**2) -> x + O(x**2)
if t is not None:
newseq2.append(t)
newseq = newseq2 + order_factors
# 1 + O(1) -> O(1)
for o in order_factors:
if o.contains(coeff):
coeff = S.Zero
break
# order args canonically
_addsort(newseq)
# current code expects coeff to be first
if coeff is not S.Zero:
newseq.insert(0, coeff)
if extra:
newseq += extra
noncommutative = True
# we are done
if noncommutative:
return [], newseq, None
else:
return newseq, [], None
@classmethod
def class_key(cls):
"""Nice order of classes"""
return 3, 1, cls.__name__
@property
def kind(self):
k = attrgetter('kind')
kinds = map(k, self.args)
kinds = frozenset(kinds)
if len(kinds) != 1:
# Since addition is group operator, kind must be same.
# We know that this is unexpected signature, so return this.
result = UndefinedKind
else:
result, = kinds
return result
def as_coefficients_dict(a):
"""Return a dictionary mapping terms to their Rational coefficient.
Since the dictionary is a defaultdict, inquiries about terms which
were not present will return a coefficient of 0. If an expression is
not an Add it is considered to have a single term.
Examples
========
>>> from sympy.abc import a, x
>>> (3*x + a*x + 4).as_coefficients_dict()
{1: 4, x: 3, a*x: 1}
>>> _[a]
0
>>> (3*a*x).as_coefficients_dict()
{a*x: 3}
"""
d = defaultdict(list)
for ai in a.args:
c, m = ai.as_coeff_Mul()
d[m].append(c)
for k, v in d.items():
if len(v) == 1:
d[k] = v[0]
else:
d[k] = Add(*v)
di = defaultdict(int)
di.update(d)
return di
@cacheit
def as_coeff_add(self, *deps):
"""
Returns a tuple (coeff, args) where self is treated as an Add and coeff
is the Number term and args is a tuple of all other terms.
Examples
========
>>> from sympy.abc import x
>>> (7 + 3*x).as_coeff_add()
(7, (3*x,))
>>> (7*x).as_coeff_add()
(0, (7*x,))
"""
if deps:
from sympy.utilities.iterables import sift
l1, l2 = sift(self.args, lambda x: x.has(*deps), binary=True)
return self._new_rawargs(*l2), tuple(l1)
coeff, notrat = self.args[0].as_coeff_add()
if coeff is not S.Zero:
return coeff, notrat + self.args[1:]
return S.Zero, self.args
def as_coeff_Add(self, rational=False, deps=None):
"""
Efficiently extract the coefficient of a summation.
"""
coeff, args = self.args[0], self.args[1:]
if coeff.is_Number and not rational or coeff.is_Rational:
return coeff, self._new_rawargs(*args)
return S.Zero, self
# Note, we intentionally do not implement Add.as_coeff_mul(). Rather, we
# let Expr.as_coeff_mul() just always return (S.One, self) for an Add. See
# issue 5524.
def _eval_power(self, e):
if e.is_Rational and self.is_number:
from sympy.core.evalf import pure_complex
from sympy.core.mul import _unevaluated_Mul
from sympy.core.exprtools import factor_terms
from sympy.core.function import expand_multinomial
from sympy.functions.elementary.complexes import sign
from sympy.functions.elementary.miscellaneous import sqrt
ri = pure_complex(self)
if ri:
r, i = ri
if e.q == 2:
D = sqrt(r**2 + i**2)
if D.is_Rational:
# (r, i, D) is a Pythagorean triple
root = sqrt(factor_terms((D - r)/2))**e.p
return root*expand_multinomial((
# principle value
(D + r)/abs(i) + sign(i)*S.ImaginaryUnit)**e.p)
elif e == -1:
return _unevaluated_Mul(
r - i*S.ImaginaryUnit,
1/(r**2 + i**2))
elif e.is_Number and abs(e) != 1:
# handle the Float case: (2.0 + 4*x)**e -> 4**e*(0.5 + x)**e
c, m = zip(*[i.as_coeff_Mul() for i in self.args])
if any(i.is_Float for i in c): # XXX should this always be done?
big = -1
for i in c:
if abs(i) >= big:
big = abs(i)
if big > 0 and big != 1:
from sympy.functions.elementary.complexes import sign
bigs = (big, -big)
c = [sign(i) if i in bigs else i/big for i in c]
addpow = Add(*[c*m for c, m in zip(c, m)])**e
return big**e*addpow
@cacheit
def _eval_derivative(self, s):
return self.func(*[a.diff(s) for a in self.args])
def _eval_nseries(self, x, n, logx, cdir=0):
terms = [t.nseries(x, n=n, logx=logx, cdir=cdir) for t in self.args]
return self.func(*terms)
def _matches_simple(self, expr, repl_dict):
# handle (w+3).matches('x+5') -> {w: x+2}
coeff, terms = self.as_coeff_add()
if len(terms) == 1:
return terms[0].matches(expr - coeff, repl_dict)
return
def matches(self, expr, repl_dict={}, old=False):
return self._matches_commutative(expr, repl_dict, old)
@staticmethod
def _combine_inverse(lhs, rhs):
"""
Returns lhs - rhs, but treats oo like a symbol so oo - oo
returns 0, instead of a nan.
"""
from sympy.simplify.simplify import signsimp
from sympy.core.symbol import Dummy
inf = (S.Infinity, S.NegativeInfinity)
if lhs.has(*inf) or rhs.has(*inf):
oo = Dummy('oo')
reps = {
S.Infinity: oo,
S.NegativeInfinity: -oo}
ireps = {v: k for k, v in reps.items()}
eq = signsimp(lhs.xreplace(reps) - rhs.xreplace(reps))
if eq.has(oo):
eq = eq.replace(
lambda x: x.is_Pow and x.base is oo,
lambda x: x.base)
return eq.xreplace(ireps)
else:
return signsimp(lhs - rhs)
@cacheit
def as_two_terms(self):
"""Return head and tail of self.
This is the most efficient way to get the head and tail of an
expression.
- if you want only the head, use self.args[0];
- if you want to process the arguments of the tail then use
self.as_coef_add() which gives the head and a tuple containing
the arguments of the tail when treated as an Add.
- if you want the coefficient when self is treated as a Mul
then use self.as_coeff_mul()[0]
>>> from sympy.abc import x, y
>>> (3*x - 2*y + 5).as_two_terms()
(5, 3*x - 2*y)
"""
return self.args[0], self._new_rawargs(*self.args[1:])
def as_numer_denom(self):
"""
Decomposes an expression to its numerator part and its
denominator part.
Examples
========
>>> from sympy.abc import x, y, z
>>> (x*y/z).as_numer_denom()
(x*y, z)
>>> (x*(y + 1)/y**7).as_numer_denom()
(x*(y + 1), y**7)
See Also
========
sympy.core.expr.Expr.as_numer_denom
"""
# clear rational denominator
content, expr = self.primitive()
ncon, dcon = content.as_numer_denom()
# collect numerators and denominators of the terms
nd = defaultdict(list)
for f in expr.args:
ni, di = f.as_numer_denom()
nd[di].append(ni)
# check for quick exit
if len(nd) == 1:
d, n = nd.popitem()
return self.func(
*[_keep_coeff(ncon, ni) for ni in n]), _keep_coeff(dcon, d)
# sum up the terms having a common denominator
for d, n in nd.items():
if len(n) == 1:
nd[d] = n[0]
else:
nd[d] = self.func(*n)
# assemble single numerator and denominator
denoms, numers = [list(i) for i in zip(*iter(nd.items()))]
n, d = self.func(*[Mul(*(denoms[:i] + [numers[i]] + denoms[i + 1:]))
for i in range(len(numers))]), Mul(*denoms)
return _keep_coeff(ncon, n), _keep_coeff(dcon, d)
def _eval_is_polynomial(self, syms):
return all(term._eval_is_polynomial(syms) for term in self.args)
def _eval_is_rational_function(self, syms):
return all(term._eval_is_rational_function(syms) for term in self.args)
def _eval_is_meromorphic(self, x, a):
return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args),
quick_exit=True)
def _eval_is_algebraic_expr(self, syms):
return all(term._eval_is_algebraic_expr(syms) for term in self.args)
# assumption methods
_eval_is_real = lambda self: _fuzzy_group(
(a.is_real for a in self.args), quick_exit=True)
_eval_is_extended_real = lambda self: _fuzzy_group(
(a.is_extended_real for a in self.args), quick_exit=True)
_eval_is_complex = lambda self: _fuzzy_group(
(a.is_complex for a in self.args), quick_exit=True)
_eval_is_antihermitian = lambda self: _fuzzy_group(
(a.is_antihermitian for a in self.args), quick_exit=True)
_eval_is_finite = lambda self: _fuzzy_group(
(a.is_finite for a in self.args), quick_exit=True)
_eval_is_hermitian = lambda self: _fuzzy_group(
(a.is_hermitian for a in self.args), quick_exit=True)
_eval_is_integer = lambda self: _fuzzy_group(
(a.is_integer for a in self.args), quick_exit=True)
_eval_is_rational = lambda self: _fuzzy_group(
(a.is_rational for a in self.args), quick_exit=True)
_eval_is_algebraic = lambda self: _fuzzy_group(
(a.is_algebraic for a in self.args), quick_exit=True)
_eval_is_commutative = lambda self: _fuzzy_group(
a.is_commutative for a in self.args)
def _eval_is_infinite(self):
sawinf = False
for a in self.args:
ainf = a.is_infinite
if ainf is None:
return None
elif ainf is True:
# infinite+infinite might not be infinite
if sawinf is True:
return None
sawinf = True
return sawinf
def _eval_is_imaginary(self):
nz = []
im_I = []
for a in self.args:
if a.is_extended_real:
if a.is_zero:
pass
elif a.is_zero is False:
nz.append(a)
else:
return
elif a.is_imaginary:
im_I.append(a*S.ImaginaryUnit)
elif (S.ImaginaryUnit*a).is_extended_real:
im_I.append(a*S.ImaginaryUnit)
else:
return
b = self.func(*nz)
if b.is_zero:
return fuzzy_not(self.func(*im_I).is_zero)
elif b.is_zero is False:
return False
def _eval_is_zero(self):
if self.is_commutative is False:
# issue 10528: there is no way to know if a nc symbol
# is zero or not
return
nz = []
z = 0
im_or_z = False
im = 0
for a in self.args:
if a.is_extended_real:
if a.is_zero:
z += 1
elif a.is_zero is False:
nz.append(a)
else:
return
elif a.is_imaginary:
im += 1
elif (S.ImaginaryUnit*a).is_extended_real:
im_or_z = True
else:
return
if z == len(self.args):
return True
if len(nz) == 0 or len(nz) == len(self.args):
return None
b = self.func(*nz)
if b.is_zero:
if not im_or_z:
if im == 0:
return True
elif im == 1:
return False
if b.is_zero is False:
return False
def _eval_is_odd(self):
l = [f for f in self.args if not (f.is_even is True)]
if not l:
return False
if l[0].is_odd:
return self._new_rawargs(*l[1:]).is_even
def _eval_is_irrational(self):
for t in self.args:
a = t.is_irrational
if a:
others = list(self.args)
others.remove(t)
if all(x.is_rational is True for x in others):
return True
return None
if a is None:
return
return False
def _eval_is_extended_positive(self):
from sympy.core.exprtools import _monotonic_sign
if self.is_number:
return super()._eval_is_extended_positive()
c, a = self.as_coeff_Add()
if not c.is_zero:
v = _monotonic_sign(a)
if v is not None:
s = v + c
if s != self and s.is_extended_positive and a.is_extended_nonnegative:
return True
if len(self.free_symbols) == 1:
v = _monotonic_sign(self)
if v is not None and v != self and v.is_extended_positive:
return True
pos = nonneg = nonpos = unknown_sign = False
saw_INF = set()
args = [a for a in self.args if not a.is_zero]
if not args:
return False
for a in args:
ispos = a.is_extended_positive
infinite = a.is_infinite
if infinite:
saw_INF.add(fuzzy_or((ispos, a.is_extended_nonnegative)))
if True in saw_INF and False in saw_INF:
return
if ispos:
pos = True
continue
elif a.is_extended_nonnegative:
nonneg = True
continue
elif a.is_extended_nonpositive:
nonpos = True
continue
if infinite is None:
return
unknown_sign = True
if saw_INF:
if len(saw_INF) > 1:
return
return saw_INF.pop()
elif unknown_sign:
return
elif not nonpos and not nonneg and pos:
return True
elif not nonpos and pos:
return True
elif not pos and not nonneg:
return False
def _eval_is_extended_nonnegative(self):
from sympy.core.exprtools import _monotonic_sign
if not self.is_number:
c, a = self.as_coeff_Add()
if not c.is_zero and a.is_extended_nonnegative:
v = _monotonic_sign(a)
if v is not None:
s = v + c
if s != self and s.is_extended_nonnegative:
return True
if len(self.free_symbols) == 1:
v = _monotonic_sign(self)
if v is not None and v != self and v.is_extended_nonnegative:
return True
def _eval_is_extended_nonpositive(self):
from sympy.core.exprtools import _monotonic_sign
if not self.is_number:
c, a = self.as_coeff_Add()
if not c.is_zero and a.is_extended_nonpositive:
v = _monotonic_sign(a)
if v is not None:
s = v + c
if s != self and s.is_extended_nonpositive:
return True
if len(self.free_symbols) == 1:
v = _monotonic_sign(self)
if v is not None and v != self and v.is_extended_nonpositive:
return True
def _eval_is_extended_negative(self):
from sympy.core.exprtools import _monotonic_sign
if self.is_number:
return super()._eval_is_extended_negative()
c, a = self.as_coeff_Add()
if not c.is_zero:
v = _monotonic_sign(a)
if v is not None:
s = v + c
if s != self and s.is_extended_negative and a.is_extended_nonpositive:
return True
if len(self.free_symbols) == 1:
v = _monotonic_sign(self)
if v is not None and v != self and v.is_extended_negative:
return True
neg = nonpos = nonneg = unknown_sign = False
saw_INF = set()
args = [a for a in self.args if not a.is_zero]
if not args:
return False
for a in args:
isneg = a.is_extended_negative
infinite = a.is_infinite
if infinite:
saw_INF.add(fuzzy_or((isneg, a.is_extended_nonpositive)))
if True in saw_INF and False in saw_INF:
return
if isneg:
neg = True
continue
elif a.is_extended_nonpositive:
nonpos = True
continue
elif a.is_extended_nonnegative:
nonneg = True
continue
if infinite is None:
return
unknown_sign = True
if saw_INF:
if len(saw_INF) > 1:
return
return saw_INF.pop()
elif unknown_sign:
return
elif not nonneg and not nonpos and neg:
return True
elif not nonneg and neg:
return True
elif not neg and not nonpos:
return False
def _eval_subs(self, old, new):
if not old.is_Add:
if old is S.Infinity and -old in self.args:
# foo - oo is foo + (-oo) internally
return self.xreplace({-old: -new})
return None
coeff_self, terms_self = self.as_coeff_Add()
coeff_old, terms_old = old.as_coeff_Add()
if coeff_self.is_Rational and coeff_old.is_Rational:
if terms_self == terms_old: # (2 + a).subs( 3 + a, y) -> -1 + y
return self.func(new, coeff_self, -coeff_old)
if terms_self == -terms_old: # (2 + a).subs(-3 - a, y) -> -1 - y
return self.func(-new, coeff_self, coeff_old)
if coeff_self.is_Rational and coeff_old.is_Rational \
or coeff_self == coeff_old:
args_old, args_self = self.func.make_args(
terms_old), self.func.make_args(terms_self)
if len(args_old) < len(args_self): # (a+b+c).subs(b+c,x) -> a+x
self_set = set(args_self)
old_set = set(args_old)
if old_set < self_set:
ret_set = self_set - old_set
return self.func(new, coeff_self, -coeff_old,
*[s._subs(old, new) for s in ret_set])
args_old = self.func.make_args(
-terms_old) # (a+b+c+d).subs(-b-c,x) -> a-x+d
old_set = set(args_old)
if old_set < self_set:
ret_set = self_set - old_set
return self.func(-new, coeff_self, coeff_old,
*[s._subs(old, new) for s in ret_set])
def removeO(self):
args = [a for a in self.args if not a.is_Order]
return self._new_rawargs(*args)
def getO(self):
args = [a for a in self.args if a.is_Order]
if args:
return self._new_rawargs(*args)
@cacheit
def extract_leading_order(self, symbols, point=None):
"""
Returns the leading term and its order.
Examples
========
>>> from sympy.abc import x
>>> (x + 1 + 1/x**5).extract_leading_order(x)
((x**(-5), O(x**(-5))),)
>>> (1 + x).extract_leading_order(x)
((1, O(1)),)
>>> (x + x**2).extract_leading_order(x)
((x, O(x)),)
"""
from sympy import Order
lst = []
symbols = list(symbols if is_sequence(symbols) else [symbols])
if not point:
point = [0]*len(symbols)
seq = [(f, Order(f, *zip(symbols, point))) for f in self.args]
for ef, of in seq:
for e, o in lst:
if o.contains(of) and o != of:
of = None
break
if of is None:
continue
new_lst = [(ef, of)]
for e, o in lst:
if of.contains(o) and o != of:
continue
new_lst.append((e, o))
lst = new_lst
return tuple(lst)
def as_real_imag(self, deep=True, **hints):
"""
returns a tuple representing a complex number
Examples
========
>>> from sympy import I
>>> (7 + 9*I).as_real_imag()
(7, 9)
>>> ((1 + I)/(1 - I)).as_real_imag()
(0, 1)
>>> ((1 + 2*I)*(1 + 3*I)).as_real_imag()
(-5, 5)
"""
sargs = self.args
re_part, im_part = [], []
for term in sargs:
re, im = term.as_real_imag(deep=deep)
re_part.append(re)
im_part.append(im)
return (self.func(*re_part), self.func(*im_part))
def _eval_as_leading_term(self, x, cdir=0):
from sympy import expand_mul, Order
old = self
expr = expand_mul(self)
if not expr.is_Add:
return expr.as_leading_term(x, cdir=cdir)
infinite = [t for t in expr.args if t.is_infinite]
leading_terms = [t.as_leading_term(x, cdir=cdir) for t in expr.args]
min, new_expr = Order(0), 0
try:
for term in leading_terms:
order = Order(term, x)
if not min or order not in min:
min = order
new_expr = term
elif min in order:
new_expr += term
except TypeError:
return expr
is_zero = new_expr.is_zero
if is_zero is None:
new_expr = new_expr.trigsimp().cancel()
is_zero = new_expr.is_zero
if is_zero is True:
# simple leading term analysis gave us cancelled terms but we have to send
# back a term, so compute the leading term (via series)
n0 = min.getn()
res = Order(1)
incr = S.One
while res.is_Order:
res = old._eval_nseries(x, n=n0+incr, logx=None, cdir=cdir).cancel().trigsimp()
incr *= 2
return res.as_leading_term(x, cdir=cdir)
elif new_expr is S.NaN:
return old.func._from_args(infinite)
else:
return new_expr
def _eval_adjoint(self):
return self.func(*[t.adjoint() for t in self.args])
def _eval_conjugate(self):
return self.func(*[t.conjugate() for t in self.args])
def _eval_transpose(self):
return self.func(*[t.transpose() for t in self.args])
def _sage_(self):
s = 0
for x in self.args:
s += x._sage_()
return s
def primitive(self):
"""
Return ``(R, self/R)`` where ``R``` is the Rational GCD of ``self```.
``R`` is collected only from the leading coefficient of each term.
Examples
========
>>> from sympy.abc import x, y
>>> (2*x + 4*y).primitive()
(2, x + 2*y)
>>> (2*x/3 + 4*y/9).primitive()
(2/9, 3*x + 2*y)
>>> (2*x/3 + 4.2*y).primitive()
(1/3, 2*x + 12.6*y)
No subprocessing of term factors is performed:
>>> ((2 + 2*x)*x + 2).primitive()
(1, x*(2*x + 2) + 2)
Recursive processing can be done with the ``as_content_primitive()``
method:
>>> ((2 + 2*x)*x + 2).as_content_primitive()
(2, x*(x + 1) + 1)
See also: primitive() function in polytools.py
"""
terms = []
inf = False
for a in self.args:
c, m = a.as_coeff_Mul()
if not c.is_Rational:
c = S.One
m = a
inf = inf or m is S.ComplexInfinity
terms.append((c.p, c.q, m))
if not inf:
ngcd = reduce(igcd, [t[0] for t in terms], 0)
dlcm = reduce(ilcm, [t[1] for t in terms], 1)
else:
ngcd = reduce(igcd, [t[0] for t in terms if t[1]], 0)
dlcm = reduce(ilcm, [t[1] for t in terms if t[1]], 1)
if ngcd == dlcm == 1:
return S.One, self
if not inf:
for i, (p, q, term) in enumerate(terms):
terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term)
else:
for i, (p, q, term) in enumerate(terms):
if q:
terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term)
else:
terms[i] = _keep_coeff(Rational(p, q), term)
# we don't need a complete re-flattening since no new terms will join
# so we just use the same sort as is used in Add.flatten. When the
# coefficient changes, the ordering of terms may change, e.g.
# (3*x, 6*y) -> (2*y, x)
#
# We do need to make sure that term[0] stays in position 0, however.
#
if terms[0].is_Number or terms[0] is S.ComplexInfinity:
c = terms.pop(0)
else:
c = None
_addsort(terms)
if c:
terms.insert(0, c)
return Rational(ngcd, dlcm), self._new_rawargs(*terms)
def as_content_primitive(self, radical=False, clear=True):
"""Return the tuple (R, self/R) where R is the positive Rational
extracted from self. If radical is True (default is False) then
common radicals will be removed and included as a factor of the
primitive expression.
Examples
========
>>> from sympy import sqrt
>>> (3 + 3*sqrt(2)).as_content_primitive()
(3, 1 + sqrt(2))
Radical content can also be factored out of the primitive:
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
(2, sqrt(2)*(1 + 2*sqrt(5)))
See docstring of Expr.as_content_primitive for more examples.
"""
con, prim = self.func(*[_keep_coeff(*a.as_content_primitive(
radical=radical, clear=clear)) for a in self.args]).primitive()
if not clear and not con.is_Integer and prim.is_Add:
con, d = con.as_numer_denom()
_p = prim/d
if any(a.as_coeff_Mul()[0].is_Integer for a in _p.args):
prim = _p
else:
con /= d
if radical and prim.is_Add:
# look for common radicals that can be removed
args = prim.args
rads = []
common_q = None
for m in args:
term_rads = defaultdict(list)
for ai in Mul.make_args(m):
if ai.is_Pow:
b, e = ai.as_base_exp()
if e.is_Rational and b.is_Integer:
term_rads[e.q].append(abs(int(b))**e.p)
if not term_rads:
break
if common_q is None:
common_q = set(term_rads.keys())
else:
common_q = common_q & set(term_rads.keys())
if not common_q:
break
rads.append(term_rads)
else:
# process rads
# keep only those in common_q
for r in rads:
for q in list(r.keys()):
if q not in common_q:
r.pop(q)
for q in r:
r[q] = prod(r[q])
# find the gcd of bases for each q
G = []
for q in common_q:
g = reduce(igcd, [r[q] for r in rads], 0)
if g != 1:
G.append(g**Rational(1, q))
if G:
G = Mul(*G)
args = [ai/G for ai in args]
prim = G*prim.func(*args)
return con, prim
@property
def _sorted_args(self):
from sympy.core.compatibility import default_sort_key
return tuple(sorted(self.args, key=default_sort_key))
def _eval_difference_delta(self, n, step):
from sympy.series.limitseq import difference_delta as dd
return self.func(*[dd(a, n, step) for a in self.args])
@property
def _mpc_(self):
"""
Convert self to an mpmath mpc if possible
"""
from sympy.core.numbers import I, Float
re_part, rest = self.as_coeff_Add()
im_part, imag_unit = rest.as_coeff_Mul()
if not imag_unit == I:
# ValueError may seem more reasonable but since it's a @property,
# we need to use AttributeError to keep from confusing things like
# hasattr.
raise AttributeError("Cannot convert Add to mpc. Must be of the form Number + Number*I")
return (Float(re_part)._mpf_, Float(im_part)._mpf_)
def __neg__(self):
if not global_parameters.distribute:
return super().__neg__()
return Add(*[-i for i in self.args])
add = AssocOpDispatcher('add')
from .mul import Mul, _keep_coeff, prod
from sympy.core.numbers import Rational
|
ed1466879dd1213b31fcc62e758a6660d525f6974528a11703733850e0924d1a | from typing import Tuple as tTuple
from collections.abc import Iterable
from functools import reduce
from .sympify import sympify, _sympify, SympifyError
from .basic import Basic, Atom
from .singleton import S
from .evalf import EvalfMixin, pure_complex
from .decorators import call_highest_priority, sympify_method_args, sympify_return
from .cache import cacheit
from .compatibility import as_int, default_sort_key
from sympy.utilities.misc import func_name
from mpmath.libmp import mpf_log, prec_to_dps
from collections import defaultdict
@sympify_method_args
class Expr(Basic, EvalfMixin):
"""
Base class for algebraic expressions.
Explanation
===========
Everything that requires arithmetic operations to be defined
should subclass this class, instead of Basic (which should be
used only for argument storage and expression manipulation, i.e.
pattern matching, substitutions, etc).
If you want to override the comparisons of expressions:
Should use _eval_is_ge for inequality, or _eval_is_eq, with multiple dispatch.
_eval_is_ge return true if x >= y, false if x < y, and None if the two types
are not comparable or the comparison is indeterminate
See Also
========
sympy.core.basic.Basic
"""
__slots__ = () # type: tTuple[str, ...]
is_scalar = True # self derivative is 1
@property
def _diff_wrt(self):
"""Return True if one can differentiate with respect to this
object, else False.
Explanation
===========
Subclasses such as Symbol, Function and Derivative return True
to enable derivatives wrt them. The implementation in Derivative
separates the Symbol and non-Symbol (_diff_wrt=True) variables and
temporarily converts the non-Symbols into Symbols when performing
the differentiation. By default, any object deriving from Expr
will behave like a scalar with self.diff(self) == 1. If this is
not desired then the object must also set `is_scalar = False` or
else define an _eval_derivative routine.
Note, see the docstring of Derivative for how this should work
mathematically. In particular, note that expr.subs(yourclass, Symbol)
should be well-defined on a structural level, or this will lead to
inconsistent results.
Examples
========
>>> from sympy import Expr
>>> e = Expr()
>>> e._diff_wrt
False
>>> class MyScalar(Expr):
... _diff_wrt = True
...
>>> MyScalar().diff(MyScalar())
1
>>> class MySymbol(Expr):
... _diff_wrt = True
... is_scalar = False
...
>>> MySymbol().diff(MySymbol())
Derivative(MySymbol(), MySymbol())
"""
return False
@cacheit
def sort_key(self, order=None):
coeff, expr = self.as_coeff_Mul()
if expr.is_Pow:
if expr.base is S.Exp1:
# If we remove this, many doctests will go crazy:
# (keeps E**x sorted like the exp(x) function,
# part of exp(x) to E**x transition)
expr, exp = Function("exp")(expr.exp), S.One
else:
expr, exp = expr.args
else:
expr, exp = expr, S.One
if expr.is_Dummy:
args = (expr.sort_key(),)
elif expr.is_Atom:
args = (str(expr),)
else:
if expr.is_Add:
args = expr.as_ordered_terms(order=order)
elif expr.is_Mul:
args = expr.as_ordered_factors(order=order)
else:
args = expr.args
args = tuple(
[ default_sort_key(arg, order=order) for arg in args ])
args = (len(args), tuple(args))
exp = exp.sort_key(order=order)
return expr.class_key(), args, exp, coeff
def __hash__(self) -> int:
# hash cannot be cached using cache_it because infinite recurrence
# occurs as hash is needed for setting cache dictionary keys
h = self._mhash
if h is None:
h = hash((type(self).__name__,) + self._hashable_content())
self._mhash = h
return h
def _hashable_content(self):
"""Return a tuple of information about self that can be used to
compute the hash. If a class defines additional attributes,
like ``name`` in Symbol, then this method should be updated
accordingly to return such relevant attributes.
Defining more than _hashable_content is necessary if __eq__ has
been defined by a class. See note about this in Basic.__eq__."""
return self._args
def __eq__(self, other):
try:
other = _sympify(other)
if not isinstance(other, Expr):
return False
except (SympifyError, SyntaxError):
return False
# check for pure number expr
if not (self.is_Number and other.is_Number) and (
type(self) != type(other)):
return False
a, b = self._hashable_content(), other._hashable_content()
if a != b:
return False
# check number *in* an expression
for a, b in zip(a, b):
if not isinstance(a, Expr):
continue
if a.is_Number and type(a) != type(b):
return False
return True
# ***************
# * Arithmetics *
# ***************
# Expr and its sublcasses use _op_priority to determine which object
# passed to a binary special method (__mul__, etc.) will handle the
# operation. In general, the 'call_highest_priority' decorator will choose
# the object with the highest _op_priority to handle the call.
# Custom subclasses that want to define their own binary special methods
# should set an _op_priority value that is higher than the default.
#
# **NOTE**:
# This is a temporary fix, and will eventually be replaced with
# something better and more powerful. See issue 5510.
_op_priority = 10.0
@property
def _add_handler(self):
return Add
@property
def _mul_handler(self):
return Mul
def __pos__(self):
return self
def __neg__(self):
# Mul has its own __neg__ routine, so we just
# create a 2-args Mul with the -1 in the canonical
# slot 0.
c = self.is_commutative
return Mul._from_args((S.NegativeOne, self), c)
def __abs__(self):
from sympy import Abs
return Abs(self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__radd__')
def __add__(self, other):
return Add(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__add__')
def __radd__(self, other):
return Add(other, self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rsub__')
def __sub__(self, other):
return Add(self, -other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__sub__')
def __rsub__(self, other):
return Add(other, -self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rmul__')
def __mul__(self, other):
return Mul(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return Mul(other, self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rpow__')
def _pow(self, other):
return Pow(self, other)
def __pow__(self, other, mod=None):
if mod is None:
return self._pow(other)
try:
_self, other, mod = as_int(self), as_int(other), as_int(mod)
if other >= 0:
return pow(_self, other, mod)
else:
from sympy.core.numbers import mod_inverse
return mod_inverse(pow(_self, -other, mod), mod)
except ValueError:
power = self._pow(other)
try:
return power%mod
except TypeError:
return NotImplemented
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__pow__')
def __rpow__(self, other):
return Pow(other, self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rtruediv__')
def __truediv__(self, other):
denom = Pow(other, S.NegativeOne)
if self is S.One:
return denom
else:
return Mul(self, denom)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__truediv__')
def __rtruediv__(self, other):
denom = Pow(self, S.NegativeOne)
if other is S.One:
return denom
else:
return Mul(other, denom)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rmod__')
def __mod__(self, other):
return Mod(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__mod__')
def __rmod__(self, other):
return Mod(other, self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rfloordiv__')
def __floordiv__(self, other):
from sympy.functions.elementary.integers import floor
return floor(self / other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__floordiv__')
def __rfloordiv__(self, other):
from sympy.functions.elementary.integers import floor
return floor(other / self)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__rdivmod__')
def __divmod__(self, other):
from sympy.functions.elementary.integers import floor
return floor(self / other), Mod(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
@call_highest_priority('__divmod__')
def __rdivmod__(self, other):
from sympy.functions.elementary.integers import floor
return floor(other / self), Mod(other, self)
def __int__(self):
# Although we only need to round to the units position, we'll
# get one more digit so the extra testing below can be avoided
# unless the rounded value rounded to an integer, e.g. if an
# expression were equal to 1.9 and we rounded to the unit position
# we would get a 2 and would not know if this rounded up or not
# without doing a test (as done below). But if we keep an extra
# digit we know that 1.9 is not the same as 1 and there is no
# need for further testing: our int value is correct. If the value
# were 1.99, however, this would round to 2.0 and our int value is
# off by one. So...if our round value is the same as the int value
# (regardless of how much extra work we do to calculate extra decimal
# places) we need to test whether we are off by one.
from sympy import Dummy
if not self.is_number:
raise TypeError("can't convert symbols to int")
r = self.round(2)
if not r.is_Number:
raise TypeError("can't convert complex to int")
if r in (S.NaN, S.Infinity, S.NegativeInfinity):
raise TypeError("can't convert %s to int" % r)
i = int(r)
if not i:
return 0
# off-by-one check
if i == r and not (self - i).equals(0):
isign = 1 if i > 0 else -1
x = Dummy()
# in the following (self - i).evalf(2) will not always work while
# (self - r).evalf(2) and the use of subs does; if the test that
# was added when this comment was added passes, it might be safe
# to simply use sign to compute this rather than doing this by hand:
diff_sign = 1 if (self - x).evalf(2, subs={x: i}) > 0 else -1
if diff_sign != isign:
i -= isign
return i
def __float__(self):
# Don't bother testing if it's a number; if it's not this is going
# to fail, and if it is we still need to check that it evalf'ed to
# a number.
result = self.evalf()
if result.is_Number:
return float(result)
if result.is_number and result.as_real_imag()[1]:
raise TypeError("can't convert complex to float")
raise TypeError("can't convert expression to float")
def __complex__(self):
result = self.evalf()
re, im = result.as_real_imag()
return complex(float(re), float(im))
@sympify_return([('other', 'Expr')], NotImplemented)
def __ge__(self, other):
from .relational import GreaterThan
return GreaterThan(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
def __le__(self, other):
from .relational import LessThan
return LessThan(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
def __gt__(self, other):
from .relational import StrictGreaterThan
return StrictGreaterThan(self, other)
@sympify_return([('other', 'Expr')], NotImplemented)
def __lt__(self, other):
from .relational import StrictLessThan
return StrictLessThan(self, other)
def __trunc__(self):
if not self.is_number:
raise TypeError("can't truncate symbols and expressions")
else:
return Integer(self)
@staticmethod
def _from_mpmath(x, prec):
from sympy import Float
if hasattr(x, "_mpf_"):
return Float._new(x._mpf_, prec)
elif hasattr(x, "_mpc_"):
re, im = x._mpc_
re = Float._new(re, prec)
im = Float._new(im, prec)*S.ImaginaryUnit
return re + im
else:
raise TypeError("expected mpmath number (mpf or mpc)")
@property
def is_number(self):
"""Returns True if ``self`` has no free symbols and no
undefined functions (AppliedUndef, to be precise). It will be
faster than ``if not self.free_symbols``, however, since
``is_number`` will fail as soon as it hits a free symbol
or undefined function.
Examples
========
>>> from sympy import Integral, cos, sin, pi
>>> from sympy.core.function import Function
>>> from sympy.abc import x
>>> f = Function('f')
>>> x.is_number
False
>>> f(1).is_number
False
>>> (2*x).is_number
False
>>> (2 + Integral(2, x)).is_number
False
>>> (2 + Integral(2, (x, 1, 2))).is_number
True
Not all numbers are Numbers in the SymPy sense:
>>> pi.is_number, pi.is_Number
(True, False)
If something is a number it should evaluate to a number with
real and imaginary parts that are Numbers; the result may not
be comparable, however, since the real and/or imaginary part
of the result may not have precision.
>>> cos(1).is_number and cos(1).is_comparable
True
>>> z = cos(1)**2 + sin(1)**2 - 1
>>> z.is_number
True
>>> z.is_comparable
False
See Also
========
sympy.core.basic.Basic.is_comparable
"""
return all(obj.is_number for obj in self.args)
def _random(self, n=None, re_min=-1, im_min=-1, re_max=1, im_max=1):
"""Return self evaluated, if possible, replacing free symbols with
random complex values, if necessary.
Explanation
===========
The random complex value for each free symbol is generated
by the random_complex_number routine giving real and imaginary
parts in the range given by the re_min, re_max, im_min, and im_max
values. The returned value is evaluated to a precision of n
(if given) else the maximum of 15 and the precision needed
to get more than 1 digit of precision. If the expression
could not be evaluated to a number, or could not be evaluated
to more than 1 digit of precision, then None is returned.
Examples
========
>>> from sympy import sqrt
>>> from sympy.abc import x, y
>>> x._random() # doctest: +SKIP
0.0392918155679172 + 0.916050214307199*I
>>> x._random(2) # doctest: +SKIP
-0.77 - 0.87*I
>>> (x + y/2)._random(2) # doctest: +SKIP
-0.57 + 0.16*I
>>> sqrt(2)._random(2)
1.4
See Also
========
sympy.testing.randtest.random_complex_number
"""
free = self.free_symbols
prec = 1
if free:
from sympy.testing.randtest import random_complex_number
a, c, b, d = re_min, re_max, im_min, im_max
reps = dict(list(zip(free, [random_complex_number(a, b, c, d, rational=True)
for zi in free])))
try:
nmag = abs(self.evalf(2, subs=reps))
except (ValueError, TypeError):
# if an out of range value resulted in evalf problems
# then return None -- XXX is there a way to know how to
# select a good random number for a given expression?
# e.g. when calculating n! negative values for n should not
# be used
return None
else:
reps = {}
nmag = abs(self.evalf(2))
if not hasattr(nmag, '_prec'):
# e.g. exp_polar(2*I*pi) doesn't evaluate but is_number is True
return None
if nmag._prec == 1:
# increase the precision up to the default maximum
# precision to see if we can get any significance
from mpmath.libmp.libintmath import giant_steps
from sympy.core.evalf import DEFAULT_MAXPREC as target
# evaluate
for prec in giant_steps(2, target):
nmag = abs(self.evalf(prec, subs=reps))
if nmag._prec != 1:
break
if nmag._prec != 1:
if n is None:
n = max(prec, 15)
return self.evalf(n, subs=reps)
# never got any significance
return None
def is_constant(self, *wrt, **flags):
"""Return True if self is constant, False if not, or None if
the constancy could not be determined conclusively.
Explanation
===========
If an expression has no free symbols then it is a constant. If
there are free symbols it is possible that the expression is a
constant, perhaps (but not necessarily) zero. To test such
expressions, a few strategies are tried:
1) numerical evaluation at two random points. If two such evaluations
give two different values and the values have a precision greater than
1 then self is not constant. If the evaluations agree or could not be
obtained with any precision, no decision is made. The numerical testing
is done only if ``wrt`` is different than the free symbols.
2) differentiation with respect to variables in 'wrt' (or all free
symbols if omitted) to see if the expression is constant or not. This
will not always lead to an expression that is zero even though an
expression is constant (see added test in test_expr.py). If
all derivatives are zero then self is constant with respect to the
given symbols.
3) finding out zeros of denominator expression with free_symbols.
It won't be constant if there are zeros. It gives more negative
answers for expression that are not constant.
If neither evaluation nor differentiation can prove the expression is
constant, None is returned unless two numerical values happened to be
the same and the flag ``failing_number`` is True -- in that case the
numerical value will be returned.
If flag simplify=False is passed, self will not be simplified;
the default is True since self should be simplified before testing.
Examples
========
>>> from sympy import cos, sin, Sum, S, pi
>>> from sympy.abc import a, n, x, y
>>> x.is_constant()
False
>>> S(2).is_constant()
True
>>> Sum(x, (x, 1, 10)).is_constant()
True
>>> Sum(x, (x, 1, n)).is_constant()
False
>>> Sum(x, (x, 1, n)).is_constant(y)
True
>>> Sum(x, (x, 1, n)).is_constant(n)
False
>>> Sum(x, (x, 1, n)).is_constant(x)
True
>>> eq = a*cos(x)**2 + a*sin(x)**2 - a
>>> eq.is_constant()
True
>>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
True
>>> (0**x).is_constant()
False
>>> x.is_constant()
False
>>> (x**x).is_constant()
False
>>> one = cos(x)**2 + sin(x)**2
>>> one.is_constant()
True
>>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1
True
"""
def check_denominator_zeros(expression):
from sympy.solvers.solvers import denoms
retNone = False
for den in denoms(expression):
z = den.is_zero
if z is True:
return True
if z is None:
retNone = True
if retNone:
return None
return False
simplify = flags.get('simplify', True)
if self.is_number:
return True
free = self.free_symbols
if not free:
return True # assume f(1) is some constant
# if we are only interested in some symbols and they are not in the
# free symbols then this expression is constant wrt those symbols
wrt = set(wrt)
if wrt and not wrt & free:
return True
wrt = wrt or free
# simplify unless this has already been done
expr = self
if simplify:
expr = expr.simplify()
# is_zero should be a quick assumptions check; it can be wrong for
# numbers (see test_is_not_constant test), giving False when it
# shouldn't, but hopefully it will never give True unless it is sure.
if expr.is_zero:
return True
# try numerical evaluation to see if we get two different values
failing_number = None
if wrt == free:
# try 0 (for a) and 1 (for b)
try:
a = expr.subs(list(zip(free, [0]*len(free))),
simultaneous=True)
if a is S.NaN:
# evaluation may succeed when substitution fails
a = expr._random(None, 0, 0, 0, 0)
except ZeroDivisionError:
a = None
if a is not None and a is not S.NaN:
try:
b = expr.subs(list(zip(free, [1]*len(free))),
simultaneous=True)
if b is S.NaN:
# evaluation may succeed when substitution fails
b = expr._random(None, 1, 0, 1, 0)
except ZeroDivisionError:
b = None
if b is not None and b is not S.NaN and b.equals(a) is False:
return False
# try random real
b = expr._random(None, -1, 0, 1, 0)
if b is not None and b is not S.NaN and b.equals(a) is False:
return False
# try random complex
b = expr._random()
if b is not None and b is not S.NaN:
if b.equals(a) is False:
return False
failing_number = a if a.is_number else b
# now we will test each wrt symbol (or all free symbols) to see if the
# expression depends on them or not using differentiation. This is
# not sufficient for all expressions, however, so we don't return
# False if we get a derivative other than 0 with free symbols.
for w in wrt:
deriv = expr.diff(w)
if simplify:
deriv = deriv.simplify()
if deriv != 0:
if not (pure_complex(deriv, or_real=True)):
if flags.get('failing_number', False):
return failing_number
elif deriv.free_symbols:
# dead line provided _random returns None in such cases
return None
return False
cd = check_denominator_zeros(self)
if cd is True:
return False
elif cd is None:
return None
return True
def equals(self, other, failing_expression=False):
"""Return True if self == other, False if it doesn't, or None. If
failing_expression is True then the expression which did not simplify
to a 0 will be returned instead of None.
Explanation
===========
If ``self`` is a Number (or complex number) that is not zero, then
the result is False.
If ``self`` is a number and has not evaluated to zero, evalf will be
used to test whether the expression evaluates to zero. If it does so
and the result has significance (i.e. the precision is either -1, for
a Rational result, or is greater than 1) then the evalf value will be
used to return True or False.
"""
from sympy.simplify.simplify import nsimplify, simplify
from sympy.solvers.solvers import solve
from sympy.polys.polyerrors import NotAlgebraic
from sympy.polys.numberfields import minimal_polynomial
other = sympify(other)
if self == other:
return True
# they aren't the same so see if we can make the difference 0;
# don't worry about doing simplification steps one at a time
# because if the expression ever goes to 0 then the subsequent
# simplification steps that are done will be very fast.
diff = factor_terms(simplify(self - other), radical=True)
if not diff:
return True
if not diff.has(Add, Mod):
# if there is no expanding to be done after simplifying
# then this can't be a zero
return False
constant = diff.is_constant(simplify=False, failing_number=True)
if constant is False:
return False
if not diff.is_number:
if constant is None:
# e.g. unless the right simplification is done, a symbolic
# zero is possible (see expression of issue 6829: without
# simplification constant will be None).
return
if constant is True:
# this gives a number whether there are free symbols or not
ndiff = diff._random()
# is_comparable will work whether the result is real
# or complex; it could be None, however.
if ndiff and ndiff.is_comparable:
return False
# sometimes we can use a simplified result to give a clue as to
# what the expression should be; if the expression is *not* zero
# then we should have been able to compute that and so now
# we can just consider the cases where the approximation appears
# to be zero -- we try to prove it via minimal_polynomial.
#
# removed
# ns = nsimplify(diff)
# if diff.is_number and (not ns or ns == diff):
#
# The thought was that if it nsimplifies to 0 that's a sure sign
# to try the following to prove it; or if it changed but wasn't
# zero that might be a sign that it's not going to be easy to
# prove. But tests seem to be working without that logic.
#
if diff.is_number:
# try to prove via self-consistency
surds = [s for s in diff.atoms(Pow) if s.args[0].is_Integer]
# it seems to work better to try big ones first
surds.sort(key=lambda x: -x.args[0])
for s in surds:
try:
# simplify is False here -- this expression has already
# been identified as being hard to identify as zero;
# we will handle the checking ourselves using nsimplify
# to see if we are in the right ballpark or not and if so
# *then* the simplification will be attempted.
sol = solve(diff, s, simplify=False)
if sol:
if s in sol:
# the self-consistent result is present
return True
if all(si.is_Integer for si in sol):
# perfect powers are removed at instantiation
# so surd s cannot be an integer
return False
if all(i.is_algebraic is False for i in sol):
# a surd is algebraic
return False
if any(si in surds for si in sol):
# it wasn't equal to s but it is in surds
# and different surds are not equal
return False
if any(nsimplify(s - si) == 0 and
simplify(s - si) == 0 for si in sol):
return True
if s.is_real:
if any(nsimplify(si, [s]) == s and simplify(si) == s
for si in sol):
return True
except NotImplementedError:
pass
# try to prove with minimal_polynomial but know when
# *not* to use this or else it can take a long time. e.g. issue 8354
if True: # change True to condition that assures non-hang
try:
mp = minimal_polynomial(diff)
if mp.is_Symbol:
return True
return False
except (NotAlgebraic, NotImplementedError):
pass
# diff has not simplified to zero; constant is either None, True
# or the number with significance (is_comparable) that was randomly
# calculated twice as the same value.
if constant not in (True, None) and constant != 0:
return False
if failing_expression:
return diff
return None
def _eval_is_positive(self):
finite = self.is_finite
if finite is False:
return False
extended_positive = self.is_extended_positive
if finite is True:
return extended_positive
if extended_positive is False:
return False
def _eval_is_negative(self):
finite = self.is_finite
if finite is False:
return False
extended_negative = self.is_extended_negative
if finite is True:
return extended_negative
if extended_negative is False:
return False
def _eval_is_extended_positive_negative(self, positive):
from sympy.core.numbers import pure_complex
from sympy.polys.numberfields import minimal_polynomial
from sympy.polys.polyerrors import NotAlgebraic
if self.is_number:
if self.is_extended_real is False:
return False
# check to see that we can get a value
try:
n2 = self._eval_evalf(2)
# XXX: This shouldn't be caught here
# Catches ValueError: hypsum() failed to converge to the requested
# 34 bits of accuracy
except ValueError:
return None
if n2 is None:
return None
if getattr(n2, '_prec', 1) == 1: # no significance
return None
if n2 is S.NaN:
return None
f = self.evalf(2)
if f.is_Float:
match = f, S.Zero
else:
match = pure_complex(f)
if match is None:
return False
r, i = match
if not (i.is_Number and r.is_Number):
return False
if r._prec != 1 and i._prec != 1:
return bool(not i and ((r > 0) if positive else (r < 0)))
elif r._prec == 1 and (not i or i._prec == 1) and \
self.is_algebraic and not self.has(Function):
try:
if minimal_polynomial(self).is_Symbol:
return False
except (NotAlgebraic, NotImplementedError):
pass
def _eval_is_extended_positive(self):
return self._eval_is_extended_positive_negative(positive=True)
def _eval_is_extended_negative(self):
return self._eval_is_extended_positive_negative(positive=False)
def _eval_interval(self, x, a, b):
"""
Returns evaluation over an interval. For most functions this is:
self.subs(x, b) - self.subs(x, a),
possibly using limit() if NaN is returned from subs, or if
singularities are found between a and b.
If b or a is None, it only evaluates -self.subs(x, a) or self.subs(b, x),
respectively.
"""
from sympy.series import limit, Limit
from sympy.solvers.solveset import solveset
from sympy.sets.sets import Interval
from sympy.functions.elementary.exponential import log
from sympy.calculus.util import AccumBounds
if (a is None and b is None):
raise ValueError('Both interval ends cannot be None.')
def _eval_endpoint(left):
c = a if left else b
if c is None:
return 0
else:
C = self.subs(x, c)
if C.has(S.NaN, S.Infinity, S.NegativeInfinity,
S.ComplexInfinity, AccumBounds):
if (a < b) != False:
C = limit(self, x, c, "+" if left else "-")
else:
C = limit(self, x, c, "-" if left else "+")
if isinstance(C, Limit):
raise NotImplementedError("Could not compute limit")
return C
if a == b:
return 0
A = _eval_endpoint(left=True)
if A is S.NaN:
return A
B = _eval_endpoint(left=False)
if (a and b) is None:
return B - A
value = B - A
if a.is_comparable and b.is_comparable:
if a < b:
domain = Interval(a, b)
else:
domain = Interval(b, a)
# check the singularities of self within the interval
# if singularities is a ConditionSet (not iterable), catch the exception and pass
singularities = solveset(self.cancel().as_numer_denom()[1], x,
domain=domain)
for logterm in self.atoms(log):
singularities = singularities | solveset(logterm.args[0], x,
domain=domain)
try:
for s in singularities:
if value is S.NaN:
# no need to keep adding, it will stay NaN
break
if not s.is_comparable:
continue
if (a < s) == (s < b) == True:
value += -limit(self, x, s, "+") + limit(self, x, s, "-")
elif (b < s) == (s < a) == True:
value += limit(self, x, s, "+") - limit(self, x, s, "-")
except TypeError:
pass
return value
def _eval_power(self, other):
# subclass to compute self**other for cases when
# other is not NaN, 0, or 1
return None
def _eval_conjugate(self):
if self.is_extended_real:
return self
elif self.is_imaginary:
return -self
def conjugate(self):
"""Returns the complex conjugate of 'self'."""
from sympy.functions.elementary.complexes import conjugate as c
return c(self)
def dir(self, x, cdir):
from sympy import log
minexp = S.Zero
if self.is_zero:
return S.Zero
arg = self
while arg:
minexp += S.One
arg = arg.diff(x)
coeff = arg.subs(x, 0)
if coeff in (S.NaN, S.ComplexInfinity):
try:
coeff, _ = arg.leadterm(x)
if coeff.has(log(x)):
raise ValueError()
except ValueError:
coeff = arg.limit(x, 0)
if coeff != S.Zero:
break
return coeff*cdir**minexp
def _eval_transpose(self):
from sympy.functions.elementary.complexes import conjugate
if (self.is_complex or self.is_infinite):
return self
elif self.is_hermitian:
return conjugate(self)
elif self.is_antihermitian:
return -conjugate(self)
def transpose(self):
from sympy.functions.elementary.complexes import transpose
return transpose(self)
def _eval_adjoint(self):
from sympy.functions.elementary.complexes import conjugate, transpose
if self.is_hermitian:
return self
elif self.is_antihermitian:
return -self
obj = self._eval_conjugate()
if obj is not None:
return transpose(obj)
obj = self._eval_transpose()
if obj is not None:
return conjugate(obj)
def adjoint(self):
from sympy.functions.elementary.complexes import adjoint
return adjoint(self)
@classmethod
def _parse_order(cls, order):
"""Parse and configure the ordering of terms. """
from sympy.polys.orderings import monomial_key
startswith = getattr(order, "startswith", None)
if startswith is None:
reverse = False
else:
reverse = startswith('rev-')
if reverse:
order = order[4:]
monom_key = monomial_key(order)
def neg(monom):
result = []
for m in monom:
if isinstance(m, tuple):
result.append(neg(m))
else:
result.append(-m)
return tuple(result)
def key(term):
_, ((re, im), monom, ncpart) = term
monom = neg(monom_key(monom))
ncpart = tuple([e.sort_key(order=order) for e in ncpart])
coeff = ((bool(im), im), (re, im))
return monom, ncpart, coeff
return key, reverse
def as_ordered_factors(self, order=None):
"""Return list of ordered factors (if Mul) else [self]."""
return [self]
def as_poly(self, *gens, **args):
"""Converts ``self`` to a polynomial or returns ``None``.
Explanation
===========
>>> from sympy import sin
>>> from sympy.abc import x, y
>>> print((x**2 + x*y).as_poly())
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + x*y).as_poly(x, y))
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + sin(y)).as_poly(x, y))
None
"""
from sympy.polys import Poly, PolynomialError
try:
poly = Poly(self, *gens, **args)
if not poly.is_Poly:
return None
else:
return poly
except PolynomialError:
return None
def as_ordered_terms(self, order=None, data=False):
"""
Transform an expression to an ordered list of terms.
Examples
========
>>> from sympy import sin, cos
>>> from sympy.abc import x
>>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms()
[sin(x)**2*cos(x), sin(x)**2, 1]
"""
from .numbers import Number, NumberSymbol
if order is None and self.is_Add:
# Spot the special case of Add(Number, Mul(Number, expr)) with the
# first number positive and thhe second number nagative
key = lambda x:not isinstance(x, (Number, NumberSymbol))
add_args = sorted(Add.make_args(self), key=key)
if (len(add_args) == 2
and isinstance(add_args[0], (Number, NumberSymbol))
and isinstance(add_args[1], Mul)):
mul_args = sorted(Mul.make_args(add_args[1]), key=key)
if (len(mul_args) == 2
and isinstance(mul_args[0], Number)
and add_args[0].is_positive
and mul_args[0].is_negative):
return add_args
key, reverse = self._parse_order(order)
terms, gens = self.as_terms()
if not any(term.is_Order for term, _ in terms):
ordered = sorted(terms, key=key, reverse=reverse)
else:
_terms, _order = [], []
for term, repr in terms:
if not term.is_Order:
_terms.append((term, repr))
else:
_order.append((term, repr))
ordered = sorted(_terms, key=key, reverse=True) \
+ sorted(_order, key=key, reverse=True)
if data:
return ordered, gens
else:
return [term for term, _ in ordered]
def as_terms(self):
"""Transform an expression to a list of terms. """
from .add import Add
from .mul import Mul
from .exprtools import decompose_power
gens, terms = set(), []
for term in Add.make_args(self):
coeff, _term = term.as_coeff_Mul()
coeff = complex(coeff)
cpart, ncpart = {}, []
if _term is not S.One:
for factor in Mul.make_args(_term):
if factor.is_number:
try:
coeff *= complex(factor)
except (TypeError, ValueError):
pass
else:
continue
if factor.is_commutative:
base, exp = decompose_power(factor)
cpart[base] = exp
gens.add(base)
else:
ncpart.append(factor)
coeff = coeff.real, coeff.imag
ncpart = tuple(ncpart)
terms.append((term, (coeff, cpart, ncpart)))
gens = sorted(gens, key=default_sort_key)
k, indices = len(gens), {}
for i, g in enumerate(gens):
indices[g] = i
result = []
for term, (coeff, cpart, ncpart) in terms:
monom = [0]*k
for base, exp in cpart.items():
monom[indices[base]] = exp
result.append((term, (coeff, tuple(monom), ncpart)))
return result, gens
def removeO(self):
"""Removes the additive O(..) symbol if there is one"""
return self
def getO(self):
"""Returns the additive O(..) symbol if there is one, else None."""
return None
def getn(self):
"""
Returns the order of the expression.
Explanation
===========
The order is determined either from the O(...) term. If there
is no O(...) term, it returns None.
Examples
========
>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
"""
from sympy import Dummy, Symbol
o = self.getO()
if o is None:
return None
elif o.is_Order:
o = o.expr
if o is S.One:
return S.Zero
if o.is_Symbol:
return S.One
if o.is_Pow:
return o.args[1]
if o.is_Mul: # x**n*log(x)**n or x**n/log(x)**n
for oi in o.args:
if oi.is_Symbol:
return S.One
if oi.is_Pow:
syms = oi.atoms(Symbol)
if len(syms) == 1:
x = syms.pop()
oi = oi.subs(x, Dummy('x', positive=True))
if oi.base.is_Symbol and oi.exp.is_Rational:
return abs(oi.exp)
raise NotImplementedError('not sure of order of %s' % o)
def count_ops(self, visual=None):
"""wrapper for count_ops that returns the operation count."""
from .function import count_ops
return count_ops(self, visual)
def args_cnc(self, cset=False, warn=True, split_1=True):
"""Return [commutative factors, non-commutative factors] of self.
Explanation
===========
self is treated as a Mul and the ordering of the factors is maintained.
If ``cset`` is True the commutative factors will be returned in a set.
If there were repeated factors (as may happen with an unevaluated Mul)
then an error will be raised unless it is explicitly suppressed by
setting ``warn`` to False.
Note: -1 is always separated from a Number unless split_1 is False.
Examples
========
>>> from sympy import symbols, oo
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[[-1, 2, x, y], []]
>>> (-2.5*x).args_cnc()
[[-1, 2.5, x], []]
>>> (-2*x*A*B*y).args_cnc()
[[-1, 2, x, y], [A, B]]
>>> (-2*x*A*B*y).args_cnc(split_1=False)
[[-2, x, y], [A, B]]
>>> (-2*x*y).args_cnc(cset=True)
[{-1, 2, x, y}, []]
The arg is always treated as a Mul:
>>> (-2 + x + A).args_cnc()
[[], [x - 2 + A]]
>>> (-oo).args_cnc() # -oo is a singleton
[[-1, oo], []]
"""
if self.is_Mul:
args = list(self.args)
else:
args = [self]
for i, mi in enumerate(args):
if not mi.is_commutative:
c = args[:i]
nc = args[i:]
break
else:
c = args
nc = []
if c and split_1 and (
c[0].is_Number and
c[0].is_extended_negative and
c[0] is not S.NegativeOne):
c[:1] = [S.NegativeOne, -c[0]]
if cset:
clen = len(c)
c = set(c)
if clen and warn and len(c) != clen:
raise ValueError('repeated commutative arguments: %s' %
[ci for ci in c if list(self.args).count(ci) > 1])
return [c, nc]
def coeff(self, x, n=1, right=False):
"""
Returns the coefficient from the term(s) containing ``x**n``. If ``n``
is zero then all terms independent of ``x`` will be returned.
Explanation
===========
When ``x`` is noncommutative, the coefficient to the left (default) or
right of ``x`` can be returned. The keyword 'right' is ignored when
``x`` is commutative.
Examples
========
>>> from sympy import symbols
>>> from sympy.abc import x, y, z
You can select terms that have an explicit negative in front of them:
>>> (-x + 2*y).coeff(-1)
x
>>> (x - 2*y).coeff(-1)
2*y
You can select terms with no Rational coefficient:
>>> (x + 2*y).coeff(1)
x
>>> (3 + 2*x + 4*x**2).coeff(1)
0
You can select terms independent of x by making n=0; in this case
expr.as_independent(x)[0] is returned (and 0 will be returned instead
of None):
>>> (3 + 2*x + 4*x**2).coeff(x, 0)
3
>>> eq = ((x + 1)**3).expand() + 1
>>> eq
x**3 + 3*x**2 + 3*x + 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 2]
>>> eq -= 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 0]
You can select terms that have a numerical term in front of them:
>>> (-x - 2*y).coeff(2)
-y
>>> from sympy import sqrt
>>> (x + sqrt(2)*x).coeff(sqrt(2))
x
The matching is exact:
>>> (3 + 2*x + 4*x**2).coeff(x)
2
>>> (3 + 2*x + 4*x**2).coeff(x**2)
4
>>> (3 + 2*x + 4*x**2).coeff(x**3)
0
>>> (z*(x + y)**2).coeff((x + y)**2)
z
>>> (z*(x + y)**2).coeff(x + y)
0
In addition, no factoring is done, so 1 + z*(1 + y) is not obtained
from the following:
>>> (x + z*(x + x*y)).coeff(x)
1
If such factoring is desired, factor_terms can be used first:
>>> from sympy import factor_terms
>>> factor_terms(x + z*(x + x*y)).coeff(x)
z*(y + 1) + 1
>>> n, m, o = symbols('n m o', commutative=False)
>>> n.coeff(n)
1
>>> (3*n).coeff(n)
3
>>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m
1 + m
>>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m
m
If there is more than one possible coefficient 0 is returned:
>>> (n*m + m*n).coeff(n)
0
If there is only one possible coefficient, it is returned:
>>> (n*m + x*m*n).coeff(m*n)
x
>>> (n*m + x*m*n).coeff(m*n, right=1)
1
See Also
========
as_coefficient: separate the expression into a coefficient and factor
as_coeff_Add: separate the additive constant from an expression
as_coeff_Mul: separate the multiplicative constant from an expression
as_independent: separate x-dependent terms/factors from others
sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used
"""
x = sympify(x)
if not isinstance(x, Basic):
return S.Zero
n = as_int(n)
if not x:
return S.Zero
if x == self:
if n == 1:
return S.One
return S.Zero
if x is S.One:
co = [a for a in Add.make_args(self)
if a.as_coeff_Mul()[0] is S.One]
if not co:
return S.Zero
return Add(*co)
if n == 0:
if x.is_Add and self.is_Add:
c = self.coeff(x, right=right)
if not c:
return S.Zero
if not right:
return self - Add(*[a*x for a in Add.make_args(c)])
return self - Add(*[x*a for a in Add.make_args(c)])
return self.as_independent(x, as_Add=True)[0]
# continue with the full method, looking for this power of x:
x = x**n
def incommon(l1, l2):
if not l1 or not l2:
return []
n = min(len(l1), len(l2))
for i in range(n):
if l1[i] != l2[i]:
return l1[:i]
return l1[:]
def find(l, sub, first=True):
""" Find where list sub appears in list l. When ``first`` is True
the first occurrence from the left is returned, else the last
occurrence is returned. Return None if sub is not in l.
Examples
========
>> l = range(5)*2
>> find(l, [2, 3])
2
>> find(l, [2, 3], first=0)
7
>> find(l, [2, 4])
None
"""
if not sub or not l or len(sub) > len(l):
return None
n = len(sub)
if not first:
l.reverse()
sub.reverse()
for i in range(0, len(l) - n + 1):
if all(l[i + j] == sub[j] for j in range(n)):
break
else:
i = None
if not first:
l.reverse()
sub.reverse()
if i is not None and not first:
i = len(l) - (i + n)
return i
co = []
args = Add.make_args(self)
self_c = self.is_commutative
x_c = x.is_commutative
if self_c and not x_c:
return S.Zero
one_c = self_c or x_c
xargs, nx = x.args_cnc(cset=True, warn=bool(not x_c))
# find the parts that pass the commutative terms
for a in args:
margs, nc = a.args_cnc(cset=True, warn=bool(not self_c))
if nc is None:
nc = []
if len(xargs) > len(margs):
continue
resid = margs.difference(xargs)
if len(resid) + len(xargs) == len(margs):
if one_c:
co.append(Mul(*(list(resid) + nc)))
else:
co.append((resid, nc))
if one_c:
if co == []:
return S.Zero
elif co:
return Add(*co)
else: # both nc
# now check the non-comm parts
if not co:
return S.Zero
if all(n == co[0][1] for r, n in co):
ii = find(co[0][1], nx, right)
if ii is not None:
if not right:
return Mul(Add(*[Mul(*r) for r, c in co]), Mul(*co[0][1][:ii]))
else:
return Mul(*co[0][1][ii + len(nx):])
beg = reduce(incommon, (n[1] for n in co))
if beg:
ii = find(beg, nx, right)
if ii is not None:
if not right:
gcdc = co[0][0]
for i in range(1, len(co)):
gcdc = gcdc.intersection(co[i][0])
if not gcdc:
break
return Mul(*(list(gcdc) + beg[:ii]))
else:
m = ii + len(nx)
return Add(*[Mul(*(list(r) + n[m:])) for r, n in co])
end = list(reversed(
reduce(incommon, (list(reversed(n[1])) for n in co))))
if end:
ii = find(end, nx, right)
if ii is not None:
if not right:
return Add(*[Mul(*(list(r) + n[:-len(end) + ii])) for r, n in co])
else:
return Mul(*end[ii + len(nx):])
# look for single match
hit = None
for i, (r, n) in enumerate(co):
ii = find(n, nx, right)
if ii is not None:
if not hit:
hit = ii, r, n
else:
break
else:
if hit:
ii, r, n = hit
if not right:
return Mul(*(list(r) + n[:ii]))
else:
return Mul(*n[ii + len(nx):])
return S.Zero
def as_expr(self, *gens):
"""
Convert a polynomial to a SymPy expression.
Examples
========
>>> from sympy import sin
>>> from sympy.abc import x, y
>>> f = (x**2 + x*y).as_poly(x, y)
>>> f.as_expr()
x**2 + x*y
>>> sin(x).as_expr()
sin(x)
"""
return self
def as_coefficient(self, expr):
"""
Extracts symbolic coefficient at the given expression. In
other words, this functions separates 'self' into the product
of 'expr' and 'expr'-free coefficient. If such separation
is not possible it will return None.
Examples
========
>>> from sympy import E, pi, sin, I, Poly
>>> from sympy.abc import x
>>> E.as_coefficient(E)
1
>>> (2*E).as_coefficient(E)
2
>>> (2*sin(E)*E).as_coefficient(E)
Two terms have E in them so a sum is returned. (If one were
desiring the coefficient of the term exactly matching E then
the constant from the returned expression could be selected.
Or, for greater precision, a method of Poly can be used to
indicate the desired term from which the coefficient is
desired.)
>>> (2*E + x*E).as_coefficient(E)
x + 2
>>> _.args[0] # just want the exact match
2
>>> p = Poly(2*E + x*E); p
Poly(x*E + 2*E, x, E, domain='ZZ')
>>> p.coeff_monomial(E)
2
>>> p.nth(0, 1)
2
Since the following cannot be written as a product containing
E as a factor, None is returned. (If the coefficient ``2*x`` is
desired then the ``coeff`` method should be used.)
>>> (2*E*x + x).as_coefficient(E)
>>> (2*E*x + x).coeff(E)
2*x
>>> (E*(x + 1) + x).as_coefficient(E)
>>> (2*pi*I).as_coefficient(pi*I)
2
>>> (2*I).as_coefficient(pi*I)
See Also
========
coeff: return sum of terms have a given factor
as_coeff_Add: separate the additive constant from an expression
as_coeff_Mul: separate the multiplicative constant from an expression
as_independent: separate x-dependent terms/factors from others
sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used
"""
r = self.extract_multiplicatively(expr)
if r and not r.has(expr):
return r
def as_independent(self, *deps, **hint):
"""
A mostly naive separation of a Mul or Add into arguments that are not
are dependent on deps. To obtain as complete a separation of variables
as possible, use a separation method first, e.g.:
* separatevars() to change Mul, Add and Pow (including exp) into Mul
* .expand(mul=True) to change Add or Mul into Add
* .expand(log=True) to change log expr into an Add
The only non-naive thing that is done here is to respect noncommutative
ordering of variables and to always return (0, 0) for `self` of zero
regardless of hints.
For nonzero `self`, the returned tuple (i, d) has the
following interpretation:
* i will has no variable that appears in deps
* d will either have terms that contain variables that are in deps, or
be equal to 0 (when self is an Add) or 1 (when self is a Mul)
* if self is an Add then self = i + d
* if self is a Mul then self = i*d
* otherwise (self, S.One) or (S.One, self) is returned.
To force the expression to be treated as an Add, use the hint as_Add=True
Examples
========
-- self is an Add
>>> from sympy import sin, cos, exp
>>> from sympy.abc import x, y, z
>>> (x + x*y).as_independent(x)
(0, x*y + x)
>>> (x + x*y).as_independent(y)
(x, x*y)
>>> (2*x*sin(x) + y + x + z).as_independent(x)
(y + z, 2*x*sin(x) + x)
>>> (2*x*sin(x) + y + x + z).as_independent(x, y)
(z, 2*x*sin(x) + x + y)
-- self is a Mul
>>> (x*sin(x)*cos(y)).as_independent(x)
(cos(y), x*sin(x))
non-commutative terms cannot always be separated out when self is a Mul
>>> from sympy import symbols
>>> n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
>>> (n1 + n1*n2).as_independent(n2)
(n1, n1*n2)
>>> (n2*n1 + n1*n2).as_independent(n2)
(0, n1*n2 + n2*n1)
>>> (n1*n2*n3).as_independent(n1)
(1, n1*n2*n3)
>>> (n1*n2*n3).as_independent(n2)
(n1, n2*n3)
>>> ((x-n1)*(x-y)).as_independent(x)
(1, (x - y)*(x - n1))
-- self is anything else:
>>> (sin(x)).as_independent(x)
(1, sin(x))
>>> (sin(x)).as_independent(y)
(sin(x), 1)
>>> exp(x+y).as_independent(x)
(1, exp(x + y))
-- force self to be treated as an Add:
>>> (3*x).as_independent(x, as_Add=True)
(0, 3*x)
-- force self to be treated as a Mul:
>>> (3+x).as_independent(x, as_Add=False)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=False)
(1, x - 3)
Note how the below differs from the above in making the
constant on the dep term positive.
>>> (y*(-3+x)).as_independent(x)
(y, x - 3)
-- use .as_independent() for true independence testing instead
of .has(). The former considers only symbols in the free
symbols while the latter considers all symbols
>>> from sympy import Integral
>>> I = Integral(x, (x, 1, 2))
>>> I.has(x)
True
>>> x in I.free_symbols
False
>>> I.as_independent(x) == (I, 1)
True
>>> (I + x).as_independent(x) == (I, x)
True
Note: when trying to get independent terms, a separation method
might need to be used first. In this case, it is important to keep
track of what you send to this routine so you know how to interpret
the returned values
>>> from sympy import separatevars, log
>>> separatevars(exp(x+y)).as_independent(x)
(exp(y), exp(x))
>>> (x + x*y).as_independent(y)
(x, x*y)
>>> separatevars(x + x*y).as_independent(y)
(x, y + 1)
>>> (x*(1 + y)).as_independent(y)
(x, y + 1)
>>> (x*(1 + y)).expand(mul=True).as_independent(y)
(x, x*y)
>>> a, b=symbols('a b', positive=True)
>>> (log(a*b).expand(log=True)).as_independent(b)
(log(a), log(b))
See Also
========
.separatevars(), .expand(log=True), sympy.core.add.Add.as_two_terms(),
sympy.core.mul.Mul.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
"""
from .symbol import Symbol
from .add import _unevaluated_Add
from .mul import _unevaluated_Mul
from sympy.utilities.iterables import sift
if self.is_zero:
return S.Zero, S.Zero
func = self.func
if hint.get('as_Add', isinstance(self, Add) ):
want = Add
else:
want = Mul
# sift out deps into symbolic and other and ignore
# all symbols but those that are in the free symbols
sym = set()
other = []
for d in deps:
if isinstance(d, Symbol): # Symbol.is_Symbol is True
sym.add(d)
else:
other.append(d)
def has(e):
"""return the standard has() if there are no literal symbols, else
check to see that symbol-deps are in the free symbols."""
has_other = e.has(*other)
if not sym:
return has_other
return has_other or e.has(*(e.free_symbols & sym))
if (want is not func or
func is not Add and func is not Mul):
if has(self):
return (want.identity, self)
else:
return (self, want.identity)
else:
if func is Add:
args = list(self.args)
else:
args, nc = self.args_cnc()
d = sift(args, lambda x: has(x))
depend = d[True]
indep = d[False]
if func is Add: # all terms were treated as commutative
return (Add(*indep), _unevaluated_Add(*depend))
else: # handle noncommutative by stopping at first dependent term
for i, n in enumerate(nc):
if has(n):
depend.extend(nc[i:])
break
indep.append(n)
return Mul(*indep), (
Mul(*depend, evaluate=False) if nc else
_unevaluated_Mul(*depend))
def as_real_imag(self, deep=True, **hints):
"""Performs complex expansion on 'self' and returns a tuple
containing collected both real and imaginary parts. This
method can't be confused with re() and im() functions,
which does not perform complex expansion at evaluation.
However it is possible to expand both re() and im()
functions and get exactly the same results as with
a single call to this function.
>>> from sympy import symbols, I
>>> x, y = symbols('x,y', real=True)
>>> (x + y*I).as_real_imag()
(x, y)
>>> from sympy.abc import z, w
>>> (z + w*I).as_real_imag()
(re(z) - im(w), re(w) + im(z))
"""
from sympy import im, re
if hints.get('ignore') == self:
return None
else:
return (re(self), im(self))
def as_powers_dict(self):
"""Return self as a dictionary of factors with each factor being
treated as a power. The keys are the bases of the factors and the
values, the corresponding exponents. The resulting dictionary should
be used with caution if the expression is a Mul and contains non-
commutative factors since the order that they appeared will be lost in
the dictionary.
See Also
========
as_ordered_factors: An alternative for noncommutative applications,
returning an ordered list of factors.
args_cnc: Similar to as_ordered_factors, but guarantees separation
of commutative and noncommutative factors.
"""
d = defaultdict(int)
d.update(dict([self.as_base_exp()]))
return d
def as_coefficients_dict(self):
"""Return a dictionary mapping terms to their Rational coefficient.
Since the dictionary is a defaultdict, inquiries about terms which
were not present will return a coefficient of 0. If an expression is
not an Add it is considered to have a single term.
Examples
========
>>> from sympy.abc import a, x
>>> (3*x + a*x + 4).as_coefficients_dict()
{1: 4, x: 3, a*x: 1}
>>> _[a]
0
>>> (3*a*x).as_coefficients_dict()
{a*x: 3}
"""
c, m = self.as_coeff_Mul()
if not c.is_Rational:
c = S.One
m = self
d = defaultdict(int)
d.update({m: c})
return d
def as_base_exp(self):
# a -> b ** e
return self, S.One
def as_coeff_mul(self, *deps, **kwargs):
"""Return the tuple (c, args) where self is written as a Mul, ``m``.
c should be a Rational multiplied by any factors of the Mul that are
independent of deps.
args should be a tuple of all other factors of m; args is empty
if self is a Number or if self is independent of deps (when given).
This should be used when you don't know if self is a Mul or not but
you want to treat self as a Mul or if you want to process the
individual arguments of the tail of self as a Mul.
- if you know self is a Mul and want only the head, use self.args[0];
- if you don't want to process the arguments of the tail but need the
tail then use self.as_two_terms() which gives the head and tail;
- if you want to split self into an independent and dependent parts
use ``self.as_independent(*deps)``
>>> from sympy import S
>>> from sympy.abc import x, y
>>> (S(3)).as_coeff_mul()
(3, ())
>>> (3*x*y).as_coeff_mul()
(3, (x, y))
>>> (3*x*y).as_coeff_mul(x)
(3*y, (x,))
>>> (3*y).as_coeff_mul(x)
(3*y, ())
"""
if deps:
if not self.has(*deps):
return self, tuple()
return S.One, (self,)
def as_coeff_add(self, *deps):
"""Return the tuple (c, args) where self is written as an Add, ``a``.
c should be a Rational added to any terms of the Add that are
independent of deps.
args should be a tuple of all other terms of ``a``; args is empty
if self is a Number or if self is independent of deps (when given).
This should be used when you don't know if self is an Add or not but
you want to treat self as an Add or if you want to process the
individual arguments of the tail of self as an Add.
- if you know self is an Add and want only the head, use self.args[0];
- if you don't want to process the arguments of the tail but need the
tail then use self.as_two_terms() which gives the head and tail.
- if you want to split self into an independent and dependent parts
use ``self.as_independent(*deps)``
>>> from sympy import S
>>> from sympy.abc import x, y
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x).as_coeff_add()
(3, (x,))
>>> (3 + x + y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
"""
if deps:
if not self.has(*deps):
return self, tuple()
return S.Zero, (self,)
def primitive(self):
"""Return the positive Rational that can be extracted non-recursively
from every term of self (i.e., self is treated like an Add). This is
like the as_coeff_Mul() method but primitive always extracts a positive
Rational (never a negative or a Float).
Examples
========
>>> from sympy.abc import x
>>> (3*(x + 1)**2).primitive()
(3, (x + 1)**2)
>>> a = (6*x + 2); a.primitive()
(2, 3*x + 1)
>>> b = (x/2 + 3); b.primitive()
(1/2, x + 6)
>>> (a*b).primitive() == (1, a*b)
True
"""
if not self:
return S.One, S.Zero
c, r = self.as_coeff_Mul(rational=True)
if c.is_negative:
c, r = -c, -r
return c, r
def as_content_primitive(self, radical=False, clear=True):
"""This method should recursively remove a Rational from all arguments
and return that (content) and the new self (primitive). The content
should always be positive and ``Mul(*foo.as_content_primitive()) == foo``.
The primitive need not be in canonical form and should try to preserve
the underlying structure if possible (i.e. expand_mul should not be
applied to self).
Examples
========
>>> from sympy import sqrt
>>> from sympy.abc import x, y, z
>>> eq = 2 + 2*x + 2*y*(3 + 3*y)
The as_content_primitive function is recursive and retains structure:
>>> eq.as_content_primitive()
(2, x + 3*y*(y + 1) + 1)
Integer powers will have Rationals extracted from the base:
>>> ((2 + 6*x)**2).as_content_primitive()
(4, (3*x + 1)**2)
>>> ((2 + 6*x)**(2*y)).as_content_primitive()
(1, (2*(3*x + 1))**(2*y))
Terms may end up joining once their as_content_primitives are added:
>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
(11, x*(y + 1))
>>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
(9, x*(y + 1))
>>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive()
(1, 6.0*x*(y + 1) + 3*z*(y + 1))
>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive()
(121, x**2*(y + 1)**2)
>>> ((x*(1 + y) + 0.4*x*(3 + 3*y))**2).as_content_primitive()
(1, 4.84*x**2*(y + 1)**2)
Radical content can also be factored out of the primitive:
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
(2, sqrt(2)*(1 + 2*sqrt(5)))
If clear=False (default is True) then content will not be removed
from an Add if it can be distributed to leave one or more
terms with integer coefficients.
>>> (x/2 + y).as_content_primitive()
(1/2, x + 2*y)
>>> (x/2 + y).as_content_primitive(clear=False)
(1, x/2 + y)
"""
return S.One, self
def as_numer_denom(self):
""" expression -> a/b -> a, b
This is just a stub that should be defined by
an object's class methods to get anything else.
See Also
========
normal: return ``a/b`` instead of ``(a, b)``
"""
return self, S.One
def normal(self):
""" expression -> a/b
See Also
========
as_numer_denom: return ``(a, b)`` instead of ``a/b``
"""
from .mul import _unevaluated_Mul
n, d = self.as_numer_denom()
if d is S.One:
return n
if d.is_Number:
return _unevaluated_Mul(n, 1/d)
else:
return n/d
def extract_multiplicatively(self, c):
"""Return None if it's not possible to make self in the form
c * something in a nice way, i.e. preserving the properties
of arguments of self.
Examples
========
>>> from sympy import symbols, Rational
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_multiplicatively(x**2 * y)
x*y**2
>>> ((x*y)**3).extract_multiplicatively(x**4 * y)
>>> (2*x).extract_multiplicatively(2)
x
>>> (2*x).extract_multiplicatively(3)
>>> (Rational(1, 2)*x).extract_multiplicatively(3)
x/6
"""
from .add import _unevaluated_Add
c = sympify(c)
if self is S.NaN:
return None
if c is S.One:
return self
elif c == self:
return S.One
if c.is_Add:
cc, pc = c.primitive()
if cc is not S.One:
c = Mul(cc, pc, evaluate=False)
if c.is_Mul:
a, b = c.as_two_terms()
x = self.extract_multiplicatively(a)
if x is not None:
return x.extract_multiplicatively(b)
else:
return x
quotient = self / c
if self.is_Number:
if self is S.Infinity:
if c.is_positive:
return S.Infinity
elif self is S.NegativeInfinity:
if c.is_negative:
return S.Infinity
elif c.is_positive:
return S.NegativeInfinity
elif self is S.ComplexInfinity:
if not c.is_zero:
return S.ComplexInfinity
elif self.is_Integer:
if not quotient.is_Integer:
return None
elif self.is_positive and quotient.is_negative:
return None
else:
return quotient
elif self.is_Rational:
if not quotient.is_Rational:
return None
elif self.is_positive and quotient.is_negative:
return None
else:
return quotient
elif self.is_Float:
if not quotient.is_Float:
return None
elif self.is_positive and quotient.is_negative:
return None
else:
return quotient
elif self.is_NumberSymbol or self.is_Symbol or self is S.ImaginaryUnit:
if quotient.is_Mul and len(quotient.args) == 2:
if quotient.args[0].is_Integer and quotient.args[0].is_positive and quotient.args[1] == self:
return quotient
elif quotient.is_Integer and c.is_Number:
return quotient
elif self.is_Add:
cs, ps = self.primitive()
# assert cs >= 1
if c.is_Number and c is not S.NegativeOne:
# assert c != 1 (handled at top)
if cs is not S.One:
if c.is_negative:
xc = -(cs.extract_multiplicatively(-c))
else:
xc = cs.extract_multiplicatively(c)
if xc is not None:
return xc*ps # rely on 2-arg Mul to restore Add
return # |c| != 1 can only be extracted from cs
if c == ps:
return cs
# check args of ps
newargs = []
for arg in ps.args:
newarg = arg.extract_multiplicatively(c)
if newarg is None:
return # all or nothing
newargs.append(newarg)
if cs is not S.One:
args = [cs*t for t in newargs]
# args may be in different order
return _unevaluated_Add(*args)
else:
return Add._from_args(newargs)
elif self.is_Mul:
args = list(self.args)
for i, arg in enumerate(args):
newarg = arg.extract_multiplicatively(c)
if newarg is not None:
args[i] = newarg
return Mul(*args)
elif self.is_Pow:
if c.is_Pow and c.base == self.base:
new_exp = self.exp.extract_additively(c.exp)
if new_exp is not None:
return self.base ** (new_exp)
elif c == self.base:
new_exp = self.exp.extract_additively(1)
if new_exp is not None:
return self.base ** (new_exp)
def extract_additively(self, c):
"""Return self - c if it's possible to subtract c from self and
make all matching coefficients move towards zero, else return None.
Examples
========
>>> from sympy.abc import x, y
>>> e = 2*x + 3
>>> e.extract_additively(x + 1)
x + 2
>>> e.extract_additively(3*x)
>>> e.extract_additively(4)
>>> (y*(x + 1)).extract_additively(x + 1)
>>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1)
(x + 1)*(x + 2*y) + 3
Sometimes auto-expansion will return a less simplified result
than desired; gcd_terms might be used in such cases:
>>> from sympy import gcd_terms
>>> (4*x*(y + 1) + y).extract_additively(x)
4*x*(y + 1) + x*(4*y + 3) - x*(4*y + 4) + y
>>> gcd_terms(_)
x*(4*y + 3) + y
See Also
========
extract_multiplicatively
coeff
as_coefficient
"""
c = sympify(c)
if self is S.NaN:
return None
if c.is_zero:
return self
elif c == self:
return S.Zero
elif self == S.Zero:
return None
if self.is_Number:
if not c.is_Number:
return None
co = self
diff = co - c
# XXX should we match types? i.e should 3 - .1 succeed?
if (co > 0 and diff > 0 and diff < co or
co < 0 and diff < 0 and diff > co):
return diff
return None
if c.is_Number:
co, t = self.as_coeff_Add()
xa = co.extract_additively(c)
if xa is None:
return None
return xa + t
# handle the args[0].is_Number case separately
# since we will have trouble looking for the coeff of
# a number.
if c.is_Add and c.args[0].is_Number:
# whole term as a term factor
co = self.coeff(c)
xa0 = (co.extract_additively(1) or 0)*c
if xa0:
diff = self - co*c
return (xa0 + (diff.extract_additively(c) or diff)) or None
# term-wise
h, t = c.as_coeff_Add()
sh, st = self.as_coeff_Add()
xa = sh.extract_additively(h)
if xa is None:
return None
xa2 = st.extract_additively(t)
if xa2 is None:
return None
return xa + xa2
# whole term as a term factor
co = self.coeff(c)
xa0 = (co.extract_additively(1) or 0)*c
if xa0:
diff = self - co*c
return (xa0 + (diff.extract_additively(c) or diff)) or None
# term-wise
coeffs = []
for a in Add.make_args(c):
ac, at = a.as_coeff_Mul()
co = self.coeff(at)
if not co:
return None
coc, cot = co.as_coeff_Add()
xa = coc.extract_additively(ac)
if xa is None:
return None
self -= co*at
coeffs.append((cot + xa)*at)
coeffs.append(self)
return Add(*coeffs)
@property
def expr_free_symbols(self):
"""
Like ``free_symbols``, but returns the free symbols only if
they are contained in an expression node.
Examples
========
>>> from sympy.utilities.exceptions import SymPyDeprecationWarning
>>> import warnings
>>> warnings.simplefilter("ignore", SymPyDeprecationWarning)
>>> from sympy.abc import x, y
>>> (x + y).expr_free_symbols
{x, y}
If the expression is contained in a non-expression object, don't return
the free symbols. Compare:
>>> from sympy import Tuple
>>> t = Tuple(x + y)
>>> t.expr_free_symbols
set()
>>> t.free_symbols
{x, y}
"""
from sympy.utilities.exceptions import SymPyDeprecationWarning
SymPyDeprecationWarning(feature="expr_free_symbols method",
issue=21494,
deprecated_since_version="1.9").warn()
return {j for i in self.args for j in i.expr_free_symbols}
def could_extract_minus_sign(self):
"""Return True if self is not in a canonical form with respect
to its sign.
For most expressions, e, there will be a difference in e and -e.
When there is, True will be returned for one and False for the
other; False will be returned if there is no difference.
Examples
========
>>> from sympy.abc import x, y
>>> e = x - y
>>> {i.could_extract_minus_sign() for i in (e, -e)}
{False, True}
"""
negative_self = -self
if self == negative_self:
return False # e.g. zoo*x == -zoo*x
self_has_minus = (self.extract_multiplicatively(-1) is not None)
negative_self_has_minus = (
(negative_self).extract_multiplicatively(-1) is not None)
if self_has_minus != negative_self_has_minus:
return self_has_minus
else:
if self.is_Add:
# We choose the one with less arguments with minus signs
all_args = len(self.args)
negative_args = len([False for arg in self.args if arg.could_extract_minus_sign()])
positive_args = all_args - negative_args
if positive_args > negative_args:
return False
elif positive_args < negative_args:
return True
elif self.is_Mul:
# We choose the one with an odd number of minus signs
num, den = self.as_numer_denom()
args = Mul.make_args(num) + Mul.make_args(den)
arg_signs = [arg.could_extract_minus_sign() for arg in args]
negative_args = list(filter(None, arg_signs))
return len(negative_args) % 2 == 1
# As a last resort, we choose the one with greater value of .sort_key()
return bool(self.sort_key() < negative_self.sort_key())
def extract_branch_factor(self, allow_half=False):
"""
Try to write self as ``exp_polar(2*pi*I*n)*z`` in a nice way.
Return (z, n).
>>> from sympy import exp_polar, I, pi
>>> from sympy.abc import x, y
>>> exp_polar(I*pi).extract_branch_factor()
(exp_polar(I*pi), 0)
>>> exp_polar(2*I*pi).extract_branch_factor()
(1, 1)
>>> exp_polar(-pi*I).extract_branch_factor()
(exp_polar(I*pi), -1)
>>> exp_polar(3*pi*I + x).extract_branch_factor()
(exp_polar(x + I*pi), 1)
>>> (y*exp_polar(-5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor()
(y*exp_polar(2*pi*x), -1)
>>> exp_polar(-I*pi/2).extract_branch_factor()
(exp_polar(-I*pi/2), 0)
If allow_half is True, also extract exp_polar(I*pi):
>>> exp_polar(I*pi).extract_branch_factor(allow_half=True)
(1, 1/2)
>>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True)
(1, 1)
>>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True)
(1, 3/2)
>>> exp_polar(-I*pi).extract_branch_factor(allow_half=True)
(1, -1/2)
"""
from sympy import exp_polar, pi, I, ceiling, Add
n = S.Zero
res = S.One
args = Mul.make_args(self)
exps = []
for arg in args:
if isinstance(arg, exp_polar):
exps += [arg.exp]
else:
res *= arg
piimult = S.Zero
extras = []
while exps:
exp = exps.pop()
if exp.is_Add:
exps += exp.args
continue
if exp.is_Mul:
coeff = exp.as_coefficient(pi*I)
if coeff is not None:
piimult += coeff
continue
extras += [exp]
if piimult.is_number:
coeff = piimult
tail = ()
else:
coeff, tail = piimult.as_coeff_add(*piimult.free_symbols)
# round down to nearest multiple of 2
branchfact = ceiling(coeff/2 - S.Half)*2
n += branchfact/2
c = coeff - branchfact
if allow_half:
nc = c.extract_additively(1)
if nc is not None:
n += S.Half
c = nc
newexp = pi*I*Add(*((c, ) + tail)) + Add(*extras)
if newexp != 0:
res *= exp_polar(newexp)
return res, n
def _eval_is_polynomial(self, syms):
if self.free_symbols.intersection(syms) == set():
return True
return False
def is_polynomial(self, *syms):
r"""
Return True if self is a polynomial in syms and False otherwise.
This checks if self is an exact polynomial in syms. This function
returns False for expressions that are "polynomials" with symbolic
exponents. Thus, you should be able to apply polynomial algorithms to
expressions for which this returns True, and Poly(expr, \*syms) should
work if and only if expr.is_polynomial(\*syms) returns True. The
polynomial does not have to be in expanded form. If no symbols are
given, all free symbols in the expression will be used.
This is not part of the assumptions system. You cannot do
Symbol('z', polynomial=True).
Examples
========
>>> from sympy import Symbol
>>> x = Symbol('x')
>>> ((x**2 + 1)**4).is_polynomial(x)
True
>>> ((x**2 + 1)**4).is_polynomial()
True
>>> (2**x + 1).is_polynomial(x)
False
>>> n = Symbol('n', nonnegative=True, integer=True)
>>> (x**n + 1).is_polynomial(x)
False
This function does not attempt any nontrivial simplifications that may
result in an expression that does not appear to be a polynomial to
become one.
>>> from sympy import sqrt, factor, cancel
>>> y = Symbol('y', positive=True)
>>> a = sqrt(y**2 + 2*y + 1)
>>> a.is_polynomial(y)
False
>>> factor(a)
y + 1
>>> factor(a).is_polynomial(y)
True
>>> b = (y**2 + 2*y + 1)/(y + 1)
>>> b.is_polynomial(y)
False
>>> cancel(b)
y + 1
>>> cancel(b).is_polynomial(y)
True
See also .is_rational_function()
"""
if syms:
syms = set(map(sympify, syms))
else:
syms = self.free_symbols
if syms.intersection(self.free_symbols) == set():
# constant polynomial
return True
else:
return self._eval_is_polynomial(syms)
def _eval_is_rational_function(self, syms):
if self.free_symbols.intersection(syms) == set():
return True
return False
def is_rational_function(self, *syms):
"""
Test whether function is a ratio of two polynomials in the given
symbols, syms. When syms is not given, all free symbols will be used.
The rational function does not have to be in expanded or in any kind of
canonical form.
This function returns False for expressions that are "rational
functions" with symbolic exponents. Thus, you should be able to call
.as_numer_denom() and apply polynomial algorithms to the result for
expressions for which this returns True.
This is not part of the assumptions system. You cannot do
Symbol('z', rational_function=True).
Examples
========
>>> from sympy import Symbol, sin
>>> from sympy.abc import x, y
>>> (x/y).is_rational_function()
True
>>> (x**2).is_rational_function()
True
>>> (x/sin(y)).is_rational_function(y)
False
>>> n = Symbol('n', integer=True)
>>> (x**n + 1).is_rational_function(x)
False
This function does not attempt any nontrivial simplifications that may
result in an expression that does not appear to be a rational function
to become one.
>>> from sympy import sqrt, factor
>>> y = Symbol('y', positive=True)
>>> a = sqrt(y**2 + 2*y + 1)/y
>>> a.is_rational_function(y)
False
>>> factor(a)
(y + 1)/y
>>> factor(a).is_rational_function(y)
True
See also is_algebraic_expr().
"""
if self in [S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
return False
if syms:
syms = set(map(sympify, syms))
else:
syms = self.free_symbols
if syms.intersection(self.free_symbols) == set():
# constant rational function
return True
else:
return self._eval_is_rational_function(syms)
def _eval_is_meromorphic(self, x, a):
# Default implementation, return True for constants.
return None if self.has(x) else True
def is_meromorphic(self, x, a):
"""
This tests whether an expression is meromorphic as
a function of the given symbol ``x`` at the point ``a``.
This method is intended as a quick test that will return
None if no decision can be made without simplification or
more detailed analysis.
Examples
========
>>> from sympy import zoo, log, sin, sqrt
>>> from sympy.abc import x
>>> f = 1/x**2 + 1 - 2*x**3
>>> f.is_meromorphic(x, 0)
True
>>> f.is_meromorphic(x, 1)
True
>>> f.is_meromorphic(x, zoo)
True
>>> g = x**log(3)
>>> g.is_meromorphic(x, 0)
False
>>> g.is_meromorphic(x, 1)
True
>>> g.is_meromorphic(x, zoo)
False
>>> h = sin(1/x)*x**2
>>> h.is_meromorphic(x, 0)
False
>>> h.is_meromorphic(x, 1)
True
>>> h.is_meromorphic(x, zoo)
True
Multivalued functions are considered meromorphic when their
branches are meromorphic. Thus most functions are meromorphic
everywhere except at essential singularities and branch points.
In particular, they will be meromorphic also on branch cuts
except at their endpoints.
>>> log(x).is_meromorphic(x, -1)
True
>>> log(x).is_meromorphic(x, 0)
False
>>> sqrt(x).is_meromorphic(x, -1)
True
>>> sqrt(x).is_meromorphic(x, 0)
False
"""
if not x.is_symbol:
raise TypeError("{} should be of symbol type".format(x))
a = sympify(a)
return self._eval_is_meromorphic(x, a)
def _eval_is_algebraic_expr(self, syms):
if self.free_symbols.intersection(syms) == set():
return True
return False
def is_algebraic_expr(self, *syms):
"""
This tests whether a given expression is algebraic or not, in the
given symbols, syms. When syms is not given, all free symbols
will be used. The rational function does not have to be in expanded
or in any kind of canonical form.
This function returns False for expressions that are "algebraic
expressions" with symbolic exponents. This is a simple extension to the
is_rational_function, including rational exponentiation.
Examples
========
>>> from sympy import Symbol, sqrt
>>> x = Symbol('x', real=True)
>>> sqrt(1 + x).is_rational_function()
False
>>> sqrt(1 + x).is_algebraic_expr()
True
This function does not attempt any nontrivial simplifications that may
result in an expression that does not appear to be an algebraic
expression to become one.
>>> from sympy import exp, factor
>>> a = sqrt(exp(x)**2 + 2*exp(x) + 1)/(exp(x) + 1)
>>> a.is_algebraic_expr(x)
False
>>> factor(a).is_algebraic_expr()
True
See Also
========
is_rational_function()
References
==========
- https://en.wikipedia.org/wiki/Algebraic_expression
"""
if syms:
syms = set(map(sympify, syms))
else:
syms = self.free_symbols
if syms.intersection(self.free_symbols) == set():
# constant algebraic expression
return True
else:
return self._eval_is_algebraic_expr(syms)
###################################################################################
##################### SERIES, LEADING TERM, LIMIT, ORDER METHODS ##################
###################################################################################
def series(self, x=None, x0=0, n=6, dir="+", logx=None, cdir=0):
"""
Series expansion of "self" around ``x = x0`` yielding either terms of
the series one by one (the lazy series given when n=None), else
all the terms at once when n != None.
Returns the series expansion of "self" around the point ``x = x0``
with respect to ``x`` up to ``O((x - x0)**n, x, x0)`` (default n is 6).
If ``x=None`` and ``self`` is univariate, the univariate symbol will
be supplied, otherwise an error will be raised.
Parameters
==========
expr : Expression
The expression whose series is to be expanded.
x : Symbol
It is the variable of the expression to be calculated.
x0 : Value
The value around which ``x`` is calculated. Can be any value
from ``-oo`` to ``oo``.
n : Value
The number of terms upto which the series is to be expanded.
dir : String, optional
The series-expansion can be bi-directional. If ``dir="+"``,
then (x->x0+). If ``dir="-", then (x->x0-). For infinite
``x0`` (``oo`` or ``-oo``), the ``dir`` argument is determined
from the direction of the infinity (i.e., ``dir="-"`` for
``oo``).
logx : optional
It is used to replace any log(x) in the returned series with a
symbolic value rather than evaluating the actual value.
cdir : optional
It stands for complex direction, and indicates the direction
from which the expansion needs to be evaluated.
Examples
========
>>> from sympy import cos, exp, tan
>>> from sympy.abc import x, y
>>> cos(x).series()
1 - x**2/2 + x**4/24 + O(x**6)
>>> cos(x).series(n=4)
1 - x**2/2 + O(x**4)
>>> cos(x).series(x, x0=1, n=2)
cos(1) - (x - 1)*sin(1) + O((x - 1)**2, (x, 1))
>>> e = cos(x + exp(y))
>>> e.series(y, n=2)
cos(x + 1) - y*sin(x + 1) + O(y**2)
>>> e.series(x, n=2)
cos(exp(y)) - x*sin(exp(y)) + O(x**2)
If ``n=None`` then a generator of the series terms will be returned.
>>> term=cos(x).series(n=None)
>>> [next(term) for i in range(2)]
[1, -x**2/2]
For ``dir=+`` (default) the series is calculated from the right and
for ``dir=-`` the series from the left. For smooth functions this
flag will not alter the results.
>>> abs(x).series(dir="+")
x
>>> abs(x).series(dir="-")
-x
>>> f = tan(x)
>>> f.series(x, 2, 6, "+")
tan(2) + (1 + tan(2)**2)*(x - 2) + (x - 2)**2*(tan(2)**3 + tan(2)) +
(x - 2)**3*(1/3 + 4*tan(2)**2/3 + tan(2)**4) + (x - 2)**4*(tan(2)**5 +
5*tan(2)**3/3 + 2*tan(2)/3) + (x - 2)**5*(2/15 + 17*tan(2)**2/15 +
2*tan(2)**4 + tan(2)**6) + O((x - 2)**6, (x, 2))
>>> f.series(x, 2, 3, "-")
tan(2) + (2 - x)*(-tan(2)**2 - 1) + (2 - x)**2*(tan(2)**3 + tan(2))
+ O((x - 2)**3, (x, 2))
Returns
=======
Expr : Expression
Series expansion of the expression about x0
Raises
======
TypeError
If "n" and "x0" are infinity objects
PoleError
If "x0" is an infinity object
"""
from sympy import collect, Dummy, Order, Rational, Symbol, ceiling
if x is None:
syms = self.free_symbols
if not syms:
return self
elif len(syms) > 1:
raise ValueError('x must be given for multivariate functions.')
x = syms.pop()
if isinstance(x, Symbol):
dep = x in self.free_symbols
else:
d = Dummy()
dep = d in self.xreplace({x: d}).free_symbols
if not dep:
if n is None:
return (s for s in [self])
else:
return self
if len(dir) != 1 or dir not in '+-':
raise ValueError("Dir must be '+' or '-'")
if x0 in [S.Infinity, S.NegativeInfinity]:
sgn = 1 if x0 is S.Infinity else -1
s = self.subs(x, sgn/x).series(x, n=n, dir='+', cdir=cdir)
if n is None:
return (si.subs(x, sgn/x) for si in s)
return s.subs(x, sgn/x)
# use rep to shift origin to x0 and change sign (if dir is negative)
# and undo the process with rep2
if x0 or dir == '-':
if dir == '-':
rep = -x + x0
rep2 = -x
rep2b = x0
else:
rep = x + x0
rep2 = x
rep2b = -x0
s = self.subs(x, rep).series(x, x0=0, n=n, dir='+', logx=logx, cdir=cdir)
if n is None: # lseries...
return (si.subs(x, rep2 + rep2b) for si in s)
return s.subs(x, rep2 + rep2b)
# from here on it's x0=0 and dir='+' handling
if x.is_positive is x.is_negative is None or x.is_Symbol is not True:
# replace x with an x that has a positive assumption
xpos = Dummy('x', positive=True, finite=True)
rv = self.subs(x, xpos).series(xpos, x0, n, dir, logx=logx, cdir=cdir)
if n is None:
return (s.subs(xpos, x) for s in rv)
else:
return rv.subs(xpos, x)
if n is not None: # nseries handling
s1 = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
o = s1.getO() or S.Zero
if o:
# make sure the requested order is returned
ngot = o.getn()
if ngot > n:
# leave o in its current form (e.g. with x*log(x)) so
# it eats terms properly, then replace it below
if n != 0:
s1 += o.subs(x, x**Rational(n, ngot))
else:
s1 += Order(1, x)
elif ngot < n:
# increase the requested number of terms to get the desired
# number keep increasing (up to 9) until the received order
# is different than the original order and then predict how
# many additional terms are needed
for more in range(1, 9):
s1 = self._eval_nseries(x, n=n + more, logx=logx, cdir=cdir)
newn = s1.getn()
if newn != ngot:
ndo = n + ceiling((n - ngot)*more/(newn - ngot))
s1 = self._eval_nseries(x, n=ndo, logx=logx, cdir=cdir)
while s1.getn() < n:
s1 = self._eval_nseries(x, n=ndo, logx=logx, cdir=cdir)
ndo += 1
break
else:
raise ValueError('Could not calculate %s terms for %s'
% (str(n), self))
s1 += Order(x**n, x)
o = s1.getO()
s1 = s1.removeO()
elif s1.has(Order):
# asymptotic expansion
return s1
else:
o = Order(x**n, x)
s1done = s1.doit()
if (s1done + o).removeO() == s1done:
o = S.Zero
try:
return collect(s1, x) + o
except NotImplementedError:
return s1 + o
else: # lseries handling
def yield_lseries(s):
"""Return terms of lseries one at a time."""
for si in s:
if not si.is_Add:
yield si
continue
# yield terms 1 at a time if possible
# by increasing order until all the
# terms have been returned
yielded = 0
o = Order(si, x)*x
ndid = 0
ndo = len(si.args)
while 1:
do = (si - yielded + o).removeO()
o *= x
if not do or do.is_Order:
continue
if do.is_Add:
ndid += len(do.args)
else:
ndid += 1
yield do
if ndid == ndo:
break
yielded += do
return yield_lseries(self.removeO()._eval_lseries(x, logx=logx, cdir=cdir))
def aseries(self, x=None, n=6, bound=0, hir=False):
"""Asymptotic Series expansion of self.
This is equivalent to ``self.series(x, oo, n)``.
Parameters
==========
self : Expression
The expression whose series is to be expanded.
x : Symbol
It is the variable of the expression to be calculated.
n : Value
The number of terms upto which the series is to be expanded.
hir : Boolean
Set this parameter to be True to produce hierarchical series.
It stops the recursion at an early level and may provide nicer
and more useful results.
bound : Value, Integer
Use the ``bound`` parameter to give limit on rewriting
coefficients in its normalised form.
Examples
========
>>> from sympy import sin, exp
>>> from sympy.abc import x
>>> e = sin(1/x + exp(-x)) - sin(1/x)
>>> e.aseries(x)
(1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
>>> e.aseries(x, n=3, hir=True)
-exp(-2*x)*sin(1/x)/2 + exp(-x)*cos(1/x) + O(exp(-3*x), (x, oo))
>>> e = exp(exp(x)/(1 - 1/x))
>>> e.aseries(x)
exp(exp(x)/(1 - 1/x))
>>> e.aseries(x, bound=3)
exp(exp(x)/x**2)*exp(exp(x)/x)*exp(-exp(x) + exp(x)/(1 - 1/x) - exp(x)/x - exp(x)/x**2)*exp(exp(x))
Returns
=======
Expr
Asymptotic series expansion of the expression.
Notes
=====
This algorithm is directly induced from the limit computational algorithm provided by Gruntz.
It majorly uses the mrv and rewrite sub-routines. The overall idea of this algorithm is first
to look for the most rapidly varying subexpression w of a given expression f and then expands f
in a series in w. Then same thing is recursively done on the leading coefficient
till we get constant coefficients.
If the most rapidly varying subexpression of a given expression f is f itself,
the algorithm tries to find a normalised representation of the mrv set and rewrites f
using this normalised representation.
If the expansion contains an order term, it will be either ``O(x ** (-n))`` or ``O(w ** (-n))``
where ``w`` belongs to the most rapidly varying expression of ``self``.
References
==========
.. [1] A New Algorithm for Computing Asymptotic Series - Dominik Gruntz
.. [2] Gruntz thesis - p90
.. [3] http://en.wikipedia.org/wiki/Asymptotic_expansion
See Also
========
Expr.aseries: See the docstring of this function for complete details of this wrapper.
"""
from sympy import Order, Dummy
from sympy.functions import exp, log
from sympy.series.gruntz import mrv, rewrite
if x.is_positive is x.is_negative is None:
xpos = Dummy('x', positive=True)
return self.subs(x, xpos).aseries(xpos, n, bound, hir).subs(xpos, x)
om, exps = mrv(self, x)
# We move one level up by replacing `x` by `exp(x)`, and then
# computing the asymptotic series for f(exp(x)). Then asymptotic series
# can be obtained by moving one-step back, by replacing x by ln(x).
if x in om:
s = self.subs(x, exp(x)).aseries(x, n, bound, hir).subs(x, log(x))
if s.getO():
return s + Order(1/x**n, (x, S.Infinity))
return s
k = Dummy('k', positive=True)
# f is rewritten in terms of omega
func, logw = rewrite(exps, om, x, k)
if self in om:
if bound <= 0:
return self
s = (self.exp).aseries(x, n, bound=bound)
s = s.func(*[t.removeO() for t in s.args])
res = exp(s.subs(x, 1/x).as_leading_term(x).subs(x, 1/x))
func = exp(self.args[0] - res.args[0]) / k
logw = log(1/res)
s = func.series(k, 0, n)
# Hierarchical series
if hir:
return s.subs(k, exp(logw))
o = s.getO()
terms = sorted(Add.make_args(s.removeO()), key=lambda i: int(i.as_coeff_exponent(k)[1]))
s = S.Zero
has_ord = False
# Then we recursively expand these coefficients one by one into
# their asymptotic series in terms of their most rapidly varying subexpressions.
for t in terms:
coeff, expo = t.as_coeff_exponent(k)
if coeff.has(x):
# Recursive step
snew = coeff.aseries(x, n, bound=bound-1)
if has_ord and snew.getO():
break
elif snew.getO():
has_ord = True
s += (snew * k**expo)
else:
s += t
if not o or has_ord:
return s.subs(k, exp(logw))
return (s + o).subs(k, exp(logw))
def taylor_term(self, n, x, *previous_terms):
"""General method for the taylor term.
This method is slow, because it differentiates n-times. Subclasses can
redefine it to make it faster by using the "previous_terms".
"""
from sympy import Dummy, factorial
x = sympify(x)
_x = Dummy('x')
return self.subs(x, _x).diff(_x, n).subs(_x, x).subs(x, 0) * x**n / factorial(n)
def lseries(self, x=None, x0=0, dir='+', logx=None, cdir=0):
"""
Wrapper for series yielding an iterator of the terms of the series.
Note: an infinite series will yield an infinite iterator. The following,
for exaxmple, will never terminate. It will just keep printing terms
of the sin(x) series::
for term in sin(x).lseries(x):
print term
The advantage of lseries() over nseries() is that many times you are
just interested in the next term in the series (i.e. the first term for
example), but you don't know how many you should ask for in nseries()
using the "n" parameter.
See also nseries().
"""
return self.series(x, x0, n=None, dir=dir, logx=logx, cdir=cdir)
def _eval_lseries(self, x, logx=None, cdir=0):
# default implementation of lseries is using nseries(), and adaptively
# increasing the "n". As you can see, it is not very efficient, because
# we are calculating the series over and over again. Subclasses should
# override this method and implement much more efficient yielding of
# terms.
n = 0
series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
while series.is_Order:
n += 1
series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
e = series.removeO()
yield e
if e is S.Zero:
return
while 1:
while 1:
n += 1
series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir).removeO()
if e != series:
break
if (series - self).cancel() is S.Zero:
return
yield series - e
e = series
def nseries(self, x=None, x0=0, n=6, dir='+', logx=None, cdir=0):
"""
Wrapper to _eval_nseries if assumptions allow, else to series.
If x is given, x0 is 0, dir='+', and self has x, then _eval_nseries is
called. This calculates "n" terms in the innermost expressions and
then builds up the final series just by "cross-multiplying" everything
out.
The optional ``logx`` parameter can be used to replace any log(x) in the
returned series with a symbolic value to avoid evaluating log(x) at 0. A
symbol to use in place of log(x) should be provided.
Advantage -- it's fast, because we don't have to determine how many
terms we need to calculate in advance.
Disadvantage -- you may end up with less terms than you may have
expected, but the O(x**n) term appended will always be correct and
so the result, though perhaps shorter, will also be correct.
If any of those assumptions is not met, this is treated like a
wrapper to series which will try harder to return the correct
number of terms.
See also lseries().
Examples
========
>>> from sympy import sin, log, Symbol
>>> from sympy.abc import x, y
>>> sin(x).nseries(x, 0, 6)
x - x**3/6 + x**5/120 + O(x**6)
>>> log(x+1).nseries(x, 0, 5)
x - x**2/2 + x**3/3 - x**4/4 + O(x**5)
Handling of the ``logx`` parameter --- in the following example the
expansion fails since ``sin`` does not have an asymptotic expansion
at -oo (the limit of log(x) as x approaches 0):
>>> e = sin(log(x))
>>> e.nseries(x, 0, 6)
Traceback (most recent call last):
...
PoleError: ...
...
>>> logx = Symbol('logx')
>>> e.nseries(x, 0, 6, logx=logx)
sin(logx)
In the following example, the expansion works but gives only an Order term
unless the ``logx`` parameter is used:
>>> e = x**y
>>> e.nseries(x, 0, 2)
O(log(x)**2)
>>> e.nseries(x, 0, 2, logx=logx)
exp(logx*y)
"""
if x and not x in self.free_symbols:
return self
if x is None or x0 or dir != '+': # {see XPOS above} or (x.is_positive == x.is_negative == None):
return self.series(x, x0, n, dir, cdir=cdir)
else:
return self._eval_nseries(x, n=n, logx=logx, cdir=cdir)
def _eval_nseries(self, x, n, logx, cdir):
"""
Return terms of series for self up to O(x**n) at x=0
from the positive direction.
This is a method that should be overridden in subclasses. Users should
never call this method directly (use .nseries() instead), so you don't
have to write docstrings for _eval_nseries().
"""
from sympy.utilities.misc import filldedent
raise NotImplementedError(filldedent("""
The _eval_nseries method should be added to
%s to give terms up to O(x**n) at x=0
from the positive direction so it is available when
nseries calls it.""" % self.func)
)
def limit(self, x, xlim, dir='+'):
""" Compute limit x->xlim.
"""
from sympy.series.limits import limit
return limit(self, x, xlim, dir)
def compute_leading_term(self, x, logx=None):
"""
as_leading_term is only allowed for results of .series()
This is a wrapper to compute a series first.
"""
from sympy import Dummy, log, Piecewise, piecewise_fold
from sympy.series.gruntz import calculate_series
if self.has(Piecewise):
expr = piecewise_fold(self)
else:
expr = self
if self.removeO() == 0:
return self
if logx is None:
d = Dummy('logx')
s = calculate_series(expr, x, d).subs(d, log(x))
else:
s = calculate_series(expr, x, logx)
return s.as_leading_term(x)
@cacheit
def as_leading_term(self, *symbols, cdir=0):
"""
Returns the leading (nonzero) term of the series expansion of self.
The _eval_as_leading_term routines are used to do this, and they must
always return a non-zero value.
Examples
========
>>> from sympy.abc import x
>>> (1 + x + x**2).as_leading_term(x)
1
>>> (1/x**2 + x + x**2).as_leading_term(x)
x**(-2)
"""
from sympy import powsimp
if len(symbols) > 1:
c = self
for x in symbols:
c = c.as_leading_term(x, cdir=cdir)
return c
elif not symbols:
return self
x = sympify(symbols[0])
if not x.is_symbol:
raise ValueError('expecting a Symbol but got %s' % x)
if x not in self.free_symbols:
return self
obj = self._eval_as_leading_term(x, cdir=cdir)
if obj is not None:
return powsimp(obj, deep=True, combine='exp')
raise NotImplementedError('as_leading_term(%s, %s)' % (self, x))
def _eval_as_leading_term(self, x, cdir=0):
return self
def as_coeff_exponent(self, x):
""" ``c*x**e -> c,e`` where x can be any symbolic expression.
"""
from sympy import collect
s = collect(self, x)
c, p = s.as_coeff_mul(x)
if len(p) == 1:
b, e = p[0].as_base_exp()
if b == x:
return c, e
return s, S.Zero
def leadterm(self, x, cdir=0):
"""
Returns the leading term a*x**b as a tuple (a, b).
Examples
========
>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)
"""
from sympy import Dummy, log
l = self.as_leading_term(x, cdir=cdir)
d = Dummy('logx')
if l.has(log(x)):
l = l.subs(log(x), d)
c, e = l.as_coeff_exponent(x)
if x in c.free_symbols:
from sympy.utilities.misc import filldedent
raise ValueError(filldedent("""
cannot compute leadterm(%s, %s). The coefficient
should have been free of %s but got %s""" % (self, x, x, c)))
c = c.subs(d, log(x))
return c, e
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product. """
return S.One, self
def as_coeff_Add(self, rational=False):
"""Efficiently extract the coefficient of a summation. """
return S.Zero, self
def fps(self, x=None, x0=0, dir=1, hyper=True, order=4, rational=True,
full=False):
"""
Compute formal power power series of self.
See the docstring of the :func:`fps` function in sympy.series.formal for
more information.
"""
from sympy.series.formal import fps
return fps(self, x, x0, dir, hyper, order, rational, full)
def fourier_series(self, limits=None):
"""Compute fourier sine/cosine series of self.
See the docstring of the :func:`fourier_series` in sympy.series.fourier
for more information.
"""
from sympy.series.fourier import fourier_series
return fourier_series(self, limits)
###################################################################################
##################### DERIVATIVE, INTEGRAL, FUNCTIONAL METHODS ####################
###################################################################################
def diff(self, *symbols, **assumptions):
assumptions.setdefault("evaluate", True)
return _derivative_dispatch(self, *symbols, **assumptions)
###########################################################################
###################### EXPRESSION EXPANSION METHODS #######################
###########################################################################
# Relevant subclasses should override _eval_expand_hint() methods. See
# the docstring of expand() for more info.
def _eval_expand_complex(self, **hints):
real, imag = self.as_real_imag(**hints)
return real + S.ImaginaryUnit*imag
@staticmethod
def _expand_hint(expr, hint, deep=True, **hints):
"""
Helper for ``expand()``. Recursively calls ``expr._eval_expand_hint()``.
Returns ``(expr, hit)``, where expr is the (possibly) expanded
``expr`` and ``hit`` is ``True`` if ``expr`` was truly expanded and
``False`` otherwise.
"""
hit = False
# XXX: Hack to support non-Basic args
# |
# V
if deep and getattr(expr, 'args', ()) and not expr.is_Atom:
sargs = []
for arg in expr.args:
arg, arghit = Expr._expand_hint(arg, hint, **hints)
hit |= arghit
sargs.append(arg)
if hit:
expr = expr.func(*sargs)
if hasattr(expr, hint):
newexpr = getattr(expr, hint)(**hints)
if newexpr != expr:
return (newexpr, True)
return (expr, hit)
@cacheit
def expand(self, deep=True, modulus=None, power_base=True, power_exp=True,
mul=True, log=True, multinomial=True, basic=True, **hints):
"""
Expand an expression using hints.
See the docstring of the expand() function in sympy.core.function for
more information.
"""
from sympy.simplify.radsimp import fraction
hints.update(power_base=power_base, power_exp=power_exp, mul=mul,
log=log, multinomial=multinomial, basic=basic)
expr = self
if hints.pop('frac', False):
n, d = [a.expand(deep=deep, modulus=modulus, **hints)
for a in fraction(self)]
return n/d
elif hints.pop('denom', False):
n, d = fraction(self)
return n/d.expand(deep=deep, modulus=modulus, **hints)
elif hints.pop('numer', False):
n, d = fraction(self)
return n.expand(deep=deep, modulus=modulus, **hints)/d
# Although the hints are sorted here, an earlier hint may get applied
# at a given node in the expression tree before another because of how
# the hints are applied. e.g. expand(log(x*(y + z))) -> log(x*y +
# x*z) because while applying log at the top level, log and mul are
# applied at the deeper level in the tree so that when the log at the
# upper level gets applied, the mul has already been applied at the
# lower level.
# Additionally, because hints are only applied once, the expression
# may not be expanded all the way. For example, if mul is applied
# before multinomial, x*(x + 1)**2 won't be expanded all the way. For
# now, we just use a special case to make multinomial run before mul,
# so that at least polynomials will be expanded all the way. In the
# future, smarter heuristics should be applied.
# TODO: Smarter heuristics
def _expand_hint_key(hint):
"""Make multinomial come before mul"""
if hint == 'mul':
return 'mulz'
return hint
for hint in sorted(hints.keys(), key=_expand_hint_key):
use_hint = hints[hint]
if use_hint:
hint = '_eval_expand_' + hint
expr, hit = Expr._expand_hint(expr, hint, deep=deep, **hints)
while True:
was = expr
if hints.get('multinomial', False):
expr, _ = Expr._expand_hint(
expr, '_eval_expand_multinomial', deep=deep, **hints)
if hints.get('mul', False):
expr, _ = Expr._expand_hint(
expr, '_eval_expand_mul', deep=deep, **hints)
if hints.get('log', False):
expr, _ = Expr._expand_hint(
expr, '_eval_expand_log', deep=deep, **hints)
if expr == was:
break
if modulus is not None:
modulus = sympify(modulus)
if not modulus.is_Integer or modulus <= 0:
raise ValueError(
"modulus must be a positive integer, got %s" % modulus)
terms = []
for term in Add.make_args(expr):
coeff, tail = term.as_coeff_Mul(rational=True)
coeff %= modulus
if coeff:
terms.append(coeff*tail)
expr = Add(*terms)
return expr
###########################################################################
################### GLOBAL ACTION VERB WRAPPER METHODS ####################
###########################################################################
def integrate(self, *args, **kwargs):
"""See the integrate function in sympy.integrals"""
from sympy.integrals import integrate
return integrate(self, *args, **kwargs)
def nsimplify(self, constants=[], tolerance=None, full=False):
"""See the nsimplify function in sympy.simplify"""
from sympy.simplify import nsimplify
return nsimplify(self, constants, tolerance, full)
def separate(self, deep=False, force=False):
"""See the separate function in sympy.simplify"""
from sympy.core.function import expand_power_base
return expand_power_base(self, deep=deep, force=force)
def collect(self, syms, func=None, evaluate=True, exact=False, distribute_order_term=True):
"""See the collect function in sympy.simplify"""
from sympy.simplify import collect
return collect(self, syms, func, evaluate, exact, distribute_order_term)
def together(self, *args, **kwargs):
"""See the together function in sympy.polys"""
from sympy.polys import together
return together(self, *args, **kwargs)
def apart(self, x=None, **args):
"""See the apart function in sympy.polys"""
from sympy.polys import apart
return apart(self, x, **args)
def ratsimp(self):
"""See the ratsimp function in sympy.simplify"""
from sympy.simplify import ratsimp
return ratsimp(self)
def trigsimp(self, **args):
"""See the trigsimp function in sympy.simplify"""
from sympy.simplify import trigsimp
return trigsimp(self, **args)
def radsimp(self, **kwargs):
"""See the radsimp function in sympy.simplify"""
from sympy.simplify import radsimp
return radsimp(self, **kwargs)
def powsimp(self, *args, **kwargs):
"""See the powsimp function in sympy.simplify"""
from sympy.simplify import powsimp
return powsimp(self, *args, **kwargs)
def combsimp(self):
"""See the combsimp function in sympy.simplify"""
from sympy.simplify import combsimp
return combsimp(self)
def gammasimp(self):
"""See the gammasimp function in sympy.simplify"""
from sympy.simplify import gammasimp
return gammasimp(self)
def factor(self, *gens, **args):
"""See the factor() function in sympy.polys.polytools"""
from sympy.polys import factor
return factor(self, *gens, **args)
def cancel(self, *gens, **args):
"""See the cancel function in sympy.polys"""
from sympy.polys import cancel
return cancel(self, *gens, **args)
def invert(self, g, *gens, **args):
"""Return the multiplicative inverse of ``self`` mod ``g``
where ``self`` (and ``g``) may be symbolic expressions).
See Also
========
sympy.core.numbers.mod_inverse, sympy.polys.polytools.invert
"""
from sympy.polys.polytools import invert
from sympy.core.numbers import mod_inverse
if self.is_number and getattr(g, 'is_number', True):
return mod_inverse(self, g)
return invert(self, g, *gens, **args)
def round(self, n=None):
"""Return x rounded to the given decimal place.
If a complex number would results, apply round to the real
and imaginary components of the number.
Examples
========
>>> from sympy import pi, E, I, S, Number
>>> pi.round()
3
>>> pi.round(2)
3.14
>>> (2*pi + E*I).round()
6 + 3*I
The round method has a chopping effect:
>>> (2*pi + I/10).round()
6
>>> (pi/10 + 2*I).round()
2*I
>>> (pi/10 + E*I).round(2)
0.31 + 2.72*I
Notes
=====
The Python ``round`` function uses the SymPy ``round`` method so it
will always return a SymPy number (not a Python float or int):
>>> isinstance(round(S(123), -2), Number)
True
"""
from sympy.core.numbers import Float
x = self
if not x.is_number:
raise TypeError("can't round symbolic expression")
if not x.is_Atom:
if not pure_complex(x.n(2), or_real=True):
raise TypeError(
'Expected a number but got %s:' % func_name(x))
elif x in (S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity):
return x
if x.is_extended_real is False:
r, i = x.as_real_imag()
return r.round(n) + S.ImaginaryUnit*i.round(n)
if not x:
return S.Zero if n is None else x
p = as_int(n or 0)
if x.is_Integer:
return Integer(round(int(x), p))
digits_to_decimal = _mag(x) # _mag(12) = 2, _mag(.012) = -1
allow = digits_to_decimal + p
precs = [f._prec for f in x.atoms(Float)]
dps = prec_to_dps(max(precs)) if precs else None
if dps is None:
# assume everything is exact so use the Python
# float default or whatever was requested
dps = max(15, allow)
else:
allow = min(allow, dps)
# this will shift all digits to right of decimal
# and give us dps to work with as an int
shift = -digits_to_decimal + dps
extra = 1 # how far we look past known digits
# NOTE
# mpmath will calculate the binary representation to
# an arbitrary number of digits but we must base our
# answer on a finite number of those digits, e.g.
# .575 2589569785738035/2**52 in binary.
# mpmath shows us that the first 18 digits are
# >>> Float(.575).n(18)
# 0.574999999999999956
# The default precision is 15 digits and if we ask
# for 15 we get
# >>> Float(.575).n(15)
# 0.575000000000000
# mpmath handles rounding at the 15th digit. But we
# need to be careful since the user might be asking
# for rounding at the last digit and our semantics
# are to round toward the even final digit when there
# is a tie. So the extra digit will be used to make
# that decision. In this case, the value is the same
# to 15 digits:
# >>> Float(.575).n(16)
# 0.5750000000000000
# Now converting this to the 15 known digits gives
# 575000000000000.0
# which rounds to integer
# 5750000000000000
# And now we can round to the desired digt, e.g. at
# the second from the left and we get
# 5800000000000000
# and rescaling that gives
# 0.58
# as the final result.
# If the value is made slightly less than 0.575 we might
# still obtain the same value:
# >>> Float(.575-1e-16).n(16)*10**15
# 574999999999999.8
# What 15 digits best represents the known digits (which are
# to the left of the decimal? 5750000000000000, the same as
# before. The only way we will round down (in this case) is
# if we declared that we had more than 15 digits of precision.
# For example, if we use 16 digits of precision, the integer
# we deal with is
# >>> Float(.575-1e-16).n(17)*10**16
# 5749999999999998.4
# and this now rounds to 5749999999999998 and (if we round to
# the 2nd digit from the left) we get 5700000000000000.
#
xf = x.n(dps + extra)*Pow(10, shift)
xi = Integer(xf)
# use the last digit to select the value of xi
# nearest to x before rounding at the desired digit
sign = 1 if x > 0 else -1
dif2 = sign*(xf - xi).n(extra)
if dif2 < 0:
raise NotImplementedError(
'not expecting int(x) to round away from 0')
if dif2 > .5:
xi += sign # round away from 0
elif dif2 == .5:
xi += sign if xi%2 else -sign # round toward even
# shift p to the new position
ip = p - shift
# let Python handle the int rounding then rescale
xr = round(xi.p, ip)
# restore scale
rv = Rational(xr, Pow(10, shift))
# return Float or Integer
if rv.is_Integer:
if n is None: # the single-arg case
return rv
# use str or else it won't be a float
return Float(str(rv), dps) # keep same precision
else:
if not allow and rv > self:
allow += 1
return Float(rv, allow)
__round__ = round
def _eval_derivative_matrix_lines(self, x):
from sympy.matrices.expressions.matexpr import _LeftRightArgs
return [_LeftRightArgs([S.One, S.One], higher=self._eval_derivative(x))]
class AtomicExpr(Atom, Expr):
"""
A parent class for object which are both atoms and Exprs.
For example: Symbol, Number, Rational, Integer, ...
But not: Add, Mul, Pow, ...
"""
is_number = False
is_Atom = True
__slots__ = ()
def _eval_derivative(self, s):
if self == s:
return S.One
return S.Zero
def _eval_derivative_n_times(self, s, n):
from sympy import Piecewise, Eq
from sympy import Tuple, MatrixExpr
from sympy.matrices.common import MatrixCommon
if isinstance(s, (MatrixCommon, Tuple, Iterable, MatrixExpr)):
return super()._eval_derivative_n_times(s, n)
if self == s:
return Piecewise((self, Eq(n, 0)), (1, Eq(n, 1)), (0, True))
else:
return Piecewise((self, Eq(n, 0)), (0, True))
def _eval_is_polynomial(self, syms):
return True
def _eval_is_rational_function(self, syms):
return True
def _eval_is_meromorphic(self, x, a):
from sympy.calculus.util import AccumBounds
return (not self.is_Number or self.is_finite) and not isinstance(self, AccumBounds)
def _eval_is_algebraic_expr(self, syms):
return True
def _eval_nseries(self, x, n, logx, cdir=0):
return self
@property
def expr_free_symbols(self):
from sympy.utilities.exceptions import SymPyDeprecationWarning
SymPyDeprecationWarning(feature="expr_free_symbols method",
issue=21494,
deprecated_since_version="1.9").warn()
return {self}
def _mag(x):
"""Return integer ``i`` such that .1 <= x/10**i < 1
Examples
========
>>> from sympy.core.expr import _mag
>>> from sympy import Float
>>> _mag(Float(.1))
0
>>> _mag(Float(.01))
-1
>>> _mag(Float(1234))
4
"""
from math import log10, ceil, log
from sympy import Float
xpos = abs(x.n())
if not xpos:
return S.Zero
try:
mag_first_dig = int(ceil(log10(xpos)))
except (ValueError, OverflowError):
mag_first_dig = int(ceil(Float(mpf_log(xpos._mpf_, 53))/log(10)))
# check that we aren't off by 1
if (xpos/10**mag_first_dig) >= 1:
assert 1 <= (xpos/10**mag_first_dig) < 10
mag_first_dig += 1
return mag_first_dig
class UnevaluatedExpr(Expr):
"""
Expression that is not evaluated unless released.
Examples
========
>>> from sympy import UnevaluatedExpr
>>> from sympy.abc import x
>>> x*(1/x)
1
>>> x*UnevaluatedExpr(1/x)
x*1/x
"""
def __new__(cls, arg, **kwargs):
arg = _sympify(arg)
obj = Expr.__new__(cls, arg, **kwargs)
return obj
def doit(self, **kwargs):
if kwargs.get("deep", True):
return self.args[0].doit(**kwargs)
else:
return self.args[0]
def unchanged(func, *args):
"""Return True if `func` applied to the `args` is unchanged.
Can be used instead of `assert foo == foo`.
Examples
========
>>> from sympy import Piecewise, cos, pi
>>> from sympy.core.expr import unchanged
>>> from sympy.abc import x
>>> unchanged(cos, 1) # instead of assert cos(1) == cos(1)
True
>>> unchanged(cos, pi)
False
Comparison of args uses the builtin capabilities of the object's
arguments to test for equality so args can be defined loosely. Here,
the ExprCondPair arguments of Piecewise compare as equal to the
tuples that can be used to create the Piecewise:
>>> unchanged(Piecewise, (x, x > 1), (0, True))
True
"""
f = func(*args)
return f.func == func and f.args == args
class ExprBuilder:
def __init__(self, op, args=[], validator=None, check=True):
if not hasattr(op, "__call__"):
raise TypeError("op {} needs to be callable".format(op))
self.op = op
self.args = args
self.validator = validator
if (validator is not None) and check:
self.validate()
@staticmethod
def _build_args(args):
return [i.build() if isinstance(i, ExprBuilder) else i for i in args]
def validate(self):
if self.validator is None:
return
args = self._build_args(self.args)
self.validator(*args)
def build(self, check=True):
args = self._build_args(self.args)
if self.validator and check:
self.validator(*args)
return self.op(*args)
def append_argument(self, arg, check=True):
self.args.append(arg)
if self.validator and check:
self.validate(*self.args)
def __getitem__(self, item):
if item == 0:
return self.op
else:
return self.args[item-1]
def __repr__(self):
return str(self.build())
def search_element(self, elem):
for i, arg in enumerate(self.args):
if isinstance(arg, ExprBuilder):
ret = arg.search_index(elem)
if ret is not None:
return (i,) + ret
elif id(arg) == id(elem):
return (i,)
return None
from .mul import Mul
from .add import Add
from .power import Pow
from .function import Function, _derivative_dispatch
from .mod import Mod
from .exprtools import factor_terms
from .numbers import Integer, Rational
|
7d92200c24ecc46ad5d25f9e6cf5fab0873ddd2ba4df09c4e80b163ea40439e1 | from typing import Dict, Union, Type
from sympy.utilities.exceptions import SymPyDeprecationWarning
from .basic import S, Atom
from .compatibility import ordered
from .basic import Basic
from .evalf import EvalfMixin
from .function import AppliedUndef
from .sympify import _sympify, SympifyError
from .parameters import global_parameters
from sympy.core.logic import fuzzy_bool, fuzzy_xor, fuzzy_and, fuzzy_not
from sympy.logic.boolalg import Boolean, BooleanAtom
__all__ = (
'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge',
'Relational', 'Equality', 'Unequality', 'StrictLessThan', 'LessThan',
'StrictGreaterThan', 'GreaterThan',
)
from .expr import Expr
from sympy.multipledispatch import dispatch
from .containers import Tuple
from .symbol import Symbol
def _nontrivBool(side):
return isinstance(side, Boolean) and \
not isinstance(side, Atom)
# Note, see issue 4986. Ideally, we wouldn't want to subclass both Boolean
# and Expr.
# from .. import Expr
def _canonical(cond):
# return a condition in which all relationals are canonical
reps = {r: r.canonical for r in cond.atoms(Relational)}
return cond.xreplace(reps)
# XXX: AttributeError was being caught here but it wasn't triggered by any of
# the tests so I've removed it...
class Relational(Boolean, EvalfMixin):
"""Base class for all relation types.
Explanation
===========
Subclasses of Relational should generally be instantiated directly, but
Relational can be instantiated with a valid ``rop`` value to dispatch to
the appropriate subclass.
Parameters
==========
rop : str or None
Indicates what subclass to instantiate. Valid values can be found
in the keys of Relational.ValidRelationOperator.
Examples
========
>>> from sympy import Rel
>>> from sympy.abc import x, y
>>> Rel(y, x + x**2, '==')
Eq(y, x**2 + x)
"""
__slots__ = ()
ValidRelationOperator = {} # type: Dict[Union[str, None], Type[Relational]]
is_Relational = True
# ValidRelationOperator - Defined below, because the necessary classes
# have not yet been defined
def __new__(cls, lhs, rhs, rop=None, **assumptions):
# If called by a subclass, do nothing special and pass on to Basic.
if cls is not Relational:
return Basic.__new__(cls, lhs, rhs, **assumptions)
# XXX: Why do this? There should be a separate function to make a
# particular subclass of Relational from a string.
#
# If called directly with an operator, look up the subclass
# corresponding to that operator and delegate to it
cls = cls.ValidRelationOperator.get(rop, None)
if cls is None:
raise ValueError("Invalid relational operator symbol: %r" % rop)
if not issubclass(cls, (Eq, Ne)):
# validate that Booleans are not being used in a relational
# other than Eq/Ne;
# Note: Symbol is a subclass of Boolean but is considered
# acceptable here.
if any(map(_nontrivBool, (lhs, rhs))):
from sympy.utilities.misc import filldedent
raise TypeError(filldedent('''
A Boolean argument can only be used in
Eq and Ne; all other relationals expect
real expressions.
'''))
return cls(lhs, rhs, **assumptions)
@property
def lhs(self):
"""The left-hand side of the relation."""
return self._args[0]
@property
def rhs(self):
"""The right-hand side of the relation."""
return self._args[1]
@property
def reversed(self):
"""Return the relationship with sides reversed.
Examples
========
>>> from sympy import Eq
>>> from sympy.abc import x
>>> Eq(x, 1)
Eq(x, 1)
>>> _.reversed
Eq(1, x)
>>> x < 1
x < 1
>>> _.reversed
1 > x
"""
ops = {Eq: Eq, Gt: Lt, Ge: Le, Lt: Gt, Le: Ge, Ne: Ne}
a, b = self.args
return Relational.__new__(ops.get(self.func, self.func), b, a)
@property
def reversedsign(self):
"""Return the relationship with signs reversed.
Examples
========
>>> from sympy import Eq
>>> from sympy.abc import x
>>> Eq(x, 1)
Eq(x, 1)
>>> _.reversedsign
Eq(-x, -1)
>>> x < 1
x < 1
>>> _.reversedsign
-x > -1
"""
a, b = self.args
if not (isinstance(a, BooleanAtom) or isinstance(b, BooleanAtom)):
ops = {Eq: Eq, Gt: Lt, Ge: Le, Lt: Gt, Le: Ge, Ne: Ne}
return Relational.__new__(ops.get(self.func, self.func), -a, -b)
else:
return self
@property
def negated(self):
"""Return the negated relationship.
Examples
========
>>> from sympy import Eq
>>> from sympy.abc import x
>>> Eq(x, 1)
Eq(x, 1)
>>> _.negated
Ne(x, 1)
>>> x < 1
x < 1
>>> _.negated
x >= 1
Notes
=====
This works more or less identical to ``~``/``Not``. The difference is
that ``negated`` returns the relationship even if ``evaluate=False``.
Hence, this is useful in code when checking for e.g. negated relations
to existing ones as it will not be affected by the `evaluate` flag.
"""
ops = {Eq: Ne, Ge: Lt, Gt: Le, Le: Gt, Lt: Ge, Ne: Eq}
# If there ever will be new Relational subclasses, the following line
# will work until it is properly sorted out
# return ops.get(self.func, lambda a, b, evaluate=False: ~(self.func(a,
# b, evaluate=evaluate)))(*self.args, evaluate=False)
return Relational.__new__(ops.get(self.func), *self.args)
def _eval_evalf(self, prec):
return self.func(*[s._evalf(prec) for s in self.args])
@property
def canonical(self):
"""Return a canonical form of the relational by putting a
number on the rhs, canonically removing a sign or else
ordering the args canonically. No other simplification is
attempted.
Examples
========
>>> from sympy.abc import x, y
>>> x < 2
x < 2
>>> _.reversed.canonical
x < 2
>>> (-y < x).canonical
x > -y
>>> (-y > x).canonical
x < -y
>>> (-y < -x).canonical
x < y
"""
args = self.args
r = self
if r.rhs.is_number:
if r.rhs.is_Number and r.lhs.is_Number and r.lhs > r.rhs:
r = r.reversed
elif r.lhs.is_number:
r = r.reversed
elif tuple(ordered(args)) != args:
r = r.reversed
LHS_CEMS = getattr(r.lhs, 'could_extract_minus_sign', None)
RHS_CEMS = getattr(r.rhs, 'could_extract_minus_sign', None)
if isinstance(r.lhs, BooleanAtom) or isinstance(r.rhs, BooleanAtom):
return r
# Check if first value has negative sign
if LHS_CEMS and LHS_CEMS():
return r.reversedsign
elif not r.rhs.is_number and RHS_CEMS and RHS_CEMS():
# Right hand side has a minus, but not lhs.
# How does the expression with reversed signs behave?
# This is so that expressions of the type
# Eq(x, -y) and Eq(-x, y)
# have the same canonical representation
expr1, _ = ordered([r.lhs, -r.rhs])
if expr1 != r.lhs:
return r.reversed.reversedsign
return r
def equals(self, other, failing_expression=False):
"""Return True if the sides of the relationship are mathematically
identical and the type of relationship is the same.
If failing_expression is True, return the expression whose truth value
was unknown."""
if isinstance(other, Relational):
if self == other or self.reversed == other:
return True
a, b = self, other
if a.func in (Eq, Ne) or b.func in (Eq, Ne):
if a.func != b.func:
return False
left, right = [i.equals(j,
failing_expression=failing_expression)
for i, j in zip(a.args, b.args)]
if left is True:
return right
if right is True:
return left
lr, rl = [i.equals(j, failing_expression=failing_expression)
for i, j in zip(a.args, b.reversed.args)]
if lr is True:
return rl
if rl is True:
return lr
e = (left, right, lr, rl)
if all(i is False for i in e):
return False
for i in e:
if i not in (True, False):
return i
else:
if b.func != a.func:
b = b.reversed
if a.func != b.func:
return False
left = a.lhs.equals(b.lhs,
failing_expression=failing_expression)
if left is False:
return False
right = a.rhs.equals(b.rhs,
failing_expression=failing_expression)
if right is False:
return False
if left is True:
return right
return left
def _eval_simplify(self, **kwargs):
from .add import Add
from sympy.core.expr import Expr
r = self
r = r.func(*[i.simplify(**kwargs) for i in r.args])
if r.is_Relational:
if not isinstance(r.lhs, Expr) or not isinstance(r.rhs, Expr):
return r
dif = r.lhs - r.rhs
# replace dif with a valid Number that will
# allow a definitive comparison with 0
v = None
if dif.is_comparable:
v = dif.n(2)
elif dif.equals(0): # XXX this is expensive
v = S.Zero
if v is not None:
r = r.func._eval_relation(v, S.Zero)
r = r.canonical
# If there is only one symbol in the expression,
# try to write it on a simplified form
free = list(filter(lambda x: x.is_real is not False, r.free_symbols))
if len(free) == 1:
try:
from sympy.solvers.solveset import linear_coeffs
x = free.pop()
dif = r.lhs - r.rhs
m, b = linear_coeffs(dif, x)
if m.is_zero is False:
if m.is_negative:
# Dividing with a negative number, so change order of arguments
# canonical will put the symbol back on the lhs later
r = r.func(-b / m, x)
else:
r = r.func(x, -b / m)
else:
r = r.func(b, S.zero)
except ValueError:
# maybe not a linear function, try polynomial
from sympy.polys import Poly, poly, PolynomialError, gcd
try:
p = poly(dif, x)
c = p.all_coeffs()
constant = c[-1]
c[-1] = 0
scale = gcd(c)
c = [ctmp / scale for ctmp in c]
r = r.func(Poly.from_list(c, x).as_expr(), -constant / scale)
except PolynomialError:
pass
elif len(free) >= 2:
try:
from sympy.solvers.solveset import linear_coeffs
from sympy.polys import gcd
free = list(ordered(free))
dif = r.lhs - r.rhs
m = linear_coeffs(dif, *free)
constant = m[-1]
del m[-1]
scale = gcd(m)
m = [mtmp / scale for mtmp in m]
nzm = list(filter(lambda f: f[0] != 0, list(zip(m, free))))
if scale.is_zero is False:
if constant != 0:
# lhs: expression, rhs: constant
newexpr = Add(*[i * j for i, j in nzm])
r = r.func(newexpr, -constant / scale)
else:
# keep first term on lhs
lhsterm = nzm[0][0] * nzm[0][1]
del nzm[0]
newexpr = Add(*[i * j for i, j in nzm])
r = r.func(lhsterm, -newexpr)
else:
r = r.func(constant, S.zero)
except ValueError:
pass
# Did we get a simplified result?
r = r.canonical
measure = kwargs['measure']
if measure(r) < kwargs['ratio'] * measure(self):
return r
else:
return self
def _eval_trigsimp(self, **opts):
from sympy.simplify import trigsimp
return self.func(trigsimp(self.lhs, **opts), trigsimp(self.rhs, **opts))
def expand(self, **kwargs):
args = (arg.expand(**kwargs) for arg in self.args)
return self.func(*args)
def __bool__(self):
raise TypeError("cannot determine truth value of Relational")
def _eval_as_set(self):
# self is univariate and periodicity(self, x) in (0, None)
from sympy.solvers.inequalities import solve_univariate_inequality
from sympy.sets.conditionset import ConditionSet
syms = self.free_symbols
assert len(syms) == 1
x = syms.pop()
try:
xset = solve_univariate_inequality(self, x, relational=False)
except NotImplementedError:
# solve_univariate_inequality raises NotImplementedError for
# unsolvable equations/inequalities.
xset = ConditionSet(x, self, S.Reals)
return xset
@property
def binary_symbols(self):
# override where necessary
return set()
Rel = Relational
class Equality(Relational):
"""An equal relation between two objects.
Explanation
===========
Represents that two objects are equal. If they can be easily shown
to be definitively equal (or unequal), this will reduce to True (or
False). Otherwise, the relation is maintained as an unevaluated
Equality object. Use the ``simplify`` function on this object for
more nontrivial evaluation of the equality relation.
As usual, the keyword argument ``evaluate=False`` can be used to
prevent any evaluation.
Examples
========
>>> from sympy import Eq, simplify, exp, cos
>>> from sympy.abc import x, y
>>> Eq(y, x + x**2)
Eq(y, x**2 + x)
>>> Eq(2, 5)
False
>>> Eq(2, 5, evaluate=False)
Eq(2, 5)
>>> _.doit()
False
>>> Eq(exp(x), exp(x).rewrite(cos))
Eq(exp(x), sinh(x) + cosh(x))
>>> simplify(_)
True
See Also
========
sympy.logic.boolalg.Equivalent : for representing equality between two
boolean expressions
Notes
=====
Python treats 1 and True (and 0 and False) as being equal; SymPy
does not. And integer will always compare as unequal to a Boolean:
>>> Eq(True, 1), True == 1
(False, True)
This class is not the same as the == operator. The == operator tests
for exact structural equality between two expressions; this class
compares expressions mathematically.
If either object defines an ``_eval_Eq`` method, it can be used in place of
the default algorithm. If ``lhs._eval_Eq(rhs)`` or ``rhs._eval_Eq(lhs)``
returns anything other than None, that return value will be substituted for
the Equality. If None is returned by ``_eval_Eq``, an Equality object will
be created as usual.
Since this object is already an expression, it does not respond to
the method ``as_expr`` if one tries to create `x - y` from ``Eq(x, y)``.
This can be done with the ``rewrite(Add)`` method.
"""
rel_op = '=='
__slots__ = ()
is_Equality = True
def __new__(cls, lhs, rhs=None, **options):
if rhs is None:
SymPyDeprecationWarning(
feature="Eq(expr) with rhs default to 0",
useinstead="Eq(expr, 0)",
issue=16587,
deprecated_since_version="1.5"
).warn()
rhs = 0
evaluate = options.pop('evaluate', global_parameters.evaluate)
lhs = _sympify(lhs)
rhs = _sympify(rhs)
if evaluate:
val = is_eq(lhs, rhs)
if val is None:
return cls(lhs, rhs, evaluate=False)
else:
return _sympify(val)
return Relational.__new__(cls, lhs, rhs)
@classmethod
def _eval_relation(cls, lhs, rhs):
return _sympify(lhs == rhs)
def _eval_rewrite_as_Add(self, *args, **kwargs):
"""
return Eq(L, R) as L - R. To control the evaluation of
the result set pass `evaluate=True` to give L - R;
if `evaluate=None` then terms in L and R will not cancel
but they will be listed in canonical order; otherwise
non-canonical args will be returned.
Examples
========
>>> from sympy import Eq, Add
>>> from sympy.abc import b, x
>>> eq = Eq(x + b, x - b)
>>> eq.rewrite(Add)
2*b
>>> eq.rewrite(Add, evaluate=None).args
(b, b, x, -x)
>>> eq.rewrite(Add, evaluate=False).args
(b, x, b, -x)
"""
from .add import _unevaluated_Add, Add
L, R = args
evaluate = kwargs.get('evaluate', True)
if evaluate:
# allow cancellation of args
return L - R
args = Add.make_args(L) + Add.make_args(-R)
if evaluate is None:
# no cancellation, but canonical
return _unevaluated_Add(*args)
# no cancellation, not canonical
return Add._from_args(args)
@property
def binary_symbols(self):
if S.true in self.args or S.false in self.args:
if self.lhs.is_Symbol:
return {self.lhs}
elif self.rhs.is_Symbol:
return {self.rhs}
return set()
def _eval_simplify(self, **kwargs):
from .add import Add
from sympy.core.expr import Expr
from sympy.solvers.solveset import linear_coeffs
# standard simplify
e = super()._eval_simplify(**kwargs)
if not isinstance(e, Equality):
return e
if not isinstance(e.lhs, Expr) or not isinstance(e.rhs, Expr):
return e
free = self.free_symbols
if len(free) == 1:
try:
x = free.pop()
m, b = linear_coeffs(
e.rewrite(Add, evaluate=False), x)
if m.is_zero is False:
enew = e.func(x, -b / m)
else:
enew = e.func(m * x, -b)
measure = kwargs['measure']
if measure(enew) <= kwargs['ratio'] * measure(e):
e = enew
except ValueError:
pass
return e.canonical
def integrate(self, *args, **kwargs):
"""See the integrate function in sympy.integrals"""
from sympy.integrals import integrate
return integrate(self, *args, **kwargs)
def as_poly(self, *gens, **kwargs):
'''Returns lhs-rhs as a Poly
Examples
========
>>> from sympy import Eq
>>> from sympy.abc import x
>>> Eq(x**2, 1).as_poly(x)
Poly(x**2 - 1, x, domain='ZZ')
'''
return (self.lhs - self.rhs).as_poly(*gens, **kwargs)
Eq = Equality
class Unequality(Relational):
"""An unequal relation between two objects.
Explanation
===========
Represents that two objects are not equal. If they can be shown to be
definitively equal, this will reduce to False; if definitively unequal,
this will reduce to True. Otherwise, the relation is maintained as an
Unequality object.
Examples
========
>>> from sympy import Ne
>>> from sympy.abc import x, y
>>> Ne(y, x+x**2)
Ne(y, x**2 + x)
See Also
========
Equality
Notes
=====
This class is not the same as the != operator. The != operator tests
for exact structural equality between two expressions; this class
compares expressions mathematically.
This class is effectively the inverse of Equality. As such, it uses the
same algorithms, including any available `_eval_Eq` methods.
"""
rel_op = '!='
__slots__ = ()
def __new__(cls, lhs, rhs, **options):
lhs = _sympify(lhs)
rhs = _sympify(rhs)
evaluate = options.pop('evaluate', global_parameters.evaluate)
if evaluate:
val = is_neq(lhs, rhs)
if val is None:
return cls(lhs, rhs, evaluate=False)
else:
return _sympify(val)
return Relational.__new__(cls, lhs, rhs, **options)
@classmethod
def _eval_relation(cls, lhs, rhs):
return _sympify(lhs != rhs)
@property
def binary_symbols(self):
if S.true in self.args or S.false in self.args:
if self.lhs.is_Symbol:
return {self.lhs}
elif self.rhs.is_Symbol:
return {self.rhs}
return set()
def _eval_simplify(self, **kwargs):
# simplify as an equality
eq = Equality(*self.args)._eval_simplify(**kwargs)
if isinstance(eq, Equality):
# send back Ne with the new args
return self.func(*eq.args)
return eq.negated # result of Ne is the negated Eq
Ne = Unequality
class _Inequality(Relational):
"""Internal base class for all *Than types.
Each subclass must implement _eval_relation to provide the method for
comparing two real numbers.
"""
__slots__ = ()
def __new__(cls, lhs, rhs, **options):
try:
lhs = _sympify(lhs)
rhs = _sympify(rhs)
except SympifyError:
return NotImplemented
evaluate = options.pop('evaluate', global_parameters.evaluate)
if evaluate:
for me in (lhs, rhs):
if me.is_extended_real is False:
raise TypeError("Invalid comparison of non-real %s" % me)
if me is S.NaN:
raise TypeError("Invalid NaN comparison")
# First we invoke the appropriate inequality method of `lhs`
# (e.g., `lhs.__lt__`). That method will try to reduce to
# boolean or raise an exception. It may keep calling
# superclasses until it reaches `Expr` (e.g., `Expr.__lt__`).
# In some cases, `Expr` will just invoke us again (if neither it
# nor a subclass was able to reduce to boolean or raise an
# exception). In that case, it must call us with
# `evaluate=False` to prevent infinite recursion.
return cls._eval_relation(lhs, rhs, **options)
# make a "non-evaluated" Expr for the inequality
return Relational.__new__(cls, lhs, rhs, **options)
@classmethod
def _eval_relation(cls, lhs, rhs, **options):
val = cls._eval_fuzzy_relation(lhs, rhs)
if val is None:
return cls(lhs, rhs, evaluate=False)
else:
return _sympify(val)
class _Greater(_Inequality):
"""Not intended for general use
_Greater is only used so that GreaterThan and StrictGreaterThan may
subclass it for the .gts and .lts properties.
"""
__slots__ = ()
@property
def gts(self):
return self._args[0]
@property
def lts(self):
return self._args[1]
class _Less(_Inequality):
"""Not intended for general use.
_Less is only used so that LessThan and StrictLessThan may subclass it for
the .gts and .lts properties.
"""
__slots__ = ()
@property
def gts(self):
return self._args[1]
@property
def lts(self):
return self._args[0]
class GreaterThan(_Greater):
"""Class representations of inequalities.
Explanation
===========
The ``*Than`` classes represent inequal relationships, where the left-hand
side is generally bigger or smaller than the right-hand side. For example,
the GreaterThan class represents an inequal relationship where the
left-hand side is at least as big as the right side, if not bigger. In
mathematical notation:
lhs >= rhs
In total, there are four ``*Than`` classes, to represent the four
inequalities:
+-----------------+--------+
|Class Name | Symbol |
+=================+========+
|GreaterThan | (>=) |
+-----------------+--------+
|LessThan | (<=) |
+-----------------+--------+
|StrictGreaterThan| (>) |
+-----------------+--------+
|StrictLessThan | (<) |
+-----------------+--------+
All classes take two arguments, lhs and rhs.
+----------------------------+-----------------+
|Signature Example | Math equivalent |
+============================+=================+
|GreaterThan(lhs, rhs) | lhs >= rhs |
+----------------------------+-----------------+
|LessThan(lhs, rhs) | lhs <= rhs |
+----------------------------+-----------------+
|StrictGreaterThan(lhs, rhs) | lhs > rhs |
+----------------------------+-----------------+
|StrictLessThan(lhs, rhs) | lhs < rhs |
+----------------------------+-----------------+
In addition to the normal .lhs and .rhs of Relations, ``*Than`` inequality
objects also have the .lts and .gts properties, which represent the "less
than side" and "greater than side" of the operator. Use of .lts and .gts
in an algorithm rather than .lhs and .rhs as an assumption of inequality
direction will make more explicit the intent of a certain section of code,
and will make it similarly more robust to client code changes:
>>> from sympy import GreaterThan, StrictGreaterThan
>>> from sympy import LessThan, StrictLessThan
>>> from sympy import And, Ge, Gt, Le, Lt, Rel, S
>>> from sympy.abc import x, y, z
>>> from sympy.core.relational import Relational
>>> e = GreaterThan(x, 1)
>>> e
x >= 1
>>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts)
'x >= 1 is the same as 1 <= x'
Examples
========
One generally does not instantiate these classes directly, but uses various
convenience methods:
>>> for f in [Ge, Gt, Le, Lt]: # convenience wrappers
... print(f(x, 2))
x >= 2
x > 2
x <= 2
x < 2
Another option is to use the Python inequality operators (>=, >, <=, <)
directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts,
is that one can write a more "mathematical looking" statement rather than
littering the math with oddball function calls. However there are certain
(minor) caveats of which to be aware (search for 'gotcha', below).
>>> x >= 2
x >= 2
>>> _ == Ge(x, 2)
True
However, it is also perfectly valid to instantiate a ``*Than`` class less
succinctly and less conveniently:
>>> Rel(x, 1, ">")
x > 1
>>> Relational(x, 1, ">")
x > 1
>>> StrictGreaterThan(x, 1)
x > 1
>>> GreaterThan(x, 1)
x >= 1
>>> LessThan(x, 1)
x <= 1
>>> StrictLessThan(x, 1)
x < 1
Notes
=====
There are a couple of "gotchas" to be aware of when using Python's
operators.
The first is that what your write is not always what you get:
>>> 1 < x
x > 1
Due to the order that Python parses a statement, it may
not immediately find two objects comparable. When "1 < x"
is evaluated, Python recognizes that the number 1 is a native
number and that x is *not*. Because a native Python number does
not know how to compare itself with a SymPy object
Python will try the reflective operation, "x > 1" and that is the
form that gets evaluated, hence returned.
If the order of the statement is important (for visual output to
the console, perhaps), one can work around this annoyance in a
couple ways:
(1) "sympify" the literal before comparison
>>> S(1) < x
1 < x
(2) use one of the wrappers or less succinct methods described
above
>>> Lt(1, x)
1 < x
>>> Relational(1, x, "<")
1 < x
The second gotcha involves writing equality tests between relationals
when one or both sides of the test involve a literal relational:
>>> e = x < 1; e
x < 1
>>> e == e # neither side is a literal
True
>>> e == x < 1 # expecting True, too
False
>>> e != x < 1 # expecting False
x < 1
>>> x < 1 != x < 1 # expecting False or the same thing as before
Traceback (most recent call last):
...
TypeError: cannot determine truth value of Relational
The solution for this case is to wrap literal relationals in
parentheses:
>>> e == (x < 1)
True
>>> e != (x < 1)
False
>>> (x < 1) != (x < 1)
False
The third gotcha involves chained inequalities not involving
'==' or '!='. Occasionally, one may be tempted to write:
>>> e = x < y < z
Traceback (most recent call last):
...
TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python [1]_,
there is no way for SymPy to create a chained inequality with
that syntax so one must use And:
>>> e = And(x < y, y < z)
>>> type( e )
And
>>> e
(x < y) & (y < z)
Although this can also be done with the '&' operator, it cannot
be done with the 'and' operarator:
>>> (x < y) & (y < z)
(x < y) & (y < z)
>>> (x < y) and (y < z)
Traceback (most recent call last):
...
TypeError: cannot determine truth value of Relational
.. [1] This implementation detail is that Python provides no reliable
method to determine that a chained inequality is being built.
Chained comparison operators are evaluated pairwise, using "and"
logic (see
http://docs.python.org/2/reference/expressions.html#notin). This
is done in an efficient way, so that each object being compared
is only evaluated once and the comparison can short-circuit. For
example, ``1 > 2 > 3`` is evaluated by Python as ``(1 > 2) and (2
> 3)``. The ``and`` operator coerces each side into a bool,
returning the object itself when it short-circuits. The bool of
the --Than operators will raise TypeError on purpose, because
SymPy cannot determine the mathematical ordering of symbolic
expressions. Thus, if we were to compute ``x > y > z``, with
``x``, ``y``, and ``z`` being Symbols, Python converts the
statement (roughly) into these steps:
(1) x > y > z
(2) (x > y) and (y > z)
(3) (GreaterThanObject) and (y > z)
(4) (GreaterThanObject.__bool__()) and (y > z)
(5) TypeError
Because of the "and" added at step 2, the statement gets turned into a
weak ternary statement, and the first object's __bool__ method will
raise TypeError. Thus, creating a chained inequality is not possible.
In Python, there is no way to override the ``and`` operator, or to
control how it short circuits, so it is impossible to make something
like ``x > y > z`` work. There was a PEP to change this,
:pep:`335`, but it was officially closed in March, 2012.
"""
__slots__ = ()
rel_op = '>='
@classmethod
def _eval_fuzzy_relation(cls, lhs, rhs):
return is_ge(lhs, rhs)
Ge = GreaterThan
class LessThan(_Less):
__doc__ = GreaterThan.__doc__
__slots__ = ()
rel_op = '<='
@classmethod
def _eval_fuzzy_relation(cls, lhs, rhs):
return is_le(lhs, rhs)
Le = LessThan
class StrictGreaterThan(_Greater):
__doc__ = GreaterThan.__doc__
__slots__ = ()
rel_op = '>'
@classmethod
def _eval_fuzzy_relation(cls, lhs, rhs):
return is_gt(lhs, rhs)
Gt = StrictGreaterThan
class StrictLessThan(_Less):
__doc__ = GreaterThan.__doc__
__slots__ = ()
rel_op = '<'
@classmethod
def _eval_fuzzy_relation(cls, lhs, rhs):
return is_lt(lhs, rhs)
Lt = StrictLessThan
# A class-specific (not object-specific) data item used for a minor speedup.
# It is defined here, rather than directly in the class, because the classes
# that it references have not been defined until now (e.g. StrictLessThan).
Relational.ValidRelationOperator = {
None: Equality,
'==': Equality,
'eq': Equality,
'!=': Unequality,
'<>': Unequality,
'ne': Unequality,
'>=': GreaterThan,
'ge': GreaterThan,
'<=': LessThan,
'le': LessThan,
'>': StrictGreaterThan,
'gt': StrictGreaterThan,
'<': StrictLessThan,
'lt': StrictLessThan,
}
def _n2(a, b):
"""Return (a - b).evalf(2) if a and b are comparable, else None.
This should only be used when a and b are already sympified.
"""
# /!\ it is very important (see issue 8245) not to
# use a re-evaluated number in the calculation of dif
if a.is_comparable and b.is_comparable:
dif = (a - b).evalf(2)
if dif.is_comparable:
return dif
@dispatch(Expr, Expr)
def _eval_is_ge(lhs, rhs):
return None
@dispatch(Basic, Basic)
def _eval_is_eq(lhs, rhs):
return None
@dispatch(Tuple, Expr) # type: ignore
def _eval_is_eq(lhs, rhs): # noqa:F811
return False
@dispatch(Tuple, AppliedUndef) # type: ignore
def _eval_is_eq(lhs, rhs): # noqa:F811
return None
@dispatch(Tuple, Symbol) # type: ignore
def _eval_is_eq(lhs, rhs): # noqa:F811
return None
@dispatch(Tuple, Tuple) # type: ignore
def _eval_is_eq(lhs, rhs): # noqa:F811
if len(lhs) != len(rhs):
return False
return fuzzy_and(fuzzy_bool(is_eq(s, o)) for s, o in zip(lhs, rhs))
def is_lt(lhs, rhs, assumptions=None):
"""Fuzzy bool for lhs is strictly less than rhs.
See the docstring for :func:`~.is_ge` for more.
"""
return fuzzy_not(is_ge(lhs, rhs, assumptions))
def is_gt(lhs, rhs, assumptions=None):
"""Fuzzy bool for lhs is strictly greater than rhs.
See the docstring for :func:`~.is_ge` for more.
"""
return fuzzy_not(is_le(lhs, rhs, assumptions))
def is_le(lhs, rhs, assumptions=None):
"""Fuzzy bool for lhs is less than or equal to rhs.
See the docstring for :func:`~.is_ge` for more.
"""
return is_ge(rhs, lhs, assumptions)
def is_ge(lhs, rhs, assumptions=None):
"""
Fuzzy bool for *lhs* is greater than or equal to *rhs*.
Parameters
==========
lhs : Expr
The left-hand side of the expression, must be sympified,
and an instance of expression. Throws an exception if
lhs is not an instance of expression.
rhs : Expr
The right-hand side of the expression, must be sympified
and an instance of expression. Throws an exception if
lhs is not an instance of expression.
assumptions: Boolean, optional
Assumptions taken to evaluate the inequality.
Returns
=======
``True`` if *lhs* is greater than or equal to *rhs*, ``False`` if *lhs*
is less than *rhs*, and ``None`` if the comparison between *lhs* and
*rhs* is indeterminate.
Explanation
===========
This function is intended to give a relatively fast determination and
deliberately does not attempt slow calculations that might help in
obtaining a determination of True or False in more difficult cases.
The four comparison functions ``is_le``, ``is_lt``, ``is_ge``, and ``is_gt`` are
each implemented in terms of ``is_ge`` in the following way:
is_ge(x, y) := is_ge(x, y)
is_le(x, y) := is_ge(y, x)
is_lt(x, y) := fuzzy_not(is_ge(x, y))
is_gt(x, y) := fuzzy_not(is_ge(y, x))
Therefore, supporting new type with this function will ensure behavior for
other three functions as well.
To maintain these equivalences in fuzzy logic it is important that in cases where
either x or y is non-real all comparisons will give None.
Examples
========
>>> from sympy import S, Q
>>> from sympy.core.relational import is_ge, is_le, is_gt, is_lt
>>> from sympy.abc import x
>>> is_ge(S(2), S(0))
True
>>> is_ge(S(0), S(2))
False
>>> is_le(S(0), S(2))
True
>>> is_gt(S(0), S(2))
False
>>> is_lt(S(2), S(0))
False
Assumptions can be passed to evaluate the quality which is otherwise
indeterminate.
>>> print(is_ge(x, S(0)))
None
>>> is_ge(x, S(0), assumptions=Q.positive(x))
True
New types can be supported by dispatching to ``_eval_is_ge``.
>>> from sympy import Expr, sympify
>>> from sympy.multipledispatch import dispatch
>>> class MyExpr(Expr):
... def __new__(cls, arg):
... return super().__new__(cls, sympify(arg))
... @property
... def value(self):
... return self.args[0]
>>> @dispatch(MyExpr, MyExpr)
... def _eval_is_ge(a, b):
... return is_ge(a.value, b.value)
>>> a = MyExpr(1)
>>> b = MyExpr(2)
>>> is_ge(b, a)
True
>>> is_le(a, b)
True
"""
from sympy.assumptions.wrapper import AssumptionsWrapper, is_extended_nonnegative
if not (isinstance(lhs, Expr) and isinstance(rhs, Expr)):
raise TypeError("Can only compare inequalities with Expr")
retval = _eval_is_ge(lhs, rhs)
if retval is not None:
return retval
else:
n2 = _n2(lhs, rhs)
if n2 is not None:
# use float comparison for infinity.
# otherwise get stuck in infinite recursion
if n2 in (S.Infinity, S.NegativeInfinity):
n2 = float(n2)
return n2 >= 0
_lhs = AssumptionsWrapper(lhs, assumptions)
_rhs = AssumptionsWrapper(rhs, assumptions)
if _lhs.is_extended_real and _rhs.is_extended_real:
if (_lhs.is_infinite and _lhs.is_extended_positive) or (_rhs.is_infinite and _rhs.is_extended_negative):
return True
diff = lhs - rhs
if diff is not S.NaN:
rv = is_extended_nonnegative(diff, assumptions)
if rv is not None:
return rv
def is_neq(lhs, rhs, assumptions=None):
"""Fuzzy bool for lhs does not equal rhs.
See the docstring for :func:`~.is_eq` for more.
"""
return fuzzy_not(is_eq(lhs, rhs, assumptions))
def is_eq(lhs, rhs, assumptions=None):
"""
Fuzzy bool representing mathematical equality between *lhs* and *rhs*.
Parameters
==========
lhs : Expr
The left-hand side of the expression, must be sympified.
rhs : Expr
The right-hand side of the expression, must be sympified.
assumptions: Boolean, optional
Assumptions taken to evaluate the equality.
Returns
=======
``True`` if *lhs* is equal to *rhs*, ``False`` is *lhs* is not equal to *rhs*,
and ``None`` if the comparison between *lhs* and *rhs* is indeterminate.
Explanation
===========
This function is intended to give a relatively fast determination and
deliberately does not attempt slow calculations that might help in
obtaining a determination of True or False in more difficult cases.
:func:`~.is_neq` calls this function to return its value, so supporting
new type with this function will ensure correct behavior for ``is_neq``
as well.
Examples
========
>>> from sympy import Q, S
>>> from sympy.core.relational import is_eq, is_neq
>>> from sympy.abc import x
>>> is_eq(S(0), S(0))
True
>>> is_neq(S(0), S(0))
False
>>> is_eq(S(0), S(2))
False
>>> is_neq(S(0), S(2))
True
Assumptions can be passed to evaluate the equality which is otherwise
indeterminate.
>>> print(is_eq(x, S(0)))
None
>>> is_eq(x, S(0), assumptions=Q.zero(x))
True
New types can be supported by dispatching to ``_eval_is_eq``.
>>> from sympy import Basic, sympify
>>> from sympy.multipledispatch import dispatch
>>> class MyBasic(Basic):
... def __new__(cls, arg):
... return Basic.__new__(cls, sympify(arg))
... @property
... def value(self):
... return self.args[0]
...
>>> @dispatch(MyBasic, MyBasic)
... def _eval_is_eq(a, b):
... return is_eq(a.value, b.value)
...
>>> a = MyBasic(1)
>>> b = MyBasic(1)
>>> is_eq(a, b)
True
>>> is_neq(a, b)
False
"""
from sympy.assumptions.wrapper import (AssumptionsWrapper,
is_infinite, is_extended_real)
from sympy.core.add import Add
from sympy.functions.elementary.complexes import arg
from sympy.simplify.simplify import clear_coefficients
from sympy.utilities.iterables import sift
# here, _eval_Eq is only called for backwards compatibility
# new code should use is_eq with multiple dispatch as
# outlined in the docstring
for side1, side2 in (lhs, rhs), (rhs, lhs):
eval_func = getattr(side1, '_eval_Eq', None)
if eval_func is not None:
retval = eval_func(side2)
if retval is not None:
return retval
retval = _eval_is_eq(lhs, rhs)
if retval is not None:
return retval
if dispatch(type(lhs), type(rhs)) != dispatch(type(rhs), type(lhs)):
retval = _eval_is_eq(rhs, lhs)
if retval is not None:
return retval
# retval is still None, so go through the equality logic
# If expressions have the same structure, they must be equal.
if lhs == rhs:
return True # e.g. True == True
elif all(isinstance(i, BooleanAtom) for i in (rhs, lhs)):
return False # True != False
elif not (lhs.is_Symbol or rhs.is_Symbol) and (
isinstance(lhs, Boolean) !=
isinstance(rhs, Boolean)):
return False # only Booleans can equal Booleans
_lhs = AssumptionsWrapper(lhs, assumptions)
_rhs = AssumptionsWrapper(rhs, assumptions)
if _lhs.is_infinite or _rhs.is_infinite:
if fuzzy_xor([_lhs.is_infinite, _rhs.is_infinite]):
return False
if fuzzy_xor([_lhs.is_extended_real, _rhs.is_extended_real]):
return False
if fuzzy_and([_lhs.is_extended_real, _rhs.is_extended_real]):
return fuzzy_xor([_lhs.is_extended_positive, fuzzy_not(_rhs.is_extended_positive)])
# Try to split real/imaginary parts and equate them
I = S.ImaginaryUnit
def split_real_imag(expr):
real_imag = lambda t: (
'real' if is_extended_real(t, assumptions) else
'imag' if is_extended_real(I*t, assumptions) else None)
return sift(Add.make_args(expr), real_imag)
lhs_ri = split_real_imag(lhs)
if not lhs_ri[None]:
rhs_ri = split_real_imag(rhs)
if not rhs_ri[None]:
eq_real = is_eq(Add(*lhs_ri['real']), Add(*rhs_ri['real']), assumptions)
eq_imag = is_eq(I * Add(*lhs_ri['imag']), I * Add(*rhs_ri['imag']), assumptions)
return fuzzy_and(map(fuzzy_bool, [eq_real, eq_imag]))
# Compare e.g. zoo with 1+I*oo by comparing args
arglhs = arg(lhs)
argrhs = arg(rhs)
# Guard against Eq(nan, nan) -> False
if not (arglhs == S.NaN and argrhs == S.NaN):
return fuzzy_bool(is_eq(arglhs, argrhs, assumptions))
if all(isinstance(i, Expr) for i in (lhs, rhs)):
# see if the difference evaluates
dif = lhs - rhs
_dif = AssumptionsWrapper(dif, assumptions)
z = _dif.is_zero
if z is not None:
if z is False and _dif.is_commutative: # issue 10728
return False
if z:
return True
n2 = _n2(lhs, rhs)
if n2 is not None:
return _sympify(n2 == 0)
# see if the ratio evaluates
n, d = dif.as_numer_denom()
rv = None
_n = AssumptionsWrapper(n, assumptions)
_d = AssumptionsWrapper(d, assumptions)
if _n.is_zero:
rv = _d.is_nonzero
elif _n.is_finite:
if _d.is_infinite:
rv = True
elif _n.is_zero is False:
rv = _d.is_infinite
if rv is None:
# if the condition that makes the denominator
# infinite does not make the original expression
# True then False can be returned
l, r = clear_coefficients(d, S.Infinity)
args = [_.subs(l, r) for _ in (lhs, rhs)]
if args != [lhs, rhs]:
rv = fuzzy_bool(is_eq(*args, assumptions))
if rv is True:
rv = None
elif any(is_infinite(a, assumptions) for a in Add.make_args(n)):
# (inf or nan)/x != 0
rv = False
if rv is not None:
return rv
|
882b9b8528df105dbcbb4e3a8a93661605235687f495a2626985c88e40f39306 | import numbers
import decimal
import fractions
import math
import re as regex
import sys
from .containers import Tuple
from .sympify import (SympifyError, converter, sympify, _convert_numpy_types, _sympify,
_is_numpy_instance)
from .singleton import S, Singleton
from .expr import Expr, AtomicExpr
from .evalf import pure_complex
from .decorators import _sympifyit
from .cache import cacheit, clear_cache
from .logic import fuzzy_not
from sympy.core.compatibility import (as_int, HAS_GMPY, SYMPY_INTS,
gmpy)
from sympy.core.cache import lru_cache
from .kind import NumberKind
from sympy.multipledispatch import dispatch
import mpmath
import mpmath.libmp as mlib
from mpmath.libmp import bitcount
from mpmath.libmp.backend import MPZ
from mpmath.libmp import mpf_pow, mpf_pi, mpf_e, phi_fixed
from mpmath.ctx_mp import mpnumeric
from mpmath.libmp.libmpf import (
finf as _mpf_inf, fninf as _mpf_ninf,
fnan as _mpf_nan, fzero, _normalize as mpf_normalize,
prec_to_dps)
from sympy.utilities.misc import debug, filldedent
from .parameters import global_parameters
from sympy.utilities.exceptions import SymPyDeprecationWarning
rnd = mlib.round_nearest
_LOG2 = math.log(2)
def comp(z1, z2, tol=None):
"""Return a bool indicating whether the error between z1 and z2
is <= tol.
Examples
========
If ``tol`` is None then True will be returned if
``abs(z1 - z2)*10**p <= 5`` where ``p`` is minimum value of the
decimal precision of each value.
>>> from sympy.core.numbers import comp, pi
>>> pi4 = pi.n(4); pi4
3.142
>>> comp(_, 3.142)
True
>>> comp(pi4, 3.141)
False
>>> comp(pi4, 3.143)
False
A comparison of strings will be made
if ``z1`` is a Number and ``z2`` is a string or ``tol`` is ''.
>>> comp(pi4, 3.1415)
True
>>> comp(pi4, 3.1415, '')
False
When ``tol`` is provided and ``z2`` is non-zero and
``|z1| > 1`` the error is normalized by ``|z1|``:
>>> abs(pi4 - 3.14)/pi4
0.000509791731426756
>>> comp(pi4, 3.14, .001) # difference less than 0.1%
True
>>> comp(pi4, 3.14, .0005) # difference less than 0.1%
False
When ``|z1| <= 1`` the absolute error is used:
>>> 1/pi4
0.3183
>>> abs(1/pi4 - 0.3183)/(1/pi4)
3.07371499106316e-5
>>> abs(1/pi4 - 0.3183)
9.78393554684764e-6
>>> comp(1/pi4, 0.3183, 1e-5)
True
To see if the absolute error between ``z1`` and ``z2`` is less
than or equal to ``tol``, call this as ``comp(z1 - z2, 0, tol)``
or ``comp(z1 - z2, tol=tol)``:
>>> abs(pi4 - 3.14)
0.00160156249999988
>>> comp(pi4 - 3.14, 0, .002)
True
>>> comp(pi4 - 3.14, 0, .001)
False
"""
if type(z2) is str:
if not pure_complex(z1, or_real=True):
raise ValueError('when z2 is a str z1 must be a Number')
return str(z1) == z2
if not z1:
z1, z2 = z2, z1
if not z1:
return True
if not tol:
a, b = z1, z2
if tol == '':
return str(a) == str(b)
if tol is None:
a, b = sympify(a), sympify(b)
if not all(i.is_number for i in (a, b)):
raise ValueError('expecting 2 numbers')
fa = a.atoms(Float)
fb = b.atoms(Float)
if not fa and not fb:
# no floats -- compare exactly
return a == b
# get a to be pure_complex
for do in range(2):
ca = pure_complex(a, or_real=True)
if not ca:
if fa:
a = a.n(prec_to_dps(min([i._prec for i in fa])))
ca = pure_complex(a, or_real=True)
break
else:
fa, fb = fb, fa
a, b = b, a
cb = pure_complex(b)
if not cb and fb:
b = b.n(prec_to_dps(min([i._prec for i in fb])))
cb = pure_complex(b, or_real=True)
if ca and cb and (ca[1] or cb[1]):
return all(comp(i, j) for i, j in zip(ca, cb))
tol = 10**prec_to_dps(min(a._prec, getattr(b, '_prec', a._prec)))
return int(abs(a - b)*tol) <= 5
diff = abs(z1 - z2)
az1 = abs(z1)
if z2 and az1 > 1:
return diff/az1 <= tol
else:
return diff <= tol
def mpf_norm(mpf, prec):
"""Return the mpf tuple normalized appropriately for the indicated
precision after doing a check to see if zero should be returned or
not when the mantissa is 0. ``mpf_normlize`` always assumes that this
is zero, but it may not be since the mantissa for mpf's values "+inf",
"-inf" and "nan" have a mantissa of zero, too.
Note: this is not intended to validate a given mpf tuple, so sending
mpf tuples that were not created by mpmath may produce bad results. This
is only a wrapper to ``mpf_normalize`` which provides the check for non-
zero mpfs that have a 0 for the mantissa.
"""
sign, man, expt, bc = mpf
if not man:
# hack for mpf_normalize which does not do this;
# it assumes that if man is zero the result is 0
# (see issue 6639)
if not bc:
return fzero
else:
# don't change anything; this should already
# be a well formed mpf tuple
return mpf
# Necessary if mpmath is using the gmpy backend
from mpmath.libmp.backend import MPZ
rv = mpf_normalize(sign, MPZ(man), expt, bc, prec, rnd)
return rv
# TODO: we should use the warnings module
_errdict = {"divide": False}
def seterr(divide=False):
"""
Should sympy raise an exception on 0/0 or return a nan?
divide == True .... raise an exception
divide == False ... return nan
"""
if _errdict["divide"] != divide:
clear_cache()
_errdict["divide"] = divide
def _as_integer_ratio(p):
neg_pow, man, expt, bc = getattr(p, '_mpf_', mpmath.mpf(p)._mpf_)
p = [1, -1][neg_pow % 2]*man
if expt < 0:
q = 2**-expt
else:
q = 1
p *= 2**expt
return int(p), int(q)
def _decimal_to_Rational_prec(dec):
"""Convert an ordinary decimal instance to a Rational."""
if not dec.is_finite():
raise TypeError("dec must be finite, got %s." % dec)
s, d, e = dec.as_tuple()
prec = len(d)
if e >= 0: # it's an integer
rv = Integer(int(dec))
else:
s = (-1)**s
d = sum([di*10**i for i, di in enumerate(reversed(d))])
rv = Rational(s*d, 10**-e)
return rv, prec
_floatpat = regex.compile(r"[-+]?((\d*\.\d+)|(\d+\.?))")
def _literal_float(f):
"""Return True if n starts like a floating point number."""
return bool(_floatpat.match(f))
# (a,b) -> gcd(a,b)
# TODO caching with decorator, but not to degrade performance
@lru_cache(1024)
def igcd(*args):
"""Computes nonnegative integer greatest common divisor.
Explanation
===========
The algorithm is based on the well known Euclid's algorithm. To
improve speed, igcd() has its own caching mechanism implemented.
Examples
========
>>> from sympy.core.numbers import igcd
>>> igcd(2, 4)
2
>>> igcd(5, 10, 15)
5
"""
if len(args) < 2:
raise TypeError(
'igcd() takes at least 2 arguments (%s given)' % len(args))
args_temp = [abs(as_int(i)) for i in args]
if 1 in args_temp:
return 1
a = args_temp.pop()
if HAS_GMPY: # Using gmpy if present to speed up.
for b in args_temp:
a = gmpy.gcd(a, b) if b else a
return as_int(a)
for b in args_temp:
a = math.gcd(a, b)
return a
igcd2 = math.gcd
def igcd_lehmer(a, b):
"""Computes greatest common divisor of two integers.
Explanation
===========
Euclid's algorithm for the computation of the greatest
common divisor gcd(a, b) of two (positive) integers
a and b is based on the division identity
a = q*b + r,
where the quotient q and the remainder r are integers
and 0 <= r < b. Then each common divisor of a and b
divides r, and it follows that gcd(a, b) == gcd(b, r).
The algorithm works by constructing the sequence
r0, r1, r2, ..., where r0 = a, r1 = b, and each rn
is the remainder from the division of the two preceding
elements.
In Python, q = a // b and r = a % b are obtained by the
floor division and the remainder operations, respectively.
These are the most expensive arithmetic operations, especially
for large a and b.
Lehmer's algorithm is based on the observation that the quotients
qn = r(n-1) // rn are in general small integers even
when a and b are very large. Hence the quotients can be
usually determined from a relatively small number of most
significant bits.
The efficiency of the algorithm is further enhanced by not
computing each long remainder in Euclid's sequence. The remainders
are linear combinations of a and b with integer coefficients
derived from the quotients. The coefficients can be computed
as far as the quotients can be determined from the chosen
most significant parts of a and b. Only then a new pair of
consecutive remainders is computed and the algorithm starts
anew with this pair.
References
==========
.. [1] https://en.wikipedia.org/wiki/Lehmer%27s_GCD_algorithm
"""
a, b = abs(as_int(a)), abs(as_int(b))
if a < b:
a, b = b, a
# The algorithm works by using one or two digit division
# whenever possible. The outer loop will replace the
# pair (a, b) with a pair of shorter consecutive elements
# of the Euclidean gcd sequence until a and b
# fit into two Python (long) int digits.
nbits = 2*sys.int_info.bits_per_digit
while a.bit_length() > nbits and b != 0:
# Quotients are mostly small integers that can
# be determined from most significant bits.
n = a.bit_length() - nbits
x, y = int(a >> n), int(b >> n) # most significant bits
# Elements of the Euclidean gcd sequence are linear
# combinations of a and b with integer coefficients.
# Compute the coefficients of consecutive pairs
# a' = A*a + B*b, b' = C*a + D*b
# using small integer arithmetic as far as possible.
A, B, C, D = 1, 0, 0, 1 # initial values
while True:
# The coefficients alternate in sign while looping.
# The inner loop combines two steps to keep track
# of the signs.
# At this point we have
# A > 0, B <= 0, C <= 0, D > 0,
# x' = x + B <= x < x" = x + A,
# y' = y + C <= y < y" = y + D,
# and
# x'*N <= a' < x"*N, y'*N <= b' < y"*N,
# where N = 2**n.
# Now, if y' > 0, and x"//y' and x'//y" agree,
# then their common value is equal to q = a'//b'.
# In addition,
# x'%y" = x' - q*y" < x" - q*y' = x"%y',
# and
# (x'%y")*N < a'%b' < (x"%y')*N.
# On the other hand, we also have x//y == q,
# and therefore
# x'%y" = x + B - q*(y + D) = x%y + B',
# x"%y' = x + A - q*(y + C) = x%y + A',
# where
# B' = B - q*D < 0, A' = A - q*C > 0.
if y + C <= 0:
break
q = (x + A) // (y + C)
# Now x'//y" <= q, and equality holds if
# x' - q*y" = (x - q*y) + (B - q*D) >= 0.
# This is a minor optimization to avoid division.
x_qy, B_qD = x - q*y, B - q*D
if x_qy + B_qD < 0:
break
# Next step in the Euclidean sequence.
x, y = y, x_qy
A, B, C, D = C, D, A - q*C, B_qD
# At this point the signs of the coefficients
# change and their roles are interchanged.
# A <= 0, B > 0, C > 0, D < 0,
# x' = x + A <= x < x" = x + B,
# y' = y + D < y < y" = y + C.
if y + D <= 0:
break
q = (x + B) // (y + D)
x_qy, A_qC = x - q*y, A - q*C
if x_qy + A_qC < 0:
break
x, y = y, x_qy
A, B, C, D = C, D, A_qC, B - q*D
# Now the conditions on top of the loop
# are again satisfied.
# A > 0, B < 0, C < 0, D > 0.
if B == 0:
# This can only happen when y == 0 in the beginning
# and the inner loop does nothing.
# Long division is forced.
a, b = b, a % b
continue
# Compute new long arguments using the coefficients.
a, b = A*a + B*b, C*a + D*b
# Small divisors. Finish with the standard algorithm.
while b:
a, b = b, a % b
return a
def ilcm(*args):
"""Computes integer least common multiple.
Examples
========
>>> from sympy.core.numbers import ilcm
>>> ilcm(5, 10)
10
>>> ilcm(7, 3)
21
>>> ilcm(5, 10, 15)
30
"""
if len(args) < 2:
raise TypeError(
'ilcm() takes at least 2 arguments (%s given)' % len(args))
if 0 in args:
return 0
a = args[0]
for b in args[1:]:
a = a // igcd(a, b) * b # since gcd(a,b) | a
return a
def igcdex(a, b):
"""Returns x, y, g such that g = x*a + y*b = gcd(a, b).
Examples
========
>>> from sympy.core.numbers import igcdex
>>> igcdex(2, 3)
(-1, 1, 1)
>>> igcdex(10, 12)
(-1, 1, 2)
>>> x, y, g = igcdex(100, 2004)
>>> x, y, g
(-20, 1, 4)
>>> x*100 + y*2004
4
"""
if (not a) and (not b):
return (0, 1, 0)
if not a:
return (0, b//abs(b), abs(b))
if not b:
return (a//abs(a), 0, abs(a))
if a < 0:
a, x_sign = -a, -1
else:
x_sign = 1
if b < 0:
b, y_sign = -b, -1
else:
y_sign = 1
x, y, r, s = 1, 0, 0, 1
while b:
(c, q) = (a % b, a // b)
(a, b, r, s, x, y) = (b, c, x - q*r, y - q*s, r, s)
return (x*x_sign, y*y_sign, a)
def mod_inverse(a, m):
"""
Return the number c such that, (a * c) = 1 (mod m)
where c has the same sign as m. If no such value exists,
a ValueError is raised.
Examples
========
>>> from sympy import S
>>> from sympy.core.numbers import mod_inverse
Suppose we wish to find multiplicative inverse x of
3 modulo 11. This is the same as finding x such
that 3 * x = 1 (mod 11). One value of x that satisfies
this congruence is 4. Because 3 * 4 = 12 and 12 = 1 (mod 11).
This is the value returned by mod_inverse:
>>> mod_inverse(3, 11)
4
>>> mod_inverse(-3, 11)
7
When there is a common factor between the numerators of
``a`` and ``m`` the inverse does not exist:
>>> mod_inverse(2, 4)
Traceback (most recent call last):
...
ValueError: inverse of 2 mod 4 does not exist
>>> mod_inverse(S(2)/7, S(5)/2)
7/2
References
==========
.. [1] https://en.wikipedia.org/wiki/Modular_multiplicative_inverse
.. [2] https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
"""
c = None
try:
a, m = as_int(a), as_int(m)
if m != 1 and m != -1:
x, y, g = igcdex(a, m)
if g == 1:
c = x % m
except ValueError:
a, m = sympify(a), sympify(m)
if not (a.is_number and m.is_number):
raise TypeError(filldedent('''
Expected numbers for arguments; symbolic `mod_inverse`
is not implemented
but symbolic expressions can be handled with the
similar function,
sympy.polys.polytools.invert'''))
big = (m > 1)
if not (big is S.true or big is S.false):
raise ValueError('m > 1 did not evaluate; try to simplify %s' % m)
elif big:
c = 1/a
if c is None:
raise ValueError('inverse of %s (mod %s) does not exist' % (a, m))
return c
class Number(AtomicExpr):
"""Represents atomic numbers in SymPy.
Explanation
===========
Floating point numbers are represented by the Float class.
Rational numbers (of any size) are represented by the Rational class.
Integer numbers (of any size) are represented by the Integer class.
Float and Rational are subclasses of Number; Integer is a subclass
of Rational.
For example, ``2/3`` is represented as ``Rational(2, 3)`` which is
a different object from the floating point number obtained with
Python division ``2/3``. Even for numbers that are exactly
represented in binary, there is a difference between how two forms,
such as ``Rational(1, 2)`` and ``Float(0.5)``, are used in SymPy.
The rational form is to be preferred in symbolic computations.
Other kinds of numbers, such as algebraic numbers ``sqrt(2)`` or
complex numbers ``3 + 4*I``, are not instances of Number class as
they are not atomic.
See Also
========
Float, Integer, Rational
"""
is_commutative = True
is_number = True
is_Number = True
__slots__ = ()
# Used to make max(x._prec, y._prec) return x._prec when only x is a float
_prec = -1
kind = NumberKind
def __new__(cls, *obj):
if len(obj) == 1:
obj = obj[0]
if isinstance(obj, Number):
return obj
if isinstance(obj, SYMPY_INTS):
return Integer(obj)
if isinstance(obj, tuple) and len(obj) == 2:
return Rational(*obj)
if isinstance(obj, (float, mpmath.mpf, decimal.Decimal)):
return Float(obj)
if isinstance(obj, str):
_obj = obj.lower() # float('INF') == float('inf')
if _obj == 'nan':
return S.NaN
elif _obj == 'inf':
return S.Infinity
elif _obj == '+inf':
return S.Infinity
elif _obj == '-inf':
return S.NegativeInfinity
val = sympify(obj)
if isinstance(val, Number):
return val
else:
raise ValueError('String "%s" does not denote a Number' % obj)
msg = "expected str|int|long|float|Decimal|Number object but got %r"
raise TypeError(msg % type(obj).__name__)
def invert(self, other, *gens, **args):
from sympy.polys.polytools import invert
if getattr(other, 'is_number', True):
return mod_inverse(self, other)
return invert(self, other, *gens, **args)
def __divmod__(self, other):
from .containers import Tuple
from sympy.functions.elementary.complexes import sign
try:
other = Number(other)
if self.is_infinite or S.NaN in (self, other):
return (S.NaN, S.NaN)
except TypeError:
return NotImplemented
if not other:
raise ZeroDivisionError('modulo by zero')
if self.is_Integer and other.is_Integer:
return Tuple(*divmod(self.p, other.p))
elif isinstance(other, Float):
rat = self/Rational(other)
else:
rat = self/other
if other.is_finite:
w = int(rat) if rat >= 0 else int(rat) - 1
r = self - other*w
else:
w = 0 if not self or (sign(self) == sign(other)) else -1
r = other if w else self
return Tuple(w, r)
def __rdivmod__(self, other):
try:
other = Number(other)
except TypeError:
return NotImplemented
return divmod(other, self)
def _as_mpf_val(self, prec):
"""Evaluation of mpf tuple accurate to at least prec bits."""
raise NotImplementedError('%s needs ._as_mpf_val() method' %
(self.__class__.__name__))
def _eval_evalf(self, prec):
return Float._new(self._as_mpf_val(prec), prec)
def _as_mpf_op(self, prec):
prec = max(prec, self._prec)
return self._as_mpf_val(prec), prec
def __float__(self):
return mlib.to_float(self._as_mpf_val(53))
def floor(self):
raise NotImplementedError('%s needs .floor() method' %
(self.__class__.__name__))
def ceiling(self):
raise NotImplementedError('%s needs .ceiling() method' %
(self.__class__.__name__))
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
def _eval_conjugate(self):
return self
def _eval_order(self, *symbols):
from sympy import Order
# Order(5, x, y) -> Order(1,x,y)
return Order(S.One, *symbols)
def _eval_subs(self, old, new):
if old == -self:
return -new
return self # there is no other possibility
def _eval_is_finite(self):
return True
@classmethod
def class_key(cls):
return 1, 0, 'Number'
@cacheit
def sort_key(self, order=None):
return self.class_key(), (0, ()), (), self
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NaN:
return S.NaN
elif other is S.Infinity:
return S.Infinity
elif other is S.NegativeInfinity:
return S.NegativeInfinity
return AtomicExpr.__add__(self, other)
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NaN:
return S.NaN
elif other is S.Infinity:
return S.NegativeInfinity
elif other is S.NegativeInfinity:
return S.Infinity
return AtomicExpr.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NaN:
return S.NaN
elif other is S.Infinity:
if self.is_zero:
return S.NaN
elif self.is_positive:
return S.Infinity
else:
return S.NegativeInfinity
elif other is S.NegativeInfinity:
if self.is_zero:
return S.NaN
elif self.is_positive:
return S.NegativeInfinity
else:
return S.Infinity
elif isinstance(other, Tuple):
return NotImplemented
return AtomicExpr.__mul__(self, other)
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NaN:
return S.NaN
elif other is S.Infinity or other is S.NegativeInfinity:
return S.Zero
return AtomicExpr.__truediv__(self, other)
def __eq__(self, other):
raise NotImplementedError('%s needs .__eq__() method' %
(self.__class__.__name__))
def __ne__(self, other):
raise NotImplementedError('%s needs .__ne__() method' %
(self.__class__.__name__))
def __lt__(self, other):
try:
other = _sympify(other)
except SympifyError:
raise TypeError("Invalid comparison %s < %s" % (self, other))
raise NotImplementedError('%s needs .__lt__() method' %
(self.__class__.__name__))
def __le__(self, other):
try:
other = _sympify(other)
except SympifyError:
raise TypeError("Invalid comparison %s <= %s" % (self, other))
raise NotImplementedError('%s needs .__le__() method' %
(self.__class__.__name__))
def __gt__(self, other):
try:
other = _sympify(other)
except SympifyError:
raise TypeError("Invalid comparison %s > %s" % (self, other))
return _sympify(other).__lt__(self)
def __ge__(self, other):
try:
other = _sympify(other)
except SympifyError:
raise TypeError("Invalid comparison %s >= %s" % (self, other))
return _sympify(other).__le__(self)
def __hash__(self):
return super().__hash__()
def is_constant(self, *wrt, **flags):
return True
def as_coeff_mul(self, *deps, rational=True, **kwargs):
# a -> c*t
if self.is_Rational or not rational:
return self, tuple()
elif self.is_negative:
return S.NegativeOne, (-self,)
return S.One, (self,)
def as_coeff_add(self, *deps):
# a -> c + t
if self.is_Rational:
return self, tuple()
return S.Zero, (self,)
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product. """
if rational and not self.is_Rational:
return S.One, self
return (self, S.One) if self else (S.One, self)
def as_coeff_Add(self, rational=False):
"""Efficiently extract the coefficient of a summation. """
if not rational:
return self, S.Zero
return S.Zero, self
def gcd(self, other):
"""Compute GCD of `self` and `other`. """
from sympy.polys import gcd
return gcd(self, other)
def lcm(self, other):
"""Compute LCM of `self` and `other`. """
from sympy.polys import lcm
return lcm(self, other)
def cofactors(self, other):
"""Compute GCD and cofactors of `self` and `other`. """
from sympy.polys import cofactors
return cofactors(self, other)
class Float(Number):
"""Represent a floating-point number of arbitrary precision.
Examples
========
>>> from sympy import Float
>>> Float(3.5)
3.50000000000000
>>> Float(3)
3.00000000000000
Creating Floats from strings (and Python ``int`` and ``long``
types) will give a minimum precision of 15 digits, but the
precision will automatically increase to capture all digits
entered.
>>> Float(1)
1.00000000000000
>>> Float(10**20)
100000000000000000000.
>>> Float('1e20')
100000000000000000000.
However, *floating-point* numbers (Python ``float`` types) retain
only 15 digits of precision:
>>> Float(1e20)
1.00000000000000e+20
>>> Float(1.23456789123456789)
1.23456789123457
It may be preferable to enter high-precision decimal numbers
as strings:
>>> Float('1.23456789123456789')
1.23456789123456789
The desired number of digits can also be specified:
>>> Float('1e-3', 3)
0.00100
>>> Float(100, 4)
100.0
Float can automatically count significant figures if a null string
is sent for the precision; spaces or underscores are also allowed. (Auto-
counting is only allowed for strings, ints and longs).
>>> Float('123 456 789.123_456', '')
123456789.123456
>>> Float('12e-3', '')
0.012
>>> Float(3, '')
3.
If a number is written in scientific notation, only the digits before the
exponent are considered significant if a decimal appears, otherwise the
"e" signifies only how to move the decimal:
>>> Float('60.e2', '') # 2 digits significant
6.0e+3
>>> Float('60e2', '') # 4 digits significant
6000.
>>> Float('600e-2', '') # 3 digits significant
6.00
Notes
=====
Floats are inexact by their nature unless their value is a binary-exact
value.
>>> approx, exact = Float(.1, 1), Float(.125, 1)
For calculation purposes, evalf needs to be able to change the precision
but this will not increase the accuracy of the inexact value. The
following is the most accurate 5-digit approximation of a value of 0.1
that had only 1 digit of precision:
>>> approx.evalf(5)
0.099609
By contrast, 0.125 is exact in binary (as it is in base 10) and so it
can be passed to Float or evalf to obtain an arbitrary precision with
matching accuracy:
>>> Float(exact, 5)
0.12500
>>> exact.evalf(20)
0.12500000000000000000
Trying to make a high-precision Float from a float is not disallowed,
but one must keep in mind that the *underlying float* (not the apparent
decimal value) is being obtained with high precision. For example, 0.3
does not have a finite binary representation. The closest rational is
the fraction 5404319552844595/2**54. So if you try to obtain a Float of
0.3 to 20 digits of precision you will not see the same thing as 0.3
followed by 19 zeros:
>>> Float(0.3, 20)
0.29999999999999998890
If you want a 20-digit value of the decimal 0.3 (not the floating point
approximation of 0.3) you should send the 0.3 as a string. The underlying
representation is still binary but a higher precision than Python's float
is used:
>>> Float('0.3', 20)
0.30000000000000000000
Although you can increase the precision of an existing Float using Float
it will not increase the accuracy -- the underlying value is not changed:
>>> def show(f): # binary rep of Float
... from sympy import Mul, Pow
... s, m, e, b = f._mpf_
... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False)
... print('%s at prec=%s' % (v, f._prec))
...
>>> t = Float('0.3', 3)
>>> show(t)
4915/2**14 at prec=13
>>> show(Float(t, 20)) # higher prec, not higher accuracy
4915/2**14 at prec=70
>>> show(Float(t, 2)) # lower prec
307/2**10 at prec=10
The same thing happens when evalf is used on a Float:
>>> show(t.evalf(20))
4915/2**14 at prec=70
>>> show(t.evalf(2))
307/2**10 at prec=10
Finally, Floats can be instantiated with an mpf tuple (n, c, p) to
produce the number (-1)**n*c*2**p:
>>> n, c, p = 1, 5, 0
>>> (-1)**n*c*2**p
-5
>>> Float((1, 5, 0))
-5.00000000000000
An actual mpf tuple also contains the number of bits in c as the last
element of the tuple:
>>> _._mpf_
(1, 5, 0, 3)
This is not needed for instantiation and is not the same thing as the
precision. The mpf tuple and the precision are two separate quantities
that Float tracks.
In SymPy, a Float is a number that can be computed with arbitrary
precision. Although floating point 'inf' and 'nan' are not such
numbers, Float can create these numbers:
>>> Float('-inf')
-oo
>>> _.is_Float
False
"""
__slots__ = ('_mpf_', '_prec')
# A Float represents many real numbers,
# both rational and irrational.
is_rational = None
is_irrational = None
is_number = True
is_real = True
is_extended_real = True
is_Float = True
def __new__(cls, num, dps=None, prec=None, precision=None):
if prec is not None:
SymPyDeprecationWarning(
feature="Using 'prec=XX' to denote decimal precision",
useinstead="'dps=XX' for decimal precision and 'precision=XX' "\
"for binary precision",
issue=12820,
deprecated_since_version="1.1").warn()
dps = prec
del prec # avoid using this deprecated kwarg
if dps is not None and precision is not None:
raise ValueError('Both decimal and binary precision supplied. '
'Supply only one. ')
if isinstance(num, str):
# Float accepts spaces as digit separators
num = num.replace(' ', '').lower()
# in Py 3.6
# underscores are allowed. In anticipation of that, we ignore
# legally placed underscores
if '_' in num:
parts = num.split('_')
if not (all(parts) and
all(parts[i][-1].isdigit()
for i in range(0, len(parts), 2)) and
all(parts[i][0].isdigit()
for i in range(1, len(parts), 2))):
# copy Py 3.6 error
raise ValueError("could not convert string to float: '%s'" % num)
num = ''.join(parts)
if num.startswith('.') and len(num) > 1:
num = '0' + num
elif num.startswith('-.') and len(num) > 2:
num = '-0.' + num[2:]
elif num in ('inf', '+inf'):
return S.Infinity
elif num == '-inf':
return S.NegativeInfinity
elif isinstance(num, float) and num == 0:
num = '0'
elif isinstance(num, float) and num == float('inf'):
return S.Infinity
elif isinstance(num, float) and num == float('-inf'):
return S.NegativeInfinity
elif isinstance(num, float) and num == float('nan'):
return S.NaN
elif isinstance(num, (SYMPY_INTS, Integer)):
num = str(num)
elif num is S.Infinity:
return num
elif num is S.NegativeInfinity:
return num
elif num is S.NaN:
return num
elif _is_numpy_instance(num): # support for numpy datatypes
num = _convert_numpy_types(num)
elif isinstance(num, mpmath.mpf):
if precision is None:
if dps is None:
precision = num.context.prec
num = num._mpf_
if dps is None and precision is None:
dps = 15
if isinstance(num, Float):
return num
if isinstance(num, str) and _literal_float(num):
try:
Num = decimal.Decimal(num)
except decimal.InvalidOperation:
pass
else:
isint = '.' not in num
num, dps = _decimal_to_Rational_prec(Num)
if num.is_Integer and isint:
dps = max(dps, len(str(num).lstrip('-')))
dps = max(15, dps)
precision = mlib.libmpf.dps_to_prec(dps)
elif precision == '' and dps is None or precision is None and dps == '':
if not isinstance(num, str):
raise ValueError('The null string can only be used when '
'the number to Float is passed as a string or an integer.')
ok = None
if _literal_float(num):
try:
Num = decimal.Decimal(num)
except decimal.InvalidOperation:
pass
else:
isint = '.' not in num
num, dps = _decimal_to_Rational_prec(Num)
if num.is_Integer and isint:
dps = max(dps, len(str(num).lstrip('-')))
precision = mlib.libmpf.dps_to_prec(dps)
ok = True
if ok is None:
raise ValueError('string-float not recognized: %s' % num)
# decimal precision(dps) is set and maybe binary precision(precision)
# as well.From here on binary precision is used to compute the Float.
# Hence, if supplied use binary precision else translate from decimal
# precision.
if precision is None or precision == '':
precision = mlib.libmpf.dps_to_prec(dps)
precision = int(precision)
if isinstance(num, float):
_mpf_ = mlib.from_float(num, precision, rnd)
elif isinstance(num, str):
_mpf_ = mlib.from_str(num, precision, rnd)
elif isinstance(num, decimal.Decimal):
if num.is_finite():
_mpf_ = mlib.from_str(str(num), precision, rnd)
elif num.is_nan():
return S.NaN
elif num.is_infinite():
if num > 0:
return S.Infinity
return S.NegativeInfinity
else:
raise ValueError("unexpected decimal value %s" % str(num))
elif isinstance(num, tuple) and len(num) in (3, 4):
if type(num[1]) is str:
# it's a hexadecimal (coming from a pickled object)
# assume that it is in standard form
num = list(num)
# If we're loading an object pickled in Python 2 into
# Python 3, we may need to strip a tailing 'L' because
# of a shim for int on Python 3, see issue #13470.
if num[1].endswith('L'):
num[1] = num[1][:-1]
num[1] = MPZ(num[1], 16)
_mpf_ = tuple(num)
else:
if len(num) == 4:
# handle normalization hack
return Float._new(num, precision)
else:
if not all((
num[0] in (0, 1),
num[1] >= 0,
all(type(i) in (int, int) for i in num)
)):
raise ValueError('malformed mpf: %s' % (num,))
# don't compute number or else it may
# over/underflow
return Float._new(
(num[0], num[1], num[2], bitcount(num[1])),
precision)
else:
try:
_mpf_ = num._as_mpf_val(precision)
except (NotImplementedError, AttributeError):
_mpf_ = mpmath.mpf(num, prec=precision)._mpf_
return cls._new(_mpf_, precision, zero=False)
@classmethod
def _new(cls, _mpf_, _prec, zero=True):
# special cases
if zero and _mpf_ == fzero:
return S.Zero # Float(0) -> 0.0; Float._new((0,0,0,0)) -> 0
elif _mpf_ == _mpf_nan:
return S.NaN
elif _mpf_ == _mpf_inf:
return S.Infinity
elif _mpf_ == _mpf_ninf:
return S.NegativeInfinity
obj = Expr.__new__(cls)
obj._mpf_ = mpf_norm(_mpf_, _prec)
obj._prec = _prec
return obj
# mpz can't be pickled
def __getnewargs_ex__(self):
return ((mlib.to_pickable(self._mpf_),), {'precision': self._prec})
def _hashable_content(self):
return (self._mpf_, self._prec)
def floor(self):
return Integer(int(mlib.to_int(
mlib.mpf_floor(self._mpf_, self._prec))))
def ceiling(self):
return Integer(int(mlib.to_int(
mlib.mpf_ceil(self._mpf_, self._prec))))
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
@property
def num(self):
return mpmath.mpf(self._mpf_)
def _as_mpf_val(self, prec):
rv = mpf_norm(self._mpf_, prec)
if rv != self._mpf_ and self._prec == prec:
debug(self._mpf_, rv)
return rv
def _as_mpf_op(self, prec):
return self._mpf_, max(prec, self._prec)
def _eval_is_finite(self):
if self._mpf_ in (_mpf_inf, _mpf_ninf):
return False
return True
def _eval_is_infinite(self):
if self._mpf_ in (_mpf_inf, _mpf_ninf):
return True
return False
def _eval_is_integer(self):
return self._mpf_ == fzero
def _eval_is_negative(self):
if self._mpf_ == _mpf_ninf or self._mpf_ == _mpf_inf:
return False
return self.num < 0
def _eval_is_positive(self):
if self._mpf_ == _mpf_ninf or self._mpf_ == _mpf_inf:
return False
return self.num > 0
def _eval_is_extended_negative(self):
if self._mpf_ == _mpf_ninf:
return True
if self._mpf_ == _mpf_inf:
return False
return self.num < 0
def _eval_is_extended_positive(self):
if self._mpf_ == _mpf_inf:
return True
if self._mpf_ == _mpf_ninf:
return False
return self.num > 0
def _eval_is_zero(self):
return self._mpf_ == fzero
def __bool__(self):
return self._mpf_ != fzero
def __neg__(self):
return Float._new(mlib.mpf_neg(self._mpf_), self._prec)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_add(self._mpf_, rhs, prec, rnd), prec)
return Number.__add__(self, other)
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_sub(self._mpf_, rhs, prec, rnd), prec)
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_mul(self._mpf_, rhs, prec, rnd), prec)
return Number.__mul__(self, other)
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and other != 0 and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_div(self._mpf_, rhs, prec, rnd), prec)
return Number.__truediv__(self, other)
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if isinstance(other, Rational) and other.q != 1 and global_parameters.evaluate:
# calculate mod with Rationals, *then* round the result
return Float(Rational.__mod__(Rational(self), other),
precision=self._prec)
if isinstance(other, Float) and global_parameters.evaluate:
r = self/other
if r == int(r):
return Float(0, precision=max(self._prec, other._prec))
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_mod(self._mpf_, rhs, prec, rnd), prec)
return Number.__mod__(self, other)
@_sympifyit('other', NotImplemented)
def __rmod__(self, other):
if isinstance(other, Float) and global_parameters.evaluate:
return other.__mod__(self)
if isinstance(other, Number) and global_parameters.evaluate:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_mod(rhs, self._mpf_, prec, rnd), prec)
return Number.__rmod__(self, other)
def _eval_power(self, expt):
"""
expt is symbolic object but not equal to 0, 1
(-p)**r -> exp(r*log(-p)) -> exp(r*(log(p) + I*Pi)) ->
-> p**r*(sin(Pi*r) + cos(Pi*r)*I)
"""
if self == 0:
if expt.is_positive:
return S.Zero
if expt.is_negative:
return S.Infinity
if isinstance(expt, Number):
if isinstance(expt, Integer):
prec = self._prec
return Float._new(
mlib.mpf_pow_int(self._mpf_, expt.p, prec, rnd), prec)
elif isinstance(expt, Rational) and \
expt.p == 1 and expt.q % 2 and self.is_negative:
return Pow(S.NegativeOne, expt, evaluate=False)*(
-self)._eval_power(expt)
expt, prec = expt._as_mpf_op(self._prec)
mpfself = self._mpf_
try:
y = mpf_pow(mpfself, expt, prec, rnd)
return Float._new(y, prec)
except mlib.ComplexResult:
re, im = mlib.mpc_pow(
(mpfself, fzero), (expt, fzero), prec, rnd)
return Float._new(re, prec) + \
Float._new(im, prec)*S.ImaginaryUnit
def __abs__(self):
return Float._new(mlib.mpf_abs(self._mpf_), self._prec)
def __int__(self):
if self._mpf_ == fzero:
return 0
return int(mlib.to_int(self._mpf_)) # uses round_fast = round_down
def __eq__(self, other):
from sympy.logic.boolalg import Boolean
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if isinstance(other, Boolean):
return False
if other.is_NumberSymbol:
if other.is_irrational:
return False
return other.__eq__(self)
if other.is_Float:
# comparison is exact
# so Float(.1, 3) != Float(.1, 33)
return self._mpf_ == other._mpf_
if other.is_Rational:
return other.__eq__(self)
if other.is_Number:
# numbers should compare at the same precision;
# all _as_mpf_val routines should be sure to abide
# by the request to change the prec if necessary; if
# they don't, the equality test will fail since it compares
# the mpf tuples
ompf = other._as_mpf_val(self._prec)
return bool(mlib.mpf_eq(self._mpf_, ompf))
if not self:
return not other
return False # Float != non-Number
def __ne__(self, other):
return not self == other
def _Frel(self, other, op):
from sympy.core.numbers import prec_to_dps
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Rational:
# test self*other.q <?> other.p without losing precision
'''
>>> f = Float(.1,2)
>>> i = 1234567890
>>> (f*i)._mpf_
(0, 471, 18, 9)
>>> mlib.mpf_mul(f._mpf_, mlib.from_int(i))
(0, 505555550955, -12, 39)
'''
smpf = mlib.mpf_mul(self._mpf_, mlib.from_int(other.q))
ompf = mlib.from_int(other.p)
return _sympify(bool(op(smpf, ompf)))
elif other.is_Float:
return _sympify(bool(
op(self._mpf_, other._mpf_)))
elif other.is_comparable and other not in (
S.Infinity, S.NegativeInfinity):
other = other.evalf(prec_to_dps(self._prec))
if other._prec > 1:
if other.is_Number:
return _sympify(bool(
op(self._mpf_, other._as_mpf_val(self._prec))))
def __gt__(self, other):
if isinstance(other, NumberSymbol):
return other.__lt__(self)
rv = self._Frel(other, mlib.mpf_gt)
if rv is None:
return Expr.__gt__(self, other)
return rv
def __ge__(self, other):
if isinstance(other, NumberSymbol):
return other.__le__(self)
rv = self._Frel(other, mlib.mpf_ge)
if rv is None:
return Expr.__ge__(self, other)
return rv
def __lt__(self, other):
if isinstance(other, NumberSymbol):
return other.__gt__(self)
rv = self._Frel(other, mlib.mpf_lt)
if rv is None:
return Expr.__lt__(self, other)
return rv
def __le__(self, other):
if isinstance(other, NumberSymbol):
return other.__ge__(self)
rv = self._Frel(other, mlib.mpf_le)
if rv is None:
return Expr.__le__(self, other)
return rv
def __hash__(self):
return super().__hash__()
def epsilon_eq(self, other, epsilon="1e-15"):
return abs(self - other) < Float(epsilon)
def _sage_(self):
import sage.all as sage
return sage.RealNumber(str(self))
def __format__(self, format_spec):
return format(decimal.Decimal(str(self)), format_spec)
# Add sympify converters
converter[float] = converter[decimal.Decimal] = Float
# this is here to work nicely in Sage
RealNumber = Float
class Rational(Number):
"""Represents rational numbers (p/q) of any size.
Examples
========
>>> from sympy import Rational, nsimplify, S, pi
>>> Rational(1, 2)
1/2
Rational is unprejudiced in accepting input. If a float is passed, the
underlying value of the binary representation will be returned:
>>> Rational(.5)
1/2
>>> Rational(.2)
3602879701896397/18014398509481984
If the simpler representation of the float is desired then consider
limiting the denominator to the desired value or convert the float to
a string (which is roughly equivalent to limiting the denominator to
10**12):
>>> Rational(str(.2))
1/5
>>> Rational(.2).limit_denominator(10**12)
1/5
An arbitrarily precise Rational is obtained when a string literal is
passed:
>>> Rational("1.23")
123/100
>>> Rational('1e-2')
1/100
>>> Rational(".1")
1/10
>>> Rational('1e-2/3.2')
1/320
The conversion of other types of strings can be handled by
the sympify() function, and conversion of floats to expressions
or simple fractions can be handled with nsimplify:
>>> S('.[3]') # repeating digits in brackets
1/3
>>> S('3**2/10') # general expressions
9/10
>>> nsimplify(.3) # numbers that have a simple form
3/10
But if the input does not reduce to a literal Rational, an error will
be raised:
>>> Rational(pi)
Traceback (most recent call last):
...
TypeError: invalid input: pi
Low-level
---------
Access numerator and denominator as .p and .q:
>>> r = Rational(3, 4)
>>> r
3/4
>>> r.p
3
>>> r.q
4
Note that p and q return integers (not SymPy Integers) so some care
is needed when using them in expressions:
>>> r.p/r.q
0.75
See Also
========
sympy.core.sympify.sympify, sympy.simplify.simplify.nsimplify
"""
is_real = True
is_integer = False
is_rational = True
is_number = True
__slots__ = ('p', 'q')
is_Rational = True
@cacheit
def __new__(cls, p, q=None, gcd=None):
if q is None:
if isinstance(p, Rational):
return p
if isinstance(p, SYMPY_INTS):
pass
else:
if isinstance(p, (float, Float)):
return Rational(*_as_integer_ratio(p))
if not isinstance(p, str):
try:
p = sympify(p)
except (SympifyError, SyntaxError):
pass # error will raise below
else:
if p.count('/') > 1:
raise TypeError('invalid input: %s' % p)
p = p.replace(' ', '')
pq = p.rsplit('/', 1)
if len(pq) == 2:
p, q = pq
fp = fractions.Fraction(p)
fq = fractions.Fraction(q)
p = fp/fq
try:
p = fractions.Fraction(p)
except ValueError:
pass # error will raise below
else:
return Rational(p.numerator, p.denominator, 1)
if not isinstance(p, Rational):
raise TypeError('invalid input: %s' % p)
q = 1
gcd = 1
else:
p = Rational(p)
q = Rational(q)
if isinstance(q, Rational):
p *= q.q
q = q.p
if isinstance(p, Rational):
q *= p.q
p = p.p
# p and q are now integers
if q == 0:
if p == 0:
if _errdict["divide"]:
raise ValueError("Indeterminate 0/0")
else:
return S.NaN
return S.ComplexInfinity
if q < 0:
q = -q
p = -p
if not gcd:
gcd = igcd(abs(p), q)
if gcd > 1:
p //= gcd
q //= gcd
if q == 1:
return Integer(p)
if p == 1 and q == 2:
return S.Half
obj = Expr.__new__(cls)
obj.p = p
obj.q = q
return obj
def limit_denominator(self, max_denominator=1000000):
"""Closest Rational to self with denominator at most max_denominator.
Examples
========
>>> from sympy import Rational
>>> Rational('3.141592653589793').limit_denominator(10)
22/7
>>> Rational('3.141592653589793').limit_denominator(100)
311/99
"""
f = fractions.Fraction(self.p, self.q)
return Rational(f.limit_denominator(fractions.Fraction(int(max_denominator))))
def __getnewargs__(self):
return (self.p, self.q)
def _hashable_content(self):
return (self.p, self.q)
def _eval_is_positive(self):
return self.p > 0
def _eval_is_zero(self):
return self.p == 0
def __neg__(self):
return Rational(-self.p, self.q)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(self.p + self.q*other.p, self.q, 1)
elif isinstance(other, Rational):
#TODO: this can probably be optimized more
return Rational(self.p*other.q + self.q*other.p, self.q*other.q)
elif isinstance(other, Float):
return other + self
else:
return Number.__add__(self, other)
return Number.__add__(self, other)
__radd__ = __add__
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(self.p - self.q*other.p, self.q, 1)
elif isinstance(other, Rational):
return Rational(self.p*other.q - self.q*other.p, self.q*other.q)
elif isinstance(other, Float):
return -other + self
else:
return Number.__sub__(self, other)
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __rsub__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(self.q*other.p - self.p, self.q, 1)
elif isinstance(other, Rational):
return Rational(self.q*other.p - self.p*other.q, self.q*other.q)
elif isinstance(other, Float):
return -self + other
else:
return Number.__rsub__(self, other)
return Number.__rsub__(self, other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(self.p*other.p, self.q, igcd(other.p, self.q))
elif isinstance(other, Rational):
return Rational(self.p*other.p, self.q*other.q, igcd(self.p, other.q)*igcd(self.q, other.p))
elif isinstance(other, Float):
return other*self
else:
return Number.__mul__(self, other)
return Number.__mul__(self, other)
__rmul__ = __mul__
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
if self.p and other.p == S.Zero:
return S.ComplexInfinity
else:
return Rational(self.p, self.q*other.p, igcd(self.p, other.p))
elif isinstance(other, Rational):
return Rational(self.p*other.q, self.q*other.p, igcd(self.p, other.p)*igcd(self.q, other.q))
elif isinstance(other, Float):
return self*(1/other)
else:
return Number.__truediv__(self, other)
return Number.__truediv__(self, other)
@_sympifyit('other', NotImplemented)
def __rtruediv__(self, other):
if global_parameters.evaluate:
if isinstance(other, Integer):
return Rational(other.p*self.q, self.p, igcd(self.p, other.p))
elif isinstance(other, Rational):
return Rational(other.p*self.q, other.q*self.p, igcd(self.p, other.p)*igcd(self.q, other.q))
elif isinstance(other, Float):
return other*(1/self)
else:
return Number.__rtruediv__(self, other)
return Number.__rtruediv__(self, other)
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if global_parameters.evaluate:
if isinstance(other, Rational):
n = (self.p*other.q) // (other.p*self.q)
return Rational(self.p*other.q - n*other.p*self.q, self.q*other.q)
if isinstance(other, Float):
# calculate mod with Rationals, *then* round the answer
return Float(self.__mod__(Rational(other)),
precision=other._prec)
return Number.__mod__(self, other)
return Number.__mod__(self, other)
@_sympifyit('other', NotImplemented)
def __rmod__(self, other):
if isinstance(other, Rational):
return Rational.__mod__(other, self)
return Number.__rmod__(self, other)
def _eval_power(self, expt):
if isinstance(expt, Number):
if isinstance(expt, Float):
return self._eval_evalf(expt._prec)**expt
if expt.is_extended_negative:
# (3/4)**-2 -> (4/3)**2
ne = -expt
if (ne is S.One):
return Rational(self.q, self.p)
if self.is_negative:
return S.NegativeOne**expt*Rational(self.q, -self.p)**ne
else:
return Rational(self.q, self.p)**ne
if expt is S.Infinity: # -oo already caught by test for negative
if self.p > self.q:
# (3/2)**oo -> oo
return S.Infinity
if self.p < -self.q:
# (-3/2)**oo -> oo + I*oo
return S.Infinity + S.Infinity*S.ImaginaryUnit
return S.Zero
if isinstance(expt, Integer):
# (4/3)**2 -> 4**2 / 3**2
return Rational(self.p**expt.p, self.q**expt.p, 1)
if isinstance(expt, Rational):
if self.p != 1:
# (4/3)**(5/6) -> 4**(5/6)*3**(-5/6)
return Integer(self.p)**expt*Integer(self.q)**(-expt)
# as the above caught negative self.p, now self is positive
return Integer(self.q)**Rational(
expt.p*(expt.q - 1), expt.q) / \
Integer(self.q)**Integer(expt.p)
if self.is_extended_negative and expt.is_even:
return (-self)**expt
return
def _as_mpf_val(self, prec):
return mlib.from_rational(self.p, self.q, prec, rnd)
def _mpmath_(self, prec, rnd):
return mpmath.make_mpf(mlib.from_rational(self.p, self.q, prec, rnd))
def __abs__(self):
return Rational(abs(self.p), self.q)
def __int__(self):
p, q = self.p, self.q
if p < 0:
return -int(-p//q)
return int(p//q)
def floor(self):
return Integer(self.p // self.q)
def ceiling(self):
return -Integer(-self.p // self.q)
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
def __eq__(self, other):
from sympy.core.power import integer_log
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if not isinstance(other, Number):
# S(0) == S.false is False
# S(0) == False is True
return False
if not self:
return not other
if other.is_NumberSymbol:
if other.is_irrational:
return False
return other.__eq__(self)
if other.is_Rational:
# a Rational is always in reduced form so will never be 2/4
# so we can just check equivalence of args
return self.p == other.p and self.q == other.q
if other.is_Float:
# all Floats have a denominator that is a power of 2
# so if self doesn't, it can't be equal to other
if self.q & (self.q - 1):
return False
s, m, t = other._mpf_[:3]
if s:
m = -m
if not t:
# other is an odd integer
if not self.is_Integer or self.is_even:
return False
return m == self.p
if t > 0:
# other is an even integer
if not self.is_Integer:
return False
# does m*2**t == self.p
return self.p and not self.p % m and \
integer_log(self.p//m, 2) == (t, True)
# does non-integer s*m/2**-t = p/q?
if self.is_Integer:
return False
return m == self.p and integer_log(self.q, 2) == (-t, True)
return False
def __ne__(self, other):
return not self == other
def _Rrel(self, other, attr):
# if you want self < other, pass self, other, __gt__
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Number:
op = None
s, o = self, other
if other.is_NumberSymbol:
op = getattr(o, attr)
elif other.is_Float:
op = getattr(o, attr)
elif other.is_Rational:
s, o = Integer(s.p*o.q), Integer(s.q*o.p)
op = getattr(o, attr)
if op:
return op(s)
if o.is_number and o.is_extended_real:
return Integer(s.p), s.q*o
def __gt__(self, other):
rv = self._Rrel(other, '__lt__')
if rv is None:
rv = self, other
elif not type(rv) is tuple:
return rv
return Expr.__gt__(*rv)
def __ge__(self, other):
rv = self._Rrel(other, '__le__')
if rv is None:
rv = self, other
elif not type(rv) is tuple:
return rv
return Expr.__ge__(*rv)
def __lt__(self, other):
rv = self._Rrel(other, '__gt__')
if rv is None:
rv = self, other
elif not type(rv) is tuple:
return rv
return Expr.__lt__(*rv)
def __le__(self, other):
rv = self._Rrel(other, '__ge__')
if rv is None:
rv = self, other
elif not type(rv) is tuple:
return rv
return Expr.__le__(*rv)
def __hash__(self):
return super().__hash__()
def factors(self, limit=None, use_trial=True, use_rho=False,
use_pm1=False, verbose=False, visual=False):
"""A wrapper to factorint which return factors of self that are
smaller than limit (or cheap to compute). Special methods of
factoring are disabled by default so that only trial division is used.
"""
from sympy.ntheory import factorrat
return factorrat(self, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose).copy()
@property
def numerator(self):
return self.p
@property
def denominator(self):
return self.q
@_sympifyit('other', NotImplemented)
def gcd(self, other):
if isinstance(other, Rational):
if other == S.Zero:
return other
return Rational(
Integer(igcd(self.p, other.p)),
Integer(ilcm(self.q, other.q)))
return Number.gcd(self, other)
@_sympifyit('other', NotImplemented)
def lcm(self, other):
if isinstance(other, Rational):
return Rational(
self.p // igcd(self.p, other.p) * other.p,
igcd(self.q, other.q))
return Number.lcm(self, other)
def as_numer_denom(self):
return Integer(self.p), Integer(self.q)
def _sage_(self):
import sage.all as sage
return sage.Integer(self.p)/sage.Integer(self.q)
def as_content_primitive(self, radical=False, clear=True):
"""Return the tuple (R, self/R) where R is the positive Rational
extracted from self.
Examples
========
>>> from sympy import S
>>> (S(-3)/2).as_content_primitive()
(3/2, -1)
See docstring of Expr.as_content_primitive for more examples.
"""
if self:
if self.is_positive:
return self, S.One
return -self, S.NegativeOne
return S.One, self
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product. """
return self, S.One
def as_coeff_Add(self, rational=False):
"""Efficiently extract the coefficient of a summation. """
return self, S.Zero
class Integer(Rational):
"""Represents integer numbers of any size.
Examples
========
>>> from sympy import Integer
>>> Integer(3)
3
If a float or a rational is passed to Integer, the fractional part
will be discarded; the effect is of rounding toward zero.
>>> Integer(3.8)
3
>>> Integer(-3.8)
-3
A string is acceptable input if it can be parsed as an integer:
>>> Integer("9" * 20)
99999999999999999999
It is rarely needed to explicitly instantiate an Integer, because
Python integers are automatically converted to Integer when they
are used in SymPy expressions.
"""
q = 1
is_integer = True
is_number = True
is_Integer = True
__slots__ = ('p',)
def _as_mpf_val(self, prec):
return mlib.from_int(self.p, prec, rnd)
def _mpmath_(self, prec, rnd):
return mpmath.make_mpf(self._as_mpf_val(prec))
@cacheit
def __new__(cls, i):
if isinstance(i, str):
i = i.replace(' ', '')
# whereas we cannot, in general, make a Rational from an
# arbitrary expression, we can make an Integer unambiguously
# (except when a non-integer expression happens to round to
# an integer). So we proceed by taking int() of the input and
# let the int routines determine whether the expression can
# be made into an int or whether an error should be raised.
try:
ival = int(i)
except TypeError:
raise TypeError(
"Argument of Integer should be of numeric type, got %s." % i)
# We only work with well-behaved integer types. This converts, for
# example, numpy.int32 instances.
if ival == 1:
return S.One
if ival == -1:
return S.NegativeOne
if ival == 0:
return S.Zero
obj = Expr.__new__(cls)
obj.p = ival
return obj
def __getnewargs__(self):
return (self.p,)
# Arithmetic operations are here for efficiency
def __int__(self):
return self.p
def floor(self):
return Integer(self.p)
def ceiling(self):
return Integer(self.p)
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
def __neg__(self):
return Integer(-self.p)
def __abs__(self):
if self.p >= 0:
return self
else:
return Integer(-self.p)
def __divmod__(self, other):
from .containers import Tuple
if isinstance(other, Integer) and global_parameters.evaluate:
return Tuple(*(divmod(self.p, other.p)))
else:
return Number.__divmod__(self, other)
def __rdivmod__(self, other):
from .containers import Tuple
if isinstance(other, int) and global_parameters.evaluate:
return Tuple(*(divmod(other, self.p)))
else:
try:
other = Number(other)
except TypeError:
msg = "unsupported operand type(s) for divmod(): '%s' and '%s'"
oname = type(other).__name__
sname = type(self).__name__
raise TypeError(msg % (oname, sname))
return Number.__divmod__(other, self)
# TODO make it decorator + bytecodehacks?
def __add__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p + other)
elif isinstance(other, Integer):
return Integer(self.p + other.p)
elif isinstance(other, Rational):
return Rational(self.p*other.q + other.p, other.q, 1)
return Rational.__add__(self, other)
else:
return Add(self, other)
def __radd__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other + self.p)
elif isinstance(other, Rational):
return Rational(other.p + self.p*other.q, other.q, 1)
return Rational.__radd__(self, other)
return Rational.__radd__(self, other)
def __sub__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p - other)
elif isinstance(other, Integer):
return Integer(self.p - other.p)
elif isinstance(other, Rational):
return Rational(self.p*other.q - other.p, other.q, 1)
return Rational.__sub__(self, other)
return Rational.__sub__(self, other)
def __rsub__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other - self.p)
elif isinstance(other, Rational):
return Rational(other.p - self.p*other.q, other.q, 1)
return Rational.__rsub__(self, other)
return Rational.__rsub__(self, other)
def __mul__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p*other)
elif isinstance(other, Integer):
return Integer(self.p*other.p)
elif isinstance(other, Rational):
return Rational(self.p*other.p, other.q, igcd(self.p, other.q))
return Rational.__mul__(self, other)
return Rational.__mul__(self, other)
def __rmul__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other*self.p)
elif isinstance(other, Rational):
return Rational(other.p*self.p, other.q, igcd(self.p, other.q))
return Rational.__rmul__(self, other)
return Rational.__rmul__(self, other)
def __mod__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p % other)
elif isinstance(other, Integer):
return Integer(self.p % other.p)
return Rational.__mod__(self, other)
return Rational.__mod__(self, other)
def __rmod__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other % self.p)
elif isinstance(other, Integer):
return Integer(other.p % self.p)
return Rational.__rmod__(self, other)
return Rational.__rmod__(self, other)
def __eq__(self, other):
if isinstance(other, int):
return (self.p == other)
elif isinstance(other, Integer):
return (self.p == other.p)
return Rational.__eq__(self, other)
def __ne__(self, other):
return not self == other
def __gt__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p > other.p)
return Rational.__gt__(self, other)
def __lt__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p < other.p)
return Rational.__lt__(self, other)
def __ge__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p >= other.p)
return Rational.__ge__(self, other)
def __le__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p <= other.p)
return Rational.__le__(self, other)
def __hash__(self):
return hash(self.p)
def __index__(self):
return self.p
########################################
def _eval_is_odd(self):
return bool(self.p % 2)
def _eval_power(self, expt):
"""
Tries to do some simplifications on self**expt
Returns None if no further simplifications can be done.
Explanation
===========
When exponent is a fraction (so we have for example a square root),
we try to find a simpler representation by factoring the argument
up to factors of 2**15, e.g.
- sqrt(4) becomes 2
- sqrt(-4) becomes 2*I
- (2**(3+7)*3**(6+7))**Rational(1,7) becomes 6*18**(3/7)
Further simplification would require a special call to factorint on
the argument which is not done here for sake of speed.
"""
from sympy.ntheory.factor_ import perfect_power
if expt is S.Infinity:
if self.p > S.One:
return S.Infinity
# cases -1, 0, 1 are done in their respective classes
return S.Infinity + S.ImaginaryUnit*S.Infinity
if expt is S.NegativeInfinity:
return Rational(1, self)**S.Infinity
if not isinstance(expt, Number):
# simplify when expt is even
# (-2)**k --> 2**k
if self.is_negative and expt.is_even:
return (-self)**expt
if isinstance(expt, Float):
# Rational knows how to exponentiate by a Float
return super()._eval_power(expt)
if not isinstance(expt, Rational):
return
if expt is S.Half and self.is_negative:
# we extract I for this special case since everyone is doing so
return S.ImaginaryUnit*Pow(-self, expt)
if expt.is_negative:
# invert base and change sign on exponent
ne = -expt
if self.is_negative:
return S.NegativeOne**expt*Rational(1, -self)**ne
else:
return Rational(1, self.p)**ne
# see if base is a perfect root, sqrt(4) --> 2
x, xexact = integer_nthroot(abs(self.p), expt.q)
if xexact:
# if it's a perfect root we've finished
result = Integer(x**abs(expt.p))
if self.is_negative:
result *= S.NegativeOne**expt
return result
# The following is an algorithm where we collect perfect roots
# from the factors of base.
# if it's not an nth root, it still might be a perfect power
b_pos = int(abs(self.p))
p = perfect_power(b_pos)
if p is not False:
dict = {p[0]: p[1]}
else:
dict = Integer(b_pos).factors(limit=2**15)
# now process the dict of factors
out_int = 1 # integer part
out_rad = 1 # extracted radicals
sqr_int = 1
sqr_gcd = 0
sqr_dict = {}
for prime, exponent in dict.items():
exponent *= expt.p
# remove multiples of expt.q: (2**12)**(1/10) -> 2*(2**2)**(1/10)
div_e, div_m = divmod(exponent, expt.q)
if div_e > 0:
out_int *= prime**div_e
if div_m > 0:
# see if the reduced exponent shares a gcd with e.q
# (2**2)**(1/10) -> 2**(1/5)
g = igcd(div_m, expt.q)
if g != 1:
out_rad *= Pow(prime, Rational(div_m//g, expt.q//g))
else:
sqr_dict[prime] = div_m
# identify gcd of remaining powers
for p, ex in sqr_dict.items():
if sqr_gcd == 0:
sqr_gcd = ex
else:
sqr_gcd = igcd(sqr_gcd, ex)
if sqr_gcd == 1:
break
for k, v in sqr_dict.items():
sqr_int *= k**(v//sqr_gcd)
if sqr_int == b_pos and out_int == 1 and out_rad == 1:
result = None
else:
result = out_int*out_rad*Pow(sqr_int, Rational(sqr_gcd, expt.q))
if self.is_negative:
result *= Pow(S.NegativeOne, expt)
return result
def _eval_is_prime(self):
from sympy.ntheory import isprime
return isprime(self)
def _eval_is_composite(self):
if self > 1:
return fuzzy_not(self.is_prime)
else:
return False
def as_numer_denom(self):
return self, S.One
@_sympifyit('other', NotImplemented)
def __floordiv__(self, other):
if not isinstance(other, Expr):
return NotImplemented
if isinstance(other, Integer):
return Integer(self.p // other)
return Integer(divmod(self, other)[0])
def __rfloordiv__(self, other):
return Integer(Integer(other).p // self.p)
# Add sympify converters
converter[int] = Integer
class AlgebraicNumber(Expr):
"""Class for representing algebraic numbers in SymPy. """
__slots__ = ('rep', 'root', 'alias', 'minpoly')
is_AlgebraicNumber = True
is_algebraic = True
is_number = True
kind = NumberKind
# Optional alias symbol is not free.
# Actually, alias should be a Str, but some methods
# expect that it be an instance of Expr.
free_symbols = set()
def __new__(cls, expr, coeffs=None, alias=None, **args):
"""Construct a new algebraic number. """
from sympy import Poly
from sympy.polys.polyclasses import ANP, DMP
from sympy.polys.numberfields import minimal_polynomial
from sympy.core.symbol import Symbol
expr = sympify(expr)
if isinstance(expr, (tuple, Tuple)):
minpoly, root = expr
if not minpoly.is_Poly:
minpoly = Poly(minpoly)
elif expr.is_AlgebraicNumber:
minpoly, root = expr.minpoly, expr.root
else:
minpoly, root = minimal_polynomial(
expr, args.get('gen'), polys=True), expr
dom = minpoly.get_domain()
if coeffs is not None:
if not isinstance(coeffs, ANP):
rep = DMP.from_sympy_list(sympify(coeffs), 0, dom)
scoeffs = Tuple(*coeffs)
else:
rep = DMP.from_list(coeffs.to_list(), 0, dom)
scoeffs = Tuple(*coeffs.to_list())
if rep.degree() >= minpoly.degree():
rep = rep.rem(minpoly.rep)
else:
rep = DMP.from_list([1, 0], 0, dom)
scoeffs = Tuple(1, 0)
sargs = (root, scoeffs)
if alias is not None:
if not isinstance(alias, Symbol):
alias = Symbol(alias)
sargs = sargs + (alias,)
obj = Expr.__new__(cls, *sargs)
obj.rep = rep
obj.root = root
obj.alias = alias
obj.minpoly = minpoly
return obj
def __hash__(self):
return super().__hash__()
def _eval_evalf(self, prec):
return self.as_expr()._evalf(prec)
@property
def is_aliased(self):
"""Returns ``True`` if ``alias`` was set. """
return self.alias is not None
def as_poly(self, x=None):
"""Create a Poly instance from ``self``. """
from sympy import Dummy, Poly, PurePoly
if x is not None:
return Poly.new(self.rep, x)
else:
if self.alias is not None:
return Poly.new(self.rep, self.alias)
else:
return PurePoly.new(self.rep, Dummy('x'))
def as_expr(self, x=None):
"""Create a Basic expression from ``self``. """
return self.as_poly(x or self.root).as_expr().expand()
def coeffs(self):
"""Returns all SymPy coefficients of an algebraic number. """
return [ self.rep.dom.to_sympy(c) for c in self.rep.all_coeffs() ]
def native_coeffs(self):
"""Returns all native coefficients of an algebraic number. """
return self.rep.all_coeffs()
def to_algebraic_integer(self):
"""Convert ``self`` to an algebraic integer. """
from sympy import Poly
f = self.minpoly
if f.LC() == 1:
return self
coeff = f.LC()**(f.degree() - 1)
poly = f.compose(Poly(f.gen/f.LC()))
minpoly = poly*coeff
root = f.LC()*self.root
return AlgebraicNumber((minpoly, root), self.coeffs())
def _eval_simplify(self, **kwargs):
from sympy.polys import CRootOf, minpoly
measure, ratio = kwargs['measure'], kwargs['ratio']
for r in [r for r in self.minpoly.all_roots() if r.func != CRootOf]:
if minpoly(self.root - r).is_Symbol:
# use the matching root if it's simpler
if measure(r) < ratio*measure(self.root):
return AlgebraicNumber(r)
return self
class RationalConstant(Rational):
"""
Abstract base class for rationals with specific behaviors
Derived classes must define class attributes p and q and should probably all
be singletons.
"""
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
class IntegerConstant(Integer):
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
class Zero(IntegerConstant, metaclass=Singleton):
"""The number zero.
Zero is a singleton, and can be accessed by ``S.Zero``
Examples
========
>>> from sympy import S, Integer
>>> Integer(0) is S.Zero
True
>>> 1/S.Zero
zoo
References
==========
.. [1] https://en.wikipedia.org/wiki/Zero
"""
p = 0
q = 1
is_positive = False
is_negative = False
is_zero = True
is_number = True
is_comparable = True
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.Zero
@staticmethod
def __neg__():
return S.Zero
def _eval_power(self, expt):
if expt.is_positive:
return self
if expt.is_negative:
return S.ComplexInfinity
if expt.is_extended_real is False:
return S.NaN
# infinities are already handled with pos and neg
# tests above; now throw away leading numbers on Mul
# exponent
coeff, terms = expt.as_coeff_Mul()
if coeff.is_negative:
return S.ComplexInfinity**terms
if coeff is not S.One: # there is a Number to discard
return self**terms
def _eval_order(self, *symbols):
# Order(0,x) -> 0
return self
def __bool__(self):
return False
def as_coeff_Mul(self, rational=False): # XXX this routine should be deleted
"""Efficiently extract the coefficient of a summation. """
return S.One, self
class One(IntegerConstant, metaclass=Singleton):
"""The number one.
One is a singleton, and can be accessed by ``S.One``.
Examples
========
>>> from sympy import S, Integer
>>> Integer(1) is S.One
True
References
==========
.. [1] https://en.wikipedia.org/wiki/1_%28number%29
"""
is_number = True
is_positive = True
p = 1
q = 1
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.One
@staticmethod
def __neg__():
return S.NegativeOne
def _eval_power(self, expt):
return self
def _eval_order(self, *symbols):
return
@staticmethod
def factors(limit=None, use_trial=True, use_rho=False, use_pm1=False,
verbose=False, visual=False):
if visual:
return S.One
else:
return {}
class NegativeOne(IntegerConstant, metaclass=Singleton):
"""The number negative one.
NegativeOne is a singleton, and can be accessed by ``S.NegativeOne``.
Examples
========
>>> from sympy import S, Integer
>>> Integer(-1) is S.NegativeOne
True
See Also
========
One
References
==========
.. [1] https://en.wikipedia.org/wiki/%E2%88%921_%28number%29
"""
is_number = True
p = -1
q = 1
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.One
@staticmethod
def __neg__():
return S.One
def _eval_power(self, expt):
if expt.is_odd:
return S.NegativeOne
if expt.is_even:
return S.One
if isinstance(expt, Number):
if isinstance(expt, Float):
return Float(-1.0)**expt
if expt is S.NaN:
return S.NaN
if expt is S.Infinity or expt is S.NegativeInfinity:
return S.NaN
if expt is S.Half:
return S.ImaginaryUnit
if isinstance(expt, Rational):
if expt.q == 2:
return S.ImaginaryUnit**Integer(expt.p)
i, r = divmod(expt.p, expt.q)
if i:
return self**i*self**Rational(r, expt.q)
return
class Half(RationalConstant, metaclass=Singleton):
"""The rational number 1/2.
Half is a singleton, and can be accessed by ``S.Half``.
Examples
========
>>> from sympy import S, Rational
>>> Rational(1, 2) is S.Half
True
References
==========
.. [1] https://en.wikipedia.org/wiki/One_half
"""
is_number = True
p = 1
q = 2
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.Half
class Infinity(Number, metaclass=Singleton):
r"""Positive infinite quantity.
Explanation
===========
In real analysis the symbol `\infty` denotes an unbounded
limit: `x\to\infty` means that `x` grows without bound.
Infinity is often used not only to define a limit but as a value
in the affinely extended real number system. Points labeled `+\infty`
and `-\infty` can be added to the topological space of the real numbers,
producing the two-point compactification of the real numbers. Adding
algebraic properties to this gives us the extended real numbers.
Infinity is a singleton, and can be accessed by ``S.Infinity``,
or can be imported as ``oo``.
Examples
========
>>> from sympy import oo, exp, limit, Symbol
>>> 1 + oo
oo
>>> 42/oo
0
>>> x = Symbol('x')
>>> limit(exp(x), x, oo)
oo
See Also
========
NegativeInfinity, NaN
References
==========
.. [1] https://en.wikipedia.org/wiki/Infinity
"""
is_commutative = True
is_number = True
is_complex = False
is_extended_real = True
is_infinite = True
is_comparable = True
is_extended_positive = True
is_prime = False
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
def _latex(self, printer):
return r"\infty"
def _eval_subs(self, old, new):
if self == old:
return new
def _eval_evalf(self, prec=None):
return Float('inf')
def evalf(self, prec=None, **options):
return self._eval_evalf(prec)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NegativeInfinity or other is S.NaN:
return S.NaN
return self
return Number.__add__(self, other)
__radd__ = __add__
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.Infinity or other is S.NaN:
return S.NaN
return self
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __rsub__(self, other):
return (-self).__add__(other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other.is_zero or other is S.NaN:
return S.NaN
if other.is_extended_positive:
return self
return S.NegativeInfinity
return Number.__mul__(self, other)
__rmul__ = __mul__
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.Infinity or \
other is S.NegativeInfinity or \
other is S.NaN:
return S.NaN
if other.is_extended_nonnegative:
return self
return S.NegativeInfinity
return Number.__truediv__(self, other)
def __abs__(self):
return S.Infinity
def __neg__(self):
return S.NegativeInfinity
def _eval_power(self, expt):
"""
``expt`` is symbolic object but not equal to 0 or 1.
================ ======= ==============================
Expression Result Notes
================ ======= ==============================
``oo ** nan`` ``nan``
``oo ** -p`` ``0`` ``p`` is number, ``oo``
================ ======= ==============================
See Also
========
Pow
NaN
NegativeInfinity
"""
from sympy.functions import re
if expt.is_extended_positive:
return S.Infinity
if expt.is_extended_negative:
return S.Zero
if expt is S.NaN:
return S.NaN
if expt is S.ComplexInfinity:
return S.NaN
if expt.is_extended_real is False and expt.is_number:
expt_real = re(expt)
if expt_real.is_positive:
return S.ComplexInfinity
if expt_real.is_negative:
return S.Zero
if expt_real.is_zero:
return S.NaN
return self**expt.evalf()
def _as_mpf_val(self, prec):
return mlib.finf
def _sage_(self):
import sage.all as sage
return sage.oo
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
return other is S.Infinity or other == float('inf')
def __ne__(self, other):
return other is not S.Infinity and other != float('inf')
__gt__ = Expr.__gt__
__ge__ = Expr.__ge__
__lt__ = Expr.__lt__
__le__ = Expr.__le__
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if not isinstance(other, Expr):
return NotImplemented
return S.NaN
__rmod__ = __mod__
def floor(self):
return self
def ceiling(self):
return self
oo = S.Infinity
class NegativeInfinity(Number, metaclass=Singleton):
"""Negative infinite quantity.
NegativeInfinity is a singleton, and can be accessed
by ``S.NegativeInfinity``.
See Also
========
Infinity
"""
is_extended_real = True
is_complex = False
is_commutative = True
is_infinite = True
is_comparable = True
is_extended_negative = True
is_number = True
is_prime = False
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
def _latex(self, printer):
return r"-\infty"
def _eval_subs(self, old, new):
if self == old:
return new
def _eval_evalf(self, prec=None):
return Float('-inf')
def evalf(self, prec=None, **options):
return self._eval_evalf(prec)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.Infinity or other is S.NaN:
return S.NaN
return self
return Number.__add__(self, other)
__radd__ = __add__
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.NegativeInfinity or other is S.NaN:
return S.NaN
return self
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __rsub__(self, other):
return (-self).__add__(other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other.is_zero or other is S.NaN:
return S.NaN
if other.is_extended_positive:
return self
return S.Infinity
return Number.__mul__(self, other)
__rmul__ = __mul__
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and global_parameters.evaluate:
if other is S.Infinity or \
other is S.NegativeInfinity or \
other is S.NaN:
return S.NaN
if other.is_extended_nonnegative:
return self
return S.Infinity
return Number.__truediv__(self, other)
def __abs__(self):
return S.Infinity
def __neg__(self):
return S.Infinity
def _eval_power(self, expt):
"""
``expt`` is symbolic object but not equal to 0 or 1.
================ ======= ==============================
Expression Result Notes
================ ======= ==============================
``(-oo) ** nan`` ``nan``
``(-oo) ** oo`` ``nan``
``(-oo) ** -oo`` ``nan``
``(-oo) ** e`` ``oo`` ``e`` is positive even integer
``(-oo) ** o`` ``-oo`` ``o`` is positive odd integer
================ ======= ==============================
See Also
========
Infinity
Pow
NaN
"""
if expt.is_number:
if expt is S.NaN or \
expt is S.Infinity or \
expt is S.NegativeInfinity:
return S.NaN
if isinstance(expt, Integer) and expt.is_extended_positive:
if expt.is_odd:
return S.NegativeInfinity
else:
return S.Infinity
return S.NegativeOne**expt*S.Infinity**expt
def _as_mpf_val(self, prec):
return mlib.fninf
def _sage_(self):
import sage.all as sage
return -(sage.oo)
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
return other is S.NegativeInfinity or other == float('-inf')
def __ne__(self, other):
return other is not S.NegativeInfinity and other != float('-inf')
__gt__ = Expr.__gt__
__ge__ = Expr.__ge__
__lt__ = Expr.__lt__
__le__ = Expr.__le__
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if not isinstance(other, Expr):
return NotImplemented
return S.NaN
__rmod__ = __mod__
def floor(self):
return self
def ceiling(self):
return self
def as_powers_dict(self):
return {S.NegativeOne: 1, S.Infinity: 1}
class NaN(Number, metaclass=Singleton):
"""
Not a Number.
Explanation
===========
This serves as a place holder for numeric values that are indeterminate.
Most operations on NaN, produce another NaN. Most indeterminate forms,
such as ``0/0`` or ``oo - oo` produce NaN. Two exceptions are ``0**0``
and ``oo**0``, which all produce ``1`` (this is consistent with Python's
float).
NaN is loosely related to floating point nan, which is defined in the
IEEE 754 floating point standard, and corresponds to the Python
``float('nan')``. Differences are noted below.
NaN is mathematically not equal to anything else, even NaN itself. This
explains the initially counter-intuitive results with ``Eq`` and ``==`` in
the examples below.
NaN is not comparable so inequalities raise a TypeError. This is in
contrast with floating point nan where all inequalities are false.
NaN is a singleton, and can be accessed by ``S.NaN``, or can be imported
as ``nan``.
Examples
========
>>> from sympy import nan, S, oo, Eq
>>> nan is S.NaN
True
>>> oo - oo
nan
>>> nan + 1
nan
>>> Eq(nan, nan) # mathematical equality
False
>>> nan == nan # structural equality
True
References
==========
.. [1] https://en.wikipedia.org/wiki/NaN
"""
is_commutative = True
is_extended_real = None
is_real = None
is_rational = None
is_algebraic = None
is_transcendental = None
is_integer = None
is_comparable = False
is_finite = None
is_zero = None
is_prime = None
is_positive = None
is_negative = None
is_number = True
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
def _latex(self, printer):
return r"\text{NaN}"
def __neg__(self):
return self
@_sympifyit('other', NotImplemented)
def __add__(self, other):
return self
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
return self
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
return self
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
return self
def floor(self):
return self
def ceiling(self):
return self
def _as_mpf_val(self, prec):
return _mpf_nan
def _sage_(self):
import sage.all as sage
return sage.NaN
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
# NaN is structurally equal to another NaN
return other is S.NaN
def __ne__(self, other):
return other is not S.NaN
# Expr will _sympify and raise TypeError
__gt__ = Expr.__gt__
__ge__ = Expr.__ge__
__lt__ = Expr.__lt__
__le__ = Expr.__le__
nan = S.NaN
@dispatch(NaN, Expr) # type:ignore
def _eval_is_eq(a, b): # noqa:F811
return False
class ComplexInfinity(AtomicExpr, metaclass=Singleton):
r"""Complex infinity.
Explanation
===========
In complex analysis the symbol `\tilde\infty`, called "complex
infinity", represents a quantity with infinite magnitude, but
undetermined complex phase.
ComplexInfinity is a singleton, and can be accessed by
``S.ComplexInfinity``, or can be imported as ``zoo``.
Examples
========
>>> from sympy import zoo
>>> zoo + 42
zoo
>>> 42/zoo
0
>>> zoo + zoo
nan
>>> zoo*zoo
zoo
See Also
========
Infinity
"""
is_commutative = True
is_infinite = True
is_number = True
is_prime = False
is_complex = False
is_extended_real = False
kind = NumberKind
__slots__ = ()
def __new__(cls):
return AtomicExpr.__new__(cls)
def _latex(self, printer):
return r"\tilde{\infty}"
@staticmethod
def __abs__():
return S.Infinity
def floor(self):
return self
def ceiling(self):
return self
@staticmethod
def __neg__():
return S.ComplexInfinity
def _eval_power(self, expt):
if expt is S.ComplexInfinity:
return S.NaN
if isinstance(expt, Number):
if expt.is_zero:
return S.NaN
else:
if expt.is_positive:
return S.ComplexInfinity
else:
return S.Zero
def _sage_(self):
import sage.all as sage
return sage.UnsignedInfinityRing.gen()
zoo = S.ComplexInfinity
class NumberSymbol(AtomicExpr):
is_commutative = True
is_finite = True
is_number = True
__slots__ = ()
is_NumberSymbol = True
kind = NumberKind
def __new__(cls):
return AtomicExpr.__new__(cls)
def approximation(self, number_cls):
""" Return an interval with number_cls endpoints
that contains the value of NumberSymbol.
If not implemented, then return None.
"""
def _eval_evalf(self, prec):
return Float._new(self._as_mpf_val(prec), prec)
def __eq__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if self is other:
return True
if other.is_Number and self.is_irrational:
return False
return False # NumberSymbol != non-(Number|self)
def __ne__(self, other):
return not self == other
def __le__(self, other):
if self is other:
return S.true
return Expr.__le__(self, other)
def __ge__(self, other):
if self is other:
return S.true
return Expr.__ge__(self, other)
def __int__(self):
# subclass with appropriate return value
raise NotImplementedError
def __hash__(self):
return super().__hash__()
class Exp1(NumberSymbol, metaclass=Singleton):
r"""The `e` constant.
Explanation
===========
The transcendental number `e = 2.718281828\ldots` is the base of the
natural logarithm and of the exponential function, `e = \exp(1)`.
Sometimes called Euler's number or Napier's constant.
Exp1 is a singleton, and can be accessed by ``S.Exp1``,
or can be imported as ``E``.
Examples
========
>>> from sympy import exp, log, E
>>> E is exp(1)
True
>>> log(E)
1
References
==========
.. [1] https://en.wikipedia.org/wiki/E_%28mathematical_constant%29
"""
is_real = True
is_positive = True
is_negative = False # XXX Forces is_negative/is_nonnegative
is_irrational = True
is_number = True
is_algebraic = False
is_transcendental = True
__slots__ = ()
def _latex(self, printer):
return r"e"
@staticmethod
def __abs__():
return S.Exp1
def __int__(self):
return 2
def _as_mpf_val(self, prec):
return mpf_e(prec)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (Integer(2), Integer(3))
elif issubclass(number_cls, Rational):
pass
def _eval_power(self, expt):
from sympy import exp
if global_parameters.exp_is_pow:
return self._eval_power_exp_is_pow(expt)
else:
return exp(expt)
def _eval_power_exp_is_pow(self, arg):
from ..functions.elementary.exponential import log
from . import Add, Mul, Pow
if arg.is_Number:
if arg is oo:
return oo
elif arg == -oo:
return S.Zero
elif isinstance(arg, log):
return arg.args[0]
# don't autoexpand Pow or Mul (see the issue 3351):
elif not arg.is_Add:
Ioo = I*oo
if arg in [Ioo, -Ioo]:
return nan
coeff = arg.coeff(pi*I)
if coeff:
if (2*coeff).is_integer:
if coeff.is_even:
return S.One
elif coeff.is_odd:
return S.NegativeOne
elif (coeff + S.Half).is_even:
return -I
elif (coeff + S.Half).is_odd:
return I
elif coeff.is_Rational:
ncoeff = coeff % 2 # restrict to [0, 2pi)
if ncoeff > 1: # restrict to (-pi, pi]
ncoeff -= 2
if ncoeff != coeff:
return S.Exp1**(ncoeff*S.Pi*S.ImaginaryUnit)
# Warning: code in risch.py will be very sensitive to changes
# in this (see DifferentialExtension).
# look for a single log factor
coeff, terms = arg.as_coeff_Mul()
# but it can't be multiplied by oo
if coeff in (oo, -oo):
return
coeffs, log_term = [coeff], None
for term in Mul.make_args(terms):
if isinstance(term, log):
if log_term is None:
log_term = term.args[0]
else:
return
elif term.is_comparable:
coeffs.append(term)
else:
return
return log_term**Mul(*coeffs) if log_term else None
elif arg.is_Add:
out = []
add = []
argchanged = False
for a in arg.args:
if a is S.One:
add.append(a)
continue
newa = self**a
if isinstance(newa, Pow) and newa.base is self:
if newa.exp != a:
add.append(newa.exp)
argchanged = True
else:
add.append(a)
else:
out.append(newa)
if out or argchanged:
return Mul(*out)*Pow(self, Add(*add), evaluate=False)
elif arg.is_Matrix:
return arg.exp()
def _eval_rewrite_as_sin(self, **kwargs):
from sympy import sin
I = S.ImaginaryUnit
return sin(I + S.Pi/2) - I*sin(I)
def _eval_rewrite_as_cos(self, **kwargs):
from sympy import cos
I = S.ImaginaryUnit
return cos(I) + I*cos(I + S.Pi/2)
def _sage_(self):
import sage.all as sage
return sage.e
E = S.Exp1
class Pi(NumberSymbol, metaclass=Singleton):
r"""The `\pi` constant.
Explanation
===========
The transcendental number `\pi = 3.141592654\ldots` represents the ratio
of a circle's circumference to its diameter, the area of the unit circle,
the half-period of trigonometric functions, and many other things
in mathematics.
Pi is a singleton, and can be accessed by ``S.Pi``, or can
be imported as ``pi``.
Examples
========
>>> from sympy import S, pi, oo, sin, exp, integrate, Symbol
>>> S.Pi
pi
>>> pi > 3
True
>>> pi.is_irrational
True
>>> x = Symbol('x')
>>> sin(x + 2*pi)
sin(x)
>>> integrate(exp(-x**2), (x, -oo, oo))
sqrt(pi)
References
==========
.. [1] https://en.wikipedia.org/wiki/Pi
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = True
is_number = True
is_algebraic = False
is_transcendental = True
__slots__ = ()
def _latex(self, printer):
return r"\pi"
@staticmethod
def __abs__():
return S.Pi
def __int__(self):
return 3
def _as_mpf_val(self, prec):
return mpf_pi(prec)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (Integer(3), Integer(4))
elif issubclass(number_cls, Rational):
return (Rational(223, 71), Rational(22, 7))
def _sage_(self):
import sage.all as sage
return sage.pi
pi = S.Pi
class GoldenRatio(NumberSymbol, metaclass=Singleton):
r"""The golden ratio, `\phi`.
Explanation
===========
`\phi = \frac{1 + \sqrt{5}}{2}` is algebraic number. Two quantities
are in the golden ratio if their ratio is the same as the ratio of
their sum to the larger of the two quantities, i.e. their maximum.
GoldenRatio is a singleton, and can be accessed by ``S.GoldenRatio``.
Examples
========
>>> from sympy import S
>>> S.GoldenRatio > 1
True
>>> S.GoldenRatio.expand(func=True)
1/2 + sqrt(5)/2
>>> S.GoldenRatio.is_irrational
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Golden_ratio
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = True
is_number = True
is_algebraic = True
is_transcendental = False
__slots__ = ()
def _latex(self, printer):
return r"\phi"
def __int__(self):
return 1
def _as_mpf_val(self, prec):
# XXX track down why this has to be increased
rv = mlib.from_man_exp(phi_fixed(prec + 10), -prec - 10)
return mpf_norm(rv, prec)
def _eval_expand_func(self, **hints):
from sympy import sqrt
return S.Half + S.Half*sqrt(5)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (S.One, Rational(2))
elif issubclass(number_cls, Rational):
pass
def _sage_(self):
import sage.all as sage
return sage.golden_ratio
_eval_rewrite_as_sqrt = _eval_expand_func
class TribonacciConstant(NumberSymbol, metaclass=Singleton):
r"""The tribonacci constant.
Explanation
===========
The tribonacci numbers are like the Fibonacci numbers, but instead
of starting with two predetermined terms, the sequence starts with
three predetermined terms and each term afterwards is the sum of the
preceding three terms.
The tribonacci constant is the ratio toward which adjacent tribonacci
numbers tend. It is a root of the polynomial `x^3 - x^2 - x - 1 = 0`,
and also satisfies the equation `x + x^{-3} = 2`.
TribonacciConstant is a singleton, and can be accessed
by ``S.TribonacciConstant``.
Examples
========
>>> from sympy import S
>>> S.TribonacciConstant > 1
True
>>> S.TribonacciConstant.expand(func=True)
1/3 + (19 - 3*sqrt(33))**(1/3)/3 + (3*sqrt(33) + 19)**(1/3)/3
>>> S.TribonacciConstant.is_irrational
True
>>> S.TribonacciConstant.n(20)
1.8392867552141611326
References
==========
.. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = True
is_number = True
is_algebraic = True
is_transcendental = False
__slots__ = ()
def _latex(self, printer):
return r"\text{TribonacciConstant}"
def __int__(self):
return 2
def _eval_evalf(self, prec):
rv = self._eval_expand_func(function=True)._eval_evalf(prec + 4)
return Float(rv, precision=prec)
def _eval_expand_func(self, **hints):
from sympy import sqrt, cbrt
return (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (S.One, Rational(2))
elif issubclass(number_cls, Rational):
pass
_eval_rewrite_as_sqrt = _eval_expand_func
class EulerGamma(NumberSymbol, metaclass=Singleton):
r"""The Euler-Mascheroni constant.
Explanation
===========
`\gamma = 0.5772157\ldots` (also called Euler's constant) is a mathematical
constant recurring in analysis and number theory. It is defined as the
limiting difference between the harmonic series and the
natural logarithm:
.. math:: \gamma = \lim\limits_{n\to\infty}
\left(\sum\limits_{k=1}^n\frac{1}{k} - \ln n\right)
EulerGamma is a singleton, and can be accessed by ``S.EulerGamma``.
Examples
========
>>> from sympy import S
>>> S.EulerGamma.is_irrational
>>> S.EulerGamma > 0
True
>>> S.EulerGamma > 1
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = None
is_number = True
__slots__ = ()
def _latex(self, printer):
return r"\gamma"
def __int__(self):
return 0
def _as_mpf_val(self, prec):
# XXX track down why this has to be increased
v = mlib.libhyper.euler_fixed(prec + 10)
rv = mlib.from_man_exp(v, -prec - 10)
return mpf_norm(rv, prec)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (S.Zero, S.One)
elif issubclass(number_cls, Rational):
return (S.Half, Rational(3, 5))
def _sage_(self):
import sage.all as sage
return sage.euler_gamma
class Catalan(NumberSymbol, metaclass=Singleton):
r"""Catalan's constant.
Explanation
===========
`K = 0.91596559\ldots` is given by the infinite series
.. math:: K = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2}
Catalan is a singleton, and can be accessed by ``S.Catalan``.
Examples
========
>>> from sympy import S
>>> S.Catalan.is_irrational
>>> S.Catalan > 0
True
>>> S.Catalan > 1
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Catalan%27s_constant
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = None
is_number = True
__slots__ = ()
def __int__(self):
return 0
def _as_mpf_val(self, prec):
# XXX track down why this has to be increased
v = mlib.catalan_fixed(prec + 10)
rv = mlib.from_man_exp(v, -prec - 10)
return mpf_norm(rv, prec)
def approximation_interval(self, number_cls):
if issubclass(number_cls, Integer):
return (S.Zero, S.One)
elif issubclass(number_cls, Rational):
return (Rational(9, 10), S.One)
def _eval_rewrite_as_Sum(self, k_sym=None, symbols=None):
from sympy import Sum, Dummy
if (k_sym is not None) or (symbols is not None):
return self
k = Dummy('k', integer=True, nonnegative=True)
return Sum((-1)**k / (2*k+1)**2, (k, 0, S.Infinity))
def _sage_(self):
import sage.all as sage
return sage.catalan
class ImaginaryUnit(AtomicExpr, metaclass=Singleton):
r"""The imaginary unit, `i = \sqrt{-1}`.
I is a singleton, and can be accessed by ``S.I``, or can be
imported as ``I``.
Examples
========
>>> from sympy import I, sqrt
>>> sqrt(-1)
I
>>> I*I
-1
>>> 1/I
-I
References
==========
.. [1] https://en.wikipedia.org/wiki/Imaginary_unit
"""
is_commutative = True
is_imaginary = True
is_finite = True
is_number = True
is_algebraic = True
is_transcendental = False
kind = NumberKind
__slots__ = ()
def _latex(self, printer):
return printer._settings['imaginary_unit_latex']
@staticmethod
def __abs__():
return S.One
def _eval_evalf(self, prec):
return self
def _eval_conjugate(self):
return -S.ImaginaryUnit
def _eval_power(self, expt):
"""
b is I = sqrt(-1)
e is symbolic object but not equal to 0, 1
I**r -> (-1)**(r/2) -> exp(r/2*Pi*I) -> sin(Pi*r/2) + cos(Pi*r/2)*I, r is decimal
I**0 mod 4 -> 1
I**1 mod 4 -> I
I**2 mod 4 -> -1
I**3 mod 4 -> -I
"""
if isinstance(expt, Integer):
expt = expt % 4
if expt == 0:
return S.One
elif expt == 1:
return S.ImaginaryUnit
elif expt == 2:
return S.NegativeOne
elif expt == 3:
return -S.ImaginaryUnit
if isinstance(expt, Rational):
i, r = divmod(expt, 2)
rv = Pow(S.ImaginaryUnit, r, evaluate=False)
if i % 2:
return Mul(S.NegativeOne, rv, evaluate=False)
return rv
def as_base_exp(self):
return S.NegativeOne, S.Half
def _sage_(self):
import sage.all as sage
return sage.I
@property
def _mpc_(self):
return (Float(0)._mpf_, Float(1)._mpf_)
I = S.ImaginaryUnit
@dispatch(Tuple, Number) # type:ignore
def _eval_is_eq(self, other): # noqa: F811
return False
def sympify_fractions(f):
return Rational(f.numerator, f.denominator, 1)
converter[fractions.Fraction] = sympify_fractions
if HAS_GMPY:
def sympify_mpz(x):
return Integer(int(x))
# XXX: The sympify_mpq function here was never used because it is
# overridden by the other sympify_mpq function below. Maybe it should just
# be removed or maybe it should be used for something...
def sympify_mpq(x):
return Rational(int(x.numerator), int(x.denominator))
converter[type(gmpy.mpz(1))] = sympify_mpz
converter[type(gmpy.mpq(1, 2))] = sympify_mpq
def sympify_mpmath_mpq(x):
p, q = x._mpq_
return Rational(p, q, 1)
converter[type(mpmath.rational.mpq(1, 2))] = sympify_mpmath_mpq
def sympify_mpmath(x):
return Expr._from_mpmath(x, x.context.prec)
converter[mpnumeric] = sympify_mpmath
def sympify_complex(a):
real, imag = list(map(sympify, (a.real, a.imag)))
return real + S.ImaginaryUnit*imag
converter[complex] = sympify_complex
from .power import Pow, integer_nthroot
from .mul import Mul
Mul.identity = One()
from .add import Add
Add.identity = Zero()
def _register_classes():
numbers.Number.register(Number)
numbers.Real.register(Float)
numbers.Rational.register(Rational)
numbers.Rational.register(Integer)
_register_classes()
|
c82782a11869e23f637f502efe2e94f1528e87e610b05f406d942b1c92c6e702 | from sympy.core.numbers import nan
from .function import Function
from .kind import NumberKind
class Mod(Function):
"""Represents a modulo operation on symbolic expressions.
Parameters
==========
p : Expr
Dividend.
q : Expr
Divisor.
Notes
=====
The convention used is the same as Python's: the remainder always has the
same sign as the divisor.
Examples
========
>>> from sympy.abc import x, y
>>> x**2 % y
Mod(x**2, y)
>>> _.subs({x: 5, y: 6})
1
"""
kind = NumberKind
@classmethod
def eval(cls, p, q):
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.core.exprtools import gcd_terms
from sympy.polys.polyerrors import PolynomialError
from sympy.polys.polytools import gcd
def doit(p, q):
"""Try to return p % q if both are numbers or +/-p is known
to be less than or equal q.
"""
if q.is_zero:
raise ZeroDivisionError("Modulo by zero")
if p.is_finite is False or q.is_finite is False or p is nan or q is nan:
return nan
if p is S.Zero or p == q or p == -q or (p.is_integer and q == 1):
return S.Zero
if q.is_Number:
if p.is_Number:
return p%q
if q == 2:
if p.is_even:
return S.Zero
elif p.is_odd:
return S.One
if hasattr(p, '_eval_Mod'):
rv = getattr(p, '_eval_Mod')(q)
if rv is not None:
return rv
# by ratio
r = p/q
if r.is_integer:
return S.Zero
try:
d = int(r)
except TypeError:
pass
else:
if isinstance(d, int):
rv = p - d*q
if (rv*q < 0) == True:
rv += q
return rv
# by difference
# -2|q| < p < 2|q|
d = abs(p)
for _ in range(2):
d -= abs(q)
if d.is_negative:
if q.is_positive:
if p.is_positive:
return d + q
elif p.is_negative:
return -d
elif q.is_negative:
if p.is_positive:
return d
elif p.is_negative:
return -d + q
break
rv = doit(p, q)
if rv is not None:
return rv
# denest
if isinstance(p, cls):
qinner = p.args[1]
if qinner % q == 0:
return cls(p.args[0], q)
elif (qinner*(q - qinner)).is_nonnegative:
# |qinner| < |q| and have same sign
return p
elif isinstance(-p, cls):
qinner = (-p).args[1]
if qinner % q == 0:
return cls(-(-p).args[0], q)
elif (qinner*(q + qinner)).is_nonpositive:
# |qinner| < |q| and have different sign
return p
elif isinstance(p, Add):
# separating into modulus and non modulus
both_l = non_mod_l, mod_l = [], []
for arg in p.args:
both_l[isinstance(arg, cls)].append(arg)
# if q same for all
if mod_l and all(inner.args[1] == q for inner in mod_l):
net = Add(*non_mod_l) + Add(*[i.args[0] for i in mod_l])
return cls(net, q)
elif isinstance(p, Mul):
# separating into modulus and non modulus
both_l = non_mod_l, mod_l = [], []
for arg in p.args:
both_l[isinstance(arg, cls)].append(arg)
if mod_l and all(inner.args[1] == q for inner in mod_l):
# finding distributive term
non_mod_l = [cls(x, q) for x in non_mod_l]
mod = []
non_mod = []
for j in non_mod_l:
if isinstance(j, cls):
mod.append(j.args[0])
else:
non_mod.append(j)
prod_mod = Mul(*mod)
prod_non_mod = Mul(*non_mod)
prod_mod1 = Mul(*[i.args[0] for i in mod_l])
net = prod_mod1*prod_mod
return prod_non_mod*cls(net, q)
if q.is_Integer and q is not S.One:
_ = []
for i in non_mod_l:
if i.is_Integer and (i % q is not S.Zero):
_.append(i%q)
else:
_.append(i)
non_mod_l = _
p = Mul(*(non_mod_l + mod_l))
# XXX other possibilities?
# extract gcd; any further simplification should be done by the user
try:
G = gcd(p, q)
if G != 1:
p, q = [gcd_terms(i/G, clear=False, fraction=False)
for i in (p, q)]
except PolynomialError: # issue 21373
G = S.One
pwas, qwas = p, q
# simplify terms
# (x + y + 2) % x -> Mod(y + 2, x)
if p.is_Add:
args = []
for i in p.args:
a = cls(i, q)
if a.count(cls) > i.count(cls):
args.append(i)
else:
args.append(a)
if args != list(p.args):
p = Add(*args)
else:
# handle coefficients if they are not Rational
# since those are not handled by factor_terms
# e.g. Mod(.6*x, .3*y) -> 0.3*Mod(2*x, y)
cp, p = p.as_coeff_Mul()
cq, q = q.as_coeff_Mul()
ok = False
if not cp.is_Rational or not cq.is_Rational:
r = cp % cq
if r == 0:
G *= cq
p *= int(cp/cq)
ok = True
if not ok:
p = cp*p
q = cq*q
# simple -1 extraction
if p.could_extract_minus_sign() and q.could_extract_minus_sign():
G, p, q = [-i for i in (G, p, q)]
# check again to see if p and q can now be handled as numbers
rv = doit(p, q)
if rv is not None:
return rv*G
# put 1.0 from G on inside
if G.is_Float and G == 1:
p *= G
return cls(p, q, evaluate=False)
elif G.is_Mul and G.args[0].is_Float and G.args[0] == 1:
p = G.args[0]*p
G = Mul._from_args(G.args[1:])
return G*cls(p, q, evaluate=(p, q) != (pwas, qwas))
def _eval_is_integer(self):
from sympy.core.logic import fuzzy_and, fuzzy_not
p, q = self.args
if fuzzy_and([p.is_integer, q.is_integer, fuzzy_not(q.is_zero)]):
return True
def _eval_is_nonnegative(self):
if self.args[1].is_positive:
return True
def _eval_is_nonpositive(self):
if self.args[1].is_negative:
return True
def _eval_rewrite_as_floor(self, a, b, **kwargs):
from sympy.functions.elementary.integers import floor
return a - b*floor(a/b)
|
4936a6fcce4211159d3b82b91e41d5d87fe4ae1a22dd9eabd6dd1c689e754e43 | """sympify -- convert objects SymPy internal format"""
import typing
if typing.TYPE_CHECKING:
from typing import Any, Callable, Dict, Type
from inspect import getmro
from .compatibility import iterable
from .parameters import global_parameters
class SympifyError(ValueError):
def __init__(self, expr, base_exc=None):
self.expr = expr
self.base_exc = base_exc
def __str__(self):
if self.base_exc is None:
return "SympifyError: %r" % (self.expr,)
return ("Sympify of expression '%s' failed, because of exception being "
"raised:\n%s: %s" % (self.expr, self.base_exc.__class__.__name__,
str(self.base_exc)))
# See sympify docstring.
converter = {} # type: Dict[Type[Any], Callable[[Any], Basic]]
class CantSympify:
"""
Mix in this trait to a class to disallow sympification of its instances.
Examples
========
>>> from sympy.core.sympify import sympify, CantSympify
>>> class Something(dict):
... pass
...
>>> sympify(Something())
{}
>>> class Something(dict, CantSympify):
... pass
...
>>> sympify(Something())
Traceback (most recent call last):
...
SympifyError: SympifyError: {}
"""
pass
def _is_numpy_instance(a):
"""
Checks if an object is an instance of a type from the numpy module.
"""
# This check avoids unnecessarily importing NumPy. We check the whole
# __mro__ in case any base type is a numpy type.
return any(type_.__module__ == 'numpy'
for type_ in type(a).__mro__)
def _convert_numpy_types(a, **sympify_args):
"""
Converts a numpy datatype input to an appropriate SymPy type.
"""
import numpy as np
if not isinstance(a, np.floating):
if np.iscomplex(a):
return converter[complex](a.item())
else:
return sympify(a.item(), **sympify_args)
else:
try:
from sympy.core.numbers import Float
prec = np.finfo(a).nmant + 1
# E.g. double precision means prec=53 but nmant=52
# Leading bit of mantissa is always 1, so is not stored
a = str(list(np.reshape(np.asarray(a),
(1, np.size(a)))[0]))[1:-1]
return Float(a, precision=prec)
except NotImplementedError:
raise SympifyError('Translation for numpy float : %s '
'is not implemented' % a)
def sympify(a, locals=None, convert_xor=True, strict=False, rational=False,
evaluate=None):
"""
Converts an arbitrary expression to a type that can be used inside SymPy.
Explanation
===========
It will convert Python ints into instances of sympy.Integer,
floats into instances of sympy.Float, etc. It is also able to coerce symbolic
expressions which inherit from Basic. This can be useful in cooperation
with SAGE.
.. warning::
Note that this function uses ``eval``, and thus shouldn't be used on
unsanitized input.
If the argument is already a type that SymPy understands, it will do
nothing but return that value. This can be used at the beginning of a
function to ensure you are working with the correct type.
Examples
========
>>> from sympy import sympify
>>> sympify(2).is_integer
True
>>> sympify(2).is_real
True
>>> sympify(2.0).is_real
True
>>> sympify("2.0").is_real
True
>>> sympify("2e-45").is_real
True
If the expression could not be converted, a SympifyError is raised.
>>> sympify("x***2")
Traceback (most recent call last):
...
SympifyError: SympifyError: "could not parse 'x***2'"
Locals
------
The sympification happens with access to everything that is loaded
by ``from sympy import *``; anything used in a string that is not
defined by that import will be converted to a symbol. In the following,
the ``bitcount`` function is treated as a symbol and the ``O`` is
interpreted as the Order object (used with series) and it raises
an error when used improperly:
>>> s = 'bitcount(42)'
>>> sympify(s)
bitcount(42)
>>> sympify("O(x)")
O(x)
>>> sympify("O + 1")
Traceback (most recent call last):
...
TypeError: unbound method...
In order to have ``bitcount`` be recognized it can be imported into a
namespace dictionary and passed as locals:
>>> ns = {}
>>> exec('from sympy.core.evalf import bitcount', ns)
>>> sympify(s, locals=ns)
6
In order to have the ``O`` interpreted as a Symbol, identify it as such
in the namespace dictionary. This can be done in a variety of ways; all
three of the following are possibilities:
>>> from sympy import Symbol
>>> ns["O"] = Symbol("O") # method 1
>>> exec('from sympy.abc import O', ns) # method 2
>>> ns.update(dict(O=Symbol("O"))) # method 3
>>> sympify("O + 1", locals=ns)
O + 1
If you want *all* single-letter and Greek-letter variables to be symbols
then you can use the clashing-symbols dictionaries that have been defined
there as private variables: _clash1 (single-letter variables), _clash2
(the multi-letter Greek names) or _clash (both single and multi-letter
names that are defined in abc).
>>> from sympy.abc import _clash1
>>> set(_clash1)
{'E', 'I', 'N', 'O', 'Q', 'S'}
>>> sympify('I & Q', _clash1)
I & Q
Strict
------
If the option ``strict`` is set to ``True``, only the types for which an
explicit conversion has been defined are converted. In the other
cases, a SympifyError is raised.
>>> print(sympify(None))
None
>>> sympify(None, strict=True)
Traceback (most recent call last):
...
SympifyError: SympifyError: None
Evaluation
----------
If the option ``evaluate`` is set to ``False``, then arithmetic and
operators will be converted into their SymPy equivalents and the
``evaluate=False`` option will be added. Nested ``Add`` or ``Mul`` will
be denested first. This is done via an AST transformation that replaces
operators with their SymPy equivalents, so if an operand redefines any
of those operations, the redefined operators will not be used. If
argument a is not a string, the mathematical expression is evaluated
before being passed to sympify, so adding evaluate=False will still
return the evaluated result of expression.
>>> sympify('2**2 / 3 + 5')
19/3
>>> sympify('2**2 / 3 + 5', evaluate=False)
2**2/3 + 5
>>> sympify('4/2+7', evaluate=True)
9
>>> sympify('4/2+7', evaluate=False)
4/2 + 7
>>> sympify(4/2+7, evaluate=False)
9.00000000000000
Extending
---------
To extend ``sympify`` to convert custom objects (not derived from ``Basic``),
just define a ``_sympy_`` method to your class. You can do that even to
classes that you do not own by subclassing or adding the method at runtime.
>>> from sympy import Matrix
>>> class MyList1(object):
... def __iter__(self):
... yield 1
... yield 2
... return
... def __getitem__(self, i): return list(self)[i]
... def _sympy_(self): return Matrix(self)
>>> sympify(MyList1())
Matrix([
[1],
[2]])
If you do not have control over the class definition you could also use the
``converter`` global dictionary. The key is the class and the value is a
function that takes a single argument and returns the desired SymPy
object, e.g. ``converter[MyList] = lambda x: Matrix(x)``.
>>> class MyList2(object): # XXX Do not do this if you control the class!
... def __iter__(self): # Use _sympy_!
... yield 1
... yield 2
... return
... def __getitem__(self, i): return list(self)[i]
>>> from sympy.core.sympify import converter
>>> converter[MyList2] = lambda x: Matrix(x)
>>> sympify(MyList2())
Matrix([
[1],
[2]])
Notes
=====
The keywords ``rational`` and ``convert_xor`` are only used
when the input is a string.
convert_xor
-----------
>>> sympify('x^y',convert_xor=True)
x**y
>>> sympify('x^y',convert_xor=False)
x ^ y
rational
--------
>>> sympify('0.1',rational=False)
0.1
>>> sympify('0.1',rational=True)
1/10
Sometimes autosimplification during sympification results in expressions
that are very different in structure than what was entered. Until such
autosimplification is no longer done, the ``kernS`` function might be of
some use. In the example below you can see how an expression reduces to
-1 by autosimplification, but does not do so when ``kernS`` is used.
>>> from sympy.core.sympify import kernS
>>> from sympy.abc import x
>>> -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
-1
>>> s = '-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1'
>>> sympify(s)
-1
>>> kernS(s)
-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
Parameters
==========
a :
- any object defined in SymPy
- standard numeric python types: int, long, float, Decimal
- strings (like "0.09", "2e-19" or 'sin(x)')
- booleans, including ``None`` (will leave ``None`` unchanged)
- dict, lists, sets or tuples containing any of the above
convert_xor : boolean, optional
If true, treats XOR as exponentiation.
If False, treats XOR as XOR itself.
Used only when input is a string.
locals : any object defined in SymPy, optional
In order to have strings be recognized it can be imported
into a namespace dictionary and passed as locals.
strict : boolean, optional
If the option strict is set to True, only the types for which
an explicit conversion has been defined are converted. In the
other cases, a SympifyError is raised.
rational : boolean, optional
If true, converts floats into Rational.
If false, it lets floats remain as it is.
Used only when input is a string.
evaluate : boolean, optional
If False, then arithmetic and operators will be converted into
their SymPy equivalents. If True the expression will be evaluated
and the result will be returned.
"""
# XXX: If a is a Basic subclass rather than instance (e.g. sin rather than
# sin(x)) then a.__sympy__ will be the property. Only on the instance will
# a.__sympy__ give the *value* of the property (True). Since sympify(sin)
# was used for a long time we allow it to pass. However if strict=True as
# is the case in internal calls to _sympify then we only allow
# is_sympy=True.
#
# https://github.com/sympy/sympy/issues/20124
is_sympy = getattr(a, '__sympy__', None)
if is_sympy is True:
return a
elif is_sympy is not None:
if not strict:
return a
else:
raise SympifyError(a)
if isinstance(a, CantSympify):
raise SympifyError(a)
cls = getattr(a, "__class__", None)
if cls is None:
cls = type(a) # Probably an old-style class
conv = converter.get(cls, None)
if conv is not None:
return conv(a)
for superclass in getmro(cls):
try:
return converter[superclass](a)
except KeyError:
continue
if cls is type(None):
if strict:
raise SympifyError(a)
else:
return a
if evaluate is None:
evaluate = global_parameters.evaluate
# Support for basic numpy datatypes
if _is_numpy_instance(a):
import numpy as np
if np.isscalar(a):
return _convert_numpy_types(a, locals=locals,
convert_xor=convert_xor, strict=strict, rational=rational,
evaluate=evaluate)
_sympy_ = getattr(a, "_sympy_", None)
if _sympy_ is not None:
try:
return a._sympy_()
# XXX: Catches AttributeError: 'SympyConverter' object has no
# attribute 'tuple'
# This is probably a bug somewhere but for now we catch it here.
except AttributeError:
pass
if not strict:
# Put numpy array conversion _before_ float/int, see
# <https://github.com/sympy/sympy/issues/13924>.
flat = getattr(a, "flat", None)
if flat is not None:
shape = getattr(a, "shape", None)
if shape is not None:
from ..tensor.array import Array
return Array(a.flat, a.shape) # works with e.g. NumPy arrays
if not isinstance(a, str):
if _is_numpy_instance(a):
import numpy as np
assert not isinstance(a, np.number)
if isinstance(a, np.ndarray):
# Scalar arrays (those with zero dimensions) have sympify
# called on the scalar element.
if a.ndim == 0:
try:
return sympify(a.item(),
locals=locals,
convert_xor=convert_xor,
strict=strict,
rational=rational,
evaluate=evaluate)
except SympifyError:
pass
else:
# float and int can coerce size-one numpy arrays to their lone
# element. See issue https://github.com/numpy/numpy/issues/10404.
for coerce in (float, int):
try:
return sympify(coerce(a))
except (TypeError, ValueError, AttributeError, SympifyError):
continue
if strict:
raise SympifyError(a)
if iterable(a):
try:
return type(a)([sympify(x, locals=locals, convert_xor=convert_xor,
rational=rational, evaluate=evaluate) for x in a])
except TypeError:
# Not all iterables are rebuildable with their type.
pass
if not isinstance(a, str):
try:
a = str(a)
except Exception as exc:
raise SympifyError(a, exc)
from sympy.utilities.exceptions import SymPyDeprecationWarning
SymPyDeprecationWarning(
feature="String fallback in sympify",
useinstead= \
'sympify(str(obj)) or ' + \
'sympy.core.sympify.converter or obj._sympy_',
issue=18066,
deprecated_since_version='1.6'
).warn()
from sympy.parsing.sympy_parser import (parse_expr, TokenError,
standard_transformations)
from sympy.parsing.sympy_parser import convert_xor as t_convert_xor
from sympy.parsing.sympy_parser import rationalize as t_rationalize
transformations = standard_transformations
if rational:
transformations += (t_rationalize,)
if convert_xor:
transformations += (t_convert_xor,)
try:
a = a.replace('\n', '')
expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
except (TokenError, SyntaxError) as exc:
raise SympifyError('could not parse %r' % a, exc)
return expr
def _sympify(a):
"""
Short version of sympify for internal usage for __add__ and __eq__ methods
where it is ok to allow some things (like Python integers and floats) in
the expression. This excludes things (like strings) that are unwise to
allow into such an expression.
>>> from sympy import Integer
>>> Integer(1) == 1
True
>>> Integer(1) == '1'
False
>>> from sympy.abc import x
>>> x + 1
x + 1
>>> x + '1'
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'Symbol' and 'str'
see: sympify
"""
return sympify(a, strict=True)
def kernS(s):
"""Use a hack to try keep autosimplification from distributing a
a number into an Add; this modification doesn't
prevent the 2-arg Mul from becoming an Add, however.
Examples
========
>>> from sympy.core.sympify import kernS
>>> from sympy.abc import x, y
The 2-arg Mul distributes a number (or minus sign) across the terms
of an expression, but kernS will prevent that:
>>> 2*(x + y), -(x + 1)
(2*x + 2*y, -x - 1)
>>> kernS('2*(x + y)')
2*(x + y)
>>> kernS('-(x + 1)')
-(x + 1)
If use of the hack fails, the un-hacked string will be passed to sympify...
and you get what you get.
XXX This hack should not be necessary once issue 4596 has been resolved.
"""
import string
from random import choice
from sympy.core.symbol import Symbol
hit = False
quoted = '"' in s or "'" in s
if '(' in s and not quoted:
if s.count('(') != s.count(")"):
raise SympifyError('unmatched left parenthesis')
# strip all space from s
s = ''.join(s.split())
olds = s
# now use space to represent a symbol that
# will
# step 1. turn potential 2-arg Muls into 3-arg versions
# 1a. *( -> * *(
s = s.replace('*(', '* *(')
# 1b. close up exponentials
s = s.replace('** *', '**')
# 2. handle the implied multiplication of a negated
# parenthesized expression in two steps
# 2a: -(...) --> -( *(...)
target = '-( *('
s = s.replace('-(', target)
# 2b: double the matching closing parenthesis
# -( *(...) --> -( *(...))
i = nest = 0
assert target.endswith('(') # assumption below
while True:
j = s.find(target, i)
if j == -1:
break
j += len(target) - 1
for j in range(j, len(s)):
if s[j] == "(":
nest += 1
elif s[j] == ")":
nest -= 1
if nest == 0:
break
s = s[:j] + ")" + s[j:]
i = j + 2 # the first char after 2nd )
if ' ' in s:
# get a unique kern
kern = '_'
while kern in s:
kern += choice(string.ascii_letters + string.digits)
s = s.replace(' ', kern)
hit = kern in s
else:
hit = False
for i in range(2):
try:
expr = sympify(s)
break
except TypeError: # the kern might cause unknown errors...
if hit:
s = olds # maybe it didn't like the kern; use un-kerned s
hit = False
continue
expr = sympify(s) # let original error raise
if not hit:
return expr
rep = {Symbol(kern): 1}
def _clear(expr):
if isinstance(expr, (list, tuple, set)):
return type(expr)([_clear(e) for e in expr])
if hasattr(expr, 'subs'):
return expr.subs(rep, hack2=True)
return expr
expr = _clear(expr)
# hope that kern is not there anymore
return expr
# Avoid circular import
from .basic import Basic
|
5a85efb51a4cc58b3e735774d8ccbf69e23de86fad185a716e04cf59ae6ed879 | from collections import defaultdict
from functools import cmp_to_key, reduce
import operator
from .sympify import sympify
from .basic import Basic
from .singleton import S
from .operations import AssocOp, AssocOpDispatcher
from .cache import cacheit
from .logic import fuzzy_not, _fuzzy_group
from .expr import Expr
from .parameters import global_parameters
from .kind import KindDispatcher
# internal marker to indicate:
# "there are still non-commutative objects -- don't forget to process them"
class NC_Marker:
is_Order = False
is_Mul = False
is_Number = False
is_Poly = False
is_commutative = False
# Key for sorting commutative args in canonical order
_args_sortkey = cmp_to_key(Basic.compare)
def _mulsort(args):
# in-place sorting of args
args.sort(key=_args_sortkey)
def _unevaluated_Mul(*args):
"""Return a well-formed unevaluated Mul: Numbers are collected and
put in slot 0, any arguments that are Muls will be flattened, and args
are sorted. Use this when args have changed but you still want to return
an unevaluated Mul.
Examples
========
>>> from sympy.core.mul import _unevaluated_Mul as uMul
>>> from sympy import S, sqrt, Mul
>>> from sympy.abc import x
>>> a = uMul(*[S(3.0), x, S(2)])
>>> a.args[0]
6.00000000000000
>>> a.args[1]
x
Two unevaluated Muls with the same arguments will
always compare as equal during testing:
>>> m = uMul(sqrt(2), sqrt(3))
>>> m == uMul(sqrt(3), sqrt(2))
True
>>> u = Mul(sqrt(3), sqrt(2), evaluate=False)
>>> m == uMul(u)
True
>>> m == Mul(*m.args)
False
"""
args = list(args)
newargs = []
ncargs = []
co = S.One
while args:
a = args.pop()
if a.is_Mul:
c, nc = a.args_cnc()
args.extend(c)
if nc:
ncargs.append(Mul._from_args(nc))
elif a.is_Number:
co *= a
else:
newargs.append(a)
_mulsort(newargs)
if co is not S.One:
newargs.insert(0, co)
if ncargs:
newargs.append(Mul._from_args(ncargs))
return Mul._from_args(newargs)
class Mul(Expr, AssocOp):
"""
Expression representing multiplication operation for algebraic field.
Every argument of ``Mul()`` must be ``Expr``. Infix operator ``*``
on most scalar objects in SymPy calls this class.
Another use of ``Mul()`` is to represent the structure of abstract
multiplication so that its arguments can be substituted to return
different class. Refer to examples section for this.
``Mul()`` evaluates the argument unless ``evaluate=False`` is passed.
The evaluation logic includes:
1. Flattening
``Mul(x, Mul(y, z))`` -> ``Mul(x, y, z)``
2. Identity removing
``Mul(x, 1, y)`` -> ``Mul(x, y)``
3. Exponent collecting by ``.as_base_exp()``
``Mul(x, x**2)`` -> ``Pow(x, 3)``
4. Term sorting
``Mul(y, x, 2)`` -> ``Mul(2, x, y)``
Since multiplication can be vector space operation, arguments may
have the different :obj:`sympy.core.kind.Kind()`. Kind of the
resulting object is automatically inferred.
Examples
========
>>> from sympy import Mul
>>> from sympy.abc import x, y
>>> Mul(x, 1)
x
>>> Mul(x, x)
x**2
If ``evaluate=False`` is passed, result is not evaluated.
>>> Mul(1, 2, evaluate=False)
1*2
>>> Mul(x, x, evaluate=False)
x*x
``Mul()`` also represents the general structure of multiplication
operation.
>>> from sympy import MatrixSymbol
>>> A = MatrixSymbol('A', 2,2)
>>> expr = Mul(x,y).subs({y:A})
>>> expr
x*A
>>> type(expr)
<class 'sympy.matrices.expressions.matmul.MatMul'>
See Also
========
MatMul
"""
__slots__ = ()
is_Mul = True
_args_type = Expr
_kind_dispatcher = KindDispatcher("Mul_kind_dispatcher", commutative=True)
@property
def kind(self):
arg_kinds = (a.kind for a in self.args)
return self._kind_dispatcher(*arg_kinds)
def __neg__(self):
c, args = self.as_coeff_mul()
c = -c
if c is not S.One:
if args[0].is_Number:
args = list(args)
if c is S.NegativeOne:
args[0] = -args[0]
else:
args[0] *= c
else:
args = (c,) + args
return self._from_args(args, self.is_commutative)
@classmethod
def flatten(cls, seq):
"""Return commutative, noncommutative and order arguments by
combining related terms.
Notes
=====
* In an expression like ``a*b*c``, python process this through sympy
as ``Mul(Mul(a, b), c)``. This can have undesirable consequences.
- Sometimes terms are not combined as one would like:
{c.f. https://github.com/sympy/sympy/issues/4596}
>>> from sympy import Mul, sqrt
>>> from sympy.abc import x, y, z
>>> 2*(x + 1) # this is the 2-arg Mul behavior
2*x + 2
>>> y*(x + 1)*2
2*y*(x + 1)
>>> 2*(x + 1)*y # 2-arg result will be obtained first
y*(2*x + 2)
>>> Mul(2, x + 1, y) # all 3 args simultaneously processed
2*y*(x + 1)
>>> 2*((x + 1)*y) # parentheses can control this behavior
2*y*(x + 1)
Powers with compound bases may not find a single base to
combine with unless all arguments are processed at once.
Post-processing may be necessary in such cases.
{c.f. https://github.com/sympy/sympy/issues/5728}
>>> a = sqrt(x*sqrt(y))
>>> a**3
(x*sqrt(y))**(3/2)
>>> Mul(a,a,a)
(x*sqrt(y))**(3/2)
>>> a*a*a
x*sqrt(y)*sqrt(x*sqrt(y))
>>> _.subs(a.base, z).subs(z, a.base)
(x*sqrt(y))**(3/2)
- If more than two terms are being multiplied then all the
previous terms will be re-processed for each new argument.
So if each of ``a``, ``b`` and ``c`` were :class:`Mul`
expression, then ``a*b*c`` (or building up the product
with ``*=``) will process all the arguments of ``a`` and
``b`` twice: once when ``a*b`` is computed and again when
``c`` is multiplied.
Using ``Mul(a, b, c)`` will process all arguments once.
* The results of Mul are cached according to arguments, so flatten
will only be called once for ``Mul(a, b, c)``. If you can
structure a calculation so the arguments are most likely to be
repeats then this can save time in computing the answer. For
example, say you had a Mul, M, that you wished to divide by ``d[i]``
and multiply by ``n[i]`` and you suspect there are many repeats
in ``n``. It would be better to compute ``M*n[i]/d[i]`` rather
than ``M/d[i]*n[i]`` since every time n[i] is a repeat, the
product, ``M*n[i]`` will be returned without flattening -- the
cached value will be returned. If you divide by the ``d[i]``
first (and those are more unique than the ``n[i]``) then that will
create a new Mul, ``M/d[i]`` the args of which will be traversed
again when it is multiplied by ``n[i]``.
{c.f. https://github.com/sympy/sympy/issues/5706}
This consideration is moot if the cache is turned off.
NB
--
The validity of the above notes depends on the implementation
details of Mul and flatten which may change at any time. Therefore,
you should only consider them when your code is highly performance
sensitive.
Removal of 1 from the sequence is already handled by AssocOp.__new__.
"""
from sympy.calculus.util import AccumBounds
from sympy.matrices.expressions import MatrixExpr
rv = None
if len(seq) == 2:
a, b = seq
if b.is_Rational:
a, b = b, a
seq = [a, b]
assert not a is S.One
if not a.is_zero and a.is_Rational:
r, b = b.as_coeff_Mul()
if b.is_Add:
if r is not S.One: # 2-arg hack
# leave the Mul as a Mul?
ar = a*r
if ar is S.One:
arb = b
else:
arb = cls(a*r, b, evaluate=False)
rv = [arb], [], None
elif global_parameters.distribute and b.is_commutative:
r, b = b.as_coeff_Add()
bargs = [_keep_coeff(a, bi) for bi in Add.make_args(b)]
_addsort(bargs)
ar = a*r
if ar:
bargs.insert(0, ar)
bargs = [Add._from_args(bargs)]
rv = bargs, [], None
if rv:
return rv
# apply associativity, separate commutative part of seq
c_part = [] # out: commutative factors
nc_part = [] # out: non-commutative factors
nc_seq = []
coeff = S.One # standalone term
# e.g. 3 * ...
c_powers = [] # (base,exp) n
# e.g. (x,n) for x
num_exp = [] # (num-base, exp) y
# e.g. (3, y) for ... * 3 * ...
neg1e = S.Zero # exponent on -1 extracted from Number-based Pow and I
pnum_rat = {} # (num-base, Rat-exp) 1/2
# e.g. (3, 1/2) for ... * 3 * ...
order_symbols = None
# --- PART 1 ---
#
# "collect powers and coeff":
#
# o coeff
# o c_powers
# o num_exp
# o neg1e
# o pnum_rat
#
# NOTE: this is optimized for all-objects-are-commutative case
for o in seq:
# O(x)
if o.is_Order:
o, order_symbols = o.as_expr_variables(order_symbols)
# Mul([...])
if o.is_Mul:
if o.is_commutative:
seq.extend(o.args) # XXX zerocopy?
else:
# NCMul can have commutative parts as well
for q in o.args:
if q.is_commutative:
seq.append(q)
else:
nc_seq.append(q)
# append non-commutative marker, so we don't forget to
# process scheduled non-commutative objects
seq.append(NC_Marker)
continue
# 3
elif o.is_Number:
if o is S.NaN or coeff is S.ComplexInfinity and o.is_zero:
# we know for sure the result will be nan
return [S.NaN], [], None
elif coeff.is_Number or isinstance(coeff, AccumBounds): # it could be zoo
coeff *= o
if coeff is S.NaN:
# we know for sure the result will be nan
return [S.NaN], [], None
continue
elif isinstance(o, AccumBounds):
coeff = o.__mul__(coeff)
continue
elif o is S.ComplexInfinity:
if not coeff:
# 0 * zoo = NaN
return [S.NaN], [], None
coeff = S.ComplexInfinity
continue
elif o is S.ImaginaryUnit:
neg1e += S.Half
continue
elif o.is_commutative:
# e
# o = b
b, e = o.as_base_exp()
# y
# 3
if o.is_Pow:
if b.is_Number:
# get all the factors with numeric base so they can be
# combined below, but don't combine negatives unless
# the exponent is an integer
if e.is_Rational:
if e.is_Integer:
coeff *= Pow(b, e) # it is an unevaluated power
continue
elif e.is_negative: # also a sign of an unevaluated power
seq.append(Pow(b, e))
continue
elif b.is_negative:
neg1e += e
b = -b
if b is not S.One:
pnum_rat.setdefault(b, []).append(e)
continue
elif b.is_positive or e.is_integer:
num_exp.append((b, e))
continue
c_powers.append((b, e))
# NON-COMMUTATIVE
# TODO: Make non-commutative exponents not combine automatically
else:
if o is not NC_Marker:
nc_seq.append(o)
# process nc_seq (if any)
while nc_seq:
o = nc_seq.pop(0)
if not nc_part:
nc_part.append(o)
continue
# b c b+c
# try to combine last terms: a * a -> a
o1 = nc_part.pop()
b1, e1 = o1.as_base_exp()
b2, e2 = o.as_base_exp()
new_exp = e1 + e2
# Only allow powers to combine if the new exponent is
# not an Add. This allow things like a**2*b**3 == a**5
# if a.is_commutative == False, but prohibits
# a**x*a**y and x**a*x**b from combining (x,y commute).
if b1 == b2 and (not new_exp.is_Add):
o12 = b1 ** new_exp
# now o12 could be a commutative object
if o12.is_commutative:
seq.append(o12)
continue
else:
nc_seq.insert(0, o12)
else:
nc_part.append(o1)
nc_part.append(o)
# We do want a combined exponent if it would not be an Add, such as
# y 2y 3y
# x * x -> x
# We determine if two exponents have the same term by using
# as_coeff_Mul.
#
# Unfortunately, this isn't smart enough to consider combining into
# exponents that might already be adds, so things like:
# z - y y
# x * x will be left alone. This is because checking every possible
# combination can slow things down.
# gather exponents of common bases...
def _gather(c_powers):
common_b = {} # b:e
for b, e in c_powers:
co = e.as_coeff_Mul()
common_b.setdefault(b, {}).setdefault(
co[1], []).append(co[0])
for b, d in common_b.items():
for di, li in d.items():
d[di] = Add(*li)
new_c_powers = []
for b, e in common_b.items():
new_c_powers.extend([(b, c*t) for t, c in e.items()])
return new_c_powers
# in c_powers
c_powers = _gather(c_powers)
# and in num_exp
num_exp = _gather(num_exp)
# --- PART 2 ---
#
# o process collected powers (x**0 -> 1; x**1 -> x; otherwise Pow)
# o combine collected powers (2**x * 3**x -> 6**x)
# with numeric base
# ................................
# now we have:
# - coeff:
# - c_powers: (b, e)
# - num_exp: (2, e)
# - pnum_rat: {(1/3, [1/3, 2/3, 1/4])}
# 0 1
# x -> 1 x -> x
# this should only need to run twice; if it fails because
# it needs to be run more times, perhaps this should be
# changed to a "while True" loop -- the only reason it
# isn't such now is to allow a less-than-perfect result to
# be obtained rather than raising an error or entering an
# infinite loop
for i in range(2):
new_c_powers = []
changed = False
for b, e in c_powers:
if e.is_zero:
# canceling out infinities yields NaN
if (b.is_Add or b.is_Mul) and any(infty in b.args
for infty in (S.ComplexInfinity, S.Infinity,
S.NegativeInfinity)):
return [S.NaN], [], None
continue
if e is S.One:
if b.is_Number:
coeff *= b
continue
p = b
if e is not S.One:
p = Pow(b, e)
# check to make sure that the base doesn't change
# after exponentiation; to allow for unevaluated
# Pow, we only do so if b is not already a Pow
if p.is_Pow and not b.is_Pow:
bi = b
b, e = p.as_base_exp()
if b != bi:
changed = True
c_part.append(p)
new_c_powers.append((b, e))
# there might have been a change, but unless the base
# matches some other base, there is nothing to do
if changed and len({
b for b, e in new_c_powers}) != len(new_c_powers):
# start over again
c_part = []
c_powers = _gather(new_c_powers)
else:
break
# x x x
# 2 * 3 -> 6
inv_exp_dict = {} # exp:Mul(num-bases) x x
# e.g. x:6 for ... * 2 * 3 * ...
for b, e in num_exp:
inv_exp_dict.setdefault(e, []).append(b)
for e, b in inv_exp_dict.items():
inv_exp_dict[e] = cls(*b)
c_part.extend([Pow(b, e) for e, b in inv_exp_dict.items() if e])
# b, e -> e' = sum(e), b
# {(1/5, [1/3]), (1/2, [1/12, 1/4]} -> {(1/3, [1/5, 1/2])}
comb_e = {}
for b, e in pnum_rat.items():
comb_e.setdefault(Add(*e), []).append(b)
del pnum_rat
# process them, reducing exponents to values less than 1
# and updating coeff if necessary else adding them to
# num_rat for further processing
num_rat = []
for e, b in comb_e.items():
b = cls(*b)
if e.q == 1:
coeff *= Pow(b, e)
continue
if e.p > e.q:
e_i, ep = divmod(e.p, e.q)
coeff *= Pow(b, e_i)
e = Rational(ep, e.q)
num_rat.append((b, e))
del comb_e
# extract gcd of bases in num_rat
# 2**(1/3)*6**(1/4) -> 2**(1/3+1/4)*3**(1/4)
pnew = defaultdict(list)
i = 0 # steps through num_rat which may grow
while i < len(num_rat):
bi, ei = num_rat[i]
grow = []
for j in range(i + 1, len(num_rat)):
bj, ej = num_rat[j]
g = bi.gcd(bj)
if g is not S.One:
# 4**r1*6**r2 -> 2**(r1+r2) * 2**r1 * 3**r2
# this might have a gcd with something else
e = ei + ej
if e.q == 1:
coeff *= Pow(g, e)
else:
if e.p > e.q:
e_i, ep = divmod(e.p, e.q) # change e in place
coeff *= Pow(g, e_i)
e = Rational(ep, e.q)
grow.append((g, e))
# update the jth item
num_rat[j] = (bj/g, ej)
# update bi that we are checking with
bi = bi/g
if bi is S.One:
break
if bi is not S.One:
obj = Pow(bi, ei)
if obj.is_Number:
coeff *= obj
else:
# changes like sqrt(12) -> 2*sqrt(3)
for obj in Mul.make_args(obj):
if obj.is_Number:
coeff *= obj
else:
assert obj.is_Pow
bi, ei = obj.args
pnew[ei].append(bi)
num_rat.extend(grow)
i += 1
# combine bases of the new powers
for e, b in pnew.items():
pnew[e] = cls(*b)
# handle -1 and I
if neg1e:
# treat I as (-1)**(1/2) and compute -1's total exponent
p, q = neg1e.as_numer_denom()
# if the integer part is odd, extract -1
n, p = divmod(p, q)
if n % 2:
coeff = -coeff
# if it's a multiple of 1/2 extract I
if q == 2:
c_part.append(S.ImaginaryUnit)
elif p:
# see if there is any positive base this power of
# -1 can join
neg1e = Rational(p, q)
for e, b in pnew.items():
if e == neg1e and b.is_positive:
pnew[e] = -b
break
else:
# keep it separate; we've already evaluated it as
# much as possible so evaluate=False
c_part.append(Pow(S.NegativeOne, neg1e, evaluate=False))
# add all the pnew powers
c_part.extend([Pow(b, e) for e, b in pnew.items()])
# oo, -oo
if (coeff is S.Infinity) or (coeff is S.NegativeInfinity):
def _handle_for_oo(c_part, coeff_sign):
new_c_part = []
for t in c_part:
if t.is_extended_positive:
continue
if t.is_extended_negative:
coeff_sign *= -1
continue
new_c_part.append(t)
return new_c_part, coeff_sign
c_part, coeff_sign = _handle_for_oo(c_part, 1)
nc_part, coeff_sign = _handle_for_oo(nc_part, coeff_sign)
coeff *= coeff_sign
# zoo
if coeff is S.ComplexInfinity:
# zoo might be
# infinite_real + bounded_im
# bounded_real + infinite_im
# infinite_real + infinite_im
# and non-zero real or imaginary will not change that status.
c_part = [c for c in c_part if not (fuzzy_not(c.is_zero) and
c.is_extended_real is not None)]
nc_part = [c for c in nc_part if not (fuzzy_not(c.is_zero) and
c.is_extended_real is not None)]
# 0
elif coeff.is_zero:
# we know for sure the result will be 0 except the multiplicand
# is infinity or a matrix
if any(isinstance(c, MatrixExpr) for c in nc_part):
return [coeff], nc_part, order_symbols
if any(c.is_finite == False for c in c_part):
return [S.NaN], [], order_symbols
return [coeff], [], order_symbols
# check for straggling Numbers that were produced
_new = []
for i in c_part:
if i.is_Number:
coeff *= i
else:
_new.append(i)
c_part = _new
# order commutative part canonically
_mulsort(c_part)
# current code expects coeff to be always in slot-0
if coeff is not S.One:
c_part.insert(0, coeff)
# we are done
if (global_parameters.distribute and not nc_part and len(c_part) == 2 and
c_part[0].is_Number and c_part[0].is_finite and c_part[1].is_Add):
# 2*(1+a) -> 2 + 2 * a
coeff = c_part[0]
c_part = [Add(*[coeff*f for f in c_part[1].args])]
return c_part, nc_part, order_symbols
def _eval_power(self, e):
# don't break up NC terms: (A*B)**3 != A**3*B**3, it is A*B*A*B*A*B
cargs, nc = self.args_cnc(split_1=False)
if e.is_Integer:
return Mul(*[Pow(b, e, evaluate=False) for b in cargs]) * \
Pow(Mul._from_args(nc), e, evaluate=False)
if e.is_Rational and e.q == 2:
from sympy.core.power import integer_nthroot
from sympy.functions.elementary.complexes import sign
if self.is_imaginary:
a = self.as_real_imag()[1]
if a.is_Rational:
n, d = abs(a/2).as_numer_denom()
n, t = integer_nthroot(n, 2)
if t:
d, t = integer_nthroot(d, 2)
if t:
r = sympify(n)/d
return _unevaluated_Mul(r**e.p, (1 + sign(a)*S.ImaginaryUnit)**e.p)
p = Pow(self, e, evaluate=False)
if e.is_Rational or e.is_Float:
return p._eval_expand_power_base()
return p
@classmethod
def class_key(cls):
return 3, 0, cls.__name__
def _eval_evalf(self, prec):
c, m = self.as_coeff_Mul()
if c is S.NegativeOne:
if m.is_Mul:
rv = -AssocOp._eval_evalf(m, prec)
else:
mnew = m._eval_evalf(prec)
if mnew is not None:
m = mnew
rv = -m
else:
rv = AssocOp._eval_evalf(self, prec)
if rv.is_number:
return rv.expand()
return rv
@property
def _mpc_(self):
"""
Convert self to an mpmath mpc if possible
"""
from sympy.core.numbers import I, Float
im_part, imag_unit = self.as_coeff_Mul()
if not imag_unit == I:
# ValueError may seem more reasonable but since it's a @property,
# we need to use AttributeError to keep from confusing things like
# hasattr.
raise AttributeError("Cannot convert Mul to mpc. Must be of the form Number*I")
return (Float(0)._mpf_, Float(im_part)._mpf_)
@cacheit
def as_two_terms(self):
"""Return head and tail of self.
This is the most efficient way to get the head and tail of an
expression.
- if you want only the head, use self.args[0];
- if you want to process the arguments of the tail then use
self.as_coef_mul() which gives the head and a tuple containing
the arguments of the tail when treated as a Mul.
- if you want the coefficient when self is treated as an Add
then use self.as_coeff_add()[0]
Examples
========
>>> from sympy.abc import x, y
>>> (3*x*y).as_two_terms()
(3, x*y)
"""
args = self.args
if len(args) == 1:
return S.One, self
elif len(args) == 2:
return args
else:
return args[0], self._new_rawargs(*args[1:])
@cacheit
def as_coefficients_dict(self):
"""Return a dictionary mapping terms to their coefficient.
Since the dictionary is a defaultdict, inquiries about terms which
were not present will return a coefficient of 0. The dictionary
is considered to have a single term.
Examples
========
>>> from sympy.abc import a, x
>>> (3*a*x).as_coefficients_dict()
{a*x: 3}
>>> _[a]
0
"""
d = defaultdict(int)
args = self.args
if len(args) == 1 or not args[0].is_Number:
d[self] = S.One
else:
d[self._new_rawargs(*args[1:])] = args[0]
return d
@cacheit
def as_coeff_mul(self, *deps, rational=True, **kwargs):
if deps:
from sympy.utilities.iterables import sift
l1, l2 = sift(self.args, lambda x: x.has(*deps), binary=True)
return self._new_rawargs(*l2), tuple(l1)
args = self.args
if args[0].is_Number:
if not rational or args[0].is_Rational:
return args[0], args[1:]
elif args[0].is_extended_negative:
return S.NegativeOne, (-args[0],) + args[1:]
return S.One, args
def as_coeff_Mul(self, rational=False):
"""
Efficiently extract the coefficient of a product.
"""
coeff, args = self.args[0], self.args[1:]
if coeff.is_Number:
if not rational or coeff.is_Rational:
if len(args) == 1:
return coeff, args[0]
else:
return coeff, self._new_rawargs(*args)
elif coeff.is_extended_negative:
return S.NegativeOne, self._new_rawargs(*((-coeff,) + args))
return S.One, self
def as_real_imag(self, deep=True, **hints):
from sympy import Abs, expand_mul, im, re
other = []
coeffr = []
coeffi = []
addterms = S.One
for a in self.args:
r, i = a.as_real_imag()
if i.is_zero:
coeffr.append(r)
elif r.is_zero:
coeffi.append(i*S.ImaginaryUnit)
elif a.is_commutative:
# search for complex conjugate pairs:
for i, x in enumerate(other):
if x == a.conjugate():
coeffr.append(Abs(x)**2)
del other[i]
break
else:
if a.is_Add:
addterms *= a
else:
other.append(a)
else:
other.append(a)
m = self.func(*other)
if hints.get('ignore') == m:
return
if len(coeffi) % 2:
imco = im(coeffi.pop(0))
# all other pairs make a real factor; they will be
# put into reco below
else:
imco = S.Zero
reco = self.func(*(coeffr + coeffi))
r, i = (reco*re(m), reco*im(m))
if addterms == 1:
if m == 1:
if imco.is_zero:
return (reco, S.Zero)
else:
return (S.Zero, reco*imco)
if imco is S.Zero:
return (r, i)
return (-imco*i, imco*r)
addre, addim = expand_mul(addterms, deep=False).as_real_imag()
if imco is S.Zero:
return (r*addre - i*addim, i*addre + r*addim)
else:
r, i = -imco*i, imco*r
return (r*addre - i*addim, r*addim + i*addre)
@staticmethod
def _expandsums(sums):
"""
Helper function for _eval_expand_mul.
sums must be a list of instances of Basic.
"""
L = len(sums)
if L == 1:
return sums[0].args
terms = []
left = Mul._expandsums(sums[:L//2])
right = Mul._expandsums(sums[L//2:])
terms = [Mul(a, b) for a in left for b in right]
added = Add(*terms)
return Add.make_args(added) # it may have collapsed down to one term
def _eval_expand_mul(self, **hints):
from sympy import fraction
# Handle things like 1/(x*(x + 1)), which are automatically converted
# to 1/x*1/(x + 1)
expr = self
n, d = fraction(expr)
if d.is_Mul:
n, d = [i._eval_expand_mul(**hints) if i.is_Mul else i
for i in (n, d)]
expr = n/d
if not expr.is_Mul:
return expr
plain, sums, rewrite = [], [], False
for factor in expr.args:
if factor.is_Add:
sums.append(factor)
rewrite = True
else:
if factor.is_commutative:
plain.append(factor)
else:
sums.append(Basic(factor)) # Wrapper
if not rewrite:
return expr
else:
plain = self.func(*plain)
if sums:
deep = hints.get("deep", False)
terms = self.func._expandsums(sums)
args = []
for term in terms:
t = self.func(plain, term)
if t.is_Mul and any(a.is_Add for a in t.args) and deep:
t = t._eval_expand_mul()
args.append(t)
return Add(*args)
else:
return plain
@cacheit
def _eval_derivative(self, s):
args = list(self.args)
terms = []
for i in range(len(args)):
d = args[i].diff(s)
if d:
# Note: reduce is used in step of Mul as Mul is unable to
# handle subtypes and operation priority:
terms.append(reduce(lambda x, y: x*y, (args[:i] + [d] + args[i + 1:]), S.One))
return Add.fromiter(terms)
@cacheit
def _eval_derivative_n_times(self, s, n):
from sympy import Integer, factorial, prod, Sum, Max
from sympy.ntheory.multinomial import multinomial_coefficients_iterator
from .function import AppliedUndef
from .symbol import Symbol, symbols, Dummy
if not isinstance(s, AppliedUndef) and not isinstance(s, Symbol):
# other types of s may not be well behaved, e.g.
# (cos(x)*sin(y)).diff([[x, y, z]])
return super()._eval_derivative_n_times(s, n)
args = self.args
m = len(args)
if isinstance(n, (int, Integer)):
# https://en.wikipedia.org/wiki/General_Leibniz_rule#More_than_two_factors
terms = []
for kvals, c in multinomial_coefficients_iterator(m, n):
p = prod([arg.diff((s, k)) for k, arg in zip(kvals, args)])
terms.append(c * p)
return Add(*terms)
kvals = symbols("k1:%i" % m, cls=Dummy)
klast = n - sum(kvals)
nfact = factorial(n)
e, l = (# better to use the multinomial?
nfact/prod(map(factorial, kvals))/factorial(klast)*\
prod([args[t].diff((s, kvals[t])) for t in range(m-1)])*\
args[-1].diff((s, Max(0, klast))),
[(k, 0, n) for k in kvals])
return Sum(e, *l)
def _eval_difference_delta(self, n, step):
from sympy.series.limitseq import difference_delta as dd
arg0 = self.args[0]
rest = Mul(*self.args[1:])
return (arg0.subs(n, n + step) * dd(rest, n, step) + dd(arg0, n, step) *
rest)
def _matches_simple(self, expr, repl_dict):
# handle (w*3).matches('x*5') -> {w: x*5/3}
coeff, terms = self.as_coeff_Mul()
terms = Mul.make_args(terms)
if len(terms) == 1:
newexpr = self.__class__._combine_inverse(expr, coeff)
return terms[0].matches(newexpr, repl_dict)
return
def matches(self, expr, repl_dict={}, old=False):
expr = sympify(expr)
repl_dict = repl_dict.copy()
if self.is_commutative and expr.is_commutative:
return self._matches_commutative(expr, repl_dict, old)
elif self.is_commutative is not expr.is_commutative:
return None
# Proceed only if both both expressions are non-commutative
c1, nc1 = self.args_cnc()
c2, nc2 = expr.args_cnc()
c1, c2 = [c or [1] for c in [c1, c2]]
# TODO: Should these be self.func?
comm_mul_self = Mul(*c1)
comm_mul_expr = Mul(*c2)
repl_dict = comm_mul_self.matches(comm_mul_expr, repl_dict, old)
# If the commutative arguments didn't match and aren't equal, then
# then the expression as a whole doesn't match
if repl_dict is None and c1 != c2:
return None
# Now match the non-commutative arguments, expanding powers to
# multiplications
nc1 = Mul._matches_expand_pows(nc1)
nc2 = Mul._matches_expand_pows(nc2)
repl_dict = Mul._matches_noncomm(nc1, nc2, repl_dict)
return repl_dict or None
@staticmethod
def _matches_expand_pows(arg_list):
new_args = []
for arg in arg_list:
if arg.is_Pow and arg.exp > 0:
new_args.extend([arg.base] * arg.exp)
else:
new_args.append(arg)
return new_args
@staticmethod
def _matches_noncomm(nodes, targets, repl_dict={}):
"""Non-commutative multiplication matcher.
`nodes` is a list of symbols within the matcher multiplication
expression, while `targets` is a list of arguments in the
multiplication expression being matched against.
"""
repl_dict = repl_dict.copy()
# List of possible future states to be considered
agenda = []
# The current matching state, storing index in nodes and targets
state = (0, 0)
node_ind, target_ind = state
# Mapping between wildcard indices and the index ranges they match
wildcard_dict = {}
repl_dict = repl_dict.copy()
while target_ind < len(targets) and node_ind < len(nodes):
node = nodes[node_ind]
if node.is_Wild:
Mul._matches_add_wildcard(wildcard_dict, state)
states_matches = Mul._matches_new_states(wildcard_dict, state,
nodes, targets)
if states_matches:
new_states, new_matches = states_matches
agenda.extend(new_states)
if new_matches:
for match in new_matches:
repl_dict[match] = new_matches[match]
if not agenda:
return None
else:
state = agenda.pop()
node_ind, target_ind = state
return repl_dict
@staticmethod
def _matches_add_wildcard(dictionary, state):
node_ind, target_ind = state
if node_ind in dictionary:
begin, end = dictionary[node_ind]
dictionary[node_ind] = (begin, target_ind)
else:
dictionary[node_ind] = (target_ind, target_ind)
@staticmethod
def _matches_new_states(dictionary, state, nodes, targets):
node_ind, target_ind = state
node = nodes[node_ind]
target = targets[target_ind]
# Don't advance at all if we've exhausted the targets but not the nodes
if target_ind >= len(targets) - 1 and node_ind < len(nodes) - 1:
return None
if node.is_Wild:
match_attempt = Mul._matches_match_wilds(dictionary, node_ind,
nodes, targets)
if match_attempt:
# If the same node has been matched before, don't return
# anything if the current match is diverging from the previous
# match
other_node_inds = Mul._matches_get_other_nodes(dictionary,
nodes, node_ind)
for ind in other_node_inds:
other_begin, other_end = dictionary[ind]
curr_begin, curr_end = dictionary[node_ind]
other_targets = targets[other_begin:other_end + 1]
current_targets = targets[curr_begin:curr_end + 1]
for curr, other in zip(current_targets, other_targets):
if curr != other:
return None
# A wildcard node can match more than one target, so only the
# target index is advanced
new_state = [(node_ind, target_ind + 1)]
# Only move on to the next node if there is one
if node_ind < len(nodes) - 1:
new_state.append((node_ind + 1, target_ind + 1))
return new_state, match_attempt
else:
# If we're not at a wildcard, then make sure we haven't exhausted
# nodes but not targets, since in this case one node can only match
# one target
if node_ind >= len(nodes) - 1 and target_ind < len(targets) - 1:
return None
match_attempt = node.matches(target)
if match_attempt:
return [(node_ind + 1, target_ind + 1)], match_attempt
elif node == target:
return [(node_ind + 1, target_ind + 1)], None
else:
return None
@staticmethod
def _matches_match_wilds(dictionary, wildcard_ind, nodes, targets):
"""Determine matches of a wildcard with sub-expression in `target`."""
wildcard = nodes[wildcard_ind]
begin, end = dictionary[wildcard_ind]
terms = targets[begin:end + 1]
# TODO: Should this be self.func?
mul = Mul(*terms) if len(terms) > 1 else terms[0]
return wildcard.matches(mul)
@staticmethod
def _matches_get_other_nodes(dictionary, nodes, node_ind):
"""Find other wildcards that may have already been matched."""
other_node_inds = []
for ind in dictionary:
if nodes[ind] == nodes[node_ind]:
other_node_inds.append(ind)
return other_node_inds
@staticmethod
def _combine_inverse(lhs, rhs):
"""
Returns lhs/rhs, but treats arguments like symbols, so things
like oo/oo return 1 (instead of a nan) and ``I`` behaves like
a symbol instead of sqrt(-1).
"""
from sympy.simplify.simplify import signsimp
from .symbol import Dummy
if lhs == rhs:
return S.One
def check(l, r):
if l.is_Float and r.is_comparable:
# if both objects are added to 0 they will share the same "normalization"
# and are more likely to compare the same. Since Add(foo, 0) will not allow
# the 0 to pass, we use __add__ directly.
return l.__add__(0) == r.evalf().__add__(0)
return False
if check(lhs, rhs) or check(rhs, lhs):
return S.One
if any(i.is_Pow or i.is_Mul for i in (lhs, rhs)):
# gruntz and limit wants a literal I to not combine
# with a power of -1
d = Dummy('I')
_i = {S.ImaginaryUnit: d}
i_ = {d: S.ImaginaryUnit}
a = lhs.xreplace(_i).as_powers_dict()
b = rhs.xreplace(_i).as_powers_dict()
blen = len(b)
for bi in tuple(b.keys()):
if bi in a:
a[bi] -= b.pop(bi)
if not a[bi]:
a.pop(bi)
if len(b) != blen:
lhs = Mul(*[k**v for k, v in a.items()]).xreplace(i_)
rhs = Mul(*[k**v for k, v in b.items()]).xreplace(i_)
return signsimp(lhs/rhs)
def as_powers_dict(self):
d = defaultdict(int)
for term in self.args:
for b, e in term.as_powers_dict().items():
d[b] += e
return d
def as_numer_denom(self):
# don't use _from_args to rebuild the numerators and denominators
# as the order is not guaranteed to be the same once they have
# been separated from each other
numers, denoms = list(zip(*[f.as_numer_denom() for f in self.args]))
return self.func(*numers), self.func(*denoms)
def as_base_exp(self):
e1 = None
bases = []
nc = 0
for m in self.args:
b, e = m.as_base_exp()
if not b.is_commutative:
nc += 1
if e1 is None:
e1 = e
elif e != e1 or nc > 1:
return self, S.One
bases.append(b)
return self.func(*bases), e1
def _eval_is_polynomial(self, syms):
return all(term._eval_is_polynomial(syms) for term in self.args)
def _eval_is_rational_function(self, syms):
return all(term._eval_is_rational_function(syms) for term in self.args)
def _eval_is_meromorphic(self, x, a):
return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args),
quick_exit=True)
def _eval_is_algebraic_expr(self, syms):
return all(term._eval_is_algebraic_expr(syms) for term in self.args)
_eval_is_commutative = lambda self: _fuzzy_group(
a.is_commutative for a in self.args)
def _eval_is_complex(self):
comp = _fuzzy_group(a.is_complex for a in self.args)
if comp is False:
if any(a.is_infinite for a in self.args):
if any(a.is_zero is not False for a in self.args):
return None
return False
return comp
def _eval_is_finite(self):
if all(a.is_finite for a in self.args):
return True
if any(a.is_infinite for a in self.args):
if all(a.is_zero is False for a in self.args):
return False
def _eval_is_infinite(self):
if any(a.is_infinite for a in self.args):
if any(a.is_zero for a in self.args):
return S.NaN.is_infinite
if any(a.is_zero is None for a in self.args):
return None
return True
def _eval_is_rational(self):
r = _fuzzy_group((a.is_rational for a in self.args), quick_exit=True)
if r:
return r
elif r is False:
return self.is_zero
def _eval_is_algebraic(self):
r = _fuzzy_group((a.is_algebraic for a in self.args), quick_exit=True)
if r:
return r
elif r is False:
return self.is_zero
def _eval_is_zero(self):
zero = infinite = False
for a in self.args:
z = a.is_zero
if z:
if infinite:
return # 0*oo is nan and nan.is_zero is None
zero = True
else:
if not a.is_finite:
if zero:
return # 0*oo is nan and nan.is_zero is None
infinite = True
if zero is False and z is None: # trap None
zero = None
return zero
# without involving odd/even checks this code would suffice:
#_eval_is_integer = lambda self: _fuzzy_group(
# (a.is_integer for a in self.args), quick_exit=True)
def _eval_is_integer(self):
is_rational = self._eval_is_rational()
if is_rational is False:
return False
numerators = []
denominators = []
for a in self.args:
if a.is_integer:
numerators.append(a)
elif a.is_Rational:
n, d = a.as_numer_denom()
numerators.append(n)
denominators.append(d)
elif a.is_Pow:
b, e = a.as_base_exp()
if not b.is_integer or not e.is_integer: return
if e.is_negative:
denominators.append(b)
else:
# for integer b and positive integer e: a = b**e would be integer
assert not e.is_positive
# for self being rational and e equal to zero: a = b**e would be 1
assert not e.is_zero
return # sign of e unknown -> self.is_integer cannot be decided
else:
return
if not denominators:
return True
odd = lambda ints: all(i.is_odd for i in ints)
even = lambda ints: any(i.is_even for i in ints)
if odd(numerators) and even(denominators):
return False
elif even(numerators) and denominators == [2]:
return True
def _eval_is_polar(self):
has_polar = any(arg.is_polar for arg in self.args)
return has_polar and \
all(arg.is_polar or arg.is_positive for arg in self.args)
def _eval_is_extended_real(self):
return self._eval_real_imag(True)
def _eval_real_imag(self, real):
zero = False
t_not_re_im = None
for t in self.args:
if (t.is_complex or t.is_infinite) is False and t.is_extended_real is False:
return False
elif t.is_imaginary: # I
real = not real
elif t.is_extended_real: # 2
if not zero:
z = t.is_zero
if not z and zero is False:
zero = z
elif z:
if all(a.is_finite for a in self.args):
return True
return
elif t.is_extended_real is False:
# symbolic or literal like `2 + I` or symbolic imaginary
if t_not_re_im:
return # complex terms might cancel
t_not_re_im = t
elif t.is_imaginary is False: # symbolic like `2` or `2 + I`
if t_not_re_im:
return # complex terms might cancel
t_not_re_im = t
else:
return
if t_not_re_im:
if t_not_re_im.is_extended_real is False:
if real: # like 3
return zero # 3*(smthng like 2 + I or i) is not real
if t_not_re_im.is_imaginary is False: # symbolic 2 or 2 + I
if not real: # like I
return zero # I*(smthng like 2 or 2 + I) is not real
elif zero is False:
return real # can't be trumped by 0
elif real:
return real # doesn't matter what zero is
def _eval_is_imaginary(self):
z = self.is_zero
if z:
return False
if self.is_finite is False:
return False
elif z is False and self.is_finite is True:
return self._eval_real_imag(False)
def _eval_is_hermitian(self):
return self._eval_herm_antiherm(True)
def _eval_herm_antiherm(self, real):
one_nc = zero = one_neither = False
for t in self.args:
if not t.is_commutative:
if one_nc:
return
one_nc = True
if t.is_antihermitian:
real = not real
elif t.is_hermitian:
if not zero:
z = t.is_zero
if not z and zero is False:
zero = z
elif z:
if all(a.is_finite for a in self.args):
return True
return
elif t.is_hermitian is False:
if one_neither:
return
one_neither = True
else:
return
if one_neither:
if real:
return zero
elif zero is False or real:
return real
def _eval_is_antihermitian(self):
z = self.is_zero
if z:
return False
elif z is False:
return self._eval_herm_antiherm(False)
def _eval_is_irrational(self):
for t in self.args:
a = t.is_irrational
if a:
others = list(self.args)
others.remove(t)
if all((x.is_rational and fuzzy_not(x.is_zero)) is True for x in others):
return True
return
if a is None:
return
if all(x.is_real for x in self.args):
return False
def _eval_is_extended_positive(self):
"""Return True if self is positive, False if not, and None if it
cannot be determined.
Explanation
===========
This algorithm is non-recursive and works by keeping track of the
sign which changes when a negative or nonpositive is encountered.
Whether a nonpositive or nonnegative is seen is also tracked since
the presence of these makes it impossible to return True, but
possible to return False if the end result is nonpositive. e.g.
pos * neg * nonpositive -> pos or zero -> None is returned
pos * neg * nonnegative -> neg or zero -> False is returned
"""
return self._eval_pos_neg(1)
def _eval_pos_neg(self, sign):
saw_NON = saw_NOT = False
for t in self.args:
if t.is_extended_positive:
continue
elif t.is_extended_negative:
sign = -sign
elif t.is_zero:
if all(a.is_finite for a in self.args):
return False
return
elif t.is_extended_nonpositive:
sign = -sign
saw_NON = True
elif t.is_extended_nonnegative:
saw_NON = True
# FIXME: is_positive/is_negative is False doesn't take account of
# Symbol('x', infinite=True, extended_real=True) which has
# e.g. is_positive is False but has uncertain sign.
elif t.is_positive is False:
sign = -sign
if saw_NOT:
return
saw_NOT = True
elif t.is_negative is False:
if saw_NOT:
return
saw_NOT = True
else:
return
if sign == 1 and saw_NON is False and saw_NOT is False:
return True
if sign < 0:
return False
def _eval_is_extended_negative(self):
return self._eval_pos_neg(-1)
def _eval_is_odd(self):
is_integer = self.is_integer
if is_integer:
r, acc = True, 1
for t in self.args:
if not t.is_integer:
return None
elif t.is_even:
r = False
elif t.is_integer:
if r is False:
pass
elif acc != 1 and (acc + t).is_odd:
r = False
elif t.is_odd is None:
r = None
acc = t
return r
# !integer -> !odd
elif is_integer is False:
return False
def _eval_is_even(self):
is_integer = self.is_integer
if is_integer:
return fuzzy_not(self.is_odd)
elif is_integer is False:
return False
def _eval_is_composite(self):
"""
Here we count the number of arguments that have a minimum value
greater than two.
If there are more than one of such a symbol then the result is composite.
Else, the result cannot be determined.
"""
number_of_args = 0 # count of symbols with minimum value greater than one
for arg in self.args:
if not (arg.is_integer and arg.is_positive):
return None
if (arg-1).is_positive:
number_of_args += 1
if number_of_args > 1:
return True
def _eval_subs(self, old, new):
from sympy.functions.elementary.complexes import sign
from sympy.ntheory.factor_ import multiplicity
from sympy.simplify.powsimp import powdenest
from sympy.simplify.radsimp import fraction
if not old.is_Mul:
return None
# try keep replacement literal so -2*x doesn't replace 4*x
if old.args[0].is_Number and old.args[0] < 0:
if self.args[0].is_Number:
if self.args[0] < 0:
return self._subs(-old, -new)
return None
def base_exp(a):
# if I and -1 are in a Mul, they get both end up with
# a -1 base (see issue 6421); all we want here are the
# true Pow or exp separated into base and exponent
from sympy import exp
if a.is_Pow or isinstance(a, exp):
return a.as_base_exp()
return a, S.One
def breakup(eq):
"""break up powers of eq when treated as a Mul:
b**(Rational*e) -> b**e, Rational
commutatives come back as a dictionary {b**e: Rational}
noncommutatives come back as a list [(b**e, Rational)]
"""
(c, nc) = (defaultdict(int), list())
for a in Mul.make_args(eq):
a = powdenest(a)
(b, e) = base_exp(a)
if e is not S.One:
(co, _) = e.as_coeff_mul()
b = Pow(b, e/co)
e = co
if a.is_commutative:
c[b] += e
else:
nc.append([b, e])
return (c, nc)
def rejoin(b, co):
"""
Put rational back with exponent; in general this is not ok, but
since we took it from the exponent for analysis, it's ok to put
it back.
"""
(b, e) = base_exp(b)
return Pow(b, e*co)
def ndiv(a, b):
"""if b divides a in an extractive way (like 1/4 divides 1/2
but not vice versa, and 2/5 does not divide 1/3) then return
the integer number of times it divides, else return 0.
"""
if not b.q % a.q or not a.q % b.q:
return int(a/b)
return 0
# give Muls in the denominator a chance to be changed (see issue 5651)
# rv will be the default return value
rv = None
n, d = fraction(self)
self2 = self
if d is not S.One:
self2 = n._subs(old, new)/d._subs(old, new)
if not self2.is_Mul:
return self2._subs(old, new)
if self2 != self:
rv = self2
# Now continue with regular substitution.
# handle the leading coefficient and use it to decide if anything
# should even be started; we always know where to find the Rational
# so it's a quick test
co_self = self2.args[0]
co_old = old.args[0]
co_xmul = None
if co_old.is_Rational and co_self.is_Rational:
# if coeffs are the same there will be no updating to do
# below after breakup() step; so skip (and keep co_xmul=None)
if co_old != co_self:
co_xmul = co_self.extract_multiplicatively(co_old)
elif co_old.is_Rational:
return rv
# break self and old into factors
(c, nc) = breakup(self2)
(old_c, old_nc) = breakup(old)
# update the coefficients if we had an extraction
# e.g. if co_self were 2*(3/35*x)**2 and co_old = 3/5
# then co_self in c is replaced by (3/5)**2 and co_residual
# is 2*(1/7)**2
if co_xmul and co_xmul.is_Rational and abs(co_old) != 1:
mult = S(multiplicity(abs(co_old), co_self))
c.pop(co_self)
if co_old in c:
c[co_old] += mult
else:
c[co_old] = mult
co_residual = co_self/co_old**mult
else:
co_residual = 1
# do quick tests to see if we can't succeed
ok = True
if len(old_nc) > len(nc):
# more non-commutative terms
ok = False
elif len(old_c) > len(c):
# more commutative terms
ok = False
elif {i[0] for i in old_nc}.difference({i[0] for i in nc}):
# unmatched non-commutative bases
ok = False
elif set(old_c).difference(set(c)):
# unmatched commutative terms
ok = False
elif any(sign(c[b]) != sign(old_c[b]) for b in old_c):
# differences in sign
ok = False
if not ok:
return rv
if not old_c:
cdid = None
else:
rat = []
for (b, old_e) in old_c.items():
c_e = c[b]
rat.append(ndiv(c_e, old_e))
if not rat[-1]:
return rv
cdid = min(rat)
if not old_nc:
ncdid = None
for i in range(len(nc)):
nc[i] = rejoin(*nc[i])
else:
ncdid = 0 # number of nc replacements we did
take = len(old_nc) # how much to look at each time
limit = cdid or S.Infinity # max number that we can take
failed = [] # failed terms will need subs if other terms pass
i = 0
while limit and i + take <= len(nc):
hit = False
# the bases must be equivalent in succession, and
# the powers must be extractively compatible on the
# first and last factor but equal in between.
rat = []
for j in range(take):
if nc[i + j][0] != old_nc[j][0]:
break
elif j == 0:
rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
elif j == take - 1:
rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
elif nc[i + j][1] != old_nc[j][1]:
break
else:
rat.append(1)
j += 1
else:
ndo = min(rat)
if ndo:
if take == 1:
if cdid:
ndo = min(cdid, ndo)
nc[i] = Pow(new, ndo)*rejoin(nc[i][0],
nc[i][1] - ndo*old_nc[0][1])
else:
ndo = 1
# the left residual
l = rejoin(nc[i][0], nc[i][1] - ndo*
old_nc[0][1])
# eliminate all middle terms
mid = new
# the right residual (which may be the same as the middle if take == 2)
ir = i + take - 1
r = (nc[ir][0], nc[ir][1] - ndo*
old_nc[-1][1])
if r[1]:
if i + take < len(nc):
nc[i:i + take] = [l*mid, r]
else:
r = rejoin(*r)
nc[i:i + take] = [l*mid*r]
else:
# there was nothing left on the right
nc[i:i + take] = [l*mid]
limit -= ndo
ncdid += ndo
hit = True
if not hit:
# do the subs on this failing factor
failed.append(i)
i += 1
else:
if not ncdid:
return rv
# although we didn't fail, certain nc terms may have
# failed so we rebuild them after attempting a partial
# subs on them
failed.extend(range(i, len(nc)))
for i in failed:
nc[i] = rejoin(*nc[i]).subs(old, new)
# rebuild the expression
if cdid is None:
do = ncdid
elif ncdid is None:
do = cdid
else:
do = min(ncdid, cdid)
margs = []
for b in c:
if b in old_c:
# calculate the new exponent
e = c[b] - old_c[b]*do
margs.append(rejoin(b, e))
else:
margs.append(rejoin(b.subs(old, new), c[b]))
if cdid and not ncdid:
# in case we are replacing commutative with non-commutative,
# we want the new term to come at the front just like the
# rest of this routine
margs = [Pow(new, cdid)] + margs
return co_residual*self2.func(*margs)*self2.func(*nc)
def _eval_nseries(self, x, n, logx, cdir=0):
from sympy import degree, Mul, Order, ceiling, powsimp, PolynomialError
from itertools import product
def coeff_exp(term, x):
coeff, exp = S.One, S.Zero
for factor in Mul.make_args(term):
if factor.has(x):
base, exp = factor.as_base_exp()
if base != x:
try:
return term.leadterm(x)
except ValueError:
return term, S.Zero
else:
coeff *= factor
return coeff, exp
ords = []
try:
for t in self.args:
coeff, exp = t.leadterm(x)
if not coeff.has(x):
ords.append((t, exp))
else:
raise ValueError
n0 = sum(t[1] for t in ords)
facs = []
for t, m in ords:
n1 = ceiling(n - n0 + m)
s = t.nseries(x, n=n1, logx=logx, cdir=cdir)
ns = s.getn()
if ns is not None:
if ns < n1: # less than expected
n -= n1 - ns # reduce n
facs.append(s.removeO())
except (ValueError, NotImplementedError, TypeError, AttributeError):
facs = [t.nseries(x, n=n, logx=logx, cdir=cdir) for t in self.args]
res = powsimp(self.func(*facs).expand(), combine='exp', deep=True)
if res.has(Order):
res += Order(x**n, x)
return res
res = S.Zero
ords2 = [Add.make_args(factor) for factor in facs]
for fac in product(*ords2):
ords3 = [coeff_exp(term, x) for term in fac]
coeffs, powers = zip(*ords3)
power = sum(powers)
if power < n:
res += Mul(*coeffs)*(x**power)
if self.is_polynomial(x):
try:
if degree(self, x) != degree(res, x):
res += Order(x**n, x)
except PolynomialError:
pass
else:
return res
for i in (1, 2, 3):
if (res - self).subs(x, i) is not S.Zero:
res += Order(x**n, x)
break
return res
def _eval_as_leading_term(self, x, cdir=0):
return self.func(*[t.as_leading_term(x, cdir=cdir) for t in self.args])
def _eval_conjugate(self):
return self.func(*[t.conjugate() for t in self.args])
def _eval_transpose(self):
return self.func(*[t.transpose() for t in self.args[::-1]])
def _eval_adjoint(self):
return self.func(*[t.adjoint() for t in self.args[::-1]])
def _sage_(self):
s = 1
for x in self.args:
s *= x._sage_()
return s
def as_content_primitive(self, radical=False, clear=True):
"""Return the tuple (R, self/R) where R is the positive Rational
extracted from self.
Examples
========
>>> from sympy import sqrt
>>> (-3*sqrt(2)*(2 - 2*sqrt(2))).as_content_primitive()
(6, -sqrt(2)*(1 - sqrt(2)))
See docstring of Expr.as_content_primitive for more examples.
"""
coef = S.One
args = []
for i, a in enumerate(self.args):
c, p = a.as_content_primitive(radical=radical, clear=clear)
coef *= c
if p is not S.One:
args.append(p)
# don't use self._from_args here to reconstruct args
# since there may be identical args now that should be combined
# e.g. (2+2*x)*(3+3*x) should be (6, (1 + x)**2) not (6, (1+x)*(1+x))
return coef, self.func(*args)
def as_ordered_factors(self, order=None):
"""Transform an expression into an ordered list of factors.
Examples
========
>>> from sympy import sin, cos
>>> from sympy.abc import x, y
>>> (2*x*y*sin(x)*cos(x)).as_ordered_factors()
[2, x, y, sin(x), cos(x)]
"""
cpart, ncpart = self.args_cnc()
cpart.sort(key=lambda expr: expr.sort_key(order=order))
return cpart + ncpart
@property
def _sorted_args(self):
return tuple(self.as_ordered_factors())
mul = AssocOpDispatcher('mul')
def prod(a, start=1):
"""Return product of elements of a. Start with int 1 so if only
ints are included then an int result is returned.
Examples
========
>>> from sympy import prod, S
>>> prod(range(3))
0
>>> type(_) is int
True
>>> prod([S(2), 3])
6
>>> _.is_Integer
True
You can start the product at something other than 1:
>>> prod([1, 2], 3)
6
"""
return reduce(operator.mul, a, start)
def _keep_coeff(coeff, factors, clear=True, sign=False):
"""Return ``coeff*factors`` unevaluated if necessary.
If ``clear`` is False, do not keep the coefficient as a factor
if it can be distributed on a single factor such that one or
more terms will still have integer coefficients.
If ``sign`` is True, allow a coefficient of -1 to remain factored out.
Examples
========
>>> from sympy.core.mul import _keep_coeff
>>> from sympy.abc import x, y
>>> from sympy import S
>>> _keep_coeff(S.Half, x + 2)
(x + 2)/2
>>> _keep_coeff(S.Half, x + 2, clear=False)
x/2 + 1
>>> _keep_coeff(S.Half, (x + 2)*y, clear=False)
y*(x + 2)/2
>>> _keep_coeff(S(-1), x + y)
-x - y
>>> _keep_coeff(S(-1), x + y, sign=True)
-(x + y)
"""
if not coeff.is_Number:
if factors.is_Number:
factors, coeff = coeff, factors
else:
return coeff*factors
if factors is S.One:
return coeff
if coeff is S.One:
return factors
elif coeff is S.NegativeOne and not sign:
return -factors
elif factors.is_Add:
if not clear and coeff.is_Rational and coeff.q != 1:
args = [i.as_coeff_Mul() for i in factors.args]
args = [(_keep_coeff(c, coeff), m) for c, m in args]
if any(c == int(c) for c, _ in args):
return Add._from_args([Mul._from_args(
i[1:] if i[0] == 1 else i) for i in args])
return Mul(coeff, factors, evaluate=False)
elif factors.is_Mul:
margs = list(factors.args)
if margs[0].is_Number:
margs[0] *= coeff
if margs[0] == 1:
margs.pop(0)
else:
margs.insert(0, coeff)
return Mul._from_args(margs)
else:
m = coeff*factors
if m.is_Number and not factors.is_Number:
m = Mul._from_args((coeff, factors))
return m
def expand_2arg(e):
from sympy.simplify.simplify import bottom_up
def do(e):
if e.is_Mul:
c, r = e.as_coeff_Mul()
if c.is_Number and r.is_Add:
return _unevaluated_Add(*[c*ri for ri in r.args])
return e
return bottom_up(e, do)
from .numbers import Rational
from .power import Pow
from .add import Add, _addsort, _unevaluated_Add
|
f021803dff8716de667aeb2ea5a4e54154165e024143a2c399c7525e29cefe11 | from sympy.core.expr import Expr
from sympy.core.symbol import Dummy
from sympy.core.sympify import _sympify
from sympy.polys.polyerrors import CoercionFailed
from sympy.polys.polytools import Poly, parallel_poly_from_expr
from sympy.polys.domains import QQ
from sympy.polys.matrices import DomainMatrix
from sympy.polys.matrices.domainscalar import DomainScalar
class MutablePolyDenseMatrix:
"""
A mutable matrix of objects from poly module or to operate with them.
Examples
========
>>> from sympy.polys.polymatrix import PolyMatrix
>>> from sympy import Symbol, Poly
>>> x = Symbol('x')
>>> pm1 = PolyMatrix([[Poly(x**2, x), Poly(-x, x)], [Poly(x**3, x), Poly(-1 + x, x)]])
>>> v1 = PolyMatrix([[1, 0], [-1, 0]], x)
>>> pm1*v1
PolyMatrix([
[ x**2 + x, 0],
[x**3 - x + 1, 0]], ring=QQ[x])
>>> pm1.ring
ZZ[x]
>>> v1*pm1
PolyMatrix([
[ x**2, -x],
[-x**2, x]], ring=QQ[x])
>>> pm2 = PolyMatrix([[Poly(x**2, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(1, x, domain='QQ'), \
Poly(x**3, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(-x**3, x, domain='QQ')]])
>>> v2 = PolyMatrix([1, 0, 0, 0, 0, 0], x)
>>> v2.ring
QQ[x]
>>> pm2*v2
PolyMatrix([[x**2]], ring=QQ[x])
"""
def __new__(cls, *args, ring=None):
if not args:
# PolyMatrix(ring=QQ[x])
if ring is None:
raise TypeError("The ring needs to be specified for an empty PolyMatrix")
rows, cols, items, gens = 0, 0, [], ()
elif isinstance(args[0], list):
elements, gens = args[0], args[1:]
if not elements:
# PolyMatrix([])
rows, cols, items = 0, 0, []
elif isinstance(elements[0], (list, tuple)):
# PolyMatrix([[1, 2]], x)
rows, cols = len(elements), len(elements[0])
items = [e for row in elements for e in row]
else:
# PolyMatrix([1, 2], x)
rows, cols = len(elements), 1
items = elements
elif [type(a) for a in args[:3]] == [int, int, list]:
# PolyMatrix(2, 2, [1, 2, 3, 4], x)
rows, cols, items, gens = args[0], args[1], args[2], args[3:]
elif [type(a) for a in args[:3]] == [int, int, type(lambda: 0)]:
# PolyMatrix(2, 2, lambda i, j: i+j, x)
rows, cols, func, gens = args[0], args[1], args[2], args[3:]
items = [func(i, j) for i in range(rows) for j in range(cols)]
else:
raise TypeError("Invalid arguments")
# PolyMatrix([[1]], x, y) vs PolyMatrix([[1]], (x, y))
if len(gens) == 1 and isinstance(gens[0], tuple):
gens = gens[0]
# gens is now a tuple (x, y)
return cls.from_list(rows, cols, items, gens, ring)
@classmethod
def from_list(cls, rows, cols, items, gens, ring):
# items can be Expr, Poly, or a mix of Expr and Poly
items = [_sympify(item) for item in items]
if items and all(isinstance(item, Poly) for item in items):
polys = True
else:
polys = False
# Identify the ring for the polys
if ring is not None:
# Parse a domain string like 'QQ[x]'
if isinstance(ring, str):
ring = Poly(0, Dummy(), domain=ring).domain
elif polys:
p = items[0]
for p2 in items[1:]:
p, _ = p.unify(p2)
ring = p.domain[p.gens]
else:
items, info = parallel_poly_from_expr(items, gens, field=True)
ring = info['domain'][info['gens']]
polys = True
# Efficiently convert when all elements are Poly
if polys:
p_ring = Poly(0, ring.symbols, domain=ring.domain)
to_ring = ring.ring.from_list
convert_poly = lambda p: to_ring(p.unify(p_ring)[0].rep.rep)
elements = [convert_poly(p) for p in items]
else:
convert_expr = ring.from_sympy
elements = [convert_expr(e.as_expr()) for e in items]
# Convert to domain elements and construct DomainMatrix
elements_lol = [[elements[i*cols + j] for j in range(cols)] for i in range(rows)]
dm = DomainMatrix(elements_lol, (rows, cols), ring)
return cls.from_dm(dm)
@classmethod
def from_dm(cls, dm):
obj = super().__new__(cls)
dm = dm.to_sparse()
R = dm.domain
obj._dm = dm
obj.ring = R
obj.domain = R.domain
obj.gens = R.symbols
return obj
def to_Matrix(self):
return self._dm.to_Matrix()
@classmethod
def from_Matrix(cls, other, *gens, ring=None):
return cls(*other.shape, other._mat, *gens, ring=ring)
def set_gens(self, gens):
return self.from_Matrix(self.to_Matrix(), gens)
def __repr__(self):
if self.rows * self.cols:
return 'Poly' + repr(self.to_Matrix())[:-1] + f', ring={self.ring})'
else:
return f'PolyMatrix({self.rows}, {self.cols}, [], ring={self.ring})'
@property
def shape(self):
return self._dm.shape
@property
def rows(self):
return self.shape[0]
@property
def cols(self):
return self.shape[1]
def __len__(self):
return self.rows * self.cols
def __getitem__(self, key):
def to_poly(v):
ground = self._dm.domain.domain
gens = self._dm.domain.symbols
return Poly(v.to_dict(), gens, domain=ground)
dm = self._dm
if isinstance(key, slice):
items = dm.flat()[key]
return [to_poly(item) for item in items]
elif isinstance(key, int):
i, j = divmod(key, self.cols)
e = dm[i,j]
return to_poly(e.element)
i, j = key
if isinstance(i, int) and isinstance(j, int):
return to_poly(dm[i, j].element)
else:
return self.from_dm(dm[i, j])
def __eq__(self, other):
if not isinstance(self, type(other)):
return NotImplemented
return self._dm == other._dm
def __add__(self, other):
if isinstance(other, type(self)):
return self.from_dm(self._dm + other._dm)
return NotImplemented
def __sub__(self, other):
if isinstance(other, type(self)):
return self.from_dm(self._dm - other._dm)
return NotImplemented
def __mul__(self, other):
if isinstance(other, type(self)):
return self.from_dm(self._dm * other._dm)
elif isinstance(other, int):
other = _sympify(other)
if isinstance(other, Expr):
Kx = self.ring
try:
other_ds = DomainScalar(Kx.from_sympy(other), Kx)
except (CoercionFailed, ValueError):
other_ds = DomainScalar.from_sympy(other)
return self.from_dm(self._dm * other_ds)
return NotImplemented
def __rmul__(self, other):
if isinstance(other, int):
other = _sympify(other)
if isinstance(other, Expr):
other_ds = DomainScalar.from_sympy(other)
return self.from_dm(other_ds * self._dm)
return NotImplemented
def __truediv__(self, other):
if isinstance(other, Poly):
other = other.as_expr()
elif isinstance(other, int):
other = _sympify(other)
if not isinstance(other, Expr):
return NotImplemented
other = self.domain.from_sympy(other)
inverse = self.ring.convert_from(1/other, self.domain)
inverse = DomainScalar(inverse, self.ring)
dm = self._dm * inverse
return self.from_dm(dm)
def __neg__(self):
return self.from_dm(-self._dm)
def transpose(self):
return self.from_dm(self._dm.transpose())
def row_join(self, other):
dm = DomainMatrix.hstack(self._dm, other._dm)
return self.from_dm(dm)
def col_join(self, other):
dm = DomainMatrix.vstack(self._dm, other._dm)
return self.from_dm(dm)
def applyfunc(self, func):
M = self.to_Matrix().applyfunc(func)
return self.from_Matrix(M, self.gens)
@classmethod
def eye(cls, n, gens):
return cls.from_dm(DomainMatrix.eye(n, QQ[gens]))
@classmethod
def zeros(cls, m, n, gens):
return cls.from_dm(DomainMatrix.zeros((m, n), QQ[gens]))
def rref(self, simplify='ignore', normalize_last='ignore'):
# If this is K[x] then computes RREF in ground field K.
if not (self.domain.is_Field and all(p.is_ground for p in self)):
raise ValueError("PolyMatrix rref is only for ground field elements")
dm = self._dm
dm_ground = dm.convert_to(dm.domain.domain)
dm_rref, pivots = dm_ground.rref()
dm_rref = dm_rref.convert_to(dm.domain)
return self.from_dm(dm_rref), pivots
def nullspace(self):
# If this is K[x] then computes nullspace in ground field K.
if not (self.domain.is_Field and all(p.is_ground for p in self)):
raise ValueError("PolyMatrix nullspace is only for ground field elements")
dm = self._dm
K, Kx = self.domain, self.ring
dm_null_rows = dm.convert_to(K).nullspace().convert_to(Kx)
dm_null = dm_null_rows.transpose()
dm_basis = [dm_null[:,i] for i in range(dm_null.shape[1])]
return [self.from_dm(dmvec) for dmvec in dm_basis]
def rank(self):
return self.cols - len(self.nullspace())
MutablePolyMatrix = PolyMatrix = MutablePolyDenseMatrix
|
61db39fc398ac7a14649caf5ca5353409d46a0635d227602b1fc0cfc3ade45a2 | """OO layer for several polynomial representations. """
from sympy import oo
from sympy.core.sympify import CantSympify
from sympy.polys.polyerrors import CoercionFailed, NotReversible, NotInvertible
from sympy.polys.polyutils import PicklableWithSlots
class GenericPoly(PicklableWithSlots):
"""Base class for low-level polynomial representations. """
def ground_to_ring(f):
"""Make the ground domain a ring. """
return f.set_domain(f.dom.get_ring())
def ground_to_field(f):
"""Make the ground domain a field. """
return f.set_domain(f.dom.get_field())
def ground_to_exact(f):
"""Make the ground domain exact. """
return f.set_domain(f.dom.get_exact())
@classmethod
def _perify_factors(per, result, include):
if include:
coeff, factors = result
else:
coeff = result
factors = [ (per(g), k) for g, k in factors ]
if include:
return coeff, factors
else:
return factors
from sympy.polys.densebasic import (
dmp_validate,
dup_normal, dmp_normal,
dup_convert, dmp_convert,
dmp_from_sympy,
dup_strip,
dup_degree, dmp_degree_in,
dmp_degree_list,
dmp_negative_p,
dup_LC, dmp_ground_LC,
dup_TC, dmp_ground_TC,
dmp_ground_nth,
dmp_one, dmp_ground,
dmp_zero_p, dmp_one_p, dmp_ground_p,
dup_from_dict, dmp_from_dict,
dmp_to_dict,
dmp_deflate,
dmp_inject, dmp_eject,
dmp_terms_gcd,
dmp_list_terms, dmp_exclude,
dmp_slice_in, dmp_permute,
dmp_to_tuple,)
from sympy.polys.densearith import (
dmp_add_ground,
dmp_sub_ground,
dmp_mul_ground,
dmp_quo_ground,
dmp_exquo_ground,
dmp_abs,
dup_neg, dmp_neg,
dup_add, dmp_add,
dup_sub, dmp_sub,
dup_mul, dmp_mul,
dmp_sqr,
dup_pow, dmp_pow,
dmp_pdiv,
dmp_prem,
dmp_pquo,
dmp_pexquo,
dmp_div,
dup_rem, dmp_rem,
dmp_quo,
dmp_exquo,
dmp_add_mul, dmp_sub_mul,
dmp_max_norm,
dmp_l1_norm)
from sympy.polys.densetools import (
dmp_clear_denoms,
dmp_integrate_in,
dmp_diff_in,
dmp_eval_in,
dup_revert,
dmp_ground_trunc,
dmp_ground_content,
dmp_ground_primitive,
dmp_ground_monic,
dmp_compose,
dup_decompose,
dup_shift,
dup_transform,
dmp_lift)
from sympy.polys.euclidtools import (
dup_half_gcdex, dup_gcdex, dup_invert,
dmp_subresultants,
dmp_resultant,
dmp_discriminant,
dmp_inner_gcd,
dmp_gcd,
dmp_lcm,
dmp_cancel)
from sympy.polys.sqfreetools import (
dup_gff_list,
dmp_norm,
dmp_sqf_p,
dmp_sqf_norm,
dmp_sqf_part,
dmp_sqf_list, dmp_sqf_list_include)
from sympy.polys.factortools import (
dup_cyclotomic_p, dmp_irreducible_p,
dmp_factor_list, dmp_factor_list_include)
from sympy.polys.rootisolation import (
dup_isolate_real_roots_sqf,
dup_isolate_real_roots,
dup_isolate_all_roots_sqf,
dup_isolate_all_roots,
dup_refine_real_root,
dup_count_real_roots,
dup_count_complex_roots,
dup_sturm)
from sympy.polys.polyerrors import (
UnificationFailed,
PolynomialError)
def init_normal_DMP(rep, lev, dom):
return DMP(dmp_normal(rep, lev, dom), dom, lev)
class DMP(PicklableWithSlots, CantSympify):
"""Dense Multivariate Polynomials over `K`. """
__slots__ = ('rep', 'lev', 'dom', 'ring')
def __init__(self, rep, dom, lev=None, ring=None):
if lev is not None:
if type(rep) is dict:
rep = dmp_from_dict(rep, lev, dom)
elif type(rep) is not list:
rep = dmp_ground(dom.convert(rep), lev)
else:
rep, lev = dmp_validate(rep)
self.rep = rep
self.lev = lev
self.dom = dom
self.ring = ring
def __repr__(f):
return "%s(%s, %s, %s)" % (f.__class__.__name__, f.rep, f.dom, f.ring)
def __hash__(f):
return hash((f.__class__.__name__, f.to_tuple(), f.lev, f.dom, f.ring))
def unify(f, g):
"""Unify representations of two multivariate polynomials. """
if not isinstance(g, DMP) or f.lev != g.lev:
raise UnificationFailed("can't unify %s with %s" % (f, g))
if f.dom == g.dom and f.ring == g.ring:
return f.lev, f.dom, f.per, f.rep, g.rep
else:
lev, dom = f.lev, f.dom.unify(g.dom)
ring = f.ring
if g.ring is not None:
if ring is not None:
ring = ring.unify(g.ring)
else:
ring = g.ring
F = dmp_convert(f.rep, lev, f.dom, dom)
G = dmp_convert(g.rep, lev, g.dom, dom)
def per(rep, dom=dom, lev=lev, kill=False):
if kill:
if not lev:
return rep
else:
lev -= 1
return DMP(rep, dom, lev, ring)
return lev, dom, per, F, G
def per(f, rep, dom=None, kill=False, ring=None):
"""Create a DMP out of the given representation. """
lev = f.lev
if kill:
if not lev:
return rep
else:
lev -= 1
if dom is None:
dom = f.dom
if ring is None:
ring = f.ring
return DMP(rep, dom, lev, ring)
@classmethod
def zero(cls, lev, dom, ring=None):
return DMP(0, dom, lev, ring)
@classmethod
def one(cls, lev, dom, ring=None):
return DMP(1, dom, lev, ring)
@classmethod
def from_list(cls, rep, lev, dom):
"""Create an instance of ``cls`` given a list of native coefficients. """
return cls(dmp_convert(rep, lev, None, dom), dom, lev)
@classmethod
def from_sympy_list(cls, rep, lev, dom):
"""Create an instance of ``cls`` given a list of SymPy coefficients. """
return cls(dmp_from_sympy(rep, lev, dom), dom, lev)
def to_dict(f, zero=False):
"""Convert ``f`` to a dict representation with native coefficients. """
return dmp_to_dict(f.rep, f.lev, f.dom, zero=zero)
def to_sympy_dict(f, zero=False):
"""Convert ``f`` to a dict representation with SymPy coefficients. """
rep = dmp_to_dict(f.rep, f.lev, f.dom, zero=zero)
for k, v in rep.items():
rep[k] = f.dom.to_sympy(v)
return rep
def to_list(f):
"""Convert ``f`` to a list representation with native coefficients. """
return f.rep
def to_sympy_list(f):
"""Convert ``f`` to a list representation with SymPy coefficients. """
def sympify_nested_list(rep):
out = []
for val in rep:
if isinstance(val, list):
out.append(sympify_nested_list(val))
else:
out.append(f.dom.to_sympy(val))
return out
return sympify_nested_list(f.rep)
def to_tuple(f):
"""
Convert ``f`` to a tuple representation with native coefficients.
This is needed for hashing.
"""
return dmp_to_tuple(f.rep, f.lev)
@classmethod
def from_dict(cls, rep, lev, dom):
"""Construct and instance of ``cls`` from a ``dict`` representation. """
return cls(dmp_from_dict(rep, lev, dom), dom, lev)
@classmethod
def from_monoms_coeffs(cls, monoms, coeffs, lev, dom, ring=None):
return DMP(dict(list(zip(monoms, coeffs))), dom, lev, ring)
def to_ring(f):
"""Make the ground domain a ring. """
return f.convert(f.dom.get_ring())
def to_field(f):
"""Make the ground domain a field. """
return f.convert(f.dom.get_field())
def to_exact(f):
"""Make the ground domain exact. """
return f.convert(f.dom.get_exact())
def convert(f, dom):
"""Convert the ground domain of ``f``. """
if f.dom == dom:
return f
else:
return DMP(dmp_convert(f.rep, f.lev, f.dom, dom), dom, f.lev)
def slice(f, m, n, j=0):
"""Take a continuous subsequence of terms of ``f``. """
return f.per(dmp_slice_in(f.rep, m, n, j, f.lev, f.dom))
def coeffs(f, order=None):
"""Returns all non-zero coefficients from ``f`` in lex order. """
return [ c for _, c in dmp_list_terms(f.rep, f.lev, f.dom, order=order) ]
def monoms(f, order=None):
"""Returns all non-zero monomials from ``f`` in lex order. """
return [ m for m, _ in dmp_list_terms(f.rep, f.lev, f.dom, order=order) ]
def terms(f, order=None):
"""Returns all non-zero terms from ``f`` in lex order. """
return dmp_list_terms(f.rep, f.lev, f.dom, order=order)
def all_coeffs(f):
"""Returns all coefficients from ``f``. """
if not f.lev:
if not f:
return [f.dom.zero]
else:
return [ c for c in f.rep ]
else:
raise PolynomialError('multivariate polynomials not supported')
def all_monoms(f):
"""Returns all monomials from ``f``. """
if not f.lev:
n = dup_degree(f.rep)
if n < 0:
return [(0,)]
else:
return [ (n - i,) for i, c in enumerate(f.rep) ]
else:
raise PolynomialError('multivariate polynomials not supported')
def all_terms(f):
"""Returns all terms from a ``f``. """
if not f.lev:
n = dup_degree(f.rep)
if n < 0:
return [((0,), f.dom.zero)]
else:
return [ ((n - i,), c) for i, c in enumerate(f.rep) ]
else:
raise PolynomialError('multivariate polynomials not supported')
def lift(f):
"""Convert algebraic coefficients to rationals. """
return f.per(dmp_lift(f.rep, f.lev, f.dom), dom=f.dom.dom)
def deflate(f):
"""Reduce degree of `f` by mapping `x_i^m` to `y_i`. """
J, F = dmp_deflate(f.rep, f.lev, f.dom)
return J, f.per(F)
def inject(f, front=False):
"""Inject ground domain generators into ``f``. """
F, lev = dmp_inject(f.rep, f.lev, f.dom, front=front)
return f.__class__(F, f.dom.dom, lev)
def eject(f, dom, front=False):
"""Eject selected generators into the ground domain. """
F = dmp_eject(f.rep, f.lev, dom, front=front)
return f.__class__(F, dom, f.lev - len(dom.symbols))
def exclude(f):
r"""
Remove useless generators from ``f``.
Returns the removed generators and the new excluded ``f``.
Examples
========
>>> from sympy.polys.polyclasses import DMP
>>> from sympy.polys.domains import ZZ
>>> DMP([[[ZZ(1)]], [[ZZ(1)], [ZZ(2)]]], ZZ).exclude()
([2], DMP([[1], [1, 2]], ZZ, None))
"""
J, F, u = dmp_exclude(f.rep, f.lev, f.dom)
return J, f.__class__(F, f.dom, u)
def permute(f, P):
r"""
Returns a polynomial in `K[x_{P(1)}, ..., x_{P(n)}]`.
Examples
========
>>> from sympy.polys.polyclasses import DMP
>>> from sympy.polys.domains import ZZ
>>> DMP([[[ZZ(2)], [ZZ(1), ZZ(0)]], [[]]], ZZ).permute([1, 0, 2])
DMP([[[2], []], [[1, 0], []]], ZZ, None)
>>> DMP([[[ZZ(2)], [ZZ(1), ZZ(0)]], [[]]], ZZ).permute([1, 2, 0])
DMP([[[1], []], [[2, 0], []]], ZZ, None)
"""
return f.per(dmp_permute(f.rep, P, f.lev, f.dom))
def terms_gcd(f):
"""Remove GCD of terms from the polynomial ``f``. """
J, F = dmp_terms_gcd(f.rep, f.lev, f.dom)
return J, f.per(F)
def add_ground(f, c):
"""Add an element of the ground domain to ``f``. """
return f.per(dmp_add_ground(f.rep, f.dom.convert(c), f.lev, f.dom))
def sub_ground(f, c):
"""Subtract an element of the ground domain from ``f``. """
return f.per(dmp_sub_ground(f.rep, f.dom.convert(c), f.lev, f.dom))
def mul_ground(f, c):
"""Multiply ``f`` by a an element of the ground domain. """
return f.per(dmp_mul_ground(f.rep, f.dom.convert(c), f.lev, f.dom))
def quo_ground(f, c):
"""Quotient of ``f`` by a an element of the ground domain. """
return f.per(dmp_quo_ground(f.rep, f.dom.convert(c), f.lev, f.dom))
def exquo_ground(f, c):
"""Exact quotient of ``f`` by a an element of the ground domain. """
return f.per(dmp_exquo_ground(f.rep, f.dom.convert(c), f.lev, f.dom))
def abs(f):
"""Make all coefficients in ``f`` positive. """
return f.per(dmp_abs(f.rep, f.lev, f.dom))
def neg(f):
"""Negate all coefficients in ``f``. """
return f.per(dmp_neg(f.rep, f.lev, f.dom))
def add(f, g):
"""Add two multivariate polynomials ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
return per(dmp_add(F, G, lev, dom))
def sub(f, g):
"""Subtract two multivariate polynomials ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
return per(dmp_sub(F, G, lev, dom))
def mul(f, g):
"""Multiply two multivariate polynomials ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
return per(dmp_mul(F, G, lev, dom))
def sqr(f):
"""Square a multivariate polynomial ``f``. """
return f.per(dmp_sqr(f.rep, f.lev, f.dom))
def pow(f, n):
"""Raise ``f`` to a non-negative power ``n``. """
if isinstance(n, int):
return f.per(dmp_pow(f.rep, n, f.lev, f.dom))
else:
raise TypeError("``int`` expected, got %s" % type(n))
def pdiv(f, g):
"""Polynomial pseudo-division of ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
q, r = dmp_pdiv(F, G, lev, dom)
return per(q), per(r)
def prem(f, g):
"""Polynomial pseudo-remainder of ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
return per(dmp_prem(F, G, lev, dom))
def pquo(f, g):
"""Polynomial pseudo-quotient of ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
return per(dmp_pquo(F, G, lev, dom))
def pexquo(f, g):
"""Polynomial exact pseudo-quotient of ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
return per(dmp_pexquo(F, G, lev, dom))
def div(f, g):
"""Polynomial division with remainder of ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
q, r = dmp_div(F, G, lev, dom)
return per(q), per(r)
def rem(f, g):
"""Computes polynomial remainder of ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
return per(dmp_rem(F, G, lev, dom))
def quo(f, g):
"""Computes polynomial quotient of ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
return per(dmp_quo(F, G, lev, dom))
def exquo(f, g):
"""Computes polynomial exact quotient of ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
res = per(dmp_exquo(F, G, lev, dom))
if f.ring and res not in f.ring:
from sympy.polys.polyerrors import ExactQuotientFailed
raise ExactQuotientFailed(f, g, f.ring)
return res
def degree(f, j=0):
"""Returns the leading degree of ``f`` in ``x_j``. """
if isinstance(j, int):
return dmp_degree_in(f.rep, j, f.lev)
else:
raise TypeError("``int`` expected, got %s" % type(j))
def degree_list(f):
"""Returns a list of degrees of ``f``. """
return dmp_degree_list(f.rep, f.lev)
def total_degree(f):
"""Returns the total degree of ``f``. """
return max(sum(m) for m in f.monoms())
def homogenize(f, s):
"""Return homogeneous polynomial of ``f``"""
td = f.total_degree()
result = {}
new_symbol = (s == len(f.terms()[0][0]))
for term in f.terms():
d = sum(term[0])
if d < td:
i = td - d
else:
i = 0
if new_symbol:
result[term[0] + (i,)] = term[1]
else:
l = list(term[0])
l[s] += i
result[tuple(l)] = term[1]
return DMP(result, f.dom, f.lev + int(new_symbol), f.ring)
def homogeneous_order(f):
"""Returns the homogeneous order of ``f``. """
if f.is_zero:
return -oo
monoms = f.monoms()
tdeg = sum(monoms[0])
for monom in monoms:
_tdeg = sum(monom)
if _tdeg != tdeg:
return None
return tdeg
def LC(f):
"""Returns the leading coefficient of ``f``. """
return dmp_ground_LC(f.rep, f.lev, f.dom)
def TC(f):
"""Returns the trailing coefficient of ``f``. """
return dmp_ground_TC(f.rep, f.lev, f.dom)
def nth(f, *N):
"""Returns the ``n``-th coefficient of ``f``. """
if all(isinstance(n, int) for n in N):
return dmp_ground_nth(f.rep, N, f.lev, f.dom)
else:
raise TypeError("a sequence of integers expected")
def max_norm(f):
"""Returns maximum norm of ``f``. """
return dmp_max_norm(f.rep, f.lev, f.dom)
def l1_norm(f):
"""Returns l1 norm of ``f``. """
return dmp_l1_norm(f.rep, f.lev, f.dom)
def clear_denoms(f):
"""Clear denominators, but keep the ground domain. """
coeff, F = dmp_clear_denoms(f.rep, f.lev, f.dom)
return coeff, f.per(F)
def integrate(f, m=1, j=0):
"""Computes the ``m``-th order indefinite integral of ``f`` in ``x_j``. """
if not isinstance(m, int):
raise TypeError("``int`` expected, got %s" % type(m))
if not isinstance(j, int):
raise TypeError("``int`` expected, got %s" % type(j))
return f.per(dmp_integrate_in(f.rep, m, j, f.lev, f.dom))
def diff(f, m=1, j=0):
"""Computes the ``m``-th order derivative of ``f`` in ``x_j``. """
if not isinstance(m, int):
raise TypeError("``int`` expected, got %s" % type(m))
if not isinstance(j, int):
raise TypeError("``int`` expected, got %s" % type(j))
return f.per(dmp_diff_in(f.rep, m, j, f.lev, f.dom))
def eval(f, a, j=0):
"""Evaluates ``f`` at the given point ``a`` in ``x_j``. """
if not isinstance(j, int):
raise TypeError("``int`` expected, got %s" % type(j))
return f.per(dmp_eval_in(f.rep,
f.dom.convert(a), j, f.lev, f.dom), kill=True)
def half_gcdex(f, g):
"""Half extended Euclidean algorithm, if univariate. """
lev, dom, per, F, G = f.unify(g)
if not lev:
s, h = dup_half_gcdex(F, G, dom)
return per(s), per(h)
else:
raise ValueError('univariate polynomial expected')
def gcdex(f, g):
"""Extended Euclidean algorithm, if univariate. """
lev, dom, per, F, G = f.unify(g)
if not lev:
s, t, h = dup_gcdex(F, G, dom)
return per(s), per(t), per(h)
else:
raise ValueError('univariate polynomial expected')
def invert(f, g):
"""Invert ``f`` modulo ``g``, if possible. """
lev, dom, per, F, G = f.unify(g)
if not lev:
return per(dup_invert(F, G, dom))
else:
raise ValueError('univariate polynomial expected')
def revert(f, n):
"""Compute ``f**(-1)`` mod ``x**n``. """
if not f.lev:
return f.per(dup_revert(f.rep, n, f.dom))
else:
raise ValueError('univariate polynomial expected')
def subresultants(f, g):
"""Computes subresultant PRS sequence of ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
R = dmp_subresultants(F, G, lev, dom)
return list(map(per, R))
def resultant(f, g, includePRS=False):
"""Computes resultant of ``f`` and ``g`` via PRS. """
lev, dom, per, F, G = f.unify(g)
if includePRS:
res, R = dmp_resultant(F, G, lev, dom, includePRS=includePRS)
return per(res, kill=True), list(map(per, R))
return per(dmp_resultant(F, G, lev, dom), kill=True)
def discriminant(f):
"""Computes discriminant of ``f``. """
return f.per(dmp_discriminant(f.rep, f.lev, f.dom), kill=True)
def cofactors(f, g):
"""Returns GCD of ``f`` and ``g`` and their cofactors. """
lev, dom, per, F, G = f.unify(g)
h, cff, cfg = dmp_inner_gcd(F, G, lev, dom)
return per(h), per(cff), per(cfg)
def gcd(f, g):
"""Returns polynomial GCD of ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
return per(dmp_gcd(F, G, lev, dom))
def lcm(f, g):
"""Returns polynomial LCM of ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
return per(dmp_lcm(F, G, lev, dom))
def cancel(f, g, include=True):
"""Cancel common factors in a rational function ``f/g``. """
lev, dom, per, F, G = f.unify(g)
if include:
F, G = dmp_cancel(F, G, lev, dom, include=True)
else:
cF, cG, F, G = dmp_cancel(F, G, lev, dom, include=False)
F, G = per(F), per(G)
if include:
return F, G
else:
return cF, cG, F, G
def trunc(f, p):
"""Reduce ``f`` modulo a constant ``p``. """
return f.per(dmp_ground_trunc(f.rep, f.dom.convert(p), f.lev, f.dom))
def monic(f):
"""Divides all coefficients by ``LC(f)``. """
return f.per(dmp_ground_monic(f.rep, f.lev, f.dom))
def content(f):
"""Returns GCD of polynomial coefficients. """
return dmp_ground_content(f.rep, f.lev, f.dom)
def primitive(f):
"""Returns content and a primitive form of ``f``. """
cont, F = dmp_ground_primitive(f.rep, f.lev, f.dom)
return cont, f.per(F)
def compose(f, g):
"""Computes functional composition of ``f`` and ``g``. """
lev, dom, per, F, G = f.unify(g)
return per(dmp_compose(F, G, lev, dom))
def decompose(f):
"""Computes functional decomposition of ``f``. """
if not f.lev:
return list(map(f.per, dup_decompose(f.rep, f.dom)))
else:
raise ValueError('univariate polynomial expected')
def shift(f, a):
"""Efficiently compute Taylor shift ``f(x + a)``. """
if not f.lev:
return f.per(dup_shift(f.rep, f.dom.convert(a), f.dom))
else:
raise ValueError('univariate polynomial expected')
def transform(f, p, q):
"""Evaluate functional transformation ``q**n * f(p/q)``."""
if f.lev:
raise ValueError('univariate polynomial expected')
lev, dom, per, P, Q = p.unify(q)
lev, dom, per, F, P = f.unify(per(P, dom, lev))
lev, dom, per, F, Q = per(F, dom, lev).unify(per(Q, dom, lev))
if not lev:
return per(dup_transform(F, P, Q, dom))
else:
raise ValueError('univariate polynomial expected')
def sturm(f):
"""Computes the Sturm sequence of ``f``. """
if not f.lev:
return list(map(f.per, dup_sturm(f.rep, f.dom)))
else:
raise ValueError('univariate polynomial expected')
def gff_list(f):
"""Computes greatest factorial factorization of ``f``. """
if not f.lev:
return [ (f.per(g), k) for g, k in dup_gff_list(f.rep, f.dom) ]
else:
raise ValueError('univariate polynomial expected')
def norm(f):
"""Computes ``Norm(f)``."""
r = dmp_norm(f.rep, f.lev, f.dom)
return f.per(r, dom=f.dom.dom)
def sqf_norm(f):
"""Computes square-free norm of ``f``. """
s, g, r = dmp_sqf_norm(f.rep, f.lev, f.dom)
return s, f.per(g), f.per(r, dom=f.dom.dom)
def sqf_part(f):
"""Computes square-free part of ``f``. """
return f.per(dmp_sqf_part(f.rep, f.lev, f.dom))
def sqf_list(f, all=False):
"""Returns a list of square-free factors of ``f``. """
coeff, factors = dmp_sqf_list(f.rep, f.lev, f.dom, all)
return coeff, [ (f.per(g), k) for g, k in factors ]
def sqf_list_include(f, all=False):
"""Returns a list of square-free factors of ``f``. """
factors = dmp_sqf_list_include(f.rep, f.lev, f.dom, all)
return [ (f.per(g), k) for g, k in factors ]
def factor_list(f):
"""Returns a list of irreducible factors of ``f``. """
coeff, factors = dmp_factor_list(f.rep, f.lev, f.dom)
return coeff, [ (f.per(g), k) for g, k in factors ]
def factor_list_include(f):
"""Returns a list of irreducible factors of ``f``. """
factors = dmp_factor_list_include(f.rep, f.lev, f.dom)
return [ (f.per(g), k) for g, k in factors ]
def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False):
"""Compute isolating intervals for roots of ``f``. """
if not f.lev:
if not all:
if not sqf:
return dup_isolate_real_roots(f.rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
else:
return dup_isolate_real_roots_sqf(f.rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
else:
if not sqf:
return dup_isolate_all_roots(f.rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
else:
return dup_isolate_all_roots_sqf(f.rep, f.dom, eps=eps, inf=inf, sup=sup, fast=fast)
else:
raise PolynomialError(
"can't isolate roots of a multivariate polynomial")
def refine_root(f, s, t, eps=None, steps=None, fast=False):
"""
Refine an isolating interval to the given precision.
``eps`` should be a rational number.
"""
if not f.lev:
return dup_refine_real_root(f.rep, s, t, f.dom, eps=eps, steps=steps, fast=fast)
else:
raise PolynomialError(
"can't refine a root of a multivariate polynomial")
def count_real_roots(f, inf=None, sup=None):
"""Return the number of real roots of ``f`` in ``[inf, sup]``. """
return dup_count_real_roots(f.rep, f.dom, inf=inf, sup=sup)
def count_complex_roots(f, inf=None, sup=None):
"""Return the number of complex roots of ``f`` in ``[inf, sup]``. """
return dup_count_complex_roots(f.rep, f.dom, inf=inf, sup=sup)
@property
def is_zero(f):
"""Returns ``True`` if ``f`` is a zero polynomial. """
return dmp_zero_p(f.rep, f.lev)
@property
def is_one(f):
"""Returns ``True`` if ``f`` is a unit polynomial. """
return dmp_one_p(f.rep, f.lev, f.dom)
@property
def is_ground(f):
"""Returns ``True`` if ``f`` is an element of the ground domain. """
return dmp_ground_p(f.rep, None, f.lev)
@property
def is_sqf(f):
"""Returns ``True`` if ``f`` is a square-free polynomial. """
return dmp_sqf_p(f.rep, f.lev, f.dom)
@property
def is_monic(f):
"""Returns ``True`` if the leading coefficient of ``f`` is one. """
return f.dom.is_one(dmp_ground_LC(f.rep, f.lev, f.dom))
@property
def is_primitive(f):
"""Returns ``True`` if the GCD of the coefficients of ``f`` is one. """
return f.dom.is_one(dmp_ground_content(f.rep, f.lev, f.dom))
@property
def is_linear(f):
"""Returns ``True`` if ``f`` is linear in all its variables. """
return all(sum(monom) <= 1 for monom in dmp_to_dict(f.rep, f.lev, f.dom).keys())
@property
def is_quadratic(f):
"""Returns ``True`` if ``f`` is quadratic in all its variables. """
return all(sum(monom) <= 2 for monom in dmp_to_dict(f.rep, f.lev, f.dom).keys())
@property
def is_monomial(f):
"""Returns ``True`` if ``f`` is zero or has only one term. """
return len(f.to_dict()) <= 1
@property
def is_homogeneous(f):
"""Returns ``True`` if ``f`` is a homogeneous polynomial. """
return f.homogeneous_order() is not None
@property
def is_irreducible(f):
"""Returns ``True`` if ``f`` has no factors over its domain. """
return dmp_irreducible_p(f.rep, f.lev, f.dom)
@property
def is_cyclotomic(f):
"""Returns ``True`` if ``f`` is a cyclotomic polynomial. """
if not f.lev:
return dup_cyclotomic_p(f.rep, f.dom)
else:
return False
def __abs__(f):
return f.abs()
def __neg__(f):
return f.neg()
def __add__(f, g):
if not isinstance(g, DMP):
try:
g = f.per(dmp_ground(f.dom.convert(g), f.lev))
except TypeError:
return NotImplemented
except (CoercionFailed, NotImplementedError):
if f.ring is not None:
try:
g = f.ring.convert(g)
except (CoercionFailed, NotImplementedError):
return NotImplemented
return f.add(g)
def __radd__(f, g):
return f.__add__(g)
def __sub__(f, g):
if not isinstance(g, DMP):
try:
g = f.per(dmp_ground(f.dom.convert(g), f.lev))
except TypeError:
return NotImplemented
except (CoercionFailed, NotImplementedError):
if f.ring is not None:
try:
g = f.ring.convert(g)
except (CoercionFailed, NotImplementedError):
return NotImplemented
return f.sub(g)
def __rsub__(f, g):
return (-f).__add__(g)
def __mul__(f, g):
if isinstance(g, DMP):
return f.mul(g)
else:
try:
return f.mul_ground(g)
except TypeError:
return NotImplemented
except (CoercionFailed, NotImplementedError):
if f.ring is not None:
try:
return f.mul(f.ring.convert(g))
except (CoercionFailed, NotImplementedError):
pass
return NotImplemented
def __truediv__(f, g):
if isinstance(g, DMP):
return f.exquo(g)
else:
try:
return f.mul_ground(g)
except TypeError:
return NotImplemented
except (CoercionFailed, NotImplementedError):
if f.ring is not None:
try:
return f.exquo(f.ring.convert(g))
except (CoercionFailed, NotImplementedError):
pass
return NotImplemented
def __rtruediv__(f, g):
if isinstance(g, DMP):
return g.exquo(f)
elif f.ring is not None:
try:
return f.ring.convert(g).exquo(f)
except (CoercionFailed, NotImplementedError):
pass
return NotImplemented
def __rmul__(f, g):
return f.__mul__(g)
def __pow__(f, n):
return f.pow(n)
def __divmod__(f, g):
return f.div(g)
def __mod__(f, g):
return f.rem(g)
def __floordiv__(f, g):
if isinstance(g, DMP):
return f.quo(g)
else:
try:
return f.quo_ground(g)
except TypeError:
return NotImplemented
def __eq__(f, g):
try:
_, _, _, F, G = f.unify(g)
if f.lev == g.lev:
return F == G
except UnificationFailed:
pass
return False
def __ne__(f, g):
return not f == g
def eq(f, g, strict=False):
if not strict:
return f == g
else:
return f._strict_eq(g)
def ne(f, g, strict=False):
return not f.eq(g, strict=strict)
def _strict_eq(f, g):
return isinstance(g, f.__class__) and f.lev == g.lev \
and f.dom == g.dom \
and f.rep == g.rep
def __lt__(f, g):
_, _, _, F, G = f.unify(g)
return F < G
def __le__(f, g):
_, _, _, F, G = f.unify(g)
return F <= G
def __gt__(f, g):
_, _, _, F, G = f.unify(g)
return F > G
def __ge__(f, g):
_, _, _, F, G = f.unify(g)
return F >= G
def __bool__(f):
return not dmp_zero_p(f.rep, f.lev)
def init_normal_DMF(num, den, lev, dom):
return DMF(dmp_normal(num, lev, dom),
dmp_normal(den, lev, dom), dom, lev)
class DMF(PicklableWithSlots, CantSympify):
"""Dense Multivariate Fractions over `K`. """
__slots__ = ('num', 'den', 'lev', 'dom', 'ring')
def __init__(self, rep, dom, lev=None, ring=None):
num, den, lev = self._parse(rep, dom, lev)
num, den = dmp_cancel(num, den, lev, dom)
self.num = num
self.den = den
self.lev = lev
self.dom = dom
self.ring = ring
@classmethod
def new(cls, rep, dom, lev=None, ring=None):
num, den, lev = cls._parse(rep, dom, lev)
obj = object.__new__(cls)
obj.num = num
obj.den = den
obj.lev = lev
obj.dom = dom
obj.ring = ring
return obj
@classmethod
def _parse(cls, rep, dom, lev=None):
if type(rep) is tuple:
num, den = rep
if lev is not None:
if type(num) is dict:
num = dmp_from_dict(num, lev, dom)
if type(den) is dict:
den = dmp_from_dict(den, lev, dom)
else:
num, num_lev = dmp_validate(num)
den, den_lev = dmp_validate(den)
if num_lev == den_lev:
lev = num_lev
else:
raise ValueError('inconsistent number of levels')
if dmp_zero_p(den, lev):
raise ZeroDivisionError('fraction denominator')
if dmp_zero_p(num, lev):
den = dmp_one(lev, dom)
else:
if dmp_negative_p(den, lev, dom):
num = dmp_neg(num, lev, dom)
den = dmp_neg(den, lev, dom)
else:
num = rep
if lev is not None:
if type(num) is dict:
num = dmp_from_dict(num, lev, dom)
elif type(num) is not list:
num = dmp_ground(dom.convert(num), lev)
else:
num, lev = dmp_validate(num)
den = dmp_one(lev, dom)
return num, den, lev
def __repr__(f):
return "%s((%s, %s), %s, %s)" % (f.__class__.__name__, f.num, f.den,
f.dom, f.ring)
def __hash__(f):
return hash((f.__class__.__name__, dmp_to_tuple(f.num, f.lev),
dmp_to_tuple(f.den, f.lev), f.lev, f.dom, f.ring))
def poly_unify(f, g):
"""Unify a multivariate fraction and a polynomial. """
if not isinstance(g, DMP) or f.lev != g.lev:
raise UnificationFailed("can't unify %s with %s" % (f, g))
if f.dom == g.dom and f.ring == g.ring:
return (f.lev, f.dom, f.per, (f.num, f.den), g.rep)
else:
lev, dom = f.lev, f.dom.unify(g.dom)
ring = f.ring
if g.ring is not None:
if ring is not None:
ring = ring.unify(g.ring)
else:
ring = g.ring
F = (dmp_convert(f.num, lev, f.dom, dom),
dmp_convert(f.den, lev, f.dom, dom))
G = dmp_convert(g.rep, lev, g.dom, dom)
def per(num, den, cancel=True, kill=False, lev=lev):
if kill:
if not lev:
return num/den
else:
lev = lev - 1
if cancel:
num, den = dmp_cancel(num, den, lev, dom)
return f.__class__.new((num, den), dom, lev, ring=ring)
return lev, dom, per, F, G
def frac_unify(f, g):
"""Unify representations of two multivariate fractions. """
if not isinstance(g, DMF) or f.lev != g.lev:
raise UnificationFailed("can't unify %s with %s" % (f, g))
if f.dom == g.dom and f.ring == g.ring:
return (f.lev, f.dom, f.per, (f.num, f.den),
(g.num, g.den))
else:
lev, dom = f.lev, f.dom.unify(g.dom)
ring = f.ring
if g.ring is not None:
if ring is not None:
ring = ring.unify(g.ring)
else:
ring = g.ring
F = (dmp_convert(f.num, lev, f.dom, dom),
dmp_convert(f.den, lev, f.dom, dom))
G = (dmp_convert(g.num, lev, g.dom, dom),
dmp_convert(g.den, lev, g.dom, dom))
def per(num, den, cancel=True, kill=False, lev=lev):
if kill:
if not lev:
return num/den
else:
lev = lev - 1
if cancel:
num, den = dmp_cancel(num, den, lev, dom)
return f.__class__.new((num, den), dom, lev, ring=ring)
return lev, dom, per, F, G
def per(f, num, den, cancel=True, kill=False, ring=None):
"""Create a DMF out of the given representation. """
lev, dom = f.lev, f.dom
if kill:
if not lev:
return num/den
else:
lev -= 1
if cancel:
num, den = dmp_cancel(num, den, lev, dom)
if ring is None:
ring = f.ring
return f.__class__.new((num, den), dom, lev, ring=ring)
def half_per(f, rep, kill=False):
"""Create a DMP out of the given representation. """
lev = f.lev
if kill:
if not lev:
return rep
else:
lev -= 1
return DMP(rep, f.dom, lev)
@classmethod
def zero(cls, lev, dom, ring=None):
return cls.new(0, dom, lev, ring=ring)
@classmethod
def one(cls, lev, dom, ring=None):
return cls.new(1, dom, lev, ring=ring)
def numer(f):
"""Returns the numerator of ``f``. """
return f.half_per(f.num)
def denom(f):
"""Returns the denominator of ``f``. """
return f.half_per(f.den)
def cancel(f):
"""Remove common factors from ``f.num`` and ``f.den``. """
return f.per(f.num, f.den)
def neg(f):
"""Negate all coefficients in ``f``. """
return f.per(dmp_neg(f.num, f.lev, f.dom), f.den, cancel=False)
def add(f, g):
"""Add two multivariate fractions ``f`` and ``g``. """
if isinstance(g, DMP):
lev, dom, per, (F_num, F_den), G = f.poly_unify(g)
num, den = dmp_add_mul(F_num, F_den, G, lev, dom), F_den
else:
lev, dom, per, F, G = f.frac_unify(g)
(F_num, F_den), (G_num, G_den) = F, G
num = dmp_add(dmp_mul(F_num, G_den, lev, dom),
dmp_mul(F_den, G_num, lev, dom), lev, dom)
den = dmp_mul(F_den, G_den, lev, dom)
return per(num, den)
def sub(f, g):
"""Subtract two multivariate fractions ``f`` and ``g``. """
if isinstance(g, DMP):
lev, dom, per, (F_num, F_den), G = f.poly_unify(g)
num, den = dmp_sub_mul(F_num, F_den, G, lev, dom), F_den
else:
lev, dom, per, F, G = f.frac_unify(g)
(F_num, F_den), (G_num, G_den) = F, G
num = dmp_sub(dmp_mul(F_num, G_den, lev, dom),
dmp_mul(F_den, G_num, lev, dom), lev, dom)
den = dmp_mul(F_den, G_den, lev, dom)
return per(num, den)
def mul(f, g):
"""Multiply two multivariate fractions ``f`` and ``g``. """
if isinstance(g, DMP):
lev, dom, per, (F_num, F_den), G = f.poly_unify(g)
num, den = dmp_mul(F_num, G, lev, dom), F_den
else:
lev, dom, per, F, G = f.frac_unify(g)
(F_num, F_den), (G_num, G_den) = F, G
num = dmp_mul(F_num, G_num, lev, dom)
den = dmp_mul(F_den, G_den, lev, dom)
return per(num, den)
def pow(f, n):
"""Raise ``f`` to a non-negative power ``n``. """
if isinstance(n, int):
num, den = f.num, f.den
if n < 0:
num, den, n = den, num, -n
return f.per(dmp_pow(num, n, f.lev, f.dom),
dmp_pow(den, n, f.lev, f.dom), cancel=False)
else:
raise TypeError("``int`` expected, got %s" % type(n))
def quo(f, g):
"""Computes quotient of fractions ``f`` and ``g``. """
if isinstance(g, DMP):
lev, dom, per, (F_num, F_den), G = f.poly_unify(g)
num, den = F_num, dmp_mul(F_den, G, lev, dom)
else:
lev, dom, per, F, G = f.frac_unify(g)
(F_num, F_den), (G_num, G_den) = F, G
num = dmp_mul(F_num, G_den, lev, dom)
den = dmp_mul(F_den, G_num, lev, dom)
res = per(num, den)
if f.ring is not None and res not in f.ring:
from sympy.polys.polyerrors import ExactQuotientFailed
raise ExactQuotientFailed(f, g, f.ring)
return res
exquo = quo
def invert(f, check=True):
"""Computes inverse of a fraction ``f``. """
if check and f.ring is not None and not f.ring.is_unit(f):
raise NotReversible(f, f.ring)
res = f.per(f.den, f.num, cancel=False)
return res
@property
def is_zero(f):
"""Returns ``True`` if ``f`` is a zero fraction. """
return dmp_zero_p(f.num, f.lev)
@property
def is_one(f):
"""Returns ``True`` if ``f`` is a unit fraction. """
return dmp_one_p(f.num, f.lev, f.dom) and \
dmp_one_p(f.den, f.lev, f.dom)
def __neg__(f):
return f.neg()
def __add__(f, g):
if isinstance(g, (DMP, DMF)):
return f.add(g)
try:
return f.add(f.half_per(g))
except TypeError:
return NotImplemented
except (CoercionFailed, NotImplementedError):
if f.ring is not None:
try:
return f.add(f.ring.convert(g))
except (CoercionFailed, NotImplementedError):
pass
return NotImplemented
def __radd__(f, g):
return f.__add__(g)
def __sub__(f, g):
if isinstance(g, (DMP, DMF)):
return f.sub(g)
try:
return f.sub(f.half_per(g))
except TypeError:
return NotImplemented
except (CoercionFailed, NotImplementedError):
if f.ring is not None:
try:
return f.sub(f.ring.convert(g))
except (CoercionFailed, NotImplementedError):
pass
return NotImplemented
def __rsub__(f, g):
return (-f).__add__(g)
def __mul__(f, g):
if isinstance(g, (DMP, DMF)):
return f.mul(g)
try:
return f.mul(f.half_per(g))
except TypeError:
return NotImplemented
except (CoercionFailed, NotImplementedError):
if f.ring is not None:
try:
return f.mul(f.ring.convert(g))
except (CoercionFailed, NotImplementedError):
pass
return NotImplemented
def __rmul__(f, g):
return f.__mul__(g)
def __pow__(f, n):
return f.pow(n)
def __truediv__(f, g):
if isinstance(g, (DMP, DMF)):
return f.quo(g)
try:
return f.quo(f.half_per(g))
except TypeError:
return NotImplemented
except (CoercionFailed, NotImplementedError):
if f.ring is not None:
try:
return f.quo(f.ring.convert(g))
except (CoercionFailed, NotImplementedError):
pass
return NotImplemented
def __rtruediv__(self, g):
r = self.invert(check=False)*g
if self.ring and r not in self.ring:
from sympy.polys.polyerrors import ExactQuotientFailed
raise ExactQuotientFailed(g, self, self.ring)
return r
def __eq__(f, g):
try:
if isinstance(g, DMP):
_, _, _, (F_num, F_den), G = f.poly_unify(g)
if f.lev == g.lev:
return dmp_one_p(F_den, f.lev, f.dom) and F_num == G
else:
_, _, _, F, G = f.frac_unify(g)
if f.lev == g.lev:
return F == G
except UnificationFailed:
pass
return False
def __ne__(f, g):
try:
if isinstance(g, DMP):
_, _, _, (F_num, F_den), G = f.poly_unify(g)
if f.lev == g.lev:
return not (dmp_one_p(F_den, f.lev, f.dom) and F_num == G)
else:
_, _, _, F, G = f.frac_unify(g)
if f.lev == g.lev:
return F != G
except UnificationFailed:
pass
return True
def __lt__(f, g):
_, _, _, F, G = f.frac_unify(g)
return F < G
def __le__(f, g):
_, _, _, F, G = f.frac_unify(g)
return F <= G
def __gt__(f, g):
_, _, _, F, G = f.frac_unify(g)
return F > G
def __ge__(f, g):
_, _, _, F, G = f.frac_unify(g)
return F >= G
def __bool__(f):
return not dmp_zero_p(f.num, f.lev)
def init_normal_ANP(rep, mod, dom):
return ANP(dup_normal(rep, dom),
dup_normal(mod, dom), dom)
class ANP(PicklableWithSlots, CantSympify):
"""Dense Algebraic Number Polynomials over a field. """
__slots__ = ('rep', 'mod', 'dom')
def __init__(self, rep, mod, dom):
if type(rep) is dict:
self.rep = dup_from_dict(rep, dom)
else:
if type(rep) is not list:
rep = [dom.convert(rep)]
self.rep = dup_strip(rep)
if isinstance(mod, DMP):
self.mod = mod.rep
else:
if type(mod) is dict:
self.mod = dup_from_dict(mod, dom)
else:
self.mod = dup_strip(mod)
self.dom = dom
def __repr__(f):
return "%s(%s, %s, %s)" % (f.__class__.__name__, f.rep, f.mod, f.dom)
def __hash__(f):
return hash((f.__class__.__name__, f.to_tuple(), dmp_to_tuple(f.mod, 0), f.dom))
def unify(f, g):
"""Unify representations of two algebraic numbers. """
if not isinstance(g, ANP) or f.mod != g.mod:
raise UnificationFailed("can't unify %s with %s" % (f, g))
if f.dom == g.dom:
return f.dom, f.per, f.rep, g.rep, f.mod
else:
dom = f.dom.unify(g.dom)
F = dup_convert(f.rep, f.dom, dom)
G = dup_convert(g.rep, g.dom, dom)
if dom != f.dom and dom != g.dom:
mod = dup_convert(f.mod, f.dom, dom)
else:
if dom == f.dom:
mod = f.mod
else:
mod = g.mod
per = lambda rep: ANP(rep, mod, dom)
return dom, per, F, G, mod
def per(f, rep, mod=None, dom=None):
return ANP(rep, mod or f.mod, dom or f.dom)
@classmethod
def zero(cls, mod, dom):
return ANP(0, mod, dom)
@classmethod
def one(cls, mod, dom):
return ANP(1, mod, dom)
def to_dict(f):
"""Convert ``f`` to a dict representation with native coefficients. """
return dmp_to_dict(f.rep, 0, f.dom)
def to_sympy_dict(f):
"""Convert ``f`` to a dict representation with SymPy coefficients. """
rep = dmp_to_dict(f.rep, 0, f.dom)
for k, v in rep.items():
rep[k] = f.dom.to_sympy(v)
return rep
def to_list(f):
"""Convert ``f`` to a list representation with native coefficients. """
return f.rep
def to_sympy_list(f):
"""Convert ``f`` to a list representation with SymPy coefficients. """
return [ f.dom.to_sympy(c) for c in f.rep ]
def to_tuple(f):
"""
Convert ``f`` to a tuple representation with native coefficients.
This is needed for hashing.
"""
return dmp_to_tuple(f.rep, 0)
@classmethod
def from_list(cls, rep, mod, dom):
return ANP(dup_strip(list(map(dom.convert, rep))), mod, dom)
def neg(f):
return f.per(dup_neg(f.rep, f.dom))
def add(f, g):
dom, per, F, G, mod = f.unify(g)
return per(dup_add(F, G, dom))
def sub(f, g):
dom, per, F, G, mod = f.unify(g)
return per(dup_sub(F, G, dom))
def mul(f, g):
dom, per, F, G, mod = f.unify(g)
return per(dup_rem(dup_mul(F, G, dom), mod, dom))
def pow(f, n):
"""Raise ``f`` to a non-negative power ``n``. """
if isinstance(n, int):
if n < 0:
F, n = dup_invert(f.rep, f.mod, f.dom), -n
else:
F = f.rep
return f.per(dup_rem(dup_pow(F, n, f.dom), f.mod, f.dom))
else:
raise TypeError("``int`` expected, got %s" % type(n))
def div(f, g):
dom, per, F, G, mod = f.unify(g)
return (per(dup_rem(dup_mul(F, dup_invert(G, mod, dom), dom), mod, dom)), f.zero(mod, dom))
def rem(f, g):
dom, _, _, G, mod = f.unify(g)
s, h = dup_half_gcdex(G, mod, dom)
if h == [dom.one]:
return f.zero(mod, dom)
else:
raise NotInvertible("zero divisor")
def quo(f, g):
dom, per, F, G, mod = f.unify(g)
return per(dup_rem(dup_mul(F, dup_invert(G, mod, dom), dom), mod, dom))
exquo = quo
def LC(f):
"""Returns the leading coefficient of ``f``. """
return dup_LC(f.rep, f.dom)
def TC(f):
"""Returns the trailing coefficient of ``f``. """
return dup_TC(f.rep, f.dom)
@property
def is_zero(f):
"""Returns ``True`` if ``f`` is a zero algebraic number. """
return not f
@property
def is_one(f):
"""Returns ``True`` if ``f`` is a unit algebraic number. """
return f.rep == [f.dom.one]
@property
def is_ground(f):
"""Returns ``True`` if ``f`` is an element of the ground domain. """
return not f.rep or len(f.rep) == 1
def __pos__(f):
return f
def __neg__(f):
return f.neg()
def __add__(f, g):
if isinstance(g, ANP):
return f.add(g)
else:
try:
return f.add(f.per(g))
except (CoercionFailed, TypeError):
return NotImplemented
def __radd__(f, g):
return f.__add__(g)
def __sub__(f, g):
if isinstance(g, ANP):
return f.sub(g)
else:
try:
return f.sub(f.per(g))
except (CoercionFailed, TypeError):
return NotImplemented
def __rsub__(f, g):
return (-f).__add__(g)
def __mul__(f, g):
if isinstance(g, ANP):
return f.mul(g)
else:
try:
return f.mul(f.per(g))
except (CoercionFailed, TypeError):
return NotImplemented
def __rmul__(f, g):
return f.__mul__(g)
def __pow__(f, n):
return f.pow(n)
def __divmod__(f, g):
return f.div(g)
def __mod__(f, g):
return f.rem(g)
def __truediv__(f, g):
if isinstance(g, ANP):
return f.quo(g)
else:
try:
return f.quo(f.per(g))
except (CoercionFailed, TypeError):
return NotImplemented
def __eq__(f, g):
try:
_, _, F, G, _ = f.unify(g)
return F == G
except UnificationFailed:
return False
def __ne__(f, g):
try:
_, _, F, G, _ = f.unify(g)
return F != G
except UnificationFailed:
return True
def __lt__(f, g):
_, _, F, G, _ = f.unify(g)
return F < G
def __le__(f, g):
_, _, F, G, _ = f.unify(g)
return F <= G
def __gt__(f, g):
_, _, F, G, _ = f.unify(g)
return F > G
def __ge__(f, g):
_, _, F, G, _ = f.unify(g)
return F >= G
def __bool__(f):
return bool(f.rep)
|
b215036d6ac3bbffcd352eecd8b846125c8c5aad4e2e7655393943aca65f15b3 | """Sparse polynomial rings. """
from typing import Any, Dict
from operator import add, mul, lt, le, gt, ge
from functools import reduce
from types import GeneratorType
from sympy.core.compatibility import is_sequence
from sympy.core.expr import Expr
from sympy.core.numbers import igcd, oo
from sympy.core.symbol import Symbol, symbols as _symbols
from sympy.core.sympify import CantSympify, sympify
from sympy.ntheory.multinomial import multinomial_coefficients
from sympy.polys.compatibility import IPolys
from sympy.polys.constructor import construct_domain
from sympy.polys.densebasic import dmp_to_dict, dmp_from_dict
from sympy.polys.domains.domainelement import DomainElement
from sympy.polys.domains.polynomialring import PolynomialRing
from sympy.polys.heuristicgcd import heugcd
from sympy.polys.monomials import MonomialOps
from sympy.polys.orderings import lex
from sympy.polys.polyerrors import (
CoercionFailed, GeneratorsError,
ExactQuotientFailed, MultivariatePolynomialError)
from sympy.polys.polyoptions import (Domain as DomainOpt,
Order as OrderOpt, build_options)
from sympy.polys.polyutils import (expr_from_dict, _dict_reorder,
_parallel_dict_from_expr)
from sympy.printing.defaults import DefaultPrinting
from sympy.utilities import public
from sympy.utilities.magic import pollute
@public
def ring(symbols, domain, order=lex):
"""Construct a polynomial ring returning ``(ring, x_1, ..., x_n)``.
Parameters
==========
symbols : str
Symbol/Expr or sequence of str, Symbol/Expr (non-empty)
domain : :class:`~.Domain` or coercible
order : :class:`~.MonomialOrder` or coercible, optional, defaults to ``lex``
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.orderings import lex
>>> R, x, y, z = ring("x,y,z", ZZ, lex)
>>> R
Polynomial ring in x, y, z over ZZ with lex order
>>> x + y + z
x + y + z
>>> type(_)
<class 'sympy.polys.rings.PolyElement'>
"""
_ring = PolyRing(symbols, domain, order)
return (_ring,) + _ring.gens
@public
def xring(symbols, domain, order=lex):
"""Construct a polynomial ring returning ``(ring, (x_1, ..., x_n))``.
Parameters
==========
symbols : str
Symbol/Expr or sequence of str, Symbol/Expr (non-empty)
domain : :class:`~.Domain` or coercible
order : :class:`~.MonomialOrder` or coercible, optional, defaults to ``lex``
Examples
========
>>> from sympy.polys.rings import xring
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.orderings import lex
>>> R, (x, y, z) = xring("x,y,z", ZZ, lex)
>>> R
Polynomial ring in x, y, z over ZZ with lex order
>>> x + y + z
x + y + z
>>> type(_)
<class 'sympy.polys.rings.PolyElement'>
"""
_ring = PolyRing(symbols, domain, order)
return (_ring, _ring.gens)
@public
def vring(symbols, domain, order=lex):
"""Construct a polynomial ring and inject ``x_1, ..., x_n`` into the global namespace.
Parameters
==========
symbols : str
Symbol/Expr or sequence of str, Symbol/Expr (non-empty)
domain : :class:`~.Domain` or coercible
order : :class:`~.MonomialOrder` or coercible, optional, defaults to ``lex``
Examples
========
>>> from sympy.polys.rings import vring
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.orderings import lex
>>> vring("x,y,z", ZZ, lex)
Polynomial ring in x, y, z over ZZ with lex order
>>> x + y + z # noqa:
x + y + z
>>> type(_)
<class 'sympy.polys.rings.PolyElement'>
"""
_ring = PolyRing(symbols, domain, order)
pollute([ sym.name for sym in _ring.symbols ], _ring.gens)
return _ring
@public
def sring(exprs, *symbols, **options):
"""Construct a ring deriving generators and domain from options and input expressions.
Parameters
==========
exprs : :class:`~.Expr` or sequence of :class:`~.Expr` (sympifiable)
symbols : sequence of :class:`~.Symbol`/:class:`~.Expr`
options : keyword arguments understood by :class:`~.Options`
Examples
========
>>> from sympy.core import symbols
>>> from sympy.polys.rings import sring
>>> x, y, z = symbols("x,y,z")
>>> R, f = sring(x + 2*y + 3*z)
>>> R
Polynomial ring in x, y, z over ZZ with lex order
>>> f
x + 2*y + 3*z
>>> type(_)
<class 'sympy.polys.rings.PolyElement'>
"""
single = False
if not is_sequence(exprs):
exprs, single = [exprs], True
exprs = list(map(sympify, exprs))
opt = build_options(symbols, options)
# TODO: rewrite this so that it doesn't use expand() (see poly()).
reps, opt = _parallel_dict_from_expr(exprs, opt)
if opt.domain is None:
coeffs = sum([ list(rep.values()) for rep in reps ], [])
opt.domain, coeffs_dom = construct_domain(coeffs, opt=opt)
coeff_map = dict(zip(coeffs, coeffs_dom))
reps = [{m: coeff_map[c] for m, c in rep.items()} for rep in reps]
_ring = PolyRing(opt.gens, opt.domain, opt.order)
polys = list(map(_ring.from_dict, reps))
if single:
return (_ring, polys[0])
else:
return (_ring, polys)
def _parse_symbols(symbols):
if isinstance(symbols, str):
return _symbols(symbols, seq=True) if symbols else ()
elif isinstance(symbols, Expr):
return (symbols,)
elif is_sequence(symbols):
if all(isinstance(s, str) for s in symbols):
return _symbols(symbols)
elif all(isinstance(s, Expr) for s in symbols):
return symbols
raise GeneratorsError("expected a string, Symbol or expression or a non-empty sequence of strings, Symbols or expressions")
_ring_cache = {} # type: Dict[Any, Any]
class PolyRing(DefaultPrinting, IPolys):
"""Multivariate distributed polynomial ring. """
def __new__(cls, symbols, domain, order=lex):
symbols = tuple(_parse_symbols(symbols))
ngens = len(symbols)
domain = DomainOpt.preprocess(domain)
order = OrderOpt.preprocess(order)
_hash_tuple = (cls.__name__, symbols, ngens, domain, order)
obj = _ring_cache.get(_hash_tuple)
if obj is None:
if domain.is_Composite and set(symbols) & set(domain.symbols):
raise GeneratorsError("polynomial ring and it's ground domain share generators")
obj = object.__new__(cls)
obj._hash_tuple = _hash_tuple
obj._hash = hash(_hash_tuple)
obj.dtype = type("PolyElement", (PolyElement,), {"ring": obj})
obj.symbols = symbols
obj.ngens = ngens
obj.domain = domain
obj.order = order
obj.zero_monom = (0,)*ngens
obj.gens = obj._gens()
obj._gens_set = set(obj.gens)
obj._one = [(obj.zero_monom, domain.one)]
if ngens:
# These expect monomials in at least one variable
codegen = MonomialOps(ngens)
obj.monomial_mul = codegen.mul()
obj.monomial_pow = codegen.pow()
obj.monomial_mulpow = codegen.mulpow()
obj.monomial_ldiv = codegen.ldiv()
obj.monomial_div = codegen.div()
obj.monomial_lcm = codegen.lcm()
obj.monomial_gcd = codegen.gcd()
else:
monunit = lambda a, b: ()
obj.monomial_mul = monunit
obj.monomial_pow = monunit
obj.monomial_mulpow = lambda a, b, c: ()
obj.monomial_ldiv = monunit
obj.monomial_div = monunit
obj.monomial_lcm = monunit
obj.monomial_gcd = monunit
if order is lex:
obj.leading_expv = lambda f: max(f)
else:
obj.leading_expv = lambda f: max(f, key=order)
for symbol, generator in zip(obj.symbols, obj.gens):
if isinstance(symbol, Symbol):
name = symbol.name
if not hasattr(obj, name):
setattr(obj, name, generator)
_ring_cache[_hash_tuple] = obj
return obj
def _gens(self):
"""Return a list of polynomial generators. """
one = self.domain.one
_gens = []
for i in range(self.ngens):
expv = self.monomial_basis(i)
poly = self.zero
poly[expv] = one
_gens.append(poly)
return tuple(_gens)
def __getnewargs__(self):
return (self.symbols, self.domain, self.order)
def __getstate__(self):
state = self.__dict__.copy()
del state["leading_expv"]
for key, value in state.items():
if key.startswith("monomial_"):
del state[key]
return state
def __hash__(self):
return self._hash
def __eq__(self, other):
return isinstance(other, PolyRing) and \
(self.symbols, self.domain, self.ngens, self.order) == \
(other.symbols, other.domain, other.ngens, other.order)
def __ne__(self, other):
return not self == other
def clone(self, symbols=None, domain=None, order=None):
return self.__class__(symbols or self.symbols, domain or self.domain, order or self.order)
def monomial_basis(self, i):
"""Return the ith-basis element. """
basis = [0]*self.ngens
basis[i] = 1
return tuple(basis)
@property
def zero(self):
return self.dtype()
@property
def one(self):
return self.dtype(self._one)
def domain_new(self, element, orig_domain=None):
return self.domain.convert(element, orig_domain)
def ground_new(self, coeff):
return self.term_new(self.zero_monom, coeff)
def term_new(self, monom, coeff):
coeff = self.domain_new(coeff)
poly = self.zero
if coeff:
poly[monom] = coeff
return poly
def ring_new(self, element):
if isinstance(element, PolyElement):
if self == element.ring:
return element
elif isinstance(self.domain, PolynomialRing) and self.domain.ring == element.ring:
return self.ground_new(element)
else:
raise NotImplementedError("conversion")
elif isinstance(element, str):
raise NotImplementedError("parsing")
elif isinstance(element, dict):
return self.from_dict(element)
elif isinstance(element, list):
try:
return self.from_terms(element)
except ValueError:
return self.from_list(element)
elif isinstance(element, Expr):
return self.from_expr(element)
else:
return self.ground_new(element)
__call__ = ring_new
def from_dict(self, element, orig_domain=None):
domain_new = self.domain_new
poly = self.zero
for monom, coeff in element.items():
coeff = domain_new(coeff, orig_domain)
if coeff:
poly[monom] = coeff
return poly
def from_terms(self, element, orig_domain=None):
return self.from_dict(dict(element), orig_domain)
def from_list(self, element):
return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain))
def _rebuild_expr(self, expr, mapping):
domain = self.domain
def _rebuild(expr):
generator = mapping.get(expr)
if generator is not None:
return generator
elif expr.is_Add:
return reduce(add, list(map(_rebuild, expr.args)))
elif expr.is_Mul:
return reduce(mul, list(map(_rebuild, expr.args)))
elif expr.is_Pow and expr.exp.is_Integer and expr.exp >= 0:
return _rebuild(expr.base)**int(expr.exp)
else:
return self.ground_new(domain.convert(expr))
return _rebuild(sympify(expr))
def from_expr(self, expr):
mapping = dict(list(zip(self.symbols, self.gens)))
try:
poly = self._rebuild_expr(expr, mapping)
except CoercionFailed:
raise ValueError("expected an expression convertible to a polynomial in %s, got %s" % (self, expr))
else:
return self.ring_new(poly)
def index(self, gen):
"""Compute index of ``gen`` in ``self.gens``. """
if gen is None:
if self.ngens:
i = 0
else:
i = -1 # indicate impossible choice
elif isinstance(gen, int):
i = gen
if 0 <= i and i < self.ngens:
pass
elif -self.ngens <= i and i <= -1:
i = -i - 1
else:
raise ValueError("invalid generator index: %s" % gen)
elif isinstance(gen, self.dtype):
try:
i = self.gens.index(gen)
except ValueError:
raise ValueError("invalid generator: %s" % gen)
elif isinstance(gen, str):
try:
i = self.symbols.index(gen)
except ValueError:
raise ValueError("invalid generator: %s" % gen)
else:
raise ValueError("expected a polynomial generator, an integer, a string or None, got %s" % gen)
return i
def drop(self, *gens):
"""Remove specified generators from this ring. """
indices = set(map(self.index, gens))
symbols = [ s for i, s in enumerate(self.symbols) if i not in indices ]
if not symbols:
return self.domain
else:
return self.clone(symbols=symbols)
def __getitem__(self, key):
symbols = self.symbols[key]
if not symbols:
return self.domain
else:
return self.clone(symbols=symbols)
def to_ground(self):
# TODO: should AlgebraicField be a Composite domain?
if self.domain.is_Composite or hasattr(self.domain, 'domain'):
return self.clone(domain=self.domain.domain)
else:
raise ValueError("%s is not a composite domain" % self.domain)
def to_domain(self):
return PolynomialRing(self)
def to_field(self):
from sympy.polys.fields import FracField
return FracField(self.symbols, self.domain, self.order)
@property
def is_univariate(self):
return len(self.gens) == 1
@property
def is_multivariate(self):
return len(self.gens) > 1
def add(self, *objs):
"""
Add a sequence of polynomials or containers of polynomials.
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> R, x = ring("x", ZZ)
>>> R.add([ x**2 + 2*i + 3 for i in range(4) ])
4*x**2 + 24
>>> _.factor_list()
(4, [(x**2 + 6, 1)])
"""
p = self.zero
for obj in objs:
if is_sequence(obj, include=GeneratorType):
p += self.add(*obj)
else:
p += obj
return p
def mul(self, *objs):
"""
Multiply a sequence of polynomials or containers of polynomials.
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> R, x = ring("x", ZZ)
>>> R.mul([ x**2 + 2*i + 3 for i in range(4) ])
x**8 + 24*x**6 + 206*x**4 + 744*x**2 + 945
>>> _.factor_list()
(1, [(x**2 + 3, 1), (x**2 + 5, 1), (x**2 + 7, 1), (x**2 + 9, 1)])
"""
p = self.one
for obj in objs:
if is_sequence(obj, include=GeneratorType):
p *= self.mul(*obj)
else:
p *= obj
return p
def drop_to_ground(self, *gens):
r"""
Remove specified generators from the ring and inject them into
its domain.
"""
indices = set(map(self.index, gens))
symbols = [s for i, s in enumerate(self.symbols) if i not in indices]
gens = [gen for i, gen in enumerate(self.gens) if i not in indices]
if not symbols:
return self
else:
return self.clone(symbols=symbols, domain=self.drop(*gens))
def compose(self, other):
"""Add the generators of ``other`` to ``self``"""
if self != other:
syms = set(self.symbols).union(set(other.symbols))
return self.clone(symbols=list(syms))
else:
return self
def add_gens(self, symbols):
"""Add the elements of ``symbols`` as generators to ``self``"""
syms = set(self.symbols).union(set(symbols))
return self.clone(symbols=list(syms))
class PolyElement(DomainElement, DefaultPrinting, CantSympify, dict):
"""Element of multivariate distributed polynomial ring. """
def new(self, init):
return self.__class__(init)
def parent(self):
return self.ring.to_domain()
def __getnewargs__(self):
return (self.ring, list(self.iterterms()))
_hash = None
def __hash__(self):
# XXX: This computes a hash of a dictionary, but currently we don't
# protect dictionary from being changed so any use site modifications
# will make hashing go wrong. Use this feature with caution until we
# figure out how to make a safe API without compromising speed of this
# low-level class.
_hash = self._hash
if _hash is None:
self._hash = _hash = hash((self.ring, frozenset(self.items())))
return _hash
def copy(self):
"""Return a copy of polynomial self.
Polynomials are mutable; if one is interested in preserving
a polynomial, and one plans to use inplace operations, one
can copy the polynomial. This method makes a shallow copy.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.rings import ring
>>> R, x, y = ring('x, y', ZZ)
>>> p = (x + y)**2
>>> p1 = p.copy()
>>> p2 = p
>>> p[R.zero_monom] = 3
>>> p
x**2 + 2*x*y + y**2 + 3
>>> p1
x**2 + 2*x*y + y**2
>>> p2
x**2 + 2*x*y + y**2 + 3
"""
return self.new(self)
def set_ring(self, new_ring):
if self.ring == new_ring:
return self
elif self.ring.symbols != new_ring.symbols:
terms = list(zip(*_dict_reorder(self, self.ring.symbols, new_ring.symbols)))
return new_ring.from_terms(terms, self.ring.domain)
else:
return new_ring.from_dict(self, self.ring.domain)
def as_expr(self, *symbols):
if symbols and len(symbols) != self.ring.ngens:
raise ValueError("not enough symbols, expected %s got %s" % (self.ring.ngens, len(symbols)))
else:
symbols = self.ring.symbols
return expr_from_dict(self.as_expr_dict(), *symbols)
def as_expr_dict(self):
to_sympy = self.ring.domain.to_sympy
return {monom: to_sympy(coeff) for monom, coeff in self.iterterms()}
def clear_denoms(self):
domain = self.ring.domain
if not domain.is_Field or not domain.has_assoc_Ring:
return domain.one, self
ground_ring = domain.get_ring()
common = ground_ring.one
lcm = ground_ring.lcm
denom = domain.denom
for coeff in self.values():
common = lcm(common, denom(coeff))
poly = self.new([ (k, v*common) for k, v in self.items() ])
return common, poly
def strip_zero(self):
"""Eliminate monomials with zero coefficient. """
for k, v in list(self.items()):
if not v:
del self[k]
def __eq__(p1, p2):
"""Equality test for polynomials.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.rings import ring
>>> _, x, y = ring('x, y', ZZ)
>>> p1 = (x + y)**2 + (x - y)**2
>>> p1 == 4*x*y
False
>>> p1 == 2*(x**2 + y**2)
True
"""
if not p2:
return not p1
elif isinstance(p2, PolyElement) and p2.ring == p1.ring:
return dict.__eq__(p1, p2)
elif len(p1) > 1:
return False
else:
return p1.get(p1.ring.zero_monom) == p2
def __ne__(p1, p2):
return not p1 == p2
def almosteq(p1, p2, tolerance=None):
"""Approximate equality test for polynomials. """
ring = p1.ring
if isinstance(p2, ring.dtype):
if set(p1.keys()) != set(p2.keys()):
return False
almosteq = ring.domain.almosteq
for k in p1.keys():
if not almosteq(p1[k], p2[k], tolerance):
return False
return True
elif len(p1) > 1:
return False
else:
try:
p2 = ring.domain.convert(p2)
except CoercionFailed:
return False
else:
return ring.domain.almosteq(p1.const(), p2, tolerance)
def sort_key(self):
return (len(self), self.terms())
def _cmp(p1, p2, op):
if isinstance(p2, p1.ring.dtype):
return op(p1.sort_key(), p2.sort_key())
else:
return NotImplemented
def __lt__(p1, p2):
return p1._cmp(p2, lt)
def __le__(p1, p2):
return p1._cmp(p2, le)
def __gt__(p1, p2):
return p1._cmp(p2, gt)
def __ge__(p1, p2):
return p1._cmp(p2, ge)
def _drop(self, gen):
ring = self.ring
i = ring.index(gen)
if ring.ngens == 1:
return i, ring.domain
else:
symbols = list(ring.symbols)
del symbols[i]
return i, ring.clone(symbols=symbols)
def drop(self, gen):
i, ring = self._drop(gen)
if self.ring.ngens == 1:
if self.is_ground:
return self.coeff(1)
else:
raise ValueError("can't drop %s" % gen)
else:
poly = ring.zero
for k, v in self.items():
if k[i] == 0:
K = list(k)
del K[i]
poly[tuple(K)] = v
else:
raise ValueError("can't drop %s" % gen)
return poly
def _drop_to_ground(self, gen):
ring = self.ring
i = ring.index(gen)
symbols = list(ring.symbols)
del symbols[i]
return i, ring.clone(symbols=symbols, domain=ring[i])
def drop_to_ground(self, gen):
if self.ring.ngens == 1:
raise ValueError("can't drop only generator to ground")
i, ring = self._drop_to_ground(gen)
poly = ring.zero
gen = ring.domain.gens[0]
for monom, coeff in self.iterterms():
mon = monom[:i] + monom[i+1:]
if not mon in poly:
poly[mon] = (gen**monom[i]).mul_ground(coeff)
else:
poly[mon] += (gen**monom[i]).mul_ground(coeff)
return poly
def to_dense(self):
return dmp_from_dict(self, self.ring.ngens-1, self.ring.domain)
def to_dict(self):
return dict(self)
def str(self, printer, precedence, exp_pattern, mul_symbol):
if not self:
return printer._print(self.ring.domain.zero)
prec_mul = precedence["Mul"]
prec_atom = precedence["Atom"]
ring = self.ring
symbols = ring.symbols
ngens = ring.ngens
zm = ring.zero_monom
sexpvs = []
for expv, coeff in self.terms():
negative = ring.domain.is_negative(coeff)
sign = " - " if negative else " + "
sexpvs.append(sign)
if expv == zm:
scoeff = printer._print(coeff)
if negative and scoeff.startswith("-"):
scoeff = scoeff[1:]
else:
if negative:
coeff = -coeff
if coeff != self.ring.one:
scoeff = printer.parenthesize(coeff, prec_mul, strict=True)
else:
scoeff = ''
sexpv = []
for i in range(ngens):
exp = expv[i]
if not exp:
continue
symbol = printer.parenthesize(symbols[i], prec_atom, strict=True)
if exp != 1:
if exp != int(exp) or exp < 0:
sexp = printer.parenthesize(exp, prec_atom, strict=False)
else:
sexp = exp
sexpv.append(exp_pattern % (symbol, sexp))
else:
sexpv.append('%s' % symbol)
if scoeff:
sexpv = [scoeff] + sexpv
sexpvs.append(mul_symbol.join(sexpv))
if sexpvs[0] in [" + ", " - "]:
head = sexpvs.pop(0)
if head == " - ":
sexpvs.insert(0, "-")
return "".join(sexpvs)
@property
def is_generator(self):
return self in self.ring._gens_set
@property
def is_ground(self):
return not self or (len(self) == 1 and self.ring.zero_monom in self)
@property
def is_monomial(self):
return not self or (len(self) == 1 and self.LC == 1)
@property
def is_term(self):
return len(self) <= 1
@property
def is_negative(self):
return self.ring.domain.is_negative(self.LC)
@property
def is_positive(self):
return self.ring.domain.is_positive(self.LC)
@property
def is_nonnegative(self):
return self.ring.domain.is_nonnegative(self.LC)
@property
def is_nonpositive(self):
return self.ring.domain.is_nonpositive(self.LC)
@property
def is_zero(f):
return not f
@property
def is_one(f):
return f == f.ring.one
@property
def is_monic(f):
return f.ring.domain.is_one(f.LC)
@property
def is_primitive(f):
return f.ring.domain.is_one(f.content())
@property
def is_linear(f):
return all(sum(monom) <= 1 for monom in f.itermonoms())
@property
def is_quadratic(f):
return all(sum(monom) <= 2 for monom in f.itermonoms())
@property
def is_squarefree(f):
if not f.ring.ngens:
return True
return f.ring.dmp_sqf_p(f)
@property
def is_irreducible(f):
if not f.ring.ngens:
return True
return f.ring.dmp_irreducible_p(f)
@property
def is_cyclotomic(f):
if f.ring.is_univariate:
return f.ring.dup_cyclotomic_p(f)
else:
raise MultivariatePolynomialError("cyclotomic polynomial")
def __neg__(self):
return self.new([ (monom, -coeff) for monom, coeff in self.iterterms() ])
def __pos__(self):
return self
def __add__(p1, p2):
"""Add two polynomials.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.rings import ring
>>> _, x, y = ring('x, y', ZZ)
>>> (x + y)**2 + (x - y)**2
2*x**2 + 2*y**2
"""
if not p2:
return p1.copy()
ring = p1.ring
if isinstance(p2, ring.dtype):
p = p1.copy()
get = p.get
zero = ring.domain.zero
for k, v in p2.items():
v = get(k, zero) + v
if v:
p[k] = v
else:
del p[k]
return p
elif isinstance(p2, PolyElement):
if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring:
pass
elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring:
return p2.__radd__(p1)
else:
return NotImplemented
try:
cp2 = ring.domain_new(p2)
except CoercionFailed:
return NotImplemented
else:
p = p1.copy()
if not cp2:
return p
zm = ring.zero_monom
if zm not in p1.keys():
p[zm] = cp2
else:
if p2 == -p[zm]:
del p[zm]
else:
p[zm] += cp2
return p
def __radd__(p1, n):
p = p1.copy()
if not n:
return p
ring = p1.ring
try:
n = ring.domain_new(n)
except CoercionFailed:
return NotImplemented
else:
zm = ring.zero_monom
if zm not in p1.keys():
p[zm] = n
else:
if n == -p[zm]:
del p[zm]
else:
p[zm] += n
return p
def __sub__(p1, p2):
"""Subtract polynomial p2 from p1.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.rings import ring
>>> _, x, y = ring('x, y', ZZ)
>>> p1 = x + y**2
>>> p2 = x*y + y**2
>>> p1 - p2
-x*y + x
"""
if not p2:
return p1.copy()
ring = p1.ring
if isinstance(p2, ring.dtype):
p = p1.copy()
get = p.get
zero = ring.domain.zero
for k, v in p2.items():
v = get(k, zero) - v
if v:
p[k] = v
else:
del p[k]
return p
elif isinstance(p2, PolyElement):
if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring:
pass
elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring:
return p2.__rsub__(p1)
else:
return NotImplemented
try:
p2 = ring.domain_new(p2)
except CoercionFailed:
return NotImplemented
else:
p = p1.copy()
zm = ring.zero_monom
if zm not in p1.keys():
p[zm] = -p2
else:
if p2 == p[zm]:
del p[zm]
else:
p[zm] -= p2
return p
def __rsub__(p1, n):
"""n - p1 with n convertible to the coefficient domain.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.rings import ring
>>> _, x, y = ring('x, y', ZZ)
>>> p = x + y
>>> 4 - p
-x - y + 4
"""
ring = p1.ring
try:
n = ring.domain_new(n)
except CoercionFailed:
return NotImplemented
else:
p = ring.zero
for expv in p1:
p[expv] = -p1[expv]
p += n
return p
def __mul__(p1, p2):
"""Multiply two polynomials.
Examples
========
>>> from sympy.polys.domains import QQ
>>> from sympy.polys.rings import ring
>>> _, x, y = ring('x, y', QQ)
>>> p1 = x + y
>>> p2 = x - y
>>> p1*p2
x**2 - y**2
"""
ring = p1.ring
p = ring.zero
if not p1 or not p2:
return p
elif isinstance(p2, ring.dtype):
get = p.get
zero = ring.domain.zero
monomial_mul = ring.monomial_mul
p2it = list(p2.items())
for exp1, v1 in p1.items():
for exp2, v2 in p2it:
exp = monomial_mul(exp1, exp2)
p[exp] = get(exp, zero) + v1*v2
p.strip_zero()
return p
elif isinstance(p2, PolyElement):
if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring:
pass
elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring:
return p2.__rmul__(p1)
else:
return NotImplemented
try:
p2 = ring.domain_new(p2)
except CoercionFailed:
return NotImplemented
else:
for exp1, v1 in p1.items():
v = v1*p2
if v:
p[exp1] = v
return p
def __rmul__(p1, p2):
"""p2 * p1 with p2 in the coefficient domain of p1.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.rings import ring
>>> _, x, y = ring('x, y', ZZ)
>>> p = x + y
>>> 4 * p
4*x + 4*y
"""
p = p1.ring.zero
if not p2:
return p
try:
p2 = p.ring.domain_new(p2)
except CoercionFailed:
return NotImplemented
else:
for exp1, v1 in p1.items():
v = p2*v1
if v:
p[exp1] = v
return p
def __pow__(self, n):
"""raise polynomial to power `n`
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.rings import ring
>>> _, x, y = ring('x, y', ZZ)
>>> p = x + y**2
>>> p**3
x**3 + 3*x**2*y**2 + 3*x*y**4 + y**6
"""
ring = self.ring
if not n:
if self:
return ring.one
else:
raise ValueError("0**0")
elif len(self) == 1:
monom, coeff = list(self.items())[0]
p = ring.zero
if coeff == 1:
p[ring.monomial_pow(monom, n)] = coeff
else:
p[ring.monomial_pow(monom, n)] = coeff**n
return p
# For ring series, we need negative and rational exponent support only
# with monomials.
n = int(n)
if n < 0:
raise ValueError("Negative exponent")
elif n == 1:
return self.copy()
elif n == 2:
return self.square()
elif n == 3:
return self*self.square()
elif len(self) <= 5: # TODO: use an actual density measure
return self._pow_multinomial(n)
else:
return self._pow_generic(n)
def _pow_generic(self, n):
p = self.ring.one
c = self
while True:
if n & 1:
p = p*c
n -= 1
if not n:
break
c = c.square()
n = n // 2
return p
def _pow_multinomial(self, n):
multinomials = multinomial_coefficients(len(self), n).items()
monomial_mulpow = self.ring.monomial_mulpow
zero_monom = self.ring.zero_monom
terms = self.items()
zero = self.ring.domain.zero
poly = self.ring.zero
for multinomial, multinomial_coeff in multinomials:
product_monom = zero_monom
product_coeff = multinomial_coeff
for exp, (monom, coeff) in zip(multinomial, terms):
if exp:
product_monom = monomial_mulpow(product_monom, monom, exp)
product_coeff *= coeff**exp
monom = tuple(product_monom)
coeff = product_coeff
coeff = poly.get(monom, zero) + coeff
if coeff:
poly[monom] = coeff
elif monom in poly:
del poly[monom]
return poly
def square(self):
"""square of a polynomial
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring('x, y', ZZ)
>>> p = x + y**2
>>> p.square()
x**2 + 2*x*y**2 + y**4
"""
ring = self.ring
p = ring.zero
get = p.get
keys = list(self.keys())
zero = ring.domain.zero
monomial_mul = ring.monomial_mul
for i in range(len(keys)):
k1 = keys[i]
pk = self[k1]
for j in range(i):
k2 = keys[j]
exp = monomial_mul(k1, k2)
p[exp] = get(exp, zero) + pk*self[k2]
p = p.imul_num(2)
get = p.get
for k, v in self.items():
k2 = monomial_mul(k, k)
p[k2] = get(k2, zero) + v**2
p.strip_zero()
return p
def __divmod__(p1, p2):
ring = p1.ring
if not p2:
raise ZeroDivisionError("polynomial division")
elif isinstance(p2, ring.dtype):
return p1.div(p2)
elif isinstance(p2, PolyElement):
if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring:
pass
elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring:
return p2.__rdivmod__(p1)
else:
return NotImplemented
try:
p2 = ring.domain_new(p2)
except CoercionFailed:
return NotImplemented
else:
return (p1.quo_ground(p2), p1.rem_ground(p2))
def __rdivmod__(p1, p2):
return NotImplemented
def __mod__(p1, p2):
ring = p1.ring
if not p2:
raise ZeroDivisionError("polynomial division")
elif isinstance(p2, ring.dtype):
return p1.rem(p2)
elif isinstance(p2, PolyElement):
if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring:
pass
elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring:
return p2.__rmod__(p1)
else:
return NotImplemented
try:
p2 = ring.domain_new(p2)
except CoercionFailed:
return NotImplemented
else:
return p1.rem_ground(p2)
def __rmod__(p1, p2):
return NotImplemented
def __truediv__(p1, p2):
ring = p1.ring
if not p2:
raise ZeroDivisionError("polynomial division")
elif isinstance(p2, ring.dtype):
if p2.is_monomial:
return p1*(p2**(-1))
else:
return p1.quo(p2)
elif isinstance(p2, PolyElement):
if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring:
pass
elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring:
return p2.__rtruediv__(p1)
else:
return NotImplemented
try:
p2 = ring.domain_new(p2)
except CoercionFailed:
return NotImplemented
else:
return p1.quo_ground(p2)
def __rtruediv__(p1, p2):
return NotImplemented
__floordiv__ = __truediv__
__rfloordiv__ = __rtruediv__
# TODO: use // (__floordiv__) for exquo()?
def _term_div(self):
zm = self.ring.zero_monom
domain = self.ring.domain
domain_quo = domain.quo
monomial_div = self.ring.monomial_div
if domain.is_Field:
def term_div(a_lm_a_lc, b_lm_b_lc):
a_lm, a_lc = a_lm_a_lc
b_lm, b_lc = b_lm_b_lc
if b_lm == zm: # apparently this is a very common case
monom = a_lm
else:
monom = monomial_div(a_lm, b_lm)
if monom is not None:
return monom, domain_quo(a_lc, b_lc)
else:
return None
else:
def term_div(a_lm_a_lc, b_lm_b_lc):
a_lm, a_lc = a_lm_a_lc
b_lm, b_lc = b_lm_b_lc
if b_lm == zm: # apparently this is a very common case
monom = a_lm
else:
monom = monomial_div(a_lm, b_lm)
if not (monom is None or a_lc % b_lc):
return monom, domain_quo(a_lc, b_lc)
else:
return None
return term_div
def div(self, fv):
"""Division algorithm, see [CLO] p64.
fv array of polynomials
return qv, r such that
self = sum(fv[i]*qv[i]) + r
All polynomials are required not to be Laurent polynomials.
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring('x, y', ZZ)
>>> f = x**3
>>> f0 = x - y**2
>>> f1 = x - y
>>> qv, r = f.div((f0, f1))
>>> qv[0]
x**2 + x*y**2 + y**4
>>> qv[1]
0
>>> r
y**6
"""
ring = self.ring
ret_single = False
if isinstance(fv, PolyElement):
ret_single = True
fv = [fv]
if any(not f for f in fv):
raise ZeroDivisionError("polynomial division")
if not self:
if ret_single:
return ring.zero, ring.zero
else:
return [], ring.zero
for f in fv:
if f.ring != ring:
raise ValueError('self and f must have the same ring')
s = len(fv)
qv = [ring.zero for i in range(s)]
p = self.copy()
r = ring.zero
term_div = self._term_div()
expvs = [fx.leading_expv() for fx in fv]
while p:
i = 0
divoccurred = 0
while i < s and divoccurred == 0:
expv = p.leading_expv()
term = term_div((expv, p[expv]), (expvs[i], fv[i][expvs[i]]))
if term is not None:
expv1, c = term
qv[i] = qv[i]._iadd_monom((expv1, c))
p = p._iadd_poly_monom(fv[i], (expv1, -c))
divoccurred = 1
else:
i += 1
if not divoccurred:
expv = p.leading_expv()
r = r._iadd_monom((expv, p[expv]))
del p[expv]
if expv == ring.zero_monom:
r += p
if ret_single:
if not qv:
return ring.zero, r
else:
return qv[0], r
else:
return qv, r
def rem(self, G):
f = self
if isinstance(G, PolyElement):
G = [G]
if any(not g for g in G):
raise ZeroDivisionError("polynomial division")
ring = f.ring
domain = ring.domain
zero = domain.zero
monomial_mul = ring.monomial_mul
r = ring.zero
term_div = f._term_div()
ltf = f.LT
f = f.copy()
get = f.get
while f:
for g in G:
tq = term_div(ltf, g.LT)
if tq is not None:
m, c = tq
for mg, cg in g.iterterms():
m1 = monomial_mul(mg, m)
c1 = get(m1, zero) - c*cg
if not c1:
del f[m1]
else:
f[m1] = c1
ltm = f.leading_expv()
if ltm is not None:
ltf = ltm, f[ltm]
break
else:
ltm, ltc = ltf
if ltm in r:
r[ltm] += ltc
else:
r[ltm] = ltc
del f[ltm]
ltm = f.leading_expv()
if ltm is not None:
ltf = ltm, f[ltm]
return r
def quo(f, G):
return f.div(G)[0]
def exquo(f, G):
q, r = f.div(G)
if not r:
return q
else:
raise ExactQuotientFailed(f, G)
def _iadd_monom(self, mc):
"""add to self the monomial coeff*x0**i0*x1**i1*...
unless self is a generator -- then just return the sum of the two.
mc is a tuple, (monom, coeff), where monomial is (i0, i1, ...)
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring('x, y', ZZ)
>>> p = x**4 + 2*y
>>> m = (1, 2)
>>> p1 = p._iadd_monom((m, 5))
>>> p1
x**4 + 5*x*y**2 + 2*y
>>> p1 is p
True
>>> p = x
>>> p1 = p._iadd_monom((m, 5))
>>> p1
5*x*y**2 + x
>>> p1 is p
False
"""
if self in self.ring._gens_set:
cpself = self.copy()
else:
cpself = self
expv, coeff = mc
c = cpself.get(expv)
if c is None:
cpself[expv] = coeff
else:
c += coeff
if c:
cpself[expv] = c
else:
del cpself[expv]
return cpself
def _iadd_poly_monom(self, p2, mc):
"""add to self the product of (p)*(coeff*x0**i0*x1**i1*...)
unless self is a generator -- then just return the sum of the two.
mc is a tuple, (monom, coeff), where monomial is (i0, i1, ...)
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y, z = ring('x, y, z', ZZ)
>>> p1 = x**4 + 2*y
>>> p2 = y + z
>>> m = (1, 2, 3)
>>> p1 = p1._iadd_poly_monom(p2, (m, 3))
>>> p1
x**4 + 3*x*y**3*z**3 + 3*x*y**2*z**4 + 2*y
"""
p1 = self
if p1 in p1.ring._gens_set:
p1 = p1.copy()
(m, c) = mc
get = p1.get
zero = p1.ring.domain.zero
monomial_mul = p1.ring.monomial_mul
for k, v in p2.items():
ka = monomial_mul(k, m)
coeff = get(ka, zero) + v*c
if coeff:
p1[ka] = coeff
else:
del p1[ka]
return p1
def degree(f, x=None):
"""
The leading degree in ``x`` or the main variable.
Note that the degree of 0 is negative infinity (the SymPy object -oo).
"""
i = f.ring.index(x)
if not f:
return -oo
elif i < 0:
return 0
else:
return max([ monom[i] for monom in f.itermonoms() ])
def degrees(f):
"""
A tuple containing leading degrees in all variables.
Note that the degree of 0 is negative infinity (the SymPy object -oo)
"""
if not f:
return (-oo,)*f.ring.ngens
else:
return tuple(map(max, list(zip(*f.itermonoms()))))
def tail_degree(f, x=None):
"""
The tail degree in ``x`` or the main variable.
Note that the degree of 0 is negative infinity (the SymPy object -oo)
"""
i = f.ring.index(x)
if not f:
return -oo
elif i < 0:
return 0
else:
return min([ monom[i] for monom in f.itermonoms() ])
def tail_degrees(f):
"""
A tuple containing tail degrees in all variables.
Note that the degree of 0 is negative infinity (the SymPy object -oo)
"""
if not f:
return (-oo,)*f.ring.ngens
else:
return tuple(map(min, list(zip(*f.itermonoms()))))
def leading_expv(self):
"""Leading monomial tuple according to the monomial ordering.
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y, z = ring('x, y, z', ZZ)
>>> p = x**4 + x**3*y + x**2*z**2 + z**7
>>> p.leading_expv()
(4, 0, 0)
"""
if self:
return self.ring.leading_expv(self)
else:
return None
def _get_coeff(self, expv):
return self.get(expv, self.ring.domain.zero)
def coeff(self, element):
"""
Returns the coefficient that stands next to the given monomial.
Parameters
==========
element : PolyElement (with ``is_monomial = True``) or 1
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y, z = ring("x,y,z", ZZ)
>>> f = 3*x**2*y - x*y*z + 7*z**3 + 23
>>> f.coeff(x**2*y)
3
>>> f.coeff(x*y)
0
>>> f.coeff(1)
23
"""
if element == 1:
return self._get_coeff(self.ring.zero_monom)
elif isinstance(element, self.ring.dtype):
terms = list(element.iterterms())
if len(terms) == 1:
monom, coeff = terms[0]
if coeff == self.ring.domain.one:
return self._get_coeff(monom)
raise ValueError("expected a monomial, got %s" % element)
def const(self):
"""Returns the constant coeffcient. """
return self._get_coeff(self.ring.zero_monom)
@property
def LC(self):
return self._get_coeff(self.leading_expv())
@property
def LM(self):
expv = self.leading_expv()
if expv is None:
return self.ring.zero_monom
else:
return expv
def leading_monom(self):
"""
Leading monomial as a polynomial element.
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring('x, y', ZZ)
>>> (3*x*y + y**2).leading_monom()
x*y
"""
p = self.ring.zero
expv = self.leading_expv()
if expv:
p[expv] = self.ring.domain.one
return p
@property
def LT(self):
expv = self.leading_expv()
if expv is None:
return (self.ring.zero_monom, self.ring.domain.zero)
else:
return (expv, self._get_coeff(expv))
def leading_term(self):
"""Leading term as a polynomial element.
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring('x, y', ZZ)
>>> (3*x*y + y**2).leading_term()
3*x*y
"""
p = self.ring.zero
expv = self.leading_expv()
if expv is not None:
p[expv] = self[expv]
return p
def _sorted(self, seq, order):
if order is None:
order = self.ring.order
else:
order = OrderOpt.preprocess(order)
if order is lex:
return sorted(seq, key=lambda monom: monom[0], reverse=True)
else:
return sorted(seq, key=lambda monom: order(monom[0]), reverse=True)
def coeffs(self, order=None):
"""Ordered list of polynomial coefficients.
Parameters
==========
order : :class:`~.MonomialOrder` or coercible, optional
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.orderings import lex, grlex
>>> _, x, y = ring("x, y", ZZ, lex)
>>> f = x*y**7 + 2*x**2*y**3
>>> f.coeffs()
[2, 1]
>>> f.coeffs(grlex)
[1, 2]
"""
return [ coeff for _, coeff in self.terms(order) ]
def monoms(self, order=None):
"""Ordered list of polynomial monomials.
Parameters
==========
order : :class:`~.MonomialOrder` or coercible, optional
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.orderings import lex, grlex
>>> _, x, y = ring("x, y", ZZ, lex)
>>> f = x*y**7 + 2*x**2*y**3
>>> f.monoms()
[(2, 3), (1, 7)]
>>> f.monoms(grlex)
[(1, 7), (2, 3)]
"""
return [ monom for monom, _ in self.terms(order) ]
def terms(self, order=None):
"""Ordered list of polynomial terms.
Parameters
==========
order : :class:`~.MonomialOrder` or coercible, optional
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.orderings import lex, grlex
>>> _, x, y = ring("x, y", ZZ, lex)
>>> f = x*y**7 + 2*x**2*y**3
>>> f.terms()
[((2, 3), 2), ((1, 7), 1)]
>>> f.terms(grlex)
[((1, 7), 1), ((2, 3), 2)]
"""
return self._sorted(list(self.items()), order)
def itercoeffs(self):
"""Iterator over coefficients of a polynomial. """
return iter(self.values())
def itermonoms(self):
"""Iterator over monomials of a polynomial. """
return iter(self.keys())
def iterterms(self):
"""Iterator over terms of a polynomial. """
return iter(self.items())
def listcoeffs(self):
"""Unordered list of polynomial coefficients. """
return list(self.values())
def listmonoms(self):
"""Unordered list of polynomial monomials. """
return list(self.keys())
def listterms(self):
"""Unordered list of polynomial terms. """
return list(self.items())
def imul_num(p, c):
"""multiply inplace the polynomial p by an element in the
coefficient ring, provided p is not one of the generators;
else multiply not inplace
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring('x, y', ZZ)
>>> p = x + y**2
>>> p1 = p.imul_num(3)
>>> p1
3*x + 3*y**2
>>> p1 is p
True
>>> p = x
>>> p1 = p.imul_num(3)
>>> p1
3*x
>>> p1 is p
False
"""
if p in p.ring._gens_set:
return p*c
if not c:
p.clear()
return
for exp in p:
p[exp] *= c
return p
def content(f):
"""Returns GCD of polynomial's coefficients. """
domain = f.ring.domain
cont = domain.zero
gcd = domain.gcd
for coeff in f.itercoeffs():
cont = gcd(cont, coeff)
return cont
def primitive(f):
"""Returns content and a primitive polynomial. """
cont = f.content()
return cont, f.quo_ground(cont)
def monic(f):
"""Divides all coefficients by the leading coefficient. """
if not f:
return f
else:
return f.quo_ground(f.LC)
def mul_ground(f, x):
if not x:
return f.ring.zero
terms = [ (monom, coeff*x) for monom, coeff in f.iterterms() ]
return f.new(terms)
def mul_monom(f, monom):
monomial_mul = f.ring.monomial_mul
terms = [ (monomial_mul(f_monom, monom), f_coeff) for f_monom, f_coeff in f.items() ]
return f.new(terms)
def mul_term(f, term):
monom, coeff = term
if not f or not coeff:
return f.ring.zero
elif monom == f.ring.zero_monom:
return f.mul_ground(coeff)
monomial_mul = f.ring.monomial_mul
terms = [ (monomial_mul(f_monom, monom), f_coeff*coeff) for f_monom, f_coeff in f.items() ]
return f.new(terms)
def quo_ground(f, x):
domain = f.ring.domain
if not x:
raise ZeroDivisionError('polynomial division')
if not f or x == domain.one:
return f
if domain.is_Field:
quo = domain.quo
terms = [ (monom, quo(coeff, x)) for monom, coeff in f.iterterms() ]
else:
terms = [ (monom, coeff // x) for monom, coeff in f.iterterms() if not (coeff % x) ]
return f.new(terms)
def quo_term(f, term):
monom, coeff = term
if not coeff:
raise ZeroDivisionError("polynomial division")
elif not f:
return f.ring.zero
elif monom == f.ring.zero_monom:
return f.quo_ground(coeff)
term_div = f._term_div()
terms = [ term_div(t, term) for t in f.iterterms() ]
return f.new([ t for t in terms if t is not None ])
def trunc_ground(f, p):
if f.ring.domain.is_ZZ:
terms = []
for monom, coeff in f.iterterms():
coeff = coeff % p
if coeff > p // 2:
coeff = coeff - p
terms.append((monom, coeff))
else:
terms = [ (monom, coeff % p) for monom, coeff in f.iterterms() ]
poly = f.new(terms)
poly.strip_zero()
return poly
rem_ground = trunc_ground
def extract_ground(self, g):
f = self
fc = f.content()
gc = g.content()
gcd = f.ring.domain.gcd(fc, gc)
f = f.quo_ground(gcd)
g = g.quo_ground(gcd)
return gcd, f, g
def _norm(f, norm_func):
if not f:
return f.ring.domain.zero
else:
ground_abs = f.ring.domain.abs
return norm_func([ ground_abs(coeff) for coeff in f.itercoeffs() ])
def max_norm(f):
return f._norm(max)
def l1_norm(f):
return f._norm(sum)
def deflate(f, *G):
ring = f.ring
polys = [f] + list(G)
J = [0]*ring.ngens
for p in polys:
for monom in p.itermonoms():
for i, m in enumerate(monom):
J[i] = igcd(J[i], m)
for i, b in enumerate(J):
if not b:
J[i] = 1
J = tuple(J)
if all(b == 1 for b in J):
return J, polys
H = []
for p in polys:
h = ring.zero
for I, coeff in p.iterterms():
N = [ i // j for i, j in zip(I, J) ]
h[tuple(N)] = coeff
H.append(h)
return J, H
def inflate(f, J):
poly = f.ring.zero
for I, coeff in f.iterterms():
N = [ i*j for i, j in zip(I, J) ]
poly[tuple(N)] = coeff
return poly
def lcm(self, g):
f = self
domain = f.ring.domain
if not domain.is_Field:
fc, f = f.primitive()
gc, g = g.primitive()
c = domain.lcm(fc, gc)
h = (f*g).quo(f.gcd(g))
if not domain.is_Field:
return h.mul_ground(c)
else:
return h.monic()
def gcd(f, g):
return f.cofactors(g)[0]
def cofactors(f, g):
if not f and not g:
zero = f.ring.zero
return zero, zero, zero
elif not f:
h, cff, cfg = f._gcd_zero(g)
return h, cff, cfg
elif not g:
h, cfg, cff = g._gcd_zero(f)
return h, cff, cfg
elif len(f) == 1:
h, cff, cfg = f._gcd_monom(g)
return h, cff, cfg
elif len(g) == 1:
h, cfg, cff = g._gcd_monom(f)
return h, cff, cfg
J, (f, g) = f.deflate(g)
h, cff, cfg = f._gcd(g)
return (h.inflate(J), cff.inflate(J), cfg.inflate(J))
def _gcd_zero(f, g):
one, zero = f.ring.one, f.ring.zero
if g.is_nonnegative:
return g, zero, one
else:
return -g, zero, -one
def _gcd_monom(f, g):
ring = f.ring
ground_gcd = ring.domain.gcd
ground_quo = ring.domain.quo
monomial_gcd = ring.monomial_gcd
monomial_ldiv = ring.monomial_ldiv
mf, cf = list(f.iterterms())[0]
_mgcd, _cgcd = mf, cf
for mg, cg in g.iterterms():
_mgcd = monomial_gcd(_mgcd, mg)
_cgcd = ground_gcd(_cgcd, cg)
h = f.new([(_mgcd, _cgcd)])
cff = f.new([(monomial_ldiv(mf, _mgcd), ground_quo(cf, _cgcd))])
cfg = f.new([(monomial_ldiv(mg, _mgcd), ground_quo(cg, _cgcd)) for mg, cg in g.iterterms()])
return h, cff, cfg
def _gcd(f, g):
ring = f.ring
if ring.domain.is_QQ:
return f._gcd_QQ(g)
elif ring.domain.is_ZZ:
return f._gcd_ZZ(g)
else: # TODO: don't use dense representation (port PRS algorithms)
return ring.dmp_inner_gcd(f, g)
def _gcd_ZZ(f, g):
return heugcd(f, g)
def _gcd_QQ(self, g):
f = self
ring = f.ring
new_ring = ring.clone(domain=ring.domain.get_ring())
cf, f = f.clear_denoms()
cg, g = g.clear_denoms()
f = f.set_ring(new_ring)
g = g.set_ring(new_ring)
h, cff, cfg = f._gcd_ZZ(g)
h = h.set_ring(ring)
c, h = h.LC, h.monic()
cff = cff.set_ring(ring).mul_ground(ring.domain.quo(c, cf))
cfg = cfg.set_ring(ring).mul_ground(ring.domain.quo(c, cg))
return h, cff, cfg
def cancel(self, g):
"""
Cancel common factors in a rational function ``f/g``.
Examples
========
>>> from sympy.polys import ring, ZZ
>>> R, x,y = ring("x,y", ZZ)
>>> (2*x**2 - 2).cancel(x**2 - 2*x + 1)
(2*x + 2, x - 1)
"""
f = self
ring = f.ring
if not f:
return f, ring.one
domain = ring.domain
if not (domain.is_Field and domain.has_assoc_Ring):
_, p, q = f.cofactors(g)
else:
new_ring = ring.clone(domain=domain.get_ring())
cq, f = f.clear_denoms()
cp, g = g.clear_denoms()
f = f.set_ring(new_ring)
g = g.set_ring(new_ring)
_, p, q = f.cofactors(g)
_, cp, cq = new_ring.domain.cofactors(cp, cq)
p = p.set_ring(ring)
q = q.set_ring(ring)
p = p.mul_ground(cp)
q = q.mul_ground(cq)
# Make canonical with respect to sign or quadrant in the case of ZZ_I
# or QQ_I. This ensures that the LC of the denominator is canonical by
# multiplying top and bottom by a unit of the ring.
u = q.canonical_unit()
if u == domain.one:
p, q = p, q
elif u == -domain.one:
p, q = -p, -q
else:
p = p.mul_ground(u)
q = q.mul_ground(u)
return p, q
def canonical_unit(f):
domain = f.ring.domain
return domain.canonical_unit(f.LC)
def diff(f, x):
"""Computes partial derivative in ``x``.
Examples
========
>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring("x,y", ZZ)
>>> p = x + x**2*y**3
>>> p.diff(x)
2*x*y**3 + 1
"""
ring = f.ring
i = ring.index(x)
m = ring.monomial_basis(i)
g = ring.zero
for expv, coeff in f.iterterms():
if expv[i]:
e = ring.monomial_ldiv(expv, m)
g[e] = ring.domain_new(coeff*expv[i])
return g
def __call__(f, *values):
if 0 < len(values) <= f.ring.ngens:
return f.evaluate(list(zip(f.ring.gens, values)))
else:
raise ValueError("expected at least 1 and at most %s values, got %s" % (f.ring.ngens, len(values)))
def evaluate(self, x, a=None):
f = self
if isinstance(x, list) and a is None:
(X, a), x = x[0], x[1:]
f = f.evaluate(X, a)
if not x:
return f
else:
x = [ (Y.drop(X), a) for (Y, a) in x ]
return f.evaluate(x)
ring = f.ring
i = ring.index(x)
a = ring.domain.convert(a)
if ring.ngens == 1:
result = ring.domain.zero
for (n,), coeff in f.iterterms():
result += coeff*a**n
return result
else:
poly = ring.drop(x).zero
for monom, coeff in f.iterterms():
n, monom = monom[i], monom[:i] + monom[i+1:]
coeff = coeff*a**n
if monom in poly:
coeff = coeff + poly[monom]
if coeff:
poly[monom] = coeff
else:
del poly[monom]
else:
if coeff:
poly[monom] = coeff
return poly
def subs(self, x, a=None):
f = self
if isinstance(x, list) and a is None:
for X, a in x:
f = f.subs(X, a)
return f
ring = f.ring
i = ring.index(x)
a = ring.domain.convert(a)
if ring.ngens == 1:
result = ring.domain.zero
for (n,), coeff in f.iterterms():
result += coeff*a**n
return ring.ground_new(result)
else:
poly = ring.zero
for monom, coeff in f.iterterms():
n, monom = monom[i], monom[:i] + (0,) + monom[i+1:]
coeff = coeff*a**n
if monom in poly:
coeff = coeff + poly[monom]
if coeff:
poly[monom] = coeff
else:
del poly[monom]
else:
if coeff:
poly[monom] = coeff
return poly
def compose(f, x, a=None):
ring = f.ring
poly = ring.zero
gens_map = dict(list(zip(ring.gens, list(range(ring.ngens)))))
if a is not None:
replacements = [(x, a)]
else:
if isinstance(x, list):
replacements = list(x)
elif isinstance(x, dict):
replacements = sorted(list(x.items()), key=lambda k: gens_map[k[0]])
else:
raise ValueError("expected a generator, value pair a sequence of such pairs")
for k, (x, g) in enumerate(replacements):
replacements[k] = (gens_map[x], ring.ring_new(g))
for monom, coeff in f.iterterms():
monom = list(monom)
subpoly = ring.one
for i, g in replacements:
n, monom[i] = monom[i], 0
if n:
subpoly *= g**n
subpoly = subpoly.mul_term((tuple(monom), coeff))
poly += subpoly
return poly
# TODO: following methods should point to polynomial
# representation independent algorithm implementations.
def pdiv(f, g):
return f.ring.dmp_pdiv(f, g)
def prem(f, g):
return f.ring.dmp_prem(f, g)
def pquo(f, g):
return f.ring.dmp_quo(f, g)
def pexquo(f, g):
return f.ring.dmp_exquo(f, g)
def half_gcdex(f, g):
return f.ring.dmp_half_gcdex(f, g)
def gcdex(f, g):
return f.ring.dmp_gcdex(f, g)
def subresultants(f, g):
return f.ring.dmp_subresultants(f, g)
def resultant(f, g):
return f.ring.dmp_resultant(f, g)
def discriminant(f):
return f.ring.dmp_discriminant(f)
def decompose(f):
if f.ring.is_univariate:
return f.ring.dup_decompose(f)
else:
raise MultivariatePolynomialError("polynomial decomposition")
def shift(f, a):
if f.ring.is_univariate:
return f.ring.dup_shift(f, a)
else:
raise MultivariatePolynomialError("polynomial shift")
def sturm(f):
if f.ring.is_univariate:
return f.ring.dup_sturm(f)
else:
raise MultivariatePolynomialError("sturm sequence")
def gff_list(f):
return f.ring.dmp_gff_list(f)
def sqf_norm(f):
return f.ring.dmp_sqf_norm(f)
def sqf_part(f):
return f.ring.dmp_sqf_part(f)
def sqf_list(f, all=False):
return f.ring.dmp_sqf_list(f, all=all)
def factor_list(f):
return f.ring.dmp_factor_list(f)
|
87b6bd9b3e6ff997fb1b7be44bc34671e668ff55cee5788f97788f50839892d0 | """Low-level linear systems solver. """
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.iterables import connected_components
from sympy.core.sympify import sympify
from sympy.matrices.dense import MutableDenseMatrix
from sympy.polys.domains import ZZ, QQ
from sympy.polys.domains import EX
from sympy.polys.rings import sring
from sympy.polys.polyerrors import NotInvertible
from sympy.polys.domainmatrix import DomainMatrix
class PolyNonlinearError(Exception):
"""Raised by solve_lin_sys for nonlinear equations"""
pass
class RawMatrix(MutableDenseMatrix):
"""
XXX: This class is broken by design. Use DomainMatrix if you want a matrix
over the polys domains or Matrix for a matrix with Expr elements. The
RawMatrix class will be removed/broken in future in order to reestablish
the invariant that the elements of a Matrix should be of type Expr.
"""
_sympify = staticmethod(lambda x: x)
def __init__(self, *args, **kwargs):
SymPyDeprecationWarning(
feature="RawMatrix class",
useinstead="DomainMatrix or Matrix",
issue=21405,
deprecated_since_version="1.9"
).warn()
domain = ZZ
for i in range(self.rows):
for j in range(self.cols):
val = self[i,j]
if getattr(val, 'is_Poly', False):
K = val.domain[val.gens]
val_sympy = val.as_expr()
elif hasattr(val, 'parent'):
K = val.parent()
val_sympy = K.to_sympy(val)
elif isinstance(val, int):
K = ZZ
val_sympy = sympify(val)
else:
for K in ZZ, QQ:
if K.of_type(val):
val_sympy = K.to_sympy(val)
break
else:
raise TypeError
domain = domain.unify(K)
self[i,j] = val_sympy
self.ring = domain
def eqs_to_matrix(eqs_coeffs, eqs_rhs, gens, domain):
"""Get matrix from linear equations in dict format.
Explanation
===========
Get the matrix representation of a system of linear equations represented
as dicts with low-level DomainElement coefficients. This is an
*internal* function that is used by solve_lin_sys.
Parameters
==========
eqs_coeffs: list[dict[Symbol, DomainElement]]
The left hand sides of the equations as dicts mapping from symbols to
coefficients where the coefficients are instances of
DomainElement.
eqs_rhs: list[DomainElements]
The right hand sides of the equations as instances of
DomainElement.
gens: list[Symbol]
The unknowns in the system of equations.
domain: Domain
The domain for coefficients of both lhs and rhs.
Returns
=======
The augmented matrix representation of the system as a DomainMatrix.
Examples
========
>>> from sympy import symbols, ZZ
>>> from sympy.polys.solvers import eqs_to_matrix
>>> x, y = symbols('x, y')
>>> eqs_coeff = [{x:ZZ(1), y:ZZ(1)}, {x:ZZ(1), y:ZZ(-1)}]
>>> eqs_rhs = [ZZ(0), ZZ(-1)]
>>> eqs_to_matrix(eqs_coeff, eqs_rhs, [x, y], ZZ)
DomainMatrix([[1, 1, 0], [1, -1, 1]], (2, 3), ZZ)
See also
========
solve_lin_sys: Uses :func:`~eqs_to_matrix` internally
"""
sym2index = {x: n for n, x in enumerate(gens)}
nrows = len(eqs_coeffs)
ncols = len(gens) + 1
rows = [[domain.zero] * ncols for _ in range(nrows)]
for row, eq_coeff, eq_rhs in zip(rows, eqs_coeffs, eqs_rhs):
for sym, coeff in eq_coeff.items():
row[sym2index[sym]] = domain.convert(coeff)
row[-1] = -domain.convert(eq_rhs)
return DomainMatrix(rows, (nrows, ncols), domain)
def sympy_eqs_to_ring(eqs, symbols):
"""Convert a system of equations from Expr to a PolyRing
Explanation
===========
High-level functions like ``solve`` expect Expr as inputs but can use
``solve_lin_sys`` internally. This function converts equations from
``Expr`` to the low-level poly types used by the ``solve_lin_sys``
function.
Parameters
==========
eqs: List of Expr
A list of equations as Expr instances
symbols: List of Symbol
A list of the symbols that are the unknowns in the system of
equations.
Returns
=======
Tuple[List[PolyElement], Ring]: The equations as PolyElement instances
and the ring of polynomials within which each equation is represented.
Examples
========
>>> from sympy import symbols
>>> from sympy.polys.solvers import sympy_eqs_to_ring
>>> a, x, y = symbols('a, x, y')
>>> eqs = [x-y, x+a*y]
>>> eqs_ring, ring = sympy_eqs_to_ring(eqs, [x, y])
>>> eqs_ring
[x - y, x + a*y]
>>> type(eqs_ring[0])
<class 'sympy.polys.rings.PolyElement'>
>>> ring
ZZ(a)[x,y]
With the equations in this form they can be passed to ``solve_lin_sys``:
>>> from sympy.polys.solvers import solve_lin_sys
>>> solve_lin_sys(eqs_ring, ring)
{y: 0, x: 0}
"""
try:
K, eqs_K = sring(eqs, symbols, field=True, extension=True)
except NotInvertible:
# https://github.com/sympy/sympy/issues/18874
K, eqs_K = sring(eqs, symbols, domain=EX)
return eqs_K, K.to_domain()
def solve_lin_sys(eqs, ring, _raw=True):
"""Solve a system of linear equations from a PolynomialRing
Explanation
===========
Solves a system of linear equations given as PolyElement instances of a
PolynomialRing. The basic arithmetic is carried out using instance of
DomainElement which is more efficient than :class:`~sympy.core.expr.Expr`
for the most common inputs.
While this is a public function it is intended primarily for internal use
so its interface is not necessarily convenient. Users are suggested to use
the :func:`sympy.solvers.solveset.linsolve` function (which uses this
function internally) instead.
Parameters
==========
eqs: list[PolyElement]
The linear equations to be solved as elements of a
PolynomialRing (assumed equal to zero).
ring: PolynomialRing
The polynomial ring from which eqs are drawn. The generators of this
ring are the unkowns to be solved for and the domain of the ring is
the domain of the coefficients of the system of equations.
_raw: bool
If *_raw* is False, the keys and values in the returned dictionary
will be of type Expr (and the unit of the field will be removed from
the keys) otherwise the low-level polys types will be returned, e.g.
PolyElement: PythonRational.
Returns
=======
``None`` if the system has no solution.
dict[Symbol, Expr] if _raw=False
dict[Symbol, DomainElement] if _raw=True.
Examples
========
>>> from sympy import symbols
>>> from sympy.polys.solvers import solve_lin_sys, sympy_eqs_to_ring
>>> x, y = symbols('x, y')
>>> eqs = [x - y, x + y - 2]
>>> eqs_ring, ring = sympy_eqs_to_ring(eqs, [x, y])
>>> solve_lin_sys(eqs_ring, ring)
{y: 1, x: 1}
Passing ``_raw=False`` returns the same result except that the keys are
``Expr`` rather than low-level poly types.
>>> solve_lin_sys(eqs_ring, ring, _raw=False)
{x: 1, y: 1}
See also
========
sympy_eqs_to_ring: prepares the inputs to ``solve_lin_sys``.
linsolve: ``linsolve`` uses ``solve_lin_sys`` internally.
sympy.solvers.solvers.solve: ``solve`` uses ``solve_lin_sys`` internally.
"""
as_expr = not _raw
assert ring.domain.is_Field
eqs_dict = [dict(eq) for eq in eqs]
one_monom = ring.one.monoms()[0]
zero = ring.domain.zero
eqs_rhs = []
eqs_coeffs = []
for eq_dict in eqs_dict:
eq_rhs = eq_dict.pop(one_monom, zero)
eq_coeffs = {}
for monom, coeff in eq_dict.items():
if sum(monom) != 1:
msg = "Nonlinear term encountered in solve_lin_sys"
raise PolyNonlinearError(msg)
eq_coeffs[ring.gens[monom.index(1)]] = coeff
if not eq_coeffs:
if not eq_rhs:
continue
else:
return None
eqs_rhs.append(eq_rhs)
eqs_coeffs.append(eq_coeffs)
result = _solve_lin_sys(eqs_coeffs, eqs_rhs, ring)
if result is not None and as_expr:
def to_sympy(x):
as_expr = getattr(x, 'as_expr', None)
if as_expr:
return as_expr()
else:
return ring.domain.to_sympy(x)
tresult = {to_sympy(sym): to_sympy(val) for sym, val in result.items()}
# Remove 1.0x
result = {}
for k, v in tresult.items():
if k.is_Mul:
c, s = k.as_coeff_Mul()
result[s] = v/c
else:
result[k] = v
return result
def _solve_lin_sys(eqs_coeffs, eqs_rhs, ring):
"""Solve a linear system from dict of PolynomialRing coefficients
Explanation
===========
This is an **internal** function used by :func:`solve_lin_sys` after the
equations have been preprocessed. The role of this function is to split
the system into connected components and pass those to
:func:`_solve_lin_sys_component`.
Examples
========
Setup a system for $x-y=0$ and $x+y=2$ and solve:
>>> from sympy import symbols, sring
>>> from sympy.polys.solvers import _solve_lin_sys
>>> x, y = symbols('x, y')
>>> R, (xr, yr) = sring([x, y], [x, y])
>>> eqs = [{xr:R.one, yr:-R.one}, {xr:R.one, yr:R.one}]
>>> eqs_rhs = [R.zero, -2*R.one]
>>> _solve_lin_sys(eqs, eqs_rhs, R)
{y: 1, x: 1}
See also
========
solve_lin_sys: This function is used internally by :func:`solve_lin_sys`.
"""
V = ring.gens
E = []
for eq_coeffs in eqs_coeffs:
syms = list(eq_coeffs)
E.extend(zip(syms[:-1], syms[1:]))
G = V, E
components = connected_components(G)
sym2comp = {}
for n, component in enumerate(components):
for sym in component:
sym2comp[sym] = n
subsystems = [([], []) for _ in range(len(components))]
for eq_coeff, eq_rhs in zip(eqs_coeffs, eqs_rhs):
sym = next(iter(eq_coeff), None)
sub_coeff, sub_rhs = subsystems[sym2comp[sym]]
sub_coeff.append(eq_coeff)
sub_rhs.append(eq_rhs)
sol = {}
for subsystem in subsystems:
subsol = _solve_lin_sys_component(subsystem[0], subsystem[1], ring)
if subsol is None:
return None
sol.update(subsol)
return sol
def _solve_lin_sys_component(eqs_coeffs, eqs_rhs, ring):
"""Solve a linear system from dict of PolynomialRing coefficients
Explanation
===========
This is an **internal** function used by :func:`solve_lin_sys` after the
equations have been preprocessed. After :func:`_solve_lin_sys` splits the
system into connected components this function is called for each
component. The system of equations is solved using Gauss-Jordan
elimination with division followed by back-substitution.
Examples
========
Setup a system for $x-y=0$ and $x+y=2$ and solve:
>>> from sympy import symbols, sring
>>> from sympy.polys.solvers import _solve_lin_sys_component
>>> x, y = symbols('x, y')
>>> R, (xr, yr) = sring([x, y], [x, y])
>>> eqs = [{xr:R.one, yr:-R.one}, {xr:R.one, yr:R.one}]
>>> eqs_rhs = [R.zero, -2*R.one]
>>> _solve_lin_sys_component(eqs, eqs_rhs, R)
{y: 1, x: 1}
See also
========
solve_lin_sys: This function is used internally by :func:`solve_lin_sys`.
"""
# transform from equations to matrix form
matrix = eqs_to_matrix(eqs_coeffs, eqs_rhs, ring.gens, ring.domain)
# convert to a field for rref
if not matrix.domain.is_Field:
matrix = matrix.to_field()
# solve by row-reduction
echelon, pivots = matrix.rref()
# construct the returnable form of the solutions
keys = ring.gens
if pivots and pivots[-1] == len(keys):
return None
if len(pivots) == len(keys):
sol = []
for s in [row[-1] for row in echelon.rep.to_ddm()]:
a = s
sol.append(a)
sols = dict(zip(keys, sol))
else:
sols = {}
g = ring.gens
# Extract ground domain coefficients and convert to the ring:
if hasattr(ring, 'ring'):
convert = ring.ring.ground_new
else:
convert = ring.ground_new
echelon = echelon.rep.to_ddm()
vals_set = {v for row in echelon for v in row}
vals_map = {v: convert(v) for v in vals_set}
echelon = [[vals_map[eij] for eij in ei] for ei in echelon]
for i, p in enumerate(pivots):
v = echelon[i][-1] - sum(echelon[i][j]*g[j] for j in range(p+1, len(g)) if echelon[i][j])
sols[keys[p]] = v
return sols
|
56ee05bef05074e13079de3d0b2d4c28a457a4ec92ea1a5f535db3d04e72dd99 | """Computational algebraic field theory. """
from functools import reduce
from sympy import (
S, Rational, AlgebraicNumber, GoldenRatio, TribonacciConstant,
Add, Mul, sympify, Dummy, expand_mul, I, pi
)
from sympy.functions import sqrt, cbrt
from sympy.core.exprtools import Factors
from sympy.core.function import _mexpand
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.trigonometric import cos, sin, tan
from sympy.ntheory import sieve
from sympy.ntheory.factor_ import divisors
from sympy.utilities.iterables import subsets
from sympy.polys.densetools import dup_eval
from sympy.polys.domains import ZZ, QQ
from sympy.polys.orthopolys import dup_chebyshevt
from sympy.polys.polyerrors import (
IsomorphismFailed,
NotAlgebraic,
GeneratorsError,
)
from sympy.polys.polytools import (
Poly, PurePoly, invert, factor_list, groebner, resultant,
degree, poly_from_expr, parallel_poly_from_expr, lcm
)
from sympy.polys.polyutils import dict_from_expr, expr_from_dict
from sympy.polys.ring_series import rs_compose_add
from sympy.polys.rings import ring
from sympy.polys.rootoftools import CRootOf
from sympy.polys.specialpolys import cyclotomic_poly
from sympy.printing.lambdarepr import LambdaPrinter
from sympy.printing.pycode import PythonCodePrinter, MpmathPrinter
from sympy.simplify.radsimp import _split_gcd
from sympy.simplify.simplify import _is_sum_surds
from sympy.utilities import (
numbered_symbols, lambdify, public, sift
)
from mpmath import pslq, mp
def _choose_factor(factors, x, v, dom=QQ, prec=200, bound=5):
"""
Return a factor having root ``v``
It is assumed that one of the factors has root ``v``.
"""
from sympy.polys.polyutils import illegal
if isinstance(factors[0], tuple):
factors = [f[0] for f in factors]
if len(factors) == 1:
return factors[0]
prec1 = 10
points = {}
symbols = dom.symbols if hasattr(dom, 'symbols') else []
while prec1 <= prec:
# when dealing with non-Rational numbers we usually evaluate
# with `subs` argument but we only need a ballpark evaluation
xv = {x:v if not v.is_number else v.n(prec1)}
fe = [f.as_expr().xreplace(xv) for f in factors]
# assign integers [0, n) to symbols (if any)
for n in subsets(range(bound), k=len(symbols), repetition=True):
for s, i in zip(symbols, n):
points[s] = i
# evaluate the expression at these points
candidates = [(abs(f.subs(points).n(prec1)), i)
for i,f in enumerate(fe)]
# if we get invalid numbers (e.g. from division by zero)
# we try again
if any(i in illegal for i, _ in candidates):
continue
# find the smallest two -- if they differ significantly
# then we assume we have found the factor that becomes
# 0 when v is substituted into it
can = sorted(candidates)
(a, ix), (b, _) = can[:2]
if b > a * 10**6: # XXX what to use?
return factors[ix]
prec1 *= 2
raise NotImplementedError("multiple candidates for the minimal polynomial of %s" % v)
def _separate_sq(p):
"""
helper function for ``_minimal_polynomial_sq``
It selects a rational ``g`` such that the polynomial ``p``
consists of a sum of terms whose surds squared have gcd equal to ``g``
and a sum of terms with surds squared prime with ``g``;
then it takes the field norm to eliminate ``sqrt(g)``
See simplify.simplify.split_surds and polytools.sqf_norm.
Examples
========
>>> from sympy import sqrt
>>> from sympy.abc import x
>>> from sympy.polys.numberfields import _separate_sq
>>> p= -x + sqrt(2) + sqrt(3) + sqrt(7)
>>> p = _separate_sq(p); p
-x**2 + 2*sqrt(3)*x + 2*sqrt(7)*x - 2*sqrt(21) - 8
>>> p = _separate_sq(p); p
-x**4 + 4*sqrt(7)*x**3 - 32*x**2 + 8*sqrt(7)*x + 20
>>> p = _separate_sq(p); p
-x**8 + 48*x**6 - 536*x**4 + 1728*x**2 - 400
"""
from sympy.utilities.iterables import sift
def is_sqrt(expr):
return expr.is_Pow and expr.exp is S.Half
# p = c1*sqrt(q1) + ... + cn*sqrt(qn) -> a = [(c1, q1), .., (cn, qn)]
a = []
for y in p.args:
if not y.is_Mul:
if is_sqrt(y):
a.append((S.One, y**2))
elif y.is_Atom:
a.append((y, S.One))
elif y.is_Pow and y.exp.is_integer:
a.append((y, S.One))
else:
raise NotImplementedError
continue
T, F = sift(y.args, is_sqrt, binary=True)
a.append((Mul(*F), Mul(*T)**2))
a.sort(key=lambda z: z[1])
if a[-1][1] is S.One:
# there are no surds
return p
surds = [z for y, z in a]
for i in range(len(surds)):
if surds[i] != 1:
break
g, b1, b2 = _split_gcd(*surds[i:])
a1 = []
a2 = []
for y, z in a:
if z in b1:
a1.append(y*z**S.Half)
else:
a2.append(y*z**S.Half)
p1 = Add(*a1)
p2 = Add(*a2)
p = _mexpand(p1**2) - _mexpand(p2**2)
return p
def _minimal_polynomial_sq(p, n, x):
"""
Returns the minimal polynomial for the ``nth-root`` of a sum of surds
or ``None`` if it fails.
Parameters
==========
p : sum of surds
n : positive integer
x : variable of the returned polynomial
Examples
========
>>> from sympy.polys.numberfields import _minimal_polynomial_sq
>>> from sympy import sqrt
>>> from sympy.abc import x
>>> q = 1 + sqrt(2) + sqrt(3)
>>> _minimal_polynomial_sq(q, 3, x)
x**12 - 4*x**9 - 4*x**6 + 16*x**3 - 8
"""
from sympy.simplify.simplify import _is_sum_surds
p = sympify(p)
n = sympify(n)
if not n.is_Integer or not n > 0 or not _is_sum_surds(p):
return None
pn = p**Rational(1, n)
# eliminate the square roots
p -= x
while 1:
p1 = _separate_sq(p)
if p1 is p:
p = p1.subs({x:x**n})
break
else:
p = p1
# _separate_sq eliminates field extensions in a minimal way, so that
# if n = 1 then `p = constant*(minimal_polynomial(p))`
# if n > 1 it contains the minimal polynomial as a factor.
if n == 1:
p1 = Poly(p)
if p.coeff(x**p1.degree(x)) < 0:
p = -p
p = p.primitive()[1]
return p
# by construction `p` has root `pn`
# the minimal polynomial is the factor vanishing in x = pn
factors = factor_list(p)[1]
result = _choose_factor(factors, x, pn)
return result
def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None):
"""
return the minimal polynomial for ``op(ex1, ex2)``
Parameters
==========
op : operation ``Add`` or ``Mul``
ex1, ex2 : expressions for the algebraic elements
x : indeterminate of the polynomials
dom: ground domain
mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None
Examples
========
>>> from sympy import sqrt, Add, Mul, QQ
>>> from sympy.polys.numberfields import _minpoly_op_algebraic_element
>>> from sympy.abc import x, y
>>> p1 = sqrt(sqrt(2) + 1)
>>> p2 = sqrt(sqrt(2) - 1)
>>> _minpoly_op_algebraic_element(Mul, p1, p2, x, QQ)
x - 1
>>> q1 = sqrt(y)
>>> q2 = 1 / y
>>> _minpoly_op_algebraic_element(Add, q1, q2, x, QQ.frac_field(y))
x**2*y**2 - 2*x*y - y**3 + 1
References
==========
.. [1] https://en.wikipedia.org/wiki/Resultant
.. [2] I.M. Isaacs, Proc. Amer. Math. Soc. 25 (1970), 638
"Degrees of sums in a separable field extension".
"""
y = Dummy(str(x))
if mp1 is None:
mp1 = _minpoly_compose(ex1, x, dom)
if mp2 is None:
mp2 = _minpoly_compose(ex2, y, dom)
else:
mp2 = mp2.subs({x: y})
if op is Add:
# mp1a = mp1.subs({x: x - y})
if dom == QQ:
R, X = ring('X', QQ)
p1 = R(dict_from_expr(mp1)[0])
p2 = R(dict_from_expr(mp2)[0])
else:
(p1, p2), _ = parallel_poly_from_expr((mp1, x - y), x, y)
r = p1.compose(p2)
mp1a = r.as_expr()
elif op is Mul:
mp1a = _muly(mp1, x, y)
else:
raise NotImplementedError('option not available')
if op is Mul or dom != QQ:
r = resultant(mp1a, mp2, gens=[y, x])
else:
r = rs_compose_add(p1, p2)
r = expr_from_dict(r.as_expr_dict(), x)
deg1 = degree(mp1, x)
deg2 = degree(mp2, y)
if op is Mul and deg1 == 1 or deg2 == 1:
# if deg1 = 1, then mp1 = x - a; mp1a = x - y - a;
# r = mp2(x - a), so that `r` is irreducible
return r
r = Poly(r, x, domain=dom)
_, factors = r.factor_list()
res = _choose_factor(factors, x, op(ex1, ex2), dom)
return res.as_expr()
def _invertx(p, x):
"""
Returns ``expand_mul(x**degree(p, x)*p.subs(x, 1/x))``
"""
p1 = poly_from_expr(p, x)[0]
n = degree(p1)
a = [c * x**(n - i) for (i,), c in p1.terms()]
return Add(*a)
def _muly(p, x, y):
"""
Returns ``_mexpand(y**deg*p.subs({x:x / y}))``
"""
p1 = poly_from_expr(p, x)[0]
n = degree(p1)
a = [c * x**i * y**(n - i) for (i,), c in p1.terms()]
return Add(*a)
def _minpoly_pow(ex, pw, x, dom, mp=None):
"""
Returns ``minpoly(ex**pw, x)``
Parameters
==========
ex : algebraic element
pw : rational number
x : indeterminate of the polynomial
dom: ground domain
mp : minimal polynomial of ``p``
Examples
========
>>> from sympy import sqrt, QQ, Rational
>>> from sympy.polys.numberfields import _minpoly_pow, minpoly
>>> from sympy.abc import x, y
>>> p = sqrt(1 + sqrt(2))
>>> _minpoly_pow(p, 2, x, QQ)
x**2 - 2*x - 1
>>> minpoly(p**2, x)
x**2 - 2*x - 1
>>> _minpoly_pow(y, Rational(1, 3), x, QQ.frac_field(y))
x**3 - y
>>> minpoly(y**Rational(1, 3), x)
x**3 - y
"""
pw = sympify(pw)
if not mp:
mp = _minpoly_compose(ex, x, dom)
if not pw.is_rational:
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
if pw < 0:
if mp == x:
raise ZeroDivisionError('%s is zero' % ex)
mp = _invertx(mp, x)
if pw == -1:
return mp
pw = -pw
ex = 1/ex
y = Dummy(str(x))
mp = mp.subs({x: y})
n, d = pw.as_numer_denom()
res = Poly(resultant(mp, x**d - y**n, gens=[y]), x, domain=dom)
_, factors = res.factor_list()
res = _choose_factor(factors, x, ex**pw, dom)
return res.as_expr()
def _minpoly_add(x, dom, *a):
"""
returns ``minpoly(Add(*a), dom, x)``
"""
mp = _minpoly_op_algebraic_element(Add, a[0], a[1], x, dom)
p = a[0] + a[1]
for px in a[2:]:
mp = _minpoly_op_algebraic_element(Add, p, px, x, dom, mp1=mp)
p = p + px
return mp
def _minpoly_mul(x, dom, *a):
"""
returns ``minpoly(Mul(*a), dom, x)``
"""
mp = _minpoly_op_algebraic_element(Mul, a[0], a[1], x, dom)
p = a[0] * a[1]
for px in a[2:]:
mp = _minpoly_op_algebraic_element(Mul, p, px, x, dom, mp1=mp)
p = p * px
return mp
def _minpoly_sin(ex, x):
"""
Returns the minimal polynomial of ``sin(ex)``
see http://mathworld.wolfram.com/TrigonometryAngles.html
"""
c, a = ex.args[0].as_coeff_Mul()
if a is pi:
if c.is_rational:
n = c.q
q = sympify(n)
if q.is_prime:
# for a = pi*p/q with q odd prime, using chebyshevt
# write sin(q*a) = mp(sin(a))*sin(a);
# the roots of mp(x) are sin(pi*p/q) for p = 1,..., q - 1
a = dup_chebyshevt(n, ZZ)
return Add(*[x**(n - i - 1)*a[i] for i in range(n)])
if c.p == 1:
if q == 9:
return 64*x**6 - 96*x**4 + 36*x**2 - 3
if n % 2 == 1:
# for a = pi*p/q with q odd, use
# sin(q*a) = 0 to see that the minimal polynomial must be
# a factor of dup_chebyshevt(n, ZZ)
a = dup_chebyshevt(n, ZZ)
a = [x**(n - i)*a[i] for i in range(n + 1)]
r = Add(*a)
_, factors = factor_list(r)
res = _choose_factor(factors, x, ex)
return res
expr = ((1 - cos(2*c*pi))/2)**S.Half
res = _minpoly_compose(expr, x, QQ)
return res
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
def _minpoly_cos(ex, x):
"""
Returns the minimal polynomial of ``cos(ex)``
see http://mathworld.wolfram.com/TrigonometryAngles.html
"""
from sympy import sqrt
c, a = ex.args[0].as_coeff_Mul()
if a is pi:
if c.is_rational:
if c.p == 1:
if c.q == 7:
return 8*x**3 - 4*x**2 - 4*x + 1
if c.q == 9:
return 8*x**3 - 6*x + 1
elif c.p == 2:
q = sympify(c.q)
if q.is_prime:
s = _minpoly_sin(ex, x)
return _mexpand(s.subs({x:sqrt((1 - x)/2)}))
# for a = pi*p/q, cos(q*a) =T_q(cos(a)) = (-1)**p
n = int(c.q)
a = dup_chebyshevt(n, ZZ)
a = [x**(n - i)*a[i] for i in range(n + 1)]
r = Add(*a) - (-1)**c.p
_, factors = factor_list(r)
res = _choose_factor(factors, x, ex)
return res
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
def _minpoly_tan(ex, x):
"""
Returns the minimal polynomial of ``tan(ex)``
see https://github.com/sympy/sympy/issues/21430
"""
c, a = ex.args[0].as_coeff_Mul()
if a is pi:
if c.is_rational:
c = c * 2
n = int(c.q)
a = n if c.p % 2 == 0 else 1
terms = []
for k in range((c.p+1)%2, n+1, 2):
terms.append(a*x**k)
a = -(a*(n-k-1)*(n-k)) // ((k+1)*(k+2))
r = Add(*terms)
_, factors = factor_list(r)
res = _choose_factor(factors, x, ex)
return res
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
def _minpoly_exp(ex, x):
"""
Returns the minimal polynomial of ``exp(ex)``
"""
c, a = ex.args[0].as_coeff_Mul()
q = sympify(c.q)
if a == I*pi:
if c.is_rational:
if c.p == 1 or c.p == -1:
if q == 3:
return x**2 - x + 1
if q == 4:
return x**4 + 1
if q == 6:
return x**4 - x**2 + 1
if q == 8:
return x**8 + 1
if q == 9:
return x**6 - x**3 + 1
if q == 10:
return x**8 - x**6 + x**4 - x**2 + 1
if q.is_prime:
s = 0
for i in range(q):
s += (-x)**i
return s
# x**(2*q) = product(factors)
factors = [cyclotomic_poly(i, x) for i in divisors(2*q)]
mp = _choose_factor(factors, x, ex)
return mp
else:
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
def _minpoly_rootof(ex, x):
"""
Returns the minimal polynomial of a ``CRootOf`` object.
"""
p = ex.expr
p = p.subs({ex.poly.gens[0]:x})
_, factors = factor_list(p, x)
result = _choose_factor(factors, x, ex)
return result
def _minpoly_compose(ex, x, dom):
"""
Computes the minimal polynomial of an algebraic element
using operations on minimal polynomials
Examples
========
>>> from sympy import minimal_polynomial, sqrt, Rational
>>> from sympy.abc import x, y
>>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=True)
x**2 - 2*x - 1
>>> minimal_polynomial(sqrt(y) + 1/y, x, compose=True)
x**2*y**2 - 2*x*y - y**3 + 1
"""
if ex.is_Rational:
return ex.q*x - ex.p
if ex is I:
_, factors = factor_list(x**2 + 1, x, domain=dom)
return x**2 + 1 if len(factors) == 1 else x - I
if ex is GoldenRatio:
_, factors = factor_list(x**2 - x - 1, x, domain=dom)
if len(factors) == 1:
return x**2 - x - 1
else:
return _choose_factor(factors, x, (1 + sqrt(5))/2, dom=dom)
if ex is TribonacciConstant:
_, factors = factor_list(x**3 - x**2 - x - 1, x, domain=dom)
if len(factors) == 1:
return x**3 - x**2 - x - 1
else:
fac = (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
return _choose_factor(factors, x, fac, dom=dom)
if hasattr(dom, 'symbols') and ex in dom.symbols:
return x - ex
if dom.is_QQ and _is_sum_surds(ex):
# eliminate the square roots
ex -= x
while 1:
ex1 = _separate_sq(ex)
if ex1 is ex:
return ex
else:
ex = ex1
if ex.is_Add:
res = _minpoly_add(x, dom, *ex.args)
elif ex.is_Mul:
f = Factors(ex).factors
r = sift(f.items(), lambda itx: itx[0].is_Rational and itx[1].is_Rational)
if r[True] and dom == QQ:
ex1 = Mul(*[bx**ex for bx, ex in r[False] + r[None]])
r1 = dict(r[True])
dens = [y.q for y in r1.values()]
lcmdens = reduce(lcm, dens, 1)
neg1 = S.NegativeOne
expn1 = r1.pop(neg1, S.Zero)
nums = [base**(y.p*lcmdens // y.q) for base, y in r1.items()]
ex2 = Mul(*nums)
mp1 = minimal_polynomial(ex1, x)
# use the fact that in SymPy canonicalization products of integers
# raised to rational powers are organized in relatively prime
# bases, and that in ``base**(n/d)`` a perfect power is
# simplified with the root
# Powers of -1 have to be treated separately to preserve sign.
mp2 = ex2.q*x**lcmdens - ex2.p*neg1**(expn1*lcmdens)
ex2 = neg1**expn1 * ex2**Rational(1, lcmdens)
res = _minpoly_op_algebraic_element(Mul, ex1, ex2, x, dom, mp1=mp1, mp2=mp2)
else:
res = _minpoly_mul(x, dom, *ex.args)
elif ex.is_Pow:
res = _minpoly_pow(ex.base, ex.exp, x, dom)
elif ex.__class__ is sin:
res = _minpoly_sin(ex, x)
elif ex.__class__ is cos:
res = _minpoly_cos(ex, x)
elif ex.__class__ is tan:
res = _minpoly_tan(ex, x)
elif ex.__class__ is exp:
res = _minpoly_exp(ex, x)
elif ex.__class__ is CRootOf:
res = _minpoly_rootof(ex, x)
else:
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
return res
@public
def minimal_polynomial(ex, x=None, compose=True, polys=False, domain=None):
"""
Computes the minimal polynomial of an algebraic element.
Parameters
==========
ex : Expr
Element or expression whose minimal polynomial is to be calculated.
x : Symbol, optional
Independent variable of the minimal polynomial
compose : boolean, optional (default=True)
Method to use for computing minimal polynomial. If ``compose=True``
(default) then ``_minpoly_compose`` is used, if ``compose=False`` then
groebner bases are used.
polys : boolean, optional (default=False)
If ``True`` returns a ``Poly`` object else an ``Expr`` object.
domain : Domain, optional
Ground domain
Notes
=====
By default ``compose=True``, the minimal polynomial of the subexpressions of ``ex``
are computed, then the arithmetic operations on them are performed using the resultant
and factorization.
If ``compose=False``, a bottom-up algorithm is used with ``groebner``.
The default algorithm stalls less frequently.
If no ground domain is given, it will be generated automatically from the expression.
Examples
========
>>> from sympy import minimal_polynomial, sqrt, solve, QQ
>>> from sympy.abc import x, y
>>> minimal_polynomial(sqrt(2), x)
x**2 - 2
>>> minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2)))
x - sqrt(2)
>>> minimal_polynomial(sqrt(2) + sqrt(3), x)
x**4 - 10*x**2 + 1
>>> minimal_polynomial(solve(x**3 + x + 3)[0], x)
x**3 + x + 3
>>> minimal_polynomial(sqrt(y), x)
x**2 - y
"""
from sympy.polys.polytools import degree
from sympy.polys.domains import FractionField
from sympy.core.basic import preorder_traversal
ex = sympify(ex)
if ex.is_number:
# not sure if it's always needed but try it for numbers (issue 8354)
ex = _mexpand(ex, recursive=True)
for expr in preorder_traversal(ex):
if expr.is_AlgebraicNumber:
compose = False
break
if x is not None:
x, cls = sympify(x), Poly
else:
x, cls = Dummy('x'), PurePoly
if not domain:
if ex.free_symbols:
domain = FractionField(QQ, list(ex.free_symbols))
else:
domain = QQ
if hasattr(domain, 'symbols') and x in domain.symbols:
raise GeneratorsError("the variable %s is an element of the ground "
"domain %s" % (x, domain))
if compose:
result = _minpoly_compose(ex, x, domain)
result = result.primitive()[1]
c = result.coeff(x**degree(result, x))
if c.is_negative:
result = expand_mul(-result)
return cls(result, x, field=True) if polys else result.collect(x)
if not domain.is_QQ:
raise NotImplementedError("groebner method only works for QQ")
result = _minpoly_groebner(ex, x, cls)
return cls(result, x, field=True) if polys else result.collect(x)
def _minpoly_groebner(ex, x, cls):
"""
Computes the minimal polynomial of an algebraic number
using Groebner bases
Examples
========
>>> from sympy import minimal_polynomial, sqrt, Rational
>>> from sympy.abc import x
>>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=False)
x**2 - 2*x - 1
"""
from sympy.polys.polytools import degree
from sympy.core.function import expand_multinomial
generator = numbered_symbols('a', cls=Dummy)
mapping, symbols = {}, {}
def update_mapping(ex, exp, base=None):
a = next(generator)
symbols[ex] = a
if base is not None:
mapping[ex] = a**exp + base
else:
mapping[ex] = exp.as_expr(a)
return a
def bottom_up_scan(ex):
if ex.is_Atom:
if ex is S.ImaginaryUnit:
if ex not in mapping:
return update_mapping(ex, 2, 1)
else:
return symbols[ex]
elif ex.is_Rational:
return ex
elif ex.is_Add:
return Add(*[ bottom_up_scan(g) for g in ex.args ])
elif ex.is_Mul:
return Mul(*[ bottom_up_scan(g) for g in ex.args ])
elif ex.is_Pow:
if ex.exp.is_Rational:
if ex.exp < 0:
minpoly_base = _minpoly_groebner(ex.base, x, cls)
inverse = invert(x, minpoly_base).as_expr()
base_inv = inverse.subs(x, ex.base).expand()
if ex.exp == -1:
return bottom_up_scan(base_inv)
else:
ex = base_inv**(-ex.exp)
if not ex.exp.is_Integer:
base, exp = (
ex.base**ex.exp.p).expand(), Rational(1, ex.exp.q)
else:
base, exp = ex.base, ex.exp
base = bottom_up_scan(base)
expr = base**exp
if expr not in mapping:
return update_mapping(expr, 1/exp, -base)
else:
return symbols[expr]
elif ex.is_AlgebraicNumber:
if ex.root not in mapping:
return update_mapping(ex.root, ex.minpoly)
else:
return symbols[ex.root]
raise NotAlgebraic("%s doesn't seem to be an algebraic number" % ex)
def simpler_inverse(ex):
"""
Returns True if it is more likely that the minimal polynomial
algorithm works better with the inverse
"""
if ex.is_Pow:
if (1/ex.exp).is_integer and ex.exp < 0:
if ex.base.is_Add:
return True
if ex.is_Mul:
hit = True
for p in ex.args:
if p.is_Add:
return False
if p.is_Pow:
if p.base.is_Add and p.exp > 0:
return False
if hit:
return True
return False
inverted = False
ex = expand_multinomial(ex)
if ex.is_AlgebraicNumber:
return ex.minpoly.as_expr(x)
elif ex.is_Rational:
result = ex.q*x - ex.p
else:
inverted = simpler_inverse(ex)
if inverted:
ex = ex**-1
res = None
if ex.is_Pow and (1/ex.exp).is_Integer:
n = 1/ex.exp
res = _minimal_polynomial_sq(ex.base, n, x)
elif _is_sum_surds(ex):
res = _minimal_polynomial_sq(ex, S.One, x)
if res is not None:
result = res
if res is None:
bus = bottom_up_scan(ex)
F = [x - bus] + list(mapping.values())
G = groebner(F, list(symbols.values()) + [x], order='lex')
_, factors = factor_list(G[-1])
# by construction G[-1] has root `ex`
result = _choose_factor(factors, x, ex)
if inverted:
result = _invertx(result, x)
if result.coeff(x**degree(result, x)) < 0:
result = expand_mul(-result)
return result
minpoly = minimal_polynomial
def _switch_domain(g, K):
# An algebraic relation f(a, b) = 0 over Q can also be written
# g(b) = 0 where g is in Q(a)[x] and h(a) = 0 where h is in Q(b)[x].
# This function transforms g into h where Q(b) = K.
frep = g.rep.inject()
hrep = frep.eject(K, front=True)
return g.new(hrep, g.gens[0])
def _linsolve(p):
# Compute root of linear polynomial.
c, d = p.rep.rep
return -d/c
@public
def primitive_element(extension, x=None, *, ex=False, polys=False):
"""Construct a common number field for all extensions. """
if not extension:
raise ValueError("can't compute primitive element for empty extension")
if x is not None:
x, cls = sympify(x), Poly
else:
x, cls = Dummy('x'), PurePoly
if not ex:
gen, coeffs = extension[0], [1]
g = minimal_polynomial(gen, x, polys=True)
for ext in extension[1:]:
_, factors = factor_list(g, extension=ext)
g = _choose_factor(factors, x, gen)
s, _, g = g.sqf_norm()
gen += s*ext
coeffs.append(s)
if not polys:
return g.as_expr(), coeffs
else:
return cls(g), coeffs
gen, coeffs = extension[0], [1]
f = minimal_polynomial(gen, x, polys=True)
K = QQ.algebraic_field((f, gen)) # incrementally constructed field
reps = [K.unit] # representations of extension elements in K
for ext in extension[1:]:
p = minimal_polynomial(ext, x, polys=True)
L = QQ.algebraic_field((p, ext))
_, factors = factor_list(f, domain=L)
f = _choose_factor(factors, x, gen)
s, g, f = f.sqf_norm()
gen += s*ext
coeffs.append(s)
K = QQ.algebraic_field((f, gen))
h = _switch_domain(g, K)
erep = _linsolve(h.gcd(p)) # ext as element of K
ogen = K.unit - s*erep # old gen as element of K
reps = [dup_eval(_.rep, ogen, K) for _ in reps] + [erep]
H = [_.rep for _ in reps]
if not polys:
return f.as_expr(), coeffs, H
else:
return f, coeffs, H
def is_isomorphism_possible(a, b):
"""Returns `True` if there is a chance for isomorphism. """
n = a.minpoly.degree()
m = b.minpoly.degree()
if m % n != 0:
return False
if n == m:
return True
da = a.minpoly.discriminant()
db = b.minpoly.discriminant()
i, k, half = 1, m//n, db//2
while True:
p = sieve[i]
P = p**k
if P > half:
break
if ((da % p) % 2) and not (db % P):
return False
i += 1
return True
def field_isomorphism_pslq(a, b):
"""Construct field isomorphism using PSLQ algorithm. """
if not a.root.is_real or not b.root.is_real:
raise NotImplementedError("PSLQ doesn't support complex coefficients")
f = a.minpoly
g = b.minpoly.replace(f.gen)
n, m, prev = 100, b.minpoly.degree(), None
for i in range(1, 5):
A = a.root.evalf(n)
B = b.root.evalf(n)
basis = [1, B] + [ B**i for i in range(2, m) ] + [A]
dps, mp.dps = mp.dps, n
coeffs = pslq(basis, maxcoeff=int(1e10), maxsteps=1000)
mp.dps = dps
if coeffs is None:
break
if coeffs != prev:
prev = coeffs
else:
break
coeffs = [S(c)/coeffs[-1] for c in coeffs[:-1]]
while not coeffs[-1]:
coeffs.pop()
coeffs = list(reversed(coeffs))
h = Poly(coeffs, f.gen, domain='QQ')
if f.compose(h).rem(g).is_zero:
d, approx = len(coeffs) - 1, 0
for i, coeff in enumerate(coeffs):
approx += coeff*B**(d - i)
if A*approx < 0:
return [ -c for c in coeffs ]
else:
return coeffs
elif f.compose(-h).rem(g).is_zero:
return [ -c for c in coeffs ]
else:
n *= 2
return None
def field_isomorphism_factor(a, b):
"""Construct field isomorphism via factorization. """
_, factors = factor_list(a.minpoly, extension=b)
for f, _ in factors:
if f.degree() == 1:
coeffs = f.rep.TC().to_sympy_list()
d, terms = len(coeffs) - 1, []
for i, coeff in enumerate(coeffs):
terms.append(coeff*b.root**(d - i))
root = Add(*terms)
if (a.root - root).evalf(chop=True) == 0:
return coeffs
if (a.root + root).evalf(chop=True) == 0:
return [-c for c in coeffs]
return None
@public
def field_isomorphism(a, b, *, fast=True):
"""Construct an isomorphism between two number fields. """
a, b = sympify(a), sympify(b)
if not a.is_AlgebraicNumber:
a = AlgebraicNumber(a)
if not b.is_AlgebraicNumber:
b = AlgebraicNumber(b)
if a == b:
return a.coeffs()
n = a.minpoly.degree()
m = b.minpoly.degree()
if n == 1:
return [a.root]
if m % n != 0:
return None
if fast:
try:
result = field_isomorphism_pslq(a, b)
if result is not None:
return result
except NotImplementedError:
pass
return field_isomorphism_factor(a, b)
@public
def to_number_field(extension, theta=None, *, gen=None):
"""Express `extension` in the field generated by `theta`. """
if hasattr(extension, '__iter__'):
extension = list(extension)
else:
extension = [extension]
if len(extension) == 1 and type(extension[0]) is tuple:
return AlgebraicNumber(extension[0])
minpoly, coeffs = primitive_element(extension, gen, polys=True)
root = sum([ coeff*ext for coeff, ext in zip(coeffs, extension) ])
if theta is None:
return AlgebraicNumber((minpoly, root))
else:
theta = sympify(theta)
if not theta.is_AlgebraicNumber:
theta = AlgebraicNumber(theta, gen=gen)
coeffs = field_isomorphism(root, theta)
if coeffs is not None:
return AlgebraicNumber(theta, coeffs)
else:
raise IsomorphismFailed(
"%s is not in a subfield of %s" % (root, theta.root))
class IntervalPrinter(MpmathPrinter, LambdaPrinter):
"""Use ``lambda`` printer but print numbers as ``mpi`` intervals. """
def _print_Integer(self, expr):
return "mpi('%s')" % super(PythonCodePrinter, self)._print_Integer(expr)
def _print_Rational(self, expr):
return "mpi('%s')" % super(PythonCodePrinter, self)._print_Rational(expr)
def _print_Half(self, expr):
return "mpi('%s')" % super(PythonCodePrinter, self)._print_Rational(expr)
def _print_Pow(self, expr):
return super(MpmathPrinter, self)._print_Pow(expr, rational=True)
@public
def isolate(alg, eps=None, fast=False):
"""Give a rational isolating interval for an algebraic number. """
alg = sympify(alg)
if alg.is_Rational:
return (alg, alg)
elif not alg.is_real:
raise NotImplementedError(
"complex algebraic numbers are not supported")
func = lambdify((), alg, modules="mpmath", printer=IntervalPrinter())
poly = minpoly(alg, polys=True)
intervals = poly.intervals(sqf=True)
dps, done = mp.dps, False
try:
while not done:
alg = func()
for a, b in intervals:
if a <= alg.a and alg.b <= b:
done = True
break
else:
mp.dps *= 2
finally:
mp.dps = dps
if eps is not None:
a, b = poly.refine_root(a, b, eps=eps, fast=fast)
return (a, b)
|
922b82b72a440ef7210dc1db162b5cfc361f12dae39e76b5fe01db7cc8d30d58 | """Tools for constructing domains for expressions. """
from sympy.core import sympify
from sympy.core.compatibility import ordered
from sympy.core.evalf import pure_complex
from sympy.polys.domains import ZZ, QQ, ZZ_I, QQ_I, EX
from sympy.polys.domains.complexfield import ComplexField
from sympy.polys.domains.realfield import RealField
from sympy.polys.polyoptions import build_options
from sympy.polys.polyutils import parallel_dict_from_basic
from sympy.utilities import public
def _construct_simple(coeffs, opt):
"""Handle simple domains, e.g.: ZZ, QQ, RR and algebraic domains. """
rationals = floats = complexes = algebraics = False
float_numbers = []
if opt.extension is True:
is_algebraic = lambda coeff: coeff.is_number and coeff.is_algebraic
else:
is_algebraic = lambda coeff: False
for coeff in coeffs:
if coeff.is_Rational:
if not coeff.is_Integer:
rationals = True
elif coeff.is_Float:
if algebraics:
# there are both reals and algebraics -> EX
return False
else:
floats = True
float_numbers.append(coeff)
else:
is_complex = pure_complex(coeff)
if is_complex:
complexes = True
x, y = is_complex
if x.is_Rational and y.is_Rational:
if not (x.is_Integer and y.is_Integer):
rationals = True
continue
else:
floats = True
if x.is_Float:
float_numbers.append(x)
if y.is_Float:
float_numbers.append(y)
elif is_algebraic(coeff):
if floats:
# there are both algebraics and reals -> EX
return False
algebraics = True
else:
# this is a composite domain, e.g. ZZ[X], EX
return None
# Use the maximum precision of all coefficients for the RR or CC
# precision
max_prec = max(c._prec for c in float_numbers) if float_numbers else 53
if algebraics:
domain, result = _construct_algebraic(coeffs, opt)
else:
if floats and complexes:
domain = ComplexField(prec=max_prec)
elif floats:
domain = RealField(prec=max_prec)
elif rationals or opt.field:
domain = QQ_I if complexes else QQ
else:
domain = ZZ_I if complexes else ZZ
result = [domain.from_sympy(coeff) for coeff in coeffs]
return domain, result
def _construct_algebraic(coeffs, opt):
"""We know that coefficients are algebraic so construct the extension. """
from sympy.polys.numberfields import primitive_element
exts = set()
def build_trees(args):
trees = []
for a in args:
if a.is_Rational:
tree = ('Q', QQ.from_sympy(a))
elif a.is_Add:
tree = ('+', build_trees(a.args))
elif a.is_Mul:
tree = ('*', build_trees(a.args))
else:
tree = ('e', a)
exts.add(a)
trees.append(tree)
return trees
trees = build_trees(coeffs)
exts = list(ordered(exts))
g, span, H = primitive_element(exts, ex=True, polys=True)
root = sum([ s*ext for s, ext in zip(span, exts) ])
domain, g = QQ.algebraic_field((g, root)), g.rep.rep
exts_dom = [domain.dtype.from_list(h, g, QQ) for h in H]
exts_map = dict(zip(exts, exts_dom))
def convert_tree(tree):
op, args = tree
if op == 'Q':
return domain.dtype.from_list([args], g, QQ)
elif op == '+':
return sum((convert_tree(a) for a in args), domain.zero)
elif op == '*':
# return prod(convert(a) for a in args)
t = convert_tree(args[0])
for a in args[1:]:
t *= convert_tree(a)
return t
elif op == 'e':
return exts_map[args]
else:
raise RuntimeError
result = [convert_tree(tree) for tree in trees]
return domain, result
def _construct_composite(coeffs, opt):
"""Handle composite domains, e.g.: ZZ[X], QQ[X], ZZ(X), QQ(X). """
numers, denoms = [], []
for coeff in coeffs:
numer, denom = coeff.as_numer_denom()
numers.append(numer)
denoms.append(denom)
polys, gens = parallel_dict_from_basic(numers + denoms) # XXX: sorting
if not gens:
return None
if opt.composite is None:
if any(gen.is_number and gen.is_algebraic for gen in gens):
return None # generators are number-like so lets better use EX
all_symbols = set()
for gen in gens:
symbols = gen.free_symbols
if all_symbols & symbols:
return None # there could be algebraic relations between generators
else:
all_symbols |= symbols
n = len(gens)
k = len(polys)//2
numers = polys[:k]
denoms = polys[k:]
if opt.field:
fractions = True
else:
fractions, zeros = False, (0,)*n
for denom in denoms:
if len(denom) > 1 or zeros not in denom:
fractions = True
break
coeffs = set()
if not fractions:
for numer, denom in zip(numers, denoms):
denom = denom[zeros]
for monom, coeff in numer.items():
coeff /= denom
coeffs.add(coeff)
numer[monom] = coeff
else:
for numer, denom in zip(numers, denoms):
coeffs.update(list(numer.values()))
coeffs.update(list(denom.values()))
rationals = floats = complexes = False
float_numbers = []
for coeff in coeffs:
if coeff.is_Rational:
if not coeff.is_Integer:
rationals = True
elif coeff.is_Float:
floats = True
float_numbers.append(coeff)
else:
is_complex = pure_complex(coeff)
if is_complex is not None:
complexes = True
x, y = is_complex
if x.is_Rational and y.is_Rational:
if not (x.is_Integer and y.is_Integer):
rationals = True
else:
floats = True
if x.is_Float:
float_numbers.append(x)
if y.is_Float:
float_numbers.append(y)
max_prec = max(c._prec for c in float_numbers) if float_numbers else 53
if floats and complexes:
ground = ComplexField(prec=max_prec)
elif floats:
ground = RealField(prec=max_prec)
elif complexes:
if rationals:
ground = QQ_I
else:
ground = ZZ_I
elif rationals:
ground = QQ
else:
ground = ZZ
result = []
if not fractions:
domain = ground.poly_ring(*gens)
for numer in numers:
for monom, coeff in numer.items():
numer[monom] = ground.from_sympy(coeff)
result.append(domain(numer))
else:
domain = ground.frac_field(*gens)
for numer, denom in zip(numers, denoms):
for monom, coeff in numer.items():
numer[monom] = ground.from_sympy(coeff)
for monom, coeff in denom.items():
denom[monom] = ground.from_sympy(coeff)
result.append(domain((numer, denom)))
return domain, result
def _construct_expression(coeffs, opt):
"""The last resort case, i.e. use the expression domain. """
domain, result = EX, []
for coeff in coeffs:
result.append(domain.from_sympy(coeff))
return domain, result
@public
def construct_domain(obj, **args):
"""Construct a minimal domain for a list of expressions.
Explanation
===========
Given a list of normal SymPy expressions (of type :py:class:`~.Expr`)
``construct_domain`` will find a minimal :py:class:`~.Domain` that can
represent those expressions. The expressions will be converted to elements
of the domain and both the domain and the domain elements are returned.
Parameters
==========
obj: list or dict
The expressions to build a domain for.
**args: keyword arguments
Options that affect the choice of domain.
Returns
=======
(K, elements): Domain and list of domain elements
The domain K that can represent the expressions and the list or dict
of domain elements representing the same expressions as elements of K.
Examples
========
Given a list of :py:class:`~.Integer` ``construct_domain`` will return the
domain :ref:`ZZ` and a list of integers as elements of :ref:`ZZ`.
>>> from sympy import construct_domain, S
>>> expressions = [S(2), S(3), S(4)]
>>> K, elements = construct_domain(expressions)
>>> K
ZZ
>>> elements
[2, 3, 4]
>>> type(elements[0]) # doctest: +SKIP
<class 'int'>
>>> type(expressions[0])
<class 'sympy.core.numbers.Integer'>
If there are any :py:class:`~.Rational` then :ref:`QQ` is returned
instead.
>>> construct_domain([S(1)/2, S(3)/4])
(QQ, [1/2, 3/4])
If there are symbols then a polynomial ring :ref:`K[x]` is returned.
>>> from sympy import symbols
>>> x, y = symbols('x, y')
>>> construct_domain([2*x + 1, S(3)/4])
(QQ[x], [2*x + 1, 3/4])
>>> construct_domain([2*x + 1, y])
(ZZ[x,y], [2*x + 1, y])
If any symbols appear with negative powers then a rational function field
:ref:`K(x)` will be returned.
>>> construct_domain([y/x, x/(1 - y)])
(ZZ(x,y), [y/x, -x/(y - 1)])
Irrational algebraic numbers will result in the :ref:`EX` domain by
default. The keyword argument ``extension=True`` leads to the construction
of an algebraic number field :ref:`QQ(a)`.
>>> from sympy import sqrt
>>> construct_domain([sqrt(2)])
(EX, [EX(sqrt(2))])
>>> construct_domain([sqrt(2)], extension=True) # doctest: +SKIP
(QQ<sqrt(2)>, [ANP([1, 0], [1, 0, -2], QQ)])
See also
========
Domain
Expr
"""
opt = build_options(args)
if hasattr(obj, '__iter__'):
if isinstance(obj, dict):
if not obj:
monoms, coeffs = [], []
else:
monoms, coeffs = list(zip(*list(obj.items())))
else:
coeffs = obj
else:
coeffs = [obj]
coeffs = list(map(sympify, coeffs))
result = _construct_simple(coeffs, opt)
if result is not None:
if result is not False:
domain, coeffs = result
else:
domain, coeffs = _construct_expression(coeffs, opt)
else:
if opt.composite is False:
result = None
else:
result = _construct_composite(coeffs, opt)
if result is not None:
domain, coeffs = result
else:
domain, coeffs = _construct_expression(coeffs, opt)
if hasattr(obj, '__iter__'):
if isinstance(obj, dict):
return domain, dict(list(zip(monoms, coeffs)))
else:
return domain, coeffs
else:
return domain, coeffs[0]
|
32f620da98bad582e9105d6a30400e5a6b18b1e72ce2ead0c2495fd9587a3d52 | """
This module implements Holonomic Functions and
various operations on them.
"""
from sympy import (Symbol, S, Dummy, Order, rf, I,
solve, limit, Float, nsimplify, gamma)
from sympy.core.compatibility import ordered
from sympy.core.numbers import NaN, Infinity, NegativeInfinity
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import binomial, factorial
from sympy.functions.elementary.exponential import exp_polar, exp
from sympy.functions.special.hyper import hyper, meijerg
from sympy.integrals import meijerint
from sympy.matrices import Matrix
from sympy.polys.rings import PolyElement
from sympy.polys.fields import FracElement
from sympy.polys.domains import QQ, RR
from sympy.polys.polyclasses import DMF
from sympy.polys.polyroots import roots
from sympy.polys.polytools import Poly
from sympy.polys.matrices import DomainMatrix
from sympy.printing import sstr
from sympy.simplify.hyperexpand import hyperexpand
from .recurrence import HolonomicSequence, RecurrenceOperator, RecurrenceOperators
from .holonomicerrors import (NotPowerSeriesError, NotHyperSeriesError,
SingularityError, NotHolonomicError)
def _find_nonzero_solution(r, homosys):
ones = lambda shape: DomainMatrix.ones(shape, r.domain)
particular, nullspace = r._solve(homosys)
nullity = nullspace.shape[0]
nullpart = ones((1, nullity)) * nullspace
sol = (particular + nullpart).transpose()
return sol
def DifferentialOperators(base, generator):
r"""
This function is used to create annihilators using ``Dx``.
Explanation
===========
Returns an Algebra of Differential Operators also called Weyl Algebra
and the operator for differentiation i.e. the ``Dx`` operator.
Parameters
==========
base:
Base polynomial ring for the algebra.
The base polynomial ring is the ring of polynomials in :math:`x` that
will appear as coefficients in the operators.
generator:
Generator of the algebra which can
be either a noncommutative ``Symbol`` or a string. e.g. "Dx" or "D".
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.abc import x
>>> from sympy.holonomic.holonomic import DifferentialOperators
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
>>> R
Univariate Differential Operator Algebra in intermediate Dx over the base ring ZZ[x]
>>> Dx*x
(1) + (x)*Dx
"""
ring = DifferentialOperatorAlgebra(base, generator)
return (ring, ring.derivative_operator)
class DifferentialOperatorAlgebra:
r"""
An Ore Algebra is a set of noncommutative polynomials in the
intermediate ``Dx`` and coefficients in a base polynomial ring :math:`A`.
It follows the commutation rule:
.. math ::
Dxa = \sigma(a)Dx + \delta(a)
for :math:`a \subset A`.
Where :math:`\sigma: A \Rightarrow A` is an endomorphism and :math:`\delta: A \rightarrow A`
is a skew-derivation i.e. :math:`\delta(ab) = \delta(a) b + \sigma(a) \delta(b)`.
If one takes the sigma as identity map and delta as the standard derivation
then it becomes the algebra of Differential Operators also called
a Weyl Algebra i.e. an algebra whose elements are Differential Operators.
This class represents a Weyl Algebra and serves as the parent ring for
Differential Operators.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy import symbols
>>> from sympy.holonomic.holonomic import DifferentialOperators
>>> x = symbols('x')
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
>>> R
Univariate Differential Operator Algebra in intermediate Dx over the base ring
ZZ[x]
See Also
========
DifferentialOperator
"""
def __init__(self, base, generator):
# the base polynomial ring for the algebra
self.base = base
# the operator representing differentiation i.e. `Dx`
self.derivative_operator = DifferentialOperator(
[base.zero, base.one], self)
if generator is None:
self.gen_symbol = Symbol('Dx', commutative=False)
else:
if isinstance(generator, str):
self.gen_symbol = Symbol(generator, commutative=False)
elif isinstance(generator, Symbol):
self.gen_symbol = generator
def __str__(self):
string = 'Univariate Differential Operator Algebra in intermediate '\
+ sstr(self.gen_symbol) + ' over the base ring ' + \
(self.base).__str__()
return string
__repr__ = __str__
def __eq__(self, other):
if self.base == other.base and self.gen_symbol == other.gen_symbol:
return True
else:
return False
class DifferentialOperator:
"""
Differential Operators are elements of Weyl Algebra. The Operators
are defined by a list of polynomials in the base ring and the
parent ring of the Operator i.e. the algebra it belongs to.
Explanation
===========
Takes a list of polynomials for each power of ``Dx`` and the
parent ring which must be an instance of DifferentialOperatorAlgebra.
A Differential Operator can be created easily using
the operator ``Dx``. See examples below.
Examples
========
>>> from sympy.holonomic.holonomic import DifferentialOperator, DifferentialOperators
>>> from sympy.polys.domains import ZZ
>>> from sympy import symbols
>>> x = symbols('x')
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
>>> DifferentialOperator([0, 1, x**2], R)
(1)*Dx + (x**2)*Dx**2
>>> (x*Dx*x + 1 - Dx**2)**2
(2*x**2 + 2*x + 1) + (4*x**3 + 2*x**2 - 4)*Dx + (x**4 - 6*x - 2)*Dx**2 + (-2*x**2)*Dx**3 + (1)*Dx**4
See Also
========
DifferentialOperatorAlgebra
"""
_op_priority = 20
def __init__(self, list_of_poly, parent):
"""
Parameters
==========
list_of_poly:
List of polynomials belonging to the base ring of the algebra.
parent:
Parent algebra of the operator.
"""
# the parent ring for this operator
# must be an DifferentialOperatorAlgebra object
self.parent = parent
base = self.parent.base
self.x = base.gens[0] if isinstance(base.gens[0], Symbol) else base.gens[0][0]
# sequence of polynomials in x for each power of Dx
# the list should not have trailing zeroes
# represents the operator
# convert the expressions into ring elements using from_sympy
for i, j in enumerate(list_of_poly):
if not isinstance(j, base.dtype):
list_of_poly[i] = base.from_sympy(sympify(j))
else:
list_of_poly[i] = base.from_sympy(base.to_sympy(j))
self.listofpoly = list_of_poly
# highest power of `Dx`
self.order = len(self.listofpoly) - 1
def __mul__(self, other):
"""
Multiplies two DifferentialOperator and returns another
DifferentialOperator instance using the commutation rule
Dx*a = a*Dx + a'
"""
listofself = self.listofpoly
if not isinstance(other, DifferentialOperator):
if not isinstance(other, self.parent.base.dtype):
listofother = [self.parent.base.from_sympy(sympify(other))]
else:
listofother = [other]
else:
listofother = other.listofpoly
# multiplies a polynomial `b` with a list of polynomials
def _mul_dmp_diffop(b, listofother):
if isinstance(listofother, list):
sol = []
for i in listofother:
sol.append(i * b)
return sol
else:
return [b * listofother]
sol = _mul_dmp_diffop(listofself[0], listofother)
# compute Dx^i * b
def _mul_Dxi_b(b):
sol1 = [self.parent.base.zero]
sol2 = []
if isinstance(b, list):
for i in b:
sol1.append(i)
sol2.append(i.diff())
else:
sol1.append(self.parent.base.from_sympy(b))
sol2.append(self.parent.base.from_sympy(b).diff())
return _add_lists(sol1, sol2)
for i in range(1, len(listofself)):
# find Dx^i * b in ith iteration
listofother = _mul_Dxi_b(listofother)
# solution = solution + listofself[i] * (Dx^i * b)
sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother))
return DifferentialOperator(sol, self.parent)
def __rmul__(self, other):
if not isinstance(other, DifferentialOperator):
if not isinstance(other, self.parent.base.dtype):
other = (self.parent.base).from_sympy(sympify(other))
sol = []
for j in self.listofpoly:
sol.append(other * j)
return DifferentialOperator(sol, self.parent)
def __add__(self, other):
if isinstance(other, DifferentialOperator):
sol = _add_lists(self.listofpoly, other.listofpoly)
return DifferentialOperator(sol, self.parent)
else:
list_self = self.listofpoly
if not isinstance(other, self.parent.base.dtype):
list_other = [((self.parent).base).from_sympy(sympify(other))]
else:
list_other = [other]
sol = []
sol.append(list_self[0] + list_other[0])
sol += list_self[1:]
return DifferentialOperator(sol, self.parent)
__radd__ = __add__
def __sub__(self, other):
return self + (-1) * other
def __rsub__(self, other):
return (-1) * self + other
def __neg__(self):
return -1 * self
def __truediv__(self, other):
return self * (S.One / other)
def __pow__(self, n):
if n == 1:
return self
if n == 0:
return DifferentialOperator([self.parent.base.one], self.parent)
# if self is `Dx`
if self.listofpoly == self.parent.derivative_operator.listofpoly:
sol = []
for i in range(0, n):
sol.append(self.parent.base.zero)
sol.append(self.parent.base.one)
return DifferentialOperator(sol, self.parent)
# the general case
else:
if n % 2 == 1:
powreduce = self**(n - 1)
return powreduce * self
elif n % 2 == 0:
powreduce = self**(n / 2)
return powreduce * powreduce
def __str__(self):
listofpoly = self.listofpoly
print_str = ''
for i, j in enumerate(listofpoly):
if j == self.parent.base.zero:
continue
if i == 0:
print_str += '(' + sstr(j) + ')'
continue
if print_str:
print_str += ' + '
if i == 1:
print_str += '(' + sstr(j) + ')*%s' %(self.parent.gen_symbol)
continue
print_str += '(' + sstr(j) + ')' + '*%s**' %(self.parent.gen_symbol) + sstr(i)
return print_str
__repr__ = __str__
def __eq__(self, other):
if isinstance(other, DifferentialOperator):
if self.listofpoly == other.listofpoly and self.parent == other.parent:
return True
else:
return False
else:
if self.listofpoly[0] == other:
for i in self.listofpoly[1:]:
if i is not self.parent.base.zero:
return False
return True
else:
return False
def is_singular(self, x0):
"""
Checks if the differential equation is singular at x0.
"""
base = self.parent.base
return x0 in roots(base.to_sympy(self.listofpoly[-1]), self.x)
class HolonomicFunction:
r"""
A Holonomic Function is a solution to a linear homogeneous ordinary
differential equation with polynomial coefficients. This differential
equation can also be represented by an annihilator i.e. a Differential
Operator ``L`` such that :math:`L.f = 0`. For uniqueness of these functions,
initial conditions can also be provided along with the annihilator.
Explanation
===========
Holonomic functions have closure properties and thus forms a ring.
Given two Holonomic Functions f and g, their sum, product,
integral and derivative is also a Holonomic Function.
For ordinary points initial condition should be a vector of values of
the derivatives i.e. :math:`[y(x_0), y'(x_0), y''(x_0) ... ]`.
For regular singular points initial conditions can also be provided in this
format:
:math:`{s0: [C_0, C_1, ...], s1: [C^1_0, C^1_1, ...], ...}`
where s0, s1, ... are the roots of indicial equation and vectors
:math:`[C_0, C_1, ...], [C^0_0, C^0_1, ...], ...` are the corresponding initial
terms of the associated power series. See Examples below.
Examples
========
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
>>> from sympy.polys.domains import QQ
>>> from sympy import symbols, S
>>> x = symbols('x')
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
>>> p = HolonomicFunction(Dx - 1, x, 0, [1]) # e^x
>>> q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) # sin(x)
>>> p + q # annihilator of e^x + sin(x)
HolonomicFunction((-1) + (1)*Dx + (-1)*Dx**2 + (1)*Dx**3, x, 0, [1, 2, 1])
>>> p * q # annihilator of e^x * sin(x)
HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x, 0, [0, 1])
An example of initial conditions for regular singular points,
the indicial equation has only one root `1/2`.
>>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]})
HolonomicFunction((-1/2) + (x)*Dx, x, 0, {1/2: [1]})
>>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_expr()
sqrt(x)
To plot a Holonomic Function, one can use `.evalf()` for numerical
computation. Here's an example on `sin(x)**2/x` using numpy and matplotlib.
>>> import sympy.holonomic # doctest: +SKIP
>>> from sympy import var, sin # doctest: +SKIP
>>> import matplotlib.pyplot as plt # doctest: +SKIP
>>> import numpy as np # doctest: +SKIP
>>> var("x") # doctest: +SKIP
>>> r = np.linspace(1, 5, 100) # doctest: +SKIP
>>> y = sympy.holonomic.expr_to_holonomic(sin(x)**2/x, x0=1).evalf(r) # doctest: +SKIP
>>> plt.plot(r, y, label="holonomic function") # doctest: +SKIP
>>> plt.show() # doctest: +SKIP
"""
_op_priority = 20
def __init__(self, annihilator, x, x0=0, y0=None):
"""
Parameters
==========
annihilator:
Annihilator of the Holonomic Function, represented by a
`DifferentialOperator` object.
x:
Variable of the function.
x0:
The point at which initial conditions are stored.
Generally an integer.
y0:
The initial condition. The proper format for the initial condition
is described in class docstring. To make the function unique,
length of the vector `y0` should be equal to or greater than the
order of differential equation.
"""
# initial condition
self.y0 = y0
# the point for initial conditions, default is zero.
self.x0 = x0
# differential operator L such that L.f = 0
self.annihilator = annihilator
self.x = x
def __str__(self):
if self._have_init_cond():
str_sol = 'HolonomicFunction(%s, %s, %s, %s)' % (str(self.annihilator),\
sstr(self.x), sstr(self.x0), sstr(self.y0))
else:
str_sol = 'HolonomicFunction(%s, %s)' % (str(self.annihilator),\
sstr(self.x))
return str_sol
__repr__ = __str__
def unify(self, other):
"""
Unifies the base polynomial ring of a given two Holonomic
Functions.
"""
R1 = self.annihilator.parent.base
R2 = other.annihilator.parent.base
dom1 = R1.dom
dom2 = R2.dom
if R1 == R2:
return (self, other)
R = (dom1.unify(dom2)).old_poly_ring(self.x)
newparent, _ = DifferentialOperators(R, str(self.annihilator.parent.gen_symbol))
sol1 = [R1.to_sympy(i) for i in self.annihilator.listofpoly]
sol2 = [R2.to_sympy(i) for i in other.annihilator.listofpoly]
sol1 = DifferentialOperator(sol1, newparent)
sol2 = DifferentialOperator(sol2, newparent)
sol1 = HolonomicFunction(sol1, self.x, self.x0, self.y0)
sol2 = HolonomicFunction(sol2, other.x, other.x0, other.y0)
return (sol1, sol2)
def is_singularics(self):
"""
Returns True if the function have singular initial condition
in the dictionary format.
Returns False if the function have ordinary initial condition
in the list format.
Returns None for all other cases.
"""
if isinstance(self.y0, dict):
return True
elif isinstance(self.y0, list):
return False
def _have_init_cond(self):
"""
Checks if the function have initial condition.
"""
return bool(self.y0)
def _singularics_to_ord(self):
"""
Converts a singular initial condition to ordinary if possible.
"""
a = list(self.y0)[0]
b = self.y0[a]
if len(self.y0) == 1 and a == int(a) and a > 0:
y0 = []
a = int(a)
for i in range(a):
y0.append(S.Zero)
y0 += [j * factorial(a + i) for i, j in enumerate(b)]
return HolonomicFunction(self.annihilator, self.x, self.x0, y0)
def __add__(self, other):
# if the ground domains are different
if self.annihilator.parent.base != other.annihilator.parent.base:
a, b = self.unify(other)
return a + b
deg1 = self.annihilator.order
deg2 = other.annihilator.order
dim = max(deg1, deg2)
R = self.annihilator.parent.base
K = R.get_field()
rowsself = [self.annihilator]
rowsother = [other.annihilator]
gen = self.annihilator.parent.derivative_operator
# constructing annihilators up to order dim
for i in range(dim - deg1):
diff1 = (gen * rowsself[-1])
rowsself.append(diff1)
for i in range(dim - deg2):
diff2 = (gen * rowsother[-1])
rowsother.append(diff2)
row = rowsself + rowsother
# constructing the matrix of the ansatz
r = []
for expr in row:
p = []
for i in range(dim + 1):
if i >= len(expr.listofpoly):
p.append(K.zero)
else:
p.append(K.new(expr.listofpoly[i].rep))
r.append(p)
# solving the linear system using gauss jordan solver
r = DomainMatrix(r, (len(row), dim+1), K).transpose()
homosys = DomainMatrix.zeros((dim+1, 1), K)
sol = _find_nonzero_solution(r, homosys)
# if a solution is not obtained then increasing the order by 1 in each
# iteration
while sol.is_zero_matrix:
dim += 1
diff1 = (gen * rowsself[-1])
rowsself.append(diff1)
diff2 = (gen * rowsother[-1])
rowsother.append(diff2)
row = rowsself + rowsother
r = []
for expr in row:
p = []
for i in range(dim + 1):
if i >= len(expr.listofpoly):
p.append(K.zero)
else:
p.append(K.new(expr.listofpoly[i].rep))
r.append(p)
# solving the linear system using gauss jordan solver
r = DomainMatrix(r, (len(row), dim+1), K).transpose()
homosys = DomainMatrix.zeros((dim+1, 1), K)
sol = _find_nonzero_solution(r, homosys)
# taking only the coefficients needed to multiply with `self`
# can be also be done the other way by taking R.H.S and multiplying with
# `other`
sol = sol.flat()[:dim + 1 - deg1]
sol1 = _normalize(sol, self.annihilator.parent)
# annihilator of the solution
sol = sol1 * (self.annihilator)
sol = _normalize(sol.listofpoly, self.annihilator.parent, negative=False)
if not (self._have_init_cond() and other._have_init_cond()):
return HolonomicFunction(sol, self.x)
# both the functions have ordinary initial conditions
if self.is_singularics() == False and other.is_singularics() == False:
# directly add the corresponding value
if self.x0 == other.x0:
# try to extended the initial conditions
# using the annihilator
y1 = _extend_y0(self, sol.order)
y2 = _extend_y0(other, sol.order)
y0 = [a + b for a, b in zip(y1, y2)]
return HolonomicFunction(sol, self.x, self.x0, y0)
else:
# change the intiial conditions to a same point
selfat0 = self.annihilator.is_singular(0)
otherat0 = other.annihilator.is_singular(0)
if self.x0 == 0 and not selfat0 and not otherat0:
return self + other.change_ics(0)
elif other.x0 == 0 and not selfat0 and not otherat0:
return self.change_ics(0) + other
else:
selfatx0 = self.annihilator.is_singular(self.x0)
otheratx0 = other.annihilator.is_singular(self.x0)
if not selfatx0 and not otheratx0:
return self + other.change_ics(self.x0)
else:
return self.change_ics(other.x0) + other
if self.x0 != other.x0:
return HolonomicFunction(sol, self.x)
# if the functions have singular_ics
y1 = None
y2 = None
if self.is_singularics() == False and other.is_singularics() == True:
# convert the ordinary initial condition to singular.
_y0 = [j / factorial(i) for i, j in enumerate(self.y0)]
y1 = {S.Zero: _y0}
y2 = other.y0
elif self.is_singularics() == True and other.is_singularics() == False:
_y0 = [j / factorial(i) for i, j in enumerate(other.y0)]
y1 = self.y0
y2 = {S.Zero: _y0}
elif self.is_singularics() == True and other.is_singularics() == True:
y1 = self.y0
y2 = other.y0
# computing singular initial condition for the result
# taking union of the series terms of both functions
y0 = {}
for i in y1:
# add corresponding initial terms if the power
# on `x` is same
if i in y2:
y0[i] = [a + b for a, b in zip(y1[i], y2[i])]
else:
y0[i] = y1[i]
for i in y2:
if not i in y1:
y0[i] = y2[i]
return HolonomicFunction(sol, self.x, self.x0, y0)
def integrate(self, limits, initcond=False):
"""
Integrates the given holonomic function.
Examples
========
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
>>> from sympy.polys.domains import QQ
>>> from sympy import symbols
>>> x = symbols('x')
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
>>> HolonomicFunction(Dx - 1, x, 0, [1]).integrate((x, 0, x)) # e^x - 1
HolonomicFunction((-1)*Dx + (1)*Dx**2, x, 0, [0, 1])
>>> HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).integrate((x, 0, x))
HolonomicFunction((1)*Dx + (1)*Dx**3, x, 0, [0, 1, 0])
"""
# to get the annihilator, just multiply by Dx from right
D = self.annihilator.parent.derivative_operator
# if the function have initial conditions of the series format
if self.is_singularics() == True:
r = self._singularics_to_ord()
if r:
return r.integrate(limits, initcond=initcond)
# computing singular initial condition for the function
# produced after integration.
y0 = {}
for i in self.y0:
c = self.y0[i]
c2 = []
for j in range(len(c)):
if c[j] == 0:
c2.append(S.Zero)
# if power on `x` is -1, the integration becomes log(x)
# TODO: Implement this case
elif i + j + 1 == 0:
raise NotImplementedError("logarithmic terms in the series are not supported")
else:
c2.append(c[j] / S(i + j + 1))
y0[i + 1] = c2
if hasattr(limits, "__iter__"):
raise NotImplementedError("Definite integration for singular initial conditions")
return HolonomicFunction(self.annihilator * D, self.x, self.x0, y0)
# if no initial conditions are available for the function
if not self._have_init_cond():
if initcond:
return HolonomicFunction(self.annihilator * D, self.x, self.x0, [S.Zero])
return HolonomicFunction(self.annihilator * D, self.x)
# definite integral
# initial conditions for the answer will be stored at point `a`,
# where `a` is the lower limit of the integrand
if hasattr(limits, "__iter__"):
if len(limits) == 3 and limits[0] == self.x:
x0 = self.x0
a = limits[1]
b = limits[2]
definite = True
else:
definite = False
y0 = [S.Zero]
y0 += self.y0
indefinite_integral = HolonomicFunction(self.annihilator * D, self.x, self.x0, y0)
if not definite:
return indefinite_integral
# use evalf to get the values at `a`
if x0 != a:
try:
indefinite_expr = indefinite_integral.to_expr()
except (NotHyperSeriesError, NotPowerSeriesError):
indefinite_expr = None
if indefinite_expr:
lower = indefinite_expr.subs(self.x, a)
if isinstance(lower, NaN):
lower = indefinite_expr.limit(self.x, a)
else:
lower = indefinite_integral.evalf(a)
if b == self.x:
y0[0] = y0[0] - lower
return HolonomicFunction(self.annihilator * D, self.x, x0, y0)
elif S(b).is_Number:
if indefinite_expr:
upper = indefinite_expr.subs(self.x, b)
if isinstance(upper, NaN):
upper = indefinite_expr.limit(self.x, b)
else:
upper = indefinite_integral.evalf(b)
return upper - lower
# if the upper limit is `x`, the answer will be a function
if b == self.x:
return HolonomicFunction(self.annihilator * D, self.x, a, y0)
# if the upper limits is a Number, a numerical value will be returned
elif S(b).is_Number:
try:
s = HolonomicFunction(self.annihilator * D, self.x, a,\
y0).to_expr()
indefinite = s.subs(self.x, b)
if not isinstance(indefinite, NaN):
return indefinite
else:
return s.limit(self.x, b)
except (NotHyperSeriesError, NotPowerSeriesError):
return HolonomicFunction(self.annihilator * D, self.x, a, y0).evalf(b)
return HolonomicFunction(self.annihilator * D, self.x)
def diff(self, *args, **kwargs):
r"""
Differentiation of the given Holonomic function.
Examples
========
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
>>> from sympy.polys.domains import ZZ
>>> from sympy import symbols
>>> x = symbols('x')
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
>>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).diff().to_expr()
cos(x)
>>> HolonomicFunction(Dx - 2, x, 0, [1]).diff().to_expr()
2*exp(2*x)
See Also
========
.integrate()
"""
kwargs.setdefault('evaluate', True)
if args:
if args[0] != self.x:
return S.Zero
elif len(args) == 2:
sol = self
for i in range(args[1]):
sol = sol.diff(args[0])
return sol
ann = self.annihilator
# if the function is constant.
if ann.listofpoly[0] == ann.parent.base.zero and ann.order == 1:
return S.Zero
# if the coefficient of y in the differential equation is zero.
# a shifting is done to compute the answer in this case.
elif ann.listofpoly[0] == ann.parent.base.zero:
sol = DifferentialOperator(ann.listofpoly[1:], ann.parent)
if self._have_init_cond():
# if ordinary initial condition
if self.is_singularics() == False:
return HolonomicFunction(sol, self.x, self.x0, self.y0[1:])
# TODO: support for singular initial condition
return HolonomicFunction(sol, self.x)
else:
return HolonomicFunction(sol, self.x)
# the general algorithm
R = ann.parent.base
K = R.get_field()
seq_dmf = [K.new(i.rep) for i in ann.listofpoly]
# -y = a1*y'/a0 + a2*y''/a0 ... + an*y^n/a0
rhs = [i / seq_dmf[0] for i in seq_dmf[1:]]
rhs.insert(0, K.zero)
# differentiate both lhs and rhs
sol = _derivate_diff_eq(rhs)
# add the term y' in lhs to rhs
sol = _add_lists(sol, [K.zero, K.one])
sol = _normalize(sol[1:], self.annihilator.parent, negative=False)
if not self._have_init_cond() or self.is_singularics() == True:
return HolonomicFunction(sol, self.x)
y0 = _extend_y0(self, sol.order + 1)[1:]
return HolonomicFunction(sol, self.x, self.x0, y0)
def __eq__(self, other):
if self.annihilator == other.annihilator:
if self.x == other.x:
if self._have_init_cond() and other._have_init_cond():
if self.x0 == other.x0 and self.y0 == other.y0:
return True
else:
return False
else:
return True
else:
return False
else:
return False
def __mul__(self, other):
ann_self = self.annihilator
if not isinstance(other, HolonomicFunction):
other = sympify(other)
if other.has(self.x):
raise NotImplementedError(" Can't multiply a HolonomicFunction and expressions/functions.")
if not self._have_init_cond():
return self
else:
y0 = _extend_y0(self, ann_self.order)
y1 = []
for j in y0:
y1.append((Poly.new(j, self.x) * other).rep)
return HolonomicFunction(ann_self, self.x, self.x0, y1)
if self.annihilator.parent.base != other.annihilator.parent.base:
a, b = self.unify(other)
return a * b
ann_other = other.annihilator
list_self = []
list_other = []
a = ann_self.order
b = ann_other.order
R = ann_self.parent.base
K = R.get_field()
for j in ann_self.listofpoly:
list_self.append(K.new(j.rep))
for j in ann_other.listofpoly:
list_other.append(K.new(j.rep))
# will be used to reduce the degree
self_red = [-list_self[i] / list_self[a] for i in range(a)]
other_red = [-list_other[i] / list_other[b] for i in range(b)]
# coeff_mull[i][j] is the coefficient of Dx^i(f).Dx^j(g)
coeff_mul = [[K.zero for i in range(b + 1)] for j in range(a + 1)]
coeff_mul[0][0] = K.one
# making the ansatz
lin_sys_elements = [[coeff_mul[i][j] for i in range(a) for j in range(b)]]
lin_sys = DomainMatrix(lin_sys_elements, (1, a*b), K).transpose()
homo_sys = DomainMatrix.zeros((a*b, 1), K)
sol = _find_nonzero_solution(lin_sys, homo_sys)
# until a non trivial solution is found
while sol.is_zero_matrix:
# updating the coefficients Dx^i(f).Dx^j(g) for next degree
for i in range(a - 1, -1, -1):
for j in range(b - 1, -1, -1):
coeff_mul[i][j + 1] += coeff_mul[i][j]
coeff_mul[i + 1][j] += coeff_mul[i][j]
if isinstance(coeff_mul[i][j], K.dtype):
coeff_mul[i][j] = DMFdiff(coeff_mul[i][j])
else:
coeff_mul[i][j] = coeff_mul[i][j].diff(self.x)
# reduce the terms to lower power using annihilators of f, g
for i in range(a + 1):
if not coeff_mul[i][b].is_zero:
for j in range(b):
coeff_mul[i][j] += other_red[j] * \
coeff_mul[i][b]
coeff_mul[i][b] = K.zero
# not d2 + 1, as that is already covered in previous loop
for j in range(b):
if not coeff_mul[a][j] == 0:
for i in range(a):
coeff_mul[i][j] += self_red[i] * \
coeff_mul[a][j]
coeff_mul[a][j] = K.zero
lin_sys_elements.append([coeff_mul[i][j] for i in range(a) for j in range(b)])
lin_sys = DomainMatrix(lin_sys_elements, (len(lin_sys_elements), a*b), K).transpose()
sol = _find_nonzero_solution(lin_sys, homo_sys)
sol_ann = _normalize(sol.flat(), self.annihilator.parent, negative=False)
if not (self._have_init_cond() and other._have_init_cond()):
return HolonomicFunction(sol_ann, self.x)
if self.is_singularics() == False and other.is_singularics() == False:
# if both the conditions are at same point
if self.x0 == other.x0:
# try to find more initial conditions
y0_self = _extend_y0(self, sol_ann.order)
y0_other = _extend_y0(other, sol_ann.order)
# h(x0) = f(x0) * g(x0)
y0 = [y0_self[0] * y0_other[0]]
# coefficient of Dx^j(f)*Dx^i(g) in Dx^i(fg)
for i in range(1, min(len(y0_self), len(y0_other))):
coeff = [[0 for i in range(i + 1)] for j in range(i + 1)]
for j in range(i + 1):
for k in range(i + 1):
if j + k == i:
coeff[j][k] = binomial(i, j)
sol = 0
for j in range(i + 1):
for k in range(i + 1):
sol += coeff[j][k]* y0_self[j] * y0_other[k]
y0.append(sol)
return HolonomicFunction(sol_ann, self.x, self.x0, y0)
# if the points are different, consider one
else:
selfat0 = self.annihilator.is_singular(0)
otherat0 = other.annihilator.is_singular(0)
if self.x0 == 0 and not selfat0 and not otherat0:
return self * other.change_ics(0)
elif other.x0 == 0 and not selfat0 and not otherat0:
return self.change_ics(0) * other
else:
selfatx0 = self.annihilator.is_singular(self.x0)
otheratx0 = other.annihilator.is_singular(self.x0)
if not selfatx0 and not otheratx0:
return self * other.change_ics(self.x0)
else:
return self.change_ics(other.x0) * other
if self.x0 != other.x0:
return HolonomicFunction(sol_ann, self.x)
# if the functions have singular_ics
y1 = None
y2 = None
if self.is_singularics() == False and other.is_singularics() == True:
_y0 = [j / factorial(i) for i, j in enumerate(self.y0)]
y1 = {S.Zero: _y0}
y2 = other.y0
elif self.is_singularics() == True and other.is_singularics() == False:
_y0 = [j / factorial(i) for i, j in enumerate(other.y0)]
y1 = self.y0
y2 = {S.Zero: _y0}
elif self.is_singularics() == True and other.is_singularics() == True:
y1 = self.y0
y2 = other.y0
y0 = {}
# multiply every possible pair of the series terms
for i in y1:
for j in y2:
k = min(len(y1[i]), len(y2[j]))
c = []
for a in range(k):
s = S.Zero
for b in range(a + 1):
s += y1[i][b] * y2[j][a - b]
c.append(s)
if not i + j in y0:
y0[i + j] = c
else:
y0[i + j] = [a + b for a, b in zip(c, y0[i + j])]
return HolonomicFunction(sol_ann, self.x, self.x0, y0)
__rmul__ = __mul__
def __sub__(self, other):
return self + other * -1
def __rsub__(self, other):
return self * -1 + other
def __neg__(self):
return -1 * self
def __truediv__(self, other):
return self * (S.One / other)
def __pow__(self, n):
if self.annihilator.order <= 1:
ann = self.annihilator
parent = ann.parent
if self.y0 is None:
y0 = None
else:
y0 = [list(self.y0)[0] ** n]
p0 = ann.listofpoly[0]
p1 = ann.listofpoly[1]
p0 = (Poly.new(p0, self.x) * n).rep
sol = [parent.base.to_sympy(i) for i in [p0, p1]]
dd = DifferentialOperator(sol, parent)
return HolonomicFunction(dd, self.x, self.x0, y0)
if n < 0:
raise NotHolonomicError("Negative Power on a Holonomic Function")
if n == 0:
Dx = self.annihilator.parent.derivative_operator
return HolonomicFunction(Dx, self.x, S.Zero, [S.One])
if n == 1:
return self
else:
if n % 2 == 1:
powreduce = self**(n - 1)
return powreduce * self
elif n % 2 == 0:
powreduce = self**(n / 2)
return powreduce * powreduce
def degree(self):
"""
Returns the highest power of `x` in the annihilator.
"""
sol = [i.degree() for i in self.annihilator.listofpoly]
return max(sol)
def composition(self, expr, *args, **kwargs):
"""
Returns function after composition of a holonomic
function with an algebraic function. The method can't compute
initial conditions for the result by itself, so they can be also be
provided.
Examples
========
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
>>> from sympy.polys.domains import QQ
>>> from sympy import symbols
>>> x = symbols('x')
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
>>> HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2)
HolonomicFunction((-2*x) + (1)*Dx, x, 0, [1])
>>> HolonomicFunction(Dx**2 + 1, x).composition(x**2 - 1, 1, [1, 0])
HolonomicFunction((4*x**3) + (-1)*Dx + (x)*Dx**2, x, 1, [1, 0])
See Also
========
from_hyper()
"""
R = self.annihilator.parent
a = self.annihilator.order
diff = expr.diff(self.x)
listofpoly = self.annihilator.listofpoly
for i, j in enumerate(listofpoly):
if isinstance(j, self.annihilator.parent.base.dtype):
listofpoly[i] = self.annihilator.parent.base.to_sympy(j)
r = listofpoly[a].subs({self.x:expr})
subs = [-listofpoly[i].subs({self.x:expr}) / r for i in range (a)]
coeffs = [S.Zero for i in range(a)] # coeffs[i] == coeff of (D^i f)(a) in D^k (f(a))
coeffs[0] = S.One
system = [coeffs]
homogeneous = Matrix([[S.Zero for i in range(a)]]).transpose()
sol = S.Zero
while True:
coeffs_next = [p.diff(self.x) for p in coeffs]
for i in range(a - 1):
coeffs_next[i + 1] += (coeffs[i] * diff)
for i in range(a):
coeffs_next[i] += (coeffs[-1] * subs[i] * diff)
coeffs = coeffs_next
# check for linear relations
system.append(coeffs)
sol, taus = (Matrix(system).transpose()
).gauss_jordan_solve(homogeneous)
if sol.is_zero_matrix is not True:
break
tau = list(taus)[0]
sol = sol.subs(tau, 1)
sol = _normalize(sol[0:], R, negative=False)
# if initial conditions are given for the resulting function
if args:
return HolonomicFunction(sol, self.x, args[0], args[1])
return HolonomicFunction(sol, self.x)
def to_sequence(self, lb=True):
r"""
Finds recurrence relation for the coefficients in the series expansion
of the function about :math:`x_0`, where :math:`x_0` is the point at
which the initial condition is stored.
Explanation
===========
If the point :math:`x_0` is ordinary, solution of the form :math:`[(R, n_0)]`
is returned. Where :math:`R` is the recurrence relation and :math:`n_0` is the
smallest ``n`` for which the recurrence holds true.
If the point :math:`x_0` is regular singular, a list of solutions in
the format :math:`(R, p, n_0)` is returned, i.e. `[(R, p, n_0), ... ]`.
Each tuple in this vector represents a recurrence relation :math:`R`
associated with a root of the indicial equation ``p``. Conditions of
a different format can also be provided in this case, see the
docstring of HolonomicFunction class.
If it's not possible to numerically compute a initial condition,
it is returned as a symbol :math:`C_j`, denoting the coefficient of
:math:`(x - x_0)^j` in the power series about :math:`x_0`.
Examples
========
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
>>> from sympy.polys.domains import QQ
>>> from sympy import symbols, S
>>> x = symbols('x')
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
>>> HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence()
[(HolonomicSequence((-1) + (n + 1)Sn, n), u(0) = 1, 0)]
>>> HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_sequence()
[(HolonomicSequence((n**2) + (n**2 + n)Sn, n), u(0) = 0, u(1) = 1, u(2) = -1/2, 2)]
>>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_sequence()
[(HolonomicSequence((n), n), u(0) = 1, 1/2, 1)]
See Also
========
HolonomicFunction.series()
References
==========
.. [1] https://hal.inria.fr/inria-00070025/document
.. [2] http://www.risc.jku.at/publications/download/risc_2244/DIPLFORM.pdf
"""
if self.x0 != 0:
return self.shift_x(self.x0).to_sequence()
# check whether a power series exists if the point is singular
if self.annihilator.is_singular(self.x0):
return self._frobenius(lb=lb)
dict1 = {}
n = Symbol('n', integer=True)
dom = self.annihilator.parent.base.dom
R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn')
# substituting each term of the form `x^k Dx^j` in the
# annihilator, according to the formula below:
# x^k Dx^j = Sum(rf(n + 1 - k, j) * a(n + j - k) * x^n, (n, k, oo))
# for explanation see [2].
for i, j in enumerate(self.annihilator.listofpoly):
listofdmp = j.all_coeffs()
degree = len(listofdmp) - 1
for k in range(degree + 1):
coeff = listofdmp[degree - k]
if coeff == 0:
continue
if (i - k, k) in dict1:
dict1[(i - k, k)] += (dom.to_sympy(coeff) * rf(n - k + 1, i))
else:
dict1[(i - k, k)] = (dom.to_sympy(coeff) * rf(n - k + 1, i))
sol = []
keylist = [i[0] for i in dict1]
lower = min(keylist)
upper = max(keylist)
degree = self.degree()
# the recurrence relation holds for all values of
# n greater than smallest_n, i.e. n >= smallest_n
smallest_n = lower + degree
dummys = {}
eqs = []
unknowns = []
# an appropriate shift of the recurrence
for j in range(lower, upper + 1):
if j in keylist:
temp = S.Zero
for k in dict1.keys():
if k[0] == j:
temp += dict1[k].subs(n, n - lower)
sol.append(temp)
else:
sol.append(S.Zero)
# the recurrence relation
sol = RecurrenceOperator(sol, R)
# computing the initial conditions for recurrence
order = sol.order
all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z')
all_roots = all_roots.keys()
if all_roots:
max_root = max(all_roots) + 1
smallest_n = max(max_root, smallest_n)
order += smallest_n
y0 = _extend_y0(self, order)
u0 = []
# u(n) = y^n(0)/factorial(n)
for i, j in enumerate(y0):
u0.append(j / factorial(i))
# if sufficient conditions can't be computed then
# try to use the series method i.e.
# equate the coefficients of x^k in the equation formed by
# substituting the series in differential equation, to zero.
if len(u0) < order:
for i in range(degree):
eq = S.Zero
for j in dict1:
if i + j[0] < 0:
dummys[i + j[0]] = S.Zero
elif i + j[0] < len(u0):
dummys[i + j[0]] = u0[i + j[0]]
elif not i + j[0] in dummys:
dummys[i + j[0]] = Symbol('C_%s' %(i + j[0]))
unknowns.append(dummys[i + j[0]])
if j[1] <= i:
eq += dict1[j].subs(n, i) * dummys[i + j[0]]
eqs.append(eq)
# solve the system of equations formed
soleqs = solve(eqs, *unknowns)
if isinstance(soleqs, dict):
for i in range(len(u0), order):
if i not in dummys:
dummys[i] = Symbol('C_%s' %i)
if dummys[i] in soleqs:
u0.append(soleqs[dummys[i]])
else:
u0.append(dummys[i])
if lb:
return [(HolonomicSequence(sol, u0), smallest_n)]
return [HolonomicSequence(sol, u0)]
for i in range(len(u0), order):
if i not in dummys:
dummys[i] = Symbol('C_%s' %i)
s = False
for j in soleqs:
if dummys[i] in j:
u0.append(j[dummys[i]])
s = True
if not s:
u0.append(dummys[i])
if lb:
return [(HolonomicSequence(sol, u0), smallest_n)]
return [HolonomicSequence(sol, u0)]
def _frobenius(self, lb=True):
# compute the roots of indicial equation
indicialroots = self._indicial()
reals = []
compl = []
for i in ordered(indicialroots.keys()):
if i.is_real:
reals.extend([i] * indicialroots[i])
else:
a, b = i.as_real_imag()
compl.extend([(i, a, b)] * indicialroots[i])
# sort the roots for a fixed ordering of solution
compl.sort(key=lambda x : x[1])
compl.sort(key=lambda x : x[2])
reals.sort()
# grouping the roots, roots differ by an integer are put in the same group.
grp = []
for i in reals:
intdiff = False
if len(grp) == 0:
grp.append([i])
continue
for j in grp:
if int(j[0] - i) == j[0] - i:
j.append(i)
intdiff = True
break
if not intdiff:
grp.append([i])
# True if none of the roots differ by an integer i.e.
# each element in group have only one member
independent = True if all(len(i) == 1 for i in grp) else False
allpos = all(i >= 0 for i in reals)
allint = all(int(i) == i for i in reals)
# if initial conditions are provided
# then use them.
if self.is_singularics() == True:
rootstoconsider = []
for i in ordered(self.y0.keys()):
for j in ordered(indicialroots.keys()):
if j == i:
rootstoconsider.append(i)
elif allpos and allint:
rootstoconsider = [min(reals)]
elif independent:
rootstoconsider = [i[0] for i in grp] + [j[0] for j in compl]
elif not allint:
rootstoconsider = []
for i in reals:
if not int(i) == i:
rootstoconsider.append(i)
elif not allpos:
if not self._have_init_cond() or S(self.y0[0]).is_finite == False:
rootstoconsider = [min(reals)]
else:
posroots = []
for i in reals:
if i >= 0:
posroots.append(i)
rootstoconsider = [min(posroots)]
n = Symbol('n', integer=True)
dom = self.annihilator.parent.base.dom
R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn')
finalsol = []
char = ord('C')
for p in rootstoconsider:
dict1 = {}
for i, j in enumerate(self.annihilator.listofpoly):
listofdmp = j.all_coeffs()
degree = len(listofdmp) - 1
for k in range(degree + 1):
coeff = listofdmp[degree - k]
if coeff == 0:
continue
if (i - k, k - i) in dict1:
dict1[(i - k, k - i)] += (dom.to_sympy(coeff) * rf(n - k + 1 + p, i))
else:
dict1[(i - k, k - i)] = (dom.to_sympy(coeff) * rf(n - k + 1 + p, i))
sol = []
keylist = [i[0] for i in dict1]
lower = min(keylist)
upper = max(keylist)
degree = max([i[1] for i in dict1])
degree2 = min([i[1] for i in dict1])
smallest_n = lower + degree
dummys = {}
eqs = []
unknowns = []
for j in range(lower, upper + 1):
if j in keylist:
temp = S.Zero
for k in dict1.keys():
if k[0] == j:
temp += dict1[k].subs(n, n - lower)
sol.append(temp)
else:
sol.append(S.Zero)
# the recurrence relation
sol = RecurrenceOperator(sol, R)
# computing the initial conditions for recurrence
order = sol.order
all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z')
all_roots = all_roots.keys()
if all_roots:
max_root = max(all_roots) + 1
smallest_n = max(max_root, smallest_n)
order += smallest_n
u0 = []
if self.is_singularics() == True:
u0 = self.y0[p]
elif self.is_singularics() == False and p >= 0 and int(p) == p and len(rootstoconsider) == 1:
y0 = _extend_y0(self, order + int(p))
# u(n) = y^n(0)/factorial(n)
if len(y0) > int(p):
for i in range(int(p), len(y0)):
u0.append(y0[i] / factorial(i))
if len(u0) < order:
for i in range(degree2, degree):
eq = S.Zero
for j in dict1:
if i + j[0] < 0:
dummys[i + j[0]] = S.Zero
elif i + j[0] < len(u0):
dummys[i + j[0]] = u0[i + j[0]]
elif not i + j[0] in dummys:
letter = chr(char) + '_%s' %(i + j[0])
dummys[i + j[0]] = Symbol(letter)
unknowns.append(dummys[i + j[0]])
if j[1] <= i:
eq += dict1[j].subs(n, i) * dummys[i + j[0]]
eqs.append(eq)
# solve the system of equations formed
soleqs = solve(eqs, *unknowns)
if isinstance(soleqs, dict):
for i in range(len(u0), order):
if i not in dummys:
letter = chr(char) + '_%s' %i
dummys[i] = Symbol(letter)
if dummys[i] in soleqs:
u0.append(soleqs[dummys[i]])
else:
u0.append(dummys[i])
if lb:
finalsol.append((HolonomicSequence(sol, u0), p, smallest_n))
continue
else:
finalsol.append((HolonomicSequence(sol, u0), p))
continue
for i in range(len(u0), order):
if i not in dummys:
letter = chr(char) + '_%s' %i
dummys[i] = Symbol(letter)
s = False
for j in soleqs:
if dummys[i] in j:
u0.append(j[dummys[i]])
s = True
if not s:
u0.append(dummys[i])
if lb:
finalsol.append((HolonomicSequence(sol, u0), p, smallest_n))
else:
finalsol.append((HolonomicSequence(sol, u0), p))
char += 1
return finalsol
def series(self, n=6, coefficient=False, order=True, _recur=None):
r"""
Finds the power series expansion of given holonomic function about :math:`x_0`.
Explanation
===========
A list of series might be returned if :math:`x_0` is a regular point with
multiple roots of the indicial equation.
Examples
========
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
>>> from sympy.polys.domains import QQ
>>> from sympy import symbols
>>> x = symbols('x')
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
>>> HolonomicFunction(Dx - 1, x, 0, [1]).series() # e^x
1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6)
>>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).series(n=8) # sin(x)
x - x**3/6 + x**5/120 - x**7/5040 + O(x**8)
See Also
========
HolonomicFunction.to_sequence()
"""
if _recur is None:
recurrence = self.to_sequence()
else:
recurrence = _recur
if isinstance(recurrence, tuple) and len(recurrence) == 2:
recurrence = recurrence[0]
constantpower = 0
elif isinstance(recurrence, tuple) and len(recurrence) == 3:
constantpower = recurrence[1]
recurrence = recurrence[0]
elif len(recurrence) == 1 and len(recurrence[0]) == 2:
recurrence = recurrence[0][0]
constantpower = 0
elif len(recurrence) == 1 and len(recurrence[0]) == 3:
constantpower = recurrence[0][1]
recurrence = recurrence[0][0]
else:
sol = []
for i in recurrence:
sol.append(self.series(_recur=i))
return sol
n = n - int(constantpower)
l = len(recurrence.u0) - 1
k = recurrence.recurrence.order
x = self.x
x0 = self.x0
seq_dmp = recurrence.recurrence.listofpoly
R = recurrence.recurrence.parent.base
K = R.get_field()
seq = []
for i, j in enumerate(seq_dmp):
seq.append(K.new(j.rep))
sub = [-seq[i] / seq[k] for i in range(k)]
sol = [i for i in recurrence.u0]
if l + 1 >= n:
pass
else:
# use the initial conditions to find the next term
for i in range(l + 1 - k, n - k):
coeff = S.Zero
for j in range(k):
if i + j >= 0:
coeff += DMFsubs(sub[j], i) * sol[i + j]
sol.append(coeff)
if coefficient:
return sol
ser = S.Zero
for i, j in enumerate(sol):
ser += x**(i + constantpower) * j
if order:
ser += Order(x**(n + int(constantpower)), x)
if x0 != 0:
return ser.subs(x, x - x0)
return ser
def _indicial(self):
"""
Computes roots of the Indicial equation.
"""
if self.x0 != 0:
return self.shift_x(self.x0)._indicial()
list_coeff = self.annihilator.listofpoly
R = self.annihilator.parent.base
x = self.x
s = R.zero
y = R.one
def _pole_degree(poly):
root_all = roots(R.to_sympy(poly), x, filter='Z')
if 0 in root_all.keys():
return root_all[0]
else:
return 0
degree = [j.degree() for j in list_coeff]
degree = max(degree)
inf = 10 * (max(1, degree) + max(1, self.annihilator.order))
deg = lambda q: inf if q.is_zero else _pole_degree(q)
b = deg(list_coeff[0])
for j in range(1, len(list_coeff)):
b = min(b, deg(list_coeff[j]) - j)
for i, j in enumerate(list_coeff):
listofdmp = j.all_coeffs()
degree = len(listofdmp) - 1
if - i - b <= 0 and degree - i - b >= 0:
s = s + listofdmp[degree - i - b] * y
y *= x - i
return roots(R.to_sympy(s), x)
def evalf(self, points, method='RK4', h=0.05, derivatives=False):
r"""
Finds numerical value of a holonomic function using numerical methods.
(RK4 by default). A set of points (real or complex) must be provided
which will be the path for the numerical integration.
Explanation
===========
The path should be given as a list :math:`[x_1, x_2, ... x_n]`. The numerical
values will be computed at each point in this order
:math:`x_1 --> x_2 --> x_3 ... --> x_n`.
Returns values of the function at :math:`x_1, x_2, ... x_n` in a list.
Examples
========
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
>>> from sympy.polys.domains import QQ
>>> from sympy import symbols
>>> x = symbols('x')
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
A straight line on the real axis from (0 to 1)
>>> r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
Runge-Kutta 4th order on e^x from 0.1 to 1.
Exact solution at 1 is 2.71828182845905
>>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r)
[1.10517083333333, 1.22140257085069, 1.34985849706254, 1.49182424008069,
1.64872063859684, 1.82211796209193, 2.01375162659678, 2.22553956329232,
2.45960141378007, 2.71827974413517]
Euler's method for the same
>>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r, method='Euler')
[1.1, 1.21, 1.331, 1.4641, 1.61051, 1.771561, 1.9487171, 2.14358881,
2.357947691, 2.5937424601]
One can also observe that the value obtained using Runge-Kutta 4th order
is much more accurate than Euler's method.
"""
from sympy.holonomic.numerical import _evalf
lp = False
# if a point `b` is given instead of a mesh
if not hasattr(points, "__iter__"):
lp = True
b = S(points)
if self.x0 == b:
return _evalf(self, [b], method=method, derivatives=derivatives)[-1]
if not b.is_Number:
raise NotImplementedError
a = self.x0
if a > b:
h = -h
n = int((b - a) / h)
points = [a + h]
for i in range(n - 1):
points.append(points[-1] + h)
for i in roots(self.annihilator.parent.base.to_sympy(self.annihilator.listofpoly[-1]), self.x):
if i == self.x0 or i in points:
raise SingularityError(self, i)
if lp:
return _evalf(self, points, method=method, derivatives=derivatives)[-1]
return _evalf(self, points, method=method, derivatives=derivatives)
def change_x(self, z):
"""
Changes only the variable of Holonomic Function, for internal
purposes. For composition use HolonomicFunction.composition()
"""
dom = self.annihilator.parent.base.dom
R = dom.old_poly_ring(z)
parent, _ = DifferentialOperators(R, 'Dx')
sol = []
for j in self.annihilator.listofpoly:
sol.append(R(j.rep))
sol = DifferentialOperator(sol, parent)
return HolonomicFunction(sol, z, self.x0, self.y0)
def shift_x(self, a):
"""
Substitute `x + a` for `x`.
"""
x = self.x
listaftershift = self.annihilator.listofpoly
base = self.annihilator.parent.base
sol = [base.from_sympy(base.to_sympy(i).subs(x, x + a)) for i in listaftershift]
sol = DifferentialOperator(sol, self.annihilator.parent)
x0 = self.x0 - a
if not self._have_init_cond():
return HolonomicFunction(sol, x)
return HolonomicFunction(sol, x, x0, self.y0)
def to_hyper(self, as_list=False, _recur=None):
r"""
Returns a hypergeometric function (or linear combination of them)
representing the given holonomic function.
Explanation
===========
Returns an answer of the form:
`a_1 \cdot x^{b_1} \cdot{hyper()} + a_2 \cdot x^{b_2} \cdot{hyper()} ...`
This is very useful as one can now use ``hyperexpand`` to find the
symbolic expressions/functions.
Examples
========
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
>>> from sympy.polys.domains import ZZ
>>> from sympy import symbols
>>> x = symbols('x')
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
>>> # sin(x)
>>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_hyper()
x*hyper((), (3/2,), -x**2/4)
>>> # exp(x)
>>> HolonomicFunction(Dx - 1, x, 0, [1]).to_hyper()
hyper((), (), x)
See Also
========
from_hyper, from_meijerg
"""
if _recur is None:
recurrence = self.to_sequence()
else:
recurrence = _recur
if isinstance(recurrence, tuple) and len(recurrence) == 2:
smallest_n = recurrence[1]
recurrence = recurrence[0]
constantpower = 0
elif isinstance(recurrence, tuple) and len(recurrence) == 3:
smallest_n = recurrence[2]
constantpower = recurrence[1]
recurrence = recurrence[0]
elif len(recurrence) == 1 and len(recurrence[0]) == 2:
smallest_n = recurrence[0][1]
recurrence = recurrence[0][0]
constantpower = 0
elif len(recurrence) == 1 and len(recurrence[0]) == 3:
smallest_n = recurrence[0][2]
constantpower = recurrence[0][1]
recurrence = recurrence[0][0]
else:
sol = self.to_hyper(as_list=as_list, _recur=recurrence[0])
for i in recurrence[1:]:
sol += self.to_hyper(as_list=as_list, _recur=i)
return sol
u0 = recurrence.u0
r = recurrence.recurrence
x = self.x
x0 = self.x0
# order of the recurrence relation
m = r.order
# when no recurrence exists, and the power series have finite terms
if m == 0:
nonzeroterms = roots(r.parent.base.to_sympy(r.listofpoly[0]), recurrence.n, filter='R')
sol = S.Zero
for j, i in enumerate(nonzeroterms):
if i < 0 or int(i) != i:
continue
i = int(i)
if i < len(u0):
if isinstance(u0[i], (PolyElement, FracElement)):
u0[i] = u0[i].as_expr()
sol += u0[i] * x**i
else:
sol += Symbol('C_%s' %j) * x**i
if isinstance(sol, (PolyElement, FracElement)):
sol = sol.as_expr() * x**constantpower
else:
sol = sol * x**constantpower
if as_list:
if x0 != 0:
return [(sol.subs(x, x - x0), )]
return [(sol, )]
if x0 != 0:
return sol.subs(x, x - x0)
return sol
if smallest_n + m > len(u0):
raise NotImplementedError("Can't compute sufficient Initial Conditions")
# check if the recurrence represents a hypergeometric series
is_hyper = True
for i in range(1, len(r.listofpoly)-1):
if r.listofpoly[i] != r.parent.base.zero:
is_hyper = False
break
if not is_hyper:
raise NotHyperSeriesError(self, self.x0)
a = r.listofpoly[0]
b = r.listofpoly[-1]
# the constant multiple of argument of hypergeometric function
if isinstance(a.rep[0], (PolyElement, FracElement)):
c = - (S(a.rep[0].as_expr()) * m**(a.degree())) / (S(b.rep[0].as_expr()) * m**(b.degree()))
else:
c = - (S(a.rep[0]) * m**(a.degree())) / (S(b.rep[0]) * m**(b.degree()))
sol = 0
arg1 = roots(r.parent.base.to_sympy(a), recurrence.n)
arg2 = roots(r.parent.base.to_sympy(b), recurrence.n)
# iterate through the initial conditions to find
# the hypergeometric representation of the given
# function.
# The answer will be a linear combination
# of different hypergeometric series which satisfies
# the recurrence.
if as_list:
listofsol = []
for i in range(smallest_n + m):
# if the recurrence relation doesn't hold for `n = i`,
# then a Hypergeometric representation doesn't exist.
# add the algebraic term a * x**i to the solution,
# where a is u0[i]
if i < smallest_n:
if as_list:
listofsol.append(((S(u0[i]) * x**(i+constantpower)).subs(x, x-x0), ))
else:
sol += S(u0[i]) * x**i
continue
# if the coefficient u0[i] is zero, then the
# independent hypergeomtric series starting with
# x**i is not a part of the answer.
if S(u0[i]) == 0:
continue
ap = []
bq = []
# substitute m * n + i for n
for k in ordered(arg1.keys()):
ap.extend([nsimplify((i - k) / m)] * arg1[k])
for k in ordered(arg2.keys()):
bq.extend([nsimplify((i - k) / m)] * arg2[k])
# convention of (k + 1) in the denominator
if 1 in bq:
bq.remove(1)
else:
ap.append(1)
if as_list:
listofsol.append(((S(u0[i])*x**(i+constantpower)).subs(x, x-x0), (hyper(ap, bq, c*x**m)).subs(x, x-x0)))
else:
sol += S(u0[i]) * hyper(ap, bq, c * x**m) * x**i
if as_list:
return listofsol
sol = sol * x**constantpower
if x0 != 0:
return sol.subs(x, x - x0)
return sol
def to_expr(self):
"""
Converts a Holonomic Function back to elementary functions.
Examples
========
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
>>> from sympy.polys.domains import ZZ
>>> from sympy import symbols, S
>>> x = symbols('x')
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
>>> HolonomicFunction(x**2*Dx**2 + x*Dx + (x**2 - 1), x, 0, [0, S(1)/2]).to_expr()
besselj(1, x)
>>> HolonomicFunction((1 + x)*Dx**3 + Dx**2, x, 0, [1, 1, 1]).to_expr()
x*log(x + 1) + log(x + 1) + 1
"""
return hyperexpand(self.to_hyper()).simplify()
def change_ics(self, b, lenics=None):
"""
Changes the point `x0` to ``b`` for initial conditions.
Examples
========
>>> from sympy.holonomic import expr_to_holonomic
>>> from sympy import symbols, sin, exp
>>> x = symbols('x')
>>> expr_to_holonomic(sin(x)).change_ics(1)
HolonomicFunction((1) + (1)*Dx**2, x, 1, [sin(1), cos(1)])
>>> expr_to_holonomic(exp(x)).change_ics(2)
HolonomicFunction((-1) + (1)*Dx, x, 2, [exp(2)])
"""
symbolic = True
if lenics is None and len(self.y0) > self.annihilator.order:
lenics = len(self.y0)
dom = self.annihilator.parent.base.domain
try:
sol = expr_to_holonomic(self.to_expr(), x=self.x, x0=b, lenics=lenics, domain=dom)
except (NotPowerSeriesError, NotHyperSeriesError):
symbolic = False
if symbolic and sol.x0 == b:
return sol
y0 = self.evalf(b, derivatives=True)
return HolonomicFunction(self.annihilator, self.x, b, y0)
def to_meijerg(self):
"""
Returns a linear combination of Meijer G-functions.
Examples
========
>>> from sympy.holonomic import expr_to_holonomic
>>> from sympy import sin, cos, hyperexpand, log, symbols
>>> x = symbols('x')
>>> hyperexpand(expr_to_holonomic(cos(x) + sin(x)).to_meijerg())
sin(x) + cos(x)
>>> hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify()
log(x)
See Also
========
to_hyper()
"""
# convert to hypergeometric first
rep = self.to_hyper(as_list=True)
sol = S.Zero
for i in rep:
if len(i) == 1:
sol += i[0]
elif len(i) == 2:
sol += i[0] * _hyper_to_meijerg(i[1])
return sol
def from_hyper(func, x0=0, evalf=False):
r"""
Converts a hypergeometric function to holonomic.
``func`` is the Hypergeometric Function and ``x0`` is the point at
which initial conditions are required.
Examples
========
>>> from sympy.holonomic.holonomic import from_hyper
>>> from sympy import symbols, hyper, S
>>> x = symbols('x')
>>> from_hyper(hyper([], [S(3)/2], x**2/4))
HolonomicFunction((-x) + (2)*Dx + (x)*Dx**2, x, 1, [sinh(1), -sinh(1) + cosh(1)])
"""
a = func.ap
b = func.bq
z = func.args[2]
x = z.atoms(Symbol).pop()
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
# generalized hypergeometric differential equation
r1 = 1
for i in range(len(a)):
r1 = r1 * (x * Dx + a[i])
r2 = Dx
for i in range(len(b)):
r2 = r2 * (x * Dx + b[i] - 1)
sol = r1 - r2
simp = hyperexpand(func)
if isinstance(simp, Infinity) or isinstance(simp, NegativeInfinity):
return HolonomicFunction(sol, x).composition(z)
def _find_conditions(simp, x, x0, order, evalf=False):
y0 = []
for i in range(order):
if evalf:
val = simp.subs(x, x0).evalf()
else:
val = simp.subs(x, x0)
# return None if it is Infinite or NaN
if val.is_finite is False or isinstance(val, NaN):
return None
y0.append(val)
simp = simp.diff(x)
return y0
# if the function is known symbolically
if not isinstance(simp, hyper):
y0 = _find_conditions(simp, x, x0, sol.order)
while not y0:
# if values don't exist at 0, then try to find initial
# conditions at 1. If it doesn't exist at 1 too then
# try 2 and so on.
x0 += 1
y0 = _find_conditions(simp, x, x0, sol.order)
return HolonomicFunction(sol, x).composition(z, x0, y0)
if isinstance(simp, hyper):
x0 = 1
# use evalf if the function can't be simplified
y0 = _find_conditions(simp, x, x0, sol.order, evalf)
while not y0:
x0 += 1
y0 = _find_conditions(simp, x, x0, sol.order, evalf)
return HolonomicFunction(sol, x).composition(z, x0, y0)
return HolonomicFunction(sol, x).composition(z)
def from_meijerg(func, x0=0, evalf=False, initcond=True, domain=QQ):
"""
Converts a Meijer G-function to Holonomic.
``func`` is the G-Function and ``x0`` is the point at
which initial conditions are required.
Examples
========
>>> from sympy.holonomic.holonomic import from_meijerg
>>> from sympy import symbols, meijerg, S
>>> x = symbols('x')
>>> from_meijerg(meijerg(([], []), ([S(1)/2], [0]), x**2/4))
HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1/sqrt(pi)])
"""
a = func.ap
b = func.bq
n = len(func.an)
m = len(func.bm)
p = len(a)
z = func.args[2]
x = z.atoms(Symbol).pop()
R, Dx = DifferentialOperators(domain.old_poly_ring(x), 'Dx')
# compute the differential equation satisfied by the
# Meijer G-function.
mnp = (-1)**(m + n - p)
r1 = x * mnp
for i in range(len(a)):
r1 *= x * Dx + 1 - a[i]
r2 = 1
for i in range(len(b)):
r2 *= x * Dx - b[i]
sol = r1 - r2
if not initcond:
return HolonomicFunction(sol, x).composition(z)
simp = hyperexpand(func)
if isinstance(simp, Infinity) or isinstance(simp, NegativeInfinity):
return HolonomicFunction(sol, x).composition(z)
def _find_conditions(simp, x, x0, order, evalf=False):
y0 = []
for i in range(order):
if evalf:
val = simp.subs(x, x0).evalf()
else:
val = simp.subs(x, x0)
if val.is_finite is False or isinstance(val, NaN):
return None
y0.append(val)
simp = simp.diff(x)
return y0
# computing initial conditions
if not isinstance(simp, meijerg):
y0 = _find_conditions(simp, x, x0, sol.order)
while not y0:
x0 += 1
y0 = _find_conditions(simp, x, x0, sol.order)
return HolonomicFunction(sol, x).composition(z, x0, y0)
if isinstance(simp, meijerg):
x0 = 1
y0 = _find_conditions(simp, x, x0, sol.order, evalf)
while not y0:
x0 += 1
y0 = _find_conditions(simp, x, x0, sol.order, evalf)
return HolonomicFunction(sol, x).composition(z, x0, y0)
return HolonomicFunction(sol, x).composition(z)
x_1 = Dummy('x_1')
_lookup_table = None
domain_for_table = None
from sympy.integrals.meijerint import _mytype
def expr_to_holonomic(func, x=None, x0=0, y0=None, lenics=None, domain=None, initcond=True):
"""
Converts a function or an expression to a holonomic function.
Parameters
==========
func:
The expression to be converted.
x:
variable for the function.
x0:
point at which initial condition must be computed.
y0:
One can optionally provide initial condition if the method
isn't able to do it automatically.
lenics:
Number of terms in the initial condition. By default it is
equal to the order of the annihilator.
domain:
Ground domain for the polynomials in ``x`` appearing as coefficients
in the annihilator.
initcond:
Set it false if you don't want the initial conditions to be computed.
Examples
========
>>> from sympy.holonomic.holonomic import expr_to_holonomic
>>> from sympy import sin, exp, symbols
>>> x = symbols('x')
>>> expr_to_holonomic(sin(x))
HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1])
>>> expr_to_holonomic(exp(x))
HolonomicFunction((-1) + (1)*Dx, x, 0, [1])
See Also
========
sympy.integrals.meijerint._rewrite1, _convert_poly_rat_alg, _create_table
"""
func = sympify(func)
syms = func.free_symbols
if not x:
if len(syms) == 1:
x= syms.pop()
else:
raise ValueError("Specify the variable for the function")
elif x in syms:
syms.remove(x)
extra_syms = list(syms)
if domain is None:
if func.has(Float):
domain = RR
else:
domain = QQ
if len(extra_syms) != 0:
domain = domain[extra_syms].get_field()
# try to convert if the function is polynomial or rational
solpoly = _convert_poly_rat_alg(func, x, x0=x0, y0=y0, lenics=lenics, domain=domain, initcond=initcond)
if solpoly:
return solpoly
# create the lookup table
global _lookup_table, domain_for_table
if not _lookup_table:
domain_for_table = domain
_lookup_table = {}
_create_table(_lookup_table, domain=domain)
elif domain != domain_for_table:
domain_for_table = domain
_lookup_table = {}
_create_table(_lookup_table, domain=domain)
# use the table directly to convert to Holonomic
if func.is_Function:
f = func.subs(x, x_1)
t = _mytype(f, x_1)
if t in _lookup_table:
l = _lookup_table[t]
sol = l[0][1].change_x(x)
else:
sol = _convert_meijerint(func, x, initcond=False, domain=domain)
if not sol:
raise NotImplementedError
if y0:
sol.y0 = y0
if y0 or not initcond:
sol.x0 = x0
return sol
if not lenics:
lenics = sol.annihilator.order
_y0 = _find_conditions(func, x, x0, lenics)
while not _y0:
x0 += 1
_y0 = _find_conditions(func, x, x0, lenics)
return HolonomicFunction(sol.annihilator, x, x0, _y0)
if y0 or not initcond:
sol = sol.composition(func.args[0])
if y0:
sol.y0 = y0
sol.x0 = x0
return sol
if not lenics:
lenics = sol.annihilator.order
_y0 = _find_conditions(func, x, x0, lenics)
while not _y0:
x0 += 1
_y0 = _find_conditions(func, x, x0, lenics)
return sol.composition(func.args[0], x0, _y0)
# iterate through the expression recursively
args = func.args
f = func.func
from sympy.core import Add, Mul, Pow
sol = expr_to_holonomic(args[0], x=x, initcond=False, domain=domain)
if f is Add:
for i in range(1, len(args)):
sol += expr_to_holonomic(args[i], x=x, initcond=False, domain=domain)
elif f is Mul:
for i in range(1, len(args)):
sol *= expr_to_holonomic(args[i], x=x, initcond=False, domain=domain)
elif f is Pow:
sol = sol**args[1]
sol.x0 = x0
if not sol:
raise NotImplementedError
if y0:
sol.y0 = y0
if y0 or not initcond:
return sol
if sol.y0:
return sol
if not lenics:
lenics = sol.annihilator.order
if sol.annihilator.is_singular(x0):
r = sol._indicial()
l = list(r)
if len(r) == 1 and r[l[0]] == S.One:
r = l[0]
g = func / (x - x0)**r
singular_ics = _find_conditions(g, x, x0, lenics)
singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)]
y0 = {r:singular_ics}
return HolonomicFunction(sol.annihilator, x, x0, y0)
_y0 = _find_conditions(func, x, x0, lenics)
while not _y0:
x0 += 1
_y0 = _find_conditions(func, x, x0, lenics)
return HolonomicFunction(sol.annihilator, x, x0, _y0)
## Some helper functions ##
def _normalize(list_of, parent, negative=True):
"""
Normalize a given annihilator
"""
num = []
denom = []
base = parent.base
K = base.get_field()
lcm_denom = base.from_sympy(S.One)
list_of_coeff = []
# convert polynomials to the elements of associated
# fraction field
for i, j in enumerate(list_of):
if isinstance(j, base.dtype):
list_of_coeff.append(K.new(j.rep))
elif not isinstance(j, K.dtype):
list_of_coeff.append(K.from_sympy(sympify(j)))
else:
list_of_coeff.append(j)
# corresponding numerators of the sequence of polynomials
num.append(list_of_coeff[i].numer())
# corresponding denominators
denom.append(list_of_coeff[i].denom())
# lcm of denominators in the coefficients
for i in denom:
lcm_denom = i.lcm(lcm_denom)
if negative:
lcm_denom = -lcm_denom
lcm_denom = K.new(lcm_denom.rep)
# multiply the coefficients with lcm
for i, j in enumerate(list_of_coeff):
list_of_coeff[i] = j * lcm_denom
gcd_numer = base((list_of_coeff[-1].numer() / list_of_coeff[-1].denom()).rep)
# gcd of numerators in the coefficients
for i in num:
gcd_numer = i.gcd(gcd_numer)
gcd_numer = K.new(gcd_numer.rep)
# divide all the coefficients by the gcd
for i, j in enumerate(list_of_coeff):
frac_ans = j / gcd_numer
list_of_coeff[i] = base((frac_ans.numer() / frac_ans.denom()).rep)
return DifferentialOperator(list_of_coeff, parent)
def _derivate_diff_eq(listofpoly):
"""
Let a differential equation a0(x)y(x) + a1(x)y'(x) + ... = 0
where a0, a1,... are polynomials or rational functions. The function
returns b0, b1, b2... such that the differential equation
b0(x)y(x) + b1(x)y'(x) +... = 0 is formed after differentiating the
former equation.
"""
sol = []
a = len(listofpoly) - 1
sol.append(DMFdiff(listofpoly[0]))
for i, j in enumerate(listofpoly[1:]):
sol.append(DMFdiff(j) + listofpoly[i])
sol.append(listofpoly[a])
return sol
def _hyper_to_meijerg(func):
"""
Converts a `hyper` to meijerg.
"""
ap = func.ap
bq = func.bq
ispoly = any(i <= 0 and int(i) == i for i in ap)
if ispoly:
return hyperexpand(func)
z = func.args[2]
# parameters of the `meijerg` function.
an = (1 - i for i in ap)
anp = ()
bm = (S.Zero, )
bmq = (1 - i for i in bq)
k = S.One
for i in bq:
k = k * gamma(i)
for i in ap:
k = k / gamma(i)
return k * meijerg(an, anp, bm, bmq, -z)
def _add_lists(list1, list2):
"""Takes polynomial sequences of two annihilators a and b and returns
the list of polynomials of sum of a and b.
"""
if len(list1) <= len(list2):
sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):]
else:
sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):]
return sol
def _extend_y0(Holonomic, n):
"""
Tries to find more initial conditions by substituting the initial
value point in the differential equation.
"""
if Holonomic.annihilator.is_singular(Holonomic.x0) or Holonomic.is_singularics() == True:
return Holonomic.y0
annihilator = Holonomic.annihilator
a = annihilator.order
listofpoly = []
y0 = Holonomic.y0
R = annihilator.parent.base
K = R.get_field()
for i, j in enumerate(annihilator.listofpoly):
if isinstance(j, annihilator.parent.base.dtype):
listofpoly.append(K.new(j.rep))
if len(y0) < a or n <= len(y0):
return y0
else:
list_red = [-listofpoly[i] / listofpoly[a]
for i in range(a)]
if len(y0) > a:
y1 = [y0[i] for i in range(a)]
else:
y1 = [i for i in y0]
for i in range(n - a):
sol = 0
for a, b in zip(y1, list_red):
r = DMFsubs(b, Holonomic.x0)
if not getattr(r, 'is_finite', True):
return y0
if isinstance(r, (PolyElement, FracElement)):
r = r.as_expr()
sol += a * r
y1.append(sol)
list_red = _derivate_diff_eq(list_red)
return y0 + y1[len(y0):]
def DMFdiff(frac):
# differentiate a DMF object represented as p/q
if not isinstance(frac, DMF):
return frac.diff()
K = frac.ring
p = K.numer(frac)
q = K.denom(frac)
sol_num = - p * q.diff() + q * p.diff()
sol_denom = q**2
return K((sol_num.rep, sol_denom.rep))
def DMFsubs(frac, x0, mpm=False):
# substitute the point x0 in DMF object of the form p/q
if not isinstance(frac, DMF):
return frac
p = frac.num
q = frac.den
sol_p = S.Zero
sol_q = S.Zero
if mpm:
from mpmath import mp
for i, j in enumerate(reversed(p)):
if mpm:
j = sympify(j)._to_mpmath(mp.prec)
sol_p += j * x0**i
for i, j in enumerate(reversed(q)):
if mpm:
j = sympify(j)._to_mpmath(mp.prec)
sol_q += j * x0**i
if isinstance(sol_p, (PolyElement, FracElement)):
sol_p = sol_p.as_expr()
if isinstance(sol_q, (PolyElement, FracElement)):
sol_q = sol_q.as_expr()
return sol_p / sol_q
def _convert_poly_rat_alg(func, x, x0=0, y0=None, lenics=None, domain=QQ, initcond=True):
"""
Converts polynomials, rationals and algebraic functions to holonomic.
"""
ispoly = func.is_polynomial()
if not ispoly:
israt = func.is_rational_function()
else:
israt = True
if not (ispoly or israt):
basepoly, ratexp = func.as_base_exp()
if basepoly.is_polynomial() and ratexp.is_Number:
if isinstance(ratexp, Float):
ratexp = nsimplify(ratexp)
m, n = ratexp.p, ratexp.q
is_alg = True
else:
is_alg = False
else:
is_alg = True
if not (ispoly or israt or is_alg):
return None
R = domain.old_poly_ring(x)
_, Dx = DifferentialOperators(R, 'Dx')
# if the function is constant
if not func.has(x):
return HolonomicFunction(Dx, x, 0, [func])
if ispoly:
# differential equation satisfied by polynomial
sol = func * Dx - func.diff(x)
sol = _normalize(sol.listofpoly, sol.parent, negative=False)
is_singular = sol.is_singular(x0)
# try to compute the conditions for singular points
if y0 is None and x0 == 0 and is_singular:
rep = R.from_sympy(func).rep
for i, j in enumerate(reversed(rep)):
if j == 0:
continue
else:
coeff = list(reversed(rep))[i:]
indicial = i
break
for i, j in enumerate(coeff):
if isinstance(j, (PolyElement, FracElement)):
coeff[i] = j.as_expr()
y0 = {indicial: S(coeff)}
elif israt:
p, q = func.as_numer_denom()
# differential equation satisfied by rational
sol = p * q * Dx + p * q.diff(x) - q * p.diff(x)
sol = _normalize(sol.listofpoly, sol.parent, negative=False)
elif is_alg:
sol = n * (x / m) * Dx - 1
sol = HolonomicFunction(sol, x).composition(basepoly).annihilator
is_singular = sol.is_singular(x0)
# try to compute the conditions for singular points
if y0 is None and x0 == 0 and is_singular and \
(lenics is None or lenics <= 1):
rep = R.from_sympy(basepoly).rep
for i, j in enumerate(reversed(rep)):
if j == 0:
continue
if isinstance(j, (PolyElement, FracElement)):
j = j.as_expr()
coeff = S(j)**ratexp
indicial = S(i) * ratexp
break
if isinstance(coeff, (PolyElement, FracElement)):
coeff = coeff.as_expr()
y0 = {indicial: S([coeff])}
if y0 or not initcond:
return HolonomicFunction(sol, x, x0, y0)
if not lenics:
lenics = sol.order
if sol.is_singular(x0):
r = HolonomicFunction(sol, x, x0)._indicial()
l = list(r)
if len(r) == 1 and r[l[0]] == S.One:
r = l[0]
g = func / (x - x0)**r
singular_ics = _find_conditions(g, x, x0, lenics)
singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)]
y0 = {r:singular_ics}
return HolonomicFunction(sol, x, x0, y0)
y0 = _find_conditions(func, x, x0, lenics)
while not y0:
x0 += 1
y0 = _find_conditions(func, x, x0, lenics)
return HolonomicFunction(sol, x, x0, y0)
def _convert_meijerint(func, x, initcond=True, domain=QQ):
args = meijerint._rewrite1(func, x)
if args:
fac, po, g, _ = args
else:
return None
# lists for sum of meijerg functions
fac_list = [fac * i[0] for i in g]
t = po.as_base_exp()
s = t[1] if t[0] == x else S.Zero
po_list = [s + i[1] for i in g]
G_list = [i[2] for i in g]
# finds meijerg representation of x**s * meijerg(a1 ... ap, b1 ... bq, z)
def _shift(func, s):
z = func.args[-1]
if z.has(I):
z = z.subs(exp_polar, exp)
d = z.collect(x, evaluate=False)
b = list(d)[0]
a = d[b]
t = b.as_base_exp()
b = t[1] if t[0] == x else S.Zero
r = s / b
an = (i + r for i in func.args[0][0])
ap = (i + r for i in func.args[0][1])
bm = (i + r for i in func.args[1][0])
bq = (i + r for i in func.args[1][1])
return a**-r, meijerg((an, ap), (bm, bq), z)
coeff, m = _shift(G_list[0], po_list[0])
sol = fac_list[0] * coeff * from_meijerg(m, initcond=initcond, domain=domain)
# add all the meijerg functions after converting to holonomic
for i in range(1, len(G_list)):
coeff, m = _shift(G_list[i], po_list[i])
sol += fac_list[i] * coeff * from_meijerg(m, initcond=initcond, domain=domain)
return sol
def _create_table(table, domain=QQ):
"""
Creates the look-up table. For a similar implementation
see meijerint._create_lookup_table.
"""
def add(formula, annihilator, arg, x0=0, y0=[]):
"""
Adds a formula in the dictionary
"""
table.setdefault(_mytype(formula, x_1), []).append((formula,
HolonomicFunction(annihilator, arg, x0, y0)))
R = domain.old_poly_ring(x_1)
_, Dx = DifferentialOperators(R, 'Dx')
from sympy import (sin, cos, exp, log, erf, sqrt, pi,
sinh, cosh, sinc, erfc, Si, Ci, Shi, erfi)
# add some basic functions
add(sin(x_1), Dx**2 + 1, x_1, 0, [0, 1])
add(cos(x_1), Dx**2 + 1, x_1, 0, [1, 0])
add(exp(x_1), Dx - 1, x_1, 0, 1)
add(log(x_1), Dx + x_1*Dx**2, x_1, 1, [0, 1])
add(erf(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)])
add(erfc(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [1, -2/sqrt(pi)])
add(erfi(x_1), -2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)])
add(sinh(x_1), Dx**2 - 1, x_1, 0, [0, 1])
add(cosh(x_1), Dx**2 - 1, x_1, 0, [1, 0])
add(sinc(x_1), x_1 + 2*Dx + x_1*Dx**2, x_1)
add(Si(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1)
add(Ci(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1)
add(Shi(x_1), -x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1)
def _find_conditions(func, x, x0, order):
y0 = []
for i in range(order):
val = func.subs(x, x0)
if isinstance(val, NaN):
val = limit(func, x, x0)
if val.is_finite is False or isinstance(val, NaN):
return None
y0.append(val)
func = func.diff(x)
return y0
|
8173996d6542f955d72f7f80c53b9937fca1292602ddd8f33a282ac3c2f5db8d | """Transform a string with Python-like source code into SymPy expression. """
from tokenize import (generate_tokens, untokenize, TokenError,
NUMBER, STRING, NAME, OP, ENDMARKER, ERRORTOKEN, NEWLINE)
from keyword import iskeyword
import ast
import unicodedata
from io import StringIO
from sympy.assumptions.ask import AssumptionKeys
from sympy.core.compatibility import iterable
from sympy.core.basic import Basic
from sympy.core import Symbol
from sympy.core.function import arity, Function
from sympy.utilities.misc import filldedent, func_name
def _token_splittable(token):
"""
Predicate for whether a token name can be split into multiple tokens.
A token is splittable if it does not contain an underscore character and
it is not the name of a Greek letter. This is used to implicitly convert
expressions like 'xyz' into 'x*y*z'.
"""
if '_' in token:
return False
else:
try:
return not unicodedata.lookup('GREEK SMALL LETTER ' + token)
except KeyError:
pass
if len(token) > 1:
return True
return False
def _token_callable(token, local_dict, global_dict, nextToken=None):
"""
Predicate for whether a token name represents a callable function.
Essentially wraps ``callable``, but looks up the token name in the
locals and globals.
"""
func = local_dict.get(token[1])
if not func:
func = global_dict.get(token[1])
return callable(func) and not isinstance(func, Symbol)
def _add_factorial_tokens(name, result):
if result == [] or result[-1][1] == '(':
raise TokenError()
beginning = [(NAME, name), (OP, '(')]
end = [(OP, ')')]
diff = 0
length = len(result)
for index, token in enumerate(result[::-1]):
toknum, tokval = token
i = length - index - 1
if tokval == ')':
diff += 1
elif tokval == '(':
diff -= 1
if diff == 0:
if i - 1 >= 0 and result[i - 1][0] == NAME:
return result[:i - 1] + beginning + result[i - 1:] + end
else:
return result[:i] + beginning + result[i:] + end
return result
class AppliedFunction:
"""
A group of tokens representing a function and its arguments.
`exponent` is for handling the shorthand sin^2, ln^2, etc.
"""
def __init__(self, function, args, exponent=None):
if exponent is None:
exponent = []
self.function = function
self.args = args
self.exponent = exponent
self.items = ['function', 'args', 'exponent']
def expand(self):
"""Return a list of tokens representing the function"""
result = []
result.append(self.function)
result.extend(self.args)
return result
def __getitem__(self, index):
return getattr(self, self.items[index])
def __repr__(self):
return "AppliedFunction(%s, %s, %s)" % (self.function, self.args,
self.exponent)
class ParenthesisGroup(list):
"""List of tokens representing an expression in parentheses."""
pass
def _flatten(result):
result2 = []
for tok in result:
if isinstance(tok, AppliedFunction):
result2.extend(tok.expand())
else:
result2.append(tok)
return result2
def _group_parentheses(recursor):
def _inner(tokens, local_dict, global_dict):
"""Group tokens between parentheses with ParenthesisGroup.
Also processes those tokens recursively.
"""
result = []
stacks = []
stacklevel = 0
for token in tokens:
if token[0] == OP:
if token[1] == '(':
stacks.append(ParenthesisGroup([]))
stacklevel += 1
elif token[1] == ')':
stacks[-1].append(token)
stack = stacks.pop()
if len(stacks) > 0:
# We don't recurse here since the upper-level stack
# would reprocess these tokens
stacks[-1].extend(stack)
else:
# Recurse here to handle nested parentheses
# Strip off the outer parentheses to avoid an infinite loop
inner = stack[1:-1]
inner = recursor(inner,
local_dict,
global_dict)
parenGroup = [stack[0]] + inner + [stack[-1]]
result.append(ParenthesisGroup(parenGroup))
stacklevel -= 1
continue
if stacklevel:
stacks[-1].append(token)
else:
result.append(token)
if stacklevel:
raise TokenError("Mismatched parentheses")
return result
return _inner
def _apply_functions(tokens, local_dict, global_dict):
"""Convert a NAME token + ParenthesisGroup into an AppliedFunction.
Note that ParenthesisGroups, if not applied to any function, are
converted back into lists of tokens.
"""
result = []
symbol = None
for tok in tokens:
if tok[0] == NAME:
symbol = tok
result.append(tok)
elif isinstance(tok, ParenthesisGroup):
if symbol and _token_callable(symbol, local_dict, global_dict):
result[-1] = AppliedFunction(symbol, tok)
symbol = None
else:
result.extend(tok)
else:
symbol = None
result.append(tok)
return result
def _implicit_multiplication(tokens, local_dict, global_dict):
"""Implicitly adds '*' tokens.
Cases:
- Two AppliedFunctions next to each other ("sin(x)cos(x)")
- AppliedFunction next to an open parenthesis ("sin x (cos x + 1)")
- A close parenthesis next to an AppliedFunction ("(x+2)sin x")\
- A close parenthesis next to an open parenthesis ("(x+2)(x+3)")
- AppliedFunction next to an implicitly applied function ("sin(x)cos x")
"""
result = []
skip = False
for tok, nextTok in zip(tokens, tokens[1:]):
result.append(tok)
if skip:
skip = False
continue
if tok[0] == OP and tok[1] == '.' and nextTok[0] == NAME:
# Dotted name. Do not do implicit multiplication
skip = True
continue
if (isinstance(tok, AppliedFunction) and
isinstance(nextTok, AppliedFunction)):
result.append((OP, '*'))
elif (isinstance(tok, AppliedFunction) and
nextTok[0] == OP and nextTok[1] == '('):
# Applied function followed by an open parenthesis
if tok.function[1] == "Function":
result[-1].function = (result[-1].function[0], 'Symbol')
result.append((OP, '*'))
elif (tok[0] == OP and tok[1] == ')' and
isinstance(nextTok, AppliedFunction)):
# Close parenthesis followed by an applied function
result.append((OP, '*'))
elif (tok[0] == OP and tok[1] == ')' and
nextTok[0] == NAME):
# Close parenthesis followed by an implicitly applied function
result.append((OP, '*'))
elif (tok[0] == nextTok[0] == OP
and tok[1] == ')' and nextTok[1] == '('):
# Close parenthesis followed by an open parenthesis
result.append((OP, '*'))
elif (isinstance(tok, AppliedFunction) and nextTok[0] == NAME):
# Applied function followed by implicitly applied function
result.append((OP, '*'))
elif (tok[0] == NAME and
not _token_callable(tok, local_dict, global_dict) and
nextTok[0] == OP and nextTok[1] == '('):
# Constant followed by parenthesis
result.append((OP, '*'))
elif (tok[0] == NAME and
not _token_callable(tok, local_dict, global_dict) and
nextTok[0] == NAME and
not _token_callable(nextTok, local_dict, global_dict)):
# Constant followed by constant
result.append((OP, '*'))
elif (tok[0] == NAME and
not _token_callable(tok, local_dict, global_dict) and
(isinstance(nextTok, AppliedFunction) or nextTok[0] == NAME)):
# Constant followed by (implicitly applied) function
result.append((OP, '*'))
if tokens:
result.append(tokens[-1])
return result
def _implicit_application(tokens, local_dict, global_dict):
"""Adds parentheses as needed after functions."""
result = []
appendParen = 0 # number of closing parentheses to add
skip = 0 # number of tokens to delay before adding a ')' (to
# capture **, ^, etc.)
exponentSkip = False # skipping tokens before inserting parentheses to
# work with function exponentiation
for tok, nextTok in zip(tokens, tokens[1:]):
result.append(tok)
if (tok[0] == NAME and nextTok[0] not in [OP, ENDMARKER, NEWLINE]):
if _token_callable(tok, local_dict, global_dict, nextTok):
result.append((OP, '('))
appendParen += 1
# name followed by exponent - function exponentiation
elif (tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**'):
if _token_callable(tok, local_dict, global_dict):
exponentSkip = True
elif exponentSkip:
# if the last token added was an applied function (i.e. the
# power of the function exponent) OR a multiplication (as
# implicit multiplication would have added an extraneous
# multiplication)
if (isinstance(tok, AppliedFunction)
or (tok[0] == OP and tok[1] == '*')):
# don't add anything if the next token is a multiplication
# or if there's already a parenthesis (if parenthesis, still
# stop skipping tokens)
if not (nextTok[0] == OP and nextTok[1] == '*'):
if not(nextTok[0] == OP and nextTok[1] == '('):
result.append((OP, '('))
appendParen += 1
exponentSkip = False
elif appendParen:
if nextTok[0] == OP and nextTok[1] in ('^', '**', '*'):
skip = 1
continue
if skip:
skip -= 1
continue
result.append((OP, ')'))
appendParen -= 1
if tokens:
result.append(tokens[-1])
if appendParen:
result.extend([(OP, ')')] * appendParen)
return result
def function_exponentiation(tokens, local_dict, global_dict):
"""Allows functions to be exponentiated, e.g. ``cos**2(x)``.
Examples
========
>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, function_exponentiation)
>>> transformations = standard_transformations + (function_exponentiation,)
>>> parse_expr('sin**4(x)', transformations=transformations)
sin(x)**4
"""
result = []
exponent = []
consuming_exponent = False
level = 0
for tok, nextTok in zip(tokens, tokens[1:]):
if tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**':
if _token_callable(tok, local_dict, global_dict):
consuming_exponent = True
elif consuming_exponent:
if tok[0] == NAME and tok[1] == 'Function':
tok = (NAME, 'Symbol')
exponent.append(tok)
# only want to stop after hitting )
if tok[0] == nextTok[0] == OP and tok[1] == ')' and nextTok[1] == '(':
consuming_exponent = False
# if implicit multiplication was used, we may have )*( instead
if tok[0] == nextTok[0] == OP and tok[1] == '*' and nextTok[1] == '(':
consuming_exponent = False
del exponent[-1]
continue
elif exponent and not consuming_exponent:
if tok[0] == OP:
if tok[1] == '(':
level += 1
elif tok[1] == ')':
level -= 1
if level == 0:
result.append(tok)
result.extend(exponent)
exponent = []
continue
result.append(tok)
if tokens:
result.append(tokens[-1])
if exponent:
result.extend(exponent)
return result
def split_symbols_custom(predicate):
"""Creates a transformation that splits symbol names.
``predicate`` should return True if the symbol name is to be split.
For instance, to retain the default behavior but avoid splitting certain
symbol names, a predicate like this would work:
>>> from sympy.parsing.sympy_parser import (parse_expr, _token_splittable,
... standard_transformations, implicit_multiplication,
... split_symbols_custom)
>>> def can_split(symbol):
... if symbol not in ('list', 'of', 'unsplittable', 'names'):
... return _token_splittable(symbol)
... return False
...
>>> transformation = split_symbols_custom(can_split)
>>> parse_expr('unsplittable', transformations=standard_transformations +
... (transformation, implicit_multiplication))
unsplittable
"""
def _split_symbols(tokens, local_dict, global_dict):
result = []
split = False
split_previous=False
for tok in tokens:
if split_previous:
# throw out closing parenthesis of Symbol that was split
split_previous=False
continue
split_previous=False
if tok[0] == NAME and tok[1] in ['Symbol', 'Function']:
split = True
elif split and tok[0] == NAME:
symbol = tok[1][1:-1]
if predicate(symbol):
tok_type = result[-2][1] # Symbol or Function
del result[-2:] # Get rid of the call to Symbol
i = 0
while i < len(symbol):
char = symbol[i]
if char in local_dict or char in global_dict:
result.extend([(NAME, "%s" % char)])
elif char.isdigit():
char = [char]
for i in range(i + 1, len(symbol)):
if not symbol[i].isdigit():
i -= 1
break
char.append(symbol[i])
char = ''.join(char)
result.extend([(NAME, 'Number'), (OP, '('),
(NAME, "'%s'" % char), (OP, ')')])
else:
use = tok_type if i == len(symbol) else 'Symbol'
result.extend([(NAME, use), (OP, '('),
(NAME, "'%s'" % char), (OP, ')')])
i += 1
# Set split_previous=True so will skip
# the closing parenthesis of the original Symbol
split = False
split_previous = True
continue
else:
split = False
result.append(tok)
return result
return _split_symbols
#: Splits symbol names for implicit multiplication.
#:
#: Intended to let expressions like ``xyz`` be parsed as ``x*y*z``. Does not
#: split Greek character names, so ``theta`` will *not* become
#: ``t*h*e*t*a``. Generally this should be used with
#: ``implicit_multiplication``.
split_symbols = split_symbols_custom(_token_splittable)
def implicit_multiplication(result, local_dict, global_dict):
"""Makes the multiplication operator optional in most cases.
Use this before :func:`implicit_application`, otherwise expressions like
``sin 2x`` will be parsed as ``x * sin(2)`` rather than ``sin(2*x)``.
Examples
========
>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_multiplication)
>>> transformations = standard_transformations + (implicit_multiplication,)
>>> parse_expr('3 x y', transformations=transformations)
3*x*y
"""
# These are interdependent steps, so we don't expose them separately
for step in (_group_parentheses(implicit_multiplication),
_apply_functions,
_implicit_multiplication):
result = step(result, local_dict, global_dict)
result = _flatten(result)
return result
def implicit_application(result, local_dict, global_dict):
"""Makes parentheses optional in some cases for function calls.
Use this after :func:`implicit_multiplication`, otherwise expressions
like ``sin 2x`` will be parsed as ``x * sin(2)`` rather than
``sin(2*x)``.
Examples
========
>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_application)
>>> transformations = standard_transformations + (implicit_application,)
>>> parse_expr('cot z + csc z', transformations=transformations)
cot(z) + csc(z)
"""
for step in (_group_parentheses(implicit_application),
_apply_functions,
_implicit_application,):
result = step(result, local_dict, global_dict)
result = _flatten(result)
return result
def implicit_multiplication_application(result, local_dict, global_dict):
"""Allows a slightly relaxed syntax.
- Parentheses for single-argument method calls are optional.
- Multiplication is implicit.
- Symbol names can be split (i.e. spaces are not needed between
symbols).
- Functions can be exponentiated.
Examples
========
>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, implicit_multiplication_application)
>>> parse_expr("10sin**2 x**2 + 3xyz + tan theta",
... transformations=(standard_transformations +
... (implicit_multiplication_application,)))
3*x*y*z + 10*sin(x**2)**2 + tan(theta)
"""
for step in (split_symbols, implicit_multiplication,
implicit_application, function_exponentiation):
result = step(result, local_dict, global_dict)
return result
def auto_symbol(tokens, local_dict, global_dict):
"""Inserts calls to ``Symbol``/``Function`` for undefined variables."""
result = []
prevTok = (None, None)
tokens.append((None, None)) # so zip traverses all tokens
for tok, nextTok in zip(tokens, tokens[1:]):
tokNum, tokVal = tok
nextTokNum, nextTokVal = nextTok
if tokNum == NAME:
name = tokVal
if (name in ['True', 'False', 'None']
or iskeyword(name)
# Don't convert attribute access
or (prevTok[0] == OP and prevTok[1] == '.')
# Don't convert keyword arguments
or (prevTok[0] == OP and prevTok[1] in ('(', ',')
and nextTokNum == OP and nextTokVal == '=')
# the name has already been defined
or name in local_dict and local_dict[name] is not None):
result.append((NAME, name))
continue
elif name in local_dict:
local_dict.setdefault(None, set()).add(name)
if nextTokVal == '(':
local_dict[name] = Function(name)
else:
local_dict[name] = Symbol(name)
result.append((NAME, name))
continue
elif name in global_dict:
obj = global_dict[name]
if isinstance(obj, (AssumptionKeys, Basic, type)) or callable(obj):
result.append((NAME, name))
continue
result.extend([
(NAME, 'Symbol' if nextTokVal != '(' else 'Function'),
(OP, '('),
(NAME, repr(str(name))),
(OP, ')'),
])
else:
result.append((tokNum, tokVal))
prevTok = (tokNum, tokVal)
return result
def lambda_notation(tokens, local_dict, global_dict):
"""Substitutes "lambda" with its Sympy equivalent Lambda().
However, the conversion doesn't take place if only "lambda"
is passed because that is a syntax error.
"""
result = []
flag = False
toknum, tokval = tokens[0]
tokLen = len(tokens)
if toknum == NAME and tokval == 'lambda':
if tokLen == 2 or tokLen == 3 and tokens[1][0] == NEWLINE:
# In Python 3.6.7+, inputs without a newline get NEWLINE added to
# the tokens
result.extend(tokens)
elif tokLen > 2:
result.extend([
(NAME, 'Lambda'),
(OP, '('),
(OP, '('),
(OP, ')'),
(OP, ')'),
])
for tokNum, tokVal in tokens[1:]:
if tokNum == OP and tokVal == ':':
tokVal = ','
flag = True
if not flag and tokNum == OP and tokVal in ['*', '**']:
raise TokenError("Starred arguments in lambda not supported")
if flag:
result.insert(-1, (tokNum, tokVal))
else:
result.insert(-2, (tokNum, tokVal))
else:
result.extend(tokens)
return result
def factorial_notation(tokens, local_dict, global_dict):
"""Allows standard notation for factorial."""
result = []
nfactorial = 0
for toknum, tokval in tokens:
if toknum == ERRORTOKEN:
op = tokval
if op == '!':
nfactorial += 1
else:
nfactorial = 0
result.append((OP, op))
else:
if nfactorial == 1:
result = _add_factorial_tokens('factorial', result)
elif nfactorial == 2:
result = _add_factorial_tokens('factorial2', result)
elif nfactorial > 2:
raise TokenError
nfactorial = 0
result.append((toknum, tokval))
return result
def convert_xor(tokens, local_dict, global_dict):
"""Treats XOR, ``^``, as exponentiation, ``**``."""
result = []
for toknum, tokval in tokens:
if toknum == OP:
if tokval == '^':
result.append((OP, '**'))
else:
result.append((toknum, tokval))
else:
result.append((toknum, tokval))
return result
def repeated_decimals(tokens, local_dict, global_dict):
"""
Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90)
Run this before auto_number.
"""
result = []
def is_digit(s):
return all(i in '0123456789_' for i in s)
# num will running match any DECIMAL [ INTEGER ]
num = []
for toknum, tokval in tokens:
if toknum == NUMBER:
if (not num and '.' in tokval and 'e' not in tokval.lower() and
'j' not in tokval.lower()):
num.append((toknum, tokval))
elif is_digit(tokval)and len(num) == 2:
num.append((toknum, tokval))
elif is_digit(tokval) and len(num) == 3 and is_digit(num[-1][1]):
# Python 2 tokenizes 00123 as '00', '123'
# Python 3 tokenizes 01289 as '012', '89'
num.append((toknum, tokval))
else:
num = []
elif toknum == OP:
if tokval == '[' and len(num) == 1:
num.append((OP, tokval))
elif tokval == ']' and len(num) >= 3:
num.append((OP, tokval))
elif tokval == '.' and not num:
# handle .[1]
num.append((NUMBER, '0.'))
else:
num = []
else:
num = []
result.append((toknum, tokval))
if num and num[-1][1] == ']':
# pre.post[repetend] = a + b/c + d/e where a = pre, b/c = post,
# and d/e = repetend
result = result[:-len(num)]
pre, post = num[0][1].split('.')
repetend = num[2][1]
if len(num) == 5:
repetend += num[3][1]
pre = pre.replace('_', '')
post = post.replace('_', '')
repetend = repetend.replace('_', '')
zeros = '0'*len(post)
post, repetends = [w.lstrip('0') for w in [post, repetend]]
# or else interpreted as octal
a = pre or '0'
b, c = post or '0', '1' + zeros
d, e = repetends, ('9'*len(repetend)) + zeros
seq = [
(OP, '('),
(NAME, 'Integer'),
(OP, '('),
(NUMBER, a),
(OP, ')'),
(OP, '+'),
(NAME, 'Rational'),
(OP, '('),
(NUMBER, b),
(OP, ','),
(NUMBER, c),
(OP, ')'),
(OP, '+'),
(NAME, 'Rational'),
(OP, '('),
(NUMBER, d),
(OP, ','),
(NUMBER, e),
(OP, ')'),
(OP, ')'),
]
result.extend(seq)
num = []
return result
def auto_number(tokens, local_dict, global_dict):
"""
Converts numeric literals to use SymPy equivalents.
Complex numbers use ``I``, integer literals use ``Integer``, and float
literals use ``Float``.
"""
result = []
for toknum, tokval in tokens:
if toknum == NUMBER:
number = tokval
postfix = []
if number.endswith('j') or number.endswith('J'):
number = number[:-1]
postfix = [(OP, '*'), (NAME, 'I')]
if '.' in number or (('e' in number or 'E' in number) and
not (number.startswith('0x') or number.startswith('0X'))):
seq = [(NAME, 'Float'), (OP, '('),
(NUMBER, repr(str(number))), (OP, ')')]
else:
seq = [(NAME, 'Integer'), (OP, '('), (
NUMBER, number), (OP, ')')]
result.extend(seq + postfix)
else:
result.append((toknum, tokval))
return result
def rationalize(tokens, local_dict, global_dict):
"""Converts floats into ``Rational``. Run AFTER ``auto_number``."""
result = []
passed_float = False
for toknum, tokval in tokens:
if toknum == NAME:
if tokval == 'Float':
passed_float = True
tokval = 'Rational'
result.append((toknum, tokval))
elif passed_float == True and toknum == NUMBER:
passed_float = False
result.append((STRING, tokval))
else:
result.append((toknum, tokval))
return result
def _transform_equals_sign(tokens, local_dict, global_dict):
"""Transforms the equals sign ``=`` to instances of Eq.
This is a helper function for `convert_equals_signs`.
Works with expressions containing one equals sign and no
nesting. Expressions like `(1=2)=False` won't work with this
and should be used with `convert_equals_signs`.
Examples: 1=2 to Eq(1,2)
1*2=x to Eq(1*2, x)
This does not deal with function arguments yet.
"""
result = []
if (OP, "=") in tokens:
result.append((NAME, "Eq"))
result.append((OP, "("))
for index, token in enumerate(tokens):
if token == (OP, "="):
result.append((OP, ","))
continue
result.append(token)
result.append((OP, ")"))
else:
result = tokens
return result
def convert_equals_signs(result, local_dict, global_dict):
""" Transforms all the equals signs ``=`` to instances of Eq.
Parses the equals signs in the expression and replaces them with
appropriate Eq instances.Also works with nested equals signs.
Does not yet play well with function arguments.
For example, the expression `(x=y)` is ambiguous and can be interpreted
as x being an argument to a function and `convert_equals_signs` won't
work for this.
See also
========
convert_equality_operators
Examples
========
>>> from sympy.parsing.sympy_parser import (parse_expr,
... standard_transformations, convert_equals_signs)
>>> parse_expr("1*2=x", transformations=(
... standard_transformations + (convert_equals_signs,)))
Eq(2, x)
>>> parse_expr("(1*2=x)=False", transformations=(
... standard_transformations + (convert_equals_signs,)))
Eq(Eq(2, x), False)
"""
for step in (_group_parentheses(convert_equals_signs),
_apply_functions,
_transform_equals_sign):
result = step(result, local_dict, global_dict)
result = _flatten(result)
return result
#: Standard transformations for :func:`parse_expr`.
#: Inserts calls to :class:`~.Symbol`, :class:`~.Integer`, and other SymPy
#: datatypes and allows the use of standard factorial notation (e.g. ``x!``).
standard_transformations = (lambda_notation, auto_symbol, repeated_decimals, auto_number,
factorial_notation)
def stringify_expr(s, local_dict, global_dict, transformations):
"""
Converts the string ``s`` to Python code, in ``local_dict``
Generally, ``parse_expr`` should be used.
"""
tokens = []
input_code = StringIO(s.strip())
for toknum, tokval, _, _, _ in generate_tokens(input_code.readline):
tokens.append((toknum, tokval))
for transform in transformations:
tokens = transform(tokens, local_dict, global_dict)
return untokenize(tokens)
def eval_expr(code, local_dict, global_dict):
"""
Evaluate Python code generated by ``stringify_expr``.
Generally, ``parse_expr`` should be used.
"""
expr = eval(
code, global_dict, local_dict) # take local objects in preference
return expr
def parse_expr(s, local_dict=None, transformations=standard_transformations,
global_dict=None, evaluate=True):
"""Converts the string ``s`` to a SymPy expression, in ``local_dict``
Parameters
==========
s : str
The string to parse.
local_dict : dict, optional
A dictionary of local variables to use when parsing.
global_dict : dict, optional
A dictionary of global variables. By default, this is initialized
with ``from sympy import *``; provide this parameter to override
this behavior (for instance, to parse ``"Q & S"``).
transformations : tuple, optional
A tuple of transformation functions used to modify the tokens of the
parsed expression before evaluation. The default transformations
convert numeric literals into their SymPy equivalents, convert
undefined variables into SymPy symbols, and allow the use of standard
mathematical factorial notation (e.g. ``x!``).
evaluate : bool, optional
When False, the order of the arguments will remain as they were in the
string and automatic simplification that would normally occur is
suppressed. (see examples)
Examples
========
>>> from sympy.parsing.sympy_parser import parse_expr
>>> parse_expr("1/2")
1/2
>>> type(_)
<class 'sympy.core.numbers.Half'>
>>> from sympy.parsing.sympy_parser import standard_transformations,\\
... implicit_multiplication_application
>>> transformations = (standard_transformations +
... (implicit_multiplication_application,))
>>> parse_expr("2x", transformations=transformations)
2*x
When evaluate=False, some automatic simplifications will not occur:
>>> parse_expr("2**3"), parse_expr("2**3", evaluate=False)
(8, 2**3)
In addition the order of the arguments will not be made canonical.
This feature allows one to tell exactly how the expression was entered:
>>> a = parse_expr('1 + x', evaluate=False)
>>> b = parse_expr('x + 1', evaluate=0)
>>> a == b
False
>>> a.args
(1, x)
>>> b.args
(x, 1)
See Also
========
stringify_expr, eval_expr, standard_transformations,
implicit_multiplication_application
"""
if local_dict is None:
local_dict = {}
elif not isinstance(local_dict, dict):
raise TypeError('expecting local_dict to be a dict')
if global_dict is None:
global_dict = {}
exec('from sympy import *', global_dict)
elif not isinstance(global_dict, dict):
raise TypeError('expecting global_dict to be a dict')
transformations = transformations or ()
if transformations:
if not iterable(transformations):
raise TypeError(
'`transformations` should be a list of functions.')
for _ in transformations:
if not callable(_):
raise TypeError(filldedent('''
expected a function in `transformations`,
not %s''' % func_name(_)))
if arity(_) != 3:
raise TypeError(filldedent('''
a transformation should be function that
takes 3 arguments'''))
code = stringify_expr(s, local_dict, global_dict, transformations)
if not evaluate:
code = compile(evaluateFalse(code), '<string>', 'eval')
try:
rv = eval_expr(code, local_dict, global_dict)
# restore neutral definitions for names
for i in local_dict.pop(None, ()):
local_dict[i] = None
return rv
except Exception as e:
# restore neutral definitions for names
for i in local_dict.pop(None, ()):
local_dict[i] = None
raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}")
def evaluateFalse(s):
"""
Replaces operators with the SymPy equivalent and sets evaluate=False.
"""
node = ast.parse(s)
node = EvaluateFalseTransformer().visit(node)
# node is a Module, we want an Expression
node = ast.Expression(node.body[0].value)
return ast.fix_missing_locations(node)
class EvaluateFalseTransformer(ast.NodeTransformer):
operators = {
ast.Add: 'Add',
ast.Mult: 'Mul',
ast.Pow: 'Pow',
ast.Sub: 'Add',
ast.Div: 'Mul',
ast.BitOr: 'Or',
ast.BitAnd: 'And',
ast.BitXor: 'Not',
}
def flatten(self, args, func):
result = []
for arg in args:
if isinstance(arg, ast.Call):
arg_func = arg.func
if isinstance(arg_func, ast.Call):
arg_func = arg_func.func
if arg_func.id == func:
result.extend(self.flatten(arg.args, func))
else:
result.append(arg)
else:
result.append(arg)
return result
def visit_BinOp(self, node):
if node.op.__class__ in self.operators:
sympy_class = self.operators[node.op.__class__]
right = self.visit(node.right)
left = self.visit(node.left)
rev = False
if isinstance(node.op, ast.Sub):
right = ast.Call(
func=ast.Name(id='Mul', ctx=ast.Load()),
args=[ast.UnaryOp(op=ast.USub(), operand=ast.Num(1)), right],
keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))],
starargs=None,
kwargs=None
)
elif isinstance(node.op, ast.Div):
if isinstance(node.left, ast.UnaryOp):
left, right = right, left
rev = True
left = ast.Call(
func=ast.Name(id='Pow', ctx=ast.Load()),
args=[left, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))],
keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))],
starargs=None,
kwargs=None
)
else:
right = ast.Call(
func=ast.Name(id='Pow', ctx=ast.Load()),
args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))],
keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))],
starargs=None,
kwargs=None
)
if rev: # undo reversal
left, right = right, left
new_node = ast.Call(
func=ast.Name(id=sympy_class, ctx=ast.Load()),
args=[left, right],
keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))],
starargs=None,
kwargs=None
)
if sympy_class in ('Add', 'Mul'):
# Denest Add or Mul as appropriate
new_node.args = self.flatten(new_node.args, sympy_class)
return new_node
return node
|
7bf392f0456769ee11a43f4411dac55b65a9b3f55a902672fc750ea276a02e9c | r"""Module that defines indexed objects
The classes ``IndexedBase``, ``Indexed``, and ``Idx`` represent a
matrix element ``M[i, j]`` as in the following diagram::
1) The Indexed class represents the entire indexed object.
|
___|___
' '
M[i, j]
/ \__\______
| |
| |
| 2) The Idx class represents indices; each Idx can
| optionally contain information about its range.
|
3) IndexedBase represents the 'stem' of an indexed object, here `M`.
The stem used by itself is usually taken to represent the entire
array.
There can be any number of indices on an Indexed object. No
transformation properties are implemented in these Base objects, but
implicit contraction of repeated indices is supported.
Note that the support for complicated (i.e. non-atomic) integer
expressions as indices is limited. (This should be improved in
future releases.)
Examples
========
To express the above matrix element example you would write:
>>> from sympy import symbols, IndexedBase, Idx
>>> M = IndexedBase('M')
>>> i, j = symbols('i j', cls=Idx)
>>> M[i, j]
M[i, j]
Repeated indices in a product implies a summation, so to express a
matrix-vector product in terms of Indexed objects:
>>> x = IndexedBase('x')
>>> M[i, j]*x[j]
M[i, j]*x[j]
If the indexed objects will be converted to component based arrays, e.g.
with the code printers or the autowrap framework, you also need to provide
(symbolic or numerical) dimensions. This can be done by passing an
optional shape parameter to IndexedBase upon construction:
>>> dim1, dim2 = symbols('dim1 dim2', integer=True)
>>> A = IndexedBase('A', shape=(dim1, 2*dim1, dim2))
>>> A.shape
(dim1, 2*dim1, dim2)
>>> A[i, j, 3].shape
(dim1, 2*dim1, dim2)
If an IndexedBase object has no shape information, it is assumed that the
array is as large as the ranges of its indices:
>>> n, m = symbols('n m', integer=True)
>>> i = Idx('i', m)
>>> j = Idx('j', n)
>>> M[i, j].shape
(m, n)
>>> M[i, j].ranges
[(0, m - 1), (0, n - 1)]
The above can be compared with the following:
>>> A[i, 2, j].shape
(dim1, 2*dim1, dim2)
>>> A[i, 2, j].ranges
[(0, m - 1), None, (0, n - 1)]
To analyze the structure of indexed expressions, you can use the methods
get_indices() and get_contraction_structure():
>>> from sympy.tensor import get_indices, get_contraction_structure
>>> get_indices(A[i, j, j])
({i}, {})
>>> get_contraction_structure(A[i, j, j])
{(j,): {A[i, j, j]}}
See the appropriate docstrings for a detailed explanation of the output.
"""
# TODO: (some ideas for improvement)
#
# o test and guarantee numpy compatibility
# - implement full support for broadcasting
# - strided arrays
#
# o more functions to analyze indexed expressions
# - identify standard constructs, e.g matrix-vector product in a subexpression
#
# o functions to generate component based arrays (numpy and sympy.Matrix)
# - generate a single array directly from Indexed
# - convert simple sub-expressions
#
# o sophisticated indexing (possibly in subclasses to preserve simplicity)
# - Idx with range smaller than dimension of Indexed
# - Idx with stepsize != 1
# - Idx with step determined by function call
from collections.abc import Iterable
from sympy import Number
from sympy.core.assumptions import StdFactKB
from sympy.core import Expr, Tuple, sympify, S
from sympy.core.symbol import _filter_assumptions, Symbol
from sympy.core.compatibility import (is_sequence, NotIterable)
from sympy.core.logic import fuzzy_bool, fuzzy_not
from sympy.core.sympify import _sympify
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.multipledispatch import dispatch
class IndexException(Exception):
pass
class Indexed(Expr):
"""Represents a mathematical object with indices.
>>> from sympy import Indexed, IndexedBase, Idx, symbols
>>> i, j = symbols('i j', cls=Idx)
>>> Indexed('A', i, j)
A[i, j]
It is recommended that ``Indexed`` objects be created by indexing ``IndexedBase``:
``IndexedBase('A')[i, j]`` instead of ``Indexed(IndexedBase('A'), i, j)``.
>>> A = IndexedBase('A')
>>> a_ij = A[i, j] # Prefer this,
>>> b_ij = Indexed(A, i, j) # over this.
>>> a_ij == b_ij
True
"""
is_commutative = True
is_Indexed = True
is_symbol = True
is_Atom = True
def __new__(cls, base, *args, **kw_args):
from sympy.utilities.misc import filldedent
from sympy.tensor.array.ndim_array import NDimArray
from sympy.matrices.matrices import MatrixBase
if not args:
raise IndexException("Indexed needs at least one index.")
if isinstance(base, (str, Symbol)):
base = IndexedBase(base)
elif not hasattr(base, '__getitem__') and not isinstance(base, IndexedBase):
raise TypeError(filldedent("""
The base can only be replaced with a string, Symbol,
IndexedBase or an object with a method for getting
items (i.e. an object with a `__getitem__` method).
"""))
args = list(map(sympify, args))
if isinstance(base, (NDimArray, Iterable, Tuple, MatrixBase)) and all([i.is_number for i in args]):
if len(args) == 1:
return base[args[0]]
else:
return base[args]
obj = Expr.__new__(cls, base, *args, **kw_args)
try:
IndexedBase._set_assumptions(obj, base.assumptions0)
except AttributeError:
IndexedBase._set_assumptions(obj, {})
return obj
def _hashable_content(self):
return super()._hashable_content() + tuple(sorted(self.assumptions0.items()))
@property
def name(self):
return str(self)
@property
def _diff_wrt(self):
"""Allow derivatives with respect to an ``Indexed`` object."""
return True
def _eval_derivative(self, wrt):
from sympy.tensor.array.ndim_array import NDimArray
if isinstance(wrt, Indexed) and wrt.base == self.base:
if len(self.indices) != len(wrt.indices):
msg = "Different # of indices: d({!s})/d({!s})".format(self,
wrt)
raise IndexException(msg)
result = S.One
for index1, index2 in zip(self.indices, wrt.indices):
result *= KroneckerDelta(index1, index2)
return result
elif isinstance(self.base, NDimArray):
from sympy.tensor.array import derive_by_array
return Indexed(derive_by_array(self.base, wrt), *self.args[1:])
else:
if Tuple(self.indices).has(wrt):
return S.NaN
return S.Zero
@property
def assumptions0(self):
return {k: v for k, v in self._assumptions.items() if v is not None}
@property
def base(self):
"""Returns the ``IndexedBase`` of the ``Indexed`` object.
Examples
========
>>> from sympy import Indexed, IndexedBase, Idx, symbols
>>> i, j = symbols('i j', cls=Idx)
>>> Indexed('A', i, j).base
A
>>> B = IndexedBase('B')
>>> B == B[i, j].base
True
"""
return self.args[0]
@property
def indices(self):
"""
Returns the indices of the ``Indexed`` object.
Examples
========
>>> from sympy import Indexed, Idx, symbols
>>> i, j = symbols('i j', cls=Idx)
>>> Indexed('A', i, j).indices
(i, j)
"""
return self.args[1:]
@property
def rank(self):
"""
Returns the rank of the ``Indexed`` object.
Examples
========
>>> from sympy import Indexed, Idx, symbols
>>> i, j, k, l, m = symbols('i:m', cls=Idx)
>>> Indexed('A', i, j).rank
2
>>> q = Indexed('A', i, j, k, l, m)
>>> q.rank
5
>>> q.rank == len(q.indices)
True
"""
return len(self.args) - 1
@property
def shape(self):
"""Returns a list with dimensions of each index.
Dimensions is a property of the array, not of the indices. Still, if
the ``IndexedBase`` does not define a shape attribute, it is assumed
that the ranges of the indices correspond to the shape of the array.
>>> from sympy import IndexedBase, Idx, symbols
>>> n, m = symbols('n m', integer=True)
>>> i = Idx('i', m)
>>> j = Idx('j', m)
>>> A = IndexedBase('A', shape=(n, n))
>>> B = IndexedBase('B')
>>> A[i, j].shape
(n, n)
>>> B[i, j].shape
(m, m)
"""
from sympy.utilities.misc import filldedent
if self.base.shape:
return self.base.shape
sizes = []
for i in self.indices:
upper = getattr(i, 'upper', None)
lower = getattr(i, 'lower', None)
if None in (upper, lower):
raise IndexException(filldedent("""
Range is not defined for all indices in: %s""" % self))
try:
size = upper - lower + 1
except TypeError:
raise IndexException(filldedent("""
Shape cannot be inferred from Idx with
undefined range: %s""" % self))
sizes.append(size)
return Tuple(*sizes)
@property
def ranges(self):
"""Returns a list of tuples with lower and upper range of each index.
If an index does not define the data members upper and lower, the
corresponding slot in the list contains ``None`` instead of a tuple.
Examples
========
>>> from sympy import Indexed,Idx, symbols
>>> Indexed('A', Idx('i', 2), Idx('j', 4), Idx('k', 8)).ranges
[(0, 1), (0, 3), (0, 7)]
>>> Indexed('A', Idx('i', 3), Idx('j', 3), Idx('k', 3)).ranges
[(0, 2), (0, 2), (0, 2)]
>>> x, y, z = symbols('x y z', integer=True)
>>> Indexed('A', x, y, z).ranges
[None, None, None]
"""
ranges = []
for i in self.indices:
sentinel = object()
upper = getattr(i, 'upper', sentinel)
lower = getattr(i, 'lower', sentinel)
if sentinel not in (upper, lower):
ranges.append(Tuple(lower, upper))
else:
ranges.append(None)
return ranges
def _sympystr(self, p):
indices = list(map(p.doprint, self.indices))
return "%s[%s]" % (p.doprint(self.base), ", ".join(indices))
@property
def free_symbols(self):
base_free_symbols = self.base.free_symbols
indices_free_symbols = {
fs for i in self.indices for fs in i.free_symbols}
if base_free_symbols:
return {self} | base_free_symbols | indices_free_symbols
else:
return indices_free_symbols
@property
def expr_free_symbols(self):
from sympy.utilities.exceptions import SymPyDeprecationWarning
SymPyDeprecationWarning(feature="expr_free_symbols method",
issue=21494,
deprecated_since_version="1.9").warn()
return {self}
class IndexedBase(Expr, NotIterable):
"""Represent the base or stem of an indexed object
The IndexedBase class represent an array that contains elements. The main purpose
of this class is to allow the convenient creation of objects of the Indexed
class. The __getitem__ method of IndexedBase returns an instance of
Indexed. Alone, without indices, the IndexedBase class can be used as a
notation for e.g. matrix equations, resembling what you could do with the
Symbol class. But, the IndexedBase class adds functionality that is not
available for Symbol instances:
- An IndexedBase object can optionally store shape information. This can
be used in to check array conformance and conditions for numpy
broadcasting. (TODO)
- An IndexedBase object implements syntactic sugar that allows easy symbolic
representation of array operations, using implicit summation of
repeated indices.
- The IndexedBase object symbolizes a mathematical structure equivalent
to arrays, and is recognized as such for code generation and automatic
compilation and wrapping.
>>> from sympy.tensor import IndexedBase, Idx
>>> from sympy import symbols
>>> A = IndexedBase('A'); A
A
>>> type(A)
<class 'sympy.tensor.indexed.IndexedBase'>
When an IndexedBase object receives indices, it returns an array with named
axes, represented by an Indexed object:
>>> i, j = symbols('i j', integer=True)
>>> A[i, j, 2]
A[i, j, 2]
>>> type(A[i, j, 2])
<class 'sympy.tensor.indexed.Indexed'>
The IndexedBase constructor takes an optional shape argument. If given,
it overrides any shape information in the indices. (But not the index
ranges!)
>>> m, n, o, p = symbols('m n o p', integer=True)
>>> i = Idx('i', m)
>>> j = Idx('j', n)
>>> A[i, j].shape
(m, n)
>>> B = IndexedBase('B', shape=(o, p))
>>> B[i, j].shape
(o, p)
Assumptions can be specified with keyword arguments the same way as for Symbol:
>>> A_real = IndexedBase('A', real=True)
>>> A_real.is_real
True
>>> A != A_real
True
Assumptions can also be inherited if a Symbol is used to initialize the IndexedBase:
>>> I = symbols('I', integer=True)
>>> C_inherit = IndexedBase(I)
>>> C_explicit = IndexedBase('I', integer=True)
>>> C_inherit == C_explicit
True
"""
is_commutative = True
is_symbol = True
is_Atom = True
@staticmethod
def _set_assumptions(obj, assumptions):
"""Set assumptions on obj, making sure to apply consistent values."""
tmp_asm_copy = assumptions.copy()
is_commutative = fuzzy_bool(assumptions.get('commutative', True))
assumptions['commutative'] = is_commutative
obj._assumptions = StdFactKB(assumptions)
obj._assumptions._generator = tmp_asm_copy # Issue #8873
def __new__(cls, label, shape=None, *, offset=S.Zero, strides=None, **kw_args):
from sympy import MatrixBase, NDimArray
assumptions, kw_args = _filter_assumptions(kw_args)
if isinstance(label, str):
label = Symbol(label, **assumptions)
elif isinstance(label, Symbol):
assumptions = label._merge(assumptions)
elif isinstance(label, (MatrixBase, NDimArray)):
return label
elif isinstance(label, Iterable):
return _sympify(label)
else:
label = _sympify(label)
if is_sequence(shape):
shape = Tuple(*shape)
elif shape is not None:
shape = Tuple(shape)
if shape is not None:
obj = Expr.__new__(cls, label, shape)
else:
obj = Expr.__new__(cls, label)
obj._shape = shape
obj._offset = offset
obj._strides = strides
obj._name = str(label)
IndexedBase._set_assumptions(obj, assumptions)
return obj
@property
def name(self):
return self._name
def _hashable_content(self):
return super()._hashable_content() + tuple(sorted(self.assumptions0.items()))
@property
def assumptions0(self):
return {k: v for k, v in self._assumptions.items() if v is not None}
def __getitem__(self, indices, **kw_args):
if is_sequence(indices):
# Special case needed because M[*my_tuple] is a syntax error.
if self.shape and len(self.shape) != len(indices):
raise IndexException("Rank mismatch.")
return Indexed(self, *indices, **kw_args)
else:
if self.shape and len(self.shape) != 1:
raise IndexException("Rank mismatch.")
return Indexed(self, indices, **kw_args)
@property
def shape(self):
"""Returns the shape of the ``IndexedBase`` object.
Examples
========
>>> from sympy import IndexedBase, Idx
>>> from sympy.abc import x, y
>>> IndexedBase('A', shape=(x, y)).shape
(x, y)
Note: If the shape of the ``IndexedBase`` is specified, it will override
any shape information given by the indices.
>>> A = IndexedBase('A', shape=(x, y))
>>> B = IndexedBase('B')
>>> i = Idx('i', 2)
>>> j = Idx('j', 1)
>>> A[i, j].shape
(x, y)
>>> B[i, j].shape
(2, 1)
"""
return self._shape
@property
def strides(self):
"""Returns the strided scheme for the ``IndexedBase`` object.
Normally this is a tuple denoting the number of
steps to take in the respective dimension when traversing
an array. For code generation purposes strides='C' and
strides='F' can also be used.
strides='C' would mean that code printer would unroll
in row-major order and 'F' means unroll in column major
order.
"""
return self._strides
@property
def offset(self):
"""Returns the offset for the ``IndexedBase`` object.
This is the value added to the resulting index when the
2D Indexed object is unrolled to a 1D form. Used in code
generation.
Examples
==========
>>> from sympy.printing import ccode
>>> from sympy.tensor import IndexedBase, Idx
>>> from sympy import symbols
>>> l, m, n, o = symbols('l m n o', integer=True)
>>> A = IndexedBase('A', strides=(l, m, n), offset=o)
>>> i, j, k = map(Idx, 'ijk')
>>> ccode(A[i, j, k])
'A[l*i + m*j + n*k + o]'
"""
return self._offset
@property
def label(self):
"""Returns the label of the ``IndexedBase`` object.
Examples
========
>>> from sympy import IndexedBase
>>> from sympy.abc import x, y
>>> IndexedBase('A', shape=(x, y)).label
A
"""
return self.args[0]
def _sympystr(self, p):
return p.doprint(self.label)
class Idx(Expr):
"""Represents an integer index as an ``Integer`` or integer expression.
There are a number of ways to create an ``Idx`` object. The constructor
takes two arguments:
``label``
An integer or a symbol that labels the index.
``range``
Optionally you can specify a range as either
* ``Symbol`` or integer: This is interpreted as a dimension. Lower and
upper bounds are set to ``0`` and ``range - 1``, respectively.
* ``tuple``: The two elements are interpreted as the lower and upper
bounds of the range, respectively.
Note: bounds of the range are assumed to be either integer or infinite (oo
and -oo are allowed to specify an unbounded range). If ``n`` is given as a
bound, then ``n.is_integer`` must not return false.
For convenience, if the label is given as a string it is automatically
converted to an integer symbol. (Note: this conversion is not done for
range or dimension arguments.)
Examples
========
>>> from sympy import Idx, symbols, oo
>>> n, i, L, U = symbols('n i L U', integer=True)
If a string is given for the label an integer ``Symbol`` is created and the
bounds are both ``None``:
>>> idx = Idx('qwerty'); idx
qwerty
>>> idx.lower, idx.upper
(None, None)
Both upper and lower bounds can be specified:
>>> idx = Idx(i, (L, U)); idx
i
>>> idx.lower, idx.upper
(L, U)
When only a single bound is given it is interpreted as the dimension
and the lower bound defaults to 0:
>>> idx = Idx(i, n); idx.lower, idx.upper
(0, n - 1)
>>> idx = Idx(i, 4); idx.lower, idx.upper
(0, 3)
>>> idx = Idx(i, oo); idx.lower, idx.upper
(0, oo)
"""
is_integer = True
is_finite = True
is_real = True
is_symbol = True
is_Atom = True
_diff_wrt = True
def __new__(cls, label, range=None, **kw_args):
from sympy.utilities.misc import filldedent
if isinstance(label, str):
label = Symbol(label, integer=True)
label, range = list(map(sympify, (label, range)))
if label.is_Number:
if not label.is_integer:
raise TypeError("Index is not an integer number.")
return label
if not label.is_integer:
raise TypeError("Idx object requires an integer label.")
elif is_sequence(range):
if len(range) != 2:
raise ValueError(filldedent("""
Idx range tuple must have length 2, but got %s""" % len(range)))
for bound in range:
if (bound.is_integer is False and bound is not S.Infinity
and bound is not S.NegativeInfinity):
raise TypeError("Idx object requires integer bounds.")
args = label, Tuple(*range)
elif isinstance(range, Expr):
if range is not S.Infinity and fuzzy_not(range.is_integer):
raise TypeError("Idx object requires an integer dimension.")
args = label, Tuple(0, range - 1)
elif range:
raise TypeError(filldedent("""
The range must be an ordered iterable or
integer SymPy expression."""))
else:
args = label,
obj = Expr.__new__(cls, *args, **kw_args)
obj._assumptions["finite"] = True
obj._assumptions["real"] = True
return obj
@property
def label(self):
"""Returns the label (Integer or integer expression) of the Idx object.
Examples
========
>>> from sympy import Idx, Symbol
>>> x = Symbol('x', integer=True)
>>> Idx(x).label
x
>>> j = Symbol('j', integer=True)
>>> Idx(j).label
j
>>> Idx(j + 1).label
j + 1
"""
return self.args[0]
@property
def lower(self):
"""Returns the lower bound of the ``Idx``.
Examples
========
>>> from sympy import Idx
>>> Idx('j', 2).lower
0
>>> Idx('j', 5).lower
0
>>> Idx('j').lower is None
True
"""
try:
return self.args[1][0]
except IndexError:
return
@property
def upper(self):
"""Returns the upper bound of the ``Idx``.
Examples
========
>>> from sympy import Idx
>>> Idx('j', 2).upper
1
>>> Idx('j', 5).upper
4
>>> Idx('j').upper is None
True
"""
try:
return self.args[1][1]
except IndexError:
return
def _sympystr(self, p):
return p.doprint(self.label)
@property
def name(self):
return self.label.name if self.label.is_Symbol else str(self.label)
@property
def free_symbols(self):
return {self}
@dispatch(Idx, Idx)
def _eval_is_ge(lhs, rhs): # noqa:F811
other_upper = rhs if rhs.upper is None else rhs.upper
other_lower = rhs if rhs.lower is None else rhs.lower
if lhs.lower is not None and (lhs.lower >= other_upper) == True:
return True
if lhs.upper is not None and (lhs.upper < other_lower) == True:
return False
return None
@dispatch(Idx, Number) # type:ignore
def _eval_is_ge(lhs, rhs): # noqa:F811
other_upper = rhs
other_lower = rhs
if lhs.lower is not None and (lhs.lower >= other_upper) == True:
return True
if lhs.upper is not None and (lhs.upper < other_lower) == True:
return False
return None
@dispatch(Number, Idx) # type:ignore
def _eval_is_ge(lhs, rhs): # noqa:F811
other_upper = lhs
other_lower = lhs
if rhs.upper is not None and (rhs.upper <= other_lower) == True:
return True
if rhs.lower is not None and (rhs.lower > other_upper) == True:
return False
return None
|
a973cafcb8bfdb1b18efa83404b61cea4a42886180a00bc3cc3911b9b2d6eb90 | """
Boolean algebra module for SymPy
"""
from collections import defaultdict
from itertools import chain, combinations, product
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.cache import cacheit
from sympy.core.compatibility import ordered, as_int
from sympy.core.decorators import sympify_method_args, sympify_return
from sympy.core.function import Application, Derivative
from sympy.core.numbers import Number
from sympy.core.operations import LatticeOp
from sympy.core.singleton import Singleton, S
from sympy.core.sympify import converter, _sympify, sympify
from sympy.core.kind import BooleanKind
from sympy.utilities.iterables import sift, ibin
from sympy.utilities.misc import filldedent
def as_Boolean(e):
"""Like bool, return the Boolean value of an expression, e,
which can be any instance of Boolean or bool.
Examples
========
>>> from sympy import true, false, nan
>>> from sympy.logic.boolalg import as_Boolean
>>> from sympy.abc import x
>>> as_Boolean(0) is false
True
>>> as_Boolean(1) is true
True
>>> as_Boolean(x)
x
>>> as_Boolean(2)
Traceback (most recent call last):
...
TypeError: expecting bool or Boolean, not `2`.
>>> as_Boolean(nan)
Traceback (most recent call last):
...
TypeError: expecting bool or Boolean, not `nan`.
"""
from sympy.core.symbol import Symbol
if e == True:
return S.true
if e == False:
return S.false
if isinstance(e, Symbol):
z = e.is_zero
if z is None:
return e
return S.false if z else S.true
if isinstance(e, Boolean):
return e
raise TypeError('expecting bool or Boolean, not `%s`.' % e)
@sympify_method_args
class Boolean(Basic):
"""A boolean object is an object for which logic operations make sense."""
__slots__ = ()
kind = BooleanKind
@sympify_return([('other', 'Boolean')], NotImplemented)
def __and__(self, other):
return And(self, other)
__rand__ = __and__
@sympify_return([('other', 'Boolean')], NotImplemented)
def __or__(self, other):
return Or(self, other)
__ror__ = __or__
def __invert__(self):
"""Overloading for ~"""
return Not(self)
@sympify_return([('other', 'Boolean')], NotImplemented)
def __rshift__(self, other):
return Implies(self, other)
@sympify_return([('other', 'Boolean')], NotImplemented)
def __lshift__(self, other):
return Implies(other, self)
__rrshift__ = __lshift__
__rlshift__ = __rshift__
@sympify_return([('other', 'Boolean')], NotImplemented)
def __xor__(self, other):
return Xor(self, other)
__rxor__ = __xor__
def equals(self, other):
"""
Returns True if the given formulas have the same truth table.
For two formulas to be equal they must have the same literals.
Examples
========
>>> from sympy.abc import A, B, C
>>> from sympy.logic.boolalg import And, Or, Not
>>> (A >> B).equals(~B >> ~A)
True
>>> Not(And(A, B, C)).equals(And(Not(A), Not(B), Not(C)))
False
>>> Not(And(A, Not(A))).equals(Or(B, Not(B)))
False
"""
from sympy.logic.inference import satisfiable
from sympy.core.relational import Relational
if self.has(Relational) or other.has(Relational):
raise NotImplementedError('handling of relationals')
return self.atoms() == other.atoms() and \
not satisfiable(Not(Equivalent(self, other)))
def to_nnf(self, simplify=True):
# override where necessary
return self
def as_set(self):
"""
Rewrites Boolean expression in terms of real sets.
Examples
========
>>> from sympy import Symbol, Eq, Or, And
>>> x = Symbol('x', real=True)
>>> Eq(x, 0).as_set()
FiniteSet(0)
>>> (x > 0).as_set()
Interval.open(0, oo)
>>> And(-2 < x, x < 2).as_set()
Interval.open(-2, 2)
>>> Or(x < -2, 2 < x).as_set()
Union(Interval.open(-oo, -2), Interval.open(2, oo))
"""
from sympy.calculus.util import periodicity
from sympy.core.relational import Relational
free = self.free_symbols
if len(free) == 1:
x = free.pop()
reps = {}
for r in self.atoms(Relational):
if periodicity(r, x) not in (0, None):
s = r._eval_as_set()
if s in (S.EmptySet, S.UniversalSet, S.Reals):
reps[r] = s.as_relational(x)
continue
raise NotImplementedError(filldedent('''
as_set is not implemented for relationals
with periodic solutions
'''))
return self.subs(reps)._eval_as_set()
else:
raise NotImplementedError("Sorry, as_set has not yet been"
" implemented for multivariate"
" expressions")
@property
def binary_symbols(self):
from sympy.core.relational import Eq, Ne
return set().union(*[i.binary_symbols for i in self.args
if i.is_Boolean or i.is_Symbol
or isinstance(i, (Eq, Ne))])
def _eval_refine(self, assumptions):
from sympy.assumptions import ask
ret = ask(self, assumptions)
if ret is True:
return true
elif ret is False:
return false
return None
class BooleanAtom(Boolean):
"""
Base class of BooleanTrue and BooleanFalse.
"""
is_Boolean = True
is_Atom = True
_op_priority = 11 # higher than Expr
def simplify(self, *a, **kw):
return self
def expand(self, *a, **kw):
return self
@property
def canonical(self):
return self
def _noop(self, other=None):
raise TypeError('BooleanAtom not allowed in this context.')
__add__ = _noop
__radd__ = _noop
__sub__ = _noop
__rsub__ = _noop
__mul__ = _noop
__rmul__ = _noop
__pow__ = _noop
__rpow__ = _noop
__truediv__ = _noop
__rtruediv__ = _noop
__mod__ = _noop
__rmod__ = _noop
_eval_power = _noop
# /// drop when Py2 is no longer supported
def __lt__(self, other):
from sympy.utilities.misc import filldedent
raise TypeError(filldedent('''
A Boolean argument can only be used in
Eq and Ne; all other relationals expect
real expressions.
'''))
__le__ = __lt__
__gt__ = __lt__
__ge__ = __lt__
# \\\
class BooleanTrue(BooleanAtom, metaclass=Singleton):
"""
SymPy version of True, a singleton that can be accessed via S.true.
This is the SymPy version of True, for use in the logic module. The
primary advantage of using true instead of True is that shorthand boolean
operations like ~ and >> will work as expected on this class, whereas with
True they act bitwise on 1. Functions in the logic module will return this
class when they evaluate to true.
Notes
=====
There is liable to be some confusion as to when ``True`` should
be used and when ``S.true`` should be used in various contexts
throughout SymPy. An important thing to remember is that
``sympify(True)`` returns ``S.true``. This means that for the most
part, you can just use ``True`` and it will automatically be converted
to ``S.true`` when necessary, similar to how you can generally use 1
instead of ``S.One``.
The rule of thumb is:
"If the boolean in question can be replaced by an arbitrary symbolic
``Boolean``, like ``Or(x, y)`` or ``x > 1``, use ``S.true``.
Otherwise, use ``True``"
In other words, use ``S.true`` only on those contexts where the
boolean is being used as a symbolic representation of truth.
For example, if the object ends up in the ``.args`` of any expression,
then it must necessarily be ``S.true`` instead of ``True``, as
elements of ``.args`` must be ``Basic``. On the other hand,
``==`` is not a symbolic operation in SymPy, since it always returns
``True`` or ``False``, and does so in terms of structural equality
rather than mathematical, so it should return ``True``. The assumptions
system should use ``True`` and ``False``. Aside from not satisfying
the above rule of thumb, the assumptions system uses a three-valued logic
(``True``, ``False``, ``None``), whereas ``S.true`` and ``S.false``
represent a two-valued logic. When in doubt, use ``True``.
"``S.true == True is True``."
While "``S.true is True``" is ``False``, "``S.true == True``"
is ``True``, so if there is any doubt over whether a function or
expression will return ``S.true`` or ``True``, just use ``==``
instead of ``is`` to do the comparison, and it will work in either
case. Finally, for boolean flags, it's better to just use ``if x``
instead of ``if x is True``. To quote PEP 8:
Don't compare boolean values to ``True`` or ``False``
using ``==``.
* Yes: ``if greeting:``
* No: ``if greeting == True:``
* Worse: ``if greeting is True:``
Examples
========
>>> from sympy import sympify, true, false, Or
>>> sympify(True)
True
>>> _ is True, _ is true
(False, True)
>>> Or(true, false)
True
>>> _ is true
True
Python operators give a boolean result for true but a
bitwise result for True
>>> ~true, ~True
(False, -2)
>>> true >> true, True >> True
(True, 0)
Python operators give a boolean result for true but a
bitwise result for True
>>> ~true, ~True
(False, -2)
>>> true >> true, True >> True
(True, 0)
See Also
========
sympy.logic.boolalg.BooleanFalse
"""
def __bool__(self):
return True
def __hash__(self):
return hash(True)
@property
def negated(self):
return S.false
def as_set(self):
"""
Rewrite logic operators and relationals in terms of real sets.
Examples
========
>>> from sympy import true
>>> true.as_set()
UniversalSet
"""
return S.UniversalSet
class BooleanFalse(BooleanAtom, metaclass=Singleton):
"""
SymPy version of False, a singleton that can be accessed via S.false.
This is the SymPy version of False, for use in the logic module. The
primary advantage of using false instead of False is that shorthand boolean
operations like ~ and >> will work as expected on this class, whereas with
False they act bitwise on 0. Functions in the logic module will return this
class when they evaluate to false.
Notes
======
See the notes section in :py:class:`sympy.logic.boolalg.BooleanTrue`
Examples
========
>>> from sympy import sympify, true, false, Or
>>> sympify(False)
False
>>> _ is False, _ is false
(False, True)
>>> Or(true, false)
True
>>> _ is true
True
Python operators give a boolean result for false but a
bitwise result for False
>>> ~false, ~False
(True, -1)
>>> false >> false, False >> False
(True, 0)
See Also
========
sympy.logic.boolalg.BooleanTrue
"""
def __bool__(self):
return False
def __hash__(self):
return hash(False)
@property
def negated(self):
return S.true
def as_set(self):
"""
Rewrite logic operators and relationals in terms of real sets.
Examples
========
>>> from sympy import false
>>> false.as_set()
EmptySet
"""
return S.EmptySet
true = BooleanTrue()
false = BooleanFalse()
# We want S.true and S.false to work, rather than S.BooleanTrue and
# S.BooleanFalse, but making the class and instance names the same causes some
# major issues (like the inability to import the class directly from this
# file).
S.true = true
S.false = false
converter[bool] = lambda x: S.true if x else S.false
class BooleanFunction(Application, Boolean):
"""Boolean function is a function that lives in a boolean space
It is used as base class for And, Or, Not, etc.
"""
is_Boolean = True
def _eval_simplify(self, **kwargs):
rv = self.func(*[a.simplify(**kwargs) for a in self.args])
return simplify_logic(rv)
def simplify(self, **kwargs):
from sympy.simplify.simplify import simplify
return simplify(self, **kwargs)
def __lt__(self, other):
from sympy.utilities.misc import filldedent
raise TypeError(filldedent('''
A Boolean argument can only be used in
Eq and Ne; all other relationals expect
real expressions.
'''))
__le__ = __lt__
__ge__ = __lt__
__gt__ = __lt__
@classmethod
def binary_check_and_simplify(self, *args):
from sympy.core.relational import Relational, Eq, Ne
args = [as_Boolean(i) for i in args]
bin = set().union(*[i.binary_symbols for i in args])
rel = set().union(*[i.atoms(Relational) for i in args])
reps = {}
for x in bin:
for r in rel:
if x in bin and x in r.free_symbols:
if isinstance(r, (Eq, Ne)):
if not (
S.true in r.args or
S.false in r.args):
reps[r] = S.false
else:
raise TypeError(filldedent('''
Incompatible use of binary symbol `%s` as a
real variable in `%s`
''' % (x, r)))
return [i.subs(reps) for i in args]
def to_nnf(self, simplify=True):
return self._to_nnf(*self.args, simplify=simplify)
def to_anf(self, deep=True):
return self._to_anf(*self.args, deep=deep)
@classmethod
def _to_nnf(cls, *args, **kwargs):
simplify = kwargs.get('simplify', True)
argset = set()
for arg in args:
if not is_literal(arg):
arg = arg.to_nnf(simplify)
if simplify:
if isinstance(arg, cls):
arg = arg.args
else:
arg = (arg,)
for a in arg:
if Not(a) in argset:
return cls.zero
argset.add(a)
else:
argset.add(arg)
return cls(*argset)
@classmethod
def _to_anf(cls, *args, **kwargs):
deep = kwargs.get('deep', True)
argset = set()
for arg in args:
if deep:
if not is_literal(arg) or isinstance(arg, Not):
arg = arg.to_anf(deep=deep)
argset.add(arg)
else:
argset.add(arg)
return cls(*argset, remove_true=False)
# the diff method below is copied from Expr class
def diff(self, *symbols, **assumptions):
assumptions.setdefault("evaluate", True)
return Derivative(self, *symbols, **assumptions)
def _eval_derivative(self, x):
from sympy.core.relational import Eq
from sympy.functions.elementary.piecewise import Piecewise
if x in self.binary_symbols:
return Piecewise(
(0, Eq(self.subs(x, 0), self.subs(x, 1))),
(1, True))
elif x in self.free_symbols:
# not implemented, see https://www.encyclopediaofmath.org/
# index.php/Boolean_differential_calculus
pass
else:
return S.Zero
def _apply_patternbased_simplification(self, rv, patterns, measure,
dominatingvalue,
replacementvalue=None):
"""
Replace patterns of Relational
Parameters
==========
rv : Expr
Boolean expression
patterns : tuple
Tuple of tuples, with (pattern to simplify, simplified pattern)
measure : function
Simplification measure
dominatingvalue : boolean or None
The dominating value for the function of consideration.
For example, for And S.false is dominating. As soon as one
expression is S.false in And, the whole expression is S.false.
replacementvalue : boolean or None, optional
The resulting value for the whole expression if one argument
evaluates to dominatingvalue.
For example, for Nand S.false is dominating, but in this case
the resulting value is S.true. Default is None. If replacementvalue
is None and dominatingvalue is not None,
replacementvalue = dominatingvalue
"""
from sympy.core.relational import Relational, _canonical
if replacementvalue is None and dominatingvalue is not None:
replacementvalue = dominatingvalue
# Use replacement patterns for Relationals
changed = True
Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational),
binary=True)
if len(Rel) <= 1:
return rv
Rel, nonRealRel = sift(Rel, lambda i: all(s.is_real is not False
for s in i.free_symbols),
binary=True)
Rel = [i.canonical for i in Rel]
while changed and len(Rel) >= 2:
changed = False
# Sort based on ordered
Rel = list(ordered(Rel))
# Create a list of possible replacements
results = []
# Try all combinations
for ((i, pi), (j, pj)) in combinations(enumerate(Rel), 2):
for k, (pattern, simp) in enumerate(patterns):
res = []
# use SymPy matching
oldexpr = rv.func(pi, pj)
tmpres = oldexpr.match(pattern)
if tmpres:
res.append((tmpres, oldexpr))
# Try reversing first relational
# This and the rest should not be required with a better
# canonical
oldexpr = rv.func(pi.reversed, pj)
tmpres = oldexpr.match(pattern)
if tmpres:
res.append((tmpres, oldexpr))
# Try reversing second relational
oldexpr = rv.func(pi, pj.reversed)
tmpres = oldexpr.match(pattern)
if tmpres:
res.append((tmpres, oldexpr))
# Try reversing both relationals
oldexpr = rv.func(pi.reversed, pj.reversed)
tmpres = oldexpr.match(pattern)
if tmpres:
res.append((tmpres, oldexpr))
if res:
for tmpres, oldexpr in res:
# we have a matching, compute replacement
np = simp.subs(tmpres)
if np == dominatingvalue:
# if dominatingvalue, the whole expression
# will be replacementvalue
return replacementvalue
# add replacement
if not isinstance(np, ITE):
# We only want to use ITE replacements if
# they simplify to a relational
costsaving = measure(oldexpr) - measure(np)
if costsaving > 0:
results.append((costsaving, (i, j, np)))
if results:
# Sort results based on complexity
results = list(reversed(sorted(results,
key=lambda pair: pair[0])))
# Replace the one providing most simplification
cost, replacement = results[0]
i, j, newrel = replacement
# Remove the old relationals
del Rel[j]
del Rel[i]
if dominatingvalue is None or newrel != ~dominatingvalue:
# Insert the new one (no need to insert a value that will
# not affect the result)
Rel.append(newrel)
# We did change something so try again
changed = True
rv = rv.func(*([_canonical(i) for i in ordered(Rel)]
+ nonRel + nonRealRel))
return rv
class And(LatticeOp, BooleanFunction):
"""
Logical AND function.
It evaluates its arguments in order, giving False immediately
if any of them are False, and True if they are all True.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.logic.boolalg import And
>>> x & y
x & y
Notes
=====
The ``&`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise
and. Hence, ``And(a, b)`` and ``a & b`` will return different things if
``a`` and ``b`` are integers.
>>> And(x, y).subs(x, 1)
y
"""
zero = false
identity = true
nargs = None
@classmethod
def _new_args_filter(cls, args):
args = BooleanFunction.binary_check_and_simplify(*args)
args = LatticeOp._new_args_filter(args, And)
newargs = []
rel = set()
for x in ordered(args):
if x.is_Relational:
c = x.canonical
if c in rel:
continue
elif c.negated.canonical in rel:
return [S.false]
else:
rel.add(c)
newargs.append(x)
return newargs
def _eval_subs(self, old, new):
args = []
bad = None
for i in self.args:
try:
i = i.subs(old, new)
except TypeError:
# store TypeError
if bad is None:
bad = i
continue
if i == False:
return S.false
elif i != True:
args.append(i)
if bad is not None:
# let it raise
bad.subs(old, new)
return self.func(*args)
def _eval_simplify(self, **kwargs):
from sympy.core.relational import Equality, Relational
from sympy.solvers.solveset import linear_coeffs
# standard simplify
rv = super()._eval_simplify(**kwargs)
if not isinstance(rv, And):
return rv
# simplify args that are equalities involving
# symbols so x == 0 & x == y -> x==0 & y == 0
Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational),
binary=True)
if not Rel:
return rv
eqs, other = sift(Rel, lambda i: isinstance(i, Equality), binary=True)
if not eqs:
return rv
measure, ratio = kwargs['measure'], kwargs['ratio']
reps = {}
sifted = {}
if eqs:
# group by length of free symbols
sifted = sift(ordered([
(i.free_symbols, i) for i in eqs]),
lambda x: len(x[0]))
eqs = []
while 1 in sifted:
for free, e in sifted.pop(1):
x = free.pop()
if e.lhs != x or x in e.rhs.free_symbols:
try:
m, b = linear_coeffs(
e.rewrite(Add, evaluate=False), x)
enew = e.func(x, -b/m)
if measure(enew) <= ratio*measure(e):
e = enew
else:
eqs.append(e)
continue
except ValueError:
pass
if x in reps:
eqs.append(e.func(e.rhs, reps[x]))
else:
reps[x] = e.rhs
eqs.append(e)
resifted = defaultdict(list)
for k in sifted:
for f, e in sifted[k]:
e = e.subs(reps)
f = e.free_symbols
resifted[len(f)].append((f, e))
sifted = resifted
for k in sifted:
eqs.extend([e for f, e in sifted[k]])
other = [ei.subs(reps) for ei in other]
rv = rv.func(*([i.canonical for i in (eqs + other)] + nonRel))
patterns = simplify_patterns_and()
return self._apply_patternbased_simplification(rv, patterns,
measure, False)
def _eval_as_set(self):
from sympy.sets.sets import Intersection
return Intersection(*[arg.as_set() for arg in self.args])
def _eval_rewrite_as_Nor(self, *args, **kwargs):
return Nor(*[Not(arg) for arg in self.args])
def to_anf(self, deep=True):
if deep:
result = And._to_anf(*self.args, deep=deep)
return distribute_xor_over_and(result)
return self
class Or(LatticeOp, BooleanFunction):
"""
Logical OR function
It evaluates its arguments in order, giving True immediately
if any of them are True, and False if they are all False.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.logic.boolalg import Or
>>> x | y
x | y
Notes
=====
The ``|`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise
or. Hence, ``Or(a, b)`` and ``a | b`` will return different things if
``a`` and ``b`` are integers.
>>> Or(x, y).subs(x, 0)
y
"""
zero = true
identity = false
@classmethod
def _new_args_filter(cls, args):
newargs = []
rel = []
args = BooleanFunction.binary_check_and_simplify(*args)
for x in args:
if x.is_Relational:
c = x.canonical
if c in rel:
continue
nc = c.negated.canonical
if any(r == nc for r in rel):
return [S.true]
rel.append(c)
newargs.append(x)
return LatticeOp._new_args_filter(newargs, Or)
def _eval_subs(self, old, new):
args = []
bad = None
for i in self.args:
try:
i = i.subs(old, new)
except TypeError:
# store TypeError
if bad is None:
bad = i
continue
if i == True:
return S.true
elif i != False:
args.append(i)
if bad is not None:
# let it raise
bad.subs(old, new)
return self.func(*args)
def _eval_as_set(self):
from sympy.sets.sets import Union
return Union(*[arg.as_set() for arg in self.args])
def _eval_rewrite_as_Nand(self, *args, **kwargs):
return Nand(*[Not(arg) for arg in self.args])
def _eval_simplify(self, **kwargs):
# standard simplify
rv = super()._eval_simplify(**kwargs)
if not isinstance(rv, Or):
return rv
patterns = simplify_patterns_or()
return self._apply_patternbased_simplification(rv, patterns,
kwargs['measure'], S.true)
def to_anf(self, deep=True):
args = range(1, len(self.args) + 1)
args = (combinations(self.args, j) for j in args)
args = chain.from_iterable(args) # powerset
args = (And(*arg) for arg in args)
args = map(lambda x: to_anf(x, deep=deep) if deep else x, args)
return Xor(*list(args), remove_true=False)
class Not(BooleanFunction):
"""
Logical Not function (negation)
Returns True if the statement is False
Returns False if the statement is True
Examples
========
>>> from sympy.logic.boolalg import Not, And, Or
>>> from sympy.abc import x, A, B
>>> Not(True)
False
>>> Not(False)
True
>>> Not(And(True, False))
True
>>> Not(Or(True, False))
False
>>> Not(And(And(True, x), Or(x, False)))
~x
>>> ~x
~x
>>> Not(And(Or(A, B), Or(~A, ~B)))
~((A | B) & (~A | ~B))
Notes
=====
- The ``~`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise
not. In particular, ``~a`` and ``Not(a)`` will be different if ``a`` is
an integer. Furthermore, since bools in Python subclass from ``int``,
``~True`` is the same as ``~1`` which is ``-2``, which has a boolean
value of True. To avoid this issue, use the SymPy boolean types
``true`` and ``false``.
>>> from sympy import true
>>> ~True
-2
>>> ~true
False
"""
is_Not = True
@classmethod
def eval(cls, arg):
if isinstance(arg, Number) or arg in (True, False):
return false if arg else true
if arg.is_Not:
return arg.args[0]
# Simplify Relational objects.
if arg.is_Relational:
return arg.negated
def _eval_as_set(self):
"""
Rewrite logic operators and relationals in terms of real sets.
Examples
========
>>> from sympy import Not, Symbol
>>> x = Symbol('x')
>>> Not(x > 0).as_set()
Interval(-oo, 0)
"""
return self.args[0].as_set().complement(S.Reals)
def to_nnf(self, simplify=True):
if is_literal(self):
return self
expr = self.args[0]
func, args = expr.func, expr.args
if func == And:
return Or._to_nnf(*[~arg for arg in args], simplify=simplify)
if func == Or:
return And._to_nnf(*[~arg for arg in args], simplify=simplify)
if func == Implies:
a, b = args
return And._to_nnf(a, ~b, simplify=simplify)
if func == Equivalent:
return And._to_nnf(Or(*args), Or(*[~arg for arg in args]),
simplify=simplify)
if func == Xor:
result = []
for i in range(1, len(args)+1, 2):
for neg in combinations(args, i):
clause = [~s if s in neg else s for s in args]
result.append(Or(*clause))
return And._to_nnf(*result, simplify=simplify)
if func == ITE:
a, b, c = args
return And._to_nnf(Or(a, ~c), Or(~a, ~b), simplify=simplify)
raise ValueError("Illegal operator %s in expression" % func)
def to_anf(self, deep=True):
return Xor._to_anf(true, self.args[0], deep=deep)
class Xor(BooleanFunction):
"""
Logical XOR (exclusive OR) function.
Returns True if an odd number of the arguments are True and the rest are
False.
Returns False if an even number of the arguments are True and the rest are
False.
Examples
========
>>> from sympy.logic.boolalg import Xor
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Xor(True, False)
True
>>> Xor(True, True)
False
>>> Xor(True, False, True, True, False)
True
>>> Xor(True, False, True, False)
False
>>> x ^ y
x ^ y
Notes
=====
The ``^`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise xor. In
particular, ``a ^ b`` and ``Xor(a, b)`` will be different if ``a`` and
``b`` are integers.
>>> Xor(x, y).subs(y, 0)
x
"""
def __new__(cls, *args, remove_true=True, **kwargs):
argset = set()
obj = super().__new__(cls, *args, **kwargs)
for arg in obj._args:
if isinstance(arg, Number) or arg in (True, False):
if arg:
arg = true
else:
continue
if isinstance(arg, Xor):
for a in arg.args:
argset.remove(a) if a in argset else argset.add(a)
elif arg in argset:
argset.remove(arg)
else:
argset.add(arg)
rel = [(r, r.canonical, r.negated.canonical)
for r in argset if r.is_Relational]
odd = False # is number of complimentary pairs odd? start 0 -> False
remove = []
for i, (r, c, nc) in enumerate(rel):
for j in range(i + 1, len(rel)):
rj, cj = rel[j][:2]
if cj == nc:
odd = ~odd
break
elif cj == c:
break
else:
continue
remove.append((r, rj))
if odd:
argset.remove(true) if true in argset else argset.add(true)
for a, b in remove:
argset.remove(a)
argset.remove(b)
if len(argset) == 0:
return false
elif len(argset) == 1:
return argset.pop()
elif True in argset and remove_true:
argset.remove(True)
return Not(Xor(*argset))
else:
obj._args = tuple(ordered(argset))
obj._argset = frozenset(argset)
return obj
# XXX: This should be cached on the object rather than using cacheit
# Maybe it can be computed in __new__?
@property # type: ignore
@cacheit
def args(self):
return tuple(ordered(self._argset))
def to_nnf(self, simplify=True):
args = []
for i in range(0, len(self.args)+1, 2):
for neg in combinations(self.args, i):
clause = [~s if s in neg else s for s in self.args]
args.append(Or(*clause))
return And._to_nnf(*args, simplify=simplify)
def _eval_rewrite_as_Or(self, *args, **kwargs):
a = self.args
return Or(*[_convert_to_varsSOP(x, self.args)
for x in _get_odd_parity_terms(len(a))])
def _eval_rewrite_as_And(self, *args, **kwargs):
a = self.args
return And(*[_convert_to_varsPOS(x, self.args)
for x in _get_even_parity_terms(len(a))])
def _eval_simplify(self, **kwargs):
# as standard simplify uses simplify_logic which writes things as
# And and Or, we only simplify the partial expressions before using
# patterns
rv = self.func(*[a.simplify(**kwargs) for a in self.args])
if not isinstance(rv, Xor): # This shouldn't really happen here
return rv
patterns = simplify_patterns_xor()
return self._apply_patternbased_simplification(rv, patterns,
kwargs['measure'], None)
class Nand(BooleanFunction):
"""
Logical NAND function.
It evaluates its arguments in order, giving True immediately if any
of them are False, and False if they are all True.
Returns True if any of the arguments are False
Returns False if all arguments are True
Examples
========
>>> from sympy.logic.boolalg import Nand
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Nand(False, True)
True
>>> Nand(True, True)
False
>>> Nand(x, y)
~(x & y)
"""
@classmethod
def eval(cls, *args):
return Not(And(*args))
class Nor(BooleanFunction):
"""
Logical NOR function.
It evaluates its arguments in order, giving False immediately if any
of them are True, and True if they are all False.
Returns False if any argument is True
Returns True if all arguments are False
Examples
========
>>> from sympy.logic.boolalg import Nor
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Nor(True, False)
False
>>> Nor(True, True)
False
>>> Nor(False, True)
False
>>> Nor(False, False)
True
>>> Nor(x, y)
~(x | y)
"""
@classmethod
def eval(cls, *args):
return Not(Or(*args))
class Xnor(BooleanFunction):
"""
Logical XNOR function.
Returns False if an odd number of the arguments are True and the rest are
False.
Returns True if an even number of the arguments are True and the rest are
False.
Examples
========
>>> from sympy.logic.boolalg import Xnor
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Xnor(True, False)
False
>>> Xnor(True, True)
True
>>> Xnor(True, False, True, True, False)
False
>>> Xnor(True, False, True, False)
True
"""
@classmethod
def eval(cls, *args):
return Not(Xor(*args))
class Implies(BooleanFunction):
"""
Logical implication.
A implies B is equivalent to !A v B
Accepts two Boolean arguments; A and B.
Returns False if A is True and B is False
Returns True otherwise.
Examples
========
>>> from sympy.logic.boolalg import Implies
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Implies(True, False)
False
>>> Implies(False, False)
True
>>> Implies(True, True)
True
>>> Implies(False, True)
True
>>> x >> y
Implies(x, y)
>>> y << x
Implies(x, y)
Notes
=====
The ``>>`` and ``<<`` operators are provided as a convenience, but note
that their use here is different from their normal use in Python, which is
bit shifts. Hence, ``Implies(a, b)`` and ``a >> b`` will return different
things if ``a`` and ``b`` are integers. In particular, since Python
considers ``True`` and ``False`` to be integers, ``True >> True`` will be
the same as ``1 >> 1``, i.e., 0, which has a truth value of False. To
avoid this issue, use the SymPy objects ``true`` and ``false``.
>>> from sympy import true, false
>>> True >> False
1
>>> true >> false
False
"""
@classmethod
def eval(cls, *args):
try:
newargs = []
for x in args:
if isinstance(x, Number) or x in (0, 1):
newargs.append(True if x else False)
else:
newargs.append(x)
A, B = newargs
except ValueError:
raise ValueError(
"%d operand(s) used for an Implies "
"(pairs are required): %s" % (len(args), str(args)))
if A == True or A == False or B == True or B == False:
return Or(Not(A), B)
elif A == B:
return S.true
elif A.is_Relational and B.is_Relational:
if A.canonical == B.canonical:
return S.true
if A.negated.canonical == B.canonical:
return B
else:
return Basic.__new__(cls, *args)
def to_nnf(self, simplify=True):
a, b = self.args
return Or._to_nnf(~a, b, simplify=simplify)
def to_anf(self, deep=True):
a, b = self.args
return Xor._to_anf(true, a, And(a, b), deep=deep)
class Equivalent(BooleanFunction):
"""
Equivalence relation.
Equivalent(A, B) is True iff A and B are both True or both False
Returns True if all of the arguments are logically equivalent.
Returns False otherwise.
Examples
========
>>> from sympy.logic.boolalg import Equivalent, And
>>> from sympy.abc import x
>>> Equivalent(False, False, False)
True
>>> Equivalent(True, False, False)
False
>>> Equivalent(x, And(x, True))
True
"""
def __new__(cls, *args, **options):
from sympy.core.relational import Relational
args = [_sympify(arg) for arg in args]
argset = set(args)
for x in args:
if isinstance(x, Number) or x in [True, False]: # Includes 0, 1
argset.discard(x)
argset.add(True if x else False)
rel = []
for r in argset:
if isinstance(r, Relational):
rel.append((r, r.canonical, r.negated.canonical))
remove = []
for i, (r, c, nc) in enumerate(rel):
for j in range(i + 1, len(rel)):
rj, cj = rel[j][:2]
if cj == nc:
return false
elif cj == c:
remove.append((r, rj))
break
for a, b in remove:
argset.remove(a)
argset.remove(b)
argset.add(True)
if len(argset) <= 1:
return true
if True in argset:
argset.discard(True)
return And(*argset)
if False in argset:
argset.discard(False)
return And(*[~arg for arg in argset])
_args = frozenset(argset)
obj = super().__new__(cls, _args)
obj._argset = _args
return obj
# XXX: This should be cached on the object rather than using cacheit
# Maybe it can be computed in __new__?
@property # type: ignore
@cacheit
def args(self):
return tuple(ordered(self._argset))
def to_nnf(self, simplify=True):
args = []
for a, b in zip(self.args, self.args[1:]):
args.append(Or(~a, b))
args.append(Or(~self.args[-1], self.args[0]))
return And._to_nnf(*args, simplify=simplify)
def to_anf(self, deep=True):
a = And(*self.args)
b = And(*[to_anf(Not(arg), deep=False) for arg in self.args])
b = distribute_xor_over_and(b)
return Xor._to_anf(a, b, deep=deep)
class ITE(BooleanFunction):
"""
If then else clause.
ITE(A, B, C) evaluates and returns the result of B if A is true
else it returns the result of C. All args must be Booleans.
Examples
========
>>> from sympy.logic.boolalg import ITE, And, Xor, Or
>>> from sympy.abc import x, y, z
>>> ITE(True, False, True)
False
>>> ITE(Or(True, False), And(True, True), Xor(True, True))
True
>>> ITE(x, y, z)
ITE(x, y, z)
>>> ITE(True, x, y)
x
>>> ITE(False, x, y)
y
>>> ITE(x, y, y)
y
Trying to use non-Boolean args will generate a TypeError:
>>> ITE(True, [], ())
Traceback (most recent call last):
...
TypeError: expecting bool, Boolean or ITE, not `[]`
"""
def __new__(cls, *args, **kwargs):
from sympy.core.relational import Eq, Ne
if len(args) != 3:
raise ValueError('expecting exactly 3 args')
a, b, c = args
# check use of binary symbols
if isinstance(a, (Eq, Ne)):
# in this context, we can evaluate the Eq/Ne
# if one arg is a binary symbol and the other
# is true/false
b, c = map(as_Boolean, (b, c))
bin = set().union(*[i.binary_symbols for i in (b, c)])
if len(set(a.args) - bin) == 1:
# one arg is a binary_symbols
_a = a
if a.lhs is S.true:
a = a.rhs
elif a.rhs is S.true:
a = a.lhs
elif a.lhs is S.false:
a = ~a.rhs
elif a.rhs is S.false:
a = ~a.lhs
else:
# binary can only equal True or False
a = S.false
if isinstance(_a, Ne):
a = ~a
else:
a, b, c = BooleanFunction.binary_check_and_simplify(
a, b, c)
rv = None
if kwargs.get('evaluate', True):
rv = cls.eval(a, b, c)
if rv is None:
rv = BooleanFunction.__new__(cls, a, b, c, evaluate=False)
return rv
@classmethod
def eval(cls, *args):
from sympy.core.relational import Eq, Ne
# do the args give a singular result?
a, b, c = args
if isinstance(a, (Ne, Eq)):
_a = a
if S.true in a.args:
a = a.lhs if a.rhs is S.true else a.rhs
elif S.false in a.args:
a = ~a.lhs if a.rhs is S.false else ~a.rhs
else:
_a = None
if _a is not None and isinstance(_a, Ne):
a = ~a
if a is S.true:
return b
if a is S.false:
return c
if b == c:
return b
else:
# or maybe the results allow the answer to be expressed
# in terms of the condition
if b is S.true and c is S.false:
return a
if b is S.false and c is S.true:
return Not(a)
if [a, b, c] != args:
return cls(a, b, c, evaluate=False)
def to_nnf(self, simplify=True):
a, b, c = self.args
return And._to_nnf(Or(~a, b), Or(a, c), simplify=simplify)
def _eval_as_set(self):
return self.to_nnf().as_set()
def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
from sympy.functions import Piecewise
return Piecewise((args[1], args[0]), (args[2], True))
class Exclusive(BooleanFunction):
"""
True if only one or no argument is true.
``Exclusive(A, B, C)`` is equivalent to ``~(A & B) & ~(A & C) & ~(B & C)``.
Examples
========
>>> from sympy.logic.boolalg import Exclusive
>>> Exclusive(False, False, False)
True
>>> Exclusive(False, True, False)
True
>>> Exclusive(False, True, True)
False
"""
@classmethod
def eval(cls, *args):
and_args = []
for a, b in combinations(args, 2):
and_args.append(Not(And(a, b)))
return And(*and_args)
# end class definitions. Some useful methods
def conjuncts(expr):
"""Return a list of the conjuncts in the expr s.
Examples
========
>>> from sympy.logic.boolalg import conjuncts
>>> from sympy.abc import A, B
>>> conjuncts(A & B)
frozenset({A, B})
>>> conjuncts(A | B)
frozenset({A | B})
"""
return And.make_args(expr)
def disjuncts(expr):
"""Return a list of the disjuncts in the sentence s.
Examples
========
>>> from sympy.logic.boolalg import disjuncts
>>> from sympy.abc import A, B
>>> disjuncts(A | B)
frozenset({A, B})
>>> disjuncts(A & B)
frozenset({A & B})
"""
return Or.make_args(expr)
def distribute_and_over_or(expr):
"""
Given a sentence s consisting of conjunctions and disjunctions
of literals, return an equivalent sentence in CNF.
Examples
========
>>> from sympy.logic.boolalg import distribute_and_over_or, And, Or, Not
>>> from sympy.abc import A, B, C
>>> distribute_and_over_or(Or(A, And(Not(B), Not(C))))
(A | ~B) & (A | ~C)
"""
return _distribute((expr, And, Or))
def distribute_or_over_and(expr):
"""
Given a sentence s consisting of conjunctions and disjunctions
of literals, return an equivalent sentence in DNF.
Note that the output is NOT simplified.
Examples
========
>>> from sympy.logic.boolalg import distribute_or_over_and, And, Or, Not
>>> from sympy.abc import A, B, C
>>> distribute_or_over_and(And(Or(Not(A), B), C))
(B & C) | (C & ~A)
"""
return _distribute((expr, Or, And))
def distribute_xor_over_and(expr):
"""
Given a sentence s consisting of conjunction and
exclusive disjunctions of literals, return an
equivalent exclusive disjunction.
Note that the output is NOT simplified.
Examples
========
>>> from sympy.logic.boolalg import distribute_xor_over_and, And, Xor, Not
>>> from sympy.abc import A, B, C
>>> distribute_xor_over_and(And(Xor(Not(A), B), C))
(B & C) ^ (C & ~A)
"""
return _distribute((expr, Xor, And))
def _distribute(info):
"""
Distributes info[1] over info[2] with respect to info[0].
"""
if isinstance(info[0], info[2]):
for arg in info[0].args:
if isinstance(arg, info[1]):
conj = arg
break
else:
return info[0]
rest = info[2](*[a for a in info[0].args if a is not conj])
return info[1](*list(map(_distribute,
[(info[2](c, rest), info[1], info[2])
for c in conj.args])), remove_true=False)
elif isinstance(info[0], info[1]):
return info[1](*list(map(_distribute,
[(x, info[1], info[2])
for x in info[0].args])),
remove_true=False)
else:
return info[0]
def to_anf(expr, deep=True):
r"""
Converts expr to Algebraic Normal Form (ANF).
ANF is a canonical normal form, which means that two
equivalent formulas will convert to the same ANF.
A logical expression is in ANF if it has the form
.. math:: 1 \oplus a \oplus b \oplus ab \oplus abc
i.e. it can be:
- purely true,
- purely false,
- conjunction of variables,
- exclusive disjunction.
The exclusive disjunction can only contain true, variables
or conjunction of variables. No negations are permitted.
If ``deep`` is ``False``, arguments of the boolean
expression are considered variables, i.e. only the
top-level expression is converted to ANF.
Examples
========
>>> from sympy.logic.boolalg import And, Or, Not, Implies, Equivalent
>>> from sympy.logic.boolalg import to_anf
>>> from sympy.abc import A, B, C
>>> to_anf(Not(A))
A ^ True
>>> to_anf(And(Or(A, B), Not(C)))
A ^ B ^ (A & B) ^ (A & C) ^ (B & C) ^ (A & B & C)
>>> to_anf(Implies(Not(A), Equivalent(B, C)), deep=False)
True ^ ~A ^ (~A & (Equivalent(B, C)))
"""
expr = sympify(expr)
if is_anf(expr):
return expr
return expr.to_anf(deep=deep)
def to_nnf(expr, simplify=True):
"""
Converts expr to Negation Normal Form.
A logical expression is in Negation Normal Form (NNF) if it
contains only And, Or and Not, and Not is applied only to literals.
If simplify is True, the result contains no redundant clauses.
Examples
========
>>> from sympy.abc import A, B, C, D
>>> from sympy.logic.boolalg import Not, Equivalent, to_nnf
>>> to_nnf(Not((~A & ~B) | (C & D)))
(A | B) & (~C | ~D)
>>> to_nnf(Equivalent(A >> B, B >> A))
(A | ~B | (A & ~B)) & (B | ~A | (B & ~A))
"""
if is_nnf(expr, simplify):
return expr
return expr.to_nnf(simplify)
def to_cnf(expr, simplify=False, force=False):
"""
Convert a propositional logical sentence s to conjunctive normal
form: ((A | ~B | ...) & (B | C | ...) & ...).
If simplify is True, the expr is evaluated to its simplest CNF
form using the Quine-McCluskey algorithm; this may take a long
time if there are more than 8 variables and requires that the
``force`` flag be set to True (default is False).
Examples
========
>>> from sympy.logic.boolalg import to_cnf
>>> from sympy.abc import A, B, D
>>> to_cnf(~(A | B) | D)
(D | ~A) & (D | ~B)
>>> to_cnf((A | B) & (A | ~A), True)
A | B
"""
expr = sympify(expr)
if not isinstance(expr, BooleanFunction):
return expr
if simplify:
if not force and len(_find_predicates(expr)) > 8:
raise ValueError(filldedent('''
To simplify a logical expression with more
than 8 variables may take a long time and requires
the use of `force=True`.'''))
return simplify_logic(expr, 'cnf', True, force=force)
# Don't convert unless we have to
if is_cnf(expr):
return expr
expr = eliminate_implications(expr)
res = distribute_and_over_or(expr)
return res
def to_dnf(expr, simplify=False, force=False):
"""
Convert a propositional logical sentence s to disjunctive normal
form: ((A & ~B & ...) | (B & C & ...) | ...).
If simplify is True, the expr is evaluated to its simplest DNF form using
the Quine-McCluskey algorithm; this may take a long
time if there are more than 8 variables and requires that the
``force`` flag be set to True (default is False).
Examples
========
>>> from sympy.logic.boolalg import to_dnf
>>> from sympy.abc import A, B, C
>>> to_dnf(B & (A | C))
(A & B) | (B & C)
>>> to_dnf((A & B) | (A & ~B) | (B & C) | (~B & C), True)
A | C
"""
expr = sympify(expr)
if not isinstance(expr, BooleanFunction):
return expr
if simplify:
if not force and len(_find_predicates(expr)) > 8:
raise ValueError(filldedent('''
To simplify a logical expression with more
than 8 variables may take a long time and requires
the use of `force=True`.'''))
return simplify_logic(expr, 'dnf', True, force=force)
# Don't convert unless we have to
if is_dnf(expr):
return expr
expr = eliminate_implications(expr)
return distribute_or_over_and(expr)
def is_anf(expr):
r"""
Checks if expr is in Algebraic Normal Form (ANF).
A logical expression is in ANF if it has the form
.. math:: 1 \oplus a \oplus b \oplus ab \oplus abc
i.e. it is purely true, purely false, conjunction of
variables or exclusive disjunction. The exclusive
disjunction can only contain true, variables or
conjunction of variables. No negations are permitted.
Examples
========
>>> from sympy.logic.boolalg import And, Not, Xor, true, is_anf
>>> from sympy.abc import A, B, C
>>> is_anf(true)
True
>>> is_anf(A)
True
>>> is_anf(And(A, B, C))
True
>>> is_anf(Xor(A, Not(B)))
False
"""
expr = sympify(expr)
if is_literal(expr) and not isinstance(expr, Not):
return True
if isinstance(expr, And):
for arg in expr.args:
if not arg.is_Symbol:
return False
return True
elif isinstance(expr, Xor):
for arg in expr.args:
if isinstance(arg, And):
for a in arg.args:
if not a.is_Symbol:
return False
elif is_literal(arg):
if isinstance(arg, Not):
return False
else:
return False
return True
else:
return False
def is_nnf(expr, simplified=True):
"""
Checks if expr is in Negation Normal Form.
A logical expression is in Negation Normal Form (NNF) if it
contains only And, Or and Not, and Not is applied only to literals.
If simplified is True, checks if result contains no redundant clauses.
Examples
========
>>> from sympy.abc import A, B, C
>>> from sympy.logic.boolalg import Not, is_nnf
>>> is_nnf(A & B | ~C)
True
>>> is_nnf((A | ~A) & (B | C))
False
>>> is_nnf((A | ~A) & (B | C), False)
True
>>> is_nnf(Not(A & B) | C)
False
>>> is_nnf((A >> B) & (B >> A))
False
"""
expr = sympify(expr)
if is_literal(expr):
return True
stack = [expr]
while stack:
expr = stack.pop()
if expr.func in (And, Or):
if simplified:
args = expr.args
for arg in args:
if Not(arg) in args:
return False
stack.extend(expr.args)
elif not is_literal(expr):
return False
return True
def is_cnf(expr):
"""
Test whether or not an expression is in conjunctive normal form.
Examples
========
>>> from sympy.logic.boolalg import is_cnf
>>> from sympy.abc import A, B, C
>>> is_cnf(A | B | C)
True
>>> is_cnf(A & B & C)
True
>>> is_cnf((A & B) | C)
False
"""
return _is_form(expr, And, Or)
def is_dnf(expr):
"""
Test whether or not an expression is in disjunctive normal form.
Examples
========
>>> from sympy.logic.boolalg import is_dnf
>>> from sympy.abc import A, B, C
>>> is_dnf(A | B | C)
True
>>> is_dnf(A & B & C)
True
>>> is_dnf((A & B) | C)
True
>>> is_dnf(A & (B | C))
False
"""
return _is_form(expr, Or, And)
def _is_form(expr, function1, function2):
"""
Test whether or not an expression is of the required form.
"""
expr = sympify(expr)
vals = function1.make_args(expr) if isinstance(expr, function1) else [expr]
for lit in vals:
if isinstance(lit, function2):
vals2 = function2.make_args(lit) if isinstance(lit, function2) else [lit]
for l in vals2:
if is_literal(l) is False:
return False
elif is_literal(lit) is False:
return False
return True
def eliminate_implications(expr):
"""
Change >>, <<, and Equivalent into &, |, and ~. That is, return an
expression that is equivalent to s, but has only &, |, and ~ as logical
operators.
Examples
========
>>> from sympy.logic.boolalg import Implies, Equivalent, \
eliminate_implications
>>> from sympy.abc import A, B, C
>>> eliminate_implications(Implies(A, B))
B | ~A
>>> eliminate_implications(Equivalent(A, B))
(A | ~B) & (B | ~A)
>>> eliminate_implications(Equivalent(A, B, C))
(A | ~C) & (B | ~A) & (C | ~B)
"""
return to_nnf(expr, simplify=False)
def is_literal(expr):
"""
Returns True if expr is a literal, else False.
Examples
========
>>> from sympy import Or, Q
>>> from sympy.abc import A, B
>>> from sympy.logic.boolalg import is_literal
>>> is_literal(A)
True
>>> is_literal(~A)
True
>>> is_literal(Q.zero(A))
True
>>> is_literal(A + B)
True
>>> is_literal(Or(A, B))
False
"""
from sympy.assumptions import AppliedPredicate
if isinstance(expr, Not):
return is_literal(expr.args[0])
elif expr in (True, False) or isinstance(expr, AppliedPredicate) or expr.is_Atom:
return True
elif not isinstance(expr, BooleanFunction) and all(
(isinstance(expr, AppliedPredicate) or a.is_Atom) for a in expr.args):
return True
return False
def to_int_repr(clauses, symbols):
"""
Takes clauses in CNF format and puts them into an integer representation.
Examples
========
>>> from sympy.logic.boolalg import to_int_repr
>>> from sympy.abc import x, y
>>> to_int_repr([x | y, y], [x, y]) == [{1, 2}, {2}]
True
"""
# Convert the symbol list into a dict
symbols = dict(list(zip(symbols, list(range(1, len(symbols) + 1)))))
def append_symbol(arg, symbols):
if isinstance(arg, Not):
return -symbols[arg.args[0]]
else:
return symbols[arg]
return [{append_symbol(arg, symbols) for arg in Or.make_args(c)}
for c in clauses]
def term_to_integer(term):
"""
Return an integer corresponding to the base-2 digits given by ``term``.
Parameters
==========
term : a string or list of ones and zeros
Examples
========
>>> from sympy.logic.boolalg import term_to_integer
>>> term_to_integer([1, 0, 0])
4
>>> term_to_integer('100')
4
"""
return int(''.join(list(map(str, list(term)))), 2)
def integer_to_term(k, n_bits=None):
"""
Return a list of the base-2 digits in the integer, ``k``.
Parameters
==========
k : int
n_bits : int
If ``n_bits`` is given and the number of digits in the binary
representation of ``k`` is smaller than ``n_bits`` then left-pad the
list with 0s.
Examples
========
>>> from sympy.logic.boolalg import integer_to_term
>>> integer_to_term(4)
[1, 0, 0]
>>> integer_to_term(4, 6)
[0, 0, 0, 1, 0, 0]
"""
s = '{0:0{1}b}'.format(abs(as_int(k)), as_int(abs(n_bits or 0)))
return list(map(int, s))
def truth_table(expr, variables, input=True):
"""
Return a generator of all possible configurations of the input variables,
and the result of the boolean expression for those values.
Parameters
==========
expr : string or boolean expression
variables : list of variables
input : boolean (default True)
indicates whether to return the input combinations.
Examples
========
>>> from sympy.logic.boolalg import truth_table
>>> from sympy.abc import x,y
>>> table = truth_table(x >> y, [x, y])
>>> for t in table:
... print('{0} -> {1}'.format(*t))
[0, 0] -> True
[0, 1] -> True
[1, 0] -> False
[1, 1] -> True
>>> table = truth_table(x | y, [x, y])
>>> list(table)
[([0, 0], False), ([0, 1], True), ([1, 0], True), ([1, 1], True)]
If input is false, truth_table returns only a list of truth values.
In this case, the corresponding input values of variables can be
deduced from the index of a given output.
>>> from sympy.logic.boolalg import integer_to_term
>>> vars = [y, x]
>>> values = truth_table(x >> y, vars, input=False)
>>> values = list(values)
>>> values
[True, False, True, True]
>>> for i, value in enumerate(values):
... print('{0} -> {1}'.format(list(zip(
... vars, integer_to_term(i, len(vars)))), value))
[(y, 0), (x, 0)] -> True
[(y, 0), (x, 1)] -> False
[(y, 1), (x, 0)] -> True
[(y, 1), (x, 1)] -> True
"""
variables = [sympify(v) for v in variables]
expr = sympify(expr)
if not isinstance(expr, BooleanFunction) and not is_literal(expr):
return
table = product([0, 1], repeat=len(variables))
for term in table:
term = list(term)
value = expr.xreplace(dict(zip(variables, term)))
if input:
yield term, value
else:
yield value
def _check_pair(minterm1, minterm2):
"""
Checks if a pair of minterms differs by only one bit. If yes, returns
index, else returns -1.
"""
# Early termination seems to be faster than list comprehension,
# at least for large examples.
index = -1
for x, i in enumerate(minterm1): # zip(minterm1, minterm2) is slower
if i != minterm2[x]:
if index == -1:
index = x
else:
return -1
return index
def _convert_to_varsSOP(minterm, variables):
"""
Converts a term in the expansion of a function from binary to its
variable form (for SOP).
"""
temp = [variables[n] if val == 1 else Not(variables[n])
for n, val in enumerate(minterm) if val != 3]
return And(*temp)
def _convert_to_varsPOS(maxterm, variables):
"""
Converts a term in the expansion of a function from binary to its
variable form (for POS).
"""
temp = [variables[n] if val == 0 else Not(variables[n])
for n, val in enumerate(maxterm) if val != 3]
return Or(*temp)
def _convert_to_varsANF(term, variables):
"""
Converts a term in the expansion of a function from binary to it's
variable form (for ANF).
Parameters
==========
term : list of 1's and 0's (complementation patter)
variables : list of variables
"""
temp = [variables[n] for n, t in enumerate(term) if t == 1]
if not temp:
return true
return And(*temp)
def _get_odd_parity_terms(n):
"""
Returns a list of lists, with all possible combinations of n zeros and ones
with an odd number of ones.
"""
return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 1]
def _get_even_parity_terms(n):
"""
Returns a list of lists, with all possible combinations of n zeros and ones
with an even number of ones.
"""
return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 0]
def _simplified_pairs(terms):
"""
Reduces a set of minterms, if possible, to a simplified set of minterms
with one less variable in the terms using QM method.
"""
if not terms:
return []
simplified_terms = []
todo = list(range(len(terms)))
# Count number of ones as _check_pair can only potentially match if there
# is at most a difference of a single one
def ones_count(term):
return sum([1 for t in term if t == 1])
termdict = defaultdict(list)
for n, term in enumerate(terms):
ones = ones_count(term)
termdict[ones].append(n)
variables = len(terms[0])
for k in range(variables):
for i in termdict[k]:
for j in termdict[k+1]:
index = _check_pair(terms[i], terms[j])
if index != -1:
# Mark terms handled
todo[i] = todo[j] = None
# Copy old term
newterm = terms[i][:]
# Set differing position to don't care
newterm[index] = 3
# Add if not already there
if newterm not in simplified_terms:
simplified_terms.append(newterm)
if simplified_terms:
# Further simplifications only among the new terms
simplified_terms = _simplified_pairs(simplified_terms)
# Add remaining, non-simplified, terms
simplified_terms.extend(
[terms[i] for i in [_ for _ in todo if _ is not None]])
return simplified_terms
def _compare_term(minterm, term):
"""
Return True if a binary term is satisfied by the given term. Used
for recognizing prime implicants.
"""
for m, t in zip(minterm, term):
if t != 3 and m != t:
return False
return True
def _rem_redundancy(l1, terms):
"""
After the truth table has been sufficiently simplified, use the prime
implicant table method to recognize and eliminate redundant pairs,
and return the essential arguments.
"""
if not terms:
return []
nterms = len(terms)
nl1 = len(l1)
# Create dominating matrix
dommatrix = [[0]*nl1 for n in range(nterms)]
for primei, prime in enumerate(l1):
for termi, term in enumerate(terms):
if _compare_term(term, prime):
dommatrix[termi][primei] = 1
# Non-dominated prime implicants, dominated to be removed
ndprimeimplicants = set(range(nl1))
# Non-dominated terms, dominated to be removed
ndterms = set(range(nterms))
# Keep track if anything changed
anythingchanged = True
# Then, go again
while anythingchanged:
anythingchanged = False
# Make copy for iteration
oldndterms = ndterms.copy()
# Filter matrix to only get non-dominated items
filteredrows = [[dommatrix[rowi][i] for i in list(ndprimeimplicants)]
for rowi in oldndterms]
for n, rowi in enumerate(oldndterms):
# Still non-dominated?
if rowi in ndterms:
row = filteredrows[n]
for n2, row2i in enumerate(oldndterms):
# Still non-dominated?
if n != n2 and row2i in ndterms:
if all(a >= b for (a, b) in zip(filteredrows[n2], row)):
# row2 dominating row, remove row2
ndterms.remove(row2i)
anythingchanged = True
# Make copy for iteration
oldndprimeimplicants = ndprimeimplicants.copy()
# Filter matrix to only get non-dominated items
filteredcols = [[dommatrix[i][coli] for i in list(ndterms)]
for coli in oldndprimeimplicants]
for n, coli in enumerate(oldndprimeimplicants):
# Still non-dominated?
if coli in ndprimeimplicants:
col = filteredcols[n]
for n2, col2i in enumerate(oldndprimeimplicants):
# Still non-dominated?
if coli != col2i and col2i in ndprimeimplicants:
if all(a >= b for (a, b) in zip(col, filteredcols[n2])):
# col dominating col2, remove col2
ndprimeimplicants.remove(col2i)
anythingchanged = True
return [l1[i] for i in ndprimeimplicants]
def _input_to_binlist(inputlist, variables):
binlist = []
bits = len(variables)
for val in inputlist:
if isinstance(val, int):
binlist.append(ibin(val, bits))
elif isinstance(val, dict):
nonspecvars = list(variables)
for key in val.keys():
nonspecvars.remove(key)
for t in product([0, 1], repeat=len(nonspecvars)):
d = dict(zip(nonspecvars, t))
d.update(val)
binlist.append([d[v] for v in variables])
elif isinstance(val, (list, tuple)):
if len(val) != bits:
raise ValueError("Each term must contain {} bits as there are"
"\n{} variables (or be an integer)."
"".format(bits, bits))
binlist.append(list(val))
else:
raise TypeError("A term list can only contain lists,"
" ints or dicts.")
return binlist
def SOPform(variables, minterms, dontcares=None):
"""
The SOPform function uses simplified_pairs and a redundant group-
eliminating algorithm to convert the list of all input combos that
generate '1' (the minterms) into the smallest Sum of Products form.
The variables must be given as the first argument.
Return a logical Or function (i.e., the "sum of products" or "SOP"
form) that gives the desired outcome. If there are inputs that can
be ignored, pass them as a list, too.
The result will be one of the (perhaps many) functions that satisfy
the conditions.
Examples
========
>>> from sympy.logic import SOPform
>>> from sympy import symbols
>>> w, x, y, z = symbols('w x y z')
>>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1],
... [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]]
>>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
>>> SOPform([w, x, y, z], minterms, dontcares)
(y & z) | (~w & ~x)
The terms can also be represented as integers:
>>> minterms = [1, 3, 7, 11, 15]
>>> dontcares = [0, 2, 5]
>>> SOPform([w, x, y, z], minterms, dontcares)
(y & z) | (~w & ~x)
They can also be specified using dicts, which does not have to be fully
specified:
>>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}]
>>> SOPform([w, x, y, z], minterms)
(x & ~w) | (y & z & ~x)
Or a combination:
>>> minterms = [4, 7, 11, [1, 1, 1, 1]]
>>> dontcares = [{w : 0, x : 0, y: 0}, 5]
>>> SOPform([w, x, y, z], minterms, dontcares)
(w & y & z) | (~w & ~y) | (x & z & ~w)
References
==========
.. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm
"""
variables = [sympify(v) for v in variables]
if minterms == []:
return false
minterms = _input_to_binlist(minterms, variables)
dontcares = _input_to_binlist((dontcares or []), variables)
for d in dontcares:
if d in minterms:
raise ValueError('%s in minterms is also in dontcares' % d)
new = _simplified_pairs(minterms + dontcares)
essential = _rem_redundancy(new, minterms)
return Or(*[_convert_to_varsSOP(x, variables) for x in essential])
def POSform(variables, minterms, dontcares=None):
"""
The POSform function uses simplified_pairs and a redundant-group
eliminating algorithm to convert the list of all input combinations
that generate '1' (the minterms) into the smallest Product of Sums form.
The variables must be given as the first argument.
Return a logical And function (i.e., the "product of sums" or "POS"
form) that gives the desired outcome. If there are inputs that can
be ignored, pass them as a list, too.
The result will be one of the (perhaps many) functions that satisfy
the conditions.
Examples
========
>>> from sympy.logic import POSform
>>> from sympy import symbols
>>> w, x, y, z = symbols('w x y z')
>>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1],
... [1, 0, 1, 1], [1, 1, 1, 1]]
>>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
>>> POSform([w, x, y, z], minterms, dontcares)
z & (y | ~w)
The terms can also be represented as integers:
>>> minterms = [1, 3, 7, 11, 15]
>>> dontcares = [0, 2, 5]
>>> POSform([w, x, y, z], minterms, dontcares)
z & (y | ~w)
They can also be specified using dicts, which does not have to be fully
specified:
>>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}]
>>> POSform([w, x, y, z], minterms)
(x | y) & (x | z) & (~w | ~x)
Or a combination:
>>> minterms = [4, 7, 11, [1, 1, 1, 1]]
>>> dontcares = [{w : 0, x : 0, y: 0}, 5]
>>> POSform([w, x, y, z], minterms, dontcares)
(w | x) & (y | ~w) & (z | ~y)
References
==========
.. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm
"""
variables = [sympify(v) for v in variables]
if minterms == []:
return false
minterms = _input_to_binlist(minterms, variables)
dontcares = _input_to_binlist((dontcares or []), variables)
for d in dontcares:
if d in minterms:
raise ValueError('%s in minterms is also in dontcares' % d)
maxterms = []
for t in product([0, 1], repeat=len(variables)):
t = list(t)
if (t not in minterms) and (t not in dontcares):
maxterms.append(t)
new = _simplified_pairs(maxterms + dontcares)
essential = _rem_redundancy(new, maxterms)
return And(*[_convert_to_varsPOS(x, variables) for x in essential])
def ANFform(variables, truthvalues):
"""
The ANFform function converts the list of truth values to
Algebraic Normal Form (ANF).
The variables must be given as the first argument.
Return True, False, logical And funciton (i.e., the
"Zhegalkin monomial") or logical Xor function (i.e.,
the "Zhegalkin polynomial"). When True and False
are represented by 1 and 0, respectively, then
And is multiplication and Xor is addition.
Formally a "Zhegalkin monomial" is the product (logical
And) of a finite set of distinct variables, including
the empty set whose product is denoted 1 (True).
A "Zhegalkin polynomial" is the sum (logical Xor) of a
set of Zhegalkin monomials, with the empty set denoted
by 0 (False).
Parameters
==========
variables : list of variables
truthvalues : list of 1's and 0's (result column of truth table)
Examples
========
>>> from sympy.logic.boolalg import ANFform
>>> from sympy.abc import x, y
>>> ANFform([x], [1, 0])
x ^ True
>>> ANFform([x, y], [0, 1, 1, 1])
x ^ y ^ (x & y)
References
==========
.. [2] https://en.wikipedia.org/wiki/Zhegalkin_polynomial
"""
n_vars = len(variables)
n_values = len(truthvalues)
if n_values != 2 ** n_vars:
raise ValueError("The number of truth values must be equal to 2^%d, "
"got %d" % (n_vars, n_values))
variables = [sympify(v) for v in variables]
coeffs = anf_coeffs(truthvalues)
terms = []
for i, t in enumerate(product([0, 1], repeat=n_vars)):
if coeffs[i] == 1:
terms.append(t)
return Xor(*[_convert_to_varsANF(x, variables) for x in terms],
remove_true=False)
def anf_coeffs(truthvalues):
"""
Convert a list of truth values of some boolean expression
to the list of coefficients of the polynomial mod 2 (exclusive
disjunction) representing the boolean expression in ANF
(i.e., the "Zhegalkin polynomial").
There are 2^n possible Zhegalkin monomials in n variables, since
each monomial is fully specified by the presence or absence of
each variable.
We can enumerate all the monomials. For example, boolean
function with four variables (a, b, c, d) can contain
up to 2^4 = 16 monomials. The 13-th monomial is the
product a & b & d, because 13 in binary is 1, 1, 0, 1.
A given monomial's presence or absence in a polynomial corresponds
to that monomial's coefficient being 1 or 0 respectively.
Examples
========
>>> from sympy.logic.boolalg import anf_coeffs, bool_monomial, Xor
>>> from sympy.abc import a, b, c
>>> truthvalues = [0, 1, 1, 0, 0, 1, 0, 1]
>>> coeffs = anf_coeffs(truthvalues)
>>> coeffs
[0, 1, 1, 0, 0, 0, 1, 0]
>>> polynomial = Xor(*[
... bool_monomial(k, [a, b, c])
... for k, coeff in enumerate(coeffs) if coeff == 1
... ])
>>> polynomial
b ^ c ^ (a & b)
"""
s = '{:b}'.format(len(truthvalues))
n = len(s) - 1
if len(truthvalues) != 2**n:
raise ValueError("The number of truth values must be a power of two, "
"got %d" % len(truthvalues))
coeffs = [[v] for v in truthvalues]
for i in range(n):
tmp = []
for j in range(2 ** (n-i-1)):
tmp.append(coeffs[2*j] +
list(map(lambda x, y: x^y, coeffs[2*j], coeffs[2*j+1])))
coeffs = tmp
return coeffs[0]
def bool_minterm(k, variables):
"""
Return the k-th minterm.
Minterms are numbered by a binary encoding of the complementation
pattern of the variables. This convention assigns the value 1 to
the direct form and 0 to the complemented form.
Parameters
==========
k : int or list of 1's and 0's (complementation patter)
variables : list of variables
Examples
========
>>> from sympy.logic.boolalg import bool_minterm
>>> from sympy.abc import x, y, z
>>> bool_minterm([1, 0, 1], [x, y, z])
x & z & ~y
>>> bool_minterm(6, [x, y, z])
x & y & ~z
References
==========
.. [3] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_minterms
"""
if isinstance(k, int):
k = integer_to_term(k, len(variables))
variables = list(map(sympify, variables))
return _convert_to_varsSOP(k, variables)
def bool_maxterm(k, variables):
"""
Return the k-th maxterm.
Each maxterm is assigned an index based on the opposite
conventional binary encoding used for minterms. The maxterm
convention assigns the value 0 to the direct form and 1 to
the complemented form.
Parameters
==========
k : int or list of 1's and 0's (complementation pattern)
variables : list of variables
Examples
========
>>> from sympy.logic.boolalg import bool_maxterm
>>> from sympy.abc import x, y, z
>>> bool_maxterm([1, 0, 1], [x, y, z])
y | ~x | ~z
>>> bool_maxterm(6, [x, y, z])
z | ~x | ~y
References
==========
.. [4] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_maxterms
"""
if isinstance(k, int):
k = integer_to_term(k, len(variables))
variables = list(map(sympify, variables))
return _convert_to_varsPOS(k, variables)
def bool_monomial(k, variables):
"""
Return the k-th monomial.
Monomials are numbered by a binary encoding of the presence and
absences of the variables. This convention assigns the value
1 to the presence of variable and 0 to the absence of variable.
Each boolean function can be uniquely represented by a
Zhegalkin Polynomial (Algebraic Normal Form). The Zhegalkin
Polynomial of the boolean function with n variables can contain
up to 2^n monomials. We can enumarate all the monomials.
Each monomial is fully specified by the presence or absence
of each variable.
For example, boolean function with four variables (a, b, c, d)
can contain up to 2^4 = 16 monomials. The 13-th monomial is the
product a & b & d, because 13 in binary is 1, 1, 0, 1.
Parameters
==========
k : int or list of 1's and 0's
variables : list of variables
Examples
========
>>> from sympy.logic.boolalg import bool_monomial
>>> from sympy.abc import x, y, z
>>> bool_monomial([1, 0, 1], [x, y, z])
x & z
>>> bool_monomial(6, [x, y, z])
x & y
"""
if isinstance(k, int):
k = integer_to_term(k, len(variables))
variables = list(map(sympify, variables))
return _convert_to_varsANF(k, variables)
def _find_predicates(expr):
"""Helper to find logical predicates in BooleanFunctions.
A logical predicate is defined here as anything within a BooleanFunction
that is not a BooleanFunction itself.
"""
if not isinstance(expr, BooleanFunction):
return {expr}
return set().union(*(_find_predicates(i) for i in expr.args))
def simplify_logic(expr, form=None, deep=True, force=False):
"""
This function simplifies a boolean function to its simplified version
in SOP or POS form. The return type is an Or or And object in SymPy.
Parameters
==========
expr : string or boolean expression
form : string ('cnf' or 'dnf') or None (default).
If 'cnf' or 'dnf', the simplest expression in the corresponding
normal form is returned; if None, the answer is returned
according to the form with fewest args (in CNF by default).
deep : boolean (default True)
Indicates whether to recursively simplify any
non-boolean functions contained within the input.
force : boolean (default False)
As the simplifications require exponential time in the number
of variables, there is by default a limit on expressions with
8 variables. When the expression has more than 8 variables
only symbolical simplification (controlled by ``deep``) is
made. By setting force to ``True``, this limit is removed. Be
aware that this can lead to very long simplification times.
Examples
========
>>> from sympy.logic import simplify_logic
>>> from sympy.abc import x, y, z
>>> from sympy import S
>>> b = (~x & ~y & ~z) | ( ~x & ~y & z)
>>> simplify_logic(b)
~x & ~y
>>> S(b)
(z & ~x & ~y) | (~x & ~y & ~z)
>>> simplify_logic(_)
~x & ~y
"""
if form not in (None, 'cnf', 'dnf'):
raise ValueError("form can be cnf or dnf only")
expr = sympify(expr)
# check for quick exit: right form and all args are
# literal and do not involve Not
isc = is_cnf(expr)
isd = is_dnf(expr)
form_ok = (
isc and form == 'cnf' or
isd and form == 'dnf')
if form_ok and all(is_literal(a)
for a in expr.args):
return expr
if deep:
variables = _find_predicates(expr)
from sympy.simplify.simplify import simplify
s = [simplify(v) for v in variables]
expr = expr.xreplace(dict(zip(variables, s)))
if not isinstance(expr, BooleanFunction):
return expr
# get variables in case not deep or after doing
# deep simplification since they may have changed
variables = _find_predicates(expr)
if not force and len(variables) > 8:
return expr
# group into constants and variable values
c, v = sift(variables, lambda x: x in (True, False), binary=True)
variables = c + v
truthtable = []
# standardize constants to be 1 or 0 in keeping with truthtable
c = [1 if i == True else 0 for i in c]
for t in product([0, 1], repeat=len(v)):
if expr.xreplace(dict(zip(v, t))) == True:
truthtable.append(c + list(t))
big = len(truthtable) >= (2 ** (len(variables) - 1))
if form == 'dnf' or form is None and big:
return SOPform(variables, truthtable)
return POSform(variables, truthtable)
def _finger(eq):
"""
Assign a 5-item fingerprint to each symbol in the equation:
[
# of times it appeared as a Symbol;
# of times it appeared as a Not(symbol);
# of times it appeared as a Symbol in an And or Or;
# of times it appeared as a Not(Symbol) in an And or Or;
a sorted tuple of tuples, (i, j, k), where i is the number of arguments
in an And or Or with which it appeared as a Symbol, and j is
the number of arguments that were Not(Symbol); k is the number
of times that (i, j) was seen.
]
Examples
========
>>> from sympy.logic.boolalg import _finger as finger
>>> from sympy import And, Or, Not, Xor, to_cnf, symbols
>>> from sympy.abc import a, b, x, y
>>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y))
>>> dict(finger(eq))
{(0, 0, 1, 0, ((2, 0, 1),)): [x],
(0, 0, 1, 0, ((2, 1, 1),)): [a, b],
(0, 0, 1, 2, ((2, 0, 1),)): [y]}
>>> dict(finger(x & ~y))
{(0, 1, 0, 0, ()): [y], (1, 0, 0, 0, ()): [x]}
In the following, the (5, 2, 6) means that there were 6 Or
functions in which a symbol appeared as itself amongst 5 arguments in
which there were also 2 negated symbols, e.g. ``(a0 | a1 | a2 | ~a3 | ~a4)``
is counted once for a0, a1 and a2.
>>> dict(finger(to_cnf(Xor(*symbols('a:5')))))
{(0, 0, 8, 8, ((5, 0, 1), (5, 2, 6), (5, 4, 1))): [a0, a1, a2, a3, a4]}
The equation must not have more than one level of nesting:
>>> dict(finger(And(Or(x, y), y)))
{(0, 0, 1, 0, ((2, 0, 1),)): [x], (1, 0, 1, 0, ((2, 0, 1),)): [y]}
>>> dict(finger(And(Or(x, And(a, x)), y)))
Traceback (most recent call last):
...
NotImplementedError: unexpected level of nesting
So y and x have unique fingerprints, but a and b do not.
"""
f = eq.free_symbols
d = dict(list(zip(f, [[0]*4 + [defaultdict(int)] for fi in f])))
for a in eq.args:
if a.is_Symbol:
d[a][0] += 1
elif a.is_Not:
d[a.args[0]][1] += 1
else:
o = len(a.args), sum(isinstance(ai, Not) for ai in a.args)
for ai in a.args:
if ai.is_Symbol:
d[ai][2] += 1
d[ai][-1][o] += 1
elif ai.is_Not:
d[ai.args[0]][3] += 1
else:
raise NotImplementedError('unexpected level of nesting')
inv = defaultdict(list)
for k, v in ordered(iter(d.items())):
v[-1] = tuple(sorted([i + (j,) for i, j in v[-1].items()]))
inv[tuple(v)].append(k)
return inv
def bool_map(bool1, bool2):
"""
Return the simplified version of bool1, and the mapping of variables
that makes the two expressions bool1 and bool2 represent the same
logical behaviour for some correspondence between the variables
of each.
If more than one mappings of this sort exist, one of them
is returned.
For example, And(x, y) is logically equivalent to And(a, b) for
the mapping {x: a, y:b} or {x: b, y:a}.
If no such mapping exists, return False.
Examples
========
>>> from sympy import SOPform, bool_map, Or, And, Not, Xor
>>> from sympy.abc import w, x, y, z, a, b, c, d
>>> function1 = SOPform([x, z, y],[[1, 0, 1], [0, 0, 1]])
>>> function2 = SOPform([a, b, c],[[1, 0, 1], [1, 0, 0]])
>>> bool_map(function1, function2)
(y & ~z, {y: a, z: b})
The results are not necessarily unique, but they are canonical. Here,
``(w, z)`` could be ``(a, d)`` or ``(d, a)``:
>>> eq = Or(And(Not(y), w), And(Not(y), z), And(x, y))
>>> eq2 = Or(And(Not(c), a), And(Not(c), d), And(b, c))
>>> bool_map(eq, eq2)
((x & y) | (w & ~y) | (z & ~y), {w: a, x: b, y: c, z: d})
>>> eq = And(Xor(a, b), c, And(c,d))
>>> bool_map(eq, eq.subs(c, x))
(c & d & (a | b) & (~a | ~b), {a: a, b: b, c: d, d: x})
"""
def match(function1, function2):
"""Return the mapping that equates variables between two
simplified boolean expressions if possible.
By "simplified" we mean that a function has been denested
and is either an And (or an Or) whose arguments are either
symbols (x), negated symbols (Not(x)), or Or (or an And) whose
arguments are only symbols or negated symbols. For example,
And(x, Not(y), Or(w, Not(z))).
Basic.match is not robust enough (see issue 4835) so this is
a workaround that is valid for simplified boolean expressions
"""
# do some quick checks
if function1.__class__ != function2.__class__:
return None # maybe simplification makes them the same?
if len(function1.args) != len(function2.args):
return None # maybe simplification makes them the same?
if function1.is_Symbol:
return {function1: function2}
# get the fingerprint dictionaries
f1 = _finger(function1)
f2 = _finger(function2)
# more quick checks
if len(f1) != len(f2):
return False
# assemble the match dictionary if possible
matchdict = {}
for k in f1.keys():
if k not in f2:
return False
if len(f1[k]) != len(f2[k]):
return False
for i, x in enumerate(f1[k]):
matchdict[x] = f2[k][i]
return matchdict
a = simplify_logic(bool1)
b = simplify_logic(bool2)
m = match(a, b)
if m:
return a, m
return m
def simplify_patterns_and():
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.core import Wild
from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
a = Wild('a')
b = Wild('b')
c = Wild('c')
# With a better canonical fewer results are required
_matchers_and = ((And(Eq(a, b), Ge(a, b)), Eq(a, b)),
(And(Eq(a, b), Gt(a, b)), S.false),
(And(Eq(a, b), Le(a, b)), Eq(a, b)),
(And(Eq(a, b), Lt(a, b)), S.false),
(And(Ge(a, b), Gt(a, b)), Gt(a, b)),
(And(Ge(a, b), Le(a, b)), Eq(a, b)),
(And(Ge(a, b), Lt(a, b)), S.false),
(And(Ge(a, b), Ne(a, b)), Gt(a, b)),
(And(Gt(a, b), Le(a, b)), S.false),
(And(Gt(a, b), Lt(a, b)), S.false),
(And(Gt(a, b), Ne(a, b)), Gt(a, b)),
(And(Le(a, b), Lt(a, b)), Lt(a, b)),
(And(Le(a, b), Ne(a, b)), Lt(a, b)),
(And(Lt(a, b), Ne(a, b)), Lt(a, b)),
# Min/max
(And(Ge(a, b), Ge(a, c)), Ge(a, Max(b, c))),
(And(Ge(a, b), Gt(a, c)), ITE(b > c, Ge(a, b), Gt(a, c))),
(And(Gt(a, b), Gt(a, c)), Gt(a, Max(b, c))),
(And(Le(a, b), Le(a, c)), Le(a, Min(b, c))),
(And(Le(a, b), Lt(a, c)), ITE(b < c, Le(a, b), Lt(a, c))),
(And(Lt(a, b), Lt(a, c)), Lt(a, Min(b, c))),
# Sign
(And(Eq(a, b), Eq(a, -b)), And(Eq(a, S.Zero), Eq(b, S.Zero))),
)
return _matchers_and
def simplify_patterns_or():
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.core import Wild
from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
a = Wild('a')
b = Wild('b')
c = Wild('c')
_matchers_or = ((Or(Eq(a, b), Ge(a, b)), Ge(a, b)),
(Or(Eq(a, b), Gt(a, b)), Ge(a, b)),
(Or(Eq(a, b), Le(a, b)), Le(a, b)),
(Or(Eq(a, b), Lt(a, b)), Le(a, b)),
(Or(Ge(a, b), Gt(a, b)), Ge(a, b)),
(Or(Ge(a, b), Le(a, b)), S.true),
(Or(Ge(a, b), Lt(a, b)), S.true),
(Or(Ge(a, b), Ne(a, b)), S.true),
(Or(Gt(a, b), Le(a, b)), S.true),
(Or(Gt(a, b), Lt(a, b)), Ne(a, b)),
(Or(Gt(a, b), Ne(a, b)), Ne(a, b)),
(Or(Le(a, b), Lt(a, b)), Le(a, b)),
(Or(Le(a, b), Ne(a, b)), S.true),
(Or(Lt(a, b), Ne(a, b)), Ne(a, b)),
# Min/max
(Or(Ge(a, b), Ge(a, c)), Ge(a, Min(b, c))),
(Or(Ge(a, b), Gt(a, c)), ITE(b > c, Gt(a, c), Ge(a, b))),
(Or(Gt(a, b), Gt(a, c)), Gt(a, Min(b, c))),
(Or(Le(a, b), Le(a, c)), Le(a, Max(b, c))),
(Or(Le(a, b), Lt(a, c)), ITE(b >= c, Le(a, b), Lt(a, c))),
(Or(Lt(a, b), Lt(a, c)), Lt(a, Max(b, c))),
)
return _matchers_or
def simplify_patterns_xor():
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.core import Wild
from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
a = Wild('a')
b = Wild('b')
c = Wild('c')
_matchers_xor = ((Xor(Eq(a, b), Ge(a, b)), Gt(a, b)),
(Xor(Eq(a, b), Gt(a, b)), Ge(a, b)),
(Xor(Eq(a, b), Le(a, b)), Lt(a, b)),
(Xor(Eq(a, b), Lt(a, b)), Le(a, b)),
(Xor(Ge(a, b), Gt(a, b)), Eq(a, b)),
(Xor(Ge(a, b), Le(a, b)), Ne(a, b)),
(Xor(Ge(a, b), Lt(a, b)), S.true),
(Xor(Ge(a, b), Ne(a, b)), Le(a, b)),
(Xor(Gt(a, b), Le(a, b)), S.true),
(Xor(Gt(a, b), Lt(a, b)), Ne(a, b)),
(Xor(Gt(a, b), Ne(a, b)), Lt(a, b)),
(Xor(Le(a, b), Lt(a, b)), Eq(a, b)),
(Xor(Le(a, b), Ne(a, b)), Ge(a, b)),
(Xor(Lt(a, b), Ne(a, b)), Gt(a, b)),
# Min/max
(Xor(Ge(a, b), Ge(a, c)),
And(Ge(a, Min(b, c)), Lt(a, Max(b, c)))),
(Xor(Ge(a, b), Gt(a, c)),
ITE(b > c, And(Gt(a, c), Lt(a, b)),
And(Ge(a, b), Le(a, c)))),
(Xor(Gt(a, b), Gt(a, c)),
And(Gt(a, Min(b, c)), Le(a, Max(b, c)))),
(Xor(Le(a, b), Le(a, c)),
And(Le(a, Max(b, c)), Gt(a, Min(b, c)))),
(Xor(Le(a, b), Lt(a, c)),
ITE(b < c, And(Lt(a, c), Gt(a, b)),
And(Le(a, b), Ge(a, c)))),
(Xor(Lt(a, b), Lt(a, c)),
And(Lt(a, Max(b, c)), Ge(a, Min(b, c)))),
)
return _matchers_xor
|
83d46e5124511f4700a3584b6ddf4f4a6fcb6f781b0b28d6cf8da7061b89c954 | """Inference in propositional logic"""
from sympy.logic.boolalg import And, Not, conjuncts, to_cnf
from sympy.core.compatibility import ordered
from sympy.core.sympify import sympify
from sympy.external.importtools import import_module
def literal_symbol(literal):
"""
The symbol in this literal (without the negation).
Examples
========
>>> from sympy.abc import A
>>> from sympy.logic.inference import literal_symbol
>>> literal_symbol(A)
A
>>> literal_symbol(~A)
A
"""
if literal is True or literal is False:
return literal
try:
if literal.is_Symbol:
return literal
if literal.is_Not:
return literal_symbol(literal.args[0])
else:
raise ValueError
except (AttributeError, ValueError):
raise ValueError("Argument must be a boolean literal.")
def satisfiable(expr, algorithm=None, all_models=False, minimal=False):
"""
Check satisfiability of a propositional sentence.
Returns a model when it succeeds.
Returns {true: true} for trivially true expressions.
On setting all_models to True, if given expr is satisfiable then
returns a generator of models. However, if expr is unsatisfiable
then returns a generator containing the single element False.
Examples
========
>>> from sympy.abc import A, B
>>> from sympy.logic.inference import satisfiable
>>> satisfiable(A & ~B)
{A: True, B: False}
>>> satisfiable(A & ~A)
False
>>> satisfiable(True)
{True: True}
>>> next(satisfiable(A & ~A, all_models=True))
False
>>> models = satisfiable((A >> B) & B, all_models=True)
>>> next(models)
{A: False, B: True}
>>> next(models)
{A: True, B: True}
>>> def use_models(models):
... for model in models:
... if model:
... # Do something with the model.
... print(model)
... else:
... # Given expr is unsatisfiable.
... print("UNSAT")
>>> use_models(satisfiable(A >> ~A, all_models=True))
{A: False}
>>> use_models(satisfiable(A ^ A, all_models=True))
UNSAT
"""
if algorithm is None or algorithm == "pycosat":
pycosat = import_module('pycosat')
if pycosat is not None:
algorithm = "pycosat"
else:
if algorithm == "pycosat":
raise ImportError("pycosat module is not present")
# Silently fall back to dpll2 if pycosat
# is not installed
algorithm = "dpll2"
if algorithm=="minisat22":
pysat = import_module('pysat')
if pysat is None:
algorithm = "dpll2"
if algorithm == "dpll":
from sympy.logic.algorithms.dpll import dpll_satisfiable
return dpll_satisfiable(expr)
elif algorithm == "dpll2":
from sympy.logic.algorithms.dpll2 import dpll_satisfiable
return dpll_satisfiable(expr, all_models)
elif algorithm == "pycosat":
from sympy.logic.algorithms.pycosat_wrapper import pycosat_satisfiable
return pycosat_satisfiable(expr, all_models)
elif algorithm == "minisat22":
from sympy.logic.algorithms.minisat22_wrapper import minisat22_satisfiable
return minisat22_satisfiable(expr, all_models, minimal)
raise NotImplementedError
def valid(expr):
"""
Check validity of a propositional sentence.
A valid propositional sentence is True under every assignment.
Examples
========
>>> from sympy.abc import A, B
>>> from sympy.logic.inference import valid
>>> valid(A | ~A)
True
>>> valid(A | B)
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Validity
"""
return not satisfiable(Not(expr))
def pl_true(expr, model={}, deep=False):
"""
Returns whether the given assignment is a model or not.
If the assignment does not specify the value for every proposition,
this may return None to indicate 'not obvious'.
Parameters
==========
model : dict, optional, default: {}
Mapping of symbols to boolean values to indicate assignment.
deep: boolean, optional, default: False
Gives the value of the expression under partial assignments
correctly. May still return None to indicate 'not obvious'.
Examples
========
>>> from sympy.abc import A, B
>>> from sympy.logic.inference import pl_true
>>> pl_true( A & B, {A: True, B: True})
True
>>> pl_true(A & B, {A: False})
False
>>> pl_true(A & B, {A: True})
>>> pl_true(A & B, {A: True}, deep=True)
>>> pl_true(A >> (B >> A))
>>> pl_true(A >> (B >> A), deep=True)
True
>>> pl_true(A & ~A)
>>> pl_true(A & ~A, deep=True)
False
>>> pl_true(A & B & (~A | ~B), {A: True})
>>> pl_true(A & B & (~A | ~B), {A: True}, deep=True)
False
"""
from sympy.core.symbol import Symbol
from sympy.logic.boolalg import BooleanFunction
boolean = (True, False)
def _validate(expr):
if isinstance(expr, Symbol) or expr in boolean:
return True
if not isinstance(expr, BooleanFunction):
return False
return all(_validate(arg) for arg in expr.args)
if expr in boolean:
return expr
expr = sympify(expr)
if not _validate(expr):
raise ValueError("%s is not a valid boolean expression" % expr)
model = {k: v for k, v in model.items() if v in boolean}
result = expr.subs(model)
if result in boolean:
return bool(result)
if deep:
model = {k: True for k in result.atoms()}
if pl_true(result, model):
if valid(result):
return True
else:
if not satisfiable(result):
return False
return None
def entails(expr, formula_set={}):
"""
Check whether the given expr_set entail an expr.
If formula_set is empty then it returns the validity of expr.
Examples
========
>>> from sympy.abc import A, B, C
>>> from sympy.logic.inference import entails
>>> entails(A, [A >> B, B >> C])
False
>>> entails(C, [A >> B, B >> C, A])
True
>>> entails(A >> B)
False
>>> entails(A >> (B >> A))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Logical_consequence
"""
formula_set = list(formula_set)
formula_set.append(Not(expr))
return not satisfiable(And(*formula_set))
class KB:
"""Base class for all knowledge bases"""
def __init__(self, sentence=None):
self.clauses_ = set()
if sentence:
self.tell(sentence)
def tell(self, sentence):
raise NotImplementedError
def ask(self, query):
raise NotImplementedError
def retract(self, sentence):
raise NotImplementedError
@property
def clauses(self):
return list(ordered(self.clauses_))
class PropKB(KB):
"""A KB for Propositional Logic. Inefficient, with no indexing."""
def tell(self, sentence):
"""Add the sentence's clauses to the KB
Examples
========
>>> from sympy.logic.inference import PropKB
>>> from sympy.abc import x, y
>>> l = PropKB()
>>> l.clauses
[]
>>> l.tell(x | y)
>>> l.clauses
[x | y]
>>> l.tell(y)
>>> l.clauses
[y, x | y]
"""
for c in conjuncts(to_cnf(sentence)):
self.clauses_.add(c)
def ask(self, query):
"""Checks if the query is true given the set of clauses.
Examples
========
>>> from sympy.logic.inference import PropKB
>>> from sympy.abc import x, y
>>> l = PropKB()
>>> l.tell(x & ~y)
>>> l.ask(x)
True
>>> l.ask(y)
False
"""
return entails(query, self.clauses_)
def retract(self, sentence):
"""Remove the sentence's clauses from the KB
Examples
========
>>> from sympy.logic.inference import PropKB
>>> from sympy.abc import x, y
>>> l = PropKB()
>>> l.clauses
[]
>>> l.tell(x | y)
>>> l.clauses
[x | y]
>>> l.retract(x | y)
>>> l.clauses
[]
"""
for c in conjuncts(to_cnf(sentence)):
self.clauses_.discard(c)
|
35c6ac13f651c646ebb18e33d1668fa4219591e6ede241f47ef7e7a0ccc451f4 | '''Functions returning normal forms of matrices'''
from sympy.polys.polytools import Poly
from sympy.polys.matrices import DomainMatrix
from sympy.polys.matrices.normalforms import (
smith_normal_form as _snf,
invariant_factors as _invf,
)
def _to_domain(m, domain=None):
"""Convert Matrix to DomainMatrix"""
# XXX: deprecated support for RawMatrix:
ring = getattr(m, "ring", None)
m = m.applyfunc(lambda e: e.as_expr() if isinstance(e, Poly) else e)
dM = DomainMatrix.from_Matrix(m)
domain = domain or ring
if domain is not None:
dM = dM.convert_to(domain)
return dM
def smith_normal_form(m, domain=None):
'''
Return the Smith Normal Form of a matrix `m` over the ring `domain`.
This will only work if the ring is a principal ideal domain.
Examples
========
>>> from sympy import Matrix, ZZ
>>> from sympy.matrices.normalforms import smith_normal_form
>>> m = Matrix([[12, 6, 4], [3, 9, 6], [2, 16, 14]])
>>> print(smith_normal_form(m, domain=ZZ))
Matrix([[1, 0, 0], [0, 10, 0], [0, 0, -30]])
'''
dM = _to_domain(m, domain)
return _snf(dM).to_Matrix()
def invariant_factors(m, domain=None):
'''
Return the tuple of abelian invariants for a matrix `m`
(as in the Smith-Normal form)
References
==========
[1] https://en.wikipedia.org/wiki/Smith_normal_form#Algorithm
[2] http://sierra.nmsu.edu/morandi/notes/SmithNormalForm.pdf
'''
dM = _to_domain(m, domain)
factors = _invf(dM)
factors = tuple(dM.domain.to_sympy(f) for f in factors)
# XXX: deprecated.
if hasattr(m, "ring"):
if m.ring.is_PolynomialRing:
K = m.ring
to_poly = lambda f: Poly(f, K.symbols, domain=K.domain)
factors = tuple(to_poly(f) for f in factors)
return factors
|
ec600a0bc2ca96d32c351689f30004a065680a58237c7e90442449a39139cd39 | from types import FunctionType
from sympy.core.numbers import Float, Integer
from sympy.core.singleton import S
from sympy.core.symbol import uniquely_named_symbol
from sympy.core.mul import Mul
from sympy.polys import PurePoly, cancel
from sympy.simplify.simplify import (simplify as _simplify,
dotprodsimp as _dotprodsimp)
from sympy import sympify
from sympy.functions.combinatorial.numbers import nC
from sympy.polys.matrices.domainmatrix import DomainMatrix
from .common import NonSquareMatrixError
from .utilities import (
_get_intermediate_simp, _get_intermediate_simp_bool,
_iszero, _is_zero_after_expand_mul)
def _find_reasonable_pivot(col, iszerofunc=_iszero, simpfunc=_simplify):
""" Find the lowest index of an item in ``col`` that is
suitable for a pivot. If ``col`` consists only of
Floats, the pivot with the largest norm is returned.
Otherwise, the first element where ``iszerofunc`` returns
False is used. If ``iszerofunc`` doesn't return false,
items are simplified and retested until a suitable
pivot is found.
Returns a 4-tuple
(pivot_offset, pivot_val, assumed_nonzero, newly_determined)
where pivot_offset is the index of the pivot, pivot_val is
the (possibly simplified) value of the pivot, assumed_nonzero
is True if an assumption that the pivot was non-zero
was made without being proved, and newly_determined are
elements that were simplified during the process of pivot
finding."""
newly_determined = []
col = list(col)
# a column that contains a mix of floats and integers
# but at least one float is considered a numerical
# column, and so we do partial pivoting
if all(isinstance(x, (Float, Integer)) for x in col) and any(
isinstance(x, Float) for x in col):
col_abs = [abs(x) for x in col]
max_value = max(col_abs)
if iszerofunc(max_value):
# just because iszerofunc returned True, doesn't
# mean the value is numerically zero. Make sure
# to replace all entries with numerical zeros
if max_value != 0:
newly_determined = [(i, 0) for i, x in enumerate(col) if x != 0]
return (None, None, False, newly_determined)
index = col_abs.index(max_value)
return (index, col[index], False, newly_determined)
# PASS 1 (iszerofunc directly)
possible_zeros = []
for i, x in enumerate(col):
is_zero = iszerofunc(x)
# is someone wrote a custom iszerofunc, it may return
# BooleanFalse or BooleanTrue instead of True or False,
# so use == for comparison instead of `is`
if is_zero == False:
# we found something that is definitely not zero
return (i, x, False, newly_determined)
possible_zeros.append(is_zero)
# by this point, we've found no certain non-zeros
if all(possible_zeros):
# if everything is definitely zero, we have
# no pivot
return (None, None, False, newly_determined)
# PASS 2 (iszerofunc after simplify)
# we haven't found any for-sure non-zeros, so
# go through the elements iszerofunc couldn't
# make a determination about and opportunistically
# simplify to see if we find something
for i, x in enumerate(col):
if possible_zeros[i] is not None:
continue
simped = simpfunc(x)
is_zero = iszerofunc(simped)
if is_zero == True or is_zero == False:
newly_determined.append((i, simped))
if is_zero == False:
return (i, simped, False, newly_determined)
possible_zeros[i] = is_zero
# after simplifying, some things that were recognized
# as zeros might be zeros
if all(possible_zeros):
# if everything is definitely zero, we have
# no pivot
return (None, None, False, newly_determined)
# PASS 3 (.equals(0))
# some expressions fail to simplify to zero, but
# ``.equals(0)`` evaluates to True. As a last-ditch
# attempt, apply ``.equals`` to these expressions
for i, x in enumerate(col):
if possible_zeros[i] is not None:
continue
if x.equals(S.Zero):
# ``.iszero`` may return False with
# an implicit assumption (e.g., ``x.equals(0)``
# when ``x`` is a symbol), so only treat it
# as proved when ``.equals(0)`` returns True
possible_zeros[i] = True
newly_determined.append((i, S.Zero))
if all(possible_zeros):
return (None, None, False, newly_determined)
# at this point there is nothing that could definitely
# be a pivot. To maintain compatibility with existing
# behavior, we'll assume that an illdetermined thing is
# non-zero. We should probably raise a warning in this case
i = possible_zeros.index(None)
return (i, col[i], True, newly_determined)
def _find_reasonable_pivot_naive(col, iszerofunc=_iszero, simpfunc=None):
"""
Helper that computes the pivot value and location from a
sequence of contiguous matrix column elements. As a side effect
of the pivot search, this function may simplify some of the elements
of the input column. A list of these simplified entries and their
indices are also returned.
This function mimics the behavior of _find_reasonable_pivot(),
but does less work trying to determine if an indeterminate candidate
pivot simplifies to zero. This more naive approach can be much faster,
with the trade-off that it may erroneously return a pivot that is zero.
``col`` is a sequence of contiguous column entries to be searched for
a suitable pivot.
``iszerofunc`` is a callable that returns a Boolean that indicates
if its input is zero, or None if no such determination can be made.
``simpfunc`` is a callable that simplifies its input. It must return
its input if it does not simplify its input. Passing in
``simpfunc=None`` indicates that the pivot search should not attempt
to simplify any candidate pivots.
Returns a 4-tuple:
(pivot_offset, pivot_val, assumed_nonzero, newly_determined)
``pivot_offset`` is the sequence index of the pivot.
``pivot_val`` is the value of the pivot.
pivot_val and col[pivot_index] are equivalent, but will be different
when col[pivot_index] was simplified during the pivot search.
``assumed_nonzero`` is a boolean indicating if the pivot cannot be
guaranteed to be zero. If assumed_nonzero is true, then the pivot
may or may not be non-zero. If assumed_nonzero is false, then
the pivot is non-zero.
``newly_determined`` is a list of index-value pairs of pivot candidates
that were simplified during the pivot search.
"""
# indeterminates holds the index-value pairs of each pivot candidate
# that is neither zero or non-zero, as determined by iszerofunc().
# If iszerofunc() indicates that a candidate pivot is guaranteed
# non-zero, or that every candidate pivot is zero then the contents
# of indeterminates are unused.
# Otherwise, the only viable candidate pivots are symbolic.
# In this case, indeterminates will have at least one entry,
# and all but the first entry are ignored when simpfunc is None.
indeterminates = []
for i, col_val in enumerate(col):
col_val_is_zero = iszerofunc(col_val)
if col_val_is_zero == False:
# This pivot candidate is non-zero.
return i, col_val, False, []
elif col_val_is_zero is None:
# The candidate pivot's comparison with zero
# is indeterminate.
indeterminates.append((i, col_val))
if len(indeterminates) == 0:
# All candidate pivots are guaranteed to be zero, i.e. there is
# no pivot.
return None, None, False, []
if simpfunc is None:
# Caller did not pass in a simplification function that might
# determine if an indeterminate pivot candidate is guaranteed
# to be nonzero, so assume the first indeterminate candidate
# is non-zero.
return indeterminates[0][0], indeterminates[0][1], True, []
# newly_determined holds index-value pairs of candidate pivots
# that were simplified during the search for a non-zero pivot.
newly_determined = []
for i, col_val in indeterminates:
tmp_col_val = simpfunc(col_val)
if id(col_val) != id(tmp_col_val):
# simpfunc() simplified this candidate pivot.
newly_determined.append((i, tmp_col_val))
if iszerofunc(tmp_col_val) == False:
# Candidate pivot simplified to a guaranteed non-zero value.
return i, tmp_col_val, False, newly_determined
return indeterminates[0][0], indeterminates[0][1], True, newly_determined
# This functions is a candidate for caching if it gets implemented for matrices.
def _berkowitz_toeplitz_matrix(M):
"""Return (A,T) where T the Toeplitz matrix used in the Berkowitz algorithm
corresponding to ``M`` and A is the first principal submatrix.
"""
# the 0 x 0 case is trivial
if M.rows == 0 and M.cols == 0:
return M._new(1,1, [M.one])
#
# Partition M = [ a_11 R ]
# [ C A ]
#
a, R = M[0,0], M[0, 1:]
C, A = M[1:, 0], M[1:,1:]
#
# The Toeplitz matrix looks like
#
# [ 1 ]
# [ -a 1 ]
# [ -RC -a 1 ]
# [ -RAC -RC -a 1 ]
# [ -RA**2C -RAC -RC -a 1 ]
# etc.
# Compute the diagonal entries.
# Because multiplying matrix times vector is so much
# more efficient than matrix times matrix, recursively
# compute -R * A**n * C.
diags = [C]
for i in range(M.rows - 2):
diags.append(A.multiply(diags[i], dotprodsimp=None))
diags = [(-R).multiply(d, dotprodsimp=None)[0, 0] for d in diags]
diags = [M.one, -a] + diags
def entry(i,j):
if j > i:
return M.zero
return diags[i - j]
toeplitz = M._new(M.cols + 1, M.rows, entry)
return (A, toeplitz)
# This functions is a candidate for caching if it gets implemented for matrices.
def _berkowitz_vector(M):
""" Run the Berkowitz algorithm and return a vector whose entries
are the coefficients of the characteristic polynomial of ``M``.
Given N x N matrix, efficiently compute
coefficients of characteristic polynomials of ``M``
without division in the ground domain.
This method is particularly useful for computing determinant,
principal minors and characteristic polynomial when ``M``
has complicated coefficients e.g. polynomials. Semi-direct
usage of this algorithm is also important in computing
efficiently sub-resultant PRS.
Assuming that M is a square matrix of dimension N x N and
I is N x N identity matrix, then the Berkowitz vector is
an N x 1 vector whose entries are coefficients of the
polynomial
charpoly(M) = det(t*I - M)
As a consequence, all polynomials generated by Berkowitz
algorithm are monic.
For more information on the implemented algorithm refer to:
[1] S.J. Berkowitz, On computing the determinant in small
parallel time using a small number of processors, ACM,
Information Processing Letters 18, 1984, pp. 147-150
[2] M. Keber, Division-Free computation of sub-resultants
using Bezout matrices, Tech. Report MPI-I-2006-1-006,
Saarbrucken, 2006
"""
# handle the trivial cases
if M.rows == 0 and M.cols == 0:
return M._new(1, 1, [M.one])
elif M.rows == 1 and M.cols == 1:
return M._new(2, 1, [M.one, -M[0,0]])
submat, toeplitz = _berkowitz_toeplitz_matrix(M)
return toeplitz.multiply(_berkowitz_vector(submat), dotprodsimp=None)
def _adjugate(M, method="berkowitz"):
"""Returns the adjugate, or classical adjoint, of
a matrix. That is, the transpose of the matrix of cofactors.
https://en.wikipedia.org/wiki/Adjugate
Parameters
==========
method : string, optional
Method to use to find the cofactors, can be "bareiss", "berkowitz" or
"lu".
Examples
========
>>> from sympy import Matrix
>>> M = Matrix([[1, 2], [3, 4]])
>>> M.adjugate()
Matrix([
[ 4, -2],
[-3, 1]])
See Also
========
cofactor_matrix
sympy.matrices.common.MatrixCommon.transpose
"""
return M.cofactor_matrix(method=method).transpose()
# This functions is a candidate for caching if it gets implemented for matrices.
def _charpoly(M, x='lambda', simplify=_simplify):
"""Computes characteristic polynomial det(x*I - M) where I is
the identity matrix.
A PurePoly is returned, so using different variables for ``x`` does
not affect the comparison or the polynomials:
Parameters
==========
x : string, optional
Name for the "lambda" variable, defaults to "lambda".
simplify : function, optional
Simplification function to use on the characteristic polynomial
calculated. Defaults to ``simplify``.
Examples
========
>>> from sympy import Matrix
>>> from sympy.abc import x, y
>>> M = Matrix([[1, 3], [2, 0]])
>>> M.charpoly()
PurePoly(lambda**2 - lambda - 6, lambda, domain='ZZ')
>>> M.charpoly(x) == M.charpoly(y)
True
>>> M.charpoly(x) == M.charpoly(y)
True
Specifying ``x`` is optional; a symbol named ``lambda`` is used by
default (which looks good when pretty-printed in unicode):
>>> M.charpoly().as_expr()
lambda**2 - lambda - 6
And if ``x`` clashes with an existing symbol, underscores will
be prepended to the name to make it unique:
>>> M = Matrix([[1, 2], [x, 0]])
>>> M.charpoly(x).as_expr()
_x**2 - _x - 2*x
Whether you pass a symbol or not, the generator can be obtained
with the gen attribute since it may not be the same as the symbol
that was passed:
>>> M.charpoly(x).gen
_x
>>> M.charpoly(x).gen == x
False
Notes
=====
The Samuelson-Berkowitz algorithm is used to compute
the characteristic polynomial efficiently and without any
division operations. Thus the characteristic polynomial over any
commutative ring without zero divisors can be computed.
If the determinant det(x*I - M) can be found out easily as
in the case of an upper or a lower triangular matrix, then
instead of Samuelson-Berkowitz algorithm, eigenvalues are computed
and the characteristic polynomial with their help.
See Also
========
det
"""
if not M.is_square:
raise NonSquareMatrixError()
if M.is_lower or M.is_upper:
diagonal_elements = M.diagonal()
x = uniquely_named_symbol(x, diagonal_elements, modify=lambda s: '_' + s)
m = 1
for i in diagonal_elements:
m = m * (x - simplify(i))
return PurePoly(m, x)
berk_vector = _berkowitz_vector(M)
x = uniquely_named_symbol(x, berk_vector, modify=lambda s: '_' + s)
return PurePoly([simplify(a) for a in berk_vector], x)
def _cofactor(M, i, j, method="berkowitz"):
"""Calculate the cofactor of an element.
Parameters
==========
method : string, optional
Method to use to find the cofactors, can be "bareiss", "berkowitz" or
"lu".
Examples
========
>>> from sympy import Matrix
>>> M = Matrix([[1, 2], [3, 4]])
>>> M.cofactor(0, 1)
-3
See Also
========
cofactor_matrix
minor
minor_submatrix
"""
if not M.is_square or M.rows < 1:
raise NonSquareMatrixError()
return (-1)**((i + j) % 2) * M.minor(i, j, method)
def _cofactor_matrix(M, method="berkowitz"):
"""Return a matrix containing the cofactor of each element.
Parameters
==========
method : string, optional
Method to use to find the cofactors, can be "bareiss", "berkowitz" or
"lu".
Examples
========
>>> from sympy import Matrix
>>> M = Matrix([[1, 2], [3, 4]])
>>> M.cofactor_matrix()
Matrix([
[ 4, -3],
[-2, 1]])
See Also
========
cofactor
minor
minor_submatrix
"""
if not M.is_square or M.rows < 1:
raise NonSquareMatrixError()
return M._new(M.rows, M.cols,
lambda i, j: M.cofactor(i, j, method))
def _per(M):
"""Returns the permanent of a matrix. Unlike determinant,
permanent is defined for both square and non-square matrices.
For an m x n matrix, with m less than or equal to n,
it is given as the sum over the permutations s of size
less than or equal to m on [1, 2, . . . n] of the product
from i = 1 to m of M[i, s[i]]. Taking the transpose will
not affect the value of the permanent.
In the case of a square matrix, this is the same as the permutation
definition of the determinant, but it does not take the sign of the
permutation into account. Computing the permanent with this definition
is quite inefficient, so here the Ryser formula is used.
Examples
========
>>> from sympy import Matrix
>>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> M.per()
450
>>> M = Matrix([1, 5, 7])
>>> M.per()
13
References
==========
.. [1] Prof. Frank Ben's notes: https://math.berkeley.edu/~bernd/ban275.pdf
.. [2] Wikipedia article on Permanent: https://en.wikipedia.org/wiki/Permanent_(mathematics)
.. [3] https://reference.wolfram.com/language/ref/Permanent.html
.. [4] Permanent of a rectangular matrix : https://arxiv.org/pdf/0904.3251.pdf
"""
import itertools
m, n = M.shape
if m > n:
M = M.T
m, n = n, m
s = list(range(n))
subsets = []
for i in range(1, m + 1):
subsets += list(map(list, itertools.combinations(s, i)))
perm = 0
for subset in subsets:
prod = 1
sub_len = len(subset)
for i in range(m):
prod *= sum([M[i, j] for j in subset])
perm += prod * (-1)**sub_len * nC(n - sub_len, m - sub_len)
perm *= (-1)**m
perm = sympify(perm)
return perm.simplify()
def _det_DOM(M):
DOM = DomainMatrix.from_Matrix(M, field=True, extension=True)
K = DOM.domain
return K.to_sympy(DOM.det())
# This functions is a candidate for caching if it gets implemented for matrices.
def _det(M, method="bareiss", iszerofunc=None):
"""Computes the determinant of a matrix if ``M`` is a concrete matrix object
otherwise return an expressions ``Determinant(M)`` if ``M`` is a
``MatrixSymbol`` or other expression.
Parameters
==========
method : string, optional
Specifies the algorithm used for computing the matrix determinant.
If the matrix is at most 3x3, a hard-coded formula is used and the
specified method is ignored. Otherwise, it defaults to
``'bareiss'``.
Also, if the matrix is an upper or a lower triangular matrix, determinant
is computed by simple multiplication of diagonal elements, and the
specified method is ignored.
If it is set to ``'domain-ge'``, then Gaussian elimination method will
be used via using DomainMatrix.
If it is set to ``'bareiss'``, Bareiss' fraction-free algorithm will
be used.
If it is set to ``'berkowitz'``, Berkowitz' algorithm will be used.
Otherwise, if it is set to ``'lu'``, LU decomposition will be used.
.. note::
For backward compatibility, legacy keys like "bareis" and
"det_lu" can still be used to indicate the corresponding
methods.
And the keys are also case-insensitive for now. However, it is
suggested to use the precise keys for specifying the method.
iszerofunc : FunctionType or None, optional
If it is set to ``None``, it will be defaulted to ``_iszero`` if the
method is set to ``'bareiss'``, and ``_is_zero_after_expand_mul`` if
the method is set to ``'lu'``.
It can also accept any user-specified zero testing function, if it
is formatted as a function which accepts a single symbolic argument
and returns ``True`` if it is tested as zero and ``False`` if it
tested as non-zero, and also ``None`` if it is undecidable.
Returns
=======
det : Basic
Result of determinant.
Raises
======
ValueError
If unrecognized keys are given for ``method`` or ``iszerofunc``.
NonSquareMatrixError
If attempted to calculate determinant from a non-square matrix.
Examples
========
>>> from sympy import Matrix, eye, det
>>> I3 = eye(3)
>>> det(I3)
1
>>> M = Matrix([[1, 2], [3, 4]])
>>> det(M)
-2
>>> det(M) == M.det()
True
>>> M.det(method="domain-ge")
-2
"""
# sanitize `method`
method = method.lower()
if method == "bareis":
method = "bareiss"
elif method == "det_lu":
method = "lu"
if method not in ("bareiss", "berkowitz", "lu", "domain-ge"):
raise ValueError("Determinant method '%s' unrecognized" % method)
if iszerofunc is None:
if method == "bareiss":
iszerofunc = _is_zero_after_expand_mul
elif method == "lu":
iszerofunc = _iszero
elif not isinstance(iszerofunc, FunctionType):
raise ValueError("Zero testing method '%s' unrecognized" % iszerofunc)
n = M.rows
if n == M.cols: # square check is done in individual method functions
if n == 0:
return M.one
elif n == 1:
return M[0, 0]
elif n == 2:
m = M[0, 0] * M[1, 1] - M[0, 1] * M[1, 0]
return _get_intermediate_simp(_dotprodsimp)(m)
elif n == 3:
m = (M[0, 0] * M[1, 1] * M[2, 2]
+ M[0, 1] * M[1, 2] * M[2, 0]
+ M[0, 2] * M[1, 0] * M[2, 1]
- M[0, 2] * M[1, 1] * M[2, 0]
- M[0, 0] * M[1, 2] * M[2, 1]
- M[0, 1] * M[1, 0] * M[2, 2])
return _get_intermediate_simp(_dotprodsimp)(m)
dets = []
for b in M.strongly_connected_components():
if method == "domain-ge": # uses DomainMatrix to evalute determinant
det = _det_DOM(M[b, b])
elif method == "bareiss":
det = M[b, b]._eval_det_bareiss(iszerofunc=iszerofunc)
elif method == "berkowitz":
det = M[b, b]._eval_det_berkowitz()
elif method == "lu":
det = M[b, b]._eval_det_lu(iszerofunc=iszerofunc)
dets.append(det)
return Mul(*dets)
# This functions is a candidate for caching if it gets implemented for matrices.
def _det_bareiss(M, iszerofunc=_is_zero_after_expand_mul):
"""Compute matrix determinant using Bareiss' fraction-free
algorithm which is an extension of the well known Gaussian
elimination method. This approach is best suited for dense
symbolic matrices and will result in a determinant with
minimal number of fractions. It means that less term
rewriting is needed on resulting formulae.
Parameters
==========
iszerofunc : function, optional
The function to use to determine zeros when doing an LU decomposition.
Defaults to ``lambda x: x.is_zero``.
TODO: Implement algorithm for sparse matrices (SFF),
http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.
"""
# Recursively implemented Bareiss' algorithm as per Deanna Richelle Leggett's
# thesis http://www.math.usm.edu/perry/Research/Thesis_DRL.pdf
def bareiss(mat, cumm=1):
if mat.rows == 0:
return mat.one
elif mat.rows == 1:
return mat[0, 0]
# find a pivot and extract the remaining matrix
# With the default iszerofunc, _find_reasonable_pivot slows down
# the computation by the factor of 2.5 in one test.
# Relevant issues: #10279 and #13877.
pivot_pos, pivot_val, _, _ = _find_reasonable_pivot(mat[:, 0], iszerofunc=iszerofunc)
if pivot_pos is None:
return mat.zero
# if we have a valid pivot, we'll do a "row swap", so keep the
# sign of the det
sign = (-1) ** (pivot_pos % 2)
# we want every row but the pivot row and every column
rows = list(i for i in range(mat.rows) if i != pivot_pos)
cols = list(range(mat.cols))
tmp_mat = mat.extract(rows, cols)
def entry(i, j):
ret = (pivot_val*tmp_mat[i, j + 1] - mat[pivot_pos, j + 1]*tmp_mat[i, 0]) / cumm
if _get_intermediate_simp_bool(True):
return _dotprodsimp(ret)
elif not ret.is_Atom:
return cancel(ret)
return ret
return sign*bareiss(M._new(mat.rows - 1, mat.cols - 1, entry), pivot_val)
if not M.is_square:
raise NonSquareMatrixError()
if M.rows == 0:
return M.one
# sympy/matrices/tests/test_matrices.py contains a test that
# suggests that the determinant of a 0 x 0 matrix is one, by
# convention.
return bareiss(M)
def _det_berkowitz(M):
""" Use the Berkowitz algorithm to compute the determinant."""
if not M.is_square:
raise NonSquareMatrixError()
if M.rows == 0:
return M.one
# sympy/matrices/tests/test_matrices.py contains a test that
# suggests that the determinant of a 0 x 0 matrix is one, by
# convention.
berk_vector = _berkowitz_vector(M)
return (-1)**(len(berk_vector) - 1) * berk_vector[-1]
# This functions is a candidate for caching if it gets implemented for matrices.
def _det_LU(M, iszerofunc=_iszero, simpfunc=None):
""" Computes the determinant of a matrix from its LU decomposition.
This function uses the LU decomposition computed by
LUDecomposition_Simple().
The keyword arguments iszerofunc and simpfunc are passed to
LUDecomposition_Simple().
iszerofunc is a callable that returns a boolean indicating if its
input is zero, or None if it cannot make the determination.
simpfunc is a callable that simplifies its input.
The default is simpfunc=None, which indicate that the pivot search
algorithm should not attempt to simplify any candidate pivots.
If simpfunc fails to simplify its input, then it must return its input
instead of a copy.
Parameters
==========
iszerofunc : function, optional
The function to use to determine zeros when doing an LU decomposition.
Defaults to ``lambda x: x.is_zero``.
simpfunc : function, optional
The simplification function to use when looking for zeros for pivots.
"""
if not M.is_square:
raise NonSquareMatrixError()
if M.rows == 0:
return M.one
# sympy/matrices/tests/test_matrices.py contains a test that
# suggests that the determinant of a 0 x 0 matrix is one, by
# convention.
lu, row_swaps = M.LUdecomposition_Simple(iszerofunc=iszerofunc,
simpfunc=simpfunc)
# P*A = L*U => det(A) = det(L)*det(U)/det(P) = det(P)*det(U).
# Lower triangular factor L encoded in lu has unit diagonal => det(L) = 1.
# P is a permutation matrix => det(P) in {-1, 1} => 1/det(P) = det(P).
# LUdecomposition_Simple() returns a list of row exchange index pairs, rather
# than a permutation matrix, but det(P) = (-1)**len(row_swaps).
# Avoid forming the potentially time consuming product of U's diagonal entries
# if the product is zero.
# Bottom right entry of U is 0 => det(A) = 0.
# It may be impossible to determine if this entry of U is zero when it is symbolic.
if iszerofunc(lu[lu.rows-1, lu.rows-1]):
return M.zero
# Compute det(P)
det = -M.one if len(row_swaps)%2 else M.one
# Compute det(U) by calculating the product of U's diagonal entries.
# The upper triangular portion of lu is the upper triangular portion of the
# U factor in the LU decomposition.
for k in range(lu.rows):
det *= lu[k, k]
# return det(P)*det(U)
return det
def _minor(M, i, j, method="berkowitz"):
"""Return the (i,j) minor of ``M``. That is,
return the determinant of the matrix obtained by deleting
the `i`th row and `j`th column from ``M``.
Parameters
==========
i, j : int
The row and column to exclude to obtain the submatrix.
method : string, optional
Method to use to find the determinant of the submatrix, can be
"bareiss", "berkowitz" or "lu".
Examples
========
>>> from sympy import Matrix
>>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> M.minor(1, 1)
-12
See Also
========
minor_submatrix
cofactor
det
"""
if not M.is_square:
raise NonSquareMatrixError()
return M.minor_submatrix(i, j).det(method=method)
def _minor_submatrix(M, i, j):
"""Return the submatrix obtained by removing the `i`th row
and `j`th column from ``M`` (works with Pythonic negative indices).
Parameters
==========
i, j : int
The row and column to exclude to obtain the submatrix.
Examples
========
>>> from sympy import Matrix
>>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> M.minor_submatrix(1, 1)
Matrix([
[1, 3],
[7, 9]])
See Also
========
minor
cofactor
"""
if i < 0:
i += M.rows
if j < 0:
j += M.cols
if not 0 <= i < M.rows or not 0 <= j < M.cols:
raise ValueError("`i` and `j` must satisfy 0 <= i < ``M.rows`` "
"(%d)" % M.rows + "and 0 <= j < ``M.cols`` (%d)." % M.cols)
rows = [a for a in range(M.rows) if a != i]
cols = [a for a in range(M.cols) if a != j]
return M.extract(rows, cols)
|
875daf7a4354407f67d91e93abc96144ba69f8f038214680cbe8ce333ec2b343 | from sympy.utilities.iterables import \
flatten, connected_components, strongly_connected_components
from .common import NonSquareMatrixError
def _connected_components(M):
"""Returns the list of connected vertices of the graph when
a square matrix is viewed as a weighted graph.
Examples
========
>>> from sympy import Matrix
>>> A = Matrix([
... [66, 0, 0, 68, 0, 0, 0, 0, 67],
... [0, 55, 0, 0, 0, 0, 54, 53, 0],
... [0, 0, 0, 0, 1, 2, 0, 0, 0],
... [86, 0, 0, 88, 0, 0, 0, 0, 87],
... [0, 0, 10, 0, 11, 12, 0, 0, 0],
... [0, 0, 20, 0, 21, 22, 0, 0, 0],
... [0, 45, 0, 0, 0, 0, 44, 43, 0],
... [0, 35, 0, 0, 0, 0, 34, 33, 0],
... [76, 0, 0, 78, 0, 0, 0, 0, 77]])
>>> A.connected_components()
[[0, 3, 8], [1, 6, 7], [2, 4, 5]]
Notes
=====
Even if any symbolic elements of the matrix can be indeterminate
to be zero mathematically, this only takes the account of the
structural aspect of the matrix, so they will considered to be
nonzero.
"""
if not M.is_square:
raise NonSquareMatrixError
V = range(M.rows)
E = sorted(M.todok().keys())
return connected_components((V, E))
def _strongly_connected_components(M):
"""Returns the list of strongly connected vertices of the graph when
a square matrix is viewed as a weighted graph.
Examples
========
>>> from sympy import Matrix
>>> A = Matrix([
... [44, 0, 0, 0, 43, 0, 45, 0, 0],
... [0, 66, 62, 61, 0, 68, 0, 60, 67],
... [0, 0, 22, 21, 0, 0, 0, 20, 0],
... [0, 0, 12, 11, 0, 0, 0, 10, 0],
... [34, 0, 0, 0, 33, 0, 35, 0, 0],
... [0, 86, 82, 81, 0, 88, 0, 80, 87],
... [54, 0, 0, 0, 53, 0, 55, 0, 0],
... [0, 0, 2, 1, 0, 0, 0, 0, 0],
... [0, 76, 72, 71, 0, 78, 0, 70, 77]])
>>> A.strongly_connected_components()
[[0, 4, 6], [2, 3, 7], [1, 5, 8]]
"""
if not M.is_square:
raise NonSquareMatrixError
V = range(M.rows)
E = sorted(M.todok().keys())
return strongly_connected_components((V, E))
def _connected_components_decomposition(M):
"""Decomposes a square matrix into block diagonal form only
using the permutations.
Explanation
===========
The decomposition is in a form of $A = P^{-1} B P$ where $P$ is a
permutation matrix and $B$ is a block diagonal matrix.
Returns
=======
P, B : PermutationMatrix, BlockDiagMatrix
*P* is a permutation matrix for the similarity transform
as in the explanation. And *B* is the block diagonal matrix of
the result of the permutation.
If you would like to get the diagonal blocks from the
BlockDiagMatrix, see
:meth:`~sympy.matrices.expressions.blockmatrix.BlockDiagMatrix.get_diag_blocks`.
Examples
========
>>> from sympy import Matrix, pprint
>>> A = Matrix([
... [66, 0, 0, 68, 0, 0, 0, 0, 67],
... [0, 55, 0, 0, 0, 0, 54, 53, 0],
... [0, 0, 0, 0, 1, 2, 0, 0, 0],
... [86, 0, 0, 88, 0, 0, 0, 0, 87],
... [0, 0, 10, 0, 11, 12, 0, 0, 0],
... [0, 0, 20, 0, 21, 22, 0, 0, 0],
... [0, 45, 0, 0, 0, 0, 44, 43, 0],
... [0, 35, 0, 0, 0, 0, 34, 33, 0],
... [76, 0, 0, 78, 0, 0, 0, 0, 77]])
>>> P, B = A.connected_components_decomposition()
>>> pprint(P)
PermutationMatrix((1 3)(2 8 5 7 4 6))
>>> pprint(B)
[[66 68 67] ]
[[ ] ]
[[86 88 87] 0 0 ]
[[ ] ]
[[76 78 77] ]
[ ]
[ [55 54 53] ]
[ [ ] ]
[ 0 [45 44 43] 0 ]
[ [ ] ]
[ [35 34 33] ]
[ ]
[ [0 1 2 ]]
[ [ ]]
[ 0 0 [10 11 12]]
[ [ ]]
[ [20 21 22]]
>>> P = P.as_explicit()
>>> B = B.as_explicit()
>>> P.T*B*P == A
True
Notes
=====
This problem corresponds to the finding of the connected components
of a graph, when a matrix is viewed as a weighted graph.
"""
from sympy.combinatorics.permutations import Permutation
from sympy.matrices.expressions.blockmatrix import BlockDiagMatrix
from sympy.matrices.expressions.permutation import PermutationMatrix
iblocks = M.connected_components()
p = Permutation(flatten(iblocks))
P = PermutationMatrix(p)
blocks = []
for b in iblocks:
blocks.append(M[b, b])
B = BlockDiagMatrix(*blocks)
return P, B
def _strongly_connected_components_decomposition(M, lower=True):
"""Decomposes a square matrix into block triangular form only
using the permutations.
Explanation
===========
The decomposition is in a form of $A = P^{-1} B P$ where $P$ is a
permutation matrix and $B$ is a block diagonal matrix.
Parameters
==========
lower : bool
Makes $B$ lower block triangular when ``True``.
Otherwise, makes $B$ upper block triangular.
Returns
=======
P, B : PermutationMatrix, BlockMatrix
*P* is a permutation matrix for the similarity transform
as in the explanation. And *B* is the block triangular matrix of
the result of the permutation.
Examples
========
>>> from sympy import Matrix, pprint
>>> A = Matrix([
... [44, 0, 0, 0, 43, 0, 45, 0, 0],
... [0, 66, 62, 61, 0, 68, 0, 60, 67],
... [0, 0, 22, 21, 0, 0, 0, 20, 0],
... [0, 0, 12, 11, 0, 0, 0, 10, 0],
... [34, 0, 0, 0, 33, 0, 35, 0, 0],
... [0, 86, 82, 81, 0, 88, 0, 80, 87],
... [54, 0, 0, 0, 53, 0, 55, 0, 0],
... [0, 0, 2, 1, 0, 0, 0, 0, 0],
... [0, 76, 72, 71, 0, 78, 0, 70, 77]])
A lower block triangular decomposition:
>>> P, B = A.strongly_connected_components_decomposition()
>>> pprint(P)
PermutationMatrix((8)(1 4 3 2 6)(5 7))
>>> pprint(B)
[[44 43 45] [0 0 0] [0 0 0] ]
[[ ] [ ] [ ] ]
[[34 33 35] [0 0 0] [0 0 0] ]
[[ ] [ ] [ ] ]
[[54 53 55] [0 0 0] [0 0 0] ]
[ ]
[ [0 0 0] [22 21 20] [0 0 0] ]
[ [ ] [ ] [ ] ]
[ [0 0 0] [12 11 10] [0 0 0] ]
[ [ ] [ ] [ ] ]
[ [0 0 0] [2 1 0 ] [0 0 0] ]
[ ]
[ [0 0 0] [62 61 60] [66 68 67]]
[ [ ] [ ] [ ]]
[ [0 0 0] [82 81 80] [86 88 87]]
[ [ ] [ ] [ ]]
[ [0 0 0] [72 71 70] [76 78 77]]
>>> P = P.as_explicit()
>>> B = B.as_explicit()
>>> P.T * B * P == A
True
An upper block triangular decomposition:
>>> P, B = A.strongly_connected_components_decomposition(lower=False)
>>> pprint(P)
PermutationMatrix((0 1 5 7 4 3 2 8 6))
>>> pprint(B)
[[66 68 67] [62 61 60] [0 0 0] ]
[[ ] [ ] [ ] ]
[[86 88 87] [82 81 80] [0 0 0] ]
[[ ] [ ] [ ] ]
[[76 78 77] [72 71 70] [0 0 0] ]
[ ]
[ [0 0 0] [22 21 20] [0 0 0] ]
[ [ ] [ ] [ ] ]
[ [0 0 0] [12 11 10] [0 0 0] ]
[ [ ] [ ] [ ] ]
[ [0 0 0] [2 1 0 ] [0 0 0] ]
[ ]
[ [0 0 0] [0 0 0] [44 43 45]]
[ [ ] [ ] [ ]]
[ [0 0 0] [0 0 0] [34 33 35]]
[ [ ] [ ] [ ]]
[ [0 0 0] [0 0 0] [54 53 55]]
>>> P = P.as_explicit()
>>> B = B.as_explicit()
>>> P.T * B * P == A
True
"""
from sympy.combinatorics.permutations import Permutation
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.matrices.expressions.permutation import PermutationMatrix
iblocks = M.strongly_connected_components()
if not lower:
iblocks = list(reversed(iblocks))
p = Permutation(flatten(iblocks))
P = PermutationMatrix(p)
rows = []
for a in iblocks:
cols = []
for b in iblocks:
cols.append(M[a, b])
rows.append(cols)
B = BlockMatrix(rows)
return P, B
|
6cb6d186ab390f174471678beb189f6f2aa2d189a79a80a2fc63bcc7eaf08014 | """
Basic methods common to all matrices to be used
when creating more advanced matrices (e.g., matrices over rings,
etc.).
"""
from collections import defaultdict
from collections.abc import Iterable
from inspect import isfunction
from functools import reduce
from sympy.core.logic import FuzzyBool
from sympy.assumptions.refine import refine
from sympy.core import SympifyError, Add
from sympy.core.basic import Atom
from sympy.core.compatibility import as_int, is_sequence
from sympy.core.decorators import call_highest_priority
from sympy.core.kind import Kind, NumberKind
from sympy.core.logic import fuzzy_and
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.functions import Abs
from sympy.polys.polytools import Poly
from sympy.simplify import simplify as _simplify
from sympy.simplify.simplify import dotprodsimp as _dotprodsimp
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.iterables import flatten
from sympy.utilities.misc import filldedent
from sympy.tensor.array import NDimArray
from .utilities import _get_intermediate_simp_bool
class MatrixError(Exception):
pass
class ShapeError(ValueError, MatrixError):
"""Wrong matrix shape"""
pass
class NonSquareMatrixError(ShapeError):
pass
class NonInvertibleMatrixError(ValueError, MatrixError):
"""The matrix in not invertible (division by multidimensional zero error)."""
pass
class NonPositiveDefiniteMatrixError(ValueError, MatrixError):
"""The matrix is not a positive-definite matrix."""
pass
class MatrixRequired:
"""All subclasses of matrix objects must implement the
required matrix properties listed here."""
rows = None # type: int
cols = None # type: int
_simplify = None
@classmethod
def _new(cls, *args, **kwargs):
"""`_new` must, at minimum, be callable as
`_new(rows, cols, mat) where mat is a flat list of the
elements of the matrix."""
raise NotImplementedError("Subclasses must implement this.")
def __eq__(self, other):
raise NotImplementedError("Subclasses must implement this.")
def __getitem__(self, key):
"""Implementations of __getitem__ should accept ints, in which
case the matrix is indexed as a flat list, tuples (i,j) in which
case the (i,j) entry is returned, slices, or mixed tuples (a,b)
where a and b are any combintion of slices and integers."""
raise NotImplementedError("Subclasses must implement this.")
def __len__(self):
"""The total number of entries in the matrix."""
raise NotImplementedError("Subclasses must implement this.")
@property
def shape(self):
raise NotImplementedError("Subclasses must implement this.")
class MatrixShaping(MatrixRequired):
"""Provides basic matrix shaping and extracting of submatrices"""
def _eval_col_del(self, col):
def entry(i, j):
return self[i, j] if j < col else self[i, j + 1]
return self._new(self.rows, self.cols - 1, entry)
def _eval_col_insert(self, pos, other):
def entry(i, j):
if j < pos:
return self[i, j]
elif pos <= j < pos + other.cols:
return other[i, j - pos]
return self[i, j - other.cols]
return self._new(self.rows, self.cols + other.cols,
lambda i, j: entry(i, j))
def _eval_col_join(self, other):
rows = self.rows
def entry(i, j):
if i < rows:
return self[i, j]
return other[i - rows, j]
return classof(self, other)._new(self.rows + other.rows, self.cols,
lambda i, j: entry(i, j))
def _eval_extract(self, rowsList, colsList):
mat = list(self)
cols = self.cols
indices = (i * cols + j for i in rowsList for j in colsList)
return self._new(len(rowsList), len(colsList),
list(mat[i] for i in indices))
def _eval_get_diag_blocks(self):
sub_blocks = []
def recurse_sub_blocks(M):
i = 1
while i <= M.shape[0]:
if i == 1:
to_the_right = M[0, i:]
to_the_bottom = M[i:, 0]
else:
to_the_right = M[:i, i:]
to_the_bottom = M[i:, :i]
if any(to_the_right) or any(to_the_bottom):
i += 1
continue
else:
sub_blocks.append(M[:i, :i])
if M.shape == M[:i, :i].shape:
return
else:
recurse_sub_blocks(M[i:, i:])
return
recurse_sub_blocks(self)
return sub_blocks
def _eval_row_del(self, row):
def entry(i, j):
return self[i, j] if i < row else self[i + 1, j]
return self._new(self.rows - 1, self.cols, entry)
def _eval_row_insert(self, pos, other):
entries = list(self)
insert_pos = pos * self.cols
entries[insert_pos:insert_pos] = list(other)
return self._new(self.rows + other.rows, self.cols, entries)
def _eval_row_join(self, other):
cols = self.cols
def entry(i, j):
if j < cols:
return self[i, j]
return other[i, j - cols]
return classof(self, other)._new(self.rows, self.cols + other.cols,
lambda i, j: entry(i, j))
def _eval_tolist(self):
return [list(self[i,:]) for i in range(self.rows)]
def _eval_todok(self):
dok = {}
rows, cols = self.shape
for i in range(rows):
for j in range(cols):
val = self[i, j]
if val != self.zero:
dok[i, j] = val
return dok
def _eval_vec(self):
rows = self.rows
def entry(n, _):
# we want to read off the columns first
j = n // rows
i = n - j * rows
return self[i, j]
return self._new(len(self), 1, entry)
def _eval_vech(self, diagonal):
c = self.cols
v = []
if diagonal:
for j in range(c):
for i in range(j, c):
v.append(self[i, j])
else:
for j in range(c):
for i in range(j + 1, c):
v.append(self[i, j])
return self._new(len(v), 1, v)
def col_del(self, col):
"""Delete the specified column."""
if col < 0:
col += self.cols
if not 0 <= col < self.cols:
raise IndexError("Column {} is out of range.".format(col))
return self._eval_col_del(col)
def col_insert(self, pos, other):
"""Insert one or more columns at the given column position.
Examples
========
>>> from sympy import zeros, ones
>>> M = zeros(3)
>>> V = ones(3, 1)
>>> M.col_insert(1, V)
Matrix([
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0]])
See Also
========
col
row_insert
"""
# Allows you to build a matrix even if it is null matrix
if not self:
return type(self)(other)
pos = as_int(pos)
if pos < 0:
pos = self.cols + pos
if pos < 0:
pos = 0
elif pos > self.cols:
pos = self.cols
if self.rows != other.rows:
raise ShapeError(
"`self` and `other` must have the same number of rows.")
return self._eval_col_insert(pos, other)
def col_join(self, other):
"""Concatenates two matrices along self's last and other's first row.
Examples
========
>>> from sympy import zeros, ones
>>> M = zeros(3)
>>> V = ones(1, 3)
>>> M.col_join(V)
Matrix([
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[1, 1, 1]])
See Also
========
col
row_join
"""
# A null matrix can always be stacked (see #10770)
if self.rows == 0 and self.cols != other.cols:
return self._new(0, other.cols, []).col_join(other)
if self.cols != other.cols:
raise ShapeError(
"`self` and `other` must have the same number of columns.")
return self._eval_col_join(other)
def col(self, j):
"""Elementary column selector.
Examples
========
>>> from sympy import eye
>>> eye(2).col(0)
Matrix([
[1],
[0]])
See Also
========
row
sympy.matrices.dense.MutableDenseMatrix.col_op
sympy.matrices.dense.MutableDenseMatrix.col_swap
col_del
col_join
col_insert
"""
return self[:, j]
def extract(self, rowsList, colsList):
"""Return a submatrix by specifying a list of rows and columns.
Negative indices can be given. All indices must be in the range
-n <= i < n where n is the number of rows or columns.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(4, 3, range(12))
>>> m
Matrix([
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11]])
>>> m.extract([0, 1, 3], [0, 1])
Matrix([
[0, 1],
[3, 4],
[9, 10]])
Rows or columns can be repeated:
>>> m.extract([0, 0, 1], [-1])
Matrix([
[2],
[2],
[5]])
Every other row can be taken by using range to provide the indices:
>>> m.extract(range(0, m.rows, 2), [-1])
Matrix([
[2],
[8]])
RowsList or colsList can also be a list of booleans, in which case
the rows or columns corresponding to the True values will be selected:
>>> m.extract([0, 1, 2, 3], [True, False, True])
Matrix([
[0, 2],
[3, 5],
[6, 8],
[9, 11]])
"""
if not is_sequence(rowsList) or not is_sequence(colsList):
raise TypeError("rowsList and colsList must be iterable")
# ensure rowsList and colsList are lists of integers
if rowsList and all(isinstance(i, bool) for i in rowsList):
rowsList = [index for index, item in enumerate(rowsList) if item]
if colsList and all(isinstance(i, bool) for i in colsList):
colsList = [index for index, item in enumerate(colsList) if item]
# ensure everything is in range
rowsList = [a2idx(k, self.rows) for k in rowsList]
colsList = [a2idx(k, self.cols) for k in colsList]
return self._eval_extract(rowsList, colsList)
def get_diag_blocks(self):
"""Obtains the square sub-matrices on the main diagonal of a square matrix.
Useful for inverting symbolic matrices or solving systems of
linear equations which may be decoupled by having a block diagonal
structure.
Examples
========
>>> from sympy import Matrix
>>> from sympy.abc import x, y, z
>>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]])
>>> a1, a2, a3 = A.get_diag_blocks()
>>> a1
Matrix([
[1, 3],
[y, z**2]])
>>> a2
Matrix([[x]])
>>> a3
Matrix([[0]])
"""
return self._eval_get_diag_blocks()
@classmethod
def hstack(cls, *args):
"""Return a matrix formed by joining args horizontally (i.e.
by repeated application of row_join).
Examples
========
>>> from sympy.matrices import Matrix, eye
>>> Matrix.hstack(eye(2), 2*eye(2))
Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]])
"""
if len(args) == 0:
return cls._new()
kls = type(args[0])
return reduce(kls.row_join, args)
def reshape(self, rows, cols):
"""Reshape the matrix. Total number of elements must remain the same.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(2, 3, lambda i, j: 1)
>>> m
Matrix([
[1, 1, 1],
[1, 1, 1]])
>>> m.reshape(1, 6)
Matrix([[1, 1, 1, 1, 1, 1]])
>>> m.reshape(3, 2)
Matrix([
[1, 1],
[1, 1],
[1, 1]])
"""
if self.rows * self.cols != rows * cols:
raise ValueError("Invalid reshape parameters %d %d" % (rows, cols))
return self._new(rows, cols, lambda i, j: self[i * cols + j])
def row_del(self, row):
"""Delete the specified row."""
if row < 0:
row += self.rows
if not 0 <= row < self.rows:
raise IndexError("Row {} is out of range.".format(row))
return self._eval_row_del(row)
def row_insert(self, pos, other):
"""Insert one or more rows at the given row position.
Examples
========
>>> from sympy import zeros, ones
>>> M = zeros(3)
>>> V = ones(1, 3)
>>> M.row_insert(1, V)
Matrix([
[0, 0, 0],
[1, 1, 1],
[0, 0, 0],
[0, 0, 0]])
See Also
========
row
col_insert
"""
# Allows you to build a matrix even if it is null matrix
if not self:
return self._new(other)
pos = as_int(pos)
if pos < 0:
pos = self.rows + pos
if pos < 0:
pos = 0
elif pos > self.rows:
pos = self.rows
if self.cols != other.cols:
raise ShapeError(
"`self` and `other` must have the same number of columns.")
return self._eval_row_insert(pos, other)
def row_join(self, other):
"""Concatenates two matrices along self's last and rhs's first column
Examples
========
>>> from sympy import zeros, ones
>>> M = zeros(3)
>>> V = ones(3, 1)
>>> M.row_join(V)
Matrix([
[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1]])
See Also
========
row
col_join
"""
# A null matrix can always be stacked (see #10770)
if self.cols == 0 and self.rows != other.rows:
return self._new(other.rows, 0, []).row_join(other)
if self.rows != other.rows:
raise ShapeError(
"`self` and `rhs` must have the same number of rows.")
return self._eval_row_join(other)
def diagonal(self, k=0):
"""Returns the kth diagonal of self. The main diagonal
corresponds to `k=0`; diagonals above and below correspond to
`k > 0` and `k < 0`, respectively. The values of `self[i, j]`
for which `j - i = k`, are returned in order of increasing
`i + j`, starting with `i + j = |k|`.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(3, 3, lambda i, j: j - i); m
Matrix([
[ 0, 1, 2],
[-1, 0, 1],
[-2, -1, 0]])
>>> _.diagonal()
Matrix([[0, 0, 0]])
>>> m.diagonal(1)
Matrix([[1, 1]])
>>> m.diagonal(-2)
Matrix([[-2]])
Even though the diagonal is returned as a Matrix, the element
retrieval can be done with a single index:
>>> Matrix.diag(1, 2, 3).diagonal()[1] # instead of [0, 1]
2
See Also
========
diag - to create a diagonal matrix
"""
rv = []
k = as_int(k)
r = 0 if k > 0 else -k
c = 0 if r else k
while True:
if r == self.rows or c == self.cols:
break
rv.append(self[r, c])
r += 1
c += 1
if not rv:
raise ValueError(filldedent('''
The %s diagonal is out of range [%s, %s]''' % (
k, 1 - self.rows, self.cols - 1)))
return self._new(1, len(rv), rv)
def row(self, i):
"""Elementary row selector.
Examples
========
>>> from sympy import eye
>>> eye(2).row(0)
Matrix([[1, 0]])
See Also
========
col
sympy.matrices.dense.MutableDenseMatrix.row_op
sympy.matrices.dense.MutableDenseMatrix.row_swap
row_del
row_join
row_insert
"""
return self[i, :]
@property
def shape(self):
"""The shape (dimensions) of the matrix as the 2-tuple (rows, cols).
Examples
========
>>> from sympy.matrices import zeros
>>> M = zeros(2, 3)
>>> M.shape
(2, 3)
>>> M.rows
2
>>> M.cols
3
"""
return (self.rows, self.cols)
def todok(self):
"""Return the matrix as dictionary of keys.
Examples
========
>>> from sympy import Matrix
>>> M = Matrix.eye(3)
>>> M.todok()
{(0, 0): 1, (1, 1): 1, (2, 2): 1}
"""
return self._eval_todok()
def tolist(self):
"""Return the Matrix as a nested Python list.
Examples
========
>>> from sympy import Matrix, ones
>>> m = Matrix(3, 3, range(9))
>>> m
Matrix([
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> m.tolist()
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
>>> ones(3, 0).tolist()
[[], [], []]
When there are no rows then it will not be possible to tell how
many columns were in the original matrix:
>>> ones(0, 3).tolist()
[]
"""
if not self.rows:
return []
if not self.cols:
return [[] for i in range(self.rows)]
return self._eval_tolist()
def todod(M):
"""Returns matrix as dict of dicts containing non-zero elements of the Matrix
Examples
========
>>> from sympy import Matrix
>>> A = Matrix([[0, 1],[0, 3]])
>>> A
Matrix([
[0, 1],
[0, 3]])
>>> A.todod()
{0: {1: 1}, 1: {1: 3}}
"""
rowsdict = {}
Mlol = M.tolist()
for i, Mi in enumerate(Mlol):
row = {j: Mij for j, Mij in enumerate(Mi) if Mij}
if row:
rowsdict[i] = row
return rowsdict
def vec(self):
"""Return the Matrix converted into a one column matrix by stacking columns
Examples
========
>>> from sympy import Matrix
>>> m=Matrix([[1, 3], [2, 4]])
>>> m
Matrix([
[1, 3],
[2, 4]])
>>> m.vec()
Matrix([
[1],
[2],
[3],
[4]])
See Also
========
vech
"""
return self._eval_vec()
def vech(self, diagonal=True, check_symmetry=True):
"""Reshapes the matrix into a column vector by stacking the
elements in the lower triangle.
Parameters
==========
diagonal : bool, optional
If ``True``, it includes the diagonal elements.
check_symmetry : bool, optional
If ``True``, it checks whether the matrix is symmetric.
Examples
========
>>> from sympy import Matrix
>>> m=Matrix([[1, 2], [2, 3]])
>>> m
Matrix([
[1, 2],
[2, 3]])
>>> m.vech()
Matrix([
[1],
[2],
[3]])
>>> m.vech(diagonal=False)
Matrix([[2]])
Notes
=====
This should work for symmetric matrices and ``vech`` can
represent symmetric matrices in vector form with less size than
``vec``.
See Also
========
vec
"""
if not self.is_square:
raise NonSquareMatrixError
if check_symmetry and not self.is_symmetric():
raise ValueError("The matrix is not symmetric.")
return self._eval_vech(diagonal)
@classmethod
def vstack(cls, *args):
"""Return a matrix formed by joining args vertically (i.e.
by repeated application of col_join).
Examples
========
>>> from sympy.matrices import Matrix, eye
>>> Matrix.vstack(eye(2), 2*eye(2))
Matrix([
[1, 0],
[0, 1],
[2, 0],
[0, 2]])
"""
if len(args) == 0:
return cls._new()
kls = type(args[0])
return reduce(kls.col_join, args)
class MatrixSpecial(MatrixRequired):
"""Construction of special matrices"""
@classmethod
def _eval_diag(cls, rows, cols, diag_dict):
"""diag_dict is a defaultdict containing
all the entries of the diagonal matrix."""
def entry(i, j):
return diag_dict[(i, j)]
return cls._new(rows, cols, entry)
@classmethod
def _eval_eye(cls, rows, cols):
vals = [cls.zero]*(rows*cols)
vals[::cols+1] = [cls.one]*min(rows, cols)
return cls._new(rows, cols, vals, copy=False)
@classmethod
def _eval_jordan_block(cls, rows, cols, eigenvalue, band='upper'):
if band == 'lower':
def entry(i, j):
if i == j:
return eigenvalue
elif j + 1 == i:
return cls.one
return cls.zero
else:
def entry(i, j):
if i == j:
return eigenvalue
elif i + 1 == j:
return cls.one
return cls.zero
return cls._new(rows, cols, entry)
@classmethod
def _eval_ones(cls, rows, cols):
def entry(i, j):
return cls.one
return cls._new(rows, cols, entry)
@classmethod
def _eval_zeros(cls, rows, cols):
return cls._new(rows, cols, [cls.zero]*(rows*cols), copy=False)
@classmethod
def _eval_wilkinson(cls, n):
def entry(i, j):
return cls.one if i + 1 == j else cls.zero
D = cls._new(2*n + 1, 2*n + 1, entry)
wminus = cls.diag([i for i in range(-n, n + 1)], unpack=True) + D + D.T
wplus = abs(cls.diag([i for i in range(-n, n + 1)], unpack=True)) + D + D.T
return wminus, wplus
@classmethod
def diag(kls, *args, strict=False, unpack=True, rows=None, cols=None, **kwargs):
"""Returns a matrix with the specified diagonal.
If matrices are passed, a block-diagonal matrix
is created (i.e. the "direct sum" of the matrices).
kwargs
======
rows : rows of the resulting matrix; computed if
not given.
cols : columns of the resulting matrix; computed if
not given.
cls : class for the resulting matrix
unpack : bool which, when True (default), unpacks a single
sequence rather than interpreting it as a Matrix.
strict : bool which, when False (default), allows Matrices to
have variable-length rows.
Examples
========
>>> from sympy.matrices import Matrix
>>> Matrix.diag(1, 2, 3)
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
The current default is to unpack a single sequence. If this is
not desired, set `unpack=False` and it will be interpreted as
a matrix.
>>> Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3)
True
When more than one element is passed, each is interpreted as
something to put on the diagonal. Lists are converted to
matrices. Filling of the diagonal always continues from
the bottom right hand corner of the previous item: this
will create a block-diagonal matrix whether the matrices
are square or not.
>>> col = [1, 2, 3]
>>> row = [[4, 5]]
>>> Matrix.diag(col, row)
Matrix([
[1, 0, 0],
[2, 0, 0],
[3, 0, 0],
[0, 4, 5]])
When `unpack` is False, elements within a list need not all be
of the same length. Setting `strict` to True would raise a
ValueError for the following:
>>> Matrix.diag([[1, 2, 3], [4, 5], [6]], unpack=False)
Matrix([
[1, 2, 3],
[4, 5, 0],
[6, 0, 0]])
The type of the returned matrix can be set with the ``cls``
keyword.
>>> from sympy.matrices import ImmutableMatrix
>>> from sympy.utilities.misc import func_name
>>> func_name(Matrix.diag(1, cls=ImmutableMatrix))
'ImmutableDenseMatrix'
A zero dimension matrix can be used to position the start of
the filling at the start of an arbitrary row or column:
>>> from sympy import ones
>>> r2 = ones(0, 2)
>>> Matrix.diag(r2, 1, 2)
Matrix([
[0, 0, 1, 0],
[0, 0, 0, 2]])
See Also
========
eye
diagonal - to extract a diagonal
.dense.diag
.expressions.blockmatrix.BlockMatrix
.sparsetools.banded - to create multi-diagonal matrices
"""
from sympy.matrices.matrices import MatrixBase
from sympy.matrices.dense import Matrix
from sympy.matrices.sparse import SparseMatrix
klass = kwargs.get('cls', kls)
if unpack and len(args) == 1 and is_sequence(args[0]) and \
not isinstance(args[0], MatrixBase):
args = args[0]
# fill a default dict with the diagonal entries
diag_entries = defaultdict(int)
rmax = cmax = 0 # keep track of the biggest index seen
for m in args:
if isinstance(m, list):
if strict:
# if malformed, Matrix will raise an error
_ = Matrix(m)
r, c = _.shape
m = _.tolist()
else:
r, c, smat = SparseMatrix._handle_creation_inputs(m)
for (i, j), _ in smat.items():
diag_entries[(i + rmax, j + cmax)] = _
m = [] # to skip process below
elif hasattr(m, 'shape'): # a Matrix
# convert to list of lists
r, c = m.shape
m = m.tolist()
else: # in this case, we're a single value
diag_entries[(rmax, cmax)] = m
rmax += 1
cmax += 1
continue
# process list of lists
for i in range(len(m)):
for j, _ in enumerate(m[i]):
diag_entries[(i + rmax, j + cmax)] = _
rmax += r
cmax += c
if rows is None:
rows, cols = cols, rows
if rows is None:
rows, cols = rmax, cmax
else:
cols = rows if cols is None else cols
if rows < rmax or cols < cmax:
raise ValueError(filldedent('''
The constructed matrix is {} x {} but a size of {} x {}
was specified.'''.format(rmax, cmax, rows, cols)))
return klass._eval_diag(rows, cols, diag_entries)
@classmethod
def eye(kls, rows, cols=None, **kwargs):
"""Returns an identity matrix.
Args
====
rows : rows of the matrix
cols : cols of the matrix (if None, cols=rows)
kwargs
======
cls : class of the returned matrix
"""
if cols is None:
cols = rows
if rows < 0 or cols < 0:
raise ValueError("Cannot create a {} x {} matrix. "
"Both dimensions must be positive".format(rows, cols))
klass = kwargs.get('cls', kls)
rows, cols = as_int(rows), as_int(cols)
return klass._eval_eye(rows, cols)
@classmethod
def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs):
"""Returns a Jordan block
Parameters
==========
size : Integer, optional
Specifies the shape of the Jordan block matrix.
eigenvalue : Number or Symbol
Specifies the value for the main diagonal of the matrix.
.. note::
The keyword ``eigenval`` is also specified as an alias
of this keyword, but it is not recommended to use.
We may deprecate the alias in later release.
band : 'upper' or 'lower', optional
Specifies the position of the off-diagonal to put `1` s on.
cls : Matrix, optional
Specifies the matrix class of the output form.
If it is not specified, the class type where the method is
being executed on will be returned.
rows, cols : Integer, optional
Specifies the shape of the Jordan block matrix. See Notes
section for the details of how these key works.
.. note::
This feature will be deprecated in the future.
Returns
=======
Matrix
A Jordan block matrix.
Raises
======
ValueError
If insufficient arguments are given for matrix size
specification, or no eigenvalue is given.
Examples
========
Creating a default Jordan block:
>>> from sympy import Matrix
>>> from sympy.abc import x
>>> Matrix.jordan_block(4, x)
Matrix([
[x, 1, 0, 0],
[0, x, 1, 0],
[0, 0, x, 1],
[0, 0, 0, x]])
Creating an alternative Jordan block matrix where `1` is on
lower off-diagonal:
>>> Matrix.jordan_block(4, x, band='lower')
Matrix([
[x, 0, 0, 0],
[1, x, 0, 0],
[0, 1, x, 0],
[0, 0, 1, x]])
Creating a Jordan block with keyword arguments
>>> Matrix.jordan_block(size=4, eigenvalue=x)
Matrix([
[x, 1, 0, 0],
[0, x, 1, 0],
[0, 0, x, 1],
[0, 0, 0, x]])
Notes
=====
.. note::
This feature will be deprecated in the future.
The keyword arguments ``size``, ``rows``, ``cols`` relates to
the Jordan block size specifications.
If you want to create a square Jordan block, specify either
one of the three arguments.
If you want to create a rectangular Jordan block, specify
``rows`` and ``cols`` individually.
+--------------------------------+---------------------+
| Arguments Given | Matrix Shape |
+----------+----------+----------+----------+----------+
| size | rows | cols | rows | cols |
+==========+==========+==========+==========+==========+
| size | Any | size | size |
+----------+----------+----------+----------+----------+
| | None | ValueError |
| +----------+----------+----------+----------+
| None | rows | None | rows | rows |
| +----------+----------+----------+----------+
| | None | cols | cols | cols |
+ +----------+----------+----------+----------+
| | rows | cols | rows | cols |
+----------+----------+----------+----------+----------+
References
==========
.. [1] https://en.wikipedia.org/wiki/Jordan_matrix
"""
if 'rows' in kwargs or 'cols' in kwargs:
SymPyDeprecationWarning(
feature="Keyword arguments 'rows' or 'cols'",
issue=16102,
useinstead="a more generic banded matrix constructor",
deprecated_since_version="1.4"
).warn()
klass = kwargs.pop('cls', kls)
rows = kwargs.pop('rows', None)
cols = kwargs.pop('cols', None)
eigenval = kwargs.get('eigenval', None)
if eigenvalue is None and eigenval is None:
raise ValueError("Must supply an eigenvalue")
elif eigenvalue != eigenval and None not in (eigenval, eigenvalue):
raise ValueError(
"Inconsistent values are given: 'eigenval'={}, "
"'eigenvalue'={}".format(eigenval, eigenvalue))
else:
if eigenval is not None:
eigenvalue = eigenval
if (size, rows, cols) == (None, None, None):
raise ValueError("Must supply a matrix size")
if size is not None:
rows, cols = size, size
elif rows is not None and cols is None:
cols = rows
elif cols is not None and rows is None:
rows = cols
rows, cols = as_int(rows), as_int(cols)
return klass._eval_jordan_block(rows, cols, eigenvalue, band)
@classmethod
def ones(kls, rows, cols=None, **kwargs):
"""Returns a matrix of ones.
Args
====
rows : rows of the matrix
cols : cols of the matrix (if None, cols=rows)
kwargs
======
cls : class of the returned matrix
"""
if cols is None:
cols = rows
klass = kwargs.get('cls', kls)
rows, cols = as_int(rows), as_int(cols)
return klass._eval_ones(rows, cols)
@classmethod
def zeros(kls, rows, cols=None, **kwargs):
"""Returns a matrix of zeros.
Args
====
rows : rows of the matrix
cols : cols of the matrix (if None, cols=rows)
kwargs
======
cls : class of the returned matrix
"""
if cols is None:
cols = rows
if rows < 0 or cols < 0:
raise ValueError("Cannot create a {} x {} matrix. "
"Both dimensions must be positive".format(rows, cols))
klass = kwargs.get('cls', kls)
rows, cols = as_int(rows), as_int(cols)
return klass._eval_zeros(rows, cols)
@classmethod
def companion(kls, poly):
"""Returns a companion matrix of a polynomial.
Examples
========
>>> from sympy import Matrix, Poly, Symbol, symbols
>>> x = Symbol('x')
>>> c0, c1, c2, c3, c4 = symbols('c0:5')
>>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x)
>>> Matrix.companion(p)
Matrix([
[0, 0, 0, 0, -c0],
[1, 0, 0, 0, -c1],
[0, 1, 0, 0, -c2],
[0, 0, 1, 0, -c3],
[0, 0, 0, 1, -c4]])
"""
poly = kls._sympify(poly)
if not isinstance(poly, Poly):
raise ValueError("{} must be a Poly instance.".format(poly))
if not poly.is_monic:
raise ValueError("{} must be a monic polynomial.".format(poly))
if not poly.is_univariate:
raise ValueError(
"{} must be a univariate polynomial.".format(poly))
size = poly.degree()
if not size >= 1:
raise ValueError(
"{} must have degree not less than 1.".format(poly))
coeffs = poly.all_coeffs()
def entry(i, j):
if j == size - 1:
return -coeffs[-1 - i]
elif i == j + 1:
return kls.one
return kls.zero
return kls._new(size, size, entry)
@classmethod
def wilkinson(kls, n, **kwargs):
"""Returns two square Wilkinson Matrix of size 2*n + 1
$W_{2n + 1}^-, W_{2n + 1}^+ =$ Wilkinson(n)
Examples
========
>>> from sympy.matrices import Matrix
>>> wminus, wplus = Matrix.wilkinson(3)
>>> wminus
Matrix([
[-3, 1, 0, 0, 0, 0, 0],
[ 1, -2, 1, 0, 0, 0, 0],
[ 0, 1, -1, 1, 0, 0, 0],
[ 0, 0, 1, 0, 1, 0, 0],
[ 0, 0, 0, 1, 1, 1, 0],
[ 0, 0, 0, 0, 1, 2, 1],
[ 0, 0, 0, 0, 0, 1, 3]])
>>> wplus
Matrix([
[3, 1, 0, 0, 0, 0, 0],
[1, 2, 1, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 2, 1],
[0, 0, 0, 0, 0, 1, 3]])
References
==========
.. [1] https://blogs.mathworks.com/cleve/2013/04/15/wilkinsons-matrices-2/
.. [2] J. H. Wilkinson, The Algebraic Eigenvalue Problem, Claredon Press, Oxford, 1965, 662 pp.
"""
klass = kwargs.get('cls', kls)
n = as_int(n)
return klass._eval_wilkinson(n)
class MatrixProperties(MatrixRequired):
"""Provides basic properties of a matrix."""
def _eval_atoms(self, *types):
result = set()
for i in self:
result.update(i.atoms(*types))
return result
def _eval_free_symbols(self):
return set().union(*(i.free_symbols for i in self if i))
def _eval_has(self, *patterns):
return any(a.has(*patterns) for a in self)
def _eval_is_anti_symmetric(self, simpfunc):
if not all(simpfunc(self[i, j] + self[j, i]).is_zero for i in range(self.rows) for j in range(self.cols)):
return False
return True
def _eval_is_diagonal(self):
for i in range(self.rows):
for j in range(self.cols):
if i != j and self[i, j]:
return False
return True
# _eval_is_hermitian is called by some general sympy
# routines and has a different *args signature. Make
# sure the names don't clash by adding `_matrix_` in name.
def _eval_is_matrix_hermitian(self, simpfunc):
mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i].conjugate()))
return mat.is_zero_matrix
def _eval_is_Identity(self) -> FuzzyBool:
def dirac(i, j):
if i == j:
return 1
return 0
return all(self[i, j] == dirac(i, j)
for i in range(self.rows)
for j in range(self.cols))
def _eval_is_lower_hessenberg(self):
return all(self[i, j].is_zero
for i in range(self.rows)
for j in range(i + 2, self.cols))
def _eval_is_lower(self):
return all(self[i, j].is_zero
for i in range(self.rows)
for j in range(i + 1, self.cols))
def _eval_is_symbolic(self):
return self.has(Symbol)
def _eval_is_symmetric(self, simpfunc):
mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i]))
return mat.is_zero_matrix
def _eval_is_zero_matrix(self):
if any(i.is_zero == False for i in self):
return False
if any(i.is_zero is None for i in self):
return None
return True
def _eval_is_upper_hessenberg(self):
return all(self[i, j].is_zero
for i in range(2, self.rows)
for j in range(min(self.cols, (i - 1))))
def _eval_values(self):
return [i for i in self if not i.is_zero]
def _has_positive_diagonals(self):
diagonal_entries = (self[i, i] for i in range(self.rows))
return fuzzy_and(x.is_positive for x in diagonal_entries)
def _has_nonnegative_diagonals(self):
diagonal_entries = (self[i, i] for i in range(self.rows))
return fuzzy_and(x.is_nonnegative for x in diagonal_entries)
def atoms(self, *types):
"""Returns the atoms that form the current object.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.matrices import Matrix
>>> Matrix([[x]])
Matrix([[x]])
>>> _.atoms()
{x}
>>> Matrix([[x, y], [y, x]])
Matrix([
[x, y],
[y, x]])
>>> _.atoms()
{x, y}
"""
types = tuple(t if isinstance(t, type) else type(t) for t in types)
if not types:
types = (Atom,)
return self._eval_atoms(*types)
@property
def free_symbols(self):
"""Returns the free symbols within the matrix.
Examples
========
>>> from sympy.abc import x
>>> from sympy.matrices import Matrix
>>> Matrix([[x], [1]]).free_symbols
{x}
"""
return self._eval_free_symbols()
def has(self, *patterns):
"""Test whether any subexpression matches any of the patterns.
Examples
========
>>> from sympy import Matrix, SparseMatrix, Float
>>> from sympy.abc import x, y
>>> A = Matrix(((1, x), (0.2, 3)))
>>> B = SparseMatrix(((1, x), (0.2, 3)))
>>> A.has(x)
True
>>> A.has(y)
False
>>> A.has(Float)
True
>>> B.has(x)
True
>>> B.has(y)
False
>>> B.has(Float)
True
"""
return self._eval_has(*patterns)
def is_anti_symmetric(self, simplify=True):
"""Check if matrix M is an antisymmetric matrix,
that is, M is a square matrix with all M[i, j] == -M[j, i].
When ``simplify=True`` (default), the sum M[i, j] + M[j, i] is
simplified before testing to see if it is zero. By default,
the SymPy simplify function is used. To use a custom function
set simplify to a function that accepts a single argument which
returns a simplified expression. To skip simplification, set
simplify to False but note that although this will be faster,
it may induce false negatives.
Examples
========
>>> from sympy import Matrix, symbols
>>> m = Matrix(2, 2, [0, 1, -1, 0])
>>> m
Matrix([
[ 0, 1],
[-1, 0]])
>>> m.is_anti_symmetric()
True
>>> x, y = symbols('x y')
>>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0])
>>> m
Matrix([
[ 0, 0, x],
[-y, 0, 0]])
>>> m.is_anti_symmetric()
False
>>> from sympy.abc import x, y
>>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y,
... -(x + 1)**2 , 0, x*y,
... -y, -x*y, 0])
Simplification of matrix elements is done by default so even
though two elements which should be equal and opposite wouldn't
pass an equality test, the matrix is still reported as
anti-symmetric:
>>> m[0, 1] == -m[1, 0]
False
>>> m.is_anti_symmetric()
True
If 'simplify=False' is used for the case when a Matrix is already
simplified, this will speed things up. Here, we see that without
simplification the matrix does not appear anti-symmetric:
>>> m.is_anti_symmetric(simplify=False)
False
But if the matrix were already expanded, then it would appear
anti-symmetric and simplification in the is_anti_symmetric routine
is not needed:
>>> m = m.expand()
>>> m.is_anti_symmetric(simplify=False)
True
"""
# accept custom simplification
simpfunc = simplify
if not isfunction(simplify):
simpfunc = _simplify if simplify else lambda x: x
if not self.is_square:
return False
return self._eval_is_anti_symmetric(simpfunc)
def is_diagonal(self):
"""Check if matrix is diagonal,
that is matrix in which the entries outside the main diagonal are all zero.
Examples
========
>>> from sympy import Matrix, diag
>>> m = Matrix(2, 2, [1, 0, 0, 2])
>>> m
Matrix([
[1, 0],
[0, 2]])
>>> m.is_diagonal()
True
>>> m = Matrix(2, 2, [1, 1, 0, 2])
>>> m
Matrix([
[1, 1],
[0, 2]])
>>> m.is_diagonal()
False
>>> m = diag(1, 2, 3)
>>> m
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
>>> m.is_diagonal()
True
See Also
========
is_lower
is_upper
sympy.matrices.matrices.MatrixEigen.is_diagonalizable
diagonalize
"""
return self._eval_is_diagonal()
@property
def is_weakly_diagonally_dominant(self):
r"""Tests if the matrix is row weakly diagonally dominant.
Explanation
===========
A $n, n$ matrix $A$ is row weakly diagonally dominant if
.. math::
\left|A_{i, i}\right| \ge \sum_{j = 0, j \neq i}^{n-1}
\left|A_{i, j}\right| \quad {\text{for all }}
i \in \{ 0, ..., n-1 \}
Examples
========
>>> from sympy.matrices import Matrix
>>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]])
>>> A.is_weakly_diagonally_dominant
True
>>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]])
>>> A.is_weakly_diagonally_dominant
False
>>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]])
>>> A.is_weakly_diagonally_dominant
True
Notes
=====
If you want to test whether a matrix is column diagonally
dominant, you can apply the test after transposing the matrix.
"""
if not self.is_square:
return False
rows, cols = self.shape
def test_row(i):
summation = self.zero
for j in range(cols):
if i != j:
summation += Abs(self[i, j])
return (Abs(self[i, i]) - summation).is_nonnegative
return fuzzy_and(test_row(i) for i in range(rows))
@property
def is_strongly_diagonally_dominant(self):
r"""Tests if the matrix is row strongly diagonally dominant.
Explanation
===========
A $n, n$ matrix $A$ is row strongly diagonally dominant if
.. math::
\left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1}
\left|A_{i, j}\right| \quad {\text{for all }}
i \in \{ 0, ..., n-1 \}
Examples
========
>>> from sympy.matrices import Matrix
>>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]])
>>> A.is_strongly_diagonally_dominant
False
>>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]])
>>> A.is_strongly_diagonally_dominant
False
>>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]])
>>> A.is_strongly_diagonally_dominant
True
Notes
=====
If you want to test whether a matrix is column diagonally
dominant, you can apply the test after transposing the matrix.
"""
if not self.is_square:
return False
rows, cols = self.shape
def test_row(i):
summation = self.zero
for j in range(cols):
if i != j:
summation += Abs(self[i, j])
return (Abs(self[i, i]) - summation).is_positive
return fuzzy_and(test_row(i) for i in range(rows))
@property
def is_hermitian(self):
"""Checks if the matrix is Hermitian.
In a Hermitian matrix element i,j is the complex conjugate of
element j,i.
Examples
========
>>> from sympy.matrices import Matrix
>>> from sympy import I
>>> from sympy.abc import x
>>> a = Matrix([[1, I], [-I, 1]])
>>> a
Matrix([
[ 1, I],
[-I, 1]])
>>> a.is_hermitian
True
>>> a[0, 0] = 2*I
>>> a.is_hermitian
False
>>> a[0, 0] = x
>>> a.is_hermitian
>>> a[0, 1] = a[1, 0]*I
>>> a.is_hermitian
False
"""
if not self.is_square:
return False
return self._eval_is_matrix_hermitian(_simplify)
@property
def is_Identity(self) -> FuzzyBool:
if not self.is_square:
return False
return self._eval_is_Identity()
@property
def is_lower_hessenberg(self):
r"""Checks if the matrix is in the lower-Hessenberg form.
The lower hessenberg matrix has zero entries
above the first superdiagonal.
Examples
========
>>> from sympy.matrices import Matrix
>>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]])
>>> a
Matrix([
[1, 2, 0, 0],
[5, 2, 3, 0],
[3, 4, 3, 7],
[5, 6, 1, 1]])
>>> a.is_lower_hessenberg
True
See Also
========
is_upper_hessenberg
is_lower
"""
return self._eval_is_lower_hessenberg()
@property
def is_lower(self):
"""Check if matrix is a lower triangular matrix. True can be returned
even if the matrix is not square.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(2, 2, [1, 0, 0, 1])
>>> m
Matrix([
[1, 0],
[0, 1]])
>>> m.is_lower
True
>>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4 , 0, 6, 6, 5])
>>> m
Matrix([
[0, 0, 0],
[2, 0, 0],
[1, 4, 0],
[6, 6, 5]])
>>> m.is_lower
True
>>> from sympy.abc import x, y
>>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y])
>>> m
Matrix([
[x**2 + y, x + y**2],
[ 0, x + y]])
>>> m.is_lower
False
See Also
========
is_upper
is_diagonal
is_lower_hessenberg
"""
return self._eval_is_lower()
@property
def is_square(self):
"""Checks if a matrix is square.
A matrix is square if the number of rows equals the number of columns.
The empty matrix is square by definition, since the number of rows and
the number of columns are both zero.
Examples
========
>>> from sympy import Matrix
>>> a = Matrix([[1, 2, 3], [4, 5, 6]])
>>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> c = Matrix([])
>>> a.is_square
False
>>> b.is_square
True
>>> c.is_square
True
"""
return self.rows == self.cols
def is_symbolic(self):
"""Checks if any elements contain Symbols.
Examples
========
>>> from sympy.matrices import Matrix
>>> from sympy.abc import x, y
>>> M = Matrix([[x, y], [1, 0]])
>>> M.is_symbolic()
True
"""
return self._eval_is_symbolic()
def is_symmetric(self, simplify=True):
"""Check if matrix is symmetric matrix,
that is square matrix and is equal to its transpose.
By default, simplifications occur before testing symmetry.
They can be skipped using 'simplify=False'; while speeding things a bit,
this may however induce false negatives.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(2, 2, [0, 1, 1, 2])
>>> m
Matrix([
[0, 1],
[1, 2]])
>>> m.is_symmetric()
True
>>> m = Matrix(2, 2, [0, 1, 2, 0])
>>> m
Matrix([
[0, 1],
[2, 0]])
>>> m.is_symmetric()
False
>>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0])
>>> m
Matrix([
[0, 0, 0],
[0, 0, 0]])
>>> m.is_symmetric()
False
>>> from sympy.abc import x, y
>>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2 , 2, 0, y, 0, 3])
>>> m
Matrix([
[ 1, x**2 + 2*x + 1, y],
[(x + 1)**2, 2, 0],
[ y, 0, 3]])
>>> m.is_symmetric()
True
If the matrix is already simplified, you may speed-up is_symmetric()
test by using 'simplify=False'.
>>> bool(m.is_symmetric(simplify=False))
False
>>> m1 = m.expand()
>>> m1.is_symmetric(simplify=False)
True
"""
simpfunc = simplify
if not isfunction(simplify):
simpfunc = _simplify if simplify else lambda x: x
if not self.is_square:
return False
return self._eval_is_symmetric(simpfunc)
@property
def is_upper_hessenberg(self):
"""Checks if the matrix is the upper-Hessenberg form.
The upper hessenberg matrix has zero entries
below the first subdiagonal.
Examples
========
>>> from sympy.matrices import Matrix
>>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]])
>>> a
Matrix([
[1, 4, 2, 3],
[3, 4, 1, 7],
[0, 2, 3, 4],
[0, 0, 1, 3]])
>>> a.is_upper_hessenberg
True
See Also
========
is_lower_hessenberg
is_upper
"""
return self._eval_is_upper_hessenberg()
@property
def is_upper(self):
"""Check if matrix is an upper triangular matrix. True can be returned
even if the matrix is not square.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(2, 2, [1, 0, 0, 1])
>>> m
Matrix([
[1, 0],
[0, 1]])
>>> m.is_upper
True
>>> m = Matrix(4, 3, [5, 1, 9, 0, 4 , 6, 0, 0, 5, 0, 0, 0])
>>> m
Matrix([
[5, 1, 9],
[0, 4, 6],
[0, 0, 5],
[0, 0, 0]])
>>> m.is_upper
True
>>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1])
>>> m
Matrix([
[4, 2, 5],
[6, 1, 1]])
>>> m.is_upper
False
See Also
========
is_lower
is_diagonal
is_upper_hessenberg
"""
return all(self[i, j].is_zero
for i in range(1, self.rows)
for j in range(min(i, self.cols)))
@property
def is_zero_matrix(self):
"""Checks if a matrix is a zero matrix.
A matrix is zero if every element is zero. A matrix need not be square
to be considered zero. The empty matrix is zero by the principle of
vacuous truth. For a matrix that may or may not be zero (e.g.
contains a symbol), this will be None
Examples
========
>>> from sympy import Matrix, zeros
>>> from sympy.abc import x
>>> a = Matrix([[0, 0], [0, 0]])
>>> b = zeros(3, 4)
>>> c = Matrix([[0, 1], [0, 0]])
>>> d = Matrix([])
>>> e = Matrix([[x, 0], [0, 0]])
>>> a.is_zero_matrix
True
>>> b.is_zero_matrix
True
>>> c.is_zero_matrix
False
>>> d.is_zero_matrix
True
>>> e.is_zero_matrix
"""
return self._eval_is_zero_matrix()
def values(self):
"""Return non-zero values of self."""
return self._eval_values()
class MatrixOperations(MatrixRequired):
"""Provides basic matrix shape and elementwise
operations. Should not be instantiated directly."""
def _eval_adjoint(self):
return self.transpose().conjugate()
def _eval_applyfunc(self, f):
out = self._new(self.rows, self.cols, [f(x) for x in self])
return out
def _eval_as_real_imag(self): # type: ignore
from sympy.functions.elementary.complexes import re, im
return (self.applyfunc(re), self.applyfunc(im))
def _eval_conjugate(self):
return self.applyfunc(lambda x: x.conjugate())
def _eval_permute_cols(self, perm):
# apply the permutation to a list
mapping = list(perm)
def entry(i, j):
return self[i, mapping[j]]
return self._new(self.rows, self.cols, entry)
def _eval_permute_rows(self, perm):
# apply the permutation to a list
mapping = list(perm)
def entry(i, j):
return self[mapping[i], j]
return self._new(self.rows, self.cols, entry)
def _eval_trace(self):
return sum(self[i, i] for i in range(self.rows))
def _eval_transpose(self):
return self._new(self.cols, self.rows, lambda i, j: self[j, i])
def adjoint(self):
"""Conjugate transpose or Hermitian conjugation."""
return self._eval_adjoint()
def applyfunc(self, f):
"""Apply a function to each element of the matrix.
Examples
========
>>> from sympy import Matrix
>>> m = Matrix(2, 2, lambda i, j: i*2+j)
>>> m
Matrix([
[0, 1],
[2, 3]])
>>> m.applyfunc(lambda i: 2*i)
Matrix([
[0, 2],
[4, 6]])
"""
if not callable(f):
raise TypeError("`f` must be callable.")
return self._eval_applyfunc(f)
def as_real_imag(self, deep=True, **hints):
"""Returns a tuple containing the (real, imaginary) part of matrix."""
# XXX: Ignoring deep and hints...
return self._eval_as_real_imag()
def conjugate(self):
"""Return the by-element conjugation.
Examples
========
>>> from sympy.matrices import SparseMatrix
>>> from sympy import I
>>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I)))
>>> a
Matrix([
[1, 2 + I],
[3, 4],
[I, -I]])
>>> a.C
Matrix([
[ 1, 2 - I],
[ 3, 4],
[-I, I]])
See Also
========
transpose: Matrix transposition
H: Hermite conjugation
sympy.matrices.matrices.MatrixBase.D: Dirac conjugation
"""
return self._eval_conjugate()
def doit(self, **kwargs):
return self.applyfunc(lambda x: x.doit())
def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False):
"""Apply evalf() to each element of self."""
options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict,
'quad':quad, 'verbose':verbose}
return self.applyfunc(lambda i: i.evalf(n, **options))
def expand(self, deep=True, modulus=None, power_base=True, power_exp=True,
mul=True, log=True, multinomial=True, basic=True, **hints):
"""Apply core.function.expand to each entry of the matrix.
Examples
========
>>> from sympy.abc import x
>>> from sympy.matrices import Matrix
>>> Matrix(1, 1, [x*(x+1)])
Matrix([[x*(x + 1)]])
>>> _.expand()
Matrix([[x**2 + x]])
"""
return self.applyfunc(lambda x: x.expand(
deep, modulus, power_base, power_exp, mul, log, multinomial, basic,
**hints))
@property
def H(self):
"""Return Hermite conjugate.
Examples
========
>>> from sympy import Matrix, I
>>> m = Matrix((0, 1 + I, 2, 3))
>>> m
Matrix([
[ 0],
[1 + I],
[ 2],
[ 3]])
>>> m.H
Matrix([[0, 1 - I, 2, 3]])
See Also
========
conjugate: By-element conjugation
sympy.matrices.matrices.MatrixBase.D: Dirac conjugation
"""
return self.T.C
def permute(self, perm, orientation='rows', direction='forward'):
r"""Permute the rows or columns of a matrix by the given list of
swaps.
Parameters
==========
perm : Permutation, list, or list of lists
A representation for the permutation.
If it is ``Permutation``, it is used directly with some
resizing with respect to the matrix size.
If it is specified as list of lists,
(e.g., ``[[0, 1], [0, 2]]``), then the permutation is formed
from applying the product of cycles. The direction how the
cyclic product is applied is described in below.
If it is specified as a list, the list should represent
an array form of a permutation. (e.g., ``[1, 2, 0]``) which
would would form the swapping function
`0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0`.
orientation : 'rows', 'cols'
A flag to control whether to permute the rows or the columns
direction : 'forward', 'backward'
A flag to control whether to apply the permutations from
the start of the list first, or from the back of the list
first.
For example, if the permutation specification is
``[[0, 1], [0, 2]]``,
If the flag is set to ``'forward'``, the cycle would be
formed as `0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0`.
If the flag is set to ``'backward'``, the cycle would be
formed as `0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0`.
If the argument ``perm`` is not in a form of list of lists,
this flag takes no effect.
Examples
========
>>> from sympy.matrices import eye
>>> M = eye(3)
>>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward')
Matrix([
[0, 0, 1],
[1, 0, 0],
[0, 1, 0]])
>>> from sympy.matrices import eye
>>> M = eye(3)
>>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward')
Matrix([
[0, 1, 0],
[0, 0, 1],
[1, 0, 0]])
Notes
=====
If a bijective function
`\sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0` denotes the
permutation.
If the matrix `A` is the matrix to permute, represented as
a horizontal or a vertical stack of vectors:
.. math::
A =
\begin{bmatrix}
a_0 \\ a_1 \\ \vdots \\ a_{n-1}
\end{bmatrix} =
\begin{bmatrix}
\alpha_0 & \alpha_1 & \cdots & \alpha_{n-1}
\end{bmatrix}
If the matrix `B` is the result, the permutation of matrix rows
is defined as:
.. math::
B := \begin{bmatrix}
a_{\sigma(0)} \\ a_{\sigma(1)} \\ \vdots \\ a_{\sigma(n-1)}
\end{bmatrix}
And the permutation of matrix columns is defined as:
.. math::
B := \begin{bmatrix}
\alpha_{\sigma(0)} & \alpha_{\sigma(1)} &
\cdots & \alpha_{\sigma(n-1)}
\end{bmatrix}
"""
from sympy.combinatorics import Permutation
# allow british variants and `columns`
if direction == 'forwards':
direction = 'forward'
if direction == 'backwards':
direction = 'backward'
if orientation == 'columns':
orientation = 'cols'
if direction not in ('forward', 'backward'):
raise TypeError("direction='{}' is an invalid kwarg. "
"Try 'forward' or 'backward'".format(direction))
if orientation not in ('rows', 'cols'):
raise TypeError("orientation='{}' is an invalid kwarg. "
"Try 'rows' or 'cols'".format(orientation))
if not isinstance(perm, (Permutation, Iterable)):
raise ValueError(
"{} must be a list, a list of lists, "
"or a SymPy permutation object.".format(perm))
# ensure all swaps are in range
max_index = self.rows if orientation == 'rows' else self.cols
if not all(0 <= t <= max_index for t in flatten(list(perm))):
raise IndexError("`swap` indices out of range.")
if perm and not isinstance(perm, Permutation) and \
isinstance(perm[0], Iterable):
if direction == 'forward':
perm = list(reversed(perm))
perm = Permutation(perm, size=max_index+1)
else:
perm = Permutation(perm, size=max_index+1)
if orientation == 'rows':
return self._eval_permute_rows(perm)
if orientation == 'cols':
return self._eval_permute_cols(perm)
def permute_cols(self, swaps, direction='forward'):
"""Alias for
``self.permute(swaps, orientation='cols', direction=direction)``
See Also
========
permute
"""
return self.permute(swaps, orientation='cols', direction=direction)
def permute_rows(self, swaps, direction='forward'):
"""Alias for
``self.permute(swaps, orientation='rows', direction=direction)``
See Also
========
permute
"""
return self.permute(swaps, orientation='rows', direction=direction)
def refine(self, assumptions=True):
"""Apply refine to each element of the matrix.
Examples
========
>>> from sympy import Symbol, Matrix, Abs, sqrt, Q
>>> x = Symbol('x')
>>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]])
Matrix([
[ Abs(x)**2, sqrt(x**2)],
[sqrt(x**2), Abs(x)**2]])
>>> _.refine(Q.real(x))
Matrix([
[ x**2, Abs(x)],
[Abs(x), x**2]])
"""
return self.applyfunc(lambda x: refine(x, assumptions))
def replace(self, F, G, map=False, simultaneous=True, exact=None):
"""Replaces Function F in Matrix entries with Function G.
Examples
========
>>> from sympy import symbols, Function, Matrix
>>> F, G = symbols('F, G', cls=Function)
>>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M
Matrix([
[F(0), F(1)],
[F(1), F(2)]])
>>> N = M.replace(F,G)
>>> N
Matrix([
[G(0), G(1)],
[G(1), G(2)]])
"""
return self.applyfunc(
lambda x: x.replace(F, G, map=map, simultaneous=simultaneous, exact=exact))
def rot90(self, k=1):
"""Rotates Matrix by 90 degrees
Parameters
==========
k : int
Specifies how many times the matrix is rotated by 90 degrees
(clockwise when positive, counter-clockwise when negative).
Examples
========
>>> from sympy import Matrix, symbols
>>> A = Matrix(2, 2, symbols('a:d'))
>>> A
Matrix([
[a, b],
[c, d]])
Rotating the matrix clockwise one time:
>>> A.rot90(1)
Matrix([
[c, a],
[d, b]])
Rotating the matrix anticlockwise two times:
>>> A.rot90(-2)
Matrix([
[d, c],
[b, a]])
"""
mod = k%4
if mod == 0:
return self
if mod == 1:
return self[::-1, ::].T
if mod == 2:
return self[::-1, ::-1]
if mod == 3:
return self[::, ::-1].T
def simplify(self, **kwargs):
"""Apply simplify to each element of the matrix.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import sin, cos
>>> from sympy.matrices import SparseMatrix
>>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2])
Matrix([[x*sin(y)**2 + x*cos(y)**2]])
>>> _.simplify()
Matrix([[x]])
"""
return self.applyfunc(lambda x: x.simplify(**kwargs))
def subs(self, *args, **kwargs): # should mirror core.basic.subs
"""Return a new matrix with subs applied to each entry.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.matrices import SparseMatrix, Matrix
>>> SparseMatrix(1, 1, [x])
Matrix([[x]])
>>> _.subs(x, y)
Matrix([[y]])
>>> Matrix(_).subs(y, x)
Matrix([[x]])
"""
if len(args) == 1 and not isinstance(args[0], (dict, set)) and iter(args[0]) and not is_sequence(args[0]):
args = (list(args[0]),)
return self.applyfunc(lambda x: x.subs(*args, **kwargs))
def trace(self):
"""
Returns the trace of a square matrix i.e. the sum of the
diagonal elements.
Examples
========
>>> from sympy import Matrix
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> A.trace()
5
"""
if self.rows != self.cols:
raise NonSquareMatrixError()
return self._eval_trace()
def transpose(self):
"""
Returns the transpose of the matrix.
Examples
========
>>> from sympy import Matrix
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> A.transpose()
Matrix([
[1, 3],
[2, 4]])
>>> from sympy import Matrix, I
>>> m=Matrix(((1, 2+I), (3, 4)))
>>> m
Matrix([
[1, 2 + I],
[3, 4]])
>>> m.transpose()
Matrix([
[ 1, 3],
[2 + I, 4]])
>>> m.T == m.transpose()
True
See Also
========
conjugate: By-element conjugation
"""
return self._eval_transpose()
@property
def T(self):
'''Matrix transposition'''
return self.transpose()
@property
def C(self):
'''By-element conjugation'''
return self.conjugate()
def n(self, *args, **kwargs):
"""Apply evalf() to each element of self."""
return self.evalf(*args, **kwargs)
def xreplace(self, rule): # should mirror core.basic.xreplace
"""Return a new matrix with xreplace applied to each entry.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.matrices import SparseMatrix, Matrix
>>> SparseMatrix(1, 1, [x])
Matrix([[x]])
>>> _.xreplace({x: y})
Matrix([[y]])
>>> Matrix(_).xreplace({y: x})
Matrix([[x]])
"""
return self.applyfunc(lambda x: x.xreplace(rule))
def _eval_simplify(self, **kwargs):
# XXX: We can't use self.simplify here as mutable subclasses will
# override simplify and have it return None
return MatrixOperations.simplify(self, **kwargs)
def _eval_trigsimp(self, **opts):
from sympy.simplify import trigsimp
return self.applyfunc(lambda x: trigsimp(x, **opts))
def upper_triangular(self, k=0):
"""returns the elements on and above the kth diagonal of a matrix.
If k is not specified then simply returns upper-triangular portion
of a matrix
Examples
========
>>> from sympy import ones
>>> A = ones(4)
>>> A.upper_triangular()
Matrix([
[1, 1, 1, 1],
[0, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, 0, 1]])
>>> A.upper_triangular(2)
Matrix([
[0, 0, 1, 1],
[0, 0, 0, 1],
[0, 0, 0, 0],
[0, 0, 0, 0]])
>>> A.upper_triangular(-1)
Matrix([
[1, 1, 1, 1],
[1, 1, 1, 1],
[0, 1, 1, 1],
[0, 0, 1, 1]])
"""
def entry(i, j):
return self[i, j] if i + k <= j else self.zero
return self._new(self.rows, self.cols, entry)
def lower_triangular(self, k=0):
"""returns the elements on and below the kth diagonal of a matrix.
If k is not specified then simply returns lower-triangular portion
of a matrix
Examples
========
>>> from sympy import ones
>>> A = ones(4)
>>> A.lower_triangular()
Matrix([
[1, 0, 0, 0],
[1, 1, 0, 0],
[1, 1, 1, 0],
[1, 1, 1, 1]])
>>> A.lower_triangular(-2)
Matrix([
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 0, 0, 0],
[1, 1, 0, 0]])
>>> A.lower_triangular(1)
Matrix([
[1, 1, 0, 0],
[1, 1, 1, 0],
[1, 1, 1, 1],
[1, 1, 1, 1]])
"""
def entry(i, j):
return self[i, j] if i + k >= j else self.zero
return self._new(self.rows, self.cols, entry)
class MatrixArithmetic(MatrixRequired):
"""Provides basic matrix arithmetic operations.
Should not be instantiated directly."""
_op_priority = 10.01
def _eval_Abs(self):
return self._new(self.rows, self.cols, lambda i, j: Abs(self[i, j]))
def _eval_add(self, other):
return self._new(self.rows, self.cols,
lambda i, j: self[i, j] + other[i, j])
def _eval_matrix_mul(self, other):
def entry(i, j):
vec = [self[i,k]*other[k,j] for k in range(self.cols)]
try:
return Add(*vec)
except (TypeError, SympifyError):
# Some matrices don't work with `sum` or `Add`
# They don't work with `sum` because `sum` tries to add `0`
# Fall back to a safe way to multiply if the `Add` fails.
return reduce(lambda a, b: a + b, vec)
return self._new(self.rows, other.cols, entry)
def _eval_matrix_mul_elementwise(self, other):
return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other[i,j])
def _eval_matrix_rmul(self, other):
def entry(i, j):
return sum(other[i,k]*self[k,j] for k in range(other.cols))
return self._new(other.rows, self.cols, entry)
def _eval_pow_by_recursion(self, num):
if num == 1:
return self
if num % 2 == 1:
a, b = self, self._eval_pow_by_recursion(num - 1)
else:
a = b = self._eval_pow_by_recursion(num // 2)
return a.multiply(b)
def _eval_pow_by_cayley(self, exp):
from sympy.discrete.recurrences import linrec_coeffs
row = self.shape[0]
p = self.charpoly()
coeffs = (-p).all_coeffs()[1:]
coeffs = linrec_coeffs(coeffs, exp)
new_mat = self.eye(row)
ans = self.zeros(row)
for i in range(row):
ans += coeffs[i]*new_mat
new_mat *= self
return ans
def _eval_pow_by_recursion_dotprodsimp(self, num, prevsimp=None):
if prevsimp is None:
prevsimp = [True]*len(self)
if num == 1:
return self
if num % 2 == 1:
a, b = self, self._eval_pow_by_recursion_dotprodsimp(num - 1,
prevsimp=prevsimp)
else:
a = b = self._eval_pow_by_recursion_dotprodsimp(num // 2,
prevsimp=prevsimp)
m = a.multiply(b, dotprodsimp=False)
lenm = len(m)
elems = [None]*lenm
for i in range(lenm):
if prevsimp[i]:
elems[i], prevsimp[i] = _dotprodsimp(m[i], withsimp=True)
else:
elems[i] = m[i]
return m._new(m.rows, m.cols, elems)
def _eval_scalar_mul(self, other):
return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other)
def _eval_scalar_rmul(self, other):
return self._new(self.rows, self.cols, lambda i, j: other*self[i,j])
def _eval_Mod(self, other):
from sympy import Mod
return self._new(self.rows, self.cols, lambda i, j: Mod(self[i, j], other))
# python arithmetic functions
def __abs__(self):
"""Returns a new matrix with entry-wise absolute values."""
return self._eval_Abs()
@call_highest_priority('__radd__')
def __add__(self, other):
"""Return self + other, raising ShapeError if shapes don't match."""
if isinstance(other, NDimArray): # Matrix and array addition is currently not implemented
return NotImplemented
other = _matrixify(other)
# matrix-like objects can have shapes. This is
# our first sanity check.
if hasattr(other, 'shape'):
if self.shape != other.shape:
raise ShapeError("Matrix size mismatch: %s + %s" % (
self.shape, other.shape))
# honest sympy matrices defer to their class's routine
if getattr(other, 'is_Matrix', False):
# call the highest-priority class's _eval_add
a, b = self, other
if a.__class__ != classof(a, b):
b, a = a, b
return a._eval_add(b)
# Matrix-like objects can be passed to CommonMatrix routines directly.
if getattr(other, 'is_MatrixLike', False):
return MatrixArithmetic._eval_add(self, other)
raise TypeError('cannot add %s and %s' % (type(self), type(other)))
@call_highest_priority('__rtruediv__')
def __truediv__(self, other):
return self * (self.one / other)
@call_highest_priority('__rmatmul__')
def __matmul__(self, other):
other = _matrixify(other)
if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False):
return NotImplemented
return self.__mul__(other)
def __mod__(self, other):
return self.applyfunc(lambda x: x % other)
@call_highest_priority('__rmul__')
def __mul__(self, other):
"""Return self*other where other is either a scalar or a matrix
of compatible dimensions.
Examples
========
>>> from sympy.matrices import Matrix
>>> A = Matrix([[1, 2, 3], [4, 5, 6]])
>>> 2*A == A*2 == Matrix([[2, 4, 6], [8, 10, 12]])
True
>>> B = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> A*B
Matrix([
[30, 36, 42],
[66, 81, 96]])
>>> B*A
Traceback (most recent call last):
...
ShapeError: Matrices size mismatch.
>>>
See Also
========
matrix_multiply_elementwise
"""
return self.multiply(other)
def multiply(self, other, dotprodsimp=None):
"""Same as __mul__() but with optional simplification.
Parameters
==========
dotprodsimp : bool, optional
Specifies whether intermediate term algebraic simplification is used
during matrix multiplications to control expression blowup and thus
speed up calculation. Default is off.
"""
isimpbool = _get_intermediate_simp_bool(False, dotprodsimp)
other = _matrixify(other)
# matrix-like objects can have shapes. This is
# our first sanity check. Double check other is not explicitly not a Matrix.
if (hasattr(other, 'shape') and len(other.shape) == 2 and
(getattr(other, 'is_Matrix', True) or
getattr(other, 'is_MatrixLike', True))):
if self.shape[1] != other.shape[0]:
raise ShapeError("Matrix size mismatch: %s * %s." % (
self.shape, other.shape))
# honest sympy matrices defer to their class's routine
if getattr(other, 'is_Matrix', False):
m = self._eval_matrix_mul(other)
if isimpbool:
return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m])
return m
# Matrix-like objects can be passed to CommonMatrix routines directly.
if getattr(other, 'is_MatrixLike', False):
return MatrixArithmetic._eval_matrix_mul(self, other)
# if 'other' is not iterable then scalar multiplication.
if not isinstance(other, Iterable):
try:
return self._eval_scalar_mul(other)
except TypeError:
pass
return NotImplemented
def multiply_elementwise(self, other):
"""Return the Hadamard product (elementwise product) of A and B
Examples
========
>>> from sympy.matrices import Matrix
>>> A = Matrix([[0, 1, 2], [3, 4, 5]])
>>> B = Matrix([[1, 10, 100], [100, 10, 1]])
>>> A.multiply_elementwise(B)
Matrix([
[ 0, 10, 200],
[300, 40, 5]])
See Also
========
sympy.matrices.matrices.MatrixBase.cross
sympy.matrices.matrices.MatrixBase.dot
multiply
"""
if self.shape != other.shape:
raise ShapeError("Matrix shapes must agree {} != {}".format(self.shape, other.shape))
return self._eval_matrix_mul_elementwise(other)
def __neg__(self):
return self._eval_scalar_mul(-1)
@call_highest_priority('__rpow__')
def __pow__(self, exp):
"""Return self**exp a scalar or symbol."""
return self.pow(exp)
def pow(self, exp, method=None):
r"""Return self**exp a scalar or symbol.
Parameters
==========
method : multiply, mulsimp, jordan, cayley
If multiply then it returns exponentiation using recursion.
If jordan then Jordan form exponentiation will be used.
If cayley then the exponentiation is done using Cayley-Hamilton
theorem.
If mulsimp then the exponentiation is done using recursion
with dotprodsimp. This specifies whether intermediate term
algebraic simplification is used during naive matrix power to
control expression blowup and thus speed up calculation.
If None, then it heuristically decides which method to use.
"""
if method is not None and method not in ['multiply', 'mulsimp', 'jordan', 'cayley']:
raise TypeError('No such method')
if self.rows != self.cols:
raise NonSquareMatrixError()
a = self
jordan_pow = getattr(a, '_matrix_pow_by_jordan_blocks', None)
exp = sympify(exp)
if exp.is_zero:
return a._new(a.rows, a.cols, lambda i, j: int(i == j))
if exp == 1:
return a
diagonal = getattr(a, 'is_diagonal', None)
if diagonal is not None and diagonal():
return a._new(a.rows, a.cols, lambda i, j: a[i,j]**exp if i == j else 0)
if exp.is_Number and exp % 1 == 0:
if a.rows == 1:
return a._new([[a[0]**exp]])
if exp < 0:
exp = -exp
a = a.inv()
# When certain conditions are met,
# Jordan block algorithm is faster than
# computation by recursion.
if method == 'jordan':
try:
return jordan_pow(exp)
except MatrixError:
if method == 'jordan':
raise
elif method == 'cayley':
if not exp.is_Number or exp % 1 != 0:
raise ValueError("cayley method is only valid for integer powers")
return a._eval_pow_by_cayley(exp)
elif method == "mulsimp":
if not exp.is_Number or exp % 1 != 0:
raise ValueError("mulsimp method is only valid for integer powers")
return a._eval_pow_by_recursion_dotprodsimp(exp)
elif method == "multiply":
if not exp.is_Number or exp % 1 != 0:
raise ValueError("multiply method is only valid for integer powers")
return a._eval_pow_by_recursion(exp)
elif method is None and exp.is_Number and exp % 1 == 0:
# Decide heuristically which method to apply
if a.rows == 2 and exp > 100000:
return jordan_pow(exp)
elif _get_intermediate_simp_bool(True, None):
return a._eval_pow_by_recursion_dotprodsimp(exp)
elif exp > 10000:
return a._eval_pow_by_cayley(exp)
else:
return a._eval_pow_by_recursion(exp)
if jordan_pow:
try:
return jordan_pow(exp)
except NonInvertibleMatrixError:
# Raised by jordan_pow on zero determinant matrix unless exp is
# definitely known to be a non-negative integer.
# Here we raise if n is definitely not a non-negative integer
# but otherwise we can leave this as an unevaluated MatPow.
if exp.is_integer is False or exp.is_nonnegative is False:
raise
from sympy.matrices.expressions import MatPow
return MatPow(a, exp)
@call_highest_priority('__add__')
def __radd__(self, other):
return self + other
@call_highest_priority('__matmul__')
def __rmatmul__(self, other):
other = _matrixify(other)
if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False):
return NotImplemented
return self.__rmul__(other)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return self.rmultiply(other)
def rmultiply(self, other, dotprodsimp=None):
"""Same as __rmul__() but with optional simplification.
Parameters
==========
dotprodsimp : bool, optional
Specifies whether intermediate term algebraic simplification is used
during matrix multiplications to control expression blowup and thus
speed up calculation. Default is off.
"""
isimpbool = _get_intermediate_simp_bool(False, dotprodsimp)
other = _matrixify(other)
# matrix-like objects can have shapes. This is
# our first sanity check. Double check other is not explicitly not a Matrix.
if (hasattr(other, 'shape') and len(other.shape) == 2 and
(getattr(other, 'is_Matrix', True) or
getattr(other, 'is_MatrixLike', True))):
if self.shape[0] != other.shape[1]:
raise ShapeError("Matrix size mismatch.")
# honest sympy matrices defer to their class's routine
if getattr(other, 'is_Matrix', False):
m = self._eval_matrix_rmul(other)
if isimpbool:
return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m])
return m
# Matrix-like objects can be passed to CommonMatrix routines directly.
if getattr(other, 'is_MatrixLike', False):
return MatrixArithmetic._eval_matrix_rmul(self, other)
# if 'other' is not iterable then scalar multiplication.
if not isinstance(other, Iterable):
try:
return self._eval_scalar_rmul(other)
except TypeError:
pass
return NotImplemented
@call_highest_priority('__sub__')
def __rsub__(self, a):
return (-self) + a
@call_highest_priority('__rsub__')
def __sub__(self, a):
return self + (-a)
class MatrixCommon(MatrixArithmetic, MatrixOperations, MatrixProperties,
MatrixSpecial, MatrixShaping):
"""All common matrix operations including basic arithmetic, shaping,
and special matrices like `zeros`, and `eye`."""
_diff_wrt = True # type: bool
class _MinimalMatrix:
"""Class providing the minimum functionality
for a matrix-like object and implementing every method
required for a `MatrixRequired`. This class does not have everything
needed to become a full-fledged SymPy object, but it will satisfy the
requirements of anything inheriting from `MatrixRequired`. If you wish
to make a specialized matrix type, make sure to implement these
methods and properties with the exception of `__init__` and `__repr__`
which are included for convenience."""
is_MatrixLike = True
_sympify = staticmethod(sympify)
_class_priority = 3
zero = S.Zero
one = S.One
is_Matrix = True
is_MatrixExpr = False
@classmethod
def _new(cls, *args, **kwargs):
return cls(*args, **kwargs)
def __init__(self, rows, cols=None, mat=None, copy=False):
if isfunction(mat):
# if we passed in a function, use that to populate the indices
mat = list(mat(i, j) for i in range(rows) for j in range(cols))
if cols is None and mat is None:
mat = rows
rows, cols = getattr(mat, 'shape', (rows, cols))
try:
# if we passed in a list of lists, flatten it and set the size
if cols is None and mat is None:
mat = rows
cols = len(mat[0])
rows = len(mat)
mat = [x for l in mat for x in l]
except (IndexError, TypeError):
pass
self.mat = tuple(self._sympify(x) for x in mat)
self.rows, self.cols = rows, cols
if self.rows is None or self.cols is None:
raise NotImplementedError("Cannot initialize matrix with given parameters")
def __getitem__(self, key):
def _normalize_slices(row_slice, col_slice):
"""Ensure that row_slice and col_slice don't have
`None` in their arguments. Any integers are converted
to slices of length 1"""
if not isinstance(row_slice, slice):
row_slice = slice(row_slice, row_slice + 1, None)
row_slice = slice(*row_slice.indices(self.rows))
if not isinstance(col_slice, slice):
col_slice = slice(col_slice, col_slice + 1, None)
col_slice = slice(*col_slice.indices(self.cols))
return (row_slice, col_slice)
def _coord_to_index(i, j):
"""Return the index in _mat corresponding
to the (i,j) position in the matrix. """
return i * self.cols + j
if isinstance(key, tuple):
i, j = key
if isinstance(i, slice) or isinstance(j, slice):
# if the coordinates are not slices, make them so
# and expand the slices so they don't contain `None`
i, j = _normalize_slices(i, j)
rowsList, colsList = list(range(self.rows))[i], \
list(range(self.cols))[j]
indices = (i * self.cols + j for i in rowsList for j in
colsList)
return self._new(len(rowsList), len(colsList),
list(self.mat[i] for i in indices))
# if the key is a tuple of ints, change
# it to an array index
key = _coord_to_index(i, j)
return self.mat[key]
def __eq__(self, other):
try:
classof(self, other)
except TypeError:
return False
return (
self.shape == other.shape and list(self) == list(other))
def __len__(self):
return self.rows*self.cols
def __repr__(self):
return "_MinimalMatrix({}, {}, {})".format(self.rows, self.cols,
self.mat)
@property
def shape(self):
return (self.rows, self.cols)
class _CastableMatrix: # this is needed here ONLY FOR TESTS.
def as_mutable(self):
return self
def as_immutable(self):
return self
class _MatrixWrapper:
"""Wrapper class providing the minimum functionality for a matrix-like
object: .rows, .cols, .shape, indexability, and iterability. CommonMatrix
math operations should work on matrix-like objects. This one is intended for
matrix-like objects which use the same indexing format as SymPy with respect
to returning matrix elements instead of rows for non-tuple indexes.
"""
is_Matrix = False # needs to be here because of __getattr__
is_MatrixLike = True
def __init__(self, mat, shape):
self.mat = mat
self.shape = shape
self.rows, self.cols = shape
def __getitem__(self, key):
if isinstance(key, tuple):
return sympify(self.mat.__getitem__(key))
return sympify(self.mat.__getitem__((key // self.rows, key % self.cols)))
def __iter__(self): # supports numpy.matrix and numpy.array
mat = self.mat
cols = self.cols
return iter(sympify(mat[r, c]) for r in range(self.rows) for c in range(cols))
class MatrixKind(Kind):
"""
Kind for all matrices in SymPy.
Basic class for this kind is ``MatrixBase`` and ``MatrixExpr``,
but any expression representing the matrix can have this.
Parameters
==========
element_kind : Kind
Kind of the element. Default is :obj:NumberKind `<sympy.core.kind.NumberKind>`,
which means that the matrix contains only numbers.
Examples
========
Any instance of matrix class has ``MatrixKind``.
>>> from sympy import MatrixSymbol
>>> A = MatrixSymbol('A', 2,2)
>>> A.kind
MatrixKind(NumberKind)
Although expression representing a matrix may be not instance of
matrix class, it will have ``MatrixKind`` as well.
>>> from sympy import Integral
>>> from sympy.matrices.expressions import MatrixExpr
>>> from sympy.abc import x
>>> intM = Integral(A, x)
>>> isinstance(intM, MatrixExpr)
False
>>> intM.kind
MatrixKind(NumberKind)
Use ``isinstance()`` to check for ``MatrixKind` without specifying
the element kind. Use ``is`` with specifying the element kind.
>>> from sympy import Matrix
>>> from sympy.matrices import MatrixKind
>>> from sympy.core.kind import NumberKind
>>> M = Matrix([1, 2])
>>> isinstance(M.kind, MatrixKind)
True
>>> M.kind is MatrixKind(NumberKind)
True
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 "MatrixKind(%s)" % self.element_kind
def _matrixify(mat):
"""If `mat` is a Matrix or is matrix-like,
return a Matrix or MatrixWrapper object. Otherwise
`mat` is passed through without modification."""
if getattr(mat, 'is_Matrix', False) or getattr(mat, 'is_MatrixLike', False):
return mat
if not(getattr(mat, 'is_Matrix', True) or getattr(mat, 'is_MatrixLike', True)):
return mat
shape = None
if hasattr(mat, 'shape'): # numpy, scipy.sparse
if len(mat.shape) == 2:
shape = mat.shape
elif hasattr(mat, 'rows') and hasattr(mat, 'cols'): # mpmath
shape = (mat.rows, mat.cols)
if shape:
return _MatrixWrapper(mat, shape)
return mat
def a2idx(j, n=None):
"""Return integer after making positive and validating against n."""
if type(j) is not int:
jindex = getattr(j, '__index__', None)
if jindex is not None:
j = jindex()
else:
raise IndexError("Invalid index a[%r]" % (j,))
if n is not None:
if j < 0:
j += n
if not (j >= 0 and j < n):
raise IndexError("Index out of range: a[%s]" % (j,))
return int(j)
def classof(A, B):
"""
Get the type of the result when combining matrices of different types.
Currently the strategy is that immutability is contagious.
Examples
========
>>> from sympy import Matrix, ImmutableMatrix
>>> from sympy.matrices.common import classof
>>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix
>>> IM = ImmutableMatrix([[1, 2], [3, 4]])
>>> classof(M, IM)
<class 'sympy.matrices.immutable.ImmutableDenseMatrix'>
"""
priority_A = getattr(A, '_class_priority', None)
priority_B = getattr(B, '_class_priority', None)
if None not in (priority_A, priority_B):
if A._class_priority > B._class_priority:
return A.__class__
else:
return B.__class__
try:
import numpy
except ImportError:
pass
else:
if isinstance(A, numpy.ndarray):
return B.__class__
if isinstance(B, numpy.ndarray):
return A.__class__
raise TypeError("Incompatible classes %s, %s" % (A.__class__, B.__class__))
|
8dae22adca89490c8ccf4c6e841f6c0e0941590c4c8ac4f37f9f218bbf83e4c8 | import random
from functools import reduce
from sympy.core import SympifyError, Add
from sympy.core.basic import Basic
from sympy.core.compatibility import is_sequence
from sympy.core.expr import Expr
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify, _sympify
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.matrices.common import \
a2idx, classof, ShapeError
from sympy.matrices.matrices import MatrixBase
from sympy.simplify.simplify import simplify as _simplify
from sympy.utilities.decorator import doctest_depends_on
from sympy.utilities.misc import filldedent
from sympy.utilities.exceptions import SymPyDeprecationWarning
from .decompositions import _cholesky, _LDLdecomposition
from .solvers import _lower_triangular_solve, _upper_triangular_solve
def _iszero(x):
"""Returns True if x is zero."""
return x.is_zero
def _compare_sequence(a, b):
"""Compares the elements of a list/tuple `a`
and a list/tuple `b`. `_compare_sequence((1,2), [1, 2])`
is True, whereas `(1,2) == [1, 2]` is False"""
if type(a) is type(b):
# if they are the same type, compare directly
return a == b
# there is no overhead for calling `tuple` on a
# tuple
return tuple(a) == tuple(b)
class DenseMatrix(MatrixBase):
is_MatrixExpr = False # type: bool
_op_priority = 10.01
_class_priority = 4
def __eq__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
self_shape = getattr(self, 'shape', None)
other_shape = getattr(other, 'shape', None)
if None in (self_shape, other_shape):
return False
if self_shape != other_shape:
return False
if isinstance(other, Matrix):
return _compare_sequence(self._mat, other._mat)
elif isinstance(other, MatrixBase):
return _compare_sequence(self._mat, Matrix(other)._mat)
def __getitem__(self, key):
"""Return portion of self defined by key. If the key involves a slice
then a list will be returned (if key is a single slice) or a matrix
(if key was a tuple involving a slice).
Examples
========
>>> from sympy import Matrix, I
>>> m = Matrix([
... [1, 2 + I],
... [3, 4 ]])
If the key is a tuple that doesn't involve a slice then that element
is returned:
>>> m[1, 0]
3
When a tuple key involves a slice, a matrix is returned. Here, the
first column is selected (all rows, column 0):
>>> m[:, 0]
Matrix([
[1],
[3]])
If the slice is not a tuple then it selects from the underlying
list of elements that are arranged in row order and a list is
returned if a slice is involved:
>>> m[0]
1
>>> m[::2]
[1, 3]
"""
if isinstance(key, tuple):
i, j = key
try:
i, j = self.key2ij(key)
return self._mat[i*self.cols + j]
except (TypeError, IndexError):
if (isinstance(i, Expr) and not i.is_number) or (isinstance(j, Expr) and not j.is_number):
if ((j < 0) is True) or ((j >= self.shape[1]) is True) or\
((i < 0) is True) or ((i >= self.shape[0]) is True):
raise ValueError("index out of boundary")
from sympy.matrices.expressions.matexpr import MatrixElement
return MatrixElement(self, i, j)
if isinstance(i, slice):
i = range(self.rows)[i]
elif is_sequence(i):
pass
else:
i = [i]
if isinstance(j, slice):
j = range(self.cols)[j]
elif is_sequence(j):
pass
else:
j = [j]
return self.extract(i, j)
else:
# row-wise decomposition of matrix
if isinstance(key, slice):
return self._mat[key]
return self._mat[a2idx(key)]
def __setitem__(self, key, value):
raise NotImplementedError()
def _eval_add(self, other):
# we assume both arguments are dense matrices since
# sparse matrices have a higher priority
mat = [a + b for a,b in zip(self._mat, other._mat)]
return classof(self, other)._new(self.rows, self.cols, mat, copy=False)
def _eval_extract(self, rowsList, colsList):
mat = self._mat
cols = self.cols
indices = (i * cols + j for i in rowsList for j in colsList)
return self._new(len(rowsList), len(colsList),
list(mat[i] for i in indices), copy=False)
def _eval_matrix_mul(self, other):
other_len = other.rows*other.cols
new_len = self.rows*other.cols
new_mat = [self.zero]*new_len
# if we multiply an n x 0 with a 0 x m, the
# expected behavior is to produce an n x m matrix of zeros
if self.cols != 0 and other.rows != 0:
self_cols = self.cols
mat = self._mat
other_mat = other._mat
for i in range(new_len):
row, col = i // other.cols, i % other.cols
row_indices = range(self_cols*row, self_cols*(row+1))
col_indices = range(col, other_len, other.cols)
vec = [mat[a]*other_mat[b] for a, b in zip(row_indices, col_indices)]
try:
new_mat[i] = Add(*vec)
except (TypeError, SympifyError):
# Some matrices don't work with `sum` or `Add`
# They don't work with `sum` because `sum` tries to add `0`
# Fall back to a safe way to multiply if the `Add` fails.
new_mat[i] = reduce(lambda a, b: a + b, vec)
return classof(self, other)._new(self.rows, other.cols, new_mat, copy=False)
def _eval_matrix_mul_elementwise(self, other):
mat = [a*b for a,b in zip(self._mat, other._mat)]
return classof(self, other)._new(self.rows, self.cols, mat, copy=False)
def _eval_inverse(self, **kwargs):
return self.inv(method=kwargs.get('method', 'GE'),
iszerofunc=kwargs.get('iszerofunc', _iszero),
try_block_diag=kwargs.get('try_block_diag', False))
def _eval_scalar_mul(self, other):
mat = [other*a for a in self._mat]
return self._new(self.rows, self.cols, mat, copy=False)
def _eval_scalar_rmul(self, other):
mat = [a*other for a in self._mat]
return self._new(self.rows, self.cols, mat, copy=False)
def _eval_tolist(self):
mat = list(self._mat)
cols = self.cols
return [mat[i*cols:(i + 1)*cols] for i in range(self.rows)]
def _eval_todok(self):
cols = self.cols
return {divmod(ij, cols): e for ij, e in enumerate(self._mat) if e}
def as_immutable(self):
"""Returns an Immutable version of this Matrix
"""
from .immutable import ImmutableDenseMatrix as cls
if self.rows and self.cols:
return cls._new(self.tolist())
return cls._new(self.rows, self.cols, [])
def as_mutable(self):
"""Returns a mutable version of this matrix
Examples
========
>>> from sympy import ImmutableMatrix
>>> X = ImmutableMatrix([[1, 2], [3, 4]])
>>> Y = X.as_mutable()
>>> Y[1, 1] = 5 # Can set values in Y
>>> Y
Matrix([
[1, 2],
[3, 5]])
"""
return Matrix(self)
def equals(self, other, failing_expression=False):
"""Applies ``equals`` to corresponding elements of the matrices,
trying to prove that the elements are equivalent, returning True
if they are, False if any pair is not, and None (or the first
failing expression if failing_expression is True) if it cannot
be decided if the expressions are equivalent or not. This is, in
general, an expensive operation.
Examples
========
>>> from sympy.matrices import Matrix
>>> from sympy.abc import x
>>> A = Matrix([x*(x - 1), 0])
>>> B = Matrix([x**2 - x, 0])
>>> A == B
False
>>> A.simplify() == B.simplify()
True
>>> A.equals(B)
True
>>> A.equals(2)
False
See Also
========
sympy.core.expr.Expr.equals
"""
self_shape = getattr(self, 'shape', None)
other_shape = getattr(other, 'shape', None)
if None in (self_shape, other_shape):
return False
if self_shape != other_shape:
return False
rv = True
for i in range(self.rows):
for j in range(self.cols):
ans = self[i, j].equals(other[i, j], failing_expression)
if ans is False:
return False
elif ans is not True and rv is True:
rv = ans
return rv
def cholesky(self, hermitian=True):
return _cholesky(self, hermitian=hermitian)
def LDLdecomposition(self, hermitian=True):
return _LDLdecomposition(self, hermitian=hermitian)
def lower_triangular_solve(self, rhs):
return _lower_triangular_solve(self, rhs)
def upper_triangular_solve(self, rhs):
return _upper_triangular_solve(self, rhs)
cholesky.__doc__ = _cholesky.__doc__
LDLdecomposition.__doc__ = _LDLdecomposition.__doc__
lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__
upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__
def _force_mutable(x):
"""Return a matrix as a Matrix, otherwise return x."""
if getattr(x, 'is_Matrix', False):
return x.as_mutable()
elif isinstance(x, Basic):
return x
elif hasattr(x, '__array__'):
a = x.__array__()
if len(a.shape) == 0:
return sympify(a)
return Matrix(x)
return x
class MutableDenseMatrix(DenseMatrix, MatrixBase):
__hash__ = None # type: ignore
def __new__(cls, *args, **kwargs):
return cls._new(*args, **kwargs)
@classmethod
def _new(cls, *args, copy=True, **kwargs):
if copy is False:
# The input was rows, cols, [list].
# It should be used directly without creating a copy.
if len(args) != 3:
raise TypeError("'copy=False' requires a matrix be initialized as rows,cols,[list]")
rows, cols, flat_list = args
else:
rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs)
flat_list = list(flat_list) # create a shallow copy
types = set(map(type, flat_list))
if not all(issubclass(typ, Expr) for typ in types):
SymPyDeprecationWarning(
feature="non-Expr objects in a Matrix",
useinstead="list of lists, TableForm or some other data structure",
issue=21497,
deprecated_since_version="1.9"
).warn()
self = object.__new__(cls)
self.rows = rows
self.cols = cols
self._mat = flat_list
return self
def __setitem__(self, key, value):
"""
Examples
========
>>> from sympy import Matrix, I, zeros, ones
>>> m = Matrix(((1, 2+I), (3, 4)))
>>> m
Matrix([
[1, 2 + I],
[3, 4]])
>>> m[1, 0] = 9
>>> m
Matrix([
[1, 2 + I],
[9, 4]])
>>> m[1, 0] = [[0, 1]]
To replace row r you assign to position r*m where m
is the number of columns:
>>> M = zeros(4)
>>> m = M.cols
>>> M[3*m] = ones(1, m)*2; M
Matrix([
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[2, 2, 2, 2]])
And to replace column c you can assign to position c:
>>> M[2] = ones(m, 1)*4; M
Matrix([
[0, 0, 4, 0],
[0, 0, 4, 0],
[0, 0, 4, 0],
[2, 2, 4, 2]])
"""
rv = self._setitem(key, value)
if rv is not None:
i, j, value = rv
self._mat[i*self.cols + j] = value
def as_mutable(self):
return self.copy()
def _eval_col_del(self, col):
for j in range(self.rows-1, -1, -1):
del self._mat[col + j*self.cols]
self.cols -= 1
def _eval_row_del(self, row):
del self._mat[row*self.cols: (row+1)*self.cols]
self.rows -= 1
def col_op(self, j, f):
"""In-place operation on col j using two-arg functor whose args are
interpreted as (self[i, j], i).
Examples
========
>>> from sympy.matrices import eye
>>> M = eye(3)
>>> M.col_op(1, lambda v, i: v + 2*M[i, 0]); M
Matrix([
[1, 2, 0],
[0, 1, 0],
[0, 0, 1]])
See Also
========
col
row_op
"""
self._mat[j::self.cols] = [f(*t) for t in list(zip(self._mat[j::self.cols], list(range(self.rows))))]
def col_swap(self, i, j):
"""Swap the two given columns of the matrix in-place.
Examples
========
>>> from sympy.matrices import Matrix
>>> M = Matrix([[1, 0], [1, 0]])
>>> M
Matrix([
[1, 0],
[1, 0]])
>>> M.col_swap(0, 1)
>>> M
Matrix([
[0, 1],
[0, 1]])
See Also
========
col
row_swap
"""
for k in range(0, self.rows):
self[k, i], self[k, j] = self[k, j], self[k, i]
def copyin_list(self, key, value):
"""Copy in elements from a list.
Parameters
==========
key : slice
The section of this matrix to replace.
value : iterable
The iterable to copy values from.
Examples
========
>>> from sympy.matrices import eye
>>> I = eye(3)
>>> I[:2, 0] = [1, 2] # col
>>> I
Matrix([
[1, 0, 0],
[2, 1, 0],
[0, 0, 1]])
>>> I[1, :2] = [[3, 4]]
>>> I
Matrix([
[1, 0, 0],
[3, 4, 0],
[0, 0, 1]])
See Also
========
copyin_matrix
"""
if not is_sequence(value):
raise TypeError("`value` must be an ordered iterable, not %s." % type(value))
return self.copyin_matrix(key, Matrix(value))
def copyin_matrix(self, key, value):
"""Copy in values from a matrix into the given bounds.
Parameters
==========
key : slice
The section of this matrix to replace.
value : Matrix
The matrix to copy values from.
Examples
========
>>> from sympy.matrices import Matrix, eye
>>> M = Matrix([[0, 1], [2, 3], [4, 5]])
>>> I = eye(3)
>>> I[:3, :2] = M
>>> I
Matrix([
[0, 1, 0],
[2, 3, 0],
[4, 5, 1]])
>>> I[0, 1] = M
>>> I
Matrix([
[0, 0, 1],
[2, 2, 3],
[4, 4, 5]])
See Also
========
copyin_list
"""
rlo, rhi, clo, chi = self.key2bounds(key)
shape = value.shape
dr, dc = rhi - rlo, chi - clo
if shape != (dr, dc):
raise ShapeError(filldedent("The Matrix `value` doesn't have the "
"same dimensions "
"as the in sub-Matrix given by `key`."))
for i in range(value.rows):
for j in range(value.cols):
self[i + rlo, j + clo] = value[i, j]
def fill(self, value):
"""Fill the matrix with the scalar value.
See Also
========
zeros
ones
"""
self._mat = [value]*len(self)
def row_op(self, i, f):
"""In-place operation on row ``i`` using two-arg functor whose args are
interpreted as ``(self[i, j], j)``.
Examples
========
>>> from sympy.matrices import eye
>>> M = eye(3)
>>> M.row_op(1, lambda v, j: v + 2*M[0, j]); M
Matrix([
[1, 0, 0],
[2, 1, 0],
[0, 0, 1]])
See Also
========
row
zip_row_op
col_op
"""
i0 = i*self.cols
ri = self._mat[i0: i0 + self.cols]
self._mat[i0: i0 + self.cols] = [f(x, j) for x, j in zip(ri, list(range(self.cols)))]
def row_swap(self, i, j):
"""Swap the two given rows of the matrix in-place.
Examples
========
>>> from sympy.matrices import Matrix
>>> M = Matrix([[0, 1], [1, 0]])
>>> M
Matrix([
[0, 1],
[1, 0]])
>>> M.row_swap(0, 1)
>>> M
Matrix([
[1, 0],
[0, 1]])
See Also
========
row
col_swap
"""
for k in range(0, self.cols):
self[i, k], self[j, k] = self[j, k], self[i, k]
def simplify(self, **kwargs):
"""Applies simplify to the elements of a matrix in place.
This is a shortcut for M.applyfunc(lambda x: simplify(x, ratio, measure))
See Also
========
sympy.simplify.simplify.simplify
"""
for i in range(len(self._mat)):
self._mat[i] = _simplify(self._mat[i], **kwargs)
def zip_row_op(self, i, k, f):
"""In-place operation on row ``i`` using two-arg functor whose args are
interpreted as ``(self[i, j], self[k, j])``.
Examples
========
>>> from sympy.matrices import eye
>>> M = eye(3)
>>> M.zip_row_op(1, 0, lambda v, u: v + 2*u); M
Matrix([
[1, 0, 0],
[2, 1, 0],
[0, 0, 1]])
See Also
========
row
row_op
col_op
"""
i0 = i*self.cols
k0 = k*self.cols
ri = self._mat[i0: i0 + self.cols]
rk = self._mat[k0: k0 + self.cols]
self._mat[i0: i0 + self.cols] = [f(x, y) for x, y in zip(ri, rk)]
is_zero = False
MutableMatrix = Matrix = MutableDenseMatrix
###########
# Numpy Utility Functions:
# list2numpy, matrix2numpy, symmarray, rot_axis[123]
###########
def list2numpy(l, dtype=object): # pragma: no cover
"""Converts python list of SymPy expressions to a NumPy array.
See Also
========
matrix2numpy
"""
from numpy import empty
a = empty(len(l), dtype)
for i, s in enumerate(l):
a[i] = s
return a
def matrix2numpy(m, dtype=object): # pragma: no cover
"""Converts SymPy's matrix to a NumPy array.
See Also
========
list2numpy
"""
from numpy import empty
a = empty(m.shape, dtype)
for i in range(m.rows):
for j in range(m.cols):
a[i, j] = m[i, j]
return a
def rot_axis3(theta):
"""Returns a rotation matrix for a rotation of theta (in radians) about
the 3-axis.
Examples
========
>>> from sympy import pi
>>> from sympy.matrices import rot_axis3
A rotation of pi/3 (60 degrees):
>>> theta = pi/3
>>> rot_axis3(theta)
Matrix([
[ 1/2, sqrt(3)/2, 0],
[-sqrt(3)/2, 1/2, 0],
[ 0, 0, 1]])
If we rotate by pi/2 (90 degrees):
>>> rot_axis3(pi/2)
Matrix([
[ 0, 1, 0],
[-1, 0, 0],
[ 0, 0, 1]])
See Also
========
rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
about the 1-axis
rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
about the 2-axis
"""
ct = cos(theta)
st = sin(theta)
lil = ((ct, st, 0),
(-st, ct, 0),
(0, 0, 1))
return Matrix(lil)
def rot_axis2(theta):
"""Returns a rotation matrix for a rotation of theta (in radians) about
the 2-axis.
Examples
========
>>> from sympy import pi
>>> from sympy.matrices import rot_axis2
A rotation of pi/3 (60 degrees):
>>> theta = pi/3
>>> rot_axis2(theta)
Matrix([
[ 1/2, 0, -sqrt(3)/2],
[ 0, 1, 0],
[sqrt(3)/2, 0, 1/2]])
If we rotate by pi/2 (90 degrees):
>>> rot_axis2(pi/2)
Matrix([
[0, 0, -1],
[0, 1, 0],
[1, 0, 0]])
See Also
========
rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
about the 1-axis
rot_axis3: Returns a rotation matrix for a rotation of theta (in radians)
about the 3-axis
"""
ct = cos(theta)
st = sin(theta)
lil = ((ct, 0, -st),
(0, 1, 0),
(st, 0, ct))
return Matrix(lil)
def rot_axis1(theta):
"""Returns a rotation matrix for a rotation of theta (in radians) about
the 1-axis.
Examples
========
>>> from sympy import pi
>>> from sympy.matrices import rot_axis1
A rotation of pi/3 (60 degrees):
>>> theta = pi/3
>>> rot_axis1(theta)
Matrix([
[1, 0, 0],
[0, 1/2, sqrt(3)/2],
[0, -sqrt(3)/2, 1/2]])
If we rotate by pi/2 (90 degrees):
>>> rot_axis1(pi/2)
Matrix([
[1, 0, 0],
[0, 0, 1],
[0, -1, 0]])
See Also
========
rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
about the 2-axis
rot_axis3: Returns a rotation matrix for a rotation of theta (in radians)
about the 3-axis
"""
ct = cos(theta)
st = sin(theta)
lil = ((1, 0, 0),
(0, ct, st),
(0, -st, ct))
return Matrix(lil)
@doctest_depends_on(modules=('numpy',))
def symarray(prefix, shape, **kwargs): # pragma: no cover
r"""Create a numpy ndarray of symbols (as an object array).
The created symbols are named ``prefix_i1_i2_``... You should thus provide a
non-empty prefix if you want your symbols to be unique for different output
arrays, as SymPy symbols with identical names are the same object.
Parameters
----------
prefix : string
A prefix prepended to the name of every symbol.
shape : int or tuple
Shape of the created array. If an int, the array is one-dimensional; for
more than one dimension the shape must be a tuple.
\*\*kwargs : dict
keyword arguments passed on to Symbol
Examples
========
These doctests require numpy.
>>> from sympy import symarray
>>> symarray('', 3)
[_0 _1 _2]
If you want multiple symarrays to contain distinct symbols, you *must*
provide unique prefixes:
>>> a = symarray('', 3)
>>> b = symarray('', 3)
>>> a[0] == b[0]
True
>>> a = symarray('a', 3)
>>> b = symarray('b', 3)
>>> a[0] == b[0]
False
Creating symarrays with a prefix:
>>> symarray('a', 3)
[a_0 a_1 a_2]
For more than one dimension, the shape must be given as a tuple:
>>> symarray('a', (2, 3))
[[a_0_0 a_0_1 a_0_2]
[a_1_0 a_1_1 a_1_2]]
>>> symarray('a', (2, 3, 2))
[[[a_0_0_0 a_0_0_1]
[a_0_1_0 a_0_1_1]
[a_0_2_0 a_0_2_1]]
<BLANKLINE>
[[a_1_0_0 a_1_0_1]
[a_1_1_0 a_1_1_1]
[a_1_2_0 a_1_2_1]]]
For setting assumptions of the underlying Symbols:
>>> [s.is_real for s in symarray('a', 2, real=True)]
[True, True]
"""
from numpy import empty, ndindex
arr = empty(shape, dtype=object)
for index in ndindex(shape):
arr[index] = Symbol('%s_%s' % (prefix, '_'.join(map(str, index))),
**kwargs)
return arr
###############
# Functions
###############
def casoratian(seqs, n, zero=True):
"""Given linear difference operator L of order 'k' and homogeneous
equation Ly = 0 we want to compute kernel of L, which is a set
of 'k' sequences: a(n), b(n), ... z(n).
Solutions of L are linearly independent iff their Casoratian,
denoted as C(a, b, ..., z), do not vanish for n = 0.
Casoratian is defined by k x k determinant::
+ a(n) b(n) . . . z(n) +
| a(n+1) b(n+1) . . . z(n+1) |
| . . . . |
| . . . . |
| . . . . |
+ a(n+k-1) b(n+k-1) . . . z(n+k-1) +
It proves very useful in rsolve_hyper() where it is applied
to a generating set of a recurrence to factor out linearly
dependent solutions and return a basis:
>>> from sympy import Symbol, casoratian, factorial
>>> n = Symbol('n', integer=True)
Exponential and factorial are linearly independent:
>>> casoratian([2**n, factorial(n)], n) != 0
True
"""
seqs = list(map(sympify, seqs))
if not zero:
f = lambda i, j: seqs[j].subs(n, n + i)
else:
f = lambda i, j: seqs[j].subs(n, i)
k = len(seqs)
return Matrix(k, k, f).det()
def eye(*args, **kwargs):
"""Create square identity matrix n x n
See Also
========
diag
zeros
ones
"""
return Matrix.eye(*args, **kwargs)
def diag(*values, strict=True, unpack=False, **kwargs):
"""Returns a matrix with the provided values placed on the
diagonal. If non-square matrices are included, they will
produce a block-diagonal matrix.
Examples
========
This version of diag is a thin wrapper to Matrix.diag that differs
in that it treats all lists like matrices -- even when a single list
is given. If this is not desired, either put a `*` before the list or
set `unpack=True`.
>>> from sympy import diag
>>> diag([1, 2, 3], unpack=True) # = diag(1,2,3) or diag(*[1,2,3])
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
>>> diag([1, 2, 3]) # a column vector
Matrix([
[1],
[2],
[3]])
See Also
========
.common.MatrixCommon.eye
.common.MatrixCommon.diagonal - to extract a diagonal
.common.MatrixCommon.diag
.expressions.blockmatrix.BlockMatrix
"""
return Matrix.diag(*values, strict=strict, unpack=unpack, **kwargs)
def GramSchmidt(vlist, orthonormal=False):
"""Apply the Gram-Schmidt process to a set of vectors.
Parameters
==========
vlist : List of Matrix
Vectors to be orthogonalized for.
orthonormal : Bool, optional
If true, return an orthonormal basis.
Returns
=======
vlist : List of Matrix
Orthogonalized vectors
Notes
=====
This routine is mostly duplicate from ``Matrix.orthogonalize``,
except for some difference that this always raises error when
linearly dependent vectors are found, and the keyword ``normalize``
has been named as ``orthonormal`` in this function.
See Also
========
.matrices.MatrixSubspaces.orthogonalize
References
==========
.. [1] https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process
"""
return MutableDenseMatrix.orthogonalize(
*vlist, normalize=orthonormal, rankcheck=True
)
def hessian(f, varlist, constraints=[]):
"""Compute Hessian matrix for a function f wrt parameters in varlist
which may be given as a sequence or a row/column vector. A list of
constraints may optionally be given.
Examples
========
>>> from sympy import Function, hessian, pprint
>>> from sympy.abc import x, y
>>> f = Function('f')(x, y)
>>> g1 = Function('g')(x, y)
>>> g2 = x**2 + 3*y
>>> pprint(hessian(f, (x, y), [g1, g2]))
[ d d ]
[ 0 0 --(g(x, y)) --(g(x, y)) ]
[ dx dy ]
[ ]
[ 0 0 2*x 3 ]
[ ]
[ 2 2 ]
[d d d ]
[--(g(x, y)) 2*x ---(f(x, y)) -----(f(x, y))]
[dx 2 dy dx ]
[ dx ]
[ ]
[ 2 2 ]
[d d d ]
[--(g(x, y)) 3 -----(f(x, y)) ---(f(x, y)) ]
[dy dy dx 2 ]
[ dy ]
References
==========
https://en.wikipedia.org/wiki/Hessian_matrix
See Also
========
sympy.matrices.matrices.MatrixCalculus.jacobian
wronskian
"""
# f is the expression representing a function f, return regular matrix
if isinstance(varlist, MatrixBase):
if 1 not in varlist.shape:
raise ShapeError("`varlist` must be a column or row vector.")
if varlist.cols == 1:
varlist = varlist.T
varlist = varlist.tolist()[0]
if is_sequence(varlist):
n = len(varlist)
if not n:
raise ShapeError("`len(varlist)` must not be zero.")
else:
raise ValueError("Improper variable list in hessian function")
if not getattr(f, 'diff'):
# check differentiability
raise ValueError("Function `f` (%s) is not differentiable" % f)
m = len(constraints)
N = m + n
out = zeros(N)
for k, g in enumerate(constraints):
if not getattr(g, 'diff'):
# check differentiability
raise ValueError("Function `f` (%s) is not differentiable" % f)
for i in range(n):
out[k, i + m] = g.diff(varlist[i])
for i in range(n):
for j in range(i, n):
out[i + m, j + m] = f.diff(varlist[i]).diff(varlist[j])
for i in range(N):
for j in range(i + 1, N):
out[j, i] = out[i, j]
return out
def jordan_cell(eigenval, n):
"""
Create a Jordan block:
Examples
========
>>> from sympy.matrices import jordan_cell
>>> from sympy.abc import x
>>> jordan_cell(x, 4)
Matrix([
[x, 1, 0, 0],
[0, x, 1, 0],
[0, 0, x, 1],
[0, 0, 0, x]])
"""
return Matrix.jordan_block(size=n, eigenvalue=eigenval)
def matrix_multiply_elementwise(A, B):
"""Return the Hadamard product (elementwise product) of A and B
>>> from sympy.matrices import matrix_multiply_elementwise
>>> from sympy.matrices import Matrix
>>> A = Matrix([[0, 1, 2], [3, 4, 5]])
>>> B = Matrix([[1, 10, 100], [100, 10, 1]])
>>> matrix_multiply_elementwise(A, B)
Matrix([
[ 0, 10, 200],
[300, 40, 5]])
See Also
========
sympy.matrices.common.MatrixCommon.__mul__
"""
return A.multiply_elementwise(B)
def ones(*args, **kwargs):
"""Returns a matrix of ones with ``rows`` rows and ``cols`` columns;
if ``cols`` is omitted a square matrix will be returned.
See Also
========
zeros
eye
diag
"""
if 'c' in kwargs:
kwargs['cols'] = kwargs.pop('c')
return Matrix.ones(*args, **kwargs)
def randMatrix(r, c=None, min=0, max=99, seed=None, symmetric=False,
percent=100, prng=None):
"""Create random matrix with dimensions ``r`` x ``c``. If ``c`` is omitted
the matrix will be square. If ``symmetric`` is True the matrix must be
square. If ``percent`` is less than 100 then only approximately the given
percentage of elements will be non-zero.
The pseudo-random number generator used to generate matrix is chosen in the
following way.
* If ``prng`` is supplied, it will be used as random number generator.
It should be an instance of ``random.Random``, or at least have
``randint`` and ``shuffle`` methods with same signatures.
* if ``prng`` is not supplied but ``seed`` is supplied, then new
``random.Random`` with given ``seed`` will be created;
* otherwise, a new ``random.Random`` with default seed will be used.
Examples
========
>>> from sympy.matrices import randMatrix
>>> randMatrix(3) # doctest:+SKIP
[25, 45, 27]
[44, 54, 9]
[23, 96, 46]
>>> randMatrix(3, 2) # doctest:+SKIP
[87, 29]
[23, 37]
[90, 26]
>>> randMatrix(3, 3, 0, 2) # doctest:+SKIP
[0, 2, 0]
[2, 0, 1]
[0, 0, 1]
>>> randMatrix(3, symmetric=True) # doctest:+SKIP
[85, 26, 29]
[26, 71, 43]
[29, 43, 57]
>>> A = randMatrix(3, seed=1)
>>> B = randMatrix(3, seed=2)
>>> A == B
False
>>> A == randMatrix(3, seed=1)
True
>>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP
[77, 70, 0],
[70, 0, 0],
[ 0, 0, 88]
"""
# Note that ``Random()`` is equivalent to ``Random(None)``
prng = prng or random.Random(seed)
if c is None:
c = r
if symmetric and r != c:
raise ValueError('For symmetric matrices, r must equal c, but %i != %i' % (r, c))
ij = range(r * c)
if percent != 100:
ij = prng.sample(ij, int(len(ij)*percent // 100))
m = zeros(r, c)
if not symmetric:
for ijk in ij:
i, j = divmod(ijk, c)
m[i, j] = prng.randint(min, max)
else:
for ijk in ij:
i, j = divmod(ijk, c)
if i <= j:
m[i, j] = m[j, i] = prng.randint(min, max)
return m
def wronskian(functions, var, method='bareiss'):
"""
Compute Wronskian for [] of functions
::
| f1 f2 ... fn |
| f1' f2' ... fn' |
| . . . . |
W(f1, ..., fn) = | . . . . |
| . . . . |
| (n) (n) (n) |
| D (f1) D (f2) ... D (fn) |
see: https://en.wikipedia.org/wiki/Wronskian
See Also
========
sympy.matrices.matrices.MatrixCalculus.jacobian
hessian
"""
for index in range(0, len(functions)):
functions[index] = sympify(functions[index])
n = len(functions)
if n == 0:
return 1
W = Matrix(n, n, lambda i, j: functions[i].diff(var, j))
return W.det(method)
def zeros(*args, **kwargs):
"""Returns a matrix of zeros with ``rows`` rows and ``cols`` columns;
if ``cols`` is omitted a square matrix will be returned.
See Also
========
ones
eye
diag
"""
if 'c' in kwargs:
kwargs['cols'] = kwargs.pop('c')
return Matrix.zeros(*args, **kwargs)
|
17922017e6fe2e79a6c61bb37d948c85f2a7174f291bd6bfa96dbfe9dd0bbd23 | import mpmath as mp
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.compatibility import (
Callable, NotIterable, as_int, is_sequence)
from sympy.core.decorators import deprecated
from sympy.core.expr import Expr
from sympy.core.kind import _NumberKind, NumberKind, UndefinedKind
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, uniquely_named_symbol
from sympy.core.sympify import sympify
from sympy.core.sympify import _sympify
from sympy.functions import exp, factorial, log
from sympy.functions.elementary.miscellaneous import Max, Min, sqrt
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.polys import cancel
from sympy.printing import sstr
from sympy.printing.defaults import Printable
from sympy.simplify import simplify as _simplify
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.iterables import flatten
from sympy.utilities.misc import filldedent
from .common import (
MatrixCommon, MatrixError, NonSquareMatrixError, NonInvertibleMatrixError,
ShapeError, MatrixKind)
from .utilities import _iszero, _is_zero_after_expand_mul
from .determinant import (
_find_reasonable_pivot, _find_reasonable_pivot_naive,
_adjugate, _charpoly, _cofactor, _cofactor_matrix, _per,
_det, _det_bareiss, _det_berkowitz, _det_LU, _minor, _minor_submatrix)
from .reductions import _is_echelon, _echelon_form, _rank, _rref
from .subspaces import _columnspace, _nullspace, _rowspace, _orthogonalize
from .eigen import (
_eigenvals, _eigenvects,
_bidiagonalize, _bidiagonal_decomposition,
_is_diagonalizable, _diagonalize,
_is_positive_definite, _is_positive_semidefinite,
_is_negative_definite, _is_negative_semidefinite, _is_indefinite,
_jordan_form, _left_eigenvects, _singular_values)
from .decompositions import (
_rank_decomposition, _cholesky, _LDLdecomposition,
_LUdecomposition, _LUdecomposition_Simple, _LUdecompositionFF,
_singular_value_decomposition, _QRdecomposition, _upper_hessenberg_decomposition)
from .graph import (
_connected_components, _connected_components_decomposition,
_strongly_connected_components, _strongly_connected_components_decomposition)
from .solvers import (
_diagonal_solve, _lower_triangular_solve, _upper_triangular_solve,
_cholesky_solve, _LDLsolve, _LUsolve, _QRsolve, _gauss_jordan_solve,
_pinv_solve, _solve, _solve_least_squares)
from .inverse import (
_pinv, _inv_mod, _inv_ADJ, _inv_GE, _inv_LU, _inv_CH, _inv_LDL, _inv_QR,
_inv, _inv_block)
class DeferredVector(Symbol, NotIterable):
"""A vector whose components are deferred (e.g. for use with lambdify)
Examples
========
>>> from sympy import DeferredVector, lambdify
>>> X = DeferredVector( 'X' )
>>> X
X
>>> expr = (X[0] + 2, X[2] + 3)
>>> func = lambdify( X, expr)
>>> func( [1, 2, 3] )
(3, 6)
"""
def __getitem__(self, i):
if i == -0:
i = 0
if i < 0:
raise IndexError('DeferredVector index out of range')
component_name = '%s[%d]' % (self.name, i)
return Symbol(component_name)
def __str__(self):
return sstr(self)
def __repr__(self):
return "DeferredVector('%s')" % self.name
class MatrixDeterminant(MatrixCommon):
"""Provides basic matrix determinant operations. Should not be instantiated
directly. See ``determinant.py`` for their implementations."""
def _eval_det_bareiss(self, iszerofunc=_is_zero_after_expand_mul):
return _det_bareiss(self, iszerofunc=iszerofunc)
def _eval_det_berkowitz(self):
return _det_berkowitz(self)
def _eval_det_lu(self, iszerofunc=_iszero, simpfunc=None):
return _det_LU(self, iszerofunc=iszerofunc, simpfunc=simpfunc)
def _eval_determinant(self): # for expressions.determinant.Determinant
return _det(self)
def adjugate(self, method="berkowitz"):
return _adjugate(self, method=method)
def charpoly(self, x='lambda', simplify=_simplify):
return _charpoly(self, x=x, simplify=simplify)
def cofactor(self, i, j, method="berkowitz"):
return _cofactor(self, i, j, method=method)
def cofactor_matrix(self, method="berkowitz"):
return _cofactor_matrix(self, method=method)
def det(self, method="bareiss", iszerofunc=None):
return _det(self, method=method, iszerofunc=iszerofunc)
def per(self):
return _per(self)
def minor(self, i, j, method="berkowitz"):
return _minor(self, i, j, method=method)
def minor_submatrix(self, i, j):
return _minor_submatrix(self, i, j)
_find_reasonable_pivot.__doc__ = _find_reasonable_pivot.__doc__
_find_reasonable_pivot_naive.__doc__ = _find_reasonable_pivot_naive.__doc__
_eval_det_bareiss.__doc__ = _det_bareiss.__doc__
_eval_det_berkowitz.__doc__ = _det_berkowitz.__doc__
_eval_det_lu.__doc__ = _det_LU.__doc__
_eval_determinant.__doc__ = _det.__doc__
adjugate.__doc__ = _adjugate.__doc__
charpoly.__doc__ = _charpoly.__doc__
cofactor.__doc__ = _cofactor.__doc__
cofactor_matrix.__doc__ = _cofactor_matrix.__doc__
det.__doc__ = _det.__doc__
per.__doc__ = _per.__doc__
minor.__doc__ = _minor.__doc__
minor_submatrix.__doc__ = _minor_submatrix.__doc__
class MatrixReductions(MatrixDeterminant):
"""Provides basic matrix row/column operations. Should not be instantiated
directly. See ``reductions.py`` for some of their implementations."""
def echelon_form(self, iszerofunc=_iszero, simplify=False, with_pivots=False):
return _echelon_form(self, iszerofunc=iszerofunc, simplify=simplify,
with_pivots=with_pivots)
@property
def is_echelon(self):
return _is_echelon(self)
def rank(self, iszerofunc=_iszero, simplify=False):
return _rank(self, iszerofunc=iszerofunc, simplify=simplify)
def rref(self, iszerofunc=_iszero, simplify=False, pivots=True,
normalize_last=True):
return _rref(self, iszerofunc=iszerofunc, simplify=simplify,
pivots=pivots, normalize_last=normalize_last)
echelon_form.__doc__ = _echelon_form.__doc__
is_echelon.__doc__ = _is_echelon.__doc__
rank.__doc__ = _rank.__doc__
rref.__doc__ = _rref.__doc__
def _normalize_op_args(self, op, col, k, col1, col2, error_str="col"):
"""Validate the arguments for a row/column operation. ``error_str``
can be one of "row" or "col" depending on the arguments being parsed."""
if op not in ["n->kn", "n<->m", "n->n+km"]:
raise ValueError("Unknown {} operation '{}'. Valid col operations "
"are 'n->kn', 'n<->m', 'n->n+km'".format(error_str, op))
# define self_col according to error_str
self_cols = self.cols if error_str == 'col' else self.rows
# normalize and validate the arguments
if op == "n->kn":
col = col if col is not None else col1
if col is None or k is None:
raise ValueError("For a {0} operation 'n->kn' you must provide the "
"kwargs `{0}` and `k`".format(error_str))
if not 0 <= col < self_cols:
raise ValueError("This matrix doesn't have a {} '{}'".format(error_str, col))
elif op == "n<->m":
# we need two cols to swap. It doesn't matter
# how they were specified, so gather them together and
# remove `None`
cols = {col, k, col1, col2}.difference([None])
if len(cols) > 2:
# maybe the user left `k` by mistake?
cols = {col, col1, col2}.difference([None])
if len(cols) != 2:
raise ValueError("For a {0} operation 'n<->m' you must provide the "
"kwargs `{0}1` and `{0}2`".format(error_str))
col1, col2 = cols
if not 0 <= col1 < self_cols:
raise ValueError("This matrix doesn't have a {} '{}'".format(error_str, col1))
if not 0 <= col2 < self_cols:
raise ValueError("This matrix doesn't have a {} '{}'".format(error_str, col2))
elif op == "n->n+km":
col = col1 if col is None else col
col2 = col1 if col2 is None else col2
if col is None or col2 is None or k is None:
raise ValueError("For a {0} operation 'n->n+km' you must provide the "
"kwargs `{0}`, `k`, and `{0}2`".format(error_str))
if col == col2:
raise ValueError("For a {0} operation 'n->n+km' `{0}` and `{0}2` must "
"be different.".format(error_str))
if not 0 <= col < self_cols:
raise ValueError("This matrix doesn't have a {} '{}'".format(error_str, col))
if not 0 <= col2 < self_cols:
raise ValueError("This matrix doesn't have a {} '{}'".format(error_str, col2))
else:
raise ValueError('invalid operation %s' % repr(op))
return op, col, k, col1, col2
def _eval_col_op_multiply_col_by_const(self, col, k):
def entry(i, j):
if j == col:
return k * self[i, j]
return self[i, j]
return self._new(self.rows, self.cols, entry)
def _eval_col_op_swap(self, col1, col2):
def entry(i, j):
if j == col1:
return self[i, col2]
elif j == col2:
return self[i, col1]
return self[i, j]
return self._new(self.rows, self.cols, entry)
def _eval_col_op_add_multiple_to_other_col(self, col, k, col2):
def entry(i, j):
if j == col:
return self[i, j] + k * self[i, col2]
return self[i, j]
return self._new(self.rows, self.cols, entry)
def _eval_row_op_swap(self, row1, row2):
def entry(i, j):
if i == row1:
return self[row2, j]
elif i == row2:
return self[row1, j]
return self[i, j]
return self._new(self.rows, self.cols, entry)
def _eval_row_op_multiply_row_by_const(self, row, k):
def entry(i, j):
if i == row:
return k * self[i, j]
return self[i, j]
return self._new(self.rows, self.cols, entry)
def _eval_row_op_add_multiple_to_other_row(self, row, k, row2):
def entry(i, j):
if i == row:
return self[i, j] + k * self[row2, j]
return self[i, j]
return self._new(self.rows, self.cols, entry)
def elementary_col_op(self, op="n->kn", col=None, k=None, col1=None, col2=None):
"""Performs the elementary column operation `op`.
`op` may be one of
* "n->kn" (column n goes to k*n)
* "n<->m" (swap column n and column m)
* "n->n+km" (column n goes to column n + k*column m)
Parameters
==========
op : string; the elementary row operation
col : the column to apply the column operation
k : the multiple to apply in the column operation
col1 : one column of a column swap
col2 : second column of a column swap or column "m" in the column operation
"n->n+km"
"""
op, col, k, col1, col2 = self._normalize_op_args(op, col, k, col1, col2, "col")
# now that we've validated, we're all good to dispatch
if op == "n->kn":
return self._eval_col_op_multiply_col_by_const(col, k)
if op == "n<->m":
return self._eval_col_op_swap(col1, col2)
if op == "n->n+km":
return self._eval_col_op_add_multiple_to_other_col(col, k, col2)
def elementary_row_op(self, op="n->kn", row=None, k=None, row1=None, row2=None):
"""Performs the elementary row operation `op`.
`op` may be one of
* "n->kn" (row n goes to k*n)
* "n<->m" (swap row n and row m)
* "n->n+km" (row n goes to row n + k*row m)
Parameters
==========
op : string; the elementary row operation
row : the row to apply the row operation
k : the multiple to apply in the row operation
row1 : one row of a row swap
row2 : second row of a row swap or row "m" in the row operation
"n->n+km"
"""
op, row, k, row1, row2 = self._normalize_op_args(op, row, k, row1, row2, "row")
# now that we've validated, we're all good to dispatch
if op == "n->kn":
return self._eval_row_op_multiply_row_by_const(row, k)
if op == "n<->m":
return self._eval_row_op_swap(row1, row2)
if op == "n->n+km":
return self._eval_row_op_add_multiple_to_other_row(row, k, row2)
class MatrixSubspaces(MatrixReductions):
"""Provides methods relating to the fundamental subspaces of a matrix.
Should not be instantiated directly. See ``subspaces.py`` for their
implementations."""
def columnspace(self, simplify=False):
return _columnspace(self, simplify=simplify)
def nullspace(self, simplify=False, iszerofunc=_iszero):
return _nullspace(self, simplify=simplify, iszerofunc=iszerofunc)
def rowspace(self, simplify=False):
return _rowspace(self, simplify=simplify)
# This is a classmethod but is converted to such later in order to allow
# assignment of __doc__ since that does not work for already wrapped
# classmethods in Python 3.6.
def orthogonalize(cls, *vecs, **kwargs):
return _orthogonalize(cls, *vecs, **kwargs)
columnspace.__doc__ = _columnspace.__doc__
nullspace.__doc__ = _nullspace.__doc__
rowspace.__doc__ = _rowspace.__doc__
orthogonalize.__doc__ = _orthogonalize.__doc__
orthogonalize = classmethod(orthogonalize) # type:ignore
class MatrixEigen(MatrixSubspaces):
"""Provides basic matrix eigenvalue/vector operations.
Should not be instantiated directly. See ``eigen.py`` for their
implementations."""
def eigenvals(self, error_when_incomplete=True, **flags):
return _eigenvals(self, error_when_incomplete=error_when_incomplete, **flags)
def eigenvects(self, error_when_incomplete=True, iszerofunc=_iszero, **flags):
return _eigenvects(self, error_when_incomplete=error_when_incomplete,
iszerofunc=iszerofunc, **flags)
def is_diagonalizable(self, reals_only=False, **kwargs):
return _is_diagonalizable(self, reals_only=reals_only, **kwargs)
def diagonalize(self, reals_only=False, sort=False, normalize=False):
return _diagonalize(self, reals_only=reals_only, sort=sort,
normalize=normalize)
def bidiagonalize(self, upper=True):
return _bidiagonalize(self, upper=upper)
def bidiagonal_decomposition(self, upper=True):
return _bidiagonal_decomposition(self, upper=upper)
@property
def is_positive_definite(self):
return _is_positive_definite(self)
@property
def is_positive_semidefinite(self):
return _is_positive_semidefinite(self)
@property
def is_negative_definite(self):
return _is_negative_definite(self)
@property
def is_negative_semidefinite(self):
return _is_negative_semidefinite(self)
@property
def is_indefinite(self):
return _is_indefinite(self)
def jordan_form(self, calc_transform=True, **kwargs):
return _jordan_form(self, calc_transform=calc_transform, **kwargs)
def left_eigenvects(self, **flags):
return _left_eigenvects(self, **flags)
def singular_values(self):
return _singular_values(self)
eigenvals.__doc__ = _eigenvals.__doc__
eigenvects.__doc__ = _eigenvects.__doc__
is_diagonalizable.__doc__ = _is_diagonalizable.__doc__
diagonalize.__doc__ = _diagonalize.__doc__
is_positive_definite.__doc__ = _is_positive_definite.__doc__
is_positive_semidefinite.__doc__ = _is_positive_semidefinite.__doc__
is_negative_definite.__doc__ = _is_negative_definite.__doc__
is_negative_semidefinite.__doc__ = _is_negative_semidefinite.__doc__
is_indefinite.__doc__ = _is_indefinite.__doc__
jordan_form.__doc__ = _jordan_form.__doc__
left_eigenvects.__doc__ = _left_eigenvects.__doc__
singular_values.__doc__ = _singular_values.__doc__
bidiagonalize.__doc__ = _bidiagonalize.__doc__
bidiagonal_decomposition.__doc__ = _bidiagonal_decomposition.__doc__
class MatrixCalculus(MatrixCommon):
"""Provides calculus-related matrix operations."""
def diff(self, *args, **kwargs):
"""Calculate the derivative of each element in the matrix.
``args`` will be passed to the ``integrate`` function.
Examples
========
>>> from sympy.matrices import Matrix
>>> from sympy.abc import x, y
>>> M = Matrix([[x, y], [1, 0]])
>>> M.diff(x)
Matrix([
[1, 0],
[0, 0]])
See Also
========
integrate
limit
"""
# XXX this should be handled here rather than in Derivative
from sympy.tensor.array.array_derivatives import ArrayDerivative
kwargs.setdefault('evaluate', True)
deriv = ArrayDerivative(self, *args, evaluate=True)
if not isinstance(self, Basic):
return deriv.as_mutable()
else:
return deriv
def _eval_derivative(self, arg):
return self.applyfunc(lambda x: x.diff(arg))
def integrate(self, *args, **kwargs):
"""Integrate each element of the matrix. ``args`` will
be passed to the ``integrate`` function.
Examples
========
>>> from sympy.matrices import Matrix
>>> from sympy.abc import x, y
>>> M = Matrix([[x, y], [1, 0]])
>>> M.integrate((x, ))
Matrix([
[x**2/2, x*y],
[ x, 0]])
>>> M.integrate((x, 0, 2))
Matrix([
[2, 2*y],
[2, 0]])
See Also
========
limit
diff
"""
return self.applyfunc(lambda x: x.integrate(*args, **kwargs))
def jacobian(self, X):
"""Calculates the Jacobian matrix (derivative of a vector-valued function).
Parameters
==========
``self`` : vector of expressions representing functions f_i(x_1, ..., x_n).
X : set of x_i's in order, it can be a list or a Matrix
Both ``self`` and X can be a row or a column matrix in any order
(i.e., jacobian() should always work).
Examples
========
>>> from sympy import sin, cos, Matrix
>>> from sympy.abc import rho, phi
>>> X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
>>> Y = Matrix([rho, phi])
>>> X.jacobian(Y)
Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi), rho*cos(phi)],
[ 2*rho, 0]])
>>> X = Matrix([rho*cos(phi), rho*sin(phi)])
>>> X.jacobian(Y)
Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi), rho*cos(phi)]])
See Also
========
hessian
wronskian
"""
if not isinstance(X, MatrixBase):
X = self._new(X)
# Both X and ``self`` can be a row or a column matrix, so we need to make
# sure all valid combinations work, but everything else fails:
if self.shape[0] == 1:
m = self.shape[1]
elif self.shape[1] == 1:
m = self.shape[0]
else:
raise TypeError("``self`` must be a row or a column matrix")
if X.shape[0] == 1:
n = X.shape[1]
elif X.shape[1] == 1:
n = X.shape[0]
else:
raise TypeError("X must be a row or a column matrix")
# m is the number of functions and n is the number of variables
# computing the Jacobian is now easy:
return self._new(m, n, lambda j, i: self[j].diff(X[i]))
def limit(self, *args):
"""Calculate the limit of each element in the matrix.
``args`` will be passed to the ``limit`` function.
Examples
========
>>> from sympy.matrices import Matrix
>>> from sympy.abc import x, y
>>> M = Matrix([[x, y], [1, 0]])
>>> M.limit(x, 2)
Matrix([
[2, y],
[1, 0]])
See Also
========
integrate
diff
"""
return self.applyfunc(lambda x: x.limit(*args))
# https://github.com/sympy/sympy/pull/12854
class MatrixDeprecated(MatrixCommon):
"""A class to house deprecated matrix methods."""
def _legacy_array_dot(self, b):
"""Compatibility function for deprecated behavior of ``matrix.dot(vector)``
"""
from .dense import Matrix
if not isinstance(b, MatrixBase):
if is_sequence(b):
if len(b) != self.cols and len(b) != self.rows:
raise ShapeError(
"Dimensions incorrect for dot product: %s, %s" % (
self.shape, len(b)))
return self.dot(Matrix(b))
else:
raise TypeError(
"`b` must be an ordered iterable or Matrix, not %s." %
type(b))
mat = self
if mat.cols == b.rows:
if b.cols != 1:
mat = mat.T
b = b.T
prod = flatten((mat * b).tolist())
return prod
if mat.cols == b.cols:
return mat.dot(b.T)
elif mat.rows == b.rows:
return mat.T.dot(b)
else:
raise ShapeError("Dimensions incorrect for dot product: %s, %s" % (
self.shape, b.shape))
def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_simplify):
return self.charpoly(x=x)
def berkowitz_det(self):
"""Computes determinant using Berkowitz method.
See Also
========
det
berkowitz
"""
return self.det(method='berkowitz')
def berkowitz_eigenvals(self, **flags):
"""Computes eigenvalues of a Matrix using Berkowitz method.
See Also
========
berkowitz
"""
return self.eigenvals(**flags)
def berkowitz_minors(self):
"""Computes principal minors using Berkowitz method.
See Also
========
berkowitz
"""
sign, minors = self.one, []
for poly in self.berkowitz():
minors.append(sign * poly[-1])
sign = -sign
return tuple(minors)
def berkowitz(self):
from sympy.matrices import zeros
berk = ((1,),)
if not self:
return berk
if not self.is_square:
raise NonSquareMatrixError()
A, N = self, self.rows
transforms = [0] * (N - 1)
for n in range(N, 1, -1):
T, k = zeros(n + 1, n), n - 1
R, C = -A[k, :k], A[:k, k]
A, a = A[:k, :k], -A[k, k]
items = [C]
for i in range(0, n - 2):
items.append(A * items[i])
for i, B in enumerate(items):
items[i] = (R * B)[0, 0]
items = [self.one, a] + items
for i in range(n):
T[i:, i] = items[:n - i + 1]
transforms[k - 1] = T
polys = [self._new([self.one, -A[0, 0]])]
for i, T in enumerate(transforms):
polys.append(T * polys[i])
return berk + tuple(map(tuple, polys))
def cofactorMatrix(self, method="berkowitz"):
return self.cofactor_matrix(method=method)
def det_bareis(self):
return _det_bareiss(self)
def det_LU_decomposition(self):
"""Compute matrix determinant using LU decomposition
Note that this method fails if the LU decomposition itself
fails. In particular, if the matrix has no inverse this method
will fail.
TODO: Implement algorithm for sparse matrices (SFF),
http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.
See Also
========
det
det_bareiss
berkowitz_det
"""
return self.det(method='lu')
def jordan_cell(self, eigenval, n):
return self.jordan_block(size=n, eigenvalue=eigenval)
def jordan_cells(self, calc_transformation=True):
P, J = self.jordan_form()
return P, J.get_diag_blocks()
def minorEntry(self, i, j, method="berkowitz"):
return self.minor(i, j, method=method)
def minorMatrix(self, i, j):
return self.minor_submatrix(i, j)
def permuteBkwd(self, perm):
"""Permute the rows of the matrix with the given permutation in reverse."""
return self.permute_rows(perm, direction='backward')
def permuteFwd(self, perm):
"""Permute the rows of the matrix with the given permutation."""
return self.permute_rows(perm, direction='forward')
@Mul._kind_dispatcher.register(_NumberKind, MatrixKind)
def num_mat_mul(k1, k2):
"""
Return MatrixKind. The element kind is selected by recursive dispatching.
Do not need to dispatch in reversed order because KindDispatcher
searches for this automatically.
"""
# Deal with Mul._kind_dispatcher's commutativity
elemk = Mul._kind_dispatcher(NumberKind, k2.element_kind)
return MatrixKind(elemk)
@Mul._kind_dispatcher.register(MatrixKind, MatrixKind)
def mat_mat_mul(k1, k2):
"""
Return MatrixKind. The element kind is selected by recursive dispatching.
"""
elemk = Mul._kind_dispatcher(k1.element_kind, k2.element_kind)
return MatrixKind(elemk)
class MatrixBase(MatrixDeprecated,
MatrixCalculus,
MatrixEigen,
MatrixCommon,
Printable):
"""Base class for matrix objects."""
# Added just for numpy compatibility
__array_priority__ = 11
is_Matrix = True
_class_priority = 3
_sympify = staticmethod(sympify)
zero = S.Zero
one = S.One
@property
def kind(self):
elem_kinds = set(e.kind for e in self._mat)
if len(elem_kinds) == 1:
elemkind, = elem_kinds
else:
elemkind = UndefinedKind
return MatrixKind(elemkind)
def __array__(self, dtype=object):
from .dense import matrix2numpy
return matrix2numpy(self, dtype=dtype)
def __len__(self):
"""Return the number of elements of ``self``.
Implemented mainly so bool(Matrix()) == False.
"""
return self.rows * self.cols
def _matrix_pow_by_jordan_blocks(self, num):
from sympy.matrices import diag, MutableMatrix
from sympy import binomial
def jordan_cell_power(jc, n):
N = jc.shape[0]
l = jc[0,0]
if l.is_zero:
if N == 1 and n.is_nonnegative:
jc[0,0] = l**n
elif not (n.is_integer and n.is_nonnegative):
raise NonInvertibleMatrixError("Non-invertible matrix can only be raised to a nonnegative integer")
else:
for i in range(N):
jc[0,i] = KroneckerDelta(i, n)
else:
for i in range(N):
bn = binomial(n, i)
if isinstance(bn, binomial):
bn = bn._eval_expand_func()
jc[0,i] = l**(n-i)*bn
for i in range(N):
for j in range(1, N-i):
jc[j,i+j] = jc [j-1,i+j-1]
P, J = self.jordan_form()
jordan_cells = J.get_diag_blocks()
# Make sure jordan_cells matrices are mutable:
jordan_cells = [MutableMatrix(j) for j in jordan_cells]
for j in jordan_cells:
jordan_cell_power(j, num)
return self._new(P.multiply(diag(*jordan_cells))
.multiply(P.inv()))
def __str__(self):
if self.rows == 0 or self.cols == 0:
return 'Matrix(%s, %s, [])' % (self.rows, self.cols)
return "Matrix(%s)" % str(self.tolist())
def _format_str(self, printer=None):
if not printer:
from sympy.printing.str import StrPrinter
printer = StrPrinter()
# Handle zero dimensions:
if self.rows == 0 or self.cols == 0:
return 'Matrix(%s, %s, [])' % (self.rows, self.cols)
if self.rows == 1:
return "Matrix([%s])" % self.table(printer, rowsep=',\n')
return "Matrix([\n%s])" % self.table(printer, rowsep=',\n')
@classmethod
def irregular(cls, ntop, *matrices, **kwargs):
"""Return a matrix filled by the given matrices which
are listed in order of appearance from left to right, top to
bottom as they first appear in the matrix. They must fill the
matrix completely.
Examples
========
>>> from sympy import ones, Matrix
>>> 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]])
"""
from sympy.core.compatibility import as_int
ntop = as_int(ntop)
# make sure we are working with explicit matrices
b = [i.as_explicit() if hasattr(i, 'as_explicit') else i
for i in matrices]
q = list(range(len(b)))
dat = [i.rows for i in b]
active = [q.pop(0) for _ in range(ntop)]
cols = sum([b[i].cols for i in active])
rows = []
while any(dat):
r = []
for a, j in enumerate(active):
r.extend(b[j][-dat[j], :])
dat[j] -= 1
if dat[j] == 0 and q:
active[a] = q.pop(0)
if len(r) != cols:
raise ValueError(filldedent('''
Matrices provided do not appear to fill
the space completely.'''))
rows.append(r)
return cls._new(rows)
@classmethod
def _handle_ndarray(cls, arg):
# NumPy array or matrix or some other object that implements
# __array__. So let's first use this method to get a
# numpy.array() and then make a python list out of it.
arr = arg.__array__()
if len(arr.shape) == 2:
rows, cols = arr.shape[0], arr.shape[1]
flat_list = [cls._sympify(i) for i in arr.ravel()]
return rows, cols, flat_list
elif len(arr.shape) == 1:
flat_list = [cls._sympify(i) for i in arr]
return arr.shape[0], 1, flat_list
else:
raise NotImplementedError(
"SymPy supports just 1D and 2D matrices")
@classmethod
def _handle_creation_inputs(cls, *args, **kwargs):
"""Return the number of rows, cols and flat matrix elements.
Examples
========
>>> from sympy import Matrix, I
Matrix can be constructed as follows:
* from a nested list of iterables
>>> Matrix( ((1, 2+I), (3, 4)) )
Matrix([
[1, 2 + I],
[3, 4]])
* from un-nested iterable (interpreted as a column)
>>> Matrix( [1, 2] )
Matrix([
[1],
[2]])
* from un-nested iterable with dimensions
>>> Matrix(1, 2, [1, 2] )
Matrix([[1, 2]])
* from no arguments (a 0 x 0 matrix)
>>> Matrix()
Matrix(0, 0, [])
* from a rule
>>> Matrix(2, 2, lambda i, j: i/(j + 1) )
Matrix([
[0, 0],
[1, 1/2]])
See Also
========
irregular - filling a matrix with irregular blocks
"""
from sympy.matrices.sparse import SparseMatrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.utilities.iterables import reshape
flat_list = None
if len(args) == 1:
# Matrix(SparseMatrix(...))
if isinstance(args[0], SparseMatrix):
return args[0].rows, args[0].cols, flatten(args[0].tolist())
# Matrix(Matrix(...))
elif isinstance(args[0], MatrixBase):
return args[0].rows, args[0].cols, args[0]._mat
# Matrix(MatrixSymbol('X', 2, 2))
elif isinstance(args[0], Basic) and args[0].is_Matrix:
return args[0].rows, args[0].cols, args[0].as_explicit()._mat
elif isinstance(args[0], mp.matrix):
M = args[0]
flat_list = [cls._sympify(x) for x in M]
return M.rows, M.cols, flat_list
# Matrix(numpy.ones((2, 2)))
elif hasattr(args[0], "__array__"):
return cls._handle_ndarray(args[0])
# Matrix([1, 2, 3]) or Matrix([[1, 2], [3, 4]])
elif is_sequence(args[0]) \
and not isinstance(args[0], DeferredVector):
dat = list(args[0])
ismat = lambda i: isinstance(i, MatrixBase) and (
evaluate or
isinstance(i, BlockMatrix) or
isinstance(i, MatrixSymbol))
raw = lambda i: is_sequence(i) and not ismat(i)
evaluate = kwargs.get('evaluate', True)
if evaluate:
def do(x):
# make Block and Symbol explicit
if isinstance(x, (list, tuple)):
return type(x)([do(i) for i in x])
if isinstance(x, BlockMatrix) or \
isinstance(x, MatrixSymbol) and \
all(_.is_Integer for _ in x.shape):
return x.as_explicit()
return cls._sympify(x)
dat = do(dat)
if dat == [] or dat == [[]]:
rows = cols = 0
flat_list = []
elif not any(raw(i) or ismat(i) for i in dat):
# a column as a list of values
flat_list = [cls._sympify(i) for i in dat]
rows = len(flat_list)
cols = 1 if rows else 0
elif evaluate and all(ismat(i) for i in dat):
# a column as a list of matrices
ncol = {i.cols for i in dat if any(i.shape)}
if ncol:
if len(ncol) != 1:
raise ValueError('mismatched dimensions')
flat_list = [_ for i in dat for r in i.tolist() for _ in r]
cols = ncol.pop()
rows = len(flat_list)//cols
else:
rows = cols = 0
flat_list = []
elif evaluate and any(ismat(i) for i in dat):
ncol = set()
flat_list = []
for i in dat:
if ismat(i):
flat_list.extend(
[k for j in i.tolist() for k in j])
if any(i.shape):
ncol.add(i.cols)
elif raw(i):
if i:
ncol.add(len(i))
flat_list.extend(i)
else:
ncol.add(1)
flat_list.append(i)
if len(ncol) > 1:
raise ValueError('mismatched dimensions')
cols = ncol.pop()
rows = len(flat_list)//cols
else:
# list of lists; each sublist is a logical row
# which might consist of many rows if the values in
# the row are matrices
flat_list = []
ncol = set()
rows = cols = 0
for row in dat:
if not is_sequence(row) and \
not getattr(row, 'is_Matrix', False):
raise ValueError('expecting list of lists')
if hasattr(row, '__array__'):
if 0 in row.shape:
continue
elif not row:
continue
if evaluate and all(ismat(i) for i in row):
r, c, flatT = cls._handle_creation_inputs(
[i.T for i in row])
T = reshape(flatT, [c])
flat = \
[T[i][j] for j in range(c) for i in range(r)]
r, c = c, r
else:
r = 1
if getattr(row, 'is_Matrix', False):
c = 1
flat = [row]
else:
c = len(row)
flat = [cls._sympify(i) for i in row]
ncol.add(c)
if len(ncol) > 1:
raise ValueError('mismatched dimensions')
flat_list.extend(flat)
rows += r
cols = ncol.pop() if ncol else 0
elif len(args) == 3:
rows = as_int(args[0])
cols = as_int(args[1])
if rows < 0 or cols < 0:
raise ValueError("Cannot create a {} x {} matrix. "
"Both dimensions must be positive".format(rows, cols))
# Matrix(2, 2, lambda i, j: i+j)
if len(args) == 3 and isinstance(args[2], Callable):
op = args[2]
flat_list = []
for i in range(rows):
flat_list.extend(
[cls._sympify(op(cls._sympify(i), cls._sympify(j)))
for j in range(cols)])
# Matrix(2, 2, [1, 2, 3, 4])
elif len(args) == 3 and is_sequence(args[2]):
flat_list = args[2]
if len(flat_list) != rows * cols:
raise ValueError(
'List length should be equal to rows*columns')
flat_list = [cls._sympify(i) for i in flat_list]
# Matrix()
elif len(args) == 0:
# Empty Matrix
rows = cols = 0
flat_list = []
if flat_list is None:
raise TypeError(filldedent('''
Data type not understood; expecting list of lists
or lists of values.'''))
return rows, cols, flat_list
def _setitem(self, key, value):
"""Helper to set value at location given by key.
Examples
========
>>> from sympy import Matrix, I, zeros, ones
>>> m = Matrix(((1, 2+I), (3, 4)))
>>> m
Matrix([
[1, 2 + I],
[3, 4]])
>>> m[1, 0] = 9
>>> m
Matrix([
[1, 2 + I],
[9, 4]])
>>> m[1, 0] = [[0, 1]]
To replace row r you assign to position r*m where m
is the number of columns:
>>> M = zeros(4)
>>> m = M.cols
>>> M[3*m] = ones(1, m)*2; M
Matrix([
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[2, 2, 2, 2]])
And to replace column c you can assign to position c:
>>> M[2] = ones(m, 1)*4; M
Matrix([
[0, 0, 4, 0],
[0, 0, 4, 0],
[0, 0, 4, 0],
[2, 2, 4, 2]])
"""
from .dense import Matrix
is_slice = isinstance(key, slice)
i, j = key = self.key2ij(key)
is_mat = isinstance(value, MatrixBase)
if type(i) is slice or type(j) is slice:
if is_mat:
self.copyin_matrix(key, value)
return
if not isinstance(value, Expr) and is_sequence(value):
self.copyin_list(key, value)
return
raise ValueError('unexpected value: %s' % value)
else:
if (not is_mat and
not isinstance(value, Basic) and is_sequence(value)):
value = Matrix(value)
is_mat = True
if is_mat:
if is_slice:
key = (slice(*divmod(i, self.cols)),
slice(*divmod(j, self.cols)))
else:
key = (slice(i, i + value.rows),
slice(j, j + value.cols))
self.copyin_matrix(key, value)
else:
return i, j, self._sympify(value)
return
def add(self, b):
"""Return self + b """
return self + b
def condition_number(self):
"""Returns the condition number of a matrix.
This is the maximum singular value divided by the minimum singular value
Examples
========
>>> from sympy import Matrix, S
>>> A = Matrix([[1, 0, 0], [0, 10, 0], [0, 0, S.One/10]])
>>> A.condition_number()
100
See Also
========
singular_values
"""
if not self:
return self.zero
singularvalues = self.singular_values()
return Max(*singularvalues) / Min(*singularvalues)
def copy(self):
"""
Returns the copy of a matrix.
Examples
========
>>> from sympy import Matrix
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> A.copy()
Matrix([
[1, 2],
[3, 4]])
"""
return self._new(self.rows, self.cols, self._mat)
def cross(self, b):
r"""
Return the cross product of ``self`` and ``b`` relaxing the condition
of compatible dimensions: if each has 3 elements, a matrix of the
same type and shape as ``self`` will be returned. If ``b`` has the same
shape as ``self`` then common identities for the cross product (like
`a \times b = - b \times a`) will hold.
Parameters
==========
b : 3x1 or 1x3 Matrix
See Also
========
dot
multiply
multiply_elementwise
"""
from sympy.matrices.expressions.matexpr import MatrixExpr
if not isinstance(b, MatrixBase) and not isinstance(b, MatrixExpr):
raise TypeError(
"{} must be a Matrix, not {}.".format(b, type(b)))
if not (self.rows * self.cols == b.rows * b.cols == 3):
raise ShapeError("Dimensions incorrect for cross product: %s x %s" %
((self.rows, self.cols), (b.rows, b.cols)))
else:
return self._new(self.rows, self.cols, (
(self[1] * b[2] - self[2] * b[1]),
(self[2] * b[0] - self[0] * b[2]),
(self[0] * b[1] - self[1] * b[0])))
@property
def D(self):
"""Return Dirac conjugate (if ``self.rows == 4``).
Examples
========
>>> from sympy import Matrix, I, eye
>>> m = Matrix((0, 1 + I, 2, 3))
>>> m.D
Matrix([[0, 1 - I, -2, -3]])
>>> m = (eye(4) + I*eye(4))
>>> m[0, 3] = 2
>>> m.D
Matrix([
[1 - I, 0, 0, 0],
[ 0, 1 - I, 0, 0],
[ 0, 0, -1 + I, 0],
[ 2, 0, 0, -1 + I]])
If the matrix does not have 4 rows an AttributeError will be raised
because this property is only defined for matrices with 4 rows.
>>> Matrix(eye(2)).D
Traceback (most recent call last):
...
AttributeError: Matrix has no attribute D.
See Also
========
sympy.matrices.common.MatrixCommon.conjugate: By-element conjugation
sympy.matrices.common.MatrixCommon.H: Hermite conjugation
"""
from sympy.physics.matrices import mgamma
if self.rows != 4:
# In Python 3.2, properties can only return an AttributeError
# so we can't raise a ShapeError -- see commit which added the
# first line of this inline comment. Also, there is no need
# for a message since MatrixBase will raise the AttributeError
raise AttributeError
return self.H * mgamma(0)
def dot(self, b, hermitian=None, conjugate_convention=None):
"""Return the dot or inner product of two vectors of equal length.
Here ``self`` must be a ``Matrix`` of size 1 x n or n x 1, and ``b``
must be either a matrix of size 1 x n, n x 1, or a list/tuple of length n.
A scalar is returned.
By default, ``dot`` does not conjugate ``self`` or ``b``, even if there are
complex entries. Set ``hermitian=True`` (and optionally a ``conjugate_convention``)
to compute the hermitian inner product.
Possible kwargs are ``hermitian`` and ``conjugate_convention``.
If ``conjugate_convention`` is ``"left"``, ``"math"`` or ``"maths"``,
the conjugate of the first vector (``self``) is used. If ``"right"``
or ``"physics"`` is specified, the conjugate of the second vector ``b`` is used.
Examples
========
>>> from sympy import Matrix
>>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> v = Matrix([1, 1, 1])
>>> M.row(0).dot(v)
6
>>> M.col(0).dot(v)
12
>>> v = [3, 2, 1]
>>> M.row(0).dot(v)
10
>>> from sympy import I
>>> q = Matrix([1*I, 1*I, 1*I])
>>> q.dot(q, hermitian=False)
-3
>>> q.dot(q, hermitian=True)
3
>>> q1 = Matrix([1, 1, 1*I])
>>> q.dot(q1, hermitian=True, conjugate_convention="maths")
1 - 2*I
>>> q.dot(q1, hermitian=True, conjugate_convention="physics")
1 + 2*I
See Also
========
cross
multiply
multiply_elementwise
"""
from .dense import Matrix
if not isinstance(b, MatrixBase):
if is_sequence(b):
if len(b) != self.cols and len(b) != self.rows:
raise ShapeError(
"Dimensions incorrect for dot product: %s, %s" % (
self.shape, len(b)))
return self.dot(Matrix(b))
else:
raise TypeError(
"`b` must be an ordered iterable or Matrix, not %s." %
type(b))
mat = self
if (1 not in mat.shape) or (1 not in b.shape) :
SymPyDeprecationWarning(
feature="Dot product of non row/column vectors",
issue=13815,
deprecated_since_version="1.2",
useinstead="* to take matrix products").warn()
return mat._legacy_array_dot(b)
if len(mat) != len(b):
raise ShapeError("Dimensions incorrect for dot product: %s, %s" % (self.shape, b.shape))
n = len(mat)
if mat.shape != (1, n):
mat = mat.reshape(1, n)
if b.shape != (n, 1):
b = b.reshape(n, 1)
# Now ``mat`` is a row vector and ``b`` is a column vector.
# If it so happens that only conjugate_convention is passed
# then automatically set hermitian to True. If only hermitian
# is true but no conjugate_convention is not passed then
# automatically set it to ``"maths"``
if conjugate_convention is not None and hermitian is None:
hermitian = True
if hermitian and conjugate_convention is None:
conjugate_convention = "maths"
if hermitian == True:
if conjugate_convention in ("maths", "left", "math"):
mat = mat.conjugate()
elif conjugate_convention in ("physics", "right"):
b = b.conjugate()
else:
raise ValueError("Unknown conjugate_convention was entered."
" conjugate_convention must be one of the"
" following: math, maths, left, physics or right.")
return (mat * b)[0]
def dual(self):
"""Returns the dual of a matrix, which is:
``(1/2)*levicivita(i, j, k, l)*M(k, l)`` summed over indices `k` and `l`
Since the levicivita method is anti_symmetric for any pairwise
exchange of indices, the dual of a symmetric matrix is the zero
matrix. Strictly speaking the dual defined here assumes that the
'matrix' `M` is a contravariant anti_symmetric second rank tensor,
so that the dual is a covariant second rank tensor.
"""
from sympy import LeviCivita
from sympy.matrices import zeros
M, n = self[:, :], self.rows
work = zeros(n)
if self.is_symmetric():
return work
for i in range(1, n):
for j in range(1, n):
acum = 0
for k in range(1, n):
acum += LeviCivita(i, j, 0, k) * M[0, k]
work[i, j] = acum
work[j, i] = -acum
for l in range(1, n):
acum = 0
for a in range(1, n):
for b in range(1, n):
acum += LeviCivita(0, l, a, b) * M[a, b]
acum /= 2
work[0, l] = -acum
work[l, 0] = acum
return work
def _eval_matrix_exp_jblock(self):
"""A helper function to compute an exponential of a Jordan block
matrix
Examples
========
>>> from sympy import Symbol, Matrix
>>> l = Symbol('lamda')
A trivial example of 1*1 Jordan block:
>>> m = Matrix.jordan_block(1, l)
>>> m._eval_matrix_exp_jblock()
Matrix([[exp(lamda)]])
An example of 3*3 Jordan block:
>>> m = Matrix.jordan_block(3, l)
>>> m._eval_matrix_exp_jblock()
Matrix([
[exp(lamda), exp(lamda), exp(lamda)/2],
[ 0, exp(lamda), exp(lamda)],
[ 0, 0, exp(lamda)]])
References
==========
.. [1] https://en.wikipedia.org/wiki/Matrix_function#Jordan_decomposition
"""
size = self.rows
l = self[0, 0]
exp_l = exp(l)
bands = {i: exp_l / factorial(i) for i in range(size)}
from .sparsetools import banded
return self.__class__(banded(size, bands))
def analytic_func(self, f, x):
"""
Computes f(A) where A is a Square Matrix
and f is an analytic function.
Examples
========
>>> from sympy import Symbol, Matrix, S, log
>>> x = Symbol('x')
>>> m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]])
>>> f = log(x)
>>> m.analytic_func(f, x)
Matrix([
[ 0, log(2)],
[log(2), 0]])
Parameters
==========
f : Expr
Analytic Function
x : Symbol
parameter of f
"""
from sympy import diff
f, x = _sympify(f), _sympify(x)
if not self.is_square:
raise NonSquareMatrixError
if not x.is_symbol:
raise ValueError("{} must be a symbol.".format(x))
if x not in f.free_symbols:
raise ValueError(
"{} must be a parameter of {}.".format(x, f))
if x in self.free_symbols:
raise ValueError(
"{} must not be a parameter of {}.".format(x, self))
eigen = self.eigenvals()
max_mul = max(eigen.values())
derivative = {}
dd = f
for i in range(max_mul - 1):
dd = diff(dd, x)
derivative[i + 1] = dd
n = self.shape[0]
r = self.zeros(n)
f_val = self.zeros(n, 1)
row = 0
for i in eigen:
mul = eigen[i]
f_val[row] = f.subs(x, i)
if f_val[row].is_number and not f_val[row].is_complex:
raise ValueError(
"Cannot evaluate the function because the "
"function {} is not analytic at the given "
"eigenvalue {}".format(f, f_val[row]))
val = 1
for a in range(n):
r[row, a] = val
val *= i
if mul > 1:
coe = [1 for ii in range(n)]
deri = 1
while mul > 1:
row = row + 1
mul -= 1
d_i = derivative[deri].subs(x, i)
if d_i.is_number and not d_i.is_complex:
raise ValueError(
"Cannot evaluate the function because the "
"derivative {} is not analytic at the given "
"eigenvalue {}".format(derivative[deri], d_i))
f_val[row] = d_i
for a in range(n):
if a - deri + 1 <= 0:
r[row, a] = 0
coe[a] = 0
continue
coe[a] = coe[a]*(a - deri + 1)
r[row, a] = coe[a]*pow(i, a - deri)
deri += 1
row += 1
c = r.solve(f_val)
ans = self.zeros(n)
pre = self.eye(n)
for i in range(n):
ans = ans + c[i]*pre
pre *= self
return ans
def exp(self):
"""Return the exponential of a square matrix
Examples
========
>>> from sympy import Symbol, Matrix
>>> t = Symbol('t')
>>> m = Matrix([[0, 1], [-1, 0]]) * t
>>> m.exp()
Matrix([
[ exp(I*t)/2 + exp(-I*t)/2, -I*exp(I*t)/2 + I*exp(-I*t)/2],
[I*exp(I*t)/2 - I*exp(-I*t)/2, exp(I*t)/2 + exp(-I*t)/2]])
"""
if not self.is_square:
raise NonSquareMatrixError(
"Exponentiation is valid only for square matrices")
try:
P, J = self.jordan_form()
cells = J.get_diag_blocks()
except MatrixError:
raise NotImplementedError(
"Exponentiation is implemented only for matrices for which the Jordan normal form can be computed")
blocks = [cell._eval_matrix_exp_jblock() for cell in cells]
from sympy.matrices import diag
from sympy import re
eJ = diag(*blocks)
# n = self.rows
ret = P.multiply(eJ, dotprodsimp=None).multiply(P.inv(), dotprodsimp=None)
if all(value.is_real for value in self.values()):
return type(self)(re(ret))
else:
return type(self)(ret)
def _eval_matrix_log_jblock(self):
"""Helper function to compute logarithm of a jordan block.
Examples
========
>>> from sympy import Symbol, Matrix
>>> l = Symbol('lamda')
A trivial example of 1*1 Jordan block:
>>> m = Matrix.jordan_block(1, l)
>>> m._eval_matrix_log_jblock()
Matrix([[log(lamda)]])
An example of 3*3 Jordan block:
>>> m = Matrix.jordan_block(3, l)
>>> m._eval_matrix_log_jblock()
Matrix([
[log(lamda), 1/lamda, -1/(2*lamda**2)],
[ 0, log(lamda), 1/lamda],
[ 0, 0, log(lamda)]])
"""
size = self.rows
l = self[0, 0]
if l.is_zero:
raise MatrixError(
'Could not take logarithm or reciprocal for the given '
'eigenvalue {}'.format(l))
bands = {0: log(l)}
for i in range(1, size):
bands[i] = -((-l) ** -i) / i
from .sparsetools import banded
return self.__class__(banded(size, bands))
def log(self, simplify=cancel):
"""Return the logarithm of a square matrix
Parameters
==========
simplify : function, bool
The function to simplify the result with.
Default is ``cancel``, which is effective to reduce the
expression growing for taking reciprocals and inverses for
symbolic matrices.
Examples
========
>>> from sympy import S, Matrix
Examples for positive-definite matrices:
>>> m = Matrix([[1, 1], [0, 1]])
>>> m.log()
Matrix([
[0, 1],
[0, 0]])
>>> m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]])
>>> m.log()
Matrix([
[ 0, log(2)],
[log(2), 0]])
Examples for non positive-definite matrices:
>>> m = Matrix([[S(3)/4, S(5)/4], [S(5)/4, S(3)/4]])
>>> m.log()
Matrix([
[ I*pi/2, log(2) - I*pi/2],
[log(2) - I*pi/2, I*pi/2]])
>>> m = Matrix(
... [[0, 0, 0, 1],
... [0, 0, 1, 0],
... [0, 1, 0, 0],
... [1, 0, 0, 0]])
>>> m.log()
Matrix([
[ I*pi/2, 0, 0, -I*pi/2],
[ 0, I*pi/2, -I*pi/2, 0],
[ 0, -I*pi/2, I*pi/2, 0],
[-I*pi/2, 0, 0, I*pi/2]])
"""
if not self.is_square:
raise NonSquareMatrixError(
"Logarithm is valid only for square matrices")
try:
if simplify:
P, J = simplify(self).jordan_form()
else:
P, J = self.jordan_form()
cells = J.get_diag_blocks()
except MatrixError:
raise NotImplementedError(
"Logarithm is implemented only for matrices for which "
"the Jordan normal form can be computed")
blocks = [
cell._eval_matrix_log_jblock()
for cell in cells]
from sympy.matrices import diag
eJ = diag(*blocks)
if simplify:
ret = simplify(P * eJ * simplify(P.inv()))
ret = self.__class__(ret)
else:
ret = P * eJ * P.inv()
return ret
def is_nilpotent(self):
"""Checks if a matrix is nilpotent.
A matrix B is nilpotent if for some integer k, B**k is
a zero matrix.
Examples
========
>>> from sympy import Matrix
>>> a = Matrix([[0, 0, 0], [1, 0, 0], [1, 1, 0]])
>>> a.is_nilpotent()
True
>>> a = Matrix([[1, 0, 1], [1, 0, 0], [1, 1, 0]])
>>> a.is_nilpotent()
False
"""
if not self:
return True
if not self.is_square:
raise NonSquareMatrixError(
"Nilpotency is valid only for square matrices")
x = uniquely_named_symbol('x', self, modify=lambda s: '_' + s)
p = self.charpoly(x)
if p.args[0] == x ** self.rows:
return True
return False
def key2bounds(self, keys):
"""Converts a key with potentially mixed types of keys (integer and slice)
into a tuple of ranges and raises an error if any index is out of ``self``'s
range.
See Also
========
key2ij
"""
from sympy.matrices.common import a2idx as a2idx_ # Remove this line after deprecation of a2idx from matrices.py
islice, jslice = [isinstance(k, slice) for k in keys]
if islice:
if not self.rows:
rlo = rhi = 0
else:
rlo, rhi = keys[0].indices(self.rows)[:2]
else:
rlo = a2idx_(keys[0], self.rows)
rhi = rlo + 1
if jslice:
if not self.cols:
clo = chi = 0
else:
clo, chi = keys[1].indices(self.cols)[:2]
else:
clo = a2idx_(keys[1], self.cols)
chi = clo + 1
return rlo, rhi, clo, chi
def key2ij(self, key):
"""Converts key into canonical form, converting integers or indexable
items into valid integers for ``self``'s range or returning slices
unchanged.
See Also
========
key2bounds
"""
from sympy.matrices.common import a2idx as a2idx_ # Remove this line after deprecation of a2idx from matrices.py
if is_sequence(key):
if not len(key) == 2:
raise TypeError('key must be a sequence of length 2')
return [a2idx_(i, n) if not isinstance(i, slice) else i
for i, n in zip(key, self.shape)]
elif isinstance(key, slice):
return key.indices(len(self))[:2]
else:
return divmod(a2idx_(key, len(self)), self.cols)
def normalized(self, iszerofunc=_iszero):
"""Return the normalized version of ``self``.
Parameters
==========
iszerofunc : Function, optional
A function to determine whether ``self`` is a zero vector.
The default ``_iszero`` tests to see if each element is
exactly zero.
Returns
=======
Matrix
Normalized vector form of ``self``.
It has the same length as a unit vector. However, a zero vector
will be returned for a vector with norm 0.
Raises
======
ShapeError
If the matrix is not in a vector form.
See Also
========
norm
"""
if self.rows != 1 and self.cols != 1:
raise ShapeError("A Matrix must be a vector to normalize.")
norm = self.norm()
if iszerofunc(norm):
out = self.zeros(self.rows, self.cols)
else:
out = self.applyfunc(lambda i: i / norm)
return out
def norm(self, ord=None):
"""Return the Norm of a Matrix or Vector.
In the simplest case this is the geometric size of the vector
Other norms can be specified by the ord parameter
===== ============================ ==========================
ord norm for matrices norm for vectors
===== ============================ ==========================
None Frobenius norm 2-norm
'fro' Frobenius norm - does not exist
inf maximum row sum max(abs(x))
-inf -- min(abs(x))
1 maximum column sum as below
-1 -- as below
2 2-norm (largest sing. value) as below
-2 smallest singular value as below
other - does not exist sum(abs(x)**ord)**(1./ord)
===== ============================ ==========================
Examples
========
>>> from sympy import Matrix, Symbol, trigsimp, cos, sin, oo
>>> x = Symbol('x', real=True)
>>> v = Matrix([cos(x), sin(x)])
>>> trigsimp( v.norm() )
1
>>> v.norm(10)
(sin(x)**10 + cos(x)**10)**(1/10)
>>> A = Matrix([[1, 1], [1, 1]])
>>> A.norm(1) # maximum sum of absolute values of A is 2
2
>>> A.norm(2) # Spectral norm (max of |Ax|/|x| under 2-vector-norm)
2
>>> A.norm(-2) # Inverse spectral norm (smallest singular value)
0
>>> A.norm() # Frobenius Norm
2
>>> A.norm(oo) # Infinity Norm
2
>>> Matrix([1, -2]).norm(oo)
2
>>> Matrix([-1, 2]).norm(-oo)
1
See Also
========
normalized
"""
# Row or Column Vector Norms
vals = list(self.values()) or [0]
if self.rows == 1 or self.cols == 1:
if ord == 2 or ord is None: # Common case sqrt(<x, x>)
return sqrt(Add(*(abs(i) ** 2 for i in vals)))
elif ord == 1: # sum(abs(x))
return Add(*(abs(i) for i in vals))
elif ord is S.Infinity: # max(abs(x))
return Max(*[abs(i) for i in vals])
elif ord is S.NegativeInfinity: # min(abs(x))
return Min(*[abs(i) for i in vals])
# Otherwise generalize the 2-norm, Sum(x_i**ord)**(1/ord)
# Note that while useful this is not mathematically a norm
try:
return Pow(Add(*(abs(i) ** ord for i in vals)), S.One / ord)
except (NotImplementedError, TypeError):
raise ValueError("Expected order to be Number, Symbol, oo")
# Matrix Norms
else:
if ord == 1: # Maximum column sum
m = self.applyfunc(abs)
return Max(*[sum(m.col(i)) for i in range(m.cols)])
elif ord == 2: # Spectral Norm
# Maximum singular value
return Max(*self.singular_values())
elif ord == -2:
# Minimum singular value
return Min(*self.singular_values())
elif ord is S.Infinity: # Infinity Norm - Maximum row sum
m = self.applyfunc(abs)
return Max(*[sum(m.row(i)) for i in range(m.rows)])
elif (ord is None or isinstance(ord,
str) and ord.lower() in
['f', 'fro', 'frobenius', 'vector']):
# Reshape as vector and send back to norm function
return self.vec().norm(ord=2)
else:
raise NotImplementedError("Matrix Norms under development")
def print_nonzero(self, symb="X"):
"""Shows location of non-zero entries for fast shape lookup.
Examples
========
>>> from sympy.matrices import Matrix, eye
>>> m = Matrix(2, 3, lambda i, j: i*3+j)
>>> m
Matrix([
[0, 1, 2],
[3, 4, 5]])
>>> m.print_nonzero()
[ XX]
[XXX]
>>> m = eye(4)
>>> m.print_nonzero("x")
[x ]
[ x ]
[ x ]
[ x]
"""
s = []
for i in range(self.rows):
line = []
for j in range(self.cols):
if self[i, j] == 0:
line.append(" ")
else:
line.append(str(symb))
s.append("[%s]" % ''.join(line))
print('\n'.join(s))
def project(self, v):
"""Return the projection of ``self`` onto the line containing ``v``.
Examples
========
>>> from sympy import Matrix, S, sqrt
>>> V = Matrix([sqrt(3)/2, S.Half])
>>> x = Matrix([[1, 0]])
>>> V.project(x)
Matrix([[sqrt(3)/2, 0]])
>>> V.project(-x)
Matrix([[sqrt(3)/2, 0]])
"""
return v * (self.dot(v) / v.dot(v))
def table(self, printer, rowstart='[', rowend=']', rowsep='\n',
colsep=', ', align='right'):
r"""
String form of Matrix as a table.
``printer`` is the printer to use for on the elements (generally
something like StrPrinter())
``rowstart`` is the string used to start each row (by default '[').
``rowend`` is the string used to end each row (by default ']').
``rowsep`` is the string used to separate rows (by default a newline).
``colsep`` is the string used to separate columns (by default ', ').
``align`` defines how the elements are aligned. Must be one of 'left',
'right', or 'center'. You can also use '<', '>', and '^' to mean the
same thing, respectively.
This is used by the string printer for Matrix.
Examples
========
>>> from sympy import Matrix
>>> from sympy.printing.str import StrPrinter
>>> M = Matrix([[1, 2], [-33, 4]])
>>> printer = StrPrinter()
>>> M.table(printer)
'[ 1, 2]\n[-33, 4]'
>>> print(M.table(printer))
[ 1, 2]
[-33, 4]
>>> print(M.table(printer, rowsep=',\n'))
[ 1, 2],
[-33, 4]
>>> print('[%s]' % M.table(printer, rowsep=',\n'))
[[ 1, 2],
[-33, 4]]
>>> print(M.table(printer, colsep=' '))
[ 1 2]
[-33 4]
>>> print(M.table(printer, align='center'))
[ 1 , 2]
[-33, 4]
>>> print(M.table(printer, rowstart='{', rowend='}'))
{ 1, 2}
{-33, 4}
"""
# Handle zero dimensions:
if self.rows == 0 or self.cols == 0:
return '[]'
# Build table of string representations of the elements
res = []
# Track per-column max lengths for pretty alignment
maxlen = [0] * self.cols
for i in range(self.rows):
res.append([])
for j in range(self.cols):
s = printer._print(self[i, j])
res[-1].append(s)
maxlen[j] = max(len(s), maxlen[j])
# Patch strings together
align = {
'left': 'ljust',
'right': 'rjust',
'center': 'center',
'<': 'ljust',
'>': 'rjust',
'^': 'center',
}[align]
for i, row in enumerate(res):
for j, elem in enumerate(row):
row[j] = getattr(elem, align)(maxlen[j])
res[i] = rowstart + colsep.join(row) + rowend
return rowsep.join(res)
def rank_decomposition(self, iszerofunc=_iszero, simplify=False):
return _rank_decomposition(self, iszerofunc=iszerofunc,
simplify=simplify)
def cholesky(self, hermitian=True):
raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix')
def LDLdecomposition(self, hermitian=True):
raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix')
def LUdecomposition(self, iszerofunc=_iszero, simpfunc=None,
rankcheck=False):
return _LUdecomposition(self, iszerofunc=iszerofunc, simpfunc=simpfunc,
rankcheck=rankcheck)
def LUdecomposition_Simple(self, iszerofunc=_iszero, simpfunc=None,
rankcheck=False):
return _LUdecomposition_Simple(self, iszerofunc=iszerofunc,
simpfunc=simpfunc, rankcheck=rankcheck)
def LUdecompositionFF(self):
return _LUdecompositionFF(self)
def singular_value_decomposition(self):
return _singular_value_decomposition(self)
def QRdecomposition(self):
return _QRdecomposition(self)
def upper_hessenberg_decomposition(self):
return _upper_hessenberg_decomposition(self)
def diagonal_solve(self, rhs):
return _diagonal_solve(self, rhs)
def lower_triangular_solve(self, rhs):
raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix')
def upper_triangular_solve(self, rhs):
raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix')
def cholesky_solve(self, rhs):
return _cholesky_solve(self, rhs)
def LDLsolve(self, rhs):
return _LDLsolve(self, rhs)
def LUsolve(self, rhs, iszerofunc=_iszero):
return _LUsolve(self, rhs, iszerofunc=iszerofunc)
def QRsolve(self, b):
return _QRsolve(self, b)
def gauss_jordan_solve(self, B, freevar=False):
return _gauss_jordan_solve(self, B, freevar=freevar)
def pinv_solve(self, B, arbitrary_matrix=None):
return _pinv_solve(self, B, arbitrary_matrix=arbitrary_matrix)
def solve(self, rhs, method='GJ'):
return _solve(self, rhs, method=method)
def solve_least_squares(self, rhs, method='CH'):
return _solve_least_squares(self, rhs, method=method)
def pinv(self, method='RD'):
return _pinv(self, method=method)
def inv_mod(self, m):
return _inv_mod(self, m)
def inverse_ADJ(self, iszerofunc=_iszero):
return _inv_ADJ(self, iszerofunc=iszerofunc)
def inverse_BLOCK(self, iszerofunc=_iszero):
return _inv_block(self, iszerofunc=iszerofunc)
def inverse_GE(self, iszerofunc=_iszero):
return _inv_GE(self, iszerofunc=iszerofunc)
def inverse_LU(self, iszerofunc=_iszero):
return _inv_LU(self, iszerofunc=iszerofunc)
def inverse_CH(self, iszerofunc=_iszero):
return _inv_CH(self, iszerofunc=iszerofunc)
def inverse_LDL(self, iszerofunc=_iszero):
return _inv_LDL(self, iszerofunc=iszerofunc)
def inverse_QR(self, iszerofunc=_iszero):
return _inv_QR(self, iszerofunc=iszerofunc)
def inv(self, method=None, iszerofunc=_iszero, try_block_diag=False):
return _inv(self, method=method, iszerofunc=iszerofunc,
try_block_diag=try_block_diag)
def connected_components(self):
return _connected_components(self)
def connected_components_decomposition(self):
return _connected_components_decomposition(self)
def strongly_connected_components(self):
return _strongly_connected_components(self)
def strongly_connected_components_decomposition(self, lower=True):
return _strongly_connected_components_decomposition(self, lower=lower)
rank_decomposition.__doc__ = _rank_decomposition.__doc__
cholesky.__doc__ = _cholesky.__doc__
LDLdecomposition.__doc__ = _LDLdecomposition.__doc__
LUdecomposition.__doc__ = _LUdecomposition.__doc__
LUdecomposition_Simple.__doc__ = _LUdecomposition_Simple.__doc__
LUdecompositionFF.__doc__ = _LUdecompositionFF.__doc__
singular_value_decomposition.__doc__ = _singular_value_decomposition.__doc__
QRdecomposition.__doc__ = _QRdecomposition.__doc__
upper_hessenberg_decomposition.__doc__ = _upper_hessenberg_decomposition.__doc__
diagonal_solve.__doc__ = _diagonal_solve.__doc__
lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__
upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__
cholesky_solve.__doc__ = _cholesky_solve.__doc__
LDLsolve.__doc__ = _LDLsolve.__doc__
LUsolve.__doc__ = _LUsolve.__doc__
QRsolve.__doc__ = _QRsolve.__doc__
gauss_jordan_solve.__doc__ = _gauss_jordan_solve.__doc__
pinv_solve.__doc__ = _pinv_solve.__doc__
solve.__doc__ = _solve.__doc__
solve_least_squares.__doc__ = _solve_least_squares.__doc__
pinv.__doc__ = _pinv.__doc__
inv_mod.__doc__ = _inv_mod.__doc__
inverse_ADJ.__doc__ = _inv_ADJ.__doc__
inverse_GE.__doc__ = _inv_GE.__doc__
inverse_LU.__doc__ = _inv_LU.__doc__
inverse_CH.__doc__ = _inv_CH.__doc__
inverse_LDL.__doc__ = _inv_LDL.__doc__
inverse_QR.__doc__ = _inv_QR.__doc__
inverse_BLOCK.__doc__ = _inv_block.__doc__
inv.__doc__ = _inv.__doc__
connected_components.__doc__ = _connected_components.__doc__
connected_components_decomposition.__doc__ = \
_connected_components_decomposition.__doc__
strongly_connected_components.__doc__ = \
_strongly_connected_components.__doc__
strongly_connected_components_decomposition.__doc__ = \
_strongly_connected_components_decomposition.__doc__
@deprecated(
issue=15109,
useinstead="from sympy.matrices.common import classof",
deprecated_since_version="1.3")
def classof(A, B):
from sympy.matrices.common import classof as classof_
return classof_(A, B)
@deprecated(
issue=15109,
deprecated_since_version="1.3",
useinstead="from sympy.matrices.common import a2idx")
def a2idx(j, n=None):
from sympy.matrices.common import a2idx as a2idx_
return a2idx_(j, n)
|
2a01943790d252a2edde0990b52dc71bc043072cae5e0580424ba7f4987ace6e | from types import FunctionType
from collections import Counter
from mpmath import mp, workprec
from mpmath.libmp.libmpf import prec_to_dps
from sympy.core.compatibility import default_sort_key
from sympy.core.evalf import DEFAULT_MAXPREC, PrecisionExhausted
from sympy.core.logic import fuzzy_and, fuzzy_or
from sympy.core.numbers import Float
from sympy.core.sympify import _sympify
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.polys import roots, CRootOf, EX
from sympy.polys.matrices import DomainMatrix
from sympy.polys.matrices.eigen import dom_eigenvects, dom_eigenvects_to_sympy
from sympy.simplify import nsimplify, simplify as _simplify
from sympy.utilities.exceptions import SymPyDeprecationWarning
from .common import MatrixError, NonSquareMatrixError
from .determinant import _find_reasonable_pivot
from .utilities import _iszero
def _eigenvals_eigenvects_mpmath(M):
norm2 = lambda v: mp.sqrt(sum(i**2 for i in v))
v1 = None
prec = max([x._prec for x in M.atoms(Float)])
eps = 2**-prec
while prec < DEFAULT_MAXPREC:
with workprec(prec):
A = mp.matrix(M.evalf(n=prec_to_dps(prec)))
E, ER = mp.eig(A)
v2 = norm2([i for e in E for i in (mp.re(e), mp.im(e))])
if v1 is not None and mp.fabs(v1 - v2) < eps:
return E, ER
v1 = v2
prec *= 2
# we get here because the next step would have taken us
# past MAXPREC or because we never took a step; in case
# of the latter, we refuse to send back a solution since
# it would not have been verified; we also resist taking
# a small step to arrive exactly at MAXPREC since then
# the two calculations might be artificially close.
raise PrecisionExhausted
def _eigenvals_mpmath(M, multiple=False):
"""Compute eigenvalues using mpmath"""
E, _ = _eigenvals_eigenvects_mpmath(M)
result = [_sympify(x) for x in E]
if multiple:
return result
return dict(Counter(result))
def _eigenvects_mpmath(M):
E, ER = _eigenvals_eigenvects_mpmath(M)
result = []
for i in range(M.rows):
eigenval = _sympify(E[i])
eigenvect = _sympify(ER[:, i])
result.append((eigenval, 1, [eigenvect]))
return result
# This function is a candidate for caching if it gets implemented for matrices.
def _eigenvals(
M, error_when_incomplete=True, *, simplify=False, multiple=False,
rational=False, **flags):
r"""Compute eigenvalues of the matrix.
Parameters
==========
error_when_incomplete : bool, optional
If it is set to ``True``, it will raise an error if not all
eigenvalues are computed. This is caused by ``roots`` not returning
a full list of eigenvalues.
simplify : bool or function, optional
If it is set to ``True``, it attempts to return the most
simplified form of expressions returned by applying default
simplification method in every routine.
If it is set to ``False``, it will skip simplification in this
particular routine to save computation resources.
If a function is passed to, it will attempt to apply
the particular function as simplification method.
rational : bool, optional
If it is set to ``True``, every floating point numbers would be
replaced with rationals before computation. It can solve some
issues of ``roots`` routine not working well with floats.
multiple : bool, optional
If it is set to ``True``, the result will be in the form of a
list.
If it is set to ``False``, the result will be in the form of a
dictionary.
Returns
=======
eigs : list or dict
Eigenvalues of a matrix. The return format would be specified by
the key ``multiple``.
Raises
======
MatrixError
If not enough roots had got computed.
NonSquareMatrixError
If attempted to compute eigenvalues from a non-square matrix.
Examples
========
>>> from sympy.matrices import Matrix
>>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1])
>>> M.eigenvals()
{-1: 1, 0: 1, 2: 1}
See Also
========
MatrixDeterminant.charpoly
eigenvects
Notes
=====
Eigenvalues of a matrix $A$ can be computed by solving a matrix
equation $\det(A - \lambda I) = 0$
It's not always possible to return radical solutions for
eigenvalues for matrices larger than $4, 4$ shape due to
Abel-Ruffini theorem.
If there is no radical solution is found for the eigenvalue,
it may return eigenvalues in the form of
:class:`sympy.polys.rootoftools.ComplexRootOf`.
"""
if not M:
if multiple:
return []
return {}
if not M.is_square:
raise NonSquareMatrixError("{} must be a square matrix.".format(M))
if all(x.is_number for x in M) and M.has(Float):
return _eigenvals_mpmath(M, multiple=multiple)
if rational:
M = M.applyfunc(
lambda x: nsimplify(x, rational=True) if x.has(Float) else x)
if multiple:
return _eigenvals_list(
M, error_when_incomplete=error_when_incomplete, simplify=simplify,
**flags)
return _eigenvals_dict(
M, error_when_incomplete=error_when_incomplete, simplify=simplify,
**flags)
eigenvals_error_message = \
"It is not always possible to express the eigenvalues of a matrix " + \
"of size 5x5 or higher in radicals. " + \
"We have CRootOf, but domains other than the rationals are not " + \
"currently supported. " + \
"If there are no symbols in the matrix, " + \
"it should still be possible to compute numeric approximations " + \
"of the eigenvalues using " + \
"M.evalf().eigenvals() or M.charpoly().nroots()."
def _eigenvals_list(
M, error_when_incomplete=True, simplify=False, **flags):
iblocks = M.strongly_connected_components()
all_eigs = []
for b in iblocks:
block = M[b, b]
if isinstance(simplify, FunctionType):
charpoly = block.charpoly(simplify=simplify)
else:
charpoly = block.charpoly()
eigs = roots(charpoly, multiple=True, **flags)
if len(eigs) != block.rows:
degree = int(charpoly.degree())
f = charpoly.as_expr()
x = charpoly.gen
try:
eigs = [CRootOf(f, x, idx) for idx in range(degree)]
except NotImplementedError:
if error_when_incomplete:
raise MatrixError(eigenvals_error_message)
else:
eigs = []
all_eigs += eigs
if not simplify:
return all_eigs
if not isinstance(simplify, FunctionType):
simplify = _simplify
return [simplify(value) for value in all_eigs]
def _eigenvals_dict(
M, error_when_incomplete=True, simplify=False, **flags):
iblocks = M.strongly_connected_components()
all_eigs = {}
for b in iblocks:
block = M[b, b]
if isinstance(simplify, FunctionType):
charpoly = block.charpoly(simplify=simplify)
else:
charpoly = block.charpoly()
eigs = roots(charpoly, multiple=False, **flags)
if sum(eigs.values()) != block.rows:
degree = int(charpoly.degree())
f = charpoly.as_expr()
x = charpoly.gen
try:
eigs = {CRootOf(f, x, idx): 1 for idx in range(degree)}
except NotImplementedError:
if error_when_incomplete:
raise MatrixError(eigenvals_error_message)
else:
eigs = {}
for k, v in eigs.items():
if k in all_eigs:
all_eigs[k] += v
else:
all_eigs[k] = v
if not simplify:
return all_eigs
if not isinstance(simplify, FunctionType):
simplify = _simplify
return {simplify(key): value for key, value in all_eigs.items()}
def _eigenspace(M, eigenval, iszerofunc=_iszero, simplify=False):
"""Get a basis for the eigenspace for a particular eigenvalue"""
m = M - M.eye(M.rows) * eigenval
ret = m.nullspace(iszerofunc=iszerofunc)
# The nullspace for a real eigenvalue should be non-trivial.
# If we didn't find an eigenvector, try once more a little harder
if len(ret) == 0 and simplify:
ret = m.nullspace(iszerofunc=iszerofunc, simplify=True)
if len(ret) == 0:
raise NotImplementedError(
"Can't evaluate eigenvector for eigenvalue {}".format(eigenval))
return ret
def _eigenvects_DOM(M, **kwargs):
DOM = DomainMatrix.from_Matrix(M, field=True, extension=True)
DOM = DOM.to_dense()
if DOM.domain != EX:
rational, algebraic = dom_eigenvects(DOM)
eigenvects = dom_eigenvects_to_sympy(
rational, algebraic, M.__class__, **kwargs)
eigenvects = sorted(eigenvects, key=lambda x: default_sort_key(x[0]))
return eigenvects
return None
def _eigenvects_sympy(M, iszerofunc, simplify=True, **flags):
eigenvals = M.eigenvals(rational=False, **flags)
# Make sure that we have all roots in radical form
for x in eigenvals:
if x.has(CRootOf):
raise MatrixError(
"Eigenvector computation is not implemented if the matrix have "
"eigenvalues in CRootOf form")
eigenvals = sorted(eigenvals.items(), key=default_sort_key)
ret = []
for val, mult in eigenvals:
vects = _eigenspace(M, val, iszerofunc=iszerofunc, simplify=simplify)
ret.append((val, mult, vects))
return ret
# This functions is a candidate for caching if it gets implemented for matrices.
def _eigenvects(M, error_when_incomplete=True, iszerofunc=_iszero, *, chop=False, **flags):
"""Compute eigenvectors of the matrix.
Parameters
==========
error_when_incomplete : bool, optional
Raise an error when not all eigenvalues are computed. This is
caused by ``roots`` not returning a full list of eigenvalues.
iszerofunc : function, optional
Specifies a zero testing function to be used in ``rref``.
Default value is ``_iszero``, which uses SymPy's naive and fast
default assumption handler.
It can also accept any user-specified zero testing function, if it
is formatted as a function which accepts a single symbolic argument
and returns ``True`` if it is tested as zero and ``False`` if it
is tested as non-zero, and ``None`` if it is undecidable.
simplify : bool or function, optional
If ``True``, ``as_content_primitive()`` will be used to tidy up
normalization artifacts.
It will also be used by the ``nullspace`` routine.
chop : bool or positive number, optional
If the matrix contains any Floats, they will be changed to Rationals
for computation purposes, but the answers will be returned after
being evaluated with evalf. The ``chop`` flag is passed to ``evalf``.
When ``chop=True`` a default precision will be used; a number will
be interpreted as the desired level of precision.
Returns
=======
ret : [(eigenval, multiplicity, eigenspace), ...]
A ragged list containing tuples of data obtained by ``eigenvals``
and ``nullspace``.
``eigenspace`` is a list containing the ``eigenvector`` for each
eigenvalue.
``eigenvector`` is a vector in the form of a ``Matrix``. e.g.
a vector of length 3 is returned as ``Matrix([a_1, a_2, a_3])``.
Raises
======
NotImplementedError
If failed to compute nullspace.
Examples
========
>>> from sympy.matrices import Matrix
>>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1])
>>> M.eigenvects()
[(-1, 1, [Matrix([
[-1],
[ 1],
[ 0]])]), (0, 1, [Matrix([
[ 0],
[-1],
[ 1]])]), (2, 1, [Matrix([
[2/3],
[1/3],
[ 1]])])]
See Also
========
eigenvals
MatrixSubspaces.nullspace
"""
simplify = flags.get('simplify', True)
primitive = flags.get('simplify', False)
flags.pop('simplify', None) # remove this if it's there
flags.pop('multiple', None) # remove this if it's there
if not isinstance(simplify, FunctionType):
simpfunc = _simplify if simplify else lambda x: x
has_floats = M.has(Float)
if has_floats:
if all(x.is_number for x in M):
return _eigenvects_mpmath(M)
M = M.applyfunc(lambda x: nsimplify(x, rational=True))
ret = _eigenvects_DOM(M)
if ret is None:
ret = _eigenvects_sympy(M, iszerofunc, simplify=simplify, **flags)
if primitive:
# if the primitive flag is set, get rid of any common
# integer denominators
def denom_clean(l):
from sympy import gcd
return [(v / gcd(list(v))).applyfunc(simpfunc) for v in l]
ret = [(val, mult, denom_clean(es)) for val, mult, es in ret]
if has_floats:
# if we had floats to start with, turn the eigenvectors to floats
ret = [(val.evalf(chop=chop), mult, [v.evalf(chop=chop) for v in es])
for val, mult, es in ret]
return ret
def _is_diagonalizable_with_eigen(M, reals_only=False):
"""See _is_diagonalizable. This function returns the bool along with the
eigenvectors to avoid calculating them again in functions like
``diagonalize``."""
if not M.is_square:
return False, []
eigenvecs = M.eigenvects(simplify=True)
for val, mult, basis in eigenvecs:
if reals_only and not val.is_real: # if we have a complex eigenvalue
return False, eigenvecs
if mult != len(basis): # if the geometric multiplicity doesn't equal the algebraic
return False, eigenvecs
return True, eigenvecs
def _is_diagonalizable(M, reals_only=False, **kwargs):
"""Returns ``True`` if a matrix is diagonalizable.
Parameters
==========
reals_only : bool, optional
If ``True``, it tests whether the matrix can be diagonalized
to contain only real numbers on the diagonal.
If ``False``, it tests whether the matrix can be diagonalized
at all, even with numbers that may not be real.
Examples
========
Example of a diagonalizable matrix:
>>> from sympy import Matrix
>>> M = Matrix([[1, 2, 0], [0, 3, 0], [2, -4, 2]])
>>> M.is_diagonalizable()
True
Example of a non-diagonalizable matrix:
>>> M = Matrix([[0, 1], [0, 0]])
>>> M.is_diagonalizable()
False
Example of a matrix that is diagonalized in terms of non-real entries:
>>> M = Matrix([[0, 1], [-1, 0]])
>>> M.is_diagonalizable(reals_only=False)
True
>>> M.is_diagonalizable(reals_only=True)
False
See Also
========
is_diagonal
diagonalize
"""
if 'clear_cache' in kwargs:
SymPyDeprecationWarning(
feature='clear_cache',
deprecated_since_version=1.4,
issue=15887
).warn()
if 'clear_subproducts' in kwargs:
SymPyDeprecationWarning(
feature='clear_subproducts',
deprecated_since_version=1.4,
issue=15887
).warn()
if not M.is_square:
return False
if all(e.is_real for e in M) and M.is_symmetric():
return True
if all(e.is_complex for e in M) and M.is_hermitian:
return True
return _is_diagonalizable_with_eigen(M, reals_only=reals_only)[0]
#G&VL, Matrix Computations, Algo 5.4.2
def _householder_vector(x):
if not x.cols == 1:
raise ValueError("Input must be a column matrix")
v = x.copy()
v_plus = x.copy()
v_minus = x.copy()
q = x[0, 0] / abs(x[0, 0])
norm_x = x.norm()
v_plus[0, 0] = x[0, 0] + q * norm_x
v_minus[0, 0] = x[0, 0] - q * norm_x
if x[1:, 0].norm() == 0:
bet = 0
v[0, 0] = 1
else:
if v_plus.norm() <= v_minus.norm():
v = v_plus
else:
v = v_minus
v = v / v[0]
bet = 2 / (v.norm() ** 2)
return v, bet
def _bidiagonal_decmp_hholder(M):
m = M.rows
n = M.cols
A = M.as_mutable()
U, V = A.eye(m), A.eye(n)
for i in range(min(m, n)):
v, bet = _householder_vector(A[i:, i])
hh_mat = A.eye(m - i) - bet * v * v.H
A[i:, i:] = hh_mat * A[i:, i:]
temp = A.eye(m)
temp[i:, i:] = hh_mat
U = U * temp
if i + 1 <= n - 2:
v, bet = _householder_vector(A[i, i+1:].T)
hh_mat = A.eye(n - i - 1) - bet * v * v.H
A[i:, i+1:] = A[i:, i+1:] * hh_mat
temp = A.eye(n)
temp[i+1:, i+1:] = hh_mat
V = temp * V
return U, A, V
def _eval_bidiag_hholder(M):
m = M.rows
n = M.cols
A = M.as_mutable()
for i in range(min(m, n)):
v, bet = _householder_vector(A[i:, i])
hh_mat = A.eye(m-i) - bet * v * v.H
A[i:, i:] = hh_mat * A[i:, i:]
if i + 1 <= n - 2:
v, bet = _householder_vector(A[i, i+1:].T)
hh_mat = A.eye(n - i - 1) - bet * v * v.H
A[i:, i+1:] = A[i:, i+1:] * hh_mat
return A
def _bidiagonal_decomposition(M, upper=True):
"""
Returns (U,B,V.H)
$A = UBV^{H}$
where A is the input matrix, and B is its Bidiagonalized form
Note: Bidiagonal Computation can hang for symbolic matrices.
Parameters
==========
upper : bool. Whether to do upper bidiagnalization or lower.
True for upper and False for lower.
References
==========
1. Algorith 5.4.2, Matrix computations by Golub and Van Loan, 4th edition
2. Complex Matrix Bidiagonalization : https://github.com/vslobody/Householder-Bidiagonalization
"""
if type(upper) is not bool:
raise ValueError("upper must be a boolean")
if not upper:
X = _bidiagonal_decmp_hholder(M.H)
return X[2].H, X[1].H, X[0].H
return _bidiagonal_decmp_hholder(M)
def _bidiagonalize(M, upper=True):
"""
Returns $B$, the Bidiagonalized form of the input matrix.
Note: Bidiagonal Computation can hang for symbolic matrices.
Parameters
==========
upper : bool. Whether to do upper bidiagnalization or lower.
True for upper and False for lower.
References
==========
1. Algorith 5.4.2, Matrix computations by Golub and Van Loan, 4th edition
2. Complex Matrix Bidiagonalization : https://github.com/vslobody/Householder-Bidiagonalization
"""
if type(upper) is not bool:
raise ValueError("upper must be a boolean")
if not upper:
return _eval_bidiag_hholder(M.H).H
return _eval_bidiag_hholder(M)
def _diagonalize(M, reals_only=False, sort=False, normalize=False):
"""
Return (P, D), where D is diagonal and
D = P^-1 * M * P
where M is current matrix.
Parameters
==========
reals_only : bool. Whether to throw an error if complex numbers are need
to diagonalize. (Default: False)
sort : bool. Sort the eigenvalues along the diagonal. (Default: False)
normalize : bool. If True, normalize the columns of P. (Default: False)
Examples
========
>>> from sympy.matrices import Matrix
>>> M = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
>>> M
Matrix([
[1, 2, 0],
[0, 3, 0],
[2, -4, 2]])
>>> (P, D) = M.diagonalize()
>>> D
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
>>> P
Matrix([
[-1, 0, -1],
[ 0, 0, -1],
[ 2, 1, 2]])
>>> P.inv() * M * P
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
See Also
========
is_diagonal
is_diagonalizable
"""
if not M.is_square:
raise NonSquareMatrixError()
is_diagonalizable, eigenvecs = _is_diagonalizable_with_eigen(M,
reals_only=reals_only)
if not is_diagonalizable:
raise MatrixError("Matrix is not diagonalizable")
if sort:
eigenvecs = sorted(eigenvecs, key=default_sort_key)
p_cols, diag = [], []
for val, mult, basis in eigenvecs:
diag += [val] * mult
p_cols += basis
if normalize:
p_cols = [v / v.norm() for v in p_cols]
return M.hstack(*p_cols), M.diag(*diag)
def _fuzzy_positive_definite(M):
positive_diagonals = M._has_positive_diagonals()
if positive_diagonals is False:
return False
if positive_diagonals and M.is_strongly_diagonally_dominant:
return True
return None
def _fuzzy_positive_semidefinite(M):
nonnegative_diagonals = M._has_nonnegative_diagonals()
if nonnegative_diagonals is False:
return False
if nonnegative_diagonals and M.is_weakly_diagonally_dominant:
return True
return None
def _is_positive_definite(M):
if not M.is_hermitian:
if not M.is_square:
return False
M = M + M.H
fuzzy = _fuzzy_positive_definite(M)
if fuzzy is not None:
return fuzzy
return _is_positive_definite_GE(M)
def _is_positive_semidefinite(M):
if not M.is_hermitian:
if not M.is_square:
return False
M = M + M.H
fuzzy = _fuzzy_positive_semidefinite(M)
if fuzzy is not None:
return fuzzy
return _is_positive_semidefinite_cholesky(M)
def _is_negative_definite(M):
return _is_positive_definite(-M)
def _is_negative_semidefinite(M):
return _is_positive_semidefinite(-M)
def _is_indefinite(M):
if M.is_hermitian:
eigen = M.eigenvals()
args1 = [x.is_positive for x in eigen.keys()]
any_positive = fuzzy_or(args1)
args2 = [x.is_negative for x in eigen.keys()]
any_negative = fuzzy_or(args2)
return fuzzy_and([any_positive, any_negative])
elif M.is_square:
return (M + M.H).is_indefinite
return False
def _is_positive_definite_GE(M):
"""A division-free gaussian elimination method for testing
positive-definiteness."""
M = M.as_mutable()
size = M.rows
for i in range(size):
is_positive = M[i, i].is_positive
if is_positive is not True:
return is_positive
for j in range(i+1, size):
M[j, i+1:] = M[i, i] * M[j, i+1:] - M[j, i] * M[i, i+1:]
return True
def _is_positive_semidefinite_cholesky(M):
"""Uses Cholesky factorization with complete pivoting
References
==========
.. [1] http://eprints.ma.man.ac.uk/1199/1/covered/MIMS_ep2008_116.pdf
.. [2] https://www.value-at-risk.net/cholesky-factorization/
"""
M = M.as_mutable()
for k in range(M.rows):
diags = [M[i, i] for i in range(k, M.rows)]
pivot, pivot_val, nonzero, _ = _find_reasonable_pivot(diags)
if nonzero:
return None
if pivot is None:
for i in range(k+1, M.rows):
for j in range(k, M.cols):
iszero = M[i, j].is_zero
if iszero is None:
return None
elif iszero is False:
return False
return True
if M[k, k].is_negative or pivot_val.is_negative:
return False
if pivot > 0:
M.col_swap(k, k+pivot)
M.row_swap(k, k+pivot)
M[k, k] = sqrt(M[k, k])
M[k, k+1:] /= M[k, k]
M[k+1:, k+1:] -= M[k, k+1:].H * M[k, k+1:]
return M[-1, -1].is_nonnegative
_doc_positive_definite = \
r"""Finds out the definiteness of a matrix.
Explanation
===========
A square real matrix $A$ is:
- A positive definite matrix if $x^T A x > 0$
for all non-zero real vectors $x$.
- A positive semidefinite matrix if $x^T A x \geq 0$
for all non-zero real vectors $x$.
- A negative definite matrix if $x^T A x < 0$
for all non-zero real vectors $x$.
- A negative semidefinite matrix if $x^T A x \leq 0$
for all non-zero real vectors $x$.
- An indefinite matrix if there exists non-zero real vectors
$x, y$ with $x^T A x > 0 > y^T A y$.
A square complex matrix $A$ is:
- A positive definite matrix if $\text{re}(x^H A x) > 0$
for all non-zero complex vectors $x$.
- A positive semidefinite matrix if $\text{re}(x^H A x) \geq 0$
for all non-zero complex vectors $x$.
- A negative definite matrix if $\text{re}(x^H A x) < 0$
for all non-zero complex vectors $x$.
- A negative semidefinite matrix if $\text{re}(x^H A x) \leq 0$
for all non-zero complex vectors $x$.
- An indefinite matrix if there exists non-zero complex vectors
$x, y$ with $\text{re}(x^H A x) > 0 > \text{re}(y^H A y)$.
A matrix need not be symmetric or hermitian to be positive definite.
- A real non-symmetric matrix is positive definite if and only if
$\frac{A + A^T}{2}$ is positive definite.
- A complex non-hermitian matrix is positive definite if and only if
$\frac{A + A^H}{2}$ is positive definite.
And this extension can apply for all the definitions above.
However, for complex cases, you can restrict the definition of
$\text{re}(x^H A x) > 0$ to $x^H A x > 0$ and require the matrix
to be hermitian.
But we do not present this restriction for computation because you
can check ``M.is_hermitian`` independently with this and use
the same procedure.
Examples
========
An example of symmetric positive definite matrix:
.. plot::
:context: reset
:format: doctest
:include-source: True
>>> from sympy import Matrix, symbols
>>> from sympy.plotting import plot3d
>>> a, b = symbols('a b')
>>> x = Matrix([a, b])
>>> A = Matrix([[1, 0], [0, 1]])
>>> A.is_positive_definite
True
>>> A.is_positive_semidefinite
True
>>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))
An example of symmetric positive semidefinite matrix:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> A = Matrix([[1, -1], [-1, 1]])
>>> A.is_positive_definite
False
>>> A.is_positive_semidefinite
True
>>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))
An example of symmetric negative definite matrix:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> A = Matrix([[-1, 0], [0, -1]])
>>> A.is_negative_definite
True
>>> A.is_negative_semidefinite
True
>>> A.is_indefinite
False
>>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))
An example of symmetric indefinite matrix:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> A = Matrix([[1, 2], [2, -1]])
>>> A.is_indefinite
True
>>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))
An example of non-symmetric positive definite matrix.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> A = Matrix([[1, 2], [-2, 1]])
>>> A.is_positive_definite
True
>>> A.is_positive_semidefinite
True
>>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))
Notes
=====
Although some people trivialize the definition of positive definite
matrices only for symmetric or hermitian matrices, this restriction
is not correct because it does not classify all instances of
positive definite matrices from the definition $x^T A x > 0$ or
$\text{re}(x^H A x) > 0$.
For instance, ``Matrix([[1, 2], [-2, 1]])`` presented in
the example above is an example of real positive definite matrix
that is not symmetric.
However, since the following formula holds true;
.. math::
\text{re}(x^H A x) > 0 \iff
\text{re}(x^H \frac{A + A^H}{2} x) > 0
We can classify all positive definite matrices that may or may not
be symmetric or hermitian by transforming the matrix to
$\frac{A + A^T}{2}$ or $\frac{A + A^H}{2}$
(which is guaranteed to be always real symmetric or complex
hermitian) and we can defer most of the studies to symmetric or
hermitian positive definite matrices.
But it is a different problem for the existance of Cholesky
decomposition. Because even though a non symmetric or a non
hermitian matrix can be positive definite, Cholesky or LDL
decomposition does not exist because the decompositions require the
matrix to be symmetric or hermitian.
References
==========
.. [1] https://en.wikipedia.org/wiki/Definiteness_of_a_matrix#Eigenvalues
.. [2] http://mathworld.wolfram.com/PositiveDefiniteMatrix.html
.. [3] Johnson, C. R. "Positive Definite Matrices." Amer.
Math. Monthly 77, 259-264 1970.
"""
_is_positive_definite.__doc__ = _doc_positive_definite
_is_positive_semidefinite.__doc__ = _doc_positive_definite
_is_negative_definite.__doc__ = _doc_positive_definite
_is_negative_semidefinite.__doc__ = _doc_positive_definite
_is_indefinite.__doc__ = _doc_positive_definite
def _jordan_form(M, calc_transform=True, *, chop=False):
"""Return $(P, J)$ where $J$ is a Jordan block
matrix and $P$ is a matrix such that $M = P J P^{-1}$
Parameters
==========
calc_transform : bool
If ``False``, then only $J$ is returned.
chop : bool
All matrices are converted to exact types when computing
eigenvalues and eigenvectors. As a result, there may be
approximation errors. If ``chop==True``, these errors
will be truncated.
Examples
========
>>> from sympy.matrices import Matrix
>>> M = Matrix([[ 6, 5, -2, -3], [-3, -1, 3, 3], [ 2, 1, -2, -3], [-1, 1, 5, 5]])
>>> P, J = M.jordan_form()
>>> J
Matrix([
[2, 1, 0, 0],
[0, 2, 0, 0],
[0, 0, 2, 1],
[0, 0, 0, 2]])
See Also
========
jordan_block
"""
if not M.is_square:
raise NonSquareMatrixError("Only square matrices have Jordan forms")
mat = M
has_floats = M.has(Float)
if has_floats:
try:
max_prec = max(term._prec for term in M._mat if isinstance(term, Float))
except ValueError:
# if no term in the matrix is explicitly a Float calling max()
# will throw a error so setting max_prec to default value of 53
max_prec = 53
# setting minimum max_dps to 15 to prevent loss of precision in
# matrix containing non evaluated expressions
max_dps = max(prec_to_dps(max_prec), 15)
def restore_floats(*args):
"""If ``has_floats`` is `True`, cast all ``args`` as
matrices of floats."""
if has_floats:
args = [m.evalf(n=max_dps, chop=chop) for m in args]
if len(args) == 1:
return args[0]
return args
# cache calculations for some speedup
mat_cache = {}
def eig_mat(val, pow):
"""Cache computations of ``(M - val*I)**pow`` for quick
retrieval"""
if (val, pow) in mat_cache:
return mat_cache[(val, pow)]
if (val, pow - 1) in mat_cache:
mat_cache[(val, pow)] = mat_cache[(val, pow - 1)].multiply(
mat_cache[(val, 1)], dotprodsimp=None)
else:
mat_cache[(val, pow)] = (mat - val*M.eye(M.rows)).pow(pow)
return mat_cache[(val, pow)]
# helper functions
def nullity_chain(val, algebraic_multiplicity):
"""Calculate the sequence [0, nullity(E), nullity(E**2), ...]
until it is constant where ``E = M - val*I``"""
# mat.rank() is faster than computing the null space,
# so use the rank-nullity theorem
cols = M.cols
ret = [0]
nullity = cols - eig_mat(val, 1).rank()
i = 2
while nullity != ret[-1]:
ret.append(nullity)
if nullity == algebraic_multiplicity:
break
nullity = cols - eig_mat(val, i).rank()
i += 1
# Due to issues like #7146 and #15872, SymPy sometimes
# gives the wrong rank. In this case, raise an error
# instead of returning an incorrect matrix
if nullity < ret[-1] or nullity > algebraic_multiplicity:
raise MatrixError(
"SymPy had encountered an inconsistent "
"result while computing Jordan block: "
"{}".format(M))
return ret
def blocks_from_nullity_chain(d):
"""Return a list of the size of each Jordan block.
If d_n is the nullity of E**n, then the number
of Jordan blocks of size n is
2*d_n - d_(n-1) - d_(n+1)"""
# d[0] is always the number of columns, so skip past it
mid = [2*d[n] - d[n - 1] - d[n + 1] for n in range(1, len(d) - 1)]
# d is assumed to plateau with "d[ len(d) ] == d[-1]", so
# 2*d_n - d_(n-1) - d_(n+1) == d_n - d_(n-1)
end = [d[-1] - d[-2]] if len(d) > 1 else [d[0]]
return mid + end
def pick_vec(small_basis, big_basis):
"""Picks a vector from big_basis that isn't in
the subspace spanned by small_basis"""
if len(small_basis) == 0:
return big_basis[0]
for v in big_basis:
_, pivots = M.hstack(*(small_basis + [v])).echelon_form(
with_pivots=True)
if pivots[-1] == len(small_basis):
return v
# roots doesn't like Floats, so replace them with Rationals
if has_floats:
mat = mat.applyfunc(lambda x: nsimplify(x, rational=True))
# first calculate the jordan block structure
eigs = mat.eigenvals()
# Make sure that we have all roots in radical form
for x in eigs:
if x.has(CRootOf):
raise MatrixError(
"Jordan normal form is not implemented if the matrix have "
"eigenvalues in CRootOf form")
# most matrices have distinct eigenvalues
# and so are diagonalizable. In this case, don't
# do extra work!
if len(eigs.keys()) == mat.cols:
blocks = list(sorted(eigs.keys(), key=default_sort_key))
jordan_mat = mat.diag(*blocks)
if not calc_transform:
return restore_floats(jordan_mat)
jordan_basis = [eig_mat(eig, 1).nullspace()[0]
for eig in blocks]
basis_mat = mat.hstack(*jordan_basis)
return restore_floats(basis_mat, jordan_mat)
block_structure = []
for eig in sorted(eigs.keys(), key=default_sort_key):
algebraic_multiplicity = eigs[eig]
chain = nullity_chain(eig, algebraic_multiplicity)
block_sizes = blocks_from_nullity_chain(chain)
# if block_sizes = = [a, b, c, ...], then the number of
# Jordan blocks of size 1 is a, of size 2 is b, etc.
# create an array that has (eig, block_size) with one
# entry for each block
size_nums = [(i+1, num) for i, num in enumerate(block_sizes)]
# we expect larger Jordan blocks to come earlier
size_nums.reverse()
block_structure.extend(
(eig, size) for size, num in size_nums for _ in range(num))
jordan_form_size = sum(size for eig, size in block_structure)
if jordan_form_size != M.rows:
raise MatrixError(
"SymPy had encountered an inconsistent result while "
"computing Jordan block. : {}".format(M))
blocks = (mat.jordan_block(size=size, eigenvalue=eig) for eig, size in block_structure)
jordan_mat = mat.diag(*blocks)
if not calc_transform:
return restore_floats(jordan_mat)
# For each generalized eigenspace, calculate a basis.
# We start by looking for a vector in null( (A - eig*I)**n )
# which isn't in null( (A - eig*I)**(n-1) ) where n is
# the size of the Jordan block
#
# Ideally we'd just loop through block_structure and
# compute each generalized eigenspace. However, this
# causes a lot of unneeded computation. Instead, we
# go through the eigenvalues separately, since we know
# their generalized eigenspaces must have bases that
# are linearly independent.
jordan_basis = []
for eig in sorted(eigs.keys(), key=default_sort_key):
eig_basis = []
for block_eig, size in block_structure:
if block_eig != eig:
continue
null_big = (eig_mat(eig, size)).nullspace()
null_small = (eig_mat(eig, size - 1)).nullspace()
# we want to pick something that is in the big basis
# and not the small, but also something that is independent
# of any other generalized eigenvectors from a different
# generalized eigenspace sharing the same eigenvalue.
vec = pick_vec(null_small + eig_basis, null_big)
new_vecs = [eig_mat(eig, i).multiply(vec, dotprodsimp=None)
for i in range(size)]
eig_basis.extend(new_vecs)
jordan_basis.extend(reversed(new_vecs))
basis_mat = mat.hstack(*jordan_basis)
return restore_floats(basis_mat, jordan_mat)
def _left_eigenvects(M, **flags):
"""Returns left eigenvectors and eigenvalues.
This function returns the list of triples (eigenval, multiplicity,
basis) for the left eigenvectors. Options are the same as for
eigenvects(), i.e. the ``**flags`` arguments gets passed directly to
eigenvects().
Examples
========
>>> from sympy.matrices import Matrix
>>> M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]])
>>> M.eigenvects()
[(-1, 1, [Matrix([
[-1],
[ 1],
[ 0]])]), (0, 1, [Matrix([
[ 0],
[-1],
[ 1]])]), (2, 1, [Matrix([
[2/3],
[1/3],
[ 1]])])]
>>> M.left_eigenvects()
[(-1, 1, [Matrix([[-2, 1, 1]])]), (0, 1, [Matrix([[-1, -1, 1]])]), (2,
1, [Matrix([[1, 1, 1]])])]
"""
eigs = M.transpose().eigenvects(**flags)
return [(val, mult, [l.transpose() for l in basis]) for val, mult, basis in eigs]
def _singular_values(M):
"""Compute the singular values of a Matrix
Examples
========
>>> from sympy import Matrix, Symbol
>>> x = Symbol('x', real=True)
>>> M = Matrix([[0, 1, 0], [0, x, 0], [-1, 0, 0]])
>>> M.singular_values()
[sqrt(x**2 + 1), 1, 0]
See Also
========
condition_number
"""
if M.rows >= M.cols:
valmultpairs = M.H.multiply(M).eigenvals()
else:
valmultpairs = M.multiply(M.H).eigenvals()
# Expands result from eigenvals into a simple list
vals = []
for k, v in valmultpairs.items():
vals += [sqrt(k)] * v # dangerous! same k in several spots!
# Pad with zeros if singular values are computed in reverse way,
# to give consistent format.
if len(vals) < M.cols:
vals += [M.zero] * (M.cols - len(vals))
# sort them in descending order
vals.sort(reverse=True, key=default_sort_key)
return vals
|
416fbfccc2d2c67e03e2855a24f5b8584dd47cf76d61249e0b46c15829e85c4d | from sympy import (symbols, pi, oo, S, exp, sqrt, besselk, Indexed, Sum, simplify,
Rational, factorial, gamma, Piecewise, Eq, Product, Interval,
IndexedBase, RisingFactorial, polar_lift, ProductSet, Range)
from sympy.core.numbers import comp
from sympy.integrals.integrals import integrate
from sympy.matrices import Matrix, MatrixSymbol
from sympy.stats import density, median, marginal_distribution, Normal, Laplace, E, sample
from sympy.stats.joint_rv_types import (JointRV, MultivariateNormalDistribution,
JointDistributionHandmade, MultivariateT, NormalGamma,
GeneralizedMultivariateLogGammaOmega as GMVLGO, MultivariateBeta,
GeneralizedMultivariateLogGamma as GMVLG, MultivariateEwens,
Multinomial, NegativeMultinomial, MultivariateNormal,
MultivariateLaplace)
from sympy.testing.pytest import raises, XFAIL, ignore_warnings, skip
from sympy.external import import_module
x, y, z, a, b = symbols('x y z a b')
def test_Normal():
m = Normal('A', [1, 2], [[1, 0], [0, 1]])
A = MultivariateNormal('A', [1, 2], [[1, 0], [0, 1]])
assert m == A
assert density(m)(1, 2) == 1/(2*pi)
assert m.pspace.distribution.set == ProductSet(S.Reals, S.Reals)
raises (ValueError, lambda:m[2])
raises (ValueError,\
lambda: Normal('M',[1, 2], [[0, 0], [0, 1]]))
n = Normal('B', [1, 2, 3], [[1, 0, 0], [0, 1, 0], [0, 0, 1]])
p = Normal('C', Matrix([1, 2]), Matrix([[1, 0], [0, 1]]))
assert density(m)(x, y) == density(p)(x, y)
assert marginal_distribution(n, 0, 1)(1, 2) == 1/(2*pi)
raises(ValueError, lambda: marginal_distribution(m))
assert integrate(density(m)(x, y), (x, -oo, oo), (y, -oo, oo)).evalf() == 1
N = Normal('N', [1, 2], [[x, 0], [0, y]])
assert density(N)(0, 0) == exp(-((4*x + y)/(2*x*y)))/(2*pi*sqrt(x*y))
raises (ValueError, lambda: Normal('M', [1, 2], [[1, 1], [1, -1]]))
# symbolic
n = symbols('n', natural=True)
mu = MatrixSymbol('mu', n, 1)
sigma = MatrixSymbol('sigma', n, n)
X = Normal('X', mu, sigma)
assert density(X) == MultivariateNormalDistribution(mu, sigma)
raises (NotImplementedError, lambda: median(m))
# Below tests should work after issue #17267 is resolved
# assert E(X) == mu
# assert variance(X) == sigma
def test_MultivariateTDist():
t1 = MultivariateT('T', [0, 0], [[1, 0], [0, 1]], 2)
assert(density(t1))(1, 1) == 1/(8*pi)
assert t1.pspace.distribution.set == ProductSet(S.Reals, S.Reals)
assert integrate(density(t1)(x, y), (x, -oo, oo), \
(y, -oo, oo)).evalf() == 1
raises(ValueError, lambda: MultivariateT('T', [1, 2], [[1, 1], [1, -1]], 1))
t2 = MultivariateT('t2', [1, 2], [[x, 0], [0, y]], 1)
assert density(t2)(1, 2) == 1/(2*pi*sqrt(x*y))
def test_multivariate_laplace():
raises(ValueError, lambda: Laplace('T', [1, 2], [[1, 2], [2, 1]]))
L = Laplace('L', [1, 0], [[1, 0], [0, 1]])
L2 = MultivariateLaplace('L2', [1, 0], [[1, 0], [0, 1]])
assert density(L)(2, 3) == exp(2)*besselk(0, sqrt(39))/pi
L1 = Laplace('L1', [1, 2], [[x, 0], [0, y]])
assert density(L1)(0, 1) == \
exp(2/y)*besselk(0, sqrt((2 + 4/y + 1/x)/y))/(pi*sqrt(x*y))
assert L.pspace.distribution.set == ProductSet(S.Reals, S.Reals)
assert L.pspace.distribution == L2.pspace.distribution
def test_NormalGamma():
ng = NormalGamma('G', 1, 2, 3, 4)
assert density(ng)(1, 1) == 32*exp(-4)/sqrt(pi)
assert ng.pspace.distribution.set == ProductSet(S.Reals, Interval(0, oo))
raises(ValueError, lambda:NormalGamma('G', 1, 2, 3, -1))
assert marginal_distribution(ng, 0)(1) == \
3*sqrt(10)*gamma(Rational(7, 4))/(10*sqrt(pi)*gamma(Rational(5, 4)))
assert marginal_distribution(ng, y)(1) == exp(Rational(-1, 4))/128
assert marginal_distribution(ng,[0,1])(x) == x**2*exp(-x/4)/128
def test_GeneralizedMultivariateLogGammaDistribution():
h = S.Half
omega = Matrix([[1, h, h, h],
[h, 1, h, h],
[h, h, 1, h],
[h, h, h, 1]])
v, l, mu = (4, [1, 2, 3, 4], [1, 2, 3, 4])
y_1, y_2, y_3, y_4 = symbols('y_1:5', real=True)
delta = symbols('d', positive=True)
G = GMVLGO('G', omega, v, l, mu)
Gd = GMVLG('Gd', delta, v, l, mu)
dend = ("d**4*Sum(4*24**(-n - 4)*(1 - d)**n*exp((n + 4)*(y_1 + 2*y_2 + 3*y_3 "
"+ 4*y_4) - exp(y_1) - exp(2*y_2)/2 - exp(3*y_3)/3 - exp(4*y_4)/4)/"
"(gamma(n + 1)*gamma(n + 4)**3), (n, 0, oo))")
assert str(density(Gd)(y_1, y_2, y_3, y_4)) == dend
den = ("5*2**(2/3)*5**(1/3)*Sum(4*24**(-n - 4)*(-2**(2/3)*5**(1/3)/4 + 1)**n*"
"exp((n + 4)*(y_1 + 2*y_2 + 3*y_3 + 4*y_4) - exp(y_1) - exp(2*y_2)/2 - "
"exp(3*y_3)/3 - exp(4*y_4)/4)/(gamma(n + 1)*gamma(n + 4)**3), (n, 0, oo))/64")
assert str(density(G)(y_1, y_2, y_3, y_4)) == den
marg = ("5*2**(2/3)*5**(1/3)*exp(4*y_1)*exp(-exp(y_1))*Integral(exp(-exp(4*G[3])"
"/4)*exp(16*G[3])*Integral(exp(-exp(3*G[2])/3)*exp(12*G[2])*Integral(exp("
"-exp(2*G[1])/2)*exp(8*G[1])*Sum((-1/4)**n*(-4 + 2**(2/3)*5**(1/3"
"))**n*exp(n*y_1)*exp(2*n*G[1])*exp(3*n*G[2])*exp(4*n*G[3])/(24**n*gamma(n + 1)"
"*gamma(n + 4)**3), (n, 0, oo)), (G[1], -oo, oo)), (G[2], -oo, oo)), (G[3]"
", -oo, oo))/5308416")
assert str(marginal_distribution(G, G[0])(y_1)) == marg
omega_f1 = Matrix([[1, h, h]])
omega_f2 = Matrix([[1, h, h, h],
[h, 1, 2, h],
[h, h, 1, h],
[h, h, h, 1]])
omega_f3 = Matrix([[6, h, h, h],
[h, 1, 2, h],
[h, h, 1, h],
[h, h, h, 1]])
v_f = symbols("v_f", positive=False, real=True)
l_f = [1, 2, v_f, 4]
m_f = [v_f, 2, 3, 4]
omega_f4 = Matrix([[1, h, h, h, h],
[h, 1, h, h, h],
[h, h, 1, h, h],
[h, h, h, 1, h],
[h, h, h, h, 1]])
l_f1 = [1, 2, 3, 4, 5]
omega_f5 = Matrix([[1]])
mu_f5 = l_f5 = [1]
raises(ValueError, lambda: GMVLGO('G', omega_f1, v, l, mu))
raises(ValueError, lambda: GMVLGO('G', omega_f2, v, l, mu))
raises(ValueError, lambda: GMVLGO('G', omega_f3, v, l, mu))
raises(ValueError, lambda: GMVLGO('G', omega, v_f, l, mu))
raises(ValueError, lambda: GMVLGO('G', omega, v, l_f, mu))
raises(ValueError, lambda: GMVLGO('G', omega, v, l, m_f))
raises(ValueError, lambda: GMVLGO('G', omega_f4, v, l, mu))
raises(ValueError, lambda: GMVLGO('G', omega, v, l_f1, mu))
raises(ValueError, lambda: GMVLGO('G', omega_f5, v, l_f5, mu_f5))
raises(ValueError, lambda: GMVLG('G', Rational(3, 2), v, l, mu))
def test_MultivariateBeta():
a1, a2 = symbols('a1, a2', positive=True)
a1_f, a2_f = symbols('a1, a2', positive=False, real=True)
mb = MultivariateBeta('B', [a1, a2])
mb_c = MultivariateBeta('C', a1, a2)
assert density(mb)(1, 2) == S(2)**(a2 - 1)*gamma(a1 + a2)/\
(gamma(a1)*gamma(a2))
assert marginal_distribution(mb_c, 0)(3) == S(3)**(a1 - 1)*gamma(a1 + a2)/\
(a2*gamma(a1)*gamma(a2))
raises(ValueError, lambda: MultivariateBeta('b1', [a1_f, a2]))
raises(ValueError, lambda: MultivariateBeta('b2', [a1, a2_f]))
raises(ValueError, lambda: MultivariateBeta('b3', [0, 0]))
raises(ValueError, lambda: MultivariateBeta('b4', [a1_f, a2_f]))
assert mb.pspace.distribution.set == ProductSet(Interval(0, 1), Interval(0, 1))
def test_MultivariateEwens():
n, theta, i = symbols('n theta i', positive=True)
# tests for integer dimensions
theta_f = symbols('t_f', negative=True)
a = symbols('a_1:4', positive = True, integer = True)
ed = MultivariateEwens('E', 3, theta)
assert density(ed)(a[0], a[1], a[2]) == Piecewise((6*2**(-a[1])*3**(-a[2])*
theta**a[0]*theta**a[1]*theta**a[2]/
(theta*(theta + 1)*(theta + 2)*
factorial(a[0])*factorial(a[1])*
factorial(a[2])), Eq(a[0] + 2*a[1] +
3*a[2], 3)), (0, True))
assert marginal_distribution(ed, ed[1])(a[1]) == Piecewise((6*2**(-a[1])*
theta**a[1]/((theta + 1)*
(theta + 2)*factorial(a[1])),
Eq(2*a[1] + 1, 3)), (0, True))
raises(ValueError, lambda: MultivariateEwens('e1', 5, theta_f))
assert ed.pspace.distribution.set == ProductSet(Range(0, 4, 1),
Range(0, 2, 1), Range(0, 2, 1))
# tests for symbolic dimensions
eds = MultivariateEwens('E', n, theta)
a = IndexedBase('a')
j, k = symbols('j, k')
den = Piecewise((factorial(n)*Product(theta**a[j]*(j + 1)**(-a[j])/
factorial(a[j]), (j, 0, n - 1))/RisingFactorial(theta, n),
Eq(n, Sum((k + 1)*a[k], (k, 0, n - 1)))), (0, True))
assert density(eds)(a).dummy_eq(den)
def test_Multinomial():
n, x1, x2, x3, x4 = symbols('n, x1, x2, x3, x4', nonnegative=True, integer=True)
p1, p2, p3, p4 = symbols('p1, p2, p3, p4', positive=True)
p1_f, n_f = symbols('p1_f, n_f', negative=True)
M = Multinomial('M', n, [p1, p2, p3, p4])
C = Multinomial('C', 3, p1, p2, p3)
f = factorial
assert density(M)(x1, x2, x3, x4) == Piecewise((p1**x1*p2**x2*p3**x3*p4**x4*
f(n)/(f(x1)*f(x2)*f(x3)*f(x4)),
Eq(n, x1 + x2 + x3 + x4)), (0, True))
assert marginal_distribution(C, C[0])(x1).subs(x1, 1) ==\
3*p1*p2**2 +\
6*p1*p2*p3 +\
3*p1*p3**2
raises(ValueError, lambda: Multinomial('b1', 5, [p1, p2, p3, p1_f]))
raises(ValueError, lambda: Multinomial('b2', n_f, [p1, p2, p3, p4]))
raises(ValueError, lambda: Multinomial('b3', n, 0.5, 0.4, 0.3, 0.1))
def test_NegativeMultinomial():
k0, x1, x2, x3, x4 = symbols('k0, x1, x2, x3, x4', nonnegative=True, integer=True)
p1, p2, p3, p4 = symbols('p1, p2, p3, p4', positive=True)
p1_f = symbols('p1_f', negative=True)
N = NegativeMultinomial('N', 4, [p1, p2, p3, p4])
C = NegativeMultinomial('C', 4, 0.1, 0.2, 0.3)
g = gamma
f = factorial
assert simplify(density(N)(x1, x2, x3, x4) -
p1**x1*p2**x2*p3**x3*p4**x4*(-p1 - p2 - p3 - p4 + 1)**4*g(x1 + x2 +
x3 + x4 + 4)/(6*f(x1)*f(x2)*f(x3)*f(x4))) is S.Zero
assert comp(marginal_distribution(C, C[0])(1).evalf(), 0.33, .01)
raises(ValueError, lambda: NegativeMultinomial('b1', 5, [p1, p2, p3, p1_f]))
raises(ValueError, lambda: NegativeMultinomial('b2', k0, 0.5, 0.4, 0.3, 0.4))
assert N.pspace.distribution.set == ProductSet(Range(0, oo, 1),
Range(0, oo, 1), Range(0, oo, 1), Range(0, oo, 1))
def test_JointPSpace_marginal_distribution():
T = MultivariateT('T', [0, 0], [[1, 0], [0, 1]], 2)
assert marginal_distribution(T, T[1])(x) == sqrt(2)*(x**2 + 2)/(
8*polar_lift(x**2/2 + 1)**Rational(5, 2))
assert integrate(marginal_distribution(T, 1)(x), (x, -oo, oo)) == 1
t = MultivariateT('T', [0, 0, 0], [[1, 0, 0], [0, 1, 0], [0, 0, 1]], 3)
assert comp(marginal_distribution(t, 0)(1).evalf(), 0.2, .01)
def test_JointRV():
x1, x2 = (Indexed('x', i) for i in (1, 2))
pdf = exp(-x1**2/2 + x1 - x2**2/2 - S.Half)/(2*pi)
X = JointRV('x', pdf)
assert density(X)(1, 2) == exp(-2)/(2*pi)
assert isinstance(X.pspace.distribution, JointDistributionHandmade)
assert marginal_distribution(X, 0)(2) == sqrt(2)*exp(Rational(-1, 2))/(2*sqrt(pi))
def test_expectation():
m = Normal('A', [x, y], [[1, 0], [0, 1]])
assert simplify(E(m[1])) == y
@XFAIL
def test_joint_vector_expectation():
m = Normal('A', [x, y], [[1, 0], [0, 1]])
assert E(m) == (x, y)
def test_sample_numpy():
distribs_numpy = [
MultivariateNormal("M", [3, 4], [[2, 1], [1, 2]]),
MultivariateBeta("B", [0.4, 5, 15, 50, 203]),
Multinomial("N", 50, [0.3, 0.2, 0.1, 0.25, 0.15])
]
size = 3
numpy = import_module('numpy')
if not numpy:
skip('Numpy is not installed. Abort tests for _sample_numpy.')
else:
with ignore_warnings(UserWarning):
for X in distribs_numpy:
samps = next(sample(X, size=size, library='numpy'))
for sam in samps:
assert tuple(sam) in X.pspace.distribution.set
N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1)
raises(NotImplementedError, lambda: next(sample(N_c, library='numpy')))
def test_sample_scipy():
distribs_scipy = [
MultivariateNormal("M", [0, 0], [[0.1, 0.025], [0.025, 0.1]]),
MultivariateBeta("B", [0.4, 5, 15]),
Multinomial("N", 8, [0.3, 0.2, 0.1, 0.4])
]
size = 3
scipy = import_module('scipy')
if not scipy:
skip('Scipy not installed. Abort tests for _sample_scipy.')
else:
with ignore_warnings(UserWarning):
for X in distribs_scipy:
samps = next(sample(X, size=size))
samps2 = next(sample(X, size=(2, 2)))
for sam in samps:
assert tuple(sam) in X.pspace.distribution.set
for i in range(2):
for j in range(2):
assert tuple(samps2[i][j]) in X.pspace.distribution.set
N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1)
raises(NotImplementedError, lambda: next(sample(N_c)))
def test_sample_pymc3():
distribs_pymc3 = [
MultivariateNormal("M", [5, 2], [[1, 0], [0, 1]]),
MultivariateBeta("B", [0.4, 5, 15]),
Multinomial("N", 4, [0.3, 0.2, 0.1, 0.4])
]
size = 3
pymc3 = import_module('pymc3')
if not pymc3:
skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
else:
with ignore_warnings(UserWarning):
for X in distribs_pymc3:
samps = next(sample(X, size=size, library='pymc3'))
for sam in samps:
assert tuple(sam.flatten()) in X.pspace.distribution.set
N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1)
raises(NotImplementedError, lambda: next(sample(N_c, library='pymc3')))
def test_sample_seed():
x1, x2 = (Indexed('x', i) for i in (1, 2))
pdf = exp(-x1**2/2 + x1 - x2**2/2 - S.Half)/(2*pi)
X = JointRV('x', pdf)
libraries = ['scipy', 'numpy', 'pymc3']
for lib in libraries:
try:
imported_lib = import_module(lib)
if imported_lib:
s0, s1, s2 = [], [], []
s0 = list(sample(X, numsamples=10, library=lib, seed=0))
s1 = list(sample(X, numsamples=10, library=lib, seed=0))
s2 = list(sample(X, numsamples=10, library=lib, seed=1))
assert s0 == s1
assert s1 != s2
except NotImplementedError:
continue
|
fd7ce47533e3dcc9609ebe4134046fb4ecbe03fed8cbe6771274e2b0815467a2 | from sympy import Mul, S, Pow, Symbol, summation, Dict, factorial as fac
from sympy.core.evalf import bitcount
from sympy.core.numbers import Integer, Rational
from sympy.ntheory import (totient,
factorint, primefactors, divisors, nextprime,
primerange, pollard_rho, perfect_power, multiplicity, multiplicity_in_factorial,
trailing, divisor_count, primorial, pollard_pm1, divisor_sigma,
factorrat, reduced_totient)
from sympy.ntheory.factor_ import (smoothness, smoothness_p, proper_divisors,
antidivisors, antidivisor_count, core, udivisors, udivisor_sigma,
udivisor_count, proper_divisor_count, primenu, primeomega, small_trailing,
mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant,
is_deficient, is_amicable, dra, drm)
from sympy.testing.pytest import raises
from sympy.utilities.iterables import capture
def fac_multiplicity(n, p):
"""Return the power of the prime number p in the
factorization of n!"""
if p > n:
return 0
if p > n//2:
return 1
q, m = n, 0
while q >= p:
q //= p
m += q
return m
def multiproduct(seq=(), start=1):
"""
Return the product of a sequence of factors with multiplicities,
times the value of the parameter ``start``. The input may be a
sequence of (factor, exponent) pairs or a dict of such pairs.
>>> multiproduct({3:7, 2:5}, 4) # = 3**7 * 2**5 * 4
279936
"""
if not seq:
return start
if isinstance(seq, dict):
seq = iter(seq.items())
units = start
multi = []
for base, exp in seq:
if not exp:
continue
elif exp == 1:
units *= base
else:
if exp % 2:
units *= base
multi.append((base, exp//2))
return units * multiproduct(multi)**2
def test_trailing_bitcount():
assert trailing(0) == 0
assert trailing(1) == 0
assert trailing(-1) == 0
assert trailing(2) == 1
assert trailing(7) == 0
assert trailing(-7) == 0
for i in range(100):
assert trailing(1 << i) == i
assert trailing((1 << i) * 31337) == i
assert trailing(1 << 1000001) == 1000001
assert trailing((1 << 273956)*7**37) == 273956
# issue 12709
big = small_trailing[-1]*2
assert trailing(-big) == trailing(big)
assert bitcount(-big) == bitcount(big)
def test_multiplicity():
for b in range(2, 20):
for i in range(100):
assert multiplicity(b, b**i) == i
assert multiplicity(b, (b**i) * 23) == i
assert multiplicity(b, (b**i) * 1000249) == i
# Should be fast
assert multiplicity(10, 10**10023) == 10023
# Should exit quickly
assert multiplicity(10**10, 10**10) == 1
# Should raise errors for bad input
raises(ValueError, lambda: multiplicity(1, 1))
raises(ValueError, lambda: multiplicity(1, 2))
raises(ValueError, lambda: multiplicity(1.3, 2))
raises(ValueError, lambda: multiplicity(2, 0))
raises(ValueError, lambda: multiplicity(1.3, 0))
# handles Rationals
assert multiplicity(10, Rational(30, 7)) == 1
assert multiplicity(Rational(2, 7), Rational(4, 7)) == 1
assert multiplicity(Rational(1, 7), Rational(3, 49)) == 2
assert multiplicity(Rational(2, 7), Rational(7, 2)) == -1
assert multiplicity(3, Rational(1, 9)) == -2
def test_multiplicity_in_factorial():
n = fac(1000)
for i in (2, 4, 6, 12, 30, 36, 48, 60, 72, 96):
assert multiplicity(i, n) == multiplicity_in_factorial(i, 1000)
def test_perfect_power():
raises(ValueError, lambda: perfect_power(0))
raises(ValueError, lambda: perfect_power(Rational(25, 4)))
assert perfect_power(1) is False
assert perfect_power(2) is False
assert perfect_power(3) is False
assert perfect_power(4) == (2, 2)
assert perfect_power(14) is False
assert perfect_power(25) == (5, 2)
assert perfect_power(22) is False
assert perfect_power(22, [2]) is False
assert perfect_power(137**(3*5*13)) == (137, 3*5*13)
assert perfect_power(137**(3*5*13) + 1) is False
assert perfect_power(137**(3*5*13) - 1) is False
assert perfect_power(103005006004**7) == (103005006004, 7)
assert perfect_power(103005006004**7 + 1) is False
assert perfect_power(103005006004**7 - 1) is False
assert perfect_power(103005006004**12) == (103005006004, 12)
assert perfect_power(103005006004**12 + 1) is False
assert perfect_power(103005006004**12 - 1) is False
assert perfect_power(2**10007) == (2, 10007)
assert perfect_power(2**10007 + 1) is False
assert perfect_power(2**10007 - 1) is False
assert perfect_power((9**99 + 1)**60) == (9**99 + 1, 60)
assert perfect_power((9**99 + 1)**60 + 1) is False
assert perfect_power((9**99 + 1)**60 - 1) is False
assert perfect_power((10**40000)**2, big=False) == (10**40000, 2)
assert perfect_power(10**100000) == (10, 100000)
assert perfect_power(10**100001) == (10, 100001)
assert perfect_power(13**4, [3, 5]) is False
assert perfect_power(3**4, [3, 10], factor=0) is False
assert perfect_power(3**3*5**3) == (15, 3)
assert perfect_power(2**3*5**5) is False
assert perfect_power(2*13**4) is False
assert perfect_power(2**5*3**3) is False
t = 2**24
for d in divisors(24):
m = perfect_power(t*3**d)
assert m and m[1] == d or d == 1
m = perfect_power(t*3**d, big=False)
assert m and m[1] == 2 or d == 1 or d == 3, (d, m)
def test_factorint():
assert primefactors(123456) == [2, 3, 643]
assert factorint(0) == {0: 1}
assert factorint(1) == {}
assert factorint(-1) == {-1: 1}
assert factorint(-2) == {-1: 1, 2: 1}
assert factorint(-16) == {-1: 1, 2: 4}
assert factorint(2) == {2: 1}
assert factorint(126) == {2: 1, 3: 2, 7: 1}
assert factorint(123456) == {2: 6, 3: 1, 643: 1}
assert factorint(5951757) == {3: 1, 7: 1, 29: 2, 337: 1}
assert factorint(64015937) == {7993: 1, 8009: 1}
assert factorint(2**(2**6) + 1) == {274177: 1, 67280421310721: 1}
#issue 19683
assert factorint(10**38 - 1) == {3: 2, 11: 1, 909090909090909091: 1, 1111111111111111111: 1}
#issue 17676
assert factorint(28300421052393658575) == {3: 1, 5: 2, 11: 2, 43: 1, 2063: 2, 4127: 1, 4129: 1}
assert factorint(2063**2 * 4127**1 * 4129**1) == {2063: 2, 4127: 1, 4129: 1}
assert factorint(2347**2 * 7039**1 * 7043**1) == {2347: 2, 7039: 1, 7043: 1}
assert factorint(0, multiple=True) == [0]
assert factorint(1, multiple=True) == []
assert factorint(-1, multiple=True) == [-1]
assert factorint(-2, multiple=True) == [-1, 2]
assert factorint(-16, multiple=True) == [-1, 2, 2, 2, 2]
assert factorint(2, multiple=True) == [2]
assert factorint(24, multiple=True) == [2, 2, 2, 3]
assert factorint(126, multiple=True) == [2, 3, 3, 7]
assert factorint(123456, multiple=True) == [2, 2, 2, 2, 2, 2, 3, 643]
assert factorint(5951757, multiple=True) == [3, 7, 29, 29, 337]
assert factorint(64015937, multiple=True) == [7993, 8009]
assert factorint(2**(2**6) + 1, multiple=True) == [274177, 67280421310721]
assert factorint(fac(1, evaluate=False)) == {}
assert factorint(fac(7, evaluate=False)) == {2: 4, 3: 2, 5: 1, 7: 1}
assert factorint(fac(15, evaluate=False)) == \
{2: 11, 3: 6, 5: 3, 7: 2, 11: 1, 13: 1}
assert factorint(fac(20, evaluate=False)) == \
{2: 18, 3: 8, 5: 4, 7: 2, 11: 1, 13: 1, 17: 1, 19: 1}
assert factorint(fac(23, evaluate=False)) == \
{2: 19, 3: 9, 5: 4, 7: 3, 11: 2, 13: 1, 17: 1, 19: 1, 23: 1}
assert multiproduct(factorint(fac(200))) == fac(200)
assert multiproduct(factorint(fac(200, evaluate=False))) == fac(200)
for b, e in factorint(fac(150)).items():
assert e == fac_multiplicity(150, b)
for b, e in factorint(fac(150, evaluate=False)).items():
assert e == fac_multiplicity(150, b)
assert factorint(103005006059**7) == {103005006059: 7}
assert factorint(31337**191) == {31337: 191}
assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \
{2: 1000, 3: 500, 257: 127, 383: 60}
assert len(factorint(fac(10000))) == 1229
assert len(factorint(fac(10000, evaluate=False))) == 1229
assert factorint(12932983746293756928584532764589230) == \
{2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1}
assert factorint(727719592270351) == {727719592270351: 1}
assert factorint(2**64 + 1, use_trial=False) == factorint(2**64 + 1)
for n in range(60000):
assert multiproduct(factorint(n)) == n
assert pollard_rho(2**64 + 1, seed=1) == 274177
assert pollard_rho(19, seed=1) is None
assert factorint(3, limit=2) == {3: 1}
assert factorint(12345) == {3: 1, 5: 1, 823: 1}
assert factorint(
12345, limit=3) == {4115: 1, 3: 1} # the 5 is greater than the limit
assert factorint(1, limit=1) == {}
assert factorint(0, 3) == {0: 1}
assert factorint(12, limit=1) == {12: 1}
assert factorint(30, limit=2) == {2: 1, 15: 1}
assert factorint(16, limit=2) == {2: 4}
assert factorint(124, limit=3) == {2: 2, 31: 1}
assert factorint(4*31**2, limit=3) == {2: 2, 31: 2}
p1 = nextprime(2**32)
p2 = nextprime(2**16)
p3 = nextprime(p2)
assert factorint(p1*p2*p3) == {p1: 1, p2: 1, p3: 1}
assert factorint(13*17*19, limit=15) == {13: 1, 17*19: 1}
assert factorint(1951*15013*15053, limit=2000) == {225990689: 1, 1951: 1}
assert factorint(primorial(17) + 1, use_pm1=0) == \
{int(19026377261): 1, 3467: 1, 277: 1, 105229: 1}
# when prime b is closer than approx sqrt(8*p) to prime p then they are
# "close" and have a trivial factorization
a = nextprime(2**2**8) # 78 digits
b = nextprime(a + 2**2**4)
assert 'Fermat' in capture(lambda: factorint(a*b, verbose=1))
raises(ValueError, lambda: pollard_rho(4))
raises(ValueError, lambda: pollard_pm1(3))
raises(ValueError, lambda: pollard_pm1(10, B=2))
# verbose coverage
n = nextprime(2**16)*nextprime(2**17)*nextprime(1901)
assert 'with primes' in capture(lambda: factorint(n, verbose=1))
capture(lambda: factorint(nextprime(2**16)*1012, verbose=1))
n = nextprime(2**17)
capture(lambda: factorint(n**3, verbose=1)) # perfect power termination
capture(lambda: factorint(2*n, verbose=1)) # factoring complete msg
# exceed 1st
n = nextprime(2**17)
n *= nextprime(n)
assert '1000' in capture(lambda: factorint(n, limit=1000, verbose=1))
n *= nextprime(n)
assert len(factorint(n)) == 3
assert len(factorint(n, limit=p1)) == 3
n *= nextprime(2*n)
# exceed 2nd
assert '2001' in capture(lambda: factorint(n, limit=2000, verbose=1))
assert capture(
lambda: factorint(n, limit=4000, verbose=1)).count('Pollard') == 2
# non-prime pm1 result
n = nextprime(8069)
n *= nextprime(2*n)*nextprime(2*n, 2)
capture(lambda: factorint(n, verbose=1)) # non-prime pm1 result
# factor fermat composite
p1 = nextprime(2**17)
p2 = nextprime(2*p1)
assert factorint((p1*p2**2)**3) == {p1: 3, p2: 6}
# Test for non integer input
raises(ValueError, lambda: factorint(4.5))
# test dict/Dict input
sans = '2**10*3**3'
n = {4: 2, 12: 3}
assert str(factorint(n)) == sans
assert str(factorint(Dict(n))) == sans
def test_divisors_and_divisor_count():
assert divisors(-1) == [1]
assert divisors(0) == []
assert divisors(1) == [1]
assert divisors(2) == [1, 2]
assert divisors(3) == [1, 3]
assert divisors(17) == [1, 17]
assert divisors(10) == [1, 2, 5, 10]
assert divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50, 100]
assert divisors(101) == [1, 101]
assert divisor_count(0) == 0
assert divisor_count(-1) == 1
assert divisor_count(1) == 1
assert divisor_count(6) == 4
assert divisor_count(12) == 6
assert divisor_count(180, 3) == divisor_count(180//3)
assert divisor_count(2*3*5, 7) == 0
def test_proper_divisors_and_proper_divisor_count():
assert proper_divisors(-1) == []
assert proper_divisors(0) == []
assert proper_divisors(1) == []
assert proper_divisors(2) == [1]
assert proper_divisors(3) == [1]
assert proper_divisors(17) == [1]
assert proper_divisors(10) == [1, 2, 5]
assert proper_divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50]
assert proper_divisors(1000000007) == [1]
assert proper_divisor_count(0) == 0
assert proper_divisor_count(-1) == 0
assert proper_divisor_count(1) == 0
assert proper_divisor_count(36) == 8
assert proper_divisor_count(2*3*5) == 7
def test_udivisors_and_udivisor_count():
assert udivisors(-1) == [1]
assert udivisors(0) == []
assert udivisors(1) == [1]
assert udivisors(2) == [1, 2]
assert udivisors(3) == [1, 3]
assert udivisors(17) == [1, 17]
assert udivisors(10) == [1, 2, 5, 10]
assert udivisors(100) == [1, 4, 25, 100]
assert udivisors(101) == [1, 101]
assert udivisors(1000) == [1, 8, 125, 1000]
assert udivisor_count(0) == 0
assert udivisor_count(-1) == 1
assert udivisor_count(1) == 1
assert udivisor_count(6) == 4
assert udivisor_count(12) == 4
assert udivisor_count(180) == 8
assert udivisor_count(2*3*5*7) == 16
def test_issue_6981():
S = set(divisors(4)).union(set(divisors(Integer(2))))
assert S == {1,2,4}
def test_totient():
assert [totient(k) for k in range(1, 12)] == \
[1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10]
assert totient(5005) == 2880
assert totient(5006) == 2502
assert totient(5009) == 5008
assert totient(2**100) == 2**99
raises(ValueError, lambda: totient(30.1))
raises(ValueError, lambda: totient(20.001))
m = Symbol("m", integer=True)
assert totient(m)
assert totient(m).subs(m, 3**10) == 3**10 - 3**9
assert summation(totient(m), (m, 1, 11)) == 42
n = Symbol("n", integer=True, positive=True)
assert totient(n).is_integer
x=Symbol("x", integer=False)
raises(ValueError, lambda: totient(x))
y=Symbol("y", positive=False)
raises(ValueError, lambda: totient(y))
z=Symbol("z", positive=True, integer=True)
raises(ValueError, lambda: totient(2**(-z)))
def test_reduced_totient():
assert [reduced_totient(k) for k in range(1, 16)] == \
[1, 1, 2, 2, 4, 2, 6, 2, 6, 4, 10, 2, 12, 6, 4]
assert reduced_totient(5005) == 60
assert reduced_totient(5006) == 2502
assert reduced_totient(5009) == 5008
assert reduced_totient(2**100) == 2**98
m = Symbol("m", integer=True)
assert reduced_totient(m)
assert reduced_totient(m).subs(m, 2**3*3**10) == 3**10 - 3**9
assert summation(reduced_totient(m), (m, 1, 16)) == 68
n = Symbol("n", integer=True, positive=True)
assert reduced_totient(n).is_integer
def test_divisor_sigma():
assert [divisor_sigma(k) for k in range(1, 12)] == \
[1, 3, 4, 7, 6, 12, 8, 15, 13, 18, 12]
assert [divisor_sigma(k, 2) for k in range(1, 12)] == \
[1, 5, 10, 21, 26, 50, 50, 85, 91, 130, 122]
assert divisor_sigma(23450) == 50592
assert divisor_sigma(23450, 0) == 24
assert divisor_sigma(23450, 1) == 50592
assert divisor_sigma(23450, 2) == 730747500
assert divisor_sigma(23450, 3) == 14666785333344
a = Symbol("a", prime=True)
b = Symbol("b", prime=True)
j = Symbol("j", integer=True, positive=True)
k = Symbol("k", integer=True, positive=True)
assert divisor_sigma(a**j*b**k) == (a**(j + 1) - 1)*(b**(k + 1) - 1)/((a - 1)*(b - 1))
assert divisor_sigma(a**j*b**k, 2) == (a**(2*j + 2) - 1)*(b**(2*k + 2) - 1)/((a**2 - 1)*(b**2 - 1))
assert divisor_sigma(a**j*b**k, 0) == (j + 1)*(k + 1)
m = Symbol("m", integer=True)
k = Symbol("k", integer=True)
assert divisor_sigma(m)
assert divisor_sigma(m, k)
assert divisor_sigma(m).subs(m, 3**10) == 88573
assert divisor_sigma(m, k).subs([(m, 3**10), (k, 3)]) == 213810021790597
assert summation(divisor_sigma(m), (m, 1, 11)) == 99
def test_udivisor_sigma():
assert [udivisor_sigma(k) for k in range(1, 12)] == \
[1, 3, 4, 5, 6, 12, 8, 9, 10, 18, 12]
assert [udivisor_sigma(k, 3) for k in range(1, 12)] == \
[1, 9, 28, 65, 126, 252, 344, 513, 730, 1134, 1332]
assert udivisor_sigma(23450) == 42432
assert udivisor_sigma(23450, 0) == 16
assert udivisor_sigma(23450, 1) == 42432
assert udivisor_sigma(23450, 2) == 702685000
assert udivisor_sigma(23450, 4) == 321426961814978248
m = Symbol("m", integer=True)
k = Symbol("k", integer=True)
assert udivisor_sigma(m)
assert udivisor_sigma(m, k)
assert udivisor_sigma(m).subs(m, 4**9) == 262145
assert udivisor_sigma(m, k).subs([(m, 4**9), (k, 2)]) == 68719476737
assert summation(udivisor_sigma(m), (m, 2, 15)) == 169
def test_issue_4356():
assert factorint(1030903) == {53: 2, 367: 1}
def test_divisors():
assert divisors(28) == [1, 2, 4, 7, 14, 28]
assert [x for x in divisors(3*5*7, 1)] == [1, 3, 5, 15, 7, 21, 35, 105]
assert divisors(0) == []
def test_divisor_count():
assert divisor_count(0) == 0
assert divisor_count(6) == 4
def test_proper_divisors():
assert proper_divisors(-1) == []
assert proper_divisors(28) == [1, 2, 4, 7, 14]
assert [x for x in proper_divisors(3*5*7, True)] == [1, 3, 5, 15, 7, 21, 35]
def test_proper_divisor_count():
assert proper_divisor_count(6) == 3
assert proper_divisor_count(108) == 11
def test_antidivisors():
assert antidivisors(-1) == []
assert antidivisors(-3) == [2]
assert antidivisors(14) == [3, 4, 9]
assert antidivisors(237) == [2, 5, 6, 11, 19, 25, 43, 95, 158]
assert antidivisors(12345) == [2, 6, 7, 10, 30, 1646, 3527, 4938, 8230]
assert antidivisors(393216) == [262144]
assert sorted(x for x in antidivisors(3*5*7, 1)) == \
[2, 6, 10, 11, 14, 19, 30, 42, 70]
assert antidivisors(1) == []
def test_antidivisor_count():
assert antidivisor_count(0) == 0
assert antidivisor_count(-1) == 0
assert antidivisor_count(-4) == 1
assert antidivisor_count(20) == 3
assert antidivisor_count(25) == 5
assert antidivisor_count(38) == 7
assert antidivisor_count(180) == 6
assert antidivisor_count(2*3*5) == 3
def test_smoothness_and_smoothness_p():
assert smoothness(1) == (1, 1)
assert smoothness(2**4*3**2) == (3, 16)
assert smoothness_p(10431, m=1) == \
(1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
assert smoothness_p(10431) == \
(-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
assert smoothness_p(10431, power=1) == \
(-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
assert smoothness_p(21477639576571, visual=1) == \
'p**i=4410317**1 has p-1 B=1787, B-pow=1787\n' + \
'p**i=4869863**1 has p-1 B=2434931, B-pow=2434931'
def test_visual_factorint():
assert factorint(1, visual=1) == 1
forty2 = factorint(42, visual=True)
assert type(forty2) == Mul
assert str(forty2) == '2**1*3**1*7**1'
assert factorint(1, visual=True) is S.One
no = dict(evaluate=False)
assert factorint(42**2, visual=True) == Mul(Pow(2, 2, **no),
Pow(3, 2, **no),
Pow(7, 2, **no), **no)
assert -1 in factorint(-42, visual=True).args
def test_factorrat():
assert str(factorrat(S(12)/1, visual=True)) == '2**2*3**1'
assert str(factorrat(Rational(1, 1), visual=True)) == '1'
assert str(factorrat(S(25)/14, visual=True)) == '5**2/(2*7)'
assert str(factorrat(Rational(25, 14), visual=True)) == '5**2/(2*7)'
assert str(factorrat(S(-25)/14/9, visual=True)) == '-1*5**2/(2*3**2*7)'
assert factorrat(S(12)/1, multiple=True) == [2, 2, 3]
assert factorrat(Rational(1, 1), multiple=True) == []
assert factorrat(S(25)/14, multiple=True) == [Rational(1, 7), S.Half, 5, 5]
assert factorrat(Rational(25, 14), multiple=True) == [Rational(1, 7), S.Half, 5, 5]
assert factorrat(Rational(12, 1), multiple=True) == [2, 2, 3]
assert factorrat(S(-25)/14/9, multiple=True) == \
[-1, Rational(1, 7), Rational(1, 3), Rational(1, 3), S.Half, 5, 5]
def test_visual_io():
sm = smoothness_p
fi = factorint
# with smoothness_p
n = 124
d = fi(n)
m = fi(d, visual=True)
t = sm(n)
s = sm(t)
for th in [d, s, t, n, m]:
assert sm(th, visual=True) == s
assert sm(th, visual=1) == s
for th in [d, s, t, n, m]:
assert sm(th, visual=False) == t
assert [sm(th, visual=None) for th in [d, s, t, n, m]] == [s, d, s, t, t]
assert [sm(th, visual=2) for th in [d, s, t, n, m]] == [s, d, s, t, t]
# with factorint
for th in [d, m, n]:
assert fi(th, visual=True) == m
assert fi(th, visual=1) == m
for th in [d, m, n]:
assert fi(th, visual=False) == d
assert [fi(th, visual=None) for th in [d, m, n]] == [m, d, d]
assert [fi(th, visual=0) for th in [d, m, n]] == [m, d, d]
# test reevaluation
no = dict(evaluate=False)
assert sm({4: 2}, visual=False) == sm(16)
assert sm(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no),
visual=False) == sm(2**10)
assert fi({4: 2}, visual=False) == fi(16)
assert fi(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no),
visual=False) == fi(2**10)
def test_core():
assert core(35**13, 10) == 42875
assert core(210**2) == 1
assert core(7776, 3) == 36
assert core(10**27, 22) == 10**5
assert core(537824) == 14
assert core(1, 6) == 1
def test_primenu():
assert primenu(2) == 1
assert primenu(2 * 3) == 2
assert primenu(2 * 3 * 5) == 3
assert primenu(3 * 25) == primenu(3) + primenu(25)
assert [primenu(p) for p in primerange(1, 10)] == [1, 1, 1, 1]
assert primenu(fac(50)) == 15
assert primenu(2 ** 9941 - 1) == 1
n = Symbol('n', integer=True)
assert primenu(n)
assert primenu(n).subs(n, 2 ** 31 - 1) == 1
assert summation(primenu(n), (n, 2, 30)) == 43
def test_primeomega():
assert primeomega(2) == 1
assert primeomega(2 * 2) == 2
assert primeomega(2 * 2 * 3) == 3
assert primeomega(3 * 25) == primeomega(3) + primeomega(25)
assert [primeomega(p) for p in primerange(1, 10)] == [1, 1, 1, 1]
assert primeomega(fac(50)) == 108
assert primeomega(2 ** 9941 - 1) == 1
n = Symbol('n', integer=True)
assert primeomega(n)
assert primeomega(n).subs(n, 2 ** 31 - 1) == 1
assert summation(primeomega(n), (n, 2, 30)) == 59
def test_mersenne_prime_exponent():
assert mersenne_prime_exponent(1) == 2
assert mersenne_prime_exponent(4) == 7
assert mersenne_prime_exponent(10) == 89
assert mersenne_prime_exponent(25) == 21701
raises(ValueError, lambda: mersenne_prime_exponent(52))
raises(ValueError, lambda: mersenne_prime_exponent(0))
def test_is_perfect():
assert is_perfect(6) is True
assert is_perfect(15) is False
assert is_perfect(28) is True
assert is_perfect(400) is False
assert is_perfect(496) is True
assert is_perfect(8128) is True
assert is_perfect(10000) is False
def test_is_mersenne_prime():
assert is_mersenne_prime(10) is False
assert is_mersenne_prime(127) is True
assert is_mersenne_prime(511) is False
assert is_mersenne_prime(131071) is True
assert is_mersenne_prime(2147483647) is True
def test_is_abundant():
assert is_abundant(10) is False
assert is_abundant(12) is True
assert is_abundant(18) is True
assert is_abundant(21) is False
assert is_abundant(945) is True
def test_is_deficient():
assert is_deficient(10) is True
assert is_deficient(22) is True
assert is_deficient(56) is False
assert is_deficient(20) is False
assert is_deficient(36) is False
def test_is_amicable():
assert is_amicable(173, 129) is False
assert is_amicable(220, 284) is True
assert is_amicable(8756, 8756) is False
def test_dra():
assert dra(19, 12) == 8
assert dra(2718, 10) == 9
assert dra(0, 22) == 0
assert dra(23456789, 10) == 8
raises(ValueError, lambda: dra(24, -2))
raises(ValueError, lambda: dra(24.2, 5))
def test_drm():
assert drm(19, 12) == 7
assert drm(2718, 10) == 2
assert drm(0, 15) == 0
assert drm(234161, 10) == 6
raises(ValueError, lambda: drm(24, -2))
raises(ValueError, lambda: drm(11.6, 9))
|
0753e65d8247e834e865cde983d6a07f3ce98d4fe2865ddcaa0d3e5d80950bfb | from sympy import (
Abs, And, binomial, Catalan, combsimp, cos, Derivative, E, Eq, exp, EulerGamma,
factorial, Function, harmonic, I, Integral, KroneckerDelta, log,
nan, oo, pi, Piecewise, Product, product, Rational, S, simplify, Identity,
sin, sqrt, Sum, summation, Symbol, symbols, sympify, zeta, gamma,
Indexed, Idx, IndexedBase, prod, Dummy, lowergamma, Range, floor,
rf, MatrixSymbol, tanh, sinh)
from sympy.abc import a, b, c, d, k, m, x, y, z
from sympy.concrete.summations import (
telescopic, _dummy_with_inherited_properties_concrete, eval_sum_residue)
from sympy.concrete.expr_with_intlimits import ReorderError
from sympy.core.facts import InconsistentAssumptions
from sympy.testing.pytest import XFAIL, raises, slow
from sympy.matrices import \
Matrix, SparseMatrix, ImmutableDenseMatrix, ImmutableSparseMatrix
from sympy.core.mod import Mod
n = Symbol('n', integer=True)
def test_karr_convention():
# Test the Karr summation convention that we want to hold.
# See his paper "Summation in Finite Terms" for a detailed
# reasoning why we really want exactly this definition.
# The convention is described on page 309 and essentially
# in section 1.4, definition 3:
#
# \sum_{m <= i < n} f(i) 'has the obvious meaning' for m < n
# \sum_{m <= i < n} f(i) = 0 for m = n
# \sum_{m <= i < n} f(i) = - \sum_{n <= i < m} f(i) for m > n
#
# It is important to note that he defines all sums with
# the upper limit being *exclusive*.
# In contrast, sympy and the usual mathematical notation has:
#
# sum_{i = a}^b f(i) = f(a) + f(a+1) + ... + f(b-1) + f(b)
#
# with the upper limit *inclusive*. So translating between
# the two we find that:
#
# \sum_{m <= i < n} f(i) = \sum_{i = m}^{n-1} f(i)
#
# where we intentionally used two different ways to typeset the
# sum and its limits.
i = Symbol("i", integer=True)
k = Symbol("k", integer=True)
j = Symbol("j", integer=True)
# A simple example with a concrete summand and symbolic limits.
# The normal sum: m = k and n = k + j and therefore m < n:
m = k
n = k + j
a = m
b = n - 1
S1 = Sum(i**2, (i, a, b)).doit()
# The reversed sum: m = k + j and n = k and therefore m > n:
m = k + j
n = k
a = m
b = n - 1
S2 = Sum(i**2, (i, a, b)).doit()
assert simplify(S1 + S2) == 0
# Test the empty sum: m = k and n = k and therefore m = n:
m = k
n = k
a = m
b = n - 1
Sz = Sum(i**2, (i, a, b)).doit()
assert Sz == 0
# Another example this time with an unspecified summand and
# numeric limits. (We can not do both tests in the same example.)
f = Function("f")
# The normal sum with m < n:
m = 2
n = 11
a = m
b = n - 1
S1 = Sum(f(i), (i, a, b)).doit()
# The reversed sum with m > n:
m = 11
n = 2
a = m
b = n - 1
S2 = Sum(f(i), (i, a, b)).doit()
assert simplify(S1 + S2) == 0
# Test the empty sum with m = n:
m = 5
n = 5
a = m
b = n - 1
Sz = Sum(f(i), (i, a, b)).doit()
assert Sz == 0
e = Piecewise((exp(-i), Mod(i, 2) > 0), (0, True))
s = Sum(e, (i, 0, 11))
assert s.n(3) == s.doit().n(3)
def test_karr_proposition_2a():
# Test Karr, page 309, proposition 2, part a
i = Symbol("i", integer=True)
u = Symbol("u", integer=True)
v = Symbol("v", integer=True)
def test_the_sum(m, n):
# g
g = i**3 + 2*i**2 - 3*i
# f = Delta g
f = simplify(g.subs(i, i+1) - g)
# The sum
a = m
b = n - 1
S = Sum(f, (i, a, b)).doit()
# Test if Sum_{m <= i < n} f(i) = g(n) - g(m)
assert simplify(S - (g.subs(i, n) - g.subs(i, m))) == 0
# m < n
test_the_sum(u, u+v)
# m = n
test_the_sum(u, u )
# m > n
test_the_sum(u+v, u )
def test_karr_proposition_2b():
# Test Karr, page 309, proposition 2, part b
i = Symbol("i", integer=True)
u = Symbol("u", integer=True)
v = Symbol("v", integer=True)
w = Symbol("w", integer=True)
def test_the_sum(l, n, m):
# Summand
s = i**3
# First sum
a = l
b = n - 1
S1 = Sum(s, (i, a, b)).doit()
# Second sum
a = l
b = m - 1
S2 = Sum(s, (i, a, b)).doit()
# Third sum
a = m
b = n - 1
S3 = Sum(s, (i, a, b)).doit()
# Test if S1 = S2 + S3 as required
assert S1 - (S2 + S3) == 0
# l < m < n
test_the_sum(u, u+v, u+v+w)
# l < m = n
test_the_sum(u, u+v, u+v )
# l < m > n
test_the_sum(u, u+v+w, v )
# l = m < n
test_the_sum(u, u, u+v )
# l = m = n
test_the_sum(u, u, u )
# l = m > n
test_the_sum(u+v, u+v, u )
# l > m < n
test_the_sum(u+v, u, u+w )
# l > m = n
test_the_sum(u+v, u, u )
# l > m > n
test_the_sum(u+v+w, u+v, u )
def test_arithmetic_sums():
assert summation(1, (n, a, b)) == b - a + 1
assert Sum(S.NaN, (n, a, b)) is S.NaN
assert Sum(x, (n, a, a)).doit() == x
assert Sum(x, (x, a, a)).doit() == a
assert Sum(x, (n, 1, a)).doit() == a*x
assert Sum(x, (x, Range(1, 11))).doit() == 55
assert Sum(x, (x, Range(1, 11, 2))).doit() == 25
assert Sum(x, (x, Range(1, 10, 2))) == Sum(x, (x, Range(9, 0, -2)))
lo, hi = 1, 2
s1 = Sum(n, (n, lo, hi))
s2 = Sum(n, (n, hi, lo))
assert s1 != s2
assert s1.doit() == 3 and s2.doit() == 0
lo, hi = x, x + 1
s1 = Sum(n, (n, lo, hi))
s2 = Sum(n, (n, hi, lo))
assert s1 != s2
assert s1.doit() == 2*x + 1 and s2.doit() == 0
assert Sum(Integral(x, (x, 1, y)) + x, (x, 1, 2)).doit() == \
y**2 + 2
assert summation(1, (n, 1, 10)) == 10
assert summation(2*n, (n, 0, 10**10)) == 100000000010000000000
assert summation(4*n*m, (n, a, 1), (m, 1, d)).expand() == \
2*d + 2*d**2 + a*d + a*d**2 - d*a**2 - a**2*d**2
assert summation(cos(n), (n, -2, 1)) == cos(-2) + cos(-1) + cos(0) + cos(1)
assert summation(cos(n), (n, x, x + 2)) == cos(x) + cos(x + 1) + cos(x + 2)
assert isinstance(summation(cos(n), (n, x, x + S.Half)), Sum)
assert summation(k, (k, 0, oo)) is oo
assert summation(k, (k, Range(1, 11))) == 55
def test_polynomial_sums():
assert summation(n**2, (n, 3, 8)) == 199
assert summation(n, (n, a, b)) == \
((a + b)*(b - a + 1)/2).expand()
assert summation(n**2, (n, 1, b)) == \
((2*b**3 + 3*b**2 + b)/6).expand()
assert summation(n**3, (n, 1, b)) == \
((b**4 + 2*b**3 + b**2)/4).expand()
assert summation(n**6, (n, 1, b)) == \
((6*b**7 + 21*b**6 + 21*b**5 - 7*b**3 + b)/42).expand()
def test_geometric_sums():
assert summation(pi**n, (n, 0, b)) == (1 - pi**(b + 1)) / (1 - pi)
assert summation(2 * 3**n, (n, 0, b)) == 3**(b + 1) - 1
assert summation(S.Half**n, (n, 1, oo)) == 1
assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1
assert summation(2**n, (n, 1, oo)) is oo
assert summation(2**(-n), (n, 1, oo)) == 1
assert summation(3**(-n), (n, 4, oo)) == Rational(1, 54)
assert summation(2**(-4*n + 3), (n, 1, oo)) == Rational(8, 15)
assert summation(2**(n + 1), (n, 1, b)).expand() == 4*(2**b - 1)
# issue 6664:
assert summation(x**n, (n, 0, oo)) == \
Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**n, (n, 0, oo)), True))
assert summation(-2**n, (n, 0, oo)) is -oo
assert summation(I**n, (n, 0, oo)) == Sum(I**n, (n, 0, oo))
# issue 6802:
assert summation((-1)**(2*x + 2), (x, 0, n)) == n + 1
assert summation((-2)**(2*x + 2), (x, 0, n)) == 4*4**(n + 1)/S(3) - Rational(4, 3)
assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1)/S(2) + S.Half
assert summation(y**x, (x, a, b)) == \
Piecewise((-a + b + 1, Eq(y, 1)), ((y**a - y**(b + 1))/(-y + 1), True))
assert summation((-2)**(y*x + 2), (x, 0, n)) == \
4*Piecewise((n + 1, Eq((-2)**y, 1)),
((-(-2)**(y*(n + 1)) + 1)/(-(-2)**y + 1), True))
# issue 8251:
assert summation((1/(n + 1)**2)*n**2, (n, 0, oo)) is oo
#issue 9908:
assert Sum(1/(n**3 - 1), (n, -oo, -2)).doit() == summation(1/(n**3 - 1), (n, -oo, -2))
#issue 11642:
result = Sum(0.5**n, (n, 1, oo)).doit()
assert result == 1
assert result.is_Float
result = Sum(0.25**n, (n, 1, oo)).doit()
assert result == 1/3.
assert result.is_Float
result = Sum(0.99999**n, (n, 1, oo)).doit()
assert result == 99999
assert result.is_Float
result = Sum(S.Half**n, (n, 1, oo)).doit()
assert result == 1
assert not result.is_Float
result = Sum(Rational(3, 5)**n, (n, 1, oo)).doit()
assert result == Rational(3, 2)
assert not result.is_Float
assert Sum(1.0**n, (n, 1, oo)).doit() is oo
assert Sum(2.43**n, (n, 1, oo)).doit() is oo
# Issue 13979
i, k, q = symbols('i k q', integer=True)
result = summation(
exp(-2*I*pi*k*i/n) * exp(2*I*pi*q*i/n) / n, (i, 0, n - 1)
)
assert result.simplify() == Piecewise(
(1, Eq(exp(-2*I*pi*(k - q)/n), 1)), (0, True)
)
def test_harmonic_sums():
assert summation(1/k, (k, 0, n)) == Sum(1/k, (k, 0, n))
assert summation(1/k, (k, 1, n)) == harmonic(n)
assert summation(n/k, (k, 1, n)) == n*harmonic(n)
assert summation(1/k, (k, 5, n)) == harmonic(n) - harmonic(4)
def test_composite_sums():
f = S.Half*(7 - 6*n + Rational(1, 7)*n**3)
s = summation(f, (n, a, b))
assert not isinstance(s, Sum)
A = 0
for i in range(-3, 5):
A += f.subs(n, i)
B = s.subs(a, -3).subs(b, 4)
assert A == B
def test_hypergeometric_sums():
assert summation(
binomial(2*k, k)/4**k, (k, 0, n)) == (1 + 2*n)*binomial(2*n, n)/4**n
assert summation(binomial(2*k, k)/5**k, (k, -oo, oo)) == sqrt(5)
def test_other_sums():
f = m**2 + m*exp(m)
g = 3*exp(Rational(3, 2))/2 + exp(S.Half)/2 - exp(Rational(-1, 2))/2 - 3*exp(Rational(-3, 2))/2 + 5
assert summation(f, (m, Rational(-3, 2), Rational(3, 2))) == g
assert summation(f, (m, -1.5, 1.5)).evalf().epsilon_eq(g.evalf(), 1e-10)
fac = factorial
def NS(e, n=15, **options):
return str(sympify(e).evalf(n, **options))
def test_evalf_fast_series():
# Euler transformed series for sqrt(1+x)
assert NS(Sum(
fac(2*n + 1)/fac(n)**2/2**(3*n + 1), (n, 0, oo)), 100) == NS(sqrt(2), 100)
# Some series for exp(1)
estr = NS(E, 100)
assert NS(Sum(1/fac(n), (n, 0, oo)), 100) == estr
assert NS(1/Sum((1 - 2*n)/fac(2*n), (n, 0, oo)), 100) == estr
assert NS(Sum((2*n + 1)/fac(2*n), (n, 0, oo)), 100) == estr
assert NS(Sum((4*n + 3)/2**(2*n + 1)/fac(2*n + 1), (n, 0, oo))**2, 100) == estr
pistr = NS(pi, 100)
# Ramanujan series for pi
assert NS(9801/sqrt(8)/Sum(fac(
4*n)*(1103 + 26390*n)/fac(n)**4/396**(4*n), (n, 0, oo)), 100) == pistr
assert NS(1/Sum(
binomial(2*n, n)**3 * (42*n + 5)/2**(12*n + 4), (n, 0, oo)), 100) == pistr
# Machin's formula for pi
assert NS(16*Sum((-1)**n/(2*n + 1)/5**(2*n + 1), (n, 0, oo)) -
4*Sum((-1)**n/(2*n + 1)/239**(2*n + 1), (n, 0, oo)), 100) == pistr
# Apery's constant
astr = NS(zeta(3), 100)
P = 126392*n**5 + 412708*n**4 + 531578*n**3 + 336367*n**2 + 104000* \
n + 12463
assert NS(Sum((-1)**n * P / 24 * (fac(2*n + 1)*fac(2*n)*fac(
n))**3 / fac(3*n + 2) / fac(4*n + 3)**3, (n, 0, oo)), 100) == astr
assert NS(Sum((-1)**n * (205*n**2 + 250*n + 77)/64 * fac(n)**10 /
fac(2*n + 1)**5, (n, 0, oo)), 100) == astr
def test_evalf_fast_series_issue_4021():
# Catalan's constant
assert NS(Sum((-1)**(n - 1)*2**(8*n)*(40*n**2 - 24*n + 3)*fac(2*n)**3*
fac(n)**2/n**3/(2*n - 1)/fac(4*n)**2, (n, 1, oo))/64, 100) == \
NS(Catalan, 100)
astr = NS(zeta(3), 100)
assert NS(5*Sum(
(-1)**(n - 1)*fac(n)**2 / n**3 / fac(2*n), (n, 1, oo))/2, 100) == astr
assert NS(Sum((-1)**(n - 1)*(56*n**2 - 32*n + 5) / (2*n - 1)**2 * fac(n - 1)
**3 / fac(3*n), (n, 1, oo))/4, 100) == astr
def test_evalf_slow_series():
assert NS(Sum((-1)**n / n, (n, 1, oo)), 15) == NS(-log(2), 15)
assert NS(Sum((-1)**n / n, (n, 1, oo)), 50) == NS(-log(2), 50)
assert NS(Sum(1/n**2, (n, 1, oo)), 15) == NS(pi**2/6, 15)
assert NS(Sum(1/n**2, (n, 1, oo)), 100) == NS(pi**2/6, 100)
assert NS(Sum(1/n**2, (n, 1, oo)), 500) == NS(pi**2/6, 500)
assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 15) == NS(pi**3/32, 15)
assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 50) == NS(pi**3/32, 50)
def test_euler_maclaurin():
# Exact polynomial sums with E-M
def check_exact(f, a, b, m, n):
A = Sum(f, (k, a, b))
s, e = A.euler_maclaurin(m, n)
assert (e == 0) and (s.expand() == A.doit())
check_exact(k**4, a, b, 0, 2)
check_exact(k**4 + 2*k, a, b, 1, 2)
check_exact(k**4 + k**2, a, b, 1, 5)
check_exact(k**5, 2, 6, 1, 2)
check_exact(k**5, 2, 6, 1, 3)
assert Sum(x-1, (x, 0, 2)).euler_maclaurin(m=30, n=30, eps=2**-15) == (0, 0)
# Not exact
assert Sum(k**6, (k, a, b)).euler_maclaurin(0, 2)[1] != 0
# Numerical test
for mi, ni in [(2, 4), (2, 20), (10, 20), (18, 20)]:
A = Sum(1/k**3, (k, 1, oo))
s, e = A.euler_maclaurin(mi, ni)
assert abs((s - zeta(3)).evalf()) < e.evalf()
raises(ValueError, lambda: Sum(1, (x, 0, 1), (k, 0, 1)).euler_maclaurin())
@slow
def test_evalf_euler_maclaurin():
assert NS(Sum(1/k**k, (k, 1, oo)), 15) == '1.29128599706266'
assert NS(Sum(1/k**k, (k, 1, oo)),
50) == '1.2912859970626635404072825905956005414986193682745'
assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 15) == NS(EulerGamma, 15)
assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 50) == NS(EulerGamma, 50)
assert NS(Sum(log(k)/k**2, (k, 1, oo)), 15) == '0.937548254315844'
assert NS(Sum(log(k)/k**2, (k, 1, oo)),
50) == '0.93754825431584375370257409456786497789786028861483'
assert NS(Sum(1/k, (k, 1000000, 2000000)), 15) == '0.693147930560008'
assert NS(Sum(1/k, (k, 1000000, 2000000)),
50) == '0.69314793056000780941723211364567656807940638436025'
def test_evalf_symbolic():
f, g = symbols('f g', cls=Function)
# issue 6328
expr = Sum(f(x), (x, 1, 3)) + Sum(g(x), (x, 1, 3))
assert expr.evalf() == expr
def test_evalf_issue_3273():
assert Sum(0, (k, 1, oo)).evalf() == 0
def test_simple_products():
assert Product(S.NaN, (x, 1, 3)) is S.NaN
assert product(S.NaN, (x, 1, 3)) is S.NaN
assert Product(x, (n, a, a)).doit() == x
assert Product(x, (x, a, a)).doit() == a
assert Product(x, (y, 1, a)).doit() == x**a
lo, hi = 1, 2
s1 = Product(n, (n, lo, hi))
s2 = Product(n, (n, hi, lo))
assert s1 != s2
# This IS correct according to Karr product convention
assert s1.doit() == 2
assert s2.doit() == 1
lo, hi = x, x + 1
s1 = Product(n, (n, lo, hi))
s2 = Product(n, (n, hi, lo))
s3 = 1 / Product(n, (n, hi + 1, lo - 1))
assert s1 != s2
# This IS correct according to Karr product convention
assert s1.doit() == x*(x + 1)
assert s2.doit() == 1
assert s3.doit() == x*(x + 1)
assert Product(Integral(2*x, (x, 1, y)) + 2*x, (x, 1, 2)).doit() == \
(y**2 + 1)*(y**2 + 3)
assert product(2, (n, a, b)) == 2**(b - a + 1)
assert product(n, (n, 1, b)) == factorial(b)
assert product(n**3, (n, 1, b)) == factorial(b)**3
assert product(3**(2 + n), (n, a, b)) \
== 3**(2*(1 - a + b) + b/2 + (b**2)/2 + a/2 - (a**2)/2)
assert product(cos(n), (n, 3, 5)) == cos(3)*cos(4)*cos(5)
assert product(cos(n), (n, x, x + 2)) == cos(x)*cos(x + 1)*cos(x + 2)
assert isinstance(product(cos(n), (n, x, x + S.Half)), Product)
# If Product managed to evaluate this one, it most likely got it wrong!
assert isinstance(Product(n**n, (n, 1, b)), Product)
def test_rational_products():
assert combsimp(product(1 + 1/n, (n, a, b))) == (1 + b)/a
assert combsimp(product(n + 1, (n, a, b))) == gamma(2 + b)/gamma(1 + a)
assert combsimp(product((n + 1)/(n - 1), (n, a, b))) == b*(1 + b)/(a*(a - 1))
assert combsimp(product(n/(n + 1)/(n + 2), (n, a, b))) == \
a*gamma(a + 2)/(b + 1)/gamma(b + 3)
assert combsimp(product(n*(n + 1)/(n - 1)/(n - 2), (n, a, b))) == \
b**2*(b - 1)*(1 + b)/(a - 1)**2/(a*(a - 2))
def test_wallis_product():
# Wallis product, given in two different forms to ensure that Product
# can factor simple rational expressions
A = Product(4*n**2 / (4*n**2 - 1), (n, 1, b))
B = Product((2*n)*(2*n)/(2*n - 1)/(2*n + 1), (n, 1, b))
R = pi*gamma(b + 1)**2/(2*gamma(b + S.Half)*gamma(b + Rational(3, 2)))
assert simplify(A.doit()) == R
assert simplify(B.doit()) == R
# This one should eventually also be doable (Euler's product formula for sin)
# assert Product(1+x/n**2, (n, 1, b)) == ...
def test_telescopic_sums():
#checks also input 2 of comment 1 issue 4127
assert Sum(1/k - 1/(k + 1), (k, 1, n)).doit() == 1 - 1/(1 + n)
f = Function("f")
assert Sum(
f(k) - f(k + 2), (k, m, n)).doit() == -f(1 + n) - f(2 + n) + f(m) + f(1 + m)
assert Sum(cos(k) - cos(k + 3), (k, 1, n)).doit() == -cos(1 + n) - \
cos(2 + n) - cos(3 + n) + cos(1) + cos(2) + cos(3)
# dummy variable shouldn't matter
assert telescopic(1/m, -m/(1 + m), (m, n - 1, n)) == \
telescopic(1/k, -k/(1 + k), (k, n - 1, n))
assert Sum(1/x/(x - 1), (x, a, b)).doit() == -((a - b - 1)/(b*(a - 1)))
def test_sum_reconstruct():
s = Sum(n**2, (n, -1, 1))
assert s == Sum(*s.args)
raises(ValueError, lambda: Sum(x, x))
raises(ValueError, lambda: Sum(x, (x, 1)))
def test_limit_subs():
for F in (Sum, Product, Integral):
assert F(a*exp(a), (a, -2, 2)) == F(a*exp(a), (a, -b, b)).subs(b, 2)
assert F(a, (a, F(b, (b, 1, 2)), 4)).subs(F(b, (b, 1, 2)), c) == \
F(a, (a, c, 4))
assert F(x, (x, 1, x + y)).subs(x, 1) == F(x, (x, 1, y + 1))
def test_function_subs():
f = Function("f")
S = Sum(x*f(y),(x,0,oo),(y,0,oo))
assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo))
assert S.subs(f(x),x) == S
raises(ValueError, lambda: S.subs(f(y),x+y) )
S = Sum(x*log(y),(x,0,oo),(y,0,oo))
assert S.subs(log(y),y) == S
S = Sum(x*f(y),(x,0,oo),(y,0,oo))
assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo))
def test_equality():
# if this fails remove special handling below
raises(ValueError, lambda: Sum(x, x))
r = symbols('x', real=True)
for F in (Sum, Product, Integral):
try:
assert F(x, x) != F(y, y)
assert F(x, (x, 1, 2)) != F(x, x)
assert F(x, (x, x)) != F(x, x) # or else they print the same
assert F(1, x) != F(1, y)
except ValueError:
pass
assert F(a, (x, 1, 2)) != F(a, (x, 1, 3)) # diff limit
assert F(a, (x, 1, x)) != F(a, (y, 1, y))
assert F(a, (x, 1, 2)) != F(b, (x, 1, 2)) # diff expression
assert F(x, (x, 1, 2)) != F(r, (r, 1, 2)) # diff assumptions
assert F(1, (x, 1, x)) != F(1, (y, 1, x)) # only dummy is diff
assert F(1, (x, 1, x)).dummy_eq(F(1, (y, 1, x)))
# issue 5265
assert Sum(x, (x, 1, x)).subs(x, a) == Sum(x, (x, 1, a))
def test_Sum_doit():
f = Function('f')
assert Sum(n*Integral(a**2), (n, 0, 2)).doit() == a**3
assert Sum(n*Integral(a**2), (n, 0, 2)).doit(deep=False) == \
3*Integral(a**2)
assert summation(n*Integral(a**2), (n, 0, 2)) == 3*Integral(a**2)
# test nested sum evaluation
s = Sum( Sum( Sum(2,(z,1,n+1)), (y,x+1,n)), (x,1,n))
assert 0 == (s.doit() - n*(n+1)*(n-1)).factor()
# Integer assumes finite
assert Sum(KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((1, And(-oo <= y, y < oo)), (0, True))
assert Sum(KroneckerDelta(m, n), (m, -oo, oo)).doit() == 1
assert Sum(m*KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((m, And(-oo <= y, y < oo)), (0, True))
assert Sum(x*KroneckerDelta(m, n), (m, -oo, oo)).doit() == x
assert Sum(Sum(KroneckerDelta(m, n), (m, 1, 3)), (n, 1, 3)).doit() == 3
assert Sum(Sum(KroneckerDelta(k, m), (m, 1, 3)), (n, 1, 3)).doit() == \
3 * Piecewise((1, And(1 <= k, k <= 3)), (0, True))
assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, 3)).doit() == \
f(1) + f(2) + f(3)
assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, oo)).doit() == \
Sum(f(n), (n, 1, oo))
# issue 2597
nmax = symbols('N', integer=True, positive=True)
pw = Piecewise((1, And(1 <= n, n <= nmax)), (0, True))
assert Sum(pw, (n, 1, nmax)).doit() == Sum(Piecewise((1, nmax >= n),
(0, True)), (n, 1, nmax))
q, s = symbols('q, s')
assert summation(1/n**(2*s), (n, 1, oo)) == Piecewise((zeta(2*s), 2*s > 1),
(Sum(n**(-2*s), (n, 1, oo)), True))
assert summation(1/(n+1)**s, (n, 0, oo)) == Piecewise((zeta(s), s > 1),
(Sum((n + 1)**(-s), (n, 0, oo)), True))
assert summation(1/(n+q)**s, (n, 0, oo)) == Piecewise(
(zeta(s, q), And(q > 0, s > 1)),
(Sum((n + q)**(-s), (n, 0, oo)), True))
assert summation(1/(n+q)**s, (n, q, oo)) == Piecewise(
(zeta(s, 2*q), And(2*q > 0, s > 1)),
(Sum((n + q)**(-s), (n, q, oo)), True))
assert summation(1/n**2, (n, 1, oo)) == zeta(2)
assert summation(1/n**s, (n, 0, oo)) == Sum(n**(-s), (n, 0, oo))
def test_Product_doit():
assert Product(n*Integral(a**2), (n, 1, 3)).doit() == 2 * a**9 / 9
assert Product(n*Integral(a**2), (n, 1, 3)).doit(deep=False) == \
6*Integral(a**2)**3
assert product(n*Integral(a**2), (n, 1, 3)) == 6*Integral(a**2)**3
def test_Sum_interface():
assert isinstance(Sum(0, (n, 0, 2)), Sum)
assert Sum(nan, (n, 0, 2)) is nan
assert Sum(nan, (n, 0, oo)) is nan
assert Sum(0, (n, 0, 2)).doit() == 0
assert isinstance(Sum(0, (n, 0, oo)), Sum)
assert Sum(0, (n, 0, oo)).doit() == 0
raises(ValueError, lambda: Sum(1))
raises(ValueError, lambda: summation(1))
def test_diff():
assert Sum(x, (x, 1, 2)).diff(x) == 0
assert Sum(x*y, (x, 1, 2)).diff(x) == 0
assert Sum(x*y, (y, 1, 2)).diff(x) == Sum(y, (y, 1, 2))
e = Sum(x*y, (x, 1, a))
assert e.diff(a) == Derivative(e, a)
assert Sum(x*y, (x, 1, 3), (a, 2, 5)).diff(y).doit() == \
Sum(x*y, (x, 1, 3), (a, 2, 5)).doit().diff(y) == 24
assert Sum(x, (x, 1, 2)).diff(y) == 0
def test_hypersum():
from sympy import sin
assert simplify(summation(x**n/fac(n), (n, 1, oo))) == -1 + exp(x)
assert summation((-1)**n * x**(2*n) / fac(2*n), (n, 0, oo)) == cos(x)
assert simplify(summation((-1)**n*x**(2*n + 1) /
factorial(2*n + 1), (n, 3, oo))) == -x + sin(x) + x**3/6 - x**5/120
assert summation(1/(n + 2)**3, (n, 1, oo)) == Rational(-9, 8) + zeta(3)
assert summation(1/n**4, (n, 1, oo)) == pi**4/90
s = summation(x**n*n, (n, -oo, 0))
assert s.is_Piecewise
assert s.args[0].args[0] == -1/(x*(1 - 1/x)**2)
assert s.args[0].args[1] == (abs(1/x) < 1)
m = Symbol('n', integer=True, positive=True)
assert summation(binomial(m, k), (k, 0, m)) == 2**m
def test_issue_4170():
assert summation(1/factorial(k), (k, 0, oo)) == E
def test_is_commutative():
from sympy.physics.secondquant import NO, F, Fd
m = Symbol('m', commutative=False)
for f in (Sum, Product, Integral):
assert f(z, (z, 1, 1)).is_commutative is True
assert f(z*y, (z, 1, 6)).is_commutative is True
assert f(m*x, (x, 1, 2)).is_commutative is False
assert f(NO(Fd(x)*F(y))*z, (z, 1, 2)).is_commutative is False
def test_is_zero():
for func in [Sum, Product]:
assert func(0, (x, 1, 1)).is_zero is True
assert func(x, (x, 1, 1)).is_zero is None
assert Sum(0, (x, 1, 0)).is_zero is True
assert Product(0, (x, 1, 0)).is_zero is False
def test_is_number():
# is number should not rely on evaluation or assumptions,
# it should be equivalent to `not foo.free_symbols`
assert Sum(1, (x, 1, 1)).is_number is True
assert Sum(1, (x, 1, x)).is_number is False
assert Sum(0, (x, y, z)).is_number is False
assert Sum(x, (y, 1, 2)).is_number is False
assert Sum(x, (y, 1, 1)).is_number is False
assert Sum(x, (x, 1, 2)).is_number is True
assert Sum(x*y, (x, 1, 2), (y, 1, 3)).is_number is True
assert Product(2, (x, 1, 1)).is_number is True
assert Product(2, (x, 1, y)).is_number is False
assert Product(0, (x, y, z)).is_number is False
assert Product(1, (x, y, z)).is_number is False
assert Product(x, (y, 1, x)).is_number is False
assert Product(x, (y, 1, 2)).is_number is False
assert Product(x, (y, 1, 1)).is_number is False
assert Product(x, (x, 1, 2)).is_number is True
def test_free_symbols():
for func in [Sum, Product]:
assert func(1, (x, 1, 2)).free_symbols == set()
assert func(0, (x, 1, y)).free_symbols == {y}
assert func(2, (x, 1, y)).free_symbols == {y}
assert func(x, (x, 1, 2)).free_symbols == set()
assert func(x, (x, 1, y)).free_symbols == {y}
assert func(x, (y, 1, y)).free_symbols == {x, y}
assert func(x, (y, 1, 2)).free_symbols == {x}
assert func(x, (y, 1, 1)).free_symbols == {x}
assert func(x, (y, 1, z)).free_symbols == {x, z}
assert func(x, (x, 1, y), (y, 1, 2)).free_symbols == set()
assert func(x, (x, 1, y), (y, 1, z)).free_symbols == {z}
assert func(x, (x, 1, y), (y, 1, y)).free_symbols == {y}
assert func(x, (y, 1, y), (y, 1, z)).free_symbols == {x, z}
assert Sum(1, (x, 1, y)).free_symbols == {y}
# free_symbols answers whether the object *as written* has free symbols,
# not whether the evaluated expression has free symbols
assert Product(1, (x, 1, y)).free_symbols == {y}
def test_conjugate_transpose():
A, B = symbols("A B", commutative=False)
p = Sum(A*B**n, (n, 1, 3))
assert p.adjoint().doit() == p.doit().adjoint()
assert p.conjugate().doit() == p.doit().conjugate()
assert p.transpose().doit() == p.doit().transpose()
p = Sum(B**n*A, (n, 1, 3))
assert p.adjoint().doit() == p.doit().adjoint()
assert p.conjugate().doit() == p.doit().conjugate()
assert p.transpose().doit() == p.doit().transpose()
def test_noncommutativity_honoured():
A, B = symbols("A B", commutative=False)
M = symbols('M', integer=True, positive=True)
p = Sum(A*B**n, (n, 1, M))
assert p.doit() == A*Piecewise((M, Eq(B, 1)),
((B - B**(M + 1))*(1 - B)**(-1), True))
p = Sum(B**n*A, (n, 1, M))
assert p.doit() == Piecewise((M, Eq(B, 1)),
((B - B**(M + 1))*(1 - B)**(-1), True))*A
p = Sum(B**n*A*B**n, (n, 1, M))
assert p.doit() == p
def test_issue_4171():
assert summation(factorial(2*k + 1)/factorial(2*k), (k, 0, oo)) is oo
assert summation(2*k + 1, (k, 0, oo)) is oo
def test_issue_6273():
assert Sum(x, (x, 1, n)).n(2, subs={n: 1}) == 1
def test_issue_6274():
assert Sum(x, (x, 1, 0)).doit() == 0
assert NS(Sum(x, (x, 1, 0))) == '0'
assert Sum(n, (n, 10, 5)).doit() == -30
assert NS(Sum(n, (n, 10, 5))) == '-30.0000000000000'
def test_simplify_sum():
y, t, v = symbols('y, t, v')
_simplify = lambda e: simplify(e, doit=False)
assert _simplify(Sum(x*y, (x, n, m), (y, a, k)) + \
Sum(y, (x, n, m), (y, a, k))) == Sum(y * (x + 1), (x, n, m), (y, a, k))
assert _simplify(Sum(x, (x, n, m)) + Sum(x, (x, m + 1, a))) == \
Sum(x, (x, n, a))
assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x, (x, n, k))) == \
Sum(x, (x, n, a))
assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x + 1, (x, n, k))) == \
Sum(x, (x, n, a)) + Sum(1, (x, n, k))
assert _simplify(Sum(x, (x, 0, 3)) * 3 + 3 * Sum(x, (x, 4, 6)) + \
4 * Sum(z, (z, 0, 1))) == 4*Sum(z, (z, 0, 1)) + 3*Sum(x, (x, 0, 6))
assert _simplify(3*Sum(x**2, (x, a, b)) + Sum(x, (x, a, b))) == \
Sum(x*(3*x + 1), (x, a, b))
assert _simplify(Sum(x**3, (x, n, k)) * 3 + 3 * Sum(x, (x, n, k)) + \
4 * y * Sum(z, (z, n, k))) + 1 == \
4*y*Sum(z, (z, n, k)) + 3*Sum(x**3 + x, (x, n, k)) + 1
assert _simplify(Sum(x, (x, a, b)) + 1 + Sum(x, (x, b + 1, c))) == \
1 + Sum(x, (x, a, c))
assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + \
Sum(x, (t, b+1, c))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b))
assert _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + \
Sum(y, (t, a, b))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b))
assert _simplify(Sum(x, (t, a, b)) + 2 * Sum(x, (t, b+1, c))) == \
_simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + Sum(x, (t, b+1, c)))
assert _simplify(Sum(x, (x, a, b))*Sum(x**2, (x, a, b))) == \
Sum(x, (x, a, b)) * Sum(x**2, (x, a, b))
assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b))) \
== (x + y + z) * Sum(1, (t, a, b)) # issue 8596
assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b)) + \
Sum(v, (t, a, b))) == (x + y + z + v) * Sum(1, (t, a, b)) # issue 8596
assert _simplify(Sum(x * y, (x, a, b)) / (3 * y)) == \
(Sum(x, (x, a, b)) / 3)
assert _simplify(Sum(Function('f')(x) * y * z, (x, a, b)) / (y * z)) \
== Sum(Function('f')(x), (x, a, b))
assert _simplify(Sum(c * x, (x, a, b)) - c * Sum(x, (x, a, b))) == 0
assert _simplify(c * (Sum(x, (x, a, b)) + y)) == c * (y + Sum(x, (x, a, b)))
assert _simplify(c * (Sum(x, (x, a, b)) + y * Sum(x, (x, a, b)))) == \
c * (y + 1) * Sum(x, (x, a, b))
assert _simplify(Sum(Sum(c * x, (x, a, b)), (y, a, b))) == \
c * Sum(x, (x, a, b), (y, a, b))
assert _simplify(Sum((3 + y) * Sum(c * x, (x, a, b)), (y, a, b))) == \
c * Sum((3 + y), (y, a, b)) * Sum(x, (x, a, b))
assert _simplify(Sum((3 + t) * Sum(c * t, (x, a, b)), (y, a, b))) == \
c*t*(t + 3)*Sum(1, (x, a, b))*Sum(1, (y, a, b))
assert _simplify(Sum(Sum(d * t, (x, a, b - 1)) + \
Sum(d * t, (x, b, c)), (t, a, b))) == \
d * Sum(1, (x, a, c)) * Sum(t, (t, a, b))
def test_change_index():
b, v, w = symbols('b, v, w', integer = True)
assert Sum(x, (x, a, b)).change_index(x, x + 1, y) == \
Sum(y - 1, (y, a + 1, b + 1))
assert Sum(x**2, (x, a, b)).change_index( x, x - 1) == \
Sum((x+1)**2, (x, a - 1, b - 1))
assert Sum(x**2, (x, a, b)).change_index( x, -x, y) == \
Sum((-y)**2, (y, -b, -a))
assert Sum(x, (x, a, b)).change_index( x, -x - 1) == \
Sum(-x - 1, (x, -b - 1, -a - 1))
assert Sum(x*y, (x, a, b), (y, c, d)).change_index( x, x - 1, z) == \
Sum((z + 1)*y, (z, a - 1, b - 1), (y, c, d))
assert Sum(x, (x, a, b)).change_index( x, x + v) == \
Sum(-v + x, (x, a + v, b + v))
assert Sum(x, (x, a, b)).change_index( x, -x - v) == \
Sum(-v - x, (x, -b - v, -a - v))
assert Sum(x, (x, a, b)).change_index(x, w*x, v) == \
Sum(v/w, (v, b*w, a*w))
raises(ValueError, lambda: Sum(x, (x, a, b)).change_index(x, 2*x))
def test_reorder():
b, y, c, d, z = symbols('b, y, c, d, z', integer = True)
assert Sum(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \
Sum(x*y, (y, c, d), (x, a, b))
assert Sum(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \
Sum(x, (x, c, d), (x, a, b))
assert Sum(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\
(2, 0), (0, 1)) == Sum(x*y + z, (z, m, n), (y, c, d), (x, a, b))
assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
(0, 1), (1, 2), (0, 2)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d))
assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
(x, y), (y, z), (x, z)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d))
assert Sum(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \
Sum(x*y, (y, c, d), (x, a, b))
assert Sum(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \
Sum(x*y, (y, c, d), (x, a, b))
def test_reverse_order():
assert Sum(x, (x, 0, 3)).reverse_order(0) == Sum(-x, (x, 4, -1))
assert Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \
Sum(x*y, (x, 6, 0), (y, 7, -1))
assert Sum(x, (x, 1, 2)).reverse_order(0) == Sum(-x, (x, 3, 0))
assert Sum(x, (x, 1, 3)).reverse_order(0) == Sum(-x, (x, 4, 0))
assert Sum(x, (x, 1, a)).reverse_order(0) == Sum(-x, (x, a + 1, 0))
assert Sum(x, (x, a, 5)).reverse_order(0) == Sum(-x, (x, 6, a - 1))
assert Sum(x, (x, a + 1, a + 5)).reverse_order(0) == \
Sum(-x, (x, a + 6, a))
assert Sum(x, (x, a + 1, a + 2)).reverse_order(0) == \
Sum(-x, (x, a + 3, a))
assert Sum(x, (x, a + 1, a + 1)).reverse_order(0) == \
Sum(-x, (x, a + 2, a))
assert Sum(x, (x, a, b)).reverse_order(0) == Sum(-x, (x, b + 1, a - 1))
assert Sum(x, (x, a, b)).reverse_order(x) == Sum(-x, (x, b + 1, a - 1))
assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
def test_issue_7097():
assert sum(x**n/n for n in range(1, 401)) == summation(x**n/n, (n, 1, 400))
def test_factor_expand_subs():
# test factoring
assert Sum(4 * x, (x, 1, y)).factor() == 4 * Sum(x, (x, 1, y))
assert Sum(x * a, (x, 1, y)).factor() == a * Sum(x, (x, 1, y))
assert Sum(4 * x * a, (x, 1, y)).factor() == 4 * a * Sum(x, (x, 1, y))
assert Sum(4 * x * y, (x, 1, y)).factor() == 4 * y * Sum(x, (x, 1, y))
# test expand
assert Sum(x+1,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(1,(x,1,y))
assert Sum(x+a*x**2,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(a*x**2,(x,1,y))
assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand() \
== Sum(x*x**n, (n, -1, oo)) + Sum(n*x*x**n, (n, -1, oo))
assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(power_exp=False) \
== Sum(n*x**(n+1), (n, -1, oo)) + Sum(x**(n+1), (n, -1, oo))
assert Sum(a*n+a*n**2,(n,0,4)).expand() \
== Sum(a*n,(n,0,4)) + Sum(a*n**2,(n,0,4))
assert Sum(x**a*x**n,(x,0,3)) \
== Sum(x**(a+n),(x,0,3)).expand(power_exp=True)
assert Sum(x**(a+n),(x,0,3)) \
== Sum(x**(a+n),(x,0,3)).expand(power_exp=False)
# test subs
assert Sum(1/(1+a*x**2),(x,0,3)).subs([(a,3)]) == Sum(1/(1+3*x**2),(x,0,3))
assert Sum(x*y,(x,0,y),(y,0,x)).subs([(x,3)]) == Sum(x*y,(x,0,y),(y,0,3))
assert Sum(x,(x,1,10)).subs([(x,y-2)]) == Sum(x,(x,1,10))
assert Sum(1/x,(x,1,10)).subs([(x,(3+n)**3)]) == Sum(1/x,(x,1,10))
assert Sum(1/x,(x,1,10)).subs([(x,3*x-2)]) == Sum(1/x,(x,1,10))
def test_distribution_over_equality():
f = Function('f')
assert Product(Eq(x*2, f(x)), (x, 1, 3)).doit() == Eq(48, f(1)*f(2)*f(3))
assert Sum(Eq(f(x), x**2), (x, 0, y)) == \
Eq(Sum(f(x), (x, 0, y)), Sum(x**2, (x, 0, y)))
def test_issue_2787():
n, k = symbols('n k', positive=True, integer=True)
p = symbols('p', positive=True)
binomial_dist = binomial(n, k)*p**k*(1 - p)**(n - k)
s = Sum(binomial_dist*k, (k, 0, n))
res = s.doit().simplify()
assert res == Piecewise(
(n*p, p/Abs(p - 1) <= 1),
((-p + 1)**n*Sum(k*p**k*(-p + 1)**(-k)*binomial(n, k), (k, 0, n)),
True))
# Issue #17165: make sure that another simplify does not change/increase
# the result
assert res == res.simplify()
def test_issue_4668():
assert summation(1/n, (n, 2, oo)) is oo
def test_matrix_sum():
A = Matrix([[0, 1], [n, 0]])
result = Sum(A, (n, 0, 3)).doit()
assert result == Matrix([[0, 4], [6, 0]])
assert result.__class__ == ImmutableDenseMatrix
A = SparseMatrix([[0, 1], [n, 0]])
result = Sum(A, (n, 0, 3)).doit()
assert result.__class__ == ImmutableSparseMatrix
def test_failing_matrix_sum():
n = Symbol('n')
# TODO Implement matrix geometric series summation.
A = Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 0]])
assert Sum(A ** n, (n, 1, 4)).doit() == \
Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
# issue sympy/sympy#16989
assert summation(A**n, (n, 1, 1)) == A
def test_indexed_idx_sum():
i = symbols('i', cls=Idx)
r = Indexed('r', i)
assert Sum(r, (i, 0, 3)).doit() == sum([r.xreplace({i: j}) for j in range(4)])
assert Product(r, (i, 0, 3)).doit() == prod([r.xreplace({i: j}) for j in range(4)])
j = symbols('j', integer=True)
assert Sum(r, (i, j, j+2)).doit() == sum([r.xreplace({i: j+k}) for k in range(3)])
assert Product(r, (i, j, j+2)).doit() == prod([r.xreplace({i: j+k}) for k in range(3)])
k = Idx('k', range=(1, 3))
A = IndexedBase('A')
assert Sum(A[k], k).doit() == sum([A[Idx(j, (1, 3))] for j in range(1, 4)])
assert Product(A[k], k).doit() == prod([A[Idx(j, (1, 3))] for j in range(1, 4)])
raises(ValueError, lambda: Sum(A[k], (k, 1, 4)))
raises(ValueError, lambda: Sum(A[k], (k, 0, 3)))
raises(ValueError, lambda: Sum(A[k], (k, 2, oo)))
raises(ValueError, lambda: Product(A[k], (k, 1, 4)))
raises(ValueError, lambda: Product(A[k], (k, 0, 3)))
raises(ValueError, lambda: Product(A[k], (k, 2, oo)))
def test_is_convergent():
# divergence tests --
assert Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() is S.false
assert Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() is S.false
assert Sum(3**(-2*n - 1)*n**n, (n, 1, oo)).is_convergent() is S.false
assert Sum((-1)**n*n, (n, 3, oo)).is_convergent() is S.false
assert Sum((-1)**n, (n, 1, oo)).is_convergent() is S.false
assert Sum(log(1/n), (n, 2, oo)).is_convergent() is S.false
# Raabe's test --
assert Sum(Product((3*m),(m,1,n))/Product((3*m+4),(m,1,n)),(n,1,oo)).is_convergent() is S.true
# root test --
assert Sum((-12)**n/n, (n, 1, oo)).is_convergent() is S.false
# integral test --
# p-series test --
assert Sum(1/(n**2 + 1), (n, 1, oo)).is_convergent() is S.true
assert Sum(1/n**Rational(6, 5), (n, 1, oo)).is_convergent() is S.true
assert Sum(2/(n*sqrt(n - 1)), (n, 2, oo)).is_convergent() is S.true
assert Sum(1/(sqrt(n)*sqrt(n)), (n, 2, oo)).is_convergent() is S.false
assert Sum(factorial(n) / factorial(n+2), (n, 1, oo)).is_convergent() is S.true
assert Sum(rf(5,n)/rf(7,n),(n,1,oo)).is_convergent() is S.true
assert Sum((rf(1, n)*rf(2, n))/(rf(3, n)*factorial(n)),(n,1,oo)).is_convergent() is S.false
# comparison test --
assert Sum(1/(n + log(n)), (n, 1, oo)).is_convergent() is S.false
assert Sum(1/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true
assert Sum(1/(n*log(n)), (n, 2, oo)).is_convergent() is S.false
assert Sum(2/(n*log(n)*log(log(n))**2), (n, 5, oo)).is_convergent() is S.true
assert Sum(2/(n*log(n)**2), (n, 2, oo)).is_convergent() is S.true
assert Sum((n - 1)/(n**2*log(n)**3), (n, 2, oo)).is_convergent() is S.true
assert Sum(1/(n*log(n)*log(log(n))), (n, 5, oo)).is_convergent() is S.false
assert Sum((n - 1)/(n*log(n)**3), (n, 3, oo)).is_convergent() is S.false
assert Sum(2/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true
assert Sum(1/(n*sqrt(log(n))*log(log(n))), (n, 100, oo)).is_convergent() is S.false
assert Sum(log(log(n))/(n*log(n)**2), (n, 100, oo)).is_convergent() is S.true
assert Sum(log(n)/n**2, (n, 5, oo)).is_convergent() is S.true
# alternating series tests --
assert Sum((-1)**(n - 1)/(n**2 - 1), (n, 3, oo)).is_convergent() is S.true
# with -negativeInfinite Limits
assert Sum(1/(n**2 + 1), (n, -oo, 1)).is_convergent() is S.true
assert Sum(1/(n - 1), (n, -oo, -1)).is_convergent() is S.false
assert Sum(1/(n**2 - 1), (n, -oo, -5)).is_convergent() is S.true
assert Sum(1/(n**2 - 1), (n, -oo, 2)).is_convergent() is S.true
assert Sum(1/(n**2 - 1), (n, -oo, oo)).is_convergent() is S.true
# piecewise functions
f = Piecewise((n**(-2), n <= 1), (n**2, n > 1))
assert Sum(f, (n, 1, oo)).is_convergent() is S.false
assert Sum(f, (n, -oo, oo)).is_convergent() is S.false
assert Sum(f, (n, 1, 100)).is_convergent() is S.true
#assert Sum(f, (n, -oo, 1)).is_convergent() is S.true
# integral test
assert Sum(log(n)/n**3, (n, 1, oo)).is_convergent() is S.true
assert Sum(-log(n)/n**3, (n, 1, oo)).is_convergent() is S.true
# the following function has maxima located at (x, y) =
# (1.2, 0.43), (3.0, -0.25) and (6.8, 0.050)
eq = (x - 2)*(x**2 - 6*x + 4)*exp(-x)
assert Sum(eq, (x, 1, oo)).is_convergent() is S.true
assert Sum(eq, (x, 1, 2)).is_convergent() is S.true
assert Sum(1/(x**3), (x, 1, oo)).is_convergent() is S.true
assert Sum(1/(x**S.Half), (x, 1, oo)).is_convergent() is S.false
# issue 19545
assert Sum(1/n - 3/(3*n +2), (n, 1, oo)).is_convergent() is S.true
# issue 19836
assert Sum(4/(n + 2) - 5/(n + 1) + 1/n,(n, 7, oo)).is_convergent() is S.true
def test_is_absolutely_convergent():
assert Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() is S.false
assert Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() is S.true
@XFAIL
def test_convergent_failing():
# dirichlet tests
assert Sum(sin(n)/n, (n, 1, oo)).is_convergent() is S.true
assert Sum(sin(2*n)/n, (n, 1, oo)).is_convergent() is S.true
def test_issue_6966():
i, k, m = symbols('i k m', integer=True)
z_i, q_i = symbols('z_i q_i')
a_k = Sum(-q_i*z_i/k,(i,1,m))
b_k = a_k.diff(z_i)
assert isinstance(b_k, Sum)
assert b_k == Sum(-q_i/k,(i,1,m))
def test_issue_10156():
cx = Sum(2*y**2*x, (x, 1,3))
e = 2*y*Sum(2*cx*x**2, (x, 1, 9))
assert e.factor() == \
8*y**3*Sum(x, (x, 1, 3))*Sum(x**2, (x, 1, 9))
def test_issue_10973():
assert Sum((-n + (n**3 + 1)**(S(1)/3))/log(n), (n, 1, oo)).is_convergent() is S.true
def test_issue_14129():
assert Sum( k*x**k, (k, 0, n-1)).doit() == \
Piecewise((n**2/2 - n/2, Eq(x, 1)), ((n*x*x**n -
n*x**n - x*x**n + x)/(x - 1)**2, True))
assert Sum( x**k, (k, 0, n-1)).doit() == \
Piecewise((n, Eq(x, 1)), ((-x**n + 1)/(-x + 1), True))
assert Sum( k*(x/y+x)**k, (k, 0, n-1)).doit() == \
Piecewise((n*(n - 1)/2, Eq(x, y/(y + 1))),
(x*(y + 1)*(n*x*y*(x + x/y)**n/(x + x/y)
+ n*x*(x + x/y)**n/(x + x/y) - n*y*(x
+ x/y)**n/(x + x/y) - x*y*(x + x/y)**n/(x
+ x/y) - x*(x + x/y)**n/(x + x/y) + y)/(x*y
+ x - y)**2, True))
def test_issue_14112():
assert Sum((-1)**n/sqrt(n), (n, 1, oo)).is_absolutely_convergent() is S.false
assert Sum((-1)**(2*n)/n, (n, 1, oo)).is_convergent() is S.false
assert Sum((-2)**n + (-3)**n, (n, 1, oo)).is_convergent() is S.false
def test_sin_times_absolutely_convergent():
assert Sum(sin(n) / n**3, (n, 1, oo)).is_convergent() is S.true
assert Sum(sin(n) * log(n) / n**3, (n, 1, oo)).is_convergent() is S.true
def test_issue_14111():
assert Sum(1/log(log(n)), (n, 22, oo)).is_convergent() is S.false
def test_issue_14484():
raises(NotImplementedError, lambda: Sum(sin(n)/log(log(n)), (n, 22, oo)).is_convergent())
def test_issue_14640():
i, n = symbols("i n", integer=True)
a, b, c = symbols("a b c")
assert Sum(a**-i/(a - b), (i, 0, n)).doit() == Sum(
1/(a*a**i - a**i*b), (i, 0, n)).doit() == Piecewise(
(n + 1, Eq(1/a, 1)),
((-a**(-n - 1) + 1)/(1 - 1/a), True))/(a - b)
assert Sum((b*a**i - c*a**i)**-2, (i, 0, n)).doit() == Piecewise(
(n + 1, Eq(a**(-2), 1)),
((-a**(-2*n - 2) + 1)/(1 - 1/a**2), True))/(b - c)**2
s = Sum(i*(a**(n - i) - b**(n - i))/(a - b), (i, 0, n)).doit()
assert not s.has(Sum)
assert s.subs({a: 2, b: 3, n: 5}) == 122
def test_issue_15943():
s = Sum(binomial(n, k)*factorial(n - k), (k, 0, n)).doit().rewrite(gamma)
assert s == -E*(n + 1)*gamma(n + 1)*lowergamma(n + 1, 1)/gamma(n + 2
) + E*gamma(n + 1)
assert s.simplify() == E*(factorial(n) - lowergamma(n + 1, 1))
def test_Sum_dummy_eq():
assert not Sum(x, (x, a, b)).dummy_eq(1)
assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b), (a, 1, 2)))
assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, c)))
assert Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b)))
d = Dummy()
assert Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)), c)
assert not Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)))
assert Sum(x, (x, a, c)).dummy_eq(Sum(y, (y, a, c)))
assert Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)), c)
assert not Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)))
def test_issue_15852():
assert summation(x**y*y, (y, -oo, oo)).doit() == Sum(x**y*y, (y, -oo, oo))
def test_exceptions():
S = Sum(x, (x, a, b))
raises(ValueError, lambda: S.change_index(x, x**2, y))
S = Sum(x, (x, a, b), (x, 1, 4))
raises(ValueError, lambda: S.index(x))
S = Sum(x, (x, a, b), (y, 1, 4))
raises(ValueError, lambda: S.reorder([x]))
S = Sum(x, (x, y, b), (y, 1, 4))
raises(ReorderError, lambda: S.reorder_limit(0, 1))
S = Sum(x*y, (x, a, b), (y, 1, 4))
raises(NotImplementedError, lambda: S.is_convergent())
def test_sumproducts_assumptions():
M = Symbol('M', integer=True, positive=True)
m = Symbol('m', integer=True)
for func in [Sum, Product]:
assert func(m, (m, -M, M)).is_positive is None
assert func(m, (m, -M, M)).is_nonpositive is None
assert func(m, (m, -M, M)).is_negative is None
assert func(m, (m, -M, M)).is_nonnegative is None
assert func(m, (m, -M, M)).is_finite is True
m = Symbol('m', integer=True, nonnegative=True)
for func in [Sum, Product]:
assert func(m, (m, 0, M)).is_positive is None
assert func(m, (m, 0, M)).is_nonpositive is None
assert func(m, (m, 0, M)).is_negative is False
assert func(m, (m, 0, M)).is_nonnegative is True
assert func(m, (m, 0, M)).is_finite is True
m = Symbol('m', integer=True, positive=True)
for func in [Sum, Product]:
assert func(m, (m, 1, M)).is_positive is True
assert func(m, (m, 1, M)).is_nonpositive is False
assert func(m, (m, 1, M)).is_negative is False
assert func(m, (m, 1, M)).is_nonnegative is True
assert func(m, (m, 1, M)).is_finite is True
m = Symbol('m', integer=True, negative=True)
assert Sum(m, (m, -M, -1)).is_positive is False
assert Sum(m, (m, -M, -1)).is_nonpositive is True
assert Sum(m, (m, -M, -1)).is_negative is True
assert Sum(m, (m, -M, -1)).is_nonnegative is False
assert Sum(m, (m, -M, -1)).is_finite is True
assert Product(m, (m, -M, -1)).is_positive is None
assert Product(m, (m, -M, -1)).is_nonpositive is None
assert Product(m, (m, -M, -1)).is_negative is None
assert Product(m, (m, -M, -1)).is_nonnegative is None
assert Product(m, (m, -M, -1)).is_finite is True
m = Symbol('m', integer=True, nonpositive=True)
assert Sum(m, (m, -M, 0)).is_positive is False
assert Sum(m, (m, -M, 0)).is_nonpositive is True
assert Sum(m, (m, -M, 0)).is_negative is None
assert Sum(m, (m, -M, 0)).is_nonnegative is None
assert Sum(m, (m, -M, 0)).is_finite is True
assert Product(m, (m, -M, 0)).is_positive is None
assert Product(m, (m, -M, 0)).is_nonpositive is None
assert Product(m, (m, -M, 0)).is_negative is None
assert Product(m, (m, -M, 0)).is_nonnegative is None
assert Product(m, (m, -M, 0)).is_finite is True
m = Symbol('m', integer=True)
assert Sum(2, (m, 0, oo)).is_positive is None
assert Sum(2, (m, 0, oo)).is_nonpositive is None
assert Sum(2, (m, 0, oo)).is_negative is None
assert Sum(2, (m, 0, oo)).is_nonnegative is None
assert Sum(2, (m, 0, oo)).is_finite is None
assert Product(2, (m, 0, oo)).is_positive is None
assert Product(2, (m, 0, oo)).is_nonpositive is None
assert Product(2, (m, 0, oo)).is_negative is False
assert Product(2, (m, 0, oo)).is_nonnegative is None
assert Product(2, (m, 0, oo)).is_finite is None
assert Product(0, (x, M, M-1)).is_positive is True
assert Product(0, (x, M, M-1)).is_finite is True
def test_expand_with_assumptions():
M = Symbol('M', integer=True, positive=True)
x = Symbol('x', positive=True)
m = Symbol('m', nonnegative=True)
assert log(Product(x**m, (m, 0, M))).expand() == Sum(m*log(x), (m, 0, M))
assert log(Product(exp(x**m), (m, 0, M))).expand() == Sum(x**m, (m, 0, M))
assert log(Product(x**m, (m, 0, M))).rewrite(Sum).expand() == Sum(m*log(x), (m, 0, M))
assert log(Product(exp(x**m), (m, 0, M))).rewrite(Sum).expand() == Sum(x**m, (m, 0, M))
n = Symbol('n', nonnegative=True)
i, j = symbols('i,j', positive=True, integer=True)
x, y = symbols('x,y', positive=True)
assert log(Product(x**i*y**j, (i, 1, n), (j, 1, m))).expand() \
== Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
def test_has_finite_limits():
x = Symbol('x')
assert Sum(1, (x, 1, 9)).has_finite_limits is True
assert Sum(1, (x, 1, oo)).has_finite_limits is False
M = Symbol('M')
assert Sum(1, (x, 1, M)).has_finite_limits is None
M = Symbol('M', positive=True)
assert Sum(1, (x, 1, M)).has_finite_limits is True
x = Symbol('x', positive=True)
M = Symbol('M')
assert Sum(1, (x, 1, M)).has_finite_limits is True
assert Sum(1, (x, 1, M), (y, -oo, oo)).has_finite_limits is False
def test_has_reversed_limits():
assert Sum(1, (x, 1, 1)).has_reversed_limits is False
assert Sum(1, (x, 1, 9)).has_reversed_limits is False
assert Sum(1, (x, 1, -9)).has_reversed_limits is True
assert Sum(1, (x, 1, 0)).has_reversed_limits is True
assert Sum(1, (x, 1, oo)).has_reversed_limits is False
M = Symbol('M')
assert Sum(1, (x, 1, M)).has_reversed_limits is None
M = Symbol('M', positive=True, integer=True)
assert Sum(1, (x, 1, M)).has_reversed_limits is False
assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is False
M = Symbol('M', negative=True)
assert Sum(1, (x, 1, M)).has_reversed_limits is True
assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is True
assert Sum(1, (x, oo, oo)).has_reversed_limits is None
def test_has_empty_sequence():
assert Sum(1, (x, 1, 1)).has_empty_sequence is False
assert Sum(1, (x, 1, 9)).has_empty_sequence is False
assert Sum(1, (x, 1, -9)).has_empty_sequence is False
assert Sum(1, (x, 1, 0)).has_empty_sequence is True
assert Sum(1, (x, y, y - 1)).has_empty_sequence is True
assert Sum(1, (x, 3, 2), (y, -oo, oo)).has_empty_sequence is True
assert Sum(1, (y, -oo, oo), (x, 3, 2)).has_empty_sequence is True
assert Sum(1, (x, oo, oo)).has_empty_sequence is False
def test_empty_sequence():
assert Product(x*y, (x, -oo, oo), (y, 1, 0)).doit() == 1
assert Product(x*y, (y, 1, 0), (x, -oo, oo)).doit() == 1
assert Sum(x, (x, -oo, oo), (y, 1, 0)).doit() == 0
assert Sum(x, (y, 1, 0), (x, -oo, oo)).doit() == 0
def test_issue_8016():
k = Symbol('k', integer=True)
n, m = symbols('n, m', integer=True, positive=True)
s = Sum(binomial(m, k)*binomial(m, n - k)*(-1)**k, (k, 0, n))
assert s.doit().simplify() == \
cos(pi*n/2)*gamma(m + 1)/gamma(n/2 + 1)/gamma(m - n/2 + 1)
def test_issue_14313():
assert Sum(S.Half**floor(n/2), (n, 1, oo)).is_convergent()
def test_issue_14563():
# The assertion was failing due to no assumptions methods in Sums and Product
assert 1 % Sum(1, (x, 0, 1)) == 1
def test_issue_16735():
assert Sum(5**n/gamma(n+1), (n, 1, oo)).is_convergent() is S.true
def test_issue_14871():
assert Sum((Rational(1, 10))**n*rf(0, n)/factorial(n), (n, 0, oo)).rewrite(factorial).doit() == 1
def test_issue_17165():
n = symbols("n", integer=True)
x = symbols('x')
s = (x*Sum(x**n, (n, -1, oo)))
ssimp = s.doit().simplify()
assert ssimp == Piecewise((-1/(x - 1), Abs(x) < 1),
(x*Sum(x**n, (n, -1, oo)), True))
assert ssimp == ssimp.simplify()
def test_issue_19379():
assert Sum(factorial(n)/factorial(n + 2), (n, 1, oo)).is_convergent() is S.true
def test_issue_20777():
assert Sum(exp(x*sin(n/m)), (n, 1, m)).doit() == Sum(exp(x*sin(n/m)), (n, 1, m))
def test__dummy_with_inherited_properties_concrete():
x = Symbol('x')
from sympy import Tuple
d = _dummy_with_inherited_properties_concrete(Tuple(x, 0, 5))
assert d.is_real
assert d.is_integer
assert d.is_nonnegative
assert d.is_extended_nonnegative
d = _dummy_with_inherited_properties_concrete(Tuple(x, 1, 9))
assert d.is_real
assert d.is_integer
assert d.is_positive
assert d.is_odd is None
d = _dummy_with_inherited_properties_concrete(Tuple(x, -5, 5))
assert d.is_real
assert d.is_integer
assert d.is_positive is None
assert d.is_extended_nonnegative is None
assert d.is_odd is None
d = _dummy_with_inherited_properties_concrete(Tuple(x, -1.5, 1.5))
assert d.is_real
assert d.is_integer is None
assert d.is_positive is None
assert d.is_extended_nonnegative is None
N = Symbol('N', integer=True, positive=True)
d = _dummy_with_inherited_properties_concrete(Tuple(x, 2, N))
assert d.is_real
assert d.is_positive
assert d.is_integer
# Return None if no assumptions are added
N = Symbol('N', integer=True, positive=True)
d = _dummy_with_inherited_properties_concrete(Tuple(N, 2, 4))
assert d is None
x = Symbol('x', negative=True)
raises(InconsistentAssumptions,
lambda: _dummy_with_inherited_properties_concrete(Tuple(x, 1, 5)))
def test_matrixsymbol_summation_numerical_limits():
A = MatrixSymbol('A', 3, 3)
n = Symbol('n', integer=True)
assert Sum(A**n, (n, 0, 2)).doit() == Identity(3) + A + A**2
assert Sum(A, (n, 0, 2)).doit() == 3*A
assert Sum(n*A, (n, 0, 2)).doit() == 3*A
B = Matrix([[0, n, 0], [-1, 0, 0], [0, 0, 2]])
ans = Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]]) + 4*A
assert Sum(A+B, (n, 0, 3)).doit() == ans
ans = A*Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]])
assert Sum(A*B, (n, 0, 3)).doit() == ans
ans = (A**2*Matrix([[-2, 0, 0], [0,-2, 0], [0, 0, 4]]) +
A**3*Matrix([[0, -9, 0], [3, 0, 0], [0, 0, 8]]) +
A*Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 2]]))
assert Sum(A**n*B**n, (n, 1, 3)).doit() == ans
@XFAIL
def test_matrixsymbol_summation_symbolic_limits():
N = Symbol('N', integer=True, positive=True)
A = MatrixSymbol('A', 3, 3)
n = Symbol('n', integer=True)
assert Sum(A, (n, 0, N)).doit() == (N+1)*A
assert Sum(n*A, (n, 0, N)).doit() == (N**2/2+N/2)*A
def test_summation_by_residues():
x = Symbol('x')
# Examples from Nakhle H. Asmar, Loukas Grafakos,
# Complex Analysis with Applications
assert eval_sum_residue(1 / (x**2 + 1), (x, -oo, oo)) == pi/tanh(pi)
assert eval_sum_residue(1 / x**6, (x, S(1), oo)) == pi**6/945
assert eval_sum_residue(1 / (x**2 + 9), (x, -oo, oo)) == pi/(3*tanh(3*pi))
assert eval_sum_residue(1 / (x**2 + 1)**2, (x, -oo, oo)) == \
-pi*(-pi/(2*tanh(pi)**2) - 1/(2*tanh(pi)) + pi/2)
assert eval_sum_residue(x**2 / (x**2 + 1)**2, (x, -oo, oo)) == \
-pi*(-pi/2 - 1/(2*tanh(pi)) + pi/(2*tanh(pi)**2))
assert eval_sum_residue(1 / (4*x**2 - 1), (x, -oo, oo)) == 0
assert eval_sum_residue(x**2 / (x**2 - S(1)/4)**2, (x, -oo, oo)) == pi**2/2
assert eval_sum_residue(1 / (4*x**2 - 1)**2, (x, -oo, oo)) == pi**2/8
assert eval_sum_residue(1 / ((x - S(1)/2)**2 + 1), (x, -oo, oo)) == pi*tanh(pi)
assert eval_sum_residue(1 / x**2, (x, S(1), oo)) == pi**2/6
assert eval_sum_residue(1 / x**4, (x, S(1), oo)) == pi**4/90
assert eval_sum_residue(1 / x**2 / (x**2 + 4), (x, S(1), oo)) == \
-pi*(-pi/12 - 1/(16*pi) + 1/(8*tanh(2*pi)))/2
# Some examples made from 1 / (x**2 + 1)
assert eval_sum_residue(1 / (x**2 + 1), (x, S(0), oo)) == \
S(1)/2 + pi/(2*tanh(pi))
assert eval_sum_residue(1 / (x**2 + 1), (x, S(1), oo)) == \
-S(1)/2 + pi/(2*tanh(pi))
assert eval_sum_residue(1 / (x**2 + 1), (x, S(-1), oo)) == \
1 + pi/(2*tanh(pi))
assert eval_sum_residue((-1)**x / (x**2 + 1), (x, -oo, oo)) == \
pi/sinh(pi)
assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(0), oo)) == \
pi/(2*sinh(pi)) + S(1)/2
assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(1), oo)) == \
-S(1)/2 + pi/(2*sinh(pi))
assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(-1), oo)) == \
pi/(2*sinh(pi))
# Some examples made from shifting of 1 / (x**2 + 1)
assert eval_sum_residue(1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*tanh(pi))
assert eval_sum_residue(1 / (x**2 + 4*x + 5), (x, S(-2), oo)) == S(1)/2 + pi/(2*tanh(pi))
assert eval_sum_residue(1 / (x**2 - 2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*tanh(pi))
assert eval_sum_residue(1 / (x**2 - 4*x + 5), (x, S(2), oo)) == S(1)/2 + pi/(2*tanh(pi))
assert eval_sum_residue((-1)**x * -1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*sinh(pi))
assert eval_sum_residue((-1)**x * -1 / (x**2 -2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*sinh(pi))
# Some examples made from 1 / x**2
assert eval_sum_residue(1 / x**2, (x, S(2), oo)) == -1 + pi**2/6
assert eval_sum_residue(1 / x**2, (x, S(3), oo)) == -S(5)/4 + pi**2/6
assert eval_sum_residue((-1)**x / x**2, (x, S(1), oo)) == -pi**2/12
assert eval_sum_residue((-1)**x / x**2, (x, S(2), oo)) == 1 - pi**2/12
def test_summation_by_residues_failing():
x = Symbol('x')
# Failing because of the bug in residue computation
assert eval_sum_residue(x**2 / (x**4 + 1), (x, S(1), oo))
assert eval_sum_residue(1 / ((x - 1)*(x - 2) + 1), (x, -oo, oo)) != 0
|
a2ef11f019ef1703e327fc3a85dc7f467327f1712dc2031f0ef0d320a81f1c44 | from sympy import sin, cos, exp, E, series, oo, S, Derivative, O, Integral, \
Function, PoleError, log, sqrt, N, Symbol, Subs, pi, symbols, atan, LambertW, Rational
from sympy.abc import x, y, n, k
from sympy.testing.pytest import raises
from sympy.series.gruntz import calculate_series
def test_sin():
e1 = sin(x).series(x, 0)
e2 = series(sin(x), x, 0)
assert e1 == e2
def test_cos():
e1 = cos(x).series(x, 0)
e2 = series(cos(x), x, 0)
assert e1 == e2
def test_exp():
e1 = exp(x).series(x, 0)
e2 = series(exp(x), x, 0)
assert e1 == e2
def test_exp2():
e1 = exp(cos(x)).series(x, 0)
e2 = series(exp(cos(x)), x, 0)
assert e1 == e2
def test_issue_5223():
assert series(1, x) == 1
assert next(S.Zero.lseries(x)) == 0
assert cos(x).series() == cos(x).series(x)
raises(ValueError, lambda: cos(x + y).series())
raises(ValueError, lambda: x.series(dir=""))
assert (cos(x).series(x, 1) -
cos(x + 1).series(x).subs(x, x - 1)).removeO() == 0
e = cos(x).series(x, 1, n=None)
assert [next(e) for i in range(2)] == [cos(1), -((x - 1)*sin(1))]
e = cos(x).series(x, 1, n=None, dir='-')
assert [next(e) for i in range(2)] == [cos(1), (1 - x)*sin(1)]
# the following test is exact so no need for x -> x - 1 replacement
assert abs(x).series(x, 1, dir='-') == x
assert exp(x).series(x, 1, dir='-', n=3).removeO() == \
E - E*(-x + 1) + E*(-x + 1)**2/2
D = Derivative
assert D(x**2 + x**3*y**2, x, 2, y, 1).series(x).doit() == 12*x*y
assert next(D(cos(x), x).lseries()) == D(1, x)
assert D(
exp(x), x).series(n=3) == D(1, x) + D(x, x) + D(x**2/2, x) + D(x**3/6, x) + O(x**3)
assert Integral(x, (x, 1, 3), (y, 1, x)).series(x) == -4 + 4*x
assert (1 + x + O(x**2)).getn() == 2
assert (1 + x).getn() is None
raises(PoleError, lambda: ((1/sin(x))**oo).series())
logx = Symbol('logx')
assert ((sin(x))**y).nseries(x, n=1, logx=logx) == \
exp(y*logx) + O(x*exp(y*logx), x)
assert sin(1/x).series(x, oo, n=5) == 1/x - 1/(6*x**3) + O(x**(-5), (x, oo))
assert abs(x).series(x, oo, n=5, dir='+') == x
assert abs(x).series(x, -oo, n=5, dir='-') == -x
assert abs(-x).series(x, oo, n=5, dir='+') == x
assert abs(-x).series(x, -oo, n=5, dir='-') == -x
assert exp(x*log(x)).series(n=3) == \
1 + x*log(x) + x**2*log(x)**2/2 + O(x**3*log(x)**3)
# XXX is this right? If not, fix "ngot > n" handling in expr.
p = Symbol('p', positive=True)
assert exp(sqrt(p)**3*log(p)).series(n=3) == \
1 + p**S('3/2')*log(p) + O(p**3*log(p)**3)
assert exp(sin(x)*log(x)).series(n=2) == 1 + x*log(x) + O(x**2*log(x)**2)
def test_issue_11313():
assert Integral(cos(x), x).series(x) == sin(x).series(x)
assert Derivative(sin(x), x).series(x, n=3).doit() == cos(x).series(x, n=3)
assert Derivative(x**3, x).as_leading_term(x) == 3*x**2
assert Derivative(x**3, y).as_leading_term(x) == 0
assert Derivative(sin(x), x).as_leading_term(x) == 1
assert Derivative(cos(x), x).as_leading_term(x) == -x
# This result is equivalent to zero, zero is not return because
# `Expr.series` doesn't currently detect an `x` in its `free_symbol`s.
assert Derivative(1, x).as_leading_term(x) == Derivative(1, x)
assert Derivative(exp(x), x).series(x).doit() == exp(x).series(x)
assert 1 + Integral(exp(x), x).series(x) == exp(x).series(x)
assert Derivative(log(x), x).series(x).doit() == (1/x).series(x)
assert Integral(log(x), x).series(x) == Integral(log(x), x).doit().series(x).removeO()
def test_series_of_Subs():
from sympy.abc import x, y, z
subs1 = Subs(sin(x), x, y)
subs2 = Subs(sin(x) * cos(z), x, y)
subs3 = Subs(sin(x * z), (x, z), (y, x))
assert subs1.series(x) == subs1
subs1_series = (Subs(x, x, y) + Subs(-x**3/6, x, y) +
Subs(x**5/120, x, y) + O(y**6))
assert subs1.series() == subs1_series
assert subs1.series(y) == subs1_series
assert subs1.series(z) == subs1
assert subs2.series(z) == (Subs(z**4*sin(x)/24, x, y) +
Subs(-z**2*sin(x)/2, x, y) + Subs(sin(x), x, y) + O(z**6))
assert subs3.series(x).doit() == subs3.doit().series(x)
assert subs3.series(z).doit() == sin(x*y)
raises(ValueError, lambda: Subs(x + 2*y, y, z).series())
assert Subs(x + y, y, z).series(x).doit() == x + z
def test_issue_3978():
f = Function('f')
assert f(x).series(x, 0, 3, dir='-') == \
f(0) + x*Subs(Derivative(f(x), x), x, 0) + \
x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3)
assert f(x).series(x, 0, 3) == \
f(0) + x*Subs(Derivative(f(x), x), x, 0) + \
x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3)
assert f(x**2).series(x, 0, 3) == \
f(0) + x**2*Subs(Derivative(f(x), x), x, 0) + O(x**3)
assert f(x**2+1).series(x, 0, 3) == \
f(1) + x**2*Subs(Derivative(f(x), x), x, 1) + O(x**3)
class TestF(Function):
pass
assert TestF(x).series(x, 0, 3) == TestF(0) + \
x*Subs(Derivative(TestF(x), x), x, 0) + \
x**2*Subs(Derivative(TestF(x), x, x), x, 0)/2 + O(x**3)
from sympy.series.acceleration import richardson, shanks
from sympy import Sum, Integer
def test_acceleration():
e = (1 + 1/n)**n
assert round(richardson(e, n, 10, 20).evalf(), 10) == round(E.evalf(), 10)
A = Sum(Integer(-1)**(k + 1) / k, (k, 1, n))
assert round(shanks(A, n, 25).evalf(), 4) == round(log(2).evalf(), 4)
assert round(shanks(A, n, 25, 5).evalf(), 10) == round(log(2).evalf(), 10)
def test_issue_5852():
assert series(1/cos(x/log(x)), x, 0) == 1 + x**2/(2*log(x)**2) + \
5*x**4/(24*log(x)**4) + O(x**6)
def test_issue_4583():
assert cos(1 + x + x**2).series(x, 0, 5) == cos(1) - x*sin(1) + \
x**2*(-sin(1) - cos(1)/2) + x**3*(-cos(1) + sin(1)/6) + \
x**4*(-11*cos(1)/24 + sin(1)/2) + O(x**5)
def test_issue_6318():
eq = (1/x)**Rational(2, 3)
assert (eq + 1).as_leading_term(x) == eq
def test_x_is_base_detection():
eq = (x**2)**Rational(2, 3)
assert eq.series() == x**Rational(4, 3)
def test_sin_power():
e = sin(x)**1.2
assert calculate_series(e, x) == x**1.2
def test_issue_7203():
assert series(cos(x), x, pi, 3) == \
-1 + (x - pi)**2/2 + O((x - pi)**3, (x, pi))
def test_exp_product_positive_factors():
a, b = symbols('a, b', positive=True)
x = a * b
assert series(exp(x), x, n=8) == 1 + a*b + a**2*b**2/2 + \
a**3*b**3/6 + a**4*b**4/24 + a**5*b**5/120 + a**6*b**6/720 + \
a**7*b**7/5040 + O(a**8*b**8, a, b)
def test_issue_8805():
assert series(1, n=8) == 1
def test_issue_9549():
y = (x**2 + x + 1) / (x**3 + x**2)
assert series(y, x, oo) == x**(-5) - 1/x**4 + x**(-3) + 1/x + O(x**(-6), (x, oo))
def test_issue_10761():
assert series(1/(x**-2 + x**-3), x, 0) == x**3 - x**4 + x**5 + O(x**6)
def test_issue_12578():
y = (1 - 1/(x/2 - 1/(2*x))**4)**(S(1)/8)
assert y.series(x, 0, n=17) == 1 - 2*x**4 - 8*x**6 - 34*x**8 - 152*x**10 - 714*x**12 - \
3472*x**14 - 17318*x**16 + O(x**17)
def test_issue_12791():
beta = symbols('beta', real=True, positive=True)
theta, varphi = symbols('theta varphi', real=True)
expr = (-beta**2*varphi*sin(theta) + beta**2*cos(theta) + \
beta*varphi*sin(theta) - beta*cos(theta) - beta + 1)/(beta*cos(theta) - 1)**2
sol = 0.5/(0.5*cos(theta) - 1.0)**2 - 0.25*cos(theta)/(0.5*cos(theta)\
- 1.0)**2 + (beta - 0.5)*(-0.25*varphi*sin(2*theta) - 1.5*cos(theta)\
+ 0.25*cos(2*theta) + 1.25)/(0.5*cos(theta) - 1.0)**3\
+ 0.25*varphi*sin(theta)/(0.5*cos(theta) - 1.0)**2 + O((beta - 0.5)**2, (beta, 0.5))
assert expr.series(beta, 0.5, 2).trigsimp() == sol
def test_issue_14885():
assert series(x**Rational(-3, 2)*exp(x), x, 0) == (x**Rational(-3, 2) + 1/sqrt(x) +
sqrt(x)/2 + x**Rational(3, 2)/6 + x**Rational(5, 2)/24 + x**Rational(7, 2)/120 +
x**Rational(9, 2)/720 + x**Rational(11, 2)/5040 + O(x**6))
def test_issue_15539():
assert series(atan(x), x, -oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x - pi/2
+ O(x**(-6), (x, -oo)))
assert series(atan(x), x, oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x + pi/2
+ O(x**(-6), (x, oo)))
def test_issue_7259():
assert series(LambertW(x), x) == x - x**2 + 3*x**3/2 - 8*x**4/3 + 125*x**5/24 + O(x**6)
assert series(LambertW(x**2), x, n=8) == x**2 - x**4 + 3*x**6/2 + O(x**8)
assert series(LambertW(sin(x)), x, n=4) == x - x**2 + 4*x**3/3 + O(x**4)
def test_issue_11884():
assert cos(x).series(x, 1, n=1) == cos(1) + O(x - 1, (x, 1))
def test_issue_18008():
y = x*(1 + x*(1 - x))/((1 + x*(1 - x)) - (1 - x)*(1 - x))
assert y.series(x, oo, n=4) == -9/(32*x**3) - 3/(16*x**2) - 1/(8*x) + S(1)/4 + x/2 + \
O(x**(-4), (x, oo))
def test_issue_18842():
f = log(x/(1 - x))
assert f.series(x, 0.491, n=1).removeO().nsimplify() == \
-S(180019443780011)/5000000000000000
def test_issue_19534():
dt = symbols('dt', real=True)
expr = 16*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0)/45 + \
49*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + 0.051640768506639183825*dt + \
dt*(1/2 - sqrt(21)/14) + 1.0)/180 + 49*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \
0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + \
2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \
1.1854881643947648988*dt + dt*(sqrt(21)/14 + 1/2) + 1.0)/180 + \
dt*(0.66666666666666666667*dt*(2.0*dt + 1.0) + \
6.0173399699313066769*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
4.1117044797036320069*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) - \
7.0189140975801991157*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) + \
0.94010945196161777522*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \
0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + \
2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \
0.35816132904077632692*dt + 1.0) + 5.5065024887242400038*dt + 1.0)/20 + dt/20 + 1
assert N(expr.series(dt, 0, 8), 20) == -0.00092592592592592596126*dt**7 + 0.0027777777777777783175*dt**6 + \
0.016666666666666656027*dt**5 + 0.083333333333333300952*dt**4 + 0.33333333333333337034*dt**3 + \
1.0*dt**2 + 1.0*dt + 1.0
def test_issue_11407():
a, b, c, x = symbols('a b c x')
assert series(sqrt(a + b + c*x), x, 0, 1) == sqrt(a + b) + O(x)
assert series(sqrt(a + b + c + c*x), x, 0, 1) == sqrt(a + b + c) + O(x)
def test_issue_14037():
assert (sin(x**50)/x**51).series(x, n=0) == 1/x + O(1, x)
def test_issue_20551():
expr = (exp(x)/x).series(x, n=None)
terms = [ next(expr) for i in range(3) ]
assert terms == [1/x, 1, x/2]
def test_issue_20697():
p_0, p_1, p_2, p_3, b_0, b_1, b_2 = symbols('p_0 p_1 p_2 p_3 b_0 b_1 b_2')
Q = (p_0 + (p_1 + (p_2 + p_3/y)/y)/y)/(1 + ((p_3/(b_0*y) + (b_0*p_2\
- b_1*p_3)/b_0**2)/y + (b_0**2*p_1 - b_0*b_1*p_2 - p_3*(b_0*b_2\
- b_1**2))/b_0**3)/y)
assert Q.series(y, n=3) == b_2*y**2 + b_1*y + b_0 + O(y**3)
def test_issue_21245():
fi = (1 + sqrt(5))/2
assert (1/(1 - x - x**2)).series(x, 1/fi, 1) == \
(36/(-36*sqrt(5) - 80) + 16*sqrt(5)/(-36*sqrt(5) - 80))/(x - 1/(S.Half\
+ sqrt(5)/2)) - 1220*sqrt(5)/(-6100*sqrt(5) - 13640) - 2728\
/(-6100*sqrt(5) - 13640) + O(x - 2/(1 + sqrt(5)), (x, 2/(1 + sqrt(5))))
|
52f4bc2629b6acfe3aaaba29b984752ac99df3232f0d00e982781cc08c83d9a2 | from sympy import limit, Symbol, oo, sqrt, Rational, log, exp, cos, sin, tan, \
pi, asin, together, root, S
# Numbers listed with the tests refer to problem numbers in the book
# "Anti-demidovich, problemas resueltos, Ed. URSS"
x = Symbol("x")
def test_leadterm():
assert (3 + 2*x**(log(3)/log(2) - 1)).leadterm(x) == (3, 0)
def root3(x):
return root(x, 3)
def root4(x):
return root(x, 4)
def test_Limits_simple_0():
assert limit((2**(x + 1) + 3**(x + 1))/(2**x + 3**x), x, oo) == 3 # 175
def test_Limits_simple_1():
assert limit((x + 1)*(x + 2)*(x + 3)/x**3, x, oo) == 1 # 172
assert limit(sqrt(x + 1) - sqrt(x), x, oo) == 0 # 179
assert limit((2*x - 3)*(3*x + 5)*(4*x - 6)/(3*x**3 + x - 1), x, oo) == 8 # Primjer 1
assert limit(x/root3(x**3 + 10), x, oo) == 1 # Primjer 2
assert limit((x + 1)**2/(x**2 + 1), x, oo) == 1 # 181
def test_Limits_simple_2():
assert limit(1000*x/(x**2 - 1), x, oo) == 0 # 182
assert limit((x**2 - 5*x + 1)/(3*x + 7), x, oo) is oo # 183
assert limit((2*x**2 - x + 3)/(x**3 - 8*x + 5), x, oo) == 0 # 184
assert limit((2*x**2 - 3*x - 4)/sqrt(x**4 + 1), x, oo) == 2 # 186
assert limit((2*x + 3)/(x + root3(x)), x, oo) == 2 # 187
assert limit(x**2/(10 + x*sqrt(x)), x, oo) is oo # 188
assert limit(root3(x**2 + 1)/(x + 1), x, oo) == 0 # 189
assert limit(sqrt(x)/sqrt(x + sqrt(x + sqrt(x))), x, oo) == 1 # 190
def test_Limits_simple_3a():
a = Symbol('a')
#issue 3513
assert together(limit((x**2 - (a + 1)*x + a)/(x**3 - a**3), x, a)) == \
(a - 1)/(3*a**2) # 196
def test_Limits_simple_3b():
h = Symbol("h")
assert limit(((x + h)**3 - x**3)/h, h, 0) == 3*x**2 # 197
assert limit((1/(1 - x) - 3/(1 - x**3)), x, 1) == -1 # 198
assert limit((sqrt(1 + x) - 1)/(root3(1 + x) - 1), x, 0) == Rational(3)/2 # Primer 4
assert limit((sqrt(x) - 1)/(x - 1), x, 1) == Rational(1)/2 # 199
assert limit((sqrt(x) - 8)/(root3(x) - 4), x, 64) == 3 # 200
assert limit((root3(x) - 1)/(root4(x) - 1), x, 1) == Rational(4)/3 # 201
assert limit(
(root3(x**2) - 2*root3(x) + 1)/(x - 1)**2, x, 1) == Rational(1)/9 # 202
def test_Limits_simple_4a():
a = Symbol('a')
assert limit((sqrt(x) - sqrt(a))/(x - a), x, a) == 1/(2*sqrt(a)) # Primer 5
assert limit((sqrt(x) - 1)/(root3(x) - 1), x, 1) == Rational(3, 2) # 205
assert limit((sqrt(1 + x) - sqrt(1 - x))/x, x, 0) == 1 # 207
assert limit(sqrt(x**2 - 5*x + 6) - x, x, oo) == Rational(-5, 2) # 213
def test_limits_simple_4aa():
assert limit(x*(sqrt(x**2 + 1) - x), x, oo) == Rational(1)/2 # 214
def test_Limits_simple_4b():
#issue 3511
assert limit(x - root3(x**3 - 1), x, oo) == 0 # 215
def test_Limits_simple_4c():
assert limit(log(1 + exp(x))/x, x, -oo) == 0 # 267a
assert limit(log(1 + exp(x))/x, x, oo) == 1 # 267b
def test_bounded():
assert limit(sin(x)/x, x, oo) == 0 # 216b
assert limit(x*sin(1/x), x, 0) == 0 # 227a
def test_f1a():
#issue 3508:
assert limit((sin(2*x)/x)**(1 + x), x, 0) == 2 # Primer 7
def test_f1a2():
#issue 3509:
assert limit(((x - 1)/(x + 1))**x, x, oo) == exp(-2) # Primer 9
def test_f1b():
m = Symbol("m")
n = Symbol("n")
h = Symbol("h")
a = Symbol("a")
assert limit(sin(x)/x, x, 2) == sin(2)/2 # 216a
assert limit(sin(3*x)/x, x, 0) == 3 # 217
assert limit(sin(5*x)/sin(2*x), x, 0) == Rational(5, 2) # 218
assert limit(sin(pi*x)/sin(3*pi*x), x, 0) == Rational(1, 3) # 219
assert limit(x*sin(pi/x), x, oo) == pi # 220
assert limit((1 - cos(x))/x**2, x, 0) == S.Half # 221
assert limit(x*sin(1/x), x, oo) == 1 # 227b
assert limit((cos(m*x) - cos(n*x))/x**2, x, 0) == -m**2/2 + n**2/2 # 232
assert limit((tan(x) - sin(x))/x**3, x, 0) == S.Half # 233
assert limit((x - sin(2*x))/(x + sin(3*x)), x, 0) == -Rational(1, 4) # 237
assert limit((1 - sqrt(cos(x)))/x**2, x, 0) == Rational(1, 4) # 239
assert limit((sqrt(1 + sin(x)) - sqrt(1 - sin(x)))/x, x, 0) == 1 # 240
assert limit((1 + h/x)**x, x, oo) == exp(h) # Primer 9
assert limit((sin(x) - sin(a))/(x - a), x, a) == cos(a) # 222, *176
assert limit((cos(x) - cos(a))/(x - a), x, a) == -sin(a) # 223
assert limit((sin(x + h) - sin(x))/h, h, 0) == cos(x) # 225
def test_f2a():
assert limit(((x + 1)/(2*x + 1))**(x**2), x, oo) == 0 # Primer 8
def test_f2():
assert limit((sqrt(
cos(x)) - root3(cos(x)))/(sin(x)**2), x, 0) == -Rational(1, 12) # *184
def test_f3():
a = Symbol('a')
#issue 3504
assert limit(asin(a*x)/x, x, 0) == a
|
eaa8e64c4c424095d50ab5653c47622c086b020372a1dbcfe2cafa41f4ac815c | from itertools import product as cartes
from sympy import (
limit, exp, oo, log, sqrt, Limit, sin, floor, cos, ceiling,
atan, Abs, gamma, Symbol, S, pi, Integral, Rational, I, E,
tan, cot, integrate, Sum, sign, Function, subfactorial, symbols,
binomial, simplify, frac, Float, sec, zoo, fresnelc, fresnels,
acos, erf, erfc, erfi, LambertW, factorial, digamma, uppergamma,
Ei, EulerGamma, asin, atanh, acot, acoth, asec, acsc, cbrt, besselk)
from sympy.calculus.util import AccumBounds
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.series.limits import heuristics
from sympy.series.order import Order
from sympy.testing.pytest import XFAIL, raises
from sympy.abc import x, y, z, k
n = Symbol('n', integer=True, positive=True)
def test_basic1():
assert limit(x, x, oo) is oo
assert limit(x, x, -oo) is -oo
assert limit(-x, x, oo) is -oo
assert limit(x**2, x, -oo) is oo
assert limit(-x**2, x, oo) is -oo
assert limit(x*log(x), x, 0, dir="+") == 0
assert limit(1/x, x, oo) == 0
assert limit(exp(x), x, oo) is oo
assert limit(-exp(x), x, oo) is -oo
assert limit(exp(x)/x, x, oo) is oo
assert limit(1/x - exp(-x), x, oo) == 0
assert limit(x + 1/x, x, oo) is oo
assert limit(x - x**2, x, oo) is -oo
assert limit((1 + x)**(1 + sqrt(2)), x, 0) == 1
assert limit((1 + x)**oo, x, 0) == Limit((x + 1)**oo, x, 0)
assert limit((1 + x)**oo, x, 0, dir='-') == Limit((x + 1)**oo, x, 0, dir='-')
assert limit((1 + x + y)**oo, x, 0, dir='-') == Limit((x + y + 1)**oo, x, 0, dir='-')
assert limit(y/x/log(x), x, 0) == -oo*sign(y)
assert limit(cos(x + y)/x, x, 0) == sign(cos(y))*oo
assert limit(gamma(1/x + 3), x, oo) == 2
assert limit(S.NaN, x, -oo) is S.NaN
assert limit(Order(2)*x, x, S.NaN) is S.NaN
assert limit(1/(x - 1), x, 1, dir="+") is oo
assert limit(1/(x - 1), x, 1, dir="-") is -oo
assert limit(1/(5 - x)**3, x, 5, dir="+") is -oo
assert limit(1/(5 - x)**3, x, 5, dir="-") is oo
assert limit(1/sin(x), x, pi, dir="+") is -oo
assert limit(1/sin(x), x, pi, dir="-") is oo
assert limit(1/cos(x), x, pi/2, dir="+") is -oo
assert limit(1/cos(x), x, pi/2, dir="-") is oo
assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="+") is oo
assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="-") is -oo
assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="+") is -oo
assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="-") is oo
# test bi-directional limits
assert limit(sin(x)/x, x, 0, dir="+-") == 1
assert limit(x**2, x, 0, dir="+-") == 0
assert limit(1/x**2, x, 0, dir="+-") is oo
# test failing bi-directional limits
assert limit(1/x, x, 0, dir="+-") is zoo
# approaching 0
# from dir="+"
assert limit(1 + 1/x, x, 0) is oo
# from dir='-'
# Add
assert limit(1 + 1/x, x, 0, dir='-') is -oo
# Pow
assert limit(x**(-2), x, 0, dir='-') is oo
assert limit(x**(-3), x, 0, dir='-') is -oo
assert limit(1/sqrt(x), x, 0, dir='-') == (-oo)*I
assert limit(x**2, x, 0, dir='-') == 0
assert limit(sqrt(x), x, 0, dir='-') == 0
assert limit(x**-pi, x, 0, dir='-') == oo*sign((-1)**(-pi))
assert limit((1 + cos(x))**oo, x, 0) == Limit((cos(x) + 1)**oo, x, 0)
def test_basic2():
assert limit(x**x, x, 0, dir="+") == 1
assert limit((exp(x) - 1)/x, x, 0) == 1
assert limit(1 + 1/x, x, oo) == 1
assert limit(-exp(1/x), x, oo) == -1
assert limit(x + exp(-x), x, oo) is oo
assert limit(x + exp(-x**2), x, oo) is oo
assert limit(x + exp(-exp(x)), x, oo) is oo
assert limit(13 + 1/x - exp(-x), x, oo) == 13
def test_basic3():
assert limit(1/x, x, 0, dir="+") is oo
assert limit(1/x, x, 0, dir="-") is -oo
def test_basic4():
assert limit(2*x + y*x, x, 0) == 0
assert limit(2*x + y*x, x, 1) == 2 + y
assert limit(2*x**8 + y*x**(-3), x, -2) == 512 - y/8
assert limit(sqrt(x + 1) - sqrt(x), x, oo) == 0
assert integrate(1/(x**3 + 1), (x, 0, oo)) == 2*pi*sqrt(3)/9
def test_basic5():
class my(Function):
@classmethod
def eval(cls, arg):
if arg is S.Infinity:
return S.NaN
assert limit(my(x), x, oo) == Limit(my(x), x, oo)
def test_issue_3885():
assert limit(x*y + x*z, z, 2) == x*y + 2*x
def test_Limit():
assert Limit(sin(x)/x, x, 0) != 1
assert Limit(sin(x)/x, x, 0).doit() == 1
assert Limit(x, x, 0, dir='+-').args == (x, x, 0, Symbol('+-'))
def test_floor():
assert limit(floor(x), x, -2, "+") == -2
assert limit(floor(x), x, -2, "-") == -3
assert limit(floor(x), x, -1, "+") == -1
assert limit(floor(x), x, -1, "-") == -2
assert limit(floor(x), x, 0, "+") == 0
assert limit(floor(x), x, 0, "-") == -1
assert limit(floor(x), x, 1, "+") == 1
assert limit(floor(x), x, 1, "-") == 0
assert limit(floor(x), x, 2, "+") == 2
assert limit(floor(x), x, 2, "-") == 1
assert limit(floor(x), x, 248, "+") == 248
assert limit(floor(x), x, 248, "-") == 247
# https://github.com/sympy/sympy/issues/14478
assert limit(x*floor(3/x)/2, x, 0, '+') == Rational(3, 2)
assert limit(floor(x + 1/2) - floor(x), x, oo) == AccumBounds(-0.5, 1.5)
def test_floor_requires_robust_assumptions():
assert limit(floor(sin(x)), x, 0, "+") == 0
assert limit(floor(sin(x)), x, 0, "-") == -1
assert limit(floor(cos(x)), x, 0, "+") == 0
assert limit(floor(cos(x)), x, 0, "-") == 0
assert limit(floor(5 + sin(x)), x, 0, "+") == 5
assert limit(floor(5 + sin(x)), x, 0, "-") == 4
assert limit(floor(5 + cos(x)), x, 0, "+") == 5
assert limit(floor(5 + cos(x)), x, 0, "-") == 5
def test_ceiling():
assert limit(ceiling(x), x, -2, "+") == -1
assert limit(ceiling(x), x, -2, "-") == -2
assert limit(ceiling(x), x, -1, "+") == 0
assert limit(ceiling(x), x, -1, "-") == -1
assert limit(ceiling(x), x, 0, "+") == 1
assert limit(ceiling(x), x, 0, "-") == 0
assert limit(ceiling(x), x, 1, "+") == 2
assert limit(ceiling(x), x, 1, "-") == 1
assert limit(ceiling(x), x, 2, "+") == 3
assert limit(ceiling(x), x, 2, "-") == 2
assert limit(ceiling(x), x, 248, "+") == 249
assert limit(ceiling(x), x, 248, "-") == 248
# https://github.com/sympy/sympy/issues/14478
assert limit(x*ceiling(3/x)/2, x, 0, '+') == Rational(3, 2)
assert limit(ceiling(x + 1/2) - ceiling(x), x, oo) == AccumBounds(-0.5, 1.5)
def test_ceiling_requires_robust_assumptions():
assert limit(ceiling(sin(x)), x, 0, "+") == 1
assert limit(ceiling(sin(x)), x, 0, "-") == 0
assert limit(ceiling(cos(x)), x, 0, "+") == 1
assert limit(ceiling(cos(x)), x, 0, "-") == 1
assert limit(ceiling(5 + sin(x)), x, 0, "+") == 6
assert limit(ceiling(5 + sin(x)), x, 0, "-") == 5
assert limit(ceiling(5 + cos(x)), x, 0, "+") == 6
assert limit(ceiling(5 + cos(x)), x, 0, "-") == 6
def test_atan():
x = Symbol("x", real=True)
assert limit(atan(x)*sin(1/x), x, 0) == 0
assert limit(atan(x) + sqrt(x + 1) - sqrt(x), x, oo) == pi/2
def test_abs():
assert limit(abs(x), x, 0) == 0
assert limit(abs(sin(x)), x, 0) == 0
assert limit(abs(cos(x)), x, 0) == 1
assert limit(abs(sin(x + 1)), x, 0) == sin(1)
def test_heuristic():
x = Symbol("x", real=True)
assert heuristics(sin(1/x) + atan(x), x, 0, '+') == AccumBounds(-1, 1)
assert limit(log(2 + sqrt(atan(x))*sqrt(sin(1/x))), x, 0) == log(2)
def test_issue_3871():
z = Symbol("z", positive=True)
f = -1/z*exp(-z*x)
assert limit(f, x, oo) == 0
assert f.limit(x, oo) == 0
def test_exponential():
n = Symbol('n')
x = Symbol('x', real=True)
assert limit((1 + x/n)**n, n, oo) == exp(x)
assert limit((1 + x/(2*n))**n, n, oo) == exp(x/2)
assert limit((1 + x/(2*n + 1))**n, n, oo) == exp(x/2)
assert limit(((x - 1)/(x + 1))**x, x, oo) == exp(-2)
assert limit(1 + (1 + 1/x)**x, x, oo) == 1 + S.Exp1
assert limit((2 + 6*x)**x/(6*x)**x, x, oo) == exp(S('1/3'))
def test_exponential2():
n = Symbol('n')
assert limit((1 + x/(n + sin(n)))**n, n, oo) == exp(x)
def test_doit():
f = Integral(2 * x, x)
l = Limit(f, x, oo)
assert l.doit() is oo
def test_series_AccumBounds():
assert limit(sin(k) - sin(k + 1), k, oo) == AccumBounds(-2, 2)
assert limit(cos(k) - cos(k + 1) + 1, k, oo) == AccumBounds(-1, 3)
# not the exact bound
assert limit(sin(k) - sin(k)*cos(k), k, oo) == AccumBounds(-2, 2)
# test for issue #9934
t1 = Mul(S.Half, 1/(-1 + cos(1)), Add(AccumBounds(-3, 1), cos(1)))
assert limit(simplify(Sum(cos(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t1
t2 = Mul(S.Half, Add(AccumBounds(-2, 2), sin(1)), 1/(-cos(1) + 1))
assert limit(simplify(Sum(sin(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t2
assert limit(frac(x)**x, x, oo) == AccumBounds(0, oo) # wolfram gives (0, 1)
assert limit(((sin(x) + 1)/2)**x, x, oo) == AccumBounds(0, oo) # wolfram says 0
@XFAIL
def test_doit2():
f = Integral(2 * x, x)
l = Limit(f, x, oo)
# limit() breaks on the contained Integral.
assert l.doit(deep=False) == l
def test_issue_2929():
assert limit((x * exp(x))/(exp(x) - 1), x, -oo) == 0
def test_issue_3792():
assert limit((1 - cos(x))/x**2, x, S.Half) == 4 - 4*cos(S.Half)
assert limit(sin(sin(x + 1) + 1), x, 0) == sin(1 + sin(1))
assert limit(abs(sin(x + 1) + 1), x, 0) == 1 + sin(1)
def test_issue_4090():
assert limit(1/(x + 3), x, 2) == Rational(1, 5)
assert limit(1/(x + pi), x, 2) == S.One/(2 + pi)
assert limit(log(x)/(x**2 + 3), x, 2) == log(2)/7
assert limit(log(x)/(x**2 + pi), x, 2) == log(2)/(4 + pi)
def test_issue_4547():
assert limit(cot(x), x, 0, dir='+') is oo
assert limit(cot(x), x, pi/2, dir='+') == 0
def test_issue_5164():
assert limit(x**0.5, x, oo) == oo**0.5 is oo
assert limit(x**0.5, x, 16) == S(16)**0.5
assert limit(x**0.5, x, 0) == 0
assert limit(x**(-0.5), x, oo) == 0
assert limit(x**(-0.5), x, 4) == S(4)**(-0.5)
def test_issue_5383():
func = (1.0 * 1 + 1.0 * x)**(1.0 * 1 / x)
assert limit(func, x, 0) == E.n()
def test_issue_14793():
expr = ((x + S(1)/2) * log(x) - x + log(2*pi)/2 - \
log(factorial(x)) + S(1)/(12*x))*x**3
assert limit(expr, x, oo) == S(1)/360
def test_issue_5183():
# using list(...) so py.test can recalculate values
tests = list(cartes([x, -x],
[-1, 1],
[2, 3, S.Half, Rational(2, 3)],
['-', '+']))
results = (oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3), oo,
0, 0, 0, 0, 0, 0, 0, 0,
oo, oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3),
0, 0, 0, 0, 0, 0, 0, 0)
assert len(tests) == len(results)
for i, (args, res) in enumerate(zip(tests, results)):
y, s, e, d = args
eq = y**(s*e)
try:
assert limit(eq, x, 0, dir=d) == res
except AssertionError:
if 0: # change to 1 if you want to see the failing tests
print()
print(i, res, eq, d, limit(eq, x, 0, dir=d))
else:
assert None
def test_issue_5184():
assert limit(sin(x)/x, x, oo) == 0
assert limit(atan(x), x, oo) == pi/2
assert limit(gamma(x), x, oo) is oo
assert limit(cos(x)/x, x, oo) == 0
assert limit(gamma(x), x, S.Half) == sqrt(pi)
r = Symbol('r', real=True)
assert limit(r*sin(1/r), r, 0) == 0
def test_issue_5229():
assert limit((1 + y)**(1/y) - S.Exp1, y, 0) == 0
def test_issue_4546():
# using list(...) so py.test can recalculate values
tests = list(cartes([cot, tan],
[-pi/2, 0, pi/2, pi, pi*Rational(3, 2)],
['-', '+']))
results = (0, 0, -oo, oo, 0, 0, -oo, oo, 0, 0,
oo, -oo, 0, 0, oo, -oo, 0, 0, oo, -oo)
assert len(tests) == len(results)
for i, (args, res) in enumerate(zip(tests, results)):
f, l, d = args
eq = f(x)
try:
assert limit(eq, x, l, dir=d) == res
except AssertionError:
if 0: # change to 1 if you want to see the failing tests
print()
print(i, res, eq, l, d, limit(eq, x, l, dir=d))
else:
assert None
def test_issue_3934():
assert limit((1 + x**log(3))**(1/x), x, 0) == 1
assert limit((5**(1/x) + 3**(1/x))**x, x, 0) == 5
def test_calculate_series():
# needs gruntz calculate_series to go to n = 32
assert limit(x**Rational(77, 3)/(1 + x**Rational(77, 3)), x, oo) == 1
# needs gruntz calculate_series to go to n = 128
assert limit(x**101.1/(1 + x**101.1), x, oo) == 1
def test_issue_5955():
assert limit((x**16)/(1 + x**16), x, oo) == 1
assert limit((x**100)/(1 + x**100), x, oo) == 1
assert limit((x**1885)/(1 + x**1885), x, oo) == 1
assert limit((x**1000/((x + 1)**1000 + exp(-x))), x, oo) == 1
def test_newissue():
assert limit(exp(1/sin(x))/exp(cot(x)), x, 0) == 1
def test_extended_real_line():
assert limit(x - oo, x, oo) is -oo
assert limit(oo - x, x, -oo) is oo
assert limit(x**2/(x - 5) - oo, x, oo) is -oo
assert limit(1/(x + sin(x)) - oo, x, 0) is -oo
assert limit(oo/x, x, oo) is oo
assert limit(x - oo + 1/x, x, oo) is -oo
assert limit(x - oo + 1/x, x, 0) is -oo
@XFAIL
def test_order_oo():
x = Symbol('x', positive=True)
assert Order(x)*oo != Order(1, x)
assert limit(oo/(x**2 - 4), x, oo) is oo
def test_issue_5436():
raises(NotImplementedError, lambda: limit(exp(x*y), x, oo))
raises(NotImplementedError, lambda: limit(exp(-x*y), x, oo))
def test_Limit_dir():
raises(TypeError, lambda: Limit(x, x, 0, dir=0))
raises(ValueError, lambda: Limit(x, x, 0, dir='0'))
def test_polynomial():
assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, oo) == 1
assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, -oo) == 1
def test_rational():
assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, oo) == (z - 1)/(y*z)
assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, -oo) == (z - 1)/(y*z)
def test_issue_5740():
assert limit(log(x)*z - log(2*x)*y, x, 0) == oo*sign(y - z)
def test_issue_6366():
n = Symbol('n', integer=True, positive=True)
r = (n + 1)*x**(n + 1)/(x**(n + 1) - 1) - x/(x - 1)
assert limit(r, x, 1).cancel() == n/2
def test_factorial():
from sympy import factorial, E
f = factorial(x)
assert limit(f, x, oo) is oo
assert limit(x/f, x, oo) == 0
# see Stirling's approximation:
# https://en.wikipedia.org/wiki/Stirling's_approximation
assert limit(f/(sqrt(2*pi*x)*(x/E)**x), x, oo) == 1
assert limit(f, x, -oo) == factorial(-oo)
assert limit(f, x, x**2) == factorial(x**2)
assert limit(f, x, -x**2) == factorial(-x**2)
def test_issue_6560():
e = (5*x**3/4 - x*Rational(3, 4) + (y*(3*x**2/2 - S.Half) +
35*x**4/8 - 15*x**2/4 + Rational(3, 8))/(2*(y + 1)))
assert limit(e, y, oo) == 5*x**3/4 + 3*x**2/4 - 3*x/4 - Rational(1, 4)
@XFAIL
def test_issue_5172():
n = Symbol('n')
r = Symbol('r', positive=True)
c = Symbol('c')
p = Symbol('p', positive=True)
m = Symbol('m', negative=True)
expr = ((2*n*(n - r + 1)/(n + r*(n - r + 1)))**c +
(r - 1)*(n*(n - r + 2)/(n + r*(n - r + 1)))**c - n)/(n**c - n)
expr = expr.subs(c, c + 1)
raises(NotImplementedError, lambda: limit(expr, n, oo))
assert limit(expr.subs(c, m), n, oo) == 1
assert limit(expr.subs(c, p), n, oo).simplify() == \
(2**(p + 1) + r - 1)/(r + 1)**(p + 1)
def test_issue_7088():
a = Symbol('a')
assert limit(sqrt(x/(x + a)), x, oo) == 1
def test_branch_cuts():
assert limit(asin(I*x + 2), x, 0) == pi - asin(2)
assert limit(asin(I*x + 2), x, 0, '-') == asin(2)
assert limit(asin(I*x - 2), x, 0) == -asin(2)
assert limit(asin(I*x - 2), x, 0, '-') == -pi + asin(2)
assert limit(acos(I*x + 2), x, 0) == -acos(2)
assert limit(acos(I*x + 2), x, 0, '-') == acos(2)
assert limit(acos(I*x - 2), x, 0) == acos(-2)
assert limit(acos(I*x - 2), x, 0, '-') == 2*pi - acos(-2)
assert limit(atan(x + 2*I), x, 0) == I*atanh(2)
assert limit(atan(x + 2*I), x, 0, '-') == -pi + I*atanh(2)
assert limit(atan(x - 2*I), x, 0) == pi - I*atanh(2)
assert limit(atan(x - 2*I), x, 0, '-') == -I*atanh(2)
assert limit(atan(1/x), x, 0) == pi/2
assert limit(atan(1/x), x, 0, '-') == -pi/2
assert limit(atan(x), x, oo) == pi/2
assert limit(atan(x), x, -oo) == -pi/2
assert limit(acot(x + S(1)/2*I), x, 0) == pi - I*acoth(S(1)/2)
assert limit(acot(x + S(1)/2*I), x, 0, '-') == -I*acoth(S(1)/2)
assert limit(acot(x - S(1)/2*I), x, 0) == I*acoth(S(1)/2)
assert limit(acot(x - S(1)/2*I), x, 0, '-') == -pi + I*acoth(S(1)/2)
assert limit(acot(x), x, 0) == pi/2
assert limit(acot(x), x, 0, '-') == -pi/2
assert limit(asec(I*x + S(1)/2), x, 0) == asec(S(1)/2)
assert limit(asec(I*x + S(1)/2), x, 0, '-') == -asec(S(1)/2)
assert limit(asec(I*x - S(1)/2), x, 0) == 2*pi - asec(-S(1)/2)
assert limit(asec(I*x - S(1)/2), x, 0, '-') == asec(-S(1)/2)
assert limit(acsc(I*x + S(1)/2), x, 0) == acsc(S(1)/2)
assert limit(acsc(I*x + S(1)/2), x, 0, '-') == pi - acsc(S(1)/2)
assert limit(acsc(I*x - S(1)/2), x, 0) == -pi + acsc(S(1)/2)
assert limit(acsc(I*x - S(1)/2), x, 0, '-') == -acsc(S(1)/2)
assert limit(log(I*x - 1), x, 0) == I*pi
assert limit(log(I*x - 1), x, 0, '-') == -I*pi
assert limit(log(-I*x - 1), x, 0) == -I*pi
assert limit(log(-I*x - 1), x, 0, '-') == I*pi
assert limit(sqrt(I*x - 1), x, 0) == I
assert limit(sqrt(I*x - 1), x, 0, '-') == -I
assert limit(sqrt(-I*x - 1), x, 0) == -I
assert limit(sqrt(-I*x - 1), x, 0, '-') == I
assert limit(cbrt(I*x - 1), x, 0) == (-1)**(S(1)/3)
assert limit(cbrt(I*x - 1), x, 0, '-') == -(-1)**(S(2)/3)
assert limit(cbrt(-I*x - 1), x, 0) == -(-1)**(S(2)/3)
assert limit(cbrt(-I*x - 1), x, 0, '-') == (-1)**(S(1)/3)
def test_issue_6364():
a = Symbol('a')
e = z/(1 - sqrt(1 + z)*sin(a)**2 - sqrt(1 - z)*cos(a)**2)
assert limit(e, z, 0) == 2/(2*cos(a)**2 - 1)
def test_issue_4099():
a = Symbol('a')
assert limit(a/x, x, 0) == oo*sign(a)
assert limit(-a/x, x, 0) == -oo*sign(a)
assert limit(-a*x, x, oo) == -oo*sign(a)
assert limit(a*x, x, oo) == oo*sign(a)
def test_issue_4503():
dx = Symbol('dx')
assert limit((sqrt(1 + exp(x + dx)) - sqrt(1 + exp(x)))/dx, dx, 0) == \
exp(x)/(2*sqrt(exp(x) + 1))
def test_issue_8208():
assert limit(n**(Rational(1, 1e9) - 1), n, oo) == 0
def test_issue_8229():
assert limit((x**Rational(1, 4) - 2)/(sqrt(x) - 4)**Rational(2, 3), x, 16) == 0
def test_issue_8433():
d, t = symbols('d t', positive=True)
assert limit(erf(1 - t/d), t, oo) == -1
def test_issue_8481():
k = Symbol('k', integer=True, nonnegative=True)
lamda = Symbol('lamda', real=True, positive=True)
limit(lamda**k * exp(-lamda) / factorial(k), k, oo) == 0
def test_issue_8730():
assert limit(subfactorial(x), x, oo) is oo
def test_issue_9252():
n = Symbol('n', integer=True)
c = Symbol('c', positive=True)
assert limit((log(n))**(n/log(n)) / (1 + c)**n, n, oo) == 0
# limit should depend on the value of c
raises(NotImplementedError, lambda: limit((log(n))**(n/log(n)) / c**n, n, oo))
def test_issue_9449():
assert limit((Abs(x + y) - Abs(x - y))/(2*x), x, 0) == sign(y)
def test_issue_9558():
assert limit(sin(x)**15, x, 0, '-') == 0
def test_issue_10801():
# make sure limits work with binomial
assert limit(16**k / (k * binomial(2*k, k)**2), k, oo) == pi
def test_issue_10976():
s, x = symbols('s x', real=True)
assert limit(erf(s*x)/erf(s), s, 0) == x
def test_issue_9041():
assert limit(factorial(n) / ((n/exp(1))**n * sqrt(2*pi*n)), n, oo) == 1
def test_issue_9205():
x, y, a = symbols('x, y, a')
assert Limit(x, x, a).free_symbols == {a}
assert Limit(x, x, a, '-').free_symbols == {a}
assert Limit(x + y, x + y, a).free_symbols == {a}
assert Limit(-x**2 + y, x**2, a).free_symbols == {y, a}
def test_issue_9471():
assert limit(((27**(log(n,3)))/n**3),n,oo) == 1
assert limit(((27**(log(n,3)+1))/n**3),n,oo) == 27
def test_issue_11496():
assert limit(erfc(log(1/x)), x, oo) == 2
def test_issue_11879():
assert simplify(limit(((x+y)**n-x**n)/y, y, 0)) == n*x**(n-1)
def test_limit_with_Float():
k = symbols("k")
assert limit(1.0 ** k, k, oo) == 1
assert limit(0.3*1.0**k, k, oo) == Float(0.3)
def test_issue_10610():
assert limit(3**x*3**(-x - 1)*(x + 1)**2/x**2, x, oo) == Rational(1, 3)
def test_issue_6599():
assert limit((n + cos(n))/n, n, oo) == 1
def test_issue_12398():
assert limit(Abs(log(x)/x**3), x, oo) == 0
assert limit(x*(Abs(log(x)/x**3)/Abs(log(x + 1)/(x + 1)**3) - 1), x, oo) == 3
def test_issue_12555():
assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, -oo) == 2
assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, oo) is oo
def test_issue_12769():
r, z, x = symbols('r z x', real=True)
a, b, s0, K, F0, s, T = symbols('a b s0 K F0 s T', positive=True, real=True)
fx = (F0**b*K**b*r*s0 - sqrt((F0**2*K**(2*b)*a**2*(b - 1) + \
F0**(2*b)*K**2*a**2*(b - 1) + F0**(2*b)*K**(2*b)*s0**2*(b - 1)*(b**2 - 2*b + 1) - \
2*F0**(2*b)*K**(b + 1)*a*r*s0*(b**2 - 2*b + 1) + \
2*F0**(b + 1)*K**(2*b)*a*r*s0*(b**2 - 2*b + 1) - \
2*F0**(b + 1)*K**(b + 1)*a**2*(b - 1))/((b - 1)*(b**2 - 2*b + 1))))*(b*r - b - r + 1)
assert fx.subs(K, F0).factor(deep=True) == limit(fx, K, F0).factor(deep=True)
def test_issue_13332():
assert limit(sqrt(30)*5**(-5*x - 1)*(46656*x)**x*(5*x + 2)**(5*x + 5*S.Half) *
(6*x + 2)**(-6*x - 5*S.Half), x, oo) == Rational(25, 36)
def test_issue_12564():
assert limit(x**2 + x*sin(x) + cos(x), x, -oo) is oo
assert limit(x**2 + x*sin(x) + cos(x), x, oo) is oo
assert limit(((x + cos(x))**2).expand(), x, oo) is oo
assert limit(((x + sin(x))**2).expand(), x, oo) is oo
assert limit(((x + cos(x))**2).expand(), x, -oo) is oo
assert limit(((x + sin(x))**2).expand(), x, -oo) is oo
def test_issue_14456():
raises(NotImplementedError, lambda: Limit(exp(x), x, zoo).doit())
raises(NotImplementedError, lambda: Limit(x**2/(x+1), x, zoo).doit())
def test_issue_14411():
assert limit(3*sec(4*pi*x - x/3), x, 3*pi/(24*pi - 2)) is -oo
def test_issue_13382():
assert limit(x*(((x + 1)**2 + 1)/(x**2 + 1) - 1), x, oo) == 2
def test_issue_13403():
assert limit(x*(-1 + (x + log(x + 1) + 1)/(x + log(x))), x ,oo) == 1
def test_issue_13416():
assert limit((-x**3*log(x)**3 + (x - 1)*(x + 1)**2*log(x + 1)**3)/(x**2*log(x)**3), x ,oo) == 1
def test_issue_13462():
assert limit(n**2*(2*n*(-(1 - 1/(2*n))**x + 1) - x - (-x**2/4 + x/4)/n), n, oo) == x*(x - 2)*(x - 1)/24
def test_issue_13750():
a = Symbol('a')
assert limit(erf(a - x), x, oo) == -1
assert limit(erf(sqrt(x) - x), x, oo) == -1
def test_issue_14514():
assert limit((1/(log(x)**log(x)))**(1/x), x, oo) == 1
def test_issue_14574():
assert limit(sqrt(x)*cos(x - x**2) / (x + 1), x, oo) == 0
def test_issue_10102():
assert limit(fresnels(x), x, oo) == S.Half
assert limit(3 + fresnels(x), x, oo) == 3 + S.Half
assert limit(5*fresnels(x), x, oo) == Rational(5, 2)
assert limit(fresnelc(x), x, oo) == S.Half
assert limit(fresnels(x), x, -oo) == Rational(-1, 2)
assert limit(4*fresnelc(x), x, -oo) == -2
def test_issue_14377():
raises(NotImplementedError, lambda: limit(exp(I*x)*sin(pi*x), x, oo))
def test_issue_15146():
e = (x/2) * (-2*x**3 - 2*(x**3 - 1) * x**2 * digamma(x**3 + 1) + \
2*(x**3 - 1) * x**2 * digamma(x**3 + x + 1) + x + 3)
assert limit(e, x, oo) == S(1)/3
def test_issue_15202():
e = (2**x*(2 + 2**(-x)*(-2*2**x + x + 2))/(x + 1))**(x + 1)
assert limit(e, x, oo) == exp(1)
e = (log(x, 2)**7 + 10*x*factorial(x) + 5**x) / (factorial(x + 1) + 3*factorial(x) + 10**x)
assert limit(e, x, oo) == 10
def test_issue_15282():
assert limit((x**2000 - (x + 1)**2000) / x**1999, x, oo) == -2000
def test_issue_15984():
assert limit((-x + log(exp(x) + 1))/x, x, oo, dir='-').doit() == 0
def test_issue_13571():
assert limit(uppergamma(x, 1) / gamma(x), x, oo) == 1
def test_issue_13575():
assert limit(acos(erfi(x)), x, 1).cancel() == acos(-I*erf(I))
def test_issue_17325():
assert Limit(sin(x)/x, x, 0, dir="+-").doit() == 1
assert Limit(x**2, x, 0, dir="+-").doit() == 0
assert Limit(1/x**2, x, 0, dir="+-").doit() is oo
assert Limit(1/x, x, 0, dir="+-").doit() is zoo
def test_issue_10978():
assert LambertW(x).limit(x, 0) == 0
def test_issue_14313_comment():
assert limit(floor(n/2), n, oo) is oo
@XFAIL
def test_issue_15323():
d = ((1 - 1/x)**x).diff(x)
assert limit(d, x, 1, dir='+') == 1
def test_issue_12571():
assert limit(-LambertW(-log(x))/log(x), x, 1) == 1
def test_issue_14590():
assert limit((x**3*((x + 1)/x)**x)/((x + 1)*(x + 2)*(x + 3)), x, oo) == exp(1)
def test_issue_14393():
a, b = symbols('a b')
assert limit((x**b - y**b)/(x**a - y**a), x, y) == b*y**(-a)*y**b/a
def test_issue_14556():
assert limit(factorial(n + 1)**(1/(n + 1)) - factorial(n)**(1/n), n, oo) == exp(-1)
def test_issue_14811():
assert limit(((1 + ((S(2)/3)**(x + 1)))**(2**x))/(2**((S(4)/3)**(x - 1))), x, oo) == oo
def test_issue_14874():
assert limit(besselk(0, x), x, oo) == 0
def test_issue_16222():
assert limit(exp(x), x, 1000000000) == exp(1000000000)
def test_issue_16714():
assert limit(((x**(x + 1) + (x + 1)**x) / x**(x + 1))**x, x, oo) == exp(exp(1))
def test_issue_16722():
z = symbols('z', positive=True)
assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1)
z = symbols('z', positive=True, integer=True)
assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1)
def test_issue_17431():
assert limit(((n + 1) + 1) / (((n + 1) + 2) * factorial(n + 1)) *
(n + 2) * factorial(n) / (n + 1), n, oo) == 0
assert limit((n + 2)**2*factorial(n)/((n + 1)*(n + 3)*factorial(n + 1))
, n, oo) == 0
assert limit((n + 1) * factorial(n) / (n * factorial(n + 1)), n, oo) == 0
def test_issue_17671():
assert limit(Ei(-log(x)) - log(log(x))/x, x, 1) == EulerGamma
def test_issue_17751():
a, b, c, x = symbols('a b c x', positive=True)
assert limit((a + 1)*x - sqrt((a + 1)**2*x**2 + b*x + c), x, oo) == -b/(2*a + 2)
def test_issue_17792():
assert limit(factorial(n)/sqrt(n)*(exp(1)/n)**n, n, oo) == sqrt(2)*sqrt(pi)
def test_issue_18118():
assert limit(sign(sin(x)), x, 0, "-") == -1
assert limit(sign(sin(x)), x, 0, "+") == 1
def test_issue_18306():
assert limit(sin(sqrt(x))/sqrt(sin(x)), x, 0, '+') == 1
def test_issue_18378():
assert limit(log(exp(3*x) + x)/log(exp(x) + x**100), x, oo) == 3
def test_issue_18399():
assert limit((1 - S(1)/2*x)**(3*x), x, oo) is zoo
assert limit((-x)**x, x, oo) is zoo
def test_issue_18442():
assert limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-') == Limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-')
def test_issue_18452():
assert limit(abs(log(x))**x, x, 0) == 1
assert limit(abs(log(x))**x, x, 0, "-") == 1
def test_issue_18482():
assert limit((2*exp(3*x)/(exp(2*x) + 1))**(1/x), x, oo) == exp(1)
def test_issue_18501():
assert limit(Abs(log(x - 1)**3 - 1), x, 1, '+') == oo
def test_issue_18508():
assert limit(sin(x)/sqrt(1-cos(x)), x, 0) == sqrt(2)
assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='+') == sqrt(2)
assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='-') == -sqrt(2)
def test_issue_18969():
a, b = symbols('a b', positive=True)
assert limit(LambertW(a), a, b) == LambertW(b)
assert limit(exp(LambertW(a)), a, b) == exp(LambertW(b))
def test_issue_18992():
assert limit(n/(factorial(n)**(1/n)), n, oo) == exp(1)
def test_issue_18997():
assert limit(Abs(log(x)), x, 0) == oo
assert limit(Abs(log(Abs(x))), x, 0) == oo
def test_issue_19026():
x = Symbol('x', positive=True)
assert limit(Abs(log(x) + 1)/log(x), x, oo) == 1
def test_issue_19067():
x = Symbol('x')
assert limit(gamma(x)/(gamma(x - 1)*gamma(x + 2)), x, 0) == -1
def test_issue_19586():
assert limit(x**(2**x*3**(-x)), x, oo) == 1
def test_issue_13715():
n = Symbol('n')
p = Symbol('p', zero=True)
assert limit(n + p, n, 0) == 0
def test_issue_15055():
assert limit(n**3*((-n - 1)*sin(1/n) + (n + 2)*sin(1/(n + 1)))/(-n + 1), n, oo) == 1
def test_issue_16708():
m, vi = symbols('m vi', positive=True)
B, ti, d = symbols('B ti d')
assert limit((B*ti*vi - sqrt(m)*sqrt(-2*B*d*vi + m*(vi)**2) + m*vi)/(B*vi), B, 0) == (d + ti*vi)/vi
def test_issue_19739():
assert limit((-S(1)/4)**x, x, oo) == 0
def test_issue_19766():
assert limit(2**(-x)*sqrt(4**(x + 1) + 1), x, oo) == 2
def test_issue_19770():
m = Symbol('m')
# the result is not 0 for non-real m
assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-')
m = Symbol('m', real=True)
# can be improved to give the correct result 0
assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-')
m = Symbol('m', nonzero=True)
assert limit(cos(m*x), x, oo) == AccumBounds(-1, 1)
assert limit(cos(m*x)/x, x, oo) == 0
def test_issue_7535():
assert limit(tan(x)/sin(tan(x)), x, pi/2) == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+')
assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='-')
assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-')
assert limit(sin(tan(x)),x,pi/2) == AccumBounds(-1, 1)
assert -oo*(1/sin(-oo)) == AccumBounds(-oo, oo)
assert oo*(1/sin(oo)) == AccumBounds(-oo, oo)
assert oo*(1/sin(-oo)) == AccumBounds(-oo, oo)
assert -oo*(1/sin(oo)) == AccumBounds(-oo, oo)
def test_issue_20704():
assert limit(x*(Abs(1/x + y) - Abs(y - 1/x))/2, x, 0) == 0
def test_issue_21038():
assert limit(sin(pi*x)/(3*x - 12), x, 4) == pi/3
def test_issue_21550():
r = (sqrt(5) - 1)/2
assert limit((x - r)/(x**2 + x - 1), x, r) == (-1 + sqrt(5))/(5 - sqrt(5))
|
baf80339e06baf0b95d6bf5f030476660ac95ce88a16f2c3f4a039901c65378f | from sympy import (residue, Symbol, Function, sin, I, exp, log, pi, S,
factorial, sqrt, Rational, tan, cot, tanh)
from sympy.testing.pytest import XFAIL, raises
from sympy.abc import x, z, a, s
def test_basic1():
assert residue(1/x, x, 0) == 1
assert residue(-2/x, x, 0) == -2
assert residue(81/x, x, 0) == 81
assert residue(1/x**2, x, 0) == 0
assert residue(0, x, 0) == 0
assert residue(5, x, 0) == 0
assert residue(x, x, 0) == 0
assert residue(x**2, x, 0) == 0
def test_basic2():
assert residue(1/x, x, 1) == 0
assert residue(-2/x, x, 1) == 0
assert residue(81/x, x, -1) == 0
assert residue(1/x**2, x, 1) == 0
assert residue(0, x, 1) == 0
assert residue(5, x, 1) == 0
assert residue(x, x, 1) == 0
assert residue(x**2, x, 5) == 0
def test_f():
f = Function("f")
assert residue(f(x)/x**5, x, 0) == f(x).diff(x, 4).subs(x, 0)/24
def test_functions():
assert residue(1/sin(x), x, 0) == 1
assert residue(2/sin(x), x, 0) == 2
assert residue(1/sin(x)**2, x, 0) == 0
assert residue(1/sin(x)**5, x, 0) == Rational(3, 8)
def test_expressions():
assert residue(1/(x + 1), x, 0) == 0
assert residue(1/(x + 1), x, -1) == 1
assert residue(1/(x**2 + 1), x, -1) == 0
assert residue(1/(x**2 + 1), x, I) == -I/2
assert residue(1/(x**2 + 1), x, -I) == I/2
assert residue(1/(x**4 + 1), x, 0) == 0
assert residue(1/(x**4 + 1), x, exp(I*pi/4)).equals(-(Rational(1, 4) + I/4)/sqrt(2))
assert residue(1/(x**2 + a**2)**2, x, a*I) == -I/4/a**3
@XFAIL
def test_expressions_failing():
n = Symbol('n', integer=True, positive=True)
assert residue(exp(z)/(z - pi*I/4*a)**n, z, I*pi*a) == \
exp(I*pi*a/4)/factorial(n - 1)
def test_NotImplemented():
raises(NotImplementedError, lambda: residue(exp(1/z), z, 0))
def test_bug():
assert residue(2**(z)*(s + z)*(1 - s - z)/z**2, z, 0) == \
1 + s*log(2) - s**2*log(2) - 2*s
def test_issue_5654():
assert residue(1/(x**2 + a**2)**2, x, a*I) == -I/(4*a**3)
def test_issue_6499():
assert residue(1/(exp(z) - 1), z, 0) == 1
def test_issue_14037():
assert residue(sin(x**50)/x**51, x, 0) == 1
def test_issue_21176():
f = x**2*cot(pi*x)/(x**4 + 1)
assert residue(f, x, -sqrt(2)/2 - sqrt(2)*I/2).together() == \
sqrt(2)*(1 - I)/(8*tan(sqrt(2)*pi/2 + sqrt(2)*I*pi/2))
def test_issue_21177():
r = -sqrt(3)*tanh(sqrt(3)*pi/2)/3
a = residue(cot(pi*x)/((x - 1)*(x - 2) + 1), x, S(3)/2 - sqrt(3)*I/2)
b = residue(cot(pi*x)/(x**2 - 3*x + 3), x, S(3)/2 - sqrt(3)*I/2)
assert a == r
assert (b - a).cancel() == 0
|
0c3e4552fca2aa27fe655d3d8c73021e26bbc53f9f6e9c31031448d8ec688061 | from sympy import (Symbol, Rational, ln, exp, log, sqrt, E, O, pi, I, sinh,
sin, cosh, cos, tanh, coth, asinh, acosh, atanh, acoth, tan, cot, Integer,
PoleError, floor, ceiling, asin, symbols, limit, sign, cbrt,
Derivative, S)
from sympy.abc import x, y, z
from sympy.testing.pytest import raises, XFAIL
def test_simple_1():
assert x.nseries(x, n=5) == x
assert y.nseries(x, n=5) == y
assert (1/(x*y)).nseries(y, n=5) == 1/(x*y)
assert Rational(3, 4).nseries(x, n=5) == Rational(3, 4)
assert x.nseries() == x
def test_mul_0():
assert (x*ln(x)).nseries(x, n=5) == x*ln(x)
def test_mul_1():
assert (x*ln(2 + x)).nseries(x, n=5) == x*log(2) + x**2/2 - x**3/8 + \
x**4/24 + O(x**5)
assert (x*ln(1 + x)).nseries(
x, n=5) == x**2 - x**3/2 + x**4/3 + O(x**5)
def test_pow_0():
assert (x**2).nseries(x, n=5) == x**2
assert (1/x).nseries(x, n=5) == 1/x
assert (1/x**2).nseries(x, n=5) == 1/x**2
assert (x**Rational(2, 3)).nseries(x, n=5) == (x**Rational(2, 3))
assert (sqrt(x)**3).nseries(x, n=5) == (sqrt(x)**3)
def test_pow_1():
assert ((1 + x)**2).nseries(x, n=5) == x**2 + 2*x + 1
# https://github.com/sympy/sympy/issues/21075
assert ((sqrt(x) + 1)**2).nseries(x) == 2*sqrt(x) + x + 1
assert ((sqrt(x) + cbrt(x))**2).nseries(x) == 2*x**Rational(5, 6)\
+ x**Rational(2, 3) + x
def test_geometric_1():
assert (1/(1 - x)).nseries(x, n=5) == 1 + x + x**2 + x**3 + x**4 + O(x**5)
assert (x/(1 - x)).nseries(x, n=6) == x + x**2 + x**3 + x**4 + x**5 + O(x**6)
assert (x**3/(1 - x)).nseries(x, n=8) == x**3 + x**4 + x**5 + x**6 + \
x**7 + O(x**8)
def test_sqrt_1():
assert sqrt(1 + x).nseries(x, n=5) == 1 + x/2 - x**2/8 + x**3/16 - 5*x**4/128 + O(x**5)
def test_exp_1():
assert exp(x).nseries(x, n=5) == 1 + x + x**2/2 + x**3/6 + x**4/24 + O(x**5)
assert exp(x).nseries(x, n=12) == 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + \
x**6/720 + x**7/5040 + x**8/40320 + x**9/362880 + x**10/3628800 + \
x**11/39916800 + O(x**12)
assert exp(1/x).nseries(x, n=5) == exp(1/x)
assert exp(1/(1 + x)).nseries(x, n=4) == \
(E*(1 - x - 13*x**3/6 + 3*x**2/2)).expand() + O(x**4)
assert exp(2 + x).nseries(x, n=5) == \
(exp(2)*(1 + x + x**2/2 + x**3/6 + x**4/24)).expand() + O(x**5)
def test_exp_sqrt_1():
assert exp(1 + sqrt(x)).nseries(x, n=3) == \
(exp(1)*(1 + sqrt(x) + x/2 + sqrt(x)*x/6)).expand() + O(sqrt(x)**3)
def test_power_x_x1():
assert (exp(x*ln(x))).nseries(x, n=4) == \
1 + x*log(x) + x**2*log(x)**2/2 + x**3*log(x)**3/6 + O(x**4*log(x)**4)
def test_power_x_x2():
assert (x**x).nseries(x, n=4) == \
1 + x*log(x) + x**2*log(x)**2/2 + x**3*log(x)**3/6 + O(x**4*log(x)**4)
def test_log_singular1():
assert log(1 + 1/x).nseries(x, n=5) == x - log(x) - x**2/2 + x**3/3 - \
x**4/4 + O(x**5)
def test_log_power1():
e = 1 / (1/x + x ** (log(3)/log(2)))
assert e.nseries(x, n=5) == -x**(log(3)/log(2) + 2) + x + O(x**5)
def test_log_series():
l = Symbol('l')
e = 1/(1 - log(x))
assert e.nseries(x, n=5, logx=l) == 1/(1 - l)
def test_log2():
e = log(-1/x)
assert e.nseries(x, n=5) == -log(x) + log(-1)
def test_log3():
l = Symbol('l')
e = 1/log(-1/x)
assert e.nseries(x, n=4, logx=l) == 1/(-l + log(-1))
def test_series1():
e = sin(x)
assert e.nseries(x, 0, 0) != 0
assert e.nseries(x, 0, 0) == O(1, x)
assert e.nseries(x, 0, 1) == O(x, x)
assert e.nseries(x, 0, 2) == x + O(x**2, x)
assert e.nseries(x, 0, 3) == x + O(x**3, x)
assert e.nseries(x, 0, 4) == x - x**3/6 + O(x**4, x)
e = (exp(x) - 1)/x
assert e.nseries(x, 0, 3) == 1 + x/2 + x**2/6 + O(x**3)
assert x.nseries(x, 0, 2) == x
@XFAIL
def test_series1_failing():
assert x.nseries(x, 0, 0) == O(1, x)
assert x.nseries(x, 0, 1) == O(x, x)
def test_seriesbug1():
assert (1/x).nseries(x, 0, 3) == 1/x
assert (x + 1/x).nseries(x, 0, 3) == x + 1/x
def test_series2x():
assert ((x + 1)**(-2)).nseries(x, 0, 4) == 1 - 2*x + 3*x**2 - 4*x**3 + O(x**4, x)
assert ((x + 1)**(-1)).nseries(x, 0, 4) == 1 - x + x**2 - x**3 + O(x**4, x)
assert ((x + 1)**0).nseries(x, 0, 3) == 1
assert ((x + 1)**1).nseries(x, 0, 3) == 1 + x
assert ((x + 1)**2).nseries(x, 0, 3) == x**2 + 2*x + 1
assert ((x + 1)**3).nseries(x, 0, 3) == 1 + 3*x + 3*x**2 + O(x**3)
assert (1/(1 + x)).nseries(x, 0, 4) == 1 - x + x**2 - x**3 + O(x**4, x)
assert (x + 3/(1 + 2*x)).nseries(x, 0, 4) == 3 - 5*x + 12*x**2 - 24*x**3 + O(x**4, x)
assert ((1/x + 1)**3).nseries(x, 0, 3) == 1 + 3/x + 3/x**2 + x**(-3)
assert (1/(1 + 1/x)).nseries(x, 0, 4) == x - x**2 + x**3 - O(x**4, x)
assert (1/(1 + 1/x**2)).nseries(x, 0, 6) == x**2 - x**4 + O(x**6, x)
def test_bug2(): # 1/log(0)*log(0) problem
w = Symbol("w")
e = (w**(-1) + w**(
-log(3)*log(2)**(-1)))**(-1)*(3*w**(-log(3)*log(2)**(-1)) + 2*w**(-1))
e = e.expand()
assert e.nseries(w, 0, 4).subs(w, 0) == 3
def test_exp():
e = (1 + x)**(1/x)
assert e.nseries(x, n=3) == exp(1) - x*exp(1)/2 + 11*exp(1)*x**2/24 + O(x**3)
def test_exp2():
w = Symbol("w")
e = w**(1 - log(x)/(log(2) + log(x)))
logw = Symbol("logw")
assert e.nseries(
w, 0, 1, logx=logw) == exp(logw*log(2)/(log(x) + log(2)))
def test_bug3():
e = (2/x + 3/x**2)/(1/x + 1/x**2)
assert e.nseries(x, n=3) == 3 - x + x**2 + O(x**3)
def test_generalexponent():
p = 2
e = (2/x + 3/x**p)/(1/x + 1/x**p)
assert e.nseries(x, 0, 3) == 3 - x + x**2 + O(x**3)
p = S.Half
e = (2/x + 3/x**p)/(1/x + 1/x**p)
assert e.nseries(x, 0, 2) == 2 - x + sqrt(x) + x**(S(3)/2) + O(x**2)
e = 1 + sqrt(x)
assert e.nseries(x, 0, 4) == 1 + sqrt(x)
# more complicated example
def test_genexp_x():
e = 1/(1 + sqrt(x))
assert e.nseries(x, 0, 2) == \
1 + x - sqrt(x) - sqrt(x)**3 + O(x**2, x)
# more complicated example
def test_genexp_x2():
p = Rational(3, 2)
e = (2/x + 3/x**p)/(1/x + 1/x**p)
assert e.nseries(x, 0, 3) == 3 + x + x**2 - sqrt(x) - x**(S(3)/2) - x**(S(5)/2) + O(x**3)
def test_seriesbug2():
w = Symbol("w")
#simple case (1):
e = ((2*w)/w)**(1 + w)
assert e.nseries(w, 0, 1) == 2 + O(w, w)
assert e.nseries(w, 0, 1).subs(w, 0) == 2
def test_seriesbug2b():
w = Symbol("w")
#test sin
e = sin(2*w)/w
assert e.nseries(w, 0, 3) == 2 - 4*w**2/3 + O(w**3)
def test_seriesbug2d():
w = Symbol("w", real=True)
e = log(sin(2*w)/w)
assert e.series(w, n=5) == log(2) - 2*w**2/3 - 4*w**4/45 + O(w**5)
def test_seriesbug2c():
w = Symbol("w", real=True)
#more complicated case, but sin(x)~x, so the result is the same as in (1)
e = (sin(2*w)/w)**(1 + w)
assert e.series(w, 0, 1) == 2 + O(w)
assert e.series(w, 0, 3) == 2 + 2*w*log(2) + \
w**2*(Rational(-4, 3) + log(2)**2) + O(w**3)
assert e.series(w, 0, 2).subs(w, 0) == 2
def test_expbug4():
x = Symbol("x", real=True)
assert (log(
sin(2*x)/x)*(1 + x)).series(x, 0, 2) == log(2) + x*log(2) + O(x**2, x)
assert exp(
log(sin(2*x)/x)*(1 + x)).series(x, 0, 2) == 2 + 2*x*log(2) + O(x**2)
assert exp(log(2) + O(x)).nseries(x, 0, 2) == 2 + O(x)
assert ((2 + O(x))**(1 + x)).nseries(x, 0, 2) == 2 + O(x)
def test_logbug4():
assert log(2 + O(x)).nseries(x, 0, 2) == log(2) + O(x, x)
def test_expbug5():
assert exp(log(1 + x)/x).nseries(x, n=3) == exp(1) + -exp(1)*x/2 + 11*exp(1)*x**2/24 + O(x**3)
assert exp(O(x)).nseries(x, 0, 2) == 1 + O(x)
def test_sinsinbug():
assert sin(sin(x)).nseries(x, 0, 8) == x - x**3/3 + x**5/10 - 8*x**7/315 + O(x**8)
def test_issue_3258():
a = x/(exp(x) - 1)
assert a.nseries(x, 0, 5) == 1 - x/2 - x**4/720 + x**2/12 + O(x**5)
def test_issue_3204():
x = Symbol("x", nonnegative=True)
f = sin(x**3)**Rational(1, 3)
assert f.nseries(x, 0, 17) == x - x**7/18 - x**13/3240 + O(x**17)
def test_issue_3224():
f = sqrt(1 - sqrt(y))
assert f.nseries(y, 0, 2) == 1 - sqrt(y)/2 - y/8 - sqrt(y)**3/16 + O(y**2)
def test_issue_3463():
from sympy import symbols
w, i = symbols('w,i')
r = log(5)/log(3)
p = w**(-1 + r)
e = 1/x*(-log(w**(1 + r)) + log(w + w**r))
e_ser = -r*log(w)/x + p/x - p**2/(2*x) + O(w)
assert e.nseries(w, n=1) == e_ser
def test_sin():
assert sin(8*x).nseries(x, n=4) == 8*x - 256*x**3/3 + O(x**4)
assert sin(x + y).nseries(x, n=1) == sin(y) + O(x)
assert sin(x + y).nseries(x, n=2) == sin(y) + cos(y)*x + O(x**2)
assert sin(x + y).nseries(x, n=5) == sin(y) + cos(y)*x - sin(y)*x**2/2 - \
cos(y)*x**3/6 + sin(y)*x**4/24 + O(x**5)
def test_issue_3515():
e = sin(8*x)/x
assert e.nseries(x, n=6) == 8 - 256*x**2/3 + 4096*x**4/15 + O(x**6)
def test_issue_3505():
e = sin(x)**(-4)*(sqrt(cos(x))*sin(x)**2 -
cos(x)**Rational(1, 3)*sin(x)**2)
assert e.nseries(x, n=9) == Rational(-1, 12) - 7*x**2/288 - \
43*x**4/10368 - 1123*x**6/2488320 + 377*x**8/29859840 + O(x**9)
def test_issue_3501():
a = Symbol("a")
e = x**(-2)*(x*sin(a + x) - x*sin(a))
assert e.nseries(x, n=6) == cos(a) - sin(a)*x/2 - cos(a)*x**2/6 + \
sin(a)*x**3/24 + O(x**4)
e = x**(-2)*(x*cos(a + x) - x*cos(a))
assert e.nseries(x, n=6) == -sin(a) - cos(a)*x/2 + sin(a)*x**2/6 + \
cos(a)*x**3/24 + O(x**4)
def test_issue_3502():
e = sin(5*x)/sin(2*x)
assert e.nseries(x, n=2) == Rational(5, 2) + O(x**2)
assert e.nseries(x, n=6) == \
Rational(5, 2) - 35*x**2/4 + 329*x**4/48 + O(x**6)
def test_issue_3503():
e = sin(2 + x)/(2 + x)
assert e.nseries(x, n=2) == sin(2)/2 + x*cos(2)/2 - x*sin(2)/4 + O(x**2)
def test_issue_3506():
e = (x + sin(3*x))**(-2)*(x*(x + sin(3*x)) - (x + sin(3*x))*sin(2*x))
assert e.nseries(x, n=7) == \
Rational(-1, 4) + 5*x**2/96 + 91*x**4/768 + 11117*x**6/129024 + O(x**7)
def test_issue_3508():
x = Symbol("x", real=True)
assert log(sin(x)).series(x, n=5) == log(x) - x**2/6 - x**4/180 + O(x**5)
e = -log(x) + x*(-log(x) + log(sin(2*x))) + log(sin(2*x))
assert e.series(x, n=5) == \
log(2) + log(2)*x - 2*x**2/3 - 2*x**3/3 - 4*x**4/45 + O(x**5)
def test_issue_3507():
e = x**(-4)*(x**2 - x**2*sqrt(cos(x)))
assert e.nseries(x, n=9) == \
Rational(1, 4) + x**2/96 + 19*x**4/5760 + 559*x**6/645120 + 29161*x**8/116121600 + O(x**9)
def test_issue_3639():
assert sin(cos(x)).nseries(x, n=5) == \
sin(1) - x**2*cos(1)/2 - x**4*sin(1)/8 + x**4*cos(1)/24 + O(x**5)
def test_hyperbolic():
assert sinh(x).nseries(x, n=6) == x + x**3/6 + x**5/120 + O(x**6)
assert cosh(x).nseries(x, n=5) == 1 + x**2/2 + x**4/24 + O(x**5)
assert tanh(x).nseries(x, n=6) == x - x**3/3 + 2*x**5/15 + O(x**6)
assert coth(x).nseries(x, n=6) == \
1/x - x**3/45 + x/3 + 2*x**5/945 + O(x**6)
assert asinh(x).nseries(x, n=6) == x - x**3/6 + 3*x**5/40 + O(x**6)
assert acosh(x).nseries(x, n=6) == \
pi*I/2 - I*x - 3*I*x**5/40 - I*x**3/6 + O(x**6)
assert atanh(x).nseries(x, n=6) == x + x**3/3 + x**5/5 + O(x**6)
assert acoth(x).nseries(x, n=6) == x + x**3/3 + x**5/5 + pi*I/2 + O(x**6)
def test_series2():
w = Symbol("w", real=True)
x = Symbol("x", real=True)
e = w**(-2)*(w*exp(1/x - w) - w*exp(1/x))
assert e.nseries(w, n=4) == -exp(1/x) + w*exp(1/x)/2 - w**2*exp(1/x)/6 + w**3*exp(1/x)/24 + O(w**4)
def test_series3():
w = Symbol("w", real=True)
e = w**(-6)*(w**3*tan(w) - w**3*sin(w))
assert e.nseries(w, n=8) == Integer(1)/2 + w**2/8 + 13*w**4/240 + 529*w**6/24192 + O(w**8)
def test_bug4():
w = Symbol("w")
e = x/(w**4 + x**2*w**4 + 2*x*w**4)*w**4
assert e.nseries(w, n=2).removeO().expand() in [x/(1 + 2*x + x**2),
1/(1 + x/2 + 1/x/2)/2, 1/x/(1 + 2/x + x**(-2))]
def test_bug5():
w = Symbol("w")
l = Symbol('l')
e = (-log(w) + log(1 + w*log(x)))**(-2)*w**(-2)*((-log(w) +
log(1 + x*w))*(-log(w) + log(1 + w*log(x)))*w - x*(-log(w) +
log(1 + w*log(x)))*w)
assert e.nseries(w, n=2, logx=l) == x/w/l + 1/w + O(1, w)
assert e.nseries(w, n=3, logx=l) == x/w/l + 1/w - x/l + 1/l*log(x) \
+ x*log(x)/l**2 + O(w)
def test_issue_4115():
assert (sin(x)/(1 - cos(x))).nseries(x, n=1) == 2/x + O(x)
assert (sin(x)**2/(1 - cos(x))).nseries(x, n=1) == 2 + O(x)
def test_pole():
raises(PoleError, lambda: sin(1/x).series(x, 0, 5))
raises(PoleError, lambda: sin(1 + 1/x).series(x, 0, 5))
raises(PoleError, lambda: (x*sin(1/x)).series(x, 0, 5))
def test_expsinbug():
assert exp(sin(x)).series(x, 0, 0) == O(1, x)
assert exp(sin(x)).series(x, 0, 1) == 1 + O(x)
assert exp(sin(x)).series(x, 0, 2) == 1 + x + O(x**2)
assert exp(sin(x)).series(x, 0, 3) == 1 + x + x**2/2 + O(x**3)
assert exp(sin(x)).series(x, 0, 4) == 1 + x + x**2/2 + O(x**4)
assert exp(sin(x)).series(x, 0, 5) == 1 + x + x**2/2 - x**4/8 + O(x**5)
def test_floor():
x = Symbol('x')
assert floor(x).series(x) == 0
assert floor(-x).series(x) == -1
assert floor(sin(x)).series(x) == 0
assert floor(sin(-x)).series(x) == -1
assert floor(x**3).series(x) == 0
assert floor(-x**3).series(x) == -1
assert floor(cos(x)).series(x) == 0
assert floor(cos(-x)).series(x) == 0
assert floor(5 + sin(x)).series(x) == 5
assert floor(5 + sin(-x)).series(x) == 4
assert floor(x).series(x, 2) == 2
assert floor(-x).series(x, 2) == -3
x = Symbol('x', negative=True)
assert floor(x + 1.5).series(x) == 1
def test_ceiling():
assert ceiling(x).series(x) == 1
assert ceiling(-x).series(x) == 0
assert ceiling(sin(x)).series(x) == 1
assert ceiling(sin(-x)).series(x) == 0
assert ceiling(1 - cos(x)).series(x) == 1
assert ceiling(1 - cos(-x)).series(x) == 1
assert ceiling(x).series(x, 2) == 3
assert ceiling(-x).series(x, 2) == -2
def test_abs():
a = Symbol('a')
assert abs(x).nseries(x, n=4) == x
assert abs(-x).nseries(x, n=4) == x
assert abs(x + 1).nseries(x, n=4) == x + 1
assert abs(sin(x)).nseries(x, n=4) == x - Rational(1, 6)*x**3 + O(x**4)
assert abs(sin(-x)).nseries(x, n=4) == x - Rational(1, 6)*x**3 + O(x**4)
assert abs(x - a).nseries(x, 1) == -a*sign(1 - a) + (x - 1)*sign(1 - a) + sign(1 - a)
def test_dir():
assert abs(x).series(x, 0, dir="+") == x
assert abs(x).series(x, 0, dir="-") == -x
assert floor(x + 2).series(x, 0, dir='+') == 2
assert floor(x + 2).series(x, 0, dir='-') == 1
assert floor(x + 2.2).series(x, 0, dir='-') == 2
assert ceiling(x + 2.2).series(x, 0, dir='-') == 3
assert sin(x + y).series(x, 0, dir='-') == sin(x + y).series(x, 0, dir='+')
def test_issue_3504():
a = Symbol("a")
e = asin(a*x)/x
assert e.series(x, 4, n=2).removeO() == \
(x - 4)*(a/(4*sqrt(-16*a**2 + 1)) - asin(4*a)/16) + asin(4*a)/4
def test_issue_4441():
a, b = symbols('a,b')
f = 1/(1 + a*x)
assert f.series(x, 0, 5) == 1 - a*x + a**2*x**2 - a**3*x**3 + \
a**4*x**4 + O(x**5)
f = 1/(1 + (a + b)*x)
assert f.series(x, 0, 3) == 1 + x*(-a - b)\
+ x**2*(a**2 + 2*a*b + b**2) + O(x**3)
def test_issue_4329():
assert tan(x).series(x, pi/2, n=3).removeO() == \
-pi/6 + x/3 - 1/(x - pi/2)
assert cot(x).series(x, pi, n=3).removeO() == \
-x/3 + pi/3 + 1/(x - pi)
assert limit(tan(x)**tan(2*x), x, pi/4) == exp(-1)
def test_issue_5183():
assert abs(x + x**2).series(n=1) == O(x)
assert abs(x + x**2).series(n=2) == x + O(x**2)
assert ((1 + x)**2).series(x, n=6) == x**2 + 2*x + 1
assert (1 + 1/x).series() == 1 + 1/x
assert Derivative(exp(x).series(), x).doit() == \
1 + x + x**2/2 + x**3/6 + x**4/24 + O(x**5)
def test_issue_5654():
a = Symbol('a')
assert (1/(x**2+a**2)**2).nseries(x, x0=I*a, n=0) == \
-I/(4*a**3*(-I*a + x)) - 1/(4*a**2*(-I*a + x)**2) + O(1, (x, I*a))
assert (1/(x**2+a**2)**2).nseries(x, x0=I*a, n=1) == 3/(16*a**4) \
-I/(4*a**3*(-I*a + x)) - 1/(4*a**2*(-I*a + x)**2) + O(-I*a + x, (x, I*a))
def test_issue_5925():
sx = sqrt(x + z).series(z, 0, 1)
sxy = sqrt(x + y + z).series(z, 0, 1)
s1, s2 = sx.subs(x, x + y), sxy
assert (s1 - s2).expand().removeO().simplify() == 0
sx = sqrt(x + z).series(z, 0, 1)
sxy = sqrt(x + y + z).series(z, 0, 1)
assert sxy.subs({x:1, y:2}) == sx.subs(x, 3)
def test_exp_2():
assert exp(x**3).nseries(x, 0, 14) == 1 + x**3 + x**6/2 + x**9/6 + x**12/24 + O(x**14)
|
92e1dce721d3d67c660b9afb971effc85221bdc9f027e51a0010d7544979dadb | from sympy import (
symbols, powsimp, MatrixSymbol, sqrt, pi, Mul, gamma, Function,
S, I, exp, simplify, sin, E, log, hyper, Symbol, Dummy, powdenest, root,
Rational, oo, signsimp)
from sympy.core.symbol import Str
from sympy.abc import x, y, z, a, b
def test_powsimp():
x, y, z, n = symbols('x,y,z,n')
f = Function('f')
assert powsimp( 4**x * 2**(-x) * 2**(-x) ) == 1
assert powsimp( (-4)**x * (-2)**(-x) * 2**(-x) ) == 1
assert powsimp(
f(4**x * 2**(-x) * 2**(-x)) ) == f(4**x * 2**(-x) * 2**(-x))
assert powsimp( f(4**x * 2**(-x) * 2**(-x)), deep=True ) == f(1)
assert exp(x)*exp(y) == exp(x)*exp(y)
assert powsimp(exp(x)*exp(y)) == exp(x + y)
assert powsimp(exp(x)*exp(y)*2**x*2**y) == (2*E)**(x + y)
assert powsimp(exp(x)*exp(y)*2**x*2**y, combine='exp') == \
exp(x + y)*2**(x + y)
assert powsimp(exp(x)*exp(y)*exp(2)*sin(x) + sin(y) + 2**x*2**y) == \
exp(2 + x + y)*sin(x) + sin(y) + 2**(x + y)
assert powsimp(sin(exp(x)*exp(y))) == sin(exp(x)*exp(y))
assert powsimp(sin(exp(x)*exp(y)), deep=True) == sin(exp(x + y))
assert powsimp(x**2*x**y) == x**(2 + y)
# This should remain factored, because 'exp' with deep=True is supposed
# to act like old automatic exponent combining.
assert powsimp((1 + E*exp(E))*exp(-E), combine='exp', deep=True) == \
(1 + exp(1 + E))*exp(-E)
assert powsimp((1 + E*exp(E))*exp(-E), deep=True) == \
(1 + exp(1 + E))*exp(-E)
assert powsimp((1 + E*exp(E))*exp(-E)) == (1 + exp(1 + E))*exp(-E)
assert powsimp((1 + E*exp(E))*exp(-E), combine='exp') == \
(1 + exp(1 + E))*exp(-E)
assert powsimp((1 + E*exp(E))*exp(-E), combine='base') == \
(1 + E*exp(E))*exp(-E)
x, y = symbols('x,y', nonnegative=True)
n = Symbol('n', real=True)
assert powsimp(y**n * (y/x)**(-n)) == x**n
assert powsimp(x**(x**(x*y)*y**(x*y))*y**(x**(x*y)*y**(x*y)), deep=True) \
== (x*y)**(x*y)**(x*y)
assert powsimp(2**(2**(2*x)*x), deep=False) == 2**(2**(2*x)*x)
assert powsimp(2**(2**(2*x)*x), deep=True) == 2**(x*4**x)
assert powsimp(
exp(-x + exp(-x)*exp(-x*log(x))), deep=False, combine='exp') == \
exp(-x + exp(-x)*exp(-x*log(x)))
assert powsimp(
exp(-x + exp(-x)*exp(-x*log(x))), deep=False, combine='exp') == \
exp(-x + exp(-x)*exp(-x*log(x)))
assert powsimp((x + y)/(3*z), deep=False, combine='exp') == (x + y)/(3*z)
assert powsimp((x/3 + y/3)/z, deep=True, combine='exp') == (x/3 + y/3)/z
assert powsimp(exp(x)/(1 + exp(x)*exp(y)), deep=True) == \
exp(x)/(1 + exp(x + y))
assert powsimp(x*y**(z**x*z**y), deep=True) == x*y**(z**(x + y))
assert powsimp((z**x*z**y)**x, deep=True) == (z**(x + y))**x
assert powsimp(x*(z**x*z**y)**x, deep=True) == x*(z**(x + y))**x
p = symbols('p', positive=True)
assert powsimp((1/x)**log(2)/x) == (1/x)**(1 + log(2))
assert powsimp((1/p)**log(2)/p) == p**(-1 - log(2))
# coefficient of exponent can only be simplified for positive bases
assert powsimp(2**(2*x)) == 4**x
assert powsimp((-1)**(2*x)) == (-1)**(2*x)
i = symbols('i', integer=True)
assert powsimp((-1)**(2*i)) == 1
assert powsimp((-1)**(-x)) != (-1)**x # could be 1/((-1)**x), but is not
# force=True overrides assumptions
assert powsimp((-1)**(2*x), force=True) == 1
# rational exponents allow combining of negative terms
w, n, m = symbols('w n m', negative=True)
e = i/a # not a rational exponent if `a` is unknown
ex = w**e*n**e*m**e
assert powsimp(ex) == m**(i/a)*n**(i/a)*w**(i/a)
e = i/3
ex = w**e*n**e*m**e
assert powsimp(ex) == (-1)**i*(-m*n*w)**(i/3)
e = (3 + i)/i
ex = w**e*n**e*m**e
assert powsimp(ex) == (-1)**(3*e)*(-m*n*w)**e
eq = x**(a*Rational(2, 3))
# eq != (x**a)**(2/3) (try x = -1 and a = 3 to see)
assert powsimp(eq).exp == eq.exp == a*Rational(2, 3)
# powdenest goes the other direction
assert powsimp(2**(2*x)) == 4**x
assert powsimp(exp(p/2)) == exp(p/2)
# issue 6368
eq = Mul(*[sqrt(Dummy(imaginary=True)) for i in range(3)])
assert powsimp(eq) == eq and eq.is_Mul
assert all(powsimp(e) == e for e in (sqrt(x**a), sqrt(x**2)))
# issue 8836
assert str( powsimp(exp(I*pi/3)*root(-1,3)) ) == '(-1)**(2/3)'
# issue 9183
assert powsimp(-0.1**x) == -0.1**x
# issue 10095
assert powsimp((1/(2*E))**oo) == (exp(-1)/2)**oo
# PR 13131
eq = sin(2*x)**2*sin(2.0*x)**2
assert powsimp(eq) == eq
# issue 14615
assert powsimp(x**2*y**3*(x*y**2)**Rational(3, 2)
) == x*y*(x*y**2)**Rational(5, 2)
def test_powsimp_negated_base():
assert powsimp((-x + y)/sqrt(x - y)) == -sqrt(x - y)
assert powsimp((-x + y)*(-z + y)/sqrt(x - y)/sqrt(z - y)) == sqrt(x - y)*sqrt(z - y)
p = symbols('p', positive=True)
reps = {p: 2, a: S.Half}
assert powsimp((-p)**a/p**a).subs(reps) == ((-1)**a).subs(reps)
assert powsimp((-p)**a*p**a).subs(reps) == ((-p**2)**a).subs(reps)
n = symbols('n', negative=True)
reps = {p: -2, a: S.Half}
assert powsimp((-n)**a/n**a).subs(reps) == (-1)**(-a).subs(a, S.Half)
assert powsimp((-n)**a*n**a).subs(reps) == ((-n**2)**a).subs(reps)
# if x is 0 then the lhs is 0**a*oo**a which is not (-1)**a
eq = (-x)**a/x**a
assert powsimp(eq) == eq
def test_powsimp_nc():
x, y, z = symbols('x,y,z')
A, B, C = symbols('A B C', commutative=False)
assert powsimp(A**x*A**y, combine='all') == A**(x + y)
assert powsimp(A**x*A**y, combine='base') == A**x*A**y
assert powsimp(A**x*A**y, combine='exp') == A**(x + y)
assert powsimp(A**x*B**x, combine='all') == A**x*B**x
assert powsimp(A**x*B**x, combine='base') == A**x*B**x
assert powsimp(A**x*B**x, combine='exp') == A**x*B**x
assert powsimp(B**x*A**x, combine='all') == B**x*A**x
assert powsimp(B**x*A**x, combine='base') == B**x*A**x
assert powsimp(B**x*A**x, combine='exp') == B**x*A**x
assert powsimp(A**x*A**y*A**z, combine='all') == A**(x + y + z)
assert powsimp(A**x*A**y*A**z, combine='base') == A**x*A**y*A**z
assert powsimp(A**x*A**y*A**z, combine='exp') == A**(x + y + z)
assert powsimp(A**x*B**x*C**x, combine='all') == A**x*B**x*C**x
assert powsimp(A**x*B**x*C**x, combine='base') == A**x*B**x*C**x
assert powsimp(A**x*B**x*C**x, combine='exp') == A**x*B**x*C**x
assert powsimp(B**x*A**x*C**x, combine='all') == B**x*A**x*C**x
assert powsimp(B**x*A**x*C**x, combine='base') == B**x*A**x*C**x
assert powsimp(B**x*A**x*C**x, combine='exp') == B**x*A**x*C**x
def test_issue_6440():
assert powsimp(16*2**a*8**b) == 2**(a + 3*b + 4)
def test_powdenest():
from sympy import powdenest
from sympy.abc import x, y, z, a, b
p, q = symbols('p q', positive=True)
i, j = symbols('i,j', integer=True)
assert powdenest(x) == x
assert powdenest(x + 2*(x**(a*Rational(2, 3)))**(3*x)) == (x + 2*(x**(a*Rational(2, 3)))**(3*x))
assert powdenest((exp(a*Rational(2, 3)))**(3*x)) # -X-> (exp(a/3))**(6*x)
assert powdenest((x**(a*Rational(2, 3)))**(3*x)) == ((x**(a*Rational(2, 3)))**(3*x))
assert powdenest(exp(3*x*log(2))) == 2**(3*x)
assert powdenest(sqrt(p**2)) == p
eq = p**(2*i)*q**(4*i)
assert powdenest(eq) == (p*q**2)**(2*i)
# -X-> (x**x)**i*(x**x)**j == x**(x*(i + j))
assert powdenest((x**x)**(i + j))
assert powdenest(exp(3*y*log(x))) == x**(3*y)
assert powdenest(exp(y*(log(a) + log(b)))) == (a*b)**y
assert powdenest(exp(3*(log(a) + log(b)))) == a**3*b**3
assert powdenest(((x**(2*i))**(3*y))**x) == ((x**(2*i))**(3*y))**x
assert powdenest(((x**(2*i))**(3*y))**x, force=True) == x**(6*i*x*y)
assert powdenest(((x**(a*Rational(2, 3)))**(3*y/i))**x) == \
(((x**(a*Rational(2, 3)))**(3*y/i))**x)
assert powdenest((x**(2*i)*y**(4*i))**z, force=True) == (x*y**2)**(2*i*z)
assert powdenest((p**(2*i)*q**(4*i))**j) == (p*q**2)**(2*i*j)
e = ((p**(2*a))**(3*y))**x
assert powdenest(e) == e
e = ((x**2*y**4)**a)**(x*y)
assert powdenest(e) == e
e = (((x**2*y**4)**a)**(x*y))**3
assert powdenest(e) == ((x**2*y**4)**a)**(3*x*y)
assert powdenest((((x**2*y**4)**a)**(x*y)), force=True) == \
(x*y**2)**(2*a*x*y)
assert powdenest((((x**2*y**4)**a)**(x*y))**3, force=True) == \
(x*y**2)**(6*a*x*y)
assert powdenest((x**2*y**6)**i) != (x*y**3)**(2*i)
x, y = symbols('x,y', positive=True)
assert powdenest((x**2*y**6)**i) == (x*y**3)**(2*i)
assert powdenest((x**(i*Rational(2, 3))*y**(i/2))**(2*i)) == (x**Rational(4, 3)*y)**(i**2)
assert powdenest(sqrt(x**(2*i)*y**(6*i))) == (x*y**3)**i
assert powdenest(4**x) == 2**(2*x)
assert powdenest((4**x)**y) == 2**(2*x*y)
assert powdenest(4**x*y) == 2**(2*x)*y
def test_powdenest_polar():
x, y, z = symbols('x y z', polar=True)
a, b, c = symbols('a b c')
assert powdenest((x*y*z)**a) == x**a*y**a*z**a
assert powdenest((x**a*y**b)**c) == x**(a*c)*y**(b*c)
assert powdenest(((x**a)**b*y**c)**c) == x**(a*b*c)*y**(c**2)
def test_issue_5805():
arg = ((gamma(x)*hyper((), (), x))*pi)**2
assert powdenest(arg) == (pi*gamma(x)*hyper((), (), x))**2
assert arg.is_positive is None
def test_issue_9324_powsimp_on_matrix_symbol():
M = MatrixSymbol('M', 10, 10)
expr = powsimp(M, deep=True)
assert expr == M
assert expr.args[0] == Str('M')
def test_issue_6367():
z = -5*sqrt(2)/(2*sqrt(2*sqrt(29) + 29)) + sqrt(-sqrt(29)/29 + S.Half)
assert Mul(*[powsimp(a) for a in Mul.make_args(z.normal())]) == 0
assert powsimp(z.normal()) == 0
assert simplify(z) == 0
assert powsimp(sqrt(2 + sqrt(3))*sqrt(2 - sqrt(3)) + 1) == 2
assert powsimp(z) != 0
def test_powsimp_polar():
from sympy import polar_lift, exp_polar
x, y, z = symbols('x y z')
p, q, r = symbols('p q r', polar=True)
assert (polar_lift(-1))**(2*x) == exp_polar(2*pi*I*x)
assert powsimp(p**x * q**x) == (p*q)**x
assert p**x * (1/p)**x == 1
assert (1/p)**x == p**(-x)
assert exp_polar(x)*exp_polar(y) == exp_polar(x)*exp_polar(y)
assert powsimp(exp_polar(x)*exp_polar(y)) == exp_polar(x + y)
assert powsimp(exp_polar(x)*exp_polar(y)*p**x*p**y) == \
(p*exp_polar(1))**(x + y)
assert powsimp(exp_polar(x)*exp_polar(y)*p**x*p**y, combine='exp') == \
exp_polar(x + y)*p**(x + y)
assert powsimp(
exp_polar(x)*exp_polar(y)*exp_polar(2)*sin(x) + sin(y) + p**x*p**y) \
== p**(x + y) + sin(x)*exp_polar(2 + x + y) + sin(y)
assert powsimp(sin(exp_polar(x)*exp_polar(y))) == \
sin(exp_polar(x)*exp_polar(y))
assert powsimp(sin(exp_polar(x)*exp_polar(y)), deep=True) == \
sin(exp_polar(x + y))
def test_issue_5728():
b = x*sqrt(y)
a = sqrt(b)
c = sqrt(sqrt(x)*y)
assert powsimp(a*b) == sqrt(b)**3
assert powsimp(a*b**2*sqrt(y)) == sqrt(y)*a**5
assert powsimp(a*x**2*c**3*y) == c**3*a**5
assert powsimp(a*x*c**3*y**2) == c**7*a
assert powsimp(x*c**3*y**2) == c**7
assert powsimp(x*c**3*y) == x*y*c**3
assert powsimp(sqrt(x)*c**3*y) == c**5
assert powsimp(sqrt(x)*a**3*sqrt(y)) == sqrt(x)*sqrt(y)*a**3
assert powsimp(Mul(sqrt(x)*c**3*sqrt(y), y, evaluate=False)) == \
sqrt(x)*sqrt(y)**3*c**3
assert powsimp(a**2*a*x**2*y) == a**7
# symbolic powers work, too
b = x**y*y
a = b*sqrt(b)
assert a.is_Mul is True
assert powsimp(a) == sqrt(b)**3
# as does exp
a = x*exp(y*Rational(2, 3))
assert powsimp(a*sqrt(a)) == sqrt(a)**3
assert powsimp(a**2*sqrt(a)) == sqrt(a)**5
assert powsimp(a**2*sqrt(sqrt(a))) == sqrt(sqrt(a))**9
def test_issue_from_PR1599():
n1, n2, n3, n4 = symbols('n1 n2 n3 n4', negative=True)
assert (powsimp(sqrt(n1)*sqrt(n2)*sqrt(n3)) ==
-I*sqrt(-n1)*sqrt(-n2)*sqrt(-n3))
assert (powsimp(root(n1, 3)*root(n2, 3)*root(n3, 3)*root(n4, 3)) ==
-(-1)**Rational(1, 3)*
(-n1)**Rational(1, 3)*(-n2)**Rational(1, 3)*(-n3)**Rational(1, 3)*(-n4)**Rational(1, 3))
def test_issue_10195():
a = Symbol('a', integer=True)
l = Symbol('l', even=True, nonzero=True)
n = Symbol('n', odd=True)
e_x = (-1)**(n/2 - S.Half) - (-1)**(n*Rational(3, 2) - S.Half)
assert powsimp((-1)**(l/2)) == I**l
assert powsimp((-1)**(n/2)) == I**n
assert powsimp((-1)**(n*Rational(3, 2))) == -I**n
assert powsimp(e_x) == (-1)**(n/2 - S.Half) + (-1)**(n*Rational(3, 2) +
S.Half)
assert powsimp((-1)**(a*Rational(3, 2))) == (-I)**a
def test_issue_15709():
assert powsimp(3**x*Rational(2, 3)) == 2*3**(x-1)
assert powsimp(2*3**x/3) == 2*3**(x-1)
def test_issue_11981():
x, y = symbols('x y', commutative=False)
assert powsimp((x*y)**2 * (y*x)**2) == (x*y)**2 * (y*x)**2
def test_issue_17524():
a = symbols("a", real=True)
e = (-1 - a**2)*sqrt(1 + a**2)
assert signsimp(powsimp(e)) == signsimp(e) == -(a**2 + 1)**(S(3)/2)
def test_issue_19627():
# if you use force the user must verify
assert powdenest(sqrt(sin(x)**2), force=True) == sin(x)
assert powdenest((x**(S.Half/y))**(2*y), force=True) == x
from sympy import expand_power_base
e = 1 - a
expr = (exp(z/e)*x**(b/e)*y**((1 - b)/e))**e
assert powdenest(expand_power_base(expr, force=True), force=True
) == x**b*y**(1 - b)*exp(z)
|
56c191ab6ae88eb58131dfeac9a64ea9db335b127965ae3c61761f6958c9bd4a | from functools import reduce
import itertools
from operator import add
from sympy import (
Add, Mul, Pow, Symbol, exp, sqrt, symbols, sympify, cse,
Matrix, S, cos, sin, Eq, Function, Tuple, CRootOf,
IndexedBase, Idx, Piecewise, O, signsimp
)
from sympy.core.function import count_ops
from sympy.simplify.cse_opts import sub_pre, sub_post
from sympy.functions.special.hyper import meijerg
from sympy.simplify import cse_main, cse_opts
from sympy.utilities.iterables import subsets
from sympy.testing.pytest import XFAIL, raises
from sympy.matrices import (MutableDenseMatrix, MutableSparseMatrix,
ImmutableDenseMatrix, ImmutableSparseMatrix)
from sympy.matrices.expressions import MatrixSymbol
w, x, y, z = symbols('w,x,y,z')
x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12 = symbols('x:13')
def test_numbered_symbols():
ns = cse_main.numbered_symbols(prefix='y')
assert list(itertools.islice(
ns, 0, 10)) == [Symbol('y%s' % i) for i in range(0, 10)]
ns = cse_main.numbered_symbols(prefix='y')
assert list(itertools.islice(
ns, 10, 20)) == [Symbol('y%s' % i) for i in range(10, 20)]
ns = cse_main.numbered_symbols()
assert list(itertools.islice(
ns, 0, 10)) == [Symbol('x%s' % i) for i in range(0, 10)]
# Dummy "optimization" functions for testing.
def opt1(expr):
return expr + y
def opt2(expr):
return expr*z
def test_preprocess_for_cse():
assert cse_main.preprocess_for_cse(x, [(opt1, None)]) == x + y
assert cse_main.preprocess_for_cse(x, [(None, opt1)]) == x
assert cse_main.preprocess_for_cse(x, [(None, None)]) == x
assert cse_main.preprocess_for_cse(x, [(opt1, opt2)]) == x + y
assert cse_main.preprocess_for_cse(
x, [(opt1, None), (opt2, None)]) == (x + y)*z
def test_postprocess_for_cse():
assert cse_main.postprocess_for_cse(x, [(opt1, None)]) == x
assert cse_main.postprocess_for_cse(x, [(None, opt1)]) == x + y
assert cse_main.postprocess_for_cse(x, [(None, None)]) == x
assert cse_main.postprocess_for_cse(x, [(opt1, opt2)]) == x*z
# Note the reverse order of application.
assert cse_main.postprocess_for_cse(
x, [(None, opt1), (None, opt2)]) == x*z + y
def test_cse_single():
# Simple substitution.
e = Add(Pow(x + y, 2), sqrt(x + y))
substs, reduced = cse([e])
assert substs == [(x0, x + y)]
assert reduced == [sqrt(x0) + x0**2]
subst42, (red42,) = cse([42]) # issue_15082
assert len(subst42) == 0 and red42 == 42
subst_half, (red_half,) = cse([0.5])
assert len(subst_half) == 0 and red_half == 0.5
def test_cse_single2():
# Simple substitution, test for being able to pass the expression directly
e = Add(Pow(x + y, 2), sqrt(x + y))
substs, reduced = cse(e)
assert substs == [(x0, x + y)]
assert reduced == [sqrt(x0) + x0**2]
substs, reduced = cse(Matrix([[1]]))
assert isinstance(reduced[0], Matrix)
subst42, (red42,) = cse(42) # issue 15082
assert len(subst42) == 0 and red42 == 42
subst_half, (red_half,) = cse(0.5) # issue 15082
assert len(subst_half) == 0 and red_half == 0.5
def test_cse_not_possible():
# No substitution possible.
e = Add(x, y)
substs, reduced = cse([e])
assert substs == []
assert reduced == [x + y]
# issue 6329
eq = (meijerg((1, 2), (y, 4), (5,), [], x) +
meijerg((1, 3), (y, 4), (5,), [], x))
assert cse(eq) == ([], [eq])
def test_nested_substitution():
# Substitution within a substitution.
e = Add(Pow(w*x + y, 2), sqrt(w*x + y))
substs, reduced = cse([e])
assert substs == [(x0, w*x + y)]
assert reduced == [sqrt(x0) + x0**2]
def test_subtraction_opt():
# Make sure subtraction is optimized.
e = (x - y)*(z - y) + exp((x - y)*(z - y))
substs, reduced = cse(
[e], optimizations=[(cse_opts.sub_pre, cse_opts.sub_post)])
assert substs == [(x0, (x - y)*(y - z))]
assert reduced == [-x0 + exp(-x0)]
e = -(x - y)*(z - y) + exp(-(x - y)*(z - y))
substs, reduced = cse(
[e], optimizations=[(cse_opts.sub_pre, cse_opts.sub_post)])
assert substs == [(x0, (x - y)*(y - z))]
assert reduced == [x0 + exp(x0)]
# issue 4077
n = -1 + 1/x
e = n/x/(-n)**2 - 1/n/x
assert cse(e, optimizations=[(cse_opts.sub_pre, cse_opts.sub_post)]) == \
([], [0])
def test_multiple_expressions():
e1 = (x + y)*z
e2 = (x + y)*w
substs, reduced = cse([e1, e2])
assert substs == [(x0, x + y)]
assert reduced == [x0*z, x0*w]
l = [w*x*y + z, w*y]
substs, reduced = cse(l)
rsubsts, _ = cse(reversed(l))
assert substs == rsubsts
assert reduced == [z + x*x0, x0]
l = [w*x*y, w*x*y + z, w*y]
substs, reduced = cse(l)
rsubsts, _ = cse(reversed(l))
assert substs == rsubsts
assert reduced == [x1, x1 + z, x0]
l = [(x - z)*(y - z), x - z, y - z]
substs, reduced = cse(l)
rsubsts, _ = cse(reversed(l))
assert substs == [(x0, -z), (x1, x + x0), (x2, x0 + y)]
assert rsubsts == [(x0, -z), (x1, x0 + y), (x2, x + x0)]
assert reduced == [x1*x2, x1, x2]
l = [w*y + w + x + y + z, w*x*y]
assert cse(l) == ([(x0, w*y)], [w + x + x0 + y + z, x*x0])
assert cse([x + y, x + y + z]) == ([(x0, x + y)], [x0, z + x0])
assert cse([x + y, x + z]) == ([], [x + y, x + z])
assert cse([x*y, z + x*y, x*y*z + 3]) == \
([(x0, x*y)], [x0, z + x0, 3 + x0*z])
@XFAIL # CSE of non-commutative Mul terms is disabled
def test_non_commutative_cse():
A, B, C = symbols('A B C', commutative=False)
l = [A*B*C, A*C]
assert cse(l) == ([], l)
l = [A*B*C, A*B]
assert cse(l) == ([(x0, A*B)], [x0*C, x0])
# Test if CSE of non-commutative Mul terms is disabled
def test_bypass_non_commutatives():
A, B, C = symbols('A B C', commutative=False)
l = [A*B*C, A*C]
assert cse(l) == ([], l)
l = [A*B*C, A*B]
assert cse(l) == ([], l)
l = [B*C, A*B*C]
assert cse(l) == ([], l)
@XFAIL # CSE fails when replacing non-commutative sub-expressions
def test_non_commutative_order():
A, B, C = symbols('A B C', commutative=False)
x0 = symbols('x0', commutative=False)
l = [B+C, A*(B+C)]
assert cse(l) == ([(x0, B+C)], [x0, A*x0])
@XFAIL # Worked in gh-11232, but was reverted due to performance considerations
def test_issue_10228():
assert cse([x*y**2 + x*y]) == ([(x0, x*y)], [x0*y + x0])
assert cse([x + y, 2*x + y]) == ([(x0, x + y)], [x0, x + x0])
assert cse((w + 2*x + y + z, w + x + 1)) == (
[(x0, w + x)], [x0 + x + y + z, x0 + 1])
assert cse(((w + x + y + z)*(w - x))/(w + x)) == (
[(x0, w + x)], [(x0 + y + z)*(w - x)/x0])
a, b, c, d, f, g, j, m = symbols('a, b, c, d, f, g, j, m')
exprs = (d*g**2*j*m, 4*a*f*g*m, a*b*c*f**2)
assert cse(exprs) == (
[(x0, g*m), (x1, a*f)], [d*g*j*x0, 4*x0*x1, b*c*f*x1]
)
@XFAIL
def test_powers():
assert cse(x*y**2 + x*y) == ([(x0, x*y)], [x0*y + x0])
def test_issue_4498():
assert cse(w/(x - y) + z/(y - x), optimizations='basic') == \
([], [(w - z)/(x - y)])
def test_issue_4020():
assert cse(x**5 + x**4 + x**3 + x**2, optimizations='basic') \
== ([(x0, x**2)], [x0*(x**3 + x + x0 + 1)])
def test_issue_4203():
assert cse(sin(x**x)/x**x) == ([(x0, x**x)], [sin(x0)/x0])
def test_issue_6263():
e = Eq(x*(-x + 1) + x*(x - 1), 0)
assert cse(e, optimizations='basic') == ([], [True])
def test_dont_cse_tuples():
from sympy import Subs
f = Function("f")
g = Function("g")
name_val, (expr,) = cse(
Subs(f(x, y), (x, y), (0, 1))
+ Subs(g(x, y), (x, y), (0, 1)))
assert name_val == []
assert expr == (Subs(f(x, y), (x, y), (0, 1))
+ Subs(g(x, y), (x, y), (0, 1)))
name_val, (expr,) = cse(
Subs(f(x, y), (x, y), (0, x + y))
+ Subs(g(x, y), (x, y), (0, x + y)))
assert name_val == [(x0, x + y)]
assert expr == Subs(f(x, y), (x, y), (0, x0)) + \
Subs(g(x, y), (x, y), (0, x0))
def test_pow_invpow():
assert cse(1/x**2 + x**2) == \
([(x0, x**2)], [x0 + 1/x0])
assert cse(x**2 + (1 + 1/x**2)/x**2) == \
([(x0, x**2), (x1, 1/x0)], [x0 + x1*(x1 + 1)])
assert cse(1/x**2 + (1 + 1/x**2)*x**2) == \
([(x0, x**2), (x1, 1/x0)], [x0*(x1 + 1) + x1])
assert cse(cos(1/x**2) + sin(1/x**2)) == \
([(x0, x**(-2))], [sin(x0) + cos(x0)])
assert cse(cos(x**2) + sin(x**2)) == \
([(x0, x**2)], [sin(x0) + cos(x0)])
assert cse(y/(2 + x**2) + z/x**2/y) == \
([(x0, x**2)], [y/(x0 + 2) + z/(x0*y)])
assert cse(exp(x**2) + x**2*cos(1/x**2)) == \
([(x0, x**2)], [x0*cos(1/x0) + exp(x0)])
assert cse((1 + 1/x**2)/x**2) == \
([(x0, x**(-2))], [x0*(x0 + 1)])
assert cse(x**(2*y) + x**(-2*y)) == \
([(x0, x**(2*y))], [x0 + 1/x0])
def test_postprocess():
eq = (x + 1 + exp((x + 1)/(y + 1)) + cos(y + 1))
assert cse([eq, Eq(x, z + 1), z - 2, (z + 1)*(x + 1)],
postprocess=cse_main.cse_separate) == \
[[(x0, y + 1), (x2, z + 1), (x, x2), (x1, x + 1)],
[x1 + exp(x1/x0) + cos(x0), z - 2, x1*x2]]
def test_issue_4499():
# previously, this gave 16 constants
from sympy.abc import a, b
B = Function('B')
G = Function('G')
t = Tuple(*
(a, a + S.Half, 2*a, b, 2*a - b + 1, (sqrt(z)/2)**(-2*a + 1)*B(2*a -
b, sqrt(z))*B(b - 1, sqrt(z))*G(b)*G(2*a - b + 1),
sqrt(z)*(sqrt(z)/2)**(-2*a + 1)*B(b, sqrt(z))*B(2*a - b,
sqrt(z))*G(b)*G(2*a - b + 1), sqrt(z)*(sqrt(z)/2)**(-2*a + 1)*B(b - 1,
sqrt(z))*B(2*a - b + 1, sqrt(z))*G(b)*G(2*a - b + 1),
(sqrt(z)/2)**(-2*a + 1)*B(b, sqrt(z))*B(2*a - b + 1,
sqrt(z))*G(b)*G(2*a - b + 1), 1, 0, S.Half, z/2, -b + 1, -2*a + b,
-2*a))
c = cse(t)
ans = (
[(x0, 2*a), (x1, -b), (x2, x0 + x1), (x3, x2 + 1), (x4, sqrt(z)), (x5,
B(b - 1, x4)), (x6, -x0), (x7, (x4/2)**(x6 + 1)*G(b)*G(x3)), (x8,
x7*B(x2, x4)), (x9, B(b, x4)), (x10, x7*B(x3, x4))],
[(a, a + S.Half, x0, b, x3, x5*x8, x4*x8*x9, x10*x4*x5, x10*x9,
1, 0, S.Half, z/2, x1 + 1, b + x6, x6)])
assert ans == c
def test_issue_6169():
r = CRootOf(x**6 - 4*x**5 - 2, 1)
assert cse(r) == ([], [r])
# and a check that the right thing is done with the new
# mechanism
assert sub_post(sub_pre((-x - y)*z - x - y)) == -z*(x + y) - x - y
def test_cse_Indexed():
len_y = 5
y = IndexedBase('y', shape=(len_y,))
x = IndexedBase('x', shape=(len_y,))
i = Idx('i', len_y-1)
expr1 = (y[i+1]-y[i])/(x[i+1]-x[i])
expr2 = 1/(x[i+1]-x[i])
replacements, reduced_exprs = cse([expr1, expr2])
assert len(replacements) > 0
def test_cse_MatrixSymbol():
# MatrixSymbols have non-Basic args, so make sure that works
A = MatrixSymbol("A", 3, 3)
assert cse(A) == ([], [A])
n = symbols('n', integer=True)
B = MatrixSymbol("B", n, n)
assert cse(B) == ([], [B])
def test_cse_MatrixExpr():
from sympy import MatrixSymbol
A = MatrixSymbol('A', 3, 3)
y = MatrixSymbol('y', 3, 1)
expr1 = (A.T*A).I * A * y
expr2 = (A.T*A) * A * y
replacements, reduced_exprs = cse([expr1, expr2])
assert len(replacements) > 0
replacements, reduced_exprs = cse([expr1 + expr2, expr1])
assert replacements
replacements, reduced_exprs = cse([A**2, A + A**2])
assert replacements
def test_Piecewise():
f = Piecewise((-z + x*y, Eq(y, 0)), (-z - x*y, True))
ans = cse(f)
actual_ans = ([(x0, -z), (x1, x*y)],
[Piecewise((x0 + x1, Eq(y, 0)), (x0 - x1, True))])
assert ans == actual_ans
def test_ignore_order_terms():
eq = exp(x).series(x,0,3) + sin(y+x**3) - 1
assert cse(eq) == ([], [sin(x**3 + y) + x + x**2/2 + O(x**3)])
def test_name_conflict():
z1 = x0 + y
z2 = x2 + x3
l = [cos(z1) + z1, cos(z2) + z2, x0 + x2]
substs, reduced = cse(l)
assert [e.subs(reversed(substs)) for e in reduced] == l
def test_name_conflict_cust_symbols():
z1 = x0 + y
z2 = x2 + x3
l = [cos(z1) + z1, cos(z2) + z2, x0 + x2]
substs, reduced = cse(l, symbols("x:10"))
assert [e.subs(reversed(substs)) for e in reduced] == l
def test_symbols_exhausted_error():
l = cos(x+y)+x+y+cos(w+y)+sin(w+y)
sym = [x, y, z]
with raises(ValueError):
cse(l, symbols=sym)
def test_issue_7840():
# daveknippers' example
C393 = sympify( \
'Piecewise((C391 - 1.65, C390 < 0.5), (Piecewise((C391 - 1.65, \
C391 > 2.35), (C392, True)), True))'
)
C391 = sympify( \
'Piecewise((2.05*C390**(-1.03), C390 < 0.5), (2.5*C390**(-0.625), True))'
)
C393 = C393.subs('C391',C391)
# simple substitution
sub = {}
sub['C390'] = 0.703451854
sub['C392'] = 1.01417794
ss_answer = C393.subs(sub)
# cse
substitutions,new_eqn = cse(C393)
for pair in substitutions:
sub[pair[0].name] = pair[1].subs(sub)
cse_answer = new_eqn[0].subs(sub)
# both methods should be the same
assert ss_answer == cse_answer
# GitRay's example
expr = sympify(
"Piecewise((Symbol('ON'), Equality(Symbol('mode'), Symbol('ON'))), \
(Piecewise((Piecewise((Symbol('OFF'), StrictLessThan(Symbol('x'), \
Symbol('threshold'))), (Symbol('ON'), true)), Equality(Symbol('mode'), \
Symbol('AUTO'))), (Symbol('OFF'), true)), true))"
)
substitutions, new_eqn = cse(expr)
# this Piecewise should be exactly the same
assert new_eqn[0] == expr
# there should not be any replacements
assert len(substitutions) < 1
def test_issue_8891():
for cls in (MutableDenseMatrix, MutableSparseMatrix,
ImmutableDenseMatrix, ImmutableSparseMatrix):
m = cls(2, 2, [x + y, 0, 0, 0])
res = cse([x + y, m])
ans = ([(x0, x + y)], [x0, cls([[x0, 0], [0, 0]])])
assert res == ans
assert isinstance(res[1][-1], cls)
def test_issue_11230():
# a specific test that always failed
a, b, f, k, l, i = symbols('a b f k l i')
p = [a*b*f*k*l, a*i*k**2*l, f*i*k**2*l]
R, C = cse(p)
assert not any(i.is_Mul for a in C for i in a.args)
# random tests for the issue
from random import choice
from sympy.core.function import expand_mul
s = symbols('a:m')
# 35 Mul tests, none of which should ever fail
ex = [Mul(*[choice(s) for i in range(5)]) for i in range(7)]
for p in subsets(ex, 3):
p = list(p)
R, C = cse(p)
assert not any(i.is_Mul for a in C for i in a.args)
for ri in reversed(R):
for i in range(len(C)):
C[i] = C[i].subs(*ri)
assert p == C
# 35 Add tests, none of which should ever fail
ex = [Add(*[choice(s[:7]) for i in range(5)]) for i in range(7)]
for p in subsets(ex, 3):
p = list(p)
R, C = cse(p)
assert not any(i.is_Add for a in C for i in a.args)
for ri in reversed(R):
for i in range(len(C)):
C[i] = C[i].subs(*ri)
# use expand_mul to handle cases like this:
# p = [a + 2*b + 2*e, 2*b + c + 2*e, b + 2*c + 2*g]
# x0 = 2*(b + e) is identified giving a rebuilt p that
# is now `[a + 2*(b + e), c + 2*(b + e), b + 2*c + 2*g]`
assert p == [expand_mul(i) for i in C]
@XFAIL
def test_issue_11577():
def check(eq):
r, c = cse(eq)
assert eq.count_ops() >= \
len(r) + sum([i[1].count_ops() for i in r]) + \
count_ops(c)
eq = x**5*y**2 + x**5*y + x**5
assert cse(eq) == (
[(x0, x**4), (x1, x*y)], [x**5 + x0*x1*y + x0*x1])
# ([(x0, x**5*y)], [x0*y + x0 + x**5]) or
# ([(x0, x**5)], [x0*y**2 + x0*y + x0])
check(eq)
eq = x**2/(y + 1)**2 + x/(y + 1)
assert cse(eq) == (
[(x0, y + 1)], [x**2/x0**2 + x/x0])
# ([(x0, x/(y + 1))], [x0**2 + x0])
check(eq)
def test_hollow_rejection():
eq = [x + 3, x + 4]
assert cse(eq) == ([], eq)
def test_cse_ignore():
exprs = [exp(y)*(3*y + 3*sqrt(x+1)), exp(y)*(5*y + 5*sqrt(x+1))]
subst1, red1 = cse(exprs)
assert any(y in sub.free_symbols for _, sub in subst1), "cse failed to identify any term with y"
subst2, red2 = cse(exprs, ignore=(y,)) # y is not allowed in substitutions
assert not any(y in sub.free_symbols for _, sub in subst2), "Sub-expressions containing y must be ignored"
assert any(sub - sqrt(x + 1) == 0 for _, sub in subst2), "cse failed to identify sqrt(x + 1) as sub-expression"
def test_cse_ignore_issue_15002():
l = [
w*exp(x)*exp(-z),
exp(y)*exp(x)*exp(-z)
]
substs, reduced = cse(l, ignore=(x,))
rl = [e.subs(reversed(substs)) for e in reduced]
assert rl == l
def test_cse__performance():
nexprs, nterms = 3, 20
x = symbols('x:%d' % nterms)
exprs = [
reduce(add, [x[j]*(-1)**(i+j) for j in range(nterms)])
for i in range(nexprs)
]
assert (exprs[0] + exprs[1]).simplify() == 0
subst, red = cse(exprs)
assert len(subst) > 0, "exprs[0] == -exprs[2], i.e. a CSE"
for i, e in enumerate(red):
assert (e.subs(reversed(subst)) - exprs[i]).simplify() == 0
def test_issue_12070():
exprs = [x + y, 2 + x + y, x + y + z, 3 + x + y + z]
subst, red = cse(exprs)
assert 6 >= (len(subst) + sum([v.count_ops() for k, v in subst]) +
count_ops(red))
def test_issue_13000():
eq = x/(-4*x**2 + y**2)
cse_eq = cse(eq)[1][0]
assert cse_eq == eq
def test_issue_18203():
eq = CRootOf(x**5 + 11*x - 2, 0) + CRootOf(x**5 + 11*x - 2, 1)
assert cse(eq) == ([], [eq])
def test_unevaluated_mul():
eq = Mul(x + y, x + y, evaluate=False)
assert cse(eq) == ([(x0, x + y)], [x0**2])
def test_issue_18991():
A = MatrixSymbol('A', 2, 2)
assert signsimp(-A * A - A) == -A * A - A
def test_unevaluated_Mul():
m = [Mul(1, 2, evaluate=False)]
assert cse(m) == ([], m)
|
576220ec4b22ccf4ef081d27a0aceabb4c479cd8c7dff124f2a0cfcd75dc2854 | from sympy.core import Lambda, Symbol, symbols
from sympy.diffgeom.rn import R2, R2_p, R2_r, R3_r, R3_c, R3_s, R2_origin
from sympy.diffgeom import (CoordSystem, Commutator, Differential, TensorProduct,
WedgeProduct, BaseCovarDerivativeOp, CovarDerivativeOp, LieDerivative,
covariant_order, contravariant_order, twoform_to_matrix, metric_to_Christoffel_1st,
metric_to_Christoffel_2nd, metric_to_Riemann_components,
metric_to_Ricci_components, intcurve_diffequ, intcurve_series)
from sympy.simplify import trigsimp, simplify
from sympy.functions import sqrt, atan2, sin
from sympy.matrices import Matrix
from sympy.testing.pytest import raises, nocache_fail
from sympy.testing.pytest import warns_deprecated_sympy
TP = TensorProduct
def test_coordsys_transform():
# test inverse transforms
p, q, r, s = symbols('p q r s')
rel = {('first', 'second'): [(p, q), (q, -p)]}
R2_pq = CoordSystem('first', R2_origin, [p, q], rel)
R2_rs = CoordSystem('second', R2_origin, [r, s], rel)
r, s = R2_rs.symbols
assert R2_rs.transform(R2_pq) == Matrix([[-s], [r]])
# inverse transform impossible case
a, b = symbols('a b', positive=True)
rel = {('first', 'second'): [(a,), (-a,)]}
R2_a = CoordSystem('first', R2_origin, [a], rel)
R2_b = CoordSystem('second', R2_origin, [b], rel)
# This transformation is uninvertible because there is no positive a, b satisfying a = -b
with raises(NotImplementedError):
R2_b.transform(R2_a)
# inverse transform ambiguous case
c, d = symbols('c d')
rel = {('first', 'second'): [(c,), (c**2,)]}
R2_c = CoordSystem('first', R2_origin, [c], rel)
R2_d = CoordSystem('second', R2_origin, [d], rel)
# The transform method should throw if it finds multiple inverses for a coordinate transformation.
with raises(ValueError):
R2_d.transform(R2_c)
# test indirect transformation
a, b, c, d, e, f = symbols('a, b, c, d, e, f')
rel = {('C1', 'C2'): [(a, b), (2*a, 3*b)],
('C2', 'C3'): [(c, d), (3*c, 2*d)]}
C1 = CoordSystem('C1', R2_origin, (a, b), rel)
C2 = CoordSystem('C2', R2_origin, (c, d), rel)
C3 = CoordSystem('C3', R2_origin, (e, f), rel)
a, b = C1.symbols
c, d = C2.symbols
e, f = C3.symbols
assert C2.transform(C1) == Matrix([c/2, d/3])
assert C1.transform(C3) == Matrix([6*a, 6*b])
assert C3.transform(C1) == Matrix([e/6, f/6])
assert C3.transform(C2) == Matrix([e/3, f/2])
a, b, c, d, e, f = symbols('a, b, c, d, e, f')
rel = {('C1', 'C2'): [(a, b), (2*a, 3*b + 1)],
('C3', 'C2'): [(e, f), (-e - 2, 2*f)]}
C1 = CoordSystem('C1', R2_origin, (a, b), rel)
C2 = CoordSystem('C2', R2_origin, (c, d), rel)
C3 = CoordSystem('C3', R2_origin, (e, f), rel)
a, b = C1.symbols
c, d = C2.symbols
e, f = C3.symbols
assert C2.transform(C1) == Matrix([c/2, (d - 1)/3])
assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2])
assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3])
assert C3.transform(C2) == Matrix([-e - 2, 2*f])
# old signature uses Lambda
a, b, c, d, e, f = symbols('a, b, c, d, e, f')
rel = {('C1', 'C2'): Lambda((a, b), (2*a, 3*b + 1)),
('C3', 'C2'): Lambda((e, f), (-e - 2, 2*f))}
C1 = CoordSystem('C1', R2_origin, (a, b), rel)
C2 = CoordSystem('C2', R2_origin, (c, d), rel)
C3 = CoordSystem('C3', R2_origin, (e, f), rel)
a, b = C1.symbols
c, d = C2.symbols
e, f = C3.symbols
assert C2.transform(C1) == Matrix([c/2, (d - 1)/3])
assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2])
assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3])
assert C3.transform(C2) == Matrix([-e - 2, 2*f])
def test_R2():
x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', real=True)
point_r = R2_r.point([x0, y0])
point_p = R2_p.point([r0, theta0])
# r**2 = x**2 + y**2
assert (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_r) == 0
assert trigsimp( (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_p) ) == 0
assert trigsimp(R2.e_r(R2.x**2 + R2.y**2).rcall(point_p).doit()) == 2*r0
# polar->rect->polar == Id
a, b = symbols('a b', positive=True)
m = Matrix([[a], [b]])
#TODO assert m == R2_r.transform(R2_p, R2_p.transform(R2_r, [a, b])).applyfunc(simplify)
assert m == R2_p.transform(R2_r, R2_r.transform(R2_p, m)).applyfunc(simplify)
# deprecated method
with warns_deprecated_sympy():
assert m == R2_p.coord_tuple_transform_to(
R2_r, R2_r.coord_tuple_transform_to(R2_p, m)).applyfunc(simplify)
def test_R3():
a, b, c = symbols('a b c', positive=True)
m = Matrix([[a], [b], [c]])
assert m == R3_c.transform(R3_r, R3_r.transform(R3_c, m)).applyfunc(simplify)
#TODO assert m == R3_r.transform(R3_c, R3_c.transform(R3_r, m)).applyfunc(simplify)
assert m == R3_s.transform(
R3_r, R3_r.transform(R3_s, m)).applyfunc(simplify)
#TODO assert m == R3_r.transform(R3_s, R3_s.transform(R3_r, m)).applyfunc(simplify)
assert m == R3_s.transform(
R3_c, R3_c.transform(R3_s, m)).applyfunc(simplify)
#TODO assert m == R3_c.transform(R3_s, R3_s.transform(R3_c, m)).applyfunc(simplify)
with warns_deprecated_sympy():
assert m == R3_c.coord_tuple_transform_to(
R3_r, R3_r.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify)
#TODO assert m == R3_r.coord_tuple_transform_to(R3_c, R3_c.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify)
assert m == R3_s.coord_tuple_transform_to(
R3_r, R3_r.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify)
#TODO assert m == R3_r.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify)
assert m == R3_s.coord_tuple_transform_to(
R3_c, R3_c.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify)
#TODO assert m == R3_c.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify)
def test_point():
x, y = symbols('x, y')
p = R2_r.point([x, y])
assert p.free_symbols == {x, y}
assert p.coords(R2_r) == p.coords() == Matrix([x, y])
assert p.coords(R2_p) == Matrix([sqrt(x**2 + y**2), atan2(y, x)])
def test_commutator():
assert Commutator(R2.e_x, R2.e_y) == 0
assert Commutator(R2.x*R2.e_x, R2.x*R2.e_x) == 0
assert Commutator(R2.x*R2.e_x, R2.x*R2.e_y) == R2.x*R2.e_y
c = Commutator(R2.e_x, R2.e_r)
assert c(R2.x) == R2.y*(R2.x**2 + R2.y**2)**(-1)*sin(R2.theta)
def test_differential():
xdy = R2.x*R2.dy
dxdy = Differential(xdy)
assert xdy.rcall(None) == xdy
assert dxdy(R2.e_x, R2.e_y) == 1
assert dxdy(R2.e_x, R2.x*R2.e_y) == R2.x
assert Differential(dxdy) == 0
def test_products():
assert TensorProduct(
R2.dx, R2.dy)(R2.e_x, R2.e_y) == R2.dx(R2.e_x)*R2.dy(R2.e_y) == 1
assert TensorProduct(R2.dx, R2.dy)(None, R2.e_y) == R2.dx
assert TensorProduct(R2.dx, R2.dy)(R2.e_x, None) == R2.dy
assert TensorProduct(R2.dx, R2.dy)(R2.e_x) == R2.dy
assert TensorProduct(R2.x, R2.dx) == R2.x*R2.dx
assert TensorProduct(
R2.e_x, R2.e_y)(R2.x, R2.y) == R2.e_x(R2.x) * R2.e_y(R2.y) == 1
assert TensorProduct(R2.e_x, R2.e_y)(None, R2.y) == R2.e_x
assert TensorProduct(R2.e_x, R2.e_y)(R2.x, None) == R2.e_y
assert TensorProduct(R2.e_x, R2.e_y)(R2.x) == R2.e_y
assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x
assert TensorProduct(
R2.dx, R2.e_y)(R2.e_x, R2.y) == R2.dx(R2.e_x) * R2.e_y(R2.y) == 1
assert TensorProduct(R2.dx, R2.e_y)(None, R2.y) == R2.dx
assert TensorProduct(R2.dx, R2.e_y)(R2.e_x, None) == R2.e_y
assert TensorProduct(R2.dx, R2.e_y)(R2.e_x) == R2.e_y
assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x
assert TensorProduct(
R2.e_x, R2.dy)(R2.x, R2.e_y) == R2.e_x(R2.x) * R2.dy(R2.e_y) == 1
assert TensorProduct(R2.e_x, R2.dy)(None, R2.e_y) == R2.e_x
assert TensorProduct(R2.e_x, R2.dy)(R2.x, None) == R2.dy
assert TensorProduct(R2.e_x, R2.dy)(R2.x) == R2.dy
assert TensorProduct(R2.e_y,R2.e_x)(R2.x**2 + R2.y**2,R2.x**2 + R2.y**2) == 4*R2.x*R2.y
assert WedgeProduct(R2.dx, R2.dy)(R2.e_x, R2.e_y) == 1
assert WedgeProduct(R2.e_x, R2.e_y)(R2.x, R2.y) == 1
def test_lie_derivative():
assert LieDerivative(R2.e_x, R2.y) == R2.e_x(R2.y) == 0
assert LieDerivative(R2.e_x, R2.x) == R2.e_x(R2.x) == 1
assert LieDerivative(R2.e_x, R2.e_x) == Commutator(R2.e_x, R2.e_x) == 0
assert LieDerivative(R2.e_x, R2.e_r) == Commutator(R2.e_x, R2.e_r)
assert LieDerivative(R2.e_x + R2.e_y, R2.x) == 1
assert LieDerivative(
R2.e_x, TensorProduct(R2.dx, R2.dy))(R2.e_x, R2.e_y) == 0
@nocache_fail
def test_covar_deriv():
ch = metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
cvd = BaseCovarDerivativeOp(R2_r, 0, ch)
assert cvd(R2.x) == 1
# This line fails if the cache is disabled:
assert cvd(R2.x*R2.e_x) == R2.e_x
cvd = CovarDerivativeOp(R2.x*R2.e_x, ch)
assert cvd(R2.x) == R2.x
assert cvd(R2.x*R2.e_x) == R2.x*R2.e_x
def test_intcurve_diffequ():
t = symbols('t')
start_point = R2_r.point([1, 0])
vector_field = -R2.y*R2.e_x + R2.x*R2.e_y
equations, init_cond = intcurve_diffequ(vector_field, t, start_point)
assert str(equations) == '[f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]'
assert str(init_cond) == '[f_0(0) - 1, f_1(0)]'
equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p)
assert str(
equations) == '[Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]'
assert str(init_cond) == '[f_0(0) - 1, f_1(0)]'
def test_helpers_and_coordinate_dependent():
one_form = R2.dr + R2.dx
two_form = Differential(R2.x*R2.dr + R2.r*R2.dx)
three_form = Differential(
R2.y*two_form) + Differential(R2.x*Differential(R2.r*R2.dr))
metric = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dy, R2.dy)
metric_ambig = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dr, R2.dr)
misform_a = TensorProduct(R2.dr, R2.dr) + R2.dr
misform_b = R2.dr**4
misform_c = R2.dx*R2.dy
twoform_not_sym = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dx, R2.dy)
twoform_not_TP = WedgeProduct(R2.dx, R2.dy)
one_vector = R2.e_x + R2.e_y
two_vector = TensorProduct(R2.e_x, R2.e_y)
three_vector = TensorProduct(R2.e_x, R2.e_y, R2.e_x)
two_wp = WedgeProduct(R2.e_x,R2.e_y)
assert covariant_order(one_form) == 1
assert covariant_order(two_form) == 2
assert covariant_order(three_form) == 3
assert covariant_order(two_form + metric) == 2
assert covariant_order(two_form + metric_ambig) == 2
assert covariant_order(two_form + twoform_not_sym) == 2
assert covariant_order(two_form + twoform_not_TP) == 2
assert contravariant_order(one_vector) == 1
assert contravariant_order(two_vector) == 2
assert contravariant_order(three_vector) == 3
assert contravariant_order(two_vector + two_wp) == 2
raises(ValueError, lambda: covariant_order(misform_a))
raises(ValueError, lambda: covariant_order(misform_b))
raises(ValueError, lambda: covariant_order(misform_c))
assert twoform_to_matrix(metric) == Matrix([[1, 0], [0, 1]])
assert twoform_to_matrix(twoform_not_sym) == Matrix([[1, 0], [1, 0]])
assert twoform_to_matrix(twoform_not_TP) == Matrix([[0, -1], [1, 0]])
raises(ValueError, lambda: twoform_to_matrix(one_form))
raises(ValueError, lambda: twoform_to_matrix(three_form))
raises(ValueError, lambda: twoform_to_matrix(metric_ambig))
raises(ValueError, lambda: metric_to_Christoffel_1st(twoform_not_sym))
raises(ValueError, lambda: metric_to_Christoffel_2nd(twoform_not_sym))
raises(ValueError, lambda: metric_to_Riemann_components(twoform_not_sym))
raises(ValueError, lambda: metric_to_Ricci_components(twoform_not_sym))
def test_correct_arguments():
raises(ValueError, lambda: R2.e_x(R2.e_x))
raises(ValueError, lambda: R2.e_x(R2.dx))
raises(ValueError, lambda: Commutator(R2.e_x, R2.x))
raises(ValueError, lambda: Commutator(R2.dx, R2.e_x))
raises(ValueError, lambda: Differential(Differential(R2.e_x)))
raises(ValueError, lambda: R2.dx(R2.x))
raises(ValueError, lambda: LieDerivative(R2.dx, R2.dx))
raises(ValueError, lambda: LieDerivative(R2.x, R2.dx))
raises(ValueError, lambda: CovarDerivativeOp(R2.dx, []))
raises(ValueError, lambda: CovarDerivativeOp(R2.x, []))
a = Symbol('a')
raises(ValueError, lambda: intcurve_series(R2.dx, a, R2_r.point([1, 2])))
raises(ValueError, lambda: intcurve_series(R2.x, a, R2_r.point([1, 2])))
raises(ValueError, lambda: intcurve_diffequ(R2.dx, a, R2_r.point([1, 2])))
raises(ValueError, lambda: intcurve_diffequ(R2.x, a, R2_r.point([1, 2])))
raises(ValueError, lambda: contravariant_order(R2.e_x + R2.dx))
raises(ValueError, lambda: covariant_order(R2.e_x + R2.dx))
raises(ValueError, lambda: contravariant_order(R2.e_x*R2.e_y))
raises(ValueError, lambda: covariant_order(R2.dx*R2.dy))
def test_simplify():
x, y = R2_r.coord_functions()
dx, dy = R2_r.base_oneforms()
ex, ey = R2_r.base_vectors()
assert simplify(x) == x
assert simplify(x*y) == x*y
assert simplify(dx*dy) == dx*dy
assert simplify(ex*ey) == ex*ey
assert ((1-x)*dx)/(1-x)**2 == dx/(1-x)
|
30c7441a74de5ac48a916bb11e68302d468bcca037916c37fd0a5b569d805f5d | from sympy import Mul, Basic, Q, Expr, And, symbols, Or
from sympy.assumptions.sathandlers import (ClassFactRegistry, allargs,
anyarg, exactlyonearg,)
x, y, z = symbols('x y z')
def test_class_handler_registry():
my_handler_registry = ClassFactRegistry()
# The predicate doesn't matter here, so just pass
@my_handler_registry.register(Mul)
def fact1(expr):
pass
@my_handler_registry.multiregister(Expr)
def fact2(expr):
pass
assert my_handler_registry[Basic] == (frozenset(), frozenset())
assert my_handler_registry[Expr] == (frozenset(), frozenset({fact2}))
assert my_handler_registry[Mul] == (frozenset({fact1}), frozenset({fact2}))
def test_allargs():
assert allargs(x, Q.zero(x), x*y) == And(Q.zero(x), Q.zero(y))
assert allargs(x, Q.positive(x) | Q.negative(x), x*y) == And(Q.positive(x) | Q.negative(x), Q.positive(y) | Q.negative(y))
def test_anyarg():
assert anyarg(x, Q.zero(x), x*y) == Or(Q.zero(x), Q.zero(y))
assert anyarg(x, Q.positive(x) & Q.negative(x), x*y) == \
Or(Q.positive(x) & Q.negative(x), Q.positive(y) & Q.negative(y))
def test_exactlyonearg():
assert exactlyonearg(x, Q.zero(x), x*y) == \
Or(Q.zero(x) & ~Q.zero(y), Q.zero(y) & ~Q.zero(x))
assert exactlyonearg(x, Q.zero(x), x*y*z) == \
Or(Q.zero(x) & ~Q.zero(y) & ~Q.zero(z), Q.zero(y)
& ~Q.zero(x) & ~Q.zero(z), Q.zero(z) & ~Q.zero(x) & ~Q.zero(y))
assert exactlyonearg(x, Q.positive(x) | Q.negative(x), x*y) == \
Or((Q.positive(x) | Q.negative(x)) &
~(Q.positive(y) | Q.negative(y)), (Q.positive(y) | Q.negative(y)) &
~(Q.positive(x) | Q.negative(x)))
|
b2e4caf19eaf8693b2d316a3a8a27a205929117c80939fd02e29fed79963059d | from sympy.abc import t, w, x, y, z, n, k, m, p, i
from sympy.assumptions import (ask, AssumptionsContext, Q, register_handler,
remove_handler)
from sympy.assumptions.assume import assuming, global_assumptions, Predicate
from sympy.assumptions.cnf import CNF, Literal
from sympy.assumptions.facts import (single_fact_lookup,
get_known_facts, generate_known_facts_dict, get_known_facts_keys)
from sympy.assumptions.handlers import AskHandler
from sympy.assumptions.ask_generated import (get_all_known_facts,
get_known_facts_dict)
from sympy.core.add import Add
from sympy.core.numbers import (I, Integer, Rational, oo, zoo, pi)
from sympy.core.singleton import S
from sympy.core.power import Pow
from sympy.core.symbol import symbols, Symbol
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import (Abs, im, re, sign)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (
acos, acot, asin, atan, cos, cot, sin, tan)
from sympy.logic.boolalg import Equivalent, Implies, Xor, And, to_cnf
from sympy.matrices import Matrix, SparseMatrix
from sympy.testing.pytest import XFAIL, slow, raises, warns_deprecated_sympy, _both_exp_pow
import math
def test_int_1():
z = 1
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is True
assert ask(Q.rational(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is True
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_int_11():
z = 11
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is True
assert ask(Q.rational(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is True
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is True
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_int_12():
z = 12
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is True
assert ask(Q.rational(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is True
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is True
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_float_1():
z = 1.0
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is None
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is None
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
z = 7.2123
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is None
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is None
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
# test for issue #12168
assert ask(Q.rational(math.pi)) is None
def test_zero_0():
z = Integer(0)
assert ask(Q.nonzero(z)) is False
assert ask(Q.zero(z)) is True
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is True
assert ask(Q.rational(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is False
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is True
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is True
def test_negativeone():
z = Integer(-1)
assert ask(Q.nonzero(z)) is True
assert ask(Q.zero(z)) is False
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is True
assert ask(Q.rational(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is False
assert ask(Q.negative(z)) is True
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is True
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_infinity():
assert ask(Q.commutative(oo)) is True
assert ask(Q.integer(oo)) is False
assert ask(Q.rational(oo)) is False
assert ask(Q.algebraic(oo)) is False
assert ask(Q.real(oo)) is False
assert ask(Q.extended_real(oo)) is True
assert ask(Q.complex(oo)) is False
assert ask(Q.irrational(oo)) is False
assert ask(Q.imaginary(oo)) is False
assert ask(Q.positive(oo)) is False
assert ask(Q.extended_positive(oo)) is True
assert ask(Q.negative(oo)) is False
assert ask(Q.even(oo)) is False
assert ask(Q.odd(oo)) is False
assert ask(Q.finite(oo)) is False
assert ask(Q.infinite(oo)) is True
assert ask(Q.prime(oo)) is False
assert ask(Q.composite(oo)) is False
assert ask(Q.hermitian(oo)) is False
assert ask(Q.antihermitian(oo)) is False
assert ask(Q.positive_infinite(oo)) is True
assert ask(Q.negative_infinite(oo)) is False
def test_neg_infinity():
mm = S.NegativeInfinity
assert ask(Q.commutative(mm)) is True
assert ask(Q.integer(mm)) is False
assert ask(Q.rational(mm)) is False
assert ask(Q.algebraic(mm)) is False
assert ask(Q.real(mm)) is False
assert ask(Q.extended_real(mm)) is True
assert ask(Q.complex(mm)) is False
assert ask(Q.irrational(mm)) is False
assert ask(Q.imaginary(mm)) is False
assert ask(Q.positive(mm)) is False
assert ask(Q.negative(mm)) is False
assert ask(Q.extended_negative(mm)) is True
assert ask(Q.even(mm)) is False
assert ask(Q.odd(mm)) is False
assert ask(Q.finite(mm)) is False
assert ask(Q.infinite(oo)) is True
assert ask(Q.prime(mm)) is False
assert ask(Q.composite(mm)) is False
assert ask(Q.hermitian(mm)) is False
assert ask(Q.antihermitian(mm)) is False
assert ask(Q.positive_infinite(-oo)) is False
assert ask(Q.negative_infinite(-oo)) is True
def test_complex_infinity():
assert ask(Q.commutative(zoo)) is True
assert ask(Q.integer(zoo)) is False
assert ask(Q.rational(zoo)) is False
assert ask(Q.algebraic(zoo)) is False
assert ask(Q.real(zoo)) is False
assert ask(Q.extended_real(zoo)) is False
assert ask(Q.complex(zoo)) is False
assert ask(Q.irrational(zoo)) is False
assert ask(Q.imaginary(zoo)) is False
assert ask(Q.positive(zoo)) is False
assert ask(Q.negative(zoo)) is False
assert ask(Q.zero(zoo)) is False
assert ask(Q.nonzero(zoo)) is False
assert ask(Q.even(zoo)) is False
assert ask(Q.odd(zoo)) is False
assert ask(Q.finite(zoo)) is False
assert ask(Q.infinite(zoo)) is True
assert ask(Q.prime(zoo)) is False
assert ask(Q.composite(zoo)) is False
assert ask(Q.hermitian(zoo)) is False
assert ask(Q.antihermitian(zoo)) is False
assert ask(Q.positive_infinite(zoo)) is False
assert ask(Q.negative_infinite(zoo)) is False
def test_nan():
nan = S.NaN
assert ask(Q.commutative(nan)) is True
assert ask(Q.integer(nan)) is None
assert ask(Q.rational(nan)) is None
assert ask(Q.algebraic(nan)) is None
assert ask(Q.real(nan)) is None
assert ask(Q.extended_real(nan)) is None
assert ask(Q.complex(nan)) is None
assert ask(Q.irrational(nan)) is None
assert ask(Q.imaginary(nan)) is None
assert ask(Q.positive(nan)) is None
assert ask(Q.nonzero(nan)) is None
assert ask(Q.zero(nan)) is None
assert ask(Q.even(nan)) is None
assert ask(Q.odd(nan)) is None
assert ask(Q.finite(nan)) is None
assert ask(Q.infinite(nan)) is None
assert ask(Q.prime(nan)) is None
assert ask(Q.composite(nan)) is None
assert ask(Q.hermitian(nan)) is None
assert ask(Q.antihermitian(nan)) is None
def test_Rational_number():
r = Rational(3, 4)
assert ask(Q.commutative(r)) is True
assert ask(Q.integer(r)) is False
assert ask(Q.rational(r)) is True
assert ask(Q.real(r)) is True
assert ask(Q.complex(r)) is True
assert ask(Q.irrational(r)) is False
assert ask(Q.imaginary(r)) is False
assert ask(Q.positive(r)) is True
assert ask(Q.negative(r)) is False
assert ask(Q.even(r)) is False
assert ask(Q.odd(r)) is False
assert ask(Q.finite(r)) is True
assert ask(Q.prime(r)) is False
assert ask(Q.composite(r)) is False
assert ask(Q.hermitian(r)) is True
assert ask(Q.antihermitian(r)) is False
r = Rational(1, 4)
assert ask(Q.positive(r)) is True
assert ask(Q.negative(r)) is False
r = Rational(5, 4)
assert ask(Q.negative(r)) is False
assert ask(Q.positive(r)) is True
r = Rational(5, 3)
assert ask(Q.positive(r)) is True
assert ask(Q.negative(r)) is False
r = Rational(-3, 4)
assert ask(Q.positive(r)) is False
assert ask(Q.negative(r)) is True
r = Rational(-1, 4)
assert ask(Q.positive(r)) is False
assert ask(Q.negative(r)) is True
r = Rational(-5, 4)
assert ask(Q.negative(r)) is True
assert ask(Q.positive(r)) is False
r = Rational(-5, 3)
assert ask(Q.positive(r)) is False
assert ask(Q.negative(r)) is True
def test_sqrt_2():
z = sqrt(2)
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_pi():
z = S.Pi
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
z = S.Pi + 1
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
z = 2*S.Pi
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
z = S.Pi ** 2
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
z = (1 + S.Pi) ** 2
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_E():
z = S.Exp1
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is False
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_GoldenRatio():
z = S.GoldenRatio
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_TribonacciConstant():
z = S.TribonacciConstant
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is True
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
def test_I():
z = I
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is True
assert ask(Q.real(z)) is False
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is True
assert ask(Q.positive(z)) is False
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is False
assert ask(Q.antihermitian(z)) is True
z = 1 + I
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is True
assert ask(Q.real(z)) is False
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is False
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is False
assert ask(Q.antihermitian(z)) is False
z = I*(1 + I)
assert ask(Q.commutative(z)) is True
assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is False
assert ask(Q.algebraic(z)) is True
assert ask(Q.real(z)) is False
assert ask(Q.complex(z)) is True
assert ask(Q.irrational(z)) is False
assert ask(Q.imaginary(z)) is False
assert ask(Q.positive(z)) is False
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.prime(z)) is False
assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is False
assert ask(Q.antihermitian(z)) is False
z = I**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
z = (-I)**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
z = (3*I)**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is False
z = (1)**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
z = (-1)**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
z = (1+I)**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is False
z = (I)**(I+3)
assert ask(Q.imaginary(z)) is True
assert ask(Q.real(z)) is False
z = (I)**(I+2)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
z = (I)**(2)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
z = (I)**(3)
assert ask(Q.imaginary(z)) is True
assert ask(Q.real(z)) is False
z = (3)**(I)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is False
z = (I)**(0)
assert ask(Q.imaginary(z)) is False
assert ask(Q.real(z)) is True
def test_bounded():
x, y, z = symbols('x,y,z')
assert ask(Q.finite(x)) is None
assert ask(Q.finite(x), Q.finite(x)) is True
assert ask(Q.finite(x), Q.finite(y)) is None
assert ask(Q.finite(x), Q.complex(x)) is True
assert ask(Q.finite(x), Q.extended_real(x)) is None
assert ask(Q.finite(x + 1)) is None
assert ask(Q.finite(x + 1), Q.finite(x)) is True
a = x + y
x, y = a.args
# B + B
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is True
assert ask(Q.finite(a), Q.positive(x) & Q.finite(y)) is True
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)) is True
assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)) is True
assert ask(Q.finite(a), Q.positive(x) & Q.finite(y)
& ~Q.positive(y)) is True
assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x)
& Q.positive(y)) is True
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & ~Q.positive(x)
& ~Q.positive(y)) is True
# B + U
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is False
assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)) is False
assert ask(Q.finite(a), Q.finite(x)
& Q.positive_infinite(y)) is False
assert ask(Q.finite(a), Q.positive(x)
& Q.positive_infinite(y)) is False
assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)
& ~Q.positive(y)) is False
assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x)
& Q.positive_infinite(y)) is False
assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) & ~Q.finite(y)
& ~Q.positive(y)) is False
# B + ?
assert ask(Q.finite(a), Q.finite(x)) is None
assert ask(Q.finite(a), Q.positive(x)) is None
assert ask(Q.finite(a), Q.finite(x)
& Q.extended_positive(y)) is None
assert ask(Q.finite(a), Q.positive(x)
& Q.extended_positive(y)) is None
assert ask(Q.finite(a), Q.positive(x) & ~Q.positive(y)) is None
assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x)
& Q.extended_positive(y)) is None
assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x)
& ~Q.positive(y)) is None
# U + U
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.positive_infinite(x)
& ~Q.finite(y)) is None
assert ask(Q.finite(a), ~Q.finite(x)
& Q.positive_infinite(y)) is None
assert ask(Q.finite(a), Q.positive_infinite(x)
& Q.positive_infinite(y)) is False
assert ask(Q.finite(a), Q.positive_infinite(x) & ~Q.finite(y)
& ~Q.extended_positive(y)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.extended_positive(x)
& Q.positive_infinite(y)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)
& ~Q.extended_positive(x) & ~Q.extended_positive(y)) is False
# U + ?
assert ask(Q.finite(a), ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.extended_positive(x)
& ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.positive_infinite(y)) is None
assert ask(Q.finite(a), Q.extended_positive(x)
& Q.positive_infinite(y)) is False
assert ask(Q.finite(a), Q.extended_positive(x)
& ~Q.finite(y) & ~Q.extended_positive(y)) is None
assert ask(Q.finite(a), ~Q.extended_positive(x)
& Q.positive_infinite(y)) is None
assert ask(Q.finite(a), ~Q.extended_positive(x) & ~Q.finite(y)
& ~Q.extended_positive(y)) is False
# ? + ?
assert ask(Q.finite(a)) is None
assert ask(Q.finite(a), Q.extended_positive(x)) is None
assert ask(Q.finite(a), Q.extended_positive(y)) is None
assert ask(Q.finite(a), Q.extended_positive(x)
& Q.extended_positive(y)) is None
assert ask(Q.finite(a), Q.extended_positive(x)
& ~Q.extended_positive(y)) is None
assert ask(Q.finite(a), ~Q.extended_positive(x)
& Q.extended_positive(y)) is None
assert ask(Q.finite(a), ~Q.extended_positive(x)
& ~Q.extended_positive(y)) is None
x, y, z = symbols('x,y,z')
a = x + y + z
x, y, z = a.args
assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)
& Q.negative(z)) is True
assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)
& Q.finite(z)) is True
assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)
& Q.positive(z)) is True
assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)
& Q.negative_infinite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)
& ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)
& Q.positive_infinite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(y)
& Q.finite(z)) is True
assert ask(Q.finite(a), Q.negative(x) & Q.finite(y)
& Q.positive(z)) is True
assert ask(Q.finite(a), Q.negative(x) & Q.finite(y)
& Q.negative_infinite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.finite(y)
& ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.finite(y)
& Q.positive_infinite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.finite(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.finite(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.positive(y)
& Q.positive(z)) is True
assert ask(Q.finite(a), Q.negative(x) & Q.positive(y)
& Q.negative_infinite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.positive(y)
& ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.positive(y)
& Q.positive_infinite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.positive(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.extended_positive(y)
& Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.positive(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y)
& Q.negative_infinite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y)
& ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y)
& Q.positive_infinite(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y)
& Q.extended_negative(z)) is False
assert ask(Q.finite(a), Q.negative(x)
& Q.negative_infinite(y)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y)
& ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y)
& Q.positive_infinite(z)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y)
& Q.positive_infinite(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y)
& Q.negative_infinite(z)) is None
assert ask(Q.finite(a), Q.negative(x) &
Q.positive_infinite(y)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y)
& Q.extended_positive(z)) is False
assert ask(Q.finite(a), Q.negative(x) & Q.extended_negative(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.negative(x)
& Q.extended_negative(y)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.extended_negative(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative(x)) is None
assert ask(Q.finite(a), Q.negative(x)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative(x) & Q.extended_positive(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)
& Q.finite(z)) is True
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)
& Q.positive(z)) is True
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)
& Q.negative_infinite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)
& ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)
& Q.positive_infinite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)
& Q.positive(z)) is True
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)
& Q.negative_infinite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)
& ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)
& Q.positive_infinite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y)
& Q.negative_infinite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y)
& ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y)
& Q.positive_infinite(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y)
& Q.extended_negative(z)) is False
assert ask(Q.finite(a), Q.finite(x)
& Q.negative_infinite(y)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)
& ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)
& Q.positive_infinite(z)) is None
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y)
& Q.positive_infinite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.finite(x)
& Q.positive_infinite(y)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y)
& Q.extended_positive(z)) is False
assert ask(Q.finite(a), Q.finite(x) & Q.extended_negative(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.finite(x)
& Q.extended_negative(y)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.extended_negative(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.finite(x)) is None
assert ask(Q.finite(a), Q.finite(x)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.extended_positive(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)
& Q.positive(z)) is True
assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)
& Q.negative_infinite(z)) is False
assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)
& ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)
& Q.positive_infinite(z)) is False
assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y)
& Q.negative_infinite(z)) is False
assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y)
& ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y)
& Q.positive_infinite(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y)
& Q.extended_negative(z)) is False
assert ask(Q.finite(a), Q.positive(x)
& Q.negative_infinite(y)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)
& ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)
& Q.positive_infinite(z)) is None
assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y)
& Q.positive_infinite(z)) is False
assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.positive(x)
& Q.positive_infinite(y)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y)
& Q.extended_positive(z)) is False
assert ask(Q.finite(a), Q.positive(x) & Q.extended_negative(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.positive(x)
& Q.extended_negative(y)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.extended_negative(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.positive(x)) is None
assert ask(Q.finite(a), Q.positive(x)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.positive(x) & Q.extended_positive(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.negative_infinite(y) & Q.negative_infinite(z)) is False
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.negative_infinite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.negative_infinite(y)& Q.positive_infinite(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.negative_infinite(y) & Q.extended_negative(z)) is False
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.negative_infinite(y)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.negative_infinite(y) & Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& ~Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& ~Q.finite(y) & Q.positive_infinite(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& ~Q.finite(y) & Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& ~Q.finite(y) & Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.positive_infinite(y) & Q.positive_infinite(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.positive_infinite(y) & Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.positive_infinite(y)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.positive_infinite(y) & Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.extended_negative(y) & Q.extended_negative(z)) is False
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.extended_negative(y)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.extended_negative(y) & Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.negative_infinite(x)
& Q.extended_positive(y) & Q.extended_positive(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)
& ~Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(z)
& ~Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y)
& Q.positive_infinite(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), ~Q.finite(x)
& Q.positive_infinite(y)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_negative(y)
& Q.extended_negative(z)) is None
assert ask(Q.finite(a), ~Q.finite(x)
& Q.extended_negative(y)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_negative(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), ~Q.finite(x)) is None
assert ask(Q.finite(a), ~Q.finite(x)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_positive(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.positive_infinite(x)
& Q.positive_infinite(y) & Q.positive_infinite(z)) is False
assert ask(Q.finite(a), Q.positive_infinite(x)
& Q.positive_infinite(y) & Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.positive_infinite(x)
& Q.positive_infinite(y)) is None
assert ask(Q.finite(a), Q.positive_infinite(x)
& Q.positive_infinite(y) & Q.extended_positive(z)) is False
assert ask(Q.finite(a), Q.positive_infinite(x)
& Q.extended_negative(y) & Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.positive_infinite(x)
& Q.extended_negative(y)) is None
assert ask(Q.finite(a), Q.positive_infinite(x)
& Q.extended_negative(y) & Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.positive_infinite(x)) is None
assert ask(Q.finite(a), Q.positive_infinite(x)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.positive_infinite(x)
& Q.extended_positive(y) & Q.extended_positive(z)) is False
assert ask(Q.finite(a), Q.extended_negative(x)
& Q.extended_negative(y) & Q.extended_negative(z)) is None
assert ask(Q.finite(a), Q.extended_negative(x)
& Q.extended_negative(y)) is None
assert ask(Q.finite(a), Q.extended_negative(x)
& Q.extended_negative(y) & Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.extended_negative(x)) is None
assert ask(Q.finite(a), Q.extended_negative(x)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.extended_negative(x)
& Q.extended_positive(y) & Q.extended_positive(z)) is None
assert ask(Q.finite(a)) is None
assert ask(Q.finite(a), Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.extended_positive(y)
& Q.extended_positive(z)) is None
assert ask(Q.finite(a), Q.extended_positive(x)
& Q.extended_positive(y) & Q.extended_positive(z)) is None
assert ask(Q.finite(2*x)) is None
assert ask(Q.finite(2*x), Q.finite(x)) is True
x, y, z = symbols('x,y,z')
a = x*y
x, y = a.args
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is True
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is False
assert ask(Q.finite(a), Q.finite(x)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y)) is False
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is False
assert ask(Q.finite(a), ~Q.finite(x)) is None
assert ask(Q.finite(a), Q.finite(y)) is None
assert ask(Q.finite(a), ~Q.finite(y)) is None
assert ask(Q.finite(a)) is None
a = x*y*z
x, y, z = a.args
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)
& Q.finite(z)) is True
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)
& ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is None
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)
& Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)
& ~Q.finite(z)) is False
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.finite(x) & Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(x)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y)
& Q.finite(z)) is False
assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y)
& ~Q.finite(z)) is False
assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)
& Q.finite(z)) is False
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)
& ~Q.finite(z)) is False
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None
assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(x)) is None
assert ask(Q.finite(a), Q.finite(y) & Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), Q.finite(y)) is None
assert ask(Q.finite(a), ~Q.finite(y) & Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(y) & ~Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(y)) is None
assert ask(Q.finite(a), Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(z)) is None
assert ask(Q.finite(a), ~Q.finite(z) & Q.extended_nonzero(x)
& Q.extended_nonzero(y) & Q.extended_nonzero(z)) is None
assert ask(Q.finite(a), Q.extended_nonzero(x) & ~Q.finite(y)
& Q.extended_nonzero(y) & ~Q.finite(z)
& Q.extended_nonzero(z)) is False
x, y, z = symbols('x,y,z')
assert ask(Q.finite(x**2)) is None
assert ask(Q.finite(2**x)) is None
assert ask(Q.finite(2**x), Q.finite(x)) is True
assert ask(Q.finite(x**x)) is None
assert ask(Q.finite(S.Half ** x)) is None
assert ask(Q.finite(S.Half ** x), Q.extended_positive(x)) is True
assert ask(Q.finite(S.Half ** x), Q.extended_negative(x)) is None
assert ask(Q.finite(2**x), Q.extended_negative(x)) is True
assert ask(Q.finite(sqrt(x))) is None
assert ask(Q.finite(2**x), ~Q.finite(x)) is False
assert ask(Q.finite(x**2), ~Q.finite(x)) is False
# sign function
assert ask(Q.finite(sign(x))) is True
assert ask(Q.finite(sign(x)), ~Q.finite(x)) is True
# exponential functions
assert ask(Q.finite(log(x))) is None
assert ask(Q.finite(log(x)), Q.finite(x)) is None
assert ask(Q.finite(log(x)), ~Q.zero(x)) is True
assert ask(Q.finite(log(x)), Q.infinite(x)) is False
assert ask(Q.finite(log(x)), Q.zero(x)) is False
assert ask(Q.finite(exp(x))) is None
assert ask(Q.finite(exp(x)), Q.finite(x)) is True
assert ask(Q.finite(exp(2))) is True
# trigonometric functions
assert ask(Q.finite(sin(x))) is True
assert ask(Q.finite(sin(x)), ~Q.finite(x)) is True
assert ask(Q.finite(cos(x))) is True
assert ask(Q.finite(cos(x)), ~Q.finite(x)) is True
assert ask(Q.finite(2*sin(x))) is True
assert ask(Q.finite(sin(x)**2)) is True
assert ask(Q.finite(cos(x)**2)) is True
assert ask(Q.finite(cos(x) + sin(x))) is True
@XFAIL
def test_bounded_xfail():
"""We need to support relations in ask for this to work"""
assert ask(Q.finite(sin(x)**x)) is True
assert ask(Q.finite(cos(x)**x)) is True
def test_commutative():
"""By default objects are Q.commutative that is why it returns True
for both key=True and key=False"""
assert ask(Q.commutative(x)) is True
assert ask(Q.commutative(x), ~Q.commutative(x)) is False
assert ask(Q.commutative(x), Q.complex(x)) is True
assert ask(Q.commutative(x), Q.imaginary(x)) is True
assert ask(Q.commutative(x), Q.real(x)) is True
assert ask(Q.commutative(x), Q.positive(x)) is True
assert ask(Q.commutative(x), ~Q.commutative(y)) is True
assert ask(Q.commutative(2*x)) is True
assert ask(Q.commutative(2*x), ~Q.commutative(x)) is False
assert ask(Q.commutative(x + 1)) is True
assert ask(Q.commutative(x + 1), ~Q.commutative(x)) is False
assert ask(Q.commutative(x**2)) is True
assert ask(Q.commutative(x**2), ~Q.commutative(x)) is False
assert ask(Q.commutative(log(x))) is True
@_both_exp_pow
def test_complex():
assert ask(Q.complex(x)) is None
assert ask(Q.complex(x), Q.complex(x)) is True
assert ask(Q.complex(x), Q.complex(y)) is None
assert ask(Q.complex(x), ~Q.complex(x)) is False
assert ask(Q.complex(x), Q.real(x)) is True
assert ask(Q.complex(x), ~Q.real(x)) is None
assert ask(Q.complex(x), Q.rational(x)) is True
assert ask(Q.complex(x), Q.irrational(x)) is True
assert ask(Q.complex(x), Q.positive(x)) is True
assert ask(Q.complex(x), Q.imaginary(x)) is True
assert ask(Q.complex(x), Q.algebraic(x)) is True
# a+b
assert ask(Q.complex(x + 1), Q.complex(x)) is True
assert ask(Q.complex(x + 1), Q.real(x)) is True
assert ask(Q.complex(x + 1), Q.rational(x)) is True
assert ask(Q.complex(x + 1), Q.irrational(x)) is True
assert ask(Q.complex(x + 1), Q.imaginary(x)) is True
assert ask(Q.complex(x + 1), Q.integer(x)) is True
assert ask(Q.complex(x + 1), Q.even(x)) is True
assert ask(Q.complex(x + 1), Q.odd(x)) is True
assert ask(Q.complex(x + y), Q.complex(x) & Q.complex(y)) is True
assert ask(Q.complex(x + y), Q.real(x) & Q.imaginary(y)) is True
# a*x +b
assert ask(Q.complex(2*x + 1), Q.complex(x)) is True
assert ask(Q.complex(2*x + 1), Q.real(x)) is True
assert ask(Q.complex(2*x + 1), Q.positive(x)) is True
assert ask(Q.complex(2*x + 1), Q.rational(x)) is True
assert ask(Q.complex(2*x + 1), Q.irrational(x)) is True
assert ask(Q.complex(2*x + 1), Q.imaginary(x)) is True
assert ask(Q.complex(2*x + 1), Q.integer(x)) is True
assert ask(Q.complex(2*x + 1), Q.even(x)) is True
assert ask(Q.complex(2*x + 1), Q.odd(x)) is True
# x**2
assert ask(Q.complex(x**2), Q.complex(x)) is True
assert ask(Q.complex(x**2), Q.real(x)) is True
assert ask(Q.complex(x**2), Q.positive(x)) is True
assert ask(Q.complex(x**2), Q.rational(x)) is True
assert ask(Q.complex(x**2), Q.irrational(x)) is True
assert ask(Q.complex(x**2), Q.imaginary(x)) is True
assert ask(Q.complex(x**2), Q.integer(x)) is True
assert ask(Q.complex(x**2), Q.even(x)) is True
assert ask(Q.complex(x**2), Q.odd(x)) is True
# 2**x
assert ask(Q.complex(2**x), Q.complex(x)) is True
assert ask(Q.complex(2**x), Q.real(x)) is True
assert ask(Q.complex(2**x), Q.positive(x)) is True
assert ask(Q.complex(2**x), Q.rational(x)) is True
assert ask(Q.complex(2**x), Q.irrational(x)) is True
assert ask(Q.complex(2**x), Q.imaginary(x)) is True
assert ask(Q.complex(2**x), Q.integer(x)) is True
assert ask(Q.complex(2**x), Q.even(x)) is True
assert ask(Q.complex(2**x), Q.odd(x)) is True
assert ask(Q.complex(x**y), Q.complex(x) & Q.complex(y)) is True
# trigonometric expressions
assert ask(Q.complex(sin(x))) is True
assert ask(Q.complex(sin(2*x + 1))) is True
assert ask(Q.complex(cos(x))) is True
assert ask(Q.complex(cos(2*x + 1))) is True
# exponential
assert ask(Q.complex(exp(x))) is True
assert ask(Q.complex(exp(x))) is True
# Q.complexes
assert ask(Q.complex(Abs(x))) is True
assert ask(Q.complex(re(x))) is True
assert ask(Q.complex(im(x))) is True
def test_even_query():
assert ask(Q.even(x)) is None
assert ask(Q.even(x), Q.integer(x)) is None
assert ask(Q.even(x), ~Q.integer(x)) is False
assert ask(Q.even(x), Q.rational(x)) is None
assert ask(Q.even(x), Q.positive(x)) is None
assert ask(Q.even(2*x)) is None
assert ask(Q.even(2*x), Q.integer(x)) is True
assert ask(Q.even(2*x), Q.even(x)) is True
assert ask(Q.even(2*x), Q.irrational(x)) is False
assert ask(Q.even(2*x), Q.odd(x)) is True
assert ask(Q.even(2*x), ~Q.integer(x)) is None
assert ask(Q.even(3*x), Q.integer(x)) is None
assert ask(Q.even(3*x), Q.even(x)) is True
assert ask(Q.even(3*x), Q.odd(x)) is False
assert ask(Q.even(x + 1), Q.odd(x)) is True
assert ask(Q.even(x + 1), Q.even(x)) is False
assert ask(Q.even(x + 2), Q.odd(x)) is False
assert ask(Q.even(x + 2), Q.even(x)) is True
assert ask(Q.even(7 - x), Q.odd(x)) is True
assert ask(Q.even(7 + x), Q.odd(x)) is True
assert ask(Q.even(x + y), Q.odd(x) & Q.odd(y)) is True
assert ask(Q.even(x + y), Q.odd(x) & Q.even(y)) is False
assert ask(Q.even(x + y), Q.even(x) & Q.even(y)) is True
assert ask(Q.even(2*x + 1), Q.integer(x)) is False
assert ask(Q.even(2*x*y), Q.rational(x) & Q.rational(x)) is None
assert ask(Q.even(2*x*y), Q.irrational(x) & Q.irrational(x)) is None
assert ask(Q.even(x + y + z), Q.odd(x) & Q.odd(y) & Q.even(z)) is True
assert ask(Q.even(x + y + z + t),
Q.odd(x) & Q.odd(y) & Q.even(z) & Q.integer(t)) is None
assert ask(Q.even(Abs(x)), Q.even(x)) is True
assert ask(Q.even(Abs(x)), ~Q.even(x)) is None
assert ask(Q.even(re(x)), Q.even(x)) is True
assert ask(Q.even(re(x)), ~Q.even(x)) is None
assert ask(Q.even(im(x)), Q.even(x)) is True
assert ask(Q.even(im(x)), Q.real(x)) is True
assert ask(Q.even((-1)**n), Q.integer(n)) is False
assert ask(Q.even(k**2), Q.even(k)) is True
assert ask(Q.even(n**2), Q.odd(n)) is False
assert ask(Q.even(2**k), Q.even(k)) is None
assert ask(Q.even(x**2)) is None
assert ask(Q.even(k**m), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None
assert ask(Q.even(n**m), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is False
assert ask(Q.even(k**p), Q.even(k) & Q.integer(p) & Q.positive(p)) is True
assert ask(Q.even(n**p), Q.odd(n) & Q.integer(p) & Q.positive(p)) is False
assert ask(Q.even(m**k), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None
assert ask(Q.even(p**k), Q.even(k) & Q.integer(p) & Q.positive(p)) is None
assert ask(Q.even(m**n), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is None
assert ask(Q.even(p**n), Q.odd(n) & Q.integer(p) & Q.positive(p)) is None
assert ask(Q.even(k**x), Q.even(k)) is None
assert ask(Q.even(n**x), Q.odd(n)) is None
assert ask(Q.even(x*y), Q.integer(x) & Q.integer(y)) is None
assert ask(Q.even(x*x), Q.integer(x)) is None
assert ask(Q.even(x*(x + y)), Q.integer(x) & Q.odd(y)) is True
assert ask(Q.even(x*(x + y)), Q.integer(x) & Q.even(y)) is None
@XFAIL
def test_evenness_in_ternary_integer_product_with_odd():
# Tests that oddness inference is independent of term ordering.
# Term ordering at the point of testing depends on SymPy's symbol order, so
# we try to force a different order by modifying symbol names.
assert ask(Q.even(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is True
assert ask(Q.even(y*x*(x + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is True
def test_evenness_in_ternary_integer_product_with_even():
assert ask(Q.even(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.even(z)) is None
def test_extended_real():
assert ask(Q.extended_real(x), Q.positive_infinite(x)) is True
assert ask(Q.extended_real(x), Q.positive(x)) is True
assert ask(Q.extended_real(x), Q.zero(x)) is True
assert ask(Q.extended_real(x), Q.negative(x)) is True
assert ask(Q.extended_real(x), Q.negative_infinite(x)) is True
assert ask(Q.extended_real(-x), Q.positive(x)) is True
assert ask(Q.extended_real(-x), Q.negative(x)) is True
assert ask(Q.extended_real(x + S.Infinity), Q.real(x)) is True
assert ask(Q.extended_real(x), Q.infinite(x)) is None
@_both_exp_pow
def test_rational():
assert ask(Q.rational(x), Q.integer(x)) is True
assert ask(Q.rational(x), Q.irrational(x)) is False
assert ask(Q.rational(x), Q.real(x)) is None
assert ask(Q.rational(x), Q.positive(x)) is None
assert ask(Q.rational(x), Q.negative(x)) is None
assert ask(Q.rational(x), Q.nonzero(x)) is None
assert ask(Q.rational(x), ~Q.algebraic(x)) is False
assert ask(Q.rational(2*x), Q.rational(x)) is True
assert ask(Q.rational(2*x), Q.integer(x)) is True
assert ask(Q.rational(2*x), Q.even(x)) is True
assert ask(Q.rational(2*x), Q.odd(x)) is True
assert ask(Q.rational(2*x), Q.irrational(x)) is False
assert ask(Q.rational(x/2), Q.rational(x)) is True
assert ask(Q.rational(x/2), Q.integer(x)) is True
assert ask(Q.rational(x/2), Q.even(x)) is True
assert ask(Q.rational(x/2), Q.odd(x)) is True
assert ask(Q.rational(x/2), Q.irrational(x)) is False
assert ask(Q.rational(1/x), Q.rational(x)) is True
assert ask(Q.rational(1/x), Q.integer(x)) is True
assert ask(Q.rational(1/x), Q.even(x)) is True
assert ask(Q.rational(1/x), Q.odd(x)) is True
assert ask(Q.rational(1/x), Q.irrational(x)) is False
assert ask(Q.rational(2/x), Q.rational(x)) is True
assert ask(Q.rational(2/x), Q.integer(x)) is True
assert ask(Q.rational(2/x), Q.even(x)) is True
assert ask(Q.rational(2/x), Q.odd(x)) is True
assert ask(Q.rational(2/x), Q.irrational(x)) is False
assert ask(Q.rational(x), ~Q.algebraic(x)) is False
# with multiple symbols
assert ask(Q.rational(x*y), Q.irrational(x) & Q.irrational(y)) is None
assert ask(Q.rational(y/x), Q.rational(x) & Q.rational(y)) is True
assert ask(Q.rational(y/x), Q.integer(x) & Q.rational(y)) is True
assert ask(Q.rational(y/x), Q.even(x) & Q.rational(y)) is True
assert ask(Q.rational(y/x), Q.odd(x) & Q.rational(y)) is True
assert ask(Q.rational(y/x), Q.irrational(x) & Q.rational(y)) is False
for f in [exp, sin, tan, asin, atan, cos]:
assert ask(Q.rational(f(7))) is False
assert ask(Q.rational(f(7, evaluate=False))) is False
assert ask(Q.rational(f(0, evaluate=False))) is True
assert ask(Q.rational(f(x)), Q.rational(x)) is None
assert ask(Q.rational(f(x)), Q.rational(x) & Q.nonzero(x)) is False
for g in [log, acos]:
assert ask(Q.rational(g(7))) is False
assert ask(Q.rational(g(7, evaluate=False))) is False
assert ask(Q.rational(g(1, evaluate=False))) is True
assert ask(Q.rational(g(x)), Q.rational(x)) is None
assert ask(Q.rational(g(x)), Q.rational(x) & Q.nonzero(x - 1)) is False
for h in [cot, acot]:
assert ask(Q.rational(h(7))) is False
assert ask(Q.rational(h(7, evaluate=False))) is False
assert ask(Q.rational(h(x)), Q.rational(x)) is False
def test_hermitian():
assert ask(Q.hermitian(x)) is None
assert ask(Q.hermitian(x), Q.antihermitian(x)) is None
assert ask(Q.hermitian(x), Q.imaginary(x)) is False
assert ask(Q.hermitian(x), Q.prime(x)) is True
assert ask(Q.hermitian(x), Q.real(x)) is True
assert ask(Q.hermitian(x), Q.zero(x)) is True
assert ask(Q.hermitian(x + 1), Q.antihermitian(x)) is None
assert ask(Q.hermitian(x + 1), Q.complex(x)) is None
assert ask(Q.hermitian(x + 1), Q.hermitian(x)) is True
assert ask(Q.hermitian(x + 1), Q.imaginary(x)) is False
assert ask(Q.hermitian(x + 1), Q.real(x)) is True
assert ask(Q.hermitian(x + I), Q.antihermitian(x)) is None
assert ask(Q.hermitian(x + I), Q.complex(x)) is None
assert ask(Q.hermitian(x + I), Q.hermitian(x)) is False
assert ask(Q.hermitian(x + I), Q.imaginary(x)) is None
assert ask(Q.hermitian(x + I), Q.real(x)) is False
assert ask(
Q.hermitian(x + y), Q.antihermitian(x) & Q.antihermitian(y)) is None
assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.complex(y)) is None
assert ask(
Q.hermitian(x + y), Q.antihermitian(x) & Q.hermitian(y)) is None
assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.imaginary(y)) is None
assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.real(y)) is None
assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.complex(y)) is None
assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.hermitian(y)) is True
assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.imaginary(y)) is False
assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.real(y)) is True
assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.complex(y)) is None
assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.imaginary(y)) is None
assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.real(y)) is False
assert ask(Q.hermitian(x + y), Q.real(x) & Q.complex(y)) is None
assert ask(Q.hermitian(x + y), Q.real(x) & Q.real(y)) is True
assert ask(Q.hermitian(I*x), Q.antihermitian(x)) is True
assert ask(Q.hermitian(I*x), Q.complex(x)) is None
assert ask(Q.hermitian(I*x), Q.hermitian(x)) is False
assert ask(Q.hermitian(I*x), Q.imaginary(x)) is True
assert ask(Q.hermitian(I*x), Q.real(x)) is False
assert ask(Q.hermitian(x*y), Q.hermitian(x) & Q.real(y)) is True
assert ask(
Q.hermitian(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is True
assert ask(Q.hermitian(x + y + z),
Q.real(x) & Q.real(y) & Q.imaginary(z)) is False
assert ask(Q.hermitian(x + y + z),
Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is None
assert ask(Q.hermitian(x + y + z),
Q.imaginary(x) & Q.imaginary(y) & Q.imaginary(z)) is None
assert ask(Q.antihermitian(x)) is None
assert ask(Q.antihermitian(x), Q.real(x)) is False
assert ask(Q.antihermitian(x), Q.prime(x)) is False
assert ask(Q.antihermitian(x + 1), Q.antihermitian(x)) is False
assert ask(Q.antihermitian(x + 1), Q.complex(x)) is None
assert ask(Q.antihermitian(x + 1), Q.hermitian(x)) is None
assert ask(Q.antihermitian(x + 1), Q.imaginary(x)) is False
assert ask(Q.antihermitian(x + 1), Q.real(x)) is None
assert ask(Q.antihermitian(x + I), Q.antihermitian(x)) is True
assert ask(Q.antihermitian(x + I), Q.complex(x)) is None
assert ask(Q.antihermitian(x + I), Q.hermitian(x)) is None
assert ask(Q.antihermitian(x + I), Q.imaginary(x)) is True
assert ask(Q.antihermitian(x + I), Q.real(x)) is False
assert ask(Q.antihermitian(x), Q.zero(x)) is True
assert ask(
Q.antihermitian(x + y), Q.antihermitian(x) & Q.antihermitian(y)
) is True
assert ask(
Q.antihermitian(x + y), Q.antihermitian(x) & Q.complex(y)) is None
assert ask(
Q.antihermitian(x + y), Q.antihermitian(x) & Q.hermitian(y)) is None
assert ask(
Q.antihermitian(x + y), Q.antihermitian(x) & Q.imaginary(y)) is True
assert ask(Q.antihermitian(x + y), Q.antihermitian(x) & Q.real(y)
) is False
assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.complex(y)) is None
assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.hermitian(y)
) is None
assert ask(
Q.antihermitian(x + y), Q.hermitian(x) & Q.imaginary(y)) is None
assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.real(y)) is None
assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.complex(y)) is None
assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.imaginary(y)) is True
assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.real(y)) is False
assert ask(Q.antihermitian(x + y), Q.real(x) & Q.complex(y)) is None
assert ask(Q.antihermitian(x + y), Q.real(x) & Q.real(y)) is None
assert ask(Q.antihermitian(I*x), Q.real(x)) is True
assert ask(Q.antihermitian(I*x), Q.antihermitian(x)) is False
assert ask(Q.antihermitian(I*x), Q.complex(x)) is None
assert ask(Q.antihermitian(x*y), Q.antihermitian(x) & Q.real(y)) is True
assert ask(Q.antihermitian(x + y + z),
Q.real(x) & Q.real(y) & Q.real(z)) is None
assert ask(Q.antihermitian(x + y + z),
Q.real(x) & Q.real(y) & Q.imaginary(z)) is None
assert ask(Q.antihermitian(x + y + z),
Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is False
assert ask(Q.antihermitian(x + y + z),
Q.imaginary(x) & Q.imaginary(y) & Q.imaginary(z)) is True
@_both_exp_pow
def test_imaginary():
assert ask(Q.imaginary(x)) is None
assert ask(Q.imaginary(x), Q.real(x)) is False
assert ask(Q.imaginary(x), Q.prime(x)) is False
assert ask(Q.imaginary(x + 1), Q.real(x)) is False
assert ask(Q.imaginary(x + 1), Q.imaginary(x)) is False
assert ask(Q.imaginary(x + I), Q.real(x)) is False
assert ask(Q.imaginary(x + I), Q.imaginary(x)) is True
assert ask(Q.imaginary(x + y), Q.imaginary(x) & Q.imaginary(y)) is True
assert ask(Q.imaginary(x + y), Q.real(x) & Q.real(y)) is False
assert ask(Q.imaginary(x + y), Q.imaginary(x) & Q.real(y)) is False
assert ask(Q.imaginary(x + y), Q.complex(x) & Q.real(y)) is None
assert ask(
Q.imaginary(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is False
assert ask(Q.imaginary(x + y + z),
Q.real(x) & Q.real(y) & Q.imaginary(z)) is None
assert ask(Q.imaginary(x + y + z),
Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is False
assert ask(Q.imaginary(I*x), Q.real(x)) is True
assert ask(Q.imaginary(I*x), Q.imaginary(x)) is False
assert ask(Q.imaginary(I*x), Q.complex(x)) is None
assert ask(Q.imaginary(x*y), Q.imaginary(x) & Q.real(y)) is True
assert ask(Q.imaginary(x*y), Q.real(x) & Q.real(y)) is False
assert ask(Q.imaginary(I**x), Q.negative(x)) is None
assert ask(Q.imaginary(I**x), Q.positive(x)) is None
assert ask(Q.imaginary(I**x), Q.even(x)) is False
assert ask(Q.imaginary(I**x), Q.odd(x)) is True
assert ask(Q.imaginary(I**x), Q.imaginary(x)) is False
assert ask(Q.imaginary((2*I)**x), Q.imaginary(x)) is False
assert ask(Q.imaginary(x**0), Q.imaginary(x)) is False
assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.imaginary(y)) is None
assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.real(y)) is None
assert ask(Q.imaginary(x**y), Q.real(x) & Q.imaginary(y)) is None
assert ask(Q.imaginary(x**y), Q.real(x) & Q.real(y)) is None
assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.integer(y)) is None
assert ask(Q.imaginary(x**y), Q.imaginary(y) & Q.integer(x)) is None
assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.odd(y)) is True
assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.rational(y)) is None
assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.even(y)) is False
assert ask(Q.imaginary(x**y), Q.real(x) & Q.integer(y)) is False
assert ask(Q.imaginary(x**y), Q.positive(x) & Q.real(y)) is False
assert ask(Q.imaginary(x**y), Q.negative(x) & Q.real(y)) is None
assert ask(Q.imaginary(x**y), Q.negative(x) & Q.real(y) & ~Q.rational(y)) is False
assert ask(Q.imaginary(x**y), Q.integer(x) & Q.imaginary(y)) is None
assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y) & Q.integer(2*y)) is True
assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y) & ~Q.integer(2*y)) is False
assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y)) is None
assert ask(Q.imaginary(x**y), Q.real(x) & Q.rational(y) & ~Q.integer(2*y)) is False
assert ask(Q.imaginary(x**y), Q.real(x) & Q.rational(y) & Q.integer(2*y)) is None
# logarithm
assert ask(Q.imaginary(log(I))) is True
assert ask(Q.imaginary(log(2*I))) is False
assert ask(Q.imaginary(log(I + 1))) is False
assert ask(Q.imaginary(log(x)), Q.complex(x)) is None
assert ask(Q.imaginary(log(x)), Q.imaginary(x)) is None
assert ask(Q.imaginary(log(x)), Q.positive(x)) is False
assert ask(Q.imaginary(log(exp(x))), Q.complex(x)) is None
assert ask(Q.imaginary(log(exp(x))), Q.imaginary(x)) is None # zoo/I/a+I*b
assert ask(Q.imaginary(log(exp(I)))) is True
# exponential
assert ask(Q.imaginary(exp(x)**x), Q.imaginary(x)) is False
eq = Pow(exp(pi*I*x, evaluate=False), x, evaluate=False)
assert ask(Q.imaginary(eq), Q.even(x)) is False
eq = Pow(exp(pi*I*x/2, evaluate=False), x, evaluate=False)
assert ask(Q.imaginary(eq), Q.odd(x)) is True
assert ask(Q.imaginary(exp(3*I*pi*x)**x), Q.integer(x)) is False
assert ask(Q.imaginary(exp(2*pi*I, evaluate=False))) is False
assert ask(Q.imaginary(exp(pi*I/2, evaluate=False))) is True
# issue 7886
assert ask(Q.imaginary(Pow(x, Rational(1, 4))), Q.real(x) & Q.negative(x)) is False
def test_integer():
assert ask(Q.integer(x)) is None
assert ask(Q.integer(x), Q.integer(x)) is True
assert ask(Q.integer(x), ~Q.integer(x)) is False
assert ask(Q.integer(x), ~Q.real(x)) is False
assert ask(Q.integer(x), ~Q.positive(x)) is None
assert ask(Q.integer(x), Q.even(x) | Q.odd(x)) is True
assert ask(Q.integer(2*x), Q.integer(x)) is True
assert ask(Q.integer(2*x), Q.even(x)) is True
assert ask(Q.integer(2*x), Q.prime(x)) is True
assert ask(Q.integer(2*x), Q.rational(x)) is None
assert ask(Q.integer(2*x), Q.real(x)) is None
assert ask(Q.integer(sqrt(2)*x), Q.integer(x)) is False
assert ask(Q.integer(sqrt(2)*x), Q.irrational(x)) is None
assert ask(Q.integer(x/2), Q.odd(x)) is False
assert ask(Q.integer(x/2), Q.even(x)) is True
assert ask(Q.integer(x/3), Q.odd(x)) is None
assert ask(Q.integer(x/3), Q.even(x)) is None
def test_negative():
assert ask(Q.negative(x), Q.negative(x)) is True
assert ask(Q.negative(x), Q.positive(x)) is False
assert ask(Q.negative(x), ~Q.real(x)) is False
assert ask(Q.negative(x), Q.prime(x)) is False
assert ask(Q.negative(x), ~Q.prime(x)) is None
assert ask(Q.negative(-x), Q.positive(x)) is True
assert ask(Q.negative(-x), ~Q.positive(x)) is None
assert ask(Q.negative(-x), Q.negative(x)) is False
assert ask(Q.negative(-x), Q.positive(x)) is True
assert ask(Q.negative(x - 1), Q.negative(x)) is True
assert ask(Q.negative(x + y)) is None
assert ask(Q.negative(x + y), Q.negative(x)) is None
assert ask(Q.negative(x + y), Q.negative(x) & Q.negative(y)) is True
assert ask(Q.negative(x + y), Q.negative(x) & Q.nonpositive(y)) is True
assert ask(Q.negative(2 + I)) is False
# although this could be False, it is representative of expressions
# that don't evaluate to a zero with precision
assert ask(Q.negative(cos(I)**2 + sin(I)**2 - 1)) is None
assert ask(Q.negative(-I + I*(cos(2)**2 + sin(2)**2))) is None
assert ask(Q.negative(x**2)) is None
assert ask(Q.negative(x**2), Q.real(x)) is False
assert ask(Q.negative(x**1.4), Q.real(x)) is None
assert ask(Q.negative(x**I), Q.positive(x)) is None
assert ask(Q.negative(x*y)) is None
assert ask(Q.negative(x*y), Q.positive(x) & Q.positive(y)) is False
assert ask(Q.negative(x*y), Q.positive(x) & Q.negative(y)) is True
assert ask(Q.negative(x*y), Q.complex(x) & Q.complex(y)) is None
assert ask(Q.negative(x**y)) is None
assert ask(Q.negative(x**y), Q.negative(x) & Q.even(y)) is False
assert ask(Q.negative(x**y), Q.negative(x) & Q.odd(y)) is True
assert ask(Q.negative(x**y), Q.positive(x) & Q.integer(y)) is False
assert ask(Q.negative(Abs(x))) is False
def test_nonzero():
assert ask(Q.nonzero(x)) is None
assert ask(Q.nonzero(x), Q.real(x)) is None
assert ask(Q.nonzero(x), Q.positive(x)) is True
assert ask(Q.nonzero(x), Q.negative(x)) is True
assert ask(Q.nonzero(x), Q.negative(x) | Q.positive(x)) is True
assert ask(Q.nonzero(x + y)) is None
assert ask(Q.nonzero(x + y), Q.positive(x) & Q.positive(y)) is True
assert ask(Q.nonzero(x + y), Q.positive(x) & Q.negative(y)) is None
assert ask(Q.nonzero(x + y), Q.negative(x) & Q.negative(y)) is True
assert ask(Q.nonzero(2*x)) is None
assert ask(Q.nonzero(2*x), Q.positive(x)) is True
assert ask(Q.nonzero(2*x), Q.negative(x)) is True
assert ask(Q.nonzero(x*y), Q.nonzero(x)) is None
assert ask(Q.nonzero(x*y), Q.nonzero(x) & Q.nonzero(y)) is True
assert ask(Q.nonzero(x**y), Q.nonzero(x)) is True
assert ask(Q.nonzero(Abs(x))) is None
assert ask(Q.nonzero(Abs(x)), Q.nonzero(x)) is True
assert ask(Q.nonzero(log(exp(2*I)))) is False
# although this could be False, it is representative of expressions
# that don't evaluate to a zero with precision
assert ask(Q.nonzero(cos(1)**2 + sin(1)**2 - 1)) is None
def test_zero():
assert ask(Q.zero(x)) is None
assert ask(Q.zero(x), Q.real(x)) is None
assert ask(Q.zero(x), Q.positive(x)) is False
assert ask(Q.zero(x), Q.negative(x)) is False
assert ask(Q.zero(x), Q.negative(x) | Q.positive(x)) is False
assert ask(Q.zero(x), Q.nonnegative(x) & Q.nonpositive(x)) is True
assert ask(Q.zero(x + y)) is None
assert ask(Q.zero(x + y), Q.positive(x) & Q.positive(y)) is False
assert ask(Q.zero(x + y), Q.positive(x) & Q.negative(y)) is None
assert ask(Q.zero(x + y), Q.negative(x) & Q.negative(y)) is False
assert ask(Q.zero(2*x)) is None
assert ask(Q.zero(2*x), Q.positive(x)) is False
assert ask(Q.zero(2*x), Q.negative(x)) is False
assert ask(Q.zero(x*y), Q.nonzero(x)) is None
assert ask(Q.zero(Abs(x))) is None
assert ask(Q.zero(Abs(x)), Q.zero(x)) is True
assert ask(Q.integer(x), Q.zero(x)) is True
assert ask(Q.even(x), Q.zero(x)) is True
assert ask(Q.odd(x), Q.zero(x)) is False
assert ask(Q.zero(x), Q.even(x)) is None
assert ask(Q.zero(x), Q.odd(x)) is False
assert ask(Q.zero(x) | Q.zero(y), Q.zero(x*y)) is True
def test_odd_query():
assert ask(Q.odd(x)) is None
assert ask(Q.odd(x), Q.odd(x)) is True
assert ask(Q.odd(x), Q.integer(x)) is None
assert ask(Q.odd(x), ~Q.integer(x)) is False
assert ask(Q.odd(x), Q.rational(x)) is None
assert ask(Q.odd(x), Q.positive(x)) is None
assert ask(Q.odd(-x), Q.odd(x)) is True
assert ask(Q.odd(2*x)) is None
assert ask(Q.odd(2*x), Q.integer(x)) is False
assert ask(Q.odd(2*x), Q.odd(x)) is False
assert ask(Q.odd(2*x), Q.irrational(x)) is False
assert ask(Q.odd(2*x), ~Q.integer(x)) is None
assert ask(Q.odd(3*x), Q.integer(x)) is None
assert ask(Q.odd(x/3), Q.odd(x)) is None
assert ask(Q.odd(x/3), Q.even(x)) is None
assert ask(Q.odd(x + 1), Q.even(x)) is True
assert ask(Q.odd(x + 2), Q.even(x)) is False
assert ask(Q.odd(x + 2), Q.odd(x)) is True
assert ask(Q.odd(3 - x), Q.odd(x)) is False
assert ask(Q.odd(3 - x), Q.even(x)) is True
assert ask(Q.odd(3 + x), Q.odd(x)) is False
assert ask(Q.odd(3 + x), Q.even(x)) is True
assert ask(Q.odd(x + y), Q.odd(x) & Q.odd(y)) is False
assert ask(Q.odd(x + y), Q.odd(x) & Q.even(y)) is True
assert ask(Q.odd(x - y), Q.even(x) & Q.odd(y)) is True
assert ask(Q.odd(x - y), Q.odd(x) & Q.odd(y)) is False
assert ask(Q.odd(x + y + z), Q.odd(x) & Q.odd(y) & Q.even(z)) is False
assert ask(Q.odd(x + y + z + t),
Q.odd(x) & Q.odd(y) & Q.even(z) & Q.integer(t)) is None
assert ask(Q.odd(2*x + 1), Q.integer(x)) is True
assert ask(Q.odd(2*x + y), Q.integer(x) & Q.odd(y)) is True
assert ask(Q.odd(2*x + y), Q.integer(x) & Q.even(y)) is False
assert ask(Q.odd(2*x + y), Q.integer(x) & Q.integer(y)) is None
assert ask(Q.odd(x*y), Q.odd(x) & Q.even(y)) is False
assert ask(Q.odd(x*y), Q.odd(x) & Q.odd(y)) is True
assert ask(Q.odd(2*x*y), Q.rational(x) & Q.rational(x)) is None
assert ask(Q.odd(2*x*y), Q.irrational(x) & Q.irrational(x)) is None
assert ask(Q.odd(Abs(x)), Q.odd(x)) is True
assert ask(Q.odd((-1)**n), Q.integer(n)) is True
assert ask(Q.odd(k**2), Q.even(k)) is False
assert ask(Q.odd(n**2), Q.odd(n)) is True
assert ask(Q.odd(3**k), Q.even(k)) is None
assert ask(Q.odd(k**m), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None
assert ask(Q.odd(n**m), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is True
assert ask(Q.odd(k**p), Q.even(k) & Q.integer(p) & Q.positive(p)) is False
assert ask(Q.odd(n**p), Q.odd(n) & Q.integer(p) & Q.positive(p)) is True
assert ask(Q.odd(m**k), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None
assert ask(Q.odd(p**k), Q.even(k) & Q.integer(p) & Q.positive(p)) is None
assert ask(Q.odd(m**n), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is None
assert ask(Q.odd(p**n), Q.odd(n) & Q.integer(p) & Q.positive(p)) is None
assert ask(Q.odd(k**x), Q.even(k)) is None
assert ask(Q.odd(n**x), Q.odd(n)) is None
assert ask(Q.odd(x*y), Q.integer(x) & Q.integer(y)) is None
assert ask(Q.odd(x*x), Q.integer(x)) is None
assert ask(Q.odd(x*(x + y)), Q.integer(x) & Q.odd(y)) is False
assert ask(Q.odd(x*(x + y)), Q.integer(x) & Q.even(y)) is None
@XFAIL
def test_oddness_in_ternary_integer_product_with_odd():
# Tests that oddness inference is independent of term ordering.
# Term ordering at the point of testing depends on SymPy's symbol order, so
# we try to force a different order by modifying symbol names.
assert ask(Q.odd(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is False
assert ask(Q.odd(y*x*(x + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is False
def test_oddness_in_ternary_integer_product_with_even():
assert ask(Q.odd(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.even(z)) is None
def test_prime():
assert ask(Q.prime(x), Q.prime(x)) is True
assert ask(Q.prime(x), ~Q.prime(x)) is False
assert ask(Q.prime(x), Q.integer(x)) is None
assert ask(Q.prime(x), ~Q.integer(x)) is False
assert ask(Q.prime(2*x), Q.integer(x)) is None
assert ask(Q.prime(x*y)) is None
assert ask(Q.prime(x*y), Q.prime(x)) is None
assert ask(Q.prime(x*y), Q.integer(x) & Q.integer(y)) is None
assert ask(Q.prime(4*x), Q.integer(x)) is False
assert ask(Q.prime(4*x)) is None
assert ask(Q.prime(x**2), Q.integer(x)) is False
assert ask(Q.prime(x**2), Q.prime(x)) is False
assert ask(Q.prime(x**y), Q.integer(x) & Q.integer(y)) is False
@_both_exp_pow
def test_positive():
assert ask(Q.positive(x), Q.positive(x)) is True
assert ask(Q.positive(x), Q.negative(x)) is False
assert ask(Q.positive(x), Q.nonzero(x)) is None
assert ask(Q.positive(-x), Q.positive(x)) is False
assert ask(Q.positive(-x), Q.negative(x)) is True
assert ask(Q.positive(x + y), Q.positive(x) & Q.positive(y)) is True
assert ask(Q.positive(x + y), Q.positive(x) & Q.nonnegative(y)) is True
assert ask(Q.positive(x + y), Q.positive(x) & Q.negative(y)) is None
assert ask(Q.positive(x + y), Q.positive(x) & Q.imaginary(y)) is False
assert ask(Q.positive(2*x), Q.positive(x)) is True
assumptions = Q.positive(x) & Q.negative(y) & Q.negative(z) & Q.positive(w)
assert ask(Q.positive(x*y*z)) is None
assert ask(Q.positive(x*y*z), assumptions) is True
assert ask(Q.positive(-x*y*z), assumptions) is False
assert ask(Q.positive(x**I), Q.positive(x)) is None
assert ask(Q.positive(x**2), Q.positive(x)) is True
assert ask(Q.positive(x**2), Q.negative(x)) is True
assert ask(Q.positive(x**3), Q.negative(x)) is False
assert ask(Q.positive(1/(1 + x**2)), Q.real(x)) is True
assert ask(Q.positive(2**I)) is False
assert ask(Q.positive(2 + I)) is False
# although this could be False, it is representative of expressions
# that don't evaluate to a zero with precision
assert ask(Q.positive(cos(I)**2 + sin(I)**2 - 1)) is None
assert ask(Q.positive(-I + I*(cos(2)**2 + sin(2)**2))) is None
#exponential
assert ask(Q.positive(exp(x)), Q.real(x)) is True
assert ask(~Q.negative(exp(x)), Q.real(x)) is True
assert ask(Q.positive(x + exp(x)), Q.real(x)) is None
assert ask(Q.positive(exp(x)), Q.imaginary(x)) is None
assert ask(Q.positive(exp(2*pi*I, evaluate=False)), Q.imaginary(x)) is True
assert ask(Q.negative(exp(pi*I, evaluate=False)), Q.imaginary(x)) is True
assert ask(Q.positive(exp(x*pi*I)), Q.even(x)) is True
assert ask(Q.positive(exp(x*pi*I)), Q.odd(x)) is False
assert ask(Q.positive(exp(x*pi*I)), Q.real(x)) is None
# logarithm
assert ask(Q.positive(log(x)), Q.imaginary(x)) is False
assert ask(Q.positive(log(x)), Q.negative(x)) is False
assert ask(Q.positive(log(x)), Q.positive(x)) is None
assert ask(Q.positive(log(x + 2)), Q.positive(x)) is True
# factorial
assert ask(Q.positive(factorial(x)), Q.integer(x) & Q.positive(x))
assert ask(Q.positive(factorial(x)), Q.integer(x)) is None
#absolute value
assert ask(Q.positive(Abs(x))) is None # Abs(0) = 0
assert ask(Q.positive(Abs(x)), Q.positive(x)) is True
def test_nonpositive():
assert ask(Q.nonpositive(-1))
assert ask(Q.nonpositive(0))
assert ask(Q.nonpositive(1)) is False
assert ask(~Q.positive(x), Q.nonpositive(x))
assert ask(Q.nonpositive(x), Q.positive(x)) is False
assert ask(Q.nonpositive(sqrt(-1))) is False
assert ask(Q.nonpositive(x), Q.imaginary(x)) is False
def test_nonnegative():
assert ask(Q.nonnegative(-1)) is False
assert ask(Q.nonnegative(0))
assert ask(Q.nonnegative(1))
assert ask(~Q.negative(x), Q.nonnegative(x))
assert ask(Q.nonnegative(x), Q.negative(x)) is False
assert ask(Q.nonnegative(sqrt(-1))) is False
assert ask(Q.nonnegative(x), Q.imaginary(x)) is False
def test_real_basic():
assert ask(Q.real(x)) is None
assert ask(Q.real(x), Q.real(x)) is True
assert ask(Q.real(x), Q.nonzero(x)) is True
assert ask(Q.real(x), Q.positive(x)) is True
assert ask(Q.real(x), Q.negative(x)) is True
assert ask(Q.real(x), Q.integer(x)) is True
assert ask(Q.real(x), Q.even(x)) is True
assert ask(Q.real(x), Q.prime(x)) is True
assert ask(Q.real(x/sqrt(2)), Q.real(x)) is True
assert ask(Q.real(x/sqrt(-2)), Q.real(x)) is False
assert ask(Q.real(x + 1), Q.real(x)) is True
assert ask(Q.real(x + I), Q.real(x)) is False
assert ask(Q.real(x + I), Q.complex(x)) is None
assert ask(Q.real(2*x), Q.real(x)) is True
assert ask(Q.real(I*x), Q.real(x)) is False
assert ask(Q.real(I*x), Q.imaginary(x)) is True
assert ask(Q.real(I*x), Q.complex(x)) is None
def test_real_pow():
assert ask(Q.real(x**2), Q.real(x)) is True
assert ask(Q.real(sqrt(x)), Q.negative(x)) is False
assert ask(Q.real(x**y), Q.real(x) & Q.integer(y)) is True
assert ask(Q.real(x**y), Q.real(x) & Q.real(y)) is None
assert ask(Q.real(x**y), Q.positive(x) & Q.real(y)) is True
assert ask(Q.real(x**y), Q.imaginary(x) & Q.imaginary(y)) is None # I**I or (2*I)**I
assert ask(Q.real(x**y), Q.imaginary(x) & Q.real(y)) is None # I**1 or I**0
assert ask(Q.real(x**y), Q.real(x) & Q.imaginary(y)) is None # could be exp(2*pi*I) or 2**I
assert ask(Q.real(x**0), Q.imaginary(x)) is True
assert ask(Q.real(x**y), Q.real(x) & Q.integer(y)) is True
assert ask(Q.real(x**y), Q.positive(x) & Q.real(y)) is True
assert ask(Q.real(x**y), Q.real(x) & Q.rational(y)) is None
assert ask(Q.real(x**y), Q.imaginary(x) & Q.integer(y)) is None
assert ask(Q.real(x**y), Q.imaginary(x) & Q.odd(y)) is False
assert ask(Q.real(x**y), Q.imaginary(x) & Q.even(y)) is True
assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.rational(y/z) & Q.even(z) & Q.positive(x)) is True
assert ask(Q.real(x**(y/z)), Q.real(x) & Q.rational(y/z) & Q.even(z) & Q.negative(x)) is False
assert ask(Q.real(x**(y/z)), Q.real(x) & Q.integer(y/z)) is True
assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.positive(x)) is True
assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.negative(x)) is False
assert ask(Q.real((-I)**i), Q.imaginary(i)) is True
assert ask(Q.real(I**i), Q.imaginary(i)) is True
assert ask(Q.real(i**i), Q.imaginary(i)) is None # i might be 2*I
assert ask(Q.real(x**i), Q.imaginary(i)) is None # x could be 0
assert ask(Q.real(x**(I*pi/log(x))), Q.real(x)) is True
@_both_exp_pow
def test_real_functions():
# trigonometric functions
assert ask(Q.real(sin(x))) is None
assert ask(Q.real(cos(x))) is None
assert ask(Q.real(sin(x)), Q.real(x)) is True
assert ask(Q.real(cos(x)), Q.real(x)) is True
# exponential function
assert ask(Q.real(exp(x))) is None
assert ask(Q.real(exp(x)), Q.real(x)) is True
assert ask(Q.real(x + exp(x)), Q.real(x)) is True
assert ask(Q.real(exp(2*pi*I, evaluate=False))) is True
assert ask(Q.real(exp(pi*I, evaluate=False))) is True
assert ask(Q.real(exp(pi*I/2, evaluate=False))) is False
# logarithm
assert ask(Q.real(log(I))) is False
assert ask(Q.real(log(2*I))) is False
assert ask(Q.real(log(I + 1))) is False
assert ask(Q.real(log(x)), Q.complex(x)) is None
assert ask(Q.real(log(x)), Q.imaginary(x)) is False
assert ask(Q.real(log(exp(x))), Q.imaginary(x)) is None # exp(2*pi*I) is 1, log(exp(pi*I)) is pi*I (disregarding periodicity)
assert ask(Q.real(log(exp(x))), Q.complex(x)) is None
eq = Pow(exp(2*pi*I*x, evaluate=False), x, evaluate=False)
assert ask(Q.real(eq), Q.integer(x)) is True
assert ask(Q.real(exp(x)**x), Q.imaginary(x)) is True
assert ask(Q.real(exp(x)**x), Q.complex(x)) is None
# Q.complexes
assert ask(Q.real(re(x))) is True
assert ask(Q.real(im(x))) is True
def test_matrix():
# hermitian
assert ask(Q.hermitian(Matrix([[2, 2 + I, 4], [2 - I, 3, I], [4, -I, 1]]))) == True
assert ask(Q.hermitian(Matrix([[2, 2 + I, 4], [2 + I, 3, I], [4, -I, 1]]))) == False
z = symbols('z', complex=True)
assert ask(Q.hermitian(Matrix([[2, 2 + I, z], [2 - I, 3, I], [4, -I, 1]]))) == None
assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))))) == True
assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, I, 0), (-5, 0, 11))))) == False
assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, z, 0), (-5, 0, 11))))) == None
# antihermitian
A = Matrix([[0, -2 - I, 0], [2 - I, 0, -I], [0, -I, 0]])
B = Matrix([[-I, 2 + I, 0], [-2 + I, 0, 2 + I], [0, -2 + I, -I]])
assert ask(Q.antihermitian(A)) is True
assert ask(Q.antihermitian(B)) is True
assert ask(Q.antihermitian(A**2)) is False
C = (B**3)
C.simplify()
assert ask(Q.antihermitian(C)) is True
_A = Matrix([[0, -2 - I, 0], [z, 0, -I], [0, -I, 0]])
assert ask(Q.antihermitian(_A)) is None
@_both_exp_pow
def test_algebraic():
assert ask(Q.algebraic(x)) is None
assert ask(Q.algebraic(I)) is True
assert ask(Q.algebraic(2*I)) is True
assert ask(Q.algebraic(I/3)) is True
assert ask(Q.algebraic(sqrt(7))) is True
assert ask(Q.algebraic(2*sqrt(7))) is True
assert ask(Q.algebraic(sqrt(7)/3)) is True
assert ask(Q.algebraic(I*sqrt(3))) is True
assert ask(Q.algebraic(sqrt(1 + I*sqrt(3)))) is True
assert ask(Q.algebraic(1 + I*sqrt(3)**Rational(17, 31))) is True
assert ask(Q.algebraic(1 + I*sqrt(3)**(17/pi))) is False
for f in [exp, sin, tan, asin, atan, cos]:
assert ask(Q.algebraic(f(7))) is False
assert ask(Q.algebraic(f(7, evaluate=False))) is False
assert ask(Q.algebraic(f(0, evaluate=False))) is True
assert ask(Q.algebraic(f(x)), Q.algebraic(x)) is None
assert ask(Q.algebraic(f(x)), Q.algebraic(x) & Q.nonzero(x)) is False
for g in [log, acos]:
assert ask(Q.algebraic(g(7))) is False
assert ask(Q.algebraic(g(7, evaluate=False))) is False
assert ask(Q.algebraic(g(1, evaluate=False))) is True
assert ask(Q.algebraic(g(x)), Q.algebraic(x)) is None
assert ask(Q.algebraic(g(x)), Q.algebraic(x) & Q.nonzero(x - 1)) is False
for h in [cot, acot]:
assert ask(Q.algebraic(h(7))) is False
assert ask(Q.algebraic(h(7, evaluate=False))) is False
assert ask(Q.algebraic(h(x)), Q.algebraic(x)) is False
assert ask(Q.algebraic(sqrt(sin(7)))) is False
assert ask(Q.algebraic(sqrt(y + I*sqrt(7)))) is None
assert ask(Q.algebraic(2.47)) is True
assert ask(Q.algebraic(x), Q.transcendental(x)) is False
assert ask(Q.transcendental(x), Q.algebraic(x)) is False
def test_global():
"""Test ask with global assumptions"""
assert ask(Q.integer(x)) is None
global_assumptions.add(Q.integer(x))
assert ask(Q.integer(x)) is True
global_assumptions.clear()
assert ask(Q.integer(x)) is None
def test_custom_context():
"""Test ask with custom assumptions context"""
assert ask(Q.integer(x)) is None
local_context = AssumptionsContext()
local_context.add(Q.integer(x))
assert ask(Q.integer(x), context=local_context) is True
assert ask(Q.integer(x)) is None
def test_functions_in_assumptions():
assert ask(Q.negative(x), Q.real(x) >> Q.positive(x)) is False
assert ask(Q.negative(x), Equivalent(Q.real(x), Q.positive(x))) is False
assert ask(Q.negative(x), Xor(Q.real(x), Q.negative(x))) is False
def test_composite_ask():
assert ask(Q.negative(x) & Q.integer(x),
assumptions=Q.real(x) >> Q.positive(x)) is False
def test_composite_proposition():
assert ask(True) is True
assert ask(False) is False
assert ask(~Q.negative(x), Q.positive(x)) is True
assert ask(~Q.real(x), Q.commutative(x)) is None
assert ask(Q.negative(x) & Q.integer(x), Q.positive(x)) is False
assert ask(Q.negative(x) & Q.integer(x)) is None
assert ask(Q.real(x) | Q.integer(x), Q.positive(x)) is True
assert ask(Q.real(x) | Q.integer(x)) is None
assert ask(Q.real(x) >> Q.positive(x), Q.negative(x)) is False
assert ask(Implies(
Q.real(x), Q.positive(x), evaluate=False), Q.negative(x)) is False
assert ask(Implies(Q.real(x), Q.positive(x), evaluate=False)) is None
assert ask(Equivalent(Q.integer(x), Q.even(x)), Q.even(x)) is True
assert ask(Equivalent(Q.integer(x), Q.even(x))) is None
assert ask(Equivalent(Q.positive(x), Q.integer(x)), Q.integer(x)) is None
assert ask(Q.real(x) | Q.integer(x), Q.real(x) | Q.integer(x)) is True
def test_tautology():
assert ask(Q.real(x) | ~Q.real(x)) is True
assert ask(Q.real(x) & ~Q.real(x)) is False
def test_composite_assumptions():
assert ask(Q.real(x), Q.real(x) & Q.real(y)) is True
assert ask(Q.positive(x), Q.positive(x) | Q.positive(y)) is None
assert ask(Q.positive(x), Q.real(x) >> Q.positive(y)) is None
assert ask(Q.real(x), ~(Q.real(x) >> Q.real(y))) is True
def test_key_extensibility():
"""test that you can add keys to the ask system at runtime"""
# make sure the key is not defined
raises(AttributeError, lambda: ask(Q.my_key(x)))
# Old handler system
class MyAskHandler(AskHandler):
@staticmethod
def Symbol(expr, assumptions):
return True
try:
with warns_deprecated_sympy():
register_handler('my_key', MyAskHandler)
with warns_deprecated_sympy():
assert ask(Q.my_key(x)) is True
with warns_deprecated_sympy():
assert ask(Q.my_key(x + 1)) is None
finally:
with warns_deprecated_sympy():
remove_handler('my_key', MyAskHandler)
del Q.my_key
raises(AttributeError, lambda: ask(Q.my_key(x)))
# New handler system
class MyPredicate(Predicate):
pass
try:
Q.my_key = MyPredicate()
@Q.my_key.register(Symbol)
def _(expr, assumptions):
return True
assert ask(Q.my_key(x)) is True
assert ask(Q.my_key(x+1)) is None
finally:
del Q.my_key
raises(AttributeError, lambda: ask(Q.my_key(x)))
def test_type_extensibility():
"""test that new types can be added to the ask system at runtime
"""
from sympy.core import Basic
class MyType(Basic):
pass
@Q.prime.register(MyType)
def _(expr, assumptions):
return True
assert ask(Q.prime(MyType())) is True
def test_single_fact_lookup():
known_facts = And(Implies(Q.integer, Q.rational),
Implies(Q.rational, Q.real),
Implies(Q.real, Q.complex))
known_facts_keys = {Q.integer, Q.rational, Q.real, Q.complex}
known_facts_cnf = to_cnf(known_facts)
mapping = single_fact_lookup(known_facts_keys, known_facts_cnf)
assert mapping[Q.rational] == {Q.real, Q.rational, Q.complex}
def test_generate_known_facts_dict():
known_facts = And(Implies(Q.integer(x), Q.rational(x)),
Implies(Q.rational(x), Q.real(x)),
Implies(Q.real(x), Q.complex(x)))
known_facts_keys = {Q.integer(x), Q.rational(x), Q.real(x), Q.complex(x)}
assert generate_known_facts_dict(known_facts_keys, known_facts) == \
{Q.complex: ({Q.complex}, set()),
Q.integer: ({Q.complex, Q.integer, Q.rational, Q.real}, set()),
Q.rational: ({Q.complex, Q.rational, Q.real}, set()),
Q.real: ({Q.complex, Q.real}, set())}
@slow
def test_known_facts_consistent():
""""Test that ask_generated.py is up-to-date"""
x = Symbol('x')
fact = get_known_facts(x)
# test cnf clauses of fact between unary predicates
cnf = CNF.to_CNF(fact)
clauses = set()
for cl in cnf.clauses:
clauses.add(frozenset(Literal(lit.arg.function, lit.is_Not) for lit in sorted(cl, key=str)))
assert get_all_known_facts() == clauses
# test dictionary of fact between unary predicates
keys = [pred(x) for pred in get_known_facts_keys()]
mapping = generate_known_facts_dict(keys, fact)
assert get_known_facts_dict() == mapping
def test_Add_queries():
assert ask(Q.prime(12345678901234567890 + (cos(1)**2 + sin(1)**2))) is True
assert ask(Q.even(Add(S(2), S(2), evaluate=0))) is True
assert ask(Q.prime(Add(S(2), S(2), evaluate=0))) is False
assert ask(Q.integer(Add(S(2), S(2), evaluate=0))) is True
def test_positive_assuming():
with assuming(Q.positive(x + 1)):
assert not ask(Q.positive(x))
def test_issue_5421():
raises(TypeError, lambda: ask(pi/log(x), Q.real))
def test_issue_3906():
raises(TypeError, lambda: ask(Q.positive))
def test_issue_5833():
assert ask(Q.positive(log(x)**2), Q.positive(x)) is None
assert ask(~Q.negative(log(x)**2), Q.positive(x)) is True
def test_issue_6732():
raises(ValueError, lambda: ask(Q.positive(x), Q.positive(x) & Q.negative(x)))
raises(ValueError, lambda: ask(Q.negative(x), Q.positive(x) & Q.negative(x)))
def test_issue_7246():
assert ask(Q.positive(atan(p)), Q.positive(p)) is True
assert ask(Q.positive(atan(p)), Q.negative(p)) is False
assert ask(Q.positive(atan(p)), Q.zero(p)) is False
assert ask(Q.positive(atan(x))) is None
assert ask(Q.positive(asin(p)), Q.positive(p)) is None
assert ask(Q.positive(asin(p)), Q.zero(p)) is None
assert ask(Q.positive(asin(Rational(1, 7)))) is True
assert ask(Q.positive(asin(x)), Q.positive(x) & Q.nonpositive(x - 1)) is True
assert ask(Q.positive(asin(x)), Q.negative(x) & Q.nonnegative(x + 1)) is False
assert ask(Q.positive(acos(p)), Q.positive(p)) is None
assert ask(Q.positive(acos(Rational(1, 7)))) is True
assert ask(Q.positive(acos(x)), Q.nonnegative(x + 1) & Q.nonpositive(x - 1)) is True
assert ask(Q.positive(acos(x)), Q.nonnegative(x - 1)) is None
assert ask(Q.positive(acot(x)), Q.positive(x)) is True
assert ask(Q.positive(acot(x)), Q.real(x)) is True
assert ask(Q.positive(acot(x)), Q.imaginary(x)) is False
assert ask(Q.positive(acot(x))) is None
@XFAIL
def test_issue_7246_failing():
#Move this test to test_issue_7246 once
#the new assumptions module is improved.
assert ask(Q.positive(acos(x)), Q.zero(x)) is True
def test_check_old_assumption():
x = symbols('x', real=True)
assert ask(Q.real(x)) is True
assert ask(Q.imaginary(x)) is False
assert ask(Q.complex(x)) is True
x = symbols('x', imaginary=True)
assert ask(Q.real(x)) is False
assert ask(Q.imaginary(x)) is True
assert ask(Q.complex(x)) is True
x = symbols('x', complex=True)
assert ask(Q.real(x)) is None
assert ask(Q.complex(x)) is True
x = symbols('x', positive=True, finite=True)
assert ask(Q.positive(x)) is True
assert ask(Q.negative(x)) is False
assert ask(Q.real(x)) is True
x = symbols('x', commutative=False)
assert ask(Q.commutative(x)) is False
x = symbols('x', negative=True)
assert ask(Q.positive(x)) is False
assert ask(Q.negative(x)) is True
x = symbols('x', nonnegative=True)
assert ask(Q.negative(x)) is False
assert ask(Q.positive(x)) is None
assert ask(Q.zero(x)) is None
x = symbols('x', finite=True)
assert ask(Q.finite(x)) is True
x = symbols('x', prime=True)
assert ask(Q.prime(x)) is True
assert ask(Q.composite(x)) is False
x = symbols('x', composite=True)
assert ask(Q.prime(x)) is False
assert ask(Q.composite(x)) is True
x = symbols('x', even=True)
assert ask(Q.even(x)) is True
assert ask(Q.odd(x)) is False
x = symbols('x', odd=True)
assert ask(Q.even(x)) is False
assert ask(Q.odd(x)) is True
x = symbols('x', nonzero=True)
assert ask(Q.nonzero(x)) is True
assert ask(Q.zero(x)) is False
x = symbols('x', zero=True)
assert ask(Q.zero(x)) is True
x = symbols('x', integer=True)
assert ask(Q.integer(x)) is True
x = symbols('x', rational=True)
assert ask(Q.rational(x)) is True
assert ask(Q.irrational(x)) is False
x = symbols('x', irrational=True)
assert ask(Q.irrational(x)) is True
assert ask(Q.rational(x)) is False
def test_issue_9636():
assert ask(Q.integer(1.0)) is False
assert ask(Q.prime(3.0)) is False
assert ask(Q.composite(4.0)) is False
assert ask(Q.even(2.0)) is False
assert ask(Q.odd(3.0)) is False
def test_autosimp_used_to_fail():
# See issue #9807
assert ask(Q.imaginary(0**I)) is None
assert ask(Q.imaginary(0**(-I))) is None
assert ask(Q.real(0**I)) is None
assert ask(Q.real(0**(-I))) is None
def test_custom_AskHandler():
from sympy.logic.boolalg import conjuncts
# Old handler system
class MersenneHandler(AskHandler):
@staticmethod
def Integer(expr, assumptions):
from sympy import log
if ask(Q.integer(log(expr + 1, 2))):
return True
@staticmethod
def Symbol(expr, assumptions):
if expr in conjuncts(assumptions):
return True
try:
with warns_deprecated_sympy():
register_handler('mersenne', MersenneHandler)
n = Symbol('n', integer=True)
with warns_deprecated_sympy():
assert ask(Q.mersenne(7))
with warns_deprecated_sympy():
assert ask(Q.mersenne(n), Q.mersenne(n))
finally:
del Q.mersenne
# New handler system
class MersennePredicate(Predicate):
pass
try:
Q.mersenne = MersennePredicate()
@Q.mersenne.register(Integer)
def _(expr, assumptions):
from sympy import log
if ask(Q.integer(log(expr + 1, 2))):
return True
@Q.mersenne.register(Symbol)
def _(expr, assumptions):
if expr in conjuncts(assumptions):
return True
assert ask(Q.mersenne(7))
assert ask(Q.mersenne(n), Q.mersenne(n))
finally:
del Q.mersenne
def test_polyadic_predicate():
class SexyPredicate(Predicate):
pass
try:
Q.sexyprime = SexyPredicate()
@Q.sexyprime.register(Integer, Integer)
def _(int1, int2, assumptions):
args = sorted([int1, int2])
if not all(ask(Q.prime(a), assumptions) for a in args):
return False
return args[1] - args[0] == 6
@Q.sexyprime.register(Integer, Integer, Integer)
def _(int1, int2, int3, assumptions):
args = sorted([int1, int2, int3])
if not all(ask(Q.prime(a), assumptions) for a in args):
return False
return args[2] - args[1] == 6 and args[1] - args[0] == 6
assert ask(Q.sexyprime(5, 11))
assert ask(Q.sexyprime(7, 13, 19))
finally:
del Q.sexyprime
def test_Predicate_handler_is_unique():
# Undefined predicate does not have a handler
assert Predicate('mypredicate').handler is None
# Handler of defined predicate is unique to the class
class MyPredicate(Predicate):
pass
mp1 = MyPredicate('mp1')
mp2 = MyPredicate('mp2')
assert mp1.handler is mp2.handler
def test_relational():
assert ask(Q.eq(x, 0), Q.zero(x))
assert not ask(Q.eq(x, 0), Q.nonzero(x))
assert not ask(Q.ne(x, 0), Q.zero(x))
assert ask(Q.ne(x, 0), Q.nonzero(x))
|
21cae2233464fab5ad233f6b8397bf5a72d9da20fc2283e454601304c508faa9 | """
This module implements some special functions that commonly appear in
combinatorial contexts (e.g. in power series); in particular,
sequences of rational numbers such as Bernoulli and Fibonacci numbers.
Factorials, binomial coefficients and related functions are located in
the separate 'factorials' module.
"""
from typing import Callable, Dict
from sympy.core import S, Symbol, Rational, Integer, Add, Dummy
from sympy.core.cache import cacheit
from sympy.core.compatibility import as_int, SYMPY_INTS
from sympy.core.function import Function, expand_mul
from sympy.core.logic import fuzzy_not
from sympy.core.numbers import E, pi
from sympy.core.relational import LessThan, StrictGreaterThan
from sympy.functions.combinatorial.factorials import binomial, factorial
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt, cbrt
from sympy.functions.elementary.trigonometric import sin, cos, cot
from sympy.ntheory import isprime
from sympy.ntheory.primetest import is_square
from sympy.utilities.memoization import recurrence_memo
from mpmath import bernfrac, workprec
from mpmath.libmp import ifib as _ifib
def _product(a, b):
p = 1
for k in range(a, b + 1):
p *= k
return p
# Dummy symbol used for computing polynomial sequences
_sym = Symbol('x')
#----------------------------------------------------------------------------#
# #
# Carmichael numbers #
# #
#----------------------------------------------------------------------------#
class carmichael(Function):
"""
Carmichael Numbers:
Certain cryptographic algorithms make use of big prime numbers.
However, checking whether a big number is prime is not so easy.
Randomized prime number checking tests exist that offer a high degree of confidence of
accurate determination at low cost, such as the Fermat test.
Let 'a' be a random number between 2 and n - 1, where n is the number whose primality we are testing.
Then, n is probably prime if it satisfies the modular arithmetic congruence relation :
a^(n-1) = 1(mod n).
(where mod refers to the modulo operation)
If a number passes the Fermat test several times, then it is prime with a
high probability.
Unfortunately, certain composite numbers (non-primes) still pass the Fermat test
with every number smaller than themselves.
These numbers are called Carmichael numbers.
A Carmichael number will pass a Fermat primality test to every base b relatively prime to the number,
even though it is not actually prime. This makes tests based on Fermat's Little Theorem less effective than
strong probable prime tests such as the Baillie-PSW primality test and the Miller-Rabin primality test.
mr functions given in sympy/sympy/ntheory/primetest.py will produce wrong results for each and every
carmichael number.
Examples
========
>>> from sympy import carmichael
>>> carmichael.find_first_n_carmichaels(5)
[561, 1105, 1729, 2465, 2821]
>>> carmichael.is_prime(2465)
False
>>> carmichael.is_prime(1729)
False
>>> carmichael.find_carmichael_numbers_in_range(0, 562)
[561]
>>> carmichael.find_carmichael_numbers_in_range(0,1000)
[561]
>>> carmichael.find_carmichael_numbers_in_range(0,2000)
[561, 1105, 1729]
References
==========
.. [1] https://en.wikipedia.org/wiki/Carmichael_number
.. [2] https://en.wikipedia.org/wiki/Fermat_primality_test
.. [3] https://www.jstor.org/stable/23248683?seq=1#metadata_info_tab_contents
"""
@staticmethod
def is_perfect_square(n):
return is_square(n)
@staticmethod
def divides(p, n):
return n % p == 0
@staticmethod
def is_prime(n):
return isprime(n)
@staticmethod
def is_carmichael(n):
if n >= 0:
if (n == 1) or (carmichael.is_prime(n)) or (n % 2 == 0):
return False
divisors = list([1, n])
# get divisors
for i in range(3, n // 2 + 1, 2):
if n % i == 0:
divisors.append(i)
for i in divisors:
if carmichael.is_perfect_square(i) and i != 1:
return False
if carmichael.is_prime(i):
if not carmichael.divides(i - 1, n - 1):
return False
return True
else:
raise ValueError('The provided number must be greater than or equal to 0')
@staticmethod
def find_carmichael_numbers_in_range(x, y):
if 0 <= x <= y:
if x % 2 == 0:
return list([i for i in range(x + 1, y, 2) if carmichael.is_carmichael(i)])
else:
return list([i for i in range(x, y, 2) if carmichael.is_carmichael(i)])
else:
raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y')
@staticmethod
def find_first_n_carmichaels(n):
i = 1
carmichaels = list()
while len(carmichaels) < n:
if carmichael.is_carmichael(i):
carmichaels.append(i)
i += 2
return carmichaels
#----------------------------------------------------------------------------#
# #
# Fibonacci numbers #
# #
#----------------------------------------------------------------------------#
class fibonacci(Function):
r"""
Fibonacci numbers / Fibonacci polynomials
The Fibonacci numbers are the integer sequence defined by the
initial terms `F_0 = 0`, `F_1 = 1` and the two-term recurrence
relation `F_n = F_{n-1} + F_{n-2}`. This definition
extended to arbitrary real and complex arguments using
the formula
.. math :: F_z = \frac{\phi^z - \cos(\pi z) \phi^{-z}}{\sqrt 5}
The Fibonacci polynomials are defined by `F_1(x) = 1`,
`F_2(x) = x`, and `F_n(x) = x*F_{n-1}(x) + F_{n-2}(x)` for `n > 2`.
For all positive integers `n`, `F_n(1) = F_n`.
* ``fibonacci(n)`` gives the `n^{th}` Fibonacci number, `F_n`
* ``fibonacci(n, x)`` gives the `n^{th}` Fibonacci polynomial in `x`, `F_n(x)`
Examples
========
>>> from sympy import fibonacci, Symbol
>>> [fibonacci(x) for x in range(11)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> fibonacci(5, Symbol('t'))
t**4 + 3*t**2 + 1
See Also
========
bell, bernoulli, catalan, euler, harmonic, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Fibonacci_number
.. [2] http://mathworld.wolfram.com/FibonacciNumber.html
"""
@staticmethod
def _fib(n):
return _ifib(n)
@staticmethod
@recurrence_memo([None, S.One, _sym])
def _fibpoly(n, prev):
return (prev[-2] + _sym*prev[-1]).expand()
@classmethod
def eval(cls, n, sym=None):
if n is S.Infinity:
return S.Infinity
if n.is_Integer:
if sym is None:
n = int(n)
if n < 0:
return S.NegativeOne**(n + 1) * fibonacci(-n)
else:
return Integer(cls._fib(n))
else:
if n < 1:
raise ValueError("Fibonacci polynomials are defined "
"only for positive integer indices.")
return cls._fibpoly(n).subs(_sym, sym)
def _eval_rewrite_as_sqrt(self, n, **kwargs):
return 2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5
def _eval_rewrite_as_GoldenRatio(self,n, **kwargs):
return (S.GoldenRatio**n - 1/(-S.GoldenRatio)**n)/(2*S.GoldenRatio-1)
#----------------------------------------------------------------------------#
# #
# Lucas numbers #
# #
#----------------------------------------------------------------------------#
class lucas(Function):
"""
Lucas numbers
Lucas numbers satisfy a recurrence relation similar to that of
the Fibonacci sequence, in which each term is the sum of the
preceding two. They are generated by choosing the initial
values `L_0 = 2` and `L_1 = 1`.
* ``lucas(n)`` gives the `n^{th}` Lucas number
Examples
========
>>> from sympy import lucas
>>> [lucas(x) for x in range(11)]
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123]
See Also
========
bell, bernoulli, catalan, euler, fibonacci, harmonic, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Lucas_number
.. [2] http://mathworld.wolfram.com/LucasNumber.html
"""
@classmethod
def eval(cls, n):
if n is S.Infinity:
return S.Infinity
if n.is_Integer:
return fibonacci(n + 1) + fibonacci(n - 1)
def _eval_rewrite_as_sqrt(self, n, **kwargs):
return 2**(-n)*((1 + sqrt(5))**n + (-sqrt(5) + 1)**n)
#----------------------------------------------------------------------------#
# #
# Tribonacci numbers #
# #
#----------------------------------------------------------------------------#
class tribonacci(Function):
r"""
Tribonacci numbers / Tribonacci polynomials
The Tribonacci numbers are the integer sequence defined by the
initial terms `T_0 = 0`, `T_1 = 1`, `T_2 = 1` and the three-term
recurrence relation `T_n = T_{n-1} + T_{n-2} + T_{n-3}`.
The Tribonacci polynomials are defined by `T_0(x) = 0`, `T_1(x) = 1`,
`T_2(x) = x^2`, and `T_n(x) = x^2 T_{n-1}(x) + x T_{n-2}(x) + T_{n-3}(x)`
for `n > 2`. For all positive integers `n`, `T_n(1) = T_n`.
* ``tribonacci(n)`` gives the `n^{th}` Tribonacci number, `T_n`
* ``tribonacci(n, x)`` gives the `n^{th}` Tribonacci polynomial in `x`, `T_n(x)`
Examples
========
>>> from sympy import tribonacci, Symbol
>>> [tribonacci(x) for x in range(11)]
[0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149]
>>> tribonacci(5, Symbol('t'))
t**8 + 3*t**5 + 3*t**2
See Also
========
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition
References
==========
.. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
.. [2] http://mathworld.wolfram.com/TribonacciNumber.html
.. [3] https://oeis.org/A000073
"""
@staticmethod
@recurrence_memo([S.Zero, S.One, S.One])
def _trib(n, prev):
return (prev[-3] + prev[-2] + prev[-1])
@staticmethod
@recurrence_memo([S.Zero, S.One, _sym**2])
def _tribpoly(n, prev):
return (prev[-3] + _sym*prev[-2] + _sym**2*prev[-1]).expand()
@classmethod
def eval(cls, n, sym=None):
if n is S.Infinity:
return S.Infinity
if n.is_Integer:
n = int(n)
if n < 0:
raise ValueError("Tribonacci polynomials are defined "
"only for non-negative integer indices.")
if sym is None:
return Integer(cls._trib(n))
else:
return cls._tribpoly(n).subs(_sym, sym)
def _eval_rewrite_as_sqrt(self, n, **kwargs):
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
Tn = (a**(n + 1)/((a - b)*(a - c))
+ b**(n + 1)/((b - a)*(b - c))
+ c**(n + 1)/((c - a)*(c - b)))
return Tn
def _eval_rewrite_as_TribonacciConstant(self, n, **kwargs):
b = cbrt(586 + 102*sqrt(33))
Tn = 3 * b * S.TribonacciConstant**n / (b**2 - 2*b + 4)
return floor(Tn + S.Half)
#----------------------------------------------------------------------------#
# #
# Bernoulli numbers #
# #
#----------------------------------------------------------------------------#
class bernoulli(Function):
r"""
Bernoulli numbers / Bernoulli polynomials
The Bernoulli numbers are a sequence of rational numbers
defined by `B_0 = 1` and the recursive relation (`n > 0`):
.. math :: 0 = \sum_{k=0}^n \binom{n+1}{k} B_k
They are also commonly defined by their exponential generating
function, which is `\frac{x}{e^x - 1}`. For odd indices > 1, the
Bernoulli numbers are zero.
The Bernoulli polynomials satisfy the analogous formula:
.. math :: B_n(x) = \sum_{k=0}^n \binom{n}{k} B_k x^{n-k}
Bernoulli numbers and Bernoulli polynomials are related as
`B_n(0) = B_n`.
We compute Bernoulli numbers using Ramanujan's formula:
.. math :: B_n = \frac{A(n) - S(n)}{\binom{n+3}{n}}
where:
.. math :: A(n) = \begin{cases} \frac{n+3}{3} &
n \equiv 0\ \text{or}\ 2 \pmod{6} \\
-\frac{n+3}{6} & n \equiv 4 \pmod{6} \end{cases}
and:
.. math :: S(n) = \sum_{k=1}^{[n/6]} \binom{n+3}{n-6k} B_{n-6k}
This formula is similar to the sum given in the definition, but
cuts 2/3 of the terms. For Bernoulli polynomials, we use the
formula in the definition.
* ``bernoulli(n)`` gives the nth Bernoulli number, `B_n`
* ``bernoulli(n, x)`` gives the nth Bernoulli polynomial in `x`, `B_n(x)`
Examples
========
>>> from sympy import bernoulli
>>> [bernoulli(n) for n in range(11)]
[1, -1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
>>> bernoulli(1000001)
0
See Also
========
bell, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Bernoulli_number
.. [2] https://en.wikipedia.org/wiki/Bernoulli_polynomial
.. [3] http://mathworld.wolfram.com/BernoulliNumber.html
.. [4] http://mathworld.wolfram.com/BernoulliPolynomial.html
"""
# Calculates B_n for positive even n
@staticmethod
def _calc_bernoulli(n):
s = 0
a = int(binomial(n + 3, n - 6))
for j in range(1, n//6 + 1):
s += a * bernoulli(n - 6*j)
# Avoid computing each binomial coefficient from scratch
a *= _product(n - 6 - 6*j + 1, n - 6*j)
a //= _product(6*j + 4, 6*j + 9)
if n % 6 == 4:
s = -Rational(n + 3, 6) - s
else:
s = Rational(n + 3, 3) - s
return s / binomial(n + 3, n)
# We implement a specialized memoization scheme to handle each
# case modulo 6 separately
_cache = {0: S.One, 2: Rational(1, 6), 4: Rational(-1, 30)}
_highest = {0: 0, 2: 2, 4: 4}
@classmethod
def eval(cls, n, sym=None):
if n.is_Number:
if n.is_Integer and n.is_nonnegative:
if n.is_zero:
return S.One
elif n is S.One:
if sym is None:
return Rational(-1, 2)
else:
return sym - S.Half
# Bernoulli numbers
elif sym is None:
if n.is_odd:
return S.Zero
n = int(n)
# Use mpmath for enormous Bernoulli numbers
if n > 500:
p, q = bernfrac(n)
return Rational(int(p), int(q))
case = n % 6
highest_cached = cls._highest[case]
if n <= highest_cached:
return cls._cache[n]
# To avoid excessive recursion when, say, bernoulli(1000) is
# requested, calculate and cache the entire sequence ... B_988,
# B_994, B_1000 in increasing order
for i in range(highest_cached + 6, n + 6, 6):
b = cls._calc_bernoulli(i)
cls._cache[i] = b
cls._highest[case] = i
return b
# Bernoulli polynomials
else:
n, result = int(n), []
for k in range(n + 1):
result.append(binomial(n, k)*cls(k)*sym**(n - k))
return Add(*result)
else:
raise ValueError("Bernoulli numbers are defined only"
" for nonnegative integer indices.")
if sym is None:
if n.is_odd and (n - 1).is_positive:
return S.Zero
#----------------------------------------------------------------------------#
# #
# Bell numbers #
# #
#----------------------------------------------------------------------------#
class bell(Function):
r"""
Bell numbers / Bell polynomials
The Bell numbers satisfy `B_0 = 1` and
.. math:: B_n = \sum_{k=0}^{n-1} \binom{n-1}{k} B_k.
They are also given by:
.. math:: B_n = \frac{1}{e} \sum_{k=0}^{\infty} \frac{k^n}{k!}.
The Bell polynomials are given by `B_0(x) = 1` and
.. math:: B_n(x) = x \sum_{k=1}^{n-1} \binom{n-1}{k-1} B_{k-1}(x).
The second kind of Bell polynomials (are sometimes called "partial" Bell
polynomials or incomplete Bell polynomials) are defined as
.. math:: B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) =
\sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n}
\frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!}
\left(\frac{x_1}{1!} \right)^{j_1}
\left(\frac{x_2}{2!} \right)^{j_2} \dotsb
\left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}.
* ``bell(n)`` gives the `n^{th}` Bell number, `B_n`.
* ``bell(n, x)`` gives the `n^{th}` Bell polynomial, `B_n(x)`.
* ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind,
`B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`.
Notes
=====
Not to be confused with Bernoulli numbers and Bernoulli polynomials,
which use the same notation.
Examples
========
>>> from sympy import bell, Symbol, symbols
>>> [bell(n) for n in range(11)]
[1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975]
>>> bell(30)
846749014511809332450147
>>> bell(4, Symbol('t'))
t**4 + 6*t**3 + 7*t**2 + t
>>> bell(6, 2, symbols('x:6')[1:])
6*x1*x5 + 15*x2*x4 + 10*x3**2
See Also
========
bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Bell_number
.. [2] http://mathworld.wolfram.com/BellNumber.html
.. [3] http://mathworld.wolfram.com/BellPolynomial.html
"""
@staticmethod
@recurrence_memo([1, 1])
def _bell(n, prev):
s = 1
a = 1
for k in range(1, n):
a = a * (n - k) // k
s += a * prev[k]
return s
@staticmethod
@recurrence_memo([S.One, _sym])
def _bell_poly(n, prev):
s = 1
a = 1
for k in range(2, n + 1):
a = a * (n - k + 1) // (k - 1)
s += a * prev[k - 1]
return expand_mul(_sym * s)
@staticmethod
def _bell_incomplete_poly(n, k, symbols):
r"""
The second kind of Bell polynomials (incomplete Bell polynomials).
Calculated by recurrence formula:
.. math:: B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1}) =
\sum_{m=1}^{n-k+1}
\x_m \binom{n-1}{m-1} B_{n-m,k-1}(x_1, x_2, \dotsc, x_{n-m-k})
where
`B_{0,0} = 1;`
`B_{n,0} = 0; for n \ge 1`
`B_{0,k} = 0; for k \ge 1`
"""
if (n == 0) and (k == 0):
return S.One
elif (n == 0) or (k == 0):
return S.Zero
s = S.Zero
a = S.One
for m in range(1, n - k + 2):
s += a * bell._bell_incomplete_poly(
n - m, k - 1, symbols) * symbols[m - 1]
a = a * (n - m) / m
return expand_mul(s)
@classmethod
def eval(cls, n, k_sym=None, symbols=None):
if n is S.Infinity:
if k_sym is None:
return S.Infinity
else:
raise ValueError("Bell polynomial is not defined")
if n.is_negative or n.is_integer is False:
raise ValueError("a non-negative integer expected")
if n.is_Integer and n.is_nonnegative:
if k_sym is None:
return Integer(cls._bell(int(n)))
elif symbols is None:
return cls._bell_poly(int(n)).subs(_sym, k_sym)
else:
r = cls._bell_incomplete_poly(int(n), int(k_sym), symbols)
return r
def _eval_rewrite_as_Sum(self, n, k_sym=None, symbols=None, **kwargs):
from sympy import Sum
if (k_sym is not None) or (symbols is not None):
return self
# Dobinski's formula
if not n.is_nonnegative:
return self
k = Dummy('k', integer=True, nonnegative=True)
return 1 / E * Sum(k**n / factorial(k), (k, 0, S.Infinity))
#----------------------------------------------------------------------------#
# #
# Harmonic numbers #
# #
#----------------------------------------------------------------------------#
class harmonic(Function):
r"""
Harmonic numbers
The nth harmonic number is given by `\operatorname{H}_{n} =
1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}`.
More generally:
.. math:: \operatorname{H}_{n,m} = \sum_{k=1}^{n} \frac{1}{k^m}
As `n \rightarrow \infty`, `\operatorname{H}_{n,m} \rightarrow \zeta(m)`,
the Riemann zeta function.
* ``harmonic(n)`` gives the nth harmonic number, `\operatorname{H}_n`
* ``harmonic(n, m)`` gives the nth generalized harmonic number
of order `m`, `\operatorname{H}_{n,m}`, where
``harmonic(n) == harmonic(n, 1)``
Examples
========
>>> from sympy import harmonic, oo
>>> [harmonic(n) for n in range(6)]
[0, 1, 3/2, 11/6, 25/12, 137/60]
>>> [harmonic(n, 2) for n in range(6)]
[0, 1, 5/4, 49/36, 205/144, 5269/3600]
>>> harmonic(oo, 2)
pi**2/6
>>> from sympy import Symbol, Sum
>>> n = Symbol("n")
>>> harmonic(n).rewrite(Sum)
Sum(1/_k, (_k, 1, n))
We can evaluate harmonic numbers for all integral and positive
rational arguments:
>>> from sympy import S, expand_func, simplify
>>> harmonic(8)
761/280
>>> harmonic(11)
83711/27720
>>> H = harmonic(1/S(3))
>>> H
harmonic(1/3)
>>> He = expand_func(H)
>>> He
-log(6) - sqrt(3)*pi/6 + 2*Sum(log(sin(_k*pi/3))*cos(2*_k*pi/3), (_k, 1, 1))
+ 3*Sum(1/(3*_k + 1), (_k, 0, 0))
>>> He.doit()
-log(6) - sqrt(3)*pi/6 - log(sqrt(3)/2) + 3
>>> H = harmonic(25/S(7))
>>> He = simplify(expand_func(H).doit())
>>> He
log(sin(2*pi/7)**(2*cos(16*pi/7))/(14*sin(pi/7)**(2*cos(pi/7))*cos(pi/14)**(2*sin(pi/14)))) + pi*tan(pi/14)/2 + 30247/9900
>>> He.n(40)
1.983697455232980674869851942390639915940
>>> harmonic(25/S(7)).n(40)
1.983697455232980674869851942390639915940
We can rewrite harmonic numbers in terms of polygamma functions:
>>> from sympy import digamma, polygamma
>>> m = Symbol("m")
>>> harmonic(n).rewrite(digamma)
polygamma(0, n + 1) + EulerGamma
>>> harmonic(n).rewrite(polygamma)
polygamma(0, n + 1) + EulerGamma
>>> harmonic(n,3).rewrite(polygamma)
polygamma(2, n + 1)/2 - polygamma(2, 1)/2
>>> harmonic(n,m).rewrite(polygamma)
(-1)**m*(polygamma(m - 1, 1) - polygamma(m - 1, n + 1))/factorial(m - 1)
Integer offsets in the argument can be pulled out:
>>> from sympy import expand_func
>>> expand_func(harmonic(n+4))
harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
>>> expand_func(harmonic(n-4))
harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
Some limits can be computed as well:
>>> from sympy import limit, oo
>>> limit(harmonic(n), n, oo)
oo
>>> limit(harmonic(n, 2), n, oo)
pi**2/6
>>> limit(harmonic(n, 3), n, oo)
-polygamma(2, 1)/2
However we can not compute the general relation yet:
>>> limit(harmonic(n, m), n, oo)
harmonic(oo, m)
which equals ``zeta(m)`` for ``m > 1``.
See Also
========
bell, bernoulli, catalan, euler, fibonacci, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Harmonic_number
.. [2] http://functions.wolfram.com/GammaBetaErf/HarmonicNumber/
.. [3] http://functions.wolfram.com/GammaBetaErf/HarmonicNumber2/
"""
# Generate one memoized Harmonic number-generating function for each
# order and store it in a dictionary
_functions = {} # type: Dict[Integer, Callable[[int], Rational]]
@classmethod
def eval(cls, n, m=None):
from sympy import zeta
if m is S.One:
return cls(n)
if m is None:
m = S.One
if m.is_zero:
return n
if n is S.Infinity and m.is_Number:
# TODO: Fix for symbolic values of m
if m.is_negative:
return S.NaN
elif LessThan(m, S.One):
return S.Infinity
elif StrictGreaterThan(m, S.One):
return zeta(m)
else:
return cls
if n == 0:
return S.Zero
if n.is_Integer and n.is_nonnegative and m.is_Integer:
if not m in cls._functions:
@recurrence_memo([0])
def f(n, prev):
return prev[-1] + S.One / n**m
cls._functions[m] = f
return cls._functions[m](int(n))
def _eval_rewrite_as_polygamma(self, n, m=1, **kwargs):
from sympy.functions.special.gamma_functions import polygamma
return S.NegativeOne**m/factorial(m - 1) * (polygamma(m - 1, 1) - polygamma(m - 1, n + 1))
def _eval_rewrite_as_digamma(self, n, m=1, **kwargs):
from sympy.functions.special.gamma_functions import polygamma
return self.rewrite(polygamma)
def _eval_rewrite_as_trigamma(self, n, m=1, **kwargs):
from sympy.functions.special.gamma_functions import polygamma
return self.rewrite(polygamma)
def _eval_rewrite_as_Sum(self, n, m=None, **kwargs):
from sympy import Sum
k = Dummy("k", integer=True)
if m is None:
m = S.One
return Sum(k**(-m), (k, 1, n))
def _eval_expand_func(self, **hints):
from sympy import Sum
n = self.args[0]
m = self.args[1] if len(self.args) == 2 else 1
if m == S.One:
if n.is_Add:
off = n.args[0]
nnew = n - off
if off.is_Integer and off.is_positive:
result = [S.One/(nnew + i) for i in range(off, 0, -1)] + [harmonic(nnew)]
return Add(*result)
elif off.is_Integer and off.is_negative:
result = [-S.One/(nnew + i) for i in range(0, off, -1)] + [harmonic(nnew)]
return Add(*result)
if n.is_Rational:
# Expansions for harmonic numbers at general rational arguments (u + p/q)
# Split n as u + p/q with p < q
p, q = n.as_numer_denom()
u = p // q
p = p - u * q
if u.is_nonnegative and p.is_positive and q.is_positive and p < q:
k = Dummy("k")
t1 = q * Sum(1 / (q * k + p), (k, 0, u))
t2 = 2 * Sum(cos((2 * pi * p * k) / S(q)) *
log(sin((pi * k) / S(q))),
(k, 1, floor((q - 1) / S(2))))
t3 = (pi / 2) * cot((pi * p) / q) + log(2 * q)
return t1 + t2 - t3
return self
def _eval_rewrite_as_tractable(self, n, m=1, limitvar=None, **kwargs):
from sympy import polygamma
return self.rewrite(polygamma).rewrite("tractable", deep=True)
def _eval_evalf(self, prec):
from sympy import polygamma
if all(i.is_number for i in self.args):
return self.rewrite(polygamma)._eval_evalf(prec)
#----------------------------------------------------------------------------#
# #
# Euler numbers #
# #
#----------------------------------------------------------------------------#
class euler(Function):
r"""
Euler numbers / Euler polynomials
The Euler numbers are given by:
.. math:: E_{2n} = I \sum_{k=1}^{2n+1} \sum_{j=0}^k \binom{k}{j}
\frac{(-1)^j (k-2j)^{2n+1}}{2^k I^k k}
.. math:: E_{2n+1} = 0
Euler numbers and Euler polynomials are related by
.. math:: E_n = 2^n E_n\left(\frac{1}{2}\right).
We compute symbolic Euler polynomials using [5]_
.. math:: E_n(x) = \sum_{k=0}^n \binom{n}{k} \frac{E_k}{2^k}
\left(x - \frac{1}{2}\right)^{n-k}.
However, numerical evaluation of the Euler polynomial is computed
more efficiently (and more accurately) using the mpmath library.
* ``euler(n)`` gives the `n^{th}` Euler number, `E_n`.
* ``euler(n, x)`` gives the `n^{th}` Euler polynomial, `E_n(x)`.
Examples
========
>>> from sympy import Symbol, S
>>> from sympy.functions import euler
>>> [euler(n) for n in range(10)]
[1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]
>>> n = Symbol("n")
>>> euler(n + 2*n)
euler(3*n)
>>> x = Symbol("x")
>>> euler(n, x)
euler(n, x)
>>> euler(0, x)
1
>>> euler(1, x)
x - 1/2
>>> euler(2, x)
x**2 - x
>>> euler(3, x)
x**3 - 3*x**2/2 + 1/4
>>> euler(4, x)
x**4 - 2*x**3 + x
>>> euler(12, S.Half)
2702765/4096
>>> euler(12)
2702765
See Also
========
bell, bernoulli, catalan, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Euler_numbers
.. [2] http://mathworld.wolfram.com/EulerNumber.html
.. [3] https://en.wikipedia.org/wiki/Alternating_permutation
.. [4] http://mathworld.wolfram.com/AlternatingPermutation.html
.. [5] http://dlmf.nist.gov/24.2#ii
"""
@classmethod
def eval(cls, m, sym=None):
if m.is_Number:
if m.is_Integer and m.is_nonnegative:
# Euler numbers
if sym is None:
if m.is_odd:
return S.Zero
from mpmath import mp
m = m._to_mpmath(mp.prec)
res = mp.eulernum(m, exact=True)
return Integer(res)
# Euler polynomial
else:
from sympy.core.evalf import pure_complex
reim = pure_complex(sym, or_real=True)
# Evaluate polynomial numerically using mpmath
if reim and all(a.is_Float or a.is_Integer for a in reim) \
and any(a.is_Float for a in reim):
from mpmath import mp
from sympy import Expr
m = int(m)
# XXX ComplexFloat (#12192) would be nice here, above
prec = min([a._prec for a in reim if a.is_Float])
with workprec(prec):
res = mp.eulerpoly(m, sym)
return Expr._from_mpmath(res, prec)
# Construct polynomial symbolically from definition
m, result = int(m), []
for k in range(m + 1):
result.append(binomial(m, k)*cls(k)/(2**k)*(sym - S.Half)**(m - k))
return Add(*result).expand()
else:
raise ValueError("Euler numbers are defined only"
" for nonnegative integer indices.")
if sym is None:
if m.is_odd and m.is_positive:
return S.Zero
def _eval_rewrite_as_Sum(self, n, x=None, **kwargs):
from sympy import Sum
if x is None and n.is_even:
k = Dummy("k", integer=True)
j = Dummy("j", integer=True)
n = n / 2
Em = (S.ImaginaryUnit * Sum(Sum(binomial(k, j) * ((-1)**j * (k - 2*j)**(2*n + 1)) /
(2**k*S.ImaginaryUnit**k * k), (j, 0, k)), (k, 1, 2*n + 1)))
return Em
if x:
k = Dummy("k", integer=True)
return Sum(binomial(n, k)*euler(k)/2**k*(x - S.Half)**(n - k), (k, 0, n))
def _eval_evalf(self, prec):
m, x = (self.args[0], None) if len(self.args) == 1 else self.args
if x is None and m.is_Integer and m.is_nonnegative:
from mpmath import mp
from sympy import Expr
m = m._to_mpmath(prec)
with workprec(prec):
res = mp.eulernum(m)
return Expr._from_mpmath(res, prec)
if x and x.is_number and m.is_Integer and m.is_nonnegative:
from mpmath import mp
from sympy import Expr
m = int(m)
x = x._to_mpmath(prec)
with workprec(prec):
res = mp.eulerpoly(m, x)
return Expr._from_mpmath(res, prec)
#----------------------------------------------------------------------------#
# #
# Catalan numbers #
# #
#----------------------------------------------------------------------------#
class catalan(Function):
r"""
Catalan numbers
The `n^{th}` catalan number is given by:
.. math :: C_n = \frac{1}{n+1} \binom{2n}{n}
* ``catalan(n)`` gives the `n^{th}` Catalan number, `C_n`
Examples
========
>>> from sympy import (Symbol, binomial, gamma, hyper, catalan,
... diff, combsimp, Rational, I)
>>> [catalan(i) for i in range(1,10)]
[1, 2, 5, 14, 42, 132, 429, 1430, 4862]
>>> n = Symbol("n", integer=True)
>>> catalan(n)
catalan(n)
Catalan numbers can be transformed into several other, identical
expressions involving other mathematical functions
>>> catalan(n).rewrite(binomial)
binomial(2*n, n)/(n + 1)
>>> catalan(n).rewrite(gamma)
4**n*gamma(n + 1/2)/(sqrt(pi)*gamma(n + 2))
>>> catalan(n).rewrite(hyper)
hyper((1 - n, -n), (2,), 1)
For some non-integer values of n we can get closed form
expressions by rewriting in terms of gamma functions:
>>> catalan(Rational(1, 2)).rewrite(gamma)
8/(3*pi)
We can differentiate the Catalan numbers C(n) interpreted as a
continuous real function in n:
>>> diff(catalan(n), n)
(polygamma(0, n + 1/2) - polygamma(0, n + 2) + log(4))*catalan(n)
As a more advanced example consider the following ratio
between consecutive numbers:
>>> combsimp((catalan(n + 1)/catalan(n)).rewrite(binomial))
2*(2*n + 1)/(n + 2)
The Catalan numbers can be generalized to complex numbers:
>>> catalan(I).rewrite(gamma)
4**I*gamma(1/2 + I)/(sqrt(pi)*gamma(2 + I))
and evaluated with arbitrary precision:
>>> catalan(I).evalf(20)
0.39764993382373624267 - 0.020884341620842555705*I
See Also
========
bell, bernoulli, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
sympy.functions.combinatorial.factorials.binomial
References
==========
.. [1] https://en.wikipedia.org/wiki/Catalan_number
.. [2] http://mathworld.wolfram.com/CatalanNumber.html
.. [3] http://functions.wolfram.com/GammaBetaErf/CatalanNumber/
.. [4] http://geometer.org/mathcircles/catalan.pdf
"""
@classmethod
def eval(cls, n):
from sympy import gamma
if (n.is_Integer and n.is_nonnegative) or \
(n.is_noninteger and n.is_negative):
return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
if (n.is_integer and n.is_negative):
if (n + 1).is_negative:
return S.Zero
if (n + 1).is_zero:
return Rational(-1, 2)
def fdiff(self, argindex=1):
from sympy import polygamma, log
n = self.args[0]
return catalan(n)*(polygamma(0, n + S.Half) - polygamma(0, n + 2) + log(4))
def _eval_rewrite_as_binomial(self, n, **kwargs):
return binomial(2*n, n)/(n + 1)
def _eval_rewrite_as_factorial(self, n, **kwargs):
return factorial(2*n) / (factorial(n+1) * factorial(n))
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
from sympy import gamma
# The gamma function allows to generalize Catalan numbers to complex n
return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
def _eval_rewrite_as_hyper(self, n, **kwargs):
from sympy import hyper
return hyper([1 - n, -n], [2], 1)
def _eval_rewrite_as_Product(self, n, **kwargs):
from sympy import Product
if not (n.is_integer and n.is_nonnegative):
return self
k = Dummy('k', integer=True, positive=True)
return Product((n + k) / k, (k, 2, n))
def _eval_is_integer(self):
if self.args[0].is_integer and self.args[0].is_nonnegative:
return True
def _eval_is_positive(self):
if self.args[0].is_nonnegative:
return True
def _eval_is_composite(self):
if self.args[0].is_integer and (self.args[0] - 3).is_positive:
return True
def _eval_evalf(self, prec):
from sympy import gamma
if self.args[0].is_number:
return self.rewrite(gamma)._eval_evalf(prec)
#----------------------------------------------------------------------------#
# #
# Genocchi numbers #
# #
#----------------------------------------------------------------------------#
class genocchi(Function):
r"""
Genocchi numbers
The Genocchi numbers are a sequence of integers `G_n` that satisfy the
relation:
.. math:: \frac{2t}{e^t + 1} = \sum_{n=1}^\infty \frac{G_n t^n}{n!}
Examples
========
>>> from sympy import Symbol
>>> from sympy.functions import genocchi
>>> [genocchi(n) for n in range(1, 9)]
[1, -1, 0, 1, 0, -3, 0, 17]
>>> n = Symbol('n', integer=True, positive=True)
>>> genocchi(2*n + 1)
0
See Also
========
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, partition, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Genocchi_number
.. [2] http://mathworld.wolfram.com/GenocchiNumber.html
"""
@classmethod
def eval(cls, n):
if n.is_Number:
if (not n.is_Integer) or n.is_nonpositive:
raise ValueError("Genocchi numbers are defined only for " +
"positive integers")
return 2 * (1 - S(2) ** n) * bernoulli(n)
if n.is_odd and (n - 1).is_positive:
return S.Zero
if (n - 1).is_zero:
return S.One
def _eval_rewrite_as_bernoulli(self, n, **kwargs):
if n.is_integer and n.is_nonnegative:
return (1 - S(2) ** n) * bernoulli(n) * 2
def _eval_is_integer(self):
if self.args[0].is_integer and self.args[0].is_positive:
return True
def _eval_is_negative(self):
n = self.args[0]
if n.is_integer and n.is_positive:
if n.is_odd:
return False
return (n / 2).is_odd
def _eval_is_positive(self):
n = self.args[0]
if n.is_integer and n.is_positive:
if n.is_odd:
return fuzzy_not((n - 1).is_positive)
return (n / 2).is_even
def _eval_is_even(self):
n = self.args[0]
if n.is_integer and n.is_positive:
if n.is_even:
return False
return (n - 1).is_positive
def _eval_is_odd(self):
n = self.args[0]
if n.is_integer and n.is_positive:
if n.is_even:
return True
return fuzzy_not((n - 1).is_positive)
def _eval_is_prime(self):
n = self.args[0]
# only G_6 = -3 and G_8 = 17 are prime,
# but SymPy does not consider negatives as prime
# so only n=8 is tested
return (n - 8).is_zero
#----------------------------------------------------------------------------#
# #
# Partition numbers #
# #
#----------------------------------------------------------------------------#
_npartition = [1, 1]
class partition(Function):
r"""
Partition numbers
The Partition numbers are a sequence of integers `p_n` that represent the
number of distinct ways of representing `n` as a sum of natural numbers
(with order irrelevant). The generating function for `p_n` is given by:
.. math:: \sum_{n=0}^\infty p_n x^n = \prod_{k=1}^\infty (1 - x^k)^{-1}
Examples
========
>>> from sympy import Symbol
>>> from sympy.functions import partition
>>> [partition(n) for n in range(9)]
[1, 1, 2, 3, 5, 7, 11, 15, 22]
>>> n = Symbol('n', integer=True, negative=True)
>>> partition(n)
0
See Also
========
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, tribonacci
References
==========
.. [1] https://en.wikipedia.org/wiki/Partition_(number_theory%29
.. [2] https://en.wikipedia.org/wiki/Pentagonal_number_theorem
"""
@staticmethod
def _partition(n):
L = len(_npartition)
if n < L:
return _npartition[n]
# lengthen cache
for _n in range(L, n + 1):
v, p, i = 0, 0, 0
while 1:
s = 0
p += 3*i + 1 # p = pentagonal number: 1, 5, 12, ...
if _n >= p:
s += _npartition[_n - p]
i += 1
gp = p + i # gp = generalized pentagonal: 2, 7, 15, ...
if _n >= gp:
s += _npartition[_n - gp]
if s == 0:
break
else:
v += s if i%2 == 1 else -s
_npartition.append(v)
return v
@classmethod
def eval(cls, n):
is_int = n.is_integer
if is_int == False:
raise ValueError("Partition numbers are defined only for "
"integers")
elif is_int:
if n.is_negative:
return S.Zero
if n.is_zero or (n - 1).is_zero:
return S.One
if n.is_Integer:
return Integer(cls._partition(n))
def _eval_is_integer(self):
if self.args[0].is_integer:
return True
def _eval_is_negative(self):
if self.args[0].is_integer:
return False
def _eval_is_positive(self):
n = self.args[0]
if n.is_nonnegative and n.is_integer:
return True
#######################################################################
###
### Functions for enumerating partitions, permutations and combinations
###
#######################################################################
class _MultisetHistogram(tuple):
pass
_N = -1
_ITEMS = -2
_M = slice(None, _ITEMS)
def _multiset_histogram(n):
"""Return tuple used in permutation and combination counting. Input
is a dictionary giving items with counts as values or a sequence of
items (which need not be sorted).
The data is stored in a class deriving from tuple so it is easily
recognized and so it can be converted easily to a list.
"""
if isinstance(n, dict): # item: count
if not all(isinstance(v, int) and v >= 0 for v in n.values()):
raise ValueError
tot = sum(n.values())
items = sum(1 for k in n if n[k] > 0)
return _MultisetHistogram([n[k] for k in n if n[k] > 0] + [items, tot])
else:
n = list(n)
s = set(n)
if len(s) == len(n):
n = [1]*len(n)
n.extend([len(n), len(n)])
return _MultisetHistogram(n)
m = dict(zip(s, range(len(s))))
d = dict(zip(range(len(s)), [0]*len(s)))
for i in n:
d[m[i]] += 1
return _multiset_histogram(d)
def nP(n, k=None, replacement=False):
"""Return the number of permutations of ``n`` items taken ``k`` at a time.
Possible values for ``n``:
integer - set of length ``n``
sequence - converted to a multiset internally
multiset - {element: multiplicity}
If ``k`` is None then the total of all permutations of length 0
through the number of items represented by ``n`` will be returned.
If ``replacement`` is True then a given item can appear more than once
in the ``k`` items. (For example, for 'ab' permutations of 2 would
include 'aa', 'ab', 'ba' and 'bb'.) The multiplicity of elements in
``n`` is ignored when ``replacement`` is True but the total number
of elements is considered since no element can appear more times than
the number of elements in ``n``.
Examples
========
>>> from sympy.functions.combinatorial.numbers import nP
>>> from sympy.utilities.iterables import multiset_permutations, multiset
>>> nP(3, 2)
6
>>> nP('abc', 2) == nP(multiset('abc'), 2) == 6
True
>>> nP('aab', 2)
3
>>> nP([1, 2, 2], 2)
3
>>> [nP(3, i) for i in range(4)]
[1, 3, 6, 6]
>>> nP(3) == sum(_)
True
When ``replacement`` is True, each item can have multiplicity
equal to the length represented by ``n``:
>>> nP('aabc', replacement=True)
121
>>> [len(list(multiset_permutations('aaaabbbbcccc', i))) for i in range(5)]
[1, 3, 9, 27, 81]
>>> sum(_)
121
See Also
========
sympy.utilities.iterables.multiset_permutations
References
==========
.. [1] https://en.wikipedia.org/wiki/Permutation
"""
try:
n = as_int(n)
except ValueError:
return Integer(_nP(_multiset_histogram(n), k, replacement))
return Integer(_nP(n, k, replacement))
@cacheit
def _nP(n, k=None, replacement=False):
from sympy.functions.combinatorial.factorials import factorial
from sympy.core.mul import prod
if k == 0:
return 1
if isinstance(n, SYMPY_INTS): # n different items
# assert n >= 0
if k is None:
return sum(_nP(n, i, replacement) for i in range(n + 1))
elif replacement:
return n**k
elif k > n:
return 0
elif k == n:
return factorial(k)
elif k == 1:
return n
else:
# assert k >= 0
return _product(n - k + 1, n)
elif isinstance(n, _MultisetHistogram):
if k is None:
return sum(_nP(n, i, replacement) for i in range(n[_N] + 1))
elif replacement:
return n[_ITEMS]**k
elif k == n[_N]:
return factorial(k)/prod([factorial(i) for i in n[_M] if i > 1])
elif k > n[_N]:
return 0
elif k == 1:
return n[_ITEMS]
else:
# assert k >= 0
tot = 0
n = list(n)
for i in range(len(n[_M])):
if not n[i]:
continue
n[_N] -= 1
if n[i] == 1:
n[i] = 0
n[_ITEMS] -= 1
tot += _nP(_MultisetHistogram(n), k - 1)
n[_ITEMS] += 1
n[i] = 1
else:
n[i] -= 1
tot += _nP(_MultisetHistogram(n), k - 1)
n[i] += 1
n[_N] += 1
return tot
@cacheit
def _AOP_product(n):
"""for n = (m1, m2, .., mk) return the coefficients of the polynomial,
prod(sum(x**i for i in range(nj + 1)) for nj in n); i.e. the coefficients
of the product of AOPs (all-one polynomials) or order given in n. The
resulting coefficient corresponding to x**r is the number of r-length
combinations of sum(n) elements with multiplicities given in n.
The coefficients are given as a default dictionary (so if a query is made
for a key that is not present, 0 will be returned).
Examples
========
>>> from sympy.functions.combinatorial.numbers import _AOP_product
>>> from sympy.abc import x
>>> n = (2, 2, 3) # e.g. aabbccc
>>> prod = ((x**2 + x + 1)*(x**2 + x + 1)*(x**3 + x**2 + x + 1)).expand()
>>> c = _AOP_product(n); dict(c)
{0: 1, 1: 3, 2: 6, 3: 8, 4: 8, 5: 6, 6: 3, 7: 1}
>>> [c[i] for i in range(8)] == [prod.coeff(x, i) for i in range(8)]
True
The generating poly used here is the same as that listed in
http://tinyurl.com/cep849r, but in a refactored form.
"""
from collections import defaultdict
n = list(n)
ord = sum(n)
need = (ord + 2)//2
rv = [1]*(n.pop() + 1)
rv.extend([0]*(need - len(rv)))
rv = rv[:need]
while n:
ni = n.pop()
N = ni + 1
was = rv[:]
for i in range(1, min(N, len(rv))):
rv[i] += rv[i - 1]
for i in range(N, need):
rv[i] += rv[i - 1] - was[i - N]
rev = list(reversed(rv))
if ord % 2:
rv = rv + rev
else:
rv[-1:] = rev
d = defaultdict(int)
for i in range(len(rv)):
d[i] = rv[i]
return d
def nC(n, k=None, replacement=False):
"""Return the number of combinations of ``n`` items taken ``k`` at a time.
Possible values for ``n``:
integer - set of length ``n``
sequence - converted to a multiset internally
multiset - {element: multiplicity}
If ``k`` is None then the total of all combinations of length 0
through the number of items represented in ``n`` will be returned.
If ``replacement`` is True then a given item can appear more than once
in the ``k`` items. (For example, for 'ab' sets of 2 would include 'aa',
'ab', and 'bb'.) The multiplicity of elements in ``n`` is ignored when
``replacement`` is True but the total number of elements is considered
since no element can appear more times than the number of elements in
``n``.
Examples
========
>>> from sympy.functions.combinatorial.numbers import nC
>>> from sympy.utilities.iterables import multiset_combinations
>>> nC(3, 2)
3
>>> nC('abc', 2)
3
>>> nC('aab', 2)
2
When ``replacement`` is True, each item can have multiplicity
equal to the length represented by ``n``:
>>> nC('aabc', replacement=True)
35
>>> [len(list(multiset_combinations('aaaabbbbcccc', i))) for i in range(5)]
[1, 3, 6, 10, 15]
>>> sum(_)
35
If there are ``k`` items with multiplicities ``m_1, m_2, ..., m_k``
then the total of all combinations of length 0 through ``k`` is the
product, ``(m_1 + 1)*(m_2 + 1)*...*(m_k + 1)``. When the multiplicity
of each item is 1 (i.e., k unique items) then there are 2**k
combinations. For example, if there are 4 unique items, the total number
of combinations is 16:
>>> sum(nC(4, i) for i in range(5))
16
See Also
========
sympy.utilities.iterables.multiset_combinations
References
==========
.. [1] https://en.wikipedia.org/wiki/Combination
.. [2] http://tinyurl.com/cep849r
"""
from sympy.functions.combinatorial.factorials import binomial
from sympy.core.mul import prod
if isinstance(n, SYMPY_INTS):
if k is None:
if not replacement:
return 2**n
return sum(nC(n, i, replacement) for i in range(n + 1))
if k < 0:
raise ValueError("k cannot be negative")
if replacement:
return binomial(n + k - 1, k)
return binomial(n, k)
if isinstance(n, _MultisetHistogram):
N = n[_N]
if k is None:
if not replacement:
return prod(m + 1 for m in n[_M])
return sum(nC(n, i, replacement) for i in range(N + 1))
elif replacement:
return nC(n[_ITEMS], k, replacement)
# assert k >= 0
elif k in (1, N - 1):
return n[_ITEMS]
elif k in (0, N):
return 1
return _AOP_product(tuple(n[_M]))[k]
else:
return nC(_multiset_histogram(n), k, replacement)
def _eval_stirling1(n, k):
if n == k == 0:
return S.One
if 0 in (n, k):
return S.Zero
# some special values
if n == k:
return S.One
elif k == n - 1:
return binomial(n, 2)
elif k == n - 2:
return (3*n - 1)*binomial(n, 3)/4
elif k == n - 3:
return binomial(n, 2)*binomial(n, 4)
return _stirling1(n, k)
@cacheit
def _stirling1(n, k):
row = [0, 1]+[0]*(k-1) # for n = 1
for i in range(2, n+1):
for j in range(min(k,i), 0, -1):
row[j] = (i-1) * row[j] + row[j-1]
return Integer(row[k])
def _eval_stirling2(n, k):
if n == k == 0:
return S.One
if 0 in (n, k):
return S.Zero
# some special values
if n == k:
return S.One
elif k == n - 1:
return binomial(n, 2)
elif k == 1:
return S.One
elif k == 2:
return Integer(2**(n - 1) - 1)
return _stirling2(n, k)
@cacheit
def _stirling2(n, k):
row = [0, 1]+[0]*(k-1) # for n = 1
for i in range(2, n+1):
for j in range(min(k,i), 0, -1):
row[j] = j * row[j] + row[j-1]
return Integer(row[k])
def stirling(n, k, d=None, kind=2, signed=False):
r"""Return Stirling number $S(n, k)$ of the first or second (default) kind.
The sum of all Stirling numbers of the second kind for $k = 1$
through $n$ is ``bell(n)``. The recurrence relationship for these numbers
is:
.. math :: {0 \brace 0} = 1; {n \brace 0} = {0 \brace k} = 0;
.. math :: {{n+1} \brace k} = j {n \brace k} + {n \brace {k-1}}
where $j$ is:
$n$ for Stirling numbers of the first kind,
$-n$ for signed Stirling numbers of the first kind,
$k$ for Stirling numbers of the second kind.
The first kind of Stirling number counts the number of permutations of
``n`` distinct items that have ``k`` cycles; the second kind counts the
ways in which ``n`` distinct items can be partitioned into ``k`` parts.
If ``d`` is given, the "reduced Stirling number of the second kind" is
returned: $S^{d}(n, k) = S(n - d + 1, k - d + 1)$ with $n \ge k \ge d$.
(This counts the ways to partition $n$ consecutive integers into $k$
groups with no pairwise difference less than $d$. See example below.)
To obtain the signed Stirling numbers of the first kind, use keyword
``signed=True``. Using this keyword automatically sets ``kind`` to 1.
Examples
========
>>> from sympy.functions.combinatorial.numbers import stirling, bell
>>> from sympy.combinatorics import Permutation
>>> from sympy.utilities.iterables import multiset_partitions, permutations
First kind (unsigned by default):
>>> [stirling(6, i, kind=1) for i in range(7)]
[0, 120, 274, 225, 85, 15, 1]
>>> perms = list(permutations(range(4)))
>>> [sum(Permutation(p).cycles == i for p in perms) for i in range(5)]
[0, 6, 11, 6, 1]
>>> [stirling(4, i, kind=1) for i in range(5)]
[0, 6, 11, 6, 1]
First kind (signed):
>>> [stirling(4, i, signed=True) for i in range(5)]
[0, -6, 11, -6, 1]
Second kind:
>>> [stirling(10, i) for i in range(12)]
[0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1, 0]
>>> sum(_) == bell(10)
True
>>> len(list(multiset_partitions(range(4), 2))) == stirling(4, 2)
True
Reduced second kind:
>>> from sympy import subsets, oo
>>> 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
>>> sum(1 for p in parts if all(delta(i) >= d for i in p))
7
>>> stirling(5, 3, 2)
7
See Also
========
sympy.utilities.iterables.multiset_partitions
References
==========
.. [1] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
.. [2] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
"""
# TODO: make this a class like bell()
n = as_int(n)
k = as_int(k)
if n < 0:
raise ValueError('n must be nonnegative')
if k > n:
return S.Zero
if d:
# assert k >= d
# kind is ignored -- only kind=2 is supported
return _eval_stirling2(n - d + 1, k - d + 1)
elif signed:
# kind is ignored -- only kind=1 is supported
return (-1)**(n - k)*_eval_stirling1(n, k)
if kind == 1:
return _eval_stirling1(n, k)
elif kind == 2:
return _eval_stirling2(n, k)
else:
raise ValueError('kind must be 1 or 2, not %s' % k)
@cacheit
def _nT(n, k):
"""Return the partitions of ``n`` items into ``k`` parts. This
is used by ``nT`` for the case when ``n`` is an integer."""
# really quick exits
if k > n or k < 0:
return 0
if k == n or k == 1:
return 1
if k == 0:
return 0
# exits that could be done below but this is quicker
if k == 2:
return n//2
d = n - k
if d <= 3:
return d
# quick exit
if 3*k >= n: # or, equivalently, 2*k >= d
# all the information needed in this case
# will be in the cache needed to calculate
# partition(d), so...
# update cache
tot = partition._partition(d)
# and correct for values not needed
if d - k > 0:
tot -= sum(_npartition[:d - k])
return tot
# regular exit
# nT(n, k) = Sum(nT(n - k, m), (m, 1, k));
# calculate needed nT(i, j) values
p = [1]*d
for i in range(2, k + 1):
for m in range(i + 1, d):
p[m] += p[m - i]
d -= 1
# if p[0] were appended to the end of p then the last
# k values of p are the nT(n, j) values for 0 < j < k in reverse
# order p[-1] = nT(n, 1), p[-2] = nT(n, 2), etc.... Instead of
# putting the 1 from p[0] there, however, it is simply added to
# the sum below which is valid for 1 < k <= n//2
return (1 + sum(p[1 - k:]))
def nT(n, k=None):
"""Return the number of ``k``-sized partitions of ``n`` items.
Possible values for ``n``:
integer - ``n`` identical items
sequence - converted to a multiset internally
multiset - {element: multiplicity}
Note: the convention for ``nT`` is different than that of ``nC`` and
``nP`` in that
here an integer indicates ``n`` *identical* items instead of a set of
length ``n``; this is in keeping with the ``partitions`` function which
treats its integer-``n`` input like a list of ``n`` 1s. One can use
``range(n)`` for ``n`` to indicate ``n`` distinct items.
If ``k`` is None then the total number of ways to partition the elements
represented in ``n`` will be returned.
Examples
========
>>> from sympy.functions.combinatorial.numbers import nT
Partitions of the given multiset:
>>> [nT('aabbc', i) for i in range(1, 7)]
[1, 8, 11, 5, 1, 0]
>>> nT('aabbc') == sum(_)
True
>>> [nT("mississippi", i) for i in range(1, 12)]
[1, 74, 609, 1521, 1768, 1224, 579, 197, 50, 9, 1]
Partitions when all items are identical:
>>> [nT(5, i) for i in range(1, 6)]
[1, 2, 2, 1, 1]
>>> nT('1'*5) == sum(_)
True
When all items are different:
>>> [nT(range(5), i) for i in range(1, 6)]
[1, 15, 25, 10, 1]
>>> nT(range(5)) == sum(_)
True
Partitions of an integer expressed as a sum of positive integers:
>>> from sympy.functions.combinatorial.numbers import partition
>>> partition(4)
5
>>> nT(4, 1) + nT(4, 2) + nT(4, 3) + nT(4, 4)
5
>>> nT('1'*4)
5
See Also
========
sympy.utilities.iterables.partitions
sympy.utilities.iterables.multiset_partitions
sympy.functions.combinatorial.numbers.partition
References
==========
.. [1] http://undergraduate.csse.uwa.edu.au/units/CITS7209/partition.pdf
"""
from sympy.utilities.enumerative import MultisetPartitionTraverser
if isinstance(n, SYMPY_INTS):
# n identical items
if k is None:
return partition(n)
if isinstance(k, SYMPY_INTS):
n = as_int(n)
k = as_int(k)
return Integer(_nT(n, k))
if not isinstance(n, _MultisetHistogram):
try:
# if n contains hashable items there is some
# quick handling that can be done
u = len(set(n))
if u <= 1:
return nT(len(n), k)
elif u == len(n):
n = range(u)
raise TypeError
except TypeError:
n = _multiset_histogram(n)
N = n[_N]
if k is None and N == 1:
return 1
if k in (1, N):
return 1
if k == 2 or N == 2 and k is None:
m, r = divmod(N, 2)
rv = sum(nC(n, i) for i in range(1, m + 1))
if not r:
rv -= nC(n, m)//2
if k is None:
rv += 1 # for k == 1
return rv
if N == n[_ITEMS]:
# all distinct
if k is None:
return bell(N)
return stirling(N, k)
m = MultisetPartitionTraverser()
if k is None:
return m.count_partitions(n[_M])
# MultisetPartitionTraverser does not have a range-limited count
# method, so need to enumerate and count
tot = 0
for discard in m.enum_range(n[_M], k-1, k):
tot += 1
return tot
#-----------------------------------------------------------------------------#
# #
# Motzkin numbers #
# #
#-----------------------------------------------------------------------------#
class motzkin(Function):
"""
The nth Motzkin number is the number
of ways of drawing non-intersecting chords
between n points on a circle (not necessarily touching
every point by a chord). The Motzkin numbers are named
after Theodore Motzkin and have diverse applications
in geometry, combinatorics and number theory.
Motzkin numbers are the integer sequence defined by the
initial terms `M_0 = 1`, `M_1 = 1` and the two-term recurrence relation
`M_n = \frac{2*n + 1}{n + 2} * M_{n-1} + \frac{3n - 3}{n + 2} * M_{n-2}`.
Examples
========
>>> from sympy import motzkin
>>> motzkin.is_motzkin(5)
False
>>> motzkin.find_motzkin_numbers_in_range(2,300)
[2, 4, 9, 21, 51, 127]
>>> motzkin.find_motzkin_numbers_in_range(2,900)
[2, 4, 9, 21, 51, 127, 323, 835]
>>> motzkin.find_first_n_motzkins(10)
[1, 1, 2, 4, 9, 21, 51, 127, 323, 835]
References
==========
.. [1] https://en.wikipedia.org/wiki/Motzkin_number
.. [2] https://mathworld.wolfram.com/MotzkinNumber.html
"""
@staticmethod
def is_motzkin(n):
try:
n = as_int(n)
except ValueError:
return False
if n > 0:
if n == 1 or n == 2:
return True
tn1 = 1
tn = 2
i = 3
while tn < n:
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
i += 1
tn1 = tn
tn = a
if tn == n:
return True
else:
return False
else:
return False
@staticmethod
def find_motzkin_numbers_in_range(x, y):
if 0 <= x <= y:
motzkins = list()
if x <= 1 <= y:
motzkins.append(1)
tn1 = 1
tn = 2
i = 3
while tn <= y:
if tn >= x:
motzkins.append(tn)
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
i += 1
tn1 = tn
tn = int(a)
return motzkins
else:
raise ValueError('The provided range is not valid. This condition should satisfy x <= y')
@staticmethod
def find_first_n_motzkins(n):
try:
n = as_int(n)
except ValueError:
raise ValueError('The provided number must be a positive integer')
if n < 0:
raise ValueError('The provided number must be a positive integer')
motzkins = list()
if n >= 0:
motzkins.append(1)
if n >= 1:
motzkins.append(1)
tn1 = 1
tn = 2
i = 3
while i <= n:
motzkins.append(tn)
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
i += 1
tn1 = tn
tn = int(a)
return motzkins
@staticmethod
@recurrence_memo([S.One, S.One])
def _motzkin(n, prev):
return ((2*n + 1)*prev[-1] + (3*n - 3)*prev[-2]) // (n + 2)
@classmethod
def eval(cls, n):
try:
n = as_int(n)
except ValueError:
raise ValueError('The provided number must be a positive integer')
if n < 0:
raise ValueError('The provided number must be a positive integer')
return Integer(cls._motzkin(n - 1))
|
001c38e53d5db680e6322ed2ec2ccfd4ee88ed343d0d9782cc4d5d8e76046ac2 | from typing import Tuple
from sympy.core.add import Add
from sympy.core.basic import sympify, 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
from sympy.core.numbers import igcdex, Rational, pi
from sympy.core.relational import Ne
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.combinatorial.factorials import factorial, RisingFactorial
from sympy.functions.elementary.exponential import log, exp
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.hyperbolic import (acoth, asinh, atanh, cosh,
coth, HyperbolicFunction, sinh, tanh)
from sympy.functions.elementary.miscellaneous import sqrt, Min, Max
from sympy.functions.elementary.piecewise import Piecewise
from sympy.sets.sets import FiniteSet
from sympy.utilities.iterables import numbered_symbols
###############################################################################
########################## 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.")
def _peeloff_pi(arg):
"""
Split ARG into two parts, a "rest" and a multiple of pi/2.
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 as peel
>>> from sympy import pi
>>> from sympy.abc import x, y
>>> peel(x + pi/2)
(x, pi/2)
>>> peel(x + 2*pi/3 + pi*y)
(x + pi*y + pi/6, pi/2)
"""
pi_coeff = S.Zero
rest_terms = []
for a in Add.make_args(arg):
K = a.coeff(S.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)*S.Pi
m2 = pi_coeff*S.Pi - m1
final_coeff = m2 / S.Pi
if final_coeff.is_integer or ((2*final_coeff).is_integer
and final_coeff.is_even is False):
return Add(*(rest_terms + [m1])), m2
return arg, S.Zero
def _pi_coeff(arg, cycles=1):
"""
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 as coeff
>>> from sympy import pi, Dummy
>>> from sympy.abc import x
>>> coeff(3*x*pi)
3*x
>>> coeff(11*pi/7)
11/7
>>> coeff(-11*pi/7)
3/7
>>> coeff(4*pi)
0
>>> coeff(5*pi)
1
>>> coeff(5.0*pi)
1
>>> coeff(5.5*pi)
3/2
>>> coeff(2 + pi)
>>> coeff(2*Dummy(integer=True)*pi)
2
>>> coeff(2*Dummy(even=True)*pi)
0
"""
arg = sympify(arg)
if arg is S.Pi:
return S.One
elif not arg:
return S.Zero
elif arg.is_Mul:
cx = arg.coeff(S.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 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 S(2)
else:
return c2*x
return cx
elif arg.is_zero:
return S.Zero
class sin(TrigonometricFunction):
"""
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 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 is S.Infinity or arg is S.NegativeInfinity:
return AccumBounds(-1, 1)
if arg is S.ComplexInfinity:
return S.NaN
if isinstance(arg, AccumBounds):
min, max = arg.min, arg.max
d = floor(min/(2*S.Pi))
if min is not S.NegativeInfinity:
min = min - d*2*S.Pi
if max is not S.Infinity:
max = max - d*2*S.Pi
if AccumBounds(min, max).intersection(FiniteSet(S.Pi/2, S.Pi*Rational(5, 2))) \
is not S.EmptySet and \
AccumBounds(min, max).intersection(FiniteSet(S.Pi*Rational(3, 2),
S.Pi*Rational(7, 2))) is not S.EmptySet:
return AccumBounds(-1, 1)
elif AccumBounds(min, max).intersection(FiniteSet(S.Pi/2, S.Pi*Rational(5, 2))) \
is not S.EmptySet:
return AccumBounds(Min(sin(min), sin(max)), 1)
elif AccumBounds(min, max).intersection(FiniteSet(S.Pi*Rational(3, 2), S.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 = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
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*S.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)*S.Pi)
if 2*x > 1:
return cls((1 - x)*S.Pi)
narg = ((pi_coeff + Rational(3, 2)) % 2)*S.Pi
result = cos(narg)
if not isinstance(result, cos):
return result
if pi_coeff*S.Pi != arg:
return cls(pi_coeff*S.Pi)
return None
if arg.is_Add:
x, m = _peeloff_pi(arg)
if m:
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 (-1)**(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
if isinstance(arg, TrigonometricFunction) or isinstance(arg, 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 - S.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 2*cot_half/(1 + cot_half**2)
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 - S.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):
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 import expand_mul
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 (-1)**((n - 1)/2)*chebyshevt(n, sin(x))
else:
return expand_mul((-1)**(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, cdir=0):
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
n = x0/S.Pi
if n.is_integer:
lt = (arg - n*S.Pi).as_leading_term(x)
return ((-1)**n)*lt
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):
arg = self.args[0]
if arg.is_zero:
return True
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.util 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 is S.Infinity or arg is 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 + S.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 = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
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*S.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)
cst_table_some = {
3: S.Half,
5: (sqrt(5) + 1)/4,
}
if pi_coeff.is_Rational:
q = pi_coeff.q
p = pi_coeff.p % (2*q)
if p > q:
narg = (pi_coeff - 1)*S.Pi
return -cls(narg)
if 2*p > q:
narg = (1 - pi_coeff)*S.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 = {
12: (3, 4),
20: (4, 5),
30: (5, 6),
15: (6, 10),
24: (6, 8),
40: (8, 10),
60: (20, 30),
120: (40, 60)
}
if q in table2:
a, b = p*S.Pi/table2[q][0], p*S.Pi/table2[q][1]
nvala, nvalb = cls(a), cls(b)
if None == nvala or None == nvalb:
return None
return nvala*nvalb + cls(S.Pi/2 - a)*cls(S.Pi/2 - b)
if q > 12:
return None
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)*S.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:
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 (-1)**(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
if isinstance(arg, TrigonometricFunction) or isinstance(arg, 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 + S.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 (cot_half - 1)/(cot_half + 1)
def _eval_rewrite_as_pow(self, arg, **kwargs):
return self._eval_rewrite_as_sqrt(arg)
def _eval_rewrite_as_sqrt(self, arg, **kwargs):
from sympy.functions.special.polynomials import chebyshevt
def migcdex(x):
# recursive calcuation of gcd and linear combination
# for a sequence of integers.
# Given (x1, x2, x3)
# Returns (y1, y1, y3, g)
# such that g is the gcd and x1*y1+x2*y2+x3*y3 - g = 0
# Note, that this is only one such linear combination.
if len(x) == 1:
return (1, x[0])
if len(x) == 2:
return igcdex(x[0], x[-1])
g = migcdex(x[1:])
u, v, h = igcdex(x[0], g[-1])
return tuple([u] + [v*i for i in g[0:-1] ] + [h])
def ipartfrac(r, factors=None):
from sympy.ntheory import factorint
if isinstance(r, int):
return r
if not isinstance(r, Rational):
raise TypeError("r is not rational")
n = r.q
if 2 > r.q*r.q:
return r.q
if None == factors:
a = [n//x**y for x, y in factorint(r.q).items()]
else:
a = [n//x for x in factors]
if len(a) == 1:
return [ r ]
h = migcdex(a)
ans = [ r.p*Rational(i*j, r.q) for i, j in zip(h[:-1], a) ]
assert r == sum(ans)
return ans
pi_coeff = _pi_coeff(arg)
if pi_coeff is None:
return None
if pi_coeff.is_integer:
# it was unevaluated
return self.func(pi_coeff*S.Pi)
if not pi_coeff.is_Rational:
return None
def _cospi257():
""" Express cos(pi/257) explicitly as a function of radicals
Based upon the equations in
http://math.stackexchange.com/questions/516142/how-does-cos2-pi-257-look-like-in-real-radicals
See also http://www.susqu.edu/brakke/constructions/257-gon.m.txt
"""
def f1(a, b):
return (a + sqrt(a**2 + b))/2, (a - sqrt(a**2 + b))/2
def f2(a, b):
return (a - sqrt(a**2 + b))/2
t1, t2 = f1(-1, 256)
z1, z3 = f1(t1, 64)
z2, z4 = f1(t2, 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)
cst_table_some = {
3: S.Half,
5: (sqrt(5) + 1)/4,
17: 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),
257: _cospi257()
# 65537 is the only other known Fermat prime and the very
# large expression is intentionally omitted from SymPy; see
# http://www.susqu.edu/brakke/constructions/65537-gon.m.txt
}
def _fermatCoords(n):
# if n can be factored in terms of Fermat primes with
# multiplicity of each being 1, return those primes, else
# False
primes = []
for p_i in cst_table_some:
quotient, remainder = divmod(n, p_i)
if remainder == 0:
n = quotient
primes.append(p_i)
if n == 1:
return tuple(primes)
return False
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*S.Pi).rewrite(sqrt)
x = (pico2 + 1)/2
sign_cos = -1 if int(x) % 2 else 1
return sign_cos*sqrt( (1 + nval)/2 )
FC = _fermatCoords(pi_coeff.q)
if FC:
decomp = ipartfrac(pi_coeff, FC)
X = [(x[1], x[0]*S.Pi) for x in zip(decomp, numbered_symbols('z'))]
pcls = cos(sum([x[0] for x in X]))._eval_expand_trig().subs(X)
return pcls.rewrite(sqrt)
else:
decomp = ipartfrac(pi_coeff)
X = [(x[1], x[0]*S.Pi) for x in zip(decomp, numbered_symbols('z'))]
pcls = cos(sum([x[0] for x in X]))._eval_expand_trig().subs(X)
return pcls
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):
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, cdir=0):
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
n = (x0 + S.Pi/2)/S.Pi
if n.is_integer:
lt = (arg - n*S.Pi + S.Pi/2).as_leading_term(x)
return ((-1)**n)*lt
if not x0.is_finite:
return self
return self.func(x0)
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
class tan(TrigonometricFunction):
"""
The tangent function.
Returns the tangent of x (measured in radians).
Explanation
===========
See :func:`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.util import AccumBounds
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg.is_zero:
return S.Zero
elif arg is S.Infinity or arg is 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/S.Pi)
if min is not S.NegativeInfinity:
min = min - d*S.Pi
if max is not S.Infinity:
max = max - d*S.Pi
if AccumBounds(min, max).intersection(FiniteSet(S.Pi/2, S.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 = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
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*S.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 == 5 or q == 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*S.Pi*2
cresult, sresult = cos(narg), cos(narg - S.Pi/2)
if not isinstance(cresult, cos) \
and not isinstance(sresult, cos):
if sresult == 0:
return S.ComplexInfinity
return 1/sresult - cresult/sresult
table2 = {
12: (3, 4),
20: (4, 5),
30: (5, 6),
15: (6, 10),
24: (6, 8),
40: (8, 10),
60: (20, 30),
120: (40, 60)
}
if q in table2:
nvala, nvalb = cls(p*S.Pi/table2[q][0]), cls(p*S.Pi/table2[q][1])
if None == nvala or None == nvalb:
return None
return (nvala - nvalb)/(1 + nvala*nvalb)
narg = ((pi_coeff + S.Half) % 1 - S.Half)*S.Pi
# see cos() to specify which expressions should be
# expanded automatically in terms of radicals
cresult, sresult = cos(narg), cos(narg - S.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)
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):
from sympy import bernoulli
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 (-1)**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/S.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:
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):
from sympy import im, re
arg = self.args[0]
x = None
if arg.is_Add:
from sympy import symmetric_poly
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
if isinstance(arg, TrigonometricFunction) or isinstance(arg, 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 - S.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, cdir=0):
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
n = 2*x0/S.Pi
if n.is_integer:
lt = (arg - n*S.Pi/2).as_leading_term(x)
return lt if n.is_even else -1/lt
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):
arg = self.args[0]
if arg.is_zero:
return True
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 :func:`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.util import AccumBounds
if arg.is_Number:
if arg is S.NaN:
return S.NaN
if arg.is_zero:
return S.ComplexInfinity
if arg is S.ComplexInfinity:
return S.NaN
if isinstance(arg, AccumBounds):
return -tan(arg + S.Pi/2)
if arg.could_extract_minus_sign():
return -cls(-arg)
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
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*S.Pi
if narg != arg:
return cls(narg)
return None
if pi_coeff.is_Rational:
if pi_coeff.q == 5 or pi_coeff.q == 10:
return tan(S.Pi/2 - arg)
if pi_coeff.q > 2 and not pi_coeff.q % 2:
narg = pi_coeff*S.Pi*2
cresult, sresult = cos(narg), cos(narg - S.Pi/2)
if not isinstance(cresult, cos) \
and not isinstance(sresult, cos):
return 1/sresult + cresult/sresult
table2 = {
12: (3, 4),
20: (4, 5),
30: (5, 6),
15: (6, 10),
24: (6, 8),
40: (8, 10),
60: (20, 30),
120: (40, 60)
}
q = pi_coeff.q
p = pi_coeff.p % q
if q in table2:
nvala, nvalb = cls(p*S.Pi/table2[q][0]), cls(p*S.Pi/table2[q][1])
if None == nvala or None == nvalb:
return None
return (1 + nvala*nvalb)/(nvalb - nvala)
narg = (((pi_coeff + S.Half) % 1) - S.Half)*S.Pi
# see cos() to specify which expressions should be
# expanded automatically in terms of radicals
cresult, sresult = cos(narg), cos(narg - S.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)
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):
from sympy import bernoulli
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 (-1)**((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)/S.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:
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):
I = S.ImaginaryUnit
if isinstance(arg, TrigonometricFunction) or isinstance(arg, 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 - S.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, cdir=0):
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
n = 2*x0/S.Pi
if n.is_integer:
lt = (arg - n*S.Pi/2).as_leading_term(x)
return 1/lt if n.is_even else -lt
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):
from sympy import im, re
arg = self.args[0]
x = None
if arg.is_Add:
from sympy import symmetric_poly
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_subs(self, old, new):
arg = self.args[0]
argnew = arg.subs(old, new)
if arg != argnew and (argnew/S.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 = None # type: FuzzyBool
_is_odd = None # type: FuzzyBool
@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)*S.Pi
return -cls(narg)
if 2*p > q:
narg = (1 - pi_coeff)*S.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, 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 :func:`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/
from sympy.functions.combinatorial.numbers import euler
if n < 0 or n % 2 == 1:
return S.Zero
else:
x = sympify(x)
k = n//2
return (-1)**k*euler(2*k)/factorial(2*k)*x**(2*k)
def _eval_as_leading_term(self, x, cdir=0):
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
n = (x0 + S.Pi/2)/S.Pi
if n.is_integer:
lt = (arg - n*S.Pi + S.Pi/2).as_leading_term(x)
return ((-1)**n)/lt
return self.func(x0)
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):
from sympy import bernoulli
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 ((-1)**(k - 1)*2*(2**(2*k - 1) - 1)*
bernoulli(2*k)*x**(2*k - 1)/factorial(2*k))
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))
###############################################################################
########################### TRIGONOMETRIC INVERSES ############################
###############################################################################
class InverseTrigonometricFunction(Function):
"""Base class for inverse trigonometric functions."""
_singularities = (S.One, S.NegativeOne, S.Zero, S.ComplexInfinity) # type: Tuple[Expr, ...]
@staticmethod
def _asin_table():
# Only keys with could_extract_minus_sign() == False
# are actually needed.
return {
sqrt(3)/2: S.Pi/3,
sqrt(2)/2: S.Pi/4,
1/sqrt(2): S.Pi/4,
sqrt((5 - sqrt(5))/8): S.Pi/5,
sqrt(2)*sqrt(5 - sqrt(5))/4: S.Pi/5,
sqrt((5 + sqrt(5))/8): S.Pi*Rational(2, 5),
sqrt(2)*sqrt(5 + sqrt(5))/4: S.Pi*Rational(2, 5),
S.Half: S.Pi/6,
sqrt(2 - sqrt(2))/2: S.Pi/8,
sqrt(S.Half - sqrt(2)/4): S.Pi/8,
sqrt(2 + sqrt(2))/2: S.Pi*Rational(3, 8),
sqrt(S.Half + sqrt(2)/4): S.Pi*Rational(3, 8),
(sqrt(5) - 1)/4: S.Pi/10,
(1 - sqrt(5))/4: -S.Pi/10,
(sqrt(5) + 1)/4: S.Pi*Rational(3, 10),
sqrt(6)/4 - sqrt(2)/4: S.Pi/12,
-sqrt(6)/4 + sqrt(2)/4: -S.Pi/12,
(sqrt(3) - 1)/sqrt(8): S.Pi/12,
(1 - sqrt(3))/sqrt(8): -S.Pi/12,
sqrt(6)/4 + sqrt(2)/4: S.Pi*Rational(5, 12),
(1 + sqrt(3))/sqrt(8): S.Pi*Rational(5, 12)
}
@staticmethod
def _atan_table():
# Only keys with could_extract_minus_sign() == False
# are actually needed.
return {
sqrt(3)/3: S.Pi/6,
1/sqrt(3): S.Pi/6,
sqrt(3): S.Pi/3,
sqrt(2) - 1: S.Pi/8,
1 - sqrt(2): -S.Pi/8,
1 + sqrt(2): S.Pi*Rational(3, 8),
sqrt(5 - 2*sqrt(5)): S.Pi/5,
sqrt(5 + 2*sqrt(5)): S.Pi*Rational(2, 5),
sqrt(1 - 2*sqrt(5)/5): S.Pi/10,
sqrt(1 + 2*sqrt(5)/5): S.Pi*Rational(3, 10),
2 - sqrt(3): S.Pi/12,
-2 + sqrt(3): -S.Pi/12,
2 + sqrt(3): S.Pi*Rational(5, 12)
}
@staticmethod
def _acsc_table():
# Keys for which could_extract_minus_sign()
# will obviously return True are omitted.
return {
2*sqrt(3)/3: S.Pi/3,
sqrt(2): S.Pi/4,
sqrt(2 + 2*sqrt(5)/5): S.Pi/5,
1/sqrt(Rational(5, 8) - sqrt(5)/8): S.Pi/5,
sqrt(2 - 2*sqrt(5)/5): S.Pi*Rational(2, 5),
1/sqrt(Rational(5, 8) + sqrt(5)/8): S.Pi*Rational(2, 5),
2: S.Pi/6,
sqrt(4 + 2*sqrt(2)): S.Pi/8,
2/sqrt(2 - sqrt(2)): S.Pi/8,
sqrt(4 - 2*sqrt(2)): S.Pi*Rational(3, 8),
2/sqrt(2 + sqrt(2)): S.Pi*Rational(3, 8),
1 + sqrt(5): S.Pi/10,
sqrt(5) - 1: S.Pi*Rational(3, 10),
-(sqrt(5) - 1): S.Pi*Rational(-3, 10),
sqrt(6) + sqrt(2): S.Pi/12,
sqrt(6) - sqrt(2): S.Pi*Rational(5, 12),
-(sqrt(6) - sqrt(2)): S.Pi*Rational(-5, 12)
}
class asin(InverseTrigonometricFunction):
"""
The inverse sine function.
Returns the arcsine of x in radians.
Explanation
===========
``asin(x)`` will evaluate automatically in the cases ``oo``, ``-oo``,
``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 S.Pi/2
elif arg is S.NegativeOne:
return -S.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 = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
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, cdir=0):
from sympy import I, im, log
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
if x0.is_zero:
return arg.as_leading_term(x)
if x0 is S.ComplexInfinity:
return I*log(arg.as_leading_term(x))
if cdir != 0:
cdir = arg.dir(x, cdir)
if im(cdir) < 0 and x0.is_real and x0 < S.NegativeOne:
return -S.Pi - self.func(x0)
elif im(cdir) > 0 and x0.is_real and x0 > S.One:
return S.Pi - self.func(x0)
return self.func(x0)
def _eval_nseries(self, x, n, logx, cdir=0): #asin
from sympy import Dummy, im, O
arg0 = self.args[0].subs(x, 0)
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 S.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 -S.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
if cdir != 0:
cdir = self.args[0].dir(x, cdir)
if im(cdir) < 0 and arg0.is_real and arg0 < S.NegativeOne:
return -S.Pi - res
elif im(cdir) > 0 and arg0.is_real and arg0 > S.One:
return S.Pi - res
return res
def _eval_rewrite_as_acos(self, x, **kwargs):
return S.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))
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 S.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):
"""
The inverse cosine function.
Returns the arc cosine of x (measured in radians).
Examples
========
``acos(x)`` will evaluate automatically in the cases
``oo``, ``-oo``, ``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 S.Pi/2
elif arg is S.One:
return S.Zero
elif arg is S.NegativeOne:
return S.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 = arg.as_coefficient(S.ImaginaryUnit)
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 S.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, cdir=0):
from sympy import I, im, log
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
if x0 == 1:
return sqrt(2)*sqrt((S.One - arg).as_leading_term(x))
if x0 is S.ComplexInfinity:
return I*log(arg.as_leading_term(x))
if cdir != 0:
cdir = arg.dir(x, cdir)
if im(cdir) < 0 and x0.is_real and x0 < S.NegativeOne:
return 2*S.Pi - self.func(x0)
elif im(cdir) > 0 and x0.is_real and x0 > S.One:
return -self.func(x0)
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 import Dummy, im, O
arg0 = self.args[0].subs(x, 0)
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 S.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
if cdir != 0:
cdir = self.args[0].dir(x, cdir)
if im(cdir) < 0 and arg0.is_real and arg0 < S.NegativeOne:
return 2*S.Pi - res
elif im(cdir) > 0 and arg0.is_real and arg0 > S.One:
return -res
return res
def _eval_rewrite_as_log(self, x, **kwargs):
return S.Pi/2 + S.ImaginaryUnit*\
log(S.ImaginaryUnit*x + sqrt(1 - x**2))
def _eval_rewrite_as_asin(self, x, **kwargs):
return S.Pi/2 - asin(x)
def _eval_rewrite_as_atan(self, x, **kwargs):
return atan(sqrt(1 - x**2)/x) + (S.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 S.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 S.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):
"""
The inverse tangent function.
Returns the arc tangent of x (measured in radians).
Explanation
===========
``atan(x)`` will evaluate automatically in the cases
``oo``, ``-oo``, ``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
"""
_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 S.Pi/2
elif arg is S.NegativeInfinity:
return -S.Pi/2
elif arg.is_zero:
return S.Zero
elif arg is S.One:
return S.Pi/4
elif arg is S.NegativeOne:
return -S.Pi/4
if arg is S.ComplexInfinity:
from sympy.calculus.util import AccumBounds
return AccumBounds(-S.Pi/2, S.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 = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
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 (-1)**((n - 1)//2)*x**n/n
def _eval_as_leading_term(self, x, cdir=0):
from sympy import im, re
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
if x0.is_zero:
return arg.as_leading_term(x)
if x0 is S.ComplexInfinity:
return acot(1/arg)._eval_as_leading_term(x, cdir=cdir)
if cdir != 0:
cdir = arg.dir(x, cdir)
if re(cdir) < 0 and re(x0).is_zero and im(x0) > S.One:
return self.func(x0) - S.Pi
elif re(cdir) > 0 and re(x0).is_zero and im(x0) < S.NegativeOne:
return self.func(x0) + S.Pi
return self.func(x0)
def _eval_nseries(self, x, n, logx, cdir=0): #atan
from sympy import im, re
arg0 = self.args[0].subs(x, 0)
res = Function._eval_nseries(self, x, n=n, logx=logx)
if cdir != 0:
cdir = self.args[0].dir(x, cdir)
if arg0 is S.ComplexInfinity:
if re(cdir) > 0:
return res - S.Pi
return res
if re(cdir) < 0 and re(arg0).is_zero and im(arg0) > S.One:
return res - S.Pi
elif re(cdir) > 0 and re(arg0).is_zero and im(arg0) < S.NegativeOne:
return res + S.Pi
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))
def _eval_aseries(self, n, args0, x, logx):
if args0[0] is S.Infinity:
return (S.Pi/2 - atan(1/self.args[0]))._eval_nseries(x, n, logx)
elif args0[0] is S.NegativeInfinity:
return (-S.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*(S.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*(S.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 ``oo``, ``-oo``,
``zoo``, ``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 S.Pi/ 2
elif arg is S.One:
return S.Pi/4
elif arg is S.NegativeOne:
return -S.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 = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return -S.ImaginaryUnit*acoth(i_coeff)
if arg.is_zero:
return S.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 S.Pi/2 # FIX THIS
elif n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
return (-1)**((n + 1)//2)*x**n/n
def _eval_as_leading_term(self, x, cdir=0):
from sympy import im, re
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
if x0 is S.ComplexInfinity:
return (1/arg).as_leading_term(x)
if cdir != 0:
cdir = arg.dir(x, cdir)
if x0.is_zero:
if re(cdir) < 0:
return self.func(x0) - S.Pi
return self.func(x0)
if re(cdir) > 0 and re(x0).is_zero and im(x0) > S.Zero and im(x0) < S.One:
return self.func(x0) + S.Pi
if re(cdir) < 0 and re(x0).is_zero and im(x0) < S.Zero and im(x0) > S.NegativeOne:
return self.func(x0) - S.Pi
return self.func(x0)
def _eval_nseries(self, x, n, logx, cdir=0): #acot
from sympy import im, re
arg0 = self.args[0].subs(x, 0)
res = Function._eval_nseries(self, x, n=n, logx=logx)
if arg0 is S.ComplexInfinity:
return res
if cdir != 0:
cdir = self.args[0].dir(x, cdir)
if arg0.is_zero:
if re(cdir) < 0:
return res - S.Pi
return res
if re(cdir) > 0 and re(arg0).is_zero and im(arg0) > S.Zero and im(arg0) < S.One:
return res + S.Pi
if re(cdir) < 0 and re(arg0).is_zero and im(arg0) < S.Zero and im(arg0) > S.NegativeOne:
return res - S.Pi
return res
def _eval_aseries(self, n, args0, x, logx):
if args0[0] is S.Infinity:
return (S.Pi/2 - acot(1/self.args[0]))._eval_nseries(x, n, logx)
elif args0[0] is S.NegativeInfinity:
return (S.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))
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)*
(S.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)*(S.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 ``oo``, ``-oo``,
``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 S.Pi
if arg in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
return S.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 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
def _eval_as_leading_term(self, x, cdir=0):
from sympy import I, im, log
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
if x0 == 1:
return sqrt(2)*sqrt((arg - S.One).as_leading_term(x))
if x0.is_zero:
return I*log(arg.as_leading_term(x))
if cdir != 0:
cdir = arg.dir(x, cdir)
if im(cdir) < 0 and x0.is_real and x0 > S.Zero and x0 < S.One:
return -self.func(x0)
elif im(cdir) > 0 and x0.is_real and x0 < S.Zero and x0 > S.NegativeOne:
return 2*S.Pi - self.func(x0)
return self.func(x0)
def _eval_nseries(self, x, n, logx, cdir=0): #asec
from sympy import Dummy, im, O
arg0 = self.args[0].subs(x, 0)
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
if cdir != 0:
cdir = self.args[0].dir(x, cdir)
if im(cdir) < 0 and arg0.is_real and arg0 > S.Zero and arg0 < S.One:
return -res
elif im(cdir) > 0 and arg0.is_real and arg0 < S.Zero and arg0 > S.NegativeOne:
return 2*S.Pi - res
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 S.Pi/2 + S.ImaginaryUnit*log(S.ImaginaryUnit/arg + sqrt(1 - 1/arg**2))
def _eval_rewrite_as_asin(self, arg, **kwargs):
return S.Pi/2 - asin(1/arg)
def _eval_rewrite_as_acos(self, arg, **kwargs):
return acos(1/arg)
def _eval_rewrite_as_atan(self, arg, **kwargs):
return sqrt(arg**2)/arg*(-S.Pi/2 + 2*atan(arg + sqrt(arg**2 - 1)))
def _eval_rewrite_as_acot(self, arg, **kwargs):
return sqrt(arg**2)/arg*(-S.Pi/2 + 2*acot(arg - sqrt(arg**2 - 1)))
def _eval_rewrite_as_acsc(self, arg, **kwargs):
return S.Pi/2 - acsc(arg)
class acsc(InverseTrigonometricFunction):
"""
The inverse cosecant function.
Returns the arc cosecant of x (measured in radians).
Explanation
===========
``acsc(x)`` will evaluate automatically in the cases ``oo``, ``-oo``,
``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 S.Pi/2
elif arg is S.NegativeOne:
return -S.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_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
def _eval_as_leading_term(self, x, cdir=0):
from sympy import I, im, log
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
if x0.is_zero:
return I*log(arg.as_leading_term(x))
if x0 is S.ComplexInfinity:
return arg.as_leading_term(x)
if cdir != 0:
cdir = arg.dir(x, cdir)
if im(cdir) < 0 and x0.is_real and x0 > S.Zero and x0 < S.One:
return S.Pi - self.func(x0)
elif im(cdir) > 0 and x0.is_real and x0 < S.Zero and x0 > S.NegativeOne:
return -S.Pi - self.func(x0)
return self.func(x0)
def _eval_nseries(self, x, n, logx, cdir=0): #acsc
from sympy import Dummy, im, O
arg0 = self.args[0].subs(x, 0)
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
if cdir != 0:
cdir = self.args[0].dir(x, cdir)
if im(cdir) < 0 and arg0.is_real and arg0 > S.Zero and arg0 < S.One:
return S.Pi - res
elif im(cdir) > 0 and arg0.is_real and arg0 < S.Zero and arg0 > S.NegativeOne:
return -S.Pi - res
return res
def _eval_rewrite_as_log(self, arg, **kwargs):
return -S.ImaginaryUnit*log(S.ImaginaryUnit/arg + sqrt(1 - 1/arg**2))
def _eval_rewrite_as_asin(self, arg, **kwargs):
return asin(1/arg)
def _eval_rewrite_as_acos(self, arg, **kwargs):
return S.Pi/2 - acos(1/arg)
def _eval_rewrite_as_atan(self, arg, **kwargs):
return sqrt(arg**2)/arg*(S.Pi/2 - atan(sqrt(arg**2 - 1)))
def _eval_rewrite_as_acot(self, arg, **kwargs):
return sqrt(arg**2)/arg*(S.Pi/2 - acot(1/sqrt(arg**2 - 1)))
def _eval_rewrite_as_asec(self, arg, **kwargs):
return S.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 import Heaviside, im, re
if x is S.NegativeInfinity:
if y.is_zero:
# Special case y = 0 because we define Heaviside(0) = 1/2
return S.Pi
return 2*S.Pi*(Heaviside(re(y))) - S.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) - S.Pi
elif y.is_nonnegative:
return atan(y/x) + S.Pi
elif x.is_zero:
if y.is_positive:
return S.Pi/2
elif y.is_negative:
return -S.Pi/2
elif y.is_zero:
return S.NaN
if y.is_zero:
if x.is_extended_nonzero:
return S.Pi*(S.One - Heaviside(x))
if x.is_number:
return Piecewise((S.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):
from sympy import re
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):
from sympy import arg
if x.is_extended_real and y.is_extended_real:
return arg(x + y*S.ImaginaryUnit)
n = x + S.ImaginaryUnit*y
d = x**2 + y**2
return arg(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)
|
6de6ff6ad3b159cdbd112f2051c36a36ac4e23bddb782bc5a83899b000887a80 | from sympy.core import Function, S, sympify
from sympy.utilities.iterables import sift
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.compatibility import ordered
from sympy.core.operations import LatticeOp, ShortCircuit
from sympy.core.function import (Application, Lambda,
ArgumentIndexError)
from sympy.core.expr import Expr
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.symbol import Dummy
from sympy.core.rules import Transform
from sympy.core.logic import fuzzy_and, fuzzy_or, _torf
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 = []
for j in range(i + 1, len(args)):
c.append(Relational(a, args[j], op))
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)
Traceback (most recent call last):
...
sympy.core.sympify.SympifyError: SympifyError: <function sqrt at 0x10e8900d0>
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
==========
* https://en.wikipedia.org/wiki/Cube_root
* 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
==========
* https://en.wikipedia.org/wiki/Square_root
* https://en.wikipedia.org/wiki/Real_root
* https://en.wikipedia.org/wiki/Root_of_unity
* https://en.wikipedia.org/wiki/Principal_value
* 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):
"""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/odd)`` will be changed to ``-n**(1/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):
evaluate = assumptions.pop('evaluate', True)
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
else:
args = frozenset(args)
if evaluate:
# remove redundant args that are easily identified
args = cls._collapse_arguments(args, **assumptions)
# find local zeros
args = cls._find_localzeros(args, **assumptions)
if not args:
return cls.identity
if len(args) == 1:
return list(args).pop()
# base creation
_args = frozenset(args)
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)))
"""
from sympy.utilities.iterables import ordered
from sympy.simplify.simplify import walk
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 i in range(len(args)):
if not args[i].is_number:
break
if (args[i] < small) == True:
small = args[i]
elif cls == Max:
for i in range(len(args)):
if not args[i].is_number:
break
if (args[i] > big) == True:
big = args[i]
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.
"""
from sympy.core.exprtools import factor_terms
def hit(v, t, f):
if not v.is_Relational:
return t if v else f
for i in range(2):
if x == y:
return True
r = hit(x >= y, Max, Min)
if r is not None:
return r
r = hit(y <= x, Max, Min)
if r is not None:
return r
r = hit(x <= y, Min, Max)
if r is not None:
return r
r = hit(y >= x, Min, Max)
if r is not None:
return r
# 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):
"""
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 >= 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). E.g. `oo`.
In case of it 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 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 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 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 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)
|
72953b69c14bca2f776be81a9e95c0ef13be912ee7ff61117e24046ccb7c47a1 | from sympy.core import Basic, S, Function, diff, Tuple, Dummy
from sympy.core.basic import as_Basic
from sympy.core.numbers import Rational, NumberSymbol
from sympy.core.relational import (Equality, Unequality, Relational,
_canonical)
from sympy.functions.elementary.miscellaneous import Max, Min
from sympy.logic.boolalg import (And, Boolean, distribute_and_over_or,
true, false, Or, ITE, simplify_logic)
from sympy.utilities.iterables import uniq, ordered, product, sift
from sympy.utilities.misc import filldedent, func_name
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 determined 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.
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 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, 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
if options.pop('evaluate', True):
r = cls.eval(*newargs)
else:
r = None
if r is None:
return Basic.__new__(cls, *newargs, **options)
else:
return r
@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
3) 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.
"""
from sympy.functions.elementary.complexes import im, re
if not _args:
return Undefined
if len(_args) == 1 and _args[0][-1] == True:
return _args[0][0]
newargs = [] # the unevaluated conditions
current_cond = set() # the conditions up to a given e, c pair
# make conditions canonical
args = []
for e, c in _args:
if (not c.is_Atom and not isinstance(c, Relational) and
not c.has(im, re)):
free = c.free_symbols
if len(free) == 1:
funcs = [i for i in c.atoms(Function)
if not isinstance(i, Boolean)]
if len(funcs) == 1 and len(
c.xreplace({list(funcs)[0]: Dummy()}
).free_symbols) == 1:
# we can treat function like a symbol
free = funcs
_c = c
x = free.pop()
try:
c = c.as_set().as_relational(x)
except NotImplementedError:
pass
else:
reps = {}
for i in c.atoms(Relational):
ic = i.canonical
if ic.rhs in (S.Infinity, S.NegativeInfinity):
if not _c.has(ic.rhs):
# don't accept introduction of
# new Relationals with +/-oo
reps[i] = S.true
elif ('=' not in ic.rel_op and
c.xreplace({x: i.rhs}) !=
_c.xreplace({x: i.rhs})):
reps[i] = Relational(
i.lhs, i.rhs, i.rel_op + '=')
c = c.xreplace(reps)
args.append((e, _canonical(c)))
for expr, cond in args:
# 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) and
c.negated.canonical in current_cond):
continue
nonredundant.append(c)
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:
newargs[-1] = ExprCondPair(expr, cond)
continue
newargs.append(ExprCondPair(expr, cond))
# 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, 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 piecewise_integrate(self, x, **kwargs):
"""Return the Piecewise with each expression being
replaced with its antiderivative. To obtain a continuous
antiderivative, use the `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
# -----------------------------------------------------------------------
try:
abei = self._intervals(x)
except NotImplementedError:
from sympy 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)
if sum == Undefined:
sum = 0
sum += anti._eval_interval(x, a, x)
# 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
from sympy.core.symbol import Dummy
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
# -----------------------------------------------------------------
try:
abei = self._intervals(x)
except NotImplementedError:
from sympy 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):
"""Return 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 <= b when involving symbols.
If there are any relationals not involving sym, or any
relational cannot be solved for sym, NotImplementedError is
raised. 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
from sympy.logic.boolalg import to_cnf, distribute_or_over_and
assert isinstance(self, Piecewise)
def _solve_relational(r):
if sym not in r.free_symbols:
nonsymfail(r)
rv = _solve_inequality(r, sym)
if isinstance(rv, Relational):
free = rv.args[1].free_symbols
if rv.args[0] != sym or sym in free:
raise NotImplementedError(filldedent('''
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 rv
def nonsymfail(cond):
raise NotImplementedError(filldedent('''
A condition not involving
%s appeared: %s''' % (sym, cond)))
# make self canonical wrt Relationals
reps = {
r: _solve_relational(r) for r in self.atoms(Relational)}
# 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
elif cond is S.true:
default = expr
idefault = i
break
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, Equality)])
elif cond is not S.false:
expr_cond.append((i, expr, cond))
# 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 isinstance(cond2, Equality):
lower = upper # ignore
break
elif isinstance(cond2, Unequality):
l, r = cond2.args
if l == sym:
exclude.append(r)
elif r == sym:
exclude.append(l)
else:
nonsymfail(cond2)
continue
elif cond2.lts == sym:
upper = Min(cond2.gts, upper)
elif cond2.gts == sym:
lower = Max(cond2.lts, lower)
else:
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):
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:
nonsymfail(cond)
else:
raise NotImplementedError(
'unrecognized condition: %s' % cond)
lower, upper = lower, Max(lower, upper)
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 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, Equality):
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, (Equality, Unequality)):
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 import Ne, Eq, Not, 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 = 1
for c in args:
if b1:
k *= 1 - rewrite(c)
else:
k *= rewrite(c)
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):
"""
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.
Examples
========
>>> from sympy import Piecewise, piecewise_fold, sympify as 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
"""
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:
from sympy.utilities.iterables import cartes, sift, common_prefix
# 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 cartes(*[
(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)))
return Piecewise(*new_args)
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 import simplify
args = []
for e, c in expr.args:
if isinstance(e, Basic):
doit = kwargs.pop('doit', None)
# 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 != expr:
e = newe
if isinstance(c, Basic):
c = simplify(c, doit=doit, **kwargs)
args.append((e, c))
return Piecewise(*args)
def piecewise_simplify(expr, **kwargs):
expr = piecewise_simplify_arguments(expr, **kwargs)
if not isinstance(expr, Piecewise):
return expr
args = list(expr.args)
_blessed = lambda e: getattr(e.lhs, '_diff_wrt', False) and (
getattr(e.rhs, '_diff_wrt', None) or
isinstance(e.rhs, (Rational, NumberSymbol)))
for i, (expr, cond) in enumerate(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))
if isinstance(cond, And):
eqs, other = sift(cond.args,
lambda i: isinstance(i, Equality), binary=True)
elif isinstance(cond, Equality):
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)
# 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, Equality), binary=True)
elif isinstance(cond, Equality):
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 Piecewise(*args)
|
58aa912d59577b825e5f16db87c4a66a2f32bb8afa1cdec2bd9366a93e2d0a5b | from sympy.core.logic import FuzzyBool
from sympy.core import S, sympify, cacheit, pi, I, Rational
from sympy.core.add import Add
from sympy.core.function import Function, ArgumentIndexError, _coeff_isneg
from sympy.functions.combinatorial.factorials import factorial, RisingFactorial
from sympy.functions.elementary.exponential import exp, log, match_real_imag
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.integers import floor
from sympy.core.logic import fuzzy_or, fuzzy_and
def _rewrite_hyperbolics_as_exp(expr):
expr = sympify(expr)
return expr.xreplace({h: h.rewrite(exp)
for h in expr.atoms(HyperbolicFunction)})
###############################################################################
########################### HYPERBOLIC FUNCTIONS ##############################
###############################################################################
class HyperbolicFunction(Function):
"""
Base class for hyperbolic functions.
See Also
========
sinh, cosh, tanh, coth
"""
unbranched = True
def _peeloff_ipi(arg):
"""
Split ARG into two parts, a "rest" and a multiple of I*pi/2.
This assumes ARG to be an Add.
The multiple of I*pi returned in the second position is always a Rational.
Examples
========
>>> from sympy.functions.elementary.hyperbolic import _peeloff_ipi as peel
>>> from sympy import pi, I
>>> from sympy.abc import x, y
>>> peel(x + I*pi/2)
(x, I*pi/2)
>>> peel(x + I*2*pi/3 + I*pi*y)
(x + I*pi*y + I*pi/6, I*pi/2)
"""
for a in Add.make_args(arg):
if a == S.Pi*S.ImaginaryUnit:
K = S.One
break
elif a.is_Mul:
K, p = a.as_two_terms()
if p == S.Pi*S.ImaginaryUnit and K.is_Rational:
break
else:
return arg, S.Zero
m1 = (K % S.Half)*S.Pi*S.ImaginaryUnit
m2 = K*S.Pi*S.ImaginaryUnit - m1
return arg - m2, m2
class sinh(HyperbolicFunction):
r"""
sinh(x) is the hyperbolic sine of x.
The hyperbolic sine function is $\frac{e^x - e^{-x}}{2}$.
Examples
========
>>> from sympy import sinh
>>> from sympy.abc import x
>>> sinh(x)
sinh(x)
See Also
========
cosh, tanh, asinh
"""
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
return cosh(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return asinh
@classmethod
def eval(cls, arg):
from sympy import sin
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.NegativeInfinity
elif arg.is_zero:
return S.Zero
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
return S.NaN
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return S.ImaginaryUnit * sin(i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
if arg.is_Add:
x, m = _peeloff_ipi(arg)
if m:
return sinh(m)*cosh(x) + cosh(m)*sinh(x)
if arg.is_zero:
return S.Zero
if arg.func == asinh:
return arg.args[0]
if arg.func == acosh:
x = arg.args[0]
return sqrt(x - 1) * sqrt(x + 1)
if arg.func == atanh:
x = arg.args[0]
return x/sqrt(1 - x**2)
if arg.func == acoth:
x = arg.args[0]
return 1/(sqrt(x - 1) * sqrt(x + 1))
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
"""
Returns the next term in the Taylor series expansion.
"""
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 x**(n) / factorial(n)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
"""
Returns this function as a complex coordinate.
"""
from sympy import cos, sin
if self.args[0].is_extended_real:
if deep:
hints['complex'] = False
return (self.expand(deep, **hints), S.Zero)
else:
return (self, S.Zero)
if deep:
re, im = self.args[0].expand(deep, **hints).as_real_imag()
else:
re, im = self.args[0].as_real_imag()
return (sinh(re)*cos(im), cosh(re)*sin(im))
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 _eval_expand_trig(self, deep=True, **hints):
if deep:
arg = self.args[0].expand(deep, **hints)
else:
arg = self.args[0]
x = None
if arg.is_Add: # TODO, implement more if deep stuff here
x, y = arg.as_two_terms()
else:
coeff, terms = arg.as_coeff_Mul(rational=True)
if coeff is not S.One and coeff.is_Integer and terms is not S.One:
x = terms
y = (coeff - 1)*x
if x is not None:
return (sinh(x)*cosh(y) + sinh(y)*cosh(x)).expand(trig=True)
return sinh(arg)
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
return (exp(arg) - exp(-arg)) / 2
def _eval_rewrite_as_exp(self, arg, **kwargs):
return (exp(arg) - exp(-arg)) / 2
def _eval_rewrite_as_cosh(self, arg, **kwargs):
return -S.ImaginaryUnit*cosh(arg + S.Pi*S.ImaginaryUnit/2)
def _eval_rewrite_as_tanh(self, arg, **kwargs):
tanh_half = tanh(S.Half*arg)
return 2*tanh_half/(1 - tanh_half**2)
def _eval_rewrite_as_coth(self, arg, **kwargs):
coth_half = coth(S.Half*arg)
return 2*coth_half/(coth_half**2 - 1)
def _eval_as_leading_term(self, x, cdir=0):
from sympy import Order
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and Order(1, x).contains(arg):
return arg
else:
return self.func(arg)
def _eval_is_real(self):
arg = self.args[0]
if arg.is_real:
return True
# if `im` is of the form n*pi
# else, check if it is a number
re, im = arg.as_real_imag()
return (im%pi).is_zero
def _eval_is_extended_real(self):
if self.args[0].is_extended_real:
return True
def _eval_is_positive(self):
if self.args[0].is_extended_real:
return self.args[0].is_positive
def _eval_is_negative(self):
if self.args[0].is_extended_real:
return self.args[0].is_negative
def _eval_is_finite(self):
arg = self.args[0]
return arg.is_finite
def _eval_is_zero(self):
arg = self.args[0]
if arg.is_zero:
return True
class cosh(HyperbolicFunction):
r"""
cosh(x) is the hyperbolic cosine of x.
The hyperbolic cosine function is $\frac{e^x + e^{-x}}{2}$.
Examples
========
>>> from sympy import cosh
>>> from sympy.abc import x
>>> cosh(x)
cosh(x)
See Also
========
sinh, tanh, acosh
"""
def fdiff(self, argindex=1):
if argindex == 1:
return sinh(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
from sympy import cos
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.Infinity
elif arg.is_zero:
return S.One
elif arg.is_negative:
return cls(-arg)
else:
if arg is S.ComplexInfinity:
return S.NaN
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return cos(i_coeff)
else:
if _coeff_isneg(arg):
return cls(-arg)
if arg.is_Add:
x, m = _peeloff_ipi(arg)
if m:
return cosh(m)*cosh(x) + sinh(m)*sinh(x)
if arg.is_zero:
return S.One
if arg.func == asinh:
return sqrt(1 + arg.args[0]**2)
if arg.func == acosh:
return arg.args[0]
if arg.func == atanh:
return 1/sqrt(1 - arg.args[0]**2)
if arg.func == acoth:
x = arg.args[0]
return x/(sqrt(x - 1) * sqrt(x + 1))
@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 x**(n)/factorial(n)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
from sympy import cos, sin
if self.args[0].is_extended_real:
if deep:
hints['complex'] = False
return (self.expand(deep, **hints), S.Zero)
else:
return (self, S.Zero)
if deep:
re, im = self.args[0].expand(deep, **hints).as_real_imag()
else:
re, im = self.args[0].as_real_imag()
return (cosh(re)*cos(im), sinh(re)*sin(im))
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 _eval_expand_trig(self, deep=True, **hints):
if deep:
arg = self.args[0].expand(deep, **hints)
else:
arg = self.args[0]
x = None
if arg.is_Add: # TODO, implement more if deep stuff here
x, y = arg.as_two_terms()
else:
coeff, terms = arg.as_coeff_Mul(rational=True)
if coeff is not S.One and coeff.is_Integer and terms is not S.One:
x = terms
y = (coeff - 1)*x
if x is not None:
return (cosh(x)*cosh(y) + sinh(x)*sinh(y)).expand(trig=True)
return cosh(arg)
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
return (exp(arg) + exp(-arg)) / 2
def _eval_rewrite_as_exp(self, arg, **kwargs):
return (exp(arg) + exp(-arg)) / 2
def _eval_rewrite_as_sinh(self, arg, **kwargs):
return -S.ImaginaryUnit*sinh(arg + S.Pi*S.ImaginaryUnit/2)
def _eval_rewrite_as_tanh(self, arg, **kwargs):
tanh_half = tanh(S.Half*arg)**2
return (1 + tanh_half)/(1 - tanh_half)
def _eval_rewrite_as_coth(self, arg, **kwargs):
coth_half = coth(S.Half*arg)**2
return (coth_half + 1)/(coth_half - 1)
def _eval_as_leading_term(self, x, cdir=0):
from sympy import Order
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and Order(1, x).contains(arg):
return S.One
else:
return self.func(arg)
def _eval_is_real(self):
arg = self.args[0]
# `cosh(x)` is real for real OR purely imaginary `x`
if arg.is_real or arg.is_imaginary:
return True
# cosh(a+ib) = cos(b)*cosh(a) + i*sin(b)*sinh(a)
# the imaginary part can be an expression like n*pi
# if not, check if the imaginary part is a number
re, im = arg.as_real_imag()
return (im%pi).is_zero
def _eval_is_positive(self):
# cosh(x+I*y) = cos(y)*cosh(x) + I*sin(y)*sinh(x)
# cosh(z) is positive iff it is real and the real part is positive.
# So we need sin(y)*sinh(x) = 0 which gives x=0 or y=n*pi
# Case 1 (y=n*pi): cosh(z) = (-1)**n * cosh(x) -> positive for n even
# Case 2 (x=0): cosh(z) = cos(y) -> positive when cos(y) is positive
z = self.args[0]
x, y = z.as_real_imag()
ymod = y % (2*pi)
yzero = ymod.is_zero
# shortcut if ymod is zero
if yzero:
return True
xzero = x.is_zero
# shortcut x is not zero
if xzero is False:
return yzero
return fuzzy_or([
# Case 1:
yzero,
# Case 2:
fuzzy_and([
xzero,
fuzzy_or([ymod < pi/2, ymod > 3*pi/2])
])
])
def _eval_is_nonnegative(self):
z = self.args[0]
x, y = z.as_real_imag()
ymod = y % (2*pi)
yzero = ymod.is_zero
# shortcut if ymod is zero
if yzero:
return True
xzero = x.is_zero
# shortcut x is not zero
if xzero is False:
return yzero
return fuzzy_or([
# Case 1:
yzero,
# Case 2:
fuzzy_and([
xzero,
fuzzy_or([ymod <= pi/2, ymod >= 3*pi/2])
])
])
def _eval_is_finite(self):
arg = self.args[0]
return arg.is_finite
class tanh(HyperbolicFunction):
r"""
tanh(x) is the hyperbolic tangent of x.
The hyperbolic tangent function is $\frac{\sinh(x)}{\cosh(x)}$.
Examples
========
>>> from sympy import tanh
>>> from sympy.abc import x
>>> tanh(x)
tanh(x)
See Also
========
sinh, cosh, atanh
"""
def fdiff(self, argindex=1):
if argindex == 1:
return S.One - tanh(self.args[0])**2
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return atanh
@classmethod
def eval(cls, arg):
from sympy import tan
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.One
elif arg is S.NegativeInfinity:
return S.NegativeOne
elif arg.is_zero:
return S.Zero
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
return S.NaN
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
if _coeff_isneg(i_coeff):
return -S.ImaginaryUnit * tan(-i_coeff)
return S.ImaginaryUnit * tan(i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
if arg.is_Add:
x, m = _peeloff_ipi(arg)
if m:
tanhm = tanh(m)
if tanhm is S.ComplexInfinity:
return coth(x)
else: # tanhm == 0
return tanh(x)
if arg.is_zero:
return S.Zero
if arg.func == asinh:
x = arg.args[0]
return x/sqrt(1 + x**2)
if arg.func == acosh:
x = arg.args[0]
return sqrt(x - 1) * sqrt(x + 1) / x
if arg.func == atanh:
return arg.args[0]
if arg.func == acoth:
return 1/arg.args[0]
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
from sympy import bernoulli
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
a = 2**(n + 1)
B = bernoulli(n + 1)
F = factorial(n + 1)
return a*(a - 1) * B/F * x**n
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
from sympy import cos, sin
if self.args[0].is_extended_real:
if deep:
hints['complex'] = False
return (self.expand(deep, **hints), S.Zero)
else:
return (self, S.Zero)
if deep:
re, im = self.args[0].expand(deep, **hints).as_real_imag()
else:
re, im = self.args[0].as_real_imag()
denom = sinh(re)**2 + cos(im)**2
return (sinh(re)*cosh(re)/denom, sin(im)*cos(im)/denom)
def _eval_expand_trig(self, **hints):
arg = self.args[0]
if arg.is_Add:
from sympy import symmetric_poly
n = len(arg.args)
TX = [tanh(x, evaluate=False)._eval_expand_trig()
for x in arg.args]
p = [0, 0] # [den, num]
for i in range(n + 1):
p[i % 2] += symmetric_poly(i, TX)
return p[1]/p[0]
elif arg.is_Mul:
from sympy.functions.combinatorial.numbers import nC
coeff, terms = arg.as_coeff_Mul()
if coeff.is_Integer and coeff > 1:
n = []
d = []
T = tanh(terms)
for k in range(1, coeff + 1, 2):
n.append(nC(range(coeff), k)*T**k)
for k in range(0, coeff + 1, 2):
d.append(nC(range(coeff), k)*T**k)
return Add(*n)/Add(*d)
return tanh(arg)
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
neg_exp, pos_exp = exp(-arg), exp(arg)
return (pos_exp - neg_exp)/(pos_exp + neg_exp)
def _eval_rewrite_as_exp(self, arg, **kwargs):
neg_exp, pos_exp = exp(-arg), exp(arg)
return (pos_exp - neg_exp)/(pos_exp + neg_exp)
def _eval_rewrite_as_sinh(self, arg, **kwargs):
return S.ImaginaryUnit*sinh(arg)/sinh(S.Pi*S.ImaginaryUnit/2 - arg)
def _eval_rewrite_as_cosh(self, arg, **kwargs):
return S.ImaginaryUnit*cosh(S.Pi*S.ImaginaryUnit/2 - arg)/cosh(arg)
def _eval_rewrite_as_coth(self, arg, **kwargs):
return 1/coth(arg)
def _eval_as_leading_term(self, x, cdir=0):
from sympy import Order
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and Order(1, x).contains(arg):
return arg
else:
return self.func(arg)
def _eval_is_real(self):
arg = self.args[0]
if arg.is_real:
return True
re, im = arg.as_real_imag()
# if denom = 0, tanh(arg) = zoo
if re == 0 and im % pi == pi/2:
return None
# check if im is of the form n*pi/2 to make sin(2*im) = 0
# if not, im could be a number, return False in that case
return (im % (pi/2)).is_zero
def _eval_is_extended_real(self):
if self.args[0].is_extended_real:
return True
def _eval_is_positive(self):
if self.args[0].is_extended_real:
return self.args[0].is_positive
def _eval_is_negative(self):
if self.args[0].is_extended_real:
return self.args[0].is_negative
def _eval_is_finite(self):
from sympy import sinh, cos
arg = self.args[0]
re, im = arg.as_real_imag()
denom = cos(im)**2 + sinh(re)**2
if denom == 0:
return False
elif denom.is_number:
return True
if arg.is_extended_real:
return True
def _eval_is_zero(self):
arg = self.args[0]
if arg.is_zero:
return True
class coth(HyperbolicFunction):
r"""
coth(x) is the hyperbolic cotangent of x.
The hyperbolic cotangent function is $\frac{\cosh(x)}{\sinh(x)}$.
Examples
========
>>> from sympy import coth
>>> from sympy.abc import x
>>> coth(x)
coth(x)
See Also
========
sinh, cosh, acoth
"""
def fdiff(self, argindex=1):
if argindex == 1:
return -1/sinh(self.args[0])**2
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return acoth
@classmethod
def eval(cls, arg):
from sympy import cot
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.One
elif arg is S.NegativeInfinity:
return S.NegativeOne
elif arg.is_zero:
return S.ComplexInfinity
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
return S.NaN
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
if _coeff_isneg(i_coeff):
return S.ImaginaryUnit * cot(-i_coeff)
return -S.ImaginaryUnit * cot(i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
if arg.is_Add:
x, m = _peeloff_ipi(arg)
if m:
cothm = coth(m)
if cothm is S.ComplexInfinity:
return coth(x)
else: # cothm == 0
return tanh(x)
if arg.is_zero:
return S.ComplexInfinity
if arg.func == asinh:
x = arg.args[0]
return sqrt(1 + x**2)/x
if arg.func == acosh:
x = arg.args[0]
return x/(sqrt(x - 1) * sqrt(x + 1))
if arg.func == atanh:
return 1/arg.args[0]
if arg.func == acoth:
return arg.args[0]
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
from sympy import bernoulli
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 2**(n + 1) * B/F * x**n
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
from sympy import cos, sin
if self.args[0].is_extended_real:
if deep:
hints['complex'] = False
return (self.expand(deep, **hints), S.Zero)
else:
return (self, S.Zero)
if deep:
re, im = self.args[0].expand(deep, **hints).as_real_imag()
else:
re, im = self.args[0].as_real_imag()
denom = sinh(re)**2 + sin(im)**2
return (sinh(re)*cosh(re)/denom, -sin(im)*cos(im)/denom)
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
neg_exp, pos_exp = exp(-arg), exp(arg)
return (pos_exp + neg_exp)/(pos_exp - neg_exp)
def _eval_rewrite_as_exp(self, arg, **kwargs):
neg_exp, pos_exp = exp(-arg), exp(arg)
return (pos_exp + neg_exp)/(pos_exp - neg_exp)
def _eval_rewrite_as_sinh(self, arg, **kwargs):
return -S.ImaginaryUnit*sinh(S.Pi*S.ImaginaryUnit/2 - arg)/sinh(arg)
def _eval_rewrite_as_cosh(self, arg, **kwargs):
return -S.ImaginaryUnit*cosh(arg)/cosh(S.Pi*S.ImaginaryUnit/2 - arg)
def _eval_rewrite_as_tanh(self, arg, **kwargs):
return 1/tanh(arg)
def _eval_is_positive(self):
if self.args[0].is_extended_real:
return self.args[0].is_positive
def _eval_is_negative(self):
if self.args[0].is_extended_real:
return self.args[0].is_negative
def _eval_as_leading_term(self, x, cdir=0):
from sympy import Order
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and Order(1, x).contains(arg):
return 1/arg
else:
return self.func(arg)
def _eval_expand_trig(self, **hints):
arg = self.args[0]
if arg.is_Add:
from sympy import symmetric_poly
CX = [coth(x, evaluate=False)._eval_expand_trig() for x in arg.args]
p = [[], []]
n = len(arg.args)
for i in range(n, -1, -1):
p[(n - i) % 2].append(symmetric_poly(i, CX))
return Add(*p[0])/Add(*p[1])
elif arg.is_Mul:
from sympy import binomial
coeff, x = arg.as_coeff_Mul(rational=True)
if coeff.is_Integer and coeff > 1:
c = coth(x, evaluate=False)
p = [[], []]
for i in range(coeff, -1, -1):
p[(coeff - i) % 2].append(binomial(coeff, i)*c**i)
return Add(*p[0])/Add(*p[1])
return coth(arg)
class ReciprocalHyperbolicFunction(HyperbolicFunction):
"""Base class for reciprocal functions of hyperbolic functions. """
#To be defined in class
_reciprocal_of = None
_is_even = None # type: FuzzyBool
_is_odd = None # type: FuzzyBool
@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)
t = cls._reciprocal_of.eval(arg)
if hasattr(arg, 'inverse') and arg.inverse() == cls:
return arg.args[0]
return 1/t if t is not None else 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 _eval_rewrite_as_exp(self, arg, **kwargs):
return self._rewrite_reciprocal("_eval_rewrite_as_exp", arg)
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
return self._rewrite_reciprocal("_eval_rewrite_as_tractable", arg)
def _eval_rewrite_as_tanh(self, arg, **kwargs):
return self._rewrite_reciprocal("_eval_rewrite_as_tanh", arg)
def _eval_rewrite_as_coth(self, arg, **kwargs):
return self._rewrite_reciprocal("_eval_rewrite_as_coth", arg)
def as_real_imag(self, deep = True, **hints):
return (1 / self._reciprocal_of(self.args[0])).as_real_imag(deep, **hints)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def _eval_expand_complex(self, deep=True, **hints):
re_part, im_part = self.as_real_imag(deep=True, **hints)
return re_part + S.ImaginaryUnit*im_part
def _eval_expand_trig(self, **hints):
return self._calculate_reciprocal("_eval_expand_trig", **hints)
def _eval_as_leading_term(self, x, cdir=0):
return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x)
def _eval_is_extended_real(self):
return self._reciprocal_of(self.args[0]).is_extended_real
def _eval_is_finite(self):
return (1/self._reciprocal_of(self.args[0])).is_finite
class csch(ReciprocalHyperbolicFunction):
r"""
csch(x) is the hyperbolic cosecant of x.
The hyperbolic cosecant function is $\frac{2}{e^x - e^{-x}}$
Examples
========
>>> from sympy import csch
>>> from sympy.abc import x
>>> csch(x)
csch(x)
See Also
========
sinh, cosh, tanh, sech, asinh, acosh
"""
_reciprocal_of = sinh
_is_odd = True
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function
"""
if argindex == 1:
return -coth(self.args[0]) * csch(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
"""
Returns the next term in the Taylor series expansion
"""
from sympy import bernoulli
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 2 * (1 - 2**n) * B/F * x**n
def _eval_rewrite_as_cosh(self, arg, **kwargs):
return S.ImaginaryUnit / cosh(arg + S.ImaginaryUnit * S.Pi / 2)
def _eval_is_positive(self):
if self.args[0].is_extended_real:
return self.args[0].is_positive
def _eval_is_negative(self):
if self.args[0].is_extended_real:
return self.args[0].is_negative
def _sage_(self):
import sage.all as sage
return sage.csch(self.args[0]._sage_())
class sech(ReciprocalHyperbolicFunction):
r"""
sech(x) is the hyperbolic secant of x.
The hyperbolic secant function is $\frac{2}{e^x + e^{-x}}$
Examples
========
>>> from sympy import sech
>>> from sympy.abc import x
>>> sech(x)
sech(x)
See Also
========
sinh, cosh, tanh, coth, csch, asinh, acosh
"""
_reciprocal_of = cosh
_is_even = True
def fdiff(self, argindex=1):
if argindex == 1:
return - tanh(self.args[0])*sech(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
from sympy.functions.combinatorial.numbers import euler
if n < 0 or n % 2 == 1:
return S.Zero
else:
x = sympify(x)
return euler(n) / factorial(n) * x**(n)
def _eval_rewrite_as_sinh(self, arg, **kwargs):
return S.ImaginaryUnit / sinh(arg + S.ImaginaryUnit * S.Pi /2)
def _eval_is_positive(self):
if self.args[0].is_extended_real:
return True
def _sage_(self):
import sage.all as sage
return sage.sech(self.args[0]._sage_())
###############################################################################
############################# HYPERBOLIC INVERSES #############################
###############################################################################
class InverseHyperbolicFunction(Function):
"""Base class for inverse hyperbolic functions."""
pass
class asinh(InverseHyperbolicFunction):
"""
asinh(x) is the inverse hyperbolic sine of x.
The inverse hyperbolic sine function.
Examples
========
>>> from sympy import asinh
>>> from sympy.abc import x
>>> asinh(x).diff(x)
1/sqrt(x**2 + 1)
>>> asinh(1)
log(1 + sqrt(2))
See Also
========
acosh, atanh, sinh
"""
def fdiff(self, argindex=1):
if argindex == 1:
return 1/sqrt(self.args[0]**2 + 1)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
from sympy import asin
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.NegativeInfinity
elif arg.is_zero:
return S.Zero
elif arg is S.One:
return log(sqrt(2) + 1)
elif arg is S.NegativeOne:
return log(sqrt(2) - 1)
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
return S.ComplexInfinity
if arg.is_zero:
return S.Zero
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return S.ImaginaryUnit * asin(i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
if isinstance(arg, sinh) and arg.args[0].is_number:
z = arg.args[0]
if z.is_real:
return z
r, i = match_real_imag(z)
if r is not None and i is not None:
f = floor((i + pi/2)/pi)
m = z - I*pi*f
even = f.is_even
if even is True:
return m
elif even is False:
return -m
@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 (-1)**k * R / F * x**n / n
def _eval_as_leading_term(self, x, cdir=0):
from sympy import Order
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and Order(1, x).contains(arg):
return arg
else:
return self.func(arg)
def _eval_rewrite_as_log(self, x, **kwargs):
return log(x + sqrt(x**2 + 1))
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return sinh
def _eval_is_zero(self):
arg = self.args[0]
if arg.is_zero:
return True
class acosh(InverseHyperbolicFunction):
"""
acosh(x) is the inverse hyperbolic cosine of x.
The inverse hyperbolic cosine function.
Examples
========
>>> from sympy import acosh
>>> from sympy.abc import x
>>> acosh(x).diff(x)
1/sqrt(x**2 - 1)
>>> acosh(1)
0
See Also
========
asinh, atanh, cosh
"""
def fdiff(self, argindex=1):
if argindex == 1:
return 1/sqrt(self.args[0]**2 - 1)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.Infinity
elif arg.is_zero:
return S.Pi*S.ImaginaryUnit / 2
elif arg is S.One:
return S.Zero
elif arg is S.NegativeOne:
return S.Pi*S.ImaginaryUnit
if arg.is_number:
cst_table = {
S.ImaginaryUnit: log(S.ImaginaryUnit*(1 + sqrt(2))),
-S.ImaginaryUnit: log(-S.ImaginaryUnit*(1 + sqrt(2))),
S.Half: S.Pi/3,
Rational(-1, 2): S.Pi*Rational(2, 3),
sqrt(2)/2: S.Pi/4,
-sqrt(2)/2: S.Pi*Rational(3, 4),
1/sqrt(2): S.Pi/4,
-1/sqrt(2): S.Pi*Rational(3, 4),
sqrt(3)/2: S.Pi/6,
-sqrt(3)/2: S.Pi*Rational(5, 6),
(sqrt(3) - 1)/sqrt(2**3): S.Pi*Rational(5, 12),
-(sqrt(3) - 1)/sqrt(2**3): S.Pi*Rational(7, 12),
sqrt(2 + sqrt(2))/2: S.Pi/8,
-sqrt(2 + sqrt(2))/2: S.Pi*Rational(7, 8),
sqrt(2 - sqrt(2))/2: S.Pi*Rational(3, 8),
-sqrt(2 - sqrt(2))/2: S.Pi*Rational(5, 8),
(1 + sqrt(3))/(2*sqrt(2)): S.Pi/12,
-(1 + sqrt(3))/(2*sqrt(2)): S.Pi*Rational(11, 12),
(sqrt(5) + 1)/4: S.Pi/5,
-(sqrt(5) + 1)/4: S.Pi*Rational(4, 5)
}
if arg in cst_table:
if arg.is_extended_real:
return cst_table[arg]*S.ImaginaryUnit
return cst_table[arg]
if arg is S.ComplexInfinity:
return S.ComplexInfinity
if arg == S.ImaginaryUnit*S.Infinity:
return S.Infinity + S.ImaginaryUnit*S.Pi/2
if arg == -S.ImaginaryUnit*S.Infinity:
return S.Infinity - S.ImaginaryUnit*S.Pi/2
if arg.is_zero:
return S.Pi*S.ImaginaryUnit*S.Half
if isinstance(arg, cosh) and arg.args[0].is_number:
z = arg.args[0]
if z.is_real:
from sympy.functions.elementary.complexes import Abs
return Abs(z)
r, i = match_real_imag(z)
if r is not None and i is not None:
f = floor(i/pi)
m = z - I*pi*f
even = f.is_even
if even is True:
if r.is_nonnegative:
return m
elif r.is_negative:
return -m
elif even is False:
m -= I*pi
if r.is_nonpositive:
return -m
elif r.is_positive:
return m
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n == 0:
return S.Pi*S.ImaginaryUnit / 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 * S.ImaginaryUnit * x**n / n
def _eval_as_leading_term(self, x, cdir=0):
from sympy import Order
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and Order(1, x).contains(arg):
return S.ImaginaryUnit*S.Pi/2
else:
return self.func(arg)
def _eval_rewrite_as_log(self, x, **kwargs):
return log(x + sqrt(x + 1) * sqrt(x - 1))
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return cosh
class atanh(InverseHyperbolicFunction):
"""
atanh(x) is the inverse hyperbolic tangent of x.
The inverse hyperbolic tangent function.
Examples
========
>>> from sympy import atanh
>>> from sympy.abc import x
>>> atanh(x).diff(x)
1/(1 - x**2)
See Also
========
asinh, acosh, tanh
"""
def fdiff(self, argindex=1):
if argindex == 1:
return 1/(1 - self.args[0]**2)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
from sympy import atan
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg.is_zero:
return S.Zero
elif arg is S.One:
return S.Infinity
elif arg is S.NegativeOne:
return S.NegativeInfinity
elif arg is S.Infinity:
return -S.ImaginaryUnit * atan(arg)
elif arg is S.NegativeInfinity:
return S.ImaginaryUnit * atan(-arg)
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
from sympy.calculus.util import AccumBounds
return S.ImaginaryUnit*AccumBounds(-S.Pi/2, S.Pi/2)
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return S.ImaginaryUnit * atan(i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
if arg.is_zero:
return S.Zero
if isinstance(arg, tanh) and arg.args[0].is_number:
z = arg.args[0]
if z.is_real:
return z
r, i = match_real_imag(z)
if r is not None and i is not None:
f = floor(2*i/pi)
even = f.is_even
m = z - I*f*pi/2
if even is True:
return m
elif even is False:
return m - I*pi/2
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
return x**n / n
def _eval_as_leading_term(self, x, cdir=0):
from sympy import Order
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and Order(1, x).contains(arg):
return arg
else:
return self.func(arg)
def _eval_rewrite_as_log(self, x, **kwargs):
return (log(1 + x) - log(1 - x)) / 2
def _eval_is_zero(self):
arg = self.args[0]
if arg.is_zero:
return True
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return tanh
class acoth(InverseHyperbolicFunction):
"""
acoth(x) is the inverse hyperbolic cotangent of x.
The inverse hyperbolic cotangent function.
Examples
========
>>> from sympy import acoth
>>> from sympy.abc import x
>>> acoth(x).diff(x)
1/(1 - x**2)
See Also
========
asinh, acosh, coth
"""
def fdiff(self, argindex=1):
if argindex == 1:
return 1/(1 - self.args[0]**2)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
from sympy import acot
arg = sympify(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 S.Pi*S.ImaginaryUnit / 2
elif arg is S.One:
return S.Infinity
elif arg is S.NegativeOne:
return S.NegativeInfinity
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
return S.Zero
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return -S.ImaginaryUnit * acot(i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
if arg.is_zero:
return S.Pi*S.ImaginaryUnit*S.Half
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n == 0:
return S.Pi*S.ImaginaryUnit / 2
elif n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
return x**n / n
def _eval_as_leading_term(self, x, cdir=0):
from sympy import Order
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and Order(1, x).contains(arg):
return S.ImaginaryUnit*S.Pi/2
else:
return self.func(arg)
def _eval_rewrite_as_log(self, x, **kwargs):
return (log(1 + 1/x) - log(1 - 1/x)) / 2
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return coth
class asech(InverseHyperbolicFunction):
"""
asech(x) is the inverse hyperbolic secant of x.
The inverse hyperbolic secant function.
Examples
========
>>> from sympy import asech, sqrt, S
>>> from sympy.abc import x
>>> asech(x).diff(x)
-1/(x*sqrt(1 - x**2))
>>> asech(1).diff(x)
0
>>> asech(1)
0
>>> asech(S(2))
I*pi/3
>>> asech(-sqrt(2))
3*I*pi/4
>>> asech((sqrt(6) - sqrt(2)))
I*pi/12
See Also
========
asinh, atanh, cosh, acoth
References
==========
.. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
.. [2] http://dlmf.nist.gov/4.37
.. [3] http://functions.wolfram.com/ElementaryFunctions/ArcSech/
"""
def fdiff(self, argindex=1):
if argindex == 1:
z = self.args[0]
return -1/(z*sqrt(1 - z**2))
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Pi*S.ImaginaryUnit / 2
elif arg is S.NegativeInfinity:
return S.Pi*S.ImaginaryUnit / 2
elif arg.is_zero:
return S.Infinity
elif arg is S.One:
return S.Zero
elif arg is S.NegativeOne:
return S.Pi*S.ImaginaryUnit
if arg.is_number:
cst_table = {
S.ImaginaryUnit: - (S.Pi*S.ImaginaryUnit / 2) + log(1 + sqrt(2)),
-S.ImaginaryUnit: (S.Pi*S.ImaginaryUnit / 2) + log(1 + sqrt(2)),
(sqrt(6) - sqrt(2)): S.Pi / 12,
(sqrt(2) - sqrt(6)): 11*S.Pi / 12,
sqrt(2 - 2/sqrt(5)): S.Pi / 10,
-sqrt(2 - 2/sqrt(5)): 9*S.Pi / 10,
2 / sqrt(2 + sqrt(2)): S.Pi / 8,
-2 / sqrt(2 + sqrt(2)): 7*S.Pi / 8,
2 / sqrt(3): S.Pi / 6,
-2 / sqrt(3): 5*S.Pi / 6,
(sqrt(5) - 1): S.Pi / 5,
(1 - sqrt(5)): 4*S.Pi / 5,
sqrt(2): S.Pi / 4,
-sqrt(2): 3*S.Pi / 4,
sqrt(2 + 2/sqrt(5)): 3*S.Pi / 10,
-sqrt(2 + 2/sqrt(5)): 7*S.Pi / 10,
S(2): S.Pi / 3,
-S(2): 2*S.Pi / 3,
sqrt(2*(2 + sqrt(2))): 3*S.Pi / 8,
-sqrt(2*(2 + sqrt(2))): 5*S.Pi / 8,
(1 + sqrt(5)): 2*S.Pi / 5,
(-1 - sqrt(5)): 3*S.Pi / 5,
(sqrt(6) + sqrt(2)): 5*S.Pi / 12,
(-sqrt(6) - sqrt(2)): 7*S.Pi / 12,
}
if arg in cst_table:
if arg.is_extended_real:
return cst_table[arg]*S.ImaginaryUnit
return cst_table[arg]
if arg is S.ComplexInfinity:
from sympy.calculus.util import AccumBounds
return S.ImaginaryUnit*AccumBounds(-S.Pi/2, S.Pi/2)
if arg.is_zero:
return S.Infinity
@staticmethod
@cacheit
def expansion_term(n, x, *previous_terms):
if n == 0:
return 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)**2 // (n // 2)**2 * x**2 / 4
else:
k = n // 2
R = RisingFactorial(S.Half , k) * n
F = factorial(k) * n // 2 * n // 2
return -1 * R / F * x**n / 4
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return sech
def _eval_rewrite_as_log(self, arg, **kwargs):
return log(1/arg + sqrt(1/arg - 1) * sqrt(1/arg + 1))
class acsch(InverseHyperbolicFunction):
"""
acsch(x) is the inverse hyperbolic cosecant of x.
The inverse hyperbolic cosecant function.
Examples
========
>>> from sympy import acsch, sqrt, S
>>> from sympy.abc import x
>>> acsch(x).diff(x)
-1/(x**2*sqrt(1 + x**(-2)))
>>> acsch(1).diff(x)
0
>>> acsch(1)
log(1 + sqrt(2))
>>> acsch(S.ImaginaryUnit)
-I*pi/2
>>> acsch(-2*S.ImaginaryUnit)
I*pi/6
>>> acsch(S.ImaginaryUnit*(sqrt(6) - sqrt(2)))
-5*I*pi/12
See Also
========
asinh
References
==========
.. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
.. [2] http://dlmf.nist.gov/4.37
.. [3] http://functions.wolfram.com/ElementaryFunctions/ArcCsch/
"""
def fdiff(self, argindex=1):
if argindex == 1:
z = self.args[0]
return -1/(z**2*sqrt(1 + 1/z**2))
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
arg = sympify(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 S.ComplexInfinity
elif arg is S.One:
return log(1 + sqrt(2))
elif arg is S.NegativeOne:
return - log(1 + sqrt(2))
if arg.is_number:
cst_table = {
S.ImaginaryUnit: -S.Pi / 2,
S.ImaginaryUnit*(sqrt(2) + sqrt(6)): -S.Pi / 12,
S.ImaginaryUnit*(1 + sqrt(5)): -S.Pi / 10,
S.ImaginaryUnit*2 / sqrt(2 - sqrt(2)): -S.Pi / 8,
S.ImaginaryUnit*2: -S.Pi / 6,
S.ImaginaryUnit*sqrt(2 + 2/sqrt(5)): -S.Pi / 5,
S.ImaginaryUnit*sqrt(2): -S.Pi / 4,
S.ImaginaryUnit*(sqrt(5)-1): -3*S.Pi / 10,
S.ImaginaryUnit*2 / sqrt(3): -S.Pi / 3,
S.ImaginaryUnit*2 / sqrt(2 + sqrt(2)): -3*S.Pi / 8,
S.ImaginaryUnit*sqrt(2 - 2/sqrt(5)): -2*S.Pi / 5,
S.ImaginaryUnit*(sqrt(6) - sqrt(2)): -5*S.Pi / 12,
S(2): -S.ImaginaryUnit*log((1+sqrt(5))/2),
}
if arg in cst_table:
return cst_table[arg]*S.ImaginaryUnit
if arg is S.ComplexInfinity:
return S.Zero
if arg.is_zero:
return S.ComplexInfinity
if _coeff_isneg(arg):
return -cls(-arg)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return csch
def _eval_rewrite_as_log(self, arg, **kwargs):
return log(1/arg + sqrt(1/arg**2 + 1))
|
a05b6f03933a41428a9007199a637d3902c975632ce77e36af5d63eb84d34497 | from sympy.core import S, Add, Mul, sympify, Symbol, Dummy, Basic
from sympy.core.expr import Expr
from sympy.core.exprtools import factor_terms
from sympy.core.function import (Function, Derivative, ArgumentIndexError,
AppliedUndef)
from sympy.core.logic import fuzzy_not, fuzzy_or
from sympy.core.numbers import pi, I, oo
from sympy.core.relational import Eq
from sympy.functions.elementary.exponential import exp, exp_polar, log
from sympy.functions.elementary.integers import ceiling
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import atan, atan2
###############################################################################
######################### REAL and IMAGINARY PARTS ############################
###############################################################################
class re(Function):
"""
Returns real part of expression. This function performs only
elementary analysis and so it will fail to decompose properly
more complicated expressions. If completely simplified result
is needed then use Basic.as_real_imag() or perform complex
expansion on instance of this function.
Examples
========
>>> from sympy import re, im, I, E, symbols
>>> x, y = symbols('x y', real=True)
>>> re(2*E)
2*E
>>> re(2*I + 17)
17
>>> re(2*I)
0
>>> re(im(x) + x*I + 2)
2
>>> re(5 + I + 2)
7
Parameters
==========
arg : Expr
Real or complex expression.
Returns
=======
expr : Expr
Real part of expression.
See Also
========
im
"""
is_extended_real = True
unbranched = True # implicitly works on the projection to C
_singularities = True # non-holomorphic
@classmethod
def eval(cls, arg):
if arg is S.NaN:
return S.NaN
elif arg is S.ComplexInfinity:
return S.NaN
elif arg.is_extended_real:
return arg
elif arg.is_imaginary or (S.ImaginaryUnit*arg).is_extended_real:
return S.Zero
elif arg.is_Matrix:
return arg.as_real_imag()[0]
elif arg.is_Function and isinstance(arg, conjugate):
return re(arg.args[0])
else:
included, reverted, excluded = [], [], []
args = Add.make_args(arg)
for term in args:
coeff = term.as_coefficient(S.ImaginaryUnit)
if coeff is not None:
if not coeff.is_extended_real:
reverted.append(coeff)
elif not term.has(S.ImaginaryUnit) and term.is_extended_real:
excluded.append(term)
else:
# Try to do some advanced expansion. If
# impossible, don't try to do re(arg) again
# (because this is what we are trying to do now).
real_imag = term.as_real_imag(ignore=arg)
if real_imag:
excluded.append(real_imag[0])
else:
included.append(term)
if len(args) != len(included):
a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
return cls(a) - im(b) + c
def as_real_imag(self, deep=True, **hints):
"""
Returns the real number with a zero imaginary part.
"""
return (self, S.Zero)
def _eval_derivative(self, x):
if x.is_extended_real or self.args[0].is_extended_real:
return re(Derivative(self.args[0], x, evaluate=True))
if x.is_imaginary or self.args[0].is_imaginary:
return -S.ImaginaryUnit \
* im(Derivative(self.args[0], x, evaluate=True))
def _eval_rewrite_as_im(self, arg, **kwargs):
return self.args[0] - S.ImaginaryUnit*im(self.args[0])
def _eval_is_algebraic(self):
return self.args[0].is_algebraic
def _eval_is_zero(self):
# is_imaginary implies nonzero
return fuzzy_or([self.args[0].is_imaginary, self.args[0].is_zero])
def _eval_is_finite(self):
if self.args[0].is_finite:
return True
def _eval_is_complex(self):
if self.args[0].is_finite:
return True
def _sage_(self):
import sage.all as sage
return sage.real_part(self.args[0]._sage_())
class im(Function):
"""
Returns imaginary part of expression. This function performs only
elementary analysis and so it will fail to decompose properly more
complicated expressions. If completely simplified result is needed then
use Basic.as_real_imag() or perform complex expansion on instance of
this function.
Examples
========
>>> from sympy import re, im, E, I
>>> from sympy.abc import x, y
>>> im(2*E)
0
>>> im(2*I + 17)
2
>>> im(x*I)
re(x)
>>> im(re(x) + y)
im(y)
>>> im(2 + 3*I)
3
Parameters
==========
arg : Expr
Real or complex expression.
Returns
=======
expr : Expr
Imaginary part of expression.
See Also
========
re
"""
is_extended_real = True
unbranched = True # implicitly works on the projection to C
_singularities = True # non-holomorphic
@classmethod
def eval(cls, arg):
if arg is S.NaN:
return S.NaN
elif arg is S.ComplexInfinity:
return S.NaN
elif arg.is_extended_real:
return S.Zero
elif arg.is_imaginary or (S.ImaginaryUnit*arg).is_extended_real:
return -S.ImaginaryUnit * arg
elif arg.is_Matrix:
return arg.as_real_imag()[1]
elif arg.is_Function and isinstance(arg, conjugate):
return -im(arg.args[0])
else:
included, reverted, excluded = [], [], []
args = Add.make_args(arg)
for term in args:
coeff = term.as_coefficient(S.ImaginaryUnit)
if coeff is not None:
if not coeff.is_extended_real:
reverted.append(coeff)
else:
excluded.append(coeff)
elif term.has(S.ImaginaryUnit) or not term.is_extended_real:
# Try to do some advanced expansion. If
# impossible, don't try to do im(arg) again
# (because this is what we are trying to do now).
real_imag = term.as_real_imag(ignore=arg)
if real_imag:
excluded.append(real_imag[1])
else:
included.append(term)
if len(args) != len(included):
a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
return cls(a) + re(b) + c
def as_real_imag(self, deep=True, **hints):
"""
Return the imaginary part with a zero real part.
"""
return (self, S.Zero)
def _eval_derivative(self, x):
if x.is_extended_real or self.args[0].is_extended_real:
return im(Derivative(self.args[0], x, evaluate=True))
if x.is_imaginary or self.args[0].is_imaginary:
return -S.ImaginaryUnit \
* re(Derivative(self.args[0], x, evaluate=True))
def _sage_(self):
import sage.all as sage
return sage.imag_part(self.args[0]._sage_())
def _eval_rewrite_as_re(self, arg, **kwargs):
return -S.ImaginaryUnit*(self.args[0] - re(self.args[0]))
def _eval_is_algebraic(self):
return self.args[0].is_algebraic
def _eval_is_zero(self):
return self.args[0].is_extended_real
def _eval_is_finite(self):
if self.args[0].is_finite:
return True
def _eval_is_complex(self):
if self.args[0].is_finite:
return True
###############################################################################
############### SIGN, ABSOLUTE VALUE, ARGUMENT and CONJUGATION ################
###############################################################################
class sign(Function):
"""
Returns the complex sign of an expression:
Explanation
===========
If the expression is real the sign will be:
* 1 if expression is positive
* 0 if expression is equal to zero
* -1 if expression is negative
If the expression is imaginary the sign will be:
* I if im(expression) is positive
* -I if im(expression) is negative
Otherwise an unevaluated expression will be returned. When evaluated, the
result (in general) will be ``cos(arg(expr)) + I*sin(arg(expr))``.
Examples
========
>>> from sympy.functions import sign
>>> from sympy.core.numbers import I
>>> sign(-1)
-1
>>> sign(0)
0
>>> sign(-3*I)
-I
>>> sign(1 + I)
sign(1 + I)
>>> _.evalf()
0.707106781186548 + 0.707106781186548*I
Parameters
==========
arg : Expr
Real or imaginary expression.
Returns
=======
expr : Expr
Complex sign of expression.
See Also
========
Abs, conjugate
"""
is_complex = True
_singularities = True
def doit(self, **hints):
if self.args[0].is_zero is False:
return self.args[0] / Abs(self.args[0])
return self
@classmethod
def eval(cls, arg):
# handle what we can
if arg.is_Mul:
c, args = arg.as_coeff_mul()
unk = []
s = sign(c)
for a in args:
if a.is_extended_negative:
s = -s
elif a.is_extended_positive:
pass
else:
if a.is_imaginary:
ai = im(a)
if ai.is_comparable: # i.e. a = I*real
s *= S.ImaginaryUnit
if ai.is_extended_negative:
# can't use sign(ai) here since ai might not be
# a Number
s = -s
else:
unk.append(a)
else:
unk.append(a)
if c is S.One and len(unk) == len(args):
return None
return s * cls(arg._new_rawargs(*unk))
if arg is S.NaN:
return S.NaN
if arg.is_zero: # it may be an Expr that is zero
return S.Zero
if arg.is_extended_positive:
return S.One
if arg.is_extended_negative:
return S.NegativeOne
if arg.is_Function:
if isinstance(arg, sign):
return arg
if arg.is_imaginary:
if arg.is_Pow and arg.exp is S.Half:
# we catch this because non-trivial sqrt args are not expanded
# e.g. sqrt(1-sqrt(2)) --x--> to I*sqrt(sqrt(2) - 1)
return S.ImaginaryUnit
arg2 = -S.ImaginaryUnit * arg
if arg2.is_extended_positive:
return S.ImaginaryUnit
if arg2.is_extended_negative:
return -S.ImaginaryUnit
def _eval_Abs(self):
if fuzzy_not(self.args[0].is_zero):
return S.One
def _eval_conjugate(self):
return sign(conjugate(self.args[0]))
def _eval_derivative(self, x):
if self.args[0].is_extended_real:
from sympy.functions.special.delta_functions import DiracDelta
return 2 * Derivative(self.args[0], x, evaluate=True) \
* DiracDelta(self.args[0])
elif self.args[0].is_imaginary:
from sympy.functions.special.delta_functions import DiracDelta
return 2 * Derivative(self.args[0], x, evaluate=True) \
* DiracDelta(-S.ImaginaryUnit * self.args[0])
def _eval_is_nonnegative(self):
if self.args[0].is_nonnegative:
return True
def _eval_is_nonpositive(self):
if self.args[0].is_nonpositive:
return True
def _eval_is_imaginary(self):
return self.args[0].is_imaginary
def _eval_is_integer(self):
return self.args[0].is_extended_real
def _eval_is_zero(self):
return self.args[0].is_zero
def _eval_power(self, other):
if (
fuzzy_not(self.args[0].is_zero) and
other.is_integer and
other.is_even
):
return S.One
def _eval_nseries(self, x, n, logx, cdir=0):
arg0 = self.args[0]
x0 = arg0.subs(x, 0)
if x0 != 0:
return self.func(x0)
if cdir != 0:
cdir = arg0.dir(x, cdir)
return -S.One if re(cdir) < 0 else S.One
def _sage_(self):
import sage.all as sage
return sage.sgn(self.args[0]._sage_())
def _eval_rewrite_as_Piecewise(self, arg, **kwargs):
if arg.is_extended_real:
return Piecewise((1, arg > 0), (-1, arg < 0), (0, True))
def _eval_rewrite_as_Heaviside(self, arg, **kwargs):
from sympy.functions.special.delta_functions import Heaviside
if arg.is_extended_real:
return Heaviside(arg) * 2 - 1
def _eval_rewrite_as_Abs(self, arg, **kwargs):
return Piecewise((0, Eq(arg, 0)), (arg / Abs(arg), True))
def _eval_simplify(self, **kwargs):
return self.func(factor_terms(self.args[0])) # XXX include doit?
class Abs(Function):
"""
Return the absolute value of the argument.
Explanation
===========
This is an extension of the built-in function abs() to accept symbolic
values. If you pass a SymPy expression to the built-in abs(), it will
pass it automatically to Abs().
Examples
========
>>> from sympy import Abs, Symbol, S, I
>>> Abs(-1)
1
>>> x = Symbol('x', real=True)
>>> Abs(-x)
Abs(x)
>>> Abs(x**2)
x**2
>>> abs(-x) # The Python built-in
Abs(x)
>>> Abs(3*x + 2*I)
sqrt(9*x**2 + 4)
>>> Abs(8*I)
8
Note that the Python built-in will return either an Expr or int depending on
the argument::
>>> type(abs(-1))
<... 'int'>
>>> type(abs(S.NegativeOne))
<class 'sympy.core.numbers.One'>
Abs will always return a sympy object.
Parameters
==========
arg : Expr
Real or complex expression.
Returns
=======
expr : Expr
Absolute value returned can be an expression or integer depending on
input arg.
See Also
========
sign, conjugate
"""
is_extended_real = True
is_extended_negative = False
is_extended_nonnegative = True
unbranched = True
_singularities = True # non-holomorphic
def fdiff(self, argindex=1):
"""
Get the first derivative of the argument to Abs().
"""
if argindex == 1:
return sign(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
from sympy.simplify.simplify import signsimp
from sympy.core.function import expand_mul
from sympy.core.power import Pow
if hasattr(arg, '_eval_Abs'):
obj = arg._eval_Abs()
if obj is not None:
return obj
if not isinstance(arg, Expr):
raise TypeError("Bad argument type for Abs(): %s" % type(arg))
# handle what we can
arg = signsimp(arg, evaluate=False)
n, d = arg.as_numer_denom()
if d.free_symbols and not n.free_symbols:
return cls(n)/cls(d)
if arg.is_Mul:
known = []
unk = []
for t in arg.args:
if t.is_Pow and t.exp.is_integer and t.exp.is_negative:
bnew = cls(t.base)
if isinstance(bnew, cls):
unk.append(t)
else:
known.append(Pow(bnew, t.exp))
else:
tnew = cls(t)
if isinstance(tnew, cls):
unk.append(t)
else:
known.append(tnew)
known = Mul(*known)
unk = cls(Mul(*unk), evaluate=False) if unk else S.One
return known*unk
if arg is S.NaN:
return S.NaN
if arg is S.ComplexInfinity:
return S.Infinity
if arg.is_Pow:
base, exponent = arg.as_base_exp()
if base.is_extended_real:
if exponent.is_integer:
if exponent.is_even:
return arg
if base is S.NegativeOne:
return S.One
return Abs(base)**exponent
if base.is_extended_nonnegative:
return base**re(exponent)
if base.is_extended_negative:
return (-base)**re(exponent)*exp(-S.Pi*im(exponent))
return
elif not base.has(Symbol): # complex base
# express base**exponent as exp(exponent*log(base))
a, b = log(base).as_real_imag()
z = a + I*b
return exp(re(exponent*z))
if isinstance(arg, exp):
return exp(re(arg.args[0]))
if isinstance(arg, AppliedUndef):
if arg.is_positive:
return arg
elif arg.is_negative:
return -arg
return
if arg.is_Add and arg.has(S.Infinity, S.NegativeInfinity):
if any(a.is_infinite for a in arg.as_real_imag()):
return S.Infinity
if arg.is_zero:
return S.Zero
if arg.is_extended_nonnegative:
return arg
if arg.is_extended_nonpositive:
return -arg
if arg.is_imaginary:
arg2 = -S.ImaginaryUnit * arg
if arg2.is_extended_nonnegative:
return arg2
# reject result if all new conjugates are just wrappers around
# an expression that was already in the arg
conj = signsimp(arg.conjugate(), evaluate=False)
new_conj = conj.atoms(conjugate) - arg.atoms(conjugate)
if new_conj and all(arg.has(i.args[0]) for i in new_conj):
return
if arg != conj and arg != -conj:
ignore = arg.atoms(Abs)
abs_free_arg = arg.xreplace({i: Dummy(real=True) for i in ignore})
unk = [a for a in abs_free_arg.free_symbols if a.is_extended_real is None]
if not unk or not all(conj.has(conjugate(u)) for u in unk):
return sqrt(expand_mul(arg*conj))
def _eval_is_real(self):
if self.args[0].is_finite:
return True
def _eval_is_integer(self):
if self.args[0].is_extended_real:
return self.args[0].is_integer
def _eval_is_extended_nonzero(self):
return fuzzy_not(self._args[0].is_zero)
def _eval_is_zero(self):
return self._args[0].is_zero
def _eval_is_extended_positive(self):
is_z = self.is_zero
if is_z is not None:
return not is_z
def _eval_is_rational(self):
if self.args[0].is_extended_real:
return self.args[0].is_rational
def _eval_is_even(self):
if self.args[0].is_extended_real:
return self.args[0].is_even
def _eval_is_odd(self):
if self.args[0].is_extended_real:
return self.args[0].is_odd
def _eval_is_algebraic(self):
return self.args[0].is_algebraic
def _eval_power(self, exponent):
if self.args[0].is_extended_real and exponent.is_integer:
if exponent.is_even:
return self.args[0]**exponent
elif exponent is not S.NegativeOne and exponent.is_Integer:
return self.args[0]**(exponent - 1)*self
return
def _eval_nseries(self, x, n, logx, cdir=0):
direction = self.args[0].leadterm(x)[0]
if direction.has(log(x)):
direction = direction.subs(log(x), logx)
s = self.args[0]._eval_nseries(x, n=n, logx=logx)
return (sign(direction)*s).expand()
def _sage_(self):
import sage.all as sage
return sage.abs_symbolic(self.args[0]._sage_())
def _eval_derivative(self, x):
if self.args[0].is_extended_real or self.args[0].is_imaginary:
return Derivative(self.args[0], x, evaluate=True) \
* sign(conjugate(self.args[0]))
rv = (re(self.args[0]) * Derivative(re(self.args[0]), x,
evaluate=True) + im(self.args[0]) * Derivative(im(self.args[0]),
x, evaluate=True)) / Abs(self.args[0])
return rv.rewrite(sign)
def _eval_rewrite_as_Heaviside(self, arg, **kwargs):
# Note this only holds for real arg (since Heaviside is not defined
# for complex arguments).
from sympy.functions.special.delta_functions import Heaviside
if arg.is_extended_real:
return arg*(Heaviside(arg) - Heaviside(-arg))
def _eval_rewrite_as_Piecewise(self, arg, **kwargs):
if arg.is_extended_real:
return Piecewise((arg, arg >= 0), (-arg, True))
elif arg.is_imaginary:
return Piecewise((I*arg, I*arg >= 0), (-I*arg, True))
def _eval_rewrite_as_sign(self, arg, **kwargs):
return arg/sign(arg)
def _eval_rewrite_as_conjugate(self, arg, **kwargs):
return (arg*conjugate(arg))**S.Half
class arg(Function):
"""
returns the argument (in radians) of a complex number. The argument is
evaluated in consistent convention with atan2 where the branch-cut is
taken along the negative real axis and arg(z) is in the interval
(-pi,pi]. For a positive number, the argument is always 0.
Examples
========
>>> from sympy.functions import arg
>>> from sympy import I, sqrt
>>> arg(2.0)
0
>>> arg(I)
pi/2
>>> arg(sqrt(2) + I*sqrt(2))
pi/4
>>> arg(sqrt(3)/2 + I/2)
pi/6
>>> arg(4 + 3*I)
atan(3/4)
>>> arg(0.8 + 0.6*I)
0.643501108793284
Parameters
==========
arg : Expr
Real or complex expression.
Returns
=======
value : Expr
Returns arc tangent of arg measured in radians.
"""
is_extended_real = True
is_real = True
is_finite = True
_singularities = True # non-holomorphic
@classmethod
def eval(cls, arg):
if isinstance(arg, exp_polar):
return periodic_argument(arg, oo)
if not arg.is_Atom:
c, arg_ = factor_terms(arg).as_coeff_Mul()
if arg_.is_Mul:
arg_ = Mul(*[a if (sign(a) not in (-1, 1)) else
sign(a) for a in arg_.args])
arg_ = sign(c)*arg_
else:
arg_ = arg
if any(i.is_extended_positive is None for i in arg_.atoms(AppliedUndef)):
return
x, y = arg_.as_real_imag()
rv = atan2(y, x)
if rv.is_number:
return rv
if arg_ != arg:
return cls(arg_, evaluate=False)
def _eval_derivative(self, t):
x, y = self.args[0].as_real_imag()
return (x * Derivative(y, t, evaluate=True) - y *
Derivative(x, t, evaluate=True)) / (x**2 + y**2)
def _eval_rewrite_as_atan2(self, arg, **kwargs):
x, y = self.args[0].as_real_imag()
return atan2(y, x)
class conjugate(Function):
"""
Returns the `complex conjugate` Ref[1] of an argument.
In mathematics, the complex conjugate of a complex number
is given by changing the sign of the imaginary part.
Thus, the conjugate of the complex number
:math:`a + ib` (where a and b are real numbers) is :math:`a - ib`
Examples
========
>>> from sympy import conjugate, I
>>> conjugate(2)
2
>>> conjugate(I)
-I
>>> conjugate(3 + 2*I)
3 - 2*I
>>> conjugate(5 - I)
5 + I
Parameters
==========
arg : Expr
Real or complex expression.
Returns
=======
arg : Expr
Complex conjugate of arg as real, imaginary or mixed expression.
See Also
========
sign, Abs
References
==========
.. [1] https://en.wikipedia.org/wiki/Complex_conjugation
"""
_singularities = True # non-holomorphic
@classmethod
def eval(cls, arg):
obj = arg._eval_conjugate()
if obj is not None:
return obj
def _eval_Abs(self):
return Abs(self.args[0], evaluate=True)
def _eval_adjoint(self):
return transpose(self.args[0])
def _eval_conjugate(self):
return self.args[0]
def _eval_derivative(self, x):
if x.is_real:
return conjugate(Derivative(self.args[0], x, evaluate=True))
elif x.is_imaginary:
return -conjugate(Derivative(self.args[0], x, evaluate=True))
def _eval_transpose(self):
return adjoint(self.args[0])
def _eval_is_algebraic(self):
return self.args[0].is_algebraic
class transpose(Function):
"""
Linear map transposition.
Examples
========
>>> from sympy.functions import transpose
>>> from sympy.matrices import MatrixSymbol
>>> from sympy import Matrix
>>> A = MatrixSymbol('A', 25, 9)
>>> transpose(A)
A.T
>>> B = MatrixSymbol('B', 9, 22)
>>> transpose(B)
B.T
>>> transpose(A*B)
B.T*A.T
>>> M = Matrix([[4, 5], [2, 1], [90, 12]])
>>> M
Matrix([
[ 4, 5],
[ 2, 1],
[90, 12]])
>>> transpose(M)
Matrix([
[4, 2, 90],
[5, 1, 12]])
Parameters
==========
arg : Matrix
Matrix or matrix expression to take the transpose of.
Returns
=======
value : Matrix
Transpose of arg.
"""
@classmethod
def eval(cls, arg):
obj = arg._eval_transpose()
if obj is not None:
return obj
def _eval_adjoint(self):
return conjugate(self.args[0])
def _eval_conjugate(self):
return adjoint(self.args[0])
def _eval_transpose(self):
return self.args[0]
class adjoint(Function):
"""
Conjugate transpose or Hermite conjugation.
Examples
========
>>> from sympy import adjoint
>>> from sympy.matrices import MatrixSymbol
>>> A = MatrixSymbol('A', 10, 5)
>>> adjoint(A)
Adjoint(A)
Parameters
==========
arg : Matrix
Matrix or matrix expression to take the adjoint of.
Returns
=======
value : Matrix
Represents the conjugate transpose or Hermite
conjugation of arg.
"""
@classmethod
def eval(cls, arg):
obj = arg._eval_adjoint()
if obj is not None:
return obj
obj = arg._eval_transpose()
if obj is not None:
return conjugate(obj)
def _eval_adjoint(self):
return self.args[0]
def _eval_conjugate(self):
return transpose(self.args[0])
def _eval_transpose(self):
return conjugate(self.args[0])
def _latex(self, printer, exp=None, *args):
arg = printer._print(self.args[0])
tex = r'%s^{\dagger}' % arg
if exp:
tex = r'\left(%s\right)^{%s}' % (tex, exp)
return tex
def _pretty(self, printer, *args):
from sympy.printing.pretty.stringpict import prettyForm
pform = printer._print(self.args[0], *args)
if printer._use_unicode:
pform = pform**prettyForm('\N{DAGGER}')
else:
pform = pform**prettyForm('+')
return pform
###############################################################################
############### HANDLING OF POLAR NUMBERS #####################################
###############################################################################
class polar_lift(Function):
"""
Lift argument to the Riemann surface of the logarithm, using the
standard branch.
Examples
========
>>> from sympy import Symbol, polar_lift, I
>>> p = Symbol('p', polar=True)
>>> x = Symbol('x')
>>> polar_lift(4)
4*exp_polar(0)
>>> polar_lift(-4)
4*exp_polar(I*pi)
>>> polar_lift(-I)
exp_polar(-I*pi/2)
>>> polar_lift(I + 2)
polar_lift(2 + I)
>>> polar_lift(4*x)
4*polar_lift(x)
>>> polar_lift(4*p)
4*p
Parameters
==========
arg : Expr
Real or complex expression.
See Also
========
sympy.functions.elementary.exponential.exp_polar
periodic_argument
"""
is_polar = True
is_comparable = False # Cannot be evalf'd.
@classmethod
def eval(cls, arg):
from sympy.functions.elementary.complexes import arg as argument
if arg.is_number:
ar = argument(arg)
# In general we want to affirm that something is known,
# e.g. `not ar.has(argument) and not ar.has(atan)`
# but for now we will just be more restrictive and
# see that it has evaluated to one of the known values.
if ar in (0, pi/2, -pi/2, pi):
return exp_polar(I*ar)*abs(arg)
if arg.is_Mul:
args = arg.args
else:
args = [arg]
included = []
excluded = []
positive = []
for arg in args:
if arg.is_polar:
included += [arg]
elif arg.is_positive:
positive += [arg]
else:
excluded += [arg]
if len(excluded) < len(args):
if excluded:
return Mul(*(included + positive))*polar_lift(Mul(*excluded))
elif included:
return Mul(*(included + positive))
else:
return Mul(*positive)*exp_polar(0)
def _eval_evalf(self, prec):
""" Careful! any evalf of polar numbers is flaky """
return self.args[0]._eval_evalf(prec)
def _eval_Abs(self):
return Abs(self.args[0], evaluate=True)
class periodic_argument(Function):
"""
Represent the argument on a quotient of the Riemann surface of the
logarithm. That is, given a period $P$, always return a value in
(-P/2, P/2], by using exp(P*I) == 1.
Examples
========
>>> from sympy import exp_polar, periodic_argument
>>> from sympy import I, pi
>>> periodic_argument(exp_polar(10*I*pi), 2*pi)
0
>>> periodic_argument(exp_polar(5*I*pi), 4*pi)
pi
>>> from sympy import exp_polar, periodic_argument
>>> from sympy import I, pi
>>> periodic_argument(exp_polar(5*I*pi), 2*pi)
pi
>>> periodic_argument(exp_polar(5*I*pi), 3*pi)
-pi
>>> periodic_argument(exp_polar(5*I*pi), pi)
0
Parameters
==========
ar : Expr
A polar number.
period : ExprT
The period $P$.
See Also
========
sympy.functions.elementary.exponential.exp_polar
polar_lift : Lift argument to the Riemann surface of the logarithm
principal_branch
"""
@classmethod
def _getunbranched(cls, ar):
if ar.is_Mul:
args = ar.args
else:
args = [ar]
unbranched = 0
for a in args:
if not a.is_polar:
unbranched += arg(a)
elif isinstance(a, exp_polar):
unbranched += a.exp.as_real_imag()[1]
elif a.is_Pow:
re, im = a.exp.as_real_imag()
unbranched += re*unbranched_argument(
a.base) + im*log(abs(a.base))
elif isinstance(a, polar_lift):
unbranched += arg(a.args[0])
else:
return None
return unbranched
@classmethod
def eval(cls, ar, period):
# Our strategy is to evaluate the argument on the Riemann surface of the
# logarithm, and then reduce.
# NOTE evidently this means it is a rather bad idea to use this with
# period != 2*pi and non-polar numbers.
if not period.is_extended_positive:
return None
if period == oo and isinstance(ar, principal_branch):
return periodic_argument(*ar.args)
if isinstance(ar, polar_lift) and period >= 2*pi:
return periodic_argument(ar.args[0], period)
if ar.is_Mul:
newargs = [x for x in ar.args if not x.is_positive]
if len(newargs) != len(ar.args):
return periodic_argument(Mul(*newargs), period)
unbranched = cls._getunbranched(ar)
if unbranched is None:
return None
if unbranched.has(periodic_argument, atan2, atan):
return None
if period == oo:
return unbranched
if period != oo:
n = ceiling(unbranched/period - S.Half)*period
if not n.has(ceiling):
return unbranched - n
def _eval_evalf(self, prec):
z, period = self.args
if period == oo:
unbranched = periodic_argument._getunbranched(z)
if unbranched is None:
return self
return unbranched._eval_evalf(prec)
ub = periodic_argument(z, oo)._eval_evalf(prec)
return (ub - ceiling(ub/period - S.Half)*period)._eval_evalf(prec)
def unbranched_argument(arg):
'''
Returns periodic argument of arg with period as infinity.
Examples
========
>>> from sympy import exp_polar, unbranched_argument
>>> from sympy import I, pi
>>> unbranched_argument(exp_polar(15*I*pi))
15*pi
>>> unbranched_argument(exp_polar(7*I*pi))
7*pi
See also
========
periodic_argument
'''
return periodic_argument(arg, oo)
class principal_branch(Function):
"""
Represent a polar number reduced to its principal branch on a quotient
of the Riemann surface of the logarithm.
Explanation
===========
This is a function of two arguments. The first argument is a polar
number `z`, and the second one a positive real number or infinity, `p`.
The result is "z mod exp_polar(I*p)".
Examples
========
>>> from sympy import exp_polar, principal_branch, oo, I, pi
>>> from sympy.abc import z
>>> principal_branch(z, oo)
z
>>> principal_branch(exp_polar(2*pi*I)*3, 2*pi)
3*exp_polar(0)
>>> principal_branch(exp_polar(2*pi*I)*3*z, 2*pi)
3*principal_branch(z, 2*pi)
Parameters
==========
x : Expr
A polar number.
period : Expr
Positive real number or infinity.
See Also
========
sympy.functions.elementary.exponential.exp_polar
polar_lift : Lift argument to the Riemann surface of the logarithm
periodic_argument
"""
is_polar = True
is_comparable = False # cannot always be evalf'd
@classmethod
def eval(self, x, period):
from sympy import oo, exp_polar, I, Mul, polar_lift, Symbol
if isinstance(x, polar_lift):
return principal_branch(x.args[0], period)
if period == oo:
return x
ub = periodic_argument(x, oo)
barg = periodic_argument(x, period)
if ub != barg and not ub.has(periodic_argument) \
and not barg.has(periodic_argument):
pl = polar_lift(x)
def mr(expr):
if not isinstance(expr, Symbol):
return polar_lift(expr)
return expr
pl = pl.replace(polar_lift, mr)
# Recompute unbranched argument
ub = periodic_argument(pl, oo)
if not pl.has(polar_lift):
if ub != barg:
res = exp_polar(I*(barg - ub))*pl
else:
res = pl
if not res.is_polar and not res.has(exp_polar):
res *= exp_polar(0)
return res
if not x.free_symbols:
c, m = x, ()
else:
c, m = x.as_coeff_mul(*x.free_symbols)
others = []
for y in m:
if y.is_positive:
c *= y
else:
others += [y]
m = tuple(others)
arg = periodic_argument(c, period)
if arg.has(periodic_argument):
return None
if arg.is_number and (unbranched_argument(c) != arg or
(arg == 0 and m != () and c != 1)):
if arg == 0:
return abs(c)*principal_branch(Mul(*m), period)
return principal_branch(exp_polar(I*arg)*Mul(*m), period)*abs(c)
if arg.is_number and ((abs(arg) < period/2) == True or arg == period/2) \
and m == ():
return exp_polar(arg*I)*abs(c)
def _eval_evalf(self, prec):
from sympy import exp, pi, I
z, period = self.args
p = periodic_argument(z, period)._eval_evalf(prec)
if abs(p) > pi or p == -pi:
return self # Cannot evalf for this argument.
return (abs(z)*exp(I*p))._eval_evalf(prec)
def _polarify(eq, lift, pause=False):
from sympy import Integral
if eq.is_polar:
return eq
if eq.is_number and not pause:
return polar_lift(eq)
if isinstance(eq, Symbol) and not pause and lift:
return polar_lift(eq)
elif eq.is_Atom:
return eq
elif eq.is_Add:
r = eq.func(*[_polarify(arg, lift, pause=True) for arg in eq.args])
if lift:
return polar_lift(r)
return r
elif eq.is_Pow and eq.base == S.Exp1:
return eq.func(S.Exp1, _polarify(eq.exp, lift, pause=False))
elif eq.is_Function:
return eq.func(*[_polarify(arg, lift, pause=False) for arg in eq.args])
elif isinstance(eq, Integral):
# Don't lift the integration variable
func = _polarify(eq.function, lift, pause=pause)
limits = []
for limit in eq.args[1:]:
var = _polarify(limit[0], lift=False, pause=pause)
rest = _polarify(limit[1:], lift=lift, pause=pause)
limits.append((var,) + rest)
return Integral(*((func,) + tuple(limits)))
else:
return eq.func(*[_polarify(arg, lift, pause=pause)
if isinstance(arg, Expr) else arg for arg in eq.args])
def polarify(eq, subs=True, lift=False):
"""
Turn all numbers in eq into their polar equivalents (under the standard
choice of argument).
Note that no attempt is made to guess a formal convention of adding
polar numbers, expressions like 1 + x will generally not be altered.
Note also that this function does not promote exp(x) to exp_polar(x).
If ``subs`` is True, all symbols which are not already polar will be
substituted for polar dummies; in this case the function behaves much
like posify.
If ``lift`` is True, both addition statements and non-polar symbols are
changed to their polar_lift()ed versions.
Note that lift=True implies subs=False.
Examples
========
>>> from sympy import polarify, sin, I
>>> from sympy.abc import x, y
>>> expr = (-x)**y
>>> expr.expand()
(-x)**y
>>> polarify(expr)
((_x*exp_polar(I*pi))**_y, {_x: x, _y: y})
>>> polarify(expr)[0].expand()
_x**_y*exp_polar(_y*I*pi)
>>> polarify(x, lift=True)
polar_lift(x)
>>> polarify(x*(1+y), lift=True)
polar_lift(x)*polar_lift(y + 1)
Adds are treated carefully:
>>> polarify(1 + sin((1 + I)*x))
(sin(_x*polar_lift(1 + I)) + 1, {_x: x})
"""
if lift:
subs = False
eq = _polarify(sympify(eq), lift)
if not subs:
return eq
reps = {s: Dummy(s.name, polar=True) for s in eq.free_symbols}
eq = eq.subs(reps)
return eq, {r: s for s, r in reps.items()}
def _unpolarify(eq, exponents_only, pause=False):
if not isinstance(eq, Basic) or eq.is_Atom:
return eq
if not pause:
if isinstance(eq, exp_polar):
return exp(_unpolarify(eq.exp, exponents_only))
if isinstance(eq, principal_branch) and eq.args[1] == 2*pi:
return _unpolarify(eq.args[0], exponents_only)
if (
eq.is_Add or eq.is_Mul or eq.is_Boolean or
eq.is_Relational and (
eq.rel_op in ('==', '!=') and 0 in eq.args or
eq.rel_op not in ('==', '!='))
):
return eq.func(*[_unpolarify(x, exponents_only) for x in eq.args])
if isinstance(eq, polar_lift):
return _unpolarify(eq.args[0], exponents_only)
if eq.is_Pow:
expo = _unpolarify(eq.exp, exponents_only)
base = _unpolarify(eq.base, exponents_only,
not (expo.is_integer and not pause))
return base**expo
if eq.is_Function and getattr(eq.func, 'unbranched', False):
return eq.func(*[_unpolarify(x, exponents_only, exponents_only)
for x in eq.args])
return eq.func(*[_unpolarify(x, exponents_only, True) for x in eq.args])
def unpolarify(eq, subs={}, exponents_only=False):
"""
If p denotes the projection from the Riemann surface of the logarithm to
the complex line, return a simplified version eq' of `eq` such that
p(eq') == p(eq).
Also apply the substitution subs in the end. (This is a convenience, since
``unpolarify``, in a certain sense, undoes polarify.)
Examples
========
>>> from sympy import unpolarify, polar_lift, sin, I
>>> unpolarify(polar_lift(I + 2))
2 + I
>>> unpolarify(sin(polar_lift(I + 7)))
sin(7 + I)
"""
if isinstance(eq, bool):
return eq
eq = sympify(eq)
if subs != {}:
return unpolarify(eq.subs(subs))
changed = True
pause = False
if exponents_only:
pause = True
while changed:
changed = False
res = _unpolarify(eq, exponents_only, pause)
if res != eq:
changed = True
eq = res
if isinstance(res, bool):
return res
# Finally, replacing Exp(0) by 1 is always correct.
# So is polar_lift(0) -> 0.
return res.subs({exp_polar(0): 1, polar_lift(0): 0})
|
327cf6c27071ed5b6f1e47d8d62f07411394a5f365c90612255ad5d210f4afb5 | from sympy.core import S, sympify, diff
from sympy.core.decorators import deprecated
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.logic import fuzzy_not
from sympy.core.relational import Eq, Ne
from sympy.functions.elementary.complexes import im, sign
from sympy.functions.elementary.piecewise import Piecewise
from sympy.polys.polyerrors import PolynomialError
from sympy.utilities import filldedent
###############################################################################
################################ DELTA FUNCTION ###############################
###############################################################################
class DiracDelta(Function):
r"""
The DiracDelta function and its derivatives.
Explanation
===========
DiracDelta is not an ordinary function. It can be rigorously defined either
as a distribution or as a measure.
DiracDelta only makes sense in definite integrals, and in particular,
integrals of the form ``Integral(f(x)*DiracDelta(x - x0), (x, a, b))``,
where it equals ``f(x0)`` if ``a <= x0 <= b`` and ``0`` otherwise. Formally,
DiracDelta acts in some ways like a function that is ``0`` everywhere except
at ``0``, but in many ways it also does not. It can often be useful to treat
DiracDelta in formal ways, building up and manipulating expressions with
delta functions (which may eventually be integrated), but care must be taken
to not treat it as a real function. SymPy's ``oo`` is similar. It only
truly makes sense formally in certain contexts (such as integration limits),
but SymPy allows its use everywhere, and it tries to be consistent with
operations on it (like ``1/oo``), but it is easy to get into trouble and get
wrong results if ``oo`` is treated too much like a number. Similarly, if
DiracDelta is treated too much like a function, it is easy to get wrong or
nonsensical results.
DiracDelta function has the following properties:
1) $\frac{d}{d x} \theta(x) = \delta(x)$
2) $\int_{-\infty}^\infty \delta(x - a)f(x)\, dx = f(a)$ and $\int_{a-
\epsilon}^{a+\epsilon} \delta(x - a)f(x)\, dx = f(a)$
3) $\delta(x) = 0$ for all $x \neq 0$
4) $\delta(g(x)) = \sum_i \frac{\delta(x - x_i)}{\|g'(x_i)\|}$ where $x_i$
are the roots of $g$
5) $\delta(-x) = \delta(x)$
Derivatives of ``k``-th order of DiracDelta have the following properties:
6) $\delta(x, k) = 0$ for all $x \neq 0$
7) $\delta(-x, k) = -\delta(x, k)$ for odd $k$
8) $\delta(-x, k) = \delta(x, k)$ for even $k$
Examples
========
>>> from sympy import DiracDelta, diff, pi
>>> from sympy.abc import x, y
>>> DiracDelta(x)
DiracDelta(x)
>>> DiracDelta(1)
0
>>> DiracDelta(-1)
0
>>> DiracDelta(pi)
0
>>> DiracDelta(x - 4).subs(x, 4)
DiracDelta(0)
>>> diff(DiracDelta(x))
DiracDelta(x, 1)
>>> diff(DiracDelta(x - 1),x,2)
DiracDelta(x - 1, 2)
>>> diff(DiracDelta(x**2 - 1),x,2)
2*(2*x**2*DiracDelta(x**2 - 1, 2) + DiracDelta(x**2 - 1, 1))
>>> DiracDelta(3*x).is_simple(x)
True
>>> DiracDelta(x**2).is_simple(x)
False
>>> DiracDelta((x**2 - 1)*y).expand(diracdelta=True, wrt=x)
DiracDelta(x - 1)/(2*Abs(y)) + DiracDelta(x + 1)/(2*Abs(y))
See Also
========
Heaviside
sympy.simplify.simplify.simplify, is_simple
sympy.functions.special.tensor_functions.KroneckerDelta
References
==========
.. [1] http://mathworld.wolfram.com/DeltaFunction.html
"""
is_real = True
def fdiff(self, argindex=1):
"""
Returns the first derivative of a DiracDelta Function.
Explanation
===========
The difference between ``diff()`` and ``fdiff()`` is: ``diff()`` is the
user-level function and ``fdiff()`` is an object method. ``fdiff()`` is
a convenience method available in the ``Function`` class. It returns
the derivative of the function without considering the chain rule.
``diff(function, x)`` calls ``Function._eval_derivative`` which in turn
calls ``fdiff()`` internally to compute the derivative of the function.
Examples
========
>>> from sympy import DiracDelta, diff
>>> from sympy.abc import x
>>> DiracDelta(x).fdiff()
DiracDelta(x, 1)
>>> DiracDelta(x, 1).fdiff()
DiracDelta(x, 2)
>>> DiracDelta(x**2 - 1).fdiff()
DiracDelta(x**2 - 1, 1)
>>> diff(DiracDelta(x, 1)).fdiff()
DiracDelta(x, 3)
Parameters
==========
argindex : integer
degree of derivative
"""
if argindex == 1:
#I didn't know if there is a better way to handle default arguments
k = 0
if len(self.args) > 1:
k = self.args[1]
return self.func(self.args[0], k + 1)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg, k=0):
"""
Returns a simplified form or a value of DiracDelta depending on the
argument passed by the DiracDelta object.
Explanation
===========
The ``eval()`` method is automatically called when the ``DiracDelta``
class is about to be instantiated and it returns either some simplified
instance or the unevaluated instance depending on the argument passed.
In other words, ``eval()`` method is not needed to be called explicitly,
it is being called and evaluated once the object is called.
Examples
========
>>> from sympy import DiracDelta, S
>>> from sympy.abc import x
>>> DiracDelta(x)
DiracDelta(x)
>>> DiracDelta(-x, 1)
-DiracDelta(x, 1)
>>> DiracDelta(1)
0
>>> DiracDelta(5, 1)
0
>>> DiracDelta(0)
DiracDelta(0)
>>> DiracDelta(-1)
0
>>> DiracDelta(S.NaN)
nan
>>> DiracDelta(x).eval(1)
0
>>> DiracDelta(x - 100).subs(x, 5)
0
>>> DiracDelta(x - 100).subs(x, 100)
DiracDelta(0)
Parameters
==========
k : integer
order of derivative
arg : argument passed to DiracDelta
"""
k = sympify(k)
if not k.is_Integer or k.is_negative:
raise ValueError("Error: the second argument of DiracDelta must be \
a non-negative integer, %s given instead." % (k,))
arg = sympify(arg)
if arg is S.NaN:
return S.NaN
if arg.is_nonzero:
return S.Zero
if fuzzy_not(im(arg).is_zero):
raise ValueError(filldedent('''
Function defined only for Real Values.
Complex part: %s found in %s .''' % (
repr(im(arg)), repr(arg))))
c, nc = arg.args_cnc()
if c and c[0] is S.NegativeOne:
# keep this fast and simple instead of using
# could_extract_minus_sign
if k.is_odd:
return -cls(-arg, k)
elif k.is_even:
return cls(-arg, k) if k else cls(-arg)
@deprecated(useinstead="expand(diracdelta=True, wrt=x)", issue=12859, deprecated_since_version="1.1")
def simplify(self, x, **kwargs):
return self.expand(diracdelta=True, wrt=x)
def _eval_expand_diracdelta(self, **hints):
"""
Compute a simplified representation of the function using
property number 4. Pass ``wrt`` as a hint to expand the expression
with respect to a particular variable.
Explanation
===========
``wrt`` is:
- a variable with respect to which a DiracDelta expression will
get expanded.
Examples
========
>>> from sympy import DiracDelta
>>> from sympy.abc import x, y
>>> DiracDelta(x*y).expand(diracdelta=True, wrt=x)
DiracDelta(x)/Abs(y)
>>> DiracDelta(x*y).expand(diracdelta=True, wrt=y)
DiracDelta(y)/Abs(x)
>>> DiracDelta(x**2 + x - 2).expand(diracdelta=True, wrt=x)
DiracDelta(x - 1)/3 + DiracDelta(x + 2)/3
See Also
========
is_simple, Diracdelta
"""
from sympy.polys.polyroots import roots
wrt = hints.get('wrt', None)
if wrt is None:
free = self.free_symbols
if len(free) == 1:
wrt = free.pop()
else:
raise TypeError(filldedent('''
When there is more than 1 free symbol or variable in the expression,
the 'wrt' keyword is required as a hint to expand when using the
DiracDelta hint.'''))
if not self.args[0].has(wrt) or (len(self.args) > 1 and self.args[1] != 0 ):
return self
try:
argroots = roots(self.args[0], wrt)
result = 0
valid = True
darg = abs(diff(self.args[0], wrt))
for r, m in argroots.items():
if r.is_real is not False and m == 1:
result += self.func(wrt - r)/darg.subs(wrt, r)
else:
# don't handle non-real and if m != 1 then
# a polynomial will have a zero in the derivative (darg)
# at r
valid = False
break
if valid:
return result
except PolynomialError:
pass
return self
def is_simple(self, x):
"""
Tells whether the argument(args[0]) of DiracDelta is a linear
expression in *x*.
Examples
========
>>> from sympy import DiracDelta, cos
>>> from sympy.abc import x, y
>>> DiracDelta(x*y).is_simple(x)
True
>>> DiracDelta(x*y).is_simple(y)
True
>>> DiracDelta(x**2 + x - 2).is_simple(x)
False
>>> DiracDelta(cos(x)).is_simple(x)
False
Parameters
==========
x : can be a symbol
See Also
========
sympy.simplify.simplify.simplify, DiracDelta
"""
p = self.args[0].as_poly(x)
if p:
return p.degree() == 1
return False
def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
"""
Represents DiracDelta in a piecewise form.
Examples
========
>>> from sympy import DiracDelta, Piecewise, Symbol
>>> x = Symbol('x')
>>> DiracDelta(x).rewrite(Piecewise)
Piecewise((DiracDelta(0), Eq(x, 0)), (0, True))
>>> DiracDelta(x - 5).rewrite(Piecewise)
Piecewise((DiracDelta(0), Eq(x - 5, 0)), (0, True))
>>> DiracDelta(x**2 - 5).rewrite(Piecewise)
Piecewise((DiracDelta(0), Eq(x**2 - 5, 0)), (0, True))
>>> DiracDelta(x - 5, 4).rewrite(Piecewise)
DiracDelta(x - 5, 4)
"""
if len(args) == 1:
return Piecewise((DiracDelta(0), Eq(args[0], 0)), (0, True))
def _eval_rewrite_as_SingularityFunction(self, *args, **kwargs):
"""
Returns the DiracDelta expression written in the form of Singularity
Functions.
"""
from sympy.solvers import solve
from sympy.functions import SingularityFunction
if self == DiracDelta(0):
return SingularityFunction(0, 0, -1)
if self == DiracDelta(0, 1):
return SingularityFunction(0, 0, -2)
free = self.free_symbols
if len(free) == 1:
x = (free.pop())
if len(args) == 1:
return SingularityFunction(x, solve(args[0], x)[0], -1)
return SingularityFunction(x, solve(args[0], x)[0], -args[1] - 1)
else:
# I don't know how to handle the case for DiracDelta expressions
# having arguments with more than one variable.
raise TypeError(filldedent('''
rewrite(SingularityFunction) doesn't support
arguments with more that 1 variable.'''))
def _sage_(self):
import sage.all as sage
return sage.dirac_delta(self.args[0]._sage_())
###############################################################################
############################## HEAVISIDE FUNCTION #############################
###############################################################################
class Heaviside(Function):
r"""
Heaviside step function.
Explanation
===========
The Heaviside step function has the following properties:
1) $\frac{d}{d x} \theta(x) = \delta(x)$
2) $\theta(x) = \begin{cases} 0 & \text{for}\: x < 0 \\ \frac{1}{2} &
\text{for}\: x = 0 \\1 & \text{for}\: x > 0 \end{cases}$
3) $\frac{d}{d x} \max(x, 0) = \theta(x)$
Heaviside(x) is printed as $\theta(x)$ with the SymPy LaTeX printer.
The value at 0 is set differently in different fields. SymPy uses 1/2,
which is a convention from electronics and signal processing, and is
consistent with solving improper integrals by Fourier transform and
convolution.
To specify a different value of Heaviside at ``x=0``, a second argument
can be given. Using ``Heaviside(x, nan)`` gives an expression that will
evaluate to nan for x=0.
.. versionchanged:: 1.9 ``Heaviside(0)`` now returns 1/2 (before: undefined)
Examples
========
>>> from sympy import Heaviside, nan
>>> from sympy.abc import x
>>> Heaviside(9)
1
>>> Heaviside(-9)
0
>>> Heaviside(0)
1/2
>>> Heaviside(0, nan)
nan
>>> (Heaviside(x) + 1).replace(Heaviside(x), Heaviside(x, 1))
Heaviside(x, 1) + 1
See Also
========
DiracDelta
References
==========
.. [1] http://mathworld.wolfram.com/HeavisideStepFunction.html
.. [2] http://dlmf.nist.gov/1.16#iv
"""
is_real = True
def fdiff(self, argindex=1):
"""
Returns the first derivative of a Heaviside Function.
Examples
========
>>> from sympy import Heaviside, diff
>>> from sympy.abc import x
>>> Heaviside(x).fdiff()
DiracDelta(x)
>>> Heaviside(x**2 - 1).fdiff()
DiracDelta(x**2 - 1)
>>> diff(Heaviside(x)).fdiff()
DiracDelta(x, 1)
Parameters
==========
argindex : integer
order of derivative
"""
if argindex == 1:
return DiracDelta(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
def __new__(cls, arg, H0=S.Half, **options):
if isinstance(H0, Heaviside) and len(H0.args) == 1:
H0 = S.Half
return super(cls, cls).__new__(cls, arg, H0, **options)
@classmethod
def eval(cls, arg, H0=S.Half):
"""
Returns a simplified form or a value of Heaviside depending on the
argument passed by the Heaviside object.
Explanation
===========
The ``eval()`` method is automatically called when the ``Heaviside``
class is about to be instantiated and it returns either some simplified
instance or the unevaluated instance depending on the argument passed.
In other words, ``eval()`` method is not needed to be called explicitly,
it is being called and evaluated once the object is called.
Examples
========
>>> from sympy import Heaviside, S
>>> from sympy.abc import x
>>> Heaviside(x)
Heaviside(x, 1/2)
>>> Heaviside(19)
1
>>> Heaviside(0)
1/2
>>> Heaviside(0, 1)
1
>>> Heaviside(-5)
0
>>> Heaviside(S.NaN)
nan
>>> Heaviside(x).eval(42)
1
>>> Heaviside(x - 100).subs(x, 5)
0
>>> Heaviside(x - 100).subs(x, 105)
1
Parameters
==========
arg : argument passed by Heaviside object
H0 : value of Heaviside(0)
"""
H0 = sympify(H0)
arg = sympify(arg)
if arg.is_extended_negative:
return S.Zero
elif arg.is_extended_positive:
return S.One
elif arg.is_zero:
return H0
elif arg is S.NaN:
return S.NaN
elif fuzzy_not(im(arg).is_zero):
raise ValueError("Function defined only for Real Values. Complex part: %s found in %s ." % (repr(im(arg)), repr(arg)) )
def _eval_rewrite_as_Piecewise(self, arg, H0=None, **kwargs):
"""
Represents Heaviside in a Piecewise form.
Examples
========
>>> from sympy import Heaviside, Piecewise, Symbol, nan
>>> x = Symbol('x')
>>> Heaviside(x).rewrite(Piecewise)
Piecewise((0, x < 0), (1/2, Eq(x, 0)), (1, x > 0))
>>> Heaviside(x,nan).rewrite(Piecewise)
Piecewise((0, x < 0), (nan, Eq(x, 0)), (1, x > 0))
>>> Heaviside(x - 5).rewrite(Piecewise)
Piecewise((0, x - 5 < 0), (1/2, Eq(x - 5, 0)), (1, x - 5 > 0))
>>> Heaviside(x**2 - 1).rewrite(Piecewise)
Piecewise((0, x**2 - 1 < 0), (1/2, Eq(x**2 - 1, 0)), (1, x**2 - 1 > 0))
"""
if H0 == 0:
return Piecewise((0, arg <= 0), (1, arg > 0))
if H0 == 1:
return Piecewise((0, arg < 0), (1, arg >= 0))
return Piecewise((0, arg < 0), (H0, Eq(arg, 0)), (1, arg > 0))
def _eval_rewrite_as_sign(self, arg, H0=S.Half, **kwargs):
"""
Represents the Heaviside function in the form of sign function.
Explanation
===========
The value of Heaviside(0) must be 1/2 for rewritting as sign to be
strictly equivalent. For easier usage, we also allow this rewriting
when Heaviside(0) is undefined.
Examples
========
>>> from sympy import Heaviside, Symbol, sign, nan
>>> x = Symbol('x', real=True)
>>> y = Symbol('y')
>>> Heaviside(x).rewrite(sign)
sign(x)/2 + 1/2
>>> Heaviside(x, 0).rewrite(sign)
Piecewise((sign(x)/2 + 1/2, Ne(x, 0)), (0, True))
>>> Heaviside(x, nan).rewrite(sign)
Piecewise((sign(x)/2 + 1/2, Ne(x, 0)), (nan, True))
>>> Heaviside(x - 2).rewrite(sign)
sign(x - 2)/2 + 1/2
>>> Heaviside(x**2 - 2*x + 1).rewrite(sign)
sign(x**2 - 2*x + 1)/2 + 1/2
>>> Heaviside(y).rewrite(sign)
Heaviside(y, 1/2)
>>> Heaviside(y**2 - 2*y + 1).rewrite(sign)
Heaviside(y**2 - 2*y + 1, 1/2)
See Also
========
sign
"""
if arg.is_extended_real:
pw1 = Piecewise(
((sign(arg) + 1)/2, Ne(arg, 0)),
(Heaviside(0, H0=H0), True))
pw2 = Piecewise(
((sign(arg) + 1)/2, Eq(Heaviside(0, H0=H0), S(1)/2)),
(pw1, True))
return pw2
def _eval_rewrite_as_SingularityFunction(self, args, H0=S.Half, **kwargs):
"""
Returns the Heaviside expression written in the form of Singularity
Functions.
"""
from sympy.solvers import solve
from sympy.functions import SingularityFunction
if self == Heaviside(0):
return SingularityFunction(0, 0, 0)
free = self.free_symbols
if len(free) == 1:
x = (free.pop())
return SingularityFunction(x, solve(args, x)[0], 0)
# TODO
# ((x - 5)**3*Heaviside(x - 5)).rewrite(SingularityFunction) should output
# SingularityFunction(x, 5, 0) instead of (x - 5)**3*SingularityFunction(x, 5, 0)
else:
# I don't know how to handle the case for Heaviside expressions
# having arguments with more than one variable.
raise TypeError(filldedent('''
rewrite(SingularityFunction) doesn't
support arguments with more that 1 variable.'''))
def _sage_(self):
import sage.all as sage
return sage.heaviside(self.args[0]._sage_())
|
2e2d2324cf4e5834305d602ab6b231c53131b5d3eef4034f2e7fadef8353518e | """ Riemann zeta and related function. """
from sympy.core import Function, S, sympify, pi, I
from sympy.core.function import ArgumentIndexError
from sympy.functions.combinatorial.numbers import bernoulli, factorial, harmonic
from sympy.functions.elementary.exponential import log, exp_polar
from sympy.functions.elementary.miscellaneous import sqrt
###############################################################################
###################### LERCH TRANSCENDENT #####################################
###############################################################################
class lerchphi(Function):
r"""
Lerch transcendent (Lerch phi function).
Explanation
===========
For $\operatorname{Re}(a) > 0$, $|z| < 1$ and $s \in \mathbb{C}$, the
Lerch transcendent is defined as
.. math :: \Phi(z, s, a) = \sum_{n=0}^\infty \frac{z^n}{(n + a)^s},
where the standard branch of the argument is used for $n + a$,
and by analytic continuation for other values of the parameters.
A commonly used related function is the Lerch zeta function, defined by
.. math:: L(q, s, a) = \Phi(e^{2\pi i q}, s, a).
**Analytic Continuation and Branching Behavior**
It can be shown that
.. math:: \Phi(z, s, a) = z\Phi(z, s, a+1) + a^{-s}.
This provides the analytic continuation to $\operatorname{Re}(a) \le 0$.
Assume now $\operatorname{Re}(a) > 0$. The integral representation
.. math:: \Phi_0(z, s, a) = \int_0^\infty \frac{t^{s-1} e^{-at}}{1 - ze^{-t}}
\frac{\mathrm{d}t}{\Gamma(s)}
provides an analytic continuation to $\mathbb{C} - [1, \infty)$.
Finally, for $x \in (1, \infty)$ we find
.. math:: \lim_{\epsilon \to 0^+} \Phi_0(x + i\epsilon, s, a)
-\lim_{\epsilon \to 0^+} \Phi_0(x - i\epsilon, s, a)
= \frac{2\pi i \log^{s-1}{x}}{x^a \Gamma(s)},
using the standard branch for both $\log{x}$ and
$\log{\log{x}}$ (a branch of $\log{\log{x}}$ is needed to
evaluate $\log{x}^{s-1}$).
This concludes the analytic continuation. The Lerch transcendent is thus
branched at $z \in \{0, 1, \infty\}$ and
$a \in \mathbb{Z}_{\le 0}$. For fixed $z, a$ outside these
branch points, it is an entire function of $s$.
Examples
========
The Lerch transcendent is a fairly general function, for this reason it does
not automatically evaluate to simpler functions. Use ``expand_func()`` to
achieve this.
If $z=1$, the Lerch transcendent reduces to the Hurwitz zeta function:
>>> from sympy import lerchphi, expand_func
>>> from sympy.abc import z, s, a
>>> expand_func(lerchphi(1, s, a))
zeta(s, a)
More generally, if $z$ is a root of unity, the Lerch transcendent
reduces to a sum of Hurwitz zeta functions:
>>> expand_func(lerchphi(-1, s, a))
zeta(s, a/2)/2**s - zeta(s, a/2 + 1/2)/2**s
If $a=1$, the Lerch transcendent reduces to the polylogarithm:
>>> expand_func(lerchphi(z, s, 1))
polylog(s, z)/z
More generally, if $a$ is rational, the Lerch transcendent reduces
to a sum of polylogarithms:
>>> from sympy import S
>>> expand_func(lerchphi(z, s, S(1)/2))
2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) -
polylog(s, sqrt(z)*exp_polar(I*pi))/sqrt(z))
>>> expand_func(lerchphi(z, s, S(3)/2))
-2**s/z + 2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) -
polylog(s, sqrt(z)*exp_polar(I*pi))/sqrt(z))/z
The derivatives with respect to $z$ and $a$ can be computed in
closed form:
>>> lerchphi(z, s, a).diff(z)
(-a*lerchphi(z, s, a) + lerchphi(z, s - 1, a))/z
>>> lerchphi(z, s, a).diff(a)
-s*lerchphi(z, s + 1, a)
See Also
========
polylog, zeta
References
==========
.. [1] Bateman, H.; Erdelyi, A. (1953), Higher Transcendental Functions,
Vol. I, New York: McGraw-Hill. Section 1.11.
.. [2] http://dlmf.nist.gov/25.14
.. [3] https://en.wikipedia.org/wiki/Lerch_transcendent
"""
def _eval_expand_func(self, **hints):
from sympy import exp, I, floor, Add, Poly, Dummy, exp_polar, unpolarify
z, s, a = self.args
if z == 1:
return zeta(s, a)
if s.is_Integer and s <= 0:
t = Dummy('t')
p = Poly((t + a)**(-s), t)
start = 1/(1 - t)
res = S.Zero
for c in reversed(p.all_coeffs()):
res += c*start
start = t*start.diff(t)
return res.subs(t, z)
if a.is_Rational:
# See section 18 of
# Kelly B. Roach. Hypergeometric Function Representations.
# In: Proceedings of the 1997 International Symposium on Symbolic and
# Algebraic Computation, pages 205-211, New York, 1997. ACM.
# TODO should something be polarified here?
add = S.Zero
mul = S.One
# First reduce a to the interaval (0, 1]
if a > 1:
n = floor(a)
if n == a:
n -= 1
a -= n
mul = z**(-n)
add = Add(*[-z**(k - n)/(a + k)**s for k in range(n)])
elif a <= 0:
n = floor(-a) + 1
a += n
mul = z**n
add = Add(*[z**(n - 1 - k)/(a - k - 1)**s for k in range(n)])
m, n = S([a.p, a.q])
zet = exp_polar(2*pi*I/n)
root = z**(1/n)
return add + mul*n**(s - 1)*Add(
*[polylog(s, zet**k*root)._eval_expand_func(**hints)
/ (unpolarify(zet)**k*root)**m for k in range(n)])
# TODO use minpoly instead of ad-hoc methods when issue 5888 is fixed
if isinstance(z, exp) and (z.args[0]/(pi*I)).is_Rational or z in [-1, I, -I]:
# TODO reference?
if z == -1:
p, q = S([1, 2])
elif z == I:
p, q = S([1, 4])
elif z == -I:
p, q = S([-1, 4])
else:
arg = z.args[0]/(2*pi*I)
p, q = S([arg.p, arg.q])
return Add(*[exp(2*pi*I*k*p/q)/q**s*zeta(s, (k + a)/q)
for k in range(q)])
return lerchphi(z, s, a)
def fdiff(self, argindex=1):
z, s, a = self.args
if argindex == 3:
return -s*lerchphi(z, s + 1, a)
elif argindex == 1:
return (lerchphi(z, s - 1, a) - a*lerchphi(z, s, a))/z
else:
raise ArgumentIndexError
def _eval_rewrite_helper(self, z, s, a, target):
res = self._eval_expand_func()
if res.has(target):
return res
else:
return self
def _eval_rewrite_as_zeta(self, z, s, a, **kwargs):
return self._eval_rewrite_helper(z, s, a, zeta)
def _eval_rewrite_as_polylog(self, z, s, a, **kwargs):
return self._eval_rewrite_helper(z, s, a, polylog)
###############################################################################
###################### POLYLOGARITHM ##########################################
###############################################################################
class polylog(Function):
r"""
Polylogarithm function.
Explanation
===========
For $|z| < 1$ and $s \in \mathbb{C}$, the polylogarithm is
defined by
.. math:: \operatorname{Li}_s(z) = \sum_{n=1}^\infty \frac{z^n}{n^s},
where the standard branch of the argument is used for $n$. It admits
an analytic continuation which is branched at $z=1$ (notably not on the
sheet of initial definition), $z=0$ and $z=\infty$.
The name polylogarithm comes from the fact that for $s=1$, the
polylogarithm is related to the ordinary logarithm (see examples), and that
.. math:: \operatorname{Li}_{s+1}(z) =
\int_0^z \frac{\operatorname{Li}_s(t)}{t} \mathrm{d}t.
The polylogarithm is a special case of the Lerch transcendent:
.. math:: \operatorname{Li}_{s}(z) = z \Phi(z, s, 1).
Examples
========
For $z \in \{0, 1, -1\}$, the polylogarithm is automatically expressed
using other functions:
>>> from sympy import polylog
>>> from sympy.abc import s
>>> polylog(s, 0)
0
>>> polylog(s, 1)
zeta(s)
>>> polylog(s, -1)
-dirichlet_eta(s)
If $s$ is a negative integer, $0$ or $1$, the polylogarithm can be
expressed using elementary functions. This can be done using
``expand_func()``:
>>> from sympy import expand_func
>>> from sympy.abc import z
>>> expand_func(polylog(1, z))
-log(1 - z)
>>> expand_func(polylog(0, z))
z/(1 - z)
The derivative with respect to $z$ can be computed in closed form:
>>> polylog(s, z).diff(z)
polylog(s - 1, z)/z
The polylogarithm can be expressed in terms of the lerch transcendent:
>>> from sympy import lerchphi
>>> polylog(s, z).rewrite(lerchphi)
z*lerchphi(z, s, 1)
See Also
========
zeta, lerchphi
"""
@classmethod
def eval(cls, s, z):
s, z = sympify((s, z))
if z is S.One:
return zeta(s)
elif z is S.NegativeOne:
return -dirichlet_eta(s)
elif z is S.Zero:
return S.Zero
elif s == 2:
if z == S.Half:
return pi**2/12 - log(2)**2/2
elif z == 2:
return pi**2/4 - I*pi*log(2)
elif z == -(sqrt(5) - 1)/2:
return -pi**2/15 + log((sqrt(5)-1)/2)**2/2
elif z == -(sqrt(5) + 1)/2:
return -pi**2/10 - log((sqrt(5)+1)/2)**2
elif z == (3 - sqrt(5))/2:
return pi**2/15 - log((sqrt(5)-1)/2)**2
elif z == (sqrt(5) - 1)/2:
return pi**2/10 - log((sqrt(5)-1)/2)**2
if z.is_zero:
return S.Zero
# Make an effort to determine if z is 1 to avoid replacing into
# expression with singularity
zone = z.equals(S.One)
if zone:
return zeta(s)
elif zone is False:
# For s = 0 or -1 use explicit formulas to evaluate, but
# automatically expanding polylog(1, z) to -log(1-z) seems
# undesirable for summation methods based on hypergeometric
# functions
if s is S.Zero:
return z/(1 - z)
elif s is S.NegativeOne:
return z/(1 - z)**2
if s.is_zero:
return z/(1 - z)
# polylog is branched, but not over the unit disk
from sympy.functions.elementary.complexes import (Abs, unpolarify,
polar_lift)
if z.has(exp_polar, polar_lift) and (zone or (Abs(z) <= S.One) == True):
return cls(s, unpolarify(z))
def fdiff(self, argindex=1):
s, z = self.args
if argindex == 2:
return polylog(s - 1, z)/z
raise ArgumentIndexError
def _eval_rewrite_as_lerchphi(self, s, z, **kwargs):
return z*lerchphi(z, s, 1)
def _eval_expand_func(self, **hints):
from sympy import log, expand_mul, Dummy
s, z = self.args
if s == 1:
return -log(1 - z)
if s.is_Integer and s <= 0:
u = Dummy('u')
start = u/(1 - u)
for _ in range(-s):
start = u*start.diff(u)
return expand_mul(start).subs(u, z)
return polylog(s, z)
def _eval_is_zero(self):
z = self.args[1]
if z.is_zero:
return True
###############################################################################
###################### HURWITZ GENERALIZED ZETA FUNCTION ######################
###############################################################################
class zeta(Function):
r"""
Hurwitz zeta function (or Riemann zeta function).
Explanation
===========
For $\operatorname{Re}(a) > 0$ and $\operatorname{Re}(s) > 1$, this
function is defined as
.. math:: \zeta(s, a) = \sum_{n=0}^\infty \frac{1}{(n + a)^s},
where the standard choice of argument for $n + a$ is used. For fixed
$a$ with $\operatorname{Re}(a) > 0$ the Hurwitz zeta function admits a
meromorphic continuation to all of $\mathbb{C}$, it is an unbranched
function with a simple pole at $s = 1$.
Analytic continuation to other $a$ is possible under some circumstances,
but this is not typically done.
The Hurwitz zeta function is a special case of the Lerch transcendent:
.. math:: \zeta(s, a) = \Phi(1, s, a).
This formula defines an analytic continuation for all possible values of
$s$ and $a$ (also $\operatorname{Re}(a) < 0$), see the documentation of
:class:`lerchphi` for a description of the branching behavior.
If no value is passed for $a$, by this function assumes a default value
of $a = 1$, yielding the Riemann zeta function.
Examples
========
For $a = 1$ the Hurwitz zeta function reduces to the famous Riemann
zeta function:
.. math:: \zeta(s, 1) = \zeta(s) = \sum_{n=1}^\infty \frac{1}{n^s}.
>>> from sympy import zeta
>>> from sympy.abc import s
>>> zeta(s, 1)
zeta(s)
>>> zeta(s)
zeta(s)
The Riemann zeta function can also be expressed using the Dirichlet eta
function:
>>> from sympy import dirichlet_eta
>>> zeta(s).rewrite(dirichlet_eta)
dirichlet_eta(s)/(1 - 2**(1 - s))
The Riemann zeta function at positive even integer and negative odd integer
values is related to the Bernoulli numbers:
>>> zeta(2)
pi**2/6
>>> zeta(4)
pi**4/90
>>> zeta(-1)
-1/12
The specific formulae are:
.. math:: \zeta(2n) = (-1)^{n+1} \frac{B_{2n} (2\pi)^{2n}}{2(2n)!}
.. math:: \zeta(-n) = -\frac{B_{n+1}}{n+1}
At negative even integers the Riemann zeta function is zero:
>>> zeta(-4)
0
No closed-form expressions are known at positive odd integers, but
numerical evaluation is possible:
>>> zeta(3).n()
1.20205690315959
The derivative of $\zeta(s, a)$ with respect to $a$ can be computed:
>>> from sympy.abc import a
>>> zeta(s, a).diff(a)
-s*zeta(s + 1, a)
However the derivative with respect to $s$ has no useful closed form
expression:
>>> zeta(s, a).diff(s)
Derivative(zeta(s, a), s)
The Hurwitz zeta function can be expressed in terms of the Lerch
transcendent, :class:`~.lerchphi`:
>>> from sympy import lerchphi
>>> zeta(s, a).rewrite(lerchphi)
lerchphi(1, s, a)
See Also
========
dirichlet_eta, lerchphi, polylog
References
==========
.. [1] http://dlmf.nist.gov/25.11
.. [2] https://en.wikipedia.org/wiki/Hurwitz_zeta_function
"""
@classmethod
def eval(cls, z, a_=None):
if a_ is None:
z, a = list(map(sympify, (z, 1)))
else:
z, a = list(map(sympify, (z, a_)))
if a.is_Number:
if a is S.NaN:
return S.NaN
elif a is S.One and a_ is not None:
return cls(z)
# TODO Should a == 0 return S.NaN as well?
if z.is_Number:
if z is S.NaN:
return S.NaN
elif z is S.Infinity:
return S.One
elif z.is_zero:
return S.Half - a
elif z is S.One:
return S.ComplexInfinity
if z.is_integer:
if a.is_Integer:
if z.is_negative:
zeta = (-1)**z * bernoulli(-z + 1)/(-z + 1)
elif z.is_even and z.is_positive:
B, F = bernoulli(z), factorial(z)
zeta = ((-1)**(z/2+1) * 2**(z - 1) * B * pi**z) / F
else:
return
if a.is_negative:
return zeta + harmonic(abs(a), z)
else:
return zeta - harmonic(a - 1, z)
if z.is_zero:
return S.Half - a
def _eval_rewrite_as_dirichlet_eta(self, s, a=1, **kwargs):
if a != 1:
return self
s = self.args[0]
return dirichlet_eta(s)/(1 - 2**(1 - s))
def _eval_rewrite_as_lerchphi(self, s, a=1, **kwargs):
return lerchphi(1, s, a)
def _eval_is_finite(self):
arg_is_one = (self.args[0] - 1).is_zero
if arg_is_one is not None:
return not arg_is_one
def fdiff(self, argindex=1):
if len(self.args) == 2:
s, a = self.args
else:
s, a = self.args + (1,)
if argindex == 2:
return -s*zeta(s + 1, a)
else:
raise ArgumentIndexError
class dirichlet_eta(Function):
r"""
Dirichlet eta function.
Explanation
===========
For $\operatorname{Re}(s) > 0$, this function is defined as
.. math:: \eta(s) = \sum_{n=1}^\infty \frac{(-1)^{n-1}}{n^s}.
It admits a unique analytic continuation to all of $\mathbb{C}$.
It is an entire, unbranched function.
Examples
========
The Dirichlet eta function is closely related to the Riemann zeta function:
>>> from sympy import dirichlet_eta, zeta
>>> from sympy.abc import s
>>> dirichlet_eta(s).rewrite(zeta)
(1 - 2**(1 - s))*zeta(s)
See Also
========
zeta
References
==========
.. [1] https://en.wikipedia.org/wiki/Dirichlet_eta_function
"""
@classmethod
def eval(cls, s):
if s == 1:
return log(2)
z = zeta(s)
if not z.has(zeta):
return (1 - 2**(1 - s))*z
def _eval_rewrite_as_zeta(self, s, **kwargs):
return (1 - 2**(1 - s)) * zeta(s)
class riemann_xi(Function):
r"""
Riemann Xi function.
Examples
========
The Riemann Xi function is closely related to the Riemann zeta function.
The zeros of Riemann Xi function are precisely the non-trivial zeros
of the zeta function.
>>> from sympy import riemann_xi, zeta
>>> from sympy.abc import s
>>> riemann_xi(s).rewrite(zeta)
s*(s - 1)*gamma(s/2)*zeta(s)/(2*pi**(s/2))
References
==========
.. [1] https://en.wikipedia.org/wiki/Riemann_Xi_function
"""
@classmethod
def eval(cls, s):
from sympy import gamma
z = zeta(s)
if s is S.Zero or s is S.One:
return S.Half
if not isinstance(z, zeta):
return s*(s - 1)*gamma(s/2)*z/(2*pi**(s/2))
def _eval_rewrite_as_zeta(self, s, **kwargs):
from sympy import gamma
return s*(s - 1)*gamma(s/2)*zeta(s)/(2*pi**(s/2))
class stieltjes(Function):
r"""
Represents Stieltjes constants, $\gamma_{k}$ that occur in
Laurent Series expansion of the Riemann zeta function.
Examples
========
>>> from sympy import stieltjes
>>> from sympy.abc import n, m
>>> stieltjes(n)
stieltjes(n)
The zero'th stieltjes constant:
>>> stieltjes(0)
EulerGamma
>>> stieltjes(0, 1)
EulerGamma
For generalized stieltjes constants:
>>> stieltjes(n, m)
stieltjes(n, m)
Constants are only defined for integers >= 0:
>>> stieltjes(-1)
zoo
References
==========
.. [1] https://en.wikipedia.org/wiki/Stieltjes_constants
"""
@classmethod
def eval(cls, n, a=None):
n = sympify(n)
if a is not None:
a = sympify(a)
if a is S.NaN:
return S.NaN
if a.is_Integer and a.is_nonpositive:
return S.ComplexInfinity
if n.is_Number:
if n is S.NaN:
return S.NaN
elif n < 0:
return S.ComplexInfinity
elif not n.is_Integer:
return S.ComplexInfinity
elif n is S.Zero and a in [None, 1]:
return S.EulerGamma
if n.is_extended_negative:
return S.ComplexInfinity
if n.is_zero and a in [None, 1]:
return S.EulerGamma
if n.is_integer == False:
return S.ComplexInfinity
|
8fef1e87074522b1a56f0329e449a84803d03ebbe9f7fddc193e9067043f9ea8 | from sympy.core import S, sympify, oo, diff
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.logic import fuzzy_not
from sympy.core.relational import Eq
from sympy.functions.elementary.complexes import im
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.special.delta_functions import Heaviside
###############################################################################
############################# SINGULARITY FUNCTION ############################
###############################################################################
class SingularityFunction(Function):
r"""
Singularity functions are a class of discontinuous functions.
Explanation
===========
Singularity functions take a variable, an offset, and an exponent as
arguments. These functions are represented using Macaulay brackets as:
SingularityFunction(x, a, n) := <x - a>^n
The singularity function will automatically evaluate to
``Derivative(DiracDelta(x - a), x, -n - 1)`` if ``n < 0``
and ``(x - a)**n*Heaviside(x - a)`` if ``n >= 0``.
Examples
========
>>> from sympy import SingularityFunction, diff, Piecewise, DiracDelta, Heaviside, Symbol
>>> from sympy.abc import x, a, n
>>> SingularityFunction(x, a, n)
SingularityFunction(x, a, n)
>>> y = Symbol('y', positive=True)
>>> n = Symbol('n', nonnegative=True)
>>> SingularityFunction(y, -10, n)
(y + 10)**n
>>> y = Symbol('y', negative=True)
>>> SingularityFunction(y, 10, n)
0
>>> SingularityFunction(x, 4, -1).subs(x, 4)
oo
>>> SingularityFunction(x, 10, -2).subs(x, 10)
oo
>>> SingularityFunction(4, 1, 5)
243
>>> diff(SingularityFunction(x, 1, 5) + SingularityFunction(x, 1, 4), x)
4*SingularityFunction(x, 1, 3) + 5*SingularityFunction(x, 1, 4)
>>> diff(SingularityFunction(x, 4, 0), x, 2)
SingularityFunction(x, 4, -2)
>>> SingularityFunction(x, 4, 5).rewrite(Piecewise)
Piecewise(((x - 4)**5, x - 4 > 0), (0, True))
>>> expr = SingularityFunction(x, a, n)
>>> y = Symbol('y', positive=True)
>>> n = Symbol('n', nonnegative=True)
>>> expr.subs({x: y, a: -10, n: n})
(y + 10)**n
The methods ``rewrite(DiracDelta)``, ``rewrite(Heaviside)``, and
``rewrite('HeavisideDiracDelta')`` returns the same output. One can use any
of these methods according to their choice.
>>> expr = SingularityFunction(x, 4, 5) + SingularityFunction(x, -3, -1) - SingularityFunction(x, 0, -2)
>>> expr.rewrite(Heaviside)
(x - 4)**5*Heaviside(x - 4, 1/2) + DiracDelta(x + 3) - DiracDelta(x, 1)
>>> expr.rewrite(DiracDelta)
(x - 4)**5*Heaviside(x - 4, 1/2) + DiracDelta(x + 3) - DiracDelta(x, 1)
>>> expr.rewrite('HeavisideDiracDelta')
(x - 4)**5*Heaviside(x - 4, 1/2) + DiracDelta(x + 3) - DiracDelta(x, 1)
See Also
========
DiracDelta, Heaviside
References
==========
.. [1] https://en.wikipedia.org/wiki/Singularity_function
"""
is_real = True
def fdiff(self, argindex=1):
"""
Returns the first derivative of a DiracDelta Function.
Explanation
===========
The difference between ``diff()`` and ``fdiff()`` is: ``diff()`` is the
user-level function and ``fdiff()`` is an object method. ``fdiff()`` is
a convenience method available in the ``Function`` class. It returns
the derivative of the function without considering the chain rule.
``diff(function, x)`` calls ``Function._eval_derivative`` which in turn
calls ``fdiff()`` internally to compute the derivative of the function.
"""
if argindex == 1:
x = sympify(self.args[0])
a = sympify(self.args[1])
n = sympify(self.args[2])
if n == 0 or n == -1:
return self.func(x, a, n-1)
elif n.is_positive:
return n*self.func(x, a, n-1)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, variable, offset, exponent):
"""
Returns a simplified form or a value of Singularity Function depending
on the argument passed by the object.
Explanation
===========
The ``eval()`` method is automatically called when the
``SingularityFunction`` class is about to be instantiated and it
returns either some simplified instance or the unevaluated instance
depending on the argument passed. In other words, ``eval()`` method is
not needed to be called explicitly, it is being called and evaluated
once the object is called.
Examples
========
>>> from sympy import SingularityFunction, Symbol, nan
>>> from sympy.abc import x, a, n
>>> SingularityFunction(x, a, n)
SingularityFunction(x, a, n)
>>> SingularityFunction(5, 3, 2)
4
>>> SingularityFunction(x, a, nan)
nan
>>> SingularityFunction(x, 3, 0).subs(x, 3)
1
>>> SingularityFunction(x, a, n).eval(3, 5, 1)
0
>>> SingularityFunction(x, a, n).eval(4, 1, 5)
243
>>> x = Symbol('x', positive = True)
>>> a = Symbol('a', negative = True)
>>> n = Symbol('n', nonnegative = True)
>>> SingularityFunction(x, a, n)
(-a + x)**n
>>> x = Symbol('x', negative = True)
>>> a = Symbol('a', positive = True)
>>> SingularityFunction(x, a, n)
0
"""
x = sympify(variable)
a = sympify(offset)
n = sympify(exponent)
shift = (x - a)
if fuzzy_not(im(shift).is_zero):
raise ValueError("Singularity Functions are defined only for Real Numbers.")
if fuzzy_not(im(n).is_zero):
raise ValueError("Singularity Functions are not defined for imaginary exponents.")
if shift is S.NaN or n is S.NaN:
return S.NaN
if (n + 2).is_negative:
raise ValueError("Singularity Functions are not defined for exponents less than -2.")
if shift.is_extended_negative:
return S.Zero
if n.is_nonnegative and shift.is_extended_nonnegative:
return (x - a)**n
if n == -1 or n == -2:
if shift.is_negative or shift.is_extended_positive:
return S.Zero
if shift.is_zero:
return S.Infinity
def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
'''
Converts a Singularity Function expression into its Piecewise form.
'''
x = self.args[0]
a = self.args[1]
n = sympify(self.args[2])
if n == -1 or n == -2:
return Piecewise((oo, Eq((x - a), 0)), (0, True))
elif n.is_nonnegative:
return Piecewise(((x - a)**n, (x - a) > 0), (0, True))
def _eval_rewrite_as_Heaviside(self, *args, **kwargs):
'''
Rewrites a Singularity Function expression using Heavisides and DiracDeltas.
'''
x = self.args[0]
a = self.args[1]
n = sympify(self.args[2])
if n == -2:
return diff(Heaviside(x - a), x.free_symbols.pop(), 2)
if n == -1:
return diff(Heaviside(x - a), x.free_symbols.pop(), 1)
if n.is_nonnegative:
return (x - a)**n*Heaviside(x - a)
_eval_rewrite_as_DiracDelta = _eval_rewrite_as_Heaviside
_eval_rewrite_as_HeavisideDiracDelta = _eval_rewrite_as_Heaviside
|
c02d17e4a3a52ee0d6cce5fd8141472e0a81b8503493814108a2a2416dcb68a4 | from functools import wraps
from sympy import Add, S, pi, I, Rational, Wild, cacheit, sympify
from sympy.core.function import Function, ArgumentIndexError, _mexpand
from sympy.core.logic import fuzzy_or, fuzzy_not
from sympy.core.power import Pow
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.trigonometric import sin, cos, csc, cot
from sympy.functions.elementary.integers import ceiling
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.miscellaneous import sqrt, root
from sympy.functions.elementary.complexes import re, im
from sympy.functions.special.gamma_functions import gamma, digamma
from sympy.functions.special.hyper import hyper
from sympy.polys.orthopolys import spherical_bessel_fn as fn
# TODO
# o Scorer functions G1 and G2
# o Asymptotic expansions
# These are possible, e.g. for fixed order, but since the bessel type
# functions are oscillatory they are not actually tractable at
# infinity, so this is not particularly useful right now.
# o Nicer series expansions.
# o More rewriting.
# o Add solvers to ode.py (or rather add solvers for the hypergeometric equation).
class BesselBase(Function):
"""
Abstract base class for Bessel-type functions.
This class is meant to reduce code duplication.
All Bessel-type functions can 1) be differentiated, with the derivatives
expressed in terms of similar functions, and 2) be rewritten in terms
of other Bessel-type functions.
Here, Bessel-type functions are assumed to have one complex parameter.
To use this base class, define class attributes ``_a`` and ``_b`` such that
``2*F_n' = -_a*F_{n+1} + b*F_{n-1}``.
"""
@property
def order(self):
""" The order of the Bessel-type function. """
return self.args[0]
@property
def argument(self):
""" The argument of the Bessel-type function. """
return self.args[1]
@classmethod
def eval(cls, nu, z):
return
def fdiff(self, argindex=2):
if argindex != 2:
raise ArgumentIndexError(self, argindex)
return (self._b/2 * self.__class__(self.order - 1, self.argument) -
self._a/2 * self.__class__(self.order + 1, self.argument))
def _eval_conjugate(self):
z = self.argument
if z.is_extended_negative is False:
return self.__class__(self.order.conjugate(), z.conjugate())
def _eval_is_meromorphic(self, x, a):
nu, z = self.order, self.argument
if nu.has(x):
return False
if not z._eval_is_meromorphic(x, a):
return None
z0 = z.subs(x, a)
if nu.is_integer:
if isinstance(self, (besselj, besseli, hn1, hn2, jn, yn)) or not nu.is_zero:
return fuzzy_not(z0.is_infinite)
return fuzzy_not(fuzzy_or([z0.is_zero, z0.is_infinite]))
def _eval_expand_func(self, **hints):
nu, z, f = self.order, self.argument, self.__class__
if nu.is_real:
if (nu - 1).is_positive:
return (-self._a*self._b*f(nu - 2, z)._eval_expand_func() +
2*self._a*(nu - 1)*f(nu - 1, z)._eval_expand_func()/z)
elif (nu + 1).is_negative:
return (2*self._b*(nu + 1)*f(nu + 1, z)._eval_expand_func()/z -
self._a*self._b*f(nu + 2, z)._eval_expand_func())
return self
def _eval_simplify(self, **kwargs):
from sympy.simplify.simplify import besselsimp
return besselsimp(self)
class besselj(BesselBase):
r"""
Bessel function of the first kind.
Explanation
===========
The Bessel $J$ function of order $\nu$ is defined to be the function
satisfying Bessel's differential equation
.. math ::
z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2}
+ z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu^2) w = 0,
with Laurent expansion
.. math ::
J_\nu(z) = z^\nu \left(\frac{1}{\Gamma(\nu + 1) 2^\nu} + O(z^2) \right),
if $\nu$ is not a negative integer. If $\nu=-n \in \mathbb{Z}_{<0}$
*is* a negative integer, then the definition is
.. math ::
J_{-n}(z) = (-1)^n J_n(z).
Examples
========
Create a Bessel function object:
>>> from sympy import besselj, jn
>>> from sympy.abc import z, n
>>> b = besselj(n, z)
Differentiate it:
>>> b.diff(z)
besselj(n - 1, z)/2 - besselj(n + 1, z)/2
Rewrite in terms of spherical Bessel functions:
>>> b.rewrite(jn)
sqrt(2)*sqrt(z)*jn(n - 1/2, z)/sqrt(pi)
Access the parameter and argument:
>>> b.order
n
>>> b.argument
z
See Also
========
bessely, besseli, besselk
References
==========
.. [1] Abramowitz, Milton; Stegun, Irene A., eds. (1965), "Chapter 9",
Handbook of Mathematical Functions with Formulas, Graphs, and
Mathematical Tables
.. [2] Luke, Y. L. (1969), The Special Functions and Their
Approximations, Volume 1
.. [3] https://en.wikipedia.org/wiki/Bessel_function
.. [4] http://functions.wolfram.com/Bessel-TypeFunctions/BesselJ/
"""
_a = S.One
_b = S.One
@classmethod
def eval(cls, nu, z):
if z.is_zero:
if nu.is_zero:
return S.One
elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive:
return S.Zero
elif re(nu).is_negative and not (nu.is_integer is True):
return S.ComplexInfinity
elif nu.is_imaginary:
return S.NaN
if z is S.Infinity or (z is S.NegativeInfinity):
return S.Zero
if z.could_extract_minus_sign():
return (z)**nu*(-z)**(-nu)*besselj(nu, -z)
if nu.is_integer:
if nu.could_extract_minus_sign():
return S.NegativeOne**(-nu)*besselj(-nu, z)
newz = z.extract_multiplicatively(I)
if newz: # NOTE we don't want to change the function if z==0
return I**(nu)*besseli(nu, newz)
# branch handling:
from sympy import unpolarify
if nu.is_integer:
newz = unpolarify(z)
if newz != z:
return besselj(nu, newz)
else:
newz, n = z.extract_branch_factor()
if n != 0:
return exp(2*n*pi*nu*I)*besselj(nu, newz)
nnu = unpolarify(nu)
if nu != nnu:
return besselj(nnu, z)
def _eval_rewrite_as_besseli(self, nu, z, **kwargs):
from sympy import polar_lift
return exp(I*pi*nu/2)*besseli(nu, polar_lift(-I)*z)
def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
if nu.is_integer is False:
return csc(pi*nu)*bessely(-nu, z) - cot(pi*nu)*bessely(nu, z)
def _eval_rewrite_as_jn(self, nu, z, **kwargs):
return sqrt(2*z/pi)*jn(nu - S.Half, self.argument)
def _eval_as_leading_term(self, x, cdir=0):
nu, z = self.args
arg = z.as_leading_term(x)
if x in arg.free_symbols:
return z**nu
else:
return self.func(*self.args)
def _eval_is_extended_real(self):
nu, z = self.args
if nu.is_integer and z.is_extended_real:
return True
def _eval_nseries(self, x, n, logx, cdir=0):
from sympy.series.order import Order
nu, z = self.args
# In case of powers less than 1, number of terms need to be computed
# separately to avoid repeated callings of _eval_nseries with wrong n
try:
_, exp = z.leadterm(x)
except (ValueError, NotImplementedError):
return self
if exp.is_positive:
newn = ceiling(n/exp)
o = Order(x**n, x)
r = (z/2)._eval_nseries(x, n, logx, cdir).removeO()
if r is S.Zero:
return o
t = (_mexpand(r**2) + o).removeO()
term = r**nu/gamma(nu + 1)
s = [term]
for k in range(1, (newn + 1)//2):
term *= -t/(k*(nu + k))
term = (_mexpand(term) + o).removeO()
s.append(term)
return Add(*s) + o
return super(besselj, self)._eval_nseries(x, n, logx, cdir)
def _sage_(self):
import sage.all as sage
return sage.bessel_J(self.args[0]._sage_(), self.args[1]._sage_())
class bessely(BesselBase):
r"""
Bessel function of the second kind.
Explanation
===========
The Bessel $Y$ function of order $\nu$ is defined as
.. math ::
Y_\nu(z) = \lim_{\mu \to \nu} \frac{J_\mu(z) \cos(\pi \mu)
- J_{-\mu}(z)}{\sin(\pi \mu)},
where $J_\mu(z)$ is the Bessel function of the first kind.
It is a solution to Bessel's equation, and linearly independent from
$J_\nu$.
Examples
========
>>> from sympy import bessely, yn
>>> from sympy.abc import z, n
>>> b = bessely(n, z)
>>> b.diff(z)
bessely(n - 1, z)/2 - bessely(n + 1, z)/2
>>> b.rewrite(yn)
sqrt(2)*sqrt(z)*yn(n - 1/2, z)/sqrt(pi)
See Also
========
besselj, besseli, besselk
References
==========
.. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselY/
"""
_a = S.One
_b = S.One
@classmethod
def eval(cls, nu, z):
if z.is_zero:
if nu.is_zero:
return S.NegativeInfinity
elif re(nu).is_zero is False:
return S.ComplexInfinity
elif re(nu).is_zero:
return S.NaN
if z is S.Infinity or z is S.NegativeInfinity:
return S.Zero
if nu.is_integer:
if nu.could_extract_minus_sign():
return S.NegativeOne**(-nu)*bessely(-nu, z)
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
if nu.is_integer is False:
return csc(pi*nu)*(cos(pi*nu)*besselj(nu, z) - besselj(-nu, z))
def _eval_rewrite_as_besseli(self, nu, z, **kwargs):
aj = self._eval_rewrite_as_besselj(*self.args)
if aj:
return aj.rewrite(besseli)
def _eval_rewrite_as_yn(self, nu, z, **kwargs):
return sqrt(2*z/pi) * yn(nu - S.Half, self.argument)
def _eval_as_leading_term(self, x, cdir=0):
nu, z = self.args
arg = z.as_leading_term(x)
if x in arg.free_symbols:
return z**nu
else:
return self.func(*self.args)
def _eval_is_extended_real(self):
nu, z = self.args
if nu.is_integer and z.is_positive:
return True
def _eval_nseries(self, x, n, logx, cdir=0):
from sympy.series.order import Order
nu, z = self.args
# In case of powers less than 1, number of terms need to be computed
# separately to avoid repeated callings of _eval_nseries with wrong n
try:
_, exp = z.leadterm(x)
except (ValueError, NotImplementedError):
return self
if exp.is_positive and nu.is_integer:
newn = ceiling(n/exp)
bn = besselj(nu, z)
a = ((2/pi)*log(z/2)*bn)._eval_nseries(x, n, logx, cdir)
b, c = [], []
o = Order(x**n, x)
r = (z/2)._eval_nseries(x, n, logx, cdir).removeO()
if r is S.Zero:
return o
t = (_mexpand(r**2) + o).removeO()
if nu > S.One:
term = r**(-nu)*factorial(nu - 1)/pi
b.append(term)
for k in range(1, nu - 1):
term *= t*(nu - k - 1)/k
term = (_mexpand(term) + o).removeO()
b.append(term)
p = r**nu/(pi*factorial(nu))
term = p*(digamma(nu + 1) - S.EulerGamma)
c.append(term)
for k in range(1, (newn + 1)//2):
p *= -t/(k*(k + nu))
p = (_mexpand(p) + o).removeO()
term = p*(digamma(k + nu + 1) + digamma(k + 1))
c.append(term)
return a - Add(*b) - Add(*c) # Order term comes from a
return super(bessely, self)._eval_nseries(x, n, logx, cdir)
def _sage_(self):
import sage.all as sage
return sage.bessel_Y(self.args[0]._sage_(), self.args[1]._sage_())
class besseli(BesselBase):
r"""
Modified Bessel function of the first kind.
Explanation
===========
The Bessel $I$ function is a solution to the modified Bessel equation
.. math ::
z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2}
+ z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 + \nu^2)^2 w = 0.
It can be defined as
.. math ::
I_\nu(z) = i^{-\nu} J_\nu(iz),
where $J_\nu(z)$ is the Bessel function of the first kind.
Examples
========
>>> from sympy import besseli
>>> from sympy.abc import z, n
>>> besseli(n, z).diff(z)
besseli(n - 1, z)/2 + besseli(n + 1, z)/2
See Also
========
besselj, bessely, besselk
References
==========
.. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselI/
"""
_a = -S.One
_b = S.One
@classmethod
def eval(cls, nu, z):
if z.is_zero:
if nu.is_zero:
return S.One
elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive:
return S.Zero
elif re(nu).is_negative and not (nu.is_integer is True):
return S.ComplexInfinity
elif nu.is_imaginary:
return S.NaN
if im(z) is S.Infinity or im(z) is S.NegativeInfinity:
return S.Zero
if z.could_extract_minus_sign():
return (z)**nu*(-z)**(-nu)*besseli(nu, -z)
if nu.is_integer:
if nu.could_extract_minus_sign():
return besseli(-nu, z)
newz = z.extract_multiplicatively(I)
if newz: # NOTE we don't want to change the function if z==0
return I**(-nu)*besselj(nu, -newz)
# branch handling:
from sympy import unpolarify
if nu.is_integer:
newz = unpolarify(z)
if newz != z:
return besseli(nu, newz)
else:
newz, n = z.extract_branch_factor()
if n != 0:
return exp(2*n*pi*nu*I)*besseli(nu, newz)
nnu = unpolarify(nu)
if nu != nnu:
return besseli(nnu, z)
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
from sympy import polar_lift
return exp(-I*pi*nu/2)*besselj(nu, polar_lift(I)*z)
def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
aj = self._eval_rewrite_as_besselj(*self.args)
if aj:
return aj.rewrite(bessely)
def _eval_rewrite_as_jn(self, nu, z, **kwargs):
return self._eval_rewrite_as_besselj(*self.args).rewrite(jn)
def _eval_is_extended_real(self):
nu, z = self.args
if nu.is_integer and z.is_extended_real:
return True
def _sage_(self):
import sage.all as sage
return sage.bessel_I(self.args[0]._sage_(), self.args[1]._sage_())
class besselk(BesselBase):
r"""
Modified Bessel function of the second kind.
Explanation
===========
The Bessel $K$ function of order $\nu$ is defined as
.. math ::
K_\nu(z) = \lim_{\mu \to \nu} \frac{\pi}{2}
\frac{I_{-\mu}(z) -I_\mu(z)}{\sin(\pi \mu)},
where $I_\mu(z)$ is the modified Bessel function of the first kind.
It is a solution of the modified Bessel equation, and linearly independent
from $Y_\nu$.
Examples
========
>>> from sympy import besselk
>>> from sympy.abc import z, n
>>> besselk(n, z).diff(z)
-besselk(n - 1, z)/2 - besselk(n + 1, z)/2
See Also
========
besselj, besseli, bessely
References
==========
.. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselK/
"""
_a = S.One
_b = -S.One
@classmethod
def eval(cls, nu, z):
if z.is_zero:
if nu.is_zero:
return S.Infinity
elif re(nu).is_zero is False:
return S.ComplexInfinity
elif re(nu).is_zero:
return S.NaN
if z in (S.Infinity, I*S.Infinity, I*S.NegativeInfinity):
return S.Zero
if nu.is_integer:
if nu.could_extract_minus_sign():
return besselk(-nu, z)
def _eval_rewrite_as_besseli(self, nu, z, **kwargs):
if nu.is_integer is False:
return pi*csc(pi*nu)*(besseli(-nu, z) - besseli(nu, z))/2
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
ai = self._eval_rewrite_as_besseli(*self.args)
if ai:
return ai.rewrite(besselj)
def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
aj = self._eval_rewrite_as_besselj(*self.args)
if aj:
return aj.rewrite(bessely)
def _eval_rewrite_as_yn(self, nu, z, **kwargs):
ay = self._eval_rewrite_as_bessely(*self.args)
if ay:
return ay.rewrite(yn)
def _eval_is_extended_real(self):
nu, z = self.args
if nu.is_integer and z.is_positive:
return True
def _sage_(self):
import sage.all as sage
return sage.bessel_K(self.args[0]._sage_(), self.args[1]._sage_())
class hankel1(BesselBase):
r"""
Hankel function of the first kind.
Explanation
===========
This function is defined as
.. math ::
H_\nu^{(1)} = J_\nu(z) + iY_\nu(z),
where $J_\nu(z)$ is the Bessel function of the first kind, and
$Y_\nu(z)$ is the Bessel function of the second kind.
It is a solution to Bessel's equation.
Examples
========
>>> from sympy import hankel1
>>> from sympy.abc import z, n
>>> hankel1(n, z).diff(z)
hankel1(n - 1, z)/2 - hankel1(n + 1, z)/2
See Also
========
hankel2, besselj, bessely
References
==========
.. [1] http://functions.wolfram.com/Bessel-TypeFunctions/HankelH1/
"""
_a = S.One
_b = S.One
def _eval_conjugate(self):
z = self.argument
if z.is_extended_negative is False:
return hankel2(self.order.conjugate(), z.conjugate())
class hankel2(BesselBase):
r"""
Hankel function of the second kind.
Explanation
===========
This function is defined as
.. math ::
H_\nu^{(2)} = J_\nu(z) - iY_\nu(z),
where $J_\nu(z)$ is the Bessel function of the first kind, and
$Y_\nu(z)$ is the Bessel function of the second kind.
It is a solution to Bessel's equation, and linearly independent from
$H_\nu^{(1)}$.
Examples
========
>>> from sympy import hankel2
>>> from sympy.abc import z, n
>>> hankel2(n, z).diff(z)
hankel2(n - 1, z)/2 - hankel2(n + 1, z)/2
See Also
========
hankel1, besselj, bessely
References
==========
.. [1] http://functions.wolfram.com/Bessel-TypeFunctions/HankelH2/
"""
_a = S.One
_b = S.One
def _eval_conjugate(self):
z = self.argument
if z.is_extended_negative is False:
return hankel1(self.order.conjugate(), z.conjugate())
def assume_integer_order(fn):
@wraps(fn)
def g(self, nu, z):
if nu.is_integer:
return fn(self, nu, z)
return g
class SphericalBesselBase(BesselBase):
"""
Base class for spherical Bessel functions.
These are thin wrappers around ordinary Bessel functions,
since spherical Bessel functions differ from the ordinary
ones just by a slight change in order.
To use this class, define the ``_rewrite()`` and ``_expand()`` methods.
"""
def _expand(self, **hints):
""" Expand self into a polynomial. Nu is guaranteed to be Integer. """
raise NotImplementedError('expansion')
def _rewrite(self):
""" Rewrite self in terms of ordinary Bessel functions. """
raise NotImplementedError('rewriting')
def _eval_expand_func(self, **hints):
if self.order.is_Integer:
return self._expand(**hints)
return self
def _eval_evalf(self, prec):
if self.order.is_Integer:
return self._rewrite()._eval_evalf(prec)
def fdiff(self, argindex=2):
if argindex != 2:
raise ArgumentIndexError(self, argindex)
return self.__class__(self.order - 1, self.argument) - \
self * (self.order + 1)/self.argument
def _jn(n, z):
return fn(n, z)*sin(z) + (-1)**(n + 1)*fn(-n - 1, z)*cos(z)
def _yn(n, z):
# (-1)**(n + 1) * _jn(-n - 1, z)
return (-1)**(n + 1) * fn(-n - 1, z)*sin(z) - fn(n, z)*cos(z)
class jn(SphericalBesselBase):
r"""
Spherical Bessel function of the first kind.
Explanation
===========
This function is a solution to the spherical Bessel equation
.. math ::
z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2}
+ 2z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu(\nu + 1)) w = 0.
It can be defined as
.. math ::
j_\nu(z) = \sqrt{\frac{\pi}{2z}} J_{\nu + \frac{1}{2}}(z),
where $J_\nu(z)$ is the Bessel function of the first kind.
The spherical Bessel functions of integral order are
calculated using the formula:
.. math:: j_n(z) = f_n(z) \sin{z} + (-1)^{n+1} f_{-n-1}(z) \cos{z},
where the coefficients $f_n(z)$ are available as
:func:`sympy.polys.orthopolys.spherical_bessel_fn`.
Examples
========
>>> from sympy import Symbol, jn, sin, cos, expand_func, besselj, bessely
>>> z = Symbol("z")
>>> nu = Symbol("nu", integer=True)
>>> print(expand_func(jn(0, z)))
sin(z)/z
>>> expand_func(jn(1, z)) == sin(z)/z**2 - cos(z)/z
True
>>> expand_func(jn(3, z))
(-6/z**2 + 15/z**4)*sin(z) + (1/z - 15/z**3)*cos(z)
>>> jn(nu, z).rewrite(besselj)
sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(nu + 1/2, z)/2
>>> jn(nu, z).rewrite(bessely)
(-1)**nu*sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(-nu - 1/2, z)/2
>>> jn(2, 5.2+0.3j).evalf(20)
0.099419756723640344491 - 0.054525080242173562897*I
See Also
========
besselj, bessely, besselk, yn
References
==========
.. [1] http://dlmf.nist.gov/10.47
"""
@classmethod
def eval(cls, nu, z):
if z.is_zero:
if nu.is_zero:
return S.One
elif nu.is_integer:
if nu.is_positive:
return S.Zero
else:
return S.ComplexInfinity
if z in (S.NegativeInfinity, S.Infinity):
return S.Zero
def _rewrite(self):
return self._eval_rewrite_as_besselj(self.order, self.argument)
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
return sqrt(pi/(2*z)) * besselj(nu + S.Half, z)
def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
return (-1)**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z)
def _eval_rewrite_as_yn(self, nu, z, **kwargs):
return (-1)**(nu) * yn(-nu - 1, z)
def _expand(self, **hints):
return _jn(self.order, self.argument)
class yn(SphericalBesselBase):
r"""
Spherical Bessel function of the second kind.
Explanation
===========
This function is another solution to the spherical Bessel equation, and
linearly independent from $j_n$. It can be defined as
.. math ::
y_\nu(z) = \sqrt{\frac{\pi}{2z}} Y_{\nu + \frac{1}{2}}(z),
where $Y_\nu(z)$ is the Bessel function of the second kind.
For integral orders $n$, $y_n$ is calculated using the formula:
.. math:: y_n(z) = (-1)^{n+1} j_{-n-1}(z)
Examples
========
>>> from sympy import Symbol, yn, sin, cos, expand_func, besselj, bessely
>>> z = Symbol("z")
>>> nu = Symbol("nu", integer=True)
>>> print(expand_func(yn(0, z)))
-cos(z)/z
>>> expand_func(yn(1, z)) == -cos(z)/z**2-sin(z)/z
True
>>> yn(nu, z).rewrite(besselj)
(-1)**(nu + 1)*sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(-nu - 1/2, z)/2
>>> yn(nu, z).rewrite(bessely)
sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(nu + 1/2, z)/2
>>> yn(2, 5.2+0.3j).evalf(20)
0.18525034196069722536 + 0.014895573969924817587*I
See Also
========
besselj, bessely, besselk, jn
References
==========
.. [1] http://dlmf.nist.gov/10.47
"""
def _rewrite(self):
return self._eval_rewrite_as_bessely(self.order, self.argument)
@assume_integer_order
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
return (-1)**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z)
@assume_integer_order
def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
return sqrt(pi/(2*z)) * bessely(nu + S.Half, z)
def _eval_rewrite_as_jn(self, nu, z, **kwargs):
return (-1)**(nu + 1) * jn(-nu - 1, z)
def _expand(self, **hints):
return _yn(self.order, self.argument)
class SphericalHankelBase(SphericalBesselBase):
def _rewrite(self):
return self._eval_rewrite_as_besselj(self.order, self.argument)
@assume_integer_order
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
# jn +- I*yn
# jn as beeselj: sqrt(pi/(2*z)) * besselj(nu + S.Half, z)
# yn as besselj: (-1)**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z)
hks = self._hankel_kind_sign
return sqrt(pi/(2*z))*(besselj(nu + S.Half, z) +
hks*I*(-1)**(nu+1)*besselj(-nu - S.Half, z))
@assume_integer_order
def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
# jn +- I*yn
# jn as bessely: (-1)**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z)
# yn as bessely: sqrt(pi/(2*z)) * bessely(nu + S.Half, z)
hks = self._hankel_kind_sign
return sqrt(pi/(2*z))*((-1)**nu*bessely(-nu - S.Half, z) +
hks*I*bessely(nu + S.Half, z))
def _eval_rewrite_as_yn(self, nu, z, **kwargs):
hks = self._hankel_kind_sign
return jn(nu, z).rewrite(yn) + hks*I*yn(nu, z)
def _eval_rewrite_as_jn(self, nu, z, **kwargs):
hks = self._hankel_kind_sign
return jn(nu, z) + hks*I*yn(nu, z).rewrite(jn)
def _eval_expand_func(self, **hints):
if self.order.is_Integer:
return self._expand(**hints)
else:
nu = self.order
z = self.argument
hks = self._hankel_kind_sign
return jn(nu, z) + hks*I*yn(nu, z)
def _expand(self, **hints):
n = self.order
z = self.argument
hks = self._hankel_kind_sign
# fully expanded version
# return ((fn(n, z) * sin(z) +
# (-1)**(n + 1) * fn(-n - 1, z) * cos(z)) + # jn
# (hks * I * (-1)**(n + 1) *
# (fn(-n - 1, z) * hk * I * sin(z) +
# (-1)**(-n) * fn(n, z) * I * cos(z))) # +-I*yn
# )
return (_jn(n, z) + hks*I*_yn(n, z)).expand()
class hn1(SphericalHankelBase):
r"""
Spherical Hankel function of the first kind.
Explanation
===========
This function is defined as
.. math:: h_\nu^(1)(z) = j_\nu(z) + i y_\nu(z),
where $j_\nu(z)$ and $y_\nu(z)$ are the spherical
Bessel function of the first and second kinds.
For integral orders $n$, $h_n^(1)$ is calculated using the formula:
.. math:: h_n^(1)(z) = j_{n}(z) + i (-1)^{n+1} j_{-n-1}(z)
Examples
========
>>> from sympy import Symbol, hn1, hankel1, expand_func, yn, jn
>>> z = Symbol("z")
>>> nu = Symbol("nu", integer=True)
>>> print(expand_func(hn1(nu, z)))
jn(nu, z) + I*yn(nu, z)
>>> print(expand_func(hn1(0, z)))
sin(z)/z - I*cos(z)/z
>>> print(expand_func(hn1(1, z)))
-I*sin(z)/z - cos(z)/z + sin(z)/z**2 - I*cos(z)/z**2
>>> hn1(nu, z).rewrite(jn)
(-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z)
>>> hn1(nu, z).rewrite(yn)
(-1)**nu*yn(-nu - 1, z) + I*yn(nu, z)
>>> hn1(nu, z).rewrite(hankel1)
sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel1(nu, z)/2
See Also
========
hn2, jn, yn, hankel1, hankel2
References
==========
.. [1] http://dlmf.nist.gov/10.47
"""
_hankel_kind_sign = S.One
@assume_integer_order
def _eval_rewrite_as_hankel1(self, nu, z, **kwargs):
return sqrt(pi/(2*z))*hankel1(nu, z)
class hn2(SphericalHankelBase):
r"""
Spherical Hankel function of the second kind.
Explanation
===========
This function is defined as
.. math:: h_\nu^(2)(z) = j_\nu(z) - i y_\nu(z),
where $j_\nu(z)$ and $y_\nu(z)$ are the spherical
Bessel function of the first and second kinds.
For integral orders $n$, $h_n^(2)$ is calculated using the formula:
.. math:: h_n^(2)(z) = j_{n} - i (-1)^{n+1} j_{-n-1}(z)
Examples
========
>>> from sympy import Symbol, hn2, hankel2, expand_func, jn, yn
>>> z = Symbol("z")
>>> nu = Symbol("nu", integer=True)
>>> print(expand_func(hn2(nu, z)))
jn(nu, z) - I*yn(nu, z)
>>> print(expand_func(hn2(0, z)))
sin(z)/z + I*cos(z)/z
>>> print(expand_func(hn2(1, z)))
I*sin(z)/z - cos(z)/z + sin(z)/z**2 + I*cos(z)/z**2
>>> hn2(nu, z).rewrite(hankel2)
sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel2(nu, z)/2
>>> hn2(nu, z).rewrite(jn)
-(-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z)
>>> hn2(nu, z).rewrite(yn)
(-1)**nu*yn(-nu - 1, z) - I*yn(nu, z)
See Also
========
hn1, jn, yn, hankel1, hankel2
References
==========
.. [1] http://dlmf.nist.gov/10.47
"""
_hankel_kind_sign = -S.One
@assume_integer_order
def _eval_rewrite_as_hankel2(self, nu, z, **kwargs):
return sqrt(pi/(2*z))*hankel2(nu, z)
def jn_zeros(n, k, method="sympy", dps=15):
"""
Zeros of the spherical Bessel function of the first kind.
Explanation
===========
This returns an array of zeros of $jn$ up to the $k$-th zero.
* method = "sympy": uses `mpmath.besseljzero
<http://mpmath.org/doc/current/functions/bessel.html#mpmath.besseljzero>`_
* method = "scipy": uses the
`SciPy's sph_jn <http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.jn_zeros.html>`_
and
`newton <http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html>`_
to find all
roots, which is faster than computing the zeros using a general
numerical solver, but it requires SciPy and only works with low
precision floating point numbers. (The function used with
method="sympy" is a recent addition to mpmath; before that a general
solver was used.)
Examples
========
>>> from sympy import jn_zeros
>>> jn_zeros(2, 4, dps=5)
[5.7635, 9.095, 12.323, 15.515]
See Also
========
jn, yn, besselj, besselk, bessely
Parameters
==========
n : integer
order of Bessel function
k : integer
number of zeros to return
"""
from math import pi
if method == "sympy":
from mpmath import besseljzero
from mpmath.libmp.libmpf import dps_to_prec
from sympy import Expr
prec = dps_to_prec(dps)
return [Expr._from_mpmath(besseljzero(S(n + 0.5)._to_mpmath(prec),
int(l)), prec)
for l in range(1, k + 1)]
elif method == "scipy":
from scipy.optimize import newton
try:
from scipy.special import spherical_jn
f = lambda x: spherical_jn(n, x)
except ImportError:
from scipy.special import sph_jn
f = lambda x: sph_jn(n, x)[0][-1]
else:
raise NotImplementedError("Unknown method.")
def solver(f, x):
if method == "scipy":
root = newton(f, x)
else:
raise NotImplementedError("Unknown method.")
return root
# we need to approximate the position of the first root:
root = n + pi
# determine the first root exactly:
root = solver(f, root)
roots = [root]
for i in range(k - 1):
# estimate the position of the next root using the last root + pi:
root = solver(f, root + pi)
roots.append(root)
return roots
class AiryBase(Function):
"""
Abstract base class for Airy functions.
This class is meant to reduce code duplication.
"""
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def _eval_is_extended_real(self):
return self.args[0].is_extended_real
def as_real_imag(self, deep=True, **hints):
z = self.args[0]
zc = z.conjugate()
f = self.func
u = (f(z)+f(zc))/2
v = I*(f(zc)-f(z))/2
return u, v
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
class airyai(AiryBase):
r"""
The Airy function $\operatorname{Ai}$ of the first kind.
Explanation
===========
The Airy function $\operatorname{Ai}(z)$ is defined to be the function
satisfying Airy's differential equation
.. math::
\frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = 0.
Equivalently, for real $z$
.. math::
\operatorname{Ai}(z) := \frac{1}{\pi}
\int_0^\infty \cos\left(\frac{t^3}{3} + z t\right) \mathrm{d}t.
Examples
========
Create an Airy function object:
>>> from sympy import airyai
>>> from sympy.abc import z
>>> airyai(z)
airyai(z)
Several special values are known:
>>> airyai(0)
3**(1/3)/(3*gamma(2/3))
>>> from sympy import oo
>>> airyai(oo)
0
>>> airyai(-oo)
0
The Airy function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(airyai(z))
airyai(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(airyai(z), z)
airyaiprime(z)
>>> diff(airyai(z), z, 2)
z*airyai(z)
Series expansion is also supported:
>>> from sympy import series
>>> series(airyai(z), z, 0, 3)
3**(5/6)*gamma(1/3)/(6*pi) - 3**(1/6)*z*gamma(2/3)/(2*pi) + O(z**3)
We can numerically evaluate the Airy function to arbitrary precision
on the whole complex plane:
>>> airyai(-2).evalf(50)
0.22740742820168557599192443603787379946077222541710
Rewrite $\operatorname{Ai}(z)$ in terms of hypergeometric functions:
>>> from sympy import hyper
>>> airyai(z).rewrite(hyper)
-3**(2/3)*z*hyper((), (4/3,), z**3/9)/(3*gamma(1/3)) + 3**(1/3)*hyper((), (2/3,), z**3/9)/(3*gamma(2/3))
See Also
========
airybi: Airy function of the second kind.
airyaiprime: Derivative of the Airy function of the first kind.
airybiprime: Derivative of the Airy function of the second kind.
References
==========
.. [1] https://en.wikipedia.org/wiki/Airy_function
.. [2] http://dlmf.nist.gov/9
.. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions
.. [4] http://mathworld.wolfram.com/AiryFunctions.html
"""
nargs = 1
unbranched = True
@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 S.One / (3**Rational(2, 3) * gamma(Rational(2, 3)))
if arg.is_zero:
return S.One / (3**Rational(2, 3) * gamma(Rational(2, 3)))
def fdiff(self, argindex=1):
if argindex == 1:
return airyaiprime(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 1:
p = previous_terms[-1]
return ((3**Rational(1, 3)*x)**(-n)*(3**Rational(1, 3)*x)**(n + 1)*sin(pi*(n*Rational(2, 3) + Rational(4, 3)))*factorial(n) *
gamma(n/3 + Rational(2, 3))/(sin(pi*(n*Rational(2, 3) + Rational(2, 3)))*factorial(n + 1)*gamma(n/3 + Rational(1, 3))) * p)
else:
return (S.One/(3**Rational(2, 3)*pi) * gamma((n+S.One)/S(3)) * sin(2*pi*(n+S.One)/S(3)) /
factorial(n) * (root(3, 3)*x)**n)
def _eval_rewrite_as_besselj(self, z, **kwargs):
ot = Rational(1, 3)
tt = Rational(2, 3)
a = Pow(-z, Rational(3, 2))
if re(z).is_negative:
return ot*sqrt(-z) * (besselj(-ot, tt*a) + besselj(ot, tt*a))
def _eval_rewrite_as_besseli(self, z, **kwargs):
ot = Rational(1, 3)
tt = Rational(2, 3)
a = Pow(z, Rational(3, 2))
if re(z).is_positive:
return ot*sqrt(z) * (besseli(-ot, tt*a) - besseli(ot, tt*a))
else:
return ot*(Pow(a, ot)*besseli(-ot, tt*a) - z*Pow(a, -ot)*besseli(ot, tt*a))
def _eval_rewrite_as_hyper(self, z, **kwargs):
pf1 = S.One / (3**Rational(2, 3)*gamma(Rational(2, 3)))
pf2 = z / (root(3, 3)*gamma(Rational(1, 3)))
return pf1 * hyper([], [Rational(2, 3)], z**3/9) - pf2 * hyper([], [Rational(4, 3)], z**3/9)
def _eval_expand_func(self, **hints):
arg = self.args[0]
symbs = arg.free_symbols
if len(symbs) == 1:
z = symbs.pop()
c = Wild("c", exclude=[z])
d = Wild("d", exclude=[z])
m = Wild("m", exclude=[z])
n = Wild("n", exclude=[z])
M = arg.match(c*(d*z**n)**m)
if M is not None:
m = M[m]
# The transformation is given by 03.05.16.0001.01
# http://functions.wolfram.com/Bessel-TypeFunctions/AiryAi/16/01/01/0001/
if (3*m).is_integer:
c = M[c]
d = M[d]
n = M[n]
pf = (d * z**n)**m / (d**m * z**(m*n))
newarg = c * d**m * z**(m*n)
return S.Half * ((pf + S.One)*airyai(newarg) - (pf - S.One)/sqrt(3)*airybi(newarg))
class airybi(AiryBase):
r"""
The Airy function $\operatorname{Bi}$ of the second kind.
Explanation
===========
The Airy function $\operatorname{Bi}(z)$ is defined to be the function
satisfying Airy's differential equation
.. math::
\frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = 0.
Equivalently, for real $z$
.. math::
\operatorname{Bi}(z) := \frac{1}{\pi}
\int_0^\infty
\exp\left(-\frac{t^3}{3} + z t\right)
+ \sin\left(\frac{t^3}{3} + z t\right) \mathrm{d}t.
Examples
========
Create an Airy function object:
>>> from sympy import airybi
>>> from sympy.abc import z
>>> airybi(z)
airybi(z)
Several special values are known:
>>> airybi(0)
3**(5/6)/(3*gamma(2/3))
>>> from sympy import oo
>>> airybi(oo)
oo
>>> airybi(-oo)
0
The Airy function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(airybi(z))
airybi(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(airybi(z), z)
airybiprime(z)
>>> diff(airybi(z), z, 2)
z*airybi(z)
Series expansion is also supported:
>>> from sympy import series
>>> series(airybi(z), z, 0, 3)
3**(1/3)*gamma(1/3)/(2*pi) + 3**(2/3)*z*gamma(2/3)/(2*pi) + O(z**3)
We can numerically evaluate the Airy function to arbitrary precision
on the whole complex plane:
>>> airybi(-2).evalf(50)
-0.41230258795639848808323405461146104203453483447240
Rewrite $\operatorname{Bi}(z)$ in terms of hypergeometric functions:
>>> from sympy import hyper
>>> airybi(z).rewrite(hyper)
3**(1/6)*z*hyper((), (4/3,), z**3/9)/gamma(1/3) + 3**(5/6)*hyper((), (2/3,), z**3/9)/(3*gamma(2/3))
See Also
========
airyai: Airy function of the first kind.
airyaiprime: Derivative of the Airy function of the first kind.
airybiprime: Derivative of the Airy function of the second kind.
References
==========
.. [1] https://en.wikipedia.org/wiki/Airy_function
.. [2] http://dlmf.nist.gov/9
.. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions
.. [4] http://mathworld.wolfram.com/AiryFunctions.html
"""
nargs = 1
unbranched = True
@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
elif arg is S.NegativeInfinity:
return S.Zero
elif arg.is_zero:
return S.One / (3**Rational(1, 6) * gamma(Rational(2, 3)))
if arg.is_zero:
return S.One / (3**Rational(1, 6) * gamma(Rational(2, 3)))
def fdiff(self, argindex=1):
if argindex == 1:
return airybiprime(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 1:
p = previous_terms[-1]
return (3**Rational(1, 3)*x * Abs(sin(2*pi*(n + S.One)/S(3))) * factorial((n - S.One)/S(3)) /
((n + S.One) * Abs(cos(2*pi*(n + S.Half)/S(3))) * factorial((n - 2)/S(3))) * p)
else:
return (S.One/(root(3, 6)*pi) * gamma((n + S.One)/S(3)) * Abs(sin(2*pi*(n + S.One)/S(3))) /
factorial(n) * (root(3, 3)*x)**n)
def _eval_rewrite_as_besselj(self, z, **kwargs):
ot = Rational(1, 3)
tt = Rational(2, 3)
a = Pow(-z, Rational(3, 2))
if re(z).is_negative:
return sqrt(-z/3) * (besselj(-ot, tt*a) - besselj(ot, tt*a))
def _eval_rewrite_as_besseli(self, z, **kwargs):
ot = Rational(1, 3)
tt = Rational(2, 3)
a = Pow(z, Rational(3, 2))
if re(z).is_positive:
return sqrt(z)/sqrt(3) * (besseli(-ot, tt*a) + besseli(ot, tt*a))
else:
b = Pow(a, ot)
c = Pow(a, -ot)
return sqrt(ot)*(b*besseli(-ot, tt*a) + z*c*besseli(ot, tt*a))
def _eval_rewrite_as_hyper(self, z, **kwargs):
pf1 = S.One / (root(3, 6)*gamma(Rational(2, 3)))
pf2 = z*root(3, 6) / gamma(Rational(1, 3))
return pf1 * hyper([], [Rational(2, 3)], z**3/9) + pf2 * hyper([], [Rational(4, 3)], z**3/9)
def _eval_expand_func(self, **hints):
arg = self.args[0]
symbs = arg.free_symbols
if len(symbs) == 1:
z = symbs.pop()
c = Wild("c", exclude=[z])
d = Wild("d", exclude=[z])
m = Wild("m", exclude=[z])
n = Wild("n", exclude=[z])
M = arg.match(c*(d*z**n)**m)
if M is not None:
m = M[m]
# The transformation is given by 03.06.16.0001.01
# http://functions.wolfram.com/Bessel-TypeFunctions/AiryBi/16/01/01/0001/
if (3*m).is_integer:
c = M[c]
d = M[d]
n = M[n]
pf = (d * z**n)**m / (d**m * z**(m*n))
newarg = c * d**m * z**(m*n)
return S.Half * (sqrt(3)*(S.One - pf)*airyai(newarg) + (S.One + pf)*airybi(newarg))
class airyaiprime(AiryBase):
r"""
The derivative $\operatorname{Ai}^\prime$ of the Airy function of the first
kind.
Explanation
===========
The Airy function $\operatorname{Ai}^\prime(z)$ is defined to be the
function
.. math::
\operatorname{Ai}^\prime(z) := \frac{\mathrm{d} \operatorname{Ai}(z)}{\mathrm{d} z}.
Examples
========
Create an Airy function object:
>>> from sympy import airyaiprime
>>> from sympy.abc import z
>>> airyaiprime(z)
airyaiprime(z)
Several special values are known:
>>> airyaiprime(0)
-3**(2/3)/(3*gamma(1/3))
>>> from sympy import oo
>>> airyaiprime(oo)
0
The Airy function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(airyaiprime(z))
airyaiprime(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(airyaiprime(z), z)
z*airyai(z)
>>> diff(airyaiprime(z), z, 2)
z*airyaiprime(z) + airyai(z)
Series expansion is also supported:
>>> from sympy import series
>>> series(airyaiprime(z), z, 0, 3)
-3**(2/3)/(3*gamma(1/3)) + 3**(1/3)*z**2/(6*gamma(2/3)) + O(z**3)
We can numerically evaluate the Airy function to arbitrary precision
on the whole complex plane:
>>> airyaiprime(-2).evalf(50)
0.61825902074169104140626429133247528291577794512415
Rewrite $\operatorname{Ai}^\prime(z)$ in terms of hypergeometric functions:
>>> from sympy import hyper
>>> airyaiprime(z).rewrite(hyper)
3**(1/3)*z**2*hyper((), (5/3,), z**3/9)/(6*gamma(2/3)) - 3**(2/3)*hyper((), (1/3,), z**3/9)/(3*gamma(1/3))
See Also
========
airyai: Airy function of the first kind.
airybi: Airy function of the second kind.
airybiprime: Derivative of the Airy function of the second kind.
References
==========
.. [1] https://en.wikipedia.org/wiki/Airy_function
.. [2] http://dlmf.nist.gov/9
.. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions
.. [4] http://mathworld.wolfram.com/AiryFunctions.html
"""
nargs = 1
unbranched = True
@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
if arg.is_zero:
return S.NegativeOne / (3**Rational(1, 3) * gamma(Rational(1, 3)))
def fdiff(self, argindex=1):
if argindex == 1:
return self.args[0]*airyai(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
def _eval_evalf(self, prec):
from mpmath import mp, workprec
from sympy import Expr
z = self.args[0]._to_mpmath(prec)
with workprec(prec):
res = mp.airyai(z, derivative=1)
return Expr._from_mpmath(res, prec)
def _eval_rewrite_as_besselj(self, z, **kwargs):
tt = Rational(2, 3)
a = Pow(-z, Rational(3, 2))
if re(z).is_negative:
return z/3 * (besselj(-tt, tt*a) - besselj(tt, tt*a))
def _eval_rewrite_as_besseli(self, z, **kwargs):
ot = Rational(1, 3)
tt = Rational(2, 3)
a = tt * Pow(z, Rational(3, 2))
if re(z).is_positive:
return z/3 * (besseli(tt, a) - besseli(-tt, a))
else:
a = Pow(z, Rational(3, 2))
b = Pow(a, tt)
c = Pow(a, -tt)
return ot * (z**2*c*besseli(tt, tt*a) - b*besseli(-ot, tt*a))
def _eval_rewrite_as_hyper(self, z, **kwargs):
pf1 = z**2 / (2*3**Rational(2, 3)*gamma(Rational(2, 3)))
pf2 = 1 / (root(3, 3)*gamma(Rational(1, 3)))
return pf1 * hyper([], [Rational(5, 3)], z**3/9) - pf2 * hyper([], [Rational(1, 3)], z**3/9)
def _eval_expand_func(self, **hints):
arg = self.args[0]
symbs = arg.free_symbols
if len(symbs) == 1:
z = symbs.pop()
c = Wild("c", exclude=[z])
d = Wild("d", exclude=[z])
m = Wild("m", exclude=[z])
n = Wild("n", exclude=[z])
M = arg.match(c*(d*z**n)**m)
if M is not None:
m = M[m]
# The transformation is in principle
# given by 03.07.16.0001.01 but note
# that there is an error in this formula.
# http://functions.wolfram.com/Bessel-TypeFunctions/AiryAiPrime/16/01/01/0001/
if (3*m).is_integer:
c = M[c]
d = M[d]
n = M[n]
pf = (d**m * z**(n*m)) / (d * z**n)**m
newarg = c * d**m * z**(n*m)
return S.Half * ((pf + S.One)*airyaiprime(newarg) + (pf - S.One)/sqrt(3)*airybiprime(newarg))
class airybiprime(AiryBase):
r"""
The derivative $\operatorname{Bi}^\prime$ of the Airy function of the first
kind.
Explanation
===========
The Airy function $\operatorname{Bi}^\prime(z)$ is defined to be the
function
.. math::
\operatorname{Bi}^\prime(z) := \frac{\mathrm{d} \operatorname{Bi}(z)}{\mathrm{d} z}.
Examples
========
Create an Airy function object:
>>> from sympy import airybiprime
>>> from sympy.abc import z
>>> airybiprime(z)
airybiprime(z)
Several special values are known:
>>> airybiprime(0)
3**(1/6)/gamma(1/3)
>>> from sympy import oo
>>> airybiprime(oo)
oo
>>> airybiprime(-oo)
0
The Airy function obeys the mirror symmetry:
>>> from sympy import conjugate
>>> conjugate(airybiprime(z))
airybiprime(conjugate(z))
Differentiation with respect to $z$ is supported:
>>> from sympy import diff
>>> diff(airybiprime(z), z)
z*airybi(z)
>>> diff(airybiprime(z), z, 2)
z*airybiprime(z) + airybi(z)
Series expansion is also supported:
>>> from sympy import series
>>> series(airybiprime(z), z, 0, 3)
3**(1/6)/gamma(1/3) + 3**(5/6)*z**2/(6*gamma(2/3)) + O(z**3)
We can numerically evaluate the Airy function to arbitrary precision
on the whole complex plane:
>>> airybiprime(-2).evalf(50)
0.27879516692116952268509756941098324140300059345163
Rewrite $\operatorname{Bi}^\prime(z)$ in terms of hypergeometric functions:
>>> from sympy import hyper
>>> airybiprime(z).rewrite(hyper)
3**(5/6)*z**2*hyper((), (5/3,), z**3/9)/(6*gamma(2/3)) + 3**(1/6)*hyper((), (1/3,), z**3/9)/gamma(1/3)
See Also
========
airyai: Airy function of the first kind.
airybi: Airy function of the second kind.
airyaiprime: Derivative of the Airy function of the first kind.
References
==========
.. [1] https://en.wikipedia.org/wiki/Airy_function
.. [2] http://dlmf.nist.gov/9
.. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions
.. [4] http://mathworld.wolfram.com/AiryFunctions.html
"""
nargs = 1
unbranched = True
@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
elif arg is S.NegativeInfinity:
return S.Zero
elif arg.is_zero:
return 3**Rational(1, 6) / gamma(Rational(1, 3))
if arg.is_zero:
return 3**Rational(1, 6) / gamma(Rational(1, 3))
def fdiff(self, argindex=1):
if argindex == 1:
return self.args[0]*airybi(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
def _eval_evalf(self, prec):
from mpmath import mp, workprec
from sympy import Expr
z = self.args[0]._to_mpmath(prec)
with workprec(prec):
res = mp.airybi(z, derivative=1)
return Expr._from_mpmath(res, prec)
def _eval_rewrite_as_besselj(self, z, **kwargs):
tt = Rational(2, 3)
a = tt * Pow(-z, Rational(3, 2))
if re(z).is_negative:
return -z/sqrt(3) * (besselj(-tt, a) + besselj(tt, a))
def _eval_rewrite_as_besseli(self, z, **kwargs):
ot = Rational(1, 3)
tt = Rational(2, 3)
a = tt * Pow(z, Rational(3, 2))
if re(z).is_positive:
return z/sqrt(3) * (besseli(-tt, a) + besseli(tt, a))
else:
a = Pow(z, Rational(3, 2))
b = Pow(a, tt)
c = Pow(a, -tt)
return sqrt(ot) * (b*besseli(-tt, tt*a) + z**2*c*besseli(tt, tt*a))
def _eval_rewrite_as_hyper(self, z, **kwargs):
pf1 = z**2 / (2*root(3, 6)*gamma(Rational(2, 3)))
pf2 = root(3, 6) / gamma(Rational(1, 3))
return pf1 * hyper([], [Rational(5, 3)], z**3/9) + pf2 * hyper([], [Rational(1, 3)], z**3/9)
def _eval_expand_func(self, **hints):
arg = self.args[0]
symbs = arg.free_symbols
if len(symbs) == 1:
z = symbs.pop()
c = Wild("c", exclude=[z])
d = Wild("d", exclude=[z])
m = Wild("m", exclude=[z])
n = Wild("n", exclude=[z])
M = arg.match(c*(d*z**n)**m)
if M is not None:
m = M[m]
# The transformation is in principle
# given by 03.08.16.0001.01 but note
# that there is an error in this formula.
# http://functions.wolfram.com/Bessel-TypeFunctions/AiryBiPrime/16/01/01/0001/
if (3*m).is_integer:
c = M[c]
d = M[d]
n = M[n]
pf = (d**m * z**(n*m)) / (d * z**n)**m
newarg = c * d**m * z**(n*m)
return S.Half * (sqrt(3)*(pf - S.One)*airyaiprime(newarg) + (pf + S.One)*airybiprime(newarg))
class marcumq(Function):
r"""
The Marcum Q-function.
Explanation
===========
The Marcum Q-function is defined by the meromorphic continuation of
.. math::
Q_m(a, b) = a^{- m + 1} \int_{b}^{\infty} x^{m} e^{- \frac{a^{2}}{2} - \frac{x^{2}}{2}} I_{m - 1}\left(a x\right)\, dx
Examples
========
>>> from sympy import marcumq
>>> from sympy.abc import m, a, b
>>> marcumq(m, a, b)
marcumq(m, a, b)
Special values:
>>> marcumq(m, 0, b)
uppergamma(m, b**2/2)/gamma(m)
>>> marcumq(0, 0, 0)
0
>>> marcumq(0, a, 0)
1 - exp(-a**2/2)
>>> marcumq(1, a, a)
1/2 + exp(-a**2)*besseli(0, a**2)/2
>>> marcumq(2, a, a)
1/2 + exp(-a**2)*besseli(0, a**2)/2 + exp(-a**2)*besseli(1, a**2)
Differentiation with respect to $a$ and $b$ is supported:
>>> from sympy import diff
>>> diff(marcumq(m, a, b), a)
a*(-marcumq(m, a, b) + marcumq(m + 1, a, b))
>>> diff(marcumq(m, a, b), b)
-a**(1 - m)*b**m*exp(-a**2/2 - b**2/2)*besseli(m - 1, a*b)
References
==========
.. [1] https://en.wikipedia.org/wiki/Marcum_Q-function
.. [2] http://mathworld.wolfram.com/MarcumQ-Function.html
"""
@classmethod
def eval(cls, m, a, b):
from sympy import exp, uppergamma
if a is S.Zero:
if m is S.Zero and b is S.Zero:
return S.Zero
return uppergamma(m, b**2 * S.Half) / gamma(m)
if m is S.Zero and b is S.Zero:
return 1 - 1 / exp(a**2 * S.Half)
if a == b:
if m is S.One:
return (1 + exp(-a**2) * besseli(0, a**2))*S.Half
if m == 2:
return S.Half + S.Half * exp(-a**2) * besseli(0, a**2) + exp(-a**2) * besseli(1, a**2)
if a.is_zero:
if m.is_zero and b.is_zero:
return S.Zero
return uppergamma(m, b**2*S.Half) / gamma(m)
if m.is_zero and b.is_zero:
return 1 - 1 / exp(a**2*S.Half)
def fdiff(self, argindex=2):
from sympy import exp
m, a, b = self.args
if argindex == 2:
return a * (-marcumq(m, a, b) + marcumq(1+m, a, b))
elif argindex == 3:
return (-b**m / a**(m-1)) * exp(-(a**2 + b**2)/2) * besseli(m-1, a*b)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_Integral(self, m, a, b, **kwargs):
from sympy import Integral, exp, Dummy, oo
x = kwargs.get('x', Dummy('x'))
return a ** (1 - m) * \
Integral(x**m * exp(-(x**2 + a**2)/2) * besseli(m-1, a*x), [x, b, oo])
def _eval_rewrite_as_Sum(self, m, a, b, **kwargs):
from sympy import Sum, exp, Dummy, oo
k = kwargs.get('k', Dummy('k'))
return exp(-(a**2 + b**2) / 2) * Sum((a/b)**k * besseli(k, a*b), [k, 1-m, oo])
def _eval_rewrite_as_besseli(self, m, a, b, **kwargs):
if a == b:
from sympy import exp
if m == 1:
return (1 + exp(-a**2) * besseli(0, a**2)) / 2
if m.is_Integer and m >= 2:
s = sum([besseli(i, a**2) for i in range(1, m)])
return S.Half + exp(-a**2) * besseli(0, a**2) / 2 + exp(-a**2) * s
def _eval_is_zero(self):
if all(arg.is_zero for arg in self.args):
return True
|
64931d75aa221e418ad6c3332575e1f143ae5530be3f874e1ea0b57df34294fa | """
This module mainly implements special orthogonal polynomials.
See also functions.combinatorial.numbers which contains some
combinatorial polynomials.
"""
from sympy.core import Rational
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.singleton import S
from sympy.core.symbol import Dummy
from sympy.functions.combinatorial.factorials import binomial, factorial, RisingFactorial
from sympy.functions.elementary.complexes import re
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import cos, sec
from sympy.functions.special.gamma_functions import gamma
from sympy.functions.special.hyper import hyper
from sympy.polys.orthopolys import (
jacobi_poly,
gegenbauer_poly,
chebyshevt_poly,
chebyshevu_poly,
laguerre_poly,
hermite_poly,
legendre_poly
)
_x = Dummy('x')
class OrthogonalPolynomial(Function):
"""Base class for orthogonal polynomials.
"""
@classmethod
def _eval_at_order(cls, n, x):
if n.is_integer and n >= 0:
return cls._ortho_poly(int(n), _x).subs(_x, x)
def _eval_conjugate(self):
return self.func(self.args[0], self.args[1].conjugate())
#----------------------------------------------------------------------------
# Jacobi polynomials
#
class jacobi(OrthogonalPolynomial):
r"""
Jacobi polynomial $P_n^{\left(\alpha, \beta\right)}(x)$.
Explanation
===========
``jacobi(n, alpha, beta, x)`` gives the nth Jacobi polynomial
in x, $P_n^{\left(\alpha, \beta\right)}(x)$.
The Jacobi polynomials are orthogonal on $[-1, 1]$ with respect
to the weight $\left(1-x\right)^\alpha \left(1+x\right)^\beta$.
Examples
========
>>> from sympy import jacobi, S, conjugate, diff
>>> from sympy.abc import a, b, n, x
>>> jacobi(0, a, b, x)
1
>>> jacobi(1, a, b, x)
a/2 - b/2 + x*(a/2 + b/2 + 1)
>>> jacobi(2, a, b, x)
a**2/8 - a*b/4 - a/8 + b**2/8 - b/8 + x**2*(a**2/8 + a*b/4 + 7*a/8 + b**2/8 + 7*b/8 + 3/2) + x*(a**2/4 + 3*a/4 - b**2/4 - 3*b/4) - 1/2
>>> jacobi(n, a, b, x)
jacobi(n, a, b, x)
>>> jacobi(n, a, a, x)
RisingFactorial(a + 1, n)*gegenbauer(n,
a + 1/2, x)/RisingFactorial(2*a + 1, n)
>>> jacobi(n, 0, 0, x)
legendre(n, x)
>>> jacobi(n, S(1)/2, S(1)/2, x)
RisingFactorial(3/2, n)*chebyshevu(n, x)/factorial(n + 1)
>>> jacobi(n, -S(1)/2, -S(1)/2, x)
RisingFactorial(1/2, n)*chebyshevt(n, x)/factorial(n)
>>> jacobi(n, a, b, -x)
(-1)**n*jacobi(n, b, a, x)
>>> jacobi(n, a, b, 0)
gamma(a + n + 1)*hyper((-b - n, -n), (a + 1,), -1)/(2**n*factorial(n)*gamma(a + 1))
>>> jacobi(n, a, b, 1)
RisingFactorial(a + 1, n)/factorial(n)
>>> conjugate(jacobi(n, a, b, x))
jacobi(n, conjugate(a), conjugate(b), conjugate(x))
>>> diff(jacobi(n,a,b,x), x)
(a/2 + b/2 + n/2 + 1/2)*jacobi(n - 1, a + 1, b + 1, x)
See Also
========
gegenbauer,
chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly,
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Jacobi_polynomials
.. [2] http://mathworld.wolfram.com/JacobiPolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/JacobiP/
"""
@classmethod
def eval(cls, n, a, b, x):
# Simplify to other polynomials
# P^{a, a}_n(x)
if a == b:
if a == Rational(-1, 2):
return RisingFactorial(S.Half, n) / factorial(n) * chebyshevt(n, x)
elif a.is_zero:
return legendre(n, x)
elif a == S.Half:
return RisingFactorial(3*S.Half, n) / factorial(n + 1) * chebyshevu(n, x)
else:
return RisingFactorial(a + 1, n) / RisingFactorial(2*a + 1, n) * gegenbauer(n, a + S.Half, x)
elif b == -a:
# P^{a, -a}_n(x)
return gamma(n + a + 1) / gamma(n + 1) * (1 + x)**(a/2) / (1 - x)**(a/2) * assoc_legendre(n, -a, x)
if not n.is_Number:
# Symbolic result P^{a,b}_n(x)
# P^{a,b}_n(-x) ---> (-1)**n * P^{b,a}_n(-x)
if x.could_extract_minus_sign():
return S.NegativeOne**n * jacobi(n, b, a, -x)
# We can evaluate for some special values of x
if x.is_zero:
return (2**(-n) * gamma(a + n + 1) / (gamma(a + 1) * factorial(n)) *
hyper([-b - n, -n], [a + 1], -1))
if x == S.One:
return RisingFactorial(a + 1, n) / factorial(n)
elif x is S.Infinity:
if n.is_positive:
# Make sure a+b+2*n \notin Z
if (a + b + 2*n).is_integer:
raise ValueError("Error. a + b + 2*n should not be an integer.")
return RisingFactorial(a + b + n + 1, n) * S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial
return jacobi_poly(n, a, b, x)
def fdiff(self, argindex=4):
from sympy import Sum
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt a
n, a, b, x = self.args
k = Dummy("k")
f1 = 1 / (a + b + n + k + 1)
f2 = ((a + b + 2*k + 1) * RisingFactorial(b + k + 1, n - k) /
((n - k) * RisingFactorial(a + b + k + 1, n - k)))
return Sum(f1 * (jacobi(n, a, b, x) + f2*jacobi(k, a, b, x)), (k, 0, n - 1))
elif argindex == 3:
# Diff wrt b
n, a, b, x = self.args
k = Dummy("k")
f1 = 1 / (a + b + n + k + 1)
f2 = (-1)**(n - k) * ((a + b + 2*k + 1) * RisingFactorial(a + k + 1, n - k) /
((n - k) * RisingFactorial(a + b + k + 1, n - k)))
return Sum(f1 * (jacobi(n, a, b, x) + f2*jacobi(k, a, b, x)), (k, 0, n - 1))
elif argindex == 4:
# Diff wrt x
n, a, b, x = self.args
return S.Half * (a + b + n + 1) * jacobi(n - 1, a + 1, b + 1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_polynomial(self, n, a, b, x, **kwargs):
from sympy import Sum
# Make sure n \in N
if n.is_negative or n.is_integer is False:
raise ValueError("Error: n should be a non-negative integer.")
k = Dummy("k")
kern = (RisingFactorial(-n, k) * RisingFactorial(a + b + n + 1, k) * RisingFactorial(a + k + 1, n - k) /
factorial(k) * ((1 - x)/2)**k)
return 1 / factorial(n) * Sum(kern, (k, 0, n))
def _eval_conjugate(self):
n, a, b, x = self.args
return self.func(n, a.conjugate(), b.conjugate(), x.conjugate())
def jacobi_normalized(n, a, b, x):
r"""
Jacobi polynomial $P_n^{\left(\alpha, \beta\right)}(x)$.
Explanation
===========
``jacobi_normalized(n, alpha, beta, x)`` gives the nth
Jacobi polynomial in *x*, $P_n^{\left(\alpha, \beta\right)}(x)$.
The Jacobi polynomials are orthogonal on $[-1, 1]$ with respect
to the weight $\left(1-x\right)^\alpha \left(1+x\right)^\beta$.
This functions returns the polynomials normilzed:
.. math::
\int_{-1}^{1}
P_m^{\left(\alpha, \beta\right)}(x)
P_n^{\left(\alpha, \beta\right)}(x)
(1-x)^{\alpha} (1+x)^{\beta} \mathrm{d}x
= \delta_{m,n}
Examples
========
>>> from sympy import jacobi_normalized
>>> from sympy.abc import n,a,b,x
>>> jacobi_normalized(n, a, b, x)
jacobi(n, a, b, x)/sqrt(2**(a + b + 1)*gamma(a + n + 1)*gamma(b + n + 1)/((a + b + 2*n + 1)*factorial(n)*gamma(a + b + n + 1)))
Parameters
==========
n : integer degree of polynomial
a : alpha value
b : beta value
x : symbol
See Also
========
gegenbauer,
chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly,
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Jacobi_polynomials
.. [2] http://mathworld.wolfram.com/JacobiPolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/JacobiP/
"""
nfactor = (S(2)**(a + b + 1) * (gamma(n + a + 1) * gamma(n + b + 1))
/ (2*n + a + b + 1) / (factorial(n) * gamma(n + a + b + 1)))
return jacobi(n, a, b, x) / sqrt(nfactor)
#----------------------------------------------------------------------------
# Gegenbauer polynomials
#
class gegenbauer(OrthogonalPolynomial):
r"""
Gegenbauer polynomial $C_n^{\left(\alpha\right)}(x)$.
Explanation
===========
``gegenbauer(n, alpha, x)`` gives the nth Gegenbauer polynomial
in x, $C_n^{\left(\alpha\right)}(x)$.
The Gegenbauer polynomials are orthogonal on $[-1, 1]$ with
respect to the weight $\left(1-x^2\right)^{\alpha-\frac{1}{2}}$.
Examples
========
>>> from sympy import gegenbauer, conjugate, diff
>>> from sympy.abc import n,a,x
>>> gegenbauer(0, a, x)
1
>>> gegenbauer(1, a, x)
2*a*x
>>> gegenbauer(2, a, x)
-a + x**2*(2*a**2 + 2*a)
>>> gegenbauer(3, a, x)
x**3*(4*a**3/3 + 4*a**2 + 8*a/3) + x*(-2*a**2 - 2*a)
>>> gegenbauer(n, a, x)
gegenbauer(n, a, x)
>>> gegenbauer(n, a, -x)
(-1)**n*gegenbauer(n, a, x)
>>> gegenbauer(n, a, 0)
2**n*sqrt(pi)*gamma(a + n/2)/(gamma(a)*gamma(1/2 - n/2)*gamma(n + 1))
>>> gegenbauer(n, a, 1)
gamma(2*a + n)/(gamma(2*a)*gamma(n + 1))
>>> conjugate(gegenbauer(n, a, x))
gegenbauer(n, conjugate(a), conjugate(x))
>>> diff(gegenbauer(n, a, x), x)
2*a*gegenbauer(n - 1, a + 1, x)
See Also
========
jacobi,
chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Gegenbauer_polynomials
.. [2] http://mathworld.wolfram.com/GegenbauerPolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/GegenbauerC3/
"""
@classmethod
def eval(cls, n, a, x):
# For negative n the polynomials vanish
# See http://functions.wolfram.com/Polynomials/GegenbauerC3/03/01/03/0012/
if n.is_negative:
return S.Zero
# Some special values for fixed a
if a == S.Half:
return legendre(n, x)
elif a == S.One:
return chebyshevu(n, x)
elif a == S.NegativeOne:
return S.Zero
if not n.is_Number:
# Handle this before the general sign extraction rule
if x == S.NegativeOne:
if (re(a) > S.Half) == True:
return S.ComplexInfinity
else:
return (cos(S.Pi*(a+n)) * sec(S.Pi*a) * gamma(2*a+n) /
(gamma(2*a) * gamma(n+1)))
# Symbolic result C^a_n(x)
# C^a_n(-x) ---> (-1)**n * C^a_n(x)
if x.could_extract_minus_sign():
return S.NegativeOne**n * gegenbauer(n, a, -x)
# We can evaluate for some special values of x
if x.is_zero:
return (2**n * sqrt(S.Pi) * gamma(a + S.Half*n) /
(gamma((1 - n)/2) * gamma(n + 1) * gamma(a)) )
if x == S.One:
return gamma(2*a + n) / (gamma(2*a) * gamma(n + 1))
elif x is S.Infinity:
if n.is_positive:
return RisingFactorial(a, n) * S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial
return gegenbauer_poly(n, a, x)
def fdiff(self, argindex=3):
from sympy import Sum
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt a
n, a, x = self.args
k = Dummy("k")
factor1 = 2 * (1 + (-1)**(n - k)) * (k + a) / ((k +
n + 2*a) * (n - k))
factor2 = 2*(k + 1) / ((k + 2*a) * (2*k + 2*a + 1)) + \
2 / (k + n + 2*a)
kern = factor1*gegenbauer(k, a, x) + factor2*gegenbauer(n, a, x)
return Sum(kern, (k, 0, n - 1))
elif argindex == 3:
# Diff wrt x
n, a, x = self.args
return 2*a*gegenbauer(n - 1, a + 1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_polynomial(self, n, a, x, **kwargs):
from sympy import Sum
k = Dummy("k")
kern = ((-1)**k * RisingFactorial(a, n - k) * (2*x)**(n - 2*k) /
(factorial(k) * factorial(n - 2*k)))
return Sum(kern, (k, 0, floor(n/2)))
def _eval_conjugate(self):
n, a, x = self.args
return self.func(n, a.conjugate(), x.conjugate())
#----------------------------------------------------------------------------
# Chebyshev polynomials of first and second kind
#
class chebyshevt(OrthogonalPolynomial):
r"""
Chebyshev polynomial of the first kind, $T_n(x)$.
Explanation
===========
``chebyshevt(n, x)`` gives the nth Chebyshev polynomial (of the first
kind) in x, $T_n(x)$.
The Chebyshev polynomials of the first kind are orthogonal on
$[-1, 1]$ with respect to the weight $\frac{1}{\sqrt{1-x^2}}$.
Examples
========
>>> from sympy import chebyshevt, diff
>>> from sympy.abc import n,x
>>> chebyshevt(0, x)
1
>>> chebyshevt(1, x)
x
>>> chebyshevt(2, x)
2*x**2 - 1
>>> chebyshevt(n, x)
chebyshevt(n, x)
>>> chebyshevt(n, -x)
(-1)**n*chebyshevt(n, x)
>>> chebyshevt(-n, x)
chebyshevt(n, x)
>>> chebyshevt(n, 0)
cos(pi*n/2)
>>> chebyshevt(n, -1)
(-1)**n
>>> diff(chebyshevt(n, x), x)
n*chebyshevu(n - 1, x)
See Also
========
jacobi, gegenbauer,
chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Chebyshev_polynomial
.. [2] http://mathworld.wolfram.com/ChebyshevPolynomialoftheFirstKind.html
.. [3] http://mathworld.wolfram.com/ChebyshevPolynomialoftheSecondKind.html
.. [4] http://functions.wolfram.com/Polynomials/ChebyshevT/
.. [5] http://functions.wolfram.com/Polynomials/ChebyshevU/
"""
_ortho_poly = staticmethod(chebyshevt_poly)
@classmethod
def eval(cls, n, x):
if not n.is_Number:
# Symbolic result T_n(x)
# T_n(-x) ---> (-1)**n * T_n(x)
if x.could_extract_minus_sign():
return S.NegativeOne**n * chebyshevt(n, -x)
# T_{-n}(x) ---> T_n(x)
if n.could_extract_minus_sign():
return chebyshevt(-n, x)
# We can evaluate for some special values of x
if x.is_zero:
return cos(S.Half * S.Pi * n)
if x == S.One:
return S.One
elif x is S.Infinity:
return S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial
if n.is_negative:
# T_{-n}(x) == T_n(x)
return cls._eval_at_order(-n, x)
else:
return cls._eval_at_order(n, x)
def fdiff(self, argindex=2):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt x
n, x = self.args
return n * chebyshevu(n - 1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
from sympy import Sum
k = Dummy("k")
kern = binomial(n, 2*k) * (x**2 - 1)**k * x**(n - 2*k)
return Sum(kern, (k, 0, floor(n/2)))
class chebyshevu(OrthogonalPolynomial):
r"""
Chebyshev polynomial of the second kind, $U_n(x)$.
Explanation
===========
``chebyshevu(n, x)`` gives the nth Chebyshev polynomial of the second
kind in x, $U_n(x)$.
The Chebyshev polynomials of the second kind are orthogonal on
$[-1, 1]$ with respect to the weight $\sqrt{1-x^2}$.
Examples
========
>>> from sympy import chebyshevu, diff
>>> from sympy.abc import n,x
>>> chebyshevu(0, x)
1
>>> chebyshevu(1, x)
2*x
>>> chebyshevu(2, x)
4*x**2 - 1
>>> chebyshevu(n, x)
chebyshevu(n, x)
>>> chebyshevu(n, -x)
(-1)**n*chebyshevu(n, x)
>>> chebyshevu(-n, x)
-chebyshevu(n - 2, x)
>>> chebyshevu(n, 0)
cos(pi*n/2)
>>> chebyshevu(n, 1)
n + 1
>>> diff(chebyshevu(n, x), x)
(-x*chebyshevu(n, x) + (n + 1)*chebyshevt(n + 1, x))/(x**2 - 1)
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu_root,
legendre, assoc_legendre,
hermite,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Chebyshev_polynomial
.. [2] http://mathworld.wolfram.com/ChebyshevPolynomialoftheFirstKind.html
.. [3] http://mathworld.wolfram.com/ChebyshevPolynomialoftheSecondKind.html
.. [4] http://functions.wolfram.com/Polynomials/ChebyshevT/
.. [5] http://functions.wolfram.com/Polynomials/ChebyshevU/
"""
_ortho_poly = staticmethod(chebyshevu_poly)
@classmethod
def eval(cls, n, x):
if not n.is_Number:
# Symbolic result U_n(x)
# U_n(-x) ---> (-1)**n * U_n(x)
if x.could_extract_minus_sign():
return S.NegativeOne**n * chebyshevu(n, -x)
# U_{-n}(x) ---> -U_{n-2}(x)
if n.could_extract_minus_sign():
if n == S.NegativeOne:
# n can not be -1 here
return S.Zero
elif not (-n - 2).could_extract_minus_sign():
return -chebyshevu(-n - 2, x)
# We can evaluate for some special values of x
if x.is_zero:
return cos(S.Half * S.Pi * n)
if x == S.One:
return S.One + n
elif x is S.Infinity:
return S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial
if n.is_negative:
# U_{-n}(x) ---> -U_{n-2}(x)
if n == S.NegativeOne:
return S.Zero
else:
return -cls._eval_at_order(-n - 2, x)
else:
return cls._eval_at_order(n, x)
def fdiff(self, argindex=2):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt x
n, x = self.args
return ((n + 1) * chebyshevt(n + 1, x) - x * chebyshevu(n, x)) / (x**2 - 1)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
from sympy import Sum
k = Dummy("k")
kern = S.NegativeOne**k * factorial(
n - k) * (2*x)**(n - 2*k) / (factorial(k) * factorial(n - 2*k))
return Sum(kern, (k, 0, floor(n/2)))
class chebyshevt_root(Function):
r"""
``chebyshev_root(n, k)`` returns the kth root (indexed from zero) of
the nth Chebyshev polynomial of the first kind; that is, if
0 <= k < n, ``chebyshevt(n, chebyshevt_root(n, k)) == 0``.
Examples
========
>>> from sympy import chebyshevt, chebyshevt_root
>>> chebyshevt_root(3, 2)
-sqrt(3)/2
>>> chebyshevt(3, chebyshevt_root(3, 2))
0
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
"""
@classmethod
def eval(cls, n, k):
if not ((0 <= k) and (k < n)):
raise ValueError("must have 0 <= k < n, "
"got k = %s and n = %s" % (k, n))
return cos(S.Pi*(2*k + 1)/(2*n))
class chebyshevu_root(Function):
r"""
``chebyshevu_root(n, k)`` returns the kth root (indexed from zero) of the
nth Chebyshev polynomial of the second kind; that is, if 0 <= k < n,
``chebyshevu(n, chebyshevu_root(n, k)) == 0``.
Examples
========
>>> from sympy import chebyshevu, chebyshevu_root
>>> chebyshevu_root(3, 2)
-sqrt(2)/2
>>> chebyshevu(3, chebyshevu_root(3, 2))
0
See Also
========
chebyshevt, chebyshevt_root, chebyshevu,
legendre, assoc_legendre,
hermite,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
"""
@classmethod
def eval(cls, n, k):
if not ((0 <= k) and (k < n)):
raise ValueError("must have 0 <= k < n, "
"got k = %s and n = %s" % (k, n))
return cos(S.Pi*(k + 1)/(n + 1))
#----------------------------------------------------------------------------
# Legendre polynomials and Associated Legendre polynomials
#
class legendre(OrthogonalPolynomial):
r"""
``legendre(n, x)`` gives the nth Legendre polynomial of x, $P_n(x)$
Explanation
===========
The Legendre polynomials are orthogonal on [-1, 1] with respect to
the constant weight 1. They satisfy $P_n(1) = 1$ for all n; further,
$P_n$ is odd for odd n and even for even n.
Examples
========
>>> from sympy import legendre, diff
>>> from sympy.abc import x, n
>>> legendre(0, x)
1
>>> legendre(1, x)
x
>>> legendre(2, x)
3*x**2/2 - 1/2
>>> legendre(n, x)
legendre(n, x)
>>> diff(legendre(n,x), x)
n*(x*legendre(n, x) - legendre(n - 1, x))/(x**2 - 1)
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
assoc_legendre,
hermite,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Legendre_polynomial
.. [2] http://mathworld.wolfram.com/LegendrePolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/LegendreP/
.. [4] http://functions.wolfram.com/Polynomials/LegendreP2/
"""
_ortho_poly = staticmethod(legendre_poly)
@classmethod
def eval(cls, n, x):
if not n.is_Number:
# Symbolic result L_n(x)
# L_n(-x) ---> (-1)**n * L_n(x)
if x.could_extract_minus_sign():
return S.NegativeOne**n * legendre(n, -x)
# L_{-n}(x) ---> L_{n-1}(x)
if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign():
return legendre(-n - S.One, x)
# We can evaluate for some special values of x
if x.is_zero:
return sqrt(S.Pi)/(gamma(S.Half - n/2)*gamma(S.One + n/2))
elif x == S.One:
return S.One
elif x is S.Infinity:
return S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial;
# L_{-n}(x) ---> L_{n-1}(x)
if n.is_negative:
n = -n - S.One
return cls._eval_at_order(n, x)
def fdiff(self, argindex=2):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt x
# Find better formula, this is unsuitable for x = +/-1
# http://www.autodiff.org/ad16/Oral/Buecker_Legendre.pdf says
# at x = 1:
# n*(n + 1)/2 , m = 0
# oo , m = 1
# -(n-1)*n*(n+1)*(n+2)/4 , m = 2
# 0 , m = 3, 4, ..., n
#
# at x = -1
# (-1)**(n+1)*n*(n + 1)/2 , m = 0
# (-1)**n*oo , m = 1
# (-1)**n*(n-1)*n*(n+1)*(n+2)/4 , m = 2
# 0 , m = 3, 4, ..., n
n, x = self.args
return n/(x**2 - 1)*(x*legendre(n, x) - legendre(n - 1, x))
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
from sympy import Sum
k = Dummy("k")
kern = (-1)**k*binomial(n, k)**2*((1 + x)/2)**(n - k)*((1 - x)/2)**k
return Sum(kern, (k, 0, n))
class assoc_legendre(Function):
r"""
``assoc_legendre(n, m, x)`` gives $P_n^m(x)$, where n and m are
the degree and order or an expression which is related to the nth
order Legendre polynomial, $P_n(x)$ in the following manner:
.. math::
P_n^m(x) = (-1)^m (1 - x^2)^{\frac{m}{2}}
\frac{\mathrm{d}^m P_n(x)}{\mathrm{d} x^m}
Explanation
===========
Associated Legendre polynomials are orthogonal on [-1, 1] with:
- weight = 1 for the same m, and different n.
- weight = 1/(1-x**2) for the same n, and different m.
Examples
========
>>> from sympy import assoc_legendre
>>> from sympy.abc import x, m, n
>>> assoc_legendre(0,0, x)
1
>>> assoc_legendre(1,0, x)
x
>>> assoc_legendre(1,1, x)
-sqrt(1 - x**2)
>>> assoc_legendre(n,m,x)
assoc_legendre(n, m, x)
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
legendre,
hermite,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Associated_Legendre_polynomials
.. [2] http://mathworld.wolfram.com/LegendrePolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/LegendreP/
.. [4] http://functions.wolfram.com/Polynomials/LegendreP2/
"""
@classmethod
def _eval_at_order(cls, n, m):
P = legendre_poly(n, _x, polys=True).diff((_x, m))
return (-1)**m * (1 - _x**2)**Rational(m, 2) * P.as_expr()
@classmethod
def eval(cls, n, m, x):
if m.could_extract_minus_sign():
# P^{-m}_n ---> F * P^m_n
return S.NegativeOne**(-m) * (factorial(m + n)/factorial(n - m)) * assoc_legendre(n, -m, x)
if m == 0:
# P^0_n ---> L_n
return legendre(n, x)
if x == 0:
return 2**m*sqrt(S.Pi) / (gamma((1 - m - n)/2)*gamma(1 - (m - n)/2))
if n.is_Number and m.is_Number and n.is_integer and m.is_integer:
if n.is_negative:
raise ValueError("%s : 1st index must be nonnegative integer (got %r)" % (cls, n))
if abs(m) > n:
raise ValueError("%s : abs('2nd index') must be <= '1st index' (got %r, %r)" % (cls, n, m))
return cls._eval_at_order(int(n), abs(int(m))).subs(_x, x)
def fdiff(self, argindex=3):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt m
raise ArgumentIndexError(self, argindex)
elif argindex == 3:
# Diff wrt x
# Find better formula, this is unsuitable for x = 1
n, m, x = self.args
return 1/(x**2 - 1)*(x*n*assoc_legendre(n, m, x) - (m + n)*assoc_legendre(n - 1, m, x))
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_polynomial(self, n, m, x, **kwargs):
from sympy import Sum
k = Dummy("k")
kern = factorial(2*n - 2*k)/(2**n*factorial(n - k)*factorial(
k)*factorial(n - 2*k - m))*(-1)**k*x**(n - m - 2*k)
return (1 - x**2)**(m/2) * Sum(kern, (k, 0, floor((n - m)*S.Half)))
def _eval_conjugate(self):
n, m, x = self.args
return self.func(n, m.conjugate(), x.conjugate())
#----------------------------------------------------------------------------
# Hermite polynomials
#
class hermite(OrthogonalPolynomial):
r"""
``hermite(n, x)`` gives the nth Hermite polynomial in x, $H_n(x)$
Explanation
===========
The Hermite polynomials are orthogonal on $(-\infty, \infty)$
with respect to the weight $\exp\left(-x^2\right)$.
Examples
========
>>> from sympy import hermite, diff
>>> from sympy.abc import x, n
>>> hermite(0, x)
1
>>> hermite(1, x)
2*x
>>> hermite(2, x)
4*x**2 - 2
>>> hermite(n, x)
hermite(n, x)
>>> diff(hermite(n,x), x)
2*n*hermite(n - 1, x)
>>> hermite(n, -x)
(-1)**n*hermite(n, x)
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
laguerre, assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Hermite_polynomial
.. [2] http://mathworld.wolfram.com/HermitePolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/HermiteH/
"""
_ortho_poly = staticmethod(hermite_poly)
@classmethod
def eval(cls, n, x):
if not n.is_Number:
# Symbolic result H_n(x)
# H_n(-x) ---> (-1)**n * H_n(x)
if x.could_extract_minus_sign():
return S.NegativeOne**n * hermite(n, -x)
# We can evaluate for some special values of x
if x.is_zero:
return 2**n * sqrt(S.Pi) / gamma((S.One - n)/2)
elif x is S.Infinity:
return S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial
if n.is_negative:
raise ValueError(
"The index n must be nonnegative integer (got %r)" % n)
else:
return cls._eval_at_order(n, x)
def fdiff(self, argindex=2):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt x
n, x = self.args
return 2*n*hermite(n - 1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
from sympy import Sum
k = Dummy("k")
kern = (-1)**k / (factorial(k)*factorial(n - 2*k)) * (2*x)**(n - 2*k)
return factorial(n)*Sum(kern, (k, 0, floor(n/2)))
#----------------------------------------------------------------------------
# Laguerre polynomials
#
class laguerre(OrthogonalPolynomial):
r"""
Returns the nth Laguerre polynomial in x, $L_n(x)$.
Examples
========
>>> from sympy import laguerre, diff
>>> from sympy.abc import x, n
>>> laguerre(0, x)
1
>>> laguerre(1, x)
1 - x
>>> laguerre(2, x)
x**2/2 - 2*x + 1
>>> laguerre(3, x)
-x**3/6 + 3*x**2/2 - 3*x + 1
>>> laguerre(n, x)
laguerre(n, x)
>>> diff(laguerre(n, x), x)
-assoc_laguerre(n - 1, 1, x)
Parameters
==========
n : int
Degree of Laguerre polynomial. Must be ``n >= 0``.
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite,
assoc_laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial
.. [2] http://mathworld.wolfram.com/LaguerrePolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/LaguerreL/
.. [4] http://functions.wolfram.com/Polynomials/LaguerreL3/
"""
_ortho_poly = staticmethod(laguerre_poly)
@classmethod
def eval(cls, n, x):
if n.is_integer is False:
raise ValueError("Error: n should be an integer.")
if not n.is_Number:
# Symbolic result L_n(x)
# L_{n}(-x) ---> exp(-x) * L_{-n-1}(x)
# L_{-n}(x) ---> exp(x) * L_{n-1}(-x)
if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign():
return exp(x)*laguerre(-n - 1, -x)
# We can evaluate for some special values of x
if x.is_zero:
return S.One
elif x is S.NegativeInfinity:
return S.Infinity
elif x is S.Infinity:
return S.NegativeOne**n * S.Infinity
else:
if n.is_negative:
return exp(x)*laguerre(-n - 1, -x)
else:
return cls._eval_at_order(n, x)
def fdiff(self, argindex=2):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt x
n, x = self.args
return -assoc_laguerre(n - 1, 1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
from sympy import Sum
# Make sure n \in N_0
if n.is_negative:
return exp(x) * self._eval_rewrite_as_polynomial(-n - 1, -x, **kwargs)
if n.is_integer is False:
raise ValueError("Error: n should be an integer.")
k = Dummy("k")
kern = RisingFactorial(-n, k) / factorial(k)**2 * x**k
return Sum(kern, (k, 0, n))
class assoc_laguerre(OrthogonalPolynomial):
r"""
Returns the nth generalized Laguerre polynomial in x, $L_n(x)$.
Examples
========
>>> from sympy import assoc_laguerre, diff
>>> from sympy.abc import x, n, a
>>> assoc_laguerre(0, a, x)
1
>>> assoc_laguerre(1, a, x)
a - x + 1
>>> assoc_laguerre(2, a, x)
a**2/2 + 3*a/2 + x**2/2 + x*(-a - 2) + 1
>>> assoc_laguerre(3, a, x)
a**3/6 + a**2 + 11*a/6 - x**3/6 + x**2*(a/2 + 3/2) +
x*(-a**2/2 - 5*a/2 - 3) + 1
>>> assoc_laguerre(n, a, 0)
binomial(a + n, a)
>>> assoc_laguerre(n, a, x)
assoc_laguerre(n, a, x)
>>> assoc_laguerre(n, 0, x)
laguerre(n, x)
>>> diff(assoc_laguerre(n, a, x), x)
-assoc_laguerre(n - 1, a + 1, x)
>>> diff(assoc_laguerre(n, a, x), a)
Sum(assoc_laguerre(_k, a, x)/(-a + n), (_k, 0, n - 1))
Parameters
==========
n : int
Degree of Laguerre polynomial. Must be ``n >= 0``.
alpha : Expr
Arbitrary expression. For ``alpha=0`` regular Laguerre
polynomials will be generated.
See Also
========
jacobi, gegenbauer,
chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
legendre, assoc_legendre,
hermite,
laguerre,
sympy.polys.orthopolys.jacobi_poly
sympy.polys.orthopolys.gegenbauer_poly
sympy.polys.orthopolys.chebyshevt_poly
sympy.polys.orthopolys.chebyshevu_poly
sympy.polys.orthopolys.hermite_poly
sympy.polys.orthopolys.legendre_poly
sympy.polys.orthopolys.laguerre_poly
References
==========
.. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial#Generalized_Laguerre_polynomials
.. [2] http://mathworld.wolfram.com/AssociatedLaguerrePolynomial.html
.. [3] http://functions.wolfram.com/Polynomials/LaguerreL/
.. [4] http://functions.wolfram.com/Polynomials/LaguerreL3/
"""
@classmethod
def eval(cls, n, alpha, x):
# L_{n}^{0}(x) ---> L_{n}(x)
if alpha.is_zero:
return laguerre(n, x)
if not n.is_Number:
# We can evaluate for some special values of x
if x.is_zero:
return binomial(n + alpha, alpha)
elif x is S.Infinity and n > 0:
return S.NegativeOne**n * S.Infinity
elif x is S.NegativeInfinity and n > 0:
return S.Infinity
else:
# n is a given fixed integer, evaluate into polynomial
if n.is_negative:
raise ValueError(
"The index n must be nonnegative integer (got %r)" % n)
else:
return laguerre_poly(n, x, alpha)
def fdiff(self, argindex=3):
from sympy import Sum
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt alpha
n, alpha, x = self.args
k = Dummy("k")
return Sum(assoc_laguerre(k, alpha, x) / (n - alpha), (k, 0, n - 1))
elif argindex == 3:
# Diff wrt x
n, alpha, x = self.args
return -assoc_laguerre(n - 1, alpha + 1, x)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_polynomial(self, n, alpha, x, **kwargs):
from sympy import Sum
# Make sure n \in N_0
if n.is_negative or n.is_integer is False:
raise ValueError("Error: n should be a non-negative integer.")
k = Dummy("k")
kern = RisingFactorial(
-n, k) / (gamma(k + alpha + 1) * factorial(k)) * x**k
return gamma(n + alpha + 1) / factorial(n) * Sum(kern, (k, 0, n))
def _eval_conjugate(self):
n, alpha, x = self.args
return self.func(n, alpha.conjugate(), x.conjugate())
|
eab83884e93ea80c098b1ff2c584e4e9426868ea9c0225c639adbb5c0cac4763 | from sympy import (symbols, Symbol, nan, oo, zoo, I, sinh, sin, pi, atan,
acos, Rational, sqrt, asin, acot, coth, E, S, tan, tanh, cos,
cosh, atan2, exp, log, asinh, acoth, atanh, O, cancel, Matrix, re, im,
Float, Pow, gcd, sec, csc, cot, diff, simplify, Heaviside, arg,
conjugate, series, FiniteSet, asec, acsc, Mul, sinc, jn,
AccumBounds, Interval, ImageSet, Lambda, besselj, Add, limit)
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.core.relational import Ne, Eq
from sympy.functions.elementary.piecewise import Piecewise
from sympy.sets.setexpr import SetExpr
from sympy.testing.pytest import XFAIL, slow, raises
x, y, z = symbols('x y z')
r = Symbol('r', real=True)
k, m = symbols('k m', integer=True)
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
np = Symbol('p', nonpositive=True)
nn = Symbol('n', nonnegative=True)
nz = Symbol('nz', nonzero=True)
ep = Symbol('ep', extended_positive=True)
en = Symbol('en', extended_negative=True)
enp = Symbol('ep', extended_nonpositive=True)
enn = Symbol('en', extended_nonnegative=True)
enz = Symbol('enz', extended_nonzero=True)
a = Symbol('a', algebraic=True)
na = Symbol('na', nonzero=True, algebraic=True)
def test_sin():
x, y = symbols('x y')
assert sin.nargs == FiniteSet(1)
assert sin(nan) is nan
assert sin(zoo) is nan
assert sin(oo) == AccumBounds(-1, 1)
assert sin(oo) - sin(oo) == AccumBounds(-2, 2)
assert sin(oo*I) == oo*I
assert sin(-oo*I) == -oo*I
assert 0*sin(oo) is S.Zero
assert 0/sin(oo) is S.Zero
assert 0 + sin(oo) == AccumBounds(-1, 1)
assert 5 + sin(oo) == AccumBounds(4, 6)
assert sin(0) == 0
assert sin(asin(x)) == x
assert sin(atan(x)) == x / sqrt(1 + x**2)
assert sin(acos(x)) == sqrt(1 - x**2)
assert sin(acot(x)) == 1 / (sqrt(1 + 1 / x**2) * x)
assert sin(acsc(x)) == 1 / x
assert sin(asec(x)) == sqrt(1 - 1 / x**2)
assert sin(atan2(y, x)) == y / sqrt(x**2 + y**2)
assert sin(pi*I) == sinh(pi)*I
assert sin(-pi*I) == -sinh(pi)*I
assert sin(-2*I) == -sinh(2)*I
assert sin(pi) == 0
assert sin(-pi) == 0
assert sin(2*pi) == 0
assert sin(-2*pi) == 0
assert sin(-3*10**73*pi) == 0
assert sin(7*10**103*pi) == 0
assert sin(pi/2) == 1
assert sin(-pi/2) == -1
assert sin(pi*Rational(5, 2)) == 1
assert sin(pi*Rational(7, 2)) == -1
ne = symbols('ne', integer=True, even=False)
e = symbols('e', even=True)
assert sin(pi*ne/2) == (-1)**(ne/2 - S.Half)
assert sin(pi*k/2).func == sin
assert sin(pi*e/2) == 0
assert sin(pi*k) == 0
assert sin(pi*k).subs(k, 3) == sin(pi*k/2).subs(k, 6) # issue 8298
assert sin(pi/3) == S.Half*sqrt(3)
assert sin(pi*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)
assert sin(pi/4) == S.Half*sqrt(2)
assert sin(-pi/4) == Rational(-1, 2)*sqrt(2)
assert sin(pi*Rational(17, 4)) == S.Half*sqrt(2)
assert sin(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
assert sin(pi/6) == S.Half
assert sin(-pi/6) == Rational(-1, 2)
assert sin(pi*Rational(7, 6)) == Rational(-1, 2)
assert sin(pi*Rational(-5, 6)) == Rational(-1, 2)
assert sin(pi*Rational(1, 5)) == sqrt((5 - sqrt(5)) / 8)
assert sin(pi*Rational(2, 5)) == sqrt((5 + sqrt(5)) / 8)
assert sin(pi*Rational(3, 5)) == sin(pi*Rational(2, 5))
assert sin(pi*Rational(4, 5)) == sin(pi*Rational(1, 5))
assert sin(pi*Rational(6, 5)) == -sin(pi*Rational(1, 5))
assert sin(pi*Rational(8, 5)) == -sin(pi*Rational(2, 5))
assert sin(pi*Rational(-1273, 5)) == -sin(pi*Rational(2, 5))
assert sin(pi/8) == sqrt((2 - sqrt(2))/4)
assert sin(pi/10) == Rational(-1, 4) + sqrt(5)/4
assert sin(pi/12) == -sqrt(2)/4 + sqrt(6)/4
assert sin(pi*Rational(5, 12)) == sqrt(2)/4 + sqrt(6)/4
assert sin(pi*Rational(-7, 12)) == -sqrt(2)/4 - sqrt(6)/4
assert sin(pi*Rational(-11, 12)) == sqrt(2)/4 - sqrt(6)/4
assert sin(pi*Rational(104, 105)) == sin(pi/105)
assert sin(pi*Rational(106, 105)) == -sin(pi/105)
assert sin(pi*Rational(-104, 105)) == -sin(pi/105)
assert sin(pi*Rational(-106, 105)) == sin(pi/105)
assert sin(x*I) == sinh(x)*I
assert sin(k*pi) == 0
assert sin(17*k*pi) == 0
assert sin(2*k*pi + 4) == sin(4)
assert sin(2*k*pi + m*pi + 1) == (-1)**(m + 2*k)*sin(1)
assert sin(k*pi*I) == sinh(k*pi)*I
assert sin(r).is_real is True
assert sin(0, evaluate=False).is_algebraic
assert sin(a).is_algebraic is None
assert sin(na).is_algebraic is False
q = Symbol('q', rational=True)
assert sin(pi*q).is_algebraic
qn = Symbol('qn', rational=True, nonzero=True)
assert sin(qn).is_rational is False
assert sin(q).is_rational is None # issue 8653
assert isinstance(sin( re(x) - im(y)), sin) is True
assert isinstance(sin(-re(x) + im(y)), sin) is False
assert sin(SetExpr(Interval(0, 1))) == SetExpr(ImageSet(Lambda(x, sin(x)),
Interval(0, 1)))
for d in list(range(1, 22)) + [60, 85]:
for n in range(0, d*2 + 1):
x = n*pi/d
e = abs( float(sin(x)) - sin(float(x)) )
assert e < 1e-12
assert sin(0, evaluate=False).is_zero is True
assert sin(k*pi, evaluate=False).is_zero is None
assert sin(Add(1, -1, evaluate=False), evaluate=False).is_zero is True
def test_sin_cos():
for d in [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 24, 30, 40, 60, 120]: # list is not exhaustive...
for n in range(-2*d, d*2):
x = n*pi/d
assert sin(x + pi/2) == cos(x), "fails for %d*pi/%d" % (n, d)
assert sin(x - pi/2) == -cos(x), "fails for %d*pi/%d" % (n, d)
assert sin(x) == cos(x - pi/2), "fails for %d*pi/%d" % (n, d)
assert -sin(x) == cos(x + pi/2), "fails for %d*pi/%d" % (n, d)
def test_sin_series():
assert sin(x).series(x, 0, 9) == \
x - x**3/6 + x**5/120 - x**7/5040 + O(x**9)
def test_sin_rewrite():
assert sin(x).rewrite(exp) == -I*(exp(I*x) - exp(-I*x))/2
assert sin(x).rewrite(tan) == 2*tan(x/2)/(1 + tan(x/2)**2)
assert sin(x).rewrite(cot) == 2*cot(x/2)/(1 + cot(x/2)**2)
assert sin(sinh(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sinh(3)).n()
assert sin(cosh(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cosh(3)).n()
assert sin(tanh(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tanh(3)).n()
assert sin(coth(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, coth(3)).n()
assert sin(sin(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sin(3)).n()
assert sin(cos(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cos(3)).n()
assert sin(tan(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tan(3)).n()
assert sin(cot(x)).rewrite(
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cot(3)).n()
assert sin(log(x)).rewrite(Pow) == I*x**-I / 2 - I*x**I /2
assert sin(x).rewrite(csc) == 1/csc(x)
assert sin(x).rewrite(cos) == cos(x - pi / 2, evaluate=False)
assert sin(x).rewrite(sec) == 1 / sec(x - pi / 2, evaluate=False)
assert sin(cos(x)).rewrite(Pow) == sin(cos(x))
def _test_extrig(f, i, e):
from sympy.core.expr import unchanged
from sympy.core.function import expand_trig
assert unchanged(f, i)
assert expand_trig(f(i)) == f(i)
# testing directly instead of with .expand(trig=True)
# because the other expansions undo the unevaluated Mul
assert expand_trig(f(Mul(i, 1, evaluate=False))) == e
assert abs(f(i) - e).n() < 1e-10
def test_sin_expansion():
# Note: these formulas are not unique. The ones here come from the
# Chebyshev formulas.
assert sin(x + y).expand(trig=True) == sin(x)*cos(y) + cos(x)*sin(y)
assert sin(x - y).expand(trig=True) == sin(x)*cos(y) - cos(x)*sin(y)
assert sin(y - x).expand(trig=True) == cos(x)*sin(y) - sin(x)*cos(y)
assert sin(2*x).expand(trig=True) == 2*sin(x)*cos(x)
assert sin(3*x).expand(trig=True) == -4*sin(x)**3 + 3*sin(x)
assert sin(4*x).expand(trig=True) == -8*sin(x)**3*cos(x) + 4*sin(x)*cos(x)
_test_extrig(sin, 2, 2*sin(1)*cos(1))
_test_extrig(sin, 3, -4*sin(1)**3 + 3*sin(1))
def test_sin_AccumBounds():
assert sin(AccumBounds(-oo, oo)) == AccumBounds(-1, 1)
assert sin(AccumBounds(0, oo)) == AccumBounds(-1, 1)
assert sin(AccumBounds(-oo, 0)) == AccumBounds(-1, 1)
assert sin(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1)
assert sin(AccumBounds(0, S.Pi*Rational(3, 4))) == AccumBounds(0, 1)
assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(7, 4))) == AccumBounds(-1, sin(S.Pi*Rational(3, 4)))
assert sin(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(sin(S.Pi/4), sin(S.Pi/3))
assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 6))) == AccumBounds(sin(S.Pi*Rational(5, 6)), sin(S.Pi*Rational(3, 4)))
def test_sin_fdiff():
assert sin(x).fdiff() == cos(x)
raises(ArgumentIndexError, lambda: sin(x).fdiff(2))
def test_trig_symmetry():
assert sin(-x) == -sin(x)
assert cos(-x) == cos(x)
assert tan(-x) == -tan(x)
assert cot(-x) == -cot(x)
assert sin(x + pi) == -sin(x)
assert sin(x + 2*pi) == sin(x)
assert sin(x + 3*pi) == -sin(x)
assert sin(x + 4*pi) == sin(x)
assert sin(x - 5*pi) == -sin(x)
assert cos(x + pi) == -cos(x)
assert cos(x + 2*pi) == cos(x)
assert cos(x + 3*pi) == -cos(x)
assert cos(x + 4*pi) == cos(x)
assert cos(x - 5*pi) == -cos(x)
assert tan(x + pi) == tan(x)
assert tan(x - 3*pi) == tan(x)
assert cot(x + pi) == cot(x)
assert cot(x - 3*pi) == cot(x)
assert sin(pi/2 - x) == cos(x)
assert sin(pi*Rational(3, 2) - x) == -cos(x)
assert sin(pi*Rational(5, 2) - x) == cos(x)
assert cos(pi/2 - x) == sin(x)
assert cos(pi*Rational(3, 2) - x) == -sin(x)
assert cos(pi*Rational(5, 2) - x) == sin(x)
assert tan(pi/2 - x) == cot(x)
assert tan(pi*Rational(3, 2) - x) == cot(x)
assert tan(pi*Rational(5, 2) - x) == cot(x)
assert cot(pi/2 - x) == tan(x)
assert cot(pi*Rational(3, 2) - x) == tan(x)
assert cot(pi*Rational(5, 2) - x) == tan(x)
assert sin(pi/2 + x) == cos(x)
assert cos(pi/2 + x) == -sin(x)
assert tan(pi/2 + x) == -cot(x)
assert cot(pi/2 + x) == -tan(x)
def test_cos():
x, y = symbols('x y')
assert cos.nargs == FiniteSet(1)
assert cos(nan) is nan
assert cos(oo) == AccumBounds(-1, 1)
assert cos(oo) - cos(oo) == AccumBounds(-2, 2)
assert cos(oo*I) is oo
assert cos(-oo*I) is oo
assert cos(zoo) is nan
assert cos(0) == 1
assert cos(acos(x)) == x
assert cos(atan(x)) == 1 / sqrt(1 + x**2)
assert cos(asin(x)) == sqrt(1 - x**2)
assert cos(acot(x)) == 1 / sqrt(1 + 1 / x**2)
assert cos(acsc(x)) == sqrt(1 - 1 / x**2)
assert cos(asec(x)) == 1 / x
assert cos(atan2(y, x)) == x / sqrt(x**2 + y**2)
assert cos(pi*I) == cosh(pi)
assert cos(-pi*I) == cosh(pi)
assert cos(-2*I) == cosh(2)
assert cos(pi/2) == 0
assert cos(-pi/2) == 0
assert cos(pi/2) == 0
assert cos(-pi/2) == 0
assert cos((-3*10**73 + 1)*pi/2) == 0
assert cos((7*10**103 + 1)*pi/2) == 0
n = symbols('n', integer=True, even=False)
e = symbols('e', even=True)
assert cos(pi*n/2) == 0
assert cos(pi*e/2) == (-1)**(e/2)
assert cos(pi) == -1
assert cos(-pi) == -1
assert cos(2*pi) == 1
assert cos(5*pi) == -1
assert cos(8*pi) == 1
assert cos(pi/3) == S.Half
assert cos(pi*Rational(-2, 3)) == Rational(-1, 2)
assert cos(pi/4) == S.Half*sqrt(2)
assert cos(-pi/4) == S.Half*sqrt(2)
assert cos(pi*Rational(11, 4)) == Rational(-1, 2)*sqrt(2)
assert cos(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
assert cos(pi/6) == S.Half*sqrt(3)
assert cos(-pi/6) == S.Half*sqrt(3)
assert cos(pi*Rational(7, 6)) == Rational(-1, 2)*sqrt(3)
assert cos(pi*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3)
assert cos(pi*Rational(1, 5)) == (sqrt(5) + 1)/4
assert cos(pi*Rational(2, 5)) == (sqrt(5) - 1)/4
assert cos(pi*Rational(3, 5)) == -cos(pi*Rational(2, 5))
assert cos(pi*Rational(4, 5)) == -cos(pi*Rational(1, 5))
assert cos(pi*Rational(6, 5)) == -cos(pi*Rational(1, 5))
assert cos(pi*Rational(8, 5)) == cos(pi*Rational(2, 5))
assert cos(pi*Rational(-1273, 5)) == -cos(pi*Rational(2, 5))
assert cos(pi/8) == sqrt((2 + sqrt(2))/4)
assert cos(pi/12) == sqrt(2)/4 + sqrt(6)/4
assert cos(pi*Rational(5, 12)) == -sqrt(2)/4 + sqrt(6)/4
assert cos(pi*Rational(7, 12)) == sqrt(2)/4 - sqrt(6)/4
assert cos(pi*Rational(11, 12)) == -sqrt(2)/4 - sqrt(6)/4
assert cos(pi*Rational(104, 105)) == -cos(pi/105)
assert cos(pi*Rational(106, 105)) == -cos(pi/105)
assert cos(pi*Rational(-104, 105)) == -cos(pi/105)
assert cos(pi*Rational(-106, 105)) == -cos(pi/105)
assert cos(x*I) == cosh(x)
assert cos(k*pi*I) == cosh(k*pi)
assert cos(r).is_real is True
assert cos(0, evaluate=False).is_algebraic
assert cos(a).is_algebraic is None
assert cos(na).is_algebraic is False
q = Symbol('q', rational=True)
assert cos(pi*q).is_algebraic
assert cos(pi*Rational(2, 7)).is_algebraic
assert cos(k*pi) == (-1)**k
assert cos(2*k*pi) == 1
for d in list(range(1, 22)) + [60, 85]:
for n in range(0, 2*d + 1):
x = n*pi/d
e = abs( float(cos(x)) - cos(float(x)) )
assert e < 1e-12
def test_issue_6190():
c = Float('123456789012345678901234567890.25', '')
for cls in [sin, cos, tan, cot]:
assert cls(c*pi) == cls(pi/4)
assert cls(4.125*pi) == cls(pi/8)
assert cls(4.7*pi) == cls((4.7 % 2)*pi)
def test_cos_series():
assert cos(x).series(x, 0, 9) == \
1 - x**2/2 + x**4/24 - x**6/720 + x**8/40320 + O(x**9)
def test_cos_rewrite():
assert cos(x).rewrite(exp) == exp(I*x)/2 + exp(-I*x)/2
assert cos(x).rewrite(tan) == (1 - tan(x/2)**2)/(1 + tan(x/2)**2)
assert cos(x).rewrite(cot) == -(1 - cot(x/2)**2)/(1 + cot(x/2)**2)
assert cos(sinh(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sinh(3)).n()
assert cos(cosh(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cosh(3)).n()
assert cos(tanh(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tanh(3)).n()
assert cos(coth(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, coth(3)).n()
assert cos(sin(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sin(3)).n()
assert cos(cos(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cos(3)).n()
assert cos(tan(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tan(3)).n()
assert cos(cot(x)).rewrite(
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cot(3)).n()
assert cos(log(x)).rewrite(Pow) == x**I/2 + x**-I/2
assert cos(x).rewrite(sec) == 1/sec(x)
assert cos(x).rewrite(sin) == sin(x + pi/2, evaluate=False)
assert cos(x).rewrite(csc) == 1/csc(-x + pi/2, evaluate=False)
assert cos(sin(x)).rewrite(Pow) == cos(sin(x))
def test_cos_expansion():
assert cos(x + y).expand(trig=True) == cos(x)*cos(y) - sin(x)*sin(y)
assert cos(x - y).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y)
assert cos(y - x).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y)
assert cos(2*x).expand(trig=True) == 2*cos(x)**2 - 1
assert cos(3*x).expand(trig=True) == 4*cos(x)**3 - 3*cos(x)
assert cos(4*x).expand(trig=True) == 8*cos(x)**4 - 8*cos(x)**2 + 1
_test_extrig(cos, 2, 2*cos(1)**2 - 1)
_test_extrig(cos, 3, 4*cos(1)**3 - 3*cos(1))
def test_cos_AccumBounds():
assert cos(AccumBounds(-oo, oo)) == AccumBounds(-1, 1)
assert cos(AccumBounds(0, oo)) == AccumBounds(-1, 1)
assert cos(AccumBounds(-oo, 0)) == AccumBounds(-1, 1)
assert cos(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1)
assert cos(AccumBounds(-S.Pi/3, S.Pi/4)) == AccumBounds(cos(-S.Pi/3), 1)
assert cos(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 4))) == AccumBounds(-1, cos(S.Pi*Rational(3, 4)))
assert cos(AccumBounds(S.Pi*Rational(5, 4), S.Pi*Rational(4, 3))) == AccumBounds(cos(S.Pi*Rational(5, 4)), cos(S.Pi*Rational(4, 3)))
assert cos(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(cos(S.Pi/3), cos(S.Pi/4))
def test_cos_fdiff():
assert cos(x).fdiff() == -sin(x)
raises(ArgumentIndexError, lambda: cos(x).fdiff(2))
def test_tan():
assert tan(nan) is nan
assert tan(zoo) is nan
assert tan(oo) == AccumBounds(-oo, oo)
assert tan(oo) - tan(oo) == AccumBounds(-oo, oo)
assert tan.nargs == FiniteSet(1)
assert tan(oo*I) == I
assert tan(-oo*I) == -I
assert tan(0) == 0
assert tan(atan(x)) == x
assert tan(asin(x)) == x / sqrt(1 - x**2)
assert tan(acos(x)) == sqrt(1 - x**2) / x
assert tan(acot(x)) == 1 / x
assert tan(acsc(x)) == 1 / (sqrt(1 - 1 / x**2) * x)
assert tan(asec(x)) == sqrt(1 - 1 / x**2) * x
assert tan(atan2(y, x)) == y/x
assert tan(pi*I) == tanh(pi)*I
assert tan(-pi*I) == -tanh(pi)*I
assert tan(-2*I) == -tanh(2)*I
assert tan(pi) == 0
assert tan(-pi) == 0
assert tan(2*pi) == 0
assert tan(-2*pi) == 0
assert tan(-3*10**73*pi) == 0
assert tan(pi/2) is zoo
assert tan(pi*Rational(3, 2)) is zoo
assert tan(pi/3) == sqrt(3)
assert tan(pi*Rational(-2, 3)) == sqrt(3)
assert tan(pi/4) is S.One
assert tan(-pi/4) is S.NegativeOne
assert tan(pi*Rational(17, 4)) is S.One
assert tan(pi*Rational(-3, 4)) is S.One
assert tan(pi/5) == sqrt(5 - 2*sqrt(5))
assert tan(pi*Rational(2, 5)) == sqrt(5 + 2*sqrt(5))
assert tan(pi*Rational(18, 5)) == -sqrt(5 + 2*sqrt(5))
assert tan(pi*Rational(-16, 5)) == -sqrt(5 - 2*sqrt(5))
assert tan(pi/6) == 1/sqrt(3)
assert tan(-pi/6) == -1/sqrt(3)
assert tan(pi*Rational(7, 6)) == 1/sqrt(3)
assert tan(pi*Rational(-5, 6)) == 1/sqrt(3)
assert tan(pi/8) == -1 + sqrt(2)
assert tan(pi*Rational(3, 8)) == 1 + sqrt(2) # issue 15959
assert tan(pi*Rational(5, 8)) == -1 - sqrt(2)
assert tan(pi*Rational(7, 8)) == 1 - sqrt(2)
assert tan(pi/10) == sqrt(1 - 2*sqrt(5)/5)
assert tan(pi*Rational(3, 10)) == sqrt(1 + 2*sqrt(5)/5)
assert tan(pi*Rational(17, 10)) == -sqrt(1 + 2*sqrt(5)/5)
assert tan(pi*Rational(-31, 10)) == -sqrt(1 - 2*sqrt(5)/5)
assert tan(pi/12) == -sqrt(3) + 2
assert tan(pi*Rational(5, 12)) == sqrt(3) + 2
assert tan(pi*Rational(7, 12)) == -sqrt(3) - 2
assert tan(pi*Rational(11, 12)) == sqrt(3) - 2
assert tan(pi/24).radsimp() == -2 - sqrt(3) + sqrt(2) + sqrt(6)
assert tan(pi*Rational(5, 24)).radsimp() == -2 + sqrt(3) - sqrt(2) + sqrt(6)
assert tan(pi*Rational(7, 24)).radsimp() == 2 - sqrt(3) - sqrt(2) + sqrt(6)
assert tan(pi*Rational(11, 24)).radsimp() == 2 + sqrt(3) + sqrt(2) + sqrt(6)
assert tan(pi*Rational(13, 24)).radsimp() == -2 - sqrt(3) - sqrt(2) - sqrt(6)
assert tan(pi*Rational(17, 24)).radsimp() == -2 + sqrt(3) + sqrt(2) - sqrt(6)
assert tan(pi*Rational(19, 24)).radsimp() == 2 - sqrt(3) + sqrt(2) - sqrt(6)
assert tan(pi*Rational(23, 24)).radsimp() == 2 + sqrt(3) - sqrt(2) - sqrt(6)
assert tan(x*I) == tanh(x)*I
assert tan(k*pi) == 0
assert tan(17*k*pi) == 0
assert tan(k*pi*I) == tanh(k*pi)*I
assert tan(r).is_real is None
assert tan(r).is_extended_real is True
assert tan(0, evaluate=False).is_algebraic
assert tan(a).is_algebraic is None
assert tan(na).is_algebraic is False
assert tan(pi*Rational(10, 7)) == tan(pi*Rational(3, 7))
assert tan(pi*Rational(11, 7)) == -tan(pi*Rational(3, 7))
assert tan(pi*Rational(-11, 7)) == tan(pi*Rational(3, 7))
assert tan(pi*Rational(15, 14)) == tan(pi/14)
assert tan(pi*Rational(-15, 14)) == -tan(pi/14)
assert tan(r).is_finite is None
assert tan(I*r).is_finite is True
# https://github.com/sympy/sympy/issues/21177
f = tan(pi*(x + S(3)/2))/(3*x)
assert f.as_leading_term(x) == -1/(3*pi*x**2)
def test_tan_series():
assert tan(x).series(x, 0, 9) == \
x + x**3/3 + 2*x**5/15 + 17*x**7/315 + O(x**9)
def test_tan_rewrite():
neg_exp, pos_exp = exp(-x*I), exp(x*I)
assert tan(x).rewrite(exp) == I*(neg_exp - pos_exp)/(neg_exp + pos_exp)
assert tan(x).rewrite(sin) == 2*sin(x)**2/sin(2*x)
assert tan(x).rewrite(cos) == cos(x - S.Pi/2, evaluate=False)/cos(x)
assert tan(x).rewrite(cot) == 1/cot(x)
assert tan(sinh(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sinh(3)).n()
assert tan(cosh(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cosh(3)).n()
assert tan(tanh(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tanh(3)).n()
assert tan(coth(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, coth(3)).n()
assert tan(sin(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sin(3)).n()
assert tan(cos(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cos(3)).n()
assert tan(tan(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tan(3)).n()
assert tan(cot(x)).rewrite(
exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cot(3)).n()
assert tan(log(x)).rewrite(Pow) == I*(x**-I - x**I)/(x**-I + x**I)
assert 0 == (cos(pi/34)*tan(pi/34) - sin(pi/34)).rewrite(pow)
assert 0 == (cos(pi/17)*tan(pi/17) - sin(pi/17)).rewrite(pow)
assert tan(pi/19).rewrite(pow) == tan(pi/19)
assert tan(pi*Rational(8, 19)).rewrite(sqrt) == tan(pi*Rational(8, 19))
assert tan(x).rewrite(sec) == sec(x)/sec(x - pi/2, evaluate=False)
assert tan(x).rewrite(csc) == csc(-x + pi/2, evaluate=False)/csc(x)
assert tan(sin(x)).rewrite(Pow) == tan(sin(x))
assert tan(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == sqrt(sqrt(5)/8 +
Rational(5, 8))/(Rational(-1, 4) + sqrt(5)/4)
def test_tan_subs():
assert tan(x).subs(tan(x), y) == y
assert tan(x).subs(x, y) == tan(y)
assert tan(x).subs(x, S.Pi/2) is zoo
assert tan(x).subs(x, S.Pi*Rational(3, 2)) is zoo
def test_tan_expansion():
assert tan(x + y).expand(trig=True) == ((tan(x) + tan(y))/(1 - tan(x)*tan(y))).expand()
assert tan(x - y).expand(trig=True) == ((tan(x) - tan(y))/(1 + tan(x)*tan(y))).expand()
assert tan(x + y + z).expand(trig=True) == (
(tan(x) + tan(y) + tan(z) - tan(x)*tan(y)*tan(z))/
(1 - tan(x)*tan(y) - tan(x)*tan(z) - tan(y)*tan(z))).expand()
assert 0 == tan(2*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 7))])*24 - 7
assert 0 == tan(3*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*55 - 37
assert 0 == tan(4*x - pi/4).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*239 - 1
_test_extrig(tan, 2, 2*tan(1)/(1 - tan(1)**2))
_test_extrig(tan, 3, (-tan(1)**3 + 3*tan(1))/(1 - 3*tan(1)**2))
def test_tan_AccumBounds():
assert tan(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo)
assert tan(AccumBounds(S.Pi/3, S.Pi*Rational(2, 3))) == AccumBounds(-oo, oo)
assert tan(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(tan(S.Pi/6), tan(S.Pi/3))
def test_tan_fdiff():
assert tan(x).fdiff() == tan(x)**2 + 1
raises(ArgumentIndexError, lambda: tan(x).fdiff(2))
def test_cot():
assert cot(nan) is nan
assert cot.nargs == FiniteSet(1)
assert cot(oo*I) == -I
assert cot(-oo*I) == I
assert cot(zoo) is nan
assert cot(0) is zoo
assert cot(2*pi) is zoo
assert cot(acot(x)) == x
assert cot(atan(x)) == 1 / x
assert cot(asin(x)) == sqrt(1 - x**2) / x
assert cot(acos(x)) == x / sqrt(1 - x**2)
assert cot(acsc(x)) == sqrt(1 - 1 / x**2) * x
assert cot(asec(x)) == 1 / (sqrt(1 - 1 / x**2) * x)
assert cot(atan2(y, x)) == x/y
assert cot(pi*I) == -coth(pi)*I
assert cot(-pi*I) == coth(pi)*I
assert cot(-2*I) == coth(2)*I
assert cot(pi) == cot(2*pi) == cot(3*pi)
assert cot(-pi) == cot(-2*pi) == cot(-3*pi)
assert cot(pi/2) == 0
assert cot(-pi/2) == 0
assert cot(pi*Rational(5, 2)) == 0
assert cot(pi*Rational(7, 2)) == 0
assert cot(pi/3) == 1/sqrt(3)
assert cot(pi*Rational(-2, 3)) == 1/sqrt(3)
assert cot(pi/4) is S.One
assert cot(-pi/4) is S.NegativeOne
assert cot(pi*Rational(17, 4)) is S.One
assert cot(pi*Rational(-3, 4)) is S.One
assert cot(pi/6) == sqrt(3)
assert cot(-pi/6) == -sqrt(3)
assert cot(pi*Rational(7, 6)) == sqrt(3)
assert cot(pi*Rational(-5, 6)) == sqrt(3)
assert cot(pi/8) == 1 + sqrt(2)
assert cot(pi*Rational(3, 8)) == -1 + sqrt(2)
assert cot(pi*Rational(5, 8)) == 1 - sqrt(2)
assert cot(pi*Rational(7, 8)) == -1 - sqrt(2)
assert cot(pi/12) == sqrt(3) + 2
assert cot(pi*Rational(5, 12)) == -sqrt(3) + 2
assert cot(pi*Rational(7, 12)) == sqrt(3) - 2
assert cot(pi*Rational(11, 12)) == -sqrt(3) - 2
assert cot(pi/24).radsimp() == sqrt(2) + sqrt(3) + 2 + sqrt(6)
assert cot(pi*Rational(5, 24)).radsimp() == -sqrt(2) - sqrt(3) + 2 + sqrt(6)
assert cot(pi*Rational(7, 24)).radsimp() == -sqrt(2) + sqrt(3) - 2 + sqrt(6)
assert cot(pi*Rational(11, 24)).radsimp() == sqrt(2) - sqrt(3) - 2 + sqrt(6)
assert cot(pi*Rational(13, 24)).radsimp() == -sqrt(2) + sqrt(3) + 2 - sqrt(6)
assert cot(pi*Rational(17, 24)).radsimp() == sqrt(2) - sqrt(3) + 2 - sqrt(6)
assert cot(pi*Rational(19, 24)).radsimp() == sqrt(2) + sqrt(3) - 2 - sqrt(6)
assert cot(pi*Rational(23, 24)).radsimp() == -sqrt(2) - sqrt(3) - 2 - sqrt(6)
assert cot(x*I) == -coth(x)*I
assert cot(k*pi*I) == -coth(k*pi)*I
assert cot(r).is_real is None
assert cot(r).is_extended_real is True
assert cot(a).is_algebraic is None
assert cot(na).is_algebraic is False
assert cot(pi*Rational(10, 7)) == cot(pi*Rational(3, 7))
assert cot(pi*Rational(11, 7)) == -cot(pi*Rational(3, 7))
assert cot(pi*Rational(-11, 7)) == cot(pi*Rational(3, 7))
assert cot(pi*Rational(39, 34)) == cot(pi*Rational(5, 34))
assert cot(pi*Rational(-41, 34)) == -cot(pi*Rational(7, 34))
assert cot(x).is_finite is None
assert cot(r).is_finite is None
i = Symbol('i', imaginary=True)
assert cot(i).is_finite is True
assert cot(x).subs(x, 3*pi) is zoo
# https://github.com/sympy/sympy/issues/21177
f = cot(pi*(x + 4))/(3*x)
assert f.as_leading_term(x) == 1/(3*pi*x**2)
def test_tan_cot_sin_cos_evalf():
assert abs((tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15)) - 1).evalf()) < 1e-14
assert abs((cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15)) - 1).evalf()) < 1e-14
@XFAIL
def test_tan_cot_sin_cos_ratsimp():
assert 1 == (tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15))).ratsimp()
assert 1 == (cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15))).ratsimp()
def test_cot_series():
assert cot(x).series(x, 0, 9) == \
1/x - x/3 - x**3/45 - 2*x**5/945 - x**7/4725 + O(x**9)
# issue 6210
assert cot(x**4 + x**5).series(x, 0, 1) == \
x**(-4) - 1/x**3 + x**(-2) - 1/x + 1 + O(x)
assert cot(pi*(1-x)).series(x, 0, 3) == -1/(pi*x) + pi*x/3 + O(x**3)
assert cot(x).taylor_term(0, x) == 1/x
assert cot(x).taylor_term(2, x) is S.Zero
assert cot(x).taylor_term(3, x) == -x**3/45
def test_cot_rewrite():
neg_exp, pos_exp = exp(-x*I), exp(x*I)
assert cot(x).rewrite(exp) == I*(pos_exp + neg_exp)/(pos_exp - neg_exp)
assert cot(x).rewrite(sin) == sin(2*x)/(2*(sin(x)**2))
assert cot(x).rewrite(cos) == cos(x)/cos(x - pi/2, evaluate=False)
assert cot(x).rewrite(tan) == 1/tan(x)
assert cot(sinh(x)).rewrite(
exp).subs(x, 3).n() == cot(x).rewrite(exp).subs(x, sinh(3)).n()
assert cot(cosh(x)).rewrite(
exp).subs(x, 3).n() == cot(x).rewrite(exp).subs(x, cosh(3)).n()
assert cot(tanh(x)).rewrite(
exp).subs(x, 3).n() == cot(x).rewrite(exp).subs(x, tanh(3)).n()
assert cot(coth(x)).rewrite(
exp).subs(x, 3).n() == cot(x).rewrite(exp).subs(x, coth(3)).n()
assert cot(sin(x)).rewrite(
exp).subs(x, 3).n() == cot(x).rewrite(exp).subs(x, sin(3)).n()
assert cot(tan(x)).rewrite(
exp).subs(x, 3).n() == cot(x).rewrite(exp).subs(x, tan(3)).n()
assert cot(log(x)).rewrite(Pow) == -I*(x**-I + x**I)/(x**-I - x**I)
assert cot(pi*Rational(4, 34)).rewrite(pow).ratsimp() == (cos(pi*Rational(4, 34))/sin(pi*Rational(4, 34))).rewrite(pow).ratsimp()
assert cot(pi*Rational(4, 17)).rewrite(pow) == (cos(pi*Rational(4, 17))/sin(pi*Rational(4, 17))).rewrite(pow)
assert cot(pi/19).rewrite(pow) == cot(pi/19)
assert cot(pi/19).rewrite(sqrt) == cot(pi/19)
assert cot(x).rewrite(sec) == sec(x - pi / 2, evaluate=False) / sec(x)
assert cot(x).rewrite(csc) == csc(x) / csc(- x + pi / 2, evaluate=False)
assert cot(sin(x)).rewrite(Pow) == cot(sin(x))
assert cot(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == (Rational(-1, 4) + sqrt(5)/4)/\
sqrt(sqrt(5)/8 + Rational(5, 8))
def test_cot_subs():
assert cot(x).subs(cot(x), y) == y
assert cot(x).subs(x, y) == cot(y)
assert cot(x).subs(x, 0) is zoo
assert cot(x).subs(x, S.Pi) is zoo
def test_cot_expansion():
assert cot(x + y).expand(trig=True).together() == (
(cot(x)*cot(y) - 1)/(cot(x) + cot(y)))
assert cot(x - y).expand(trig=True).together() == (
cot(x)*cot(-y) - 1)/(cot(x) + cot(-y))
assert cot(x + y + z).expand(trig=True).together() == (
(cot(x)*cot(y)*cot(z) - cot(x) - cot(y) - cot(z))/
(-1 + cot(x)*cot(y) + cot(x)*cot(z) + cot(y)*cot(z)))
assert cot(3*x).expand(trig=True).together() == (
(cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1))
assert cot(2*x).expand(trig=True) == cot(x)/2 - 1/(2*cot(x))
assert cot(3*x).expand(trig=True).together() == (
cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1)
assert cot(4*x - pi/4).expand(trig=True).cancel() == (
-tan(x)**4 + 4*tan(x)**3 + 6*tan(x)**2 - 4*tan(x) - 1
)/(tan(x)**4 + 4*tan(x)**3 - 6*tan(x)**2 - 4*tan(x) + 1)
_test_extrig(cot, 2, (-1 + cot(1)**2)/(2*cot(1)))
_test_extrig(cot, 3, (-3*cot(1) + cot(1)**3)/(-1 + 3*cot(1)**2))
def test_cot_AccumBounds():
assert cot(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo)
assert cot(AccumBounds(-S.Pi/3, S.Pi/3)) == AccumBounds(-oo, oo)
assert cot(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(cot(S.Pi/3), cot(S.Pi/6))
def test_cot_fdiff():
assert cot(x).fdiff() == -cot(x)**2 - 1
raises(ArgumentIndexError, lambda: cot(x).fdiff(2))
def test_sinc():
assert isinstance(sinc(x), sinc)
s = Symbol('s', zero=True)
assert sinc(s) is S.One
assert sinc(S.Infinity) is S.Zero
assert sinc(S.NegativeInfinity) is S.Zero
assert sinc(S.NaN) is S.NaN
assert sinc(S.ComplexInfinity) is S.NaN
n = Symbol('n', integer=True, nonzero=True)
assert sinc(n*pi) is S.Zero
assert sinc(-n*pi) is S.Zero
assert sinc(pi/2) == 2 / pi
assert sinc(-pi/2) == 2 / pi
assert sinc(pi*Rational(5, 2)) == 2 / (5*pi)
assert sinc(pi*Rational(7, 2)) == -2 / (7*pi)
assert sinc(-x) == sinc(x)
assert sinc(x).diff(x) == cos(x)/x - sin(x)/x**2
assert sinc(x).diff(x) == (sin(x)/x).diff(x)
assert sinc(x).diff(x, x) == (-sin(x) - 2*cos(x)/x + 2*sin(x)/x**2)/x
assert sinc(x).diff(x, x) == (sin(x)/x).diff(x, x)
assert limit(sinc(x).diff(x), x, 0) == 0
assert limit(sinc(x).diff(x, x), x, 0) == -S(1)/3
# https://github.com/sympy/sympy/issues/11402
#
# assert sinc(x).diff(x) == Piecewise(((x*cos(x) - sin(x)) / x**2, Ne(x, 0)), (0, True))
#
# assert sinc(x).diff(x).equals(sinc(x).rewrite(sin).diff(x))
#
# assert sinc(x).diff(x).subs(x, 0) is S.Zero
assert sinc(x).series() == 1 - x**2/6 + x**4/120 + O(x**6)
assert sinc(x).rewrite(jn) == jn(0, x)
assert sinc(x).rewrite(sin) == Piecewise((sin(x)/x, Ne(x, 0)), (1, True))
def test_asin():
assert asin(nan) is nan
assert asin.nargs == FiniteSet(1)
assert asin(oo) == -I*oo
assert asin(-oo) == I*oo
assert asin(zoo) is zoo
# Note: asin(-x) = - asin(x)
assert asin(0) == 0
assert asin(1) == pi/2
assert asin(-1) == -pi/2
assert asin(sqrt(3)/2) == pi/3
assert asin(-sqrt(3)/2) == -pi/3
assert asin(sqrt(2)/2) == pi/4
assert asin(-sqrt(2)/2) == -pi/4
assert asin(sqrt((5 - sqrt(5))/8)) == pi/5
assert asin(-sqrt((5 - sqrt(5))/8)) == -pi/5
assert asin(S.Half) == pi/6
assert asin(Rational(-1, 2)) == -pi/6
assert asin((sqrt(2 - sqrt(2)))/2) == pi/8
assert asin(-(sqrt(2 - sqrt(2)))/2) == -pi/8
assert asin((sqrt(5) - 1)/4) == pi/10
assert asin(-(sqrt(5) - 1)/4) == -pi/10
assert asin((sqrt(3) - 1)/sqrt(2**3)) == pi/12
assert asin(-(sqrt(3) - 1)/sqrt(2**3)) == -pi/12
# check round-trip for exact values:
for d in [5, 6, 8, 10, 12]:
for n in range(-(d//2), d//2 + 1):
if gcd(n, d) == 1:
assert asin(sin(n*pi/d)) == n*pi/d
assert asin(x).diff(x) == 1/sqrt(1 - x**2)
assert asin(1/x).as_leading_term(x) == I*log(1/x)
assert asin(0.2).is_real is True
assert asin(-2).is_real is False
assert asin(r).is_real is None
assert asin(-2*I) == -I*asinh(2)
assert asin(Rational(1, 7), evaluate=False).is_positive is True
assert asin(Rational(-1, 7), evaluate=False).is_positive is False
assert asin(p).is_positive is None
assert asin(sin(Rational(7, 2))) == Rational(-7, 2) + pi
assert asin(sin(Rational(-7, 4))) == Rational(7, 4) - pi
assert unchanged(asin, cos(x))
def test_asin_series():
assert asin(x).series(x, 0, 9) == \
x + x**3/6 + 3*x**5/40 + 5*x**7/112 + O(x**9)
t5 = asin(x).taylor_term(5, x)
assert t5 == 3*x**5/40
assert asin(x).taylor_term(7, x, t5, 0) == 5*x**7/112
def test_asin_rewrite():
assert asin(x).rewrite(log) == -I*log(I*x + sqrt(1 - x**2))
assert asin(x).rewrite(atan) == 2*atan(x/(1 + sqrt(1 - x**2)))
assert asin(x).rewrite(acos) == S.Pi/2 - acos(x)
assert asin(x).rewrite(acot) == 2*acot((sqrt(-x**2 + 1) + 1)/x)
assert asin(x).rewrite(asec) == -asec(1/x) + pi/2
assert asin(x).rewrite(acsc) == acsc(1/x)
def test_asin_fdiff():
assert asin(x).fdiff() == 1/sqrt(1 - x**2)
raises(ArgumentIndexError, lambda: asin(x).fdiff(2))
def test_acos():
assert acos(nan) is nan
assert acos(zoo) is zoo
assert acos.nargs == FiniteSet(1)
assert acos(oo) == I*oo
assert acos(-oo) == -I*oo
# Note: acos(-x) = pi - acos(x)
assert acos(0) == pi/2
assert acos(S.Half) == pi/3
assert acos(Rational(-1, 2)) == pi*Rational(2, 3)
assert acos(1) == 0
assert acos(-1) == pi
assert acos(sqrt(2)/2) == pi/4
assert acos(-sqrt(2)/2) == pi*Rational(3, 4)
# check round-trip for exact values:
for d in [5, 6, 8, 10, 12]:
for num in range(d):
if gcd(num, d) == 1:
assert acos(cos(num*pi/d)) == num*pi/d
assert acos(2*I) == pi/2 - asin(2*I)
assert acos(x).diff(x) == -1/sqrt(1 - x**2)
assert acos(1/x).as_leading_term(x) == I*log(1/x)
assert acos(0.2).is_real is True
assert acos(-2).is_real is False
assert acos(r).is_real is None
assert acos(Rational(1, 7), evaluate=False).is_positive is True
assert acos(Rational(-1, 7), evaluate=False).is_positive is True
assert acos(Rational(3, 2), evaluate=False).is_positive is False
assert acos(p).is_positive is None
assert acos(2 + p).conjugate() != acos(10 + p)
assert acos(-3 + n).conjugate() != acos(-3 + n)
assert acos(Rational(1, 3)).conjugate() == acos(Rational(1, 3))
assert acos(Rational(-1, 3)).conjugate() == acos(Rational(-1, 3))
assert acos(p + n*I).conjugate() == acos(p - n*I)
assert acos(z).conjugate() != acos(conjugate(z))
def test_acos_series():
assert acos(x).series(x, 0, 8) == \
pi/2 - x - x**3/6 - 3*x**5/40 - 5*x**7/112 + O(x**8)
assert acos(x).series(x, 0, 8) == pi/2 - asin(x).series(x, 0, 8)
t5 = acos(x).taylor_term(5, x)
assert t5 == -3*x**5/40
assert acos(x).taylor_term(7, x, t5, 0) == -5*x**7/112
assert acos(x).taylor_term(0, x) == pi/2
assert acos(x).taylor_term(2, x) is S.Zero
def test_acos_rewrite():
assert acos(x).rewrite(log) == pi/2 + I*log(I*x + sqrt(1 - x**2))
assert acos(x).rewrite(atan) == \
atan(sqrt(1 - x**2)/x) + (pi/2)*(1 - x*sqrt(1/x**2))
assert acos(0).rewrite(atan) == S.Pi/2
assert acos(0.5).rewrite(atan) == acos(0.5).rewrite(log)
assert acos(x).rewrite(asin) == S.Pi/2 - asin(x)
assert acos(x).rewrite(acot) == -2*acot((sqrt(-x**2 + 1) + 1)/x) + pi/2
assert acos(x).rewrite(asec) == asec(1/x)
assert acos(x).rewrite(acsc) == -acsc(1/x) + pi/2
def test_acos_fdiff():
assert acos(x).fdiff() == -1/sqrt(1 - x**2)
raises(ArgumentIndexError, lambda: acos(x).fdiff(2))
def test_atan():
assert atan(nan) is nan
assert atan.nargs == FiniteSet(1)
assert atan(oo) == pi/2
assert atan(-oo) == -pi/2
assert atan(zoo) == AccumBounds(-pi/2, pi/2)
assert atan(0) == 0
assert atan(1) == pi/4
assert atan(sqrt(3)) == pi/3
assert atan(-(1 + sqrt(2))) == pi*Rational(-3, 8)
assert atan(sqrt(5 - 2 * sqrt(5))) == pi/5
assert atan(-sqrt(1 - 2 * sqrt(5)/ 5)) == -pi/10
assert atan(sqrt(1 + 2 * sqrt(5) / 5)) == pi*Rational(3, 10)
assert atan(-2 + sqrt(3)) == -pi/12
assert atan(2 + sqrt(3)) == pi*Rational(5, 12)
assert atan(-2 - sqrt(3)) == pi*Rational(-5, 12)
# check round-trip for exact values:
for d in [5, 6, 8, 10, 12]:
for num in range(-(d//2), d//2 + 1):
if gcd(num, d) == 1:
assert atan(tan(num*pi/d)) == num*pi/d
assert atan(oo) == pi/2
assert atan(x).diff(x) == 1/(1 + x**2)
assert atan(1/x).as_leading_term(x) == pi/2
assert atan(r).is_real is True
assert atan(-2*I) == -I*atanh(2)
assert unchanged(atan, cot(x))
assert atan(cot(Rational(1, 4))) == Rational(-1, 4) + pi/2
assert acot(Rational(1, 4)).is_rational is False
for s in (x, p, n, np, nn, nz, ep, en, enp, enn, enz):
if s.is_real or s.is_extended_real is None:
assert s.is_nonzero is atan(s).is_nonzero
assert s.is_positive is atan(s).is_positive
assert s.is_negative is atan(s).is_negative
assert s.is_nonpositive is atan(s).is_nonpositive
assert s.is_nonnegative is atan(s).is_nonnegative
else:
assert s.is_extended_nonzero is atan(s).is_nonzero
assert s.is_extended_positive is atan(s).is_positive
assert s.is_extended_negative is atan(s).is_negative
assert s.is_extended_nonpositive is atan(s).is_nonpositive
assert s.is_extended_nonnegative is atan(s).is_nonnegative
assert s.is_extended_nonzero is atan(s).is_extended_nonzero
assert s.is_extended_positive is atan(s).is_extended_positive
assert s.is_extended_negative is atan(s).is_extended_negative
assert s.is_extended_nonpositive is atan(s).is_extended_nonpositive
assert s.is_extended_nonnegative is atan(s).is_extended_nonnegative
def test_atan_rewrite():
assert atan(x).rewrite(log) == I*(log(1 - I*x)-log(1 + I*x))/2
assert atan(x).rewrite(asin) == (-asin(1/sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x
assert atan(x).rewrite(acos) == sqrt(x**2)*acos(1/sqrt(x**2 + 1))/x
assert atan(x).rewrite(acot) == acot(1/x)
assert atan(x).rewrite(asec) == sqrt(x**2)*asec(sqrt(x**2 + 1))/x
assert atan(x).rewrite(acsc) == (-acsc(sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x
assert atan(-5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:-5*I})
assert atan(5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:5*I})
def test_atan_fdiff():
assert atan(x).fdiff() == 1/(x**2 + 1)
raises(ArgumentIndexError, lambda: atan(x).fdiff(2))
def test_atan2():
assert atan2.nargs == FiniteSet(2)
assert atan2(0, 0) is S.NaN
assert atan2(0, 1) == 0
assert atan2(1, 1) == pi/4
assert atan2(1, 0) == pi/2
assert atan2(1, -1) == pi*Rational(3, 4)
assert atan2(0, -1) == pi
assert atan2(-1, -1) == pi*Rational(-3, 4)
assert atan2(-1, 0) == -pi/2
assert atan2(-1, 1) == -pi/4
i = symbols('i', imaginary=True)
r = symbols('r', real=True)
eq = atan2(r, i)
ans = -I*log((i + I*r)/sqrt(i**2 + r**2))
reps = ((r, 2), (i, I))
assert eq.subs(reps) == ans.subs(reps)
x = Symbol('x', negative=True)
y = Symbol('y', negative=True)
assert atan2(y, x) == atan(y/x) - pi
y = Symbol('y', nonnegative=True)
assert atan2(y, x) == atan(y/x) + pi
y = Symbol('y')
assert atan2(y, x) == atan2(y, x, evaluate=False)
u = Symbol("u", positive=True)
assert atan2(0, u) == 0
u = Symbol("u", negative=True)
assert atan2(0, u) == pi
assert atan2(y, oo) == 0
assert atan2(y, -oo)== 2*pi*Heaviside(re(y), S.Half) - pi
assert atan2(y, x).rewrite(log) == -I*log((x + I*y)/sqrt(x**2 + y**2))
assert atan2(0, 0) is S.NaN
ex = atan2(y, x) - arg(x + I*y)
assert ex.subs({x:2, y:3}).rewrite(arg) == 0
assert ex.subs({x:2, y:3*I}).rewrite(arg) == -pi - I*log(sqrt(5)*I/5)
assert ex.subs({x:2*I, y:3}).rewrite(arg) == -pi/2 - I*log(sqrt(5)*I)
assert ex.subs({x:2*I, y:3*I}).rewrite(arg) == -pi + atan(Rational(2, 3)) + atan(Rational(3, 2))
i = symbols('i', imaginary=True)
r = symbols('r', real=True)
e = atan2(i, r)
rewrite = e.rewrite(arg)
reps = {i: I, r: -2}
assert rewrite == -I*log(abs(I*i + r)/sqrt(abs(i**2 + r**2))) + arg((I*i + r)/sqrt(i**2 + r**2))
assert (e - rewrite).subs(reps).equals(0)
assert atan2(0, x).rewrite(atan) == Piecewise((pi, re(x) < 0),
(0, Ne(x, 0)),
(nan, True))
assert atan2(0, r).rewrite(atan) == Piecewise((pi, r < 0), (0, Ne(r, 0)), (S.NaN, True))
assert atan2(0, i),rewrite(atan) == 0
assert atan2(0, r + i).rewrite(atan) == Piecewise((pi, r < 0), (0, True))
assert atan2(y, x).rewrite(atan) == Piecewise(
(2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)),
(pi, re(x) < 0),
(0, (re(x) > 0) | Ne(im(x), 0)),
(nan, True))
assert conjugate(atan2(x, y)) == atan2(conjugate(x), conjugate(y))
assert diff(atan2(y, x), x) == -y/(x**2 + y**2)
assert diff(atan2(y, x), y) == x/(x**2 + y**2)
assert simplify(diff(atan2(y, x).rewrite(log), x)) == -y/(x**2 + y**2)
assert simplify(diff(atan2(y, x).rewrite(log), y)) == x/(x**2 + y**2)
assert str(atan2(1, 2).evalf(5)) == '0.46365'
raises(ArgumentIndexError, lambda: atan2(x, y).fdiff(3))
def test_issue_17461():
class A(Symbol):
is_extended_real = True
def _eval_evalf(self, prec):
return Float(5.0)
x = A('X')
y = A('Y')
assert abs(atan2(x, y).evalf() - 0.785398163397448) <= 1e-10
def test_acot():
assert acot(nan) is nan
assert acot.nargs == FiniteSet(1)
assert acot(-oo) == 0
assert acot(oo) == 0
assert acot(zoo) == 0
assert acot(1) == pi/4
assert acot(0) == pi/2
assert acot(sqrt(3)/3) == pi/3
assert acot(1/sqrt(3)) == pi/3
assert acot(-1/sqrt(3)) == -pi/3
assert acot(x).diff(x) == -1/(1 + x**2)
assert acot(1/x).as_leading_term(x) == x
assert acot(r).is_extended_real is True
assert acot(I*pi) == -I*acoth(pi)
assert acot(-2*I) == I*acoth(2)
assert acot(x).is_positive is None
assert acot(n).is_positive is False
assert acot(p).is_positive is True
assert acot(I).is_positive is False
assert acot(Rational(1, 4)).is_rational is False
assert unchanged(acot, cot(x))
assert unchanged(acot, tan(x))
assert acot(cot(Rational(1, 4))) == Rational(1, 4)
assert acot(tan(Rational(-1, 4))) == Rational(1, 4) - pi/2
def test_acot_rewrite():
assert acot(x).rewrite(log) == I*(log(1 - I/x)-log(1 + I/x))/2
assert acot(x).rewrite(asin) == x*(-asin(sqrt(-x**2)/sqrt(-x**2 - 1)) + pi/2)*sqrt(x**(-2))
assert acot(x).rewrite(acos) == x*sqrt(x**(-2))*acos(sqrt(-x**2)/sqrt(-x**2 - 1))
assert acot(x).rewrite(atan) == atan(1/x)
assert acot(x).rewrite(asec) == x*sqrt(x**(-2))*asec(sqrt((x**2 + 1)/x**2))
assert acot(x).rewrite(acsc) == x*(-acsc(sqrt((x**2 + 1)/x**2)) + pi/2)*sqrt(x**(-2))
assert acot(-I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:-I/5})
assert acot(I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:I/5})
def test_acot_fdiff():
assert acot(x).fdiff() == -1/(x**2 + 1)
raises(ArgumentIndexError, lambda: acot(x).fdiff(2))
def test_attributes():
assert sin(x).args == (x,)
def test_sincos_rewrite():
assert sin(pi/2 - x) == cos(x)
assert sin(pi - x) == sin(x)
assert cos(pi/2 - x) == sin(x)
assert cos(pi - x) == -cos(x)
def _check_even_rewrite(func, arg):
"""Checks that the expr has been rewritten using f(-x) -> f(x)
arg : -x
"""
return func(arg).args[0] == -arg
def _check_odd_rewrite(func, arg):
"""Checks that the expr has been rewritten using f(-x) -> -f(x)
arg : -x
"""
return func(arg).func.is_Mul
def _check_no_rewrite(func, arg):
"""Checks that the expr is not rewritten"""
return func(arg).args[0] == arg
def test_evenodd_rewrite():
a = cos(2) # negative
b = sin(1) # positive
even = [cos]
odd = [sin, tan, cot, asin, atan, acot]
with_minus = [-1, -2**1024 * E, -pi/105, -x*y, -x - y]
for func in even:
for expr in with_minus:
assert _check_even_rewrite(func, expr)
assert _check_no_rewrite(func, a*b)
assert func(
x - y) == func(y - x) # it doesn't matter which form is canonical
for func in odd:
for expr in with_minus:
assert _check_odd_rewrite(func, expr)
assert _check_no_rewrite(func, a*b)
assert func(
x - y) == -func(y - x) # it doesn't matter which form is canonical
def test_issue_4547():
assert sin(x).rewrite(cot) == 2*cot(x/2)/(1 + cot(x/2)**2)
assert cos(x).rewrite(cot) == -(1 - cot(x/2)**2)/(1 + cot(x/2)**2)
assert tan(x).rewrite(cot) == 1/cot(x)
assert cot(x).fdiff() == -1 - cot(x)**2
def test_as_leading_term_issue_5272():
assert sin(x).as_leading_term(x) == x
assert cos(x).as_leading_term(x) == 1
assert tan(x).as_leading_term(x) == x
assert cot(x).as_leading_term(x) == 1/x
assert asin(x).as_leading_term(x) == x
assert acos(x).as_leading_term(x) == pi/2
assert atan(x).as_leading_term(x) == x
assert acot(x).as_leading_term(x) == pi/2
def test_leading_terms():
for func in [sin, cos, tan, cot]:
for a in (1/x, S.Half):
eq = func(a)
assert eq.as_leading_term(x) == eq
# https://github.com/sympy/sympy/issues/21038
f = sin(pi*(x + 4))/(3*x)
assert f.as_leading_term(x) == pi/3
def test_atan2_expansion():
assert cancel(atan2(x**2, x + 1).diff(x) - atan(x**2/(x + 1)).diff(x)) == 0
assert cancel(atan(y/x).series(y, 0, 5) - atan2(y, x).series(y, 0, 5)
+ atan2(0, x) - atan(0)) == O(y**5)
assert cancel(atan(y/x).series(x, 1, 4) - atan2(y, x).series(x, 1, 4)
+ atan2(y, 1) - atan(y)) == O((x - 1)**4, (x, 1))
assert cancel(atan((y + x)/x).series(x, 1, 3) - atan2(y + x, x).series(x, 1, 3)
+ atan2(1 + y, 1) - atan(1 + y)) == O((x - 1)**3, (x, 1))
assert Matrix([atan2(y, x)]).jacobian([y, x]) == \
Matrix([[x/(y**2 + x**2), -y/(y**2 + x**2)]])
def test_aseries():
def t(n, v, d, e):
assert abs(
n(1/v).evalf() - n(1/x).series(x, dir=d).removeO().subs(x, v)) < e
t(atan, 0.1, '+', 1e-5)
t(atan, -0.1, '-', 1e-5)
t(acot, 0.1, '+', 1e-5)
t(acot, -0.1, '-', 1e-5)
def test_issue_4420():
i = Symbol('i', integer=True)
e = Symbol('e', even=True)
o = Symbol('o', odd=True)
# unknown parity for variable
assert cos(4*i*pi) == 1
assert sin(4*i*pi) == 0
assert tan(4*i*pi) == 0
assert cot(4*i*pi) is zoo
assert cos(3*i*pi) == cos(pi*i) # +/-1
assert sin(3*i*pi) == 0
assert tan(3*i*pi) == 0
assert cot(3*i*pi) is zoo
assert cos(4.0*i*pi) == 1
assert sin(4.0*i*pi) == 0
assert tan(4.0*i*pi) == 0
assert cot(4.0*i*pi) is zoo
assert cos(3.0*i*pi) == cos(pi*i) # +/-1
assert sin(3.0*i*pi) == 0
assert tan(3.0*i*pi) == 0
assert cot(3.0*i*pi) is zoo
assert cos(4.5*i*pi) == cos(0.5*pi*i)
assert sin(4.5*i*pi) == sin(0.5*pi*i)
assert tan(4.5*i*pi) == tan(0.5*pi*i)
assert cot(4.5*i*pi) == cot(0.5*pi*i)
# parity of variable is known
assert cos(4*e*pi) == 1
assert sin(4*e*pi) == 0
assert tan(4*e*pi) == 0
assert cot(4*e*pi) is zoo
assert cos(3*e*pi) == 1
assert sin(3*e*pi) == 0
assert tan(3*e*pi) == 0
assert cot(3*e*pi) is zoo
assert cos(4.0*e*pi) == 1
assert sin(4.0*e*pi) == 0
assert tan(4.0*e*pi) == 0
assert cot(4.0*e*pi) is zoo
assert cos(3.0*e*pi) == 1
assert sin(3.0*e*pi) == 0
assert tan(3.0*e*pi) == 0
assert cot(3.0*e*pi) is zoo
assert cos(4.5*e*pi) == cos(0.5*pi*e)
assert sin(4.5*e*pi) == sin(0.5*pi*e)
assert tan(4.5*e*pi) == tan(0.5*pi*e)
assert cot(4.5*e*pi) == cot(0.5*pi*e)
assert cos(4*o*pi) == 1
assert sin(4*o*pi) == 0
assert tan(4*o*pi) == 0
assert cot(4*o*pi) is zoo
assert cos(3*o*pi) == -1
assert sin(3*o*pi) == 0
assert tan(3*o*pi) == 0
assert cot(3*o*pi) is zoo
assert cos(4.0*o*pi) == 1
assert sin(4.0*o*pi) == 0
assert tan(4.0*o*pi) == 0
assert cot(4.0*o*pi) is zoo
assert cos(3.0*o*pi) == -1
assert sin(3.0*o*pi) == 0
assert tan(3.0*o*pi) == 0
assert cot(3.0*o*pi) is zoo
assert cos(4.5*o*pi) == cos(0.5*pi*o)
assert sin(4.5*o*pi) == sin(0.5*pi*o)
assert tan(4.5*o*pi) == tan(0.5*pi*o)
assert cot(4.5*o*pi) == cot(0.5*pi*o)
# x could be imaginary
assert cos(4*x*pi) == cos(4*pi*x)
assert sin(4*x*pi) == sin(4*pi*x)
assert tan(4*x*pi) == tan(4*pi*x)
assert cot(4*x*pi) == cot(4*pi*x)
assert cos(3*x*pi) == cos(3*pi*x)
assert sin(3*x*pi) == sin(3*pi*x)
assert tan(3*x*pi) == tan(3*pi*x)
assert cot(3*x*pi) == cot(3*pi*x)
assert cos(4.0*x*pi) == cos(4.0*pi*x)
assert sin(4.0*x*pi) == sin(4.0*pi*x)
assert tan(4.0*x*pi) == tan(4.0*pi*x)
assert cot(4.0*x*pi) == cot(4.0*pi*x)
assert cos(3.0*x*pi) == cos(3.0*pi*x)
assert sin(3.0*x*pi) == sin(3.0*pi*x)
assert tan(3.0*x*pi) == tan(3.0*pi*x)
assert cot(3.0*x*pi) == cot(3.0*pi*x)
assert cos(4.5*x*pi) == cos(4.5*pi*x)
assert sin(4.5*x*pi) == sin(4.5*pi*x)
assert tan(4.5*x*pi) == tan(4.5*pi*x)
assert cot(4.5*x*pi) == cot(4.5*pi*x)
def test_inverses():
raises(AttributeError, lambda: sin(x).inverse())
raises(AttributeError, lambda: cos(x).inverse())
assert tan(x).inverse() == atan
assert cot(x).inverse() == acot
raises(AttributeError, lambda: csc(x).inverse())
raises(AttributeError, lambda: sec(x).inverse())
assert asin(x).inverse() == sin
assert acos(x).inverse() == cos
assert atan(x).inverse() == tan
assert acot(x).inverse() == cot
def test_real_imag():
a, b = symbols('a b', real=True)
z = a + b*I
for deep in [True, False]:
assert sin(
z).as_real_imag(deep=deep) == (sin(a)*cosh(b), cos(a)*sinh(b))
assert cos(
z).as_real_imag(deep=deep) == (cos(a)*cosh(b), -sin(a)*sinh(b))
assert tan(z).as_real_imag(deep=deep) == (sin(2*a)/(cos(2*a) +
cosh(2*b)), sinh(2*b)/(cos(2*a) + cosh(2*b)))
assert cot(z).as_real_imag(deep=deep) == (-sin(2*a)/(cos(2*a) -
cosh(2*b)), sinh(2*b)/(cos(2*a) - cosh(2*b)))
assert sin(a).as_real_imag(deep=deep) == (sin(a), 0)
assert cos(a).as_real_imag(deep=deep) == (cos(a), 0)
assert tan(a).as_real_imag(deep=deep) == (tan(a), 0)
assert cot(a).as_real_imag(deep=deep) == (cot(a), 0)
@XFAIL
def test_sin_cos_with_infinity():
# Test for issue 5196
# https://github.com/sympy/sympy/issues/5196
assert sin(oo) is S.NaN
assert cos(oo) is S.NaN
@slow
def test_sincos_rewrite_sqrt():
# equivalent to testing rewrite(pow)
for p in [1, 3, 5, 17]:
for t in [1, 8]:
n = t*p
# The vertices `exp(i*pi/n)` of a regular `n`-gon can
# be expressed by means of nested square roots if and
# only if `n` is a product of Fermat primes, `p`, and
# powers of 2, `t'. The code aims to check all vertices
# not belonging to an `m`-gon for `m < n`(`gcd(i, n) == 1`).
# For large `n` this makes the test too slow, therefore
# the vertices are limited to those of index `i < 10`.
for i in range(1, min((n + 1)//2 + 1, 10)):
if 1 == gcd(i, n):
x = i*pi/n
s1 = sin(x).rewrite(sqrt)
c1 = cos(x).rewrite(sqrt)
assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
assert 1e-3 > abs(sin(x.evalf(5)) - s1.evalf(2)), "fails for %d*pi/%d" % (i, n)
assert 1e-3 > abs(cos(x.evalf(5)) - c1.evalf(2)), "fails for %d*pi/%d" % (i, n)
assert cos(pi/14).rewrite(sqrt) == sqrt(cos(pi/7)/2 + S.Half)
assert cos(pi/257).rewrite(sqrt).evalf(64) == cos(pi/257).evalf(64)
assert cos(pi*Rational(-15, 2)/11, evaluate=False).rewrite(
sqrt) == -sqrt(-cos(pi*Rational(4, 11))/2 + S.Half)
assert cos(Mul(2, pi, S.Half, evaluate=False), evaluate=False).rewrite(
sqrt) == -1
e = cos(pi/3/17) # don't use pi/15 since that is caught at instantiation
a = (
-3*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17) + 17)/64 -
3*sqrt(34)*sqrt(sqrt(17) + 17)/128 - sqrt(sqrt(17) +
17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17)
+ sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 - sqrt(-sqrt(17)
+ 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 - Rational(1, 32) +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 +
3*sqrt(2)*sqrt(sqrt(17) + 17)/128 + sqrt(34)*sqrt(-sqrt(17) + 17)/128
+ 13*sqrt(2)*sqrt(-sqrt(17) + 17)/128 + sqrt(17)*sqrt(-sqrt(17) +
17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17)
+ sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 + 5*sqrt(17)/32
+ sqrt(3)*sqrt(-sqrt(2)*sqrt(sqrt(17) + 17)*sqrt(sqrt(17)/32 +
sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/8 -
5*sqrt(2)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 -
3*sqrt(2)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 +
sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/32
+ sqrt(34)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 +
sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/2 +
S.Half + sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) +
17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) -
sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) +
6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) -
sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) +
6*sqrt(17) + 34)/32 + sqrt(34)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 +
sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
Rational(15, 32))/32)/2)
assert e.rewrite(sqrt) == a
assert e.n() == a.n()
# coverage of fermatCoords: multiplicity > 1; the following could be
# different but that portion of the code should be tested in some way
assert cos(pi/9/17).rewrite(sqrt) == \
sin(pi/9)*sin(pi*Rational(2, 17)) + cos(pi/9)*cos(pi*Rational(2, 17))
@slow
def test_tancot_rewrite_sqrt():
# equivalent to testing rewrite(pow)
for p in [1, 3, 5, 17]:
for t in [1, 8]:
n = t*p
for i in range(1, min((n + 1)//2 + 1, 10)):
if 1 == gcd(i, n):
x = i*pi/n
if 2*i != n and 3*i != 2*n:
t1 = tan(x).rewrite(sqrt)
assert not t1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
assert 1e-3 > abs( tan(x.evalf(7)) - t1.evalf(4) ), "fails for %d*pi/%d" % (i, n)
if i != 0 and i != n:
c1 = cot(x).rewrite(sqrt)
assert not c1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
assert 1e-3 > abs( cot(x.evalf(7)) - c1.evalf(4) ), "fails for %d*pi/%d" % (i, n)
def test_sec():
x = symbols('x', real=True)
z = symbols('z')
assert sec.nargs == FiniteSet(1)
assert sec(zoo) is nan
assert sec(0) == 1
assert sec(pi) == -1
assert sec(pi/2) is zoo
assert sec(-pi/2) is zoo
assert sec(pi/6) == 2*sqrt(3)/3
assert sec(pi/3) == 2
assert sec(pi*Rational(5, 2)) is zoo
assert sec(pi*Rational(9, 7)) == -sec(pi*Rational(2, 7))
assert sec(pi*Rational(3, 4)) == -sqrt(2) # issue 8421
assert sec(I) == 1/cosh(1)
assert sec(x*I) == 1/cosh(x)
assert sec(-x) == sec(x)
assert sec(asec(x)) == x
assert sec(z).conjugate() == sec(conjugate(z))
assert (sec(z).as_real_imag() ==
(cos(re(z))*cosh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
cos(re(z))**2*cosh(im(z))**2),
sin(re(z))*sinh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
cos(re(z))**2*cosh(im(z))**2)))
assert sec(x).expand(trig=True) == 1/cos(x)
assert sec(2*x).expand(trig=True) == 1/(2*cos(x)**2 - 1)
assert sec(x).is_extended_real == True
assert sec(z).is_real == None
assert sec(a).is_algebraic is None
assert sec(na).is_algebraic is False
assert sec(x).as_leading_term() == sec(x)
assert sec(0).is_finite == True
assert sec(x).is_finite == None
assert sec(pi/2).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).is_finite == False
assert csc(x).is_finite == None
assert csc(pi/2).is_finite == True
assert series(csc(x), x, x0=pi/2, n=6) == \
1 + (x - pi/2)**2/2 + 5*(x - pi/2)**4/24 + O((x - pi/2)**6, (x, pi/2))
assert series(csc(x), x, x0=0, n=6) == \
1/x + x/6 + 7*x**3/360 + 31*x**5/15120 + O(x**6)
assert csc(x).diff(x) == -cot(x)*csc(x)
assert csc(x).taylor_term(2, x) == 0
assert csc(x).taylor_term(3, x) == 7*x**3/360
assert csc(x).taylor_term(5, x) == 31*x**5/15120
raises(ArgumentIndexError, lambda: csc(x).fdiff(2))
def test_asec():
z = Symbol('z', zero=True)
assert asec(z) is zoo
assert asec(nan) is nan
assert asec(1) == 0
assert asec(-1) == pi
assert asec(oo) == pi/2
assert asec(-oo) == pi/2
assert asec(zoo) == pi/2
assert asec(sec(pi*Rational(13, 4))) == pi*Rational(3, 4)
assert asec(1 + sqrt(5)) == pi*Rational(2, 5)
assert asec(2/sqrt(3)) == pi/6
assert asec(sqrt(4 - 2*sqrt(2))) == pi/8
assert asec(-sqrt(4 + 2*sqrt(2))) == pi*Rational(5, 8)
assert asec(sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(3, 10)
assert asec(-sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(7, 10)
assert asec(sqrt(2) - sqrt(6)) == pi*Rational(11, 12)
assert asec(x).diff(x) == 1/(x**2*sqrt(1 - 1/x**2))
assert asec(x).as_leading_term(x) == I*log(x)
assert asec(x).rewrite(log) == I*log(sqrt(1 - 1/x**2) + I/x) + pi/2
assert asec(x).rewrite(asin) == -asin(1/x) + pi/2
assert asec(x).rewrite(acos) == acos(1/x)
assert asec(x).rewrite(atan) == (2*atan(x + sqrt(x**2 - 1)) - pi/2)*sqrt(x**2)/x
assert asec(x).rewrite(acot) == (2*acot(x - sqrt(x**2 - 1)) - pi/2)*sqrt(x**2)/x
assert asec(x).rewrite(acsc) == -acsc(x) + pi/2
raises(ArgumentIndexError, lambda: asec(x).fdiff(2))
def test_asec_is_real():
assert asec(S.Half).is_real is False
n = Symbol('n', positive=True, integer=True)
assert asec(n).is_extended_real is True
assert asec(x).is_real is None
assert asec(r).is_real is None
t = Symbol('t', real=False, finite=True)
assert asec(t).is_real is False
def test_acsc():
assert acsc(nan) is nan
assert acsc(1) == pi/2
assert acsc(-1) == -pi/2
assert acsc(oo) == 0
assert acsc(-oo) == 0
assert acsc(zoo) == 0
assert acsc(0) is zoo
assert acsc(csc(3)) == -3 + pi
assert acsc(csc(4)) == -4 + pi
assert acsc(csc(6)) == 6 - 2*pi
assert unchanged(acsc, csc(x))
assert unchanged(acsc, sec(x))
assert acsc(2/sqrt(3)) == pi/3
assert acsc(csc(pi*Rational(13, 4))) == -pi/4
assert acsc(sqrt(2 + 2*sqrt(5)/5)) == pi/5
assert acsc(-sqrt(2 + 2*sqrt(5)/5)) == -pi/5
assert acsc(-2) == -pi/6
assert acsc(-sqrt(4 + 2*sqrt(2))) == -pi/8
assert acsc(sqrt(4 - 2*sqrt(2))) == pi*Rational(3, 8)
assert acsc(1 + sqrt(5)) == pi/10
assert acsc(sqrt(2) - sqrt(6)) == pi*Rational(-5, 12)
assert acsc(x).diff(x) == -1/(x**2*sqrt(1 - 1/x**2))
assert acsc(x).as_leading_term(x) == I*log(x)
assert acsc(x).rewrite(log) == -I*log(sqrt(1 - 1/x**2) + I/x)
assert acsc(x).rewrite(asin) == asin(1/x)
assert acsc(x).rewrite(acos) == -acos(1/x) + pi/2
assert acsc(x).rewrite(atan) == (-atan(sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x
assert acsc(x).rewrite(acot) == (-acot(1/sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x
assert acsc(x).rewrite(asec) == -asec(x) + pi/2
raises(ArgumentIndexError, lambda: acsc(x).fdiff(2))
def test_csc_rewrite():
assert csc(x).rewrite(pow) == csc(x)
assert csc(x).rewrite(sqrt) == csc(x)
assert csc(x).rewrite(exp) == 2*I/(exp(I*x) - exp(-I*x))
assert csc(x).rewrite(sin) == 1/sin(x)
assert csc(x).rewrite(tan) == (tan(x/2)**2 + 1)/(2*tan(x/2))
assert csc(x).rewrite(cot) == (cot(x/2)**2 + 1)/(2*cot(x/2))
assert csc(x).rewrite(cos) == 1/cos(x - pi/2, evaluate=False)
assert csc(x).rewrite(sec) == sec(-x + pi/2, evaluate=False)
# issue 17349
assert csc(1 - exp(-besselj(I, I))).rewrite(cos) == \
-1/cos(-pi/2 - 1 + cos(I*besselj(I, I)) +
I*cos(-pi/2 + I*besselj(I, I), evaluate=False), evaluate=False)
def test_inverses_nseries():
assert asin(x + 2)._eval_nseries(x, 4, None, I) == -asin(2) + pi + sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 + \
sqrt(3)*I*x**3/18 + O(x**4)
assert asin(x + 2)._eval_nseries(x, 4, None, -I) == asin(2) - sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
assert asin(x - 2)._eval_nseries(x, 4, None, I) == -asin(2) - sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
assert asin(x - 2)._eval_nseries(x, 4, None, -I) == asin(2) - pi + sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 + \
sqrt(3)*I*x**3/18 + O(x**4)
assert asin(I*x + I*x**3 + 2)._eval_nseries(x, 3, None, 1) == -asin(2) + pi - sqrt(3)*x/3 + sqrt(3)*I*x**2/9 + O(x**3)
assert asin(I*x + I*x**3 + 2)._eval_nseries(x, 3, None, -1) == asin(2) + sqrt(3)*x/3 - sqrt(3)*I*x**2/9 + O(x**3)
assert asin(I*x + I*x**3 - 2)._eval_nseries(x, 3, None, 1) == -asin(2) + sqrt(3)*x/3 + sqrt(3)*I*x**2/9 + O(x**3)
assert asin(I*x + I*x**3 - 2)._eval_nseries(x, 3, None, -1) == asin(2) - pi - sqrt(3)*x/3 - sqrt(3)*I*x**2/9 + O(x**3)
assert asin(I*x**2 + I*x**3 + 2)._eval_nseries(x, 3, None, 1) == -asin(2) + pi - sqrt(3)*x**2/3 + O(x**3)
assert asin(I*x**2 + I*x**3 + 2)._eval_nseries(x, 3, None, -1) == -asin(2) + pi - sqrt(3)*x**2/3 + O(x**3)
assert asin(I*x**2 + I*x**3 - 2)._eval_nseries(x, 3, None, 1) == -asin(2) + sqrt(3)*x**2/3 + O(x**3)
assert asin(I*x**2 + I*x**3 - 2)._eval_nseries(x, 3, None, -1) == -asin(2) + sqrt(3)*x**2/3 + O(x**3)
assert asin(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) - \
sqrt(2)*(-x)**(S(3)/2)/12 - 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
assert asin(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) + \
sqrt(2)*x**(S(3)/2)/12 + 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
assert asin(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) + \
sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
assert asin(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - \
sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
assert acos(x + 2)._eval_nseries(x, 4, None, I) == -acos(2) - sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
assert acos(x + 2)._eval_nseries(x, 4, None, -I) == acos(2) + sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
assert acos(x - 2)._eval_nseries(x, 4, None, I) == acos(-2) + sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
assert acos(x - 2)._eval_nseries(x, 4, None, -I) == -acos(-2) + 2*pi - sqrt(3)*I*x/3 - \
sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
# assert acos(I*x + I*x**3 + 2)._eval_nseries(x, 3, None, 1) == -acos(2) + sqrt(3)*x/3 - sqrt(3)*I*x**2/9 + O(x**3)
# assert acos(I*x + I*x**3 + 2)._eval_nseries(x, 3, None, -1) == acos(2) - sqrt(3)*x/3 + sqrt(3)*I*x**2/9 + O(x**3)
# assert acos(I*x + I*x**3 - 2)._eval_nseries(x, 3, None, 1) == acos(-2) - sqrt(3)*x/3 - sqrt(3)*I*x**2/9 + O(x**3)
# assert acos(I*x + I*x**3 - 2)._eval_nseries(x, 3, None, -1) == -acos(-2) + 2*pi + sqrt(3)*x/3 + sqrt(3)*I*x**2/9 + O(x**3)
# assert acos(I*x**2 + I*x**3 + 2)._eval_nseries(x, 3, None, 1) == -acos(2) + sqrt(3)*x**2/3 + O(x**3)
# assert acos(I*x**2 + I*x**3 + 2)._eval_nseries(x, 3, None, -1) == -acos(2) + sqrt(3)*x**2/3 + O(x**3)
# assert acos(I*x**2 + I*x**3 - 2)._eval_nseries(x, 3, None, 1) == acos(-2) - sqrt(3)*x**2/3 + O(x**3)
# assert acos(I*x**2 + I*x**3 - 2)._eval_nseries(x, 3, None, -1) == acos(-2) - sqrt(3)*x**2/3 + O(x**3)
# assert acos(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) + sqrt(2)*(-x)**(S(3)/2)/12 + 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
# assert acos(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) - sqrt(2)*x**(S(3)/2)/12 - 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
# assert acos(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) - sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
# assert acos(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
assert atan(x + 2*I)._eval_nseries(x, 4, None, 1) == I*atanh(2) - x/3 - 2*I*x**2/9 + 13*x**3/81 + O(x**4)
assert atan(x + 2*I)._eval_nseries(x, 4, None, -1) == I*atanh(2) - pi - x/3 - 2*I*x**2/9 + 13*x**3/81 + O(x**4)
assert atan(x - 2*I)._eval_nseries(x, 4, None, 1) == -I*atanh(2) + pi - x/3 + 2*I*x**2/9 + 13*x**3/81 + O(x**4)
assert atan(x - 2*I)._eval_nseries(x, 4, None, -1) == -I*atanh(2) - x/3 + 2*I*x**2/9 + 13*x**3/81 + O(x**4)
# assert atan(x**2 + 2*I)._eval_nseries(x, 3, None, 1) == I*atanh(2) - x**2/3 + O(x**3)
# assert atan(x**2 + 2*I)._eval_nseries(x, 3, None, -1) == I*atanh(2) - x**2/3 + O(x**3)
# assert atan(x**2 - 2*I)._eval_nseries(x, 3, None, 1) == -I*atanh(2) + pi - x**2/3 + O(x**3)
# assert atan(x**2 - 2*I)._eval_nseries(x, 3, None, -1) == -I*atanh(2) + pi - x**2/3 + O(x**3)
assert atan(1/x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2)
assert atan(1/x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2)
assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, 1) == -I*acoth(S(1)/2) + pi - 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4)
assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, -1) == -I*acoth(S(1)/2) - 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4)
assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, 1) == I*acoth(S(1)/2) - 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4)
assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, -1) == I*acoth(S(1)/2) - pi - 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4)
# assert acot(x**2 + S(1)/2*I)._eval_nseries(x, 3, None, 1) == -I*acoth(S(1)/2) + pi - 4*x**2/3 + O(x**3)
# assert acot(x**2 + S(1)/2*I)._eval_nseries(x, 3, None, -1) == -I*acoth(S(1)/2) + pi - 4*x**2/3 + O(x**3)
# assert acot(x**2 - S(1)/2*I)._eval_nseries(x, 3, None, 1) == I*acoth(S(1)/2) - 4*x**2/3 + O(x**3)
# assert acot(x**2 - S(1)/2*I)._eval_nseries(x, 3, None, -1) == I*acoth(S(1)/2) - 4*x**2/3 + O(x**3)
# assert acot(x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2)
# assert acot(x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2)
assert asec(x + S(1)/2)._eval_nseries(x, 4, None, I) == asec(S(1)/2) - 4*sqrt(3)*I*x/3 + \
8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
assert asec(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -asec(S(1)/2) + 4*sqrt(3)*I*x/3 - \
8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
assert asec(x - S(1)/2)._eval_nseries(x, 4, None, I) == -asec(-S(1)/2) + 2*pi + 4*sqrt(3)*I*x/3 + \
8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
assert asec(x - S(1)/2)._eval_nseries(x, 4, None, -I) == asec(-S(1)/2) - 4*sqrt(3)*I*x/3 - \
8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
# assert asec(I*x + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, 1) == asec(S(1)/2) + 4*sqrt(3)*x/3 - 8*sqrt(3)*I*x**2/9 + O(x**3)
# assert asec(I*x + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, -1) == -asec(S(1)/2) - 4*sqrt(3)*x/3 + 8*sqrt(3)*I*x**2/9 + O(x**3)
# assert asec(I*x + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, 1) == -asec(-S(1)/2) + 2*pi - 4*sqrt(3)*x/3 - 8*sqrt(3)*I*x**2/9 + O(x**3)
# assert asec(I*x + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, -1) == asec(-S(1)/2) + 4*sqrt(3)*x/3 + 8*sqrt(3)*I*x**2/9 + O(x**3)
# assert asec(I*x**2 + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, 1) == asec(S(1)/2) + 4*sqrt(3)*x**2/3 + O(x**3)
# assert asec(I*x**2 + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, -1) == asec(S(1)/2) + 4*sqrt(3)*x**2/3 + O(x**3)
# assert asec(I*x**2 + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, 1) == -asec(-S(1)/2) + 2*pi - 4*sqrt(3)*x**2/3 + O(x**3)
# assert asec(I*x**2 + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, -1) == -asec(-S(1)/2) + 2*pi - 4*sqrt(3)*x**2/3 + O(x**3)
# assert asec(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - 5*sqrt(2)*x**(S(3)/2)/12 + 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
# assert asec(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + 5*sqrt(2)*(-x)**(S(3)/2)/12 - 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
# assert asec(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3)
# assert asec(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) + sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3)
assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) + 4*sqrt(3)*I*x/3 - \
8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + pi - 4*sqrt(3)*I*x/3 + \
8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) - pi - 4*sqrt(3)*I*x/3 - \
8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + 4*sqrt(3)*I*x/3 + \
8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
# assert acsc(I*x + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, 1) == acsc(S(1)/2) - 4*sqrt(3)*x/3 + 8*sqrt(3)*I*x**2/9 + O(x**3)
# assert acsc(I*x + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, -1) == -acsc(S(1)/2) + pi + 4*sqrt(3)*x/3 - 8*sqrt(3)*I*x**2/9 + O(x**3)
# assert acsc(I*x + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, 1) == acsc(S(1)/2) - pi + 4*sqrt(3)*x/3 + 8*sqrt(3)*I*x**2/9 + O(x**3)
# assert acsc(I*x + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, -1) == -acsc(S(1)/2) - 4*sqrt(3)*x/3 - 8*sqrt(3)*I*x**2/9 + O(x**3)
# assert acsc(I*x**2 + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, 1) == acsc(S(1)/2) - 4*sqrt(3)*x**2/3 + O(x**3)
# assert acsc(I*x**2 + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, -1) == acsc(S(1)/2) - 4*sqrt(3)*x**2/3 + O(x**3)
# assert acsc(I*x**2 + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, 1) == acsc(S(1)/2) - pi + 4*sqrt(3)*x**2/3 + O(x**3)
# assert acsc(I*x**2 + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, -1) == acsc(S(1)/2) - pi + 4*sqrt(3)*x**2/3 + O(x**3)
# assert acsc(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + 5*sqrt(2)*x**(S(3)/2)/12 - 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
# assert acsc(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - 5*sqrt(2)*(-x)**(S(3)/2)/12 + 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
# assert acsc(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3)
# assert acsc(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) - sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3)
def test_issue_8653():
n = Symbol('n', integer=True)
assert sin(n).is_irrational is None
assert cos(n).is_irrational is None
assert tan(n).is_irrational is None
def test_issue_9157():
n = Symbol('n', integer=True, positive=True)
assert atan(n - 1).is_nonnegative is True
def test_trig_period():
x, y = symbols('x, y')
assert sin(x).period() == 2*pi
assert cos(x).period() == 2*pi
assert tan(x).period() == pi
assert cot(x).period() == pi
assert sec(x).period() == 2*pi
assert csc(x).period() == 2*pi
assert sin(2*x).period() == pi
assert cot(4*x - 6).period() == pi/4
assert cos((-3)*x).period() == pi*Rational(2, 3)
assert cos(x*y).period(x) == 2*pi/abs(y)
assert sin(3*x*y + 2*pi).period(y) == 2*pi/abs(3*x)
assert tan(3*x).period(y) is S.Zero
raises(NotImplementedError, lambda: sin(x**2).period(x))
def test_issue_7171():
assert sin(x).rewrite(sqrt) == sin(x)
assert sin(x).rewrite(pow) == sin(x)
def test_issue_11864():
w, k = symbols('w, k', real=True)
F = Piecewise((1, Eq(2*pi*k, 0)), (sin(pi*k)/(pi*k), True))
soln = Piecewise((1, Eq(2*pi*k, 0)), (sinc(pi*k), True))
assert F.rewrite(sinc) == soln
def test_real_assumptions():
z = Symbol('z', real=False, finite=True)
assert sin(z).is_real is None
assert cos(z).is_real is None
assert tan(z).is_real is False
assert sec(z).is_real is None
assert csc(z).is_real is None
assert cot(z).is_real is False
assert asin(p).is_real is None
assert asin(n).is_real is None
assert asec(p).is_real is None
assert asec(n).is_real is None
assert acos(p).is_real is None
assert acos(n).is_real is None
assert acsc(p).is_real is None
assert acsc(n).is_real is None
assert atan(p).is_positive is True
assert atan(n).is_negative is True
assert acot(p).is_positive is True
assert acot(n).is_negative is True
def test_issue_14320():
assert asin(sin(2)) == -2 + pi and (-pi/2 <= -2 + pi <= pi/2) and sin(2) == sin(-2 + pi)
assert asin(cos(2)) == -2 + pi/2 and (-pi/2 <= -2 + pi/2 <= pi/2) and cos(2) == sin(-2 + pi/2)
assert acos(sin(2)) == -pi/2 + 2 and (0 <= -pi/2 + 2 <= pi) and sin(2) == cos(-pi/2 + 2)
assert acos(cos(20)) == -6*pi + 20 and (0 <= -6*pi + 20 <= pi) and cos(20) == cos(-6*pi + 20)
assert acos(cos(30)) == -30 + 10*pi and (0 <= -30 + 10*pi <= pi) and cos(30) == cos(-30 + 10*pi)
assert atan(tan(17)) == -5*pi + 17 and (-pi/2 < -5*pi + 17 < pi/2) and tan(17) == tan(-5*pi + 17)
assert atan(tan(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 < pi/2) and tan(15) == tan(-5*pi + 15)
assert atan(cot(12)) == -12 + pi*Rational(7, 2) and (-pi/2 < -12 + pi*Rational(7, 2) < pi/2) and cot(12) == tan(-12 + pi*Rational(7, 2))
assert acot(cot(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 <= pi/2) and cot(15) == cot(-5*pi + 15)
assert acot(tan(19)) == -19 + pi*Rational(13, 2) and (-pi/2 < -19 + pi*Rational(13, 2) <= pi/2) and tan(19) == cot(-19 + pi*Rational(13, 2))
assert asec(sec(11)) == -11 + 4*pi and (0 <= -11 + 4*pi <= pi) and cos(11) == cos(-11 + 4*pi)
assert asec(csc(13)) == -13 + pi*Rational(9, 2) and (0 <= -13 + pi*Rational(9, 2) <= pi) and sin(13) == cos(-13 + pi*Rational(9, 2))
assert acsc(csc(14)) == -4*pi + 14 and (-pi/2 <= -4*pi + 14 <= pi/2) and sin(14) == sin(-4*pi + 14)
assert acsc(sec(10)) == pi*Rational(-7, 2) + 10 and (-pi/2 <= pi*Rational(-7, 2) + 10 <= pi/2) and cos(10) == sin(pi*Rational(-7, 2) + 10)
def test_issue_14543():
assert sec(2*pi + 11) == sec(11)
assert sec(2*pi - 11) == sec(11)
assert sec(pi + 11) == -sec(11)
assert sec(pi - 11) == -sec(11)
assert csc(2*pi + 17) == csc(17)
assert csc(2*pi - 17) == -csc(17)
assert csc(pi + 17) == -csc(17)
assert csc(pi - 17) == csc(17)
x = Symbol('x')
assert csc(pi/2 + x) == sec(x)
assert csc(pi/2 - x) == sec(x)
assert csc(pi*Rational(3, 2) + x) == -sec(x)
assert csc(pi*Rational(3, 2) - x) == -sec(x)
assert sec(pi/2 - x) == csc(x)
assert sec(pi/2 + x) == -csc(x)
assert sec(pi*Rational(3, 2) + x) == csc(x)
assert sec(pi*Rational(3, 2) - x) == -csc(x)
def test_as_real_imag():
# This is for https://github.com/sympy/sympy/issues/17142
# If it start failing again in irrelevant builds or in the master
# please open up the issue again.
expr = atan(I/(I + I*tan(1)))
assert expr.as_real_imag() == (expr, 0)
def test_issue_18746():
e3 = cos(S.Pi*(x/4 + 1/4))
assert e3.period() == 8
|
254128b0b27b70ca228cde2fc4951460ecb850979fa2b3fc5b6f6da8d432076b | from sympy import (
Abs, acos, adjoint, arg, atan, atan2, conjugate, cos, DiracDelta,
E, exp, expand, Expr, Function, Heaviside, I, im, log, nan, oo,
pi, Rational, re, S, sign, sin, sqrt, Symbol, symbols, transpose,
zoo, exp_polar, Piecewise, Interval, comp, Integral, Matrix,
ImmutableMatrix, SparseMatrix, ImmutableSparseMatrix, MatrixSymbol,
FunctionMatrix, Lambda, Derivative, Eq)
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.testing.pytest import XFAIL, raises, _both_exp_pow
def N_equals(a, b):
"""Check whether two complex numbers are numerically close"""
return comp(a.n(), b.n(), 1.e-6)
def test_re():
x, y = symbols('x,y')
a, b = symbols('a,b', real=True)
r = Symbol('r', real=True)
i = Symbol('i', imaginary=True)
assert re(nan) is nan
assert re(oo) is oo
assert re(-oo) is -oo
assert re(0) == 0
assert re(1) == 1
assert re(-1) == -1
assert re(E) == E
assert re(-E) == -E
assert unchanged(re, x)
assert re(x*I) == -im(x)
assert re(r*I) == 0
assert re(r) == r
assert re(i*I) == I * i
assert re(i) == 0
assert re(x + y) == re(x) + re(y)
assert re(x + r) == re(x) + r
assert re(re(x)) == re(x)
assert re(2 + I) == 2
assert re(x + I) == re(x)
assert re(x + y*I) == re(x) - im(y)
assert re(x + r*I) == re(x)
assert re(log(2*I)) == log(2)
assert re((2 + I)**2).expand(complex=True) == 3
assert re(conjugate(x)) == re(x)
assert conjugate(re(x)) == re(x)
assert re(x).as_real_imag() == (re(x), 0)
assert re(i*r*x).diff(r) == re(i*x)
assert re(i*r*x).diff(i) == I*r*im(x)
assert re(
sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)
assert re(a * (2 + b*I)) == 2*a
assert re((1 + sqrt(a + b*I))/2) == \
(a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)/2 + S.Half
assert re(x).rewrite(im) == x - S.ImaginaryUnit*im(x)
assert (x + re(y)).rewrite(re, im) == x + y - S.ImaginaryUnit*im(y)
a = Symbol('a', algebraic=True)
t = Symbol('t', transcendental=True)
x = Symbol('x')
assert re(a).is_algebraic
assert re(x).is_algebraic is None
assert re(t).is_algebraic is False
assert re(S.ComplexInfinity) is S.NaN
n, m, l = symbols('n m l')
A = MatrixSymbol('A',n,m)
assert re(A) == (S.Half) * (A + conjugate(A))
A = Matrix([[1 + 4*I,2],[0, -3*I]])
assert re(A) == Matrix([[1, 2],[0, 0]])
A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]])
assert re(A) == ImmutableMatrix([[1, 3],[0, 0]])
X = SparseMatrix([[2*j + i*I for i in range(5)] for j in range(5)])
assert re(X) - Matrix([[0, 0, 0, 0, 0],
[2, 2, 2, 2, 2],
[4, 4, 4, 4, 4],
[6, 6, 6, 6, 6],
[8, 8, 8, 8, 8]]) == Matrix.zeros(5)
assert im(X) - Matrix([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]) == Matrix.zeros(5)
X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I))
assert re(X) == Matrix([[0, 0, 0], [1, 1, 1], [2, 2, 2]])
def test_im():
x, y = symbols('x,y')
a, b = symbols('a,b', real=True)
r = Symbol('r', real=True)
i = Symbol('i', imaginary=True)
assert im(nan) is nan
assert im(oo*I) is oo
assert im(-oo*I) is -oo
assert im(0) == 0
assert im(1) == 0
assert im(-1) == 0
assert im(E*I) == E
assert im(-E*I) == -E
assert unchanged(im, x)
assert im(x*I) == re(x)
assert im(r*I) == r
assert im(r) == 0
assert im(i*I) == 0
assert im(i) == -I * i
assert im(x + y) == im(x) + im(y)
assert im(x + r) == im(x)
assert im(x + r*I) == im(x) + r
assert im(im(x)*I) == im(x)
assert im(2 + I) == 1
assert im(x + I) == im(x) + 1
assert im(x + y*I) == im(x) + re(y)
assert im(x + r*I) == im(x) + r
assert im(log(2*I)) == pi/2
assert im((2 + I)**2).expand(complex=True) == 4
assert im(conjugate(x)) == -im(x)
assert conjugate(im(x)) == im(x)
assert im(x).as_real_imag() == (im(x), 0)
assert im(i*r*x).diff(r) == im(i*x)
assert im(i*r*x).diff(i) == -I * re(r*x)
assert im(
sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)
assert im(a * (2 + b*I)) == a*b
assert im((1 + sqrt(a + b*I))/2) == \
(a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2
assert im(x).rewrite(re) == -S.ImaginaryUnit * (x - re(x))
assert (x + im(y)).rewrite(im, re) == x - S.ImaginaryUnit * (y - re(y))
a = Symbol('a', algebraic=True)
t = Symbol('t', transcendental=True)
x = Symbol('x')
assert re(a).is_algebraic
assert re(x).is_algebraic is None
assert re(t).is_algebraic is False
assert im(S.ComplexInfinity) is S.NaN
n, m, l = symbols('n m l')
A = MatrixSymbol('A',n,m)
assert im(A) == (S.One/(2*I)) * (A - conjugate(A))
A = Matrix([[1 + 4*I, 2],[0, -3*I]])
assert im(A) == Matrix([[4, 0],[0, -3]])
A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]])
assert im(A) == ImmutableMatrix([[3, -2],[0, 2]])
X = ImmutableSparseMatrix(
[[i*I + i for i in range(5)] for i in range(5)])
Y = SparseMatrix([[i for i in range(5)] for i in range(5)])
assert im(X).as_immutable() == Y
X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I))
assert im(X) == Matrix([[0, 1, 2], [0, 1, 2], [0, 1, 2]])
def test_sign():
assert sign(1.2) == 1
assert sign(-1.2) == -1
assert sign(3*I) == I
assert sign(-3*I) == -I
assert sign(0) == 0
assert sign(nan) is nan
assert sign(2 + 2*I).doit() == sqrt(2)*(2 + 2*I)/4
assert sign(2 + 3*I).simplify() == sign(2 + 3*I)
assert sign(2 + 2*I).simplify() == sign(1 + I)
assert sign(im(sqrt(1 - sqrt(3)))) == 1
assert sign(sqrt(1 - sqrt(3))) == I
x = Symbol('x')
assert sign(x).is_finite is True
assert sign(x).is_complex is True
assert sign(x).is_imaginary is None
assert sign(x).is_integer is None
assert sign(x).is_real is None
assert sign(x).is_zero is None
assert sign(x).doit() == sign(x)
assert sign(1.2*x) == sign(x)
assert sign(2*x) == sign(x)
assert sign(I*x) == I*sign(x)
assert sign(-2*I*x) == -I*sign(x)
assert sign(conjugate(x)) == conjugate(sign(x))
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
m = Symbol('m', negative=True)
assert sign(2*p*x) == sign(x)
assert sign(n*x) == -sign(x)
assert sign(n*m*x) == sign(x)
x = Symbol('x', imaginary=True)
assert sign(x).is_imaginary is True
assert sign(x).is_integer is False
assert sign(x).is_real is False
assert sign(x).is_zero is False
assert sign(x).diff(x) == 2*DiracDelta(-I*x)
assert sign(x).doit() == x / Abs(x)
assert conjugate(sign(x)) == -sign(x)
x = Symbol('x', real=True)
assert sign(x).is_imaginary is False
assert sign(x).is_integer is True
assert sign(x).is_real is True
assert sign(x).is_zero is None
assert sign(x).diff(x) == 2*DiracDelta(x)
assert sign(x).doit() == sign(x)
assert conjugate(sign(x)) == sign(x)
x = Symbol('x', nonzero=True)
assert sign(x).is_imaginary is False
assert sign(x).is_integer is True
assert sign(x).is_real is True
assert sign(x).is_zero is False
assert sign(x).doit() == x / Abs(x)
assert sign(Abs(x)) == 1
assert Abs(sign(x)) == 1
x = Symbol('x', positive=True)
assert sign(x).is_imaginary is False
assert sign(x).is_integer is True
assert sign(x).is_real is True
assert sign(x).is_zero is False
assert sign(x).doit() == x / Abs(x)
assert sign(Abs(x)) == 1
assert Abs(sign(x)) == 1
x = 0
assert sign(x).is_imaginary is False
assert sign(x).is_integer is True
assert sign(x).is_real is True
assert sign(x).is_zero is True
assert sign(x).doit() == 0
assert sign(Abs(x)) == 0
assert Abs(sign(x)) == 0
nz = Symbol('nz', nonzero=True, integer=True)
assert sign(nz).is_imaginary is False
assert sign(nz).is_integer is True
assert sign(nz).is_real is True
assert sign(nz).is_zero is False
assert sign(nz)**2 == 1
assert (sign(nz)**3).args == (sign(nz), 3)
assert sign(Symbol('x', nonnegative=True)).is_nonnegative
assert sign(Symbol('x', nonnegative=True)).is_nonpositive is None
assert sign(Symbol('x', nonpositive=True)).is_nonnegative is None
assert sign(Symbol('x', nonpositive=True)).is_nonpositive
assert sign(Symbol('x', real=True)).is_nonnegative is None
assert sign(Symbol('x', real=True)).is_nonpositive is None
assert sign(Symbol('x', real=True, zero=False)).is_nonpositive is None
x, y = Symbol('x', real=True), Symbol('y')
f = Function('f')
assert sign(x).rewrite(Piecewise) == \
Piecewise((1, x > 0), (-1, x < 0), (0, True))
assert sign(y).rewrite(Piecewise) == sign(y)
assert sign(x).rewrite(Heaviside) == 2*Heaviside(x, H0=S(1)/2) - 1
assert sign(y).rewrite(Heaviside) == sign(y)
assert sign(y).rewrite(Abs) == Piecewise((0, Eq(y, 0)), (y/Abs(y), True))
assert sign(f(y)).rewrite(Abs) == Piecewise((0, Eq(f(y), 0)), (f(y)/Abs(f(y)), True))
# evaluate what can be evaluated
assert sign(exp_polar(I*pi)*pi) is S.NegativeOne
eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
# if there is a fast way to know when and when you cannot prove an
# expression like this is zero then the equality to zero is ok
assert sign(eq).func is sign or sign(eq) == 0
# but sometimes it's hard to do this so it's better not to load
# abs down with tests that will be very slow
q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
p = expand(q**3)**Rational(1, 3)
d = p - q
assert sign(d).func is sign or sign(d) == 0
def test_as_real_imag():
n = pi**1000
# the special code for working out the real
# and complex parts of a power with Integer exponent
# should not run if there is no imaginary part, hence
# this should not hang
assert n.as_real_imag() == (n, 0)
# issue 6261
x = Symbol('x')
assert sqrt(x).as_real_imag() == \
((re(x)**2 + im(x)**2)**Rational(1, 4)*cos(atan2(im(x), re(x))/2),
(re(x)**2 + im(x)**2)**Rational(1, 4)*sin(atan2(im(x), re(x))/2))
# issue 3853
a, b = symbols('a,b', real=True)
assert ((1 + sqrt(a + b*I))/2).as_real_imag() == \
(
(a**2 + b**2)**Rational(
1, 4)*cos(atan2(b, a)/2)/2 + S.Half,
(a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2)
assert sqrt(a**2).as_real_imag() == (sqrt(a**2), 0)
i = symbols('i', imaginary=True)
assert sqrt(i**2).as_real_imag() == (0, abs(i))
assert ((1 + I)/(1 - I)).as_real_imag() == (0, 1)
assert ((1 + I)**3/(1 - I)).as_real_imag() == (-2, 0)
@XFAIL
def test_sign_issue_3068():
n = pi**1000
i = int(n)
x = Symbol('x')
assert (n - i).round() == 1 # doesn't hang
assert sign(n - i) == 1
# perhaps it's not possible to get the sign right when
# only 1 digit is being requested for this situation;
# 2 digits works
assert (n - x).n(1, subs={x: i}) > 0
assert (n - x).n(2, subs={x: i}) > 0
def test_Abs():
raises(TypeError, lambda: Abs(Interval(2, 3))) # issue 8717
x, y = symbols('x,y')
assert sign(sign(x)) == sign(x)
assert sign(x*y).func is sign
assert Abs(0) == 0
assert Abs(1) == 1
assert Abs(-1) == 1
assert Abs(I) == 1
assert Abs(-I) == 1
assert Abs(nan) is nan
assert Abs(zoo) is oo
assert Abs(I * pi) == pi
assert Abs(-I * pi) == pi
assert Abs(I * x) == Abs(x)
assert Abs(-I * x) == Abs(x)
assert Abs(-2*x) == 2*Abs(x)
assert Abs(-2.0*x) == 2.0*Abs(x)
assert Abs(2*pi*x*y) == 2*pi*Abs(x*y)
assert Abs(conjugate(x)) == Abs(x)
assert conjugate(Abs(x)) == Abs(x)
assert Abs(x).expand(complex=True) == sqrt(re(x)**2 + im(x)**2)
a = Symbol('a', positive=True)
assert Abs(2*pi*x*a) == 2*pi*a*Abs(x)
assert Abs(2*pi*I*x*a) == 2*pi*a*Abs(x)
x = Symbol('x', real=True)
n = Symbol('n', integer=True)
assert Abs((-1)**n) == 1
assert x**(2*n) == Abs(x)**(2*n)
assert Abs(x).diff(x) == sign(x)
assert abs(x) == Abs(x) # Python built-in
assert Abs(x)**3 == x**2*Abs(x)
assert Abs(x)**4 == x**4
assert (
Abs(x)**(3*n)).args == (Abs(x), 3*n) # leave symbolic odd unchanged
assert (1/Abs(x)).args == (Abs(x), -1)
assert 1/Abs(x)**3 == 1/(x**2*Abs(x))
assert Abs(x)**-3 == Abs(x)/(x**4)
assert Abs(x**3) == x**2*Abs(x)
assert Abs(I**I) == exp(-pi/2)
assert Abs((4 + 5*I)**(6 + 7*I)) == 68921*exp(-7*atan(Rational(5, 4)))
y = Symbol('y', real=True)
assert Abs(I**y) == 1
y = Symbol('y')
assert Abs(I**y) == exp(-pi*im(y)/2)
x = Symbol('x', imaginary=True)
assert Abs(x).diff(x) == -sign(x)
eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
# if there is a fast way to know when you can and when you cannot prove an
# expression like this is zero then the equality to zero is ok
assert abs(eq).func is Abs or abs(eq) == 0
# but sometimes it's hard to do this so it's better not to load
# abs down with tests that will be very slow
q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
p = expand(q**3)**Rational(1, 3)
d = p - q
assert abs(d).func is Abs or abs(d) == 0
assert Abs(4*exp(pi*I/4)) == 4
assert Abs(3**(2 + I)) == 9
assert Abs((-3)**(1 - I)) == 3*exp(pi)
assert Abs(oo) is oo
assert Abs(-oo) is oo
assert Abs(oo + I) is oo
assert Abs(oo + I*oo) is oo
a = Symbol('a', algebraic=True)
t = Symbol('t', transcendental=True)
x = Symbol('x')
assert re(a).is_algebraic
assert re(x).is_algebraic is None
assert re(t).is_algebraic is False
assert Abs(x).fdiff() == sign(x)
raises(ArgumentIndexError, lambda: Abs(x).fdiff(2))
# doesn't have recursion error
arg = sqrt(acos(1 - I)*acos(1 + I))
assert abs(arg) == arg
# special handling to put Abs in denom
assert abs(1/x) == 1/Abs(x)
e = abs(2/x**2)
assert e.is_Mul and e == 2/Abs(x**2)
assert unchanged(Abs, y/x)
assert unchanged(Abs, x/(x + 1))
assert unchanged(Abs, x*y)
p = Symbol('p', positive=True)
assert abs(x/p) == abs(x)/p
# coverage
assert unchanged(Abs, Symbol('x', real=True)**y)
# issue 19627
f = Function('f', positive=True)
assert sqrt(f(x)**2) == f(x)
def test_Abs_rewrite():
x = Symbol('x', real=True)
a = Abs(x).rewrite(Heaviside).expand()
assert a == x*Heaviside(x) - x*Heaviside(-x)
for i in [-2, -1, 0, 1, 2]:
assert a.subs(x, i) == abs(i)
y = Symbol('y')
assert Abs(y).rewrite(Heaviside) == Abs(y)
x, y = Symbol('x', real=True), Symbol('y')
assert Abs(x).rewrite(Piecewise) == Piecewise((x, x >= 0), (-x, True))
assert Abs(y).rewrite(Piecewise) == Abs(y)
assert Abs(y).rewrite(sign) == y/sign(y)
i = Symbol('i', imaginary=True)
assert abs(i).rewrite(Piecewise) == Piecewise((I*i, I*i >= 0), (-I*i, True))
assert Abs(y).rewrite(conjugate) == sqrt(y*conjugate(y))
assert Abs(i).rewrite(conjugate) == sqrt(-i**2) # == -I*i
y = Symbol('y', extended_real=True)
assert (Abs(exp(-I*x)-exp(-I*y))**2).rewrite(conjugate) == \
-exp(I*x)*exp(-I*y) + 2 - exp(-I*x)*exp(I*y)
def test_Abs_real():
# test some properties of abs that only apply
# to real numbers
x = Symbol('x', complex=True)
assert sqrt(x**2) != Abs(x)
assert Abs(x**2) != x**2
x = Symbol('x', real=True)
assert sqrt(x**2) == Abs(x)
assert Abs(x**2) == x**2
# if the symbol is zero, the following will still apply
nn = Symbol('nn', nonnegative=True, real=True)
np = Symbol('np', nonpositive=True, real=True)
assert Abs(nn) == nn
assert Abs(np) == -np
def test_Abs_properties():
x = Symbol('x')
assert Abs(x).is_real is None
assert Abs(x).is_extended_real is True
assert Abs(x).is_rational is None
assert Abs(x).is_positive is None
assert Abs(x).is_nonnegative is None
assert Abs(x).is_extended_positive is None
assert Abs(x).is_extended_nonnegative is True
f = Symbol('x', finite=True)
assert Abs(f).is_real is True
assert Abs(f).is_extended_real is True
assert Abs(f).is_rational is None
assert Abs(f).is_positive is None
assert Abs(f).is_nonnegative is True
assert Abs(f).is_extended_positive is None
assert Abs(f).is_extended_nonnegative is True
z = Symbol('z', complex=True, zero=False)
assert Abs(z).is_real is True # since complex implies finite
assert Abs(z).is_extended_real is True
assert Abs(z).is_rational is None
assert Abs(z).is_positive is True
assert Abs(z).is_extended_positive is True
assert Abs(z).is_zero is False
p = Symbol('p', positive=True)
assert Abs(p).is_real is True
assert Abs(p).is_extended_real is True
assert Abs(p).is_rational is None
assert Abs(p).is_positive is True
assert Abs(p).is_zero is False
q = Symbol('q', rational=True)
assert Abs(q).is_real is True
assert Abs(q).is_rational is True
assert Abs(q).is_integer is None
assert Abs(q).is_positive is None
assert Abs(q).is_nonnegative is True
i = Symbol('i', integer=True)
assert Abs(i).is_real is True
assert Abs(i).is_integer is True
assert Abs(i).is_positive is None
assert Abs(i).is_nonnegative is True
e = Symbol('n', even=True)
ne = Symbol('ne', real=True, even=False)
assert Abs(e).is_even is True
assert Abs(ne).is_even is False
assert Abs(i).is_even is None
o = Symbol('n', odd=True)
no = Symbol('no', real=True, odd=False)
assert Abs(o).is_odd is True
assert Abs(no).is_odd is False
assert Abs(i).is_odd is None
def test_abs():
# this tests that abs calls Abs; don't rename to
# test_Abs since that test is already above
a = Symbol('a', positive=True)
assert abs(I*(1 + a)**2) == (1 + a)**2
def test_arg():
assert arg(0) is nan
assert arg(1) == 0
assert arg(-1) == pi
assert arg(I) == pi/2
assert arg(-I) == -pi/2
assert arg(1 + I) == pi/4
assert arg(-1 + I) == pi*Rational(3, 4)
assert arg(1 - I) == -pi/4
assert arg(exp_polar(4*pi*I)) == 4*pi
assert arg(exp_polar(-7*pi*I)) == -7*pi
assert arg(exp_polar(5 - 3*pi*I/4)) == pi*Rational(-3, 4)
f = Function('f')
assert not arg(f(0) + I*f(1)).atoms(re)
x = Symbol('x')
p = Function('p', extended_positive=True)
assert arg(p(x)) == 0
assert arg((3 + I)*p(x)) == arg(3 + I)
p = Symbol('p', positive=True)
assert arg(p) == 0
n = Symbol('n', negative=True)
assert arg(n) == pi
x = Symbol('x')
assert conjugate(arg(x)) == arg(x)
e = p + I*p**2
assert arg(e) == arg(1 + p*I)
# make sure sign doesn't swap
e = -2*p + 4*I*p**2
assert arg(e) == arg(-1 + 2*p*I)
# make sure sign isn't lost
x = symbols('x', real=True) # could be zero
e = x + I*x
assert arg(e) == arg(x*(1 + I))
assert arg(e/p) == arg(x*(1 + I))
e = p*cos(p) + I*log(p)*exp(p)
assert arg(e).args[0] == e
# keep it simple -- let the user do more advanced cancellation
e = (p + 1) + I*(p**2 - 1)
assert arg(e).args[0] == e
f = Function('f')
e = 2*x*(f(0) - 1) - 2*x*f(0)
assert arg(e) == arg(-2*x)
assert arg(f(0)).func == arg and arg(f(0)).args == (f(0),)
def test_arg_rewrite():
assert arg(1 + I) == atan2(1, 1)
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert arg(x + I*y).rewrite(atan2) == atan2(y, x)
def test_adjoint():
a = Symbol('a', antihermitian=True)
b = Symbol('b', hermitian=True)
assert adjoint(a) == -a
assert adjoint(I*a) == I*a
assert adjoint(b) == b
assert adjoint(I*b) == -I*b
assert adjoint(a*b) == -b*a
assert adjoint(I*a*b) == I*b*a
x, y = symbols('x y')
assert adjoint(adjoint(x)) == x
assert adjoint(x + y) == adjoint(x) + adjoint(y)
assert adjoint(x - y) == adjoint(x) - adjoint(y)
assert adjoint(x * y) == adjoint(x) * adjoint(y)
assert adjoint(x / y) == adjoint(x) / adjoint(y)
assert adjoint(-x) == -adjoint(x)
x, y = symbols('x y', commutative=False)
assert adjoint(adjoint(x)) == x
assert adjoint(x + y) == adjoint(x) + adjoint(y)
assert adjoint(x - y) == adjoint(x) - adjoint(y)
assert adjoint(x * y) == adjoint(y) * adjoint(x)
assert adjoint(x / y) == 1 / adjoint(y) * adjoint(x)
assert adjoint(-x) == -adjoint(x)
def test_conjugate():
a = Symbol('a', real=True)
b = Symbol('b', imaginary=True)
assert conjugate(a) == a
assert conjugate(I*a) == -I*a
assert conjugate(b) == -b
assert conjugate(I*b) == I*b
assert conjugate(a*b) == -a*b
assert conjugate(I*a*b) == I*a*b
x, y = symbols('x y')
assert conjugate(conjugate(x)) == x
assert conjugate(x + y) == conjugate(x) + conjugate(y)
assert conjugate(x - y) == conjugate(x) - conjugate(y)
assert conjugate(x * y) == conjugate(x) * conjugate(y)
assert conjugate(x / y) == conjugate(x) / conjugate(y)
assert conjugate(-x) == -conjugate(x)
a = Symbol('a', algebraic=True)
t = Symbol('t', transcendental=True)
assert re(a).is_algebraic
assert re(x).is_algebraic is None
assert re(t).is_algebraic is False
def test_conjugate_transpose():
x = Symbol('x')
assert conjugate(transpose(x)) == adjoint(x)
assert transpose(conjugate(x)) == adjoint(x)
assert adjoint(transpose(x)) == conjugate(x)
assert transpose(adjoint(x)) == conjugate(x)
assert adjoint(conjugate(x)) == transpose(x)
assert conjugate(adjoint(x)) == transpose(x)
class Symmetric(Expr):
def _eval_adjoint(self):
return None
def _eval_conjugate(self):
return None
def _eval_transpose(self):
return self
x = Symmetric()
assert conjugate(x) == adjoint(x)
assert transpose(x) == x
def test_transpose():
a = Symbol('a', complex=True)
assert transpose(a) == a
assert transpose(I*a) == I*a
x, y = symbols('x y')
assert transpose(transpose(x)) == x
assert transpose(x + y) == transpose(x) + transpose(y)
assert transpose(x - y) == transpose(x) - transpose(y)
assert transpose(x * y) == transpose(x) * transpose(y)
assert transpose(x / y) == transpose(x) / transpose(y)
assert transpose(-x) == -transpose(x)
x, y = symbols('x y', commutative=False)
assert transpose(transpose(x)) == x
assert transpose(x + y) == transpose(x) + transpose(y)
assert transpose(x - y) == transpose(x) - transpose(y)
assert transpose(x * y) == transpose(y) * transpose(x)
assert transpose(x / y) == 1 / transpose(y) * transpose(x)
assert transpose(-x) == -transpose(x)
@_both_exp_pow
def test_polarify():
from sympy import polar_lift, polarify
x = Symbol('x')
z = Symbol('z', polar=True)
f = Function('f')
ES = {}
assert polarify(-1) == (polar_lift(-1), ES)
assert polarify(1 + I) == (polar_lift(1 + I), ES)
assert polarify(exp(x), subs=False) == exp(x)
assert polarify(1 + x, subs=False) == 1 + x
assert polarify(f(I) + x, subs=False) == f(polar_lift(I)) + x
assert polarify(x, lift=True) == polar_lift(x)
assert polarify(z, lift=True) == z
assert polarify(f(x), lift=True) == f(polar_lift(x))
assert polarify(1 + x, lift=True) == polar_lift(1 + x)
assert polarify(1 + f(x), lift=True) == polar_lift(1 + f(polar_lift(x)))
newex, subs = polarify(f(x) + z)
assert newex.subs(subs) == f(x) + z
mu = Symbol("mu")
sigma = Symbol("sigma", positive=True)
# Make sure polarify(lift=True) doesn't try to lift the integration
# variable
assert polarify(
Integral(sqrt(2)*x*exp(-(-mu + x)**2/(2*sigma**2))/(2*sqrt(pi)*sigma),
(x, -oo, oo)), lift=True) == Integral(sqrt(2)*(sigma*exp_polar(0))**exp_polar(I*pi)*
exp((sigma*exp_polar(0))**(2*exp_polar(I*pi))*exp_polar(I*pi)*polar_lift(-mu + x)**
(2*exp_polar(0))/2)*exp_polar(0)*polar_lift(x)/(2*sqrt(pi)), (x, -oo, oo))
def test_unpolarify():
from sympy import (exp_polar, polar_lift, exp, unpolarify,
principal_branch)
from sympy import gamma, erf, sin, tanh, uppergamma, Eq, Ne
from sympy.abc import x
p = exp_polar(7*I) + 1
u = exp(7*I) + 1
assert unpolarify(1) == 1
assert unpolarify(p) == u
assert unpolarify(p**2) == u**2
assert unpolarify(p**x) == p**x
assert unpolarify(p*x) == u*x
assert unpolarify(p + x) == u + x
assert unpolarify(sqrt(sin(p))) == sqrt(sin(u))
# Test reduction to principal branch 2*pi.
t = principal_branch(x, 2*pi)
assert unpolarify(t) == x
assert unpolarify(sqrt(t)) == sqrt(t)
# Test exponents_only.
assert unpolarify(p**p, exponents_only=True) == p**u
assert unpolarify(uppergamma(x, p**p)) == uppergamma(x, p**u)
# Test functions.
assert unpolarify(sin(p)) == sin(u)
assert unpolarify(tanh(p)) == tanh(u)
assert unpolarify(gamma(p)) == gamma(u)
assert unpolarify(erf(p)) == erf(u)
assert unpolarify(uppergamma(x, p)) == uppergamma(x, p)
assert unpolarify(uppergamma(sin(p), sin(p + exp_polar(0)))) == \
uppergamma(sin(u), sin(u + 1))
assert unpolarify(uppergamma(polar_lift(0), 2*exp_polar(0))) == \
uppergamma(0, 2)
assert unpolarify(Eq(p, 0)) == Eq(u, 0)
assert unpolarify(Ne(p, 0)) == Ne(u, 0)
assert unpolarify(polar_lift(x) > 0) == (x > 0)
# Test bools
assert unpolarify(True) is True
def test_issue_4035():
x = Symbol('x')
assert Abs(x).expand(trig=True) == Abs(x)
assert sign(x).expand(trig=True) == sign(x)
assert arg(x).expand(trig=True) == arg(x)
def test_issue_3206():
x = Symbol('x')
assert Abs(Abs(x)) == Abs(x)
def test_issue_4754_derivative_conjugate():
x = Symbol('x', real=True)
y = Symbol('y', imaginary=True)
f = Function('f')
assert (f(x).conjugate()).diff(x) == (f(x).diff(x)).conjugate()
assert (f(y).conjugate()).diff(y) == -(f(y).diff(y)).conjugate()
def test_derivatives_issue_4757():
x = Symbol('x', real=True)
y = Symbol('y', imaginary=True)
f = Function('f')
assert re(f(x)).diff(x) == re(f(x).diff(x))
assert im(f(x)).diff(x) == im(f(x).diff(x))
assert re(f(y)).diff(y) == -I*im(f(y).diff(y))
assert im(f(y)).diff(y) == -I*re(f(y).diff(y))
assert Abs(f(x)).diff(x).subs(f(x), 1 + I*x).doit() == x/sqrt(1 + x**2)
assert arg(f(x)).diff(x).subs(f(x), 1 + I*x**2).doit() == 2*x/(1 + x**4)
assert Abs(f(y)).diff(y).subs(f(y), 1 + y).doit() == -y/sqrt(1 - y**2)
assert arg(f(y)).diff(y).subs(f(y), I + y**2).doit() == 2*y/(1 + y**4)
def test_issue_11413():
from sympy import Matrix, simplify
v0 = Symbol('v0')
v1 = Symbol('v1')
v2 = Symbol('v2')
V = Matrix([[v0],[v1],[v2]])
U = V.normalized()
assert U == Matrix([
[v0/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
[v1/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
[v2/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)]])
U.norm = sqrt(v0**2/(v0**2 + v1**2 + v2**2) + v1**2/(v0**2 + v1**2 + v2**2) + v2**2/(v0**2 + v1**2 + v2**2))
assert simplify(U.norm) == 1
def test_periodic_argument():
from sympy import (periodic_argument, unbranched_argument, oo,
principal_branch, polar_lift, pi)
x = Symbol('x')
p = Symbol('p', positive=True)
assert unbranched_argument(2 + I) == periodic_argument(2 + I, oo)
assert unbranched_argument(1 + x) == periodic_argument(1 + x, oo)
assert N_equals(unbranched_argument((1 + I)**2), pi/2)
assert N_equals(unbranched_argument((1 - I)**2), -pi/2)
assert N_equals(periodic_argument((1 + I)**2, 3*pi), pi/2)
assert N_equals(periodic_argument((1 - I)**2, 3*pi), -pi/2)
assert unbranched_argument(principal_branch(x, pi)) == \
periodic_argument(x, pi)
assert unbranched_argument(polar_lift(2 + I)) == unbranched_argument(2 + I)
assert periodic_argument(polar_lift(2 + I), 2*pi) == \
periodic_argument(2 + I, 2*pi)
assert periodic_argument(polar_lift(2 + I), 3*pi) == \
periodic_argument(2 + I, 3*pi)
assert periodic_argument(polar_lift(2 + I), pi) == \
periodic_argument(polar_lift(2 + I), pi)
assert unbranched_argument(polar_lift(1 + I)) == pi/4
assert periodic_argument(2*p, p) == periodic_argument(p, p)
assert periodic_argument(pi*p, p) == periodic_argument(p, p)
assert Abs(polar_lift(1 + I)) == Abs(1 + I)
@XFAIL
def test_principal_branch_fail():
# TODO XXX why does abs(x)._eval_evalf() not fall back to global evalf?
from sympy import principal_branch
assert N_equals(principal_branch((1 + I)**2, pi/2), 0)
def test_principal_branch():
from sympy import principal_branch, polar_lift, exp_polar
p = Symbol('p', positive=True)
x = Symbol('x')
neg = Symbol('x', negative=True)
assert principal_branch(polar_lift(x), p) == principal_branch(x, p)
assert principal_branch(polar_lift(2 + I), p) == principal_branch(2 + I, p)
assert principal_branch(2*x, p) == 2*principal_branch(x, p)
assert principal_branch(1, pi) == exp_polar(0)
assert principal_branch(-1, 2*pi) == exp_polar(I*pi)
assert principal_branch(-1, pi) == exp_polar(0)
assert principal_branch(exp_polar(3*pi*I)*x, 2*pi) == \
principal_branch(exp_polar(I*pi)*x, 2*pi)
assert principal_branch(neg*exp_polar(pi*I), 2*pi) == neg*exp_polar(-I*pi)
# related to issue #14692
assert principal_branch(exp_polar(-I*pi/2)/polar_lift(neg), 2*pi) == \
exp_polar(-I*pi/2)/neg
assert N_equals(principal_branch((1 + I)**2, 2*pi), 2*I)
assert N_equals(principal_branch((1 + I)**2, 3*pi), 2*I)
assert N_equals(principal_branch((1 + I)**2, 1*pi), 2*I)
# test argument sanitization
assert principal_branch(x, I).func is principal_branch
assert principal_branch(x, -4).func is principal_branch
assert principal_branch(x, -oo).func is principal_branch
assert principal_branch(x, zoo).func is principal_branch
@XFAIL
def test_issue_6167_6151():
n = pi**1000
i = int(n)
assert sign(n - i) == 1
assert abs(n - i) == n - i
x = Symbol('x')
eps = pi**-1500
big = pi**1000
one = cos(x)**2 + sin(x)**2
e = big*one - big + eps
from sympy import simplify
assert sign(simplify(e)) == 1
for xi in (111, 11, 1, Rational(1, 10)):
assert sign(e.subs(x, xi)) == 1
def test_issue_14216():
from sympy.functions.elementary.complexes import unpolarify
A = MatrixSymbol("A", 2, 2)
assert unpolarify(A[0, 0]) == A[0, 0]
assert unpolarify(A[0, 0]*A[1, 0]) == A[0, 0]*A[1, 0]
def test_issue_14238():
# doesn't cause recursion error
r = Symbol('r', real=True)
assert Abs(r + Piecewise((0, r > 0), (1 - r, True)))
def test_zero_assumptions():
nr = Symbol('nonreal', real=False, finite=True)
ni = Symbol('nonimaginary', imaginary=False)
# imaginary implies not zero
nzni = Symbol('nonzerononimaginary', zero=False, imaginary=False)
assert re(nr).is_zero is None
assert im(nr).is_zero is False
assert re(ni).is_zero is None
assert im(ni).is_zero is None
assert re(nzni).is_zero is False
assert im(nzni).is_zero is None
@_both_exp_pow
def test_issue_15893():
f = Function('f', real=True)
x = Symbol('x', real=True)
eq = Derivative(Abs(f(x)), f(x))
assert eq.doit() == sign(f(x))
|
afd3cda417a78c4a27cb6ec4f30bd73e57229693c99eb16bc96f38c97feed227 | from sympy import (
adjoint, And, Basic, conjugate, diff, expand, Eq, Function, I, ITE,
Integral, integrate, Interval, KroneckerDelta, lambdify, log, Max, Min,
oo, Or, pi, Piecewise, piecewise_fold, Rational, solve, symbols, transpose,
cos, sin, exp, Abs, Ne, Not, Symbol, S, sqrt, Sum, Tuple, zoo, Float,
DiracDelta, Heaviside, Add, Mul, factorial, Ge, Contains)
from sympy.core.expr import unchanged
from sympy.functions.elementary.piecewise import Undefined, ExprCondPair
from sympy.printing import srepr
from sympy.testing.pytest import raises, slow
from sympy.simplify import simplify
a, b, c, d, x, y = symbols('a:d, x, y')
z = symbols('z', nonzero=True)
def test_piecewise1():
# Test canonicalization
assert unchanged(Piecewise, ExprCondPair(x, x < 1), ExprCondPair(0, True))
assert Piecewise((x, x < 1), (0, True)) == Piecewise(ExprCondPair(x, x < 1),
ExprCondPair(0, True))
assert Piecewise((x, x < 1), (0, True), (1, True)) == \
Piecewise((x, x < 1), (0, True))
assert Piecewise((x, x < 1), (0, False), (-1, 1 > 2)) == \
Piecewise((x, x < 1))
assert Piecewise((x, x < 1), (0, x < 1), (0, True)) == \
Piecewise((x, x < 1), (0, True))
assert Piecewise((x, x < 1), (0, x < 2), (0, True)) == \
Piecewise((x, x < 1), (0, True))
assert Piecewise((x, x < 1), (x, x < 2), (0, True)) == \
Piecewise((x, Or(x < 1, x < 2)), (0, True))
assert Piecewise((x, x < 1), (x, x < 2), (x, True)) == x
assert Piecewise((x, True)) == x
# Explicitly constructed empty Piecewise not accepted
raises(TypeError, lambda: Piecewise())
# False condition is never retained
assert Piecewise((2*x, x < 0), (x, False)) == \
Piecewise((2*x, x < 0), (x, False), evaluate=False) == \
Piecewise((2*x, x < 0))
assert Piecewise((x, False)) == Undefined
raises(TypeError, lambda: Piecewise(x))
assert Piecewise((x, 1)) == x # 1 and 0 are accepted as True/False
raises(TypeError, lambda: Piecewise((x, 2)))
raises(TypeError, lambda: Piecewise((x, x**2)))
raises(TypeError, lambda: Piecewise(([1], True)))
assert Piecewise(((1, 2), True)) == Tuple(1, 2)
cond = (Piecewise((1, x < 0), (2, True)) < y)
assert Piecewise((1, cond)
) == Piecewise((1, ITE(x < 0, y > 1, y > 2)))
assert Piecewise((1, x > 0), (2, And(x <= 0, x > -1))
) == Piecewise((1, x > 0), (2, x > -1))
# test for supporting Contains in Piecewise
pwise = Piecewise(
(1, And(x <= 6, x > 1, Contains(x, S.Integers))),
(0, True))
assert pwise.subs(x, pi) == 0
assert pwise.subs(x, 2) == 1
assert pwise.subs(x, 7) == 0
# Test subs
p = Piecewise((-1, x < -1), (x**2, x < 0), (log(x), x >= 0))
p_x2 = Piecewise((-1, x**2 < -1), (x**4, x**2 < 0), (log(x**2), x**2 >= 0))
assert p.subs(x, x**2) == p_x2
assert p.subs(x, -5) == -1
assert p.subs(x, -1) == 1
assert p.subs(x, 1) == log(1)
# More subs tests
p2 = Piecewise((1, x < pi), (-1, x < 2*pi), (0, x > 2*pi))
p3 = Piecewise((1, Eq(x, 0)), (1/x, True))
p4 = Piecewise((1, Eq(x, 0)), (2, 1/x>2))
assert p2.subs(x, 2) == 1
assert p2.subs(x, 4) == -1
assert p2.subs(x, 10) == 0
assert p3.subs(x, 0.0) == 1
assert p4.subs(x, 0.0) == 1
f, g, h = symbols('f,g,h', cls=Function)
pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1))
pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1))
assert pg.subs(g, f) == pf
assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 0) == 1
assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 1) == 0
assert Piecewise((1, Eq(x, y)), (0, True)).subs(x, y) == 1
assert Piecewise((1, Eq(x, z)), (0, True)).subs(x, z) == 1
assert Piecewise((1, Eq(exp(x), cos(z))), (0, True)).subs(x, z) == \
Piecewise((1, Eq(exp(z), cos(z))), (0, True))
p5 = Piecewise( (0, Eq(cos(x) + y, 0)), (1, True))
assert p5.subs(y, 0) == Piecewise( (0, Eq(cos(x), 0)), (1, True))
assert Piecewise((-1, y < 1), (0, x < 0), (1, Eq(x, 0)), (2, True)
).subs(x, 1) == Piecewise((-1, y < 1), (2, True))
assert Piecewise((1, Eq(x**2, -1)), (2, x < 0)).subs(x, I) == 1
p6 = Piecewise((x, x > 0))
n = symbols('n', negative=True)
assert p6.subs(x, n) == Undefined
# Test evalf
assert p.evalf() == p
assert p.evalf(subs={x: -2}) == -1
assert p.evalf(subs={x: -1}) == 1
assert p.evalf(subs={x: 1}) == log(1)
assert p6.evalf(subs={x: -5}) == Undefined
# Test doit
f_int = Piecewise((Integral(x, (x, 0, 1)), x < 1))
assert f_int.doit() == Piecewise( (S.Half, x < 1) )
# Test differentiation
f = x
fp = x*p
dp = Piecewise((0, x < -1), (2*x, x < 0), (1/x, x >= 0))
fp_dx = x*dp + p
assert diff(p, x) == dp
assert diff(f*p, x) == fp_dx
# Test simple arithmetic
assert x*p == fp
assert x*p + p == p + x*p
assert p + f == f + p
assert p + dp == dp + p
assert p - dp == -(dp - p)
# Test power
dp2 = Piecewise((0, x < -1), (4*x**2, x < 0), (1/x**2, x >= 0))
assert dp**2 == dp2
# Test _eval_interval
f1 = x*y + 2
f2 = x*y**2 + 3
peval = Piecewise((f1, x < 0), (f2, x > 0))
peval_interval = f1.subs(
x, 0) - f1.subs(x, -1) + f2.subs(x, 1) - f2.subs(x, 0)
assert peval._eval_interval(x, 0, 0) == 0
assert peval._eval_interval(x, -1, 1) == peval_interval
peval2 = Piecewise((f1, x < 0), (f2, True))
assert peval2._eval_interval(x, 0, 0) == 0
assert peval2._eval_interval(x, 1, -1) == -peval_interval
assert peval2._eval_interval(x, -1, -2) == f1.subs(x, -2) - f1.subs(x, -1)
assert peval2._eval_interval(x, -1, 1) == peval_interval
assert peval2._eval_interval(x, None, 0) == peval2.subs(x, 0)
assert peval2._eval_interval(x, -1, None) == -peval2.subs(x, -1)
# Test integration
assert p.integrate() == Piecewise(
(-x, x < -1),
(x**3/3 + Rational(4, 3), x < 0),
(x*log(x) - x + Rational(4, 3), True))
p = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x))
assert integrate(p, (x, -2, 2)) == Rational(5, 6)
assert integrate(p, (x, 2, -2)) == Rational(-5, 6)
p = Piecewise((0, x < 0), (1, x < 1), (0, x < 2), (1, x < 3), (0, True))
assert integrate(p, (x, -oo, oo)) == 2
p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x))
assert integrate(p, (x, -2, 2)) == Undefined
# Test commutativity
assert isinstance(p, Piecewise) and p.is_commutative is True
def test_piecewise_free_symbols():
f = Piecewise((x, a < 0), (y, True))
assert f.free_symbols == {x, y, a}
def test_piecewise_integrate1():
x, y = symbols('x y', real=True, finite=True)
f = Piecewise(((x - 2)**2, x >= 0), (1, True))
assert integrate(f, (x, -2, 2)) == Rational(14, 3)
g = Piecewise(((x - 5)**5, x >= 4), (f, True))
assert integrate(g, (x, -2, 2)) == Rational(14, 3)
assert integrate(g, (x, -2, 5)) == Rational(43, 6)
assert g == Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
g = Piecewise(((x - 5)**5, 2 <= x), (f, x < 2))
assert integrate(g, (x, -2, 2)) == Rational(14, 3)
assert integrate(g, (x, -2, 5)) == Rational(-701, 6)
assert g == Piecewise(((x - 5)**5, 2 <= x), (f, True))
g = Piecewise(((x - 5)**5, 2 <= x), (2*f, True))
assert integrate(g, (x, -2, 2)) == Rational(28, 3)
assert integrate(g, (x, -2, 5)) == Rational(-673, 6)
def test_piecewise_integrate1b():
g = Piecewise((1, x > 0), (0, Eq(x, 0)), (-1, x < 0))
assert integrate(g, (x, -1, 1)) == 0
g = Piecewise((1, x - y < 0), (0, True))
assert integrate(g, (y, -oo, 0)) == -Min(0, x)
assert g.subs(x, -3).integrate((y, -oo, 0)) == 3
assert integrate(g, (y, 0, -oo)) == Min(0, x)
assert integrate(g, (y, 0, oo)) == -Max(0, x) + oo
assert integrate(g, (y, -oo, 42)) == -Min(42, x) + 42
assert integrate(g, (y, -oo, oo)) == -x + oo
g = Piecewise((0, x < 0), (x, x <= 1), (1, True))
gy1 = g.integrate((x, y, 1))
g1y = g.integrate((x, 1, y))
for yy in (-1, S.Half, 2):
assert g.integrate((x, yy, 1)) == gy1.subs(y, yy)
assert g.integrate((x, 1, yy)) == g1y.subs(y, yy)
assert gy1 == Piecewise(
(-Min(1, Max(0, y))**2/2 + S.Half, y < 1),
(-y + 1, True))
assert g1y == Piecewise(
(Min(1, Max(0, y))**2/2 - S.Half, y < 1),
(y - 1, True))
@slow
def test_piecewise_integrate1ca():
y = symbols('y', real=True)
g = Piecewise(
(1 - x, Interval(0, 1).contains(x)),
(1 + x, Interval(-1, 0).contains(x)),
(0, True)
)
gy1 = g.integrate((x, y, 1))
g1y = g.integrate((x, 1, y))
assert g.integrate((x, -2, 1)) == gy1.subs(y, -2)
assert g.integrate((x, 1, -2)) == g1y.subs(y, -2)
assert g.integrate((x, 0, 1)) == gy1.subs(y, 0)
assert g.integrate((x, 1, 0)) == g1y.subs(y, 0)
assert g.integrate((x, 2, 1)) == gy1.subs(y, 2)
assert g.integrate((x, 1, 2)) == g1y.subs(y, 2)
assert piecewise_fold(gy1.rewrite(Piecewise)) == \
Piecewise(
(1, y <= -1),
(-y**2/2 - y + S.Half, y <= 0),
(y**2/2 - y + S.Half, y < 1),
(0, True))
assert piecewise_fold(g1y.rewrite(Piecewise)) == \
Piecewise(
(-1, y <= -1),
(y**2/2 + y - S.Half, y <= 0),
(-y**2/2 + y - S.Half, y < 1),
(0, True))
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)) == \
Piecewise(
(1, y <= -1),
(-y**2/2 - y + S.Half, y <= 0),
(y**2/2 - y + S.Half, y < 1),
(0, True))
assert piecewise_fold(g1y.rewrite(Piecewise)) == \
Piecewise(
(-1, y <= -1),
(y**2/2 + y - S.Half, y <= 0),
(-y**2/2 + y - S.Half, y < 1),
(0, True))
# g1y and gy1 should simplify if the condition that y < 1
# is applied, e.g. Min(1, Max(-1, y)) --> Max(-1, y)
assert gy1 == Piecewise(
(
-Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) +
Min(1, Max(0, y))**2 + S.Half, y < 1),
(0, True)
)
assert g1y == Piecewise(
(
Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) -
Min(1, Max(0, y))**2 - S.Half, y < 1),
(0, True))
def test_piecewise_integrate2():
from itertools import permutations
lim = Tuple(x, c, d)
p = Piecewise((1, x < a), (2, x > b), (3, True))
q = p.integrate(lim)
assert q == Piecewise(
(-c + 2*d - 2*Min(d, Max(a, c)) + Min(d, Max(a, b, c)), c < d),
(-2*c + d + 2*Min(c, Max(a, d)) - Min(c, Max(a, b, d)), True))
for v in permutations((1, 2, 3, 4)):
r = dict(zip((a, b, c, d), v))
assert p.subs(r).integrate(lim.subs(r)) == q.subs(r)
def test_meijer_bypass():
# totally bypass meijerg machinery when dealing
# with Piecewise in integrate
assert Piecewise((1, x < 4), (0, True)).integrate((x, oo, 1)) == -3
def test_piecewise_integrate3_inequality_conditions():
from sympy.utilities.iterables import cartes
lim = (x, 0, 5)
# set below includes two pts below range, 2 pts in range,
# 2 pts above range, and the boundaries
N = (-2, -1, 0, 1, 2, 5, 6, 7)
p = Piecewise((1, x > a), (2, x > b), (0, True))
ans = p.integrate(lim)
for i, j in cartes(N, repeat=2):
reps = dict(zip((a, b), (i, j)))
assert ans.subs(reps) == p.subs(reps).integrate(lim)
assert ans.subs(a, 4).subs(b, 1) == 0 + 2*3 + 1
p = Piecewise((1, x > a), (2, x < b), (0, True))
ans = p.integrate(lim)
for i, j in cartes(N, repeat=2):
reps = dict(zip((a, b), (i, j)))
assert ans.subs(reps) == p.subs(reps).integrate(lim)
# delete old tests that involved c1 and c2 since those
# reduce to the above except that a value of 0 was used
# for two expressions whereas the above uses 3 different
# values
@slow
def test_piecewise_integrate4_symbolic_conditions():
a = Symbol('a', real=True, finite=True)
b = Symbol('b', real=True, finite=True)
x = Symbol('x', real=True, finite=True)
y = Symbol('y', real=True, finite=True)
p0 = Piecewise((0, Or(x < a, x > b)), (1, True))
p1 = Piecewise((0, x < a), (0, x > b), (1, True))
p2 = Piecewise((0, x > b), (0, x < a), (1, True))
p3 = Piecewise((0, x < a), (1, x < b), (0, True))
p4 = Piecewise((0, x > b), (1, x > a), (0, True))
p5 = Piecewise((1, And(a < x, x < b)), (0, True))
# check values of a=1, b=3 (and reversed) with values
# of y of 0, 1, 2, 3, 4
lim = Tuple(x, -oo, y)
for p in (p0, p1, p2, p3, p4, p5):
ans = p.integrate(lim)
for i in range(5):
reps = {a:1, b:3, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
reps = {a: 3, b:1, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
lim = Tuple(x, y, oo)
for p in (p0, p1, p2, p3, p4, p5):
ans = p.integrate(lim)
for i in range(5):
reps = {a:1, b:3, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
reps = {a:3, b:1, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
ans = Piecewise(
(0, x <= Min(a, b)),
(x - Min(a, b), x <= b),
(b - Min(a, b), True))
for i in (p0, p1, p2, p4):
assert i.integrate(x) == ans
assert p3.integrate(x) == Piecewise(
(0, x < a),
(-a + x, x <= Max(a, b)),
(-a + Max(a, b), True))
assert p5.integrate(x) == Piecewise(
(0, x <= a),
(-a + x, x <= Max(a, b)),
(-a + Max(a, b), True))
p1 = Piecewise((0, x < a), (0.5, x > b), (1, True))
p2 = Piecewise((0.5, x > b), (0, x < a), (1, True))
p3 = Piecewise((0, x < a), (1, x < b), (0.5, True))
p4 = Piecewise((0.5, x > b), (1, x > a), (0, True))
p5 = Piecewise((1, And(a < x, x < b)), (0.5, x > b), (0, True))
# check values of a=1, b=3 (and reversed) with values
# of y of 0, 1, 2, 3, 4
lim = Tuple(x, -oo, y)
for p in (p1, p2, p3, p4, p5):
ans = p.integrate(lim)
for i in range(5):
reps = {a:1, b:3, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
reps = {a: 3, b:1, y:i}
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
def test_piecewise_integrate5_independent_conditions():
p = Piecewise((0, Eq(y, 0)), (x*y, True))
assert integrate(p, (x, 1, 3)) == Piecewise((0, Eq(y, 0)), (4*y, True))
def test_piecewise_simplify():
p = Piecewise(((x**2 + 1)/x**2, Eq(x*(1 + x) - x**2, 0)),
((-1)**x*(-1), True))
assert p.simplify() == \
Piecewise((zoo, Eq(x, 0)), ((-1)**(x + 1), True))
# simplify when there are Eq in conditions
assert Piecewise(
(a, And(Eq(a, 0), Eq(a + b, 0))), (1, True)).simplify(
) == Piecewise(
(0, And(Eq(a, 0), Eq(b, 0))), (1, True))
assert Piecewise((2*x*factorial(a)/(factorial(y)*factorial(-y + a)),
Eq(y, 0) & Eq(-y + a, 0)), (2*factorial(a)/(factorial(y)*factorial(-y
+ a)), Eq(y, 0) & Eq(-y + a, 1)), (0, True)).simplify(
) == Piecewise(
(2*x, And(Eq(a, 0), Eq(y, 0))),
(2, And(Eq(a, 1), Eq(y, 0))),
(0, True))
args = (2, And(Eq(x, 2), Ge(y ,0))), (x, True)
assert Piecewise(*args).simplify() == Piecewise(*args)
args = (1, Eq(x, 0)), (sin(x)/x, True)
assert Piecewise(*args).simplify() == Piecewise(*args)
assert Piecewise((2 + y, And(Eq(x, 2), Eq(y, 0))), (x, True)
).simplify() == x
# check that x or f(x) are recognized as being Symbol-like for lhs
args = Tuple((1, Eq(x, 0)), (sin(x) + 1 + x, True))
ans = x + sin(x) + 1
f = Function('f')
assert Piecewise(*args).simplify() == ans
assert Piecewise(*args.subs(x, f(x))).simplify() == ans.subs(x, f(x))
# issue 18634
d = Symbol("d", integer=True)
n = Symbol("n", integer=True)
t = Symbol("t", real=True, positive=True)
expr = Piecewise((-d + 2*n, Eq(1/t, 1)), (t**(1 - 4*n)*t**(4*n - 1)*(-d + 2*n), True))
assert expr.simplify() == -d + 2*n
def test_piecewise_solve():
abs2 = Piecewise((-x, x <= 0), (x, x > 0))
f = abs2.subs(x, x - 2)
assert solve(f, x) == [2]
assert solve(f - 1, x) == [1, 3]
f = Piecewise(((x - 2)**2, x >= 0), (1, True))
assert solve(f, x) == [2]
g = Piecewise(((x - 5)**5, x >= 4), (f, True))
assert solve(g, x) == [2, 5]
g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
assert solve(g, x) == [2, 5]
g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2))
assert solve(g, x) == [5]
g = Piecewise(((x - 5)**5, x >= 2), (f, True))
assert solve(g, x) == [5]
g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False))
assert solve(g, x) == [5]
g = Piecewise(((x - 5)**5, x >= 2),
(-x + 2, x - 2 <= 0), (x - 2, x - 2 > 0))
assert solve(g, x) == [5]
# if no symbol is given the piecewise detection must still work
assert solve(Piecewise((x - 2, x > 2), (2 - x, True)) - 3) == [-1, 5]
f = Piecewise(((x - 2)**2, x >= 0), (0, True))
raises(NotImplementedError, lambda: solve(f, x))
def nona(ans):
return list(filter(lambda x: x is not S.NaN, ans))
p = Piecewise((x**2 - 4, x < y), (x - 2, True))
ans = solve(p, x)
assert nona([i.subs(y, -2) for i in ans]) == [2]
assert nona([i.subs(y, 2) for i in ans]) == [-2, 2]
assert nona([i.subs(y, 3) for i in ans]) == [-2, 2]
assert ans == [
Piecewise((-2, y > -2), (S.NaN, True)),
Piecewise((2, y <= 2), (S.NaN, True)),
Piecewise((2, y > 2), (S.NaN, True))]
# issue 6060
absxm3 = Piecewise(
(x - 3, 0 <= x - 3),
(3 - x, 0 > x - 3)
)
assert solve(absxm3 - y, x) == [
Piecewise((-y + 3, -y < 0), (S.NaN, True)),
Piecewise((y + 3, y >= 0), (S.NaN, True))]
p = Symbol('p', positive=True)
assert solve(absxm3 - p, x) == [-p + 3, p + 3]
# issue 6989
f = Function('f')
assert solve(Eq(-f(x), Piecewise((1, x > 0), (0, True))), f(x)) == \
[Piecewise((-1, x > 0), (0, True))]
# issue 8587
f = Piecewise((2*x**2, And(0 < x, x < 1)), (2, True))
assert solve(f - 1) == [1/sqrt(2)]
def test_piecewise_fold():
p = Piecewise((x, x < 1), (1, 1 <= x))
assert piecewise_fold(x*p) == Piecewise((x**2, x < 1), (x, 1 <= x))
assert piecewise_fold(p + p) == Piecewise((2*x, x < 1), (2, 1 <= x))
assert piecewise_fold(Piecewise((1, x < 0), (2, True))
+ Piecewise((10, x < 0), (-10, True))) == \
Piecewise((11, x < 0), (-8, True))
p1 = Piecewise((0, x < 0), (x, x <= 1), (0, True))
p2 = Piecewise((0, x < 0), (1 - x, x <= 1), (0, True))
p = 4*p1 + 2*p2
assert integrate(
piecewise_fold(p), (x, -oo, oo)) == integrate(2*x + 2, (x, 0, 1))
assert piecewise_fold(
Piecewise((1, y <= 0), (-Piecewise((2, y >= 0)), True)
)) == Piecewise((1, y <= 0), (-2, y >= 0))
assert piecewise_fold(Piecewise((x, ITE(x > 0, y < 1, y > 1)))
) == Piecewise((x, ((x <= 0) | (y < 1)) & ((x > 0) | (y > 1))))
a, b = (Piecewise((2, Eq(x, 0)), (0, True)),
Piecewise((x, Eq(-x + y, 0)), (1, Eq(-x + y, 1)), (0, True)))
assert piecewise_fold(Mul(a, b, evaluate=False)
) == piecewise_fold(Mul(b, a, evaluate=False))
def test_piecewise_fold_piecewise_in_cond():
p1 = Piecewise((cos(x), x < 0), (0, True))
p2 = Piecewise((0, Eq(p1, 0)), (p1 / Abs(p1), True))
assert p2.subs(x, -pi/2) == 0
assert p2.subs(x, 1) == 0
assert p2.subs(x, -pi/4) == 1
p4 = Piecewise((0, Eq(p1, 0)), (1,True))
ans = piecewise_fold(p4)
for i in range(-1, 1):
assert ans.subs(x, i) == p4.subs(x, i)
r1 = 1 < Piecewise((1, x < 1), (3, True))
ans = piecewise_fold(r1)
for i in range(2):
assert ans.subs(x, i) == r1.subs(x, i)
p5 = Piecewise((1, x < 0), (3, True))
p6 = Piecewise((1, x < 1), (3, True))
p7 = Piecewise((1, p5 < p6), (0, True))
ans = piecewise_fold(p7)
for i in range(-1, 2):
assert ans.subs(x, i) == p7.subs(x, i)
def test_piecewise_fold_piecewise_in_cond_2():
p1 = Piecewise((cos(x), x < 0), (0, True))
p2 = Piecewise((0, Eq(p1, 0)), (1 / p1, True))
p3 = Piecewise(
(0, (x >= 0) | Eq(cos(x), 0)),
(1/cos(x), x < 0),
(zoo, True)) # redundant b/c all x are already covered
assert(piecewise_fold(p2) == p3)
def test_piecewise_fold_expand():
p1 = Piecewise((1, Interval(0, 1, False, True).contains(x)), (0, True))
p2 = piecewise_fold(expand((1 - x)*p1))
assert p2 == Piecewise((1 - x, (x >= 0) & (x < 1)), (0, True))
assert p2 == expand(piecewise_fold((1 - x)*p1))
def test_piecewise_duplicate():
p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x))
assert p == Piecewise(*p.args)
def test_doit():
p1 = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x))
p2 = Piecewise((x, x < 1), (Integral(2 * x), -1 <= x), (x, 3 < x))
assert p2.doit() == p1
assert p2.doit(deep=False) == p2
# issue 17165
p1 = Sum(y**x, (x, -1, oo)).doit()
assert p1.doit() == p1
def test_piecewise_interval():
p1 = Piecewise((x, Interval(0, 1).contains(x)), (0, True))
assert p1.subs(x, -0.5) == 0
assert p1.subs(x, 0.5) == 0.5
assert p1.diff(x) == Piecewise((1, Interval(0, 1).contains(x)), (0, True))
assert integrate(p1, x) == Piecewise(
(0, x <= 0),
(x**2/2, x <= 1),
(S.Half, True))
def test_piecewise_collapse():
assert Piecewise((x, True)) == x
a = x < 1
assert Piecewise((x, a), (x + 1, a)) == Piecewise((x, a))
assert Piecewise((x, a), (x + 1, a.reversed)) == Piecewise((x, a))
b = x < 5
def canonical(i):
if isinstance(i, Piecewise):
return Piecewise(*i.args)
return i
for args in [
((1, a), (Piecewise((2, a), (3, b)), b)),
((1, a), (Piecewise((2, a), (3, b.reversed)), b)),
((1, a), (Piecewise((2, a), (3, b)), b), (4, True)),
((1, a), (Piecewise((2, a), (3, b), (4, True)), b)),
((1, a), (Piecewise((2, a), (3, b), (4, True)), b), (5, True))]:
for i in (0, 2, 10):
assert canonical(
Piecewise(*args, evaluate=False).subs(x, i)
) == canonical(Piecewise(*args).subs(x, i))
r1, r2, r3, r4 = symbols('r1:5')
a = x < r1
b = x < r2
c = x < r3
d = x < r4
assert Piecewise((1, a), (Piecewise(
(2, a), (3, b), (4, c)), b), (5, c)
) == Piecewise((1, a), (3, b), (5, c))
assert Piecewise((1, a), (Piecewise(
(2, a), (3, b), (4, c), (6, True)), c), (5, d)
) == Piecewise((1, a), (Piecewise(
(3, b), (4, c)), c), (5, d))
assert Piecewise((1, Or(a, d)), (Piecewise(
(2, d), (3, b), (4, c)), b), (5, c)
) == Piecewise((1, Or(a, d)), (Piecewise(
(2, d), (3, b)), b), (5, c))
assert Piecewise((1, c), (2, ~c), (3, S.true)
) == Piecewise((1, c), (2, S.true))
assert Piecewise((1, c), (2, And(~c, b)), (3,True)
) == Piecewise((1, c), (2, b), (3, True))
assert Piecewise((1, c), (2, Or(~c, b)), (3,True)
).subs(dict(zip((r1, r2, r3, r4, x), (1, 2, 3, 4, 3.5)))) == 2
assert Piecewise((1, c), (2, ~c)) == Piecewise((1, c), (2, True))
def test_piecewise_lambdify():
p = Piecewise(
(x**2, x < 0),
(x, Interval(0, 1, False, True).contains(x)),
(2 - x, x >= 1),
(0, True)
)
f = lambdify(x, p)
assert f(-2.0) == 4.0
assert f(0.0) == 0.0
assert f(0.5) == 0.5
assert f(2.0) == 0.0
def test_piecewise_series():
from sympy import sin, cos, O
p1 = Piecewise((sin(x), x < 0), (cos(x), x > 0))
p2 = Piecewise((x + O(x**2), x < 0), (1 + O(x**2), x > 0))
assert p1.nseries(x, n=2) == p2
def test_piecewise_as_leading_term():
p1 = Piecewise((1/x, x > 1), (0, True))
p2 = Piecewise((x, x > 1), (0, True))
p3 = Piecewise((1/x, x > 1), (x, True))
p4 = Piecewise((x, x > 1), (1/x, True))
p5 = Piecewise((1/x, x > 1), (x, True))
p6 = Piecewise((1/x, x < 1), (x, True))
p7 = Piecewise((x, x < 1), (1/x, True))
p8 = Piecewise((x, x > 1), (1/x, True))
assert p1.as_leading_term(x) == 0
assert p2.as_leading_term(x) == 0
assert p3.as_leading_term(x) == x
assert p4.as_leading_term(x) == 1/x
assert p5.as_leading_term(x) == x
assert p6.as_leading_term(x) == 1/x
assert p7.as_leading_term(x) == x
assert p8.as_leading_term(x) == 1/x
def test_piecewise_complex():
p1 = Piecewise((2, x < 0), (1, 0 <= x))
p2 = Piecewise((2*I, x < 0), (I, 0 <= x))
p3 = Piecewise((I*x, x > 1), (1 + I, True))
p4 = Piecewise((-I*conjugate(x), x > 1), (1 - I, True))
assert conjugate(p1) == p1
assert conjugate(p2) == piecewise_fold(-p2)
assert conjugate(p3) == p4
assert p1.is_imaginary is False
assert p1.is_real is True
assert p2.is_imaginary is True
assert p2.is_real is False
assert p3.is_imaginary is None
assert p3.is_real is None
assert p1.as_real_imag() == (p1, 0)
assert p2.as_real_imag() == (0, -I*p2)
def test_conjugate_transpose():
A, B = symbols("A B", commutative=False)
p = Piecewise((A*B**2, x > 0), (A**2*B, True))
assert p.adjoint() == \
Piecewise((adjoint(A*B**2), x > 0), (adjoint(A**2*B), True))
assert p.conjugate() == \
Piecewise((conjugate(A*B**2), x > 0), (conjugate(A**2*B), True))
assert p.transpose() == \
Piecewise((transpose(A*B**2), x > 0), (transpose(A**2*B), True))
def test_piecewise_evaluate():
assert Piecewise((x, True)) == x
assert Piecewise((x, True), evaluate=True) == x
p = Piecewise((x, True), evaluate=False)
assert p != x
assert p.is_Piecewise
assert all(isinstance(i, Basic) for i in p.args)
assert Piecewise((1, Eq(1, x))).args == ((1, Eq(x, 1)),)
assert Piecewise((1, Eq(1, x)), evaluate=False).args == (
(1, Eq(1, x)),)
def test_as_expr_set_pairs():
assert Piecewise((x, x > 0), (-x, x <= 0)).as_expr_set_pairs() == \
[(x, Interval(0, oo, True, True)), (-x, Interval(-oo, 0))]
assert Piecewise(((x - 2)**2, x >= 0), (0, True)).as_expr_set_pairs() == \
[((x - 2)**2, Interval(0, oo)), (0, Interval(-oo, 0, True, True))]
def test_S_srepr_is_identity():
p = Piecewise((10, Eq(x, 0)), (12, True))
q = S(srepr(p))
assert p == q
def test_issue_12587():
# sort holes into intervals
p = Piecewise((1, x > 4), (2, Not((x <= 3) & (x > -1))), (3, True))
assert p.integrate((x, -5, 5)) == 23
p = Piecewise((1, x > 1), (2, x < y), (3, True))
lim = x, -3, 3
ans = p.integrate(lim)
for i in range(-1, 3):
assert ans.subs(y, i) == p.subs(y, i).integrate(lim)
def test_issue_11045():
assert integrate(1/(x*sqrt(x**2 - 1)), (x, 1, 2)) == pi/3
# handle And with Or arguments
assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True)
).integrate((x, 0, 3)) == 1
# hidden false
assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)
).integrate((x, 0, 3)) == 5
# targetcond is Eq
assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True)
).integrate((x, 0, 4)) == 6
# And has Relational needing to be solved
assert Piecewise((1, And(2*x > x + 1, x < 2)), (0, True)
).integrate((x, 0, 3)) == 1
# Or has Relational needing to be solved
assert Piecewise((1, Or(2*x > x + 2, x < 1)), (0, True)
).integrate((x, 0, 3)) == 2
# ignore hidden false (handled in canonicalization)
assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)
).integrate((x, 0, 3)) == 5
# watch for hidden True Piecewise
assert Piecewise((2, Eq(1 - x, x*(1/x - 1))), (0, True)
).integrate((x, 0, 3)) == 6
# overlapping conditions of targetcond are recognized and ignored;
# the condition x > 3 will be pre-empted by the first condition
assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True)
).integrate((x, 0, 4)) == 6
# convert Ne to Or
assert Piecewise((1, Ne(x, 0)), (2, True)
).integrate((x, -1, 1)) == 2
# no default but well defined
assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))
).integrate((x, 1, 4)) == 5
p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4)))
nan = Undefined
i = p.integrate((x, 1, y))
assert i == Piecewise(
(y - 1, y < 1),
(Min(3, y)**2/2 - Min(3, y) + Min(4, y) - S.Half,
y <= Min(4, y)),
(nan, True))
assert p.integrate((x, 1, -1)) == i.subs(y, -1)
assert p.integrate((x, 1, 4)) == 5
assert p.integrate((x, 1, 5)) is nan
# handle Not
p = Piecewise((1, x > 1), (2, Not(And(x > 1, x< 3))), (3, True))
assert p.integrate((x, 0, 3)) == 4
# handle updating of int_expr when there is overlap
p = Piecewise(
(1, And(5 > x, x > 1)),
(2, Or(x < 3, x > 7)),
(4, x < 8))
assert p.integrate((x, 0, 10)) == 20
# And with Eq arg handling
assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1))
).integrate((x, 0, 3)) is S.NaN
assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)), (3, True)
).integrate((x, 0, 3)) == 7
assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)), (3, True)
).integrate((x, -1, 1)) == 4
# middle condition doesn't matter: it's a zero width interval
assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True)
).integrate((x, 0, 3)) == 7
def test_holes():
nan = Undefined
assert Piecewise((1, x < 2)).integrate(x) == Piecewise(
(x, x < 2), (nan, True))
assert Piecewise((1, And(x > 1, x < 2))).integrate(x) == Piecewise(
(nan, x < 1), (x - 1, x < 2), (nan, True))
assert Piecewise((1, And(x > 1, x < 2))).integrate((x, 0, 3)) is nan
assert Piecewise((1, And(x > 0, x < 4))).integrate((x, 1, 3)) == 2
# this also tests that the integrate method is used on non-Piecwise
# arguments in _eval_integral
A, B = symbols("A B")
a, b = symbols('a b', real=True)
assert Piecewise((A, And(x < 0, a < 1)), (B, Or(x < 1, a > 2))
).integrate(x) == Piecewise(
(B*x, (a > 2)),
(Piecewise((A*x, x < 0), (B*x, x < 1), (nan, True)), a < 1),
(Piecewise((B*x, x < 1), (nan, True)), True))
def test_issue_11922():
def f(x):
return Piecewise((0, x < -1), (1 - x**2, x < 1), (0, True))
autocorr = lambda k: (
f(x) * f(x + k)).integrate((x, -1, 1))
assert autocorr(1.9) > 0
k = symbols('k')
good_autocorr = lambda k: (
(1 - x**2) * f(x + k)).integrate((x, -1, 1))
a = good_autocorr(k)
assert a.subs(k, 3) == 0
k = symbols('k', positive=True)
a = good_autocorr(k)
assert a.subs(k, 3) == 0
assert Piecewise((0, x < 1), (10, (x >= 1))
).integrate() == Piecewise((0, x < 1), (10*x - 10, True))
def test_issue_5227():
f = 0.0032513612725229*Piecewise((0, x < -80.8461538461539),
(-0.0160799238820171*x + 1.33215984776403, x < 2),
(Piecewise((0.3, x > 123), (0.7, True)) +
Piecewise((0.4, x > 2), (0.6, True)), x <=
123), (-0.00817409766454352*x + 2.10541401273885, x <
380.571428571429), (0, True))
i = integrate(f, (x, -oo, oo))
assert i == Integral(f, (x, -oo, oo)).doit()
assert str(i) == '1.00195081676351'
assert Piecewise((1, x - y < 0), (0, True)
).integrate(y) == Piecewise((0, y <= x), (-x + y, True))
def test_issue_10137():
a = Symbol('a', real=True, finite=True)
b = Symbol('b', real=True, finite=True)
x = Symbol('x', real=True, finite=True)
y = Symbol('y', real=True, finite=True)
p0 = Piecewise((0, Or(x < a, x > b)), (1, True))
p1 = Piecewise((0, Or(a > x, b < x)), (1, True))
assert integrate(p0, (x, y, oo)) == integrate(p1, (x, y, oo))
p3 = Piecewise((1, And(0 < x, x < a)), (0, True))
p4 = Piecewise((1, And(a > x, x > 0)), (0, True))
ip3 = integrate(p3, x)
assert ip3 == Piecewise(
(0, x <= 0),
(x, x <= Max(0, a)),
(Max(0, a), True))
ip4 = integrate(p4, x)
assert ip4 == ip3
assert p3.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2
assert p4.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2
def test_stackoverflow_43852159():
f = lambda x: Piecewise((1 , (x >= -1) & (x <= 1)) , (0, True))
Conv = lambda x: integrate(f(x - y)*f(y), (y, -oo, +oo))
cx = Conv(x)
assert cx.subs(x, -1.5) == cx.subs(x, 1.5)
assert cx.subs(x, 3) == 0
assert piecewise_fold(f(x - y)*f(y)) == Piecewise(
(1, (y >= -1) & (y <= 1) & (x - y >= -1) & (x - y <= 1)),
(0, True))
def test_issue_12557():
'''
# 3200 seconds to compute the fourier part of issue
import sympy as sym
x,y,z,t = sym.symbols('x y z t')
k = sym.symbols("k", integer=True)
fourier = sym.fourier_series(sym.cos(k*x)*sym.sqrt(x**2),
(x, -sym.pi, sym.pi))
assert fourier == FourierSeries(
sqrt(x**2)*cos(k*x), (x, -pi, pi), (Piecewise((pi**2,
Eq(k, 0)), (2*(-1)**k/k**2 - 2/k**2, True))/(2*pi),
SeqFormula(Piecewise((pi**2, (Eq(_n, 0) & Eq(k, 0)) | (Eq(_n, 0) &
Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(k, 0) & Eq(_n, -k)) | (Eq(_n,
0) & Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), (pi**2/2, Eq(_n, k) | Eq(_n,
-k) | (Eq(_n, 0) & Eq(_n, k)) | (Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) &
Eq(_n, -k)) | (Eq(_n, k) & Eq(_n, -k)) | (Eq(k, 0) & Eq(_n, -k)) |
(Eq(_n, 0) & Eq(_n, k) & Eq(_n, -k)) | (Eq(_n, k) & Eq(k, 0) & Eq(_n,
-k))), ((-1)**k*pi**2*_n**3*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
pi*k**4) - (-1)**k*pi**2*_n**3*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2
- pi*k**4) + (-1)**k*pi*_n**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
pi*k**4) - (-1)**k*pi*_n**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
pi*k**4) - (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(pi*_n**4 -
2*pi*_n**2*k**2 + pi*k**4) +
(-1)**k*pi**2*_n*k**2*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
pi*k**4) + (-1)**k*pi*k**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
pi*k**4) - (-1)**k*pi*k**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
pi*k**4) - (2*_n**2 + 2*k**2)/(_n**4 - 2*_n**2*k**2 + k**4),
True))*cos(_n*x)/pi, (_n, 1, oo)), SeqFormula(0, (_k, 1, oo))))
'''
x = symbols("x", real=True)
k = symbols('k', integer=True, finite=True)
abs2 = lambda x: Piecewise((-x, x <= 0), (x, x > 0))
assert integrate(abs2(x), (x, -pi, pi)) == pi**2
func = cos(k*x)*sqrt(x**2)
assert integrate(func, (x, -pi, pi)) == Piecewise(
(2*(-1)**k/k**2 - 2/k**2, Ne(k, 0)), (pi**2, True))
def test_issue_6900():
from itertools import permutations
t0, t1, T, t = symbols('t0, t1 T t')
f = Piecewise((0, t < t0), (x, And(t0 <= t, t < t1)), (0, t >= t1))
g = f.integrate(t)
assert g == Piecewise(
(0, t <= t0),
(t*x - t0*x, t <= Max(t0, t1)),
(-t0*x + x*Max(t0, t1), True))
for i in permutations(range(2)):
reps = dict(zip((t0,t1), i))
for tt in range(-1,3):
assert (g.xreplace(reps).subs(t,tt) ==
f.xreplace(reps).integrate(t).subs(t,tt))
lim = Tuple(t, t0, T)
g = f.integrate(lim)
ans = Piecewise(
(-t0*x + x*Min(T, Max(t0, t1)), T > t0),
(0, True))
for i in permutations(range(3)):
reps = dict(zip((t0,t1,T), i))
tru = f.xreplace(reps).integrate(lim.xreplace(reps))
assert tru == ans.xreplace(reps)
assert g == ans
def test_issue_10122():
assert solve(abs(x) + abs(x - 1) - 1 > 0, x
) == Or(And(-oo < x, x < S.Zero), And(S.One < x, x < oo))
def test_issue_4313():
u = Piecewise((0, x <= 0), (1, x >= a), (x/a, True))
e = (u - u.subs(x, y))**2/(x - y)**2
M = Max(0, a)
assert integrate(e, x).expand() == Piecewise(
(Piecewise(
(0, x <= 0),
(-y**2/(a**2*x - a**2*y) + x/a**2 - 2*y*log(-y)/a**2 +
2*y*log(x - y)/a**2 - y/a**2, x <= M),
(-y**2/(-a**2*y + a**2*M) + 1/(-y + M) -
1/(x - y) - 2*y*log(-y)/a**2 + 2*y*log(-y +
M)/a**2 - y/a**2 + M/a**2, True)),
((a <= y) & (y <= 0)) | ((y <= 0) & (y > -oo))),
(Piecewise(
(-1/(x - y), x <= 0),
(-a**2/(a**2*x - a**2*y) + 2*a*y/(a**2*x - a**2*y) -
y**2/(a**2*x - a**2*y) + 2*log(-y)/a - 2*log(x - y)/a +
2/a + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 -
y/a**2, x <= M),
(-a**2/(-a**2*y + a**2*M) + 2*a*y/(-a**2*y +
a**2*M) - y**2/(-a**2*y + a**2*M) +
2*log(-y)/a - 2*log(-y + M)/a + 2/a -
2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 -
y/a**2 + M/a**2, True)),
a <= y),
(Piecewise(
(-y**2/(a**2*x - a**2*y), x <= 0),
(x/a**2 + y/a**2, x <= M),
(a**2/(-a**2*y + a**2*M) -
a**2/(a**2*x - a**2*y) - 2*a*y/(-a**2*y + a**2*M) +
2*a*y/(a**2*x - a**2*y) + y**2/(-a**2*y + a**2*M) -
y**2/(a**2*x - a**2*y) + y/a**2 + M/a**2, True)),
True))
def test__intervals():
assert Piecewise((x + 2, Eq(x, 3)))._intervals(x) == []
assert Piecewise(
(1, x > x + 1),
(Piecewise((1, x < x + 1)), 2*x < 2*x + 1),
(1, True))._intervals(x) == [(-oo, oo, 1, 1)]
assert Piecewise((1, Ne(x, I)), (0, True))._intervals(x) == [
(-oo, oo, 1, 0)]
assert Piecewise((-cos(x), sin(x) >= 0), (cos(x), True)
)._intervals(x) == [(0, pi, -cos(x), 0), (-oo, oo, cos(x), 1)]
# the following tests that duplicates are removed and that non-Eq
# generated zero-width intervals are removed
assert Piecewise((1, Abs(x**(-2)) > 1), (0, True)
)._intervals(x) == [(-1, 0, 1, 0), (0, 1, 1, 0), (-oo, oo, 0, 1)]
def test_containment():
a, b, c, d, e = [1, 2, 3, 4, 5]
p = (Piecewise((d, x > 1), (e, True))*
Piecewise((a, Abs(x - 1) < 1), (b, Abs(x - 2) < 2), (c, True)))
assert p.integrate(x).diff(x) == Piecewise(
(c*e, x <= 0),
(a*e, x <= 1),
(a*d, x < 2), # this is what we want to get right
(b*d, x < 4),
(c*d, True))
def test_piecewise_with_DiracDelta():
d1 = DiracDelta(x - 1)
assert integrate(d1, (x, -oo, oo)) == 1
assert integrate(d1, (x, 0, 2)) == 1
assert Piecewise((d1, Eq(x, 2)), (0, True)).integrate(x) == 0
assert Piecewise((d1, x < 2), (0, True)).integrate(x) == Piecewise(
(Heaviside(x - 1), x < 2), (1, True))
# TODO raise error if function is discontinuous at limit of
# integration, e.g. integrate(d1, (x, -2, 1)) or Piecewise(
# (d1, Eq(x ,1)
def test_issue_10258():
assert Piecewise((0, x < 1), (1, True)).is_zero is None
assert Piecewise((-1, x < 1), (1, True)).is_zero is False
a = Symbol('a', zero=True)
assert Piecewise((0, x < 1), (a, True)).is_zero
assert Piecewise((1, x < 1), (a, x < 3)).is_zero is None
a = Symbol('a')
assert Piecewise((0, x < 1), (a, True)).is_zero is None
assert Piecewise((0, x < 1), (1, True)).is_nonzero is None
assert Piecewise((1, x < 1), (2, True)).is_nonzero
assert Piecewise((0, x < 1), (oo, True)).is_finite is None
assert Piecewise((0, x < 1), (1, True)).is_finite
b = Basic()
assert Piecewise((b, x < 1)).is_finite is None
# 10258
c = Piecewise((1, x < 0), (2, True)) < 3
assert c != True
assert piecewise_fold(c) == True
def test_issue_10087():
a, b = Piecewise((x, x > 1), (2, True)), Piecewise((x, x > 3), (3, True))
m = a*b
f = piecewise_fold(m)
for i in (0, 2, 4):
assert m.subs(x, i) == f.subs(x, i)
m = a + b
f = piecewise_fold(m)
for i in (0, 2, 4):
assert m.subs(x, i) == f.subs(x, i)
def test_issue_8919():
c = symbols('c:5')
x = symbols("x")
f1 = Piecewise((c[1], x < 1), (c[2], True))
f2 = Piecewise((c[3], x < Rational(1, 3)), (c[4], True))
assert integrate(f1*f2, (x, 0, 2)
) == c[1]*c[3]/3 + 2*c[1]*c[4]/3 + c[2]*c[4]
f1 = Piecewise((0, x < 1), (2, True))
f2 = Piecewise((3, x < 2), (0, True))
assert integrate(f1*f2, (x, 0, 3)) == 6
y = symbols("y", positive=True)
a, b, c, x, z = symbols("a,b,c,x,z", real=True)
I = Integral(Piecewise(
(0, (x >= y) | (x < 0) | (b > c)),
(a, True)), (x, 0, z))
ans = I.doit()
assert ans == Piecewise((0, b > c), (a*Min(y, z) - a*Min(0, z), True))
for cond in (True, False):
for yy in range(1, 3):
for zz in range(-yy, 0, yy):
reps = [(b > c, cond), (y, yy), (z, zz)]
assert ans.subs(reps) == I.subs(reps).doit()
def test_unevaluated_integrals():
f = Function('f')
p = Piecewise((1, Eq(f(x) - 1, 0)), (2, x - 10 < 0), (0, True))
assert p.integrate(x) == Integral(p, x)
assert p.integrate((x, 0, 5)) == Integral(p, (x, 0, 5))
# test it by replacing f(x) with x%2 which will not
# affect the answer: the integrand is essentially 2 over
# the domain of integration
assert Integral(p, (x, 0, 5)).subs(f(x), x%2).n() == 10
# this is a test of using _solve_inequality when
# solve_univariate_inequality fails
assert p.integrate(y) == Piecewise(
(y, Eq(f(x), 1) | ((x < 10) & Eq(f(x), 1))),
(2*y, (x >= -oo) & (x < 10)), (0, True))
def test_conditions_as_alternate_booleans():
a, b, c = symbols('a:c')
assert Piecewise((x, Piecewise((y < 1, x > 0), (y > 1, True)))
) == Piecewise((x, ITE(x > 0, y < 1, y > 1)))
def test_Piecewise_rewrite_as_ITE():
a, b, c, d = symbols('a:d')
def _ITE(*args):
return Piecewise(*args).rewrite(ITE)
assert _ITE((a, x < 1), (b, x >= 1)) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (b, x < oo)) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (b, Or(y < 1, x < oo)), (c, y > 0)
) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (b, True)) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (b, x < 2), (c, True)
) == ITE(x < 1, a, ITE(x < 2, b, c))
assert _ITE((a, x < 1), (b, y < 2), (c, True)
) == ITE(x < 1, a, ITE(y < 2, b, c))
assert _ITE((a, x < 1), (b, x < oo), (c, y < 1)
) == ITE(x < 1, a, b)
assert _ITE((a, x < 1), (c, y < 1), (b, x < oo), (d, True)
) == ITE(x < 1, a, ITE(y < 1, c, b))
assert _ITE((a, x < 0), (b, Or(x < oo, y < 1))
) == ITE(x < 0, a, b)
raises(TypeError, lambda: _ITE((x + 1, x < 1), (x, True)))
# if `a` in the following were replaced with y then the coverage
# is complete but something other than as_set would need to be
# used to detect this
raises(NotImplementedError, lambda: _ITE((x, x < y), (y, x >= a)))
raises(ValueError, lambda: _ITE((a, x < 2), (b, x > 3)))
def test_issue_14052():
assert integrate(abs(sin(x)), (x, 0, 2*pi)) == 4
def test_issue_14240():
assert piecewise_fold(
Piecewise((1, a), (2, b), (4, True)) +
Piecewise((8, a), (16, True))
) == Piecewise((9, a), (18, b), (20, True))
assert piecewise_fold(
Piecewise((2, a), (3, b), (5, True)) *
Piecewise((7, a), (11, True))
) == Piecewise((14, a), (33, b), (55, True))
# these will hang if naive folding is used
assert piecewise_fold(Add(*[
Piecewise((i, a), (0, True)) for i in range(40)])
) == Piecewise((780, a), (0, True))
assert piecewise_fold(Mul(*[
Piecewise((i, a), (0, True)) for i in range(1, 41)])
) == Piecewise((factorial(40), a), (0, True))
def test_issue_14787():
x = Symbol('x')
f = Piecewise((x, x < 1), ((S(58) / 7), True))
assert str(f.evalf()) == "Piecewise((x, x < 1), (8.28571428571429, True))"
def test_issue_8458():
x, y = symbols('x y')
# Original issue
p1 = Piecewise((0, Eq(x, 0)), (sin(x), True))
assert p1.simplify() == sin(x)
# Slightly larger variant
p2 = Piecewise((x, Eq(x, 0)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True))
assert p2.simplify() == sin(x)
# Test for problem highlighted during review
p3 = Piecewise((x+1, Eq(x, -1)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True))
assert p3.simplify() == Piecewise((0, Eq(x, -1)), (sin(x), True))
def test_issue_16417():
from sympy import im, re, Gt
z = Symbol('z')
assert unchanged(Piecewise, (1, Or(Eq(im(z), 0), Gt(re(z), 0))), (2, True))
x = Symbol('x')
assert unchanged(Piecewise, (S.Pi, re(x) < 0),
(0, Or(re(x) > 0, Ne(im(x), 0))),
(S.NaN, True))
r = Symbol('r', real=True)
p = Piecewise((S.Pi, re(r) < 0),
(0, Or(re(r) > 0, Ne(im(r), 0))),
(S.NaN, True))
assert p == Piecewise((S.Pi, r < 0),
(0, r > 0),
(S.NaN, True), evaluate=False)
# Does not work since imaginary != 0...
#i = Symbol('i', imaginary=True)
#p = Piecewise((S.Pi, re(i) < 0),
# (0, Or(re(i) > 0, Ne(im(i), 0))),
# (S.NaN, True))
#assert p == Piecewise((0, Ne(im(i), 0)),
# (S.NaN, True), evaluate=False)
i = I*r
p = Piecewise((S.Pi, re(i) < 0),
(0, Or(re(i) > 0, Ne(im(i), 0))),
(S.NaN, True))
assert p == Piecewise((0, Ne(im(i), 0)),
(S.NaN, True), evaluate=False)
assert p == Piecewise((0, Ne(r, 0)),
(S.NaN, True), evaluate=False)
def test_eval_rewrite_as_KroneckerDelta():
x, y, z, n, t, m = symbols('x y z n t m')
K = KroneckerDelta
f = lambda p: expand(p.rewrite(K))
p1 = Piecewise((0, Eq(x, y)), (1, True))
assert f(p1) == 1 - K(x, y)
p2 = Piecewise((x, Eq(y,0)), (z, Eq(t,0)), (n, True))
assert f(p2) == n*K(0, t)*K(0, y) - n*K(0, t) - n*K(0, y) + n + \
x*K(0, y) - z*K(0, t)*K(0, y) + z*K(0, t)
p3 = Piecewise((1, Ne(x, y)), (0, True))
assert f(p3) == 1 - K(x, y)
p4 = Piecewise((1, Eq(x, 3)), (4, True), (5, True))
assert f(p4) == 4 - 3*K(3, x)
p5 = Piecewise((3, Ne(x, 2)), (4, Eq(y, 2)), (5, True))
assert f(p5) == -K(2, x)*K(2, y) + 2*K(2, x) + 3
p6 = Piecewise((0, Ne(x, 1) & Ne(y, 4)), (1, True))
assert f(p6) == -K(1, x)*K(4, y) + K(1, x) + K(4, y)
p7 = Piecewise((2, Eq(y, 3) & Ne(x, 2)), (1, True))
assert f(p7) == -K(2, x)*K(3, y) + K(3, y) + 1
p8 = Piecewise((4, Eq(x, 3) & Ne(y, 2)), (1, True))
assert f(p8) == -3*K(2, y)*K(3, x) + 3*K(3, x) + 1
p9 = Piecewise((6, Eq(x, 4) & Eq(y, 1)), (1, True))
assert f(p9) == 5 * K(1, y) * K(4, x) + 1
p10 = Piecewise((4, Ne(x, -4) | Ne(y, 1)), (1, True))
assert f(p10) == -3 * K(-4, x) * K(1, y) + 4
p11 = Piecewise((1, Eq(y, 2) | Ne(x, -3)), (2, True))
assert f(p11) == -K(-3, x)*K(2, y) + K(-3, x) + 1
p12 = Piecewise((-1, Eq(x, 1) | Ne(y, 3)), (1, True))
assert f(p12) == -2*K(1, x)*K(3, y) + 2*K(3, y) - 1
p13 = Piecewise((3, Eq(x, 2) | Eq(y, 4)), (1, True))
assert f(p13) == -2*K(2, x)*K(4, y) + 2*K(2, x) + 2*K(4, y) + 1
p14 = Piecewise((1, Ne(x, 0) | Ne(y, 1)), (3, True))
assert f(p14) == 2 * K(0, x) * K(1, y) + 1
p15 = Piecewise((2, Eq(x, 3) | Ne(y, 2)), (3, Eq(x, 4) & Eq(y, 5)), (1, True))
assert f(p15) == -2*K(2, y)*K(3, x)*K(4, x)*K(5, y) + K(2, y)*K(3, x) + \
2*K(2, y)*K(4, x)*K(5, y) - K(2, y) + 2
p16 = Piecewise((0, Ne(m, n)), (1, True))*Piecewise((0, Ne(n, t)), (1, True))\
*Piecewise((0, Ne(n, x)), (1, True)) - Piecewise((0, Ne(t, x)), (1, True))
assert f(p16) == K(m, n)*K(n, t)*K(n, x) - K(t, x)
p17 = Piecewise((0, Ne(t, x) & (Ne(m, n) | Ne(n, t) | Ne(n, x))),
(1, Ne(t, x)), (-1, Ne(m, n) | Ne(n, t) | Ne(n, x)), (0, True))
assert f(p17) == K(m, n)*K(n, t)*K(n, x) - K(t, x)
p18 = Piecewise((-4, Eq(y, 1) | (Eq(x, -5) & Eq(x, z))), (4, True))
assert f(p18) == 8*K(-5, x)*K(1, y)*K(x, z) - 8*K(-5, x)*K(x, z) - 8*K(1, y) + 4
p19 = Piecewise((0, x > 2), (1, True))
assert f(p19) == p19
p20 = Piecewise((0, And(x < 2, x > -5)), (1, True))
assert f(p20) == p20
p21 = Piecewise((0, Or(x > 1, x < 0)), (1, True))
assert f(p21) == p21
p22 = Piecewise((0, ~((Eq(y, -1) | Ne(x, 0)) & (Ne(x, 1) | Ne(y, -1)))), (1, True))
assert f(p22) == K(-1, y)*K(0, x) - K(-1, y)*K(1, x) - K(0, x) + 1
@slow
def test_identical_conds_issue():
from sympy.stats import Uniform, density
u1 = Uniform('u1', 0, 1)
u2 = Uniform('u2', 0, 1)
# Result is quite big, so not really important here (and should ideally be
# simpler). Should not give an exception though.
density(u1 + u2)
def test_issue_7370():
f = Piecewise((1, x <= 2400))
v = integrate(f, (x, 0, Float("252.4", 30)))
assert str(v) == '252.400000000000000000000000000'
def test_issue_16715():
raises(NotImplementedError, lambda: Piecewise((x, x<0), (0, y>1)).as_expr_set_pairs())
def test_issue_20360():
t, tau = symbols("t tau", real=True)
n = symbols("n", integer=True)
lam = pi * (n - S.Half)
eq = integrate(exp(lam * tau), (tau, 0, t))
assert simplify(eq) == (2*exp(pi*t*(2*n - 1)/2) - 2)/(pi*(2*n - 1))
|
c6c467b8005155e63c0a38dd9c7eabb817ad8d70cb41cda0c96ef785ae2dd28f | import itertools as it
from sympy.core.expr import unchanged
from sympy.core.function import Function
from sympy.core.numbers import I, oo, Rational
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.external import import_module
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.integers import floor, ceiling
from sympy.functions.elementary.miscellaneous import (sqrt, cbrt, root, Min,
Max, real_root)
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.functions.special.delta_functions import Heaviside
from sympy.utilities.lambdify import lambdify
from sympy.testing.pytest import raises, skip, ignore_warnings
def test_Min():
from sympy.abc import x, y, z
n = Symbol('n', negative=True)
n_ = Symbol('n_', negative=True)
nn = Symbol('nn', nonnegative=True)
nn_ = Symbol('nn_', nonnegative=True)
p = Symbol('p', positive=True)
p_ = Symbol('p_', positive=True)
np = Symbol('np', nonpositive=True)
np_ = Symbol('np_', nonpositive=True)
r = Symbol('r', real=True)
assert Min(5, 4) == 4
assert Min(-oo, -oo) is -oo
assert Min(-oo, n) is -oo
assert Min(n, -oo) is -oo
assert Min(-oo, np) is -oo
assert Min(np, -oo) is -oo
assert Min(-oo, 0) is -oo
assert Min(0, -oo) is -oo
assert Min(-oo, nn) is -oo
assert Min(nn, -oo) is -oo
assert Min(-oo, p) is -oo
assert Min(p, -oo) is -oo
assert Min(-oo, oo) is -oo
assert Min(oo, -oo) is -oo
assert Min(n, n) == n
assert unchanged(Min, n, np)
assert Min(np, n) == Min(n, np)
assert Min(n, 0) == n
assert Min(0, n) == n
assert Min(n, nn) == n
assert Min(nn, n) == n
assert Min(n, p) == n
assert Min(p, n) == n
assert Min(n, oo) == n
assert Min(oo, n) == n
assert Min(np, np) == np
assert Min(np, 0) == np
assert Min(0, np) == np
assert Min(np, nn) == np
assert Min(nn, np) == np
assert Min(np, p) == np
assert Min(p, np) == np
assert Min(np, oo) == np
assert Min(oo, np) == np
assert Min(0, 0) == 0
assert Min(0, nn) == 0
assert Min(nn, 0) == 0
assert Min(0, p) == 0
assert Min(p, 0) == 0
assert Min(0, oo) == 0
assert Min(oo, 0) == 0
assert Min(nn, nn) == nn
assert unchanged(Min, nn, p)
assert Min(p, nn) == Min(nn, p)
assert Min(nn, oo) == nn
assert Min(oo, nn) == nn
assert Min(p, p) == p
assert Min(p, oo) == p
assert Min(oo, p) == p
assert Min(oo, oo) is oo
assert Min(n, n_).func is Min
assert Min(nn, nn_).func is Min
assert Min(np, np_).func is Min
assert Min(p, p_).func is Min
# lists
assert Min() is S.Infinity
assert Min(x) == x
assert Min(x, y) == Min(y, x)
assert Min(x, y, z) == Min(z, y, x)
assert Min(x, Min(y, z)) == Min(z, y, x)
assert Min(x, Max(y, -oo)) == Min(x, y)
assert Min(p, oo, n, p, p, p_) == n
assert Min(p_, n_, p) == n_
assert Min(n, oo, -7, p, p, 2) == Min(n, -7)
assert Min(2, x, p, n, oo, n_, p, 2, -2, -2) == Min(-2, x, n, n_)
assert Min(0, x, 1, y) == Min(0, x, y)
assert Min(1000, 100, -100, x, p, n) == Min(n, x, -100)
assert unchanged(Min, sin(x), cos(x))
assert Min(sin(x), cos(x)) == Min(cos(x), sin(x))
assert Min(cos(x), sin(x)).subs(x, 1) == cos(1)
assert Min(cos(x), sin(x)).subs(x, S.Half) == sin(S.Half)
raises(ValueError, lambda: Min(cos(x), sin(x)).subs(x, I))
raises(ValueError, lambda: Min(I))
raises(ValueError, lambda: Min(I, x))
raises(ValueError, lambda: Min(S.ComplexInfinity, x))
assert Min(1, x).diff(x) == Heaviside(1 - x)
assert Min(x, 1).diff(x) == Heaviside(1 - x)
assert Min(0, -x, 1 - 2*x).diff(x) == -Heaviside(x + Min(0, -2*x + 1)) \
- 2*Heaviside(2*x + Min(0, -x) - 1)
# issue 7619
f = Function('f')
assert Min(1, 2*Min(f(1), 2)) # doesn't fail
# issue 7233
e = Min(0, x)
assert e.n().args == (0, x)
# issue 8643
m = Min(n, p_, n_, r)
assert m.is_positive is False
assert m.is_nonnegative is False
assert m.is_negative is True
m = Min(p, p_)
assert m.is_positive is True
assert m.is_nonnegative is True
assert m.is_negative is False
m = Min(p, nn_, p_)
assert m.is_positive is None
assert m.is_nonnegative is True
assert m.is_negative is False
m = Min(nn, p, r)
assert m.is_positive is None
assert m.is_nonnegative is None
assert m.is_negative is None
def test_Max():
from sympy.abc import x, y, z
n = Symbol('n', negative=True)
n_ = Symbol('n_', negative=True)
nn = Symbol('nn', nonnegative=True)
p = Symbol('p', positive=True)
p_ = Symbol('p_', positive=True)
r = Symbol('r', real=True)
assert Max(5, 4) == 5
# lists
assert Max() is S.NegativeInfinity
assert Max(x) == x
assert Max(x, y) == Max(y, x)
assert Max(x, y, z) == Max(z, y, x)
assert Max(x, Max(y, z)) == Max(z, y, x)
assert Max(x, Min(y, oo)) == Max(x, y)
assert Max(n, -oo, n_, p, 2) == Max(p, 2)
assert Max(n, -oo, n_, p) == p
assert Max(2, x, p, n, -oo, S.NegativeInfinity, n_, p, 2) == Max(2, x, p)
assert Max(0, x, 1, y) == Max(1, x, y)
assert Max(r, r + 1, r - 1) == 1 + r
assert Max(1000, 100, -100, x, p, n) == Max(p, x, 1000)
assert Max(cos(x), sin(x)) == Max(sin(x), cos(x))
assert Max(cos(x), sin(x)).subs(x, 1) == sin(1)
assert Max(cos(x), sin(x)).subs(x, S.Half) == cos(S.Half)
raises(ValueError, lambda: Max(cos(x), sin(x)).subs(x, I))
raises(ValueError, lambda: Max(I))
raises(ValueError, lambda: Max(I, x))
raises(ValueError, lambda: Max(S.ComplexInfinity, 1))
assert Max(n, -oo, n_, p, 2) == Max(p, 2)
assert Max(n, -oo, n_, p, 1000) == Max(p, 1000)
assert Max(1, x).diff(x) == Heaviside(x - 1)
assert Max(x, 1).diff(x) == Heaviside(x - 1)
assert Max(x**2, 1 + x, 1).diff(x) == \
2*x*Heaviside(x**2 - Max(1, x + 1)) \
+ Heaviside(x - Max(1, x**2) + 1)
e = Max(0, x)
assert e.n().args == (0, x)
# issue 8643
m = Max(p, p_, n, r)
assert m.is_positive is True
assert m.is_nonnegative is True
assert m.is_negative is False
m = Max(n, n_)
assert m.is_positive is False
assert m.is_nonnegative is False
assert m.is_negative is True
m = Max(n, n_, r)
assert m.is_positive is None
assert m.is_nonnegative is None
assert m.is_negative is None
m = Max(n, nn, r)
assert m.is_positive is None
assert m.is_nonnegative is True
assert m.is_negative is False
def test_minmax_assumptions():
r = Symbol('r', real=True)
a = Symbol('a', real=True, algebraic=True)
t = Symbol('t', real=True, transcendental=True)
q = Symbol('q', rational=True)
p = Symbol('p', irrational=True)
n = Symbol('n', rational=True, integer=False)
i = Symbol('i', integer=True)
o = Symbol('o', odd=True)
e = Symbol('e', even=True)
k = Symbol('k', prime=True)
reals = [r, a, t, q, p, n, i, o, e, k]
for ext in (Max, Min):
for x, y in it.product(reals, repeat=2):
# Must be real
assert ext(x, y).is_real
# Algebraic?
if x.is_algebraic and y.is_algebraic:
assert ext(x, y).is_algebraic
elif x.is_transcendental and y.is_transcendental:
assert ext(x, y).is_transcendental
else:
assert ext(x, y).is_algebraic is None
# Rational?
if x.is_rational and y.is_rational:
assert ext(x, y).is_rational
elif x.is_irrational and y.is_irrational:
assert ext(x, y).is_irrational
else:
assert ext(x, y).is_rational is None
# Integer?
if x.is_integer and y.is_integer:
assert ext(x, y).is_integer
elif x.is_noninteger and y.is_noninteger:
assert ext(x, y).is_noninteger
else:
assert ext(x, y).is_integer is None
# Odd?
if x.is_odd and y.is_odd:
assert ext(x, y).is_odd
elif x.is_odd is False and y.is_odd is False:
assert ext(x, y).is_odd is False
else:
assert ext(x, y).is_odd is None
# Even?
if x.is_even and y.is_even:
assert ext(x, y).is_even
elif x.is_even is False and y.is_even is False:
assert ext(x, y).is_even is False
else:
assert ext(x, y).is_even is None
# Prime?
if x.is_prime and y.is_prime:
assert ext(x, y).is_prime
elif x.is_prime is False and y.is_prime is False:
assert ext(x, y).is_prime is False
else:
assert ext(x, y).is_prime is None
def test_issue_8413():
x = Symbol('x', real=True)
# we can't evaluate in general because non-reals are not
# comparable: Min(floor(3.2 + I), 3.2 + I) -> ValueError
assert Min(floor(x), x) == floor(x)
assert Min(ceiling(x), x) == x
assert Max(floor(x), x) == x
assert Max(ceiling(x), x) == ceiling(x)
def test_root():
from sympy.abc import x
n = Symbol('n', integer=True)
k = Symbol('k', integer=True)
assert root(2, 2) == sqrt(2)
assert root(2, 1) == 2
assert root(2, 3) == 2**Rational(1, 3)
assert root(2, 3) == cbrt(2)
assert root(2, -5) == 2**Rational(4, 5)/2
assert root(-2, 1) == -2
assert root(-2, 2) == sqrt(2)*I
assert root(-2, 1) == -2
assert root(x, 2) == sqrt(x)
assert root(x, 1) == x
assert root(x, 3) == x**Rational(1, 3)
assert root(x, 3) == cbrt(x)
assert root(x, -5) == x**Rational(-1, 5)
assert root(x, n) == x**(1/n)
assert root(x, -n) == x**(-1/n)
assert root(x, n, k) == (-1)**(2*k/n)*x**(1/n)
def test_real_root():
assert real_root(-8, 3) == -2
assert real_root(-16, 4) == root(-16, 4)
r = root(-7, 4)
assert real_root(r) == r
r1 = root(-1, 3)
r2 = r1**2
r3 = root(-1, 4)
assert real_root(r1 + r2 + r3) == -1 + r2 + r3
assert real_root(root(-2, 3)) == -root(2, 3)
assert real_root(-8., 3) == -2
x = Symbol('x')
n = Symbol('n')
g = real_root(x, n)
assert g.subs(dict(x=-8, n=3)) == -2
assert g.subs(dict(x=8, n=3)) == 2
# give principle root if there is no real root -- if this is not desired
# then maybe a Root class is needed to raise an error instead
assert g.subs(dict(x=I, n=3)) == cbrt(I)
assert g.subs(dict(x=-8, n=2)) == sqrt(-8)
assert g.subs(dict(x=I, n=2)) == sqrt(I)
def test_issue_11463():
numpy = import_module('numpy')
if not numpy:
skip("numpy not installed.")
x = Symbol('x')
f = lambdify(x, real_root((log(x/(x-2))), 3), 'numpy')
# numpy.select evaluates all options before considering conditions,
# so it raises a warning about root of negative number which does
# not affect the outcome. This warning is suppressed here
with ignore_warnings(RuntimeWarning):
assert f(numpy.array(-1)) < -1
def test_rewrite_MaxMin_as_Heaviside():
from sympy.abc import x
assert Max(0, x).rewrite(Heaviside) == x*Heaviside(x)
assert Max(3, x).rewrite(Heaviside) == x*Heaviside(x - 3) + \
3*Heaviside(-x + 3)
assert Max(0, x+2, 2*x).rewrite(Heaviside) == \
2*x*Heaviside(2*x)*Heaviside(x - 2) + \
(x + 2)*Heaviside(-x + 2)*Heaviside(x + 2)
assert Min(0, x).rewrite(Heaviside) == x*Heaviside(-x)
assert Min(3, x).rewrite(Heaviside) == x*Heaviside(-x + 3) + \
3*Heaviside(x - 3)
assert Min(x, -x, -2).rewrite(Heaviside) == \
x*Heaviside(-2*x)*Heaviside(-x - 2) - \
x*Heaviside(2*x)*Heaviside(x - 2) \
- 2*Heaviside(-x + 2)*Heaviside(x + 2)
def test_rewrite_MaxMin_as_Piecewise():
from sympy import symbols, Piecewise
x, y, z, a, b = symbols('x y z a b', real=True)
vx, vy, va = symbols('vx vy va')
assert Max(a, b).rewrite(Piecewise) == Piecewise((a, a >= b), (b, True))
assert Max(x, y, z).rewrite(Piecewise) == Piecewise((x, (x >= y) & (x >= z)), (y, y >= z), (z, True))
assert Max(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a >= b) & (a >= x) & (a >= y)),
(b, (b >= x) & (b >= y)), (x, x >= y), (y, True))
assert Min(a, b).rewrite(Piecewise) == Piecewise((a, a <= b), (b, True))
assert Min(x, y, z).rewrite(Piecewise) == Piecewise((x, (x <= y) & (x <= z)), (y, y <= z), (z, True))
assert Min(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a <= b) & (a <= x) & (a <= y)),
(b, (b <= x) & (b <= y)), (x, x <= y), (y, True))
# Piecewise rewriting of Min/Max does also takes place for not explicitly real arguments
assert Max(vx, vy).rewrite(Piecewise) == Piecewise((vx, vx >= vy), (vy, True))
assert Min(va, vx, vy).rewrite(Piecewise) == Piecewise((va, (va <= vx) & (va <= vy)), (vx, vx <= vy), (vy, True))
def test_issue_11099():
from sympy.abc import x, y
# some fixed value tests
fixed_test_data = {x: -2, y: 3}
assert Min(x, y).evalf(subs=fixed_test_data) == \
Min(x, y).subs(fixed_test_data).evalf()
assert Max(x, y).evalf(subs=fixed_test_data) == \
Max(x, y).subs(fixed_test_data).evalf()
# randomly generate some test data
from random import randint
for i in range(20):
random_test_data = {x: randint(-100, 100), y: randint(-100, 100)}
assert Min(x, y).evalf(subs=random_test_data) == \
Min(x, y).subs(random_test_data).evalf()
assert Max(x, y).evalf(subs=random_test_data) == \
Max(x, y).subs(random_test_data).evalf()
def test_issue_12638():
from sympy.abc import a, b, c
assert Min(a, b, c, Max(a, b)) == Min(a, b, c)
assert Min(a, b, Max(a, b, c)) == Min(a, b)
assert Min(a, b, Max(a, c)) == Min(a, b)
def test_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
|
e40daf44bea59797d0583ac449fc528abb95c623d7b75d01b35ac28966f5711f | from sympy import (symbols, Symbol, sinh, nan, oo, zoo, pi, asinh, acosh, log,
sqrt, coth, I, cot, E, tanh, tan, cosh, cos, S, sin, Rational, atanh, acoth,
Integer, O, exp, sech, sec, csch, asech, acsch, acos, asin, expand_mul,
AccumBounds, im, re, expand_trig)
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
from sympy.testing.pytest import raises
def test_sinh():
x, y = symbols('x,y')
k = Symbol('k', integer=True)
assert sinh(nan) is nan
assert sinh(zoo) is nan
assert sinh(oo) is oo
assert sinh(-oo) is -oo
assert sinh(0) == 0
assert unchanged(sinh, 1)
assert sinh(-1) == -sinh(1)
assert unchanged(sinh, x)
assert sinh(-x) == -sinh(x)
assert unchanged(sinh, pi)
assert sinh(-pi) == -sinh(pi)
assert unchanged(sinh, 2**1024 * E)
assert sinh(-2**1024 * E) == -sinh(2**1024 * E)
assert sinh(pi*I) == 0
assert sinh(-pi*I) == 0
assert sinh(2*pi*I) == 0
assert sinh(-2*pi*I) == 0
assert sinh(-3*10**73*pi*I) == 0
assert sinh(7*10**103*pi*I) == 0
assert sinh(pi*I/2) == I
assert sinh(-pi*I/2) == -I
assert sinh(pi*I*Rational(5, 2)) == I
assert sinh(pi*I*Rational(7, 2)) == -I
assert sinh(pi*I/3) == S.Half*sqrt(3)*I
assert sinh(pi*I*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)*I
assert sinh(pi*I/4) == S.Half*sqrt(2)*I
assert sinh(-pi*I/4) == Rational(-1, 2)*sqrt(2)*I
assert sinh(pi*I*Rational(17, 4)) == S.Half*sqrt(2)*I
assert sinh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)*I
assert sinh(pi*I/6) == S.Half*I
assert sinh(-pi*I/6) == Rational(-1, 2)*I
assert sinh(pi*I*Rational(7, 6)) == Rational(-1, 2)*I
assert sinh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*I
assert sinh(pi*I/105) == sin(pi/105)*I
assert sinh(-pi*I/105) == -sin(pi/105)*I
assert unchanged(sinh, 2 + 3*I)
assert sinh(x*I) == sin(x)*I
assert sinh(k*pi*I) == 0
assert sinh(17*k*pi*I) == 0
assert sinh(k*pi*I/2) == sin(k*pi/2)*I
assert sinh(x).as_real_imag(deep=False) == (cos(im(x))*sinh(re(x)),
sin(im(x))*cosh(re(x)))
x = Symbol('x', extended_real=True)
assert sinh(x).as_real_imag(deep=False) == (sinh(x), 0)
x = Symbol('x', real=True)
assert sinh(I*x).is_finite is True
assert sinh(x).is_real is True
assert sinh(I).is_real is False
def test_sinh_series():
x = Symbol('x')
assert sinh(x).series(x, 0, 10) == \
x + x**3/6 + x**5/120 + x**7/5040 + x**9/362880 + O(x**10)
def test_sinh_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: sinh(x).fdiff(2))
def test_cosh():
x, y = symbols('x,y')
k = Symbol('k', integer=True)
assert cosh(nan) is nan
assert cosh(zoo) is nan
assert cosh(oo) is oo
assert cosh(-oo) is oo
assert cosh(0) == 1
assert unchanged(cosh, 1)
assert cosh(-1) == cosh(1)
assert unchanged(cosh, x)
assert cosh(-x) == cosh(x)
assert cosh(pi*I) == cos(pi)
assert cosh(-pi*I) == cos(pi)
assert unchanged(cosh, 2**1024 * E)
assert cosh(-2**1024 * E) == cosh(2**1024 * E)
assert cosh(pi*I/2) == 0
assert cosh(-pi*I/2) == 0
assert cosh((-3*10**73 + 1)*pi*I/2) == 0
assert cosh((7*10**103 + 1)*pi*I/2) == 0
assert cosh(pi*I) == -1
assert cosh(-pi*I) == -1
assert cosh(5*pi*I) == -1
assert cosh(8*pi*I) == 1
assert cosh(pi*I/3) == S.Half
assert cosh(pi*I*Rational(-2, 3)) == Rational(-1, 2)
assert cosh(pi*I/4) == S.Half*sqrt(2)
assert cosh(-pi*I/4) == S.Half*sqrt(2)
assert cosh(pi*I*Rational(11, 4)) == Rational(-1, 2)*sqrt(2)
assert cosh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
assert cosh(pi*I/6) == S.Half*sqrt(3)
assert cosh(-pi*I/6) == S.Half*sqrt(3)
assert cosh(pi*I*Rational(7, 6)) == Rational(-1, 2)*sqrt(3)
assert cosh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3)
assert cosh(pi*I/105) == cos(pi/105)
assert cosh(-pi*I/105) == cos(pi/105)
assert unchanged(cosh, 2 + 3*I)
assert cosh(x*I) == cos(x)
assert cosh(k*pi*I) == cos(k*pi)
assert cosh(17*k*pi*I) == cos(17*k*pi)
assert unchanged(cosh, k*pi)
assert cosh(x).as_real_imag(deep=False) == (cos(im(x))*cosh(re(x)),
sin(im(x))*sinh(re(x)))
x = Symbol('x', extended_real=True)
assert cosh(x).as_real_imag(deep=False) == (cosh(x), 0)
x = Symbol('x', real=True)
assert cosh(I*x).is_finite is True
assert cosh(I*x).is_real is True
assert cosh(I*2 + 1).is_real is False
def test_cosh_series():
x = Symbol('x')
assert cosh(x).series(x, 0, 10) == \
1 + x**2/2 + x**4/24 + x**6/720 + x**8/40320 + O(x**10)
def test_cosh_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: cosh(x).fdiff(2))
def test_tanh():
x, y = symbols('x,y')
k = Symbol('k', integer=True)
assert tanh(nan) is nan
assert tanh(zoo) is nan
assert tanh(oo) == 1
assert tanh(-oo) == -1
assert tanh(0) == 0
assert unchanged(tanh, 1)
assert tanh(-1) == -tanh(1)
assert unchanged(tanh, x)
assert tanh(-x) == -tanh(x)
assert unchanged(tanh, pi)
assert tanh(-pi) == -tanh(pi)
assert unchanged(tanh, 2**1024 * E)
assert tanh(-2**1024 * E) == -tanh(2**1024 * E)
assert tanh(pi*I) == 0
assert tanh(-pi*I) == 0
assert tanh(2*pi*I) == 0
assert tanh(-2*pi*I) == 0
assert tanh(-3*10**73*pi*I) == 0
assert tanh(7*10**103*pi*I) == 0
assert tanh(pi*I/2) is zoo
assert tanh(-pi*I/2) is zoo
assert tanh(pi*I*Rational(5, 2)) is zoo
assert tanh(pi*I*Rational(7, 2)) is zoo
assert tanh(pi*I/3) == sqrt(3)*I
assert tanh(pi*I*Rational(-2, 3)) == sqrt(3)*I
assert tanh(pi*I/4) == I
assert tanh(-pi*I/4) == -I
assert tanh(pi*I*Rational(17, 4)) == I
assert tanh(pi*I*Rational(-3, 4)) == I
assert tanh(pi*I/6) == I/sqrt(3)
assert tanh(-pi*I/6) == -I/sqrt(3)
assert tanh(pi*I*Rational(7, 6)) == I/sqrt(3)
assert tanh(pi*I*Rational(-5, 6)) == I/sqrt(3)
assert tanh(pi*I/105) == tan(pi/105)*I
assert tanh(-pi*I/105) == -tan(pi/105)*I
assert unchanged(tanh, 2 + 3*I)
assert tanh(x*I) == tan(x)*I
assert tanh(k*pi*I) == 0
assert tanh(17*k*pi*I) == 0
assert tanh(k*pi*I/2) == tan(k*pi/2)*I
assert tanh(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(cos(im(x))**2
+ sinh(re(x))**2),
sin(im(x))*cos(im(x))/(cos(im(x))**2 + sinh(re(x))**2))
x = Symbol('x', extended_real=True)
assert tanh(x).as_real_imag(deep=False) == (tanh(x), 0)
assert tanh(I*pi/3 + 1).is_real is False
assert tanh(x).is_real is True
assert tanh(I*pi*x/2).is_real is None
def test_tanh_series():
x = Symbol('x')
assert tanh(x).series(x, 0, 10) == \
x - x**3/3 + 2*x**5/15 - 17*x**7/315 + 62*x**9/2835 + O(x**10)
def test_tanh_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: tanh(x).fdiff(2))
def test_coth():
x, y = symbols('x,y')
k = Symbol('k', integer=True)
assert coth(nan) is nan
assert coth(zoo) is nan
assert coth(oo) == 1
assert coth(-oo) == -1
assert coth(0) is zoo
assert unchanged(coth, 1)
assert coth(-1) == -coth(1)
assert unchanged(coth, x)
assert coth(-x) == -coth(x)
assert coth(pi*I) == -I*cot(pi)
assert coth(-pi*I) == cot(pi)*I
assert unchanged(coth, 2**1024 * E)
assert coth(-2**1024 * E) == -coth(2**1024 * E)
assert coth(pi*I) == -I*cot(pi)
assert coth(-pi*I) == I*cot(pi)
assert coth(2*pi*I) == -I*cot(2*pi)
assert coth(-2*pi*I) == I*cot(2*pi)
assert coth(-3*10**73*pi*I) == I*cot(3*10**73*pi)
assert coth(7*10**103*pi*I) == -I*cot(7*10**103*pi)
assert coth(pi*I/2) == 0
assert coth(-pi*I/2) == 0
assert coth(pi*I*Rational(5, 2)) == 0
assert coth(pi*I*Rational(7, 2)) == 0
assert coth(pi*I/3) == -I/sqrt(3)
assert coth(pi*I*Rational(-2, 3)) == -I/sqrt(3)
assert coth(pi*I/4) == -I
assert coth(-pi*I/4) == I
assert coth(pi*I*Rational(17, 4)) == -I
assert coth(pi*I*Rational(-3, 4)) == -I
assert coth(pi*I/6) == -sqrt(3)*I
assert coth(-pi*I/6) == sqrt(3)*I
assert coth(pi*I*Rational(7, 6)) == -sqrt(3)*I
assert coth(pi*I*Rational(-5, 6)) == -sqrt(3)*I
assert coth(pi*I/105) == -cot(pi/105)*I
assert coth(-pi*I/105) == cot(pi/105)*I
assert unchanged(coth, 2 + 3*I)
assert coth(x*I) == -cot(x)*I
assert coth(k*pi*I) == -cot(k*pi)*I
assert coth(17*k*pi*I) == -cot(17*k*pi)*I
assert coth(k*pi*I) == -cot(k*pi)*I
assert coth(log(tan(2))) == coth(log(-tan(2)))
assert coth(1 + I*pi/2) == tanh(1)
assert coth(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(sin(im(x))**2
+ sinh(re(x))**2),
-sin(im(x))*cos(im(x))/(sin(im(x))**2 + sinh(re(x))**2))
x = Symbol('x', extended_real=True)
assert coth(x).as_real_imag(deep=False) == (coth(x), 0)
assert expand_trig(coth(2*x)) == (coth(x)**2 + 1)/(2*coth(x))
assert expand_trig(coth(3*x)) == (coth(x)**3 + 3*coth(x))/(1 + 3*coth(x)**2)
assert expand_trig(coth(x + y)) == (1 + coth(x)*coth(y))/(coth(x) + coth(y))
def test_coth_series():
x = Symbol('x')
assert coth(x).series(x, 0, 8) == \
1/x + x/3 - x**3/45 + 2*x**5/945 - x**7/4725 + O(x**8)
def test_coth_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: coth(x).fdiff(2))
def test_csch():
x, y = symbols('x,y')
k = Symbol('k', integer=True)
n = Symbol('n', positive=True)
assert csch(nan) is nan
assert csch(zoo) is nan
assert csch(oo) == 0
assert csch(-oo) == 0
assert csch(0) is zoo
assert csch(-1) == -csch(1)
assert csch(-x) == -csch(x)
assert csch(-pi) == -csch(pi)
assert csch(-2**1024 * E) == -csch(2**1024 * E)
assert csch(pi*I) is zoo
assert csch(-pi*I) is zoo
assert csch(2*pi*I) is zoo
assert csch(-2*pi*I) is zoo
assert csch(-3*10**73*pi*I) is zoo
assert csch(7*10**103*pi*I) is zoo
assert csch(pi*I/2) == -I
assert csch(-pi*I/2) == I
assert csch(pi*I*Rational(5, 2)) == -I
assert csch(pi*I*Rational(7, 2)) == I
assert csch(pi*I/3) == -2/sqrt(3)*I
assert csch(pi*I*Rational(-2, 3)) == 2/sqrt(3)*I
assert csch(pi*I/4) == -sqrt(2)*I
assert csch(-pi*I/4) == sqrt(2)*I
assert csch(pi*I*Rational(7, 4)) == sqrt(2)*I
assert csch(pi*I*Rational(-3, 4)) == sqrt(2)*I
assert csch(pi*I/6) == -2*I
assert csch(-pi*I/6) == 2*I
assert csch(pi*I*Rational(7, 6)) == 2*I
assert csch(pi*I*Rational(-7, 6)) == -2*I
assert csch(pi*I*Rational(-5, 6)) == 2*I
assert csch(pi*I/105) == -1/sin(pi/105)*I
assert csch(-pi*I/105) == 1/sin(pi/105)*I
assert csch(x*I) == -1/sin(x)*I
assert csch(k*pi*I) is zoo
assert csch(17*k*pi*I) is zoo
assert csch(k*pi*I/2) == -1/sin(k*pi/2)*I
assert csch(n).is_real is True
assert expand_trig(csch(x + y)) == 1/(sinh(x)*cosh(y) + cosh(x)*sinh(y))
def test_csch_series():
x = Symbol('x')
assert csch(x).series(x, 0, 10) == \
1/ x - x/6 + 7*x**3/360 - 31*x**5/15120 + 127*x**7/604800 \
- 73*x**9/3421440 + O(x**10)
def test_csch_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: csch(x).fdiff(2))
def test_sech():
x, y = symbols('x, y')
k = Symbol('k', integer=True)
n = Symbol('n', positive=True)
assert sech(nan) is nan
assert sech(zoo) is nan
assert sech(oo) == 0
assert sech(-oo) == 0
assert sech(0) == 1
assert sech(-1) == sech(1)
assert sech(-x) == sech(x)
assert sech(pi*I) == sec(pi)
assert sech(-pi*I) == sec(pi)
assert sech(-2**1024 * E) == sech(2**1024 * E)
assert sech(pi*I/2) is zoo
assert sech(-pi*I/2) is zoo
assert sech((-3*10**73 + 1)*pi*I/2) is zoo
assert sech((7*10**103 + 1)*pi*I/2) is zoo
assert sech(pi*I) == -1
assert sech(-pi*I) == -1
assert sech(5*pi*I) == -1
assert sech(8*pi*I) == 1
assert sech(pi*I/3) == 2
assert sech(pi*I*Rational(-2, 3)) == -2
assert sech(pi*I/4) == sqrt(2)
assert sech(-pi*I/4) == sqrt(2)
assert sech(pi*I*Rational(5, 4)) == -sqrt(2)
assert sech(pi*I*Rational(-5, 4)) == -sqrt(2)
assert sech(pi*I/6) == 2/sqrt(3)
assert sech(-pi*I/6) == 2/sqrt(3)
assert sech(pi*I*Rational(7, 6)) == -2/sqrt(3)
assert sech(pi*I*Rational(-5, 6)) == -2/sqrt(3)
assert sech(pi*I/105) == 1/cos(pi/105)
assert sech(-pi*I/105) == 1/cos(pi/105)
assert sech(x*I) == 1/cos(x)
assert sech(k*pi*I) == 1/cos(k*pi)
assert sech(17*k*pi*I) == 1/cos(17*k*pi)
assert sech(n).is_real is True
assert expand_trig(sech(x + y)) == 1/(cosh(x)*cosh(y) + sinh(x)*sinh(y))
def test_sech_series():
x = Symbol('x')
assert sech(x).series(x, 0, 10) == \
1 - x**2/2 + 5*x**4/24 - 61*x**6/720 + 277*x**8/8064 + O(x**10)
def test_sech_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: sech(x).fdiff(2))
def test_asinh():
x, y = symbols('x,y')
assert unchanged(asinh, x)
assert asinh(-x) == -asinh(x)
#at specific points
assert asinh(nan) is nan
assert asinh( 0) == 0
assert asinh(+1) == log(sqrt(2) + 1)
assert asinh(-1) == log(sqrt(2) - 1)
assert asinh(I) == pi*I/2
assert asinh(-I) == -pi*I/2
assert asinh(I/2) == pi*I/6
assert asinh(-I/2) == -pi*I/6
# at infinites
assert asinh(oo) is oo
assert asinh(-oo) is -oo
assert asinh(I*oo) is oo
assert asinh(-I *oo) is -oo
assert asinh(zoo) is zoo
#properties
assert asinh(I *(sqrt(3) - 1)/(2**Rational(3, 2))) == pi*I/12
assert asinh(-I *(sqrt(3) - 1)/(2**Rational(3, 2))) == -pi*I/12
assert asinh(I*(sqrt(5) - 1)/4) == pi*I/10
assert asinh(-I*(sqrt(5) - 1)/4) == -pi*I/10
assert asinh(I*(sqrt(5) + 1)/4) == pi*I*Rational(3, 10)
assert asinh(-I*(sqrt(5) + 1)/4) == pi*I*Rational(-3, 10)
# Symmetry
assert asinh(Rational(-1, 2)) == -asinh(S.Half)
# inverse composition
assert unchanged(asinh, sinh(Symbol('v1')))
assert asinh(sinh(0, evaluate=False)) == 0
assert asinh(sinh(-3, evaluate=False)) == -3
assert asinh(sinh(2, evaluate=False)) == 2
assert asinh(sinh(I, evaluate=False)) == I
assert asinh(sinh(-I, evaluate=False)) == -I
assert asinh(sinh(5*I, evaluate=False)) == -2*I*pi + 5*I
assert asinh(sinh(15 + 11*I)) == 15 - 4*I*pi + 11*I
assert asinh(sinh(-73 + 97*I)) == 73 - 97*I + 31*I*pi
assert asinh(sinh(-7 - 23*I)) == 7 - 7*I*pi + 23*I
assert asinh(sinh(13 - 3*I)) == -13 - I*pi + 3*I
def test_asinh_rewrite():
x = Symbol('x')
assert asinh(x).rewrite(log) == log(x + sqrt(x**2 + 1))
def test_asinh_series():
x = Symbol('x')
assert asinh(x).series(x, 0, 8) == \
x - x**3/6 + 3*x**5/40 - 5*x**7/112 + O(x**8)
t5 = asinh(x).taylor_term(5, x)
assert t5 == 3*x**5/40
assert asinh(x).taylor_term(7, x, t5, 0) == -5*x**7/112
def test_asinh_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: asinh(x).fdiff(2))
def test_acosh():
x = Symbol('x')
assert unchanged(acosh, -x)
#at specific points
assert acosh(1) == 0
assert acosh(-1) == pi*I
assert acosh(0) == I*pi/2
assert acosh(S.Half) == I*pi/3
assert acosh(Rational(-1, 2)) == pi*I*Rational(2, 3)
assert acosh(nan) is nan
# at infinites
assert acosh(oo) is oo
assert acosh(-oo) is oo
assert acosh(I*oo) == oo + I*pi/2
assert acosh(-I*oo) == oo - I*pi/2
assert acosh(zoo) is zoo
assert acosh(I) == log(I*(1 + sqrt(2)))
assert acosh(-I) == log(-I*(1 + sqrt(2)))
assert acosh((sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(5, 12)
assert acosh(-(sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(7, 12)
assert acosh(sqrt(2)/2) == I*pi/4
assert acosh(-sqrt(2)/2) == I*pi*Rational(3, 4)
assert acosh(sqrt(3)/2) == I*pi/6
assert acosh(-sqrt(3)/2) == I*pi*Rational(5, 6)
assert acosh(sqrt(2 + sqrt(2))/2) == I*pi/8
assert acosh(-sqrt(2 + sqrt(2))/2) == I*pi*Rational(7, 8)
assert acosh(sqrt(2 - sqrt(2))/2) == I*pi*Rational(3, 8)
assert acosh(-sqrt(2 - sqrt(2))/2) == I*pi*Rational(5, 8)
assert acosh((1 + sqrt(3))/(2*sqrt(2))) == I*pi/12
assert acosh(-(1 + sqrt(3))/(2*sqrt(2))) == I*pi*Rational(11, 12)
assert acosh((sqrt(5) + 1)/4) == I*pi/5
assert acosh(-(sqrt(5) + 1)/4) == I*pi*Rational(4, 5)
assert str(acosh(5*I).n(6)) == '2.31244 + 1.5708*I'
assert str(acosh(-5*I).n(6)) == '2.31244 - 1.5708*I'
# inverse composition
assert unchanged(acosh, Symbol('v1'))
assert acosh(cosh(-3, evaluate=False)) == 3
assert acosh(cosh(3, evaluate=False)) == 3
assert acosh(cosh(0, evaluate=False)) == 0
assert acosh(cosh(I, evaluate=False)) == I
assert acosh(cosh(-I, evaluate=False)) == I
assert acosh(cosh(7*I, evaluate=False)) == -2*I*pi + 7*I
assert acosh(cosh(1 + I)) == 1 + I
assert acosh(cosh(3 - 3*I)) == 3 - 3*I
assert acosh(cosh(-3 + 2*I)) == 3 - 2*I
assert acosh(cosh(-5 - 17*I)) == 5 - 6*I*pi + 17*I
assert acosh(cosh(-21 + 11*I)) == 21 - 11*I + 4*I*pi
assert acosh(cosh(cosh(1) + I)) == cosh(1) + I
def test_acosh_rewrite():
x = Symbol('x')
assert acosh(x).rewrite(log) == log(x + sqrt(x - 1)*sqrt(x + 1))
def test_acosh_series():
x = Symbol('x')
assert acosh(x).series(x, 0, 8) == \
-I*x + pi*I/2 - I*x**3/6 - 3*I*x**5/40 - 5*I*x**7/112 + O(x**8)
t5 = acosh(x).taylor_term(5, x)
assert t5 == - 3*I*x**5/40
assert acosh(x).taylor_term(7, x, t5, 0) == - 5*I*x**7/112
def test_acosh_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: acosh(x).fdiff(2))
def test_asech():
x = Symbol('x')
assert unchanged(asech, -x)
# values at fixed points
assert asech(1) == 0
assert asech(-1) == pi*I
assert asech(0) is oo
assert asech(2) == I*pi/3
assert asech(-2) == 2*I*pi / 3
assert asech(nan) is nan
# at infinites
assert asech(oo) == I*pi/2
assert asech(-oo) == I*pi/2
assert asech(zoo) == I*AccumBounds(-pi/2, pi/2)
assert asech(I) == log(1 + sqrt(2)) - I*pi/2
assert asech(-I) == log(1 + sqrt(2)) + I*pi/2
assert asech(sqrt(2) - sqrt(6)) == 11*I*pi / 12
assert asech(sqrt(2 - 2/sqrt(5))) == I*pi / 10
assert asech(-sqrt(2 - 2/sqrt(5))) == 9*I*pi / 10
assert asech(2 / sqrt(2 + sqrt(2))) == I*pi / 8
assert asech(-2 / sqrt(2 + sqrt(2))) == 7*I*pi / 8
assert asech(sqrt(5) - 1) == I*pi / 5
assert asech(1 - sqrt(5)) == 4*I*pi / 5
assert asech(-sqrt(2*(2 + sqrt(2)))) == 5*I*pi / 8
# properties
# asech(x) == acosh(1/x)
assert asech(sqrt(2)) == acosh(1/sqrt(2))
assert asech(2/sqrt(3)) == acosh(sqrt(3)/2)
assert asech(2/sqrt(2 + sqrt(2))) == acosh(sqrt(2 + sqrt(2))/2)
assert asech(2) == acosh(S.Half)
# asech(x) == I*acos(1/x)
# (Note: the exact formula is asech(x) == +/- I*acos(1/x))
assert asech(-sqrt(2)) == I*acos(-1/sqrt(2))
assert asech(-2/sqrt(3)) == I*acos(-sqrt(3)/2)
assert asech(-S(2)) == I*acos(Rational(-1, 2))
assert asech(-2/sqrt(2)) == I*acos(-sqrt(2)/2)
# sech(asech(x)) / x == 1
assert expand_mul(sech(asech(sqrt(6) - sqrt(2))) / (sqrt(6) - sqrt(2))) == 1
assert expand_mul(sech(asech(sqrt(6) + sqrt(2))) / (sqrt(6) + sqrt(2))) == 1
assert (sech(asech(sqrt(2 + 2/sqrt(5)))) / (sqrt(2 + 2/sqrt(5)))).simplify() == 1
assert (sech(asech(-sqrt(2 + 2/sqrt(5)))) / (-sqrt(2 + 2/sqrt(5)))).simplify() == 1
assert (sech(asech(sqrt(2*(2 + sqrt(2))))) / (sqrt(2*(2 + sqrt(2))))).simplify() == 1
assert expand_mul(sech(asech(1 + sqrt(5))) / (1 + sqrt(5))) == 1
assert expand_mul(sech(asech(-1 - sqrt(5))) / (-1 - sqrt(5))) == 1
assert expand_mul(sech(asech(-sqrt(6) - sqrt(2))) / (-sqrt(6) - sqrt(2))) == 1
# numerical evaluation
assert str(asech(5*I).n(6)) == '0.19869 - 1.5708*I'
assert str(asech(-5*I).n(6)) == '0.19869 + 1.5708*I'
def test_asech_series():
x = Symbol('x')
t6 = asech(x).expansion_term(6, x)
assert t6 == -5*x**6/96
assert asech(x).expansion_term(8, x, t6, 0) == -35*x**8/1024
def test_asech_rewrite():
x = Symbol('x')
assert asech(x).rewrite(log) == log(1/x + sqrt(1/x - 1) * sqrt(1/x + 1))
def test_asech_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: asech(x).fdiff(2))
def test_acsch():
x = Symbol('x')
assert unchanged(acsch, x)
assert acsch(-x) == -acsch(x)
# values at fixed points
assert acsch(1) == log(1 + sqrt(2))
assert acsch(-1) == - log(1 + sqrt(2))
assert acsch(0) is zoo
assert acsch(2) == log((1+sqrt(5))/2)
assert acsch(-2) == - log((1+sqrt(5))/2)
assert acsch(I) == - I*pi/2
assert acsch(-I) == I*pi/2
assert acsch(-I*(sqrt(6) + sqrt(2))) == I*pi / 12
assert acsch(I*(sqrt(2) + sqrt(6))) == -I*pi / 12
assert acsch(-I*(1 + sqrt(5))) == I*pi / 10
assert acsch(I*(1 + sqrt(5))) == -I*pi / 10
assert acsch(-I*2 / sqrt(2 - sqrt(2))) == I*pi / 8
assert acsch(I*2 / sqrt(2 - sqrt(2))) == -I*pi / 8
assert acsch(-I*2) == I*pi / 6
assert acsch(I*2) == -I*pi / 6
assert acsch(-I*sqrt(2 + 2/sqrt(5))) == I*pi / 5
assert acsch(I*sqrt(2 + 2/sqrt(5))) == -I*pi / 5
assert acsch(-I*sqrt(2)) == I*pi / 4
assert acsch(I*sqrt(2)) == -I*pi / 4
assert acsch(-I*(sqrt(5)-1)) == 3*I*pi / 10
assert acsch(I*(sqrt(5)-1)) == -3*I*pi / 10
assert acsch(-I*2 / sqrt(3)) == I*pi / 3
assert acsch(I*2 / sqrt(3)) == -I*pi / 3
assert acsch(-I*2 / sqrt(2 + sqrt(2))) == 3*I*pi / 8
assert acsch(I*2 / sqrt(2 + sqrt(2))) == -3*I*pi / 8
assert acsch(-I*sqrt(2 - 2/sqrt(5))) == 2*I*pi / 5
assert acsch(I*sqrt(2 - 2/sqrt(5))) == -2*I*pi / 5
assert acsch(-I*(sqrt(6) - sqrt(2))) == 5*I*pi / 12
assert acsch(I*(sqrt(6) - sqrt(2))) == -5*I*pi / 12
assert acsch(nan) is nan
# properties
# acsch(x) == asinh(1/x)
assert acsch(-I*sqrt(2)) == asinh(I/sqrt(2))
assert acsch(-I*2 / sqrt(3)) == asinh(I*sqrt(3) / 2)
# acsch(x) == -I*asin(I/x)
assert acsch(-I*sqrt(2)) == -I*asin(-1/sqrt(2))
assert acsch(-I*2 / sqrt(3)) == -I*asin(-sqrt(3)/2)
# csch(acsch(x)) / x == 1
assert expand_mul(csch(acsch(-I*(sqrt(6) + sqrt(2)))) / (-I*(sqrt(6) + sqrt(2)))) == 1
assert expand_mul(csch(acsch(I*(1 + sqrt(5)))) / (I*(1 + sqrt(5)))) == 1
assert (csch(acsch(I*sqrt(2 - 2/sqrt(5)))) / (I*sqrt(2 - 2/sqrt(5)))).simplify() == 1
assert (csch(acsch(-I*sqrt(2 - 2/sqrt(5)))) / (-I*sqrt(2 - 2/sqrt(5)))).simplify() == 1
# numerical evaluation
assert str(acsch(5*I+1).n(6)) == '0.0391819 - 0.193363*I'
assert str(acsch(-5*I+1).n(6)) == '0.0391819 + 0.193363*I'
def test_acsch_infinities():
assert acsch(oo) == 0
assert acsch(-oo) == 0
assert acsch(zoo) == 0
def test_acsch_rewrite():
x = Symbol('x')
assert acsch(x).rewrite(log) == log(1/x + sqrt(1/x**2 + 1))
def test_acsch_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: acsch(x).fdiff(2))
def test_atanh():
x = Symbol('x')
#at specific points
assert atanh(0) == 0
assert atanh(I) == I*pi/4
assert atanh(-I) == -I*pi/4
assert atanh(1) is oo
assert atanh(-1) is -oo
assert atanh(nan) is nan
# at infinites
assert atanh(oo) == -I*pi/2
assert atanh(-oo) == I*pi/2
assert atanh(I*oo) == I*pi/2
assert atanh(-I*oo) == -I*pi/2
assert atanh(zoo) == I*AccumBounds(-pi/2, pi/2)
#properties
assert atanh(-x) == -atanh(x)
assert atanh(I/sqrt(3)) == I*pi/6
assert atanh(-I/sqrt(3)) == -I*pi/6
assert atanh(I*sqrt(3)) == I*pi/3
assert atanh(-I*sqrt(3)) == -I*pi/3
assert atanh(I*(1 + sqrt(2))) == pi*I*Rational(3, 8)
assert atanh(I*(sqrt(2) - 1)) == pi*I/8
assert atanh(I*(1 - sqrt(2))) == -pi*I/8
assert atanh(-I*(1 + sqrt(2))) == pi*I*Rational(-3, 8)
assert atanh(I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(2, 5)
assert atanh(-I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(-2, 5)
assert atanh(I*(2 - sqrt(3))) == pi*I/12
assert atanh(I*(sqrt(3) - 2)) == -pi*I/12
assert atanh(oo) == -I*pi/2
# Symmetry
assert atanh(Rational(-1, 2)) == -atanh(S.Half)
# inverse composition
assert unchanged(atanh, tanh(Symbol('v1')))
assert atanh(tanh(-5, evaluate=False)) == -5
assert atanh(tanh(0, evaluate=False)) == 0
assert atanh(tanh(7, evaluate=False)) == 7
assert atanh(tanh(I, evaluate=False)) == I
assert atanh(tanh(-I, evaluate=False)) == -I
assert atanh(tanh(-11*I, evaluate=False)) == -11*I + 4*I*pi
assert atanh(tanh(3 + I)) == 3 + I
assert atanh(tanh(4 + 5*I)) == 4 - 2*I*pi + 5*I
assert atanh(tanh(pi/2)) == pi/2
assert atanh(tanh(pi)) == pi
assert atanh(tanh(-3 + 7*I)) == -3 - 2*I*pi + 7*I
assert atanh(tanh(9 - I*Rational(2, 3))) == 9 - I*Rational(2, 3)
assert atanh(tanh(-32 - 123*I)) == -32 - 123*I + 39*I*pi
def test_atanh_rewrite():
x = Symbol('x')
assert atanh(x).rewrite(log) == (log(1 + x) - log(1 - x)) / 2
def test_atanh_series():
x = Symbol('x')
assert atanh(x).series(x, 0, 10) == \
x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10)
def test_atanh_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: atanh(x).fdiff(2))
def test_acoth():
x = Symbol('x')
#at specific points
assert acoth(0) == I*pi/2
assert acoth(I) == -I*pi/4
assert acoth(-I) == I*pi/4
assert acoth(1) is oo
assert acoth(-1) is -oo
assert acoth(nan) is nan
# at infinites
assert acoth(oo) == 0
assert acoth(-oo) == 0
assert acoth(I*oo) == 0
assert acoth(-I*oo) == 0
assert acoth(zoo) == 0
#properties
assert acoth(-x) == -acoth(x)
assert acoth(I/sqrt(3)) == -I*pi/3
assert acoth(-I/sqrt(3)) == I*pi/3
assert acoth(I*sqrt(3)) == -I*pi/6
assert acoth(-I*sqrt(3)) == I*pi/6
assert acoth(I*(1 + sqrt(2))) == -pi*I/8
assert acoth(-I*(sqrt(2) + 1)) == pi*I/8
assert acoth(I*(1 - sqrt(2))) == pi*I*Rational(3, 8)
assert acoth(I*(sqrt(2) - 1)) == pi*I*Rational(-3, 8)
assert acoth(I*sqrt(5 + 2*sqrt(5))) == -I*pi/10
assert acoth(-I*sqrt(5 + 2*sqrt(5))) == I*pi/10
assert acoth(I*(2 + sqrt(3))) == -pi*I/12
assert acoth(-I*(2 + sqrt(3))) == pi*I/12
assert acoth(I*(2 - sqrt(3))) == pi*I*Rational(-5, 12)
assert acoth(I*(sqrt(3) - 2)) == pi*I*Rational(5, 12)
# Symmetry
assert acoth(Rational(-1, 2)) == -acoth(S.Half)
def test_acoth_rewrite():
x = Symbol('x')
assert acoth(x).rewrite(log) == (log(1 + 1/x) - log(1 - 1/x)) / 2
def test_acoth_series():
x = Symbol('x')
assert acoth(x).series(x, 0, 10) == \
I*pi/2 + x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10)
def test_acoth_fdiff():
x = Symbol('x')
raises(ArgumentIndexError, lambda: acoth(x).fdiff(2))
def test_inverses():
x = Symbol('x')
assert sinh(x).inverse() == asinh
raises(AttributeError, lambda: cosh(x).inverse())
assert tanh(x).inverse() == atanh
assert coth(x).inverse() == acoth
assert asinh(x).inverse() == sinh
assert acosh(x).inverse() == cosh
assert atanh(x).inverse() == tanh
assert acoth(x).inverse() == coth
assert asech(x).inverse() == sech
assert acsch(x).inverse() == csch
def test_leading_term():
x = Symbol('x')
assert cosh(x).as_leading_term(x) == 1
assert coth(x).as_leading_term(x) == 1/x
assert acosh(x).as_leading_term(x) == I*pi/2
assert acoth(x).as_leading_term(x) == I*pi/2
for func in [sinh, tanh, asinh, atanh]:
assert func(x).as_leading_term(x) == x
for func in [sinh, cosh, tanh, coth, asinh, acosh, atanh, acoth]:
for arg in (1/x, S.Half):
eq = func(arg)
assert eq.as_leading_term(x) == eq
for func in [csch, sech]:
eq = func(S.Half)
assert eq.as_leading_term(x) == eq
def test_complex():
a, b = symbols('a,b', real=True)
z = a + b*I
for func in [sinh, cosh, tanh, coth, sech, csch]:
assert func(z).conjugate() == func(a - b*I)
for deep in [True, False]:
assert sinh(z).expand(
complex=True, deep=deep) == sinh(a)*cos(b) + I*cosh(a)*sin(b)
assert cosh(z).expand(
complex=True, deep=deep) == cosh(a)*cos(b) + I*sinh(a)*sin(b)
assert tanh(z).expand(complex=True, deep=deep) == sinh(a)*cosh(
a)/(cos(b)**2 + sinh(a)**2) + I*sin(b)*cos(b)/(cos(b)**2 + sinh(a)**2)
assert coth(z).expand(complex=True, deep=deep) == sinh(a)*cosh(
a)/(sin(b)**2 + sinh(a)**2) - I*sin(b)*cos(b)/(sin(b)**2 + sinh(a)**2)
assert csch(z).expand(complex=True, deep=deep) == cos(b) * sinh(a) / (sin(b)**2\
*cosh(a)**2 + cos(b)**2 * sinh(a)**2) - I*sin(b) * cosh(a) / (sin(b)**2\
*cosh(a)**2 + cos(b)**2 * sinh(a)**2)
assert sech(z).expand(complex=True, deep=deep) == cos(b) * cosh(a) / (sin(b)**2\
*sinh(a)**2 + cos(b)**2 * cosh(a)**2) - I*sin(b) * sinh(a) / (sin(b)**2\
*sinh(a)**2 + cos(b)**2 * cosh(a)**2)
def test_complex_2899():
a, b = symbols('a,b', real=True)
for deep in [True, False]:
for func in [sinh, cosh, tanh, coth]:
assert func(a).expand(complex=True, deep=deep) == func(a)
def test_simplifications():
x = Symbol('x')
assert sinh(asinh(x)) == x
assert sinh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1)
assert sinh(atanh(x)) == x/sqrt(1 - x**2)
assert sinh(acoth(x)) == 1/(sqrt(x - 1) * sqrt(x + 1))
assert cosh(asinh(x)) == sqrt(1 + x**2)
assert cosh(acosh(x)) == x
assert cosh(atanh(x)) == 1/sqrt(1 - x**2)
assert cosh(acoth(x)) == x/(sqrt(x - 1) * sqrt(x + 1))
assert tanh(asinh(x)) == x/sqrt(1 + x**2)
assert tanh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1) / x
assert tanh(atanh(x)) == x
assert tanh(acoth(x)) == 1/x
assert coth(asinh(x)) == sqrt(1 + x**2)/x
assert coth(acosh(x)) == x/(sqrt(x - 1) * sqrt(x + 1))
assert coth(atanh(x)) == 1/x
assert coth(acoth(x)) == x
assert csch(asinh(x)) == 1/x
assert csch(acosh(x)) == 1/(sqrt(x - 1) * sqrt(x + 1))
assert csch(atanh(x)) == sqrt(1 - x**2)/x
assert csch(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)
assert sech(asinh(x)) == 1/sqrt(1 + x**2)
assert sech(acosh(x)) == 1/x
assert sech(atanh(x)) == sqrt(1 - x**2)
assert sech(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)/x
def test_issue_4136():
assert cosh(asinh(Integer(3)/2)) == sqrt(Integer(13)/4)
def test_sinh_rewrite():
x = Symbol('x')
assert sinh(x).rewrite(exp) == (exp(x) - exp(-x))/2 \
== sinh(x).rewrite('tractable')
assert sinh(x).rewrite(cosh) == -I*cosh(x + I*pi/2)
tanh_half = tanh(S.Half*x)
assert sinh(x).rewrite(tanh) == 2*tanh_half/(1 - tanh_half**2)
coth_half = coth(S.Half*x)
assert sinh(x).rewrite(coth) == 2*coth_half/(coth_half**2 - 1)
def test_cosh_rewrite():
x = Symbol('x')
assert cosh(x).rewrite(exp) == (exp(x) + exp(-x))/2 \
== cosh(x).rewrite('tractable')
assert cosh(x).rewrite(sinh) == -I*sinh(x + I*pi/2)
tanh_half = tanh(S.Half*x)**2
assert cosh(x).rewrite(tanh) == (1 + tanh_half)/(1 - tanh_half)
coth_half = coth(S.Half*x)**2
assert cosh(x).rewrite(coth) == (coth_half + 1)/(coth_half - 1)
def test_tanh_rewrite():
x = Symbol('x')
assert tanh(x).rewrite(exp) == (exp(x) - exp(-x))/(exp(x) + exp(-x)) \
== tanh(x).rewrite('tractable')
assert tanh(x).rewrite(sinh) == I*sinh(x)/sinh(I*pi/2 - x)
assert tanh(x).rewrite(cosh) == I*cosh(I*pi/2 - x)/cosh(x)
assert tanh(x).rewrite(coth) == 1/coth(x)
def test_coth_rewrite():
x = Symbol('x')
assert coth(x).rewrite(exp) == (exp(x) + exp(-x))/(exp(x) - exp(-x)) \
== coth(x).rewrite('tractable')
assert coth(x).rewrite(sinh) == -I*sinh(I*pi/2 - x)/sinh(x)
assert coth(x).rewrite(cosh) == -I*cosh(x)/cosh(I*pi/2 - x)
assert coth(x).rewrite(tanh) == 1/tanh(x)
def test_csch_rewrite():
x = Symbol('x')
assert csch(x).rewrite(exp) == 1 / (exp(x)/2 - exp(-x)/2) \
== csch(x).rewrite('tractable')
assert csch(x).rewrite(cosh) == I/cosh(x + I*pi/2)
tanh_half = tanh(S.Half*x)
assert csch(x).rewrite(tanh) == (1 - tanh_half**2)/(2*tanh_half)
coth_half = coth(S.Half*x)
assert csch(x).rewrite(coth) == (coth_half**2 - 1)/(2*coth_half)
def test_sech_rewrite():
x = Symbol('x')
assert sech(x).rewrite(exp) == 1 / (exp(x)/2 + exp(-x)/2) \
== sech(x).rewrite('tractable')
assert sech(x).rewrite(sinh) == I/sinh(x + I*pi/2)
tanh_half = tanh(S.Half*x)**2
assert sech(x).rewrite(tanh) == (1 - tanh_half)/(1 + tanh_half)
coth_half = coth(S.Half*x)**2
assert sech(x).rewrite(coth) == (coth_half - 1)/(coth_half + 1)
def test_derivs():
x = Symbol('x')
assert coth(x).diff(x) == -sinh(x)**(-2)
assert sinh(x).diff(x) == cosh(x)
assert cosh(x).diff(x) == sinh(x)
assert tanh(x).diff(x) == -tanh(x)**2 + 1
assert csch(x).diff(x) == -coth(x)*csch(x)
assert sech(x).diff(x) == -tanh(x)*sech(x)
assert acoth(x).diff(x) == 1/(-x**2 + 1)
assert asinh(x).diff(x) == 1/sqrt(x**2 + 1)
assert acosh(x).diff(x) == 1/sqrt(x**2 - 1)
assert atanh(x).diff(x) == 1/(-x**2 + 1)
assert asech(x).diff(x) == -1/(x*sqrt(1 - x**2))
assert acsch(x).diff(x) == -1/(x**2*sqrt(1 + x**(-2)))
def test_sinh_expansion():
x, y = symbols('x,y')
assert sinh(x+y).expand(trig=True) == sinh(x)*cosh(y) + cosh(x)*sinh(y)
assert sinh(2*x).expand(trig=True) == 2*sinh(x)*cosh(x)
assert sinh(3*x).expand(trig=True).expand() == \
sinh(x)**3 + 3*sinh(x)*cosh(x)**2
def test_cosh_expansion():
x, y = symbols('x,y')
assert cosh(x+y).expand(trig=True) == cosh(x)*cosh(y) + sinh(x)*sinh(y)
assert cosh(2*x).expand(trig=True) == cosh(x)**2 + sinh(x)**2
assert cosh(3*x).expand(trig=True).expand() == \
3*sinh(x)**2*cosh(x) + cosh(x)**3
def test_cosh_positive():
# See issue 11721
# cosh(x) is positive for real values of x
k = symbols('k', real=True)
n = symbols('n', integer=True)
assert cosh(k, evaluate=False).is_positive is True
assert cosh(k + 2*n*pi*I, evaluate=False).is_positive is True
assert cosh(I*pi/4, evaluate=False).is_positive is True
assert cosh(3*I*pi/4, evaluate=False).is_positive is False
def test_cosh_nonnegative():
k = symbols('k', real=True)
n = symbols('n', integer=True)
assert cosh(k, evaluate=False).is_nonnegative is True
assert cosh(k + 2*n*pi*I, evaluate=False).is_nonnegative is True
assert cosh(I*pi/4, evaluate=False).is_nonnegative is True
assert cosh(3*I*pi/4, evaluate=False).is_nonnegative is False
assert cosh(S.Zero, evaluate=False).is_nonnegative is True
def test_real_assumptions():
z = Symbol('z', real=False)
assert sinh(z).is_real is None
assert cosh(z).is_real is None
assert tanh(z).is_real is None
assert sech(z).is_real is None
assert csch(z).is_real is None
assert coth(z).is_real is None
def test_sign_assumptions():
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
assert sinh(n).is_negative is True
assert sinh(p).is_positive is True
assert cosh(n).is_positive is True
assert cosh(p).is_positive is True
assert tanh(n).is_negative is True
assert tanh(p).is_positive is True
assert csch(n).is_negative is True
assert csch(p).is_positive is True
assert sech(n).is_positive is True
assert sech(p).is_positive is True
assert coth(n).is_negative is True
assert coth(p).is_positive is True
|
fa1d42b6e1466cde1882b2858322c2e3f612e2f4a181313d0079a9c4613cc501 | from sympy import (hyper, meijerg, S, Tuple, pi, I, exp, log, Rational,
cos, sqrt, symbols, oo, Derivative, gamma, O, appellf1)
from sympy.abc import x, z, k
from sympy.series.limits import limit
from sympy.testing.pytest import raises, slow
from sympy.testing.randtest import (
random_complex_number as randcplx,
verify_numerically as tn,
test_derivative_numerically as td)
def test_TupleParametersBase():
# test that our implementation of the chain rule works
p = hyper((), (), z**2)
assert p.diff(z) == p*2*z
def test_hyper():
raises(TypeError, lambda: hyper(1, 2, z))
assert hyper((1, 2), (1,), z) == hyper(Tuple(1, 2), Tuple(1), z)
h = hyper((1, 2), (3, 4, 5), z)
assert h.ap == Tuple(1, 2)
assert h.bq == Tuple(3, 4, 5)
assert h.argument == z
assert h.is_commutative is True
# just a few checks to make sure that all arguments go where they should
assert tn(hyper(Tuple(), Tuple(), z), exp(z), z)
assert tn(z*hyper((1, 1), Tuple(2), -z), log(1 + z), z)
# differentiation
h = hyper(
(randcplx(), randcplx(), randcplx()), (randcplx(), randcplx()), z)
assert td(h, z)
a1, a2, b1, b2, b3 = symbols('a1:3, b1:4')
assert hyper((a1, a2), (b1, b2, b3), z).diff(z) == \
a1*a2/(b1*b2*b3) * hyper((a1 + 1, a2 + 1), (b1 + 1, b2 + 1, b3 + 1), z)
# differentiation wrt parameters is not supported
assert hyper([z], [], z).diff(z) == Derivative(hyper([z], [], z), z)
# hyper is unbranched wrt parameters
from sympy import polar_lift
assert hyper([polar_lift(z)], [polar_lift(k)], polar_lift(x)) == \
hyper([z], [k], polar_lift(x))
# hyper does not automatically evaluate anyway, but the test is to make
# sure that the evaluate keyword is accepted
assert hyper((1, 2), (1,), z, evaluate=False).func is hyper
def test_expand_func():
# evaluation at 1 of Gauss' hypergeometric function:
from sympy.abc import a, b, c
from sympy import gamma, expand_func
a1, b1, c1 = randcplx(), randcplx(), randcplx() + 5
assert expand_func(hyper([a, b], [c], 1)) == \
gamma(c)*gamma(-a - b + c)/(gamma(-a + c)*gamma(-b + c))
assert abs(expand_func(hyper([a1, b1], [c1], 1)).n()
- hyper([a1, b1], [c1], 1).n()) < 1e-10
# hyperexpand wrapper for hyper:
assert expand_func(hyper([], [], z)) == exp(z)
assert expand_func(hyper([1, 2, 3], [], z)) == hyper([1, 2, 3], [], z)
assert expand_func(meijerg([[1, 1], []], [[1], [0]], z)) == log(z + 1)
assert expand_func(meijerg([[1, 1], []], [[], []], z)) == \
meijerg([[1, 1], []], [[], []], z)
def replace_dummy(expr, sym):
from sympy import Dummy
dum = expr.atoms(Dummy)
if not dum:
return expr
assert len(dum) == 1
return expr.xreplace({dum.pop(): sym})
def test_hyper_rewrite_sum():
from sympy import RisingFactorial, factorial, Dummy, Sum
_k = Dummy("k")
assert replace_dummy(hyper((1, 2), (1, 3), x).rewrite(Sum), _k) == \
Sum(x**_k / factorial(_k) * RisingFactorial(2, _k) /
RisingFactorial(3, _k), (_k, 0, oo))
assert hyper((1, 2, 3), (-1, 3), z).rewrite(Sum) == \
hyper((1, 2, 3), (-1, 3), z)
def test_radius_of_convergence():
assert hyper((1, 2), [3], z).radius_of_convergence == 1
assert hyper((1, 2), [3, 4], z).radius_of_convergence is oo
assert hyper((1, 2, 3), [4], z).radius_of_convergence == 0
assert hyper((0, 1, 2), [4], z).radius_of_convergence is oo
assert hyper((-1, 1, 2), [-4], z).radius_of_convergence == 0
assert hyper((-1, -2, 2), [-1], z).radius_of_convergence is oo
assert hyper((-1, 2), [-1, -2], z).radius_of_convergence == 0
assert hyper([-1, 1, 3], [-2, 2], z).radius_of_convergence == 1
assert hyper([-1, 1], [-2, 2], z).radius_of_convergence is oo
assert hyper([-1, 1, 3], [-2], z).radius_of_convergence == 0
assert hyper((-1, 2, 3, 4), [], z).radius_of_convergence is oo
assert hyper([1, 1], [3], 1).convergence_statement == True
assert hyper([1, 1], [2], 1).convergence_statement == False
assert hyper([1, 1], [2], -1).convergence_statement == True
assert hyper([1, 1], [1], -1).convergence_statement == False
def test_meijer():
raises(TypeError, lambda: meijerg(1, z))
raises(TypeError, lambda: meijerg(((1,), (2,)), (3,), (4,), z))
assert meijerg(((1, 2), (3,)), ((4,), (5,)), z) == \
meijerg(Tuple(1, 2), Tuple(3), Tuple(4), Tuple(5), z)
g = meijerg((1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11, 12, 13, 14), z)
assert g.an == Tuple(1, 2)
assert g.ap == Tuple(1, 2, 3, 4, 5)
assert g.aother == Tuple(3, 4, 5)
assert g.bm == Tuple(6, 7, 8, 9)
assert g.bq == Tuple(6, 7, 8, 9, 10, 11, 12, 13, 14)
assert g.bother == Tuple(10, 11, 12, 13, 14)
assert g.argument == z
assert g.nu == 75
assert g.delta == -1
assert g.is_commutative is True
assert g.is_number is False
#issue 13071
assert meijerg([[],[]], [[S.Half],[0]], 1).is_number is True
assert meijerg([1, 2], [3], [4], [5], z).delta == S.Half
# just a few checks to make sure that all arguments go where they should
assert tn(meijerg(Tuple(), Tuple(), Tuple(0), Tuple(), -z), exp(z), z)
assert tn(sqrt(pi)*meijerg(Tuple(), Tuple(),
Tuple(0), Tuple(S.Half), z**2/4), cos(z), z)
assert tn(meijerg(Tuple(1, 1), Tuple(), Tuple(1), Tuple(0), z),
log(1 + z), z)
# test exceptions
raises(ValueError, lambda: meijerg(((3, 1), (2,)), ((oo,), (2, 0)), x))
raises(ValueError, lambda: meijerg(((3, 1), (2,)), ((1,), (2, 0)), x))
# differentiation
g = meijerg((randcplx(),), (randcplx() + 2*I,), Tuple(),
(randcplx(), randcplx()), z)
assert td(g, z)
g = meijerg(Tuple(), (randcplx(),), Tuple(),
(randcplx(), randcplx()), z)
assert td(g, z)
g = meijerg(Tuple(), Tuple(), Tuple(randcplx()),
Tuple(randcplx(), randcplx()), z)
assert td(g, z)
a1, a2, b1, b2, c1, c2, d1, d2 = symbols('a1:3, b1:3, c1:3, d1:3')
assert meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z).diff(z) == \
(meijerg((a1 - 1, a2), (b1, b2), (c1, c2), (d1, d2), z)
+ (a1 - 1)*meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z))/z
assert meijerg([z, z], [], [], [], z).diff(z) == \
Derivative(meijerg([z, z], [], [], [], z), z)
# meijerg is unbranched wrt parameters
from sympy import polar_lift as pl
assert meijerg([pl(a1)], [pl(a2)], [pl(b1)], [pl(b2)], pl(z)) == \
meijerg([a1], [a2], [b1], [b2], pl(z))
# integrand
from sympy.abc import a, b, c, d, s
assert meijerg([a], [b], [c], [d], z).integrand(s) == \
z**s*gamma(c - s)*gamma(-a + s + 1)/(gamma(b - s)*gamma(-d + s + 1))
def test_meijerg_derivative():
assert meijerg([], [1, 1], [0, 0, x], [], z).diff(x) == \
log(z)*meijerg([], [1, 1], [0, 0, x], [], z) \
+ 2*meijerg([], [1, 1, 1], [0, 0, x, 0], [], z)
y = randcplx()
a = 5 # mpmath chokes with non-real numbers, and Mod1 with floats
assert td(meijerg([x], [], [], [], y), x)
assert td(meijerg([x**2], [], [], [], y), x)
assert td(meijerg([], [x], [], [], y), x)
assert td(meijerg([], [], [x], [], y), x)
assert td(meijerg([], [], [], [x], y), x)
assert td(meijerg([x], [a], [a + 1], [], y), x)
assert td(meijerg([x], [a + 1], [a], [], y), x)
assert td(meijerg([x, a], [], [], [a + 1], y), x)
assert td(meijerg([x, a + 1], [], [], [a], y), x)
b = Rational(3, 2)
assert td(meijerg([a + 2], [b], [b - 3, x], [a], y), x)
def test_meijerg_period():
assert meijerg([], [1], [0], [], x).get_period() == 2*pi
assert meijerg([1], [], [], [0], x).get_period() == 2*pi
assert meijerg([], [], [0], [], x).get_period() == 2*pi # exp(x)
assert meijerg(
[], [], [0], [S.Half], x).get_period() == 2*pi # cos(sqrt(x))
assert meijerg(
[], [], [S.Half], [0], x).get_period() == 4*pi # sin(sqrt(x))
assert meijerg([1, 1], [], [1], [0], x).get_period() is oo # log(1 + x)
def test_hyper_unpolarify():
from sympy import exp_polar
a = exp_polar(2*pi*I)*x
b = x
assert hyper([], [], a).argument == b
assert hyper([0], [], a).argument == a
assert hyper([0], [0], a).argument == b
assert hyper([0, 1], [0], a).argument == a
assert hyper([0, 1], [0], exp_polar(2*pi*I)).argument == 1
@slow
def test_hyperrep():
from sympy.functions.special.hyper import (HyperRep, HyperRep_atanh,
HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1,
HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2,
HyperRep_cosasin, HyperRep_sinasin)
# First test the base class works.
from sympy import Piecewise, exp_polar
a, b, c, d, z = symbols('a b c d z')
class myrep(HyperRep):
@classmethod
def _expr_small(cls, x):
return a
@classmethod
def _expr_small_minus(cls, x):
return b
@classmethod
def _expr_big(cls, x, n):
return c*n
@classmethod
def _expr_big_minus(cls, x, n):
return d*n
assert myrep(z).rewrite('nonrep') == Piecewise((0, abs(z) > 1), (a, True))
assert myrep(exp_polar(I*pi)*z).rewrite('nonrep') == \
Piecewise((0, abs(z) > 1), (b, True))
assert myrep(exp_polar(2*I*pi)*z).rewrite('nonrep') == \
Piecewise((c, abs(z) > 1), (a, True))
assert myrep(exp_polar(3*I*pi)*z).rewrite('nonrep') == \
Piecewise((d, abs(z) > 1), (b, True))
assert myrep(exp_polar(4*I*pi)*z).rewrite('nonrep') == \
Piecewise((2*c, abs(z) > 1), (a, True))
assert myrep(exp_polar(5*I*pi)*z).rewrite('nonrep') == \
Piecewise((2*d, abs(z) > 1), (b, True))
assert myrep(z).rewrite('nonrepsmall') == a
assert myrep(exp_polar(I*pi)*z).rewrite('nonrepsmall') == b
def t(func, hyp, z):
""" Test that func is a valid representation of hyp. """
# First test that func agrees with hyp for small z
if not tn(func.rewrite('nonrepsmall'), hyp, z,
a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half):
return False
# Next check that the two small representations agree.
if not tn(
func.rewrite('nonrepsmall').subs(
z, exp_polar(I*pi)*z).replace(exp_polar, exp),
func.subs(z, exp_polar(I*pi)*z).rewrite('nonrepsmall'),
z, a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half):
return False
# Next check continuity along exp_polar(I*pi)*t
expr = func.subs(z, exp_polar(I*pi)*z).rewrite('nonrep')
if abs(expr.subs(z, 1 + 1e-15).n() - expr.subs(z, 1 - 1e-15).n()) > 1e-10:
return False
# Finally check continuity of the big reps.
def dosubs(func, a, b):
rv = func.subs(z, exp_polar(a)*z).rewrite('nonrep')
return rv.subs(z, exp_polar(b)*z).replace(exp_polar, exp)
for n in [0, 1, 2, 3, 4, -1, -2, -3, -4]:
expr1 = dosubs(func, 2*I*pi*n, I*pi/2)
expr2 = dosubs(func, 2*I*pi*n + I*pi, -I*pi/2)
if not tn(expr1, expr2, z):
return False
expr1 = dosubs(func, 2*I*pi*(n + 1), -I*pi/2)
expr2 = dosubs(func, 2*I*pi*n + I*pi, I*pi/2)
if not tn(expr1, expr2, z):
return False
return True
# Now test the various representatives.
a = Rational(1, 3)
assert t(HyperRep_atanh(z), hyper([S.Half, 1], [Rational(3, 2)], z), z)
assert t(HyperRep_power1(a, z), hyper([-a], [], z), z)
assert t(HyperRep_power2(a, z), hyper([a, a - S.Half], [2*a], z), z)
assert t(HyperRep_log1(z), -z*hyper([1, 1], [2], z), z)
assert t(HyperRep_asin1(z), hyper([S.Half, S.Half], [Rational(3, 2)], z), z)
assert t(HyperRep_asin2(z), hyper([1, 1], [Rational(3, 2)], z), z)
assert t(HyperRep_sqrts1(a, z), hyper([-a, S.Half - a], [S.Half], z), z)
assert t(HyperRep_sqrts2(a, z),
-2*z/(2*a + 1)*hyper([-a - S.Half, -a], [S.Half], z).diff(z), z)
assert t(HyperRep_log2(z), -z/4*hyper([Rational(3, 2), 1, 1], [2, 2], z), z)
assert t(HyperRep_cosasin(a, z), hyper([-a, a], [S.Half], z), z)
assert t(HyperRep_sinasin(a, z), 2*a*z*hyper([1 - a, 1 + a], [Rational(3, 2)], z), z)
@slow
def test_meijerg_eval():
from sympy import besseli, exp_polar
from sympy.abc import l
a = randcplx()
arg = x*exp_polar(k*pi*I)
expr1 = pi*meijerg([[], [(a + 1)/2]], [[a/2], [-a/2, (a + 1)/2]], arg**2/4)
expr2 = besseli(a, arg)
# Test that the two expressions agree for all arguments.
for x_ in [0.5, 1.5]:
for k_ in [0.0, 0.1, 0.3, 0.5, 0.8, 1, 5.751, 15.3]:
assert abs((expr1 - expr2).n(subs={x: x_, k: k_})) < 1e-10
assert abs((expr1 - expr2).n(subs={x: x_, k: -k_})) < 1e-10
# Test continuity independently
eps = 1e-13
expr2 = expr1.subs(k, l)
for x_ in [0.5, 1.5]:
for k_ in [0.5, Rational(1, 3), 0.25, 0.75, Rational(2, 3), 1.0, 1.5]:
assert abs((expr1 - expr2).n(
subs={x: x_, k: k_ + eps, l: k_ - eps})) < 1e-10
assert abs((expr1 - expr2).n(
subs={x: x_, k: -k_ + eps, l: -k_ - eps})) < 1e-10
expr = (meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(-I*pi)/4)
+ meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(I*pi)/4)) \
/(2*sqrt(pi))
assert (expr - pi/exp(1)).n(chop=True) == 0
def test_limits():
k, x = symbols('k, x')
assert hyper((1,), (Rational(4, 3), Rational(5, 3)), k**2).series(k) == \
1 + 9*k**2/20 + 81*k**4/1120 + O(k**6) # issue 6350
assert limit(meijerg((), (), (1,), (0,), -x), x, 0) == \
meijerg(((), ()), ((1,), (0,)), 0) # issue 6052
# https://github.com/sympy/sympy/issues/11465
assert limit(1/hyper((1, ), (1, ), x), x, 0) == 1
def test_appellf1():
a, b1, b2, c, x, y = symbols('a b1 b2 c x y')
assert appellf1(a, b2, b1, c, y, x) == appellf1(a, b1, b2, c, x, y)
assert appellf1(a, b1, b1, c, y, x) == appellf1(a, b1, b1, c, x, y)
assert appellf1(a, b1, b2, c, S.Zero, S.Zero) is S.One
f = appellf1(a, b1, b2, c, S.Zero, S.Zero, evaluate=False)
assert f.func is appellf1
assert f.doit() is S.One
def test_derivative_appellf1():
from sympy import diff
a, b1, b2, c, x, y, z = symbols('a b1 b2 c x y z')
assert diff(appellf1(a, b1, b2, c, x, y), x) == a*b1*appellf1(a + 1, b2, b1 + 1, c + 1, y, x)/c
assert diff(appellf1(a, b1, b2, c, x, y), y) == a*b2*appellf1(a + 1, b1, b2 + 1, c + 1, x, y)/c
assert diff(appellf1(a, b1, b2, c, x, y), z) == 0
assert diff(appellf1(a, b1, b2, c, x, y), a) == Derivative(appellf1(a, b1, b2, c, x, y), a)
def test_eval_nseries():
a1, b1, a2, b2 = symbols('a1 b1 a2 b2')
assert hyper((1,2), (1,2,3), x**2)._eval_nseries(x, 7, None) == 1 + x**2/3 + x**4/24 + x**6/360 + O(x**7)
assert exp(x)._eval_nseries(x,7,None) == hyper((a1, b1), (a1, b1), x)._eval_nseries(x, 7, None)
assert hyper((a1, a2), (b1, b2), x)._eval_nseries(z, 7, None) == hyper((a1, a2), (b1, b2), x) + O(z**7)
|
e74412534b80e4344d6849a5bd42718a3b0963f7198ef0b55eb5cfd1b8ae36cf | from sympy import (
adjoint, conjugate, DiracDelta, Heaviside, nan, pi, sign, sqrt,
symbols, transpose, Symbol, Piecewise, I, S, Eq, Ne, oo,
SingularityFunction, signsimp
)
from sympy.testing.pytest import raises, warns_deprecated_sympy
from sympy.core.expr import unchanged
from sympy.core.function import ArgumentIndexError
x, y = symbols('x y')
i = symbols('t', nonzero=True)
j = symbols('j', positive=True)
k = symbols('k', negative=True)
def test_DiracDelta():
assert DiracDelta(1) == 0
assert DiracDelta(5.1) == 0
assert DiracDelta(-pi) == 0
assert DiracDelta(5, 7) == 0
assert DiracDelta(i) == 0
assert DiracDelta(j) == 0
assert DiracDelta(k) == 0
assert DiracDelta(nan) is nan
assert DiracDelta(0).func is DiracDelta
assert DiracDelta(x).func is DiracDelta
# FIXME: this is generally undefined @ x=0
# But then limit(Delta(c)*Heaviside(x),x,-oo)
# need's to be implemented.
# assert 0*DiracDelta(x) == 0
assert adjoint(DiracDelta(x)) == DiracDelta(x)
assert adjoint(DiracDelta(x - y)) == DiracDelta(x - y)
assert conjugate(DiracDelta(x)) == DiracDelta(x)
assert conjugate(DiracDelta(x - y)) == DiracDelta(x - y)
assert transpose(DiracDelta(x)) == DiracDelta(x)
assert transpose(DiracDelta(x - y)) == DiracDelta(x - y)
assert DiracDelta(x).diff(x) == DiracDelta(x, 1)
assert DiracDelta(x, 1).diff(x) == DiracDelta(x, 2)
assert DiracDelta(x).is_simple(x) is True
assert DiracDelta(3*x).is_simple(x) is True
assert DiracDelta(x**2).is_simple(x) is False
assert DiracDelta(sqrt(x)).is_simple(x) is False
assert DiracDelta(x).is_simple(y) is False
assert DiracDelta(x*y).expand(diracdelta=True, wrt=x) == DiracDelta(x)/abs(y)
assert DiracDelta(x*y).expand(diracdelta=True, wrt=y) == DiracDelta(y)/abs(x)
assert DiracDelta(x**2*y).expand(diracdelta=True, wrt=x) == DiracDelta(x**2*y)
assert DiracDelta(y).expand(diracdelta=True, wrt=x) == DiracDelta(y)
assert DiracDelta((x - 1)*(x - 2)*(x - 3)).expand(diracdelta=True, wrt=x) == (
DiracDelta(x - 3)/2 + DiracDelta(x - 2) + DiracDelta(x - 1)/2)
assert DiracDelta(2*x) != DiracDelta(x) # scaling property
assert DiracDelta(x) == DiracDelta(-x) # even function
assert DiracDelta(-x, 2) == DiracDelta(x, 2)
assert DiracDelta(-x, 1) == -DiracDelta(x, 1) # odd deriv is odd
assert DiracDelta(-oo*x) == DiracDelta(oo*x)
assert DiracDelta(x - y) != DiracDelta(y - x)
assert signsimp(DiracDelta(x - y) - DiracDelta(y - x)) == 0
with warns_deprecated_sympy():
assert DiracDelta(x*y).simplify(x) == DiracDelta(x)/abs(y)
with warns_deprecated_sympy():
assert DiracDelta(x*y).simplify(y) == DiracDelta(y)/abs(x)
with warns_deprecated_sympy():
assert DiracDelta(x**2*y).simplify(x) == DiracDelta(x**2*y)
with warns_deprecated_sympy():
assert DiracDelta(y).simplify(x) == DiracDelta(y)
with warns_deprecated_sympy():
assert DiracDelta((x - 1)*(x - 2)*(x - 3)).simplify(x) == (
DiracDelta(x - 3)/2 + DiracDelta(x - 2) + DiracDelta(x - 1)/2)
raises(ArgumentIndexError, lambda: DiracDelta(x).fdiff(2))
raises(ValueError, lambda: DiracDelta(x, -1))
raises(ValueError, lambda: DiracDelta(I))
raises(ValueError, lambda: DiracDelta(2 + 3*I))
def test_heaviside():
assert Heaviside(-5) == 0
assert Heaviside(1) == 1
assert Heaviside(0) == S.Half
assert Heaviside(0, x) == x
assert unchanged(Heaviside,x, nan)
assert Heaviside(0, nan) == nan
assert adjoint(Heaviside(x)) == Heaviside(x)
assert adjoint(Heaviside(x - y)) == Heaviside(x - y)
assert conjugate(Heaviside(x)) == Heaviside(x)
assert conjugate(Heaviside(x - y)) == Heaviside(x - y)
assert transpose(Heaviside(x)) == Heaviside(x)
assert transpose(Heaviside(x - y)) == Heaviside(x - y)
assert Heaviside(x).diff(x) == DiracDelta(x)
assert Heaviside(x + I).is_Function is True
assert Heaviside(I*x).is_Function is True
raises(ArgumentIndexError, lambda: Heaviside(x).fdiff(2))
raises(ValueError, lambda: Heaviside(I))
raises(ValueError, lambda: Heaviside(2 + 3*I))
def test_rewrite():
x, y = Symbol('x', real=True), Symbol('y')
assert Heaviside(x).rewrite(Piecewise) == (
Piecewise((0, x < 0), (Heaviside(0), Eq(x, 0)), (1, x > 0)))
assert Heaviside(y).rewrite(Piecewise) == (
Piecewise((0, y < 0), (Heaviside(0), Eq(y, 0)), (1, y > 0)))
assert Heaviside(x, y).rewrite(Piecewise) == (
Piecewise((0, x < 0), (y, Eq(x, 0)), (1, x > 0)))
assert Heaviside(x, 0).rewrite(Piecewise) == (
Piecewise((0, x <= 0), (1, x > 0)))
assert Heaviside(x, 1).rewrite(Piecewise) == (
Piecewise((0, x < 0), (1, x >= 0)))
assert Heaviside(x, nan).rewrite(Piecewise) == (
Piecewise((0, x < 0), (nan, Eq(x, 0)), (1, x > 0)))
assert Heaviside(x).rewrite(sign) == \
Heaviside(x, H0=Heaviside(0)).rewrite(sign) == \
Piecewise(
(sign(x)/2 + S(1)/2, Eq(Heaviside(0), S(1)/2)),
(Piecewise(
(sign(x)/2 + S(1)/2, Ne(x, 0)), (Heaviside(0), True)), True)
)
assert Heaviside(y).rewrite(sign) == Heaviside(y)
assert Heaviside(x, S.Half).rewrite(sign) == (sign(x)+1)/2
assert Heaviside(x, y).rewrite(sign) == \
Piecewise(
(sign(x)/2 + S(1)/2, Eq(y, S(1)/2)),
(Piecewise(
(sign(x)/2 + S(1)/2, Ne(x, 0)), (y, True)), True)
)
assert DiracDelta(y).rewrite(Piecewise) == Piecewise((DiracDelta(0), Eq(y, 0)), (0, True))
assert DiracDelta(y, 1).rewrite(Piecewise) == DiracDelta(y, 1)
assert DiracDelta(x - 5).rewrite(Piecewise) == (
Piecewise((DiracDelta(0), Eq(x - 5, 0)), (0, True)))
assert (x*DiracDelta(x - 10)).rewrite(SingularityFunction) == x*SingularityFunction(x, 10, -1)
assert 5*x*y*DiracDelta(y, 1).rewrite(SingularityFunction) == 5*x*y*SingularityFunction(y, 0, -2)
assert DiracDelta(0).rewrite(SingularityFunction) == SingularityFunction(0, 0, -1)
assert DiracDelta(0, 1).rewrite(SingularityFunction) == SingularityFunction(0, 0, -2)
assert Heaviside(x).rewrite(SingularityFunction) == SingularityFunction(x, 0, 0)
assert 5*x*y*Heaviside(y + 1).rewrite(SingularityFunction) == 5*x*y*SingularityFunction(y, -1, 0)
assert ((x - 3)**3*Heaviside(x - 3)).rewrite(SingularityFunction) == (x - 3)**3*SingularityFunction(x, 3, 0)
assert Heaviside(0).rewrite(SingularityFunction) == S.Half
|
50a549295b7baf486e40d1ce2a4bf4ef3dc7d17b60bc96cea930b75e0cbbf5ac | from itertools import product
from sympy import (jn, yn, symbols, Symbol, sin, cos, pi, S, jn_zeros, besselj,
bessely, besseli, besselk, hankel1, hankel2, hn1, hn2,
expand_func, sqrt, sinh, cosh, diff, series, gamma, hyper,
I, O, oo, conjugate, uppergamma, exp, Integral, Sum,
Rational, log, polar_lift, exp_polar)
from sympy.functions.special.bessel import fn
from sympy.functions.special.bessel import (airyai, airybi,
airyaiprime, airybiprime, marcumq)
from sympy.testing.randtest import (random_complex_number as randcplx,
verify_numerically as tn,
test_derivative_numerically as td,
_randint)
from sympy.simplify import besselsimp
from sympy.testing.pytest import raises, slow
from sympy.abc import z, n, k, x
randint = _randint()
def test_bessel_rand():
for f in [besselj, bessely, besseli, besselk, hankel1, hankel2]:
assert td(f(randcplx(), z), z)
for f in [jn, yn, hn1, hn2]:
assert td(f(randint(-10, 10), z), z)
def test_bessel_twoinputs():
for f in [besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn]:
raises(TypeError, lambda: f(1))
raises(TypeError, lambda: f(1, 2, 3))
def test_besselj_series():
assert besselj(0, x).series(x) == 1 - x**2/4 + x**4/64 + O(x**6)
assert besselj(0, x**(1.1)).series(x) == 1 + x**4.4/64 - x**2.2/4 + O(x**6)
assert besselj(0, x**2 + x).series(x) == 1 - x**2/4 - x**3/2\
- 15*x**4/64 + x**5/16 + O(x**6)
assert besselj(0, sqrt(x) + x).series(x, n=4) == 1 - x/4 - 15*x**2/64\
+ 215*x**3/2304 - x**Rational(3, 2)/2 + x**Rational(5, 2)/16\
+ 23*x**Rational(7, 2)/384 + O(x**4)
assert besselj(0, x/(1 - x)).series(x) == 1 - x**2/4 - x**3/2 - 47*x**4/64\
- 15*x**5/16 + O(x**6)
assert besselj(0, log(1 + x)).series(x) == 1 - x**2/4 + x**3/4\
- 41*x**4/192 + 17*x**5/96 + O(x**6)
assert besselj(1, sin(x)).series(x) == x/2 - 7*x**3/48 + 73*x**5/1920 + O(x**6)
assert besselj(1, 2*sqrt(x)).series(x) == sqrt(x) - x**Rational(3, 2)/2\
+ x**Rational(5, 2)/12 - x**Rational(7, 2)/144 + x**Rational(9, 2)/2880\
- x**Rational(11, 2)/86400 + O(x**6)
assert besselj(-2, sin(x)).series(x, n=4) == besselj(2, sin(x)).series(x, n=4)
def test_bessely_series():
const = 2*S.EulerGamma/pi - 2*log(2)/pi + 2*log(x)/pi
assert bessely(0, x).series(x, n=4) == const + x**2*(-log(x)/(2*pi)\
+ (2 - 2*S.EulerGamma)/(4*pi) + log(2)/(2*pi)) + O(x**4*log(x))
assert bessely(0, x**(1.1)).series(x, n=4) == 2*S.EulerGamma/pi\
- 2*log(2)/pi + 2.2*log(x)/pi + x**2.2*(-0.55*log(x)/pi\
+ (2 - 2*S.EulerGamma)/(4*pi) + log(2)/(2*pi)) + O(x**4*log(x))
assert bessely(0, x**2 + x).series(x, n=4) == \
const - (2 - 2*S.EulerGamma)*(-x**3/(2*pi) - x**2/(4*pi)) + 2*x/pi\
+ x**2*(-log(x)/(2*pi) - 1/pi + log(2)/(2*pi))\
+ x**3*(-log(x)/pi + 1/(6*pi) + log(2)/pi) + O(x**4*log(x))
assert bessely(0, x/(1 - x)).series(x, n=3) == const\
+ 2*x/pi + x**2*(-log(x)/(2*pi) + (2 - 2*S.EulerGamma)/(4*pi)\
+ log(2)/(2*pi) + 1/pi) + O(x**3*log(x))
assert bessely(0, log(1 + x)).series(x, n=3) == const\
- x/pi + x**2*(-log(x)/(2*pi) + (2 - 2*S.EulerGamma)/(4*pi)\
+ log(2)/(2*pi) + 5/(12*pi)) + O(x**3*log(x))
assert bessely(1, sin(x)).series(x, n=4) == -(1/pi)*(1 - 2*S.EulerGamma)\
* (-x**3/12 + x/2) + x*(log(x)/pi - log(2)/pi) + x**3*(-7*log(x)\
/ (24*pi) - 1/(6*pi) + (Rational(5, 2) - 2*S.EulerGamma)/(16*pi)\
+ 7*log(2)/(24*pi)) + O(x**4*log(x))
assert bessely(1, 2*sqrt(x)).series(x, n=3) == sqrt(x)*(log(x)/pi \
- (1 - 2*S.EulerGamma)/pi) + x**Rational(3, 2)*(-log(x)/(2*pi)\
+ (Rational(5, 2) - 2*S.EulerGamma)/(2*pi))\
+ x**Rational(5, 2)*(log(x)/(12*pi)\
- (Rational(10, 3) - 2*S.EulerGamma)/(12*pi)) + O(x**3*log(x))
assert bessely(-2, sin(x)).series(x, n=4) == bessely(2, sin(x)).series(x, n=4)
def test_diff():
assert besselj(n, z).diff(z) == besselj(n - 1, z)/2 - besselj(n + 1, z)/2
assert bessely(n, z).diff(z) == bessely(n - 1, z)/2 - bessely(n + 1, z)/2
assert besseli(n, z).diff(z) == besseli(n - 1, z)/2 + besseli(n + 1, z)/2
assert besselk(n, z).diff(z) == -besselk(n - 1, z)/2 - besselk(n + 1, z)/2
assert hankel1(n, z).diff(z) == hankel1(n - 1, z)/2 - hankel1(n + 1, z)/2
assert hankel2(n, z).diff(z) == hankel2(n - 1, z)/2 - hankel2(n + 1, z)/2
def test_rewrite():
assert besselj(n, z).rewrite(jn) == sqrt(2*z/pi)*jn(n - S.Half, z)
assert bessely(n, z).rewrite(yn) == sqrt(2*z/pi)*yn(n - S.Half, z)
assert besseli(n, z).rewrite(besselj) == \
exp(-I*n*pi/2)*besselj(n, polar_lift(I)*z)
assert besselj(n, z).rewrite(besseli) == \
exp(I*n*pi/2)*besseli(n, polar_lift(-I)*z)
nu = randcplx()
assert tn(besselj(nu, z), besselj(nu, z).rewrite(besseli), z)
assert tn(besselj(nu, z), besselj(nu, z).rewrite(bessely), z)
assert tn(besseli(nu, z), besseli(nu, z).rewrite(besselj), z)
assert tn(besseli(nu, z), besseli(nu, z).rewrite(bessely), z)
assert tn(bessely(nu, z), bessely(nu, z).rewrite(besselj), z)
assert tn(bessely(nu, z), bessely(nu, z).rewrite(besseli), z)
assert tn(besselk(nu, z), besselk(nu, z).rewrite(besselj), z)
assert tn(besselk(nu, z), besselk(nu, z).rewrite(besseli), z)
assert tn(besselk(nu, z), besselk(nu, z).rewrite(bessely), z)
# check that a rewrite was triggered, when the order is set to a generic
# symbol 'nu'
assert yn(nu, z) != yn(nu, z).rewrite(jn)
assert hn1(nu, z) != hn1(nu, z).rewrite(jn)
assert hn2(nu, z) != hn2(nu, z).rewrite(jn)
assert jn(nu, z) != jn(nu, z).rewrite(yn)
assert hn1(nu, z) != hn1(nu, z).rewrite(yn)
assert hn2(nu, z) != hn2(nu, z).rewrite(yn)
# rewriting spherical bessel functions (SBFs) w.r.t. besselj, bessely is
# not allowed if a generic symbol 'nu' is used as the order of the SBFs
# to avoid inconsistencies (the order of bessel[jy] is allowed to be
# complex-valued, whereas SBFs are defined only for integer orders)
order = nu
for f in (besselj, bessely):
assert hn1(order, z) == hn1(order, z).rewrite(f)
assert hn2(order, z) == hn2(order, z).rewrite(f)
assert jn(order, z).rewrite(besselj) == sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(order + S.Half, z)/2
assert jn(order, z).rewrite(bessely) == (-1)**nu*sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(-order - S.Half, z)/2
# for integral orders rewriting SBFs w.r.t bessel[jy] is allowed
N = Symbol('n', integer=True)
ri = randint(-11, 10)
for order in (ri, N):
for f in (besselj, bessely):
assert yn(order, z) != yn(order, z).rewrite(f)
assert jn(order, z) != jn(order, z).rewrite(f)
assert hn1(order, z) != hn1(order, z).rewrite(f)
assert hn2(order, z) != hn2(order, z).rewrite(f)
for func, refunc in product((yn, jn, hn1, hn2),
(jn, yn, besselj, bessely)):
assert tn(func(ri, z), func(ri, z).rewrite(refunc), z)
def test_expand():
assert expand_func(besselj(S.Half, z).rewrite(jn)) == \
sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z))
assert expand_func(bessely(S.Half, z).rewrite(yn)) == \
-sqrt(2)*cos(z)/(sqrt(pi)*sqrt(z))
# XXX: teach sin/cos to work around arguments like
# x*exp_polar(I*pi*n/2). Then change besselsimp -> expand_func
assert besselsimp(besselj(S.Half, z)) == sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z))
assert besselsimp(besselj(Rational(-1, 2), z)) == sqrt(2)*cos(z)/(sqrt(pi)*sqrt(z))
assert besselsimp(besselj(Rational(5, 2), z)) == \
-sqrt(2)*(z**2*sin(z) + 3*z*cos(z) - 3*sin(z))/(sqrt(pi)*z**Rational(5, 2))
assert besselsimp(besselj(Rational(-5, 2), z)) == \
-sqrt(2)*(z**2*cos(z) - 3*z*sin(z) - 3*cos(z))/(sqrt(pi)*z**Rational(5, 2))
assert besselsimp(bessely(S.Half, z)) == \
-(sqrt(2)*cos(z))/(sqrt(pi)*sqrt(z))
assert besselsimp(bessely(Rational(-1, 2), z)) == sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z))
assert besselsimp(bessely(Rational(5, 2), z)) == \
sqrt(2)*(z**2*cos(z) - 3*z*sin(z) - 3*cos(z))/(sqrt(pi)*z**Rational(5, 2))
assert besselsimp(bessely(Rational(-5, 2), z)) == \
-sqrt(2)*(z**2*sin(z) + 3*z*cos(z) - 3*sin(z))/(sqrt(pi)*z**Rational(5, 2))
assert besselsimp(besseli(S.Half, z)) == sqrt(2)*sinh(z)/(sqrt(pi)*sqrt(z))
assert besselsimp(besseli(Rational(-1, 2), z)) == \
sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z))
assert besselsimp(besseli(Rational(5, 2), z)) == \
sqrt(2)*(z**2*sinh(z) - 3*z*cosh(z) + 3*sinh(z))/(sqrt(pi)*z**Rational(5, 2))
assert besselsimp(besseli(Rational(-5, 2), z)) == \
sqrt(2)*(z**2*cosh(z) - 3*z*sinh(z) + 3*cosh(z))/(sqrt(pi)*z**Rational(5, 2))
assert besselsimp(besselk(S.Half, z)) == \
besselsimp(besselk(Rational(-1, 2), z)) == sqrt(pi)*exp(-z)/(sqrt(2)*sqrt(z))
assert besselsimp(besselk(Rational(5, 2), z)) == \
besselsimp(besselk(Rational(-5, 2), z)) == \
sqrt(2)*sqrt(pi)*(z**2 + 3*z + 3)*exp(-z)/(2*z**Rational(5, 2))
n = Symbol('n', integer=True, positive=True)
assert expand_func(besseli(n + 2, z)) == \
besseli(n, z) + (-2*n - 2)*(-2*n*besseli(n, z)/z + besseli(n - 1, z))/z
assert expand_func(besselj(n + 2, z)) == \
-besselj(n, z) + (2*n + 2)*(2*n*besselj(n, z)/z - besselj(n - 1, z))/z
assert expand_func(besselk(n + 2, z)) == \
besselk(n, z) + (2*n + 2)*(2*n*besselk(n, z)/z + besselk(n - 1, z))/z
assert expand_func(bessely(n + 2, z)) == \
-bessely(n, z) + (2*n + 2)*(2*n*bessely(n, z)/z - bessely(n - 1, z))/z
assert expand_func(besseli(n + S.Half, z).rewrite(jn)) == \
(sqrt(2)*sqrt(z)*exp(-I*pi*(n + S.Half)/2) *
exp_polar(I*pi/4)*jn(n, z*exp_polar(I*pi/2))/sqrt(pi))
assert expand_func(besselj(n + S.Half, z).rewrite(jn)) == \
sqrt(2)*sqrt(z)*jn(n, z)/sqrt(pi)
r = Symbol('r', real=True)
p = Symbol('p', positive=True)
i = Symbol('i', integer=True)
for besselx in [besselj, bessely, besseli, besselk]:
assert besselx(i, p).is_extended_real is True
assert besselx(i, x).is_extended_real is None
assert besselx(x, z).is_extended_real is None
for besselx in [besselj, besseli]:
assert besselx(i, r).is_extended_real is True
for besselx in [bessely, besselk]:
assert besselx(i, r).is_extended_real is None
for besselx in [besselj, bessely, besseli, besselk]:
assert expand_func(besselx(oo, x)) == besselx(oo, x, evaluate=False)
assert expand_func(besselx(-oo, x)) == besselx(-oo, x, evaluate=False)
@slow
def test_slow_expand():
def check(eq, ans):
return tn(eq, ans) and eq == ans
rn = randcplx(a=1, b=0, d=0, c=2)
for besselx in [besselj, bessely, besseli, besselk]:
ri = S(2*randint(-11, 10) + 1) / 2 # half integer in [-21/2, 21/2]
assert tn(besselsimp(besselx(ri, z)), besselx(ri, z))
assert check(expand_func(besseli(rn, x)),
besseli(rn - 2, x) - 2*(rn - 1)*besseli(rn - 1, x)/x)
assert check(expand_func(besseli(-rn, x)),
besseli(-rn + 2, x) + 2*(-rn + 1)*besseli(-rn + 1, x)/x)
assert check(expand_func(besselj(rn, x)),
-besselj(rn - 2, x) + 2*(rn - 1)*besselj(rn - 1, x)/x)
assert check(expand_func(besselj(-rn, x)),
-besselj(-rn + 2, x) + 2*(-rn + 1)*besselj(-rn + 1, x)/x)
assert check(expand_func(besselk(rn, x)),
besselk(rn - 2, x) + 2*(rn - 1)*besselk(rn - 1, x)/x)
assert check(expand_func(besselk(-rn, x)),
besselk(-rn + 2, x) - 2*(-rn + 1)*besselk(-rn + 1, x)/x)
assert check(expand_func(bessely(rn, x)),
-bessely(rn - 2, x) + 2*(rn - 1)*bessely(rn - 1, x)/x)
assert check(expand_func(bessely(-rn, x)),
-bessely(-rn + 2, x) + 2*(-rn + 1)*bessely(-rn + 1, x)/x)
def test_fn():
x, z = symbols("x z")
assert fn(1, z) == 1/z**2
assert fn(2, z) == -1/z + 3/z**3
assert fn(3, z) == -6/z**2 + 15/z**4
assert fn(4, z) == 1/z - 45/z**3 + 105/z**5
def mjn(n, z):
return expand_func(jn(n, z))
def myn(n, z):
return expand_func(yn(n, z))
def test_jn():
z = symbols("z")
assert jn(0, 0) == 1
assert jn(1, 0) == 0
assert jn(-1, 0) == S.ComplexInfinity
assert jn(z, 0) == jn(z, 0, evaluate=False)
assert jn(0, oo) == 0
assert jn(0, -oo) == 0
assert mjn(0, z) == sin(z)/z
assert mjn(1, z) == sin(z)/z**2 - cos(z)/z
assert mjn(2, z) == (3/z**3 - 1/z)*sin(z) - (3/z**2) * cos(z)
assert mjn(3, z) == (15/z**4 - 6/z**2)*sin(z) + (1/z - 15/z**3)*cos(z)
assert mjn(4, z) == (1/z + 105/z**5 - 45/z**3)*sin(z) + \
(-105/z**4 + 10/z**2)*cos(z)
assert mjn(5, z) == (945/z**6 - 420/z**4 + 15/z**2)*sin(z) + \
(-1/z - 945/z**5 + 105/z**3)*cos(z)
assert mjn(6, z) == (-1/z + 10395/z**7 - 4725/z**5 + 210/z**3)*sin(z) + \
(-10395/z**6 + 1260/z**4 - 21/z**2)*cos(z)
assert expand_func(jn(n, z)) == jn(n, z)
# SBFs not defined for complex-valued orders
assert jn(2+3j, 5.2+0.3j).evalf() == jn(2+3j, 5.2+0.3j)
assert eq([jn(2, 5.2+0.3j).evalf(10)],
[0.09941975672 - 0.05452508024*I])
def test_yn():
z = symbols("z")
assert myn(0, z) == -cos(z)/z
assert myn(1, z) == -cos(z)/z**2 - sin(z)/z
assert myn(2, z) == -((3/z**3 - 1/z)*cos(z) + (3/z**2)*sin(z))
assert expand_func(yn(n, z)) == yn(n, z)
# SBFs not defined for complex-valued orders
assert yn(2+3j, 5.2+0.3j).evalf() == yn(2+3j, 5.2+0.3j)
assert eq([yn(2, 5.2+0.3j).evalf(10)],
[0.185250342 + 0.01489557397*I])
def test_sympify_yn():
assert S(15) in myn(3, pi).atoms()
assert myn(3, pi) == 15/pi**4 - 6/pi**2
def eq(a, b, tol=1e-6):
for u, v in zip(a, b):
if not (abs(u - v) < tol):
return False
return True
def test_jn_zeros():
assert eq(jn_zeros(0, 4), [3.141592, 6.283185, 9.424777, 12.566370])
assert eq(jn_zeros(1, 4), [4.493409, 7.725251, 10.904121, 14.066193])
assert eq(jn_zeros(2, 4), [5.763459, 9.095011, 12.322940, 15.514603])
assert eq(jn_zeros(3, 4), [6.987932, 10.417118, 13.698023, 16.923621])
assert eq(jn_zeros(4, 4), [8.182561, 11.704907, 15.039664, 18.301255])
def test_bessel_eval():
n, m, k = Symbol('n', integer=True), Symbol('m'), Symbol('k', integer=True, zero=False)
for f in [besselj, besseli]:
assert f(0, 0) is S.One
assert f(2.1, 0) is S.Zero
assert f(-3, 0) is S.Zero
assert f(-10.2, 0) is S.ComplexInfinity
assert f(1 + 3*I, 0) is S.Zero
assert f(-3 + I, 0) is S.ComplexInfinity
assert f(-2*I, 0) is S.NaN
assert f(n, 0) != S.One and f(n, 0) != S.Zero
assert f(m, 0) != S.One and f(m, 0) != S.Zero
assert f(k, 0) is S.Zero
assert bessely(0, 0) is S.NegativeInfinity
assert besselk(0, 0) is S.Infinity
for f in [bessely, besselk]:
assert f(1 + I, 0) is S.ComplexInfinity
assert f(I, 0) is S.NaN
for f in [besselj, bessely]:
assert f(m, S.Infinity) is S.Zero
assert f(m, S.NegativeInfinity) is S.Zero
for f in [besseli, besselk]:
assert f(m, I*S.Infinity) is S.Zero
assert f(m, I*S.NegativeInfinity) is S.Zero
for f in [besseli, besselk]:
assert f(-4, z) == f(4, z)
assert f(-3, z) == f(3, z)
assert f(-n, z) == f(n, z)
assert f(-m, z) != f(m, z)
for f in [besselj, bessely]:
assert f(-4, z) == f(4, z)
assert f(-3, z) == -f(3, z)
assert f(-n, z) == (-1)**n*f(n, z)
assert f(-m, z) != (-1)**m*f(m, z)
for f in [besselj, besseli]:
assert f(m, -z) == (-z)**m*z**(-m)*f(m, z)
assert besseli(2, -z) == besseli(2, z)
assert besseli(3, -z) == -besseli(3, z)
assert besselj(0, -z) == besselj(0, z)
assert besselj(1, -z) == -besselj(1, z)
assert besseli(0, I*z) == besselj(0, z)
assert besseli(1, I*z) == I*besselj(1, z)
assert besselj(3, I*z) == -I*besseli(3, z)
def test_bessel_nan():
# FIXME: could have these return NaN; for now just fix infinite recursion
for f in [besselj, bessely, besseli, besselk, hankel1, hankel2, yn, jn]:
assert f(1, S.NaN) == f(1, S.NaN, evaluate=False)
def test_meromorphic():
assert besselj(2, x).is_meromorphic(x, 1) == True
assert besselj(2, x).is_meromorphic(x, 0) == True
assert besselj(2, x).is_meromorphic(x, oo) == False
assert besselj(S(2)/3, x).is_meromorphic(x, 1) == True
assert besselj(S(2)/3, x).is_meromorphic(x, 0) == False
assert besselj(S(2)/3, x).is_meromorphic(x, oo) == False
assert besselj(x, 2*x).is_meromorphic(x, 2) == False
assert besselk(0, x).is_meromorphic(x, 1) == True
assert besselk(2, x).is_meromorphic(x, 0) == True
assert besseli(0, x).is_meromorphic(x, 1) == True
assert besseli(2, x).is_meromorphic(x, 0) == True
assert bessely(0, x).is_meromorphic(x, 1) == True
assert bessely(0, x).is_meromorphic(x, 0) == False
assert bessely(2, x).is_meromorphic(x, 0) == True
assert hankel1(3, x**2 + 2*x).is_meromorphic(x, 1) == True
assert hankel1(0, x).is_meromorphic(x, 0) == False
assert hankel2(11, 4).is_meromorphic(x, 5) == True
assert hn1(6, 7*x**3 + 4).is_meromorphic(x, 7) == True
assert hn2(3, 2*x).is_meromorphic(x, 9) == True
assert jn(5, 2*x + 7).is_meromorphic(x, 4) == True
assert yn(8, x**2 + 11).is_meromorphic(x, 6) == True
def test_conjugate():
n = Symbol('n')
z = Symbol('z', extended_real=False)
x = Symbol('x', extended_real=True)
y = Symbol('y', real=True, positive=True)
t = Symbol('t', negative=True)
for f in [besseli, besselj, besselk, bessely, hankel1, hankel2]:
assert f(n, -1).conjugate() != f(conjugate(n), -1)
assert f(n, x).conjugate() != f(conjugate(n), x)
assert f(n, t).conjugate() != f(conjugate(n), t)
rz = randcplx(b=0.5)
for f in [besseli, besselj, besselk, bessely]:
assert f(n, 1 + I).conjugate() == f(conjugate(n), 1 - I)
assert f(n, 0).conjugate() == f(conjugate(n), 0)
assert f(n, 1).conjugate() == f(conjugate(n), 1)
assert f(n, z).conjugate() == f(conjugate(n), conjugate(z))
assert f(n, y).conjugate() == f(conjugate(n), y)
assert tn(f(n, rz).conjugate(), f(conjugate(n), conjugate(rz)))
assert hankel1(n, 1 + I).conjugate() == hankel2(conjugate(n), 1 - I)
assert hankel1(n, 0).conjugate() == hankel2(conjugate(n), 0)
assert hankel1(n, 1).conjugate() == hankel2(conjugate(n), 1)
assert hankel1(n, y).conjugate() == hankel2(conjugate(n), y)
assert hankel1(n, z).conjugate() == hankel2(conjugate(n), conjugate(z))
assert tn(hankel1(n, rz).conjugate(), hankel2(conjugate(n), conjugate(rz)))
assert hankel2(n, 1 + I).conjugate() == hankel1(conjugate(n), 1 - I)
assert hankel2(n, 0).conjugate() == hankel1(conjugate(n), 0)
assert hankel2(n, 1).conjugate() == hankel1(conjugate(n), 1)
assert hankel2(n, y).conjugate() == hankel1(conjugate(n), y)
assert hankel2(n, z).conjugate() == hankel1(conjugate(n), conjugate(z))
assert tn(hankel2(n, rz).conjugate(), hankel1(conjugate(n), conjugate(rz)))
def test_branching():
assert besselj(polar_lift(k), x) == besselj(k, x)
assert besseli(polar_lift(k), x) == besseli(k, x)
n = Symbol('n', integer=True)
assert besselj(n, exp_polar(2*pi*I)*x) == besselj(n, x)
assert besselj(n, polar_lift(x)) == besselj(n, x)
assert besseli(n, exp_polar(2*pi*I)*x) == besseli(n, x)
assert besseli(n, polar_lift(x)) == besseli(n, x)
def tn(func, s):
from random import uniform
c = uniform(1, 5)
expr = func(s, c*exp_polar(I*pi)) - func(s, c*exp_polar(-I*pi))
eps = 1e-15
expr2 = func(s + eps, -c + eps*I) - func(s + eps, -c - eps*I)
return abs(expr.n() - expr2.n()).n() < 1e-10
nu = Symbol('nu')
assert besselj(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besselj(nu, x)
assert besseli(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besseli(nu, x)
assert tn(besselj, 2)
assert tn(besselj, pi)
assert tn(besselj, I)
assert tn(besseli, 2)
assert tn(besseli, pi)
assert tn(besseli, I)
def test_airy_base():
z = Symbol('z')
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert conjugate(airyai(z)) == airyai(conjugate(z))
assert airyai(x).is_extended_real
assert airyai(x+I*y).as_real_imag() == (
airyai(x - I*y)/2 + airyai(x + I*y)/2,
I*(airyai(x - I*y) - airyai(x + I*y))/2)
def test_airyai():
z = Symbol('z', real=False)
t = Symbol('t', negative=True)
p = Symbol('p', positive=True)
assert isinstance(airyai(z), airyai)
assert airyai(0) == 3**Rational(1, 3)/(3*gamma(Rational(2, 3)))
assert airyai(oo) == 0
assert airyai(-oo) == 0
assert diff(airyai(z), z) == airyaiprime(z)
assert series(airyai(z), z, 0, 3) == (
3**Rational(5, 6)*gamma(Rational(1, 3))/(6*pi) - 3**Rational(1, 6)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3))
assert airyai(z).rewrite(hyper) == (
-3**Rational(2, 3)*z*hyper((), (Rational(4, 3),), z**3/9)/(3*gamma(Rational(1, 3))) +
3**Rational(1, 3)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3))))
assert isinstance(airyai(z).rewrite(besselj), airyai)
assert airyai(t).rewrite(besselj) == (
sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) +
besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3)
assert airyai(z).rewrite(besseli) == (
-z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(1, 3)) +
(z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3)
assert airyai(p).rewrite(besseli) == (
sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) -
besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3)
assert expand_func(airyai(2*(3*z**5)**Rational(1, 3))) == (
-sqrt(3)*(-1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/6 +
(1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2)
def test_airybi():
z = Symbol('z', real=False)
t = Symbol('t', negative=True)
p = Symbol('p', positive=True)
assert isinstance(airybi(z), airybi)
assert airybi(0) == 3**Rational(5, 6)/(3*gamma(Rational(2, 3)))
assert airybi(oo) is oo
assert airybi(-oo) == 0
assert diff(airybi(z), z) == airybiprime(z)
assert series(airybi(z), z, 0, 3) == (
3**Rational(1, 3)*gamma(Rational(1, 3))/(2*pi) + 3**Rational(2, 3)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3))
assert airybi(z).rewrite(hyper) == (
3**Rational(1, 6)*z*hyper((), (Rational(4, 3),), z**3/9)/gamma(Rational(1, 3)) +
3**Rational(5, 6)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3))))
assert isinstance(airybi(z).rewrite(besselj), airybi)
assert airyai(t).rewrite(besselj) == (
sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) +
besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3)
assert airybi(z).rewrite(besseli) == (
sqrt(3)*(z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(1, 3) +
(z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3))/3)
assert airybi(p).rewrite(besseli) == (
sqrt(3)*sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) +
besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3)
assert expand_func(airybi(2*(3*z**5)**Rational(1, 3))) == (
sqrt(3)*(1 - (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2 +
(1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/2)
def test_airyaiprime():
z = Symbol('z', real=False)
t = Symbol('t', negative=True)
p = Symbol('p', positive=True)
assert isinstance(airyaiprime(z), airyaiprime)
assert airyaiprime(0) == -3**Rational(2, 3)/(3*gamma(Rational(1, 3)))
assert airyaiprime(oo) == 0
assert diff(airyaiprime(z), z) == z*airyai(z)
assert series(airyaiprime(z), z, 0, 3) == (
-3**Rational(2, 3)/(3*gamma(Rational(1, 3))) + 3**Rational(1, 3)*z**2/(6*gamma(Rational(2, 3))) + O(z**3))
assert airyaiprime(z).rewrite(hyper) == (
3**Rational(1, 3)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) -
3**Rational(2, 3)*hyper((), (Rational(1, 3),), z**3/9)/(3*gamma(Rational(1, 3))))
assert isinstance(airyaiprime(z).rewrite(besselj), airyaiprime)
assert airyai(t).rewrite(besselj) == (
sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) +
besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3)
assert airyaiprime(z).rewrite(besseli) == (
z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(2, 3)) -
(z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3)
assert airyaiprime(p).rewrite(besseli) == (
p*(-besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3)
assert expand_func(airyaiprime(2*(3*z**5)**Rational(1, 3))) == (
sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/6 +
(z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2)
def test_airybiprime():
z = Symbol('z', real=False)
t = Symbol('t', negative=True)
p = Symbol('p', positive=True)
assert isinstance(airybiprime(z), airybiprime)
assert airybiprime(0) == 3**Rational(1, 6)/gamma(Rational(1, 3))
assert airybiprime(oo) is oo
assert airybiprime(-oo) == 0
assert diff(airybiprime(z), z) == z*airybi(z)
assert series(airybiprime(z), z, 0, 3) == (
3**Rational(1, 6)/gamma(Rational(1, 3)) + 3**Rational(5, 6)*z**2/(6*gamma(Rational(2, 3))) + O(z**3))
assert airybiprime(z).rewrite(hyper) == (
3**Rational(5, 6)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) +
3**Rational(1, 6)*hyper((), (Rational(1, 3),), z**3/9)/gamma(Rational(1, 3)))
assert isinstance(airybiprime(z).rewrite(besselj), airybiprime)
assert airyai(t).rewrite(besselj) == (
sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) +
besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3)
assert airybiprime(z).rewrite(besseli) == (
sqrt(3)*(z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(2, 3) +
(z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-2, 3), 2*z**Rational(3, 2)/3))/3)
assert airybiprime(p).rewrite(besseli) == (
sqrt(3)*p*(besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3)
assert expand_func(airybiprime(2*(3*z**5)**Rational(1, 3))) == (
sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2 +
(z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2)
def test_marcumq():
m = Symbol('m')
a = Symbol('a')
b = Symbol('b')
assert marcumq(0, 0, 0) == 0
assert marcumq(m, 0, b) == uppergamma(m, b**2/2)/gamma(m)
assert marcumq(2, 0, 5) == 27*exp(Rational(-25, 2))/2
assert marcumq(0, a, 0) == 1 - exp(-a**2/2)
assert marcumq(0, pi, 0) == 1 - exp(-pi**2/2)
assert marcumq(1, a, a) == S.Half + exp(-a**2)*besseli(0, a**2)/2
assert marcumq(2, a, a) == S.Half + exp(-a**2)*besseli(0, a**2)/2 + exp(-a**2)*besseli(1, a**2)
assert diff(marcumq(1, a, 3), a) == a*(-marcumq(1, a, 3) + marcumq(2, a, 3))
assert diff(marcumq(2, 3, b), b) == -b**2*exp(-b**2/2 - Rational(9, 2))*besseli(1, 3*b)/3
x = Symbol('x')
assert marcumq(2, 3, 4).rewrite(Integral, x=x) == \
Integral(x**2*exp(-x**2/2 - Rational(9, 2))*besseli(1, 3*x), (x, 4, oo))/3
assert eq([marcumq(5, -2, 3).rewrite(Integral).evalf(10)],
[0.7905769565])
k = Symbol('k')
assert marcumq(-3, -5, -7).rewrite(Sum, k=k) == \
exp(-37)*Sum((Rational(5, 7))**k*besseli(k, 35), (k, 4, oo))
assert eq([marcumq(1, 3, 1).rewrite(Sum).evalf(10)],
[0.9891705502])
assert marcumq(1, a, a, evaluate=False).rewrite(besseli) == S.Half + exp(-a**2)*besseli(0, a**2)/2
assert marcumq(2, a, a, evaluate=False).rewrite(besseli) == S.Half + exp(-a**2)*besseli(0, a**2)/2 + \
exp(-a**2)*besseli(1, a**2)
assert marcumq(3, a, a).rewrite(besseli) == (besseli(1, a**2) + besseli(2, a**2))*exp(-a**2) + \
S.Half + exp(-a**2)*besseli(0, a**2)/2
assert marcumq(5, 8, 8).rewrite(besseli) == exp(-64)*besseli(0, 64)/2 + \
(besseli(4, 64) + besseli(3, 64) + besseli(2, 64) + besseli(1, 64))*exp(-64) + S.Half
assert marcumq(m, a, a).rewrite(besseli) == marcumq(m, a, a)
x = Symbol('x', integer=True)
assert marcumq(x, a, a).rewrite(besseli) == marcumq(x, a, a)
|
3f0887de9d73c6fae0e0e4b8717167533ba59b108fe465ef21b2801e40912d38 | from sympy.core.add import Add
from sympy.core.assumptions import check_assumptions
from sympy.core.containers import Tuple
from sympy.core.compatibility import as_int, is_sequence, ordered
from sympy.core.exprtools import factor_terms
from sympy.core.function import _mexpand
from sympy.core.mul import Mul
from sympy.core.numbers import Rational
from sympy.core.numbers import igcdex, ilcm, igcd
from sympy.core.power import integer_nthroot, isqrt
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import Symbol, symbols
from sympy.core.sympify import _sympify
from sympy.functions.elementary.complexes import sign
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices.dense import MutableDenseMatrix as Matrix
from sympy.ntheory.factor_ import (
divisors, factorint, multiplicity, perfect_power)
from sympy.ntheory.generate import nextprime
from sympy.ntheory.primetest import is_square, isprime
from sympy.ntheory.residue_ntheory import sqrt_mod
from sympy.polys.polyerrors import GeneratorsNeeded
from sympy.polys.polytools import Poly, factor_list
from sympy.simplify.simplify import signsimp
from sympy.solvers.solveset import solveset_real
from sympy.utilities import default_sort_key, numbered_symbols
from sympy.utilities.misc import filldedent
# these are imported with 'from sympy.solvers.diophantine import *
__all__ = ['diophantine', 'classify_diop']
class DiophantineSolutionSet(set):
"""
Container for a set of solutions to a particular diophantine equation.
The base representation is a set of tuples representing each of the solutions.
Parameters
==========
symbols : list
List of free symbols in the original equation.
parameters: list
List of parameters to be used in the solution.
Examples
========
Adding solutions:
>>> from sympy.solvers.diophantine.diophantine import DiophantineSolutionSet
>>> from sympy.abc import x, y, t, u
>>> s1 = DiophantineSolutionSet([x, y], [t, u])
>>> s1
set()
>>> s1.add((2, 3))
>>> s1.add((-1, u))
>>> s1
{(-1, u), (2, 3)}
>>> s2 = DiophantineSolutionSet([x, y], [t, u])
>>> s2.add((3, 4))
>>> s1.update(*s2)
>>> s1
{(-1, u), (2, 3), (3, 4)}
Conversion of solutions into dicts:
>>> list(s1.dict_iterator())
[{x: -1, y: u}, {x: 2, y: 3}, {x: 3, y: 4}]
Substituting values:
>>> s3 = DiophantineSolutionSet([x, y], [t, u])
>>> s3.add((t**2, t + u))
>>> s3
{(t**2, t + u)}
>>> s3.subs({t: 2, u: 3})
{(4, 5)}
>>> s3.subs(t, -1)
{(1, u - 1)}
>>> s3.subs(t, 3)
{(9, u + 3)}
Evaluation at specific values. Positional arguments are given in the same order as the parameters:
>>> s3(-2, 3)
{(4, 1)}
>>> s3(5)
{(25, u + 5)}
>>> s3(None, 2)
{(t**2, t + 2)}
"""
def __init__(self, symbols_seq, parameters):
super().__init__()
if not is_sequence(symbols_seq):
raise ValueError("Symbols must be given as a sequence.")
if not is_sequence(parameters):
raise ValueError("Parameters must be given as a sequence.")
self.symbols = tuple(symbols_seq)
self.parameters = tuple(parameters)
def add(self, solution):
if len(solution) != len(self.symbols):
raise ValueError("Solution should have a length of %s, not %s" % (len(self.symbols), len(solution)))
super().add(Tuple(*solution))
def update(self, *solutions):
for solution in solutions:
self.add(solution)
def dict_iterator(self):
for solution in ordered(self):
yield dict(zip(self.symbols, solution))
def subs(self, *args, **kwargs):
result = DiophantineSolutionSet(self.symbols, self.parameters)
for solution in self:
result.add(solution.subs(*args, **kwargs))
return result
def __call__(self, *args):
if len(args) > len(self.parameters):
raise ValueError("Evaluation should have at most %s values, not %s" % (len(self.parameters), len(args)))
return self.subs(list(zip(self.parameters, args)))
class DiophantineEquationType:
"""
Internal representation of a particular diophantine equation type.
Parameters
==========
equation :
The diophantine equation that is being solved.
free_symbols : list (optional)
The symbols being solved for.
Attributes
==========
total_degree :
The maximum of the degrees of all terms in the equation
homogeneous :
Does the equation contain a term of degree 0
homogeneous_order :
Does the equation contain any coefficient that is in the symbols being solved for
dimension :
The number of symbols being solved for
"""
name = None # type: str
def __init__(self, equation, free_symbols=None):
self.equation = _sympify(equation).expand(force=True)
if free_symbols is not None:
self.free_symbols = free_symbols
else:
self.free_symbols = list(self.equation.free_symbols)
self.free_symbols.sort(key=default_sort_key)
if not self.free_symbols:
raise ValueError('equation should have 1 or more free symbols')
self.coeff = self.equation.as_coefficients_dict()
if not all(_is_int(c) for c in self.coeff.values()):
raise TypeError("Coefficients should be Integers")
self.total_degree = Poly(self.equation).total_degree()
self.homogeneous = 1 not in self.coeff
self.homogeneous_order = not (set(self.coeff) & set(self.free_symbols))
self.dimension = len(self.free_symbols)
self._parameters = None
def matches(self):
"""
Determine whether the given equation can be matched to the particular equation type.
"""
return False
@property
def n_parameters(self):
return self.dimension
@property
def parameters(self):
if self._parameters is None:
self._parameters = symbols('t_:%i' % (self.n_parameters,), integer=True)
return self._parameters
def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet:
raise NotImplementedError('No solver has been written for %s.' % self.name)
def pre_solve(self, parameters=None):
if not self.matches():
raise ValueError("This equation does not match the %s equation type." % self.name)
if parameters is not None:
if len(parameters) != self.n_parameters:
raise ValueError("Expected %s parameter(s) but got %s" % (self.n_parameters, len(parameters)))
self._parameters = parameters
class Univariate(DiophantineEquationType):
"""
Representation of a univariate diophantine equation.
A univariate diophantine equation is an equation of the form
`a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are
integer constants and `x` is an integer variable.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import Univariate
>>> from sympy.abc import x
>>> Univariate((x - 2)*(x - 3)**2).solve() # solves equation (x - 2)*(x - 3)**2 == 0
{(2,), (3,)}
"""
name = 'univariate'
def matches(self):
return self.dimension == 1
def solve(self, parameters=None, limit=None):
self.pre_solve(parameters)
result = DiophantineSolutionSet(self.free_symbols, parameters=self.parameters)
for i in solveset_real(self.equation, self.free_symbols[0]).intersect(S.Integers):
result.add((i,))
return result
class Linear(DiophantineEquationType):
"""
Representation of a linear diophantine equation.
A linear diophantine equation is an equation of the form `a_{1}x_{1} +
a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are
integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import Linear
>>> from sympy.abc import x, y, z
>>> l1 = Linear(2*x - 3*y - 5)
>>> l1.matches() # is this equation linear
True
>>> l1.solve() # solves equation 2*x - 3*y - 5 == 0
{(3*t_0 - 5, 2*t_0 - 5)}
Here x = -3*t_0 - 5 and y = -2*t_0 - 5
>>> Linear(2*x - 3*y - 4*z -3).solve()
{(t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3)}
"""
name = 'linear'
def matches(self):
return self.total_degree == 1
def solve(self, parameters=None, limit=None):
self.pre_solve(parameters)
coeff = self.coeff
var = self.free_symbols
if 1 in coeff:
# negate coeff[] because input is of the form: ax + by + c == 0
# but is used as: ax + by == -c
c = -coeff[1]
else:
c = 0
result = DiophantineSolutionSet(var, parameters=self.parameters)
params = result.parameters
if len(var) == 1:
q, r = divmod(c, coeff[var[0]])
if not r:
result.add((q,))
return result
else:
return result
'''
base_solution_linear() can solve diophantine equations of the form:
a*x + b*y == c
We break down multivariate linear diophantine equations into a
series of bivariate linear diophantine equations which can then
be solved individually by base_solution_linear().
Consider the following:
a_0*x_0 + a_1*x_1 + a_2*x_2 == c
which can be re-written as:
a_0*x_0 + g_0*y_0 == c
where
g_0 == gcd(a_1, a_2)
and
y == (a_1*x_1)/g_0 + (a_2*x_2)/g_0
This leaves us with two binary linear diophantine equations.
For the first equation:
a == a_0
b == g_0
c == c
For the second:
a == a_1/g_0
b == a_2/g_0
c == the solution we find for y_0 in the first equation.
The arrays A and B are the arrays of integers used for
'a' and 'b' in each of the n-1 bivariate equations we solve.
'''
A = [coeff[v] for v in var]
B = []
if len(var) > 2:
B.append(igcd(A[-2], A[-1]))
A[-2] = A[-2] // B[0]
A[-1] = A[-1] // B[0]
for i in range(len(A) - 3, 0, -1):
gcd = igcd(B[0], A[i])
B[0] = B[0] // gcd
A[i] = A[i] // gcd
B.insert(0, gcd)
B.append(A[-1])
'''
Consider the trivariate linear equation:
4*x_0 + 6*x_1 + 3*x_2 == 2
This can be re-written as:
4*x_0 + 3*y_0 == 2
where
y_0 == 2*x_1 + x_2
(Note that gcd(3, 6) == 3)
The complete integral solution to this equation is:
x_0 == 2 + 3*t_0
y_0 == -2 - 4*t_0
where 't_0' is any integer.
Now that we have a solution for 'x_0', find 'x_1' and 'x_2':
2*x_1 + x_2 == -2 - 4*t_0
We can then solve for '-2' and '-4' independently,
and combine the results:
2*x_1a + x_2a == -2
x_1a == 0 + t_0
x_2a == -2 - 2*t_0
2*x_1b + x_2b == -4*t_0
x_1b == 0*t_0 + t_1
x_2b == -4*t_0 - 2*t_1
==>
x_1 == t_0 + t_1
x_2 == -2 - 6*t_0 - 2*t_1
where 't_0' and 't_1' are any integers.
Note that:
4*(2 + 3*t_0) + 6*(t_0 + t_1) + 3*(-2 - 6*t_0 - 2*t_1) == 2
for any integral values of 't_0', 't_1'; as required.
This method is generalised for many variables, below.
'''
solutions = []
for i in range(len(B)):
tot_x, tot_y = [], []
for j, arg in enumerate(Add.make_args(c)):
if arg.is_Integer:
# example: 5 -> k = 5
k, p = arg, S.One
pnew = params[0]
else: # arg is a Mul or Symbol
# example: 3*t_1 -> k = 3
# example: t_0 -> k = 1
k, p = arg.as_coeff_Mul()
pnew = params[params.index(p) + 1]
sol = sol_x, sol_y = base_solution_linear(k, A[i], B[i], pnew)
if p is S.One:
if None in sol:
return result
else:
# convert a + b*pnew -> a*p + b*pnew
if isinstance(sol_x, Add):
sol_x = sol_x.args[0]*p + sol_x.args[1]
if isinstance(sol_y, Add):
sol_y = sol_y.args[0]*p + sol_y.args[1]
tot_x.append(sol_x)
tot_y.append(sol_y)
solutions.append(Add(*tot_x))
c = Add(*tot_y)
solutions.append(c)
result.add(solutions)
return result
class BinaryQuadratic(DiophantineEquationType):
"""
Representation of a binary quadratic diophantine equation.
A binary quadratic diophantine equation is an equation of the
form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`, where `A, B, C, D, E,
F` are integer constants and `x` and `y` are integer variables.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.solvers.diophantine.diophantine import BinaryQuadratic
>>> b1 = BinaryQuadratic(x**3 + y**2 + 1)
>>> b1.matches()
False
>>> b2 = BinaryQuadratic(x**2 + y**2 + 2*x + 2*y + 2)
>>> b2.matches()
True
>>> b2.solve()
{(-1, -1)}
References
==========
.. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online],
Available: http://www.alpertron.com.ar/METHODS.HTM
.. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online],
Available: https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
"""
name = 'binary_quadratic'
def matches(self):
return self.total_degree == 2 and self.dimension == 2
def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet:
self.pre_solve(parameters)
var = self.free_symbols
coeff = self.coeff
x, y = var
A = coeff[x**2]
B = coeff[x*y]
C = coeff[y**2]
D = coeff[x]
E = coeff[y]
F = coeff[S.One]
A, B, C, D, E, F = [as_int(i) for i in _remove_gcd(A, B, C, D, E, F)]
# (1) Simple-Hyperbolic case: A = C = 0, B != 0
# In this case equation can be converted to (Bx + E)(By + D) = DE - BF
# We consider two cases; DE - BF = 0 and DE - BF != 0
# More details, http://www.alpertron.com.ar/METHODS.HTM#SHyperb
result = DiophantineSolutionSet(var, self.parameters)
t, u = result.parameters
discr = B**2 - 4*A*C
if A == 0 and C == 0 and B != 0:
if D*E - B*F == 0:
q, r = divmod(E, B)
if not r:
result.add((-q, t))
q, r = divmod(D, B)
if not r:
result.add((t, -q))
else:
div = divisors(D*E - B*F)
div = div + [-term for term in div]
for d in div:
x0, r = divmod(d - E, B)
if not r:
q, r = divmod(D*E - B*F, d)
if not r:
y0, r = divmod(q - D, B)
if not r:
result.add((x0, y0))
# (2) Parabolic case: B**2 - 4*A*C = 0
# There are two subcases to be considered in this case.
# sqrt(c)D - sqrt(a)E = 0 and sqrt(c)D - sqrt(a)E != 0
# More Details, http://www.alpertron.com.ar/METHODS.HTM#Parabol
elif discr == 0:
if A == 0:
s = BinaryQuadratic(self.equation, free_symbols=[y, x]).solve(parameters=[t, u])
for soln in s:
result.add((soln[1], soln[0]))
else:
g = sign(A)*igcd(A, C)
a = A // g
c = C // g
e = sign(B / A)
sqa = isqrt(a)
sqc = isqrt(c)
_c = e*sqc*D - sqa*E
if not _c:
z = symbols("z", real=True)
eq = sqa*g*z**2 + D*z + sqa*F
roots = solveset_real(eq, z).intersect(S.Integers)
for root in roots:
ans = diop_solve(sqa*x + e*sqc*y - root)
result.add((ans[0], ans[1]))
elif _is_int(c):
solve_x = lambda u: -e*sqc*g*_c*t**2 - (E + 2*e*sqc*g*u)*t \
- (e*sqc*g*u**2 + E*u + e*sqc*F) // _c
solve_y = lambda u: sqa*g*_c*t**2 + (D + 2*sqa*g*u)*t \
+ (sqa*g*u**2 + D*u + sqa*F) // _c
for z0 in range(0, abs(_c)):
# Check if the coefficients of y and x obtained are integers or not
if (divisible(sqa*g*z0**2 + D*z0 + sqa*F, _c) and
divisible(e*sqc*g*z0**2 + E*z0 + e*sqc*F, _c)):
result.add((solve_x(z0), solve_y(z0)))
# (3) Method used when B**2 - 4*A*C is a square, is described in p. 6 of the below paper
# by John P. Robertson.
# https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
elif is_square(discr):
if A != 0:
r = sqrt(discr)
u, v = symbols("u, v", integer=True)
eq = _mexpand(
4*A*r*u*v + 4*A*D*(B*v + r*u + r*v - B*u) +
2*A*4*A*E*(u - v) + 4*A*r*4*A*F)
solution = diop_solve(eq, t)
for s0, t0 in solution:
num = B*t0 + r*s0 + r*t0 - B*s0
x_0 = S(num) / (4*A*r)
y_0 = S(s0 - t0) / (2*r)
if isinstance(s0, Symbol) or isinstance(t0, Symbol):
if len(check_param(x_0, y_0, 4*A*r, parameters)) > 0:
ans = check_param(x_0, y_0, 4*A*r, parameters)
result.update(*ans)
elif x_0.is_Integer and y_0.is_Integer:
if is_solution_quad(var, coeff, x_0, y_0):
result.add((x_0, y_0))
else:
s = BinaryQuadratic(self.equation, free_symbols=var[::-1]).solve(parameters=[t, u]) # Interchange x and y
while s:
result.add(s.pop()[::-1]) # and solution <--------+
# (4) B**2 - 4*A*C > 0 and B**2 - 4*A*C not a square or B**2 - 4*A*C < 0
else:
P, Q = _transformation_to_DN(var, coeff)
D, N = _find_DN(var, coeff)
solns_pell = diop_DN(D, N)
if D < 0:
for x0, y0 in solns_pell:
for x in [-x0, x0]:
for y in [-y0, y0]:
s = P*Matrix([x, y]) + Q
try:
result.add([as_int(_) for _ in s])
except ValueError:
pass
else:
# In this case equation can be transformed into a Pell equation
solns_pell = set(solns_pell)
for X, Y in list(solns_pell):
solns_pell.add((-X, -Y))
a = diop_DN(D, 1)
T = a[0][0]
U = a[0][1]
if all(_is_int(_) for _ in P[:4] + Q[:2]):
for r, s in solns_pell:
_a = (r + s*sqrt(D))*(T + U*sqrt(D))**t
_b = (r - s*sqrt(D))*(T - U*sqrt(D))**t
x_n = _mexpand(S(_a + _b) / 2)
y_n = _mexpand(S(_a - _b) / (2*sqrt(D)))
s = P*Matrix([x_n, y_n]) + Q
result.add(s)
else:
L = ilcm(*[_.q for _ in P[:4] + Q[:2]])
k = 1
T_k = T
U_k = U
while (T_k - 1) % L != 0 or U_k % L != 0:
T_k, U_k = T_k*T + D*U_k*U, T_k*U + U_k*T
k += 1
for X, Y in solns_pell:
for i in range(k):
if all(_is_int(_) for _ in P*Matrix([X, Y]) + Q):
_a = (X + sqrt(D)*Y)*(T_k + sqrt(D)*U_k)**t
_b = (X - sqrt(D)*Y)*(T_k - sqrt(D)*U_k)**t
Xt = S(_a + _b) / 2
Yt = S(_a - _b) / (2*sqrt(D))
s = P*Matrix([Xt, Yt]) + Q
result.add(s)
X, Y = X*T + D*U*Y, X*U + Y*T
return result
class InhomogeneousTernaryQuadratic(DiophantineEquationType):
"""
Representation of an inhomogeneous ternary quadratic.
No solver is currently implemented for this equation type.
"""
name = 'inhomogeneous_ternary_quadratic'
def matches(self):
if not (self.total_degree == 2 and self.dimension == 3):
return False
if not self.homogeneous:
return False
return not self.homogeneous_order
class HomogeneousTernaryQuadraticNormal(DiophantineEquationType):
"""
Representation of a homogeneous ternary quadratic normal diophantine equation.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine.diophantine import HomogeneousTernaryQuadraticNormal
>>> HomogeneousTernaryQuadraticNormal(4*x**2 - 5*y**2 + z**2).solve()
{(1, 2, 4)}
"""
name = 'homogeneous_ternary_quadratic_normal'
def matches(self):
if not (self.total_degree == 2 and self.dimension == 3):
return False
if not self.homogeneous:
return False
if not self.homogeneous_order:
return False
nonzero = [k for k in self.coeff if self.coeff[k]]
return len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols)
def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet:
self.pre_solve(parameters)
var = self.free_symbols
coeff = self.coeff
x, y, z = var
a = coeff[x**2]
b = coeff[y**2]
c = coeff[z**2]
(sqf_of_a, sqf_of_b, sqf_of_c), (a_1, b_1, c_1), (a_2, b_2, c_2) = \
sqf_normal(a, b, c, steps=True)
A = -a_2*c_2
B = -b_2*c_2
result = DiophantineSolutionSet(var, parameters=self.parameters)
# If following two conditions are satisfied then there are no solutions
if A < 0 and B < 0:
return result
if (
sqrt_mod(-b_2*c_2, a_2) is None or
sqrt_mod(-c_2*a_2, b_2) is None or
sqrt_mod(-a_2*b_2, c_2) is None):
return result
z_0, x_0, y_0 = descent(A, B)
z_0, q = _rational_pq(z_0, abs(c_2))
x_0 *= q
y_0 *= q
x_0, y_0, z_0 = _remove_gcd(x_0, y_0, z_0)
# Holzer reduction
if sign(a) == sign(b):
x_0, y_0, z_0 = holzer(x_0, y_0, z_0, abs(a_2), abs(b_2), abs(c_2))
elif sign(a) == sign(c):
x_0, z_0, y_0 = holzer(x_0, z_0, y_0, abs(a_2), abs(c_2), abs(b_2))
else:
y_0, z_0, x_0 = holzer(y_0, z_0, x_0, abs(b_2), abs(c_2), abs(a_2))
x_0 = reconstruct(b_1, c_1, x_0)
y_0 = reconstruct(a_1, c_1, y_0)
z_0 = reconstruct(a_1, b_1, z_0)
sq_lcm = ilcm(sqf_of_a, sqf_of_b, sqf_of_c)
x_0 = abs(x_0*sq_lcm // sqf_of_a)
y_0 = abs(y_0*sq_lcm // sqf_of_b)
z_0 = abs(z_0*sq_lcm // sqf_of_c)
result.add(_remove_gcd(x_0, y_0, z_0))
return result
class HomogeneousTernaryQuadratic(DiophantineEquationType):
"""
Representation of a homogeneous ternary quadratic diophantine equation.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine.diophantine import HomogeneousTernaryQuadratic
>>> HomogeneousTernaryQuadratic(x**2 + y**2 - 3*z**2 + x*y).solve()
{(-1, 2, 1)}
>>> HomogeneousTernaryQuadratic(3*x**2 + y**2 - 3*z**2 + 5*x*y + y*z).solve()
{(3, 12, 13)}
"""
name = 'homogeneous_ternary_quadratic'
def matches(self):
if not (self.total_degree == 2 and self.dimension == 3):
return False
if not self.homogeneous:
return False
if not self.homogeneous_order:
return False
nonzero = [k for k in self.coeff if self.coeff[k]]
return not (len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols))
def solve(self, parameters=None, limit=None):
self.pre_solve(parameters)
_var = self.free_symbols
coeff = self.coeff
x, y, z = _var
var = [x, y, z]
# Equations of the form B*x*y + C*z*x + E*y*z = 0 and At least two of the
# coefficients A, B, C are non-zero.
# There are infinitely many solutions for the equation.
# Ex: (0, 0, t), (0, t, 0), (t, 0, 0)
# Equation can be re-written as y*(B*x + E*z) = -C*x*z and we can find rather
# unobvious solutions. Set y = -C and B*x + E*z = x*z. The latter can be solved by
# using methods for binary quadratic diophantine equations. Let's select the
# solution which minimizes |x| + |z|
result = DiophantineSolutionSet(var, parameters=self.parameters)
def unpack_sol(sol):
if len(sol) > 0:
return list(sol)[0]
return None, None, None
if not any(coeff[i**2] for i in var):
if coeff[x*z]:
sols = diophantine(coeff[x*y]*x + coeff[y*z]*z - x*z)
s = sols.pop()
min_sum = abs(s[0]) + abs(s[1])
for r in sols:
m = abs(r[0]) + abs(r[1])
if m < min_sum:
s = r
min_sum = m
result.add(_remove_gcd(s[0], -coeff[x*z], s[1]))
return result
else:
var[0], var[1] = _var[1], _var[0]
y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
if x_0 is not None:
result.add((x_0, y_0, z_0))
return result
if coeff[x**2] == 0:
# If the coefficient of x is zero change the variables
if coeff[y**2] == 0:
var[0], var[2] = _var[2], _var[0]
z_0, y_0, x_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
else:
var[0], var[1] = _var[1], _var[0]
y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
else:
if coeff[x*y] or coeff[x*z]:
# Apply the transformation x --> X - (B*y + C*z)/(2*A)
A = coeff[x**2]
B = coeff[x*y]
C = coeff[x*z]
D = coeff[y**2]
E = coeff[y*z]
F = coeff[z**2]
_coeff = dict()
_coeff[x**2] = 4*A**2
_coeff[y**2] = 4*A*D - B**2
_coeff[z**2] = 4*A*F - C**2
_coeff[y*z] = 4*A*E - 2*B*C
_coeff[x*y] = 0
_coeff[x*z] = 0
x_0, y_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, _coeff))
if x_0 is None:
return result
p, q = _rational_pq(B*y_0 + C*z_0, 2*A)
x_0, y_0, z_0 = x_0*q - p, y_0*q, z_0*q
elif coeff[z*y] != 0:
if coeff[y**2] == 0:
if coeff[z**2] == 0:
# Equations of the form A*x**2 + E*yz = 0.
A = coeff[x**2]
E = coeff[y*z]
b, a = _rational_pq(-E, A)
x_0, y_0, z_0 = b, a, b
else:
# Ax**2 + E*y*z + F*z**2 = 0
var[0], var[2] = _var[2], _var[0]
z_0, y_0, x_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
else:
# A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, C may be zero
var[0], var[1] = _var[1], _var[0]
y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
else:
# Ax**2 + D*y**2 + F*z**2 = 0, C may be zero
x_0, y_0, z_0 = unpack_sol(_diop_ternary_quadratic_normal(var, coeff))
if x_0 is None:
return result
result.add(_remove_gcd(x_0, y_0, z_0))
return result
class InhomogeneousGeneralQuadratic(DiophantineEquationType):
"""
Representation of an inhomogeneous general quadratic.
No solver is currently implemented for this equation type.
"""
name = 'inhomogeneous_general_quadratic'
def matches(self):
if not (self.total_degree == 2 and self.dimension >= 3):
return False
if not self.homogeneous_order:
return True
else:
# there may be Pow keys like x**2 or Mul keys like x*y
if any(k.is_Mul for k in self.coeff): # cross terms
return not self.homogeneous
return False
class HomogeneousGeneralQuadratic(DiophantineEquationType):
"""
Representation of a homogeneous general quadratic.
No solver is currently implemented for this equation type.
"""
name = 'homogeneous_general_quadratic'
def matches(self):
if not (self.total_degree == 2 and self.dimension >= 3):
return False
if not self.homogeneous_order:
return False
else:
# there may be Pow keys like x**2 or Mul keys like x*y
if any(k.is_Mul for k in self.coeff): # cross terms
return self.homogeneous
return False
class GeneralSumOfSquares(DiophantineEquationType):
r"""
Representation of the diophantine equation
`x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.
Details
=======
When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be
no solutions. Refer [1]_ for more details.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import GeneralSumOfSquares
>>> from sympy.abc import a, b, c, d, e
>>> GeneralSumOfSquares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345).solve()
{(15, 22, 22, 24, 24)}
By default only 1 solution is returned. Use the `limit` keyword for more:
>>> sorted(GeneralSumOfSquares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345).solve(limit=3))
[(15, 22, 22, 24, 24), (16, 19, 24, 24, 24), (16, 20, 22, 23, 26)]
References
==========
.. [1] Representing an integer as a sum of three squares, [online],
Available:
http://www.proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares
"""
name = 'general_sum_of_squares'
def matches(self):
if not (self.total_degree == 2 and self.dimension >= 3):
return False
if not self.homogeneous_order:
return False
if any(k.is_Mul for k in self.coeff):
return False
return all(self.coeff[k] == 1 for k in self.coeff if k != 1)
def solve(self, parameters=None, limit=1):
self.pre_solve(parameters)
var = self.free_symbols
k = -int(self.coeff[1])
n = self.dimension
result = DiophantineSolutionSet(var, parameters=self.parameters)
if k < 0 or limit < 1:
return result
signs = [-1 if x.is_nonpositive else 1 for x in var]
negs = signs.count(-1) != 0
took = 0
for t in sum_of_squares(k, n, zeros=True):
if negs:
result.add([signs[i]*j for i, j in enumerate(t)])
else:
result.add(t)
took += 1
if took == limit:
break
return result
class GeneralPythagorean(DiophantineEquationType):
"""
Representation of the general pythagorean equation,
`a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import GeneralPythagorean
>>> from sympy.abc import a, b, c, d, e, x, y, z, t
>>> GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve()
{(t_0**2 + t_1**2 - t_2**2, 2*t_0*t_2, 2*t_1*t_2, t_0**2 + t_1**2 + t_2**2)}
>>> GeneralPythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2).solve(parameters=[x, y, z, t])
{(-10*t**2 + 10*x**2 + 10*y**2 + 10*z**2, 15*t**2 + 15*x**2 + 15*y**2 + 15*z**2, 15*t*x, 12*t*y, 60*t*z)}
"""
name = 'general_pythagorean'
def matches(self):
if not (self.total_degree == 2 and self.dimension >= 3):
return False
if not self.homogeneous_order:
return False
if any(k.is_Mul for k in self.coeff):
return False
if all(self.coeff[k] == 1 for k in self.coeff if k != 1):
return False
if not all(is_square(abs(self.coeff[k])) for k in self.coeff):
return False
# all but one has the same sign
# e.g. 4*x**2 + y**2 - 4*z**2
return abs(sum(sign(self.coeff[k]) for k in self.coeff)) == self.dimension - 2
@property
def n_parameters(self):
return self.dimension - 1
def solve(self, parameters=None, limit=1):
self.pre_solve(parameters)
coeff = self.coeff
var = self.free_symbols
n = self.dimension
if sign(coeff[var[0] ** 2]) + sign(coeff[var[1] ** 2]) + sign(coeff[var[2] ** 2]) < 0:
for key in coeff.keys():
coeff[key] = -coeff[key]
result = DiophantineSolutionSet(var, parameters=self.parameters)
index = 0
for i, v in enumerate(var):
if sign(coeff[v ** 2]) == -1:
index = i
m = result.parameters
ith = sum(m_i ** 2 for m_i in m)
L = [ith - 2 * m[n - 2] ** 2]
L.extend([2 * m[i] * m[n - 2] for i in range(n - 2)])
sol = L[:index] + [ith] + L[index:]
lcm = 1
for i, v in enumerate(var):
if i == index or (index > 0 and i == 0) or (index == 0 and i == 1):
lcm = ilcm(lcm, sqrt(abs(coeff[v ** 2])))
else:
s = sqrt(coeff[v ** 2])
lcm = ilcm(lcm, s if _odd(s) else s // 2)
for i, v in enumerate(var):
sol[i] = (lcm * sol[i]) / sqrt(abs(coeff[v ** 2]))
result.add(sol)
return result
class CubicThue(DiophantineEquationType):
"""
Representation of a cubic Thue diophantine equation.
A cubic Thue diophantine equation is a polynomial of the form
`f(x, y) = r` of degree 3, where `x` and `y` are integers
and `r` is a rational number.
No solver is currently implemented for this equation type.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.solvers.diophantine.diophantine import CubicThue
>>> c1 = CubicThue(x**3 + y**2 + 1)
>>> c1.matches()
True
"""
name = 'cubic_thue'
def matches(self):
return self.total_degree == 3 and self.dimension == 2
class GeneralSumOfEvenPowers(DiophantineEquationType):
"""
Representation of the diophantine equation
`x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`
where `e` is an even, integer power.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import GeneralSumOfEvenPowers
>>> from sympy.abc import a, b
>>> GeneralSumOfEvenPowers(a**4 + b**4 - (2**4 + 3**4)).solve()
{(2, 3)}
"""
name = 'general_sum_of_even_powers'
def matches(self):
if not self.total_degree > 3:
return False
if self.total_degree % 2 != 0:
return False
if not all(k.is_Pow and k.exp == self.total_degree for k in self.coeff if k != 1):
return False
return all(self.coeff[k] == 1 for k in self.coeff if k != 1)
def solve(self, parameters=None, limit=1):
self.pre_solve(parameters)
var = self.free_symbols
coeff = self.coeff
p = None
for q in coeff.keys():
if q.is_Pow and coeff[q]:
p = q.exp
k = len(var)
n = -coeff[1]
result = DiophantineSolutionSet(var, parameters=self.parameters)
if n < 0 or limit < 1:
return result
sign = [-1 if x.is_nonpositive else 1 for x in var]
negs = sign.count(-1) != 0
took = 0
for t in power_representation(n, p, k):
if negs:
result.add([sign[i]*j for i, j in enumerate(t)])
else:
result.add(t)
took += 1
if took == limit:
break
return result
# these types are known (but not necessarily handled)
# note that order is important here (in the current solver state)
all_diop_classes = [
Linear,
Univariate,
BinaryQuadratic,
InhomogeneousTernaryQuadratic,
HomogeneousTernaryQuadraticNormal,
HomogeneousTernaryQuadratic,
InhomogeneousGeneralQuadratic,
HomogeneousGeneralQuadratic,
GeneralSumOfSquares,
GeneralPythagorean,
CubicThue,
GeneralSumOfEvenPowers,
]
diop_known = {diop_class.name for diop_class in all_diop_classes}
def _is_int(i):
try:
as_int(i)
return True
except ValueError:
pass
def _sorted_tuple(*i):
return tuple(sorted(i))
def _remove_gcd(*x):
try:
g = igcd(*x)
except ValueError:
fx = list(filter(None, x))
if len(fx) < 2:
return x
g = igcd(*[i.as_content_primitive()[0] for i in fx])
except TypeError:
raise TypeError('_remove_gcd(a,b,c) or _remove_gcd(*container)')
if g == 1:
return x
return tuple([i//g for i in x])
def _rational_pq(a, b):
# return `(numer, denom)` for a/b; sign in numer and gcd removed
return _remove_gcd(sign(b)*a, abs(b))
def _nint_or_floor(p, q):
# return nearest int to p/q; in case of tie return floor(p/q)
w, r = divmod(p, q)
if abs(r) <= abs(q)//2:
return w
return w + 1
def _odd(i):
return i % 2 != 0
def _even(i):
return i % 2 == 0
def diophantine(eq, param=symbols("t", integer=True), syms=None,
permute=False):
"""
Simplify the solution procedure of diophantine equation ``eq`` by
converting it into a product of terms which should equal zero.
Explanation
===========
For example, when solving, `x^2 - y^2 = 0` this is treated as
`(x + y)(x - y) = 0` and `x + y = 0` and `x - y = 0` are solved
independently and combined. Each term is solved by calling
``diop_solve()``. (Although it is possible to call ``diop_solve()``
directly, one must be careful to pass an equation in the correct
form and to interpret the output correctly; ``diophantine()`` is
the public-facing function to use in general.)
Output of ``diophantine()`` is a set of tuples. The elements of the
tuple are the solutions for each variable in the equation and
are arranged according to the alphabetic ordering of the variables.
e.g. For an equation with two variables, `a` and `b`, the first
element of the tuple is the solution for `a` and the second for `b`.
Usage
=====
``diophantine(eq, t, syms)``: Solve the diophantine
equation ``eq``.
``t`` is the optional parameter to be used by ``diop_solve()``.
``syms`` is an optional list of symbols which determines the
order of the elements in the returned tuple.
By default, only the base solution is returned. If ``permute`` is set to
True then permutations of the base solution and/or permutations of the
signs of the values will be returned when applicable.
Examples
========
>>> from sympy.solvers.diophantine import diophantine
>>> from sympy.abc import a, b
>>> eq = a**4 + b**4 - (2**4 + 3**4)
>>> diophantine(eq)
{(2, 3)}
>>> diophantine(eq, permute=True)
{(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
Details
=======
``eq`` should be an expression which is assumed to be zero.
``t`` is the parameter to be used in the solution.
Examples
========
>>> from sympy.abc import x, y, z
>>> diophantine(x**2 - y**2)
{(t_0, -t_0), (t_0, t_0)}
>>> diophantine(x*(2*x + 3*y - z))
{(0, n1, n2), (t_0, t_1, 2*t_0 + 3*t_1)}
>>> diophantine(x**2 + 3*x*y + 4*x)
{(0, n1), (3*t_0 - 4, -t_0)}
See Also
========
diop_solve()
sympy.utilities.iterables.permute_signs
sympy.utilities.iterables.signed_permutations
"""
from sympy.utilities.iterables import (
subsets, permute_signs, signed_permutations)
eq = _sympify(eq)
if isinstance(eq, Eq):
eq = eq.lhs - eq.rhs
try:
var = list(eq.expand(force=True).free_symbols)
var.sort(key=default_sort_key)
if syms:
if not is_sequence(syms):
raise TypeError(
'syms should be given as a sequence, e.g. a list')
syms = [i for i in syms if i in var]
if syms != var:
dict_sym_index = dict(zip(syms, range(len(syms))))
return {tuple([t[dict_sym_index[i]] for i in var])
for t in diophantine(eq, param, permute=permute)}
n, d = eq.as_numer_denom()
if n.is_number:
return set()
if not d.is_number:
dsol = diophantine(d)
good = diophantine(n) - dsol
return {s for s in good if _mexpand(d.subs(zip(var, s)))}
else:
eq = n
eq = factor_terms(eq)
assert not eq.is_number
eq = eq.as_independent(*var, as_Add=False)[1]
p = Poly(eq)
assert not any(g.is_number for g in p.gens)
eq = p.as_expr()
assert eq.is_polynomial()
except (GeneratorsNeeded, AssertionError):
raise TypeError(filldedent('''
Equation should be a polynomial with Rational coefficients.'''))
# permute only sign
do_permute_signs = False
# permute sign and values
do_permute_signs_var = False
# permute few signs
permute_few_signs = False
try:
# if we know that factoring should not be attempted, skip
# the factoring step
v, c, t = classify_diop(eq)
# check for permute sign
if permute:
len_var = len(v)
permute_signs_for = [
GeneralSumOfSquares.name,
GeneralSumOfEvenPowers.name]
permute_signs_check = [
HomogeneousTernaryQuadratic.name,
HomogeneousTernaryQuadraticNormal.name,
BinaryQuadratic.name]
if t in permute_signs_for:
do_permute_signs_var = True
elif t in permute_signs_check:
# if all the variables in eq have even powers
# then do_permute_sign = True
if len_var == 3:
var_mul = list(subsets(v, 2))
# here var_mul is like [(x, y), (x, z), (y, z)]
xy_coeff = True
x_coeff = True
var1_mul_var2 = map(lambda a: a[0]*a[1], var_mul)
# if coeff(y*z), coeff(y*x), coeff(x*z) is not 0 then
# `xy_coeff` => True and do_permute_sign => False.
# Means no permuted solution.
for v1_mul_v2 in var1_mul_var2:
try:
coeff = c[v1_mul_v2]
except KeyError:
coeff = 0
xy_coeff = bool(xy_coeff) and bool(coeff)
var_mul = list(subsets(v, 1))
# here var_mul is like [(x,), (y, )]
for v1 in var_mul:
try:
coeff = c[v1[0]]
except KeyError:
coeff = 0
x_coeff = bool(x_coeff) and bool(coeff)
if not any([xy_coeff, x_coeff]):
# means only x**2, y**2, z**2, const is present
do_permute_signs = True
elif not x_coeff:
permute_few_signs = True
elif len_var == 2:
var_mul = list(subsets(v, 2))
# here var_mul is like [(x, y)]
xy_coeff = True
x_coeff = True
var1_mul_var2 = map(lambda x: x[0]*x[1], var_mul)
for v1_mul_v2 in var1_mul_var2:
try:
coeff = c[v1_mul_v2]
except KeyError:
coeff = 0
xy_coeff = bool(xy_coeff) and bool(coeff)
var_mul = list(subsets(v, 1))
# here var_mul is like [(x,), (y, )]
for v1 in var_mul:
try:
coeff = c[v1[0]]
except KeyError:
coeff = 0
x_coeff = bool(x_coeff) and bool(coeff)
if not any([xy_coeff, x_coeff]):
# means only x**2, y**2 and const is present
# so we can get more soln by permuting this soln.
do_permute_signs = True
elif not x_coeff:
# when coeff(x), coeff(y) is not present then signs of
# x, y can be permuted such that their sign are same
# as sign of x*y.
# e.g 1. (x_val,y_val)=> (x_val,y_val), (-x_val,-y_val)
# 2. (-x_vall, y_val)=> (-x_val,y_val), (x_val,-y_val)
permute_few_signs = True
if t == 'general_sum_of_squares':
# trying to factor such expressions will sometimes hang
terms = [(eq, 1)]
else:
raise TypeError
except (TypeError, NotImplementedError):
fl = factor_list(eq)
if fl[0].is_Rational and fl[0] != 1:
return diophantine(eq/fl[0], param=param, syms=syms, permute=permute)
terms = fl[1]
sols = set()
for term in terms:
base, _ = term
var_t, _, eq_type = classify_diop(base, _dict=False)
_, base = signsimp(base, evaluate=False).as_coeff_Mul()
solution = diop_solve(base, param)
if eq_type in [
Linear.name,
HomogeneousTernaryQuadratic.name,
HomogeneousTernaryQuadraticNormal.name,
GeneralPythagorean.name]:
sols.add(merge_solution(var, var_t, solution))
elif eq_type in [
BinaryQuadratic.name,
GeneralSumOfSquares.name,
GeneralSumOfEvenPowers.name,
Univariate.name]:
for sol in solution:
sols.add(merge_solution(var, var_t, sol))
else:
raise NotImplementedError('unhandled type: %s' % eq_type)
# remove null merge results
if () in sols:
sols.remove(())
null = tuple([0]*len(var))
# if there is no solution, return trivial solution
if not sols and eq.subs(zip(var, null)).is_zero:
sols.add(null)
final_soln = set()
for sol in sols:
if all(_is_int(s) for s in sol):
if do_permute_signs:
permuted_sign = set(permute_signs(sol))
final_soln.update(permuted_sign)
elif permute_few_signs:
lst = list(permute_signs(sol))
lst = list(filter(lambda x: x[0]*x[1] == sol[1]*sol[0], lst))
permuted_sign = set(lst)
final_soln.update(permuted_sign)
elif do_permute_signs_var:
permuted_sign_var = set(signed_permutations(sol))
final_soln.update(permuted_sign_var)
else:
final_soln.add(sol)
else:
final_soln.add(sol)
return final_soln
def merge_solution(var, var_t, solution):
"""
This is used to construct the full solution from the solutions of sub
equations.
Explanation
===========
For example when solving the equation `(x - y)(x^2 + y^2 - z^2) = 0`,
solutions for each of the equations `x - y = 0` and `x^2 + y^2 - z^2` are
found independently. Solutions for `x - y = 0` are `(x, y) = (t, t)`. But
we should introduce a value for z when we output the solution for the
original equation. This function converts `(t, t)` into `(t, t, n_{1})`
where `n_{1}` is an integer parameter.
"""
sol = []
if None in solution:
return ()
solution = iter(solution)
params = numbered_symbols("n", integer=True, start=1)
for v in var:
if v in var_t:
sol.append(next(solution))
else:
sol.append(next(params))
for val, symb in zip(sol, var):
if check_assumptions(val, **symb.assumptions0) is False:
return tuple()
return tuple(sol)
def _diop_solve(eq, params=None):
for diop_type in all_diop_classes:
if diop_type(eq).matches():
return diop_type(eq).solve(parameters=params)
def diop_solve(eq, param=symbols("t", integer=True)):
"""
Solves the diophantine equation ``eq``.
Explanation
===========
Unlike ``diophantine()``, factoring of ``eq`` is not attempted. Uses
``classify_diop()`` to determine the type of the equation and calls
the appropriate solver function.
Use of ``diophantine()`` is recommended over other helper functions.
``diop_solve()`` can return either a set or a tuple depending on the
nature of the equation.
Usage
=====
``diop_solve(eq, t)``: Solve diophantine equation, ``eq`` using ``t``
as a parameter if needed.
Details
=======
``eq`` should be an expression which is assumed to be zero.
``t`` is a parameter to be used in the solution.
Examples
========
>>> from sympy.solvers.diophantine import diop_solve
>>> from sympy.abc import x, y, z, w
>>> diop_solve(2*x + 3*y - 5)
(3*t_0 - 5, 5 - 2*t_0)
>>> diop_solve(4*x + 3*y - 4*z + 5)
(t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5)
>>> diop_solve(x + 3*y - 4*z + w - 6)
(t_0, t_0 + t_1, 6*t_0 + 5*t_1 + 4*t_2 - 6, 5*t_0 + 4*t_1 + 3*t_2 - 6)
>>> diop_solve(x**2 + y**2 - 5)
{(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)}
See Also
========
diophantine()
"""
var, coeff, eq_type = classify_diop(eq, _dict=False)
if eq_type == Linear.name:
return diop_linear(eq, param)
elif eq_type == BinaryQuadratic.name:
return diop_quadratic(eq, param)
elif eq_type == HomogeneousTernaryQuadratic.name:
return diop_ternary_quadratic(eq, parameterize=True)
elif eq_type == HomogeneousTernaryQuadraticNormal.name:
return diop_ternary_quadratic_normal(eq, parameterize=True)
elif eq_type == GeneralPythagorean.name:
return diop_general_pythagorean(eq, param)
elif eq_type == Univariate.name:
return diop_univariate(eq)
elif eq_type == GeneralSumOfSquares.name:
return diop_general_sum_of_squares(eq, limit=S.Infinity)
elif eq_type == GeneralSumOfEvenPowers.name:
return diop_general_sum_of_even_powers(eq, limit=S.Infinity)
if eq_type is not None and eq_type not in diop_known:
raise ValueError(filldedent('''
Alhough this type of equation was identified, it is not yet
handled. It should, however, be listed in `diop_known` at the
top of this file. Developers should see comments at the end of
`classify_diop`.
''')) # pragma: no cover
else:
raise NotImplementedError(
'No solver has been written for %s.' % eq_type)
def classify_diop(eq, _dict=True):
# docstring supplied externally
matched = False
diop_type = None
for diop_class in all_diop_classes:
diop_type = diop_class(eq)
if diop_type.matches():
matched = True
break
if matched:
return diop_type.free_symbols, dict(diop_type.coeff) if _dict else diop_type.coeff, diop_type.name
# new diop type instructions
# --------------------------
# if this error raises and the equation *can* be classified,
# * it should be identified in the if-block above
# * the type should be added to the diop_known
# if a solver can be written for it,
# * a dedicated handler should be written (e.g. diop_linear)
# * it should be passed to that handler in diop_solve
raise NotImplementedError(filldedent('''
This equation is not yet recognized or else has not been
simplified sufficiently to put it in a form recognized by
diop_classify().'''))
classify_diop.func_doc = ( # type: ignore
'''
Helper routine used by diop_solve() to find information about ``eq``.
Explanation
===========
Returns a tuple containing the type of the diophantine equation
along with the variables (free symbols) and their coefficients.
Variables are returned as a list and coefficients are returned
as a dict with the key being the respective term and the constant
term is keyed to 1. The type is one of the following:
* %s
Usage
=====
``classify_diop(eq)``: Return variables, coefficients and type of the
``eq``.
Details
=======
``eq`` should be an expression which is assumed to be zero.
``_dict`` is for internal use: when True (default) a dict is returned,
otherwise a defaultdict which supplies 0 for missing keys is returned.
Examples
========
>>> from sympy.solvers.diophantine import classify_diop
>>> from sympy.abc import x, y, z, w, t
>>> classify_diop(4*x + 6*y - 4)
([x, y], {1: -4, x: 4, y: 6}, 'linear')
>>> classify_diop(x + 3*y -4*z + 5)
([x, y, z], {1: 5, x: 1, y: 3, z: -4}, 'linear')
>>> classify_diop(x**2 + y**2 - x*y + x + 5)
([x, y], {1: 5, x: 1, x**2: 1, y**2: 1, x*y: -1}, 'binary_quadratic')
''' % ('\n * '.join(sorted(diop_known))))
def diop_linear(eq, param=symbols("t", integer=True)):
"""
Solves linear diophantine equations.
A linear diophantine equation is an equation of the form `a_{1}x_{1} +
a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are
integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables.
Usage
=====
``diop_linear(eq)``: Returns a tuple containing solutions to the
diophantine equation ``eq``. Values in the tuple is arranged in the same
order as the sorted variables.
Details
=======
``eq`` is a linear diophantine equation which is assumed to be zero.
``param`` is the parameter to be used in the solution.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_linear
>>> from sympy.abc import x, y, z
>>> diop_linear(2*x - 3*y - 5) # solves equation 2*x - 3*y - 5 == 0
(3*t_0 - 5, 2*t_0 - 5)
Here x = -3*t_0 - 5 and y = -2*t_0 - 5
>>> diop_linear(2*x - 3*y - 4*z -3)
(t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3)
See Also
========
diop_quadratic(), diop_ternary_quadratic(), diop_general_pythagorean(),
diop_general_sum_of_squares()
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == Linear.name:
parameters = None
if param is not None:
parameters = symbols('%s_0:%i' % (param, len(var)), integer=True)
result = Linear(eq).solve(parameters=parameters)
if param is None:
result = result(*[0]*len(result.parameters))
if len(result) > 0:
return list(result)[0]
else:
return tuple([None]*len(result.parameters))
def base_solution_linear(c, a, b, t=None):
"""
Return the base solution for the linear equation, `ax + by = c`.
Explanation
===========
Used by ``diop_linear()`` to find the base solution of a linear
Diophantine equation. If ``t`` is given then the parametrized solution is
returned.
Usage
=====
``base_solution_linear(c, a, b, t)``: ``a``, ``b``, ``c`` are coefficients
in `ax + by = c` and ``t`` is the parameter to be used in the solution.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import base_solution_linear
>>> from sympy.abc import t
>>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5
(-5, 5)
>>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0
(0, 0)
>>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5
(3*t - 5, 5 - 2*t)
>>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0
(7*t, -5*t)
"""
a, b, c = _remove_gcd(a, b, c)
if c == 0:
if t is not None:
if b < 0:
t = -t
return (b*t , -a*t)
else:
return (0, 0)
else:
x0, y0, d = igcdex(abs(a), abs(b))
x0 *= sign(a)
y0 *= sign(b)
if divisible(c, d):
if t is not None:
if b < 0:
t = -t
return (c*x0 + b*t, c*y0 - a*t)
else:
return (c*x0, c*y0)
else:
return (None, None)
def diop_univariate(eq):
"""
Solves a univariate diophantine equations.
Explanation
===========
A univariate diophantine equation is an equation of the form
`a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are
integer constants and `x` is an integer variable.
Usage
=====
``diop_univariate(eq)``: Returns a set containing solutions to the
diophantine equation ``eq``.
Details
=======
``eq`` is a univariate diophantine equation which is assumed to be zero.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_univariate
>>> from sympy.abc import x
>>> diop_univariate((x - 2)*(x - 3)**2) # solves equation (x - 2)*(x - 3)**2 == 0
{(2,), (3,)}
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == Univariate.name:
return {(int(i),) for i in solveset_real(
eq, var[0]).intersect(S.Integers)}
def divisible(a, b):
"""
Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise.
"""
return not a % b
def diop_quadratic(eq, param=symbols("t", integer=True)):
"""
Solves quadratic diophantine equations.
i.e. equations of the form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`. Returns a
set containing the tuples `(x, y)` which contains the solutions. If there
are no solutions then `(None, None)` is returned.
Usage
=====
``diop_quadratic(eq, param)``: ``eq`` is a quadratic binary diophantine
equation. ``param`` is used to indicate the parameter to be used in the
solution.
Details
=======
``eq`` should be an expression which is assumed to be zero.
``param`` is a parameter to be used in the solution.
Examples
========
>>> from sympy.abc import x, y, t
>>> from sympy.solvers.diophantine.diophantine import diop_quadratic
>>> diop_quadratic(x**2 + y**2 + 2*x + 2*y + 2, t)
{(-1, -1)}
References
==========
.. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online],
Available: http://www.alpertron.com.ar/METHODS.HTM
.. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online],
Available: https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
See Also
========
diop_linear(), diop_ternary_quadratic(), diop_general_sum_of_squares(),
diop_general_pythagorean()
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == BinaryQuadratic.name:
if param is not None:
parameters = [param, Symbol("u", integer=True)]
else:
parameters = None
return set(BinaryQuadratic(eq).solve(parameters=parameters))
def is_solution_quad(var, coeff, u, v):
"""
Check whether `(u, v)` is solution to the quadratic binary diophantine
equation with the variable list ``var`` and coefficient dictionary
``coeff``.
Not intended for use by normal users.
"""
reps = dict(zip(var, (u, v)))
eq = Add(*[j*i.xreplace(reps) for i, j in coeff.items()])
return _mexpand(eq) == 0
def diop_DN(D, N, t=symbols("t", integer=True)):
"""
Solves the equation `x^2 - Dy^2 = N`.
Explanation
===========
Mainly concerned with the case `D > 0, D` is not a perfect square,
which is the same as the generalized Pell equation. The LMM
algorithm [1]_ is used to solve this equation.
Returns one solution tuple, (`x, y)` for each class of the solutions.
Other solutions of the class can be constructed according to the
values of ``D`` and ``N``.
Usage
=====
``diop_DN(D, N, t)``: D and N are integers as in `x^2 - Dy^2 = N` and
``t`` is the parameter to be used in the solutions.
Details
=======
``D`` and ``N`` correspond to D and N in the equation.
``t`` is the parameter to be used in the solutions.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_DN
>>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4
[(3, 1), (393, 109), (36, 10)]
The output can be interpreted as follows: There are three fundamental
solutions to the equation `x^2 - 13y^2 = -4` given by (3, 1), (393, 109)
and (36, 10). Each tuple is in the form (x, y), i.e. solution (3, 1) means
that `x = 3` and `y = 1`.
>>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1
[(49299, 1570)]
See Also
========
find_DN(), diop_bf_DN()
References
==========
.. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
Robertson, July 31, 2004, Pages 16 - 17. [online], Available:
https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
"""
if D < 0:
if N == 0:
return [(0, 0)]
elif N < 0:
return []
elif N > 0:
sol = []
for d in divisors(square_factor(N)):
sols = cornacchia(1, -D, N // d**2)
if sols:
for x, y in sols:
sol.append((d*x, d*y))
if D == -1:
sol.append((d*y, d*x))
return sol
elif D == 0:
if N < 0:
return []
if N == 0:
return [(0, t)]
sN, _exact = integer_nthroot(N, 2)
if _exact:
return [(sN, t)]
else:
return []
else: # D > 0
sD, _exact = integer_nthroot(D, 2)
if _exact:
if N == 0:
return [(sD*t, t)]
else:
sol = []
for y in range(floor(sign(N)*(N - 1)/(2*sD)) + 1):
try:
sq, _exact = integer_nthroot(D*y**2 + N, 2)
except ValueError:
_exact = False
if _exact:
sol.append((sq, y))
return sol
elif 1 < N**2 < D:
# It is much faster to call `_special_diop_DN`.
return _special_diop_DN(D, N)
else:
if N == 0:
return [(0, 0)]
elif abs(N) == 1:
pqa = PQa(0, 1, D)
j = 0
G = []
B = []
for i in pqa:
a = i[2]
G.append(i[5])
B.append(i[4])
if j != 0 and a == 2*sD:
break
j = j + 1
if _odd(j):
if N == -1:
x = G[j - 1]
y = B[j - 1]
else:
count = j
while count < 2*j - 1:
i = next(pqa)
G.append(i[5])
B.append(i[4])
count += 1
x = G[count]
y = B[count]
else:
if N == 1:
x = G[j - 1]
y = B[j - 1]
else:
return []
return [(x, y)]
else:
fs = []
sol = []
div = divisors(N)
for d in div:
if divisible(N, d**2):
fs.append(d)
for f in fs:
m = N // f**2
zs = sqrt_mod(D, abs(m), all_roots=True)
zs = [i for i in zs if i <= abs(m) // 2 ]
if abs(m) != 2:
zs = zs + [-i for i in zs if i] # omit dupl 0
for z in zs:
pqa = PQa(z, abs(m), D)
j = 0
G = []
B = []
for i in pqa:
G.append(i[5])
B.append(i[4])
if j != 0 and abs(i[1]) == 1:
r = G[j-1]
s = B[j-1]
if r**2 - D*s**2 == m:
sol.append((f*r, f*s))
elif diop_DN(D, -1) != []:
a = diop_DN(D, -1)
sol.append((f*(r*a[0][0] + a[0][1]*s*D), f*(r*a[0][1] + s*a[0][0])))
break
j = j + 1
if j == length(z, abs(m), D):
break
return sol
def _special_diop_DN(D, N):
"""
Solves the equation `x^2 - Dy^2 = N` for the special case where
`1 < N**2 < D` and `D` is not a perfect square.
It is better to call `diop_DN` rather than this function, as
the former checks the condition `1 < N**2 < D`, and calls the latter only
if appropriate.
Usage
=====
WARNING: Internal method. Do not call directly!
``_special_diop_DN(D, N)``: D and N are integers as in `x^2 - Dy^2 = N`.
Details
=======
``D`` and ``N`` correspond to D and N in the equation.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import _special_diop_DN
>>> _special_diop_DN(13, -3) # Solves equation x**2 - 13*y**2 = -3
[(7, 2), (137, 38)]
The output can be interpreted as follows: There are two fundamental
solutions to the equation `x^2 - 13y^2 = -3` given by (7, 2) and
(137, 38). Each tuple is in the form (x, y), i.e. solution (7, 2) means
that `x = 7` and `y = 2`.
>>> _special_diop_DN(2445, -20) # Solves equation x**2 - 2445*y**2 = -20
[(445, 9), (17625560, 356454), (698095554475, 14118073569)]
See Also
========
diop_DN()
References
==========
.. [1] Section 4.4.4 of the following book:
Quadratic Diophantine Equations, T. Andreescu and D. Andrica,
Springer, 2015.
"""
# The following assertion was removed for efficiency, with the understanding
# that this method is not called directly. The parent method, `diop_DN`
# is responsible for performing the appropriate checks.
#
# assert (1 < N**2 < D) and (not integer_nthroot(D, 2)[1])
sqrt_D = sqrt(D)
F = [(N, 1)]
f = 2
while True:
f2 = f**2
if f2 > abs(N):
break
n, r = divmod(N, f2)
if r == 0:
F.append((n, f))
f += 1
P = 0
Q = 1
G0, G1 = 0, 1
B0, B1 = 1, 0
solutions = []
i = 0
while True:
a = floor((P + sqrt_D) / Q)
P = a*Q - P
Q = (D - P**2) // Q
G2 = a*G1 + G0
B2 = a*B1 + B0
for n, f in F:
if G2**2 - D*B2**2 == n:
solutions.append((f*G2, f*B2))
i += 1
if Q == 1 and i % 2 == 0:
break
G0, G1 = G1, G2
B0, B1 = B1, B2
return solutions
def cornacchia(a, b, m):
r"""
Solves `ax^2 + by^2 = m` where `\gcd(a, b) = 1 = gcd(a, m)` and `a, b > 0`.
Explanation
===========
Uses the algorithm due to Cornacchia. The method only finds primitive
solutions, i.e. ones with `\gcd(x, y) = 1`. So this method can't be used to
find the solutions of `x^2 + y^2 = 20` since the only solution to former is
`(x, y) = (4, 2)` and it is not primitive. When `a = b`, only the
solutions with `x \leq y` are found. For more details, see the References.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import cornacchia
>>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35
{(2, 3), (4, 1)}
>>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25
{(4, 3)}
References
===========
.. [1] A. Nitaj, "L'algorithme de Cornacchia"
.. [2] Solving the diophantine equation ax**2 + by**2 = m by Cornacchia's
method, [online], Available:
http://www.numbertheory.org/php/cornacchia.html
See Also
========
sympy.utilities.iterables.signed_permutations
"""
sols = set()
a1 = igcdex(a, m)[0]
v = sqrt_mod(-b*a1, m, all_roots=True)
if not v:
return None
for t in v:
if t < m // 2:
continue
u, r = t, m
while True:
u, r = r, u % r
if a*r**2 < m:
break
m1 = m - a*r**2
if m1 % b == 0:
m1 = m1 // b
s, _exact = integer_nthroot(m1, 2)
if _exact:
if a == b and r < s:
r, s = s, r
sols.add((int(r), int(s)))
return sols
def PQa(P_0, Q_0, D):
r"""
Returns useful information needed to solve the Pell equation.
Explanation
===========
There are six sequences of integers defined related to the continued
fraction representation of `\\frac{P + \sqrt{D}}{Q}`, namely {`P_{i}`},
{`Q_{i}`}, {`a_{i}`},{`A_{i}`}, {`B_{i}`}, {`G_{i}`}. ``PQa()`` Returns
these values as a 6-tuple in the same order as mentioned above. Refer [1]_
for more detailed information.
Usage
=====
``PQa(P_0, Q_0, D)``: ``P_0``, ``Q_0`` and ``D`` are integers corresponding
to `P_{0}`, `Q_{0}` and `D` in the continued fraction
`\\frac{P_{0} + \sqrt{D}}{Q_{0}}`.
Also it's assumed that `P_{0}^2 == D mod(|Q_{0}|)` and `D` is square free.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import PQa
>>> pqa = PQa(13, 4, 5) # (13 + sqrt(5))/4
>>> next(pqa) # (P_0, Q_0, a_0, A_0, B_0, G_0)
(13, 4, 3, 3, 1, -1)
>>> next(pqa) # (P_1, Q_1, a_1, A_1, B_1, G_1)
(-1, 1, 1, 4, 1, 3)
References
==========
.. [1] Solving the generalized Pell equation x^2 - Dy^2 = N, John P.
Robertson, July 31, 2004, Pages 4 - 8. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
"""
A_i_2 = B_i_1 = 0
A_i_1 = B_i_2 = 1
G_i_2 = -P_0
G_i_1 = Q_0
P_i = P_0
Q_i = Q_0
while True:
a_i = floor((P_i + sqrt(D))/Q_i)
A_i = a_i*A_i_1 + A_i_2
B_i = a_i*B_i_1 + B_i_2
G_i = a_i*G_i_1 + G_i_2
yield P_i, Q_i, a_i, A_i, B_i, G_i
A_i_1, A_i_2 = A_i, A_i_1
B_i_1, B_i_2 = B_i, B_i_1
G_i_1, G_i_2 = G_i, G_i_1
P_i = a_i*Q_i - P_i
Q_i = (D - P_i**2)/Q_i
def diop_bf_DN(D, N, t=symbols("t", integer=True)):
r"""
Uses brute force to solve the equation, `x^2 - Dy^2 = N`.
Explanation
===========
Mainly concerned with the generalized Pell equation which is the case when
`D > 0, D` is not a perfect square. For more information on the case refer
[1]_. Let `(t, u)` be the minimal positive solution of the equation
`x^2 - Dy^2 = 1`. Then this method requires
`\sqrt{\\frac{\mid N \mid (t \pm 1)}{2D}}` to be small.
Usage
=====
``diop_bf_DN(D, N, t)``: ``D`` and ``N`` are coefficients in
`x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions.
Details
=======
``D`` and ``N`` correspond to D and N in the equation.
``t`` is the parameter to be used in the solutions.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_bf_DN
>>> diop_bf_DN(13, -4)
[(3, 1), (-3, 1), (36, 10)]
>>> diop_bf_DN(986, 1)
[(49299, 1570)]
See Also
========
diop_DN()
References
==========
.. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
Robertson, July 31, 2004, Page 15. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
"""
D = as_int(D)
N = as_int(N)
sol = []
a = diop_DN(D, 1)
u = a[0][0]
if abs(N) == 1:
return diop_DN(D, N)
elif N > 1:
L1 = 0
L2 = integer_nthroot(int(N*(u - 1)/(2*D)), 2)[0] + 1
elif N < -1:
L1, _exact = integer_nthroot(-int(N/D), 2)
if not _exact:
L1 += 1
L2 = integer_nthroot(-int(N*(u + 1)/(2*D)), 2)[0] + 1
else: # N = 0
if D < 0:
return [(0, 0)]
elif D == 0:
return [(0, t)]
else:
sD, _exact = integer_nthroot(D, 2)
if _exact:
return [(sD*t, t), (-sD*t, t)]
else:
return [(0, 0)]
for y in range(L1, L2):
try:
x, _exact = integer_nthroot(N + D*y**2, 2)
except ValueError:
_exact = False
if _exact:
sol.append((x, y))
if not equivalent(x, y, -x, y, D, N):
sol.append((-x, y))
return sol
def equivalent(u, v, r, s, D, N):
"""
Returns True if two solutions `(u, v)` and `(r, s)` of `x^2 - Dy^2 = N`
belongs to the same equivalence class and False otherwise.
Explanation
===========
Two solutions `(u, v)` and `(r, s)` to the above equation fall to the same
equivalence class iff both `(ur - Dvs)` and `(us - vr)` are divisible by
`N`. See reference [1]_. No test is performed to test whether `(u, v)` and
`(r, s)` are actually solutions to the equation. User should take care of
this.
Usage
=====
``equivalent(u, v, r, s, D, N)``: `(u, v)` and `(r, s)` are two solutions
of the equation `x^2 - Dy^2 = N` and all parameters involved are integers.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import equivalent
>>> equivalent(18, 5, -18, -5, 13, -1)
True
>>> equivalent(3, 1, -18, 393, 109, -4)
False
References
==========
.. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
Robertson, July 31, 2004, Page 12. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
"""
return divisible(u*r - D*v*s, N) and divisible(u*s - v*r, N)
def length(P, Q, D):
r"""
Returns the (length of aperiodic part + length of periodic part) of
continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`.
It is important to remember that this does NOT return the length of the
periodic part but the sum of the lengths of the two parts as mentioned
above.
Usage
=====
``length(P, Q, D)``: ``P``, ``Q`` and ``D`` are integers corresponding to
the continued fraction `\\frac{P + \sqrt{D}}{Q}`.
Details
=======
``P``, ``D`` and ``Q`` corresponds to P, D and Q in the continued fraction,
`\\frac{P + \sqrt{D}}{Q}`.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import length
>>> length(-2 , 4, 5) # (-2 + sqrt(5))/4
3
>>> length(-5, 4, 17) # (-5 + sqrt(17))/4
4
See Also
========
sympy.ntheory.continued_fraction.continued_fraction_periodic
"""
from sympy.ntheory.continued_fraction import continued_fraction_periodic
v = continued_fraction_periodic(P, Q, D)
if type(v[-1]) is list:
rpt = len(v[-1])
nonrpt = len(v) - 1
else:
rpt = 0
nonrpt = len(v)
return rpt + nonrpt
def transformation_to_DN(eq):
"""
This function transforms general quadratic,
`ax^2 + bxy + cy^2 + dx + ey + f = 0`
to more easy to deal with `X^2 - DY^2 = N` form.
Explanation
===========
This is used to solve the general quadratic equation by transforming it to
the latter form. Refer [1]_ for more detailed information on the
transformation. This function returns a tuple (A, B) where A is a 2 X 2
matrix and B is a 2 X 1 matrix such that,
Transpose([x y]) = A * Transpose([X Y]) + B
Usage
=====
``transformation_to_DN(eq)``: where ``eq`` is the quadratic to be
transformed.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.solvers.diophantine.diophantine import transformation_to_DN
>>> A, B = transformation_to_DN(x**2 - 3*x*y - y**2 - 2*y + 1)
>>> A
Matrix([
[1/26, 3/26],
[ 0, 1/13]])
>>> B
Matrix([
[-6/13],
[-4/13]])
A, B returned are such that Transpose((x y)) = A * Transpose((X Y)) + B.
Substituting these values for `x` and `y` and a bit of simplifying work
will give an equation of the form `x^2 - Dy^2 = N`.
>>> from sympy.abc import X, Y
>>> from sympy import Matrix, simplify
>>> u = (A*Matrix([X, Y]) + B)[0] # Transformation for x
>>> u
X/26 + 3*Y/26 - 6/13
>>> v = (A*Matrix([X, Y]) + B)[1] # Transformation for y
>>> v
Y/13 - 4/13
Next we will substitute these formulas for `x` and `y` and do
``simplify()``.
>>> eq = simplify((x**2 - 3*x*y - y**2 - 2*y + 1).subs(zip((x, y), (u, v))))
>>> eq
X**2/676 - Y**2/52 + 17/13
By multiplying the denominator appropriately, we can get a Pell equation
in the standard form.
>>> eq * 676
X**2 - 13*Y**2 + 884
If only the final equation is needed, ``find_DN()`` can be used.
See Also
========
find_DN()
References
==========
.. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0,
John P.Robertson, May 8, 2003, Page 7 - 11.
https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == BinaryQuadratic.name:
return _transformation_to_DN(var, coeff)
def _transformation_to_DN(var, coeff):
x, y = var
a = coeff[x**2]
b = coeff[x*y]
c = coeff[y**2]
d = coeff[x]
e = coeff[y]
f = coeff[1]
a, b, c, d, e, f = [as_int(i) for i in _remove_gcd(a, b, c, d, e, f)]
X, Y = symbols("X, Y", integer=True)
if b:
B, C = _rational_pq(2*a, b)
A, T = _rational_pq(a, B**2)
# eq_1 = A*B*X**2 + B*(c*T - A*C**2)*Y**2 + d*T*X + (B*e*T - d*T*C)*Y + f*T*B
coeff = {X**2: A*B, X*Y: 0, Y**2: B*(c*T - A*C**2), X: d*T, Y: B*e*T - d*T*C, 1: f*T*B}
A_0, B_0 = _transformation_to_DN([X, Y], coeff)
return Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*A_0, Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*B_0
else:
if d:
B, C = _rational_pq(2*a, d)
A, T = _rational_pq(a, B**2)
# eq_2 = A*X**2 + c*T*Y**2 + e*T*Y + f*T - A*C**2
coeff = {X**2: A, X*Y: 0, Y**2: c*T, X: 0, Y: e*T, 1: f*T - A*C**2}
A_0, B_0 = _transformation_to_DN([X, Y], coeff)
return Matrix(2, 2, [S.One/B, 0, 0, 1])*A_0, Matrix(2, 2, [S.One/B, 0, 0, 1])*B_0 + Matrix([-S(C)/B, 0])
else:
if e:
B, C = _rational_pq(2*c, e)
A, T = _rational_pq(c, B**2)
# eq_3 = a*T*X**2 + A*Y**2 + f*T - A*C**2
coeff = {X**2: a*T, X*Y: 0, Y**2: A, X: 0, Y: 0, 1: f*T - A*C**2}
A_0, B_0 = _transformation_to_DN([X, Y], coeff)
return Matrix(2, 2, [1, 0, 0, S.One/B])*A_0, Matrix(2, 2, [1, 0, 0, S.One/B])*B_0 + Matrix([0, -S(C)/B])
else:
# TODO: pre-simplification: Not necessary but may simplify
# the equation.
return Matrix(2, 2, [S.One/a, 0, 0, 1]), Matrix([0, 0])
def find_DN(eq):
"""
This function returns a tuple, `(D, N)` of the simplified form,
`x^2 - Dy^2 = N`, corresponding to the general quadratic,
`ax^2 + bxy + cy^2 + dx + ey + f = 0`.
Solving the general quadratic is then equivalent to solving the equation
`X^2 - DY^2 = N` and transforming the solutions by using the transformation
matrices returned by ``transformation_to_DN()``.
Usage
=====
``find_DN(eq)``: where ``eq`` is the quadratic to be transformed.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.solvers.diophantine.diophantine import find_DN
>>> find_DN(x**2 - 3*x*y - y**2 - 2*y + 1)
(13, -884)
Interpretation of the output is that we get `X^2 -13Y^2 = -884` after
transforming `x^2 - 3xy - y^2 - 2y + 1` using the transformation returned
by ``transformation_to_DN()``.
See Also
========
transformation_to_DN()
References
==========
.. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0,
John P.Robertson, May 8, 2003, Page 7 - 11.
https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == BinaryQuadratic.name:
return _find_DN(var, coeff)
def _find_DN(var, coeff):
x, y = var
X, Y = symbols("X, Y", integer=True)
A, B = _transformation_to_DN(var, coeff)
u = (A*Matrix([X, Y]) + B)[0]
v = (A*Matrix([X, Y]) + B)[1]
eq = x**2*coeff[x**2] + x*y*coeff[x*y] + y**2*coeff[y**2] + x*coeff[x] + y*coeff[y] + coeff[1]
simplified = _mexpand(eq.subs(zip((x, y), (u, v))))
coeff = simplified.as_coefficients_dict()
return -coeff[Y**2]/coeff[X**2], -coeff[1]/coeff[X**2]
def check_param(x, y, a, params):
"""
If there is a number modulo ``a`` such that ``x`` and ``y`` are both
integers, then return a parametric representation for ``x`` and ``y``
else return (None, None).
Here ``x`` and ``y`` are functions of ``t``.
"""
from sympy.simplify.simplify import clear_coefficients
if x.is_number and not x.is_Integer:
return DiophantineSolutionSet([x, y], parameters=params)
if y.is_number and not y.is_Integer:
return DiophantineSolutionSet([x, y], parameters=params)
m, n = symbols("m, n", integer=True)
c, p = (m*x + n*y).as_content_primitive()
if a % c.q:
return DiophantineSolutionSet([x, y], parameters=params)
# clear_coefficients(mx + b, R)[1] -> (R - b)/m
eq = clear_coefficients(x, m)[1] - clear_coefficients(y, n)[1]
junk, eq = eq.as_content_primitive()
return _diop_solve(eq, params=params)
def diop_ternary_quadratic(eq, parameterize=False):
"""
Solves the general quadratic ternary form,
`ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`.
Returns a tuple `(x, y, z)` which is a base solution for the above
equation. If there are no solutions, `(None, None, None)` is returned.
Usage
=====
``diop_ternary_quadratic(eq)``: Return a tuple containing a basic solution
to ``eq``.
Details
=======
``eq`` should be an homogeneous expression of degree two in three variables
and it is assumed to be zero.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic
>>> diop_ternary_quadratic(x**2 + 3*y**2 - z**2)
(1, 0, 1)
>>> diop_ternary_quadratic(4*x**2 + 5*y**2 - z**2)
(1, 0, 2)
>>> diop_ternary_quadratic(45*x**2 - 7*y**2 - 8*x*y - z**2)
(28, 45, 105)
>>> diop_ternary_quadratic(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y)
(9, 1, 5)
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type in (
HomogeneousTernaryQuadratic.name,
HomogeneousTernaryQuadraticNormal.name):
sol = _diop_ternary_quadratic(var, coeff)
if len(sol) > 0:
x_0, y_0, z_0 = list(sol)[0]
else:
x_0, y_0, z_0 = None, None, None
if parameterize:
return _parametrize_ternary_quadratic(
(x_0, y_0, z_0), var, coeff)
return x_0, y_0, z_0
def _diop_ternary_quadratic(_var, coeff):
eq = sum([i*coeff[i] for i in coeff])
if HomogeneousTernaryQuadratic(eq).matches():
return HomogeneousTernaryQuadratic(eq, free_symbols=_var).solve()
elif HomogeneousTernaryQuadraticNormal(eq).matches():
return HomogeneousTernaryQuadraticNormal(eq, free_symbols=_var).solve()
def transformation_to_normal(eq):
"""
Returns the transformation Matrix that converts a general ternary
quadratic equation ``eq`` (`ax^2 + by^2 + cz^2 + dxy + eyz + fxz`)
to a form without cross terms: `ax^2 + by^2 + cz^2 = 0`. This is
not used in solving ternary quadratics; it is only implemented for
the sake of completeness.
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type in (
"homogeneous_ternary_quadratic",
"homogeneous_ternary_quadratic_normal"):
return _transformation_to_normal(var, coeff)
def _transformation_to_normal(var, coeff):
_var = list(var) # copy
x, y, z = var
if not any(coeff[i**2] for i in var):
# https://math.stackexchange.com/questions/448051/transform-quadratic-ternary-form-to-normal-form/448065#448065
a = coeff[x*y]
b = coeff[y*z]
c = coeff[x*z]
swap = False
if not a: # b can't be 0 or else there aren't 3 vars
swap = True
a, b = b, a
T = Matrix(((1, 1, -b/a), (1, -1, -c/a), (0, 0, 1)))
if swap:
T.row_swap(0, 1)
T.col_swap(0, 1)
return T
if coeff[x**2] == 0:
# If the coefficient of x is zero change the variables
if coeff[y**2] == 0:
_var[0], _var[2] = var[2], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 2)
T.col_swap(0, 2)
return T
else:
_var[0], _var[1] = var[1], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 1)
T.col_swap(0, 1)
return T
# Apply the transformation x --> X - (B*Y + C*Z)/(2*A)
if coeff[x*y] != 0 or coeff[x*z] != 0:
A = coeff[x**2]
B = coeff[x*y]
C = coeff[x*z]
D = coeff[y**2]
E = coeff[y*z]
F = coeff[z**2]
_coeff = dict()
_coeff[x**2] = 4*A**2
_coeff[y**2] = 4*A*D - B**2
_coeff[z**2] = 4*A*F - C**2
_coeff[y*z] = 4*A*E - 2*B*C
_coeff[x*y] = 0
_coeff[x*z] = 0
T_0 = _transformation_to_normal(_var, _coeff)
return Matrix(3, 3, [1, S(-B)/(2*A), S(-C)/(2*A), 0, 1, 0, 0, 0, 1])*T_0
elif coeff[y*z] != 0:
if coeff[y**2] == 0:
if coeff[z**2] == 0:
# Equations of the form A*x**2 + E*yz = 0.
# Apply transformation y -> Y + Z ans z -> Y - Z
return Matrix(3, 3, [1, 0, 0, 0, 1, 1, 0, 1, -1])
else:
# Ax**2 + E*y*z + F*z**2 = 0
_var[0], _var[2] = var[2], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 2)
T.col_swap(0, 2)
return T
else:
# A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, F may be zero
_var[0], _var[1] = var[1], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 1)
T.col_swap(0, 1)
return T
else:
return Matrix.eye(3)
def parametrize_ternary_quadratic(eq):
"""
Returns the parametrized general solution for the ternary quadratic
equation ``eq`` which has the form
`ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`.
Examples
========
>>> from sympy import Tuple, ordered
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine.diophantine import parametrize_ternary_quadratic
The parametrized solution may be returned with three parameters:
>>> parametrize_ternary_quadratic(2*x**2 + y**2 - 2*z**2)
(p**2 - 2*q**2, -2*p**2 + 4*p*q - 4*p*r - 4*q**2, p**2 - 4*p*q + 2*q**2 - 4*q*r)
There might also be only two parameters:
>>> parametrize_ternary_quadratic(4*x**2 + 2*y**2 - 3*z**2)
(2*p**2 - 3*q**2, -4*p**2 + 12*p*q - 6*q**2, 4*p**2 - 8*p*q + 6*q**2)
Notes
=====
Consider ``p`` and ``q`` in the previous 2-parameter
solution and observe that more than one solution can be represented
by a given pair of parameters. If `p` and ``q`` are not coprime, this is
trivially true since the common factor will also be a common factor of the
solution values. But it may also be true even when ``p`` and
``q`` are coprime:
>>> sol = Tuple(*_)
>>> p, q = ordered(sol.free_symbols)
>>> sol.subs([(p, 3), (q, 2)])
(6, 12, 12)
>>> sol.subs([(q, 1), (p, 1)])
(-1, 2, 2)
>>> sol.subs([(q, 0), (p, 1)])
(2, -4, 4)
>>> sol.subs([(q, 1), (p, 0)])
(-3, -6, 6)
Except for sign and a common factor, these are equivalent to
the solution of (1, 2, 2).
References
==========
.. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart,
London Mathematical Society Student Texts 41, Cambridge University
Press, Cambridge, 1998.
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type in (
"homogeneous_ternary_quadratic",
"homogeneous_ternary_quadratic_normal"):
x_0, y_0, z_0 = list(_diop_ternary_quadratic(var, coeff))[0]
return _parametrize_ternary_quadratic(
(x_0, y_0, z_0), var, coeff)
def _parametrize_ternary_quadratic(solution, _var, coeff):
# called for a*x**2 + b*y**2 + c*z**2 + d*x*y + e*y*z + f*x*z = 0
assert 1 not in coeff
x_0, y_0, z_0 = solution
v = list(_var) # copy
if x_0 is None:
return (None, None, None)
if solution.count(0) >= 2:
# if there are 2 zeros the equation reduces
# to k*X**2 == 0 where X is x, y, or z so X must
# be zero, too. So there is only the trivial
# solution.
return (None, None, None)
if x_0 == 0:
v[0], v[1] = v[1], v[0]
y_p, x_p, z_p = _parametrize_ternary_quadratic(
(y_0, x_0, z_0), v, coeff)
return x_p, y_p, z_p
x, y, z = v
r, p, q = symbols("r, p, q", integer=True)
eq = sum(k*v for k, v in coeff.items())
eq_1 = _mexpand(eq.subs(zip(
(x, y, z), (r*x_0, r*y_0 + p, r*z_0 + q))))
A, B = eq_1.as_independent(r, as_Add=True)
x = A*x_0
y = (A*y_0 - _mexpand(B/r*p))
z = (A*z_0 - _mexpand(B/r*q))
return _remove_gcd(x, y, z)
def diop_ternary_quadratic_normal(eq, parameterize=False):
"""
Solves the quadratic ternary diophantine equation,
`ax^2 + by^2 + cz^2 = 0`.
Explanation
===========
Here the coefficients `a`, `b`, and `c` should be non zero. Otherwise the
equation will be a quadratic binary or univariate equation. If solvable,
returns a tuple `(x, y, z)` that satisfies the given equation. If the
equation does not have integer solutions, `(None, None, None)` is returned.
Usage
=====
``diop_ternary_quadratic_normal(eq)``: where ``eq`` is an equation of the form
`ax^2 + by^2 + cz^2 = 0`.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic_normal
>>> diop_ternary_quadratic_normal(x**2 + 3*y**2 - z**2)
(1, 0, 1)
>>> diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2)
(1, 0, 2)
>>> diop_ternary_quadratic_normal(34*x**2 - 3*y**2 - 301*z**2)
(4, 9, 1)
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == HomogeneousTernaryQuadraticNormal.name:
sol = _diop_ternary_quadratic_normal(var, coeff)
if len(sol) > 0:
x_0, y_0, z_0 = list(sol)[0]
else:
x_0, y_0, z_0 = None, None, None
if parameterize:
return _parametrize_ternary_quadratic(
(x_0, y_0, z_0), var, coeff)
return x_0, y_0, z_0
def _diop_ternary_quadratic_normal(var, coeff):
eq = sum([i * coeff[i] for i in coeff])
return HomogeneousTernaryQuadraticNormal(eq, free_symbols=var).solve()
def sqf_normal(a, b, c, steps=False):
"""
Return `a', b', c'`, the coefficients of the square-free normal
form of `ax^2 + by^2 + cz^2 = 0`, where `a', b', c'` are pairwise
prime. If `steps` is True then also return three tuples:
`sq`, `sqf`, and `(a', b', c')` where `sq` contains the square
factors of `a`, `b` and `c` after removing the `gcd(a, b, c)`;
`sqf` contains the values of `a`, `b` and `c` after removing
both the `gcd(a, b, c)` and the square factors.
The solutions for `ax^2 + by^2 + cz^2 = 0` can be
recovered from the solutions of `a'x^2 + b'y^2 + c'z^2 = 0`.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import sqf_normal
>>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11)
(11, 1, 5)
>>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11, True)
((3, 1, 7), (5, 55, 11), (11, 1, 5))
References
==========
.. [1] Legendre's Theorem, Legrange's Descent,
http://public.csusm.edu/aitken_html/notes/legendre.pdf
See Also
========
reconstruct()
"""
ABC = _remove_gcd(a, b, c)
sq = tuple(square_factor(i) for i in ABC)
sqf = A, B, C = tuple([i//j**2 for i,j in zip(ABC, sq)])
pc = igcd(A, B)
A /= pc
B /= pc
pa = igcd(B, C)
B /= pa
C /= pa
pb = igcd(A, C)
A /= pb
B /= pb
A *= pa
B *= pb
C *= pc
if steps:
return (sq, sqf, (A, B, C))
else:
return A, B, C
def square_factor(a):
r"""
Returns an integer `c` s.t. `a = c^2k, \ c,k \in Z`. Here `k` is square
free. `a` can be given as an integer or a dictionary of factors.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import square_factor
>>> square_factor(24)
2
>>> square_factor(-36*3)
6
>>> square_factor(1)
1
>>> square_factor({3: 2, 2: 1, -1: 1}) # -18
3
See Also
========
sympy.ntheory.factor_.core
"""
f = a if isinstance(a, dict) else factorint(a)
return Mul(*[p**(e//2) for p, e in f.items()])
def reconstruct(A, B, z):
"""
Reconstruct the `z` value of an equivalent solution of `ax^2 + by^2 + cz^2`
from the `z` value of a solution of the square-free normal form of the
equation, `a'*x^2 + b'*y^2 + c'*z^2`, where `a'`, `b'` and `c'` are square
free and `gcd(a', b', c') == 1`.
"""
f = factorint(igcd(A, B))
for p, e in f.items():
if e != 1:
raise ValueError('a and b should be square-free')
z *= p
return z
def ldescent(A, B):
"""
Return a non-trivial solution to `w^2 = Ax^2 + By^2` using
Lagrange's method; return None if there is no such solution.
.
Here, `A \\neq 0` and `B \\neq 0` and `A` and `B` are square free. Output a
tuple `(w_0, x_0, y_0)` which is a solution to the above equation.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import ldescent
>>> ldescent(1, 1) # w^2 = x^2 + y^2
(1, 1, 0)
>>> ldescent(4, -7) # w^2 = 4x^2 - 7y^2
(2, -1, 0)
This means that `x = -1, y = 0` and `w = 2` is a solution to the equation
`w^2 = 4x^2 - 7y^2`
>>> ldescent(5, -1) # w^2 = 5x^2 - y^2
(2, 1, -1)
References
==========
.. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart,
London Mathematical Society Student Texts 41, Cambridge University
Press, Cambridge, 1998.
.. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
[online], Available:
http://eprints.nottingham.ac.uk/60/1/kvxefz87.pdf
"""
if abs(A) > abs(B):
w, y, x = ldescent(B, A)
return w, x, y
if A == 1:
return (1, 1, 0)
if B == 1:
return (1, 0, 1)
if B == -1: # and A == -1
return
r = sqrt_mod(A, B)
Q = (r**2 - A) // B
if Q == 0:
B_0 = 1
d = 0
else:
div = divisors(Q)
B_0 = None
for i in div:
sQ, _exact = integer_nthroot(abs(Q) // i, 2)
if _exact:
B_0, d = sign(Q)*i, sQ
break
if B_0 is not None:
W, X, Y = ldescent(A, B_0)
return _remove_gcd((-A*X + r*W), (r*X - W), Y*(B_0*d))
def descent(A, B):
"""
Returns a non-trivial solution, (x, y, z), to `x^2 = Ay^2 + Bz^2`
using Lagrange's descent method with lattice-reduction. `A` and `B`
are assumed to be valid for such a solution to exist.
This is faster than the normal Lagrange's descent algorithm because
the Gaussian reduction is used.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import descent
>>> descent(3, 1) # x**2 = 3*y**2 + z**2
(1, 0, 1)
`(x, y, z) = (1, 0, 1)` is a solution to the above equation.
>>> descent(41, -113)
(-16, -3, 1)
References
==========
.. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
Mathematics of Computation, Volume 00, Number 0.
"""
if abs(A) > abs(B):
x, y, z = descent(B, A)
return x, z, y
if B == 1:
return (1, 0, 1)
if A == 1:
return (1, 1, 0)
if B == -A:
return (0, 1, 1)
if B == A:
x, z, y = descent(-1, A)
return (A*y, z, x)
w = sqrt_mod(A, B)
x_0, z_0 = gaussian_reduce(w, A, B)
t = (x_0**2 - A*z_0**2) // B
t_2 = square_factor(t)
t_1 = t // t_2**2
x_1, z_1, y_1 = descent(A, t_1)
return _remove_gcd(x_0*x_1 + A*z_0*z_1, z_0*x_1 + x_0*z_1, t_1*t_2*y_1)
def gaussian_reduce(w, a, b):
r"""
Returns a reduced solution `(x, z)` to the congruence
`X^2 - aZ^2 \equiv 0 \ (mod \ b)` so that `x^2 + |a|z^2` is minimal.
Details
=======
Here ``w`` is a solution of the congruence `x^2 \equiv a \ (mod \ b)`
References
==========
.. [1] Gaussian lattice Reduction [online]. Available:
http://home.ie.cuhk.edu.hk/~wkshum/wordpress/?p=404
.. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
Mathematics of Computation, Volume 00, Number 0.
"""
u = (0, 1)
v = (1, 0)
if dot(u, v, w, a, b) < 0:
v = (-v[0], -v[1])
if norm(u, w, a, b) < norm(v, w, a, b):
u, v = v, u
while norm(u, w, a, b) > norm(v, w, a, b):
k = dot(u, v, w, a, b) // dot(v, v, w, a, b)
u, v = v, (u[0]- k*v[0], u[1]- k*v[1])
u, v = v, u
if dot(u, v, w, a, b) < dot(v, v, w, a, b)/2 or norm((u[0]-v[0], u[1]-v[1]), w, a, b) > norm(v, w, a, b):
c = v
else:
c = (u[0] - v[0], u[1] - v[1])
return c[0]*w + b*c[1], c[0]
def dot(u, v, w, a, b):
r"""
Returns a special dot product of the vectors `u = (u_{1}, u_{2})` and
`v = (v_{1}, v_{2})` which is defined in order to reduce solution of
the congruence equation `X^2 - aZ^2 \equiv 0 \ (mod \ b)`.
"""
u_1, u_2 = u
v_1, v_2 = v
return (w*u_1 + b*u_2)*(w*v_1 + b*v_2) + abs(a)*u_1*v_1
def norm(u, w, a, b):
r"""
Returns the norm of the vector `u = (u_{1}, u_{2})` under the dot product
defined by `u \cdot v = (wu_{1} + bu_{2})(w*v_{1} + bv_{2}) + |a|*u_{1}*v_{1}`
where `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})`.
"""
u_1, u_2 = u
return sqrt(dot((u_1, u_2), (u_1, u_2), w, a, b))
def holzer(x, y, z, a, b, c):
r"""
Simplify the solution `(x, y, z)` of the equation
`ax^2 + by^2 = cz^2` with `a, b, c > 0` and `z^2 \geq \mid ab \mid` to
a new reduced solution `(x', y', z')` such that `z'^2 \leq \mid ab \mid`.
The algorithm is an interpretation of Mordell's reduction as described
on page 8 of Cremona and Rusin's paper [1]_ and the work of Mordell in
reference [2]_.
References
==========
.. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
Mathematics of Computation, Volume 00, Number 0.
.. [2] Diophantine Equations, L. J. Mordell, page 48.
"""
if _odd(c):
k = 2*c
else:
k = c//2
small = a*b*c
step = 0
while True:
t1, t2, t3 = a*x**2, b*y**2, c*z**2
# check that it's a solution
if t1 + t2 != t3:
if step == 0:
raise ValueError('bad starting solution')
break
x_0, y_0, z_0 = x, y, z
if max(t1, t2, t3) <= small:
# Holzer condition
break
uv = u, v = base_solution_linear(k, y_0, -x_0)
if None in uv:
break
p, q = -(a*u*x_0 + b*v*y_0), c*z_0
r = Rational(p, q)
if _even(c):
w = _nint_or_floor(p, q)
assert abs(w - r) <= S.Half
else:
w = p//q # floor
if _odd(a*u + b*v + c*w):
w += 1
assert abs(w - r) <= S.One
A = (a*u**2 + b*v**2 + c*w**2)
B = (a*u*x_0 + b*v*y_0 + c*w*z_0)
x = Rational(x_0*A - 2*u*B, k)
y = Rational(y_0*A - 2*v*B, k)
z = Rational(z_0*A - 2*w*B, k)
assert all(i.is_Integer for i in (x, y, z))
step += 1
return tuple([int(i) for i in (x_0, y_0, z_0)])
def diop_general_pythagorean(eq, param=symbols("m", integer=True)):
"""
Solves the general pythagorean equation,
`a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`.
Returns a tuple which contains a parametrized solution to the equation,
sorted in the same order as the input variables.
Usage
=====
``diop_general_pythagorean(eq, param)``: where ``eq`` is a general
pythagorean equation which is assumed to be zero and ``param`` is the base
parameter used to construct other parameters by subscripting.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_general_pythagorean
>>> from sympy.abc import a, b, c, d, e
>>> diop_general_pythagorean(a**2 + b**2 + c**2 - d**2)
(m1**2 + m2**2 - m3**2, 2*m1*m3, 2*m2*m3, m1**2 + m2**2 + m3**2)
>>> diop_general_pythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2)
(10*m1**2 + 10*m2**2 + 10*m3**2 - 10*m4**2, 15*m1**2 + 15*m2**2 + 15*m3**2 + 15*m4**2, 15*m1*m4, 12*m2*m4, 60*m3*m4)
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == GeneralPythagorean.name:
if param is None:
params = None
else:
params = symbols('%s1:%i' % (param, len(var)), integer=True)
return list(GeneralPythagorean(eq).solve(parameters=params))[0]
def diop_general_sum_of_squares(eq, limit=1):
r"""
Solves the equation `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.
Returns at most ``limit`` number of solutions.
Usage
=====
``general_sum_of_squares(eq, limit)`` : Here ``eq`` is an expression which
is assumed to be zero. Also, ``eq`` should be in the form,
`x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.
Details
=======
When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be
no solutions. Refer [1]_ for more details.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_squares
>>> from sympy.abc import a, b, c, d, e
>>> diop_general_sum_of_squares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345)
{(15, 22, 22, 24, 24)}
Reference
=========
.. [1] Representing an integer as a sum of three squares, [online],
Available:
http://www.proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == GeneralSumOfSquares.name:
return set(GeneralSumOfSquares(eq).solve(limit=limit))
def diop_general_sum_of_even_powers(eq, limit=1):
"""
Solves the equation `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`
where `e` is an even, integer power.
Returns at most ``limit`` number of solutions.
Usage
=====
``general_sum_of_even_powers(eq, limit)`` : Here ``eq`` is an expression which
is assumed to be zero. Also, ``eq`` should be in the form,
`x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_even_powers
>>> from sympy.abc import a, b
>>> diop_general_sum_of_even_powers(a**4 + b**4 - (2**4 + 3**4))
{(2, 3)}
See Also
========
power_representation
"""
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == GeneralSumOfEvenPowers.name:
return set(GeneralSumOfEvenPowers(eq).solve(limit=limit))
## Functions below this comment can be more suitably grouped under
## an Additive number theory module rather than the Diophantine
## equation module.
def partition(n, k=None, zeros=False):
"""
Returns a generator that can be used to generate partitions of an integer
`n`.
Explanation
===========
A partition of `n` is a set of positive integers which add up to `n`. For
example, partitions of 3 are 3, 1 + 2, 1 + 1 + 1. A partition is returned
as a tuple. If ``k`` equals None, then all possible partitions are returned
irrespective of their size, otherwise only the partitions of size ``k`` are
returned. If the ``zero`` parameter is set to True then a suitable
number of zeros are added at the end of every partition of size less than
``k``.
``zero`` parameter is considered only if ``k`` is not None. When the
partitions are over, the last `next()` call throws the ``StopIteration``
exception, so this function should always be used inside a try - except
block.
Details
=======
``partition(n, k)``: Here ``n`` is a positive integer and ``k`` is the size
of the partition which is also positive integer.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import partition
>>> f = partition(5)
>>> next(f)
(1, 1, 1, 1, 1)
>>> next(f)
(1, 1, 1, 2)
>>> g = partition(5, 3)
>>> next(g)
(1, 1, 3)
>>> next(g)
(1, 2, 2)
>>> g = partition(5, 3, zeros=True)
>>> next(g)
(0, 0, 5)
"""
from sympy.utilities.iterables import ordered_partitions
if not zeros or k is None:
for i in ordered_partitions(n, k):
yield tuple(i)
else:
for m in range(1, k + 1):
for i in ordered_partitions(n, m):
i = tuple(i)
yield (0,)*(k - len(i)) + i
def prime_as_sum_of_two_squares(p):
"""
Represent a prime `p` as a unique sum of two squares; this can
only be done if the prime is congruent to 1 mod 4.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import prime_as_sum_of_two_squares
>>> prime_as_sum_of_two_squares(7) # can't be done
>>> prime_as_sum_of_two_squares(5)
(1, 2)
Reference
=========
.. [1] Representing a number as a sum of four squares, [online],
Available: http://schorn.ch/lagrange.html
See Also
========
sum_of_squares()
"""
if not p % 4 == 1:
return
if p % 8 == 5:
b = 2
else:
b = 3
while pow(b, (p - 1) // 2, p) == 1:
b = nextprime(b)
b = pow(b, (p - 1) // 4, p)
a = p
while b**2 > p:
a, b = b, a % b
return (int(a % b), int(b)) # convert from long
def sum_of_three_squares(n):
r"""
Returns a 3-tuple `(a, b, c)` such that `a^2 + b^2 + c^2 = n` and
`a, b, c \geq 0`.
Returns None if `n = 4^a(8m + 7)` for some `a, m \in Z`. See
[1]_ for more details.
Usage
=====
``sum_of_three_squares(n)``: Here ``n`` is a non-negative integer.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import sum_of_three_squares
>>> sum_of_three_squares(44542)
(18, 37, 207)
References
==========
.. [1] Representing a number as a sum of three squares, [online],
Available: http://schorn.ch/lagrange.html
See Also
========
sum_of_squares()
"""
special = {1:(1, 0, 0), 2:(1, 1, 0), 3:(1, 1, 1), 10: (1, 3, 0), 34: (3, 3, 4), 58:(3, 7, 0),
85:(6, 7, 0), 130:(3, 11, 0), 214:(3, 6, 13), 226:(8, 9, 9), 370:(8, 9, 15),
526:(6, 7, 21), 706:(15, 15, 16), 730:(1, 27, 0), 1414:(6, 17, 33), 1906:(13, 21, 36),
2986: (21, 32, 39), 9634: (56, 57, 57)}
v = 0
if n == 0:
return (0, 0, 0)
v = multiplicity(4, n)
n //= 4**v
if n % 8 == 7:
return
if n in special.keys():
x, y, z = special[n]
return _sorted_tuple(2**v*x, 2**v*y, 2**v*z)
s, _exact = integer_nthroot(n, 2)
if _exact:
return (2**v*s, 0, 0)
x = None
if n % 8 == 3:
s = s if _odd(s) else s - 1
for x in range(s, -1, -2):
N = (n - x**2) // 2
if isprime(N):
y, z = prime_as_sum_of_two_squares(N)
return _sorted_tuple(2**v*x, 2**v*(y + z), 2**v*abs(y - z))
return
if n % 8 == 2 or n % 8 == 6:
s = s if _odd(s) else s - 1
else:
s = s - 1 if _odd(s) else s
for x in range(s, -1, -2):
N = n - x**2
if isprime(N):
y, z = prime_as_sum_of_two_squares(N)
return _sorted_tuple(2**v*x, 2**v*y, 2**v*z)
def sum_of_four_squares(n):
r"""
Returns a 4-tuple `(a, b, c, d)` such that `a^2 + b^2 + c^2 + d^2 = n`.
Here `a, b, c, d \geq 0`.
Usage
=====
``sum_of_four_squares(n)``: Here ``n`` is a non-negative integer.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import sum_of_four_squares
>>> sum_of_four_squares(3456)
(8, 8, 32, 48)
>>> sum_of_four_squares(1294585930293)
(0, 1234, 2161, 1137796)
References
==========
.. [1] Representing a number as a sum of four squares, [online],
Available: http://schorn.ch/lagrange.html
See Also
========
sum_of_squares()
"""
if n == 0:
return (0, 0, 0, 0)
v = multiplicity(4, n)
n //= 4**v
if n % 8 == 7:
d = 2
n = n - 4
elif n % 8 == 6 or n % 8 == 2:
d = 1
n = n - 1
else:
d = 0
x, y, z = sum_of_three_squares(n)
return _sorted_tuple(2**v*d, 2**v*x, 2**v*y, 2**v*z)
def power_representation(n, p, k, zeros=False):
r"""
Returns a generator for finding k-tuples of integers,
`(n_{1}, n_{2}, . . . n_{k})`, such that
`n = n_{1}^p + n_{2}^p + . . . n_{k}^p`.
Usage
=====
``power_representation(n, p, k, zeros)``: Represent non-negative number
``n`` as a sum of ``k`` ``p``\ th powers. If ``zeros`` is true, then the
solutions is allowed to contain zeros.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import power_representation
Represent 1729 as a sum of two cubes:
>>> f = power_representation(1729, 3, 2)
>>> next(f)
(9, 10)
>>> next(f)
(1, 12)
If the flag `zeros` is True, the solution may contain tuples with
zeros; any such solutions will be generated after the solutions
without zeros:
>>> list(power_representation(125, 2, 3, zeros=True))
[(5, 6, 8), (3, 4, 10), (0, 5, 10), (0, 2, 11)]
For even `p` the `permute_sign` function can be used to get all
signed values:
>>> from sympy.utilities.iterables import permute_signs
>>> list(permute_signs((1, 12)))
[(1, 12), (-1, 12), (1, -12), (-1, -12)]
All possible signed permutations can also be obtained:
>>> from sympy.utilities.iterables import signed_permutations
>>> list(signed_permutations((1, 12)))
[(1, 12), (-1, 12), (1, -12), (-1, -12), (12, 1), (-12, 1), (12, -1), (-12, -1)]
"""
n, p, k = [as_int(i) for i in (n, p, k)]
if n < 0:
if p % 2:
for t in power_representation(-n, p, k, zeros):
yield tuple(-i for i in t)
return
if p < 1 or k < 1:
raise ValueError(filldedent('''
Expecting positive integers for `(p, k)`, but got `(%s, %s)`'''
% (p, k)))
if n == 0:
if zeros:
yield (0,)*k
return
if k == 1:
if p == 1:
yield (n,)
else:
be = perfect_power(n)
if be:
b, e = be
d, r = divmod(e, p)
if not r:
yield (b**d,)
return
if p == 1:
for t in partition(n, k, zeros=zeros):
yield t
return
if p == 2:
feasible = _can_do_sum_of_squares(n, k)
if not feasible:
return
if not zeros and n > 33 and k >= 5 and k <= n and n - k in (
13, 10, 7, 5, 4, 2, 1):
'''Todd G. Will, "When Is n^2 a Sum of k Squares?", [online].
Available: https://www.maa.org/sites/default/files/Will-MMz-201037918.pdf'''
return
if feasible is not True: # it's prime and k == 2
yield prime_as_sum_of_two_squares(n)
return
if k == 2 and p > 2:
be = perfect_power(n)
if be and be[1] % p == 0:
return # Fermat: a**n + b**n = c**n has no solution for n > 2
if n >= k:
a = integer_nthroot(n - (k - 1), p)[0]
for t in pow_rep_recursive(a, k, n, [], p):
yield tuple(reversed(t))
if zeros:
a = integer_nthroot(n, p)[0]
for i in range(1, k):
for t in pow_rep_recursive(a, i, n, [], p):
yield tuple(reversed(t + (0,)*(k - i)))
sum_of_powers = power_representation
def pow_rep_recursive(n_i, k, n_remaining, terms, p):
if k == 0 and n_remaining == 0:
yield tuple(terms)
else:
if n_i >= 1 and k > 0:
yield from pow_rep_recursive(n_i - 1, k, n_remaining, terms, p)
residual = n_remaining - pow(n_i, p)
if residual >= 0:
yield from pow_rep_recursive(n_i, k - 1, residual, terms + [n_i], p)
def sum_of_squares(n, k, zeros=False):
"""Return a generator that yields the k-tuples of nonnegative
values, the squares of which sum to n. If zeros is False (default)
then the solution will not contain zeros. The nonnegative
elements of a tuple are sorted.
* If k == 1 and n is square, (n,) is returned.
* If k == 2 then n can only be written as a sum of squares if
every prime in the factorization of n that has the form
4*k + 3 has an even multiplicity. If n is prime then
it can only be written as a sum of two squares if it is
in the form 4*k + 1.
* if k == 3 then n can be written as a sum of squares if it does
not have the form 4**m*(8*k + 7).
* all integers can be written as the sum of 4 squares.
* if k > 4 then n can be partitioned and each partition can
be written as a sum of 4 squares; if n is not evenly divisible
by 4 then n can be written as a sum of squares only if the
an additional partition can be written as sum of squares.
For example, if k = 6 then n is partitioned into two parts,
the first being written as a sum of 4 squares and the second
being written as a sum of 2 squares -- which can only be
done if the condition above for k = 2 can be met, so this will
automatically reject certain partitions of n.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import sum_of_squares
>>> list(sum_of_squares(25, 2))
[(3, 4)]
>>> list(sum_of_squares(25, 2, True))
[(3, 4), (0, 5)]
>>> list(sum_of_squares(25, 4))
[(1, 2, 2, 4)]
See Also
========
sympy.utilities.iterables.signed_permutations
"""
yield from power_representation(n, 2, k, zeros)
def _can_do_sum_of_squares(n, k):
"""Return True if n can be written as the sum of k squares,
False if it can't, or 1 if ``k == 2`` and ``n`` is prime (in which
case it *can* be written as a sum of two squares). A False
is returned only if it can't be written as ``k``-squares, even
if 0s are allowed.
"""
if k < 1:
return False
if n < 0:
return False
if n == 0:
return True
if k == 1:
return is_square(n)
if k == 2:
if n in (1, 2):
return True
if isprime(n):
if n % 4 == 1:
return 1 # signal that it was prime
return False
else:
f = factorint(n)
for p, m in f.items():
# we can proceed iff no prime factor in the form 4*k + 3
# has an odd multiplicity
if (p % 4 == 3) and m % 2:
return False
return True
if k == 3:
if (n//4**multiplicity(4, n)) % 8 == 7:
return False
# every number can be written as a sum of 4 squares; for k > 4 partitions
# can be 0
return True
|
3d0e8f6afe34b47e0d280bef2c70b1a5894457108920c188b04cd7847c170f82 | r"""
This module contains :py:meth:`~sympy.solvers.ode.dsolve` and different helper
functions that it uses.
:py:meth:`~sympy.solvers.ode.dsolve` solves ordinary differential equations.
See the docstring on the various functions for their uses. Note that partial
differential equations support is in ``pde.py``. Note that hint functions
have docstrings describing their various methods, but they are intended for
internal use. Use ``dsolve(ode, func, hint=hint)`` to solve an ODE using a
specific hint. See also the docstring on
:py:meth:`~sympy.solvers.ode.dsolve`.
**Functions in this module**
These are the user functions in this module:
- :py:meth:`~sympy.solvers.ode.dsolve` - Solves ODEs.
- :py:meth:`~sympy.solvers.ode.classify_ode` - Classifies ODEs into
possible hints for :py:meth:`~sympy.solvers.ode.dsolve`.
- :py:meth:`~sympy.solvers.ode.checkodesol` - Checks if an equation is the
solution to an ODE.
- :py:meth:`~sympy.solvers.ode.homogeneous_order` - Returns the
homogeneous order of an expression.
- :py:meth:`~sympy.solvers.ode.infinitesimals` - Returns the infinitesimals
of the Lie group of point transformations of an ODE, such that it is
invariant.
- :py:meth:`~sympy.solvers.ode.checkinfsol` - Checks if the given infinitesimals
are the actual infinitesimals of a first order ODE.
These are the non-solver helper functions that are for internal use. The
user should use the various options to
:py:meth:`~sympy.solvers.ode.dsolve` to obtain the functionality provided
by these functions:
- :py:meth:`~sympy.solvers.ode.ode.odesimp` - Does all forms of ODE
simplification.
- :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity` - A key function for
comparing solutions by simplicity.
- :py:meth:`~sympy.solvers.ode.constantsimp` - Simplifies arbitrary
constants.
- :py:meth:`~sympy.solvers.ode.ode.constant_renumber` - Renumber arbitrary
constants.
- :py:meth:`~sympy.solvers.ode.ode._handle_Integral` - Evaluate unevaluated
Integrals.
See also the docstrings of these functions.
**Currently implemented solver methods**
The following methods are implemented for solving ordinary differential
equations. See the docstrings of the various hint functions for more
information on each (run ``help(ode)``):
- 1st order separable differential equations.
- 1st order differential equations whose coefficients or `dx` and `dy` are
functions homogeneous of the same order.
- 1st order exact differential equations.
- 1st order linear differential equations.
- 1st order Bernoulli differential equations.
- Power series solutions for first order differential equations.
- Lie Group method of solving first order differential equations.
- 2nd order Liouville differential equations.
- Power series solutions for second order differential equations
at ordinary and regular singular points.
- `n`\th order differential equation that can be solved with algebraic
rearrangement and integration.
- `n`\th order linear homogeneous differential equation with constant
coefficients.
- `n`\th order linear inhomogeneous differential equation with constant
coefficients using the method of undetermined coefficients.
- `n`\th order linear inhomogeneous differential equation with constant
coefficients using the method of variation of parameters.
**Philosophy behind this module**
This module is designed to make it easy to add new ODE solving methods without
having to mess with the solving code for other methods. The idea is that
there is a :py:meth:`~sympy.solvers.ode.classify_ode` function, which takes in
an ODE and tells you what hints, if any, will solve the ODE. It does this
without attempting to solve the ODE, so it is fast. Each solving method is a
hint, and it has its own function, named ``ode_<hint>``. That function takes
in the ODE and any match expression gathered by
:py:meth:`~sympy.solvers.ode.classify_ode` and returns a solved result. If
this result has any integrals in it, the hint function will return an
unevaluated :py:class:`~sympy.integrals.integrals.Integral` class.
:py:meth:`~sympy.solvers.ode.dsolve`, which is the user wrapper function
around all of this, will then call :py:meth:`~sympy.solvers.ode.ode.odesimp` on
the result, which, among other things, will attempt to solve the equation for
the dependent variable (the function we are solving for), simplify the
arbitrary constants in the expression, and evaluate any integrals, if the hint
allows it.
**How to add new solution methods**
If you have an ODE that you want :py:meth:`~sympy.solvers.ode.dsolve` to be
able to solve, try to avoid adding special case code here. Instead, try
finding a general method that will solve your ODE, as well as others. This
way, the :py:mod:`~sympy.solvers.ode` module will become more robust, and
unhindered by special case hacks. WolphramAlpha and Maple's
DETools[odeadvisor] function are two resources you can use to classify a
specific ODE. It is also better for a method to work with an `n`\th order ODE
instead of only with specific orders, if possible.
To add a new method, there are a few things that you need to do. First, you
need a hint name for your method. Try to name your hint so that it is
unambiguous with all other methods, including ones that may not be implemented
yet. If your method uses integrals, also include a ``hint_Integral`` hint.
If there is more than one way to solve ODEs with your method, include a hint
for each one, as well as a ``<hint>_best`` hint. Your ``ode_<hint>_best()``
function should choose the best using min with ``ode_sol_simplicity`` as the
key argument. See
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best`, for example.
The function that uses your method will be called ``ode_<hint>()``, so the
hint must only use characters that are allowed in a Python function name
(alphanumeric characters and the underscore '``_``' character). Include a
function for every hint, except for ``_Integral`` hints
(:py:meth:`~sympy.solvers.ode.dsolve` takes care of those automatically).
Hint names should be all lowercase, unless a word is commonly capitalized
(such as Integral or Bernoulli). If you have a hint that you do not want to
run with ``all_Integral`` that doesn't have an ``_Integral`` counterpart (such
as a best hint that would defeat the purpose of ``all_Integral``), you will
need to remove it manually in the :py:meth:`~sympy.solvers.ode.dsolve` code.
See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for
guidelines on writing a hint name.
Determine *in general* how the solutions returned by your method compare with
other methods that can potentially solve the same ODEs. Then, put your hints
in the :py:data:`~sympy.solvers.ode.allhints` tuple in the order that they
should be called. The ordering of this tuple determines which hints are
default. Note that exceptions are ok, because it is easy for the user to
choose individual hints with :py:meth:`~sympy.solvers.ode.dsolve`. In
general, ``_Integral`` variants should go at the end of the list, and
``_best`` variants should go before the various hints they apply to. For
example, the ``undetermined_coefficients`` hint comes before the
``variation_of_parameters`` hint because, even though variation of parameters
is more general than undetermined coefficients, undetermined coefficients
generally returns cleaner results for the ODEs that it can solve than
variation of parameters does, and it does not require integration, so it is
much faster.
Next, you need to have a match expression or a function that matches the type
of the ODE, which you should put in :py:meth:`~sympy.solvers.ode.classify_ode`
(if the match function is more than just a few lines, like
:py:meth:`~sympy.solvers.ode.ode._undetermined_coefficients_match`, it should go
outside of :py:meth:`~sympy.solvers.ode.classify_ode`). It should match the
ODE without solving for it as much as possible, so that
:py:meth:`~sympy.solvers.ode.classify_ode` remains fast and is not hindered by
bugs in solving code. Be sure to consider corner cases. For example, if your
solution method involves dividing by something, make sure you exclude the case
where that division will be 0.
In most cases, the matching of the ODE will also give you the various parts
that you need to solve it. You should put that in a dictionary (``.match()``
will do this for you), and add that as ``matching_hints['hint'] = matchdict``
in the relevant part of :py:meth:`~sympy.solvers.ode.classify_ode`.
:py:meth:`~sympy.solvers.ode.classify_ode` will then send this to
:py:meth:`~sympy.solvers.ode.dsolve`, which will send it to your function as
the ``match`` argument. Your function should be named ``ode_<hint>(eq, func,
order, match)`. If you need to send more information, put it in the ``match``
dictionary. For example, if you had to substitute in a dummy variable in
:py:meth:`~sympy.solvers.ode.classify_ode` to match the ODE, you will need to
pass it to your function using the `match` dict to access it. You can access
the independent variable using ``func.args[0]``, and the dependent variable
(the function you are trying to solve for) as ``func.func``. If, while trying
to solve the ODE, you find that you cannot, raise ``NotImplementedError``.
:py:meth:`~sympy.solvers.ode.dsolve` will catch this error with the ``all``
meta-hint, rather than causing the whole routine to fail.
Add a docstring to your function that describes the method employed. Like
with anything else in SymPy, you will need to add a doctest to the docstring,
in addition to real tests in ``test_ode.py``. Try to maintain consistency
with the other hint functions' docstrings. Add your method to the list at the
top of this docstring. Also, add your method to ``ode.rst`` in the
``docs/src`` directory, so that the Sphinx docs will pull its docstring into
the main SymPy documentation. Be sure to make the Sphinx documentation by
running ``make html`` from within the doc directory to verify that the
docstring formats correctly.
If your solution method involves integrating, use :py:obj:`~.Integral` instead of
:py:meth:`~sympy.core.expr.Expr.integrate`. This allows the user to bypass
hard/slow integration by using the ``_Integral`` variant of your hint. In
most cases, calling :py:meth:`sympy.core.basic.Basic.doit` will integrate your
solution. If this is not the case, you will need to write special code in
:py:meth:`~sympy.solvers.ode.ode._handle_Integral`. Arbitrary constants should be
symbols named ``C1``, ``C2``, and so on. All solution methods should return
an equality instance. If you need an arbitrary number of arbitrary constants,
you can use ``constants = numbered_symbols(prefix='C', cls=Symbol, start=1)``.
If it is possible to solve for the dependent function in a general way, do so.
Otherwise, do as best as you can, but do not call solve in your
``ode_<hint>()`` function. :py:meth:`~sympy.solvers.ode.ode.odesimp` will attempt
to solve the solution for you, so you do not need to do that. Lastly, if your
ODE has a common simplification that can be applied to your solutions, you can
add a special case in :py:meth:`~sympy.solvers.ode.ode.odesimp` for it. For
example, solutions returned from the ``1st_homogeneous_coeff`` hints often
have many :obj:`~sympy.functions.elementary.exponential.log` terms, so
:py:meth:`~sympy.solvers.ode.ode.odesimp` calls
:py:meth:`~sympy.simplify.simplify.logcombine` on them (it also helps to write
the arbitrary constant as ``log(C1)`` instead of ``C1`` in this case). Also
consider common ways that you can rearrange your solution to have
:py:meth:`~sympy.solvers.ode.constantsimp` take better advantage of it. It is
better to put simplification in :py:meth:`~sympy.solvers.ode.ode.odesimp` than in
your method, because it can then be turned off with the simplify flag in
:py:meth:`~sympy.solvers.ode.dsolve`. If you have any extraneous
simplification in your function, be sure to only run it using ``if
match.get('simplify', True):``, especially if it can be slow or if it can
reduce the domain of the solution.
Finally, as with every contribution to SymPy, your method will need to be
tested. Add a test for each method in ``test_ode.py``. Follow the
conventions there, i.e., test the solver using ``dsolve(eq, f(x),
hint=your_hint)``, and also test the solution using
:py:meth:`~sympy.solvers.ode.checkodesol` (you can put these in a separate
tests and skip/XFAIL if it runs too slow/doesn't work). Be sure to call your
hint specifically in :py:meth:`~sympy.solvers.ode.dsolve`, that way the test
won't be broken simply by the introduction of another matching hint. If your
method works for higher order (>1) ODEs, you will need to run ``sol =
constant_renumber(sol, 'C', 1, order)`` for each solution, where ``order`` is
the order of the ODE. This is because ``constant_renumber`` renumbers the
arbitrary constants by printing order, which is platform dependent. Try to
test every corner case of your solver, including a range of orders if it is a
`n`\th order solver, but if your solver is slow, such as if it involves hard
integration, try to keep the test run time down.
Feel free to refactor existing hints to avoid duplicating code or creating
inconsistencies. If you can show that your method exactly duplicates an
existing method, including in the simplicity and speed of obtaining the
solutions, then you can remove the old, less general method. The existing
code is tested extensively in ``test_ode.py``, so if anything is broken, one
of those tests will surely fail.
"""
from collections import defaultdict
from itertools import islice
from sympy.functions import hyper
from sympy.core import Add, S, Mul, Pow, oo, Rational
from sympy.core.compatibility import ordered, iterable
from sympy.core.containers import Tuple
from sympy.core.exprtools import factor_terms
from sympy.core.expr import AtomicExpr, Expr
from sympy.core.function import (Function, Derivative, AppliedUndef, diff,
expand, expand_mul, Subs, _mexpand)
from sympy.core.multidimensional import vectorize
from sympy.core.numbers import NaN, zoo, Number
from sympy.core.relational import Equality, Eq
from sympy.core.symbol import Symbol, Wild, Dummy, symbols
from sympy.core.sympify import sympify
from sympy.logic.boolalg import (BooleanAtom, BooleanTrue,
BooleanFalse)
from sympy.functions import cos, cosh, exp, im, log, re, sin, sinh, sqrt, \
atan2, conjugate, cbrt, besselj, bessely, airyai, airybi
from sympy.functions.combinatorial.factorials import factorial
from sympy.integrals.integrals import Integral, integrate
from sympy.matrices import wronskian
from sympy.polys import (Poly, RootOf, rootof, terms_gcd,
PolynomialError, lcm, roots, gcd)
from sympy.polys.polytools import cancel, degree, div
from sympy.series import Order
from sympy.series.series import series
from sympy.simplify import (collect, logcombine, powsimp, # type: ignore
separatevars, simplify, trigsimp, posify, cse)
from sympy.simplify.powsimp import powdenest
from sympy.simplify.radsimp import collect_const
from sympy.solvers import checksol, solve
from sympy.solvers.pde import pdsolve
from sympy.utilities import numbered_symbols, default_sort_key, sift
from sympy.utilities.iterables import uniq
from sympy.solvers.deutils import _preprocess, ode_order, _desolve
from .subscheck import sub_func_doit
#: This is a list of hints in the order that they should be preferred by
#: :py:meth:`~sympy.solvers.ode.classify_ode`. In general, hints earlier in the
#: list should produce simpler solutions than those later in the list (for
#: ODEs that fit both). For now, the order of this list is based on empirical
#: observations by the developers of SymPy.
#:
#: The hint used by :py:meth:`~sympy.solvers.ode.dsolve` for a specific ODE
#: can be overridden (see the docstring).
#:
#: In general, ``_Integral`` hints are grouped at the end of the list, unless
#: there is a method that returns an unevaluable integral most of the time
#: (which go near the end of the list anyway). ``default``, ``all``,
#: ``best``, and ``all_Integral`` meta-hints should not be included in this
#: list, but ``_best`` and ``_Integral`` hints should be included.
allhints = (
"factorable",
"nth_algebraic",
"separable",
"1st_exact",
"1st_linear",
"Bernoulli",
"Riccati_special_minus2",
"1st_homogeneous_coeff_best",
"1st_homogeneous_coeff_subs_indep_div_dep",
"1st_homogeneous_coeff_subs_dep_div_indep",
"almost_linear",
"linear_coefficients",
"separable_reduced",
"1st_power_series",
"lie_group",
"nth_linear_constant_coeff_homogeneous",
"nth_linear_euler_eq_homogeneous",
"nth_linear_constant_coeff_undetermined_coefficients",
"nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients",
"nth_linear_constant_coeff_variation_of_parameters",
"nth_linear_euler_eq_nonhomogeneous_variation_of_parameters",
"Liouville",
"2nd_linear_airy",
"2nd_linear_bessel",
"2nd_hypergeometric",
"2nd_hypergeometric_Integral",
"nth_order_reducible",
"2nd_power_series_ordinary",
"2nd_power_series_regular",
"nth_algebraic_Integral",
"separable_Integral",
"1st_exact_Integral",
"1st_linear_Integral",
"Bernoulli_Integral",
"1st_homogeneous_coeff_subs_indep_div_dep_Integral",
"1st_homogeneous_coeff_subs_dep_div_indep_Integral",
"almost_linear_Integral",
"linear_coefficients_Integral",
"separable_reduced_Integral",
"nth_linear_constant_coeff_variation_of_parameters_Integral",
"nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral",
"Liouville_Integral",
"2nd_nonlinear_autonomous_conserved",
"2nd_nonlinear_autonomous_conserved_Integral",
)
lie_heuristics = (
"abaco1_simple",
"abaco1_product",
"abaco2_similar",
"abaco2_unique_unknown",
"abaco2_unique_general",
"linear",
"function_sum",
"bivariate",
"chi"
)
def get_numbered_constants(eq, num=1, start=1, prefix='C'):
"""
Returns a list of constants that do not occur
in eq already.
"""
ncs = iter_numbered_constants(eq, start, prefix)
Cs = [next(ncs) for i in range(num)]
return (Cs[0] if num == 1 else tuple(Cs))
def iter_numbered_constants(eq, start=1, prefix='C'):
"""
Returns an iterator of constants that do not occur
in eq already.
"""
if isinstance(eq, (Expr, Eq)):
eq = [eq]
elif not iterable(eq):
raise ValueError("Expected Expr or iterable but got %s" % eq)
atom_set = set().union(*[i.free_symbols for i in eq])
func_set = set().union(*[i.atoms(Function) for i in eq])
if func_set:
atom_set |= {Symbol(str(f.func)) for f in func_set}
return numbered_symbols(start=start, prefix=prefix, exclude=atom_set)
def dsolve(eq, func=None, hint="default", simplify=True,
ics= None, xi=None, eta=None, x0=0, n=6, **kwargs):
r"""
Solves any (supported) kind of ordinary differential equation and
system of ordinary differential equations.
For single ordinary differential equation
=========================================
It is classified under this when number of equation in ``eq`` is one.
**Usage**
``dsolve(eq, f(x), hint)`` -> Solve ordinary differential equation
``eq`` for function ``f(x)``, using method ``hint``.
**Details**
``eq`` can be any supported ordinary differential equation (see the
:py:mod:`~sympy.solvers.ode` docstring for supported methods).
This can either be an :py:class:`~sympy.core.relational.Equality`,
or an expression, which is assumed to be equal to ``0``.
``f(x)`` is a function of one variable whose derivatives in that
variable make up the ordinary differential equation ``eq``. In
many cases it is not necessary to provide this; it will be
autodetected (and an error raised if it couldn't be detected).
``hint`` is the solving method that you want dsolve to use. Use
``classify_ode(eq, f(x))`` to get all of the possible hints for an
ODE. The default hint, ``default``, will use whatever hint is
returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. See
Hints below for more options that you can use for hint.
``simplify`` enables simplification by
:py:meth:`~sympy.solvers.ode.ode.odesimp`. See its docstring for more
information. Turn this off, for example, to disable solving of
solutions for ``func`` or simplification of arbitrary constants.
It will still integrate with this hint. Note that the solution may
contain more arbitrary constants than the order of the ODE with
this option enabled.
``xi`` and ``eta`` are the infinitesimal functions of an ordinary
differential equation. They are the infinitesimals of the Lie group
of point transformations for which the differential equation is
invariant. The user can specify values for the infinitesimals. If
nothing is specified, ``xi`` and ``eta`` are calculated using
:py:meth:`~sympy.solvers.ode.infinitesimals` with the help of various
heuristics.
``ics`` is the set of initial/boundary conditions for the differential equation.
It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2):
x3}`` and so on. For power series solutions, if no initial
conditions are specified ``f(0)`` is assumed to be ``C0`` and the power
series solution is calculated about 0.
``x0`` is the point about which the power series solution of a differential
equation is to be evaluated.
``n`` gives the exponent of the dependent variable up to which the power series
solution of a differential equation is to be evaluated.
**Hints**
Aside from the various solving methods, there are also some meta-hints
that you can pass to :py:meth:`~sympy.solvers.ode.dsolve`:
``default``:
This uses whatever hint is returned first by
:py:meth:`~sympy.solvers.ode.classify_ode`. This is the
default argument to :py:meth:`~sympy.solvers.ode.dsolve`.
``all``:
To make :py:meth:`~sympy.solvers.ode.dsolve` apply all
relevant classification hints, use ``dsolve(ODE, func,
hint="all")``. This will return a dictionary of
``hint:solution`` terms. If a hint causes dsolve to raise the
``NotImplementedError``, value of that hint's key will be the
exception object raised. The dictionary will also include
some special keys:
- ``order``: The order of the ODE. See also
:py:meth:`~sympy.solvers.deutils.ode_order` in
``deutils.py``.
- ``best``: The simplest hint; what would be returned by
``best`` below.
- ``best_hint``: The hint that would produce the solution
given by ``best``. If more than one hint produces the best
solution, the first one in the tuple returned by
:py:meth:`~sympy.solvers.ode.classify_ode` is chosen.
- ``default``: The solution that would be returned by default.
This is the one produced by the hint that appears first in
the tuple returned by
:py:meth:`~sympy.solvers.ode.classify_ode`.
``all_Integral``:
This is the same as ``all``, except if a hint also has a
corresponding ``_Integral`` hint, it only returns the
``_Integral`` hint. This is useful if ``all`` causes
:py:meth:`~sympy.solvers.ode.dsolve` to hang because of a
difficult or impossible integral. This meta-hint will also be
much faster than ``all``, because
:py:meth:`~sympy.core.expr.Expr.integrate` is an expensive
routine.
``best``:
To have :py:meth:`~sympy.solvers.ode.dsolve` try all methods
and return the simplest one. This takes into account whether
the solution is solvable in the function, whether it contains
any Integral classes (i.e. unevaluatable integrals), and
which one is the shortest in size.
See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for
more info on hints, and the :py:mod:`~sympy.solvers.ode` docstring for
a list of all supported hints.
**Tips**
- You can declare the derivative of an unknown function this way:
>>> from sympy import Function, Derivative
>>> from sympy.abc import x # x is the independent variable
>>> f = Function("f")(x) # f is a function of x
>>> # f_ will be the derivative of f with respect to x
>>> f_ = Derivative(f, x)
- See ``test_ode.py`` for many tests, which serves also as a set of
examples for how to use :py:meth:`~sympy.solvers.ode.dsolve`.
- :py:meth:`~sympy.solvers.ode.dsolve` always returns an
:py:class:`~sympy.core.relational.Equality` class (except for the
case when the hint is ``all`` or ``all_Integral``). If possible, it
solves the solution explicitly for the function being solved for.
Otherwise, it returns an implicit solution.
- Arbitrary constants are symbols named ``C1``, ``C2``, and so on.
- Because all solutions should be mathematically equivalent, some
hints may return the exact same result for an ODE. Often, though,
two different hints will return the same solution formatted
differently. The two should be equivalent. Also note that sometimes
the values of the arbitrary constants in two different solutions may
not be the same, because one constant may have "absorbed" other
constants into it.
- Do ``help(ode.ode_<hintname>)`` to get help more information on a
specific hint, where ``<hintname>`` is the name of a hint without
``_Integral``.
For system of ordinary differential equations
=============================================
**Usage**
``dsolve(eq, func)`` -> Solve a system of ordinary differential
equations ``eq`` for ``func`` being list of functions including
`x(t)`, `y(t)`, `z(t)` where number of functions in the list depends
upon the number of equations provided in ``eq``.
**Details**
``eq`` can be any supported system of ordinary differential equations
This can either be an :py:class:`~sympy.core.relational.Equality`,
or an expression, which is assumed to be equal to ``0``.
``func`` holds ``x(t)`` and ``y(t)`` being functions of one variable which
together with some of their derivatives make up the system of ordinary
differential equation ``eq``. It is not necessary to provide this; it
will be autodetected (and an error raised if it couldn't be detected).
**Hints**
The hints are formed by parameters returned by classify_sysode, combining
them give hints name used later for forming method name.
Examples
========
>>> from sympy import Function, dsolve, Eq, Derivative, sin, cos, symbols
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(Derivative(f(x), x, x) + 9*f(x), f(x))
Eq(f(x), C1*sin(3*x) + C2*cos(3*x))
>>> eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x)
>>> dsolve(eq, hint='1st_exact')
[Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
>>> dsolve(eq, hint='almost_linear')
[Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
>>> t = symbols('t')
>>> x, y = symbols('x, y', cls=Function)
>>> eq = (Eq(Derivative(x(t),t), 12*t*x(t) + 8*y(t)), Eq(Derivative(y(t),t), 21*x(t) + 7*t*y(t)))
>>> dsolve(eq)
[Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t)),
Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t) +
exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)))]
>>> eq = (Eq(Derivative(x(t),t),x(t)*y(t)*sin(t)), Eq(Derivative(y(t),t),y(t)**2*sin(t)))
>>> dsolve(eq)
{Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t))), Eq(y(t), -1/(C1 - cos(t)))}
"""
if iterable(eq):
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)
orderedhints = gethints['ordered_hints']
for hint in hints:
try:
rv = _helper_simplify(eq, hint, hints[hint], simplify)
except NotImplementedError as detail:
failed_hints[hint] = detail
else:
retdict[hint] = rv
func = hints[hint]['func']
retdict['best'] = min(list(retdict.values()), key=lambda x:
ode_sol_simplicity(x, func, trysolving=not simplify))
if given_hint == 'best':
return retdict['best']
for i in orderedhints:
if retdict['best'] == retdict.get(i, None):
retdict['best_hint'] = i
break
retdict['default'] = gethints['default']
retdict['order'] = gethints['order']
retdict.update(failed_hints)
return retdict
else:
# The key 'hint' stores the hint needed to be solved for.
hint = hints['hint']
return _helper_simplify(eq, hint, hints, simplify, ics=ics)
def _helper_simplify(eq, hint, match, simplify=True, ics=None, **kwargs):
r"""
Helper function of dsolve that calls the respective
:py:mod:`~sympy.solvers.ode` functions to solve for the ordinary
differential equations. This minimizes the computation in calling
:py:meth:`~sympy.solvers.deutils._desolve` multiple times.
"""
r = match
func = r['func']
order = r['order']
match = r[hint]
if isinstance(match, SingleODESolver):
solvefunc = match
elif hint.endswith('_Integral'):
solvefunc = globals()['ode_' + hint[:-len('_Integral')]]
else:
solvefunc = globals()['ode_' + hint]
free = eq.free_symbols
cons = lambda s: s.free_symbols.difference(free)
if simplify:
# odesimp() will attempt to integrate, if necessary, apply constantsimp(),
# attempt to solve for func, and apply any other hint specific
# simplifications
if isinstance(solvefunc, SingleODESolver):
sols = solvefunc.get_general_solution()
else:
sols = solvefunc(eq, func, order, match)
if iterable(sols):
rv = [odesimp(eq, s, func, hint) for s in sols]
else:
rv = odesimp(eq, sols, func, hint)
else:
# We still want to integrate (you can disable it separately with the hint)
if isinstance(solvefunc, SingleODESolver):
exprs = solvefunc.get_general_solution(simplify=False)
else:
match['simplify'] = False # Some hints can take advantage of this option
exprs = solvefunc(eq, func, order, match)
if isinstance(exprs, list):
rv = [_handle_Integral(expr, func, hint) for expr in exprs]
else:
rv = _handle_Integral(exprs, func, hint)
if isinstance(rv, list):
if simplify:
rv = _remove_redundant_solutions(eq, rv, order, func.args[0])
if len(rv) == 1:
rv = rv[0]
if ics and not 'power_series' in hint:
if isinstance(rv, (Expr, Eq)):
solved_constants = solve_ics([rv], [r['func']], cons(rv), ics)
rv = rv.subs(solved_constants)
else:
rv1 = []
for s in rv:
try:
solved_constants = solve_ics([s], [r['func']], cons(s), ics)
except ValueError:
continue
rv1.append(s.subs(solved_constants))
if len(rv1) == 1:
return rv1[0]
rv = rv1
return rv
def solve_ics(sols, funcs, constants, ics):
"""
Solve for the constants given initial conditions
``sols`` is a list of solutions.
``funcs`` is a list of functions.
``constants`` is a list of constants.
``ics`` is the set of initial/boundary conditions for the differential
equation. It should be given in the form of ``{f(x0): x1,
f(x).diff(x).subs(x, x2): x3}`` and so on.
Returns a dictionary mapping constants to values.
``solution.subs(constants)`` will replace the constants in ``solution``.
Example
=======
>>> # From dsolve(f(x).diff(x) - f(x), f(x))
>>> from sympy import symbols, Eq, exp, Function
>>> from sympy.solvers.ode.ode import solve_ics
>>> f = Function('f')
>>> x, C1 = symbols('x C1')
>>> sols = [Eq(f(x), C1*exp(x))]
>>> funcs = [f(x)]
>>> constants = [C1]
>>> ics = {f(0): 2}
>>> solved_constants = solve_ics(sols, funcs, constants, ics)
>>> solved_constants
{C1: 2}
>>> sols[0].subs(solved_constants)
Eq(f(x), 2*exp(x))
"""
# Assume ics are of the form f(x0): value or Subs(diff(f(x), x, n), (x,
# x0)): value (currently checked by classify_ode). To solve, replace x
# with x0, f(x0) with value, then solve for constants. For f^(n)(x0),
# differentiate the solution n times, so that f^(n)(x) appears.
x = funcs[0].args[0]
diff_sols = []
subs_sols = []
diff_variables = set()
for funcarg, value in ics.items():
if isinstance(funcarg, AppliedUndef):
x0 = funcarg.args[0]
matching_func = [f for f in funcs if f.func == funcarg.func][0]
S = sols
elif isinstance(funcarg, (Subs, Derivative)):
if isinstance(funcarg, Subs):
# Make sure it stays a subs. Otherwise subs below will produce
# a different looking term.
funcarg = funcarg.doit()
if isinstance(funcarg, Subs):
deriv = funcarg.expr
x0 = funcarg.point[0]
variables = funcarg.expr.variables
matching_func = deriv
elif isinstance(funcarg, Derivative):
deriv = funcarg
x0 = funcarg.variables[0]
variables = (x,)*len(funcarg.variables)
matching_func = deriv.subs(x0, x)
if variables not in diff_variables:
for sol in sols:
if sol.has(deriv.expr.func):
diff_sols.append(Eq(sol.lhs.diff(*variables), sol.rhs.diff(*variables)))
diff_variables.add(variables)
S = diff_sols
else:
raise NotImplementedError("Unrecognized initial condition")
for sol in S:
if sol.has(matching_func):
sol2 = sol
sol2 = sol2.subs(x, x0)
sol2 = sol2.subs(funcarg, value)
# This check is necessary because of issue #15724
if not isinstance(sol2, BooleanAtom) or not subs_sols:
subs_sols = [s for s in subs_sols if not isinstance(s, BooleanAtom)]
subs_sols.append(sol2)
# TODO: Use solveset here
try:
solved_constants = solve(subs_sols, constants, dict=True)
except NotImplementedError:
solved_constants = []
# XXX: We can't differentiate between the solution not existing because of
# invalid initial conditions, and not existing because solve is not smart
# enough. If we could use solveset, this might be improvable, but for now,
# we use NotImplementedError in this case.
if not solved_constants:
raise ValueError("Couldn't solve for initial conditions")
if solved_constants == True:
raise ValueError("Initial conditions did not produce any solutions for constants. Perhaps they are degenerate.")
if len(solved_constants) > 1:
raise NotImplementedError("Initial conditions produced too many solutions for constants")
return solved_constants[0]
def classify_ode(eq, func=None, dict=False, ics=None, *, prep=True, xi=None, eta=None, n=None, **kwargs):
r"""
Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve`
classifications for an ODE.
The tuple is ordered so that first item is the classification that
:py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In
general, classifications at the near the beginning of the list will
produce better solutions faster than those near the end, thought there are
always exceptions. To make :py:meth:`~sympy.solvers.ode.dsolve` use a
different classification, use ``dsolve(ODE, func,
hint=<classification>)``. See also the
:py:meth:`~sympy.solvers.ode.dsolve` docstring for different meta-hints
you can use.
If ``dict`` is true, :py:meth:`~sympy.solvers.ode.classify_ode` will
return a dictionary of ``hint:match`` expression terms. This is intended
for internal use by :py:meth:`~sympy.solvers.ode.dsolve`. Note that
because dictionaries are ordered arbitrarily, this will most likely not be
in the same order as the tuple.
You can get help on different hints by executing
``help(ode.ode_hintname)``, where ``hintname`` is the name of the hint
without ``_Integral``.
See :py:data:`~sympy.solvers.ode.allhints` or the
:py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints
that can be returned from :py:meth:`~sympy.solvers.ode.classify_ode`.
Notes
=====
These are remarks on hint names.
``_Integral``
If a classification has ``_Integral`` at the end, it will return the
expression with an unevaluated :py:class:`~.Integral`
class in it. Note that a hint may do this anyway if
:py:meth:`~sympy.core.expr.Expr.integrate` cannot do the integral,
though just using an ``_Integral`` will do so much faster. Indeed, an
``_Integral`` hint will always be faster than its corresponding hint
without ``_Integral`` because
:py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine.
If :py:meth:`~sympy.solvers.ode.dsolve` hangs, it is probably because
:py:meth:`~sympy.core.expr.Expr.integrate` is hanging on a tough or
impossible integral. Try using an ``_Integral`` hint or
``all_Integral`` to get it return something.
Note that some hints do not have ``_Integral`` counterparts. This is
because :py:func:`~sympy.integrals.integrals.integrate` is not used in
solving the ODE for those method. For example, `n`\th order linear
homogeneous ODEs with constant coefficients do not require integration
to solve, so there is no
``nth_linear_homogeneous_constant_coeff_Integrate`` hint. You can
easily evaluate any unevaluated
:py:class:`~sympy.integrals.integrals.Integral`\s in an expression by
doing ``expr.doit()``.
Ordinals
Some hints contain an ordinal such as ``1st_linear``. This is to help
differentiate them from other hints, as well as from other methods
that may not be implemented yet. If a hint has ``nth`` in it, such as
the ``nth_linear`` hints, this means that the method used to applies
to ODEs of any order.
``indep`` and ``dep``
Some hints contain the words ``indep`` or ``dep``. These reference
the independent variable and the dependent function, respectively. For
example, if an ODE is in terms of `f(x)`, then ``indep`` will refer to
`x` and ``dep`` will refer to `f`.
``subs``
If a hints has the word ``subs`` in it, it means the the ODE is solved
by substituting the expression given after the word ``subs`` for a
single dummy variable. This is usually in terms of ``indep`` and
``dep`` as above. The substituted expression will be written only in
characters allowed for names of Python objects, meaning operators will
be spelled out. For example, ``indep``/``dep`` will be written as
``indep_div_dep``.
``coeff``
The word ``coeff`` in a hint refers to the coefficients of something
in the ODE, usually of the derivative terms. See the docstring for
the individual methods for more info (``help(ode)``). This is
contrast to ``coefficients``, as in ``undetermined_coefficients``,
which refers to the common name of a method.
``_best``
Methods that have more than one fundamental way to solve will have a
hint for each sub-method and a ``_best`` meta-classification. This
will evaluate all hints and return the best, using the same
considerations as the normal ``best`` meta-hint.
Examples
========
>>> from sympy import Function, classify_ode, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> classify_ode(Eq(f(x).diff(x), 0), f(x))
('nth_algebraic',
'separable',
'1st_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)
('nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
"""
ics = sympify(ics)
if func and len(func.args) != 1:
raise ValueError("dsolve() and classify_ode() only "
"work with functions of one variable, not %s" % func)
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
# Some methods want the unprocessed equation
eq_orig = eq
if prep or func is None:
eq, func_ = _preprocess(eq, func)
if func is None:
func = func_
x = func.args[0]
f = func.func
y = Dummy('y')
terms = n
order = ode_order(eq, f(x))
# hint:matchdict or hint:(tuple of matchdicts)
# Also will contain "default":<default hint> and "order":order items.
matching_hints = {"order": order}
df = f(x).diff(x)
a = Wild('a', exclude=[f(x)])
d = Wild('d', exclude=[df, f(x).diff(x, 2)])
e = Wild('e', exclude=[df])
n = Wild('n', exclude=[x, f(x), df])
c1 = Wild('c1', exclude=[x])
a3 = Wild('a3', exclude=[f(x), df, f(x).diff(x, 2)])
b3 = Wild('b3', exclude=[f(x), df, f(x).diff(x, 2)])
c3 = Wild('c3', exclude=[f(x), df, f(x).diff(x, 2)])
r3 = {'xi': xi, 'eta': eta} # Used for the lie_group hint
boundary = {} # Used to extract initial conditions
C1 = Symbol("C1")
# Preprocessing to get the initial conditions out
if ics is not None:
for funcarg in ics:
# Separating derivatives
if isinstance(funcarg, (Subs, Derivative)):
# f(x).diff(x).subs(x, 0) is a Subs, but f(x).diff(x).subs(x,
# y) is a Derivative
if isinstance(funcarg, Subs):
deriv = funcarg.expr
old = funcarg.variables[0]
new = funcarg.point[0]
elif isinstance(funcarg, Derivative):
deriv = funcarg
# No information on this. Just assume it was x
old = x
new = funcarg.variables[0]
if (isinstance(deriv, Derivative) and isinstance(deriv.args[0],
AppliedUndef) and deriv.args[0].func == f and
len(deriv.args[0].args) == 1 and old == x and not
new.has(x) and all(i == deriv.variables[0] for i in
deriv.variables) and not ics[funcarg].has(f)):
dorder = ode_order(deriv, x)
temp = 'f' + str(dorder)
boundary.update({temp: new, temp + 'val': ics[funcarg]})
else:
raise ValueError("Enter valid boundary conditions for Derivatives")
# Separating functions
elif isinstance(funcarg, AppliedUndef):
if (funcarg.func == f and len(funcarg.args) == 1 and
not funcarg.args[0].has(x) and not ics[funcarg].has(f)):
boundary.update({'f0': funcarg.args[0], 'f0val': ics[funcarg]})
else:
raise ValueError("Enter valid boundary conditions for Function")
else:
raise ValueError("Enter boundary conditions of the form ics={f(point): value, f(x).diff(x, order).subs(x, point): value}")
# Any ODE that can be solved with a combination of algebra and
# integrals e.g.:
# d^3/dx^3(x y) = F(x)
ode = SingleODEProblem(eq_orig, func, x, prep=prep)
solvers = {
NthAlgebraic: ('nth_algebraic',),
FirstExact:('1st_exact',),
FirstLinear: ('1st_linear',),
AlmostLinear: ('almost_linear',),
Bernoulli: ('Bernoulli',),
Factorable: ('factorable',),
RiccatiSpecial: ('Riccati_special_minus2',),
SecondNonlinearAutonomousConserved: ('2nd_nonlinear_autonomous_conserved',),
Liouville: ('Liouville',),
Separable: ('separable',),
SeparableReduced: ('separable_reduced',),
}
for solvercls in solvers:
solver = solvercls(ode)
if solver.matches():
for hints in solvers[solvercls]:
matching_hints[hints] = solver
if solvercls.has_integral:
matching_hints[hints + "_Integral"] = solver
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
r3.update(r)
# Any first order ODE can be ideally solved by the Lie Group
# method
matching_hints["lie_group"] = r3
# This match is used for several cases below; we now collect on
# f(x) so the matching works.
r = collect(reduced_eq, df, exact=True).match(d + e*df)
if r:
# Using r[d] and r[e] without any modification for hints
# linear-coefficients and separable-reduced.
num, den = r[d], r[e] # ODE = d/e + df
r['d'] = d
r['e'] = e
r['y'] = y
r[d] = num.subs(f(x), y)
r[e] = den.subs(f(x), y)
## Separable Case: y' == P(y)*Q(x)
r[d] = separatevars(r[d])
r[e] = separatevars(r[e])
## First order equation with homogeneous coefficients:
# dy/dx == F(y/x) or dy/dx == F(x/y)
ordera = homogeneous_order(r[d], x, y)
if ordera is not None:
orderb = homogeneous_order(r[e], x, y)
if ordera == orderb:
# u1=y/x and u2=x/y
u1 = Dummy('u1')
u2 = Dummy('u2')
s = "1st_homogeneous_coeff_subs"
s1 = s + "_dep_div_indep"
s2 = s + "_indep_div_dep"
if simplify((r[d] + u1*r[e]).subs({x: 1, y: u1})) != 0:
matching_hints[s1] = r
matching_hints[s1 + "_Integral"] = r
if simplify((r[e] + u2*r[d]).subs({x: u2, y: 1})) != 0:
matching_hints[s2] = r
matching_hints[s2 + "_Integral"] = r
if s1 in matching_hints and s2 in matching_hints:
matching_hints["1st_homogeneous_coeff_best"] = r
## Linear coefficients of the form
# y'+ F((a*x + b*y + c)/(a'*x + b'y + c')) = 0
# that can be reduced to homogeneous form.
F = num/den
params = _linear_coeff_match(F, func)
if params:
xarg, yarg = params
u = Dummy('u')
t = Dummy('t')
# Dummy substitution for df and f(x).
dummy_eq = reduced_eq.subs(((df, t), (f(x), u)))
reps = ((x, x + xarg), (u, u + yarg), (t, df), (u, f(x)))
dummy_eq = simplify(dummy_eq.subs(reps))
# get the re-cast values for e and d
r2 = collect(expand(dummy_eq), [df, f(x)]).match(e*df + d)
if r2:
orderd = homogeneous_order(r2[d], x, f(x))
if orderd is not None:
ordere = homogeneous_order(r2[e], x, f(x))
if orderd == ordere:
# Match arguments are passed in such a way that it
# is coherent with the already existing homogeneous
# functions.
r2[d] = r2[d].subs(f(x), y)
r2[e] = r2[e].subs(f(x), y)
r2.update({'xarg': xarg, 'yarg': yarg,
'd': d, 'e': e, 'y': y})
matching_hints["linear_coefficients"] = r2
matching_hints["linear_coefficients_Integral"] = r2
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
# For Hypergeometric solutions.
_r = {}
_r.update(r)
rn = match_2nd_hypergeometric(_r, func)
if rn:
matching_hints["2nd_hypergeometric"] = rn
matching_hints["2nd_hypergeometric_Integral"] = rn
# If the ODE has regular singular point at x0 and is of the form
# Eq((x)**2*Derivative(y(x), x, x) + x*Derivative(y(x), x) +
# (a4**2*x**(2*p)-n**2)*y(x) thus Bessel's equation
rn = match_2nd_linear_bessel(r, f(x))
if rn:
matching_hints["2nd_linear_bessel"] = rn
# If the ODE is ordinary and is of the form of Airy's Equation
# Eq(x**2*Derivative(y(x),x,x)-(ax+b)*y(x))
if p.is_zero:
a4 = Wild('a4', exclude=[x,f(x),df])
b4 = Wild('b4', exclude=[x,f(x),df])
rn = q.match(a4+b4*x)
if rn and rn[b4] != 0:
rn = {'b':rn[a4],'m':rn[b4]}
matching_hints["2nd_linear_airy"] = rn
if order > 0:
# Any ODE that can be solved with a substitution and
# repeated integration e.g.:
# `d^2/dx^2(y) + x*d/dx(y) = constant
#f'(x) must be finite for this to work
r = _nth_order_reducible_match(reduced_eq, func)
if r:
matching_hints['nth_order_reducible'] = r
# nth order linear ODE
# a_n(x)y^(n) + ... + a_1(x)y' + a_0(x)y = F(x) = b
r = _nth_linear_match(reduced_eq, func, order)
# Constant coefficient case (a_i is constant for all i)
if r and not any(r[i].has(x) for i in r if i >= 0):
# Inhomogeneous case: F(x) is not identically 0
if r[-1]:
eq_homogeneous = Add(eq,-r[-1])
undetcoeff = _undetermined_coefficients_match(r[-1], x, func, eq_homogeneous)
s = "nth_linear_constant_coeff_variation_of_parameters"
matching_hints[s] = r
matching_hints[s + "_Integral"] = r
if undetcoeff['test']:
r['trialset'] = undetcoeff['trialset']
matching_hints[
"nth_linear_constant_coeff_undetermined_coefficients"
] = r
# Homogeneous case: F(x) is identically 0
else:
matching_hints["nth_linear_constant_coeff_homogeneous"] = r
# nth order Euler equation a_n*x**n*y^(n) + ... + a_1*x*y' + a_0*y = F(x)
#In case of Homogeneous euler equation F(x) = 0
def _test_term(coeff, order):
r"""
Linear Euler ODEs have the form K*x**order*diff(y(x),x,order) = F(x),
where K is independent of x and y(x), order>= 0.
So we need to check that for each term, coeff == K*x**order from
some K. We have a few cases, since coeff may have several
different types.
"""
if order < 0:
raise ValueError("order should be greater than 0")
if coeff == 0:
return True
if order == 0:
if x in coeff.free_symbols:
return False
return True
if coeff.is_Mul:
if coeff.has(f(x)):
return False
return x**order in coeff.args
elif coeff.is_Pow:
return coeff.as_base_exp() == (x, order)
elif order == 1:
return x == coeff
return False
# Find coefficient for highest derivative, multiply coefficients to
# bring the equation into Euler form if possible
r_rescaled = None
if r is not None:
coeff = r[order]
factor = x**order / coeff
r_rescaled = {i: factor*r[i] for i in r if i != 'trialset'}
# XXX: Mixing up the trialset with the coefficients is error-prone.
# These should be separated as something like r['coeffs'] and
# r['trialset']
if r_rescaled and not any(not _test_term(r_rescaled[i], i) for i in
r_rescaled if i != 'trialset' and i >= 0):
if not r_rescaled[-1]:
matching_hints["nth_linear_euler_eq_homogeneous"] = r_rescaled
else:
matching_hints["nth_linear_euler_eq_nonhomogeneous_variation_of_parameters"] = r_rescaled
matching_hints["nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral"] = r_rescaled
e, re = posify(r_rescaled[-1].subs(x, exp(x)))
undetcoeff = _undetermined_coefficients_match(e.subs(re), x)
if undetcoeff['test']:
r_rescaled['trialset'] = undetcoeff['trialset']
matching_hints["nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients"] = r_rescaled
# Order keys based on allhints.
retlist = [i for i in allhints if i in matching_hints]
if dict:
# Dictionaries are ordered arbitrarily, so make note of which
# hint would come first for dsolve(). Use an ordered dict in Py 3.
matching_hints["default"] = retlist[0] if retlist else None
matching_hints["ordered_hints"] = tuple(retlist)
return matching_hints
else:
return tuple(retlist)
def equivalence(max_num_pow, dem_pow):
# this function is made for checking the equivalence with 2F1 type of equation.
# max_num_pow is the value of maximum power of x in numerator
# and dem_pow is list of powers of different factor of form (a*x b).
# reference from table 1 in paper - "Non-Liouvillian solutions for second order
# linear ODEs" by L. Chan, E.S. Cheb-Terrab.
# We can extend it for 1F1 and 0F1 type also.
if max_num_pow == 2:
if dem_pow in [[2, 2], [2, 2, 2]]:
return "2F1"
elif max_num_pow == 1:
if dem_pow in [[1, 2, 2], [2, 2, 2], [1, 2], [2, 2]]:
return "2F1"
elif max_num_pow == 0:
if dem_pow in [[1, 1, 2], [2, 2], [1 ,2, 2], [1, 1], [2], [1, 2], [2, 2]]:
return "2F1"
return None
def equivalence_hypergeometric(A, B, func):
from sympy import factor
# This method for finding the equivalence is only for 2F1 type.
# We can extend it for 1F1 and 0F1 type also.
x = func.args[0]
# making given equation in normal form
I1 = factor(cancel(A.diff(x)/2 + A**2/4 - B))
# computing shifted invariant(J1) of the equation
J1 = factor(cancel(x**2*I1 + S(1)/4))
num, dem = J1.as_numer_denom()
num = powdenest(expand(num))
dem = powdenest(expand(dem))
pow_num = set()
pow_dem = set()
# this function will compute the different powers of variable(x) in J1.
# then it will help in finding value of k. k is power of x such that we can express
# J1 = x**k * J0(x**k) then all the powers in J0 become integers.
def _power_counting(num):
_pow = {0}
for val in num:
if val.has(x):
if isinstance(val, Pow) and val.as_base_exp()[0] == x:
_pow.add(val.as_base_exp()[1])
elif val == x:
_pow.add(val.as_base_exp()[1])
else:
_pow.update(_power_counting(val.args))
return _pow
pow_num = _power_counting((num, ))
pow_dem = _power_counting((dem, ))
pow_dem.update(pow_num)
_pow = pow_dem
k = gcd(_pow)
# computing I0 of the given equation
I0 = powdenest(simplify(factor(((J1/k**2) - S(1)/4)/((x**k)**2))), force=True)
I0 = factor(cancel(powdenest(I0.subs(x, x**(S(1)/k)), force=True)))
num, dem = I0.as_numer_denom()
max_num_pow = max(_power_counting((num, )))
dem_args = dem.args
sing_point = []
dem_pow = []
# calculating singular point of I0.
for arg in dem_args:
if arg.has(x):
if isinstance(arg, Pow):
# (x-a)**n
dem_pow.append(arg.as_base_exp()[1])
sing_point.append(list(roots(arg.as_base_exp()[0], x).keys())[0])
else:
# (x-a) type
dem_pow.append(arg.as_base_exp()[1])
sing_point.append(list(roots(arg, x).keys())[0])
dem_pow.sort()
# checking if equivalence is exists or not.
if equivalence(max_num_pow, dem_pow) == "2F1":
return {'I0':I0, 'k':k, 'sing_point':sing_point, 'type':"2F1"}
else:
return None
def ode_2nd_hypergeometric(eq, func, order, match):
from sympy.simplify.hyperexpand import hyperexpand
from sympy import factor
x = func.args[0]
C0, C1 = get_numbered_constants(eq, num=2)
a = match['a']
b = match['b']
c = match['c']
A = match['A']
# B = match['B']
sol = None
if match['type'] == "2F1":
if c.is_integer == False:
sol = C0*hyper([a, b], [c], x) + C1*hyper([a-c+1, b-c+1], [2-c], x)*x**(1-c)
elif c == 1:
y2 = Integral(exp(Integral((-(a+b+1)*x + c)/(x**2-x), x))/(hyperexpand(hyper([a, b], [c], x))**2), x)*hyper([a, b], [c], x)
sol = C0*hyper([a, b], [c], x) + C1*y2
elif (c-a-b).is_integer == False:
sol = C0*hyper([a, b], [1+a+b-c], 1-x) + C1*hyper([c-a, c-b], [1+c-a-b], 1-x)*(1-x)**(c-a-b)
if sol is None:
raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by"
+ " the hypergeometric method")
# applying transformation in the solution
subs = match['mobius']
dtdx = simplify(1/(subs.diff(x)))
_B = ((a + b + 1)*x - c).subs(x, subs)*dtdx
_B = factor(_B + ((x**2 -x).subs(x, subs))*(dtdx.diff(x)*dtdx))
_A = factor((x**2 - x).subs(x, subs)*(dtdx**2))
e = exp(logcombine(Integral(cancel(_B/(2*_A)), x), force=True))
sol = sol.subs(x, match['mobius'])
sol = sol.subs(x, x**match['k'])
e = e.subs(x, x**match['k'])
if not A.is_zero:
e1 = Integral(A/2, x)
e1 = exp(logcombine(e1, force=True))
sol = cancel((e/e1)*x**((-match['k']+1)/2))*sol
sol = Eq(func, sol)
return sol
sol = cancel((e)*x**((-match['k']+1)/2))*sol
sol = Eq(func, sol)
return sol
def match_2nd_2F1_hypergeometric(I, k, sing_point, func):
from sympy import factor
x = func.args[0]
a = Wild("a")
b = Wild("b")
c = Wild("c")
t = Wild("t")
s = Wild("s")
r = Wild("r")
alpha = Wild("alpha")
beta = Wild("beta")
gamma = Wild("gamma")
delta = Wild("delta")
rn = {'type':None}
# I0 of the standerd 2F1 equation.
I0 = ((a-b+1)*(a-b-1)*x**2 + 2*((1-a-b)*c + 2*a*b)*x + c*(c-2))/(4*x**2*(x-1)**2)
if sing_point != [0, 1]:
# If singular point is [0, 1] then we have standerd equation.
eqs = []
sing_eqs = [-beta/alpha, -delta/gamma, (delta-beta)/(alpha-gamma)]
# making equations for the finding the mobius transformation
for i in range(3):
if i<len(sing_point):
eqs.append(Eq(sing_eqs[i], sing_point[i]))
else:
eqs.append(Eq(1/sing_eqs[i], 0))
# solving above equations for the mobius transformation
_beta = -alpha*sing_point[0]
_delta = -gamma*sing_point[1]
_gamma = alpha
if len(sing_point) == 3:
_gamma = (_beta + sing_point[2]*alpha)/(sing_point[2] - sing_point[1])
mob = (alpha*x + beta)/(gamma*x + delta)
mob = mob.subs(beta, _beta)
mob = mob.subs(delta, _delta)
mob = mob.subs(gamma, _gamma)
mob = cancel(mob)
t = (beta - delta*x)/(gamma*x - alpha)
t = cancel(((t.subs(beta, _beta)).subs(delta, _delta)).subs(gamma, _gamma))
else:
mob = x
t = x
# applying mobius transformation in I to make it into I0.
I = I.subs(x, t)
I = I*(t.diff(x))**2
I = factor(I)
dict_I = {x**2:0, x:0, 1:0}
I0_num, I0_dem = I0.as_numer_denom()
# collecting coeff of (x**2, x), of the standerd equation.
# substituting (a-b) = s, (a+b) = r
dict_I0 = {x**2:s**2 - 1, x:(2*(1-r)*c + (r+s)*(r-s)), 1:c*(c-2)}
# collecting coeff of (x**2, x) from I0 of the given equation.
dict_I.update(collect(expand(cancel(I*I0_dem)), [x**2, x], evaluate=False))
eqs = []
# We are comparing the coeff of powers of different x, for finding the values of
# parameters of standerd equation.
for key in [x**2, x, 1]:
eqs.append(Eq(dict_I[key], dict_I0[key]))
# We can have many possible roots for the equation.
# I am selecting the root on the basis that when we have
# standard equation eq = x*(x-1)*f(x).diff(x, 2) + ((a+b+1)*x-c)*f(x).diff(x) + a*b*f(x)
# then root should be a, b, c.
_c = 1 - factor(sqrt(1+eqs[2].lhs))
if not _c.has(Symbol):
_c = min(list(roots(eqs[2], c)))
_s = factor(sqrt(eqs[0].lhs + 1))
_r = _c - factor(sqrt(_c**2 + _s**2 + eqs[1].lhs - 2*_c))
_a = (_r + _s)/2
_b = (_r - _s)/2
rn = {'a':simplify(_a), 'b':simplify(_b), 'c':simplify(_c), 'k':k, 'mobius':mob, 'type':"2F1"}
return rn
def match_2nd_hypergeometric(r, func):
x = func.args[0]
a3 = Wild('a3', exclude=[func, func.diff(x), func.diff(x, 2)])
b3 = Wild('b3', exclude=[func, func.diff(x), func.diff(x, 2)])
c3 = Wild('c3', exclude=[func, func.diff(x), func.diff(x, 2)])
A = cancel(r[b3]/r[a3])
B = cancel(r[c3]/r[a3])
d = equivalence_hypergeometric(A, B, func)
rn = None
if d:
if d['type'] == "2F1":
rn = match_2nd_2F1_hypergeometric(d['I0'], d['k'], d['sing_point'], func)
if rn is not None:
rn.update({'A':A, 'B':B})
# We can extend it for 1F1 and 0F1 type also.
return rn
def match_2nd_linear_bessel(r, func):
from sympy.polys.polytools import factor
# eq = a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3*f(x)
f = func
x = func.args[0]
df = f.diff(x)
a = Wild('a', exclude=[f,df])
b = Wild('b', exclude=[x, f,df])
a4 = Wild('a4', exclude=[x,f,df])
b4 = Wild('b4', exclude=[x,f,df])
c4 = Wild('c4', exclude=[x,f,df])
d4 = Wild('d4', exclude=[x,f,df])
a3 = Wild('a3', exclude=[f, df, f.diff(x, 2)])
b3 = Wild('b3', exclude=[f, df, f.diff(x, 2)])
c3 = Wild('c3', exclude=[f, df, f.diff(x, 2)])
# leading coeff of f(x).diff(x, 2)
coeff = factor(r[a3]).match(a4*(x-b)**b4)
if coeff:
# if coeff[b4] = 0 means constant coefficient
if coeff[b4] == 0:
return None
point = coeff[b]
else:
return None
if point:
r[a3] = simplify(r[a3].subs(x, x+point))
r[b3] = simplify(r[b3].subs(x, x+point))
r[c3] = simplify(r[c3].subs(x, x+point))
# making a3 in the form of x**2
r[a3] = cancel(r[a3]/(coeff[a4]*(x)**(-2+coeff[b4])))
r[b3] = cancel(r[b3]/(coeff[a4]*(x)**(-2+coeff[b4])))
r[c3] = cancel(r[c3]/(coeff[a4]*(x)**(-2+coeff[b4])))
# checking if b3 is of form c*(x-b)
coeff1 = factor(r[b3]).match(a4*(x))
if coeff1 is None:
return None
# c3 maybe of very complex form so I am simply checking (a - b) form
# if yes later I will match with the standerd form of bessel in a and b
# a, b are wild variable defined above.
_coeff2 = r[c3].match(a - b)
if _coeff2 is None:
return None
# matching with standerd form for c3
coeff2 = factor(_coeff2[a]).match(c4**2*(x)**(2*a4))
if coeff2 is None:
return None
if _coeff2[b] == 0:
coeff2[d4] = 0
else:
coeff2[d4] = factor(_coeff2[b]).match(d4**2)[d4]
rn = {'n':coeff2[d4], 'a4':coeff2[c4], 'd4':coeff2[a4]}
rn['c4'] = coeff1[a4]
rn['b4'] = point
return rn
def classify_sysode(eq, funcs=None, **kwargs):
r"""
Returns a dictionary of parameter names and values that define the system
of ordinary differential equations in ``eq``.
The parameters are further used in
:py:meth:`~sympy.solvers.ode.dsolve` for solving that system.
Some parameter names and values are:
'is_linear' (boolean), which tells whether the given system is linear.
Note that "linear" here refers to the operator: terms such as ``x*diff(x,t)`` are
nonlinear, whereas terms like ``sin(t)*diff(x,t)`` are still linear operators.
'func' (list) contains the :py:class:`~sympy.core.function.Function`s that
appear with a derivative in the ODE, i.e. those that we are trying to solve
the ODE for.
'order' (dict) with the maximum derivative for each element of the 'func'
parameter.
'func_coeff' (dict or Matrix) with the coefficient for each triple ``(equation number,
function, order)```. The coefficients are those subexpressions that do not
appear in 'func', and hence can be considered constant for purposes of ODE
solving. The value of this parameter can also be a Matrix if the system of ODEs are
linear first order of the form X' = AX where X is the vector of dependent variables.
Here, this function returns the coefficient matrix A.
'eq' (list) with the equations from ``eq``, sympified and transformed into
expressions (we are solving for these expressions to be zero).
'no_of_equations' (int) is the number of equations (same as ``len(eq)``).
'type_of_equation' (string) is an internal classification of the type of
ODE.
'is_constant' (boolean), which tells if the system of ODEs is constant coefficient
or not. This key is temporary addition for now and is in the match dict only when
the system of ODEs is linear first order constant coefficient homogeneous. So, this
key's value is True for now if it is available else it doesn't exist.
'is_homogeneous' (boolean), which tells if the system of ODEs is homogeneous. Like the
key 'is_constant', this key is a temporary addition and it is True since this key value
is available only when the system is linear first order constant coefficient homogeneous.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode-toc1.htm
-A. D. Polyanin and A. V. Manzhirov, Handbook of Mathematics for Engineers and Scientists
Examples
========
>>> from sympy import Function, Eq, symbols, diff
>>> from sympy.solvers.ode.ode import classify_sysode
>>> from sympy.abc import t
>>> f, x, y = symbols('f, x, y', cls=Function)
>>> k, l, m, n = symbols('k, l, m, n', Integer=True)
>>> x1 = diff(x(t), t) ; y1 = diff(y(t), t)
>>> x2 = diff(x(t), t, t) ; y2 = diff(y(t), t, t)
>>> eq = (Eq(x1, 12*x(t) - 6*y(t)), Eq(y1, 11*x(t) + 3*y(t)))
>>> classify_sysode(eq)
{'eq': [-12*x(t) + 6*y(t) + Derivative(x(t), t), -11*x(t) - 3*y(t) + Derivative(y(t), t)], 'func': [x(t), y(t)],
'func_coeff': {(0, x(t), 0): -12, (0, x(t), 1): 1, (0, y(t), 0): 6, (0, y(t), 1): 0, (1, x(t), 0): -11, (1, x(t), 1): 0, (1, y(t), 0): -3, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': None}
>>> eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t) + 2), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t)))
>>> classify_sysode(eq)
{'eq': [-t**2*y(t) - 5*t*x(t) + Derivative(x(t), t) - 2, t**2*x(t) - 5*t*y(t) + Derivative(y(t), t)],
'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -5*t, (0, x(t), 1): 1, (0, y(t), 0): -t**2, (0, y(t), 1): 0,
(1, x(t), 0): t**2, (1, x(t), 1): 0, (1, y(t), 0): -5*t, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2,
'order': {x(t): 1, y(t): 1}, 'type_of_equation': None}
"""
# Sympify equations and convert iterables of equations into
# a list of equations
def _sympify(eq):
return list(map(sympify, eq if iterable(eq) else [eq]))
eq, funcs = (_sympify(w) for w in [eq, funcs])
for i, fi in enumerate(eq):
if isinstance(fi, Equality):
eq[i] = fi.lhs - fi.rhs
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
matching_hints = {"no_of_equation":i+1}
matching_hints['eq'] = eq
if i==0:
raise ValueError("classify_sysode() works for systems of ODEs. "
"For scalar ODEs, classify_ode should be used")
# find all the functions if not given
order = dict()
if funcs==[None]:
funcs = _extract_funcs(eq)
funcs = list(set(funcs))
if len(funcs) != len(eq):
raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs)
# This logic of list of lists in funcs to
# be replaced later.
func_dict = dict()
for func in funcs:
if not order.get(func, False):
max_order = 0
for i, eqs_ in enumerate(eq):
order_ = ode_order(eqs_,func)
if max_order < order_:
max_order = order_
eq_no = i
if eq_no in func_dict:
func_dict[eq_no] = [func_dict[eq_no], func]
else:
func_dict[eq_no] = func
order[func] = max_order
funcs = [func_dict[i] for i in range(len(func_dict))]
matching_hints['func'] = funcs
for func in funcs:
if isinstance(func, list):
for func_elem in func:
if len(func_elem.args) != 1:
raise ValueError("dsolve() and classify_sysode() work with "
"functions of one variable only, not %s" % func)
else:
if func and len(func.args) != 1:
raise ValueError("dsolve() and classify_sysode() work with "
"functions of one variable only, not %s" % func)
# find the order of all equation in system of odes
matching_hints["order"] = order
# find coefficients of terms f(t), diff(f(t),t) and higher derivatives
# and similarly for other functions g(t), diff(g(t),t) in all equations.
# Here j denotes the equation number, funcs[l] denotes the function about
# which we are talking about and k denotes the order of function funcs[l]
# whose coefficient we are calculating.
def linearity_check(eqs, j, func, is_linear_):
for k in range(order[func] + 1):
func_coef[j, func, k] = collect(eqs.expand(), [diff(func, t, k)]).coeff(diff(func, t, k))
if is_linear_ == True:
if func_coef[j, func, k] == 0:
if k == 0:
coef = eqs.as_independent(func, as_Add=True)[1]
for xr in range(1, ode_order(eqs,func) + 1):
coef -= eqs.as_independent(diff(func, t, xr), as_Add=True)[1]
if coef != 0:
is_linear_ = False
else:
if eqs.as_independent(diff(func, t, k), as_Add=True)[1]:
is_linear_ = False
else:
for func_ in funcs:
if isinstance(func_, list):
for elem_func_ in func_:
dep = func_coef[j, func, k].as_independent(elem_func_, as_Add=True)[1]
if dep != 0:
is_linear_ = False
else:
dep = func_coef[j, func, k].as_independent(func_, as_Add=True)[1]
if dep != 0:
is_linear_ = False
return is_linear_
func_coef = {}
is_linear = True
for j, eqs in enumerate(eq):
for func in funcs:
if isinstance(func, list):
for func_elem in func:
is_linear = linearity_check(eqs, j, func_elem, is_linear)
else:
is_linear = linearity_check(eqs, j, func, is_linear)
matching_hints['func_coeff'] = func_coef
matching_hints['is_linear'] = is_linear
if len(set(order.values())) == 1:
order_eq = list(matching_hints['order'].values())[0]
if matching_hints['is_linear'] == True:
if matching_hints['no_of_equation'] == 2:
if order_eq == 1:
type_of_equation = check_linear_2eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
# If the equation doesn't match up with any of the
# general case solvers in systems.py and the number
# of equations is greater than 2, then NotImplementedError
# should be raised.
else:
type_of_equation = None
else:
if matching_hints['no_of_equation'] == 2:
if order_eq == 1:
type_of_equation = check_nonlinear_2eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
elif matching_hints['no_of_equation'] == 3:
if order_eq == 1:
type_of_equation = check_nonlinear_3eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
else:
type_of_equation = None
else:
type_of_equation = None
matching_hints['type_of_equation'] = type_of_equation
return matching_hints
def check_linear_2eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = dict()
# for equations Eq(a1*diff(x(t),t), b1*x(t) + c1*y(t) + d1)
# and Eq(a2*diff(y(t),t), b2*x(t) + c2*y(t) + d2)
r['a1'] = fc[0,x(t),1] ; r['a2'] = fc[1,y(t),1]
r['b1'] = -fc[0,x(t),0]/fc[0,x(t),1] ; r['b2'] = -fc[1,x(t),0]/fc[1,y(t),1]
r['c1'] = -fc[0,y(t),0]/fc[0,x(t),1] ; r['c2'] = -fc[1,y(t),0]/fc[1,y(t),1]
forcing = [S.Zero,S.Zero]
for i in range(2):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t)):
forcing[i] += j
if not (forcing[0].has(t) or forcing[1].has(t)):
# We can handle homogeneous case and simple constant forcings
r['d1'] = forcing[0]
r['d2'] = forcing[1]
else:
# Issue #9244: nonhomogeneous linear systems are not supported
return None
# Conditions to check for type 6 whose equations are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and
# Eq(diff(y(t),t), a*[f(t) + a*h(t)]x(t) + a*[g(t) - h(t)]*y(t))
p = 0
q = 0
p1 = cancel(r['b2']/(cancel(r['b2']/r['c2']).as_numer_denom()[0]))
p2 = cancel(r['b1']/(cancel(r['b1']/r['c1']).as_numer_denom()[0]))
for n, i in enumerate([p1, p2]):
for j in Mul.make_args(collect_const(i)):
if not j.has(t):
q = j
if q and n==0:
if ((r['b2']/j - r['b1'])/(r['c1'] - r['c2']/j)) == j:
p = 1
elif q and n==1:
if ((r['b1']/j - r['b2'])/(r['c2'] - r['c1']/j)) == j:
p = 2
# End of condition for type 6
if r['d1']!=0 or r['d2']!=0:
return None
else:
if all(not 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 \
| -|u2 + -------|
| | /1 \|
| | sin|--||
| \ \u2//
log(f(x)) = log(C1) + | ---------------- d(u2)
| 2
| u2
|
/
>>> pprint(odesimp(eq, f(x), 1, {C1},
... hint='1st_homogeneous_coeff_subs_indep_div_dep'
... )) #doctest: +SKIP
x
--------- = C1
/f(x)\
tan|----|
\2*x /
"""
x = func.args[0]
f = func.func
C1 = get_numbered_constants(eq, num=1)
constants = eq.free_symbols - ode.free_symbols
# First, integrate if the hint allows it.
eq = _handle_Integral(eq, func, hint)
if hint.startswith("nth_linear_euler_eq_nonhomogeneous"):
eq = simplify(eq)
if not isinstance(eq, Equality):
raise TypeError("eq should be an instance of Equality")
# Second, clean up the arbitrary constants.
# Right now, nth linear hints can put as many as 2*order constants in an
# expression. If that number grows with another hint, the third argument
# here should be raised accordingly, or constantsimp() rewritten to handle
# an arbitrary number of constants.
eq = constantsimp(eq, constants)
# Lastly, now that we have cleaned up the expression, try solving for func.
# When CRootOf is implemented in solve(), we will want to return a CRootOf
# every time instead of an Equality.
# Get the f(x) on the left if possible.
if eq.rhs == func and not eq.lhs.has(func):
eq = [Eq(eq.rhs, eq.lhs)]
# make sure we are working with lists of solutions in simplified form.
if eq.lhs == func and not eq.rhs.has(func):
# The solution is already solved
eq = [eq]
# special simplification of the rhs
if hint.startswith("nth_linear_constant_coeff"):
# Collect terms to make the solution look nice.
# This is also necessary for constantsimp to remove unnecessary
# terms from the particular solution from variation of parameters
#
# Collect is not behaving reliably here. The results for
# some linear constant-coefficient equations with repeated
# roots do not properly simplify all constants sometimes.
# 'collectterms' gives different orders sometimes, and results
# differ in collect based on that order. The
# sort-reverse trick fixes things, but may fail in the
# future. In addition, collect is splitting exponentials with
# rational powers for no reason. We have to do a match
# to fix this using Wilds.
#
# XXX: This global collectterms hack should be removed.
global collectterms
collectterms.sort(key=default_sort_key)
collectterms.reverse()
assert len(eq) == 1 and eq[0].lhs == f(x)
sol = eq[0].rhs
sol = expand_mul(sol)
for i, reroot, imroot in collectterms:
sol = collect(sol, x**i*exp(reroot*x)*sin(abs(imroot)*x))
sol = collect(sol, x**i*exp(reroot*x)*cos(imroot*x))
for i, reroot, imroot in collectterms:
sol = collect(sol, x**i*exp(reroot*x))
del collectterms
# Collect is splitting exponentials with rational powers for
# no reason. We call powsimp to fix.
sol = powsimp(sol)
eq[0] = Eq(f(x), sol)
else:
# The solution is not solved, so try to solve it
try:
floats = any(i.is_Float for i in eq.atoms(Number))
eqsol = solve(eq, func, force=True, rational=False if floats else None)
if not eqsol:
raise NotImplementedError
except (NotImplementedError, PolynomialError):
eq = [eq]
else:
def _expand(expr):
numer, denom = expr.as_numer_denom()
if denom.is_Add:
return expr
else:
return powsimp(expr.expand(), combine='exp', deep=True)
# XXX: the rest of odesimp() expects each ``t`` to be in a
# specific normal form: rational expression with numerator
# expanded, but with combined exponential functions (at
# least in this setup all tests pass).
eq = [Eq(f(x), _expand(t)) for t in eqsol]
# special simplification of the lhs.
if hint.startswith("1st_homogeneous_coeff"):
for j, eqi in enumerate(eq):
newi = logcombine(eqi, force=True)
if isinstance(newi.lhs, log) and newi.rhs == 0:
newi = Eq(newi.lhs.args[0]/C1, C1)
eq[j] = newi
# We cleaned up the constants before solving to help the solve engine with
# a simpler expression, but the solved expression could have introduced
# things like -C1, so rerun constantsimp() one last time before returning.
for i, eqi in enumerate(eq):
eq[i] = constantsimp(eqi, constants)
eq[i] = constant_renumber(eq[i], ode.free_symbols)
# If there is only 1 solution, return it;
# otherwise return the list of solutions.
if len(eq) == 1:
eq = eq[0]
return eq
def ode_sol_simplicity(sol, func, trysolving=True):
r"""
Returns an extended integer representing how simple a solution to an ODE
is.
The following things are considered, in order from most simple to least:
- ``sol`` is solved for ``func``.
- ``sol`` is not solved for ``func``, but can be if passed to solve (e.g.,
a solution returned by ``dsolve(ode, func, simplify=False``).
- If ``sol`` is not solved for ``func``, then base the result on the
length of ``sol``, as computed by ``len(str(sol))``.
- If ``sol`` has any unevaluated :py:class:`~sympy.integrals.integrals.Integral`\s,
this will automatically be considered less simple than any of the above.
This function returns an integer such that if solution A is simpler than
solution B by above metric, then ``ode_sol_simplicity(sola, func) <
ode_sol_simplicity(solb, func)``.
Currently, the following are the numbers returned, but if the heuristic is
ever improved, this may change. Only the ordering is guaranteed.
+----------------------------------------------+-------------------+
| Simplicity | Return |
+==============================================+===================+
| ``sol`` solved for ``func`` | ``-2`` |
+----------------------------------------------+-------------------+
| ``sol`` not solved for ``func`` but can be | ``-1`` |
+----------------------------------------------+-------------------+
| ``sol`` is not solved nor solvable for | ``len(str(sol))`` |
| ``func`` | |
+----------------------------------------------+-------------------+
| ``sol`` contains an | ``oo`` |
| :obj:`~sympy.integrals.integrals.Integral` | |
+----------------------------------------------+-------------------+
``oo`` here means the SymPy infinity, which should compare greater than
any integer.
If you already know :py:meth:`~sympy.solvers.solvers.solve` cannot solve
``sol``, you can use ``trysolving=False`` to skip that step, which is the
only potentially slow step. For example,
:py:meth:`~sympy.solvers.ode.dsolve` with the ``simplify=False`` flag
should do this.
If ``sol`` is a list of solutions, if the worst solution in the list
returns ``oo`` it returns that, otherwise it returns ``len(str(sol))``,
that is, the length of the string representation of the whole list.
Examples
========
This function is designed to be passed to ``min`` as the key argument,
such as ``min(listofsolutions, key=lambda i: ode_sol_simplicity(i,
f(x)))``.
>>> from sympy import symbols, Function, Eq, tan, 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):
from sympy.core.basic import preorder_traversal
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
def ode_1st_homogeneous_coeff_best(eq, func, order, match):
r"""
Returns the best solution to an ODE from the two hints
``1st_homogeneous_coeff_subs_dep_div_indep`` and
``1st_homogeneous_coeff_subs_indep_div_dep``.
This is as determined by :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity`.
See the
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`
and
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`
docstrings for more information on these hints. Note that there is no
``ode_1st_homogeneous_coeff_best_Integral`` hint.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_best', simplify=False))
/ 2 \
| 3*x |
log|----- + 1|
| 2 |
\f (x) /
log(f(x)) = log(C1) - --------------
3
References
==========
- https://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
# There are two substitutions that solve the equation, u1=y/x and u2=x/y
# They produce different integrals, so try them both and see which
# one is easier.
sol1 = ode_1st_homogeneous_coeff_subs_indep_div_dep(eq,
func, order, match)
sol2 = ode_1st_homogeneous_coeff_subs_dep_div_indep(eq,
func, order, match)
simplify = match.get('simplify', True)
if simplify:
# why is odesimp called here? Should it be at the usual spot?
sol1 = odesimp(eq, sol1, func, "1st_homogeneous_coeff_subs_indep_div_dep")
sol2 = odesimp(eq, sol2, func, "1st_homogeneous_coeff_subs_dep_div_indep")
return min([sol1, sol2], key=lambda x: ode_sol_simplicity(x, func,
trysolving=not simplify))
def ode_1st_homogeneous_coeff_subs_dep_div_indep(eq, func, order, match):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_1 = \frac{\text{<dependent
variable>}}{\text{<independent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that `P` and `Q` are homogeneous and of the same order. A function
`F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`.
Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See
also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`.
If the coefficients `P` and `Q` in the differential equation above are
homogeneous functions of the same order, then it can be shown that the
substitution `y = u_1 x` (i.e. `u_1 = y/x`) will turn the differential
equation into an equation separable in the variables `x` and `u`. If
`h(u_1)` is the function that results from making the substitution `u_1 =
f(x)/x` on `P(x, f(x))` and `g(u_2)` is the function that results from the
substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) +
Q(x, f(x)) f'(x) = 0`, then the general solution is::
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = g(f(x)/x) + h(f(x)/x)*f(x).diff(x)
>>> pprint(genform)
/f(x)\ /f(x)\ d
g|----| + h|----|*--(f(x))
\ x / \ x / dx
>>> pprint(dsolve(genform, f(x),
... hint='1st_homogeneous_coeff_subs_dep_div_indep_Integral'))
f(x)
----
x
/
|
| -h(u1)
log(x) = C1 + | ---------------- d(u1)
| u1*h(u1) + g(u1)
|
/
Where `u_1 h(u_1) + g(u_1) \ne 0` and `x \ne 0`.
See also the docstrings of
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best` and
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`.
Examples
========
>>> from sympy import Function, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False))
/ 3 \
|3*f(x) f (x)|
log|------ + -----|
| x 3 |
\ x /
log(x) = log(C1) - -------------------
3
References
==========
- https://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
x = func.args[0]
f = func.func
u = Dummy('u')
u1 = Dummy('u1') # u1 == f(x)/x
r = match # d+e*diff(f(x),x)
C1 = get_numbered_constants(eq, num=1)
xarg = match.get('xarg', 0)
yarg = match.get('yarg', 0)
int = Integral(
(-r[r['e']]/(r[r['d']] + u1*r[r['e']])).subs({x: 1, r['y']: u1}),
(u1, None, f(x)/x))
sol = logcombine(Eq(log(x), int + log(C1)), force=True)
sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x))))
return sol
def ode_1st_homogeneous_coeff_subs_indep_div_dep(eq, func, order, match):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_2 = \frac{\text{<independent
variable>}}{\text{<dependent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that `P` and `Q` are homogeneous and of the same order. A function
`F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`.
Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See
also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`.
If the coefficients `P` and `Q` in the differential equation above are
homogeneous functions of the same order, then it can be shown that the
substitution `x = u_2 y` (i.e. `u_2 = x/y`) will turn the differential
equation into an equation separable in the variables `y` and `u_2`. If
`h(u_2)` is the function that results from making the substitution `u_2 =
x/f(x)` on `P(x, f(x))` and `g(u_2)` is the function that results from the
substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) +
Q(x, f(x)) f'(x) = 0`, then the general solution is:
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = g(x/f(x)) + h(x/f(x))*f(x).diff(x)
>>> pprint(genform)
/ x \ / x \ d
g|----| + h|----|*--(f(x))
\f(x)/ \f(x)/ dx
>>> pprint(dsolve(genform, f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral'))
x
----
f(x)
/
|
| -g(u2)
| ---------------- d(u2)
| u2*g(u2) + h(u2)
|
/
<BLANKLINE>
f(x) = C1*e
Where `u_2 g(u_2) + h(u_2) \ne 0` and `f(x) \ne 0`.
See also the docstrings of
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best` and
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`.
Examples
========
>>> from sympy import Function, pprint, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep',
... simplify=False))
/ 2 \
| 3*x |
log|----- + 1|
| 2 |
\f (x) /
log(f(x)) = log(C1) - --------------
3
References
==========
- https://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
x = func.args[0]
f = func.func
u = Dummy('u')
u2 = Dummy('u2') # u2 == x/f(x)
r = match # d+e*diff(f(x),x)
C1 = get_numbered_constants(eq, num=1)
xarg = match.get('xarg', 0) # If xarg present take xarg, else zero
yarg = match.get('yarg', 0) # If yarg present take yarg, else zero
int = Integral(
simplify(
(-r[r['d']]/(r[r['e']] + u2*r[r['d']])).subs({x: u2, r['y']: 1})),
(u2, None, x/f(x)))
sol = logcombine(Eq(log(f(x)), int + log(C1)), force=True)
sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x))))
return sol
# XXX: Should this function maybe go somewhere else?
def homogeneous_order(eq, *symbols):
r"""
Returns the order `n` if `g` is homogeneous and ``None`` if it is not
homogeneous.
Determines if a function is homogeneous and if so of what order. A
function `f(x, y, \cdots)` is homogeneous of order `n` if `f(t x, t y,
\cdots) = t^n f(x, y, \cdots)`.
If the function is of two variables, `F(x, y)`, then `f` being homogeneous
of any order is equivalent to being able to rewrite `F(x, y)` as `G(x/y)`
or `H(y/x)`. This fact is used to solve 1st order ordinary differential
equations whose coefficients are homogeneous of the same order (see the
docstrings of
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep` and
:py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`).
Symbols can be functions, but every argument of the function must be a
symbol, and the arguments of the function that appear in the expression
must match those given in the list of symbols. If a declared function
appears with different arguments than given in the list of symbols,
``None`` is returned.
Examples
========
>>> from sympy import Function, homogeneous_order, sqrt
>>> from sympy.abc import x, y
>>> f = Function('f')
>>> homogeneous_order(f(x), f(x)) is None
True
>>> homogeneous_order(f(x,y), f(y, x), x, y) is None
True
>>> homogeneous_order(f(x), f(x), x)
1
>>> homogeneous_order(x**2*f(x)/sqrt(x**2+f(x)**2), x, f(x))
2
>>> homogeneous_order(x**2+f(x), x, f(x)) is None
True
"""
if not symbols:
raise ValueError("homogeneous_order: no symbols were given.")
symset = set(symbols)
eq = sympify(eq)
# The following are not supported
if eq.has(Order, Derivative):
return None
# These are all constants
if (eq.is_Number or
eq.is_NumberSymbol or
eq.is_number
):
return S.Zero
# Replace all functions with dummy variables
dum = numbered_symbols(prefix='d', cls=Dummy)
newsyms = set()
for i in [j for j in symset if getattr(j, 'is_Function')]:
iargs = set(i.args)
if iargs.difference(symset):
return None
else:
dummyvar = next(dum)
eq = eq.subs(i, dummyvar)
symset.remove(i)
newsyms.add(dummyvar)
symset.update(newsyms)
if not eq.free_symbols & symset:
return None
# assuming order of a nested function can only be equal to zero
if isinstance(eq, Function):
return None if homogeneous_order(
eq.args[0], *tuple(symset)) != 0 else S.Zero
# make the replacement of x with x*t and see if t can be factored out
t = Dummy('t', positive=True) # It is sufficient that t > 0
eqs = separatevars(eq.subs([(i, t*i) for i in symset]), [t], dict=True)[t]
if eqs is S.One:
return S.Zero # there was no term with only t
i, d = eqs.as_independent(t, as_Add=False)
b, e = d.as_base_exp()
if b == t:
return e
def ode_2nd_power_series_ordinary(eq, func, order, match):
r"""
Gives a power series solution to a second order homogeneous differential
equation with polynomial coefficients at an ordinary point. A homogeneous
differential equation is of the form
.. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0
For simplicity it is assumed that `P(x)`, `Q(x)` and `R(x)` are polynomials,
it is sufficient that `\frac{Q(x)}{P(x)}` and `\frac{R(x)}{P(x)}` exists at
`x_{0}`. A recurrence relation is obtained by substituting `y` as `\sum_{n=0}^\infty a_{n}x^{n}`,
in the differential equation, and equating the nth term. Using this relation
various terms can be generated.
Examples
========
>>> from sympy import dsolve, Function, pprint
>>> from sympy.abc import x
>>> f = Function("f")
>>> eq = f(x).diff(x, 2) + f(x)
>>> pprint(dsolve(eq, hint='2nd_power_series_ordinary'))
/ 4 2 \ / 2\
|x x | | x | / 6\
f(x) = C2*|-- - -- + 1| + C1*x*|1 - --| + O\x /
\24 2 / \ 6 /
References
==========
- http://tutorial.math.lamar.edu/Classes/DE/SeriesSolutions.aspx
- George E. Simmons, "Differential Equations with Applications and
Historical Notes", p.p 176 - 184
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
n = Dummy("n", integer=True)
s = Wild("s")
k = Wild("k", exclude=[x])
x0 = match.get('x0')
terms = match.get('terms', 5)
p = match[match['a3']]
q = match[match['b3']]
r = match[match['c3']]
seriesdict = {}
recurr = Function("r")
# Generating the recurrence relation which works this way:
# for the second order term the summation begins at n = 2. The coefficients
# p is multiplied with an*(n - 1)*(n - 2)*x**n-2 and a substitution is made such that
# the exponent of x becomes n.
# For example, if p is x, then the second degree recurrence term is
# an*(n - 1)*(n - 2)*x**n-1, substituting (n - 1) as n, it transforms to
# an+1*n*(n - 1)*x**n.
# A similar process is done with the first order and zeroth order term.
coefflist = [(recurr(n), r), (n*recurr(n), q), (n*(n - 1)*recurr(n), p)]
for index, coeff in enumerate(coefflist):
if coeff[1]:
f2 = powsimp(expand((coeff[1]*(x - x0)**(n - index)).subs(x, x + x0)))
if f2.is_Add:
addargs = f2.args
else:
addargs = [f2]
for arg in addargs:
powm = arg.match(s*x**k)
term = coeff[0]*powm[s]
if not powm[k].is_Symbol:
term = term.subs(n, n - powm[k].as_independent(n)[0])
startind = powm[k].subs(n, index)
# Seeing if the startterm can be reduced further.
# If it vanishes for n lesser than startind, it is
# equal to summation from n.
if startind:
for i in reversed(range(startind)):
if not term.subs(n, i):
seriesdict[term] = i
else:
seriesdict[term] = i + 1
break
else:
seriesdict[term] = S.Zero
# Stripping of terms so that the sum starts with the same number.
teq = S.Zero
suminit = seriesdict.values()
rkeys = seriesdict.keys()
req = Add(*rkeys)
if any(suminit):
maxval = max(suminit)
for term in seriesdict:
val = seriesdict[term]
if val != maxval:
for i in range(val, maxval):
teq += term.subs(n, val)
finaldict = {}
if teq:
fargs = teq.atoms(AppliedUndef)
if len(fargs) == 1:
finaldict[fargs.pop()] = 0
else:
maxf = max(fargs, key = lambda x: x.args[0])
sol = solve(teq, maxf)
if isinstance(sol, list):
sol = sol[0]
finaldict[maxf] = sol
# Finding the recurrence relation in terms of the largest term.
fargs = req.atoms(AppliedUndef)
maxf = max(fargs, key = lambda x: x.args[0])
minf = min(fargs, key = lambda x: x.args[0])
if minf.args[0].is_Symbol:
startiter = 0
else:
startiter = -minf.args[0].as_independent(n)[0]
lhs = maxf
rhs = solve(req, maxf)
if isinstance(rhs, list):
rhs = rhs[0]
# Checking how many values are already present
tcounter = len([t for t in finaldict.values() if t])
for _ in range(tcounter, terms - 3): # Assuming c0 and c1 to be arbitrary
check = rhs.subs(n, startiter)
nlhs = lhs.subs(n, startiter)
nrhs = check.subs(finaldict)
finaldict[nlhs] = nrhs
startiter += 1
# Post processing
series = C0 + C1*(x - x0)
for term in finaldict:
if finaldict[term]:
fact = term.args[0]
series += (finaldict[term].subs([(recurr(0), C0), (recurr(1), C1)])*(
x - x0)**fact)
series = collect(expand_mul(series), [C0, C1]) + Order(x**terms)
return Eq(f(x), series)
def ode_2nd_linear_airy(eq, func, order, match):
r"""
Gives solution of the Airy differential equation
.. math :: \frac{d^2y}{dx^2} + (a + b x) y(x) = 0
in terms of Airy special functions airyai and airybi.
Examples
========
>>> from sympy import dsolve, Function
>>> from sympy.abc import x
>>> f = Function("f")
>>> eq = f(x).diff(x, 2) - x*f(x)
>>> dsolve(eq)
Eq(f(x), C1*airyai(x) + C2*airybi(x))
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
b = match['b']
m = match['m']
if m.is_positive:
arg = - b/cbrt(m)**2 - cbrt(m)*x
elif m.is_negative:
arg = - b/cbrt(-m)**2 + cbrt(-m)*x
else:
arg = - b/cbrt(-m)**2 + cbrt(-m)*x
return Eq(f(x), C0*airyai(arg) + C1*airybi(arg))
def ode_2nd_power_series_regular(eq, func, order, match):
r"""
Gives a power series solution to a second order homogeneous differential
equation with polynomial coefficients at a regular point. A second order
homogeneous differential equation is of the form
.. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0
A point is said to regular singular at `x0` if `x - x0\frac{Q(x)}{P(x)}`
and `(x - x0)^{2}\frac{R(x)}{P(x)}` are analytic at `x0`. For simplicity
`P(x)`, `Q(x)` and `R(x)` are assumed to be polynomials. The algorithm for
finding the power series solutions is:
1. Try expressing `(x - x0)P(x)` and `((x - x0)^{2})Q(x)` as power series
solutions about x0. Find `p0` and `q0` which are the constants of the
power series expansions.
2. Solve the indicial equation `f(m) = m(m - 1) + m*p0 + q0`, to obtain the
roots `m1` and `m2` of the indicial equation.
3. If `m1 - m2` is a non integer there exists two series solutions. If
`m1 = m2`, there exists only one solution. If `m1 - m2` is an integer,
then the existence of one solution is confirmed. The other solution may
or may not exist.
The power series solution is of the form `x^{m}\sum_{n=0}^\infty a_{n}x^{n}`. The
coefficients are determined by the following recurrence relation.
`a_{n} = -\frac{\sum_{k=0}^{n-1} q_{n-k} + (m + k)p_{n-k}}{f(m + n)}`. For the case
in which `m1 - m2` is an integer, it can be seen from the recurrence relation
that for the lower root `m`, when `n` equals the difference of both the
roots, the denominator becomes zero. So if the numerator is not equal to zero,
a second series solution exists.
Examples
========
>>> from sympy import dsolve, Function, pprint
>>> from sympy.abc import x
>>> f = Function("f")
>>> eq = x*(f(x).diff(x, 2)) + 2*(f(x).diff(x)) + x*f(x)
>>> pprint(dsolve(eq, hint='2nd_power_series_regular'))
/ 6 4 2 \
| x x x |
/ 4 2 \ C1*|- --- + -- - -- + 1|
| x x | \ 720 24 2 / / 6\
f(x) = C2*|--- - -- + 1| + ------------------------ + O\x /
\120 6 / x
References
==========
- George E. Simmons, "Differential Equations with Applications and
Historical Notes", p.p 176 - 184
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
m = Dummy("m") # for solving the indicial equation
x0 = match.get('x0')
terms = match.get('terms', 5)
p = match['p']
q = match['q']
# Generating the indicial equation
indicial = []
for term in [p, q]:
if not term.has(x):
indicial.append(term)
else:
term = series(term, x=x, n=1, x0=x0)
if isinstance(term, Order):
indicial.append(S.Zero)
else:
for arg in term.args:
if not arg.has(x):
indicial.append(arg)
break
p0, q0 = indicial
sollist = solve(m*(m - 1) + m*p0 + q0, m)
if sollist and isinstance(sollist, list) and all(
[sol.is_real for sol in sollist]):
serdict1 = {}
serdict2 = {}
if len(sollist) == 1:
# Only one series solution exists in this case.
m1 = m2 = sollist.pop()
if terms-m1-1 <= 0:
return Eq(f(x), Order(terms))
serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
else:
m1 = sollist[0]
m2 = sollist[1]
if m1 < m2:
m1, m2 = m2, m1
# Irrespective of whether m1 - m2 is an integer or not, one
# Frobenius series solution exists.
serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
if not (m1 - m2).is_integer:
# Second frobenius series solution exists.
serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1)
else:
# Check if second frobenius series solution exists.
serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1, check=m1)
if serdict1:
finalseries1 = C0
for key in serdict1:
power = int(key.name[1:])
finalseries1 += serdict1[key]*(x - x0)**power
finalseries1 = (x - x0)**m1*finalseries1
finalseries2 = S.Zero
if serdict2:
for key in serdict2:
power = int(key.name[1:])
finalseries2 += serdict2[key]*(x - x0)**power
finalseries2 += C1
finalseries2 = (x - x0)**m2*finalseries2
return Eq(f(x), collect(finalseries1 + finalseries2,
[C0, C1]) + Order(x**terms))
def ode_2nd_linear_bessel(eq, func, order, match):
r"""
Gives solution of the Bessel differential equation
.. math :: x^2 \frac{d^2y}{dx^2} + x \frac{dy}{dx} y(x) + (x^2-n^2) y(x)
if n is integer then the solution is of the form Eq(f(x), C0 besselj(n,x)
+ C1 bessely(n,x)) as both the solutions are linearly independent else if
n is a fraction then the solution is of the form Eq(f(x), C0 besselj(n,x)
+ C1 besselj(-n,x)) which can also transform into Eq(f(x), C0 besselj(n,x)
+ C1 bessely(n,x)).
Examples
========
>>> from sympy.abc import x
>>> from sympy import Symbol
>>> v = Symbol('v', positive=True)
>>> from sympy.solvers.ode import dsolve
>>> from sympy import Function
>>> f = Function('f')
>>> y = f(x)
>>> genform = x**2*y.diff(x, 2) + x*y.diff(x) + (x**2 - v**2)*y
>>> dsolve(genform)
Eq(f(x), C1*besselj(v, x) + C2*bessely(v, x))
References
==========
https://www.math24.net/bessel-differential-equation/
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
n = match['n']
a4 = match['a4']
c4 = match['c4']
d4 = match['d4']
b4 = match['b4']
n = sqrt(n**2 + Rational(1, 4)*(c4 - 1)**2)
return Eq(f(x), ((x**(Rational(1-c4,2)))*(C0*besselj(n/d4,a4*x**d4/d4)
+ C1*bessely(n/d4,a4*x**d4/d4))).subs(x, x-b4))
def _frobenius(n, m, p0, q0, p, q, x0, x, c, check=None):
r"""
Returns a dict with keys as coefficients and values as their values in terms of C0
"""
n = int(n)
# In cases where m1 - m2 is not an integer
m2 = check
d = Dummy("d")
numsyms = numbered_symbols("C", start=0)
numsyms = [next(numsyms) for i in range(n + 1)]
serlist = []
for ser in [p, q]:
# Order term not present
if ser.is_polynomial(x) and Poly(ser, x).degree() <= n:
if x0:
ser = ser.subs(x, x + x0)
dict_ = Poly(ser, x).as_dict()
# Order term present
else:
tseries = series(ser, x=x0, n=n+1)
# Removing order
dict_ = Poly(list(ordered(tseries.args))[: -1], x).as_dict()
# Fill in with zeros, if coefficients are zero.
for i in range(n + 1):
if (i,) not in dict_:
dict_[(i,)] = S.Zero
serlist.append(dict_)
pseries = serlist[0]
qseries = serlist[1]
indicial = d*(d - 1) + d*p0 + q0
frobdict = {}
for i in range(1, n + 1):
num = c*(m*pseries[(i,)] + qseries[(i,)])
for j in range(1, i):
sym = Symbol("C" + str(j))
num += frobdict[sym]*((m + j)*pseries[(i - j,)] + qseries[(i - j,)])
# Checking for cases when m1 - m2 is an integer. If num equals zero
# then a second Frobenius series solution cannot be found. If num is not zero
# then set constant as zero and proceed.
if m2 is not None and i == m2 - m:
if num:
return False
else:
frobdict[numsyms[i]] = S.Zero
else:
frobdict[numsyms[i]] = -num/(indicial.subs(d, m+i))
return frobdict
def _nth_order_reducible_match(eq, func):
r"""
Matches any differential equation that can be rewritten with a smaller
order. Only derivatives of ``func`` alone, wrt a single variable,
are considered, and only in them should ``func`` appear.
"""
# ODE only handles functions of 1 variable so this affirms that state
assert len(func.args) == 1
x = func.args[0]
vc = [d.variable_count[0] for d in eq.atoms(Derivative)
if d.expr == func and len(d.variable_count) == 1]
ords = [c for v, c in vc if v == x]
if len(ords) < 2:
return
smallest = min(ords)
# make sure func does not appear outside of derivatives
D = Dummy()
if eq.subs(func.diff(x, smallest), D).has(func):
return
return {'n': smallest}
def ode_nth_order_reducible(eq, func, order, match):
r"""
Solves ODEs that only involve derivatives of the dependent variable using
a substitution of the form `f^n(x) = g(x)`.
For example any second order ODE of the form `f''(x) = h(f'(x), x)` can be
transformed into a pair of 1st order ODEs `g'(x) = h(g(x), x)` and
`f'(x) = g(x)`. Usually the 1st order ODE for `g` is easier to solve. If
that gives an explicit solution for `g` then `f` is found simply by
integration.
Examples
========
>>> from sympy import Function, dsolve, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = Eq(x*f(x).diff(x)**2 + f(x).diff(x, 2), 0)
>>> dsolve(eq, f(x), hint='nth_order_reducible')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), C1 - sqrt(-1/C2)*log(-C2*sqrt(-1/C2) + x) + sqrt(-1/C2)*log(C2*sqrt(-1/C2) + x))
"""
x = func.args[0]
f = func.func
n = match['n']
# get a unique function name for g
names = [a.name for a in eq.atoms(AppliedUndef)]
while True:
name = Dummy().name
if name not in names:
g = Function(name)
break
w = f(x).diff(x, n)
geq = eq.subs(w, g(x))
gsol = dsolve(geq, g(x))
if not isinstance(gsol, list):
gsol = [gsol]
# Might be multiple solutions to the reduced ODE:
fsol = []
for gsoli in gsol:
fsoli = dsolve(gsoli.subs(g(x), w), f(x)) # or do integration n times
fsol.append(fsoli)
if len(fsol) == 1:
fsol = fsol[0]
return fsol
def _remove_redundant_solutions(eq, solns, order, var):
r"""
Remove redundant solutions from the set of solutions.
This function is needed because otherwise dsolve can return
redundant solutions. As an example consider:
eq = Eq((f(x).diff(x, 2))*f(x).diff(x), 0)
There are two ways to find solutions to eq. The first is to solve f(x).diff(x, 2) = 0
leading to solution f(x)=C1 + C2*x. The second is to solve the equation f(x).diff(x) = 0
leading to the solution f(x) = C1. In this particular case we then see
that the second solution is a special case of the first and we don't
want to return it.
This does not always happen. If we have
eq = Eq((f(x)**2-4)*(f(x).diff(x)-4), 0)
then we get the algebraic solution f(x) = [-2, 2] and the integral solution
f(x) = x + C1 and in this case the two solutions are not equivalent wrt
initial conditions so both should be returned.
"""
def is_special_case_of(soln1, soln2):
return _is_special_case_of(soln1, soln2, eq, order, var)
unique_solns = []
for soln1 in solns:
for soln2 in unique_solns[:]:
if is_special_case_of(soln1, soln2):
break
elif is_special_case_of(soln2, soln1):
unique_solns.remove(soln2)
else:
unique_solns.append(soln1)
return unique_solns
def _is_special_case_of(soln1, soln2, eq, order, var):
r"""
True if soln1 is found to be a special case of soln2 wrt some value of the
constants that appear in soln2. False otherwise.
"""
# The solutions returned by dsolve may be given explicitly or implicitly.
# We will equate the sol1=(soln1.rhs - soln1.lhs), sol2=(soln2.rhs - soln2.lhs)
# of the two solutions.
#
# Since this is supposed to hold for all x it also holds for derivatives.
# For an order n ode we should be able to differentiate
# each solution n times to get n+1 equations.
#
# We then try to solve those n+1 equations for the integrations constants
# in sol2. If we can find a solution that doesn't depend on x then it
# means that some value of the constants in sol1 is a special case of
# sol2 corresponding to a particular choice of the integration constants.
# In case the solution is in implicit form we subtract the sides
soln1 = soln1.rhs - soln1.lhs
soln2 = soln2.rhs - soln2.lhs
# Work for the series solution
if soln1.has(Order) and soln2.has(Order):
if soln1.getO() == soln2.getO():
soln1 = soln1.removeO()
soln2 = soln2.removeO()
else:
return False
elif soln1.has(Order) or soln2.has(Order):
return False
constants1 = soln1.free_symbols.difference(eq.free_symbols)
constants2 = soln2.free_symbols.difference(eq.free_symbols)
constants1_new = get_numbered_constants(Tuple(soln1, soln2), len(constants1))
if len(constants1) == 1:
constants1_new = {constants1_new}
for c_old, c_new in zip(constants1, constants1_new):
soln1 = soln1.subs(c_old, c_new)
# n equations for sol1 = sol2, sol1'=sol2', ...
lhs = soln1
rhs = soln2
eqns = [Eq(lhs, rhs)]
for n in range(1, order):
lhs = lhs.diff(var)
rhs = rhs.diff(var)
eq = Eq(lhs, rhs)
eqns.append(eq)
# BooleanTrue/False awkwardly show up for trivial equations
if any(isinstance(eq, BooleanFalse) for eq in eqns):
return False
eqns = [eq for eq in eqns if not isinstance(eq, BooleanTrue)]
try:
constant_solns = solve(eqns, constants2)
except NotImplementedError:
return False
# Sometimes returns a dict and sometimes a list of dicts
if isinstance(constant_solns, dict):
constant_solns = [constant_solns]
# after solving the issue 17418, maybe we don't need the following checksol code.
for constant_soln in constant_solns:
for eq in eqns:
eq=eq.rhs-eq.lhs
if checksol(eq, constant_soln) is not True:
return False
# If any solution gives all constants as expressions that don't depend on
# x then there exists constants for soln2 that give soln1
for constant_soln in constant_solns:
if not any(c.has(var) for c in constant_soln.values()):
return True
return False
def _nth_linear_match(eq, func, order):
r"""
Matches a differential equation to the linear form:
.. math:: a_n(x) y^{(n)} + \cdots + a_1(x)y' + a_0(x) y + B(x) = 0
Returns a dict of order:coeff terms, where order is the order of the
derivative on each term, and coeff is the coefficient of that derivative.
The key ``-1`` holds the function `B(x)`. Returns ``None`` if the ODE is
not linear. This function assumes that ``func`` has already been checked
to be good.
Examples
========
>>> from sympy import Function, cos, sin
>>> from sympy.abc import x
>>> from sympy.solvers.ode.ode import _nth_linear_match
>>> f = Function('f')
>>> _nth_linear_match(f(x).diff(x, 3) + 2*f(x).diff(x) +
... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) -
... sin(x), f(x), 3)
{-1: x - sin(x), 0: -1, 1: cos(x) + 2, 2: x, 3: 1}
>>> _nth_linear_match(f(x).diff(x, 3) + 2*f(x).diff(x) +
... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) -
... sin(f(x)), f(x), 3) == None
True
"""
x = func.args[0]
one_x = {x}
terms = {i: S.Zero for i in range(-1, order + 1)}
for i in Add.make_args(eq):
if not i.has(func):
terms[-1] += i
else:
c, f = i.as_independent(func)
if (isinstance(f, Derivative)
and set(f.variables) == one_x
and f.args[0] == func):
terms[f.derivative_count] += c
elif f == func:
terms[len(f.args[1:])] += c
else:
return None
return terms
def ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear homogeneous variable-coefficient
Cauchy-Euler equidimensional ordinary differential equation.
This is an equation with form `0 = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
These equations can be solved in a general manner, by substituting
solutions of the form `f(x) = x^r`, and deriving a characteristic equation
for `r`. When there are repeated roots, we include extra terms of the
form `C_{r k} \ln^k(x) x^r`, where `C_{r k}` is an arbitrary integration
constant, `r` is a root of the characteristic equation, and `k` ranges
over the multiplicity of `r`. In the cases where the roots are complex,
solutions of the form `C_1 x^a \sin(b \log(x)) + C_2 x^a \cos(b \log(x))`
are returned, based on expansions with Euler's formula. The general
solution is the sum of the terms found. If SymPy cannot find exact roots
to the characteristic equation, a
:py:obj:`~.ComplexRootOf` instance will be returned
instead.
>>> from sympy import Function, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(4*x**2*f(x).diff(x, 2) + f(x), f(x),
... hint='nth_linear_euler_eq_homogeneous')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), sqrt(x)*(C1 + C2*log(x)))
Note that because this method does not involve integration, there is no
``nth_linear_euler_eq_homogeneous_Integral`` hint.
The following is for internal use:
- ``returns = 'sol'`` returns the solution to the ODE.
- ``returns = 'list'`` returns a list of linearly independent solutions,
corresponding to the fundamental solution set, for use with non
homogeneous solution methods like variation of parameters and
undetermined coefficients. Note that, though the solutions should be
linearly independent, this function does not explicitly check that. You
can do ``assert simplify(wronskian(sollist)) != 0`` to check for linear
independence. Also, ``assert len(sollist) == order`` will need to pass.
- ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>,
'list': <list of linearly independent solutions>}``.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = f(x).diff(x, 2)*x**2 - 4*f(x).diff(x)*x + 6*f(x)
>>> pprint(dsolve(eq, f(x),
... hint='nth_linear_euler_eq_homogeneous'))
2
f(x) = x *(C1 + C2*x)
References
==========
- https://en.wikipedia.org/wiki/Cauchy%E2%80%93Euler_equation
- C. Bender & S. Orszag, "Advanced Mathematical Methods for Scientists and
Engineers", Springer 1999, pp. 12
# indirect doctest
"""
# XXX: This global collectterms hack should be removed.
global collectterms
collectterms = []
x = func.args[0]
f = func.func
r = match
# First, set up characteristic equation.
chareq, symbol = S.Zero, Dummy('x')
for i in r.keys():
if not isinstance(i, str) and i >= 0:
chareq += (r[i]*diff(x**symbol, x, i)*x**-symbol).expand()
chareq = Poly(chareq, symbol)
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
# A generator of constants
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
constants.reverse()
# Create a dict root: multiplicity or charroots
charroots = defaultdict(int)
for root in chareqroots:
charroots[root] += 1
gsol = S.Zero
# We need keep track of terms so we can run collect() at the end.
# This is necessary for constantsimp to work properly.
ln = log
for root, multiplicity in charroots.items():
for i in range(multiplicity):
if isinstance(root, RootOf):
gsol += (x**root) * constants.pop()
if multiplicity != 1:
raise ValueError("Value should be 1")
collectterms = [(0, root, 0)] + collectterms
elif root.is_real:
gsol += ln(x)**i*(x**root) * constants.pop()
collectterms = [(i, root, 0)] + collectterms
else:
reroot = re(root)
imroot = im(root)
gsol += ln(x)**i * (x**reroot) * (
constants.pop() * sin(abs(imroot)*ln(x))
+ constants.pop() * cos(imroot*ln(x)))
# Preserve ordering (multiplicity, real part, imaginary part)
# It will be assumed implicitly when constructing
# fundamental solution sets.
collectterms = [(i, reroot, imroot)] + collectterms
if returns == 'sol':
return Eq(f(x), gsol)
elif returns in ('list' 'both'):
# HOW TO TEST THIS CODE? (dsolve does not pass 'returns' through)
# Create a list of (hopefully) linearly independent solutions
gensols = []
# Keep track of when to use sin or cos for nonzero imroot
for i, reroot, imroot in collectterms:
if imroot == 0:
gensols.append(ln(x)**i*x**reroot)
else:
sin_form = ln(x)**i*x**reroot*sin(abs(imroot)*ln(x))
if sin_form in gensols:
cos_form = ln(x)**i*x**reroot*cos(imroot*ln(x))
gensols.append(cos_form)
else:
gensols.append(sin_form)
if returns == 'list':
return gensols
else:
return {'sol': Eq(f(x), gsol), 'list': gensols}
else:
raise ValueError('Unknown value for key "returns".')
def ode_nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional
ordinary differential equation using undetermined coefficients.
This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
These equations can be solved in a general manner, by substituting
solutions of the form `x = exp(t)`, and deriving a characteristic equation
of form `g(exp(t)) = b_0 f(t) + b_1 f'(t) + b_2 f''(t) \cdots` which can
be then solved by nth_linear_constant_coeff_undetermined_coefficients if
g(exp(t)) has finite number of linearly independent derivatives.
Functions that fit this requirement are finite sums functions of the form
`a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i`
is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For
example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`,
and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have
a finite number of derivatives, because they can be expanded into `\sin(a
x)` and `\cos(b x)` terms. However, SymPy currently cannot do that
expansion, so you will need to manually rewrite the expression in terms of
the above to use this method. So, for example, you will need to manually
convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method
of undetermined coefficients on it.
After replacement of x by exp(t), this method works by creating a trial function
from the expression and all of its linear independent derivatives and
substituting them into the original ODE. The coefficients for each term
will be a system of linear equations, which are be solved for and
substituted, giving the solution. If any of the trial functions are linearly
dependent on the solution to the homogeneous equation, they are multiplied
by sufficient `x` to make them linearly independent.
Examples
========
>>> from sympy import dsolve, Function, Derivative, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x)
>>> dsolve(eq, f(x),
... hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients').expand()
Eq(f(x), C1*x + C2*x**2 + log(x)/2 + 3/4)
"""
x = func.args[0]
f = func.func
r = match
chareq, eq, symbol = S.Zero, S.Zero, Dummy('x')
for i in r.keys():
if not isinstance(i, str) and i >= 0:
chareq += (r[i]*diff(x**symbol, x, i)*x**-symbol).expand()
for i in range(1,degree(Poly(chareq, symbol))+1):
eq += chareq.coeff(symbol**i)*diff(f(x), x, i)
if chareq.as_coeff_add(symbol)[0]:
eq += chareq.as_coeff_add(symbol)[0]*f(x)
e, re = posify(r[-1].subs(x, exp(x)))
eq += e.subs(re)
match = _nth_linear_match(eq, f(x), ode_order(eq, f(x)))
eq_homogeneous = Add(eq,-match[-1])
match['trialset'] = _undetermined_coefficients_match(match[-1], x, func, eq_homogeneous)['trialset']
return ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match).subs(x, log(x)).subs(f(log(x)), f(x)).expand()
def ode_nth_linear_euler_eq_nonhomogeneous_variation_of_parameters(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional
ordinary differential equation using variation of parameters.
This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
This method works by assuming that the particular solution takes the form
.. math:: \sum_{x=1}^{n} c_i(x) y_i(x) {a_n} {x^n} \text{,}
where `y_i` is the `i`\th solution to the homogeneous equation. The
solution is then solved using Wronskian's and Cramer's Rule. The
particular solution is given by multiplying eq given below with `a_n x^{n}`
.. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx
\right) y_i(x) \text{,}
where `W(x)` is the Wronskian of the fundamental system (the system of `n`
linearly independent solutions to the homogeneous equation), and `W_i(x)`
is the Wronskian of the fundamental system with the `i`\th column replaced
with `[0, 0, \cdots, 0, \frac{x^{- n}}{a_n} g{\left(x \right)}]`.
This method is general enough to solve any `n`\th order inhomogeneous
linear differential equation, but sometimes SymPy cannot simplify the
Wronskian well enough to integrate it. If this method hangs, try using the
``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and
simplifying the integrals manually. Also, prefer using
``nth_linear_constant_coeff_undetermined_coefficients`` when it
applies, because it doesn't use integration, making it faster and more
reliable.
Warning, using simplify=False with
'nth_linear_constant_coeff_variation_of_parameters' in
:py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will
not attempt to simplify the Wronskian before integrating. It is
recommended that you only use simplify=False with
'nth_linear_constant_coeff_variation_of_parameters_Integral' for this
method, especially if the solution to the homogeneous equation has
trigonometric functions in it.
Examples
========
>>> from sympy import Function, dsolve, Derivative
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - x**4
>>> dsolve(eq, f(x),
... hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters').expand()
Eq(f(x), C1*x + C2*x**2 + x**4/6)
"""
x = func.args[0]
f = func.func
r = match
gensol = ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='both')
match.update(gensol)
r[-1] = r[-1]/r[ode_order(eq, f(x))]
sol = _solve_variation_of_parameters(eq, func, order, match)
return Eq(f(x), r['sol'].rhs + (sol.rhs - r['sol'].rhs)*r[ode_order(eq, f(x))])
def _linear_coeff_match(expr, func):
r"""
Helper function to match hint ``linear_coefficients``.
Matches the expression to the form `(a_1 x + b_1 f(x) + c_1)/(a_2 x + b_2
f(x) + c_2)` where the following conditions hold:
1. `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are Rationals;
2. `c_1` or `c_2` are not equal to zero;
3. `a_2 b_1 - a_1 b_2` is not equal to zero.
Return ``xarg``, ``yarg`` where
1. ``xarg`` = `(b_2 c_1 - b_1 c_2)/(a_2 b_1 - a_1 b_2)`
2. ``yarg`` = `(a_1 c_2 - a_2 c_1)/(a_2 b_1 - a_1 b_2)`
Examples
========
>>> from sympy import Function
>>> from sympy.abc import x
>>> from sympy.solvers.ode.ode import _linear_coeff_match
>>> from sympy.functions.elementary.trigonometric import sin
>>> f = Function('f')
>>> _linear_coeff_match((
... (-25*f(x) - 8*x + 62)/(4*f(x) + 11*x - 11)), f(x))
(1/9, 22/9)
>>> _linear_coeff_match(
... sin((-5*f(x) - 8*x + 6)/(4*f(x) + x - 1)), f(x))
(19/27, 2/27)
>>> _linear_coeff_match(sin(f(x)/x), f(x))
"""
f = func.func
x = func.args[0]
def abc(eq):
r'''
Internal function of _linear_coeff_match
that returns Rationals a, b, c
if eq is a*x + b*f(x) + c, else None.
'''
eq = _mexpand(eq)
c = eq.as_independent(x, f(x), as_Add=True)[0]
if not c.is_Rational:
return
a = eq.coeff(x)
if not a.is_Rational:
return
b = eq.coeff(f(x))
if not b.is_Rational:
return
if eq == a*x + b*f(x) + c:
return a, b, c
def match(arg):
r'''
Internal function of _linear_coeff_match that returns Rationals a1,
b1, c1, a2, b2, c2 and a2*b1 - a1*b2 of the expression (a1*x + b1*f(x)
+ c1)/(a2*x + b2*f(x) + c2) if one of c1 or c2 and a2*b1 - a1*b2 is
non-zero, else None.
'''
n, d = arg.together().as_numer_denom()
m = abc(n)
if m is not None:
a1, b1, c1 = m
m = abc(d)
if m is not None:
a2, b2, c2 = m
d = a2*b1 - a1*b2
if (c1 or c2) and d:
return a1, b1, c1, a2, b2, c2, d
m = [fi.args[0] for fi in expr.atoms(Function) if fi.func != f and
len(fi.args) == 1 and not fi.args[0].is_Function] or {expr}
m1 = match(m.pop())
if m1 and all(match(mi) == m1 for mi in m):
a1, b1, c1, a2, b2, c2, denom = m1
return (b2*c1 - b1*c2)/denom, (a1*c2 - a2*c1)/denom
def ode_linear_coefficients(eq, func, order, match):
r"""
Solves a differential equation with linear coefficients.
The general form of a differential equation with linear coefficients is
.. math:: y' + F\left(\!\frac{a_1 x + b_1 y + c_1}{a_2 x + b_2 y +
c_2}\!\right) = 0\text{,}
where `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are constants and `a_1 b_2
- a_2 b_1 \ne 0`.
This can be solved by substituting:
.. math:: x = x' + \frac{b_2 c_1 - b_1 c_2}{a_2 b_1 - a_1 b_2}
y = y' + \frac{a_1 c_2 - a_2 c_1}{a_2 b_1 - a_1
b_2}\text{.}
This substitution reduces the equation to a homogeneous differential
equation.
See Also
========
:meth:`sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best`
:meth:`sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`
:meth:`sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`
Examples
========
>>> from sympy import Function, pprint
>>> from sympy.solvers.ode.ode import dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> df = f(x).diff(x)
>>> eq = (x + f(x) + 1)*df + (f(x) - 6*x + 1)
>>> dsolve(eq, hint='linear_coefficients')
[Eq(f(x), -x - sqrt(C1 + 7*x**2) - 1), Eq(f(x), -x + sqrt(C1 + 7*x**2) - 1)]
>>> pprint(dsolve(eq, hint='linear_coefficients'))
___________ ___________
/ 2 / 2
[f(x) = -x - \/ C1 + 7*x - 1, f(x) = -x + \/ C1 + 7*x - 1]
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
return ode_1st_homogeneous_coeff_best(eq, func, order, match)
def ode_1st_power_series(eq, func, order, match):
r"""
The power series solution is a method which gives the Taylor series expansion
to the solution of a differential equation.
For a first order differential equation `\frac{dy}{dx} = h(x, y)`, a power
series solution exists at a point `x = x_{0}` if `h(x, y)` is analytic at `x_{0}`.
The solution is given by
.. math:: y(x) = y(x_{0}) + \sum_{n = 1}^{\infty} \frac{F_{n}(x_{0},b)(x - x_{0})^n}{n!},
where `y(x_{0}) = b` is the value of y at the initial value of `x_{0}`.
To compute the values of the `F_{n}(x_{0},b)` the following algorithm is
followed, until the required number of terms are generated.
1. `F_1 = h(x_{0}, b)`
2. `F_{n+1} = \frac{\partial F_{n}}{\partial x} + \frac{\partial F_{n}}{\partial y}F_{1}`
Examples
========
>>> from sympy import Function, pprint, exp
>>> from sympy.solvers.ode.ode import dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = exp(x)*(f(x).diff(x)) - f(x)
>>> pprint(dsolve(eq, hint='1st_power_series'))
3 4 5
C1*x C1*x C1*x / 6\
f(x) = C1 + C1*x - ----- + ----- + ----- + O\x /
6 24 60
References
==========
- Travis W. Walker, Analytic power series technique for solving first-order
differential equations, p.p 17, 18
"""
x = func.args[0]
y = match['y']
f = func.func
h = -match[match['d']]/match[match['e']]
point = match.get('f0')
value = match.get('f0val')
terms = match.get('terms')
# First term
F = h
if not h:
return Eq(f(x), value)
# Initialization
series = value
if terms > 1:
hc = h.subs({x: point, y: value})
if hc.has(oo) or hc.has(NaN) or hc.has(zoo):
# Derivative does not exist, not analytic
return Eq(f(x), oo)
elif hc:
series += hc*(x - point)
for factcount in range(2, terms):
Fnew = F.diff(x) + F.diff(y)*h
Fnewc = Fnew.subs({x: point, y: value})
# Same logic as above
if Fnewc.has(oo) or Fnewc.has(NaN) or Fnewc.has(-oo) or Fnewc.has(zoo):
return Eq(f(x), oo)
series += Fnewc*((x - point)**factcount)/factorial(factcount)
F = Fnew
series += Order(x**terms)
return Eq(f(x), series)
def ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='sol'):
r"""
Solves an `n`\th order linear homogeneous differential equation with
constant coefficients.
This is an equation of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = 0\text{.}
These equations can be solved in a general manner, by taking the roots of
the characteristic equation `a_n m^n + a_{n-1} m^{n-1} + \cdots + a_1 m +
a_0 = 0`. The solution will then be the sum of `C_n x^i e^{r x}` terms,
for each where `C_n` is an arbitrary constant, `r` is a root of the
characteristic equation and `i` is one of each from 0 to the multiplicity
of the root - 1 (for example, a root 3 of multiplicity 2 would create the
terms `C_1 e^{3 x} + C_2 x e^{3 x}`). The exponential is usually expanded
for complex roots using Euler's equation `e^{I x} = \cos(x) + I \sin(x)`.
Complex roots always come in conjugate pairs in polynomials with real
coefficients, so the two roots will be represented (after simplifying the
constants) as `e^{a x} \left(C_1 \cos(b x) + C_2 \sin(b x)\right)`.
If SymPy cannot find exact roots to the characteristic equation, a
:py:class:`~sympy.polys.rootoftools.ComplexRootOf` instance will be return
instead.
>>> from sympy import Function, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(f(x).diff(x, 5) + 10*f(x).diff(x) - 2*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), C5*exp(x*CRootOf(_x**5 + 10*_x - 2, 0))
+ (C1*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 1)))
+ C2*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 1))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 1)))
+ (C3*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 3)))
+ C4*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 3))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 3))))
Note that because this method does not involve integration, there is no
``nth_linear_constant_coeff_homogeneous_Integral`` hint.
The following is for internal use:
- ``returns = 'sol'`` returns the solution to the ODE.
- ``returns = 'list'`` returns a list of linearly independent solutions,
for use with non homogeneous solution methods like variation of
parameters and undetermined coefficients. Note that, though the
solutions should be linearly independent, this function does not
explicitly check that. You can do ``assert simplify(wronskian(sollist))
!= 0`` to check for linear independence. Also, ``assert len(sollist) ==
order`` will need to pass.
- ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>,
'list': <list of linearly independent solutions>}``.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 4) + 2*f(x).diff(x, 3) -
... 2*f(x).diff(x, 2) - 6*f(x).diff(x) + 5*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous'))
x -2*x
f(x) = (C1 + C2*x)*e + (C3*sin(x) + C4*cos(x))*e
References
==========
- https://en.wikipedia.org/wiki/Linear_differential_equation section:
Nonhomogeneous_equation_with_constant_coefficients
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 211
# indirect doctest
"""
x = func.args[0]
f = func.func
r = match
# First, set up characteristic equation.
chareq, symbol = S.Zero, Dummy('x')
for i in r.keys():
if type(i) == str or i < 0:
pass
else:
chareq += r[i]*symbol**i
chareq = Poly(chareq, symbol)
# Can't just call roots because it doesn't return rootof for unsolveable
# polynomials.
chareqroots = roots(chareq, multiple=True)
if len(chareqroots) != order:
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
chareq_is_complex = not all([i.is_real for i in chareq.all_coeffs()])
# A generator of constants
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
# Create a dict root: multiplicity or charroots
charroots = defaultdict(int)
for root in chareqroots:
charroots[root] += 1
# We need to keep track of terms so we can run collect() at the end.
# This is necessary for constantsimp to work properly.
#
# XXX: This global collectterms hack should be removed.
global collectterms
collectterms = []
gensols = []
conjugate_roots = [] # used to prevent double-use of conjugate roots
# Loop over roots in theorder provided by roots/rootof...
for root in chareqroots:
# but don't repoeat multiple roots.
if root not in charroots:
continue
multiplicity = charroots.pop(root)
for i in range(multiplicity):
if chareq_is_complex:
gensols.append(x**i*exp(root*x))
collectterms = [(i, root, 0)] + collectterms
continue
reroot = re(root)
imroot = im(root)
if imroot.has(atan2) and reroot.has(atan2):
# Remove this condition when re and im stop returning
# circular atan2 usages.
gensols.append(x**i*exp(root*x))
collectterms = [(i, root, 0)] + collectterms
else:
if root in conjugate_roots:
collectterms = [(i, reroot, imroot)] + collectterms
continue
if imroot == 0:
gensols.append(x**i*exp(reroot*x))
collectterms = [(i, reroot, 0)] + collectterms
continue
conjugate_roots.append(conjugate(root))
gensols.append(x**i*exp(reroot*x) * sin(abs(imroot) * x))
gensols.append(x**i*exp(reroot*x) * cos( imroot * x))
# This ordering is important
collectterms = [(i, reroot, imroot)] + collectterms
if returns == 'list':
return gensols
elif returns in ('sol' 'both'):
gsol = Add(*[i*j for (i, j) in zip(constants, gensols)])
if returns == 'sol':
return Eq(f(x), gsol)
else:
return {'sol': Eq(f(x), gsol), 'list': gensols}
else:
raise ValueError('Unknown value for key "returns".')
def ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match):
r"""
Solves an `n`\th order linear differential equation with constant
coefficients using the method of undetermined coefficients.
This method works on differential equations of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = P(x)\text{,}
where `P(x)` is a function that has a finite number of linearly
independent derivatives.
Functions that fit this requirement are finite sums functions of the form
`a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i`
is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For
example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`,
and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have
a finite number of derivatives, because they can be expanded into `\sin(a
x)` and `\cos(b x)` terms. However, SymPy currently cannot do that
expansion, so you will need to manually rewrite the expression in terms of
the above to use this method. So, for example, you will need to manually
convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method
of undetermined coefficients on it.
This method works by creating a trial function from the expression and all
of its linear independent derivatives and substituting them into the
original ODE. The coefficients for each term will be a system of linear
equations, which are be solved for and substituted, giving the solution.
If any of the trial functions are linearly dependent on the solution to
the homogeneous equation, they are multiplied by sufficient `x` to make
them linearly independent.
Examples
========
>>> from sympy import Function, dsolve, pprint, exp, cos
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 2) + 2*f(x).diff(x) + f(x) -
... 4*exp(-x)*x**2 + cos(2*x), f(x),
... hint='nth_linear_constant_coeff_undetermined_coefficients'))
/ / 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
"""
gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='both')
match.update(gensol)
return _solve_undetermined_coefficients(eq, func, order, match)
def _solve_undetermined_coefficients(eq, func, order, match):
r"""
Helper function for the method of undetermined coefficients.
See the
:py:meth:`~sympy.solvers.ode.ode.ode_nth_linear_constant_coeff_undetermined_coefficients`
docstring for more information on this method.
The parameter ``match`` should be a dictionary that has the following
keys:
``list``
A list of solutions to the homogeneous equation, such as the list
returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='list')``.
``sol``
The general solution, such as the solution returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``.
``trialset``
The set of trial functions as returned by
``_undetermined_coefficients_match()['trialset']``.
"""
x = func.args[0]
f = func.func
r = match
coeffs = numbered_symbols('a', cls=Dummy)
coefflist = []
gensols = r['list']
gsol = r['sol']
trialset = r['trialset']
if len(gensols) != order:
raise NotImplementedError("Cannot find " + str(order) +
" solutions to the homogeneous equation necessary to apply" +
" undetermined coefficients to " + str(eq) +
" (number of terms != order)")
trialfunc = 0
for i in trialset:
c = next(coeffs)
coefflist.append(c)
trialfunc += c*i
eqs = sub_func_doit(eq, f(x), trialfunc)
coeffsdict = dict(list(zip(trialset, [0]*(len(trialset) + 1))))
eqs = _mexpand(eqs)
for i in Add.make_args(eqs):
s = separatevars(i, dict=True, symbols=[x])
if coeffsdict.get(s[x]):
coeffsdict[s[x]] += s['coeff']
else:
coeffsdict[s[x]] = s['coeff']
coeffvals = solve(list(coeffsdict.values()), coefflist)
if not coeffvals:
raise NotImplementedError(
"Could not solve `%s` using the "
"method of undetermined coefficients "
"(unable to solve for coefficients)." % eq)
psol = trialfunc.subs(coeffvals)
return Eq(f(x), gsol.rhs + psol)
def _undetermined_coefficients_match(expr, x, func=None, eq_homogeneous=S.Zero):
r"""
Returns a trial function match if undetermined coefficients can be applied
to ``expr``, and ``None`` otherwise.
A trial expression can be found for an expression for use with the method
of undetermined coefficients if the expression is an
additive/multiplicative combination of constants, polynomials in `x` (the
independent variable of expr), `\sin(a x + b)`, `\cos(a x + b)`, and
`e^{a x}` terms (in other words, it has a finite number of linearly
independent derivatives).
Note that you may still need to multiply each term returned here by
sufficient `x` to make it linearly independent with the solutions to the
homogeneous equation.
This is intended for internal use by ``undetermined_coefficients`` hints.
SymPy currently has no way to convert `\sin^n(x) \cos^m(y)` into a sum of
only `\sin(a x)` and `\cos(b x)` terms, so these are not implemented. So,
for example, you will need to manually convert `\sin^2(x)` into `[1 +
\cos(2 x)]/2` to properly apply the method of undetermined coefficients on
it.
Examples
========
>>> from sympy import log, exp
>>> from sympy.solvers.ode.ode import _undetermined_coefficients_match
>>> from sympy.abc import x
>>> _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x)
{'test': True, 'trialset': {x*exp(x), exp(-x), exp(x)}}
>>> _undetermined_coefficients_match(log(x), x)
{'test': False}
"""
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1)
retdict = {}
def _test_term(expr, x):
r"""
Test if ``expr`` fits the proper form for undetermined coefficients.
"""
if not expr.has(x):
return True
elif expr.is_Add:
return all(_test_term(i, x) for i in expr.args)
elif expr.is_Mul:
if expr.has(sin, cos):
foundtrig = False
# Make sure that there is only one trig function in the args.
# See the docstring.
for i in expr.args:
if i.has(sin, cos):
if foundtrig:
return False
else:
foundtrig = True
return all(_test_term(i, x) for i in expr.args)
elif expr.is_Function:
if expr.func in (sin, cos, exp, sinh, cosh):
if expr.args[0].match(a*x + b):
return True
else:
return False
else:
return False
elif expr.is_Pow and expr.base.is_Symbol and expr.exp.is_Integer and \
expr.exp >= 0:
return True
elif expr.is_Pow and expr.base.is_number:
if expr.exp.match(a*x + b):
return True
else:
return False
elif expr.is_Symbol or expr.is_number:
return True
else:
return False
def _get_trial_set(expr, x, exprs=set()):
r"""
Returns a set of trial terms for undetermined coefficients.
The idea behind undetermined coefficients is that the terms expression
repeat themselves after a finite number of derivatives, except for the
coefficients (they are linearly dependent). So if we collect these,
we should have the terms of our trial function.
"""
def _remove_coefficient(expr, x):
r"""
Returns the expression without a coefficient.
Similar to expr.as_independent(x)[1], except it only works
multiplicatively.
"""
term = S.One
if expr.is_Mul:
for i in expr.args:
if i.has(x):
term *= i
elif expr.has(x):
term = expr
return term
expr = expand_mul(expr)
if expr.is_Add:
for term in expr.args:
if _remove_coefficient(term, x) in exprs:
pass
else:
exprs.add(_remove_coefficient(term, x))
exprs = exprs.union(_get_trial_set(term, x, exprs))
else:
term = _remove_coefficient(expr, x)
tmpset = exprs.union({term})
oldset = set()
while tmpset != oldset:
# If you get stuck in this loop, then _test_term is probably
# broken
oldset = tmpset.copy()
expr = expr.diff(x)
term = _remove_coefficient(expr, x)
if term.is_Add:
tmpset = tmpset.union(_get_trial_set(term, x, tmpset))
else:
tmpset.add(term)
exprs = tmpset
return exprs
def is_homogeneous_solution(term):
r""" This function checks whether the given trialset contains any root
of homogenous equation"""
return expand(sub_func_doit(eq_homogeneous, func, term)).is_zero
retdict['test'] = _test_term(expr, x)
if retdict['test']:
# Try to generate a list of trial solutions that will have the
# undetermined coefficients. Note that if any of these are not linearly
# independent with any of the solutions to the homogeneous equation,
# then they will need to be multiplied by sufficient x to make them so.
# This function DOES NOT do that (it doesn't even look at the
# homogeneous equation).
temp_set = set()
for i in Add.make_args(expr):
act = _get_trial_set(i,x)
if eq_homogeneous is not S.Zero:
while any(is_homogeneous_solution(ts) for ts in act):
act = {x*ts for ts in act}
temp_set = temp_set.union(act)
retdict['trialset'] = temp_set
return retdict
def ode_nth_linear_constant_coeff_variation_of_parameters(eq, func, order, match):
r"""
Solves an `n`\th order linear differential equation with constant
coefficients using the method of variation of parameters.
This method works on any differential equations of the form
.. math:: f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0
f(x) = P(x)\text{.}
This method works by assuming that the particular solution takes the form
.. math:: \sum_{x=1}^{n} c_i(x) y_i(x)\text{,}
where `y_i` is the `i`\th solution to the homogeneous equation. The
solution is then solved using Wronskian's and Cramer's Rule. The
particular solution is given by
.. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx
\right) y_i(x) \text{,}
where `W(x)` is the Wronskian of the fundamental system (the system of `n`
linearly independent solutions to the homogeneous equation), and `W_i(x)`
is the Wronskian of the fundamental system with the `i`\th column replaced
with `[0, 0, \cdots, 0, P(x)]`.
This method is general enough to solve any `n`\th order inhomogeneous
linear differential equation with constant coefficients, but sometimes
SymPy cannot simplify the Wronskian well enough to integrate it. If this
method hangs, try using the
``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and
simplifying the integrals manually. Also, prefer using
``nth_linear_constant_coeff_undetermined_coefficients`` when it
applies, because it doesn't use integration, making it faster and more
reliable.
Warning, using simplify=False with
'nth_linear_constant_coeff_variation_of_parameters' in
:py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will
not attempt to simplify the Wronskian before integrating. It is
recommended that you only use simplify=False with
'nth_linear_constant_coeff_variation_of_parameters_Integral' for this
method, especially if the solution to the homogeneous equation has
trigonometric functions in it.
Examples
========
>>> from sympy import Function, dsolve, pprint, exp, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 3) - 3*f(x).diff(x, 2) +
... 3*f(x).diff(x) - f(x) - exp(x)*log(x), f(x),
... hint='nth_linear_constant_coeff_variation_of_parameters'))
/ / / 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
"""
gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='both')
match.update(gensol)
return _solve_variation_of_parameters(eq, func, order, match)
def _solve_variation_of_parameters(eq, func, order, match):
r"""
Helper function for the method of variation of parameters and nonhomogeneous euler eq.
See the
:py:meth:`~sympy.solvers.ode.ode.ode_nth_linear_constant_coeff_variation_of_parameters`
docstring for more information on this method.
The parameter ``match`` should be a dictionary that has the following
keys:
``list``
A list of solutions to the homogeneous equation, such as the list
returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='list')``.
``sol``
The general solution, such as the solution returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``.
"""
x = func.args[0]
f = func.func
r = match
psol = 0
gensols = r['list']
gsol = r['sol']
wr = wronskian(gensols, x)
if r.get('simplify', True):
wr = simplify(wr) # We need much better simplification for
# some ODEs. See issue 4662, for example.
# To reduce commonly occurring sin(x)**2 + cos(x)**2 to 1
wr = trigsimp(wr, deep=True, recursive=True)
if not wr:
# The wronskian will be 0 iff the solutions are not linearly
# independent.
raise NotImplementedError("Cannot find " + str(order) +
" solutions to the homogeneous equation necessary to apply " +
"variation of parameters to " + str(eq) + " (Wronskian == 0)")
if len(gensols) != order:
raise NotImplementedError("Cannot find " + str(order) +
" solutions to the homogeneous equation necessary to apply " +
"variation of parameters to " +
str(eq) + " (number of terms != order)")
negoneterm = (-1)**(order)
for i in gensols:
psol += negoneterm*Integral(wronskian([sol for sol in gensols if sol != i], x)*r[-1]/wr, x)*i/r[order]
negoneterm *= -1
if r.get('simplify', True):
psol = simplify(psol)
psol = trigsimp(psol, deep=True)
return Eq(f(x), gsol.rhs + psol)
def checkinfsol(eq, infinitesimals, func=None, order=None):
r"""
This function is used to check if the given infinitesimals are the
actual infinitesimals of the given first order differential equation.
This method is specific to the Lie Group Solver of ODEs.
As of now, it simply checks, by substituting the infinitesimals in the
partial differential equation.
.. math:: \frac{\partial \eta}{\partial x} + \left(\frac{\partial \eta}{\partial y}
- \frac{\partial \xi}{\partial x}\right)*h
- \frac{\partial \xi}{\partial y}*h^{2}
- \xi\frac{\partial h}{\partial x} - \eta\frac{\partial h}{\partial y} = 0
where `\eta`, and `\xi` are the infinitesimals and `h(x,y) = \frac{dy}{dx}`
The infinitesimals should be given in the form of a list of dicts
``[{xi(x, y): inf, eta(x, y): inf}]``, corresponding to the
output of the function infinitesimals. It returns a list
of values of the form ``[(True/False, sol)]`` where ``sol`` is the value
obtained after substituting the infinitesimals in the PDE. If it
is ``True``, then ``sol`` would be 0.
"""
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
if not func:
eq, func = _preprocess(eq)
variables = func.args
if len(variables) != 1:
raise ValueError("ODE's have only one independent variable")
else:
x = variables[0]
if not order:
order = ode_order(eq, func)
if order != 1:
raise NotImplementedError("Lie groups solver has been implemented "
"only for first order differential equations")
else:
df = func.diff(x)
a = Wild('a', exclude = [df])
b = Wild('b', exclude = [df])
match = collect(expand(eq), df).match(a*df + b)
if match:
h = -simplify(match[b]/match[a])
else:
try:
sol = solve(eq, df)
except NotImplementedError:
raise NotImplementedError("Infinitesimals for the "
"first order ODE could not be found")
else:
h = sol[0] # Find infinitesimals for one solution
y = Dummy('y')
h = h.subs(func, y)
xi = Function('xi')(x, y)
eta = Function('eta')(x, y)
dxi = Function('xi')(x, func)
deta = Function('eta')(x, func)
pde = (eta.diff(x) + (eta.diff(y) - xi.diff(x))*h -
(xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)))
soltup = []
for sol in infinitesimals:
tsol = {xi: S(sol[dxi]).subs(func, y),
eta: S(sol[deta]).subs(func, y)}
sol = simplify(pde.subs(tsol).doit())
if sol:
soltup.append((False, sol.subs(y, func)))
else:
soltup.append((True, 0))
return soltup
def _ode_lie_group_try_heuristic(eq, heuristic, func, match, inf):
xi = Function("xi")
eta = Function("eta")
f = func.func
x = func.args[0]
y = match['y']
h = match['h']
tempsol = []
if not inf:
try:
inf = infinitesimals(eq, hint=heuristic, func=func, order=1, match=match)
except ValueError:
return None
for infsim in inf:
xiinf = (infsim[xi(x, func)]).subs(func, y)
etainf = (infsim[eta(x, func)]).subs(func, y)
# This condition creates recursion while using pdsolve.
# Since the first step while solving a PDE of form
# a*(f(x, y).diff(x)) + b*(f(x, y).diff(y)) + c = 0
# is to solve the ODE dy/dx = b/a
if simplify(etainf/xiinf) == h:
continue
rpde = f(x, y).diff(x)*xiinf + f(x, y).diff(y)*etainf
r = pdsolve(rpde, func=f(x, y)).rhs
s = pdsolve(rpde - 1, func=f(x, y)).rhs
newcoord = [_lie_group_remove(coord) for coord in [r, s]]
r = Dummy("r")
s = Dummy("s")
C1 = Symbol("C1")
rcoord = newcoord[0]
scoord = newcoord[-1]
try:
sol = solve([r - rcoord, s - scoord], x, y, dict=True)
if sol == []:
continue
except NotImplementedError:
continue
else:
sol = sol[0]
xsub = sol[x]
ysub = sol[y]
num = simplify(scoord.diff(x) + scoord.diff(y)*h)
denom = simplify(rcoord.diff(x) + rcoord.diff(y)*h)
if num and denom:
diffeq = simplify((num/denom).subs([(x, xsub), (y, ysub)]))
sep = separatevars(diffeq, symbols=[r, s], dict=True)
if sep:
# Trying to separate, r and s coordinates
deq = integrate((1/sep[s]), s) + C1 - integrate(sep['coeff']*sep[r], r)
# Substituting and reverting back to original coordinates
deq = deq.subs([(r, rcoord), (s, scoord)])
try:
sdeq = solve(deq, y)
except NotImplementedError:
tempsol.append(deq)
else:
return [Eq(f(x), sol) for sol in sdeq]
elif denom: # (ds/dr) is zero which means s is constant
return [Eq(f(x), solve(scoord - C1, y)[0])]
elif num: # (dr/ds) is zero which means r is constant
return [Eq(f(x), solve(rcoord - C1, y)[0])]
# If nothing works, return solution as it is, without solving for y
if tempsol:
return [Eq(sol.subs(y, f(x)), 0) for sol in tempsol]
return None
def _ode_lie_group( s, func, order, match):
heuristics = lie_heuristics
inf = {}
f = func.func
x = func.args[0]
df = func.diff(x)
xi = Function("xi")
eta = Function("eta")
xis = match['xi']
etas = match['eta']
y = match.pop('y', None)
if y:
h = -simplify(match[match['d']]/match[match['e']])
y = y
else:
y = Dummy("y")
h = s.subs(func, y)
if xis is not None and etas is not None:
inf = [{xi(x, f(x)): S(xis), eta(x, f(x)): S(etas)}]
if checkinfsol(Eq(df, s), inf, func=f(x), order=1)[0][0]:
heuristics = ["user_defined"] + list(heuristics)
match = {'h': h, 'y': y}
# This is done so that if any heuristic raises a ValueError
# another heuristic can be used.
sol = None
for heuristic in heuristics:
sol = _ode_lie_group_try_heuristic(Eq(df, s), heuristic, func, match, inf)
if sol:
return sol
return sol
def ode_lie_group(eq, func, order, match):
r"""
This hint implements the Lie group method of solving first order differential
equations. The aim is to convert the given differential equation from the
given coordinate system into another coordinate system where it becomes
invariant under the one-parameter Lie group of translations. The converted
ODE can be easily solved by quadrature. It makes use of the
:py:meth:`sympy.solvers.ode.infinitesimals` function which returns the
infinitesimals of the transformation.
The coordinates `r` and `s` can be found by solving the following Partial
Differential Equations.
.. math :: \xi\frac{\partial r}{\partial x} + \eta\frac{\partial r}{\partial y}
= 0
.. math :: \xi\frac{\partial s}{\partial x} + \eta\frac{\partial s}{\partial y}
= 1
The differential equation becomes separable in the new coordinate system
.. math :: \frac{ds}{dr} = \frac{\frac{\partial s}{\partial x} +
h(x, y)\frac{\partial s}{\partial y}}{
\frac{\partial r}{\partial x} + h(x, y)\frac{\partial r}{\partial y}}
After finding the solution by integration, it is then converted back to the original
coordinate system by substituting `r` and `s` in terms of `x` and `y` again.
Examples
========
>>> from sympy import Function, dsolve, exp, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x) + 2*x*f(x) - x*exp(-x**2), f(x),
... hint='lie_group'))
/ 2\ 2
| x | -x
f(x) = |C1 + --|*e
\ 2 /
References
==========
- Solving differential equations by Symmetry Groups,
John Starrett, pp. 1 - pp. 14
"""
x = func.args[0]
df = func.diff(x)
try:
eqsol = solve(eq, df)
except NotImplementedError:
eqsol = []
desols = []
for s in eqsol:
sol = _ode_lie_group(s, func, order, match=match)
if sol:
desols.extend(sol)
if desols == []:
raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by"
+ " the lie group method")
return desols
def _lie_group_remove(coords):
r"""
This function is strictly meant for internal use by the Lie group ODE solving
method. It replaces arbitrary functions returned by pdsolve as follows:
1] If coords is an arbitrary function, then its argument is returned.
2] An arbitrary function in an Add object is replaced by zero.
3] An arbitrary function in a Mul object is replaced by one.
4] If there is no arbitrary function coords is returned unchanged.
Examples
========
>>> from sympy.solvers.ode.ode import _lie_group_remove
>>> from sympy import Function
>>> from sympy.abc import x, y
>>> F = Function("F")
>>> eq = x**2*y
>>> _lie_group_remove(eq)
x**2*y
>>> eq = F(x**2*y)
>>> _lie_group_remove(eq)
x**2*y
>>> eq = x*y**2 + F(x**3)
>>> _lie_group_remove(eq)
x*y**2
>>> eq = (F(x**3) + y)*x**4
>>> _lie_group_remove(eq)
x**4*y
"""
if isinstance(coords, AppliedUndef):
return coords.args[0]
elif coords.is_Add:
subfunc = coords.atoms(AppliedUndef)
if subfunc:
for func in subfunc:
coords = coords.subs(func, 0)
return coords
elif coords.is_Pow:
base, expr = coords.as_base_exp()
base = _lie_group_remove(base)
expr = _lie_group_remove(expr)
return base**expr
elif coords.is_Mul:
mulargs = []
coordargs = coords.args
for arg in coordargs:
if not isinstance(coords, AppliedUndef):
mulargs.append(_lie_group_remove(arg))
return Mul(*mulargs)
return coords
def infinitesimals(eq, func=None, order=None, hint='default', match=None):
r"""
The infinitesimal functions of an ordinary differential equation, `\xi(x,y)`
and `\eta(x,y)`, are the infinitesimals of the Lie group of point transformations
for which the differential equation is invariant. So, the ODE `y'=f(x,y)`
would admit a Lie group `x^*=X(x,y;\varepsilon)=x+\varepsilon\xi(x,y)`,
`y^*=Y(x,y;\varepsilon)=y+\varepsilon\eta(x,y)` such that `(y^*)'=f(x^*, y^*)`.
A change of coordinates, to `r(x,y)` and `s(x,y)`, can be performed so this Lie group
becomes the translation group, `r^*=r` and `s^*=s+\varepsilon`.
They are tangents to the coordinate curves of the new system.
Consider the transformation `(x, y) \to (X, Y)` such that the
differential equation remains invariant. `\xi` and `\eta` are the tangents to
the transformed coordinates `X` and `Y`, at `\varepsilon=0`.
.. math:: \left(\frac{\partial X(x,y;\varepsilon)}{\partial\varepsilon
}\right)|_{\varepsilon=0} = \xi,
\left(\frac{\partial Y(x,y;\varepsilon)}{\partial\varepsilon
}\right)|_{\varepsilon=0} = \eta,
The infinitesimals can be found by solving the following PDE:
>>> from sympy import Function, Eq, pprint
>>> from sympy.abc import x, y
>>> xi, eta, h = map(Function, ['xi', 'eta', 'h'])
>>> h = h(x, y) # dy/dx = h
>>> eta = eta(x, y)
>>> xi = xi(x, y)
>>> genform = Eq(eta.diff(x) + (eta.diff(y) - xi.diff(x))*h
... - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)), 0)
>>> pprint(genform)
/d d \ d 2 d
|--(eta(x, y)) - --(xi(x, y))|*h(x, y) - eta(x, y)*--(h(x, y)) - h (x, y)*--(x
\dy dx / dy dy
<BLANKLINE>
d d
i(x, y)) - xi(x, y)*--(h(x, y)) + --(eta(x, y)) = 0
dx dx
Solving the above mentioned PDE is not trivial, and can be solved only by
making intelligent assumptions for `\xi` and `\eta` (heuristics). Once an
infinitesimal is found, the attempt to find more heuristics stops. This is done to
optimise the speed of solving the differential equation. If a list of all the
infinitesimals is needed, ``hint`` should be flagged as ``all``, which gives
the complete list of infinitesimals. If the infinitesimals for a particular
heuristic needs to be found, it can be passed as a flag to ``hint``.
Examples
========
>>> from sympy import Function
>>> from sympy.solvers.ode.ode import infinitesimals
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = f(x).diff(x) - x**2*f(x)
>>> infinitesimals(eq)
[{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}]
References
==========
- Solving differential equations by Symmetry Groups,
John Starrett, pp. 1 - pp. 14
"""
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
if not func:
eq, func = _preprocess(eq)
variables = func.args
if len(variables) != 1:
raise ValueError("ODE's have only one independent variable")
else:
x = variables[0]
if not order:
order = ode_order(eq, func)
if order != 1:
raise NotImplementedError("Infinitesimals for only "
"first order ODE's have been implemented")
else:
df = func.diff(x)
# Matching differential equation of the form a*df + b
a = Wild('a', exclude = [df])
b = Wild('b', exclude = [df])
if match: # Used by lie_group hint
h = match['h']
y = match['y']
else:
match = collect(expand(eq), df).match(a*df + b)
if match:
h = -simplify(match[b]/match[a])
else:
try:
sol = solve(eq, df)
except NotImplementedError:
raise NotImplementedError("Infinitesimals for the "
"first order ODE could not be found")
else:
h = sol[0] # Find infinitesimals for one solution
y = Dummy("y")
h = h.subs(func, y)
u = Dummy("u")
hx = h.diff(x)
hy = h.diff(y)
hinv = ((1/h).subs([(x, u), (y, x)])).subs(u, y) # Inverse ODE
match = {'h': h, 'func': func, 'hx': hx, 'hy': hy, 'y': y, 'hinv': hinv}
if hint == 'all':
xieta = []
for heuristic in lie_heuristics:
function = globals()['lie_heuristic_' + heuristic]
inflist = function(match, comp=True)
if inflist:
xieta.extend([inf for inf in inflist if inf not in xieta])
if xieta:
return xieta
else:
raise NotImplementedError("Infinitesimals could not be found for "
"the given ODE")
elif hint == 'default':
for heuristic in lie_heuristics:
function = globals()['lie_heuristic_' + heuristic]
xieta = function(match, comp=False)
if xieta:
return xieta
raise NotImplementedError("Infinitesimals could not be found for"
" the given ODE")
elif hint not in lie_heuristics:
raise ValueError("Heuristic not recognized: " + hint)
else:
function = globals()['lie_heuristic_' + hint]
xieta = function(match, comp=True)
if xieta:
return xieta
else:
raise ValueError("Infinitesimals could not be found using the"
" given heuristic")
def lie_heuristic_abaco1_simple(match, comp=False):
r"""
The first heuristic uses the following four sets of
assumptions on `\xi` and `\eta`
.. math:: \xi = 0, \eta = f(x)
.. math:: \xi = 0, \eta = f(y)
.. math:: \xi = f(x), \eta = 0
.. math:: \xi = f(y), \eta = 0
The success of this heuristic is determined by algebraic factorisation.
For the first assumption `\xi = 0` and `\eta` to be a function of `x`, the PDE
.. math:: \frac{\partial \eta}{\partial x} + (\frac{\partial \eta}{\partial y}
- \frac{\partial \xi}{\partial x})*h
- \frac{\partial \xi}{\partial y}*h^{2}
- \xi*\frac{\partial h}{\partial x} - \eta*\frac{\partial h}{\partial y} = 0
reduces to `f'(x) - f\frac{\partial h}{\partial y} = 0`
If `\frac{\partial h}{\partial y}` is a function of `x`, then this can usually
be integrated easily. A similar idea is applied to the other 3 assumptions as well.
References
==========
- E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
Solving of First Order ODEs Using Symmetry Methods, pp. 8
"""
xieta = []
y = match['y']
h = match['h']
func = match['func']
x = func.args[0]
hx = match['hx']
hy = match['hy']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
hysym = hy.free_symbols
if y not in hysym:
try:
fx = exp(integrate(hy, x))
except NotImplementedError:
pass
else:
inf = {xi: S.Zero, eta: fx}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = hy/h
facsym = factor.free_symbols
if x not in facsym:
try:
fy = exp(integrate(factor, y))
except NotImplementedError:
pass
else:
inf = {xi: S.Zero, eta: fy.subs(y, func)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = -hx/h
facsym = factor.free_symbols
if y not in facsym:
try:
fx = exp(integrate(factor, x))
except NotImplementedError:
pass
else:
inf = {xi: fx, eta: S.Zero}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = -hx/(h**2)
facsym = factor.free_symbols
if x not in facsym:
try:
fy = exp(integrate(factor, y))
except NotImplementedError:
pass
else:
inf = {xi: fy.subs(y, func), eta: S.Zero}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_abaco1_product(match, comp=False):
r"""
The second heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = 0, \xi = f(x)*g(y)
.. math:: \eta = f(x)*g(y), \xi = 0
The first assumption of this heuristic holds good if
`\frac{1}{h^{2}}\frac{\partial^2}{\partial x \partial y}\log(h)` is
separable in `x` and `y`, then the separated factors containing `x`
is `f(x)`, and `g(y)` is obtained by
.. math:: e^{\int f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)\,dy}
provided `f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)` is a function
of `y` only.
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
satisfies. After obtaining `f(x)` and `g(y)`, the coordinates are again
interchanged, to get `\eta` as `f(x)*g(y)`
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 7 - pp. 8
"""
xieta = []
y = match['y']
h = match['h']
hinv = match['hinv']
func = match['func']
x = func.args[0]
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
inf = separatevars(((log(h).diff(y)).diff(x))/h**2, dict=True, symbols=[x, y])
if inf and inf['coeff']:
fx = inf[x]
gy = simplify(fx*((1/(fx*h)).diff(x)))
gysyms = gy.free_symbols
if x not in gysyms:
gy = exp(integrate(gy, y))
inf = {eta: S.Zero, xi: (fx*gy).subs(y, func)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
u1 = Dummy("u1")
inf = separatevars(((log(hinv).diff(y)).diff(x))/hinv**2, dict=True, symbols=[x, y])
if inf and inf['coeff']:
fx = inf[x]
gy = simplify(fx*((1/(fx*hinv)).diff(x)))
gysyms = gy.free_symbols
if x not in gysyms:
gy = exp(integrate(gy, y))
etaval = fx*gy
etaval = (etaval.subs([(x, u1), (y, x)])).subs(u1, y)
inf = {eta: etaval.subs(y, func), xi: S.Zero}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_bivariate(match, comp=False):
r"""
The third heuristic assumes the infinitesimals `\xi` and `\eta`
to be bi-variate polynomials in `x` and `y`. The assumption made here
for the logic below is that `h` is a rational function in `x` and `y`
though that may not be necessary for the infinitesimals to be
bivariate polynomials. The coefficients of the infinitesimals
are found out by substituting them in the PDE and grouping similar terms
that are polynomials and since they form a linear system, solve and check
for non trivial solutions. The degree of the assumed bivariates
are increased till a certain maximum value.
References
==========
- Lie Groups and Differential Equations
pp. 327 - pp. 329
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
if h.is_rational_function():
# The maximum degree that the infinitesimals can take is
# calculated by this technique.
etax, etay, etad, xix, xiy, xid = symbols("etax etay etad xix xiy xid")
ipde = etax + (etay - xix)*h - xiy*h**2 - xid*hx - etad*hy
num, denom = cancel(ipde).as_numer_denom()
deg = Poly(num, x, y).total_degree()
deta = Function('deta')(x, y)
dxi = Function('dxi')(x, y)
ipde = (deta.diff(x) + (deta.diff(y) - dxi.diff(x))*h - (dxi.diff(y))*h**2
- dxi*hx - deta*hy)
xieq = Symbol("xi0")
etaeq = Symbol("eta0")
for i in range(deg + 1):
if i:
xieq += Add(*[
Symbol("xi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
etaeq += Add(*[
Symbol("eta_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
pden, denom = (ipde.subs({dxi: xieq, deta: etaeq}).doit()).as_numer_denom()
pden = expand(pden)
# If the individual terms are monomials, the coefficients
# are grouped
if pden.is_polynomial(x, y) and pden.is_Add:
polyy = Poly(pden, x, y).as_dict()
if polyy:
symset = xieq.free_symbols.union(etaeq.free_symbols) - {x, y}
soldict = solve(polyy.values(), *symset)
if isinstance(soldict, list):
soldict = soldict[0]
if any(soldict.values()):
xired = xieq.subs(soldict)
etared = etaeq.subs(soldict)
# Scaling is done by substituting one for the parameters
# This can be any number except zero.
dict_ = {sym: 1 for sym in symset}
inf = {eta: etared.subs(dict_).subs(y, func),
xi: xired.subs(dict_).subs(y, func)}
return [inf]
def lie_heuristic_chi(match, comp=False):
r"""
The aim of the fourth heuristic is to find the function `\chi(x, y)`
that satisfies the PDE `\frac{d\chi}{dx} + h\frac{d\chi}{dx}
- \frac{\partial h}{\partial y}\chi = 0`.
This assumes `\chi` to be a bivariate polynomial in `x` and `y`. By intuition,
`h` should be a rational function in `x` and `y`. The method used here is
to substitute a general binomial for `\chi` up to a certain maximum degree
is reached. The coefficients of the polynomials, are calculated by by collecting
terms of the same order in `x` and `y`.
After finding `\chi`, the next step is to use `\eta = \xi*h + \chi`, to
determine `\xi` and `\eta`. This can be done by dividing `\chi` by `h`
which would give `-\xi` as the quotient and `\eta` as the remainder.
References
==========
- E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
Solving of First Order ODEs Using Symmetry Methods, pp. 8
"""
h = match['h']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
if h.is_rational_function():
schi, schix, schiy = symbols("schi, schix, schiy")
cpde = schix + h*schiy - hy*schi
num, denom = cancel(cpde).as_numer_denom()
deg = Poly(num, x, y).total_degree()
chi = Function('chi')(x, y)
chix = chi.diff(x)
chiy = chi.diff(y)
cpde = chix + h*chiy - hy*chi
chieq = Symbol("chi")
for i in range(1, deg + 1):
chieq += Add(*[
Symbol("chi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
cnum, cden = cancel(cpde.subs({chi : chieq}).doit()).as_numer_denom()
cnum = expand(cnum)
if cnum.is_polynomial(x, y) and cnum.is_Add:
cpoly = Poly(cnum, x, y).as_dict()
if cpoly:
solsyms = chieq.free_symbols - {x, y}
soldict = solve(cpoly.values(), *solsyms)
if isinstance(soldict, list):
soldict = soldict[0]
if any(soldict.values()):
chieq = chieq.subs(soldict)
dict_ = {sym: 1 for sym in solsyms}
chieq = chieq.subs(dict_)
# After finding chi, the main aim is to find out
# eta, xi by the equation eta = xi*h + chi
# One method to set xi, would be rearranging it to
# (eta/h) - xi = (chi/h). This would mean dividing
# chi by h would give -xi as the quotient and eta
# as the remainder. Thanks to Sean Vig for suggesting
# this method.
xic, etac = div(chieq, h)
inf = {eta: etac.subs(y, func), xi: -xic.subs(y, func)}
return [inf]
def lie_heuristic_function_sum(match, comp=False):
r"""
This heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = 0, \xi = f(x) + g(y)
.. math:: \eta = f(x) + g(y), \xi = 0
The first assumption of this heuristic holds good if
.. math:: \frac{\partial}{\partial y}[(h\frac{\partial^{2}}{
\partial x^{2}}(h^{-1}))^{-1}]
is separable in `x` and `y`,
1. The separated factors containing `y` is `\frac{\partial g}{\partial y}`.
From this `g(y)` can be determined.
2. The separated factors containing `x` is `f''(x)`.
3. `h\frac{\partial^{2}}{\partial x^{2}}(h^{-1})` equals
`\frac{f''(x)}{f(x) + g(y)}`. From this `f(x)` can be determined.
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first
assumption satisfies. After obtaining `f(x)` and `g(y)`, the coordinates
are again interchanged, to get `\eta` as `f(x) + g(y)`.
For both assumptions, the constant factors are separated among `g(y)`
and `f''(x)`, such that `f''(x)` obtained from 3] is the same as that
obtained from 2]. If not possible, then this heuristic fails.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 7 - pp. 8
"""
xieta = []
h = match['h']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
for odefac in [h, hinv]:
factor = odefac*((1/odefac).diff(x, 2))
sep = separatevars((1/factor).diff(y), dict=True, symbols=[x, y])
if sep and sep['coeff'] and sep[x].has(x) and sep[y].has(y):
k = Dummy("k")
try:
gy = k*integrate(sep[y], y)
except NotImplementedError:
pass
else:
fdd = 1/(k*sep[x]*sep['coeff'])
fx = simplify(fdd/factor - gy)
check = simplify(fx.diff(x, 2) - fdd)
if fx:
if not check:
fx = fx.subs(k, 1)
gy = (gy/k)
else:
sol = solve(check, k)
if sol:
sol = sol[0]
fx = fx.subs(k, sol)
gy = (gy/k)*sol
else:
continue
if odefac == hinv: # Inverse ODE
fx = fx.subs(x, y)
gy = gy.subs(y, x)
etaval = factor_terms(fx + gy)
if etaval.is_Mul:
etaval = Mul(*[arg for arg in etaval.args if arg.has(x, y)])
if odefac == hinv: # Inverse ODE
inf = {eta: etaval.subs(y, func), xi : S.Zero}
else:
inf = {xi: etaval.subs(y, func), eta : S.Zero}
if not comp:
return [inf]
else:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_abaco2_similar(match, comp=False):
r"""
This heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = g(x), \xi = f(x)
.. math:: \eta = f(y), \xi = g(y)
For the first assumption,
1. First `\frac{\frac{\partial h}{\partial y}}{\frac{\partial^{2} h}{
\partial yy}}` is calculated. Let us say this value is A
2. If this is constant, then `h` is matched to the form `A(x) + B(x)e^{
\frac{y}{C}}` then, `\frac{e^{\int \frac{A(x)}{C} \,dx}}{B(x)}` gives `f(x)`
and `A(x)*f(x)` gives `g(x)`
3. Otherwise `\frac{\frac{\partial A}{\partial X}}{\frac{\partial A}{
\partial Y}} = \gamma` is calculated. If
a] `\gamma` is a function of `x` alone
b] `\frac{\gamma\frac{\partial h}{\partial y} - \gamma'(x) - \frac{
\partial h}{\partial x}}{h + \gamma} = G` is a function of `x` alone.
then, `e^{\int G \,dx}` gives `f(x)` and `-\gamma*f(x)` gives `g(x)`
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
satisfies. After obtaining `f(x)` and `g(x)`, the coordinates are again
interchanged, to get `\xi` as `f(x^*)` and `\eta` as `g(y^*)`
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
factor = cancel(h.diff(y)/h.diff(y, 2))
factorx = factor.diff(x)
factory = factor.diff(y)
if not factor.has(x) and not factor.has(y):
A = Wild('A', exclude=[y])
B = Wild('B', exclude=[y])
C = Wild('C', exclude=[x, y])
match = h.match(A + B*exp(y/C))
try:
tau = exp(-integrate(match[A]/match[C]), x)/match[B]
except NotImplementedError:
pass
else:
gx = match[A]*tau
return [{xi: tau, eta: gx}]
else:
gamma = cancel(factorx/factory)
if not gamma.has(y):
tauint = cancel((gamma*hy - gamma.diff(x) - hx)/(h + gamma))
if not tauint.has(y):
try:
tau = exp(integrate(tauint, x))
except NotImplementedError:
pass
else:
gx = -tau*gamma
return [{xi: tau, eta: gx}]
factor = cancel(hinv.diff(y)/hinv.diff(y, 2))
factorx = factor.diff(x)
factory = factor.diff(y)
if not factor.has(x) and not factor.has(y):
A = Wild('A', exclude=[y])
B = Wild('B', exclude=[y])
C = Wild('C', exclude=[x, y])
match = h.match(A + B*exp(y/C))
try:
tau = exp(-integrate(match[A]/match[C]), x)/match[B]
except NotImplementedError:
pass
else:
gx = match[A]*tau
return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
else:
gamma = cancel(factorx/factory)
if not gamma.has(y):
tauint = cancel((gamma*hinv.diff(y) - gamma.diff(x) - hinv.diff(x))/(
hinv + gamma))
if not tauint.has(y):
try:
tau = exp(integrate(tauint, x))
except NotImplementedError:
pass
else:
gx = -tau*gamma
return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
def lie_heuristic_abaco2_unique_unknown(match, comp=False):
r"""
This heuristic assumes the presence of unknown functions or known functions
with non-integer powers.
1. A list of all functions and non-integer powers containing x and y
2. Loop over each element `f` in the list, find `\frac{\frac{\partial f}{\partial x}}{
\frac{\partial f}{\partial x}} = R`
If it is separable in `x` and `y`, let `X` be the factors containing `x`. Then
a] Check if `\xi = X` and `\eta = -\frac{X}{R}` satisfy the PDE. If yes, then return
`\xi` and `\eta`
b] Check if `\xi = \frac{-R}{X}` and `\eta = -\frac{1}{X}` satisfy the PDE.
If yes, then return `\xi` and `\eta`
If not, then check if
a] :math:`\xi = -R,\eta = 1`
b] :math:`\xi = 1, \eta = -\frac{1}{R}`
are solutions.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
funclist = []
for atom in h.atoms(Pow):
base, exp = atom.as_base_exp()
if base.has(x) and base.has(y):
if not exp.is_Integer:
funclist.append(atom)
for function in h.atoms(AppliedUndef):
syms = function.free_symbols
if x in syms and y in syms:
funclist.append(function)
for f in funclist:
frac = cancel(f.diff(y)/f.diff(x))
sep = separatevars(frac, dict=True, symbols=[x, y])
if sep and sep['coeff']:
xitry1 = sep[x]
etatry1 = -1/(sep[y]*sep['coeff'])
pde1 = etatry1.diff(y)*h - xitry1.diff(x)*h - xitry1*hx - etatry1*hy
if not simplify(pde1):
return [{xi: xitry1, eta: etatry1.subs(y, func)}]
xitry2 = 1/etatry1
etatry2 = 1/xitry1
pde2 = etatry2.diff(x) - (xitry2.diff(y))*h**2 - xitry2*hx - etatry2*hy
if not simplify(expand(pde2)):
return [{xi: xitry2.subs(y, func), eta: etatry2}]
else:
etatry = -1/frac
pde = etatry.diff(x) + etatry.diff(y)*h - hx - etatry*hy
if not simplify(pde):
return [{xi: S.One, eta: etatry.subs(y, func)}]
xitry = -frac
pde = -xitry.diff(x)*h -xitry.diff(y)*h**2 - xitry*hx -hy
if not simplify(expand(pde)):
return [{xi: xitry.subs(y, func), eta: S.One}]
def lie_heuristic_abaco2_unique_general(match, comp=False):
r"""
This heuristic finds if infinitesimals of the form `\eta = f(x)`, `\xi = g(y)`
without making any assumptions on `h`.
The complete sequence of steps is given in the paper mentioned below.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
A = hx.diff(y)
B = hy.diff(y) + hy**2
C = hx.diff(x) - hx**2
if not (A and B and C):
return
Ax = A.diff(x)
Ay = A.diff(y)
Axy = Ax.diff(y)
Axx = Ax.diff(x)
Ayy = Ay.diff(y)
D = simplify(2*Axy + hx*Ay - Ax*hy + (hx*hy + 2*A)*A)*A - 3*Ax*Ay
if not D:
E1 = simplify(3*Ax**2 + ((hx**2 + 2*C)*A - 2*Axx)*A)
if E1:
E2 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
if not E2:
E3 = simplify(
E1*((28*Ax + 4*hx*A)*A**3 - E1*(hy*A + Ay)) - E1.diff(x)*8*A**4)
if not E3:
etaval = cancel((4*A**3*(Ax - hx*A) + E1*(hy*A - Ay))/(S(2)*A*E1))
if x not in etaval:
try:
etaval = exp(integrate(etaval, y))
except NotImplementedError:
pass
else:
xival = -4*A**3*etaval/E1
if y not in xival:
return [{xi: xival, eta: etaval.subs(y, func)}]
else:
E1 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
if E1:
E2 = simplify(
4*A**3*D - D**2 + E1*((2*Axx - (hx**2 + 2*C)*A)*A - 3*Ax**2))
if not E2:
E3 = simplify(
-(A*D)*E1.diff(y) + ((E1.diff(x) - hy*D)*A + 3*Ay*D +
(A*hx - 3*Ax)*E1)*E1)
if not E3:
etaval = cancel(((A*hx - Ax)*E1 - (Ay + A*hy)*D)/(S(2)*A*D))
if x not in etaval:
try:
etaval = exp(integrate(etaval, y))
except NotImplementedError:
pass
else:
xival = -E1*etaval/D
if y not in xival:
return [{xi: xival, eta: etaval.subs(y, func)}]
def lie_heuristic_linear(match, comp=False):
r"""
This heuristic assumes
1. `\xi = ax + by + c` and
2. `\eta = fx + gy + h`
After substituting the following assumptions in the determining PDE, it
reduces to
.. math:: f + (g - a)h - bh^{2} - (ax + by + c)\frac{\partial h}{\partial x}
- (fx + gy + c)\frac{\partial h}{\partial y}
Solving the reduced PDE obtained, using the method of characteristics, becomes
impractical. The method followed is grouping similar terms and solving the system
of linear equations obtained. The difference between the bivariate heuristic is that
`h` need not be a rational function in this case.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
coeffdict = {}
symbols = numbered_symbols("c", cls=Dummy)
symlist = [next(symbols) for _ in islice(symbols, 6)]
C0, C1, C2, C3, C4, C5 = symlist
pde = C3 + (C4 - C0)*h - (C0*x + C1*y + C2)*hx - (C3*x + C4*y + C5)*hy - C1*h**2
pde, denom = pde.as_numer_denom()
pde = powsimp(expand(pde))
if pde.is_Add:
terms = pde.args
for term in terms:
if term.is_Mul:
rem = Mul(*[m for m in term.args if not m.has(x, y)])
xypart = term/rem
if xypart not in coeffdict:
coeffdict[xypart] = rem
else:
coeffdict[xypart] += rem
else:
if term not in coeffdict:
coeffdict[term] = S.One
else:
coeffdict[term] += S.One
sollist = coeffdict.values()
soldict = solve(sollist, symlist)
if soldict:
if isinstance(soldict, list):
soldict = soldict[0]
subval = soldict.values()
if any(t for t in subval):
onedict = dict(zip(symlist, [1]*6))
xival = C0*x + C1*func + C2
etaval = C3*x + C4*func + C5
xival = xival.subs(soldict)
etaval = etaval.subs(soldict)
xival = xival.subs(onedict)
etaval = etaval.subs(onedict)
return [{xi: xival, eta: etaval}]
def sysode_linear_2eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
r = dict()
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
# for equations Eq(a1*diff(x(t),t), a*x(t) + b*y(t) + k1)
# and Eq(a2*diff(x(t),t), c*x(t) + d*y(t) + k2)
r['a'] = -fc[0,x(t),0]/fc[0,x(t),1]
r['c'] = -fc[1,x(t),0]/fc[1,y(t),1]
r['b'] = -fc[0,y(t),0]/fc[0,x(t),1]
r['d'] = -fc[1,y(t),0]/fc[1,y(t),1]
forcing = [S.Zero,S.Zero]
for i in range(2):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t)):
forcing[i] += j
if not (forcing[0].has(t) or forcing[1].has(t)):
r['k1'] = forcing[0]
r['k2'] = forcing[1]
else:
raise NotImplementedError("Only homogeneous problems are supported" +
" (and constant inhomogeneity)")
if match_['type_of_equation'] == '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 (NthAlgebraic, Factorable, FirstLinear, AlmostLinear,
Bernoulli, SingleODEProblem, SingleODESolver, RiccatiSpecial,
SecondNonlinearAutonomousConserved, FirstExact, Liouville, Separable, SeparableReduced)
|
818cd04d8bcbadc09b61cc95d9209fcb97e6e45b45926f33a196c762c33181c6 | #
# This is the module for ODE solver classes for single ODEs.
#
import typing
if typing.TYPE_CHECKING:
from typing import ClassVar
from typing import Dict, Type
from typing import Iterator, List, Optional
from sympy.core import Add, S, Pow
from sympy.core.exprtools import factor_terms
from sympy.core.expr import Expr
from sympy.core.function import AppliedUndef, Derivative, Function, expand, Subs
from sympy.core.numbers import Float, 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, sqrt, tan, log
from sympy.integrals import Integral
from sympy.polys.polytools import cancel, factor
from sympy.simplify import simplify, separatevars
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
class ODEMatchError(NotImplementedError):
"""Raised if a SingleODESolver is asked to solve an ODE it does not match"""
pass
def cached_property(func):
'''Decorator to cache property method'''
attrname = '_' + func.__name__
def propfunc(self):
val = getattr(self, attrname, None)
if val is None:
val = func(self)
setattr(self, attrname, val)
return val
return property(propfunc)
class SingleODEProblem:
"""Represents an ordinary differential equation (ODE)
This class is used internally in the by dsolve and related
functions/classes so that properties of an ODE can be computed
efficiently.
Examples
========
This class is used internally by dsolve. To instantiate an instance
directly first define an ODE problem:
>>> from sympy import Function, Symbol
>>> x = Symbol('x')
>>> f = Function('f')
>>> eq = f(x).diff(x, 2)
Now you can create a SingleODEProblem instance and query its properties:
>>> from sympy.solvers.ode.single import SingleODEProblem
>>> problem = SingleODEProblem(f(x).diff(x), f(x), x)
>>> problem.eq
Derivative(f(x), x)
>>> problem.func
f(x)
>>> problem.sym
x
"""
# Instance attributes:
eq = None # type: Expr
func = None # type: AppliedUndef
sym = None # type: Symbol
_order = None # type: int
_eq_expanded = None # type: Expr
_eq_preprocessed = None # type: Expr
def __init__(self, eq, func, sym, prep=True):
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
@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_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
# TODO: Add methods that can be used by many ODE solvers:
# order
# is_linear()
# get_linear_coefficients()
# eq_prepared (the ODE in prepared form)
class SingleODESolver:
"""
Base class for Single ODE solvers.
Subclasses should implement the _matches and _get_general_solution
methods. This class is not intended to be instantiated directly but its
subclasses are as part of dsolve.
Examples
========
You can use a subclass of SingleODEProblem to solve a particular type of
ODE. We first define a particular ODE problem:
>>> from sympy import Function, Symbol
>>> x = Symbol('x')
>>> f = Function('f')
>>> eq = f(x).diff(x, 2)
Now we solve this problem using the NthAlgebraic solver which is a
subclass of SingleODESolver:
>>> from sympy.solvers.ode.single import NthAlgebraic, SingleODEProblem
>>> problem = SingleODEProblem(eq, f(x), x)
>>> solver = NthAlgebraic(problem)
>>> solver.get_general_solution()
[Eq(f(x), _C*x + _C)]
The normal way to solve an ODE is to use dsolve (which would use
NthAlgebraic and other solvers internally). When using dsolve a number of
other things are done such as evaluating integrals, simplifying the
solution and renumbering the constants:
>>> from sympy import dsolve
>>> dsolve(eq, hint='nth_algebraic')
Eq(f(x), C1 + C2*x)
"""
# Subclasses should store the hint name (the argument to dsolve) in this
# attribute
hint = None # type: ClassVar[str]
# Subclasses should define this to indicate if they support an _Integral
# hint.
has_integral = None # type: ClassVar[bool]
# The ODE to be solved
ode_problem = None # type: SingleODEProblem
# Cache whether or not the equation has matched the method
_matched = None # type: Optional[bool]
# Subclasses should store in this attribute the list of order(s) of ODE
# that subclass can solve or leave it to None if not specific to any order
order = None # type: Optional[list]
def __init__(self, ode_problem):
self.ode_problem = ode_problem
def matches(self) -> bool:
if self.order is not None and self.ode_problem.order not in self.order:
self._matched = False
return self._matched
if self._matched is None:
self._matched = self._matches()
return self._matched
def get_general_solution(self, *, simplify: bool = True) -> List[Equality]:
if not self.matches():
msg = "%s solver can not solve:\n%s"
raise ODEMatchError(msg % (self.hint, self.ode_problem.eq))
return self._get_general_solution()
def _matches(self) -> bool:
msg = "Subclasses of SingleODESolver should implement matches."
raise NotImplementedError(msg)
def _get_general_solution(self, *, simplify: 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: bool = True):
return self.solutions
# This needs to produce an invertible function but the inverse depends
# which variable we are integrating with respect to. Since the class can
# be stored in cached results we need to ensure that we always get the
# same class back for each particular integration variable so we store these
# classes in a global dict:
_diffx_stored = {} # type: 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: bool = True):
m, n = self.wilds_match()
fx = self.ode_problem.func
x = self.ode_problem.sym
(C1,) = self.ode_problem.get_numbered_constants(num=1)
y = Dummy('y')
m = m.subs(fx, y)
n = n.subs(fx, y)
gen_sol = Eq(Subs(Integral(m, x)
+ Integral(n - Integral(m, x).diff(y), y), y, fx), C1)
return [gen_sol]
class FirstLinear(SinglePatternODESolver):
r"""
Solves 1st order linear differential equations.
These are differential equations of the form
.. math:: dy/dx + P(x) y = Q(x)\text{.}
These kinds of differential equations can be solved in a general way. The
integrating factor `e^{\int P(x) \,dx}` will turn the equation into a
separable equation. The general solution is::
>>> from sympy import Function, dsolve, Eq, pprint, diff, sin
>>> from sympy.abc import x
>>> f, P, Q = map(Function, ['f', 'P', 'Q'])
>>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x))
>>> pprint(genform)
d
P(x)*f(x) + --(f(x)) = Q(x)
dx
>>> pprint(dsolve(genform, f(x), hint='1st_linear_Integral'))
/ / \
| | |
| | / | /
| | | | |
| | | P(x) dx | - | P(x) dx
| | | | |
| | / | /
f(x) = |C1 + | Q(x)*e dx|*e
| | |
\ / /
Examples
========
>>> f = Function('f')
>>> pprint(dsolve(Eq(x*diff(f(x), x) - f(x), x**2*sin(x)),
... f(x), '1st_linear'))
f(x) = x*(C1 - cos(x))
References
==========
- https://en.wikipedia.org/wiki/Linear_differential_equation#First_order_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 92
# indirect doctest
"""
hint = '1st_linear'
has_integral = True
order = [1]
def _wilds(self, f, x, order):
P = Wild('P', exclude=[f(x)])
Q = Wild('Q', exclude=[f(x), f(x).diff(x)])
return P, Q
def _equation(self, fx, x, order):
P, Q = self.wilds()
return fx.diff(x) + P*fx - Q
def _get_general_solution(self, *, simplify: 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
========
:meth:`sympy.solvers.ode.single.FirstLinear`
Examples
========
>>> from sympy import Function, pprint, sin, cos
>>> from sympy.solvers.ode import dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> d = f(x).diff(x)
>>> eq = x*d + x*f(x) + 1
>>> dsolve(eq, f(x), hint='almost_linear')
Eq(f(x), (C1 - Ei(x))*exp(-x))
>>> pprint(dsolve(eq, f(x), hint='almost_linear'))
-x
f(x) = (C1 - Ei(x))*e
>>> example = cos(f(x))*f(x).diff(x) + sin(f(x)) + 1
>>> pprint(example)
d
sin(f(x)) + cos(f(x))*--(f(x)) + 1
dx
>>> pprint(dsolve(example, f(x), hint='almost_linear'))
/ -x \ / -x \
[f(x) = pi - asin\C1*e - 1/, f(x) = asin\C1*e - 1/]
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
hint = "almost_linear"
has_integral = True
order = [1]
def _wilds(self, f, x, order):
P = Wild('P', exclude=[f(x).diff(x)])
Q = Wild('Q', exclude=[f(x).diff(x)])
return P, Q
def _equation(self, fx, x, order):
P, Q = self.wilds()
return P*fx.diff(x) + Q
def _verify(self, fx):
a, b = self.wilds_match()
c, b = b.as_independent(fx) if b.is_Add else (S.Zero, b)
# a, b and c are the function a(x), b(x) and c(x) respectively.
# c(x) is obtained by separating out b as terms with and without fx i.e, l(y)
# The following conditions checks if the given equation is an almost-linear differential equation using the fact that
# a(x)*(l(y))' / l(y)' is independent of l(y)
if b.diff(fx) != 0 and not simplify(b.diff(fx)/a).has(fx):
self.ly = factor_terms(b).as_independent(fx, as_Add=False)[1] # Gives the term containing fx i.e., l(y)
self.ax = a / self.ly.diff(fx)
self.cx = -c # cx is taken as -c(x) to simplify expression in the solution integral
self.bx = factor_terms(b) / self.ly
return True
return False
def _get_general_solution(self, *, simplify: 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
:py:meth:`~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
// / / \ \
|| | | | |
|| | / | / | / |
|| | | | | | | |
|| | (1 - n)* | P(x) dx | (1 - n)* | 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
:py:meth:`~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: 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 = self.ode_problem.eq
f = self.ode_problem.func.func
x = self.ode_problem.sym
order =self.ode_problem.order
df = f(x).diff(x)
self.eqs = []
eq = eq.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]
if len(self.eqs)==1:
if order>1:
return False
if self.eqs[0].has(Float):
return False
return fraction(factor(self.eqs[0]))[0]-eq!=0
return True
return False
def _get_general_solution(self, *, simplify: bool = True):
func = self.ode_problem.func.func
x = self.ode_problem.sym
eqns = self.eqs
sols = []
for eq in eqns:
try:
sol = dsolve(eq, func(x))
except NotImplementedError:
continue
else:
if isinstance(sol, list):
sols.extend(sol)
else:
sols.append(sol)
if sols == []:
raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by"
+ " the factorable group method")
return sols
class RiccatiSpecial(SinglePatternODESolver):
r"""
The general Riccati equation has the form
.. math:: dy/dx = f(x) y^2 + g(x) y + h(x)\text{.}
While it does not have a general solution [1], the "special" form, `dy/dx
= a y^2 - b x^c`, does have solutions in many cases [2]. This routine
returns a solution for `a(dy/dx) = b y^2 + c y/x + d/x^2` that is obtained
by using a suitable change of variables to reduce it to the special form
and is valid when neither `a` nor `b` are zero and either `c` or `d` is
zero.
>>> from sympy.abc import x, a, b, c, d
>>> from sympy.solvers.ode import dsolve, checkodesol
>>> from sympy import pprint, Function
>>> f = Function('f')
>>> y = f(x)
>>> genform = a*y.diff(x) - (b*y**2 + c*y/x + d/x**2)
>>> sol = dsolve(genform, y)
>>> pprint(sol, wrap_line=False)
/ / __________________ \\
| __________________ | / 2 ||
| / 2 | \/ 4*b*d - (a + c) *log(x)||
-|a + c - \/ 4*b*d - (a + c) *tan|C1 + ----------------------------||
\ \ 2*a //
f(x) = ------------------------------------------------------------------------
2*b*x
>>> checkodesol(genform, sol, order=1)[0]
True
References
==========
1. http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Riccati
2. http://eqworld.ipmnet.ru/en/solutions/ode/ode0106.pdf -
http://eqworld.ipmnet.ru/en/solutions/ode/ode0123.pdf
"""
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: 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 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: 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: 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: 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
========
:meth:`sympy.solvers.ode.single.Separable`
Examples
========
>>> from sympy import Function, pprint
>>> from sympy.solvers.ode.ode import dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> d = f(x).diff(x)
>>> eq = (x - x**2*f(x))*d - f(x)
>>> dsolve(eq, hint='separable_reduced')
[Eq(f(x), (1 - sqrt(C1*x**2 + 1))/x), Eq(f(x), (sqrt(C1*x**2 + 1) + 1)/x)]
>>> pprint(dsolve(eq, hint='separable_reduced'))
___________ ___________
/ 2 / 2
1 - \/ C1*x + 1 \/ C1*x + 1 + 1
[f(x) = ------------------, f(x) = ------------------]
x x
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
hint = "separable_reduced"
has_integral = True
order = [1]
def _degree(self, expr, x):
# Made this function to calculate the degree of
# x in an expression. If expr will be of form
# x**p*y, (wheare p can be variables/rationals) then it
# will return p.
for val in expr:
if val.has(x):
if isinstance(val, Pow) and val.as_base_exp()[0] == x:
return (val.as_base_exp()[1])
elif val == x:
return (val.as_base_exp()[1])
else:
return self._degree(val.args, x)
return 0
def _powers(self, expr):
# this function will return all the different relative power of x w.r.t f(x).
# expr = x**p * f(x)**q then it will return {p/q}.
pows = set()
fx = self.ode_problem.func
x = self.ode_problem.sym
self.y = Dummy('y')
if isinstance(expr, Add):
exprs = expr.atoms(Add)
elif isinstance(expr, Mul):
exprs = expr.atoms(Mul)
elif isinstance(expr, Pow):
exprs = expr.atoms(Pow)
else:
exprs = {expr}
for arg in exprs:
if arg.has(x):
_, u = arg.as_independent(x, fx)
pow = self._degree((u.subs(fx, self.y), ), x)/self._degree((u.subs(fx, self.y), ), self.y)
pows.add(pow)
return pows
def _verify(self, fx):
num, den = self.wilds_match()
x = self.ode_problem.sym
factor = simplify(x/fx*num/den)
# Try representing factor in terms of x^n*y
# where n is lowest power of x in factor;
# first remove terms like sqrt(2)*3 from factor.atoms(Mul)
num, dem = factor.as_numer_denom()
num = expand(num)
dem = expand(dem)
pows = self._powers(num)
pows.update(self._powers(dem))
pows = list(pows)
if(len(pows)==1) and pows[0]!=zoo:
self.t = Dummy('t')
self.r2 = {'t': self.t}
num = num.subs(x**pows[0]*fx, self.t)
dem = dem.subs(x**pows[0]*fx, self.t)
test = num/dem
free = test.free_symbols
if len(free) == 1 and free.pop() == self.t:
self.r2.update({'power' : pows[0], 'u' : test})
return True
return False
return False
def _get_match_object(self):
fx = self.ode_problem.func
x = self.ode_problem.sym
u = self.r2['u'].subs(self.r2['t'], self.y)
ycoeff = 1/(self.y*(self.r2['power'] - u))
m1 = {self.y: 1, x: -1/x, 'coeff': 1}
m2 = {self.y: ycoeff, x: 1, 'coeff': 1}
return m1, m2, x, x**self.r2['power']*fx
# Avoid circular import:
from .ode import dsolve
|
6d19fb0e1ed7032885d6a28c49bcd6ca6ef4c9a7a38dcaa049535ae3b2839c98 | from sympy import (Add, Matrix, Mul, S, symbols, Eq, pi, factorint, oo,
powsimp, Rational)
from sympy.core.function import _mexpand
from sympy.core.compatibility import ordered
from sympy.functions.elementary.trigonometric import sin
from sympy.solvers.diophantine import diophantine
from sympy.solvers.diophantine.diophantine import (diop_DN,
diop_solve, diop_ternary_quadratic_normal,
diop_general_pythagorean, diop_ternary_quadratic, diop_linear,
diop_quadratic, diop_general_sum_of_squares, diop_general_sum_of_even_powers,
descent, diop_bf_DN, divisible, equivalent, find_DN, ldescent, length,
reconstruct, partition, power_representation,
prime_as_sum_of_two_squares, square_factor, sum_of_four_squares,
sum_of_three_squares, transformation_to_DN, transformation_to_normal,
classify_diop, base_solution_linear, cornacchia, sqf_normal, gaussian_reduce, holzer,
check_param, parametrize_ternary_quadratic, sum_of_powers, sum_of_squares,
_diop_ternary_quadratic_normal, _nint_or_floor,
_odd, _even, _remove_gcd, _can_do_sum_of_squares, DiophantineSolutionSet, GeneralPythagorean,
BinaryQuadratic)
from sympy.utilities import default_sort_key
from sympy.testing.pytest import slow, raises, XFAIL
from sympy.utilities.iterables import (
signed_permutations)
a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z = symbols(
"a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z", integer=True)
t_0, t_1, t_2, t_3, t_4, t_5, t_6 = symbols("t_:7", integer=True)
m1, m2, m3 = symbols('m1:4', integer=True)
n1 = symbols('n1', integer=True)
def diop_simplify(eq):
return _mexpand(powsimp(_mexpand(eq)))
def test_input_format():
raises(TypeError, lambda: diophantine(sin(x)))
raises(TypeError, lambda: diophantine(x/pi - 3))
def test_nosols():
# diophantine should sympify eq so that these are equivalent
assert diophantine(3) == set()
assert diophantine(S(3)) == set()
def test_univariate():
assert diop_solve((x - 1)*(x - 2)**2) == {(1,), (2,)}
assert diop_solve((x - 1)*(x - 2)) == {(1,), (2,)}
def test_classify_diop():
raises(TypeError, lambda: classify_diop(x**2/3 - 1))
raises(ValueError, lambda: classify_diop(1))
raises(NotImplementedError, lambda: classify_diop(w*x*y*z - 1))
raises(NotImplementedError, lambda: classify_diop(x**3 + y**3 + z**4 - 90))
assert classify_diop(14*x**2 + 15*x - 42) == (
[x], {1: -42, x: 15, x**2: 14}, 'univariate')
assert classify_diop(x*y + z) == (
[x, y, z], {x*y: 1, z: 1}, 'inhomogeneous_ternary_quadratic')
assert classify_diop(x*y + z + w + x**2) == (
[w, x, y, z], {x*y: 1, w: 1, x**2: 1, z: 1}, 'inhomogeneous_general_quadratic')
assert classify_diop(x*y + x*z + x**2 + 1) == (
[x, y, z], {x*y: 1, x*z: 1, x**2: 1, 1: 1}, 'inhomogeneous_general_quadratic')
assert classify_diop(x*y + z + w + 42) == (
[w, x, y, z], {x*y: 1, w: 1, 1: 42, z: 1}, 'inhomogeneous_general_quadratic')
assert classify_diop(x*y + z*w) == (
[w, x, y, z], {x*y: 1, w*z: 1}, 'homogeneous_general_quadratic')
assert classify_diop(x*y**2 + 1) == (
[x, y], {x*y**2: 1, 1: 1}, 'cubic_thue')
assert classify_diop(x**4 + y**4 + z**4 - (1 + 16 + 81)) == (
[x, y, z], {1: -98, x**4: 1, z**4: 1, y**4: 1}, 'general_sum_of_even_powers')
assert classify_diop(x**2 + y**2 + z**2) == (
[x, y, z], {x**2: 1, y**2: 1, z**2: 1}, 'homogeneous_ternary_quadratic_normal')
def test_linear():
assert diop_solve(x) == (0,)
assert diop_solve(1*x) == (0,)
assert diop_solve(3*x) == (0,)
assert diop_solve(x + 1) == (-1,)
assert diop_solve(2*x + 1) == (None,)
assert diop_solve(2*x + 4) == (-2,)
assert diop_solve(y + x) == (t_0, -t_0)
assert diop_solve(y + x + 0) == (t_0, -t_0)
assert diop_solve(y + x - 0) == (t_0, -t_0)
assert diop_solve(0*x - y - 5) == (-5,)
assert diop_solve(3*y + 2*x - 5) == (3*t_0 - 5, -2*t_0 + 5)
assert diop_solve(2*x - 3*y - 5) == (3*t_0 - 5, 2*t_0 - 5)
assert diop_solve(-2*x - 3*y - 5) == (3*t_0 + 5, -2*t_0 - 5)
assert diop_solve(7*x + 5*y) == (5*t_0, -7*t_0)
assert diop_solve(2*x + 4*y) == (2*t_0, -t_0)
assert diop_solve(4*x + 6*y - 4) == (3*t_0 - 2, -2*t_0 + 2)
assert diop_solve(4*x + 6*y - 3) == (None, None)
assert diop_solve(0*x + 3*y - 4*z + 5) == (4*t_0 + 5, 3*t_0 + 5)
assert diop_solve(4*x + 3*y - 4*z + 5) == (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5)
assert diop_solve(4*x + 3*y - 4*z + 5, None) == (0, 5, 5)
assert diop_solve(4*x + 2*y + 8*z - 5) == (None, None, None)
assert diop_solve(5*x + 7*y - 2*z - 6) == (t_0, -3*t_0 + 2*t_1 + 6, -8*t_0 + 7*t_1 + 18)
assert diop_solve(3*x - 6*y + 12*z - 9) == (2*t_0 + 3, t_0 + 2*t_1, t_1)
assert diop_solve(6*w + 9*x + 20*y - z) == (t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 20*t_2)
# to ignore constant factors, use diophantine
raises(TypeError, lambda: diop_solve(x/2))
def test_quadratic_simple_hyperbolic_case():
# Simple Hyperbolic case: A = C = 0 and B != 0
assert diop_solve(3*x*y + 34*x - 12*y + 1) == \
{(-133, -11), (5, -57)}
assert diop_solve(6*x*y + 2*x + 3*y + 1) == set()
assert diop_solve(-13*x*y + 2*x - 4*y - 54) == {(27, 0)}
assert diop_solve(-27*x*y - 30*x - 12*y - 54) == {(-14, -1)}
assert diop_solve(2*x*y + 5*x + 56*y + 7) == {(-161, -3), (-47, -6), (-35, -12),
(-29, -69), (-27, 64), (-21, 7),
(-9, 1), (105, -2)}
assert diop_solve(6*x*y + 9*x + 2*y + 3) == set()
assert diop_solve(x*y + x + y + 1) == {(-1, t), (t, -1)}
assert diophantine(48*x*y)
def test_quadratic_elliptical_case():
# Elliptical case: B**2 - 4AC < 0
assert diop_solve(42*x**2 + 8*x*y + 15*y**2 + 23*x + 17*y - 4915) == {(-11, -1)}
assert diop_solve(4*x**2 + 3*y**2 + 5*x - 11*y + 12) == set()
assert diop_solve(x**2 + y**2 + 2*x + 2*y + 2) == {(-1, -1)}
assert diop_solve(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950) == {(-15, 6)}
assert diop_solve(10*x**2 + 12*x*y + 12*y**2 - 34) == \
{(-1, -1), (-1, 2), (1, -2), (1, 1)}
def test_quadratic_parabolic_case():
# Parabolic case: B**2 - 4AC = 0
assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 5*x + 7*y + 16)
assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 6*x + 12*y - 6)
assert check_solutions(8*x**2 + 24*x*y + 18*y**2 + 4*x + 6*y - 7)
assert check_solutions(-4*x**2 + 4*x*y - y**2 + 2*x - 3)
assert check_solutions(x**2 + 2*x*y + y**2 + 2*x + 2*y + 1)
assert check_solutions(x**2 - 2*x*y + y**2 + 2*x + 2*y + 1)
assert check_solutions(y**2 - 41*x + 40)
def test_quadratic_perfect_square():
# B**2 - 4*A*C > 0
# B**2 - 4*A*C is a perfect square
assert check_solutions(48*x*y)
assert check_solutions(4*x**2 - 5*x*y + y**2 + 2)
assert check_solutions(-2*x**2 - 3*x*y + 2*y**2 -2*x - 17*y + 25)
assert check_solutions(12*x**2 + 13*x*y + 3*y**2 - 2*x + 3*y - 12)
assert check_solutions(8*x**2 + 10*x*y + 2*y**2 - 32*x - 13*y - 23)
assert check_solutions(4*x**2 - 4*x*y - 3*y- 8*x - 3)
assert check_solutions(- 4*x*y - 4*y**2 - 3*y- 5*x - 10)
assert check_solutions(x**2 - y**2 - 2*x - 2*y)
assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y)
assert check_solutions(4*x**2 - 9*y**2 - 4*x - 12*y - 3)
def test_quadratic_non_perfect_square():
# B**2 - 4*A*C is not a perfect square
# Used check_solutions() since the solutions are complex expressions involving
# square roots and exponents
assert check_solutions(x**2 - 2*x - 5*y**2)
assert check_solutions(3*x**2 - 2*y**2 - 2*x - 2*y)
assert check_solutions(x**2 - x*y - y**2 - 3*y)
assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y)
assert BinaryQuadratic(x**2 + y**2 + 2*x + 2*y + 2).solve() == {(-1, -1)}
def test_issue_9106():
eq = -48 - 2*x*(3*x - 1) + y*(3*y - 1)
v = (x, y)
for sol in diophantine(eq):
assert not diop_simplify(eq.xreplace(dict(zip(v, sol))))
def test_issue_18138():
eq = x**2 - x - y**2
v = (x, y)
for sol in diophantine(eq):
assert not diop_simplify(eq.xreplace(dict(zip(v, sol))))
@slow
def test_quadratic_non_perfect_slow():
assert check_solutions(8*x**2 + 10*x*y - 2*y**2 - 32*x - 13*y - 23)
# This leads to very large numbers.
# assert check_solutions(5*x**2 - 13*x*y + y**2 - 4*x - 4*y - 15)
assert check_solutions(-3*x**2 - 2*x*y + 7*y**2 - 5*x - 7)
assert check_solutions(-4 - x + 4*x**2 - y - 3*x*y - 4*y**2)
assert check_solutions(1 + 2*x + 2*x**2 + 2*y + x*y - 2*y**2)
def test_DN():
# Most of the test cases were adapted from,
# Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004.
# https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
# others are verified using Wolfram Alpha.
# Covers cases where D <= 0 or D > 0 and D is a square or N = 0
# Solutions are straightforward in these cases.
assert diop_DN(3, 0) == [(0, 0)]
assert diop_DN(-17, -5) == []
assert diop_DN(-19, 23) == [(2, 1)]
assert diop_DN(-13, 17) == [(2, 1)]
assert diop_DN(-15, 13) == []
assert diop_DN(0, 5) == []
assert diop_DN(0, 9) == [(3, t)]
assert diop_DN(9, 0) == [(3*t, t)]
assert diop_DN(16, 24) == []
assert diop_DN(9, 180) == [(18, 4)]
assert diop_DN(9, -180) == [(12, 6)]
assert diop_DN(7, 0) == [(0, 0)]
# When equation is x**2 + y**2 = N
# Solutions are interchangeable
assert diop_DN(-1, 5) == [(2, 1), (1, 2)]
assert diop_DN(-1, 169) == [(12, 5), (5, 12), (13, 0), (0, 13)]
# D > 0 and D is not a square
# N = 1
assert diop_DN(13, 1) == [(649, 180)]
assert diop_DN(980, 1) == [(51841, 1656)]
assert diop_DN(981, 1) == [(158070671986249, 5046808151700)]
assert diop_DN(986, 1) == [(49299, 1570)]
assert diop_DN(991, 1) == [(379516400906811930638014896080, 12055735790331359447442538767)]
assert diop_DN(17, 1) == [(33, 8)]
assert diop_DN(19, 1) == [(170, 39)]
# N = -1
assert diop_DN(13, -1) == [(18, 5)]
assert diop_DN(991, -1) == []
assert diop_DN(41, -1) == [(32, 5)]
assert diop_DN(290, -1) == [(17, 1)]
assert diop_DN(21257, -1) == [(13913102721304, 95427381109)]
assert diop_DN(32, -1) == []
# |N| > 1
# Some tests were created using calculator at
# http://www.numbertheory.org/php/patz.html
assert diop_DN(13, -4) == [(3, 1), (393, 109), (36, 10)]
# Source I referred returned (3, 1), (393, 109) and (-3, 1) as fundamental solutions
# So (-3, 1) and (393, 109) should be in the same equivalent class
assert equivalent(-3, 1, 393, 109, 13, -4) == True
assert diop_DN(13, 27) == [(220, 61), (40, 11), (768, 213), (12, 3)]
assert set(diop_DN(157, 12)) == {(13, 1), (10663, 851), (579160, 46222),
(483790960, 38610722), (26277068347, 2097138361),
(21950079635497, 1751807067011)}
assert diop_DN(13, 25) == [(3245, 900)]
assert diop_DN(192, 18) == []
assert diop_DN(23, 13) == [(-6, 1), (6, 1)]
assert diop_DN(167, 2) == [(13, 1)]
assert diop_DN(167, -2) == []
assert diop_DN(123, -2) == [(11, 1)]
# One calculator returned [(11, 1), (-11, 1)] but both of these are in
# the same equivalence class
assert equivalent(11, 1, -11, 1, 123, -2)
assert diop_DN(123, -23) == [(-10, 1), (10, 1)]
assert diop_DN(0, 0, t) == [(0, t)]
assert diop_DN(0, -1, t) == []
def test_bf_pell():
assert diop_bf_DN(13, -4) == [(3, 1), (-3, 1), (36, 10)]
assert diop_bf_DN(13, 27) == [(12, 3), (-12, 3), (40, 11), (-40, 11)]
assert diop_bf_DN(167, -2) == []
assert diop_bf_DN(1729, 1) == [(44611924489705, 1072885712316)]
assert diop_bf_DN(89, -8) == [(9, 1), (-9, 1)]
assert diop_bf_DN(21257, -1) == [(13913102721304, 95427381109)]
assert diop_bf_DN(340, -4) == [(756, 41)]
assert diop_bf_DN(-1, 0, t) == [(0, 0)]
assert diop_bf_DN(0, 0, t) == [(0, t)]
assert diop_bf_DN(4, 0, t) == [(2*t, t), (-2*t, t)]
assert diop_bf_DN(3, 0, t) == [(0, 0)]
assert diop_bf_DN(1, -2, t) == []
def test_length():
assert length(2, 1, 0) == 1
assert length(-2, 4, 5) == 3
assert length(-5, 4, 17) == 4
assert length(0, 4, 13) == 6
assert length(7, 13, 11) == 23
assert length(1, 6, 4) == 2
def is_pell_transformation_ok(eq):
"""
Test whether X*Y, X, or Y terms are present in the equation
after transforming the equation using the transformation returned
by transformation_to_pell(). If they are not present we are good.
Moreover, coefficient of X**2 should be a divisor of coefficient of
Y**2 and the constant term.
"""
A, B = transformation_to_DN(eq)
u = (A*Matrix([X, Y]) + B)[0]
v = (A*Matrix([X, Y]) + B)[1]
simplified = diop_simplify(eq.subs(zip((x, y), (u, v))))
coeff = dict([reversed(t.as_independent(*[X, Y])) for t in simplified.args])
for term in [X*Y, X, Y]:
if term in coeff.keys():
return False
for term in [X**2, Y**2, 1]:
if term not in coeff.keys():
coeff[term] = 0
if coeff[X**2] != 0:
return divisible(coeff[Y**2], coeff[X**2]) and \
divisible(coeff[1], coeff[X**2])
return True
def test_transformation_to_pell():
assert is_pell_transformation_ok(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y - 14)
assert is_pell_transformation_ok(-17*x**2 + 19*x*y - 7*y**2 - 5*x - 13*y - 23)
assert is_pell_transformation_ok(x**2 - y**2 + 17)
assert is_pell_transformation_ok(-x**2 + 7*y**2 - 23)
assert is_pell_transformation_ok(25*x**2 - 45*x*y + 5*y**2 - 5*x - 10*y + 5)
assert is_pell_transformation_ok(190*x**2 + 30*x*y + y**2 - 3*y - 170*x - 130)
assert is_pell_transformation_ok(x**2 - 2*x*y -190*y**2 - 7*y - 23*x - 89)
assert is_pell_transformation_ok(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950)
def test_find_DN():
assert find_DN(x**2 - 2*x - y**2) == (1, 1)
assert find_DN(x**2 - 3*y**2 - 5) == (3, 5)
assert find_DN(x**2 - 2*x*y - 4*y**2 - 7) == (5, 7)
assert find_DN(4*x**2 - 8*x*y - y**2 - 9) == (20, 36)
assert find_DN(7*x**2 - 2*x*y - y**2 - 12) == (8, 84)
assert find_DN(-3*x**2 + 4*x*y -y**2) == (1, 0)
assert find_DN(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y -14) == (101, -7825480)
def test_ldescent():
# Equations which have solutions
u = ([(13, 23), (3, -11), (41, -113), (4, -7), (-7, 4), (91, -3), (1, 1), (1, -1),
(4, 32), (17, 13), (123689, 1), (19, -570)])
for a, b in u:
w, x, y = ldescent(a, b)
assert a*x**2 + b*y**2 == w**2
assert ldescent(-1, -1) is None
def test_diop_ternary_quadratic_normal():
assert check_solutions(234*x**2 - 65601*y**2 - z**2)
assert check_solutions(23*x**2 + 616*y**2 - z**2)
assert check_solutions(5*x**2 + 4*y**2 - z**2)
assert check_solutions(3*x**2 + 6*y**2 - 3*z**2)
assert check_solutions(x**2 + 3*y**2 - z**2)
assert check_solutions(4*x**2 + 5*y**2 - z**2)
assert check_solutions(x**2 + y**2 - z**2)
assert check_solutions(16*x**2 + y**2 - 25*z**2)
assert check_solutions(6*x**2 - y**2 + 10*z**2)
assert check_solutions(213*x**2 + 12*y**2 - 9*z**2)
assert check_solutions(34*x**2 - 3*y**2 - 301*z**2)
assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
def is_normal_transformation_ok(eq):
A = transformation_to_normal(eq)
X, Y, Z = A*Matrix([x, y, z])
simplified = diop_simplify(eq.subs(zip((x, y, z), (X, Y, Z))))
coeff = dict([reversed(t.as_independent(*[X, Y, Z])) for t in simplified.args])
for term in [X*Y, Y*Z, X*Z]:
if term in coeff.keys():
return False
return True
def test_transformation_to_normal():
assert is_normal_transformation_ok(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z)
assert is_normal_transformation_ok(x**2 + 3*y**2 - 100*z**2)
assert is_normal_transformation_ok(x**2 + 23*y*z)
assert is_normal_transformation_ok(3*y**2 - 100*z**2 - 12*x*y)
assert is_normal_transformation_ok(x**2 + 23*x*y - 34*y*z + 12*x*z)
assert is_normal_transformation_ok(z**2 + 34*x*y - 23*y*z + x*z)
assert is_normal_transformation_ok(x**2 + y**2 + z**2 - x*y - y*z - x*z)
assert is_normal_transformation_ok(x**2 + 2*y*z + 3*z**2)
assert is_normal_transformation_ok(x*y + 2*x*z + 3*y*z)
assert is_normal_transformation_ok(2*x*z + 3*y*z)
def test_diop_ternary_quadratic():
assert check_solutions(2*x**2 + z**2 + y**2 - 4*x*y)
assert check_solutions(x**2 - y**2 - z**2 - x*y - y*z)
assert check_solutions(3*x**2 - x*y - y*z - x*z)
assert check_solutions(x**2 - y*z - x*z)
assert check_solutions(5*x**2 - 3*x*y - x*z)
assert check_solutions(4*x**2 - 5*y**2 - x*z)
assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
assert check_solutions(8*x**2 - 12*y*z)
assert check_solutions(45*x**2 - 7*y**2 - 8*x*y - z**2)
assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y)
assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z)
assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 17*y*z)
assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 16*y*z + 12*x*z)
assert check_solutions(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z)
assert check_solutions(x*y - 7*y*z + 13*x*z)
assert diop_ternary_quadratic_normal(x**2 + y**2 + z**2) == (None, None, None)
assert diop_ternary_quadratic_normal(x**2 + y**2) is None
raises(ValueError, lambda:
_diop_ternary_quadratic_normal((x, y, z),
{x*y: 1, x**2: 2, y**2: 3, z**2: 0}))
eq = -2*x*y - 6*x*z + 7*y**2 - 3*y*z + 4*z**2
assert diop_ternary_quadratic(eq) == (7, 2, 0)
assert diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) == \
(1, 0, 2)
assert diop_ternary_quadratic(x*y + 2*y*z) == \
(-2, 0, n1)
eq = -5*x*y - 8*x*z - 3*y*z + 8*z**2
assert parametrize_ternary_quadratic(eq) == \
(8*p**2 - 3*p*q, -8*p*q + 8*q**2, 5*p*q)
# this cannot be tested with diophantine because it will
# factor into a product
assert diop_solve(x*y + 2*y*z) == (-2*p*q, -n1*p**2 + p**2, p*q)
def test_square_factor():
assert square_factor(1) == square_factor(-1) == 1
assert square_factor(0) == 1
assert square_factor(5) == square_factor(-5) == 1
assert square_factor(4) == square_factor(-4) == 2
assert square_factor(12) == square_factor(-12) == 2
assert square_factor(6) == 1
assert square_factor(18) == 3
assert square_factor(52) == 2
assert square_factor(49) == 7
assert square_factor(392) == 14
assert square_factor(factorint(-12)) == 2
def test_parametrize_ternary_quadratic():
assert check_solutions(x**2 + y**2 - z**2)
assert check_solutions(x**2 + 2*x*y + z**2)
assert check_solutions(234*x**2 - 65601*y**2 - z**2)
assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
assert check_solutions(x**2 - y**2 - z**2)
assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y - 8*x*y)
assert check_solutions(8*x*y + z**2)
assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
assert check_solutions(236*x**2 - 225*y**2 - 11*x*y - 13*y*z - 17*x*z)
assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z)
assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
def test_no_square_ternary_quadratic():
assert check_solutions(2*x*y + y*z - 3*x*z)
assert check_solutions(189*x*y - 345*y*z - 12*x*z)
assert check_solutions(23*x*y + 34*y*z)
assert check_solutions(x*y + y*z + z*x)
assert check_solutions(23*x*y + 23*y*z + 23*x*z)
def test_descent():
u = ([(13, 23), (3, -11), (41, -113), (91, -3), (1, 1), (1, -1), (17, 13), (123689, 1), (19, -570)])
for a, b in u:
w, x, y = descent(a, b)
assert a*x**2 + b*y**2 == w**2
# the docstring warns against bad input, so these are expected results
# - can't both be negative
raises(TypeError, lambda: descent(-1, -3))
# A can't be zero unless B != 1
raises(ZeroDivisionError, lambda: descent(0, 3))
# supposed to be square-free
raises(TypeError, lambda: descent(4, 3))
def test_diophantine():
assert check_solutions((x - y)*(y - z)*(z - x))
assert check_solutions((x - y)*(x**2 + y**2 - z**2))
assert check_solutions((x - 3*y + 7*z)*(x**2 + y**2 - z**2))
assert check_solutions(x**2 - 3*y**2 - 1)
assert check_solutions(y**2 + 7*x*y)
assert check_solutions(x**2 - 3*x*y + y**2)
assert check_solutions(z*(x**2 - y**2 - 15))
assert check_solutions(x*(2*y - 2*z + 5))
assert check_solutions((x**2 - 3*y**2 - 1)*(x**2 - y**2 - 15))
assert check_solutions((x**2 - 3*y**2 - 1)*(y - 7*z))
assert check_solutions((x**2 + y**2 - z**2)*(x - 7*y - 3*z + 4*w))
# Following test case caused problems in parametric representation
# But this can be solved by factoring out y.
# No need to use methods for ternary quadratic equations.
assert check_solutions(y**2 - 7*x*y + 4*y*z)
assert check_solutions(x**2 - 2*x + 1)
assert diophantine(x - y) == diophantine(Eq(x, y))
# 18196
eq = x**4 + y**4 - 97
assert diophantine(eq, permute=True) == diophantine(-eq, permute=True)
assert diophantine(3*x*pi - 2*y*pi) == {(2*t_0, 3*t_0)}
eq = x**2 + y**2 + z**2 - 14
base_sol = {(1, 2, 3)}
assert diophantine(eq) == base_sol
complete_soln = set(signed_permutations(base_sol.pop()))
assert diophantine(eq, permute=True) == complete_soln
assert diophantine(x**2 + x*Rational(15, 14) - 3) == set()
# test issue 11049
eq = 92*x**2 - 99*y**2 - z**2
coeff = eq.as_coefficients_dict()
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
{(9, 7, 51)}
assert diophantine(eq) == {(
891*p**2 + 9*q**2, -693*p**2 - 102*p*q + 7*q**2,
5049*p**2 - 1386*p*q - 51*q**2)}
eq = 2*x**2 + 2*y**2 - z**2
coeff = eq.as_coefficients_dict()
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
{(1, 1, 2)}
assert diophantine(eq) == {(
2*p**2 - q**2, -2*p**2 + 4*p*q - q**2,
4*p**2 - 4*p*q + 2*q**2)}
eq = 411*x**2+57*y**2-221*z**2
coeff = eq.as_coefficients_dict()
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
{(2021, 2645, 3066)}
assert diophantine(eq) == \
{(115197*p**2 - 446641*q**2, -150765*p**2 + 1355172*p*q -
584545*q**2, 174762*p**2 - 301530*p*q + 677586*q**2)}
eq = 573*x**2+267*y**2-984*z**2
coeff = eq.as_coefficients_dict()
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
{(49, 233, 127)}
assert diophantine(eq) == \
{(4361*p**2 - 16072*q**2, -20737*p**2 + 83312*p*q - 76424*q**2,
11303*p**2 - 41474*p*q + 41656*q**2)}
# this produces factors during reconstruction
eq = x**2 + 3*y**2 - 12*z**2
coeff = eq.as_coefficients_dict()
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
{(0, 2, 1)}
assert diophantine(eq) == \
{(24*p*q, 2*p**2 - 24*q**2, p**2 + 12*q**2)}
# solvers have not been written for every type
raises(NotImplementedError, lambda: diophantine(x*y**2 + 1))
# rational expressions
assert diophantine(1/x) == set()
assert diophantine(1/x + 1/y - S.Half) == {(6, 3), (-2, 1), (4, 4), (1, -2), (3, 6)}
assert diophantine(x**2 + y**2 +3*x- 5, permute=True) == \
{(-1, 1), (-4, -1), (1, -1), (1, 1), (-4, 1), (-1, -1), (4, 1), (4, -1)}
#test issue 18186
assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(x, y), permute=True) == \
{(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(y, x), permute=True) == \
{(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
# issue 18122
assert check_solutions(x**2-y)
assert check_solutions(y**2-x)
assert diophantine((x**2-y), t) == {(t, t**2)}
assert diophantine((y**2-x), t) == {(t**2, -t)}
def test_general_pythagorean():
from sympy.abc import a, b, c, d, e
assert check_solutions(a**2 + b**2 + c**2 - d**2)
assert check_solutions(a**2 + 4*b**2 + 4*c**2 - d**2)
assert check_solutions(9*a**2 + 4*b**2 + 4*c**2 - d**2)
assert check_solutions(9*a**2 + 4*b**2 - 25*d**2 + 4*c**2 )
assert check_solutions(9*a**2 - 16*d**2 + 4*b**2 + 4*c**2)
assert check_solutions(-e**2 + 9*a**2 + 4*b**2 + 4*c**2 + 25*d**2)
assert check_solutions(16*a**2 - b**2 + 9*c**2 + d**2 + 25*e**2)
assert GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve(parameters=[x, y, z]) == \
{(x**2 + y**2 - z**2, 2*x*z, 2*y*z, x**2 + y**2 + z**2)}
def test_diop_general_sum_of_squares_quick():
for i in range(3, 10):
assert check_solutions(sum(i**2 for i in symbols(':%i' % i)) - i)
assert diop_general_sum_of_squares(x**2 + y**2 - 2) is None
assert diop_general_sum_of_squares(x**2 + y**2 + z**2 + 2) == set()
eq = x**2 + y**2 + z**2 - (1 + 4 + 9)
assert diop_general_sum_of_squares(eq) == \
{(1, 2, 3)}
eq = u**2 + v**2 + x**2 + y**2 + z**2 - 1313
assert len(diop_general_sum_of_squares(eq, 3)) == 3
# issue 11016
var = symbols(':5') + (symbols('6', negative=True),)
eq = Add(*[i**2 for i in var]) - 112
base_soln = {(0, 1, 1, 5, 6, -7), (1, 1, 1, 3, 6, -8), (2, 3, 3, 4, 5, -7), (0, 1, 1, 1, 3, -10),
(0, 0, 4, 4, 4, -8), (1, 2, 3, 3, 5, -8), (0, 1, 2, 3, 7, -7), (2, 2, 4, 4, 6, -6),
(1, 1, 3, 4, 6, -7), (0, 2, 3, 3, 3, -9), (0, 0, 2, 2, 2, -10), (1, 1, 2, 3, 4, -9),
(0, 1, 1, 2, 5, -9), (0, 0, 2, 6, 6, -6), (1, 3, 4, 5, 5, -6), (0, 2, 2, 2, 6, -8),
(0, 3, 3, 3, 6, -7), (0, 2, 3, 5, 5, -7), (0, 1, 5, 5, 5, -6)}
assert diophantine(eq) == base_soln
assert len(diophantine(eq, permute=True)) == 196800
# handle negated squares with signsimp
assert diophantine(12 - x**2 - y**2 - z**2) == {(2, 2, 2)}
# diophantine handles simplification, so classify_diop should
# not have to look for additional patterns that are removed
# by diophantine
eq = a**2 + b**2 + c**2 + d**2 - 4
raises(NotImplementedError, lambda: classify_diop(-eq))
def test_diop_partition():
for n in [8, 10]:
for k in range(1, 8):
for p in partition(n, k):
assert len(p) == k
assert [p for p in partition(3, 5)] == []
assert [list(p) for p in partition(3, 5, 1)] == [
[0, 0, 0, 0, 3], [0, 0, 0, 1, 2], [0, 0, 1, 1, 1]]
assert list(partition(0)) == [()]
assert list(partition(1, 0)) == [()]
assert [list(i) for i in partition(3)] == [[1, 1, 1], [1, 2], [3]]
def test_prime_as_sum_of_two_squares():
for i in [5, 13, 17, 29, 37, 41, 2341, 3557, 34841, 64601]:
a, b = prime_as_sum_of_two_squares(i)
assert a**2 + b**2 == i
assert prime_as_sum_of_two_squares(7) is None
ans = prime_as_sum_of_two_squares(800029)
assert ans == (450, 773) and type(ans[0]) is int
def test_sum_of_three_squares():
for i in [0, 1, 2, 34, 123, 34304595905, 34304595905394941, 343045959052344,
800, 801, 802, 803, 804, 805, 806]:
a, b, c = sum_of_three_squares(i)
assert a**2 + b**2 + c**2 == i
assert sum_of_three_squares(7) is None
assert sum_of_three_squares((4**5)*15) is None
assert sum_of_three_squares(25) == (5, 0, 0)
assert sum_of_three_squares(4) == (0, 0, 2)
def test_sum_of_four_squares():
from random import randint
# this should never fail
n = randint(1, 100000000000000)
assert sum(i**2 for i in sum_of_four_squares(n)) == n
assert sum_of_four_squares(0) == (0, 0, 0, 0)
assert sum_of_four_squares(14) == (0, 1, 2, 3)
assert sum_of_four_squares(15) == (1, 1, 2, 3)
assert sum_of_four_squares(18) == (1, 2, 2, 3)
assert sum_of_four_squares(19) == (0, 1, 3, 3)
assert sum_of_four_squares(48) == (0, 4, 4, 4)
def test_power_representation():
tests = [(1729, 3, 2), (234, 2, 4), (2, 1, 2), (3, 1, 3), (5, 2, 2), (12352, 2, 4),
(32760, 2, 3)]
for test in tests:
n, p, k = test
f = power_representation(n, p, k)
while True:
try:
l = next(f)
assert len(l) == k
chk_sum = 0
for l_i in l:
chk_sum = chk_sum + l_i**p
assert chk_sum == n
except StopIteration:
break
assert list(power_representation(20, 2, 4, True)) == \
[(1, 1, 3, 3), (0, 0, 2, 4)]
raises(ValueError, lambda: list(power_representation(1.2, 2, 2)))
raises(ValueError, lambda: list(power_representation(2, 0, 2)))
raises(ValueError, lambda: list(power_representation(2, 2, 0)))
assert list(power_representation(-1, 2, 2)) == []
assert list(power_representation(1, 1, 1)) == [(1,)]
assert list(power_representation(3, 2, 1)) == []
assert list(power_representation(4, 2, 1)) == [(2,)]
assert list(power_representation(3**4, 4, 6, zeros=True)) == \
[(1, 2, 2, 2, 2, 2), (0, 0, 0, 0, 0, 3)]
assert list(power_representation(3**4, 4, 5, zeros=False)) == []
assert list(power_representation(-2, 3, 2)) == [(-1, -1)]
assert list(power_representation(-2, 4, 2)) == []
assert list(power_representation(0, 3, 2, True)) == [(0, 0)]
assert list(power_representation(0, 3, 2, False)) == []
# when we are dealing with squares, do feasibility checks
assert len(list(power_representation(4**10*(8*10 + 7), 2, 3))) == 0
# there will be a recursion error if these aren't recognized
big = 2**30
for i in [13, 10, 7, 5, 4, 2, 1]:
assert list(sum_of_powers(big, 2, big - i)) == []
def test_assumptions():
"""
Test whether diophantine respects the assumptions.
"""
#Test case taken from the below so question regarding assumptions in diophantine module
#https://stackoverflow.com/questions/23301941/how-can-i-declare-natural-symbols-with-sympy
m, n = symbols('m n', integer=True, positive=True)
diof = diophantine(n**2 + m*n - 500)
assert diof == {(5, 20), (40, 10), (95, 5), (121, 4), (248, 2), (499, 1)}
a, b = symbols('a b', integer=True, positive=False)
diof = diophantine(a*b + 2*a + 3*b - 6)
assert diof == {(-15, -3), (-9, -4), (-7, -5), (-6, -6), (-5, -8), (-4, -14)}
def check_solutions(eq):
"""
Determines whether solutions returned by diophantine() satisfy the original
equation. Hope to generalize this so we can remove functions like check_ternay_quadratic,
check_solutions_normal, check_solutions()
"""
s = diophantine(eq)
factors = Mul.make_args(eq)
var = list(eq.free_symbols)
var.sort(key=default_sort_key)
while s:
solution = s.pop()
for f in factors:
if diop_simplify(f.subs(zip(var, solution))) == 0:
break
else:
return False
return True
def test_diopcoverage():
eq = (2*x + y + 1)**2
assert diop_solve(eq) == {(t_0, -2*t_0 - 1)}
eq = 2*x**2 + 6*x*y + 12*x + 4*y**2 + 18*y + 18
assert diop_solve(eq) == {(t, -t - 3), (2*t - 3, -t)}
assert diop_quadratic(x + y**2 - 3) == {(-t**2 + 3, -t)}
assert diop_linear(x + y - 3) == (t_0, 3 - t_0)
assert base_solution_linear(0, 1, 2, t=None) == (0, 0)
ans = (3*t - 1, -2*t + 1)
assert base_solution_linear(4, 8, 12, t) == ans
assert base_solution_linear(4, 8, 12, t=None) == tuple(_.subs(t, 0) for _ in ans)
assert cornacchia(1, 1, 20) is None
assert cornacchia(1, 1, 5) == {(2, 1)}
assert cornacchia(1, 2, 17) == {(3, 2)}
raises(ValueError, lambda: reconstruct(4, 20, 1))
assert gaussian_reduce(4, 1, 3) == (1, 1)
eq = -w**2 - x**2 - y**2 + z**2
assert diop_general_pythagorean(eq) == \
diop_general_pythagorean(-eq) == \
(m1**2 + m2**2 - m3**2, 2*m1*m3,
2*m2*m3, m1**2 + m2**2 + m3**2)
assert len(check_param(S(3) + x/3, S(4) + x/2, S(2), [x])) == 0
assert len(check_param(Rational(3, 2), S(4) + x, S(2), [x])) == 0
assert len(check_param(S(4) + x, Rational(3, 2), S(2), [x])) == 0
assert _nint_or_floor(16, 10) == 2
assert _odd(1) == (not _even(1)) == True
assert _odd(0) == (not _even(0)) == False
assert _remove_gcd(2, 4, 6) == (1, 2, 3)
raises(TypeError, lambda: _remove_gcd((2, 4, 6)))
assert sqf_normal(2*3**2*5, 2*5*11, 2*7**2*11) == \
(11, 1, 5)
# it's ok if these pass some day when the solvers are implemented
raises(NotImplementedError, lambda: diophantine(x**2 + y**2 + x*y + 2*y*z - 12))
raises(NotImplementedError, lambda: diophantine(x**3 + y**2))
assert diop_quadratic(x**2 + y**2 - 1**2 - 3**4) == \
{(-9, -1), (-9, 1), (-1, -9), (-1, 9), (1, -9), (1, 9), (9, -1), (9, 1)}
def test_holzer():
# if the input is good, don't let it diverge in holzer()
# (but see test_fail_holzer below)
assert holzer(2, 7, 13, 4, 79, 23) == (2, 7, 13)
# None in uv condition met; solution is not Holzer reduced
# so this will hopefully change but is here for coverage
assert holzer(2, 6, 2, 1, 1, 10) == (2, 6, 2)
raises(ValueError, lambda: holzer(2, 7, 14, 4, 79, 23))
@XFAIL
def test_fail_holzer():
eq = lambda x, y, z: a*x**2 + b*y**2 - c*z**2
a, b, c = 4, 79, 23
x, y, z = xyz = 26, 1, 11
X, Y, Z = ans = 2, 7, 13
assert eq(*xyz) == 0
assert eq(*ans) == 0
assert max(a*x**2, b*y**2, c*z**2) <= a*b*c
assert max(a*X**2, b*Y**2, c*Z**2) <= a*b*c
h = holzer(x, y, z, a, b, c)
assert h == ans # it would be nice to get the smaller soln
def test_issue_9539():
assert diophantine(6*w + 9*y + 20*x - z) == \
{(t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 9*t_2)}
def test_issue_8943():
assert diophantine(
3*(x**2 + y**2 + z**2) - 14*(x*y + y*z + z*x)) == \
{(0, 0, 0)}
def test_diop_sum_of_even_powers():
eq = x**4 + y**4 + z**4 - 2673
assert diop_solve(eq) == {(3, 6, 6), (2, 4, 7)}
assert diop_general_sum_of_even_powers(eq, 2) == {(3, 6, 6), (2, 4, 7)}
raises(NotImplementedError, lambda: diop_general_sum_of_even_powers(-eq, 2))
neg = symbols('neg', negative=True)
eq = x**4 + y**4 + neg**4 - 2673
assert diop_general_sum_of_even_powers(eq) == {(-3, 6, 6)}
assert diophantine(x**4 + y**4 + 2) == set()
assert diop_general_sum_of_even_powers(x**4 + y**4 - 2, limit=0) == set()
def test_sum_of_squares_powers():
tru = {(0, 0, 1, 1, 11), (0, 0, 5, 7, 7), (0, 1, 3, 7, 8), (0, 1, 4, 5, 9), (0, 3, 4, 7, 7), (0, 3, 5, 5, 8),
(1, 1, 2, 6, 9), (1, 1, 6, 6, 7), (1, 2, 3, 3, 10), (1, 3, 4, 4, 9), (1, 5, 5, 6, 6), (2, 2, 3, 5, 9),
(2, 3, 5, 6, 7), (3, 3, 4, 5, 8)}
eq = u**2 + v**2 + x**2 + y**2 + z**2 - 123
ans = diop_general_sum_of_squares(eq, oo) # allow oo to be used
assert len(ans) == 14
assert ans == tru
raises(ValueError, lambda: list(sum_of_squares(10, -1)))
assert list(sum_of_squares(-10, 2)) == []
assert list(sum_of_squares(2, 3)) == []
assert list(sum_of_squares(0, 3, True)) == [(0, 0, 0)]
assert list(sum_of_squares(0, 3)) == []
assert list(sum_of_squares(4, 1)) == [(2,)]
assert list(sum_of_squares(5, 1)) == []
assert list(sum_of_squares(50, 2)) == [(5, 5), (1, 7)]
assert list(sum_of_squares(11, 5, True)) == [
(1, 1, 1, 2, 2), (0, 0, 1, 1, 3)]
assert list(sum_of_squares(8, 8)) == [(1, 1, 1, 1, 1, 1, 1, 1)]
assert [len(list(sum_of_squares(i, 5, True))) for i in range(30)] == [
1, 1, 1, 1, 2,
2, 1, 1, 2, 2,
2, 2, 2, 3, 2,
1, 3, 3, 3, 3,
4, 3, 3, 2, 2,
4, 4, 4, 4, 5]
assert [len(list(sum_of_squares(i, 5))) for i in range(30)] == [
0, 0, 0, 0, 0,
1, 0, 0, 1, 0,
0, 1, 0, 1, 1,
0, 1, 1, 0, 1,
2, 1, 1, 1, 1,
1, 1, 1, 1, 3]
for i in range(30):
s1 = set(sum_of_squares(i, 5, True))
assert not s1 or all(sum(j**2 for j in t) == i for t in s1)
s2 = set(sum_of_squares(i, 5))
assert all(sum(j**2 for j in t) == i for t in s2)
raises(ValueError, lambda: list(sum_of_powers(2, -1, 1)))
raises(ValueError, lambda: list(sum_of_powers(2, 1, -1)))
assert list(sum_of_powers(-2, 3, 2)) == [(-1, -1)]
assert list(sum_of_powers(-2, 4, 2)) == []
assert list(sum_of_powers(2, 1, 1)) == [(2,)]
assert list(sum_of_powers(2, 1, 3, True)) == [(0, 0, 2), (0, 1, 1)]
assert list(sum_of_powers(5, 1, 2, True)) == [(0, 5), (1, 4), (2, 3)]
assert list(sum_of_powers(6, 2, 2)) == []
assert list(sum_of_powers(3**5, 3, 1)) == []
assert list(sum_of_powers(3**6, 3, 1)) == [(9,)] and (9**3 == 3**6)
assert list(sum_of_powers(2**1000, 5, 2)) == []
def test__can_do_sum_of_squares():
assert _can_do_sum_of_squares(3, -1) is False
assert _can_do_sum_of_squares(-3, 1) is False
assert _can_do_sum_of_squares(0, 1)
assert _can_do_sum_of_squares(4, 1)
assert _can_do_sum_of_squares(1, 2)
assert _can_do_sum_of_squares(2, 2)
assert _can_do_sum_of_squares(3, 2) is False
def test_diophantine_permute_sign():
from sympy.abc import a, b, c, d, e
eq = a**4 + b**4 - (2**4 + 3**4)
base_sol = {(2, 3)}
assert diophantine(eq) == base_sol
complete_soln = set(signed_permutations(base_sol.pop()))
assert diophantine(eq, permute=True) == complete_soln
eq = a**2 + b**2 + c**2 + d**2 + e**2 - 234
assert len(diophantine(eq)) == 35
assert len(diophantine(eq, permute=True)) == 62000
soln = {(-1, -1), (-1, 2), (1, -2), (1, 1)}
assert diophantine(10*x**2 + 12*x*y + 12*y**2 - 34, permute=True) == soln
@XFAIL
def test_not_implemented():
eq = x**2 + y**4 - 1**2 - 3**4
assert diophantine(eq, syms=[x, y]) == {(9, 1), (1, 3)}
def test_issue_9538():
eq = x - 3*y + 2
assert diophantine(eq, syms=[y,x]) == {(t_0, 3*t_0 - 2)}
raises(TypeError, lambda: diophantine(eq, syms={y, x}))
def test_ternary_quadratic():
# solution with 3 parameters
s = diophantine(2*x**2 + y**2 - 2*z**2)
p, q, r = ordered(S(s).free_symbols)
assert s == {(
p**2 - 2*q**2,
-2*p**2 + 4*p*q - 4*p*r - 4*q**2,
p**2 - 4*p*q + 2*q**2 - 4*q*r)}
# solution with Mul in solution
s = diophantine(x**2 + 2*y**2 - 2*z**2)
assert s == {(4*p*q, p**2 - 2*q**2, p**2 + 2*q**2)}
# solution with no Mul in solution
s = diophantine(2*x**2 + 2*y**2 - z**2)
assert s == {(2*p**2 - q**2, -2*p**2 + 4*p*q - q**2,
4*p**2 - 4*p*q + 2*q**2)}
# reduced form when parametrized
s = diophantine(3*x**2 + 72*y**2 - 27*z**2)
assert s == {(24*p**2 - 9*q**2, 6*p*q, 8*p**2 + 3*q**2)}
assert parametrize_ternary_quadratic(
3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) == (
2*p**2 - 2*p*q - q**2, 2*p**2 + 2*p*q - q**2, 2*p**2 -
2*p*q + 3*q**2)
assert parametrize_ternary_quadratic(
124*x**2 - 30*y**2 - 7729*z**2) == (
-1410*p**2 - 363263*q**2, 2700*p**2 + 30916*p*q -
695610*q**2, -60*p**2 + 5400*p*q + 15458*q**2)
def test_diophantine_solution_set():
s1 = DiophantineSolutionSet([], [])
assert set(s1) == set()
assert s1.symbols == ()
assert s1.parameters == ()
raises(ValueError, lambda: s1.add((x,)))
assert list(s1.dict_iterator()) == []
s2 = DiophantineSolutionSet([x, y], [t, u])
assert s2.symbols == (x, y)
assert s2.parameters == (t, u)
raises(ValueError, lambda: s2.add((1,)))
s2.add((3, 4))
assert set(s2) == {(3, 4)}
s2.update((3, 4), (-1, u))
assert set(s2) == {(3, 4), (-1, u)}
raises(ValueError, lambda: s1.update(s2))
assert list(s2.dict_iterator()) == [{x: -1, y: u}, {x: 3, y: 4}]
s3 = DiophantineSolutionSet([x, y, z], [t, u])
assert len(s3.parameters) == 2
s3.add((t**2 + u, t - u, 1))
assert set(s3) == {(t**2 + u, t - u, 1)}
assert s3.subs(t, 2) == {(u + 4, 2 - u, 1)}
assert s3(2) == {(u + 4, 2 - u, 1)}
assert s3.subs({t: 7, u: 8}) == {(57, -1, 1)}
assert s3(7, 8) == {(57, -1, 1)}
assert s3.subs({t: 5}) == {(u + 25, 5 - u, 1)}
assert s3(5) == {(u + 25, 5 - u, 1)}
assert s3.subs(u, -3) == {(t**2 - 3, t + 3, 1)}
assert s3(None, -3) == {(t**2 - 3, t + 3, 1)}
assert s3.subs({t: 2, u: 8}) == {(12, -6, 1)}
assert s3(2, 8) == {(12, -6, 1)}
assert s3.subs({t: 5, u: -3}) == {(22, 8, 1)}
assert s3(5, -3) == {(22, 8, 1)}
raises(ValueError, lambda: s3.subs(x=1))
raises(ValueError, lambda: s3.subs(1, 2, 3))
raises(ValueError, lambda: s3.add(()))
raises(ValueError, lambda: s3.add((1, 2, 3, 4)))
raises(ValueError, lambda: s3.add((1, 2)))
raises(ValueError, lambda: s3(1, 2, 3))
raises(TypeError, lambda: s3(t=1))
s4 = DiophantineSolutionSet([x, y], [t, u])
s4.add((t, 11*t))
s4.add((-t, 22*t))
assert s4(0, 0) == {(0, 0)}
def test_quadratic_parameter_passing():
eq = -33*x*y + 3*y**2
solution = BinaryQuadratic(eq).solve(parameters=[t, u])
# test that parameters are passed all the way to the final solution
assert solution == {(t, 11*t), (-t, 22*t)}
assert solution(0, 0) == {(0, 0)}
|
16393c7b9af269d35047ea1daaff45fb0bf488158f00ba94241e0b4971e4b079 | from sympy import (acosh, cos, Derivative, diff,
Eq, exp, Function, I, Integral, log, O, pi,
Rational, S, sin, sqrt, Subs, Symbol, tan,
symbols, Poly, re, im, atan2, collect)
from sympy.solvers.ode import (classify_ode,
homogeneous_order, dsolve)
from sympy.solvers.ode.subscheck import checkodesol
from sympy.solvers.ode.ode import (_linear_coeff_match,
_undetermined_coefficients_match, classify_sysode,
constant_renumber, constantsimp, get_numbered_constants, solve_ics)
from sympy.solvers.deutils import ode_order
from sympy.testing.pytest import XFAIL, raises, slow
C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C0:11')
u, x, y, z = symbols('u,x:z', real=True)
f = Function('f')
g = Function('g')
h = Function('h')
# Note: Examples which were specifically testing Single ODE solver are moved to test_single.py
# and all the system of ode examples are moved to test_systems.py
# Note: the tests below may fail (but still be correct) if ODE solver,
# the integral engine, solve(), or even simplify() changes. Also, in
# differently formatted solutions, the arbitrary constants might not be
# equal. Using specific hints in tests can help to avoid this.
# Tests of order higher than 1 should run the solutions through
# constant_renumber because it will normalize it (constant_renumber causes
# dsolve() to return different results on different machines)
def test_get_numbered_constants():
with raises(ValueError):
get_numbered_constants(None)
def test_dsolve_all_hint():
eq = f(x).diff(x)
output = dsolve(eq, hint='all')
# Match the Dummy variables:
sol1 = output['separable_Integral']
_y = sol1.lhs.args[1][0]
sol1 = output['1st_homogeneous_coeff_subs_dep_div_indep_Integral']
_u1 = sol1.rhs.args[1].args[1][0]
expected = {'Bernoulli_Integral': Eq(f(x), C1 + Integral(0, x)),
'1st_homogeneous_coeff_best': Eq(f(x), C1),
'Bernoulli': Eq(f(x), C1),
'nth_algebraic': Eq(f(x), C1),
'nth_linear_euler_eq_homogeneous': Eq(f(x), C1),
'nth_linear_constant_coeff_homogeneous': Eq(f(x), C1),
'separable': Eq(f(x), C1),
'1st_homogeneous_coeff_subs_indep_div_dep': Eq(f(x), C1),
'nth_algebraic_Integral': Eq(f(x), C1),
'1st_linear': Eq(f(x), C1),
'1st_linear_Integral': Eq(f(x), C1 + Integral(0, x)),
'1st_exact': Eq(f(x), C1),
'1st_exact_Integral': Eq(Subs(Integral(0, x) + Integral(1, _y), _y, f(x)), C1),
'lie_group': Eq(f(x), C1),
'1st_homogeneous_coeff_subs_dep_div_indep': Eq(f(x), C1),
'1st_homogeneous_coeff_subs_dep_div_indep_Integral': Eq(log(x), C1 + Integral(-1/_u1, (_u1, f(x)/x))),
'1st_power_series': Eq(f(x), C1),
'separable_Integral': Eq(Integral(1, (_y, f(x))), C1 + Integral(0, x)),
'1st_homogeneous_coeff_subs_indep_div_dep_Integral': Eq(f(x), C1),
'best': Eq(f(x), C1),
'best_hint': 'nth_algebraic',
'default': 'nth_algebraic',
'order': 1}
assert output == expected
assert dsolve(eq, hint='best') == Eq(f(x), C1)
def test_dsolve_ics():
# Maybe this should just use one of the solutions instead of raising...
with raises(NotImplementedError):
dsolve(f(x).diff(x) - sqrt(f(x)), ics={f(1):1})
@slow
def test_dsolve_options():
eq = x*f(x).diff(x) + f(x)
a = dsolve(eq, hint='all')
b = dsolve(eq, hint='all', simplify=False)
c = dsolve(eq, hint='all_Integral')
keys = ['1st_exact', '1st_exact_Integral', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear',
'1st_linear_Integral', 'Bernoulli', 'Bernoulli_Integral',
'almost_linear', 'almost_linear_Integral', 'best', 'best_hint',
'default', 'lie_group',
'nth_linear_euler_eq_homogeneous', 'order',
'separable', 'separable_Integral']
Integral_keys = ['1st_exact_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear_Integral',
'Bernoulli_Integral', 'almost_linear_Integral', 'best', 'best_hint', 'default',
'nth_linear_euler_eq_homogeneous',
'order', 'separable_Integral']
assert sorted(a.keys()) == keys
assert a['order'] == ode_order(eq, f(x))
assert a['best'] == Eq(f(x), C1/x)
assert dsolve(eq, hint='best') == Eq(f(x), C1/x)
assert a['default'] == 'separable'
assert a['best_hint'] == 'separable'
assert not a['1st_exact'].has(Integral)
assert not a['separable'].has(Integral)
assert not a['1st_homogeneous_coeff_best'].has(Integral)
assert not a['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral)
assert not a['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral)
assert not a['1st_linear'].has(Integral)
assert a['1st_linear_Integral'].has(Integral)
assert a['1st_exact_Integral'].has(Integral)
assert a['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral)
assert a['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral)
assert a['separable_Integral'].has(Integral)
assert sorted(b.keys()) == keys
assert b['order'] == ode_order(eq, f(x))
assert b['best'] == Eq(f(x), C1/x)
assert dsolve(eq, hint='best', simplify=False) == Eq(f(x), C1/x)
assert b['default'] == 'separable'
assert b['best_hint'] == '1st_linear'
assert a['separable'] != b['separable']
assert a['1st_homogeneous_coeff_subs_dep_div_indep'] != \
b['1st_homogeneous_coeff_subs_dep_div_indep']
assert a['1st_homogeneous_coeff_subs_indep_div_dep'] != \
b['1st_homogeneous_coeff_subs_indep_div_dep']
assert not b['1st_exact'].has(Integral)
assert not b['separable'].has(Integral)
assert not b['1st_homogeneous_coeff_best'].has(Integral)
assert not b['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral)
assert not b['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral)
assert not b['1st_linear'].has(Integral)
assert b['1st_linear_Integral'].has(Integral)
assert b['1st_exact_Integral'].has(Integral)
assert b['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral)
assert b['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral)
assert b['separable_Integral'].has(Integral)
assert sorted(c.keys()) == Integral_keys
raises(ValueError, lambda: dsolve(eq, hint='notarealhint'))
raises(ValueError, lambda: dsolve(eq, hint='Liouville'))
assert dsolve(f(x).diff(x) - 1/f(x)**2, hint='all')['best'] == \
dsolve(f(x).diff(x) - 1/f(x)**2, hint='best')
assert dsolve(f(x) + f(x).diff(x) + sin(x).diff(x) + 1, f(x),
hint="1st_linear_Integral") == \
Eq(f(x), (C1 + Integral((-sin(x).diff(x) - 1)*
exp(Integral(1, x)), x))*exp(-Integral(1, x)))
def test_classify_ode():
assert classify_ode(f(x).diff(x, 2), f(x)) == \
(
'nth_algebraic',
'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'Liouville',
'2nd_power_series_ordinary',
'nth_algebraic_Integral',
'Liouville_Integral',
)
assert classify_ode(f(x), f(x)) == ('nth_algebraic', 'nth_algebraic_Integral')
assert classify_ode(Eq(f(x).diff(x), 0), f(x)) == (
'nth_algebraic',
'separable',
'1st_exact',
'1st_linear',
'Bernoulli',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral',
'separable_Integral',
'1st_exact_Integral',
'1st_linear_Integral',
'Bernoulli_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
assert classify_ode(f(x).diff(x)**2, f(x)) == ('factorable',
'nth_algebraic',
'separable',
'1st_exact',
'1st_linear',
'Bernoulli',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series',
'lie_group',
'nth_linear_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')
# issue 4749: f(x) should be cleared from highest derivative before classifying
a = classify_ode(Eq(f(x).diff(x) + f(x), x), f(x))
b = classify_ode(f(x).diff(x)*f(x) + f(x)*f(x) - x*f(x), f(x))
c = classify_ode(f(x).diff(x)/f(x) + f(x)/f(x) - x/f(x), f(x))
assert a == ('1st_exact',
'1st_linear',
'Bernoulli',
'almost_linear',
'1st_power_series', "lie_group",
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_exact_Integral',
'1st_linear_Integral',
'Bernoulli_Integral',
'almost_linear_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
assert b == ('factorable',
'1st_linear',
'Bernoulli',
'1st_power_series',
'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral',
'Bernoulli_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
assert c == ('1st_linear',
'Bernoulli',
'1st_power_series',
'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_linear_Integral',
'Bernoulli_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
assert classify_ode(
2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x)
) == ('1st_exact', 'Bernoulli', 'almost_linear', 'lie_group',
'1st_exact_Integral', 'Bernoulli_Integral', 'almost_linear_Integral')
assert 'Riccati_special_minus2' in \
classify_ode(2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2), f(x))
raises(ValueError, lambda: classify_ode(x + f(x, y).diff(x).diff(
y), f(x, y)))
# issue 5176
k = Symbol('k')
assert classify_ode(f(x).diff(x)/(k*f(x) + k*x*f(x)) + 2*f(x)/(k*f(x) +
k*x*f(x)) + x*f(x).diff(x)/(k*f(x) + k*x*f(x)) + z, f(x)) == \
('separable', '1st_exact', '1st_linear', 'Bernoulli',
'1st_power_series', 'lie_group', 'separable_Integral', '1st_exact_Integral',
'1st_linear_Integral', 'Bernoulli_Integral')
# preprocessing
ans = ('nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters',
'nth_algebraic_Integral',
'separable_Integral', '1st_exact_Integral',
'1st_linear_Integral',
'Bernoulli_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral')
# w/o f(x) given
assert classify_ode(diff(f(x) + x, x) + diff(f(x), x)) == ans
# w/ f(x) and prep=True
assert classify_ode(diff(f(x) + x, x) + diff(f(x), x), f(x),
prep=True) == ans
assert classify_ode(Eq(2*x**3*f(x).diff(x), 0), f(x)) == \
('factorable', 'nth_algebraic', 'separable', '1st_exact',
'1st_linear', 'Bernoulli', '1st_power_series',
'lie_group', 'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral',
'1st_linear_Integral', 'Bernoulli_Integral')
assert classify_ode(Eq(2*f(x)**3*f(x).diff(x), 0), f(x)) == \
('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear',
'Bernoulli', '1st_power_series', 'lie_group', 'nth_algebraic_Integral',
'separable_Integral', '1st_exact_Integral', '1st_linear_Integral',
'Bernoulli_Integral')
# test issue 13864
assert classify_ode(Eq(diff(f(x), x) - f(x)**x, 0), f(x)) == \
('1st_power_series', 'lie_group')
assert isinstance(classify_ode(Eq(f(x), 5), f(x), dict=True), dict)
def test_classify_ode_ics():
# Dummy
eq = f(x).diff(x, x) - f(x)
# Not f(0) or f'(0)
ics = {x: 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
############################
# f(0) type (AppliedUndef) #
############################
# Wrong function
ics = {g(0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Contains x
ics = {f(x): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Too many args
ics = {f(0, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# point contains f
# XXX: Should be NotImplementedError
ics = {f(0): f(1)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(0): 1}
classify_ode(eq, f(x), ics=ics)
#####################
# f'(0) type (Subs) #
#####################
# Wrong function
ics = {g(x).diff(x).subs(x, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Contains x
ics = {f(y).diff(y).subs(y, x): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Wrong variable
ics = {f(y).diff(y).subs(y, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Too many args
ics = {f(x, y).diff(x).subs(x, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Derivative wrt wrong vars
ics = {Derivative(f(x), x, y).subs(x, 0): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# point contains f
# XXX: Should be NotImplementedError
ics = {f(x).diff(x).subs(x, 0): f(0)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(x).diff(x).subs(x, 0): 1}
classify_ode(eq, f(x), ics=ics)
###########################
# f'(y) type (Derivative) #
###########################
# Wrong function
ics = {g(x).diff(x).subs(x, y): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Contains x
ics = {f(y).diff(y).subs(y, x): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Too many args
ics = {f(x, y).diff(x).subs(x, y): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Derivative wrt wrong vars
ics = {Derivative(f(x), x, z).subs(x, y): 1}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# point contains f
# XXX: Should be NotImplementedError
ics = {f(x).diff(x).subs(x, y): f(0)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(x).diff(x).subs(x, y): 1}
classify_ode(eq, f(x), ics=ics)
def test_classify_sysode():
# Here x is assumed to be x(t) and y as y(t) for simplicity.
# Similarly diff(x,t) and diff(y,y) is assumed to be x1 and y1 respectively.
k, l, m, n = symbols('k, l, m, n', Integer=True)
k1, k2, k3, l1, l2, l3, m1, m2, m3 = symbols('k1, k2, k3, l1, l2, l3, m1, m2, m3', Integer=True)
P, Q, R, p, q, r = symbols('P, Q, R, p, q, r', cls=Function)
P1, P2, P3, Q1, Q2, R1, R2 = symbols('P1, P2, P3, Q1, Q2, R1, R2', cls=Function)
x, y, z = symbols('x, y, z', cls=Function)
t = symbols('t')
x1 = diff(x(t),t) ; y1 = diff(y(t),t) ;
eq6 = (Eq(x1, exp(k*x(t))*P(x(t),y(t))), Eq(y1,r(y(t))*P(x(t),y(t))))
sol6 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \
(1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': 'type2', 'func': \
[x(t), y(t)], 'is_linear': False, 'eq': [-P(x(t), y(t))*exp(k*x(t)) + Derivative(x(t), t), -P(x(t), \
y(t))*r(y(t)) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq6) == sol6
eq7 = (Eq(x1, x(t)**2+y(t)/x(t)), Eq(y1, x(t)/y(t)))
sol7 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \
(1, x(t), 0): -1/y(t), (0, y(t), 1): 0, (0, y(t), 0): -1/x(t), (1, y(t), 1): 1}, 'type_of_equation': 'type3', \
'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)**2 + Derivative(x(t), t) - y(t)/x(t), -x(t)/y(t) + \
Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq7) == sol7
eq8 = (Eq(x1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)), Eq(y1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)))
sol8 = {'func': [x(t), y(t)], 'is_linear': False, 'type_of_equation': 'type4', 'eq': \
[-P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + Derivative(x(t), t), -P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + \
Derivative(y(t), t)], 'func_coeff': {(0, y(t), 1): 0, (1, y(t), 1): 1, (1, x(t), 1): 0, (0, y(t), 0): 0, \
(1, x(t), 0): 0, (0, x(t), 0): 0, (1, y(t), 0): 0, (0, x(t), 1): 1}, 'order': {y(t): 1, x(t): 1}, 'no_of_equation': 2}
assert classify_sysode(eq8) == sol8
eq11 = (Eq(x1,x(t)*y(t)**3), Eq(y1,y(t)**5))
sol11 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)**3, (1, x(t), 1): 0, (0, x(t), 1): 1, \
(1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': \
'type1', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)**3 + Derivative(x(t), t), \
-y(t)**5 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq11) == sol11
eq13 = (Eq(x1,x(t)*y(t)*sin(t)**2), Eq(y1,y(t)**2*sin(t)**2))
sol13 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)*sin(t)**2, (1, x(t), 1): 0, (0, x(t), 1): 1, \
(1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): -x(t)*sin(t)**2, (1, y(t), 1): 1}, \
'type_of_equation': 'type4', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)*sin(t)**2 + \
Derivative(x(t), t), -y(t)**2*sin(t)**2 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}}
assert classify_sysode(eq13) == sol13
def test_solve_ics():
# Basic tests that things work from dsolve.
assert dsolve(f(x).diff(x) - 1/f(x), f(x), ics={f(1): 2}) == \
Eq(f(x), sqrt(2 * x + 2))
assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(0): 1}) == Eq(f(x), exp(x))
assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), exp(x))
assert dsolve(f(x).diff(x, x) + f(x), f(x), ics={f(0): 1,
f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), sin(x) + cos(x))
assert dsolve([f(x).diff(x) - f(x) + g(x), g(x).diff(x) - g(x) - f(x)],
[f(x), g(x)], ics={f(0): 1, g(0): 0}) == [Eq(f(x), exp(x)*cos(x)), Eq(g(x), exp(x)*sin(x))]
# Test cases where dsolve returns two solutions.
eq = (x**2*f(x)**2 - x).diff(x)
assert dsolve(eq, f(x), ics={f(1): 0}) == [Eq(f(x),
-sqrt(x - 1)/x), Eq(f(x), sqrt(x - 1)/x)]
assert dsolve(eq, f(x), ics={f(x).diff(x).subs(x, 1): 0}) == [Eq(f(x),
-sqrt(x - S.Half)/x), Eq(f(x), sqrt(x - S.Half)/x)]
eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x)
assert dsolve(eq, f(x),
ics={f(0):1}, hint='1st_exact', simplify=False) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3))
assert dsolve(eq, f(x),
ics={f(0):1}, hint='1st_exact', simplify=True) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3))
assert solve_ics([Eq(f(x), C1*exp(x))], [f(x)], [C1], {f(0): 1}) == {C1: 1}
assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2],
{f(0): 1, f(pi/2): 1}) == {C1: 1, C2: 1}
assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2],
{f(0): 1, f(x).diff(x).subs(x, 0): 1}) == {C1: 1, C2: 1}
assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1}) == \
{C2: 1}
# Some more complicated tests Refer to PR #16098
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x, 1):0})) == \
{Eq(f(x), 0), Eq(f(x), x ** 3 / 6 - x / 2)}
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0})) == \
{Eq(f(x), 0), Eq(f(x), C2*x + x**3/6)}
K, r, f0 = symbols('K r f0')
sol = Eq(f(x), K*f0*exp(r*x)/((-K + f0)*(f0*exp(r*x)/(-K + f0) - 1)))
assert (dsolve(Eq(f(x).diff(x), r * f(x) * (1 - f(x) / K)), f(x), ics={f(0): f0})) == sol
#Order dependent issues Refer to PR #16098
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(x).diff(x).subs(x,0):0, f(0):0})) == \
{Eq(f(x), 0), Eq(f(x), x ** 3 / 6)}
assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x,0):0})) == \
{Eq(f(x), 0), Eq(f(x), x ** 3 / 6)}
# XXX: Ought to be ValueError
raises(ValueError, lambda: solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(pi): 1}))
# Degenerate case. f'(0) is identically 0.
raises(ValueError, lambda: solve_ics([Eq(f(x), sqrt(C1 - x**2))], [f(x)], [C1], {f(x).diff(x).subs(x, 0): 0}))
EI, q, L = symbols('EI q L')
# eq = Eq(EI*diff(f(x), x, 4), q)
sols = [Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3 + q*x**4/(24*EI))]
funcs = [f(x)]
constants = [C1, C2, C3, C4]
# Test both cases, Derivative (the default from f(x).diff(x).subs(x, L)),
# and Subs
ics1 = {f(0): 0,
f(x).diff(x).subs(x, 0): 0,
f(L).diff(L, 2): 0,
f(L).diff(L, 3): 0}
ics2 = {f(0): 0,
f(x).diff(x).subs(x, 0): 0,
Subs(f(x).diff(x, 2), x, L): 0,
Subs(f(x).diff(x, 3), x, L): 0}
solved_constants1 = solve_ics(sols, funcs, constants, ics1)
solved_constants2 = solve_ics(sols, funcs, constants, ics2)
assert solved_constants1 == solved_constants2 == {
C1: 0,
C2: 0,
C3: L**2*q/(4*EI),
C4: -L*q/(6*EI)}
def test_ode_order():
f = Function('f')
g = Function('g')
x = Symbol('x')
assert ode_order(3*x*exp(f(x)), f(x)) == 0
assert ode_order(x*diff(f(x), x) + 3*x*f(x) - sin(x)/x, f(x)) == 1
assert ode_order(x**2*f(x).diff(x, x) + x*diff(f(x), x) - f(x), f(x)) == 2
assert ode_order(diff(x*exp(f(x)), x, x), f(x)) == 2
assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), f(x)) == 3
assert ode_order(diff(f(x), x, x), g(x)) == 0
assert ode_order(diff(f(x), x, x)*diff(g(x), x), f(x)) == 2
assert ode_order(diff(f(x), x, x)*diff(g(x), x), g(x)) == 1
assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), g(x)) == 0
# issue 5835: ode_order has to also work for unevaluated derivatives
# (ie, without using doit()).
assert ode_order(Derivative(x*f(x), x), f(x)) == 1
assert ode_order(x*sin(Derivative(x*f(x)**2, x, x)), f(x)) == 2
assert ode_order(Derivative(x*Derivative(x*exp(f(x)), x, x), x), g(x)) == 0
assert ode_order(Derivative(f(x), x, x), g(x)) == 0
assert ode_order(Derivative(x*exp(f(x)), x, x), f(x)) == 2
assert ode_order(Derivative(f(x), x, x)*Derivative(g(x), x), g(x)) == 1
assert ode_order(Derivative(x*Derivative(f(x), x, x), x), f(x)) == 3
assert ode_order(
x*sin(Derivative(x*Derivative(f(x), x)**2, x, x)), f(x)) == 3
def test_homogeneous_order():
assert homogeneous_order(exp(y/x) + tan(y/x), x, y) == 0
assert homogeneous_order(x**2 + sin(x)*cos(y), x, y) is None
assert homogeneous_order(x - y - x*sin(y/x), x, y) == 1
assert homogeneous_order((x*y + sqrt(x**4 + y**4) + x**2*(log(x) - log(y)))/
(pi*x**Rational(2, 3)*sqrt(y)**3), x, y) == Rational(-1, 6)
assert homogeneous_order(y/x*cos(y/x) - x/y*sin(y/x) + cos(y/x), x, y) == 0
assert homogeneous_order(f(x), x, f(x)) == 1
assert homogeneous_order(f(x)**2, x, f(x)) == 2
assert homogeneous_order(x*y*z, x, y) == 2
assert homogeneous_order(x*y*z, x, y, z) == 3
assert homogeneous_order(x**2*f(x)/sqrt(x**2 + f(x)**2), f(x)) is None
assert homogeneous_order(f(x, y)**2, x, f(x, y), y) == 2
assert homogeneous_order(f(x, y)**2, x, f(x), y) is None
assert homogeneous_order(f(x, y)**2, x, f(x, y)) is None
assert homogeneous_order(f(y, x)**2, x, y, f(x, y)) is None
assert homogeneous_order(f(y), f(x), x) is None
assert homogeneous_order(-f(x)/x + 1/sin(f(x)/ x), f(x), x) == 0
assert homogeneous_order(log(1/y) + log(x**2), x, y) is None
assert homogeneous_order(log(1/y) + log(x), x, y) == 0
assert homogeneous_order(log(x/y), x, y) == 0
assert homogeneous_order(2*log(1/y) + 2*log(x), x, y) == 0
a = Symbol('a')
assert homogeneous_order(a*log(1/y) + a*log(x), x, y) == 0
assert homogeneous_order(f(x).diff(x), x, y) is None
assert homogeneous_order(-f(x).diff(x) + x, x, y) is None
assert homogeneous_order(O(x), x, y) is None
assert homogeneous_order(x + O(x**2), x, y) is None
assert homogeneous_order(x**pi, x) == pi
assert homogeneous_order(x**x, x) is None
raises(ValueError, lambda: homogeneous_order(x*y))
@XFAIL
def test_noncircularized_real_imaginary_parts():
# If this passes, lines numbered 3878-3882 (at the time of this commit)
# of sympy/solvers/ode.py for nth_linear_constant_coeff_homogeneous
# should be removed.
y = sqrt(1+x)
i, r = im(y), re(y)
assert not (i.has(atan2) and r.has(atan2))
def test_collect_respecting_exponentials():
# If this test passes, lines 1306-1311 (at the time of this commit)
# of sympy/solvers/ode.py should be removed.
sol = 1 + exp(x/2)
assert sol == collect( sol, exp(x/3))
def test_undetermined_coefficients_match():
assert _undetermined_coefficients_match(g(x), x) == {'test': False}
assert _undetermined_coefficients_match(sin(2*x + sqrt(5)), x) == \
{'test': True, 'trialset':
{cos(2*x + sqrt(5)), sin(2*x + sqrt(5))}}
assert _undetermined_coefficients_match(sin(x)*cos(x), x) == \
{'test': False}
s = {cos(x), x*cos(x), x**2*cos(x), x**2*sin(x), x*sin(x), sin(x)}
assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': s}
assert _undetermined_coefficients_match(
sin(x)*x**2 + sin(x)*x + sin(x), x) == {'test': True, 'trialset': s}
assert _undetermined_coefficients_match(
exp(2*x)*sin(x)*(x**2 + x + 1), x
) == {
'test': True, 'trialset': {exp(2*x)*sin(x), x**2*exp(2*x)*sin(x),
cos(x)*exp(2*x), x**2*cos(x)*exp(2*x), x*cos(x)*exp(2*x),
x*exp(2*x)*sin(x)}}
assert _undetermined_coefficients_match(1/sin(x), x) == {'test': False}
assert _undetermined_coefficients_match(log(x), x) == {'test': False}
assert _undetermined_coefficients_match(2**(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': {2**x, x*2**x, x**2*2**x}}
assert _undetermined_coefficients_match(x**y, x) == {'test': False}
assert _undetermined_coefficients_match(exp(x)*exp(2*x + 1), x) == \
{'test': True, 'trialset': {exp(1 + 3*x)}}
assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': {x*cos(x), x*sin(x), x**2*cos(x),
x**2*sin(x), cos(x), sin(x)}}
assert _undetermined_coefficients_match(sin(x)*(x + sin(x)), x) == \
{'test': False}
assert _undetermined_coefficients_match(sin(x)*(x + sin(2*x)), x) == \
{'test': False}
assert _undetermined_coefficients_match(sin(x)*tan(x), x) == \
{'test': False}
assert _undetermined_coefficients_match(
x**2*sin(x)*exp(x) + x*sin(x) + x, x
) == {
'test': True, 'trialset': {x**2*cos(x)*exp(x), x, cos(x), S.One,
exp(x)*sin(x), sin(x), x*exp(x)*sin(x), x*cos(x), x*cos(x)*exp(x),
x*sin(x), cos(x)*exp(x), x**2*exp(x)*sin(x)}}
assert _undetermined_coefficients_match(4*x*sin(x - 2), x) == {
'trialset': {x*cos(x - 2), x*sin(x - 2), cos(x - 2), sin(x - 2)},
'test': True,
}
assert _undetermined_coefficients_match(2**x*x, x) == \
{'test': True, 'trialset': {2**x, x*2**x}}
assert _undetermined_coefficients_match(2**x*exp(2*x), x) == \
{'test': True, 'trialset': {2**x*exp(2*x)}}
assert _undetermined_coefficients_match(exp(-x)/x, x) == \
{'test': False}
# Below are from Ordinary Differential Equations,
# Tenenbaum and Pollard, pg. 231
assert _undetermined_coefficients_match(S(4), x) == \
{'test': True, 'trialset': {S.One}}
assert _undetermined_coefficients_match(12*exp(x), x) == \
{'test': True, 'trialset': {exp(x)}}
assert _undetermined_coefficients_match(exp(I*x), x) == \
{'test': True, 'trialset': {exp(I*x)}}
assert _undetermined_coefficients_match(sin(x), x) == \
{'test': True, 'trialset': {cos(x), sin(x)}}
assert _undetermined_coefficients_match(cos(x), x) == \
{'test': True, 'trialset': {cos(x), sin(x)}}
assert _undetermined_coefficients_match(8 + 6*exp(x) + 2*sin(x), x) == \
{'test': True, 'trialset': {S.One, cos(x), sin(x), exp(x)}}
assert _undetermined_coefficients_match(x**2, x) == \
{'test': True, 'trialset': {S.One, x, x**2}}
assert _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) == \
{'test': True, 'trialset': {x*exp(x), exp(x), exp(-x)}}
assert _undetermined_coefficients_match(2*exp(2*x)*sin(x), x) == \
{'test': True, 'trialset': {exp(2*x)*sin(x), cos(x)*exp(2*x)}}
assert _undetermined_coefficients_match(x - sin(x), x) == \
{'test': True, 'trialset': {S.One, x, cos(x), sin(x)}}
assert _undetermined_coefficients_match(x**2 + 2*x, x) == \
{'test': True, 'trialset': {S.One, x, x**2}}
assert _undetermined_coefficients_match(4*x*sin(x), x) == \
{'test': True, 'trialset': {x*cos(x), x*sin(x), cos(x), sin(x)}}
assert _undetermined_coefficients_match(x*sin(2*x), x) == \
{'test': True, 'trialset':
{x*cos(2*x), x*sin(2*x), cos(2*x), sin(2*x)}}
assert _undetermined_coefficients_match(x**2*exp(-x), x) == \
{'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}}
assert _undetermined_coefficients_match(2*exp(-x) - x**2*exp(-x), x) == \
{'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}}
assert _undetermined_coefficients_match(exp(-2*x) + x**2, x) == \
{'test': True, 'trialset': {S.One, x, x**2, exp(-2*x)}}
assert _undetermined_coefficients_match(x*exp(-x), x) == \
{'test': True, 'trialset': {x*exp(-x), exp(-x)}}
assert _undetermined_coefficients_match(x + exp(2*x), x) == \
{'test': True, 'trialset': {S.One, x, exp(2*x)}}
assert _undetermined_coefficients_match(sin(x) + exp(-x), x) == \
{'test': True, 'trialset': {cos(x), sin(x), exp(-x)}}
assert _undetermined_coefficients_match(exp(x), x) == \
{'test': True, 'trialset': {exp(x)}}
# converted from sin(x)**2
assert _undetermined_coefficients_match(S.Half - cos(2*x)/2, x) == \
{'test': True, 'trialset': {S.One, cos(2*x), sin(2*x)}}
# converted from exp(2*x)*sin(x)**2
assert _undetermined_coefficients_match(
exp(2*x)*(S.Half + cos(2*x)/2), x
) == {
'test': True, 'trialset': {exp(2*x)*sin(2*x), cos(2*x)*exp(2*x),
exp(2*x)}}
assert _undetermined_coefficients_match(2*x + sin(x) + cos(x), x) == \
{'test': True, 'trialset': {S.One, x, cos(x), sin(x)}}
# converted from sin(2*x)*sin(x)
assert _undetermined_coefficients_match(cos(x)/2 - cos(3*x)/2, x) == \
{'test': True, 'trialset': {cos(x), cos(3*x), sin(x), sin(3*x)}}
assert _undetermined_coefficients_match(cos(x**2), x) == {'test': False}
assert _undetermined_coefficients_match(2**(x**2), x) == {'test': False}
def test_issue_4785():
from sympy.abc import A
eq = x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2
assert classify_ode(eq, f(x)) == ('1st_exact', '1st_linear',
'almost_linear', '1st_power_series', 'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_exact_Integral', '1st_linear_Integral', 'almost_linear_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
# issue 4864
eq = (x**2 + f(x)**2)*f(x).diff(x) - 2*x*f(x)
assert classify_ode(eq, f(x)) == ('1st_exact',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series',
'lie_group', '1st_exact_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
def test_issue_4825():
raises(ValueError, lambda: dsolve(f(x, y).diff(x) - y*f(x, y), f(x)))
assert classify_ode(f(x, y).diff(x) - y*f(x, y), f(x), dict=True) == \
{'order': 0, 'default': None, 'ordered_hints': ()}
# See also issue 3793, test Z13.
raises(ValueError, lambda: dsolve(f(x).diff(x), f(y)))
assert classify_ode(f(x).diff(x), f(y), dict=True) == \
{'order': 0, 'default': None, 'ordered_hints': ()}
def test_constant_renumber_order_issue_5308():
from sympy.utilities.iterables import variations
assert constant_renumber(C1*x + C2*y) == \
constant_renumber(C1*y + C2*x) == \
C1*x + C2*y
e = C1*(C2 + x)*(C3 + y)
for a, b, c in variations([C1, C2, C3], 3):
assert constant_renumber(a*(b + x)*(c + y)) == e
def test_constant_renumber():
e1, e2, x, y = symbols("e1:3 x y")
exprs = [e2*x, e1*x + e2*y]
assert constant_renumber(exprs[0]) == e2*x
assert constant_renumber(exprs[0], variables=[x]) == C1*x
assert constant_renumber(exprs[0], variables=[x], newconstants=[C2]) == C2*x
assert constant_renumber(exprs, variables=[x, y]) == [C1*x, C1*y + C2*x]
assert constant_renumber(exprs, variables=[x, y], newconstants=symbols("C3:5")) == [C3*x, C3*y + C4*x]
def test_issue_5770():
k = Symbol("k", real=True)
t = Symbol('t')
w = Function('w')
sol = dsolve(w(t).diff(t, 6) - k**6*w(t), w(t))
assert len([s for s in sol.free_symbols if s.name.startswith('C')]) == 6
assert constantsimp((C1*cos(x) + C2*cos(x))*exp(x), {C1, C2}) == \
C1*cos(x)*exp(x)
assert constantsimp(C1*cos(x) + C2*cos(x) + C3*sin(x), {C1, C2, C3}) == \
C1*cos(x) + C3*sin(x)
assert constantsimp(exp(C1 + x), {C1}) == C1*exp(x)
assert constantsimp(x + C1 + y, {C1, y}) == C1 + x
assert constantsimp(x + C1 + Integral(x, (x, 1, 2)), {C1}) == C1 + x
def test_issue_5112_5430():
assert homogeneous_order(-log(x) + acosh(x), x) is None
assert homogeneous_order(y - log(x), x, y) is None
def test_issue_5095():
f = Function('f')
raises(ValueError, lambda: dsolve(f(x).diff(x)**2, f(x), 'fdsjf'))
def test_homogeneous_function():
f = Function('f')
eq1 = tan(x + f(x))
eq2 = sin((3*x)/(4*f(x)))
eq3 = cos(x*f(x)*Rational(3, 4))
eq4 = log((3*x + 4*f(x))/(5*f(x) + 7*x))
eq5 = exp((2*x**2)/(3*f(x)**2))
eq6 = log((3*x + 4*f(x))/(5*f(x) + 7*x) + exp((2*x**2)/(3*f(x)**2)))
eq7 = sin((3*x)/(5*f(x) + x**2))
assert homogeneous_order(eq1, x, f(x)) == None
assert homogeneous_order(eq2, x, f(x)) == 0
assert homogeneous_order(eq3, x, f(x)) == None
assert homogeneous_order(eq4, x, f(x)) == 0
assert homogeneous_order(eq5, x, f(x)) == 0
assert homogeneous_order(eq6, x, f(x)) == 0
assert homogeneous_order(eq7, x, f(x)) == None
def test_linear_coeff_match():
n, d = z*(2*x + 3*f(x) + 5), z*(7*x + 9*f(x) + 11)
rat = n/d
eq1 = sin(rat) + cos(rat.expand())
eq2 = rat
eq3 = log(sin(rat))
ans = (4, Rational(-13, 3))
assert _linear_coeff_match(eq1, f(x)) == ans
assert _linear_coeff_match(eq2, f(x)) == ans
assert _linear_coeff_match(eq3, f(x)) == ans
# no c
eq4 = (3*x)/f(x)
# not x and f(x)
eq5 = (3*x + 2)/x
# denom will be zero
eq6 = (3*x + 2*f(x) + 1)/(3*x + 2*f(x) + 5)
# not rational coefficient
eq7 = (3*x + 2*f(x) + sqrt(2))/(3*x + 2*f(x) + 5)
assert _linear_coeff_match(eq4, f(x)) is None
assert _linear_coeff_match(eq5, f(x)) is None
assert _linear_coeff_match(eq6, f(x)) is None
assert _linear_coeff_match(eq7, f(x)) is None
def test_constantsimp_take_problem():
c = exp(C1) + 2
assert len(Poly(constantsimp(exp(C1) + c + c*x, [C1])).gens) == 2
def test_series():
C1 = Symbol("C1")
eq = f(x).diff(x) - f(x)
sol = Eq(f(x), C1 + C1*x + C1*x**2/2 + C1*x**3/6 + C1*x**4/24 +
C1*x**5/120 + O(x**6))
assert dsolve(eq, hint='1st_power_series') == sol
assert checkodesol(eq, sol, order=1)[0]
eq = f(x).diff(x) - x*f(x)
sol = Eq(f(x), C1*x**4/8 + C1*x**2/2 + C1 + O(x**6))
assert dsolve(eq, hint='1st_power_series') == sol
assert checkodesol(eq, sol, order=1)[0]
eq = f(x).diff(x) - sin(x*f(x))
sol = Eq(f(x), (x - 2)**2*(1+ sin(4))*cos(4) + (x - 2)*sin(4) + 2 + O(x**3))
assert dsolve(eq, hint='1st_power_series', ics={f(2): 2}, n=3) == sol
# FIXME: The solution here should be O((x-2)**3) so is incorrect
#assert checkodesol(eq, sol, order=1)[0]
@slow
def test_2nd_power_series_ordinary():
C1, C2 = symbols("C1 C2")
eq = f(x).diff(x, 2) - x*f(x)
assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary')
sol = Eq(f(x), C2*(x**3/6 + 1) + C1*x*(x**3/12 + 1) + O(x**6))
assert dsolve(eq, hint='2nd_power_series_ordinary') == sol
assert checkodesol(eq, sol) == (True, 0)
sol = Eq(f(x), C2*((x + 2)**4/6 + (x + 2)**3/6 - (x + 2)**2 + 1)
+ C1*(x + (x + 2)**4/12 - (x + 2)**3/3 + S(2))
+ O(x**6))
assert dsolve(eq, hint='2nd_power_series_ordinary', x0=-2) == sol
# FIXME: Solution should be O((x+2)**6)
# assert checkodesol(eq, sol) == (True, 0)
sol = Eq(f(x), C2*x + C1 + O(x**2))
assert dsolve(eq, hint='2nd_power_series_ordinary', n=2) == sol
assert checkodesol(eq, sol) == (True, 0)
eq = (1 + x**2)*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) -2*f(x)
assert classify_ode(eq) == ('2nd_power_series_ordinary',)
sol = Eq(f(x), C2*(-x**4/3 + x**2 + 1) + C1*x + O(x**6))
assert dsolve(eq) == sol
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + x*(f(x).diff(x)) + f(x)
assert classify_ode(eq) == ('2nd_power_series_ordinary',)
sol = Eq(f(x), C2*(x**4/8 - x**2/2 + 1) + C1*x*(-x**2/3 + 1) + O(x**6))
assert dsolve(eq) == sol
# FIXME: checkodesol fails for this solution...
# assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + f(x).diff(x) - x*f(x)
assert classify_ode(eq) == ('2nd_power_series_ordinary',)
sol = Eq(f(x), C2*(-x**4/24 + x**3/6 + 1)
+ C1*x*(x**3/24 + x**2/6 - x/2 + 1) + O(x**6))
assert dsolve(eq) == sol
# FIXME: checkodesol fails for this solution...
# assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + x*f(x)
assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary')
sol = Eq(f(x), C2*(x**6/180 - x**3/6 + 1) + C1*x*(-x**3/12 + 1) + O(x**7))
assert dsolve(eq, hint='2nd_power_series_ordinary', n=7) == sol
assert checkodesol(eq, sol) == (True, 0)
def test_2nd_power_series_regular():
C1, C2, a = symbols("C1 C2 a")
eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x)
sol = Eq(f(x), C1*x**2*(-16*x**3/9 + 4*x**2 - 4*x + 1) + O(x**6))
assert dsolve(eq, hint='2nd_power_series_regular') == sol
assert checkodesol(eq, sol) == (True, 0)
eq = 4*x**2*(f(x).diff(x, 2)) -8*x**2*(f(x).diff(x)) + (4*x**2 +
1)*f(x)
sol = Eq(f(x), C1*sqrt(x)*(x**4/24 + x**3/6 + x**2/2 + x + 1) + O(x**6))
assert dsolve(eq, hint='2nd_power_series_regular') == sol
assert checkodesol(eq, sol) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) - x**2*(f(x).diff(x)) + (
x**2 - 2)*f(x)
sol = Eq(f(x), C1*(-x**6/720 - 3*x**5/80 - x**4/8 + x**2/2 + x/2 + 1)/x +
C2*x**2*(-x**3/60 + x**2/20 + x/2 + 1) + O(x**6))
assert dsolve(eq) == sol
assert checkodesol(eq, sol) == (True, 0)
eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - Rational(1, 4))*f(x)
sol = Eq(f(x), C1*(x**4/24 - x**2/2 + 1)/sqrt(x) +
C2*sqrt(x)*(x**4/120 - x**2/6 + 1) + O(x**6))
assert dsolve(eq, hint='2nd_power_series_regular') == sol
assert checkodesol(eq, sol) == (True, 0)
eq = x*f(x).diff(x, 2) + f(x).diff(x) - a*x*f(x)
sol = Eq(f(x), C1*(a**2*x**4/64 + a*x**2/4 + 1) + O(x**6))
assert dsolve(eq, f(x), hint="2nd_power_series_regular") == sol
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + ((1 - x)/x)*f(x).diff(x) + (a/x)*f(x)
sol = Eq(f(x), C1*(-a*x**5*(a - 4)*(a - 3)*(a - 2)*(a - 1)/14400 + \
a*x**4*(a - 3)*(a - 2)*(a - 1)/576 - a*x**3*(a - 2)*(a - 1)/36 + \
a*x**2*(a - 1)/4 - a*x + 1) + O(x**6))
assert dsolve(eq, f(x), hint="2nd_power_series_regular") == sol
assert checkodesol(eq, sol) == (True, 0)
def test_issue_15056():
t = Symbol('t')
C3 = Symbol('C3')
assert get_numbered_constants(Symbol('C1') * Function('C2')(t)) == C3
def test_issue_15913():
eq = -C1/x - 2*x*f(x) - f(x) + Derivative(f(x), x)
sol = C2*exp(x**2 + x) + exp(x**2 + x)*Integral(C1*exp(-x**2 - x)/x, x)
assert checkodesol(eq, sol) == (True, 0)
sol = C1 + C2*exp(-x*y)
eq = Derivative(y*f(x), x) + f(x).diff(x, 2)
assert checkodesol(eq, sol, f(x)) == (True, 0)
def test_issue_16146():
raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x), g(x), h(x)]))
raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x)]))
def test_dsolve_remove_redundant_solutions():
eq = (f(x)-2)*f(x).diff(x)
sol = Eq(f(x), C1)
assert dsolve(eq) == sol
eq = (f(x)-sin(x))*(f(x).diff(x, 2))
sol = {Eq(f(x), C1 + C2*x), Eq(f(x), sin(x))}
assert set(dsolve(eq)) == sol
eq = (f(x)**2-2*f(x)+1)*f(x).diff(x, 3)
sol = Eq(f(x), C1 + C2*x + C3*x**2)
assert dsolve(eq) == sol
def test_issue_13060():
A, B = symbols("A B", cls=Function)
t = Symbol("t")
eq = [Eq(Derivative(A(t), t), A(t)*B(t)), Eq(Derivative(B(t), t), A(t)*B(t))]
sol = dsolve(eq)
assert checkodesol(eq, sol) == (True, [0, 0])
|
c633005bca52cec9d86b9d71442753f94274152cb593cdbec7987de74a814c11 | #
# The main tests for the code in single.py are currently located in
# sympy/solvers/tests/test_ode.py
#
r"""
This File contains test functions for the individual hints used for solving ODEs.
Examples of each solver will be returned by _get_examples_ode_sol_name_of_solver.
Examples should have a key 'XFAIL' which stores the list of hints if they are
expected to fail for that hint.
Functions that are for internal use:
1) _ode_solver_test(ode_examples) - It takes a dictionary of examples returned by
_get_examples method and tests them with their respective hints.
2) _test_particular_example(our_hint, example_name) - It tests the ODE example corresponding
to the hint provided.
3) _test_all_hints(runxfail=False) - It is used to test all the examples with all the hints
currently implemented. It calls _test_all_examples_for_one_hint() which outputs whether the
given hint functions properly if it classifies the ODE example.
If runxfail flag is set to True then it will only test the examples which are expected to fail.
Everytime the ODE of a particular solver is added, _test_all_hints() is to be executed to find
the possible failures of different solver hints.
4) _test_all_examples_for_one_hint(our_hint, all_examples) - It takes hint as argument and checks
this hint against all the ODE examples and gives output as the number of ODEs matched, number
of ODEs which were solved correctly, list of ODEs which gives incorrect solution and list of
ODEs which raises exception.
"""
from sympy import (acos, acosh, asin, asinh, atan, cos, Derivative, Dummy, diff, cbrt,
E, Eq, exp, hyper, I, im, Integral, integrate, LambertW, log, Mul, Ne, pi, Piecewise, Rational,
re, rootof, S, sin, sinh, cosh, tan, tanh, sec, sqrt, symbols, Ei, erfi)
from sympy.core import Function, Symbol
from sympy.functions import airyai, airybi, besselj, bessely, lowergamma
from sympy.integrals.risch import NonElementaryIntegral
from sympy.solvers.ode import classify_ode, dsolve
from sympy.solvers.ode.ode import allhints, _remove_redundant_solutions
from sympy.solvers.ode.single import (FirstLinear, ODEMatchError,
SingleODEProblem, SingleODESolver)
from sympy.solvers.ode.subscheck import checkodesol
from sympy.testing.pytest import raises, slow, ON_TRAVIS
import traceback
x = Symbol('x')
u = Symbol('u')
_u = Dummy('u')
y = Symbol('y')
f = Function('f')
g = Function('g')
C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C1:11')
hint_message = """\
Hint did not match the example {example}.
The ODE is:
{eq}.
The expected hint was
{our_hint}\
"""
expected_sol_message = """\
Different solution found from dsolve for example {example}.
The ODE is:
{eq}
The expected solution was
{sol}
What dsolve returned is:
{dsolve_sol}\
"""
checkodesol_msg = """\
solution found is not correct for example {example}.
The ODE is:
{eq}\
"""
dsol_incorrect_msg = """\
solution returned by dsolve is incorrect when using {hint}.
The ODE is:
{eq}
The expected solution was
{sol}
what dsolve returned is:
{dsolve_sol}
You can test this with:
eq = {eq}
sol = dsolve(eq, hint='{hint}')
print(sol)
print(checkodesol(eq, sol))
"""
exception_msg = """\
dsolve raised exception : {e}
when using {hint} for the example {example}
You can test this with:
from sympy.solvers.ode.tests.test_single import _test_an_example
_test_an_example('{hint}', example_name = '{example}')
The ODE is:
{eq}
\
"""
check_hint_msg = """\
Tested hint was : {hint}
Total of {matched} examples matched with this hint.
Out of which {solve} gave correct results.
Examples which gave incorrect results are {unsolve}.
Examples which raised exceptions are {exceptions}
\
"""
def _add_example_keys(func):
def inner():
solver=func()
examples=[]
for example in solver['examples']:
temp={
'eq': solver['examples'][example]['eq'],
'sol': solver['examples'][example]['sol'],
'XFAIL': solver['examples'][example].get('XFAIL', []),
'func': solver['examples'][example].get('func',solver['func']),
'example_name': example,
'slow': solver['examples'][example].get('slow', False),
'simplify_flag':solver['examples'][example].get('simplify_flag',True),
'checkodesol_XFAIL': solver['examples'][example].get('checkodesol_XFAIL', False),
'dsolve_too_slow':solver['examples'][example].get('dsolve_too_slow',False),
'checkodesol_too_slow':solver['examples'][example].get('checkodesol_too_slow',False),
'hint': solver['hint']
}
examples.append(temp)
return examples
return inner()
def _ode_solver_test(ode_examples, run_slow_test=False):
for example in ode_examples:
if ((not run_slow_test) and example['slow']) or (run_slow_test and (not example['slow'])):
continue
result = _test_particular_example(example['hint'], example, solver_flag=True)
if result['xpass_msg'] != "":
print(result['xpass_msg'])
def _test_all_hints(runxfail=False):
all_hints = list(allhints)+["default"]
all_examples = _get_all_examples()
for our_hint in all_hints:
if our_hint.endswith('_Integral') or 'series' in our_hint:
continue
_test_all_examples_for_one_hint(our_hint, all_examples, runxfail)
def _test_dummy_sol(expected_sol,dsolve_sol):
if type(dsolve_sol)==list:
return any(expected_sol.dummy_eq(sub_dsol) for sub_dsol in dsolve_sol)
else:
return expected_sol.dummy_eq(dsolve_sol)
def _test_an_example(our_hint, example_name):
all_examples = _get_all_examples()
for example in all_examples:
if example['example_name'] == example_name:
_test_particular_example(our_hint, example)
def _test_particular_example(our_hint, ode_example, solver_flag=False):
eq = ode_example['eq']
expected_sol = ode_example['sol']
example = ode_example['example_name']
xfail = our_hint in ode_example['XFAIL']
func = ode_example['func']
result = {'msg': '', 'xpass_msg': ''}
simplify_flag=ode_example['simplify_flag']
checkodesol_XFAIL = ode_example['checkodesol_XFAIL']
dsolve_too_slow = ode_example['dsolve_too_slow']
checkodesol_too_slow = ode_example['checkodesol_too_slow']
xpass = True
if solver_flag:
if our_hint not in classify_ode(eq, func):
message = hint_message.format(example=example, eq=eq, our_hint=our_hint)
raise AssertionError(message)
if our_hint in classify_ode(eq, func):
result['match_list'] = example
try:
if not (dsolve_too_slow):
dsolve_sol = dsolve(eq, func, simplify=simplify_flag,hint=our_hint)
else:
if len(expected_sol)==1:
dsolve_sol = expected_sol[0]
else:
dsolve_sol = expected_sol
except Exception as e:
dsolve_sol = []
result['exception_list'] = example
if not solver_flag:
traceback.print_exc()
result['msg'] = exception_msg.format(e=str(e), hint=our_hint, example=example, eq=eq)
if solver_flag and not xfail:
print(result['msg'])
raise
xpass = False
if solver_flag and dsolve_sol!=[]:
expect_sol_check = False
if type(dsolve_sol)==list:
for sub_sol in expected_sol:
if sub_sol.has(Dummy):
expect_sol_check = not _test_dummy_sol(sub_sol, dsolve_sol)
else:
expect_sol_check = sub_sol not in dsolve_sol
if expect_sol_check:
break
else:
expect_sol_check = dsolve_sol not in expected_sol
for sub_sol in expected_sol:
if sub_sol.has(Dummy):
expect_sol_check = not _test_dummy_sol(sub_sol, dsolve_sol)
if expect_sol_check:
message = expected_sol_message.format(example=example, eq=eq, sol=expected_sol, dsolve_sol=dsolve_sol)
raise AssertionError(message)
expected_checkodesol = [(True, 0) for i in range(len(expected_sol))]
if len(expected_sol) == 1:
expected_checkodesol = (True, 0)
if not (checkodesol_too_slow and ON_TRAVIS):
if not checkodesol_XFAIL:
if checkodesol(eq, dsolve_sol, func, solve_for_func=False) != expected_checkodesol:
result['unsolve_list'] = example
xpass = False
message = dsol_incorrect_msg.format(hint=our_hint, eq=eq, sol=expected_sol,dsolve_sol=dsolve_sol)
if solver_flag:
message = checkodesol_msg.format(example=example, eq=eq)
raise AssertionError(message)
else:
result['msg'] = 'AssertionError: ' + message
if xpass and xfail:
result['xpass_msg'] = example + "is now passing for the hint" + our_hint
return result
def _test_all_examples_for_one_hint(our_hint, all_examples=[], runxfail=None):
if all_examples == []:
all_examples = _get_all_examples()
match_list, unsolve_list, exception_list = [], [], []
for ode_example in all_examples:
xfail = our_hint in ode_example['XFAIL']
if runxfail and not xfail:
continue
if xfail:
continue
result = _test_particular_example(our_hint, ode_example)
match_list += result.get('match_list',[])
unsolve_list += result.get('unsolve_list',[])
exception_list += result.get('exception_list',[])
if runxfail is not None:
msg = result['msg']
if msg!='':
print(result['msg'])
# print(result.get('xpass_msg',''))
if runxfail is None:
match_count = len(match_list)
solved = len(match_list)-len(unsolve_list)-len(exception_list)
msg = check_hint_msg.format(hint=our_hint, matched=match_count, solve=solved, unsolve=unsolve_list, exceptions=exception_list)
print(msg)
def test_SingleODESolver():
# Test that not implemented methods give NotImplementedError
# Subclasses should override these methods.
problem = SingleODEProblem(f(x).diff(x), f(x), x)
solver = SingleODESolver(problem)
raises(NotImplementedError, lambda: solver.matches())
raises(NotImplementedError, lambda: solver.get_general_solution())
raises(NotImplementedError, lambda: solver._matches())
raises(NotImplementedError, lambda: solver._get_general_solution())
# This ODE can not be solved by the FirstLinear solver. Here we test that
# it does not match and the asking for a general solution gives
# ODEMatchError
problem = SingleODEProblem(f(x).diff(x) + f(x)*f(x), f(x), x)
solver = FirstLinear(problem)
raises(ODEMatchError, lambda: solver.get_general_solution())
solver = FirstLinear(problem)
assert solver.matches() is False
#These are just test for order of ODE
problem = SingleODEProblem(f(x).diff(x) + f(x), f(x), x)
assert problem.order == 1
problem = SingleODEProblem(f(x).diff(x,4) + f(x).diff(x,2) - f(x).diff(x,3), f(x), x)
assert problem.order == 4
problem = SingleODEProblem(f(x).diff(x, 3) + f(x).diff(x, 2) - f(x)**2, f(x), x)
assert problem.is_autonomous == True
problem = SingleODEProblem(f(x).diff(x, 3) + x*f(x).diff(x, 2) - f(x)**2, f(x), x)
assert problem.is_autonomous == False
def test_linear_coefficients():
_ode_solver_test(_get_examples_ode_sol_linear_coefficients)
def test_1st_homogeneous_coeff_ode():
#These were marked as test_1st_homogeneous_coeff_corner_case
eq1 = f(x).diff(x) - f(x)/x
c1 = classify_ode(eq1, f(x))
eq2 = x*f(x).diff(x) - f(x)
c2 = classify_ode(eq2, f(x))
sdi = "1st_homogeneous_coeff_subs_dep_div_indep"
sid = "1st_homogeneous_coeff_subs_indep_div_dep"
assert sid not in c1 and sdi not in c1
assert sid not in c2 and sdi not in c2
_ode_solver_test(_get_examples_ode_sol_1st_homogeneous_coeff_subs_dep_div_indep)
_ode_solver_test(_get_examples_ode_sol_1st_homogeneous_coeff_best)
@slow
def test_slow_examples_1st_homogeneous_coeff_ode():
_ode_solver_test(_get_examples_ode_sol_1st_homogeneous_coeff_subs_dep_div_indep, run_slow_test=True)
_ode_solver_test(_get_examples_ode_sol_1st_homogeneous_coeff_best, run_slow_test=True)
def test_nth_linear_constant_coeff_homogeneous():
_ode_solver_test(_get_examples_ode_sol_nth_linear_constant_coeff_homogeneous)
@slow
def test_slow_examples_nth_linear_constant_coeff_homogeneous():
_ode_solver_test(_get_examples_ode_sol_nth_linear_constant_coeff_homogeneous, run_slow_test=True)
def test_Airy_equation():
_ode_solver_test(_get_examples_ode_sol_2nd_linear_airy)
def test_lie_group():
_ode_solver_test(_get_examples_ode_sol_lie_group)
def test_separable_reduced():
df = f(x).diff(x)
eq = (x / f(x))*df + tan(x**2*f(x) / (x**2*f(x) - 1))
assert classify_ode(eq) == ('separable_reduced', 'lie_group',
'separable_reduced_Integral')
_ode_solver_test(_get_examples_ode_sol_separable_reduced)
@slow
def test_slow_examples_separable_reduced():
_ode_solver_test(_get_examples_ode_sol_separable_reduced, run_slow_test=True)
def test_2nd_2F1_hypergeometric():
_ode_solver_test(_get_examples_ode_sol_2nd_2F1_hypergeometric)
def test_2nd_2F1_hypergeometric_integral():
eq = x*(x-1)*f(x).diff(x, 2) + (-1+ S(7)/2*x)*f(x).diff(x) + f(x)
sol = Eq(f(x), (C1 + C2*Integral(exp(Integral((1 - x/2)/(x*(x - 1)), x))/(1 -
x/2)**2, x))*exp(Integral(1/(x - 1), x)/4)*exp(-Integral(7/(x -
1), x)/4)*hyper((S(1)/2, -1), (1,), x))
assert sol == dsolve(eq, hint='2nd_hypergeometric_Integral')
assert checkodesol(eq, sol) == (True, 0)
def test_2nd_nonlinear_autonomous_conserved():
_ode_solver_test(_get_examples_ode_sol_2nd_nonlinear_autonomous_conserved)
def test_2nd_nonlinear_autonomous_conserved_integral():
eq = f(x).diff(x, 2) + asin(f(x))
actual = [Eq(Integral(1/sqrt(C1 - 2*Integral(asin(_u), _u)), (_u, f(x))), C2 + x),
Eq(Integral(1/sqrt(C1 - 2*Integral(asin(_u), _u)), (_u, f(x))), C2 - x)]
solved = dsolve(eq, hint='2nd_nonlinear_autonomous_conserved_Integral', simplify=False)
for a,s in zip(actual, solved):
assert a.dummy_eq(s)
# checkodesol unable to simplify solutions with f(x) in an integral equation
assert checkodesol(eq, [s.doit() for s in solved]) == [(True, 0), (True, 0)]
def test_2nd_linear_bessel_equation():
_ode_solver_test(_get_examples_ode_sol_2nd_linear_bessel)
def test_nth_algebraic():
eqn = f(x) + f(x)*f(x).diff(x)
solns = [Eq(f(x), exp(x)),
Eq(f(x), C1*exp(C2*x))]
solns_final = _remove_redundant_solutions(eqn, solns, 2, x)
assert solns_final == [Eq(f(x), C1*exp(C2*x))]
_ode_solver_test(_get_examples_ode_sol_nth_algebraic)
@slow
def test_slow_examples_nth_linear_constant_coeff_var_of_parameters():
_ode_solver_test(_get_examples_ode_sol_nth_linear_var_of_parameters, run_slow_test=True)
def test_nth_linear_constant_coeff_var_of_parameters():
_ode_solver_test(_get_examples_ode_sol_nth_linear_var_of_parameters)
@slow
def test_nth_linear_constant_coeff_variation_of_parameters__integral():
# solve_variation_of_parameters shouldn't attempt to simplify the
# Wronskian if simplify=False. If wronskian() ever gets good enough
# to simplify the result itself, this test might fail.
our_hint = 'nth_linear_constant_coeff_variation_of_parameters_Integral'
eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x)
sol_simp = dsolve(eq, f(x), hint=our_hint, simplify=True)
sol_nsimp = dsolve(eq, f(x), hint=our_hint, simplify=False)
assert sol_simp != sol_nsimp
assert checkodesol(eq, sol_simp, order=5, solve_for_func=False) == (True, 0)
assert checkodesol(eq, sol_simp, order=5, solve_for_func=False) == (True, 0)
@slow
def test_slow_examples_1st_exact():
_ode_solver_test(_get_examples_ode_sol_1st_exact, run_slow_test=True)
def test_1st_exact():
_ode_solver_test(_get_examples_ode_sol_1st_exact)
def test_1st_exact_integral():
eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x)
sol_1 = dsolve(eq, f(x), simplify=False, hint='1st_exact_Integral')
assert checkodesol(eq, sol_1, order=1, solve_for_func=False)
@slow
def test_slow_examples_nth_order_reducible():
_ode_solver_test(_get_examples_ode_sol_nth_order_reducible, run_slow_test=True)
@slow
def test_slow_examples_nth_linear_constant_coeff_undetermined_coefficients():
_ode_solver_test(_get_examples_ode_sol_nth_linear_undetermined_coefficients, run_slow_test=True)
@slow
def test_slow_examples_separable():
_ode_solver_test(_get_examples_ode_sol_separable, run_slow_test=True)
def test_nth_linear_constant_coeff_undetermined_coefficients():
#issue-https://github.com/sympy/sympy/issues/5787
# This test case is to show the classification of imaginary constants under
# nth_linear_constant_coeff_undetermined_coefficients
eq = Eq(diff(f(x), x), I*f(x) + S.Half - I)
our_hint = 'nth_linear_constant_coeff_undetermined_coefficients'
assert our_hint in classify_ode(eq)
_ode_solver_test(_get_examples_ode_sol_nth_linear_undetermined_coefficients)
def test_nth_order_reducible():
from sympy.solvers.ode.ode import _nth_order_reducible_match
F = lambda eq: _nth_order_reducible_match(eq, f(x))
D = Derivative
assert F(D(y*f(x), x, y) + D(f(x), x)) is None
assert F(D(y*f(y), y, y) + D(f(y), y)) is None
assert F(f(x)*D(f(x), x) + D(f(x), x, 2)) is None
assert F(D(x*f(y), y, 2) + D(u*y*f(x), x, 3)) is None # no simplification by design
assert F(D(f(y), y, 2) + D(f(y), y, 3) + D(f(x), x, 4)) is None
assert F(D(f(x), x, 2) + D(f(x), x, 3)) == dict(n=2)
_ode_solver_test(_get_examples_ode_sol_nth_order_reducible)
def test_separable():
_ode_solver_test(_get_examples_ode_sol_separable)
def test_factorable():
assert integrate(-asin(f(2*x)+pi), x) == -Integral(asin(pi + f(2*x)), x)
_ode_solver_test(_get_examples_ode_sol_factorable)
def test_Riccati_special_minus2():
_ode_solver_test(_get_examples_ode_sol_riccati)
def test_Bernoulli():
_ode_solver_test(_get_examples_ode_sol_bernoulli)
def test_1st_linear():
_ode_solver_test(_get_examples_ode_sol_1st_linear)
def test_almost_linear():
_ode_solver_test(_get_examples_ode_sol_almost_linear)
def test_Liouville_ODE():
hint = 'Liouville'
not_Liouville1 = classify_ode(diff(f(x), x)/x + f(x)*diff(f(x), x, x)/2 -
diff(f(x), x)**2/2, f(x))
not_Liouville2 = classify_ode(diff(f(x), x)/x + diff(f(x), x, x)/2 -
x*diff(f(x), x)**2/2, f(x))
assert hint not in not_Liouville1
assert hint not in not_Liouville2
assert hint + '_Integral' not in not_Liouville1
assert hint + '_Integral' not in not_Liouville2
_ode_solver_test(_get_examples_ode_sol_liouville)
def test_nth_order_linear_euler_eq_homogeneous():
x, t, a, b, c = symbols('x t a b c')
y = Function('y')
our_hint = "nth_linear_euler_eq_homogeneous"
eq = diff(f(t), t, 4)*t**4 - 13*diff(f(t), t, 2)*t**2 + 36*f(t)
assert our_hint in classify_ode(eq)
eq = a*y(t) + b*t*diff(y(t), t) + c*t**2*diff(y(t), t, 2)
assert our_hint in classify_ode(eq)
_ode_solver_test(_get_examples_ode_sol_euler_homogeneous)
def test_nth_order_linear_euler_eq_nonhomogeneous_undetermined_coefficients():
x, t = symbols('x t')
a, b, c, d = symbols('a b c d', integer=True)
our_hint = "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients"
eq = x**4*diff(f(x), x, 4) - 13*x**2*diff(f(x), x, 2) + 36*f(x) + x
assert our_hint in classify_ode(eq, f(x))
eq = a*x**2*diff(f(x), x, 2) + b*x*diff(f(x), x) + c*f(x) + d*log(x)
assert our_hint in classify_ode(eq, f(x))
_ode_solver_test(_get_examples_ode_sol_euler_undetermined_coeff)
def test_nth_order_linear_euler_eq_nonhomogeneous_variation_of_parameters():
x, t = symbols('x, t')
a, b, c, d = symbols('a, b, c, d', integer=True)
our_hint = "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters"
eq = Eq(x**2*diff(f(x),x,2) - 8*x*diff(f(x),x) + 12*f(x), x**2)
assert our_hint in classify_ode(eq, f(x))
eq = Eq(a*x**3*diff(f(x),x,3) + b*x**2*diff(f(x),x,2) + c*x*diff(f(x),x) + d*f(x), x*log(x))
assert our_hint in classify_ode(eq, f(x))
_ode_solver_test(_get_examples_ode_sol_euler_var_para)
@_add_example_keys
def _get_examples_ode_sol_euler_homogeneous():
r1, r2, r3, r4, r5 = [rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, n) for n in range(5)]
return {
'hint': "nth_linear_euler_eq_homogeneous",
'func': f(x),
'examples':{
'euler_hom_01': {
'eq': Eq(-3*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0),
'sol': [Eq(f(x), C1 + C2*x**Rational(5, 2))],
},
'euler_hom_02': {
'eq': Eq(3*f(x) - 5*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0),
'sol': [Eq(f(x), C1*sqrt(x) + C2*x**3)]
},
'euler_hom_03': {
'eq': Eq(4*f(x) + 5*diff(f(x), x)*x + x**2*diff(f(x), x, x), 0),
'sol': [Eq(f(x), (C1 + C2*log(x))/x**2)]
},
'euler_hom_04': {
'eq': Eq(6*f(x) - 6*diff(f(x), x)*x + 1*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0),
'sol': [Eq(f(x), C1/x**2 + C2*x + C3*x**3)]
},
'euler_hom_05': {
'eq': Eq(-125*f(x) + 61*diff(f(x), x)*x - 12*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0),
'sol': [Eq(f(x), x**5*(C1 + C2*log(x) + C3*log(x)**2))]
},
'euler_hom_06': {
'eq': x**2*diff(f(x), x, 2) + x*diff(f(x), x) - 9*f(x),
'sol': [Eq(f(x), C1*x**-3 + C2*x**3)]
},
'euler_hom_07': {
'eq': sin(x)*x**2*f(x).diff(x, 2) + sin(x)*x*f(x).diff(x) + sin(x)*f(x),
'sol': [Eq(f(x), C1*sin(log(x)) + C2*cos(log(x)))],
'XFAIL': ['2nd_power_series_regular','nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients']
},
'euler_hom_08': {
'eq': x**6 * f(x).diff(x, 6) - x*f(x).diff(x) + f(x),
'sol': [Eq(f(x), C1*x + C2*x**r1 + C3*x**r2 + C4*x**r3 + C5*x**r4 + C6*x**r5)],
'checkodesol_XFAIL':True
},
#This example is from issue: https://github.com/sympy/sympy/issues/15237 #This example is from issue:
# https://github.com/sympy/sympy/issues/15237
'euler_hom_09': {
'eq': Derivative(x*f(x), x, x, x),
'sol': [Eq(f(x), C1 + C2/x + C3*x)],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_euler_undetermined_coeff():
return {
'hint': "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients",
'func': f(x),
'examples':{
'euler_undet_01': {
'eq': Eq(x**2*diff(f(x), x, x) + x*diff(f(x), x), 1),
'sol': [Eq(f(x), C1 + C2*log(x) + log(x)**2/2)]
},
'euler_undet_02': {
'eq': Eq(x**2*diff(f(x), x, x) - 2*x*diff(f(x), x) + 2*f(x), x**3),
'sol': [Eq(f(x), x*(C1 + C2*x + Rational(1, 2)*x**2))]
},
'euler_undet_03': {
'eq': Eq(x**2*diff(f(x), x, x) - x*diff(f(x), x) - 3*f(x), log(x)/x),
'sol': [Eq(f(x), (C1 + C2*x**4 - log(x)**2/8 - log(x)/16)/x)]
},
'euler_undet_04': {
'eq': Eq(x**2*diff(f(x), x, x) + 3*x*diff(f(x), x) - 8*f(x), log(x)**3 - log(x)),
'sol': [Eq(f(x), C1/x**4 + C2*x**2 - Rational(1,8)*log(x)**3 - Rational(3,32)*log(x)**2 - Rational(1,64)*log(x) - Rational(7, 256))]
},
'euler_undet_05': {
'eq': Eq(x**3*diff(f(x), x, x, x) - 3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), log(x)),
'sol': [Eq(f(x), C1*x + C2*x**2 + C3*x**3 - Rational(1, 6)*log(x) - Rational(11, 36))]
},
#Below examples were added for the issue: https://github.com/sympy/sympy/issues/5096
'euler_undet_06': {
'eq': 2*x**2*f(x).diff(x, 2) + f(x) + sqrt(2*x)*sin(log(2*x)/2),
'sol': [Eq(f(x), sqrt(x)*(C1*sin(log(x)/2) + C2*cos(log(x)/2) + sqrt(2)*log(x)*cos(log(2*x)/2)/2))]
},
'euler_undet_07': {
'eq': 2*x**2*f(x).diff(x, 2) + f(x) + sin(log(2*x)/2),
'sol': [Eq(f(x), C1*sqrt(x)*sin(log(x)/2) + C2*sqrt(x)*cos(log(x)/2) - 2*sin(log(2*x)/2)/5 - 4*cos(log(2*x)/2)/5)]
},
}
}
@_add_example_keys
def _get_examples_ode_sol_euler_var_para():
return {
'hint': "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters",
'func': f(x),
'examples':{
'euler_var_01': {
'eq': Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4),
'sol': [Eq(f(x), x*(C1 + C2*x + x**3/6))]
},
'euler_var_02': {
'eq': Eq(3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), x**3*exp(x)),
'sol': [Eq(f(x), C1/x**2 + C2*x + x*exp(x)/3 - 4*exp(x)/3 + 8*exp(x)/(3*x) - 8*exp(x)/(3*x**2))]
},
'euler_var_03': {
'eq': Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4*exp(x)),
'sol': [Eq(f(x), x*(C1 + C2*x + x*exp(x) - 2*exp(x)))]
},
'euler_var_04': {
'eq': x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x),
'sol': [Eq(f(x), C1*x + C2*x**2 + log(x)/2 + Rational(3, 4))]
},
'euler_var_05': {
'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x,
'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))]
},
'euler_var_06': {
'eq': x**2 * f(x).diff(x, 2) + x * f(x).diff(x) + 4 * f(x) - 1/x,
'sol': [Eq(f(x), C1*sin(2*log(x)) + C2*cos(2*log(x)) + 1/(5*x))]
},
}
}
@_add_example_keys
def _get_examples_ode_sol_bernoulli():
# Type: Bernoulli, f'(x) + p(x)*f(x) == q(x)*f(x)**n
return {
'hint': "Bernoulli",
'func': f(x),
'examples':{
'bernoulli_01': {
'eq': Eq(x*f(x).diff(x) + f(x) - f(x)**2, 0),
'sol': [Eq(f(x), 1/(C1*x + 1))],
'XFAIL': ['separable_reduced']
},
'bernoulli_02': {
'eq': f(x).diff(x) - y*f(x),
'sol': [Eq(f(x), C1*exp(x*y))]
},
'bernoulli_03': {
'eq': f(x)*f(x).diff(x) - 1,
'sol': [Eq(f(x), -sqrt(C1 + 2*x)), Eq(f(x), sqrt(C1 + 2*x))]
},
}
}
@_add_example_keys
def _get_examples_ode_sol_riccati():
# Type: Riccati special alpha = -2, a*dy/dx + b*y**2 + c*y/x +d/x**2
return {
'hint': "Riccati_special_minus2",
'func': f(x),
'examples':{
'riccati_01': {
'eq': 2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2),
'sol': [Eq(f(x), (-sqrt(3)*tan(C1 + sqrt(3)*log(x)/4) + 3)/(2*x))],
},
},
}
@_add_example_keys
def _get_examples_ode_sol_1st_linear():
# Type: first order linear form f'(x)+p(x)f(x)=q(x)
return {
'hint': "1st_linear",
'func': f(x),
'examples':{
'linear_01': {
'eq': Eq(f(x).diff(x) + x*f(x), x**2),
'sol': [Eq(f(x), (C1 + x*exp(x**2/2)- sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2)/2)*exp(-x**2/2))],
},
},
}
@_add_example_keys
def _get_examples_ode_sol_factorable():
""" some hints are marked as xfail for examples because they missed additional algebraic solution
which could be found by Factorable hint. Fact_01 raise exception for
nth_linear_constant_coeff_undetermined_coefficients"""
y = Dummy('y')
a0,a1,a2,a3,a4 = symbols('a0, a1, a2, a3, a4')
return {
'hint': "factorable",
'func': f(x),
'examples':{
'fact_01': {
'eq': f(x) + f(x)*f(x).diff(x),
'sol': [Eq(f(x), 0), Eq(f(x), C1 - x)],
'XFAIL': ['separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep',
'lie_group', 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters',
'nth_linear_constant_coeff_undetermined_coefficients']
},
'fact_02': {
'eq': f(x)*(f(x).diff(x)+f(x)*x+2),
'sol': [Eq(f(x), (C1 - sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2))*exp(-x**2/2)), Eq(f(x), 0)],
'XFAIL': ['Bernoulli', '1st_linear', 'lie_group']
},
'fact_03': {
'eq': (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + x*f(x)),
'sol': [Eq(f(x), C1*airyai(-x) + C2*airybi(-x)),Eq(f(x), C1*exp(-x**3/3))]
},
'fact_04': {
'eq': (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + f(x)),
'sol': [Eq(f(x), C1*exp(-x**3/3)), Eq(f(x), C1*sin(x) + C2*cos(x))]
},
'fact_05': {
'eq': (f(x).diff(x)**2-1)*(f(x).diff(x)**2-4),
'sol': [Eq(f(x), C1 - x), Eq(f(x), C1 + x), Eq(f(x), C1 + 2*x), Eq(f(x), C1 - 2*x)]
},
'fact_06': {
'eq': (f(x).diff(x, 2)-exp(f(x)))*f(x).diff(x),
'sol': [
Eq(f(x), log(C1/(cos(C1*sqrt(-1/C1)*(C2 + x)) - 1))),
Eq(f(x), log(C1/(cos(C1*sqrt(-1/C1)*(C2 - x)) - 1))),
Eq(f(x), C1)
]
},
'fact_07': {
'eq': (f(x).diff(x)**2-1)*(f(x)*f(x).diff(x)-1),
'sol': [Eq(f(x), C1 - x), Eq(f(x), -sqrt(C1 + 2*x)),Eq(f(x), sqrt(C1 + 2*x)), Eq(f(x), C1 + x)]
},
'fact_08': {
'eq': Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1,
'sol': [Eq(f(x), C1 - x), Eq(f(x), C1 + x)]
},
'fact_09': {
'eq': f(x)**2*Derivative(f(x), x)**6 - 2*f(x)**2*Derivative(f(x),
x)**4 + f(x)**2*Derivative(f(x), x)**2 - 2*f(x)*Derivative(f(x),
x)**5 + 4*f(x)*Derivative(f(x), x)**3 - 2*f(x)*Derivative(f(x),
x) + Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1,
'sol': [
Eq(f(x), C1 - x), Eq(f(x), -sqrt(C1 + 2*x)),
Eq(f(x), sqrt(C1 + 2*x)), Eq(f(x), C1 + x)
]
},
'fact_10': {
'eq': x**4*f(x)**2 + 2*x**4*f(x)*Derivative(f(x), (x, 2)) + x**4*Derivative(f(x),
(x, 2))**2 + 2*x**3*f(x)*Derivative(f(x), x) + 2*x**3*Derivative(f(x),
x)*Derivative(f(x), (x, 2)) - 7*x**2*f(x)**2 - 7*x**2*f(x)*Derivative(f(x),
(x, 2)) + x**2*Derivative(f(x), x)**2 - 7*x*f(x)*Derivative(f(x), x) + 12*f(x)**2,
'sol': [
Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x)),
Eq(f(x), C1*besselj(sqrt(3), x) + C2*bessely(sqrt(3), x))
]
},
'fact_11': {
'eq': (f(x).diff(x, 2)-exp(f(x)))*(f(x).diff(x, 2)+exp(f(x))),
'sol': [
Eq(f(x), log(C1/(cos(C1*sqrt(-1/C1)*(C2 + x)) - 1))),
Eq(f(x), log(C1/(cos(C1*sqrt(-1/C1)*(C2 - x)) - 1))),
Eq(f(x), log(C1/(1 - cos(C1*sqrt(-1/C1)*(C2 + x))))),
Eq(f(x), log(C1/(1 - cos(C1*sqrt(-1/C1)*(C2 - x)))))
],
'dsolve_too_slow': True,
},
#Below examples were added for the issue: https://github.com/sympy/sympy/issues/15889
'fact_12': {
'eq': exp(f(x).diff(x))-f(x)**2,
'sol': [Eq(NonElementaryIntegral(1/log(y**2), (y, f(x))), C1 + x)],
'XFAIL': ['lie_group'] #It shows not implemented error for lie_group.
},
'fact_13': {
'eq': f(x).diff(x)**2 - f(x)**3,
'sol': [Eq(f(x), 4/(C1**2 - 2*C1*x + x**2))],
'XFAIL': ['lie_group'] #It shows not implemented error for lie_group.
},
'fact_14': {
'eq': f(x).diff(x)**2 - f(x),
'sol': [Eq(f(x), C1**2/4 - C1*x/2 + x**2/4)]
},
'fact_15': {
'eq': f(x).diff(x)**2 - f(x)**2,
'sol': [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))]
},
'fact_16': {
'eq': f(x).diff(x)**2 - f(x)**3,
'sol': [Eq(f(x), 4/(C1**2 - 2*C1*x + x**2))],
},
# kamke ode 1.1
'fact_17': {
'eq': f(x).diff(x)-(a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**(-1/2),
'sol': [Eq(f(x), C1 + Integral(1/sqrt(a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4), x))],
'slow': True
},
# This is from issue: https://github.com/sympy/sympy/issues/9446
'fact_18':{
'eq': Eq(f(2 * x), sin(Derivative(f(x)))),
'sol': [Eq(f(x), C1 + pi*x - Integral(asin(f(2*x)), x)), Eq(f(x), C1 + Integral(asin(f(2*x)), x))],
'checkodesol_XFAIL':True
},
# This is from issue: https://github.com/sympy/sympy/issues/7093
'fact_19': {
'eq': Derivative(f(x), x)**2 - x**3,
'sol': [Eq(f(x), C1 - 2*x*sqrt(x**3)/5), Eq(f(x), C1 + 2*x*sqrt(x**3)/5)],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_almost_linear():
from sympy import Ei
A = Symbol('A', positive=True)
f = Function('f')
d = f(x).diff(x)
return {
'hint': "almost_linear",
'func': f(x),
'examples':{
'almost_lin_01': {
'eq': x**2*f(x)**2*d + f(x)**3 + 1,
'sol': [Eq(f(x), (C1*exp(3/x) - 1)**Rational(1, 3)),
Eq(f(x), (-1 - sqrt(3)*I)*(C1*exp(3/x) - 1)**Rational(1, 3)/2),
Eq(f(x), (-1 + sqrt(3)*I)*(C1*exp(3/x) - 1)**Rational(1, 3)/2)],
},
'almost_lin_02': {
'eq': x*f(x)*d + 2*x*f(x)**2 + 1,
'sol': [Eq(f(x), -sqrt((C1 - 2*Ei(4*x))*exp(-4*x))), Eq(f(x), sqrt((C1 - 2*Ei(4*x))*exp(-4*x)))]
},
'almost_lin_03': {
'eq': x*d + x*f(x) + 1,
'sol': [Eq(f(x), (C1 - Ei(x))*exp(-x))]
},
'almost_lin_04': {
'eq': x*exp(f(x))*d + exp(f(x)) + 3*x,
'sol': [Eq(f(x), log(C1/x - x*Rational(3, 2)))],
},
'almost_lin_05': {
'eq': x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2,
'sol': [Eq(f(x), (C1 + Piecewise(
(x, Eq(A + 1, 0)), ((-A*x + A - x - 1)*exp(x)/(A + 1), True)))*exp(-x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_liouville():
n = Symbol('n')
_y = Dummy('y')
return {
'hint': "Liouville",
'func': f(x),
'examples':{
'liouville_01': {
'eq': diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2,
'sol': [Eq(f(x), log(x/(C1 + C2*x)))],
},
'liouville_02': {
'eq': diff(x*exp(-f(x)), x, x),
'sol': [Eq(f(x), log(x/(C1 + C2*x)))]
},
'liouville_03': {
'eq': ((diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2)*exp(-f(x))/exp(f(x))).expand(),
'sol': [Eq(f(x), log(x/(C1 + C2*x)))]
},
'liouville_04': {
'eq': diff(f(x), x, x) + 1/f(x)*(diff(f(x), x))**2 + 1/x*diff(f(x), x),
'sol': [Eq(f(x), -sqrt(C1 + C2*log(x))), Eq(f(x), sqrt(C1 + C2*log(x)))],
},
'liouville_05': {
'eq': x*diff(f(x), x, x) + x/f(x)*diff(f(x), x)**2 + x*diff(f(x), x),
'sol': [Eq(f(x), -sqrt(C1 + C2*exp(-x))), Eq(f(x), sqrt(C1 + C2*exp(-x)))],
},
'liouville_06': {
'eq': Eq((x*exp(f(x))).diff(x, x), 0),
'sol': [Eq(f(x), log(C1 + C2/x))],
},
'liouville_07': {
'eq': (diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2)*exp(-f(x))/exp(f(x)),
'sol': [Eq(f(x), log(x/(C1 + C2*x)))],
},
'liouville_08': {
'eq': x**2*diff(f(x),x) + (n*f(x) + f(x)**2)*diff(f(x),x)**2 + diff(f(x), (x, 2)),
'sol': [Eq(C1 + C2*lowergamma(Rational(1,3), x**3/3) + NonElementaryIntegral(exp(_y**3/3)*exp(_y**2*n/2), (_y, f(x))), 0)],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_algebraic():
M, m, r, t = symbols('M m r t')
phi = Function('phi')
k = Symbol('k')
# This one needs a substitution f' = g.
# 'algeb_12': {
# 'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x,
# 'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))],
# },
return {
'hint': "nth_algebraic",
'func': f(x),
'examples':{
'algeb_01': {
'eq': f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1) * (f(x).diff(x) - x),
'sol': [Eq(f(x), C1 + x**2/2), Eq(f(x), C1 + C2*x)]
},
'algeb_02': {
'eq': f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1),
'sol': [Eq(f(x), C1 + C2*x)]
},
'algeb_03': {
'eq': f(x) * f(x).diff(x) * f(x).diff(x, x),
'sol': [Eq(f(x), C1 + C2*x)]
},
'algeb_04': {
'eq': Eq(-M * phi(t).diff(t),
Rational(3, 2) * m * r**2 * phi(t).diff(t) * phi(t).diff(t,t)),
'sol': [Eq(phi(t), C1), Eq(phi(t), C1 + C2*t - M*t**2/(3*m*r**2))],
'func': phi(t)
},
'algeb_05': {
'eq': (1 - sin(f(x))) * f(x).diff(x),
'sol': [Eq(f(x), C1)],
'XFAIL': ['separable'] #It raised exception.
},
'algeb_06': {
'eq': (diff(f(x)) - x)*(diff(f(x)) + x),
'sol': [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)]
},
'algeb_07': {
'eq': Eq(Derivative(f(x), x), Derivative(g(x), x)),
'sol': [Eq(f(x), C1 + g(x))],
},
'algeb_08': {
'eq': f(x).diff(x) - C1, #this example is from issue 15999
'sol': [Eq(f(x), C1*x + C2)],
},
'algeb_09': {
'eq': f(x)*f(x).diff(x),
'sol': [Eq(f(x), C1)],
},
'algeb_10': {
'eq': (diff(f(x)) - x)*(diff(f(x)) + x),
'sol': [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)],
},
'algeb_11': {
'eq': f(x) + f(x)*f(x).diff(x),
'sol': [Eq(f(x), 0), Eq(f(x), C1 - x)],
'XFAIL': ['separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep',
'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters']
#nth_linear_constant_coeff_undetermined_coefficients raises exception rest all of them misses a solution.
},
'algeb_12': {
'eq': Derivative(x*f(x), x, x, x),
'sol': [Eq(f(x), (C1 + C2*x + C3*x**2) / x)],
'XFAIL': ['nth_algebraic'] # It passes only when prep=False is set in dsolve.
},
'algeb_13': {
'eq': Eq(Derivative(x*Derivative(f(x), x), x)/x, exp(x)),
'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))],
'XFAIL': ['nth_algebraic'] # It passes only when prep=False is set in dsolve.
},
# These are simple tests from the old ode module example 14-18
'algeb_14': {
'eq': Eq(f(x).diff(x), 0),
'sol': [Eq(f(x), C1)],
},
'algeb_15': {
'eq': Eq(3*f(x).diff(x) - 5, 0),
'sol': [Eq(f(x), C1 + x*Rational(5, 3))],
},
'algeb_16': {
'eq': Eq(3*f(x).diff(x), 5),
'sol': [Eq(f(x), C1 + x*Rational(5, 3))],
},
# Type: 2nd order, constant coefficients (two complex roots)
'algeb_17': {
'eq': Eq(3*f(x).diff(x) - 1, 0),
'sol': [Eq(f(x), C1 + x/3)],
},
'algeb_18': {
'eq': Eq(x*f(x).diff(x) - 1, 0),
'sol': [Eq(f(x), C1 + log(x))],
},
# https://github.com/sympy/sympy/issues/6989
'algeb_19': {
'eq': f(x).diff(x) - x*exp(-k*x),
'sol': [Eq(f(x), C1 + Piecewise(((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)),(x**2/2, True)))],
},
'algeb_20': {
'eq': -f(x).diff(x) + x*exp(-k*x),
'sol': [Eq(f(x), C1 + Piecewise(((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)),(x**2/2, True)))],
},
# https://github.com/sympy/sympy/issues/10867
'algeb_21': {
'eq': Eq(g(x).diff(x).diff(x), (x-2)**2 + (x-3)**3),
'sol': [Eq(g(x), C1 + C2*x + x**5/20 - 2*x**4/3 + 23*x**3/6 - 23*x**2/2)],
'func': g(x),
},
# https://github.com/sympy/sympy/issues/13691
'algeb_22': {
'eq': f(x).diff(x) - C1*g(x).diff(x),
'sol': [Eq(f(x), C2 + C1*g(x))],
'func': f(x),
},
# https://github.com/sympy/sympy/issues/4838
'algeb_23': {
'eq': f(x).diff(x) - 3*C1 - 3*x**2,
'sol': [Eq(f(x), C2 + 3*C1*x + x**3)],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_order_reducible():
return {
'hint': "nth_order_reducible",
'func': f(x),
'examples':{
'reducible_01': {
'eq': Eq(x*Derivative(f(x), x)**2 + Derivative(f(x), x, 2), 0),
'sol': [Eq(f(x),C1 - sqrt(-1/C2)*log(-C2*sqrt(-1/C2) + x) +
sqrt(-1/C2)*log(C2*sqrt(-1/C2) + x))],
'slow': True,
},
'reducible_02': {
'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x,
'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))],
'slow': True,
},
'reducible_03': {
'eq': Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0),
'sol': [Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2))],
'slow': True,
},
'reducible_04': {
'eq': f(x).diff(x, 2) + 2*f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*exp(-2*x))],
},
'reducible_05': {
'eq': f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x))],
'slow': True,
},
'reducible_06': {
'eq': f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \
4*f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*exp(-2*x) + C3*exp(x) + C4*exp(2*x))],
'slow': True,
},
'reducible_07': {
'eq': f(x).diff(x, 4) + 3*f(x).diff(x, 3),
'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x))],
'slow': True,
},
'reducible_08': {
'eq': f(x).diff(x, 4) - 2*f(x).diff(x, 2),
'sol': [Eq(f(x), C1 + C2*x + C3*exp(-sqrt(2)*x) + C4*exp(sqrt(2)*x))],
'slow': True,
},
'reducible_09': {
'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2),
'sol': [Eq(f(x), C1 + C2*x + C3*sin(2*x) + C4*cos(2*x))],
'slow': True,
},
'reducible_10': {
'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*(x*sin(x) + cos(x)) + C3*(-x*cos(x) + sin(x)) + C4*sin(x) + C5*cos(x))],
'slow': True,
},
'reducible_11': {
'eq': f(x).diff(x, 2) - f(x).diff(x)**3,
'sol': [Eq(f(x), C1 - sqrt(2)*sqrt(-1/(C2 + x))*(C2 + x)),
Eq(f(x), C1 + sqrt(2)*sqrt(-1/(C2 + x))*(C2 + x))],
'slow': True,
},
# Needs to be a way to know how to combine derivatives in the expression
'reducible_12': {
'eq': Derivative(x*f(x), x, x, x) + Derivative(f(x), x, x, x),
'sol': [Eq(f(x), C1 + C2*x + C3/Mul(2, (x + 1), evaluate=False))], # 2-arg Mul!
'slow': True,
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_linear_undetermined_coefficients():
# examples 3-27 below are from Ordinary Differential Equations,
# Tenenbaum and Pollard, pg. 231
g = exp(-x)
f2 = f(x).diff(x, 2)
c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x
t = symbols("t")
u = symbols("u",cls=Function)
R, L, C, E_0, alpha = symbols("R L C E_0 alpha",positive=True)
omega = Symbol('omega')
return {
'hint': "nth_linear_constant_coeff_undetermined_coefficients",
'func': f(x),
'examples':{
'undet_01': {
'eq': c - x*g,
'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x**2/24 - 3*x/32))*exp(-x) - 1)],
'slow': True,
},
'undet_02': {
'eq': c - g,
'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x/8))*exp(-x) - 1)],
'slow': True,
},
'undet_03': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 4,
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2)],
'slow': True,
},
'undet_04': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2*exp(x))],
'slow': True,
},
'undet_05': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - exp(I*x),
'sol': [Eq(f(x), (S(3)/10 + I/10)*(C1*exp(-2*x) + C2*exp(-x) - I*exp(I*x)))],
'slow': True,
},
'undet_06': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - sin(x),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + sin(x)/10 - 3*cos(x)/10)],
'slow': True,
},
'undet_07': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - cos(x),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 3*sin(x)/10 + cos(x)/10)],
'slow': True,
},
'undet_08': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - (8 + 6*exp(x) + 2*sin(x)),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + exp(x) + sin(x)/5 - 3*cos(x)/5 + 4)],
'slow': True,
},
'undet_09': {
'eq': f2 + f(x).diff(x) + f(x) - x**2,
'sol': [Eq(f(x), -2*x + x**2 + (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(-x/2))],
'slow': True,
},
'undet_10': {
'eq': f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x),
'sol': [Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x))],
'slow': True,
},
'undet_11': {
'eq': f2 - 3*f(x).diff(x) - 2*exp(2*x)*sin(x),
'sol': [Eq(f(x), C1 + C2*exp(3*x) - 3*exp(2*x)*sin(x)/5 - exp(2*x)*cos(x)/5)],
'slow': True,
},
'undet_12': {
'eq': f(x).diff(x, 4) - 2*f2 + f(x) - x + sin(x),
'sol': [Eq(f(x), x - sin(x)/4 + (C1 + C2*x)*exp(-x) + (C3 + C4*x)*exp(x))],
'slow': True,
},
'undet_13': {
'eq': f2 + f(x).diff(x) - x**2 - 2*x,
'sol': [Eq(f(x), C1 + x**3/3 + C2*exp(-x))],
'slow': True,
},
'undet_14': {
'eq': f2 + f(x).diff(x) - x - sin(2*x),
'sol': [Eq(f(x), C1 - x - sin(2*x)/5 - cos(2*x)/10 + x**2/2 + C2*exp(-x))],
'slow': True,
},
'undet_15': {
'eq': f2 + f(x) - 4*x*sin(x),
'sol': [Eq(f(x), (C1 - x**2)*cos(x) + (C2 + x)*sin(x))],
'slow': True,
},
'undet_16': {
'eq': f2 + 4*f(x) - x*sin(2*x),
'sol': [Eq(f(x), (C1 - x**2/8)*cos(2*x) + (C2 + x/16)*sin(2*x))],
'slow': True,
},
'undet_17': {
'eq': f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x),
'sol': [Eq(f(x), (C1 + x*(C2 + x**3/12))*exp(-x))],
'slow': True,
},
'undet_18': {
'eq': f(x).diff(x, 3) + 3*f2 + 3*f(x).diff(x) + f(x) - 2*exp(-x) + \
x**2*exp(-x),
'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 - x**3/60 + x/3)))*exp(-x))],
'slow': True,
},
'undet_19': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - exp(-2*x) - x**2,
'sol': [Eq(f(x), C2*exp(-x) + x**2/2 - x*Rational(3,2) + (C1 - x)*exp(-2*x) + Rational(7,4))],
'slow': True,
},
'undet_20': {
'eq': f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x),
'sol': [Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36)],
'slow': True,
},
'undet_21': {
'eq': f2 + f(x).diff(x) - 6*f(x) - x - exp(2*x),
'sol': [Eq(f(x), Rational(-1, 36) - x/6 + C2*exp(-3*x) + (C1 + x/5)*exp(2*x))],
'slow': True,
},
'undet_22': {
'eq': f2 + f(x) - sin(x) - exp(-x),
'sol': [Eq(f(x), C2*sin(x) + (C1 - x/2)*cos(x) + exp(-x)/2)],
'slow': True,
},
'undet_23': {
'eq': f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x),
'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 + x/6)))*exp(x))],
'slow': True,
},
'undet_24': {
'eq': f2 + f(x) - S.Half - cos(2*x)/2,
'sol': [Eq(f(x), S.Half - cos(2*x)/6 + C1*sin(x) + C2*cos(x))],
'slow': True,
},
'undet_25': {
'eq': f(x).diff(x, 3) - f(x).diff(x) - exp(2*x)*(S.Half - cos(2*x)/2),
'sol': [Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + (-21*sin(2*x) + 27*cos(2*x) + 130)*exp(2*x)/1560)],
'slow': True,
},
#Note: 'undet_26' is referred in 'undet_37'
'undet_26': {
'eq': (f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x -
sin(x) - cos(x)),
'sol': [Eq(f(x), C1 + x**2 + (C2 + x*(C3 - x/8))*sin(x) + (C4 + x*(C5 + x/8))*cos(x))],
'slow': True,
},
'undet_27': {
'eq': f2 + f(x) - cos(x)/2 + cos(3*x)/2,
'sol': [Eq(f(x), cos(3*x)/16 + C2*cos(x) + (C1 + x/4)*sin(x))],
'slow': True,
},
'undet_28': {
'eq': f(x).diff(x) - 1,
'sol': [Eq(f(x), C1 + x)],
'slow': True,
},
# https://github.com/sympy/sympy/issues/19358
'undet_29': {
'eq': f2 + f(x).diff(x) + exp(x-C1),
'sol': [Eq(f(x), C2 + C3*exp(-x) - exp(-C1 + x)/2)],
'slow': True,
},
# https://github.com/sympy/sympy/issues/18408
'undet_30': {
'eq': f(x).diff(x, 3) - f(x).diff(x) - sinh(x),
'sol': [Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + x*sinh(x)/2)],
},
'undet_31': {
'eq': f(x).diff(x, 2) - 49*f(x) - sinh(3*x),
'sol': [Eq(f(x), C1*exp(-7*x) + C2*exp(7*x) - sinh(3*x)/40)],
},
'undet_32': {
'eq': f(x).diff(x, 3) - f(x).diff(x) - sinh(x) - exp(x),
'sol': [Eq(f(x), C1 + C3*exp(-x) + x*sinh(x)/2 + (C2 + x/2)*exp(x))],
},
# https://github.com/sympy/sympy/issues/5096
'undet_33': {
'eq': f(x).diff(x, x) + f(x) - x*sin(x - 2),
'sol': [Eq(f(x), C1*sin(x) + C2*cos(x) - x**2*cos(x - 2)/4 + x*sin(x - 2)/4)],
},
'undet_34': {
'eq': f(x).diff(x, 2) + f(x) - x**4*sin(x-1),
'sol': [ Eq(f(x), C1*sin(x) + C2*cos(x) - x**5*cos(x - 1)/10 + x**4*sin(x - 1)/4 + x**3*cos(x - 1)/2 - 3*x**2*sin(x - 1)/4 - 3*x*cos(x - 1)/4)],
},
'undet_35': {
'eq': f(x).diff(x, 2) - f(x) - exp(x - 1),
'sol': [Eq(f(x), C2*exp(-x) + (C1 + x*exp(-1)/2)*exp(x))],
},
'undet_36': {
'eq': f(x).diff(x, 2)+f(x)-(sin(x-2)+1),
'sol': [Eq(f(x), C1*sin(x) + C2*cos(x) - x*cos(x - 2)/2 + 1)],
},
# Equivalent to example_name 'undet_26'.
# This previously failed because the algorithm for undetermined coefficients
# didn't know to multiply exp(I*x) by sufficient x because it is linearly
# dependent on sin(x) and cos(x).
'undet_37': {
'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x),
'sol': [Eq(f(x), C1 + x**2*(I*exp(I*x)/8 + 1) + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x))],
},
# https://github.com/sympy/sympy/issues/12623
'undet_38': {
'eq': Eq( u(t).diff(t,t) + R /L*u(t).diff(t) + 1/(L*C)*u(t), alpha),
'sol': [Eq(u(t), C*L*alpha + C1*exp(t*(-R - sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L))
+ C2*exp(t*(-R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)))],
'func': u(t)
},
'undet_39': {
'eq': Eq( L*C*u(t).diff(t,t) + R*C*u(t).diff(t) + u(t), E_0*exp(I*omega*t) ),
'sol': [Eq(u(t), C1*exp(t*(-R - sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L))
+ C2*exp(t*(-R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L))
- E_0*exp(I*omega*t)/(C*L*omega**2 - I*C*R*omega - 1))],
'func': u(t),
},
# https://github.com/sympy/sympy/issues/6879
'undet_40': {
'eq': Eq(Derivative(f(x), x, 2) - 2*Derivative(f(x), x) + f(x), sin(x)),
'sol': [Eq(f(x), (C1 + C2*x)*exp(x) + cos(x)/2)],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_separable():
# test_separable1-5 are from Ordinary Differential Equations, Tenenbaum and
# Pollard, pg. 55
t,a = symbols('a,t')
m = 96
g = 9.8
k = .2
f1 = g * m
v = Function('v')
return {
'hint': "separable",
'func': f(x),
'examples':{
'separable_01': {
'eq': f(x).diff(x) - f(x),
'sol': [Eq(f(x), C1*exp(x))],
},
'separable_02': {
'eq': x*f(x).diff(x) - f(x),
'sol': [Eq(f(x), C1*x)],
},
'separable_03': {
'eq': f(x).diff(x) + sin(x),
'sol': [Eq(f(x), C1 + cos(x))],
},
'separable_04': {
'eq': f(x)**2 + 1 - (x**2 + 1)*f(x).diff(x),
'sol': [Eq(f(x), tan(C1 + atan(x)))],
},
'separable_05': {
'eq': f(x).diff(x)/tan(x) - f(x) - 2,
'sol': [Eq(f(x), C1/cos(x) - 2)],
},
'separable_06': {
'eq': f(x).diff(x) * (1 - sin(f(x))) - 1,
'sol': [Eq(-x + f(x) + cos(f(x)), C1)],
},
'separable_07': {
'eq': f(x)*x**2*f(x).diff(x) - f(x)**3 - 2*x**2*f(x).diff(x),
'sol': [
Eq(f(x), (-x + sqrt(x*(4*C1*x + x - 4)))/(C1*x - 1)/2),
Eq(f(x), -((x + sqrt(x*(4*C1*x + x - 4)))/(C1*x - 1))/2)
],
'slow': True,
},
'separable_08': {
'eq': f(x)**2 - 1 - (2*f(x) + x*f(x))*f(x).diff(x),
'sol': [Eq(f(x), -sqrt(C1*x**2 + 4*C1*x + 4*C1 + 1)),
Eq(f(x), sqrt(C1*x**2 + 4*C1*x + 4*C1 + 1))],
'slow': True,
},
'separable_09': {
'eq': x*log(x)*f(x).diff(x) + sqrt(1 + f(x)**2),
'sol': [Eq(f(x), sinh(C1 - log(log(x))))], #One more solution is f(x)=I
'slow': True,
'checkodesol_XFAIL': True,
},
'separable_10': {
'eq': exp(x + 1)*tan(f(x)) + cos(f(x))*f(x).diff(x),
'sol': [Eq(E*exp(x) + log(cos(f(x)) - 1)/2 - log(cos(f(x)) + 1)/2 + cos(f(x)), C1)],
'slow': True,
},
'separable_11': {
'eq': (x*cos(f(x)) + x**2*sin(f(x))*f(x).diff(x) - a**2*sin(f(x))*f(x).diff(x)),
'sol': [
Eq(f(x), -acos(C1*sqrt(-a**2 + x**2)) + 2*pi),
Eq(f(x), acos(C1*sqrt(-a**2 + x**2)))
],
'slow': True,
},
'separable_12': {
'eq': f(x).diff(x) - f(x)*tan(x),
'sol': [Eq(f(x), C1/cos(x))],
},
'separable_13': {
'eq': (x - 1)*cos(f(x))*f(x).diff(x) - 2*x*sin(f(x)),
'sol': [
Eq(f(x), pi - asin(C1*(x**2 - 2*x + 1)*exp(2*x))),
Eq(f(x), asin(C1*(x**2 - 2*x + 1)*exp(2*x)))
],
},
'separable_14': {
'eq': f(x).diff(x) - f(x)*log(f(x))/tan(x),
'sol': [Eq(f(x), exp(C1*sin(x)))],
},
'separable_15': {
'eq': x*f(x).diff(x) + (1 + f(x)**2)*atan(f(x)),
'sol': [Eq(f(x), tan(C1/x))], #Two more solutions are f(x)=0 and f(x)=I
'slow': True,
'checkodesol_XFAIL': True,
},
'separable_16': {
'eq': f(x).diff(x) + x*(f(x) + 1),
'sol': [Eq(f(x), -1 + C1*exp(-x**2/2))],
},
'separable_17': {
'eq': exp(f(x)**2)*(x**2 + 2*x + 1) + (x*f(x) + f(x))*f(x).diff(x),
'sol': [
Eq(f(x), -sqrt(log(1/(C1 + x**2 + 2*x)))),
Eq(f(x), sqrt(log(1/(C1 + x**2 + 2*x))))
],
},
'separable_18': {
'eq': f(x).diff(x) + f(x),
'sol': [Eq(f(x), C1*exp(-x))],
},
'separable_19': {
'eq': sin(x)*cos(2*f(x)) + cos(x)*sin(2*f(x))*f(x).diff(x),
'sol': [Eq(f(x), pi - acos(C1/cos(x)**2)/2), Eq(f(x), acos(C1/cos(x)**2)/2)],
},
'separable_20': {
'eq': (1 - x)*f(x).diff(x) - x*(f(x) + 1),
'sol': [Eq(f(x), (C1*exp(-x) - x + 1)/(x - 1))],
},
'separable_21': {
'eq': f(x)*diff(f(x), x) + x - 3*x*f(x)**2,
'sol': [Eq(f(x), -sqrt(3)*sqrt(C1*exp(3*x**2) + 1)/3),
Eq(f(x), sqrt(3)*sqrt(C1*exp(3*x**2) + 1)/3)],
},
'separable_22': {
'eq': f(x).diff(x) - exp(x + f(x)),
'sol': [Eq(f(x), log(-1/(C1 + exp(x))))],
'XFAIL': ['lie_group'] #It shows 'NoneType' object is not subscriptable for lie_group.
},
# https://github.com/sympy/sympy/issues/7081
'separable_23': {
'eq': x*(f(x).diff(x)) + 1 - f(x)**2,
'sol': [Eq(f(x), -1/(-C1 + x**2)*(C1 + x**2))],
},
# https://github.com/sympy/sympy/issues/10379
'separable_24': {
'eq': f(t).diff(t)-(1-51.05*y*f(t)),
'sol': [Eq(f(t), (0.019588638589618023*exp(y*(C1 - 51.049999999999997*t)) + 0.019588638589618023)/y)],
'func': f(t),
},
# https://github.com/sympy/sympy/issues/15999
'separable_25': {
'eq': f(x).diff(x) - C1*f(x),
'sol': [Eq(f(x), C2*exp(C1*x))],
},
'separable_26': {
'eq': f1 - k * (v(t) ** 2) - m * Derivative(v(t)),
'sol': [Eq(v(t), -68.585712797928991/tanh(C1 - 0.14288690166235204*t))],
'func': v(t),
'checkodesol_XFAIL': True,
}
}
}
@_add_example_keys
def _get_examples_ode_sol_1st_exact():
# Type: Exact differential equation, p(x,f) + q(x,f)*f' == 0,
# where dp/df == dq/dx
'''
Example 7 is an exact equation that fails under the exact engine. It is caught
by first order homogeneous albeit with a much contorted solution. The
exact engine fails because of a poorly simplified integral of q(0,y)dy,
where q is the function multiplying f'. The solutions should be
Eq(sqrt(x**2+f(x)**2)**3+y**3, C1). The equation below is
equivalent, but it is so complex that checkodesol fails, and takes a long
time to do so.
'''
return {
'hint': "1st_exact",
'func': f(x),
'examples':{
'1st_exact_01': {
'eq': sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x),
'sol': [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))],
'slow': True,
},
'1st_exact_02': {
'eq': (2*x*f(x) + 1)/f(x) + (f(x) - x)/f(x)**2*f(x).diff(x),
'sol': [Eq(f(x), exp(C1 - x**2 + LambertW(-x*exp(-C1 + x**2))))],
'XFAIL': ['lie_group'], #It shows dsolve raises an exception: List index out of range for lie_group
'slow': True,
'checkodesol_XFAIL':True
},
'1st_exact_03': {
'eq': 2*x + f(x)*cos(x) + (2*f(x) + sin(x) - sin(f(x)))*f(x).diff(x),
'sol': [Eq(f(x)*sin(x) + cos(f(x)) + x**2 + f(x)**2, C1)],
'XFAIL': ['lie_group'], #It goes into infinite loop for lie_group.
'slow': True,
},
'1st_exact_04': {
'eq': cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x),
'sol': [Eq(x*cos(f(x)) + f(x)**3/3, C1)],
'slow': True,
},
'1st_exact_05': {
'eq': 2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x),
'sol': [Eq(x**2*f(x) + f(x)**3/3, C1)],
'slow': True,
'simplify_flag':False
},
# This was from issue: https://github.com/sympy/sympy/issues/11290
'1st_exact_06': {
'eq': cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x),
'sol': [Eq(x*cos(f(x)) + f(x)**3/3, C1)],
'simplify_flag':False
},
'1st_exact_07': {
'eq': x*sqrt(x**2 + f(x)**2) - (x**2*f(x)/(f(x) - sqrt(x**2 + f(x)**2)))*f(x).diff(x),
'sol': [Eq(log(x),
C1 - 9*sqrt(1 + f(x)**2/x**2)*asinh(f(x)/x)/(-27*f(x)/x +
27*sqrt(1 + f(x)**2/x**2)) - 9*sqrt(1 + f(x)**2/x**2)*
log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/
(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) +
9*asinh(f(x)/x)*f(x)/(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))) +
9*f(x)*log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/
(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))))],
'slow': True,
'dsolve_too_slow':True
},
# Type: a(x)f'(x)+b(x)*f(x)+c(x)=0
'1st_exact_08': {
'eq': Eq(x**2*f(x).diff(x) + 3*x*f(x) - sin(x)/x, 0),
'sol': [Eq(f(x), (C1 - cos(x))/x**3)],
},
# these examples are from test_exact_enhancement
'1st_exact_09': {
'eq': f(x)/x**2 + ((f(x)*x - 1)/x)*f(x).diff(x),
'sol': [Eq(f(x), (i*sqrt(C1*x**2 + 1) + 1)/x) for i in (-1, 1)],
},
'1st_exact_10': {
'eq': (x*f(x) - 1) + f(x).diff(x)*(x**2 - x*f(x)),
'sol': [Eq(f(x), x - sqrt(C1 + x**2 - 2*log(x))), Eq(f(x), x + sqrt(C1 + x**2 - 2*log(x)))],
},
'1st_exact_11': {
'eq': (x + 2)*sin(f(x)) + f(x).diff(x)*x*cos(f(x)),
'sol': [Eq(f(x), -asin(C1*exp(-x)/x**2) + pi), Eq(f(x), asin(C1*exp(-x)/x**2))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_linear_var_of_parameters():
g = exp(-x)
f2 = f(x).diff(x, 2)
c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x
return {
'hint': "nth_linear_constant_coeff_variation_of_parameters",
'func': f(x),
'examples':{
'var_of_parameters_01': {
'eq': c - x*g,
'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x**2/24 - 3*x/32))*exp(-x) - 1)],
'slow': True,
},
'var_of_parameters_02': {
'eq': c - g,
'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x/8))*exp(-x) - 1)],
'slow': True,
},
'var_of_parameters_03': {
'eq': f(x).diff(x) - 1,
'sol': [Eq(f(x), C1 + x)],
'slow': True,
},
'var_of_parameters_04': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 4,
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2)],
'slow': True,
},
'var_of_parameters_05': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2*exp(x))],
'slow': True,
},
'var_of_parameters_06': {
'eq': f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x),
'sol': [Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x))],
'slow': True,
},
'var_of_parameters_07': {
'eq': f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x),
'sol': [Eq(f(x), (C1 + x*(C2 + x**3/12))*exp(-x))],
'slow': True,
},
'var_of_parameters_08': {
'eq': f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x),
'sol': [Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36)],
'slow': True,
},
'var_of_parameters_09': {
'eq': f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x),
'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 + x/6)))*exp(x))],
'slow': True,
},
'var_of_parameters_10': {
'eq': f2 + 2*f(x).diff(x) + f(x) - exp(-x)/x,
'sol': [Eq(f(x), (C1 + x*(C2 + log(x)))*exp(-x))],
'slow': True,
},
'var_of_parameters_11': {
'eq': f2 + f(x) - 1/sin(x)*1/cos(x),
'sol': [Eq(f(x), (C1 + log(sin(x) - 1)/2 - log(sin(x) + 1)/2
)*cos(x) + (C2 + log(cos(x) - 1)/2 - log(cos(x) + 1)/2)*sin(x))],
'slow': True,
},
'var_of_parameters_12': {
'eq': f(x).diff(x, 4) - 1/x,
'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + x**3*(C4 + log(x)/6))],
'slow': True,
},
# These were from issue: https://github.com/sympy/sympy/issues/15996
'var_of_parameters_13': {
'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x),
'sol': [Eq(f(x), C1 + x**2 + (C2 + x*(C3 - x/8 + 3*exp(I*x)/2 + 3*exp(-I*x)/2) + 5*exp(2*I*x)/16 + 2*I*exp(I*x) - 2*I*exp(-I*x))*sin(x) + (C4 + x*(C5 + I*x/8 + 3*I*exp(I*x)/2 - 3*I*exp(-I*x)/2)
+ 5*I*exp(2*I*x)/16 - 2*exp(I*x) - 2*exp(-I*x))*cos(x) - I*exp(I*x))],
},
'var_of_parameters_14': {
'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - exp(I*x),
'sol': [Eq(f(x), C1 + (C2 + x*(C3 - x/8) + 5*exp(2*I*x)/16)*sin(x) + (C4 + x*(C5 + I*x/8) + 5*I*exp(2*I*x)/16)*cos(x) - I*exp(I*x))],
},
# https://github.com/sympy/sympy/issues/14395
'var_of_parameters_15': {
'eq': Derivative(f(x), x, x) + 9*f(x) - sec(x),
'sol': [Eq(f(x), (C1 - x/3 + sin(2*x)/3)*sin(3*x) + (C2 + log(cos(x))
- 2*log(cos(x)**2)/3 + 2*cos(x)**2/3)*cos(3*x))],
'slow': True,
},
}
}
@_add_example_keys
def _get_examples_ode_sol_2nd_linear_bessel():
return {
'hint': "2nd_linear_bessel",
'func': f(x),
'examples':{
'2nd_lin_bessel_01': {
'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - 4)*f(x),
'sol': [Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x))],
},
'2nd_lin_bessel_02': {
'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 +25)*f(x),
'sol': [Eq(f(x), C1*besselj(5*I, x) + C2*bessely(5*I, x))],
},
'2nd_lin_bessel_03': {
'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2)*f(x),
'sol': [Eq(f(x), C1*besselj(0, x) + C2*bessely(0, x))],
},
'2nd_lin_bessel_04': {
'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (81*x**2 -S(1)/9)*f(x),
'sol': [Eq(f(x), C1*besselj(S(1)/3, 9*x) + C2*bessely(S(1)/3, 9*x))],
},
'2nd_lin_bessel_05': {
'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**4 - 4)*f(x),
'sol': [Eq(f(x), C1*besselj(1, x**2/2) + C2*bessely(1, x**2/2))],
},
'2nd_lin_bessel_06': {
'eq': x**2*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) + (x**4 - 4)*f(x),
'sol': [Eq(f(x), (C1*besselj(sqrt(17)/4, x**2/2) + C2*bessely(sqrt(17)/4, x**2/2))/sqrt(x))],
},
'2nd_lin_bessel_07': {
'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - S(1)/4)*f(x),
'sol': [Eq(f(x), C1*besselj(S(1)/2, x) + C2*bessely(S(1)/2, x))],
},
'2nd_lin_bessel_08': {
'eq': x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x),
'sol': [Eq(f(x), x**2*(C1*besselj(0, 4*sqrt(x)) + C2*bessely(0, 4*sqrt(x))))],
},
'2nd_lin_bessel_09': {
'eq': x*(f(x).diff(x, 2)) - f(x).diff(x) + 4*x**3*f(x),
'sol': [Eq(f(x), x*(C1*besselj(S(1)/2, x**2) + C2*bessely(S(1)/2, x**2)))],
},
'2nd_lin_bessel_10': {
'eq': (x-2)**2*(f(x).diff(x, 2)) - (x-2)*f(x).diff(x) + 4*(x-2)**2*f(x),
'sol': [Eq(f(x), (x - 2)*(C1*besselj(1, 2*x - 4) + C2*bessely(1, 2*x - 4)))],
},
# https://github.com/sympy/sympy/issues/4414
'2nd_lin_bessel_11': {
'eq': f(x).diff(x, x) + 2/x*f(x).diff(x) + f(x),
'sol': [Eq(f(x), (C1*besselj(S(1)/2, x) + C2*bessely(S(1)/2, x))/sqrt(x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_2nd_2F1_hypergeometric():
return {
'hint': "2nd_hypergeometric",
'func': f(x),
'examples':{
'2nd_2F1_hyper_01': {
'eq': x*(x-1)*f(x).diff(x, 2) + (S(3)/2 -2*x)*f(x).diff(x) + 2*f(x),
'sol': [Eq(f(x), C1*x**(S(5)/2)*hyper((S(3)/2, S(1)/2), (S(7)/2,), x) + C2*hyper((-1, -2), (-S(3)/2,), x))],
},
'2nd_2F1_hyper_02': {
'eq': x*(x-1)*f(x).diff(x, 2) + (S(7)/2*x)*f(x).diff(x) + f(x),
'sol': [Eq(f(x), (C1*(1 - x)**(S(5)/2)*hyper((S(1)/2, 2), (S(7)/2,), 1 - x) +
C2*hyper((-S(1)/2, -2), (-S(3)/2,), 1 - x))/(x - 1)**(S(5)/2))],
},
'2nd_2F1_hyper_03': {
'eq': x*(x-1)*f(x).diff(x, 2) + (S(3)+ S(7)/2*x)*f(x).diff(x) + f(x),
'sol': [Eq(f(x), (C1*(1 - x)**(S(11)/2)*hyper((S(1)/2, 2), (S(13)/2,), 1 - x) +
C2*hyper((-S(7)/2, -5), (-S(9)/2,), 1 - x))/(x - 1)**(S(11)/2))],
},
'2nd_2F1_hyper_04': {
'eq': -x**(S(5)/7)*(-416*x**(S(9)/7)/9 - 2385*x**(S(5)/7)/49 + S(298)*x/3)*f(x)/(196*(-x**(S(6)/7) +
x)**2*(x**(S(6)/7) + x)**2) + Derivative(f(x), (x, 2)),
'sol': [Eq(f(x), x**(S(45)/98)*(C1*x**(S(4)/49)*hyper((S(1)/3, -S(1)/2), (S(9)/7,), x**(S(2)/7)) +
C2*hyper((S(1)/21, -S(11)/14), (S(5)/7,), x**(S(2)/7)))/(x**(S(2)/7) - 1)**(S(19)/84))],
'checkodesol_XFAIL':True,
},
}
}
@_add_example_keys
def _get_examples_ode_sol_2nd_nonlinear_autonomous_conserved():
return {
'hint': "2nd_nonlinear_autonomous_conserved",
'func': f(x),
'examples': {
'2nd_nonlinear_autonomous_conserved_01': {
'eq': f(x).diff(x, 2) + exp(f(x)) + log(f(x)),
'sol': [
Eq(Integral(1/sqrt(C1 - 2*_u*log(_u) + 2*_u - 2*exp(_u)), (_u, f(x))), C2 + x),
Eq(Integral(1/sqrt(C1 - 2*_u*log(_u) + 2*_u - 2*exp(_u)), (_u, f(x))), C2 - x)
],
'simplify_flag': False,
},
'2nd_nonlinear_autonomous_conserved_02': {
'eq': f(x).diff(x, 2) + cbrt(f(x)) + 1/f(x),
'sol': [
Eq(sqrt(2)*Integral(1/sqrt(2*C1 - 3*_u**Rational(4, 3) - 4*log(_u)), (_u, f(x))), C2 + x),
Eq(sqrt(2)*Integral(1/sqrt(2*C1 - 3*_u**Rational(4, 3) - 4*log(_u)), (_u, f(x))), C2 - x)
],
'simplify_flag': False,
},
'2nd_nonlinear_autonomous_conserved_03': {
'eq': f(x).diff(x, 2) + sin(f(x)),
'sol': [
Eq(Integral(1/sqrt(C1 + 2*cos(_u)), (_u, f(x))), C2 + x),
Eq(Integral(1/sqrt(C1 + 2*cos(_u)), (_u, f(x))), C2 - x)
],
'simplify_flag': False,
},
'2nd_nonlinear_autonomous_conserved_04': {
'eq': f(x).diff(x, 2) + cosh(f(x)),
'sol': [
Eq(Integral(1/sqrt(C1 - 2*sinh(_u)), (_u, f(x))), C2 + x),
Eq(Integral(1/sqrt(C1 - 2*sinh(_u)), (_u, f(x))), C2 - x)
],
'simplify_flag': False,
},
'2nd_nonlinear_autonomous_conserved_05': {
'eq': f(x).diff(x, 2) + asin(f(x)),
'sol': [
Eq(Integral(1/sqrt(C1 - 2*_u*asin(_u) - 2*sqrt(1 - _u**2)), (_u, f(x))), C2 + x),
Eq(Integral(1/sqrt(C1 - 2*_u*asin(_u) - 2*sqrt(1 - _u**2)), (_u, f(x))), C2 - x)
],
'simplify_flag': False,
'XFAIL': ['2nd_nonlinear_autonomous_conserved_Integral']
}
}
}
@_add_example_keys
def _get_examples_ode_sol_separable_reduced():
df = f(x).diff(x)
return {
'hint': "separable_reduced",
'func': f(x),
'examples':{
'separable_reduced_01': {
'eq': x* df + f(x)* (1 / (x**2*f(x) - 1)),
'sol': [Eq(log(x**2*f(x))/3 + log(x**2*f(x) - Rational(3, 2))/6, C1 + log(x))],
'simplify_flag': False,
'XFAIL': ['lie_group'], #It hangs.
},
#Note: 'separable_reduced_02' is referred in 'separable_reduced_11'
'separable_reduced_02': {
'eq': f(x).diff(x) + (f(x) / (x**4*f(x) - x)),
'sol': [Eq(log(x**3*f(x))/4 + log(x**3*f(x) - Rational(4,3))/12, C1 + log(x))],
'simplify_flag': False,
'checkodesol_XFAIL':True, #It hangs for this.
},
'separable_reduced_03': {
'eq': x*df + f(x)*(x**2*f(x)),
'sol': [Eq(log(x**2*f(x))/2 - log(x**2*f(x) - 2)/2, C1 + log(x))],
'simplify_flag': False,
},
'separable_reduced_04': {
'eq': Eq(f(x).diff(x) + f(x)/x * (1 + (x**(S(2)/3)*f(x))**2), 0),
'sol': [Eq(-3*log(x**(S(2)/3)*f(x)) + 3*log(3*x**(S(4)/3)*f(x)**2 + 1)/2, C1 + log(x))],
'simplify_flag': False,
},
'separable_reduced_05': {
'eq': Eq(f(x).diff(x) + f(x)/x * (1 + (x*f(x))**2), 0),
'sol': [Eq(f(x), -sqrt(2)*sqrt(1/(C1 + log(x)))/(2*x)),\
Eq(f(x), sqrt(2)*sqrt(1/(C1 + log(x)))/(2*x))],
},
'separable_reduced_06': {
'eq': Eq(f(x).diff(x) + (x**4*f(x)**2 + x**2*f(x))*f(x)/(x*(x**6*f(x)**3 + x**4*f(x)**2)), 0),
'sol': [Eq(f(x), C1 + 1/(2*x**2))],
},
'separable_reduced_07': {
'eq': Eq(f(x).diff(x) + (f(x)**2)*f(x)/(x), 0),
'sol': [
Eq(f(x), -sqrt(2)*sqrt(1/(C1 + log(x)))/2),
Eq(f(x), sqrt(2)*sqrt(1/(C1 + log(x)))/2)
],
},
'separable_reduced_08': {
'eq': Eq(f(x).diff(x) + (f(x)+3)*f(x)/(x*(f(x)+2)), 0),
'sol': [Eq(-log(f(x) + 3)/3 - 2*log(f(x))/3, C1 + log(x))],
'simplify_flag': False,
'XFAIL': ['lie_group'], #It hangs.
},
'separable_reduced_09': {
'eq': Eq(f(x).diff(x) + (f(x)+3)*f(x)/x, 0),
'sol': [Eq(f(x), 3/(C1*x**3 - 1))],
},
'separable_reduced_10': {
'eq': Eq(f(x).diff(x) + (f(x)**2+f(x))*f(x)/(x), 0),
'sol': [Eq(- log(x) - log(f(x) + 1) + log(f(x)) + 1/f(x), C1)],
'XFAIL': ['lie_group'],#No algorithms are implemented to solve equation -C1 + x*(_y + 1)*exp(-1/_y)/_y
},
# Equivalent to example_name 'separable_reduced_02'. Only difference is testing with simplify=True
'separable_reduced_11': {
'eq': f(x).diff(x) + (f(x) / (x**4*f(x) - x)),
'sol': [Eq(f(x), -sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6
- sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
+ 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6
- 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3)),
Eq(f(x), -sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6
+ sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
+ 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6
- 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3)),
Eq(f(x), sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6
- sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
+ 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
+ 4/x**6 + 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3)),
Eq(f(x), sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6
+ sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1)
+ x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6 + 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1))
- exp(12*C1)/x**6)**Rational(1,3) - 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3))],
'checkodesol_XFAIL':True, #It hangs for this.
'slow': True,
},
#These were from issue: https://github.com/sympy/sympy/issues/6247
'separable_reduced_12': {
'eq': x**2*f(x)**2 + x*Derivative(f(x), x),
'sol': [Eq(f(x), 2*C1/(C1*x**2 - 1))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_lie_group():
a, b, c = symbols("a b c")
return {
'hint': "lie_group",
'func': f(x),
'examples':{
#Example 1-4 and 19-20 were from issue: https://github.com/sympy/sympy/issues/17322
'lie_group_01': {
'eq': x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x,
'sol': [],
'dsolve_too_slow': True,
'checkodesol_too_slow': True,
},
'lie_group_02': {
'eq': x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x,
'sol': [],
'dsolve_too_slow': True,
},
'lie_group_03': {
'eq': Eq(x**7*Derivative(f(x), x) + 5*x**3*f(x)**2 - (2*x**2 + 2)*f(x)**3, 0),
'sol': [],
'dsolve_too_slow': True,
},
'lie_group_04': {
'eq': f(x).diff(x) - (f(x) - x*log(x))**2/x**2 + log(x),
'sol': [],
'XFAIL': ['lie_group'],
},
'lie_group_05': {
'eq': f(x).diff(x)**2,
'sol': [Eq(f(x), C1)],
'XFAIL': ['factorable'], #It raises Not Implemented error
},
'lie_group_06': {
'eq': Eq(f(x).diff(x), x**2*f(x)),
'sol': [Eq(f(x), C1*exp(x**3)**Rational(1, 3))],
},
'lie_group_07': {
'eq': f(x).diff(x) + a*f(x) - c*exp(b*x),
'sol': [Eq(f(x), Piecewise(((-C1*(a + b) + c*exp(x*(a + b)))*exp(-a*x)/(a + b),\
Ne(a, -b)), ((-C1 + c*x)*exp(-a*x), True)))],
},
'lie_group_08': {
'eq': f(x).diff(x) + 2*x*f(x) - x*exp(-x**2),
'sol': [Eq(f(x), (C1 + x**2/2)*exp(-x**2))],
},
'lie_group_09': {
'eq': (1 + 2*x)*(f(x).diff(x)) + 2 - 4*exp(-f(x)),
'sol': [Eq(f(x), log(C1/(2*x + 1) + 2))],
},
'lie_group_10': {
'eq': x**2*(f(x).diff(x)) - f(x) + x**2*exp(x - (1/x)),
'sol': [Eq(f(x), -((C1 + exp(x))*exp(-1/x)))],
'XFAIL': ['factorable'], #It raises Recursion Error (maixmum depth exceeded)
},
'lie_group_11': {
'eq': x**2*f(x)**2 + x*Derivative(f(x), x),
'sol': [Eq(f(x), 2/(C1 + x**2))],
},
'lie_group_12': {
'eq': diff(f(x),x) + 2*x*f(x) - x*exp(-x**2),
'sol': [Eq(f(x), exp(-x**2)*(C1 + x**2/2))],
},
'lie_group_13': {
'eq': diff(f(x),x) + f(x)*cos(x) - exp(2*x),
'sol': [Eq(f(x), exp(-sin(x))*(C1 + Integral(exp(2*x)*exp(sin(x)), x)))],
},
'lie_group_14': {
'eq': diff(f(x),x) + f(x)*cos(x) - sin(2*x)/2,
'sol': [Eq(f(x), C1*exp(-sin(x)) + sin(x) - 1)],
},
'lie_group_15': {
'eq': x*diff(f(x),x) + f(x) - x*sin(x),
'sol': [Eq(f(x), (C1 - x*cos(x) + sin(x))/x)],
},
'lie_group_16': {
'eq': x*diff(f(x),x) - f(x) - x/log(x),
'sol': [Eq(f(x), x*(C1 + log(log(x))))],
},
'lie_group_17': {
'eq': (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x)),
'sol': [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))],
},
'lie_group_18': {
'eq': f(x).diff(x) * (f(x).diff(x) - f(x)),
'sol': [Eq(f(x), C1*exp(x)), Eq(f(x), C1)],
},
'lie_group_19': {
'eq': (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x)),
'sol': [Eq(f(x), C1*exp(-x)), Eq(f(x), C1*exp(x))],
},
'lie_group_20': {
'eq': f(x).diff(x)*(f(x).diff(x)+f(x)),
'sol': [Eq(f(x), C1), Eq(f(x), C1*exp(-x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_2nd_linear_airy():
return {
'hint': "2nd_linear_airy",
'func': f(x),
'examples':{
'2nd_lin_airy_01': {
'eq': f(x).diff(x, 2) - x*f(x),
'sol': [Eq(f(x), C1*airyai(x) + C2*airybi(x))],
},
'2nd_lin_airy_02': {
'eq': f(x).diff(x, 2) + 2*x*f(x),
'sol': [Eq(f(x), C1*airyai(-2**(S(1)/3)*x) + C2*airybi(-2**(S(1)/3)*x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_linear_constant_coeff_homogeneous():
# From Exercise 20, in Ordinary Differential Equations,
# Tenenbaum and Pollard, pg. 220
a = Symbol('a', positive=True)
k = Symbol('k', real=True)
r1, r2, r3, r4, r5 = [rootof(x**5 + 11*x - 2, n) for n in range(5)]
r6, r7, r8, r9, r10 = [rootof(x**5 - 3*x + 1, n) for n in range(5)]
r11, r12, r13, r14, r15 = [rootof(x**5 - 100*x**3 + 1000*x + 1, n) for n in range(5)]
r16, r17, r18, r19, r20 = [rootof(x**5 - x**4 + 10, n) for n in range(5)]
r21, r22, r23, r24, r25 = [rootof(x**5 - x + 1, n) for n in range(5)]
E = exp(1)
return {
'hint': "nth_linear_constant_coeff_homogeneous",
'func': f(x),
'examples':{
'lin_const_coeff_hom_01': {
'eq': f(x).diff(x, 2) + 2*f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*exp(-2*x))],
},
'lin_const_coeff_hom_02': {
'eq': f(x).diff(x, 2) - 3*f(x).diff(x) + 2*f(x),
'sol': [Eq(f(x), (C1 + C2*exp(x))*exp(x))],
},
'lin_const_coeff_hom_03': {
'eq': f(x).diff(x, 2) - f(x),
'sol': [Eq(f(x), C1*exp(-x) + C2*exp(x))],
},
'lin_const_coeff_hom_04': {
'eq': f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x))],
'slow': True,
},
'lin_const_coeff_hom_05': {
'eq': 6*f(x).diff(x, 2) - 11*f(x).diff(x) + 4*f(x),
'sol': [Eq(f(x), C1*exp(x/2) + C2*exp(x*Rational(4, 3)))],
'slow': True,
},
'lin_const_coeff_hom_06': {
'eq': Eq(f(x).diff(x, 2) + 2*f(x).diff(x) - f(x), 0),
'sol': [Eq(f(x), C1*exp(x*(-1 + sqrt(2))) + C2*exp(x*(-sqrt(2) - 1)))],
'slow': True,
},
'lin_const_coeff_hom_07': {
'eq': diff(f(x), x, 3) + diff(f(x), x, 2) - 10*diff(f(x), x) - 6*f(x),
'sol': [Eq(f(x), C1*exp(3*x) + C2*exp(x*(-2 - sqrt(2))) + C3*exp(x*(-2 + sqrt(2))))],
'slow': True,
},
'lin_const_coeff_hom_08': {
'eq': f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \
4*f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*exp(-2*x) + C3*exp(x) + C4*exp(2*x))],
'slow': True,
},
'lin_const_coeff_hom_09': {
'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 3) + f(x).diff(x, 2) - \
4*f(x).diff(x) - 2*f(x),
'sol': [Eq(f(x), C3*exp(-x) + C4*exp(x) + (C1*exp(-sqrt(2)*x) + C2*exp(sqrt(2)*x))*exp(-2*x))],
'slow': True,
},
'lin_const_coeff_hom_10': {
'eq': f(x).diff(x, 4) - a**2*f(x),
'sol': [Eq(f(x), C1*exp(-sqrt(a)*x) + C2*exp(sqrt(a)*x) + C3*sin(sqrt(a)*x) + C4*cos(sqrt(a)*x))],
'slow': True,
},
'lin_const_coeff_hom_11': {
'eq': f(x).diff(x, 2) - 2*k*f(x).diff(x) - 2*f(x),
'sol': [Eq(f(x), C1*exp(x*(k - sqrt(k**2 + 2))) + C2*exp(x*(k + sqrt(k**2 + 2))))],
'slow': True,
},
'lin_const_coeff_hom_12': {
'eq': f(x).diff(x, 2) + 4*k*f(x).diff(x) - 12*k**2*f(x),
'sol': [Eq(f(x), C1*exp(-6*k*x) + C2*exp(2*k*x))],
'slow': True,
},
'lin_const_coeff_hom_13': {
'eq': f(x).diff(x, 4),
'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3)],
'slow': True,
},
'lin_const_coeff_hom_14': {
'eq': f(x).diff(x, 2) + 4*f(x).diff(x) + 4*f(x),
'sol': [Eq(f(x), (C1 + C2*x)*exp(-2*x))],
'slow': True,
},
'lin_const_coeff_hom_15': {
'eq': 3*f(x).diff(x, 3) + 5*f(x).diff(x, 2) + f(x).diff(x) - f(x),
'sol': [Eq(f(x), (C1 + C2*x)*exp(-x) + C3*exp(x/3))],
'slow': True,
},
'lin_const_coeff_hom_16': {
'eq': f(x).diff(x, 3) - 6*f(x).diff(x, 2) + 12*f(x).diff(x) - 8*f(x),
'sol': [Eq(f(x), (C1 + x*(C2 + C3*x))*exp(2*x))],
'slow': True,
},
'lin_const_coeff_hom_17': {
'eq': f(x).diff(x, 2) - 2*a*f(x).diff(x) + a**2*f(x),
'sol': [Eq(f(x), (C1 + C2*x)*exp(a*x))],
'slow': True,
},
'lin_const_coeff_hom_18': {
'eq': f(x).diff(x, 4) + 3*f(x).diff(x, 3),
'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x))],
'slow': True,
},
'lin_const_coeff_hom_19': {
'eq': f(x).diff(x, 4) - 2*f(x).diff(x, 2),
'sol': [Eq(f(x), C1 + C2*x + C3*exp(-sqrt(2)*x) + C4*exp(sqrt(2)*x))],
'slow': True,
},
'lin_const_coeff_hom_20': {
'eq': f(x).diff(x, 4) + 2*f(x).diff(x, 3) - 11*f(x).diff(x, 2) - \
12*f(x).diff(x) + 36*f(x),
'sol': [Eq(f(x), (C1 + C2*x)*exp(-3*x) + (C3 + C4*x)*exp(2*x))],
'slow': True,
},
'lin_const_coeff_hom_21': {
'eq': 36*f(x).diff(x, 4) - 37*f(x).diff(x, 2) + 4*f(x).diff(x) + 5*f(x),
'sol': [Eq(f(x), C1*exp(-x) + C2*exp(-x/3) + C3*exp(x/2) + C4*exp(x*Rational(5, 6)))],
'slow': True,
},
'lin_const_coeff_hom_22': {
'eq': f(x).diff(x, 4) - 8*f(x).diff(x, 2) + 16*f(x),
'sol': [Eq(f(x), (C1 + C2*x)*exp(-2*x) + (C3 + C4*x)*exp(2*x))],
'slow': True,
},
'lin_const_coeff_hom_23': {
'eq': f(x).diff(x, 2) - 2*f(x).diff(x) + 5*f(x),
'sol': [Eq(f(x), (C1*sin(2*x) + C2*cos(2*x))*exp(x))],
'slow': True,
},
'lin_const_coeff_hom_24': {
'eq': f(x).diff(x, 2) - f(x).diff(x) + f(x),
'sol': [Eq(f(x), (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(x/2))],
'slow': True,
},
'lin_const_coeff_hom_25': {
'eq': f(x).diff(x, 4) + 5*f(x).diff(x, 2) + 6*f(x),
'sol': [Eq(f(x),
C1*sin(sqrt(2)*x) + C2*sin(sqrt(3)*x) + C3*cos(sqrt(2)*x) + C4*cos(sqrt(3)*x))],
'slow': True,
},
'lin_const_coeff_hom_26': {
'eq': f(x).diff(x, 2) - 4*f(x).diff(x) + 20*f(x),
'sol': [Eq(f(x), (C1*sin(4*x) + C2*cos(4*x))*exp(2*x))],
'slow': True,
},
'lin_const_coeff_hom_27': {
'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2) + 4*f(x),
'sol': [Eq(f(x), (C1 + C2*x)*sin(x*sqrt(2)) + (C3 + C4*x)*cos(x*sqrt(2)))],
'slow': True,
},
'lin_const_coeff_hom_28': {
'eq': f(x).diff(x, 3) + 8*f(x),
'sol': [Eq(f(x), (C1*sin(x*sqrt(3)) + C2*cos(x*sqrt(3)))*exp(x) + C3*exp(-2*x))],
'slow': True,
},
'lin_const_coeff_hom_29': {
'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2),
'sol': [Eq(f(x), C1 + C2*x + C3*sin(2*x) + C4*cos(2*x))],
'slow': True,
},
'lin_const_coeff_hom_30': {
'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x),
'sol': [Eq(f(x), C1 + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x))],
'slow': True,
},
'lin_const_coeff_hom_31': {
'eq': f(x).diff(x, 4) + f(x).diff(x, 2) + f(x),
'sol': [Eq(f(x), (C1*sin(sqrt(3)*x/2) + C2*cos(sqrt(3)*x/2))*exp(-x/2)
+ (C3*sin(sqrt(3)*x/2) + C4*cos(sqrt(3)*x/2))*exp(x/2))],
'slow': True,
},
'lin_const_coeff_hom_32': {
'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2) + f(x),
'sol': [Eq(f(x), C1*sin(x*sqrt(-sqrt(3) + 2)) + C2*sin(x*sqrt(sqrt(3) + 2))
+ C3*cos(x*sqrt(-sqrt(3) + 2)) + C4*cos(x*sqrt(sqrt(3) + 2)))],
'slow': True,
},
# One real root, two complex conjugate pairs
'lin_const_coeff_hom_33': {
'eq': f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x),
'sol': [Eq(f(x),
C5*exp(r1*x) + exp(re(r2)*x) * (C1*sin(im(r2)*x) + C2*cos(im(r2)*x))
+ exp(re(r4)*x) * (C3*sin(im(r4)*x) + C4*cos(im(r4)*x)))],
'checkodesol_XFAIL':True, #It Hangs
},
# Three real roots, one complex conjugate pair
'lin_const_coeff_hom_34': {
'eq': f(x).diff(x,5) - 3*f(x).diff(x) + f(x),
'sol': [Eq(f(x),
C3*exp(r6*x) + C4*exp(r7*x) + C5*exp(r8*x)
+ exp(re(r9)*x) * (C1*sin(im(r9)*x) + C2*cos(im(r9)*x)))],
'checkodesol_XFAIL':True, #It Hangs
},
# Five distinct real roots
'lin_const_coeff_hom_35': {
'eq': f(x).diff(x,5) - 100*f(x).diff(x,3) + 1000*f(x).diff(x) + f(x),
'sol': [Eq(f(x), C1*exp(r11*x) + C2*exp(r12*x) + C3*exp(r13*x) + C4*exp(r14*x) + C5*exp(r15*x))],
'checkodesol_XFAIL':True, #It Hangs
},
# Rational root and unsolvable quintic
'lin_const_coeff_hom_36': {
'eq': f(x).diff(x, 6) - 6*f(x).diff(x, 5) + 5*f(x).diff(x, 4) + 10*f(x).diff(x) - 50 * f(x),
'sol': [Eq(f(x),
C5*exp(5*x)
+ C6*exp(x*r16)
+ exp(re(r17)*x) * (C1*sin(im(r17)*x) + C2*cos(im(r17)*x))
+ exp(re(r19)*x) * (C3*sin(im(r19)*x) + C4*cos(im(r19)*x)))],
'checkodesol_XFAIL':True, #It Hangs
},
# Five double roots (this is (x**5 - x + 1)**2)
'lin_const_coeff_hom_37': {
'eq': f(x).diff(x, 10) - 2*f(x).diff(x, 6) + 2*f(x).diff(x, 5)
+ f(x).diff(x, 2) - 2*f(x).diff(x, 1) + f(x),
'sol': [Eq(f(x), (C1 + C2*x)*exp(x*r21) + (C10*sin(x*im(r24)) + C7*x*sin(x*im(r24)) + (
C8 + C9*x)*cos(x*im(r24)))*exp(x*re(r24)) + (C3*x*sin(x*im(r22)) + C6*sin(x*im(r22)
) + (C4 + C5*x)*cos(x*im(r22)))*exp(x*re(r22)))],
'checkodesol_XFAIL':True, #It Hangs
},
'lin_const_coeff_hom_38': {
'eq': Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0),
'sol': [Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2))],
},
'lin_const_coeff_hom_39': {
'eq': Eq(E * f(x).diff(x,x,x) + f(x).diff(x), 0),
'sol': [Eq(f(x), C1 + C2*sin(x/sqrt(E)) + C3*cos(x/sqrt(E)))],
},
'lin_const_coeff_hom_40': {
'eq': Eq(pi * f(x).diff(x,x,x) + f(x).diff(x), 0),
'sol': [Eq(f(x), C1 + C2*sin(x/sqrt(pi)) + C3*cos(x/sqrt(pi)))],
},
'lin_const_coeff_hom_41': {
'eq': Eq(I * f(x).diff(x,x,x) + f(x).diff(x), 0),
'sol': [Eq(f(x), C1 + C2*exp(-sqrt(I)*x) + C3*exp(sqrt(I)*x))],
},
'lin_const_coeff_hom_42': {
'eq': f(x).diff(x, x) + y*f(x),
'sol': [Eq(f(x), C1*exp(-x*sqrt(-y)) + C2*exp(x*sqrt(-y)))],
},
'lin_const_coeff_hom_43': {
'eq': Eq(9*f(x).diff(x, x) + f(x), 0),
'sol': [Eq(f(x), C1*sin(x/3) + C2*cos(x/3))],
},
'lin_const_coeff_hom_44': {
'eq': Eq(9*f(x).diff(x, x), f(x)),
'sol': [Eq(f(x), C1*exp(-x/3) + C2*exp(x/3))],
},
'lin_const_coeff_hom_45': {
'eq': Eq(f(x).diff(x, x) - 3*diff(f(x), x) + 2*f(x), 0),
'sol': [Eq(f(x), (C1 + C2*exp(x))*exp(x))],
},
'lin_const_coeff_hom_46': {
'eq': Eq(f(x).diff(x, x) - 4*diff(f(x), x) + 4*f(x), 0),
'sol': [Eq(f(x), (C1 + C2*x)*exp(2*x))],
},
# Type: 2nd order, constant coefficients (two real equal roots)
'lin_const_coeff_hom_47': {
'eq': Eq(f(x).diff(x, x) + 2*diff(f(x), x) + 3*f(x), 0),
'sol': [Eq(f(x), (C1*sin(x*sqrt(2)) + C2*cos(x*sqrt(2)))*exp(-x))],
},
#These were from issue: https://github.com/sympy/sympy/issues/6247
'lin_const_coeff_hom_48': {
'eq': f(x).diff(x, x) + 4*f(x),
'sol': [Eq(f(x), C1*sin(2*x) + C2*cos(2*x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_1st_homogeneous_coeff_subs_dep_div_indep():
return {
'hint': "1st_homogeneous_coeff_subs_dep_div_indep",
'func': f(x),
'examples':{
'dep_div_indep_01': {
'eq': f(x)/x*cos(f(x)/x) - (x/f(x)*sin(f(x)/x) + cos(f(x)/x))*f(x).diff(x),
'sol': [Eq(log(x), C1 - log(f(x)*sin(f(x)/x)/x))],
'slow': True
},
#indep_div_dep actually has a simpler solution for example 2 but it runs too slow.
'dep_div_indep_02': {
'eq': x*f(x).diff(x) - f(x) - x*sin(f(x)/x),
'sol': [Eq(log(x), log(C1) + log(cos(f(x)/x) - 1)/2 - log(cos(f(x)/x) + 1)/2)],
'simplify_flag':False,
},
'dep_div_indep_03': {
'eq': x*exp(f(x)/x) - f(x)*sin(f(x)/x) + x*sin(f(x)/x)*f(x).diff(x),
'sol': [Eq(log(x), C1 + exp(-f(x)/x)*sin(f(x)/x)/2 + exp(-f(x)/x)*cos(f(x)/x)/2)],
'slow': True
},
'dep_div_indep_04': {
'eq': f(x).diff(x) - f(x)/x + 1/sin(f(x)/x),
'sol': [Eq(f(x), x*(-acos(C1 + log(x)) + 2*pi)), Eq(f(x), x*acos(C1 + log(x)))],
'slow': True
},
# previous code was testing with these other solution:
# example5_solb = Eq(f(x), log(log(C1/x)**(-x)))
'dep_div_indep_05': {
'eq': x*exp(f(x)/x) + f(x) - x*f(x).diff(x),
'sol': [Eq(f(x), log((1/(C1 - log(x)))**x))],
'checkodesol_XFAIL':True, #(because of **x?)
},
}
}
@_add_example_keys
def _get_examples_ode_sol_linear_coefficients():
return {
'hint': "linear_coefficients",
'func': f(x),
'examples':{
'linear_coeff_01': {
'eq': f(x).diff(x) + (3 + 2*f(x))/(x + 3),
'sol': [Eq(f(x), C1/(x**2 + 6*x + 9) - Rational(3, 2))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_1st_homogeneous_coeff_best():
return {
'hint': "1st_homogeneous_coeff_best",
'func': f(x),
'examples':{
# previous code was testing this with other solution:
# example1_solb = Eq(-f(x)/(1 + log(x/f(x))), C1)
'1st_homogeneous_coeff_best_01': {
'eq': f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x),
'sol': [Eq(f(x), -exp(C1)*LambertW(-x*exp(-C1 + 1)))],
'checkodesol_XFAIL':True, #(because of LambertW?)
},
'1st_homogeneous_coeff_best_02': {
'eq': 2*f(x)*exp(x/f(x)) + f(x)*f(x).diff(x) - 2*x*exp(x/f(x))*f(x).diff(x),
'sol': [Eq(log(f(x)), C1 - 2*exp(x/f(x)))],
},
# previous code was testing this with other solution:
# example3_solb = Eq(log(C1*x*sqrt(1/x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0)
'1st_homogeneous_coeff_best_03': {
'eq': 2*x**2*f(x) + f(x)**3 + (x*f(x)**2 - 2*x**3)*f(x).diff(x),
'sol': [Eq(f(x), exp(2*C1 + LambertW(-2*x**4*exp(-4*C1))/2)/x)],
'checkodesol_XFAIL':True, #(because of LambertW?)
},
'1st_homogeneous_coeff_best_04': {
'eq': (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x),
'sol': [Eq(log(f(x)), C1 - 2*sqrt(-x/f(x) + 1))],
'slow': True,
},
'1st_homogeneous_coeff_best_05': {
'eq': x + f(x) - (x - f(x))*f(x).diff(x),
'sol': [Eq(log(x), C1 - log(sqrt(1 + f(x)**2/x**2)) + atan(f(x)/x))],
},
'1st_homogeneous_coeff_best_06': {
'eq': x*f(x).diff(x) - f(x) - x*sin(f(x)/x),
'sol': [Eq(f(x), 2*x*atan(C1*x))],
},
'1st_homogeneous_coeff_best_07': {
'eq': x**2 + f(x)**2 - 2*x*f(x)*f(x).diff(x),
'sol': [Eq(f(x), -sqrt(x*(C1 + x))), Eq(f(x), sqrt(x*(C1 + x)))],
},
'1st_homogeneous_coeff_best_08': {
'eq': f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x),
'sol': [Eq(log(x), C1 - log(f(x)/x) + acosh(f(x)/x))],
},
}
}
def _get_all_examples():
all_examples = _get_examples_ode_sol_euler_homogeneous + \
_get_examples_ode_sol_euler_undetermined_coeff + \
_get_examples_ode_sol_euler_var_para + \
_get_examples_ode_sol_factorable + \
_get_examples_ode_sol_bernoulli + \
_get_examples_ode_sol_nth_algebraic + \
_get_examples_ode_sol_riccati + \
_get_examples_ode_sol_1st_linear + \
_get_examples_ode_sol_1st_exact + \
_get_examples_ode_sol_almost_linear + \
_get_examples_ode_sol_nth_order_reducible + \
_get_examples_ode_sol_nth_linear_undetermined_coefficients + \
_get_examples_ode_sol_liouville + \
_get_examples_ode_sol_separable + \
_get_examples_ode_sol_nth_linear_var_of_parameters + \
_get_examples_ode_sol_2nd_linear_bessel + \
_get_examples_ode_sol_2nd_2F1_hypergeometric + \
_get_examples_ode_sol_2nd_nonlinear_autonomous_conserved + \
_get_examples_ode_sol_separable_reduced + \
_get_examples_ode_sol_lie_group + \
_get_examples_ode_sol_2nd_linear_airy + \
_get_examples_ode_sol_nth_linear_constant_coeff_homogeneous +\
_get_examples_ode_sol_1st_homogeneous_coeff_best +\
_get_examples_ode_sol_1st_homogeneous_coeff_subs_dep_div_indep +\
_get_examples_ode_sol_linear_coefficients
return all_examples
|
af66ed7c824911240528a81f9d8bfc50a158d5436b10831d209fabc91bce6f92 | from sympy import (Symbol, S, exp, log, sqrt, oo, E, zoo, pi, tan, sin, cos,
cot, sec, csc, Abs, symbols, I, re, simplify,
expint, Rational, Piecewise)
from sympy.calculus.util import (function_range, continuous_domain, not_empty_in,
periodicity, lcim, AccumBounds, is_convex,
stationary_points, minimum, maximum)
from sympy.core import Add, Mul, Pow
from sympy.core.expr import unchanged
from sympy.sets.sets import (Interval, FiniteSet, EmptySet, Complement,
Union)
from sympy.testing.pytest import raises, _both_exp_pow, XFAIL
from sympy.abc import x
a = Symbol('a', real=True)
B = AccumBounds
def test_function_range():
x, y, a, b = symbols('x y a b')
assert function_range(sin(x), x, Interval(-pi/2, pi/2)
) == Interval(-1, 1)
assert function_range(sin(x), x, Interval(0, pi)
) == Interval(0, 1)
assert function_range(tan(x), x, Interval(0, pi)
) == Interval(-oo, oo)
assert function_range(tan(x), x, Interval(pi/2, pi)
) == Interval(-oo, 0)
assert function_range((x + 3)/(x - 2), x, Interval(-5, 5)
) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo))
assert function_range(1/(x**2), x, Interval(-1, 1)
) == Interval(1, oo)
assert function_range(exp(x), x, Interval(-1, 1)
) == Interval(exp(-1), exp(1))
assert function_range(log(x) - x, x, S.Reals
) == Interval(-oo, -1)
assert function_range(sqrt(3*x - 1), x, Interval(0, 2)
) == Interval(0, sqrt(5))
assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals
) == FiniteSet(0)
assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals
) == FiniteSet(y)
assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4))
) == Union(Interval(-sin(3), 1), FiniteSet(sin(4)))
assert function_range(cos(x), x, Interval(-oo, -4)
) == Interval(-1, 1)
assert function_range(cos(x), x, S.EmptySet) == S.EmptySet
assert function_range(x/sqrt(x**2+1), x, S.Reals) == Interval.open(-1,1)
raises(NotImplementedError, lambda : function_range(
exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals))
raises(NotImplementedError, lambda : function_range(
sin(x) + x, x, S.Reals)) # issue 13273
raises(NotImplementedError, lambda : function_range(
log(x), x, S.Integers))
raises(NotImplementedError, lambda : function_range(
sin(x)/2, x, S.Naturals))
def test_continuous_domain():
x = Symbol('x')
assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi)
assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \
Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True),
Interval(pi*Rational(3, 2), 2*pi, True, False))
assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \
Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True))
assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \
Interval(Rational(1, 4), oo, True, True)
assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True)
assert continuous_domain(1/x - 2, x, S.Reals) == \
Union(Interval.open(-oo, 0), Interval.open(0, oo))
assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \
Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo))
domain = continuous_domain(log(tan(x)**2 + 1), x, S.Reals)
assert not domain.contains(3*pi/2)
assert domain.contains(5)
d = Symbol('d', even=True, zero=False)
assert continuous_domain(x**(1/d), x, S.Reals) == Interval(0, oo)
def test_not_empty_in():
assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \
Interval(S.Half, 2, True, False)
assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \
Union(Interval(-sqrt(2), -1), Interval(1, 2))
assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \
Union(Interval(-sqrt(17)/2 - S.Half, -2),
Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4))
assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \
Complement(S.Reals, FiniteSet(1))
assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \
Complement(S.Reals, FiniteSet(1))
assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \
Complement(S.Reals, FiniteSet(1))
assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
Interval(-oo, oo)
assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
Interval(S(3)/2, 2)
assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \
Complement(S.Reals, FiniteSet(-1, 1))
assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True),
Interval(4, 5))), x) == \
Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True),
Interval(1, 3, True, True), Interval(4, 5))
assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet
assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \
Union(Interval(-2, -1, True, False), Interval(2, oo))
raises(ValueError, lambda: not_empty_in(x))
raises(ValueError, lambda: not_empty_in(Interval(0, 1), x))
raises(NotImplementedError,
lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a))
@_both_exp_pow
def test_periodicity():
x = Symbol('x')
y = Symbol('y')
z = Symbol('z', real=True)
assert periodicity(sin(2*x), x) == pi
assert periodicity((-2)*tan(4*x), x) == pi/4
assert periodicity(sin(x)**2, x) == 2*pi
assert periodicity(3**tan(3*x), x) == pi/3
assert periodicity(tan(x)*cos(x), x) == 2*pi
assert periodicity(sin(x)**(tan(x)), x) == 2*pi
assert periodicity(tan(x)*sec(x), x) == 2*pi
assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2
assert periodicity(tan(x) + cot(x), x) == pi
assert periodicity(sin(x) - cos(2*x), x) == 2*pi
assert periodicity(sin(x) - 1, x) == 2*pi
assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi
assert periodicity(exp(sin(x)), x) == 2*pi
assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi
assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi
assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi
assert periodicity(tan(sin(2*x)), x) == pi
assert periodicity(2*tan(x)**2, x) == pi
assert periodicity(sin(x%4), x) == 4
assert periodicity(sin(x)%4, x) == 2*pi
assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3)
assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1)
assert periodicity((x**2+1) % x, x) is None
assert periodicity(sin(re(x)), x) == 2*pi
assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero
assert periodicity(tan(x), y) is S.Zero
assert periodicity(sin(x) + I*cos(x), x) == 2*pi
assert periodicity(x - sin(2*y), y) == pi
assert periodicity(exp(x), x) is None
assert periodicity(exp(I*x), x) == 2*pi
assert periodicity(exp(I*z), z) == 2*pi
assert periodicity(exp(z), z) is None
assert periodicity(exp(log(sin(z) + I*cos(2*z)), evaluate=False), z) == 2*pi
assert periodicity(exp(log(sin(2*z) + I*cos(z)), evaluate=False), z) == 2*pi
assert periodicity(exp(sin(z)), z) == 2*pi
assert periodicity(exp(2*I*z), z) == pi
assert periodicity(exp(z + I*sin(z)), z) is None
assert periodicity(exp(cos(z/2) + sin(z)), z) == 4*pi
assert periodicity(log(x), x) is None
assert periodicity(exp(x)**sin(x), x) is None
assert periodicity(sin(x)**y, y) is None
assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi
assert all(periodicity(Abs(f(x)), x) == pi for f in (
cos, sin, sec, csc, tan, cot))
assert periodicity(Abs(sin(tan(x))), x) == pi
assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi
assert periodicity(sin(x) > S.Half, x) == 2*pi
assert periodicity(x > 2, x) is None
assert periodicity(x**3 - x**2 + 1, x) is None
assert periodicity(Abs(x), x) is None
assert periodicity(Abs(x**2 - 1), x) is None
assert periodicity((x**2 + 4)%2, x) is None
assert periodicity((E**x)%3, x) is None
assert periodicity(sin(expint(1, x))/expint(1, x), x) is None
# returning `None` for any Piecewise
p = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True))
assert periodicity(p, x) is None
def test_periodicity_check():
x = Symbol('x')
y = Symbol('y')
assert periodicity(tan(x), x, check=True) == pi
assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi
assert periodicity(sec(x), x) == 2*pi
assert periodicity(sin(x*y), x) == 2*pi/abs(y)
assert periodicity(Abs(sec(sec(x))), x) == pi
def test_lcim():
from sympy import pi
assert lcim([S.Half, S(2), S(3)]) == 6
assert lcim([pi/2, pi/4, pi]) == pi
assert lcim([2*pi, pi/2]) == 2*pi
assert lcim([S.One, 2*pi]) is None
assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E
def test_is_convex():
assert is_convex(1/x, x, domain=Interval(0, oo)) == True
assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False
assert is_convex(x**2, x, domain=Interval(0, oo)) == True
assert is_convex(log(x), x) == False
raises(NotImplementedError, lambda: is_convex(log(x), x, a))
def test_stationary_points():
x, y = symbols('x y')
assert stationary_points(sin(x), x, Interval(-pi/2, pi/2)
) == {-pi/2, pi/2}
assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4)
) == EmptySet()
assert stationary_points(tan(x), x,
) == EmptySet()
assert stationary_points(sin(x)*cos(x), x, Interval(0, pi)
) == {pi/4, pi*Rational(3, 4)}
assert stationary_points(sec(x), x, Interval(0, pi)
) == {0, pi}
assert stationary_points((x+3)*(x-2), x
) == FiniteSet(Rational(-1, 2))
assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5)
) == EmptySet()
assert stationary_points((x**2+3)/(x-2), x
) == {2 - sqrt(7), 2 + sqrt(7)}
assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5)
) == {2 + sqrt(7)}
assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals
) == FiniteSet(-2, 0, Rational(5, 4))
assert stationary_points(exp(x), x
) == EmptySet()
assert stationary_points(log(x) - x, x, S.Reals
) == {1}
assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
) == {0, -pi, pi}
assert stationary_points(y, x, S.Reals
) == S.Reals
assert stationary_points(y, x, S.EmptySet) == S.EmptySet
def test_maximum():
x, y = symbols('x y')
assert maximum(sin(x), x) is S.One
assert maximum(sin(x), x, Interval(0, 1)) == sin(1)
assert maximum(tan(x), x) is oo
assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One
assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half
assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
) == sqrt(2)/4
assert maximum((x+3)*(x-2), x) is oo
assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14)
assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7)
assert simplify(maximum(-x**4-x**3+x**2+10, x)
) == 41*sqrt(41)/512 + Rational(5419, 512)
assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2)
assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne
assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
) is S.One
assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2)
assert maximum(y, x, S.Reals) == y
assert maximum(abs(a**3 + a), a, Interval(0, 2)) == 10
assert maximum(abs(60*a**3 + 24*a), a, Interval(0, 2)) == 528
assert maximum(abs(12*a*(5*a**2 + 2)), a, Interval(0, 2)) == 528
assert maximum(x/sqrt(x**2+1), x, S.Reals) == 1
raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet))
raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet))
raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet))
raises(ValueError, lambda : maximum(sin(x), sin(x)))
raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet))
raises(ValueError, lambda : maximum(sin(x), S.One))
def test_minimum():
x, y = symbols('x y')
assert minimum(sin(x), x) is S.NegativeOne
assert minimum(sin(x), x, Interval(1, 4)) == sin(4)
assert minimum(tan(x), x) is -oo
assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne
assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2)
assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
) == -sqrt(2)/4
assert minimum((x+3)*(x-2), x) == Rational(-25, 4)
assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2)
assert minimum(x**4-x**3+x**2+10, x) == S(10)
assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2)
assert minimum(log(x) - x, x, S.Reals) is -oo
assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
) is S.NegativeOne
assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2)
assert minimum(y, x, S.Reals) == y
assert minimum(x/sqrt(x**2+1), x, S.Reals) == -1
raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet))
raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet))
raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet))
raises(ValueError, lambda : minimum(sin(x), sin(x)))
raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet))
raises(ValueError, lambda : minimum(sin(x), S.One))
def test_issue_19869():
t = symbols('t')
assert (maximum(sqrt(3)*(t - 1)/(3*sqrt(t**2 + 1)), t)
) == sqrt(3)/3
def test_AccumBounds():
assert B(1, 2).args == (1, 2)
assert B(1, 2).delta is S.One
assert B(1, 2).mid == Rational(3, 2)
assert B(1, 3).is_real == True
assert B(1, 1) is S.One
assert B(1, 2) + 1 == B(2, 3)
assert 1 + B(1, 2) == B(2, 3)
assert B(1, 2) + B(2, 3) == B(3, 5)
assert -B(1, 2) == B(-2, -1)
assert B(1, 2) - 1 == B(0, 1)
assert 1 - B(1, 2) == B(-1, 0)
assert B(2, 3) - B(1, 2) == B(0, 2)
assert x + B(1, 2) == Add(B(1, 2), x)
assert a + B(1, 2) == B(1 + a, 2 + a)
assert B(1, 2) - x == Add(B(1, 2), -x)
assert B(-oo, 1) + oo == B(-oo, oo)
assert B(1, oo) + oo is oo
assert B(1, oo) - oo == B(-oo, oo)
assert (-oo - B(-1, oo)) is -oo
assert B(-oo, 1) - oo is -oo
assert B(1, oo) - oo == B(-oo, oo)
assert B(-oo, 1) - (-oo) == B(-oo, oo)
assert (oo - B(1, oo)) == B(-oo, oo)
assert (-oo - B(1, oo)) is -oo
assert B(1, 2)/2 == B(S.Half, 1)
assert 2/B(2, 3) == B(Rational(2, 3), 1)
assert 1/B(-1, 1) == B(-oo, oo)
assert abs(B(1, 2)) == B(1, 2)
assert abs(B(-2, -1)) == B(1, 2)
assert abs(B(-2, 1)) == B(0, 2)
assert abs(B(-1, 2)) == B(0, 2)
c = Symbol('c')
raises(ValueError, lambda: B(0, c))
raises(ValueError, lambda: B(1, -1))
r = Symbol('r', real=True)
raises(ValueError, lambda: B(r, r - 1))
def test_AccumBounds_mul():
assert B(1, 2)*2 == B(2, 4)
assert 2*B(1, 2) == B(2, 4)
assert B(1, 2)*B(2, 3) == B(2, 6)
assert B(0, 2)*B(2, oo) == B(0, oo)
l, r = B(-oo, oo), B(-a, a)
assert l*r == B(-oo, oo)
assert r*l == B(-oo, oo)
l, r = B(1, oo), B(-3, -2)
assert l*r == B(-oo, -2)
assert r*l == B(-oo, -2)
assert B(1, 2)*0 == 0
assert B(1, oo)*0 == B(0, oo)
assert B(-oo, 1)*0 == B(-oo, 0)
assert B(-oo, oo)*0 == B(-oo, oo)
assert B(1, 2)*x == Mul(B(1, 2), x, evaluate=False)
assert B(0, 2)*oo == B(0, oo)
assert B(-2, 0)*oo == B(-oo, 0)
assert B(0, 2)*(-oo) == B(-oo, 0)
assert B(-2, 0)*(-oo) == B(0, oo)
assert B(-1, 1)*oo == B(-oo, oo)
assert B(-1, 1)*(-oo) == B(-oo, oo)
assert B(-oo, oo)*oo == B(-oo, oo)
def test_AccumBounds_div():
assert B(-1, 3)/B(3, 4) == B(Rational(-1, 3), 1)
assert B(-2, 4)/B(-3, 4) == B(-oo, oo)
assert B(-3, -2)/B(-4, 0) == B(S.Half, oo)
# these two tests can have a better answer
# after Union of B is improved
assert B(-3, -2)/B(-2, 1) == B(-oo, oo)
assert B(2, 3)/B(-2, 2) == B(-oo, oo)
assert B(-3, -2)/B(0, 4) == B(-oo, Rational(-1, 2))
assert B(2, 4)/B(-3, 0) == B(-oo, Rational(-2, 3))
assert B(2, 4)/B(0, 3) == B(Rational(2, 3), oo)
assert B(0, 1)/B(0, 1) == B(0, oo)
assert B(-1, 0)/B(0, 1) == B(-oo, 0)
assert B(-1, 2)/B(-2, 2) == B(-oo, oo)
assert 1/B(-1, 2) == B(-oo, oo)
assert 1/B(0, 2) == B(S.Half, oo)
assert (-1)/B(0, 2) == B(-oo, Rational(-1, 2))
assert 1/B(-oo, 0) == B(-oo, 0)
assert 1/B(-1, 0) == B(-oo, -1)
assert (-2)/B(-oo, 0) == B(0, oo)
assert 1/B(-oo, -1) == B(-1, 0)
assert B(1, 2)/a == Mul(B(1, 2), 1/a, evaluate=False)
assert B(1, 2)/0 == B(1, 2)*zoo
assert B(1, oo)/oo == B(0, oo)
assert B(1, oo)/(-oo) == B(-oo, 0)
assert B(-oo, -1)/oo == B(-oo, 0)
assert B(-oo, -1)/(-oo) == B(0, oo)
assert B(-oo, oo)/oo == B(-oo, oo)
assert B(-oo, oo)/(-oo) == B(-oo, oo)
assert B(-1, oo)/oo == B(0, oo)
assert B(-1, oo)/(-oo) == B(-oo, 0)
assert B(-oo, 1)/oo == B(-oo, 0)
assert B(-oo, 1)/(-oo) == B(0, oo)
def test_issue_18795():
r = Symbol('r', real=True)
a = B(-1,1)
c = B(7, oo)
b = B(-oo, oo)
assert c - tan(r) == B(7-tan(r), oo)
assert b + tan(r) == B(-oo, oo)
assert (a + r)/a == B(-oo, oo)*B(r - 1, r + 1)
assert (b + a)/a == B(-oo, oo)
def test_AccumBounds_func():
assert (x**2 + 2*x + 1).subs(x, B(-1, 1)) == B(-1, 4)
assert exp(B(0, 1)) == B(1, E)
assert exp(B(-oo, oo)) == B(0, oo)
assert log(B(3, 6)) == B(log(3), log(6))
@XFAIL
def test_AccumBounds_powf():
nn = Symbol('nn', nonnegative=True)
assert B(1 + nn, 2 + nn)**B(1, 2) == B(1 + nn, (2 + nn)**2)
i = Symbol('i', integer=True, negative=True)
assert B(1, 2)**i == B(2**i, 1)
def test_AccumBounds_pow():
assert B(0, 2)**2 == B(0, 4)
assert B(-1, 1)**2 == B(0, 1)
assert B(1, 2)**2 == B(1, 4)
assert B(-1, 2)**3 == B(-1, 8)
assert B(-1, 1)**0 == 1
assert B(1, 2)**Rational(5, 2) == B(1, 4*sqrt(2))
assert B(0, 2)**S.Half == B(0, sqrt(2))
neg = Symbol('neg', negative=True)
unchanged(Pow, B(neg, 1), S.Half)
nn = Symbol('nn', nonnegative=True)
assert B(nn, nn + 1)**S.Half == B(sqrt(nn), sqrt(nn + 1))
assert B(nn, nn + 1)**nn == B(nn**nn, (nn + 1)**nn)
unchanged(Pow, B(nn, nn + 1), x)
i = Symbol('i', integer=True)
unchanged(Pow, B(1, 2), i)
i = Symbol('i', integer=True, nonnegative=True)
assert B(1, 2)**i == B(1, 2**i)
assert B(0, 1)**i == B(0**i, 1)
assert B(1, 5)**(-2) == B(Rational(1, 25), 1)
assert B(-1, 3)**(-2) == B(0, oo)
assert B(0, 2)**(-3) == B(Rational(1, 8), oo)
assert B(-2, 0)**(-3) == B(-oo, -Rational(1, 8))
assert B(0, 2)**(-2) == B(Rational(1, 4), oo)
assert B(-1, 2)**(-3) == B(-oo, oo)
assert B(-3, -2)**(-3) == B(Rational(-1, 8), Rational(-1, 27))
assert B(-3, -2)**(-2) == B(Rational(1, 9), Rational(1, 4))
assert B(0, oo)**S.Half == B(0, oo)
assert B(-oo, 0)**(-2) == B(0, oo)
assert B(-2, 0)**(-2) == B(Rational(1, 4), oo)
assert B(Rational(1, 3), S.Half)**oo is S.Zero
assert B(0, S.Half)**oo is S.Zero
assert B(S.Half, 1)**oo == B(0, oo)
assert B(0, 1)**oo == B(0, oo)
assert B(2, 3)**oo is oo
assert B(1, 2)**oo == B(0, oo)
assert B(S.Half, 3)**oo == B(0, oo)
assert B(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero
assert B(-1, Rational(-1, 2))**oo is S.NaN
assert B(-3, -2)**oo is zoo
assert B(-2, -1)**oo is S.NaN
assert B(-2, Rational(-1, 2))**oo is S.NaN
assert B(Rational(-1, 2), S.Half)**oo is S.Zero
assert B(Rational(-1, 2), 1)**oo == B(0, oo)
assert B(Rational(-2, 3), 2)**oo == B(0, oo)
assert B(-1, 1)**oo == B(-oo, oo)
assert B(-1, S.Half)**oo == B(-oo, oo)
assert B(-1, 2)**oo == B(-oo, oo)
assert B(-2, S.Half)**oo == B(-oo, oo)
assert B(1, 2)**x == Pow(B(1, 2), x, evaluate=False)
assert B(2, 3)**(-oo) is S.Zero
assert B(0, 2)**(-oo) == B(0, oo)
assert B(-1, 2)**(-oo) == B(-oo, oo)
assert (tan(x)**sin(2*x)).subs(x, B(0, pi/2)) == \
Pow(B(-oo, oo), B(0, 1))
def test_AccumBounds_exponent():
# base is 0
z = 0**B(a, a + S.Half)
assert z.subs(a, 0) == B(0, 1)
assert z.subs(a, 1) == 0
p = z.subs(a, -1)
assert p.is_Pow and p.args == (0, B(-1, -S.Half))
# base > 0
# when base is 1 the type of bounds does not matter
assert 1**B(a, a + 1) == 1
# otherwise we need to know if 0 is in the bounds
assert S.Half**B(-2, 2) == B(S(1)/4, 4)
assert 2**B(-2, 2) == B(S(1)/4, 4)
# +eps may introduce +oo
# if there is a negative integer exponent
assert B(0, 1)**B(S(1)/2, 1) == B(0, 1)
assert B(0, 1)**B(0, 1) == B(0, 1)
# positive bases have positive bounds
assert B(2, 3)**B(-3, -2) == B(S(1)/27, S(1)/4)
assert B(2, 3)**B(-3, 2) == B(S(1)/27, 9)
# bounds generating imaginary parts unevaluated
unchanged(Pow, B(-1, 1), B(1, 2))
assert B(0, S(1)/2)**B(1, oo) == B(0, S(1)/2)
assert B(0, 1)**B(1, oo) == B(0, oo)
assert B(0, 2)**B(1, oo) == B(0, oo)
assert B(0, oo)**B(1, oo) == B(0, oo)
assert B(S(1)/2, 1)**B(1, oo) == B(0, oo)
assert B(S(1)/2, 1)**B(-oo, -1) == B(0, oo)
assert B(S(1)/2, 1)**B(-oo, oo) == B(0, oo)
assert B(S(1)/2, 2)**B(1, oo) == B(0, oo)
assert B(S(1)/2, 2)**B(-oo, -1) == B(0, oo)
assert B(S(1)/2, 2)**B(-oo, oo) == B(0, oo)
assert B(S(1)/2, oo)**B(1, oo) == B(0, oo)
assert B(S(1)/2, oo)**B(-oo, -1) == B(0, oo)
assert B(S(1)/2, oo)**B(-oo, oo) == B(0, oo)
assert B(1, 2)**B(1, oo) == B(0, oo)
assert B(1, 2)**B(-oo, -1) == B(0, oo)
assert B(1, 2)**B(-oo, oo) == B(0, oo)
assert B(1, oo)**B(1, oo) == B(0, oo)
assert B(1, oo)**B(-oo, -1) == B(0, oo)
assert B(1, oo)**B(-oo, oo) == B(0, oo)
assert B(2, oo)**B(1, oo) == B(2, oo)
assert B(2, oo)**B(-oo, -1) == B(0, S(1)/2)
assert B(2, oo)**B(-oo, oo) == B(0, oo)
def test_comparison_AccumBounds():
assert (B(1, 3) < 4) == S.true
assert (B(1, 3) < -1) == S.false
assert (B(1, 3) < 2).rel_op == '<'
assert (B(1, 3) <= 2).rel_op == '<='
assert (B(1, 3) > 4) == S.false
assert (B(1, 3) > -1) == S.true
assert (B(1, 3) > 2).rel_op == '>'
assert (B(1, 3) >= 2).rel_op == '>='
assert (B(1, 3) < B(4, 6)) == S.true
assert (B(1, 3) < B(2, 4)).rel_op == '<'
assert (B(1, 3) < B(-2, 0)) == S.false
assert (B(1, 3) <= B(4, 6)) == S.true
assert (B(1, 3) <= B(-2, 0)) == S.false
assert (B(1, 3) > B(4, 6)) == S.false
assert (B(1, 3) > B(-2, 0)) == S.true
assert (B(1, 3) >= B(4, 6)) == S.false
assert (B(1, 3) >= B(-2, 0)) == S.true
# issue 13499
assert (cos(x) > 0).subs(x, oo) == (B(-1, 1) > 0)
c = Symbol('c')
raises(TypeError, lambda: (B(0, 1) < c))
raises(TypeError, lambda: (B(0, 1) <= c))
raises(TypeError, lambda: (B(0, 1) > c))
raises(TypeError, lambda: (B(0, 1) >= c))
def test_contains_AccumBounds():
assert (1 in B(1, 2)) == S.true
raises(TypeError, lambda: a in B(1, 2))
assert 0 in B(-1, 0)
raises(TypeError, lambda:
(cos(1)**2 + sin(1)**2 - 1) in B(-1, 0))
assert (-oo in B(1, oo)) == S.true
assert (oo in B(-oo, 0)) == S.true
# issue 13159
assert Mul(0, B(-1, 1)) == Mul(B(-1, 1), 0) == 0
import itertools
for perm in itertools.permutations([0, B(-1, 1), x]):
assert Mul(*perm) == 0
def test_intersection_AccumBounds():
assert B(0, 3).intersection(B(1, 2)) == B(1, 2)
assert B(0, 3).intersection(B(1, 4)) == B(1, 3)
assert B(0, 3).intersection(B(-1, 2)) == B(0, 2)
assert B(0, 3).intersection(B(-1, 4)) == B(0, 3)
assert B(0, 1).intersection(B(2, 3)) == S.EmptySet
raises(TypeError, lambda: B(0, 3).intersection(1))
def test_union_AccumBounds():
assert B(0, 3).union(B(1, 2)) == B(0, 3)
assert B(0, 3).union(B(1, 4)) == B(0, 4)
assert B(0, 3).union(B(-1, 2)) == B(-1, 3)
assert B(0, 3).union(B(-1, 4)) == B(-1, 4)
raises(TypeError, lambda: B(0, 3).union(1))
def test_issue_16469():
x = Symbol("x", real=True)
f = abs(x)
assert function_range(f, x, S.Reals) == Interval(0, oo, False, True)
@_both_exp_pow
def test_issue_18747():
assert periodicity(exp(pi*I*(x/4+S.Half/2)), x) == 8
|
ce601f3c5eb6976e4e3b1d6afa6fbabfb86449d77e6d26c4d275658973b4694b | 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)
from sympy.core.relational import (Equality, GreaterThan, LessThan, Relational,
StrictGreaterThan, StrictLessThan, Unequality)
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.function import Derivative, Function, FunctionClass, Lambda, \
WildFunction
from sympy.sets.sets import Interval
from sympy.core.multidimensional import vectorize
from sympy.core.compatibility import HAS_GMPY
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy import symbols, S
from sympy.external import import_module
cloudpickle = import_module('cloudpickle')
excluded_attrs = {
'_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.
}
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)
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 import Poly, ZZ, QQ, lex
def test_pickling_polys_polytools():
from sympy.polys.polytools import PurePoly
# from sympy.polys.polytools import GroebnerBasis
x = Symbol('x')
for c in (Poly, Poly(x, x)):
check(c)
for c in (PurePoly, PurePoly(x)):
check(c)
# TODO: fix pickling of Options class (see GroebnerBasis._options)
# for c in (GroebnerBasis, GroebnerBasis([x**2 - 1], x, order=lex)):
# check(c)
def test_pickling_polys_polyclasses():
from sympy.polys.polyclasses import DMP, DMF, ANP
for c in (DMP, DMP([[ZZ(1)], [ZZ(2)], [ZZ(3)]], ZZ)):
check(c)
for c in (DMF, DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(3)]), ZZ)):
check(c)
for c in (ANP, ANP([QQ(1), QQ(2)], [QQ(1), QQ(2), QQ(3)], QQ)):
check(c)
@XFAIL
def test_pickling_polys_rings():
# NOTE: can't use protocols < 2 because we have to execute __new__ to
# make sure caching of rings works properly.
from sympy.polys.rings import PolyRing
ring = PolyRing("x,y,z", ZZ, lex)
for c in (PolyRing, ring):
check(c, exclude=[0, 1])
for c in (ring.dtype, ring.one):
check(c, exclude=[0, 1], check_attr=False) # TODO: Py3k
def test_pickling_polys_fields():
pass
# NOTE: can't use protocols < 2 because we have to execute __new__ to
# make sure caching of fields works properly.
# from sympy.polys.fields import FracField
# field = FracField("x,y,z", ZZ, lex)
# TODO: AssertionError: assert id(obj) not in self.memo
# for c in (FracField, field):
# check(c, exclude=[0, 1])
# TODO: AssertionError: assert id(obj) not in self.memo
# for c in (field.dtype, field.one):
# check(c, exclude=[0, 1])
def test_pickling_polys_elements():
from sympy.polys.domains.pythonrational import PythonRational
#from sympy.polys.domains.pythonfinitefield import PythonFiniteField
#from sympy.polys.domains.mpelements import MPContext
for c in (PythonRational, PythonRational(1, 7)):
check(c)
#gf = PythonFiniteField(17)
# TODO: fix pickling of ModularInteger
# for c in (gf.dtype, gf(5)):
# check(c)
#mp = MPContext()
# TODO: fix pickling of RealElement
# for c in (mp.mpf, mp.mpf(1.0)):
# check(c)
# TODO: fix pickling of ComplexElement
# for c in (mp.mpc, mp.mpc(1.0, -1.5)):
# check(c)
def test_pickling_polys_domains():
# from sympy.polys.domains.pythonfinitefield import PythonFiniteField
from sympy.polys.domains.pythonintegerring import PythonIntegerRing
from sympy.polys.domains.pythonrationalfield import PythonRationalField
# TODO: fix pickling of ModularInteger
# for c in (PythonFiniteField, PythonFiniteField(17)):
# check(c)
for c in (PythonIntegerRing, PythonIntegerRing()):
check(c, check_attr=False)
for c in (PythonRationalField, PythonRationalField()):
check(c, check_attr=False)
if HAS_GMPY:
# from sympy.polys.domains.gmpyfinitefield import GMPYFiniteField
from sympy.polys.domains.gmpyintegerring import GMPYIntegerRing
from sympy.polys.domains.gmpyrationalfield import GMPYRationalField
# TODO: fix pickling of ModularInteger
# for c in (GMPYFiniteField, GMPYFiniteField(17)):
# check(c)
for c in (GMPYIntegerRing, GMPYIntegerRing()):
check(c, check_attr=False)
for c in (GMPYRationalField, GMPYRationalField()):
check(c, check_attr=False)
#from sympy.polys.domains.realfield import RealField
#from sympy.polys.domains.complexfield import ComplexField
from sympy.polys.domains.algebraicfield import AlgebraicField
#from sympy.polys.domains.polynomialring import PolynomialRing
#from sympy.polys.domains.fractionfield import FractionField
from sympy.polys.domains.expressiondomain import ExpressionDomain
# TODO: fix pickling of RealElement
# for c in (RealField, RealField(100)):
# check(c)
# TODO: fix pickling of ComplexElement
# for c in (ComplexField, ComplexField(100)):
# check(c)
for c in (AlgebraicField, AlgebraicField(QQ, sqrt(3))):
check(c, check_attr=False)
# TODO: AssertionError
# for c in (PolynomialRing, PolynomialRing(ZZ, "x,y,z")):
# check(c)
# TODO: AttributeError: 'PolyElement' object has no attribute 'ring'
# for c in (FractionField, FractionField(ZZ, "x,y,z")):
# check(c)
for c in (ExpressionDomain, ExpressionDomain()):
check(c, check_attr=False)
def test_pickling_polys_numberfields():
from sympy.polys.numberfields import AlgebraicNumber
for c in (AlgebraicNumber, AlgebraicNumber(sqrt(3))):
check(c, check_attr=False)
def test_pickling_polys_orderings():
from sympy.polys.orderings import (LexOrder, GradedLexOrder,
ReversedGradedLexOrder, InverseOrder)
# from sympy.polys.orderings import ProductOrder
for c in (LexOrder, LexOrder()):
check(c)
for c in (GradedLexOrder, GradedLexOrder()):
check(c)
for c in (ReversedGradedLexOrder, ReversedGradedLexOrder()):
check(c)
# TODO: Argh, Python is so naive. No lambdas nor inner function support in
# pickling module. Maybe someone could figure out what to do with this.
#
# for c in (ProductOrder, ProductOrder((LexOrder(), lambda m: m[:2]),
# (GradedLexOrder(), lambda m: m[2:]))):
# check(c)
for c in (InverseOrder, InverseOrder(LexOrder())):
check(c)
def test_pickling_polys_monomials():
from sympy.polys.monomials import MonomialOps, Monomial
x, y, z = symbols("x,y,z")
for c in (MonomialOps, MonomialOps(3)):
check(c)
for c in (Monomial, Monomial((1, 2, 3), (x, y, z))):
check(c)
def test_pickling_polys_errors():
from sympy.polys.polyerrors import (HeuristicGCDFailed,
HomomorphismFailed, IsomorphismFailed, ExtraneousFactors,
EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible,
NotReversible, NotAlgebraic, DomainError, PolynomialError,
UnificationFailed, GeneratorsError, GeneratorsNeeded,
UnivariatePolynomialError, MultivariatePolynomialError, OptionError,
FlagError)
# from sympy.polys.polyerrors import (ExactQuotientFailed,
# OperationNotSupported, ComputationFailed, PolificationFailed)
# x = Symbol('x')
# TODO: TypeError: __init__() takes at least 3 arguments (1 given)
# for c in (ExactQuotientFailed, ExactQuotientFailed(x, 3*x, ZZ)):
# check(c)
# TODO: TypeError: can't pickle instancemethod objects
# for c in (OperationNotSupported, OperationNotSupported(Poly(x), Poly.gcd)):
# check(c)
for c in (HeuristicGCDFailed, HeuristicGCDFailed()):
check(c)
for c in (HomomorphismFailed, HomomorphismFailed()):
check(c)
for c in (IsomorphismFailed, IsomorphismFailed()):
check(c)
for c in (ExtraneousFactors, ExtraneousFactors()):
check(c)
for c in (EvaluationFailed, EvaluationFailed()):
check(c)
for c in (RefinementFailed, RefinementFailed()):
check(c)
for c in (CoercionFailed, CoercionFailed()):
check(c)
for c in (NotInvertible, NotInvertible()):
check(c)
for c in (NotReversible, NotReversible()):
check(c)
for c in (NotAlgebraic, NotAlgebraic()):
check(c)
for c in (DomainError, DomainError()):
check(c)
for c in (PolynomialError, PolynomialError()):
check(c)
for c in (UnificationFailed, UnificationFailed()):
check(c)
for c in (GeneratorsError, GeneratorsError()):
check(c)
for c in (GeneratorsNeeded, GeneratorsNeeded()):
check(c)
# TODO: PicklingError: Can't pickle <function <lambda> at 0x38578c0>: it's not found as __main__.<lambda>
# for c in (ComputationFailed, ComputationFailed(lambda t: t, 3, None)):
# check(c)
for c in (UnivariatePolynomialError, UnivariatePolynomialError()):
check(c)
for c in (MultivariatePolynomialError, MultivariatePolynomialError()):
check(c)
# TODO: TypeError: __init__() takes at least 3 arguments (1 given)
# for c in (PolificationFailed, PolificationFailed({}, x, x, False)):
# check(c)
for c in (OptionError, OptionError()):
check(c)
for c in (FlagError, FlagError()):
check(c)
#def test_pickling_polys_options():
#from sympy.polys.polyoptions import Options
# TODO: fix pickling of `symbols' flag
# for c in (Options, Options((), dict(domain='ZZ', polys=False))):
# check(c)
# TODO: def test_pickling_polys_rootisolation():
# RealInterval
# ComplexInterval
def test_pickling_polys_rootoftools():
from sympy.polys.rootoftools import CRootOf, RootSum
x = Symbol('x')
f = x**3 + x + 3
for c in (CRootOf, CRootOf(f, 0)):
check(c)
for c in (RootSum, RootSum(f, exp)):
check(c)
#================== printing ====================
from sympy.printing.latex import LatexPrinter
from sympy.printing.mathml import MathMLContentPrinter, MathMLPresentationPrinter
from sympy.printing.pretty.pretty import PrettyPrinter
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.printing.printer import Printer
from sympy.printing.python import PythonPrinter
def test_printing():
for c in (LatexPrinter, LatexPrinter(), MathMLContentPrinter,
MathMLPresentationPrinter, PrettyPrinter, prettyForm, stringPict,
stringPict("a"), Printer, Printer(), PythonPrinter,
PythonPrinter()):
check(c)
@XFAIL
def test_printing1():
check(MathMLContentPrinter())
@XFAIL
def test_printing2():
check(MathMLPresentationPrinter())
@XFAIL
def test_printing3():
check(PrettyPrinter())
#================== series ======================
from sympy.series.limits import Limit
from sympy.series.order import Order
def test_series():
e = Symbol("e")
x = Symbol("x")
for c in (Limit, Limit(e, x, 1), Order, Order(e)):
check(c)
#================== concrete ==================
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
def test_concrete():
x = Symbol("x")
for c in (Product, Product(x, (x, 2, 4)), Sum, Sum(x, (x, 2, 4))):
check(c)
def test_deprecation_warning():
w = SymPyDeprecationWarning('value', 'feature', issue=12345, deprecated_since_version='1.0')
check(w)
def test_issue_18438():
assert pickle.loads(pickle.dumps(S.Half)) == 1/2
|
77b67b4162fcfb9c31ad6971e29651d35ffed79f96cace157d5dff85c673f4d1 | from itertools import product
import math
import inspect
import mpmath
from sympy.testing.pytest import raises
from sympy import (
symbols, lambdify, sqrt, sin, cos, tan, pi, acos, acosh, Rational,
Float, Lambda, Piecewise, exp, E, Integral, oo, I, Abs, Function,
true, false, And, Or, Not, ITE, Min, Max, floor, diff, IndexedBase, Sum,
DotProduct, Eq, Dummy, sinc, erf, erfc, factorial, gamma, loggamma,
digamma, RisingFactorial, besselj, bessely, besseli, besselk, S, beta,
betainc, betainc_regularized, fresnelc, fresnels)
from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, log10, hypot
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.codegen.scipy_nodes import cosm1
from sympy.functions.elementary.complexes import re, im, arg
from sympy.functions.special.polynomials import \
chebyshevt, chebyshevu, legendre, hermite, laguerre, gegenbauer, \
assoc_legendre, assoc_laguerre, jacobi
from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix
from sympy.printing.lambdarepr import LambdaPrinter
from sympy.printing.numpy import NumPyPrinter
from sympy.utilities.lambdify import implemented_function, lambdastr
from sympy.testing.pytest import skip
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.external import import_module
from sympy.functions.special.gamma_functions import uppergamma, lowergamma
import sympy
MutableDenseMatrix = Matrix
numpy = import_module('numpy')
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
numexpr = import_module('numexpr')
tensorflow = import_module('tensorflow')
cupy = import_module('cupy')
if tensorflow:
# Hide Tensorflow warnings
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
w, x, y, z = symbols('w,x,y,z')
#================== Test different arguments =======================
def test_no_args():
f = lambdify([], 1)
raises(TypeError, lambda: f(-1))
assert f() == 1
def test_single_arg():
f = lambdify(x, 2*x)
assert f(1) == 2
def test_list_args():
f = lambdify([x, y], x + y)
assert f(1, 2) == 3
def test_nested_args():
f1 = lambdify([[w, x]], [w, x])
assert f1([91, 2]) == [91, 2]
raises(TypeError, lambda: f1(1, 2))
f2 = lambdify([(w, x), (y, z)], [w, x, y, z])
assert f2((18, 12), (73, 4)) == [18, 12, 73, 4]
raises(TypeError, lambda: f2(3, 4))
f3 = lambdify([w, [[[x]], y], z], [w, x, y, z])
assert f3(10, [[[52]], 31], 44) == [10, 52, 31, 44]
def test_str_args():
f = lambdify('x,y,z', 'z,y,x')
assert f(3, 2, 1) == (1, 2, 3)
assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0)
# make sure correct number of args required
raises(TypeError, lambda: f(0))
def test_own_namespace_1():
myfunc = lambda x: 1
f = lambdify(x, sin(x), {"sin": myfunc})
assert f(0.1) == 1
assert f(100) == 1
def test_own_namespace_2():
def myfunc(x):
return 1
f = lambdify(x, sin(x), {'sin': myfunc})
assert f(0.1) == 1
assert f(100) == 1
def test_own_module():
f = lambdify(x, sin(x), math)
assert f(0) == 0.0
def test_bad_args():
# no vargs given
raises(TypeError, lambda: lambdify(1))
# same with vector exprs
raises(TypeError, lambda: lambdify([1, 2]))
def test_atoms():
# Non-Symbol atoms should not be pulled out from the expression namespace
f = lambdify(x, pi + x, {"pi": 3.14})
assert f(0) == 3.14
f = lambdify(x, I + x, {"I": 1j})
assert f(1) == 1 + 1j
#================== Test different modules =========================
# high precision output of sin(0.2*pi) is used to detect if precision is lost unwanted
@conserve_mpmath_dps
def test_sympy_lambda():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin(x), "sympy")
assert f(x) == sin(x)
prec = 1e-15
assert -prec < f(Rational(1, 5)).evalf() - Float(str(sin02)) < prec
# arctan is in numpy module and should not be available
# The arctan below gives NameError. What is this supposed to test?
# raises(NameError, lambda: lambdify(x, arctan(x), "sympy"))
@conserve_mpmath_dps
def test_math_lambda():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin(x), "math")
prec = 1e-15
assert -prec < f(0.2) - sin02 < prec
raises(TypeError, lambda: f(x))
# if this succeeds, it can't be a python math function
@conserve_mpmath_dps
def test_mpmath_lambda():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin(x), "mpmath")
prec = 1e-49 # mpmath precision is around 50 decimal places
assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec
raises(TypeError, lambda: f(x))
# if this succeeds, it can't be a mpmath function
@conserve_mpmath_dps
def test_number_precision():
mpmath.mp.dps = 50
sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
f = lambdify(x, sin02, "mpmath")
prec = 1e-49 # mpmath precision is around 50 decimal places
assert -prec < f(0) - sin02 < prec
@conserve_mpmath_dps
def test_mpmath_precision():
mpmath.mp.dps = 100
assert str(lambdify((), pi.evalf(100), 'mpmath')()) == str(pi.evalf(100))
#================== Test Translations ==============================
# We can only check if all translated functions are valid. It has to be checked
# by hand if they are complete.
def test_math_transl():
from sympy.utilities.lambdify import MATH_TRANSLATIONS
for sym, mat in MATH_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert mat in math.__dict__
def test_mpmath_transl():
from sympy.utilities.lambdify import MPMATH_TRANSLATIONS
for sym, mat in MPMATH_TRANSLATIONS.items():
assert sym in sympy.__dict__ or sym == 'Matrix'
assert mat in mpmath.__dict__
def test_numpy_transl():
if not numpy:
skip("numpy not installed.")
from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
for sym, nump in NUMPY_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert nump in numpy.__dict__
def test_scipy_transl():
if not scipy:
skip("scipy not installed.")
from sympy.utilities.lambdify import SCIPY_TRANSLATIONS
for sym, scip in SCIPY_TRANSLATIONS.items():
assert sym in sympy.__dict__
assert scip in scipy.__dict__ or scip in scipy.special.__dict__
def test_numpy_translation_abs():
if not numpy:
skip("numpy not installed.")
f = lambdify(x, Abs(x), "numpy")
assert f(-1) == 1
assert f(1) == 1
def test_numexpr_printer():
if not numexpr:
skip("numexpr not installed.")
# if translation/printing is done incorrectly then evaluating
# a lambdified numexpr expression will throw an exception
from sympy.printing.lambdarepr import NumExprPrinter
blacklist = ('where', 'complex', 'contains')
arg_tuple = (x, y, z) # some functions take more than one argument
for sym in NumExprPrinter._numexpr_functions.keys():
if sym in blacklist:
continue
ssym = S(sym)
if hasattr(ssym, '_nargs'):
nargs = ssym._nargs[0]
else:
nargs = 1
args = arg_tuple[:nargs]
f = lambdify(args, ssym(*args), modules='numexpr')
assert f(*(1, )*nargs) is not None
def test_issue_9334():
if not numexpr:
skip("numexpr not installed.")
if not numpy:
skip("numpy not installed.")
expr = S('b*a - sqrt(a**2)')
a, b = sorted(expr.free_symbols, key=lambda s: s.name)
func_numexpr = lambdify((a,b), expr, modules=[numexpr], dummify=False)
foo, bar = numpy.random.random((2, 4))
func_numexpr(foo, bar)
def test_issue_12984():
import warnings
if not numexpr:
skip("numexpr not installed.")
func_numexpr = lambdify((x,y,z), Piecewise((y, x >= 0), (z, x > -1)), numexpr)
assert func_numexpr(1, 24, 42) == 24
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
assert str(func_numexpr(-1, 24, 42)) == 'nan'
#================== Test some functions ============================
def test_exponentiation():
f = lambdify(x, x**2)
assert f(-1) == 1
assert f(0) == 0
assert f(1) == 1
assert f(-2) == 4
assert f(2) == 4
assert f(2.5) == 6.25
def test_sqrt():
f = lambdify(x, sqrt(x))
assert f(0) == 0.0
assert f(1) == 1.0
assert f(4) == 2.0
assert abs(f(2) - 1.414) < 0.001
assert f(6.25) == 2.5
def test_trig():
f = lambdify([x], [cos(x), sin(x)], 'math')
d = f(pi)
prec = 1e-11
assert -prec < d[0] + 1 < prec
assert -prec < d[1] < prec
d = f(3.14159)
prec = 1e-5
assert -prec < d[0] + 1 < prec
assert -prec < d[1] < prec
def test_integral():
f = Lambda(x, exp(-x**2))
l = lambdify(y, Integral(f(x), (x, y, oo)))
d = l(-oo)
assert 1.77245385 < d < 1.772453851
def test_double_integral():
# example from http://mpmath.org/doc/current/calculus/integration.html
i = Integral(1/(1 - x**2*y**2), (x, 0, 1), (y, 0, z))
l = lambdify([z], i)
d = l(1)
assert 1.23370055 < d < 1.233700551
#================== Test vectors ===================================
def test_vector_simple():
f = lambdify((x, y, z), (z, y, x))
assert f(3, 2, 1) == (1, 2, 3)
assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0)
# make sure correct number of args required
raises(TypeError, lambda: f(0))
def test_vector_discontinuous():
f = lambdify(x, (-1/x, 1/x))
raises(ZeroDivisionError, lambda: f(0))
assert f(1) == (-1.0, 1.0)
assert f(2) == (-0.5, 0.5)
assert f(-2) == (0.5, -0.5)
def test_trig_symbolic():
f = lambdify([x], [cos(x), sin(x)], 'math')
d = f(pi)
assert abs(d[0] + 1) < 0.0001
assert abs(d[1] - 0) < 0.0001
def test_trig_float():
f = lambdify([x], [cos(x), sin(x)])
d = f(3.14159)
assert abs(d[0] + 1) < 0.0001
assert abs(d[1] - 0) < 0.0001
def test_docs():
f = lambdify(x, x**2)
assert f(2) == 4
f = lambdify([x, y, z], [z, y, x])
assert f(1, 2, 3) == [3, 2, 1]
f = lambdify(x, sqrt(x))
assert f(4) == 2.0
f = lambdify((x, y), sin(x*y)**2)
assert f(0, 5) == 0
def test_math():
f = lambdify((x, y), sin(x), modules="math")
assert f(0, 5) == 0
def test_sin():
f = lambdify(x, sin(x)**2)
assert isinstance(f(2), float)
f = lambdify(x, sin(x)**2, modules="math")
assert isinstance(f(2), float)
def test_matrix():
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol = Matrix([[1, 2], [sin(3) + 4, 1]])
f = lambdify((x, y, z), A, modules="sympy")
assert f(1, 2, 3) == sol
f = lambdify((x, y, z), (A, [A]), modules="sympy")
assert f(1, 2, 3) == (sol, [sol])
J = Matrix((x, x + y)).jacobian((x, y))
v = Matrix((x, y))
sol = Matrix([[1, 0], [1, 1]])
assert lambdify(v, J, modules='sympy')(1, 2) == sol
assert lambdify(v.T, J, modules='sympy')(1, 2) == sol
def test_numpy_matrix():
if not numpy:
skip("numpy not installed.")
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]])
#Lambdify array first, to ensure return to array as default
f = lambdify((x, y, z), A, ['numpy'])
numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
#Check that the types are arrays and matrices
assert isinstance(f(1, 2, 3), numpy.ndarray)
# gh-15071
class dot(Function):
pass
x_dot_mtx = dot(x, Matrix([[2], [1], [0]]))
f_dot1 = lambdify(x, x_dot_mtx)
inp = numpy.zeros((17, 3))
assert numpy.all(f_dot1(inp) == 0)
strict_kw = dict(allow_unknown_functions=False, inline=True, fully_qualified_modules=False)
p2 = NumPyPrinter(dict(user_functions={'dot': 'dot'}, **strict_kw))
f_dot2 = lambdify(x, x_dot_mtx, printer=p2)
assert numpy.all(f_dot2(inp) == 0)
p3 = NumPyPrinter(strict_kw)
# The line below should probably fail upon construction (before calling with "(inp)"):
raises(Exception, lambda: lambdify(x, x_dot_mtx, printer=p3)(inp))
def test_numpy_transpose():
if not numpy:
skip("numpy not installed.")
A = Matrix([[1, x], [0, 1]])
f = lambdify((x), A.T, modules="numpy")
numpy.testing.assert_array_equal(f(2), numpy.array([[1, 0], [2, 1]]))
def test_numpy_dotproduct():
if not numpy:
skip("numpy not installed")
A = Matrix([x, y, z])
f1 = lambdify([x, y, z], DotProduct(A, A), modules='numpy')
f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy')
f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='numpy')
f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy')
assert f1(1, 2, 3) == \
f2(1, 2, 3) == \
f3(1, 2, 3) == \
f4(1, 2, 3) == \
numpy.array([14])
def test_numpy_inverse():
if not numpy:
skip("numpy not installed.")
A = Matrix([[1, x], [0, 1]])
f = lambdify((x), A**-1, modules="numpy")
numpy.testing.assert_array_equal(f(2), numpy.array([[1, -2], [0, 1]]))
def test_numpy_old_matrix():
if not numpy:
skip("numpy not installed.")
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]])
f = lambdify((x, y, z), A, [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy'])
numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
assert isinstance(f(1, 2, 3), numpy.matrix)
def test_scipy_sparse_matrix():
if not scipy:
skip("scipy not installed.")
A = SparseMatrix([[x, 0], [0, y]])
f = lambdify((x, y), A, modules="scipy")
B = f(1, 2)
assert isinstance(B, scipy.sparse.coo_matrix)
def test_python_div_zero_issue_11306():
if not numpy:
skip("numpy not installed.")
p = Piecewise((1 / x, y < -1), (x, y < 1), (1 / x, True))
f = lambdify([x, y], p, modules='numpy')
numpy.seterr(divide='ignore')
assert float(f(numpy.array([0]),numpy.array([0.5]))) == 0
assert str(float(f(numpy.array([0]),numpy.array([1])))) == 'inf'
numpy.seterr(divide='warn')
def test_issue9474():
mods = [None, 'math']
if numpy:
mods.append('numpy')
if mpmath:
mods.append('mpmath')
for mod in mods:
f = lambdify(x, S.One/x, modules=mod)
assert f(2) == 0.5
f = lambdify(x, floor(S.One/x), modules=mod)
assert f(2) == 0
for absfunc, modules in product([Abs, abs], mods):
f = lambdify(x, absfunc(x), modules=modules)
assert f(-1) == 1
assert f(1) == 1
assert f(3+4j) == 5
def test_issue_9871():
if not numexpr:
skip("numexpr not installed.")
if not numpy:
skip("numpy not installed.")
r = sqrt(x**2 + y**2)
expr = diff(1/r, x)
xn = yn = numpy.linspace(1, 10, 16)
# expr(xn, xn) = -xn/(sqrt(2)*xn)^3
fv_exact = -numpy.sqrt(2.)**-3 * xn**-2
fv_numpy = lambdify((x, y), expr, modules='numpy')(xn, yn)
fv_numexpr = lambdify((x, y), expr, modules='numexpr')(xn, yn)
numpy.testing.assert_allclose(fv_numpy, fv_exact, rtol=1e-10)
numpy.testing.assert_allclose(fv_numexpr, fv_exact, rtol=1e-10)
def test_numpy_piecewise():
if not numpy:
skip("numpy not installed.")
pieces = Piecewise((x, x < 3), (x**2, x > 5), (0, True))
f = lambdify(x, pieces, modules="numpy")
numpy.testing.assert_array_equal(f(numpy.arange(10)),
numpy.array([0, 1, 2, 0, 0, 0, 36, 49, 64, 81]))
# If we evaluate somewhere all conditions are False, we should get back NaN
nodef_func = lambdify(x, Piecewise((x, x > 0), (-x, x < 0)))
numpy.testing.assert_array_equal(nodef_func(numpy.array([-1, 0, 1])),
numpy.array([1, numpy.nan, 1]))
def test_numpy_logical_ops():
if not numpy:
skip("numpy not installed.")
and_func = lambdify((x, y), And(x, y), modules="numpy")
and_func_3 = lambdify((x, y, z), And(x, y, z), modules="numpy")
or_func = lambdify((x, y), Or(x, y), modules="numpy")
or_func_3 = lambdify((x, y, z), Or(x, y, z), modules="numpy")
not_func = lambdify((x), Not(x), modules="numpy")
arr1 = numpy.array([True, True])
arr2 = numpy.array([False, True])
arr3 = numpy.array([True, False])
numpy.testing.assert_array_equal(and_func(arr1, arr2), numpy.array([False, True]))
numpy.testing.assert_array_equal(and_func_3(arr1, arr2, arr3), numpy.array([False, False]))
numpy.testing.assert_array_equal(or_func(arr1, arr2), numpy.array([True, True]))
numpy.testing.assert_array_equal(or_func_3(arr1, arr2, arr3), numpy.array([True, True]))
numpy.testing.assert_array_equal(not_func(arr2), numpy.array([True, False]))
def test_numpy_matmul():
if not numpy:
skip("numpy not installed.")
xmat = Matrix([[x, y], [z, 1+z]])
ymat = Matrix([[x**2], [Abs(x)]])
mat_func = lambdify((x, y, z), xmat*ymat, modules="numpy")
numpy.testing.assert_array_equal(mat_func(0.5, 3, 4), numpy.array([[1.625], [3.5]]))
numpy.testing.assert_array_equal(mat_func(-0.5, 3, 4), numpy.array([[1.375], [3.5]]))
# Multiple matrices chained together in multiplication
f = lambdify((x, y, z), xmat*xmat*xmat, modules="numpy")
numpy.testing.assert_array_equal(f(0.5, 3, 4), numpy.array([[72.125, 119.25],
[159, 251]]))
def test_numpy_numexpr():
if not numpy:
skip("numpy not installed.")
if not numexpr:
skip("numexpr not installed.")
a, b, c = numpy.random.randn(3, 128, 128)
# ensure that numpy and numexpr return same value for complicated expression
expr = sin(x) + cos(y) + tan(z)**2 + Abs(z-y)*acos(sin(y*z)) + \
Abs(y-z)*acosh(2+exp(y-x))- sqrt(x**2+I*y**2)
npfunc = lambdify((x, y, z), expr, modules='numpy')
nefunc = lambdify((x, y, z), expr, modules='numexpr')
assert numpy.allclose(npfunc(a, b, c), nefunc(a, b, c))
def test_numexpr_userfunctions():
if not numpy:
skip("numpy not installed.")
if not numexpr:
skip("numexpr not installed.")
a, b = numpy.random.randn(2, 10)
uf = type('uf', (Function, ),
{'eval' : classmethod(lambda x, y : y**2+1)})
func = lambdify(x, 1-uf(x), modules='numexpr')
assert numpy.allclose(func(a), -(a**2))
uf = implemented_function(Function('uf'), lambda x, y : 2*x*y+1)
func = lambdify((x, y), uf(x, y), modules='numexpr')
assert numpy.allclose(func(a, b), 2*a*b+1)
def test_tensorflow_basic_math():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(sin(x), Abs(1/(x+2)))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
a = tensorflow.constant(0, dtype=tensorflow.float32)
assert func(a).eval(session=s) == 0.5
def test_tensorflow_placeholders():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(sin(x), Abs(1/(x+2)))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
a = tensorflow.compat.v1.placeholder(dtype=tensorflow.float32)
assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5
def test_tensorflow_variables():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(sin(x), Abs(1/(x+2)))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
a = tensorflow.Variable(0, dtype=tensorflow.float32)
s.run(a.initializer)
assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5
def test_tensorflow_logical_operations():
if not tensorflow:
skip("tensorflow not installed.")
expr = Not(And(Or(x, y), y))
func = lambdify([x, y], expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(False, True).eval(session=s) == False
def test_tensorflow_piecewise():
if not tensorflow:
skip("tensorflow not installed.")
expr = Piecewise((0, Eq(x,0)), (-1, x < 0), (1, x > 0))
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(-1).eval(session=s) == -1
assert func(0).eval(session=s) == 0
assert func(1).eval(session=s) == 1
def test_tensorflow_multi_max():
if not tensorflow:
skip("tensorflow not installed.")
expr = Max(x, -x, x**2)
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(-2).eval(session=s) == 4
def test_tensorflow_multi_min():
if not tensorflow:
skip("tensorflow not installed.")
expr = Min(x, -x, x**2)
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(-2).eval(session=s) == -2
def test_tensorflow_relational():
if not tensorflow:
skip("tensorflow not installed.")
expr = x >= 0
func = lambdify(x, expr, modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
assert func(1).eval(session=s) == True
def test_tensorflow_complexes():
if not tensorflow:
skip("tensorflow not installed")
func1 = lambdify(x, re(x), modules="tensorflow")
func2 = lambdify(x, im(x), modules="tensorflow")
func3 = lambdify(x, Abs(x), modules="tensorflow")
func4 = lambdify(x, arg(x), modules="tensorflow")
with tensorflow.compat.v1.Session() as s:
# For versions before
# https://github.com/tensorflow/tensorflow/issues/30029
# resolved, using python numeric types may not work
a = tensorflow.constant(1+2j)
assert func1(a).eval(session=s) == 1
assert func2(a).eval(session=s) == 2
tensorflow_result = func3(a).eval(session=s)
sympy_result = Abs(1 + 2j).evalf()
assert abs(tensorflow_result-sympy_result) < 10**-6
tensorflow_result = func4(a).eval(session=s)
sympy_result = arg(1 + 2j).evalf()
assert abs(tensorflow_result-sympy_result) < 10**-6
def test_tensorflow_array_arg():
# Test for issue 14655 (tensorflow part)
if not tensorflow:
skip("tensorflow not installed.")
f = lambdify([[x, y]], x*x + y, 'tensorflow')
with tensorflow.compat.v1.Session() as s:
fcall = f(tensorflow.constant([2.0, 1.0]))
assert fcall.eval(session=s) == 5.0
#================== Test symbolic ==================================
def test_sym_single_arg():
f = lambdify(x, x * y)
assert f(z) == z * y
def test_sym_list_args():
f = lambdify([x, y], x + y + z)
assert f(1, 2) == 3 + z
def test_sym_integral():
f = Lambda(x, exp(-x**2))
l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy")
assert l(y) == Integral(exp(-y**2), (y, -oo, oo))
assert l(y).doit() == sqrt(pi)
def test_namespace_order():
# lambdify had a bug, such that module dictionaries or cached module
# dictionaries would pull earlier namespaces into themselves.
# Because the module dictionaries form the namespace of the
# generated lambda, this meant that the behavior of a previously
# generated lambda function could change as a result of later calls
# to lambdify.
n1 = {'f': lambda x: 'first f'}
n2 = {'f': lambda x: 'second f',
'g': lambda x: 'function g'}
f = sympy.Function('f')
g = sympy.Function('g')
if1 = lambdify(x, f(x), modules=(n1, "sympy"))
assert if1(1) == 'first f'
if2 = lambdify(x, g(x), modules=(n2, "sympy"))
# previously gave 'second f'
assert if1(1) == 'first f'
assert if2(1) == 'function g'
def test_namespace_type():
# lambdify had a bug where it would reject modules of type unicode
# on Python 2.
x = sympy.Symbol('x')
lambdify(x, x, modules='math')
def test_imps():
# Here we check if the default returned functions are anonymous - in
# the sense that we can have more than one function with the same name
f = implemented_function('f', lambda x: 2*x)
g = implemented_function('f', lambda x: math.sqrt(x))
l1 = lambdify(x, f(x))
l2 = lambdify(x, g(x))
assert str(f(x)) == str(g(x))
assert l1(3) == 6
assert l2(3) == math.sqrt(3)
# check that we can pass in a Function as input
func = sympy.Function('myfunc')
assert not hasattr(func, '_imp_')
my_f = implemented_function(func, lambda x: 2*x)
assert hasattr(my_f, '_imp_')
# Error for functions with same name and different implementation
f2 = implemented_function("f", lambda x: x + 101)
raises(ValueError, lambda: lambdify(x, f(f2(x))))
def test_imps_errors():
# Test errors that implemented functions can return, and still be able to
# form expressions.
# See: https://github.com/sympy/sympy/issues/10810
#
# XXX: Removed AttributeError here. This test was added due to issue 10810
# but that issue was about ValueError. It doesn't seem reasonable to
# "support" catching AttributeError in the same context...
for val, error_class in product((0, 0., 2, 2.0), (TypeError, ValueError)):
def myfunc(a):
if a == 0:
raise error_class
return 1
f = implemented_function('f', myfunc)
expr = f(val)
assert expr == f(val)
def test_imps_wrong_args():
raises(ValueError, lambda: implemented_function(sin, lambda x: x))
def test_lambdify_imps():
# Test lambdify with implemented functions
# first test basic (sympy) lambdify
f = sympy.cos
assert lambdify(x, f(x))(0) == 1
assert lambdify(x, 1 + f(x))(0) == 2
assert lambdify((x, y), y + f(x))(0, 1) == 2
# make an implemented function and test
f = implemented_function("f", lambda x: x + 100)
assert lambdify(x, f(x))(0) == 100
assert lambdify(x, 1 + f(x))(0) == 101
assert lambdify((x, y), y + f(x))(0, 1) == 101
# Can also handle tuples, lists, dicts as expressions
lam = lambdify(x, (f(x), x))
assert lam(3) == (103, 3)
lam = lambdify(x, [f(x), x])
assert lam(3) == [103, 3]
lam = lambdify(x, [f(x), (f(x), x)])
assert lam(3) == [103, (103, 3)]
lam = lambdify(x, {f(x): x})
assert lam(3) == {103: 3}
lam = lambdify(x, {f(x): x})
assert lam(3) == {103: 3}
lam = lambdify(x, {x: f(x)})
assert lam(3) == {3: 103}
# Check that imp preferred to other namespaces by default
d = {'f': lambda x: x + 99}
lam = lambdify(x, f(x), d)
assert lam(3) == 103
# Unless flag passed
lam = lambdify(x, f(x), d, use_imps=False)
assert lam(3) == 102
def test_dummification():
t = symbols('t')
F = Function('F')
G = Function('G')
#"\alpha" is not a valid python variable name
#lambdify should sub in a dummy for it, and return
#without a syntax error
alpha = symbols(r'\alpha')
some_expr = 2 * F(t)**2 / G(t)
lam = lambdify((F(t), G(t)), some_expr)
assert lam(3, 9) == 2
lam = lambdify(sin(t), 2 * sin(t)**2)
assert lam(F(t)) == 2 * F(t)**2
#Test that \alpha was properly dummified
lam = lambdify((alpha, t), 2*alpha + t)
assert lam(2, 1) == 5
raises(SyntaxError, lambda: lambdify(F(t) * G(t), F(t) * G(t) + 5))
raises(SyntaxError, lambda: lambdify(2 * F(t), 2 * F(t) + 5))
raises(SyntaxError, lambda: lambdify(2 * F(t), 4 * F(t) + 5))
def test_curly_matrix_symbol():
# Issue #15009
curlyv = sympy.MatrixSymbol("{v}", 2, 1)
lam = lambdify(curlyv, curlyv)
assert lam(1)==1
lam = lambdify(curlyv, curlyv, dummify=True)
assert lam(1)==1
def test_python_keywords():
# Test for issue 7452. The automatic dummification should ensure use of
# Python reserved keywords as symbol names will create valid lambda
# functions. This is an additional regression test.
python_if = symbols('if')
expr = python_if / 2
f = lambdify(python_if, expr)
assert f(4.0) == 2.0
def test_lambdify_docstring():
func = lambdify((w, x, y, z), w + x + y + z)
ref = (
"Created with lambdify. Signature:\n\n"
"func(w, x, y, z)\n\n"
"Expression:\n\n"
"w + x + y + z"
).splitlines()
assert func.__doc__.splitlines()[:len(ref)] == ref
syms = symbols('a1:26')
func = lambdify(syms, sum(syms))
ref = (
"Created with lambdify. Signature:\n\n"
"func(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15,\n"
" a16, a17, a18, a19, a20, a21, a22, a23, a24, a25)\n\n"
"Expression:\n\n"
"a1 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a2 + a20 +..."
).splitlines()
assert func.__doc__.splitlines()[:len(ref)] == ref
#================== Test special printers ==========================
def test_special_printers():
from sympy.polys.numberfields import IntervalPrinter
def intervalrepr(expr):
return IntervalPrinter().doprint(expr)
expr = sqrt(sqrt(2) + sqrt(3)) + S.Half
func0 = lambdify((), expr, modules="mpmath", printer=intervalrepr)
func1 = lambdify((), expr, modules="mpmath", printer=IntervalPrinter)
func2 = lambdify((), expr, modules="mpmath", printer=IntervalPrinter())
mpi = type(mpmath.mpi(1, 2))
assert isinstance(func0(), mpi)
assert isinstance(func1(), mpi)
assert isinstance(func2(), mpi)
# To check Is lambdify loggamma works for mpmath or not
exp1 = lambdify(x, loggamma(x), 'mpmath')(5)
exp2 = lambdify(x, loggamma(x), 'mpmath')(1.8)
exp3 = lambdify(x, loggamma(x), 'mpmath')(15)
exp_ls = [exp1, exp2, exp3]
sol1 = mpmath.loggamma(5)
sol2 = mpmath.loggamma(1.8)
sol3 = mpmath.loggamma(15)
sol_ls = [sol1, sol2, sol3]
assert exp_ls == sol_ls
def test_true_false():
# We want exact is comparison here, not just ==
assert lambdify([], true)() is True
assert lambdify([], false)() is False
def test_issue_2790():
assert lambdify((x, (y, z)), x + y)(1, (2, 4)) == 3
assert lambdify((x, (y, (w, z))), w + x + y + z)(1, (2, (3, 4))) == 10
assert lambdify(x, x + 1, dummify=False)(1) == 2
def test_issue_12092():
f = implemented_function('f', lambda x: x**2)
assert f(f(2)).evalf() == Float(16)
def test_issue_14911():
class Variable(sympy.Symbol):
def _sympystr(self, printer):
return printer.doprint(self.name)
_lambdacode = _sympystr
_numpycode = _sympystr
x = Variable('x')
y = 2 * x
code = LambdaPrinter().doprint(y)
assert code.replace(' ', '') == '2*x'
def test_ITE():
assert lambdify((x, y, z), ITE(x, y, z))(True, 5, 3) == 5
assert lambdify((x, y, z), ITE(x, y, z))(False, 5, 3) == 3
def test_Min_Max():
# see gh-10375
assert lambdify((x, y, z), Min(x, y, z))(1, 2, 3) == 1
assert lambdify((x, y, z), Max(x, y, z))(1, 2, 3) == 3
def test_Indexed():
# Issue #10934
if not numpy:
skip("numpy not installed")
a = IndexedBase('a')
i, j = symbols('i j')
b = numpy.array([[1, 2], [3, 4]])
assert lambdify(a, Sum(a[x, y], (x, 0, 1), (y, 0, 1)))(b) == 10
def test_issue_12173():
#test for issue 12173
expr1 = lambdify((x, y), uppergamma(x, y),"mpmath")(1, 2)
expr2 = lambdify((x, y), lowergamma(x, y),"mpmath")(1, 2)
assert expr1 == uppergamma(1, 2).evalf()
assert expr2 == lowergamma(1, 2).evalf()
def test_issue_13642():
if not numpy:
skip("numpy not installed")
f = lambdify(x, sinc(x))
assert Abs(f(1) - sinc(1)).n() < 1e-15
def test_sinc_mpmath():
f = lambdify(x, sinc(x), "mpmath")
assert Abs(f(1) - sinc(1)).n() < 1e-15
def test_lambdify_dummy_arg():
d1 = Dummy()
f1 = lambdify(d1, d1 + 1, dummify=False)
assert f1(2) == 3
f1b = lambdify(d1, d1 + 1)
assert f1b(2) == 3
d2 = Dummy('x')
f2 = lambdify(d2, d2 + 1)
assert f2(2) == 3
f3 = lambdify([[d2]], d2 + 1)
assert f3([2]) == 3
def test_lambdify_mixed_symbol_dummy_args():
d = Dummy()
# Contrived example of name clash
dsym = symbols(str(d))
f = lambdify([d, dsym], d - dsym)
assert f(4, 1) == 3
def test_numpy_array_arg():
# Test for issue 14655 (numpy part)
if not numpy:
skip("numpy not installed")
f = lambdify([[x, y]], x*x + y, 'numpy')
assert f(numpy.array([2.0, 1.0])) == 5
def test_scipy_fns():
if not scipy:
skip("scipy not installed")
single_arg_sympy_fns = [erf, erfc, factorial, gamma, loggamma, digamma]
single_arg_scipy_fns = [scipy.special.erf, scipy.special.erfc,
scipy.special.factorial, scipy.special.gamma, scipy.special.gammaln,
scipy.special.psi]
numpy.random.seed(0)
for (sympy_fn, scipy_fn) in zip(single_arg_sympy_fns, single_arg_scipy_fns):
f = lambdify(x, sympy_fn(x), modules="scipy")
for i in range(20):
tv = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5)
# SciPy thinks that factorial(z) is 0 when re(z) < 0 and
# does not support complex numbers.
# SymPy does not think so.
if sympy_fn == factorial:
tv = numpy.abs(tv)
# SciPy supports gammaln for real arguments only,
# and there is also a branch cut along the negative real axis
if sympy_fn == loggamma:
tv = numpy.abs(tv)
# SymPy's digamma evaluates as polygamma(0, z)
# which SciPy supports for real arguments only
if sympy_fn == digamma:
tv = numpy.real(tv)
sympy_result = sympy_fn(tv).evalf()
assert abs(f(tv) - sympy_result) < 1e-13*(1 + abs(sympy_result))
assert abs(f(tv) - scipy_fn(tv)) < 1e-13*(1 + abs(sympy_result))
double_arg_sympy_fns = [RisingFactorial, besselj, bessely, besseli,
besselk]
double_arg_scipy_fns = [scipy.special.poch, scipy.special.jv,
scipy.special.yv, scipy.special.iv, scipy.special.kv]
for (sympy_fn, scipy_fn) in zip(double_arg_sympy_fns, double_arg_scipy_fns):
f = lambdify((x, y), sympy_fn(x, y), modules="scipy")
for i in range(20):
# SciPy supports only real orders of Bessel functions
tv1 = numpy.random.uniform(-10, 10)
tv2 = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5)
# SciPy supports poch for real arguments only
if sympy_fn == RisingFactorial:
tv2 = numpy.real(tv2)
sympy_result = sympy_fn(tv1, tv2).evalf()
assert abs(f(tv1, tv2) - sympy_result) < 1e-13*(1 + abs(sympy_result))
assert abs(f(tv1, tv2) - scipy_fn(tv1, tv2)) < 1e-13*(1 + abs(sympy_result))
def test_scipy_polys():
if not scipy:
skip("scipy not installed")
numpy.random.seed(0)
params = symbols('n k a b')
# list polynomials with the number of parameters
polys = [
(chebyshevt, 1),
(chebyshevu, 1),
(legendre, 1),
(hermite, 1),
(laguerre, 1),
(gegenbauer, 2),
(assoc_legendre, 2),
(assoc_laguerre, 2),
(jacobi, 3)
]
msg = \
"The random test of the function {func} with the arguments " \
"{args} had failed because the SymPy result {sympy_result} " \
"and SciPy result {scipy_result} had failed to converge " \
"within the tolerance {tol} " \
"(Actual absolute difference : {diff})"
for sympy_fn, num_params in polys:
args = params[:num_params] + (x,)
f = lambdify(args, sympy_fn(*args))
for _ in range(10):
tn = numpy.random.randint(3, 10)
tparams = tuple(numpy.random.uniform(0, 5, size=num_params-1))
tv = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5)
# SciPy supports hermite for real arguments only
if sympy_fn == hermite:
tv = numpy.real(tv)
# assoc_legendre needs x in (-1, 1) and integer param at most n
if sympy_fn == assoc_legendre:
tv = numpy.random.uniform(-1, 1)
tparams = tuple(numpy.random.randint(1, tn, size=1))
vals = (tn,) + tparams + (tv,)
scipy_result = f(*vals)
sympy_result = sympy_fn(*vals).evalf()
atol = 1e-9*(1 + abs(sympy_result))
diff = abs(scipy_result - sympy_result)
try:
assert diff < atol
except TypeError:
raise AssertionError(
msg.format(
func=repr(sympy_fn),
args=repr(vals),
sympy_result=repr(sympy_result),
scipy_result=repr(scipy_result),
diff=diff,
tol=atol)
)
def test_lambdify_inspect():
f = lambdify(x, x**2)
# Test that inspect.getsource works but don't hard-code implementation
# details
assert 'x**2' in inspect.getsource(f)
def test_issue_14941():
x, y = Dummy(), Dummy()
# test dict
f1 = lambdify([x, y], {x: 3, y: 3}, 'sympy')
assert f1(2, 3) == {2: 3, 3: 3}
# test tuple
f2 = lambdify([x, y], (y, x), 'sympy')
assert f2(2, 3) == (3, 2)
# test list
f3 = lambdify([x, y], [y, x], 'sympy')
assert f3(2, 3) == [3, 2]
def test_lambdify_Derivative_arg_issue_16468():
f = Function('f')(x)
fx = f.diff()
assert lambdify((f, fx), f + fx)(10, 5) == 15
assert eval(lambdastr((f, fx), f/fx))(10, 5) == 2
raises(SyntaxError, lambda:
eval(lambdastr((f, fx), f/fx, dummify=False)))
assert eval(lambdastr((f, fx), f/fx, dummify=True))(10, 5) == 2
assert eval(lambdastr((fx, f), f/fx, dummify=True))(S(10), 5) == S.Half
assert lambdify(fx, 1 + fx)(41) == 42
assert eval(lambdastr(fx, 1 + fx, dummify=True))(41) == 42
def test_imag_real():
f_re = lambdify([z], sympy.re(z))
val = 3+2j
assert f_re(val) == val.real
f_im = lambdify([z], sympy.im(z)) # see #15400
assert f_im(val) == val.imag
def test_MatrixSymbol_issue_15578():
if not numpy:
skip("numpy not installed")
A = MatrixSymbol('A', 2, 2)
A0 = numpy.array([[1, 2], [3, 4]])
f = lambdify(A, A**(-1))
assert numpy.allclose(f(A0), numpy.array([[-2., 1.], [1.5, -0.5]]))
g = lambdify(A, A**3)
assert numpy.allclose(g(A0), numpy.array([[37, 54], [81, 118]]))
def test_issue_15654():
if not scipy:
skip("scipy not installed")
from sympy.abc import n, l, r, Z
from sympy.physics import hydrogen
nv, lv, rv, Zv = 1, 0, 3, 1
sympy_value = hydrogen.R_nl(nv, lv, rv, Zv).evalf()
f = lambdify((n, l, r, Z), hydrogen.R_nl(n, l, r, Z))
scipy_value = f(nv, lv, rv, Zv)
assert abs(sympy_value - scipy_value) < 1e-15
def test_issue_15827():
if not numpy:
skip("numpy not installed")
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 2, 3)
C = MatrixSymbol("C", 3, 4)
D = MatrixSymbol("D", 4, 5)
k=symbols("k")
f = lambdify(A, (2*k)*A)
g = lambdify(A, (2+k)*A)
h = lambdify(A, 2*A)
i = lambdify((B, C, D), 2*B*C*D)
assert numpy.array_equal(f(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \
numpy.array([[2*k, 4*k, 6*k], [2*k, 4*k, 6*k], [2*k, 4*k, 6*k]], dtype=object))
assert numpy.array_equal(g(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \
numpy.array([[k + 2, 2*k + 4, 3*k + 6], [k + 2, 2*k + 4, 3*k + 6], \
[k + 2, 2*k + 4, 3*k + 6]], dtype=object))
assert numpy.array_equal(h(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \
numpy.array([[2, 4, 6], [2, 4, 6], [2, 4, 6]]))
assert numpy.array_equal(i(numpy.array([[1, 2, 3], [1, 2, 3]]), numpy.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]), \
numpy.array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])), numpy.array([[ 120, 240, 360, 480, 600], \
[ 120, 240, 360, 480, 600]]))
def test_issue_16930():
if not scipy:
skip("scipy not installed")
x = symbols("x")
f = lambda x: S.GoldenRatio * x**2
f_ = lambdify(x, f(x), modules='scipy')
assert f_(1) == scipy.constants.golden_ratio
def test_issue_17898():
if not scipy:
skip("scipy not installed")
x = symbols("x")
f_ = lambdify([x], sympy.LambertW(x,-1), modules='scipy')
assert f_(0.1) == mpmath.lambertw(0.1, -1)
def test_issue_13167_21411():
if not numpy:
skip("numpy not installed")
f1 = lambdify(x, sympy.Heaviside(x))
f2 = lambdify(x, sympy.Heaviside(x, 1))
res1 = f1([-1, 0, 1])
res2 = f2([-1, 0, 1])
assert Abs(res1[0]).n() < 1e-15 # First functionality: only one argument passed
assert Abs(res1[1] - 1/2).n() < 1e-15
assert Abs(res1[2] - 1).n() < 1e-15
assert Abs(res2[0]).n() < 1e-15 # Second functionality: two arguments passed
assert Abs(res2[1] - 1).n() < 1e-15
assert Abs(res2[2] - 1).n() < 1e-15
def test_single_e():
f = lambdify(x, E)
assert f(23) == exp(1.0)
def test_issue_16536():
if not scipy:
skip("scipy not installed")
a = symbols('a')
f1 = lowergamma(a, x)
F = lambdify((a, x), f1, modules='scipy')
assert abs(lowergamma(1, 3) - F(1, 3)) <= 1e-10
f2 = uppergamma(a, x)
F = lambdify((a, x), f2, modules='scipy')
assert abs(uppergamma(1, 3) - F(1, 3)) <= 1e-10
def test_fresnel_integrals_scipy():
if not scipy:
skip("scipy not installed")
f1 = fresnelc(x)
f2 = fresnels(x)
F1 = lambdify(x, f1, modules='scipy')
F2 = lambdify(x, f2, modules='scipy')
assert abs(fresnelc(1.3) - F1(1.3)) <= 1e-10
assert abs(fresnels(1.3) - F2(1.3)) <= 1e-10
def test_beta_scipy():
if not scipy:
skip("scipy not installed")
f = beta(x, y)
F = lambdify((x, y), f, modules='scipy')
assert abs(beta(1.3, 2.3) - F(1.3, 2.3)) <= 1e-10
def test_beta_math():
f = beta(x, y)
F = lambdify((x, y), f, modules='math')
assert abs(beta(1.3, 2.3) - F(1.3, 2.3)) <= 1e-10
def test_betainc_scipy():
if not scipy:
skip("scipy not installed")
f = betainc(w, x, y, z)
F = lambdify((w, x, y, z), f, modules='scipy')
assert abs(betainc(1.4, 3.1, 0.1, 0.5) - F(1.4, 3.1, 0.1, 0.5)) <= 1e-10
def test_betainc_regularized_scipy():
if not scipy:
skip("scipy not installed")
f = betainc_regularized(w, x, y, z)
F = lambdify((w, x, y, z), f, modules='scipy')
assert abs(betainc_regularized(0.2, 3.5, 0.1, 1) - F(0.2, 3.5, 0.1, 1)) <= 1e-10
def test_numpy_special_math():
if not numpy:
skip("numpy not installed")
funcs = [expm1, log1p, exp2, log2, log10, hypot, logaddexp, logaddexp2]
for func in funcs:
if 2 in func.nargs:
expr = func(x, y)
args = (x, y)
num_args = (0.3, 0.4)
elif 1 in func.nargs:
expr = func(x)
args = (x,)
num_args = (0.3,)
else:
raise NotImplementedError("Need to handle other than unary & binary functions in test")
f = lambdify(args, expr)
result = f(*num_args)
reference = expr.subs(dict(zip(args, num_args))).evalf()
assert numpy.allclose(result, float(reference))
lae2 = lambdify((x, y), logaddexp2(log2(x), log2(y)))
assert abs(2.0**lae2(1e-50, 2.5e-50) - 3.5e-50) < 1e-62 # from NumPy's docstring
def test_scipy_special_math():
if not scipy:
skip("scipy not installed")
cm1 = lambdify((x,), cosm1(x), modules='scipy')
assert abs(cm1(1e-20) + 5e-41) < 1e-200
def test_cupy_array_arg():
if not cupy:
skip("CuPy not installed")
f = lambdify([[x, y]], x*x + y, 'cupy')
result = f(cupy.array([2.0, 1.0]))
assert result == 5
assert "cupy" in str(type(result))
def test_cupy_array_arg_using_numpy():
# numpy functions can be run on cupy arrays
# unclear if we can "officialy" support this,
# depends on numpy __array_function__ support
if not cupy:
skip("CuPy not installed")
f = lambdify([[x, y]], x*x + y, 'numpy')
result = f(cupy.array([2.0, 1.0]))
assert result == 5
assert "cupy" in str(type(result))
def test_cupy_dotproduct():
if not cupy:
skip("CuPy not installed")
A = Matrix([x, y, z])
f1 = lambdify([x, y, z], DotProduct(A, A), modules='cupy')
f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='cupy')
f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='cupy')
f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='cupy')
assert f1(1, 2, 3) == \
f2(1, 2, 3) == \
f3(1, 2, 3) == \
f4(1, 2, 3) == \
cupy.array([14])
|
6d056d75b3d4bfa643e80318c74eb0384665ddaaa60085270724d044cb1f9c11 | import itertools
from sympy.core import S
from sympy.core.containers import Tuple
from sympy.core.function import _coeff_isneg
from sympy.core.mul import Mul
from sympy.core.numbers import Number, Rational
from sympy.core.power import Pow
from sympy.core.symbol import Symbol
from sympy.core.sympify import SympifyError
from sympy.printing.conventions import requires_partial
from sympy.printing.precedence import PRECEDENCE, precedence, precedence_traditional
from sympy.printing.printer import Printer, print_function
from sympy.printing.str import sstr
from sympy.utilities import default_sort_key
from sympy.utilities.iterables import has_variety
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.printing.pretty.pretty_symbology import hobj, vobj, xobj, \
xsym, pretty_symbol, pretty_atom, pretty_use_unicode, greek_unicode, U, \
pretty_try_use_unicode, annotated
# rename for usage from outside
pprint_use_unicode = pretty_use_unicode
pprint_try_use_unicode = pretty_try_use_unicode
class PrettyPrinter(Printer):
"""Printer, which converts an expression into 2D ASCII-art figure."""
printmethod = "_pretty"
_default_settings = {
"order": None,
"full_prec": "auto",
"use_unicode": None,
"wrap_line": True,
"num_columns": None,
"use_unicode_sqrt_char": True,
"root_notation": True,
"mat_symbol_style": "plain",
"imaginary_unit": "i",
"perm_cyclic": True
}
def __init__(self, settings=None):
Printer.__init__(self, settings)
if not isinstance(self._settings['imaginary_unit'], str):
raise TypeError("'imaginary_unit' must a string, not {}".format(self._settings['imaginary_unit']))
elif self._settings['imaginary_unit'] not in ["i", "j"]:
raise ValueError("'imaginary_unit' must be either 'i' or 'j', not '{}'".format(self._settings['imaginary_unit']))
def emptyPrinter(self, expr):
return prettyForm(str(expr))
@property
def _use_unicode(self):
if self._settings['use_unicode']:
return True
else:
return pretty_use_unicode()
def doprint(self, expr):
return self._print(expr).render(**self._settings)
# empty op so _print(stringPict) returns the same
def _print_stringPict(self, e):
return e
def _print_basestring(self, e):
return prettyForm(e)
def _print_atan2(self, e):
pform = prettyForm(*self._print_seq(e.args).parens())
pform = prettyForm(*pform.left('atan2'))
return pform
def _print_Symbol(self, e, bold_name=False):
symb = pretty_symbol(e.name, bold_name)
return prettyForm(symb)
_print_RandomSymbol = _print_Symbol
def _print_MatrixSymbol(self, e):
return self._print_Symbol(e, self._settings['mat_symbol_style'] == "bold")
def _print_Float(self, e):
# we will use StrPrinter's Float printer, but we need to handle the
# full_prec ourselves, according to the self._print_level
full_prec = self._settings["full_prec"]
if full_prec == "auto":
full_prec = self._print_level == 1
return prettyForm(sstr(e, full_prec=full_prec))
def _print_Cross(self, e):
vec1 = e._expr1
vec2 = e._expr2
pform = self._print(vec2)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN'))))
pform = prettyForm(*pform.left(')'))
pform = prettyForm(*pform.left(self._print(vec1)))
pform = prettyForm(*pform.left('('))
return pform
def _print_Curl(self, e):
vec = e._expr
pform = self._print(vec)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN'))))
pform = prettyForm(*pform.left(self._print(U('NABLA'))))
return pform
def _print_Divergence(self, e):
vec = e._expr
pform = self._print(vec)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR'))))
pform = prettyForm(*pform.left(self._print(U('NABLA'))))
return pform
def _print_Dot(self, e):
vec1 = e._expr1
vec2 = e._expr2
pform = self._print(vec2)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR'))))
pform = prettyForm(*pform.left(')'))
pform = prettyForm(*pform.left(self._print(vec1)))
pform = prettyForm(*pform.left('('))
return pform
def _print_Gradient(self, e):
func = e._expr
pform = self._print(func)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('NABLA'))))
return pform
def _print_Laplacian(self, e):
func = e._expr
pform = self._print(func)
pform = prettyForm(*pform.left('('))
pform = prettyForm(*pform.right(')'))
pform = prettyForm(*pform.left(self._print(U('INCREMENT'))))
return pform
def _print_Atom(self, e):
try:
# print atoms like Exp1 or Pi
return prettyForm(pretty_atom(e.__class__.__name__, printer=self))
except KeyError:
return self.emptyPrinter(e)
# Infinity inherits from Number, so we have to override _print_XXX order
_print_Infinity = _print_Atom
_print_NegativeInfinity = _print_Atom
_print_EmptySet = _print_Atom
_print_Naturals = _print_Atom
_print_Naturals0 = _print_Atom
_print_Integers = _print_Atom
_print_Rationals = _print_Atom
_print_Complexes = _print_Atom
_print_EmptySequence = _print_Atom
def _print_Reals(self, e):
if self._use_unicode:
return self._print_Atom(e)
else:
inf_list = ['-oo', 'oo']
return self._print_seq(inf_list, '(', ')')
def _print_subfactorial(self, e):
x = e.args[0]
pform = self._print(x)
# Add parentheses if needed
if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol):
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left('!'))
return pform
def _print_factorial(self, e):
x = e.args[0]
pform = self._print(x)
# Add parentheses if needed
if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol):
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.right('!'))
return pform
def _print_factorial2(self, e):
x = e.args[0]
pform = self._print(x)
# Add parentheses if needed
if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol):
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.right('!!'))
return pform
def _print_binomial(self, e):
n, k = e.args
n_pform = self._print(n)
k_pform = self._print(k)
bar = ' '*max(n_pform.width(), k_pform.width())
pform = prettyForm(*k_pform.above(bar))
pform = prettyForm(*pform.above(n_pform))
pform = prettyForm(*pform.parens('(', ')'))
pform.baseline = (pform.baseline + 1)//2
return pform
def _print_Relational(self, e):
op = prettyForm(' ' + xsym(e.rel_op) + ' ')
l = self._print(e.lhs)
r = self._print(e.rhs)
pform = prettyForm(*stringPict.next(l, op, r))
return pform
def _print_Not(self, e):
from sympy import Equivalent, Implies
if self._use_unicode:
arg = e.args[0]
pform = self._print(arg)
if isinstance(arg, Equivalent):
return self._print_Equivalent(arg, altchar="\N{LEFT RIGHT DOUBLE ARROW WITH STROKE}")
if isinstance(arg, Implies):
return self._print_Implies(arg, altchar="\N{RIGHTWARDS ARROW WITH STROKE}")
if arg.is_Boolean and not arg.is_Not:
pform = prettyForm(*pform.parens())
return prettyForm(*pform.left("\N{NOT SIGN}"))
else:
return self._print_Function(e)
def __print_Boolean(self, e, char, sort=True):
args = e.args
if sort:
args = sorted(e.args, key=default_sort_key)
arg = args[0]
pform = self._print(arg)
if arg.is_Boolean and not arg.is_Not:
pform = prettyForm(*pform.parens())
for arg in args[1:]:
pform_arg = self._print(arg)
if arg.is_Boolean and not arg.is_Not:
pform_arg = prettyForm(*pform_arg.parens())
pform = prettyForm(*pform.right(' %s ' % char))
pform = prettyForm(*pform.right(pform_arg))
return pform
def _print_And(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{LOGICAL AND}")
else:
return self._print_Function(e, sort=True)
def _print_Or(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{LOGICAL OR}")
else:
return self._print_Function(e, sort=True)
def _print_Xor(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{XOR}")
else:
return self._print_Function(e, sort=True)
def _print_Nand(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{NAND}")
else:
return self._print_Function(e, sort=True)
def _print_Nor(self, e):
if self._use_unicode:
return self.__print_Boolean(e, "\N{NOR}")
else:
return self._print_Function(e, sort=True)
def _print_Implies(self, e, altchar=None):
if self._use_unicode:
return self.__print_Boolean(e, altchar or "\N{RIGHTWARDS ARROW}", sort=False)
else:
return self._print_Function(e)
def _print_Equivalent(self, e, altchar=None):
if self._use_unicode:
return self.__print_Boolean(e, altchar or "\N{LEFT RIGHT DOUBLE ARROW}")
else:
return self._print_Function(e, sort=True)
def _print_conjugate(self, e):
pform = self._print(e.args[0])
return prettyForm( *pform.above( hobj('_', pform.width())) )
def _print_Abs(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens('|', '|'))
return pform
_print_Determinant = _print_Abs
def _print_floor(self, e):
if self._use_unicode:
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens('lfloor', 'rfloor'))
return pform
else:
return self._print_Function(e)
def _print_ceiling(self, e):
if self._use_unicode:
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens('lceil', 'rceil'))
return pform
else:
return self._print_Function(e)
def _print_Derivative(self, deriv):
if requires_partial(deriv.expr) and self._use_unicode:
deriv_symbol = U('PARTIAL DIFFERENTIAL')
else:
deriv_symbol = r'd'
x = None
count_total_deriv = 0
for sym, num in reversed(deriv.variable_count):
s = self._print(sym)
ds = prettyForm(*s.left(deriv_symbol))
count_total_deriv += num
if (not num.is_Integer) or (num > 1):
ds = ds**prettyForm(str(num))
if x is None:
x = ds
else:
x = prettyForm(*x.right(' '))
x = prettyForm(*x.right(ds))
f = prettyForm(
binding=prettyForm.FUNC, *self._print(deriv.expr).parens())
pform = prettyForm(deriv_symbol)
if (count_total_deriv > 1) != False:
pform = pform**prettyForm(str(count_total_deriv))
pform = prettyForm(*pform.below(stringPict.LINE, x))
pform.baseline = pform.baseline + 1
pform = prettyForm(*stringPict.next(pform, f))
pform.binding = prettyForm.MUL
return pform
def _print_Cycle(self, dc):
from sympy.combinatorics.permutations import Permutation, Cycle
# for Empty Cycle
if dc == Cycle():
cyc = stringPict('')
return prettyForm(*cyc.parens())
dc_list = Permutation(dc.list()).cyclic_form
# for Identity Cycle
if dc_list == []:
cyc = self._print(dc.size - 1)
return prettyForm(*cyc.parens())
cyc = stringPict('')
for i in dc_list:
l = self._print(str(tuple(i)).replace(',', ''))
cyc = prettyForm(*cyc.right(l))
return cyc
def _print_Permutation(self, expr):
from sympy.combinatorics.permutations import Permutation, Cycle
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
SymPyDeprecationWarning(
feature="Permutation.print_cyclic = {}".format(perm_cyclic),
useinstead="init_printing(perm_cyclic={})"
.format(perm_cyclic),
issue=15201,
deprecated_since_version="1.6").warn()
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
return self._print_Cycle(Cycle(expr))
lower = expr.array_form
upper = list(range(len(lower)))
result = stringPict('')
first = True
for u, l in zip(upper, lower):
s1 = self._print(u)
s2 = self._print(l)
col = prettyForm(*s1.below(s2))
if first:
first = False
else:
col = prettyForm(*col.left(" "))
result = prettyForm(*result.right(col))
return prettyForm(*result.parens())
def _print_Integral(self, integral):
f = integral.function
# Add parentheses if arg involves addition of terms and
# create a pretty form for the argument
prettyF = self._print(f)
# XXX generalize parens
if f.is_Add:
prettyF = prettyForm(*prettyF.parens())
# dx dy dz ...
arg = prettyF
for x in integral.limits:
prettyArg = self._print(x[0])
# XXX qparens (parens if needs-parens)
if prettyArg.width() > 1:
prettyArg = prettyForm(*prettyArg.parens())
arg = prettyForm(*arg.right(' d', prettyArg))
# \int \int \int ...
firstterm = True
s = None
for lim in integral.limits:
x = lim[0]
# Create bar based on the height of the argument
h = arg.height()
H = h + 2
# XXX hack!
ascii_mode = not self._use_unicode
if ascii_mode:
H += 2
vint = vobj('int', H)
# Construct the pretty form with the integral sign and the argument
pform = prettyForm(vint)
pform.baseline = arg.baseline + (
H - h)//2 # covering the whole argument
if len(lim) > 1:
# Create pretty forms for endpoints, if definite integral.
# Do not print empty endpoints.
if len(lim) == 2:
prettyA = prettyForm("")
prettyB = self._print(lim[1])
if len(lim) == 3:
prettyA = self._print(lim[1])
prettyB = self._print(lim[2])
if ascii_mode: # XXX hack
# Add spacing so that endpoint can more easily be
# identified with the correct integral sign
spc = max(1, 3 - prettyB.width())
prettyB = prettyForm(*prettyB.left(' ' * spc))
spc = max(1, 4 - prettyA.width())
prettyA = prettyForm(*prettyA.right(' ' * spc))
pform = prettyForm(*pform.above(prettyB))
pform = prettyForm(*pform.below(prettyA))
if not ascii_mode: # XXX hack
pform = prettyForm(*pform.right(' '))
if firstterm:
s = pform # first term
firstterm = False
else:
s = prettyForm(*s.left(pform))
pform = prettyForm(*arg.left(s))
pform.binding = prettyForm.MUL
return pform
def _print_Product(self, expr):
func = expr.term
pretty_func = self._print(func)
horizontal_chr = xobj('_', 1)
corner_chr = xobj('_', 1)
vertical_chr = xobj('|', 1)
if self._use_unicode:
# use unicode corners
horizontal_chr = xobj('-', 1)
corner_chr = '\N{BOX DRAWINGS LIGHT DOWN AND HORIZONTAL}'
func_height = pretty_func.height()
first = True
max_upper = 0
sign_height = 0
for lim in expr.limits:
pretty_lower, pretty_upper = self.__print_SumProduct_Limits(lim)
width = (func_height + 2) * 5 // 3 - 2
sign_lines = [horizontal_chr + corner_chr + (horizontal_chr * (width-2)) + corner_chr + horizontal_chr]
for _ in range(func_height + 1):
sign_lines.append(' ' + vertical_chr + (' ' * (width-2)) + vertical_chr + ' ')
pretty_sign = stringPict('')
pretty_sign = prettyForm(*pretty_sign.stack(*sign_lines))
max_upper = max(max_upper, pretty_upper.height())
if first:
sign_height = pretty_sign.height()
pretty_sign = prettyForm(*pretty_sign.above(pretty_upper))
pretty_sign = prettyForm(*pretty_sign.below(pretty_lower))
if first:
pretty_func.baseline = 0
first = False
height = pretty_sign.height()
padding = stringPict('')
padding = prettyForm(*padding.stack(*[' ']*(height - 1)))
pretty_sign = prettyForm(*pretty_sign.right(padding))
pretty_func = prettyForm(*pretty_sign.right(pretty_func))
pretty_func.baseline = max_upper + sign_height//2
pretty_func.binding = prettyForm.MUL
return pretty_func
def __print_SumProduct_Limits(self, lim):
def print_start(lhs, rhs):
op = prettyForm(' ' + xsym("==") + ' ')
l = self._print(lhs)
r = self._print(rhs)
pform = prettyForm(*stringPict.next(l, op, r))
return pform
prettyUpper = self._print(lim[2])
prettyLower = print_start(lim[0], lim[1])
return prettyLower, prettyUpper
def _print_Sum(self, expr):
ascii_mode = not self._use_unicode
def asum(hrequired, lower, upper, use_ascii):
def adjust(s, wid=None, how='<^>'):
if not wid or len(s) > wid:
return s
need = wid - len(s)
if how == '<^>' or how == "<" or how not in list('<^>'):
return s + ' '*need
half = need//2
lead = ' '*half
if how == ">":
return " "*need + s
return lead + s + ' '*(need - len(lead))
h = max(hrequired, 2)
d = h//2
w = d + 1
more = hrequired % 2
lines = []
if use_ascii:
lines.append("_"*(w) + ' ')
lines.append(r"\%s`" % (' '*(w - 1)))
for i in range(1, d):
lines.append('%s\\%s' % (' '*i, ' '*(w - i)))
if more:
lines.append('%s)%s' % (' '*(d), ' '*(w - d)))
for i in reversed(range(1, d)):
lines.append('%s/%s' % (' '*i, ' '*(w - i)))
lines.append("/" + "_"*(w - 1) + ',')
return d, h + more, lines, more
else:
w = w + more
d = d + more
vsum = vobj('sum', 4)
lines.append("_"*(w))
for i in range(0, d):
lines.append('%s%s%s' % (' '*i, vsum[2], ' '*(w - i - 1)))
for i in reversed(range(0, d)):
lines.append('%s%s%s' % (' '*i, vsum[4], ' '*(w - i - 1)))
lines.append(vsum[8]*(w))
return d, h + 2*more, lines, more
f = expr.function
prettyF = self._print(f)
if f.is_Add: # add parens
prettyF = prettyForm(*prettyF.parens())
H = prettyF.height() + 2
# \sum \sum \sum ...
first = True
max_upper = 0
sign_height = 0
for lim in expr.limits:
prettyLower, prettyUpper = self.__print_SumProduct_Limits(lim)
max_upper = max(max_upper, prettyUpper.height())
# Create sum sign based on the height of the argument
d, h, slines, adjustment = asum(
H, prettyLower.width(), prettyUpper.width(), ascii_mode)
prettySign = stringPict('')
prettySign = prettyForm(*prettySign.stack(*slines))
if first:
sign_height = prettySign.height()
prettySign = prettyForm(*prettySign.above(prettyUpper))
prettySign = prettyForm(*prettySign.below(prettyLower))
if first:
# change F baseline so it centers on the sign
prettyF.baseline -= d - (prettyF.height()//2 -
prettyF.baseline)
first = False
# put padding to the right
pad = stringPict('')
pad = prettyForm(*pad.stack(*[' ']*h))
prettySign = prettyForm(*prettySign.right(pad))
# put the present prettyF to the right
prettyF = prettyForm(*prettySign.right(prettyF))
# adjust baseline of ascii mode sigma with an odd height so that it is
# exactly through the center
ascii_adjustment = ascii_mode if not adjustment else 0
prettyF.baseline = max_upper + sign_height//2 + ascii_adjustment
prettyF.binding = prettyForm.MUL
return prettyF
def _print_Limit(self, l):
e, z, z0, dir = l.args
E = self._print(e)
if precedence(e) <= PRECEDENCE["Mul"]:
E = prettyForm(*E.parens('(', ')'))
Lim = prettyForm('lim')
LimArg = self._print(z)
if self._use_unicode:
LimArg = prettyForm(*LimArg.right('\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{RIGHTWARDS ARROW}'))
else:
LimArg = prettyForm(*LimArg.right('->'))
LimArg = prettyForm(*LimArg.right(self._print(z0)))
if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity):
dir = ""
else:
if self._use_unicode:
dir = '\N{SUPERSCRIPT PLUS SIGN}' if str(dir) == "+" else '\N{SUPERSCRIPT MINUS}'
LimArg = prettyForm(*LimArg.right(self._print(dir)))
Lim = prettyForm(*Lim.below(LimArg))
Lim = prettyForm(*Lim.right(E), binding=prettyForm.MUL)
return Lim
def _print_matrix_contents(self, e):
"""
This method factors out what is essentially grid printing.
"""
M = e # matrix
Ms = {} # i,j -> pretty(M[i,j])
for i in range(M.rows):
for j in range(M.cols):
Ms[i, j] = self._print(M[i, j])
# h- and v- spacers
hsep = 2
vsep = 1
# max width for columns
maxw = [-1] * M.cols
for j in range(M.cols):
maxw[j] = max([Ms[i, j].width() for i in range(M.rows)] or [0])
# drawing result
D = None
for i in range(M.rows):
D_row = None
for j in range(M.cols):
s = Ms[i, j]
# reshape s to maxw
# XXX this should be generalized, and go to stringPict.reshape ?
assert s.width() <= maxw[j]
# hcenter it, +0.5 to the right 2
# ( it's better to align formula starts for say 0 and r )
# XXX this is not good in all cases -- maybe introduce vbaseline?
wdelta = maxw[j] - s.width()
wleft = wdelta // 2
wright = wdelta - wleft
s = prettyForm(*s.right(' '*wright))
s = prettyForm(*s.left(' '*wleft))
# we don't need vcenter cells -- this is automatically done in
# a pretty way because when their baselines are taking into
# account in .right()
if D_row is None:
D_row = s # first box in a row
continue
D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer
D_row = prettyForm(*D_row.right(s))
if D is None:
D = D_row # first row in a picture
continue
# v-spacer
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
if D is None:
D = prettyForm('') # Empty Matrix
return D
def _print_MatrixBase(self, e):
D = self._print_matrix_contents(e)
D.baseline = D.height()//2
D = prettyForm(*D.parens('[', ']'))
return D
def _print_TensorProduct(self, expr):
# This should somehow share the code with _print_WedgeProduct:
circled_times = "\u2297"
return self._print_seq(expr.args, None, None, circled_times,
parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"])
def _print_WedgeProduct(self, expr):
# This should somehow share the code with _print_TensorProduct:
wedge_symbol = "\u2227"
return self._print_seq(expr.args, None, None, wedge_symbol,
parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"])
def _print_Trace(self, e):
D = self._print(e.arg)
D = prettyForm(*D.parens('(',')'))
D.baseline = D.height()//2
D = prettyForm(*D.left('\n'*(0) + 'tr'))
return D
def _print_MatrixElement(self, expr):
from sympy.matrices import MatrixSymbol
from sympy import Symbol
if (isinstance(expr.parent, MatrixSymbol)
and expr.i.is_number and expr.j.is_number):
return self._print(
Symbol(expr.parent.name + '_%d%d' % (expr.i, expr.j)))
else:
prettyFunc = self._print(expr.parent)
prettyFunc = prettyForm(*prettyFunc.parens())
prettyIndices = self._print_seq((expr.i, expr.j), delimiter=', '
).parens(left='[', right=']')[0]
pform = prettyForm(binding=prettyForm.FUNC,
*stringPict.next(prettyFunc, prettyIndices))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyIndices
return pform
def _print_MatrixSlice(self, m):
# XXX works only for applied functions
from sympy.matrices import MatrixSymbol
prettyFunc = self._print(m.parent)
if not isinstance(m.parent, MatrixSymbol):
prettyFunc = prettyForm(*prettyFunc.parens())
def ppslice(x, dim):
x = list(x)
if x[2] == 1:
del x[2]
if x[0] == 0:
x[0] = ''
if x[1] == dim:
x[1] = ''
return prettyForm(*self._print_seq(x, delimiter=':'))
prettyArgs = self._print_seq((ppslice(m.rowslice, m.parent.rows),
ppslice(m.colslice, m.parent.cols)), delimiter=', ').parens(left='[', right=']')[0]
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform
def _print_Transpose(self, expr):
pform = self._print(expr.arg)
from sympy.matrices import MatrixSymbol
if not isinstance(expr.arg, MatrixSymbol):
pform = prettyForm(*pform.parens())
pform = pform**(prettyForm('T'))
return pform
def _print_Adjoint(self, expr):
pform = self._print(expr.arg)
if self._use_unicode:
dag = prettyForm('\N{DAGGER}')
else:
dag = prettyForm('+')
from sympy.matrices import MatrixSymbol
if not isinstance(expr.arg, MatrixSymbol):
pform = prettyForm(*pform.parens())
pform = pform**dag
return pform
def _print_BlockMatrix(self, B):
if B.blocks.shape == (1, 1):
return self._print(B.blocks[0, 0])
return self._print(B.blocks)
def _print_MatAdd(self, expr):
s = None
for item in expr.args:
pform = self._print(item)
if s is None:
s = pform # First element
else:
coeff = item.as_coeff_mmul()[0]
if _coeff_isneg(S(coeff)):
s = prettyForm(*stringPict.next(s, ' '))
pform = self._print(item)
else:
s = prettyForm(*stringPict.next(s, ' + '))
s = prettyForm(*stringPict.next(s, pform))
return s
def _print_MatMul(self, expr):
args = list(expr.args)
from sympy import Add, MatAdd, HadamardProduct, KroneckerProduct
for i, a in enumerate(args):
if (isinstance(a, (Add, MatAdd, HadamardProduct, KroneckerProduct))
and len(expr.args) > 1):
args[i] = prettyForm(*self._print(a).parens())
else:
args[i] = self._print(a)
return prettyForm.__mul__(*args)
def _print_Identity(self, expr):
if self._use_unicode:
return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL I}')
else:
return prettyForm('I')
def _print_ZeroMatrix(self, expr):
if self._use_unicode:
return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}')
else:
return prettyForm('0')
def _print_OneMatrix(self, expr):
if self._use_unicode:
return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ONE}')
else:
return prettyForm('1')
def _print_DotProduct(self, expr):
args = list(expr.args)
for i, a in enumerate(args):
args[i] = self._print(a)
return prettyForm.__mul__(*args)
def _print_MatPow(self, expr):
pform = self._print(expr.base)
from sympy.matrices import MatrixSymbol
if not isinstance(expr.base, MatrixSymbol):
pform = prettyForm(*pform.parens())
pform = pform**(self._print(expr.exp))
return pform
def _print_HadamardProduct(self, expr):
from sympy import MatAdd, MatMul, HadamardProduct
if self._use_unicode:
delim = pretty_atom('Ring')
else:
delim = '.*'
return self._print_seq(expr.args, None, None, delim,
parenthesize=lambda x: isinstance(x, (MatAdd, MatMul, HadamardProduct)))
def _print_HadamardPower(self, expr):
# from sympy import MatAdd, MatMul
if self._use_unicode:
circ = pretty_atom('Ring')
else:
circ = self._print('.')
pretty_base = self._print(expr.base)
pretty_exp = self._print(expr.exp)
if precedence(expr.exp) < PRECEDENCE["Mul"]:
pretty_exp = prettyForm(*pretty_exp.parens())
pretty_circ_exp = prettyForm(
binding=prettyForm.LINE,
*stringPict.next(circ, pretty_exp)
)
return pretty_base**pretty_circ_exp
def _print_KroneckerProduct(self, expr):
from sympy import MatAdd, MatMul
if self._use_unicode:
delim = ' \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_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 = prettyForm(*stringPict.next(s, pform))
return s
def _print_Feedback(self, expr):
from sympy.physics.control import TransferFunction, Parallel, Series
num, tf = expr.num, TransferFunction(1, 1, expr.num.var)
num_arg_list = list(num.args) if isinstance(num, Series) else [num]
den_arg_list = list(expr.den.args) if isinstance(expr.den, Series) else [expr.den]
if isinstance(num, Series) and isinstance(expr.den, Series):
den = Parallel(tf, Series(*num_arg_list, *den_arg_list))
elif isinstance(num, Series) and isinstance(expr.den, TransferFunction):
if expr.den == tf:
den = Parallel(tf, Series(*num_arg_list))
else:
den = Parallel(tf, Series(*num_arg_list, expr.den))
elif isinstance(num, TransferFunction) and isinstance(expr.den, Series):
if num == tf:
den = Parallel(tf, Series(*den_arg_list))
else:
den = Parallel(tf, Series(num, *den_arg_list))
else:
if num == tf:
den = Parallel(tf, *den_arg_list)
elif expr.den == tf:
den = Parallel(tf, *num_arg_list)
else:
den = Parallel(tf, Series(*num_arg_list, *den_arg_list))
return self._print(num)/self._print(den)
def _print_BasisDependent(self, expr):
from sympy.vector import Vector
if not self._use_unicode:
raise NotImplementedError("ASCII pretty printing of BasisDependent is not implemented")
if expr == expr.zero:
return prettyForm(expr.zero._pretty_form)
o1 = []
vectstrs = []
if isinstance(expr, Vector):
items = expr.separate().items()
else:
items = [(0, expr)]
for system, vect in items:
inneritems = list(vect.components.items())
inneritems.sort(key = lambda x: x[0].__str__())
for k, v in inneritems:
#if the coef of the basis vector is 1
#we skip the 1
if v == 1:
o1.append("" +
k._pretty_form)
#Same for -1
elif v == -1:
o1.append("(-1) " +
k._pretty_form)
#For a general expr
else:
#We always wrap the measure numbers in
#parentheses
arg_str = self._print(
v).parens()[0]
o1.append(arg_str + ' ' + k._pretty_form)
vectstrs.append(k._pretty_form)
#outstr = u("").join(o1)
if o1[0].startswith(" + "):
o1[0] = o1[0][3:]
elif o1[0].startswith(" "):
o1[0] = o1[0][1:]
#Fixing the newlines
lengths = []
strs = ['']
flag = []
for i, partstr in enumerate(o1):
flag.append(0)
# XXX: What is this hack?
if '\n' in partstr:
tempstr = partstr
tempstr = tempstr.replace(vectstrs[i], '')
if '\N{right parenthesis extension}' in tempstr: # If scalar is a fraction
for paren in range(len(tempstr)):
flag[i] = 1
if tempstr[paren] == '\N{right parenthesis extension}':
tempstr = tempstr[:paren] + '\N{right parenthesis extension}'\
+ ' ' + vectstrs[i] + tempstr[paren + 1:]
break
elif '\N{RIGHT PARENTHESIS LOWER HOOK}' in tempstr:
flag[i] = 1
tempstr = tempstr.replace('\N{RIGHT PARENTHESIS LOWER HOOK}',
'\N{RIGHT PARENTHESIS LOWER HOOK}'
+ ' ' + vectstrs[i])
else:
tempstr = tempstr.replace('\N{RIGHT PARENTHESIS UPPER HOOK}',
'\N{RIGHT PARENTHESIS UPPER HOOK}'
+ ' ' + vectstrs[i])
o1[i] = tempstr
o1 = [x.split('\n') for x in o1]
n_newlines = max([len(x) for x in o1]) # Width of part in its pretty form
if 1 in flag: # If there was a fractional scalar
for i, parts in enumerate(o1):
if len(parts) == 1: # If part has no newline
parts.insert(0, ' ' * (len(parts[0])))
flag[i] = 1
for i, parts in enumerate(o1):
lengths.append(len(parts[flag[i]]))
for j in range(n_newlines):
if j+1 <= len(parts):
if j >= len(strs):
strs.append(' ' * (sum(lengths[:-1]) +
3*(len(lengths)-1)))
if j == flag[i]:
strs[flag[i]] += parts[flag[i]] + ' + '
else:
strs[j] += parts[j] + ' '*(lengths[-1] -
len(parts[j])+
3)
else:
if j >= len(strs):
strs.append(' ' * (sum(lengths[:-1]) +
3*(len(lengths)-1)))
strs[j] += ' '*(lengths[-1]+3)
return prettyForm('\n'.join([s[:-3] for s in strs]))
def _print_NDimArray(self, expr):
from sympy import ImmutableMatrix
if expr.rank() == 0:
return self._print(expr[()])
level_str = [[]] + [[] for i in range(expr.rank())]
shape_ranges = [list(range(i)) for i in expr.shape]
# leave eventual matrix elements unflattened
mat = lambda x: ImmutableMatrix(x, evaluate=False)
for outer_i in itertools.product(*shape_ranges):
level_str[-1].append(expr[outer_i])
even = True
for back_outer_i in range(expr.rank()-1, -1, -1):
if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]:
break
if even:
level_str[back_outer_i].append(level_str[back_outer_i+1])
else:
level_str[back_outer_i].append(mat(
level_str[back_outer_i+1]))
if len(level_str[back_outer_i + 1]) == 1:
level_str[back_outer_i][-1] = mat(
[[level_str[back_outer_i][-1]]])
even = not even
level_str[back_outer_i+1] = []
out_expr = level_str[0][0]
if expr.rank() % 2 == 1:
out_expr = mat([out_expr])
return self._print(out_expr)
def _printer_tensor_indices(self, name, indices, index_map={}):
center = stringPict(name)
top = stringPict(" "*center.width())
bot = stringPict(" "*center.width())
last_valence = None
prev_map = None
for i, index in enumerate(indices):
indpic = self._print(index.args[0])
if ((index in index_map) or prev_map) and last_valence == index.is_up:
if index.is_up:
top = prettyForm(*stringPict.next(top, ","))
else:
bot = prettyForm(*stringPict.next(bot, ","))
if index in index_map:
indpic = prettyForm(*stringPict.next(indpic, "="))
indpic = prettyForm(*stringPict.next(indpic, self._print(index_map[index])))
prev_map = True
else:
prev_map = False
if index.is_up:
top = stringPict(*top.right(indpic))
center = stringPict(*center.right(" "*indpic.width()))
bot = stringPict(*bot.right(" "*indpic.width()))
else:
bot = stringPict(*bot.right(indpic))
center = stringPict(*center.right(" "*indpic.width()))
top = stringPict(*top.right(" "*indpic.width()))
last_valence = index.is_up
pict = prettyForm(*center.above(top))
pict = prettyForm(*pict.below(bot))
return pict
def _print_Tensor(self, expr):
name = expr.args[0].name
indices = expr.get_indices()
return self._printer_tensor_indices(name, indices)
def _print_TensorElement(self, expr):
name = expr.expr.args[0].name
indices = expr.expr.get_indices()
index_map = expr.index_map
return self._printer_tensor_indices(name, indices, index_map)
def _print_TensMul(self, expr):
sign, args = expr._get_args_for_traditional_printer()
args = [
prettyForm(*self._print(i).parens()) if
precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i)
for i in args
]
pform = prettyForm.__mul__(*args)
if sign:
return prettyForm(*pform.left(sign))
else:
return pform
def _print_TensAdd(self, expr):
args = [
prettyForm(*self._print(i).parens()) if
precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i)
for i in expr.args
]
return prettyForm.__add__(*args)
def _print_TensorIndex(self, expr):
sym = expr.args[0]
if not expr.is_up:
sym = -sym
return self._print(sym)
def _print_PartialDerivative(self, deriv):
if self._use_unicode:
deriv_symbol = U('PARTIAL DIFFERENTIAL')
else:
deriv_symbol = r'd'
x = None
for variable in reversed(deriv.variables):
s = self._print(variable)
ds = prettyForm(*s.left(deriv_symbol))
if x is None:
x = ds
else:
x = prettyForm(*x.right(' '))
x = prettyForm(*x.right(ds))
f = prettyForm(
binding=prettyForm.FUNC, *self._print(deriv.expr).parens())
pform = prettyForm(deriv_symbol)
if len(deriv.variables) > 1:
pform = pform**self._print(len(deriv.variables))
pform = prettyForm(*pform.below(stringPict.LINE, x))
pform.baseline = pform.baseline + 1
pform = prettyForm(*stringPict.next(pform, f))
pform.binding = prettyForm.MUL
return pform
def _print_Piecewise(self, pexpr):
P = {}
for n, ec in enumerate(pexpr.args):
P[n, 0] = self._print(ec.expr)
if ec.cond == True:
P[n, 1] = prettyForm('otherwise')
else:
P[n, 1] = prettyForm(
*prettyForm('for ').right(self._print(ec.cond)))
hsep = 2
vsep = 1
len_args = len(pexpr.args)
# max widths
maxw = [max([P[i, j].width() for i in range(len_args)])
for j in range(2)]
# FIXME: Refactor this code and matrix into some tabular environment.
# drawing result
D = None
for i in range(len_args):
D_row = None
for j in range(2):
p = P[i, j]
assert p.width() <= maxw[j]
wdelta = maxw[j] - p.width()
wleft = wdelta // 2
wright = wdelta - wleft
p = prettyForm(*p.right(' '*wright))
p = prettyForm(*p.left(' '*wleft))
if D_row is None:
D_row = p
continue
D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer
D_row = prettyForm(*D_row.right(p))
if D is None:
D = D_row # first row in a picture
continue
# v-spacer
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
D = prettyForm(*D.parens('{', ''))
D.baseline = D.height()//2
D.binding = prettyForm.OPEN
return D
def _print_ITE(self, ite):
from sympy.functions.elementary.piecewise import Piecewise
return self._print(ite.rewrite(Piecewise))
def _hprint_vec(self, v):
D = None
for a in v:
p = a
if D is None:
D = p
else:
D = prettyForm(*D.right(', '))
D = prettyForm(*D.right(p))
if D is None:
D = stringPict(' ')
return D
def _hprint_vseparator(self, p1, p2, left=None, right=None, delimiter='', ifascii_nougly=False):
if ifascii_nougly and not self._use_unicode:
return self._print_seq((p1, '|', p2), left=left, right=right,
delimiter=delimiter, ifascii_nougly=True)
tmp = self._print_seq((p1, p2,), left=left, right=right, delimiter=delimiter)
sep = stringPict(vobj('|', tmp.height()), baseline=tmp.baseline)
return self._print_seq((p1, sep, p2), left=left, right=right,
delimiter=delimiter)
def _print_hyper(self, e):
# FIXME refactor Matrix, Piecewise, and this into a tabular environment
ap = [self._print(a) for a in e.ap]
bq = [self._print(b) for b in e.bq]
P = self._print(e.argument)
P.baseline = P.height()//2
# Drawing result - first create the ap, bq vectors
D = None
for v in [ap, bq]:
D_row = self._hprint_vec(v)
if D is None:
D = D_row # first row in a picture
else:
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
# make sure that the argument `z' is centred vertically
D.baseline = D.height()//2
# insert horizontal separator
P = prettyForm(*P.left(' '))
D = prettyForm(*D.right(' '))
# insert separating `|`
D = self._hprint_vseparator(D, P)
# add parens
D = prettyForm(*D.parens('(', ')'))
# create the F symbol
above = D.height()//2 - 1
below = D.height() - above - 1
sz, t, b, add, img = annotated('F')
F = prettyForm('\n' * (above - t) + img + '\n' * (below - b),
baseline=above + sz)
add = (sz + 1)//2
F = prettyForm(*F.left(self._print(len(e.ap))))
F = prettyForm(*F.right(self._print(len(e.bq))))
F.baseline = above + add
D = prettyForm(*F.right(' ', D))
return D
def _print_meijerg(self, e):
# FIXME refactor Matrix, Piecewise, and this into a tabular environment
v = {}
v[(0, 0)] = [self._print(a) for a in e.an]
v[(0, 1)] = [self._print(a) for a in e.aother]
v[(1, 0)] = [self._print(b) for b in e.bm]
v[(1, 1)] = [self._print(b) for b in e.bother]
P = self._print(e.argument)
P.baseline = P.height()//2
vp = {}
for idx in v:
vp[idx] = self._hprint_vec(v[idx])
for i in range(2):
maxw = max(vp[(0, i)].width(), vp[(1, i)].width())
for j in range(2):
s = vp[(j, i)]
left = (maxw - s.width()) // 2
right = maxw - left - s.width()
s = prettyForm(*s.left(' ' * left))
s = prettyForm(*s.right(' ' * right))
vp[(j, i)] = s
D1 = prettyForm(*vp[(0, 0)].right(' ', vp[(0, 1)]))
D1 = prettyForm(*D1.below(' '))
D2 = prettyForm(*vp[(1, 0)].right(' ', vp[(1, 1)]))
D = prettyForm(*D1.below(D2))
# make sure that the argument `z' is centred vertically
D.baseline = D.height()//2
# insert horizontal separator
P = prettyForm(*P.left(' '))
D = prettyForm(*D.right(' '))
# insert separating `|`
D = self._hprint_vseparator(D, P)
# add parens
D = prettyForm(*D.parens('(', ')'))
# create the G symbol
above = D.height()//2 - 1
below = D.height() - above - 1
sz, t, b, add, img = annotated('G')
F = prettyForm('\n' * (above - t) + img + '\n' * (below - b),
baseline=above + sz)
pp = self._print(len(e.ap))
pq = self._print(len(e.bq))
pm = self._print(len(e.bm))
pn = self._print(len(e.an))
def adjust(p1, p2):
diff = p1.width() - p2.width()
if diff == 0:
return p1, p2
elif diff > 0:
return p1, prettyForm(*p2.left(' '*diff))
else:
return prettyForm(*p1.left(' '*-diff)), p2
pp, pm = adjust(pp, pm)
pq, pn = adjust(pq, pn)
pu = prettyForm(*pm.right(', ', pn))
pl = prettyForm(*pp.right(', ', pq))
ht = F.baseline - above - 2
if ht > 0:
pu = prettyForm(*pu.below('\n'*ht))
p = prettyForm(*pu.below(pl))
F.baseline = above
F = prettyForm(*F.right(p))
F.baseline = above + add
D = prettyForm(*F.right(' ', D))
return D
def _print_ExpBase(self, e):
# TODO should exp_polar be printed differently?
# what about exp_polar(0), exp_polar(1)?
base = prettyForm(pretty_atom('Exp1', 'e'))
return base ** self._print(e.args[0])
def _print_Exp1(self, e):
return prettyForm(pretty_atom('Exp1', 'e'))
def _print_Function(self, e, sort=False, func_name=None):
# optional argument func_name for supplying custom names
# XXX works only for applied functions
return self._helper_print_function(e.func, e.args, sort=sort, func_name=func_name)
def _print_mathieuc(self, e):
return self._print_Function(e, func_name='C')
def _print_mathieus(self, e):
return self._print_Function(e, func_name='S')
def _print_mathieucprime(self, e):
return self._print_Function(e, func_name="C'")
def _print_mathieusprime(self, e):
return self._print_Function(e, func_name="S'")
def _helper_print_function(self, func, args, sort=False, func_name=None, delimiter=', ', elementwise=False):
if sort:
args = sorted(args, key=default_sort_key)
if not func_name and hasattr(func, "__name__"):
func_name = func.__name__
if func_name:
prettyFunc = self._print(Symbol(func_name))
else:
prettyFunc = prettyForm(*self._print(func).parens())
if elementwise:
if self._use_unicode:
circ = pretty_atom('Modifier Letter Low Ring')
else:
circ = '.'
circ = self._print(circ)
prettyFunc = prettyForm(
binding=prettyForm.LINE,
*stringPict.next(prettyFunc, circ)
)
prettyArgs = prettyForm(*self._print_seq(args, delimiter=delimiter).parens())
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform
def _print_ElementwiseApplyFunction(self, e):
func = e.function
arg = e.expr
args = [arg]
return self._helper_print_function(func, args, delimiter="", elementwise=True)
@property
def _special_function_classes(self):
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.functions.special.gamma_functions import gamma, lowergamma
from sympy.functions.special.zeta_functions import lerchphi
from sympy.functions.special.beta_functions import beta
from sympy.functions.special.delta_functions import DiracDelta
from sympy.functions.special.error_functions import Chi
return {KroneckerDelta: [greek_unicode['delta'], 'delta'],
gamma: [greek_unicode['Gamma'], 'Gamma'],
lerchphi: [greek_unicode['Phi'], 'lerchphi'],
lowergamma: [greek_unicode['gamma'], 'gamma'],
beta: [greek_unicode['Beta'], 'B'],
DiracDelta: [greek_unicode['delta'], 'delta'],
Chi: ['Chi', 'Chi']}
def _print_FunctionClass(self, expr):
for cls in self._special_function_classes:
if issubclass(expr, cls) and expr.__name__ == cls.__name__:
if self._use_unicode:
return prettyForm(self._special_function_classes[cls][0])
else:
return prettyForm(self._special_function_classes[cls][1])
func_name = expr.__name__
return prettyForm(pretty_symbol(func_name))
def _print_GeometryEntity(self, expr):
# GeometryEntity is based on Tuple but should not print like a Tuple
return self.emptyPrinter(expr)
def _print_lerchphi(self, e):
func_name = greek_unicode['Phi'] if self._use_unicode else 'lerchphi'
return self._print_Function(e, func_name=func_name)
def _print_dirichlet_eta(self, e):
func_name = greek_unicode['eta'] if self._use_unicode else 'dirichlet_eta'
return self._print_Function(e, func_name=func_name)
def _print_Heaviside(self, e):
func_name = greek_unicode['theta'] if self._use_unicode else 'Heaviside'
if e.args[1]==1/2:
pform = prettyForm(*self._print(e.args[0]).parens())
pform = prettyForm(*pform.left(func_name))
return pform
else:
return self._print_Function(e, func_name=func_name)
def _print_fresnels(self, e):
return self._print_Function(e, func_name="S")
def _print_fresnelc(self, e):
return self._print_Function(e, func_name="C")
def _print_airyai(self, e):
return self._print_Function(e, func_name="Ai")
def _print_airybi(self, e):
return self._print_Function(e, func_name="Bi")
def _print_airyaiprime(self, e):
return self._print_Function(e, func_name="Ai'")
def _print_airybiprime(self, e):
return self._print_Function(e, func_name="Bi'")
def _print_LambertW(self, e):
return self._print_Function(e, func_name="W")
def _print_Lambda(self, e):
expr = e.expr
sig = e.signature
if self._use_unicode:
arrow = " \N{RIGHTWARDS ARROW FROM BAR} "
else:
arrow = " -> "
if len(sig) == 1 and sig[0].is_symbol:
sig = sig[0]
var_form = self._print(sig)
return prettyForm(*stringPict.next(var_form, arrow, self._print(expr)), binding=8)
def _print_Order(self, expr):
pform = self._print(expr.expr)
if (expr.point and any(p != S.Zero for p in expr.point)) or \
len(expr.variables) > 1:
pform = prettyForm(*pform.right("; "))
if len(expr.variables) > 1:
pform = prettyForm(*pform.right(self._print(expr.variables)))
elif len(expr.variables):
pform = prettyForm(*pform.right(self._print(expr.variables[0])))
if self._use_unicode:
pform = prettyForm(*pform.right(" \N{RIGHTWARDS ARROW} "))
else:
pform = prettyForm(*pform.right(" -> "))
if len(expr.point) > 1:
pform = prettyForm(*pform.right(self._print(expr.point)))
else:
pform = prettyForm(*pform.right(self._print(expr.point[0])))
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left("O"))
return pform
def _print_SingularityFunction(self, e):
if self._use_unicode:
shift = self._print(e.args[0]-e.args[1])
n = self._print(e.args[2])
base = prettyForm("<")
base = prettyForm(*base.right(shift))
base = prettyForm(*base.right(">"))
pform = base**n
return pform
else:
n = self._print(e.args[2])
shift = self._print(e.args[0]-e.args[1])
base = self._print_seq(shift, "<", ">", ' ')
return base**n
def _print_beta(self, e):
func_name = greek_unicode['Beta'] if self._use_unicode else 'B'
return self._print_Function(e, func_name=func_name)
def _print_betainc(self, e):
func_name = "B'"
return self._print_Function(e, func_name=func_name)
def _print_betainc_regularized(self, e):
func_name = 'I'
return self._print_Function(e, func_name=func_name)
def _print_gamma(self, e):
func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma'
return self._print_Function(e, func_name=func_name)
def _print_uppergamma(self, e):
func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma'
return self._print_Function(e, func_name=func_name)
def _print_lowergamma(self, e):
func_name = greek_unicode['gamma'] if self._use_unicode else 'lowergamma'
return self._print_Function(e, func_name=func_name)
def _print_DiracDelta(self, e):
if self._use_unicode:
if len(e.args) == 2:
a = prettyForm(greek_unicode['delta'])
b = self._print(e.args[1])
b = prettyForm(*b.parens())
c = self._print(e.args[0])
c = prettyForm(*c.parens())
pform = a**b
pform = prettyForm(*pform.right(' '))
pform = prettyForm(*pform.right(c))
return pform
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left(greek_unicode['delta']))
return pform
else:
return self._print_Function(e)
def _print_expint(self, e):
from sympy import Function
if e.args[0].is_Integer and self._use_unicode:
return self._print_Function(Function('E_%s' % e.args[0])(e.args[1]))
return self._print_Function(e)
def _print_Chi(self, e):
# This needs a special case since otherwise it comes out as greek
# letter chi...
prettyFunc = prettyForm("Chi")
prettyArgs = prettyForm(*self._print_seq(e.args).parens())
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
# store pform parts so it can be reassembled e.g. when powered
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform
def _print_elliptic_e(self, e):
pforma0 = self._print(e.args[0])
if len(e.args) == 1:
pform = pforma0
else:
pforma1 = self._print(e.args[1])
pform = self._hprint_vseparator(pforma0, pforma1)
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left('E'))
return pform
def _print_elliptic_k(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left('K'))
return pform
def _print_elliptic_f(self, e):
pforma0 = self._print(e.args[0])
pforma1 = self._print(e.args[1])
pform = self._hprint_vseparator(pforma0, pforma1)
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left('F'))
return pform
def _print_elliptic_pi(self, e):
name = greek_unicode['Pi'] if self._use_unicode else 'Pi'
pforma0 = self._print(e.args[0])
pforma1 = self._print(e.args[1])
if len(e.args) == 2:
pform = self._hprint_vseparator(pforma0, pforma1)
else:
pforma2 = self._print(e.args[2])
pforma = self._hprint_vseparator(pforma1, pforma2, ifascii_nougly=False)
pforma = prettyForm(*pforma.left('; '))
pform = prettyForm(*pforma.left(pforma0))
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left(name))
return pform
def _print_GoldenRatio(self, expr):
if self._use_unicode:
return prettyForm(pretty_symbol('phi'))
return self._print(Symbol("GoldenRatio"))
def _print_EulerGamma(self, expr):
if self._use_unicode:
return prettyForm(pretty_symbol('gamma'))
return self._print(Symbol("EulerGamma"))
def _print_Mod(self, expr):
pform = self._print(expr.args[0])
if pform.binding > prettyForm.MUL:
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.right(' mod '))
pform = prettyForm(*pform.right(self._print(expr.args[1])))
pform.binding = prettyForm.OPEN
return pform
def _print_Add(self, expr, order=None):
terms = self._as_ordered_terms(expr, order=order)
pforms, indices = [], []
def pretty_negative(pform, index):
"""Prepend a minus sign to a pretty form. """
#TODO: Move this code to prettyForm
if index == 0:
if pform.height() > 1:
pform_neg = '- '
else:
pform_neg = '-'
else:
pform_neg = ' - '
if (pform.binding > prettyForm.NEG
or pform.binding == prettyForm.ADD):
p = stringPict(*pform.parens())
else:
p = pform
p = stringPict.next(pform_neg, p)
# Lower the binding to NEG, even if it was higher. Otherwise, it
# will print as a + ( - (b)), instead of a - (b).
return prettyForm(binding=prettyForm.NEG, *p)
for i, term in enumerate(terms):
if term.is_Mul and _coeff_isneg(term):
coeff, other = term.as_coeff_mul(rational=False)
if coeff == -1:
negterm = Mul(*other, evaluate=False)
else:
negterm = Mul(-coeff, *other, evaluate=False)
pform = self._print(negterm)
pforms.append(pretty_negative(pform, i))
elif term.is_Rational and term.q > 1:
pforms.append(None)
indices.append(i)
elif term.is_Number and term < 0:
pform = self._print(-term)
pforms.append(pretty_negative(pform, i))
elif term.is_Relational:
pforms.append(prettyForm(*self._print(term).parens()))
else:
pforms.append(self._print(term))
if indices:
large = True
for pform in pforms:
if pform is not None and pform.height() > 1:
break
else:
large = False
for i in indices:
term, negative = terms[i], False
if term < 0:
term, negative = -term, True
if large:
pform = prettyForm(str(term.p))/prettyForm(str(term.q))
else:
pform = self._print(term)
if negative:
pform = pretty_negative(pform, i)
pforms[i] = pform
return prettyForm.__add__(*pforms)
def _print_Mul(self, product):
from sympy.physics.units import Quantity
# Check for unevaluated Mul. In this case we need to make sure the
# identities are visible, multiple Rational factors are not combined
# etc so we display in a straight-forward form that fully preserves all
# args and their order.
args = product.args
if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]):
strargs = list(map(self._print, args))
# XXX: This is a hack to work around the fact that
# prettyForm.__mul__ absorbs a leading -1 in the args. Probably it
# would be better to fix this in prettyForm.__mul__ instead.
negone = strargs[0] == '-1'
if negone:
strargs[0] = prettyForm('1', 0, 0)
obj = prettyForm.__mul__(*strargs)
if negone:
obj = prettyForm('-' + obj.s, obj.baseline, obj.binding)
return obj
a = [] # items in the numerator
b = [] # items that are in the denominator (if any)
if self.order not in ('old', 'none'):
args = product.as_ordered_factors()
else:
args = list(product.args)
# If quantities are present append them at the back
args = sorted(args, key=lambda x: isinstance(x, Quantity) or
(isinstance(x, Pow) and isinstance(x.base, Quantity)))
# Gather terms for numerator/denominator
for item in args:
if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative:
if item.exp != -1:
b.append(Pow(item.base, -item.exp, evaluate=False))
else:
b.append(Pow(item.base, -item.exp))
elif item.is_Rational and item is not S.Infinity:
if item.p != 1:
a.append( Rational(item.p) )
if item.q != 1:
b.append( Rational(item.q) )
else:
a.append(item)
from sympy import Integral, Piecewise, Product, Sum
# Convert to pretty forms. Add parens to Add instances if there
# is more than one term in the numer/denom
for i in range(0, len(a)):
if (a[i].is_Add and len(a) > 1) or (i != len(a) - 1 and
isinstance(a[i], (Integral, Piecewise, Product, Sum))):
a[i] = prettyForm(*self._print(a[i]).parens())
elif a[i].is_Relational:
a[i] = prettyForm(*self._print(a[i]).parens())
else:
a[i] = self._print(a[i])
for i in range(0, len(b)):
if (b[i].is_Add and len(b) > 1) or (i != len(b) - 1 and
isinstance(b[i], (Integral, Piecewise, Product, Sum))):
b[i] = prettyForm(*self._print(b[i]).parens())
else:
b[i] = self._print(b[i])
# Construct a pretty form
if len(b) == 0:
return prettyForm.__mul__(*a)
else:
if len(a) == 0:
a.append( self._print(S.One) )
return prettyForm.__mul__(*a)/prettyForm.__mul__(*b)
# A helper function for _print_Pow to print x**(1/n)
def _print_nth_root(self, base, root):
bpretty = self._print(base)
# In very simple cases, use a single-char root sign
if (self._settings['use_unicode_sqrt_char'] and self._use_unicode
and root == 2 and bpretty.height() == 1
and (bpretty.width() == 1
or (base.is_Integer and base.is_nonnegative))):
return prettyForm(*bpretty.left('\N{SQUARE ROOT}'))
# Construct root sign, start with the \/ shape
_zZ = xobj('/', 1)
rootsign = xobj('\\', 1) + _zZ
# Constructing the number to put on root
rpretty = self._print(root)
# roots look bad if they are not a single line
if rpretty.height() != 1:
return self._print(base)**self._print(1/root)
# If power is half, no number should appear on top of root sign
exp = '' if root == 2 else str(rpretty).ljust(2)
if len(exp) > 2:
rootsign = ' '*(len(exp) - 2) + rootsign
# Stack the exponent
rootsign = stringPict(exp + '\n' + rootsign)
rootsign.baseline = 0
# Diagonal: length is one less than height of base
linelength = bpretty.height() - 1
diagonal = stringPict('\n'.join(
' '*(linelength - i - 1) + _zZ + ' '*i
for i in range(linelength)
))
# Put baseline just below lowest line: next to exp
diagonal.baseline = linelength - 1
# Make the root symbol
rootsign = prettyForm(*rootsign.right(diagonal))
# Det the baseline to match contents to fix the height
# but if the height of bpretty is one, the rootsign must be one higher
rootsign.baseline = max(1, bpretty.baseline)
#build result
s = prettyForm(hobj('_', 2 + bpretty.width()))
s = prettyForm(*bpretty.above(s))
s = prettyForm(*s.left(rootsign))
return s
def _print_Pow(self, power):
from sympy.simplify.simplify import fraction
b, e = power.as_base_exp()
if power.is_commutative:
if e is S.NegativeOne:
return prettyForm("1")/self._print(b)
n, d = fraction(e)
if n is S.One and d.is_Atom and not e.is_Integer and (e.is_Rational or d.is_Symbol) \
and self._settings['root_notation']:
return self._print_nth_root(b, d)
if e.is_Rational and e < 0:
return prettyForm("1")/self._print(Pow(b, -e, evaluate=False))
if b.is_Relational:
return prettyForm(*self._print(b).parens()).__pow__(self._print(e))
return self._print(b)**self._print(e)
def _print_UnevaluatedExpr(self, expr):
return self._print(expr.args[0])
def __print_numer_denom(self, p, q):
if q == 1:
if p < 0:
return prettyForm(str(p), binding=prettyForm.NEG)
else:
return prettyForm(str(p))
elif abs(p) >= 10 and abs(q) >= 10:
# If more than one digit in numer and denom, print larger fraction
if p < 0:
return prettyForm(str(p), binding=prettyForm.NEG)/prettyForm(str(q))
# Old printing method:
#pform = prettyForm(str(-p))/prettyForm(str(q))
#return prettyForm(binding=prettyForm.NEG, *pform.left('- '))
else:
return prettyForm(str(p))/prettyForm(str(q))
else:
return None
def _print_Rational(self, expr):
result = self.__print_numer_denom(expr.p, expr.q)
if result is not None:
return result
else:
return self.emptyPrinter(expr)
def _print_Fraction(self, expr):
result = self.__print_numer_denom(expr.numerator, expr.denominator)
if result is not None:
return result
else:
return self.emptyPrinter(expr)
def _print_ProductSet(self, p):
if len(p.sets) >= 1 and not has_variety(p.sets):
return self._print(p.sets[0]) ** self._print(len(p.sets))
else:
prod_char = "\N{MULTIPLICATION SIGN}" if self._use_unicode else 'x'
return self._print_seq(p.sets, None, None, ' %s ' % prod_char,
parenthesize=lambda set: set.is_Union or
set.is_Intersection or set.is_ProductSet)
def _print_FiniteSet(self, s):
items = sorted(s.args, key=default_sort_key)
return self._print_seq(items, '{', '}', ', ' )
def _print_Range(self, s):
if self._use_unicode:
dots = "\N{HORIZONTAL ELLIPSIS}"
else:
dots = '...'
if s.start.is_infinite and s.stop.is_infinite:
if s.step.is_positive:
printset = dots, -1, 0, 1, dots
else:
printset = dots, 1, 0, -1, dots
elif s.start.is_infinite:
printset = dots, s[-1] - s.step, s[-1]
elif s.stop.is_infinite:
it = iter(s)
printset = next(it), next(it), dots
elif len(s) > 4:
it = iter(s)
printset = next(it), next(it), dots, s[-1]
else:
printset = tuple(s)
return self._print_seq(printset, '{', '}', ', ' )
def _print_Interval(self, i):
if i.start == i.end:
return self._print_seq(i.args[:1], '{', '}')
else:
if i.left_open:
left = '('
else:
left = '['
if i.right_open:
right = ')'
else:
right = ']'
return self._print_seq(i.args[:2], left, right)
def _print_AccumulationBounds(self, i):
left = '<'
right = '>'
return self._print_seq(i.args[:2], left, right)
def _print_Intersection(self, u):
delimiter = ' %s ' % pretty_atom('Intersection', 'n')
return self._print_seq(u.args, None, None, delimiter,
parenthesize=lambda set: set.is_ProductSet or
set.is_Union or set.is_Complement)
def _print_Union(self, u):
union_delimiter = ' %s ' % pretty_atom('Union', 'U')
return self._print_seq(u.args, None, None, union_delimiter,
parenthesize=lambda set: set.is_ProductSet or
set.is_Intersection or set.is_Complement)
def _print_SymmetricDifference(self, u):
if not self._use_unicode:
raise NotImplementedError("ASCII pretty printing of SymmetricDifference is not implemented")
sym_delimeter = ' %s ' % pretty_atom('SymmetricDifference')
return self._print_seq(u.args, None, None, sym_delimeter)
def _print_Complement(self, u):
delimiter = r' \ '
return self._print_seq(u.args, None, None, delimiter,
parenthesize=lambda set: set.is_ProductSet or set.is_Intersection
or set.is_Union)
def _print_ImageSet(self, ts):
if self._use_unicode:
inn = "\N{SMALL ELEMENT OF}"
else:
inn = 'in'
fun = ts.lamda
sets = ts.base_sets
signature = fun.signature
expr = self._print(fun.expr)
# TODO: the stuff to the left of the | and the stuff to the right of
# the | should have independent baselines, that way something like
# ImageSet(Lambda(x, 1/x**2), S.Naturals) prints the "x in N" part
# centered on the right instead of aligned with the fraction bar on
# the left. The same also applies to ConditionSet and ComplexRegion
if len(signature) == 1:
S = self._print_seq((signature[0], inn, sets[0]),
delimiter=' ')
return self._hprint_vseparator(expr, S,
left='{', right='}',
ifascii_nougly=True, delimiter=' ')
else:
pargs = tuple(j for var, setv in zip(signature, sets) for j in
(var, ' ', inn, ' ', setv, ", "))
S = self._print_seq(pargs[:-1], delimiter='')
return self._hprint_vseparator(expr, S,
left='{', right='}',
ifascii_nougly=True, delimiter=' ')
def _print_ConditionSet(self, ts):
if self._use_unicode:
inn = "\N{SMALL ELEMENT OF}"
# using _and because and is a keyword and it is bad practice to
# overwrite them
_and = "\N{LOGICAL AND}"
else:
inn = 'in'
_and = 'and'
variables = self._print_seq(Tuple(ts.sym))
as_expr = getattr(ts.condition, 'as_expr', None)
if as_expr is not None:
cond = self._print(ts.condition.as_expr())
else:
cond = self._print(ts.condition)
if self._use_unicode:
cond = self._print(cond)
cond = prettyForm(*cond.parens())
if ts.base_set is S.UniversalSet:
return self._hprint_vseparator(variables, cond, left="{",
right="}", ifascii_nougly=True,
delimiter=' ')
base = self._print(ts.base_set)
C = self._print_seq((variables, inn, base, _and, cond),
delimiter=' ')
return self._hprint_vseparator(variables, C, left="{", right="}",
ifascii_nougly=True, delimiter=' ')
def _print_ComplexRegion(self, ts):
if self._use_unicode:
inn = "\N{SMALL ELEMENT OF}"
else:
inn = 'in'
variables = self._print_seq(ts.variables)
expr = self._print(ts.expr)
prodsets = self._print(ts.sets)
C = self._print_seq((variables, inn, prodsets),
delimiter=' ')
return self._hprint_vseparator(expr, C, left="{", right="}",
ifascii_nougly=True, delimiter=' ')
def _print_Contains(self, e):
var, set = e.args
if self._use_unicode:
el = " \N{ELEMENT OF} "
return prettyForm(*stringPict.next(self._print(var),
el, self._print(set)), binding=8)
else:
return prettyForm(sstr(e))
def _print_FourierSeries(self, s):
if self._use_unicode:
dots = "\N{HORIZONTAL ELLIPSIS}"
else:
dots = '...'
return self._print_Add(s.truncate()) + self._print(dots)
def _print_FormalPowerSeries(self, s):
return self._print_Add(s.infinite)
def _print_SetExpr(self, se):
pretty_set = prettyForm(*self._print(se.set).parens())
pretty_name = self._print(Symbol("SetExpr"))
return prettyForm(*pretty_name.right(pretty_set))
def _print_SeqFormula(self, s):
if self._use_unicode:
dots = "\N{HORIZONTAL ELLIPSIS}"
else:
dots = '...'
if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0:
raise NotImplementedError("Pretty printing of sequences with symbolic bound not implemented")
if s.start is S.NegativeInfinity:
stop = s.stop
printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2),
s.coeff(stop - 1), s.coeff(stop))
elif s.stop is S.Infinity or s.length > 4:
printset = s[:4]
printset.append(dots)
printset = tuple(printset)
else:
printset = tuple(s)
return self._print_list(printset)
_print_SeqPer = _print_SeqFormula
_print_SeqAdd = _print_SeqFormula
_print_SeqMul = _print_SeqFormula
def _print_seq(self, seq, left=None, right=None, delimiter=', ',
parenthesize=lambda x: False, ifascii_nougly=True):
try:
pforms = []
for item in seq:
pform = self._print(item)
if parenthesize(item):
pform = prettyForm(*pform.parens())
if pforms:
pforms.append(delimiter)
pforms.append(pform)
if not pforms:
s = stringPict('')
else:
s = prettyForm(*stringPict.next(*pforms))
# XXX: Under the tests from #15686 the above raises:
# AttributeError: 'Fake' object has no attribute 'baseline'
# This is caught below but that is not the right way to
# fix it.
except AttributeError:
s = None
for item in seq:
pform = self.doprint(item)
if parenthesize(item):
pform = prettyForm(*pform.parens())
if s is None:
# first element
s = pform
else :
s = prettyForm(*stringPict.next(s, delimiter))
s = prettyForm(*stringPict.next(s, pform))
if s is None:
s = stringPict('')
s = prettyForm(*s.parens(left, right, ifascii_nougly=ifascii_nougly))
return s
def join(self, delimiter, args):
pform = None
for arg in args:
if pform is None:
pform = arg
else:
pform = prettyForm(*pform.right(delimiter))
pform = prettyForm(*pform.right(arg))
if pform is None:
return prettyForm("")
else:
return pform
def _print_list(self, l):
return self._print_seq(l, '[', ']')
def _print_tuple(self, t):
if len(t) == 1:
ptuple = prettyForm(*stringPict.next(self._print(t[0]), ','))
return prettyForm(*ptuple.parens('(', ')', ifascii_nougly=True))
else:
return self._print_seq(t, '(', ')')
def _print_Tuple(self, expr):
return self._print_tuple(expr)
def _print_dict(self, d):
keys = sorted(d.keys(), key=default_sort_key)
items = []
for k in keys:
K = self._print(k)
V = self._print(d[k])
s = prettyForm(*stringPict.next(K, ': ', V))
items.append(s)
return self._print_seq(items, '{', '}')
def _print_Dict(self, d):
return self._print_dict(d)
def _print_set(self, s):
if not s:
return prettyForm('set()')
items = sorted(s, key=default_sort_key)
pretty = self._print_seq(items)
pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True))
return pretty
def _print_frozenset(self, s):
if not s:
return prettyForm('frozenset()')
items = sorted(s, key=default_sort_key)
pretty = self._print_seq(items)
pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True))
pretty = prettyForm(*pretty.parens('(', ')', ifascii_nougly=True))
pretty = prettyForm(*stringPict.next(type(s).__name__, pretty))
return pretty
def _print_UniversalSet(self, s):
if self._use_unicode:
return prettyForm("\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL U}")
else:
return prettyForm('UniversalSet')
def _print_PolyRing(self, ring):
return prettyForm(sstr(ring))
def _print_FracField(self, field):
return prettyForm(sstr(field))
def _print_FreeGroupElement(self, elm):
return prettyForm(str(elm))
def _print_PolyElement(self, poly):
return prettyForm(sstr(poly))
def _print_FracElement(self, frac):
return prettyForm(sstr(frac))
def _print_AlgebraicNumber(self, expr):
if expr.is_aliased:
return self._print(expr.as_poly().as_expr())
else:
return self._print(expr.as_expr())
def _print_ComplexRootOf(self, expr):
args = [self._print_Add(expr.expr, order='lex'), expr.index]
pform = prettyForm(*self._print_seq(args).parens())
pform = prettyForm(*pform.left('CRootOf'))
return pform
def _print_RootSum(self, expr):
args = [self._print_Add(expr.expr, order='lex')]
if expr.fun is not S.IdentityFunction:
args.append(self._print(expr.fun))
pform = prettyForm(*self._print_seq(args).parens())
pform = prettyForm(*pform.left('RootSum'))
return pform
def _print_FiniteField(self, expr):
if self._use_unicode:
form = '\N{DOUBLE-STRUCK CAPITAL Z}_%d'
else:
form = 'GF(%d)'
return prettyForm(pretty_symbol(form % expr.mod))
def _print_IntegerRing(self, expr):
if self._use_unicode:
return prettyForm('\N{DOUBLE-STRUCK CAPITAL Z}')
else:
return prettyForm('ZZ')
def _print_RationalField(self, expr):
if self._use_unicode:
return prettyForm('\N{DOUBLE-STRUCK CAPITAL Q}')
else:
return prettyForm('QQ')
def _print_RealField(self, domain):
if self._use_unicode:
prefix = '\N{DOUBLE-STRUCK CAPITAL R}'
else:
prefix = 'RR'
if domain.has_default_precision:
return prettyForm(prefix)
else:
return self._print(pretty_symbol(prefix + "_" + str(domain.precision)))
def _print_ComplexField(self, domain):
if self._use_unicode:
prefix = '\N{DOUBLE-STRUCK CAPITAL C}'
else:
prefix = 'CC'
if domain.has_default_precision:
return prettyForm(prefix)
else:
return self._print(pretty_symbol(prefix + "_" + str(domain.precision)))
def _print_PolynomialRing(self, expr):
args = list(expr.symbols)
if not expr.order.is_default:
order = prettyForm(*prettyForm("order=").right(self._print(expr.order)))
args.append(order)
pform = self._print_seq(args, '[', ']')
pform = prettyForm(*pform.left(self._print(expr.domain)))
return pform
def _print_FractionField(self, expr):
args = list(expr.symbols)
if not expr.order.is_default:
order = prettyForm(*prettyForm("order=").right(self._print(expr.order)))
args.append(order)
pform = self._print_seq(args, '(', ')')
pform = prettyForm(*pform.left(self._print(expr.domain)))
return pform
def _print_PolynomialRingBase(self, expr):
g = expr.symbols
if str(expr.order) != str(expr.default_order):
g = g + ("order=" + str(expr.order),)
pform = self._print_seq(g, '[', ']')
pform = prettyForm(*pform.left(self._print(expr.domain)))
return pform
def _print_GroebnerBasis(self, basis):
exprs = [ self._print_Add(arg, order=basis.order)
for arg in basis.exprs ]
exprs = prettyForm(*self.join(", ", exprs).parens(left="[", right="]"))
gens = [ self._print(gen) for gen in basis.gens ]
domain = prettyForm(
*prettyForm("domain=").right(self._print(basis.domain)))
order = prettyForm(
*prettyForm("order=").right(self._print(basis.order)))
pform = self.join(", ", [exprs] + gens + [domain, order])
pform = prettyForm(*pform.parens())
pform = prettyForm(*pform.left(basis.__class__.__name__))
return pform
def _print_Subs(self, e):
pform = self._print(e.expr)
pform = prettyForm(*pform.parens())
h = pform.height() if pform.height() > 1 else 2
rvert = stringPict(vobj('|', h), baseline=pform.baseline)
pform = prettyForm(*pform.right(rvert))
b = pform.baseline
pform.baseline = pform.height() - 1
pform = prettyForm(*pform.right(self._print_seq([
self._print_seq((self._print(v[0]), xsym('=='), self._print(v[1])),
delimiter='') for v in zip(e.variables, e.point) ])))
pform.baseline = b
return pform
def _print_number_function(self, e, name):
# Print name_arg[0] for one argument or name_arg[0](arg[1])
# for more than one argument
pform = prettyForm(name)
arg = self._print(e.args[0])
pform_arg = prettyForm(" "*arg.width())
pform_arg = prettyForm(*pform_arg.below(arg))
pform = prettyForm(*pform.right(pform_arg))
if len(e.args) == 1:
return pform
m, x = e.args
# TODO: copy-pasted from _print_Function: can we do better?
prettyFunc = pform
prettyArgs = prettyForm(*self._print_seq([x]).parens())
pform = prettyForm(
binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))
pform.prettyFunc = prettyFunc
pform.prettyArgs = prettyArgs
return pform
def _print_euler(self, e):
return self._print_number_function(e, "E")
def _print_catalan(self, e):
return self._print_number_function(e, "C")
def _print_bernoulli(self, e):
return self._print_number_function(e, "B")
_print_bell = _print_bernoulli
def _print_lucas(self, e):
return self._print_number_function(e, "L")
def _print_fibonacci(self, e):
return self._print_number_function(e, "F")
def _print_tribonacci(self, e):
return self._print_number_function(e, "T")
def _print_stieltjes(self, e):
if self._use_unicode:
return self._print_number_function(e, '\N{GREEK SMALL LETTER GAMMA}')
else:
return self._print_number_function(e, "stieltjes")
def _print_KroneckerDelta(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.right(prettyForm(',')))
pform = prettyForm(*pform.right(self._print(e.args[1])))
if self._use_unicode:
a = stringPict(pretty_symbol('delta'))
else:
a = stringPict('d')
b = pform
top = stringPict(*b.left(' '*a.width()))
bot = stringPict(*a.right(' '*b.width()))
return prettyForm(binding=prettyForm.POW, *bot.below(top))
def _print_RandomDomain(self, d):
if hasattr(d, 'as_boolean'):
pform = self._print('Domain: ')
pform = prettyForm(*pform.right(self._print(d.as_boolean())))
return pform
elif hasattr(d, 'set'):
pform = self._print('Domain: ')
pform = prettyForm(*pform.right(self._print(d.symbols)))
pform = prettyForm(*pform.right(self._print(' in ')))
pform = prettyForm(*pform.right(self._print(d.set)))
return pform
elif hasattr(d, 'symbols'):
pform = self._print('Domain on ')
pform = prettyForm(*pform.right(self._print(d.symbols)))
return pform
else:
return self._print(None)
def _print_DMP(self, p):
try:
if p.ring is not None:
# TODO incorporate order
return self._print(p.ring.to_sympy(p))
except SympifyError:
pass
return self._print(repr(p))
def _print_DMF(self, p):
return self._print_DMP(p)
def _print_Object(self, object):
return self._print(pretty_symbol(object.name))
def _print_Morphism(self, morphism):
arrow = xsym("-->")
domain = self._print(morphism.domain)
codomain = self._print(morphism.codomain)
tail = domain.right(arrow, codomain)[0]
return prettyForm(tail)
def _print_NamedMorphism(self, morphism):
pretty_name = self._print(pretty_symbol(morphism.name))
pretty_morphism = self._print_Morphism(morphism)
return prettyForm(pretty_name.right(":", pretty_morphism)[0])
def _print_IdentityMorphism(self, morphism):
from sympy.categories import NamedMorphism
return self._print_NamedMorphism(
NamedMorphism(morphism.domain, morphism.codomain, "id"))
def _print_CompositeMorphism(self, morphism):
circle = xsym(".")
# All components of the morphism have names and it is thus
# possible to build the name of the composite.
component_names_list = [pretty_symbol(component.name) for
component in morphism.components]
component_names_list.reverse()
component_names = circle.join(component_names_list) + ":"
pretty_name = self._print(component_names)
pretty_morphism = self._print_Morphism(morphism)
return prettyForm(pretty_name.right(pretty_morphism)[0])
def _print_Category(self, category):
return self._print(pretty_symbol(category.name))
def _print_Diagram(self, diagram):
if not diagram.premises:
# This is an empty diagram.
return self._print(S.EmptySet)
pretty_result = self._print(diagram.premises)
if diagram.conclusions:
results_arrow = " %s " % xsym("==>")
pretty_conclusions = self._print(diagram.conclusions)[0]
pretty_result = pretty_result.right(
results_arrow, pretty_conclusions)
return prettyForm(pretty_result[0])
def _print_DiagramGrid(self, grid):
from sympy.matrices import Matrix
from sympy import Symbol
matrix = Matrix([[grid[i, j] if grid[i, j] else Symbol(" ")
for j in range(grid.width)]
for i in range(grid.height)])
return self._print_matrix_contents(matrix)
def _print_FreeModuleElement(self, m):
# Print as row vector for convenience, for now.
return self._print_seq(m, '[', ']')
def _print_SubModule(self, M):
return self._print_seq(M.gens, '<', '>')
def _print_FreeModule(self, M):
return self._print(M.ring)**self._print(M.rank)
def _print_ModuleImplementedIdeal(self, M):
return self._print_seq([x for [x] in M._module.gens], '<', '>')
def _print_QuotientRing(self, R):
return self._print(R.ring) / self._print(R.base_ideal)
def _print_QuotientRingElement(self, R):
return self._print(R.data) + self._print(R.ring.base_ideal)
def _print_QuotientModuleElement(self, m):
return self._print(m.data) + self._print(m.module.killed_module)
def _print_QuotientModule(self, M):
return self._print(M.base) / self._print(M.killed_module)
def _print_MatrixHomomorphism(self, h):
matrix = self._print(h._sympy_matrix())
matrix.baseline = matrix.height() // 2
pform = prettyForm(*matrix.right(' : ', self._print(h.domain),
' %s> ' % hobj('-', 2), self._print(h.codomain)))
return pform
def _print_Manifold(self, manifold):
return self._print(manifold.name)
def _print_Patch(self, patch):
return self._print(patch.name)
def _print_CoordSystem(self, coords):
return self._print(coords.name)
def _print_BaseScalarField(self, field):
string = field._coord_sys.symbols[field._index].name
return self._print(pretty_symbol(string))
def _print_BaseVectorField(self, field):
s = U('PARTIAL DIFFERENTIAL') + '_' + field._coord_sys.symbols[field._index].name
return self._print(pretty_symbol(s))
def _print_Differential(self, diff):
field = diff._form_field
if hasattr(field, '_coord_sys'):
string = field._coord_sys.symbols[field._index].name
return self._print('\N{DOUBLE-STRUCK ITALIC SMALL D} ' + pretty_symbol(string))
else:
pform = self._print(field)
pform = prettyForm(*pform.parens())
return prettyForm(*pform.left("\N{DOUBLE-STRUCK ITALIC SMALL D}"))
def _print_Tr(self, p):
#TODO: Handle indices
pform = self._print(p.args[0])
pform = prettyForm(*pform.left('%s(' % (p.__class__.__name__)))
pform = prettyForm(*pform.right(')'))
return pform
def _print_primenu(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens())
if self._use_unicode:
pform = prettyForm(*pform.left(greek_unicode['nu']))
else:
pform = prettyForm(*pform.left('nu'))
return pform
def _print_primeomega(self, e):
pform = self._print(e.args[0])
pform = prettyForm(*pform.parens())
if self._use_unicode:
pform = prettyForm(*pform.left(greek_unicode['Omega']))
else:
pform = prettyForm(*pform.left('Omega'))
return pform
def _print_Quantity(self, e):
if e.name.name == 'degree':
pform = self._print("\N{DEGREE SIGN}")
return pform
else:
return self.emptyPrinter(e)
def _print_AssignmentBase(self, e):
op = prettyForm(' ' + xsym(e.op) + ' ')
l = self._print(e.lhs)
r = self._print(e.rhs)
pform = prettyForm(*stringPict.next(l, op, r))
return pform
def _print_Str(self, s):
return self._print(s.name)
@print_function(PrettyPrinter)
def pretty(expr, **settings):
"""Returns a string containing the prettified form of expr.
For information on keyword arguments see pretty_print function.
"""
pp = PrettyPrinter(settings)
# XXX: this is an ugly hack, but at least it works
use_unicode = pp._settings['use_unicode']
uflag = pretty_use_unicode(use_unicode)
try:
return pp.doprint(expr)
finally:
pretty_use_unicode(uflag)
def pretty_print(expr, **kwargs):
"""Prints expr in pretty form.
pprint is just a shortcut for this function.
Parameters
==========
expr : expression
The expression to print.
wrap_line : bool, optional (default=True)
Line wrapping enabled/disabled.
num_columns : int or None, optional (default=None)
Number of columns before line breaking (default to None which reads
the terminal width), useful when using SymPy without terminal.
use_unicode : bool or None, optional (default=None)
Use unicode characters, such as the Greek letter pi instead of
the string pi.
full_prec : bool or string, optional (default="auto")
Use full precision.
order : bool or string, optional (default=None)
Set to 'none' for long expressions if slow; default is None.
use_unicode_sqrt_char : bool, optional (default=True)
Use compact single-character square root symbol (when unambiguous).
root_notation : bool, optional (default=True)
Set to 'False' for printing exponents of the form 1/n in fractional form.
By default exponent is printed in root form.
mat_symbol_style : string, optional (default="plain")
Set to "bold" for printing MatrixSymbols using a bold mathematical symbol face.
By default the standard face is used.
imaginary_unit : string, optional (default="i")
Letter to use for imaginary unit when use_unicode is True.
Can be "i" (default) or "j".
"""
print(pretty(expr, **kwargs))
pprint = pretty_print
def pager_print(expr, **settings):
"""Prints expr using the pager, in pretty form.
This invokes a pager command using pydoc. Lines are not wrapped
automatically. This routine is meant to be used with a pager that allows
sideways scrolling, like ``less -S``.
Parameters are the same as for ``pretty_print``. If you wish to wrap lines,
pass ``num_columns=None`` to auto-detect the width of the terminal.
"""
from pydoc import pager
from locale import getpreferredencoding
if 'num_columns' not in settings:
settings['num_columns'] = 500000 # disable line wrap
pager(pretty(expr, **settings).encode(getpreferredencoding()))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.