hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
793ecd5b197aa5e1e6645ed5a59bc7d60b5181868b6f03bbfe8e625e7ed6d99b | from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import AppliedUndef, UndefinedFunction
from sympy.core.mul import Mul
from sympy.core.relational import Equality, Relational
from sympy.core.singleton import S
from sympy.core.symbol import Symbol, Dummy
from sympy.core.sympify import sympify
from sympy.functions.elementary.piecewise import (piecewise_fold,
Piecewise)
from sympy.logic.boolalg import BooleanFunction
from sympy.matrices.matrices import MatrixBase
from sympy.sets.sets import Interval, Set
from sympy.sets.fancysets import Range
from sympy.tensor.indexed import Idx
from sympy.utilities import flatten
from sympy.utilities.iterables import sift, is_sequence
from sympy.utilities.exceptions import sympy_deprecation_warning
def _common_new(cls, function, *symbols, discrete, **assumptions):
"""Return either a special return value or the tuple,
(function, limits, orientation). This code is common to
both ExprWithLimits and AddWithLimits."""
function = sympify(function)
if isinstance(function, Equality):
# This transforms e.g. Integral(Eq(x, y)) to Eq(Integral(x), Integral(y))
# but that is only valid for definite integrals.
limits, orientation = _process_limits(*symbols, discrete=discrete)
if not (limits and all(len(limit) == 3 for limit in limits)):
sympy_deprecation_warning(
"""
Creating a indefinite integral with an Eq() argument is
deprecated.
This is because indefinite integrals do not preserve equality
due to the arbitrary constants. If you want an equality of
indefinite integrals, use Eq(Integral(a, x), Integral(b, x))
explicitly.
""",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-indefinite-integral-eq",
stacklevel=5,
)
lhs = function.lhs
rhs = function.rhs
return Equality(cls(lhs, *symbols, **assumptions), \
cls(rhs, *symbols, **assumptions))
if function is S.NaN:
return S.NaN
if symbols:
limits, orientation = _process_limits(*symbols, discrete=discrete)
for i, li in enumerate(limits):
if len(li) == 4:
function = function.subs(li[0], li[-1])
limits[i] = Tuple(*li[:-1])
else:
# symbol not provided -- we can still try to compute a general form
free = function.free_symbols
if len(free) != 1:
raise ValueError(
"specify dummy variables for %s" % function)
limits, orientation = [Tuple(s) for s in free], 1
# denest any nested calls
while cls == type(function):
limits = list(function.limits) + limits
function = function.function
# Any embedded piecewise functions need to be brought out to the
# top level. We only fold Piecewise that contain the integration
# variable.
reps = {}
symbols_of_integration = {i[0] for i in limits}
for p in function.atoms(Piecewise):
if not p.has(*symbols_of_integration):
reps[p] = Dummy()
# mask off those that don't
function = function.xreplace(reps)
# do the fold
function = piecewise_fold(function)
# remove the masking
function = function.xreplace({v: k for k, v in reps.items()})
return function, limits, orientation
def _process_limits(*symbols, discrete=None):
"""Process the list of symbols and convert them to canonical limits,
storing them as Tuple(symbol, lower, upper). The orientation of
the function is also returned when the upper limit is missing
so (x, 1, None) becomes (x, None, 1) and the orientation is changed.
In the case that a limit is specified as (symbol, Range), a list of
length 4 may be returned if a change of variables is needed; the
expression that should replace the symbol in the expression is
the fourth element in the list.
"""
limits = []
orientation = 1
if discrete is None:
err_msg = 'discrete must be True or False'
elif discrete:
err_msg = 'use Range, not Interval or Relational'
else:
err_msg = 'use Interval or Relational, not Range'
for V in symbols:
if isinstance(V, (Relational, BooleanFunction)):
if discrete:
raise TypeError(err_msg)
variable = V.atoms(Symbol).pop()
V = (variable, V.as_set())
elif isinstance(V, Symbol) or getattr(V, '_diff_wrt', False):
if isinstance(V, Idx):
if V.lower is None or V.upper is None:
limits.append(Tuple(V))
else:
limits.append(Tuple(V, V.lower, V.upper))
else:
limits.append(Tuple(V))
continue
if is_sequence(V) and not isinstance(V, Set):
if len(V) == 2 and isinstance(V[1], Set):
V = list(V)
if isinstance(V[1], Interval): # includes Reals
if discrete:
raise TypeError(err_msg)
V[1:] = V[1].inf, V[1].sup
elif isinstance(V[1], Range):
if not discrete:
raise TypeError(err_msg)
lo = V[1].inf
hi = V[1].sup
dx = abs(V[1].step) # direction doesn't matter
if dx == 1:
V[1:] = [lo, hi]
else:
if lo is not S.NegativeInfinity:
V = [V[0]] + [0, (hi - lo)//dx, dx*V[0] + lo]
else:
V = [V[0]] + [0, S.Infinity, -dx*V[0] + hi]
else:
# more complicated sets would require splitting, e.g.
# Union(Interval(1, 3), interval(6,10))
raise NotImplementedError(
'expecting Range' if discrete else
'Relational or single Interval' )
V = sympify(flatten(V)) # list of sympified elements/None
if isinstance(V[0], (Symbol, Idx)) or getattr(V[0], '_diff_wrt', False):
newsymbol = V[0]
if len(V) == 3:
# general case
if V[2] is None and V[1] is not None:
orientation *= -1
V = [newsymbol] + [i for i in V[1:] if i is not None]
lenV = len(V)
if not isinstance(newsymbol, Idx) or lenV == 3:
if lenV == 4:
limits.append(Tuple(*V))
continue
if lenV == 3:
if isinstance(newsymbol, Idx):
# Idx represents an integer which may have
# specified values it can take on; if it is
# given such a value, an error is raised here
# if the summation would try to give it a larger
# or smaller value than permitted. None and Symbolic
# values will not raise an error.
lo, hi = newsymbol.lower, newsymbol.upper
try:
if lo is not None and not bool(V[1] >= lo):
raise ValueError("Summation will set Idx value too low.")
except TypeError:
pass
try:
if hi is not None and not bool(V[2] <= hi):
raise ValueError("Summation will set Idx value too high.")
except TypeError:
pass
limits.append(Tuple(*V))
continue
if lenV == 1 or (lenV == 2 and V[1] is None):
limits.append(Tuple(newsymbol))
continue
elif lenV == 2:
limits.append(Tuple(newsymbol, V[1]))
continue
raise ValueError('Invalid limits given: %s' % str(symbols))
return limits, orientation
class ExprWithLimits(Expr):
__slots__ = ('is_commutative',)
def __new__(cls, function, *symbols, **assumptions):
from sympy.concrete.products import Product
pre = _common_new(cls, function, *symbols,
discrete=issubclass(cls, Product), **assumptions)
if isinstance(pre, tuple):
function, limits, _ = pre
else:
return pre
# limits must have upper and lower bounds; the indefinite form
# is not supported. This restriction does not apply to AddWithLimits
if any(len(l) != 3 or None in l for l in limits):
raise ValueError('ExprWithLimits requires values for lower and upper bounds.')
obj = Expr.__new__(cls, **assumptions)
arglist = [function]
arglist.extend(limits)
obj._args = tuple(arglist)
obj.is_commutative = function.is_commutative # limits already checked
return obj
@property
def function(self):
"""Return the function applied across limits.
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x
>>> Integral(x**2, (x,)).function
x**2
See Also
========
limits, variables, free_symbols
"""
return self._args[0]
@property
def kind(self):
return self.function.kind
@property
def limits(self):
"""Return the limits of expression.
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x, i
>>> Integral(x**i, (i, 1, 3)).limits
((i, 1, 3),)
See Also
========
function, variables, free_symbols
"""
return self._args[1:]
@property
def variables(self):
"""Return a list of the limit variables.
>>> from sympy import Sum
>>> from sympy.abc import x, i
>>> Sum(x**i, (i, 1, 3)).variables
[i]
See Also
========
function, limits, free_symbols
as_dummy : Rename dummy variables
sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable
"""
return [l[0] for l in self.limits]
@property
def bound_symbols(self):
"""Return only variables that are dummy variables.
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x, i, j, k
>>> Integral(x**i, (i, 1, 3), (j, 2), k).bound_symbols
[i, j]
See Also
========
function, limits, free_symbols
as_dummy : Rename dummy variables
sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable
"""
return [l[0] for l in self.limits if len(l) != 1]
@property
def free_symbols(self):
"""
This method returns the symbols in the object, excluding those
that take on a specific value (i.e. the dummy symbols).
Examples
========
>>> from sympy import Sum
>>> from sympy.abc import x, y
>>> Sum(x, (x, y, 1)).free_symbols
{y}
"""
# don't test for any special values -- nominal free symbols
# should be returned, e.g. don't return set() if the
# function is zero -- treat it like an unevaluated expression.
function, limits = self.function, self.limits
# mask off non-symbol integration variables that have
# more than themself as a free symbol
reps = {i[0]: i[0] if i[0].free_symbols == {i[0]} else Dummy()
for i in self.limits}
function = function.xreplace(reps)
isyms = function.free_symbols
for xab in limits:
v = reps[xab[0]]
if len(xab) == 1:
isyms.add(v)
continue
# take out the target symbol
if v in isyms:
isyms.remove(v)
# add in the new symbols
for i in xab[1:]:
isyms.update(i.free_symbols)
reps = {v: k for k, v in reps.items()}
return set([reps.get(_, _) for _ in isyms])
@property
def is_number(self):
"""Return True if the Sum has no free symbols, else False."""
return not self.free_symbols
def _eval_interval(self, x, a, b):
limits = [(i if i[0] != x else (x, a, b)) for i in self.limits]
integrand = self.function
return self.func(integrand, *limits)
def _eval_subs(self, old, new):
"""
Perform substitutions over non-dummy variables
of an expression with limits. Also, can be used
to specify point-evaluation of an abstract antiderivative.
Examples
========
>>> from sympy import Sum, oo
>>> from sympy.abc import s, n
>>> Sum(1/n**s, (n, 1, oo)).subs(s, 2)
Sum(n**(-2), (n, 1, oo))
>>> from sympy import Integral
>>> from sympy.abc import x, a
>>> Integral(a*x**2, x).subs(x, 4)
Integral(a*x**2, (x, 4))
See Also
========
variables : Lists the integration variables
transform : Perform mapping on the dummy variable for integrals
change_index : Perform mapping on the sum and product dummy variables
"""
func, limits = self.function, list(self.limits)
# If one of the expressions we are replacing is used as a func index
# one of two things happens.
# - the old variable first appears as a free variable
# so we perform all free substitutions before it becomes
# a func index.
# - the old variable first appears as a func index, in
# which case we ignore. See change_index.
# Reorder limits to match standard mathematical practice for scoping
limits.reverse()
if not isinstance(old, Symbol) or \
old.free_symbols.intersection(self.free_symbols):
sub_into_func = True
for i, xab in enumerate(limits):
if 1 == len(xab) and old == xab[0]:
if new._diff_wrt:
xab = (new,)
else:
xab = (old, old)
limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]])
if len(xab[0].free_symbols.intersection(old.free_symbols)) != 0:
sub_into_func = False
break
if isinstance(old, (AppliedUndef, UndefinedFunction)):
sy2 = set(self.variables).intersection(set(new.atoms(Symbol)))
sy1 = set(self.variables).intersection(set(old.args))
if not sy2.issubset(sy1):
raise ValueError(
"substitution cannot create dummy dependencies")
sub_into_func = True
if sub_into_func:
func = func.subs(old, new)
else:
# old is a Symbol and a dummy variable of some limit
for i, xab in enumerate(limits):
if len(xab) == 3:
limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]])
if old == xab[0]:
break
# simplify redundant limits (x, x) to (x, )
for i, xab in enumerate(limits):
if len(xab) == 2 and (xab[0] - xab[1]).is_zero:
limits[i] = Tuple(xab[0], )
# Reorder limits back to representation-form
limits.reverse()
return self.func(func, *limits)
@property
def has_finite_limits(self):
"""
Returns True if the limits are known to be finite, either by the
explicit bounds, assumptions on the bounds, or assumptions on the
variables. False if known to be infinite, based on the bounds.
None if not enough information is available to determine.
Examples
========
>>> from sympy import Sum, Integral, Product, oo, Symbol
>>> x = Symbol('x')
>>> Sum(x, (x, 1, 8)).has_finite_limits
True
>>> Integral(x, (x, 1, oo)).has_finite_limits
False
>>> M = Symbol('M')
>>> Sum(x, (x, 1, M)).has_finite_limits
>>> N = Symbol('N', integer=True)
>>> Product(x, (x, 1, N)).has_finite_limits
True
See Also
========
has_reversed_limits
"""
ret_None = False
for lim in self.limits:
if len(lim) == 3:
if any(l.is_infinite for l in lim[1:]):
# Any of the bounds are +/-oo
return False
elif any(l.is_infinite is None for l in lim[1:]):
# Maybe there are assumptions on the variable?
if lim[0].is_infinite is None:
ret_None = True
else:
if lim[0].is_infinite is None:
ret_None = True
if ret_None:
return None
return True
@property
def has_reversed_limits(self):
"""
Returns True if the limits are known to be in reversed order, either
by the explicit bounds, assumptions on the bounds, or assumptions on the
variables. False if known to be in normal order, based on the bounds.
None if not enough information is available to determine.
Examples
========
>>> from sympy import Sum, Integral, Product, oo, Symbol
>>> x = Symbol('x')
>>> Sum(x, (x, 8, 1)).has_reversed_limits
True
>>> Sum(x, (x, 1, oo)).has_reversed_limits
False
>>> M = Symbol('M')
>>> Integral(x, (x, 1, M)).has_reversed_limits
>>> N = Symbol('N', integer=True, positive=True)
>>> Sum(x, (x, 1, N)).has_reversed_limits
False
>>> Product(x, (x, 2, N)).has_reversed_limits
>>> Product(x, (x, 2, N)).subs(N, N + 2).has_reversed_limits
False
See Also
========
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.has_empty_sequence
"""
ret_None = False
for lim in self.limits:
if len(lim) == 3:
var, a, b = lim
dif = b - a
if dif.is_extended_negative:
return True
elif dif.is_extended_nonnegative:
continue
else:
ret_None = True
else:
return None
if ret_None:
return None
return False
class AddWithLimits(ExprWithLimits):
r"""Represents unevaluated oriented additions.
Parent class for Integral and Sum.
"""
__slots__ = ()
def __new__(cls, function, *symbols, **assumptions):
from sympy.concrete.summations import Sum
pre = _common_new(cls, function, *symbols,
discrete=issubclass(cls, Sum), **assumptions)
if isinstance(pre, tuple):
function, limits, orientation = pre
else:
return pre
obj = Expr.__new__(cls, **assumptions)
arglist = [orientation*function] # orientation not used in ExprWithLimits
arglist.extend(limits)
obj._args = tuple(arglist)
obj.is_commutative = function.is_commutative # limits already checked
return obj
def _eval_adjoint(self):
if all(x.is_real for x in flatten(self.limits)):
return self.func(self.function.adjoint(), *self.limits)
return None
def _eval_conjugate(self):
if all(x.is_real for x in flatten(self.limits)):
return self.func(self.function.conjugate(), *self.limits)
return None
def _eval_transpose(self):
if all(x.is_real for x in flatten(self.limits)):
return self.func(self.function.transpose(), *self.limits)
return None
def _eval_factor(self, **hints):
if 1 == len(self.limits):
summand = self.function.factor(**hints)
if summand.is_Mul:
out = sift(summand.args, lambda w: w.is_commutative \
and not set(self.variables) & w.free_symbols)
return Mul(*out[True])*self.func(Mul(*out[False]), \
*self.limits)
else:
summand = self.func(self.function, *self.limits[0:-1]).factor()
if not summand.has(self.variables[-1]):
return self.func(1, [self.limits[-1]]).doit()*summand
elif isinstance(summand, Mul):
return self.func(summand, self.limits[-1]).factor()
return self
def _eval_expand_basic(self, **hints):
summand = self.function.expand(**hints)
if summand.is_Add and summand.is_commutative:
return Add(*[self.func(i, *self.limits) for i in summand.args])
elif isinstance(summand, MatrixBase):
return summand.applyfunc(lambda x: self.func(x, *self.limits))
elif summand != self.function:
return self.func(summand, *self.limits)
return self
|
d4999f8132ab57d9ac72bd631d8c4713536406be7f52acea4784da7d86c497c7 | from typing import Tuple as tTuple
from sympy.calculus.singularities import is_decreasing
from sympy.calculus.accumulationbounds import AccumulationBounds
from .expr_with_intlimits import ExprWithIntLimits
from .expr_with_limits import AddWithLimits
from .gosper import gosper_sum
from sympy.core.expr import Expr
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.function import Derivative, expand
from sympy.core.mul import Mul
from sympy.core.numbers import Float, _illegal
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.sorting import ordered
from sympy.core.symbol import Dummy, Wild, Symbol, symbols
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.combinatorial.numbers import bernoulli, harmonic
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import cot, csc
from sympy.functions.special.hyper import hyper
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.functions.special.zeta_functions import zeta
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import And
from sympy.polys.partfrac import apart
from sympy.polys.polyerrors import PolynomialError, PolificationFailed
from sympy.polys.polytools import parallel_poly_from_expr, Poly, factor
from sympy.polys.rationaltools import together
from sympy.series.limitseq import limit_seq
from sympy.series.order import O
from sympy.series.residues import residue
from sympy.sets.sets import FiniteSet, Interval
from sympy.utilities.iterables import sift
import itertools
class Sum(AddWithLimits, ExprWithIntLimits):
r"""
Represents unevaluated summation.
Explanation
===========
``Sum`` represents a finite or infinite series, 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
summation.
Finite sums
===========
For finite sums (and sums with symbolic limits assumed to be finite) we
follow the summation convention described by Karr [1], especially
definition 3 of section 1.4. The sum:
.. math::
\sum_{m \leq i < n} f(i)
has *the obvious meaning* for `m < n`, namely:
.. math::
\sum_{m \leq i < n} f(i) = f(m) + f(m+1) + \ldots + f(n-2) + f(n-1)
with the upper limit value `f(n)` excluded. The sum over an empty set is
zero if and only if `m = n`:
.. math::
\sum_{m \leq i < n} f(i) = 0 \quad \mathrm{for} \quad m = n
Finally, for all other sums over empty sets we assume the following
definition:
.. math::
\sum_{m \leq i < n} f(i) = - \sum_{n \leq i < m} f(i) \quad \mathrm{for} \quad m > n
It is important to note that Karr defines all sums with the upper
limit being exclusive. This is in contrast to the usual mathematical notation,
but does not affect the summation convention. Indeed we have:
.. math::
\sum_{m \leq i < n} f(i) = \sum_{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 i, k, m, n, x
>>> from sympy import Sum, factorial, oo, IndexedBase, Function
>>> Sum(k, (k, 1, m))
Sum(k, (k, 1, m))
>>> Sum(k, (k, 1, m)).doit()
m**2/2 + m/2
>>> Sum(k**2, (k, 1, m))
Sum(k**2, (k, 1, m))
>>> Sum(k**2, (k, 1, m)).doit()
m**3/3 + m**2/2 + m/6
>>> Sum(x**k, (k, 0, oo))
Sum(x**k, (k, 0, oo))
>>> Sum(x**k, (k, 0, oo)).doit()
Piecewise((1/(1 - x), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True))
>>> Sum(x**k/factorial(k), (k, 0, oo)).doit()
exp(x)
Here are examples to do summation with symbolic indices. You
can use either Function of IndexedBase classes:
>>> f = Function('f')
>>> Sum(f(n), (n, 0, 3)).doit()
f(0) + f(1) + f(2) + f(3)
>>> Sum(f(n), (n, 0, oo)).doit()
Sum(f(n), (n, 0, oo))
>>> f = IndexedBase('f')
>>> Sum(f[n]**2, (n, 0, 3)).doit()
f[0]**2 + f[1]**2 + f[2]**2 + f[3]**2
An example showing that the symbolic result of a summation is still
valid for seemingly nonsensical values of the limits. Then the Karr
convention allows us to give a perfectly valid interpretation to
those sums by interchanging the limits according to the above rules:
>>> S = Sum(i, (i, 1, n)).doit()
>>> S
n**2/2 + n/2
>>> S.subs(n, -4)
6
>>> Sum(i, (i, 1, -4)).doit()
6
>>> Sum(-i, (i, -3, 0)).doit()
6
An explicit example of the Karr summation convention:
>>> S1 = Sum(i**2, (i, m, m+n-1)).doit()
>>> S1
m**2*n + m*n**2 - m*n + n**3/3 - n**2/2 + n/6
>>> S2 = Sum(i**2, (i, m+n, m-1)).doit()
>>> S2
-m**2*n - m*n**2 + m*n - n**3/3 + n**2/2 - n/6
>>> S1 + S2
0
>>> S3 = Sum(i, (i, m, m-1)).doit()
>>> S3
0
See Also
========
summation
Product, sympy.concrete.products.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/Summation#Capital-sigma_notation
.. [3] https://en.wikipedia.org/wiki/Empty_sum
"""
__slots__ = ()
limits: tTuple[tTuple[Symbol, Expr, Expr]]
def __new__(cls, function, *symbols, **assumptions):
obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
if not hasattr(obj, 'limits'):
return obj
if any(len(l) != 3 or None in l for l in obj.limits):
raise ValueError('Sum requires values for lower and upper bounds.')
return obj
def _eval_is_zero(self):
# a Sum is only zero if its function is zero or if all terms
# cancel out. This only answers whether the summand is zero; if
# not then None is returned since we don't analyze whether all
# terms cancel out.
if self.function.is_zero or self.has_empty_sequence:
return True
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_finite_limits and self.has_reversed_limits is False:
return self.function.is_positive
def _eval_is_negative(self):
if self.has_finite_limits and self.has_reversed_limits is False:
return self.function.is_negative
def _eval_is_finite(self):
if self.has_finite_limits and self.function.is_finite:
return True
def doit(self, **hints):
if hints.get('deep', True):
f = self.function.doit(**hints)
else:
f = self.function
# first make sure any definite limits have summation
# variables with matching assumptions
reps = {}
for xab in self.limits:
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 isinstance(did, tuple): # when separate=True
did = tuple([i.xreplace(undo) for i in did])
elif did is not None:
did = did.xreplace(undo)
else:
did = self
return did
if self.function.is_Matrix:
expanded = self.expand()
if self != expanded:
return expanded.doit()
return _eval_matrix_sum(self)
for n, limit in enumerate(self.limits):
i, a, b = limit
dif = b - a
if dif == -1:
# Any summation over an empty set is zero
return S.Zero
if dif.is_integer and dif.is_negative:
a, b = b + 1, a - 1
f = -f
newf = eval_sum(f, (i, a, b))
if newf is None:
if f == self.function:
zeta_function = self.eval_zeta_function(f, (i, a, b))
if zeta_function is not None:
return zeta_function
return self
else:
return self.func(f, *self.limits[n:])
f = newf
if hints.get('deep', True):
# eval_sum could return partially unevaluated
# result with Piecewise. In this case we won't
# doit() recursively.
if not isinstance(f, Piecewise):
return f.doit(**hints)
return f
def eval_zeta_function(self, f, limits):
"""
Check whether the function matches with the zeta function.
If it matches, then return a `Piecewise` expression because
zeta function does not converge unless `s > 1` and `q > 0`
"""
i, a, b = limits
w, y, z = Wild('w', exclude=[i]), Wild('y', exclude=[i]), Wild('z', exclude=[i])
result = f.match((w * i + y) ** (-z))
if result is not None and b is S.Infinity:
coeff = 1 / result[w] ** result[z]
s = result[z]
q = result[y] / result[w] + a
return Piecewise((coeff * zeta(s, q), And(q > 0, s > 1)), (self, True))
def _eval_derivative(self, x):
"""
Differentiate wrt x as long as x is not in the free symbols of any of
the upper or lower limits.
Explanation
===========
Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a`
since the value of the sum is discontinuous in `a`. In a case
involving a limit variable, the unevaluated derivative is returned.
"""
# diff already confirmed that x is in the free symbols of self, but we
# don't want to differentiate wrt any free symbol in the upper or lower
# limits
# XXX remove this test for free_symbols when the default _eval_derivative is in
if isinstance(x, Symbol) and x not in self.free_symbols:
return S.Zero
# get limits and the function
f, limits = self.function, list(self.limits)
limit = limits.pop(-1)
if limits: # f is the argument to a Sum
f = self.func(f, *limits)
_, a, b = limit
if x in a.free_symbols or x in b.free_symbols:
return None
df = Derivative(f, x, evaluate=True)
rv = self.func(df, limit)
return rv
def _eval_difference_delta(self, n, step):
k, _, upper = self.args[-1]
new_upper = upper.subs(n, n + step)
if len(self.args) == 2:
f = self.args[0]
else:
f = self.func(*self.args[:-1])
return Sum(f, (k, upper + 1, new_upper)).doit()
def _eval_simplify(self, **kwargs):
# split the function into adds
terms = Add.make_args(expand(self.function))
s_t = [] # Sum Terms
o_t = [] # Other Terms
for term in terms:
if term.has(Sum):
# if there is an embedded sum here
# it is of the form x * (Sum(whatever))
# hence we make a Mul out of it, and simplify all interior sum terms
subterms = Mul.make_args(expand(term))
out_terms = []
for subterm in subterms:
# go through each term
if isinstance(subterm, Sum):
# if it's a sum, simplify it
out_terms.append(subterm._eval_simplify())
else:
# otherwise, add it as is
out_terms.append(subterm)
# turn it back into a Mul
s_t.append(Mul(*out_terms))
else:
o_t.append(term)
# next try to combine any interior sums for further simplification
from sympy.simplify.simplify import factor_sum, sum_combine
result = Add(sum_combine(s_t), *o_t)
return factor_sum(result, limits=self.limits)
def is_convergent(self):
r"""
Checks for the convergence of a Sum.
Explanation
===========
We divide the study of convergence of infinite sums and products in
two parts.
First Part:
One part is the question whether all the terms are well defined, i.e.,
they are finite in a sum and also non-zero in a product. Zero
is the analogy of (minus) infinity in products as
:math:`e^{-\infty} = 0`.
Second Part:
The second part is the question of convergence after infinities,
and zeros in products, have been omitted assuming that their number
is finite. This means that we only consider the tail of the sum or
product, starting from some point after which all terms are well
defined.
For example, in a sum of the form:
.. math::
\sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b}
where a and b are numbers. The routine will return true, even if there
are infinities in the term sequence (at most two). An analogous
product would be:
.. math::
\prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}}
This is how convergence is interpreted. It is concerned with what
happens at the limit. Finding the bad terms is another independent
matter.
Note: It is responsibility of user to see that the sum or product
is well defined.
There are various tests employed to check the convergence like
divergence test, root test, integral test, alternating series test,
comparison tests, Dirichlet tests. It returns true if Sum is convergent
and false if divergent and NotImplementedError if it cannot be checked.
References
==========
.. [1] https://en.wikipedia.org/wiki/Convergence_tests
Examples
========
>>> from sympy import factorial, S, Sum, Symbol, oo
>>> n = Symbol('n', integer=True)
>>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
True
>>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
False
>>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
False
>>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
True
See Also
========
Sum.is_absolutely_convergent()
sympy.concrete.products.Product.is_convergent()
"""
p, q, r = symbols('p q r', cls=Wild)
sym = self.limits[0][0]
lower_limit = self.limits[0][1]
upper_limit = self.limits[0][2]
sequence_term = self.function.simplify()
if len(sequence_term.free_symbols) > 1:
raise NotImplementedError("convergence checking for more than one symbol "
"containing series is not handled")
if lower_limit.is_finite and upper_limit.is_finite:
return S.true
# transform sym -> -sym and swap the upper_limit = S.Infinity
# and lower_limit = - upper_limit
if lower_limit is S.NegativeInfinity:
if upper_limit is S.Infinity:
return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
from sympy.simplify.simplify import simplify
sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
lower_limit = -upper_limit
upper_limit = S.Infinity
sym_ = Dummy(sym.name, integer=True, positive=True)
sequence_term = sequence_term.xreplace({sym: sym_})
sym = sym_
interval = Interval(lower_limit, upper_limit)
# Piecewise function handle
if sequence_term.is_Piecewise:
for func, cond in sequence_term.args:
# see if it represents something going to oo
if cond == True or cond.as_set().sup is S.Infinity:
s = Sum(func, (sym, lower_limit, upper_limit))
return s.is_convergent()
return S.true
### -------- Divergence test ----------- ###
try:
lim_val = limit_seq(sequence_term, sym)
if lim_val is not None and lim_val.is_zero is False:
return S.false
except NotImplementedError:
pass
try:
lim_val_abs = limit_seq(abs(sequence_term), sym)
if lim_val_abs is not None and lim_val_abs.is_zero is False:
return S.false
except NotImplementedError:
pass
order = O(sequence_term, (sym, S.Infinity))
### --------- p-series test (1/n**p) ---------- ###
p_series_test = order.expr.match(sym**p)
if p_series_test is not None:
if p_series_test[p] < -1:
return S.true
if p_series_test[p] >= -1:
return S.false
### ------------- comparison test ------------- ###
# 1/(n**p*log(n)**q*log(log(n))**r) comparison
n_log_test = order.expr.match(1/(sym**p*log(sym)**q*log(log(sym))**r))
if n_log_test is not None:
if (n_log_test[p] > 1 or
(n_log_test[p] == 1 and n_log_test[q] > 1) or
(n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)):
return S.true
return S.false
### ------------- Limit comparison test -----------###
# (1/n) comparison
try:
lim_comp = limit_seq(sym*sequence_term, sym)
if lim_comp is not None and lim_comp.is_number and lim_comp > 0:
return S.false
except NotImplementedError:
pass
### ----------- ratio test ---------------- ###
next_sequence_term = sequence_term.xreplace({sym: sym + 1})
from sympy.simplify.combsimp import combsimp
from sympy.simplify.powsimp import powsimp
ratio = combsimp(powsimp(next_sequence_term/sequence_term))
try:
lim_ratio = limit_seq(ratio, sym)
if lim_ratio is not None and lim_ratio.is_number:
if abs(lim_ratio) > 1:
return S.false
if abs(lim_ratio) < 1:
return S.true
except NotImplementedError:
lim_ratio = None
### ---------- Raabe's test -------------- ###
if lim_ratio == 1: # ratio test inconclusive
test_val = sym*(sequence_term/
sequence_term.subs(sym, sym + 1) - 1)
test_val = test_val.gammasimp()
try:
lim_val = limit_seq(test_val, sym)
if lim_val is not None and lim_val.is_number:
if lim_val > 1:
return S.true
if lim_val < 1:
return S.false
except NotImplementedError:
pass
### ----------- root test ---------------- ###
# lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity)
try:
lim_evaluated = limit_seq(abs(sequence_term)**(1/sym), sym)
if lim_evaluated is not None and lim_evaluated.is_number:
if lim_evaluated < 1:
return S.true
if lim_evaluated > 1:
return S.false
except NotImplementedError:
pass
### ------------- alternating series test ----------- ###
dict_val = sequence_term.match(S.NegativeOne**(sym + p)*q)
if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
return S.true
### ------------- integral test -------------- ###
check_interval = None
from sympy.solvers.solveset import solveset
maxima = solveset(sequence_term.diff(sym), sym, interval)
if not maxima:
check_interval = interval
elif isinstance(maxima, FiniteSet) and maxima.sup.is_number:
check_interval = Interval(maxima.sup, interval.sup)
if (check_interval is not None and
(is_decreasing(sequence_term, check_interval) or
is_decreasing(-sequence_term, check_interval))):
integral_val = Integral(
sequence_term, (sym, lower_limit, upper_limit))
try:
integral_val_evaluated = integral_val.doit()
if integral_val_evaluated.is_number:
return S(integral_val_evaluated.is_finite)
except NotImplementedError:
pass
### ----- Dirichlet and bounded times convergent tests ----- ###
# TODO
#
# Dirichlet_test
# https://en.wikipedia.org/wiki/Dirichlet%27s_test
#
# Bounded times convergent test
# It is based on comparison theorems for series.
# In particular, if the general term of a series can
# be written as a product of two terms a_n and b_n
# and if a_n is bounded and if Sum(b_n) is absolutely
# convergent, then the original series Sum(a_n * b_n)
# is absolutely convergent and so convergent.
#
# The following code can grows like 2**n where n is the
# number of args in order.expr
# Possibly combined with the potentially slow checks
# inside the loop, could make this test extremely slow
# for larger summation expressions.
if order.expr.is_Mul:
args = order.expr.args
argset = set(args)
### -------------- Dirichlet tests -------------- ###
m = Dummy('m', integer=True)
def _dirichlet_test(g_n):
try:
ing_val = limit_seq(Sum(g_n, (sym, interval.inf, m)).doit(), m)
if ing_val is not None and ing_val.is_finite:
return S.true
except NotImplementedError:
pass
### -------- bounded times convergent test ---------###
def _bounded_convergent_test(g1_n, g2_n):
try:
lim_val = limit_seq(g1_n, sym)
if lim_val is not None and (lim_val.is_finite or (
isinstance(lim_val, AccumulationBounds)
and (lim_val.max - lim_val.min).is_finite)):
if Sum(g2_n, (sym, lower_limit, upper_limit)).is_absolutely_convergent():
return S.true
except NotImplementedError:
pass
for n in range(1, len(argset)):
for a_tuple in itertools.combinations(args, n):
b_set = argset - set(a_tuple)
a_n = Mul(*a_tuple)
b_n = Mul(*b_set)
if is_decreasing(a_n, interval):
dirich = _dirichlet_test(b_n)
if dirich is not None:
return dirich
bc_test = _bounded_convergent_test(a_n, b_n)
if bc_test is not None:
return bc_test
_sym = self.limits[0][0]
sequence_term = sequence_term.xreplace({sym: _sym})
raise NotImplementedError("The algorithm to find the Sum convergence of %s "
"is not yet implemented" % (sequence_term))
def is_absolutely_convergent(self):
"""
Checks for the absolute convergence of an infinite series.
Same as checking convergence of absolute value of sequence_term of
an infinite series.
References
==========
.. [1] https://en.wikipedia.org/wiki/Absolute_convergence
Examples
========
>>> from sympy import Sum, Symbol, oo
>>> n = Symbol('n', integer=True)
>>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent()
False
>>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent()
True
See Also
========
Sum.is_convergent()
"""
return Sum(abs(self.function), self.limits).is_convergent()
def euler_maclaurin(self, m=0, n=0, eps=0, eval_integral=True):
"""
Return an Euler-Maclaurin approximation of self, where m is the
number of leading terms to sum directly and n is the number of
terms in the tail.
With m = n = 0, this is simply the corresponding integral
plus a first-order endpoint correction.
Returns (s, e) where s is the Euler-Maclaurin approximation
and e is the estimated error (taken to be the magnitude of
the first omitted term in the tail):
>>> from sympy.abc import k, a, b
>>> from sympy import Sum
>>> Sum(1/k, (k, 2, 5)).doit().evalf()
1.28333333333333
>>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin()
>>> s
-log(2) + 7/20 + log(5)
>>> from sympy import sstr
>>> print(sstr((s.evalf(), e.evalf()), full_prec=True))
(1.26629073187415, 0.0175000000000000)
The endpoints may be symbolic:
>>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin()
>>> s
-log(a) + log(b) + 1/(2*b) + 1/(2*a)
>>> e
Abs(1/(12*b**2) - 1/(12*a**2))
If the function is a polynomial of degree at most 2n+1, the
Euler-Maclaurin formula becomes exact (and e = 0 is returned):
>>> Sum(k, (k, 2, b)).euler_maclaurin()
(b**2/2 + b/2 - 1, 0)
>>> Sum(k, (k, 2, b)).doit()
b**2/2 + b/2 - 1
With a nonzero eps specified, the summation is ended
as soon as the remainder term is less than the epsilon.
"""
m = int(m)
n = int(n)
f = self.function
if len(self.limits) != 1:
raise ValueError("More than 1 limit")
i, a, b = self.limits[0]
if (a > b) == True:
if a - b == 1:
return S.Zero, S.Zero
a, b = b + 1, a - 1
f = -f
s = S.Zero
if m:
if b.is_Integer and a.is_Integer:
m = min(m, b - a + 1)
if not eps or f.is_polynomial(i):
for k in range(m):
s += f.subs(i, a + k)
else:
term = f.subs(i, a)
if term:
test = abs(term.evalf(3)) < eps
if test == True:
return s, abs(term)
elif not (test == False):
# a symbolic Relational class, can't go further
return term, S.Zero
s += term
for k in range(1, m):
term = f.subs(i, a + k)
if abs(term.evalf(3)) < eps and term != 0:
return s, abs(term)
s += term
if b - a + 1 == m:
return s, S.Zero
a += m
x = Dummy('x')
I = Integral(f.subs(i, x), (x, a, b))
if eval_integral:
I = I.doit()
s += I
def fpoint(expr):
if b is S.Infinity:
return expr.subs(i, a), 0
return expr.subs(i, a), expr.subs(i, b)
fa, fb = fpoint(f)
iterm = (fa + fb)/2
g = f.diff(i)
for k in range(1, n + 2):
ga, gb = fpoint(g)
term = bernoulli(2*k)/factorial(2*k)*(gb - ga)
if k > n:
break
if eps and term:
term_evalf = term.evalf(3)
if term_evalf is S.NaN:
return S.NaN, S.NaN
if abs(term_evalf) < eps:
break
s += term
g = g.diff(i, 2, simplify=False)
return s + iterm, abs(term)
def reverse_order(self, *indices):
"""
Reverse the order of a limit in a Sum.
Explanation
===========
``reverse_order(self, *indices)`` reverses some limits in the expression
``self`` 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 Sum
>>> from sympy.abc import x, y, a, b, c, d
>>> Sum(x, (x, 0, 3)).reverse_order(x)
Sum(-x, (x, 4, -1))
>>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y)
Sum(x*y, (x, 6, 0), (y, 7, -1))
>>> Sum(x, (x, a, b)).reverse_order(x)
Sum(-x, (x, b + 1, a - 1))
>>> Sum(x, (x, a, b)).reverse_order(0)
Sum(-x, (x, b + 1, a - 1))
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**2, (x, a, b), (x, c, d))
>>> S
Sum(x**2, (x, a, b), (x, c, d))
>>> S0 = S.reverse_order(0)
>>> S0
Sum(-x**2, (x, b + 1, a - 1), (x, c, d))
>>> S1 = S0.reverse_order(1)
>>> S1
Sum(x**2, (x, b + 1, a - 1), (x, 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] = self.index(indx)
e = 1
limits = []
for i, limit in enumerate(self.limits):
l = limit
if i in l_indices:
e = -e
l = (limit[0], limit[2] + 1, limit[1] - 1)
limits.append(l)
return Sum(e * self.function, *limits)
def _eval_rewrite_as_Product(self, *args, **kwargs):
from sympy.concrete.products import Product
if self.function.is_extended_real:
return log(Product(exp(self.function), *self.limits))
def summation(f, *symbols, **kwargs):
r"""
Compute the summation of f with respect to symbols.
Explanation
===========
The notation for symbols is similar to the notation used in Integral.
summation(f, (i, a, b)) computes the sum of f with respect to i from a to b,
i.e.,
::
b
____
\ `
summation(f, (i, a, b)) = ) f
/___,
i = a
If it cannot compute the sum, it returns an unevaluated Sum object.
Repeated sums can be computed by introducing additional symbols tuples::
Examples
========
>>> from sympy import summation, oo, symbols, log
>>> i, n, m = symbols('i n m', integer=True)
>>> summation(2*i - 1, (i, 1, n))
n**2
>>> summation(1/2**i, (i, 0, oo))
2
>>> summation(1/log(n)**n, (n, 2, oo))
Sum(log(n)**(-n), (n, 2, oo))
>>> summation(i, (i, 0, n), (n, 0, m))
m**3/6 + m**2/2 + m/3
>>> from sympy.abc import x
>>> from sympy import factorial
>>> summation(x**n/factorial(n), (n, 0, oo))
exp(x)
See Also
========
Sum
Product, sympy.concrete.products.product
"""
return Sum(f, *symbols, **kwargs).doit(deep=False)
def telescopic_direct(L, R, n, limits):
"""
Returns the direct summation of the terms of a telescopic sum
Explanation
===========
L is the term with lower index
R is the term with higher index
n difference between the indexes of L and R
Examples
========
>>> from sympy.concrete.summations import telescopic_direct
>>> from sympy.abc import k, a, b
>>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b))
-1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a
"""
(i, a, b) = limits
s = 0
for m in range(n):
s += L.subs(i, a + m) + R.subs(i, b - m)
return s
def telescopic(L, R, limits):
'''
Tries to perform the summation using the telescopic property.
Return None if not possible.
'''
(i, a, b) = limits
if L.is_Add or R.is_Add:
return None
# We want to solve(L.subs(i, i + m) + R, m)
# First we try a simple match since this does things that
# solve doesn't do, e.g. solve(cos(k+m)-cos(k), m) gives
# a more complicated solution than m == 0.
k = Wild("k")
sol = (-R).match(L.subs(i, i + k))
s = None
if sol and k in sol:
s = sol[k]
if not (s.is_Integer and L.subs(i, i + s) + R == 0):
# invalid match or match didn't work
s = None
# But there are things that match doesn't do that solve
# can do, e.g. determine that 1/(x + m) = 1/(1 - x) when m = 1
if s is None:
m = Dummy('m')
try:
from sympy.solvers.solvers import solve
sol = solve(L.subs(i, i + m) + R, m) or []
except NotImplementedError:
return None
sol = [si for si in sol if si.is_Integer and
(L.subs(i, i + si) + R).expand().is_zero]
if len(sol) != 1:
return None
s = sol[0]
if s < 0:
return telescopic_direct(R, L, abs(s), (i, a, b))
elif s > 0:
return telescopic_direct(L, R, s, (i, a, b))
def eval_sum(f, limits):
(i, a, b) = limits
if f.is_zero:
return S.Zero
if i not in f.free_symbols:
return f*(b - a + 1)
if a == b:
return f.subs(i, a)
if isinstance(f, Piecewise):
if not any(i in arg.args[1].free_symbols for arg in f.args):
# Piecewise conditions do not depend on the dummy summation variable,
# therefore we can fold: Sum(Piecewise((e, c), ...), limits)
# --> Piecewise((Sum(e, limits), c), ...)
newargs = []
for arg in f.args:
newexpr = eval_sum(arg.expr, limits)
if newexpr is None:
return None
newargs.append((newexpr, arg.cond))
return f.func(*newargs)
if f.has(KroneckerDelta):
from .delta import deltasummation, _has_simple_delta
f = f.replace(
lambda x: isinstance(x, Sum),
lambda x: x.factor()
)
if _has_simple_delta(f, limits[0]):
return deltasummation(f, limits)
dif = b - a
definite = dif.is_Integer
# Doing it directly may be faster if there are very few terms.
if definite and (dif < 100):
return eval_sum_direct(f, (i, a, b))
if isinstance(f, Piecewise):
return None
# Try to do it symbolically. Even when the number of terms is
# known, this can save time when b-a is big.
value = eval_sum_symbolic(f.expand(), (i, a, b))
if value is not None:
return value
# Do it directly
if definite:
return eval_sum_direct(f, (i, a, b))
def eval_sum_direct(expr, limits):
"""
Evaluate expression directly, but perform some simple checks first
to possibly result in a smaller expression and faster execution.
"""
(i, a, b) = limits
dif = b - a
# Linearity
if expr.is_Mul:
# Try factor out everything not including i
without_i, with_i = expr.as_independent(i)
if without_i != 1:
s = eval_sum_direct(with_i, (i, a, b))
if s:
r = without_i*s
if r is not S.NaN:
return r
else:
# Try term by term
L, R = expr.as_two_terms()
if not L.has(i):
sR = eval_sum_direct(R, (i, a, b))
if sR:
return L*sR
if not R.has(i):
sL = eval_sum_direct(L, (i, a, b))
if sL:
return sL*R
# do this whether its an Add or Mul
# e.g. apart(1/(25*i**2 + 45*i + 14)) and
# apart(1/((5*i + 2)*(5*i + 7))) ->
# -1/(5*(5*i + 7)) + 1/(5*(5*i + 2))
try:
expr = apart(expr, i) # see if it becomes an Add
except PolynomialError:
pass
if expr.is_Add:
# Try factor out everything not including i
without_i, with_i = expr.as_independent(i)
if without_i != 0:
s = eval_sum_direct(with_i, (i, a, b))
if s:
r = without_i*(dif + 1) + s
if r is not S.NaN:
return r
else:
# Try term by term
L, R = expr.as_two_terms()
lsum = eval_sum_direct(L, (i, a, b))
rsum = eval_sum_direct(R, (i, a, b))
if None not in (lsum, rsum):
r = lsum + rsum
if r is not S.NaN:
return r
return Add(*[expr.subs(i, a + j) for j in range(dif + 1)])
def eval_sum_symbolic(f, limits):
f_orig = f
(i, a, b) = limits
if not f.has(i):
return f*(b - a + 1)
# Linearity
if f.is_Mul:
# Try factor out everything not including i
without_i, with_i = f.as_independent(i)
if without_i != 1:
s = eval_sum_symbolic(with_i, (i, a, b))
if s:
r = without_i*s
if r is not S.NaN:
return r
else:
# Try term by term
L, R = f.as_two_terms()
if not L.has(i):
sR = eval_sum_symbolic(R, (i, a, b))
if sR:
return L*sR
if not R.has(i):
sL = eval_sum_symbolic(L, (i, a, b))
if sL:
return sL*R
# do this whether its an Add or Mul
# e.g. apart(1/(25*i**2 + 45*i + 14)) and
# apart(1/((5*i + 2)*(5*i + 7))) ->
# -1/(5*(5*i + 7)) + 1/(5*(5*i + 2))
try:
f = apart(f, i)
except PolynomialError:
pass
if f.is_Add:
L, R = f.as_two_terms()
lrsum = telescopic(L, R, (i, a, b))
if lrsum:
return lrsum
# Try factor out everything not including i
without_i, with_i = f.as_independent(i)
if without_i != 0:
s = eval_sum_symbolic(with_i, (i, a, b))
if s:
r = without_i*(b - a + 1) + s
if r is not S.NaN:
return r
else:
# Try term by term
lsum = eval_sum_symbolic(L, (i, a, b))
rsum = eval_sum_symbolic(R, (i, a, b))
if None not in (lsum, rsum):
r = lsum + rsum
if r is not S.NaN:
return r
# Polynomial terms with Faulhaber's formula
n = Wild('n')
result = f.match(i**n)
if result is not None:
n = result[n]
if n.is_Integer:
if n >= 0:
if (b is S.Infinity and a is not S.NegativeInfinity) or \
(a is S.NegativeInfinity and b is not S.Infinity):
return S.Infinity
return ((bernoulli(n + 1, b + 1) - bernoulli(n + 1, a))/(n + 1)).expand()
elif a.is_Integer and a >= 1:
if n == -1:
return harmonic(b) - harmonic(a - 1)
else:
return harmonic(b, abs(n)) - harmonic(a - 1, abs(n))
if not (a.has(S.Infinity, S.NegativeInfinity) or
b.has(S.Infinity, S.NegativeInfinity)):
# Geometric terms
c1 = Wild('c1', exclude=[i])
c2 = Wild('c2', exclude=[i])
c3 = Wild('c3', exclude=[i])
wexp = Wild('wexp')
# Here we first attempt powsimp on f for easier matching with the
# exponential pattern, and attempt expansion on the exponent for easier
# matching with the linear pattern.
e = f.powsimp().match(c1 ** wexp)
if e is not None:
e_exp = e.pop(wexp).expand().match(c2*i + c3)
if e_exp is not None:
e.update(e_exp)
p = (c1**c3).subs(e)
q = (c1**c2).subs(e)
r = p*(q**a - q**(b + 1))/(1 - q)
l = p*(b - a + 1)
return Piecewise((l, Eq(q, S.One)), (r, True))
r = gosper_sum(f, (i, a, b))
if isinstance(r, (Mul,Add)):
from sympy.simplify.radsimp import denom
from sympy.solvers.solvers import solve
non_limit = r.free_symbols - Tuple(*limits[1:]).free_symbols
den = denom(together(r))
den_sym = non_limit & den.free_symbols
args = []
for v in ordered(den_sym):
try:
s = solve(den, v)
m = Eq(v, s[0]) if s else S.false
if m != False:
args.append((Sum(f_orig.subs(*m.args), limits).doit(), m))
break
except NotImplementedError:
continue
args.append((r, True))
return Piecewise(*args)
if r not in (None, S.NaN):
return r
h = eval_sum_hyper(f_orig, (i, a, b))
if h is not None:
return h
r = eval_sum_residue(f_orig, (i, a, b))
if r is not None:
return r
factored = f_orig.factor()
if factored != f_orig:
return eval_sum_symbolic(factored, (i, a, b))
def _eval_sum_hyper(f, i, a):
""" Returns (res, cond). Sums from a to oo. """
if a != 0:
return _eval_sum_hyper(f.subs(i, i + a), i, 0)
if f.subs(i, 0) == 0:
from sympy.simplify.simplify import simplify
if simplify(f.subs(i, Dummy('i', integer=True, positive=True))) == 0:
return S.Zero, True
return _eval_sum_hyper(f.subs(i, i + 1), i, 0)
from sympy.simplify.simplify import hypersimp
hs = hypersimp(f, i)
if hs is None:
return None
if isinstance(hs, Float):
from sympy.simplify.simplify import nsimplify
hs = nsimplify(hs)
from sympy.simplify.combsimp import combsimp
from sympy.simplify.hyperexpand import hyperexpand
from sympy.simplify.radsimp import fraction
numer, denom = fraction(factor(hs))
top, topl = numer.as_coeff_mul(i)
bot, botl = denom.as_coeff_mul(i)
ab = [top, bot]
factors = [topl, botl]
params = [[], []]
for k in range(2):
for fac in factors[k]:
mul = 1
if fac.is_Pow:
mul = fac.exp
fac = fac.base
if not mul.is_Integer:
return None
p = Poly(fac, i)
if p.degree() != 1:
return None
m, n = p.all_coeffs()
ab[k] *= m**mul
params[k] += [n/m]*mul
# Add "1" to numerator parameters, to account for implicit n! in
# hypergeometric series.
ap = params[0] + [1]
bq = params[1]
x = ab[0]/ab[1]
h = hyper(ap, bq, x)
f = combsimp(f)
return f.subs(i, 0)*hyperexpand(h), h.convergence_statement
def eval_sum_hyper(f, i_a_b):
i, a, b = i_a_b
if f.is_hypergeometric(i) is False:
return
if (b - a).is_Integer:
# We are never going to do better than doing the sum in the obvious way
return None
old_sum = Sum(f, (i, a, b))
if b != S.Infinity:
if a is S.NegativeInfinity:
res = _eval_sum_hyper(f.subs(i, -i), i, -b)
if res is not None:
return Piecewise(res, (old_sum, True))
else:
n_illegal = lambda x: sum(x.count(_) for _ in _illegal)
had = n_illegal(f)
# check that no extra illegals are introduced
res1 = _eval_sum_hyper(f, i, a)
if res1 is None or n_illegal(res1) > had:
return
res2 = _eval_sum_hyper(f, i, b + 1)
if res2 is None or n_illegal(res2) > had:
return
(res1, cond1), (res2, cond2) = res1, res2
cond = And(cond1, cond2)
if cond == False:
return None
return Piecewise((res1 - res2, cond), (old_sum, True))
if a is S.NegativeInfinity:
res1 = _eval_sum_hyper(f.subs(i, -i), i, 1)
res2 = _eval_sum_hyper(f, i, 0)
if res1 is None or res2 is None:
return None
res1, cond1 = res1
res2, cond2 = res2
cond = And(cond1, cond2)
if cond == False or cond.as_set() == S.EmptySet:
return None
return Piecewise((res1 + res2, cond), (old_sum, True))
# Now b == oo, a != -oo
res = _eval_sum_hyper(f, i, a)
if res is not None:
r, c = res
if c == False:
if r.is_number:
f = f.subs(i, Dummy('i', integer=True, positive=True) + a)
if f.is_positive or f.is_zero:
return S.Infinity
elif f.is_negative:
return S.NegativeInfinity
return None
return Piecewise(res, (old_sum, True))
def eval_sum_residue(f, i_a_b):
r"""Compute the infinite summation with residues
Notes
=====
If $f(n), g(n)$ are polynomials with $\deg(g(n)) - \deg(f(n)) \ge 2$,
some infinite summations can be computed by the following residue
evaluations.
.. math::
\sum_{n=-\infty, g(n) \ne 0}^{\infty} \frac{f(n)}{g(n)} =
-\pi \sum_{\alpha|g(\alpha)=0}
\text{Res}(\cot(\pi x) \frac{f(x)}{g(x)}, \alpha)
.. math::
\sum_{n=-\infty, g(n) \ne 0}^{\infty} (-1)^n \frac{f(n)}{g(n)} =
-\pi \sum_{\alpha|g(\alpha)=0}
\text{Res}(\csc(\pi x) \frac{f(x)}{g(x)}, \alpha)
Examples
========
>>> from sympy import Sum, oo, Symbol
>>> x = Symbol('x')
Doubly infinite series of rational functions.
>>> Sum(1 / (x**2 + 1), (x, -oo, oo)).doit()
pi/tanh(pi)
Doubly infinite alternating series of rational functions.
>>> Sum((-1)**x / (x**2 + 1), (x, -oo, oo)).doit()
pi/sinh(pi)
Infinite series of even rational functions.
>>> Sum(1 / (x**2 + 1), (x, 0, oo)).doit()
1/2 + pi/(2*tanh(pi))
Infinite series of alternating even rational functions.
>>> Sum((-1)**x / (x**2 + 1), (x, 0, oo)).doit()
pi/(2*sinh(pi)) + 1/2
This also have heuristics to transform arbitrarily shifted summand or
arbitrarily shifted summation range to the canonical problem the
formula can handle.
>>> Sum(1 / (x**2 + 2*x + 2), (x, -1, oo)).doit()
1/2 + pi/(2*tanh(pi))
>>> Sum(1 / (x**2 + 4*x + 5), (x, -2, oo)).doit()
1/2 + pi/(2*tanh(pi))
>>> Sum(1 / (x**2 + 1), (x, 1, oo)).doit()
-1/2 + pi/(2*tanh(pi))
>>> Sum(1 / (x**2 + 1), (x, 2, oo)).doit()
-1 + pi/(2*tanh(pi))
References
==========
.. [#] http://www.supermath.info/InfiniteSeriesandtheResidueTheorem.pdf
.. [#] Asmar N.H., Grafakos L. (2018) Residue Theory.
In: Complex Analysis with Applications.
Undergraduate Texts in Mathematics. Springer, Cham.
https://doi.org/10.1007/978-3-319-94063-2_5
"""
i, a, b = i_a_b
def is_even_function(numer, denom):
"""Test if the rational function is an even function"""
numer_even = all(i % 2 == 0 for (i,) in numer.monoms())
denom_even = all(i % 2 == 0 for (i,) in denom.monoms())
numer_odd = all(i % 2 == 1 for (i,) in numer.monoms())
denom_odd = all(i % 2 == 1 for (i,) in denom.monoms())
return (numer_even and denom_even) or (numer_odd and denom_odd)
def match_rational(f, i):
numer, denom = f.as_numer_denom()
try:
(numer, denom), opt = parallel_poly_from_expr((numer, denom), i)
except (PolificationFailed, PolynomialError):
return None
return numer, denom
def get_poles(denom):
roots = denom.sqf_part().all_roots()
roots = sift(roots, lambda x: x.is_integer)
if None in roots:
return None
int_roots, nonint_roots = roots[True], roots[False]
return int_roots, nonint_roots
def get_shift(denom):
n = denom.degree(i)
a = denom.coeff_monomial(i**n)
b = denom.coeff_monomial(i**(n-1))
shift = - b / a / n
return shift
def get_residue_factor(numer, denom, alternating):
if not alternating:
residue_factor = (numer.as_expr() / denom.as_expr()) * cot(S.Pi * i)
else:
residue_factor = (numer.as_expr() / denom.as_expr()) * csc(S.Pi * i)
return residue_factor
# We don't know how to deal with symbolic constants in summand
if f.free_symbols - set([i]):
return None
if not (a.is_Integer or a in (S.Infinity, S.NegativeInfinity)):
return None
if not (b.is_Integer or b in (S.Infinity, S.NegativeInfinity)):
return None
# Quick exit heuristic for the sums which doesn't have infinite range
if a != S.NegativeInfinity and b != S.Infinity:
return None
match = match_rational(f, i)
if match:
alternating = False
numer, denom = match
else:
match = match_rational(f / S.NegativeOne**i, i)
if match:
alternating = True
numer, denom = match
else:
return None
if denom.degree(i) - numer.degree(i) < 2:
return None
if (a, b) == (S.NegativeInfinity, S.Infinity):
poles = get_poles(denom)
if poles is None:
return None
int_roots, nonint_roots = poles
if int_roots:
return None
residue_factor = get_residue_factor(numer, denom, alternating)
residues = [residue(residue_factor, i, root) for root in nonint_roots]
return -S.Pi * sum(residues)
if not (a.is_finite and b is S.Infinity):
return None
if not is_even_function(numer, denom):
# Try shifting summation and check if the summand can be made
# and even function from the origin.
# Sum(f(n), (n, a, b)) => Sum(f(n + s), (n, a - s, b - s))
shift = get_shift(denom)
if not shift.is_Integer:
return None
if shift == 0:
return None
numer = numer.shift(shift)
denom = denom.shift(shift)
if not is_even_function(numer, denom):
return None
if alternating:
f = S.NegativeOne**i * (S.NegativeOne**shift * numer.as_expr() / denom.as_expr())
else:
f = numer.as_expr() / denom.as_expr()
return eval_sum_residue(f, (i, a-shift, b-shift))
poles = get_poles(denom)
if poles is None:
return None
int_roots, nonint_roots = poles
if int_roots:
int_roots = [int(root) for root in int_roots]
int_roots_max = max(int_roots)
int_roots_min = min(int_roots)
# Integer valued poles must be next to each other
# and also symmetric from origin (Because the function is even)
if not len(int_roots) == int_roots_max - int_roots_min + 1:
return None
# Check whether the summation indices contain poles
if a <= max(int_roots):
return None
residue_factor = get_residue_factor(numer, denom, alternating)
residues = [residue(residue_factor, i, root) for root in int_roots + nonint_roots]
full_sum = -S.Pi * sum(residues)
if not int_roots:
# Compute Sum(f, (i, 0, oo)) by adding a extraneous evaluation
# at the origin.
half_sum = (full_sum + f.xreplace({i: 0})) / 2
# Add and subtract extraneous evaluations
extraneous_neg = [f.xreplace({i: i0}) for i0 in range(int(a), 0)]
extraneous_pos = [f.xreplace({i: i0}) for i0 in range(0, int(a))]
result = half_sum + sum(extraneous_neg) - sum(extraneous_pos)
return result
# Compute Sum(f, (i, min(poles) + 1, oo))
half_sum = full_sum / 2
# Subtract extraneous evaluations
extraneous = [f.xreplace({i: i0}) for i0 in range(max(int_roots) + 1, int(a))]
result = half_sum - sum(extraneous)
return result
def _eval_matrix_sum(expression):
f = expression.function
for n, limit in enumerate(expression.limits):
i, a, b = limit
dif = b - a
if dif.is_Integer:
if (dif < 0) == True:
a, b = b + 1, a - 1
f = -f
newf = eval_sum_direct(f, (i, a, b))
if newf is not None:
return newf.doit()
def _dummy_with_inherited_properties_concrete(limits):
"""
Return a Dummy symbol that inherits as many assumptions as possible
from the provided symbol and limits.
If the symbol already has all True assumption shared by the limits
then return None.
"""
x, a, b = limits
l = [a, b]
assumptions_to_consider = ['extended_nonnegative', 'nonnegative',
'extended_nonpositive', 'nonpositive',
'extended_positive', 'positive',
'extended_negative', 'negative',
'integer', 'rational', 'finite',
'zero', 'real', 'extended_real']
assumptions_to_keep = {}
assumptions_to_add = {}
for assum in assumptions_to_consider:
assum_true = x._assumptions.get(assum, None)
if assum_true:
assumptions_to_keep[assum] = True
elif all(getattr(i, 'is_' + assum) for i in l):
assumptions_to_add[assum] = True
if assumptions_to_add:
assumptions_to_keep.update(assumptions_to_add)
return Dummy('d', **assumptions_to_keep)
|
db4a85b74fa69b91df3b1b502aba7bb35586b9312c5b1bbdc29f1805b9fd76e0 | from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.polys.polytools import lcm
from sympy.utilities import public
@public
def approximants(l, X=Symbol('x'), simplify=False):
"""
Return a generator for consecutive Pade approximants for a series.
It can also be used for computing the rational generating function of a
series when possible, since the last approximant returned by the generator
will be the generating function (if any).
Explanation
===========
The input list can contain more complex expressions than integer or rational
numbers; symbols may also be involved in the computation. An example below
show how to compute the generating function of the whole Pascal triangle.
The generator can be asked to apply the sympy.simplify function on each
generated term, which will make the computation slower; however it may be
useful when symbols are involved in the expressions.
Examples
========
>>> from sympy.series import approximants
>>> from sympy import lucas, fibonacci, symbols, binomial
>>> g = [lucas(k) for k in range(16)]
>>> [e for e in approximants(g)]
[2, -4/(x - 2), (5*x - 2)/(3*x - 1), (x - 2)/(x**2 + x - 1)]
>>> h = [fibonacci(k) for k in range(16)]
>>> [e for e in approximants(h)]
[x, -x/(x - 1), (x**2 - x)/(2*x - 1), -x/(x**2 + x - 1)]
>>> x, t = symbols("x,t")
>>> p=[sum(binomial(k,i)*x**i for i in range(k+1)) for k in range(16)]
>>> y = approximants(p, t)
>>> for k in range(3): print(next(y))
1
(x + 1)/((-x - 1)*(t*(x + 1) + (x + 1)/(-x - 1)))
nan
>>> y = approximants(p, t, simplify=True)
>>> for k in range(3): print(next(y))
1
-1/(t*(x + 1) - 1)
nan
See Also
========
See function sympy.concrete.guess.guess_generating_function_rational and
function mpmath.pade
"""
from sympy.simplify import simplify as simp
from sympy.simplify.radsimp import denom
p1, q1 = [S.One], [S.Zero]
p2, q2 = [S.Zero], [S.One]
while len(l):
b = 0
while l[b]==0:
b += 1
if b == len(l):
return
m = [S.One/l[b]]
for k in range(b+1, len(l)):
s = 0
for j in range(b, k):
s -= l[j+1] * m[b-j-1]
m.append(s/l[b])
l = m
a, l[0] = l[0], 0
p = [0] * max(len(p2), b+len(p1))
q = [0] * max(len(q2), b+len(q1))
for k in range(len(p2)):
p[k] = a*p2[k]
for k in range(b, b+len(p1)):
p[k] += p1[k-b]
for k in range(len(q2)):
q[k] = a*q2[k]
for k in range(b, b+len(q1)):
q[k] += q1[k-b]
while p[-1]==0: p.pop()
while q[-1]==0: q.pop()
p1, p2 = p2, p
q1, q2 = q2, q
# yield result
c = 1
for x in p:
c = lcm(c, denom(x))
for x in q:
c = lcm(c, denom(x))
out = ( sum(c*e*X**k for k, e in enumerate(p))
/ sum(c*e*X**k for k, e in enumerate(q)) )
if simplify:
yield(simp(out))
else:
yield out
return
|
6ad64aedba3f9ebdc30aa545a790c498a35e9a72d023bb6f98337cb60052e736 | """
Limits
======
Implemented according to the PhD thesis
http://www.cybertester.com/data/gruntz.pdf, which contains very thorough
descriptions of the algorithm including many examples. We summarize here
the gist of it.
All functions are sorted according to how rapidly varying they are at
infinity using the following rules. Any two functions f and g can be
compared using the properties of L:
L=lim log|f(x)| / log|g(x)| (for x -> oo)
We define >, < ~ according to::
1. f > g .... L=+-oo
we say that:
- f is greater than any power of g
- f is more rapidly varying than g
- f goes to infinity/zero faster than g
2. f < g .... L=0
we say that:
- f is lower than any power of g
3. f ~ g .... L!=0, +-oo
we say that:
- both f and g are bounded from above and below by suitable integral
powers of the other
Examples
========
::
2 < x < exp(x) < exp(x**2) < exp(exp(x))
2 ~ 3 ~ -5
x ~ x**2 ~ x**3 ~ 1/x ~ x**m ~ -x
exp(x) ~ exp(-x) ~ exp(2x) ~ exp(x)**2 ~ exp(x+exp(-x))
f ~ 1/f
So we can divide all the functions into comparability classes (x and x^2
belong to one class, exp(x) and exp(-x) belong to some other class). In
principle, we could compare any two functions, but in our algorithm, we
do not compare anything below the class 2~3~-5 (for example log(x) is
below this), so we set 2~3~-5 as the lowest comparability class.
Given the function f, we find the list of most rapidly varying (mrv set)
subexpressions of it. This list belongs to the same comparability class.
Let's say it is {exp(x), exp(2x)}. Using the rule f ~ 1/f we find an
element "w" (either from the list or a new one) from the same
comparability class which goes to zero at infinity. In our example we
set w=exp(-x) (but we could also set w=exp(-2x) or w=exp(-3x) ...). We
rewrite the mrv set using w, in our case {1/w, 1/w^2}, and substitute it
into f. Then we expand f into a series in w::
f = c0*w^e0 + c1*w^e1 + ... + O(w^en), where e0<e1<...<en, c0!=0
but for x->oo, lim f = lim c0*w^e0, because all the other terms go to zero,
because w goes to zero faster than the ci and ei. So::
for e0>0, lim f = 0
for e0<0, lim f = +-oo (the sign depends on the sign of c0)
for e0=0, lim f = lim c0
We need to recursively compute limits at several places of the algorithm, but
as is shown in the PhD thesis, it always finishes.
Important functions from the implementation:
compare(a, b, x) compares "a" and "b" by computing the limit L.
mrv(e, x) returns list of most rapidly varying (mrv) subexpressions of "e"
rewrite(e, Omega, x, wsym) rewrites "e" in terms of w
leadterm(f, x) returns the lowest power term in the series of f
mrv_leadterm(e, x) returns the lead term (c0, e0) for e
limitinf(e, x) computes lim e (for x->oo)
limit(e, z, z0) computes any limit by converting it to the case x->oo
All the functions are really simple and straightforward except
rewrite(), which is the most difficult/complex part of the algorithm.
When the algorithm fails, the bugs are usually in the series expansion
(i.e. in SymPy) or in rewrite.
This code is almost exact rewrite of the Maple code inside the Gruntz
thesis.
Debugging
---------
Because the gruntz algorithm is highly recursive, it's difficult to
figure out what went wrong inside a debugger. Instead, turn on nice
debug prints by defining the environment variable SYMPY_DEBUG. For
example:
[user@localhost]: SYMPY_DEBUG=True ./bin/isympy
In [1]: limit(sin(x)/x, x, 0)
limitinf(_x*sin(1/_x), _x) = 1
+-mrv_leadterm(_x*sin(1/_x), _x) = (1, 0)
| +-mrv(_x*sin(1/_x), _x) = set([_x])
| | +-mrv(_x, _x) = set([_x])
| | +-mrv(sin(1/_x), _x) = set([_x])
| | +-mrv(1/_x, _x) = set([_x])
| | +-mrv(_x, _x) = set([_x])
| +-mrv_leadterm(exp(_x)*sin(exp(-_x)), _x, set([exp(_x)])) = (1, 0)
| +-rewrite(exp(_x)*sin(exp(-_x)), set([exp(_x)]), _x, _w) = (1/_w*sin(_w), -_x)
| +-sign(_x, _x) = 1
| +-mrv_leadterm(1, _x) = (1, 0)
+-sign(0, _x) = 0
+-limitinf(1, _x) = 1
And check manually which line is wrong. Then go to the source code and
debug this function to figure out the exact problem.
"""
from functools import reduce
from sympy.core import Basic, S, Mul, PoleError
from sympy.core.cache import cacheit
from sympy.core.numbers import ilcm, I, oo
from sympy.core.symbol import Dummy, Wild
from sympy.core.traversal import bottom_up
from sympy.functions import log, exp, sign as _sign
from sympy.series.order import Order
from sympy.utilities.misc import debug_decorator as debug
from sympy.utilities.timeutils import timethis
timeit = timethis('gruntz')
def compare(a, b, x):
"""Returns "<" if a<b, "=" for a == b, ">" for a>b"""
# log(exp(...)) must always be simplified here for termination
la, lb = log(a), log(b)
if isinstance(a, Basic) and (isinstance(a, exp) or (a.is_Pow and a.base == S.Exp1)):
la = a.exp
if isinstance(b, Basic) and (isinstance(b, exp) or (b.is_Pow and b.base == S.Exp1)):
lb = b.exp
c = limitinf(la/lb, x)
if c == 0:
return "<"
elif c.is_infinite:
return ">"
else:
return "="
class SubsSet(dict):
"""
Stores (expr, dummy) pairs, and how to rewrite expr-s.
Explanation
===========
The gruntz algorithm needs to rewrite certain expressions in term of a new
variable w. We cannot use subs, because it is just too smart for us. For
example::
> Omega=[exp(exp(_p - exp(-_p))/(1 - 1/_p)), exp(exp(_p))]
> O2=[exp(-exp(_p) + exp(-exp(-_p))*exp(_p)/(1 - 1/_p))/_w, 1/_w]
> e = exp(exp(_p - exp(-_p))/(1 - 1/_p)) - exp(exp(_p))
> e.subs(Omega[0],O2[0]).subs(Omega[1],O2[1])
-1/w + exp(exp(p)*exp(-exp(-p))/(1 - 1/p))
is really not what we want!
So we do it the hard way and keep track of all the things we potentially
want to substitute by dummy variables. Consider the expression::
exp(x - exp(-x)) + exp(x) + x.
The mrv set is {exp(x), exp(-x), exp(x - exp(-x))}.
We introduce corresponding dummy variables d1, d2, d3 and rewrite::
d3 + d1 + x.
This class first of all keeps track of the mapping expr->variable, i.e.
will at this stage be a dictionary::
{exp(x): d1, exp(-x): d2, exp(x - exp(-x)): d3}.
[It turns out to be more convenient this way round.]
But sometimes expressions in the mrv set have other expressions from the
mrv set as subexpressions, and we need to keep track of that as well. In
this case, d3 is really exp(x - d2), so rewrites at this stage is::
{d3: exp(x-d2)}.
The function rewrite uses all this information to correctly rewrite our
expression in terms of w. In this case w can be chosen to be exp(-x),
i.e. d2. The correct rewriting then is::
exp(-w)/w + 1/w + x.
"""
def __init__(self):
self.rewrites = {}
def __repr__(self):
return super().__repr__() + ', ' + self.rewrites.__repr__()
def __getitem__(self, key):
if key not in self:
self[key] = Dummy()
return dict.__getitem__(self, key)
def do_subs(self, e):
"""Substitute the variables with expressions"""
for expr, var in self.items():
e = e.xreplace({var: expr})
return e
def meets(self, s2):
"""Tell whether or not self and s2 have non-empty intersection"""
return set(self.keys()).intersection(list(s2.keys())) != set()
def union(self, s2, exps=None):
"""Compute the union of self and s2, adjusting exps"""
res = self.copy()
tr = {}
for expr, var in s2.items():
if expr in self:
if exps:
exps = exps.xreplace({var: res[expr]})
tr[var] = res[expr]
else:
res[expr] = var
for var, rewr in s2.rewrites.items():
res.rewrites[var] = rewr.xreplace(tr)
return res, exps
def copy(self):
"""Create a shallow copy of SubsSet"""
r = SubsSet()
r.rewrites = self.rewrites.copy()
for expr, var in self.items():
r[expr] = var
return r
@debug
def mrv(e, x):
"""Returns a SubsSet of most rapidly varying (mrv) subexpressions of 'e',
and e rewritten in terms of these"""
from sympy.simplify.powsimp import powsimp
e = powsimp(e, deep=True, combine='exp')
if not isinstance(e, Basic):
raise TypeError("e should be an instance of Basic")
if not e.has(x):
return SubsSet(), e
elif e == x:
s = SubsSet()
return s, s[x]
elif e.is_Mul or e.is_Add:
i, d = e.as_independent(x) # throw away x-independent terms
if d.func != e.func:
s, expr = mrv(d, x)
return s, e.func(i, expr)
a, b = d.as_two_terms()
s1, e1 = mrv(a, x)
s2, e2 = mrv(b, x)
return mrv_max1(s1, s2, e.func(i, e1, e2), x)
elif e.is_Pow and e.base != S.Exp1:
e1 = S.One
while e.is_Pow:
b1 = e.base
e1 *= e.exp
e = b1
if b1 == 1:
return SubsSet(), b1
if e1.has(x):
base_lim = limitinf(b1, x)
if base_lim is S.One:
return mrv(exp(e1 * (b1 - 1)), x)
return mrv(exp(e1 * log(b1)), x)
else:
s, expr = mrv(b1, x)
return s, expr**e1
elif isinstance(e, log):
s, expr = mrv(e.args[0], x)
return s, log(expr)
elif isinstance(e, exp) or (e.is_Pow and e.base == S.Exp1):
# We know from the theory of this algorithm that exp(log(...)) may always
# be simplified here, and doing so is vital for termination.
if isinstance(e.exp, log):
return mrv(e.exp.args[0], x)
# if a product has an infinite factor the result will be
# infinite if there is no zero, otherwise NaN; here, we
# consider the result infinite if any factor is infinite
li = limitinf(e.exp, x)
if any(_.is_infinite for _ in Mul.make_args(li)):
s1 = SubsSet()
e1 = s1[e]
s2, e2 = mrv(e.exp, x)
su = s1.union(s2)[0]
su.rewrites[e1] = exp(e2)
return mrv_max3(s1, e1, s2, exp(e2), su, e1, x)
else:
s, expr = mrv(e.exp, x)
return s, exp(expr)
elif e.is_Function:
l = [mrv(a, x) for a in e.args]
l2 = [s for (s, _) in l if s != SubsSet()]
if len(l2) != 1:
# e.g. something like BesselJ(x, x)
raise NotImplementedError("MRV set computation for functions in"
" several variables not implemented.")
s, ss = l2[0], SubsSet()
args = [ss.do_subs(x[1]) for x in l]
return s, e.func(*args)
elif e.is_Derivative:
raise NotImplementedError("MRV set computation for derviatives"
" not implemented yet.")
raise NotImplementedError(
"Don't know how to calculate the mrv of '%s'" % e)
def mrv_max3(f, expsf, g, expsg, union, expsboth, x):
"""
Computes the maximum of two sets of expressions f and g, which
are in the same comparability class, i.e. max() compares (two elements of)
f and g and returns either (f, expsf) [if f is larger], (g, expsg)
[if g is larger] or (union, expsboth) [if f, g are of the same class].
"""
if not isinstance(f, SubsSet):
raise TypeError("f should be an instance of SubsSet")
if not isinstance(g, SubsSet):
raise TypeError("g should be an instance of SubsSet")
if f == SubsSet():
return g, expsg
elif g == SubsSet():
return f, expsf
elif f.meets(g):
return union, expsboth
c = compare(list(f.keys())[0], list(g.keys())[0], x)
if c == ">":
return f, expsf
elif c == "<":
return g, expsg
else:
if c != "=":
raise ValueError("c should be =")
return union, expsboth
def mrv_max1(f, g, exps, x):
"""Computes the maximum of two sets of expressions f and g, which
are in the same comparability class, i.e. mrv_max1() compares (two elements of)
f and g and returns the set, which is in the higher comparability class
of the union of both, if they have the same order of variation.
Also returns exps, with the appropriate substitutions made.
"""
u, b = f.union(g, exps)
return mrv_max3(f, g.do_subs(exps), g, f.do_subs(exps),
u, b, x)
@debug
@cacheit
@timeit
def sign(e, x):
"""
Returns a sign of an expression e(x) for x->oo.
::
e > 0 for x sufficiently large ... 1
e == 0 for x sufficiently large ... 0
e < 0 for x sufficiently large ... -1
The result of this function is currently undefined if e changes sign
arbitrarily often for arbitrarily large x (e.g. sin(x)).
Note that this returns zero only if e is *constantly* zero
for x sufficiently large. [If e is constant, of course, this is just
the same thing as the sign of e.]
"""
if not isinstance(e, Basic):
raise TypeError("e should be an instance of Basic")
if e.is_positive:
return 1
elif e.is_negative:
return -1
elif e.is_zero:
return 0
elif not e.has(x):
from sympy.simplify import logcombine
e = logcombine(e)
return _sign(e)
elif e == x:
return 1
elif e.is_Mul:
a, b = e.as_two_terms()
sa = sign(a, x)
if not sa:
return 0
return sa * sign(b, x)
elif isinstance(e, exp):
return 1
elif e.is_Pow:
if e.base == S.Exp1:
return 1
s = sign(e.base, x)
if s == 1:
return 1
if e.exp.is_Integer:
return s**e.exp
elif isinstance(e, log):
return sign(e.args[0] - 1, x)
# if all else fails, do it the hard way
c0, e0 = mrv_leadterm(e, x)
return sign(c0, x)
@debug
@timeit
@cacheit
def limitinf(e, x, leadsimp=False):
"""Limit e(x) for x-> oo.
Explanation
===========
If ``leadsimp`` is True, an attempt is made to simplify the leading
term of the series expansion of ``e``. That may succeed even if
``e`` cannot be simplified.
"""
# rewrite e in terms of tractable functions only
if not e.has(x):
return e # e is a constant
from sympy.simplify.powsimp import powdenest
if e.has(Order):
e = e.expand().removeO()
if not x.is_positive or x.is_integer:
# We make sure that x.is_positive is True and x.is_integer is None
# so we get all the correct mathematical behavior from the expression.
# We need a fresh variable.
p = Dummy('p', positive=True)
e = e.subs(x, p)
x = p
e = e.rewrite('tractable', deep=True, limitvar=x)
e = powdenest(e)
c0, e0 = mrv_leadterm(e, x)
sig = sign(e0, x)
if sig == 1:
return S.Zero # e0>0: lim f = 0
elif sig == -1: # e0<0: lim f = +-oo (the sign depends on the sign of c0)
if c0.match(I*Wild("a", exclude=[I])):
return c0*oo
s = sign(c0, x)
# the leading term shouldn't be 0:
if s == 0:
raise ValueError("Leading term should not be 0")
return s*oo
elif sig == 0:
if leadsimp:
c0 = c0.simplify()
return limitinf(c0, x, leadsimp) # e0=0: lim f = lim c0
else:
raise ValueError("{} could not be evaluated".format(sig))
def moveup2(s, x):
r = SubsSet()
for expr, var in s.items():
r[expr.xreplace({x: exp(x)})] = var
for var, expr in s.rewrites.items():
r.rewrites[var] = s.rewrites[var].xreplace({x: exp(x)})
return r
def moveup(l, x):
return [e.xreplace({x: exp(x)}) for e in l]
@debug
@timeit
def calculate_series(e, x, logx=None):
""" Calculates at least one term of the series of ``e`` in ``x``.
This is a place that fails most often, so it is in its own function.
"""
from sympy.simplify.powsimp import powdenest
for t in e.lseries(x, logx=logx):
# bottom_up function is required for a specific case - when e is
# -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p)
t = bottom_up(t, lambda w:
getattr(w, 'normal', lambda: w)())
# And the expression
# `(-sin(1/x) + sin((x + exp(x))*exp(-x)/x))*exp(x)`
# from the first test of test_gruntz_eval_special needs to
# be expanded. But other forms need to be have at least
# factor_terms applied. `factor` accomplishes both and is
# faster than using `factor_terms` for the gruntz suite. It
# does not appear that use of `cancel` is necessary.
# t = cancel(t, expand=False)
t = t.factor()
if t.has(exp) and t.has(log):
t = powdenest(t)
if not t.is_zero:
break
return t
@debug
@timeit
@cacheit
def mrv_leadterm(e, x):
"""Returns (c0, e0) for e."""
Omega = SubsSet()
if not e.has(x):
return (e, S.Zero)
if Omega == SubsSet():
Omega, exps = mrv(e, x)
if not Omega:
# e really does not depend on x after simplification
return exps, S.Zero
if x in Omega:
# move the whole omega up (exponentiate each term):
Omega_up = moveup2(Omega, x)
exps_up = moveup([exps], x)[0]
# NOTE: there is no need to move this down!
Omega = Omega_up
exps = exps_up
#
# The positive dummy, w, is used here so log(w*2) etc. will expand;
# a unique dummy is needed in this algorithm
#
# For limits of complex functions, the algorithm would have to be
# improved, or just find limits of Re and Im components separately.
#
w = Dummy("w", positive=True)
f, logw = rewrite(exps, Omega, x, w)
series = calculate_series(f, w, logx=logw)
try:
lt = series.leadterm(w, logx=logw)
except (ValueError, PoleError):
lt = f.as_coeff_exponent(w)
# as_coeff_exponent won't always split in required form. It may simply
# return (f, 0) when a better form may be obtained. Example (-x)**(-pi)
# can be written as (-1**(-pi), -pi) which as_coeff_exponent does not return
if lt[0].has(w):
base = f.as_base_exp()[0].as_coeff_exponent(w)
ex = f.as_base_exp()[1]
lt = (base[0]**ex, base[1]*ex)
return (lt[0].subs(log(w), logw), lt[1])
def build_expression_tree(Omega, rewrites):
r""" Helper function for rewrite.
We need to sort Omega (mrv set) so that we replace an expression before
we replace any expression in terms of which it has to be rewritten::
e1 ---> e2 ---> e3
\
-> e4
Here we can do e1, e2, e3, e4 or e1, e2, e4, e3.
To do this we assemble the nodes into a tree, and sort them by height.
This function builds the tree, rewrites then sorts the nodes.
"""
class Node:
def __init__(self):
self.before = []
self.expr = None
self.var = None
def ht(self):
return reduce(lambda x, y: x + y,
[x.ht() for x in self.before], 1)
nodes = {}
for expr, v in Omega:
n = Node()
n.var = v
n.expr = expr
nodes[v] = n
for _, v in Omega:
if v in rewrites:
n = nodes[v]
r = rewrites[v]
for _, v2 in Omega:
if r.has(v2):
n.before.append(nodes[v2])
return nodes
@debug
@timeit
def rewrite(e, Omega, x, wsym):
"""e(x) ... the function
Omega ... the mrv set
wsym ... the symbol which is going to be used for w
Returns the rewritten e in terms of w and log(w). See test_rewrite1()
for examples and correct results.
"""
if not isinstance(Omega, SubsSet):
raise TypeError("Omega should be an instance of SubsSet")
if len(Omega) == 0:
raise ValueError("Length cannot be 0")
# all items in Omega must be exponentials
for t in Omega.keys():
if not isinstance(t, exp):
raise ValueError("Value should be exp")
rewrites = Omega.rewrites
Omega = list(Omega.items())
nodes = build_expression_tree(Omega, rewrites)
Omega.sort(key=lambda x: nodes[x[1]].ht(), reverse=True)
# make sure we know the sign of each exp() term; after the loop,
# g is going to be the "w" - the simplest one in the mrv set
for g, _ in Omega:
sig = sign(g.exp, x)
if sig != 1 and sig != -1:
raise NotImplementedError('Result depends on the sign of %s' % sig)
if sig == 1:
wsym = 1/wsym # if g goes to oo, substitute 1/w
# O2 is a list, which results by rewriting each item in Omega using "w"
O2 = []
denominators = []
for f, var in Omega:
c = limitinf(f.exp/g.exp, x)
if c.is_Rational:
denominators.append(c.q)
arg = f.exp
if var in rewrites:
if not isinstance(rewrites[var], exp):
raise ValueError("Value should be exp")
arg = rewrites[var].args[0]
O2.append((var, exp((arg - c*g.exp).expand())*wsym**c))
# Remember that Omega contains subexpressions of "e". So now we find
# them in "e" and substitute them for our rewriting, stored in O2
# the following powsimp is necessary to automatically combine exponentials,
# so that the .xreplace() below succeeds:
# TODO this should not be necessary
from sympy.simplify.powsimp import powsimp
f = powsimp(e, deep=True, combine='exp')
for a, b in O2:
f = f.xreplace({a: b})
for _, var in Omega:
assert not f.has(var)
# finally compute the logarithm of w (logw).
logw = g.exp
if sig == 1:
logw = -logw # log(w)->log(1/w)=-log(w)
# Some parts of SymPy have difficulty computing series expansions with
# non-integral exponents. The following heuristic improves the situation:
exponent = reduce(ilcm, denominators, 1)
f = f.subs({wsym: wsym**exponent})
logw /= exponent
return f, logw
def gruntz(e, z, z0, dir="+"):
"""
Compute the limit of e(z) at the point z0 using the Gruntz algorithm.
Explanation
===========
``z0`` can be any expression, including oo and -oo.
For ``dir="+"`` (default) it calculates the limit from the right
(z->z0+) and for ``dir="-"`` the limit from the left (z->z0-). For infinite z0
(oo or -oo), the dir argument does not matter.
This algorithm is fully described in the module docstring in the gruntz.py
file. It relies heavily on the series expansion. Most frequently, gruntz()
is only used if the faster limit() function (which uses heuristics) fails.
"""
if not z.is_symbol:
raise NotImplementedError("Second argument must be a Symbol")
# convert all limits to the limit z->oo; sign of z is handled in limitinf
r = None
if z0 == oo:
e0 = e
elif z0 == -oo:
e0 = e.subs(z, -z)
else:
if str(dir) == "-":
e0 = e.subs(z, z0 - 1/z)
elif str(dir) == "+":
e0 = e.subs(z, z0 + 1/z)
else:
raise NotImplementedError("dir must be '+' or '-'")
try:
r = limitinf(e0, z)
except ValueError:
r = limitinf(e0, z, leadsimp=True)
# This is a bit of a heuristic for nice results... we always rewrite
# tractable functions in terms of familiar intractable ones.
# It might be nicer to rewrite the exactly to what they were initially,
# but that would take some work to implement.
return r.rewrite('intractable', deep=True)
|
4b6fc6b4788f63dab6069cdb56026c0f8a417ff7b8c96bde13096e5fdad21c5e | from sympy.core.basic import Basic
from sympy.core.cache import cacheit
from sympy.core.containers import Tuple
from sympy.core.decorators import call_highest_priority
from sympy.core.parameters import global_parameters
from sympy.core.function import AppliedUndef, expand
from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.core.relational import Eq
from sympy.core.singleton import S, Singleton
from sympy.core.sorting import ordered
from sympy.core.symbol import Dummy, Symbol, Wild
from sympy.core.sympify import sympify
from sympy.matrices import Matrix
from sympy.polys import lcm, factor
from sympy.sets.sets import Interval, Intersection
from sympy.tensor.indexed import Idx
from sympy.utilities.iterables import flatten, is_sequence, iterable
###############################################################################
# SEQUENCES #
###############################################################################
class SeqBase(Basic):
"""Base class for sequences"""
is_commutative = True
_op_priority = 15
@staticmethod
def _start_key(expr):
"""Return start (if possible) else S.Infinity.
adapted from Set._infimum_key
"""
try:
start = expr.start
except (NotImplementedError,
AttributeError, ValueError):
start = S.Infinity
return start
def _intersect_interval(self, other):
"""Returns start and stop.
Takes intersection over the two intervals.
"""
interval = Intersection(self.interval, other.interval)
return interval.inf, interval.sup
@property
def gen(self):
"""Returns the generator for the sequence"""
raise NotImplementedError("(%s).gen" % self)
@property
def interval(self):
"""The interval on which the sequence is defined"""
raise NotImplementedError("(%s).interval" % self)
@property
def start(self):
"""The starting point of the sequence. This point is included"""
raise NotImplementedError("(%s).start" % self)
@property
def stop(self):
"""The ending point of the sequence. This point is included"""
raise NotImplementedError("(%s).stop" % self)
@property
def length(self):
"""Length of the sequence"""
raise NotImplementedError("(%s).length" % self)
@property
def variables(self):
"""Returns a tuple of variables that are bounded"""
return ()
@property
def free_symbols(self):
"""
This method returns the symbols in the object, excluding those
that take on a specific value (i.e. the dummy symbols).
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n, m
>>> SeqFormula(m*n**2, (n, 0, 5)).free_symbols
{m}
"""
return ({j for i in self.args for j in i.free_symbols
.difference(self.variables)})
@cacheit
def coeff(self, pt):
"""Returns the coefficient at point pt"""
if pt < self.start or pt > self.stop:
raise IndexError("Index %s out of bounds %s" % (pt, self.interval))
return self._eval_coeff(pt)
def _eval_coeff(self, pt):
raise NotImplementedError("The _eval_coeff method should be added to"
"%s to return coefficient so it is available"
"when coeff calls it."
% self.func)
def _ith_point(self, i):
"""Returns the i'th point of a sequence.
Explanation
===========
If start point is negative infinity, point is returned from the end.
Assumes the first point to be indexed zero.
Examples
=========
>>> from sympy import oo
>>> from sympy.series.sequences import SeqPer
bounded
>>> SeqPer((1, 2, 3), (-10, 10))._ith_point(0)
-10
>>> SeqPer((1, 2, 3), (-10, 10))._ith_point(5)
-5
End is at infinity
>>> SeqPer((1, 2, 3), (0, oo))._ith_point(5)
5
Starts at negative infinity
>>> SeqPer((1, 2, 3), (-oo, 0))._ith_point(5)
-5
"""
if self.start is S.NegativeInfinity:
initial = self.stop
else:
initial = self.start
if self.start is S.NegativeInfinity:
step = -1
else:
step = 1
return initial + i*step
def _add(self, other):
"""
Should only be used internally.
Explanation
===========
self._add(other) returns a new, term-wise added sequence if self
knows how to add with other, otherwise it returns ``None``.
``other`` should only be a sequence object.
Used within :class:`SeqAdd` class.
"""
return None
def _mul(self, other):
"""
Should only be used internally.
Explanation
===========
self._mul(other) returns a new, term-wise multiplied sequence if self
knows how to multiply with other, otherwise it returns ``None``.
``other`` should only be a sequence object.
Used within :class:`SeqMul` class.
"""
return None
def coeff_mul(self, other):
"""
Should be used when ``other`` is not a sequence. Should be
defined to define custom behaviour.
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n
>>> SeqFormula(n**2).coeff_mul(2)
SeqFormula(2*n**2, (n, 0, oo))
Notes
=====
'*' defines multiplication of sequences with sequences only.
"""
return Mul(self, other)
def __add__(self, other):
"""Returns the term-wise addition of 'self' and 'other'.
``other`` should be a sequence.
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n
>>> SeqFormula(n**2) + SeqFormula(n**3)
SeqFormula(n**3 + n**2, (n, 0, oo))
"""
if not isinstance(other, SeqBase):
raise TypeError('cannot add sequence and %s' % type(other))
return SeqAdd(self, other)
@call_highest_priority('__add__')
def __radd__(self, other):
return self + other
def __sub__(self, other):
"""Returns the term-wise subtraction of ``self`` and ``other``.
``other`` should be a sequence.
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n
>>> SeqFormula(n**2) - (SeqFormula(n))
SeqFormula(n**2 - n, (n, 0, oo))
"""
if not isinstance(other, SeqBase):
raise TypeError('cannot subtract sequence and %s' % type(other))
return SeqAdd(self, -other)
@call_highest_priority('__sub__')
def __rsub__(self, other):
return (-self) + other
def __neg__(self):
"""Negates the sequence.
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n
>>> -SeqFormula(n**2)
SeqFormula(-n**2, (n, 0, oo))
"""
return self.coeff_mul(-1)
def __mul__(self, other):
"""Returns the term-wise multiplication of 'self' and 'other'.
``other`` should be a sequence. For ``other`` not being a
sequence see :func:`coeff_mul` method.
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n
>>> SeqFormula(n**2) * (SeqFormula(n))
SeqFormula(n**3, (n, 0, oo))
"""
if not isinstance(other, SeqBase):
raise TypeError('cannot multiply sequence and %s' % type(other))
return SeqMul(self, other)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return self * other
def __iter__(self):
for i in range(self.length):
pt = self._ith_point(i)
yield self.coeff(pt)
def __getitem__(self, index):
if isinstance(index, int):
index = self._ith_point(index)
return self.coeff(index)
elif isinstance(index, slice):
start, stop = index.start, index.stop
if start is None:
start = 0
if stop is None:
stop = self.length
return [self.coeff(self._ith_point(i)) for i in
range(start, stop, index.step or 1)]
def find_linear_recurrence(self,n,d=None,gfvar=None):
r"""
Finds the shortest linear recurrence that satisfies the first n
terms of sequence of order `\leq` ``n/2`` if possible.
If ``d`` is specified, find shortest linear recurrence of order
`\leq` min(d, n/2) if possible.
Returns list of coefficients ``[b(1), b(2), ...]`` corresponding to the
recurrence relation ``x(n) = b(1)*x(n-1) + b(2)*x(n-2) + ...``
Returns ``[]`` if no recurrence is found.
If gfvar is specified, also returns ordinary generating function as a
function of gfvar.
Examples
========
>>> from sympy import sequence, sqrt, oo, lucas
>>> from sympy.abc import n, x, y
>>> sequence(n**2).find_linear_recurrence(10, 2)
[]
>>> sequence(n**2).find_linear_recurrence(10)
[3, -3, 1]
>>> sequence(2**n).find_linear_recurrence(10)
[2]
>>> sequence(23*n**4+91*n**2).find_linear_recurrence(10)
[5, -10, 10, -5, 1]
>>> sequence(sqrt(5)*(((1 + sqrt(5))/2)**n - (-(1 + sqrt(5))/2)**(-n))/5).find_linear_recurrence(10)
[1, 1]
>>> sequence(x+y*(-2)**(-n), (n, 0, oo)).find_linear_recurrence(30)
[1/2, 1/2]
>>> sequence(3*5**n + 12).find_linear_recurrence(20,gfvar=x)
([6, -5], 3*(5 - 21*x)/((x - 1)*(5*x - 1)))
>>> sequence(lucas(n)).find_linear_recurrence(15,gfvar=x)
([1, 1], (x - 2)/(x**2 + x - 1))
"""
from sympy.simplify import simplify
x = [simplify(expand(t)) for t in self[:n]]
lx = len(x)
if d is None:
r = lx//2
else:
r = min(d,lx//2)
coeffs = []
for l in range(1, r+1):
l2 = 2*l
mlist = []
for k in range(l):
mlist.append(x[k:k+l])
m = Matrix(mlist)
if m.det() != 0:
y = simplify(m.LUsolve(Matrix(x[l:l2])))
if lx == l2:
coeffs = flatten(y[::-1])
break
mlist = []
for k in range(l,lx-l):
mlist.append(x[k:k+l])
m = Matrix(mlist)
if m*y == Matrix(x[l2:]):
coeffs = flatten(y[::-1])
break
if gfvar is None:
return coeffs
else:
l = len(coeffs)
if l == 0:
return [], None
else:
n, d = x[l-1]*gfvar**(l-1), 1 - coeffs[l-1]*gfvar**l
for i in range(l-1):
n += x[i]*gfvar**i
for j in range(l-i-1):
n -= coeffs[i]*x[j]*gfvar**(i+j+1)
d -= coeffs[i]*gfvar**(i+1)
return coeffs, simplify(factor(n)/factor(d))
class EmptySequence(SeqBase, metaclass=Singleton):
"""Represents an empty sequence.
The empty sequence is also available as a singleton as
``S.EmptySequence``.
Examples
========
>>> from sympy import EmptySequence, SeqPer
>>> from sympy.abc import x
>>> EmptySequence
EmptySequence
>>> SeqPer((1, 2), (x, 0, 10)) + EmptySequence
SeqPer((1, 2), (x, 0, 10))
>>> SeqPer((1, 2)) * EmptySequence
EmptySequence
>>> EmptySequence.coeff_mul(-1)
EmptySequence
"""
@property
def interval(self):
return S.EmptySet
@property
def length(self):
return S.Zero
def coeff_mul(self, coeff):
"""See docstring of SeqBase.coeff_mul"""
return self
def __iter__(self):
return iter([])
class SeqExpr(SeqBase):
"""Sequence expression class.
Various sequences should inherit from this class.
Examples
========
>>> from sympy.series.sequences import SeqExpr
>>> from sympy.abc import x
>>> from sympy import Tuple
>>> s = SeqExpr(Tuple(1, 2, 3), Tuple(x, 0, 10))
>>> s.gen
(1, 2, 3)
>>> s.interval
Interval(0, 10)
>>> s.length
11
See Also
========
sympy.series.sequences.SeqPer
sympy.series.sequences.SeqFormula
"""
@property
def gen(self):
return self.args[0]
@property
def interval(self):
return Interval(self.args[1][1], self.args[1][2])
@property
def start(self):
return self.interval.inf
@property
def stop(self):
return self.interval.sup
@property
def length(self):
return self.stop - self.start + 1
@property
def variables(self):
return (self.args[1][0],)
class SeqPer(SeqExpr):
"""
Represents a periodic sequence.
The elements are repeated after a given period.
Examples
========
>>> from sympy import SeqPer, oo
>>> from sympy.abc import k
>>> s = SeqPer((1, 2, 3), (0, 5))
>>> s.periodical
(1, 2, 3)
>>> s.period
3
For value at a particular point
>>> s.coeff(3)
1
supports slicing
>>> s[:]
[1, 2, 3, 1, 2, 3]
iterable
>>> list(s)
[1, 2, 3, 1, 2, 3]
sequence starts from negative infinity
>>> SeqPer((1, 2, 3), (-oo, 0))[0:6]
[1, 2, 3, 1, 2, 3]
Periodic formulas
>>> SeqPer((k, k**2, k**3), (k, 0, oo))[0:6]
[0, 1, 8, 3, 16, 125]
See Also
========
sympy.series.sequences.SeqFormula
"""
def __new__(cls, periodical, limits=None):
periodical = sympify(periodical)
def _find_x(periodical):
free = periodical.free_symbols
if len(periodical.free_symbols) == 1:
return free.pop()
else:
return Dummy('k')
x, start, stop = None, None, None
if limits is None:
x, start, stop = _find_x(periodical), 0, S.Infinity
if is_sequence(limits, Tuple):
if len(limits) == 3:
x, start, stop = limits
elif len(limits) == 2:
x = _find_x(periodical)
start, stop = limits
if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
raise ValueError('Invalid limits given: %s' % str(limits))
if start is S.NegativeInfinity and stop is S.Infinity:
raise ValueError("Both the start and end value"
"cannot be unbounded")
limits = sympify((x, start, stop))
if is_sequence(periodical, Tuple):
periodical = sympify(tuple(flatten(periodical)))
else:
raise ValueError("invalid period %s should be something "
"like e.g (1, 2) " % periodical)
if Interval(limits[1], limits[2]) is S.EmptySet:
return S.EmptySequence
return Basic.__new__(cls, periodical, limits)
@property
def period(self):
return len(self.gen)
@property
def periodical(self):
return self.gen
def _eval_coeff(self, pt):
if self.start is S.NegativeInfinity:
idx = (self.stop - pt) % self.period
else:
idx = (pt - self.start) % self.period
return self.periodical[idx].subs(self.variables[0], pt)
def _add(self, other):
"""See docstring of SeqBase._add"""
if isinstance(other, SeqPer):
per1, lper1 = self.periodical, self.period
per2, lper2 = other.periodical, other.period
per_length = lcm(lper1, lper2)
new_per = []
for x in range(per_length):
ele1 = per1[x % lper1]
ele2 = per2[x % lper2]
new_per.append(ele1 + ele2)
start, stop = self._intersect_interval(other)
return SeqPer(new_per, (self.variables[0], start, stop))
def _mul(self, other):
"""See docstring of SeqBase._mul"""
if isinstance(other, SeqPer):
per1, lper1 = self.periodical, self.period
per2, lper2 = other.periodical, other.period
per_length = lcm(lper1, lper2)
new_per = []
for x in range(per_length):
ele1 = per1[x % lper1]
ele2 = per2[x % lper2]
new_per.append(ele1 * ele2)
start, stop = self._intersect_interval(other)
return SeqPer(new_per, (self.variables[0], start, stop))
def coeff_mul(self, coeff):
"""See docstring of SeqBase.coeff_mul"""
coeff = sympify(coeff)
per = [x * coeff for x in self.periodical]
return SeqPer(per, self.args[1])
class SeqFormula(SeqExpr):
"""
Represents sequence based on a formula.
Elements are generated using a formula.
Examples
========
>>> from sympy import SeqFormula, oo, Symbol
>>> n = Symbol('n')
>>> s = SeqFormula(n**2, (n, 0, 5))
>>> s.formula
n**2
For value at a particular point
>>> s.coeff(3)
9
supports slicing
>>> s[:]
[0, 1, 4, 9, 16, 25]
iterable
>>> list(s)
[0, 1, 4, 9, 16, 25]
sequence starts from negative infinity
>>> SeqFormula(n**2, (-oo, 0))[0:6]
[0, 1, 4, 9, 16, 25]
See Also
========
sympy.series.sequences.SeqPer
"""
def __new__(cls, formula, limits=None):
formula = sympify(formula)
def _find_x(formula):
free = formula.free_symbols
if len(free) == 1:
return free.pop()
elif not free:
return Dummy('k')
else:
raise ValueError(
" specify dummy variables for %s. If the formula contains"
" more than one free symbol, a dummy variable should be"
" supplied explicitly e.g., SeqFormula(m*n**2, (n, 0, 5))"
% formula)
x, start, stop = None, None, None
if limits is None:
x, start, stop = _find_x(formula), 0, S.Infinity
if is_sequence(limits, Tuple):
if len(limits) == 3:
x, start, stop = limits
elif len(limits) == 2:
x = _find_x(formula)
start, stop = limits
if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
raise ValueError('Invalid limits given: %s' % str(limits))
if start is S.NegativeInfinity and stop is S.Infinity:
raise ValueError("Both the start and end value "
"cannot be unbounded")
limits = sympify((x, start, stop))
if Interval(limits[1], limits[2]) is S.EmptySet:
return S.EmptySequence
return Basic.__new__(cls, formula, limits)
@property
def formula(self):
return self.gen
def _eval_coeff(self, pt):
d = self.variables[0]
return self.formula.subs(d, pt)
def _add(self, other):
"""See docstring of SeqBase._add"""
if isinstance(other, SeqFormula):
form1, v1 = self.formula, self.variables[0]
form2, v2 = other.formula, other.variables[0]
formula = form1 + form2.subs(v2, v1)
start, stop = self._intersect_interval(other)
return SeqFormula(formula, (v1, start, stop))
def _mul(self, other):
"""See docstring of SeqBase._mul"""
if isinstance(other, SeqFormula):
form1, v1 = self.formula, self.variables[0]
form2, v2 = other.formula, other.variables[0]
formula = form1 * form2.subs(v2, v1)
start, stop = self._intersect_interval(other)
return SeqFormula(formula, (v1, start, stop))
def coeff_mul(self, coeff):
"""See docstring of SeqBase.coeff_mul"""
coeff = sympify(coeff)
formula = self.formula * coeff
return SeqFormula(formula, self.args[1])
def expand(self, *args, **kwargs):
return SeqFormula(expand(self.formula, *args, **kwargs), self.args[1])
class RecursiveSeq(SeqBase):
"""
A finite degree recursive sequence.
Explanation
===========
That is, a sequence a(n) that depends on a fixed, finite number of its
previous values. The general form is
a(n) = f(a(n - 1), a(n - 2), ..., a(n - d))
for some fixed, positive integer d, where f is some function defined by a
SymPy expression.
Parameters
==========
recurrence : SymPy expression defining recurrence
This is *not* an equality, only the expression that the nth term is
equal to. For example, if :code:`a(n) = f(a(n - 1), ..., a(n - d))`,
then the expression should be :code:`f(a(n - 1), ..., a(n - d))`.
yn : applied undefined function
Represents the nth term of the sequence as e.g. :code:`y(n)` where
:code:`y` is an undefined function and `n` is the sequence index.
n : symbolic argument
The name of the variable that the recurrence is in, e.g., :code:`n` if
the recurrence function is :code:`y(n)`.
initial : iterable with length equal to the degree of the recurrence
The initial values of the recurrence.
start : start value of sequence (inclusive)
Examples
========
>>> from sympy import Function, symbols
>>> from sympy.series.sequences import RecursiveSeq
>>> y = Function("y")
>>> n = symbols("n")
>>> fib = RecursiveSeq(y(n - 1) + y(n - 2), y(n), n, [0, 1])
>>> fib.coeff(3) # Value at a particular point
2
>>> fib[:6] # supports slicing
[0, 1, 1, 2, 3, 5]
>>> fib.recurrence # inspect recurrence
Eq(y(n), y(n - 2) + y(n - 1))
>>> fib.degree # automatically determine degree
2
>>> for x in zip(range(10), fib): # supports iteration
... print(x)
(0, 0)
(1, 1)
(2, 1)
(3, 2)
(4, 3)
(5, 5)
(6, 8)
(7, 13)
(8, 21)
(9, 34)
See Also
========
sympy.series.sequences.SeqFormula
"""
def __new__(cls, recurrence, yn, n, initial=None, start=0):
if not isinstance(yn, AppliedUndef):
raise TypeError("recurrence sequence must be an applied undefined function"
", found `{}`".format(yn))
if not isinstance(n, Basic) or not n.is_symbol:
raise TypeError("recurrence variable must be a symbol"
", found `{}`".format(n))
if yn.args != (n,):
raise TypeError("recurrence sequence does not match symbol")
y = yn.func
k = Wild("k", exclude=(n,))
degree = 0
# Find all applications of y in the recurrence and check that:
# 1. The function y is only being used with a single argument; and
# 2. All arguments are n + k for constant negative integers k.
prev_ys = recurrence.find(y)
for prev_y in prev_ys:
if len(prev_y.args) != 1:
raise TypeError("Recurrence should be in a single variable")
shift = prev_y.args[0].match(n + k)[k]
if not (shift.is_constant() and shift.is_integer and shift < 0):
raise TypeError("Recurrence should have constant,"
" negative, integer shifts"
" (found {})".format(prev_y))
if -shift > degree:
degree = -shift
if not initial:
initial = [Dummy("c_{}".format(k)) for k in range(degree)]
if len(initial) != degree:
raise ValueError("Number of initial terms must equal degree")
degree = Integer(degree)
start = sympify(start)
initial = Tuple(*(sympify(x) for x in initial))
seq = Basic.__new__(cls, recurrence, yn, n, initial, start)
seq.cache = {y(start + k): init for k, init in enumerate(initial)}
seq.degree = degree
return seq
@property
def _recurrence(self):
"""Equation defining recurrence."""
return self.args[0]
@property
def recurrence(self):
"""Equation defining recurrence."""
return Eq(self.yn, self.args[0])
@property
def yn(self):
"""Applied function representing the nth term"""
return self.args[1]
@property
def y(self):
"""Undefined function for the nth term of the sequence"""
return self.yn.func
@property
def n(self):
"""Sequence index symbol"""
return self.args[2]
@property
def initial(self):
"""The initial values of the sequence"""
return self.args[3]
@property
def start(self):
"""The starting point of the sequence. This point is included"""
return self.args[4]
@property
def stop(self):
"""The ending point of the sequence. (oo)"""
return S.Infinity
@property
def interval(self):
"""Interval on which sequence is defined."""
return (self.start, S.Infinity)
def _eval_coeff(self, index):
if index - self.start < len(self.cache):
return self.cache[self.y(index)]
for current in range(len(self.cache), index + 1):
# Use xreplace over subs for performance.
# See issue #10697.
seq_index = self.start + current
current_recurrence = self._recurrence.xreplace({self.n: seq_index})
new_term = current_recurrence.xreplace(self.cache)
self.cache[self.y(seq_index)] = new_term
return self.cache[self.y(self.start + current)]
def __iter__(self):
index = self.start
while True:
yield self._eval_coeff(index)
index += 1
def sequence(seq, limits=None):
"""
Returns appropriate sequence object.
Explanation
===========
If ``seq`` is a SymPy sequence, returns :class:`SeqPer` object
otherwise returns :class:`SeqFormula` object.
Examples
========
>>> from sympy import sequence
>>> from sympy.abc import n
>>> sequence(n**2, (n, 0, 5))
SeqFormula(n**2, (n, 0, 5))
>>> sequence((1, 2, 3), (n, 0, 5))
SeqPer((1, 2, 3), (n, 0, 5))
See Also
========
sympy.series.sequences.SeqPer
sympy.series.sequences.SeqFormula
"""
seq = sympify(seq)
if is_sequence(seq, Tuple):
return SeqPer(seq, limits)
else:
return SeqFormula(seq, limits)
###############################################################################
# OPERATIONS #
###############################################################################
class SeqExprOp(SeqBase):
"""
Base class for operations on sequences.
Examples
========
>>> from sympy.series.sequences import SeqExprOp, sequence
>>> from sympy.abc import n
>>> s1 = sequence(n**2, (n, 0, 10))
>>> s2 = sequence((1, 2, 3), (n, 5, 10))
>>> s = SeqExprOp(s1, s2)
>>> s.gen
(n**2, (1, 2, 3))
>>> s.interval
Interval(5, 10)
>>> s.length
6
See Also
========
sympy.series.sequences.SeqAdd
sympy.series.sequences.SeqMul
"""
@property
def gen(self):
"""Generator for the sequence.
returns a tuple of generators of all the argument sequences.
"""
return tuple(a.gen for a in self.args)
@property
def interval(self):
"""Sequence is defined on the intersection
of all the intervals of respective sequences
"""
return Intersection(*(a.interval for a in self.args))
@property
def start(self):
return self.interval.inf
@property
def stop(self):
return self.interval.sup
@property
def variables(self):
"""Cumulative of all the bound variables"""
return tuple(flatten([a.variables for a in self.args]))
@property
def length(self):
return self.stop - self.start + 1
class SeqAdd(SeqExprOp):
"""Represents term-wise addition of sequences.
Rules:
* The interval on which sequence is defined is the intersection
of respective intervals of sequences.
* Anything + :class:`EmptySequence` remains unchanged.
* Other rules are defined in ``_add`` methods of sequence classes.
Examples
========
>>> from sympy import EmptySequence, oo, SeqAdd, SeqPer, SeqFormula
>>> from sympy.abc import n
>>> SeqAdd(SeqPer((1, 2), (n, 0, oo)), EmptySequence)
SeqPer((1, 2), (n, 0, oo))
>>> SeqAdd(SeqPer((1, 2), (n, 0, 5)), SeqPer((1, 2), (n, 6, 10)))
EmptySequence
>>> SeqAdd(SeqPer((1, 2), (n, 0, oo)), SeqFormula(n**2, (n, 0, oo)))
SeqAdd(SeqFormula(n**2, (n, 0, oo)), SeqPer((1, 2), (n, 0, oo)))
>>> SeqAdd(SeqFormula(n**3), SeqFormula(n**2))
SeqFormula(n**3 + n**2, (n, 0, oo))
See Also
========
sympy.series.sequences.SeqMul
"""
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_parameters.evaluate)
# flatten inputs
args = list(args)
# adapted from sympy.sets.sets.Union
def _flatten(arg):
if isinstance(arg, SeqBase):
if isinstance(arg, SeqAdd):
return sum(map(_flatten, arg.args), [])
else:
return [arg]
if iterable(arg):
return sum(map(_flatten, arg), [])
raise TypeError("Input must be Sequences or "
" iterables of Sequences")
args = _flatten(args)
args = [a for a in args if a is not S.EmptySequence]
# Addition of no sequences is EmptySequence
if not args:
return S.EmptySequence
if Intersection(*(a.interval for a in args)) is S.EmptySet:
return S.EmptySequence
# reduce using known rules
if evaluate:
return SeqAdd.reduce(args)
args = list(ordered(args, SeqBase._start_key))
return Basic.__new__(cls, *args)
@staticmethod
def reduce(args):
"""Simplify :class:`SeqAdd` using known rules.
Iterates through all pairs and ask the constituent
sequences if they can simplify themselves with any other constituent.
Notes
=====
adapted from ``Union.reduce``
"""
new_args = True
while new_args:
for id1, s in enumerate(args):
new_args = False
for id2, t in enumerate(args):
if id1 == id2:
continue
new_seq = s._add(t)
# This returns None if s does not know how to add
# with t. Returns the newly added sequence otherwise
if new_seq is not None:
new_args = [a for a in args if a not in (s, t)]
new_args.append(new_seq)
break
if new_args:
args = new_args
break
if len(args) == 1:
return args.pop()
else:
return SeqAdd(args, evaluate=False)
def _eval_coeff(self, pt):
"""adds up the coefficients of all the sequences at point pt"""
return sum(a.coeff(pt) for a in self.args)
class SeqMul(SeqExprOp):
r"""Represents term-wise multiplication of sequences.
Explanation
===========
Handles multiplication of sequences only. For multiplication
with other objects see :func:`SeqBase.coeff_mul`.
Rules:
* The interval on which sequence is defined is the intersection
of respective intervals of sequences.
* Anything \* :class:`EmptySequence` returns :class:`EmptySequence`.
* Other rules are defined in ``_mul`` methods of sequence classes.
Examples
========
>>> from sympy import EmptySequence, oo, SeqMul, SeqPer, SeqFormula
>>> from sympy.abc import n
>>> SeqMul(SeqPer((1, 2), (n, 0, oo)), EmptySequence)
EmptySequence
>>> SeqMul(SeqPer((1, 2), (n, 0, 5)), SeqPer((1, 2), (n, 6, 10)))
EmptySequence
>>> SeqMul(SeqPer((1, 2), (n, 0, oo)), SeqFormula(n**2))
SeqMul(SeqFormula(n**2, (n, 0, oo)), SeqPer((1, 2), (n, 0, oo)))
>>> SeqMul(SeqFormula(n**3), SeqFormula(n**2))
SeqFormula(n**5, (n, 0, oo))
See Also
========
sympy.series.sequences.SeqAdd
"""
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_parameters.evaluate)
# flatten inputs
args = list(args)
# adapted from sympy.sets.sets.Union
def _flatten(arg):
if isinstance(arg, SeqBase):
if isinstance(arg, SeqMul):
return sum(map(_flatten, arg.args), [])
else:
return [arg]
elif iterable(arg):
return sum(map(_flatten, arg), [])
raise TypeError("Input must be Sequences or "
" iterables of Sequences")
args = _flatten(args)
# Multiplication of no sequences is EmptySequence
if not args:
return S.EmptySequence
if Intersection(*(a.interval for a in args)) is S.EmptySet:
return S.EmptySequence
# reduce using known rules
if evaluate:
return SeqMul.reduce(args)
args = list(ordered(args, SeqBase._start_key))
return Basic.__new__(cls, *args)
@staticmethod
def reduce(args):
"""Simplify a :class:`SeqMul` using known rules.
Explanation
===========
Iterates through all pairs and ask the constituent
sequences if they can simplify themselves with any other constituent.
Notes
=====
adapted from ``Union.reduce``
"""
new_args = True
while new_args:
for id1, s in enumerate(args):
new_args = False
for id2, t in enumerate(args):
if id1 == id2:
continue
new_seq = s._mul(t)
# This returns None if s does not know how to multiply
# with t. Returns the newly multiplied sequence otherwise
if new_seq is not None:
new_args = [a for a in args if a not in (s, t)]
new_args.append(new_seq)
break
if new_args:
args = new_args
break
if len(args) == 1:
return args.pop()
else:
return SeqMul(args, evaluate=False)
def _eval_coeff(self, pt):
"""multiplies the coefficients of all the sequences at point pt"""
val = 1
for a in self.args:
val *= a.coeff(pt)
return val
|
42309439a9c8de27afd0faa58f995a15aa162ddeadd42b9ac882ffb9f2f30274 | from sympy.calculus.accumulationbounds import AccumBounds
from sympy.core import S, Symbol, Add, sympify, Expr, PoleError, Mul
from sympy.core.exprtools import factor_terms
from sympy.core.numbers import Float, _illegal
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import (Abs, sign)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.special.gamma_functions import gamma
from sympy.polys import PolynomialError, factor
from sympy.series.order import Order
from .gruntz import gruntz
def limit(e, z, z0, dir="+"):
"""Computes the limit of ``e(z)`` at the point ``z0``.
Parameters
==========
e : expression, the limit of which is to be taken
z : symbol representing the variable in the limit.
Other symbols are treated as constants. Multivariate limits
are not supported.
z0 : the value toward which ``z`` tends. Can be any expression,
including ``oo`` and ``-oo``.
dir : string, optional (default: "+")
The limit is bi-directional if ``dir="+-"``, from the right
(z->z0+) if ``dir="+"``, and from the left (z->z0-) if
``dir="-"``. For infinite ``z0`` (``oo`` or ``-oo``), the ``dir``
argument is determined from the direction of the infinity
(i.e., ``dir="-"`` for ``oo``).
Examples
========
>>> from sympy import limit, sin, oo
>>> from sympy.abc import x
>>> limit(sin(x)/x, x, 0)
1
>>> limit(1/x, x, 0) # default dir='+'
oo
>>> limit(1/x, x, 0, dir="-")
-oo
>>> limit(1/x, x, 0, dir='+-')
zoo
>>> limit(1/x, x, oo)
0
Notes
=====
First we try some heuristics for easy and frequent cases like "x", "1/x",
"x**2" and similar, so that it's fast. For all other cases, we use the
Gruntz algorithm (see the gruntz() function).
See Also
========
limit_seq : returns the limit of a sequence.
"""
return Limit(e, z, z0, dir).doit(deep=False)
def heuristics(e, z, z0, dir):
"""Computes the limit of an expression term-wise.
Parameters are the same as for the ``limit`` function.
Works with the arguments of expression ``e`` one by one, computing
the limit of each and then combining the results. This approach
works only for simple limits, but it is fast.
"""
rv = None
if abs(z0) is S.Infinity:
rv = limit(e.subs(z, 1/z), z, S.Zero, "+" if z0 is S.Infinity else "-")
if isinstance(rv, Limit):
return
elif e.is_Mul or e.is_Add or e.is_Pow or e.is_Function:
r = []
from sympy.simplify.simplify import together
for a in e.args:
l = limit(a, z, z0, dir)
if l.has(S.Infinity) and l.is_finite is None:
if isinstance(e, Add):
m = factor_terms(e)
if not isinstance(m, Mul): # try together
m = together(m)
if not isinstance(m, Mul): # try factor if the previous methods failed
m = factor(e)
if isinstance(m, Mul):
return heuristics(m, z, z0, dir)
return
return
elif isinstance(l, Limit):
return
elif l is S.NaN:
return
else:
r.append(l)
if r:
rv = e.func(*r)
if rv is S.NaN and e.is_Mul and any(isinstance(rr, AccumBounds) for rr in r):
r2 = []
e2 = []
for ii in range(len(r)):
if isinstance(r[ii], AccumBounds):
r2.append(r[ii])
else:
e2.append(e.args[ii])
if len(e2) > 0:
e3 = Mul(*e2).simplify()
l = limit(e3, z, z0, dir)
rv = l * Mul(*r2)
if rv is S.NaN:
try:
from sympy.simplify.ratsimp import ratsimp
rat_e = ratsimp(e)
except PolynomialError:
return
if rat_e is S.NaN or rat_e == e:
return
return limit(rat_e, z, z0, dir)
return rv
class Limit(Expr):
"""Represents an unevaluated limit.
Examples
========
>>> from sympy import Limit, sin
>>> from sympy.abc import x
>>> Limit(sin(x)/x, x, 0)
Limit(sin(x)/x, x, 0)
>>> Limit(1/x, x, 0, dir="-")
Limit(1/x, x, 0, dir='-')
"""
def __new__(cls, e, z, z0, dir="+"):
e = sympify(e)
z = sympify(z)
z0 = sympify(z0)
if z0 is S.Infinity:
dir = "-"
elif z0 is S.NegativeInfinity:
dir = "+"
if(z0.has(z)):
raise NotImplementedError("Limits approaching a variable point are"
" not supported (%s -> %s)" % (z, z0))
if isinstance(dir, str):
dir = Symbol(dir)
elif not isinstance(dir, Symbol):
raise TypeError("direction must be of type basestring or "
"Symbol, not %s" % type(dir))
if str(dir) not in ('+', '-', '+-'):
raise ValueError("direction must be one of '+', '-' "
"or '+-', not %s" % dir)
obj = Expr.__new__(cls)
obj._args = (e, z, z0, dir)
return obj
@property
def free_symbols(self):
e = self.args[0]
isyms = e.free_symbols
isyms.difference_update(self.args[1].free_symbols)
isyms.update(self.args[2].free_symbols)
return isyms
def pow_heuristics(self, e):
_, z, z0, _ = self.args
b1, e1 = e.base, e.exp
if not b1.has(z):
res = limit(e1*log(b1), z, z0)
return exp(res)
ex_lim = limit(e1, z, z0)
base_lim = limit(b1, z, z0)
if base_lim is S.One:
if ex_lim in (S.Infinity, S.NegativeInfinity):
res = limit(e1*(b1 - 1), z, z0)
return exp(res)
if base_lim is S.NegativeInfinity and ex_lim is S.Infinity:
return S.ComplexInfinity
def doit(self, **hints):
"""Evaluates the limit.
Parameters
==========
deep : bool, optional (default: True)
Invoke the ``doit`` method of the expressions involved before
taking the limit.
hints : optional keyword arguments
To be passed to ``doit`` methods; only used if deep is True.
"""
e, z, z0, dir = self.args
if z0 is S.ComplexInfinity:
raise NotImplementedError("Limits at complex "
"infinity are not implemented")
if hints.get('deep', True):
e = e.doit(**hints)
z = z.doit(**hints)
z0 = z0.doit(**hints)
if e == z:
return z0
if not e.has(z):
return e
if z0 is S.NaN:
return S.NaN
if e.has(*_illegal):
return self
if e.is_Order:
return Order(limit(e.expr, z, z0), *e.args[1:])
cdir = 0
if str(dir) == "+":
cdir = 1
elif str(dir) == "-":
cdir = -1
def set_signs(expr):
if not expr.args:
return expr
newargs = tuple(set_signs(arg) for arg in expr.args)
if newargs != expr.args:
expr = expr.func(*newargs)
abs_flag = isinstance(expr, Abs)
sign_flag = isinstance(expr, sign)
if abs_flag or sign_flag:
sig = limit(expr.args[0], z, z0, dir)
if sig.is_zero:
sig = limit(1/expr.args[0], z, z0, dir)
if sig.is_extended_real:
if (sig < 0) == True:
return -expr.args[0] if abs_flag else S.NegativeOne
elif (sig > 0) == True:
return expr.args[0] if abs_flag else S.One
return expr
if e.has(Float):
# Convert floats like 0.5 to exact SymPy numbers like S.Half, to
# prevent rounding errors which can lead to unexpected execution
# of conditional blocks that work on comparisons
# Also see comments in https://github.com/sympy/sympy/issues/19453
from sympy.simplify.simplify import nsimplify
e = nsimplify(e)
e = set_signs(e)
if e.is_meromorphic(z, z0):
if abs(z0) is S.Infinity:
newe = e.subs(z, 1/z)
# cdir changes sign as oo- should become 0+
cdir = -cdir
else:
newe = e.subs(z, z + z0)
try:
coeff, ex = newe.leadterm(z, cdir=cdir)
except ValueError:
pass
else:
if ex > 0:
return S.Zero
elif ex == 0:
return coeff
if cdir == 1 or not(int(ex) & 1):
return S.Infinity*sign(coeff)
elif cdir == -1:
return S.NegativeInfinity*sign(coeff)
else:
return S.ComplexInfinity
if abs(z0) is S.Infinity:
if e.is_Mul:
e = factor_terms(e)
newe = e.subs(z, 1/z)
# cdir changes sign as oo- should become 0+
cdir = -cdir
else:
newe = e.subs(z, z + z0)
try:
coeff, ex = newe.leadterm(z, cdir=cdir)
except (ValueError, NotImplementedError, PoleError):
# The NotImplementedError catching is for custom functions
from sympy.simplify.powsimp import powsimp
e = powsimp(e)
if e.is_Pow:
r = self.pow_heuristics(e)
if r is not None:
return r
else:
if isinstance(coeff, AccumBounds) and ex == S.Zero:
return coeff
if coeff.has(S.Infinity, S.NegativeInfinity, S.ComplexInfinity, S.NaN):
return self
if not coeff.has(z):
if ex.is_positive:
return S.Zero
elif ex == 0:
return coeff
elif ex.is_negative:
if ex.is_integer:
if cdir == 1 or ex.is_even:
return S.Infinity*sign(coeff)
elif cdir == -1:
return S.NegativeInfinity*sign(coeff)
else:
return S.ComplexInfinity
else:
if cdir == 1:
return S.Infinity*sign(coeff)
elif cdir == -1:
return S.Infinity*sign(coeff)*S.NegativeOne**ex
else:
return S.ComplexInfinity
# gruntz fails on factorials but works with the gamma function
# If no factorial term is present, e should remain unchanged.
# factorial is defined to be zero for negative inputs (which
# differs from gamma) so only rewrite for positive z0.
if z0.is_extended_positive:
e = e.rewrite(factorial, gamma)
l = None
try:
if str(dir) == '+-':
r = gruntz(e, z, z0, '+')
l = gruntz(e, z, z0, '-')
if l != r:
raise ValueError("The limit does not exist since "
"left hand limit = %s and right hand limit = %s"
% (l, r))
else:
r = gruntz(e, z, z0, dir)
if r is S.NaN or l is S.NaN:
raise PoleError()
except (PoleError, ValueError):
if l is not None:
raise
r = heuristics(e, z, z0, dir)
if r is None:
return self
return r
|
4015a68fd540d5f96a38513ad381f56061366b5747369a06022bba6d382bcc0c | """Fourier Series"""
from sympy.core.numbers import (oo, pi)
from sympy.core.symbol import Wild
from sympy.core.expr import Expr
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.singleton import S
from sympy.core.symbol import Dummy, Symbol
from sympy.core.sympify import sympify
from sympy.functions.elementary.trigonometric import sin, cos, sinc
from sympy.series.series_class import SeriesBase
from sympy.series.sequences import SeqFormula
from sympy.sets.sets import Interval
from sympy.utilities.iterables import is_sequence
def fourier_cos_seq(func, limits, n):
"""Returns the cos sequence in a Fourier series"""
from sympy.integrals import integrate
x, L = limits[0], limits[2] - limits[1]
cos_term = cos(2*n*pi*x / L)
formula = 2 * cos_term * integrate(func * cos_term, limits) / L
a0 = formula.subs(n, S.Zero) / 2
return a0, SeqFormula(2 * cos_term * integrate(func * cos_term, limits)
/ L, (n, 1, oo))
def fourier_sin_seq(func, limits, n):
"""Returns the sin sequence in a Fourier series"""
from sympy.integrals import integrate
x, L = limits[0], limits[2] - limits[1]
sin_term = sin(2*n*pi*x / L)
return SeqFormula(2 * sin_term * integrate(func * sin_term, limits)
/ L, (n, 1, oo))
def _process_limits(func, limits):
"""
Limits should be of the form (x, start, stop).
x should be a symbol. Both start and stop should be bounded.
Explanation
===========
* If x is not given, x is determined from func.
* If limits is None. Limit of the form (x, -pi, pi) is returned.
Examples
========
>>> from sympy.series.fourier import _process_limits as pari
>>> from sympy.abc import x
>>> pari(x**2, (x, -2, 2))
(x, -2, 2)
>>> pari(x**2, (-2, 2))
(x, -2, 2)
>>> pari(x**2, None)
(x, -pi, pi)
"""
def _find_x(func):
free = func.free_symbols
if len(free) == 1:
return free.pop()
elif not free:
return Dummy('k')
else:
raise ValueError(
" specify dummy variables for %s. If the function contains"
" more than one free symbol, a dummy variable should be"
" supplied explicitly e.g. FourierSeries(m*n**2, (n, -pi, pi))"
% func)
x, start, stop = None, None, None
if limits is None:
x, start, stop = _find_x(func), -pi, pi
if is_sequence(limits, Tuple):
if len(limits) == 3:
x, start, stop = limits
elif len(limits) == 2:
x = _find_x(func)
start, stop = limits
if not isinstance(x, Symbol) or start is None or stop is None:
raise ValueError('Invalid limits given: %s' % str(limits))
unbounded = [S.NegativeInfinity, S.Infinity]
if start in unbounded or stop in unbounded:
raise ValueError("Both the start and end value should be bounded")
return sympify((x, start, stop))
def finite_check(f, x, L):
def check_fx(exprs, x):
return x not in exprs.free_symbols
def check_sincos(_expr, x, L):
if isinstance(_expr, (sin, cos)):
sincos_args = _expr.args[0]
if sincos_args.match(a*(pi/L)*x + b) is not None:
return True
else:
return False
from sympy.simplify.fu import TR2, TR1, sincos_to_sum
_expr = sincos_to_sum(TR2(TR1(f)))
add_coeff = _expr.as_coeff_add()
a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k != S.Zero, ])
b = Wild('b', properties=[lambda k: x not in k.free_symbols, ])
for s in add_coeff[1]:
mul_coeffs = s.as_coeff_mul()[1]
for t in mul_coeffs:
if not (check_fx(t, x) or check_sincos(t, x, L)):
return False, f
return True, _expr
class FourierSeries(SeriesBase):
r"""Represents Fourier sine/cosine series.
Explanation
===========
This class only represents a fourier series.
No computation is performed.
For how to compute Fourier series, see the :func:`fourier_series`
docstring.
See Also
========
sympy.series.fourier.fourier_series
"""
def __new__(cls, *args):
args = map(sympify, args)
return Expr.__new__(cls, *args)
@property
def function(self):
return self.args[0]
@property
def x(self):
return self.args[1][0]
@property
def period(self):
return (self.args[1][1], self.args[1][2])
@property
def a0(self):
return self.args[2][0]
@property
def an(self):
return self.args[2][1]
@property
def bn(self):
return self.args[2][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 L(self):
return abs(self.period[1] - self.period[0]) / 2
def _eval_subs(self, old, new):
x = self.x
if old.has(x):
return self
def truncate(self, n=3):
"""
Return the first n nonzero terms of the series.
If ``n`` is None return an iterator.
Parameters
==========
n : int or None
Amount of non-zero terms in approximation or None.
Returns
=======
Expr or iterator :
Approximation of function expanded into Fourier series.
Examples
========
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> s = fourier_series(x, (x, -pi, pi))
>>> s.truncate(4)
2*sin(x) - sin(2*x) + 2*sin(3*x)/3 - sin(4*x)/2
See Also
========
sympy.series.fourier.FourierSeries.sigma_approximation
"""
if n is None:
return iter(self)
terms = []
for t in self:
if len(terms) == n:
break
if t is not S.Zero:
terms.append(t)
return Add(*terms)
def sigma_approximation(self, n=3):
r"""
Return :math:`\sigma`-approximation of Fourier series with respect
to order n.
Explanation
===========
Sigma approximation adjusts a Fourier summation to eliminate the Gibbs
phenomenon which would otherwise occur at discontinuities.
A sigma-approximated summation for a Fourier series of a T-periodical
function can be written as
.. math::
s(\theta) = \frac{1}{2} a_0 + \sum _{k=1}^{m-1}
\operatorname{sinc} \Bigl( \frac{k}{m} \Bigr) \cdot
\left[ a_k \cos \Bigl( \frac{2\pi k}{T} \theta \Bigr)
+ b_k \sin \Bigl( \frac{2\pi k}{T} \theta \Bigr) \right],
where :math:`a_0, a_k, b_k, k=1,\ldots,{m-1}` are standard Fourier
series coefficients and
:math:`\operatorname{sinc} \Bigl( \frac{k}{m} \Bigr)` is a Lanczos
:math:`\sigma` factor (expressed in terms of normalized
:math:`\operatorname{sinc}` function).
Parameters
==========
n : int
Highest order of the terms taken into account in approximation.
Returns
=======
Expr :
Sigma approximation of function expanded into Fourier series.
Examples
========
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> s = fourier_series(x, (x, -pi, pi))
>>> s.sigma_approximation(4)
2*sin(x)*sinc(pi/4) - 2*sin(2*x)/pi + 2*sin(3*x)*sinc(3*pi/4)/3
See Also
========
sympy.series.fourier.FourierSeries.truncate
Notes
=====
The behaviour of
:meth:`~sympy.series.fourier.FourierSeries.sigma_approximation`
is different from :meth:`~sympy.series.fourier.FourierSeries.truncate`
- it takes all nonzero terms of degree smaller than n, rather than
first n nonzero ones.
References
==========
.. [1] https://en.wikipedia.org/wiki/Gibbs_phenomenon
.. [2] https://en.wikipedia.org/wiki/Sigma_approximation
"""
terms = [sinc(pi * i / n) * t for i, t in enumerate(self[:n])
if t is not S.Zero]
return Add(*terms)
def shift(self, s):
"""
Shift the function by a term independent of x.
Explanation
===========
f(x) -> f(x) + s
This is fast, if Fourier series of f(x) is already
computed.
Examples
========
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> s = fourier_series(x**2, (x, -pi, pi))
>>> s.shift(1).truncate()
-4*cos(x) + cos(2*x) + 1 + pi**2/3
"""
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
a0 = self.a0 + s
sfunc = self.function + s
return self.func(sfunc, self.args[1], (a0, self.an, self.bn))
def shiftx(self, s):
"""
Shift x by a term independent of x.
Explanation
===========
f(x) -> f(x + s)
This is fast, if Fourier series of f(x) is already
computed.
Examples
========
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> s = fourier_series(x**2, (x, -pi, pi))
>>> s.shiftx(1).truncate()
-4*cos(x + 1) + cos(2*x + 2) + pi**2/3
"""
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
an = self.an.subs(x, x + s)
bn = self.bn.subs(x, x + s)
sfunc = self.function.subs(x, x + s)
return self.func(sfunc, self.args[1], (self.a0, an, bn))
def scale(self, s):
"""
Scale the function by a term independent of x.
Explanation
===========
f(x) -> s * f(x)
This is fast, if Fourier series of f(x) is already
computed.
Examples
========
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> s = fourier_series(x**2, (x, -pi, pi))
>>> s.scale(2).truncate()
-8*cos(x) + 2*cos(2*x) + 2*pi**2/3
"""
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
an = self.an.coeff_mul(s)
bn = self.bn.coeff_mul(s)
a0 = self.a0 * s
sfunc = self.args[0] * s
return self.func(sfunc, self.args[1], (a0, an, bn))
def scalex(self, s):
"""
Scale x by a term independent of x.
Explanation
===========
f(x) -> f(s*x)
This is fast, if Fourier series of f(x) is already
computed.
Examples
========
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> s = fourier_series(x**2, (x, -pi, pi))
>>> s.scalex(2).truncate()
-4*cos(2*x) + cos(4*x) + pi**2/3
"""
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
an = self.an.subs(x, x * s)
bn = self.bn.subs(x, x * s)
sfunc = self.function.subs(x, x * s)
return self.func(sfunc, self.args[1], (self.a0, an, bn))
def _eval_as_leading_term(self, x, logx=None, cdir=0):
for t in self:
if t is not S.Zero:
return t
def _eval_term(self, pt):
if pt == 0:
return self.a0
return self.an.coeff(pt) + self.bn.coeff(pt)
def __neg__(self):
return self.scale(-1)
def __add__(self, other):
if isinstance(other, FourierSeries):
if self.period != other.period:
raise ValueError("Both the series should have same periods")
x, y = self.x, other.x
function = self.function + other.function.subs(y, x)
if self.x not in function.free_symbols:
return function
an = self.an + other.an
bn = self.bn + other.bn
a0 = self.a0 + other.a0
return self.func(function, self.args[1], (a0, an, bn))
return Add(self, other)
def __sub__(self, other):
return self.__add__(-other)
class FiniteFourierSeries(FourierSeries):
r"""Represents Finite Fourier sine/cosine series.
For how to compute Fourier series, see the :func:`fourier_series`
docstring.
Parameters
==========
f : Expr
Expression for finding fourier_series
limits : ( x, start, stop)
x is the independent variable for the expression f
(start, stop) is the period of the fourier series
exprs: (a0, an, bn) or Expr
a0 is the constant term a0 of the fourier series
an is a dictionary of coefficients of cos terms
an[k] = coefficient of cos(pi*(k/L)*x)
bn is a dictionary of coefficients of sin terms
bn[k] = coefficient of sin(pi*(k/L)*x)
or exprs can be an expression to be converted to fourier form
Methods
=======
This class is an extension of FourierSeries class.
Please refer to sympy.series.fourier.FourierSeries for
further information.
See Also
========
sympy.series.fourier.FourierSeries
sympy.series.fourier.fourier_series
"""
def __new__(cls, f, limits, exprs):
f = sympify(f)
limits = sympify(limits)
exprs = sympify(exprs)
if not (isinstance(exprs, Tuple) and len(exprs) == 3): # exprs is not of form (a0, an, bn)
# Converts the expression to fourier form
c, e = exprs.as_coeff_add()
from sympy.simplify.fu import TR10
rexpr = c + Add(*[TR10(i) for i in e])
a0, exp_ls = rexpr.expand(trig=False, power_base=False, power_exp=False, log=False).as_coeff_add()
x = limits[0]
L = abs(limits[2] - limits[1]) / 2
a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k is not S.Zero, ])
b = Wild('b', properties=[lambda k: x not in k.free_symbols, ])
an = dict()
bn = dict()
# separates the coefficients of sin and cos terms in dictionaries an, and bn
for p in exp_ls:
t = p.match(b * cos(a * (pi / L) * x))
q = p.match(b * sin(a * (pi / L) * x))
if t:
an[t[a]] = t[b] + an.get(t[a], S.Zero)
elif q:
bn[q[a]] = q[b] + bn.get(q[a], S.Zero)
else:
a0 += p
exprs = Tuple(a0, an, bn)
return Expr.__new__(cls, f, limits, exprs)
@property
def interval(self):
_length = 1 if self.a0 else 0
_length += max(set(self.an.keys()).union(set(self.bn.keys()))) + 1
return Interval(0, _length)
@property
def length(self):
return self.stop - self.start
def shiftx(self, s):
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
_expr = self.truncate().subs(x, x + s)
sfunc = self.function.subs(x, x + s)
return self.func(sfunc, self.args[1], _expr)
def scale(self, s):
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
_expr = self.truncate() * s
sfunc = self.function * s
return self.func(sfunc, self.args[1], _expr)
def scalex(self, s):
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
_expr = self.truncate().subs(x, x * s)
sfunc = self.function.subs(x, x * s)
return self.func(sfunc, self.args[1], _expr)
def _eval_term(self, pt):
if pt == 0:
return self.a0
_term = self.an.get(pt, S.Zero) * cos(pt * (pi / self.L) * self.x) \
+ self.bn.get(pt, S.Zero) * sin(pt * (pi / self.L) * self.x)
return _term
def __add__(self, other):
if isinstance(other, FourierSeries):
return other.__add__(fourier_series(self.function, self.args[1],\
finite=False))
elif isinstance(other, FiniteFourierSeries):
if self.period != other.period:
raise ValueError("Both the series should have same periods")
x, y = self.x, other.x
function = self.function + other.function.subs(y, x)
if self.x not in function.free_symbols:
return function
return fourier_series(function, limits=self.args[1])
def fourier_series(f, limits=None, finite=True):
r"""Computes the Fourier trigonometric series expansion.
Explanation
===========
Fourier trigonometric series of $f(x)$ over the interval $(a, b)$
is defined as:
.. math::
\frac{a_0}{2} + \sum_{n=1}^{\infty}
(a_n \cos(\frac{2n \pi x}{L}) + b_n \sin(\frac{2n \pi x}{L}))
where the coefficients are:
.. math::
L = b - a
.. math::
a_0 = \frac{2}{L} \int_{a}^{b}{f(x) dx}
.. math::
a_n = \frac{2}{L} \int_{a}^{b}{f(x) \cos(\frac{2n \pi x}{L}) dx}
.. math::
b_n = \frac{2}{L} \int_{a}^{b}{f(x) \sin(\frac{2n \pi x}{L}) dx}
The condition whether the function $f(x)$ given should be periodic
or not is more than necessary, because it is sufficient to consider
the series to be converging to $f(x)$ only in the given interval,
not throughout the whole real line.
This also brings a lot of ease for the computation because
you do not have to make $f(x)$ artificially periodic by
wrapping it with piecewise, modulo operations,
but you can shape the function to look like the desired periodic
function only in the interval $(a, b)$, and the computed series will
automatically become the series of the periodic version of $f(x)$.
This property is illustrated in the examples section below.
Parameters
==========
limits : (sym, start, end), optional
*sym* denotes the symbol the series is computed with respect to.
*start* and *end* denotes the start and the end of the interval
where the fourier series converges to the given function.
Default range is specified as $-\pi$ and $\pi$.
Returns
=======
FourierSeries
A symbolic object representing the Fourier trigonometric series.
Examples
========
Computing the Fourier series of $f(x) = x^2$:
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> f = x**2
>>> s = fourier_series(f, (x, -pi, pi))
>>> s1 = s.truncate(n=3)
>>> s1
-4*cos(x) + cos(2*x) + pi**2/3
Shifting of the Fourier series:
>>> s.shift(1).truncate()
-4*cos(x) + cos(2*x) + 1 + pi**2/3
>>> s.shiftx(1).truncate()
-4*cos(x + 1) + cos(2*x + 2) + pi**2/3
Scaling of the Fourier series:
>>> s.scale(2).truncate()
-8*cos(x) + 2*cos(2*x) + 2*pi**2/3
>>> s.scalex(2).truncate()
-4*cos(2*x) + cos(4*x) + pi**2/3
Computing the Fourier series of $f(x) = x$:
This illustrates how truncating to the higher order gives better
convergence.
.. plot::
:context: reset
:format: doctest
:include-source: True
>>> from sympy import fourier_series, pi, plot
>>> from sympy.abc import x
>>> f = x
>>> s = fourier_series(f, (x, -pi, pi))
>>> s1 = s.truncate(n = 3)
>>> s2 = s.truncate(n = 5)
>>> s3 = s.truncate(n = 7)
>>> p = plot(f, s1, s2, s3, (x, -pi, pi), show=False, legend=True)
>>> p[0].line_color = (0, 0, 0)
>>> p[0].label = 'x'
>>> p[1].line_color = (0.7, 0.7, 0.7)
>>> p[1].label = 'n=3'
>>> p[2].line_color = (0.5, 0.5, 0.5)
>>> p[2].label = 'n=5'
>>> p[3].line_color = (0.3, 0.3, 0.3)
>>> p[3].label = 'n=7'
>>> p.show()
This illustrates how the series converges to different sawtooth
waves if the different ranges are specified.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> s1 = fourier_series(x, (x, -1, 1)).truncate(10)
>>> s2 = fourier_series(x, (x, -pi, pi)).truncate(10)
>>> s3 = fourier_series(x, (x, 0, 1)).truncate(10)
>>> p = plot(x, s1, s2, s3, (x, -5, 5), show=False, legend=True)
>>> p[0].line_color = (0, 0, 0)
>>> p[0].label = 'x'
>>> p[1].line_color = (0.7, 0.7, 0.7)
>>> p[1].label = '[-1, 1]'
>>> p[2].line_color = (0.5, 0.5, 0.5)
>>> p[2].label = '[-pi, pi]'
>>> p[3].line_color = (0.3, 0.3, 0.3)
>>> p[3].label = '[0, 1]'
>>> p.show()
Notes
=====
Computing Fourier series can be slow
due to the integration required in computing
an, bn.
It is faster to compute Fourier series of a function
by using shifting and scaling on an already
computed Fourier series rather than computing
again.
e.g. If the Fourier series of ``x**2`` is known
the Fourier series of ``x**2 - 1`` can be found by shifting by ``-1``.
See Also
========
sympy.series.fourier.FourierSeries
References
==========
.. [1] https://mathworld.wolfram.com/FourierSeries.html
"""
f = sympify(f)
limits = _process_limits(f, limits)
x = limits[0]
if x not in f.free_symbols:
return f
if finite:
L = abs(limits[2] - limits[1]) / 2
is_finite, res_f = finite_check(f, x, L)
if is_finite:
return FiniteFourierSeries(f, limits, res_f)
n = Dummy('n')
center = (limits[1] + limits[2]) / 2
if center.is_zero:
neg_f = f.subs(x, -x)
if f == neg_f:
a0, an = fourier_cos_seq(f, limits, n)
bn = SeqFormula(0, (1, oo))
return FourierSeries(f, limits, (a0, an, bn))
elif f == -neg_f:
a0 = S.Zero
an = SeqFormula(0, (1, oo))
bn = fourier_sin_seq(f, limits, n)
return FourierSeries(f, limits, (a0, an, bn))
a0, an = fourier_cos_seq(f, limits, n)
bn = fourier_sin_seq(f, limits, n)
return FourierSeries(f, limits, (a0, an, bn))
|
49acff54d886f12959478b6e55918db9387aca565d05edb84694056f7165dfc2 | """Formal Power Series"""
from collections import defaultdict
from sympy.core.numbers import (nan, oo, zoo)
from sympy.core.add import Add
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.series.sequences import sequence
from sympy.series.series_class import SeriesBase
from sympy.utilities.iterables import iterable
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)
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
from sympy.simplify.powsimp import powsimp
if symb.is_zero:
symb = S.One
else:
symb = powsimp(symb)
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, logx=None, 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 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 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 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)
|
7a17a315cfb1ea242314102419f61f6a74e84c7b135143bde59b935600cd9010 | from sympy.core import S, sympify, Expr, Dummy, Add, Mul
from sympy.core.cache import cacheit
from sympy.core.containers import Tuple
from sympy.core.function import Function, PoleError, expand_power_base, expand_log
from sympy.core.sorting import default_sort_key
from sympy.functions.elementary.exponential import exp, log
from sympy.sets.sets import Complement
from sympy.utilities.iterables import uniq, is_sequence
class Order(Expr):
r""" Represents the limiting behavior of some function.
Explanation
===========
The order of a function characterizes the function based on the limiting
behavior of the function as it goes to some limit. Only taking the limit
point to be a number is currently supported. This is expressed in
big O notation [1]_.
The formal definition for the order of a function `g(x)` about a point `a`
is such that `g(x) = O(f(x))` as `x \rightarrow a` if and only if for any
`\delta > 0` there exists a `M > 0` such that `|g(x)| \leq M|f(x)|` for
`|x-a| < \delta`. This is equivalent to `\lim_{x \rightarrow a}
\sup |g(x)/f(x)| < \infty`.
Let's illustrate it on the following example by taking the expansion of
`\sin(x)` about 0:
.. math ::
\sin(x) = x - x^3/3! + O(x^5)
where in this case `O(x^5) = x^5/5! - x^7/7! + \cdots`. By the definition
of `O`, for any `\delta > 0` there is an `M` such that:
.. math ::
|x^5/5! - x^7/7! + ....| <= M|x^5| \text{ for } |x| < \delta
or by the alternate definition:
.. math ::
\lim_{x \rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| < \infty
which surely is true, because
.. math ::
\lim_{x \rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| = 1/5!
As it is usually used, the order of a function can be intuitively thought
of representing all terms of powers greater than the one specified. For
example, `O(x^3)` corresponds to any terms proportional to `x^3,
x^4,\ldots` and any higher power. For a polynomial, this leaves terms
proportional to `x^2`, `x` and constants.
Examples
========
>>> from sympy import O, oo, cos, pi
>>> from sympy.abc import x, y
>>> O(x + x**2)
O(x)
>>> O(x + x**2, (x, 0))
O(x)
>>> O(x + x**2, (x, oo))
O(x**2, (x, oo))
>>> O(1 + x*y)
O(1, x, y)
>>> O(1 + x*y, (x, 0), (y, 0))
O(1, x, y)
>>> O(1 + x*y, (x, oo), (y, oo))
O(x*y, (x, oo), (y, oo))
>>> O(1) in O(1, x)
True
>>> O(1, x) in O(1)
False
>>> O(x) in O(1, x)
True
>>> O(x**2) in O(x)
True
>>> O(x)*x
O(x**2)
>>> O(x) - O(x)
O(x)
>>> O(cos(x))
O(1)
>>> O(cos(x), (x, pi/2))
O(x - pi/2, (x, pi/2))
References
==========
.. [1] `Big O notation <https://en.wikipedia.org/wiki/Big_O_notation>`_
Notes
=====
In ``O(f(x), x)`` the expression ``f(x)`` is assumed to have a leading
term. ``O(f(x), x)`` is automatically transformed to
``O(f(x).as_leading_term(x),x)``.
``O(expr*f(x), x)`` is ``O(f(x), x)``
``O(expr, x)`` is ``O(1)``
``O(0, x)`` is 0.
Multivariate O is also supported:
``O(f(x, y), x, y)`` is transformed to
``O(f(x, y).as_leading_term(x,y).as_leading_term(y), x, y)``
In the multivariate case, it is assumed the limits w.r.t. the various
symbols commute.
If no symbols are passed then all symbols in the expression are used
and the limit point is assumed to be zero.
"""
is_Order = True
__slots__ = ()
@cacheit
def __new__(cls, expr, *args, **kwargs):
expr = sympify(expr)
if not args:
if expr.is_Order:
variables = expr.variables
point = expr.point
else:
variables = list(expr.free_symbols)
point = [S.Zero]*len(variables)
else:
args = list(args if is_sequence(args) else [args])
variables, point = [], []
if is_sequence(args[0]):
for a in args:
v, p = list(map(sympify, a))
variables.append(v)
point.append(p)
else:
variables = list(map(sympify, args))
point = [S.Zero]*len(variables)
if not all(v.is_symbol for v in variables):
raise TypeError('Variables are not symbols, got %s' % variables)
if len(list(uniq(variables))) != len(variables):
raise ValueError('Variables are supposed to be unique symbols, got %s' % variables)
if expr.is_Order:
expr_vp = dict(expr.args[1:])
new_vp = dict(expr_vp)
vp = dict(zip(variables, point))
for v, p in vp.items():
if v in new_vp.keys():
if p != new_vp[v]:
raise NotImplementedError(
"Mixing Order at different points is not supported.")
else:
new_vp[v] = p
if set(expr_vp.keys()) == set(new_vp.keys()):
return expr
else:
variables = list(new_vp.keys())
point = [new_vp[v] for v in variables]
if expr is S.NaN:
return S.NaN
if any(x in p.free_symbols for x in variables for p in point):
raise ValueError('Got %s as a point.' % point)
if variables:
if any(p != point[0] for p in point):
raise NotImplementedError(
"Multivariable orders at different points are not supported.")
if point[0] is S.Infinity:
s = {k: 1/Dummy() for k in variables}
rs = {1/v: 1/k for k, v in s.items()}
ps = [S.Zero for p in point]
elif point[0] is S.NegativeInfinity:
s = {k: -1/Dummy() for k in variables}
rs = {-1/v: -1/k for k, v in s.items()}
ps = [S.Zero for p in point]
elif point[0] is not S.Zero:
s = {k: Dummy() + point[0] for k in variables}
rs = {(v - point[0]).together(): k - point[0] for k, v in s.items()}
ps = [S.Zero for p in point]
else:
s = ()
rs = ()
ps = list(point)
expr = expr.subs(s)
if expr.is_Add:
expr = expr.factor()
if s:
args = tuple([r[0] for r in rs.items()])
else:
args = tuple(variables)
if len(variables) > 1:
# XXX: better way? We need this expand() to
# workaround e.g: expr = x*(x + y).
# (x*(x + y)).as_leading_term(x, y) currently returns
# x*y (wrong order term!). That's why we want to deal with
# expand()'ed expr (handled in "if expr.is_Add" branch below).
expr = expr.expand()
old_expr = None
while old_expr != expr:
old_expr = expr
if expr.is_Add:
lst = expr.extract_leading_order(args)
expr = Add(*[f.expr for (e, f) in lst])
elif expr:
try:
expr = expr.as_leading_term(*args)
except PoleError:
if isinstance(expr, Function) or\
all(isinstance(arg, Function) for arg in expr.args):
# It is not possible to simplify an expression
# containing only functions (which raise error on
# call to leading term) further
pass
else:
orders = []
pts = tuple(zip(args, ps))
for arg in expr.args:
try:
lt = arg.as_leading_term(*args)
except PoleError:
lt = arg
if lt not in args:
order = Order(lt)
else:
order = Order(lt, *pts)
orders.append(order)
if expr.is_Add:
new_expr = Order(Add(*orders), *pts)
if new_expr.is_Add:
new_expr = Order(Add(*[a.expr for a in new_expr.args]), *pts)
expr = new_expr.expr
elif expr.is_Mul:
expr = Mul(*[a.expr for a in orders])
elif expr.is_Pow:
e = expr.exp
b = expr.base
expr = exp(e * log(b))
expr = expr.as_independent(*args, as_Add=False)[1]
expr = expand_power_base(expr)
expr = expand_log(expr)
if len(args) == 1:
# The definition of O(f(x)) symbol explicitly stated that
# the argument of f(x) is irrelevant. That's why we can
# combine some power exponents (only "on top" of the
# expression tree for f(x)), e.g.:
# x**p * (-x)**q -> x**(p+q) for real p, q.
x = args[0]
margs = list(Mul.make_args(
expr.as_independent(x, as_Add=False)[1]))
for i, t in enumerate(margs):
if t.is_Pow:
b, q = t.args
if b in (x, -x) and q.is_real and not q.has(x):
margs[i] = x**q
elif b.is_Pow and not b.exp.has(x):
b, r = b.args
if b in (x, -x) and r.is_real:
margs[i] = x**(r*q)
elif b.is_Mul and b.args[0] is S.NegativeOne:
b = -b
if b.is_Pow and not b.exp.has(x):
b, r = b.args
if b in (x, -x) and r.is_real:
margs[i] = x**(r*q)
expr = Mul(*margs)
expr = expr.subs(rs)
if expr.is_Order:
expr = expr.expr
if not expr.has(*variables) and not expr.is_zero:
expr = S.One
# create Order instance:
vp = dict(zip(variables, point))
variables.sort(key=default_sort_key)
point = [vp[v] for v in variables]
args = (expr,) + Tuple(*zip(variables, point))
obj = Expr.__new__(cls, *args)
return obj
def _eval_nseries(self, x, n, logx, cdir=0):
return self
@property
def expr(self):
return self.args[0]
@property
def variables(self):
if self.args[1:]:
return tuple(x[0] for x in self.args[1:])
else:
return ()
@property
def point(self):
if self.args[1:]:
return tuple(x[1] for x in self.args[1:])
else:
return ()
@property
def free_symbols(self):
return self.expr.free_symbols | set(self.variables)
def _eval_power(b, e):
if e.is_Number and e.is_nonnegative:
return b.func(b.expr ** e, *b.args[1:])
if e == O(1):
return b
return
def as_expr_variables(self, order_symbols):
if order_symbols is None:
order_symbols = self.args[1:]
else:
if (not all(o[1] == order_symbols[0][1] for o in order_symbols) and
not all(p == self.point[0] for p in self.point)): # pragma: no cover
raise NotImplementedError('Order at points other than 0 '
'or oo not supported, got %s as a point.' % self.point)
if order_symbols and order_symbols[0][1] != self.point[0]:
raise NotImplementedError(
"Multiplying Order at different points is not supported.")
order_symbols = dict(order_symbols)
for s, p in dict(self.args[1:]).items():
if s not in order_symbols.keys():
order_symbols[s] = p
order_symbols = sorted(order_symbols.items(), key=lambda x: default_sort_key(x[0]))
return self.expr, tuple(order_symbols)
def removeO(self):
return S.Zero
def getO(self):
return self
@cacheit
def contains(self, expr):
r"""
Return True if expr belongs to Order(self.expr, \*self.variables).
Return False if self belongs to expr.
Return None if the inclusion relation cannot be determined
(e.g. when self and expr have different symbols).
"""
expr = sympify(expr)
if expr.is_zero:
return True
if expr is S.NaN:
return False
point = self.point[0] if self.point else S.Zero
if expr.is_Order:
if (any(p != point for p in expr.point) or
any(p != point for p in self.point)):
return None
if expr.expr == self.expr:
# O(1) + O(1), O(1) + O(1, x), etc.
return all(x in self.args[1:] for x in expr.args[1:])
if expr.expr.is_Add:
return all(self.contains(x) for x in expr.expr.args)
if self.expr.is_Add and point.is_zero:
return any(self.func(x, *self.args[1:]).contains(expr)
for x in self.expr.args)
if self.variables and expr.variables:
common_symbols = tuple(
[s for s in self.variables if s in expr.variables])
elif self.variables:
common_symbols = self.variables
else:
common_symbols = expr.variables
if not common_symbols:
return None
if (self.expr.is_Pow and len(self.variables) == 1
and self.variables == expr.variables):
symbol = self.variables[0]
other = expr.expr.as_independent(symbol, as_Add=False)[1]
if (other.is_Pow and other.base == symbol and
self.expr.base == symbol):
if point.is_zero:
rv = (self.expr.exp - other.exp).is_nonpositive
if point.is_infinite:
rv = (self.expr.exp - other.exp).is_nonnegative
if rv is not None:
return rv
from sympy.simplify.powsimp import powsimp
r = None
ratio = self.expr/expr.expr
ratio = powsimp(ratio, deep=True, combine='exp')
for s in common_symbols:
from sympy.series.limits import Limit
l = Limit(ratio, s, point).doit(heuristics=False)
if not isinstance(l, Limit):
l = l != 0
else:
l = None
if r is None:
r = l
else:
if r != l:
return
return r
if self.expr.is_Pow and len(self.variables) == 1:
symbol = self.variables[0]
other = expr.as_independent(symbol, as_Add=False)[1]
if (other.is_Pow and other.base == symbol and
self.expr.base == symbol):
if point.is_zero:
rv = (self.expr.exp - other.exp).is_nonpositive
if point.is_infinite:
rv = (self.expr.exp - other.exp).is_nonnegative
if rv is not None:
return rv
obj = self.func(expr, *self.args[1:])
return self.contains(obj)
def __contains__(self, other):
result = self.contains(other)
if result is None:
raise TypeError('contains did not evaluate to a bool')
return result
def _eval_subs(self, old, new):
if old in self.variables:
newexpr = self.expr.subs(old, new)
i = self.variables.index(old)
newvars = list(self.variables)
newpt = list(self.point)
if new.is_symbol:
newvars[i] = new
else:
syms = new.free_symbols
if len(syms) == 1 or old in syms:
if old in syms:
var = self.variables[i]
else:
var = syms.pop()
# First, try to substitute self.point in the "new"
# expr to see if this is a fixed point.
# E.g. O(y).subs(y, sin(x))
point = new.subs(var, self.point[i])
if point != self.point[i]:
from sympy.solvers.solveset import solveset
d = Dummy()
sol = solveset(old - new.subs(var, d), d)
if isinstance(sol, Complement):
e1 = sol.args[0]
e2 = sol.args[1]
sol = set(e1) - set(e2)
res = [dict(zip((d, ), sol))]
point = d.subs(res[0]).limit(old, self.point[i])
newvars[i] = var
newpt[i] = point
elif old not in syms:
del newvars[i], newpt[i]
if not syms and new == self.point[i]:
newvars.extend(syms)
newpt.extend([S.Zero]*len(syms))
else:
return
return Order(newexpr, *zip(newvars, newpt))
def _eval_conjugate(self):
expr = self.expr._eval_conjugate()
if expr is not None:
return self.func(expr, *self.args[1:])
def _eval_derivative(self, x):
return self.func(self.expr.diff(x), *self.args[1:]) or self
def _eval_transpose(self):
expr = self.expr._eval_transpose()
if expr is not None:
return self.func(expr, *self.args[1:])
def __neg__(self):
return self
O = Order
|
6e9cab1f790acafa58b7de13e34daba7865be646e4345650bcb33074368a2e9f | """
Expand Hypergeometric (and Meijer G) functions into named
special functions.
The algorithm for doing this uses a collection of lookup tables of
hypergeometric functions, and various of their properties, to expand
many hypergeometric functions in terms of special functions.
It is based on the following paper:
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.
It is described in great(er) detail in the Sphinx documentation.
"""
# SUMMARY OF EXTENSIONS FOR MEIJER G FUNCTIONS
#
# o z**rho G(ap, bq; z) = G(ap + rho, bq + rho; z)
#
# o denote z*d/dz by D
#
# o It is helpful to keep in mind that ap and bq play essentially symmetric
# roles: G(1/z) has slightly altered parameters, with ap and bq interchanged.
#
# o There are four shift operators:
# A_J = b_J - D, J = 1, ..., n
# B_J = 1 - a_j + D, J = 1, ..., m
# C_J = -b_J + D, J = m+1, ..., q
# D_J = a_J - 1 - D, J = n+1, ..., p
#
# A_J, C_J increment b_J
# B_J, D_J decrement a_J
#
# o The corresponding four inverse-shift operators are defined if there
# is no cancellation. Thus e.g. an index a_J (upper or lower) can be
# incremented if a_J != b_i for i = 1, ..., q.
#
# o Order reduction: if b_j - a_i is a non-negative integer, where
# j <= m and i > n, the corresponding quotient of gamma functions reduces
# to a polynomial. Hence the G function can be expressed using a G-function
# of lower order.
# Similarly if j > m and i <= n.
#
# Secondly, there are paired index theorems [Adamchik, The evaluation of
# integrals of Bessel functions via G-function identities]. Suppose there
# are three parameters a, b, c, where a is an a_i, i <= n, b is a b_j,
# j <= m and c is a denominator parameter (i.e. a_i, i > n or b_j, j > m).
# Suppose further all three differ by integers.
# Then the order can be reduced.
# TODO work this out in detail.
#
# o An index quadruple is called suitable if its order cannot be reduced.
# If there exists a sequence of shift operators transforming one index
# quadruple into another, we say one is reachable from the other.
#
# o Deciding if one index quadruple is reachable from another is tricky. For
# this reason, we use hand-built routines to match and instantiate formulas.
#
from collections import defaultdict
from itertools import product
from functools import reduce
from sympy import SYMPY_DEBUG
from sympy.core import (S, Dummy, symbols, sympify, Tuple, expand, I, pi, Mul,
EulerGamma, oo, zoo, expand_func, Add, nan, Expr, Rational)
from sympy.core.mod import Mod
from sympy.core.sorting import default_sort_key
from sympy.functions import (exp, sqrt, root, log, lowergamma, cos,
besseli, gamma, uppergamma, expint, erf, sin, besselj, Ei, Ci, Si, Shi,
sinh, cosh, Chi, fresnels, fresnelc, polar_lift, exp_polar, floor, ceiling,
rf, factorial, lerchphi, Piecewise, re, elliptic_k, elliptic_e)
from sympy.functions.elementary.complexes import polarify, unpolarify
from sympy.functions.special.hyper import (hyper, HyperRep_atanh,
HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1,
HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2,
HyperRep_cosasin, HyperRep_sinasin, meijerg)
from sympy.matrices import Matrix, eye, zeros
from sympy.polys import apart, poly, Poly
from sympy.series import residue
from sympy.simplify.powsimp import powdenest
from sympy.utilities.iterables import sift
# function to define "buckets"
def _mod1(x):
# TODO see if this can work as Mod(x, 1); this will require
# different handling of the "buckets" since these need to
# be sorted and that fails when there is a mixture of
# integers and expressions with parameters. With the current
# Mod behavior, Mod(k, 1) == Mod(1, 1) == 0 if k is an integer.
# Although the sorting can be done with Basic.compare, this may
# still require different handling of the sorted buckets.
if x.is_Number:
return Mod(x, 1)
c, x = x.as_coeff_Add()
return Mod(c, 1) + x
# leave add formulae at the top for easy reference
def add_formulae(formulae):
""" Create our knowledge base. """
a, b, c, z = symbols('a b c, z', cls=Dummy)
def add(ap, bq, res):
func = Hyper_Function(ap, bq)
formulae.append(Formula(func, z, res, (a, b, c)))
def addb(ap, bq, B, C, M):
func = Hyper_Function(ap, bq)
formulae.append(Formula(func, z, None, (a, b, c), B, C, M))
# Luke, Y. L. (1969), The Special Functions and Their Approximations,
# Volume 1, section 6.2
# 0F0
add((), (), exp(z))
# 1F0
add((a, ), (), HyperRep_power1(-a, z))
# 2F1
addb((a, a - S.Half), (2*a, ),
Matrix([HyperRep_power2(a, z),
HyperRep_power2(a + S.Half, z)/2]),
Matrix([[1, 0]]),
Matrix([[(a - S.Half)*z/(1 - z), (S.Half - a)*z/(1 - z)],
[a/(1 - z), a*(z - 2)/(1 - z)]]))
addb((1, 1), (2, ),
Matrix([HyperRep_log1(z), 1]), Matrix([[-1/z, 0]]),
Matrix([[0, z/(z - 1)], [0, 0]]))
addb((S.Half, 1), (S('3/2'), ),
Matrix([HyperRep_atanh(z), 1]),
Matrix([[1, 0]]),
Matrix([[Rational(-1, 2), 1/(1 - z)/2], [0, 0]]))
addb((S.Half, S.Half), (S('3/2'), ),
Matrix([HyperRep_asin1(z), HyperRep_power1(Rational(-1, 2), z)]),
Matrix([[1, 0]]),
Matrix([[Rational(-1, 2), S.Half], [0, z/(1 - z)/2]]))
addb((a, S.Half + a), (S.Half, ),
Matrix([HyperRep_sqrts1(-a, z), -HyperRep_sqrts2(-a - S.Half, z)]),
Matrix([[1, 0]]),
Matrix([[0, -a],
[z*(-2*a - 1)/2/(1 - z), S.Half - z*(-2*a - 1)/(1 - z)]]))
# A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990).
# Integrals and Series: More Special Functions, Vol. 3,.
# Gordon and Breach Science Publisher
addb([a, -a], [S.Half],
Matrix([HyperRep_cosasin(a, z), HyperRep_sinasin(a, z)]),
Matrix([[1, 0]]),
Matrix([[0, -a], [a*z/(1 - z), 1/(1 - z)/2]]))
addb([1, 1], [3*S.Half],
Matrix([HyperRep_asin2(z), 1]), Matrix([[1, 0]]),
Matrix([[(z - S.Half)/(1 - z), 1/(1 - z)/2], [0, 0]]))
# Complete elliptic integrals K(z) and E(z), both a 2F1 function
addb([S.Half, S.Half], [S.One],
Matrix([elliptic_k(z), elliptic_e(z)]),
Matrix([[2/pi, 0]]),
Matrix([[Rational(-1, 2), -1/(2*z-2)],
[Rational(-1, 2), S.Half]]))
addb([Rational(-1, 2), S.Half], [S.One],
Matrix([elliptic_k(z), elliptic_e(z)]),
Matrix([[0, 2/pi]]),
Matrix([[Rational(-1, 2), -1/(2*z-2)],
[Rational(-1, 2), S.Half]]))
# 3F2
addb([Rational(-1, 2), 1, 1], [S.Half, 2],
Matrix([z*HyperRep_atanh(z), HyperRep_log1(z), 1]),
Matrix([[Rational(-2, 3), -S.One/(3*z), Rational(2, 3)]]),
Matrix([[S.Half, 0, z/(1 - z)/2],
[0, 0, z/(z - 1)],
[0, 0, 0]]))
# actually the formula for 3/2 is much nicer ...
addb([Rational(-1, 2), 1, 1], [2, 2],
Matrix([HyperRep_power1(S.Half, z), HyperRep_log2(z), 1]),
Matrix([[Rational(4, 9) - 16/(9*z), 4/(3*z), 16/(9*z)]]),
Matrix([[z/2/(z - 1), 0, 0], [1/(2*(z - 1)), 0, S.Half], [0, 0, 0]]))
# 1F1
addb([1], [b], Matrix([z**(1 - b) * exp(z) * lowergamma(b - 1, z), 1]),
Matrix([[b - 1, 0]]), Matrix([[1 - b + z, 1], [0, 0]]))
addb([a], [2*a],
Matrix([z**(S.Half - a)*exp(z/2)*besseli(a - S.Half, z/2)
* gamma(a + S.Half)/4**(S.Half - a),
z**(S.Half - a)*exp(z/2)*besseli(a + S.Half, z/2)
* gamma(a + S.Half)/4**(S.Half - a)]),
Matrix([[1, 0]]),
Matrix([[z/2, z/2], [z/2, (z/2 - 2*a)]]))
mz = polar_lift(-1)*z
addb([a], [a + 1],
Matrix([mz**(-a)*a*lowergamma(a, mz), a*exp(z)]),
Matrix([[1, 0]]),
Matrix([[-a, 1], [0, z]]))
# This one is redundant.
add([Rational(-1, 2)], [S.Half], exp(z) - sqrt(pi*z)*(-I)*erf(I*sqrt(z)))
# Added to get nice results for Laplace transform of Fresnel functions
# http://functions.wolfram.com/07.22.03.6437.01
# Basic rule
#add([1], [Rational(3, 4), Rational(5, 4)],
# sqrt(pi) * (cos(2*sqrt(polar_lift(-1)*z))*fresnelc(2*root(polar_lift(-1)*z,4)/sqrt(pi)) +
# sin(2*sqrt(polar_lift(-1)*z))*fresnels(2*root(polar_lift(-1)*z,4)/sqrt(pi)))
# / (2*root(polar_lift(-1)*z,4)))
# Manually tuned rule
addb([1], [Rational(3, 4), Rational(5, 4)],
Matrix([ sqrt(pi)*(I*sinh(2*sqrt(z))*fresnels(2*root(z, 4)*exp(I*pi/4)/sqrt(pi))
+ cosh(2*sqrt(z))*fresnelc(2*root(z, 4)*exp(I*pi/4)/sqrt(pi)))
* exp(-I*pi/4)/(2*root(z, 4)),
sqrt(pi)*root(z, 4)*(sinh(2*sqrt(z))*fresnelc(2*root(z, 4)*exp(I*pi/4)/sqrt(pi))
+ I*cosh(2*sqrt(z))*fresnels(2*root(z, 4)*exp(I*pi/4)/sqrt(pi)))
*exp(-I*pi/4)/2,
1 ]),
Matrix([[1, 0, 0]]),
Matrix([[Rational(-1, 4), 1, Rational(1, 4)],
[ z, Rational(1, 4), 0],
[ 0, 0, 0]]))
# 2F2
addb([S.Half, a], [Rational(3, 2), a + 1],
Matrix([a/(2*a - 1)*(-I)*sqrt(pi/z)*erf(I*sqrt(z)),
a/(2*a - 1)*(polar_lift(-1)*z)**(-a)*
lowergamma(a, polar_lift(-1)*z),
a/(2*a - 1)*exp(z)]),
Matrix([[1, -1, 0]]),
Matrix([[Rational(-1, 2), 0, 1], [0, -a, 1], [0, 0, z]]))
# We make a "basis" of four functions instead of three, and give EulerGamma
# an extra slot (it could just be a coefficient to 1). The advantage is
# that this way Polys will not see multivariate polynomials (it treats
# EulerGamma as an indeterminate), which is *way* faster.
addb([1, 1], [2, 2],
Matrix([Ei(z) - log(z), exp(z), 1, EulerGamma]),
Matrix([[1/z, 0, 0, -1/z]]),
Matrix([[0, 1, -1, 0], [0, z, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]))
# 0F1
add((), (S.Half, ), cosh(2*sqrt(z)))
addb([], [b],
Matrix([gamma(b)*z**((1 - b)/2)*besseli(b - 1, 2*sqrt(z)),
gamma(b)*z**(1 - b/2)*besseli(b, 2*sqrt(z))]),
Matrix([[1, 0]]), Matrix([[0, 1], [z, (1 - b)]]))
# 0F3
x = 4*z**Rational(1, 4)
def fp(a, z):
return besseli(a, x) + besselj(a, x)
def fm(a, z):
return besseli(a, x) - besselj(a, x)
# TODO branching
addb([], [S.Half, a, a + S.Half],
Matrix([fp(2*a - 1, z), fm(2*a, z)*z**Rational(1, 4),
fm(2*a - 1, z)*sqrt(z), fp(2*a, z)*z**Rational(3, 4)])
* 2**(-2*a)*gamma(2*a)*z**((1 - 2*a)/4),
Matrix([[1, 0, 0, 0]]),
Matrix([[0, 1, 0, 0],
[0, S.Half - a, 1, 0],
[0, 0, S.Half, 1],
[z, 0, 0, 1 - a]]))
x = 2*(4*z)**Rational(1, 4)*exp_polar(I*pi/4)
addb([], [a, a + S.Half, 2*a],
(2*sqrt(polar_lift(-1)*z))**(1 - 2*a)*gamma(2*a)**2 *
Matrix([besselj(2*a - 1, x)*besseli(2*a - 1, x),
x*(besseli(2*a, x)*besselj(2*a - 1, x)
- besseli(2*a - 1, x)*besselj(2*a, x)),
x**2*besseli(2*a, x)*besselj(2*a, x),
x**3*(besseli(2*a, x)*besselj(2*a - 1, x)
+ besseli(2*a - 1, x)*besselj(2*a, x))]),
Matrix([[1, 0, 0, 0]]),
Matrix([[0, Rational(1, 4), 0, 0],
[0, (1 - 2*a)/2, Rational(-1, 2), 0],
[0, 0, 1 - 2*a, Rational(1, 4)],
[-32*z, 0, 0, 1 - a]]))
# 1F2
addb([a], [a - S.Half, 2*a],
Matrix([z**(S.Half - a)*besseli(a - S.Half, sqrt(z))**2,
z**(1 - a)*besseli(a - S.Half, sqrt(z))
*besseli(a - Rational(3, 2), sqrt(z)),
z**(Rational(3, 2) - a)*besseli(a - Rational(3, 2), sqrt(z))**2]),
Matrix([[-gamma(a + S.Half)**2/4**(S.Half - a),
2*gamma(a - S.Half)*gamma(a + S.Half)/4**(1 - a),
0]]),
Matrix([[1 - 2*a, 1, 0], [z/2, S.Half - a, S.Half], [0, z, 0]]))
addb([S.Half], [b, 2 - b],
pi*(1 - b)/sin(pi*b)*
Matrix([besseli(1 - b, sqrt(z))*besseli(b - 1, sqrt(z)),
sqrt(z)*(besseli(-b, sqrt(z))*besseli(b - 1, sqrt(z))
+ besseli(1 - b, sqrt(z))*besseli(b, sqrt(z))),
besseli(-b, sqrt(z))*besseli(b, sqrt(z))]),
Matrix([[1, 0, 0]]),
Matrix([[b - 1, S.Half, 0],
[z, 0, z],
[0, S.Half, -b]]))
addb([S.Half], [Rational(3, 2), Rational(3, 2)],
Matrix([Shi(2*sqrt(z))/2/sqrt(z), sinh(2*sqrt(z))/2/sqrt(z),
cosh(2*sqrt(z))]),
Matrix([[1, 0, 0]]),
Matrix([[Rational(-1, 2), S.Half, 0], [0, Rational(-1, 2), S.Half], [0, 2*z, 0]]))
# FresnelS
# Basic rule
#add([Rational(3, 4)], [Rational(3, 2),Rational(7, 4)], 6*fresnels( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) / ( pi * (exp(pi*I/4)*root(z,4)*2/sqrt(pi))**3 ) )
# Manually tuned rule
addb([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)],
Matrix(
[ fresnels(
exp(
pi*I/4)*root(
z, 4)*2/sqrt(
pi) ) / (
pi * (exp(pi*I/4)*root(z, 4)*2/sqrt(pi))**3 ),
sinh(2*sqrt(z))/sqrt(z),
cosh(2*sqrt(z)) ]),
Matrix([[6, 0, 0]]),
Matrix([[Rational(-3, 4), Rational(1, 16), 0],
[ 0, Rational(-1, 2), 1],
[ 0, z, 0]]))
# FresnelC
# Basic rule
#add([Rational(1, 4)], [S.Half,Rational(5, 4)], fresnelc( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) / ( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) )
# Manually tuned rule
addb([Rational(1, 4)], [S.Half, Rational(5, 4)],
Matrix(
[ sqrt(
pi)*exp(
-I*pi/4)*fresnelc(
2*root(z, 4)*exp(I*pi/4)/sqrt(pi))/(2*root(z, 4)),
cosh(2*sqrt(z)),
sinh(2*sqrt(z))*sqrt(z) ]),
Matrix([[1, 0, 0]]),
Matrix([[Rational(-1, 4), Rational(1, 4), 0 ],
[ 0, 0, 1 ],
[ 0, z, S.Half]]))
# 2F3
# XXX with this five-parameter formula is pretty slow with the current
# Formula.find_instantiations (creates 2!*3!*3**(2+3) ~ 3000
# instantiations ... But it's not too bad.
addb([a, a + S.Half], [2*a, b, 2*a - b + 1],
gamma(b)*gamma(2*a - b + 1) * (sqrt(z)/2)**(1 - 2*a) *
Matrix([besseli(b - 1, sqrt(z))*besseli(2*a - b, sqrt(z)),
sqrt(z)*besseli(b, sqrt(z))*besseli(2*a - b, sqrt(z)),
sqrt(z)*besseli(b - 1, sqrt(z))*besseli(2*a - b + 1, sqrt(z)),
besseli(b, sqrt(z))*besseli(2*a - b + 1, sqrt(z))]),
Matrix([[1, 0, 0, 0]]),
Matrix([[0, S.Half, S.Half, 0],
[z/2, 1 - b, 0, z/2],
[z/2, 0, b - 2*a, z/2],
[0, S.Half, S.Half, -2*a]]))
# (C/f above comment about eulergamma in the basis).
addb([1, 1], [2, 2, Rational(3, 2)],
Matrix([Chi(2*sqrt(z)) - log(2*sqrt(z)),
cosh(2*sqrt(z)), sqrt(z)*sinh(2*sqrt(z)), 1, EulerGamma]),
Matrix([[1/z, 0, 0, 0, -1/z]]),
Matrix([[0, S.Half, 0, Rational(-1, 2), 0],
[0, 0, 1, 0, 0],
[0, z, S.Half, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]))
# 3F3
# This is rule: http://functions.wolfram.com/07.31.03.0134.01
# Initial reason to add it was a nice solution for
# integrate(erf(a*z)/z**2, z) and same for erfc and erfi.
# Basic rule
# add([1, 1, a], [2, 2, a+1], (a/(z*(a-1)**2)) *
# (1 - (-z)**(1-a) * (gamma(a) - uppergamma(a,-z))
# - (a-1) * (EulerGamma + uppergamma(0,-z) + log(-z))
# - exp(z)))
# Manually tuned rule
addb([1, 1, a], [2, 2, a+1],
Matrix([a*(log(-z) + expint(1, -z) + EulerGamma)/(z*(a**2 - 2*a + 1)),
a*(-z)**(-a)*(gamma(a) - uppergamma(a, -z))/(a - 1)**2,
a*exp(z)/(a**2 - 2*a + 1),
a/(z*(a**2 - 2*a + 1))]),
Matrix([[1-a, 1, -1/z, 1]]),
Matrix([[-1,0,-1/z,1],
[0,-a,1,0],
[0,0,z,0],
[0,0,0,-1]]))
def add_meijerg_formulae(formulae):
a, b, c, z = list(map(Dummy, 'abcz'))
rho = Dummy('rho')
def add(an, ap, bm, bq, B, C, M, matcher):
formulae.append(MeijerFormula(an, ap, bm, bq, z, [a, b, c, rho],
B, C, M, matcher))
def detect_uppergamma(func):
x = func.an[0]
y, z = func.bm
swapped = False
if not _mod1((x - y).simplify()):
swapped = True
(y, z) = (z, y)
if _mod1((x - z).simplify()) or x - z > 0:
return None
l = [y, x]
if swapped:
l = [x, y]
return {rho: y, a: x - y}, G_Function([x], [], l, [])
add([a + rho], [], [rho, a + rho], [],
Matrix([gamma(1 - a)*z**rho*exp(z)*uppergamma(a, z),
gamma(1 - a)*z**(a + rho)]),
Matrix([[1, 0]]),
Matrix([[rho + z, -1], [0, a + rho]]),
detect_uppergamma)
def detect_3113(func):
"""http://functions.wolfram.com/07.34.03.0984.01"""
x = func.an[0]
u, v, w = func.bm
if _mod1((u - v).simplify()) == 0:
if _mod1((v - w).simplify()) == 0:
return
sig = (S.Half, S.Half, S.Zero)
x1, x2, y = u, v, w
else:
if _mod1((x - u).simplify()) == 0:
sig = (S.Half, S.Zero, S.Half)
x1, y, x2 = u, v, w
else:
sig = (S.Zero, S.Half, S.Half)
y, x1, x2 = u, v, w
if (_mod1((x - x1).simplify()) != 0 or
_mod1((x - x2).simplify()) != 0 or
_mod1((x - y).simplify()) != S.Half or
x - x1 > 0 or x - x2 > 0):
return
return {a: x}, G_Function([x], [], [x - S.Half + t for t in sig], [])
s = sin(2*sqrt(z))
c_ = cos(2*sqrt(z))
S_ = Si(2*sqrt(z)) - pi/2
C = Ci(2*sqrt(z))
add([a], [], [a, a, a - S.Half], [],
Matrix([sqrt(pi)*z**(a - S.Half)*(c_*S_ - s*C),
sqrt(pi)*z**a*(s*S_ + c_*C),
sqrt(pi)*z**a]),
Matrix([[-2, 0, 0]]),
Matrix([[a - S.Half, -1, 0], [z, a, S.Half], [0, 0, a]]),
detect_3113)
def make_simp(z):
""" Create a function that simplifies rational functions in ``z``. """
def simp(expr):
""" Efficiently simplify the rational function ``expr``. """
numer, denom = expr.as_numer_denom()
numer = numer.expand()
# denom = denom.expand() # is this needed?
c, numer, denom = poly(numer, z).cancel(poly(denom, z))
return c * numer.as_expr() / denom.as_expr()
return simp
def debug(*args):
if SYMPY_DEBUG:
for a in args:
print(a, end="")
print()
class Hyper_Function(Expr):
""" A generalized hypergeometric function. """
def __new__(cls, ap, bq):
obj = super().__new__(cls)
obj.ap = Tuple(*list(map(expand, ap)))
obj.bq = Tuple(*list(map(expand, bq)))
return obj
@property
def args(self):
return (self.ap, self.bq)
@property
def sizes(self):
return (len(self.ap), len(self.bq))
@property
def gamma(self):
"""
Number of upper parameters that are negative integers
This is a transformation invariant.
"""
return sum(bool(x.is_integer and x.is_negative) for x in self.ap)
def _hashable_content(self):
return super()._hashable_content() + (self.ap,
self.bq)
def __call__(self, arg):
return hyper(self.ap, self.bq, arg)
def build_invariants(self):
"""
Compute the invariant vector.
Explanation
===========
The invariant vector is:
(gamma, ((s1, n1), ..., (sk, nk)), ((t1, m1), ..., (tr, mr)))
where gamma is the number of integer a < 0,
s1 < ... < sk
nl is the number of parameters a_i congruent to sl mod 1
t1 < ... < tr
ml is the number of parameters b_i congruent to tl mod 1
If the index pair contains parameters, then this is not truly an
invariant, since the parameters cannot be sorted uniquely mod1.
Examples
========
>>> from sympy.simplify.hyperexpand import Hyper_Function
>>> from sympy import S
>>> ap = (S.Half, S.One/3, S(-1)/2, -2)
>>> bq = (1, 2)
Here gamma = 1,
k = 3, s1 = 0, s2 = 1/3, s3 = 1/2
n1 = 1, n2 = 1, n2 = 2
r = 1, t1 = 0
m1 = 2:
>>> Hyper_Function(ap, bq).build_invariants()
(1, ((0, 1), (1/3, 1), (1/2, 2)), ((0, 2),))
"""
abuckets, bbuckets = sift(self.ap, _mod1), sift(self.bq, _mod1)
def tr(bucket):
bucket = list(bucket.items())
if not any(isinstance(x[0], Mod) for x in bucket):
bucket.sort(key=lambda x: default_sort_key(x[0]))
bucket = tuple([(mod, len(values)) for mod, values in bucket if
values])
return bucket
return (self.gamma, tr(abuckets), tr(bbuckets))
def difficulty(self, func):
""" Estimate how many steps it takes to reach ``func`` from self.
Return -1 if impossible. """
if self.gamma != func.gamma:
return -1
oabuckets, obbuckets, abuckets, bbuckets = [sift(params, _mod1) for
params in (self.ap, self.bq, func.ap, func.bq)]
diff = 0
for bucket, obucket in [(abuckets, oabuckets), (bbuckets, obbuckets)]:
for mod in set(list(bucket.keys()) + list(obucket.keys())):
if (mod not in bucket) or (mod not in obucket) \
or len(bucket[mod]) != len(obucket[mod]):
return -1
l1 = list(bucket[mod])
l2 = list(obucket[mod])
l1.sort()
l2.sort()
for i, j in zip(l1, l2):
diff += abs(i - j)
return diff
def _is_suitable_origin(self):
"""
Decide if ``self`` is a suitable origin.
Explanation
===========
A function is a suitable origin iff:
* none of the ai equals bj + n, with n a non-negative integer
* none of the ai is zero
* none of the bj is a non-positive integer
Note that this gives meaningful results only when none of the indices
are symbolic.
"""
for a in self.ap:
for b in self.bq:
if (a - b).is_integer and (a - b).is_negative is False:
return False
for a in self.ap:
if a == 0:
return False
for b in self.bq:
if b.is_integer and b.is_nonpositive:
return False
return True
class G_Function(Expr):
""" A Meijer G-function. """
def __new__(cls, an, ap, bm, bq):
obj = super().__new__(cls)
obj.an = Tuple(*list(map(expand, an)))
obj.ap = Tuple(*list(map(expand, ap)))
obj.bm = Tuple(*list(map(expand, bm)))
obj.bq = Tuple(*list(map(expand, bq)))
return obj
@property
def args(self):
return (self.an, self.ap, self.bm, self.bq)
def _hashable_content(self):
return super()._hashable_content() + self.args
def __call__(self, z):
return meijerg(self.an, self.ap, self.bm, self.bq, z)
def compute_buckets(self):
"""
Compute buckets for the fours sets of parameters.
Explanation
===========
We guarantee that any two equal Mod objects returned are actually the
same, and that the buckets are sorted by real part (an and bq
descendending, bm and ap ascending).
Examples
========
>>> from sympy.simplify.hyperexpand import G_Function
>>> from sympy.abc import y
>>> from sympy import S
>>> a, b = [1, 3, 2, S(3)/2], [1 + y, y, 2, y + 3]
>>> G_Function(a, b, [2], [y]).compute_buckets()
({0: [3, 2, 1], 1/2: [3/2]},
{0: [2], y: [y, y + 1, y + 3]}, {0: [2]}, {y: [y]})
"""
dicts = pan, pap, pbm, pbq = [defaultdict(list) for i in range(4)]
for dic, lis in zip(dicts, (self.an, self.ap, self.bm, self.bq)):
for x in lis:
dic[_mod1(x)].append(x)
for dic, flip in zip(dicts, (True, False, False, True)):
for m, items in dic.items():
x0 = items[0]
items.sort(key=lambda x: x - x0, reverse=flip)
dic[m] = items
return tuple([dict(w) for w in dicts])
@property
def signature(self):
return (len(self.an), len(self.ap), len(self.bm), len(self.bq))
# Dummy variable.
_x = Dummy('x')
class Formula:
"""
This class represents hypergeometric formulae.
Explanation
===========
Its data members are:
- z, the argument
- closed_form, the closed form expression
- symbols, the free symbols (parameters) in the formula
- func, the function
- B, C, M (see _compute_basis)
Examples
========
>>> from sympy.abc import a, b, z
>>> from sympy.simplify.hyperexpand import Formula, Hyper_Function
>>> func = Hyper_Function((a/2, a/3 + b, (1+a)/2), (a, b, (a+b)/7))
>>> f = Formula(func, z, None, [a, b])
"""
def _compute_basis(self, closed_form):
"""
Compute a set of functions B=(f1, ..., fn), a nxn matrix M
and a 1xn matrix C such that:
closed_form = C B
z d/dz B = M B.
"""
afactors = [_x + a for a in self.func.ap]
bfactors = [_x + b - 1 for b in self.func.bq]
expr = _x*Mul(*bfactors) - self.z*Mul(*afactors)
poly = Poly(expr, _x)
n = poly.degree() - 1
b = [closed_form]
for _ in range(n):
b.append(self.z*b[-1].diff(self.z))
self.B = Matrix(b)
self.C = Matrix([[1] + [0]*n])
m = eye(n)
m = m.col_insert(0, zeros(n, 1))
l = poly.all_coeffs()[1:]
l.reverse()
self.M = m.row_insert(n, -Matrix([l])/poly.all_coeffs()[0])
def __init__(self, func, z, res, symbols, B=None, C=None, M=None):
z = sympify(z)
res = sympify(res)
symbols = [x for x in sympify(symbols) if func.has(x)]
self.z = z
self.symbols = symbols
self.B = B
self.C = C
self.M = M
self.func = func
# TODO with symbolic parameters, it could be advantageous
# (for prettier answers) to compute a basis only *after*
# instantiation
if res is not None:
self._compute_basis(res)
@property
def closed_form(self):
return reduce(lambda s,m: s+m[0]*m[1], zip(self.C, self.B), S.Zero)
def find_instantiations(self, func):
"""
Find substitutions of the free symbols that match ``func``.
Return the substitution dictionaries as a list. Note that the returned
instantiations need not actually match, or be valid!
"""
from sympy.solvers import solve
ap = func.ap
bq = func.bq
if len(ap) != len(self.func.ap) or len(bq) != len(self.func.bq):
raise TypeError('Cannot instantiate other number of parameters')
symbol_values = []
for a in self.symbols:
if a in self.func.ap.args:
symbol_values.append(ap)
elif a in self.func.bq.args:
symbol_values.append(bq)
else:
raise ValueError("At least one of the parameters of the "
"formula must be equal to %s" % (a,))
base_repl = [dict(list(zip(self.symbols, values)))
for values in product(*symbol_values)]
abuckets, bbuckets = [sift(params, _mod1) for params in [ap, bq]]
a_inv, b_inv = [{a: len(vals) for a, vals in bucket.items()}
for bucket in [abuckets, bbuckets]]
critical_values = [[0] for _ in self.symbols]
result = []
_n = Dummy()
for repl in base_repl:
symb_a, symb_b = [sift(params, lambda x: _mod1(x.xreplace(repl)))
for params in [self.func.ap, self.func.bq]]
for bucket, obucket in [(abuckets, symb_a), (bbuckets, symb_b)]:
for mod in set(list(bucket.keys()) + list(obucket.keys())):
if (mod not in bucket) or (mod not in obucket) \
or len(bucket[mod]) != len(obucket[mod]):
break
for a, vals in zip(self.symbols, critical_values):
if repl[a].free_symbols:
continue
exprs = [expr for expr in obucket[mod] if expr.has(a)]
repl0 = repl.copy()
repl0[a] += _n
for expr in exprs:
for target in bucket[mod]:
n0, = solve(expr.xreplace(repl0) - target, _n)
if n0.free_symbols:
raise ValueError("Value should not be true")
vals.append(n0)
else:
values = []
for a, vals in zip(self.symbols, critical_values):
a0 = repl[a]
min_ = floor(min(vals))
max_ = ceiling(max(vals))
values.append([a0 + n for n in range(min_, max_ + 1)])
result.extend(dict(list(zip(self.symbols, l))) for l in product(*values))
return result
class FormulaCollection:
""" A collection of formulae to use as origins. """
def __init__(self):
""" Doing this globally at module init time is a pain ... """
self.symbolic_formulae = {}
self.concrete_formulae = {}
self.formulae = []
add_formulae(self.formulae)
# Now process the formulae into a helpful form.
# These dicts are indexed by (p, q).
for f in self.formulae:
sizes = f.func.sizes
if len(f.symbols) > 0:
self.symbolic_formulae.setdefault(sizes, []).append(f)
else:
inv = f.func.build_invariants()
self.concrete_formulae.setdefault(sizes, {})[inv] = f
def lookup_origin(self, func):
"""
Given the suitable target ``func``, try to find an origin in our
knowledge base.
Examples
========
>>> from sympy.simplify.hyperexpand import (FormulaCollection,
... Hyper_Function)
>>> f = FormulaCollection()
>>> f.lookup_origin(Hyper_Function((), ())).closed_form
exp(_z)
>>> f.lookup_origin(Hyper_Function([1], ())).closed_form
HyperRep_power1(-1, _z)
>>> from sympy import S
>>> i = Hyper_Function([S('1/4'), S('3/4 + 4')], [S.Half])
>>> f.lookup_origin(i).closed_form
HyperRep_sqrts1(-1/4, _z)
"""
inv = func.build_invariants()
sizes = func.sizes
if sizes in self.concrete_formulae and \
inv in self.concrete_formulae[sizes]:
return self.concrete_formulae[sizes][inv]
# We don't have a concrete formula. Try to instantiate.
if sizes not in self.symbolic_formulae:
return None # Too bad...
possible = []
for f in self.symbolic_formulae[sizes]:
repls = f.find_instantiations(func)
for repl in repls:
func2 = f.func.xreplace(repl)
if not func2._is_suitable_origin():
continue
diff = func2.difficulty(func)
if diff == -1:
continue
possible.append((diff, repl, f, func2))
# find the nearest origin
possible.sort(key=lambda x: x[0])
for _, repl, f, func2 in possible:
f2 = Formula(func2, f.z, None, [], f.B.subs(repl),
f.C.subs(repl), f.M.subs(repl))
if not any(e.has(S.NaN, oo, -oo, zoo) for e in [f2.B, f2.M, f2.C]):
return f2
return None
class MeijerFormula:
"""
This class represents a Meijer G-function formula.
Its data members are:
- z, the argument
- symbols, the free symbols (parameters) in the formula
- func, the function
- B, C, M (c/f ordinary Formula)
"""
def __init__(self, an, ap, bm, bq, z, symbols, B, C, M, matcher):
an, ap, bm, bq = [Tuple(*list(map(expand, w))) for w in [an, ap, bm, bq]]
self.func = G_Function(an, ap, bm, bq)
self.z = z
self.symbols = symbols
self._matcher = matcher
self.B = B
self.C = C
self.M = M
@property
def closed_form(self):
return reduce(lambda s,m: s+m[0]*m[1], zip(self.C, self.B), S.Zero)
def try_instantiate(self, func):
"""
Try to instantiate the current formula to (almost) match func.
This uses the _matcher passed on init.
"""
if func.signature != self.func.signature:
return None
res = self._matcher(func)
if res is not None:
subs, newfunc = res
return MeijerFormula(newfunc.an, newfunc.ap, newfunc.bm, newfunc.bq,
self.z, [],
self.B.subs(subs), self.C.subs(subs),
self.M.subs(subs), None)
class MeijerFormulaCollection:
"""
This class holds a collection of meijer g formulae.
"""
def __init__(self):
formulae = []
add_meijerg_formulae(formulae)
self.formulae = defaultdict(list)
for formula in formulae:
self.formulae[formula.func.signature].append(formula)
self.formulae = dict(self.formulae)
def lookup_origin(self, func):
""" Try to find a formula that matches func. """
if func.signature not in self.formulae:
return None
for formula in self.formulae[func.signature]:
res = formula.try_instantiate(func)
if res is not None:
return res
class Operator:
"""
Base class for operators to be applied to our functions.
Explanation
===========
These operators are differential operators. They are by convention
expressed in the variable D = z*d/dz (although this base class does
not actually care).
Note that when the operator is applied to an object, we typically do
*not* blindly differentiate but instead use a different representation
of the z*d/dz operator (see make_derivative_operator).
To subclass from this, define a __init__ method that initializes a
self._poly variable. This variable stores a polynomial. By convention
the generator is z*d/dz, and acts to the right of all coefficients.
Thus this poly
x**2 + 2*z*x + 1
represents the differential operator
(z*d/dz)**2 + 2*z**2*d/dz.
This class is used only in the implementation of the hypergeometric
function expansion algorithm.
"""
def apply(self, obj, op):
"""
Apply ``self`` to the object ``obj``, where the generator is ``op``.
Examples
========
>>> from sympy.simplify.hyperexpand import Operator
>>> from sympy.polys.polytools import Poly
>>> from sympy.abc import x, y, z
>>> op = Operator()
>>> op._poly = Poly(x**2 + z*x + y, x)
>>> op.apply(z**7, lambda f: f.diff(z))
y*z**7 + 7*z**7 + 42*z**5
"""
coeffs = self._poly.all_coeffs()
coeffs.reverse()
diffs = [obj]
for c in coeffs[1:]:
diffs.append(op(diffs[-1]))
r = coeffs[0]*diffs[0]
for c, d in zip(coeffs[1:], diffs[1:]):
r += c*d
return r
class MultOperator(Operator):
""" Simply multiply by a "constant" """
def __init__(self, p):
self._poly = Poly(p, _x)
class ShiftA(Operator):
""" Increment an upper index. """
def __init__(self, ai):
ai = sympify(ai)
if ai == 0:
raise ValueError('Cannot increment zero upper index.')
self._poly = Poly(_x/ai + 1, _x)
def __str__(self):
return '<Increment upper %s.>' % (1/self._poly.all_coeffs()[0])
class ShiftB(Operator):
""" Decrement a lower index. """
def __init__(self, bi):
bi = sympify(bi)
if bi == 1:
raise ValueError('Cannot decrement unit lower index.')
self._poly = Poly(_x/(bi - 1) + 1, _x)
def __str__(self):
return '<Decrement lower %s.>' % (1/self._poly.all_coeffs()[0] + 1)
class UnShiftA(Operator):
""" Decrement an upper index. """
def __init__(self, ap, bq, i, z):
""" Note: i counts from zero! """
ap, bq, i = list(map(sympify, [ap, bq, i]))
self._ap = ap
self._bq = bq
self._i = i
ap = list(ap)
bq = list(bq)
ai = ap.pop(i) - 1
if ai == 0:
raise ValueError('Cannot decrement unit upper index.')
m = Poly(z*ai, _x)
for a in ap:
m *= Poly(_x + a, _x)
A = Dummy('A')
n = D = Poly(ai*A - ai, A)
for b in bq:
n *= D + (b - 1).as_poly(A)
b0 = -n.nth(0)
if b0 == 0:
raise ValueError('Cannot decrement upper index: '
'cancels with lower')
n = Poly(Poly(n.all_coeffs()[:-1], A).as_expr().subs(A, _x/ai + 1), _x)
self._poly = Poly((n - m)/b0, _x)
def __str__(self):
return '<Decrement upper index #%s of %s, %s.>' % (self._i,
self._ap, self._bq)
class UnShiftB(Operator):
""" Increment a lower index. """
def __init__(self, ap, bq, i, z):
""" Note: i counts from zero! """
ap, bq, i = list(map(sympify, [ap, bq, i]))
self._ap = ap
self._bq = bq
self._i = i
ap = list(ap)
bq = list(bq)
bi = bq.pop(i) + 1
if bi == 0:
raise ValueError('Cannot increment -1 lower index.')
m = Poly(_x*(bi - 1), _x)
for b in bq:
m *= Poly(_x + b - 1, _x)
B = Dummy('B')
D = Poly((bi - 1)*B - bi + 1, B)
n = Poly(z, B)
for a in ap:
n *= (D + a.as_poly(B))
b0 = n.nth(0)
if b0 == 0:
raise ValueError('Cannot increment index: cancels with upper')
n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs(
B, _x/(bi - 1) + 1), _x)
self._poly = Poly((m - n)/b0, _x)
def __str__(self):
return '<Increment lower index #%s of %s, %s.>' % (self._i,
self._ap, self._bq)
class MeijerShiftA(Operator):
""" Increment an upper b index. """
def __init__(self, bi):
bi = sympify(bi)
self._poly = Poly(bi - _x, _x)
def __str__(self):
return '<Increment upper b=%s.>' % (self._poly.all_coeffs()[1])
class MeijerShiftB(Operator):
""" Decrement an upper a index. """
def __init__(self, bi):
bi = sympify(bi)
self._poly = Poly(1 - bi + _x, _x)
def __str__(self):
return '<Decrement upper a=%s.>' % (1 - self._poly.all_coeffs()[1])
class MeijerShiftC(Operator):
""" Increment a lower b index. """
def __init__(self, bi):
bi = sympify(bi)
self._poly = Poly(-bi + _x, _x)
def __str__(self):
return '<Increment lower b=%s.>' % (-self._poly.all_coeffs()[1])
class MeijerShiftD(Operator):
""" Decrement a lower a index. """
def __init__(self, bi):
bi = sympify(bi)
self._poly = Poly(bi - 1 - _x, _x)
def __str__(self):
return '<Decrement lower a=%s.>' % (self._poly.all_coeffs()[1] + 1)
class MeijerUnShiftA(Operator):
""" Decrement an upper b index. """
def __init__(self, an, ap, bm, bq, i, z):
""" Note: i counts from zero! """
an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
self._an = an
self._ap = ap
self._bm = bm
self._bq = bq
self._i = i
an = list(an)
ap = list(ap)
bm = list(bm)
bq = list(bq)
bi = bm.pop(i) - 1
m = Poly(1, _x)
for b in bm:
m *= Poly(b - _x, _x)
for b in bq:
m *= Poly(_x - b, _x)
A = Dummy('A')
D = Poly(bi - A, A)
n = Poly(z, A)
for a in an:
n *= (D + 1 - a)
for a in ap:
n *= (-D + a - 1)
b0 = n.nth(0)
if b0 == 0:
raise ValueError('Cannot decrement upper b index (cancels)')
n = Poly(Poly(n.all_coeffs()[:-1], A).as_expr().subs(A, bi - _x), _x)
self._poly = Poly((m - n)/b0, _x)
def __str__(self):
return '<Decrement upper b index #%s of %s, %s, %s, %s.>' % (self._i,
self._an, self._ap, self._bm, self._bq)
class MeijerUnShiftB(Operator):
""" Increment an upper a index. """
def __init__(self, an, ap, bm, bq, i, z):
""" Note: i counts from zero! """
an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
self._an = an
self._ap = ap
self._bm = bm
self._bq = bq
self._i = i
an = list(an)
ap = list(ap)
bm = list(bm)
bq = list(bq)
ai = an.pop(i) + 1
m = Poly(z, _x)
for a in an:
m *= Poly(1 - a + _x, _x)
for a in ap:
m *= Poly(a - 1 - _x, _x)
B = Dummy('B')
D = Poly(B + ai - 1, B)
n = Poly(1, B)
for b in bm:
n *= (-D + b)
for b in bq:
n *= (D - b)
b0 = n.nth(0)
if b0 == 0:
raise ValueError('Cannot increment upper a index (cancels)')
n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs(
B, 1 - ai + _x), _x)
self._poly = Poly((m - n)/b0, _x)
def __str__(self):
return '<Increment upper a index #%s of %s, %s, %s, %s.>' % (self._i,
self._an, self._ap, self._bm, self._bq)
class MeijerUnShiftC(Operator):
""" Decrement a lower b index. """
# XXX this is "essentially" the same as MeijerUnShiftA. This "essentially"
# can be made rigorous using the functional equation G(1/z) = G'(z),
# where G' denotes a G function of slightly altered parameters.
# However, sorting out the details seems harder than just coding it
# again.
def __init__(self, an, ap, bm, bq, i, z):
""" Note: i counts from zero! """
an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
self._an = an
self._ap = ap
self._bm = bm
self._bq = bq
self._i = i
an = list(an)
ap = list(ap)
bm = list(bm)
bq = list(bq)
bi = bq.pop(i) - 1
m = Poly(1, _x)
for b in bm:
m *= Poly(b - _x, _x)
for b in bq:
m *= Poly(_x - b, _x)
C = Dummy('C')
D = Poly(bi + C, C)
n = Poly(z, C)
for a in an:
n *= (D + 1 - a)
for a in ap:
n *= (-D + a - 1)
b0 = n.nth(0)
if b0 == 0:
raise ValueError('Cannot decrement lower b index (cancels)')
n = Poly(Poly(n.all_coeffs()[:-1], C).as_expr().subs(C, _x - bi), _x)
self._poly = Poly((m - n)/b0, _x)
def __str__(self):
return '<Decrement lower b index #%s of %s, %s, %s, %s.>' % (self._i,
self._an, self._ap, self._bm, self._bq)
class MeijerUnShiftD(Operator):
""" Increment a lower a index. """
# XXX This is essentially the same as MeijerUnShiftA.
# See comment at MeijerUnShiftC.
def __init__(self, an, ap, bm, bq, i, z):
""" Note: i counts from zero! """
an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
self._an = an
self._ap = ap
self._bm = bm
self._bq = bq
self._i = i
an = list(an)
ap = list(ap)
bm = list(bm)
bq = list(bq)
ai = ap.pop(i) + 1
m = Poly(z, _x)
for a in an:
m *= Poly(1 - a + _x, _x)
for a in ap:
m *= Poly(a - 1 - _x, _x)
B = Dummy('B') # - this is the shift operator `D_I`
D = Poly(ai - 1 - B, B)
n = Poly(1, B)
for b in bm:
n *= (-D + b)
for b in bq:
n *= (D - b)
b0 = n.nth(0)
if b0 == 0:
raise ValueError('Cannot increment lower a index (cancels)')
n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs(
B, ai - 1 - _x), _x)
self._poly = Poly((m - n)/b0, _x)
def __str__(self):
return '<Increment lower a index #%s of %s, %s, %s, %s.>' % (self._i,
self._an, self._ap, self._bm, self._bq)
class ReduceOrder(Operator):
""" Reduce Order by cancelling an upper and a lower index. """
def __new__(cls, ai, bj):
""" For convenience if reduction is not possible, return None. """
ai = sympify(ai)
bj = sympify(bj)
n = ai - bj
if not n.is_Integer or n < 0:
return None
if bj.is_integer and bj.is_nonpositive:
return None
expr = Operator.__new__(cls)
p = S.One
for k in range(n):
p *= (_x + bj + k)/(bj + k)
expr._poly = Poly(p, _x)
expr._a = ai
expr._b = bj
return expr
@classmethod
def _meijer(cls, b, a, sign):
""" Cancel b + sign*s and a + sign*s
This is for meijer G functions. """
b = sympify(b)
a = sympify(a)
n = b - a
if n.is_negative or not n.is_Integer:
return None
expr = Operator.__new__(cls)
p = S.One
for k in range(n):
p *= (sign*_x + a + k)
expr._poly = Poly(p, _x)
if sign == -1:
expr._a = b
expr._b = a
else:
expr._b = Add(1, a - 1, evaluate=False)
expr._a = Add(1, b - 1, evaluate=False)
return expr
@classmethod
def meijer_minus(cls, b, a):
return cls._meijer(b, a, -1)
@classmethod
def meijer_plus(cls, a, b):
return cls._meijer(1 - a, 1 - b, 1)
def __str__(self):
return '<Reduce order by cancelling upper %s with lower %s.>' % \
(self._a, self._b)
def _reduce_order(ap, bq, gen, key):
""" Order reduction algorithm used in Hypergeometric and Meijer G """
ap = list(ap)
bq = list(bq)
ap.sort(key=key)
bq.sort(key=key)
nap = []
# we will edit bq in place
operators = []
for a in ap:
op = None
for i in range(len(bq)):
op = gen(a, bq[i])
if op is not None:
bq.pop(i)
break
if op is None:
nap.append(a)
else:
operators.append(op)
return nap, bq, operators
def reduce_order(func):
"""
Given the hypergeometric function ``func``, find a sequence of operators to
reduces order as much as possible.
Explanation
===========
Return (newfunc, [operators]), where applying the operators to the
hypergeometric function newfunc yields func.
Examples
========
>>> from sympy.simplify.hyperexpand import reduce_order, Hyper_Function
>>> reduce_order(Hyper_Function((1, 2), (3, 4)))
(Hyper_Function((1, 2), (3, 4)), [])
>>> reduce_order(Hyper_Function((1,), (1,)))
(Hyper_Function((), ()), [<Reduce order by cancelling upper 1 with lower 1.>])
>>> reduce_order(Hyper_Function((2, 4), (3, 3)))
(Hyper_Function((2,), (3,)), [<Reduce order by cancelling
upper 4 with lower 3.>])
"""
nap, nbq, operators = _reduce_order(func.ap, func.bq, ReduceOrder, default_sort_key)
return Hyper_Function(Tuple(*nap), Tuple(*nbq)), operators
def reduce_order_meijer(func):
"""
Given the Meijer G function parameters, ``func``, find a sequence of
operators that reduces order as much as possible.
Return newfunc, [operators].
Examples
========
>>> from sympy.simplify.hyperexpand import (reduce_order_meijer,
... G_Function)
>>> reduce_order_meijer(G_Function([3, 4], [5, 6], [3, 4], [1, 2]))[0]
G_Function((4, 3), (5, 6), (3, 4), (2, 1))
>>> reduce_order_meijer(G_Function([3, 4], [5, 6], [3, 4], [1, 8]))[0]
G_Function((3,), (5, 6), (3, 4), (1,))
>>> reduce_order_meijer(G_Function([3, 4], [5, 6], [7, 5], [1, 5]))[0]
G_Function((3,), (), (), (1,))
>>> reduce_order_meijer(G_Function([3, 4], [5, 6], [7, 5], [5, 3]))[0]
G_Function((), (), (), ())
"""
nan, nbq, ops1 = _reduce_order(func.an, func.bq, ReduceOrder.meijer_plus,
lambda x: default_sort_key(-x))
nbm, nap, ops2 = _reduce_order(func.bm, func.ap, ReduceOrder.meijer_minus,
default_sort_key)
return G_Function(nan, nap, nbm, nbq), ops1 + ops2
def make_derivative_operator(M, z):
""" Create a derivative operator, to be passed to Operator.apply. """
def doit(C):
r = z*C.diff(z) + C*M
r = r.applyfunc(make_simp(z))
return r
return doit
def apply_operators(obj, ops, op):
"""
Apply the list of operators ``ops`` to object ``obj``, substituting
``op`` for the generator.
"""
res = obj
for o in reversed(ops):
res = o.apply(res, op)
return res
def devise_plan(target, origin, z):
"""
Devise a plan (consisting of shift and un-shift operators) to be applied
to the hypergeometric function ``target`` to yield ``origin``.
Returns a list of operators.
Examples
========
>>> from sympy.simplify.hyperexpand import devise_plan, Hyper_Function
>>> from sympy.abc import z
Nothing to do:
>>> devise_plan(Hyper_Function((1, 2), ()), Hyper_Function((1, 2), ()), z)
[]
>>> devise_plan(Hyper_Function((), (1, 2)), Hyper_Function((), (1, 2)), z)
[]
Very simple plans:
>>> devise_plan(Hyper_Function((2,), ()), Hyper_Function((1,), ()), z)
[<Increment upper 1.>]
>>> devise_plan(Hyper_Function((), (2,)), Hyper_Function((), (1,)), z)
[<Increment lower index #0 of [], [1].>]
Several buckets:
>>> from sympy import S
>>> devise_plan(Hyper_Function((1, S.Half), ()),
... Hyper_Function((2, S('3/2')), ()), z) #doctest: +NORMALIZE_WHITESPACE
[<Decrement upper index #0 of [3/2, 1], [].>,
<Decrement upper index #0 of [2, 3/2], [].>]
A slightly more complicated plan:
>>> devise_plan(Hyper_Function((1, 3), ()), Hyper_Function((2, 2), ()), z)
[<Increment upper 2.>, <Decrement upper index #0 of [2, 2], [].>]
Another more complicated plan: (note that the ap have to be shifted first!)
>>> devise_plan(Hyper_Function((1, -1), (2,)), Hyper_Function((3, -2), (4,)), z)
[<Decrement lower 3.>, <Decrement lower 4.>,
<Decrement upper index #1 of [-1, 2], [4].>,
<Decrement upper index #1 of [-1, 3], [4].>, <Increment upper -2.>]
"""
abuckets, bbuckets, nabuckets, nbbuckets = [sift(params, _mod1) for
params in (target.ap, target.bq, origin.ap, origin.bq)]
if len(list(abuckets.keys())) != len(list(nabuckets.keys())) or \
len(list(bbuckets.keys())) != len(list(nbbuckets.keys())):
raise ValueError('%s not reachable from %s' % (target, origin))
ops = []
def do_shifts(fro, to, inc, dec):
ops = []
for i in range(len(fro)):
if to[i] - fro[i] > 0:
sh = inc
ch = 1
else:
sh = dec
ch = -1
while to[i] != fro[i]:
ops += [sh(fro, i)]
fro[i] += ch
return ops
def do_shifts_a(nal, nbk, al, aother, bother):
""" Shift us from (nal, nbk) to (al, nbk). """
return do_shifts(nal, al, lambda p, i: ShiftA(p[i]),
lambda p, i: UnShiftA(p + aother, nbk + bother, i, z))
def do_shifts_b(nal, nbk, bk, aother, bother):
""" Shift us from (nal, nbk) to (nal, bk). """
return do_shifts(nbk, bk,
lambda p, i: UnShiftB(nal + aother, p + bother, i, z),
lambda p, i: ShiftB(p[i]))
for r in sorted(list(abuckets.keys()) + list(bbuckets.keys()), key=default_sort_key):
al = ()
nal = ()
bk = ()
nbk = ()
if r in abuckets:
al = abuckets[r]
nal = nabuckets[r]
if r in bbuckets:
bk = bbuckets[r]
nbk = nbbuckets[r]
if len(al) != len(nal) or len(bk) != len(nbk):
raise ValueError('%s not reachable from %s' % (target, origin))
al, nal, bk, nbk = [sorted(list(w), key=default_sort_key)
for w in [al, nal, bk, nbk]]
def others(dic, key):
l = []
for k, value in dic.items():
if k != key:
l += list(dic[k])
return l
aother = others(nabuckets, r)
bother = others(nbbuckets, r)
if len(al) == 0:
# there can be no complications, just shift the bs as we please
ops += do_shifts_b([], nbk, bk, aother, bother)
elif len(bk) == 0:
# there can be no complications, just shift the as as we please
ops += do_shifts_a(nal, [], al, aother, bother)
else:
namax = nal[-1]
amax = al[-1]
if nbk[0] - namax <= 0 or bk[0] - amax <= 0:
raise ValueError('Non-suitable parameters.')
if namax - amax > 0:
# we are going to shift down - first do the as, then the bs
ops += do_shifts_a(nal, nbk, al, aother, bother)
ops += do_shifts_b(al, nbk, bk, aother, bother)
else:
# we are going to shift up - first do the bs, then the as
ops += do_shifts_b(nal, nbk, bk, aother, bother)
ops += do_shifts_a(nal, bk, al, aother, bother)
nabuckets[r] = al
nbbuckets[r] = bk
ops.reverse()
return ops
def try_shifted_sum(func, z):
""" Try to recognise a hypergeometric sum that starts from k > 0. """
abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1)
if len(abuckets[S.Zero]) != 1:
return None
r = abuckets[S.Zero][0]
if r <= 0:
return None
if S.Zero not in bbuckets:
return None
l = list(bbuckets[S.Zero])
l.sort()
k = l[0]
if k <= 0:
return None
nap = list(func.ap)
nap.remove(r)
nbq = list(func.bq)
nbq.remove(k)
k -= 1
nap = [x - k for x in nap]
nbq = [x - k for x in nbq]
ops = []
for n in range(r - 1):
ops.append(ShiftA(n + 1))
ops.reverse()
fac = factorial(k)/z**k
for a in nap:
fac /= rf(a, k)
for b in nbq:
fac *= rf(b, k)
ops += [MultOperator(fac)]
p = 0
for n in range(k):
m = z**n/factorial(n)
for a in nap:
m *= rf(a, n)
for b in nbq:
m /= rf(b, n)
p += m
return Hyper_Function(nap, nbq), ops, -p
def try_polynomial(func, z):
""" Recognise polynomial cases. Returns None if not such a case.
Requires order to be fully reduced. """
abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1)
a0 = abuckets[S.Zero]
b0 = bbuckets[S.Zero]
a0.sort()
b0.sort()
al0 = [x for x in a0 if x <= 0]
bl0 = [x for x in b0 if x <= 0]
if bl0 and all(a < bl0[-1] for a in al0):
return oo
if not al0:
return None
a = al0[-1]
fac = 1
res = S.One
for n in Tuple(*list(range(-a))):
fac *= z
fac /= n + 1
for a in func.ap:
fac *= a + n
for b in func.bq:
fac /= b + n
res += fac
return res
def try_lerchphi(func):
"""
Try to find an expression for Hyper_Function ``func`` in terms of Lerch
Transcendents.
Return None if no such expression can be found.
"""
# This is actually quite simple, and is described in Roach's paper,
# section 18.
# We don't need to implement the reduction to polylog here, this
# is handled by expand_func.
# First we need to figure out if the summation coefficient is a rational
# function of the summation index, and construct that rational function.
abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1)
paired = {}
for key, value in abuckets.items():
if key != 0 and key not in bbuckets:
return None
bvalue = bbuckets[key]
paired[key] = (list(value), list(bvalue))
bbuckets.pop(key, None)
if bbuckets != {}:
return None
if S.Zero not in abuckets:
return None
aints, bints = paired[S.Zero]
# Account for the additional n! in denominator
paired[S.Zero] = (aints, bints + [1])
t = Dummy('t')
numer = S.One
denom = S.One
for key, (avalue, bvalue) in paired.items():
if len(avalue) != len(bvalue):
return None
# Note that since order has been reduced fully, all the b are
# bigger than all the a they differ from by an integer. In particular
# if there are any negative b left, this function is not well-defined.
for a, b in zip(avalue, bvalue):
if (a - b).is_positive:
k = a - b
numer *= rf(b + t, k)
denom *= rf(b, k)
else:
k = b - a
numer *= rf(a, k)
denom *= rf(a + t, k)
# Now do a partial fraction decomposition.
# We assemble two structures: a list monomials of pairs (a, b) representing
# a*t**b (b a non-negative integer), and a dict terms, where
# terms[a] = [(b, c)] means that there is a term b/(t-a)**c.
part = apart(numer/denom, t)
args = Add.make_args(part)
monomials = []
terms = {}
for arg in args:
numer, denom = arg.as_numer_denom()
if not denom.has(t):
p = Poly(numer, t)
if not p.is_monomial:
raise TypeError("p should be monomial")
((b, ), a) = p.LT()
monomials += [(a/denom, b)]
continue
if numer.has(t):
raise NotImplementedError('Need partial fraction decomposition'
' with linear denominators')
indep, [dep] = denom.as_coeff_mul(t)
n = 1
if dep.is_Pow:
n = dep.exp
dep = dep.base
if dep == t:
a == 0
elif dep.is_Add:
a, tmp = dep.as_independent(t)
b = 1
if tmp != t:
b, _ = tmp.as_independent(t)
if dep != b*t + a:
raise NotImplementedError('unrecognised form %s' % dep)
a /= b
indep *= b**n
else:
raise NotImplementedError('unrecognised form of partial fraction')
terms.setdefault(a, []).append((numer/indep, n))
# Now that we have this information, assemble our formula. All the
# monomials yield rational functions and go into one basis element.
# The terms[a] are related by differentiation. If the largest exponent is
# n, we need lerchphi(z, k, a) for k = 1, 2, ..., n.
# deriv maps a basis to its derivative, expressed as a C(z)-linear
# combination of other basis elements.
deriv = {}
coeffs = {}
z = Dummy('z')
monomials.sort(key=lambda x: x[1])
mon = {0: 1/(1 - z)}
if monomials:
for k in range(monomials[-1][1]):
mon[k + 1] = z*mon[k].diff(z)
for a, n in monomials:
coeffs.setdefault(S.One, []).append(a*mon[n])
for a, l in terms.items():
for c, k in l:
coeffs.setdefault(lerchphi(z, k, a), []).append(c)
l.sort(key=lambda x: x[1])
for k in range(2, l[-1][1] + 1):
deriv[lerchphi(z, k, a)] = [(-a, lerchphi(z, k, a)),
(1, lerchphi(z, k - 1, a))]
deriv[lerchphi(z, 1, a)] = [(-a, lerchphi(z, 1, a)),
(1/(1 - z), S.One)]
trans = {}
for n, b in enumerate([S.One] + list(deriv.keys())):
trans[b] = n
basis = [expand_func(b) for (b, _) in sorted(list(trans.items()),
key=lambda x:x[1])]
B = Matrix(basis)
C = Matrix([[0]*len(B)])
for b, c in coeffs.items():
C[trans[b]] = Add(*c)
M = zeros(len(B))
for b, l in deriv.items():
for c, b2 in l:
M[trans[b], trans[b2]] = c
return Formula(func, z, None, [], B, C, M)
def build_hypergeometric_formula(func):
"""
Create a formula object representing the hypergeometric function ``func``.
"""
# We know that no `ap` are negative integers, otherwise "detect poly"
# would have kicked in. However, `ap` could be empty. In this case we can
# use a different basis.
# I'm not aware of a basis that works in all cases.
z = Dummy('z')
if func.ap:
afactors = [_x + a for a in func.ap]
bfactors = [_x + b - 1 for b in func.bq]
expr = _x*Mul(*bfactors) - z*Mul(*afactors)
poly = Poly(expr, _x)
n = poly.degree()
basis = []
M = zeros(n)
for k in range(n):
a = func.ap[0] + k
basis += [hyper([a] + list(func.ap[1:]), func.bq, z)]
if k < n - 1:
M[k, k] = -a
M[k, k + 1] = a
B = Matrix(basis)
C = Matrix([[1] + [0]*(n - 1)])
derivs = [eye(n)]
for k in range(n):
derivs.append(M*derivs[k])
l = poly.all_coeffs()
l.reverse()
res = [0]*n
for k, c in enumerate(l):
for r, d in enumerate(C*derivs[k]):
res[r] += c*d
for k, c in enumerate(res):
M[n - 1, k] = -c/derivs[n - 1][0, n - 1]/poly.all_coeffs()[0]
return Formula(func, z, None, [], B, C, M)
else:
# Since there are no `ap`, none of the `bq` can be non-positive
# integers.
basis = []
bq = list(func.bq[:])
for i in range(len(bq)):
basis += [hyper([], bq, z)]
bq[i] += 1
basis += [hyper([], bq, z)]
B = Matrix(basis)
n = len(B)
C = Matrix([[1] + [0]*(n - 1)])
M = zeros(n)
M[0, n - 1] = z/Mul(*func.bq)
for k in range(1, n):
M[k, k - 1] = func.bq[k - 1]
M[k, k] = -func.bq[k - 1]
return Formula(func, z, None, [], B, C, M)
def hyperexpand_special(ap, bq, z):
"""
Try to find a closed-form expression for hyper(ap, bq, z), where ``z``
is supposed to be a "special" value, e.g. 1.
This function tries various of the classical summation formulae
(Gauss, Saalschuetz, etc).
"""
# This code is very ad-hoc. There are many clever algorithms
# (notably Zeilberger's) related to this problem.
# For now we just want a few simple cases to work.
p, q = len(ap), len(bq)
z_ = z
z = unpolarify(z)
if z == 0:
return S.One
from sympy.simplify.simplify import simplify
if p == 2 and q == 1:
# 2F1
a, b, c = ap + bq
if z == 1:
# Gauss
return gamma(c - a - b)*gamma(c)/gamma(c - a)/gamma(c - b)
if z == -1 and simplify(b - a + c) == 1:
b, a = a, b
if z == -1 and simplify(a - b + c) == 1:
# Kummer
if b.is_integer and b.is_negative:
return 2*cos(pi*b/2)*gamma(-b)*gamma(b - a + 1) \
/gamma(-b/2)/gamma(b/2 - a + 1)
else:
return gamma(b/2 + 1)*gamma(b - a + 1) \
/gamma(b + 1)/gamma(b/2 - a + 1)
# TODO tons of more formulae
# investigate what algorithms exist
return hyper(ap, bq, z_)
_collection = None
def _hyperexpand(func, z, ops0=[], z0=Dummy('z0'), premult=1, prem=0,
rewrite='default'):
"""
Try to find an expression for the hypergeometric function ``func``.
Explanation
===========
The result is expressed in terms of a dummy variable ``z0``. Then it
is multiplied by ``premult``. Then ``ops0`` is applied.
``premult`` must be a*z**prem for some a independent of ``z``.
"""
if z.is_zero:
return S.One
from sympy.simplify.simplify import simplify
z = polarify(z, subs=False)
if rewrite == 'default':
rewrite = 'nonrepsmall'
def carryout_plan(f, ops):
C = apply_operators(f.C.subs(f.z, z0), ops,
make_derivative_operator(f.M.subs(f.z, z0), z0))
C = apply_operators(C, ops0,
make_derivative_operator(f.M.subs(f.z, z0)
+ prem*eye(f.M.shape[0]), z0))
if premult == 1:
C = C.applyfunc(make_simp(z0))
r = reduce(lambda s,m: s+m[0]*m[1], zip(C, f.B.subs(f.z, z0)), S.Zero)*premult
res = r.subs(z0, z)
if rewrite:
res = res.rewrite(rewrite)
return res
# TODO
# The following would be possible:
# *) PFD Duplication (see Kelly Roach's paper)
# *) In a similar spirit, try_lerchphi() can be generalised considerably.
global _collection
if _collection is None:
_collection = FormulaCollection()
debug('Trying to expand hypergeometric function ', func)
# First reduce order as much as possible.
func, ops = reduce_order(func)
if ops:
debug(' Reduced order to ', func)
else:
debug(' Could not reduce order.')
# Now try polynomial cases
res = try_polynomial(func, z0)
if res is not None:
debug(' Recognised polynomial.')
p = apply_operators(res, ops, lambda f: z0*f.diff(z0))
p = apply_operators(p*premult, ops0, lambda f: z0*f.diff(z0))
return unpolarify(simplify(p).subs(z0, z))
# Try to recognise a shifted sum.
p = S.Zero
res = try_shifted_sum(func, z0)
if res is not None:
func, nops, p = res
debug(' Recognised shifted sum, reduced order to ', func)
ops += nops
# apply the plan for poly
p = apply_operators(p, ops, lambda f: z0*f.diff(z0))
p = apply_operators(p*premult, ops0, lambda f: z0*f.diff(z0))
p = simplify(p).subs(z0, z)
# Try special expansions early.
if unpolarify(z) in [1, -1] and (len(func.ap), len(func.bq)) == (2, 1):
f = build_hypergeometric_formula(func)
r = carryout_plan(f, ops).replace(hyper, hyperexpand_special)
if not r.has(hyper):
return r + p
# Try to find a formula in our collection
formula = _collection.lookup_origin(func)
# Now try a lerch phi formula
if formula is None:
formula = try_lerchphi(func)
if formula is None:
debug(' Could not find an origin. ',
'Will return answer in terms of '
'simpler hypergeometric functions.')
formula = build_hypergeometric_formula(func)
debug(' Found an origin: ', formula.closed_form, ' ', formula.func)
# We need to find the operators that convert formula into func.
ops += devise_plan(func, formula.func, z0)
# Now carry out the plan.
r = carryout_plan(formula, ops) + p
return powdenest(r, polar=True).replace(hyper, hyperexpand_special)
def devise_plan_meijer(fro, to, z):
"""
Find operators to convert G-function ``fro`` into G-function ``to``.
Explanation
===========
It is assumed that ``fro`` and ``to`` have the same signatures, and that in fact
any corresponding pair of parameters differs by integers, and a direct path
is possible. I.e. if there are parameters a1 b1 c1 and a2 b2 c2 it is
assumed that a1 can be shifted to a2, etc. The only thing this routine
determines is the order of shifts to apply, nothing clever will be tried.
It is also assumed that ``fro`` is suitable.
Examples
========
>>> from sympy.simplify.hyperexpand import (devise_plan_meijer,
... G_Function)
>>> from sympy.abc import z
Empty plan:
>>> devise_plan_meijer(G_Function([1], [2], [3], [4]),
... G_Function([1], [2], [3], [4]), z)
[]
Very simple plans:
>>> devise_plan_meijer(G_Function([0], [], [], []),
... G_Function([1], [], [], []), z)
[<Increment upper a index #0 of [0], [], [], [].>]
>>> devise_plan_meijer(G_Function([0], [], [], []),
... G_Function([-1], [], [], []), z)
[<Decrement upper a=0.>]
>>> devise_plan_meijer(G_Function([], [1], [], []),
... G_Function([], [2], [], []), z)
[<Increment lower a index #0 of [], [1], [], [].>]
Slightly more complicated plans:
>>> devise_plan_meijer(G_Function([0], [], [], []),
... G_Function([2], [], [], []), z)
[<Increment upper a index #0 of [1], [], [], [].>,
<Increment upper a index #0 of [0], [], [], [].>]
>>> devise_plan_meijer(G_Function([0], [], [0], []),
... G_Function([-1], [], [1], []), z)
[<Increment upper b=0.>, <Decrement upper a=0.>]
Order matters:
>>> devise_plan_meijer(G_Function([0], [], [0], []),
... G_Function([1], [], [1], []), z)
[<Increment upper a index #0 of [0], [], [1], [].>, <Increment upper b=0.>]
"""
# TODO for now, we use the following simple heuristic: inverse-shift
# when possible, shift otherwise. Give up if we cannot make progress.
def try_shift(f, t, shifter, diff, counter):
""" Try to apply ``shifter`` in order to bring some element in ``f``
nearer to its counterpart in ``to``. ``diff`` is +/- 1 and
determines the effect of ``shifter``. Counter is a list of elements
blocking the shift.
Return an operator if change was possible, else None.
"""
for idx, (a, b) in enumerate(zip(f, t)):
if (
(a - b).is_integer and (b - a)/diff > 0 and
all(a != x for x in counter)):
sh = shifter(idx)
f[idx] += diff
return sh
fan = list(fro.an)
fap = list(fro.ap)
fbm = list(fro.bm)
fbq = list(fro.bq)
ops = []
change = True
while change:
change = False
op = try_shift(fan, to.an,
lambda i: MeijerUnShiftB(fan, fap, fbm, fbq, i, z),
1, fbm + fbq)
if op is not None:
ops += [op]
change = True
continue
op = try_shift(fap, to.ap,
lambda i: MeijerUnShiftD(fan, fap, fbm, fbq, i, z),
1, fbm + fbq)
if op is not None:
ops += [op]
change = True
continue
op = try_shift(fbm, to.bm,
lambda i: MeijerUnShiftA(fan, fap, fbm, fbq, i, z),
-1, fan + fap)
if op is not None:
ops += [op]
change = True
continue
op = try_shift(fbq, to.bq,
lambda i: MeijerUnShiftC(fan, fap, fbm, fbq, i, z),
-1, fan + fap)
if op is not None:
ops += [op]
change = True
continue
op = try_shift(fan, to.an, lambda i: MeijerShiftB(fan[i]), -1, [])
if op is not None:
ops += [op]
change = True
continue
op = try_shift(fap, to.ap, lambda i: MeijerShiftD(fap[i]), -1, [])
if op is not None:
ops += [op]
change = True
continue
op = try_shift(fbm, to.bm, lambda i: MeijerShiftA(fbm[i]), 1, [])
if op is not None:
ops += [op]
change = True
continue
op = try_shift(fbq, to.bq, lambda i: MeijerShiftC(fbq[i]), 1, [])
if op is not None:
ops += [op]
change = True
continue
if fan != list(to.an) or fap != list(to.ap) or fbm != list(to.bm) or \
fbq != list(to.bq):
raise NotImplementedError('Could not devise plan.')
ops.reverse()
return ops
_meijercollection = None
def _meijergexpand(func, z0, allow_hyper=False, rewrite='default',
place=None):
"""
Try to find an expression for the Meijer G function specified
by the G_Function ``func``. If ``allow_hyper`` is True, then returning
an expression in terms of hypergeometric functions is allowed.
Currently this just does Slater's theorem.
If expansions exist both at zero and at infinity, ``place``
can be set to ``0`` or ``zoo`` for the preferred choice.
"""
global _meijercollection
if _meijercollection is None:
_meijercollection = MeijerFormulaCollection()
if rewrite == 'default':
rewrite = None
func0 = func
debug('Try to expand Meijer G function corresponding to ', func)
# We will play games with analytic continuation - rather use a fresh symbol
z = Dummy('z')
func, ops = reduce_order_meijer(func)
if ops:
debug(' Reduced order to ', func)
else:
debug(' Could not reduce order.')
# Try to find a direct formula
f = _meijercollection.lookup_origin(func)
if f is not None:
debug(' Found a Meijer G formula: ', f.func)
ops += devise_plan_meijer(f.func, func, z)
# Now carry out the plan.
C = apply_operators(f.C.subs(f.z, z), ops,
make_derivative_operator(f.M.subs(f.z, z), z))
C = C.applyfunc(make_simp(z))
r = C*f.B.subs(f.z, z)
r = r[0].subs(z, z0)
return powdenest(r, polar=True)
debug(" Could not find a direct formula. Trying Slater's theorem.")
# TODO the following would be possible:
# *) Paired Index Theorems
# *) PFD Duplication
# (See Kelly Roach's paper for details on either.)
#
# TODO Also, we tend to create combinations of gamma functions that can be
# simplified.
def can_do(pbm, pap):
""" Test if slater applies. """
for i in pbm:
if len(pbm[i]) > 1:
l = 0
if i in pap:
l = len(pap[i])
if l + 1 < len(pbm[i]):
return False
return True
def do_slater(an, bm, ap, bq, z, zfinal):
# zfinal is the value that will eventually be substituted for z.
# We pass it to _hyperexpand to improve performance.
func = G_Function(an, bm, ap, bq)
_, pbm, pap, _ = func.compute_buckets()
if not can_do(pbm, pap):
return S.Zero, False
cond = len(an) + len(ap) < len(bm) + len(bq)
if len(an) + len(ap) == len(bm) + len(bq):
cond = abs(z) < 1
if cond is False:
return S.Zero, False
res = S.Zero
for m in pbm:
if len(pbm[m]) == 1:
bh = pbm[m][0]
fac = 1
bo = list(bm)
bo.remove(bh)
for bj in bo:
fac *= gamma(bj - bh)
for aj in an:
fac *= gamma(1 + bh - aj)
for bj in bq:
fac /= gamma(1 + bh - bj)
for aj in ap:
fac /= gamma(aj - bh)
nap = [1 + bh - a for a in list(an) + list(ap)]
nbq = [1 + bh - b for b in list(bo) + list(bq)]
k = polar_lift(S.NegativeOne**(len(ap) - len(bm)))
harg = k*zfinal
# NOTE even though k "is" +-1, this has to be t/k instead of
# t*k ... we are using polar numbers for consistency!
premult = (t/k)**bh
hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
t, premult, bh, rewrite=None)
res += fac * hyp
else:
b_ = pbm[m][0]
ki = [bi - b_ for bi in pbm[m][1:]]
u = len(ki)
li = [ai - b_ for ai in pap[m][:u + 1]]
bo = list(bm)
for b in pbm[m]:
bo.remove(b)
ao = list(ap)
for a in pap[m][:u]:
ao.remove(a)
lu = li[-1]
di = [l - k for (l, k) in zip(li, ki)]
# We first work out the integrand:
s = Dummy('s')
integrand = z**s
for b in bm:
if not Mod(b, 1) and b.is_Number:
b = int(round(b))
integrand *= gamma(b - s)
for a in an:
integrand *= gamma(1 - a + s)
for b in bq:
integrand /= gamma(1 - b + s)
for a in ap:
integrand /= gamma(a - s)
# Now sum the finitely many residues:
# XXX This speeds up some cases - is it a good idea?
integrand = expand_func(integrand)
for r in range(int(round(lu))):
resid = residue(integrand, s, b_ + r)
resid = apply_operators(resid, ops, lambda f: z*f.diff(z))
res -= resid
# Now the hypergeometric term.
au = b_ + lu
k = polar_lift(S.NegativeOne**(len(ao) + len(bo) + 1))
harg = k*zfinal
premult = (t/k)**au
nap = [1 + au - a for a in list(an) + list(ap)] + [1]
nbq = [1 + au - b for b in list(bm) + list(bq)]
hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
t, premult, au, rewrite=None)
C = S.NegativeOne**(lu)/factorial(lu)
for i in range(u):
C *= S.NegativeOne**di[i]/rf(lu - li[i] + 1, di[i])
for a in an:
C *= gamma(1 - a + au)
for b in bo:
C *= gamma(b - au)
for a in ao:
C /= gamma(a - au)
for b in bq:
C /= gamma(1 - b + au)
res += C*hyp
return res, cond
t = Dummy('t')
slater1, cond1 = do_slater(func.an, func.bm, func.ap, func.bq, z, z0)
def tr(l):
return [1 - x for x in l]
for op in ops:
op._poly = Poly(op._poly.subs({z: 1/t, _x: -_x}), _x)
slater2, cond2 = do_slater(tr(func.bm), tr(func.an), tr(func.bq), tr(func.ap),
t, 1/z0)
slater1 = powdenest(slater1.subs(z, z0), polar=True)
slater2 = powdenest(slater2.subs(t, 1/z0), polar=True)
if not isinstance(cond2, bool):
cond2 = cond2.subs(t, 1/z)
m = func(z)
if m.delta > 0 or \
(m.delta == 0 and len(m.ap) == len(m.bq) and
(re(m.nu) < -1) is not False and polar_lift(z0) == polar_lift(1)):
# The condition delta > 0 means that the convergence region is
# connected. Any expression we find can be continued analytically
# to the entire convergence region.
# The conditions delta==0, p==q, re(nu) < -1 imply that G is continuous
# on the positive reals, so the values at z=1 agree.
if cond1 is not False:
cond1 = True
if cond2 is not False:
cond2 = True
if cond1 is True:
slater1 = slater1.rewrite(rewrite or 'nonrep')
else:
slater1 = slater1.rewrite(rewrite or 'nonrepsmall')
if cond2 is True:
slater2 = slater2.rewrite(rewrite or 'nonrep')
else:
slater2 = slater2.rewrite(rewrite or 'nonrepsmall')
if cond1 is not False and cond2 is not False:
# If one condition is False, there is no choice.
if place == 0:
cond2 = False
if place == zoo:
cond1 = False
if not isinstance(cond1, bool):
cond1 = cond1.subs(z, z0)
if not isinstance(cond2, bool):
cond2 = cond2.subs(z, z0)
def weight(expr, cond):
if cond is True:
c0 = 0
elif cond is False:
c0 = 1
else:
c0 = 2
if expr.has(oo, zoo, -oo, nan):
# XXX this actually should not happen, but consider
# S('meijerg(((0, -1/2, 0, -1/2, 1/2), ()), ((0,),
# (-1/2, -1/2, -1/2, -1)), exp_polar(I*pi))/4')
c0 = 3
return (c0, expr.count(hyper), expr.count_ops())
w1 = weight(slater1, cond1)
w2 = weight(slater2, cond2)
if min(w1, w2) <= (0, 1, oo):
if w1 < w2:
return slater1
else:
return slater2
if max(w1[0], w2[0]) <= 1 and max(w1[1], w2[1]) <= 1:
return Piecewise((slater1, cond1), (slater2, cond2), (func0(z0), True))
# We couldn't find an expression without hypergeometric functions.
# TODO it would be helpful to give conditions under which the integral
# is known to diverge.
r = Piecewise((slater1, cond1), (slater2, cond2), (func0(z0), True))
if r.has(hyper) and not allow_hyper:
debug(' Could express using hypergeometric functions, '
'but not allowed.')
if not r.has(hyper) or allow_hyper:
return r
return func0(z0)
def hyperexpand(f, allow_hyper=False, rewrite='default', place=None):
"""
Expand hypergeometric functions. If allow_hyper is True, allow partial
simplification (that is a result different from input,
but still containing hypergeometric functions).
If a G-function has expansions both at zero and at infinity,
``place`` can be set to ``0`` or ``zoo`` to indicate the
preferred choice.
Examples
========
>>> from sympy.simplify.hyperexpand import hyperexpand
>>> from sympy.functions import hyper
>>> from sympy.abc import z
>>> hyperexpand(hyper([], [], z))
exp(z)
Non-hyperegeometric parts of the expression and hypergeometric expressions
that are not recognised are left unchanged:
>>> hyperexpand(1 + hyper([1, 1, 1], [], z))
hyper((1, 1, 1), (), z) + 1
"""
f = sympify(f)
def do_replace(ap, bq, z):
r = _hyperexpand(Hyper_Function(ap, bq), z, rewrite=rewrite)
if r is None:
return hyper(ap, bq, z)
else:
return r
def do_meijer(ap, bq, z):
r = _meijergexpand(G_Function(ap[0], ap[1], bq[0], bq[1]), z,
allow_hyper, rewrite=rewrite, place=place)
if not r.has(nan, zoo, oo, -oo):
return r
return f.replace(hyper, do_replace).replace(meijerg, do_meijer)
|
27e68853c6b622c83f9f30fccf51c6a832a689b639e7f26075cb6f172471e280 | from collections import defaultdict
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
from sympy.core import (Basic, S, Add, Mul, Pow, Symbol, sympify,
expand_func, Function, Dummy, Expr, factor_terms,
expand_power_exp, Eq)
from sympy.core.exprtools import factor_nc
from sympy.core.parameters import global_parameters
from sympy.core.function import (expand_log, count_ops, _mexpand,
nfloat, expand_mul, expand)
from sympy.core.numbers import Float, I, pi, Rational
from sympy.core.relational import Relational
from sympy.core.rules import Transform
from sympy.core.sorting import ordered
from sympy.core.sympify import _sympify
from sympy.core.traversal import bottom_up as _bottom_up, walk as _walk
from sympy.functions import gamma, exp, sqrt, log, exp_polar, re
from sympy.functions.combinatorial.factorials import CombinatorialFunction
from sympy.functions.elementary.complexes import unpolarify, Abs, sign
from sympy.functions.elementary.exponential import ExpBase
from sympy.functions.elementary.hyperbolic import HyperbolicFunction
from sympy.functions.elementary.integers import ceiling
from sympy.functions.elementary.piecewise import (Piecewise, piecewise_fold,
piecewise_simplify)
from sympy.functions.elementary.trigonometric import TrigonometricFunction
from sympy.functions.special.bessel import (BesselBase, besselj, besseli,
besselk, bessely, jn)
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.integrals.integrals import Integral
from sympy.matrices.expressions import (MatrixExpr, MatAdd, MatMul,
MatPow, MatrixSymbol)
from sympy.polys import together, cancel, factor
from sympy.polys.numberfields.minpoly import _is_sum_surds, _minimal_polynomial_sq
from sympy.simplify.combsimp import combsimp
from sympy.simplify.cse_opts import sub_pre, sub_post
from sympy.simplify.hyperexpand import hyperexpand
from sympy.simplify.powsimp import powsimp
from sympy.simplify.radsimp import radsimp, fraction, collect_abs
from sympy.simplify.sqrtdenest import sqrtdenest
from sympy.simplify.trigsimp import trigsimp, exptrigsimp
from sympy.utilities.decorator import deprecated
from sympy.utilities.iterables import has_variety, sift, subsets, iterable
from sympy.utilities.misc import as_int
import mpmath
def separatevars(expr, symbols=[], dict=False, force=False):
"""
Separates variables in an expression, if possible. By
default, it separates with respect to all symbols in an
expression and collects constant coefficients that are
independent of symbols.
Explanation
===========
If ``dict=True`` then the separated terms will be returned
in a dictionary keyed to their corresponding symbols.
By default, all symbols in the expression will appear as
keys; if symbols are provided, then all those symbols will
be used as keys, and any terms in the expression containing
other symbols or non-symbols will be returned keyed to the
string 'coeff'. (Passing None for symbols will return the
expression in a dictionary keyed to 'coeff'.)
If ``force=True``, then bases of powers will be separated regardless
of assumptions on the symbols involved.
Notes
=====
The order of the factors is determined by Mul, so that the
separated expressions may not necessarily be grouped together.
Although factoring is necessary to separate variables in some
expressions, it is not necessary in all cases, so one should not
count on the returned factors being factored.
Examples
========
>>> from sympy.abc import x, y, z, alpha
>>> from sympy import separatevars, sin
>>> separatevars((x*y)**y)
(x*y)**y
>>> separatevars((x*y)**y, force=True)
x**y*y**y
>>> e = 2*x**2*z*sin(y)+2*z*x**2
>>> separatevars(e)
2*x**2*z*(sin(y) + 1)
>>> separatevars(e, symbols=(x, y), dict=True)
{'coeff': 2*z, x: x**2, y: sin(y) + 1}
>>> separatevars(e, [x, y, alpha], dict=True)
{'coeff': 2*z, alpha: 1, x: x**2, y: sin(y) + 1}
If the expression is not really separable, or is only partially
separable, separatevars will do the best it can to separate it
by using factoring.
>>> separatevars(x + x*y - 3*x**2)
-x*(3*x - y - 1)
If the expression is not separable then expr is returned unchanged
or (if dict=True) then None is returned.
>>> eq = 2*x + y*sin(x)
>>> separatevars(eq) == eq
True
>>> separatevars(2*x + y*sin(x), symbols=(x, y), dict=True) is None
True
"""
expr = sympify(expr)
if dict:
return _separatevars_dict(_separatevars(expr, force), symbols)
else:
return _separatevars(expr, force)
def _separatevars(expr, force):
if isinstance(expr, Abs):
arg = expr.args[0]
if arg.is_Mul and not arg.is_number:
s = separatevars(arg, dict=True, force=force)
if s is not None:
return Mul(*map(expr.func, s.values()))
else:
return expr
if len(expr.free_symbols) < 2:
return expr
# don't destroy a Mul since much of the work may already be done
if expr.is_Mul:
args = list(expr.args)
changed = False
for i, a in enumerate(args):
args[i] = separatevars(a, force)
changed = changed or args[i] != a
if changed:
expr = expr.func(*args)
return expr
# get a Pow ready for expansion
if expr.is_Pow and expr.base != S.Exp1:
expr = Pow(separatevars(expr.base, force=force), expr.exp)
# First try other expansion methods
expr = expr.expand(mul=False, multinomial=False, force=force)
_expr, reps = posify(expr) if force else (expr, {})
expr = factor(_expr).subs(reps)
if not expr.is_Add:
return expr
# Find any common coefficients to pull out
args = list(expr.args)
commonc = args[0].args_cnc(cset=True, warn=False)[0]
for i in args[1:]:
commonc &= i.args_cnc(cset=True, warn=False)[0]
commonc = Mul(*commonc)
commonc = commonc.as_coeff_Mul()[1] # ignore constants
commonc_set = commonc.args_cnc(cset=True, warn=False)[0]
# remove them
for i, a in enumerate(args):
c, nc = a.args_cnc(cset=True, warn=False)
c = c - commonc_set
args[i] = Mul(*c)*Mul(*nc)
nonsepar = Add(*args)
if len(nonsepar.free_symbols) > 1:
_expr = nonsepar
_expr, reps = posify(_expr) if force else (_expr, {})
_expr = (factor(_expr)).subs(reps)
if not _expr.is_Add:
nonsepar = _expr
return commonc*nonsepar
def _separatevars_dict(expr, symbols):
if symbols:
if not all(t.is_Atom for t in symbols):
raise ValueError("symbols must be Atoms.")
symbols = list(symbols)
elif symbols is None:
return {'coeff': expr}
else:
symbols = list(expr.free_symbols)
if not symbols:
return None
ret = {i: [] for i in symbols + ['coeff']}
for i in Mul.make_args(expr):
expsym = i.free_symbols
intersection = set(symbols).intersection(expsym)
if len(intersection) > 1:
return None
if len(intersection) == 0:
# There are no symbols, so it is part of the coefficient
ret['coeff'].append(i)
else:
ret[intersection.pop()].append(i)
# rebuild
for k, v in ret.items():
ret[k] = Mul(*v)
return ret
def posify(eq):
"""Return ``eq`` (with generic symbols made positive) and a
dictionary containing the mapping between the old and new
symbols.
Explanation
===========
Any symbol that has positive=None will be replaced with a positive dummy
symbol having the same name. This replacement will allow more symbolic
processing of expressions, especially those involving powers and
logarithms.
A dictionary that can be sent to subs to restore ``eq`` to its original
symbols is also returned.
>>> from sympy import posify, Symbol, log, solve
>>> from sympy.abc import x
>>> posify(x + Symbol('p', positive=True) + Symbol('n', negative=True))
(_x + n + p, {_x: x})
>>> eq = 1/x
>>> log(eq).expand()
log(1/x)
>>> log(posify(eq)[0]).expand()
-log(_x)
>>> p, rep = posify(eq)
>>> log(p).expand().subs(rep)
-log(x)
It is possible to apply the same transformations to an iterable
of expressions:
>>> eq = x**2 - 4
>>> solve(eq, x)
[-2, 2]
>>> eq_x, reps = posify([eq, x]); eq_x
[_x**2 - 4, _x]
>>> solve(*eq_x)
[2]
"""
eq = sympify(eq)
if iterable(eq):
f = type(eq)
eq = list(eq)
syms = set()
for e in eq:
syms = syms.union(e.atoms(Symbol))
reps = {}
for s in syms:
reps.update({v: k for k, v in posify(s)[1].items()})
for i, e in enumerate(eq):
eq[i] = e.subs(reps)
return f(eq), {r: s for s, r in reps.items()}
reps = {s: Dummy(s.name, positive=True, **s.assumptions0)
for s in eq.free_symbols if s.is_positive is None}
eq = eq.subs(reps)
return eq, {r: s for s, r in reps.items()}
def hypersimp(f, k):
"""Given combinatorial term f(k) simplify its consecutive term ratio
i.e. f(k+1)/f(k). The input term can be composed of functions and
integer sequences which have equivalent representation in terms
of gamma special function.
Explanation
===========
The algorithm performs three basic steps:
1. Rewrite all functions in terms of gamma, if possible.
2. Rewrite all occurrences of gamma in terms of products
of gamma and rising factorial with integer, absolute
constant exponent.
3. Perform simplification of nested fractions, powers
and if the resulting expression is a quotient of
polynomials, reduce their total degree.
If f(k) is hypergeometric then as result we arrive with a
quotient of polynomials of minimal degree. Otherwise None
is returned.
For more information on the implemented algorithm refer to:
1. W. Koepf, Algorithms for m-fold Hypergeometric Summation,
Journal of Symbolic Computation (1995) 20, 399-417
"""
f = sympify(f)
g = f.subs(k, k + 1) / f
g = g.rewrite(gamma)
if g.has(Piecewise):
g = piecewise_fold(g)
g = g.args[-1][0]
g = expand_func(g)
g = powsimp(g, deep=True, combine='exp')
if g.is_rational_function(k):
return simplify(g, ratio=S.Infinity)
else:
return None
def hypersimilar(f, g, k):
"""
Returns True if ``f`` and ``g`` are hyper-similar.
Explanation
===========
Similarity in hypergeometric sense means that a quotient of
f(k) and g(k) is a rational function in ``k``. This procedure
is useful in solving recurrence relations.
For more information see hypersimp().
"""
f, g = list(map(sympify, (f, g)))
h = (f/g).rewrite(gamma)
h = h.expand(func=True, basic=False)
return h.is_rational_function(k)
def signsimp(expr, evaluate=None):
"""Make all Add sub-expressions canonical wrt sign.
Explanation
===========
If an Add subexpression, ``a``, can have a sign extracted,
as determined by could_extract_minus_sign, it is replaced
with Mul(-1, a, evaluate=False). This allows signs to be
extracted from powers and products.
Examples
========
>>> from sympy import signsimp, exp, symbols
>>> from sympy.abc import x, y
>>> i = symbols('i', odd=True)
>>> n = -1 + 1/x
>>> n/x/(-n)**2 - 1/n/x
(-1 + 1/x)/(x*(1 - 1/x)**2) - 1/(x*(-1 + 1/x))
>>> signsimp(_)
0
>>> x*n + x*-n
x*(-1 + 1/x) + x*(1 - 1/x)
>>> signsimp(_)
0
Since powers automatically handle leading signs
>>> (-2)**i
-2**i
signsimp can be used to put the base of a power with an integer
exponent into canonical form:
>>> n**i
(-1 + 1/x)**i
By default, signsimp does not leave behind any hollow simplification:
if making an Add canonical wrt sign didn't change the expression, the
original Add is restored. If this is not desired then the keyword
``evaluate`` can be set to False:
>>> e = exp(y - x)
>>> signsimp(e) == e
True
>>> signsimp(e, evaluate=False)
exp(-(x - y))
"""
if evaluate is None:
evaluate = global_parameters.evaluate
expr = sympify(expr)
if not isinstance(expr, (Expr, Relational)) or expr.is_Atom:
return expr
# get rid of an pre-existing unevaluation regarding sign
e = expr.replace(lambda x: x.is_Mul and -(-x) != x, lambda x: -(-x))
e = sub_post(sub_pre(e))
if not isinstance(e, (Expr, Relational)) or e.is_Atom:
return e
if e.is_Add:
rv = e.func(*[signsimp(a) for a in e.args])
if not evaluate and isinstance(rv, Add
) and rv.could_extract_minus_sign():
return Mul(S.NegativeOne, -rv, evaluate=False)
return rv
if evaluate:
e = e.replace(lambda x: x.is_Mul and -(-x) != x, lambda x: -(-x))
return e
def simplify(expr, ratio=1.7, measure=count_ops, rational=False, inverse=False, doit=True, **kwargs):
"""Simplifies the given expression.
Explanation
===========
Simplification is not a well defined term and the exact strategies
this function tries can change in the future versions of SymPy. If
your algorithm relies on "simplification" (whatever it is), try to
determine what you need exactly - is it powsimp()?, radsimp()?,
together()?, logcombine()?, or something else? And use this particular
function directly, because those are well defined and thus your algorithm
will be robust.
Nonetheless, especially for interactive use, or when you do not know
anything about the structure of the expression, simplify() tries to apply
intelligent heuristics to make the input expression "simpler". For
example:
>>> from sympy import simplify, cos, sin
>>> from sympy.abc import x, y
>>> a = (x + x**2)/(x*sin(y)**2 + x*cos(y)**2)
>>> a
(x**2 + x)/(x*sin(y)**2 + x*cos(y)**2)
>>> simplify(a)
x + 1
Note that we could have obtained the same result by using specific
simplification functions:
>>> from sympy import trigsimp, cancel
>>> trigsimp(a)
(x**2 + x)/x
>>> cancel(_)
x + 1
In some cases, applying :func:`simplify` may actually result in some more
complicated expression. The default ``ratio=1.7`` prevents more extreme
cases: if (result length)/(input length) > ratio, then input is returned
unmodified. The ``measure`` parameter lets you specify the function used
to determine how complex an expression is. The function should take a
single argument as an expression and return a number such that if
expression ``a`` is more complex than expression ``b``, then
``measure(a) > measure(b)``. The default measure function is
:func:`~.count_ops`, which returns the total number of operations in the
expression.
For example, if ``ratio=1``, ``simplify`` output cannot be longer
than input.
::
>>> from sympy import sqrt, simplify, count_ops, oo
>>> root = 1/(sqrt(2)+3)
Since ``simplify(root)`` would result in a slightly longer expression,
root is returned unchanged instead::
>>> simplify(root, ratio=1) == root
True
If ``ratio=oo``, simplify will be applied anyway::
>>> count_ops(simplify(root, ratio=oo)) > count_ops(root)
True
Note that the shortest expression is not necessary the simplest, so
setting ``ratio`` to 1 may not be a good idea.
Heuristically, the default value ``ratio=1.7`` seems like a reasonable
choice.
You can easily define your own measure function based on what you feel
should represent the "size" or "complexity" of the input expression. Note
that some choices, such as ``lambda expr: len(str(expr))`` may appear to be
good metrics, but have other problems (in this case, the measure function
may slow down simplify too much for very large expressions). If you do not
know what a good metric would be, the default, ``count_ops``, is a good
one.
For example:
>>> from sympy import symbols, log
>>> a, b = symbols('a b', positive=True)
>>> g = log(a) + log(b) + log(a)*log(1/b)
>>> h = simplify(g)
>>> h
log(a*b**(1 - log(a)))
>>> count_ops(g)
8
>>> count_ops(h)
5
So you can see that ``h`` is simpler than ``g`` using the count_ops metric.
However, we may not like how ``simplify`` (in this case, using
``logcombine``) has created the ``b**(log(1/a) + 1)`` term. A simple way
to reduce this would be to give more weight to powers as operations in
``count_ops``. We can do this by using the ``visual=True`` option:
>>> print(count_ops(g, visual=True))
2*ADD + DIV + 4*LOG + MUL
>>> print(count_ops(h, visual=True))
2*LOG + MUL + POW + SUB
>>> from sympy import Symbol, S
>>> def my_measure(expr):
... POW = Symbol('POW')
... # Discourage powers by giving POW a weight of 10
... count = count_ops(expr, visual=True).subs(POW, 10)
... # Every other operation gets a weight of 1 (the default)
... count = count.replace(Symbol, type(S.One))
... return count
>>> my_measure(g)
8
>>> my_measure(h)
14
>>> 15./8 > 1.7 # 1.7 is the default ratio
True
>>> simplify(g, measure=my_measure)
-log(a)*log(b) + log(a) + log(b)
Note that because ``simplify()`` internally tries many different
simplification strategies and then compares them using the measure
function, we get a completely different result that is still different
from the input expression by doing this.
If ``rational=True``, Floats will be recast as Rationals before simplification.
If ``rational=None``, Floats will be recast as Rationals but the result will
be recast as Floats. If rational=False(default) then nothing will be done
to the Floats.
If ``inverse=True``, it will be assumed that a composition of inverse
functions, such as sin and asin, can be cancelled in any order.
For example, ``asin(sin(x))`` will yield ``x`` without checking whether
x belongs to the set where this relation is true. The default is
False.
Note that ``simplify()`` automatically calls ``doit()`` on the final
expression. You can avoid this behavior by passing ``doit=False`` as
an argument.
Also, it should be noted that simplifying the boolian expression is not
well defined. If the expression prefers automatic evaluation (such as
:obj:`~.Eq()` or :obj:`~.Or()`), simplification will return ``True`` or
``False`` if truth value can be determined. If the expression is not
evaluated by default (such as :obj:`~.Predicate()`), simplification will
not reduce it and you should use :func:`~.refine()` or :func:`~.ask()`
function. This inconsistency will be resolved in future version.
See Also
========
sympy.assumptions.refine.refine : Simplification using assumptions.
sympy.assumptions.ask.ask : Query for boolean expressions using assumptions.
"""
def shorter(*choices):
"""
Return the choice that has the fewest ops. In case of a tie,
the expression listed first is selected.
"""
if not has_variety(choices):
return choices[0]
return min(choices, key=measure)
def done(e):
rv = e.doit() if doit else e
return shorter(rv, collect_abs(rv))
expr = sympify(expr, rational=rational)
kwargs = dict(
ratio=kwargs.get('ratio', ratio),
measure=kwargs.get('measure', measure),
rational=kwargs.get('rational', rational),
inverse=kwargs.get('inverse', inverse),
doit=kwargs.get('doit', doit))
# no routine for Expr needs to check for is_zero
if isinstance(expr, Expr) and expr.is_zero:
return S.Zero if not expr.is_Number else expr
_eval_simplify = getattr(expr, '_eval_simplify', None)
if _eval_simplify is not None:
return _eval_simplify(**kwargs)
original_expr = expr = collect_abs(signsimp(expr))
if not isinstance(expr, Basic) or not expr.args: # XXX: temporary hack
return expr
if inverse and expr.has(Function):
expr = inversecombine(expr)
if not expr.args: # simplified to atomic
return expr
# do deep simplification
handled = Add, Mul, Pow, ExpBase
expr = expr.replace(
# here, checking for x.args is not enough because Basic has
# args but Basic does not always play well with replace, e.g.
# when simultaneous is True found expressions will be masked
# off with a Dummy but not all Basic objects in an expression
# can be replaced with a Dummy
lambda x: isinstance(x, Expr) and x.args and not isinstance(
x, handled),
lambda x: x.func(*[simplify(i, **kwargs) for i in x.args]),
simultaneous=False)
if not isinstance(expr, handled):
return done(expr)
if not expr.is_commutative:
expr = nc_simplify(expr)
# TODO: Apply different strategies, considering expression pattern:
# is it a purely rational function? Is there any trigonometric function?...
# See also https://github.com/sympy/sympy/pull/185.
# rationalize Floats
floats = False
if rational is not False and expr.has(Float):
floats = True
expr = nsimplify(expr, rational=True)
expr = _bottom_up(expr, lambda w: getattr(w, 'normal', lambda: w)())
expr = Mul(*powsimp(expr).as_content_primitive())
_e = cancel(expr)
expr1 = shorter(_e, _mexpand(_e).cancel()) # issue 6829
expr2 = shorter(together(expr, deep=True), together(expr1, deep=True))
if ratio is S.Infinity:
expr = expr2
else:
expr = shorter(expr2, expr1, expr)
if not isinstance(expr, Basic): # XXX: temporary hack
return expr
expr = factor_terms(expr, sign=False)
# must come before `Piecewise` since this introduces more `Piecewise` terms
if expr.has(sign):
expr = expr.rewrite(Abs)
# Deal with Piecewise separately to avoid recursive growth of expressions
if expr.has(Piecewise):
# Fold into a single Piecewise
expr = piecewise_fold(expr)
# Apply doit, if doit=True
expr = done(expr)
# Still a Piecewise?
if expr.has(Piecewise):
# Fold into a single Piecewise, in case doit lead to some
# expressions being Piecewise
expr = piecewise_fold(expr)
# kroneckersimp also affects Piecewise
if expr.has(KroneckerDelta):
expr = kroneckersimp(expr)
# Still a Piecewise?
if expr.has(Piecewise):
# Do not apply doit on the segments as it has already
# been done above, but simplify
expr = piecewise_simplify(expr, deep=True, doit=False)
# Still a Piecewise?
if expr.has(Piecewise):
# Try factor common terms
expr = shorter(expr, factor_terms(expr))
# As all expressions have been simplified above with the
# complete simplify, nothing more needs to be done here
return expr
# hyperexpand automatically only works on hypergeometric terms
# Do this after the Piecewise part to avoid recursive expansion
expr = hyperexpand(expr)
if expr.has(KroneckerDelta):
expr = kroneckersimp(expr)
if expr.has(BesselBase):
expr = besselsimp(expr)
if expr.has(TrigonometricFunction, HyperbolicFunction):
expr = trigsimp(expr, deep=True)
if expr.has(log):
expr = shorter(expand_log(expr, deep=True), logcombine(expr))
if expr.has(CombinatorialFunction, gamma):
# expression with gamma functions or non-integer arguments is
# automatically passed to gammasimp
expr = combsimp(expr)
if expr.has(Sum):
expr = sum_simplify(expr, **kwargs)
if expr.has(Integral):
expr = expr.xreplace({
i: factor_terms(i) for i in expr.atoms(Integral)})
if expr.has(Product):
expr = product_simplify(expr)
from sympy.physics.units import Quantity
if expr.has(Quantity):
from sympy.physics.units.util import quantity_simplify
expr = quantity_simplify(expr)
short = shorter(powsimp(expr, combine='exp', deep=True), powsimp(expr), expr)
short = shorter(short, cancel(short))
short = shorter(short, factor_terms(short), expand_power_exp(expand_mul(short)))
if short.has(TrigonometricFunction, HyperbolicFunction, ExpBase, exp):
short = exptrigsimp(short)
# get rid of hollow 2-arg Mul factorization
hollow_mul = Transform(
lambda x: Mul(*x.args),
lambda x:
x.is_Mul and
len(x.args) == 2 and
x.args[0].is_Number and
x.args[1].is_Add and
x.is_commutative)
expr = short.xreplace(hollow_mul)
numer, denom = expr.as_numer_denom()
if denom.is_Add:
n, d = fraction(radsimp(1/denom, symbolic=False, max_terms=1))
if n is not S.One:
expr = (numer*n).expand()/d
if expr.could_extract_minus_sign():
n, d = fraction(expr)
if d != 0:
expr = signsimp(-n/(-d))
if measure(expr) > ratio*measure(original_expr):
expr = original_expr
# restore floats
if floats and rational is None:
expr = nfloat(expr, exponent=False)
return done(expr)
def sum_simplify(s, **kwargs):
"""Main function for Sum simplification"""
if not isinstance(s, Add):
s = s.xreplace({a: sum_simplify(a, **kwargs)
for a in s.atoms(Add) if a.has(Sum)})
s = expand(s)
if not isinstance(s, Add):
return s
terms = s.args
s_t = [] # Sum Terms
o_t = [] # Other Terms
for term in terms:
sum_terms, other = sift(Mul.make_args(term),
lambda i: isinstance(i, Sum), binary=True)
if not sum_terms:
o_t.append(term)
continue
other = [Mul(*other)]
s_t.append(Mul(*(other + [s._eval_simplify(**kwargs) for s in sum_terms])))
result = Add(sum_combine(s_t), *o_t)
return result
def sum_combine(s_t):
"""Helper function for Sum simplification
Attempts to simplify a list of sums, by combining limits / sum function's
returns the simplified sum
"""
used = [False] * len(s_t)
for method in range(2):
for i, s_term1 in enumerate(s_t):
if not used[i]:
for j, s_term2 in enumerate(s_t):
if not used[j] and i != j:
temp = sum_add(s_term1, s_term2, method)
if isinstance(temp, (Sum, Mul)):
s_t[i] = temp
s_term1 = s_t[i]
used[j] = True
result = S.Zero
for i, s_term in enumerate(s_t):
if not used[i]:
result = Add(result, s_term)
return result
def factor_sum(self, limits=None, radical=False, clear=False, fraction=False, sign=True):
"""Return Sum with constant factors extracted.
If ``limits`` is specified then ``self`` is the summand; the other
keywords are passed to ``factor_terms``.
Examples
========
>>> from sympy import Sum
>>> from sympy.abc import x, y
>>> from sympy.simplify.simplify import factor_sum
>>> s = Sum(x*y, (x, 1, 3))
>>> factor_sum(s)
y*Sum(x, (x, 1, 3))
>>> factor_sum(s.function, s.limits)
y*Sum(x, (x, 1, 3))
"""
# XXX deprecate in favor of direct call to factor_terms
kwargs = dict(radical=radical, clear=clear,
fraction=fraction, sign=sign)
expr = Sum(self, *limits) if limits else self
return factor_terms(expr, **kwargs)
def sum_add(self, other, method=0):
"""Helper function for Sum simplification"""
#we know this is something in terms of a constant * a sum
#so we temporarily put the constants inside for simplification
#then simplify the result
def __refactor(val):
args = Mul.make_args(val)
sumv = next(x for x in args if isinstance(x, Sum))
constant = Mul(*[x for x in args if x != sumv])
return Sum(constant * sumv.function, *sumv.limits)
if isinstance(self, Mul):
rself = __refactor(self)
else:
rself = self
if isinstance(other, Mul):
rother = __refactor(other)
else:
rother = other
if type(rself) is type(rother):
if method == 0:
if rself.limits == rother.limits:
return factor_sum(Sum(rself.function + rother.function, *rself.limits))
elif method == 1:
if simplify(rself.function - rother.function) == 0:
if len(rself.limits) == len(rother.limits) == 1:
i = rself.limits[0][0]
x1 = rself.limits[0][1]
y1 = rself.limits[0][2]
j = rother.limits[0][0]
x2 = rother.limits[0][1]
y2 = rother.limits[0][2]
if i == j:
if x2 == y1 + 1:
return factor_sum(Sum(rself.function, (i, x1, y2)))
elif x1 == y2 + 1:
return factor_sum(Sum(rself.function, (i, x2, y1)))
return Add(self, other)
def product_simplify(s):
"""Main function for Product simplification"""
terms = Mul.make_args(s)
p_t = [] # Product Terms
o_t = [] # Other Terms
for term in terms:
if isinstance(term, Product):
p_t.append(term)
else:
o_t.append(term)
used = [False] * len(p_t)
for method in range(2):
for i, p_term1 in enumerate(p_t):
if not used[i]:
for j, p_term2 in enumerate(p_t):
if not used[j] and i != j:
if isinstance(product_mul(p_term1, p_term2, method), Product):
p_t[i] = product_mul(p_term1, p_term2, method)
used[j] = True
result = Mul(*o_t)
for i, p_term in enumerate(p_t):
if not used[i]:
result = Mul(result, p_term)
return result
def product_mul(self, other, method=0):
"""Helper function for Product simplification"""
if type(self) is type(other):
if method == 0:
if self.limits == other.limits:
return Product(self.function * other.function, *self.limits)
elif method == 1:
if simplify(self.function - other.function) == 0:
if len(self.limits) == len(other.limits) == 1:
i = self.limits[0][0]
x1 = self.limits[0][1]
y1 = self.limits[0][2]
j = other.limits[0][0]
x2 = other.limits[0][1]
y2 = other.limits[0][2]
if i == j:
if x2 == y1 + 1:
return Product(self.function, (i, x1, y2))
elif x1 == y2 + 1:
return Product(self.function, (i, x2, y1))
return Mul(self, other)
def _nthroot_solve(p, n, prec):
"""
helper function for ``nthroot``
It denests ``p**Rational(1, n)`` using its minimal polynomial
"""
from sympy.solvers import solve
while n % 2 == 0:
p = sqrtdenest(sqrt(p))
n = n // 2
if n == 1:
return p
pn = p**Rational(1, n)
x = Symbol('x')
f = _minimal_polynomial_sq(p, n, x)
if f is None:
return None
sols = solve(f, x)
for sol in sols:
if abs(sol - pn).n() < 1./10**prec:
sol = sqrtdenest(sol)
if _mexpand(sol**n) == p:
return sol
def logcombine(expr, force=False):
"""
Takes logarithms and combines them using the following rules:
- log(x) + log(y) == log(x*y) if both are positive
- a*log(x) == log(x**a) if x is positive and a is real
If ``force`` is ``True`` then the assumptions above will be assumed to hold if
there is no assumption already in place on a quantity. For example, if
``a`` is imaginary or the argument negative, force will not perform a
combination but if ``a`` is a symbol with no assumptions the change will
take place.
Examples
========
>>> from sympy import Symbol, symbols, log, logcombine, I
>>> from sympy.abc import a, x, y, z
>>> logcombine(a*log(x) + log(y) - log(z))
a*log(x) + log(y) - log(z)
>>> logcombine(a*log(x) + log(y) - log(z), force=True)
log(x**a*y/z)
>>> x,y,z = symbols('x,y,z', positive=True)
>>> a = Symbol('a', real=True)
>>> logcombine(a*log(x) + log(y) - log(z))
log(x**a*y/z)
The transformation is limited to factors and/or terms that
contain logs, so the result depends on the initial state of
expansion:
>>> eq = (2 + 3*I)*log(x)
>>> logcombine(eq, force=True) == eq
True
>>> logcombine(eq.expand(), force=True)
log(x**2) + I*log(x**3)
See Also
========
posify: replace all symbols with symbols having positive assumptions
sympy.core.function.expand_log: expand the logarithms of products
and powers; the opposite of logcombine
"""
def f(rv):
if not (rv.is_Add or rv.is_Mul):
return rv
def gooda(a):
# bool to tell whether the leading ``a`` in ``a*log(x)``
# could appear as log(x**a)
return (a is not S.NegativeOne and # -1 *could* go, but we disallow
(a.is_extended_real or force and a.is_extended_real is not False))
def goodlog(l):
# bool to tell whether log ``l``'s argument can combine with others
a = l.args[0]
return a.is_positive or force and a.is_nonpositive is not False
other = []
logs = []
log1 = defaultdict(list)
for a in Add.make_args(rv):
if isinstance(a, log) and goodlog(a):
log1[()].append(([], a))
elif not a.is_Mul:
other.append(a)
else:
ot = []
co = []
lo = []
for ai in a.args:
if ai.is_Rational and ai < 0:
ot.append(S.NegativeOne)
co.append(-ai)
elif isinstance(ai, log) and goodlog(ai):
lo.append(ai)
elif gooda(ai):
co.append(ai)
else:
ot.append(ai)
if len(lo) > 1:
logs.append((ot, co, lo))
elif lo:
log1[tuple(ot)].append((co, lo[0]))
else:
other.append(a)
# if there is only one log in other, put it with the
# good logs
if len(other) == 1 and isinstance(other[0], log):
log1[()].append(([], other.pop()))
# if there is only one log at each coefficient and none have
# an exponent to place inside the log then there is nothing to do
if not logs and all(len(log1[k]) == 1 and log1[k][0] == [] for k in log1):
return rv
# collapse multi-logs as far as possible in a canonical way
# TODO: see if x*log(a)+x*log(a)*log(b) -> x*log(a)*(1+log(b))?
# -- in this case, it's unambiguous, but if it were were a log(c) in
# each term then it's arbitrary whether they are grouped by log(a) or
# by log(c). So for now, just leave this alone; it's probably better to
# let the user decide
for o, e, l in logs:
l = list(ordered(l))
e = log(l.pop(0).args[0]**Mul(*e))
while l:
li = l.pop(0)
e = log(li.args[0]**e)
c, l = Mul(*o), e
if isinstance(l, log): # it should be, but check to be sure
log1[(c,)].append(([], l))
else:
other.append(c*l)
# logs that have the same coefficient can multiply
for k in list(log1.keys()):
log1[Mul(*k)] = log(logcombine(Mul(*[
l.args[0]**Mul(*c) for c, l in log1.pop(k)]),
force=force), evaluate=False)
# logs that have oppositely signed coefficients can divide
for k in ordered(list(log1.keys())):
if k not in log1: # already popped as -k
continue
if -k in log1:
# figure out which has the minus sign; the one with
# more op counts should be the one
num, den = k, -k
if num.count_ops() > den.count_ops():
num, den = den, num
other.append(
num*log(log1.pop(num).args[0]/log1.pop(den).args[0],
evaluate=False))
else:
other.append(k*log1.pop(k))
return Add(*other)
return _bottom_up(expr, f)
def inversecombine(expr):
"""Simplify the composition of a function and its inverse.
Explanation
===========
No attention is paid to whether the inverse is a left inverse or a
right inverse; thus, the result will in general not be equivalent
to the original expression.
Examples
========
>>> from sympy.simplify.simplify import inversecombine
>>> from sympy import asin, sin, log, exp
>>> from sympy.abc import x
>>> inversecombine(asin(sin(x)))
x
>>> inversecombine(2*log(exp(3*x)))
6*x
"""
def f(rv):
if isinstance(rv, log):
if isinstance(rv.args[0], exp) or (rv.args[0].is_Pow and rv.args[0].base == S.Exp1):
rv = rv.args[0].exp
elif rv.is_Function and hasattr(rv, "inverse"):
if (len(rv.args) == 1 and len(rv.args[0].args) == 1 and
isinstance(rv.args[0], rv.inverse(argindex=1))):
rv = rv.args[0].args[0]
if rv.is_Pow and rv.base == S.Exp1:
if isinstance(rv.exp, log):
rv = rv.exp.args[0]
return rv
return _bottom_up(expr, f)
def kroneckersimp(expr):
"""
Simplify expressions with KroneckerDelta.
The only simplification currently attempted is to identify multiplicative cancellation:
Examples
========
>>> from sympy import KroneckerDelta, kroneckersimp
>>> from sympy.abc import i
>>> kroneckersimp(1 + KroneckerDelta(0, i) * KroneckerDelta(1, i))
1
"""
def args_cancel(args1, args2):
for i1 in range(2):
for i2 in range(2):
a1 = args1[i1]
a2 = args2[i2]
a3 = args1[(i1 + 1) % 2]
a4 = args2[(i2 + 1) % 2]
if Eq(a1, a2) is S.true and Eq(a3, a4) is S.false:
return True
return False
def cancel_kronecker_mul(m):
args = m.args
deltas = [a for a in args if isinstance(a, KroneckerDelta)]
for delta1, delta2 in subsets(deltas, 2):
args1 = delta1.args
args2 = delta2.args
if args_cancel(args1, args2):
return S.Zero * m # In case of oo etc
return m
if not expr.has(KroneckerDelta):
return expr
if expr.has(Piecewise):
expr = expr.rewrite(KroneckerDelta)
newexpr = expr
expr = None
while newexpr != expr:
expr = newexpr
newexpr = expr.replace(lambda e: isinstance(e, Mul), cancel_kronecker_mul)
return expr
def besselsimp(expr):
"""
Simplify bessel-type functions.
Explanation
===========
This routine tries to simplify bessel-type functions. Currently it only
works on the Bessel J and I functions, however. It works by looking at all
such functions in turn, and eliminating factors of "I" and "-1" (actually
their polar equivalents) in front of the argument. Then, functions of
half-integer order are rewritten using strigonometric functions and
functions of integer order (> 1) are rewritten using functions
of low order. Finally, if the expression was changed, compute
factorization of the result with factor().
>>> from sympy import besselj, besseli, besselsimp, polar_lift, I, S
>>> from sympy.abc import z, nu
>>> besselsimp(besselj(nu, z*polar_lift(-1)))
exp(I*pi*nu)*besselj(nu, z)
>>> besselsimp(besseli(nu, z*polar_lift(-I)))
exp(-I*pi*nu/2)*besselj(nu, z)
>>> besselsimp(besseli(S(-1)/2, z))
sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z))
>>> besselsimp(z*besseli(0, z) + z*(besseli(2, z))/2 + besseli(1, z))
3*z*besseli(0, z)/2
"""
# TODO
# - better algorithm?
# - simplify (cos(pi*b)*besselj(b,z) - besselj(-b,z))/sin(pi*b) ...
# - use contiguity relations?
def replacer(fro, to, factors):
factors = set(factors)
def repl(nu, z):
if factors.intersection(Mul.make_args(z)):
return to(nu, z)
return fro(nu, z)
return repl
def torewrite(fro, to):
def tofunc(nu, z):
return fro(nu, z).rewrite(to)
return tofunc
def tominus(fro):
def tofunc(nu, z):
return exp(I*pi*nu)*fro(nu, exp_polar(-I*pi)*z)
return tofunc
orig_expr = expr
ifactors = [I, exp_polar(I*pi/2), exp_polar(-I*pi/2)]
expr = expr.replace(
besselj, replacer(besselj,
torewrite(besselj, besseli), ifactors))
expr = expr.replace(
besseli, replacer(besseli,
torewrite(besseli, besselj), ifactors))
minusfactors = [-1, exp_polar(I*pi)]
expr = expr.replace(
besselj, replacer(besselj, tominus(besselj), minusfactors))
expr = expr.replace(
besseli, replacer(besseli, tominus(besseli), minusfactors))
z0 = Dummy('z')
def expander(fro):
def repl(nu, z):
if (nu % 1) == S.Half:
return simplify(trigsimp(unpolarify(
fro(nu, z0).rewrite(besselj).rewrite(jn).expand(
func=True)).subs(z0, z)))
elif nu.is_Integer and nu > 1:
return fro(nu, z).expand(func=True)
return fro(nu, z)
return repl
expr = expr.replace(besselj, expander(besselj))
expr = expr.replace(bessely, expander(bessely))
expr = expr.replace(besseli, expander(besseli))
expr = expr.replace(besselk, expander(besselk))
def _bessel_simp_recursion(expr):
def _use_recursion(bessel, expr):
while True:
bessels = expr.find(lambda x: isinstance(x, bessel))
try:
for ba in sorted(bessels, key=lambda x: re(x.args[0])):
a, x = ba.args
bap1 = bessel(a+1, x)
bap2 = bessel(a+2, x)
if expr.has(bap1) and expr.has(bap2):
expr = expr.subs(ba, 2*(a+1)/x*bap1 - bap2)
break
else:
return expr
except (ValueError, TypeError):
return expr
if expr.has(besselj):
expr = _use_recursion(besselj, expr)
if expr.has(bessely):
expr = _use_recursion(bessely, expr)
return expr
expr = _bessel_simp_recursion(expr)
if expr != orig_expr:
expr = expr.factor()
return expr
def nthroot(expr, n, max_len=4, prec=15):
"""
Compute a real nth-root of a sum of surds.
Parameters
==========
expr : sum of surds
n : integer
max_len : maximum number of surds passed as constants to ``nsimplify``
Algorithm
=========
First ``nsimplify`` is used to get a candidate root; if it is not a
root the minimal polynomial is computed; the answer is one of its
roots.
Examples
========
>>> from sympy.simplify.simplify import nthroot
>>> from sympy import sqrt
>>> nthroot(90 + 34*sqrt(7), 3)
sqrt(7) + 3
"""
expr = sympify(expr)
n = sympify(n)
p = expr**Rational(1, n)
if not n.is_integer:
return p
if not _is_sum_surds(expr):
return p
surds = []
coeff_muls = [x.as_coeff_Mul() for x in expr.args]
for x, y in coeff_muls:
if not x.is_rational:
return p
if y is S.One:
continue
if not (y.is_Pow and y.exp == S.Half and y.base.is_integer):
return p
surds.append(y)
surds.sort()
surds = surds[:max_len]
if expr < 0 and n % 2 == 1:
p = (-expr)**Rational(1, n)
a = nsimplify(p, constants=surds)
res = a if _mexpand(a**n) == _mexpand(-expr) else p
return -res
a = nsimplify(p, constants=surds)
if _mexpand(a) is not _mexpand(p) and _mexpand(a**n) == _mexpand(expr):
return _mexpand(a)
expr = _nthroot_solve(expr, n, prec)
if expr is None:
return p
return expr
def nsimplify(expr, constants=(), tolerance=None, full=False, rational=None,
rational_conversion='base10'):
"""
Find a simple representation for a number or, if there are free symbols or
if ``rational=True``, then replace Floats with their Rational equivalents. If
no change is made and rational is not False then Floats will at least be
converted to Rationals.
Explanation
===========
For numerical expressions, a simple formula that numerically matches the
given numerical expression is sought (and the input should be possible
to evalf to a precision of at least 30 digits).
Optionally, a list of (rationally independent) constants to
include in the formula may be given.
A lower tolerance may be set to find less exact matches. If no tolerance
is given then the least precise value will set the tolerance (e.g. Floats
default to 15 digits of precision, so would be tolerance=10**-15).
With ``full=True``, a more extensive search is performed
(this is useful to find simpler numbers when the tolerance
is set low).
When converting to rational, if rational_conversion='base10' (the default), then
convert floats to rationals using their base-10 (string) representation.
When rational_conversion='exact' it uses the exact, base-2 representation.
Examples
========
>>> from sympy import nsimplify, sqrt, GoldenRatio, exp, I, pi
>>> nsimplify(4/(1+sqrt(5)), [GoldenRatio])
-2 + 2*GoldenRatio
>>> nsimplify((1/(exp(3*pi*I/5)+1)))
1/2 - I*sqrt(sqrt(5)/10 + 1/4)
>>> nsimplify(I**I, [pi])
exp(-pi/2)
>>> nsimplify(pi, tolerance=0.01)
22/7
>>> nsimplify(0.333333333333333, rational=True, rational_conversion='exact')
6004799503160655/18014398509481984
>>> nsimplify(0.333333333333333, rational=True)
1/3
See Also
========
sympy.core.function.nfloat
"""
try:
return sympify(as_int(expr))
except (TypeError, ValueError):
pass
expr = sympify(expr).xreplace({
Float('inf'): S.Infinity,
Float('-inf'): S.NegativeInfinity,
})
if expr is S.Infinity or expr is S.NegativeInfinity:
return expr
if rational or expr.free_symbols:
return _real_to_rational(expr, tolerance, rational_conversion)
# SymPy's default tolerance for Rationals is 15; other numbers may have
# lower tolerances set, so use them to pick the largest tolerance if None
# was given
if tolerance is None:
tolerance = 10**-min([15] +
[mpmath.libmp.libmpf.prec_to_dps(n._prec)
for n in expr.atoms(Float)])
# XXX should prec be set independent of tolerance or should it be computed
# from tolerance?
prec = 30
bprec = int(prec*3.33)
constants_dict = {}
for constant in constants:
constant = sympify(constant)
v = constant.evalf(prec)
if not v.is_Float:
raise ValueError("constants must be real-valued")
constants_dict[str(constant)] = v._to_mpmath(bprec)
exprval = expr.evalf(prec, chop=True)
re, im = exprval.as_real_imag()
# safety check to make sure that this evaluated to a number
if not (re.is_Number and im.is_Number):
return expr
def nsimplify_real(x):
orig = mpmath.mp.dps
xv = x._to_mpmath(bprec)
try:
# We'll be happy with low precision if a simple fraction
if not (tolerance or full):
mpmath.mp.dps = 15
rat = mpmath.pslq([xv, 1])
if rat is not None:
return Rational(-int(rat[1]), int(rat[0]))
mpmath.mp.dps = prec
newexpr = mpmath.identify(xv, constants=constants_dict,
tol=tolerance, full=full)
if not newexpr:
raise ValueError
if full:
newexpr = newexpr[0]
expr = sympify(newexpr)
if x and not expr: # don't let x become 0
raise ValueError
if expr.is_finite is False and xv not in [mpmath.inf, mpmath.ninf]:
raise ValueError
return expr
finally:
# even though there are returns above, this is executed
# before leaving
mpmath.mp.dps = orig
try:
if re:
re = nsimplify_real(re)
if im:
im = nsimplify_real(im)
except ValueError:
if rational is None:
return _real_to_rational(expr, rational_conversion=rational_conversion)
return expr
rv = re + im*S.ImaginaryUnit
# if there was a change or rational is explicitly not wanted
# return the value, else return the Rational representation
if rv != expr or rational is False:
return rv
return _real_to_rational(expr, rational_conversion=rational_conversion)
def _real_to_rational(expr, tolerance=None, rational_conversion='base10'):
"""
Replace all reals in expr with rationals.
Examples
========
>>> from sympy.simplify.simplify import _real_to_rational
>>> from sympy.abc import x
>>> _real_to_rational(.76 + .1*x**.5)
sqrt(x)/10 + 19/25
If rational_conversion='base10', this uses the base-10 string. If
rational_conversion='exact', the exact, base-2 representation is used.
>>> _real_to_rational(0.333333333333333, rational_conversion='exact')
6004799503160655/18014398509481984
>>> _real_to_rational(0.333333333333333)
1/3
"""
expr = _sympify(expr)
inf = Float('inf')
p = expr
reps = {}
reduce_num = None
if tolerance is not None and tolerance < 1:
reduce_num = ceiling(1/tolerance)
for fl in p.atoms(Float):
key = fl
if reduce_num is not None:
r = Rational(fl).limit_denominator(reduce_num)
elif (tolerance is not None and tolerance >= 1 and
fl.is_Integer is False):
r = Rational(tolerance*round(fl/tolerance)
).limit_denominator(int(tolerance))
else:
if rational_conversion == 'exact':
r = Rational(fl)
reps[key] = r
continue
elif rational_conversion != 'base10':
raise ValueError("rational_conversion must be 'base10' or 'exact'")
r = nsimplify(fl, rational=False)
# e.g. log(3).n() -> log(3) instead of a Rational
if fl and not r:
r = Rational(fl)
elif not r.is_Rational:
if fl in (inf, -inf):
r = S.ComplexInfinity
elif fl < 0:
fl = -fl
d = Pow(10, int(mpmath.log(fl)/mpmath.log(10)))
r = -Rational(str(fl/d))*d
elif fl > 0:
d = Pow(10, int(mpmath.log(fl)/mpmath.log(10)))
r = Rational(str(fl/d))*d
else:
r = S.Zero
reps[key] = r
return p.subs(reps, simultaneous=True)
def clear_coefficients(expr, rhs=S.Zero):
"""Return `p, r` where `p` is the expression obtained when Rational
additive and multiplicative coefficients of `expr` have been stripped
away in a naive fashion (i.e. without simplification). The operations
needed to remove the coefficients will be applied to `rhs` and returned
as `r`.
Examples
========
>>> from sympy.simplify.simplify import clear_coefficients
>>> from sympy.abc import x, y
>>> from sympy import Dummy
>>> expr = 4*y*(6*x + 3)
>>> clear_coefficients(expr - 2)
(y*(2*x + 1), 1/6)
When solving 2 or more expressions like `expr = a`,
`expr = b`, etc..., it is advantageous to provide a Dummy symbol
for `rhs` and simply replace it with `a`, `b`, etc... in `r`.
>>> rhs = Dummy('rhs')
>>> clear_coefficients(expr, rhs)
(y*(2*x + 1), _rhs/12)
>>> _[1].subs(rhs, 2)
1/6
"""
was = None
free = expr.free_symbols
if expr.is_Rational:
return (S.Zero, rhs - expr)
while expr and was != expr:
was = expr
m, expr = (
expr.as_content_primitive()
if free else
factor_terms(expr).as_coeff_Mul(rational=True))
rhs /= m
c, expr = expr.as_coeff_Add(rational=True)
rhs -= c
expr = signsimp(expr, evaluate = False)
if expr.could_extract_minus_sign():
expr = -expr
rhs = -rhs
return expr, rhs
def nc_simplify(expr, deep=True):
'''
Simplify a non-commutative expression composed of multiplication
and raising to a power by grouping repeated subterms into one power.
Priority is given to simplifications that give the fewest number
of arguments in the end (for example, in a*b*a*b*c*a*b*c simplifying
to (a*b)**2*c*a*b*c gives 5 arguments while a*b*(a*b*c)**2 has 3).
If ``expr`` is a sum of such terms, the sum of the simplified terms
is returned.
Keyword argument ``deep`` controls whether or not subexpressions
nested deeper inside the main expression are simplified. See examples
below. Setting `deep` to `False` can save time on nested expressions
that do not need simplifying on all levels.
Examples
========
>>> from sympy import symbols
>>> from sympy.simplify.simplify import nc_simplify
>>> a, b, c = symbols("a b c", commutative=False)
>>> nc_simplify(a*b*a*b*c*a*b*c)
a*b*(a*b*c)**2
>>> expr = a**2*b*a**4*b*a**4
>>> nc_simplify(expr)
a**2*(b*a**4)**2
>>> nc_simplify(a*b*a*b*c**2*(a*b)**2*c**2)
((a*b)**2*c**2)**2
>>> nc_simplify(a*b*a*b + 2*a*c*a**2*c*a**2*c*a)
(a*b)**2 + 2*(a*c*a)**3
>>> nc_simplify(b**-1*a**-1*(a*b)**2)
a*b
>>> nc_simplify(a**-1*b**-1*c*a)
(b*a)**(-1)*c*a
>>> expr = (a*b*a*b)**2*a*c*a*c
>>> nc_simplify(expr)
(a*b)**4*(a*c)**2
>>> nc_simplify(expr, deep=False)
(a*b*a*b)**2*(a*c)**2
'''
if isinstance(expr, MatrixExpr):
expr = expr.doit(inv_expand=False)
_Add, _Mul, _Pow, _Symbol = MatAdd, MatMul, MatPow, MatrixSymbol
else:
_Add, _Mul, _Pow, _Symbol = Add, Mul, Pow, Symbol
# =========== Auxiliary functions ========================
def _overlaps(args):
# Calculate a list of lists m such that m[i][j] contains the lengths
# of all possible overlaps between args[:i+1] and args[i+1+j:].
# An overlap is a suffix of the prefix that matches a prefix
# of the suffix.
# For example, let expr=c*a*b*a*b*a*b*a*b. Then m[3][0] contains
# the lengths of overlaps of c*a*b*a*b with a*b*a*b. The overlaps
# are a*b*a*b, a*b and the empty word so that m[3][0]=[4,2,0].
# All overlaps rather than only the longest one are recorded
# because this information helps calculate other overlap lengths.
m = [[([1, 0] if a == args[0] else [0]) for a in args[1:]]]
for i in range(1, len(args)):
overlaps = []
j = 0
for j in range(len(args) - i - 1):
overlap = []
for v in m[i-1][j+1]:
if j + i + 1 + v < len(args) and args[i] == args[j+i+1+v]:
overlap.append(v + 1)
overlap += [0]
overlaps.append(overlap)
m.append(overlaps)
return m
def _reduce_inverses(_args):
# replace consecutive negative powers by an inverse
# of a product of positive powers, e.g. a**-1*b**-1*c
# will simplify to (a*b)**-1*c;
# return that new args list and the number of negative
# powers in it (inv_tot)
inv_tot = 0 # total number of inverses
inverses = []
args = []
for arg in _args:
if isinstance(arg, _Pow) and arg.args[1] < 0:
inverses = [arg**-1] + inverses
inv_tot += 1
else:
if len(inverses) == 1:
args.append(inverses[0]**-1)
elif len(inverses) > 1:
args.append(_Pow(_Mul(*inverses), -1))
inv_tot -= len(inverses) - 1
inverses = []
args.append(arg)
if inverses:
args.append(_Pow(_Mul(*inverses), -1))
inv_tot -= len(inverses) - 1
return inv_tot, tuple(args)
def get_score(s):
# compute the number of arguments of s
# (including in nested expressions) overall
# but ignore exponents
if isinstance(s, _Pow):
return get_score(s.args[0])
elif isinstance(s, (_Add, _Mul)):
return sum([get_score(a) for a in s.args])
return 1
def compare(s, alt_s):
# compare two possible simplifications and return a
# "better" one
if s != alt_s and get_score(alt_s) < get_score(s):
return alt_s
return s
# ========================================================
if not isinstance(expr, (_Add, _Mul, _Pow)) or expr.is_commutative:
return expr
args = expr.args[:]
if isinstance(expr, _Pow):
if deep:
return _Pow(nc_simplify(args[0]), args[1]).doit()
else:
return expr
elif isinstance(expr, _Add):
return _Add(*[nc_simplify(a, deep=deep) for a in args]).doit()
else:
# get the non-commutative part
c_args, args = expr.args_cnc()
com_coeff = Mul(*c_args)
if com_coeff != 1:
return com_coeff*nc_simplify(expr/com_coeff, deep=deep)
inv_tot, args = _reduce_inverses(args)
# if most arguments are negative, work with the inverse
# of the expression, e.g. a**-1*b*a**-1*c**-1 will become
# (c*a*b**-1*a)**-1 at the end so can work with c*a*b**-1*a
invert = False
if inv_tot > len(args)/2:
invert = True
args = [a**-1 for a in args[::-1]]
if deep:
args = tuple(nc_simplify(a) for a in args)
m = _overlaps(args)
# simps will be {subterm: end} where `end` is the ending
# index of a sequence of repetitions of subterm;
# this is for not wasting time with subterms that are part
# of longer, already considered sequences
simps = {}
post = 1
pre = 1
# the simplification coefficient is the number of
# arguments by which contracting a given sequence
# would reduce the word; e.g. in a*b*a*b*c*a*b*c,
# contracting a*b*a*b to (a*b)**2 removes 3 arguments
# while a*b*c*a*b*c to (a*b*c)**2 removes 6. It's
# better to contract the latter so simplification
# with a maximum simplification coefficient will be chosen
max_simp_coeff = 0
simp = None # information about future simplification
for i in range(1, len(args)):
simp_coeff = 0
l = 0 # length of a subterm
p = 0 # the power of a subterm
if i < len(args) - 1:
rep = m[i][0]
start = i # starting index of the repeated sequence
end = i+1 # ending index of the repeated sequence
if i == len(args)-1 or rep == [0]:
# no subterm is repeated at this stage, at least as
# far as the arguments are concerned - there may be
# a repetition if powers are taken into account
if (isinstance(args[i], _Pow) and
not isinstance(args[i].args[0], _Symbol)):
subterm = args[i].args[0].args
l = len(subterm)
if args[i-l:i] == subterm:
# e.g. a*b in a*b*(a*b)**2 is not repeated
# in args (= [a, b, (a*b)**2]) but it
# can be matched here
p += 1
start -= l
if args[i+1:i+1+l] == subterm:
# e.g. a*b in (a*b)**2*a*b
p += 1
end += l
if p:
p += args[i].args[1]
else:
continue
else:
l = rep[0] # length of the longest repeated subterm at this point
start -= l - 1
subterm = args[start:end]
p = 2
end += l
if subterm in simps and simps[subterm] >= start:
# the subterm is part of a sequence that
# has already been considered
continue
# count how many times it's repeated
while end < len(args):
if l in m[end-1][0]:
p += 1
end += l
elif isinstance(args[end], _Pow) and args[end].args[0].args == subterm:
# for cases like a*b*a*b*(a*b)**2*a*b
p += args[end].args[1]
end += 1
else:
break
# see if another match can be made, e.g.
# for b*a**2 in b*a**2*b*a**3 or a*b in
# a**2*b*a*b
pre_exp = 0
pre_arg = 1
if start - l >= 0 and args[start-l+1:start] == subterm[1:]:
if isinstance(subterm[0], _Pow):
pre_arg = subterm[0].args[0]
exp = subterm[0].args[1]
else:
pre_arg = subterm[0]
exp = 1
if isinstance(args[start-l], _Pow) and args[start-l].args[0] == pre_arg:
pre_exp = args[start-l].args[1] - exp
start -= l
p += 1
elif args[start-l] == pre_arg:
pre_exp = 1 - exp
start -= l
p += 1
post_exp = 0
post_arg = 1
if end + l - 1 < len(args) and args[end:end+l-1] == subterm[:-1]:
if isinstance(subterm[-1], _Pow):
post_arg = subterm[-1].args[0]
exp = subterm[-1].args[1]
else:
post_arg = subterm[-1]
exp = 1
if isinstance(args[end+l-1], _Pow) and args[end+l-1].args[0] == post_arg:
post_exp = args[end+l-1].args[1] - exp
end += l
p += 1
elif args[end+l-1] == post_arg:
post_exp = 1 - exp
end += l
p += 1
# Consider a*b*a**2*b*a**2*b*a:
# b*a**2 is explicitly repeated, but note
# that in this case a*b*a is also repeated
# so there are two possible simplifications:
# a*(b*a**2)**3*a**-1 or (a*b*a)**3
# The latter is obviously simpler.
# But in a*b*a**2*b**2*a**2 the simplifications are
# a*(b*a**2)**2 and (a*b*a)**3*a in which case
# it's better to stick with the shorter subterm
if post_exp and exp % 2 == 0 and start > 0:
exp = exp/2
_pre_exp = 1
_post_exp = 1
if isinstance(args[start-1], _Pow) and args[start-1].args[0] == post_arg:
_post_exp = post_exp + exp
_pre_exp = args[start-1].args[1] - exp
elif args[start-1] == post_arg:
_post_exp = post_exp + exp
_pre_exp = 1 - exp
if _pre_exp == 0 or _post_exp == 0:
if not pre_exp:
start -= 1
post_exp = _post_exp
pre_exp = _pre_exp
pre_arg = post_arg
subterm = (post_arg**exp,) + subterm[:-1] + (post_arg**exp,)
simp_coeff += end-start
if post_exp:
simp_coeff -= 1
if pre_exp:
simp_coeff -= 1
simps[subterm] = end
if simp_coeff > max_simp_coeff:
max_simp_coeff = simp_coeff
simp = (start, _Mul(*subterm), p, end, l)
pre = pre_arg**pre_exp
post = post_arg**post_exp
if simp:
subterm = _Pow(nc_simplify(simp[1], deep=deep), simp[2])
pre = nc_simplify(_Mul(*args[:simp[0]])*pre, deep=deep)
post = post*nc_simplify(_Mul(*args[simp[3]:]), deep=deep)
simp = pre*subterm*post
if pre != 1 or post != 1:
# new simplifications may be possible but no need
# to recurse over arguments
simp = nc_simplify(simp, deep=False)
else:
simp = _Mul(*args)
if invert:
simp = _Pow(simp, -1)
# see if factor_nc(expr) is simplified better
if not isinstance(expr, MatrixExpr):
f_expr = factor_nc(expr)
if f_expr != expr:
alt_simp = nc_simplify(f_expr, deep=deep)
simp = compare(simp, alt_simp)
else:
simp = simp.doit(inv_expand=False)
return simp
def dotprodsimp(expr, withsimp=False):
"""Simplification for a sum of products targeted at the kind of blowup that
occurs during summation of products. Intended to reduce expression blowup
during matrix multiplication or other similar operations. Only works with
algebraic expressions and does not recurse into non.
Parameters
==========
withsimp : bool, optional
Specifies whether a flag should be returned along with the expression
to indicate roughly whether simplification was successful. It is used
in ``MatrixArithmetic._eval_pow_by_recursion`` to avoid attempting to
simplify an expression repetitively which does not simplify.
"""
def count_ops_alg(expr):
"""Optimized count algebraic operations with no recursion into
non-algebraic args that ``core.function.count_ops`` does. Also returns
whether rational functions may be present according to negative
exponents of powers or non-number fractions.
Returns
=======
ops, ratfunc : int, bool
``ops`` is the number of algebraic operations starting at the top
level expression (not recursing into non-alg children). ``ratfunc``
specifies whether the expression MAY contain rational functions
which ``cancel`` MIGHT optimize.
"""
ops = 0
args = [expr]
ratfunc = False
while args:
a = args.pop()
if not isinstance(a, Basic):
continue
if a.is_Rational:
if a is not S.One: # -1/3 = NEG + DIV
ops += bool (a.p < 0) + bool (a.q != 1)
elif a.is_Mul:
if a.could_extract_minus_sign():
ops += 1
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 += 1 + bool (n < 0)
args.append(d) # won't be -Mul but could be Add
elif d is not S.One:
if not d.is_Integer:
args.append(d)
ratfunc=True
ops += 1
args.append(n) # could be -Mul
else:
ops += len(a.args) - 1
args.extend(a.args)
elif a.is_Add:
laargs = len(a.args)
negs = 0
for ai in a.args:
if ai.could_extract_minus_sign():
negs += 1
ai = -ai
args.append(ai)
ops += laargs - (negs != laargs) # -x - y = NEG + SUB
elif a.is_Pow:
ops += 1
args.append(a.base)
if not ratfunc:
ratfunc = a.exp.is_negative is not False
return ops, ratfunc
def nonalg_subs_dummies(expr, dummies):
"""Substitute dummy variables for non-algebraic expressions to avoid
evaluation of non-algebraic terms that ``polys.polytools.cancel`` does.
"""
if not expr.args:
return expr
if expr.is_Add or expr.is_Mul or expr.is_Pow:
args = None
for i, a in enumerate(expr.args):
c = nonalg_subs_dummies(a, dummies)
if c is a:
continue
if args is None:
args = list(expr.args)
args[i] = c
if args is None:
return expr
return expr.func(*args)
return dummies.setdefault(expr, Dummy())
simplified = False # doesn't really mean simplified, rather "can simplify again"
if isinstance(expr, Basic) and (expr.is_Add or expr.is_Mul or expr.is_Pow):
expr2 = expr.expand(deep=True, modulus=None, power_base=False,
power_exp=False, mul=True, log=False, multinomial=True, basic=False)
if expr2 != expr:
expr = expr2
simplified = True
exprops, ratfunc = count_ops_alg(expr)
if exprops >= 6: # empirically tested cutoff for expensive simplification
if ratfunc:
dummies = {}
expr2 = nonalg_subs_dummies(expr, dummies)
if expr2 is expr or count_ops_alg(expr2)[0] >= 6: # check again after substitution
expr3 = cancel(expr2)
if expr3 != expr2:
expr = expr3.subs([(d, e) for e, d in dummies.items()])
simplified = True
# very special case: x/(x-1) - 1/(x-1) -> 1
elif (exprops == 5 and expr.is_Add and expr.args [0].is_Mul and
expr.args [1].is_Mul and expr.args [0].args [-1].is_Pow and
expr.args [1].args [-1].is_Pow and
expr.args [0].args [-1].exp is S.NegativeOne and
expr.args [1].args [-1].exp is S.NegativeOne):
expr2 = together (expr)
expr2ops = count_ops_alg(expr2)[0]
if expr2ops < exprops:
expr = expr2
simplified = True
else:
simplified = True
return (expr, simplified) if withsimp else expr
bottom_up = deprecated(
"""
Using bottom_up from the sympy.simplify.simplify submodule is
deprecated.
Instead, use bottom_up from the top-level sympy namespace, like
sympy.bottom_up
""",
deprecated_since_version="1.10",
active_deprecations_target="deprecated-traversal-functions-moved",
)(_bottom_up)
# XXX: This function really should either be private API or exported in the
# top-level sympy/__init__.py
walk = deprecated(
"""
Using walk from the sympy.simplify.simplify submodule is
deprecated.
Instead, use walk from sympy.core.traversal.walk
""",
deprecated_since_version="1.10",
active_deprecations_target="deprecated-traversal-functions-moved",
)(_walk)
|
a67fedf58ae4fd22f55f4be5fb3551eb265ac64636e43e0cc1306fe32c270f56 | from sympy.core.traversal import use as _use
from sympy.utilities.decorator import deprecated
use = deprecated(
"""
Using use from the sympy.simplify.traversaltools submodule is
deprecated.
Instead, use use from the top-level sympy namespace, like
sympy.use
""",
deprecated_since_version="1.10",
active_deprecations_target="deprecated-traversal-functions-moved"
)(_use)
|
f5861d500f1c8907452faf9f28bd00ba0ce95a41f896b29ceaf96ed86a20691a | from collections import defaultdict
from functools import reduce
from sympy.core.function import expand_log, count_ops, _coeff_isneg
from sympy.core import sympify, Basic, Dummy, S, Add, Mul, Pow, expand_mul, factor_terms
from sympy.core.sorting import ordered, default_sort_key
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.matrices.expressions.matexpr import MatrixSymbol
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))
"""
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)
if e.is_Add and (b.is_positive or e.is_integer):
e = factor_terms(e)
if _coeff_isneg(e):
e = -e
b = 1/b
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, 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))
|
bec4a414de5387cc8b447ace1808bd5c95976353db3058cfe046b2929954187e | from collections import defaultdict
from functools import reduce
from sympy.core import (sympify, Basic, S, Expr, factor_terms,
Mul, Add, bottom_up)
from sympy.core.cache import cacheit
from sympy.core.function import (count_ops, _mexpand, FunctionClass, expand,
expand_mul, Derivative)
from sympy.core.numbers import I, Integer, igcd
from sympy.core.sorting import _nodes
from sympy.core.symbol import Dummy, symbols, Wild
from sympy.external.gmpy import SYMPY_INTS
from sympy.functions import sin, cos, exp, cosh, tanh, sinh, tan, cot, coth
from sympy.functions.elementary.hyperbolic import HyperbolicFunction
from sympy.functions.elementary.trigonometric import TrigonometricFunction
from sympy.polys import Poly, factor, cancel, parallel_poly_from_expr
from sympy.polys.domains import ZZ
from sympy.polys.polyerrors import PolificationFailed
from sympy.polys.polytools import groebner
from sympy.simplify.cse_main import cse
from sympy.strategies.core import identity
from sympy.strategies.tree import greedy
from sympy.utilities.iterables import iterable
from sympy.utilities.misc import debug
def trigsimp_groebner(expr, hints=[], quick=False, order="grlex",
polynomial=False):
"""
Simplify trigonometric expressions using a groebner basis algorithm.
Explanation
===========
This routine takes a fraction involving trigonometric or hyperbolic
expressions, and tries to simplify it. The primary metric is the
total degree. Some attempts are made to choose the simplest possible
expression of the minimal degree, but this is non-rigorous, and also
very slow (see the ``quick=True`` option).
If ``polynomial`` is set to True, instead of simplifying numerator and
denominator together, this function just brings numerator and denominator
into a canonical form. This is much faster, but has potentially worse
results. However, if the input is a polynomial, then the result is
guaranteed to be an equivalent polynomial of minimal degree.
The most important option is hints. Its entries can be any of the
following:
- a natural number
- a function
- an iterable of the form (func, var1, var2, ...)
- anything else, interpreted as a generator
A number is used to indicate that the search space should be increased.
A function is used to indicate that said function is likely to occur in a
simplified expression.
An iterable is used indicate that func(var1 + var2 + ...) is likely to
occur in a simplified .
An additional generator also indicates that it is likely to occur.
(See examples below).
This routine carries out various computationally intensive algorithms.
The option ``quick=True`` can be used to suppress one particularly slow
step (at the expense of potentially more complicated results, but never at
the expense of increased total degree).
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import sin, tan, cos, sinh, cosh, tanh
>>> from sympy.simplify.trigsimp import trigsimp_groebner
Suppose you want to simplify ``sin(x)*cos(x)``. Naively, nothing happens:
>>> ex = sin(x)*cos(x)
>>> trigsimp_groebner(ex)
sin(x)*cos(x)
This is because ``trigsimp_groebner`` only looks for a simplification
involving just ``sin(x)`` and ``cos(x)``. You can tell it to also try
``2*x`` by passing ``hints=[2]``:
>>> trigsimp_groebner(ex, hints=[2])
sin(2*x)/2
>>> trigsimp_groebner(sin(x)**2 - cos(x)**2, hints=[2])
-cos(2*x)
Increasing the search space this way can quickly become expensive. A much
faster way is to give a specific expression that is likely to occur:
>>> trigsimp_groebner(ex, hints=[sin(2*x)])
sin(2*x)/2
Hyperbolic expressions are similarly supported:
>>> trigsimp_groebner(sinh(2*x)/sinh(x))
2*cosh(x)
Note how no hints had to be passed, since the expression already involved
``2*x``.
The tangent function is also supported. You can either pass ``tan`` in the
hints, to indicate that tan should be tried whenever cosine or sine are,
or you can pass a specific generator:
>>> trigsimp_groebner(sin(x)/cos(x), hints=[tan])
tan(x)
>>> trigsimp_groebner(sinh(x)/cosh(x), hints=[tanh(x)])
tanh(x)
Finally, you can use the iterable form to suggest that angle sum formulae
should be tried:
>>> ex = (tan(x) + tan(y))/(1 - tan(x)*tan(y))
>>> trigsimp_groebner(ex, hints=[(tan, x, y)])
tan(x + y)
"""
# TODO
# - preprocess by replacing everything by funcs we can handle
# - optionally use cot instead of tan
# - more intelligent hinting.
# For example, if the ideal is small, and we have sin(x), sin(y),
# add sin(x + y) automatically... ?
# - algebraic numbers ...
# - expressions of lowest degree are not distinguished properly
# e.g. 1 - sin(x)**2
# - we could try to order the generators intelligently, so as to influence
# which monomials appear in the quotient basis
# THEORY
# ------
# Ratsimpmodprime above can be used to "simplify" a rational function
# modulo a prime ideal. "Simplify" mainly means finding an equivalent
# expression of lower total degree.
#
# We intend to use this to simplify trigonometric functions. To do that,
# we need to decide (a) which ring to use, and (b) modulo which ideal to
# simplify. In practice, (a) means settling on a list of "generators"
# a, b, c, ..., such that the fraction we want to simplify is a rational
# function in a, b, c, ..., with coefficients in ZZ (integers).
# (2) means that we have to decide what relations to impose on the
# generators. There are two practical problems:
# (1) The ideal has to be *prime* (a technical term).
# (2) The relations have to be polynomials in the generators.
#
# We typically have two kinds of generators:
# - trigonometric expressions, like sin(x), cos(5*x), etc
# - "everything else", like gamma(x), pi, etc.
#
# Since this function is trigsimp, we will concentrate on what to do with
# trigonometric expressions. We can also simplify hyperbolic expressions,
# but the extensions should be clear.
#
# One crucial point is that all *other* generators really should behave
# like indeterminates. In particular if (say) "I" is one of them, then
# in fact I**2 + 1 = 0 and we may and will compute non-sensical
# expressions. However, we can work with a dummy and add the relation
# I**2 + 1 = 0 to our ideal, then substitute back in the end.
#
# Now regarding trigonometric generators. We split them into groups,
# according to the argument of the trigonometric functions. We want to
# organise this in such a way that most trigonometric identities apply in
# the same group. For example, given sin(x), cos(2*x) and cos(y), we would
# group as [sin(x), cos(2*x)] and [cos(y)].
#
# Our prime ideal will be built in three steps:
# (1) For each group, compute a "geometrically prime" ideal of relations.
# Geometrically prime means that it generates a prime ideal in
# CC[gens], not just ZZ[gens].
# (2) Take the union of all the generators of the ideals for all groups.
# By the geometric primality condition, this is still prime.
# (3) Add further inter-group relations which preserve primality.
#
# Step (1) works as follows. We will isolate common factors in the
# argument, so that all our generators are of the form sin(n*x), cos(n*x)
# or tan(n*x), with n an integer. Suppose first there are no tan terms.
# The ideal [sin(x)**2 + cos(x)**2 - 1] is geometrically prime, since
# X**2 + Y**2 - 1 is irreducible over CC.
# Now, if we have a generator sin(n*x), than we can, using trig identities,
# express sin(n*x) as a polynomial in sin(x) and cos(x). We can add this
# relation to the ideal, preserving geometric primality, since the quotient
# ring is unchanged.
# Thus we have treated all sin and cos terms.
# For tan(n*x), we add a relation tan(n*x)*cos(n*x) - sin(n*x) = 0.
# (This requires of course that we already have relations for cos(n*x) and
# sin(n*x).) It is not obvious, but it seems that this preserves geometric
# primality.
# XXX A real proof would be nice. HELP!
# Sketch that <S**2 + C**2 - 1, C*T - S> is a prime ideal of
# CC[S, C, T]:
# - it suffices to show that the projective closure in CP**3 is
# irreducible
# - using the half-angle substitutions, we can express sin(x), tan(x),
# cos(x) as rational functions in tan(x/2)
# - from this, we get a rational map from CP**1 to our curve
# - this is a morphism, hence the curve is prime
#
# Step (2) is trivial.
#
# Step (3) works by adding selected relations of the form
# sin(x + y) - sin(x)*cos(y) - sin(y)*cos(x), etc. Geometric primality is
# preserved by the same argument as before.
def parse_hints(hints):
"""Split hints into (n, funcs, iterables, gens)."""
n = 1
funcs, iterables, gens = [], [], []
for e in hints:
if isinstance(e, (SYMPY_INTS, Integer)):
n = e
elif isinstance(e, FunctionClass):
funcs.append(e)
elif iterable(e):
iterables.append((e[0], e[1:]))
# XXX sin(x+2y)?
# Note: we go through polys so e.g.
# sin(-x) -> -sin(x) -> sin(x)
gens.extend(parallel_poly_from_expr(
[e[0](x) for x in e[1:]] + [e[0](Add(*e[1:]))])[1].gens)
else:
gens.append(e)
return n, funcs, iterables, gens
def build_ideal(x, terms):
"""
Build generators for our ideal. ``Terms`` is an iterable with elements of
the form (fn, coeff), indicating that we have a generator fn(coeff*x).
If any of the terms is trigonometric, sin(x) and cos(x) are guaranteed
to appear in terms. Similarly for hyperbolic functions. For tan(n*x),
sin(n*x) and cos(n*x) are guaranteed.
"""
I = []
y = Dummy('y')
for fn, coeff in terms:
for c, s, t, rel in (
[cos, sin, tan, cos(x)**2 + sin(x)**2 - 1],
[cosh, sinh, tanh, cosh(x)**2 - sinh(x)**2 - 1]):
if coeff == 1 and fn in [c, s]:
I.append(rel)
elif fn == t:
I.append(t(coeff*x)*c(coeff*x) - s(coeff*x))
elif fn in [c, s]:
cn = fn(coeff*y).expand(trig=True).subs(y, x)
I.append(fn(coeff*x) - cn)
return list(set(I))
def analyse_gens(gens, hints):
"""
Analyse the generators ``gens``, using the hints ``hints``.
The meaning of ``hints`` is described in the main docstring.
Return a new list of generators, and also the ideal we should
work with.
"""
# First parse the hints
n, funcs, iterables, extragens = parse_hints(hints)
debug('n=%s' % n, 'funcs:', funcs, 'iterables:',
iterables, 'extragens:', extragens)
# We just add the extragens to gens and analyse them as before
gens = list(gens)
gens.extend(extragens)
# remove duplicates
funcs = list(set(funcs))
iterables = list(set(iterables))
gens = list(set(gens))
# all the functions we can do anything with
allfuncs = {sin, cos, tan, sinh, cosh, tanh}
# sin(3*x) -> ((3, x), sin)
trigterms = [(g.args[0].as_coeff_mul(), g.func) for g in gens
if g.func in allfuncs]
# Our list of new generators - start with anything that we cannot
# work with (i.e. is not a trigonometric term)
freegens = [g for g in gens if g.func not in allfuncs]
newgens = []
trigdict = {}
for (coeff, var), fn in trigterms:
trigdict.setdefault(var, []).append((coeff, fn))
res = [] # the ideal
for key, val in trigdict.items():
# We have now assembeled a dictionary. Its keys are common
# arguments in trigonometric expressions, and values are lists of
# pairs (fn, coeff). x0, (fn, coeff) in trigdict means that we
# need to deal with fn(coeff*x0). We take the rational gcd of the
# coeffs, call it ``gcd``. We then use x = x0/gcd as "base symbol",
# all other arguments are integral multiples thereof.
# We will build an ideal which works with sin(x), cos(x).
# If hint tan is provided, also work with tan(x). Moreover, if
# n > 1, also work with sin(k*x) for k <= n, and similarly for cos
# (and tan if the hint is provided). Finally, any generators which
# the ideal does not work with but we need to accommodate (either
# because it was in expr or because it was provided as a hint)
# we also build into the ideal.
# This selection process is expressed in the list ``terms``.
# build_ideal then generates the actual relations in our ideal,
# from this list.
fns = [x[1] for x in val]
val = [x[0] for x in val]
gcd = reduce(igcd, val)
terms = [(fn, v/gcd) for (fn, v) in zip(fns, val)]
fs = set(funcs + fns)
for c, s, t in ([cos, sin, tan], [cosh, sinh, tanh]):
if any(x in fs for x in (c, s, t)):
fs.add(c)
fs.add(s)
for fn in fs:
for k in range(1, n + 1):
terms.append((fn, k))
extra = []
for fn, v in terms:
if fn == tan:
extra.append((sin, v))
extra.append((cos, v))
if fn in [sin, cos] and tan in fs:
extra.append((tan, v))
if fn == tanh:
extra.append((sinh, v))
extra.append((cosh, v))
if fn in [sinh, cosh] and tanh in fs:
extra.append((tanh, v))
terms.extend(extra)
x = gcd*Mul(*key)
r = build_ideal(x, terms)
res.extend(r)
newgens.extend({fn(v*x) for fn, v in terms})
# Add generators for compound expressions from iterables
for fn, args in iterables:
if fn == tan:
# Tan expressions are recovered from sin and cos.
iterables.extend([(sin, args), (cos, args)])
elif fn == tanh:
# Tanh expressions are recovered from sihn and cosh.
iterables.extend([(sinh, args), (cosh, args)])
else:
dummys = symbols('d:%i' % len(args), cls=Dummy)
expr = fn( Add(*dummys)).expand(trig=True).subs(list(zip(dummys, args)))
res.append(fn(Add(*args)) - expr)
if myI in gens:
res.append(myI**2 + 1)
freegens.remove(myI)
newgens.append(myI)
return res, freegens, newgens
myI = Dummy('I')
expr = expr.subs(S.ImaginaryUnit, myI)
subs = [(myI, S.ImaginaryUnit)]
num, denom = cancel(expr).as_numer_denom()
try:
(pnum, pdenom), opt = parallel_poly_from_expr([num, denom])
except PolificationFailed:
return expr
debug('initial gens:', opt.gens)
ideal, freegens, gens = analyse_gens(opt.gens, hints)
debug('ideal:', ideal)
debug('new gens:', gens, " -- len", len(gens))
debug('free gens:', freegens, " -- len", len(gens))
# NOTE we force the domain to be ZZ to stop polys from injecting generators
# (which is usually a sign of a bug in the way we build the ideal)
if not gens:
return expr
G = groebner(ideal, order=order, gens=gens, domain=ZZ)
debug('groebner basis:', list(G), " -- len", len(G))
# If our fraction is a polynomial in the free generators, simplify all
# coefficients separately:
from sympy.simplify.ratsimp import ratsimpmodprime
if freegens and pdenom.has_only_gens(*set(gens).intersection(pdenom.gens)):
num = Poly(num, gens=gens+freegens).eject(*gens)
res = []
for monom, coeff in num.terms():
ourgens = set(parallel_poly_from_expr([coeff, denom])[1].gens)
# We compute the transitive closure of all generators that can
# be reached from our generators through relations in the ideal.
changed = True
while changed:
changed = False
for p in ideal:
p = Poly(p)
if not ourgens.issuperset(p.gens) and \
not p.has_only_gens(*set(p.gens).difference(ourgens)):
changed = True
ourgens.update(p.exclude().gens)
# NOTE preserve order!
realgens = [x for x in gens if x in ourgens]
# The generators of the ideal have now been (implicitly) split
# into two groups: those involving ourgens and those that don't.
# Since we took the transitive closure above, these two groups
# live in subgrings generated by a *disjoint* set of variables.
# Any sensible groebner basis algorithm will preserve this disjoint
# structure (i.e. the elements of the groebner basis can be split
# similarly), and and the two subsets of the groebner basis then
# form groebner bases by themselves. (For the smaller generating
# sets, of course.)
ourG = [g.as_expr() for g in G.polys if
g.has_only_gens(*ourgens.intersection(g.gens))]
res.append(Mul(*[a**b for a, b in zip(freegens, monom)]) * \
ratsimpmodprime(coeff/denom, ourG, order=order,
gens=realgens, quick=quick, domain=ZZ,
polynomial=polynomial).subs(subs))
return Add(*res)
# NOTE The following is simpler and has less assumptions on the
# groebner basis algorithm. If the above turns out to be broken,
# use this.
return Add(*[Mul(*[a**b for a, b in zip(freegens, monom)]) * \
ratsimpmodprime(coeff/denom, list(G), order=order,
gens=gens, quick=quick, domain=ZZ)
for monom, coeff in num.terms()])
else:
return ratsimpmodprime(
expr, list(G), order=order, gens=freegens+gens,
quick=quick, domain=ZZ, polynomial=polynomial).subs(subs)
_trigs = (TrigonometricFunction, HyperbolicFunction)
def trigsimp(expr, **opts):
"""Returns a reduced expression by using known trig identities.
Parameters
==========
method : string, optional
Specifies the method to use. Valid choices are:
- ``'matching'``, default
- ``'groebner'``
- ``'combined'``
- ``'fu'``
- ``'old'``
If ``'matching'``, simplify the expression recursively by targeting
common patterns. If ``'groebner'``, apply an experimental groebner
basis algorithm. In this case further options are forwarded to
``trigsimp_groebner``, please refer to
its docstring. If ``'combined'``, it first runs the groebner basis
algorithm with small default parameters, then runs the ``'matching'``
algorithm. If ``'fu'``, run the collection of trigonometric
transformations described by Fu, et al. (see the
:py:func:`~sympy.simplify.fu.fu` docstring). If ``'old'``, the original
SymPy trig simplication function is run.
opts :
Optional keyword arguments passed to the method. See each method's
function docstring for details.
Examples
========
>>> from sympy import trigsimp, sin, cos, log
>>> from sympy.abc import x
>>> e = 2*sin(x)**2 + 2*cos(x)**2
>>> trigsimp(e)
2
Simplification occurs wherever trigonometric functions are located.
>>> trigsimp(log(e))
log(2)
Using ``method='groebner'`` (or ``method='combined'``) might lead to
greater simplification.
The old trigsimp routine can be accessed as with method ``method='old'``.
>>> from sympy import coth, tanh
>>> t = 3*tanh(x)**7 - 2/coth(x)**7
>>> trigsimp(t, method='old') == t
True
>>> trigsimp(t)
tanh(x)**7
"""
from sympy.simplify.fu import fu
expr = sympify(expr)
_eval_trigsimp = getattr(expr, '_eval_trigsimp', None)
if _eval_trigsimp is not None:
return _eval_trigsimp(**opts)
old = opts.pop('old', False)
if not old:
opts.pop('deep', None)
opts.pop('recursive', None)
method = opts.pop('method', 'matching')
else:
method = 'old'
def groebnersimp(ex, **opts):
def traverse(e):
if e.is_Atom:
return e
args = [traverse(x) for x in e.args]
if e.is_Function or e.is_Pow:
args = [trigsimp_groebner(x, **opts) for x in args]
return e.func(*args)
new = traverse(ex)
if not isinstance(new, Expr):
return new
return trigsimp_groebner(new, **opts)
trigsimpfunc = {
'fu': (lambda x: fu(x, **opts)),
'matching': (lambda x: futrig(x)),
'groebner': (lambda x: groebnersimp(x, **opts)),
'combined': (lambda x: futrig(groebnersimp(x,
polynomial=True, hints=[2, tan]))),
'old': lambda x: trigsimp_old(x, **opts),
}[method]
return trigsimpfunc(expr)
def exptrigsimp(expr):
"""
Simplifies exponential / trigonometric / hyperbolic functions.
Examples
========
>>> from sympy import exptrigsimp, exp, cosh, sinh
>>> from sympy.abc import z
>>> exptrigsimp(exp(z) + exp(-z))
2*cosh(z)
>>> exptrigsimp(cosh(z) - sinh(z))
exp(-z)
"""
from sympy.simplify.fu import hyper_as_trig, TR2i
def exp_trig(e):
# select the better of e, and e rewritten in terms of exp or trig
# functions
choices = [e]
if e.has(*_trigs):
choices.append(e.rewrite(exp))
choices.append(e.rewrite(cos))
return min(*choices, key=count_ops)
newexpr = bottom_up(expr, exp_trig)
def f(rv):
if not rv.is_Mul:
return rv
commutative_part, noncommutative_part = rv.args_cnc()
# Since as_powers_dict loses order information,
# if there is more than one noncommutative factor,
# it should only be used to simplify the commutative part.
if (len(noncommutative_part) > 1):
return f(Mul(*commutative_part))*Mul(*noncommutative_part)
rvd = rv.as_powers_dict()
newd = rvd.copy()
def signlog(expr, sign=S.One):
if expr is S.Exp1:
return sign, S.One
elif isinstance(expr, exp) or (expr.is_Pow and expr.base == S.Exp1):
return sign, expr.exp
elif sign is S.One:
return signlog(-expr, sign=-S.One)
else:
return None, None
ee = rvd[S.Exp1]
for k in rvd:
if k.is_Add and len(k.args) == 2:
# k == c*(1 + sign*E**x)
c = k.args[0]
sign, x = signlog(k.args[1]/c)
if not x:
continue
m = rvd[k]
newd[k] -= m
if ee == -x*m/2:
# sinh and cosh
newd[S.Exp1] -= ee
ee = 0
if sign == 1:
newd[2*c*cosh(x/2)] += m
else:
newd[-2*c*sinh(x/2)] += m
elif newd[1 - sign*S.Exp1**x] == -m:
# tanh
del newd[1 - sign*S.Exp1**x]
if sign == 1:
newd[-c/tanh(x/2)] += m
else:
newd[-c*tanh(x/2)] += m
else:
newd[1 + sign*S.Exp1**x] += m
newd[c] += m
return Mul(*[k**newd[k] for k in newd])
newexpr = bottom_up(newexpr, f)
# sin/cos and sinh/cosh ratios to tan and tanh, respectively
if newexpr.has(HyperbolicFunction):
e, f = hyper_as_trig(newexpr)
newexpr = f(TR2i(e))
if newexpr.has(TrigonometricFunction):
newexpr = TR2i(newexpr)
# can we ever generate an I where there was none previously?
if not (newexpr.has(I) and not expr.has(I)):
expr = newexpr
return expr
#-------------------- the old trigsimp routines ---------------------
def trigsimp_old(expr, *, first=True, **opts):
"""
Reduces expression by using known trig identities.
Notes
=====
deep:
- Apply trigsimp inside all objects with arguments
recursive:
- Use common subexpression elimination (cse()) and apply
trigsimp recursively (this is quite expensive if the
expression is large)
method:
- Determine the method to use. Valid choices are 'matching' (default),
'groebner', 'combined', 'fu' and 'futrig'. If 'matching', simplify the
expression recursively by pattern matching. If 'groebner', apply an
experimental groebner basis algorithm. In this case further options
are forwarded to ``trigsimp_groebner``, please refer to its docstring.
If 'combined', first run the groebner basis algorithm with small
default parameters, then run the 'matching' algorithm. 'fu' runs the
collection of trigonometric transformations described by Fu, et al.
(see the `fu` docstring) while `futrig` runs a subset of Fu-transforms
that mimic the behavior of `trigsimp`.
compare:
- show input and output from `trigsimp` and `futrig` when different,
but returns the `trigsimp` value.
Examples
========
>>> from sympy import trigsimp, sin, cos, log, cot
>>> from sympy.abc import x
>>> e = 2*sin(x)**2 + 2*cos(x)**2
>>> trigsimp(e, old=True)
2
>>> trigsimp(log(e), old=True)
log(2*sin(x)**2 + 2*cos(x)**2)
>>> trigsimp(log(e), deep=True, old=True)
log(2)
Using `method="groebner"` (or `"combined"`) can sometimes lead to a lot
more simplification:
>>> e = (-sin(x) + 1)/cos(x) + cos(x)/(-sin(x) + 1)
>>> trigsimp(e, old=True)
(1 - sin(x))/cos(x) + cos(x)/(1 - sin(x))
>>> trigsimp(e, method="groebner", old=True)
2/cos(x)
>>> trigsimp(1/cot(x)**2, compare=True, old=True)
futrig: tan(x)**2
cot(x)**(-2)
"""
old = expr
if first:
if not expr.has(*_trigs):
return expr
trigsyms = set().union(*[t.free_symbols for t in expr.atoms(*_trigs)])
if len(trigsyms) > 1:
from sympy.simplify.simplify import separatevars
d = separatevars(expr)
if d.is_Mul:
d = separatevars(d, dict=True) or d
if isinstance(d, dict):
expr = 1
for k, v in d.items():
# remove hollow factoring
was = v
v = expand_mul(v)
opts['first'] = False
vnew = trigsimp(v, **opts)
if vnew == v:
vnew = was
expr *= vnew
old = expr
else:
if d.is_Add:
for s in trigsyms:
r, e = expr.as_independent(s)
if r:
opts['first'] = False
expr = r + trigsimp(e, **opts)
if not expr.is_Add:
break
old = expr
recursive = opts.pop('recursive', False)
deep = opts.pop('deep', False)
method = opts.pop('method', 'matching')
def groebnersimp(ex, deep, **opts):
def traverse(e):
if e.is_Atom:
return e
args = [traverse(x) for x in e.args]
if e.is_Function or e.is_Pow:
args = [trigsimp_groebner(x, **opts) for x in args]
return e.func(*args)
if deep:
ex = traverse(ex)
return trigsimp_groebner(ex, **opts)
trigsimpfunc = {
'matching': (lambda x, d: _trigsimp(x, d)),
'groebner': (lambda x, d: groebnersimp(x, d, **opts)),
'combined': (lambda x, d: _trigsimp(groebnersimp(x,
d, polynomial=True, hints=[2, tan]),
d))
}[method]
if recursive:
w, g = cse(expr)
g = trigsimpfunc(g[0], deep)
for sub in reversed(w):
g = g.subs(sub[0], sub[1])
g = trigsimpfunc(g, deep)
result = g
else:
result = trigsimpfunc(expr, deep)
if opts.get('compare', False):
f = futrig(old)
if f != result:
print('\tfutrig:', f)
return result
def _dotrig(a, b):
"""Helper to tell whether ``a`` and ``b`` have the same sorts
of symbols in them -- no need to test hyperbolic patterns against
expressions that have no hyperbolics in them."""
return a.func == b.func and (
a.has(TrigonometricFunction) and b.has(TrigonometricFunction) or
a.has(HyperbolicFunction) and b.has(HyperbolicFunction))
_trigpat = None
def _trigpats():
global _trigpat
a, b, c = symbols('a b c', cls=Wild)
d = Wild('d', commutative=False)
# for the simplifications like sinh/cosh -> tanh:
# DO NOT REORDER THE FIRST 14 since these are assumed to be in this
# order in _match_div_rewrite.
matchers_division = (
(a*sin(b)**c/cos(b)**c, a*tan(b)**c, sin(b), cos(b)),
(a*tan(b)**c*cos(b)**c, a*sin(b)**c, sin(b), cos(b)),
(a*cot(b)**c*sin(b)**c, a*cos(b)**c, sin(b), cos(b)),
(a*tan(b)**c/sin(b)**c, a/cos(b)**c, sin(b), cos(b)),
(a*cot(b)**c/cos(b)**c, a/sin(b)**c, sin(b), cos(b)),
(a*cot(b)**c*tan(b)**c, a, sin(b), cos(b)),
(a*(cos(b) + 1)**c*(cos(b) - 1)**c,
a*(-sin(b)**2)**c, cos(b) + 1, cos(b) - 1),
(a*(sin(b) + 1)**c*(sin(b) - 1)**c,
a*(-cos(b)**2)**c, sin(b) + 1, sin(b) - 1),
(a*sinh(b)**c/cosh(b)**c, a*tanh(b)**c, S.One, S.One),
(a*tanh(b)**c*cosh(b)**c, a*sinh(b)**c, S.One, S.One),
(a*coth(b)**c*sinh(b)**c, a*cosh(b)**c, S.One, S.One),
(a*tanh(b)**c/sinh(b)**c, a/cosh(b)**c, S.One, S.One),
(a*coth(b)**c/cosh(b)**c, a/sinh(b)**c, S.One, S.One),
(a*coth(b)**c*tanh(b)**c, a, S.One, S.One),
(c*(tanh(a) + tanh(b))/(1 + tanh(a)*tanh(b)),
tanh(a + b)*c, S.One, S.One),
)
matchers_add = (
(c*sin(a)*cos(b) + c*cos(a)*sin(b) + d, sin(a + b)*c + d),
(c*cos(a)*cos(b) - c*sin(a)*sin(b) + d, cos(a + b)*c + d),
(c*sin(a)*cos(b) - c*cos(a)*sin(b) + d, sin(a - b)*c + d),
(c*cos(a)*cos(b) + c*sin(a)*sin(b) + d, cos(a - b)*c + d),
(c*sinh(a)*cosh(b) + c*sinh(b)*cosh(a) + d, sinh(a + b)*c + d),
(c*cosh(a)*cosh(b) + c*sinh(a)*sinh(b) + d, cosh(a + b)*c + d),
)
# for cos(x)**2 + sin(x)**2 -> 1
matchers_identity = (
(a*sin(b)**2, a - a*cos(b)**2),
(a*tan(b)**2, a*(1/cos(b))**2 - a),
(a*cot(b)**2, a*(1/sin(b))**2 - a),
(a*sin(b + c), a*(sin(b)*cos(c) + sin(c)*cos(b))),
(a*cos(b + c), a*(cos(b)*cos(c) - sin(b)*sin(c))),
(a*tan(b + c), a*((tan(b) + tan(c))/(1 - tan(b)*tan(c)))),
(a*sinh(b)**2, a*cosh(b)**2 - a),
(a*tanh(b)**2, a - a*(1/cosh(b))**2),
(a*coth(b)**2, a + a*(1/sinh(b))**2),
(a*sinh(b + c), a*(sinh(b)*cosh(c) + sinh(c)*cosh(b))),
(a*cosh(b + c), a*(cosh(b)*cosh(c) + sinh(b)*sinh(c))),
(a*tanh(b + c), a*((tanh(b) + tanh(c))/(1 + tanh(b)*tanh(c)))),
)
# Reduce any lingering artifacts, such as sin(x)**2 changing
# to 1-cos(x)**2 when sin(x)**2 was "simpler"
artifacts = (
(a - a*cos(b)**2 + c, a*sin(b)**2 + c, cos),
(a - a*(1/cos(b))**2 + c, -a*tan(b)**2 + c, cos),
(a - a*(1/sin(b))**2 + c, -a*cot(b)**2 + c, sin),
(a - a*cosh(b)**2 + c, -a*sinh(b)**2 + c, cosh),
(a - a*(1/cosh(b))**2 + c, a*tanh(b)**2 + c, cosh),
(a + a*(1/sinh(b))**2 + c, a*coth(b)**2 + c, sinh),
# same as above but with noncommutative prefactor
(a*d - a*d*cos(b)**2 + c, a*d*sin(b)**2 + c, cos),
(a*d - a*d*(1/cos(b))**2 + c, -a*d*tan(b)**2 + c, cos),
(a*d - a*d*(1/sin(b))**2 + c, -a*d*cot(b)**2 + c, sin),
(a*d - a*d*cosh(b)**2 + c, -a*d*sinh(b)**2 + c, cosh),
(a*d - a*d*(1/cosh(b))**2 + c, a*d*tanh(b)**2 + c, cosh),
(a*d + a*d*(1/sinh(b))**2 + c, a*d*coth(b)**2 + c, sinh),
)
_trigpat = (a, b, c, d, matchers_division, matchers_add,
matchers_identity, artifacts)
return _trigpat
def _replace_mul_fpowxgpow(expr, f, g, rexp, h, rexph):
"""Helper for _match_div_rewrite.
Replace f(b_)**c_*g(b_)**(rexp(c_)) with h(b)**rexph(c) if f(b_)
and g(b_) are both positive or if c_ is an integer.
"""
# assert expr.is_Mul and expr.is_commutative and f != g
fargs = defaultdict(int)
gargs = defaultdict(int)
args = []
for x in expr.args:
if x.is_Pow or x.func in (f, g):
b, e = x.as_base_exp()
if b.is_positive or e.is_integer:
if b.func == f:
fargs[b.args[0]] += e
continue
elif b.func == g:
gargs[b.args[0]] += e
continue
args.append(x)
common = set(fargs) & set(gargs)
hit = False
while common:
key = common.pop()
fe = fargs.pop(key)
ge = gargs.pop(key)
if fe == rexp(ge):
args.append(h(key)**rexph(fe))
hit = True
else:
fargs[key] = fe
gargs[key] = ge
if not hit:
return expr
while fargs:
key, e = fargs.popitem()
args.append(f(key)**e)
while gargs:
key, e = gargs.popitem()
args.append(g(key)**e)
return Mul(*args)
_idn = lambda x: x
_midn = lambda x: -x
_one = lambda x: S.One
def _match_div_rewrite(expr, i):
"""helper for __trigsimp"""
if i == 0:
expr = _replace_mul_fpowxgpow(expr, sin, cos,
_midn, tan, _idn)
elif i == 1:
expr = _replace_mul_fpowxgpow(expr, tan, cos,
_idn, sin, _idn)
elif i == 2:
expr = _replace_mul_fpowxgpow(expr, cot, sin,
_idn, cos, _idn)
elif i == 3:
expr = _replace_mul_fpowxgpow(expr, tan, sin,
_midn, cos, _midn)
elif i == 4:
expr = _replace_mul_fpowxgpow(expr, cot, cos,
_midn, sin, _midn)
elif i == 5:
expr = _replace_mul_fpowxgpow(expr, cot, tan,
_idn, _one, _idn)
# i in (6, 7) is skipped
elif i == 8:
expr = _replace_mul_fpowxgpow(expr, sinh, cosh,
_midn, tanh, _idn)
elif i == 9:
expr = _replace_mul_fpowxgpow(expr, tanh, cosh,
_idn, sinh, _idn)
elif i == 10:
expr = _replace_mul_fpowxgpow(expr, coth, sinh,
_idn, cosh, _idn)
elif i == 11:
expr = _replace_mul_fpowxgpow(expr, tanh, sinh,
_midn, cosh, _midn)
elif i == 12:
expr = _replace_mul_fpowxgpow(expr, coth, cosh,
_midn, sinh, _midn)
elif i == 13:
expr = _replace_mul_fpowxgpow(expr, coth, tanh,
_idn, _one, _idn)
else:
return None
return expr
def _trigsimp(expr, deep=False):
# protect the cache from non-trig patterns; we only allow
# trig patterns to enter the cache
if expr.has(*_trigs):
return __trigsimp(expr, deep)
return expr
@cacheit
def __trigsimp(expr, deep=False):
"""recursive helper for trigsimp"""
from sympy.simplify.fu import TR10i
if _trigpat is None:
_trigpats()
a, b, c, d, matchers_division, matchers_add, \
matchers_identity, artifacts = _trigpat
if expr.is_Mul:
# do some simplifications like sin/cos -> tan:
if not expr.is_commutative:
com, nc = expr.args_cnc()
expr = _trigsimp(Mul._from_args(com), deep)*Mul._from_args(nc)
else:
for i, (pattern, simp, ok1, ok2) in enumerate(matchers_division):
if not _dotrig(expr, pattern):
continue
newexpr = _match_div_rewrite(expr, i)
if newexpr is not None:
if newexpr != expr:
expr = newexpr
break
else:
continue
# use SymPy matching instead
res = expr.match(pattern)
if res and res.get(c, 0):
if not res[c].is_integer:
ok = ok1.subs(res)
if not ok.is_positive:
continue
ok = ok2.subs(res)
if not ok.is_positive:
continue
# if "a" contains any of trig or hyperbolic funcs with
# argument "b" then skip the simplification
if any(w.args[0] == res[b] for w in res[a].atoms(
TrigonometricFunction, HyperbolicFunction)):
continue
# simplify and finish:
expr = simp.subs(res)
break # process below
if expr.is_Add:
args = []
for term in expr.args:
if not term.is_commutative:
com, nc = term.args_cnc()
nc = Mul._from_args(nc)
term = Mul._from_args(com)
else:
nc = S.One
term = _trigsimp(term, deep)
for pattern, result in matchers_identity:
res = term.match(pattern)
if res is not None:
term = result.subs(res)
break
args.append(term*nc)
if args != expr.args:
expr = Add(*args)
expr = min(expr, expand(expr), key=count_ops)
if expr.is_Add:
for pattern, result in matchers_add:
if not _dotrig(expr, pattern):
continue
expr = TR10i(expr)
if expr.has(HyperbolicFunction):
res = expr.match(pattern)
# if "d" contains any trig or hyperbolic funcs with
# argument "a" or "b" then skip the simplification;
# this isn't perfect -- see tests
if res is None or not (a in res and b in res) or any(
w.args[0] in (res[a], res[b]) for w in res[d].atoms(
TrigonometricFunction, HyperbolicFunction)):
continue
expr = result.subs(res)
break
# Reduce any lingering artifacts, such as sin(x)**2 changing
# to 1 - cos(x)**2 when sin(x)**2 was "simpler"
for pattern, result, ex in artifacts:
if not _dotrig(expr, pattern):
continue
# Substitute a new wild that excludes some function(s)
# to help influence a better match. This is because
# sometimes, for example, 'a' would match sec(x)**2
a_t = Wild('a', exclude=[ex])
pattern = pattern.subs(a, a_t)
result = result.subs(a, a_t)
m = expr.match(pattern)
was = None
while m and was != expr:
was = expr
if m[a_t] == 0 or \
-m[a_t] in m[c].args or m[a_t] + m[c] == 0:
break
if d in m and m[a_t]*m[d] + m[c] == 0:
break
expr = result.subs(m)
m = expr.match(pattern)
m.setdefault(c, S.Zero)
elif expr.is_Mul or expr.is_Pow or deep and expr.args:
expr = expr.func(*[_trigsimp(a, deep) for a in expr.args])
try:
if not expr.has(*_trigs):
raise TypeError
e = expr.atoms(exp)
new = expr.rewrite(exp, deep=deep)
if new == e:
raise TypeError
fnew = factor(new)
if fnew != new:
new = sorted([new, factor(new)], key=count_ops)[0]
# if all exp that were introduced disappeared then accept it
if not (new.atoms(exp) - e):
expr = new
except TypeError:
pass
return expr
#------------------- end of old trigsimp routines --------------------
def futrig(e, *, hyper=True, **kwargs):
"""Return simplified ``e`` using Fu-like transformations.
This is not the "Fu" algorithm. This is called by default
from ``trigsimp``. By default, hyperbolics subexpressions
will be simplified, but this can be disabled by setting
``hyper=False``.
Examples
========
>>> from sympy import trigsimp, tan, sinh, tanh
>>> from sympy.simplify.trigsimp import futrig
>>> from sympy.abc import x
>>> trigsimp(1/tan(x)**2)
tan(x)**(-2)
>>> futrig(sinh(x)/tanh(x))
cosh(x)
"""
from sympy.simplify.fu import hyper_as_trig
e = sympify(e)
if not isinstance(e, Basic):
return e
if not e.args:
return e
old = e
e = bottom_up(e, _futrig)
if hyper and e.has(HyperbolicFunction):
e, f = hyper_as_trig(e)
e = f(bottom_up(e, _futrig))
if e != old and e.is_Mul and e.args[0].is_Rational:
# redistribute leading coeff on 2-arg Add
e = Mul(*e.as_coeff_Mul())
return e
def _futrig(e):
"""Helper for futrig."""
from sympy.simplify.fu import (
TR1, TR2, TR3, TR2i, TR10, L, TR10i,
TR8, TR6, TR15, TR16, TR111, TR5, TRmorrie, TR11, _TR11, TR14, TR22,
TR12)
if not e.has(TrigonometricFunction):
return e
if e.is_Mul:
coeff, e = e.as_independent(TrigonometricFunction)
else:
coeff = None
Lops = lambda x: (L(x), x.count_ops(), _nodes(x), len(x.args), x.is_Add)
trigs = lambda x: x.has(TrigonometricFunction)
tree = [identity,
(
TR3, # canonical angles
TR1, # sec-csc -> cos-sin
TR12, # expand tan of sum
lambda x: _eapply(factor, x, trigs),
TR2, # tan-cot -> sin-cos
[identity, lambda x: _eapply(_mexpand, x, trigs)],
TR2i, # sin-cos ratio -> tan
lambda x: _eapply(lambda i: factor(i.normal()), x, trigs),
TR14, # factored identities
TR5, # sin-pow -> cos_pow
TR10, # sin-cos of sums -> sin-cos prod
TR11, _TR11, TR6, # reduce double angles and rewrite cos pows
lambda x: _eapply(factor, x, trigs),
TR14, # factored powers of identities
[identity, lambda x: _eapply(_mexpand, x, trigs)],
TR10i, # sin-cos products > sin-cos of sums
TRmorrie,
[identity, TR8], # sin-cos products -> sin-cos of sums
[identity, lambda x: TR2i(TR2(x))], # tan -> sin-cos -> tan
[
lambda x: _eapply(expand_mul, TR5(x), trigs),
lambda x: _eapply(
expand_mul, TR15(x), trigs)], # pos/neg powers of sin
[
lambda x: _eapply(expand_mul, TR6(x), trigs),
lambda x: _eapply(
expand_mul, TR16(x), trigs)], # pos/neg powers of cos
TR111, # tan, sin, cos to neg power -> cot, csc, sec
[identity, TR2i], # sin-cos ratio to tan
[identity, lambda x: _eapply(
expand_mul, TR22(x), trigs)], # tan-cot to sec-csc
TR1, TR2, TR2i,
[identity, lambda x: _eapply(
factor_terms, TR12(x), trigs)], # expand tan of sum
)]
e = greedy(tree, objective=Lops)(e)
if coeff is not None:
e = coeff * e
return e
def _is_Expr(e):
"""_eapply helper to tell whether ``e`` and all its args
are Exprs."""
if isinstance(e, Derivative):
return _is_Expr(e.expr)
if not isinstance(e, Expr):
return False
return all(_is_Expr(i) for i in e.args)
def _eapply(func, e, cond=None):
"""Apply ``func`` to ``e`` if all args are Exprs else only
apply it to those args that *are* Exprs."""
if not isinstance(e, Expr):
return e
if _is_Expr(e) or not e.args:
return func(e)
return e.func(*[
_eapply(func, ei) if (cond is None or cond(ei)) else ei
for ei in e.args])
|
4a76ffb11bc9532886f66b21f209b2a705a5367157eeeb91565fdf5c061f2b54 | """ Tools for doing common subexpression elimination.
"""
from collections import defaultdict
from sympy.core import Basic, Mul, Add, Pow, sympify
from sympy.core.containers import Tuple, OrderedSet
from sympy.core.exprtools import factor_terms
from sympy.core.singleton import S
from sympy.core.sorting import ordered
from sympy.core.symbol import symbols, Symbol
from sympy.matrices import (MatrixBase, Matrix, ImmutableMatrix,
SparseMatrix, ImmutableSparseMatrix)
from sympy.matrices.expressions import (MatrixExpr, MatrixSymbol, MatMul,
MatAdd, MatPow)
from sympy.matrices.expressions.matexpr import MatrixElement
from sympy.polys.rootoftools import RootOf
from sympy.utilities.iterables import numbered_symbols, sift, \
topological_sort, iterable
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]
def cse_release_variables(r, e):
"""
Return tuples giving ``(a, b)`` where ``a`` is a symbol and ``b`` is
either an expression or None. The value of None is used when a
symbol is no longer needed for subsequent expressions.
Use of such output can reduce the memory footprint of lambdified
expressions that contain large, repeated subexpressions.
Examples
========
>>> from sympy import cse
>>> from sympy.simplify.cse_main import cse_release_variables
>>> from sympy.abc import x, y
>>> eqs = [(x + y - 1)**2, x, x + y, (x + y)/(2*x + 1) + (x + y - 1)**2, (2*x + 1)**(x + y)]
>>> defs, rvs = cse_release_variables(*cse(eqs))
>>> for i in defs:
... print(i)
...
(x0, x + y)
(x1, (x0 - 1)**2)
(x2, 2*x + 1)
(_3, x0/x2 + x1)
(_4, x2**x0)
(x2, None)
(_0, x1)
(x1, None)
(_2, x0)
(x0, None)
(_1, x)
>>> print(rvs)
(_0, _1, _2, _3, _4)
"""
if not r:
return r, e
s, p = zip(*r)
esyms = symbols('_:%d' % len(e))
syms = list(esyms)
s = list(s)
in_use = set(s)
p = list(p)
# sort e so those with most sub-expressions appear first
e = [(e[i], syms[i]) for i in range(len(e))]
e, syms = zip(*sorted(e,
key=lambda x: -sum([p[s.index(i)].count_ops()
for i in x[0].free_symbols & in_use])))
syms = list(syms)
p += e
rv = []
i = len(p) - 1
while i >= 0:
_p = p.pop()
c = in_use & _p.free_symbols
if c: # sorting for canonical results
rv.extend([(s, None) for s in sorted(c, key=str)])
if i >= len(r):
rv.append((syms.pop(), _p))
else:
rv.append((s[i], _p))
in_use -= c
i -= 1
rv.reverse()
return rv, esyms
# ====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``.
"""
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))
"""
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 expr.could_extract_minus_sign():
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 exp.could_extract_minus_sign():
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.
"""
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 or
isinstance(expr, (MatrixSymbol, MatrixElement))):
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=(), list=True):
""" 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.
list : bool, (default True)
Returns expression in list or else with same type as input (when False).
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])
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])
The default return value for the reduced expression(s) is a list, even if there is only
one expression. The `list` flag preserves the type of the input in the output:
>>> cse(x)
([], [x])
>>> cse(x, list=False)
([], x)
"""
if not list:
return _cse_homogeneous(exprs,
symbols=symbols, optimizations=optimizations,
postprocess=postprocess, order=order, ignore=ignore)
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.flat()))
elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)):
temp.append(Tuple(*e.todok().items()))
else:
temp.append(e)
exprs = temp
del temp
if optimizations is None:
optimizations = []
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)
def _cse_homogeneous(exprs, **kwargs):
"""
Same as ``cse`` but the ``reduced_exprs`` are returned
with the same type as ``exprs`` or a sympified version of the same.
Parameters
==========
exprs : an Expr, iterable of Expr or dictionary with Expr values
the expressions in which repeated subexpressions will be identified
kwargs : additional arguments for the ``cse`` function
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.simplify.cse_main import cse
>>> from sympy import cos, Tuple, Matrix
>>> from sympy.abc import x
>>> output = lambda x: type(cse(x, list=False)[1])
>>> output(1)
<class 'sympy.core.numbers.One'>
>>> output('cos(x)')
<class 'str'>
>>> output(cos(x))
cos
>>> output(Tuple(1, x))
<class 'sympy.core.containers.Tuple'>
>>> output(Matrix([[1,0], [0,1]]))
<class 'sympy.matrices.dense.MutableDenseMatrix'>
>>> output([1, x])
<class 'list'>
>>> output((1, x))
<class 'tuple'>
>>> output({1, x})
<class 'set'>
"""
if isinstance(exprs, str):
replacements, reduced_exprs = _cse_homogeneous(
sympify(exprs), **kwargs)
return replacements, repr(reduced_exprs)
if isinstance(exprs, (list, tuple, set)):
replacements, reduced_exprs = cse(exprs, **kwargs)
return replacements, type(exprs)(reduced_exprs)
if isinstance(exprs, dict):
keys = list(exprs.keys()) # In order to guarantee the order of the elements.
replacements, values = cse([exprs[k] for k in keys], **kwargs)
reduced_exprs = dict(zip(keys, values))
return replacements, reduced_exprs
try:
replacements, (reduced_exprs,) = cse(exprs, **kwargs)
except TypeError: # For example 'mpf' objects
return [], exprs
else:
return replacements, reduced_exprs
|
ff0394b246e118732a8274b7eb258552edf16c5bc174d5c21fef514e77ab480c | from collections import defaultdict
from sympy.core.add import Add
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.singleton import S
from sympy.core.sorting import ordered
from sympy.core.symbol import Dummy
from sympy.core.sympify import sympify
from sympy.core.traversal import bottom_up
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.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[type(rv)](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
----------------------------------------------------
sin(a) 0 1/2 sqrt(2)/2 sqrt(3)/2 1
cos(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[type(a)].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[type(a.base)].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
was not 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 rv.func not 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 rv.func not 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 t.func not 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[type(b)].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))
"""
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[type(a)].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)*S.NegativeOne**((n-1)/2)*Add(*[binomial(n, k)*
S.NegativeOne**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)*S.NegativeOne**(n/2)*Add(*[binomial(n, k)*
S.NegativeOne**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)))
|
1c4a9e68a1cea04955eb79b411eda278385ae68e0a3c9b7ff4eac0ebb18d90c2 | from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.functions.elementary.complexes import (conjugate, im, re, sign)
from sympy.functions.elementary.exponential import (exp, log as ln)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (acos, cos, sin, atan2)
from sympy.simplify.trigsimp import trigsimp
from sympy.integrals.integrals import integrate
from sympy.matrices.dense import MutableDenseMatrix as Matrix
from sympy.core.sympify import sympify
from sympy.core.expr import Expr
from sympy.core.logic import fuzzy_not, fuzzy_or
from mpmath.libmp.libmpf import prec_to_dps
class Quaternion(Expr):
"""Provides basic quaternion operations.
Quaternion objects can be instantiated as Quaternion(a, b, c, d)
as in (a + b*i + c*j + d*k).
Examples
========
>>> from sympy import Quaternion
>>> q = Quaternion(1, 2, 3, 4)
>>> q
1 + 2*i + 3*j + 4*k
Quaternions over complex fields can be defined as :
>>> from sympy import Quaternion
>>> from sympy import symbols, I
>>> x = symbols('x')
>>> q1 = Quaternion(x, x**3, x, x**2, real_field = False)
>>> q2 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False)
>>> q1
x + x**3*i + x*j + x**2*k
>>> q2
(3 + 4*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k
References
==========
.. [1] http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/
.. [2] https://en.wikipedia.org/wiki/Quaternion
"""
_op_priority = 11.0
is_commutative = False
def __new__(cls, a=0, b=0, c=0, d=0, real_field=True):
a = sympify(a)
b = sympify(b)
c = sympify(c)
d = sympify(d)
if any(i.is_commutative is False for i in [a, b, c, d]):
raise ValueError("arguments have to be commutative")
else:
obj = Expr.__new__(cls, a, b, c, d)
obj._a = a
obj._b = b
obj._c = c
obj._d = d
obj._real_field = real_field
return obj
@property
def a(self):
return self._a
@property
def b(self):
return self._b
@property
def c(self):
return self._c
@property
def d(self):
return self._d
@property
def real_field(self):
return self._real_field
@classmethod
def from_axis_angle(cls, vector, angle):
"""Returns a rotation quaternion given the axis and the angle of rotation.
Parameters
==========
vector : tuple of three numbers
The vector representation of the given axis.
angle : number
The angle by which axis is rotated (in radians).
Returns
=======
Quaternion
The normalized rotation quaternion calculated from the given axis and the angle of rotation.
Examples
========
>>> from sympy import Quaternion
>>> from sympy import pi, sqrt
>>> q = Quaternion.from_axis_angle((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), 2*pi/3)
>>> q
1/2 + 1/2*i + 1/2*j + 1/2*k
"""
(x, y, z) = vector
norm = sqrt(x**2 + y**2 + z**2)
(x, y, z) = (x / norm, y / norm, z / norm)
s = sin(angle * S.Half)
a = cos(angle * S.Half)
b = x * s
c = y * s
d = z * s
# note that this quaternion is already normalized by construction:
# c^2 + (s*x)^2 + (s*y)^2 + (s*z)^2 = c^2 + s^2*(x^2 + y^2 + z^2) = c^2 + s^2 * 1 = c^2 + s^2 = 1
# so, what we return is a normalized quaternion
return cls(a, b, c, d)
@classmethod
def from_rotation_matrix(cls, M):
"""Returns the equivalent quaternion of a matrix. The quaternion will be normalized
only if the matrix is special orthogonal (orthogonal and det(M) = 1).
Parameters
==========
M : Matrix
Input matrix to be converted to equivalent quaternion. M must be special
orthogonal (orthogonal and det(M) = 1) for the quaternion to be normalized.
Returns
=======
Quaternion
The quaternion equivalent to given matrix.
Examples
========
>>> from sympy import Quaternion
>>> from sympy import Matrix, symbols, cos, sin, trigsimp
>>> x = symbols('x')
>>> M = Matrix([[cos(x), -sin(x), 0], [sin(x), cos(x), 0], [0, 0, 1]])
>>> q = trigsimp(Quaternion.from_rotation_matrix(M))
>>> q
sqrt(2)*sqrt(cos(x) + 1)/2 + 0*i + 0*j + sqrt(2 - 2*cos(x))*sign(sin(x))/2*k
"""
absQ = M.det()**Rational(1, 3)
a = sqrt(absQ + M[0, 0] + M[1, 1] + M[2, 2]) / 2
b = sqrt(absQ + M[0, 0] - M[1, 1] - M[2, 2]) / 2
c = sqrt(absQ - M[0, 0] + M[1, 1] - M[2, 2]) / 2
d = sqrt(absQ - M[0, 0] - M[1, 1] + M[2, 2]) / 2
b = b * sign(M[2, 1] - M[1, 2])
c = c * sign(M[0, 2] - M[2, 0])
d = d * sign(M[1, 0] - M[0, 1])
return Quaternion(a, b, c, d)
def __add__(self, other):
return self.add(other)
def __radd__(self, other):
return self.add(other)
def __sub__(self, other):
return self.add(other*-1)
def __mul__(self, other):
return self._generic_mul(self, other)
def __rmul__(self, other):
return self._generic_mul(other, self)
def __pow__(self, p):
return self.pow(p)
def __neg__(self):
return Quaternion(-self._a, -self._b, -self._c, -self.d)
def __truediv__(self, other):
return self * sympify(other)**-1
def __rtruediv__(self, other):
return sympify(other) * self**-1
def _eval_Integral(self, *args):
return self.integrate(*args)
def diff(self, *symbols, **kwargs):
kwargs.setdefault('evaluate', True)
return self.func(*[a.diff(*symbols, **kwargs) for a in self.args])
def add(self, other):
"""Adds quaternions.
Parameters
==========
other : Quaternion
The quaternion to add to current (self) quaternion.
Returns
=======
Quaternion
The resultant quaternion after adding self to other
Examples
========
>>> from sympy import Quaternion
>>> from sympy import symbols
>>> q1 = Quaternion(1, 2, 3, 4)
>>> q2 = Quaternion(5, 6, 7, 8)
>>> q1.add(q2)
6 + 8*i + 10*j + 12*k
>>> q1 + 5
6 + 2*i + 3*j + 4*k
>>> x = symbols('x', real = True)
>>> q1.add(x)
(x + 1) + 2*i + 3*j + 4*k
Quaternions over complex fields :
>>> from sympy import Quaternion
>>> from sympy import I
>>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False)
>>> q3.add(2 + 3*I)
(5 + 7*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k
"""
q1 = self
q2 = sympify(other)
# If q2 is a number or a SymPy expression instead of a quaternion
if not isinstance(q2, Quaternion):
if q1.real_field and q2.is_complex:
return Quaternion(re(q2) + q1.a, im(q2) + q1.b, q1.c, q1.d)
elif q2.is_commutative:
return Quaternion(q1.a + q2, q1.b, q1.c, q1.d)
else:
raise ValueError("Only commutative expressions can be added with a Quaternion.")
return Quaternion(q1.a + q2.a, q1.b + q2.b, q1.c + q2.c, q1.d
+ q2.d)
def mul(self, other):
"""Multiplies quaternions.
Parameters
==========
other : Quaternion or symbol
The quaternion to multiply to current (self) quaternion.
Returns
=======
Quaternion
The resultant quaternion after multiplying self with other
Examples
========
>>> from sympy import Quaternion
>>> from sympy import symbols
>>> q1 = Quaternion(1, 2, 3, 4)
>>> q2 = Quaternion(5, 6, 7, 8)
>>> q1.mul(q2)
(-60) + 12*i + 30*j + 24*k
>>> q1.mul(2)
2 + 4*i + 6*j + 8*k
>>> x = symbols('x', real = True)
>>> q1.mul(x)
x + 2*x*i + 3*x*j + 4*x*k
Quaternions over complex fields :
>>> from sympy import Quaternion
>>> from sympy import I
>>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False)
>>> q3.mul(2 + 3*I)
(2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k
"""
return self._generic_mul(self, other)
@staticmethod
def _generic_mul(q1, q2):
"""Generic multiplication.
Parameters
==========
q1 : Quaternion or symbol
q2 : Quaternion or symbol
It's important to note that if neither q1 nor q2 is a Quaternion,
this function simply returns q1 * q2.
Returns
=======
Quaternion
The resultant quaternion after multiplying q1 and q2
Examples
========
>>> from sympy import Quaternion
>>> from sympy import Symbol
>>> q1 = Quaternion(1, 2, 3, 4)
>>> q2 = Quaternion(5, 6, 7, 8)
>>> Quaternion._generic_mul(q1, q2)
(-60) + 12*i + 30*j + 24*k
>>> Quaternion._generic_mul(q1, 2)
2 + 4*i + 6*j + 8*k
>>> x = Symbol('x', real = True)
>>> Quaternion._generic_mul(q1, x)
x + 2*x*i + 3*x*j + 4*x*k
Quaternions over complex fields :
>>> from sympy import Quaternion
>>> from sympy import I
>>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False)
>>> Quaternion._generic_mul(q3, 2 + 3*I)
(2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k
"""
q1 = sympify(q1)
q2 = sympify(q2)
# None is a Quaternion:
if not isinstance(q1, Quaternion) and not isinstance(q2, Quaternion):
return q1 * q2
# If q1 is a number or a SymPy expression instead of a quaternion
if not isinstance(q1, Quaternion):
if q2.real_field and q1.is_complex:
return Quaternion(re(q1), im(q1), 0, 0) * q2
elif q1.is_commutative:
return Quaternion(q1 * q2.a, q1 * q2.b, q1 * q2.c, q1 * q2.d)
else:
raise ValueError("Only commutative expressions can be multiplied with a Quaternion.")
# If q2 is a number or a SymPy expression instead of a quaternion
if not isinstance(q2, Quaternion):
if q1.real_field and q2.is_complex:
return q1 * Quaternion(re(q2), im(q2), 0, 0)
elif q2.is_commutative:
return Quaternion(q2 * q1.a, q2 * q1.b, q2 * q1.c, q2 * q1.d)
else:
raise ValueError("Only commutative expressions can be multiplied with a Quaternion.")
return Quaternion(-q1.b*q2.b - q1.c*q2.c - q1.d*q2.d + q1.a*q2.a,
q1.b*q2.a + q1.c*q2.d - q1.d*q2.c + q1.a*q2.b,
-q1.b*q2.d + q1.c*q2.a + q1.d*q2.b + q1.a*q2.c,
q1.b*q2.c - q1.c*q2.b + q1.d*q2.a + q1.a * q2.d)
def _eval_conjugate(self):
"""Returns the conjugate of the quaternion."""
q = self
return Quaternion(q.a, -q.b, -q.c, -q.d)
def norm(self):
"""Returns the norm of the quaternion."""
q = self
# trigsimp is used to simplify sin(x)^2 + cos(x)^2 (these terms
# arise when from_axis_angle is used).
return sqrt(trigsimp(q.a**2 + q.b**2 + q.c**2 + q.d**2))
def normalize(self):
"""Returns the normalized form of the quaternion."""
q = self
return q * (1/q.norm())
def inverse(self):
"""Returns the inverse of the quaternion."""
q = self
if not q.norm():
raise ValueError("Cannot compute inverse for a quaternion with zero norm")
return conjugate(q) * (1/q.norm()**2)
def pow(self, p):
"""Finds the pth power of the quaternion.
Parameters
==========
p : int
Power to be applied on quaternion.
Returns
=======
Quaternion
Returns the p-th power of the current quaternion.
Returns the inverse if p = -1.
Examples
========
>>> from sympy import Quaternion
>>> q = Quaternion(1, 2, 3, 4)
>>> q.pow(4)
668 + (-224)*i + (-336)*j + (-448)*k
"""
p = sympify(p)
q = self
if p == -1:
return q.inverse()
res = 1
if not p.is_Integer:
return NotImplemented
if p < 0:
q, p = q.inverse(), -p
while p > 0:
if p % 2 == 1:
res = q * res
p = p//2
q = q * q
return res
def exp(self):
"""Returns the exponential of q (e^q).
Returns
=======
Quaternion
Exponential of q (e^q).
Examples
========
>>> from sympy import Quaternion
>>> q = Quaternion(1, 2, 3, 4)
>>> q.exp()
E*cos(sqrt(29))
+ 2*sqrt(29)*E*sin(sqrt(29))/29*i
+ 3*sqrt(29)*E*sin(sqrt(29))/29*j
+ 4*sqrt(29)*E*sin(sqrt(29))/29*k
"""
# exp(q) = e^a(cos||v|| + v/||v||*sin||v||)
q = self
vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2)
a = exp(q.a) * cos(vector_norm)
b = exp(q.a) * sin(vector_norm) * q.b / vector_norm
c = exp(q.a) * sin(vector_norm) * q.c / vector_norm
d = exp(q.a) * sin(vector_norm) * q.d / vector_norm
return Quaternion(a, b, c, d)
def _ln(self):
"""Returns the natural logarithm of the quaternion (_ln(q)).
Examples
========
>>> from sympy import Quaternion
>>> q = Quaternion(1, 2, 3, 4)
>>> q._ln()
log(sqrt(30))
+ 2*sqrt(29)*acos(sqrt(30)/30)/29*i
+ 3*sqrt(29)*acos(sqrt(30)/30)/29*j
+ 4*sqrt(29)*acos(sqrt(30)/30)/29*k
"""
# _ln(q) = _ln||q|| + v/||v||*arccos(a/||q||)
q = self
vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2)
q_norm = q.norm()
a = ln(q_norm)
b = q.b * acos(q.a / q_norm) / vector_norm
c = q.c * acos(q.a / q_norm) / vector_norm
d = q.d * acos(q.a / q_norm) / vector_norm
return Quaternion(a, b, c, d)
def _eval_evalf(self, prec):
"""Returns the floating point approximations (decimal numbers) of the quaternion.
Returns
=======
Quaternion
Floating point approximations of quaternion(self)
Examples
========
>>> from sympy import Quaternion
>>> from sympy import sqrt
>>> q = Quaternion(1/sqrt(1), 1/sqrt(2), 1/sqrt(3), 1/sqrt(4))
>>> q.evalf()
1.00000000000000
+ 0.707106781186547*i
+ 0.577350269189626*j
+ 0.500000000000000*k
"""
nprec = prec_to_dps(prec)
return Quaternion(*[arg.evalf(n=nprec) for arg in self.args])
def pow_cos_sin(self, p):
"""Computes the pth power in the cos-sin form.
Parameters
==========
p : int
Power to be applied on quaternion.
Returns
=======
Quaternion
The p-th power in the cos-sin form.
Examples
========
>>> from sympy import Quaternion
>>> q = Quaternion(1, 2, 3, 4)
>>> q.pow_cos_sin(4)
900*cos(4*acos(sqrt(30)/30))
+ 1800*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*i
+ 2700*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*j
+ 3600*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*k
"""
# q = ||q||*(cos(a) + u*sin(a))
# q^p = ||q||^p * (cos(p*a) + u*sin(p*a))
q = self
(v, angle) = q.to_axis_angle()
q2 = Quaternion.from_axis_angle(v, p * angle)
return q2 * (q.norm()**p)
def integrate(self, *args):
"""Computes integration of quaternion.
Returns
=======
Quaternion
Integration of the quaternion(self) with the given variable.
Examples
========
Indefinite Integral of quaternion :
>>> from sympy import Quaternion
>>> from sympy.abc import x
>>> q = Quaternion(1, 2, 3, 4)
>>> q.integrate(x)
x + 2*x*i + 3*x*j + 4*x*k
Definite integral of quaternion :
>>> from sympy import Quaternion
>>> from sympy.abc import x
>>> q = Quaternion(1, 2, 3, 4)
>>> q.integrate((x, 1, 5))
4 + 8*i + 12*j + 16*k
"""
# TODO: is this expression correct?
return Quaternion(integrate(self.a, *args), integrate(self.b, *args),
integrate(self.c, *args), integrate(self.d, *args))
@staticmethod
def rotate_point(pin, r):
"""Returns the coordinates of the point pin(a 3 tuple) after rotation.
Parameters
==========
pin : tuple
A 3-element tuple of coordinates of a point which needs to be
rotated.
r : Quaternion or tuple
Axis and angle of rotation.
It's important to note that when r is a tuple, it must be of the form
(axis, angle)
Returns
=======
tuple
The coordinates of the point after rotation.
Examples
========
>>> from sympy import Quaternion
>>> from sympy import symbols, trigsimp, cos, sin
>>> x = symbols('x')
>>> q = Quaternion(cos(x/2), 0, 0, sin(x/2))
>>> trigsimp(Quaternion.rotate_point((1, 1, 1), q))
(sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1)
>>> (axis, angle) = q.to_axis_angle()
>>> trigsimp(Quaternion.rotate_point((1, 1, 1), (axis, angle)))
(sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1)
"""
if isinstance(r, tuple):
# if r is of the form (vector, angle)
q = Quaternion.from_axis_angle(r[0], r[1])
else:
# if r is a quaternion
q = r.normalize()
pout = q * Quaternion(0, pin[0], pin[1], pin[2]) * conjugate(q)
return (pout.b, pout.c, pout.d)
def to_axis_angle(self):
"""Returns the axis and angle of rotation of a quaternion
Returns
=======
tuple
Tuple of (axis, angle)
Examples
========
>>> from sympy import Quaternion
>>> q = Quaternion(1, 1, 1, 1)
>>> (axis, angle) = q.to_axis_angle()
>>> axis
(sqrt(3)/3, sqrt(3)/3, sqrt(3)/3)
>>> angle
2*pi/3
"""
q = self
if q.a.is_negative:
q = q * -1
q = q.normalize()
angle = trigsimp(2 * acos(q.a))
# Since quaternion is normalised, q.a is less than 1.
s = sqrt(1 - q.a*q.a)
x = trigsimp(q.b / s)
y = trigsimp(q.c / s)
z = trigsimp(q.d / s)
v = (x, y, z)
t = (v, angle)
return t
def to_rotation_matrix(self, v=None):
"""Returns the equivalent rotation transformation matrix of the quaternion
which represents rotation about the origin if v is not passed.
Parameters
==========
v : tuple or None
Default value: None
Returns
=======
tuple
Returns the equivalent rotation transformation matrix of the quaternion
which represents rotation about the origin if v is not passed.
Examples
========
>>> from sympy import Quaternion
>>> from sympy import symbols, trigsimp, cos, sin
>>> x = symbols('x')
>>> q = Quaternion(cos(x/2), 0, 0, sin(x/2))
>>> trigsimp(q.to_rotation_matrix())
Matrix([
[cos(x), -sin(x), 0],
[sin(x), cos(x), 0],
[ 0, 0, 1]])
Generates a 4x4 transformation matrix (used for rotation about a point
other than the origin) if the point(v) is passed as an argument.
Examples
========
>>> from sympy import Quaternion
>>> from sympy import symbols, trigsimp, cos, sin
>>> x = symbols('x')
>>> q = Quaternion(cos(x/2), 0, 0, sin(x/2))
>>> trigsimp(q.to_rotation_matrix((1, 1, 1)))
Matrix([
[cos(x), -sin(x), 0, sin(x) - cos(x) + 1],
[sin(x), cos(x), 0, -sin(x) - cos(x) + 1],
[ 0, 0, 1, 0],
[ 0, 0, 0, 1]])
"""
q = self
s = q.norm()**-2
m00 = 1 - 2*s*(q.c**2 + q.d**2)
m01 = 2*s*(q.b*q.c - q.d*q.a)
m02 = 2*s*(q.b*q.d + q.c*q.a)
m10 = 2*s*(q.b*q.c + q.d*q.a)
m11 = 1 - 2*s*(q.b**2 + q.d**2)
m12 = 2*s*(q.c*q.d - q.b*q.a)
m20 = 2*s*(q.b*q.d - q.c*q.a)
m21 = 2*s*(q.c*q.d + q.b*q.a)
m22 = 1 - 2*s*(q.b**2 + q.c**2)
if not v:
return Matrix([[m00, m01, m02], [m10, m11, m12], [m20, m21, m22]])
else:
(x, y, z) = v
m03 = x - x*m00 - y*m01 - z*m02
m13 = y - x*m10 - y*m11 - z*m12
m23 = z - x*m20 - y*m21 - z*m22
m30 = m31 = m32 = 0
m33 = 1
return Matrix([[m00, m01, m02, m03], [m10, m11, m12, m13],
[m20, m21, m22, m23], [m30, m31, m32, m33]])
def scalar_part(self):
r"""Returns scalar part($\mathbf{S}(q)$) of the quaternion q.
Explanation
===========
Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{S}(q) = a$.
Examples
========
>>> from sympy.algebras.quaternion import Quaternion
>>> q = Quaternion(4, 8, 13, 12)
>>> q.scalar_part()
4
"""
return self.a
def vector_part(self):
r"""
Returns vector part($\mathbf{V}(q)$) of the quaternion q.
Explanation
===========
Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{V}(q) = bi + cj + dk$.
Examples
========
>>> from sympy.algebras.quaternion import Quaternion
>>> q = Quaternion(1, 1, 1, 1)
>>> q.vector_part()
0 + 1*i + 1*j + 1*k
>>> q = Quaternion(4, 8, 13, 12)
>>> q.vector_part()
0 + 8*i + 13*j + 12*k
"""
return Quaternion(0, self.b, self.c, self.d)
def axis(self):
r"""
Returns the axis($\mathbf{Ax}(q)$) of the quaternion.
Explanation
===========
Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{Ax}(q)$ i.e., the versor of the vector part of that quaternion
equal to $\mathbf{U}[\mathbf{V}(q)]$.
The axis is always an imaginary unit with square equal to $-1 + 0i + 0j + 0k$.
Examples
========
>>> from sympy.algebras.quaternion import Quaternion
>>> q = Quaternion(1, 1, 1, 1)
>>> q.axis()
0 + sqrt(3)/3*i + sqrt(3)/3*j + sqrt(3)/3*k
See Also
========
vector_part
"""
axis = self.vector_part().normalize()
return Quaternion(0, axis.b, axis.c, axis.d)
def is_pure(self):
"""
Returns true if the quaternion is pure, false if the quaternion is not pure
or returns none if it is unknown.
Explanation
===========
A pure quaternion (also a vector quaternion) is a quaternion with scalar
part equal to 0.
Examples
========
>>> from sympy.algebras.quaternion import Quaternion
>>> q = Quaternion(0, 8, 13, 12)
>>> q.is_pure()
True
See Also
========
scalar_part
"""
return self.a.is_zero
def is_zero_quaternion(self):
"""
Returns true if the quaternion is a zero quaternion or false if it is not a zero quaternion
and None if the value is unknown.
Explanation
===========
A zero quaternion is a quaternion with both scalar part and
vector part equal to 0.
Examples
========
>>> from sympy.algebras.quaternion import Quaternion
>>> q = Quaternion(1, 0, 0, 0)
>>> q.is_zero_quaternion()
False
>>> q = Quaternion(0, 0, 0, 0)
>>> q.is_zero_quaternion()
True
See Also
========
scalar_part
vector_part
"""
return self.norm().is_zero
def angle(self):
r"""
Returns the angle of the quaternion measured in the real-axis plane.
Explanation
===========
Given a quaternion $q = a + bi + cj + dk$ where a, b, c and d
are real numbers, returns the angle of the quaternion given by
.. math::
angle := atan2(\sqrt{b^2 + c^2 + d^2}, {a})
Examples
========
>>> from sympy.algebras.quaternion import Quaternion
>>> q = Quaternion(1, 4, 4, 4)
>>> q.angle()
atan(4*sqrt(3))
"""
return atan2(self.vector_part().norm(), self.scalar_part())
def arc_coplanar(self, other):
"""
Returns True if the transformation arcs represented by the input quaternions happen in the same plane.
Explanation
===========
Two quaternions are said to be coplanar (in this arc sense) when their axes are parallel.
The plane of a quaternion is the one normal to its axis.
Parameters
==========
other : a Quaternion
Returns
=======
True : if the planes of the two quaternions are the same, apart from its orientation/sign.
False : if the planes of the two quaternions are not the same, apart from its orientation/sign.
None : if plane of either of the quaternion is unknown.
Examples
========
>>> from sympy.algebras.quaternion import Quaternion
>>> q1 = Quaternion(1, 4, 4, 4)
>>> q2 = Quaternion(3, 8, 8, 8)
>>> Quaternion.arc_coplanar(q1, q2)
True
>>> q1 = Quaternion(2, 8, 13, 12)
>>> Quaternion.arc_coplanar(q1, q2)
False
See Also
========
vector_coplanar
is_pure
"""
if (self.is_zero_quaternion()) or (other.is_zero_quaternion()):
raise ValueError('Neither of the given quaternions can be 0')
return fuzzy_or([(self.axis() - other.axis()).is_zero_quaternion(), (self.axis() + other.axis()).is_zero_quaternion()])
@classmethod
def vector_coplanar(cls, q1, q2, q3):
r"""
Returns True if the axis of the pure quaternions seen as 3D vectors
q1, q2, and q3 are coplanar.
Explanation
===========
Three pure quaternions are vector coplanar if the quaternions seen as 3D vectors are coplanar.
Parameters
==========
q1 : a pure Quaternion.
q2 : a pure Quaternion.
q3 : a pure Quaternion.
Returns
=======
True : if the axis of the pure quaternions seen as 3D vectors
q1, q2, and q3 are coplanar.
False : if the axis of the pure quaternions seen as 3D vectors
q1, q2, and q3 are not coplanar.
None : if the axis of the pure quaternions seen as 3D vectors
q1, q2, and q3 are coplanar is unknown.
Examples
========
>>> from sympy.algebras.quaternion import Quaternion
>>> q1 = Quaternion(0, 4, 4, 4)
>>> q2 = Quaternion(0, 8, 8, 8)
>>> q3 = Quaternion(0, 24, 24, 24)
>>> Quaternion.vector_coplanar(q1, q2, q3)
True
>>> q1 = Quaternion(0, 8, 16, 8)
>>> q2 = Quaternion(0, 8, 3, 12)
>>> Quaternion.vector_coplanar(q1, q2, q3)
False
See Also
========
axis
is_pure
"""
if fuzzy_not(q1.is_pure()) or fuzzy_not(q2.is_pure()) or fuzzy_not(q3.is_pure()):
raise ValueError('The given quaternions must be pure')
M = Matrix([[q1.b, q1.c, q1.d], [q2.b, q2.c, q2.d], [q3.b, q3.c, q3.d]]).det()
return M.is_zero
def parallel(self, other):
"""
Returns True if the two pure quaternions seen as 3D vectors are parallel.
Explanation
===========
Two pure quaternions are called parallel when their vector product is commutative which
implies that the quaternions seen as 3D vectors have same direction.
Parameters
==========
other : a Quaternion
Returns
=======
True : if the two pure quaternions seen as 3D vectors are parallel.
False : if the two pure quaternions seen as 3D vectors are not parallel.
None : if the two pure quaternions seen as 3D vectors are parallel is unknown.
Examples
========
>>> from sympy.algebras.quaternion import Quaternion
>>> q = Quaternion(0, 4, 4, 4)
>>> q1 = Quaternion(0, 8, 8, 8)
>>> q.parallel(q1)
True
>>> q1 = Quaternion(0, 8, 13, 12)
>>> q.parallel(q1)
False
"""
if fuzzy_not(self.is_pure()) or fuzzy_not(other.is_pure()):
raise ValueError('The provided quaternions must be pure')
return (self*other - other*self).is_zero_quaternion()
def orthogonal(self, other):
"""
Returns the orthogonality of two quaternions.
Explanation
===========
Two pure quaternions are called orthogonal when their product is anti-commutative.
Parameters
==========
other : a Quaternion
Returns
=======
True : if the two pure quaternions seen as 3D vectors are orthogonal.
False : if the two pure quaternions seen as 3D vectors are not orthogonal.
None : if the two pure quaternions seen as 3D vectors are orthogonal is unknown.
Examples
========
>>> from sympy.algebras.quaternion import Quaternion
>>> q = Quaternion(0, 4, 4, 4)
>>> q1 = Quaternion(0, 8, 8, 8)
>>> q.orthogonal(q1)
False
>>> q1 = Quaternion(0, 2, 2, 0)
>>> q = Quaternion(0, 2, -2, 0)
>>> q.orthogonal(q1)
True
"""
if fuzzy_not(self.is_pure()) or fuzzy_not(other.is_pure()):
raise ValueError('The given quaternions must be pure')
return (self*other + other*self).is_zero_quaternion()
def index_vector(self):
r"""
Returns the index vector of the quaternion.
Explanation
===========
Index vector is given by $\mathbf{T}(q)$ multiplied by $\mathbf{Ax}(q)$ where $\mathbf{Ax}(q)$ is the axis of the quaternion q,
and mod(q) is the $\mathbf{T}(q)$ (magnitude) of the quaternion.
Returns
=======
Quaternion: representing index vector of the provided quaternion.
Examples
========
>>> from sympy.algebras.quaternion import Quaternion
>>> q = Quaternion(2, 4, 2, 4)
>>> q.index_vector()
0 + 4*sqrt(10)/3*i + 2*sqrt(10)/3*j + 4*sqrt(10)/3*k
See Also
========
axis
norm
"""
return self.norm() * self.axis()
def mensor(self):
"""
Returns the natural logarithm of the norm(magnitude) of the quaternion.
Examples
========
>>> from sympy.algebras.quaternion import Quaternion
>>> q = Quaternion(2, 4, 2, 4)
>>> q.mensor()
log(2*sqrt(10))
>>> q.norm()
2*sqrt(10)
See Also
========
norm
"""
return ln(self.norm())
|
0533e6cb3cce6ccd3228d8cb507c13b678afcc85e08aac4f081e2cc91972c515 | from typing import Any, Set as tSet
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.solvers import solve
from sympy.utilities.exceptions import (sympy_deprecation_warning,
SymPyDeprecationWarning,
ignore_warnings)
# 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 is deprecated. The Manifold object is now
immutable. Instead use a separate list to keep track of the
patches.
""", [])
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_systms is deprecated. The Patch class is now
immutable. Instead use a separate list to keep track of coordinate
systems.
""", [])
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:
sympy_deprecation_warning(
f"""
The 'names' argument to CoordSystem is deprecated. Use 'symbols' instead. That
is, replace
CoordSystem(..., names={names})
with
CoordSystem(..., symbols=[{', '.join(["Symbol(" + repr(n) + ", real=True)" for n in names])}])
""",
deprecated_since_version="1.7",
active_deprecations_target="deprecated-diffgeom-mutable",
)
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):
sympy_deprecation_warning(
f"""
Passing a string as the coordinate symbol name to CoordSystem is deprecated.
Pass a Symbol with the appropriate name and assumptions instead.
That is, replace {s} with Symbol({s!r}, real=True).
""",
deprecated_since_version="1.7",
active_deprecations_target="deprecated-diffgeom-mutable",
)
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(
"""
CoordSystem.transforms is deprecated. The CoordSystem class is now
immutable. Use the 'relations' keyword argument to the
CoordSystems() constructor to specify relations.
""", {})
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):
sympy_deprecation_warning(
"""
The CoordSystem.connect_to() method is deprecated. Instead,
generate a new instance of CoordSystem with the 'relations'
keyword argument (CoordSystem classes are now immutable).
""",
deprecated_since_version="1.7",
active_deprecations_target="deprecated-diffgeom-mutable",
)
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``."""
sympy_deprecation_warning(
"""
The CoordSystem.coord_tuple_transform_to() method is deprecated.
Use the CoordSystem.transform() method instead.
""",
deprecated_since_version="1.7",
active_deprecations_target="deprecated-diffgeom-mutable",
)
coords = Matrix(coords)
if self != to_sys:
with ignore_warnings(SymPyDeprecationWarning):
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, Lambda, Matrix, 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'): Lambda((x, y), Matrix([sqrt(x**2 + y**2), atan2(y, x)])),
... ('Pol', 'Car2D'): Lambda((r, theta), Matrix([r*cos(theta), r*sin(theta)]))
... }
>>> Car2D = CoordSystem('Car2D', p, [x, y], relation_dict)
>>> Pol = CoordSystem('Pol', p, [r, theta], relation_dict)
>>> x, y = Car2D.symbols
``CoordinateSymbol`` contains its coordinate symbol and index.
>>> x.name
'x'
>>> x.coord_sys == Car2D
True
>>> x.index
0
>>> x.is_real
True
You can transform ``CoordinateSymbol`` into other coordinate system using
``rewrite()`` method.
>>> x.rewrite(Pol)
r*cos(theta)
>>> sqrt(x**2 + y**2).rewrite(Pol).simplify()
r
"""
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()))
def _eval_rewrite(self, rule, args, **hints):
if isinstance(rule, CoordSystem):
return rule.transform(self.coord_sys)[self.index]
return super()._eval_rewrite(rule, args, **hints)
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: tSet[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 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.')
christoffel = ImmutableDenseNDimArray(christoffel)
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(d) 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, message, data):
super().__init__(data)
self.message = message
def warn(self):
sympy_deprecation_warning(
self.message,
deprecated_since_version="1.7",
active_deprecations_target="deprecated-diffgeom-mutable",
stacklevel=4
)
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
# Import at end to avoid cyclic imports
from sympy.simplify.simplify import simplify
|
3a6f8405f61db8517deed817385ebcaebf3361b9e07a6f640519bd48988a2d23 | """
AST nodes specific to C++.
"""
from sympy.codegen.ast import Attribute, String, Token, Type, none
class using(Token):
""" Represents a 'using' statement in C++ """
__slots__ = _fields = ('type', 'alias')
defaults = {'alias': none}
_construct_type = Type
_construct_alias = String
constexpr = Attribute('constexpr')
|
4d8e1e71fb6a9f29b9be26089e76f9f7318f3c55dd792190c22fbec53cfa3efa | """This module provides containers for python objects that are valid
printing targets but are not a subclass of SymPy's Printable.
"""
from sympy.core.containers import Tuple
class List(Tuple):
"""Represents a (frozen) (Python) list (for code printing purposes)."""
def __eq__(self, other):
if isinstance(other, list):
return self == List(*other)
else:
return self.args == other
def __hash__(self):
return super().__hash__()
|
6450711ec44151c435e0425151165787d1234ec492246c265ae6df9a9134fa9e | """
AST nodes specific to the C family of languages
"""
from sympy.codegen.ast import (
Attribute, Declaration, Node, String, Token, Type, none,
FunctionCall, CodeBlock
)
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.sympify import sympify
void = Type('void')
restrict = Attribute('restrict') # guarantees no pointer aliasing
volatile = Attribute('volatile')
static = Attribute('static')
def alignof(arg):
""" Generate of FunctionCall instance for calling 'alignof' """
return FunctionCall('alignof', [String(arg) if isinstance(arg, str) else arg])
def sizeof(arg):
""" Generate of FunctionCall instance for calling 'sizeof'
Examples
========
>>> from sympy.codegen.ast import real
>>> from sympy.codegen.cnodes import sizeof
>>> from sympy import ccode
>>> ccode(sizeof(real))
'sizeof(double)'
"""
return FunctionCall('sizeof', [String(arg) if isinstance(arg, str) else arg])
class CommaOperator(Basic):
""" Represents the comma operator in C """
def __new__(cls, *args):
return Basic.__new__(cls, *[sympify(arg) for arg in args])
class Label(Node):
""" Label for use with e.g. goto statement.
Examples
========
>>> from sympy import ccode, Symbol
>>> from sympy.codegen.cnodes import Label, PreIncrement
>>> print(ccode(Label('foo')))
foo:
>>> print(ccode(Label('bar', [PreIncrement(Symbol('a'))])))
bar:
++(a);
"""
__slots__ = _fields = ('name', 'body')
defaults = {'body': none}
_construct_name = String
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
class goto(Token):
""" Represents goto in C """
__slots__ = _fields = ('label',)
_construct_label = Label
class PreDecrement(Basic):
""" Represents the pre-decrement operator
Examples
========
>>> from sympy.abc import x
>>> from sympy.codegen.cnodes import PreDecrement
>>> from sympy import ccode
>>> ccode(PreDecrement(x))
'--(x)'
"""
nargs = 1
class PostDecrement(Basic):
""" Represents the post-decrement operator """
nargs = 1
class PreIncrement(Basic):
""" Represents the pre-increment operator """
nargs = 1
class PostIncrement(Basic):
""" Represents the post-increment operator """
nargs = 1
class struct(Node):
""" Represents a struct in C """
__slots__ = _fields = ('name', 'declarations')
defaults = {'name': none}
_construct_name = String
@classmethod
def _construct_declarations(cls, args):
return Tuple(*[Declaration(arg) for arg in args])
class union(struct):
""" Represents a union in C """
__slots__ = ()
|
c74a8255e52c1e5a1c4c582bab1ce253d66d7eb5b18a9157a3d93409b6290a36 | """
AST nodes specific to Fortran.
The functions defined in this module allows the user to express functions such as ``dsign``
as a SymPy function for symbolic manipulation.
"""
from sympy.codegen.ast import (
Attribute, CodeBlock, FunctionCall, Node, none, String,
Token, _mk_Tuple, Variable
)
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import Function
from sympy.core.numbers import Float, Integer
from sympy.core.symbol import Str
from sympy.core.sympify import sympify
from sympy.logic import true, false
from sympy.utilities.iterables import iterable
pure = Attribute('pure')
elemental = Attribute('elemental') # (all elemental procedures are also pure)
intent_in = Attribute('intent_in')
intent_out = Attribute('intent_out')
intent_inout = Attribute('intent_inout')
allocatable = Attribute('allocatable')
class Program(Token):
""" Represents a 'program' block in Fortran.
Examples
========
>>> from sympy.codegen.ast import Print
>>> from sympy.codegen.fnodes import Program
>>> prog = Program('myprogram', [Print([42])])
>>> from sympy import fcode
>>> print(fcode(prog, source_format='free'))
program myprogram
print *, 42
end program
"""
__slots__ = _fields = ('name', 'body')
_construct_name = String
_construct_body = staticmethod(lambda body: CodeBlock(*body))
class use_rename(Token):
""" Represents a renaming in a use statement in Fortran.
Examples
========
>>> from sympy.codegen.fnodes import use_rename, use
>>> from sympy import fcode
>>> ren = use_rename("thingy", "convolution2d")
>>> print(fcode(ren, source_format='free'))
thingy => convolution2d
>>> full = use('signallib', only=['snr', ren])
>>> print(fcode(full, source_format='free'))
use signallib, only: snr, thingy => convolution2d
"""
__slots__ = _fields = ('local', 'original')
_construct_local = String
_construct_original = String
def _name(arg):
if hasattr(arg, 'name'):
return arg.name
else:
return String(arg)
class use(Token):
""" Represents a use statement in Fortran.
Examples
========
>>> from sympy.codegen.fnodes import use
>>> from sympy import fcode
>>> fcode(use('signallib'), source_format='free')
'use signallib'
>>> fcode(use('signallib', [('metric', 'snr')]), source_format='free')
'use signallib, metric => snr'
>>> fcode(use('signallib', only=['snr', 'convolution2d']), source_format='free')
'use signallib, only: snr, convolution2d'
"""
__slots__ = _fields = ('namespace', 'rename', 'only')
defaults = {'rename': none, 'only': none}
_construct_namespace = staticmethod(_name)
_construct_rename = staticmethod(lambda args: Tuple(*[arg if isinstance(arg, use_rename) else use_rename(*arg) for arg in args]))
_construct_only = staticmethod(lambda args: Tuple(*[arg if isinstance(arg, use_rename) else _name(arg) for arg in args]))
class Module(Token):
""" Represents a module in Fortran.
Examples
========
>>> from sympy.codegen.fnodes import Module
>>> from sympy import fcode
>>> print(fcode(Module('signallib', ['implicit none'], []), source_format='free'))
module signallib
implicit none
<BLANKLINE>
contains
<BLANKLINE>
<BLANKLINE>
end module
"""
__slots__ = _fields = ('name', 'declarations', 'definitions')
defaults = {'declarations': Tuple()}
_construct_name = String
@classmethod
def _construct_declarations(cls, args):
args = [Str(arg) if isinstance(arg, str) else arg for arg in args]
return CodeBlock(*args)
_construct_definitions = staticmethod(lambda arg: CodeBlock(*arg))
class Subroutine(Node):
""" Represents a subroutine in Fortran.
Examples
========
>>> from sympy import fcode, symbols
>>> from sympy.codegen.ast import Print
>>> from sympy.codegen.fnodes import Subroutine
>>> x, y = symbols('x y', real=True)
>>> sub = Subroutine('mysub', [x, y], [Print([x**2 + y**2, x*y])])
>>> print(fcode(sub, source_format='free', standard=2003))
subroutine mysub(x, y)
real*8 :: x
real*8 :: y
print *, x**2 + y**2, x*y
end subroutine
"""
__slots__ = ('name', 'parameters', 'body')
_fields = __slots__ + Node._fields
_construct_name = String
_construct_parameters = staticmethod(lambda params: Tuple(*map(Variable.deduced, params)))
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
class SubroutineCall(Token):
""" Represents a call to a subroutine in Fortran.
Examples
========
>>> from sympy.codegen.fnodes import SubroutineCall
>>> from sympy import fcode
>>> fcode(SubroutineCall('mysub', 'x y'.split()))
' call mysub(x, y)'
"""
__slots__ = _fields = ('name', 'subroutine_args')
_construct_name = staticmethod(_name)
_construct_subroutine_args = staticmethod(_mk_Tuple)
class Do(Token):
""" Represents a Do loop in in Fortran.
Examples
========
>>> from sympy import fcode, symbols
>>> from sympy.codegen.ast import aug_assign, Print
>>> from sympy.codegen.fnodes import Do
>>> i, n = symbols('i n', integer=True)
>>> r = symbols('r', real=True)
>>> body = [aug_assign(r, '+', 1/i), Print([i, r])]
>>> do1 = Do(body, i, 1, n)
>>> print(fcode(do1, source_format='free'))
do i = 1, n
r = r + 1d0/i
print *, i, r
end do
>>> do2 = Do(body, i, 1, n, 2)
>>> print(fcode(do2, source_format='free'))
do i = 1, n, 2
r = r + 1d0/i
print *, i, r
end do
"""
__slots__ = _fields = ('body', 'counter', 'first', 'last', 'step', 'concurrent')
defaults = {'step': Integer(1), 'concurrent': false}
_construct_body = staticmethod(lambda body: CodeBlock(*body))
_construct_counter = staticmethod(sympify)
_construct_first = staticmethod(sympify)
_construct_last = staticmethod(sympify)
_construct_step = staticmethod(sympify)
_construct_concurrent = staticmethod(lambda arg: true if arg else false)
class ArrayConstructor(Token):
""" Represents an array constructor.
Examples
========
>>> from sympy import fcode
>>> from sympy.codegen.fnodes import ArrayConstructor
>>> ac = ArrayConstructor([1, 2, 3])
>>> fcode(ac, standard=95, source_format='free')
'(/1, 2, 3/)'
>>> fcode(ac, standard=2003, source_format='free')
'[1, 2, 3]'
"""
__slots__ = _fields = ('elements',)
_construct_elements = staticmethod(_mk_Tuple)
class ImpliedDoLoop(Token):
""" Represents an implied do loop in Fortran.
Examples
========
>>> from sympy import Symbol, fcode
>>> from sympy.codegen.fnodes import ImpliedDoLoop, ArrayConstructor
>>> i = Symbol('i', integer=True)
>>> idl = ImpliedDoLoop(i**3, i, -3, 3, 2) # -27, -1, 1, 27
>>> ac = ArrayConstructor([-28, idl, 28]) # -28, -27, -1, 1, 27, 28
>>> fcode(ac, standard=2003, source_format='free')
'[-28, (i**3, i = -3, 3, 2), 28]'
"""
__slots__ = _fields = ('expr', 'counter', 'first', 'last', 'step')
defaults = {'step': Integer(1)}
_construct_expr = staticmethod(sympify)
_construct_counter = staticmethod(sympify)
_construct_first = staticmethod(sympify)
_construct_last = staticmethod(sympify)
_construct_step = staticmethod(sympify)
class Extent(Basic):
""" Represents a dimension extent.
Examples
========
>>> from sympy.codegen.fnodes import Extent
>>> e = Extent(-3, 3) # -3, -2, -1, 0, 1, 2, 3
>>> from sympy import fcode
>>> fcode(e, source_format='free')
'-3:3'
>>> from sympy.codegen.ast import Variable, real
>>> from sympy.codegen.fnodes import dimension, intent_out
>>> dim = dimension(e, e)
>>> arr = Variable('x', real, attrs=[dim, intent_out])
>>> fcode(arr.as_Declaration(), source_format='free', standard=2003)
'real*8, dimension(-3:3, -3:3), intent(out) :: x'
"""
def __new__(cls, *args):
if len(args) == 2:
low, high = args
return Basic.__new__(cls, sympify(low), sympify(high))
elif len(args) == 0 or (len(args) == 1 and args[0] in (':', None)):
return Basic.__new__(cls) # assumed shape
else:
raise ValueError("Expected 0 or 2 args (or one argument == None or ':')")
def _sympystr(self, printer):
if len(self.args) == 0:
return ':'
return ":".join(str(arg) for arg in self.args)
assumed_extent = Extent() # or Extent(':'), Extent(None)
def dimension(*args):
""" Creates a 'dimension' Attribute with (up to 7) extents.
Examples
========
>>> from sympy import fcode
>>> from sympy.codegen.fnodes import dimension, intent_in
>>> dim = dimension('2', ':') # 2 rows, runtime determined number of columns
>>> from sympy.codegen.ast import Variable, integer
>>> arr = Variable('a', integer, attrs=[dim, intent_in])
>>> fcode(arr.as_Declaration(), source_format='free', standard=2003)
'integer*4, dimension(2, :), intent(in) :: a'
"""
if len(args) > 7:
raise ValueError("Fortran only supports up to 7 dimensional arrays")
parameters = []
for arg in args:
if isinstance(arg, Extent):
parameters.append(arg)
elif isinstance(arg, str):
if arg == ':':
parameters.append(Extent())
else:
parameters.append(String(arg))
elif iterable(arg):
parameters.append(Extent(*arg))
else:
parameters.append(sympify(arg))
if len(args) == 0:
raise ValueError("Need at least one dimension")
return Attribute('dimension', parameters)
assumed_size = dimension('*')
def array(symbol, dim, intent=None, *, attrs=(), value=None, type=None):
""" Convenience function for creating a Variable instance for a Fortran array.
Parameters
==========
symbol : symbol
dim : Attribute or iterable
If dim is an ``Attribute`` it need to have the name 'dimension'. If it is
not an ``Attribute``, then it is passsed to :func:`dimension` as ``*dim``
intent : str
One of: 'in', 'out', 'inout' or None
\\*\\*kwargs:
Keyword arguments for ``Variable`` ('type' & 'value')
Examples
========
>>> from sympy import fcode
>>> from sympy.codegen.ast import integer, real
>>> from sympy.codegen.fnodes import array
>>> arr = array('a', '*', 'in', type=integer)
>>> print(fcode(arr.as_Declaration(), source_format='free', standard=2003))
integer*4, dimension(*), intent(in) :: a
>>> x = array('x', [3, ':', ':'], intent='out', type=real)
>>> print(fcode(x.as_Declaration(value=1), source_format='free', standard=2003))
real*8, dimension(3, :, :), intent(out) :: x = 1
"""
if isinstance(dim, Attribute):
if str(dim.name) != 'dimension':
raise ValueError("Got an unexpected Attribute argument as dim: %s" % str(dim))
else:
dim = dimension(*dim)
attrs = list(attrs) + [dim]
if intent is not None:
if intent not in (intent_in, intent_out, intent_inout):
intent = {'in': intent_in, 'out': intent_out, 'inout': intent_inout}[intent]
attrs.append(intent)
if type is None:
return Variable.deduced(symbol, value=value, attrs=attrs)
else:
return Variable(symbol, type, value=value, attrs=attrs)
def _printable(arg):
return String(arg) if isinstance(arg, str) else sympify(arg)
def allocated(array):
""" Creates an AST node for a function call to Fortran's "allocated(...)"
Examples
========
>>> from sympy import fcode
>>> from sympy.codegen.fnodes import allocated
>>> alloc = allocated('x')
>>> fcode(alloc, source_format='free')
'allocated(x)'
"""
return FunctionCall('allocated', [_printable(array)])
def lbound(array, dim=None, kind=None):
""" Creates an AST node for a function call to Fortran's "lbound(...)"
Parameters
==========
array : Symbol or String
dim : expr
kind : expr
Examples
========
>>> from sympy import fcode
>>> from sympy.codegen.fnodes import lbound
>>> lb = lbound('arr', dim=2)
>>> fcode(lb, source_format='free')
'lbound(arr, 2)'
"""
return FunctionCall(
'lbound',
[_printable(array)] +
([_printable(dim)] if dim else []) +
([_printable(kind)] if kind else [])
)
def ubound(array, dim=None, kind=None):
return FunctionCall(
'ubound',
[_printable(array)] +
([_printable(dim)] if dim else []) +
([_printable(kind)] if kind else [])
)
def shape(source, kind=None):
""" Creates an AST node for a function call to Fortran's "shape(...)"
Parameters
==========
source : Symbol or String
kind : expr
Examples
========
>>> from sympy import fcode
>>> from sympy.codegen.fnodes import shape
>>> shp = shape('x')
>>> fcode(shp, source_format='free')
'shape(x)'
"""
return FunctionCall(
'shape',
[_printable(source)] +
([_printable(kind)] if kind else [])
)
def size(array, dim=None, kind=None):
""" Creates an AST node for a function call to Fortran's "size(...)"
Examples
========
>>> from sympy import fcode, Symbol
>>> from sympy.codegen.ast import FunctionDefinition, real, Return
>>> from sympy.codegen.fnodes import array, sum_, size
>>> a = Symbol('a', real=True)
>>> body = [Return((sum_(a**2)/size(a))**.5)]
>>> arr = array(a, dim=[':'], intent='in')
>>> fd = FunctionDefinition(real, 'rms', [arr], body)
>>> print(fcode(fd, source_format='free', standard=2003))
real*8 function rms(a)
real*8, dimension(:), intent(in) :: a
rms = sqrt(sum(a**2)*1d0/size(a))
end function
"""
return FunctionCall(
'size',
[_printable(array)] +
([_printable(dim)] if dim else []) +
([_printable(kind)] if kind else [])
)
def reshape(source, shape, pad=None, order=None):
""" Creates an AST node for a function call to Fortran's "reshape(...)"
Parameters
==========
source : Symbol or String
shape : ArrayExpr
"""
return FunctionCall(
'reshape',
[_printable(source), _printable(shape)] +
([_printable(pad)] if pad else []) +
([_printable(order)] if pad else [])
)
def bind_C(name=None):
""" Creates an Attribute ``bind_C`` with a name.
Parameters
==========
name : str
Examples
========
>>> from sympy import fcode, Symbol
>>> from sympy.codegen.ast import FunctionDefinition, real, Return
>>> from sympy.codegen.fnodes import array, sum_, bind_C
>>> a = Symbol('a', real=True)
>>> s = Symbol('s', integer=True)
>>> arr = array(a, dim=[s], intent='in')
>>> body = [Return((sum_(a**2)/s)**.5)]
>>> fd = FunctionDefinition(real, 'rms', [arr, s], body, attrs=[bind_C('rms')])
>>> print(fcode(fd, source_format='free', standard=2003))
real*8 function rms(a, s) bind(C, name="rms")
real*8, dimension(s), intent(in) :: a
integer*4 :: s
rms = sqrt(sum(a**2)/s)
end function
"""
return Attribute('bind_C', [String(name)] if name else [])
class GoTo(Token):
""" Represents a goto statement in Fortran
Examples
========
>>> from sympy.codegen.fnodes import GoTo
>>> go = GoTo([10, 20, 30], 'i')
>>> from sympy import fcode
>>> fcode(go, source_format='free')
'go to (10, 20, 30), i'
"""
__slots__ = _fields = ('labels', 'expr')
defaults = {'expr': none}
_construct_labels = staticmethod(_mk_Tuple)
_construct_expr = staticmethod(sympify)
class FortranReturn(Token):
""" AST node explicitly mapped to a fortran "return".
Explanation
===========
Because a return statement in fortran is different from C, and
in order to aid reuse of our codegen ASTs the ordinary
``.codegen.ast.Return`` is interpreted as assignment to
the result variable of the function. If one for some reason needs
to generate a fortran RETURN statement, this node should be used.
Examples
========
>>> from sympy.codegen.fnodes import FortranReturn
>>> from sympy import fcode
>>> fcode(FortranReturn('x'))
' return x'
"""
__slots__ = _fields = ('return_value',)
defaults = {'return_value': none}
_construct_return_value = staticmethod(sympify)
class FFunction(Function):
_required_standard = 77
def _fcode(self, printer):
name = self.__class__.__name__
if printer._settings['standard'] < self._required_standard:
raise NotImplementedError("%s requires Fortran %d or newer" %
(name, self._required_standard))
return '{}({})'.format(name, ', '.join(map(printer._print, self.args)))
class F95Function(FFunction):
_required_standard = 95
class isign(FFunction):
""" Fortran sign intrinsic for integer arguments. """
nargs = 2
class dsign(FFunction):
""" Fortran sign intrinsic for double precision arguments. """
nargs = 2
class cmplx(FFunction):
""" Fortran complex conversion function. """
nargs = 2 # may be extended to (2, 3) at a later point
class kind(FFunction):
""" Fortran kind function. """
nargs = 1
class merge(F95Function):
""" Fortran merge function """
nargs = 3
class _literal(Float):
_token = None # type: str
_decimals = None # type: int
def _fcode(self, printer, *args, **kwargs):
mantissa, sgnd_ex = ('%.{}e'.format(self._decimals) % self).split('e')
mantissa = mantissa.strip('0').rstrip('.')
ex_sgn, ex_num = sgnd_ex[0], sgnd_ex[1:].lstrip('0')
ex_sgn = '' if ex_sgn == '+' else ex_sgn
return (mantissa or '0') + self._token + ex_sgn + (ex_num or '0')
class literal_sp(_literal):
""" Fortran single precision real literal """
_token = 'e'
_decimals = 9
class literal_dp(_literal):
""" Fortran double precision real literal """
_token = 'd'
_decimals = 17
class sum_(Token, Expr):
__slots__ = _fields = ('array', 'dim', 'mask')
defaults = {'dim': none, 'mask': none}
_construct_array = staticmethod(sympify)
_construct_dim = staticmethod(sympify)
class product_(Token, Expr):
__slots__ = _fields = ('array', 'dim', 'mask')
defaults = {'dim': none, 'mask': none}
_construct_array = staticmethod(sympify)
_construct_dim = staticmethod(sympify)
|
35ea3580543d902df54fe807f1379e09a0c335a0dee5d7883fdecc4591603079 | from .abstract_nodes import List as AbstractList
from .ast import Token
class List(AbstractList):
pass
class NumExprEvaluate(Token):
"""represents a call to :class:`numexpr`s :func:`evaluate`"""
__slots__ = _fields = ('expr',)
|
6410183d330632a1e2e23381b4893b62d3bd2248bc005c79f3f704c0b5e879cd | """
Types used to represent a full function/module as an Abstract Syntax Tree.
Most types are small, and are merely used as tokens in the AST. A tree diagram
has been included below to illustrate the relationships between the AST types.
AST Type Tree
-------------
::
*Basic*
|
|
CodegenAST
|
|--->AssignmentBase
| |--->Assignment
| |--->AugmentedAssignment
| |--->AddAugmentedAssignment
| |--->SubAugmentedAssignment
| |--->MulAugmentedAssignment
| |--->DivAugmentedAssignment
| |--->ModAugmentedAssignment
|
|--->CodeBlock
|
|
|--->Token
|--->Attribute
|--->For
|--->String
| |--->QuotedString
| |--->Comment
|--->Type
| |--->IntBaseType
| | |--->_SizedIntType
| | |--->SignedIntType
| | |--->UnsignedIntType
| |--->FloatBaseType
| |--->FloatType
| |--->ComplexBaseType
| |--->ComplexType
|--->Node
| |--->Variable
| | |---> Pointer
| |--->FunctionPrototype
| |--->FunctionDefinition
|--->Element
|--->Declaration
|--->While
|--->Scope
|--->Stream
|--->Print
|--->FunctionCall
|--->BreakToken
|--->ContinueToken
|--->NoneToken
|--->Return
Predefined types
----------------
A number of ``Type`` instances are provided in the ``sympy.codegen.ast`` module
for convenience. Perhaps the two most common ones for code-generation (of numeric
codes) are ``float32`` and ``float64`` (known as single and double precision respectively).
There are also precision generic versions of Types (for which the codeprinters selects the
underlying data type at time of printing): ``real``, ``integer``, ``complex_``, ``bool_``.
The other ``Type`` instances defined are:
- ``intc``: Integer type used by C's "int".
- ``intp``: Integer type used by C's "unsigned".
- ``int8``, ``int16``, ``int32``, ``int64``: n-bit integers.
- ``uint8``, ``uint16``, ``uint32``, ``uint64``: n-bit unsigned integers.
- ``float80``: known as "extended precision" on modern x86/amd64 hardware.
- ``complex64``: Complex number represented by two ``float32`` numbers
- ``complex128``: Complex number represented by two ``float64`` numbers
Using the nodes
---------------
It is possible to construct simple algorithms using the AST nodes. Let's construct a loop applying
Newton's method::
>>> from sympy import symbols, cos
>>> from sympy.codegen.ast import While, Assignment, aug_assign, Print
>>> t, dx, x = symbols('tol delta val')
>>> expr = cos(x) - x**3
>>> whl = While(abs(dx) > t, [
... Assignment(dx, -expr/expr.diff(x)),
... aug_assign(x, '+', dx),
... Print([x])
... ])
>>> from sympy import pycode
>>> py_str = pycode(whl)
>>> print(py_str)
while (abs(delta) > tol):
delta = (val**3 - math.cos(val))/(-3*val**2 - math.sin(val))
val += delta
print(val)
>>> import math
>>> tol, val, delta = 1e-5, 0.5, float('inf')
>>> exec(py_str)
1.1121416371
0.909672693737
0.867263818209
0.865477135298
0.865474033111
>>> print('%3.1g' % (math.cos(val) - val**3))
-3e-11
If we want to generate Fortran code for the same while loop we simple call ``fcode``::
>>> from sympy import fcode
>>> print(fcode(whl, standard=2003, source_format='free'))
do while (abs(delta) > tol)
delta = (val**3 - cos(val))/(-3*val**2 - sin(val))
val = val + delta
print *, val
end do
There is a function constructing a loop (or a complete function) like this in
:mod:`sympy.codegen.algorithms`.
"""
from typing import Any, Dict as tDict, List, Tuple as tTuple
from collections import defaultdict
from sympy.core.relational import (Ge, Gt, Le, Lt)
from sympy.core import Symbol, Tuple, Dummy
from sympy.core.basic import Basic
from sympy.core.expr import Expr, Atom
from sympy.core.numbers import Float, Integer, oo
from sympy.core.sympify import _sympify, sympify, SympifyError
from sympy.utilities.iterables import (iterable, topological_sort,
numbered_symbols, filter_symbols)
def _mk_Tuple(args):
"""
Create a SymPy Tuple object from an iterable, converting Python strings to
AST strings.
Parameters
==========
args: iterable
Arguments to :class:`sympy.Tuple`.
Returns
=======
sympy.Tuple
"""
args = [String(arg) if isinstance(arg, str) else arg for arg in args]
return Tuple(*args)
class CodegenAST(Basic):
__slots__ = ()
class Token(CodegenAST):
""" Base class for the AST types.
Explanation
===========
Defining fields are set in ``_fields``. Attributes (defined in _fields)
are only allowed to contain instances of Basic (unless atomic, see
``String``). The arguments to ``__new__()`` correspond to the attributes in
the order defined in ``_fields`. The ``defaults`` class attribute is a
dictionary mapping attribute names to their default values.
Subclasses should not need to override the ``__new__()`` method. They may
define a class or static method named ``_construct_<attr>`` for each
attribute to process the value passed to ``__new__()``. Attributes listed
in the class attribute ``not_in_args`` are not passed to :class:`~.Basic`.
"""
__slots__ = _fields = () # type: tTuple[str, ...]
defaults = {} # type: tDict[str, Any]
not_in_args = [] # type: List[str]
indented_args = ['body']
@property
def is_Atom(self):
return len(self._fields) == 0
@classmethod
def _get_constructor(cls, attr):
""" Get the constructor function for an attribute by name. """
return getattr(cls, '_construct_%s' % attr, lambda x: x)
@classmethod
def _construct(cls, attr, arg):
""" Construct an attribute value from argument passed to ``__new__()``. """
# arg may be ``NoneToken()``, so comparation is done using == instead of ``is`` operator
if arg == None:
return cls.defaults.get(attr, none)
else:
if isinstance(arg, Dummy): # SymPy's replace uses Dummy instances
return arg
else:
return cls._get_constructor(attr)(arg)
def __new__(cls, *args, **kwargs):
# Pass through existing instances when given as sole argument
if len(args) == 1 and not kwargs and isinstance(args[0], cls):
return args[0]
if len(args) > len(cls._fields):
raise ValueError("Too many arguments (%d), expected at most %d" % (len(args), len(cls._fields)))
attrvals = []
# Process positional arguments
for attrname, argval in zip(cls._fields, args):
if attrname in kwargs:
raise TypeError('Got multiple values for attribute %r' % attrname)
attrvals.append(cls._construct(attrname, argval))
# Process keyword arguments
for attrname in cls._fields[len(args):]:
if attrname in kwargs:
argval = kwargs.pop(attrname)
elif attrname in cls.defaults:
argval = cls.defaults[attrname]
else:
raise TypeError('No value for %r given and attribute has no default' % attrname)
attrvals.append(cls._construct(attrname, argval))
if kwargs:
raise ValueError("Unknown keyword arguments: %s" % ' '.join(kwargs))
# Parent constructor
basic_args = [
val for attr, val in zip(cls._fields, attrvals)
if attr not in cls.not_in_args
]
obj = CodegenAST.__new__(cls, *basic_args)
# Set attributes
for attr, arg in zip(cls._fields, attrvals):
setattr(obj, attr, arg)
return obj
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
for attr in self._fields:
if getattr(self, attr) != getattr(other, attr):
return False
return True
def _hashable_content(self):
return tuple([getattr(self, attr) for attr in self._fields])
def __hash__(self):
return super().__hash__()
def _joiner(self, k, indent_level):
return (',\n' + ' '*indent_level) if k in self.indented_args else ', '
def _indented(self, printer, k, v, *args, **kwargs):
il = printer._context['indent_level']
def _print(arg):
if isinstance(arg, Token):
return printer._print(arg, *args, joiner=self._joiner(k, il), **kwargs)
else:
return printer._print(arg, *args, **kwargs)
if isinstance(v, Tuple):
joined = self._joiner(k, il).join([_print(arg) for arg in v.args])
if k in self.indented_args:
return '(\n' + ' '*il + joined + ',\n' + ' '*(il - 4) + ')'
else:
return ('({0},)' if len(v.args) == 1 else '({0})').format(joined)
else:
return _print(v)
def _sympyrepr(self, printer, *args, joiner=', ', **kwargs):
from sympy.printing.printer import printer_context
exclude = kwargs.get('exclude', ())
values = [getattr(self, k) for k in self._fields]
indent_level = printer._context.get('indent_level', 0)
arg_reprs = []
for i, (attr, value) in enumerate(zip(self._fields, values)):
if attr in exclude:
continue
# Skip attributes which have the default value
if attr in self.defaults and value == self.defaults[attr]:
continue
ilvl = indent_level + 4 if attr in self.indented_args else 0
with printer_context(printer, indent_level=ilvl):
indented = self._indented(printer, attr, value, *args, **kwargs)
arg_reprs.append(('{1}' if i == 0 else '{0}={1}').format(attr, indented.lstrip()))
return "{}({})".format(self.__class__.__name__, joiner.join(arg_reprs))
_sympystr = _sympyrepr
def __repr__(self): # sympy.core.Basic.__repr__ uses sstr
from sympy.printing import srepr
return srepr(self)
def kwargs(self, exclude=(), apply=None):
""" Get instance's attributes as dict of keyword arguments.
Parameters
==========
exclude : collection of str
Collection of keywords to exclude.
apply : callable, optional
Function to apply to all values.
"""
kwargs = {k: getattr(self, k) for k in self._fields if k not in exclude}
if apply is not None:
return {k: apply(v) for k, v in kwargs.items()}
else:
return kwargs
class BreakToken(Token):
""" Represents 'break' in C/Python ('exit' in Fortran).
Use the premade instance ``break_`` or instantiate manually.
Examples
========
>>> from sympy import ccode, fcode
>>> from sympy.codegen.ast import break_
>>> ccode(break_)
'break'
>>> fcode(break_, source_format='free')
'exit'
"""
break_ = BreakToken()
class ContinueToken(Token):
""" Represents 'continue' in C/Python ('cycle' in Fortran)
Use the premade instance ``continue_`` or instantiate manually.
Examples
========
>>> from sympy import ccode, fcode
>>> from sympy.codegen.ast import continue_
>>> ccode(continue_)
'continue'
>>> fcode(continue_, source_format='free')
'cycle'
"""
continue_ = ContinueToken()
class NoneToken(Token):
""" The AST equivalence of Python's NoneType
The corresponding instance of Python's ``None`` is ``none``.
Examples
========
>>> from sympy.codegen.ast import none, Variable
>>> from sympy import pycode
>>> print(pycode(Variable('x').as_Declaration(value=none)))
x = None
"""
def __eq__(self, other):
return other is None or isinstance(other, NoneToken)
def _hashable_content(self):
return ()
def __hash__(self):
return super().__hash__()
none = NoneToken()
class AssignmentBase(CodegenAST):
""" Abstract base class for Assignment and AugmentedAssignment.
Attributes:
===========
op : str
Symbol for assignment operator, e.g. "=", "+=", etc.
"""
def __new__(cls, lhs, rhs):
lhs = _sympify(lhs)
rhs = _sympify(rhs)
cls._check_args(lhs, rhs)
return super().__new__(cls, lhs, rhs)
@property
def lhs(self):
return self.args[0]
@property
def rhs(self):
return self.args[1]
@classmethod
def _check_args(cls, lhs, rhs):
""" Check arguments to __new__ and raise exception if any problems found.
Derived classes may wish to override this.
"""
from sympy.matrices.expressions.matexpr import (
MatrixElement, MatrixSymbol)
from sympy.tensor.indexed import Indexed
# Tuple of things that can be on the lhs of an assignment
assignable = (Symbol, MatrixSymbol, MatrixElement, Indexed, Element, Variable)
if not isinstance(lhs, assignable):
raise TypeError("Cannot assign to lhs of type %s." % type(lhs))
# Indexed types implement shape, but don't define it until later. This
# causes issues in assignment validation. For now, matrices are defined
# as anything with a shape that is not an Indexed
lhs_is_mat = hasattr(lhs, 'shape') and not isinstance(lhs, Indexed)
rhs_is_mat = hasattr(rhs, 'shape') and not isinstance(rhs, Indexed)
# If lhs and rhs have same structure, then this assignment is ok
if lhs_is_mat:
if not rhs_is_mat:
raise ValueError("Cannot assign a scalar to a matrix.")
elif lhs.shape != rhs.shape:
raise ValueError("Dimensions of lhs and rhs do not align.")
elif rhs_is_mat and not lhs_is_mat:
raise ValueError("Cannot assign a matrix to a scalar.")
class Assignment(AssignmentBase):
"""
Represents variable assignment for code generation.
Parameters
==========
lhs : Expr
SymPy object representing the lhs of the expression. These should be
singular objects, such as one would use in writing code. Notable types
include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
subclass these types are also supported.
rhs : Expr
SymPy object representing the rhs of the expression. This can be any
type, provided its shape corresponds to that of the lhs. For example,
a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
the dimensions will not align.
Examples
========
>>> from sympy import symbols, MatrixSymbol, Matrix
>>> from sympy.codegen.ast import Assignment
>>> x, y, z = symbols('x, y, z')
>>> Assignment(x, y)
Assignment(x, y)
>>> Assignment(x, 0)
Assignment(x, 0)
>>> A = MatrixSymbol('A', 1, 3)
>>> mat = Matrix([x, y, z]).T
>>> Assignment(A, mat)
Assignment(A, Matrix([[x, y, z]]))
>>> Assignment(A[0, 1], x)
Assignment(A[0, 1], x)
"""
op = ':='
class AugmentedAssignment(AssignmentBase):
"""
Base class for augmented assignments.
Attributes:
===========
binop : str
Symbol for binary operation being applied in the assignment, such as "+",
"*", etc.
"""
binop = None # type: str
@property
def op(self):
return self.binop + '='
class AddAugmentedAssignment(AugmentedAssignment):
binop = '+'
class SubAugmentedAssignment(AugmentedAssignment):
binop = '-'
class MulAugmentedAssignment(AugmentedAssignment):
binop = '*'
class DivAugmentedAssignment(AugmentedAssignment):
binop = '/'
class ModAugmentedAssignment(AugmentedAssignment):
binop = '%'
# Mapping from binary op strings to AugmentedAssignment subclasses
augassign_classes = {
cls.binop: cls for cls in [
AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment,
DivAugmentedAssignment, ModAugmentedAssignment
]
}
def aug_assign(lhs, op, rhs):
"""
Create 'lhs op= rhs'.
Explanation
===========
Represents augmented variable assignment for code generation. This is a
convenience function. You can also use the AugmentedAssignment classes
directly, like AddAugmentedAssignment(x, y).
Parameters
==========
lhs : Expr
SymPy object representing the lhs of the expression. These should be
singular objects, such as one would use in writing code. Notable types
include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
subclass these types are also supported.
op : str
Operator (+, -, /, \\*, %).
rhs : Expr
SymPy object representing the rhs of the expression. This can be any
type, provided its shape corresponds to that of the lhs. For example,
a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
the dimensions will not align.
Examples
========
>>> from sympy import symbols
>>> from sympy.codegen.ast import aug_assign
>>> x, y = symbols('x, y')
>>> aug_assign(x, '+', y)
AddAugmentedAssignment(x, y)
"""
if op not in augassign_classes:
raise ValueError("Unrecognized operator %s" % op)
return augassign_classes[op](lhs, rhs)
class CodeBlock(CodegenAST):
"""
Represents a block of code.
Explanation
===========
For now only assignments are supported. This restriction will be lifted in
the future.
Useful attributes on this object are:
``left_hand_sides``:
Tuple of left-hand sides of assignments, in order.
``left_hand_sides``:
Tuple of right-hand sides of assignments, in order.
``free_symbols``: Free symbols of the expressions in the right-hand sides
which do not appear in the left-hand side of an assignment.
Useful methods on this object are:
``topological_sort``:
Class method. Return a CodeBlock with assignments
sorted so that variables are assigned before they
are used.
``cse``:
Return a new CodeBlock with common subexpressions eliminated and
pulled out as assignments.
Examples
========
>>> from sympy import symbols, ccode
>>> from sympy.codegen.ast import CodeBlock, Assignment
>>> x, y = symbols('x y')
>>> c = CodeBlock(Assignment(x, 1), Assignment(y, x + 1))
>>> print(ccode(c))
x = 1;
y = x + 1;
"""
def __new__(cls, *args):
left_hand_sides = []
right_hand_sides = []
for i in args:
if isinstance(i, Assignment):
lhs, rhs = i.args
left_hand_sides.append(lhs)
right_hand_sides.append(rhs)
obj = CodegenAST.__new__(cls, *args)
obj.left_hand_sides = Tuple(*left_hand_sides)
obj.right_hand_sides = Tuple(*right_hand_sides)
return obj
def __iter__(self):
return iter(self.args)
def _sympyrepr(self, printer, *args, **kwargs):
il = printer._context.get('indent_level', 0)
joiner = ',\n' + ' '*il
joined = joiner.join(map(printer._print, self.args))
return ('{}(\n'.format(' '*(il-4) + self.__class__.__name__,) +
' '*il + joined + '\n' + ' '*(il - 4) + ')')
_sympystr = _sympyrepr
@property
def free_symbols(self):
return super().free_symbols - set(self.left_hand_sides)
@classmethod
def topological_sort(cls, assignments):
"""
Return a CodeBlock with topologically sorted assignments so that
variables are assigned before they are used.
Examples
========
The existing order of assignments is preserved as much as possible.
This function assumes that variables are assigned to only once.
This is a class constructor so that the default constructor for
CodeBlock can error when variables are used before they are assigned.
Examples
========
>>> from sympy import symbols
>>> from sympy.codegen.ast import CodeBlock, Assignment
>>> x, y, z = symbols('x y z')
>>> assignments = [
... Assignment(x, y + z),
... Assignment(y, z + 1),
... Assignment(z, 2),
... ]
>>> CodeBlock.topological_sort(assignments)
CodeBlock(
Assignment(z, 2),
Assignment(y, z + 1),
Assignment(x, y + z)
)
"""
if not all(isinstance(i, Assignment) for i in assignments):
# Will support more things later
raise NotImplementedError("CodeBlock.topological_sort only supports Assignments")
if any(isinstance(i, AugmentedAssignment) for i in assignments):
raise NotImplementedError("CodeBlock.topological_sort does not yet work with AugmentedAssignments")
# Create a graph where the nodes are assignments and there is a directed edge
# between nodes that use a variable and nodes that assign that
# variable, like
# [(x := 1, y := x + 1), (x := 1, z := y + z), (y := x + 1, z := y + z)]
# If we then topologically sort these nodes, they will be in
# assignment order, like
# x := 1
# y := x + 1
# z := y + z
# A = The nodes
#
# enumerate keeps nodes in the same order they are already in if
# possible. It will also allow us to handle duplicate assignments to
# the same variable when those are implemented.
A = list(enumerate(assignments))
# var_map = {variable: [nodes for which this variable is assigned to]}
# like {x: [(1, x := y + z), (4, x := 2 * w)], ...}
var_map = defaultdict(list)
for node in A:
i, a = node
var_map[a.lhs].append(node)
# E = Edges in the graph
E = []
for dst_node in A:
i, a = dst_node
for s in a.rhs.free_symbols:
for src_node in var_map[s]:
E.append((src_node, dst_node))
ordered_assignments = topological_sort([A, E])
# De-enumerate the result
return cls(*[a for i, a in ordered_assignments])
def cse(self, symbols=None, optimizations=None, postprocess=None,
order='canonical'):
"""
Return a new code block with common subexpressions eliminated.
Explanation
===========
See the docstring of :func:`sympy.simplify.cse_main.cse` for more
information.
Examples
========
>>> from sympy import symbols, sin
>>> from sympy.codegen.ast import CodeBlock, Assignment
>>> x, y, z = symbols('x y z')
>>> c = CodeBlock(
... Assignment(x, 1),
... Assignment(y, sin(x) + 1),
... Assignment(z, sin(x) - 1),
... )
...
>>> c.cse()
CodeBlock(
Assignment(x, 1),
Assignment(x0, sin(x)),
Assignment(y, x0 + 1),
Assignment(z, x0 - 1)
)
"""
from sympy.simplify.cse_main import cse
# Check that the CodeBlock only contains assignments to unique variables
if not all(isinstance(i, Assignment) for i in self.args):
# Will support more things later
raise NotImplementedError("CodeBlock.cse only supports Assignments")
if any(isinstance(i, AugmentedAssignment) for i in self.args):
raise NotImplementedError("CodeBlock.cse does not yet work with AugmentedAssignments")
for i, lhs in enumerate(self.left_hand_sides):
if lhs in self.left_hand_sides[:i]:
raise NotImplementedError("Duplicate assignments to the same "
"variable are not yet supported (%s)" % lhs)
# Ensure new symbols for subexpressions do not conflict with existing
existing_symbols = self.atoms(Symbol)
if symbols is None:
symbols = numbered_symbols()
symbols = filter_symbols(symbols, existing_symbols)
replacements, reduced_exprs = cse(list(self.right_hand_sides),
symbols=symbols, optimizations=optimizations, postprocess=postprocess,
order=order)
new_block = [Assignment(var, expr) for var, expr in
zip(self.left_hand_sides, reduced_exprs)]
new_assignments = [Assignment(var, expr) for var, expr in replacements]
return self.topological_sort(new_assignments + new_block)
class For(Token):
"""Represents a 'for-loop' in the code.
Expressions are of the form:
"for target in iter:
body..."
Parameters
==========
target : symbol
iter : iterable
body : CodeBlock or iterable
! When passed an iterable it is used to instantiate a CodeBlock.
Examples
========
>>> from sympy import symbols, Range
>>> from sympy.codegen.ast import aug_assign, For
>>> x, i, j, k = symbols('x i j k')
>>> for_i = For(i, Range(10), [aug_assign(x, '+', i*j*k)])
>>> for_i # doctest: -NORMALIZE_WHITESPACE
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
AddAugmentedAssignment(x, i*j*k)
))
>>> for_ji = For(j, Range(7), [for_i])
>>> for_ji # doctest: -NORMALIZE_WHITESPACE
For(j, iterable=Range(0, 7, 1), body=CodeBlock(
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
AddAugmentedAssignment(x, i*j*k)
))
))
>>> for_kji =For(k, Range(5), [for_ji])
>>> for_kji # doctest: -NORMALIZE_WHITESPACE
For(k, iterable=Range(0, 5, 1), body=CodeBlock(
For(j, iterable=Range(0, 7, 1), body=CodeBlock(
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
AddAugmentedAssignment(x, i*j*k)
))
))
))
"""
__slots__ = _fields = ('target', 'iterable', 'body')
_construct_target = staticmethod(_sympify)
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
@classmethod
def _construct_iterable(cls, itr):
if not iterable(itr):
raise TypeError("iterable must be an iterable")
if isinstance(itr, list): # _sympify errors on lists because they are mutable
itr = tuple(itr)
return _sympify(itr)
class String(Atom, Token):
""" SymPy object representing a string.
Atomic object which is not an expression (as opposed to Symbol).
Parameters
==========
text : str
Examples
========
>>> from sympy.codegen.ast import String
>>> f = String('foo')
>>> f
foo
>>> str(f)
'foo'
>>> f.text
'foo'
>>> print(repr(f))
String('foo')
"""
__slots__ = _fields = ('text',)
not_in_args = ['text']
is_Atom = True
@classmethod
def _construct_text(cls, text):
if not isinstance(text, str):
raise TypeError("Argument text is not a string type.")
return text
def _sympystr(self, printer, *args, **kwargs):
return self.text
def kwargs(self, exclude = (), apply = None):
return {}
#to be removed when Atom is given a suitable func
@property
def func(self):
return lambda: self
def _latex(self, printer):
from sympy.printing.latex import latex_escape
return r'\texttt{{"{}"}}'.format(latex_escape(self.text))
class QuotedString(String):
""" Represents a string which should be printed with quotes. """
class Comment(String):
""" Represents a comment. """
class Node(Token):
""" Subclass of Token, carrying the attribute 'attrs' (Tuple)
Examples
========
>>> from sympy.codegen.ast import Node, value_const, pointer_const
>>> n1 = Node([value_const])
>>> n1.attr_params('value_const') # get the parameters of attribute (by name)
()
>>> from sympy.codegen.fnodes import dimension
>>> n2 = Node([value_const, dimension(5, 3)])
>>> n2.attr_params(value_const) # get the parameters of attribute (by Attribute instance)
()
>>> n2.attr_params('dimension') # get the parameters of attribute (by name)
(5, 3)
>>> n2.attr_params(pointer_const) is None
True
"""
__slots__ = _fields = ('attrs',) # type: tTuple[str, ...]
defaults = {'attrs': Tuple()} # type: tDict[str, Any]
_construct_attrs = staticmethod(_mk_Tuple)
def attr_params(self, looking_for):
""" Returns the parameters of the Attribute with name ``looking_for`` in self.attrs """
for attr in self.attrs:
if str(attr.name) == str(looking_for):
return attr.parameters
class Type(Token):
""" Represents a type.
Explanation
===========
The naming is a super-set of NumPy naming. Type has a classmethod
``from_expr`` which offer type deduction. It also has a method
``cast_check`` which casts the argument to its type, possibly raising an
exception if rounding error is not within tolerances, or if the value is not
representable by the underlying data type (e.g. unsigned integers).
Parameters
==========
name : str
Name of the type, e.g. ``object``, ``int16``, ``float16`` (where the latter two
would use the ``Type`` sub-classes ``IntType`` and ``FloatType`` respectively).
If a ``Type`` instance is given, the said instance is returned.
Examples
========
>>> from sympy.codegen.ast import Type
>>> t = Type.from_expr(42)
>>> t
integer
>>> print(repr(t))
IntBaseType(String('integer'))
>>> from sympy.codegen.ast import uint8
>>> uint8.cast_check(-1) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Minimum value for data type bigger than new value.
>>> from sympy.codegen.ast import float32
>>> v6 = 0.123456
>>> float32.cast_check(v6)
0.123456
>>> v10 = 12345.67894
>>> float32.cast_check(v10) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Casting gives a significantly different value.
>>> boost_mp50 = Type('boost::multiprecision::cpp_dec_float_50')
>>> from sympy import cxxcode
>>> from sympy.codegen.ast import Declaration, Variable
>>> cxxcode(Declaration(Variable('x', type=boost_mp50)))
'boost::multiprecision::cpp_dec_float_50 x'
References
==========
.. [1] https://docs.scipy.org/doc/numpy/user/basics.types.html
"""
__slots__ = _fields = ('name',) # type: tTuple[str, ...]
_construct_name = String
def _sympystr(self, printer, *args, **kwargs):
return str(self.name)
@classmethod
def from_expr(cls, expr):
""" Deduces type from an expression or a ``Symbol``.
Parameters
==========
expr : number or SymPy object
The type will be deduced from type or properties.
Examples
========
>>> from sympy.codegen.ast import Type, integer, complex_
>>> Type.from_expr(2) == integer
True
>>> from sympy import Symbol
>>> Type.from_expr(Symbol('z', complex=True)) == complex_
True
>>> Type.from_expr(sum) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Could not deduce type from expr.
Raises
======
ValueError when type deduction fails.
"""
if isinstance(expr, (float, Float)):
return real
if isinstance(expr, (int, Integer)) or getattr(expr, 'is_integer', False):
return integer
if getattr(expr, 'is_real', False):
return real
if isinstance(expr, complex) or getattr(expr, 'is_complex', False):
return complex_
if isinstance(expr, bool) or getattr(expr, 'is_Relational', False):
return bool_
else:
raise ValueError("Could not deduce type from expr.")
def _check(self, value):
pass
def cast_check(self, value, rtol=None, atol=0, precision_targets=None):
""" Casts a value to the data type of the instance.
Parameters
==========
value : number
rtol : floating point number
Relative tolerance. (will be deduced if not given).
atol : floating point number
Absolute tolerance (in addition to ``rtol``).
type_aliases : dict
Maps substitutions for Type, e.g. {integer: int64, real: float32}
Examples
========
>>> from sympy.codegen.ast import integer, float32, int8
>>> integer.cast_check(3.0) == 3
True
>>> float32.cast_check(1e-40) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Minimum value for data type bigger than new value.
>>> int8.cast_check(256) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Maximum value for data type smaller than new value.
>>> v10 = 12345.67894
>>> float32.cast_check(v10) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Casting gives a significantly different value.
>>> from sympy.codegen.ast import float64
>>> float64.cast_check(v10)
12345.67894
>>> from sympy import Float
>>> v18 = Float('0.123456789012345646')
>>> float64.cast_check(v18)
Traceback (most recent call last):
...
ValueError: Casting gives a significantly different value.
>>> from sympy.codegen.ast import float80
>>> float80.cast_check(v18)
0.123456789012345649
"""
val = sympify(value)
ten = Integer(10)
exp10 = getattr(self, 'decimal_dig', None)
if rtol is None:
rtol = 1e-15 if exp10 is None else 2.0*ten**(-exp10)
def tol(num):
return atol + rtol*abs(num)
new_val = self.cast_nocheck(value)
self._check(new_val)
delta = new_val - val
if abs(delta) > tol(val): # rounding, e.g. int(3.5) != 3.5
raise ValueError("Casting gives a significantly different value.")
return new_val
def _latex(self, printer):
from sympy.printing.latex import latex_escape
type_name = latex_escape(self.__class__.__name__)
name = latex_escape(self.name.text)
return r"\text{{{}}}\left(\texttt{{{}}}\right)".format(type_name, name)
class IntBaseType(Type):
""" Integer base type, contains no size information. """
__slots__ = ()
cast_nocheck = lambda self, i: Integer(int(i))
class _SizedIntType(IntBaseType):
__slots__ = ('nbits',)
_fields = Type._fields + __slots__
_construct_nbits = Integer
def _check(self, value):
if value < self.min:
raise ValueError("Value is too small: %d < %d" % (value, self.min))
if value > self.max:
raise ValueError("Value is too big: %d > %d" % (value, self.max))
class SignedIntType(_SizedIntType):
""" Represents a signed integer type. """
__slots__ = ()
@property
def min(self):
return -2**(self.nbits-1)
@property
def max(self):
return 2**(self.nbits-1) - 1
class UnsignedIntType(_SizedIntType):
""" Represents an unsigned integer type. """
__slots__ = ()
@property
def min(self):
return 0
@property
def max(self):
return 2**self.nbits - 1
two = Integer(2)
class FloatBaseType(Type):
""" Represents a floating point number type. """
__slots__ = ()
cast_nocheck = Float
class FloatType(FloatBaseType):
""" Represents a floating point type with fixed bit width.
Base 2 & one sign bit is assumed.
Parameters
==========
name : str
Name of the type.
nbits : integer
Number of bits used (storage).
nmant : integer
Number of bits used to represent the mantissa.
nexp : integer
Number of bits used to represent the mantissa.
Examples
========
>>> from sympy import S
>>> from sympy.codegen.ast import FloatType
>>> half_precision = FloatType('f16', nbits=16, nmant=10, nexp=5)
>>> half_precision.max
65504
>>> half_precision.tiny == S(2)**-14
True
>>> half_precision.eps == S(2)**-10
True
>>> half_precision.dig == 3
True
>>> half_precision.decimal_dig == 5
True
>>> half_precision.cast_check(1.0)
1.0
>>> half_precision.cast_check(1e5) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Maximum value for data type smaller than new value.
"""
__slots__ = ('nbits', 'nmant', 'nexp',)
_fields = Type._fields + __slots__
_construct_nbits = _construct_nmant = _construct_nexp = Integer
@property
def max_exponent(self):
""" The largest positive number n, such that 2**(n - 1) is a representable finite value. """
# cf. C++'s ``std::numeric_limits::max_exponent``
return two**(self.nexp - 1)
@property
def min_exponent(self):
""" The lowest negative number n, such that 2**(n - 1) is a valid normalized number. """
# cf. C++'s ``std::numeric_limits::min_exponent``
return 3 - self.max_exponent
@property
def max(self):
""" Maximum value representable. """
return (1 - two**-(self.nmant+1))*two**self.max_exponent
@property
def tiny(self):
""" The minimum positive normalized value. """
# See C macros: FLT_MIN, DBL_MIN, LDBL_MIN
# or C++'s ``std::numeric_limits::min``
# or numpy.finfo(dtype).tiny
return two**(self.min_exponent - 1)
@property
def eps(self):
""" Difference between 1.0 and the next representable value. """
return two**(-self.nmant)
@property
def dig(self):
""" Number of decimal digits that are guaranteed to be preserved in text.
When converting text -> float -> text, you are guaranteed that at least ``dig``
number of digits are preserved with respect to rounding or overflow.
"""
from sympy.functions import floor, log
return floor(self.nmant * log(2)/log(10))
@property
def decimal_dig(self):
""" Number of digits needed to store & load without loss.
Explanation
===========
Number of decimal digits needed to guarantee that two consecutive conversions
(float -> text -> float) to be idempotent. This is useful when one do not want
to loose precision due to rounding errors when storing a floating point value
as text.
"""
from sympy.functions import ceiling, log
return ceiling((self.nmant + 1) * log(2)/log(10) + 1)
def cast_nocheck(self, value):
""" Casts without checking if out of bounds or subnormal. """
if value == oo: # float(oo) or oo
return float(oo)
elif value == -oo: # float(-oo) or -oo
return float(-oo)
return Float(str(sympify(value).evalf(self.decimal_dig)), self.decimal_dig)
def _check(self, value):
if value < -self.max:
raise ValueError("Value is too small: %d < %d" % (value, -self.max))
if value > self.max:
raise ValueError("Value is too big: %d > %d" % (value, self.max))
if abs(value) < self.tiny:
raise ValueError("Smallest (absolute) value for data type bigger than new value.")
class ComplexBaseType(FloatBaseType):
__slots__ = ()
def cast_nocheck(self, value):
""" Casts without checking if out of bounds or subnormal. """
from sympy.functions import re, im
return (
super().cast_nocheck(re(value)) +
super().cast_nocheck(im(value))*1j
)
def _check(self, value):
from sympy.functions import re, im
super()._check(re(value))
super()._check(im(value))
class ComplexType(ComplexBaseType, FloatType):
""" Represents a complex floating point number. """
__slots__ = ()
# NumPy types:
intc = IntBaseType('intc')
intp = IntBaseType('intp')
int8 = SignedIntType('int8', 8)
int16 = SignedIntType('int16', 16)
int32 = SignedIntType('int32', 32)
int64 = SignedIntType('int64', 64)
uint8 = UnsignedIntType('uint8', 8)
uint16 = UnsignedIntType('uint16', 16)
uint32 = UnsignedIntType('uint32', 32)
uint64 = UnsignedIntType('uint64', 64)
float16 = FloatType('float16', 16, nexp=5, nmant=10) # IEEE 754 binary16, Half precision
float32 = FloatType('float32', 32, nexp=8, nmant=23) # IEEE 754 binary32, Single precision
float64 = FloatType('float64', 64, nexp=11, nmant=52) # IEEE 754 binary64, Double precision
float80 = FloatType('float80', 80, nexp=15, nmant=63) # x86 extended precision (1 integer part bit), "long double"
float128 = FloatType('float128', 128, nexp=15, nmant=112) # IEEE 754 binary128, Quadruple precision
float256 = FloatType('float256', 256, nexp=19, nmant=236) # IEEE 754 binary256, Octuple precision
complex64 = ComplexType('complex64', nbits=64, **float32.kwargs(exclude=('name', 'nbits')))
complex128 = ComplexType('complex128', nbits=128, **float64.kwargs(exclude=('name', 'nbits')))
# Generic types (precision may be chosen by code printers):
untyped = Type('untyped')
real = FloatBaseType('real')
integer = IntBaseType('integer')
complex_ = ComplexBaseType('complex')
bool_ = Type('bool')
class Attribute(Token):
""" Attribute (possibly parametrized)
For use with :class:`sympy.codegen.ast.Node` (which takes instances of
``Attribute`` as ``attrs``).
Parameters
==========
name : str
parameters : Tuple
Examples
========
>>> from sympy.codegen.ast import Attribute
>>> volatile = Attribute('volatile')
>>> volatile
volatile
>>> print(repr(volatile))
Attribute(String('volatile'))
>>> a = Attribute('foo', [1, 2, 3])
>>> a
foo(1, 2, 3)
>>> a.parameters == (1, 2, 3)
True
"""
__slots__ = _fields = ('name', 'parameters')
defaults = {'parameters': Tuple()}
_construct_name = String
_construct_parameters = staticmethod(_mk_Tuple)
def _sympystr(self, printer, *args, **kwargs):
result = str(self.name)
if self.parameters:
result += '(%s)' % ', '.join(map(lambda arg: printer._print(
arg, *args, **kwargs), self.parameters))
return result
value_const = Attribute('value_const')
pointer_const = Attribute('pointer_const')
class Variable(Node):
""" Represents a variable.
Parameters
==========
symbol : Symbol
type : Type (optional)
Type of the variable.
attrs : iterable of Attribute instances
Will be stored as a Tuple.
Examples
========
>>> from sympy import Symbol
>>> from sympy.codegen.ast import Variable, float32, integer
>>> x = Symbol('x')
>>> v = Variable(x, type=float32)
>>> v.attrs
()
>>> v == Variable('x')
False
>>> v == Variable('x', type=float32)
True
>>> v
Variable(x, type=float32)
One may also construct a ``Variable`` instance with the type deduced from
assumptions about the symbol using the ``deduced`` classmethod:
>>> i = Symbol('i', integer=True)
>>> v = Variable.deduced(i)
>>> v.type == integer
True
>>> v == Variable('i')
False
>>> from sympy.codegen.ast import value_const
>>> value_const in v.attrs
False
>>> w = Variable('w', attrs=[value_const])
>>> w
Variable(w, attrs=(value_const,))
>>> value_const in w.attrs
True
>>> w.as_Declaration(value=42)
Declaration(Variable(w, value=42, attrs=(value_const,)))
"""
__slots__ = ('symbol', 'type', 'value')
_fields = __slots__ + Node._fields
defaults = Node.defaults.copy()
defaults.update({'type': untyped, 'value': none})
_construct_symbol = staticmethod(sympify)
_construct_value = staticmethod(sympify)
@classmethod
def deduced(cls, symbol, value=None, attrs=Tuple(), cast_check=True):
""" Alt. constructor with type deduction from ``Type.from_expr``.
Deduces type primarily from ``symbol``, secondarily from ``value``.
Parameters
==========
symbol : Symbol
value : expr
(optional) value of the variable.
attrs : iterable of Attribute instances
cast_check : bool
Whether to apply ``Type.cast_check`` on ``value``.
Examples
========
>>> from sympy import Symbol
>>> from sympy.codegen.ast import Variable, complex_
>>> n = Symbol('n', integer=True)
>>> str(Variable.deduced(n).type)
'integer'
>>> x = Symbol('x', real=True)
>>> v = Variable.deduced(x)
>>> v.type
real
>>> z = Symbol('z', complex=True)
>>> Variable.deduced(z).type == complex_
True
"""
if isinstance(symbol, Variable):
return symbol
try:
type_ = Type.from_expr(symbol)
except ValueError:
type_ = Type.from_expr(value)
if value is not None and cast_check:
value = type_.cast_check(value)
return cls(symbol, type=type_, value=value, attrs=attrs)
def as_Declaration(self, **kwargs):
""" Convenience method for creating a Declaration instance.
Explanation
===========
If the variable of the Declaration need to wrap a modified
variable keyword arguments may be passed (overriding e.g.
the ``value`` of the Variable instance).
Examples
========
>>> from sympy.codegen.ast import Variable, NoneToken
>>> x = Variable('x')
>>> decl1 = x.as_Declaration()
>>> # value is special NoneToken() which must be tested with == operator
>>> decl1.variable.value is None # won't work
False
>>> decl1.variable.value == None # not PEP-8 compliant
True
>>> decl1.variable.value == NoneToken() # OK
True
>>> decl2 = x.as_Declaration(value=42.0)
>>> decl2.variable.value == 42
True
"""
kw = self.kwargs()
kw.update(kwargs)
return Declaration(self.func(**kw))
def _relation(self, rhs, op):
try:
rhs = _sympify(rhs)
except SympifyError:
raise TypeError("Invalid comparison %s < %s" % (self, rhs))
return op(self, rhs, evaluate=False)
__lt__ = lambda self, other: self._relation(other, Lt)
__le__ = lambda self, other: self._relation(other, Le)
__ge__ = lambda self, other: self._relation(other, Ge)
__gt__ = lambda self, other: self._relation(other, Gt)
class Pointer(Variable):
""" Represents a pointer. See ``Variable``.
Examples
========
Can create instances of ``Element``:
>>> from sympy import Symbol
>>> from sympy.codegen.ast import Pointer
>>> i = Symbol('i', integer=True)
>>> p = Pointer('x')
>>> p[i+1]
Element(x, indices=(i + 1,))
"""
__slots__ = ()
def __getitem__(self, key):
try:
return Element(self.symbol, key)
except TypeError:
return Element(self.symbol, (key,))
class Element(Token):
""" Element in (a possibly N-dimensional) array.
Examples
========
>>> from sympy.codegen.ast import Element
>>> elem = Element('x', 'ijk')
>>> elem.symbol.name == 'x'
True
>>> elem.indices
(i, j, k)
>>> from sympy import ccode
>>> ccode(elem)
'x[i][j][k]'
>>> ccode(Element('x', 'ijk', strides='lmn', offset='o'))
'x[i*l + j*m + k*n + o]'
"""
__slots__ = _fields = ('symbol', 'indices', 'strides', 'offset')
defaults = {'strides': none, 'offset': none}
_construct_symbol = staticmethod(sympify)
_construct_indices = staticmethod(lambda arg: Tuple(*arg))
_construct_strides = staticmethod(lambda arg: Tuple(*arg))
_construct_offset = staticmethod(sympify)
class Declaration(Token):
""" Represents a variable declaration
Parameters
==========
variable : Variable
Examples
========
>>> from sympy.codegen.ast import Declaration, NoneToken, untyped
>>> z = Declaration('z')
>>> z.variable.type == untyped
True
>>> # value is special NoneToken() which must be tested with == operator
>>> z.variable.value is None # won't work
False
>>> z.variable.value == None # not PEP-8 compliant
True
>>> z.variable.value == NoneToken() # OK
True
"""
__slots__ = _fields = ('variable',)
_construct_variable = Variable
class While(Token):
""" Represents a 'for-loop' in the code.
Expressions are of the form:
"while condition:
body..."
Parameters
==========
condition : expression convertible to Boolean
body : CodeBlock or iterable
When passed an iterable it is used to instantiate a CodeBlock.
Examples
========
>>> from sympy import symbols, Gt, Abs
>>> from sympy.codegen import aug_assign, Assignment, While
>>> x, dx = symbols('x dx')
>>> expr = 1 - x**2
>>> whl = While(Gt(Abs(dx), 1e-9), [
... Assignment(dx, -expr/expr.diff(x)),
... aug_assign(x, '+', dx)
... ])
"""
__slots__ = _fields = ('condition', 'body')
_construct_condition = staticmethod(lambda cond: _sympify(cond))
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
class Scope(Token):
""" Represents a scope in the code.
Parameters
==========
body : CodeBlock or iterable
When passed an iterable it is used to instantiate a CodeBlock.
"""
__slots__ = _fields = ('body',)
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
class Stream(Token):
""" Represents a stream.
There are two predefined Stream instances ``stdout`` & ``stderr``.
Parameters
==========
name : str
Examples
========
>>> from sympy import pycode, Symbol
>>> from sympy.codegen.ast import Print, stderr, QuotedString
>>> print(pycode(Print(['x'], file=stderr)))
print(x, file=sys.stderr)
>>> x = Symbol('x')
>>> print(pycode(Print([QuotedString('x')], file=stderr))) # print literally "x"
print("x", file=sys.stderr)
"""
__slots__ = _fields = ('name',)
_construct_name = String
stdout = Stream('stdout')
stderr = Stream('stderr')
class Print(Token):
""" Represents print command in the code.
Parameters
==========
formatstring : str
*args : Basic instances (or convertible to such through sympify)
Examples
========
>>> from sympy.codegen.ast import Print
>>> from sympy import pycode
>>> print(pycode(Print('x y'.split(), "coordinate: %12.5g %12.5g")))
print("coordinate: %12.5g %12.5g" % (x, y))
"""
__slots__ = _fields = ('print_args', 'format_string', 'file')
defaults = {'format_string': none, 'file': none}
_construct_print_args = staticmethod(_mk_Tuple)
_construct_format_string = QuotedString
_construct_file = Stream
class FunctionPrototype(Node):
""" Represents a function prototype
Allows the user to generate forward declaration in e.g. C/C++.
Parameters
==========
return_type : Type
name : str
parameters: iterable of Variable instances
attrs : iterable of Attribute instances
Examples
========
>>> from sympy import ccode, symbols
>>> from sympy.codegen.ast import real, FunctionPrototype
>>> x, y = symbols('x y', real=True)
>>> fp = FunctionPrototype(real, 'foo', [x, y])
>>> ccode(fp)
'double foo(double x, double y)'
"""
__slots__ = ('return_type', 'name', 'parameters')
_fields = __slots__ + Node._fields # type: tTuple[str, ...]
_construct_return_type = Type
_construct_name = String
@staticmethod
def _construct_parameters(args):
def _var(arg):
if isinstance(arg, Declaration):
return arg.variable
elif isinstance(arg, Variable):
return arg
else:
return Variable.deduced(arg)
return Tuple(*map(_var, args))
@classmethod
def from_FunctionDefinition(cls, func_def):
if not isinstance(func_def, FunctionDefinition):
raise TypeError("func_def is not an instance of FunctionDefiniton")
return cls(**func_def.kwargs(exclude=('body',)))
class FunctionDefinition(FunctionPrototype):
""" Represents a function definition in the code.
Parameters
==========
return_type : Type
name : str
parameters: iterable of Variable instances
body : CodeBlock or iterable
attrs : iterable of Attribute instances
Examples
========
>>> from sympy import ccode, symbols
>>> from sympy.codegen.ast import real, FunctionPrototype
>>> x, y = symbols('x y', real=True)
>>> fp = FunctionPrototype(real, 'foo', [x, y])
>>> ccode(fp)
'double foo(double x, double y)'
>>> from sympy.codegen.ast import FunctionDefinition, Return
>>> body = [Return(x*y)]
>>> fd = FunctionDefinition.from_FunctionPrototype(fp, body)
>>> print(ccode(fd))
double foo(double x, double y){
return x*y;
}
"""
__slots__ = ('body', )
_fields = FunctionPrototype._fields[:-1] + __slots__ + Node._fields
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
@classmethod
def from_FunctionPrototype(cls, func_proto, body):
if not isinstance(func_proto, FunctionPrototype):
raise TypeError("func_proto is not an instance of FunctionPrototype")
return cls(body=body, **func_proto.kwargs())
class Return(Token):
""" Represents a return command in the code.
Parameters
==========
return : Basic
Examples
========
>>> from sympy.codegen.ast import Return
>>> from sympy.printing.pycode import pycode
>>> from sympy import Symbol
>>> x = Symbol('x')
>>> print(pycode(Return(x)))
return x
"""
__slots__ = _fields = ('return',)
_construct_return=staticmethod(_sympify)
class FunctionCall(Token, Expr):
""" Represents a call to a function in the code.
Parameters
==========
name : str
function_args : Tuple
Examples
========
>>> from sympy.codegen.ast import FunctionCall
>>> from sympy import pycode
>>> fcall = FunctionCall('foo', 'bar baz'.split())
>>> print(pycode(fcall))
foo(bar, baz)
"""
__slots__ = _fields = ('name', 'function_args')
_construct_name = String
_construct_function_args = staticmethod(lambda args: Tuple(*args))
|
1e18a9d1c6c18f6ee2fb82705629e412de0f1d16c021ee44471c32cb0a12266f | """
Additional AST nodes for operations on matrices. The nodes in this module
are meant to represent optimization of matrix expressions within codegen's
target languages that cannot be represented by SymPy expressions.
As an example, we can use :meth:`sympy.codegen.rewriting.optimize` and the
``matin_opt`` optimization provided in :mod:`sympy.codegen.rewriting` to
transform matrix multiplication under certain assumptions:
>>> from sympy import symbols, MatrixSymbol
>>> n = symbols('n', integer=True)
>>> A = MatrixSymbol('A', n, n)
>>> x = MatrixSymbol('x', n, 1)
>>> expr = A**(-1) * x
>>> from sympy import assuming, Q
>>> from sympy.codegen.rewriting import matinv_opt, optimize
>>> with assuming(Q.fullrank(A)):
... optimize(expr, [matinv_opt])
MatrixSolve(A, vector=x)
"""
from .ast import Token
from sympy.matrices import MatrixExpr
from sympy.core.sympify import sympify
class MatrixSolve(Token, MatrixExpr):
"""Represents an operation to solve a linear matrix equation.
Parameters
==========
matrix : MatrixSymbol
Matrix representing the coefficients of variables in the linear
equation. This matrix must be square and full-rank (i.e. all columns must
be linearly independent) for the solving operation to be valid.
vector : MatrixSymbol
One-column matrix representing the solutions to the equations
represented in ``matrix``.
Examples
========
>>> from sympy import symbols, MatrixSymbol
>>> from sympy.codegen.matrix_nodes import MatrixSolve
>>> n = symbols('n', integer=True)
>>> A = MatrixSymbol('A', n, n)
>>> x = MatrixSymbol('x', n, 1)
>>> from sympy.printing.numpy import NumPyPrinter
>>> NumPyPrinter().doprint(MatrixSolve(A, x))
'numpy.linalg.solve(A, x)'
>>> from sympy import octave_code
>>> octave_code(MatrixSolve(A, x))
'A \\\\ x'
"""
__slots__ = _fields = ('matrix', 'vector')
_construct_matrix = staticmethod(sympify)
@property
def shape(self):
return self.vector.shape
|
af5343005f062c06f6de40db60c6d21a84defcf36de94152aa76a931ebea433f | """
This file contains some classical ciphers and routines
implementing a linear-feedback shift register (LFSR)
and the Diffie-Hellman key exchange.
.. warning::
This module is intended for educational purposes only. Do not use the
functions in this module for real cryptographic applications. If you wish
to encrypt real data, we recommend using something like the `cryptography
<https://cryptography.io/en/latest/>`_ module.
"""
from string import whitespace, ascii_uppercase as uppercase, printable
from functools import reduce
import warnings
from itertools import cycle
from sympy.core import Symbol
from sympy.core.numbers import igcdex, mod_inverse, igcd, Rational
from sympy.core.random import _randrange, _randint
from sympy.matrices import Matrix
from sympy.ntheory import isprime, primitive_root, factorint
from sympy.ntheory import totient as _euler
from sympy.ntheory import reduced_totient as _carmichael
from sympy.ntheory.generate import nextprime
from sympy.ntheory.modular import crt
from sympy.polys.domains import FF
from sympy.polys.polytools import gcd, Poly
from sympy.utilities.misc import as_int, filldedent, translate
from sympy.utilities.iterables import uniq, multiset
class NonInvertibleCipherWarning(RuntimeWarning):
"""A warning raised if the cipher is not invertible."""
def __init__(self, msg):
self.fullMessage = msg
def __str__(self):
return '\n\t' + self.fullMessage
def warn(self, stacklevel=3):
warnings.warn(self, stacklevel=stacklevel)
def AZ(s=None):
"""Return the letters of ``s`` in uppercase. In case more than
one string is passed, each of them will be processed and a list
of upper case strings will be returned.
Examples
========
>>> from sympy.crypto.crypto import AZ
>>> AZ('Hello, world!')
'HELLOWORLD'
>>> AZ('Hello, world!'.split())
['HELLO', 'WORLD']
See Also
========
check_and_join
"""
if not s:
return uppercase
t = isinstance(s, str)
if t:
s = [s]
rv = [check_and_join(i.upper().split(), uppercase, filter=True)
for i in s]
if t:
return rv[0]
return rv
bifid5 = AZ().replace('J', '')
bifid6 = AZ() + '0123456789'
bifid10 = printable
def padded_key(key, symbols):
"""Return a string of the distinct characters of ``symbols`` with
those of ``key`` appearing first. A ValueError is raised if
a) there are duplicate characters in ``symbols`` or
b) there are characters in ``key`` that are not in ``symbols``.
Examples
========
>>> from sympy.crypto.crypto import padded_key
>>> padded_key('PUPPY', 'OPQRSTUVWXY')
'PUYOQRSTVWX'
>>> padded_key('RSA', 'ARTIST')
Traceback (most recent call last):
...
ValueError: duplicate characters in symbols: T
"""
syms = list(uniq(symbols))
if len(syms) != len(symbols):
extra = ''.join(sorted({
i for i in symbols if symbols.count(i) > 1}))
raise ValueError('duplicate characters in symbols: %s' % extra)
extra = set(key) - set(syms)
if extra:
raise ValueError(
'characters in key but not symbols: %s' % ''.join(
sorted(extra)))
key0 = ''.join(list(uniq(key)))
# remove from syms characters in key0
return key0 + translate(''.join(syms), None, key0)
def check_and_join(phrase, symbols=None, filter=None):
"""
Joins characters of ``phrase`` and if ``symbols`` is given, raises
an error if any character in ``phrase`` is not in ``symbols``.
Parameters
==========
phrase
String or list of strings to be returned as a string.
symbols
Iterable of characters allowed in ``phrase``.
If ``symbols`` is ``None``, no checking is performed.
Examples
========
>>> from sympy.crypto.crypto import check_and_join
>>> check_and_join('a phrase')
'a phrase'
>>> check_and_join('a phrase'.upper().split())
'APHRASE'
>>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True)
'ARAE'
>>> check_and_join('a phrase!'.upper().split(), 'ARE')
Traceback (most recent call last):
...
ValueError: characters in phrase but not symbols: "!HPS"
"""
rv = ''.join(''.join(phrase))
if symbols is not None:
symbols = check_and_join(symbols)
missing = ''.join(list(sorted(set(rv) - set(symbols))))
if missing:
if not filter:
raise ValueError(
'characters in phrase but not symbols: "%s"' % missing)
rv = translate(rv, None, missing)
return rv
def _prep(msg, key, alp, default=None):
if not alp:
if not default:
alp = AZ()
msg = AZ(msg)
key = AZ(key)
else:
alp = default
else:
alp = ''.join(alp)
key = check_and_join(key, alp, filter=True)
msg = check_and_join(msg, alp, filter=True)
return msg, key, alp
def cycle_list(k, n):
"""
Returns the elements of the list ``range(n)`` shifted to the
left by ``k`` (so the list starts with ``k`` (mod ``n``)).
Examples
========
>>> from sympy.crypto.crypto import cycle_list
>>> cycle_list(3, 10)
[3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
"""
k = k % n
return list(range(k, n)) + list(range(k))
######## shift cipher examples ############
def encipher_shift(msg, key, symbols=None):
"""
Performs shift cipher encryption on plaintext msg, and returns the
ciphertext.
Parameters
==========
key : int
The secret key.
msg : str
Plaintext of upper-case letters.
Returns
=======
str
Ciphertext of upper-case letters.
Examples
========
>>> from sympy.crypto.crypto import encipher_shift, decipher_shift
>>> msg = "GONAVYBEATARMY"
>>> ct = encipher_shift(msg, 1); ct
'HPOBWZCFBUBSNZ'
To decipher the shifted text, change the sign of the key:
>>> encipher_shift(ct, -1)
'GONAVYBEATARMY'
There is also a convenience function that does this with the
original key:
>>> decipher_shift(ct, 1)
'GONAVYBEATARMY'
Notes
=====
ALGORITHM:
STEPS:
0. Number the letters of the alphabet from 0, ..., N
1. Compute from the string ``msg`` a list ``L1`` of
corresponding integers.
2. Compute from the list ``L1`` a new list ``L2``, given by
adding ``(k mod 26)`` to each element in ``L1``.
3. Compute from the list ``L2`` a string ``ct`` of
corresponding letters.
The shift cipher is also called the Caesar cipher, after
Julius Caesar, who, according to Suetonius, used it with a
shift of three to protect messages of military significance.
Caesar's nephew Augustus reportedly used a similar cipher, but
with a right shift of 1.
References
==========
.. [1] https://en.wikipedia.org/wiki/Caesar_cipher
.. [2] http://mathworld.wolfram.com/CaesarsMethod.html
See Also
========
decipher_shift
"""
msg, _, A = _prep(msg, '', symbols)
shift = len(A) - key % len(A)
key = A[shift:] + A[:shift]
return translate(msg, key, A)
def decipher_shift(msg, key, symbols=None):
"""
Return the text by shifting the characters of ``msg`` to the
left by the amount given by ``key``.
Examples
========
>>> from sympy.crypto.crypto import encipher_shift, decipher_shift
>>> msg = "GONAVYBEATARMY"
>>> ct = encipher_shift(msg, 1); ct
'HPOBWZCFBUBSNZ'
To decipher the shifted text, change the sign of the key:
>>> encipher_shift(ct, -1)
'GONAVYBEATARMY'
Or use this function with the original key:
>>> decipher_shift(ct, 1)
'GONAVYBEATARMY'
"""
return encipher_shift(msg, -key, symbols)
def encipher_rot13(msg, symbols=None):
"""
Performs the ROT13 encryption on a given plaintext ``msg``.
Explanation
===========
ROT13 is a substitution cipher which substitutes each letter
in the plaintext message for the letter furthest away from it
in the English alphabet.
Equivalently, it is just a Caeser (shift) cipher with a shift
key of 13 (midway point of the alphabet).
References
==========
.. [1] https://en.wikipedia.org/wiki/ROT13
See Also
========
decipher_rot13
encipher_shift
"""
return encipher_shift(msg, 13, symbols)
def decipher_rot13(msg, symbols=None):
"""
Performs the ROT13 decryption on a given plaintext ``msg``.
Explanation
============
``decipher_rot13`` is equivalent to ``encipher_rot13`` as both
``decipher_shift`` with a key of 13 and ``encipher_shift`` key with a
key of 13 will return the same results. Nonetheless,
``decipher_rot13`` has nonetheless been explicitly defined here for
consistency.
Examples
========
>>> from sympy.crypto.crypto import encipher_rot13, decipher_rot13
>>> msg = 'GONAVYBEATARMY'
>>> ciphertext = encipher_rot13(msg);ciphertext
'TBANILORNGNEZL'
>>> decipher_rot13(ciphertext)
'GONAVYBEATARMY'
>>> encipher_rot13(msg) == decipher_rot13(msg)
True
>>> msg == decipher_rot13(ciphertext)
True
"""
return decipher_shift(msg, 13, symbols)
######## affine cipher examples ############
def encipher_affine(msg, key, symbols=None, _inverse=False):
r"""
Performs the affine cipher encryption on plaintext ``msg``, and
returns the ciphertext.
Explanation
===========
Encryption is based on the map `x \rightarrow ax+b` (mod `N`)
where ``N`` is the number of characters in the alphabet.
Decryption is based on the map `x \rightarrow cx+d` (mod `N`),
where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
In particular, for the map to be invertible, we need
`\mathrm{gcd}(a, N) = 1` and an error will be raised if this is
not true.
Parameters
==========
msg : str
Characters that appear in ``symbols``.
a, b : int, int
A pair integers, with ``gcd(a, N) = 1`` (the secret key).
symbols
String of characters (default = uppercase letters).
When no symbols are given, ``msg`` is converted to upper case
letters and all other characters are ignored.
Returns
=======
ct
String of characters (the ciphertext message)
Notes
=====
ALGORITHM:
STEPS:
0. Number the letters of the alphabet from 0, ..., N
1. Compute from the string ``msg`` a list ``L1`` of
corresponding integers.
2. Compute from the list ``L1`` a new list ``L2``, given by
replacing ``x`` by ``a*x + b (mod N)``, for each element
``x`` in ``L1``.
3. Compute from the list ``L2`` a string ``ct`` of
corresponding letters.
This is a straightforward generalization of the shift cipher with
the added complexity of requiring 2 characters to be deciphered in
order to recover the key.
References
==========
.. [1] https://en.wikipedia.org/wiki/Affine_cipher
See Also
========
decipher_affine
"""
msg, _, A = _prep(msg, '', symbols)
N = len(A)
a, b = key
assert gcd(a, N) == 1
if _inverse:
c = mod_inverse(a, N)
d = -b*c
a, b = c, d
B = ''.join([A[(a*i + b) % N] for i in range(N)])
return translate(msg, A, B)
def decipher_affine(msg, key, symbols=None):
r"""
Return the deciphered text that was made from the mapping,
`x \rightarrow ax+b` (mod `N`), where ``N`` is the
number of characters in the alphabet. Deciphering is done by
reciphering with a new key: `x \rightarrow cx+d` (mod `N`),
where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
Examples
========
>>> from sympy.crypto.crypto import encipher_affine, decipher_affine
>>> msg = "GO NAVY BEAT ARMY"
>>> key = (3, 1)
>>> encipher_affine(msg, key)
'TROBMVENBGBALV'
>>> decipher_affine(_, key)
'GONAVYBEATARMY'
See Also
========
encipher_affine
"""
return encipher_affine(msg, key, symbols, _inverse=True)
def encipher_atbash(msg, symbols=None):
r"""
Enciphers a given ``msg`` into its Atbash ciphertext and returns it.
Explanation
===========
Atbash is a substitution cipher originally used to encrypt the Hebrew
alphabet. Atbash works on the principle of mapping each alphabet to its
reverse / counterpart (i.e. a would map to z, b to y etc.)
Atbash is functionally equivalent to the affine cipher with ``a = 25``
and ``b = 25``
See Also
========
decipher_atbash
"""
return encipher_affine(msg, (25, 25), symbols)
def decipher_atbash(msg, symbols=None):
r"""
Deciphers a given ``msg`` using Atbash cipher and returns it.
Explanation
===========
``decipher_atbash`` is functionally equivalent to ``encipher_atbash``.
However, it has still been added as a separate function to maintain
consistency.
Examples
========
>>> from sympy.crypto.crypto import encipher_atbash, decipher_atbash
>>> msg = 'GONAVYBEATARMY'
>>> encipher_atbash(msg)
'TLMZEBYVZGZINB'
>>> decipher_atbash(msg)
'TLMZEBYVZGZINB'
>>> encipher_atbash(msg) == decipher_atbash(msg)
True
>>> msg == encipher_atbash(encipher_atbash(msg))
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Atbash
See Also
========
encipher_atbash
"""
return decipher_affine(msg, (25, 25), symbols)
#################### substitution cipher ###########################
def encipher_substitution(msg, old, new=None):
r"""
Returns the ciphertext obtained by replacing each character that
appears in ``old`` with the corresponding character in ``new``.
If ``old`` is a mapping, then new is ignored and the replacements
defined by ``old`` are used.
Explanation
===========
This is a more general than the affine cipher in that the key can
only be recovered by determining the mapping for each symbol.
Though in practice, once a few symbols are recognized the mappings
for other characters can be quickly guessed.
Examples
========
>>> from sympy.crypto.crypto import encipher_substitution, AZ
>>> old = 'OEYAG'
>>> new = '034^6'
>>> msg = AZ("go navy! beat army!")
>>> ct = encipher_substitution(msg, old, new); ct
'60N^V4B3^T^RM4'
To decrypt a substitution, reverse the last two arguments:
>>> encipher_substitution(ct, new, old)
'GONAVYBEATARMY'
In the special case where ``old`` and ``new`` are a permutation of
order 2 (representing a transposition of characters) their order
is immaterial:
>>> old = 'NAVY'
>>> new = 'ANYV'
>>> encipher = lambda x: encipher_substitution(x, old, new)
>>> encipher('NAVY')
'ANYV'
>>> encipher(_)
'NAVY'
The substitution cipher, in general, is a method
whereby "units" (not necessarily single characters) of plaintext
are replaced with ciphertext according to a regular system.
>>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc']))
>>> print(encipher_substitution('abc', ords))
\97\98\99
References
==========
.. [1] https://en.wikipedia.org/wiki/Substitution_cipher
"""
return translate(msg, old, new)
######################################################################
#################### Vigenere cipher examples ########################
######################################################################
def encipher_vigenere(msg, key, symbols=None):
"""
Performs the Vigenere cipher encryption on plaintext ``msg``, and
returns the ciphertext.
Examples
========
>>> from sympy.crypto.crypto import encipher_vigenere, AZ
>>> key = "encrypt"
>>> msg = "meet me on monday"
>>> encipher_vigenere(msg, key)
'QRGKKTHRZQEBPR'
Section 1 of the Kryptos sculpture at the CIA headquarters
uses this cipher and also changes the order of the
alphabet [2]_. Here is the first line of that section of
the sculpture:
>>> from sympy.crypto.crypto import decipher_vigenere, padded_key
>>> alp = padded_key('KRYPTOS', AZ())
>>> key = 'PALIMPSEST'
>>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ'
>>> decipher_vigenere(msg, key, alp)
'BETWEENSUBTLESHADINGANDTHEABSENC'
Explanation
===========
The Vigenere cipher is named after Blaise de Vigenere, a sixteenth
century diplomat and cryptographer, by a historical accident.
Vigenere actually invented a different and more complicated cipher.
The so-called *Vigenere cipher* was actually invented
by Giovan Batista Belaso in 1553.
This cipher was used in the 1800's, for example, during the American
Civil War. The Confederacy used a brass cipher disk to implement the
Vigenere cipher (now on display in the NSA Museum in Fort
Meade) [1]_.
The Vigenere cipher is a generalization of the shift cipher.
Whereas the shift cipher shifts each letter by the same amount
(that amount being the key of the shift cipher) the Vigenere
cipher shifts a letter by an amount determined by the key (which is
a word or phrase known only to the sender and receiver).
For example, if the key was a single letter, such as "C", then the
so-called Vigenere cipher is actually a shift cipher with a
shift of `2` (since "C" is the 2nd letter of the alphabet, if
you start counting at `0`). If the key was a word with two
letters, such as "CA", then the so-called Vigenere cipher will
shift letters in even positions by `2` and letters in odd positions
are left alone (shifted by `0`, since "A" is the 0th letter, if
you start counting at `0`).
ALGORITHM:
INPUT:
``msg``: string of characters that appear in ``symbols``
(the plaintext)
``key``: a string of characters that appear in ``symbols``
(the secret key)
``symbols``: a string of letters defining the alphabet
OUTPUT:
``ct``: string of characters (the ciphertext message)
STEPS:
0. Number the letters of the alphabet from 0, ..., N
1. Compute from the string ``key`` a list ``L1`` of
corresponding integers. Let ``n1 = len(L1)``.
2. Compute from the string ``msg`` a list ``L2`` of
corresponding integers. Let ``n2 = len(L2)``.
3. Break ``L2`` up sequentially into sublists of size
``n1``; the last sublist may be smaller than ``n1``
4. For each of these sublists ``L`` of ``L2``, compute a
new list ``C`` given by ``C[i] = L[i] + L1[i] (mod N)``
to the ``i``-th element in the sublist, for each ``i``.
5. Assemble these lists ``C`` by concatenation into a new
list of length ``n2``.
6. Compute from the new list a string ``ct`` of
corresponding letters.
Once it is known that the key is, say, `n` characters long,
frequency analysis can be applied to every `n`-th letter of
the ciphertext to determine the plaintext. This method is
called *Kasiski examination* (although it was first discovered
by Babbage). If they key is as long as the message and is
comprised of randomly selected characters -- a one-time pad -- the
message is theoretically unbreakable.
The cipher Vigenere actually discovered is an "auto-key" cipher
described as follows.
ALGORITHM:
INPUT:
``key``: a string of letters (the secret key)
``msg``: string of letters (the plaintext message)
OUTPUT:
``ct``: string of upper-case letters (the ciphertext message)
STEPS:
0. Number the letters of the alphabet from 0, ..., N
1. Compute from the string ``msg`` a list ``L2`` of
corresponding integers. Let ``n2 = len(L2)``.
2. Let ``n1`` be the length of the key. Append to the
string ``key`` the first ``n2 - n1`` characters of
the plaintext message. Compute from this string (also of
length ``n2``) a list ``L1`` of integers corresponding
to the letter numbers in the first step.
3. Compute a new list ``C`` given by
``C[i] = L1[i] + L2[i] (mod N)``.
4. Compute from the new list a string ``ct`` of letters
corresponding to the new integers.
To decipher the auto-key ciphertext, the key is used to decipher
the first ``n1`` characters and then those characters become the
key to decipher the next ``n1`` characters, etc...:
>>> m = AZ('go navy, beat army! yes you can'); m
'GONAVYBEATARMYYESYOUCAN'
>>> key = AZ('gold bug'); n1 = len(key); n2 = len(m)
>>> auto_key = key + m[:n2 - n1]; auto_key
'GOLDBUGGONAVYBEATARMYYE'
>>> ct = encipher_vigenere(m, auto_key); ct
'MCYDWSHKOGAMKZCELYFGAYR'
>>> n1 = len(key)
>>> pt = []
>>> while ct:
... part, ct = ct[:n1], ct[n1:]
... pt.append(decipher_vigenere(part, key))
... key = pt[-1]
...
>>> ''.join(pt) == m
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Vigenere_cipher
.. [2] http://web.archive.org/web/20071116100808/
.. [3] http://filebox.vt.edu/users/batman/kryptos.html
(short URL: https://goo.gl/ijr22d)
"""
msg, key, A = _prep(msg, key, symbols)
map = {c: i for i, c in enumerate(A)}
key = [map[c] for c in key]
N = len(map)
k = len(key)
rv = []
for i, m in enumerate(msg):
rv.append(A[(map[m] + key[i % k]) % N])
rv = ''.join(rv)
return rv
def decipher_vigenere(msg, key, symbols=None):
"""
Decode using the Vigenere cipher.
Examples
========
>>> from sympy.crypto.crypto import decipher_vigenere
>>> key = "encrypt"
>>> ct = "QRGK kt HRZQE BPR"
>>> decipher_vigenere(ct, key)
'MEETMEONMONDAY'
"""
msg, key, A = _prep(msg, key, symbols)
map = {c: i for i, c in enumerate(A)}
N = len(A) # normally, 26
K = [map[c] for c in key]
n = len(K)
C = [map[c] for c in msg]
rv = ''.join([A[(-K[i % n] + c) % N] for i, c in enumerate(C)])
return rv
#################### Hill cipher ########################
def encipher_hill(msg, key, symbols=None, pad="Q"):
r"""
Return the Hill cipher encryption of ``msg``.
Explanation
===========
The Hill cipher [1]_, invented by Lester S. Hill in the 1920's [2]_,
was the first polygraphic cipher in which it was practical
(though barely) to operate on more than three symbols at once.
The following discussion assumes an elementary knowledge of
matrices.
First, each letter is first encoded as a number starting with 0.
Suppose your message `msg` consists of `n` capital letters, with no
spaces. This may be regarded an `n`-tuple M of elements of
`Z_{26}` (if the letters are those of the English alphabet). A key
in the Hill cipher is a `k x k` matrix `K`, all of whose entries
are in `Z_{26}`, such that the matrix `K` is invertible (i.e., the
linear transformation `K: Z_{N}^k \rightarrow Z_{N}^k`
is one-to-one).
Parameters
==========
msg
Plaintext message of `n` upper-case letters.
key
A `k \times k` invertible matrix `K`, all of whose entries are
in `Z_{26}` (or whatever number of symbols are being used).
pad
Character (default "Q") to use to make length of text be a
multiple of ``k``.
Returns
=======
ct
Ciphertext of upper-case letters.
Notes
=====
ALGORITHM:
STEPS:
0. Number the letters of the alphabet from 0, ..., N
1. Compute from the string ``msg`` a list ``L`` of
corresponding integers. Let ``n = len(L)``.
2. Break the list ``L`` up into ``t = ceiling(n/k)``
sublists ``L_1``, ..., ``L_t`` of size ``k`` (with
the last list "padded" to ensure its size is
``k``).
3. Compute new list ``C_1``, ..., ``C_t`` given by
``C[i] = K*L_i`` (arithmetic is done mod N), for each
``i``.
4. Concatenate these into a list ``C = C_1 + ... + C_t``.
5. Compute from ``C`` a string ``ct`` of corresponding
letters. This has length ``k*t``.
References
==========
.. [1] https://en.wikipedia.org/wiki/Hill_cipher
.. [2] Lester S. Hill, Cryptography in an Algebraic Alphabet,
The American Mathematical Monthly Vol.36, June-July 1929,
pp.306-312.
See Also
========
decipher_hill
"""
assert key.is_square
assert len(pad) == 1
msg, pad, A = _prep(msg, pad, symbols)
map = {c: i for i, c in enumerate(A)}
P = [map[c] for c in msg]
N = len(A)
k = key.cols
n = len(P)
m, r = divmod(n, k)
if r:
P = P + [map[pad]]*(k - r)
m += 1
rv = ''.join([A[c % N] for j in range(m) for c in
list(key*Matrix(k, 1, [P[i]
for i in range(k*j, k*(j + 1))]))])
return rv
def decipher_hill(msg, key, symbols=None):
"""
Deciphering is the same as enciphering but using the inverse of the
key matrix.
Examples
========
>>> from sympy.crypto.crypto import encipher_hill, decipher_hill
>>> from sympy import Matrix
>>> key = Matrix([[1, 2], [3, 5]])
>>> encipher_hill("meet me on monday", key)
'UEQDUEODOCTCWQ'
>>> decipher_hill(_, key)
'MEETMEONMONDAY'
When the length of the plaintext (stripped of invalid characters)
is not a multiple of the key dimension, extra characters will
appear at the end of the enciphered and deciphered text. In order to
decipher the text, those characters must be included in the text to
be deciphered. In the following, the key has a dimension of 4 but
the text is 2 short of being a multiple of 4 so two characters will
be added.
>>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0],
... [2, 2, 3, 4], [1, 1, 0, 1]])
>>> msg = "ST"
>>> encipher_hill(msg, key)
'HJEB'
>>> decipher_hill(_, key)
'STQQ'
>>> encipher_hill(msg, key, pad="Z")
'ISPK'
>>> decipher_hill(_, key)
'STZZ'
If the last two characters of the ciphertext were ignored in
either case, the wrong plaintext would be recovered:
>>> decipher_hill("HD", key)
'ORMV'
>>> decipher_hill("IS", key)
'UIKY'
See Also
========
encipher_hill
"""
assert key.is_square
msg, _, A = _prep(msg, '', symbols)
map = {c: i for i, c in enumerate(A)}
C = [map[c] for c in msg]
N = len(A)
k = key.cols
n = len(C)
m, r = divmod(n, k)
if r:
C = C + [0]*(k - r)
m += 1
key_inv = key.inv_mod(N)
rv = ''.join([A[p % N] for j in range(m) for p in
list(key_inv*Matrix(
k, 1, [C[i] for i in range(k*j, k*(j + 1))]))])
return rv
#################### Bifid cipher ########################
def encipher_bifid(msg, key, symbols=None):
r"""
Performs the Bifid cipher encryption on plaintext ``msg``, and
returns the ciphertext.
This is the version of the Bifid cipher that uses an `n \times n`
Polybius square.
Parameters
==========
msg
Plaintext string.
key
Short string for key.
Duplicate characters are ignored and then it is padded with the
characters in ``symbols`` that were not in the short key.
symbols
`n \times n` characters defining the alphabet.
(default is string.printable)
Returns
=======
ciphertext
Ciphertext using Bifid5 cipher without spaces.
See Also
========
decipher_bifid, encipher_bifid5, encipher_bifid6
References
==========
.. [1] https://en.wikipedia.org/wiki/Bifid_cipher
"""
msg, key, A = _prep(msg, key, symbols, bifid10)
long_key = ''.join(uniq(key)) or A
n = len(A)**.5
if n != int(n):
raise ValueError(
'Length of alphabet (%s) is not a square number.' % len(A))
N = int(n)
if len(long_key) < N**2:
long_key = list(long_key) + [x for x in A if x not in long_key]
# the fractionalization
row_col = {ch: divmod(i, N) for i, ch in enumerate(long_key)}
r, c = zip(*[row_col[x] for x in msg])
rc = r + c
ch = {i: ch for ch, i in row_col.items()}
rv = ''.join(ch[i] for i in zip(rc[::2], rc[1::2]))
return rv
def decipher_bifid(msg, key, symbols=None):
r"""
Performs the Bifid cipher decryption on ciphertext ``msg``, and
returns the plaintext.
This is the version of the Bifid cipher that uses the `n \times n`
Polybius square.
Parameters
==========
msg
Ciphertext string.
key
Short string for key.
Duplicate characters are ignored and then it is padded with the
characters in symbols that were not in the short key.
symbols
`n \times n` characters defining the alphabet.
(default=string.printable, a `10 \times 10` matrix)
Returns
=======
deciphered
Deciphered text.
Examples
========
>>> from sympy.crypto.crypto import (
... encipher_bifid, decipher_bifid, AZ)
Do an encryption using the bifid5 alphabet:
>>> alp = AZ().replace('J', '')
>>> ct = AZ("meet me on monday!")
>>> key = AZ("gold bug")
>>> encipher_bifid(ct, key, alp)
'IEILHHFSTSFQYE'
When entering the text or ciphertext, spaces are ignored so it
can be formatted as desired. Re-entering the ciphertext from the
preceding, putting 4 characters per line and padding with an extra
J, does not cause problems for the deciphering:
>>> decipher_bifid('''
... IEILH
... HFSTS
... FQYEJ''', key, alp)
'MEETMEONMONDAY'
When no alphabet is given, all 100 printable characters will be
used:
>>> key = ''
>>> encipher_bifid('hello world!', key)
'bmtwmg-bIo*w'
>>> decipher_bifid(_, key)
'hello world!'
If the key is changed, a different encryption is obtained:
>>> key = 'gold bug'
>>> encipher_bifid('hello world!', 'gold_bug')
'hg2sfuei7t}w'
And if the key used to decrypt the message is not exact, the
original text will not be perfectly obtained:
>>> decipher_bifid(_, 'gold pug')
'heldo~wor6d!'
"""
msg, _, A = _prep(msg, '', symbols, bifid10)
long_key = ''.join(uniq(key)) or A
n = len(A)**.5
if n != int(n):
raise ValueError(
'Length of alphabet (%s) is not a square number.' % len(A))
N = int(n)
if len(long_key) < N**2:
long_key = list(long_key) + [x for x in A if x not in long_key]
# the reverse fractionalization
row_col = {
ch: divmod(i, N) for i, ch in enumerate(long_key)}
rc = [i for c in msg for i in row_col[c]]
n = len(msg)
rc = zip(*(rc[:n], rc[n:]))
ch = {i: ch for ch, i in row_col.items()}
rv = ''.join(ch[i] for i in rc)
return rv
def bifid_square(key):
"""Return characters of ``key`` arranged in a square.
Examples
========
>>> from sympy.crypto.crypto import (
... bifid_square, AZ, padded_key, bifid5)
>>> bifid_square(AZ().replace('J', ''))
Matrix([
[A, B, C, D, E],
[F, G, H, I, K],
[L, M, N, O, P],
[Q, R, S, T, U],
[V, W, X, Y, Z]])
>>> bifid_square(padded_key(AZ('gold bug!'), bifid5))
Matrix([
[G, O, L, D, B],
[U, A, C, E, F],
[H, I, K, M, N],
[P, Q, R, S, T],
[V, W, X, Y, Z]])
See Also
========
padded_key
"""
A = ''.join(uniq(''.join(key)))
n = len(A)**.5
if n != int(n):
raise ValueError(
'Length of alphabet (%s) is not a square number.' % len(A))
n = int(n)
f = lambda i, j: Symbol(A[n*i + j])
rv = Matrix(n, n, f)
return rv
def encipher_bifid5(msg, key):
r"""
Performs the Bifid cipher encryption on plaintext ``msg``, and
returns the ciphertext.
Explanation
===========
This is the version of the Bifid cipher that uses the `5 \times 5`
Polybius square. The letter "J" is ignored so it must be replaced
with something else (traditionally an "I") before encryption.
ALGORITHM: (5x5 case)
STEPS:
0. Create the `5 \times 5` Polybius square ``S`` associated
to ``key`` as follows:
a) moving from left-to-right, top-to-bottom,
place the letters of the key into a `5 \times 5`
matrix,
b) if the key has less than 25 letters, add the
letters of the alphabet not in the key until the
`5 \times 5` square is filled.
1. Create a list ``P`` of pairs of numbers which are the
coordinates in the Polybius square of the letters in
``msg``.
2. Let ``L1`` be the list of all first coordinates of ``P``
(length of ``L1 = n``), let ``L2`` be the list of all
second coordinates of ``P`` (so the length of ``L2``
is also ``n``).
3. Let ``L`` be the concatenation of ``L1`` and ``L2``
(length ``L = 2*n``), except that consecutive numbers
are paired ``(L[2*i], L[2*i + 1])``. You can regard
``L`` as a list of pairs of length ``n``.
4. Let ``C`` be the list of all letters which are of the
form ``S[i, j]``, for all ``(i, j)`` in ``L``. As a
string, this is the ciphertext of ``msg``.
Parameters
==========
msg : str
Plaintext string.
Converted to upper case and filtered of anything but all letters
except J.
key
Short string for key; non-alphabetic letters, J and duplicated
characters are ignored and then, if the length is less than 25
characters, it is padded with other letters of the alphabet
(in alphabetical order).
Returns
=======
ct
Ciphertext (all caps, no spaces).
Examples
========
>>> from sympy.crypto.crypto import (
... encipher_bifid5, decipher_bifid5)
"J" will be omitted unless it is replaced with something else:
>>> round_trip = lambda m, k: \
... decipher_bifid5(encipher_bifid5(m, k), k)
>>> key = 'a'
>>> msg = "JOSIE"
>>> round_trip(msg, key)
'OSIE'
>>> round_trip(msg.replace("J", "I"), key)
'IOSIE'
>>> j = "QIQ"
>>> round_trip(msg.replace("J", j), key).replace(j, "J")
'JOSIE'
Notes
=====
The Bifid cipher was invented around 1901 by Felix Delastelle.
It is a *fractional substitution* cipher, where letters are
replaced by pairs of symbols from a smaller alphabet. The
cipher uses a `5 \times 5` square filled with some ordering of the
alphabet, except that "J" is replaced with "I" (this is a so-called
Polybius square; there is a `6 \times 6` analog if you add back in
"J" and also append onto the usual 26 letter alphabet, the digits
0, 1, ..., 9).
According to Helen Gaines' book *Cryptanalysis*, this type of cipher
was used in the field by the German Army during World War I.
See Also
========
decipher_bifid5, encipher_bifid
"""
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
key = padded_key(key, bifid5)
return encipher_bifid(msg, '', key)
def decipher_bifid5(msg, key):
r"""
Return the Bifid cipher decryption of ``msg``.
Explanation
===========
This is the version of the Bifid cipher that uses the `5 \times 5`
Polybius square; the letter "J" is ignored unless a ``key`` of
length 25 is used.
Parameters
==========
msg
Ciphertext string.
key
Short string for key; duplicated characters are ignored and if
the length is less then 25 characters, it will be padded with
other letters from the alphabet omitting "J".
Non-alphabetic characters are ignored.
Returns
=======
plaintext
Plaintext from Bifid5 cipher (all caps, no spaces).
Examples
========
>>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5
>>> key = "gold bug"
>>> encipher_bifid5('meet me on friday', key)
'IEILEHFSTSFXEE'
>>> encipher_bifid5('meet me on monday', key)
'IEILHHFSTSFQYE'
>>> decipher_bifid5(_, key)
'MEETMEONMONDAY'
"""
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
key = padded_key(key, bifid5)
return decipher_bifid(msg, '', key)
def bifid5_square(key=None):
r"""
5x5 Polybius square.
Produce the Polybius square for the `5 \times 5` Bifid cipher.
Examples
========
>>> from sympy.crypto.crypto import bifid5_square
>>> bifid5_square("gold bug")
Matrix([
[G, O, L, D, B],
[U, A, C, E, F],
[H, I, K, M, N],
[P, Q, R, S, T],
[V, W, X, Y, Z]])
"""
if not key:
key = bifid5
else:
_, key, _ = _prep('', key.upper(), None, bifid5)
key = padded_key(key, bifid5)
return bifid_square(key)
def encipher_bifid6(msg, key):
r"""
Performs the Bifid cipher encryption on plaintext ``msg``, and
returns the ciphertext.
This is the version of the Bifid cipher that uses the `6 \times 6`
Polybius square.
Parameters
==========
msg
Plaintext string (digits okay).
key
Short string for key (digits okay).
If ``key`` is less than 36 characters long, the square will be
filled with letters A through Z and digits 0 through 9.
Returns
=======
ciphertext
Ciphertext from Bifid cipher (all caps, no spaces).
See Also
========
decipher_bifid6, encipher_bifid
"""
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
key = padded_key(key, bifid6)
return encipher_bifid(msg, '', key)
def decipher_bifid6(msg, key):
r"""
Performs the Bifid cipher decryption on ciphertext ``msg``, and
returns the plaintext.
This is the version of the Bifid cipher that uses the `6 \times 6`
Polybius square.
Parameters
==========
msg
Ciphertext string (digits okay); converted to upper case
key
Short string for key (digits okay).
If ``key`` is less than 36 characters long, the square will be
filled with letters A through Z and digits 0 through 9.
All letters are converted to uppercase.
Returns
=======
plaintext
Plaintext from Bifid cipher (all caps, no spaces).
Examples
========
>>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6
>>> key = "gold bug"
>>> encipher_bifid6('meet me on monday at 8am', key)
'KFKLJJHF5MMMKTFRGPL'
>>> decipher_bifid6(_, key)
'MEETMEONMONDAYAT8AM'
"""
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
key = padded_key(key, bifid6)
return decipher_bifid(msg, '', key)
def bifid6_square(key=None):
r"""
6x6 Polybius square.
Produces the Polybius square for the `6 \times 6` Bifid cipher.
Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9".
Examples
========
>>> from sympy.crypto.crypto import bifid6_square
>>> key = "gold bug"
>>> bifid6_square(key)
Matrix([
[G, O, L, D, B, U],
[A, C, E, F, H, I],
[J, K, M, N, P, Q],
[R, S, T, V, W, X],
[Y, Z, 0, 1, 2, 3],
[4, 5, 6, 7, 8, 9]])
"""
if not key:
key = bifid6
else:
_, key, _ = _prep('', key.upper(), None, bifid6)
key = padded_key(key, bifid6)
return bifid_square(key)
#################### RSA #############################
def _decipher_rsa_crt(i, d, factors):
"""Decipher RSA using chinese remainder theorem from the information
of the relatively-prime factors of the modulus.
Parameters
==========
i : integer
Ciphertext
d : integer
The exponent component.
factors : list of relatively-prime integers
The integers given must be coprime and the product must equal
the modulus component of the original RSA key.
Examples
========
How to decrypt RSA with CRT:
>>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
>>> primes = [61, 53]
>>> e = 17
>>> args = primes + [e]
>>> puk = rsa_public_key(*args)
>>> prk = rsa_private_key(*args)
>>> from sympy.crypto.crypto import encipher_rsa, _decipher_rsa_crt
>>> msg = 65
>>> crt_primes = primes
>>> encrypted = encipher_rsa(msg, puk)
>>> decrypted = _decipher_rsa_crt(encrypted, prk[1], primes)
>>> decrypted
65
"""
moduluses = [pow(i, d, p) for p in factors]
result = crt(factors, moduluses)
if not result:
raise ValueError("CRT failed")
return result[0]
def _rsa_key(*args, public=True, private=True, totient='Euler', index=None, multipower=None):
r"""A private subroutine to generate RSA key
Parameters
==========
public, private : bool, optional
Flag to generate either a public key, a private key.
totient : 'Euler' or 'Carmichael'
Different notation used for totient.
multipower : bool, optional
Flag to bypass warning for multipower RSA.
"""
if len(args) < 2:
return False
if totient not in ('Euler', 'Carmichael'):
raise ValueError(
"The argument totient={} should either be " \
"'Euler', 'Carmichalel'." \
.format(totient))
if totient == 'Euler':
_totient = _euler
else:
_totient = _carmichael
if index is not None:
index = as_int(index)
if totient != 'Carmichael':
raise ValueError(
"Setting the 'index' keyword argument requires totient"
"notation to be specified as 'Carmichael'.")
primes, e = args[:-1], args[-1]
if not all(isprime(p) for p in primes):
new_primes = []
for i in primes:
new_primes.extend(factorint(i, multiple=True))
primes = new_primes
n = reduce(lambda i, j: i*j, primes)
tally = multiset(primes)
if all(v == 1 for v in tally.values()):
multiple = list(tally.keys())
phi = _totient._from_distinct_primes(*multiple)
else:
if not multipower:
NonInvertibleCipherWarning(
'Non-distinctive primes found in the factors {}. '
'The cipher may not be decryptable for some numbers '
'in the complete residue system Z[{}], but the cipher '
'can still be valid if you restrict the domain to be '
'the reduced residue system Z*[{}]. You can pass '
'the flag multipower=True if you want to suppress this '
'warning.'
.format(primes, n, n)
# stacklevel=4 because most users will call a function that
# calls this function
).warn(stacklevel=4)
phi = _totient._from_factors(tally)
if igcd(e, phi) == 1:
if public and not private:
if isinstance(index, int):
e = e % phi
e += index * phi
return n, e
if private and not public:
d = mod_inverse(e, phi)
if isinstance(index, int):
d += index * phi
return n, d
return False
def rsa_public_key(*args, **kwargs):
r"""Return the RSA *public key* pair, `(n, e)`
Parameters
==========
args : naturals
If specified as `p, q, e` where `p` and `q` are distinct primes
and `e` is a desired public exponent of the RSA, `n = p q` and
`e` will be verified against the totient
`\phi(n)` (Euler totient) or `\lambda(n)` (Carmichael totient)
to be `\gcd(e, \phi(n)) = 1` or `\gcd(e, \lambda(n)) = 1`.
If specified as `p_1, p_2, \dots, p_n, e` where
`p_1, p_2, \dots, p_n` are specified as primes,
and `e` is specified as a desired public exponent of the RSA,
it will be able to form a multi-prime RSA, which is a more
generalized form of the popular 2-prime RSA.
It can also be possible to form a single-prime RSA by specifying
the argument as `p, e`, which can be considered a trivial case
of a multiprime RSA.
Furthermore, it can be possible to form a multi-power RSA by
specifying two or more pairs of the primes to be same.
However, unlike the two-distinct prime RSA or multi-prime
RSA, not every numbers in the complete residue system
(`\mathbb{Z}_n`) will be decryptable since the mapping
`\mathbb{Z}_{n} \rightarrow \mathbb{Z}_{n}`
will not be bijective.
(Only except for the trivial case when
`e = 1`
or more generally,
.. math::
e \in \left \{ 1 + k \lambda(n)
\mid k \in \mathbb{Z} \land k \geq 0 \right \}
when RSA reduces to the identity.)
However, the RSA can still be decryptable for the numbers in the
reduced residue system (`\mathbb{Z}_n^{\times}`), since the
mapping
`\mathbb{Z}_{n}^{\times} \rightarrow \mathbb{Z}_{n}^{\times}`
can still be bijective.
If you pass a non-prime integer to the arguments
`p_1, p_2, \dots, p_n`, the particular number will be
prime-factored and it will become either a multi-prime RSA or a
multi-power RSA in its canonical form, depending on whether the
product equals its radical or not.
`p_1 p_2 \dots p_n = \text{rad}(p_1 p_2 \dots p_n)`
totient : bool, optional
If ``'Euler'``, it uses Euler's totient `\phi(n)` which is
:meth:`sympy.ntheory.factor_.totient` in SymPy.
If ``'Carmichael'``, it uses Carmichael's totient `\lambda(n)`
which is :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy.
Unlike private key generation, this is a trivial keyword for
public key generation because
`\gcd(e, \phi(n)) = 1 \iff \gcd(e, \lambda(n)) = 1`.
index : nonnegative integer, optional
Returns an arbitrary solution of a RSA public key at the index
specified at `0, 1, 2, \dots`. This parameter needs to be
specified along with ``totient='Carmichael'``.
Similarly to the non-uniquenss of a RSA private key as described
in the ``index`` parameter documentation in
:meth:`rsa_private_key`, RSA public key is also not unique and
there is an infinite number of RSA public exponents which
can behave in the same manner.
From any given RSA public exponent `e`, there are can be an
another RSA public exponent `e + k \lambda(n)` where `k` is an
integer, `\lambda` is a Carmichael's totient function.
However, considering only the positive cases, there can be
a principal solution of a RSA public exponent `e_0` in
`0 < e_0 < \lambda(n)`, and all the other solutions
can be canonicalzed in a form of `e_0 + k \lambda(n)`.
``index`` specifies the `k` notation to yield any possible value
an RSA public key can have.
An example of computing any arbitrary RSA public key:
>>> from sympy.crypto.crypto import rsa_public_key
>>> rsa_public_key(61, 53, 17, totient='Carmichael', index=0)
(3233, 17)
>>> rsa_public_key(61, 53, 17, totient='Carmichael', index=1)
(3233, 797)
>>> rsa_public_key(61, 53, 17, totient='Carmichael', index=2)
(3233, 1577)
multipower : bool, optional
Any pair of non-distinct primes found in the RSA specification
will restrict the domain of the cryptosystem, as noted in the
explanation of the parameter ``args``.
SymPy RSA key generator may give a warning before dispatching it
as a multi-power RSA, however, you can disable the warning if
you pass ``True`` to this keyword.
Returns
=======
(n, e) : int, int
`n` is a product of any arbitrary number of primes given as
the argument.
`e` is relatively prime (coprime) to the Euler totient
`\phi(n)`.
False
Returned if less than two arguments are given, or `e` is
not relatively prime to the modulus.
Examples
========
>>> from sympy.crypto.crypto import rsa_public_key
A public key of a two-prime RSA:
>>> p, q, e = 3, 5, 7
>>> rsa_public_key(p, q, e)
(15, 7)
>>> rsa_public_key(p, q, 30)
False
A public key of a multiprime RSA:
>>> primes = [2, 3, 5, 7, 11, 13]
>>> e = 7
>>> args = primes + [e]
>>> rsa_public_key(*args)
(30030, 7)
Notes
=====
Although the RSA can be generalized over any modulus `n`, using
two large primes had became the most popular specification because a
product of two large primes is usually the hardest to factor
relatively to the digits of `n` can have.
However, it may need further understanding of the time complexities
of each prime-factoring algorithms to verify the claim.
See Also
========
rsa_private_key
encipher_rsa
decipher_rsa
References
==========
.. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
.. [2] http://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
.. [3] https://link.springer.com/content/pdf/10.1007%2FBFb0055738.pdf
.. [4] http://www.itiis.org/digital-library/manuscript/1381
"""
return _rsa_key(*args, public=True, private=False, **kwargs)
def rsa_private_key(*args, **kwargs):
r"""Return the RSA *private key* pair, `(n, d)`
Parameters
==========
args : naturals
The keyword is identical to the ``args`` in
:meth:`rsa_public_key`.
totient : bool, optional
If ``'Euler'``, it uses Euler's totient convention `\phi(n)`
which is :meth:`sympy.ntheory.factor_.totient` in SymPy.
If ``'Carmichael'``, it uses Carmichael's totient convention
`\lambda(n)` which is
:meth:`sympy.ntheory.factor_.reduced_totient` in SymPy.
There can be some output differences for private key generation
as examples below.
Example using Euler's totient:
>>> from sympy.crypto.crypto import rsa_private_key
>>> rsa_private_key(61, 53, 17, totient='Euler')
(3233, 2753)
Example using Carmichael's totient:
>>> from sympy.crypto.crypto import rsa_private_key
>>> rsa_private_key(61, 53, 17, totient='Carmichael')
(3233, 413)
index : nonnegative integer, optional
Returns an arbitrary solution of a RSA private key at the index
specified at `0, 1, 2, \dots`. This parameter needs to be
specified along with ``totient='Carmichael'``.
RSA private exponent is a non-unique solution of
`e d \mod \lambda(n) = 1` and it is possible in any form of
`d + k \lambda(n)`, where `d` is an another
already-computed private exponent, and `\lambda` is a
Carmichael's totient function, and `k` is any integer.
However, considering only the positive cases, there can be
a principal solution of a RSA private exponent `d_0` in
`0 < d_0 < \lambda(n)`, and all the other solutions
can be canonicalzed in a form of `d_0 + k \lambda(n)`.
``index`` specifies the `k` notation to yield any possible value
an RSA private key can have.
An example of computing any arbitrary RSA private key:
>>> from sympy.crypto.crypto import rsa_private_key
>>> rsa_private_key(61, 53, 17, totient='Carmichael', index=0)
(3233, 413)
>>> rsa_private_key(61, 53, 17, totient='Carmichael', index=1)
(3233, 1193)
>>> rsa_private_key(61, 53, 17, totient='Carmichael', index=2)
(3233, 1973)
multipower : bool, optional
The keyword is identical to the ``multipower`` in
:meth:`rsa_public_key`.
Returns
=======
(n, d) : int, int
`n` is a product of any arbitrary number of primes given as
the argument.
`d` is the inverse of `e` (mod `\phi(n)`) where `e` is the
exponent given, and `\phi` is a Euler totient.
False
Returned if less than two arguments are given, or `e` is
not relatively prime to the totient of the modulus.
Examples
========
>>> from sympy.crypto.crypto import rsa_private_key
A private key of a two-prime RSA:
>>> p, q, e = 3, 5, 7
>>> rsa_private_key(p, q, e)
(15, 7)
>>> rsa_private_key(p, q, 30)
False
A private key of a multiprime RSA:
>>> primes = [2, 3, 5, 7, 11, 13]
>>> e = 7
>>> args = primes + [e]
>>> rsa_private_key(*args)
(30030, 823)
See Also
========
rsa_public_key
encipher_rsa
decipher_rsa
References
==========
.. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
.. [2] http://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
.. [3] https://link.springer.com/content/pdf/10.1007%2FBFb0055738.pdf
.. [4] http://www.itiis.org/digital-library/manuscript/1381
"""
return _rsa_key(*args, public=False, private=True, **kwargs)
def _encipher_decipher_rsa(i, key, factors=None):
n, d = key
if not factors:
return pow(i, d, n)
def _is_coprime_set(l):
is_coprime_set = True
for i in range(len(l)):
for j in range(i+1, len(l)):
if igcd(l[i], l[j]) != 1:
is_coprime_set = False
break
return is_coprime_set
prod = reduce(lambda i, j: i*j, factors)
if prod == n and _is_coprime_set(factors):
return _decipher_rsa_crt(i, d, factors)
return _encipher_decipher_rsa(i, key, factors=None)
def encipher_rsa(i, key, factors=None):
r"""Encrypt the plaintext with RSA.
Parameters
==========
i : integer
The plaintext to be encrypted for.
key : (n, e) where n, e are integers
`n` is the modulus of the key and `e` is the exponent of the
key. The encryption is computed by `i^e \bmod n`.
The key can either be a public key or a private key, however,
the message encrypted by a public key can only be decrypted by
a private key, and vice versa, as RSA is an asymmetric
cryptography system.
factors : list of coprime integers
This is identical to the keyword ``factors`` in
:meth:`decipher_rsa`.
Notes
=====
Some specifications may make the RSA not cryptographically
meaningful.
For example, `0`, `1` will remain always same after taking any
number of exponentiation, thus, should be avoided.
Furthermore, if `i^e < n`, `i` may easily be figured out by taking
`e` th root.
And also, specifying the exponent as `1` or in more generalized form
as `1 + k \lambda(n)` where `k` is an nonnegative integer,
`\lambda` is a carmichael totient, the RSA becomes an identity
mapping.
Examples
========
>>> from sympy.crypto.crypto import encipher_rsa
>>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
Public Key Encryption:
>>> p, q, e = 3, 5, 7
>>> puk = rsa_public_key(p, q, e)
>>> msg = 12
>>> encipher_rsa(msg, puk)
3
Private Key Encryption:
>>> p, q, e = 3, 5, 7
>>> prk = rsa_private_key(p, q, e)
>>> msg = 12
>>> encipher_rsa(msg, prk)
3
Encryption using chinese remainder theorem:
>>> encipher_rsa(msg, prk, factors=[p, q])
3
"""
return _encipher_decipher_rsa(i, key, factors=factors)
def decipher_rsa(i, key, factors=None):
r"""Decrypt the ciphertext with RSA.
Parameters
==========
i : integer
The ciphertext to be decrypted for.
key : (n, d) where n, d are integers
`n` is the modulus of the key and `d` is the exponent of the
key. The decryption is computed by `i^d \bmod n`.
The key can either be a public key or a private key, however,
the message encrypted by a public key can only be decrypted by
a private key, and vice versa, as RSA is an asymmetric
cryptography system.
factors : list of coprime integers
As the modulus `n` created from RSA key generation is composed
of arbitrary prime factors
`n = {p_1}^{k_1}{p_2}^{k_2}\dots{p_n}^{k_n}` where
`p_1, p_2, \dots, p_n` are distinct primes and
`k_1, k_2, \dots, k_n` are positive integers, chinese remainder
theorem can be used to compute `i^d \bmod n` from the
fragmented modulo operations like
.. math::
i^d \bmod {p_1}^{k_1}, i^d \bmod {p_2}^{k_2}, \dots,
i^d \bmod {p_n}^{k_n}
or like
.. math::
i^d \bmod {p_1}^{k_1}{p_2}^{k_2},
i^d \bmod {p_3}^{k_3}, \dots ,
i^d \bmod {p_n}^{k_n}
as long as every moduli does not share any common divisor each
other.
The raw primes used in generating the RSA key pair can be a good
option.
Note that the speed advantage of using this is only viable for
very large cases (Like 2048-bit RSA keys) since the
overhead of using pure Python implementation of
:meth:`sympy.ntheory.modular.crt` may overcompensate the
theoritical speed advantage.
Notes
=====
See the ``Notes`` section in the documentation of
:meth:`encipher_rsa`
Examples
========
>>> from sympy.crypto.crypto import decipher_rsa, encipher_rsa
>>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
Public Key Encryption and Decryption:
>>> p, q, e = 3, 5, 7
>>> prk = rsa_private_key(p, q, e)
>>> puk = rsa_public_key(p, q, e)
>>> msg = 12
>>> new_msg = encipher_rsa(msg, prk)
>>> new_msg
3
>>> decipher_rsa(new_msg, puk)
12
Private Key Encryption and Decryption:
>>> p, q, e = 3, 5, 7
>>> prk = rsa_private_key(p, q, e)
>>> puk = rsa_public_key(p, q, e)
>>> msg = 12
>>> new_msg = encipher_rsa(msg, puk)
>>> new_msg
3
>>> decipher_rsa(new_msg, prk)
12
Decryption using chinese remainder theorem:
>>> decipher_rsa(new_msg, prk, factors=[p, q])
12
See Also
========
encipher_rsa
"""
return _encipher_decipher_rsa(i, key, factors=factors)
#################### kid krypto (kid RSA) #############################
def kid_rsa_public_key(a, b, A, B):
r"""
Kid RSA is a version of RSA useful to teach grade school children
since it does not involve exponentiation.
Explanation
===========
Alice wants to talk to Bob. Bob generates keys as follows.
Key generation:
* Select positive integers `a, b, A, B` at random.
* Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
`n = (e d - 1)//M`.
* The *public key* is `(n, e)`. Bob sends these to Alice.
* The *private key* is `(n, d)`, which Bob keeps secret.
Encryption: If `p` is the plaintext message then the
ciphertext is `c = p e \pmod n`.
Decryption: If `c` is the ciphertext message then the
plaintext is `p = c d \pmod n`.
Examples
========
>>> from sympy.crypto.crypto import kid_rsa_public_key
>>> a, b, A, B = 3, 4, 5, 6
>>> kid_rsa_public_key(a, b, A, B)
(369, 58)
"""
M = a*b - 1
e = A*M + a
d = B*M + b
n = (e*d - 1)//M
return n, e
def kid_rsa_private_key(a, b, A, B):
"""
Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
`n = (e d - 1) / M`. The *private key* is `d`, which Bob
keeps secret.
Examples
========
>>> from sympy.crypto.crypto import kid_rsa_private_key
>>> a, b, A, B = 3, 4, 5, 6
>>> kid_rsa_private_key(a, b, A, B)
(369, 70)
"""
M = a*b - 1
e = A*M + a
d = B*M + b
n = (e*d - 1)//M
return n, d
def encipher_kid_rsa(msg, key):
"""
Here ``msg`` is the plaintext and ``key`` is the public key.
Examples
========
>>> from sympy.crypto.crypto import (
... encipher_kid_rsa, kid_rsa_public_key)
>>> msg = 200
>>> a, b, A, B = 3, 4, 5, 6
>>> key = kid_rsa_public_key(a, b, A, B)
>>> encipher_kid_rsa(msg, key)
161
"""
n, e = key
return (msg*e) % n
def decipher_kid_rsa(msg, key):
"""
Here ``msg`` is the plaintext and ``key`` is the private key.
Examples
========
>>> from sympy.crypto.crypto import (
... kid_rsa_public_key, kid_rsa_private_key,
... decipher_kid_rsa, encipher_kid_rsa)
>>> a, b, A, B = 3, 4, 5, 6
>>> d = kid_rsa_private_key(a, b, A, B)
>>> msg = 200
>>> pub = kid_rsa_public_key(a, b, A, B)
>>> pri = kid_rsa_private_key(a, b, A, B)
>>> ct = encipher_kid_rsa(msg, pub)
>>> decipher_kid_rsa(ct, pri)
200
"""
n, d = key
return (msg*d) % n
#################### Morse Code ######################################
morse_char = {
".-": "A", "-...": "B",
"-.-.": "C", "-..": "D",
".": "E", "..-.": "F",
"--.": "G", "....": "H",
"..": "I", ".---": "J",
"-.-": "K", ".-..": "L",
"--": "M", "-.": "N",
"---": "O", ".--.": "P",
"--.-": "Q", ".-.": "R",
"...": "S", "-": "T",
"..-": "U", "...-": "V",
".--": "W", "-..-": "X",
"-.--": "Y", "--..": "Z",
"-----": "0", ".----": "1",
"..---": "2", "...--": "3",
"....-": "4", ".....": "5",
"-....": "6", "--...": "7",
"---..": "8", "----.": "9",
".-.-.-": ".", "--..--": ",",
"---...": ":", "-.-.-.": ";",
"..--..": "?", "-....-": "-",
"..--.-": "_", "-.--.": "(",
"-.--.-": ")", ".----.": "'",
"-...-": "=", ".-.-.": "+",
"-..-.": "/", ".--.-.": "@",
"...-..-": "$", "-.-.--": "!"}
char_morse = {v: k for k, v in morse_char.items()}
def encode_morse(msg, sep='|', mapping=None):
"""
Encodes a plaintext into popular Morse Code with letters
separated by ``sep`` and words by a double ``sep``.
Examples
========
>>> from sympy.crypto.crypto import encode_morse
>>> msg = 'ATTACK RIGHT FLANK'
>>> encode_morse(msg)
'.-|-|-|.-|-.-.|-.-||.-.|..|--.|....|-||..-.|.-..|.-|-.|-.-'
References
==========
.. [1] https://en.wikipedia.org/wiki/Morse_code
"""
mapping = mapping or char_morse
assert sep not in mapping
word_sep = 2*sep
mapping[" "] = word_sep
suffix = msg and msg[-1] in whitespace
# normalize whitespace
msg = (' ' if word_sep else '').join(msg.split())
# omit unmapped chars
chars = set(''.join(msg.split()))
ok = set(mapping.keys())
msg = translate(msg, None, ''.join(chars - ok))
morsestring = []
words = msg.split()
for word in words:
morseword = []
for letter in word:
morseletter = mapping[letter]
morseword.append(morseletter)
word = sep.join(morseword)
morsestring.append(word)
return word_sep.join(morsestring) + (word_sep if suffix else '')
def decode_morse(msg, sep='|', mapping=None):
"""
Decodes a Morse Code with letters separated by ``sep``
(default is '|') and words by `word_sep` (default is '||)
into plaintext.
Examples
========
>>> from sympy.crypto.crypto import decode_morse
>>> mc = '--|---|...-|.||.|.-|...|-'
>>> decode_morse(mc)
'MOVE EAST'
References
==========
.. [1] https://en.wikipedia.org/wiki/Morse_code
"""
mapping = mapping or morse_char
word_sep = 2*sep
characterstring = []
words = msg.strip(word_sep).split(word_sep)
for word in words:
letters = word.split(sep)
chars = [mapping[c] for c in letters]
word = ''.join(chars)
characterstring.append(word)
rv = " ".join(characterstring)
return rv
#################### LFSRs ##########################################
def lfsr_sequence(key, fill, n):
r"""
This function creates an LFSR sequence.
Parameters
==========
key : list
A list of finite field elements, `[c_0, c_1, \ldots, c_k].`
fill : list
The list of the initial terms of the LFSR sequence,
`[x_0, x_1, \ldots, x_k].`
n
Number of terms of the sequence that the function returns.
Returns
=======
L
The LFSR sequence defined by
`x_{n+1} = c_k x_n + \ldots + c_0 x_{n-k}`, for
`n \leq k`.
Notes
=====
S. Golomb [G]_ gives a list of three statistical properties a
sequence of numbers `a = \{a_n\}_{n=1}^\infty`,
`a_n \in \{0,1\}`, should display to be considered
"random". Define the autocorrelation of `a` to be
.. math::
C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (-1)^{a_n + a_{n+k}}.
In the case where `a` is periodic with period
`P` then this reduces to
.. math::
C(k) = {1\over P}\sum_{n=1}^P (-1)^{a_n + a_{n+k}}.
Assume `a` is periodic with period `P`.
- balance:
.. math::
\left|\sum_{n=1}^P(-1)^{a_n}\right| \leq 1.
- low autocorrelation:
.. math::
C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right.
(For sequences satisfying these first two properties, it is known
that `\epsilon = -1/P` must hold.)
- proportional runs property: In each period, half the runs have
length `1`, one-fourth have length `2`, etc.
Moreover, there are as many runs of `1`'s as there are of
`0`'s.
Examples
========
>>> from sympy.crypto.crypto import lfsr_sequence
>>> from sympy.polys.domains import FF
>>> F = FF(2)
>>> fill = [F(1), F(1), F(0), F(1)]
>>> key = [F(1), F(0), F(0), F(1)]
>>> lfsr_sequence(key, fill, 10)
[1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2,
1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2]
References
==========
.. [G] Solomon Golomb, Shift register sequences, Aegean Park Press,
Laguna Hills, Ca, 1967
"""
if not isinstance(key, list):
raise TypeError("key must be a list")
if not isinstance(fill, list):
raise TypeError("fill must be a list")
p = key[0].mod
F = FF(p)
s = fill
k = len(fill)
L = []
for i in range(n):
s0 = s[:]
L.append(s[0])
s = s[1:k]
x = sum([int(key[i]*s0[i]) for i in range(k)])
s.append(F(x))
return L # use [x.to_int() for x in L] for int version
def lfsr_autocorrelation(L, P, k):
"""
This function computes the LFSR autocorrelation function.
Parameters
==========
L
A periodic sequence of elements of `GF(2)`.
L must have length larger than P.
P
The period of L.
k : int
An integer `k` (`0 < k < P`).
Returns
=======
autocorrelation
The k-th value of the autocorrelation of the LFSR L.
Examples
========
>>> from sympy.crypto.crypto import (
... lfsr_sequence, lfsr_autocorrelation)
>>> from sympy.polys.domains import FF
>>> F = FF(2)
>>> fill = [F(1), F(1), F(0), F(1)]
>>> key = [F(1), F(0), F(0), F(1)]
>>> s = lfsr_sequence(key, fill, 20)
>>> lfsr_autocorrelation(s, 15, 7)
-1/15
>>> lfsr_autocorrelation(s, 15, 0)
1
"""
if not isinstance(L, list):
raise TypeError("L (=%s) must be a list" % L)
P = int(P)
k = int(k)
L0 = L[:P] # slices makes a copy
L1 = L0 + L0[:k]
L2 = [(-1)**(L1[i].to_int() + L1[i + k].to_int()) for i in range(P)]
tot = sum(L2)
return Rational(tot, P)
def lfsr_connection_polynomial(s):
"""
This function computes the LFSR connection polynomial.
Parameters
==========
s
A sequence of elements of even length, with entries in a finite
field.
Returns
=======
C(x)
The connection polynomial of a minimal LFSR yielding s.
This implements the algorithm in section 3 of J. L. Massey's
article [M]_.
Examples
========
>>> from sympy.crypto.crypto import (
... lfsr_sequence, lfsr_connection_polynomial)
>>> from sympy.polys.domains import FF
>>> F = FF(2)
>>> fill = [F(1), F(1), F(0), F(1)]
>>> key = [F(1), F(0), F(0), F(1)]
>>> s = lfsr_sequence(key, fill, 20)
>>> lfsr_connection_polynomial(s)
x**4 + x + 1
>>> fill = [F(1), F(0), F(0), F(1)]
>>> key = [F(1), F(1), F(0), F(1)]
>>> s = lfsr_sequence(key, fill, 20)
>>> lfsr_connection_polynomial(s)
x**3 + 1
>>> fill = [F(1), F(0), F(1)]
>>> key = [F(1), F(1), F(0)]
>>> s = lfsr_sequence(key, fill, 20)
>>> lfsr_connection_polynomial(s)
x**3 + x**2 + 1
>>> fill = [F(1), F(0), F(1)]
>>> key = [F(1), F(0), F(1)]
>>> s = lfsr_sequence(key, fill, 20)
>>> lfsr_connection_polynomial(s)
x**3 + x + 1
References
==========
.. [M] James L. Massey, "Shift-Register Synthesis and BCH Decoding."
IEEE Trans. on Information Theory, vol. 15(1), pp. 122-127,
Jan 1969.
"""
# Initialization:
p = s[0].mod
x = Symbol("x")
C = 1*x**0
B = 1*x**0
m = 1
b = 1*x**0
L = 0
N = 0
while N < len(s):
if L > 0:
dC = Poly(C).degree()
r = min(L + 1, dC + 1)
coeffsC = [C.subs(x, 0)] + [C.coeff(x**i)
for i in range(1, dC + 1)]
d = (s[N].to_int() + sum([coeffsC[i]*s[N - i].to_int()
for i in range(1, r)])) % p
if L == 0:
d = s[N].to_int()*x**0
if d == 0:
m += 1
N += 1
if d > 0:
if 2*L > N:
C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
m += 1
N += 1
else:
T = C
C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
L = N + 1 - L
m = 1
b = d
B = T
N += 1
dC = Poly(C).degree()
coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)]
return sum([coeffsC[i] % p*x**i for i in range(dC + 1)
if coeffsC[i] is not None])
#################### ElGamal #############################
def elgamal_private_key(digit=10, seed=None):
r"""
Return three number tuple as private key.
Explanation
===========
Elgamal encryption is based on the mathmatical problem
called the Discrete Logarithm Problem (DLP). For example,
`a^{b} \equiv c \pmod p`
In general, if ``a`` and ``b`` are known, ``ct`` is easily
calculated. If ``b`` is unknown, it is hard to use
``a`` and ``ct`` to get ``b``.
Parameters
==========
digit : int
Minimum number of binary digits for key.
Returns
=======
tuple : (p, r, d)
p = prime number.
r = primitive root.
d = random number.
Notes
=====
For testing purposes, the ``seed`` parameter may be set to control
the output of this routine. See sympy.core.random._randrange.
Examples
========
>>> from sympy.crypto.crypto import elgamal_private_key
>>> from sympy.ntheory import is_primitive_root, isprime
>>> a, b, _ = elgamal_private_key()
>>> isprime(a)
True
>>> is_primitive_root(b, a)
True
"""
randrange = _randrange(seed)
p = nextprime(2**digit)
return p, primitive_root(p), randrange(2, p)
def elgamal_public_key(key):
r"""
Return three number tuple as public key.
Parameters
==========
key : (p, r, e)
Tuple generated by ``elgamal_private_key``.
Returns
=======
tuple : (p, r, e)
`e = r**d \bmod p`
`d` is a random number in private key.
Examples
========
>>> from sympy.crypto.crypto import elgamal_public_key
>>> elgamal_public_key((1031, 14, 636))
(1031, 14, 212)
"""
p, r, e = key
return p, r, pow(r, e, p)
def encipher_elgamal(i, key, seed=None):
r"""
Encrypt message with public key.
Explanation
===========
``i`` is a plaintext message expressed as an integer.
``key`` is public key (p, r, e). In order to encrypt
a message, a random number ``a`` in ``range(2, p)``
is generated and the encryped message is returned as
`c_{1}` and `c_{2}` where:
`c_{1} \equiv r^{a} \pmod p`
`c_{2} \equiv m e^{a} \pmod p`
Parameters
==========
msg
int of encoded message.
key
Public key.
Returns
=======
tuple : (c1, c2)
Encipher into two number.
Notes
=====
For testing purposes, the ``seed`` parameter may be set to control
the output of this routine. See sympy.core.random._randrange.
Examples
========
>>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key
>>> pri = elgamal_private_key(5, seed=[3]); pri
(37, 2, 3)
>>> pub = elgamal_public_key(pri); pub
(37, 2, 8)
>>> msg = 36
>>> encipher_elgamal(msg, pub, seed=[3])
(8, 6)
"""
p, r, e = key
if i < 0 or i >= p:
raise ValueError(
'Message (%s) should be in range(%s)' % (i, p))
randrange = _randrange(seed)
a = randrange(2, p)
return pow(r, a, p), i*pow(e, a, p) % p
def decipher_elgamal(msg, key):
r"""
Decrypt message with private key.
`msg = (c_{1}, c_{2})`
`key = (p, r, d)`
According to extended Eucliden theorem,
`u c_{1}^{d} + p n = 1`
`u \equiv 1/{{c_{1}}^d} \pmod p`
`u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p`
`\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p`
Examples
========
>>> from sympy.crypto.crypto import decipher_elgamal
>>> from sympy.crypto.crypto import encipher_elgamal
>>> from sympy.crypto.crypto import elgamal_private_key
>>> from sympy.crypto.crypto import elgamal_public_key
>>> pri = elgamal_private_key(5, seed=[3])
>>> pub = elgamal_public_key(pri); pub
(37, 2, 8)
>>> msg = 17
>>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg
True
"""
p, _, d = key
c1, c2 = msg
u = igcdex(c1**d, p)[0]
return u * c2 % p
################ Diffie-Hellman Key Exchange #########################
def dh_private_key(digit=10, seed=None):
r"""
Return three integer tuple as private key.
Explanation
===========
Diffie-Hellman key exchange is based on the mathematical problem
called the Discrete Logarithm Problem (see ElGamal).
Diffie-Hellman key exchange is divided into the following steps:
* Alice and Bob agree on a base that consist of a prime ``p``
and a primitive root of ``p`` called ``g``
* Alice choses a number ``a`` and Bob choses a number ``b`` where
``a`` and ``b`` are random numbers in range `[2, p)`. These are
their private keys.
* Alice then publicly sends Bob `g^{a} \pmod p` while Bob sends
Alice `g^{b} \pmod p`
* They both raise the received value to their secretly chosen
number (``a`` or ``b``) and now have both as their shared key
`g^{ab} \pmod p`
Parameters
==========
digit
Minimum number of binary digits required in key.
Returns
=======
tuple : (p, g, a)
p = prime number.
g = primitive root of p.
a = random number from 2 through p - 1.
Notes
=====
For testing purposes, the ``seed`` parameter may be set to control
the output of this routine. See sympy.core.random._randrange.
Examples
========
>>> from sympy.crypto.crypto import dh_private_key
>>> from sympy.ntheory import isprime, is_primitive_root
>>> p, g, _ = dh_private_key()
>>> isprime(p)
True
>>> is_primitive_root(g, p)
True
>>> p, g, _ = dh_private_key(5)
>>> isprime(p)
True
>>> is_primitive_root(g, p)
True
"""
p = nextprime(2**digit)
g = primitive_root(p)
randrange = _randrange(seed)
a = randrange(2, p)
return p, g, a
def dh_public_key(key):
r"""
Return three number tuple as public key.
This is the tuple that Alice sends to Bob.
Parameters
==========
key : (p, g, a)
A tuple generated by ``dh_private_key``.
Returns
=======
tuple : int, int, int
A tuple of `(p, g, g^a \mod p)` with `p`, `g` and `a` given as
parameters.s
Examples
========
>>> from sympy.crypto.crypto import dh_private_key, dh_public_key
>>> p, g, a = dh_private_key();
>>> _p, _g, x = dh_public_key((p, g, a))
>>> p == _p and g == _g
True
>>> x == pow(g, a, p)
True
"""
p, g, a = key
return p, g, pow(g, a, p)
def dh_shared_key(key, b):
"""
Return an integer that is the shared key.
This is what Bob and Alice can both calculate using the public
keys they received from each other and their private keys.
Parameters
==========
key : (p, g, x)
Tuple `(p, g, x)` generated by ``dh_public_key``.
b
Random number in the range of `2` to `p - 1`
(Chosen by second key exchange member (Bob)).
Returns
=======
int
A shared key.
Examples
========
>>> from sympy.crypto.crypto import (
... dh_private_key, dh_public_key, dh_shared_key)
>>> prk = dh_private_key();
>>> p, g, x = dh_public_key(prk);
>>> sk = dh_shared_key((p, g, x), 1000)
>>> sk == pow(x, 1000, p)
True
"""
p, _, x = key
if 1 >= b or b >= p:
raise ValueError(filldedent('''
Value of b should be greater 1 and less
than prime %s.''' % p))
return pow(x, b, p)
################ Goldwasser-Micali Encryption #########################
def _legendre(a, p):
"""
Returns the legendre symbol of a and p
assuming that p is a prime.
i.e. 1 if a is a quadratic residue mod p
-1 if a is not a quadratic residue mod p
0 if a is divisible by p
Parameters
==========
a : int
The number to test.
p : prime
The prime to test ``a`` against.
Returns
=======
int
Legendre symbol (a / p).
"""
sig = pow(a, (p - 1)//2, p)
if sig == 1:
return 1
elif sig == 0:
return 0
else:
return -1
def _random_coprime_stream(n, seed=None):
randrange = _randrange(seed)
while True:
y = randrange(n)
if gcd(y, n) == 1:
yield y
def gm_private_key(p, q, a=None):
r"""
Check if ``p`` and ``q`` can be used as private keys for
the Goldwasser-Micali encryption. The method works
roughly as follows.
Explanation
===========
#. Pick two large primes $p$ and $q$.
#. Call their product $N$.
#. Given a message as an integer $i$, write $i$ in its bit representation $b_0, \dots, b_n$.
#. For each $k$,
if $b_k = 0$:
let $a_k$ be a random square
(quadratic residue) modulo $p q$
such that ``jacobi_symbol(a, p*q) = 1``
if $b_k = 1$:
let $a_k$ be a random non-square
(non-quadratic residue) modulo $p q$
such that ``jacobi_symbol(a, p*q) = 1``
returns $\left[a_1, a_2, \dots\right]$
$b_k$ can be recovered by checking whether or not
$a_k$ is a residue. And from the $b_k$'s, the message
can be reconstructed.
The idea is that, while ``jacobi_symbol(a, p*q)``
can be easily computed (and when it is equal to $-1$ will
tell you that $a$ is not a square mod $p q$), quadratic
residuosity modulo a composite number is hard to compute
without knowing its factorization.
Moreover, approximately half the numbers coprime to $p q$ have
:func:`~.jacobi_symbol` equal to $1$ . And among those, approximately half
are residues and approximately half are not. This maximizes the
entropy of the code.
Parameters
==========
p, q, a
Initialization variables.
Returns
=======
tuple : (p, q)
The input value ``p`` and ``q``.
Raises
======
ValueError
If ``p`` and ``q`` are not distinct odd primes.
"""
if p == q:
raise ValueError("expected distinct primes, "
"got two copies of %i" % p)
elif not isprime(p) or not isprime(q):
raise ValueError("first two arguments must be prime, "
"got %i of %i" % (p, q))
elif p == 2 or q == 2:
raise ValueError("first two arguments must not be even, "
"got %i of %i" % (p, q))
return p, q
def gm_public_key(p, q, a=None, seed=None):
"""
Compute public keys for ``p`` and ``q``.
Note that in Goldwasser-Micali Encryption,
public keys are randomly selected.
Parameters
==========
p, q, a : int, int, int
Initialization variables.
Returns
=======
tuple : (a, N)
``a`` is the input ``a`` if it is not ``None`` otherwise
some random integer coprime to ``p`` and ``q``.
``N`` is the product of ``p`` and ``q``.
"""
p, q = gm_private_key(p, q)
N = p * q
if a is None:
randrange = _randrange(seed)
while True:
a = randrange(N)
if _legendre(a, p) == _legendre(a, q) == -1:
break
else:
if _legendre(a, p) != -1 or _legendre(a, q) != -1:
return False
return (a, N)
def encipher_gm(i, key, seed=None):
"""
Encrypt integer 'i' using public_key 'key'
Note that gm uses random encryption.
Parameters
==========
i : int
The message to encrypt.
key : (a, N)
The public key.
Returns
=======
list : list of int
The randomized encrypted message.
"""
if i < 0:
raise ValueError(
"message must be a non-negative "
"integer: got %d instead" % i)
a, N = key
bits = []
while i > 0:
bits.append(i % 2)
i //= 2
gen = _random_coprime_stream(N, seed)
rev = reversed(bits)
encode = lambda b: next(gen)**2*pow(a, b) % N
return [ encode(b) for b in rev ]
def decipher_gm(message, key):
"""
Decrypt message 'message' using public_key 'key'.
Parameters
==========
message : list of int
The randomized encrypted message.
key : (p, q)
The private key.
Returns
=======
int
The encrypted message.
"""
p, q = key
res = lambda m, p: _legendre(m, p) > 0
bits = [res(m, p) * res(m, q) for m in message]
m = 0
for b in bits:
m <<= 1
m += not b
return m
########### RailFence Cipher #############
def encipher_railfence(message,rails):
"""
Performs Railfence Encryption on plaintext and returns ciphertext
Examples
========
>>> from sympy.crypto.crypto import encipher_railfence
>>> message = "hello world"
>>> encipher_railfence(message,3)
'horel ollwd'
Parameters
==========
message : string, the message to encrypt.
rails : int, the number of rails.
Returns
=======
The Encrypted string message.
References
==========
.. [1] https://en.wikipedia.org/wiki/Rail_fence_cipher
"""
r = list(range(rails))
p = cycle(r + r[-2:0:-1])
return ''.join(sorted(message, key=lambda i: next(p)))
def decipher_railfence(ciphertext,rails):
"""
Decrypt the message using the given rails
Examples
========
>>> from sympy.crypto.crypto import decipher_railfence
>>> decipher_railfence("horel ollwd",3)
'hello world'
Parameters
==========
message : string, the message to encrypt.
rails : int, the number of rails.
Returns
=======
The Decrypted string message.
"""
r = list(range(rails))
p = cycle(r + r[-2:0:-1])
idx = sorted(range(len(ciphertext)), key=lambda i: next(p))
res = [''] * len(ciphertext)
for i, c in zip(idx, ciphertext):
res[i] = c
return ''.join(res)
################ Blum-Goldwasser cryptosystem #########################
def bg_private_key(p, q):
"""
Check if p and q can be used as private keys for
the Blum-Goldwasser cryptosystem.
Explanation
===========
The three necessary checks for p and q to pass
so that they can be used as private keys:
1. p and q must both be prime
2. p and q must be distinct
3. p and q must be congruent to 3 mod 4
Parameters
==========
p, q
The keys to be checked.
Returns
=======
p, q
Input values.
Raises
======
ValueError
If p and q do not pass the above conditions.
"""
if not isprime(p) or not isprime(q):
raise ValueError("the two arguments must be prime, "
"got %i and %i" %(p, q))
elif p == q:
raise ValueError("the two arguments must be distinct, "
"got two copies of %i. " %p)
elif (p - 3) % 4 != 0 or (q - 3) % 4 != 0:
raise ValueError("the two arguments must be congruent to 3 mod 4, "
"got %i and %i" %(p, q))
return p, q
def bg_public_key(p, q):
"""
Calculates public keys from private keys.
Explanation
===========
The function first checks the validity of
private keys passed as arguments and
then returns their product.
Parameters
==========
p, q
The private keys.
Returns
=======
N
The public key.
"""
p, q = bg_private_key(p, q)
N = p * q
return N
def encipher_bg(i, key, seed=None):
"""
Encrypts the message using public key and seed.
Explanation
===========
ALGORITHM:
1. Encodes i as a string of L bits, m.
2. Select a random element r, where 1 < r < key, and computes
x = r^2 mod key.
3. Use BBS pseudo-random number generator to generate L random bits, b,
using the initial seed as x.
4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L.
5. x_L = x^(2^L) mod key.
6. Return (c, x_L)
Parameters
==========
i
Message, a non-negative integer
key
The public key
Returns
=======
Tuple
(encrypted_message, x_L)
Raises
======
ValueError
If i is negative.
"""
if i < 0:
raise ValueError(
"message must be a non-negative "
"integer: got %d instead" % i)
enc_msg = []
while i > 0:
enc_msg.append(i % 2)
i //= 2
enc_msg.reverse()
L = len(enc_msg)
r = _randint(seed)(2, key - 1)
x = r**2 % key
x_L = pow(int(x), int(2**L), int(key))
rand_bits = []
for _ in range(L):
rand_bits.append(x % 2)
x = x**2 % key
encrypt_msg = [m ^ b for (m, b) in zip(enc_msg, rand_bits)]
return (encrypt_msg, x_L)
def decipher_bg(message, key):
"""
Decrypts the message using private keys.
Explanation
===========
ALGORITHM:
1. Let, c be the encrypted message, y the second number received,
and p and q be the private keys.
2. Compute, r_p = y^((p+1)/4 ^ L) mod p and
r_q = y^((q+1)/4 ^ L) mod q.
3. Compute x_0 = (q(q^-1 mod p)r_p + p(p^-1 mod q)r_q) mod N.
4. From, recompute the bits using the BBS generator, as in the
encryption algorithm.
5. Compute original message by XORing c and b.
Parameters
==========
message
Tuple of encrypted message and a non-negative integer.
key
Tuple of private keys.
Returns
=======
orig_msg
The original message
"""
p, q = key
encrypt_msg, y = message
public_key = p * q
L = len(encrypt_msg)
p_t = ((p + 1)/4)**L
q_t = ((q + 1)/4)**L
r_p = pow(int(y), int(p_t), int(p))
r_q = pow(int(y), int(q_t), int(q))
x = (q * mod_inverse(q, p) * r_p + p * mod_inverse(p, q) * r_q) % public_key
orig_bits = []
for _ in range(L):
orig_bits.append(x % 2)
x = x**2 % public_key
orig_msg = 0
for (m, b) in zip(encrypt_msg, orig_bits):
orig_msg = orig_msg * 2
orig_msg += (m ^ b)
return orig_msg
|
3092aaaa813db9a4549f581c611ff5e96ee1bc661172847eba35e386447a2d73 | """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 (sympy_deprecation_warning,
SymPyDeprecationWarning,
ignore_warnings)
# 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[type(proposition)], 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`.
"""
sympy_deprecation_warning(
"""
The AskHandler system is deprecated. The register_handler() function
should be replaced with the multipledispatch handler of Predicate.
""",
deprecated_since_version="1.8",
active_deprecations_target='deprecated-askhandler',
)
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`.
"""
sympy_deprecation_warning(
"""
The AskHandler system is deprecated. The remove_handler() function
should be replaced with the multipledispatch handler of Predicate.
""",
deprecated_since_version="1.8",
active_deprecations_target='deprecated-askhandler',
)
if isinstance(key, Predicate):
key = key.name.name
# Don't show the same warning again recursively
with ignore_warnings(SymPyDeprecationWarning):
getattr(Q, key).remove_handler(handler)
from sympy.assumptions.ask_generated import (get_all_known_facts,
get_known_facts_dict)
|
ab448355bce6538ebff267fadd46a8e69604e0c832ae147dbe7f78409a904aff | """
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.ask 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, And, Implies
>>> from sympy.assumptions.facts import generate_known_facts_dict
>>> 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
|
7fae50fcf0e54e164c8a9ba3bac316fc7300ba3393fc019d6526a9b7c8b1faf4 | """A module which implements predicates and assumption context."""
from contextlib import contextmanager
import inspect
from sympy.core.assumptions import ManagedProperties
from sympy.core.symbol import Str
from sympy.core.sympify import _sympify
from sympy.logic.boolalg import Boolean, false, true
from sympy.multipledispatch.dispatcher import Dispatcher, str_signature
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.iterables import is_sequence
from sympy.utilities.source import get_class
class AssumptionsContext(set):
"""
Set containing default assumptions which are applied to the ``ask()``
function.
Explanation
===========
This is used to represent global assumptions, but you can also use this
class to create your own local assumptions contexts. It is basically a thin
wrapper to Python's set, so see its documentation for advanced usage.
Examples
========
The default assumption context is ``global_assumptions``, which is initially empty:
>>> from sympy import ask, Q
>>> from sympy.assumptions import global_assumptions
>>> global_assumptions
AssumptionsContext()
You can add default assumptions:
>>> from sympy.abc import x
>>> global_assumptions.add(Q.real(x))
>>> global_assumptions
AssumptionsContext({Q.real(x)})
>>> ask(Q.real(x))
True
And remove them:
>>> global_assumptions.remove(Q.real(x))
>>> print(ask(Q.real(x)))
None
The ``clear()`` method removes every assumption:
>>> global_assumptions.add(Q.positive(x))
>>> global_assumptions
AssumptionsContext({Q.positive(x)})
>>> global_assumptions.clear()
>>> global_assumptions
AssumptionsContext()
See Also
========
assuming
"""
def add(self, *assumptions):
"""Add assumptions."""
for a in assumptions:
super().add(a)
def _sympystr(self, printer):
if not self:
return "%s()" % self.__class__.__name__
return "{}({})".format(self.__class__.__name__, printer._print_set(self))
global_assumptions = AssumptionsContext()
class AppliedPredicate(Boolean):
"""
The class of expressions resulting from applying ``Predicate`` to
the arguments. ``AppliedPredicate`` merely wraps its argument and
remain unevaluated. To evaluate it, use the ``ask()`` function.
Examples
========
>>> from sympy import Q, ask
>>> Q.integer(1)
Q.integer(1)
The ``function`` attribute returns the predicate, and the ``arguments``
attribute returns the tuple of arguments.
>>> type(Q.integer(1))
<class 'sympy.assumptions.assume.AppliedPredicate'>
>>> Q.integer(1).function
Q.integer
>>> Q.integer(1).arguments
(1,)
Applied predicates can be evaluated to a boolean value with ``ask``:
>>> ask(Q.integer(1))
True
"""
__slots__ = ()
def __new__(cls, predicate, *args):
if not isinstance(predicate, Predicate):
raise TypeError("%s is not a Predicate." % predicate)
args = map(_sympify, args)
return super().__new__(cls, predicate, *args)
@property
def arg(self):
"""
Return the expression used by this assumption.
Examples
========
>>> from sympy import Q, Symbol
>>> x = Symbol('x')
>>> a = Q.integer(x + 1)
>>> a.arg
x + 1
"""
# Will be deprecated
args = self._args
if len(args) == 2:
# backwards compatibility
return args[1]
raise TypeError("'arg' property is allowed only for unary predicates.")
@property
def function(self):
"""
Return the predicate.
"""
# Will be changed to self.args[0] after args overridding is removed
return self._args[0]
@property
def arguments(self):
"""
Return the arguments which are applied to the predicate.
"""
# Will be changed to self.args[1:] after args overridding is removed
return self._args[1:]
def _eval_ask(self, assumptions):
return self.function.eval(self.arguments, assumptions)
@property
def binary_symbols(self):
from .ask import Q
if self.function == Q.is_true:
i = self.arguments[0]
if i.is_Boolean or i.is_Symbol:
return i.binary_symbols
if self.function in (Q.eq, Q.ne):
if true in self.arguments or false in self.arguments:
if self.arguments[0].is_Symbol:
return {self.arguments[0]}
elif self.arguments[1].is_Symbol:
return {self.arguments[1]}
return set()
class PredicateMeta(ManagedProperties):
def __new__(cls, clsname, bases, dct):
# If handler is not defined, assign empty dispatcher.
if "handler" not in dct:
name = f"Ask{clsname.capitalize()}Handler"
handler = Dispatcher(name, doc="Handler for key %s" % name)
dct["handler"] = handler
dct["_orig_doc"] = dct.get("__doc__", "")
return super().__new__(cls, clsname, bases, dct)
@property
def __doc__(cls):
handler = cls.handler
doc = cls._orig_doc
if cls is not Predicate and handler is not None:
doc += "Handler\n"
doc += " =======\n\n"
# Append the handler's doc without breaking sphinx documentation.
docs = [" Multiply dispatched method: %s" % handler.name]
if handler.doc:
for line in handler.doc.splitlines():
if not line:
continue
docs.append(" %s" % line)
other = []
for sig in handler.ordering[::-1]:
func = handler.funcs[sig]
if func.__doc__:
s = ' Inputs: <%s>' % str_signature(sig)
lines = []
for line in func.__doc__.splitlines():
lines.append(" %s" % line)
s += "\n".join(lines)
docs.append(s)
else:
other.append(str_signature(sig))
if other:
othersig = " Other signatures:"
for line in other:
othersig += "\n * %s" % line
docs.append(othersig)
doc += '\n\n'.join(docs)
return doc
class Predicate(Boolean, metaclass=PredicateMeta):
"""
Base class for mathematical predicates. It also serves as a
constructor for undefined predicate objects.
Explanation
===========
Predicate is a function that returns a boolean value [1].
Predicate function is object, and it is instance of predicate class.
When a predicate is applied to arguments, ``AppliedPredicate``
instance is returned. This merely wraps the argument and remain
unevaluated. To obtain the truth value of applied predicate, use the
function ``ask``.
Evaluation of predicate is done by multiple dispatching. You can
register new handler to the predicate to support new types.
Every predicate in SymPy can be accessed via the property of ``Q``.
For example, ``Q.even`` returns the predicate which checks if the
argument is even number.
To define a predicate which can be evaluated, you must subclass this
class, make an instance of it, and register it to ``Q``. After then,
dispatch the handler by argument types.
If you directly construct predicate using this class, you will get
``UndefinedPredicate`` which cannot be dispatched. This is useful
when you are building boolean expressions which do not need to be
evaluated.
Examples
========
Applying and evaluating to boolean value:
>>> from sympy import Q, ask
>>> ask(Q.prime(7))
True
You can define a new predicate by subclassing and dispatching. Here,
we define a predicate for sexy primes [2] as an example.
>>> from sympy import Predicate, Integer
>>> class SexyPrimePredicate(Predicate):
... name = "sexyprime"
>>> Q.sexyprime = SexyPrimePredicate()
>>> @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
>>> ask(Q.sexyprime(5, 11))
True
Direct constructing returns ``UndefinedPredicate``, which can be
applied but cannot be dispatched.
>>> from sympy import Predicate, Integer
>>> Q.P = Predicate("P")
>>> type(Q.P)
<class 'sympy.assumptions.assume.UndefinedPredicate'>
>>> Q.P(1)
Q.P(1)
>>> Q.P.register(Integer)(lambda expr, assump: True)
Traceback (most recent call last):
...
TypeError: <class 'sympy.assumptions.assume.UndefinedPredicate'> cannot be dispatched.
References
==========
.. [1] https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)
.. [2] https://en.wikipedia.org/wiki/Sexy_prime
"""
is_Atom = True
def __new__(cls, *args, **kwargs):
if cls is Predicate:
return UndefinedPredicate(*args, **kwargs)
obj = super().__new__(cls, *args)
return obj
@property
def name(self):
# May be overridden
return type(self).__name__
@classmethod
def register(cls, *types, **kwargs):
"""
Register the signature to the handler.
"""
if cls.handler is None:
raise TypeError("%s cannot be dispatched." % type(cls))
return cls.handler.register(*types, **kwargs)
@classmethod
def register_many(cls, *types, **kwargs):
"""
Register multiple signatures to same handler.
"""
def _(func):
for t in types:
if not is_sequence(t):
t = (t,) # for convenience, allow passing `type` to mean `(type,)`
cls.register(*t, **kwargs)(func)
return _
def __call__(self, *args):
return AppliedPredicate(self, *args)
def eval(self, args, assumptions=True):
"""
Evaluate ``self(*args)`` under the given assumptions.
This uses only direct resolution methods, not logical inference.
"""
result = None
try:
result = self.handler(*args, assumptions=assumptions)
except NotImplementedError:
pass
return result
def _eval_refine(self, assumptions):
# When Predicate is no longer Boolean, delete this method
return self
class UndefinedPredicate(Predicate):
"""
Predicate without handler.
Explanation
===========
This predicate is generated by using ``Predicate`` directly for
construction. It does not have a handler, and evaluating this with
arguments is done by SAT solver.
Examples
========
>>> from sympy import Predicate, Q
>>> Q.P = Predicate('P')
>>> Q.P.func
<class 'sympy.assumptions.assume.UndefinedPredicate'>
>>> Q.P.name
Str('P')
"""
handler = None
def __new__(cls, name, handlers=None):
# "handlers" parameter supports old design
if not isinstance(name, Str):
name = Str(name)
obj = super(Boolean, cls).__new__(cls, name)
obj.handlers = handlers or []
return obj
@property
def name(self):
return self.args[0]
def _hashable_content(self):
return (self.name,)
def __getnewargs__(self):
return (self.name,)
def __call__(self, expr):
return AppliedPredicate(self, expr)
def add_handler(self, handler):
sympy_deprecation_warning(
"""
The AskHandler system is deprecated. Predicate.add_handler()
should be replaced with the multipledispatch handler of Predicate.
""",
deprecated_since_version="1.8",
active_deprecations_target='deprecated-askhandler',
)
self.handlers.append(handler)
def remove_handler(self, handler):
sympy_deprecation_warning(
"""
The AskHandler system is deprecated. Predicate.remove_handler()
should be replaced with the multipledispatch handler of Predicate.
""",
deprecated_since_version="1.8",
active_deprecations_target='deprecated-askhandler',
)
self.handlers.remove(handler)
def eval(self, args, assumptions=True):
# Support for deprecated design
# When old design is removed, this will always return None
sympy_deprecation_warning(
"""
The AskHandler system is deprecated. Evaluating UndefinedPredicate
objects should be replaced with the multipledispatch handler of
Predicate.
""",
deprecated_since_version="1.8",
active_deprecations_target='deprecated-askhandler',
stacklevel=5,
)
expr, = args
res, _res = None, None
mro = inspect.getmro(type(expr))
for handler in self.handlers:
cls = get_class(handler)
for subclass in mro:
eval_ = getattr(cls, subclass.__name__, None)
if eval_ is None:
continue
res = eval_(expr, assumptions)
# Do not stop if value returned is None
# Try to check for higher classes
if res is None:
continue
if _res is None:
_res = res
else:
# only check consistency if both resolutors have concluded
if _res != res:
raise ValueError('incompatible resolutors')
break
return res
@contextmanager
def assuming(*assumptions):
"""
Context manager for assumptions.
Examples
========
>>> from sympy import assuming, Q, ask
>>> from sympy.abc import x, y
>>> print(ask(Q.integer(x + y)))
None
>>> with assuming(Q.integer(x), Q.integer(y)):
... print(ask(Q.integer(x + y)))
True
"""
old_global_assumptions = global_assumptions.copy()
global_assumptions.update(assumptions)
try:
yield
finally:
global_assumptions.clear()
global_assumptions.update(old_global_assumptions)
|
cd3b2eb3d40a5a5258da40473cd6869d7dc61596bdc5cb0e1154d79416de4efe | """
The classes used here are for the internal use of assumptions system
only and should not be used anywhere else as these do not possess the
signatures common to SymPy objects. For general use of logic constructs
please refer to sympy.logic classes And, Or, Not, etc.
"""
from itertools import combinations, product, zip_longest
from sympy.assumptions.assume import AppliedPredicate, Predicate
from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le
from sympy.core.singleton import S
from sympy.logic.boolalg import Or, And, Not, Xnor
from sympy.logic.boolalg import (Equivalent, ITE, Implies, Nand, Nor, Xor)
class Literal:
"""
The smallest element of a CNF object.
Parameters
==========
lit : Boolean expression
is_Not : bool
Examples
========
>>> from sympy import Q
>>> from sympy.assumptions.cnf import Literal
>>> from sympy.abc import x
>>> Literal(Q.even(x))
Literal(Q.even(x), False)
>>> Literal(~Q.even(x))
Literal(Q.even(x), True)
"""
def __new__(cls, lit, is_Not=False):
if isinstance(lit, Not):
lit = lit.args[0]
is_Not = True
elif isinstance(lit, (AND, OR, Literal)):
return ~lit if is_Not else lit
obj = super().__new__(cls)
obj.lit = lit
obj.is_Not = is_Not
return obj
@property
def arg(self):
return self.lit
def rcall(self, expr):
if callable(self.lit):
lit = self.lit(expr)
else:
try:
lit = self.lit.apply(expr)
except AttributeError:
lit = self.lit.rcall(expr)
return type(self)(lit, self.is_Not)
def __invert__(self):
is_Not = not self.is_Not
return Literal(self.lit, is_Not)
def __str__(self):
return '{}({}, {})'.format(type(self).__name__, self.lit, self.is_Not)
__repr__ = __str__
def __eq__(self, other):
return self.arg == other.arg and self.is_Not == other.is_Not
def __hash__(self):
h = hash((type(self).__name__, self.arg, self.is_Not))
return h
class OR:
"""
A low-level implementation for Or
"""
def __init__(self, *args):
self._args = args
@property
def args(self):
return sorted(self._args, key=str)
def rcall(self, expr):
return type(self)(*[arg.rcall(expr)
for arg in self._args
])
def __invert__(self):
return AND(*[~arg for arg in self._args])
def __hash__(self):
return hash((type(self).__name__,) + tuple(self.args))
def __eq__(self, other):
return self.args == other.args
def __str__(self):
s = '(' + ' | '.join([str(arg) for arg in self.args]) + ')'
return s
__repr__ = __str__
class AND:
"""
A low-level implementation for And
"""
def __init__(self, *args):
self._args = args
def __invert__(self):
return OR(*[~arg for arg in self._args])
@property
def args(self):
return sorted(self._args, key=str)
def rcall(self, expr):
return type(self)(*[arg.rcall(expr)
for arg in self._args
])
def __hash__(self):
return hash((type(self).__name__,) + tuple(self.args))
def __eq__(self, other):
return self.args == other.args
def __str__(self):
s = '('+' & '.join([str(arg) for arg in self.args])+')'
return s
__repr__ = __str__
def to_NNF(expr, composite_map=None):
"""
Generates the Negation Normal Form of any boolean expression in terms
of AND, OR, and Literal objects.
Examples
========
>>> from sympy import Q, Eq
>>> from sympy.assumptions.cnf import to_NNF
>>> from sympy.abc import x, y
>>> expr = Q.even(x) & ~Q.positive(x)
>>> to_NNF(expr)
(Literal(Q.even(x), False) & Literal(Q.positive(x), True))
Supported boolean objects are converted to corresponding predicates.
>>> to_NNF(Eq(x, y))
Literal(Q.eq(x, y), False)
If ``composite_map`` argument is given, ``to_NNF`` decomposes the
specified predicate into a combination of primitive predicates.
>>> cmap = {Q.nonpositive: Q.negative | Q.zero}
>>> to_NNF(Q.nonpositive, cmap)
(Literal(Q.negative, False) | Literal(Q.zero, False))
>>> to_NNF(Q.nonpositive(x), cmap)
(Literal(Q.negative(x), False) | Literal(Q.zero(x), False))
"""
from sympy.assumptions.ask import Q
if composite_map is None:
composite_map = dict()
binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le}
if type(expr) in binrelpreds:
pred = binrelpreds[type(expr)]
expr = pred(*expr.args)
if isinstance(expr, Not):
arg = expr.args[0]
tmp = to_NNF(arg, composite_map) # Strategy: negate the NNF of expr
return ~tmp
if isinstance(expr, Or):
return OR(*[to_NNF(x, composite_map) for x in Or.make_args(expr)])
if isinstance(expr, And):
return AND(*[to_NNF(x, composite_map) for x in And.make_args(expr)])
if isinstance(expr, Nand):
tmp = AND(*[to_NNF(x, composite_map) for x in expr.args])
return ~tmp
if isinstance(expr, Nor):
tmp = OR(*[to_NNF(x, composite_map) for x in expr.args])
return ~tmp
if isinstance(expr, Xor):
cnfs = []
for i in range(0, len(expr.args) + 1, 2):
for neg in combinations(expr.args, i):
clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map)
for s in expr.args]
cnfs.append(OR(*clause))
return AND(*cnfs)
if isinstance(expr, Xnor):
cnfs = []
for i in range(0, len(expr.args) + 1, 2):
for neg in combinations(expr.args, i):
clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map)
for s in expr.args]
cnfs.append(OR(*clause))
return ~AND(*cnfs)
if isinstance(expr, Implies):
L, R = to_NNF(expr.args[0], composite_map), to_NNF(expr.args[1], composite_map)
return OR(~L, R)
if isinstance(expr, Equivalent):
cnfs = []
for a, b in zip_longest(expr.args, expr.args[1:], fillvalue=expr.args[0]):
a = to_NNF(a, composite_map)
b = to_NNF(b, composite_map)
cnfs.append(OR(~a, b))
return AND(*cnfs)
if isinstance(expr, ITE):
L = to_NNF(expr.args[0], composite_map)
M = to_NNF(expr.args[1], composite_map)
R = to_NNF(expr.args[2], composite_map)
return AND(OR(~L, M), OR(L, R))
if isinstance(expr, AppliedPredicate):
pred, args = expr.function, expr.arguments
newpred = composite_map.get(pred, None)
if newpred is not None:
return to_NNF(newpred.rcall(*args), composite_map)
if isinstance(expr, Predicate):
newpred = composite_map.get(expr, None)
if newpred is not None:
return to_NNF(newpred, composite_map)
return Literal(expr)
def distribute_AND_over_OR(expr):
"""
Distributes AND over OR in the NNF expression.
Returns the result( Conjunctive Normal Form of expression)
as a CNF object.
"""
if not isinstance(expr, (AND, OR)):
tmp = set()
tmp.add(frozenset((expr,)))
return CNF(tmp)
if isinstance(expr, OR):
return CNF.all_or(*[distribute_AND_over_OR(arg)
for arg in expr._args])
if isinstance(expr, AND):
return CNF.all_and(*[distribute_AND_over_OR(arg)
for arg in expr._args])
class CNF:
"""
Class to represent CNF of a Boolean expression.
Consists of set of clauses, which themselves are stored as
frozenset of Literal objects.
Examples
========
>>> from sympy import Q
>>> from sympy.assumptions.cnf import CNF
>>> from sympy.abc import x
>>> cnf = CNF.from_prop(Q.real(x) & ~Q.zero(x))
>>> cnf.clauses
{frozenset({Literal(Q.zero(x), True)}),
frozenset({Literal(Q.negative(x), False),
Literal(Q.positive(x), False), Literal(Q.zero(x), False)})}
"""
def __init__(self, clauses=None):
if not clauses:
clauses = set()
self.clauses = clauses
def add(self, prop):
clauses = CNF.to_CNF(prop).clauses
self.add_clauses(clauses)
def __str__(self):
s = ' & '.join(
['(' + ' | '.join([str(lit) for lit in clause]) +')'
for clause in self.clauses]
)
return s
def extend(self, props):
for p in props:
self.add(p)
return self
def copy(self):
return CNF(set(self.clauses))
def add_clauses(self, clauses):
self.clauses |= clauses
@classmethod
def from_prop(cls, prop):
res = cls()
res.add(prop)
return res
def __iand__(self, other):
self.add_clauses(other.clauses)
return self
def all_predicates(self):
predicates = set()
for c in self.clauses:
predicates |= {arg.lit for arg in c}
return predicates
def _or(self, cnf):
clauses = set()
for a, b in product(self.clauses, cnf.clauses):
tmp = set(a)
for t in b:
tmp.add(t)
clauses.add(frozenset(tmp))
return CNF(clauses)
def _and(self, cnf):
clauses = self.clauses.union(cnf.clauses)
return CNF(clauses)
def _not(self):
clss = list(self.clauses)
ll = set()
for x in clss[-1]:
ll.add(frozenset((~x,)))
ll = CNF(ll)
for rest in clss[:-1]:
p = set()
for x in rest:
p.add(frozenset((~x,)))
ll = ll._or(CNF(p))
return ll
def rcall(self, expr):
clause_list = list()
for clause in self.clauses:
lits = [arg.rcall(expr) for arg in clause]
clause_list.append(OR(*lits))
expr = AND(*clause_list)
return distribute_AND_over_OR(expr)
@classmethod
def all_or(cls, *cnfs):
b = cnfs[0].copy()
for rest in cnfs[1:]:
b = b._or(rest)
return b
@classmethod
def all_and(cls, *cnfs):
b = cnfs[0].copy()
for rest in cnfs[1:]:
b = b._and(rest)
return b
@classmethod
def to_CNF(cls, expr):
from sympy.assumptions.facts import get_composite_predicates
expr = to_NNF(expr, get_composite_predicates())
expr = distribute_AND_over_OR(expr)
return expr
@classmethod
def CNF_to_cnf(cls, cnf):
"""
Converts CNF object to SymPy's boolean expression
retaining the form of expression.
"""
def remove_literal(arg):
return Not(arg.lit) if arg.is_Not else arg.lit
return And(*(Or(*(remove_literal(arg) for arg in clause)) for clause in cnf.clauses))
class EncodedCNF:
"""
Class for encoding the CNF expression.
"""
def __init__(self, data=None, encoding=None):
if not data and not encoding:
data = list()
encoding = dict()
self.data = data
self.encoding = encoding
self._symbols = list(encoding.keys())
def from_cnf(self, cnf):
self._symbols = list(cnf.all_predicates())
n = len(self._symbols)
self.encoding = dict(list(zip(self._symbols, list(range(1, n + 1)))))
self.data = [self.encode(clause) for clause in cnf.clauses]
@property
def symbols(self):
return self._symbols
@property
def variables(self):
return range(1, len(self._symbols) + 1)
def copy(self):
new_data = [set(clause) for clause in self.data]
return EncodedCNF(new_data, dict(self.encoding))
def add_prop(self, prop):
cnf = CNF.from_prop(prop)
self.add_from_cnf(cnf)
def add_from_cnf(self, cnf):
clauses = [self.encode(clause) for clause in cnf.clauses]
self.data += clauses
def encode_arg(self, arg):
literal = arg.lit
value = self.encoding.get(literal, None)
if value is None:
n = len(self._symbols)
self._symbols.append(literal)
value = self.encoding[literal] = n + 1
if arg.is_Not:
return -value
else:
return value
def encode(self, clause):
return {self.encode_arg(arg) if not arg.lit == S.false else 0 for arg in clause}
|
c129e48b2da710bd11d6a7f1628e9d5dfba5a88e5cf04e7d1d59e252d45a14a9 | from sympy.core.add import Add
from sympy.core.exprtools import factor_terms
from sympy.core.function import expand_log, _mexpand
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.sorting import ordered
from sympy.core.symbol import Dummy
from sympy.functions.elementary.exponential import (LambertW, exp, log)
from sympy.functions.elementary.miscellaneous import root
from sympy.polys.polyroots import roots
from sympy.polys.polytools import Poly, factor
from sympy.simplify.simplify import separatevars
from sympy.simplify.radsimp import collect
from sympy.simplify.simplify import powsimp
from sympy.solvers.solvers import solve, _invert
from sympy.utilities.iterables import uniq
def _filtered_gens(poly, symbol):
"""process the generators of ``poly``, returning the set of generators that
have ``symbol``. If there are two generators that are inverses of each other,
prefer the one that has no denominator.
Examples
========
>>> from sympy.solvers.bivariate import _filtered_gens
>>> from sympy import Poly, exp
>>> from sympy.abc import x
>>> _filtered_gens(Poly(x + 1/x + exp(x)), x)
{x, exp(x)}
"""
gens = {g for g in poly.gens if symbol in g.free_symbols}
for g in list(gens):
ag = 1/g
if g in gens and ag in gens:
if ag.as_numer_denom()[1] is not S.One:
g = ag
gens.remove(g)
return gens
def _mostfunc(lhs, func, X=None):
"""Returns the term in lhs which contains the most of the
func-type things e.g. log(log(x)) wins over log(x) if both terms appear.
``func`` can be a function (exp, log, etc...) or any other SymPy object,
like Pow.
If ``X`` is not ``None``, then the function returns the term composed with the
most ``func`` having the specified variable.
Examples
========
>>> from sympy.solvers.bivariate import _mostfunc
>>> from sympy import exp
>>> from sympy.abc import x, y
>>> _mostfunc(exp(x) + exp(exp(x) + 2), exp)
exp(exp(x) + 2)
>>> _mostfunc(exp(x) + exp(exp(y) + 2), exp)
exp(exp(y) + 2)
>>> _mostfunc(exp(x) + exp(exp(y) + 2), exp, x)
exp(x)
>>> _mostfunc(x, exp, x) is None
True
>>> _mostfunc(exp(x) + exp(x*y), exp, x)
exp(x)
"""
fterms = [tmp for tmp in lhs.atoms(func) if (not X or
X.is_Symbol and X in tmp.free_symbols or
not X.is_Symbol and tmp.has(X))]
if len(fterms) == 1:
return fterms[0]
elif fterms:
return max(list(ordered(fterms)), key=lambda x: x.count(func))
return None
def _linab(arg, symbol):
"""Return ``a, b, X`` assuming ``arg`` can be written as ``a*X + b``
where ``X`` is a symbol-dependent factor and ``a`` and ``b`` are
independent of ``symbol``.
Examples
========
>>> from sympy.solvers.bivariate import _linab
>>> from sympy.abc import x, y
>>> from sympy import exp, S
>>> _linab(S(2), x)
(2, 0, 1)
>>> _linab(2*x, x)
(2, 0, x)
>>> _linab(y + y*x + 2*x, x)
(y + 2, y, x)
>>> _linab(3 + 2*exp(x), x)
(2, 3, exp(x))
"""
arg = factor_terms(arg.expand())
ind, dep = arg.as_independent(symbol)
if arg.is_Mul and dep.is_Add:
a, b, x = _linab(dep, symbol)
return ind*a, ind*b, x
if not arg.is_Add:
b = 0
a, x = ind, dep
else:
b = ind
a, x = separatevars(dep).as_independent(symbol, as_Add=False)
if x.could_extract_minus_sign():
a = -a
x = -x
return a, b, x
def _lambert(eq, x):
"""
Given an expression assumed to be in the form
``F(X, a..f) = a*log(b*X + c) + d*X + f = 0``
where X = g(x) and x = g^-1(X), return the Lambert solution,
``x = g^-1(-c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(-f/a)))``.
"""
eq = _mexpand(expand_log(eq))
mainlog = _mostfunc(eq, log, x)
if not mainlog:
return [] # violated assumptions
other = eq.subs(mainlog, 0)
if isinstance(-other, log):
eq = (eq - other).subs(mainlog, mainlog.args[0])
mainlog = mainlog.args[0]
if not isinstance(mainlog, log):
return [] # violated assumptions
other = -(-other).args[0]
eq += other
if x not in other.free_symbols:
return [] # violated assumptions
d, f, X2 = _linab(other, x)
logterm = collect(eq - other, mainlog)
a = logterm.as_coefficient(mainlog)
if a is None or x in a.free_symbols:
return [] # violated assumptions
logarg = mainlog.args[0]
b, c, X1 = _linab(logarg, x)
if X1 != X2:
return [] # violated assumptions
# invert the generator X1 so we have x(u)
u = Dummy('rhs')
xusolns = solve(X1 - u, x)
# There are infinitely many branches for LambertW
# but only branches for k = -1 and 0 might be real. The k = 0
# branch is real and the k = -1 branch is real if the LambertW argumen
# in in range [-1/e, 0]. Since `solve` does not return infinite
# solutions we will only include the -1 branch if it tests as real.
# Otherwise, inclusion of any LambertW in the solution indicates to
# the user that there are imaginary solutions corresponding to
# different k values.
lambert_real_branches = [-1, 0]
sol = []
# solution of the given Lambert equation is like
# sol = -c/b + (a/d)*LambertW(arg, k),
# where arg = d/(a*b)*exp((c*d-b*f)/a/b) and k in lambert_real_branches.
# Instead of considering the single arg, `d/(a*b)*exp((c*d-b*f)/a/b)`,
# the individual `p` roots obtained when writing `exp((c*d-b*f)/a/b)`
# as `exp(A/p) = exp(A)**(1/p)`, where `p` is an Integer, are used.
# calculating args for LambertW
num, den = ((c*d-b*f)/a/b).as_numer_denom()
p, den = den.as_coeff_Mul()
e = exp(num/den)
t = Dummy('t')
args = [d/(a*b)*t for t in roots(t**p - e, t).keys()]
# calculating solutions from args
for arg in args:
for k in lambert_real_branches:
w = LambertW(arg, k)
if k and not w.is_real:
continue
rhs = -c/b + (a/d)*w
for xu in xusolns:
sol.append(xu.subs(u, rhs))
return sol
def _solve_lambert(f, symbol, gens):
"""Return solution to ``f`` if it is a Lambert-type expression
else raise NotImplementedError.
For ``f(X, a..f) = a*log(b*X + c) + d*X - f = 0`` the solution
for ``X`` is ``X = -c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(f/a))``.
There are a variety of forms for `f(X, a..f)` as enumerated below:
1a1)
if B**B = R for R not in [0, 1] (since those cases would already
be solved before getting here) then log of both sides gives
log(B) + log(log(B)) = log(log(R)) and
X = log(B), a = 1, b = 1, c = 0, d = 1, f = log(log(R))
1a2)
if B*(b*log(B) + c)**a = R then log of both sides gives
log(B) + a*log(b*log(B) + c) = log(R) and
X = log(B), d=1, f=log(R)
1b)
if a*log(b*B + c) + d*B = R and
X = B, f = R
2a)
if (b*B + c)*exp(d*B + g) = R then log of both sides gives
log(b*B + c) + d*B + g = log(R) and
X = B, a = 1, f = log(R) - g
2b)
if g*exp(d*B + h) - b*B = c then the log form is
log(g) + d*B + h - log(b*B + c) = 0 and
X = B, a = -1, f = -h - log(g)
3)
if d*p**(a*B + g) - b*B = c then the log form is
log(d) + (a*B + g)*log(p) - log(b*B + c) = 0 and
X = B, a = -1, d = a*log(p), f = -log(d) - g*log(p)
"""
def _solve_even_degree_expr(expr, t, symbol):
"""Return the unique solutions of equations derived from
``expr`` by replacing ``t`` with ``+/- symbol``.
Parameters
==========
expr : Expr
The expression which includes a dummy variable t to be
replaced with +symbol and -symbol.
symbol : Symbol
The symbol for which a solution is being sought.
Returns
=======
List of unique solution of the two equations generated by
replacing ``t`` with positive and negative ``symbol``.
Notes
=====
If ``expr = 2*log(t) + x/2` then solutions for
``2*log(x) + x/2 = 0`` and ``2*log(-x) + x/2 = 0`` are
returned by this function. Though this may seem
counter-intuitive, one must note that the ``expr`` being
solved here has been derived from a different expression. For
an expression like ``eq = x**2*g(x) = 1``, if we take the
log of both sides we obtain ``log(x**2) + log(g(x)) = 0``. If
x is positive then this simplifies to
``2*log(x) + log(g(x)) = 0``; the Lambert-solving routines will
return solutions for this, but we must also consider the
solutions for ``2*log(-x) + log(g(x))`` since those must also
be a solution of ``eq`` which has the same value when the ``x``
in ``x**2`` is negated. If `g(x)` does not have even powers of
symbol then we do not want to replace the ``x`` there with
``-x``. So the role of the ``t`` in the expression received by
this function is to mark where ``+/-x`` should be inserted
before obtaining the Lambert solutions.
"""
nlhs, plhs = [
expr.xreplace({t: sgn*symbol}) for sgn in (-1, 1)]
sols = _solve_lambert(nlhs, symbol, gens)
if plhs != nlhs:
sols.extend(_solve_lambert(plhs, symbol, gens))
# uniq is needed for a case like
# 2*log(t) - log(-z**2) + log(z + log(x) + log(z))
# where subtituting t with +/-x gives all the same solution;
# uniq, rather than list(set()), is used to maintain canonical
# order
return list(uniq(sols))
nrhs, lhs = f.as_independent(symbol, as_Add=True)
rhs = -nrhs
lamcheck = [tmp for tmp in gens
if (tmp.func in [exp, log] or
(tmp.is_Pow and symbol in tmp.exp.free_symbols))]
if not lamcheck:
raise NotImplementedError()
if lhs.is_Add or lhs.is_Mul:
# replacing all even_degrees of symbol with dummy variable t
# since these will need special handling; non-Add/Mul do not
# need this handling
t = Dummy('t', **symbol.assumptions0)
lhs = lhs.replace(
lambda i: # find symbol**even
i.is_Pow and i.base == symbol and i.exp.is_even,
lambda i: # replace t**even
t**i.exp)
if lhs.is_Add and lhs.has(t):
t_indep = lhs.subs(t, 0)
t_term = lhs - t_indep
_rhs = rhs - t_indep
if not t_term.is_Add and _rhs and not (
t_term.has(S.ComplexInfinity, S.NaN)):
eq = expand_log(log(t_term) - log(_rhs))
return _solve_even_degree_expr(eq, t, symbol)
elif lhs.is_Mul and rhs:
# this needs to happen whether t is present or not
lhs = expand_log(log(lhs), force=True)
rhs = log(rhs)
if lhs.has(t) and lhs.is_Add:
# it expanded from Mul to Add
eq = lhs - rhs
return _solve_even_degree_expr(eq, t, symbol)
# restore symbol in lhs
lhs = lhs.xreplace({t: symbol})
lhs = powsimp(factor(lhs, deep=True))
# make sure we have inverted as completely as possible
r = Dummy()
i, lhs = _invert(lhs - r, symbol)
rhs = i.xreplace({r: rhs})
# For the first forms:
#
# 1a1) B**B = R will arrive here as B*log(B) = log(R)
# lhs is Mul so take log of both sides:
# log(B) + log(log(B)) = log(log(R))
# 1a2) B*(b*log(B) + c)**a = R will arrive unchanged so
# lhs is Mul, so take log of both sides:
# log(B) + a*log(b*log(B) + c) = log(R)
# 1b) d*log(a*B + b) + c*B = R will arrive unchanged so
# lhs is Add, so isolate c*B and expand log of both sides:
# log(c) + log(B) = log(R - d*log(a*B + b))
soln = []
if not soln:
mainlog = _mostfunc(lhs, log, symbol)
if mainlog:
if lhs.is_Mul and rhs != 0:
soln = _lambert(log(lhs) - log(rhs), symbol)
elif lhs.is_Add:
other = lhs.subs(mainlog, 0)
if other and not other.is_Add and [
tmp for tmp in other.atoms(Pow)
if symbol in tmp.free_symbols]:
if not rhs:
diff = log(other) - log(other - lhs)
else:
diff = log(lhs - other) - log(rhs - other)
soln = _lambert(expand_log(diff), symbol)
else:
#it's ready to go
soln = _lambert(lhs - rhs, symbol)
# For the next forms,
#
# collect on main exp
# 2a) (b*B + c)*exp(d*B + g) = R
# lhs is mul, so take log of both sides:
# log(b*B + c) + d*B = log(R) - g
# 2b) g*exp(d*B + h) - b*B = R
# lhs is add, so add b*B to both sides,
# take the log of both sides and rearrange to give
# log(R + b*B) - d*B = log(g) + h
if not soln:
mainexp = _mostfunc(lhs, exp, symbol)
if mainexp:
lhs = collect(lhs, mainexp)
if lhs.is_Mul and rhs != 0:
soln = _lambert(expand_log(log(lhs) - log(rhs)), symbol)
elif lhs.is_Add:
# move all but mainexp-containing term to rhs
other = lhs.subs(mainexp, 0)
mainterm = lhs - other
rhs = rhs - other
if (mainterm.could_extract_minus_sign() and
rhs.could_extract_minus_sign()):
mainterm *= -1
rhs *= -1
diff = log(mainterm) - log(rhs)
soln = _lambert(expand_log(diff), symbol)
# For the last form:
#
# 3) d*p**(a*B + g) - b*B = c
# collect on main pow, add b*B to both sides,
# take log of both sides and rearrange to give
# a*B*log(p) - log(b*B + c) = -log(d) - g*log(p)
if not soln:
mainpow = _mostfunc(lhs, Pow, symbol)
if mainpow and symbol in mainpow.exp.free_symbols:
lhs = collect(lhs, mainpow)
if lhs.is_Mul and rhs != 0:
# b*B = 0
soln = _lambert(expand_log(log(lhs) - log(rhs)), symbol)
elif lhs.is_Add:
# move all but mainpow-containing term to rhs
other = lhs.subs(mainpow, 0)
mainterm = lhs - other
rhs = rhs - other
diff = log(mainterm) - log(rhs)
soln = _lambert(expand_log(diff), symbol)
if not soln:
raise NotImplementedError('%s does not appear to have a solution in '
'terms of LambertW' % f)
return list(ordered(soln))
def bivariate_type(f, x, y, *, first=True):
"""Given an expression, f, 3 tests will be done to see what type
of composite bivariate it might be, options for u(x, y) are::
x*y
x+y
x*y+x
x*y+y
If it matches one of these types, ``u(x, y)``, ``P(u)`` and dummy
variable ``u`` will be returned. Solving ``P(u)`` for ``u`` and
equating the solutions to ``u(x, y)`` and then solving for ``x`` or
``y`` is equivalent to solving the original expression for ``x`` or
``y``. If ``x`` and ``y`` represent two functions in the same
variable, e.g. ``x = g(t)`` and ``y = h(t)``, then if ``u(x, y) - p``
can be solved for ``t`` then these represent the solutions to
``P(u) = 0`` when ``p`` are the solutions of ``P(u) = 0``.
Only positive values of ``u`` are considered.
Examples
========
>>> from sympy import solve
>>> from sympy.solvers.bivariate import bivariate_type
>>> from sympy.abc import x, y
>>> eq = (x**2 - 3).subs(x, x + y)
>>> bivariate_type(eq, x, y)
(x + y, _u**2 - 3, _u)
>>> uxy, pu, u = _
>>> usol = solve(pu, u); usol
[sqrt(3)]
>>> [solve(uxy - s) for s in solve(pu, u)]
[[{x: -y + sqrt(3)}]]
>>> all(eq.subs(s).equals(0) for sol in _ for s in sol)
True
"""
u = Dummy('u', positive=True)
if first:
p = Poly(f, x, y)
f = p.as_expr()
_x = Dummy()
_y = Dummy()
rv = bivariate_type(Poly(f.subs({x: _x, y: _y}), _x, _y), _x, _y, first=False)
if rv:
reps = {_x: x, _y: y}
return rv[0].xreplace(reps), rv[1].xreplace(reps), rv[2]
return
p = f
f = p.as_expr()
# f(x*y)
args = Add.make_args(p.as_expr())
new = []
for a in args:
a = _mexpand(a.subs(x, u/y))
free = a.free_symbols
if x in free or y in free:
break
new.append(a)
else:
return x*y, Add(*new), u
def ok(f, v, c):
new = _mexpand(f.subs(v, c))
free = new.free_symbols
return None if (x in free or y in free) else new
# f(a*x + b*y)
new = []
d = p.degree(x)
if p.degree(y) == d:
a = root(p.coeff_monomial(x**d), d)
b = root(p.coeff_monomial(y**d), d)
new = ok(f, x, (u - b*y)/a)
if new is not None:
return a*x + b*y, new, u
# f(a*x*y + b*y)
new = []
d = p.degree(x)
if p.degree(y) == d:
for itry in range(2):
a = root(p.coeff_monomial(x**d*y**d), d)
b = root(p.coeff_monomial(y**d), d)
new = ok(f, x, (u - b*y)/a/y)
if new is not None:
return a*x*y + b*y, new, u
x, y = y, x
|
ea82538352f1cb71631634c4f49f04bac94326afc8becba6616ef450bf2109fb | r"""
This module is intended for solving recurrences or, in other words,
difference equations. Currently supported are linear, inhomogeneous
equations with polynomial or rational coefficients.
The solutions are obtained among polynomials, rational functions,
hypergeometric terms, or combinations of hypergeometric term which
are pairwise dissimilar.
``rsolve_X`` functions were meant as a low level interface
for ``rsolve`` which would use Mathematica's syntax.
Given a recurrence relation:
.. math:: a_{k}(n) y(n+k) + a_{k-1}(n) y(n+k-1) +
... + a_{0}(n) y(n) = f(n)
where `k > 0` and `a_{i}(n)` are polynomials in `n`. To use
``rsolve_X`` we need to put all coefficients in to a list ``L`` of
`k+1` elements the following way:
``L = [a_{0}(n), ..., a_{k-1}(n), a_{k}(n)]``
where ``L[i]``, for `i=0, \ldots, k`, maps to
`a_{i}(n) y(n+i)` (`y(n+i)` is implicit).
For example if we would like to compute `m`-th Bernoulli polynomial
up to a constant (example was taken from rsolve_poly docstring),
then we would use `b(n+1) - b(n) = m n^{m-1}` recurrence, which
has solution `b(n) = B_m + C`.
Then ``L = [-1, 1]`` and `f(n) = m n^(m-1)` and finally for `m=4`:
>>> from sympy import Symbol, bernoulli, rsolve_poly
>>> n = Symbol('n', integer=True)
>>> rsolve_poly([-1, 1], 4*n**3, n)
C0 + n**4 - 2*n**3 + n**2
>>> bernoulli(4, n)
n**4 - 2*n**3 + n**2 - 1/30
For the sake of completeness, `f(n)` can be:
[1] a polynomial -> rsolve_poly
[2] a rational function -> rsolve_ratio
[3] a hypergeometric function -> rsolve_hyper
"""
from collections import defaultdict
from sympy.concrete import product
from sympy.core.singleton import S
from sympy.core.numbers import Rational, I
from sympy.core.symbol import Symbol, Wild, Dummy
from sympy.core.relational import Equality
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.sorting import default_sort_key
from sympy.core.sympify import sympify
from sympy.simplify import simplify, hypersimp, hypersimilar # type: ignore
from sympy.solvers import solve, solve_undetermined_coeffs
from sympy.polys import Poly, quo, gcd, lcm, roots, resultant
from sympy.functions import binomial, factorial, FallingFactorial, RisingFactorial
from sympy.matrices import Matrix, casoratian
from sympy.utilities.iterables import numbered_symbols
def rsolve_poly(coeffs, f, n, shift=0, **hints):
r"""
Given linear recurrence operator `\operatorname{L}` of order
`k` with polynomial coefficients and inhomogeneous equation
`\operatorname{L} y = f`, where `f` is a polynomial, we seek for
all polynomial solutions over field `K` of characteristic zero.
The algorithm performs two basic steps:
(1) Compute degree `N` of the general polynomial solution.
(2) Find all polynomials of degree `N` or less
of `\operatorname{L} y = f`.
There are two methods for computing the polynomial solutions.
If the degree bound is relatively small, i.e. it's smaller than
or equal to the order of the recurrence, then naive method of
undetermined coefficients is being used. This gives system
of algebraic equations with `N+1` unknowns.
In the other case, the algorithm performs transformation of the
initial equation to an equivalent one, for which the system of
algebraic equations has only `r` indeterminates. This method is
quite sophisticated (in comparison with the naive one) and was
invented together by Abramov, Bronstein and Petkovsek.
It is possible to generalize the algorithm implemented here to
the case of linear q-difference and differential equations.
Lets say that we would like to compute `m`-th Bernoulli polynomial
up to a constant. For this we can use `b(n+1) - b(n) = m n^{m-1}`
recurrence, which has solution `b(n) = B_m + C`. For example:
>>> from sympy import Symbol, rsolve_poly
>>> n = Symbol('n', integer=True)
>>> rsolve_poly([-1, 1], 4*n**3, n)
C0 + n**4 - 2*n**3 + n**2
References
==========
.. [1] S. A. Abramov, M. Bronstein and M. Petkovsek, On polynomial
solutions of linear operator equations, in: T. Levelt, ed.,
Proc. ISSAC '95, ACM Press, New York, 1995, 290-296.
.. [2] M. Petkovsek, Hypergeometric solutions of linear recurrences
with polynomial coefficients, J. Symbolic Computation,
14 (1992), 243-264.
.. [3] M. Petkovsek, H. S. Wilf, D. Zeilberger, A = B, 1996.
"""
f = sympify(f)
if not f.is_polynomial(n):
return None
homogeneous = f.is_zero
r = len(coeffs) - 1
coeffs = [Poly(coeff, n) for coeff in coeffs]
polys = [Poly(0, n)]*(r + 1)
terms = [(S.Zero, S.NegativeInfinity)]*(r + 1)
for i in range(r + 1):
for j in range(i, r + 1):
polys[i] += coeffs[j]*(binomial(j, i).as_poly(n))
if not polys[i].is_zero:
(exp,), coeff = polys[i].LT()
terms[i] = (coeff, exp)
d = b = terms[0][1]
for i in range(1, r + 1):
if terms[i][1] > d:
d = terms[i][1]
if terms[i][1] - i > b:
b = terms[i][1] - i
d, b = int(d), int(b)
x = Dummy('x')
degree_poly = S.Zero
for i in range(r + 1):
if terms[i][1] - i == b:
degree_poly += terms[i][0]*FallingFactorial(x, i)
nni_roots = list(roots(degree_poly, x, filter='Z',
predicate=lambda r: r >= 0).keys())
if nni_roots:
N = [max(nni_roots)]
else:
N = []
if homogeneous:
N += [-b - 1]
else:
N += [f.as_poly(n).degree() - b, -b - 1]
N = int(max(N))
if N < 0:
if homogeneous:
if hints.get('symbols', False):
return (S.Zero, [])
else:
return S.Zero
else:
return None
if N <= r:
C = []
y = E = S.Zero
for i in range(N + 1):
C.append(Symbol('C' + str(i + shift)))
y += C[i] * n**i
for i in range(r + 1):
E += coeffs[i].as_expr()*y.subs(n, n + i)
solutions = solve_undetermined_coeffs(E - f, C, n)
if solutions is not None:
C = [c for c in C if (c not in solutions)]
result = y.subs(solutions)
else:
return None # TBD
else:
A = r
U = N + A + b + 1
nni_roots = list(roots(polys[r], filter='Z',
predicate=lambda r: r >= 0).keys())
if nni_roots != []:
a = max(nni_roots) + 1
else:
a = S.Zero
def _zero_vector(k):
return [S.Zero] * k
def _one_vector(k):
return [S.One] * k
def _delta(p, k):
B = S.One
D = p.subs(n, a + k)
for i in range(1, k + 1):
B *= Rational(i - k - 1, i)
D += B * p.subs(n, a + k - i)
return D
alpha = {}
for i in range(-A, d + 1):
I = _one_vector(d + 1)
for k in range(1, d + 1):
I[k] = I[k - 1] * (x + i - k + 1)/k
alpha[i] = S.Zero
for j in range(A + 1):
for k in range(d + 1):
B = binomial(k, i + j)
D = _delta(polys[j].as_expr(), k)
alpha[i] += I[k]*B*D
V = Matrix(U, A, lambda i, j: int(i == j))
if homogeneous:
for i in range(A, U):
v = _zero_vector(A)
for k in range(1, A + b + 1):
if i - k < 0:
break
B = alpha[k - A].subs(x, i - k)
for j in range(A):
v[j] += B * V[i - k, j]
denom = alpha[-A].subs(x, i)
for j in range(A):
V[i, j] = -v[j] / denom
else:
G = _zero_vector(U)
for i in range(A, U):
v = _zero_vector(A)
g = S.Zero
for k in range(1, A + b + 1):
if i - k < 0:
break
B = alpha[k - A].subs(x, i - k)
for j in range(A):
v[j] += B * V[i - k, j]
g += B * G[i - k]
denom = alpha[-A].subs(x, i)
for j in range(A):
V[i, j] = -v[j] / denom
G[i] = (_delta(f, i - A) - g) / denom
P, Q = _one_vector(U), _zero_vector(A)
for i in range(1, U):
P[i] = (P[i - 1] * (n - a - i + 1)/i).expand()
for i in range(A):
Q[i] = Add(*[(v*p).expand() for v, p in zip(V[:, i], P)])
if not homogeneous:
h = Add(*[(g*p).expand() for g, p in zip(G, P)])
C = [Symbol('C' + str(i + shift)) for i in range(A)]
g = lambda i: Add(*[c*_delta(q, i) for c, q in zip(C, Q)])
if homogeneous:
E = [g(i) for i in range(N + 1, U)]
else:
E = [g(i) + _delta(h, i) for i in range(N + 1, U)]
if E != []:
solutions = solve(E, *C)
if not solutions:
if homogeneous:
if hints.get('symbols', False):
return (S.Zero, [])
else:
return S.Zero
else:
return None
else:
solutions = {}
if homogeneous:
result = S.Zero
else:
result = h
for c, q in list(zip(C, Q)):
if c in solutions:
s = solutions[c]*q
C.remove(c)
else:
s = c*q
result += s.expand()
if hints.get('symbols', False):
return (result, C)
else:
return result
def rsolve_ratio(coeffs, f, n, **hints):
r"""
Given linear recurrence operator `\operatorname{L}` of order `k`
with polynomial coefficients and inhomogeneous equation
`\operatorname{L} y = f`, where `f` is a polynomial, we seek
for all rational solutions over field `K` of characteristic zero.
This procedure accepts only polynomials, however if you are
interested in solving recurrence with rational coefficients
then use ``rsolve`` which will pre-process the given equation
and run this procedure with polynomial arguments.
The algorithm performs two basic steps:
(1) Compute polynomial `v(n)` which can be used as universal
denominator of any rational solution of equation
`\operatorname{L} y = f`.
(2) Construct new linear difference equation by substitution
`y(n) = u(n)/v(n)` and solve it for `u(n)` finding all its
polynomial solutions. Return ``None`` if none were found.
Algorithm implemented here is a revised version of the original
Abramov's algorithm, developed in 1989. The new approach is much
simpler to implement and has better overall efficiency. This
method can be easily adapted to q-difference equations case.
Besides finding rational solutions alone, this functions is
an important part of Hyper algorithm were it is used to find
particular solution of inhomogeneous part of a recurrence.
Examples
========
>>> from sympy.abc import x
>>> from sympy.solvers.recurr import rsolve_ratio
>>> rsolve_ratio([-2*x**3 + x**2 + 2*x - 1, 2*x**3 + x**2 - 6*x,
... - 2*x**3 - 11*x**2 - 18*x - 9, 2*x**3 + 13*x**2 + 22*x + 8], 0, x)
C2*(2*x - 3)/(2*(x**2 - 1))
References
==========
.. [1] S. A. Abramov, Rational solutions of linear difference
and q-difference equations with polynomial coefficients,
in: T. Levelt, ed., Proc. ISSAC '95, ACM Press, New York,
1995, 285-289
See Also
========
rsolve_hyper
"""
f = sympify(f)
if not f.is_polynomial(n):
return None
coeffs = list(map(sympify, coeffs))
r = len(coeffs) - 1
A, B = coeffs[r], coeffs[0]
A = A.subs(n, n - r).expand()
h = Dummy('h')
res = resultant(A, B.subs(n, n + h), n)
if not res.is_polynomial(h):
p, q = res.as_numer_denom()
res = quo(p, q, h)
nni_roots = list(roots(res, h, filter='Z',
predicate=lambda r: r >= 0).keys())
if not nni_roots:
return rsolve_poly(coeffs, f, n, **hints)
else:
C, numers = S.One, [S.Zero]*(r + 1)
for i in range(int(max(nni_roots)), -1, -1):
d = gcd(A, B.subs(n, n + i), n)
A = quo(A, d, n)
B = quo(B, d.subs(n, n - i), n)
C *= Mul(*[d.subs(n, n - j) for j in range(i + 1)])
denoms = [C.subs(n, n + i) for i in range(r + 1)]
for i in range(r + 1):
g = gcd(coeffs[i], denoms[i], n)
numers[i] = quo(coeffs[i], g, n)
denoms[i] = quo(denoms[i], g, n)
for i in range(r + 1):
numers[i] *= Mul(*(denoms[:i] + denoms[i + 1:]))
result = rsolve_poly(numers, f * Mul(*denoms), n, **hints)
if result is not None:
if hints.get('symbols', False):
return (simplify(result[0] / C), result[1])
else:
return simplify(result / C)
else:
return None
def rsolve_hyper(coeffs, f, n, **hints):
r"""
Given linear recurrence operator `\operatorname{L}` of order `k`
with polynomial coefficients and inhomogeneous equation
`\operatorname{L} y = f` we seek for all hypergeometric solutions
over field `K` of characteristic zero.
The inhomogeneous part can be either hypergeometric or a sum
of a fixed number of pairwise dissimilar hypergeometric terms.
The algorithm performs three basic steps:
(1) Group together similar hypergeometric terms in the
inhomogeneous part of `\operatorname{L} y = f`, and find
particular solution using Abramov's algorithm.
(2) Compute generating set of `\operatorname{L}` and find basis
in it, so that all solutions are linearly independent.
(3) Form final solution with the number of arbitrary
constants equal to dimension of basis of `\operatorname{L}`.
Term `a(n)` is hypergeometric if it is annihilated by first order
linear difference equations with polynomial coefficients or, in
simpler words, if consecutive term ratio is a rational function.
The output of this procedure is a linear combination of fixed
number of hypergeometric terms. However the underlying method
can generate larger class of solutions - D'Alembertian terms.
Note also that this method not only computes the kernel of the
inhomogeneous equation, but also reduces in to a basis so that
solutions generated by this procedure are linearly independent
Examples
========
>>> from sympy.solvers import rsolve_hyper
>>> from sympy.abc import x
>>> rsolve_hyper([-1, -1, 1], 0, x)
C0*(1/2 - sqrt(5)/2)**x + C1*(1/2 + sqrt(5)/2)**x
>>> rsolve_hyper([-1, 1], 1 + x, x)
C0 + x*(x + 1)/2
References
==========
.. [1] M. Petkovsek, Hypergeometric solutions of linear recurrences
with polynomial coefficients, J. Symbolic Computation,
14 (1992), 243-264.
.. [2] M. Petkovsek, H. S. Wilf, D. Zeilberger, A = B, 1996.
"""
coeffs = list(map(sympify, coeffs))
f = sympify(f)
r, kernel, symbols = len(coeffs) - 1, [], set()
if not f.is_zero:
if f.is_Add:
similar = {}
for g in f.expand().args:
if not g.is_hypergeometric(n):
return None
for h in similar.keys():
if hypersimilar(g, h, n):
similar[h] += g
break
else:
similar[g] = S.Zero
inhomogeneous = []
for g, h in similar.items():
inhomogeneous.append(g + h)
elif f.is_hypergeometric(n):
inhomogeneous = [f]
else:
return None
for i, g in enumerate(inhomogeneous):
coeff, polys = S.One, coeffs[:]
denoms = [S.One]*(r + 1)
s = hypersimp(g, n)
for j in range(1, r + 1):
coeff *= s.subs(n, n + j - 1)
p, q = coeff.as_numer_denom()
polys[j] *= p
denoms[j] = q
for j in range(r + 1):
polys[j] *= Mul(*(denoms[:j] + denoms[j + 1:]))
R = rsolve_poly(polys, Mul(*denoms), n)
if not (R is None or R is S.Zero):
inhomogeneous[i] *= R
else:
return None
result = Add(*inhomogeneous)
else:
result = S.Zero
Z = Dummy('Z')
p, q = coeffs[0], coeffs[r].subs(n, n - r + 1)
p_factors = [z for z in roots(p, n).keys()]
q_factors = [z for z in roots(q, n).keys()]
factors = [(S.One, S.One)]
for p in p_factors:
for q in q_factors:
if p.is_integer and q.is_integer and p <= q:
continue
else:
factors += [(n - p, n - q)]
p = [(n - p, S.One) for p in p_factors]
q = [(S.One, n - q) for q in q_factors]
factors = p + factors + q
for A, B in factors:
polys, degrees = [], []
D = A*B.subs(n, n + r - 1)
for i in range(r + 1):
a = Mul(*[A.subs(n, n + j) for j in range(i)])
b = Mul(*[B.subs(n, n + j) for j in range(i, r)])
poly = quo(coeffs[i]*a*b, D, n)
polys.append(poly.as_poly(n))
if not poly.is_zero:
degrees.append(polys[i].degree())
if degrees:
d, poly = max(degrees), S.Zero
else:
return None
for i in range(r + 1):
coeff = polys[i].nth(d)
if coeff is not S.Zero:
poly += coeff * Z**i
for z in roots(poly, Z).keys():
if z.is_zero:
continue
recurr_coeffs = [polys[i].as_expr()*z**i for i in range(r + 1)]
if d == 0 and 0 != Add(*[recurr_coeffs[j]*j for j in range(1, r + 1)]):
# faster inline check (than calling rsolve_poly) for a
# constant solution to a constant coefficient recurrence.
C = Symbol("C" + str(len(symbols)))
s = [C]
else:
C, s = rsolve_poly(recurr_coeffs, 0, n, len(symbols), symbols=True)
if C is not None and C is not S.Zero:
symbols |= set(s)
ratio = z * A * C.subs(n, n + 1) / B / C
ratio = simplify(ratio)
# If there is a nonnegative root in the denominator of the ratio,
# this indicates that the term y(n_root) is zero, and one should
# start the product with the term y(n_root + 1).
n0 = 0
for n_root in roots(ratio.as_numer_denom()[1], n).keys():
if n_root.has(I):
return None
elif (n0 < (n_root + 1)) == True:
n0 = n_root + 1
K = product(ratio, (n, n0, n - 1))
if K.has(factorial, FallingFactorial, RisingFactorial):
K = simplify(K)
if casoratian(kernel + [K], n, zero=False) != 0:
kernel.append(K)
kernel.sort(key=default_sort_key)
sk = list(zip(numbered_symbols('C'), kernel))
if sk:
for C, ker in sk:
result += C * ker
else:
return None
if hints.get('symbols', False):
# XXX: This returns the symbols in a non-deterministic order
symbols |= {s for s, k in sk}
return (result, list(symbols))
else:
return result
def rsolve(f, y, init=None):
r"""
Solve univariate recurrence with rational coefficients.
Given `k`-th order linear recurrence `\operatorname{L} y = f`,
or equivalently:
.. math:: a_{k}(n) y(n+k) + a_{k-1}(n) y(n+k-1) +
\cdots + a_{0}(n) y(n) = f(n)
where `a_{i}(n)`, for `i=0, \ldots, k`, are polynomials or rational
functions in `n`, and `f` is a hypergeometric function or a sum
of a fixed number of pairwise dissimilar hypergeometric terms in
`n`, finds all solutions or returns ``None``, if none were found.
Initial conditions can be given as a dictionary in two forms:
(1) ``{ n_0 : v_0, n_1 : v_1, ..., n_m : v_m}``
(2) ``{y(n_0) : v_0, y(n_1) : v_1, ..., y(n_m) : v_m}``
or as a list ``L`` of values:
``L = [v_0, v_1, ..., v_m]``
where ``L[i] = v_i``, for `i=0, \ldots, m`, maps to `y(n_i)`.
Examples
========
Lets consider the following recurrence:
.. math:: (n - 1) y(n + 2) - (n^2 + 3 n - 2) y(n + 1) +
2 n (n + 1) y(n) = 0
>>> from sympy import Function, rsolve
>>> from sympy.abc import n
>>> y = Function('y')
>>> f = (n - 1)*y(n + 2) - (n**2 + 3*n - 2)*y(n + 1) + 2*n*(n + 1)*y(n)
>>> rsolve(f, y(n))
2**n*C0 + C1*factorial(n)
>>> rsolve(f, y(n), {y(0):0, y(1):3})
3*2**n - 3*factorial(n)
See Also
========
rsolve_poly, rsolve_ratio, rsolve_hyper
"""
if isinstance(f, Equality):
f = f.lhs - f.rhs
n = y.args[0]
k = Wild('k', exclude=(n,))
# Preprocess user input to allow things like
# y(n) + a*(y(n + 1) + y(n - 1))/2
f = f.expand().collect(y.func(Wild('m', integer=True)))
h_part = defaultdict(list)
i_part = []
for g in Add.make_args(f):
coeff, dep = g.as_coeff_mul(y.func)
if not dep:
i_part.append(coeff)
continue
for h in dep:
if h.is_Function and h.func == y.func:
result = h.args[0].match(n + k)
if result is not None:
h_part[int(result[k])].append(coeff)
continue
raise ValueError(
"'%s(%s + k)' expected, got '%s'" % (y.func, n, h))
for k in h_part:
h_part[k] = Add(*h_part[k])
h_part.default_factory = lambda: 0
i_part = Add(*i_part)
for k, coeff in h_part.items():
h_part[k] = simplify(coeff)
common = S.One
if not i_part.is_zero and not i_part.is_hypergeometric(n) and \
not (i_part.is_Add and all(map(lambda x: x.is_hypergeometric(n), i_part.expand().args))):
raise ValueError("The independent term should be a sum of hypergeometric functions, got '%s'" % i_part)
for coeff in h_part.values():
if coeff.is_rational_function(n):
if not coeff.is_polynomial(n):
common = lcm(common, coeff.as_numer_denom()[1], n)
else:
raise ValueError(
"Polynomial or rational function expected, got '%s'" % coeff)
i_numer, i_denom = i_part.as_numer_denom()
if i_denom.is_polynomial(n):
common = lcm(common, i_denom, n)
if common is not S.One:
for k, coeff in h_part.items():
numer, denom = coeff.as_numer_denom()
h_part[k] = numer*quo(common, denom, n)
i_part = i_numer*quo(common, i_denom, n)
K_min = min(h_part.keys())
if K_min < 0:
K = abs(K_min)
H_part = defaultdict(lambda: S.Zero)
i_part = i_part.subs(n, n + K).expand()
common = common.subs(n, n + K).expand()
for k, coeff in h_part.items():
H_part[k + K] = coeff.subs(n, n + K).expand()
else:
H_part = h_part
K_max = max(H_part.keys())
coeffs = [H_part[i] for i in range(K_max + 1)]
result = rsolve_hyper(coeffs, -i_part, n, symbols=True)
if result is None:
return None
solution, symbols = result
if init in ({}, []):
init = None
if symbols and init is not None:
if isinstance(init, list):
init = {i: init[i] for i in range(len(init))}
equations = []
for k, v in init.items():
try:
i = int(k)
except TypeError:
if k.is_Function and k.func == y.func:
i = int(k.args[0])
else:
raise ValueError("Integer or term expected, got '%s'" % k)
eq = solution.subs(n, i) - v
if eq.has(S.NaN):
eq = solution.limit(n, i) - v
equations.append(eq)
result = solve(equations, *symbols)
if not result:
return None
else:
solution = solution.subs(result)
return solution
|
7564256bb869ec0e11a88d9ad2a44d40b58d3c4baeafaf250f77554f292d7415 | from sympy.core import (Function, Pow, sympify, Expr)
from sympy.core.relational import Relational
from sympy.core.singleton import S
from sympy.polys import Poly, decompose
from sympy.utilities.misc import func_name
from sympy.functions.elementary.miscellaneous import Min, Max
def decompogen(f, symbol):
"""
Computes General functional decomposition of ``f``.
Given an expression ``f``, returns a list ``[f_1, f_2, ..., f_n]``,
where::
f = f_1 o f_2 o ... f_n = f_1(f_2(... f_n))
Note: This is a General decomposition function. It also decomposes
Polynomials. For only Polynomial decomposition see ``decompose`` in polys.
Examples
========
>>> from sympy.abc import x
>>> from sympy import decompogen, sqrt, sin, cos
>>> decompogen(sin(cos(x)), x)
[sin(x), cos(x)]
>>> decompogen(sin(x)**2 + sin(x) + 1, x)
[x**2 + x + 1, sin(x)]
>>> decompogen(sqrt(6*x**2 - 5), x)
[sqrt(x), 6*x**2 - 5]
>>> decompogen(sin(sqrt(cos(x**2 + 1))), x)
[sin(x), sqrt(x), cos(x), x**2 + 1]
>>> decompogen(x**4 + 2*x**3 - x - 1, x)
[x**2 - x - 1, x**2 + x]
"""
f = sympify(f)
if not isinstance(f, Expr) or isinstance(f, Relational):
raise TypeError('expecting Expr but got: `%s`' % func_name(f))
if symbol not in f.free_symbols:
return [f]
# ===== Simple Functions ===== #
if isinstance(f, (Function, Pow)):
if f.is_Pow and f.base == S.Exp1:
arg = f.exp
else:
arg = f.args[0]
if arg == symbol:
return [f]
return [f.subs(arg, symbol)] + decompogen(arg, symbol)
# ===== Min/Max Functions ===== #
if isinstance(f, (Min, Max)):
args = list(f.args)
d0 = None
for i, a in enumerate(args):
if not a.has_free(symbol):
continue
d = decompogen(a, symbol)
if len(d) == 1:
d = [symbol] + d
if d0 is None:
d0 = d[1:]
elif d[1:] != d0:
# decomposition is not the same for each arg:
# mark as having no decomposition
d = [symbol]
break
args[i] = d[0]
if d[0] == symbol:
return [f]
return [f.func(*args)] + d0
# ===== Convert to Polynomial ===== #
fp = Poly(f)
gens = list(filter(lambda x: symbol in x.free_symbols, fp.gens))
if len(gens) == 1 and gens[0] != symbol:
f1 = f.subs(gens[0], symbol)
f2 = gens[0]
return [f1] + decompogen(f2, symbol)
# ===== Polynomial decompose() ====== #
try:
return decompose(f)
except ValueError:
return [f]
def compogen(g_s, symbol):
"""
Returns the composition of functions.
Given a list of functions ``g_s``, returns their composition ``f``,
where:
f = g_1 o g_2 o .. o g_n
Note: This is a General composition function. It also composes Polynomials.
For only Polynomial composition see ``compose`` in polys.
Examples
========
>>> from sympy.solvers.decompogen import compogen
>>> from sympy.abc import x
>>> from sympy import sqrt, sin, cos
>>> compogen([sin(x), cos(x)], x)
sin(cos(x))
>>> compogen([x**2 + x + 1, sin(x)], x)
sin(x)**2 + sin(x) + 1
>>> compogen([sqrt(x), 6*x**2 - 5], x)
sqrt(6*x**2 - 5)
>>> compogen([sin(x), sqrt(x), cos(x), x**2 + 1], x)
sin(sqrt(cos(x**2 + 1)))
>>> compogen([x**2 - x - 1, x**2 + x], x)
-x**2 - x + (x**2 + x)**2 - 1
"""
if len(g_s) == 1:
return g_s[0]
foo = g_s[0].subs(symbol, g_s[1])
if len(g_s) == 2:
return foo
return compogen([foo] + g_s[2:], symbol)
|
ef820d4d18b398c3a1fdfae85280b8a78c9cca2747d6a916c31438c35336807e | """
This module contains functions to:
- solve a single equation for a single variable, in any domain either real or complex.
- solve a single transcendental equation for a single variable in any domain either real or complex.
(currently supports solving in real domain only)
- solve a system of linear equations with N variables and M equations.
- solve a system of Non Linear Equations with N variables and M equations
"""
from sympy.core.sympify import sympify
from sympy.core import (S, Pow, Dummy, pi, Expr, Wild, Mul, Equality,
Add)
from sympy.core.containers import Tuple
from sympy.core.function import (Lambda, expand_complex, AppliedUndef,
expand_log, _mexpand, expand_trig)
from sympy.core.mod import Mod
from sympy.core.numbers import igcd, I, Number, Rational, oo, ilcm
from sympy.core.power import integer_log
from sympy.core.relational import Eq, Ne, Relational
from sympy.core.sorting import default_sort_key, ordered
from sympy.core.symbol import Symbol, _uniquely_named_symbol
from sympy.core.sympify import _sympify
from sympy.core.traversal import iterfreeargs
from sympy.simplify.simplify import simplify, fraction, trigsimp
from sympy.simplify import powdenest, logcombine
from sympy.functions import (log, tan, cot, sin, cos, sec, csc, exp,
acos, asin, acsc, asec,
piecewise_fold, Piecewise)
from sympy.functions.elementary.complexes import Abs, arg, re, im
from sympy.functions.elementary.hyperbolic import HyperbolicFunction
from sympy.functions.elementary.miscellaneous import real_root
from sympy.functions.elementary.trigonometric import TrigonometricFunction
from sympy.logic.boolalg import And, BooleanTrue
from sympy.sets import (FiniteSet, imageset, Interval, Intersection,
Union, ConditionSet, ImageSet, Complement, Contains)
from sympy.sets.sets import Set, ProductSet
from sympy.matrices import Matrix, MatrixBase
from sympy.ntheory import totient
from sympy.ntheory.factor_ import divisors
from sympy.ntheory.residue_ntheory import discrete_log, nthroot_mod
from sympy.polys import (roots, Poly, degree, together, PolynomialError,
RootOf, factor, lcm, gcd)
from sympy.polys.polyerrors import CoercionFailed
from sympy.polys.polytools import invert
from sympy.polys.solvers import (sympy_eqs_to_ring, solve_lin_sys,
PolyNonlinearError)
from sympy.polys.matrices.linsolve import _linsolve
from sympy.solvers.solvers import (checksol, denoms, unrad,
_simple_dens, recast_to_symbols)
from sympy.solvers.polysys import solve_poly_system
from sympy.utilities import filldedent
from sympy.utilities.iterables import (numbered_symbols, has_dups,
is_sequence)
from sympy.calculus.util import periodicity, continuous_domain, function_range
from types import GeneratorType
from collections import defaultdict
class NonlinearError(ValueError):
"""Raised when unexpectedly encountering nonlinear equations"""
pass
_rc = Dummy("R", real=True), Dummy("C", complex=True)
def _masked(f, *atoms):
"""Return ``f``, with all objects given by ``atoms`` replaced with
Dummy symbols, ``d``, and the list of replacements, ``(d, e)``,
where ``e`` is an object of type given by ``atoms`` in which
any other instances of atoms have been recursively replaced with
Dummy symbols, too. The tuples are ordered so that if they are
applied in sequence, the origin ``f`` will be restored.
Examples
========
>>> from sympy import cos
>>> from sympy.abc import x
>>> from sympy.solvers.solveset import _masked
>>> f = cos(cos(x) + 1)
>>> f, reps = _masked(cos(1 + cos(x)), cos)
>>> f
_a1
>>> reps
[(_a1, cos(_a0 + 1)), (_a0, cos(x))]
>>> for d, e in reps:
... f = f.xreplace({d: e})
>>> f
cos(cos(x) + 1)
"""
sym = numbered_symbols('a', cls=Dummy, real=True)
mask = []
for a in ordered(f.atoms(*atoms)):
for i in mask:
a = a.replace(*i)
mask.append((a, next(sym)))
for i, (o, n) in enumerate(mask):
f = f.replace(o, n)
mask[i] = (n, o)
mask = list(reversed(mask))
return f, mask
def _invert(f_x, y, x, domain=S.Complexes):
r"""
Reduce the complex valued equation $f(x) = y$ to a set of equations
$$\left\{g(x) = h_1(y),\ g(x) = h_2(y),\ \dots,\ g(x) = h_n(y) \right\}$$
where $g(x)$ is a simpler function than $f(x)$. The return value is a tuple
$(g(x), \mathrm{set}_h)$, where $g(x)$ is a function of $x$ and $\mathrm{set}_h$ is
the set of function $\left\{h_1(y), h_2(y), \dots, h_n(y)\right\}$.
Here, $y$ is not necessarily a symbol.
$\mathrm{set}_h$ contains the functions, along with the information
about the domain in which they are valid, through set
operations. For instance, if :math:`y = |x| - n` is inverted
in the real domain, then $\mathrm{set}_h$ is not simply
$\{-n, n\}$ as the nature of `n` is unknown; rather, it is:
$$ \left(\left[0, \infty\right) \cap \left\{n\right\}\right) \cup
\left(\left(-\infty, 0\right] \cap \left\{- n\right\}\right)$$
By default, the complex domain is used which means that inverting even
seemingly simple functions like $\exp(x)$ will give very different
results from those obtained in the real domain.
(In the case of $\exp(x)$, the inversion via $\log$ is multi-valued
in the complex domain, having infinitely many branches.)
If you are working with real values only (or you are not sure which
function to use) you should probably set the domain to
``S.Reals`` (or use ``invert_real`` which does that automatically).
Examples
========
>>> from sympy.solvers.solveset import invert_complex, invert_real
>>> from sympy.abc import x, y
>>> from sympy import exp
When does exp(x) == y?
>>> invert_complex(exp(x), y, x)
(x, ImageSet(Lambda(_n, I*(2*_n*pi + arg(y)) + log(Abs(y))), Integers))
>>> invert_real(exp(x), y, x)
(x, Intersection({log(y)}, Reals))
When does exp(x) == 1?
>>> invert_complex(exp(x), 1, x)
(x, ImageSet(Lambda(_n, 2*_n*I*pi), Integers))
>>> invert_real(exp(x), 1, x)
(x, {0})
See Also
========
invert_real, invert_complex
"""
x = sympify(x)
if not x.is_Symbol:
raise ValueError("x must be a symbol")
f_x = sympify(f_x)
if x not in f_x.free_symbols:
raise ValueError("Inverse of constant function doesn't exist")
y = sympify(y)
if x in y.free_symbols:
raise ValueError("y should be independent of x ")
if domain.is_subset(S.Reals):
x1, s = _invert_real(f_x, FiniteSet(y), x)
else:
x1, s = _invert_complex(f_x, FiniteSet(y), x)
if not isinstance(s, FiniteSet) or x1 != x:
return x1, s
# Avoid adding gratuitous intersections with S.Complexes. Actual
# conditions should be handled by the respective inverters.
if domain is S.Complexes:
return x1, s
else:
return x1, s.intersection(domain)
invert_complex = _invert
def invert_real(f_x, y, x):
"""
Inverts a real-valued function. Same as :func:`invert_complex`, but sets
the domain to ``S.Reals`` before inverting.
"""
return _invert(f_x, y, x, S.Reals)
def _invert_real(f, g_ys, symbol):
"""Helper function for _invert."""
if f == symbol or g_ys is S.EmptySet:
return (f, g_ys)
n = Dummy('n', real=True)
if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1):
return _invert_real(f.exp,
imageset(Lambda(n, log(n)), g_ys),
symbol)
if hasattr(f, 'inverse') and f.inverse() is not None and not isinstance(f, (
TrigonometricFunction,
HyperbolicFunction,
)):
if len(f.args) > 1:
raise ValueError("Only functions with one argument are supported.")
return _invert_real(f.args[0],
imageset(Lambda(n, f.inverse()(n)), g_ys),
symbol)
if isinstance(f, Abs):
return _invert_abs(f.args[0], g_ys, symbol)
if f.is_Add:
# f = g + h
g, h = f.as_independent(symbol)
if g is not S.Zero:
return _invert_real(h, imageset(Lambda(n, n - g), g_ys), symbol)
if f.is_Mul:
# f = g*h
g, h = f.as_independent(symbol)
if g is not S.One:
return _invert_real(h, imageset(Lambda(n, n/g), g_ys), symbol)
if f.is_Pow:
base, expo = f.args
base_has_sym = base.has(symbol)
expo_has_sym = expo.has(symbol)
if not expo_has_sym:
if expo.is_rational:
num, den = expo.as_numer_denom()
if den % 2 == 0 and num % 2 == 1 and den.is_zero is False:
root = Lambda(n, real_root(n, expo))
g_ys_pos = g_ys & Interval(0, oo)
res = imageset(root, g_ys_pos)
base_positive = solveset(base >= 0, symbol, S.Reals)
_inv, _set = _invert_real(base, res, symbol)
return (_inv, _set.intersect(base_positive))
if den % 2 == 1:
root = Lambda(n, real_root(n, expo))
res = imageset(root, g_ys)
if num % 2 == 0:
neg_res = imageset(Lambda(n, -n), res)
return _invert_real(base, res + neg_res, symbol)
if num % 2 == 1:
return _invert_real(base, res, symbol)
elif expo.is_irrational:
root = Lambda(n, real_root(n, expo))
g_ys_pos = g_ys & Interval(0, oo)
res = imageset(root, g_ys_pos)
return _invert_real(base, res, symbol)
else:
# indeterminate exponent, e.g. Float or parity of
# num, den of rational could not be determined
pass # use default return
if not base_has_sym:
rhs = g_ys.args[0]
if base.is_positive:
return _invert_real(expo,
imageset(Lambda(n, log(n, base, evaluate=False)), g_ys), symbol)
elif base.is_negative:
s, b = integer_log(rhs, base)
if b:
return _invert_real(expo, FiniteSet(s), symbol)
else:
return (expo, S.EmptySet)
elif base.is_zero:
one = Eq(rhs, 1)
if one == S.true:
# special case: 0**x - 1
return _invert_real(expo, FiniteSet(0), symbol)
elif one == S.false:
return (expo, S.EmptySet)
if isinstance(f, TrigonometricFunction):
if isinstance(g_ys, FiniteSet):
def inv(trig):
if isinstance(trig, (sin, csc)):
F = asin if isinstance(trig, sin) else acsc
return (lambda a: n*pi + S.NegativeOne**n*F(a),)
if isinstance(trig, (cos, sec)):
F = acos if isinstance(trig, cos) else asec
return (
lambda a: 2*n*pi + F(a),
lambda a: 2*n*pi - F(a),)
if isinstance(trig, (tan, cot)):
return (lambda a: n*pi + trig.inverse()(a),)
n = Dummy('n', integer=True)
invs = S.EmptySet
for L in inv(f):
invs += Union(*[imageset(Lambda(n, L(g)), S.Integers) for g in g_ys])
return _invert_real(f.args[0], invs, symbol)
return (f, g_ys)
def _invert_complex(f, g_ys, symbol):
"""Helper function for _invert."""
if f == symbol or g_ys is S.EmptySet:
return (f, g_ys)
n = Dummy('n')
if f.is_Add:
# f = g + h
g, h = f.as_independent(symbol)
if g is not S.Zero:
return _invert_complex(h, imageset(Lambda(n, n - g), g_ys), symbol)
if f.is_Mul:
# f = g*h
g, h = f.as_independent(symbol)
if g is not S.One:
if g in {S.NegativeInfinity, S.ComplexInfinity, S.Infinity}:
return (h, S.EmptySet)
return _invert_complex(h, imageset(Lambda(n, n/g), g_ys), symbol)
if f.is_Pow:
base, expo = f.args
# special case: g**r = 0
# Could be improved like `_invert_real` to handle more general cases.
if expo.is_Rational and g_ys == FiniteSet(0):
if expo.is_positive:
return _invert_complex(base, g_ys, symbol)
if hasattr(f, 'inverse') and f.inverse() is not None and \
not isinstance(f, TrigonometricFunction) and \
not isinstance(f, HyperbolicFunction) and \
not isinstance(f, exp):
if len(f.args) > 1:
raise ValueError("Only functions with one argument are supported.")
return _invert_complex(f.args[0],
imageset(Lambda(n, f.inverse()(n)), g_ys), symbol)
if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1):
if isinstance(g_ys, ImageSet):
# can solve upto `(d*exp(exp(...(exp(a*x + b))...) + c)` format.
# Further can be improved to `(d*exp(exp(...(exp(a*x**n + b*x**(n-1) + ... + f))...) + c)`.
g_ys_expr = g_ys.lamda.expr
g_ys_vars = g_ys.lamda.variables
k = Dummy('k{}'.format(len(g_ys_vars)))
g_ys_vars_1 = (k,) + g_ys_vars
exp_invs = Union(*[imageset(Lambda((g_ys_vars_1,), (I*(2*k*pi + arg(g_ys_expr))
+ log(Abs(g_ys_expr)))), S.Integers**(len(g_ys_vars_1)))])
return _invert_complex(f.exp, exp_invs, symbol)
elif isinstance(g_ys, FiniteSet):
exp_invs = Union(*[imageset(Lambda(n, I*(2*n*pi + arg(g_y)) +
log(Abs(g_y))), S.Integers)
for g_y in g_ys if g_y != 0])
return _invert_complex(f.exp, exp_invs, symbol)
return (f, g_ys)
def _invert_abs(f, g_ys, symbol):
"""Helper function for inverting absolute value functions.
Returns the complete result of inverting an absolute value
function along with the conditions which must also be satisfied.
If it is certain that all these conditions are met, a :class:`~.FiniteSet`
of all possible solutions is returned. If any condition cannot be
satisfied, an :class:`~.EmptySet` is returned. Otherwise, a
:class:`~.ConditionSet` of the solutions, with all the required conditions
specified, is returned.
"""
if not g_ys.is_FiniteSet:
# this could be used for FiniteSet, but the
# results are more compact if they aren't, e.g.
# ConditionSet(x, Contains(n, Interval(0, oo)), {-n, n}) vs
# Union(Intersection(Interval(0, oo), {n}), Intersection(Interval(-oo, 0), {-n}))
# for the solution of abs(x) - n
pos = Intersection(g_ys, Interval(0, S.Infinity))
parg = _invert_real(f, pos, symbol)
narg = _invert_real(-f, pos, symbol)
if parg[0] != narg[0]:
raise NotImplementedError
return parg[0], Union(narg[1], parg[1])
# check conditions: all these must be true. If any are unknown
# then return them as conditions which must be satisfied
unknown = []
for a in g_ys.args:
ok = a.is_nonnegative if a.is_Number else a.is_positive
if ok is None:
unknown.append(a)
elif not ok:
return symbol, S.EmptySet
if unknown:
conditions = And(*[Contains(i, Interval(0, oo))
for i in unknown])
else:
conditions = True
n = Dummy('n', real=True)
# this is slightly different than above: instead of solving
# +/-f on positive values, here we solve for f on +/- g_ys
g_x, values = _invert_real(f, Union(
imageset(Lambda(n, n), g_ys),
imageset(Lambda(n, -n), g_ys)), symbol)
return g_x, ConditionSet(g_x, conditions, values)
def domain_check(f, symbol, p):
"""Returns False if point p is infinite or any subexpression of f
is infinite or becomes so after replacing symbol with p. If none of
these conditions is met then True will be returned.
Examples
========
>>> from sympy import Mul, oo
>>> from sympy.abc import x
>>> from sympy.solvers.solveset import domain_check
>>> g = 1/(1 + (1/(x + 1))**2)
>>> domain_check(g, x, -1)
False
>>> domain_check(x**2, x, 0)
True
>>> domain_check(1/x, x, oo)
False
* The function relies on the assumption that the original form
of the equation has not been changed by automatic simplification.
>>> domain_check(x/x, x, 0) # x/x is automatically simplified to 1
True
* To deal with automatic evaluations use evaluate=False:
>>> domain_check(Mul(x, 1/x, evaluate=False), x, 0)
False
"""
f, p = sympify(f), sympify(p)
if p.is_infinite:
return False
return _domain_check(f, symbol, p)
def _domain_check(f, symbol, p):
# helper for domain check
if f.is_Atom and f.is_finite:
return True
elif f.subs(symbol, p).is_infinite:
return False
elif isinstance(f, Piecewise):
# Check the cases of the Piecewise in turn. There might be invalid
# expressions in later cases that don't apply e.g.
# solveset(Piecewise((0, Eq(x, 0)), (1/x, True)), x)
for expr, cond in f.args:
condsubs = cond.subs(symbol, p)
if condsubs is S.false:
continue
elif condsubs is S.true:
return _domain_check(expr, symbol, p)
else:
# We don't know which case of the Piecewise holds. On this
# basis we cannot decide whether any solution is in or out of
# the domain. Ideally this function would allow returning a
# symbolic condition for the validity of the solution that
# could be handled in the calling code. In the mean time we'll
# give this particular solution the benefit of the doubt and
# let it pass.
return True
else:
# TODO : We should not blindly recurse through all args of arbitrary expressions like this
return all(_domain_check(g, symbol, p)
for g in f.args)
def _is_finite_with_finite_vars(f, domain=S.Complexes):
"""
Return True if the given expression is finite. For symbols that
do not assign a value for `complex` and/or `real`, the domain will
be used to assign a value; symbols that do not assign a value
for `finite` will be made finite. All other assumptions are
left unmodified.
"""
def assumptions(s):
A = s.assumptions0
A.setdefault('finite', A.get('finite', True))
if domain.is_subset(S.Reals):
# if this gets set it will make complex=True, too
A.setdefault('real', True)
else:
# don't change 'real' because being complex implies
# nothing about being real
A.setdefault('complex', True)
return A
reps = {s: Dummy(**assumptions(s)) for s in f.free_symbols}
return f.xreplace(reps).is_finite
def _is_function_class_equation(func_class, f, symbol):
""" Tests whether the equation is an equation of the given function class.
The given equation belongs to the given function class if it is
comprised of functions of the function class which are multiplied by
or added to expressions independent of the symbol. In addition, the
arguments of all such functions must be linear in the symbol as well.
Examples
========
>>> from sympy.solvers.solveset import _is_function_class_equation
>>> from sympy import tan, sin, tanh, sinh, exp
>>> from sympy.abc import x
>>> from sympy.functions.elementary.trigonometric import TrigonometricFunction
>>> from sympy.functions.elementary.hyperbolic import HyperbolicFunction
>>> _is_function_class_equation(TrigonometricFunction, exp(x) + tan(x), x)
False
>>> _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x), x)
True
>>> _is_function_class_equation(TrigonometricFunction, tan(x**2), x)
False
>>> _is_function_class_equation(TrigonometricFunction, tan(x + 2), x)
True
>>> _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x), x)
True
"""
if f.is_Mul or f.is_Add:
return all(_is_function_class_equation(func_class, arg, symbol)
for arg in f.args)
if f.is_Pow:
if not f.exp.has(symbol):
return _is_function_class_equation(func_class, f.base, symbol)
else:
return False
if not f.has(symbol):
return True
if isinstance(f, func_class):
try:
g = Poly(f.args[0], symbol)
return g.degree() <= 1
except PolynomialError:
return False
else:
return False
def _solve_as_rational(f, symbol, domain):
""" solve rational functions"""
f = together(_mexpand(f, recursive=True), deep=True)
g, h = fraction(f)
if not h.has(symbol):
try:
return _solve_as_poly(g, symbol, domain)
except NotImplementedError:
# The polynomial formed from g could end up having
# coefficients in a ring over which finding roots
# isn't implemented yet, e.g. ZZ[a] for some symbol a
return ConditionSet(symbol, Eq(f, 0), domain)
except CoercionFailed:
# contained oo, zoo or nan
return S.EmptySet
else:
valid_solns = _solveset(g, symbol, domain)
invalid_solns = _solveset(h, symbol, domain)
return valid_solns - invalid_solns
class _SolveTrig1Error(Exception):
"""Raised when _solve_trig1 heuristics do not apply"""
def _solve_trig(f, symbol, domain):
"""Function to call other helpers to solve trigonometric equations """
sol = None
try:
sol = _solve_trig1(f, symbol, domain)
except _SolveTrig1Error:
try:
sol = _solve_trig2(f, symbol, domain)
except ValueError:
raise NotImplementedError(filldedent('''
Solution to this kind of trigonometric equations
is yet to be implemented'''))
return sol
def _solve_trig1(f, symbol, domain):
"""Primary solver for trigonometric and hyperbolic equations
Returns either the solution set as a ConditionSet (auto-evaluated to a
union of ImageSets if no variables besides 'symbol' are involved) or
raises _SolveTrig1Error if f == 0 cannot be solved.
Notes
=====
Algorithm:
1. Do a change of variable x -> mu*x in arguments to trigonometric and
hyperbolic functions, in order to reduce them to small integers. (This
step is crucial to keep the degrees of the polynomials of step 4 low.)
2. Rewrite trigonometric/hyperbolic functions as exponentials.
3. Proceed to a 2nd change of variable, replacing exp(I*x) or exp(x) by y.
4. Solve the resulting rational equation.
5. Use invert_complex or invert_real to return to the original variable.
6. If the coefficients of 'symbol' were symbolic in nature, add the
necessary consistency conditions in a ConditionSet.
"""
# Prepare change of variable
x = Dummy('x')
if _is_function_class_equation(HyperbolicFunction, f, symbol):
cov = exp(x)
inverter = invert_real if domain.is_subset(S.Reals) else invert_complex
else:
cov = exp(I*x)
inverter = invert_complex
f = trigsimp(f)
f_original = f
trig_functions = f.atoms(TrigonometricFunction, HyperbolicFunction)
trig_arguments = [e.args[0] for e in trig_functions]
# trigsimp may have reduced the equation to an expression
# that is independent of 'symbol' (e.g. cos**2+sin**2)
if not any(a.has(symbol) for a in trig_arguments):
return solveset(f_original, symbol, domain)
denominators = []
numerators = []
for ar in trig_arguments:
try:
poly_ar = Poly(ar, symbol)
except PolynomialError:
raise _SolveTrig1Error("trig argument is not a polynomial")
if poly_ar.degree() > 1: # degree >1 still bad
raise _SolveTrig1Error("degree of variable must not exceed one")
if poly_ar.degree() == 0: # degree 0, don't care
continue
c = poly_ar.all_coeffs()[0] # got the coefficient of 'symbol'
numerators.append(fraction(c)[0])
denominators.append(fraction(c)[1])
mu = lcm(denominators)/gcd(numerators)
f = f.subs(symbol, mu*x)
f = f.rewrite(exp)
f = together(f)
g, h = fraction(f)
y = Dummy('y')
g, h = g.expand(), h.expand()
g, h = g.subs(cov, y), h.subs(cov, y)
if g.has(x) or h.has(x):
raise _SolveTrig1Error("change of variable not possible")
solns = solveset_complex(g, y) - solveset_complex(h, y)
if isinstance(solns, ConditionSet):
raise _SolveTrig1Error("polynomial has ConditionSet solution")
if isinstance(solns, FiniteSet):
if any(isinstance(s, RootOf) for s in solns):
raise _SolveTrig1Error("polynomial results in RootOf object")
# revert the change of variable
cov = cov.subs(x, symbol/mu)
result = Union(*[inverter(cov, s, symbol)[1] for s in solns])
# In case of symbolic coefficients, the solution set is only valid
# if numerator and denominator of mu are non-zero.
if mu.has(Symbol):
syms = (mu).atoms(Symbol)
munum, muden = fraction(mu)
condnum = munum.as_independent(*syms, as_Add=False)[1]
condden = muden.as_independent(*syms, as_Add=False)[1]
cond = And(Ne(condnum, 0), Ne(condden, 0))
else:
cond = True
# Actual conditions are returned as part of the ConditionSet. Adding an
# intersection with C would only complicate some solution sets due to
# current limitations of intersection code. (e.g. #19154)
if domain is S.Complexes:
# This is a slight abuse of ConditionSet. Ideally this should
# be some kind of "PiecewiseSet". (See #19507 discussion)
return ConditionSet(symbol, cond, result)
else:
return ConditionSet(symbol, cond, Intersection(result, domain))
elif solns is S.EmptySet:
return S.EmptySet
else:
raise _SolveTrig1Error("polynomial solutions must form FiniteSet")
def _solve_trig2(f, symbol, domain):
"""Secondary helper to solve trigonometric equations,
called when first helper fails """
f = trigsimp(f)
f_original = f
trig_functions = f.atoms(sin, cos, tan, sec, cot, csc)
trig_arguments = [e.args[0] for e in trig_functions]
denominators = []
numerators = []
# todo: This solver can be extended to hyperbolics if the
# analogous change of variable to tanh (instead of tan)
# is used.
if not trig_functions:
return ConditionSet(symbol, Eq(f_original, 0), domain)
# todo: The pre-processing below (extraction of numerators, denominators,
# gcd, lcm, mu, etc.) should be updated to the enhanced version in
# _solve_trig1. (See #19507)
for ar in trig_arguments:
try:
poly_ar = Poly(ar, symbol)
except PolynomialError:
raise ValueError("give up, we cannot solve if this is not a polynomial in x")
if poly_ar.degree() > 1: # degree >1 still bad
raise ValueError("degree of variable inside polynomial should not exceed one")
if poly_ar.degree() == 0: # degree 0, don't care
continue
c = poly_ar.all_coeffs()[0] # got the coefficient of 'symbol'
try:
numerators.append(Rational(c).p)
denominators.append(Rational(c).q)
except TypeError:
return ConditionSet(symbol, Eq(f_original, 0), domain)
x = Dummy('x')
# ilcm() and igcd() require more than one argument
if len(numerators) > 1:
mu = Rational(2)*ilcm(*denominators)/igcd(*numerators)
else:
assert len(numerators) == 1
mu = Rational(2)*denominators[0]/numerators[0]
f = f.subs(symbol, mu*x)
f = f.rewrite(tan)
f = expand_trig(f)
f = together(f)
g, h = fraction(f)
y = Dummy('y')
g, h = g.expand(), h.expand()
g, h = g.subs(tan(x), y), h.subs(tan(x), y)
if g.has(x) or h.has(x):
return ConditionSet(symbol, Eq(f_original, 0), domain)
solns = solveset(g, y, S.Reals) - solveset(h, y, S.Reals)
if isinstance(solns, FiniteSet):
result = Union(*[invert_real(tan(symbol/mu), s, symbol)[1]
for s in solns])
dsol = invert_real(tan(symbol/mu), oo, symbol)[1]
if degree(h) > degree(g): # If degree(denom)>degree(num) then there
result = Union(result, dsol) # would be another sol at Lim(denom-->oo)
return Intersection(result, domain)
elif solns is S.EmptySet:
return S.EmptySet
else:
return ConditionSet(symbol, Eq(f_original, 0), S.Reals)
def _solve_as_poly(f, symbol, domain=S.Complexes):
"""
Solve the equation using polynomial techniques if it already is a
polynomial equation or, with a change of variables, can be made so.
"""
result = None
if f.is_polynomial(symbol):
solns = roots(f, symbol, cubics=True, quartics=True,
quintics=True, domain='EX')
num_roots = sum(solns.values())
if degree(f, symbol) <= num_roots:
result = FiniteSet(*solns.keys())
else:
poly = Poly(f, symbol)
solns = poly.all_roots()
if poly.degree() <= len(solns):
result = FiniteSet(*solns)
else:
result = ConditionSet(symbol, Eq(f, 0), domain)
else:
poly = Poly(f)
if poly is None:
result = ConditionSet(symbol, Eq(f, 0), domain)
gens = [g for g in poly.gens if g.has(symbol)]
if len(gens) == 1:
poly = Poly(poly, gens[0])
gen = poly.gen
deg = poly.degree()
poly = Poly(poly.as_expr(), poly.gen, composite=True)
poly_solns = FiniteSet(*roots(poly, cubics=True, quartics=True,
quintics=True).keys())
if len(poly_solns) < deg:
result = ConditionSet(symbol, Eq(f, 0), domain)
if gen != symbol:
y = Dummy('y')
inverter = invert_real if domain.is_subset(S.Reals) else invert_complex
lhs, rhs_s = inverter(gen, y, symbol)
if lhs == symbol:
result = Union(*[rhs_s.subs(y, s) for s in poly_solns])
else:
result = ConditionSet(symbol, Eq(f, 0), domain)
else:
result = ConditionSet(symbol, Eq(f, 0), domain)
if result is not None:
if isinstance(result, FiniteSet):
# this is to simplify solutions like -sqrt(-I) to sqrt(2)/2
# - sqrt(2)*I/2. We are not expanding for solution with symbols
# or undefined functions because that makes the solution more complicated.
# For example, expand_complex(a) returns re(a) + I*im(a)
if all(s.atoms(Symbol, AppliedUndef) == set() and not isinstance(s, RootOf)
for s in result):
s = Dummy('s')
result = imageset(Lambda(s, expand_complex(s)), result)
if isinstance(result, FiniteSet) and domain != S.Complexes:
# Avoid adding gratuitous intersections with S.Complexes. Actual
# conditions should be handled elsewhere.
result = result.intersection(domain)
return result
else:
return ConditionSet(symbol, Eq(f, 0), domain)
def _solve_radical(f, unradf, symbol, solveset_solver):
""" Helper function to solve equations with radicals """
res = unradf
eq, cov = res if res else (f, [])
if not cov:
result = solveset_solver(eq, symbol) - \
Union(*[solveset_solver(g, symbol) for g in denoms(f, symbol)])
else:
y, yeq = cov
if not solveset_solver(y - I, y):
yreal = Dummy('yreal', real=True)
yeq = yeq.xreplace({y: yreal})
eq = eq.xreplace({y: yreal})
y = yreal
g_y_s = solveset_solver(yeq, symbol)
f_y_sols = solveset_solver(eq, y)
result = Union(*[imageset(Lambda(y, g_y), f_y_sols)
for g_y in g_y_s])
if not isinstance(result, FiniteSet):
solution_set = result
else:
f_set = [] # solutions for FiniteSet
c_set = [] # solutions for ConditionSet
for s in result:
if checksol(f, symbol, s):
f_set.append(s)
else:
c_set.append(s)
solution_set = FiniteSet(*f_set) + ConditionSet(symbol, Eq(f, 0), FiniteSet(*c_set))
return solution_set
def _solve_abs(f, symbol, domain):
""" Helper function to solve equation involving absolute value function """
if not domain.is_subset(S.Reals):
raise ValueError(filldedent('''
Absolute values cannot be inverted in the
complex domain.'''))
p, q, r = Wild('p'), Wild('q'), Wild('r')
pattern_match = f.match(p*Abs(q) + r) or {}
f_p, f_q, f_r = [pattern_match.get(i, S.Zero) for i in (p, q, r)]
if not (f_p.is_zero or f_q.is_zero):
domain = continuous_domain(f_q, symbol, domain)
from .inequalities import solve_univariate_inequality
q_pos_cond = solve_univariate_inequality(f_q >= 0, symbol,
relational=False, domain=domain, continuous=True)
q_neg_cond = q_pos_cond.complement(domain)
sols_q_pos = solveset_real(f_p*f_q + f_r,
symbol).intersect(q_pos_cond)
sols_q_neg = solveset_real(f_p*(-f_q) + f_r,
symbol).intersect(q_neg_cond)
return Union(sols_q_pos, sols_q_neg)
else:
return ConditionSet(symbol, Eq(f, 0), domain)
def solve_decomposition(f, symbol, domain):
"""
Function to solve equations via the principle of "Decomposition
and Rewriting".
Examples
========
>>> from sympy import exp, sin, Symbol, pprint, S
>>> from sympy.solvers.solveset import solve_decomposition as sd
>>> x = Symbol('x')
>>> f1 = exp(2*x) - 3*exp(x) + 2
>>> sd(f1, x, S.Reals)
{0, log(2)}
>>> f2 = sin(x)**2 + 2*sin(x) + 1
>>> pprint(sd(f2, x, S.Reals), use_unicode=False)
3*pi
{2*n*pi + ---- | n in Integers}
2
>>> f3 = sin(x + 2)
>>> pprint(sd(f3, x, S.Reals), use_unicode=False)
{2*n*pi - 2 | n in Integers} U {2*n*pi - 2 + pi | n in Integers}
"""
from sympy.solvers.decompogen import decompogen
# decompose the given function
g_s = decompogen(f, symbol)
# `y_s` represents the set of values for which the function `g` is to be
# solved.
# `solutions` represent the solutions of the equations `g = y_s` or
# `g = 0` depending on the type of `y_s`.
# As we are interested in solving the equation: f = 0
y_s = FiniteSet(0)
for g in g_s:
frange = function_range(g, symbol, domain)
y_s = Intersection(frange, y_s)
result = S.EmptySet
if isinstance(y_s, FiniteSet):
for y in y_s:
solutions = solveset(Eq(g, y), symbol, domain)
if not isinstance(solutions, ConditionSet):
result += solutions
else:
if isinstance(y_s, ImageSet):
iter_iset = (y_s,)
elif isinstance(y_s, Union):
iter_iset = y_s.args
elif y_s is S.EmptySet:
# y_s is not in the range of g in g_s, so no solution exists
#in the given domain
return S.EmptySet
for iset in iter_iset:
new_solutions = solveset(Eq(iset.lamda.expr, g), symbol, domain)
dummy_var = tuple(iset.lamda.expr.free_symbols)[0]
(base_set,) = iset.base_sets
if isinstance(new_solutions, FiniteSet):
new_exprs = new_solutions
elif isinstance(new_solutions, Intersection):
if isinstance(new_solutions.args[1], FiniteSet):
new_exprs = new_solutions.args[1]
for new_expr in new_exprs:
result += ImageSet(Lambda(dummy_var, new_expr), base_set)
if result is S.EmptySet:
return ConditionSet(symbol, Eq(f, 0), domain)
y_s = result
return y_s
def _solveset(f, symbol, domain, _check=False):
"""Helper for solveset to return a result from an expression
that has already been sympify'ed and is known to contain the
given symbol."""
# _check controls whether the answer is checked or not
from sympy.simplify.simplify import signsimp
if isinstance(f, BooleanTrue):
return domain
orig_f = f
if f.is_Mul:
coeff, f = f.as_independent(symbol, as_Add=False)
if coeff in {S.ComplexInfinity, S.NegativeInfinity, S.Infinity}:
f = together(orig_f)
elif f.is_Add:
a, h = f.as_independent(symbol)
m, h = h.as_independent(symbol, as_Add=False)
if m not in {S.ComplexInfinity, S.Zero, S.Infinity,
S.NegativeInfinity}:
f = a/m + h # XXX condition `m != 0` should be added to soln
# assign the solvers to use
solver = lambda f, x, domain=domain: _solveset(f, x, domain)
inverter = lambda f, rhs, symbol: _invert(f, rhs, symbol, domain)
result = S.EmptySet
if f.expand().is_zero:
return domain
elif not f.has(symbol):
return S.EmptySet
elif f.is_Mul and all(_is_finite_with_finite_vars(m, domain)
for m in f.args):
# if f(x) and g(x) are both finite we can say that the solution of
# f(x)*g(x) == 0 is same as Union(f(x) == 0, g(x) == 0) is not true in
# general. g(x) can grow to infinitely large for the values where
# f(x) == 0. To be sure that we are not silently allowing any
# wrong solutions we are using this technique only if both f and g are
# finite for a finite input.
result = Union(*[solver(m, symbol) for m in f.args])
elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \
_is_function_class_equation(HyperbolicFunction, f, symbol):
result = _solve_trig(f, symbol, domain)
elif isinstance(f, arg):
a = f.args[0]
result = Intersection(_solveset(re(a) > 0, symbol, domain),
_solveset(im(a), symbol, domain))
elif f.is_Piecewise:
expr_set_pairs = f.as_expr_set_pairs(domain)
for (expr, in_set) in expr_set_pairs:
if in_set.is_Relational:
in_set = in_set.as_set()
solns = solver(expr, symbol, in_set)
result += solns
elif isinstance(f, Eq):
result = solver(Add(f.lhs, - f.rhs, evaluate=False), symbol, domain)
elif f.is_Relational:
from .inequalities import solve_univariate_inequality
try:
result = solve_univariate_inequality(
f, symbol, domain=domain, relational=False)
except NotImplementedError:
result = ConditionSet(symbol, f, domain)
return result
elif _is_modular(f, symbol):
result = _solve_modular(f, symbol, domain)
else:
lhs, rhs_s = inverter(f, 0, symbol)
if lhs == symbol:
# do some very minimal simplification since
# repeated inversion may have left the result
# in a state that other solvers (e.g. poly)
# would have simplified; this is done here
# rather than in the inverter since here it
# is only done once whereas there it would
# be repeated for each step of the inversion
if isinstance(rhs_s, FiniteSet):
rhs_s = FiniteSet(*[Mul(*
signsimp(i).as_content_primitive())
for i in rhs_s])
result = rhs_s
elif isinstance(rhs_s, FiniteSet):
for equation in [lhs - rhs for rhs in rhs_s]:
if equation == f:
u = unrad(f, symbol)
if u:
result += _solve_radical(equation, u,
symbol,
solver)
elif equation.has(Abs):
result += _solve_abs(f, symbol, domain)
else:
result_rational = _solve_as_rational(equation, symbol, domain)
if not isinstance(result_rational, ConditionSet):
result += result_rational
else:
# may be a transcendental type equation
t_result = _transolve(equation, symbol, domain)
if isinstance(t_result, ConditionSet):
# might need factoring; this is expensive so we
# have delayed until now. To avoid recursion
# errors look for a non-trivial factoring into
# a product of symbol dependent terms; I think
# that something that factors as a Pow would
# have already been recognized by now.
factored = equation.factor()
if factored.is_Mul and equation != factored:
_, dep = factored.as_independent(symbol)
if not dep.is_Add:
# non-trivial factoring of equation
# but use form with constants
# in case they need special handling
t_result = solver(factored, symbol)
result += t_result
else:
result += solver(equation, symbol)
elif rhs_s is not S.EmptySet:
result = ConditionSet(symbol, Eq(f, 0), domain)
if isinstance(result, ConditionSet):
if isinstance(f, Expr):
num, den = f.as_numer_denom()
if den.has(symbol):
_result = _solveset(num, symbol, domain)
if not isinstance(_result, ConditionSet):
singularities = _solveset(den, symbol, domain)
result = _result - singularities
if _check:
if isinstance(result, ConditionSet):
# it wasn't solved or has enumerated all conditions
# -- leave it alone
return result
# whittle away all but the symbol-containing core
# to use this for testing
if isinstance(orig_f, Expr):
fx = orig_f.as_independent(symbol, as_Add=True)[1]
fx = fx.as_independent(symbol, as_Add=False)[1]
else:
fx = orig_f
if isinstance(result, FiniteSet):
# check the result for invalid solutions
result = FiniteSet(*[s for s in result
if isinstance(s, RootOf)
or domain_check(fx, symbol, s)])
return result
def _is_modular(f, symbol):
"""
Helper function to check below mentioned types of modular equations.
``A - Mod(B, C) = 0``
A -> This can or cannot be a function of symbol.
B -> This is surely a function of symbol.
C -> It is an integer.
Parameters
==========
f : Expr
The equation to be checked.
symbol : Symbol
The concerned variable for which the equation is to be checked.
Examples
========
>>> from sympy import symbols, exp, Mod
>>> from sympy.solvers.solveset import _is_modular as check
>>> x, y = symbols('x y')
>>> check(Mod(x, 3) - 1, x)
True
>>> check(Mod(x, 3) - 1, y)
False
>>> check(Mod(x, 3)**2 - 5, x)
False
>>> check(Mod(x, 3)**2 - y, x)
False
>>> check(exp(Mod(x, 3)) - 1, x)
False
>>> check(Mod(3, y) - 1, y)
False
"""
if not f.has(Mod):
return False
# extract modterms from f.
modterms = list(f.atoms(Mod))
return (len(modterms) == 1 and # only one Mod should be present
modterms[0].args[0].has(symbol) and # B-> function of symbol
modterms[0].args[1].is_integer and # C-> to be an integer.
any(isinstance(term, Mod)
for term in list(_term_factors(f))) # free from other funcs
)
def _invert_modular(modterm, rhs, n, symbol):
"""
Helper function to invert modular equation.
``Mod(a, m) - rhs = 0``
Generally it is inverted as (a, ImageSet(Lambda(n, m*n + rhs), S.Integers)).
More simplified form will be returned if possible.
If it is not invertible then (modterm, rhs) is returned.
The following cases arise while inverting equation ``Mod(a, m) - rhs = 0``:
1. If a is symbol then m*n + rhs is the required solution.
2. If a is an instance of ``Add`` then we try to find two symbol independent
parts of a and the symbol independent part gets tranferred to the other
side and again the ``_invert_modular`` is called on the symbol
dependent part.
3. If a is an instance of ``Mul`` then same as we done in ``Add`` we separate
out the symbol dependent and symbol independent parts and transfer the
symbol independent part to the rhs with the help of invert and again the
``_invert_modular`` is called on the symbol dependent part.
4. If a is an instance of ``Pow`` then two cases arise as following:
- If a is of type (symbol_indep)**(symbol_dep) then the remainder is
evaluated with the help of discrete_log function and then the least
period is being found out with the help of totient function.
period*n + remainder is the required solution in this case.
For reference: (https://en.wikipedia.org/wiki/Euler's_theorem)
- If a is of type (symbol_dep)**(symbol_indep) then we try to find all
primitive solutions list with the help of nthroot_mod function.
m*n + rem is the general solution where rem belongs to solutions list
from nthroot_mod function.
Parameters
==========
modterm, rhs : Expr
The modular equation to be inverted, ``modterm - rhs = 0``
symbol : Symbol
The variable in the equation to be inverted.
n : Dummy
Dummy variable for output g_n.
Returns
=======
A tuple (f_x, g_n) is being returned where f_x is modular independent function
of symbol and g_n being set of values f_x can have.
Examples
========
>>> from sympy import symbols, exp, Mod, Dummy, S
>>> from sympy.solvers.solveset import _invert_modular as invert_modular
>>> x, y = symbols('x y')
>>> n = Dummy('n')
>>> invert_modular(Mod(exp(x), 7), S(5), n, x)
(Mod(exp(x), 7), 5)
>>> invert_modular(Mod(x, 7), S(5), n, x)
(x, ImageSet(Lambda(_n, 7*_n + 5), Integers))
>>> invert_modular(Mod(3*x + 8, 7), S(5), n, x)
(x, ImageSet(Lambda(_n, 7*_n + 6), Integers))
>>> invert_modular(Mod(x**4, 7), S(5), n, x)
(x, EmptySet)
>>> invert_modular(Mod(2**(x**2 + x + 1), 7), S(2), n, x)
(x**2 + x + 1, ImageSet(Lambda(_n, 3*_n + 1), Naturals0))
"""
a, m = modterm.args
if rhs.is_real is False or any(term.is_real is False
for term in list(_term_factors(a))):
# Check for complex arguments
return modterm, rhs
if abs(rhs) >= abs(m):
# if rhs has value greater than value of m.
return symbol, S.EmptySet
if a == symbol:
return symbol, ImageSet(Lambda(n, m*n + rhs), S.Integers)
if a.is_Add:
# g + h = a
g, h = a.as_independent(symbol)
if g is not S.Zero:
x_indep_term = rhs - Mod(g, m)
return _invert_modular(Mod(h, m), Mod(x_indep_term, m), n, symbol)
if a.is_Mul:
# g*h = a
g, h = a.as_independent(symbol)
if g is not S.One:
x_indep_term = rhs*invert(g, m)
return _invert_modular(Mod(h, m), Mod(x_indep_term, m), n, symbol)
if a.is_Pow:
# base**expo = a
base, expo = a.args
if expo.has(symbol) and not base.has(symbol):
# remainder -> solution independent of n of equation.
# m, rhs are made coprime by dividing igcd(m, rhs)
try:
remainder = discrete_log(m / igcd(m, rhs), rhs, a.base)
except ValueError: # log does not exist
return modterm, rhs
# period -> coefficient of n in the solution and also referred as
# the least period of expo in which it is repeats itself.
# (a**(totient(m)) - 1) divides m. Here is link of theorem:
# (https://en.wikipedia.org/wiki/Euler's_theorem)
period = totient(m)
for p in divisors(period):
# there might a lesser period exist than totient(m).
if pow(a.base, p, m / igcd(m, a.base)) == 1:
period = p
break
# recursion is not applied here since _invert_modular is currently
# not smart enough to handle infinite rhs as here expo has infinite
# rhs = ImageSet(Lambda(n, period*n + remainder), S.Naturals0).
return expo, ImageSet(Lambda(n, period*n + remainder), S.Naturals0)
elif base.has(symbol) and not expo.has(symbol):
try:
remainder_list = nthroot_mod(rhs, expo, m, all_roots=True)
if remainder_list == []:
return symbol, S.EmptySet
except (ValueError, NotImplementedError):
return modterm, rhs
g_n = S.EmptySet
for rem in remainder_list:
g_n += ImageSet(Lambda(n, m*n + rem), S.Integers)
return base, g_n
return modterm, rhs
def _solve_modular(f, symbol, domain):
r"""
Helper function for solving modular equations of type ``A - Mod(B, C) = 0``,
where A can or cannot be a function of symbol, B is surely a function of
symbol and C is an integer.
Currently ``_solve_modular`` is only able to solve cases
where A is not a function of symbol.
Parameters
==========
f : Expr
The modular equation to be solved, ``f = 0``
symbol : Symbol
The variable in the equation to be solved.
domain : Set
A set over which the equation is solved. It has to be a subset of
Integers.
Returns
=======
A set of integer solutions satisfying the given modular equation.
A ``ConditionSet`` if the equation is unsolvable.
Examples
========
>>> from sympy.solvers.solveset import _solve_modular as solve_modulo
>>> from sympy import S, Symbol, sin, Intersection, Interval, Mod
>>> x = Symbol('x')
>>> solve_modulo(Mod(5*x - 8, 7) - 3, x, S.Integers)
ImageSet(Lambda(_n, 7*_n + 5), Integers)
>>> solve_modulo(Mod(5*x - 8, 7) - 3, x, S.Reals) # domain should be subset of integers.
ConditionSet(x, Eq(Mod(5*x + 6, 7) - 3, 0), Reals)
>>> solve_modulo(-7 + Mod(x, 5), x, S.Integers)
EmptySet
>>> solve_modulo(Mod(12**x, 21) - 18, x, S.Integers)
ImageSet(Lambda(_n, 6*_n + 2), Naturals0)
>>> solve_modulo(Mod(sin(x), 7) - 3, x, S.Integers) # not solvable
ConditionSet(x, Eq(Mod(sin(x), 7) - 3, 0), Integers)
>>> solve_modulo(3 - Mod(x, 5), x, Intersection(S.Integers, Interval(0, 100)))
Intersection(ImageSet(Lambda(_n, 5*_n + 3), Integers), Range(0, 101, 1))
"""
# extract modterm and g_y from f
unsolved_result = ConditionSet(symbol, Eq(f, 0), domain)
modterm = list(f.atoms(Mod))[0]
rhs = -S.One*(f.subs(modterm, S.Zero))
if f.as_coefficients_dict()[modterm].is_negative:
# checks if coefficient of modterm is negative in main equation.
rhs *= -S.One
if not domain.is_subset(S.Integers):
return unsolved_result
if rhs.has(symbol):
# TODO Case: A-> function of symbol, can be extended here
# in future.
return unsolved_result
n = Dummy('n', integer=True)
f_x, g_n = _invert_modular(modterm, rhs, n, symbol)
if f_x == modterm and g_n == rhs:
return unsolved_result
if f_x == symbol:
if domain is not S.Integers:
return domain.intersect(g_n)
return g_n
if isinstance(g_n, ImageSet):
lamda_expr = g_n.lamda.expr
lamda_vars = g_n.lamda.variables
base_sets = g_n.base_sets
sol_set = _solveset(f_x - lamda_expr, symbol, S.Integers)
if isinstance(sol_set, FiniteSet):
tmp_sol = S.EmptySet
for sol in sol_set:
tmp_sol += ImageSet(Lambda(lamda_vars, sol), *base_sets)
sol_set = tmp_sol
else:
sol_set = ImageSet(Lambda(lamda_vars, sol_set), *base_sets)
return domain.intersect(sol_set)
return unsolved_result
def _term_factors(f):
"""
Iterator to get the factors of all terms present
in the given equation.
Parameters
==========
f : Expr
Equation that needs to be addressed
Returns
=======
Factors of all terms present in the equation.
Examples
========
>>> from sympy import symbols
>>> from sympy.solvers.solveset import _term_factors
>>> x = symbols('x')
>>> list(_term_factors(-2 - x**2 + x*(x + 1)))
[-2, -1, x**2, x, x + 1]
"""
for add_arg in Add.make_args(f):
yield from Mul.make_args(add_arg)
def _solve_exponential(lhs, rhs, symbol, domain):
r"""
Helper function for solving (supported) exponential equations.
Exponential equations are the sum of (currently) at most
two terms with one or both of them having a power with a
symbol-dependent exponent.
For example
.. math:: 5^{2x + 3} - 5^{3x - 1}
.. math:: 4^{5 - 9x} - e^{2 - x}
Parameters
==========
lhs, rhs : Expr
The exponential equation to be solved, `lhs = rhs`
symbol : Symbol
The variable in which the equation is solved
domain : Set
A set over which the equation is solved.
Returns
=======
A set of solutions satisfying the given equation.
A ``ConditionSet`` if the equation is unsolvable or
if the assumptions are not properly defined, in that case
a different style of ``ConditionSet`` is returned having the
solution(s) of the equation with the desired assumptions.
Examples
========
>>> from sympy.solvers.solveset import _solve_exponential as solve_expo
>>> from sympy import symbols, S
>>> x = symbols('x', real=True)
>>> a, b = symbols('a b')
>>> solve_expo(2**x + 3**x - 5**x, 0, x, S.Reals) # not solvable
ConditionSet(x, Eq(2**x + 3**x - 5**x, 0), Reals)
>>> solve_expo(a**x - b**x, 0, x, S.Reals) # solvable but incorrect assumptions
ConditionSet(x, (a > 0) & (b > 0), {0})
>>> solve_expo(3**(2*x) - 2**(x + 3), 0, x, S.Reals)
{-3*log(2)/(-2*log(3) + log(2))}
>>> solve_expo(2**x - 4**x, 0, x, S.Reals)
{0}
* Proof of correctness of the method
The logarithm function is the inverse of the exponential function.
The defining relation between exponentiation and logarithm is:
.. math:: {\log_b x} = y \enspace if \enspace b^y = x
Therefore if we are given an equation with exponent terms, we can
convert every term to its corresponding logarithmic form. This is
achieved by taking logarithms and expanding the equation using
logarithmic identities so that it can easily be handled by ``solveset``.
For example:
.. math:: 3^{2x} = 2^{x + 3}
Taking log both sides will reduce the equation to
.. math:: (2x)\log(3) = (x + 3)\log(2)
This form can be easily handed by ``solveset``.
"""
unsolved_result = ConditionSet(symbol, Eq(lhs - rhs, 0), domain)
newlhs = powdenest(lhs)
if lhs != newlhs:
# it may also be advantageous to factor the new expr
neweq = factor(newlhs - rhs)
if neweq != (lhs - rhs):
return _solveset(neweq, symbol, domain) # try again with _solveset
if not (isinstance(lhs, Add) and len(lhs.args) == 2):
# solving for the sum of more than two powers is possible
# but not yet implemented
return unsolved_result
if rhs != 0:
return unsolved_result
a, b = list(ordered(lhs.args))
a_term = a.as_independent(symbol)[1]
b_term = b.as_independent(symbol)[1]
a_base, a_exp = a_term.as_base_exp()
b_base, b_exp = b_term.as_base_exp()
if domain.is_subset(S.Reals):
conditions = And(
a_base > 0,
b_base > 0,
Eq(im(a_exp), 0),
Eq(im(b_exp), 0))
else:
conditions = And(
Ne(a_base, 0),
Ne(b_base, 0))
L, R = map(lambda i: expand_log(log(i), force=True), (a, -b))
solutions = _solveset(L - R, symbol, domain)
return ConditionSet(symbol, conditions, solutions)
def _is_exponential(f, symbol):
r"""
Return ``True`` if one or more terms contain ``symbol`` only in
exponents, else ``False``.
Parameters
==========
f : Expr
The equation to be checked
symbol : Symbol
The variable in which the equation is checked
Examples
========
>>> from sympy import symbols, cos, exp
>>> from sympy.solvers.solveset import _is_exponential as check
>>> x, y = symbols('x y')
>>> check(y, y)
False
>>> check(x**y - 1, y)
True
>>> check(x**y*2**y - 1, y)
True
>>> check(exp(x + 3) + 3**x, x)
True
>>> check(cos(2**x), x)
False
* Philosophy behind the helper
The function extracts each term of the equation and checks if it is
of exponential form w.r.t ``symbol``.
"""
rv = False
for expr_arg in _term_factors(f):
if symbol not in expr_arg.free_symbols:
continue
if (isinstance(expr_arg, Pow) and
symbol not in expr_arg.base.free_symbols or
isinstance(expr_arg, exp)):
rv = True # symbol in exponent
else:
return False # dependent on symbol in non-exponential way
return rv
def _solve_logarithm(lhs, rhs, symbol, domain):
r"""
Helper to solve logarithmic equations which are reducible
to a single instance of `\log`.
Logarithmic equations are (currently) the equations that contains
`\log` terms which can be reduced to a single `\log` term or
a constant using various logarithmic identities.
For example:
.. math:: \log(x) + \log(x - 4)
can be reduced to:
.. math:: \log(x(x - 4))
Parameters
==========
lhs, rhs : Expr
The logarithmic equation to be solved, `lhs = rhs`
symbol : Symbol
The variable in which the equation is solved
domain : Set
A set over which the equation is solved.
Returns
=======
A set of solutions satisfying the given equation.
A ``ConditionSet`` if the equation is unsolvable.
Examples
========
>>> from sympy import symbols, log, S
>>> from sympy.solvers.solveset import _solve_logarithm as solve_log
>>> x = symbols('x')
>>> f = log(x - 3) + log(x + 3)
>>> solve_log(f, 0, x, S.Reals)
{-sqrt(10), sqrt(10)}
* Proof of correctness
A logarithm is another way to write exponent and is defined by
.. math:: {\log_b x} = y \enspace if \enspace b^y = x
When one side of the equation contains a single logarithm, the
equation can be solved by rewriting the equation as an equivalent
exponential equation as defined above. But if one side contains
more than one logarithm, we need to use the properties of logarithm
to condense it into a single logarithm.
Take for example
.. math:: \log(2x) - 15 = 0
contains single logarithm, therefore we can directly rewrite it to
exponential form as
.. math:: x = \frac{e^{15}}{2}
But if the equation has more than one logarithm as
.. math:: \log(x - 3) + \log(x + 3) = 0
we use logarithmic identities to convert it into a reduced form
Using,
.. math:: \log(a) + \log(b) = \log(ab)
the equation becomes,
.. math:: \log((x - 3)(x + 3))
This equation contains one logarithm and can be solved by rewriting
to exponents.
"""
new_lhs = logcombine(lhs, force=True)
new_f = new_lhs - rhs
return _solveset(new_f, symbol, domain)
def _is_logarithmic(f, symbol):
r"""
Return ``True`` if the equation is in the form
`a\log(f(x)) + b\log(g(x)) + ... + c` else ``False``.
Parameters
==========
f : Expr
The equation to be checked
symbol : Symbol
The variable in which the equation is checked
Returns
=======
``True`` if the equation is logarithmic otherwise ``False``.
Examples
========
>>> from sympy import symbols, tan, log
>>> from sympy.solvers.solveset import _is_logarithmic as check
>>> x, y = symbols('x y')
>>> check(log(x + 2) - log(x + 3), x)
True
>>> check(tan(log(2*x)), x)
False
>>> check(x*log(x), x)
False
>>> check(x + log(x), x)
False
>>> check(y + log(x), x)
True
* Philosophy behind the helper
The function extracts each term and checks whether it is
logarithmic w.r.t ``symbol``.
"""
rv = False
for term in Add.make_args(f):
saw_log = False
for term_arg in Mul.make_args(term):
if symbol not in term_arg.free_symbols:
continue
if isinstance(term_arg, log):
if saw_log:
return False # more than one log in term
saw_log = True
else:
return False # dependent on symbol in non-log way
if saw_log:
rv = True
return rv
def _is_lambert(f, symbol):
r"""
If this returns ``False`` then the Lambert solver (``_solve_lambert``) will not be called.
Explanation
===========
Quick check for cases that the Lambert solver might be able to handle.
1. Equations containing more than two operands and `symbol`s involving any of
`Pow`, `exp`, `HyperbolicFunction`,`TrigonometricFunction`, `log` terms.
2. In `Pow`, `exp` the exponent should have `symbol` whereas for
`HyperbolicFunction`,`TrigonometricFunction`, `log` should contain `symbol`.
3. For `HyperbolicFunction`,`TrigonometricFunction` the number of trigonometric functions in
equation should be less than number of symbols. (since `A*cos(x) + B*sin(x) - c`
is not the Lambert type).
Some forms of lambert equations are:
1. X**X = C
2. X*(B*log(X) + D)**A = C
3. A*log(B*X + A) + d*X = C
4. (B*X + A)*exp(d*X + g) = C
5. g*exp(B*X + h) - B*X = C
6. A*D**(E*X + g) - B*X = C
7. A*cos(X) + B*sin(X) - D*X = C
8. A*cosh(X) + B*sinh(X) - D*X = C
Where X is any variable,
A, B, C, D, E are any constants,
g, h are linear functions or log terms.
Parameters
==========
f : Expr
The equation to be checked
symbol : Symbol
The variable in which the equation is checked
Returns
=======
If this returns ``False`` then the Lambert solver (``_solve_lambert``) will not be called.
Examples
========
>>> from sympy.solvers.solveset import _is_lambert
>>> from sympy import symbols, cosh, sinh, log
>>> x = symbols('x')
>>> _is_lambert(3*log(x) - x*log(3), x)
True
>>> _is_lambert(log(log(x - 3)) + log(x-3), x)
True
>>> _is_lambert(cosh(x) - sinh(x), x)
False
>>> _is_lambert((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x)
True
See Also
========
_solve_lambert
"""
term_factors = list(_term_factors(f.expand()))
# total number of symbols in equation
no_of_symbols = len([arg for arg in term_factors if arg.has(symbol)])
# total number of trigonometric terms in equation
no_of_trig = len([arg for arg in term_factors \
if arg.has(HyperbolicFunction, TrigonometricFunction)])
if f.is_Add and no_of_symbols >= 2:
# `log`, `HyperbolicFunction`, `TrigonometricFunction` should have symbols
# and no_of_trig < no_of_symbols
lambert_funcs = (log, HyperbolicFunction, TrigonometricFunction)
if any(isinstance(arg, lambert_funcs)\
for arg in term_factors if arg.has(symbol)):
if no_of_trig < no_of_symbols:
return True
# here, `Pow`, `exp` exponent should have symbols
elif any(isinstance(arg, (Pow, exp)) \
for arg in term_factors if (arg.as_base_exp()[1]).has(symbol)):
return True
return False
def _transolve(f, symbol, domain):
r"""
Function to solve transcendental equations. It is a helper to
``solveset`` and should be used internally. ``_transolve``
currently supports the following class of equations:
- Exponential equations
- Logarithmic equations
Parameters
==========
f : Any transcendental equation that needs to be solved.
This needs to be an expression, which is assumed
to be equal to ``0``.
symbol : The variable for which the equation is solved.
This needs to be of class ``Symbol``.
domain : A set over which the equation is solved.
This needs to be of class ``Set``.
Returns
=======
Set
A set of values for ``symbol`` for which ``f`` is equal to
zero. An ``EmptySet`` is returned if ``f`` does not have solutions
in respective domain. A ``ConditionSet`` is returned as unsolved
object if algorithms to evaluate complete solution are not
yet implemented.
How to use ``_transolve``
=========================
``_transolve`` should not be used as an independent function, because
it assumes that the equation (``f``) and the ``symbol`` comes from
``solveset`` and might have undergone a few modification(s).
To use ``_transolve`` as an independent function the equation (``f``)
and the ``symbol`` should be passed as they would have been by
``solveset``.
Examples
========
>>> from sympy.solvers.solveset import _transolve as transolve
>>> from sympy.solvers.solvers import _tsolve as tsolve
>>> from sympy import symbols, S, pprint
>>> x = symbols('x', real=True) # assumption added
>>> transolve(5**(x - 3) - 3**(2*x + 1), x, S.Reals)
{-(log(3) + 3*log(5))/(-log(5) + 2*log(3))}
How ``_transolve`` works
========================
``_transolve`` uses two types of helper functions to solve equations
of a particular class:
Identifying helpers: To determine whether a given equation
belongs to a certain class of equation or not. Returns either
``True`` or ``False``.
Solving helpers: Once an equation is identified, a corresponding
helper either solves the equation or returns a form of the equation
that ``solveset`` might better be able to handle.
* Philosophy behind the module
The purpose of ``_transolve`` is to take equations which are not
already polynomial in their generator(s) and to either recast them
as such through a valid transformation or to solve them outright.
A pair of helper functions for each class of supported
transcendental functions are employed for this purpose. One
identifies the transcendental form of an equation and the other
either solves it or recasts it into a tractable form that can be
solved by ``solveset``.
For example, an equation in the form `ab^{f(x)} - cd^{g(x)} = 0`
can be transformed to
`\log(a) + f(x)\log(b) - \log(c) - g(x)\log(d) = 0`
(under certain assumptions) and this can be solved with ``solveset``
if `f(x)` and `g(x)` are in polynomial form.
How ``_transolve`` is better than ``_tsolve``
=============================================
1) Better output
``_transolve`` provides expressions in a more simplified form.
Consider a simple exponential equation
>>> f = 3**(2*x) - 2**(x + 3)
>>> pprint(transolve(f, x, S.Reals), use_unicode=False)
-3*log(2)
{------------------}
-2*log(3) + log(2)
>>> pprint(tsolve(f, x), use_unicode=False)
/ 3 \
| --------|
| log(2/9)|
[-log\2 /]
2) Extensible
The API of ``_transolve`` is designed such that it is easily
extensible, i.e. the code that solves a given class of
equations is encapsulated in a helper and not mixed in with
the code of ``_transolve`` itself.
3) Modular
``_transolve`` is designed to be modular i.e, for every class of
equation a separate helper for identification and solving is
implemented. This makes it easy to change or modify any of the
method implemented directly in the helpers without interfering
with the actual structure of the API.
4) Faster Computation
Solving equation via ``_transolve`` is much faster as compared to
``_tsolve``. In ``solve``, attempts are made computing every possibility
to get the solutions. This series of attempts makes solving a bit
slow. In ``_transolve``, computation begins only after a particular
type of equation is identified.
How to add new class of equations
=================================
Adding a new class of equation solver is a three-step procedure:
- Identify the type of the equations
Determine the type of the class of equations to which they belong:
it could be of ``Add``, ``Pow``, etc. types. Separate internal functions
are used for each type. Write identification and solving helpers
and use them from within the routine for the given type of equation
(after adding it, if necessary). Something like:
.. code-block:: python
def add_type(lhs, rhs, x):
....
if _is_exponential(lhs, x):
new_eq = _solve_exponential(lhs, rhs, x)
....
rhs, lhs = eq.as_independent(x)
if lhs.is_Add:
result = add_type(lhs, rhs, x)
- Define the identification helper.
- Define the solving helper.
Apart from this, a few other things needs to be taken care while
adding an equation solver:
- Naming conventions:
Name of the identification helper should be as
``_is_class`` where class will be the name or abbreviation
of the class of equation. The solving helper will be named as
``_solve_class``.
For example: for exponential equations it becomes
``_is_exponential`` and ``_solve_expo``.
- The identifying helpers should take two input parameters,
the equation to be checked and the variable for which a solution
is being sought, while solving helpers would require an additional
domain parameter.
- Be sure to consider corner cases.
- Add tests for each helper.
- Add a docstring to your helper that describes the method
implemented.
The documentation of the helpers should identify:
- the purpose of the helper,
- the method used to identify and solve the equation,
- a proof of correctness
- the return values of the helpers
"""
def add_type(lhs, rhs, symbol, domain):
"""
Helper for ``_transolve`` to handle equations of
``Add`` type, i.e. equations taking the form as
``a*f(x) + b*g(x) + .... = c``.
For example: 4**x + 8**x = 0
"""
result = ConditionSet(symbol, Eq(lhs - rhs, 0), domain)
# check if it is exponential type equation
if _is_exponential(lhs, symbol):
result = _solve_exponential(lhs, rhs, symbol, domain)
# check if it is logarithmic type equation
elif _is_logarithmic(lhs, symbol):
result = _solve_logarithm(lhs, rhs, symbol, domain)
return result
result = ConditionSet(symbol, Eq(f, 0), domain)
# invert_complex handles the call to the desired inverter based
# on the domain specified.
lhs, rhs_s = invert_complex(f, 0, symbol, domain)
if isinstance(rhs_s, FiniteSet):
assert (len(rhs_s.args)) == 1
rhs = rhs_s.args[0]
if lhs.is_Add:
result = add_type(lhs, rhs, symbol, domain)
else:
result = rhs_s
return result
def solveset(f, symbol=None, domain=S.Complexes):
r"""Solves a given inequality or equation with set as output
Parameters
==========
f : Expr or a relational.
The target equation or inequality
symbol : Symbol
The variable for which the equation is solved
domain : Set
The domain over which the equation is solved
Returns
=======
Set
A set of values for `symbol` for which `f` is True or is equal to
zero. An :class:`~.EmptySet` is returned if `f` is False or nonzero.
A :class:`~.ConditionSet` is returned as unsolved object if algorithms
to evaluate complete solution are not yet implemented.
``solveset`` claims to be complete in the solution set that it returns.
Raises
======
NotImplementedError
The algorithms to solve inequalities in complex domain are
not yet implemented.
ValueError
The input is not valid.
RuntimeError
It is a bug, please report to the github issue tracker.
Notes
=====
Python interprets 0 and 1 as False and True, respectively, but
in this function they refer to solutions of an expression. So 0 and 1
return the domain and EmptySet, respectively, while True and False
return the opposite (as they are assumed to be solutions of relational
expressions).
See Also
========
solveset_real: solver for real domain
solveset_complex: solver for complex domain
Examples
========
>>> from sympy import exp, sin, Symbol, pprint, S, Eq
>>> from sympy.solvers.solveset import solveset, solveset_real
* The default domain is complex. Not specifying a domain will lead
to the solving of the equation in the complex domain (and this
is not affected by the assumptions on the symbol):
>>> x = Symbol('x')
>>> pprint(solveset(exp(x) - 1, x), use_unicode=False)
{2*n*I*pi | n in Integers}
>>> x = Symbol('x', real=True)
>>> pprint(solveset(exp(x) - 1, x), use_unicode=False)
{2*n*I*pi | n in Integers}
* If you want to use ``solveset`` to solve the equation in the
real domain, provide a real domain. (Using ``solveset_real``
does this automatically.)
>>> R = S.Reals
>>> x = Symbol('x')
>>> solveset(exp(x) - 1, x, R)
{0}
>>> solveset_real(exp(x) - 1, x)
{0}
The solution is unaffected by assumptions on the symbol:
>>> p = Symbol('p', positive=True)
>>> pprint(solveset(p**2 - 4))
{-2, 2}
When a :class:`~.ConditionSet` is returned, symbols with assumptions that
would alter the set are replaced with more generic symbols:
>>> i = Symbol('i', imaginary=True)
>>> solveset(Eq(i**2 + i*sin(i), 1), i, domain=S.Reals)
ConditionSet(_R, Eq(_R**2 + _R*sin(_R) - 1, 0), Reals)
* Inequalities can be solved over the real domain only. Use of a complex
domain leads to a NotImplementedError.
>>> solveset(exp(x) > 1, x, R)
Interval.open(0, oo)
"""
f = sympify(f)
symbol = sympify(symbol)
if f is S.true:
return domain
if f is S.false:
return S.EmptySet
if not isinstance(f, (Expr, Relational, Number)):
raise ValueError("%s is not a valid SymPy expression" % f)
if not isinstance(symbol, (Expr, Relational)) and symbol is not None:
raise ValueError("%s is not a valid SymPy symbol" % (symbol,))
if not isinstance(domain, Set):
raise ValueError("%s is not a valid domain" %(domain))
free_symbols = f.free_symbols
if f.has(Piecewise):
f = piecewise_fold(f)
if symbol is None and not free_symbols:
b = Eq(f, 0)
if b is S.true:
return domain
elif b is S.false:
return S.EmptySet
else:
raise NotImplementedError(filldedent('''
relationship between value and 0 is unknown: %s''' % b))
if symbol is None:
if len(free_symbols) == 1:
symbol = free_symbols.pop()
elif free_symbols:
raise ValueError(filldedent('''
The independent variable must be specified for a
multivariate equation.'''))
elif not isinstance(symbol, Symbol):
f, s, swap = recast_to_symbols([f], [symbol])
# the xreplace will be needed if a ConditionSet is returned
return solveset(f[0], s[0], domain).xreplace(swap)
# solveset should ignore assumptions on symbols
if symbol not in _rc:
x = _rc[0] if domain.is_subset(S.Reals) else _rc[1]
rv = solveset(f.xreplace({symbol: x}), x, domain)
# try to use the original symbol if possible
try:
_rv = rv.xreplace({x: symbol})
except TypeError:
_rv = rv
if rv.dummy_eq(_rv):
rv = _rv
return rv
# Abs has its own handling method which avoids the
# rewriting property that the first piece of abs(x)
# is for x >= 0 and the 2nd piece for x < 0 -- solutions
# can look better if the 2nd condition is x <= 0. Since
# the solution is a set, duplication of results is not
# an issue, e.g. {y, -y} when y is 0 will be {0}
f, mask = _masked(f, Abs)
f = f.rewrite(Piecewise) # everything that's not an Abs
for d, e in mask:
# everything *in* an Abs
e = e.func(e.args[0].rewrite(Piecewise))
f = f.xreplace({d: e})
f = piecewise_fold(f)
return _solveset(f, symbol, domain, _check=True)
def solveset_real(f, symbol):
return solveset(f, symbol, S.Reals)
def solveset_complex(f, symbol):
return solveset(f, symbol, S.Complexes)
def _solveset_multi(eqs, syms, domains):
'''Basic implementation of a multivariate solveset.
For internal use (not ready for public consumption)'''
rep = {}
for sym, dom in zip(syms, domains):
if dom is S.Reals:
rep[sym] = Symbol(sym.name, real=True)
eqs = [eq.subs(rep) for eq in eqs]
syms = [sym.subs(rep) for sym in syms]
syms = tuple(syms)
if len(eqs) == 0:
return ProductSet(*domains)
if len(syms) == 1:
sym = syms[0]
domain = domains[0]
solsets = [solveset(eq, sym, domain) for eq in eqs]
solset = Intersection(*solsets)
return ImageSet(Lambda((sym,), (sym,)), solset).doit()
eqs = sorted(eqs, key=lambda eq: len(eq.free_symbols & set(syms)))
for n in range(len(eqs)):
sols = []
all_handled = True
for sym in syms:
if sym not in eqs[n].free_symbols:
continue
sol = solveset(eqs[n], sym, domains[syms.index(sym)])
if isinstance(sol, FiniteSet):
i = syms.index(sym)
symsp = syms[:i] + syms[i+1:]
domainsp = domains[:i] + domains[i+1:]
eqsp = eqs[:n] + eqs[n+1:]
for s in sol:
eqsp_sub = [eq.subs(sym, s) for eq in eqsp]
sol_others = _solveset_multi(eqsp_sub, symsp, domainsp)
fun = Lambda((symsp,), symsp[:i] + (s,) + symsp[i:])
sols.append(ImageSet(fun, sol_others).doit())
else:
all_handled = False
if all_handled:
return Union(*sols)
def solvify(f, symbol, domain):
"""Solves an equation using solveset and returns the solution in accordance
with the `solve` output API.
Returns
=======
We classify the output based on the type of solution returned by `solveset`.
Solution | Output
----------------------------------------
FiniteSet | list
ImageSet, | list (if `f` is periodic)
Union |
Union | list (with FiniteSet)
EmptySet | empty list
Others | None
Raises
======
NotImplementedError
A ConditionSet is the input.
Examples
========
>>> from sympy.solvers.solveset import solvify
>>> from sympy.abc import x
>>> from sympy import S, tan, sin, exp
>>> solvify(x**2 - 9, x, S.Reals)
[-3, 3]
>>> solvify(sin(x) - 1, x, S.Reals)
[pi/2]
>>> solvify(tan(x), x, S.Reals)
[0]
>>> solvify(exp(x) - 1, x, S.Complexes)
>>> solvify(exp(x) - 1, x, S.Reals)
[0]
"""
solution_set = solveset(f, symbol, domain)
result = None
if solution_set is S.EmptySet:
result = []
elif isinstance(solution_set, ConditionSet):
raise NotImplementedError('solveset is unable to solve this equation.')
elif isinstance(solution_set, FiniteSet):
result = list(solution_set)
else:
period = periodicity(f, symbol)
if period is not None:
solutions = S.EmptySet
iter_solutions = ()
if isinstance(solution_set, ImageSet):
iter_solutions = (solution_set,)
elif isinstance(solution_set, Union):
if all(isinstance(i, ImageSet) for i in solution_set.args):
iter_solutions = solution_set.args
for solution in iter_solutions:
solutions += solution.intersect(Interval(0, period, False, True))
if isinstance(solutions, FiniteSet):
result = list(solutions)
else:
solution = solution_set.intersect(domain)
if isinstance(solution, Union):
# concerned about only FiniteSet with Union but not about ImageSet
# if required could be extend
if any(isinstance(i, FiniteSet) for i in solution.args):
result = [sol for soln in solution.args \
for sol in soln.args if isinstance(soln,FiniteSet)]
else:
return None
elif isinstance(solution, FiniteSet):
result += solution
return result
###############################################################################
################################ LINSOLVE #####################################
###############################################################################
def linear_coeffs(eq, *syms, **_kw):
"""Return a list whose elements are the coefficients of the
corresponding symbols in the sum of terms in ``eq``.
The additive constant is returned as the last element of the
list.
Raises
======
NonlinearError
The equation contains a nonlinear term
Examples
========
>>> from sympy.solvers.solveset import linear_coeffs
>>> from sympy.abc import x, y, z
>>> linear_coeffs(3*x + 2*y - 1, x, y)
[3, 2, -1]
It is not necessary to expand the expression:
>>> linear_coeffs(x + y*(z*(x*3 + 2) + 3), x)
[3*y*z + 1, y*(2*z + 3)]
But if there are nonlinear or cross terms -- even if they would
cancel after simplification -- an error is raised so the situation
does not pass silently past the caller's attention:
>>> eq = 1/x*(x - 1) + 1/x
>>> linear_coeffs(eq.expand(), x)
[0, 1]
>>> linear_coeffs(eq, x)
Traceback (most recent call last):
...
NonlinearError: nonlinear term encountered: 1/x
>>> linear_coeffs(x*(y + 1) - x*y, x, y)
Traceback (most recent call last):
...
NonlinearError: nonlinear term encountered: x*(y + 1)
"""
d = defaultdict(list)
eq = _sympify(eq)
symset = set(syms)
if len(symset) != len(syms):
raise ValueError('duplicate symbols given')
has = set(iterfreeargs(eq)) & symset
if not has:
return [S.Zero]*len(syms) + [eq]
c, terms = eq.as_coeff_add(*has)
d[0].extend(Add.make_args(c))
for t in terms:
m, f = t.as_coeff_mul(*has)
if len(f) != 1:
break
f = f[0]
if f in symset:
d[f].append(m)
elif f.is_Add:
d1 = linear_coeffs(f, *has, **{'dict': True})
d[0].append(m*d1.pop(0))
for xf, vf in d1.items():
d[xf].append(m*vf)
else:
break
else:
for k, v in d.items():
d[k] = Add(*v)
if not _kw:
return [d.get(s, S.Zero) for s in syms]+ [d[0]]
return d # default is still list but this won't matter
raise NonlinearError('nonlinear term encountered: %s' % t)
def linear_eq_to_matrix(equations, *symbols):
r"""
Converts a given System of Equations into Matrix form.
Here `equations` must be a linear system of equations in
`symbols`. Element ``M[i, j]`` corresponds to the coefficient
of the jth symbol in the ith equation.
The Matrix form corresponds to the augmented matrix form.
For example:
.. math:: 4x + 2y + 3z = 1
.. math:: 3x + y + z = -6
.. math:: 2x + 4y + 9z = 2
This system will return $A$ and $b$ as:
$$ A = \left[\begin{array}{ccc}
4 & 2 & 3 \\
3 & 1 & 1 \\
2 & 4 & 9
\end{array}\right] \ \ b = \left[\begin{array}{c}
1 \\ -6 \\ 2
\end{array}\right] $$
The only simplification performed is to convert
``Eq(a, b)`` $\Rightarrow a - b$.
Raises
======
NonlinearError
The equations contain a nonlinear term.
ValueError
The symbols are not given or are not unique.
Examples
========
>>> from sympy import linear_eq_to_matrix, symbols
>>> c, x, y, z = symbols('c, x, y, z')
The coefficients (numerical or symbolic) of the symbols will
be returned as matrices:
>>> eqns = [c*x + z - 1 - c, y + z, x - y]
>>> A, b = linear_eq_to_matrix(eqns, [x, y, z])
>>> A
Matrix([
[c, 0, 1],
[0, 1, 1],
[1, -1, 0]])
>>> b
Matrix([
[c + 1],
[ 0],
[ 0]])
This routine does not simplify expressions and will raise an error
if nonlinearity is encountered:
>>> eqns = [
... (x**2 - 3*x)/(x - 3) - 3,
... y**2 - 3*y - y*(y - 4) + x - 4]
>>> linear_eq_to_matrix(eqns, [x, y])
Traceback (most recent call last):
...
NonlinearError:
The term (x**2 - 3*x)/(x - 3) is nonlinear in {x, y}
Simplifying these equations will discard the removable singularity
in the first, reveal the linear structure of the second:
>>> [e.simplify() for e in eqns]
[x - 3, x + y - 4]
Any such simplification needed to eliminate nonlinear terms must
be done before calling this routine.
"""
if not symbols:
raise ValueError(filldedent('''
Symbols must be given, for which coefficients
are to be found.
'''))
if hasattr(symbols[0], '__iter__'):
symbols = symbols[0]
for i in symbols:
if not isinstance(i, Symbol):
raise ValueError(filldedent('''
Expecting a Symbol but got %s
''' % i))
if has_dups(symbols):
raise ValueError('Symbols must be unique')
equations = sympify(equations)
if isinstance(equations, MatrixBase):
equations = list(equations)
elif isinstance(equations, (Expr, Eq)):
equations = [equations]
elif not is_sequence(equations):
raise ValueError(filldedent('''
Equation(s) must be given as a sequence, Expr,
Eq or Matrix.
'''))
A, b = [], []
for i, f in enumerate(equations):
if isinstance(f, Equality):
f = f.rewrite(Add, evaluate=False)
coeff_list = linear_coeffs(f, *symbols)
b.append(-coeff_list.pop())
A.append(coeff_list)
A, b = map(Matrix, (A, b))
return A, b
def linsolve(system, *symbols):
r"""
Solve system of $N$ linear equations with $M$ variables; both
underdetermined and overdetermined systems are supported.
The possible number of solutions is zero, one or infinite.
Zero solutions throws a ValueError, whereas infinite
solutions are represented parametrically in terms of the given
symbols. For unique solution a :class:`~.FiniteSet` of ordered tuples
is returned.
All standard input formats are supported:
For the given set of equations, the respective input types
are given below:
.. math:: 3x + 2y - z = 1
.. math:: 2x - 2y + 4z = -2
.. math:: 2x - y + 2z = 0
* Augmented matrix form, ``system`` given below:
$$ \text{system} = \left[{array}{cccc}
3 & 2 & -1 & 1\\
2 & -2 & 4 & -2\\
2 & -1 & 2 & 0
\end{array}\right] $$
::
system = Matrix([[3, 2, -1, 1], [2, -2, 4, -2], [2, -1, 2, 0]])
* List of equations form
::
system = [3x + 2y - z - 1, 2x - 2y + 4z + 2, 2x - y + 2z]
* Input $A$ and $b$ in matrix form (from $Ax = b$) are given as:
$$ A = \left[\begin{array}{ccc}
3 & 2 & -1 \\
2 & -2 & 4 \\
2 & -1 & 2
\end{array}\right] \ \ b = \left[\begin{array}{c}
1 \\ -2 \\ 0
\end{array}\right] $$
::
A = Matrix([[3, 2, -1], [2, -2, 4], [2, -1, 2]])
b = Matrix([[1], [-2], [0]])
system = (A, b)
Symbols can always be passed but are actually only needed
when 1) a system of equations is being passed and 2) the
system is passed as an underdetermined matrix and one wants
to control the name of the free variables in the result.
An error is raised if no symbols are used for case 1, but if
no symbols are provided for case 2, internally generated symbols
will be provided. When providing symbols for case 2, there should
be at least as many symbols are there are columns in matrix A.
The algorithm used here is Gauss-Jordan elimination, which
results, after elimination, in a row echelon form matrix.
Returns
=======
A FiniteSet containing an ordered tuple of values for the
unknowns for which the `system` has a solution. (Wrapping
the tuple in FiniteSet is used to maintain a consistent
output format throughout solveset.)
Returns EmptySet, if the linear system is inconsistent.
Raises
======
ValueError
The input is not valid.
The symbols are not given.
Examples
========
>>> from sympy import Matrix, linsolve, symbols
>>> x, y, z = symbols("x, y, z")
>>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
>>> b = Matrix([3, 6, 9])
>>> A
Matrix([
[1, 2, 3],
[4, 5, 6],
[7, 8, 10]])
>>> b
Matrix([
[3],
[6],
[9]])
>>> linsolve((A, b), [x, y, z])
{(-1, 2, 0)}
* Parametric Solution: In case the system is underdetermined, the
function will return a parametric solution in terms of the given
symbols. Those that are free will be returned unchanged. e.g. in
the system below, `z` is returned as the solution for variable z;
it can take on any value.
>>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> b = Matrix([3, 6, 9])
>>> linsolve((A, b), x, y, z)
{(z - 1, 2 - 2*z, z)}
If no symbols are given, internally generated symbols will be used.
The ``tau0`` in the third position indicates (as before) that the third
variable -- whatever it is named -- can take on any value:
>>> linsolve((A, b))
{(tau0 - 1, 2 - 2*tau0, tau0)}
* List of equations as input
>>> Eqns = [3*x + 2*y - z - 1, 2*x - 2*y + 4*z + 2, - x + y/2 - z]
>>> linsolve(Eqns, x, y, z)
{(1, -2, -2)}
* Augmented matrix as input
>>> aug = Matrix([[2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]])
>>> aug
Matrix([
[2, 1, 3, 1],
[2, 6, 8, 3],
[6, 8, 18, 5]])
>>> linsolve(aug, x, y, z)
{(3/10, 2/5, 0)}
* Solve for symbolic coefficients
>>> a, b, c, d, e, f = symbols('a, b, c, d, e, f')
>>> eqns = [a*x + b*y - c, d*x + e*y - f]
>>> linsolve(eqns, x, y)
{((-b*f + c*e)/(a*e - b*d), (a*f - c*d)/(a*e - b*d))}
* A degenerate system returns solution as set of given
symbols.
>>> system = Matrix(([0, 0, 0], [0, 0, 0], [0, 0, 0]))
>>> linsolve(system, x, y)
{(x, y)}
* For an empty system linsolve returns empty set
>>> linsolve([], x)
EmptySet
* An error is raised if, after expansion, any nonlinearity
is detected:
>>> linsolve([x*(1/x - 1), (y - 1)**2 - y**2 + 1], x, y)
{(1, 1)}
>>> linsolve([x**2 - 1], x)
Traceback (most recent call last):
...
NonlinearError:
nonlinear term encountered: x**2
"""
if not system:
return S.EmptySet
# If second argument is an iterable
if symbols and hasattr(symbols[0], '__iter__'):
symbols = symbols[0]
sym_gen = isinstance(symbols, GeneratorType)
b = None # if we don't get b the input was bad
# unpack system
if hasattr(system, '__iter__'):
# 1). (A, b)
if len(system) == 2 and isinstance(system[0], MatrixBase):
A, b = system
# 2). (eq1, eq2, ...)
if not isinstance(system[0], MatrixBase):
if sym_gen or not symbols:
raise ValueError(filldedent('''
When passing a system of equations, the explicit
symbols for which a solution is being sought must
be given as a sequence, too.
'''))
#
# Pass to the sparse solver implemented in polys. It is important
# that we do not attempt to convert the equations to a matrix
# because that would be very inefficient for large sparse systems
# of equations.
#
eqs = system
eqs = [sympify(eq) for eq in eqs]
try:
sol = _linsolve(eqs, symbols)
except PolyNonlinearError as exc:
# e.g. cos(x) contains an element of the set of generators
raise NonlinearError(str(exc))
if sol is None:
return S.EmptySet
sol = FiniteSet(Tuple(*(sol.get(sym, sym) for sym in symbols)))
return sol
elif isinstance(system, MatrixBase) and not (
symbols and not isinstance(symbols, GeneratorType) and
isinstance(symbols[0], MatrixBase)):
# 3). A augmented with b
A, b = system[:, :-1], system[:, -1:]
if b is None:
raise ValueError("Invalid arguments")
if sym_gen:
symbols = [next(symbols) for i in range(A.cols)]
if any(set(symbols) & (A.free_symbols | b.free_symbols)):
raise ValueError(filldedent('''
At least one of the symbols provided
already appears in the system to be solved.
One way to avoid this is to use Dummy symbols in
the generator, e.g. numbered_symbols('%s', cls=Dummy)
''' % symbols[0].name.rstrip('1234567890')))
if not symbols:
symbols = [Dummy() for _ in range(A.cols)]
name = _uniquely_named_symbol('tau', (A, b),
compare=lambda i: str(i).rstrip('1234567890')).name
gen = numbered_symbols(name)
else:
gen = None
# This is just a wrapper for solve_lin_sys
eqs = []
rows = A.tolist()
for rowi, bi in zip(rows, b):
terms = [elem * sym for elem, sym in zip(rowi, symbols) if elem]
terms.append(-bi)
eqs.append(Add(*terms))
eqs, ring = sympy_eqs_to_ring(eqs, symbols)
sol = solve_lin_sys(eqs, ring, _raw=False)
if sol is None:
return S.EmptySet
#sol = {sym:val for sym, val in sol.items() if sym != val}
sol = FiniteSet(Tuple(*(sol.get(sym, sym) for sym in symbols)))
if gen is not None:
solsym = sol.free_symbols
rep = {sym: next(gen) for sym in symbols if sym in solsym}
sol = sol.subs(rep)
return sol
##############################################################################
# ------------------------------nonlinsolve ---------------------------------#
##############################################################################
def _return_conditionset(eqs, symbols):
# return conditionset
eqs = (Eq(lhs, 0) for lhs in eqs)
condition_set = ConditionSet(
Tuple(*symbols), And(*eqs), S.Complexes**len(symbols))
return condition_set
def substitution(system, symbols, result=[{}], known_symbols=[],
exclude=[], all_symbols=None):
r"""
Solves the `system` using substitution method. It is used in
:func:`~.nonlinsolve`. This will be called from :func:`~.nonlinsolve` when any
equation(s) is non polynomial equation.
Parameters
==========
system : list of equations
The target system of equations
symbols : list of symbols to be solved.
The variable(s) for which the system is solved
known_symbols : list of solved symbols
Values are known for these variable(s)
result : An empty list or list of dict
If No symbol values is known then empty list otherwise
symbol as keys and corresponding value in dict.
exclude : Set of expression.
Mostly denominator expression(s) of the equations of the system.
Final solution should not satisfy these expressions.
all_symbols : known_symbols + symbols(unsolved).
Returns
=======
A FiniteSet of ordered tuple of values of `all_symbols` for which the
`system` has solution. Order of values in the tuple is same as symbols
present in the parameter `all_symbols`. If parameter `all_symbols` is None
then same as symbols present in the parameter `symbols`.
Please note that general FiniteSet is unordered, the solution returned
here is not simply a FiniteSet of solutions, rather it is a FiniteSet of
ordered tuple, i.e. the first & only argument to FiniteSet is a tuple of
solutions, which is ordered, & hence the returned solution is ordered.
Also note that solution could also have been returned as an ordered tuple,
FiniteSet is just a wrapper `{}` around the tuple. It has no other
significance except for the fact it is just used to maintain a consistent
output format throughout the solveset.
Raises
======
ValueError
The input is not valid.
The symbols are not given.
AttributeError
The input symbols are not :class:`~.Symbol` type.
Examples
========
>>> from sympy import symbols, substitution
>>> x, y = symbols('x, y', real=True)
>>> substitution([x + y], [x], [{y: 1}], [y], set([]), [x, y])
{(-1, 1)}
* When you want a soln not satisfying $x + 1 = 0$
>>> substitution([x + y], [x], [{y: 1}], [y], set([x + 1]), [y, x])
EmptySet
>>> substitution([x + y], [x], [{y: 1}], [y], set([x - 1]), [y, x])
{(1, -1)}
>>> substitution([x + y - 1, y - x**2 + 5], [x, y])
{(-3, 4), (2, -1)}
* Returns both real and complex solution
>>> x, y, z = symbols('x, y, z')
>>> from sympy import exp, sin
>>> substitution([exp(x) - sin(y), y**2 - 4], [x, y])
{(ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), Integers), -2),
(ImageSet(Lambda(_n, 2*_n*I*pi + log(sin(2))), Integers), 2)}
>>> eqs = [z**2 + exp(2*x) - sin(y), -3 + exp(-y)]
>>> substitution(eqs, [y, z])
{(-log(3), -sqrt(-exp(2*x) - sin(log(3)))),
(-log(3), sqrt(-exp(2*x) - sin(log(3)))),
(ImageSet(Lambda(_n, 2*_n*I*pi - log(3)), Integers),
ImageSet(Lambda(_n, -sqrt(-exp(2*x) + sin(2*_n*I*pi - log(3)))), Integers)),
(ImageSet(Lambda(_n, 2*_n*I*pi - log(3)), Integers),
ImageSet(Lambda(_n, sqrt(-exp(2*x) + sin(2*_n*I*pi - log(3)))), Integers))}
"""
if not system:
return S.EmptySet
if not symbols:
msg = ('Symbols must be given, for which solution of the '
'system is to be found.')
raise ValueError(filldedent(msg))
if not is_sequence(symbols):
msg = ('symbols should be given as a sequence, e.g. a list.'
'Not type %s: %s')
raise TypeError(filldedent(msg % (type(symbols), symbols)))
if not getattr(symbols[0], 'is_Symbol', False):
msg = ('Iterable of symbols must be given as '
'second argument, not type %s: %s')
raise ValueError(filldedent(msg % (type(symbols[0]), symbols[0])))
# By default `all_symbols` will be same as `symbols`
if all_symbols is None:
all_symbols = symbols
old_result = result
# storing complements and intersection for particular symbol
complements = {}
intersections = {}
# when total_solveset_call equals total_conditionset
# it means that solveset failed to solve all eqs.
total_conditionset = -1
total_solveset_call = -1
def _unsolved_syms(eq, sort=False):
"""Returns the unsolved symbol present
in the equation `eq`.
"""
free = eq.free_symbols
unsolved = (free - set(known_symbols)) & set(all_symbols)
if sort:
unsolved = list(unsolved)
unsolved.sort(key=default_sort_key)
return unsolved
# end of _unsolved_syms()
# sort such that equation with the fewest potential symbols is first.
# means eq with less number of variable first in the list.
eqs_in_better_order = list(
ordered(system, lambda _: len(_unsolved_syms(_))))
def add_intersection_complement(result, intersection_dict, complement_dict):
# If solveset has returned some intersection/complement
# for any symbol, it will be added in the final solution.
final_result = []
for res in result:
res_copy = res
for key_res, value_res in res.items():
intersect_set, complement_set = None, None
for key_sym, value_sym in intersection_dict.items():
if key_sym == key_res:
intersect_set = value_sym
for key_sym, value_sym in complement_dict.items():
if key_sym == key_res:
complement_set = value_sym
if intersect_set or complement_set:
new_value = FiniteSet(value_res)
if intersect_set and intersect_set != S.Complexes:
new_value = Intersection(new_value, intersect_set)
if complement_set:
new_value = Complement(new_value, complement_set)
if new_value is S.EmptySet:
res_copy = None
break
elif new_value.is_FiniteSet and len(new_value) == 1:
res_copy[key_res] = set(new_value).pop()
else:
res_copy[key_res] = new_value
if res_copy is not None:
final_result.append(res_copy)
return final_result
# end of def add_intersection_complement()
def _extract_main_soln(sym, sol, soln_imageset):
"""Separate the Complements, Intersections, ImageSet lambda expr and
its base_set. This function returns the unmasks sol from different classes
of sets and also returns the appended ImageSet elements in a
soln_imageset (dict: where key as unmasked element and value as ImageSet).
"""
# if there is union, then need to check
# Complement, Intersection, Imageset.
# Order should not be changed.
if isinstance(sol, ConditionSet):
# extracts any solution in ConditionSet
sol = sol.base_set
if isinstance(sol, Complement):
# extract solution and complement
complements[sym] = sol.args[1]
sol = sol.args[0]
# complement will be added at the end
# using `add_intersection_complement` method
# if there is union of Imageset or other in soln.
# no testcase is written for this if block
if isinstance(sol, Union):
sol_args = sol.args
sol = S.EmptySet
# We need in sequence so append finteset elements
# and then imageset or other.
for sol_arg2 in sol_args:
if isinstance(sol_arg2, FiniteSet):
sol += sol_arg2
else:
# ImageSet, Intersection, complement then
# append them directly
sol += FiniteSet(sol_arg2)
if isinstance(sol, Intersection):
# Interval/Set will be at 0th index always
if sol.args[0] not in (S.Reals, S.Complexes):
# Sometimes solveset returns soln with intersection
# S.Reals or S.Complexes. We don't consider that
# intersection.
intersections[sym] = sol.args[0]
sol = sol.args[1]
# after intersection and complement Imageset should
# be checked.
if isinstance(sol, ImageSet):
soln_imagest = sol
expr2 = sol.lamda.expr
sol = FiniteSet(expr2)
soln_imageset[expr2] = soln_imagest
if not isinstance(sol, FiniteSet):
sol = FiniteSet(sol)
return sol, soln_imageset
# end of def _extract_main_soln()
# helper function for _append_new_soln
def _check_exclude(rnew, imgset_yes):
rnew_ = rnew
if imgset_yes:
# replace all dummy variables (Imageset lambda variables)
# with zero before `checksol`. Considering fundamental soln
# for `checksol`.
rnew_copy = rnew.copy()
dummy_n = imgset_yes[0]
for key_res, value_res in rnew_copy.items():
rnew_copy[key_res] = value_res.subs(dummy_n, 0)
rnew_ = rnew_copy
# satisfy_exclude == true if it satisfies the expr of `exclude` list.
try:
# something like : `Mod(-log(3), 2*I*pi)` can't be
# simplified right now, so `checksol` returns `TypeError`.
# when this issue is fixed this try block should be
# removed. Mod(-log(3), 2*I*pi) == -log(3)
satisfy_exclude = any(
checksol(d, rnew_) for d in exclude)
except TypeError:
satisfy_exclude = None
return satisfy_exclude
# end of def _check_exclude()
# helper function for _append_new_soln
def _restore_imgset(rnew, original_imageset, newresult):
restore_sym = set(rnew.keys()) & \
set(original_imageset.keys())
for key_sym in restore_sym:
img = original_imageset[key_sym]
rnew[key_sym] = img
if rnew not in newresult:
newresult.append(rnew)
# end of def _restore_imgset()
def _append_eq(eq, result, res, delete_soln, n=None):
u = Dummy('u')
if n:
eq = eq.subs(n, 0)
satisfy = eq if eq in (True, False) else checksol(u, u, eq, minimal=True)
if satisfy is False:
delete_soln = True
res = {}
else:
result.append(res)
return result, res, delete_soln
def _append_new_soln(rnew, sym, sol, imgset_yes, soln_imageset,
original_imageset, newresult, eq=None):
"""If `rnew` (A dict <symbol: soln>) contains valid soln
append it to `newresult` list.
`imgset_yes` is (base, dummy_var) if there was imageset in previously
calculated result(otherwise empty tuple). `original_imageset` is dict
of imageset expr and imageset from this result.
`soln_imageset` dict of imageset expr and imageset of new soln.
"""
satisfy_exclude = _check_exclude(rnew, imgset_yes)
delete_soln = False
# soln should not satisfy expr present in `exclude` list.
if not satisfy_exclude:
local_n = None
# if it is imageset
if imgset_yes:
local_n = imgset_yes[0]
base = imgset_yes[1]
if sym and sol:
# when `sym` and `sol` is `None` means no new
# soln. In that case we will append rnew directly after
# substituting original imagesets in rnew values if present
# (second last line of this function using _restore_imgset)
dummy_list = list(sol.atoms(Dummy))
# use one dummy `n` which is in
# previous imageset
local_n_list = [
local_n for i in range(
0, len(dummy_list))]
dummy_zip = zip(dummy_list, local_n_list)
lam = Lambda(local_n, sol.subs(dummy_zip))
rnew[sym] = ImageSet(lam, base)
if eq is not None:
newresult, rnew, delete_soln = _append_eq(
eq, newresult, rnew, delete_soln, local_n)
elif eq is not None:
newresult, rnew, delete_soln = _append_eq(
eq, newresult, rnew, delete_soln)
elif sol in soln_imageset.keys():
rnew[sym] = soln_imageset[sol]
# restore original imageset
_restore_imgset(rnew, original_imageset, newresult)
else:
newresult.append(rnew)
elif satisfy_exclude:
delete_soln = True
rnew = {}
_restore_imgset(rnew, original_imageset, newresult)
return newresult, delete_soln
# end of def _append_new_soln()
def _new_order_result(result, eq):
# separate first, second priority. `res` that makes `eq` value equals
# to zero, should be used first then other result(second priority).
# If it is not done then we may miss some soln.
first_priority = []
second_priority = []
for res in result:
if not any(isinstance(val, ImageSet) for val in res.values()):
if eq.subs(res) == 0:
first_priority.append(res)
else:
second_priority.append(res)
if first_priority or second_priority:
return first_priority + second_priority
return result
def _solve_using_known_values(result, solver):
"""Solves the system using already known solution
(result contains the dict <symbol: value>).
solver is :func:`~.solveset_complex` or :func:`~.solveset_real`.
"""
# stores imageset <expr: imageset(Lambda(n, expr), base)>.
soln_imageset = {}
total_solvest_call = 0
total_conditionst = 0
# sort such that equation with the fewest potential symbols is first.
# means eq with less variable first
for index, eq in enumerate(eqs_in_better_order):
newresult = []
original_imageset = {}
# if imageset expr is used to solve other symbol
imgset_yes = False
result = _new_order_result(result, eq)
for res in result:
got_symbol = set() # symbols solved in one iteration
# find the imageset and use its expr.
for key_res, value_res in res.items():
if isinstance(value_res, ImageSet):
res[key_res] = value_res.lamda.expr
original_imageset[key_res] = value_res
dummy_n = value_res.lamda.expr.atoms(Dummy).pop()
(base,) = value_res.base_sets
imgset_yes = (dummy_n, base)
# update eq with everything that is known so far
eq2 = eq.subs(res).expand()
unsolved_syms = _unsolved_syms(eq2, sort=True)
if not unsolved_syms:
if res:
newresult, delete_res = _append_new_soln(
res, None, None, imgset_yes, soln_imageset,
original_imageset, newresult, eq2)
if delete_res:
# `delete_res` is true, means substituting `res` in
# eq2 doesn't return `zero` or deleting the `res`
# (a soln) since it staisfies expr of `exclude`
# list.
result.remove(res)
continue # skip as it's independent of desired symbols
depen1, depen2 = (eq2.rewrite(Add)).as_independent(*unsolved_syms)
if (depen1.has(Abs) or depen2.has(Abs)) and solver == solveset_complex:
# Absolute values cannot be inverted in the
# complex domain
continue
soln_imageset = {}
for sym in unsolved_syms:
not_solvable = False
try:
soln = solver(eq2, sym)
total_solvest_call += 1
soln_new = S.EmptySet
if isinstance(soln, Complement):
# separate solution and complement
complements[sym] = soln.args[1]
soln = soln.args[0]
# complement will be added at the end
if isinstance(soln, Intersection):
# Interval will be at 0th index always
if soln.args[0] != Interval(-oo, oo):
# sometimes solveset returns soln
# with intersection S.Reals, to confirm that
# soln is in domain=S.Reals
intersections[sym] = soln.args[0]
soln_new += soln.args[1]
soln = soln_new if soln_new else soln
if index > 0 and solver == solveset_real:
# one symbol's real soln, another symbol may have
# corresponding complex soln.
if not isinstance(soln, (ImageSet, ConditionSet)):
soln += solveset_complex(eq2, sym) # might give ValueError with Abs
except (NotImplementedError, ValueError):
# If solveset is not able to solve equation `eq2`. Next
# time we may get soln using next equation `eq2`
continue
if isinstance(soln, ConditionSet):
if soln.base_set in (S.Reals, S.Complexes):
soln = S.EmptySet
# don't do `continue` we may get soln
# in terms of other symbol(s)
not_solvable = True
total_conditionst += 1
else:
soln = soln.base_set
if soln is not S.EmptySet:
soln, soln_imageset = _extract_main_soln(
sym, soln, soln_imageset)
for sol in soln:
# sol is not a `Union` since we checked it
# before this loop
sol, soln_imageset = _extract_main_soln(
sym, sol, soln_imageset)
sol = set(sol).pop()
free = sol.free_symbols
if got_symbol and any(
ss in free for ss in got_symbol
):
# sol depends on previously solved symbols
# then continue
continue
rnew = res.copy()
# put each solution in res and append the new result
# in the new result list (solution for symbol `s`)
# along with old results.
for k, v in res.items():
if isinstance(v, Expr) and isinstance(sol, Expr):
# if any unsolved symbol is present
# Then subs known value
rnew[k] = v.subs(sym, sol)
# and add this new solution
if sol in soln_imageset.keys():
# replace all lambda variables with 0.
imgst = soln_imageset[sol]
rnew[sym] = imgst.lamda(
*[0 for i in range(0, len(
imgst.lamda.variables))])
else:
rnew[sym] = sol
newresult, delete_res = _append_new_soln(
rnew, sym, sol, imgset_yes, soln_imageset,
original_imageset, newresult)
if delete_res:
# deleting the `res` (a soln) since it staisfies
# eq of `exclude` list
result.remove(res)
# solution got for sym
if not not_solvable:
got_symbol.add(sym)
# next time use this new soln
if newresult:
result = newresult
return result, total_solvest_call, total_conditionst
# end def _solve_using_know_values()
new_result_real, solve_call1, cnd_call1 = _solve_using_known_values(
old_result, solveset_real)
new_result_complex, solve_call2, cnd_call2 = _solve_using_known_values(
old_result, solveset_complex)
# If total_solveset_call is equal to total_conditionset
# then solveset failed to solve all of the equations.
# In this case we return a ConditionSet here.
total_conditionset += (cnd_call1 + cnd_call2)
total_solveset_call += (solve_call1 + solve_call2)
if total_conditionset == total_solveset_call and total_solveset_call != -1:
return _return_conditionset(eqs_in_better_order, all_symbols)
# don't keep duplicate solutions
filtered_complex = []
for i in list(new_result_complex):
for j in list(new_result_real):
if i.keys() != j.keys():
continue
if all(a.dummy_eq(b) for a, b in zip(i.values(), j.values()) \
if not (isinstance(a, int) and isinstance(b, int))):
break
else:
filtered_complex.append(i)
# overall result
result = new_result_real + filtered_complex
result_all_variables = []
result_infinite = []
for res in result:
if not res:
# means {None : None}
continue
# If length < len(all_symbols) means infinite soln.
# Some or all the soln is dependent on 1 symbol.
# eg. {x: y+2} then final soln {x: y+2, y: y}
if len(res) < len(all_symbols):
solved_symbols = res.keys()
unsolved = list(filter(
lambda x: x not in solved_symbols, all_symbols))
for unsolved_sym in unsolved:
res[unsolved_sym] = unsolved_sym
result_infinite.append(res)
if res not in result_all_variables:
result_all_variables.append(res)
if result_infinite:
# we have general soln
# eg : [{x: -1, y : 1}, {x : -y, y: y}] then
# return [{x : -y, y : y}]
result_all_variables = result_infinite
if intersections or complements:
result_all_variables = add_intersection_complement(
result_all_variables, intersections, complements)
# convert to ordered tuple
result = S.EmptySet
for r in result_all_variables:
temp = [r[symb] for symb in all_symbols]
result += FiniteSet(tuple(temp))
return result
# end of def substitution()
def _solveset_work(system, symbols):
soln = solveset(system[0], symbols[0])
if isinstance(soln, FiniteSet):
_soln = FiniteSet(*[tuple((s,)) for s in soln])
return _soln
else:
return FiniteSet(tuple(FiniteSet(soln)))
def _handle_positive_dimensional(polys, symbols, denominators):
from sympy.polys.polytools import groebner
# substitution method where new system is groebner basis of the system
_symbols = list(symbols)
_symbols.sort(key=default_sort_key)
basis = groebner(polys, _symbols, polys=True)
new_system = []
for poly_eq in basis:
new_system.append(poly_eq.as_expr())
result = [{}]
result = substitution(
new_system, symbols, result, [],
denominators)
return result
# end of def _handle_positive_dimensional()
def _handle_zero_dimensional(polys, symbols, system):
# solve 0 dimensional poly system using `solve_poly_system`
result = solve_poly_system(polys, *symbols)
# May be some extra soln is added because
# we used `unrad` in `_separate_poly_nonpoly`, so
# need to check and remove if it is not a soln.
result_update = S.EmptySet
for res in result:
dict_sym_value = dict(list(zip(symbols, res)))
if all(checksol(eq, dict_sym_value) for eq in system):
result_update += FiniteSet(res)
return result_update
# end of def _handle_zero_dimensional()
def _separate_poly_nonpoly(system, symbols):
polys = []
polys_expr = []
nonpolys = []
denominators = set()
poly = None
for eq in system:
# Store denom expressions that contain symbols
denominators.update(_simple_dens(eq, symbols))
# Convert equality to expression
if isinstance(eq, Equality):
eq = eq.rewrite(Add)
# try to remove sqrt and rational power
without_radicals = unrad(simplify(eq), *symbols)
if without_radicals:
eq_unrad, cov = without_radicals
if not cov:
eq = eq_unrad
if isinstance(eq, Expr):
eq = eq.as_numer_denom()[0]
poly = eq.as_poly(*symbols, extension=True)
elif simplify(eq).is_number:
continue
if poly is not None:
polys.append(poly)
polys_expr.append(poly.as_expr())
else:
nonpolys.append(eq)
return polys, polys_expr, nonpolys, denominators
# end of def _separate_poly_nonpoly()
def nonlinsolve(system, *symbols):
r"""
Solve system of $N$ nonlinear equations with $M$ variables, which means both
under and overdetermined systems are supported. Positive dimensional
system is also supported (A system with infinitely many solutions is said
to be positive-dimensional). In a positive dimensional system the solution will
be dependent on at least one symbol. Returns both real solution
and complex solution (if they exist). The possible number of solutions
is zero, one or infinite.
Parameters
==========
system : list of equations
The target system of equations
symbols : list of Symbols
symbols should be given as a sequence eg. list
Returns
=======
A :class:`~.FiniteSet` of ordered tuple of values of `symbols` for which the `system`
has solution. Order of values in the tuple is same as symbols present in
the parameter `symbols`.
Please note that general :class:`~.FiniteSet` is unordered, the solution
returned here is not simply a :class:`~.FiniteSet` of solutions, rather it
is a :class:`~.FiniteSet` of ordered tuple, i.e. the first and only
argument to :class:`~.FiniteSet` is a tuple of solutions, which is
ordered, and, hence ,the returned solution is ordered.
Also note that solution could also have been returned as an ordered tuple,
FiniteSet is just a wrapper ``{}`` around the tuple. It has no other
significance except for the fact it is just used to maintain a consistent
output format throughout the solveset.
For the given set of equations, the respective input types
are given below:
.. math:: xy - 1 = 0
.. math:: 4x^2 + y^2 - 5 = 0
::
system = [x*y - 1, 4*x**2 + y**2 - 5]
symbols = [x, y]
Raises
======
ValueError
The input is not valid.
The symbols are not given.
AttributeError
The input symbols are not `Symbol` type.
Examples
========
>>> from sympy import symbols, nonlinsolve
>>> x, y, z = symbols('x, y, z', real=True)
>>> nonlinsolve([x*y - 1, 4*x**2 + y**2 - 5], [x, y])
{(-1, -1), (-1/2, -2), (1/2, 2), (1, 1)}
1. Positive dimensional system and complements:
>>> from sympy import pprint
>>> from sympy.polys.polytools import is_zero_dimensional
>>> a, b, c, d = symbols('a, b, c, d', extended_real=True)
>>> eq1 = a + b + c + d
>>> eq2 = a*b + b*c + c*d + d*a
>>> eq3 = a*b*c + b*c*d + c*d*a + d*a*b
>>> eq4 = a*b*c*d - 1
>>> system = [eq1, eq2, eq3, eq4]
>>> is_zero_dimensional(system)
False
>>> pprint(nonlinsolve(system, [a, b, c, d]), use_unicode=False)
-1 1 1 -1
{(---, -d, -, {d} \ {0}), (-, -d, ---, {d} \ {0})}
d d d d
>>> nonlinsolve([(x+y)**2 - 4, x + y - 2], [x, y])
{(2 - y, y)}
2. If some of the equations are non-polynomial then `nonlinsolve`
will call the ``substitution`` function and return real and complex solutions,
if present.
>>> from sympy import exp, sin
>>> nonlinsolve([exp(x) - sin(y), y**2 - 4], [x, y])
{(ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), Integers), -2),
(ImageSet(Lambda(_n, 2*_n*I*pi + log(sin(2))), Integers), 2)}
3. If system is non-linear polynomial and zero-dimensional then it
returns both solution (real and complex solutions, if present) using
:func:`~.solve_poly_system`:
>>> from sympy import sqrt
>>> nonlinsolve([x**2 - 2*y**2 -2, x*y - 2], [x, y])
{(-2, -1), (2, 1), (-sqrt(2)*I, sqrt(2)*I), (sqrt(2)*I, -sqrt(2)*I)}
4. ``nonlinsolve`` can solve some linear (zero or positive dimensional)
system (because it uses the :func:`sympy.polys.polytools.groebner` function to get the
groebner basis and then uses the ``substitution`` function basis as the
new `system`). But it is not recommended to solve linear system using
``nonlinsolve``, because :func:`~.linsolve` is better for general linear systems.
>>> nonlinsolve([x + 2*y -z - 3, x - y - 4*z + 9, y + z - 4], [x, y, z])
{(3*z - 5, 4 - z, z)}
5. System having polynomial equations and only real solution is
solved using :func:`~.solve_poly_system`:
>>> e1 = sqrt(x**2 + y**2) - 10
>>> e2 = sqrt(y**2 + (-x + 10)**2) - 3
>>> nonlinsolve((e1, e2), (x, y))
{(191/20, -3*sqrt(391)/20), (191/20, 3*sqrt(391)/20)}
>>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [x, y])
{(1, 2), (1 - sqrt(5), 2 + sqrt(5)), (1 + sqrt(5), 2 - sqrt(5))}
>>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [y, x])
{(2, 1), (2 - sqrt(5), 1 + sqrt(5)), (2 + sqrt(5), 1 - sqrt(5))}
6. It is better to use symbols instead of trigonometric functions or
:class:`~.Function`. For example, replace $\sin(x)$ with a symbol, replace
$f(x)$ with a symbol and so on. Get a solution from ``nonlinsolve`` and then
use :func:`~.solveset` to get the value of $x$.
How nonlinsolve is better than old solver ``_solve_system`` :
=============================================================
1. A positive dimensional system solver: nonlinsolve can return
solution for positive dimensional system. It finds the
Groebner Basis of the positive dimensional system(calling it as
basis) then we can start solving equation(having least number of
variable first in the basis) using solveset and substituting that
solved solutions into other equation(of basis) to get solution in
terms of minimum variables. Here the important thing is how we
are substituting the known values and in which equations.
2. Real and complex solutions: nonlinsolve returns both real
and complex solution. If all the equations in the system are polynomial
then using :func:`~.solve_poly_system` both real and complex solution is returned.
If all the equations in the system are not polynomial equation then goes to
``substitution`` method with this polynomial and non polynomial equation(s),
to solve for unsolved variables. Here to solve for particular variable
solveset_real and solveset_complex is used. For both real and complex
solution ``_solve_using_know_values`` is used inside ``substitution``
(``substitution`` will be called when any non-polynomial equation is present).
If a solution is valid its general solution is added to the final result.
3. :class:`~.Complement` and :class:`~.Intersection` will be added:
nonlinsolve maintains dict for complements and intersections. If solveset
find complements or/and intersections with any interval or set during the
execution of ``substitution`` function, then complement or/and
intersection for that variable is added before returning final solution.
"""
from sympy.polys.polytools import is_zero_dimensional
if not system:
return S.EmptySet
if not symbols:
msg = ('Symbols must be given, for which solution of the '
'system is to be found.')
raise ValueError(filldedent(msg))
if hasattr(symbols[0], '__iter__'):
symbols = symbols[0]
if not is_sequence(symbols) or not symbols:
msg = ('Symbols must be given, for which solution of the '
'system is to be found.')
raise IndexError(filldedent(msg))
system, symbols, swap = recast_to_symbols(system, symbols)
if swap:
soln = nonlinsolve(system, symbols)
return FiniteSet(*[tuple(i.xreplace(swap) for i in s) for s in soln])
if len(system) == 1 and len(symbols) == 1:
return _solveset_work(system, symbols)
# main code of def nonlinsolve() starts from here
polys, polys_expr, nonpolys, denominators = _separate_poly_nonpoly(
system, symbols)
if len(symbols) == len(polys):
# If all the equations in the system are poly
if is_zero_dimensional(polys, symbols):
# finite number of soln (Zero dimensional system)
try:
return _handle_zero_dimensional(polys, symbols, system)
except NotImplementedError:
# Right now it doesn't fail for any polynomial system of
# equation. If `solve_poly_system` fails then `substitution`
# method will handle it.
result = substitution(
polys_expr, symbols, exclude=denominators)
return result
# positive dimensional system
res = _handle_positive_dimensional(polys, symbols, denominators)
if res is S.EmptySet and any(not p.domain.is_Exact for p in polys):
raise NotImplementedError("Equation not in exact domain. Try converting to rational")
else:
return res
else:
# If all the equations are not polynomial.
# Use `substitution` method for the system
result = substitution(
polys_expr + nonpolys, symbols, exclude=denominators)
return result
|
75d27f64c47a3093852c8fad836d732f712ef86e8a6a2cea5423fba2918c53d4 | """
This module contains pdsolve() and different helper functions that it
uses. It is heavily inspired by the ode module and hence the basic
infrastructure remains the same.
**Functions in this module**
These are the user functions in this module:
- pdsolve() - Solves PDE's
- classify_pde() - Classifies PDEs into possible hints for dsolve().
- pde_separate() - Separate variables in partial differential equation either by
additive or multiplicative separation approach.
These are the helper functions in this module:
- pde_separate_add() - Helper function for searching additive separable solutions.
- pde_separate_mul() - Helper function for searching multiplicative
separable solutions.
**Currently implemented solver methods**
The following methods are implemented for solving partial differential
equations. See the docstrings of the various pde_hint() functions for
more information on each (run help(pde)):
- 1st order linear homogeneous partial differential equations
with constant coefficients.
- 1st order linear general partial differential equations
with constant coefficients.
- 1st order linear partial differential equations with
variable coefficients.
"""
from functools import reduce
from itertools import combinations_with_replacement
from sympy.simplify import simplify # type: ignore
from sympy.core import Add, S
from sympy.core.function import Function, expand, AppliedUndef, Subs
from sympy.core.relational import Equality, Eq
from sympy.core.symbol import Symbol, Wild, symbols
from sympy.functions import exp
from sympy.integrals.integrals import Integral, integrate
from sympy.utilities.iterables import has_dups, is_sequence
from sympy.utilities.misc import filldedent
from sympy.solvers.deutils import _preprocess, ode_order, _desolve
from sympy.solvers.solvers import solve
from sympy.simplify.radsimp import collect
import operator
allhints = (
"1st_linear_constant_coeff_homogeneous",
"1st_linear_constant_coeff",
"1st_linear_constant_coeff_Integral",
"1st_linear_variable_coeff"
)
def pdsolve(eq, func=None, hint='default', dict=False, solvefun=None, **kwargs):
"""
Solves any (supported) kind of partial differential equation.
**Usage**
pdsolve(eq, f(x,y), hint) -> Solve partial differential equation
eq for function f(x,y), using method hint.
**Details**
``eq`` can be any supported partial differential equation (see
the pde docstring for supported methods). This can either
be an Equality, or an expression, which is assumed to be
equal to 0.
``f(x,y)`` is a function of two variables whose derivatives in that
variable make up the partial differential equation. In many
cases it is not necessary to provide this; it will be autodetected
(and an error raised if it could not be detected).
``hint`` is the solving method that you want pdsolve to use. Use
classify_pde(eq, f(x,y)) to get all of the possible hints for
a PDE. The default hint, 'default', will use whatever hint
is returned first by classify_pde(). See Hints below for
more options that you can use for hint.
``solvefun`` is the convention used for arbitrary functions returned
by the PDE solver. If not set by the user, it is set by default
to be F.
**Hints**
Aside from the various solving methods, there are also some
meta-hints that you can pass to pdsolve():
"default":
This uses whatever hint is returned first by
classify_pde(). This is the default argument to
pdsolve().
"all":
To make pdsolve apply all relevant classification hints,
use pdsolve(PDE, func, hint="all"). This will return a
dictionary of hint:solution terms. If a hint causes
pdsolve 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 PDE. See also ode_order() in
deutils.py
- 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 classify_pde().
"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
pdsolve() to hang because of a difficult or impossible
integral. This meta-hint will also be much faster than
"all", because integrate() is an expensive routine.
See also the classify_pde() docstring for more info on hints,
and the pde 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, y # x and y are the independent variables
>>> f = Function("f")(x, y) # f is a function of x and y
>>> # fx will be the partial derivative of f with respect to x
>>> fx = Derivative(f, x)
>>> # fy will be the partial derivative of f with respect to y
>>> fy = Derivative(f, y)
- See test_pde.py for many tests, which serves also as a set of
examples for how to use pdsolve().
- pdsolve always returns an Equality class (except for the case
when the hint is "all" or "all_Integral"). Note that it is not possible
to get an explicit solution for f(x, y) as in the case of ODE's
- Do help(pde.pde_hintname) to get help more information on a
specific hint
Examples
========
>>> from sympy.solvers.pde import pdsolve
>>> from sympy import Function, Eq
>>> from sympy.abc import x, y
>>> f = Function('f')
>>> u = f(x, y)
>>> ux = u.diff(x)
>>> uy = u.diff(y)
>>> eq = Eq(1 + (2*(ux/u)) + (3*(uy/u)), 0)
>>> pdsolve(eq)
Eq(f(x, y), F(3*x - 2*y)*exp(-2*x/13 - 3*y/13))
"""
if not solvefun:
solvefun = Function('F')
# See the docstring of _desolve for more details.
hints = _desolve(eq, func=func, hint=hint, simplify=True,
type='pde', **kwargs)
eq = hints.pop('eq', False)
all_ = hints.pop('all', False)
if all_:
# TODO : 'best' hint should be implemented when adequate
# number of hints are added.
pdedict = {}
failed_hints = {}
gethints = classify_pde(eq, dict=True)
pdedict.update({'order': gethints['order'],
'default': gethints['default']})
for hint in hints:
try:
rv = _helper_simplify(eq, hint, hints[hint]['func'],
hints[hint]['order'], hints[hint][hint], solvefun)
except NotImplementedError as detail:
failed_hints[hint] = detail
else:
pdedict[hint] = rv
pdedict.update(failed_hints)
return pdedict
else:
return _helper_simplify(eq, hints['hint'], hints['func'],
hints['order'], hints[hints['hint']], solvefun)
def _helper_simplify(eq, hint, func, order, match, solvefun):
"""Helper function of pdsolve that calls the respective
pde functions to solve for the partial differential
equations. This minimizes the computation in
calling _desolve multiple times.
"""
if hint.endswith("_Integral"):
solvefunc = globals()[
"pde_" + hint[:-len("_Integral")]]
else:
solvefunc = globals()["pde_" + hint]
return _handle_Integral(solvefunc(eq, func, order,
match, solvefun), func, order, hint)
def _handle_Integral(expr, func, order, hint):
r"""
Converts a solution with integrals in it into an actual solution.
Simplifies the integral mainly using doit()
"""
if hint.endswith("_Integral"):
return expr
elif hint == "1st_linear_constant_coeff":
return simplify(expr.doit())
else:
return expr
def classify_pde(eq, func=None, dict=False, *, prep=True, **kwargs):
"""
Returns a tuple of possible pdsolve() classifications for a PDE.
The tuple is ordered so that first item is the classification that
pdsolve() uses to solve the PDE by default. In general,
classifications near the beginning of the list will produce
better solutions faster than those near the end, though there are
always exceptions. To make pdsolve use a different classification,
use pdsolve(PDE, func, hint=<classification>). See also the pdsolve()
docstring for different meta-hints you can use.
If ``dict`` is true, classify_pde() will return a dictionary of
hint:match expression terms. This is intended for internal use by
pdsolve(). 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 doing help(pde.pde_hintname),
where hintname is the name of the hint without "_Integral".
See sympy.pde.allhints or the sympy.pde docstring for a list of all
supported hints that can be returned from classify_pde.
Examples
========
>>> from sympy.solvers.pde import classify_pde
>>> from sympy import Function, Eq
>>> from sympy.abc import x, y
>>> f = Function('f')
>>> u = f(x, y)
>>> ux = u.diff(x)
>>> uy = u.diff(y)
>>> eq = Eq(1 + (2*(ux/u)) + (3*(uy/u)), 0)
>>> classify_pde(eq)
('1st_linear_constant_coeff_homogeneous',)
"""
if func and len(func.args) != 2:
raise NotImplementedError("Right now only partial "
"differential equations of two variables are supported")
if prep or func is None:
prep, func_ = _preprocess(eq, func)
if func is None:
func = func_
if isinstance(eq, Equality):
if eq.rhs != 0:
return classify_pde(eq.lhs - eq.rhs, func)
eq = eq.lhs
f = func.func
x = func.args[0]
y = func.args[1]
fx = f(x,y).diff(x)
fy = f(x,y).diff(y)
# TODO : For now pde.py uses support offered by the ode_order function
# to find the order with respect to a multi-variable function. An
# improvement could be to classify the order of the PDE on the basis of
# individual variables.
order = ode_order(eq, f(x,y))
# hint:matchdict or hint:(tuple of matchdicts)
# Also will contain "default":<default hint> and "order":order items.
matching_hints = {'order': order}
if not order:
if dict:
matching_hints["default"] = None
return matching_hints
else:
return ()
eq = expand(eq)
a = Wild('a', exclude = [f(x,y)])
b = Wild('b', exclude = [f(x,y), fx, fy, x, y])
c = Wild('c', exclude = [f(x,y), fx, fy, x, y])
d = Wild('d', exclude = [f(x,y), fx, fy, x, y])
e = Wild('e', exclude = [f(x,y), fx, fy])
n = Wild('n', exclude = [x, y])
# Try removing the smallest power of f(x,y)
# from the highest partial derivatives of f(x,y)
reduced_eq = None
if eq.is_Add:
var = set(combinations_with_replacement((x,y), order))
dummyvar = var.copy()
power = None
for i in var:
coeff = eq.coeff(f(x,y).diff(*i))
if coeff != 1:
match = coeff.match(a*f(x,y)**n)
if match and match[a]:
power = match[n]
dummyvar.remove(i)
break
dummyvar.remove(i)
for i in dummyvar:
coeff = eq.coeff(f(x,y).diff(*i))
if coeff != 1:
match = coeff.match(a*f(x,y)**n)
if match and match[a] and match[n] < power:
power = match[n]
if power:
den = f(x,y)**power
reduced_eq = Add(*[arg/den for arg in eq.args])
if not reduced_eq:
reduced_eq = eq
if order == 1:
reduced_eq = collect(reduced_eq, f(x, y))
r = reduced_eq.match(b*fx + c*fy + d*f(x,y) + e)
if r:
if not r[e]:
## Linear first-order homogeneous partial-differential
## equation with constant coefficients
r.update({'b': b, 'c': c, 'd': d})
matching_hints["1st_linear_constant_coeff_homogeneous"] = r
else:
if r[b]**2 + r[c]**2 != 0:
## Linear first-order general partial-differential
## equation with constant coefficients
r.update({'b': b, 'c': c, 'd': d, 'e': e})
matching_hints["1st_linear_constant_coeff"] = r
matching_hints[
"1st_linear_constant_coeff_Integral"] = r
else:
b = Wild('b', exclude=[f(x, y), fx, fy])
c = Wild('c', exclude=[f(x, y), fx, fy])
d = Wild('d', exclude=[f(x, y), fx, fy])
r = reduced_eq.match(b*fx + c*fy + d*f(x,y) + e)
if r:
r.update({'b': b, 'c': c, 'd': d, 'e': e})
matching_hints["1st_linear_variable_coeff"] = r
# Order keys based on allhints.
retlist = []
for i in allhints:
if i in matching_hints:
retlist.append(i)
if dict:
# Dictionaries are ordered arbitrarily, so make note of which
# hint would come first for pdsolve(). Use an ordered dict in Py 3.
matching_hints["default"] = None
matching_hints["ordered_hints"] = tuple(retlist)
for i in allhints:
if i in matching_hints:
matching_hints["default"] = i
break
return matching_hints
else:
return tuple(retlist)
def checkpdesol(pde, sol, func=None, solve_for_func=True):
"""
Checks if the given solution satisfies the partial differential
equation.
pde is the partial differential equation which can be given in the
form of an equation or an expression. sol is the solution for which
the pde is to be checked. This can also be given in an equation or
an expression form. If the function is not provided, the helper
function _preprocess from deutils is used to identify the function.
If a sequence of solutions is passed, the same sort of container will be
used to return the result for each solution.
The following methods are currently being implemented to check if the
solution satisfies the PDE:
1. Directly substitute the solution in the PDE and check. If the
solution has not been solved for f, then it will solve for f
provided solve_for_func has not been set to False.
If the solution satisfies the PDE, then a tuple (True, 0) is returned.
Otherwise a tuple (False, expr) where expr is the value obtained
after substituting the solution in the PDE. However if a known solution
returns False, it may be due to the inability of doit() to simplify it to zero.
Examples
========
>>> from sympy import Function, symbols
>>> from sympy.solvers.pde import checkpdesol, pdsolve
>>> x, y = symbols('x y')
>>> f = Function('f')
>>> eq = 2*f(x,y) + 3*f(x,y).diff(x) + 4*f(x,y).diff(y)
>>> sol = pdsolve(eq)
>>> assert checkpdesol(eq, sol)[0]
>>> eq = x*f(x,y) + f(x,y).diff(x)
>>> checkpdesol(eq, sol)
(False, (x*F(4*x - 3*y) - 6*F(4*x - 3*y)/25 + 4*Subs(Derivative(F(_xi_1), _xi_1), _xi_1, 4*x - 3*y))*exp(-6*x/25 - 8*y/25))
"""
# Converting the pde into an equation
if not isinstance(pde, Equality):
pde = Eq(pde, 0)
# If no function is given, try finding the function present.
if func is None:
try:
_, func = _preprocess(pde.lhs)
except ValueError:
funcs = [s.atoms(AppliedUndef) for s in (
sol if is_sequence(sol, set) else [sol])]
funcs = set().union(funcs)
if len(funcs) != 1:
raise ValueError(
'must pass func arg to checkpdesol for this case.')
func = funcs.pop()
# If the given solution is in the form of a list or a set
# then return a list or set of tuples.
if is_sequence(sol, set):
return type(sol)([checkpdesol(
pde, i, func=func,
solve_for_func=solve_for_func) for i in sol])
# Convert solution into an equation
if not isinstance(sol, Equality):
sol = Eq(func, sol)
elif sol.rhs == func:
sol = sol.reversed
# Try solving for the function
solved = sol.lhs == func and not sol.rhs.has(func)
if solve_for_func and not solved:
solved = solve(sol, func)
if solved:
if len(solved) == 1:
return checkpdesol(pde, Eq(func, solved[0]),
func=func, solve_for_func=False)
else:
return checkpdesol(pde, [Eq(func, t) for t in solved],
func=func, solve_for_func=False)
# try direct substitution of the solution into the PDE and simplify
if sol.lhs == func:
pde = pde.lhs - pde.rhs
s = simplify(pde.subs(func, sol.rhs).doit())
return s is S.Zero, s
raise NotImplementedError(filldedent('''
Unable to test if %s is a solution to %s.''' % (sol, pde)))
def pde_1st_linear_constant_coeff_homogeneous(eq, func, order, match, solvefun):
r"""
Solves a first order linear homogeneous
partial differential equation with constant coefficients.
The general form of this partial differential equation is
.. math:: a \frac{\partial f(x,y)}{\partial x}
+ b \frac{\partial f(x,y)}{\partial y} + c f(x,y) = 0
where `a`, `b` and `c` are constants.
The general solution is of the form:
.. math::
f(x, y) = F(- a y + b x ) e^{- \frac{c (a x + b y)}{a^2 + b^2}}
and can be found in SymPy with ``pdsolve``::
>>> from sympy.solvers import pdsolve
>>> from sympy.abc import x, y, a, b, c
>>> from sympy import Function, pprint
>>> f = Function('f')
>>> u = f(x,y)
>>> ux = u.diff(x)
>>> uy = u.diff(y)
>>> genform = a*ux + b*uy + c*u
>>> pprint(genform)
d d
a*--(f(x, y)) + b*--(f(x, y)) + c*f(x, y)
dx dy
>>> pprint(pdsolve(genform))
-c*(a*x + b*y)
---------------
2 2
a + b
f(x, y) = F(-a*y + b*x)*e
Examples
========
>>> from sympy import pdsolve
>>> from sympy import Function, pprint
>>> from sympy.abc import x,y
>>> f = Function('f')
>>> pdsolve(f(x,y) + f(x,y).diff(x) + f(x,y).diff(y))
Eq(f(x, y), F(x - y)*exp(-x/2 - y/2))
>>> pprint(pdsolve(f(x,y) + f(x,y).diff(x) + f(x,y).diff(y)))
x y
- - - -
2 2
f(x, y) = F(x - y)*e
References
==========
- Viktor Grigoryan, "Partial Differential Equations"
Math 124A - Fall 2010, pp.7
"""
# TODO : For now homogeneous first order linear PDE's having
# two variables are implemented. Once there is support for
# solving systems of ODE's, this can be extended to n variables.
f = func.func
x = func.args[0]
y = func.args[1]
b = match[match['b']]
c = match[match['c']]
d = match[match['d']]
return Eq(f(x,y), exp(-S(d)/(b**2 + c**2)*(b*x + c*y))*solvefun(c*x - b*y))
def pde_1st_linear_constant_coeff(eq, func, order, match, solvefun):
r"""
Solves a first order linear partial differential equation
with constant coefficients.
The general form of this partial differential equation is
.. math:: a \frac{\partial f(x,y)}{\partial x}
+ b \frac{\partial f(x,y)}{\partial y}
+ c f(x,y) = G(x,y)
where `a`, `b` and `c` are constants and `G(x, y)` can be an arbitrary
function in `x` and `y`.
The general solution of the PDE is:
.. math::
f(x, y) = \left. \left[F(\eta) + \frac{1}{a^2 + b^2}
\int\limits^{a x + b y} G\left(\frac{a \xi + b \eta}{a^2 + b^2},
\frac{- a \eta + b \xi}{a^2 + b^2} \right)
e^{\frac{c \xi}{a^2 + b^2}}\, d\xi\right]
e^{- \frac{c \xi}{a^2 + b^2}}
\right|_{\substack{\eta=- a y + b x\\ \xi=a x + b y }}\, ,
where `F(\eta)` is an arbitrary single-valued function. The solution
can be found in SymPy with ``pdsolve``::
>>> from sympy.solvers import pdsolve
>>> from sympy.abc import x, y, a, b, c
>>> from sympy import Function, pprint
>>> f = Function('f')
>>> G = Function('G')
>>> u = f(x,y)
>>> ux = u.diff(x)
>>> uy = u.diff(y)
>>> genform = a*ux + b*uy + c*u - G(x,y)
>>> pprint(genform)
d d
a*--(f(x, y)) + b*--(f(x, y)) + c*f(x, y) - G(x, y)
dx dy
>>> pprint(pdsolve(genform, hint='1st_linear_constant_coeff_Integral'))
// a*x + b*y \
|| / |
|| | |
|| | c*xi |
|| | ------- |
|| | 2 2 |
|| | /a*xi + b*eta -a*eta + b*xi\ a + b |
|| | G|------------, -------------|*e d(xi)|
|| | | 2 2 2 2 | |
|| | \ a + b a + b / |
|| | |
|| / |
|| |
f(x, y) = ||F(eta) + -------------------------------------------------------|*
|| 2 2 |
\\ a + b /
<BLANKLINE>
\|
||
||
||
||
||
||
||
||
-c*xi ||
-------||
2 2||
a + b ||
e ||
||
/|eta=-a*y + b*x, xi=a*x + b*y
Examples
========
>>> from sympy.solvers.pde import pdsolve
>>> from sympy import Function, pprint, exp
>>> from sympy.abc import x,y
>>> f = Function('f')
>>> eq = -2*f(x,y).diff(x) + 4*f(x,y).diff(y) + 5*f(x,y) - exp(x + 3*y)
>>> pdsolve(eq)
Eq(f(x, y), (F(4*x + 2*y)*exp(x/2) + exp(x + 4*y)/15)*exp(-y))
References
==========
- Viktor Grigoryan, "Partial Differential Equations"
Math 124A - Fall 2010, pp.7
"""
# TODO : For now homogeneous first order linear PDE's having
# two variables are implemented. Once there is support for
# solving systems of ODE's, this can be extended to n variables.
xi, eta = symbols("xi eta")
f = func.func
x = func.args[0]
y = func.args[1]
b = match[match['b']]
c = match[match['c']]
d = match[match['d']]
e = -match[match['e']]
expterm = exp(-S(d)/(b**2 + c**2)*xi)
functerm = solvefun(eta)
solvedict = solve((b*x + c*y - xi, c*x - b*y - eta), x, y)
# Integral should remain as it is in terms of xi,
# doit() should be done in _handle_Integral.
genterm = (1/S(b**2 + c**2))*Integral(
(1/expterm*e).subs(solvedict), (xi, b*x + c*y))
return Eq(f(x,y), Subs(expterm*(functerm + genterm),
(eta, xi), (c*x - b*y, b*x + c*y)))
def pde_1st_linear_variable_coeff(eq, func, order, match, solvefun):
r"""
Solves a first order linear partial differential equation
with variable coefficients. The general form of this partial
differential equation is
.. math:: a(x, y) \frac{\partial f(x, y)}{\partial x}
+ b(x, y) \frac{\partial f(x, y)}{\partial y}
+ c(x, y) f(x, y) = G(x, y)
where `a(x, y)`, `b(x, y)`, `c(x, y)` and `G(x, y)` are arbitrary
functions in `x` and `y`. This PDE is converted into an ODE by
making the following transformation:
1. `\xi` as `x`
2. `\eta` as the constant in the solution to the differential
equation `\frac{dy}{dx} = -\frac{b}{a}`
Making the previous substitutions reduces it to the linear ODE
.. math:: a(\xi, \eta)\frac{du}{d\xi} + c(\xi, \eta)u - G(\xi, \eta) = 0
which can be solved using ``dsolve``.
>>> from sympy.abc import x, y
>>> from sympy import Function, pprint
>>> a, b, c, G, f= [Function(i) for i in ['a', 'b', 'c', 'G', 'f']]
>>> u = f(x,y)
>>> ux = u.diff(x)
>>> uy = u.diff(y)
>>> genform = a(x, y)*u + b(x, y)*ux + c(x, y)*uy - G(x,y)
>>> pprint(genform)
d d
-G(x, y) + a(x, y)*f(x, y) + b(x, y)*--(f(x, y)) + c(x, y)*--(f(x, y))
dx dy
Examples
========
>>> from sympy.solvers.pde import pdsolve
>>> from sympy import Function, pprint
>>> from sympy.abc import x,y
>>> f = Function('f')
>>> eq = x*(u.diff(x)) - y*(u.diff(y)) + y**2*u - y**2
>>> pdsolve(eq)
Eq(f(x, y), F(x*y)*exp(y**2/2) + 1)
References
==========
- Viktor Grigoryan, "Partial Differential Equations"
Math 124A - Fall 2010, pp.7
"""
from sympy.solvers.ode import dsolve
xi, eta = symbols("xi eta")
f = func.func
x = func.args[0]
y = func.args[1]
b = match[match['b']]
c = match[match['c']]
d = match[match['d']]
e = -match[match['e']]
if not d:
# To deal with cases like b*ux = e or c*uy = e
if not (b and c):
if c:
try:
tsol = integrate(e/c, y)
except NotImplementedError:
raise NotImplementedError("Unable to find a solution"
" due to inability of integrate")
else:
return Eq(f(x,y), solvefun(x) + tsol)
if b:
try:
tsol = integrate(e/b, x)
except NotImplementedError:
raise NotImplementedError("Unable to find a solution"
" due to inability of integrate")
else:
return Eq(f(x,y), solvefun(y) + tsol)
if not c:
# To deal with cases when c is 0, a simpler method is used.
# The PDE reduces to b*(u.diff(x)) + d*u = e, which is a linear ODE in x
plode = f(x).diff(x)*b + d*f(x) - e
sol = dsolve(plode, f(x))
syms = sol.free_symbols - plode.free_symbols - {x, y}
rhs = _simplify_variable_coeff(sol.rhs, syms, solvefun, y)
return Eq(f(x, y), rhs)
if not b:
# To deal with cases when b is 0, a simpler method is used.
# The PDE reduces to c*(u.diff(y)) + d*u = e, which is a linear ODE in y
plode = f(y).diff(y)*c + d*f(y) - e
sol = dsolve(plode, f(y))
syms = sol.free_symbols - plode.free_symbols - {x, y}
rhs = _simplify_variable_coeff(sol.rhs, syms, solvefun, x)
return Eq(f(x, y), rhs)
dummy = Function('d')
h = (c/b).subs(y, dummy(x))
sol = dsolve(dummy(x).diff(x) - h, dummy(x))
if isinstance(sol, list):
sol = sol[0]
solsym = sol.free_symbols - h.free_symbols - {x, y}
if len(solsym) == 1:
solsym = solsym.pop()
etat = (solve(sol, solsym)[0]).subs(dummy(x), y)
ysub = solve(eta - etat, y)[0]
deq = (b*(f(x).diff(x)) + d*f(x) - e).subs(y, ysub)
final = (dsolve(deq, f(x), hint='1st_linear')).rhs
if isinstance(final, list):
final = final[0]
finsyms = final.free_symbols - deq.free_symbols - {x, y}
rhs = _simplify_variable_coeff(final, finsyms, solvefun, etat)
return Eq(f(x, y), rhs)
else:
raise NotImplementedError("Cannot solve the partial differential equation due"
" to inability of constantsimp")
def _simplify_variable_coeff(sol, syms, func, funcarg):
r"""
Helper function to replace constants by functions in 1st_linear_variable_coeff
"""
eta = Symbol("eta")
if len(syms) == 1:
sym = syms.pop()
final = sol.subs(sym, func(funcarg))
else:
for key, sym in enumerate(syms):
final = sol.subs(sym, func(funcarg))
return simplify(final.subs(eta, funcarg))
def pde_separate(eq, fun, sep, strategy='mul'):
"""Separate variables in partial differential equation either by additive
or multiplicative separation approach. It tries to rewrite an equation so
that one of the specified variables occurs on a different side of the
equation than the others.
:param eq: Partial differential equation
:param fun: Original function F(x, y, z)
:param sep: List of separated functions [X(x), u(y, z)]
:param strategy: Separation strategy. You can choose between additive
separation ('add') and multiplicative separation ('mul') which is
default.
Examples
========
>>> from sympy import E, Eq, Function, pde_separate, Derivative as D
>>> from sympy.abc import x, t
>>> u, X, T = map(Function, 'uXT')
>>> eq = Eq(D(u(x, t), x), E**(u(x, t))*D(u(x, t), t))
>>> pde_separate(eq, u(x, t), [X(x), T(t)], strategy='add')
[exp(-X(x))*Derivative(X(x), x), exp(T(t))*Derivative(T(t), t)]
>>> eq = Eq(D(u(x, t), x, 2), D(u(x, t), t, 2))
>>> pde_separate(eq, u(x, t), [X(x), T(t)], strategy='mul')
[Derivative(X(x), (x, 2))/X(x), Derivative(T(t), (t, 2))/T(t)]
See Also
========
pde_separate_add, pde_separate_mul
"""
do_add = False
if strategy == 'add':
do_add = True
elif strategy == 'mul':
do_add = False
else:
raise ValueError('Unknown strategy: %s' % strategy)
if isinstance(eq, Equality):
if eq.rhs != 0:
return pde_separate(Eq(eq.lhs - eq.rhs, 0), fun, sep, strategy)
else:
return pde_separate(Eq(eq, 0), fun, sep, strategy)
if eq.rhs != 0:
raise ValueError("Value should be 0")
# Handle arguments
orig_args = list(fun.args)
subs_args = []
for s in sep:
for j in range(0, len(s.args)):
subs_args.append(s.args[j])
if do_add:
functions = reduce(operator.add, sep)
else:
functions = reduce(operator.mul, sep)
# Check whether variables match
if len(subs_args) != len(orig_args):
raise ValueError("Variable counts do not match")
# Check for duplicate arguments like [X(x), u(x, y)]
if has_dups(subs_args):
raise ValueError("Duplicate substitution arguments detected")
# Check whether the variables match
if set(orig_args) != set(subs_args):
raise ValueError("Arguments do not match")
# Substitute original function with separated...
result = eq.lhs.subs(fun, functions).doit()
# Divide by terms when doing multiplicative separation
if not do_add:
eq = 0
for i in result.args:
eq += i/functions
result = eq
svar = subs_args[0]
dvar = subs_args[1:]
return _separate(result, svar, dvar)
def pde_separate_add(eq, fun, sep):
"""
Helper function for searching additive separable solutions.
Consider an equation of two independent variables x, y and a dependent
variable w, we look for the product of two functions depending on different
arguments:
`w(x, y, z) = X(x) + y(y, z)`
Examples
========
>>> from sympy import E, Eq, Function, pde_separate_add, Derivative as D
>>> from sympy.abc import x, t
>>> u, X, T = map(Function, 'uXT')
>>> eq = Eq(D(u(x, t), x), E**(u(x, t))*D(u(x, t), t))
>>> pde_separate_add(eq, u(x, t), [X(x), T(t)])
[exp(-X(x))*Derivative(X(x), x), exp(T(t))*Derivative(T(t), t)]
"""
return pde_separate(eq, fun, sep, strategy='add')
def pde_separate_mul(eq, fun, sep):
"""
Helper function for searching multiplicative separable solutions.
Consider an equation of two independent variables x, y and a dependent
variable w, we look for the product of two functions depending on different
arguments:
`w(x, y, z) = X(x)*u(y, z)`
Examples
========
>>> from sympy import Function, Eq, pde_separate_mul, Derivative as D
>>> from sympy.abc import x, y
>>> u, X, Y = map(Function, 'uXY')
>>> eq = Eq(D(u(x, y), x, 2), D(u(x, y), y, 2))
>>> pde_separate_mul(eq, u(x, y), [X(x), Y(y)])
[Derivative(X(x), (x, 2))/X(x), Derivative(Y(y), (y, 2))/Y(y)]
"""
return pde_separate(eq, fun, sep, strategy='mul')
def _separate(eq, dep, others):
"""Separate expression into two parts based on dependencies of variables."""
# FIRST PASS
# Extract derivatives depending our separable variable...
terms = set()
for term in eq.args:
if term.is_Mul:
for i in term.args:
if i.is_Derivative and not i.has(*others):
terms.add(term)
continue
elif term.is_Derivative and not term.has(*others):
terms.add(term)
# Find the factor that we need to divide by
div = set()
for term in terms:
ext, sep = term.expand().as_independent(dep)
# Failed?
if sep.has(*others):
return None
div.add(ext)
# FIXME: Find lcm() of all the divisors and divide with it, instead of
# current hack :(
# https://github.com/sympy/sympy/issues/4597
if len(div) > 0:
final = 0
for term in eq.args:
eqn = 0
for i in div:
eqn += term / i
final += simplify(eqn)
eq = final
# SECOND PASS - separate the derivatives
div = set()
lhs = rhs = 0
for term in eq.args:
# Check, whether we have already term with independent variable...
if not term.has(*others):
lhs += term
continue
# ...otherwise, try to separate
temp, sep = term.expand().as_independent(dep)
# Failed?
if sep.has(*others):
return None
# Extract the divisors
div.add(sep)
rhs -= term.expand()
# Do the division
fulldiv = reduce(operator.add, div)
lhs = simplify(lhs/fulldiv).expand()
rhs = simplify(rhs/fulldiv).expand()
# ...and check whether we were successful :)
if lhs.has(*others) or rhs.has(dep):
return None
return [lhs, rhs]
|
e05840beb34aaf39a913d5ac0cdfa744c82c725463ec38c93b971de92a8a90d9 | """Utility functions for classifying and solving
ordinary and partial differential equations.
Contains
========
_preprocess
ode_order
_desolve
"""
from sympy.core import Pow
from sympy.core.function import Derivative, AppliedUndef
from sympy.core.relational import Equality
from sympy.core.symbol import Wild
def _preprocess(expr, func=None, hint='_Integral'):
"""Prepare expr for solving by making sure that differentiation
is done so that only func remains in unevaluated derivatives and
(if hint does not end with _Integral) that doit is applied to all
other derivatives. If hint is None, do not do any differentiation.
(Currently this may cause some simple differential equations to
fail.)
In case func is None, an attempt will be made to autodetect the
function to be solved for.
>>> from sympy.solvers.deutils import _preprocess
>>> from sympy import Derivative, Function
>>> from sympy.abc import x, y, z
>>> f, g = map(Function, 'fg')
If f(x)**p == 0 and p>0 then we can solve for f(x)=0
>>> _preprocess((f(x).diff(x)-4)**5, f(x))
(Derivative(f(x), x) - 4, f(x))
Apply doit to derivatives that contain more than the function
of interest:
>>> _preprocess(Derivative(f(x) + x, x))
(Derivative(f(x), x) + 1, f(x))
Do others if the differentiation variable(s) intersect with those
of the function of interest or contain the function of interest:
>>> _preprocess(Derivative(g(x), y, z), f(y))
(0, f(y))
>>> _preprocess(Derivative(f(y), z), f(y))
(0, f(y))
Do others if the hint does not end in '_Integral' (the default
assumes that it does):
>>> _preprocess(Derivative(g(x), y), f(x))
(Derivative(g(x), y), f(x))
>>> _preprocess(Derivative(f(x), y), f(x), hint='')
(0, f(x))
Do not do any derivatives if hint is None:
>>> eq = Derivative(f(x) + 1, x) + Derivative(f(x), y)
>>> _preprocess(eq, f(x), hint=None)
(Derivative(f(x) + 1, x) + Derivative(f(x), y), f(x))
If it's not clear what the function of interest is, it must be given:
>>> eq = Derivative(f(x) + g(x), x)
>>> _preprocess(eq, g(x))
(Derivative(f(x), x) + Derivative(g(x), x), g(x))
>>> try: _preprocess(eq)
... except ValueError: print("A ValueError was raised.")
A ValueError was raised.
"""
if isinstance(expr, Pow):
# if f(x)**p=0 then f(x)=0 (p>0)
if (expr.exp).is_positive:
expr = expr.base
derivs = expr.atoms(Derivative)
if not func:
funcs = set().union(*[d.atoms(AppliedUndef) for d in derivs])
if len(funcs) != 1:
raise ValueError('The function cannot be '
'automatically detected for %s.' % expr)
func = funcs.pop()
fvars = set(func.args)
if hint is None:
return expr, func
reps = [(d, d.doit()) for d in derivs if not hint.endswith('_Integral') or
d.has(func) or set(d.variables) & fvars]
eq = expr.subs(reps)
return eq, func
def ode_order(expr, func):
"""
Returns the order of a given differential
equation with respect to func.
This function is implemented recursively.
Examples
========
>>> from sympy import Function
>>> from sympy.solvers.deutils import ode_order
>>> from sympy.abc import x
>>> f, g = map(Function, ['f', 'g'])
>>> ode_order(f(x).diff(x, 2) + f(x).diff(x)**2 +
... f(x).diff(x), f(x))
2
>>> ode_order(f(x).diff(x, 2) + g(x).diff(x, 3), f(x))
2
>>> ode_order(f(x).diff(x, 2) + g(x).diff(x, 3), g(x))
3
"""
a = Wild('a', exclude=[func])
if expr.match(a):
return 0
if isinstance(expr, Derivative):
if expr.args[0] == func:
return len(expr.variables)
else:
order = 0
for arg in expr.args[0].args:
order = max(order, ode_order(arg, func) + len(expr.variables))
return order
else:
order = 0
for arg in expr.args:
order = max(order, ode_order(arg, func))
return order
def _desolve(eq, func=None, hint="default", ics=None, simplify=True, *, prep=True, **kwargs):
"""This is a helper function to dsolve and pdsolve in the ode
and pde modules.
If the hint provided to the function is "default", then a dict with
the following keys are returned
'func' - It provides the function for which the differential equation
has to be solved. This is useful when the expression has
more than one function in it.
'default' - The default key as returned by classifier functions in ode
and pde.py
'hint' - The hint given by the user for which the differential equation
is to be solved. If the hint given by the user is 'default',
then the value of 'hint' and 'default' is the same.
'order' - The order of the function as returned by ode_order
'match' - It returns the match as given by the classifier functions, for
the default hint.
If the hint provided to the function is not "default" and is not in
('all', 'all_Integral', 'best'), then a dict with the above mentioned keys
is returned along with the keys which are returned when dict in
classify_ode or classify_pde is set True
If the hint given is in ('all', 'all_Integral', 'best'), then this function
returns a nested dict, with the keys, being the set of classified hints
returned by classifier functions, and the values being the dict of form
as mentioned above.
Key 'eq' is a common key to all the above mentioned hints which returns an
expression if eq given by user is an Equality.
See Also
========
classify_ode(ode.py)
classify_pde(pde.py)
"""
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
# preprocess the equation and find func if not given
if prep or func is None:
eq, func = _preprocess(eq, func)
prep = False
# type is an argument passed by the solve functions in ode and pde.py
# that identifies whether the function caller is an ordinary
# or partial differential equation. Accordingly corresponding
# changes are made in the function.
type = kwargs.get('type', None)
xi = kwargs.get('xi')
eta = kwargs.get('eta')
x0 = kwargs.get('x0', 0)
terms = kwargs.get('n')
if type == 'ode':
from sympy.solvers.ode import classify_ode, allhints
classifier = classify_ode
string = 'ODE '
dummy = ''
elif type == 'pde':
from sympy.solvers.pde import classify_pde, allhints
classifier = classify_pde
string = 'PDE '
dummy = 'p'
# Magic that should only be used internally. Prevents classify_ode from
# being called more than it needs to be by passing its results through
# recursive calls.
if kwargs.get('classify', True):
hints = classifier(eq, func, dict=True, ics=ics, xi=xi, eta=eta,
n=terms, x0=x0, hint=hint, prep=prep)
else:
# Here is what all this means:
#
# hint: The hint method given to _desolve() by the user.
# hints: The dictionary of hints that match the DE, along with other
# information (including the internal pass-through magic).
# default: The default hint to return, the first hint from allhints
# that matches the hint; obtained from classify_ode().
# match: Dictionary containing the match dictionary for each hint
# (the parts of the DE for solving). When going through the
# hints in "all", this holds the match string for the current
# hint.
# order: The order of the DE, as determined by ode_order().
hints = kwargs.get('hint',
{'default': hint,
hint: kwargs['match'],
'order': kwargs['order']})
if not hints['default']:
# classify_ode will set hints['default'] to None if no hints match.
if hint not in allhints and hint != 'default':
raise ValueError("Hint not recognized: " + hint)
elif hint not in hints['ordered_hints'] and hint != 'default':
raise ValueError(string + str(eq) + " does not match hint " + hint)
# If dsolve can't solve the purely algebraic equation then dsolve will raise
# ValueError
elif hints['order'] == 0:
raise ValueError(
str(eq) + " is not a solvable differential equation in " + str(func))
else:
raise NotImplementedError(dummy + "solve" + ": Cannot solve " + str(eq))
if hint == 'default':
return _desolve(eq, func, ics=ics, hint=hints['default'], simplify=simplify,
prep=prep, x0=x0, classify=False, order=hints['order'],
match=hints[hints['default']], xi=xi, eta=eta, n=terms, type=type)
elif hint in ('all', 'all_Integral', 'best'):
retdict = {}
gethints = set(hints) - {'order', 'default', 'ordered_hints'}
if hint == 'all_Integral':
for i in hints:
if i.endswith('_Integral'):
gethints.remove(i[:-len('_Integral')])
# special cases
for k in ["1st_homogeneous_coeff_best", "1st_power_series",
"lie_group", "2nd_power_series_ordinary", "2nd_power_series_regular"]:
if k in gethints:
gethints.remove(k)
for i in gethints:
sol = _desolve(eq, func, ics=ics, hint=i, x0=x0, simplify=simplify, prep=prep,
classify=False, n=terms, order=hints['order'], match=hints[i], type=type)
retdict[i] = sol
retdict['all'] = True
retdict['eq'] = eq
return retdict
elif hint not in allhints: # and hint not in ('default', 'ordered_hints'):
raise ValueError("Hint not recognized: " + hint)
elif hint not in hints:
raise ValueError(string + str(eq) + " does not match hint " + hint)
else:
# Key added to identify the hint needed to solve the equation
hints['hint'] = hint
hints.update({'func': func, 'eq': eq})
return hints
|
ef0e137b03b5f0fc6f8d0071c302cfdeedd533c190ef3250d49d42286370dac1 | """Solvers of systems of polynomial equations. """
from sympy.core import S
from sympy.core.sorting import default_sort_key
from sympy.polys import Poly, groebner, roots
from sympy.polys.polytools import parallel_poly_from_expr
from sympy.polys.polyerrors import (ComputationFailed,
PolificationFailed, CoercionFailed)
from sympy.simplify import rcollect
from sympy.utilities import postfixes
from sympy.utilities.misc import filldedent
class SolveFailed(Exception):
"""Raised when solver's conditions were not met. """
def solve_poly_system(seq, *gens, **args):
"""
Solve a system of polynomial equations.
Parameters
==========
seq: a list/tuple/set
Listing all the equations that are needed to be solved
gens: generators
generators of the equations in seq for which we want the
solutions
args: Keyword arguments
Special options for solving the equations
Returns
=======
List[Tuple]
A List of tuples. Solutions for symbols that satisfy the
equations listed in seq
Examples
========
>>> from sympy import solve_poly_system
>>> from sympy.abc import x, y
>>> solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y)
[(0, 0), (2, -sqrt(2)), (2, sqrt(2))]
"""
try:
polys, opt = parallel_poly_from_expr(seq, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('solve_poly_system', len(seq), exc)
if len(polys) == len(opt.gens) == 2:
f, g = polys
if all(i <= 2 for i in f.degree_list() + g.degree_list()):
try:
return solve_biquadratic(f, g, opt)
except SolveFailed:
pass
return solve_generic(polys, opt)
def solve_biquadratic(f, g, opt):
"""Solve a system of two bivariate quadratic polynomial equations.
Parameters
==========
f: a single Expr or Poly
First equation
g: a single Expr or Poly
Second Equation
opt: an Options object
For specifying keyword arguments and generators
Returns
=======
List[Tuple]
A List of tuples. Solutions for symbols that satisfy the
equations listed in seq.
Examples
========
>>> from sympy import Options, Poly
>>> from sympy.abc import x, y
>>> from sympy.solvers.polysys import solve_biquadratic
>>> NewOption = Options((x, y), {'domain': 'ZZ'})
>>> a = Poly(y**2 - 4 + x, y, x, domain='ZZ')
>>> b = Poly(y*2 + 3*x - 7, y, x, domain='ZZ')
>>> solve_biquadratic(a, b, NewOption)
[(1/3, 3), (41/27, 11/9)]
>>> a = Poly(y + x**2 - 3, y, x, domain='ZZ')
>>> b = Poly(-y + x - 4, y, x, domain='ZZ')
>>> solve_biquadratic(a, b, NewOption)
[(7/2 - sqrt(29)/2, -sqrt(29)/2 - 1/2), (sqrt(29)/2 + 7/2, -1/2 + \
sqrt(29)/2)]
"""
G = groebner([f, g])
if len(G) == 1 and G[0].is_ground:
return None
if len(G) != 2:
raise SolveFailed
x, y = opt.gens
p, q = G
if not p.gcd(q).is_ground:
# not 0-dimensional
raise SolveFailed
p = Poly(p, x, expand=False)
p_roots = [rcollect(expr, y) for expr in roots(p).keys()]
q = q.ltrim(-1)
q_roots = list(roots(q).keys())
solutions = []
for q_root in q_roots:
for p_root in p_roots:
solution = (p_root.subs(y, q_root), q_root)
solutions.append(solution)
return sorted(solutions, key=default_sort_key)
def solve_generic(polys, opt):
"""
Solve a generic system of polynomial equations.
Returns all possible solutions over C[x_1, x_2, ..., x_m] of a
set F = { f_1, f_2, ..., f_n } of polynomial equations, using
Groebner basis approach. For now only zero-dimensional systems
are supported, which means F can have at most a finite number
of solutions.
The algorithm works by the fact that, supposing G is the basis
of F with respect to an elimination order (here lexicographic
order is used), G and F generate the same ideal, they have the
same set of solutions. By the elimination property, if G is a
reduced, zero-dimensional Groebner basis, then there exists an
univariate polynomial in G (in its last variable). This can be
solved by computing its roots. Substituting all computed roots
for the last (eliminated) variable in other elements of G, new
polynomial system is generated. Applying the above procedure
recursively, a finite number of solutions can be found.
The ability of finding all solutions by this procedure depends
on the root finding algorithms. If no solutions were found, it
means only that roots() failed, but the system is solvable. To
overcome this difficulty use numerical algorithms instead.
Parameters
==========
polys: a list/tuple/set
Listing all the polynomial equations that are needed to be solved
opt: an Options object
For specifying keyword arguments and generators
Returns
=======
List[Tuple]
A List of tuples. Solutions for symbols that satisfy the
equations listed in seq
References
==========
.. [Buchberger01] B. Buchberger, Groebner Bases: A Short
Introduction for Systems Theorists, In: R. Moreno-Diaz,
B. Buchberger, J.L. Freire, Proceedings of EUROCAST'01,
February, 2001
.. [Cox97] D. Cox, J. Little, D. O'Shea, Ideals, Varieties
and Algorithms, Springer, Second Edition, 1997, pp. 112
Examples
========
>>> from sympy import Poly, Options
>>> from sympy.solvers.polysys import solve_generic
>>> from sympy.abc import x, y
>>> NewOption = Options((x, y), {'domain': 'ZZ'})
>>> a = Poly(x - y + 5, x, y, domain='ZZ')
>>> b = Poly(x + y - 3, x, y, domain='ZZ')
>>> solve_generic([a, b], NewOption)
[(-1, 4)]
>>> a = Poly(x - 2*y + 5, x, y, domain='ZZ')
>>> b = Poly(2*x - y - 3, x, y, domain='ZZ')
>>> solve_generic([a, b], NewOption)
[(11/3, 13/3)]
>>> a = Poly(x**2 + y, x, y, domain='ZZ')
>>> b = Poly(x + y*4, x, y, domain='ZZ')
>>> solve_generic([a, b], NewOption)
[(0, 0), (1/4, -1/16)]
"""
def _is_univariate(f):
"""Returns True if 'f' is univariate in its last variable. """
for monom in f.monoms():
if any(monom[:-1]):
return False
return True
def _subs_root(f, gen, zero):
"""Replace generator with a root so that the result is nice. """
p = f.as_expr({gen: zero})
if f.degree(gen) >= 2:
p = p.expand(deep=False)
return p
def _solve_reduced_system(system, gens, entry=False):
"""Recursively solves reduced polynomial systems. """
if len(system) == len(gens) == 1:
zeros = list(roots(system[0], gens[-1]).keys())
return [(zero,) for zero in zeros]
basis = groebner(system, gens, polys=True)
if len(basis) == 1 and basis[0].is_ground:
if not entry:
return []
else:
return None
univariate = list(filter(_is_univariate, basis))
if len(basis) < len(gens):
raise NotImplementedError(filldedent('''
only zero-dimensional systems supported
(finite number of solutions)
'''))
if len(univariate) == 1:
f = univariate.pop()
else:
raise NotImplementedError(filldedent('''
only zero-dimensional systems supported
(finite number of solutions)
'''))
gens = f.gens
gen = gens[-1]
zeros = list(roots(f.ltrim(gen)).keys())
if not zeros:
return []
if len(basis) == 1:
return [(zero,) for zero in zeros]
solutions = []
for zero in zeros:
new_system = []
new_gens = gens[:-1]
for b in basis[:-1]:
eq = _subs_root(b, gen, zero)
if eq is not S.Zero:
new_system.append(eq)
for solution in _solve_reduced_system(new_system, new_gens):
solutions.append(solution + (zero,))
if solutions and len(solutions[0]) != len(gens):
raise NotImplementedError(filldedent('''
only zero-dimensional systems supported
(finite number of solutions)
'''))
return solutions
try:
result = _solve_reduced_system(polys, opt.gens, entry=True)
except CoercionFailed:
raise NotImplementedError
if result is not None:
return sorted(result, key=default_sort_key)
else:
return None
def solve_triangulated(polys, *gens, **args):
"""
Solve a polynomial system using Gianni-Kalkbrenner algorithm.
The algorithm proceeds by computing one Groebner basis in the ground
domain and then by iteratively computing polynomial factorizations in
appropriately constructed algebraic extensions of the ground domain.
Parameters
==========
polys: a list/tuple/set
Listing all the equations that are needed to be solved
gens: generators
generators of the equations in polys for which we want the
solutions
args: Keyword arguments
Special options for solving the equations
Returns
=======
List[Tuple]
A List of tuples. Solutions for symbols that satisfy the
equations listed in polys
Examples
========
>>> from sympy import solve_triangulated
>>> from sympy.abc import x, y, z
>>> F = [x**2 + y + z - 1, x + y**2 + z - 1, x + y + z**2 - 1]
>>> solve_triangulated(F, x, y, z)
[(0, 0, 1), (0, 1, 0), (1, 0, 0)]
References
==========
1. Patrizia Gianni, Teo Mora, Algebraic Solution of System of
Polynomial Equations using Groebner Bases, AAECC-5 on Applied Algebra,
Algebraic Algorithms and Error-Correcting Codes, LNCS 356 247--257, 1989
"""
G = groebner(polys, gens, polys=True)
G = list(reversed(G))
domain = args.get('domain')
if domain is not None:
for i, g in enumerate(G):
G[i] = g.set_domain(domain)
f, G = G[0].ltrim(-1), G[1:]
dom = f.get_domain()
zeros = f.ground_roots()
solutions = set()
for zero in zeros:
solutions.add(((zero,), dom))
var_seq = reversed(gens[:-1])
vars_seq = postfixes(gens[1:])
for var, vars in zip(var_seq, vars_seq):
_solutions = set()
for values, dom in solutions:
H, mapping = [], list(zip(vars, values))
for g in G:
_vars = (var,) + vars
if g.has_only_gens(*_vars) and g.degree(var) != 0:
h = g.ltrim(var).eval(dict(mapping))
if g.degree(var) == h.degree():
H.append(h)
p = min(H, key=lambda h: h.degree())
zeros = p.ground_roots()
for zero in zeros:
if not zero.is_Rational:
dom_zero = dom.algebraic_field(zero)
else:
dom_zero = dom
_solutions.add(((zero,) + values, dom_zero))
solutions = _solutions
solutions = list(solutions)
for i, (solution, _) in enumerate(solutions):
solutions[i] = solution
return sorted(solutions, key=default_sort_key)
|
58e9c71b81ae2c21ba20cbd4499b2ba2c60cbe5e9415b3034983c2fe3a267b5a | """Tools for solving inequalities and systems of inequalities. """
from sympy.calculus.util import (continuous_domain, periodicity,
function_range)
from sympy.core import Symbol, Dummy, sympify
from sympy.core.exprtools import factor_terms
from sympy.core.relational import Relational, Eq, Ge, Lt
from sympy.sets.sets import Interval, FiniteSet, Union, Intersection
from sympy.core.singleton import S
from sympy.core.function import expand_mul
from sympy.functions.elementary.complexes import im, Abs
from sympy.logic import And
from sympy.polys import Poly, PolynomialError, parallel_poly_from_expr
from sympy.polys.polyutils import _nsort
from sympy.solvers.solveset import solvify, solveset
from sympy.utilities.iterables import sift, iterable
from sympy.utilities.misc import filldedent
def solve_poly_inequality(poly, rel):
"""Solve a polynomial inequality with rational coefficients.
Examples
========
>>> from sympy import solve_poly_inequality, Poly
>>> from sympy.abc import x
>>> solve_poly_inequality(Poly(x, x, domain='ZZ'), '==')
[{0}]
>>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '!=')
[Interval.open(-oo, -1), Interval.open(-1, 1), Interval.open(1, oo)]
>>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '==')
[{-1}, {1}]
See Also
========
solve_poly_inequalities
"""
if not isinstance(poly, Poly):
raise ValueError(
'For efficiency reasons, `poly` should be a Poly instance')
if poly.as_expr().is_number:
t = Relational(poly.as_expr(), 0, rel)
if t is S.true:
return [S.Reals]
elif t is S.false:
return [S.EmptySet]
else:
raise NotImplementedError(
"could not determine truth value of %s" % t)
reals, intervals = poly.real_roots(multiple=False), []
if rel == '==':
for root, _ in reals:
interval = Interval(root, root)
intervals.append(interval)
elif rel == '!=':
left = S.NegativeInfinity
for right, _ in reals + [(S.Infinity, 1)]:
interval = Interval(left, right, True, True)
intervals.append(interval)
left = right
else:
if poly.LC() > 0:
sign = +1
else:
sign = -1
eq_sign, equal = None, False
if rel == '>':
eq_sign = +1
elif rel == '<':
eq_sign = -1
elif rel == '>=':
eq_sign, equal = +1, True
elif rel == '<=':
eq_sign, equal = -1, True
else:
raise ValueError("'%s' is not a valid relation" % rel)
right, right_open = S.Infinity, True
for left, multiplicity in reversed(reals):
if multiplicity % 2:
if sign == eq_sign:
intervals.insert(
0, Interval(left, right, not equal, right_open))
sign, right, right_open = -sign, left, not equal
else:
if sign == eq_sign and not equal:
intervals.insert(
0, Interval(left, right, True, right_open))
right, right_open = left, True
elif sign != eq_sign and equal:
intervals.insert(0, Interval(left, left))
if sign == eq_sign:
intervals.insert(
0, Interval(S.NegativeInfinity, right, True, right_open))
return intervals
def solve_poly_inequalities(polys):
"""Solve polynomial inequalities with rational coefficients.
Examples
========
>>> from sympy import Poly
>>> from sympy.solvers.inequalities import solve_poly_inequalities
>>> from sympy.abc import x
>>> solve_poly_inequalities(((
... Poly(x**2 - 3), ">"), (
... Poly(-x**2 + 1), ">")))
Union(Interval.open(-oo, -sqrt(3)), Interval.open(-1, 1), Interval.open(sqrt(3), oo))
"""
return Union(*[s for p in polys for s in solve_poly_inequality(*p)])
def solve_rational_inequalities(eqs):
"""Solve a system of rational inequalities with rational coefficients.
Examples
========
>>> from sympy.abc import x
>>> from sympy import solve_rational_inequalities, Poly
>>> solve_rational_inequalities([[
... ((Poly(-x + 1), Poly(1, x)), '>='),
... ((Poly(-x + 1), Poly(1, x)), '<=')]])
{1}
>>> solve_rational_inequalities([[
... ((Poly(x), Poly(1, x)), '!='),
... ((Poly(-x + 1), Poly(1, x)), '>=')]])
Union(Interval.open(-oo, 0), Interval.Lopen(0, 1))
See Also
========
solve_poly_inequality
"""
result = S.EmptySet
for _eqs in eqs:
if not _eqs:
continue
global_intervals = [Interval(S.NegativeInfinity, S.Infinity)]
for (numer, denom), rel in _eqs:
numer_intervals = solve_poly_inequality(numer*denom, rel)
denom_intervals = solve_poly_inequality(denom, '==')
intervals = []
for numer_interval in numer_intervals:
for global_interval in global_intervals:
interval = numer_interval.intersect(global_interval)
if interval is not S.EmptySet:
intervals.append(interval)
global_intervals = intervals
intervals = []
for global_interval in global_intervals:
for denom_interval in denom_intervals:
global_interval -= denom_interval
if global_interval is not S.EmptySet:
intervals.append(global_interval)
global_intervals = intervals
if not global_intervals:
break
for interval in global_intervals:
result = result.union(interval)
return result
def reduce_rational_inequalities(exprs, gen, relational=True):
"""Reduce a system of rational inequalities with rational coefficients.
Examples
========
>>> from sympy import Symbol
>>> from sympy.solvers.inequalities import reduce_rational_inequalities
>>> x = Symbol('x', real=True)
>>> reduce_rational_inequalities([[x**2 <= 0]], x)
Eq(x, 0)
>>> reduce_rational_inequalities([[x + 2 > 0]], x)
-2 < x
>>> reduce_rational_inequalities([[(x + 2, ">")]], x)
-2 < x
>>> reduce_rational_inequalities([[x + 2]], x)
Eq(x, -2)
This function find the non-infinite solution set so if the unknown symbol
is declared as extended real rather than real then the result may include
finiteness conditions:
>>> y = Symbol('y', extended_real=True)
>>> reduce_rational_inequalities([[y + 2 > 0]], y)
(-2 < y) & (y < oo)
"""
exact = True
eqs = []
solution = S.Reals if exprs else S.EmptySet
for _exprs in exprs:
_eqs = []
for expr in _exprs:
if isinstance(expr, tuple):
expr, rel = expr
else:
if expr.is_Relational:
expr, rel = expr.lhs - expr.rhs, expr.rel_op
else:
expr, rel = expr, '=='
if expr is S.true:
numer, denom, rel = S.Zero, S.One, '=='
elif expr is S.false:
numer, denom, rel = S.One, S.One, '=='
else:
numer, denom = expr.together().as_numer_denom()
try:
(numer, denom), opt = parallel_poly_from_expr(
(numer, denom), gen)
except PolynomialError:
raise PolynomialError(filldedent('''
only polynomials and rational functions are
supported in this context.
'''))
if not opt.domain.is_Exact:
numer, denom, exact = numer.to_exact(), denom.to_exact(), False
domain = opt.domain.get_exact()
if not (domain.is_ZZ or domain.is_QQ):
expr = numer/denom
expr = Relational(expr, 0, rel)
solution &= solve_univariate_inequality(expr, gen, relational=False)
else:
_eqs.append(((numer, denom), rel))
if _eqs:
eqs.append(_eqs)
if eqs:
solution &= solve_rational_inequalities(eqs)
exclude = solve_rational_inequalities([[((d, d.one), '==')
for i in eqs for ((n, d), _) in i if d.has(gen)]])
solution -= exclude
if not exact and solution:
solution = solution.evalf()
if relational:
solution = solution.as_relational(gen)
return solution
def reduce_abs_inequality(expr, rel, gen):
"""Reduce an inequality with nested absolute values.
Examples
========
>>> from sympy import reduce_abs_inequality, Abs, Symbol
>>> x = Symbol('x', real=True)
>>> reduce_abs_inequality(Abs(x - 5) - 3, '<', x)
(2 < x) & (x < 8)
>>> reduce_abs_inequality(Abs(x + 2)*3 - 13, '<', x)
(-19/3 < x) & (x < 7/3)
See Also
========
reduce_abs_inequalities
"""
if gen.is_extended_real is False:
raise TypeError(filldedent('''
Cannot solve inequalities with absolute values containing
non-real variables.
'''))
def _bottom_up_scan(expr):
exprs = []
if expr.is_Add or expr.is_Mul:
op = expr.func
for arg in expr.args:
_exprs = _bottom_up_scan(arg)
if not exprs:
exprs = _exprs
else:
args = []
for expr, conds in exprs:
for _expr, _conds in _exprs:
args.append((op(expr, _expr), conds + _conds))
exprs = args
elif expr.is_Pow:
n = expr.exp
if not n.is_Integer:
raise ValueError("Only Integer Powers are allowed on Abs.")
_exprs = _bottom_up_scan(expr.base)
for expr, conds in _exprs:
exprs.append((expr**n, conds))
elif isinstance(expr, Abs):
_exprs = _bottom_up_scan(expr.args[0])
for expr, conds in _exprs:
exprs.append(( expr, conds + [Ge(expr, 0)]))
exprs.append((-expr, conds + [Lt(expr, 0)]))
else:
exprs = [(expr, [])]
return exprs
exprs = _bottom_up_scan(expr)
mapping = {'<': '>', '<=': '>='}
inequalities = []
for expr, conds in exprs:
if rel not in mapping.keys():
expr = Relational( expr, 0, rel)
else:
expr = Relational(-expr, 0, mapping[rel])
inequalities.append([expr] + conds)
return reduce_rational_inequalities(inequalities, gen)
def reduce_abs_inequalities(exprs, gen):
"""Reduce a system of inequalities with nested absolute values.
Examples
========
>>> from sympy import reduce_abs_inequalities, Abs, Symbol
>>> x = Symbol('x', extended_real=True)
>>> reduce_abs_inequalities([(Abs(3*x - 5) - 7, '<'),
... (Abs(x + 25) - 13, '>')], x)
(-2/3 < x) & (x < 4) & (((-oo < x) & (x < -38)) | ((-12 < x) & (x < oo)))
>>> reduce_abs_inequalities([(Abs(x - 4) + Abs(3*x - 5) - 7, '<')], x)
(1/2 < x) & (x < 4)
See Also
========
reduce_abs_inequality
"""
return And(*[ reduce_abs_inequality(expr, rel, gen)
for expr, rel in exprs ])
def solve_univariate_inequality(expr, gen, relational=True, domain=S.Reals, continuous=False):
"""Solves a real univariate inequality.
Parameters
==========
expr : Relational
The target inequality
gen : Symbol
The variable for which the inequality is solved
relational : bool
A Relational type output is expected or not
domain : Set
The domain over which the equation is solved
continuous: bool
True if expr is known to be continuous over the given domain
(and so continuous_domain() does not need to be called on it)
Raises
======
NotImplementedError
The solution of the inequality cannot be determined due to limitation
in :func:`sympy.solvers.solveset.solvify`.
Notes
=====
Currently, we cannot solve all the inequalities due to limitations in
:func:`sympy.solvers.solveset.solvify`. Also, the solution returned for trigonometric inequalities
are restricted in its periodic interval.
See Also
========
sympy.solvers.solveset.solvify: solver returning solveset solutions with solve's output API
Examples
========
>>> from sympy import solve_univariate_inequality, Symbol, sin, Interval, S
>>> x = Symbol('x')
>>> solve_univariate_inequality(x**2 >= 4, x)
((2 <= x) & (x < oo)) | ((-oo < x) & (x <= -2))
>>> solve_univariate_inequality(x**2 >= 4, x, relational=False)
Union(Interval(-oo, -2), Interval(2, oo))
>>> domain = Interval(0, S.Infinity)
>>> solve_univariate_inequality(x**2 >= 4, x, False, domain)
Interval(2, oo)
>>> solve_univariate_inequality(sin(x) > 0, x, relational=False)
Interval.open(0, pi)
"""
from sympy.solvers.solvers import denoms
if domain.is_subset(S.Reals) is False:
raise NotImplementedError(filldedent('''
Inequalities in the complex domain are
not supported. Try the real domain by
setting domain=S.Reals'''))
elif domain is not S.Reals:
rv = solve_univariate_inequality(
expr, gen, relational=False, continuous=continuous).intersection(domain)
if relational:
rv = rv.as_relational(gen)
return rv
else:
pass # continue with attempt to solve in Real domain
# This keeps the function independent of the assumptions about `gen`.
# `solveset` makes sure this function is called only when the domain is
# real.
_gen = gen
_domain = domain
if gen.is_extended_real is False:
rv = S.EmptySet
return rv if not relational else rv.as_relational(_gen)
elif gen.is_extended_real is None:
gen = Dummy('gen', extended_real=True)
try:
expr = expr.xreplace({_gen: gen})
except TypeError:
raise TypeError(filldedent('''
When gen is real, the relational has a complex part
which leads to an invalid comparison like I < 0.
'''))
rv = None
if expr is S.true:
rv = domain
elif expr is S.false:
rv = S.EmptySet
else:
e = expr.lhs - expr.rhs
period = periodicity(e, gen)
if period == S.Zero:
e = expand_mul(e)
const = expr.func(e, 0)
if const is S.true:
rv = domain
elif const is S.false:
rv = S.EmptySet
elif period is not None:
frange = function_range(e, gen, domain)
rel = expr.rel_op
if rel in ('<', '<='):
if expr.func(frange.sup, 0):
rv = domain
elif not expr.func(frange.inf, 0):
rv = S.EmptySet
elif rel in ('>', '>='):
if expr.func(frange.inf, 0):
rv = domain
elif not expr.func(frange.sup, 0):
rv = S.EmptySet
inf, sup = domain.inf, domain.sup
if sup - inf is S.Infinity:
domain = Interval(0, period, False, True).intersect(_domain)
_domain = domain
if rv is None:
n, d = e.as_numer_denom()
try:
if gen not in n.free_symbols and len(e.free_symbols) > 1:
raise ValueError
# this might raise ValueError on its own
# or it might give None...
solns = solvify(e, gen, domain)
if solns is None:
# in which case we raise ValueError
raise ValueError
except (ValueError, NotImplementedError):
# replace gen with generic x since it's
# univariate anyway
raise NotImplementedError(filldedent('''
The inequality, %s, cannot be solved using
solve_univariate_inequality.
''' % expr.subs(gen, Symbol('x'))))
expanded_e = expand_mul(e)
def valid(x):
# this is used to see if gen=x satisfies the
# relational by substituting it into the
# expanded form and testing against 0, e.g.
# if expr = x*(x + 1) < 2 then e = x*(x + 1) - 2
# and expanded_e = x**2 + x - 2; the test is
# whether a given value of x satisfies
# x**2 + x - 2 < 0
#
# expanded_e, expr and gen used from enclosing scope
v = expanded_e.subs(gen, expand_mul(x))
try:
r = expr.func(v, 0)
except TypeError:
r = S.false
if r in (S.true, S.false):
return r
if v.is_extended_real is False:
return S.false
else:
v = v.n(2)
if v.is_comparable:
return expr.func(v, 0)
# not comparable or couldn't be evaluated
raise NotImplementedError(
'relationship did not evaluate: %s' % r)
singularities = []
for d in denoms(expr, gen):
singularities.extend(solvify(d, gen, domain))
if not continuous:
domain = continuous_domain(expanded_e, gen, domain)
include_x = '=' in expr.rel_op and expr.rel_op != '!='
try:
discontinuities = set(domain.boundary -
FiniteSet(domain.inf, domain.sup))
# remove points that are not between inf and sup of domain
critical_points = FiniteSet(*(solns + singularities + list(
discontinuities))).intersection(
Interval(domain.inf, domain.sup,
domain.inf not in domain, domain.sup not in domain))
if all(r.is_number for r in critical_points):
reals = _nsort(critical_points, separated=True)[0]
else:
sifted = sift(critical_points, lambda x: x.is_extended_real)
if sifted[None]:
# there were some roots that weren't known
# to be real
raise NotImplementedError
try:
reals = sifted[True]
if len(reals) > 1:
reals = list(sorted(reals))
except TypeError:
raise NotImplementedError
except NotImplementedError:
raise NotImplementedError('sorting of these roots is not supported')
# If expr contains imaginary coefficients, only take real
# values of x for which the imaginary part is 0
make_real = S.Reals
if im(expanded_e) != S.Zero:
check = True
im_sol = FiniteSet()
try:
a = solveset(im(expanded_e), gen, domain)
if not isinstance(a, Interval):
for z in a:
if z not in singularities and valid(z) and z.is_extended_real:
im_sol += FiniteSet(z)
else:
start, end = a.inf, a.sup
for z in _nsort(critical_points + FiniteSet(end)):
valid_start = valid(start)
if start != end:
valid_z = valid(z)
pt = _pt(start, z)
if pt not in singularities and pt.is_extended_real and valid(pt):
if valid_start and valid_z:
im_sol += Interval(start, z)
elif valid_start:
im_sol += Interval.Ropen(start, z)
elif valid_z:
im_sol += Interval.Lopen(start, z)
else:
im_sol += Interval.open(start, z)
start = z
for s in singularities:
im_sol -= FiniteSet(s)
except (TypeError):
im_sol = S.Reals
check = False
if im_sol is S.EmptySet:
raise ValueError(filldedent('''
%s contains imaginary parts which cannot be
made 0 for any value of %s satisfying the
inequality, leading to relations like I < 0.
''' % (expr.subs(gen, _gen), _gen)))
make_real = make_real.intersect(im_sol)
sol_sets = [S.EmptySet]
start = domain.inf
if start in domain and valid(start) and start.is_finite:
sol_sets.append(FiniteSet(start))
for x in reals:
end = x
if valid(_pt(start, end)):
sol_sets.append(Interval(start, end, True, True))
if x in singularities:
singularities.remove(x)
else:
if x in discontinuities:
discontinuities.remove(x)
_valid = valid(x)
else: # it's a solution
_valid = include_x
if _valid:
sol_sets.append(FiniteSet(x))
start = end
end = domain.sup
if end in domain and valid(end) and end.is_finite:
sol_sets.append(FiniteSet(end))
if valid(_pt(start, end)):
sol_sets.append(Interval.open(start, end))
if im(expanded_e) != S.Zero and check:
rv = (make_real).intersect(_domain)
else:
rv = Intersection(
(Union(*sol_sets)), make_real, _domain).subs(gen, _gen)
return rv if not relational else rv.as_relational(_gen)
def _pt(start, end):
"""Return a point between start and end"""
if not start.is_infinite and not end.is_infinite:
pt = (start + end)/2
elif start.is_infinite and end.is_infinite:
pt = S.Zero
else:
if (start.is_infinite and start.is_extended_positive is None or
end.is_infinite and end.is_extended_positive is None):
raise ValueError('cannot proceed with unsigned infinite values')
if (end.is_infinite and end.is_extended_negative or
start.is_infinite and start.is_extended_positive):
start, end = end, start
# if possible, use a multiple of self which has
# better behavior when checking assumptions than
# an expression obtained by adding or subtracting 1
if end.is_infinite:
if start.is_extended_positive:
pt = start*2
elif start.is_extended_negative:
pt = start*S.Half
else:
pt = start + 1
elif start.is_infinite:
if end.is_extended_positive:
pt = end*S.Half
elif end.is_extended_negative:
pt = end*2
else:
pt = end - 1
return pt
def _solve_inequality(ie, s, linear=False):
"""Return the inequality with s isolated on the left, if possible.
If the relationship is non-linear, a solution involving And or Or
may be returned. False or True are returned if the relationship
is never True or always True, respectively.
If `linear` is True (default is False) an `s`-dependent expression
will be isolated on the left, if possible
but it will not be solved for `s` unless the expression is linear
in `s`. Furthermore, only "safe" operations which do not change the
sense of the relationship are applied: no division by an unsigned
value is attempted unless the relationship involves Eq or Ne and
no division by a value not known to be nonzero is ever attempted.
Examples
========
>>> from sympy import Eq, Symbol
>>> from sympy.solvers.inequalities import _solve_inequality as f
>>> from sympy.abc import x, y
For linear expressions, the symbol can be isolated:
>>> f(x - 2 < 0, x)
x < 2
>>> f(-x - 6 < x, x)
x > -3
Sometimes nonlinear relationships will be False
>>> f(x**2 + 4 < 0, x)
False
Or they may involve more than one region of values:
>>> f(x**2 - 4 < 0, x)
(-2 < x) & (x < 2)
To restrict the solution to a relational, set linear=True
and only the x-dependent portion will be isolated on the left:
>>> f(x**2 - 4 < 0, x, linear=True)
x**2 < 4
Division of only nonzero quantities is allowed, so x cannot
be isolated by dividing by y:
>>> y.is_nonzero is None # it is unknown whether it is 0 or not
True
>>> f(x*y < 1, x)
x*y < 1
And while an equality (or inequality) still holds after dividing by a
non-zero quantity
>>> nz = Symbol('nz', nonzero=True)
>>> f(Eq(x*nz, 1), x)
Eq(x, 1/nz)
the sign must be known for other inequalities involving > or <:
>>> f(x*nz <= 1, x)
nz*x <= 1
>>> p = Symbol('p', positive=True)
>>> f(x*p <= 1, x)
x <= 1/p
When there are denominators in the original expression that
are removed by expansion, conditions for them will be returned
as part of the result:
>>> f(x < x*(2/x - 1), x)
(x < 1) & Ne(x, 0)
"""
from sympy.solvers.solvers import denoms
if s not in ie.free_symbols:
return ie
if ie.rhs == s:
ie = ie.reversed
if ie.lhs == s and s not in ie.rhs.free_symbols:
return ie
def classify(ie, s, i):
# return True or False if ie evaluates when substituting s with
# i else None (if unevaluated) or NaN (when there is an error
# in evaluating)
try:
v = ie.subs(s, i)
if v is S.NaN:
return v
elif v not in (True, False):
return
return v
except TypeError:
return S.NaN
rv = None
oo = S.Infinity
expr = ie.lhs - ie.rhs
try:
p = Poly(expr, s)
if p.degree() == 0:
rv = ie.func(p.as_expr(), 0)
elif not linear and p.degree() > 1:
# handle in except clause
raise NotImplementedError
except (PolynomialError, NotImplementedError):
if not linear:
try:
rv = reduce_rational_inequalities([[ie]], s)
except PolynomialError:
rv = solve_univariate_inequality(ie, s)
# remove restrictions wrt +/-oo that may have been
# applied when using sets to simplify the relationship
okoo = classify(ie, s, oo)
if okoo is S.true and classify(rv, s, oo) is S.false:
rv = rv.subs(s < oo, True)
oknoo = classify(ie, s, -oo)
if (oknoo is S.true and
classify(rv, s, -oo) is S.false):
rv = rv.subs(-oo < s, True)
rv = rv.subs(s > -oo, True)
if rv is S.true:
rv = (s <= oo) if okoo is S.true else (s < oo)
if oknoo is not S.true:
rv = And(-oo < s, rv)
else:
p = Poly(expr)
conds = []
if rv is None:
e = p.as_expr() # this is in expanded form
# Do a safe inversion of e, moving non-s terms
# to the rhs and dividing by a nonzero factor if
# the relational is Eq/Ne; for other relationals
# the sign must also be positive or negative
rhs = 0
b, ax = e.as_independent(s, as_Add=True)
e -= b
rhs -= b
ef = factor_terms(e)
a, e = ef.as_independent(s, as_Add=False)
if (a.is_zero != False or # don't divide by potential 0
a.is_negative ==
a.is_positive is None and # if sign is not known then
ie.rel_op not in ('!=', '==')): # reject if not Eq/Ne
e = ef
a = S.One
rhs /= a
if a.is_positive:
rv = ie.func(e, rhs)
else:
rv = ie.reversed.func(e, rhs)
# return conditions under which the value is
# valid, too.
beginning_denoms = denoms(ie.lhs) | denoms(ie.rhs)
current_denoms = denoms(rv)
for d in beginning_denoms - current_denoms:
c = _solve_inequality(Eq(d, 0), s, linear=linear)
if isinstance(c, Eq) and c.lhs == s:
if classify(rv, s, c.rhs) is S.true:
# rv is permitting this value but it shouldn't
conds.append(~c)
for i in (-oo, oo):
if (classify(rv, s, i) is S.true and
classify(ie, s, i) is not S.true):
conds.append(s < i if i is oo else i < s)
conds.append(rv)
return And(*conds)
def _reduce_inequalities(inequalities, symbols):
# helper for reduce_inequalities
poly_part, abs_part = {}, {}
other = []
for inequality in inequalities:
expr, rel = inequality.lhs, inequality.rel_op # rhs is 0
# check for gens using atoms which is more strict than free_symbols to
# guard against EX domain which won't be handled by
# reduce_rational_inequalities
gens = expr.atoms(Symbol)
if len(gens) == 1:
gen = gens.pop()
else:
common = expr.free_symbols & symbols
if len(common) == 1:
gen = common.pop()
other.append(_solve_inequality(Relational(expr, 0, rel), gen))
continue
else:
raise NotImplementedError(filldedent('''
inequality has more than one symbol of interest.
'''))
if expr.is_polynomial(gen):
poly_part.setdefault(gen, []).append((expr, rel))
else:
components = expr.find(lambda u:
u.has(gen) and (
u.is_Function or u.is_Pow and not u.exp.is_Integer))
if components and all(isinstance(i, Abs) for i in components):
abs_part.setdefault(gen, []).append((expr, rel))
else:
other.append(_solve_inequality(Relational(expr, 0, rel), gen))
poly_reduced = []
abs_reduced = []
for gen, exprs in poly_part.items():
poly_reduced.append(reduce_rational_inequalities([exprs], gen))
for gen, exprs in abs_part.items():
abs_reduced.append(reduce_abs_inequalities(exprs, gen))
return And(*(poly_reduced + abs_reduced + other))
def reduce_inequalities(inequalities, symbols=[]):
"""Reduce a system of inequalities with rational coefficients.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import reduce_inequalities
>>> reduce_inequalities(0 <= x + 3, [])
(-3 <= x) & (x < oo)
>>> reduce_inequalities(0 <= x + y*2 - 1, [x])
(x < oo) & (x >= 1 - 2*y)
"""
if not iterable(inequalities):
inequalities = [inequalities]
inequalities = [sympify(i) for i in inequalities]
gens = set().union(*[i.free_symbols for i in inequalities])
if not iterable(symbols):
symbols = [symbols]
symbols = (set(symbols) or gens) & gens
if any(i.is_extended_real is False for i in symbols):
raise TypeError(filldedent('''
inequalities cannot contain symbols that are not real.
'''))
# make vanilla symbol real
recast = {i: Dummy(i.name, extended_real=True)
for i in gens if i.is_extended_real is None}
inequalities = [i.xreplace(recast) for i in inequalities]
symbols = {i.xreplace(recast) for i in symbols}
# prefilter
keep = []
for i in inequalities:
if isinstance(i, Relational):
i = i.func(i.lhs.as_expr() - i.rhs.as_expr(), 0)
elif i not in (True, False):
i = Eq(i, 0)
if i == True:
continue
elif i == False:
return S.false
if i.lhs.is_number:
raise NotImplementedError(
"could not determine truth value of %s" % i)
keep.append(i)
inequalities = keep
del keep
# solve system
rv = _reduce_inequalities(inequalities, symbols)
# restore original symbols and return
return rv.xreplace({v: k for k, v in recast.items()})
|
699a806e5692e5c165b40887ec680464e6990f3282bc7cea3659ae46f1890e0d | """
This module contain solvers for all kinds of equations:
- algebraic or transcendental, use solve()
- recurrence, use rsolve()
- differential, use dsolve()
- nonlinear (numerically), use nsolve()
(you will need a good starting point)
"""
from sympy.core import (S, Add, Symbol, Dummy, Expr, Mul)
from sympy.core.assumptions import check_assumptions
from sympy.core.exprtools import factor_terms
from sympy.core.function import (expand_mul, expand_log, Derivative,
AppliedUndef, UndefinedFunction, nfloat,
Function, expand_power_exp, _mexpand, expand,
expand_func)
from sympy.core.logic import fuzzy_not
from sympy.core.numbers import ilcm, Float, Rational, _illegal
from sympy.core.power import integer_log, Pow
from sympy.core.relational import Relational, Eq, Ne
from sympy.core.sorting import ordered, default_sort_key
from sympy.core.sympify import sympify, _sympify
from sympy.core.traversal import preorder_traversal
from sympy.logic.boolalg import And, Or, BooleanAtom
from sympy.functions import (log, exp, LambertW, cos, sin, tan, acos, asin, atan,
Abs, re, im, arg, sqrt, atan2)
from sympy.functions.combinatorial.factorials import binomial
from sympy.functions.elementary.hyperbolic import HyperbolicFunction
from sympy.functions.elementary.piecewise import piecewise_fold, Piecewise
from sympy.functions.elementary.trigonometric import TrigonometricFunction
from sympy.integrals.integrals import Integral
from sympy.ntheory.factor_ import divisors
from sympy.simplify import (simplify, collect, powsimp, posify, # type: ignore
powdenest, nsimplify, denom, logcombine, sqrtdenest, fraction,
separatevars)
from sympy.simplify.sqrtdenest import sqrt_depth
from sympy.simplify.fu import TR1, TR2i
from sympy.matrices.common import NonInvertibleMatrixError
from sympy.matrices import Matrix, zeros
from sympy.polys import roots, cancel, factor, Poly
from sympy.polys.polyerrors import GeneratorsNeeded, PolynomialError
from sympy.polys.solvers import sympy_eqs_to_ring, solve_lin_sys
from sympy.utilities.lambdify import lambdify
from sympy.utilities.misc import filldedent, debug
from sympy.utilities.iterables import (connected_components,
generate_bell, uniq, iterable, is_sequence, subsets, flatten)
from sympy.utilities.decorator import conserve_mpmath_dps
from mpmath import findroot
from sympy.solvers.polysys import solve_poly_system
from types import GeneratorType
from collections import defaultdict
from itertools import combinations, product
import warnings
def recast_to_symbols(eqs, symbols):
"""
Return (e, s, d) where e and s are versions of *eqs* and
*symbols* in which any non-Symbol objects in *symbols* have
been replaced with generic Dummy symbols and d is a dictionary
that can be used to restore the original expressions.
Examples
========
>>> from sympy.solvers.solvers import recast_to_symbols
>>> from sympy import symbols, Function
>>> x, y = symbols('x y')
>>> fx = Function('f')(x)
>>> eqs, syms = [fx + 1, x, y], [fx, y]
>>> e, s, d = recast_to_symbols(eqs, syms); (e, s, d)
([_X0 + 1, x, y], [_X0, y], {_X0: f(x)})
The original equations and symbols can be restored using d:
>>> assert [i.xreplace(d) for i in eqs] == eqs
>>> assert [d.get(i, i) for i in s] == syms
"""
if not iterable(eqs) and iterable(symbols):
raise ValueError('Both eqs and symbols must be iterable')
new_symbols = list(symbols)
swap_sym = {}
for i, s in enumerate(symbols):
if not isinstance(s, Symbol) and s not in swap_sym:
swap_sym[s] = Dummy('X%d' % i)
new_symbols[i] = swap_sym[s]
new_f = []
for i in eqs:
isubs = getattr(i, 'subs', None)
if isubs is not None:
new_f.append(isubs(swap_sym))
else:
new_f.append(i)
swap_sym = {v: k for k, v in swap_sym.items()}
return new_f, new_symbols, swap_sym
def _ispow(e):
"""Return True if e is a Pow or is exp."""
return isinstance(e, Expr) and (e.is_Pow or isinstance(e, exp))
def _simple_dens(f, symbols):
# when checking if a denominator is zero, we can just check the
# base of powers with nonzero exponents since if the base is zero
# the power will be zero, too. To keep it simple and fast, we
# limit simplification to exponents that are Numbers
dens = set()
for d in denoms(f, symbols):
if d.is_Pow and d.exp.is_Number:
if d.exp.is_zero:
continue # foo**0 is never 0
d = d.base
dens.add(d)
return dens
def denoms(eq, *symbols):
"""
Return (recursively) set of all denominators that appear in *eq*
that contain any symbol in *symbols*; if *symbols* are not
provided then all denominators will be returned.
Examples
========
>>> from sympy.solvers.solvers import denoms
>>> from sympy.abc import x, y, z
>>> denoms(x/y)
{y}
>>> denoms(x/(y*z))
{y, z}
>>> denoms(3/x + y/z)
{x, z}
>>> denoms(x/2 + y/z)
{2, z}
If *symbols* are provided then only denominators containing
those symbols will be returned:
>>> denoms(1/x + 1/y + 1/z, y, z)
{y, z}
"""
pot = preorder_traversal(eq)
dens = set()
for p in pot:
# Here p might be Tuple or Relational
# Expr subtrees (e.g. lhs and rhs) will be traversed after by pot
if not isinstance(p, Expr):
continue
den = denom(p)
if den is S.One:
continue
for d in Mul.make_args(den):
dens.add(d)
if not symbols:
return dens
elif len(symbols) == 1:
if iterable(symbols[0]):
symbols = symbols[0]
rv = []
for d in dens:
free = d.free_symbols
if any(s in free for s in symbols):
rv.append(d)
return set(rv)
def checksol(f, symbol, sol=None, **flags):
"""
Checks whether sol is a solution of equation f == 0.
Explanation
===========
Input can be either a single symbol and corresponding value
or a dictionary of symbols and values. When given as a dictionary
and flag ``simplify=True``, the values in the dictionary will be
simplified. *f* can be a single equation or an iterable of equations.
A solution must satisfy all equations in *f* to be considered valid;
if a solution does not satisfy any equation, False is returned; if one or
more checks are inconclusive (and none are False) then None is returned.
Examples
========
>>> from sympy import checksol, symbols
>>> x, y = symbols('x,y')
>>> checksol(x**4 - 1, x, 1)
True
>>> checksol(x**4 - 1, x, 0)
False
>>> checksol(x**2 + y**2 - 5**2, {x: 3, y: 4})
True
To check if an expression is zero using ``checksol()``, pass it
as *f* and send an empty dictionary for *symbol*:
>>> checksol(x**2 + x - x*(x + 1), {})
True
None is returned if ``checksol()`` could not conclude.
flags:
'numerical=True (default)'
do a fast numerical check if ``f`` has only one symbol.
'minimal=True (default is False)'
a very fast, minimal testing.
'warn=True (default is False)'
show a warning if checksol() could not conclude.
'simplify=True (default)'
simplify solution before substituting into function and
simplify the function before trying specific simplifications
'force=True (default is False)'
make positive all symbols without assumptions regarding sign.
"""
from sympy.physics.units import Unit
minimal = flags.get('minimal', False)
if sol is not None:
sol = {symbol: sol}
elif isinstance(symbol, dict):
sol = symbol
else:
msg = 'Expecting (sym, val) or ({sym: val}, None) but got (%s, %s)'
raise ValueError(msg % (symbol, sol))
if iterable(f):
if not f:
raise ValueError('no functions to check')
rv = True
for fi in f:
check = checksol(fi, sol, **flags)
if check:
continue
if check is False:
return False
rv = None # don't return, wait to see if there's a False
return rv
f = _sympify(f)
if f.is_number:
return f.is_zero
if isinstance(f, Poly):
f = f.as_expr()
elif isinstance(f, (Eq, Ne)):
if f.rhs in (S.true, S.false):
f = f.reversed
B, E = f.args
if isinstance(B, BooleanAtom):
f = f.subs(sol)
if not f.is_Boolean:
return
else:
f = f.rewrite(Add, evaluate=False)
if isinstance(f, BooleanAtom):
return bool(f)
elif not f.is_Relational and not f:
return True
illegal = set(_illegal)
if any(sympify(v).atoms() & illegal for k, v in sol.items()):
return False
was = f
attempt = -1
numerical = flags.get('numerical', True)
while 1:
attempt += 1
if attempt == 0:
val = f.subs(sol)
if isinstance(val, Mul):
val = val.as_independent(Unit)[0]
if val.atoms() & illegal:
return False
elif attempt == 1:
if not val.is_number:
if not val.is_constant(*list(sol.keys()), simplify=not minimal):
return False
# there are free symbols -- simple expansion might work
_, val = val.as_content_primitive()
val = _mexpand(val.as_numer_denom()[0], recursive=True)
elif attempt == 2:
if minimal:
return
if flags.get('simplify', True):
for k in sol:
sol[k] = simplify(sol[k])
# start over without the failed expanded form, possibly
# with a simplified solution
val = simplify(f.subs(sol))
if flags.get('force', True):
val, reps = posify(val)
# expansion may work now, so try again and check
exval = _mexpand(val, recursive=True)
if exval.is_number:
# we can decide now
val = exval
else:
# if there are no radicals and no functions then this can't be
# zero anymore -- can it?
pot = preorder_traversal(expand_mul(val))
seen = set()
saw_pow_func = False
for p in pot:
if p in seen:
continue
seen.add(p)
if p.is_Pow and not p.exp.is_Integer:
saw_pow_func = True
elif p.is_Function:
saw_pow_func = True
elif isinstance(p, UndefinedFunction):
saw_pow_func = True
if saw_pow_func:
break
if saw_pow_func is False:
return False
if flags.get('force', True):
# don't do a zero check with the positive assumptions in place
val = val.subs(reps)
nz = fuzzy_not(val.is_zero)
if nz is not None:
# issue 5673: nz may be True even when False
# so these are just hacks to keep a false positive
# from being returned
# HACK 1: LambertW (issue 5673)
if val.is_number and val.has(LambertW):
# don't eval this to verify solution since if we got here,
# numerical must be False
return None
# add other HACKs here if necessary, otherwise we assume
# the nz value is correct
return not nz
break
if numerical and val.is_number:
return (abs(val.n(18).n(12, chop=True)) < 1e-9) is S.true
if val == was:
continue
elif val.is_Rational:
return val == 0
was = val
if flags.get('warn', False):
warnings.warn("\n\tWarning: could not verify solution %s." % sol)
# returns None if it can't conclude
# TODO: improve solution testing
def solve(f, *symbols, **flags):
r"""
Algebraically solves equations and systems of equations.
Explanation
===========
Currently supported:
- polynomial
- transcendental
- piecewise combinations of the above
- systems of linear and polynomial equations
- systems containing relational expressions
Examples
========
The output varies according to the input and can be seen by example:
>>> from sympy import solve, Poly, Eq, Function, exp
>>> from sympy.abc import x, y, z, a, b
>>> f = Function('f')
Boolean or univariate Relational:
>>> solve(x < 3)
(-oo < x) & (x < 3)
To always get a list of solution mappings, use flag dict=True:
>>> solve(x - 3, dict=True)
[{x: 3}]
>>> sol = solve([x - 3, y - 1], dict=True)
>>> sol
[{x: 3, y: 1}]
>>> sol[0][x]
3
>>> sol[0][y]
1
To get a list of *symbols* and set of solution(s) use flag set=True:
>>> solve([x**2 - 3, y - 1], set=True)
([x, y], {(-sqrt(3), 1), (sqrt(3), 1)})
Single expression and single symbol that is in the expression:
>>> solve(x - y, x)
[y]
>>> solve(x - 3, x)
[3]
>>> solve(Eq(x, 3), x)
[3]
>>> solve(Poly(x - 3), x)
[3]
>>> solve(x**2 - y**2, x, set=True)
([x], {(-y,), (y,)})
>>> solve(x**4 - 1, x, set=True)
([x], {(-1,), (1,), (-I,), (I,)})
Single expression with no symbol that is in the expression:
>>> solve(3, x)
[]
>>> solve(x - 3, y)
[]
Single expression with no symbol given. In this case, all free *symbols*
will be selected as potential *symbols* to solve for. If the equation is
univariate then a list of solutions is returned; otherwise - as is the case
when *symbols* are given as an iterable of length greater than 1 - a list of
mappings will be returned:
>>> solve(x - 3)
[3]
>>> solve(x**2 - y**2)
[{x: -y}, {x: y}]
>>> solve(z**2*x**2 - z**2*y**2)
[{x: -y}, {x: y}, {z: 0}]
>>> solve(z**2*x - z**2*y**2)
[{x: y**2}, {z: 0}]
When an object other than a Symbol is given as a symbol, it is
isolated algebraically and an implicit solution may be obtained.
This is mostly provided as a convenience to save you from replacing
the object with a Symbol and solving for that Symbol. It will only
work if the specified object can be replaced with a Symbol using the
subs method:
>>> solve(f(x) - x, f(x))
[x]
>>> solve(f(x).diff(x) - f(x) - x, f(x).diff(x))
[x + f(x)]
>>> solve(f(x).diff(x) - f(x) - x, f(x))
[-x + Derivative(f(x), x)]
>>> solve(x + exp(x)**2, exp(x), set=True)
([exp(x)], {(-sqrt(-x),), (sqrt(-x),)})
>>> from sympy import Indexed, IndexedBase, Tuple, sqrt
>>> A = IndexedBase('A')
>>> eqs = Tuple(A[1] + A[2] - 3, A[1] - A[2] + 1)
>>> solve(eqs, eqs.atoms(Indexed))
{A[1]: 1, A[2]: 2}
* To solve for a symbol implicitly, use implicit=True:
>>> solve(x + exp(x), x)
[-LambertW(1)]
>>> solve(x + exp(x), x, implicit=True)
[-exp(x)]
* It is possible to solve for anything that can be targeted with
subs:
>>> solve(x + 2 + sqrt(3), x + 2)
[-sqrt(3)]
>>> solve((x + 2 + sqrt(3), x + 4 + y), y, x + 2)
{y: -2 + sqrt(3), x + 2: -sqrt(3)}
* Nothing heroic is done in this implicit solving so you may end up
with a symbol still in the solution:
>>> eqs = (x*y + 3*y + sqrt(3), x + 4 + y)
>>> solve(eqs, y, x + 2)
{y: -sqrt(3)/(x + 3), x + 2: -2*x/(x + 3) - 6/(x + 3) + sqrt(3)/(x + 3)}
>>> solve(eqs, y*x, x)
{x: -y - 4, x*y: -3*y - sqrt(3)}
* If you attempt to solve for a number remember that the number
you have obtained does not necessarily mean that the value is
equivalent to the expression obtained:
>>> solve(sqrt(2) - 1, 1)
[sqrt(2)]
>>> solve(x - y + 1, 1) # /!\ -1 is targeted, too
[x/(y - 1)]
>>> [_.subs(z, -1) for _ in solve((x - y + 1).subs(-1, z), 1)]
[-x + y]
* To solve for a function within a derivative, use ``dsolve``.
Single expression and more than one symbol:
* When there is a linear solution:
>>> solve(x - y**2, x, y)
[(y**2, y)]
>>> solve(x**2 - y, x, y)
[(x, x**2)]
>>> solve(x**2 - y, x, y, dict=True)
[{y: x**2}]
* When undetermined coefficients are identified:
* That are linear:
>>> solve((a + b)*x - b + 2, a, b)
{a: -2, b: 2}
* That are nonlinear:
>>> solve((a + b)*x - b**2 + 2, a, b, set=True)
([a, b], {(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))})
* If there is no linear solution, then the first successful
attempt for a nonlinear solution will be returned:
>>> solve(x**2 - y**2, x, y, dict=True)
[{x: -y}, {x: y}]
>>> solve(x**2 - y**2/exp(x), x, y, dict=True)
[{x: 2*LambertW(-y/2)}, {x: 2*LambertW(y/2)}]
>>> solve(x**2 - y**2/exp(x), y, x)
[(-x*sqrt(exp(x)), x), (x*sqrt(exp(x)), x)]
Iterable of one or more of the above:
* Involving relationals or bools:
>>> solve([x < 3, x - 2])
Eq(x, 2)
>>> solve([x > 3, x - 2])
False
* When the system is linear:
* With a solution:
>>> solve([x - 3], x)
{x: 3}
>>> solve((x + 5*y - 2, -3*x + 6*y - 15), x, y)
{x: -3, y: 1}
>>> solve((x + 5*y - 2, -3*x + 6*y - 15), x, y, z)
{x: -3, y: 1}
>>> solve((x + 5*y - 2, -3*x + 6*y - z), z, x, y)
{x: 2 - 5*y, z: 21*y - 6}
* Without a solution:
>>> solve([x + 3, x - 3])
[]
* When the system is not linear:
>>> solve([x**2 + y -2, y**2 - 4], x, y, set=True)
([x, y], {(-2, -2), (0, 2), (2, -2)})
* If no *symbols* are given, all free *symbols* will be selected and a
list of mappings returned:
>>> solve([x - 2, x**2 + y])
[{x: 2, y: -4}]
>>> solve([x - 2, x**2 + f(x)], {f(x), x})
[{x: 2, f(x): -4}]
* If any equation does not depend on the symbol(s) given, it will be
eliminated from the equation set and an answer may be given
implicitly in terms of variables that were not of interest:
>>> solve([x - y, y - 3], x)
{x: y}
**Additional Examples**
``solve()`` with check=True (default) will run through the symbol tags to
elimate unwanted solutions. If no assumptions are included, all possible
solutions will be returned:
>>> from sympy import Symbol, solve
>>> x = Symbol("x")
>>> solve(x**2 - 1)
[-1, 1]
By using the positive tag, only one solution will be returned:
>>> pos = Symbol("pos", positive=True)
>>> solve(pos**2 - 1)
[1]
Assumptions are not checked when ``solve()`` input involves
relationals or bools.
When the solutions are checked, those that make any denominator zero
are automatically excluded. If you do not want to exclude such solutions,
then use the check=False option:
>>> from sympy import sin, limit
>>> solve(sin(x)/x) # 0 is excluded
[pi]
If check=False, then a solution to the numerator being zero is found: x = 0.
In this case, this is a spurious solution since $\sin(x)/x$ has the well
known limit (without dicontinuity) of 1 at x = 0:
>>> solve(sin(x)/x, check=False)
[0, pi]
In the following case, however, the limit exists and is equal to the
value of x = 0 that is excluded when check=True:
>>> eq = x**2*(1/x - z**2/x)
>>> solve(eq, x)
[]
>>> solve(eq, x, check=False)
[0]
>>> limit(eq, x, 0, '-')
0
>>> limit(eq, x, 0, '+')
0
**Disabling High-Order Explicit Solutions**
When solving polynomial expressions, you might not want explicit solutions
(which can be quite long). If the expression is univariate, ``CRootOf``
instances will be returned instead:
>>> solve(x**3 - x + 1)
[-1/((-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)) -
(-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3,
-(-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3 -
1/((-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)),
-(3*sqrt(69)/2 + 27/2)**(1/3)/3 -
1/(3*sqrt(69)/2 + 27/2)**(1/3)]
>>> solve(x**3 - x + 1, cubics=False)
[CRootOf(x**3 - x + 1, 0),
CRootOf(x**3 - x + 1, 1),
CRootOf(x**3 - x + 1, 2)]
If the expression is multivariate, no solution might be returned:
>>> solve(x**3 - x + a, x, cubics=False)
[]
Sometimes solutions will be obtained even when a flag is False because the
expression could be factored. In the following example, the equation can
be factored as the product of a linear and a quadratic factor so explicit
solutions (which did not require solving a cubic expression) are obtained:
>>> eq = x**3 + 3*x**2 + x - 1
>>> solve(eq, cubics=False)
[-1, -1 + sqrt(2), -sqrt(2) - 1]
**Solving Equations Involving Radicals**
Because of SymPy's use of the principle root, some solutions
to radical equations will be missed unless check=False:
>>> from sympy import root
>>> eq = root(x**3 - 3*x**2, 3) + 1 - x
>>> solve(eq)
[]
>>> solve(eq, check=False)
[1/3]
In the above example, there is only a single solution to the
equation. Other expressions will yield spurious roots which
must be checked manually; roots which give a negative argument
to odd-powered radicals will also need special checking:
>>> from sympy import real_root, S
>>> eq = root(x, 3) - root(x, 5) + S(1)/7
>>> solve(eq) # this gives 2 solutions but misses a 3rd
[CRootOf(7*x**5 - 7*x**3 + 1, 1)**15,
CRootOf(7*x**5 - 7*x**3 + 1, 2)**15]
>>> sol = solve(eq, check=False)
>>> [abs(eq.subs(x,i).n(2)) for i in sol]
[0.48, 0.e-110, 0.e-110, 0.052, 0.052]
The first solution is negative so ``real_root`` must be used to see that it
satisfies the expression:
>>> abs(real_root(eq.subs(x, sol[0])).n(2))
0.e-110
If the roots of the equation are not real then more care will be
necessary to find the roots, especially for higher order equations.
Consider the following expression:
>>> expr = root(x, 3) - root(x, 5)
We will construct a known value for this expression at x = 3 by selecting
the 1-th root for each radical:
>>> expr1 = root(x, 3, 1) - root(x, 5, 1)
>>> v = expr1.subs(x, -3)
The ``solve`` function is unable to find any exact roots to this equation:
>>> eq = Eq(expr, v); eq1 = Eq(expr1, v)
>>> solve(eq, check=False), solve(eq1, check=False)
([], [])
The function ``unrad``, however, can be used to get a form of the equation
for which numerical roots can be found:
>>> from sympy.solvers.solvers import unrad
>>> from sympy import nroots
>>> e, (p, cov) = unrad(eq)
>>> pvals = nroots(e)
>>> inversion = solve(cov, x)[0]
>>> xvals = [inversion.subs(p, i) for i in pvals]
Although ``eq`` or ``eq1`` could have been used to find ``xvals``, the
solution can only be verified with ``expr1``:
>>> z = expr - v
>>> [xi.n(chop=1e-9) for xi in xvals if abs(z.subs(x, xi).n()) < 1e-9]
[]
>>> z1 = expr1 - v
>>> [xi.n(chop=1e-9) for xi in xvals if abs(z1.subs(x, xi).n()) < 1e-9]
[-3.0]
Parameters
==========
f :
- a single Expr or Poly that must be zero
- an Equality
- a Relational expression
- a Boolean
- iterable of one or more of the above
symbols : (object(s) to solve for) specified as
- none given (other non-numeric objects will be used)
- single symbol
- denested list of symbols
(e.g., ``solve(f, x, y)``)
- ordered iterable of symbols
(e.g., ``solve(f, [x, y])``)
flags :
dict=True (default is False)
Return list (perhaps empty) of solution mappings.
set=True (default is False)
Return list of symbols and set of tuple(s) of solution(s).
exclude=[] (default)
Do not try to solve for any of the free symbols in exclude;
if expressions are given, the free symbols in them will
be extracted automatically.
check=True (default)
If False, do not do any testing of solutions. This can be
useful if you want to include solutions that make any
denominator zero.
numerical=True (default)
Do a fast numerical check if *f* has only one symbol.
minimal=True (default is False)
A very fast, minimal testing.
warn=True (default is False)
Show a warning if ``checksol()`` could not conclude.
simplify=True (default)
Simplify all but polynomials of order 3 or greater before
returning them and (if check is not False) use the
general simplify function on the solutions and the
expression obtained when they are substituted into the
function which should be zero.
force=True (default is False)
Make positive all symbols without assumptions regarding sign.
rational=True (default)
Recast Floats as Rational; if this option is not used, the
system containing Floats may fail to solve because of issues
with polys. If rational=None, Floats will be recast as
rationals but the answer will be recast as Floats. If the
flag is False then nothing will be done to the Floats.
manual=True (default is False)
Do not use the polys/matrix method to solve a system of
equations, solve them one at a time as you might "manually."
implicit=True (default is False)
Allows ``solve`` to return a solution for a pattern in terms of
other functions that contain that pattern; this is only
needed if the pattern is inside of some invertible function
like cos, exp, ect.
particular=True (default is False)
Instructs ``solve`` to try to find a particular solution to
a linear system with as many zeros as possible; this is very
expensive.
quick=True (default is False; ``particular`` must be True)
Selects a fast heuristic to find a solution with many zeros
whereas a value of False uses the very slow method guaranteed
to find the largest number of zeros possible.
cubics=True (default)
Return explicit solutions when cubic expressions are encountered.
When False, quartics and quintics are disabled, too.
quartics=True (default)
Return explicit solutions when quartic expressions are encountered.
When False, quintics are disabled, too.
quintics=True (default)
Return explicit solutions (if possible) when quintic expressions
are encountered.
See Also
========
rsolve: For solving recurrence relationships
dsolve: For solving differential equations
"""
from .inequalities import reduce_inequalities
# set solver types explicitly; as soon as one is False
# all the rest will be False
###########################################################################
hints = ('cubics', 'quartics', 'quintics')
default = True
for k in hints:
default = flags.setdefault(k, bool(flags.get(k, default)))
# keeping track of how f was passed since if it is a list
# a dictionary of results will be returned.
###########################################################################
def _sympified_list(w):
return list(map(sympify, w if iterable(w) else [w]))
bare_f = not iterable(f)
# check flag usage for particular/quick which should only be used
# with systems of equations
if flags.get('quick', None) is not None:
if not flags.get('particular', None):
raise ValueError('when using `quick`, `particular` should be True')
if flags.get('particular', False) and bare_f:
raise ValueError(filldedent("""
The 'particular/quick' flag is usually used with systems of
equations. Either pass your equation in a list or
consider using a solver like `diophantine` if you are
looking for a solution in integers."""))
ordered_symbols = (symbols and
symbols[0] and
(isinstance(symbols[0], Symbol) or
is_sequence(symbols[0],
include=GeneratorType)))
f, symbols = (_sympified_list(w) for w in [f, symbols])
if isinstance(f, list):
f = [s for s in f if s is not S.true and s is not True]
implicit = flags.get('implicit', False)
# preprocess symbol(s)
###########################################################################
if not symbols:
# get symbols from equations
symbols = set().union(*[fi.free_symbols for fi in f])
if len(symbols) < len(f):
for fi in f:
pot = preorder_traversal(fi)
for p in pot:
if isinstance(p, AppliedUndef):
flags['dict'] = True # better show symbols
symbols.add(p)
pot.skip() # don't go any deeper
symbols = list(symbols)
ordered_symbols = False
elif len(symbols) == 1 and iterable(symbols[0]):
symbols = symbols[0]
# remove symbols the user is not interested in
exclude = flags.pop('exclude', set())
if exclude:
if isinstance(exclude, Expr):
exclude = [exclude]
exclude = set().union(*[e.free_symbols for e in sympify(exclude)])
symbols = [s for s in symbols if s not in exclude]
# preprocess equation(s)
###########################################################################
for i, fi in enumerate(f):
if isinstance(fi, (Eq, Ne)):
if 'ImmutableDenseMatrix' in [type(a).__name__ for a in fi.args]:
fi = fi.lhs - fi.rhs
else:
L, R = fi.args
if isinstance(R, BooleanAtom):
L, R = R, L
if isinstance(L, BooleanAtom):
if isinstance(fi, Ne):
L = ~L
if R.is_Relational:
fi = ~R if L is S.false else R
elif R.is_Symbol:
return L
elif R.is_Boolean and (~R).is_Symbol:
return ~L
else:
raise NotImplementedError(filldedent('''
Unanticipated argument of Eq when other arg
is True or False.
'''))
else:
fi = fi.rewrite(Add, evaluate=False)
f[i] = fi
if fi.is_Relational:
return reduce_inequalities(f, symbols=symbols)
if isinstance(fi, Poly):
f[i] = fi.as_expr()
# rewrite hyperbolics in terms of exp
f[i] = f[i].replace(lambda w: isinstance(w, HyperbolicFunction) and \
(len(w.free_symbols & set(symbols)) > 0), lambda w: w.rewrite(exp))
# if we have a Matrix, we need to iterate over its elements again
if f[i].is_Matrix:
bare_f = False
f.extend(list(f[i]))
f[i] = S.Zero
# if we can split it into real and imaginary parts then do so
freei = f[i].free_symbols
if freei and all(s.is_extended_real or s.is_imaginary for s in freei):
fr, fi = f[i].as_real_imag()
# accept as long as new re, im, arg or atan2 are not introduced
had = f[i].atoms(re, im, arg, atan2)
if fr and fi and fr != fi and not any(
i.atoms(re, im, arg, atan2) - had for i in (fr, fi)):
if bare_f:
bare_f = False
f[i: i + 1] = [fr, fi]
# real/imag handling -----------------------------
if any(isinstance(fi, (bool, BooleanAtom)) for fi in f):
if flags.get('set', False):
return [], set()
return []
for i, fi in enumerate(f):
# Abs
while True:
was = fi
fi = fi.replace(Abs, lambda arg:
separatevars(Abs(arg)).rewrite(Piecewise) if arg.has(*symbols)
else Abs(arg))
if was == fi:
break
for e in fi.find(Abs):
if e.has(*symbols):
raise NotImplementedError('solving %s when the argument '
'is not real or imaginary.' % e)
# arg
fi = fi.replace(arg, lambda a: arg(a).rewrite(atan2).rewrite(atan))
# save changes
f[i] = fi
# see if re(s) or im(s) appear
freim = [fi for fi in f if fi.has(re, im)]
if freim:
irf = []
for s in symbols:
if s.is_real or s.is_imaginary:
continue # neither re(x) nor im(x) will appear
# if re(s) or im(s) appear, the auxiliary equation must be present
if any(fi.has(re(s), im(s)) for fi in freim):
irf.append((s, re(s) + S.ImaginaryUnit*im(s)))
if irf:
for s, rhs in irf:
for i, fi in enumerate(f):
f[i] = fi.xreplace({s: rhs})
f.append(s - rhs)
symbols.extend([re(s), im(s)])
if bare_f:
bare_f = False
flags['dict'] = True
# end of real/imag handling -----------------------------
symbols = list(uniq(symbols))
if not ordered_symbols:
# we do this to make the results returned canonical in case f
# contains a system of nonlinear equations; all other cases should
# be unambiguous
symbols = sorted(symbols, key=default_sort_key)
# we can solve for non-symbol entities by replacing them with Dummy symbols
f, symbols, swap_sym = recast_to_symbols(f, symbols)
# this is needed in the next two events
symset = set(symbols)
# get rid of equations that have no symbols of interest; we don't
# try to solve them because the user didn't ask and they might be
# hard to solve; this means that solutions may be given in terms
# of the eliminated equations e.g. solve((x-y, y-3), x) -> {x: y}
newf = []
for fi in f:
# let the solver handle equations that..
# - have no symbols but are expressions
# - have symbols of interest
# - have no symbols of interest but are constant
# but when an expression is not constant and has no symbols of
# interest, it can't change what we obtain for a solution from
# the remaining equations so we don't include it; and if it's
# zero it can be removed and if it's not zero, there is no
# solution for the equation set as a whole
#
# The reason for doing this filtering is to allow an answer
# to be obtained to queries like solve((x - y, y), x); without
# this mod the return value is []
ok = False
if fi.free_symbols & symset:
ok = True
else:
if fi.is_number:
if fi.is_Number:
if fi.is_zero:
continue
return []
ok = True
else:
if fi.is_constant():
ok = True
if ok:
newf.append(fi)
if not newf:
return []
f = newf
del newf
# mask off any Object that we aren't going to invert: Derivative,
# Integral, etc... so that solving for anything that they contain will
# give an implicit solution
seen = set()
non_inverts = set()
for fi in f:
pot = preorder_traversal(fi)
for p in pot:
if not isinstance(p, Expr) or isinstance(p, Piecewise):
pass
elif (isinstance(p, bool) or
not p.args or
p in symset or
p.is_Add or p.is_Mul or
p.is_Pow and not implicit or
p.is_Function and not implicit) and p.func not in (re, im):
continue
elif p not in seen:
seen.add(p)
if p.free_symbols & symset:
non_inverts.add(p)
else:
continue
pot.skip()
del seen
non_inverts = dict(list(zip(non_inverts, [Dummy() for _ in non_inverts])))
f = [fi.subs(non_inverts) for fi in f]
# Both xreplace and subs are needed below: xreplace to force substitution
# inside Derivative, subs to handle non-straightforward substitutions
non_inverts = [(v, k.xreplace(swap_sym).subs(swap_sym)) for k, v in non_inverts.items()]
# rationalize Floats
floats = False
if flags.get('rational', True) is not False:
for i, fi in enumerate(f):
if fi.has(Float):
floats = True
f[i] = nsimplify(fi, rational=True)
# capture any denominators before rewriting since
# they may disappear after the rewrite, e.g. issue 14779
flags['_denominators'] = _simple_dens(f[0], symbols)
# Any embedded piecewise functions need to be brought out to the
# top level so that the appropriate strategy gets selected.
# However, this is necessary only if one of the piecewise
# functions depends on one of the symbols we are solving for.
def _has_piecewise(e):
if e.is_Piecewise:
return e.has(*symbols)
return any(_has_piecewise(a) for a in e.args)
for i, fi in enumerate(f):
if _has_piecewise(fi):
f[i] = piecewise_fold(fi)
#
# try to get a solution
###########################################################################
if bare_f:
solution = _solve(f[0], *symbols, **flags)
else:
solution = _solve_system(f, symbols, **flags)
#
# postprocessing
###########################################################################
# Restore masked-off objects
if non_inverts:
def _do_dict(solution):
return {k: v.subs(non_inverts) for k, v in
solution.items()}
for i in range(1):
if isinstance(solution, dict):
solution = _do_dict(solution)
break
elif solution and isinstance(solution, list):
if isinstance(solution[0], dict):
solution = [_do_dict(s) for s in solution]
break
elif isinstance(solution[0], tuple):
solution = [tuple([v.subs(non_inverts) for v in s]) for s
in solution]
break
else:
solution = [v.subs(non_inverts) for v in solution]
break
elif not solution:
break
else:
raise NotImplementedError(filldedent('''
no handling of %s was implemented''' % solution))
# Restore original "symbols" if a dictionary is returned.
# This is not necessary for
# - the single univariate equation case
# since the symbol will have been removed from the solution;
# - the nonlinear poly_system since that only supports zero-dimensional
# systems and those results come back as a list
#
# ** unless there were Derivatives with the symbols, but those were handled
# above.
if swap_sym:
symbols = [swap_sym.get(k, k) for k in symbols]
if isinstance(solution, dict):
solution = {swap_sym.get(k, k): v.subs(swap_sym)
for k, v in solution.items()}
elif solution and isinstance(solution, list) and isinstance(solution[0], dict):
for i, sol in enumerate(solution):
solution[i] = {swap_sym.get(k, k): v.subs(swap_sym)
for k, v in sol.items()}
# undo the dictionary solutions returned when the system was only partially
# solved with poly-system if all symbols are present
if (
not flags.get('dict', False) and
solution and
ordered_symbols and
not isinstance(solution, dict) and
all(isinstance(sol, dict) for sol in solution)
):
solution = [tuple([r.get(s, s) for s in symbols]) for r in solution]
# Get assumptions about symbols, to filter solutions.
# Note that if assumptions about a solution can't be verified, it is still
# returned.
check = flags.get('check', True)
# restore floats
if floats and solution and flags.get('rational', None) is None:
solution = nfloat(solution, exponent=False)
if check and solution: # assumption checking
warn = flags.get('warn', False)
got_None = [] # solutions for which one or more symbols gave None
no_False = [] # solutions for which no symbols gave False
if isinstance(solution, tuple):
# this has already been checked and is in as_set form
return solution
elif isinstance(solution, list):
if isinstance(solution[0], tuple):
for sol in solution:
for symb, val in zip(symbols, sol):
test = check_assumptions(val, **symb.assumptions0)
if test is False:
break
if test is None:
got_None.append(sol)
else:
no_False.append(sol)
elif isinstance(solution[0], dict):
for sol in solution:
a_None = False
for symb, val in sol.items():
test = check_assumptions(val, **symb.assumptions0)
if test:
continue
if test is False:
break
a_None = True
else:
no_False.append(sol)
if a_None:
got_None.append(sol)
else: # list of expressions
for sol in solution:
test = check_assumptions(sol, **symbols[0].assumptions0)
if test is False:
continue
no_False.append(sol)
if test is None:
got_None.append(sol)
elif isinstance(solution, dict):
a_None = False
for symb, val in solution.items():
test = check_assumptions(val, **symb.assumptions0)
if test:
continue
if test is False:
no_False = None
break
a_None = True
else:
no_False = solution
if a_None:
got_None.append(solution)
elif isinstance(solution, (Relational, And, Or)):
if len(symbols) != 1:
raise ValueError("Length should be 1")
if warn and symbols[0].assumptions0:
warnings.warn(filldedent("""
\tWarning: assumptions about variable '%s' are
not handled currently.""" % symbols[0]))
# TODO: check also variable assumptions for inequalities
else:
raise TypeError('Unrecognized solution') # improve the checker
solution = no_False
if warn and got_None:
warnings.warn(filldedent("""
\tWarning: assumptions concerning following solution(s)
cannot be checked:""" + '\n\t' +
', '.join(str(s) for s in got_None)))
#
# done
###########################################################################
as_dict = flags.get('dict', False)
as_set = flags.get('set', False)
if not as_set and isinstance(solution, list):
# Make sure that a list of solutions is ordered in a canonical way.
solution.sort(key=default_sort_key)
if not as_dict and not as_set:
return solution or []
# return a list of mappings or []
if not solution:
solution = []
else:
if isinstance(solution, dict):
solution = [solution]
elif iterable(solution[0]):
solution = [dict(list(zip(symbols, s))) for s in solution]
elif isinstance(solution[0], dict):
pass
else:
if len(symbols) != 1:
raise ValueError("Length should be 1")
solution = [{symbols[0]: s} for s in solution]
if as_dict:
return solution
assert as_set
# each dict does not necessarily have the same keys so unify them
k = list(ordered(set(flatten(tuple(i.keys()) for i in solution))))
return k, {tuple([s.get(ki, ki) for ki in k]) for s in solution}
def _solve(f, *symbols, **flags):
"""
Return a checked solution for *f* in terms of one or more of the
symbols. A list should be returned except for the case when a linear
undetermined-coefficients equation is encountered (in which case
a dictionary is returned).
If no method is implemented to solve the equation, a NotImplementedError
will be raised. In the case that conversion of an expression to a Poly
gives None a ValueError will be raised.
"""
not_impl_msg = "No algorithms are implemented to solve equation %s"
if len(symbols) != 1:
soln = None
free = f.free_symbols
ex = free - set(symbols)
if len(ex) != 1:
ind, dep = f.as_independent(*symbols)
ex = ind.free_symbols & dep.free_symbols
if len(ex) == 1:
ex = ex.pop()
try:
# soln may come back as dict, list of dicts or tuples, or
# tuple of symbol list and set of solution tuples
soln = solve_undetermined_coeffs(f, symbols, ex, **flags)
except NotImplementedError:
pass
if soln:
if flags.get('simplify', True):
if isinstance(soln, dict):
for k in soln:
soln[k] = simplify(soln[k])
elif isinstance(soln, list):
if isinstance(soln[0], dict):
for d in soln:
for k in d:
d[k] = simplify(d[k])
elif isinstance(soln[0], tuple):
soln = [tuple(simplify(i) for i in j) for j in soln]
else:
raise TypeError('unrecognized args in list')
elif isinstance(soln, tuple):
sym, sols = soln
soln = sym, {tuple(simplify(i) for i in j) for j in sols}
else:
raise TypeError('unrecognized solution type')
return soln
# look for solutions for desired symbols that are independent
# of symbols already solved for, e.g. if we solve for x = y
# then no symbol having x in its solution will be returned.
# First solve for linear symbols (since that is easier and limits
# solution size) and then proceed with symbols appearing
# in a non-linear fashion. Ideally, if one is solving a single
# expression for several symbols, they would have to be
# appear in factors of an expression, but we do not here
# attempt factorization. XXX perhaps handling a Mul
# should come first in this routine whether there is
# one or several symbols.
nonlin_s = []
got_s = set()
rhs_s = set()
result = []
for s in symbols:
xi, v = solve_linear(f, symbols=[s])
if xi == s:
# no need to check but we should simplify if desired
if flags.get('simplify', True):
v = simplify(v)
vfree = v.free_symbols
if vfree & got_s:
# was linear, but has redundant relationship
# e.g. x - y = 0 has y == x is redundant for x == y
# so ignore
continue
rhs_s |= vfree
got_s.add(xi)
result.append({xi: v})
elif xi: # there might be a non-linear solution if xi is not 0
nonlin_s.append(s)
if not nonlin_s:
return result
for s in nonlin_s:
try:
soln = _solve(f, s, **flags)
for sol in soln:
if sol.free_symbols & got_s:
# depends on previously solved symbols: ignore
continue
got_s.add(s)
result.append({s: sol})
except NotImplementedError:
continue
if got_s:
return result
else:
raise NotImplementedError(not_impl_msg % f)
# solve f for a single variable
symbol = symbols[0]
# expand binomials only if it has the unknown symbol
f = f.replace(lambda e: isinstance(e, binomial) and e.has(symbol),
lambda e: expand_func(e))
# checking will be done unless it is turned off before making a
# recursive call; the variables `checkdens` and `check` are
# captured here (for reference below) in case flag value changes
flags['check'] = checkdens = check = flags.pop('check', True)
# build up solutions if f is a Mul
if f.is_Mul:
result = set()
for m in f.args:
if m in {S.NegativeInfinity, S.ComplexInfinity, S.Infinity}:
result = set()
break
soln = _solve(m, symbol, **flags)
result.update(set(soln))
result = list(result)
if check:
# all solutions have been checked but now we must
# check that the solutions do not set denominators
# in any factor to zero
dens = flags.get('_denominators', _simple_dens(f, symbols))
result = [s for s in result if
not any(checksol(den, {symbol: s}, **flags) for den in
dens)]
# set flags for quick exit at end; solutions for each
# factor were already checked and simplified
check = False
flags['simplify'] = False
elif f.is_Piecewise:
result = set()
for i, (expr, cond) in enumerate(f.args):
if expr.is_zero:
raise NotImplementedError(
'solve cannot represent interval solutions')
candidates = _solve(expr, symbol, **flags)
# the explicit condition for this expr is the current cond
# and none of the previous conditions
args = [~c for _, c in f.args[:i]] + [cond]
cond = And(*args)
for candidate in candidates:
if candidate in result:
# an unconditional value was already there
continue
try:
v = cond.subs(symbol, candidate)
_eval_simplify = getattr(v, '_eval_simplify', None)
if _eval_simplify is not None:
# unconditionally take the simpification of v
v = _eval_simplify(ratio=2, measure=lambda x: 1)
except TypeError:
# incompatible type with condition(s)
continue
if v == False:
continue
if v == True:
result.add(candidate)
else:
result.add(Piecewise(
(candidate, v),
(S.NaN, True)))
# set flags for quick exit at end; solutions for each
# piece were already checked and simplified
check = False
flags['simplify'] = False
else:
# first see if it really depends on symbol and whether there
# is only a linear solution
f_num, sol = solve_linear(f, symbols=symbols)
if f_num.is_zero or sol is S.NaN:
return []
elif f_num.is_Symbol:
# no need to check but simplify if desired
if flags.get('simplify', True):
sol = simplify(sol)
return [sol]
poly = None
# check for a single Add generator
if not f_num.is_Add:
add_args = [i for i in f_num.atoms(Add)
if symbol in i.free_symbols]
if len(add_args) == 1:
gen = add_args[0]
spart = gen.as_independent(symbol)[1].as_base_exp()[0]
if spart == symbol:
try:
poly = Poly(f_num, spart)
except PolynomialError:
pass
result = False # no solution was obtained
msg = '' # there is no failure message
# Poly is generally robust enough to convert anything to
# a polynomial and tell us the different generators that it
# contains, so we will inspect the generators identified by
# polys to figure out what to do.
# try to identify a single generator that will allow us to solve this
# as a polynomial, followed (perhaps) by a change of variables if the
# generator is not a symbol
try:
if poly is None:
poly = Poly(f_num)
if poly is None:
raise ValueError('could not convert %s to Poly' % f_num)
except GeneratorsNeeded:
simplified_f = simplify(f_num)
if simplified_f != f_num:
return _solve(simplified_f, symbol, **flags)
raise ValueError('expression appears to be a constant')
gens = [g for g in poly.gens if g.has(symbol)]
def _as_base_q(x):
"""Return (b**e, q) for x = b**(p*e/q) where p/q is the leading
Rational of the exponent of x, e.g. exp(-2*x/3) -> (exp(x), 3)
"""
b, e = x.as_base_exp()
if e.is_Rational:
return b, e.q
if not e.is_Mul:
return x, 1
c, ee = e.as_coeff_Mul()
if c.is_Rational and c is not S.One: # c could be a Float
return b**ee, c.q
return x, 1
if len(gens) > 1:
# If there is more than one generator, it could be that the
# generators have the same base but different powers, e.g.
# >>> Poly(exp(x) + 1/exp(x))
# Poly(exp(-x) + exp(x), exp(-x), exp(x), domain='ZZ')
#
# If unrad was not disabled then there should be no rational
# exponents appearing as in
# >>> Poly(sqrt(x) + sqrt(sqrt(x)))
# Poly(sqrt(x) + x**(1/4), sqrt(x), x**(1/4), domain='ZZ')
bases, qs = list(zip(*[_as_base_q(g) for g in gens]))
bases = set(bases)
if len(bases) > 1 or not all(q == 1 for q in qs):
funcs = {b for b in bases if b.is_Function}
trig = {_ for _ in funcs if
isinstance(_, TrigonometricFunction)}
other = funcs - trig
if not other and len(funcs.intersection(trig)) > 1:
newf = None
if f_num.is_Add and len(f_num.args) == 2:
# check for sin(x)**p = cos(x)**p
_args = f_num.args
t = a, b = [i.atoms(Function).intersection(
trig) for i in _args]
if all(len(i) == 1 for i in t):
a, b = [i.pop() for i in t]
if isinstance(a, cos):
a, b = b, a
_args = _args[::-1]
if isinstance(a, sin) and isinstance(b, cos
) and a.args[0] == b.args[0]:
# sin(x) + cos(x) = 0 -> tan(x) + 1 = 0
newf, _d = (TR2i(_args[0]/_args[1]) + 1
).as_numer_denom()
if not _d.is_Number:
newf = None
if newf is None:
newf = TR1(f_num).rewrite(tan)
if newf != f_num:
# don't check the rewritten form --check
# solutions in the un-rewritten form below
flags['check'] = False
result = _solve(newf, symbol, **flags)
flags['check'] = check
# just a simple case - see if replacement of single function
# clears all symbol-dependent functions, e.g.
# log(x) - log(log(x) - 1) - 3 can be solved even though it has
# two generators.
if result is False and funcs:
funcs = list(ordered(funcs)) # put shallowest function first
f1 = funcs[0]
t = Dummy('t')
# perform the substitution
ftry = f_num.subs(f1, t)
# if no Functions left, we can proceed with usual solve
if not ftry.has(symbol):
cv_sols = _solve(ftry, t, **flags)
cv_inv = _solve(t - f1, symbol, **flags)[0]
sols = list()
for sol in cv_sols:
sols.append(cv_inv.subs(t, sol))
result = list(ordered(sols))
if result is False:
msg = 'multiple generators %s' % gens
else:
# e.g. case where gens are exp(x), exp(-x)
u = bases.pop()
t = Dummy('t')
inv = _solve(u - t, symbol, **flags)
if isinstance(u, (Pow, exp)):
# this will be resolved by factor in _tsolve but we might
# as well try a simple expansion here to get things in
# order so something like the following will work now without
# having to factor:
#
# >>> eq = (exp(I*(-x-2))+exp(I*(x+2)))
# >>> eq.subs(exp(x),y) # fails
# exp(I*(-x - 2)) + exp(I*(x + 2))
# >>> eq.expand().subs(exp(x),y) # works
# y**I*exp(2*I) + y**(-I)*exp(-2*I)
def _expand(p):
b, e = p.as_base_exp()
e = expand_mul(e)
return expand_power_exp(b**e)
ftry = f_num.replace(
lambda w: w.is_Pow or isinstance(w, exp),
_expand).subs(u, t)
if not ftry.has(symbol):
soln = _solve(ftry, t, **flags)
sols = list()
for sol in soln:
for i in inv:
sols.append(i.subs(t, sol))
result = list(ordered(sols))
elif len(gens) == 1:
# There is only one generator that we are interested in, but
# there may have been more than one generator identified by
# polys (e.g. for symbols other than the one we are interested
# in) so recast the poly in terms of our generator of interest.
# Also use composite=True with f_num since Poly won't update
# poly as documented in issue 8810.
poly = Poly(f_num, gens[0], composite=True)
# if we aren't on the tsolve-pass, use roots
if not flags.pop('tsolve', False):
soln = None
deg = poly.degree()
flags['tsolve'] = True
hints = ('cubics', 'quartics', 'quintics')
solvers = {h: flags.get(h) for h in hints}
soln = roots(poly, **solvers)
if sum(soln.values()) < deg:
# e.g. roots(32*x**5 + 400*x**4 + 2032*x**3 +
# 5000*x**2 + 6250*x + 3189) -> {}
# so all_roots is used and RootOf instances are
# returned *unless* the system is multivariate
# or high-order EX domain.
try:
soln = poly.all_roots()
except NotImplementedError:
if not flags.get('incomplete', True):
raise NotImplementedError(
filldedent('''
Neither high-order multivariate polynomials
nor sorting of EX-domain polynomials is supported.
If you want to see any results, pass keyword incomplete=True to
solve; to see numerical values of roots
for univariate expressions, use nroots.
'''))
else:
pass
else:
soln = list(soln.keys())
if soln is not None:
u = poly.gen
if u != symbol:
try:
t = Dummy('t')
iv = _solve(u - t, symbol, **flags)
soln = list(ordered({i.subs(t, s) for i in iv for s in soln}))
except NotImplementedError:
# perhaps _tsolve can handle f_num
soln = None
else:
check = False # only dens need to be checked
if soln is not None:
if len(soln) > 2:
# if the flag wasn't set then unset it since high-order
# results are quite long. Perhaps one could base this
# decision on a certain critical length of the
# roots. In addition, wester test M2 has an expression
# whose roots can be shown to be real with the
# unsimplified form of the solution whereas only one of
# the simplified forms appears to be real.
flags['simplify'] = flags.get('simplify', False)
result = soln
# fallback if above fails
# -----------------------
if result is False:
# try unrad
if flags.pop('_unrad', True):
try:
u = unrad(f_num, symbol)
except (ValueError, NotImplementedError):
u = False
if u:
eq, cov = u
if cov:
isym, ieq = cov
inv = _solve(ieq, symbol, **flags)[0]
rv = {inv.subs(isym, xi) for xi in _solve(eq, isym, **flags)}
else:
try:
rv = set(_solve(eq, symbol, **flags))
except NotImplementedError:
rv = None
if rv is not None:
result = list(ordered(rv))
# if the flag wasn't set then unset it since unrad results
# can be quite long or of very high order
flags['simplify'] = flags.get('simplify', False)
else:
pass # for coverage
# try _tsolve
if result is False:
flags.pop('tsolve', None) # allow tsolve to be used on next pass
try:
soln = _tsolve(f_num, symbol, **flags)
if soln is not None:
result = soln
except PolynomialError:
pass
# ----------- end of fallback ----------------------------
if result is False:
raise NotImplementedError('\n'.join([msg, not_impl_msg % f]))
if flags.get('simplify', True):
result = list(map(simplify, result))
# we just simplified the solution so we now set the flag to
# False so the simplification doesn't happen again in checksol()
flags['simplify'] = False
if checkdens:
# reject any result that makes any denom. affirmatively 0;
# if in doubt, keep it
dens = _simple_dens(f, symbols)
result = [s for s in result if
not any(checksol(d, {symbol: s}, **flags)
for d in dens)]
if check:
# keep only results if the check is not False
result = [r for r in result if
checksol(f_num, {symbol: r}, **flags) is not False]
return result
def _solve_system(exprs, symbols, **flags):
if not exprs:
return []
if flags.pop('_split', True):
# Split the system into connected components
V = exprs
symsset = set(symbols)
exprsyms = {e: e.free_symbols & symsset for e in exprs}
E = []
sym_indices = {sym: i for i, sym in enumerate(symbols)}
for n, e1 in enumerate(exprs):
for e2 in exprs[:n]:
# Equations are connected if they share a symbol
if exprsyms[e1] & exprsyms[e2]:
E.append((e1, e2))
G = V, E
subexprs = connected_components(G)
if len(subexprs) > 1:
subsols = []
for subexpr in subexprs:
subsyms = set()
for e in subexpr:
subsyms |= exprsyms[e]
subsyms = list(sorted(subsyms, key = lambda x: sym_indices[x]))
flags['_split'] = False # skip split step
subsol = _solve_system(subexpr, subsyms, **flags)
if not isinstance(subsol, list):
subsol = [subsol]
subsols.append(subsol)
# Full solution is cartesion product of subsystems
sols = []
for soldicts in product(*subsols):
sols.append(dict(item for sd in soldicts
for item in sd.items()))
# Return a list with one dict as just the dict
if len(sols) == 1:
return sols[0]
return sols
polys = []
dens = set()
failed = []
result = False
linear = False
manual = flags.get('manual', False)
checkdens = check = flags.get('check', True)
for j, g in enumerate(exprs):
dens.update(_simple_dens(g, symbols))
i, d = _invert(g, *symbols)
g = d - i
g = g.as_numer_denom()[0]
if manual:
failed.append(g)
continue
poly = g.as_poly(*symbols, extension=True)
if poly is not None:
polys.append(poly)
else:
failed.append(g)
if not polys:
solved_syms = []
else:
if all(p.is_linear for p in polys):
n, m = len(polys), len(symbols)
matrix = zeros(n, m + 1)
for i, poly in enumerate(polys):
for monom, coeff in poly.terms():
try:
j = monom.index(1)
matrix[i, j] = coeff
except ValueError:
matrix[i, m] = -coeff
# returns a dictionary ({symbols: values}) or None
if flags.pop('particular', False):
result = minsolve_linear_system(matrix, *symbols, **flags)
else:
result = solve_linear_system(matrix, *symbols, **flags)
if failed:
if result:
solved_syms = list(result.keys())
else:
solved_syms = []
else:
linear = True
else:
if len(symbols) > len(polys):
free = set().union(*[p.free_symbols for p in polys])
free = list(ordered(free.intersection(symbols)))
got_s = set()
result = []
for syms in subsets(free, len(polys)):
try:
# returns [] or list of tuples of solutions for syms
res = solve_poly_system(polys, *syms)
if res:
for r in res:
skip = False
for r1 in r:
if got_s and any(ss in r1.free_symbols
for ss in got_s):
# sol depends on previously
# solved symbols: discard it
skip = True
if not skip:
got_s.update(syms)
result.extend([dict(list(zip(syms, r)))])
except NotImplementedError:
pass
if got_s:
solved_syms = list(got_s)
else:
raise NotImplementedError('no valid subset found')
else:
try:
result = solve_poly_system(polys, *symbols)
if result:
solved_syms = symbols
# we don't know here if the symbols provided
# were given or not, so let solve resolve that.
# A list of dictionaries is going to always be
# returned from here.
result = [dict(list(zip(solved_syms, r))) for r in result]
except NotImplementedError:
failed.extend([g.as_expr() for g in polys])
solved_syms = []
result = None
if result:
if isinstance(result, dict):
result = [result]
else:
result = [{}]
if failed:
# For each failed equation, see if we can solve for one of the
# remaining symbols from that equation. If so, we update the
# solution set and continue with the next failed equation,
# repeating until we are done or we get an equation that can't
# be solved.
def _ok_syms(e, sort=False):
rv = e.free_symbols & legal
# Solve first for symbols that have lower degree in the equation.
# Ideally we want to solve firstly for symbols that appear linearly
# with rational coefficients e.g. if e = x*y + z then we should
# solve for z first.
def key(sym):
ep = e.as_poly(sym)
if ep is None:
complexity = (S.Infinity, S.Infinity, S.Infinity)
else:
coeff_syms = ep.LC().free_symbols
complexity = (ep.degree(), len(coeff_syms & rv), len(coeff_syms))
return complexity + (default_sort_key(sym),)
if sort:
rv = sorted(rv, key=key)
return rv
legal = set(symbols) # what we are interested in
# sort so equation with the fewest potential symbols is first
u = Dummy() # used in solution checking
for eq in ordered(failed, lambda _: len(_ok_syms(_))):
newresult = []
bad_results = []
got_s = set()
hit = False
for r in result:
# update eq with everything that is known so far
eq2 = eq.subs(r)
# if check is True then we see if it satisfies this
# equation, otherwise we just accept it
if check and r:
b = checksol(u, u, eq2, minimal=True)
if b is not None:
# this solution is sufficient to know whether
# it is valid or not so we either accept or
# reject it, then continue
if b:
newresult.append(r)
else:
bad_results.append(r)
continue
# search for a symbol amongst those available that
# can be solved for
ok_syms = _ok_syms(eq2, sort=True)
if not ok_syms:
if r:
newresult.append(r)
break # skip as it's independent of desired symbols
for s in ok_syms:
try:
soln = _solve(eq2, s, **flags)
except NotImplementedError:
continue
# put each solution in r and append the now-expanded
# result in the new result list; use copy since the
# solution for s is being added in-place
for sol in soln:
if got_s and any(ss in sol.free_symbols for ss in got_s):
# sol depends on previously solved symbols: discard it
continue
rnew = r.copy()
for k, v in r.items():
rnew[k] = v.subs(s, sol)
# and add this new solution
rnew[s] = sol
# check that it is independent of previous solutions
iset = set(rnew.items())
for i in newresult:
if len(i) < len(iset) and not set(i.items()) - iset:
# this is a superset of a known solution that
# is smaller
break
else:
# keep it
newresult.append(rnew)
hit = True
got_s.add(s)
if not hit:
raise NotImplementedError('could not solve %s' % eq2)
else:
result = newresult
for b in bad_results:
if b in result:
result.remove(b)
default_simplify = bool(failed) # rely on system-solvers to simplify
if flags.get('simplify', default_simplify):
for r in result:
for k in r:
r[k] = simplify(r[k])
flags['simplify'] = False # don't need to do so in checksol now
if checkdens:
result = [r for r in result
if not any(checksol(d, r, **flags) for d in dens)]
if check and not linear:
result = [r for r in result
if not any(checksol(e, r, **flags) is False for e in exprs)]
result = [r for r in result if r]
if linear and result:
result = result[0]
return result
def solve_linear(lhs, rhs=0, symbols=[], exclude=[]):
r"""
Return a tuple derived from ``f = lhs - rhs`` that is one of
the following: ``(0, 1)``, ``(0, 0)``, ``(symbol, solution)``, ``(n, d)``.
Explanation
===========
``(0, 1)`` meaning that ``f`` is independent of the symbols in *symbols*
that are not in *exclude*.
``(0, 0)`` meaning that there is no solution to the equation amongst the
symbols given. If the first element of the tuple is not zero, then the
function is guaranteed to be dependent on a symbol in *symbols*.
``(symbol, solution)`` where symbol appears linearly in the numerator of
``f``, is in *symbols* (if given), and is not in *exclude* (if given). No
simplification is done to ``f`` other than a ``mul=True`` expansion, so the
solution will correspond strictly to a unique solution.
``(n, d)`` where ``n`` and ``d`` are the numerator and denominator of ``f``
when the numerator was not linear in any symbol of interest; ``n`` will
never be a symbol unless a solution for that symbol was found (in which case
the second element is the solution, not the denominator).
Examples
========
>>> from sympy import cancel, Pow
``f`` is independent of the symbols in *symbols* that are not in
*exclude*:
>>> from sympy import cos, sin, solve_linear
>>> from sympy.abc import x, y, z
>>> eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0
>>> solve_linear(eq)
(0, 1)
>>> eq = cos(x)**2 + sin(x)**2 # = 1
>>> solve_linear(eq)
(0, 1)
>>> solve_linear(x, exclude=[x])
(0, 1)
The variable ``x`` appears as a linear variable in each of the
following:
>>> solve_linear(x + y**2)
(x, -y**2)
>>> solve_linear(1/x - y**2)
(x, y**(-2))
When not linear in ``x`` or ``y`` then the numerator and denominator are
returned:
>>> solve_linear(x**2/y**2 - 3)
(x**2 - 3*y**2, y**2)
If the numerator of the expression is a symbol, then ``(0, 0)`` is
returned if the solution for that symbol would have set any
denominator to 0:
>>> eq = 1/(1/x - 2)
>>> eq.as_numer_denom()
(x, 1 - 2*x)
>>> solve_linear(eq)
(0, 0)
But automatic rewriting may cause a symbol in the denominator to
appear in the numerator so a solution will be returned:
>>> (1/x)**-1
x
>>> solve_linear((1/x)**-1)
(x, 0)
Use an unevaluated expression to avoid this:
>>> solve_linear(Pow(1/x, -1, evaluate=False))
(0, 0)
If ``x`` is allowed to cancel in the following expression, then it
appears to be linear in ``x``, but this sort of cancellation is not
done by ``solve_linear`` so the solution will always satisfy the
original expression without causing a division by zero error.
>>> eq = x**2*(1/x - z**2/x)
>>> solve_linear(cancel(eq))
(x, 0)
>>> solve_linear(eq)
(x**2*(1 - z**2), x)
A list of symbols for which a solution is desired may be given:
>>> solve_linear(x + y + z, symbols=[y])
(y, -x - z)
A list of symbols to ignore may also be given:
>>> solve_linear(x + y + z, exclude=[x])
(y, -x - z)
(A solution for ``y`` is obtained because it is the first variable
from the canonically sorted list of symbols that had a linear
solution.)
"""
if isinstance(lhs, Eq):
if rhs:
raise ValueError(filldedent('''
If lhs is an Equality, rhs must be 0 but was %s''' % rhs))
rhs = lhs.rhs
lhs = lhs.lhs
dens = None
eq = lhs - rhs
n, d = eq.as_numer_denom()
if not n:
return S.Zero, S.One
free = n.free_symbols
if not symbols:
symbols = free
else:
bad = [s for s in symbols if not s.is_Symbol]
if bad:
if len(bad) == 1:
bad = bad[0]
if len(symbols) == 1:
eg = 'solve(%s, %s)' % (eq, symbols[0])
else:
eg = 'solve(%s, *%s)' % (eq, list(symbols))
raise ValueError(filldedent('''
solve_linear only handles symbols, not %s. To isolate
non-symbols use solve, e.g. >>> %s <<<.
''' % (bad, eg)))
symbols = free.intersection(symbols)
symbols = symbols.difference(exclude)
if not symbols:
return S.Zero, S.One
# derivatives are easy to do but tricky to analyze to see if they
# are going to disallow a linear solution, so for simplicity we
# just evaluate the ones that have the symbols of interest
derivs = defaultdict(list)
for der in n.atoms(Derivative):
csym = der.free_symbols & symbols
for c in csym:
derivs[c].append(der)
all_zero = True
for xi in sorted(symbols, key=default_sort_key): # canonical order
# if there are derivatives in this var, calculate them now
if isinstance(derivs[xi], list):
derivs[xi] = {der: der.doit() for der in derivs[xi]}
newn = n.subs(derivs[xi])
dnewn_dxi = newn.diff(xi)
# dnewn_dxi can be nonzero if it survives differentation by any
# of its free symbols
free = dnewn_dxi.free_symbols
if dnewn_dxi and (not free or any(dnewn_dxi.diff(s) for s in free) or free == symbols):
all_zero = False
if dnewn_dxi is S.NaN:
break
if xi not in dnewn_dxi.free_symbols:
vi = -1/dnewn_dxi*(newn.subs(xi, 0))
if dens is None:
dens = _simple_dens(eq, symbols)
if not any(checksol(di, {xi: vi}, minimal=True) is True
for di in dens):
# simplify any trivial integral
irep = [(i, i.doit()) for i in vi.atoms(Integral) if
i.function.is_number]
# do a slight bit of simplification
vi = expand_mul(vi.subs(irep))
return xi, vi
if all_zero:
return S.Zero, S.One
if n.is_Symbol: # no solution for this symbol was found
return S.Zero, S.Zero
return n, d
def minsolve_linear_system(system, *symbols, **flags):
r"""
Find a particular solution to a linear system.
Explanation
===========
In particular, try to find a solution with the minimal possible number
of non-zero variables using a naive algorithm with exponential complexity.
If ``quick=True``, a heuristic is used.
"""
quick = flags.get('quick', False)
# Check if there are any non-zero solutions at all
s0 = solve_linear_system(system, *symbols, **flags)
if not s0 or all(v == 0 for v in s0.values()):
return s0
if quick:
# We just solve the system and try to heuristically find a nice
# solution.
s = solve_linear_system(system, *symbols)
def update(determined, solution):
delete = []
for k, v in solution.items():
solution[k] = v.subs(determined)
if not solution[k].free_symbols:
delete.append(k)
determined[k] = solution[k]
for k in delete:
del solution[k]
determined = {}
update(determined, s)
while s:
# NOTE sort by default_sort_key to get deterministic result
k = max((k for k in s.values()),
key=lambda x: (len(x.free_symbols), default_sort_key(x)))
kfree = k.free_symbols
x = next(reversed(list(ordered(kfree))))
if len(kfree) != 1:
determined[x] = S.Zero
else:
val = _solve(k, x, check=False)[0]
if val == 0 and all(v.subs(x, val) == 0 for v in s.values()):
determined[x] = S.One
else:
determined[x] = val
update(determined, s)
return determined
else:
# We try to select n variables which we want to be non-zero.
# All others will be assumed zero. We try to solve the modified system.
# If there is a non-trivial solution, just set the free variables to
# one. If we do this for increasing n, trying all combinations of
# variables, we will find an optimal solution.
# We speed up slightly by starting at one less than the number of
# variables the quick method manages.
N = len(symbols)
bestsol = minsolve_linear_system(system, *symbols, quick=True)
n0 = len([x for x in bestsol.values() if x != 0])
for n in range(n0 - 1, 1, -1):
debug('minsolve: %s' % n)
thissol = None
for nonzeros in combinations(list(range(N)), n):
subm = Matrix([system.col(i).T for i in nonzeros] + [system.col(-1).T]).T
s = solve_linear_system(subm, *[symbols[i] for i in nonzeros])
if s and not all(v == 0 for v in s.values()):
subs = [(symbols[v], S.One) for v in nonzeros]
for k, v in s.items():
s[k] = v.subs(subs)
for sym in symbols:
if sym not in s:
if symbols.index(sym) in nonzeros:
s[sym] = S.One
else:
s[sym] = S.Zero
thissol = s
break
if thissol is None:
break
bestsol = thissol
return bestsol
def solve_linear_system(system, *symbols, **flags):
r"""
Solve system of $N$ linear equations with $M$ variables, which means
both under- and overdetermined systems are supported.
Explanation
===========
The possible number of solutions is zero, one, or infinite. Respectively,
this procedure will return None or a dictionary with solutions. In the
case of underdetermined systems, all arbitrary parameters are skipped.
This may cause a situation in which an empty dictionary is returned.
In that case, all symbols can be assigned arbitrary values.
Input to this function is a $N\times M + 1$ matrix, which means it has
to be in augmented form. If you prefer to enter $N$ equations and $M$
unknowns then use ``solve(Neqs, *Msymbols)`` instead. Note: a local
copy of the matrix is made by this routine so the matrix that is
passed will not be modified.
The algorithm used here is fraction-free Gaussian elimination,
which results, after elimination, in an upper-triangular matrix.
Then solutions are found using back-substitution. This approach
is more efficient and compact than the Gauss-Jordan method.
Examples
========
>>> from sympy import Matrix, solve_linear_system
>>> from sympy.abc import x, y
Solve the following system::
x + 4 y == 2
-2 x + y == 14
>>> system = Matrix(( (1, 4, 2), (-2, 1, 14)))
>>> solve_linear_system(system, x, y)
{x: -6, y: 2}
A degenerate system returns an empty dictionary:
>>> system = Matrix(( (0,0,0), (0,0,0) ))
>>> solve_linear_system(system, x, y)
{}
"""
assert system.shape[1] == len(symbols) + 1
# This is just a wrapper for solve_lin_sys
eqs = list(system * Matrix(symbols + (-1,)))
eqs, ring = sympy_eqs_to_ring(eqs, symbols)
sol = solve_lin_sys(eqs, ring, _raw=False)
if sol is not None:
sol = {sym:val for sym, val in sol.items() if sym != val}
return sol
def solve_undetermined_coeffs(equ, coeffs, sym, **flags):
r"""
Solve equation of a type $p(x; a_1, \ldots, a_k) = q(x)$ where both
$p$ and $q$ are univariate polynomials that depend on $k$ parameters.
Explanation
===========
The result of this function is a dictionary with symbolic values of those
parameters with respect to coefficients in $q$.
This function accepts both equations class instances and ordinary
SymPy expressions. Specification of parameters and variables is
obligatory for efficiency and simplicity reasons.
Examples
========
>>> from sympy import Eq, solve_undetermined_coeffs
>>> from sympy.abc import a, b, c, x
>>> solve_undetermined_coeffs(Eq(2*a*x + a+b, x), [a, b], x)
{a: 1/2, b: -1/2}
>>> solve_undetermined_coeffs(Eq(a*c*x + a+b, x), [a, b], x)
{a: 1/c, b: -1/c}
"""
if isinstance(equ, Eq):
# got equation, so move all the
# terms to the left hand side
equ = equ.lhs - equ.rhs
equ = cancel(equ).as_numer_denom()[0]
system = list(collect(equ.expand(), sym, evaluate=False).values())
if not any(equ.has(sym) for equ in system):
# consecutive powers in the input expressions have
# been successfully collected, so solve remaining
# system using Gaussian elimination algorithm
return solve(system, *coeffs, **flags)
else:
return None # no solutions
def solve_linear_system_LU(matrix, syms):
"""
Solves the augmented matrix system using ``LUsolve`` and returns a
dictionary in which solutions are keyed to the symbols of *syms* as ordered.
Explanation
===========
The matrix must be invertible.
Examples
========
>>> from sympy import Matrix, solve_linear_system_LU
>>> from sympy.abc import x, y, z
>>> solve_linear_system_LU(Matrix([
... [1, 2, 0, 1],
... [3, 2, 2, 1],
... [2, 0, 0, 1]]), [x, y, z])
{x: 1/2, y: 1/4, z: -1/2}
See Also
========
LUsolve
"""
if matrix.rows != matrix.cols - 1:
raise ValueError("Rows should be equal to columns - 1")
A = matrix[:matrix.rows, :matrix.rows]
b = matrix[:, matrix.cols - 1:]
soln = A.LUsolve(b)
solutions = {}
for i in range(soln.rows):
solutions[syms[i]] = soln[i, 0]
return solutions
def det_perm(M):
"""
Return the determinant of *M* by using permutations to select factors.
Explanation
===========
For sizes larger than 8 the number of permutations becomes prohibitively
large, or if there are no symbols in the matrix, it is better to use the
standard determinant routines (e.g., ``M.det()``.)
See Also
========
det_minor
det_quick
"""
args = []
s = True
n = M.rows
list_ = M.flat()
for perm in generate_bell(n):
fac = []
idx = 0
for j in perm:
fac.append(list_[idx + j])
idx += n
term = Mul(*fac) # disaster with unevaluated Mul -- takes forever for n=7
args.append(term if s else -term)
s = not s
return Add(*args)
def det_minor(M):
"""
Return the ``det(M)`` computed from minors without
introducing new nesting in products.
See Also
========
det_perm
det_quick
"""
n = M.rows
if n == 2:
return M[0, 0]*M[1, 1] - M[1, 0]*M[0, 1]
else:
return sum([(1, -1)[i % 2]*Add(*[M[0, i]*d for d in
Add.make_args(det_minor(M.minor_submatrix(0, i)))])
if M[0, i] else S.Zero for i in range(n)])
def det_quick(M, method=None):
"""
Return ``det(M)`` assuming that either
there are lots of zeros or the size of the matrix
is small. If this assumption is not met, then the normal
Matrix.det function will be used with method = ``method``.
See Also
========
det_minor
det_perm
"""
if any(i.has(Symbol) for i in M):
if M.rows < 8 and all(i.has(Symbol) for i in M):
return det_perm(M)
return det_minor(M)
else:
return M.det(method=method) if method else M.det()
def inv_quick(M):
"""Return the inverse of ``M``, assuming that either
there are lots of zeros or the size of the matrix
is small.
"""
if not all(i.is_Number for i in M):
if not any(i.is_Number for i in M):
det = lambda _: det_perm(_)
else:
det = lambda _: det_minor(_)
else:
return M.inv()
n = M.rows
d = det(M)
if d == S.Zero:
raise NonInvertibleMatrixError("Matrix det == 0; not invertible")
ret = zeros(n)
s1 = -1
for i in range(n):
s = s1 = -s1
for j in range(n):
di = det(M.minor_submatrix(i, j))
ret[j, i] = s*di/d
s = -s
return ret
# these are functions that have multiple inverse values per period
multi_inverses = {
sin: lambda x: (asin(x), S.Pi - asin(x)),
cos: lambda x: (acos(x), 2*S.Pi - acos(x)),
}
def _tsolve(eq, sym, **flags):
"""
Helper for ``_solve`` that solves a transcendental equation with respect
to the given symbol. Various equations containing powers and logarithms,
can be solved.
There is currently no guarantee that all solutions will be returned or
that a real solution will be favored over a complex one.
Either a list of potential solutions will be returned or None will be
returned (in the case that no method was known to get a solution
for the equation). All other errors (like the inability to cast an
expression as a Poly) are unhandled.
Examples
========
>>> from sympy import log
>>> from sympy.solvers.solvers import _tsolve as tsolve
>>> from sympy.abc import x
>>> tsolve(3**(2*x + 5) - 4, x)
[-5/2 + log(2)/log(3), (-5*log(3)/2 + log(2) + I*pi)/log(3)]
>>> tsolve(log(x) + 2*x, x)
[LambertW(2)/2]
"""
if 'tsolve_saw' not in flags:
flags['tsolve_saw'] = []
if eq in flags['tsolve_saw']:
return None
else:
flags['tsolve_saw'].append(eq)
rhs, lhs = _invert(eq, sym)
if lhs == sym:
return [rhs]
try:
if lhs.is_Add:
# it's time to try factoring; powdenest is used
# to try get powers in standard form for better factoring
f = factor(powdenest(lhs - rhs))
if f.is_Mul:
return _solve(f, sym, **flags)
if rhs:
f = logcombine(lhs, force=flags.get('force', True))
if f.count(log) != lhs.count(log):
if isinstance(f, log):
return _solve(f.args[0] - exp(rhs), sym, **flags)
return _tsolve(f - rhs, sym, **flags)
elif lhs.is_Pow:
if lhs.exp.is_Integer:
if lhs - rhs != eq:
return _solve(lhs - rhs, sym, **flags)
if sym not in lhs.exp.free_symbols:
return _solve(lhs.base - rhs**(1/lhs.exp), sym, **flags)
# _tsolve calls this with Dummy before passing the actual number in.
if any(t.is_Dummy for t in rhs.free_symbols):
raise NotImplementedError # _tsolve will call here again...
# a ** g(x) == 0
if not rhs:
# f(x)**g(x) only has solutions where f(x) == 0 and g(x) != 0 at
# the same place
sol_base = _solve(lhs.base, sym, **flags)
return [s for s in sol_base if lhs.exp.subs(sym, s) != 0]
# a ** g(x) == b
if not lhs.base.has(sym):
if lhs.base == 0:
return _solve(lhs.exp, sym, **flags) if rhs != 0 else []
# Gets most solutions...
if lhs.base == rhs.as_base_exp()[0]:
# handles case when bases are equal
sol = _solve(lhs.exp - rhs.as_base_exp()[1], sym, **flags)
else:
# handles cases when bases are not equal and exp
# may or may not be equal
sol = _solve(exp(log(lhs.base)*lhs.exp)-exp(log(rhs)), sym, **flags)
# Check for duplicate solutions
def equal(expr1, expr2):
_ = Dummy()
eq = checksol(expr1 - _, _, expr2)
if eq is None:
if nsimplify(expr1) != nsimplify(expr2):
return False
# they might be coincidentally the same
# so check more rigorously
eq = expr1.equals(expr2)
return eq
# Guess a rational exponent
e_rat = nsimplify(log(abs(rhs))/log(abs(lhs.base)))
e_rat = simplify(posify(e_rat)[0])
n, d = fraction(e_rat)
if expand(lhs.base**n - rhs**d) == 0:
sol = [s for s in sol if not equal(lhs.exp.subs(sym, s), e_rat)]
sol.extend(_solve(lhs.exp - e_rat, sym, **flags))
return list(ordered(set(sol)))
# f(x) ** g(x) == c
else:
sol = []
logform = lhs.exp*log(lhs.base) - log(rhs)
if logform != lhs - rhs:
try:
sol.extend(_solve(logform, sym, **flags))
except NotImplementedError:
pass
# Collect possible solutions and check with substitution later.
check = []
if rhs == 1:
# f(x) ** g(x) = 1 -- g(x)=0 or f(x)=+-1
check.extend(_solve(lhs.exp, sym, **flags))
check.extend(_solve(lhs.base - 1, sym, **flags))
check.extend(_solve(lhs.base + 1, sym, **flags))
elif rhs.is_Rational:
for d in (i for i in divisors(abs(rhs.p)) if i != 1):
e, t = integer_log(rhs.p, d)
if not t:
continue # rhs.p != d**b
for s in divisors(abs(rhs.q)):
if s**e== rhs.q:
r = Rational(d, s)
check.extend(_solve(lhs.base - r, sym, **flags))
check.extend(_solve(lhs.base + r, sym, **flags))
check.extend(_solve(lhs.exp - e, sym, **flags))
elif rhs.is_irrational:
b_l, e_l = lhs.base.as_base_exp()
n, d = (e_l*lhs.exp).as_numer_denom()
b, e = sqrtdenest(rhs).as_base_exp()
check = [sqrtdenest(i) for i in (_solve(lhs.base - b, sym, **flags))]
check.extend([sqrtdenest(i) for i in (_solve(lhs.exp - e, sym, **flags))])
if e_l*d != 1:
check.extend(_solve(b_l**n - rhs**(e_l*d), sym, **flags))
for s in check:
ok = checksol(eq, sym, s)
if ok is None:
ok = eq.subs(sym, s).equals(0)
if ok:
sol.append(s)
return list(ordered(set(sol)))
elif lhs.is_Function and len(lhs.args) == 1:
if lhs.func in multi_inverses:
# sin(x) = 1/3 -> x - asin(1/3) & x - (pi - asin(1/3))
soln = []
for i in multi_inverses[type(lhs)](rhs):
soln.extend(_solve(lhs.args[0] - i, sym, **flags))
return list(ordered(soln))
elif lhs.func == LambertW:
return _solve(lhs.args[0] - rhs*exp(rhs), sym, **flags)
rewrite = lhs.rewrite(exp)
if rewrite != lhs:
return _solve(rewrite - rhs, sym, **flags)
except NotImplementedError:
pass
# maybe it is a lambert pattern
if flags.pop('bivariate', True):
# lambert forms may need some help being recognized, e.g. changing
# 2**(3*x) + x**3*log(2)**3 + 3*x**2*log(2)**2 + 3*x*log(2) + 1
# to 2**(3*x) + (x*log(2) + 1)**3
g = _filtered_gens(eq.as_poly(), sym)
up_or_log = set()
for gi in g:
if isinstance(gi, (exp, log)) or (gi.is_Pow and gi.base == S.Exp1):
up_or_log.add(gi)
elif gi.is_Pow:
gisimp = powdenest(expand_power_exp(gi))
if gisimp.is_Pow and sym in gisimp.exp.free_symbols:
up_or_log.add(gi)
eq_down = expand_log(expand_power_exp(eq)).subs(
dict(list(zip(up_or_log, [0]*len(up_or_log)))))
eq = expand_power_exp(factor(eq_down, deep=True) + (eq - eq_down))
rhs, lhs = _invert(eq, sym)
if lhs.has(sym):
try:
poly = lhs.as_poly()
g = _filtered_gens(poly, sym)
_eq = lhs - rhs
sols = _solve_lambert(_eq, sym, g)
# use a simplified form if it satisfies eq
# and has fewer operations
for n, s in enumerate(sols):
ns = nsimplify(s)
if ns != s and ns.count_ops() <= s.count_ops():
ok = checksol(_eq, sym, ns)
if ok is None:
ok = _eq.subs(sym, ns).equals(0)
if ok:
sols[n] = ns
return sols
except NotImplementedError:
# maybe it's a convoluted function
if len(g) == 2:
try:
gpu = bivariate_type(lhs - rhs, *g)
if gpu is None:
raise NotImplementedError
g, p, u = gpu
flags['bivariate'] = False
inversion = _tsolve(g - u, sym, **flags)
if inversion:
sol = _solve(p, u, **flags)
return list(ordered({i.subs(u, s)
for i in inversion for s in sol}))
except NotImplementedError:
pass
else:
pass
if flags.pop('force', True):
flags['force'] = False
pos, reps = posify(lhs - rhs)
if rhs == S.ComplexInfinity:
return []
for u, s in reps.items():
if s == sym:
break
else:
u = sym
if pos.has(u):
try:
soln = _solve(pos, u, **flags)
return list(ordered([s.subs(reps) for s in soln]))
except NotImplementedError:
pass
else:
pass # here for coverage
return # here for coverage
# TODO: option for calculating J numerically
@conserve_mpmath_dps
def nsolve(*args, dict=False, **kwargs):
r"""
Solve a nonlinear equation system numerically: ``nsolve(f, [args,] x0,
modules=['mpmath'], **kwargs)``.
Explanation
===========
``f`` is a vector function of symbolic expressions representing the system.
*args* are the variables. If there is only one variable, this argument can
be omitted. ``x0`` is a starting vector close to a solution.
Use the modules keyword to specify which modules should be used to
evaluate the function and the Jacobian matrix. Make sure to use a module
that supports matrices. For more information on the syntax, please see the
docstring of ``lambdify``.
If the keyword arguments contain ``dict=True`` (default is False) ``nsolve``
will return a list (perhaps empty) of solution mappings. This might be
especially useful if you want to use ``nsolve`` as a fallback to solve since
using the dict argument for both methods produces return values of
consistent type structure. Please note: to keep this consistent with
``solve``, the solution will be returned in a list even though ``nsolve``
(currently at least) only finds one solution at a time.
Overdetermined systems are supported.
Examples
========
>>> from sympy import Symbol, nsolve
>>> import mpmath
>>> mpmath.mp.dps = 15
>>> x1 = Symbol('x1')
>>> x2 = Symbol('x2')
>>> f1 = 3 * x1**2 - 2 * x2**2 - 1
>>> f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
>>> print(nsolve((f1, f2), (x1, x2), (-1, 1)))
Matrix([[-1.19287309935246], [1.27844411169911]])
For one-dimensional functions the syntax is simplified:
>>> from sympy import sin, nsolve
>>> from sympy.abc import x
>>> nsolve(sin(x), x, 2)
3.14159265358979
>>> nsolve(sin(x), 2)
3.14159265358979
To solve with higher precision than the default, use the prec argument:
>>> from sympy import cos
>>> nsolve(cos(x) - x, 1)
0.739085133215161
>>> nsolve(cos(x) - x, 1, prec=50)
0.73908513321516064165531208767387340401341175890076
>>> cos(_)
0.73908513321516064165531208767387340401341175890076
To solve for complex roots of real functions, a nonreal initial point
must be specified:
>>> from sympy import I
>>> nsolve(x**2 + 2, I)
1.4142135623731*I
``mpmath.findroot`` is used and you can find their more extensive
documentation, especially concerning keyword parameters and
available solvers. Note, however, that functions which are very
steep near the root, the verification of the solution may fail. In
this case you should use the flag ``verify=False`` and
independently verify the solution.
>>> from sympy import cos, cosh
>>> f = cos(x)*cosh(x) - 1
>>> nsolve(f, 3.14*100)
Traceback (most recent call last):
...
ValueError: Could not find root within given tolerance. (1.39267e+230 > 2.1684e-19)
>>> ans = nsolve(f, 3.14*100, verify=False); ans
312.588469032184
>>> f.subs(x, ans).n(2)
2.1e+121
>>> (f/f.diff(x)).subs(x, ans).n(2)
7.4e-15
One might safely skip the verification if bounds of the root are known
and a bisection method is used:
>>> bounds = lambda i: (3.14*i, 3.14*(i + 1))
>>> nsolve(f, bounds(100), solver='bisect', verify=False)
315.730061685774
Alternatively, a function may be better behaved when the
denominator is ignored. Since this is not always the case, however,
the decision of what function to use is left to the discretion of
the user.
>>> eq = x**2/(1 - x)/(1 - 2*x)**2 - 100
>>> nsolve(eq, 0.46)
Traceback (most recent call last):
...
ValueError: Could not find root within given tolerance. (10000 > 2.1684e-19)
Try another starting point or tweak arguments.
>>> nsolve(eq.as_numer_denom()[0], 0.46)
0.46792545969349058
"""
# there are several other SymPy functions that use method= so
# guard against that here
if 'method' in kwargs:
raise ValueError(filldedent('''
Keyword "method" should not be used in this context. When using
some mpmath solvers directly, the keyword "method" is
used, but when using nsolve (and findroot) the keyword to use is
"solver".'''))
if 'prec' in kwargs:
import mpmath
mpmath.mp.dps = kwargs.pop('prec')
# keyword argument to return result as a dictionary
as_dict = dict
from builtins import dict # to unhide the builtin
# interpret arguments
if len(args) == 3:
f = args[0]
fargs = args[1]
x0 = args[2]
if iterable(fargs) and iterable(x0):
if len(x0) != len(fargs):
raise TypeError('nsolve expected exactly %i guess vectors, got %i'
% (len(fargs), len(x0)))
elif len(args) == 2:
f = args[0]
fargs = None
x0 = args[1]
if iterable(f):
raise TypeError('nsolve expected 3 arguments, got 2')
elif len(args) < 2:
raise TypeError('nsolve expected at least 2 arguments, got %i'
% len(args))
else:
raise TypeError('nsolve expected at most 3 arguments, got %i'
% len(args))
modules = kwargs.get('modules', ['mpmath'])
if iterable(f):
f = list(f)
for i, fi in enumerate(f):
if isinstance(fi, Eq):
f[i] = fi.lhs - fi.rhs
f = Matrix(f).T
if iterable(x0):
x0 = list(x0)
if not isinstance(f, Matrix):
# assume it's a SymPy expression
if isinstance(f, Eq):
f = f.lhs - f.rhs
syms = f.free_symbols
if fargs is None:
fargs = syms.copy().pop()
if not (len(syms) == 1 and (fargs in syms or fargs[0] in syms)):
raise ValueError(filldedent('''
expected a one-dimensional and numerical function'''))
# the function is much better behaved if there is no denominator
# but sending the numerator is left to the user since sometimes
# the function is better behaved when the denominator is present
# e.g., issue 11768
f = lambdify(fargs, f, modules)
x = sympify(findroot(f, x0, **kwargs))
if as_dict:
return [{fargs: x}]
return x
if len(fargs) > f.cols:
raise NotImplementedError(filldedent('''
need at least as many equations as variables'''))
verbose = kwargs.get('verbose', False)
if verbose:
print('f(x):')
print(f)
# derive Jacobian
J = f.jacobian(fargs)
if verbose:
print('J(x):')
print(J)
# create functions
f = lambdify(fargs, f.T, modules)
J = lambdify(fargs, J, modules)
# solve the system numerically
x = findroot(f, x0, J=J, **kwargs)
if as_dict:
return [dict(zip(fargs, [sympify(xi) for xi in x]))]
return Matrix(x)
def _invert(eq, *symbols, **kwargs):
"""
Return tuple (i, d) where ``i`` is independent of *symbols* and ``d``
contains symbols.
Explanation
===========
``i`` and ``d`` are obtained after recursively using algebraic inversion
until an uninvertible ``d`` remains. If there are no free symbols then
``d`` will be zero. Some (but not necessarily all) solutions to the
expression ``i - d`` will be related to the solutions of the original
expression.
Examples
========
>>> from sympy.solvers.solvers import _invert as invert
>>> from sympy import sqrt, cos
>>> from sympy.abc import x, y
>>> invert(x - 3)
(3, x)
>>> invert(3)
(3, 0)
>>> invert(2*cos(x) - 1)
(1/2, cos(x))
>>> invert(sqrt(x) - 3)
(3, sqrt(x))
>>> invert(sqrt(x) + y, x)
(-y, sqrt(x))
>>> invert(sqrt(x) + y, y)
(-sqrt(x), y)
>>> invert(sqrt(x) + y, x, y)
(0, sqrt(x) + y)
If there is more than one symbol in a power's base and the exponent
is not an Integer, then the principal root will be used for the
inversion:
>>> invert(sqrt(x + y) - 2)
(4, x + y)
>>> invert(sqrt(x + y) - 2)
(4, x + y)
If the exponent is an Integer, setting ``integer_power`` to True
will force the principal root to be selected:
>>> invert(x**2 - 4, integer_power=True)
(2, x)
"""
eq = sympify(eq)
if eq.args:
# make sure we are working with flat eq
eq = eq.func(*eq.args)
free = eq.free_symbols
if not symbols:
symbols = free
if not free & set(symbols):
return eq, S.Zero
dointpow = bool(kwargs.get('integer_power', False))
lhs = eq
rhs = S.Zero
while True:
was = lhs
while True:
indep, dep = lhs.as_independent(*symbols)
# dep + indep == rhs
if lhs.is_Add:
# this indicates we have done it all
if indep.is_zero:
break
lhs = dep
rhs -= indep
# dep * indep == rhs
else:
# this indicates we have done it all
if indep is S.One:
break
lhs = dep
rhs /= indep
# collect like-terms in symbols
if lhs.is_Add:
terms = {}
for a in lhs.args:
i, d = a.as_independent(*symbols)
terms.setdefault(d, []).append(i)
if any(len(v) > 1 for v in terms.values()):
args = []
for d, i in terms.items():
if len(i) > 1:
args.append(Add(*i)*d)
else:
args.append(i[0]*d)
lhs = Add(*args)
# if it's a two-term Add with rhs = 0 and two powers we can get the
# dependent terms together, e.g. 3*f(x) + 2*g(x) -> f(x)/g(x) = -2/3
if lhs.is_Add and not rhs and len(lhs.args) == 2 and \
not lhs.is_polynomial(*symbols):
a, b = ordered(lhs.args)
ai, ad = a.as_independent(*symbols)
bi, bd = b.as_independent(*symbols)
if any(_ispow(i) for i in (ad, bd)):
a_base, a_exp = ad.as_base_exp()
b_base, b_exp = bd.as_base_exp()
if a_base == b_base:
# a = -b
lhs = powsimp(powdenest(ad/bd))
rhs = -bi/ai
else:
rat = ad/bd
_lhs = powsimp(ad/bd)
if _lhs != rat:
lhs = _lhs
rhs = -bi/ai
elif ai == -bi:
if isinstance(ad, Function) and ad.func == bd.func:
if len(ad.args) == len(bd.args) == 1:
lhs = ad.args[0] - bd.args[0]
elif len(ad.args) == len(bd.args):
# should be able to solve
# f(x, y) - f(2 - x, 0) == 0 -> x == 1
raise NotImplementedError(
'equal function with more than 1 argument')
else:
raise ValueError(
'function with different numbers of args')
elif lhs.is_Mul and any(_ispow(a) for a in lhs.args):
lhs = powsimp(powdenest(lhs))
if lhs.is_Function:
if hasattr(lhs, 'inverse') and lhs.inverse() is not None and len(lhs.args) == 1:
# -1
# f(x) = g -> x = f (g)
#
# /!\ inverse should not be defined if there are multiple values
# for the function -- these are handled in _tsolve
#
rhs = lhs.inverse()(rhs)
lhs = lhs.args[0]
elif isinstance(lhs, atan2):
y, x = lhs.args
lhs = 2*atan(y/(sqrt(x**2 + y**2) + x))
elif lhs.func == rhs.func:
if len(lhs.args) == len(rhs.args) == 1:
lhs = lhs.args[0]
rhs = rhs.args[0]
elif len(lhs.args) == len(rhs.args):
# should be able to solve
# f(x, y) == f(2, 3) -> x == 2
# f(x, x + y) == f(2, 3) -> x == 2
raise NotImplementedError(
'equal function with more than 1 argument')
else:
raise ValueError(
'function with different numbers of args')
if rhs and lhs.is_Pow and lhs.exp.is_Integer and lhs.exp < 0:
lhs = 1/lhs
rhs = 1/rhs
# base**a = b -> base = b**(1/a) if
# a is an Integer and dointpow=True (this gives real branch of root)
# a is not an Integer and the equation is multivariate and the
# base has more than 1 symbol in it
# The rationale for this is that right now the multi-system solvers
# doesn't try to resolve generators to see, for example, if the whole
# system is written in terms of sqrt(x + y) so it will just fail, so we
# do that step here.
if lhs.is_Pow and (
lhs.exp.is_Integer and dointpow or not lhs.exp.is_Integer and
len(symbols) > 1 and len(lhs.base.free_symbols & set(symbols)) > 1):
rhs = rhs**(1/lhs.exp)
lhs = lhs.base
if lhs == was:
break
return rhs, lhs
def unrad(eq, *syms, **flags):
"""
Remove radicals with symbolic arguments and return (eq, cov),
None, or raise an error.
Explanation
===========
None is returned if there are no radicals to remove.
NotImplementedError is raised if there are radicals and they cannot be
removed or if the relationship between the original symbols and the
change of variable needed to rewrite the system as a polynomial cannot
be solved.
Otherwise the tuple, ``(eq, cov)``, is returned where:
*eq*, ``cov``
*eq* is an equation without radicals (in the symbol(s) of
interest) whose solutions are a superset of the solutions to the
original expression. *eq* might be rewritten in terms of a new
variable; the relationship to the original variables is given by
``cov`` which is a list containing ``v`` and ``v**p - b`` where
``p`` is the power needed to clear the radical and ``b`` is the
radical now expressed as a polynomial in the symbols of interest.
For example, for sqrt(2 - x) the tuple would be
``(c, c**2 - 2 + x)``. The solutions of *eq* will contain
solutions to the original equation (if there are any).
*syms*
An iterable of symbols which, if provided, will limit the focus of
radical removal: only radicals with one or more of the symbols of
interest will be cleared. All free symbols are used if *syms* is not
set.
*flags* are used internally for communication during recursive calls.
Two options are also recognized:
``take``, when defined, is interpreted as a single-argument function
that returns True if a given Pow should be handled.
Radicals can be removed from an expression if:
* All bases of the radicals are the same; a change of variables is
done in this case.
* If all radicals appear in one term of the expression.
* There are only four terms with sqrt() factors or there are less than
four terms having sqrt() factors.
* There are only two terms with radicals.
Examples
========
>>> from sympy.solvers.solvers import unrad
>>> from sympy.abc import x
>>> from sympy import sqrt, Rational, root
>>> unrad(sqrt(x)*x**Rational(1, 3) + 2)
(x**5 - 64, [])
>>> unrad(sqrt(x) + root(x + 1, 3))
(-x**3 + x**2 + 2*x + 1, [])
>>> eq = sqrt(x) + root(x, 3) - 2
>>> unrad(eq)
(_p**3 + _p**2 - 2, [_p, _p**6 - x])
"""
uflags = dict(check=False, simplify=False)
def _cov(p, e):
if cov:
# XXX - uncovered
oldp, olde = cov
if Poly(e, p).degree(p) in (1, 2):
cov[:] = [p, olde.subs(oldp, _solve(e, p, **uflags)[0])]
else:
raise NotImplementedError
else:
cov[:] = [p, e]
def _canonical(eq, cov):
if cov:
# change symbol to vanilla so no solutions are eliminated
p, e = cov
rep = {p: Dummy(p.name)}
eq = eq.xreplace(rep)
cov = [p.xreplace(rep), e.xreplace(rep)]
# remove constants and powers of factors since these don't change
# the location of the root; XXX should factor or factor_terms be used?
eq = factor_terms(_mexpand(eq.as_numer_denom()[0], recursive=True), clear=True)
if eq.is_Mul:
args = []
for f in eq.args:
if f.is_number:
continue
if f.is_Pow:
args.append(f.base)
else:
args.append(f)
eq = Mul(*args) # leave as Mul for more efficient solving
# make the sign canonical
margs = list(Mul.make_args(eq))
changed = False
for i, m in enumerate(margs):
if m.could_extract_minus_sign():
margs[i] = -m
changed = True
if changed:
eq = Mul(*margs, evaluate=False)
return eq, cov
def _Q(pow):
# return leading Rational of denominator of Pow's exponent
c = pow.as_base_exp()[1].as_coeff_Mul()[0]
if not c.is_Rational:
return S.One
return c.q
# define the _take method that will determine whether a term is of interest
def _take(d):
# return True if coefficient of any factor's exponent's den is not 1
for pow in Mul.make_args(d):
if not pow.is_Pow:
continue
if _Q(pow) == 1:
continue
if pow.free_symbols & syms:
return True
return False
_take = flags.setdefault('_take', _take)
if isinstance(eq, Eq):
eq = eq.lhs - eq.rhs # XXX legacy Eq as Eqn support
elif not isinstance(eq, Expr):
return
cov, nwas, rpt = [flags.setdefault(k, v) for k, v in
sorted(dict(cov=[], n=None, rpt=0).items())]
# preconditioning
eq = powdenest(factor_terms(eq, radical=True, clear=True))
eq = eq.as_numer_denom()[0]
eq = _mexpand(eq, recursive=True)
if eq.is_number:
return
# see if there are radicals in symbols of interest
syms = set(syms) or eq.free_symbols # _take uses this
poly = eq.as_poly()
gens = [g for g in poly.gens if _take(g)]
if not gens:
return
# recast poly in terms of eigen-gens
poly = eq.as_poly(*gens)
# - an exponent has a symbol of interest (don't handle)
if any(g.exp.has(*syms) for g in gens):
return
def _rads_bases_lcm(poly):
# if all the bases are the same or all the radicals are in one
# term, `lcm` will be the lcm of the denominators of the
# exponents of the radicals
lcm = 1
rads = set()
bases = set()
for g in poly.gens:
q = _Q(g)
if q != 1:
rads.add(g)
lcm = ilcm(lcm, q)
bases.add(g.base)
return rads, bases, lcm
rads, bases, lcm = _rads_bases_lcm(poly)
covsym = Dummy('p', nonnegative=True)
# only keep in syms symbols that actually appear in radicals;
# and update gens
newsyms = set()
for r in rads:
newsyms.update(syms & r.free_symbols)
if newsyms != syms:
syms = newsyms
# get terms together that have common generators
drad = dict(list(zip(rads, list(range(len(rads))))))
rterms = {(): []}
args = Add.make_args(poly.as_expr())
for t in args:
if _take(t):
common = set(t.as_poly().gens).intersection(rads)
key = tuple(sorted([drad[i] for i in common]))
else:
key = ()
rterms.setdefault(key, []).append(t)
others = Add(*rterms.pop(()))
rterms = [Add(*rterms[k]) for k in rterms.keys()]
# the output will depend on the order terms are processed, so
# make it canonical quickly
rterms = list(reversed(list(ordered(rterms))))
ok = False # we don't have a solution yet
depth = sqrt_depth(eq)
if len(rterms) == 1 and not (rterms[0].is_Add and lcm > 2):
eq = rterms[0]**lcm - ((-others)**lcm)
ok = True
else:
if len(rterms) == 1 and rterms[0].is_Add:
rterms = list(rterms[0].args)
if len(bases) == 1:
b = bases.pop()
if len(syms) > 1:
x = b.free_symbols
else:
x = syms
x = list(ordered(x))[0]
try:
inv = _solve(covsym**lcm - b, x, **uflags)
if not inv:
raise NotImplementedError
eq = poly.as_expr().subs(b, covsym**lcm).subs(x, inv[0])
_cov(covsym, covsym**lcm - b)
return _canonical(eq, cov)
except NotImplementedError:
pass
if len(rterms) == 2:
if not others:
eq = rterms[0]**lcm - (-rterms[1])**lcm
ok = True
elif not log(lcm, 2).is_Integer:
# the lcm-is-power-of-two case is handled below
r0, r1 = rterms
if flags.get('_reverse', False):
r1, r0 = r0, r1
i0 = _rads0, _bases0, lcm0 = _rads_bases_lcm(r0.as_poly())
i1 = _rads1, _bases1, lcm1 = _rads_bases_lcm(r1.as_poly())
for reverse in range(2):
if reverse:
i0, i1 = i1, i0
r0, r1 = r1, r0
_rads1, _, lcm1 = i1
_rads1 = Mul(*_rads1)
t1 = _rads1**lcm1
c = covsym**lcm1 - t1
for x in syms:
try:
sol = _solve(c, x, **uflags)
if not sol:
raise NotImplementedError
neweq = r0.subs(x, sol[0]) + covsym*r1/_rads1 + \
others
tmp = unrad(neweq, covsym)
if tmp:
eq, newcov = tmp
if newcov:
newp, newc = newcov
_cov(newp, c.subs(covsym,
_solve(newc, covsym, **uflags)[0]))
else:
_cov(covsym, c)
else:
eq = neweq
_cov(covsym, c)
ok = True
break
except NotImplementedError:
if reverse:
raise NotImplementedError(
'no successful change of variable found')
else:
pass
if ok:
break
elif len(rterms) == 3:
# two cube roots and another with order less than 5
# (so an analytical solution can be found) or a base
# that matches one of the cube root bases
info = [_rads_bases_lcm(i.as_poly()) for i in rterms]
RAD = 0
BASES = 1
LCM = 2
if info[0][LCM] != 3:
info.append(info.pop(0))
rterms.append(rterms.pop(0))
elif info[1][LCM] != 3:
info.append(info.pop(1))
rterms.append(rterms.pop(1))
if info[0][LCM] == info[1][LCM] == 3:
if info[1][BASES] != info[2][BASES]:
info[0], info[1] = info[1], info[0]
rterms[0], rterms[1] = rterms[1], rterms[0]
if info[1][BASES] == info[2][BASES]:
eq = rterms[0]**3 + (rterms[1] + rterms[2] + others)**3
ok = True
elif info[2][LCM] < 5:
# a*root(A, 3) + b*root(B, 3) + others = c
a, b, c, d, A, B = [Dummy(i) for i in 'abcdAB']
# zz represents the unraded expression into which the
# specifics for this case are substituted
zz = (c - d)*(A**3*a**9 + 3*A**2*B*a**6*b**3 -
3*A**2*a**6*c**3 + 9*A**2*a**6*c**2*d - 9*A**2*a**6*c*d**2 +
3*A**2*a**6*d**3 + 3*A*B**2*a**3*b**6 + 21*A*B*a**3*b**3*c**3 -
63*A*B*a**3*b**3*c**2*d + 63*A*B*a**3*b**3*c*d**2 -
21*A*B*a**3*b**3*d**3 + 3*A*a**3*c**6 - 18*A*a**3*c**5*d +
45*A*a**3*c**4*d**2 - 60*A*a**3*c**3*d**3 + 45*A*a**3*c**2*d**4 -
18*A*a**3*c*d**5 + 3*A*a**3*d**6 + B**3*b**9 - 3*B**2*b**6*c**3 +
9*B**2*b**6*c**2*d - 9*B**2*b**6*c*d**2 + 3*B**2*b**6*d**3 +
3*B*b**3*c**6 - 18*B*b**3*c**5*d + 45*B*b**3*c**4*d**2 -
60*B*b**3*c**3*d**3 + 45*B*b**3*c**2*d**4 - 18*B*b**3*c*d**5 +
3*B*b**3*d**6 - c**9 + 9*c**8*d - 36*c**7*d**2 + 84*c**6*d**3 -
126*c**5*d**4 + 126*c**4*d**5 - 84*c**3*d**6 + 36*c**2*d**7 -
9*c*d**8 + d**9)
def _t(i):
b = Mul(*info[i][RAD])
return cancel(rterms[i]/b), Mul(*info[i][BASES])
aa, AA = _t(0)
bb, BB = _t(1)
cc = -rterms[2]
dd = others
eq = zz.xreplace(dict(zip(
(a, A, b, B, c, d),
(aa, AA, bb, BB, cc, dd))))
ok = True
# handle power-of-2 cases
if not ok:
if log(lcm, 2).is_Integer and (not others and
len(rterms) == 4 or len(rterms) < 4):
def _norm2(a, b):
return a**2 + b**2 + 2*a*b
if len(rterms) == 4:
# (r0+r1)**2 - (r2+r3)**2
r0, r1, r2, r3 = rterms
eq = _norm2(r0, r1) - _norm2(r2, r3)
ok = True
elif len(rterms) == 3:
# (r1+r2)**2 - (r0+others)**2
r0, r1, r2 = rterms
eq = _norm2(r1, r2) - _norm2(r0, others)
ok = True
elif len(rterms) == 2:
# r0**2 - (r1+others)**2
r0, r1 = rterms
eq = r0**2 - _norm2(r1, others)
ok = True
new_depth = sqrt_depth(eq) if ok else depth
rpt += 1 # XXX how many repeats with others unchanging is enough?
if not ok or (
nwas is not None and len(rterms) == nwas and
new_depth is not None and new_depth == depth and
rpt > 3):
raise NotImplementedError('Cannot remove all radicals')
flags.update(dict(cov=cov, n=len(rterms), rpt=rpt))
neq = unrad(eq, *syms, **flags)
if neq:
eq, cov = neq
eq, cov = _canonical(eq, cov)
return eq, cov
# Delayed imports
from sympy.solvers.bivariate import (
bivariate_type, _solve_lambert, _filtered_gens)
|
c4b92583c639b38d237bab17c262e61bd8b2622f58124f4aa314d2173d46b5d2 | from sympy.core import Atom, Basic
class CartanType_generator():
"""
Constructor for actually creating things
"""
def __call__(self, *args):
c = args[0]
if isinstance(c, list):
letter, n = c[0], int(c[1])
elif isinstance(c, str):
letter, n = c[0], int(c[1:])
else:
raise TypeError("Argument must be a string (e.g. 'A3') or a list (e.g. ['A', 3])")
if n < 0:
raise ValueError("Lie algebra rank cannot be negative")
if letter == "A":
from . import type_a
return type_a.TypeA(n)
if letter == "B":
from . import type_b
return type_b.TypeB(n)
if letter == "C":
from . import type_c
return type_c.TypeC(n)
if letter == "D":
from . import type_d
return type_d.TypeD(n)
if letter == "E":
if n >= 6 and n <= 8:
from . import type_e
return type_e.TypeE(n)
if letter == "F":
if n == 4:
from . import type_f
return type_f.TypeF(n)
if letter == "G":
if n == 2:
from . import type_g
return type_g.TypeG(n)
CartanType = CartanType_generator()
class Standard_Cartan(Atom):
"""
Concrete base class for Cartan types such as A4, etc
"""
def __new__(cls, series, n):
obj = Basic.__new__(cls)
obj.n = n
obj.series = series
return obj
def rank(self):
"""
Returns the rank of the Lie algebra
"""
return self.n
def series(self):
"""
Returns the type of the Lie algebra
"""
return self.series
|
2160dceaa3db11c5b24e6f5033a57cbd202cfb93ad18d8a38a6ca4a16cf70a57 | """Calculus-related methods."""
from .euler import euler_equations
from .singularities import (singularities, is_increasing,
is_strictly_increasing, is_decreasing,
is_strictly_decreasing, is_monotonic)
from .finite_diff import finite_diff_weights, apply_finite_diff, differentiate_finite
from .util import (periodicity, not_empty_in, is_convex,
stationary_points, minimum, maximum)
from .accumulationbounds import AccumBounds
__all__ = [
'euler_equations',
'singularities', 'is_increasing',
'is_strictly_increasing', 'is_decreasing',
'is_strictly_decreasing', 'is_monotonic',
'finite_diff_weights', 'apply_finite_diff', 'differentiate_finite',
'periodicity', 'not_empty_in', 'is_convex', 'stationary_points',
'minimum', 'maximum',
'AccumBounds'
]
|
414b43b603b7b3aa319181ac5e726d38fb5461793fbaa91088d59f0a6a7d19ce | from sympy.core import Add, Mul, Pow, S
from sympy.core.basic import Basic
from sympy.core.expr import Expr
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.multipledispatch import dispatch
from sympy.series.order import Order
from sympy.sets.sets import FiniteSet
class AccumulationBounds(Expr):
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 \le 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 \rightarrow -\infty`, so `-\infty`
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 \times Y = \{ x \times 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: `\left\langle a, b\right\rangle^2` is not same as `\left\langle a, b\right\rangle \times \left\langle a, b\right\rangle`
>>> 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 `\left\langle a, b \right\rangle`
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 does not 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
is_number = False
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 a in self.args:
vi = other*a
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 in (S.Infinity, 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 in (S.Infinity, 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 :py:class:`~.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))
{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 ``lhs`` AccumulationBounds
object is greater than the range of values attained by ``rhs``,
where ``rhs`` may be any value of type AccumulationBounds object or
extended real number value, ``False`` if ``rhs`` satisfies
the same property, else an unevaluated :py:class:`~.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 :py:class:`~.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
|
1c965d269b9bae194dc43a42a7361fc492af266b27ac1eac2e8c7c915e6a8d11 | """
Finite difference weights
=========================
This module implements an algorithm for efficient generation of finite
difference weights for ordinary differentials of functions for
derivatives from 0 (interpolation) up to arbitrary order.
The core algorithm is provided in the finite difference weight generating
function (``finite_diff_weights``), and two convenience functions are provided
for:
- estimating a derivative (or interpolate) directly from a series of points
is also provided (``apply_finite_diff``).
- differentiating by using finite difference approximations
(``differentiate_finite``).
"""
from sympy.core.function import Derivative
from sympy.core.singleton import S
from sympy.core.function import Subs
from sympy.core.traversal import preorder_traversal
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.iterables import iterable
def finite_diff_weights(order, x_list, x0=S.One):
"""
Calculates the finite difference weights for an arbitrarily spaced
one-dimensional grid (``x_list``) for derivatives at ``x0`` of order
0, 1, ..., up to ``order`` using a recursive formula. Order of accuracy
is at least ``len(x_list) - order``, if ``x_list`` is defined correctly.
Parameters
==========
order: int
Up to what derivative order weights should be calculated.
0 corresponds to interpolation.
x_list: sequence
Sequence of (unique) values for the independent variable.
It is useful (but not necessary) to order ``x_list`` from
nearest to furthest from ``x0``; see examples below.
x0: Number or Symbol
Root or value of the independent variable for which the finite
difference weights should be generated. Default is ``S.One``.
Returns
=======
list
A list of sublists, each corresponding to coefficients for
increasing derivative order, and each containing lists of
coefficients for increasing subsets of x_list.
Examples
========
>>> from sympy import finite_diff_weights, S
>>> res = finite_diff_weights(1, [-S(1)/2, S(1)/2, S(3)/2, S(5)/2], 0)
>>> res
[[[1, 0, 0, 0],
[1/2, 1/2, 0, 0],
[3/8, 3/4, -1/8, 0],
[5/16, 15/16, -5/16, 1/16]],
[[0, 0, 0, 0],
[-1, 1, 0, 0],
[-1, 1, 0, 0],
[-23/24, 7/8, 1/8, -1/24]]]
>>> res[0][-1] # FD weights for 0th derivative, using full x_list
[5/16, 15/16, -5/16, 1/16]
>>> res[1][-1] # FD weights for 1st derivative
[-23/24, 7/8, 1/8, -1/24]
>>> res[1][-2] # FD weights for 1st derivative, using x_list[:-1]
[-1, 1, 0, 0]
>>> res[1][-1][0] # FD weight for 1st deriv. for x_list[0]
-23/24
>>> res[1][-1][1] # FD weight for 1st deriv. for x_list[1], etc.
7/8
Each sublist contains the most accurate formula at the end.
Note, that in the above example ``res[1][1]`` is the same as ``res[1][2]``.
Since res[1][2] has an order of accuracy of
``len(x_list[:3]) - order = 3 - 1 = 2``, the same is true for ``res[1][1]``!
>>> res = finite_diff_weights(1, [S(0), S(1), -S(1), S(2), -S(2)], 0)[1]
>>> res
[[0, 0, 0, 0, 0],
[-1, 1, 0, 0, 0],
[0, 1/2, -1/2, 0, 0],
[-1/2, 1, -1/3, -1/6, 0],
[0, 2/3, -2/3, -1/12, 1/12]]
>>> res[0] # no approximation possible, using x_list[0] only
[0, 0, 0, 0, 0]
>>> res[1] # classic forward step approximation
[-1, 1, 0, 0, 0]
>>> res[2] # classic centered approximation
[0, 1/2, -1/2, 0, 0]
>>> res[3:] # higher order approximations
[[-1/2, 1, -1/3, -1/6, 0], [0, 2/3, -2/3, -1/12, 1/12]]
Let us compare this to a differently defined ``x_list``. Pay attention to
``foo[i][k]`` corresponding to the gridpoint defined by ``x_list[k]``.
>>> foo = finite_diff_weights(1, [-S(2), -S(1), S(0), S(1), S(2)], 0)[1]
>>> foo
[[0, 0, 0, 0, 0],
[-1, 1, 0, 0, 0],
[1/2, -2, 3/2, 0, 0],
[1/6, -1, 1/2, 1/3, 0],
[1/12, -2/3, 0, 2/3, -1/12]]
>>> foo[1] # not the same and of lower accuracy as res[1]!
[-1, 1, 0, 0, 0]
>>> foo[2] # classic double backward step approximation
[1/2, -2, 3/2, 0, 0]
>>> foo[4] # the same as res[4]
[1/12, -2/3, 0, 2/3, -1/12]
Note that, unless you plan on using approximations based on subsets of
``x_list``, the order of gridpoints does not matter.
The capability to generate weights at arbitrary points can be
used e.g. to minimize Runge's phenomenon by using Chebyshev nodes:
>>> from sympy import cos, symbols, pi, simplify
>>> N, (h, x) = 4, symbols('h x')
>>> x_list = [x+h*cos(i*pi/(N)) for i in range(N,-1,-1)] # chebyshev nodes
>>> print(x_list)
[-h + x, -sqrt(2)*h/2 + x, x, sqrt(2)*h/2 + x, h + x]
>>> mycoeffs = finite_diff_weights(1, x_list, 0)[1][4]
>>> [simplify(c) for c in mycoeffs] #doctest: +NORMALIZE_WHITESPACE
[(h**3/2 + h**2*x - 3*h*x**2 - 4*x**3)/h**4,
(-sqrt(2)*h**3 - 4*h**2*x + 3*sqrt(2)*h*x**2 + 8*x**3)/h**4,
(6*h**2*x - 8*x**3)/h**4,
(sqrt(2)*h**3 - 4*h**2*x - 3*sqrt(2)*h*x**2 + 8*x**3)/h**4,
(-h**3/2 + h**2*x + 3*h*x**2 - 4*x**3)/h**4]
Notes
=====
If weights for a finite difference approximation of 3rd order
derivative is wanted, weights for 0th, 1st and 2nd order are
calculated "for free", so are formulae using subsets of ``x_list``.
This is something one can take advantage of to save computational cost.
Be aware that one should define ``x_list`` from nearest to furthest from
``x0``. If not, subsets of ``x_list`` will yield poorer approximations,
which might not grand an order of accuracy of ``len(x_list) - order``.
See also
========
sympy.calculus.finite_diff.apply_finite_diff
References
==========
.. [1] Generation of Finite Difference Formulas on Arbitrarily Spaced
Grids, Bengt Fornberg; Mathematics of computation; 51; 184;
(1988); 699-706; doi:10.1090/S0025-5718-1988-0935077-0
"""
# The notation below closely corresponds to the one used in the paper.
order = S(order)
if not order.is_number:
raise ValueError("Cannot handle symbolic order.")
if order < 0:
raise ValueError("Negative derivative order illegal.")
if int(order) != order:
raise ValueError("Non-integer order illegal")
M = order
N = len(x_list) - 1
delta = [[[0 for nu in range(N+1)] for n in range(N+1)] for
m in range(M+1)]
delta[0][0][0] = S.One
c1 = S.One
for n in range(1, N+1):
c2 = S.One
for nu in range(0, n):
c3 = x_list[n]-x_list[nu]
c2 = c2 * c3
if n <= M:
delta[n][n-1][nu] = 0
for m in range(0, min(n, M)+1):
delta[m][n][nu] = (x_list[n]-x0)*delta[m][n-1][nu] -\
m*delta[m-1][n-1][nu]
delta[m][n][nu] /= c3
for m in range(0, min(n, M)+1):
delta[m][n][n] = c1/c2*(m*delta[m-1][n-1][n-1] -
(x_list[n-1]-x0)*delta[m][n-1][n-1])
c1 = c2
return delta
def apply_finite_diff(order, x_list, y_list, x0=S.Zero):
"""
Calculates the finite difference approximation of
the derivative of requested order at ``x0`` from points
provided in ``x_list`` and ``y_list``.
Parameters
==========
order: int
order of derivative to approximate. 0 corresponds to interpolation.
x_list: sequence
Sequence of (unique) values for the independent variable.
y_list: sequence
The function value at corresponding values for the independent
variable in x_list.
x0: Number or Symbol
At what value of the independent variable the derivative should be
evaluated. Defaults to 0.
Returns
=======
sympy.core.add.Add or sympy.core.numbers.Number
The finite difference expression approximating the requested
derivative order at ``x0``.
Examples
========
>>> from sympy import apply_finite_diff
>>> cube = lambda arg: (1.0*arg)**3
>>> xlist = range(-3,3+1)
>>> apply_finite_diff(2, xlist, map(cube, xlist), 2) - 12 # doctest: +SKIP
-3.55271367880050e-15
we see that the example above only contain rounding errors.
apply_finite_diff can also be used on more abstract objects:
>>> from sympy import IndexedBase, Idx
>>> x, y = map(IndexedBase, 'xy')
>>> i = Idx('i')
>>> x_list, y_list = zip(*[(x[i+j], y[i+j]) for j in range(-1,2)])
>>> apply_finite_diff(1, x_list, y_list, x[i])
((x[i + 1] - x[i])/(-x[i - 1] + x[i]) - 1)*y[i]/(x[i + 1] - x[i]) -
(x[i + 1] - x[i])*y[i - 1]/((x[i + 1] - x[i - 1])*(-x[i - 1] + x[i])) +
(-x[i - 1] + x[i])*y[i + 1]/((x[i + 1] - x[i - 1])*(x[i + 1] - x[i]))
Notes
=====
Order = 0 corresponds to interpolation.
Only supply so many points you think makes sense
to around x0 when extracting the derivative (the function
need to be well behaved within that region). Also beware
of Runge's phenomenon.
See also
========
sympy.calculus.finite_diff.finite_diff_weights
References
==========
Fortran 90 implementation with Python interface for numerics: finitediff_
.. _finitediff: https://github.com/bjodah/finitediff
"""
# In the original paper the following holds for the notation:
# M = order
# N = len(x_list) - 1
N = len(x_list) - 1
if len(x_list) != len(y_list):
raise ValueError("x_list and y_list not equal in length.")
delta = finite_diff_weights(order, x_list, x0)
derivative = 0
for nu in range(0, len(x_list)):
derivative += delta[order][N][nu]*y_list[nu]
return derivative
def _as_finite_diff(derivative, points=1, x0=None, wrt=None):
"""
Returns an approximation of a derivative of a function in
the form of a finite difference formula. The expression is a
weighted sum of the function at a number of discrete values of
(one of) the independent variable(s).
Parameters
==========
derivative: a Derivative instance
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
>>> from sympy.calculus.finite_diff import _as_finite_diff
>>> x, h = symbols('x h')
>>> f = Function('f')
>>> _as_finite_diff(f(x).diff(x))
-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:
>>> _as_finite_diff(f(x).diff(x), h)
-f(-h/2 + x)/h + f(h/2 + x)/h
We can also specify the discretized values to be used in a sequence:
>>> _as_finite_diff(f(x).diff(x), [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]
>>> _as_finite_diff(f(x).diff(x, 1), xl, x+h*sq2)
2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/((-h + E*h)*(h + E*h)) +
(-(-sqrt(2)*h + h)/(2*h) - (-sqrt(2)*h + E*h)/(2*h))*f(-h + x)/(h + E*h) +
(-(h + sqrt(2)*h)/(2*h) + (-sqrt(2)*h + E*h)/(2*h))*f(h + x)/(-h + E*h)
Partial derivatives are also supported:
>>> y = Symbol('y')
>>> d2fdxdy=f(x,y).diff(x,y)
>>> _as_finite_diff(d2fdxdy, wrt=x)
-Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y)
See also
========
sympy.calculus.finite_diff.apply_finite_diff
sympy.calculus.finite_diff.finite_diff_weights
"""
if derivative.is_Derivative:
pass
elif derivative.is_Atom:
return derivative
else:
return derivative.fromiter(
[_as_finite_diff(ar, points, x0, wrt) for ar
in derivative.args], **derivative.assumptions0)
if wrt is None:
old = None
for v in derivative.variables:
if old is v:
continue
derivative = _as_finite_diff(derivative, points, x0, v)
old = v
return derivative
order = derivative.variables.count(wrt)
if x0 is None:
x0 = wrt
if not iterable(points):
if getattr(points, 'is_Function', False) and wrt in points.args:
points = points.subs(wrt, x0)
# points is simply the step-size, let's make it a
# equidistant sequence centered around x0
if order % 2 == 0:
# even order => odd number of points, grid point included
points = [x0 + points*i for i
in range(-order//2, order//2 + 1)]
else:
# odd order => even number of points, half-way wrt grid point
points = [x0 + points*S(i)/2 for i
in range(-order, order + 1, 2)]
others = [wrt, 0]
for v in set(derivative.variables):
if v == wrt:
continue
others += [v, derivative.variables.count(v)]
if len(points) < order+1:
raise ValueError("Too few points for order %d" % order)
return apply_finite_diff(order, points, [
Derivative(derivative.expr.subs({wrt: x}), *others) for
x in points], x0)
def differentiate_finite(expr, *symbols,
points=1, x0=None, wrt=None, evaluate=False):
r""" Differentiate expr and replace Derivatives with finite differences.
Parameters
==========
expr : expression
\*symbols : differentiate with respect to symbols
points: sequence, coefficient or undefined function, optional
see ``Derivative.as_finite_difference``
x0: number or Symbol, optional
see ``Derivative.as_finite_difference``
wrt: Symbol, optional
see ``Derivative.as_finite_difference``
Examples
========
>>> from sympy import sin, Function, differentiate_finite
>>> from sympy.abc import x, y, h
>>> f, g = Function('f'), Function('g')
>>> differentiate_finite(f(x)*g(x), x, points=[x-h, x+h])
-f(-h + x)*g(-h + x)/(2*h) + f(h + x)*g(h + x)/(2*h)
``differentiate_finite`` works on any expression, including the expressions
with embedded derivatives:
>>> differentiate_finite(f(x) + sin(x), x, 2)
-2*f(x) + f(x - 1) + f(x + 1) - 2*sin(x) + sin(x - 1) + sin(x + 1)
>>> differentiate_finite(f(x, y), x, y)
f(x - 1/2, y - 1/2) - f(x - 1/2, y + 1/2) - f(x + 1/2, y - 1/2) + f(x + 1/2, y + 1/2)
>>> differentiate_finite(f(x)*g(x).diff(x), x)
(-g(x) + g(x + 1))*f(x + 1/2) - (g(x) - g(x - 1))*f(x - 1/2)
To make finite difference with non-constant discretization step use
undefined functions:
>>> dx = Function('dx')
>>> differentiate_finite(f(x)*g(x).diff(x), points=dx(x))
-(-g(x - dx(x)/2 - dx(x - dx(x)/2)/2)/dx(x - dx(x)/2) +
g(x - dx(x)/2 + dx(x - dx(x)/2)/2)/dx(x - dx(x)/2))*f(x - dx(x)/2)/dx(x) +
(-g(x + dx(x)/2 - dx(x + dx(x)/2)/2)/dx(x + dx(x)/2) +
g(x + dx(x)/2 + dx(x + dx(x)/2)/2)/dx(x + dx(x)/2))*f(x + dx(x)/2)/dx(x)
"""
if any(term.is_Derivative for term in list(preorder_traversal(expr))):
evaluate = False
Dexpr = expr.diff(*symbols, evaluate=evaluate)
if evaluate:
sympy_deprecation_warning("""
The evaluate flag to differentiate_finite() is deprecated.
evaluate=True expands the intermediate derivatives before computing
differences, but this usually not what you want, as it does not
satisfy the product rule.
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-differentiate_finite-evaluate",
)
return Dexpr.replace(
lambda arg: arg.is_Derivative,
lambda arg: arg.as_finite_difference(points=points, x0=x0, wrt=wrt))
else:
DFexpr = Dexpr.as_finite_difference(points=points, x0=x0, wrt=wrt)
return DFexpr.replace(
lambda arg: isinstance(arg, Subs),
lambda arg: arg.expr.as_finite_difference(
points=points, x0=arg.point[0], wrt=arg.variables[0]))
|
550e18a38800cafb9a1379869cef1f07d28df2ddf00621563c7df6acce2139d9 | from .accumulationbounds import AccumBounds, AccumulationBounds # noqa: F401
from .singularities import singularities
from sympy.core import Pow, S
from sympy.core.function import diff, expand_mul
from sympy.core.kind import NumberKind
from sympy.core.mod import Mod
from sympy.core.relational import Relational
from sympy.core.symbol import Symbol, Dummy
from sympy.core.sympify import _sympify
from sympy.functions.elementary.complexes import Abs, im, re
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (
TrigonometricFunction, sin, cos, csc, sec)
from sympy.polys.polytools import degree, lcm_list
from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union,
Complement)
from sympy.sets.fancysets import ImageSet
from sympy.utilities import filldedent
from sympy.utilities.iterables import iterable
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 : :py:class:`~.Expr`
The concerned function.
symbol : :py:class:`~.Symbol`
The variable for which the intervals are to be determined.
domain : :py:class:`~.Interval`
The domain over which the continuity of the symbol has to be checked.
Examples
========
>>> from sympy import Interval, Symbol, S, tan, log, pi, sqrt
>>> 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
=======
:py:class:`~.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
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 : :py:class:`~.Expr`
The concerned function.
symbol : :py:class:`~.Symbol`
The variable for which the range of function is to be determined.
domain : :py:class:`~.Interval`
The domain under which the range of the function has to be found.
Examples
========
>>> from sympy import Interval, Symbol, S, exp, log, pi, sqrt, sin, tan
>>> 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
=======
:py:class:`~.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 cannot be found.
"""
if domain is S.EmptySet:
return S.EmptySet
period = periodicity(f, symbol)
if period == S.Zero:
# the expression is constant wrt symbol
return FiniteSet(f.expand())
from sympy.series.limits import limit
from sympy.solvers.solveset import solveset
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 ``finset_intersection`` in which the
``finite_set`` is not-empty
Parameters
==========
finset_intersection : Intersection of FiniteSet
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 : :py:class:`~.Expr`.
The concerned function.
symbol : :py:class:`~.Symbol`
The variable for which the period is to be determined.
check : bool, 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 periodicity, Symbol, sin, cos, tan, exp
>>> 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)
"""
if symbol.kind is not NumberKind:
raise NotImplementedError("Cannot use symbol of kind %s" % symbol.kind)
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 = f.simplify()
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, decompogen
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 not in (orig_f, 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 :py:class:`~.Symbol`
All the symbols present in a function.
symbol : :py:class:`~.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.calculus.util import lcim
>>> from sympy import S, pi
>>> 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):
r"""Determines the convexity of the function passed in the argument.
Parameters
==========
f : :py:class:`~.Expr`
The concerned function.
syms : Tuple of :py:class:`~.Symbol`
The variables with respect to which the convexity is to be determined.
domain : :py:class:`~.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
=======
bool
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 is_convex, symbols, exp, oo, Interval
>>> x = symbols('x')
>>> is_convex(exp(x), x)
True
>>> is_convex(x**3, x, domain = Interval(-1, oo))
False
>>> is_convex(1/x**2, x, domain=Interval.open(0, oo))
True
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.")
from sympy.solvers.inequalities import solve_univariate_inequality
f = _sympify(f)
var = syms[0]
if any(s in domain for s in singularities(f, var)):
return False
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 : :py:class:`~.Expr`
The concerned function.
symbol : :py:class:`~.Symbol`
The variable for which the stationary points are to be determined.
domain : :py:class:`~.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 :py:class:`~.EmptySet` is returned.
Examples
========
>>> from sympy import Interval, Symbol, S, sin, pi, pprint, stationary_points
>>> 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))
{pi/2, 3*pi/2, 5*pi/2, 7*pi/2}
"""
from sympy.solvers.solveset import solveset
if domain is S.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 : :py:class:`~.Expr`
The concerned function.
symbol : :py:class:`~.Symbol`
The variable for maximum value needs to be determined.
domain : :py:class:`~.Interval`
The domain over which the maximum have to be checked.
If unspecified, then the global maximum is returned.
Returns
=======
number
Maximum value of the function in given domain.
Examples
========
>>> from sympy import Interval, Symbol, S, sin, cos, pi, maximum
>>> 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
"""
if isinstance(symbol, Symbol):
if domain is S.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 : :py:class:`~.Expr`
The concerned function.
symbol : :py:class:`~.Symbol`
The variable for minimum value needs to be determined.
domain : :py:class:`~.Interval`
The domain over which the minimum have to be checked.
If unspecified, then the global minimum is returned.
Returns
=======
number
Minimum value of the function in the given domain.
Examples
========
>>> from sympy import Interval, Symbol, S, sin, cos, minimum
>>> 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
"""
if isinstance(symbol, Symbol):
if domain is S.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)
|
17d4c636da0dbd051d96de47614d3ce084cd99ceffffb3010922cbba506533f6 | """
.. deprecated:: 1.6
sympy.utilities.pytest has been renamed to sympy.testing.pytest.
"""
from sympy.utilities.exceptions import sympy_deprecation_warning
sympy_deprecation_warning("The sympy.utilities.pytest submodule is deprecated. Use sympy.testing.pytest instead.",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-sympy-utilities-submodules")
from sympy.testing.pytest import * # noqa:F401
|
f6c954c4c5d7cfe7a9b467f339dfe23c3bccc1ccd129d4df801b6d9655732c11 | """
This module adds several functions for interactive source code inspection.
"""
from sympy.utilities.decorator import deprecated
import inspect
@deprecated(
"""
The source() function is deprecated. Use inspect.getsource() instead, or
if you are in IPython or Jupyter, the ?? feature.
""",
deprecated_since_version="1.3",
active_deprecations_target="deprecated-source",
)
def source(object):
"""
Prints the source code of a given object.
.. deprecated:: 1.3
The ``source()`` function is deprecated. Use ``inspect.getsource()`` or
``??`` in IPython/Jupyter instead.
"""
print('In file: %s' % inspect.getsourcefile(object))
print(inspect.getsource(object))
def get_class(lookup_view):
"""
Convert a string version of a class name to the object.
For example, get_class('sympy.core.Basic') will return
class Basic located in module sympy.core
"""
if isinstance(lookup_view, str):
mod_name, func_name = get_mod_func(lookup_view)
if func_name != '':
lookup_view = getattr(
__import__(mod_name, {}, {}, ['*']), func_name)
if not callable(lookup_view):
raise AttributeError(
"'%s.%s' is not a callable." % (mod_name, func_name))
return lookup_view
def get_mod_func(callback):
"""
splits the string path to a class into a string path to the module
and the name of the class.
Examples
========
>>> from sympy.utilities.source import get_mod_func
>>> get_mod_func('sympy.core.basic.Basic')
('sympy.core.basic', 'Basic')
"""
dot = callback.rfind('.')
if dot == -1:
return callback, ''
return callback[:dot], callback[dot + 1:]
|
1ae249dd35553eaa5dd085e90707d1518eeb00939666d7d688710b8be6f1632d | """
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 as tDict, Iterable, Union as tUnion, TYPE_CHECKING
import builtins
import inspect
import keyword
import textwrap
import linecache
# Required despite static analysis claiming it is not used
from sympy.external import import_module # noqa:F401
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.decorator import doctest_depends_on
from sympy.utilities.iterables import (is_sequence, iterable,
NotIterable, flatten)
from sympy.utilities.misc import filldedent
if TYPE_CHECKING:
import sympy.core.expr
__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: tDict[str, Any]
MPMATH_DEFAULT = {} # type: tDict[str, Any]
NUMPY_DEFAULT = {"I": 1j} # type: tDict[str, Any]
SCIPY_DEFAULT = {"I": 1j} # type: tDict[str, Any]
CUPY_DEFAULT = {"I": 1j} # type: tDict[str, Any]
TENSORFLOW_DEFAULT = {} # type: tDict[str, Any]
SYMPY_DEFAULT = {} # type: tDict[str, Any]
NUMEXPR_DEFAULT = {} # type: tDict[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: tDict[str, str]
SCIPY_TRANSLATIONS = {} # type: tDict[str, str]
CUPY_TRANSLATIONS = {} # type: tDict[str, str]
TENSORFLOW_TRANSLATIONS = {} # type: tDict[str, str]
NUMEXPR_TRANSLATIONS = {} # type: tDict[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.
"""
try:
namespace, namespace_default, translations, import_commands = MODULES[
module]
except KeyError:
raise NameError(
"'%s' module cannot 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(
"Cannot 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', 'scipy', 'tensorflow',), python_version=(3,))
def lambdify(args: tUnion[Iterable, 'sympy.core.expr.Expr'], expr: 'sympy.core.expr.Expr', modules=None, printer=None, use_imps=True,
dummify=False, cse=False):
"""Convert a SymPy expression into a function that allows for fast
numeric evaluation.
.. warning::
This function uses ``exec``, and thus should not be used on
unsanitized input.
.. deprecated:: 1.7
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.
cse : bool, or callable, optional
Large expressions can be computed more efficiently when
common subexpressions are identified and precomputed before
being used multiple time. Finding the subexpressions will make
creation of the 'lambdify' function slower, however.
When ``True``, ``sympy.simplify.cse`` is used, otherwise (the default)
the user may pass a function matching the ``cse`` signature.
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.functions.elementary.trigonometric import (cos, sin)
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`` does not 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
from sympy.core.expr import Expr
# 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: tDict[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):
sympy_deprecation_warning(
"""
Passing the function arguments to lambdify() as a set is deprecated. This
leads to unpredictable results since sets are unordered. Instead, use a list
or tuple for the function arguments.
""",
deprecated_since_version="1.6.3",
active_deprecations_target="deprecated-lambdify-arguments-set",
)
# Get the names of the args, for creating a docstring
iterable_args: Iterable = (args,) if isinstance(args, Expr) else 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(iterable_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)
if cse == True:
from sympy.simplify.cse_main import cse as _cse
cses, _expr = _cse(expr, list=False)
elif callable(cse):
cses, _expr = cse(expr)
else:
cses, _expr = (), expr
funcstr = funcprinter.doprint(funcname, iterable_args, _expr, cses=cses)
# 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: tDict[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 _recursive_to_string(doprint, arg):
"""Functions in lambdify accept both SymPy types and non-SymPy types such as python
lists and tuples. This method ensures that we only call the doprint method of the
printer with SymPy types (so that the printer safely can use SymPy-methods)."""
from sympy.matrices.common import MatrixOperations
from sympy.core.basic import Basic
if isinstance(arg, (Basic, MatrixOperations)):
return doprint(arg)
elif iterable(arg):
if isinstance(arg, list):
left, right = "[]"
elif isinstance(arg, tuple):
left, right = "()"
else:
raise NotImplementedError("unhandled type: %s, %s" % (type(arg), arg))
return left +', '.join(_recursive_to_string(doprint, e) for e in arg) + right
elif isinstance(arg, str):
return arg
else:
return doprint(arg)
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.core.basic import Basic
from sympy.core.function import (Derivative, Function)
from sympy.core.symbol import (Dummy, Symbol)
from sympy.core.sympify import sympify
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 = _recursive_to_string(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, *, cses=()):
"""
Returns the function definition code as a string.
"""
from sympy.core.symbol 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)
for s, e in cses:
if e is None:
funcbody.append('del {}'.format(s))
else:
funcbody.append('{} = {}'.format(s, self._exprrepr(e)))
str_expr = _recursive_to_string(self._exprrepr, expr)
if '\n' in str_expr:
str_expr = '({})'.format(str_expr)
funcbody.append('return {}'.format(str_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.core.basic import Basic
from sympy.core.sorting import ordered
from sympy.core.function import (Derivative, Function)
from sympy.core.symbol import Dummy, uniquely_named_symbol
from sympy.matrices import DeferredVector
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.core.sympify 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).
"""
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 implemented_function
>>> from sympy import lambdify
>>> 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
|
5ef0a8b9cddec18c59b891e9670f8fadff6bc25bef2c6dbfa91c226878ae4d0e | """
.. deprecated:: 1.6
sympy.utilities.benchmarking has been renamed to sympy.testing.benchmarking.
"""
from sympy.utilities.exceptions import sympy_deprecation_warning
sympy_deprecation_warning("The sympy.utilities.benchmarking submodule is deprecated. Use sympy.testing.benchmarking instead.",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-sympy-utilities-submodules")
from sympy.testing.benchmarking import * # noqa:F401
|
badf3d68684fcadf0812f644edefab6b9f4d897fc9ce5cbd499196555e3da90d | """
Algorithms and classes to support enumerative combinatorics.
Currently just multiset partitions, but more could be added.
Terminology (following Knuth, algorithm 7.1.2.5M TAOCP)
*multiset* aaabbcccc has a *partition* aaabc | bccc
The submultisets, aaabc and bccc of the partition are called
*parts*, or sometimes *vectors*. (Knuth notes that multiset
partitions can be thought of as partitions of vectors of integers,
where the ith element of the vector gives the multiplicity of
element i.)
The values a, b and c are *components* of the multiset. These
correspond to elements of a set, but in a multiset can be present
with a multiplicity greater than 1.
The algorithm deserves some explanation.
Think of the part aaabc from the multiset above. If we impose an
ordering on the components of the multiset, we can represent a part
with a vector, in which the value of the first element of the vector
corresponds to the multiplicity of the first component in that
part. Thus, aaabc can be represented by the vector [3, 1, 1]. We
can also define an ordering on parts, based on the lexicographic
ordering of the vector (leftmost vector element, i.e., the element
with the smallest component number, is the most significant), so
that [3, 1, 1] > [3, 1, 0] and [3, 1, 1] > [2, 1, 4]. The ordering
on parts can be extended to an ordering on partitions: First, sort
the parts in each partition, left-to-right in decreasing order. Then
partition A is greater than partition B if A's leftmost/greatest
part is greater than B's leftmost part. If the leftmost parts are
equal, compare the second parts, and so on.
In this ordering, the greatest partition of a given multiset has only
one part. The least partition is the one in which the components
are spread out, one per part.
The enumeration algorithms in this file yield the partitions of the
argument multiset in decreasing order. The main data structure is a
stack of parts, corresponding to the current partition. An
important invariant is that the parts on the stack are themselves in
decreasing order. This data structure is decremented to find the
next smaller partition. Most often, decrementing the partition will
only involve adjustments to the smallest parts at the top of the
stack, much as adjacent integers *usually* differ only in their last
few digits.
Knuth's algorithm uses two main operations on parts:
Decrement - change the part so that it is smaller in the
(vector) lexicographic order, but reduced by the smallest amount possible.
For example, if the multiset has vector [5,
3, 1], and the bottom/greatest part is [4, 2, 1], this part would
decrement to [4, 2, 0], while [4, 0, 0] would decrement to [3, 3,
1]. A singleton part is never decremented -- [1, 0, 0] is not
decremented to [0, 3, 1]. Instead, the decrement operator needs
to fail for this case. In Knuth's pseudocode, the decrement
operator is step m5.
Spread unallocated multiplicity - Once a part has been decremented,
it cannot be the rightmost part in the partition. There is some
multiplicity that has not been allocated, and new parts must be
created above it in the stack to use up this multiplicity. To
maintain the invariant that the parts on the stack are in
decreasing order, these new parts must be less than or equal to
the decremented part.
For example, if the multiset is [5, 3, 1], and its most
significant part has just been decremented to [5, 3, 0], the
spread operation will add a new part so that the stack becomes
[[5, 3, 0], [0, 0, 1]]. If the most significant part (for the
same multiset) has been decremented to [2, 0, 0] the stack becomes
[[2, 0, 0], [2, 0, 0], [1, 3, 1]]. In the pseudocode, the spread
operation for one part is step m2. The complete spread operation
is a loop of steps m2 and m3.
In order to facilitate the spread operation, Knuth stores, for each
component of each part, not just the multiplicity of that component
in the part, but also the total multiplicity available for this
component in this part or any lesser part above it on the stack.
One added twist is that Knuth does not represent the part vectors as
arrays. Instead, he uses a sparse representation, in which a
component of a part is represented as a component number (c), plus
the multiplicity of the component in that part (v) as well as the
total multiplicity available for that component (u). This saves
time that would be spent skipping over zeros.
"""
class PartComponent:
"""Internal class used in support of the multiset partitions
enumerators and the associated visitor functions.
Represents one component of one part of the current partition.
A stack of these, plus an auxiliary frame array, f, represents a
partition of the multiset.
Knuth's pseudocode makes c, u, and v separate arrays.
"""
__slots__ = ('c', 'u', 'v')
def __init__(self):
self.c = 0 # Component number
self.u = 0 # The as yet unpartitioned amount in component c
# *before* it is allocated by this triple
self.v = 0 # Amount of c component in the current part
# (v<=u). An invariant of the representation is
# that the next higher triple for this component
# (if there is one) will have a value of u-v in
# its u attribute.
def __repr__(self):
"for debug/algorithm animation purposes"
return 'c:%d u:%d v:%d' % (self.c, self.u, self.v)
def __eq__(self, other):
"""Define value oriented equality, which is useful for testers"""
return (isinstance(other, self.__class__) and
self.c == other.c and
self.u == other.u and
self.v == other.v)
def __ne__(self, other):
"""Defined for consistency with __eq__"""
return not self == other
# This function tries to be a faithful implementation of algorithm
# 7.1.2.5M in Volume 4A, Combinatoral Algorithms, Part 1, of The Art
# of Computer Programming, by Donald Knuth. This includes using
# (mostly) the same variable names, etc. This makes for rather
# low-level Python.
# Changes from Knuth's pseudocode include
# - use PartComponent struct/object instead of 3 arrays
# - make the function a generator
# - map (with some difficulty) the GOTOs to Python control structures.
# - Knuth uses 1-based numbering for components, this code is 0-based
# - renamed variable l to lpart.
# - flag variable x takes on values True/False instead of 1/0
#
def multiset_partitions_taocp(multiplicities):
"""Enumerates partitions of a multiset.
Parameters
==========
multiplicities
list of integer multiplicities of the components of the multiset.
Yields
======
state
Internal data structure which encodes a particular partition.
This output is then usually processed by a visitor function
which combines the information from this data structure with
the components themselves to produce an actual partition.
Unless they wish to create their own visitor function, users will
have little need to look inside this data structure. But, for
reference, it is a 3-element list with components:
f
is a frame array, which is used to divide pstack into parts.
lpart
points to the base of the topmost part.
pstack
is an array of PartComponent objects.
The ``state`` output offers a peek into the internal data
structures of the enumeration function. The client should
treat this as read-only; any modification of the data
structure will cause unpredictable (and almost certainly
incorrect) results. Also, the components of ``state`` are
modified in place at each iteration. Hence, the visitor must
be called at each loop iteration. Accumulating the ``state``
instances and processing them later will not work.
Examples
========
>>> from sympy.utilities.enumerative import list_visitor
>>> from sympy.utilities.enumerative import multiset_partitions_taocp
>>> # variables components and multiplicities represent the multiset 'abb'
>>> components = 'ab'
>>> multiplicities = [1, 2]
>>> states = multiset_partitions_taocp(multiplicities)
>>> list(list_visitor(state, components) for state in states)
[[['a', 'b', 'b']],
[['a', 'b'], ['b']],
[['a'], ['b', 'b']],
[['a'], ['b'], ['b']]]
See Also
========
sympy.utilities.iterables.multiset_partitions: Takes a multiset
as input and directly yields multiset partitions. It
dispatches to a number of functions, including this one, for
implementation. Most users will find it more convenient to
use than multiset_partitions_taocp.
"""
# Important variables.
# m is the number of components, i.e., number of distinct elements
m = len(multiplicities)
# n is the cardinality, total number of elements whether or not distinct
n = sum(multiplicities)
# The main data structure, f segments pstack into parts. See
# list_visitor() for example code indicating how this internal
# state corresponds to a partition.
# Note: allocation of space for stack is conservative. Knuth's
# exercise 7.2.1.5.68 gives some indication of how to tighten this
# bound, but this is not implemented.
pstack = [PartComponent() for i in range(n * m + 1)]
f = [0] * (n + 1)
# Step M1 in Knuth (Initialize)
# Initial state - entire multiset in one part.
for j in range(m):
ps = pstack[j]
ps.c = j
ps.u = multiplicities[j]
ps.v = multiplicities[j]
# Other variables
f[0] = 0
a = 0
lpart = 0
f[1] = m
b = m # in general, current stack frame is from a to b - 1
while True:
while True:
# Step M2 (Subtract v from u)
j = a
k = b
x = False
while j < b:
pstack[k].u = pstack[j].u - pstack[j].v
if pstack[k].u == 0:
x = True
elif not x:
pstack[k].c = pstack[j].c
pstack[k].v = min(pstack[j].v, pstack[k].u)
x = pstack[k].u < pstack[j].v
k = k + 1
else: # x is True
pstack[k].c = pstack[j].c
pstack[k].v = pstack[k].u
k = k + 1
j = j + 1
# Note: x is True iff v has changed
# Step M3 (Push if nonzero.)
if k > b:
a = b
b = k
lpart = lpart + 1
f[lpart + 1] = b
# Return to M2
else:
break # Continue to M4
# M4 Visit a partition
state = [f, lpart, pstack]
yield state
# M5 (Decrease v)
while True:
j = b-1
while (pstack[j].v == 0):
j = j - 1
if j == a and pstack[j].v == 1:
# M6 (Backtrack)
if lpart == 0:
return
lpart = lpart - 1
b = a
a = f[lpart]
# Return to M5
else:
pstack[j].v = pstack[j].v - 1
for k in range(j + 1, b):
pstack[k].v = pstack[k].u
break # GOTO M2
# --------------- Visitor functions for multiset partitions ---------------
# A visitor takes the partition state generated by
# multiset_partitions_taocp or other enumerator, and produces useful
# output (such as the actual partition).
def factoring_visitor(state, primes):
"""Use with multiset_partitions_taocp to enumerate the ways a
number can be expressed as a product of factors. For this usage,
the exponents of the prime factors of a number are arguments to
the partition enumerator, while the corresponding prime factors
are input here.
Examples
========
To enumerate the factorings of a number we can think of the elements of the
partition as being the prime factors and the multiplicities as being their
exponents.
>>> from sympy.utilities.enumerative import factoring_visitor
>>> from sympy.utilities.enumerative import multiset_partitions_taocp
>>> from sympy import factorint
>>> primes, multiplicities = zip(*factorint(24).items())
>>> primes
(2, 3)
>>> multiplicities
(3, 1)
>>> states = multiset_partitions_taocp(multiplicities)
>>> list(factoring_visitor(state, primes) for state in states)
[[24], [8, 3], [12, 2], [4, 6], [4, 2, 3], [6, 2, 2], [2, 2, 2, 3]]
"""
f, lpart, pstack = state
factoring = []
for i in range(lpart + 1):
factor = 1
for ps in pstack[f[i]: f[i + 1]]:
if ps.v > 0:
factor *= primes[ps.c] ** ps.v
factoring.append(factor)
return factoring
def list_visitor(state, components):
"""Return a list of lists to represent the partition.
Examples
========
>>> from sympy.utilities.enumerative import list_visitor
>>> from sympy.utilities.enumerative import multiset_partitions_taocp
>>> states = multiset_partitions_taocp([1, 2, 1])
>>> s = next(states)
>>> list_visitor(s, 'abc') # for multiset 'a b b c'
[['a', 'b', 'b', 'c']]
>>> s = next(states)
>>> list_visitor(s, [1, 2, 3]) # for multiset '1 2 2 3
[[1, 2, 2], [3]]
"""
f, lpart, pstack = state
partition = []
for i in range(lpart+1):
part = []
for ps in pstack[f[i]:f[i+1]]:
if ps.v > 0:
part.extend([components[ps.c]] * ps.v)
partition.append(part)
return partition
class MultisetPartitionTraverser():
"""
Has methods to ``enumerate`` and ``count`` the partitions of a multiset.
This implements a refactored and extended version of Knuth's algorithm
7.1.2.5M [AOCP]_."
The enumeration methods of this class are generators and return
data structures which can be interpreted by the same visitor
functions used for the output of ``multiset_partitions_taocp``.
Examples
========
>>> from sympy.utilities.enumerative import MultisetPartitionTraverser
>>> m = MultisetPartitionTraverser()
>>> m.count_partitions([4,4,4,2])
127750
>>> m.count_partitions([3,3,3])
686
See Also
========
multiset_partitions_taocp
sympy.utilities.iterables.multiset_partitions
References
==========
.. [AOCP] Algorithm 7.1.2.5M in Volume 4A, Combinatoral Algorithms,
Part 1, of The Art of Computer Programming, by Donald Knuth.
.. [Factorisatio] On a Problem of Oppenheim concerning
"Factorisatio Numerorum" E. R. Canfield, Paul Erdos, Carl
Pomerance, JOURNAL OF NUMBER THEORY, Vol. 17, No. 1. August
1983. See section 7 for a description of an algorithm
similar to Knuth's.
.. [Yorgey] Generating Multiset Partitions, Brent Yorgey, The
Monad.Reader, Issue 8, September 2007.
"""
def __init__(self):
self.debug = False
# TRACING variables. These are useful for gathering
# statistics on the algorithm itself, but have no particular
# benefit to a user of the code.
self.k1 = 0
self.k2 = 0
self.p1 = 0
self.pstack = None
self.f = None
self.lpart = 0
self.discarded = 0
# dp_stack is list of lists of (part_key, start_count) pairs
self.dp_stack = []
# dp_map is map part_key-> count, where count represents the
# number of multiset which are descendants of a part with this
# key, **or any of its decrements**
# Thus, when we find a part in the map, we add its count
# value to the running total, cut off the enumeration, and
# backtrack
if not hasattr(self, 'dp_map'):
self.dp_map = {}
def db_trace(self, msg):
"""Useful for understanding/debugging the algorithms. Not
generally activated in end-user code."""
if self.debug:
# XXX: animation_visitor is undefined... Clearly this does not
# work and was not tested. Previous code in comments below.
raise RuntimeError
#letters = 'abcdefghijklmnopqrstuvwxyz'
#state = [self.f, self.lpart, self.pstack]
#print("DBG:", msg,
# ["".join(part) for part in list_visitor(state, letters)],
# animation_visitor(state))
#
# Helper methods for enumeration
#
def _initialize_enumeration(self, multiplicities):
"""Allocates and initializes the partition stack.
This is called from the enumeration/counting routines, so
there is no need to call it separately."""
num_components = len(multiplicities)
# cardinality is the total number of elements, whether or not distinct
cardinality = sum(multiplicities)
# pstack is the partition stack, which is segmented by
# f into parts.
self.pstack = [PartComponent() for i in
range(num_components * cardinality + 1)]
self.f = [0] * (cardinality + 1)
# Initial state - entire multiset in one part.
for j in range(num_components):
ps = self.pstack[j]
ps.c = j
ps.u = multiplicities[j]
ps.v = multiplicities[j]
self.f[0] = 0
self.f[1] = num_components
self.lpart = 0
# The decrement_part() method corresponds to step M5 in Knuth's
# algorithm. This is the base version for enum_all(). Modified
# versions of this method are needed if we want to restrict
# sizes of the partitions produced.
def decrement_part(self, part):
"""Decrements part (a subrange of pstack), if possible, returning
True iff the part was successfully decremented.
If you think of the v values in the part as a multi-digit
integer (least significant digit on the right) this is
basically decrementing that integer, but with the extra
constraint that the leftmost digit cannot be decremented to 0.
Parameters
==========
part
The part, represented as a list of PartComponent objects,
which is to be decremented.
"""
plen = len(part)
for j in range(plen - 1, -1, -1):
if j == 0 and part[j].v > 1 or j > 0 and part[j].v > 0:
# found val to decrement
part[j].v -= 1
# Reset trailing parts back to maximum
for k in range(j + 1, plen):
part[k].v = part[k].u
return True
return False
# Version to allow number of parts to be bounded from above.
# Corresponds to (a modified) step M5.
def decrement_part_small(self, part, ub):
"""Decrements part (a subrange of pstack), if possible, returning
True iff the part was successfully decremented.
Parameters
==========
part
part to be decremented (topmost part on the stack)
ub
the maximum number of parts allowed in a partition
returned by the calling traversal.
Notes
=====
The goal of this modification of the ordinary decrement method
is to fail (meaning that the subtree rooted at this part is to
be skipped) when it can be proved that this part can only have
child partitions which are larger than allowed by ``ub``. If a
decision is made to fail, it must be accurate, otherwise the
enumeration will miss some partitions. But, it is OK not to
capture all the possible failures -- if a part is passed that
should not be, the resulting too-large partitions are filtered
by the enumeration one level up. However, as is usual in
constrained enumerations, failing early is advantageous.
The tests used by this method catch the most common cases,
although this implementation is by no means the last word on
this problem. The tests include:
1) ``lpart`` must be less than ``ub`` by at least 2. This is because
once a part has been decremented, the partition
will gain at least one child in the spread step.
2) If the leading component of the part is about to be
decremented, check for how many parts will be added in
order to use up the unallocated multiplicity in that
leading component, and fail if this number is greater than
allowed by ``ub``. (See code for the exact expression.) This
test is given in the answer to Knuth's problem 7.2.1.5.69.
3) If there is *exactly* enough room to expand the leading
component by the above test, check the next component (if
it exists) once decrementing has finished. If this has
``v == 0``, this next component will push the expansion over the
limit by 1, so fail.
"""
if self.lpart >= ub - 1:
self.p1 += 1 # increment to keep track of usefulness of tests
return False
plen = len(part)
for j in range(plen - 1, -1, -1):
# Knuth's mod, (answer to problem 7.2.1.5.69)
if j == 0 and (part[0].v - 1)*(ub - self.lpart) < part[0].u:
self.k1 += 1
return False
if j == 0 and part[j].v > 1 or j > 0 and part[j].v > 0:
# found val to decrement
part[j].v -= 1
# Reset trailing parts back to maximum
for k in range(j + 1, plen):
part[k].v = part[k].u
# Have now decremented part, but are we doomed to
# failure when it is expanded? Check one oddball case
# that turns out to be surprisingly common - exactly
# enough room to expand the leading component, but no
# room for the second component, which has v=0.
if (plen > 1 and part[1].v == 0 and
(part[0].u - part[0].v) ==
((ub - self.lpart - 1) * part[0].v)):
self.k2 += 1
self.db_trace("Decrement fails test 3")
return False
return True
return False
def decrement_part_large(self, part, amt, lb):
"""Decrements part, while respecting size constraint.
A part can have no children which are of sufficient size (as
indicated by ``lb``) unless that part has sufficient
unallocated multiplicity. When enforcing the size constraint,
this method will decrement the part (if necessary) by an
amount needed to ensure sufficient unallocated multiplicity.
Returns True iff the part was successfully decremented.
Parameters
==========
part
part to be decremented (topmost part on the stack)
amt
Can only take values 0 or 1. A value of 1 means that the
part must be decremented, and then the size constraint is
enforced. A value of 0 means just to enforce the ``lb``
size constraint.
lb
The partitions produced by the calling enumeration must
have more parts than this value.
"""
if amt == 1:
# In this case we always need to increment, *before*
# enforcing the "sufficient unallocated multiplicity"
# constraint. Easiest for this is just to call the
# regular decrement method.
if not self.decrement_part(part):
return False
# Next, perform any needed additional decrementing to respect
# "sufficient unallocated multiplicity" (or fail if this is
# not possible).
min_unalloc = lb - self.lpart
if min_unalloc <= 0:
return True
total_mult = sum(pc.u for pc in part)
total_alloc = sum(pc.v for pc in part)
if total_mult <= min_unalloc:
return False
deficit = min_unalloc - (total_mult - total_alloc)
if deficit <= 0:
return True
for i in range(len(part) - 1, -1, -1):
if i == 0:
if part[0].v > deficit:
part[0].v -= deficit
return True
else:
return False # This shouldn't happen, due to above check
else:
if part[i].v >= deficit:
part[i].v -= deficit
return True
else:
deficit -= part[i].v
part[i].v = 0
def decrement_part_range(self, part, lb, ub):
"""Decrements part (a subrange of pstack), if possible, returning
True iff the part was successfully decremented.
Parameters
==========
part
part to be decremented (topmost part on the stack)
ub
the maximum number of parts allowed in a partition
returned by the calling traversal.
lb
The partitions produced by the calling enumeration must
have more parts than this value.
Notes
=====
Combines the constraints of _small and _large decrement
methods. If returns success, part has been decremented at
least once, but perhaps by quite a bit more if needed to meet
the lb constraint.
"""
# Constraint in the range case is just enforcing both the
# constraints from _small and _large cases. Note the 0 as the
# second argument to the _large call -- this is the signal to
# decrement only as needed to for constraint enforcement. The
# short circuiting and left-to-right order of the 'and'
# operator is important for this to work correctly.
return self.decrement_part_small(part, ub) and \
self.decrement_part_large(part, 0, lb)
def spread_part_multiplicity(self):
"""Returns True if a new part has been created, and
adjusts pstack, f and lpart as needed.
Notes
=====
Spreads unallocated multiplicity from the current top part
into a new part created above the current on the stack. This
new part is constrained to be less than or equal to the old in
terms of the part ordering.
This call does nothing (and returns False) if the current top
part has no unallocated multiplicity.
"""
j = self.f[self.lpart] # base of current top part
k = self.f[self.lpart + 1] # ub of current; potential base of next
base = k # save for later comparison
changed = False # Set to true when the new part (so far) is
# strictly less than (as opposed to less than
# or equal) to the old.
for j in range(self.f[self.lpart], self.f[self.lpart + 1]):
self.pstack[k].u = self.pstack[j].u - self.pstack[j].v
if self.pstack[k].u == 0:
changed = True
else:
self.pstack[k].c = self.pstack[j].c
if changed: # Put all available multiplicity in this part
self.pstack[k].v = self.pstack[k].u
else: # Still maintaining ordering constraint
if self.pstack[k].u < self.pstack[j].v:
self.pstack[k].v = self.pstack[k].u
changed = True
else:
self.pstack[k].v = self.pstack[j].v
k = k + 1
if k > base:
# Adjust for the new part on stack
self.lpart = self.lpart + 1
self.f[self.lpart + 1] = k
return True
return False
def top_part(self):
"""Return current top part on the stack, as a slice of pstack.
"""
return self.pstack[self.f[self.lpart]:self.f[self.lpart + 1]]
# Same interface and functionality as multiset_partitions_taocp(),
# but some might find this refactored version easier to follow.
def enum_all(self, multiplicities):
"""Enumerate the partitions of a multiset.
Examples
========
>>> from sympy.utilities.enumerative import list_visitor
>>> from sympy.utilities.enumerative import MultisetPartitionTraverser
>>> m = MultisetPartitionTraverser()
>>> states = m.enum_all([2,2])
>>> list(list_visitor(state, 'ab') for state in states)
[[['a', 'a', 'b', 'b']],
[['a', 'a', 'b'], ['b']],
[['a', 'a'], ['b', 'b']],
[['a', 'a'], ['b'], ['b']],
[['a', 'b', 'b'], ['a']],
[['a', 'b'], ['a', 'b']],
[['a', 'b'], ['a'], ['b']],
[['a'], ['a'], ['b', 'b']],
[['a'], ['a'], ['b'], ['b']]]
See Also
========
multiset_partitions_taocp():
which provides the same result as this method, but is
about twice as fast. Hence, enum_all is primarily useful
for testing. Also see the function for a discussion of
states and visitors.
"""
self._initialize_enumeration(multiplicities)
while True:
while self.spread_part_multiplicity():
pass
# M4 Visit a partition
state = [self.f, self.lpart, self.pstack]
yield state
# M5 (Decrease v)
while not self.decrement_part(self.top_part()):
# M6 (Backtrack)
if self.lpart == 0:
return
self.lpart -= 1
def enum_small(self, multiplicities, ub):
"""Enumerate multiset partitions with no more than ``ub`` parts.
Equivalent to enum_range(multiplicities, 0, ub)
Parameters
==========
multiplicities
list of multiplicities of the components of the multiset.
ub
Maximum number of parts
Examples
========
>>> from sympy.utilities.enumerative import list_visitor
>>> from sympy.utilities.enumerative import MultisetPartitionTraverser
>>> m = MultisetPartitionTraverser()
>>> states = m.enum_small([2,2], 2)
>>> list(list_visitor(state, 'ab') for state in states)
[[['a', 'a', 'b', 'b']],
[['a', 'a', 'b'], ['b']],
[['a', 'a'], ['b', 'b']],
[['a', 'b', 'b'], ['a']],
[['a', 'b'], ['a', 'b']]]
The implementation is based, in part, on the answer given to
exercise 69, in Knuth [AOCP]_.
See Also
========
enum_all, enum_large, enum_range
"""
# Keep track of iterations which do not yield a partition.
# Clearly, we would like to keep this number small.
self.discarded = 0
if ub <= 0:
return
self._initialize_enumeration(multiplicities)
while True:
while self.spread_part_multiplicity():
self.db_trace('spread 1')
if self.lpart >= ub:
self.discarded += 1
self.db_trace(' Discarding')
self.lpart = ub - 2
break
else:
# M4 Visit a partition
state = [self.f, self.lpart, self.pstack]
yield state
# M5 (Decrease v)
while not self.decrement_part_small(self.top_part(), ub):
self.db_trace("Failed decrement, going to backtrack")
# M6 (Backtrack)
if self.lpart == 0:
return
self.lpart -= 1
self.db_trace("Backtracked to")
self.db_trace("decrement ok, about to expand")
def enum_large(self, multiplicities, lb):
"""Enumerate the partitions of a multiset with lb < num(parts)
Equivalent to enum_range(multiplicities, lb, sum(multiplicities))
Parameters
==========
multiplicities
list of multiplicities of the components of the multiset.
lb
Number of parts in the partition must be greater than
this lower bound.
Examples
========
>>> from sympy.utilities.enumerative import list_visitor
>>> from sympy.utilities.enumerative import MultisetPartitionTraverser
>>> m = MultisetPartitionTraverser()
>>> states = m.enum_large([2,2], 2)
>>> list(list_visitor(state, 'ab') for state in states)
[[['a', 'a'], ['b'], ['b']],
[['a', 'b'], ['a'], ['b']],
[['a'], ['a'], ['b', 'b']],
[['a'], ['a'], ['b'], ['b']]]
See Also
========
enum_all, enum_small, enum_range
"""
self.discarded = 0
if lb >= sum(multiplicities):
return
self._initialize_enumeration(multiplicities)
self.decrement_part_large(self.top_part(), 0, lb)
while True:
good_partition = True
while self.spread_part_multiplicity():
if not self.decrement_part_large(self.top_part(), 0, lb):
# Failure here should be rare/impossible
self.discarded += 1
good_partition = False
break
# M4 Visit a partition
if good_partition:
state = [self.f, self.lpart, self.pstack]
yield state
# M5 (Decrease v)
while not self.decrement_part_large(self.top_part(), 1, lb):
# M6 (Backtrack)
if self.lpart == 0:
return
self.lpart -= 1
def enum_range(self, multiplicities, lb, ub):
"""Enumerate the partitions of a multiset with
``lb < num(parts) <= ub``.
In particular, if partitions with exactly ``k`` parts are
desired, call with ``(multiplicities, k - 1, k)``. This
method generalizes enum_all, enum_small, and enum_large.
Examples
========
>>> from sympy.utilities.enumerative import list_visitor
>>> from sympy.utilities.enumerative import MultisetPartitionTraverser
>>> m = MultisetPartitionTraverser()
>>> states = m.enum_range([2,2], 1, 2)
>>> list(list_visitor(state, 'ab') for state in states)
[[['a', 'a', 'b'], ['b']],
[['a', 'a'], ['b', 'b']],
[['a', 'b', 'b'], ['a']],
[['a', 'b'], ['a', 'b']]]
"""
# combine the constraints of the _large and _small
# enumerations.
self.discarded = 0
if ub <= 0 or lb >= sum(multiplicities):
return
self._initialize_enumeration(multiplicities)
self.decrement_part_large(self.top_part(), 0, lb)
while True:
good_partition = True
while self.spread_part_multiplicity():
self.db_trace("spread 1")
if not self.decrement_part_large(self.top_part(), 0, lb):
# Failure here - possible in range case?
self.db_trace(" Discarding (large cons)")
self.discarded += 1
good_partition = False
break
elif self.lpart >= ub:
self.discarded += 1
good_partition = False
self.db_trace(" Discarding small cons")
self.lpart = ub - 2
break
# M4 Visit a partition
if good_partition:
state = [self.f, self.lpart, self.pstack]
yield state
# M5 (Decrease v)
while not self.decrement_part_range(self.top_part(), lb, ub):
self.db_trace("Failed decrement, going to backtrack")
# M6 (Backtrack)
if self.lpart == 0:
return
self.lpart -= 1
self.db_trace("Backtracked to")
self.db_trace("decrement ok, about to expand")
def count_partitions_slow(self, multiplicities):
"""Returns the number of partitions of a multiset whose elements
have the multiplicities given in ``multiplicities``.
Primarily for comparison purposes. It follows the same path as
enumerate, and counts, rather than generates, the partitions.
See Also
========
count_partitions
Has the same calling interface, but is much faster.
"""
# number of partitions so far in the enumeration
self.pcount = 0
self._initialize_enumeration(multiplicities)
while True:
while self.spread_part_multiplicity():
pass
# M4 Visit (count) a partition
self.pcount += 1
# M5 (Decrease v)
while not self.decrement_part(self.top_part()):
# M6 (Backtrack)
if self.lpart == 0:
return self.pcount
self.lpart -= 1
def count_partitions(self, multiplicities):
"""Returns the number of partitions of a multiset whose components
have the multiplicities given in ``multiplicities``.
For larger counts, this method is much faster than calling one
of the enumerators and counting the result. Uses dynamic
programming to cut down on the number of nodes actually
explored. The dictionary used in order to accelerate the
counting process is stored in the ``MultisetPartitionTraverser``
object and persists across calls. If the user does not
expect to call ``count_partitions`` for any additional
multisets, the object should be cleared to save memory. On
the other hand, the cache built up from one count run can
significantly speed up subsequent calls to ``count_partitions``,
so it may be advantageous not to clear the object.
Examples
========
>>> from sympy.utilities.enumerative import MultisetPartitionTraverser
>>> m = MultisetPartitionTraverser()
>>> m.count_partitions([9,8,2])
288716
>>> m.count_partitions([2,2])
9
>>> del m
Notes
=====
If one looks at the workings of Knuth's algorithm M [AOCP]_, it
can be viewed as a traversal of a binary tree of parts. A
part has (up to) two children, the left child resulting from
the spread operation, and the right child from the decrement
operation. The ordinary enumeration of multiset partitions is
an in-order traversal of this tree, and with the partitions
corresponding to paths from the root to the leaves. The
mapping from paths to partitions is a little complicated,
since the partition would contain only those parts which are
leaves or the parents of a spread link, not those which are
parents of a decrement link.
For counting purposes, it is sufficient to count leaves, and
this can be done with a recursive in-order traversal. The
number of leaves of a subtree rooted at a particular part is a
function only of that part itself, so memoizing has the
potential to speed up the counting dramatically.
This method follows a computational approach which is similar
to the hypothetical memoized recursive function, but with two
differences:
1) This method is iterative, borrowing its structure from the
other enumerations and maintaining an explicit stack of
parts which are in the process of being counted. (There
may be multisets which can be counted reasonably quickly by
this implementation, but which would overflow the default
Python recursion limit with a recursive implementation.)
2) Instead of using the part data structure directly, a more
compact key is constructed. This saves space, but more
importantly coalesces some parts which would remain
separate with physical keys.
Unlike the enumeration functions, there is currently no _range
version of count_partitions. If someone wants to stretch
their brain, it should be possible to construct one by
memoizing with a histogram of counts rather than a single
count, and combining the histograms.
"""
# number of partitions so far in the enumeration
self.pcount = 0
# dp_stack is list of lists of (part_key, start_count) pairs
self.dp_stack = []
self._initialize_enumeration(multiplicities)
pkey = part_key(self.top_part())
self.dp_stack.append([(pkey, 0), ])
while True:
while self.spread_part_multiplicity():
pkey = part_key(self.top_part())
if pkey in self.dp_map:
# Already have a cached value for the count of the
# subtree rooted at this part. Add it to the
# running counter, and break out of the spread
# loop. The -1 below is to compensate for the
# leaf that this code path would otherwise find,
# and which gets incremented for below.
self.pcount += (self.dp_map[pkey] - 1)
self.lpart -= 1
break
else:
self.dp_stack.append([(pkey, self.pcount), ])
# M4 count a leaf partition
self.pcount += 1
# M5 (Decrease v)
while not self.decrement_part(self.top_part()):
# M6 (Backtrack)
for key, oldcount in self.dp_stack.pop():
self.dp_map[key] = self.pcount - oldcount
if self.lpart == 0:
return self.pcount
self.lpart -= 1
# At this point have successfully decremented the part on
# the stack and it does not appear in the cache. It needs
# to be added to the list at the top of dp_stack
pkey = part_key(self.top_part())
self.dp_stack[-1].append((pkey, self.pcount),)
def part_key(part):
"""Helper for MultisetPartitionTraverser.count_partitions that
creates a key for ``part``, that only includes information which can
affect the count for that part. (Any irrelevant information just
reduces the effectiveness of dynamic programming.)
Notes
=====
This member function is a candidate for future exploration. There
are likely symmetries that can be exploited to coalesce some
``part_key`` values, and thereby save space and improve
performance.
"""
# The component number is irrelevant for counting partitions, so
# leave it out of the memo key.
rval = []
for ps in part:
rval.append(ps.u)
rval.append(ps.v)
return tuple(rval)
|
83d7e02c28eb92e624f88997fd5e36bded9721ac8ad359969a55ca3885665bff | """
General SymPy exceptions and warnings.
"""
import warnings
import contextlib
from textwrap import dedent
class SymPyDeprecationWarning(DeprecationWarning):
r"""
A warning for deprecated features of SymPy.
See the :ref:`deprecation-policy` document for details on when and how
things should be deprecated in SymPy.
Note that simply constructing this class will not cause a warning to be
issued. To do that, you must call the :func`sympy_deprecation_warning`
function. For this reason, it is not recommended to ever construct this
class directly.
Explanation
===========
The ``SymPyDeprecationWarning`` class is a subclass of
``DeprecationWarning`` that is used for all deprecations in SymPy. A
special subclass is used so that we can automatically augment the warning
message with additional metadata about the version the deprecation was
introduced in and a link to the documentation. This also allows users to
explicitly filter deprecation warnings from SymPy using ``warnings``
filters (see :ref:`silencing-sympy-deprecation-warnings`).
Additionally, ``SymPyDeprecationWarning`` is enabled to be shown by
default, unlike normal ``DeprecationWarning``\s, which are only shown by
default in interactive sessions. This ensures that deprecation warnings in
SymPy will actually be seen by users.
See the documentation of :func:`sympy_deprecation_warning` for a
description of the parameters to this function.
To mark a function as deprecated, you can use the :func:`@deprecated
<sympy.utilities.decorator.deprecated>` decorator.
See Also
========
sympy.utilities.exceptions.sympy_deprecation_warning
sympy.utilities.exceptions.ignore_warnings
sympy.utilities.decorator.deprecated
sympy.testing.pytest.warns_deprecated_sympy
"""
def __init__(self, message, *, deprecated_since_version, active_deprecations_target):
super().__init__(message, deprecated_since_version,
active_deprecations_target)
self.message = message
if not isinstance(deprecated_since_version, str):
raise TypeError(f"'deprecated_since_version' should be a string, got {deprecated_since_version!r}")
self.deprecated_since_version = deprecated_since_version
self.active_deprecations_target = active_deprecations_target
if any(i in active_deprecations_target for i in '()='):
raise ValueError("active_deprecations_target be the part inside of the '(...)='")
self.full_message = f"""
{dedent(message).strip()}
See https://docs.sympy.org/latest/explanation/active-deprecations.html#{active_deprecations_target}
for details.
This has been deprecated since SymPy version {deprecated_since_version}. It
will be removed in a future version of SymPy.
"""
def __str__(self):
return self.full_message
def __repr__(self):
return f"{self.__class__.__name__}({self.message!r}, deprecated_since_version={self.deprecated_since_version!r}, active_deprecations_target={self.active_deprecations_target!r})"
def __eq__(self, other):
return isinstance(other, SymPyDeprecationWarning) and self.args == other.args
# Make pickling work. The by default, it tries to recreate the expression
# from its args, but this doesn't work because of our keyword-only
# arguments.
@classmethod
def _new(cls, message, deprecated_since_version,
active_deprecations_target):
return cls(message, deprecated_since_version=deprecated_since_version, active_deprecations_target=active_deprecations_target)
def __reduce__(self):
return (self._new, (self.message, self.deprecated_since_version, self.active_deprecations_target))
# Python by default hides DeprecationWarnings, which we do not want.
warnings.simplefilter("once", SymPyDeprecationWarning)
def sympy_deprecation_warning(message, *, deprecated_since_version,
active_deprecations_target, stacklevel=3):
r'''
Warn that a feature is deprecated in SymPy.
See the :ref:`deprecation-policy` document for details on when and how
things should be deprecated in SymPy.
To mark an entire function or class as deprecated, you can use the
:func:`@deprecated <sympy.utilities.decorator.deprecated>` decorator.
Parameters
==========
message: str
The deprecation message. This may span multiple lines and contain
code examples. Messages should be wrapped to 80 characters. The
message is automatically dedented and leading and trailing whitespace
stripped. Messages may include dynamic content based on the user
input, but avoid using ``str(expression)`` if an expression can be
arbitrary, as it might be huge and make the warning message
unreadable.
deprecated_since_version: str
The version of SymPy the feature has been deprecated since. For new
deprecations, this should be the version in `sympy/release.py
<https://github.com/sympy/sympy/blob/master/sympy/release.py>`_
without the ``.dev``. If the next SymPy version ends up being
different from this, the release manager will need to update any
``SymPyDeprecationWarning``\s using the incorrect version. This
argument is required and must be passed as a keyword argument.
(example: ``deprecated_since_version="1.10"``).
active_deprecations_target: str
The Sphinx target corresponding to the section for the deprecation in
the :ref:`active-deprecations` document (see
``doc/src/explanation/active-deprecations.md``). This is used to
automatically generate a URL to the page in the warning message. This
argument is required and must be passed as a keyword argument.
(example: ``active_deprecations_target="deprecated-feature-abc"``)
stacklevel: int (default: 3)
The ``stacklevel`` parameter that is passed to ``warnings.warn``. If
you create a wrapper that calls this function, this should be
increased so that the warning message shows the user line of code that
produced the warning. Note that in some cases there will be multiple
possible different user code paths that could result in the warning.
In that case, just choose the smallest common stacklevel.
Examples
========
>>> from sympy.utilities.exceptions import sympy_deprecation_warning
>>> def is_this_zero(x, y=0):
... """
... Determine if x = 0.
...
... Parameters
... ==========
...
... x : Expr
... The expression to check.
...
... y : Expr, optional
... If provided, check if x = y.
...
... .. deprecated:: 1.1
...
... The ``y`` argument to ``is_this_zero`` is deprecated. Use
... ``is_this_zero(x - y)`` instead.
...
... """
... from sympy import simplify
...
... if y != 0:
... sympy_deprecation_warning("""
... The y argument to is_zero() is deprecated. Use is_zero(x - y) instead.""",
... deprecated_since_version="1.1",
... active_deprecations_target='is-this-zero-y-deprecation')
... return simplify(x - y) == 0
>>> is_this_zero(0)
True
>>> is_this_zero(1, 1) # doctest: +SKIP
<stdin>:1: SymPyDeprecationWarning:
<BLANKLINE>
The y argument to is_zero() is deprecated. Use is_zero(x - y) instead.
<BLANKLINE>
See https://docs.sympy.org/latest/explanation/active-deprecations.html#is-this-zero-y-deprecation
for details.
<BLANKLINE>
This has been deprecated since SymPy version 1.1. It
will be removed in a future version of SymPy.
<BLANKLINE>
is_this_zero(1, 1)
True
See Also
========
sympy.utilities.exceptions.SymPyDeprecationWarning
sympy.utilities.exceptions.ignore_warnings
sympy.utilities.decorator.deprecated
sympy.testing.pytest.warns_deprecated_sympy
'''
w = SymPyDeprecationWarning(message,
deprecated_since_version=deprecated_since_version,
active_deprecations_target=active_deprecations_target)
warnings.warn(w, stacklevel=stacklevel)
@contextlib.contextmanager
def ignore_warnings(warningcls):
'''
Context manager to suppress warnings during tests.
.. note::
Do not use this with SymPyDeprecationWarning in the tests.
warns_deprecated_sympy() should be used instead.
This function is useful for suppressing warnings during tests. The warns
function should be used to assert that a warning is raised. The
ignore_warnings function is useful in situation when the warning is not
guaranteed to be raised (e.g. on importing a module) or if the warning
comes from third-party code.
This function is also useful to prevent the same or similar warnings from
being issue twice due to recursive calls.
When the warning is coming (reliably) from SymPy the warns function should
be preferred to ignore_warnings.
>>> from sympy.utilities.exceptions import ignore_warnings
>>> import warnings
Here's a warning:
>>> with warnings.catch_warnings(): # reset warnings in doctest
... warnings.simplefilter('error')
... warnings.warn('deprecated', UserWarning)
Traceback (most recent call last):
...
UserWarning: deprecated
Let's suppress it with ignore_warnings:
>>> with warnings.catch_warnings(): # reset warnings in doctest
... warnings.simplefilter('error')
... with ignore_warnings(UserWarning):
... warnings.warn('deprecated', UserWarning)
(No warning emitted)
See Also
========
sympy.utilities.exceptions.SymPyDeprecationWarning
sympy.utilities.exceptions.sympy_deprecation_warning
sympy.utilities.decorator.deprecated
sympy.testing.pytest.warns_deprecated_sympy
'''
# Absorbs all warnings in warnrec
with warnings.catch_warnings(record=True) as warnrec:
# Make sure our warning doesn't get filtered
warnings.simplefilter("always", warningcls)
# Now run the test
yield
# Reissue any warnings that we aren't testing for
for w in warnrec:
if not issubclass(w.category, warningcls):
warnings.warn_explicit(w.message, w.category, w.filename, w.lineno)
|
cd1b078a398648e6dfc0d724f0485b001fefffaf8ce854ec6b0b1e0ccfe19dea | """Useful utility decorators. """
import sys
import types
import inspect
from functools import wraps, update_wrapper
from sympy.testing.runtests import DependencyError, SymPyDocTests, PyTestReporter
from sympy.utilities.exceptions import sympy_deprecation_warning
def threaded_factory(func, use_add):
"""A factory for ``threaded`` decorators. """
from sympy.core import sympify
from sympy.matrices import MatrixBase
from sympy.utilities.iterables import iterable
@wraps(func)
def threaded_func(expr, *args, **kwargs):
if isinstance(expr, MatrixBase):
return expr.applyfunc(lambda f: func(f, *args, **kwargs))
elif iterable(expr):
try:
return expr.__class__([func(f, *args, **kwargs) for f in expr])
except TypeError:
return expr
else:
expr = sympify(expr)
if use_add and expr.is_Add:
return expr.__class__(*[ func(f, *args, **kwargs) for f in expr.args ])
elif expr.is_Relational:
return expr.__class__(func(expr.lhs, *args, **kwargs),
func(expr.rhs, *args, **kwargs))
else:
return func(expr, *args, **kwargs)
return threaded_func
def threaded(func):
"""Apply ``func`` to sub--elements of an object, including :class:`~.Add`.
This decorator is intended to make it uniformly possible to apply a
function to all elements of composite objects, e.g. matrices, lists, tuples
and other iterable containers, or just expressions.
This version of :func:`threaded` decorator allows threading over
elements of :class:`~.Add` class. If this behavior is not desirable
use :func:`xthreaded` decorator.
Functions using this decorator must have the following signature::
@threaded
def function(expr, *args, **kwargs):
"""
return threaded_factory(func, True)
def xthreaded(func):
"""Apply ``func`` to sub--elements of an object, excluding :class:`~.Add`.
This decorator is intended to make it uniformly possible to apply a
function to all elements of composite objects, e.g. matrices, lists, tuples
and other iterable containers, or just expressions.
This version of :func:`threaded` decorator disallows threading over
elements of :class:`~.Add` class. If this behavior is not desirable
use :func:`threaded` decorator.
Functions using this decorator must have the following signature::
@xthreaded
def function(expr, *args, **kwargs):
"""
return threaded_factory(func, False)
def conserve_mpmath_dps(func):
"""After the function finishes, resets the value of mpmath.mp.dps to
the value it had before the function was run."""
import mpmath
def func_wrapper(*args, **kwargs):
dps = mpmath.mp.dps
try:
return func(*args, **kwargs)
finally:
mpmath.mp.dps = dps
func_wrapper = update_wrapper(func_wrapper, func)
return func_wrapper
class no_attrs_in_subclass:
"""Don't 'inherit' certain attributes from a base class
>>> from sympy.utilities.decorator import no_attrs_in_subclass
>>> class A(object):
... x = 'test'
>>> A.x = no_attrs_in_subclass(A, A.x)
>>> class B(A):
... pass
>>> hasattr(A, 'x')
True
>>> hasattr(B, 'x')
False
"""
def __init__(self, cls, f):
self.cls = cls
self.f = f
def __get__(self, instance, owner=None):
if owner == self.cls:
if hasattr(self.f, '__get__'):
return self.f.__get__(instance, owner)
return self.f
raise AttributeError
def doctest_depends_on(exe=None, modules=None, disable_viewers=None, python_version=None):
"""
Adds metadata about the dependencies which need to be met for doctesting
the docstrings of the decorated objects.
exe should be a list of executables
modules should be a list of modules
disable_viewers should be a list of viewers for preview() to disable
python_version should be the minimum Python version required, as a tuple
(like (3, 0))
"""
dependencies = {}
if exe is not None:
dependencies['executables'] = exe
if modules is not None:
dependencies['modules'] = modules
if disable_viewers is not None:
dependencies['disable_viewers'] = disable_viewers
if python_version is not None:
dependencies['python_version'] = python_version
def skiptests():
r = PyTestReporter()
t = SymPyDocTests(r, None)
try:
t._check_dependencies(**dependencies)
except DependencyError:
return True # Skip doctests
else:
return False # Run doctests
def depends_on_deco(fn):
fn._doctest_depends_on = dependencies
fn.__doctest_skip__ = skiptests
if inspect.isclass(fn):
fn._doctest_depdends_on = no_attrs_in_subclass(
fn, fn._doctest_depends_on)
fn.__doctest_skip__ = no_attrs_in_subclass(
fn, fn.__doctest_skip__)
return fn
return depends_on_deco
def public(obj):
"""
Append ``obj``'s name to global ``__all__`` variable (call site).
By using this decorator on functions or classes you achieve the same goal
as by filling ``__all__`` variables manually, you just do not have to repeat
yourself (object's name). You also know if object is public at definition
site, not at some random location (where ``__all__`` was set).
Note that in multiple decorator setup (in almost all cases) ``@public``
decorator must be applied before any other decorators, because it relies
on the pointer to object's global namespace. If you apply other decorators
first, ``@public`` may end up modifying the wrong namespace.
Examples
========
>>> from sympy.utilities.decorator import public
>>> __all__ # noqa: F821
Traceback (most recent call last):
...
NameError: name '__all__' is not defined
>>> @public
... def some_function():
... pass
>>> __all__ # noqa: F821
['some_function']
"""
if isinstance(obj, types.FunctionType):
ns = obj.__globals__
name = obj.__name__
elif isinstance(obj, (type(type), type)):
ns = sys.modules[obj.__module__].__dict__
name = obj.__name__
else:
raise TypeError("expected a function or a class, got %s" % obj)
if "__all__" not in ns:
ns["__all__"] = [name]
else:
ns["__all__"].append(name)
return obj
def memoize_property(propfunc):
"""Property decorator that caches the value of potentially expensive
`propfunc` after the first evaluation. The cached value is stored in
the corresponding property name with an attached underscore."""
attrname = '_' + propfunc.__name__
sentinel = object()
@wraps(propfunc)
def accessor(self):
val = getattr(self, attrname, sentinel)
if val is sentinel:
val = propfunc(self)
setattr(self, attrname, val)
return val
return property(accessor)
def deprecated(message, *, deprecated_since_version,
active_deprecations_target, stacklevel=3):
'''
Mark a function as deprecated.
This decorator should be used if an entire function or class is
deprecated. If only a certain functionality is deprecated, you should use
:func:`~.warns_deprecated_sympy` directly. This decorator is just a
convenience. There is no functional difference between using this
decorator and calling ``warns_deprecated_sympy()`` at the top of the
function.
The decorator takes the same arguments as
:func:`~.warns_deprecated_sympy`. See its
documentation for details on what the keywords to this decorator do.
See the :ref:`deprecation-policy` document for details on when and how
things should be deprecated in SymPy.
Examples
========
>>> from sympy.utilities.decorator import deprecated
>>> from sympy import simplify
>>> @deprecated("""\
... The simplify_this(expr) function is deprecated. Use simplify(expr)
... instead.""", deprecated_since_version="1.1",
... active_deprecations_target='simplify-this-deprecation')
... def simplify_this(expr):
... """
... Simplify ``expr``.
...
... .. deprecated:: 1.1
...
... The ``simplify_this`` function is deprecated. Use :func:`simplify`
... instead. See its documentation for more information. See
... :ref:`simplify-this-deprecation` for details.
...
... """
... return simplify(expr)
>>> from sympy.abc import x
>>> simplify_this(x*(x + 1) - x**2) # doctest: +SKIP
<stdin>:1: SymPyDeprecationWarning:
<BLANKLINE>
The simplify_this(expr) function is deprecated. Use simplify(expr)
instead.
<BLANKLINE>
See https://docs.sympy.org/latest/explanation/active-deprecations.html#simplify-this-deprecation
for details.
<BLANKLINE>
This has been deprecated since SymPy version 1.1. It
will be removed in a future version of SymPy.
<BLANKLINE>
simplify_this(x)
x
See Also
========
sympy.utilities.exceptions.SymPyDeprecationWarning
sympy.utilities.exceptions.sympy_deprecation_warning
sympy.utilities.exceptions.ignore_warnings
sympy.testing.pytest.warns_deprecated_sympy
'''
decorator_kwargs = dict(deprecated_since_version=deprecated_since_version,
active_deprecations_target=active_deprecations_target)
def deprecated_decorator(wrapped):
if hasattr(wrapped, '__mro__'): # wrapped is actually a class
class wrapper(wrapped):
__doc__ = wrapped.__doc__
__module__ = wrapped.__module__
_sympy_deprecated_func = wrapped
if '__new__' in wrapped.__dict__:
def __new__(cls, *args, **kwargs):
sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel)
return super().__new__(cls, *args, **kwargs)
else:
def __init__(self, *args, **kwargs):
sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel)
super().__init__(*args, **kwargs)
wrapper.__name__ = wrapped.__name__
else:
@wraps(wrapped)
def wrapper(*args, **kwargs):
sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel)
return wrapped(*args, **kwargs)
wrapper._sympy_deprecated_func = wrapped
return wrapper
return deprecated_decorator
|
dee14d8c27c32c0d47dd49f4114563c3d08c9d289811991743dfdf5c0412954f | """
The objects in this module allow the usage of the MatchPy pattern matching
library on SymPy expressions.
"""
import re
from typing import List, Callable
from sympy.core.sympify import _sympify
from sympy.external import import_module
from sympy.functions import (log, sin, cos, tan, cot, csc, sec, erf, gamma, uppergamma)
from sympy.functions.elementary.hyperbolic import acosh, asinh, atanh, acoth, acsch, asech, cosh, sinh, tanh, coth, sech, csch
from sympy.functions.elementary.trigonometric import atan, acsc, asin, acot, acos, asec
from sympy.functions.special.error_functions import fresnelc, fresnels, erfc, erfi, Ei
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.relational import (Equality, Unequality)
from sympy.core.symbol import Symbol
from sympy.functions.elementary.exponential import exp
from sympy.integrals.integrals import Integral
from sympy.printing.repr import srepr
from sympy.utilities.decorator import doctest_depends_on
matchpy = import_module("matchpy")
if matchpy:
from matchpy import Operation, CommutativeOperation, AssociativeOperation, OneIdentityOperation
from matchpy.expressions.functions import op_iter, create_operation_expression, op_len
Operation.register(Integral)
Operation.register(Pow)
OneIdentityOperation.register(Pow)
Operation.register(Add)
OneIdentityOperation.register(Add)
CommutativeOperation.register(Add)
AssociativeOperation.register(Add)
Operation.register(Mul)
OneIdentityOperation.register(Mul)
CommutativeOperation.register(Mul)
AssociativeOperation.register(Mul)
Operation.register(Equality)
CommutativeOperation.register(Equality)
Operation.register(Unequality)
CommutativeOperation.register(Unequality)
Operation.register(exp)
Operation.register(log)
Operation.register(gamma)
Operation.register(uppergamma)
Operation.register(fresnels)
Operation.register(fresnelc)
Operation.register(erf)
Operation.register(Ei)
Operation.register(erfc)
Operation.register(erfi)
Operation.register(sin)
Operation.register(cos)
Operation.register(tan)
Operation.register(cot)
Operation.register(csc)
Operation.register(sec)
Operation.register(sinh)
Operation.register(cosh)
Operation.register(tanh)
Operation.register(coth)
Operation.register(csch)
Operation.register(sech)
Operation.register(asin)
Operation.register(acos)
Operation.register(atan)
Operation.register(acot)
Operation.register(acsc)
Operation.register(asec)
Operation.register(asinh)
Operation.register(acosh)
Operation.register(atanh)
Operation.register(acoth)
Operation.register(acsch)
Operation.register(asech)
@op_iter.register(Integral) # type: ignore
def _(operation):
return iter((operation._args[0],) + operation._args[1])
@op_iter.register(Basic) # type: ignore
def _(operation):
return iter(operation._args)
@op_len.register(Integral) # type: ignore
def _(operation):
return 1 + len(operation._args[1])
@op_len.register(Basic) # type: ignore
def _(operation):
return len(operation._args)
@create_operation_expression.register(Basic)
def sympy_op_factory(old_operation, new_operands, variable_name=True):
return type(old_operation)(*new_operands)
if matchpy:
from matchpy import Wildcard
else:
class Wildcard: # type: ignore
def __init__(self, min_length, fixed_size, variable_name, optional):
self.min_count = min_length
self.fixed_size = fixed_size
self.variable_name = variable_name
self.optional = optional
@doctest_depends_on(modules=('matchpy',))
class _WildAbstract(Wildcard, Symbol):
min_length: int # abstract field required in subclasses
fixed_size: bool # abstract field required in subclasses
def __init__(self, variable_name=None, optional=None, **assumptions):
min_length = self.min_length
fixed_size = self.fixed_size
if optional is not None:
optional = _sympify(optional)
Wildcard.__init__(self, min_length, fixed_size, str(variable_name), optional)
def __getstate__(self):
return {
"min_length": self.min_length,
"fixed_size": self.fixed_size,
"min_count": self.min_count,
"variable_name": self.variable_name,
"optional": self.optional,
}
def __new__(cls, variable_name=None, optional=None, **assumptions):
cls._sanitize(assumptions, cls)
return _WildAbstract.__xnew__(cls, variable_name, optional, **assumptions)
def __getnewargs__(self):
return self.variable_name, self.optional
@staticmethod
def __xnew__(cls, variable_name=None, optional=None, **assumptions):
obj = Symbol.__xnew__(cls, variable_name, **assumptions)
return obj
def _hashable_content(self):
if self.optional:
return super()._hashable_content() + (self.min_count, self.fixed_size, self.variable_name, self.optional)
else:
return super()._hashable_content() + (self.min_count, self.fixed_size, self.variable_name)
def __copy__(self) -> '_WildAbstract':
return type(self)(variable_name=self.variable_name, optional=self.optional)
def __repr__(self):
return str(self)
def __str__(self):
return self.name
@doctest_depends_on(modules=('matchpy',))
class WildDot(_WildAbstract):
min_length = 1
fixed_size = True
@doctest_depends_on(modules=('matchpy',))
class WildPlus(_WildAbstract):
min_length = 1
fixed_size = False
@doctest_depends_on(modules=('matchpy',))
class WildStar(_WildAbstract):
min_length = 0
fixed_size = False
def _get_srepr(expr):
s = srepr(expr)
s = re.sub(r"WildDot\('(\w+)'\)", r"\1", s)
s = re.sub(r"WildPlus\('(\w+)'\)", r"*\1", s)
s = re.sub(r"WildStar\('(\w+)'\)", r"*\1", s)
return s
@doctest_depends_on(modules=('matchpy',))
class Replacer:
"""
Replacer object to perform multiple pattern matching and subexpression
replacements in SymPy expressions.
Examples
========
Example to construct a simple first degree equation solver:
>>> from sympy.utilities.matchpy_connector import WildDot, Replacer
>>> from sympy import Equality, Symbol
>>> x = Symbol("x")
>>> a_ = WildDot("a_", optional=1)
>>> b_ = WildDot("b_", optional=0)
The lines above have defined two wildcards, ``a_`` and ``b_``, the
coefficients of the equation `a x + b = 0`. The optional values specified
indicate which expression to return in case no match is found, they are
necessary in equations like `a x = 0` and `x + b = 0`.
Create two constraints to make sure that ``a_`` and ``b_`` will not match
any expression containing ``x``:
>>> from matchpy import CustomConstraint
>>> free_x_a = CustomConstraint(lambda a_: not a_.has(x))
>>> free_x_b = CustomConstraint(lambda b_: not b_.has(x))
Now create the rule replacer with the constraints:
>>> replacer = Replacer(common_constraints=[free_x_a, free_x_b])
Add the matching rule:
>>> replacer.add(Equality(a_*x + b_, 0), -b_/a_)
Let's try it:
>>> replacer.replace(Equality(3*x + 4, 0))
-4/3
Notice that it will not match equations expressed with other patterns:
>>> eq = Equality(3*x, 4)
>>> replacer.replace(eq)
Eq(3*x, 4)
In order to extend the matching patterns, define another one (we also need
to clear the cache, because the previous result has already been memorized
and the pattern matcher will not iterate again if given the same expression)
>>> replacer.add(Equality(a_*x, b_), b_/a_)
>>> replacer._replacer.matcher.clear()
>>> replacer.replace(eq)
4/3
"""
def __init__(self, common_constraints: list = []):
self._replacer = matchpy.ManyToOneReplacer()
self._common_constraint = common_constraints
def _get_lambda(self, lambda_str: str) -> Callable[..., Expr]:
exec("from sympy import *")
return eval(lambda_str, locals())
def _get_custom_constraint(self, constraint_expr: Expr, condition_template: str) -> Callable[..., Expr]:
wilds = list(map(lambda x: x.name, constraint_expr.atoms(_WildAbstract)))
lambdaargs = ', '.join(wilds)
fullexpr = _get_srepr(constraint_expr)
condition = condition_template.format(fullexpr)
return matchpy.CustomConstraint(
self._get_lambda(f"lambda {lambdaargs}: ({condition})"))
def _get_custom_constraint_nonfalse(self, constraint_expr: Expr) -> Callable[..., Expr]:
return self._get_custom_constraint(constraint_expr, "({}) != False")
def _get_custom_constraint_true(self, constraint_expr: Expr) -> Callable[..., Expr]:
return self._get_custom_constraint(constraint_expr, "({}) == True")
def add(self, expr: Expr, result: Expr, conditions_true: List[Expr] = [], conditions_nonfalse: List[Expr] = []) -> None:
expr = _sympify(expr)
result = _sympify(result)
lambda_str = f"lambda {', '.join(map(lambda x: x.name, expr.atoms(_WildAbstract)))}: {_get_srepr(result)}"
lambda_expr = self._get_lambda(lambda_str)
constraints = self._common_constraint[:]
constraint_conditions_true = [
self._get_custom_constraint_true(cond) for cond in conditions_true]
constraint_conditions_nonfalse = [
self._get_custom_constraint_nonfalse(cond) for cond in conditions_nonfalse]
constraints.extend(constraint_conditions_true)
constraints.extend(constraint_conditions_nonfalse)
self._replacer.add(
matchpy.ReplacementRule(matchpy.Pattern(expr, *constraints), lambda_expr))
def replace(self, expr: Expr) -> Expr:
return self._replacer.replace(expr)
|
d0a47155178a024d13336b2615e10862ca3e10e8f25eef8cfa3c0deec6d472df | from collections import defaultdict, OrderedDict
from itertools import (
chain, combinations, combinations_with_replacement, cycle, islice,
permutations, product
)
# For backwards compatibility
from itertools import product as cartes # noqa: F401
from operator import gt
# this is the logical location of these functions
from sympy.utilities.enumerative import (
multiset_partitions_taocp, list_visitor, MultisetPartitionTraverser)
from sympy.utilities.misc import as_int
from sympy.utilities.decorator import deprecated
def is_palindromic(s, i=0, j=None):
"""
Return True if the sequence is the same from left to right as it
is from right to left in the whole sequence (default) or in the
Python slice ``s[i: j]``; else False.
Examples
========
>>> from sympy.utilities.iterables import is_palindromic
>>> is_palindromic([1, 0, 1])
True
>>> is_palindromic('abcbb')
False
>>> is_palindromic('abcbb', 1)
False
Normal Python slicing is performed in place so there is no need to
create a slice of the sequence for testing:
>>> is_palindromic('abcbb', 1, -1)
True
>>> is_palindromic('abcbb', -4, -1)
True
See Also
========
sympy.ntheory.digits.is_palindromic: tests integers
"""
i, j, _ = slice(i, j).indices(len(s))
m = (j - i)//2
# if length is odd, middle element will be ignored
return all(s[i + k] == s[j - 1 - k] for k in range(m))
def flatten(iterable, levels=None, cls=None): # noqa: F811
"""
Recursively denest iterable containers.
>>> from sympy import flatten
>>> flatten([1, 2, 3])
[1, 2, 3]
>>> flatten([1, 2, [3]])
[1, 2, 3]
>>> flatten([1, [2, 3], [4, 5]])
[1, 2, 3, 4, 5]
>>> flatten([1.0, 2, (1, None)])
[1.0, 2, 1, None]
If you want to denest only a specified number of levels of
nested containers, then set ``levels`` flag to the desired
number of levels::
>>> ls = [[(-2, -1), (1, 2)], [(0, 0)]]
>>> flatten(ls, levels=1)
[(-2, -1), (1, 2), (0, 0)]
If cls argument is specified, it will only flatten instances of that
class, for example:
>>> from sympy import Basic, S
>>> class MyOp(Basic):
... pass
...
>>> flatten([MyOp(S(1), MyOp(S(2), S(3)))], cls=MyOp)
[1, 2, 3]
adapted from https://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks
"""
from sympy.tensor.array import NDimArray
if levels is not None:
if not levels:
return iterable
elif levels > 0:
levels -= 1
else:
raise ValueError(
"expected non-negative number of levels, got %s" % levels)
if cls is None:
reducible = lambda x: is_sequence(x, set)
else:
reducible = lambda x: isinstance(x, cls)
result = []
for el in iterable:
if reducible(el):
if hasattr(el, 'args') and not isinstance(el, NDimArray):
el = el.args
result.extend(flatten(el, levels=levels, cls=cls))
else:
result.append(el)
return result
def unflatten(iter, n=2):
"""Group ``iter`` into tuples of length ``n``. Raise an error if
the length of ``iter`` is not a multiple of ``n``.
"""
if n < 1 or len(iter) % n:
raise ValueError('iter length is not a multiple of %i' % n)
return list(zip(*(iter[i::n] for i in range(n))))
def reshape(seq, how):
"""Reshape the sequence according to the template in ``how``.
Examples
========
>>> from sympy.utilities import reshape
>>> seq = list(range(1, 9))
>>> reshape(seq, [4]) # lists of 4
[[1, 2, 3, 4], [5, 6, 7, 8]]
>>> reshape(seq, (4,)) # tuples of 4
[(1, 2, 3, 4), (5, 6, 7, 8)]
>>> reshape(seq, (2, 2)) # tuples of 4
[(1, 2, 3, 4), (5, 6, 7, 8)]
>>> reshape(seq, (2, [2])) # (i, i, [i, i])
[(1, 2, [3, 4]), (5, 6, [7, 8])]
>>> reshape(seq, ((2,), [2])) # etc....
[((1, 2), [3, 4]), ((5, 6), [7, 8])]
>>> reshape(seq, (1, [2], 1))
[(1, [2, 3], 4), (5, [6, 7], 8)]
>>> reshape(tuple(seq), ([[1], 1, (2,)],))
(([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],))
>>> reshape(tuple(seq), ([1], 1, (2,)))
(([1], 2, (3, 4)), ([5], 6, (7, 8)))
>>> reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)])
[[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]]
"""
m = sum(flatten(how))
n, rem = divmod(len(seq), m)
if m < 0 or rem:
raise ValueError('template must sum to positive number '
'that divides the length of the sequence')
i = 0
container = type(how)
rv = [None]*n
for k in range(len(rv)):
rv[k] = []
for hi in how:
if isinstance(hi, int):
rv[k].extend(seq[i: i + hi])
i += hi
else:
n = sum(flatten(hi))
hi_type = type(hi)
rv[k].append(hi_type(reshape(seq[i: i + n], hi)[0]))
i += n
rv[k] = container(rv[k])
return type(seq)(rv)
def group(seq, multiple=True):
"""
Splits a sequence into a list of lists of equal, adjacent elements.
Examples
========
>>> from sympy import group
>>> group([1, 1, 1, 2, 2, 3])
[[1, 1, 1], [2, 2], [3]]
>>> group([1, 1, 1, 2, 2, 3], multiple=False)
[(1, 3), (2, 2), (3, 1)]
>>> group([1, 1, 3, 2, 2, 1], multiple=False)
[(1, 2), (3, 1), (2, 2), (1, 1)]
See Also
========
multiset
"""
if not seq:
return []
current, groups = [seq[0]], []
for elem in seq[1:]:
if elem == current[-1]:
current.append(elem)
else:
groups.append(current)
current = [elem]
groups.append(current)
if multiple:
return groups
for i, current in enumerate(groups):
groups[i] = (current[0], len(current))
return groups
def _iproduct2(iterable1, iterable2):
'''Cartesian product of two possibly infinite iterables'''
it1 = iter(iterable1)
it2 = iter(iterable2)
elems1 = []
elems2 = []
sentinel = object()
def append(it, elems):
e = next(it, sentinel)
if e is not sentinel:
elems.append(e)
n = 0
append(it1, elems1)
append(it2, elems2)
while n <= len(elems1) + len(elems2):
for m in range(n-len(elems1)+1, len(elems2)):
yield (elems1[n-m], elems2[m])
n += 1
append(it1, elems1)
append(it2, elems2)
def iproduct(*iterables):
'''
Cartesian product of iterables.
Generator of the Cartesian product of iterables. This is analogous to
itertools.product except that it works with infinite iterables and will
yield any item from the infinite product eventually.
Examples
========
>>> from sympy.utilities.iterables import iproduct
>>> sorted(iproduct([1,2], [3,4]))
[(1, 3), (1, 4), (2, 3), (2, 4)]
With an infinite iterator:
>>> from sympy import S
>>> (3,) in iproduct(S.Integers)
True
>>> (3, 4) in iproduct(S.Integers, S.Integers)
True
.. seealso::
`itertools.product <https://docs.python.org/3/library/itertools.html#itertools.product>`_
'''
if len(iterables) == 0:
yield ()
return
elif len(iterables) == 1:
for e in iterables[0]:
yield (e,)
elif len(iterables) == 2:
yield from _iproduct2(*iterables)
else:
first, others = iterables[0], iterables[1:]
for ef, eo in _iproduct2(first, iproduct(*others)):
yield (ef,) + eo
def multiset(seq):
"""Return the hashable sequence in multiset form with values being the
multiplicity of the item in the sequence.
Examples
========
>>> from sympy.utilities.iterables import multiset
>>> multiset('mississippi')
{'i': 4, 'm': 1, 'p': 2, 's': 4}
See Also
========
group
"""
rv = defaultdict(int)
for s in seq:
rv[s] += 1
return dict(rv)
def ibin(n, bits=None, str=False):
"""Return a list of length ``bits`` corresponding to the binary value
of ``n`` with small bits to the right (last). If bits is omitted, the
length will be the number required to represent ``n``. If the bits are
desired in reversed order, use the ``[::-1]`` slice of the returned list.
If a sequence of all bits-length lists starting from ``[0, 0,..., 0]``
through ``[1, 1, ..., 1]`` are desired, pass a non-integer for bits, e.g.
``'all'``.
If the bit *string* is desired pass ``str=True``.
Examples
========
>>> from sympy.utilities.iterables import ibin
>>> ibin(2)
[1, 0]
>>> ibin(2, 4)
[0, 0, 1, 0]
If all lists corresponding to 0 to 2**n - 1, pass a non-integer
for bits:
>>> bits = 2
>>> for i in ibin(2, 'all'):
... print(i)
(0, 0)
(0, 1)
(1, 0)
(1, 1)
If a bit string is desired of a given length, use str=True:
>>> n = 123
>>> bits = 10
>>> ibin(n, bits, str=True)
'0001111011'
>>> ibin(n, bits, str=True)[::-1] # small bits left
'1101111000'
>>> list(ibin(3, 'all', str=True))
['000', '001', '010', '011', '100', '101', '110', '111']
"""
if n < 0:
raise ValueError("negative numbers are not allowed")
n = as_int(n)
if bits is None:
bits = 0
else:
try:
bits = as_int(bits)
except ValueError:
bits = -1
else:
if n.bit_length() > bits:
raise ValueError(
"`bits` must be >= {}".format(n.bit_length()))
if not str:
if bits >= 0:
return [1 if i == "1" else 0 for i in bin(n)[2:].rjust(bits, "0")]
else:
return variations(list(range(2)), n, repetition=True)
else:
if bits >= 0:
return bin(n)[2:].rjust(bits, "0")
else:
return (bin(i)[2:].rjust(n, "0") for i in range(2**n))
def variations(seq, n, repetition=False):
r"""Returns an iterator over the n-sized variations of ``seq`` (size N).
``repetition`` controls whether items in ``seq`` can appear more than once;
Examples
========
``variations(seq, n)`` will return `\frac{N!}{(N - n)!}` permutations without
repetition of ``seq``'s elements:
>>> from sympy import variations
>>> list(variations([1, 2], 2))
[(1, 2), (2, 1)]
``variations(seq, n, True)`` will return the `N^n` permutations obtained
by allowing repetition of elements:
>>> list(variations([1, 2], 2, repetition=True))
[(1, 1), (1, 2), (2, 1), (2, 2)]
If you ask for more items than are in the set you get the empty set unless
you allow repetitions:
>>> list(variations([0, 1], 3, repetition=False))
[]
>>> list(variations([0, 1], 3, repetition=True))[:4]
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)]
.. seealso::
`itertools.permutations <https://docs.python.org/3/library/itertools.html#itertools.permutations>`_,
`itertools.product <https://docs.python.org/3/library/itertools.html#itertools.product>`_
"""
if not repetition:
seq = tuple(seq)
if len(seq) < n:
return iter(()) # 0 length iterator
return permutations(seq, n)
else:
if n == 0:
return iter(((),)) # yields 1 empty tuple
else:
return product(seq, repeat=n)
def subsets(seq, k=None, repetition=False):
r"""Generates all `k`-subsets (combinations) from an `n`-element set, ``seq``.
A `k`-subset of an `n`-element set is any subset of length exactly `k`. The
number of `k`-subsets of an `n`-element set is given by ``binomial(n, k)``,
whereas there are `2^n` subsets all together. If `k` is ``None`` then all
`2^n` subsets will be returned from shortest to longest.
Examples
========
>>> from sympy import subsets
``subsets(seq, k)`` will return the `\frac{n!}{k!(n - k)!}` `k`-subsets (combinations)
without repetition, i.e. once an item has been removed, it can no
longer be "taken":
>>> list(subsets([1, 2], 2))
[(1, 2)]
>>> list(subsets([1, 2]))
[(), (1,), (2,), (1, 2)]
>>> list(subsets([1, 2, 3], 2))
[(1, 2), (1, 3), (2, 3)]
``subsets(seq, k, repetition=True)`` will return the `\frac{(n - 1 + k)!}{k!(n - 1)!}`
combinations *with* repetition:
>>> list(subsets([1, 2], 2, repetition=True))
[(1, 1), (1, 2), (2, 2)]
If you ask for more items than are in the set you get the empty set unless
you allow repetitions:
>>> list(subsets([0, 1], 3, repetition=False))
[]
>>> list(subsets([0, 1], 3, repetition=True))
[(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)]
"""
if k is None:
if not repetition:
return chain.from_iterable((combinations(seq, k)
for k in range(len(seq) + 1)))
else:
return chain.from_iterable((combinations_with_replacement(seq, k)
for k in range(len(seq) + 1)))
else:
if not repetition:
return combinations(seq, k)
else:
return combinations_with_replacement(seq, k)
def filter_symbols(iterator, exclude):
"""
Only yield elements from `iterator` that do not occur in `exclude`.
Parameters
==========
iterator : iterable
iterator to take elements from
exclude : iterable
elements to exclude
Returns
=======
iterator : iterator
filtered iterator
"""
exclude = set(exclude)
for s in iterator:
if s not in exclude:
yield s
def numbered_symbols(prefix='x', cls=None, start=0, exclude=(), *args, **assumptions):
"""
Generate an infinite stream of Symbols consisting of a prefix and
increasing subscripts provided that they do not occur in ``exclude``.
Parameters
==========
prefix : str, optional
The prefix to use. By default, this function will generate symbols of
the form "x0", "x1", etc.
cls : class, optional
The class to use. By default, it uses ``Symbol``, but you can also use ``Wild`` or ``Dummy``.
start : int, optional
The start number. By default, it is 0.
Returns
=======
sym : Symbol
The subscripted symbols.
"""
exclude = set(exclude or [])
if cls is None:
# We can't just make the default cls=Symbol because it isn't
# imported yet.
from sympy.core import Symbol
cls = Symbol
while True:
name = '%s%s' % (prefix, start)
s = cls(name, *args, **assumptions)
if s not in exclude:
yield s
start += 1
def capture(func):
"""Return the printed output of func().
``func`` should be a function without arguments that produces output with
print statements.
>>> from sympy.utilities.iterables import capture
>>> from sympy import pprint
>>> from sympy.abc import x
>>> def foo():
... print('hello world!')
...
>>> 'hello' in capture(foo) # foo, not foo()
True
>>> capture(lambda: pprint(2/x))
'2\\n-\\nx\\n'
"""
from io import StringIO
import sys
stdout = sys.stdout
sys.stdout = file = StringIO()
try:
func()
finally:
sys.stdout = stdout
return file.getvalue()
def sift(seq, keyfunc, binary=False):
"""
Sift the sequence, ``seq`` according to ``keyfunc``.
Returns
=======
When ``binary`` is ``False`` (default), the output is a dictionary
where elements of ``seq`` are stored in a list keyed to the value
of keyfunc for that element. If ``binary`` is True then a tuple
with lists ``T`` and ``F`` are returned where ``T`` is a list
containing elements of seq for which ``keyfunc`` was ``True`` and
``F`` containing those elements for which ``keyfunc`` was ``False``;
a ValueError is raised if the ``keyfunc`` is not binary.
Examples
========
>>> from sympy.utilities import sift
>>> from sympy.abc import x, y
>>> from sympy import sqrt, exp, pi, Tuple
>>> sift(range(5), lambda x: x % 2)
{0: [0, 2, 4], 1: [1, 3]}
sift() returns a defaultdict() object, so any key that has no matches will
give [].
>>> sift([x], lambda x: x.is_commutative)
{True: [x]}
>>> _[False]
[]
Sometimes you will not know how many keys you will get:
>>> sift([sqrt(x), exp(x), (y**x)**2],
... lambda x: x.as_base_exp()[0])
{E: [exp(x)], x: [sqrt(x)], y: [y**(2*x)]}
Sometimes you expect the results to be binary; the
results can be unpacked by setting ``binary`` to True:
>>> sift(range(4), lambda x: x % 2, binary=True)
([1, 3], [0, 2])
>>> sift(Tuple(1, pi), lambda x: x.is_rational, binary=True)
([1], [pi])
A ValueError is raised if the predicate was not actually binary
(which is a good test for the logic where sifting is used and
binary results were expected):
>>> unknown = exp(1) - pi # the rationality of this is unknown
>>> args = Tuple(1, pi, unknown)
>>> sift(args, lambda x: x.is_rational, binary=True)
Traceback (most recent call last):
...
ValueError: keyfunc gave non-binary output
The non-binary sifting shows that there were 3 keys generated:
>>> set(sift(args, lambda x: x.is_rational).keys())
{None, False, True}
If you need to sort the sifted items it might be better to use
``ordered`` which can economically apply multiple sort keys
to a sequence while sorting.
See Also
========
ordered
"""
if not binary:
m = defaultdict(list)
for i in seq:
m[keyfunc(i)].append(i)
return m
sift = F, T = [], []
for i in seq:
try:
sift[keyfunc(i)].append(i)
except (IndexError, TypeError):
raise ValueError('keyfunc gave non-binary output')
return T, F
def take(iter, n):
"""Return ``n`` items from ``iter`` iterator. """
return [ value for _, value in zip(range(n), iter) ]
def dict_merge(*dicts):
"""Merge dictionaries into a single dictionary. """
merged = {}
for dict in dicts:
merged.update(dict)
return merged
def common_prefix(*seqs):
"""Return the subsequence that is a common start of sequences in ``seqs``.
>>> from sympy.utilities.iterables import common_prefix
>>> common_prefix(list(range(3)))
[0, 1, 2]
>>> common_prefix(list(range(3)), list(range(4)))
[0, 1, 2]
>>> common_prefix([1, 2, 3], [1, 2, 5])
[1, 2]
>>> common_prefix([1, 2, 3], [1, 3, 5])
[1]
"""
if not all(seqs):
return []
elif len(seqs) == 1:
return seqs[0]
i = 0
for i in range(min(len(s) for s in seqs)):
if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))):
break
else:
i += 1
return seqs[0][:i]
def common_suffix(*seqs):
"""Return the subsequence that is a common ending of sequences in ``seqs``.
>>> from sympy.utilities.iterables import common_suffix
>>> common_suffix(list(range(3)))
[0, 1, 2]
>>> common_suffix(list(range(3)), list(range(4)))
[]
>>> common_suffix([1, 2, 3], [9, 2, 3])
[2, 3]
>>> common_suffix([1, 2, 3], [9, 7, 3])
[3]
"""
if not all(seqs):
return []
elif len(seqs) == 1:
return seqs[0]
i = 0
for i in range(-1, -min(len(s) for s in seqs) - 1, -1):
if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))):
break
else:
i -= 1
if i == -1:
return []
else:
return seqs[0][i + 1:]
def prefixes(seq):
"""
Generate all prefixes of a sequence.
Examples
========
>>> from sympy.utilities.iterables import prefixes
>>> list(prefixes([1,2,3,4]))
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
"""
n = len(seq)
for i in range(n):
yield seq[:i + 1]
def postfixes(seq):
"""
Generate all postfixes of a sequence.
Examples
========
>>> from sympy.utilities.iterables import postfixes
>>> list(postfixes([1,2,3,4]))
[[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]]
"""
n = len(seq)
for i in range(n):
yield seq[n - i - 1:]
def topological_sort(graph, key=None):
r"""
Topological sort of graph's vertices.
Parameters
==========
graph : tuple[list, list[tuple[T, T]]
A tuple consisting of a list of vertices and a list of edges of
a graph to be sorted topologically.
key : callable[T] (optional)
Ordering key for vertices on the same level. By default the natural
(e.g. lexicographic) ordering is used (in this case the base type
must implement ordering relations).
Examples
========
Consider a graph::
+---+ +---+ +---+
| 7 |\ | 5 | | 3 |
+---+ \ +---+ +---+
| _\___/ ____ _/ |
| / \___/ \ / |
V V V V |
+----+ +---+ |
| 11 | | 8 | |
+----+ +---+ |
| | \____ ___/ _ |
| \ \ / / \ |
V \ V V / V V
+---+ \ +---+ | +----+
| 2 | | | 9 | | | 10 |
+---+ | +---+ | +----+
\________/
where vertices are integers. This graph can be encoded using
elementary Python's data structures as follows::
>>> V = [2, 3, 5, 7, 8, 9, 10, 11]
>>> E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10),
... (11, 2), (11, 9), (11, 10), (8, 9)]
To compute a topological sort for graph ``(V, E)`` issue::
>>> from sympy.utilities.iterables import topological_sort
>>> topological_sort((V, E))
[3, 5, 7, 8, 11, 2, 9, 10]
If specific tie breaking approach is needed, use ``key`` parameter::
>>> topological_sort((V, E), key=lambda v: -v)
[7, 5, 11, 3, 10, 8, 9, 2]
Only acyclic graphs can be sorted. If the input graph has a cycle,
then ``ValueError`` will be raised::
>>> topological_sort((V, E + [(10, 7)]))
Traceback (most recent call last):
...
ValueError: cycle detected
References
==========
.. [1] https://en.wikipedia.org/wiki/Topological_sorting
"""
V, E = graph
L = []
S = set(V)
E = list(E)
for v, u in E:
S.discard(u)
if key is None:
key = lambda value: value
S = sorted(S, key=key, reverse=True)
while S:
node = S.pop()
L.append(node)
for u, v in list(E):
if u == node:
E.remove((u, v))
for _u, _v in E:
if v == _v:
break
else:
kv = key(v)
for i, s in enumerate(S):
ks = key(s)
if kv > ks:
S.insert(i, v)
break
else:
S.append(v)
if E:
raise ValueError("cycle detected")
else:
return L
def strongly_connected_components(G):
r"""
Strongly connected components of a directed graph in reverse topological
order.
Parameters
==========
graph : tuple[list, list[tuple[T, T]]
A tuple consisting of a list of vertices and a list of edges of
a graph whose strongly connected components are to be found.
Examples
========
Consider a directed graph (in dot notation)::
digraph {
A -> B
A -> C
B -> C
C -> B
B -> D
}
.. graphviz::
digraph {
A -> B
A -> C
B -> C
C -> B
B -> D
}
where vertices are the letters A, B, C and D. This graph can be encoded
using Python's elementary data structures as follows::
>>> V = ['A', 'B', 'C', 'D']
>>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'B'), ('B', 'D')]
The strongly connected components of this graph can be computed as
>>> from sympy.utilities.iterables import strongly_connected_components
>>> strongly_connected_components((V, E))
[['D'], ['B', 'C'], ['A']]
This also gives the components in reverse topological order.
Since the subgraph containing B and C has a cycle they must be together in
a strongly connected component. A and D are connected to the rest of the
graph but not in a cyclic manner so they appear as their own strongly
connected components.
Notes
=====
The vertices of the graph must be hashable for the data structures used.
If the vertices are unhashable replace them with integer indices.
This function uses Tarjan's algorithm to compute the strongly connected
components in `O(|V|+|E|)` (linear) time.
References
==========
.. [1] https://en.wikipedia.org/wiki/Strongly_connected_component
.. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
See Also
========
sympy.utilities.iterables.connected_components
"""
# Map from a vertex to its neighbours
V, E = G
Gmap = {vi: [] for vi in V}
for v1, v2 in E:
Gmap[v1].append(v2)
return _strongly_connected_components(V, Gmap)
def _strongly_connected_components(V, Gmap):
"""More efficient internal routine for strongly_connected_components"""
#
# Here V is an iterable of vertices and Gmap is a dict mapping each vertex
# to a list of neighbours e.g.:
#
# V = [0, 1, 2, 3]
# Gmap = {0: [2, 3], 1: [0]}
#
# For a large graph these data structures can often be created more
# efficiently then those expected by strongly_connected_components() which
# in this case would be
#
# V = [0, 1, 2, 3]
# Gmap = [(0, 2), (0, 3), (1, 0)]
#
# XXX: Maybe this should be the recommended function to use instead...
#
# Non-recursive Tarjan's algorithm:
lowlink = {}
indices = {}
stack = OrderedDict()
callstack = []
components = []
nomore = object()
def start(v):
index = len(stack)
indices[v] = lowlink[v] = index
stack[v] = None
callstack.append((v, iter(Gmap[v])))
def finish(v1):
# Finished a component?
if lowlink[v1] == indices[v1]:
component = [stack.popitem()[0]]
while component[-1] is not v1:
component.append(stack.popitem()[0])
components.append(component[::-1])
v2, _ = callstack.pop()
if callstack:
v1, _ = callstack[-1]
lowlink[v1] = min(lowlink[v1], lowlink[v2])
for v in V:
if v in indices:
continue
start(v)
while callstack:
v1, it1 = callstack[-1]
v2 = next(it1, nomore)
# Finished children of v1?
if v2 is nomore:
finish(v1)
# Recurse on v2
elif v2 not in indices:
start(v2)
elif v2 in stack:
lowlink[v1] = min(lowlink[v1], indices[v2])
# Reverse topological sort order:
return components
def connected_components(G):
r"""
Connected components of an undirected graph or weakly connected components
of a directed graph.
Parameters
==========
graph : tuple[list, list[tuple[T, T]]
A tuple consisting of a list of vertices and a list of edges of
a graph whose connected components are to be found.
Examples
========
Given an undirected graph::
graph {
A -- B
C -- D
}
.. graphviz::
graph {
A -- B
C -- D
}
We can find the connected components using this function if we include
each edge in both directions::
>>> from sympy.utilities.iterables import connected_components
>>> V = ['A', 'B', 'C', 'D']
>>> E = [('A', 'B'), ('B', 'A'), ('C', 'D'), ('D', 'C')]
>>> connected_components((V, E))
[['A', 'B'], ['C', 'D']]
The weakly connected components of a directed graph can found the same
way.
Notes
=====
The vertices of the graph must be hashable for the data structures used.
If the vertices are unhashable replace them with integer indices.
This function uses Tarjan's algorithm to compute the connected components
in `O(|V|+|E|)` (linear) time.
References
==========
.. [1] https://en.wikipedia.org/wiki/Connected_component_(graph_theory)
.. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
See Also
========
sympy.utilities.iterables.strongly_connected_components
"""
# Duplicate edges both ways so that the graph is effectively undirected
# and return the strongly connected components:
V, E = G
E_undirected = []
for v1, v2 in E:
E_undirected.extend([(v1, v2), (v2, v1)])
return strongly_connected_components((V, E_undirected))
def rotate_left(x, y):
"""
Left rotates a list x by the number of steps specified
in y.
Examples
========
>>> from sympy.utilities.iterables import rotate_left
>>> a = [0, 1, 2]
>>> rotate_left(a, 1)
[1, 2, 0]
"""
if len(x) == 0:
return []
y = y % len(x)
return x[y:] + x[:y]
def rotate_right(x, y):
"""
Right rotates a list x by the number of steps specified
in y.
Examples
========
>>> from sympy.utilities.iterables import rotate_right
>>> a = [0, 1, 2]
>>> rotate_right(a, 1)
[2, 0, 1]
"""
if len(x) == 0:
return []
y = len(x) - y % len(x)
return x[y:] + x[:y]
def least_rotation(x, key=None):
'''
Returns the number of steps of left rotation required to
obtain lexicographically minimal string/list/tuple, etc.
Examples
========
>>> from sympy.utilities.iterables import least_rotation, rotate_left
>>> a = [3, 1, 5, 1, 2]
>>> least_rotation(a)
3
>>> rotate_left(a, _)
[1, 2, 3, 1, 5]
References
==========
.. [1] https://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation
'''
from sympy.functions.elementary.miscellaneous import Id
if key is None: key = Id
S = x + x # Concatenate string to it self to avoid modular arithmetic
f = [-1] * len(S) # Failure function
k = 0 # Least rotation of string found so far
for j in range(1,len(S)):
sj = S[j]
i = f[j-k-1]
while i != -1 and sj != S[k+i+1]:
if key(sj) < key(S[k+i+1]):
k = j-i-1
i = f[i]
if sj != S[k+i+1]:
if key(sj) < key(S[k]):
k = j
f[j-k] = -1
else:
f[j-k] = i+1
return k
def multiset_combinations(m, n, g=None):
"""
Return the unique combinations of size ``n`` from multiset ``m``.
Examples
========
>>> from sympy.utilities.iterables import multiset_combinations
>>> from itertools import combinations
>>> [''.join(i) for i in multiset_combinations('baby', 3)]
['abb', 'aby', 'bby']
>>> def count(f, s): return len(list(f(s, 3)))
The number of combinations depends on the number of letters; the
number of unique combinations depends on how the letters are
repeated.
>>> s1 = 'abracadabra'
>>> s2 = 'banana tree'
>>> count(combinations, s1), count(multiset_combinations, s1)
(165, 23)
>>> count(combinations, s2), count(multiset_combinations, s2)
(165, 54)
"""
from sympy.core.sorting import ordered
if g is None:
if isinstance(m, dict):
if any(as_int(v) < 0 for v in m.values()):
raise ValueError('counts cannot be negative')
N = sum(m.values())
if n > N:
return
g = [[k, m[k]] for k in ordered(m)]
else:
m = list(m)
N = len(m)
if n > N:
return
try:
m = multiset(m)
g = [(k, m[k]) for k in ordered(m)]
except TypeError:
m = list(ordered(m))
g = [list(i) for i in group(m, multiple=False)]
del m
else:
# not checking counts since g is intended for internal use
N = sum(v for k, v in g)
if n > N or not n:
yield []
else:
for i, (k, v) in enumerate(g):
if v >= n:
yield [k]*n
v = n - 1
for v in range(min(n, v), 0, -1):
for j in multiset_combinations(None, n - v, g[i + 1:]):
rv = [k]*v + j
if len(rv) == n:
yield rv
def multiset_permutations(m, size=None, g=None):
"""
Return the unique permutations of multiset ``m``.
Examples
========
>>> from sympy.utilities.iterables import multiset_permutations
>>> from sympy import factorial
>>> [''.join(i) for i in multiset_permutations('aab')]
['aab', 'aba', 'baa']
>>> factorial(len('banana'))
720
>>> len(list(multiset_permutations('banana')))
60
"""
from sympy.core.sorting import ordered
if g is None:
if isinstance(m, dict):
if any(as_int(v) < 0 for v in m.values()):
raise ValueError('counts cannot be negative')
g = [[k, m[k]] for k in ordered(m)]
else:
m = list(ordered(m))
g = [list(i) for i in group(m, multiple=False)]
del m
do = [gi for gi in g if gi[1] > 0]
SUM = sum([gi[1] for gi in do])
if not do or size is not None and (size > SUM or size < 1):
if not do and size is None or size == 0:
yield []
return
elif size == 1:
for k, v in do:
yield [k]
elif len(do) == 1:
k, v = do[0]
v = v if size is None else (size if size <= v else 0)
yield [k for i in range(v)]
elif all(v == 1 for k, v in do):
for p in permutations([k for k, v in do], size):
yield list(p)
else:
size = size if size is not None else SUM
for i, (k, v) in enumerate(do):
do[i][1] -= 1
for j in multiset_permutations(None, size - 1, do):
if j:
yield [k] + j
do[i][1] += 1
def _partition(seq, vector, m=None):
"""
Return the partition of seq as specified by the partition vector.
Examples
========
>>> from sympy.utilities.iterables import _partition
>>> _partition('abcde', [1, 0, 1, 2, 0])
[['b', 'e'], ['a', 'c'], ['d']]
Specifying the number of bins in the partition is optional:
>>> _partition('abcde', [1, 0, 1, 2, 0], 3)
[['b', 'e'], ['a', 'c'], ['d']]
The output of _set_partitions can be passed as follows:
>>> output = (3, [1, 0, 1, 2, 0])
>>> _partition('abcde', *output)
[['b', 'e'], ['a', 'c'], ['d']]
See Also
========
combinatorics.partitions.Partition.from_rgs
"""
if m is None:
m = max(vector) + 1
elif isinstance(vector, int): # entered as m, vector
vector, m = m, vector
p = [[] for i in range(m)]
for i, v in enumerate(vector):
p[v].append(seq[i])
return p
def _set_partitions(n):
"""Cycle through all partions of n elements, yielding the
current number of partitions, ``m``, and a mutable list, ``q``
such that ``element[i]`` is in part ``q[i]`` of the partition.
NOTE: ``q`` is modified in place and generally should not be changed
between function calls.
Examples
========
>>> from sympy.utilities.iterables import _set_partitions, _partition
>>> for m, q in _set_partitions(3):
... print('%s %s %s' % (m, q, _partition('abc', q, m)))
1 [0, 0, 0] [['a', 'b', 'c']]
2 [0, 0, 1] [['a', 'b'], ['c']]
2 [0, 1, 0] [['a', 'c'], ['b']]
2 [0, 1, 1] [['a'], ['b', 'c']]
3 [0, 1, 2] [['a'], ['b'], ['c']]
Notes
=====
This algorithm is similar to, and solves the same problem as,
Algorithm 7.2.1.5H, from volume 4A of Knuth's The Art of Computer
Programming. Knuth uses the term "restricted growth string" where
this code refers to a "partition vector". In each case, the meaning is
the same: the value in the ith element of the vector specifies to
which part the ith set element is to be assigned.
At the lowest level, this code implements an n-digit big-endian
counter (stored in the array q) which is incremented (with carries) to
get the next partition in the sequence. A special twist is that a
digit is constrained to be at most one greater than the maximum of all
the digits to the left of it. The array p maintains this maximum, so
that the code can efficiently decide when a digit can be incremented
in place or whether it needs to be reset to 0 and trigger a carry to
the next digit. The enumeration starts with all the digits 0 (which
corresponds to all the set elements being assigned to the same 0th
part), and ends with 0123...n, which corresponds to each set element
being assigned to a different, singleton, part.
This routine was rewritten to use 0-based lists while trying to
preserve the beauty and efficiency of the original algorithm.
References
==========
.. [1] Nijenhuis, Albert and Wilf, Herbert. (1978) Combinatorial Algorithms,
2nd Ed, p 91, algorithm "nexequ". Available online from
https://www.math.upenn.edu/~wilf/website/CombAlgDownld.html (viewed
November 17, 2012).
"""
p = [0]*n
q = [0]*n
nc = 1
yield nc, q
while nc != n:
m = n
while 1:
m -= 1
i = q[m]
if p[i] != 1:
break
q[m] = 0
i += 1
q[m] = i
m += 1
nc += m - n
p[0] += n - m
if i == nc:
p[nc] = 0
nc += 1
p[i - 1] -= 1
p[i] += 1
yield nc, q
def multiset_partitions(multiset, m=None):
"""
Return unique partitions of the given multiset (in list form).
If ``m`` is None, all multisets will be returned, otherwise only
partitions with ``m`` parts will be returned.
If ``multiset`` is an integer, a range [0, 1, ..., multiset - 1]
will be supplied.
Examples
========
>>> from sympy.utilities.iterables import multiset_partitions
>>> list(multiset_partitions([1, 2, 3, 4], 2))
[[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]],
[[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]],
[[1], [2, 3, 4]]]
>>> list(multiset_partitions([1, 2, 3, 4], 1))
[[[1, 2, 3, 4]]]
Only unique partitions are returned and these will be returned in a
canonical order regardless of the order of the input:
>>> a = [1, 2, 2, 1]
>>> ans = list(multiset_partitions(a, 2))
>>> a.sort()
>>> list(multiset_partitions(a, 2)) == ans
True
>>> a = range(3, 1, -1)
>>> (list(multiset_partitions(a)) ==
... list(multiset_partitions(sorted(a))))
True
If m is omitted then all partitions will be returned:
>>> list(multiset_partitions([1, 1, 2]))
[[[1, 1, 2]], [[1, 1], [2]], [[1, 2], [1]], [[1], [1], [2]]]
>>> list(multiset_partitions([1]*3))
[[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]]
Counting
========
The number of partitions of a set is given by the bell number:
>>> from sympy import bell
>>> len(list(multiset_partitions(5))) == bell(5) == 52
True
The number of partitions of length k from a set of size n is given by the
Stirling Number of the 2nd kind:
>>> from sympy.functions.combinatorial.numbers import stirling
>>> stirling(5, 2) == len(list(multiset_partitions(5, 2))) == 15
True
These comments on counting apply to *sets*, not multisets.
Notes
=====
When all the elements are the same in the multiset, the order
of the returned partitions is determined by the ``partitions``
routine. If one is counting partitions then it is better to use
the ``nT`` function.
See Also
========
partitions
sympy.combinatorics.partitions.Partition
sympy.combinatorics.partitions.IntegerPartition
sympy.functions.combinatorial.numbers.nT
"""
# This function looks at the supplied input and dispatches to
# several special-case routines as they apply.
if isinstance(multiset, int):
n = multiset
if m and m > n:
return
multiset = list(range(n))
if m == 1:
yield [multiset[:]]
return
# If m is not None, it can sometimes be faster to use
# MultisetPartitionTraverser.enum_range() even for inputs
# which are sets. Since the _set_partitions code is quite
# fast, this is only advantageous when the overall set
# partitions outnumber those with the desired number of parts
# by a large factor. (At least 60.) Such a switch is not
# currently implemented.
for nc, q in _set_partitions(n):
if m is None or nc == m:
rv = [[] for i in range(nc)]
for i in range(n):
rv[q[i]].append(multiset[i])
yield rv
return
if len(multiset) == 1 and isinstance(multiset, str):
multiset = [multiset]
if not has_variety(multiset):
# Only one component, repeated n times. The resulting
# partitions correspond to partitions of integer n.
n = len(multiset)
if m and m > n:
return
if m == 1:
yield [multiset[:]]
return
x = multiset[:1]
for size, p in partitions(n, m, size=True):
if m is None or size == m:
rv = []
for k in sorted(p):
rv.extend([x*k]*p[k])
yield rv
else:
from sympy.core.sorting import ordered
multiset = list(ordered(multiset))
n = len(multiset)
if m and m > n:
return
if m == 1:
yield [multiset[:]]
return
# Split the information of the multiset into two lists -
# one of the elements themselves, and one (of the same length)
# giving the number of repeats for the corresponding element.
elements, multiplicities = zip(*group(multiset, False))
if len(elements) < len(multiset):
# General case - multiset with more than one distinct element
# and at least one element repeated more than once.
if m:
mpt = MultisetPartitionTraverser()
for state in mpt.enum_range(multiplicities, m-1, m):
yield list_visitor(state, elements)
else:
for state in multiset_partitions_taocp(multiplicities):
yield list_visitor(state, elements)
else:
# Set partitions case - no repeated elements. Pretty much
# same as int argument case above, with same possible, but
# currently unimplemented optimization for some cases when
# m is not None
for nc, q in _set_partitions(n):
if m is None or nc == m:
rv = [[] for i in range(nc)]
for i in range(n):
rv[q[i]].append(i)
yield [[multiset[j] for j in i] for i in rv]
def partitions(n, m=None, k=None, size=False):
"""Generate all partitions of positive integer, n.
Parameters
==========
m : integer (default gives partitions of all sizes)
limits number of parts in partition (mnemonic: m, maximum parts)
k : integer (default gives partitions number from 1 through n)
limits the numbers that are kept in the partition (mnemonic: k, keys)
size : bool (default False, only partition is returned)
when ``True`` then (M, P) is returned where M is the sum of the
multiplicities and P is the generated partition.
Each partition is represented as a dictionary, mapping an integer
to the number of copies of that integer in the partition. For example,
the first partition of 4 returned is {4: 1}, "4: one of them".
Examples
========
>>> from sympy.utilities.iterables import partitions
The numbers appearing in the partition (the key of the returned dict)
are limited with k:
>>> for p in partitions(6, k=2): # doctest: +SKIP
... print(p)
{2: 3}
{1: 2, 2: 2}
{1: 4, 2: 1}
{1: 6}
The maximum number of parts in the partition (the sum of the values in
the returned dict) are limited with m (default value, None, gives
partitions from 1 through n):
>>> for p in partitions(6, m=2): # doctest: +SKIP
... print(p)
...
{6: 1}
{1: 1, 5: 1}
{2: 1, 4: 1}
{3: 2}
References
==========
.. [1] modified from Tim Peter's version to allow for k and m values:
http://code.activestate.com/recipes/218332-generator-for-integer-partitions/
See Also
========
sympy.combinatorics.partitions.Partition
sympy.combinatorics.partitions.IntegerPartition
"""
if (n <= 0 or
m is not None and m < 1 or
k is not None and k < 1 or
m and k and m*k < n):
# the empty set is the only way to handle these inputs
# and returning {} to represent it is consistent with
# the counting convention, e.g. nT(0) == 1.
if size:
yield 0, {}
else:
yield {}
return
if m is None:
m = n
else:
m = min(m, n)
k = min(k or n, n)
n, m, k = as_int(n), as_int(m), as_int(k)
q, r = divmod(n, k)
ms = {k: q}
keys = [k] # ms.keys(), from largest to smallest
if r:
ms[r] = 1
keys.append(r)
room = m - q - bool(r)
if size:
yield sum(ms.values()), ms.copy()
else:
yield ms.copy()
while keys != [1]:
# Reuse any 1's.
if keys[-1] == 1:
del keys[-1]
reuse = ms.pop(1)
room += reuse
else:
reuse = 0
while 1:
# Let i be the smallest key larger than 1. Reuse one
# instance of i.
i = keys[-1]
newcount = ms[i] = ms[i] - 1
reuse += i
if newcount == 0:
del keys[-1], ms[i]
room += 1
# Break the remainder into pieces of size i-1.
i -= 1
q, r = divmod(reuse, i)
need = q + bool(r)
if need > room:
if not keys:
return
continue
ms[i] = q
keys.append(i)
if r:
ms[r] = 1
keys.append(r)
break
room -= need
if size:
yield sum(ms.values()), ms.copy()
else:
yield ms.copy()
def ordered_partitions(n, m=None, sort=True):
"""Generates ordered partitions of integer ``n``.
Parameters
==========
m : integer (default None)
The default value gives partitions of all sizes else only
those with size m. In addition, if ``m`` is not None then
partitions are generated *in place* (see examples).
sort : bool (default True)
Controls whether partitions are
returned in sorted order when ``m`` is not None; when False,
the partitions are returned as fast as possible with elements
sorted, but when m|n the partitions will not be in
ascending lexicographical order.
Examples
========
>>> from sympy.utilities.iterables import ordered_partitions
All partitions of 5 in ascending lexicographical:
>>> for p in ordered_partitions(5):
... print(p)
[1, 1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 4]
[2, 3]
[5]
Only partitions of 5 with two parts:
>>> for p in ordered_partitions(5, 2):
... print(p)
[1, 4]
[2, 3]
When ``m`` is given, a given list objects will be used more than
once for speed reasons so you will not see the correct partitions
unless you make a copy of each as it is generated:
>>> [p for p in ordered_partitions(7, 3)]
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 2, 2]]
>>> [list(p) for p in ordered_partitions(7, 3)]
[[1, 1, 5], [1, 2, 4], [1, 3, 3], [2, 2, 3]]
When ``n`` is a multiple of ``m``, the elements are still sorted
but the partitions themselves will be *unordered* if sort is False;
the default is to return them in ascending lexicographical order.
>>> for p in ordered_partitions(6, 2):
... print(p)
[1, 5]
[2, 4]
[3, 3]
But if speed is more important than ordering, sort can be set to
False:
>>> for p in ordered_partitions(6, 2, sort=False):
... print(p)
[1, 5]
[3, 3]
[2, 4]
References
==========
.. [1] Generating Integer Partitions, [online],
Available: https://jeromekelleher.net/generating-integer-partitions.html
.. [2] Jerome Kelleher and Barry O'Sullivan, "Generating All
Partitions: A Comparison Of Two Encodings", [online],
Available: https://arxiv.org/pdf/0909.2331v2.pdf
"""
if n < 1 or m is not None and m < 1:
# the empty set is the only way to handle these inputs
# and returning {} to represent it is consistent with
# the counting convention, e.g. nT(0) == 1.
yield []
return
if m is None:
# The list `a`'s leading elements contain the partition in which
# y is the biggest element and x is either the same as y or the
# 2nd largest element; v and w are adjacent element indices
# to which x and y are being assigned, respectively.
a = [1]*n
y = -1
v = n
while v > 0:
v -= 1
x = a[v] + 1
while y >= 2 * x:
a[v] = x
y -= x
v += 1
w = v + 1
while x <= y:
a[v] = x
a[w] = y
yield a[:w + 1]
x += 1
y -= 1
a[v] = x + y
y = a[v] - 1
yield a[:w]
elif m == 1:
yield [n]
elif n == m:
yield [1]*n
else:
# recursively generate partitions of size m
for b in range(1, n//m + 1):
a = [b]*m
x = n - b*m
if not x:
if sort:
yield a
elif not sort and x <= m:
for ax in ordered_partitions(x, sort=False):
mi = len(ax)
a[-mi:] = [i + b for i in ax]
yield a
a[-mi:] = [b]*mi
else:
for mi in range(1, m):
for ax in ordered_partitions(x, mi, sort=True):
a[-mi:] = [i + b for i in ax]
yield a
a[-mi:] = [b]*mi
def binary_partitions(n):
"""
Generates the binary partition of n.
A binary partition consists only of numbers that are
powers of two. Each step reduces a `2^{k+1}` to `2^k` and
`2^k`. Thus 16 is converted to 8 and 8.
Examples
========
>>> from sympy.utilities.iterables import binary_partitions
>>> for i in binary_partitions(5):
... print(i)
...
[4, 1]
[2, 2, 1]
[2, 1, 1, 1]
[1, 1, 1, 1, 1]
References
==========
.. [1] TAOCP 4, section 7.2.1.5, problem 64
"""
from math import ceil, log
power = int(2**(ceil(log(n, 2))))
acc = 0
partition = []
while power:
if acc + power <= n:
partition.append(power)
acc += power
power >>= 1
last_num = len(partition) - 1 - (n & 1)
while last_num >= 0:
yield partition
if partition[last_num] == 2:
partition[last_num] = 1
partition.append(1)
last_num -= 1
continue
partition.append(1)
partition[last_num] >>= 1
x = partition[last_num + 1] = partition[last_num]
last_num += 1
while x > 1:
if x <= len(partition) - last_num - 1:
del partition[-x + 1:]
last_num += 1
partition[last_num] = x
else:
x >>= 1
yield [1]*n
def has_dups(seq):
"""Return True if there are any duplicate elements in ``seq``.
Examples
========
>>> from sympy import has_dups, Dict, Set
>>> has_dups((1, 2, 1))
True
>>> has_dups(range(3))
False
>>> all(has_dups(c) is False for c in (set(), Set(), dict(), Dict()))
True
"""
from sympy.core.containers import Dict
from sympy.sets.sets import Set
if isinstance(seq, (dict, set, Dict, Set)):
return False
unique = set()
try:
return any(True for s in seq if s in unique or unique.add(s))
except TypeError:
return len(seq) != len(list(uniq(seq)))
def has_variety(seq):
"""Return True if there are any different elements in ``seq``.
Examples
========
>>> from sympy import has_variety
>>> has_variety((1, 2, 1))
True
>>> has_variety((1, 1, 1))
False
"""
for i, s in enumerate(seq):
if i == 0:
sentinel = s
else:
if s != sentinel:
return True
return False
def uniq(seq, result=None):
"""
Yield unique elements from ``seq`` as an iterator. The second
parameter ``result`` is used internally; it is not necessary
to pass anything for this.
Note: changing the sequence during iteration will raise a
RuntimeError if the size of the sequence is known; if you pass
an iterator and advance the iterator you will change the
output of this routine but there will be no warning.
Examples
========
>>> from sympy.utilities.iterables import uniq
>>> dat = [1, 4, 1, 5, 4, 2, 1, 2]
>>> type(uniq(dat)) in (list, tuple)
False
>>> list(uniq(dat))
[1, 4, 5, 2]
>>> list(uniq(x for x in dat))
[1, 4, 5, 2]
>>> list(uniq([[1], [2, 1], [1]]))
[[1], [2, 1]]
"""
try:
n = len(seq)
except TypeError:
n = None
def check():
# check that size of seq did not change during iteration;
# if n == None the object won't support size changing, e.g.
# an iterator can't be changed
if n is not None and len(seq) != n:
raise RuntimeError('sequence changed size during iteration')
try:
seen = set()
result = result or []
for i, s in enumerate(seq):
if not (s in seen or seen.add(s)):
yield s
check()
except TypeError:
if s not in result:
yield s
check()
result.append(s)
if hasattr(seq, '__getitem__'):
yield from uniq(seq[i + 1:], result)
else:
yield from uniq(seq, result)
def generate_bell(n):
"""Return permutations of [0, 1, ..., n - 1] such that each permutation
differs from the last by the exchange of a single pair of neighbors.
The ``n!`` permutations are returned as an iterator. In order to obtain
the next permutation from a random starting permutation, use the
``next_trotterjohnson`` method of the Permutation class (which generates
the same sequence in a different manner).
Examples
========
>>> from itertools import permutations
>>> from sympy.utilities.iterables import generate_bell
>>> from sympy import zeros, Matrix
This is the sort of permutation used in the ringing of physical bells,
and does not produce permutations in lexicographical order. Rather, the
permutations differ from each other by exactly one inversion, and the
position at which the swapping occurs varies periodically in a simple
fashion. Consider the first few permutations of 4 elements generated
by ``permutations`` and ``generate_bell``:
>>> list(permutations(range(4)))[:5]
[(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2)]
>>> list(generate_bell(4))[:5]
[(0, 1, 2, 3), (0, 1, 3, 2), (0, 3, 1, 2), (3, 0, 1, 2), (3, 0, 2, 1)]
Notice how the 2nd and 3rd lexicographical permutations have 3 elements
out of place whereas each "bell" permutation always has only two
elements out of place relative to the previous permutation (and so the
signature (+/-1) of a permutation is opposite of the signature of the
previous permutation).
How the position of inversion varies across the elements can be seen
by tracing out where the largest number appears in the permutations:
>>> m = zeros(4, 24)
>>> for i, p in enumerate(generate_bell(4)):
... m[:, i] = Matrix([j - 3 for j in list(p)]) # make largest zero
>>> m.print_nonzero('X')
[XXX XXXXXX XXXXXX XXX]
[XX XX XXXX XX XXXX XX XX]
[X XXXX XX XXXX XX XXXX X]
[ XXXXXX XXXXXX XXXXXX ]
See Also
========
sympy.combinatorics.permutations.Permutation.next_trotterjohnson
References
==========
.. [1] https://en.wikipedia.org/wiki/Method_ringing
.. [2] https://stackoverflow.com/questions/4856615/recursive-permutation/4857018
.. [3] http://programminggeeks.com/bell-algorithm-for-permutation/
.. [4] https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm
.. [5] Generating involutions, derangements, and relatives by ECO
Vincent Vajnovszki, DMTCS vol 1 issue 12, 2010
"""
n = as_int(n)
if n < 1:
raise ValueError('n must be a positive integer')
if n == 1:
yield (0,)
elif n == 2:
yield (0, 1)
yield (1, 0)
elif n == 3:
yield from [(0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)]
else:
m = n - 1
op = [0] + [-1]*m
l = list(range(n))
while True:
yield tuple(l)
# find biggest element with op
big = None, -1 # idx, value
for i in range(n):
if op[i] and l[i] > big[1]:
big = i, l[i]
i, _ = big
if i is None:
break # there are no ops left
# swap it with neighbor in the indicated direction
j = i + op[i]
l[i], l[j] = l[j], l[i]
op[i], op[j] = op[j], op[i]
# if it landed at the end or if the neighbor in the same
# direction is bigger then turn off op
if j == 0 or j == m or l[j + op[j]] > l[j]:
op[j] = 0
# any element bigger to the left gets +1 op
for i in range(j):
if l[i] > l[j]:
op[i] = 1
# any element bigger to the right gets -1 op
for i in range(j + 1, n):
if l[i] > l[j]:
op[i] = -1
def generate_involutions(n):
"""
Generates involutions.
An involution is a permutation that when multiplied
by itself equals the identity permutation. In this
implementation the involutions are generated using
Fixed Points.
Alternatively, an involution can be considered as
a permutation that does not contain any cycles with
a length that is greater than two.
Examples
========
>>> from sympy.utilities.iterables import generate_involutions
>>> list(generate_involutions(3))
[(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)]
>>> len(list(generate_involutions(4)))
10
References
==========
.. [1] http://mathworld.wolfram.com/PermutationInvolution.html
"""
idx = list(range(n))
for p in permutations(idx):
for i in idx:
if p[p[i]] != i:
break
else:
yield p
def multiset_derangements(s):
"""Generate derangements of the elements of s *in place*.
Examples
========
>>> from sympy.utilities.iterables import multiset_derangements, uniq
Because the derangements of multisets (not sets) are generated
in place, copies of the return value must be made if a collection
of derangements is desired or else all values will be the same:
>>> list(uniq([i for i in multiset_derangements('1233')]))
[[None, None, None, None]]
>>> [i.copy() for i in multiset_derangements('1233')]
[['3', '3', '1', '2'], ['3', '3', '2', '1']]
>>> [''.join(i) for i in multiset_derangements('1233')]
['3312', '3321']
"""
from sympy.core.sorting import ordered
# create multiset dictionary of hashable elements or else
# remap elements to integers
try:
ms = multiset(s)
except TypeError:
# give each element a canonical integer value
key = dict(enumerate(ordered(uniq(s))))
h = []
for si in s:
for k in key:
if key[k] == si:
h.append(k)
break
for i in multiset_derangements(h):
yield [key[j] for j in i]
return
mx = max(ms.values()) # max repetition of any element
n = len(s) # the number of elements
## special cases
# 1) one element has more than half the total cardinality of s: no
# derangements are possible.
if mx*2 > n:
return
# 2) all elements appear once: singletons
if len(ms) == n:
yield from _set_derangements(s)
return
# find the first element that is repeated the most to place
# in the following two special cases where the selection
# is unambiguous: either there are two elements with multiplicity
# of mx or else there is only one with multiplicity mx
for M in ms:
if ms[M] == mx:
break
inonM = [i for i in range(n) if s[i] != M] # location of non-M
iM = [i for i in range(n) if s[i] == M] # locations of M
rv = [None]*n
# 3) half are the same
if 2*mx == n:
# M goes into non-M locations
for i in inonM:
rv[i] = M
# permutations of non-M go to M locations
for p in multiset_permutations([s[i] for i in inonM]):
for i, pi in zip(iM, p):
rv[i] = pi
yield rv
# clean-up (and encourages proper use of routine)
rv[:] = [None]*n
return
# 4) single repeat covers all but 1 of the non-repeats:
# if there is one repeat then the multiset of the values
# of ms would be {mx: 1, 1: n - mx}, i.e. there would
# be n - mx + 1 values with the condition that n - 2*mx = 1
if n - 2*mx == 1 and len(ms.values()) == n - mx + 1:
for i in range(len(inonM)):
i1 = inonM[i]
ifill = inonM[:i] + inonM[i+1:]
for j in ifill:
rv[j] = M
for p in permutations([s[j] for j in ifill]):
rv[i1] = s[i1]
for j, pi in zip(iM, p):
rv[j] = pi
k = i1
for j in iM:
rv[j], rv[k] = rv[k], rv[j]
yield rv
k = j
# clean-up (and encourages proper use of routine)
rv[:] = [None]*n
return
## general case is handled with 3 helpers:
# 1) `finish_derangements` will place the last two elements
# which have arbitrary multiplicities, e.g. for multiset
# {c: 3, a: 2, b: 2}, the last two elements are a and b
# 2) `iopen` will tell where a given element can be placed
# 3) `do` will recursively place elements into subsets of
# valid locations
def finish_derangements():
"""Place the last two elements into the partially completed
derangement, and yield the results.
"""
a = take[1][0] # penultimate element
a_ct = take[1][1]
b = take[0][0] # last element to be placed
b_ct = take[0][1]
# split the indexes of the not-already-assigned elemements of rv into
# three categories
forced_a = [] # positions which must have an a
forced_b = [] # positions which must have a b
open_free = [] # positions which could take either
for i in range(len(s)):
if rv[i] is None:
if s[i] == a:
forced_b.append(i)
elif s[i] == b:
forced_a.append(i)
else:
open_free.append(i)
if len(forced_a) > a_ct or len(forced_b) > b_ct:
# No derangement possible
return
for i in forced_a:
rv[i] = a
for i in forced_b:
rv[i] = b
for a_place in combinations(open_free, a_ct - len(forced_a)):
for a_pos in a_place:
rv[a_pos] = a
for i in open_free:
if rv[i] is None: # anything not in the subset is set to b
rv[i] = b
yield rv
# Clean up/undo the final placements
for i in open_free:
rv[i] = None
# additional cleanup - clear forced_a, forced_b
for i in forced_a:
rv[i] = None
for i in forced_b:
rv[i] = None
def iopen(v):
# return indices at which element v can be placed in rv:
# locations which are not already occupied if that location
# does not already contain v in the same location of s
return [i for i in range(n) if rv[i] is None and s[i] != v]
def do(j):
if j == 1:
# handle the last two elements (regardless of multiplicity)
# with a special method
yield from finish_derangements()
else:
# place the mx elements of M into a subset of places
# into which it can be replaced
M, mx = take[j]
for i in combinations(iopen(M), mx):
# place M
for ii in i:
rv[ii] = M
# recursively place the next element
yield from do(j - 1)
# mark positions where M was placed as once again
# open for placement of other elements
for ii in i:
rv[ii] = None
# process elements in order of canonically decreasing multiplicity
take = sorted(ms.items(), key=lambda x:(x[1], x[0]))
yield from do(len(take) - 1)
rv[:] = [None]*n
def random_derangement(t, choice=None, strict=True):
"""Return a list of elements in which none are in the same positions
as they were originally. If an element fills more than half of the positions
then an error will be raised since no derangement is possible. To obtain
a derangement of as many items as possible--with some of the most numerous
remaining in their original positions--pass `strict=False`. To produce a
pseudorandom derangment, pass a pseudorandom selector like `choice` (see
below).
Examples
========
>>> from sympy.utilities.iterables import random_derangement
>>> t = 'SymPy: a CAS in pure Python'
>>> d = random_derangement(t)
>>> all(i != j for i, j in zip(d, t))
True
A predictable result can be obtained by using a pseudorandom
generator for the choice:
>>> from sympy.core.random import seed, choice as c
>>> seed(1)
>>> d = [''.join(random_derangement(t, c)) for i in range(5)]
>>> assert len(set(d)) != 1 # we got different values
By reseeding, the same sequence can be obtained:
>>> seed(1)
>>> d2 = [''.join(random_derangement(t, c)) for i in range(5)]
>>> assert d == d2
"""
if choice is None:
import secrets
choice = secrets.choice
def shuffle(rv):
'''Knuth shuffle'''
for i in range(len(rv) - 1, 0, -1):
x = choice(rv[:i + 1])
j = rv.index(x)
rv[i], rv[j] = rv[j], rv[i]
def pick(rv, n):
'''shuffle rv and return the first n values
'''
shuffle(rv)
return rv[:n]
ms = multiset(t)
tot = len(t)
ms = sorted(ms.items(), key=lambda x: x[1])
# if there are not enough spaces for the most
# plentiful element to move to then some of them
# will have to stay in place
M, mx = ms[-1]
n = len(t)
xs = 2*mx - tot
if xs > 0:
if strict:
raise ValueError('no derangement possible')
opts = [i for (i, c) in enumerate(t) if c == ms[-1][0]]
pick(opts, xs)
stay = sorted(opts[:xs])
rv = list(t)
for i in reversed(stay):
rv.pop(i)
rv = random_derangement(rv, choice)
for i in stay:
rv.insert(i, ms[-1][0])
return ''.join(rv) if type(t) is str else rv
# the normal derangement calculated from here
if n == len(ms):
# approx 1/3 will succeed
rv = list(t)
while True:
shuffle(rv)
if all(i != j for i,j in zip(rv, t)):
break
else:
# general case
rv = [None]*n
while True:
j = 0
while j > -len(ms): # do most numerous first
j -= 1
e, c = ms[j]
opts = [i for i in range(n) if rv[i] is None and t[i] != e]
if len(opts) < c:
for i in range(n):
rv[i] = None
break # try again
pick(opts, c)
for i in range(c):
rv[opts[i]] = e
else:
return rv
return rv
def _set_derangements(s):
"""
yield derangements of items in ``s`` which are assumed to contain
no repeated elements
"""
if len(s) < 2:
return
if len(s) == 2:
yield [s[1], s[0]]
return
if len(s) == 3:
yield [s[1], s[2], s[0]]
yield [s[2], s[0], s[1]]
return
for p in permutations(s):
if not any(i == j for i, j in zip(p, s)):
yield list(p)
def generate_derangements(s):
"""
Return unique derangements of the elements of iterable ``s``.
Examples
========
>>> from sympy.utilities.iterables import generate_derangements
>>> list(generate_derangements([0, 1, 2]))
[[1, 2, 0], [2, 0, 1]]
>>> list(generate_derangements([0, 1, 2, 2]))
[[2, 2, 0, 1], [2, 2, 1, 0]]
>>> list(generate_derangements([0, 1, 1]))
[]
See Also
========
sympy.functions.combinatorial.factorials.subfactorial
"""
if not has_dups(s):
yield from _set_derangements(s)
else:
for p in multiset_derangements(s):
yield list(p)
def necklaces(n, k, free=False):
"""
A routine to generate necklaces that may (free=True) or may not
(free=False) be turned over to be viewed. The "necklaces" returned
are comprised of ``n`` integers (beads) with ``k`` different
values (colors). Only unique necklaces are returned.
Examples
========
>>> from sympy.utilities.iterables import necklaces, bracelets
>>> def show(s, i):
... return ''.join(s[j] for j in i)
The "unrestricted necklace" is sometimes also referred to as a
"bracelet" (an object that can be turned over, a sequence that can
be reversed) and the term "necklace" is used to imply a sequence
that cannot be reversed. So ACB == ABC for a bracelet (rotate and
reverse) while the two are different for a necklace since rotation
alone cannot make the two sequences the same.
(mnemonic: Bracelets can be viewed Backwards, but Not Necklaces.)
>>> B = [show('ABC', i) for i in bracelets(3, 3)]
>>> N = [show('ABC', i) for i in necklaces(3, 3)]
>>> set(N) - set(B)
{'ACB'}
>>> list(necklaces(4, 2))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1),
(0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)]
>>> [show('.o', i) for i in bracelets(4, 2)]
['....', '...o', '..oo', '.o.o', '.ooo', 'oooo']
References
==========
.. [1] http://mathworld.wolfram.com/Necklace.html
"""
return uniq(minlex(i, directed=not free) for i in
variations(list(range(k)), n, repetition=True))
def bracelets(n, k):
"""Wrapper to necklaces to return a free (unrestricted) necklace."""
return necklaces(n, k, free=True)
def generate_oriented_forest(n):
"""
This algorithm generates oriented forests.
An oriented graph is a directed graph having no symmetric pair of directed
edges. A forest is an acyclic graph, i.e., it has no cycles. A forest can
also be described as a disjoint union of trees, which are graphs in which
any two vertices are connected by exactly one simple path.
Examples
========
>>> from sympy.utilities.iterables import generate_oriented_forest
>>> list(generate_oriented_forest(4))
[[0, 1, 2, 3], [0, 1, 2, 2], [0, 1, 2, 1], [0, 1, 2, 0], \
[0, 1, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]]
References
==========
.. [1] T. Beyer and S.M. Hedetniemi: constant time generation of
rooted trees, SIAM J. Computing Vol. 9, No. 4, November 1980
.. [2] https://stackoverflow.com/questions/1633833/oriented-forest-taocp-algorithm-in-python
"""
P = list(range(-1, n))
while True:
yield P[1:]
if P[n] > 0:
P[n] = P[P[n]]
else:
for p in range(n - 1, 0, -1):
if P[p] != 0:
target = P[p] - 1
for q in range(p - 1, 0, -1):
if P[q] == target:
break
offset = p - q
for i in range(p, n + 1):
P[i] = P[i - offset]
break
else:
break
def minlex(seq, directed=True, key=None):
r"""
Return the rotation of the sequence in which the lexically smallest
elements appear first, e.g. `cba \rightarrow acb`.
The sequence returned is a tuple, unless the input sequence is a string
in which case a string is returned.
If ``directed`` is False then the smaller of the sequence and the
reversed sequence is returned, e.g. `cba \rightarrow abc`.
If ``key`` is not None then it is used to extract a comparison key from each element in iterable.
Examples
========
>>> from sympy.combinatorics.polyhedron import minlex
>>> minlex((1, 2, 0))
(0, 1, 2)
>>> minlex((1, 0, 2))
(0, 2, 1)
>>> minlex((1, 0, 2), directed=False)
(0, 1, 2)
>>> minlex('11010011000', directed=True)
'00011010011'
>>> minlex('11010011000', directed=False)
'00011001011'
>>> minlex(('bb', 'aaa', 'c', 'a'))
('a', 'bb', 'aaa', 'c')
>>> minlex(('bb', 'aaa', 'c', 'a'), key=len)
('c', 'a', 'bb', 'aaa')
"""
from sympy.functions.elementary.miscellaneous import Id
if key is None: key = Id
best = rotate_left(seq, least_rotation(seq, key=key))
if not directed:
rseq = seq[::-1]
rbest = rotate_left(rseq, least_rotation(rseq, key=key))
best = min(best, rbest, key=key)
# Convert to tuple, unless we started with a string.
return tuple(best) if not isinstance(seq, str) else best
def runs(seq, op=gt):
"""Group the sequence into lists in which successive elements
all compare the same with the comparison operator, ``op``:
op(seq[i + 1], seq[i]) is True from all elements in a run.
Examples
========
>>> from sympy.utilities.iterables import runs
>>> from operator import ge
>>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2])
[[0, 1, 2], [2], [1, 4], [3], [2], [2]]
>>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2], op=ge)
[[0, 1, 2, 2], [1, 4], [3], [2, 2]]
"""
cycles = []
seq = iter(seq)
try:
run = [next(seq)]
except StopIteration:
return []
while True:
try:
ei = next(seq)
except StopIteration:
break
if op(ei, run[-1]):
run.append(ei)
continue
else:
cycles.append(run)
run = [ei]
if run:
cycles.append(run)
return cycles
def kbins(l, k, ordered=None):
"""
Return sequence ``l`` partitioned into ``k`` bins.
Examples
========
The default is to give the items in the same order, but grouped
into k partitions without any reordering:
>>> from sympy.utilities.iterables import kbins
>>> for p in kbins(list(range(5)), 2):
... print(p)
...
[[0], [1, 2, 3, 4]]
[[0, 1], [2, 3, 4]]
[[0, 1, 2], [3, 4]]
[[0, 1, 2, 3], [4]]
The ``ordered`` flag is either None (to give the simple partition
of the elements) or is a 2 digit integer indicating whether the order of
the bins and the order of the items in the bins matters. Given::
A = [[0], [1, 2]]
B = [[1, 2], [0]]
C = [[2, 1], [0]]
D = [[0], [2, 1]]
the following values for ``ordered`` have the shown meanings::
00 means A == B == C == D
01 means A == B
10 means A == D
11 means A == A
>>> for ordered_flag in [None, 0, 1, 10, 11]:
... print('ordered = %s' % ordered_flag)
... for p in kbins(list(range(3)), 2, ordered=ordered_flag):
... print(' %s' % p)
...
ordered = None
[[0], [1, 2]]
[[0, 1], [2]]
ordered = 0
[[0, 1], [2]]
[[0, 2], [1]]
[[0], [1, 2]]
ordered = 1
[[0], [1, 2]]
[[0], [2, 1]]
[[1], [0, 2]]
[[1], [2, 0]]
[[2], [0, 1]]
[[2], [1, 0]]
ordered = 10
[[0, 1], [2]]
[[2], [0, 1]]
[[0, 2], [1]]
[[1], [0, 2]]
[[0], [1, 2]]
[[1, 2], [0]]
ordered = 11
[[0], [1, 2]]
[[0, 1], [2]]
[[0], [2, 1]]
[[0, 2], [1]]
[[1], [0, 2]]
[[1, 0], [2]]
[[1], [2, 0]]
[[1, 2], [0]]
[[2], [0, 1]]
[[2, 0], [1]]
[[2], [1, 0]]
[[2, 1], [0]]
See Also
========
partitions, multiset_partitions
"""
def partition(lista, bins):
# EnricoGiampieri's partition generator from
# https://stackoverflow.com/questions/13131491/
# partition-n-items-into-k-bins-in-python-lazily
if len(lista) == 1 or bins == 1:
yield [lista]
elif len(lista) > 1 and bins > 1:
for i in range(1, len(lista)):
for part in partition(lista[i:], bins - 1):
if len([lista[:i]] + part) == bins:
yield [lista[:i]] + part
if ordered is None:
yield from partition(l, k)
elif ordered == 11:
for pl in multiset_permutations(l):
pl = list(pl)
yield from partition(pl, k)
elif ordered == 00:
yield from multiset_partitions(l, k)
elif ordered == 10:
for p in multiset_partitions(l, k):
for perm in permutations(p):
yield list(perm)
elif ordered == 1:
for kgot, p in partitions(len(l), k, size=True):
if kgot != k:
continue
for li in multiset_permutations(l):
rv = []
i = j = 0
li = list(li)
for size, multiplicity in sorted(p.items()):
for m in range(multiplicity):
j = i + size
rv.append(li[i: j])
i = j
yield rv
else:
raise ValueError(
'ordered must be one of 00, 01, 10 or 11, not %s' % ordered)
def permute_signs(t):
"""Return iterator in which the signs of non-zero elements
of t are permuted.
Examples
========
>>> from sympy.utilities.iterables import permute_signs
>>> list(permute_signs((0, 1, 2)))
[(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2)]
"""
for signs in product(*[(1, -1)]*(len(t) - t.count(0))):
signs = list(signs)
yield type(t)([i*signs.pop() if i else i for i in t])
def signed_permutations(t):
"""Return iterator in which the signs of non-zero elements
of t and the order of the elements are permuted.
Examples
========
>>> from sympy.utilities.iterables import signed_permutations
>>> list(signed_permutations((0, 1, 2)))
[(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2), (0, 2, 1),
(0, -2, 1), (0, 2, -1), (0, -2, -1), (1, 0, 2), (-1, 0, 2),
(1, 0, -2), (-1, 0, -2), (1, 2, 0), (-1, 2, 0), (1, -2, 0),
(-1, -2, 0), (2, 0, 1), (-2, 0, 1), (2, 0, -1), (-2, 0, -1),
(2, 1, 0), (-2, 1, 0), (2, -1, 0), (-2, -1, 0)]
"""
return (type(t)(i) for j in permutations(t)
for i in permute_signs(j))
def rotations(s, dir=1):
"""Return a generator giving the items in s as list where
each subsequent list has the items rotated to the left (default)
or right (``dir=-1``) relative to the previous list.
Examples
========
>>> from sympy import rotations
>>> list(rotations([1,2,3]))
[[1, 2, 3], [2, 3, 1], [3, 1, 2]]
>>> list(rotations([1,2,3], -1))
[[1, 2, 3], [3, 1, 2], [2, 3, 1]]
"""
seq = list(s)
for i in range(len(seq)):
yield seq
seq = rotate_left(seq, dir)
def roundrobin(*iterables):
"""roundrobin recipe taken from itertools documentation:
https://docs.python.org/3/library/itertools.html#recipes
roundrobin('ABC', 'D', 'EF') --> A D E B F C
Recipe credited to George Sakkis
"""
nexts = cycle(iter(it).__next__ for it in iterables)
pending = len(iterables)
while pending:
try:
for nxt in nexts:
yield nxt()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
class NotIterable:
"""
Use this as mixin when creating a class which is not supposed to
return true when iterable() is called on its instances because
calling list() on the instance, for example, would result in
an infinite loop.
"""
pass
def iterable(i, exclude=(str, dict, NotIterable)):
"""
Return a boolean indicating whether ``i`` is SymPy iterable.
True also indicates that the iterator is finite, e.g. you can
call list(...) on the instance.
When SymPy is working with iterables, it is almost always assuming
that the iterable is not a string or a mapping, so those are excluded
by default. If you want a pure Python definition, make exclude=None. To
exclude multiple items, pass them as a tuple.
You can also set the _iterable attribute to True or False on your class,
which will override the checks here, including the exclude test.
As a rule of thumb, some SymPy functions use this to check if they should
recursively map over an object. If an object is technically iterable in
the Python sense but does not desire this behavior (e.g., because its
iteration is not finite, or because iteration might induce an unwanted
computation), it should disable it by setting the _iterable attribute to False.
See also: is_sequence
Examples
========
>>> from sympy.utilities.iterables import iterable
>>> from sympy import Tuple
>>> things = [[1], (1,), set([1]), Tuple(1), (j for j in [1, 2]), {1:2}, '1', 1]
>>> for i in things:
... print('%s %s' % (iterable(i), type(i)))
True <... 'list'>
True <... 'tuple'>
True <... 'set'>
True <class 'sympy.core.containers.Tuple'>
True <... 'generator'>
False <... 'dict'>
False <... 'str'>
False <... 'int'>
>>> iterable({}, exclude=None)
True
>>> iterable({}, exclude=str)
True
>>> iterable("no", exclude=str)
False
"""
if hasattr(i, '_iterable'):
return i._iterable
try:
iter(i)
except TypeError:
return False
if exclude:
return not isinstance(i, exclude)
return True
def is_sequence(i, include=None):
"""
Return a boolean indicating whether ``i`` is a sequence in the SymPy
sense. If anything that fails the test below should be included as
being a sequence for your application, set 'include' to that object's
type; multiple types should be passed as a tuple of types.
Note: although generators can generate a sequence, they often need special
handling to make sure their elements are captured before the generator is
exhausted, so these are not included by default in the definition of a
sequence.
See also: iterable
Examples
========
>>> from sympy.utilities.iterables import is_sequence
>>> from types import GeneratorType
>>> is_sequence([])
True
>>> is_sequence(set())
False
>>> is_sequence('abc')
False
>>> is_sequence('abc', include=str)
True
>>> generator = (c for c in 'abc')
>>> is_sequence(generator)
False
>>> is_sequence(generator, include=(str, GeneratorType))
True
"""
return (hasattr(i, '__getitem__') and
iterable(i) or
bool(include) and
isinstance(i, include))
@deprecated(
"""
Using postorder_traversal from the sympy.utilities.iterables submodule is
deprecated.
Instead, use postorder_traversal from the top-level sympy namespace, like
sympy.postorder_traversal
""",
deprecated_since_version="1.10",
active_deprecations_target="deprecated-traversal-functions-moved")
def postorder_traversal(node, keys=None):
from sympy.core.traversal import postorder_traversal as _postorder_traversal
return _postorder_traversal(node, keys=keys)
@deprecated(
"""
Using interactive_traversal from the sympy.utilities.iterables submodule
is deprecated.
Instead, use interactive_traversal from the top-level sympy namespace,
like
sympy.interactive_traversal
""",
deprecated_since_version="1.10",
active_deprecations_target="deprecated-traversal-functions-moved")
def interactive_traversal(expr):
from sympy.interactive.traversal import interactive_traversal as _interactive_traversal
return _interactive_traversal(expr)
@deprecated(
"""
Importing default_sort_key from sympy.utilities.iterables is deprecated.
Use from sympy import default_sort_key instead.
""",
deprecated_since_version="1.10",
active_deprecations_target="deprecated-sympy-core-compatibility",
)
def default_sort_key(*args, **kwargs):
from sympy import default_sort_key as _default_sort_key
return _default_sort_key(*args, **kwargs)
@deprecated(
"""
Importing default_sort_key from sympy.utilities.iterables is deprecated.
Use from sympy import default_sort_key instead.
""",
deprecated_since_version="1.10",
active_deprecations_target="deprecated-sympy-core-compatibility",
)
def ordered(*args, **kwargs):
from sympy import ordered as _ordered
return _ordered(*args, **kwargs)
|
8589c336214d9c38d07171b4e3fde5ccf15b533ea2d00519dab67f444095a03a | """
.. deprecated:: 1.6
sympy.utilities.runtests has been renamed to sympy.testing.runtests.
"""
from sympy.utilities.exceptions import sympy_deprecation_warning
sympy_deprecation_warning("The sympy.utilities.runtests submodule is deprecated. Use sympy.testing.runtests instead.",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-sympy-utilities-submodules")
from sympy.testing.runtests import * # noqa:F401
|
698517fe68264327d174c8c4396687339d3a099e9650ad1e16e7b0d2f153c11b | """
.. deprecated:: 1.6
sympy.utilities.randtest has been renamed to sympy.core.random.
"""
from sympy.utilities.exceptions import sympy_deprecation_warning
sympy_deprecation_warning("The sympy.utilities.randtest submodule is deprecated. Use sympy.core.random instead.",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-sympy-utilities-submodules")
from sympy.core.random import * # noqa:F401
|
e03bb9557cb8a4a9ed6c44875cb1587743b007663b40beeb3a8027ffe40f35d4 | """Miscellaneous stuff that does not really fit anywhere else."""
from typing import List
import operator
import sys
import os
import re as _re
import struct
from textwrap import fill, dedent
class Undecidable(ValueError):
# an error to be raised when a decision cannot be made definitively
# where a definitive answer is needed
pass
def filldedent(s, w=70, **kwargs):
"""
Strips leading and trailing empty lines from a copy of ``s``, then dedents,
fills and returns it.
Empty line stripping serves to deal with docstrings like this one that
start with a newline after the initial triple quote, inserting an empty
line at the beginning of the string.
Additional keyword arguments will be passed to ``textwrap.fill()``.
See Also
========
strlines, rawlines
"""
return '\n' + fill(dedent(str(s)).strip('\n'), width=w, **kwargs)
def strlines(s, c=64, short=False):
"""Return a cut-and-pastable string that, when printed, is
equivalent to the input. The lines will be surrounded by
parentheses and no line will be longer than c (default 64)
characters. If the line contains newlines characters, the
`rawlines` result will be returned. If ``short`` is True
(default is False) then if there is one line it will be
returned without bounding parentheses.
Examples
========
>>> from sympy.utilities.misc import strlines
>>> q = 'this is a long string that should be broken into shorter lines'
>>> print(strlines(q, 40))
(
'this is a long string that should be b'
'roken into shorter lines'
)
>>> q == (
... 'this is a long string that should be b'
... 'roken into shorter lines'
... )
True
See Also
========
filldedent, rawlines
"""
if not isinstance(s, str):
raise ValueError('expecting string input')
if '\n' in s:
return rawlines(s)
q = '"' if repr(s).startswith('"') else "'"
q = (q,)*2
if '\\' in s: # use r-string
m = '(\nr%s%%s%s\n)' % q
j = '%s\nr%s' % q
c -= 3
else:
m = '(\n%s%%s%s\n)' % q
j = '%s\n%s' % q
c -= 2
out = []
while s:
out.append(s[:c])
s=s[c:]
if short and len(out) == 1:
return (m % out[0]).splitlines()[1] # strip bounding (\n...\n)
return m % j.join(out)
def rawlines(s):
"""Return a cut-and-pastable string that, when printed, is equivalent
to the input. Use this when there is more than one line in the
string. The string returned is formatted so it can be indented
nicely within tests; in some cases it is wrapped in the dedent
function which has to be imported from textwrap.
Examples
========
Note: because there are characters in the examples below that need
to be escaped because they are themselves within a triple quoted
docstring, expressions below look more complicated than they would
be if they were printed in an interpreter window.
>>> from sympy.utilities.misc import rawlines
>>> from sympy import TableForm
>>> s = str(TableForm([[1, 10]], headings=(None, ['a', 'bee'])))
>>> print(rawlines(s))
(
'a bee\\n'
'-----\\n'
'1 10 '
)
>>> print(rawlines('''this
... that'''))
dedent('''\\
this
that''')
>>> print(rawlines('''this
... that
... '''))
dedent('''\\
this
that
''')
>>> s = \"\"\"this
... is a triple '''
... \"\"\"
>>> print(rawlines(s))
dedent(\"\"\"\\
this
is a triple '''
\"\"\")
>>> print(rawlines('''this
... that
... '''))
(
'this\\n'
'that\\n'
' '
)
See Also
========
filldedent, strlines
"""
lines = s.split('\n')
if len(lines) == 1:
return repr(lines[0])
triple = ["'''" in s, '"""' in s]
if any(li.endswith(' ') for li in lines) or '\\' in s or all(triple):
rv = []
# add on the newlines
trailing = s.endswith('\n')
last = len(lines) - 1
for i, li in enumerate(lines):
if i != last or trailing:
rv.append(repr(li + '\n'))
else:
rv.append(repr(li))
return '(\n %s\n)' % '\n '.join(rv)
else:
rv = '\n '.join(lines)
if triple[0]:
return 'dedent("""\\\n %s""")' % rv
else:
return "dedent('''\\\n %s''')" % rv
ARCH = str(struct.calcsize('P') * 8) + "-bit"
# XXX: PyPy does not support hash randomization
HASH_RANDOMIZATION = getattr(sys.flags, 'hash_randomization', False)
_debug_tmp = [] # type: List[str]
_debug_iter = 0
def debug_decorator(func):
"""If SYMPY_DEBUG is True, it will print a nice execution tree with
arguments and results of all decorated functions, else do nothing.
"""
from sympy import SYMPY_DEBUG
if not SYMPY_DEBUG:
return func
def maketree(f, *args, **kw):
global _debug_tmp
global _debug_iter
oldtmp = _debug_tmp
_debug_tmp = []
_debug_iter += 1
def tree(subtrees):
def indent(s, variant=1):
x = s.split("\n")
r = "+-%s\n" % x[0]
for a in x[1:]:
if a == "":
continue
if variant == 1:
r += "| %s\n" % a
else:
r += " %s\n" % a
return r
if len(subtrees) == 0:
return ""
f = []
for a in subtrees[:-1]:
f.append(indent(a))
f.append(indent(subtrees[-1], 2))
return ''.join(f)
# If there is a bug and the algorithm enters an infinite loop, enable the
# following lines. It will print the names and parameters of all major functions
# that are called, *before* they are called
#from functools import reduce
#print("%s%s %s%s" % (_debug_iter, reduce(lambda x, y: x + y, \
# map(lambda x: '-', range(1, 2 + _debug_iter))), f.__name__, args))
r = f(*args, **kw)
_debug_iter -= 1
s = "%s%s = %s\n" % (f.__name__, args, r)
if _debug_tmp != []:
s += tree(_debug_tmp)
_debug_tmp = oldtmp
_debug_tmp.append(s)
if _debug_iter == 0:
print(_debug_tmp[0])
_debug_tmp = []
return r
def decorated(*args, **kwargs):
return maketree(func, *args, **kwargs)
return decorated
def debug(*args):
"""
Print ``*args`` if SYMPY_DEBUG is True, else do nothing.
"""
from sympy import SYMPY_DEBUG
if SYMPY_DEBUG:
print(*args, file=sys.stderr)
def find_executable(executable, path=None):
"""Try to find 'executable' in the directories listed in 'path' (a
string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']). Returns the complete filename or None if not
found
"""
from .exceptions import sympy_deprecation_warning
sympy_deprecation_warning(
"""
sympy.utilities.misc.find_executable() is deprecated. Use the standard
library shutil.which() function instead.
""",
deprecated_since_version="1.7",
active_deprecations_target="deprecated-find-executable",
)
if path is None:
path = os.environ['PATH']
paths = path.split(os.pathsep)
extlist = ['']
if os.name == 'os2':
(base, ext) = os.path.splitext(executable)
# executable files on OS/2 can have an arbitrary extension, but
# .exe is automatically appended if no dot is present in the name
if not ext:
executable = executable + ".exe"
elif sys.platform == 'win32':
pathext = os.environ['PATHEXT'].lower().split(os.pathsep)
(base, ext) = os.path.splitext(executable)
if ext.lower() not in pathext:
extlist = pathext
for ext in extlist:
execname = executable + ext
if os.path.isfile(execname):
return execname
else:
for p in paths:
f = os.path.join(p, execname)
if os.path.isfile(f):
return f
return None
def func_name(x, short=False):
"""Return function name of `x` (if defined) else the `type(x)`.
If short is True and there is a shorter alias for the result,
return the alias.
Examples
========
>>> from sympy.utilities.misc import func_name
>>> from sympy import Matrix
>>> from sympy.abc import x
>>> func_name(Matrix.eye(3))
'MutableDenseMatrix'
>>> func_name(x < 1)
'StrictLessThan'
>>> func_name(x < 1, short=True)
'Lt'
"""
alias = {
'GreaterThan': 'Ge',
'StrictGreaterThan': 'Gt',
'LessThan': 'Le',
'StrictLessThan': 'Lt',
'Equality': 'Eq',
'Unequality': 'Ne',
}
typ = type(x)
if str(typ).startswith("<type '"):
typ = str(typ).split("'")[1].split("'")[0]
elif str(typ).startswith("<class '"):
typ = str(typ).split("'")[1].split("'")[0]
rv = getattr(getattr(x, 'func', x), '__name__', typ)
if '.' in rv:
rv = rv.split('.')[-1]
if short:
rv = alias.get(rv, rv)
return rv
def _replace(reps):
"""Return a function that can make the replacements, given in
``reps``, on a string. The replacements should be given as mapping.
Examples
========
>>> from sympy.utilities.misc import _replace
>>> f = _replace(dict(foo='bar', d='t'))
>>> f('food')
'bart'
>>> f = _replace({})
>>> f('food')
'food'
"""
if not reps:
return lambda x: x
D = lambda match: reps[match.group(0)]
pattern = _re.compile("|".join(
[_re.escape(k) for k, v in reps.items()]), _re.M)
return lambda string: pattern.sub(D, string)
def replace(string, *reps):
"""Return ``string`` with all keys in ``reps`` replaced with
their corresponding values, longer strings first, irrespective
of the order they are given. ``reps`` may be passed as tuples
or a single mapping.
Examples
========
>>> from sympy.utilities.misc import replace
>>> replace('foo', {'oo': 'ar', 'f': 'b'})
'bar'
>>> replace("spamham sha", ("spam", "eggs"), ("sha","md5"))
'eggsham md5'
There is no guarantee that a unique answer will be
obtained if keys in a mapping overlap (i.e. are the same
length and have some identical sequence at the
beginning/end):
>>> reps = [
... ('ab', 'x'),
... ('bc', 'y')]
>>> replace('abc', *reps) in ('xc', 'ay')
True
References
==========
.. [1] https://stackoverflow.com/questions/6116978/python-replace-multiple-strings
"""
if len(reps) == 1:
kv = reps[0]
if isinstance(kv, dict):
reps = kv
else:
return string.replace(*kv)
else:
reps = dict(reps)
return _replace(reps)(string)
def translate(s, a, b=None, c=None):
"""Return ``s`` where characters have been replaced or deleted.
SYNTAX
======
translate(s, None, deletechars):
all characters in ``deletechars`` are deleted
translate(s, map [,deletechars]):
all characters in ``deletechars`` (if provided) are deleted
then the replacements defined by map are made; if the keys
of map are strings then the longer ones are handled first.
Multicharacter deletions should have a value of ''.
translate(s, oldchars, newchars, deletechars)
all characters in ``deletechars`` are deleted
then each character in ``oldchars`` is replaced with the
corresponding character in ``newchars``
Examples
========
>>> from sympy.utilities.misc import translate
>>> abc = 'abc'
>>> translate(abc, None, 'a')
'bc'
>>> translate(abc, {'a': 'x'}, 'c')
'xb'
>>> translate(abc, {'abc': 'x', 'a': 'y'})
'x'
>>> translate('abcd', 'ac', 'AC', 'd')
'AbC'
There is no guarantee that a unique answer will be
obtained if keys in a mapping overlap are the same
length and have some identical sequences at the
beginning/end:
>>> translate(abc, {'ab': 'x', 'bc': 'y'}) in ('xc', 'ay')
True
"""
mr = {}
if a is None:
if c is not None:
raise ValueError('c should be None when a=None is passed, instead got %s' % c)
if b is None:
return s
c = b
a = b = ''
else:
if isinstance(a, dict):
short = {}
for k in list(a.keys()):
if len(k) == 1 and len(a[k]) == 1:
short[k] = a.pop(k)
mr = a
c = b
if short:
a, b = [''.join(i) for i in list(zip(*short.items()))]
else:
a = b = ''
elif len(a) != len(b):
raise ValueError('oldchars and newchars have different lengths')
if c:
val = str.maketrans('', '', c)
s = s.translate(val)
s = replace(s, mr)
n = str.maketrans(a, b)
return s.translate(n)
def ordinal(num):
"""Return ordinal number string of num, e.g. 1 becomes 1st.
"""
# modified from https://codereview.stackexchange.com/questions/41298/producing-ordinal-numbers
n = as_int(num)
k = abs(n) % 100
if 11 <= k <= 13:
suffix = 'th'
elif k % 10 == 1:
suffix = 'st'
elif k % 10 == 2:
suffix = 'nd'
elif k % 10 == 3:
suffix = 'rd'
else:
suffix = 'th'
return str(n) + suffix
def as_int(n, strict=True):
"""
Convert the argument to a builtin integer.
The return value is guaranteed to be equal to the input. ValueError is
raised if the input has a non-integral value. When ``strict`` is True, this
uses `__index__ <https://docs.python.org/3/reference/datamodel.html#object.__index__>`_
and when it is False it uses ``int``.
Examples
========
>>> from sympy.utilities.misc import as_int
>>> from sympy import sqrt, S
The function is primarily concerned with sanitizing input for
functions that need to work with builtin integers, so anything that
is unambiguously an integer should be returned as an int:
>>> as_int(S(3))
3
Floats, being of limited precision, are not assumed to be exact and
will raise an error unless the ``strict`` flag is False. This
precision issue becomes apparent for large floating point numbers:
>>> big = 1e23
>>> type(big) is float
True
>>> big == int(big)
True
>>> as_int(big)
Traceback (most recent call last):
...
ValueError: ... is not an integer
>>> as_int(big, strict=False)
99999999999999991611392
Input that might be a complex representation of an integer value is
also rejected by default:
>>> one = sqrt(3 + 2*sqrt(2)) - sqrt(2)
>>> int(one) == 1
True
>>> as_int(one)
Traceback (most recent call last):
...
ValueError: ... is not an integer
"""
if strict:
try:
if isinstance(n, bool):
raise TypeError
return operator.index(n)
except TypeError:
raise ValueError('%s is not an integer' % (n,))
else:
try:
result = int(n)
except TypeError:
raise ValueError('%s is not an integer' % (n,))
if n != result:
raise ValueError('%s is not an integer' % (n,))
return result
|
c8e8dbb3dd2c12d55cd34619caf7b26e54fcce4c23e28ef4fd19ae10a74aabfb | """
.. deprecated:: 1.6
sympy.utilities.tmpfiles has been renamed to sympy.testing.tmpfiles.
"""
from sympy.utilities.exceptions import sympy_deprecation_warning
sympy_deprecation_warning("The sympy.utilities.tmpfiles submodule is deprecated. Use sympy.testing.tmpfiles instead.",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-sympy-utilities-submodules")
from sympy.testing.tmpfiles import * # noqa:F401
|
653cbab7a1ecd8bfd7f8772ece250a79e93df86eecf107445cff2634a324eac7 | """
.. deprecated:: 1.7
cxxcode.py was deprecated and renamed to cxx.py. This is a shim file to
provide backwards compatibility.
"""
from sympy.utilities.exceptions import sympy_deprecation_warning
sympy_deprecation_warning(
"""
The sympy.printing.cxxcode submodule is deprecated. It has been renamed to
sympy.printing.cxx.
""",
deprecated_since_version="1.7",
active_deprecations_target="deprecated-printing-code-submodules",
)
from .cxx import (cxxcode, reserved, CXX98CodePrinter, # noqa:F401
CXX11CodePrinter, CXX17CodePrinter, cxx_code_printers)
|
d656f467f75c511e66655cd61403f91d7f4622ad3eff24c343177f5ed5461cdd | from sympy.core import S
from sympy.core.function import Lambda
from sympy.core.power import Pow
from .pycode import PythonCodePrinter, _known_functions_math, _print_known_const, _print_known_func, _unpack_integral_limits, ArrayPrinter
from .codeprinter import CodePrinter
_not_in_numpy = 'erf erfc factorial gamma loggamma'.split()
_in_numpy = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_numpy]
_known_functions_numpy = dict(_in_numpy, **{
'acos': 'arccos',
'acosh': 'arccosh',
'asin': 'arcsin',
'asinh': 'arcsinh',
'atan': 'arctan',
'atan2': 'arctan2',
'atanh': 'arctanh',
'exp2': 'exp2',
'sign': 'sign',
'logaddexp': 'logaddexp',
'logaddexp2': 'logaddexp2',
})
_known_constants_numpy = {
'Exp1': 'e',
'Pi': 'pi',
'EulerGamma': 'euler_gamma',
'NaN': 'nan',
'Infinity': 'PINF',
'NegativeInfinity': 'NINF'
}
_numpy_known_functions = {k: 'numpy.' + v for k, v in _known_functions_numpy.items()}
_numpy_known_constants = {k: 'numpy.' + v for k, v in _known_constants_numpy.items()}
class NumPyPrinter(ArrayPrinter, PythonCodePrinter):
"""
Numpy printer which handles vectorized piecewise functions,
logical operators, etc.
"""
_module = 'numpy'
_kf = _numpy_known_functions
_kc = _numpy_known_constants
def __init__(self, settings=None):
"""
`settings` is passed to CodePrinter.__init__()
`module` specifies the array module to use, currently 'NumPy' or 'CuPy'
"""
self.language = "Python with {}".format(self._module)
self.printmethod = "_{}code".format(self._module)
self._kf = {**PythonCodePrinter._kf, **self._kf}
super().__init__(settings=settings)
def _print_seq(self, seq):
"General sequence printer: converts to tuple"
# Print tuples here instead of lists because numba supports
# tuples in nopython mode.
delimiter=', '
return '({},)'.format(delimiter.join(self._print(item) for item in seq))
def _print_MatMul(self, expr):
"Matrix multiplication printer"
if expr.as_coeff_matrices()[0] is not S.One:
expr_list = expr.as_coeff_matrices()[1]+[(expr.as_coeff_matrices()[0])]
return '({})'.format(').dot('.join(self._print(i) for i in expr_list))
return '({})'.format(').dot('.join(self._print(i) for i in expr.args))
def _print_MatPow(self, expr):
"Matrix power printer"
return '{}({}, {})'.format(self._module_format(self._module + '.linalg.matrix_power'),
self._print(expr.args[0]), self._print(expr.args[1]))
def _print_Inverse(self, expr):
"Matrix inverse printer"
return '{}({})'.format(self._module_format(self._module + '.linalg.inv'),
self._print(expr.args[0]))
def _print_DotProduct(self, expr):
# DotProduct allows any shape order, but numpy.dot does matrix
# multiplication, so we have to make sure it gets 1 x n by n x 1.
arg1, arg2 = expr.args
if arg1.shape[0] != 1:
arg1 = arg1.T
if arg2.shape[1] != 1:
arg2 = arg2.T
return "%s(%s, %s)" % (self._module_format(self._module + '.dot'),
self._print(arg1),
self._print(arg2))
def _print_MatrixSolve(self, expr):
return "%s(%s, %s)" % (self._module_format(self._module + '.linalg.solve'),
self._print(expr.matrix),
self._print(expr.vector))
def _print_ZeroMatrix(self, expr):
return '{}({})'.format(self._module_format(self._module + '.zeros'),
self._print(expr.shape))
def _print_OneMatrix(self, expr):
return '{}({})'.format(self._module_format(self._module + '.ones'),
self._print(expr.shape))
def _print_FunctionMatrix(self, expr):
from sympy.abc import i, j
lamda = expr.lamda
if not isinstance(lamda, Lambda):
lamda = Lambda((i, j), lamda(i, j))
return '{}(lambda {}: {}, {})'.format(self._module_format(self._module + '.fromfunction'),
', '.join(self._print(arg) for arg in lamda.args[0]),
self._print(lamda.args[1]), self._print(expr.shape))
def _print_HadamardProduct(self, expr):
func = self._module_format(self._module + '.multiply')
return ''.join('{}({}, '.format(func, self._print(arg)) \
for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),
')' * (len(expr.args) - 1))
def _print_KroneckerProduct(self, expr):
func = self._module_format(self._module + '.kron')
return ''.join('{}({}, '.format(func, self._print(arg)) \
for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),
')' * (len(expr.args) - 1))
def _print_Adjoint(self, expr):
return '{}({}({}))'.format(
self._module_format(self._module + '.conjugate'),
self._module_format(self._module + '.transpose'),
self._print(expr.args[0]))
def _print_DiagonalOf(self, expr):
vect = '{}({})'.format(
self._module_format(self._module + '.diag'),
self._print(expr.arg))
return '{}({}, (-1, 1))'.format(
self._module_format(self._module + '.reshape'), vect)
def _print_DiagMatrix(self, expr):
return '{}({})'.format(self._module_format(self._module + '.diagflat'),
self._print(expr.args[0]))
def _print_DiagonalMatrix(self, expr):
return '{}({}, {}({}, {}))'.format(self._module_format(self._module + '.multiply'),
self._print(expr.arg), self._module_format(self._module + '.eye'),
self._print(expr.shape[0]), self._print(expr.shape[1]))
def _print_Piecewise(self, expr):
"Piecewise function printer"
from sympy.logic.boolalg import ITE, simplify_logic
def print_cond(cond):
""" Problem having an ITE in the cond. """
if cond.has(ITE):
return self._print(simplify_logic(cond))
else:
return self._print(cond)
exprs = '[{}]'.format(','.join(self._print(arg.expr) for arg in expr.args))
conds = '[{}]'.format(','.join(print_cond(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.
return '{}({}, {}, default={})'.format(
self._module_format(self._module + '.select'), conds, exprs,
self._print(S.NaN))
def _print_Relational(self, expr):
"Relational printer for Equality and Unequality"
op = {
'==' :'equal',
'!=' :'not_equal',
'<' :'less',
'<=' :'less_equal',
'>' :'greater',
'>=' :'greater_equal',
}
if expr.rel_op in op:
lhs = self._print(expr.lhs)
rhs = self._print(expr.rhs)
return '{op}({lhs}, {rhs})'.format(op=self._module_format(self._module + '.'+op[expr.rel_op]),
lhs=lhs, rhs=rhs)
return super()._print_Relational(expr)
def _print_And(self, expr):
"Logical And printer"
# We have to override LambdaPrinter because it uses Python 'and' keyword.
# If LambdaPrinter didn't define it, we could use StrPrinter's
# version of the function and add 'logical_and' to NUMPY_TRANSLATIONS.
return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_and'), ','.join(self._print(i) for i in expr.args))
def _print_Or(self, expr):
"Logical Or printer"
# We have to override LambdaPrinter because it uses Python 'or' keyword.
# If LambdaPrinter didn't define it, we could use StrPrinter's
# version of the function and add 'logical_or' to NUMPY_TRANSLATIONS.
return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_or'), ','.join(self._print(i) for i in expr.args))
def _print_Not(self, expr):
"Logical Not printer"
# We have to override LambdaPrinter because it uses Python 'not' keyword.
# If LambdaPrinter didn't define it, we would still have to define our
# own because StrPrinter doesn't define it.
return '{}({})'.format(self._module_format(self._module + '.logical_not'), ','.join(self._print(i) for i in expr.args))
def _print_Pow(self, expr, rational=False):
# XXX Workaround for negative integer power error
if expr.exp.is_integer and expr.exp.is_negative:
expr = Pow(expr.base, expr.exp.evalf(), evaluate=False)
return self._hprint_Pow(expr, rational=rational, sqrt=self._module + '.sqrt')
def _print_Min(self, expr):
return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amin'), ','.join(self._print(i) for i in expr.args))
def _print_Max(self, expr):
return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amax'), ','.join(self._print(i) for i in expr.args))
def _print_arg(self, expr):
return "%s(%s)" % (self._module_format(self._module + '.angle'), self._print(expr.args[0]))
def _print_im(self, expr):
return "%s(%s)" % (self._module_format(self._module + '.imag'), self._print(expr.args[0]))
def _print_Mod(self, expr):
return "%s(%s)" % (self._module_format(self._module + '.mod'), ', '.join(
map(lambda arg: self._print(arg), expr.args)))
def _print_re(self, expr):
return "%s(%s)" % (self._module_format(self._module + '.real'), self._print(expr.args[0]))
def _print_sinc(self, expr):
return "%s(%s)" % (self._module_format(self._module + '.sinc'), self._print(expr.args[0]/S.Pi))
def _print_MatrixBase(self, expr):
func = self.known_functions.get(expr.__class__.__name__, None)
if func is None:
func = self._module_format(self._module + '.array')
return "%s(%s)" % (func, self._print(expr.tolist()))
def _print_Identity(self, expr):
shape = expr.shape
if all(dim.is_Integer for dim in shape):
return "%s(%s)" % (self._module_format(self._module + '.eye'), self._print(expr.shape[0]))
else:
raise NotImplementedError("Symbolic matrix dimensions are not yet supported for identity matrices")
def _print_BlockMatrix(self, expr):
return '{}({})'.format(self._module_format(self._module + '.block'),
self._print(expr.args[0].tolist()))
def _print_NDimArray(self, expr):
if len(expr.shape) == 1:
return self._module + '.array(' + self._print(expr.args[0]) + ')'
if len(expr.shape) == 2:
return self._print(expr.tomatrix())
# Should be possible to extend to more dimensions
return CodePrinter._print_not_supported(self, expr)
_add = "add"
_einsum = "einsum"
_transpose = "transpose"
_ones = "ones"
_zeros = "zeros"
_print_lowergamma = CodePrinter._print_not_supported
_print_uppergamma = CodePrinter._print_not_supported
_print_fresnelc = CodePrinter._print_not_supported
_print_fresnels = CodePrinter._print_not_supported
for func in _numpy_known_functions:
setattr(NumPyPrinter, f'_print_{func}', _print_known_func)
for const in _numpy_known_constants:
setattr(NumPyPrinter, f'_print_{const}', _print_known_const)
_known_functions_scipy_special = {
'erf': 'erf',
'erfc': 'erfc',
'besselj': 'jv',
'bessely': 'yv',
'besseli': 'iv',
'besselk': 'kv',
'cosm1': 'cosm1',
'factorial': 'factorial',
'gamma': 'gamma',
'loggamma': 'gammaln',
'digamma': 'psi',
'RisingFactorial': 'poch',
'jacobi': 'eval_jacobi',
'gegenbauer': 'eval_gegenbauer',
'chebyshevt': 'eval_chebyt',
'chebyshevu': 'eval_chebyu',
'legendre': 'eval_legendre',
'hermite': 'eval_hermite',
'laguerre': 'eval_laguerre',
'assoc_laguerre': 'eval_genlaguerre',
'beta': 'beta',
'LambertW' : 'lambertw',
}
_known_constants_scipy_constants = {
'GoldenRatio': 'golden_ratio',
'Pi': 'pi',
}
_scipy_known_functions = {k : "scipy.special." + v for k, v in _known_functions_scipy_special.items()}
_scipy_known_constants = {k : "scipy.constants." + v for k, v in _known_constants_scipy_constants.items()}
class SciPyPrinter(NumPyPrinter):
_kf = {**NumPyPrinter._kf, **_scipy_known_functions}
_kc = {**NumPyPrinter._kc, **_scipy_known_constants}
def __init__(self, settings=None):
super().__init__(settings=settings)
self.language = "Python with SciPy and NumPy"
def _print_SparseRepMatrix(self, expr):
i, j, data = [], [], []
for (r, c), v in expr.todok().items():
i.append(r)
j.append(c)
data.append(v)
return "{name}(({data}, ({i}, {j})), shape={shape})".format(
name=self._module_format('scipy.sparse.coo_matrix'),
data=data, i=i, j=j, shape=expr.shape
)
_print_ImmutableSparseMatrix = _print_SparseRepMatrix
# SciPy's lpmv has a different order of arguments from assoc_legendre
def _print_assoc_legendre(self, expr):
return "{0}({2}, {1}, {3})".format(
self._module_format('scipy.special.lpmv'),
self._print(expr.args[0]),
self._print(expr.args[1]),
self._print(expr.args[2]))
def _print_lowergamma(self, expr):
return "{0}({2})*{1}({2}, {3})".format(
self._module_format('scipy.special.gamma'),
self._module_format('scipy.special.gammainc'),
self._print(expr.args[0]),
self._print(expr.args[1]))
def _print_uppergamma(self, expr):
return "{0}({2})*{1}({2}, {3})".format(
self._module_format('scipy.special.gamma'),
self._module_format('scipy.special.gammaincc'),
self._print(expr.args[0]),
self._print(expr.args[1]))
def _print_betainc(self, expr):
betainc = self._module_format('scipy.special.betainc')
beta = self._module_format('scipy.special.beta')
args = [self._print(arg) for arg in expr.args]
return f"({betainc}({args[0]}, {args[1]}, {args[3]}) - {betainc}({args[0]}, {args[1]}, {args[2]})) \
* {beta}({args[0]}, {args[1]})"
def _print_betainc_regularized(self, expr):
return "{0}({1}, {2}, {4}) - {0}({1}, {2}, {3})".format(
self._module_format('scipy.special.betainc'),
self._print(expr.args[0]),
self._print(expr.args[1]),
self._print(expr.args[2]),
self._print(expr.args[3]))
def _print_fresnels(self, expr):
return "{}({})[0]".format(
self._module_format("scipy.special.fresnel"),
self._print(expr.args[0]))
def _print_fresnelc(self, expr):
return "{}({})[1]".format(
self._module_format("scipy.special.fresnel"),
self._print(expr.args[0]))
def _print_airyai(self, expr):
return "{}({})[0]".format(
self._module_format("scipy.special.airy"),
self._print(expr.args[0]))
def _print_airyaiprime(self, expr):
return "{}({})[1]".format(
self._module_format("scipy.special.airy"),
self._print(expr.args[0]))
def _print_airybi(self, expr):
return "{}({})[2]".format(
self._module_format("scipy.special.airy"),
self._print(expr.args[0]))
def _print_airybiprime(self, expr):
return "{}({})[3]".format(
self._module_format("scipy.special.airy"),
self._print(expr.args[0]))
def _print_Integral(self, e):
integration_vars, limits = _unpack_integral_limits(e)
if len(limits) == 1:
# nicer (but not necessary) to prefer quad over nquad for 1D case
module_str = self._module_format("scipy.integrate.quad")
limit_str = "%s, %s" % tuple(map(self._print, limits[0]))
else:
module_str = self._module_format("scipy.integrate.nquad")
limit_str = "({})".format(", ".join(
"(%s, %s)" % tuple(map(self._print, l)) for l in limits))
return "{}(lambda {}: {}, {})[0]".format(
module_str,
", ".join(map(self._print, integration_vars)),
self._print(e.args[0]),
limit_str)
for func in _scipy_known_functions:
setattr(SciPyPrinter, f'_print_{func}', _print_known_func)
for const in _scipy_known_constants:
setattr(SciPyPrinter, f'_print_{const}', _print_known_const)
_cupy_known_functions = {k : "cupy." + v for k, v in _known_functions_numpy.items()}
_cupy_known_constants = {k : "cupy." + v for k, v in _known_constants_numpy.items()}
class CuPyPrinter(NumPyPrinter):
"""
CuPy printer which handles vectorized piecewise functions,
logical operators, etc.
"""
_module = 'cupy'
_kf = _cupy_known_functions
_kc = _cupy_known_constants
def __init__(self, settings=None):
super().__init__(settings=settings)
for func in _cupy_known_functions:
setattr(CuPyPrinter, f'_print_{func}', _print_known_func)
for const in _cupy_known_constants:
setattr(CuPyPrinter, f'_print_{const}', _print_known_const)
|
130c17bb580866d86533bf0f1681cf754f42ed4304103a00f63f989780e0afb2 | """
Python code printers
This module contains Python code printers for plain Python as well as NumPy & SciPy enabled code.
"""
from collections import defaultdict
from itertools import chain
from sympy.core import S
from sympy.core.mod import Mod
from .precedence import precedence
from .codeprinter import CodePrinter
_kw = {
'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in',
'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
'with', 'yield', 'None', 'False', 'nonlocal', 'True'
}
_known_functions = {
'Abs': 'abs',
'Min': 'min',
'Max': 'max',
}
_known_functions_math = {
'acos': 'acos',
'acosh': 'acosh',
'asin': 'asin',
'asinh': 'asinh',
'atan': 'atan',
'atan2': 'atan2',
'atanh': 'atanh',
'ceiling': 'ceil',
'cos': 'cos',
'cosh': 'cosh',
'erf': 'erf',
'erfc': 'erfc',
'exp': 'exp',
'expm1': 'expm1',
'factorial': 'factorial',
'floor': 'floor',
'gamma': 'gamma',
'hypot': 'hypot',
'loggamma': 'lgamma',
'log': 'log',
'ln': 'log',
'log10': 'log10',
'log1p': 'log1p',
'log2': 'log2',
'sin': 'sin',
'sinh': 'sinh',
'Sqrt': 'sqrt',
'tan': 'tan',
'tanh': 'tanh'
} # Not used from ``math``: [copysign isclose isfinite isinf isnan ldexp frexp pow modf
# radians trunc fmod fsum gcd degrees fabs]
_known_constants_math = {
'Exp1': 'e',
'Pi': 'pi',
'E': 'e',
'Infinity': 'inf',
'NaN': 'nan',
'ComplexInfinity': 'nan'
}
def _print_known_func(self, expr):
known = self.known_functions[expr.__class__.__name__]
return '{name}({args})'.format(name=self._module_format(known),
args=', '.join(map(lambda arg: self._print(arg), expr.args)))
def _print_known_const(self, expr):
known = self.known_constants[expr.__class__.__name__]
return self._module_format(known)
class AbstractPythonCodePrinter(CodePrinter):
printmethod = "_pythoncode"
language = "Python"
reserved_words = _kw
modules = None # initialized to a set in __init__
tab = ' '
_kf = dict(chain(
_known_functions.items(),
[(k, 'math.' + v) for k, v in _known_functions_math.items()]
))
_kc = {k: 'math.'+v for k, v in _known_constants_math.items()}
_operators = {'and': 'and', 'or': 'or', 'not': 'not'}
_default_settings = dict(
CodePrinter._default_settings,
user_functions={},
precision=17,
inline=True,
fully_qualified_modules=True,
contract=False,
standard='python3',
)
def __init__(self, settings=None):
super().__init__(settings)
# Python standard handler
std = self._settings['standard']
if std is None:
import sys
std = 'python{}'.format(sys.version_info.major)
if std != 'python3':
raise ValueError('Only Python 3 is supported.')
self.standard = std
self.module_imports = defaultdict(set)
# Known functions and constants handler
self.known_functions = dict(self._kf, **(settings or {}).get(
'user_functions', {}))
self.known_constants = dict(self._kc, **(settings or {}).get(
'user_constants', {}))
def _declare_number_const(self, name, value):
return "%s = %s" % (name, value)
def _module_format(self, fqn, register=True):
parts = fqn.split('.')
if register and len(parts) > 1:
self.module_imports['.'.join(parts[:-1])].add(parts[-1])
if self._settings['fully_qualified_modules']:
return fqn
else:
return fqn.split('(')[0].split('[')[0].split('.')[-1]
def _format_code(self, lines):
return lines
def _get_statement(self, codestring):
return "{}".format(codestring)
def _get_comment(self, text):
return " # {}".format(text)
def _expand_fold_binary_op(self, op, args):
"""
This method expands a fold on binary operations.
``functools.reduce`` is an example of a folded operation.
For example, the expression
`A + B + C + D`
is folded into
`((A + B) + C) + D`
"""
if len(args) == 1:
return self._print(args[0])
else:
return "%s(%s, %s)" % (
self._module_format(op),
self._expand_fold_binary_op(op, args[:-1]),
self._print(args[-1]),
)
def _expand_reduce_binary_op(self, op, args):
"""
This method expands a reductin on binary operations.
Notice: this is NOT the same as ``functools.reduce``.
For example, the expression
`A + B + C + D`
is reduced into:
`(A + B) + (C + D)`
"""
if len(args) == 1:
return self._print(args[0])
else:
N = len(args)
Nhalf = N // 2
return "%s(%s, %s)" % (
self._module_format(op),
self._expand_reduce_binary_op(args[:Nhalf]),
self._expand_reduce_binary_op(args[Nhalf:]),
)
def _print_NaN(self, expr):
return "float('nan')"
def _print_Infinity(self, expr):
return "float('inf')"
def _print_NegativeInfinity(self, expr):
return "float('-inf')"
def _print_ComplexInfinity(self, expr):
return self._print_NaN(expr)
def _print_Mod(self, expr):
PREC = precedence(expr)
return ('{} % {}'.format(*map(lambda x: self.parenthesize(x, PREC), expr.args)))
def _print_Piecewise(self, expr):
result = []
i = 0
for arg in expr.args:
e = arg.expr
c = arg.cond
if i == 0:
result.append('(')
result.append('(')
result.append(self._print(e))
result.append(')')
result.append(' if ')
result.append(self._print(c))
result.append(' else ')
i += 1
result = result[:-1]
if result[-1] == 'True':
result = result[:-2]
result.append(')')
else:
result.append(' else None)')
return ''.join(result)
def _print_Relational(self, expr):
"Relational printer for Equality and Unequality"
op = {
'==' :'equal',
'!=' :'not_equal',
'<' :'less',
'<=' :'less_equal',
'>' :'greater',
'>=' :'greater_equal',
}
if expr.rel_op in op:
lhs = self._print(expr.lhs)
rhs = self._print(expr.rhs)
return '({lhs} {op} {rhs})'.format(op=expr.rel_op, lhs=lhs, rhs=rhs)
return super()._print_Relational(expr)
def _print_ITE(self, expr):
from sympy.functions.elementary.piecewise import Piecewise
return self._print(expr.rewrite(Piecewise))
def _print_Sum(self, expr):
loops = (
'for {i} in range({a}, {b}+1)'.format(
i=self._print(i),
a=self._print(a),
b=self._print(b))
for i, a, b in expr.limits)
return '(builtins.sum({function} {loops}))'.format(
function=self._print(expr.function),
loops=' '.join(loops))
def _print_ImaginaryUnit(self, expr):
return '1j'
def _print_KroneckerDelta(self, expr):
a, b = expr.args
return '(1 if {a} == {b} else 0)'.format(
a = self._print(a),
b = self._print(b)
)
def _print_MatrixBase(self, expr):
name = expr.__class__.__name__
func = self.known_functions.get(name, name)
return "%s(%s)" % (func, self._print(expr.tolist()))
_print_SparseRepMatrix = \
_print_MutableSparseMatrix = \
_print_ImmutableSparseMatrix = \
_print_Matrix = \
_print_DenseMatrix = \
_print_MutableDenseMatrix = \
_print_ImmutableMatrix = \
_print_ImmutableDenseMatrix = \
lambda self, expr: self._print_MatrixBase(expr)
def _indent_codestring(self, codestring):
return '\n'.join([self.tab + line for line in codestring.split('\n')])
def _print_FunctionDefinition(self, fd):
body = '\n'.join(map(lambda arg: self._print(arg), fd.body))
return "def {name}({parameters}):\n{body}".format(
name=self._print(fd.name),
parameters=', '.join([self._print(var.symbol) for var in fd.parameters]),
body=self._indent_codestring(body)
)
def _print_While(self, whl):
body = '\n'.join(map(lambda arg: self._print(arg), whl.body))
return "while {cond}:\n{body}".format(
cond=self._print(whl.condition),
body=self._indent_codestring(body)
)
def _print_Declaration(self, decl):
return '%s = %s' % (
self._print(decl.variable.symbol),
self._print(decl.variable.value)
)
def _print_Return(self, ret):
arg, = ret.args
return 'return %s' % self._print(arg)
def _print_Print(self, prnt):
print_args = ', '.join(map(lambda arg: self._print(arg), prnt.print_args))
if prnt.format_string != None: # Must be '!= None', cannot be 'is not None'
print_args = '{} % ({})'.format(
self._print(prnt.format_string), print_args)
if prnt.file != None: # Must be '!= None', cannot be 'is not None'
print_args += ', file=%s' % self._print(prnt.file)
return 'print(%s)' % print_args
def _print_Stream(self, strm):
if str(strm.name) == 'stdout':
return self._module_format('sys.stdout')
elif str(strm.name) == 'stderr':
return self._module_format('sys.stderr')
else:
return self._print(strm.name)
def _print_NoneToken(self, arg):
return 'None'
def _hprint_Pow(self, expr, rational=False, sqrt='math.sqrt'):
"""Printing helper function for ``Pow``
Notes
=====
This only preprocesses the ``sqrt`` as math formatter
Examples
========
>>> from sympy import sqrt
>>> from sympy.printing.pycode import PythonCodePrinter
>>> from sympy.abc import x
Python code printer automatically looks up ``math.sqrt``.
>>> printer = PythonCodePrinter()
>>> printer._hprint_Pow(sqrt(x), rational=True)
'x**(1/2)'
>>> printer._hprint_Pow(sqrt(x), rational=False)
'math.sqrt(x)'
>>> printer._hprint_Pow(1/sqrt(x), rational=True)
'x**(-1/2)'
>>> printer._hprint_Pow(1/sqrt(x), rational=False)
'1/math.sqrt(x)'
Using sqrt from numpy or mpmath
>>> printer._hprint_Pow(sqrt(x), sqrt='numpy.sqrt')
'numpy.sqrt(x)'
>>> printer._hprint_Pow(sqrt(x), sqrt='mpmath.sqrt')
'mpmath.sqrt(x)'
See Also
========
sympy.printing.str.StrPrinter._print_Pow
"""
PREC = precedence(expr)
if expr.exp == S.Half and not rational:
func = self._module_format(sqrt)
arg = self._print(expr.base)
return '{func}({arg})'.format(func=func, arg=arg)
if expr.is_commutative:
if -expr.exp is S.Half and not rational:
func = self._module_format(sqrt)
num = self._print(S.One)
arg = self._print(expr.base)
return "{num}/{func}({arg})".format(
num=num, func=func, arg=arg)
base_str = self.parenthesize(expr.base, PREC, strict=False)
exp_str = self.parenthesize(expr.exp, PREC, strict=False)
return "{}**{}".format(base_str, exp_str)
class ArrayPrinter:
def _arrayify(self, indexed):
from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array
try:
return convert_indexed_to_array(indexed)
except Exception:
return indexed
def _get_einsum_string(self, subranks, contraction_indices):
letters = self._get_letter_generator_for_einsum()
contraction_string = ""
counter = 0
d = {j: min(i) for i in contraction_indices for j in i}
indices = []
for rank_arg in subranks:
lindices = []
for i in range(rank_arg):
if counter in d:
lindices.append(d[counter])
else:
lindices.append(counter)
counter += 1
indices.append(lindices)
mapping = {}
letters_free = []
letters_dum = []
for i in indices:
for j in i:
if j not in mapping:
l = next(letters)
mapping[j] = l
else:
l = mapping[j]
contraction_string += l
if j in d:
if l not in letters_dum:
letters_dum.append(l)
else:
letters_free.append(l)
contraction_string += ","
contraction_string = contraction_string[:-1]
return contraction_string, letters_free, letters_dum
def _get_letter_generator_for_einsum(self):
for i in range(97, 123):
yield chr(i)
for i in range(65, 91):
yield chr(i)
raise ValueError("out of letters")
def _print_ArrayTensorProduct(self, expr):
letters = self._get_letter_generator_for_einsum()
contraction_string = ",".join(["".join([next(letters) for j in range(i)]) for i in expr.subranks])
return '%s("%s", %s)' % (
self._module_format(self._module + "." + self._einsum),
contraction_string,
", ".join([self._print(arg) for arg in expr.args])
)
def _print_ArrayContraction(self, expr):
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
base = expr.expr
contraction_indices = expr.contraction_indices
if isinstance(base, ArrayTensorProduct):
elems = ",".join(["%s" % (self._print(arg)) for arg in base.args])
ranks = base.subranks
else:
elems = self._print(base)
ranks = [len(base.shape)]
contraction_string, letters_free, letters_dum = self._get_einsum_string(ranks, contraction_indices)
if not contraction_indices:
return self._print(base)
if isinstance(base, ArrayTensorProduct):
elems = ",".join(["%s" % (self._print(arg)) for arg in base.args])
else:
elems = self._print(base)
return "%s(\"%s\", %s)" % (
self._module_format(self._module + "." + self._einsum),
"{}->{}".format(contraction_string, "".join(sorted(letters_free))),
elems,
)
def _print_ArrayDiagonal(self, expr):
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
diagonal_indices = list(expr.diagonal_indices)
if isinstance(expr.expr, ArrayTensorProduct):
subranks = expr.expr.subranks
elems = expr.expr.args
else:
subranks = expr.subranks
elems = [expr.expr]
diagonal_string, letters_free, letters_dum = self._get_einsum_string(subranks, diagonal_indices)
elems = [self._print(i) for i in elems]
return '%s("%s", %s)' % (
self._module_format(self._module + "." + self._einsum),
"{}->{}".format(diagonal_string, "".join(letters_free+letters_dum)),
", ".join(elems)
)
def _print_PermuteDims(self, expr):
return "%s(%s, %s)" % (
self._module_format(self._module + "." + self._transpose),
self._print(expr.expr),
self._print(expr.permutation.array_form),
)
def _print_ArrayAdd(self, expr):
return self._expand_fold_binary_op(self._module + "." + self._add, expr.args)
def _print_OneArray(self, expr):
return "%s((%s,))" % (
self._module_format(self._module+ "." + self._ones),
','.join(map(self._print,expr.args))
)
def _print_ZeroArray(self, expr):
return "%s((%s,))" % (
self._module_format(self._module+ "." + self._zeros),
','.join(map(self._print,expr.args))
)
def _print_Assignment(self, expr):
#XXX: maybe this needs to happen at a higher level e.g. at _print or
#doprint?
lhs = self._print(self._arrayify(expr.lhs))
rhs = self._print(self._arrayify(expr.rhs))
return "%s = %s" % ( lhs, rhs )
def _print_IndexedBase(self, expr):
return self._print_ArraySymbol(expr)
class PythonCodePrinter(AbstractPythonCodePrinter):
def _print_sign(self, e):
return '(0.0 if {e} == 0 else {f}(1, {e}))'.format(
f=self._module_format('math.copysign'), e=self._print(e.args[0]))
def _print_Not(self, expr):
PREC = precedence(expr)
return self._operators['not'] + self.parenthesize(expr.args[0], PREC)
def _print_Indexed(self, expr):
base = expr.args[0]
index = expr.args[1:]
return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index]))
def _print_Pow(self, expr, rational=False):
return self._hprint_Pow(expr, rational=rational)
def _print_Rational(self, expr):
return '{}/{}'.format(expr.p, expr.q)
def _print_Half(self, expr):
return self._print_Rational(expr)
def _print_frac(self, expr):
return self._print_Mod(Mod(expr.args[0], 1))
def _print_Symbol(self, expr):
name = super()._print_Symbol(expr)
if name in self.reserved_words:
if self._settings['error_on_reserved']:
msg = ('This expression includes the symbol "{}" which is a '
'reserved keyword in this language.')
raise ValueError(msg.format(name))
return name + self._settings['reserved_word_suffix']
elif '{' in name: # Remove curly braces from subscripted variables
return name.replace('{', '').replace('}', '')
else:
return name
_print_lowergamma = CodePrinter._print_not_supported
_print_uppergamma = CodePrinter._print_not_supported
_print_fresnelc = CodePrinter._print_not_supported
_print_fresnels = CodePrinter._print_not_supported
for k in PythonCodePrinter._kf:
setattr(PythonCodePrinter, '_print_%s' % k, _print_known_func)
for k in _known_constants_math:
setattr(PythonCodePrinter, '_print_%s' % k, _print_known_const)
def pycode(expr, **settings):
""" Converts an expr to a string of Python code
Parameters
==========
expr : Expr
A SymPy expression.
fully_qualified_modules : bool
Whether or not to write out full module names of functions
(``math.sin`` vs. ``sin``). default: ``True``.
standard : str or None, optional
Only 'python3' (default) is supported.
This parameter may be removed in the future.
Examples
========
>>> from sympy import pycode, tan, Symbol
>>> pycode(tan(Symbol('x')) + 1)
'math.tan(x) + 1'
"""
return PythonCodePrinter(settings).doprint(expr)
_not_in_mpmath = 'log1p log2'.split()
_in_mpmath = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_mpmath]
_known_functions_mpmath = dict(_in_mpmath, **{
'beta': 'beta',
'frac': 'frac',
'fresnelc': 'fresnelc',
'fresnels': 'fresnels',
'sign': 'sign',
'loggamma': 'loggamma',
'hyper': 'hyper',
'meijerg': 'meijerg',
'besselj': 'besselj',
'bessely': 'bessely',
'besseli': 'besseli',
'besselk': 'besselk',
})
_known_constants_mpmath = {
'Exp1': 'e',
'Pi': 'pi',
'GoldenRatio': 'phi',
'EulerGamma': 'euler',
'Catalan': 'catalan',
'NaN': 'nan',
'Infinity': 'inf',
'NegativeInfinity': 'ninf'
}
def _unpack_integral_limits(integral_expr):
""" helper function for _print_Integral that
- accepts an Integral expression
- returns a tuple of
- a list variables of integration
- a list of tuples of the upper and lower limits of integration
"""
integration_vars = []
limits = []
for integration_range in integral_expr.limits:
if len(integration_range) == 3:
integration_var, lower_limit, upper_limit = integration_range
else:
raise NotImplementedError("Only definite integrals are supported")
integration_vars.append(integration_var)
limits.append((lower_limit, upper_limit))
return integration_vars, limits
class MpmathPrinter(PythonCodePrinter):
"""
Lambda printer for mpmath which maintains precision for floats
"""
printmethod = "_mpmathcode"
language = "Python with mpmath"
_kf = dict(chain(
_known_functions.items(),
[(k, 'mpmath.' + v) for k, v in _known_functions_mpmath.items()]
))
_kc = {k: 'mpmath.'+v for k, v in _known_constants_mpmath.items()}
def _print_Float(self, e):
# XXX: This does not handle setting mpmath.mp.dps. It is assumed that
# the caller of the lambdified function will have set it to sufficient
# precision to match the Floats in the expression.
# Remove 'mpz' if gmpy is installed.
args = str(tuple(map(int, e._mpf_)))
return '{func}({args})'.format(func=self._module_format('mpmath.mpf'), args=args)
def _print_Rational(self, e):
return "{func}({p})/{func}({q})".format(
func=self._module_format('mpmath.mpf'),
q=self._print(e.q),
p=self._print(e.p)
)
def _print_Half(self, e):
return self._print_Rational(e)
def _print_uppergamma(self, e):
return "{}({}, {}, {})".format(
self._module_format('mpmath.gammainc'),
self._print(e.args[0]),
self._print(e.args[1]),
self._module_format('mpmath.inf'))
def _print_lowergamma(self, e):
return "{}({}, 0, {})".format(
self._module_format('mpmath.gammainc'),
self._print(e.args[0]),
self._print(e.args[1]))
def _print_log2(self, e):
return '{0}({1})/{0}(2)'.format(
self._module_format('mpmath.log'), self._print(e.args[0]))
def _print_log1p(self, e):
return '{}({}+1)'.format(
self._module_format('mpmath.log'), self._print(e.args[0]))
def _print_Pow(self, expr, rational=False):
return self._hprint_Pow(expr, rational=rational, sqrt='mpmath.sqrt')
def _print_Integral(self, e):
integration_vars, limits = _unpack_integral_limits(e)
return "{}(lambda {}: {}, {})".format(
self._module_format("mpmath.quad"),
", ".join(map(self._print, integration_vars)),
self._print(e.args[0]),
", ".join("(%s, %s)" % tuple(map(self._print, l)) for l in limits))
for k in MpmathPrinter._kf:
setattr(MpmathPrinter, '_print_%s' % k, _print_known_func)
for k in _known_constants_mpmath:
setattr(MpmathPrinter, '_print_%s' % k, _print_known_const)
class SymPyPrinter(AbstractPythonCodePrinter):
language = "Python with SymPy"
def _print_Function(self, expr):
mod = expr.func.__module__ or ''
return '%s(%s)' % (self._module_format(mod + ('.' if mod else '') + expr.func.__name__),
', '.join(map(lambda arg: self._print(arg), expr.args)))
def _print_Pow(self, expr, rational=False):
return self._hprint_Pow(expr, rational=rational, sqrt='sympy.sqrt')
|
b39519b1936de619eb99c1e904438c696ef819bb2f432f5fe5f410357a09850a | """
A Printer for generating readable representation of most SymPy classes.
"""
from typing import Any, Dict as tDict
from sympy.core import S, Rational, Pow, Basic, Mul, Number
from sympy.core.mul import _keep_coeff
from sympy.core.relational import Relational
from sympy.core.sorting import default_sort_key
from sympy.core.sympify import SympifyError
from sympy.utilities.iterables import sift
from .precedence import precedence, PRECEDENCE
from .printer import Printer, print_function
from mpmath.libmp import prec_to_dps, to_str as mlib_to_str
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: tDict[str, Any]
_relationals = dict() # type: tDict[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):
args = list(expr.args)
for j, i in enumerate(args):
if isinstance(i, Relational) and (
i.canonical.rhs is S.NegativeInfinity):
args.insert(0, args.pop(j))
return self.stringify(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_Heaviside(self, expr):
# Same as _print_Function but uses pargs to suppress default 1/2 for
# 2nd args
return expr.func.__name__ + "(%s)" % self.stringify(expr.pargs, ", ")
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_List(self, expr):
return self._print_list(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
pre = []
# don't parenthesize first factor if negative
if n and n[0].could_extract_minus_sign():
pre = [str(n.pop(0))]
nfactors = pre + [self.parenthesize(a, prec, strict=False)
for a in n]
if not nfactors:
nfactors = ['1']
# don't parenthesize first of denominator unless singleton
if len(d) > 1 and d[0].could_extract_minus_sign():
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, Pow))):
# 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 sympy_deprecation_warning
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
sympy_deprecation_warning(
f"""
Setting Permutation.print_cyclic is deprecated. Instead use
init_printing(perm_cyclic={perm_cyclic}).
""",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-permutation-print_cyclic",
stacklevel=7,
)
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
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]" % (
self.parenthesize(expr.name, PRECEDENCE["Func"], True), ", ".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 import sqrt, 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_FiniteSet(self, s):
from sympy.sets.sets import FiniteSet
items = sorted(s, key=default_sort_key)
args = ', '.join(self._print(item) for item in items)
if any(item.has(FiniteSet) for item in items):
return 'FiniteSet({})'.format(args)
return '{{{}}}'.format(args)
def _print_Partition(self, s):
items = sorted(s, key=default_sort_key)
args = ', '.join(self._print(arg) for arg in items)
return 'Partition({})'.format(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):
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 = expr.function
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
|
c790d6054fc07785e040f2157a3ca17d44e9157a6b9d4c8f42a5cb9ec8ee065a | """
A Printer which converts an expression into its LaTeX equivalent.
"""
from typing import Any, Dict as tDict
import itertools
from sympy.core import Add, Float, Mod, Mul, Number, S, Symbol
from sympy.core.alphabets import greeks
from sympy.core.containers import Tuple
from sympy.core.function import AppliedUndef, Derivative
from sympy.core.operations import AssocOp
from sympy.core.power import Pow
from sympy.core.sorting import default_sort_key
from sympy.core.sympify import SympifyError
from sympy.logic.boolalg import true
# sympy.printing imports
from sympy.printing.precedence import precedence_traditional
from sympy.printing.printer import Printer, print_function
from sympy.printing.conventions import split_super_sub, requires_partial
from sympy.printing.precedence import precedence, PRECEDENCE
from mpmath.libmp.libmpf import prec_to_dps, to_str as mlib_to_str
from sympy.utilities.iterables import has_variety
import re
# Hand-picked functions which can be used directly in both LaTeX and MathJax
# Complete list at
# https://docs.mathjax.org/en/latest/tex.html#supported-latex-commands
# This variable only contains those functions which SymPy uses.
accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan',
'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec',
'csc', 'cot', 'coth', 're', 'im', 'frac', 'root',
'arg',
]
tex_greek_dictionary = {
'Alpha': 'A',
'Beta': 'B',
'Gamma': r'\Gamma',
'Delta': r'\Delta',
'Epsilon': 'E',
'Zeta': 'Z',
'Eta': 'H',
'Theta': r'\Theta',
'Iota': 'I',
'Kappa': 'K',
'Lambda': r'\Lambda',
'Mu': 'M',
'Nu': 'N',
'Xi': r'\Xi',
'omicron': 'o',
'Omicron': 'O',
'Pi': r'\Pi',
'Rho': 'P',
'Sigma': r'\Sigma',
'Tau': 'T',
'Upsilon': r'\Upsilon',
'Phi': r'\Phi',
'Chi': 'X',
'Psi': r'\Psi',
'Omega': r'\Omega',
'lamda': r'\lambda',
'Lamda': r'\Lambda',
'khi': r'\chi',
'Khi': r'X',
'varepsilon': r'\varepsilon',
'varkappa': r'\varkappa',
'varphi': r'\varphi',
'varpi': r'\varpi',
'varrho': r'\varrho',
'varsigma': r'\varsigma',
'vartheta': r'\vartheta',
}
other_symbols = {'aleph', 'beth', 'daleth', 'gimel', 'ell', 'eth', 'hbar',
'hslash', 'mho', 'wp'}
# Variable name modifiers
modifier_dict = {
# Accents
'mathring': lambda s: r'\mathring{'+s+r'}',
'ddddot': lambda s: r'\ddddot{'+s+r'}',
'dddot': lambda s: r'\dddot{'+s+r'}',
'ddot': lambda s: r'\ddot{'+s+r'}',
'dot': lambda s: r'\dot{'+s+r'}',
'check': lambda s: r'\check{'+s+r'}',
'breve': lambda s: r'\breve{'+s+r'}',
'acute': lambda s: r'\acute{'+s+r'}',
'grave': lambda s: r'\grave{'+s+r'}',
'tilde': lambda s: r'\tilde{'+s+r'}',
'hat': lambda s: r'\hat{'+s+r'}',
'bar': lambda s: r'\bar{'+s+r'}',
'vec': lambda s: r'\vec{'+s+r'}',
'prime': lambda s: "{"+s+"}'",
'prm': lambda s: "{"+s+"}'",
# Faces
'bold': lambda s: r'\boldsymbol{'+s+r'}',
'bm': lambda s: r'\boldsymbol{'+s+r'}',
'cal': lambda s: r'\mathcal{'+s+r'}',
'scr': lambda s: r'\mathscr{'+s+r'}',
'frak': lambda s: r'\mathfrak{'+s+r'}',
# Brackets
'norm': lambda s: r'\left\|{'+s+r'}\right\|',
'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle',
'abs': lambda s: r'\left|{'+s+r'}\right|',
'mag': lambda s: r'\left|{'+s+r'}\right|',
}
greek_letters_set = frozenset(greeks)
_between_two_numbers_p = (
re.compile(r'[0-9][} ]*$'), # search
re.compile(r'[0-9]'), # match
)
def latex_escape(s):
"""
Escape a string such that latex interprets it as plaintext.
We cannot use verbatim easily with mathjax, so escaping is easier.
Rules from https://tex.stackexchange.com/a/34586/41112.
"""
s = s.replace('\\', r'\textbackslash')
for c in '&%$#_{}':
s = s.replace(c, '\\' + c)
s = s.replace('~', r'\textasciitilde')
s = s.replace('^', r'\textasciicircum')
return s
class LatexPrinter(Printer):
printmethod = "_latex"
_default_settings = {
"full_prec": False,
"fold_frac_powers": False,
"fold_func_brackets": False,
"fold_short_frac": None,
"inv_trig_style": "abbreviated",
"itex": False,
"ln_notation": False,
"long_frac_ratio": None,
"mat_delim": "[",
"mat_str": None,
"mode": "plain",
"mul_symbol": None,
"order": None,
"symbol_names": {},
"root_notation": True,
"mat_symbol_style": "plain",
"imaginary_unit": "i",
"gothic_re_im": False,
"decimal_separator": "period",
"perm_cyclic": True,
"parenthesize_super": True,
"min": None,
"max": None,
"diff_operator": "d",
} # type: tDict[str, Any]
def __init__(self, settings=None):
Printer.__init__(self, settings)
if 'mode' in self._settings:
valid_modes = ['inline', 'plain', 'equation',
'equation*']
if self._settings['mode'] not in valid_modes:
raise ValueError("'mode' must be one of 'inline', 'plain', "
"'equation' or 'equation*'")
if self._settings['fold_short_frac'] is None and \
self._settings['mode'] == 'inline':
self._settings['fold_short_frac'] = True
mul_symbol_table = {
None: r" ",
"ldot": r" \,.\, ",
"dot": r" \cdot ",
"times": r" \times "
}
try:
self._settings['mul_symbol_latex'] = \
mul_symbol_table[self._settings['mul_symbol']]
except KeyError:
self._settings['mul_symbol_latex'] = \
self._settings['mul_symbol']
try:
self._settings['mul_symbol_latex_numbers'] = \
mul_symbol_table[self._settings['mul_symbol'] or 'dot']
except KeyError:
if (self._settings['mul_symbol'].strip() in
['', ' ', '\\', '\\,', '\\:', '\\;', '\\quad']):
self._settings['mul_symbol_latex_numbers'] = \
mul_symbol_table['dot']
else:
self._settings['mul_symbol_latex_numbers'] = \
self._settings['mul_symbol']
self._delim_dict = {'(': ')', '[': ']'}
imaginary_unit_table = {
None: r"i",
"i": r"i",
"ri": r"\mathrm{i}",
"ti": r"\text{i}",
"j": r"j",
"rj": r"\mathrm{j}",
"tj": r"\text{j}",
}
imag_unit = self._settings['imaginary_unit']
self._settings['imaginary_unit_latex'] = imaginary_unit_table.get(imag_unit, imag_unit)
diff_operator_table = {
None: r"d",
"d": r"d",
"rd": r"\mathrm{d}",
"td": r"\text{d}",
}
diff_operator = self._settings['diff_operator']
self._settings["diff_operator_latex"] = diff_operator_table.get(diff_operator, diff_operator)
def _add_parens(self, s):
return r"\left({}\right)".format(s)
# TODO: merge this with the above, which requires a lot of test changes
def _add_parens_lspace(self, s):
return r"\left( {}\right)".format(s)
def parenthesize(self, item, level, is_neg=False, strict=False):
prec_val = precedence_traditional(item)
if is_neg and strict:
return self._add_parens(self._print(item))
if (prec_val < level) or ((not strict) and prec_val <= level):
return self._add_parens(self._print(item))
else:
return self._print(item)
def parenthesize_super(self, s):
"""
Protect superscripts in s
If the parenthesize_super option is set, protect with parentheses, else
wrap in braces.
"""
if "^" in s:
if self._settings['parenthesize_super']:
return self._add_parens(s)
else:
return "{{{}}}".format(s)
return s
def doprint(self, expr):
tex = Printer.doprint(self, expr)
if self._settings['mode'] == 'plain':
return tex
elif self._settings['mode'] == 'inline':
return r"$%s$" % tex
elif self._settings['itex']:
return r"$$%s$$" % tex
else:
env_str = self._settings['mode']
return r"\begin{%s}%s\end{%s}" % (env_str, tex, env_str)
def _needs_brackets(self, expr):
"""
Returns True if the expression needs to be wrapped in brackets when
printed, False otherwise. For example: a + b => True; a => False;
10 => False; -10 => True.
"""
return not ((expr.is_Integer and expr.is_nonnegative)
or (expr.is_Atom and (expr is not S.NegativeOne
and expr.is_Rational is False)))
def _needs_function_brackets(self, expr):
"""
Returns True if the expression needs to be wrapped in brackets when
passed as an argument to a function, False otherwise. This is a more
liberal version of _needs_brackets, in that many expressions which need
to be wrapped in brackets when added/subtracted/raised to a power do
not need them when passed to a function. Such an example is a*b.
"""
if not self._needs_brackets(expr):
return False
else:
# Muls of the form a*b*c... can be folded
if expr.is_Mul and not self._mul_is_clean(expr):
return True
# Pows which don't need brackets can be folded
elif expr.is_Pow and not self._pow_is_clean(expr):
return True
# Add and Function always need brackets
elif expr.is_Add or expr.is_Function:
return True
else:
return False
def _needs_mul_brackets(self, expr, first=False, last=False):
"""
Returns True if the expression needs to be wrapped in brackets when
printed as part of a Mul, False otherwise. This is True for Add,
but also for some container objects that would not need brackets
when appearing last in a Mul, e.g. an Integral. ``last=True``
specifies that this expr is the last to appear in a Mul.
``first=True`` specifies that this expr is the first to appear in
a Mul.
"""
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
from sympy.integrals.integrals import Integral
if expr.is_Mul:
if not first and expr.could_extract_minus_sign():
return True
elif precedence_traditional(expr) < PRECEDENCE["Mul"]:
return True
elif expr.is_Relational:
return True
if expr.is_Piecewise:
return True
if any(expr.has(x) for x in (Mod,)):
return True
if (not last and
any(expr.has(x) for x in (Integral, Product, Sum))):
return True
return False
def _needs_add_brackets(self, expr):
"""
Returns True if the expression needs to be wrapped in brackets when
printed as part of an Add, False otherwise. This is False for most
things.
"""
if expr.is_Relational:
return True
if any(expr.has(x) for x in (Mod,)):
return True
if expr.is_Add:
return True
return False
def _mul_is_clean(self, expr):
for arg in expr.args:
if arg.is_Function:
return False
return True
def _pow_is_clean(self, expr):
return not self._needs_brackets(expr.base)
def _do_exponent(self, expr, exp):
if exp is not None:
return r"\left(%s\right)^{%s}" % (expr, exp)
else:
return expr
def _print_Basic(self, expr):
name = self._deal_with_super_sub(expr.__class__.__name__)
if expr.args:
ls = [self._print(o) for o in expr.args]
s = r"\operatorname{{{}}}\left({}\right)"
return s.format(name, ", ".join(ls))
else:
return r"\text{{{}}}".format(name)
def _print_bool(self, e):
return r"\text{%s}" % e
_print_BooleanTrue = _print_bool
_print_BooleanFalse = _print_bool
def _print_NoneType(self, e):
return r"\text{%s}" % e
def _print_Add(self, expr, order=None):
terms = self._as_ordered_terms(expr, order=order)
tex = ""
for i, term in enumerate(terms):
if i == 0:
pass
elif term.could_extract_minus_sign():
tex += " - "
term = -term
else:
tex += " + "
term_tex = self._print(term)
if self._needs_add_brackets(term):
term_tex = r"\left(%s\right)" % term_tex
tex += term_tex
return tex
def _print_Cycle(self, expr):
from sympy.combinatorics.permutations import Permutation
if expr.size == 0:
return r"\left( \right)"
expr = Permutation(expr)
expr_perm = expr.cyclic_form
siz = expr.size
if expr.array_form[-1] == siz - 1:
expr_perm = expr_perm + [[siz - 1]]
term_tex = ''
for i in expr_perm:
term_tex += str(i).replace(',', r"\;")
term_tex = term_tex.replace('[', r"\left( ")
term_tex = term_tex.replace(']', r"\right)")
return term_tex
def _print_Permutation(self, expr):
from sympy.combinatorics.permutations import Permutation
from sympy.utilities.exceptions import sympy_deprecation_warning
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
sympy_deprecation_warning(
f"""
Setting Permutation.print_cyclic is deprecated. Instead use
init_printing(perm_cyclic={perm_cyclic}).
""",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-permutation-print_cyclic",
stacklevel=8,
)
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
return self._print_Cycle(expr)
if expr.size == 0:
return r"\left( \right)"
lower = [self._print(arg) for arg in expr.array_form]
upper = [self._print(arg) for arg in range(len(lower))]
row1 = " & ".join(upper)
row2 = " & ".join(lower)
mat = r" \\ ".join((row1, row2))
return r"\begin{pmatrix} %s \end{pmatrix}" % mat
def _print_AppliedPermutation(self, expr):
perm, var = expr.args
return r"\sigma_{%s}(%s)" % (self._print(perm), self._print(var))
def _print_Float(self, expr):
# Based off of that in StrPrinter
dps = prec_to_dps(expr._prec)
strip = False if self._settings['full_prec'] else True
low = self._settings["min"] if "min" in self._settings else None
high = self._settings["max"] if "max" in self._settings else None
str_real = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high)
# Must always have a mul symbol (as 2.5 10^{20} just looks odd)
# thus we use the number separator
separator = self._settings['mul_symbol_latex_numbers']
if 'e' in str_real:
(mant, exp) = str_real.split('e')
if exp[0] == '+':
exp = exp[1:]
if self._settings['decimal_separator'] == 'comma':
mant = mant.replace('.','{,}')
return r"%s%s10^{%s}" % (mant, separator, exp)
elif str_real == "+inf":
return r"\infty"
elif str_real == "-inf":
return r"- \infty"
else:
if self._settings['decimal_separator'] == 'comma':
str_real = str_real.replace('.','{,}')
return str_real
def _print_Cross(self, expr):
vec1 = expr._expr1
vec2 = expr._expr2
return r"%s \times %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']),
self.parenthesize(vec2, PRECEDENCE['Mul']))
def _print_Curl(self, expr):
vec = expr._expr
return r"\nabla\times %s" % self.parenthesize(vec, PRECEDENCE['Mul'])
def _print_Divergence(self, expr):
vec = expr._expr
return r"\nabla\cdot %s" % self.parenthesize(vec, PRECEDENCE['Mul'])
def _print_Dot(self, expr):
vec1 = expr._expr1
vec2 = expr._expr2
return r"%s \cdot %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']),
self.parenthesize(vec2, PRECEDENCE['Mul']))
def _print_Gradient(self, expr):
func = expr._expr
return r"\nabla %s" % self.parenthesize(func, PRECEDENCE['Mul'])
def _print_Laplacian(self, expr):
func = expr._expr
return r"\Delta %s" % self.parenthesize(func, PRECEDENCE['Mul'])
def _print_Mul(self, expr):
from sympy.physics.units import Quantity
from sympy.simplify import fraction
separator = self._settings['mul_symbol_latex']
numbersep = self._settings['mul_symbol_latex_numbers']
def convert(expr):
if not expr.is_Mul:
return str(self._print(expr))
else:
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
args = list(expr.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)))
return convert_args(args)
def convert_args(args):
_tex = last_term_tex = ""
for i, term in enumerate(args):
term_tex = self._print(term)
if self._needs_mul_brackets(term, first=(i == 0),
last=(i == len(args) - 1)):
term_tex = r"\left(%s\right)" % term_tex
if _between_two_numbers_p[0].search(last_term_tex) and \
_between_two_numbers_p[1].match(str(term)):
# between two numbers
_tex += numbersep
elif _tex:
_tex += separator
_tex += term_tex
last_term_tex = term_tex
return _tex
# 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.
# XXX: _print_Pow calls this routine with instances of Pow...
if isinstance(expr, Mul):
args = expr.args
if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]):
return convert_args(args)
include_parens = False
if expr.could_extract_minus_sign():
expr = -expr
tex = "- "
if expr.is_Add:
tex += "("
include_parens = True
else:
tex = ""
numer, denom = fraction(expr, exact=True)
if denom is S.One and Pow(1, -1, evaluate=False) not in expr.args:
# use the original expression here, since fraction() may have
# altered it when producing numer and denom
tex += convert(expr)
else:
snumer = convert(numer)
sdenom = convert(denom)
ldenom = len(sdenom.split())
ratio = self._settings['long_frac_ratio']
if self._settings['fold_short_frac'] and ldenom <= 2 and \
"^" not in sdenom:
# handle short fractions
if self._needs_mul_brackets(numer, last=False):
tex += r"\left(%s\right) / %s" % (snumer, sdenom)
else:
tex += r"%s / %s" % (snumer, sdenom)
elif ratio is not None and \
len(snumer.split()) > ratio*ldenom:
# handle long fractions
if self._needs_mul_brackets(numer, last=True):
tex += r"\frac{1}{%s}%s\left(%s\right)" \
% (sdenom, separator, snumer)
elif numer.is_Mul:
# split a long numerator
a = S.One
b = S.One
for x in numer.args:
if self._needs_mul_brackets(x, last=False) or \
len(convert(a*x).split()) > ratio*ldenom or \
(b.is_commutative is x.is_commutative is False):
b *= x
else:
a *= x
if self._needs_mul_brackets(b, last=True):
tex += r"\frac{%s}{%s}%s\left(%s\right)" \
% (convert(a), sdenom, separator, convert(b))
else:
tex += r"\frac{%s}{%s}%s%s" \
% (convert(a), sdenom, separator, convert(b))
else:
tex += r"\frac{1}{%s}%s%s" % (sdenom, separator, snumer)
else:
tex += r"\frac{%s}{%s}" % (snumer, sdenom)
if include_parens:
tex += ")"
return tex
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):
# Treat x**Rational(1,n) as special case
if expr.exp.is_Rational and abs(expr.exp.p) == 1 and expr.exp.q != 1 \
and self._settings['root_notation']:
base = self._print(expr.base)
expq = expr.exp.q
if expq == 2:
tex = r"\sqrt{%s}" % base
elif self._settings['itex']:
tex = r"\root{%d}{%s}" % (expq, base)
else:
tex = r"\sqrt[%d]{%s}" % (expq, base)
if expr.exp.is_negative:
return r"\frac{1}{%s}" % tex
else:
return tex
elif self._settings['fold_frac_powers'] \
and expr.exp.is_Rational \
and expr.exp.q != 1:
base = self.parenthesize(expr.base, PRECEDENCE['Pow'])
p, q = expr.exp.p, expr.exp.q
# issue #12886: add parentheses for superscripts raised to powers
if expr.base.is_Symbol:
base = self.parenthesize_super(base)
if expr.base.is_Function:
return self._print(expr.base, exp="%s/%s" % (p, q))
return r"%s^{%s/%s}" % (base, p, q)
elif expr.exp.is_Rational and expr.exp.is_negative and \
expr.base.is_commutative:
# special case for 1^(-x), issue 9216
if expr.base == 1:
return r"%s^{%s}" % (expr.base, expr.exp)
# special case for (1/x)^(-y) and (-1/-x)^(-y), issue 20252
if expr.base.is_Rational and \
expr.base.p*expr.base.q == abs(expr.base.q):
if expr.exp == -1:
return r"\frac{1}{\frac{%s}{%s}}" % (expr.base.p, expr.base.q)
else:
return r"\frac{1}{(\frac{%s}{%s})^{%s}}" % (expr.base.p, expr.base.q, abs(expr.exp))
# things like 1/x
return self._print_Mul(expr)
else:
if expr.base.is_Function:
return self._print(expr.base, exp=self._print(expr.exp))
else:
tex = r"%s^{%s}"
return self._helper_print_standard_power(expr, tex)
def _helper_print_standard_power(self, expr, template):
exp = self._print(expr.exp)
# issue #12886: add parentheses around superscripts raised
# to powers
base = self.parenthesize(expr.base, PRECEDENCE['Pow'])
if expr.base.is_Symbol:
base = self.parenthesize_super(base)
elif (isinstance(expr.base, Derivative)
and base.startswith(r'\left(')
and re.match(r'\\left\(\\d?d?dot', base)
and base.endswith(r'\right)')):
# don't use parentheses around dotted derivative
base = base[6: -7] # remove outermost added parens
return template % (base, exp)
def _print_UnevaluatedExpr(self, expr):
return self._print(expr.args[0])
def _print_Sum(self, expr):
if len(expr.limits) == 1:
tex = r"\sum_{%s=%s}^{%s} " % \
tuple([self._print(i) for i in expr.limits[0]])
else:
def _format_ineq(l):
return r"%s \leq %s \leq %s" % \
tuple([self._print(s) for s in (l[1], l[0], l[2])])
tex = r"\sum_{\substack{%s}} " % \
str.join('\\\\', [_format_ineq(l) for l in expr.limits])
if isinstance(expr.function, Add):
tex += r"\left(%s\right)" % self._print(expr.function)
else:
tex += self._print(expr.function)
return tex
def _print_Product(self, expr):
if len(expr.limits) == 1:
tex = r"\prod_{%s=%s}^{%s} " % \
tuple([self._print(i) for i in expr.limits[0]])
else:
def _format_ineq(l):
return r"%s \leq %s \leq %s" % \
tuple([self._print(s) for s in (l[1], l[0], l[2])])
tex = r"\prod_{\substack{%s}} " % \
str.join('\\\\', [_format_ineq(l) for l in expr.limits])
if isinstance(expr.function, Add):
tex += r"\left(%s\right)" % self._print(expr.function)
else:
tex += self._print(expr.function)
return tex
def _print_BasisDependent(self, expr):
from sympy.vector import Vector
o1 = []
if expr == expr.zero:
return expr.zero._latex_form
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 v == 1:
o1.append(' + ' + k._latex_form)
elif v == -1:
o1.append(' - ' + k._latex_form)
else:
arg_str = r'\left(' + self._print(v) + r'\right)'
o1.append(' + ' + arg_str + k._latex_form)
outstr = (''.join(o1))
if outstr[1] != '-':
outstr = outstr[3:]
else:
outstr = outstr[1:]
return outstr
def _print_Indexed(self, expr):
tex_base = self._print(expr.base)
tex = '{'+tex_base+'}'+'_{%s}' % ','.join(
map(self._print, expr.indices))
return tex
def _print_IndexedBase(self, expr):
return self._print(expr.label)
def _print_Idx(self, expr):
label = self._print(expr.label)
if expr.upper is not None:
upper = self._print(expr.upper)
if expr.lower is not None:
lower = self._print(expr.lower)
else:
lower = self._print(S.Zero)
interval = '{lower}\\mathrel{{..}}\\nobreak{upper}'.format(
lower = lower, upper = upper)
return '{{{label}}}_{{{interval}}}'.format(
label = label, interval = interval)
#if no bounds are defined this just prints the label
return label
def _print_Derivative(self, expr):
if requires_partial(expr.expr):
diff_symbol = r'\partial'
else:
diff_symbol = self._settings["diff_operator_latex"]
tex = ""
dim = 0
for x, num in reversed(expr.variable_count):
dim += num
if num == 1:
tex += r"%s %s" % (diff_symbol, self._print(x))
else:
tex += r"%s %s^{%s}" % (diff_symbol,
self.parenthesize_super(self._print(x)),
self._print(num))
if dim == 1:
tex = r"\frac{%s}{%s}" % (diff_symbol, tex)
else:
tex = r"\frac{%s^{%s}}{%s}" % (diff_symbol, self._print(dim), tex)
if any(i.could_extract_minus_sign() for i in expr.args):
return r"%s %s" % (tex, self.parenthesize(expr.expr,
PRECEDENCE["Mul"],
is_neg=True,
strict=True))
return r"%s %s" % (tex, self.parenthesize(expr.expr,
PRECEDENCE["Mul"],
is_neg=False,
strict=True))
def _print_Subs(self, subs):
expr, old, new = subs.args
latex_expr = self._print(expr)
latex_old = (self._print(e) for e in old)
latex_new = (self._print(e) for e in new)
latex_subs = r'\\ '.join(
e[0] + '=' + e[1] for e in zip(latex_old, latex_new))
return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr,
latex_subs)
def _print_Integral(self, expr):
tex, symbols = "", []
diff_symbol = self._settings["diff_operator_latex"]
# Only up to \iiiint exists
if len(expr.limits) <= 4 and all(len(lim) == 1 for lim in expr.limits):
# Use len(expr.limits)-1 so that syntax highlighters don't think
# \" is an escaped quote
tex = r"\i" + "i"*(len(expr.limits) - 1) + "nt"
symbols = [r"\, %s%s" % (diff_symbol, self._print(symbol[0]))
for symbol in expr.limits]
else:
for lim in reversed(expr.limits):
symbol = lim[0]
tex += r"\int"
if len(lim) > 1:
if self._settings['mode'] != 'inline' \
and not self._settings['itex']:
tex += r"\limits"
if len(lim) == 3:
tex += "_{%s}^{%s}" % (self._print(lim[1]),
self._print(lim[2]))
if len(lim) == 2:
tex += "^{%s}" % (self._print(lim[1]))
symbols.insert(0, r"\, %s%s" % (diff_symbol, self._print(symbol)))
return r"%s %s%s" % (tex, self.parenthesize(expr.function,
PRECEDENCE["Mul"],
is_neg=any(i.could_extract_minus_sign() for i in expr.args),
strict=True),
"".join(symbols))
def _print_Limit(self, expr):
e, z, z0, dir = expr.args
tex = r"\lim_{%s \to " % self._print(z)
if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity):
tex += r"%s}" % self._print(z0)
else:
tex += r"%s^%s}" % (self._print(z0), self._print(dir))
if isinstance(e, AssocOp):
return r"%s\left(%s\right)" % (tex, self._print(e))
else:
return r"%s %s" % (tex, self._print(e))
def _hprint_Function(self, func):
r'''
Logic to decide how to render a function to latex
- if it is a recognized latex name, use the appropriate latex command
- if it is a single letter, just use that letter
- if it is a longer name, then put \operatorname{} around it and be
mindful of undercores in the name
'''
func = self._deal_with_super_sub(func)
if func in accepted_latex_functions:
name = r"\%s" % func
elif len(func) == 1 or func.startswith('\\'):
name = func
else:
name = r"\operatorname{%s}" % func
return name
def _print_Function(self, expr, exp=None):
r'''
Render functions to LaTeX, handling functions that LaTeX knows about
e.g., sin, cos, ... by using the proper LaTeX command (\sin, \cos, ...).
For single-letter function names, render them as regular LaTeX math
symbols. For multi-letter function names that LaTeX does not know
about, (e.g., Li, sech) use \operatorname{} so that the function name
is rendered in Roman font and LaTeX handles spacing properly.
expr is the expression involving the function
exp is an exponent
'''
func = expr.func.__name__
if hasattr(self, '_print_' + func) and \
not isinstance(expr, AppliedUndef):
return getattr(self, '_print_' + func)(expr, exp)
else:
args = [str(self._print(arg)) for arg in expr.args]
# How inverse trig functions should be displayed, formats are:
# abbreviated: asin, full: arcsin, power: sin^-1
inv_trig_style = self._settings['inv_trig_style']
# If we are dealing with a power-style inverse trig function
inv_trig_power_case = False
# If it is applicable to fold the argument brackets
can_fold_brackets = self._settings['fold_func_brackets'] and \
len(args) == 1 and \
not self._needs_function_brackets(expr.args[0])
inv_trig_table = [
"asin", "acos", "atan",
"acsc", "asec", "acot",
"asinh", "acosh", "atanh",
"acsch", "asech", "acoth",
]
# If the function is an inverse trig function, handle the style
if func in inv_trig_table:
if inv_trig_style == "abbreviated":
pass
elif inv_trig_style == "full":
func = ("ar" if func[-1] == "h" else "arc") + func[1:]
elif inv_trig_style == "power":
func = func[1:]
inv_trig_power_case = True
# Can never fold brackets if we're raised to a power
if exp is not None:
can_fold_brackets = False
if inv_trig_power_case:
if func in accepted_latex_functions:
name = r"\%s^{-1}" % func
else:
name = r"\operatorname{%s}^{-1}" % func
elif exp is not None:
func_tex = self._hprint_Function(func)
func_tex = self.parenthesize_super(func_tex)
name = r'%s^{%s}' % (func_tex, exp)
else:
name = self._hprint_Function(func)
if can_fold_brackets:
if func in accepted_latex_functions:
# Wrap argument safely to avoid parse-time conflicts
# with the function name itself
name += r" {%s}"
else:
name += r"%s"
else:
name += r"{\left(%s \right)}"
if inv_trig_power_case and exp is not None:
name += r"^{%s}" % exp
return name % ",".join(args)
def _print_UndefinedFunction(self, expr):
return self._hprint_Function(str(expr))
def _print_ElementwiseApplyFunction(self, expr):
return r"{%s}_{\circ}\left({%s}\right)" % (
self._print(expr.function),
self._print(expr.expr),
)
@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.beta_functions import beta
from sympy.functions.special.delta_functions import DiracDelta
from sympy.functions.special.error_functions import Chi
return {KroneckerDelta: r'\delta',
gamma: r'\Gamma',
lowergamma: r'\gamma',
beta: r'\operatorname{B}',
DiracDelta: r'\delta',
Chi: r'\operatorname{Chi}'}
def _print_FunctionClass(self, expr):
for cls in self._special_function_classes:
if issubclass(expr, cls) and expr.__name__ == cls.__name__:
return self._special_function_classes[cls]
return self._hprint_Function(str(expr))
def _print_Lambda(self, expr):
symbols, expr = expr.args
if len(symbols) == 1:
symbols = self._print(symbols[0])
else:
symbols = self._print(tuple(symbols))
tex = r"\left( %s \mapsto %s \right)" % (symbols, self._print(expr))
return tex
def _print_IdentityFunction(self, expr):
return r"\left( x \mapsto x \right)"
def _hprint_variadic_function(self, expr, exp=None):
args = sorted(expr.args, key=default_sort_key)
texargs = [r"%s" % self._print(symbol) for symbol in args]
tex = r"\%s\left(%s\right)" % (str(expr.func).lower(),
", ".join(texargs))
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
_print_Min = _print_Max = _hprint_variadic_function
def _print_floor(self, expr, exp=None):
tex = r"\left\lfloor{%s}\right\rfloor" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_ceiling(self, expr, exp=None):
tex = r"\left\lceil{%s}\right\rceil" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_log(self, expr, exp=None):
if not self._settings["ln_notation"]:
tex = r"\log{\left(%s \right)}" % self._print(expr.args[0])
else:
tex = r"\ln{\left(%s \right)}" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_Abs(self, expr, exp=None):
tex = r"\left|{%s}\right|" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
_print_Determinant = _print_Abs
def _print_re(self, expr, exp=None):
if self._settings['gothic_re_im']:
tex = r"\Re{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom'])
else:
tex = r"\operatorname{{re}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom']))
return self._do_exponent(tex, exp)
def _print_im(self, expr, exp=None):
if self._settings['gothic_re_im']:
tex = r"\Im{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom'])
else:
tex = r"\operatorname{{im}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom']))
return self._do_exponent(tex, exp)
def _print_Not(self, e):
from sympy.logic.boolalg import (Equivalent, Implies)
if isinstance(e.args[0], Equivalent):
return self._print_Equivalent(e.args[0], r"\not\Leftrightarrow")
if isinstance(e.args[0], Implies):
return self._print_Implies(e.args[0], r"\not\Rightarrow")
if (e.args[0].is_Boolean):
return r"\neg \left(%s\right)" % self._print(e.args[0])
else:
return r"\neg %s" % self._print(e.args[0])
def _print_LogOp(self, args, char):
arg = args[0]
if arg.is_Boolean and not arg.is_Not:
tex = r"\left(%s\right)" % self._print(arg)
else:
tex = r"%s" % self._print(arg)
for arg in args[1:]:
if arg.is_Boolean and not arg.is_Not:
tex += r" %s \left(%s\right)" % (char, self._print(arg))
else:
tex += r" %s %s" % (char, self._print(arg))
return tex
def _print_And(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r"\wedge")
def _print_Or(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r"\vee")
def _print_Xor(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r"\veebar")
def _print_Implies(self, e, altchar=None):
return self._print_LogOp(e.args, altchar or r"\Rightarrow")
def _print_Equivalent(self, e, altchar=None):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, altchar or r"\Leftrightarrow")
def _print_conjugate(self, expr, exp=None):
tex = r"\overline{%s}" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_polar_lift(self, expr, exp=None):
func = r"\operatorname{polar\_lift}"
arg = r"{\left(%s \right)}" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}%s" % (func, exp, arg)
else:
return r"%s%s" % (func, arg)
def _print_ExpBase(self, expr, exp=None):
# TODO should exp_polar be printed differently?
# what about exp_polar(0), exp_polar(1)?
tex = r"e^{%s}" % self._print(expr.args[0])
return self._do_exponent(tex, exp)
def _print_Exp1(self, expr, exp=None):
return "e"
def _print_elliptic_k(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"K^{%s}%s" % (exp, tex)
else:
return r"K%s" % tex
def _print_elliptic_f(self, expr, exp=None):
tex = r"\left(%s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]))
if exp is not None:
return r"F^{%s}%s" % (exp, tex)
else:
return r"F%s" % tex
def _print_elliptic_e(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"\left(%s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"E^{%s}%s" % (exp, tex)
else:
return r"E%s" % tex
def _print_elliptic_pi(self, expr, exp=None):
if len(expr.args) == 3:
tex = r"\left(%s; %s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]),
self._print(expr.args[2]))
else:
tex = r"\left(%s\middle| %s\right)" % \
(self._print(expr.args[0]), self._print(expr.args[1]))
if exp is not None:
return r"\Pi^{%s}%s" % (exp, tex)
else:
return r"\Pi%s" % tex
def _print_beta(self, expr, exp=None):
tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"\operatorname{B}^{%s}%s" % (exp, tex)
else:
return r"\operatorname{B}%s" % tex
def _print_betainc(self, expr, exp=None, operator='B'):
largs = [self._print(arg) for arg in expr.args]
tex = r"\left(%s, %s\right)" % (largs[0], largs[1])
if exp is not None:
return r"\operatorname{%s}_{(%s, %s)}^{%s}%s" % (operator, largs[2], largs[3], exp, tex)
else:
return r"\operatorname{%s}_{(%s, %s)}%s" % (operator, largs[2], largs[3], tex)
def _print_betainc_regularized(self, expr, exp=None):
return self._print_betainc(expr, exp, operator='I')
def _print_uppergamma(self, expr, exp=None):
tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"\Gamma^{%s}%s" % (exp, tex)
else:
return r"\Gamma%s" % tex
def _print_lowergamma(self, expr, exp=None):
tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"\gamma^{%s}%s" % (exp, tex)
else:
return r"\gamma%s" % tex
def _hprint_one_arg_func(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}%s" % (self._print(expr.func), exp, tex)
else:
return r"%s%s" % (self._print(expr.func), tex)
_print_gamma = _hprint_one_arg_func
def _print_Chi(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\operatorname{Chi}^{%s}%s" % (exp, tex)
else:
return r"\operatorname{Chi}%s" % tex
def _print_expint(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[1])
nu = self._print(expr.args[0])
if exp is not None:
return r"\operatorname{E}_{%s}^{%s}%s" % (nu, exp, tex)
else:
return r"\operatorname{E}_{%s}%s" % (nu, tex)
def _print_fresnels(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"S^{%s}%s" % (exp, tex)
else:
return r"S%s" % tex
def _print_fresnelc(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"C^{%s}%s" % (exp, tex)
else:
return r"C%s" % tex
def _print_subfactorial(self, expr, exp=None):
tex = r"!%s" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
if exp is not None:
return r"\left(%s\right)^{%s}" % (tex, exp)
else:
return tex
def _print_factorial(self, expr, exp=None):
tex = r"%s!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_factorial2(self, expr, exp=None):
tex = r"%s!!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_binomial(self, expr, exp=None):
tex = r"{\binom{%s}{%s}}" % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r"%s^{%s}" % (tex, exp)
else:
return tex
def _print_RisingFactorial(self, expr, exp=None):
n, k = expr.args
base = r"%s" % self.parenthesize(n, PRECEDENCE['Func'])
tex = r"{%s}^{\left(%s\right)}" % (base, self._print(k))
return self._do_exponent(tex, exp)
def _print_FallingFactorial(self, expr, exp=None):
n, k = expr.args
sub = r"%s" % self.parenthesize(k, PRECEDENCE['Func'])
tex = r"{\left(%s\right)}_{%s}" % (self._print(n), sub)
return self._do_exponent(tex, exp)
def _hprint_BesselBase(self, expr, exp, sym):
tex = r"%s" % (sym)
need_exp = False
if exp is not None:
if tex.find('^') == -1:
tex = r"%s^{%s}" % (tex, exp)
else:
need_exp = True
tex = r"%s_{%s}\left(%s\right)" % (tex, self._print(expr.order),
self._print(expr.argument))
if need_exp:
tex = self._do_exponent(tex, exp)
return tex
def _hprint_vec(self, vec):
if not vec:
return ""
s = ""
for i in vec[:-1]:
s += "%s, " % self._print(i)
s += self._print(vec[-1])
return s
def _print_besselj(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'J')
def _print_besseli(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'I')
def _print_besselk(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'K')
def _print_bessely(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'Y')
def _print_yn(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'y')
def _print_jn(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'j')
def _print_hankel1(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'H^{(1)}')
def _print_hankel2(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'H^{(2)}')
def _print_hn1(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'h^{(1)}')
def _print_hn2(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'h^{(2)}')
def _hprint_airy(self, expr, exp=None, notation=""):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}%s" % (notation, exp, tex)
else:
return r"%s%s" % (notation, tex)
def _hprint_airy_prime(self, expr, exp=None, notation=""):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"{%s^\prime}^{%s}%s" % (notation, exp, tex)
else:
return r"%s^\prime%s" % (notation, tex)
def _print_airyai(self, expr, exp=None):
return self._hprint_airy(expr, exp, 'Ai')
def _print_airybi(self, expr, exp=None):
return self._hprint_airy(expr, exp, 'Bi')
def _print_airyaiprime(self, expr, exp=None):
return self._hprint_airy_prime(expr, exp, 'Ai')
def _print_airybiprime(self, expr, exp=None):
return self._hprint_airy_prime(expr, exp, 'Bi')
def _print_hyper(self, expr, exp=None):
tex = r"{{}_{%s}F_{%s}\left(\begin{matrix} %s \\ %s \end{matrix}" \
r"\middle| {%s} \right)}" % \
(self._print(len(expr.ap)), self._print(len(expr.bq)),
self._hprint_vec(expr.ap), self._hprint_vec(expr.bq),
self._print(expr.argument))
if exp is not None:
tex = r"{%s}^{%s}" % (tex, exp)
return tex
def _print_meijerg(self, expr, exp=None):
tex = r"{G_{%s, %s}^{%s, %s}\left(\begin{matrix} %s & %s \\" \
r"%s & %s \end{matrix} \middle| {%s} \right)}" % \
(self._print(len(expr.ap)), self._print(len(expr.bq)),
self._print(len(expr.bm)), self._print(len(expr.an)),
self._hprint_vec(expr.an), self._hprint_vec(expr.aother),
self._hprint_vec(expr.bm), self._hprint_vec(expr.bother),
self._print(expr.argument))
if exp is not None:
tex = r"{%s}^{%s}" % (tex, exp)
return tex
def _print_dirichlet_eta(self, expr, exp=None):
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\eta^{%s}%s" % (exp, tex)
return r"\eta%s" % tex
def _print_zeta(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"\left(%s, %s\right)" % tuple(map(self._print, expr.args))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\zeta^{%s}%s" % (exp, tex)
return r"\zeta%s" % tex
def _print_stieltjes(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"_{%s}\left(%s\right)" % tuple(map(self._print, expr.args))
else:
tex = r"_{%s}" % self._print(expr.args[0])
if exp is not None:
return r"\gamma%s^{%s}" % (tex, exp)
return r"\gamma%s" % tex
def _print_lerchphi(self, expr, exp=None):
tex = r"\left(%s, %s, %s\right)" % tuple(map(self._print, expr.args))
if exp is None:
return r"\Phi%s" % tex
return r"\Phi^{%s}%s" % (exp, tex)
def _print_polylog(self, expr, exp=None):
s, z = map(self._print, expr.args)
tex = r"\left(%s\right)" % z
if exp is None:
return r"\operatorname{Li}_{%s}%s" % (s, tex)
return r"\operatorname{Li}_{%s}^{%s}%s" % (s, exp, tex)
def _print_jacobi(self, expr, exp=None):
n, a, b, x = map(self._print, expr.args)
tex = r"P_{%s}^{\left(%s,%s\right)}\left(%s\right)" % (n, a, b, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_gegenbauer(self, expr, exp=None):
n, a, x = map(self._print, expr.args)
tex = r"C_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_chebyshevt(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"T_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_chebyshevu(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"U_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_legendre(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"P_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_assoc_legendre(self, expr, exp=None):
n, a, x = map(self._print, expr.args)
tex = r"P_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_hermite(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"H_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_laguerre(self, expr, exp=None):
n, x = map(self._print, expr.args)
tex = r"L_{%s}\left(%s\right)" % (n, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_assoc_laguerre(self, expr, exp=None):
n, a, x = map(self._print, expr.args)
tex = r"L_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_Ynm(self, expr, exp=None):
n, m, theta, phi = map(self._print, expr.args)
tex = r"Y_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def _print_Znm(self, expr, exp=None):
n, m, theta, phi = map(self._print, expr.args)
tex = r"Z_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi)
if exp is not None:
tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
return tex
def __print_mathieu_functions(self, character, args, prime=False, exp=None):
a, q, z = map(self._print, args)
sup = r"^{\prime}" if prime else ""
exp = "" if not exp else "^{%s}" % exp
return r"%s%s\left(%s, %s, %s\right)%s" % (character, sup, a, q, z, exp)
def _print_mathieuc(self, expr, exp=None):
return self.__print_mathieu_functions("C", expr.args, exp=exp)
def _print_mathieus(self, expr, exp=None):
return self.__print_mathieu_functions("S", expr.args, exp=exp)
def _print_mathieucprime(self, expr, exp=None):
return self.__print_mathieu_functions("C", expr.args, prime=True, exp=exp)
def _print_mathieusprime(self, expr, exp=None):
return self.__print_mathieu_functions("S", expr.args, prime=True, exp=exp)
def _print_Rational(self, expr):
if expr.q != 1:
sign = ""
p = expr.p
if expr.p < 0:
sign = "- "
p = -p
if self._settings['fold_short_frac']:
return r"%s%d / %d" % (sign, p, expr.q)
return r"%s\frac{%d}{%d}" % (sign, p, expr.q)
else:
return self._print(expr.p)
def _print_Order(self, expr):
s = self._print(expr.expr)
if expr.point and any(p != S.Zero for p in expr.point) or \
len(expr.variables) > 1:
s += '; '
if len(expr.variables) > 1:
s += self._print(expr.variables)
elif expr.variables:
s += self._print(expr.variables[0])
s += r'\rightarrow '
if len(expr.point) > 1:
s += self._print(expr.point)
else:
s += self._print(expr.point[0])
return r"O\left(%s\right)" % s
def _print_Symbol(self, expr, style='plain'):
if expr in self._settings['symbol_names']:
return self._settings['symbol_names'][expr]
return self._deal_with_super_sub(expr.name, style=style)
_print_RandomSymbol = _print_Symbol
def _deal_with_super_sub(self, string, style='plain'):
if '{' in string:
name, supers, subs = string, [], []
else:
name, supers, subs = split_super_sub(string)
name = translate(name)
supers = [translate(sup) for sup in supers]
subs = [translate(sub) for sub in subs]
# apply the style only to the name
if style == 'bold':
name = "\\mathbf{{{}}}".format(name)
# glue all items together:
if supers:
name += "^{%s}" % " ".join(supers)
if subs:
name += "_{%s}" % " ".join(subs)
return name
def _print_Relational(self, expr):
if self._settings['itex']:
gt = r"\gt"
lt = r"\lt"
else:
gt = ">"
lt = "<"
charmap = {
"==": "=",
">": gt,
"<": lt,
">=": r"\geq",
"<=": r"\leq",
"!=": r"\neq",
}
return "%s %s %s" % (self._print(expr.lhs),
charmap[expr.rel_op], self._print(expr.rhs))
def _print_Piecewise(self, expr):
ecpairs = [r"%s & \text{for}\: %s" % (self._print(e), self._print(c))
for e, c in expr.args[:-1]]
if expr.args[-1].cond == true:
ecpairs.append(r"%s & \text{otherwise}" %
self._print(expr.args[-1].expr))
else:
ecpairs.append(r"%s & \text{for}\: %s" %
(self._print(expr.args[-1].expr),
self._print(expr.args[-1].cond)))
tex = r"\begin{cases} %s \end{cases}"
return tex % r" \\".join(ecpairs)
def _print_MatrixBase(self, expr):
lines = []
for line in range(expr.rows): # horrible, should be 'rows'
lines.append(" & ".join([self._print(i) for i in expr[line, :]]))
mat_str = self._settings['mat_str']
if mat_str is None:
if self._settings['mode'] == 'inline':
mat_str = 'smallmatrix'
else:
if (expr.cols <= 10) is True:
mat_str = 'matrix'
else:
mat_str = 'array'
out_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}'
out_str = out_str.replace('%MATSTR%', mat_str)
if mat_str == 'array':
out_str = out_str.replace('%s', '{' + 'c'*expr.cols + '}%s')
if self._settings['mat_delim']:
left_delim = self._settings['mat_delim']
right_delim = self._delim_dict[left_delim]
out_str = r'\left' + left_delim + out_str + \
r'\right' + right_delim
return out_str % r"\\".join(lines)
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 latexslice(x, dim):
x = list(x)
if x[2] == 1:
del x[2]
if x[0] == 0:
x[0] = None
if x[1] == dim:
x[1] = None
return ':'.join(self._print(xi) if xi is not None else '' for xi in x)
return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + r'\left[' +
latexslice(expr.rowslice, expr.parent.rows) + ', ' +
latexslice(expr.colslice, expr.parent.cols) + r'\right]')
def _print_BlockMatrix(self, expr):
return self._print(expr.blocks)
def _print_Transpose(self, expr):
mat = expr.arg
from sympy.matrices import MatrixSymbol
if not isinstance(mat, MatrixSymbol) and mat.is_MatrixExpr:
return r"\left(%s\right)^{T}" % self._print(mat)
else:
s = self.parenthesize(mat, precedence_traditional(expr), True)
if '^' in s:
return r"\left(%s\right)^{T}" % s
else:
return "%s^{T}" % s
def _print_Trace(self, expr):
mat = expr.arg
return r"\operatorname{tr}\left(%s \right)" % self._print(mat)
def _print_Adjoint(self, expr):
mat = expr.arg
from sympy.matrices import MatrixSymbol
if not isinstance(mat, MatrixSymbol) and mat.is_MatrixExpr:
return r"\left(%s\right)^{\dagger}" % self._print(mat)
else:
s = self.parenthesize(mat, precedence_traditional(expr), True)
if '^' in s:
return r"\left(%s\right)^{\dagger}" % s
else:
return r"%s^{\dagger}" % s
def _print_MatMul(self, expr):
from sympy.matrices.expressions.matmul import MatMul
parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
False)
args = expr.args
if isinstance(args[0], Mul):
args = args[0].as_ordered_factors() + list(args[1:])
else:
args = list(args)
if isinstance(expr, MatMul) and expr.could_extract_minus_sign():
if args[0] == -1:
args = args[1:]
else:
args[0] = -args[0]
return '- ' + ' '.join(map(parens, args))
else:
return ' '.join(map(parens, args))
def _print_Mod(self, expr, exp=None):
if exp is not None:
return r'\left(%s \bmod %s\right)^{%s}' % \
(self.parenthesize(expr.args[0], PRECEDENCE['Mul'],
strict=True),
self.parenthesize(expr.args[1], PRECEDENCE['Mul'],
strict=True),
exp)
return r'%s \bmod %s' % (self.parenthesize(expr.args[0],
PRECEDENCE['Mul'],
strict=True),
self.parenthesize(expr.args[1],
PRECEDENCE['Mul'],
strict=True))
def _print_HadamardProduct(self, expr):
args = expr.args
prec = PRECEDENCE['Pow']
parens = self.parenthesize
return r' \circ '.join(
map(lambda arg: parens(arg, prec, strict=True), args))
def _print_HadamardPower(self, expr):
if precedence_traditional(expr.exp) < PRECEDENCE["Mul"]:
template = r"%s^{\circ \left({%s}\right)}"
else:
template = r"%s^{\circ {%s}}"
return self._helper_print_standard_power(expr, template)
def _print_KroneckerProduct(self, expr):
args = expr.args
prec = PRECEDENCE['Pow']
parens = self.parenthesize
return r' \otimes '.join(
map(lambda arg: parens(arg, prec, strict=True), args))
def _print_MatPow(self, expr):
base, exp = expr.base, expr.exp
from sympy.matrices import MatrixSymbol
if not isinstance(base, MatrixSymbol):
return "\\left(%s\\right)^{%s}" % (self._print(base),
self._print(exp))
else:
base_str = self._print(base)
if '^' in base_str:
return r"\left(%s\right)^{%s}" % (base_str, self._print(exp))
else:
return "%s^{%s}" % (base_str, self._print(exp))
def _print_MatrixSymbol(self, expr):
return self._print_Symbol(expr, style=self._settings[
'mat_symbol_style'])
def _print_ZeroMatrix(self, Z):
return "0" if self._settings[
'mat_symbol_style'] == 'plain' else r"\mathbf{0}"
def _print_OneMatrix(self, O):
return "1" if self._settings[
'mat_symbol_style'] == 'plain' else r"\mathbf{1}"
def _print_Identity(self, I):
return r"\mathbb{I}" if self._settings[
'mat_symbol_style'] == 'plain' else r"\mathbf{I}"
def _print_PermutationMatrix(self, P):
perm_str = self._print(P.args[0])
return "P_{%s}" % perm_str
def _print_NDimArray(self, expr):
if expr.rank() == 0:
return self._print(expr[()])
mat_str = self._settings['mat_str']
if mat_str is None:
if self._settings['mode'] == 'inline':
mat_str = 'smallmatrix'
else:
if (expr.rank() == 0) or (expr.shape[-1] <= 10):
mat_str = 'matrix'
else:
mat_str = 'array'
block_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}'
block_str = block_str.replace('%MATSTR%', mat_str)
if self._settings['mat_delim']:
left_delim = self._settings['mat_delim']
right_delim = self._delim_dict[left_delim]
block_str = r'\left' + left_delim + block_str + \
r'\right' + right_delim
if expr.rank() == 0:
return block_str % ""
level_str = [[]] + [[] for i in range(expr.rank())]
shape_ranges = [list(range(i)) for i in expr.shape]
for outer_i in itertools.product(*shape_ranges):
level_str[-1].append(self._print(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(
r" & ".join(level_str[back_outer_i+1]))
else:
level_str[back_outer_i].append(
block_str % (r"\\".join(level_str[back_outer_i+1])))
if len(level_str[back_outer_i+1]) == 1:
level_str[back_outer_i][-1] = r"\left[" + \
level_str[back_outer_i][-1] + r"\right]"
even = not even
level_str[back_outer_i+1] = []
out_str = level_str[0][0]
if expr.rank() % 2 == 1:
out_str = block_str % out_str
return out_str
def _printer_tensor_indices(self, name, indices, index_map={}):
out_str = self._print(name)
last_valence = None
prev_map = None
for index in indices:
new_valence = index.is_up
if ((index in index_map) or prev_map) and \
last_valence == new_valence:
out_str += ","
if last_valence != new_valence:
if last_valence is not None:
out_str += "}"
if index.is_up:
out_str += "{}^{"
else:
out_str += "{}_{"
out_str += self._print(index.args[0])
if index in index_map:
out_str += "="
out_str += self._print(index_map[index])
prev_map = True
else:
prev_map = False
last_valence = new_valence
if last_valence is not None:
out_str += "}"
return out_str
def _print_Tensor(self, expr):
name = expr.args[0].args[0]
indices = expr.get_indices()
return self._printer_tensor_indices(name, indices)
def _print_TensorElement(self, expr):
name = expr.expr.args[0].args[0]
indices = expr.expr.get_indices()
index_map = expr.index_map
return self._printer_tensor_indices(name, indices, index_map)
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):
a = []
args = expr.args
for x in args:
a.append(self.parenthesize(x, precedence(expr)))
a.sort()
s = ' + '.join(a)
s = s.replace('+ -', '- ')
return s
def _print_TensorIndex(self, expr):
return "{}%s{%s}" % (
"^" if expr.is_up else "_",
self._print(expr.args[0])
)
def _print_PartialDerivative(self, expr):
if len(expr.variables) == 1:
return r"\frac{\partial}{\partial {%s}}{%s}" % (
self._print(expr.variables[0]),
self.parenthesize(expr.expr, PRECEDENCE["Mul"], False)
)
else:
return r"\frac{\partial^{%s}}{%s}{%s}" % (
len(expr.variables),
" ".join([r"\partial {%s}" % self._print(i) for i in expr.variables]),
self.parenthesize(expr.expr, PRECEDENCE["Mul"], False)
)
def _print_ArraySymbol(self, expr):
return self._print(expr.name)
def _print_ArrayElement(self, expr):
return "{{%s}_{%s}}" % (
self.parenthesize(expr.name, PRECEDENCE["Func"], True),
", ".join([f"{self._print(i)}" for i in expr.indices]))
def _print_UniversalSet(self, expr):
return r"\mathbb{U}"
def _print_frac(self, expr, exp=None):
if exp is None:
return r"\operatorname{frac}{\left(%s\right)}" % self._print(expr.args[0])
else:
return r"\operatorname{frac}{\left(%s\right)}^{%s}" % (
self._print(expr.args[0]), exp)
def _print_tuple(self, expr):
if self._settings['decimal_separator'] == 'comma':
sep = ";"
elif self._settings['decimal_separator'] == 'period':
sep = ","
else:
raise ValueError('Unknown Decimal Separator')
if len(expr) == 1:
# 1-tuple needs a trailing separator
return self._add_parens_lspace(self._print(expr[0]) + sep)
else:
return self._add_parens_lspace(
(sep + r" \ ").join([self._print(i) for i in expr]))
def _print_TensorProduct(self, expr):
elements = [self._print(a) for a in expr.args]
return r' \otimes '.join(elements)
def _print_WedgeProduct(self, expr):
elements = [self._print(a) for a in expr.args]
return r' \wedge '.join(elements)
def _print_Tuple(self, expr):
return self._print_tuple(expr)
def _print_list(self, expr):
if self._settings['decimal_separator'] == 'comma':
return r"\left[ %s\right]" % \
r"; \ ".join([self._print(i) for i in expr])
elif self._settings['decimal_separator'] == 'period':
return r"\left[ %s\right]" % \
r", \ ".join([self._print(i) for i in expr])
else:
raise ValueError('Unknown Decimal Separator')
def _print_dict(self, d):
keys = sorted(d.keys(), key=default_sort_key)
items = []
for key in keys:
val = d[key]
items.append("%s : %s" % (self._print(key), self._print(val)))
return r"\left\{ %s\right\}" % r", \ ".join(items)
def _print_Dict(self, expr):
return self._print_dict(expr)
def _print_DiracDelta(self, expr, exp=None):
if len(expr.args) == 1 or expr.args[1] == 0:
tex = r"\delta\left(%s\right)" % self._print(expr.args[0])
else:
tex = r"\delta^{\left( %s \right)}\left( %s \right)" % (
self._print(expr.args[1]), self._print(expr.args[0]))
if exp:
tex = r"\left(%s\right)^{%s}" % (tex, exp)
return tex
def _print_SingularityFunction(self, expr, exp=None):
shift = self._print(expr.args[0] - expr.args[1])
power = self._print(expr.args[2])
tex = r"{\left\langle %s \right\rangle}^{%s}" % (shift, power)
if exp is not None:
tex = r"{\left({\langle %s \rangle}^{%s}\right)}^{%s}" % (shift, power, exp)
return tex
def _print_Heaviside(self, expr, exp=None):
pargs = ', '.join(self._print(arg) for arg in expr.pargs)
tex = r"\theta\left(%s\right)" % pargs
if exp:
tex = r"\left(%s\right)^{%s}" % (tex, exp)
return tex
def _print_KroneckerDelta(self, expr, exp=None):
i = self._print(expr.args[0])
j = self._print(expr.args[1])
if expr.args[0].is_Atom and expr.args[1].is_Atom:
tex = r'\delta_{%s %s}' % (i, j)
else:
tex = r'\delta_{%s, %s}' % (i, j)
if exp is not None:
tex = r'\left(%s\right)^{%s}' % (tex, exp)
return tex
def _print_LeviCivita(self, expr, exp=None):
indices = map(self._print, expr.args)
if all(x.is_Atom for x in expr.args):
tex = r'\varepsilon_{%s}' % " ".join(indices)
else:
tex = r'\varepsilon_{%s}' % ", ".join(indices)
if exp:
tex = r'\left(%s\right)^{%s}' % (tex, exp)
return tex
def _print_RandomDomain(self, d):
if hasattr(d, 'as_boolean'):
return '\\text{Domain: }' + self._print(d.as_boolean())
elif hasattr(d, 'set'):
return ('\\text{Domain: }' + self._print(d.symbols) + ' \\in ' +
self._print(d.set))
elif hasattr(d, 'symbols'):
return '\\text{Domain on }' + self._print(d.symbols)
else:
return self._print(None)
def _print_FiniteSet(self, s):
items = sorted(s.args, key=default_sort_key)
return self._print_set(items)
def _print_set(self, s):
items = sorted(s, key=default_sort_key)
if self._settings['decimal_separator'] == 'comma':
items = "; ".join(map(self._print, items))
elif self._settings['decimal_separator'] == 'period':
items = ", ".join(map(self._print, items))
else:
raise ValueError('Unknown Decimal Separator')
return r"\left\{%s\right\}" % items
_print_frozenset = _print_set
def _print_Range(self, s):
def _print_symbolic_range():
# Symbolic Range that cannot be resolved
if s.args[0] == 0:
if s.args[2] == 1:
cont = self._print(s.args[1])
else:
cont = ", ".join(self._print(arg) for arg in s.args)
else:
if s.args[2] == 1:
cont = ", ".join(self._print(arg) for arg in s.args[:2])
else:
cont = ", ".join(self._print(arg) for arg in s.args)
return(f"\\text{{Range}}\\left({cont}\\right)")
dots = object()
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 s.is_empty is not None:
if (s.size < 4) == True:
printset = tuple(s)
elif s.is_iterable:
it = iter(s)
printset = next(it), next(it), dots, s[-1]
else:
return _print_symbolic_range()
else:
return _print_symbolic_range()
return (r"\left\{" +
r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) +
r"\right\}")
def __print_number_polynomial(self, expr, letter, exp=None):
if len(expr.args) == 2:
if exp is not None:
return r"%s_{%s}^{%s}\left(%s\right)" % (letter,
self._print(expr.args[0]), exp,
self._print(expr.args[1]))
return r"%s_{%s}\left(%s\right)" % (letter,
self._print(expr.args[0]), self._print(expr.args[1]))
tex = r"%s_{%s}" % (letter, self._print(expr.args[0]))
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
return tex
def _print_bernoulli(self, expr, exp=None):
return self.__print_number_polynomial(expr, "B", exp)
def _print_bell(self, expr, exp=None):
if len(expr.args) == 3:
tex1 = r"B_{%s, %s}" % (self._print(expr.args[0]),
self._print(expr.args[1]))
tex2 = r"\left(%s\right)" % r", ".join(self._print(el) for
el in expr.args[2])
if exp is not None:
tex = r"%s^{%s}%s" % (tex1, exp, tex2)
else:
tex = tex1 + tex2
return tex
return self.__print_number_polynomial(expr, "B", exp)
def _print_fibonacci(self, expr, exp=None):
return self.__print_number_polynomial(expr, "F", exp)
def _print_lucas(self, expr, exp=None):
tex = r"L_{%s}" % self._print(expr.args[0])
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
return tex
def _print_tribonacci(self, expr, exp=None):
return self.__print_number_polynomial(expr, "T", exp)
def _print_SeqFormula(self, s):
dots = object()
if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0:
return r"\left\{%s\right\}_{%s=%s}^{%s}" % (
self._print(s.formula),
self._print(s.variables[0]),
self._print(s.start),
self._print(s.stop)
)
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)
else:
printset = tuple(s)
return (r"\left[" +
r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) +
r"\right]")
_print_SeqPer = _print_SeqFormula
_print_SeqAdd = _print_SeqFormula
_print_SeqMul = _print_SeqFormula
def _print_Interval(self, i):
if i.start == i.end:
return r"\left\{%s\right\}" % self._print(i.start)
else:
if i.left_open:
left = '('
else:
left = '['
if i.right_open:
right = ')'
else:
right = ']'
return r"\left%s%s, %s\right%s" % \
(left, self._print(i.start), self._print(i.end), right)
def _print_AccumulationBounds(self, i):
return r"\left\langle %s, %s\right\rangle" % \
(self._print(i.min), self._print(i.max))
def _print_Union(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \cup ".join(args_str)
def _print_Complement(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \setminus ".join(args_str)
def _print_Intersection(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \cap ".join(args_str)
def _print_SymmetricDifference(self, u):
prec = precedence_traditional(u)
args_str = [self.parenthesize(i, prec) for i in u.args]
return r" \triangle ".join(args_str)
def _print_ProductSet(self, p):
prec = precedence_traditional(p)
if len(p.sets) >= 1 and not has_variety(p.sets):
return self.parenthesize(p.sets[0], prec) + "^{%d}" % len(p.sets)
return r" \times ".join(
self.parenthesize(set, prec) for set in p.sets)
def _print_EmptySet(self, e):
return r"\emptyset"
def _print_Naturals(self, n):
return r"\mathbb{N}"
def _print_Naturals0(self, n):
return r"\mathbb{N}_0"
def _print_Integers(self, i):
return r"\mathbb{Z}"
def _print_Rationals(self, i):
return r"\mathbb{Q}"
def _print_Reals(self, i):
return r"\mathbb{R}"
def _print_Complexes(self, i):
return r"\mathbb{C}"
def _print_ImageSet(self, s):
expr = s.lamda.expr
sig = s.lamda.signature
xys = ((self._print(x), self._print(y)) for x, y in zip(sig, s.base_sets))
xinys = r", ".join(r"%s \in %s" % xy for xy in xys)
return r"\left\{%s\; \middle|\; %s\right\}" % (self._print(expr), xinys)
def _print_ConditionSet(self, s):
vars_print = ', '.join([self._print(var) for var in Tuple(s.sym)])
if s.base_set is S.UniversalSet:
return r"\left\{%s\; \middle|\; %s \right\}" % \
(vars_print, self._print(s.condition))
return r"\left\{%s\; \middle|\; %s \in %s \wedge %s \right\}" % (
vars_print,
vars_print,
self._print(s.base_set),
self._print(s.condition))
def _print_PowerSet(self, expr):
arg_print = self._print(expr.args[0])
return r"\mathcal{{P}}\left({}\right)".format(arg_print)
def _print_ComplexRegion(self, s):
vars_print = ', '.join([self._print(var) for var in s.variables])
return r"\left\{%s\; \middle|\; %s \in %s \right\}" % (
self._print(s.expr),
vars_print,
self._print(s.sets))
def _print_Contains(self, e):
return r"%s \in %s" % tuple(self._print(a) for a in e.args)
def _print_FourierSeries(self, s):
if s.an.formula is S.Zero and s.bn.formula is S.Zero:
return self._print(s.a0)
return self._print_Add(s.truncate()) + r' + \ldots'
def _print_FormalPowerSeries(self, s):
return self._print_Add(s.infinite)
def _print_FiniteField(self, expr):
return r"\mathbb{F}_{%s}" % expr.mod
def _print_IntegerRing(self, expr):
return r"\mathbb{Z}"
def _print_RationalField(self, expr):
return r"\mathbb{Q}"
def _print_RealField(self, expr):
return r"\mathbb{R}"
def _print_ComplexField(self, expr):
return r"\mathbb{C}"
def _print_PolynomialRing(self, expr):
domain = self._print(expr.domain)
symbols = ", ".join(map(self._print, expr.symbols))
return r"%s\left[%s\right]" % (domain, symbols)
def _print_FractionField(self, expr):
domain = self._print(expr.domain)
symbols = ", ".join(map(self._print, expr.symbols))
return r"%s\left(%s\right)" % (domain, symbols)
def _print_PolynomialRingBase(self, expr):
domain = self._print(expr.domain)
symbols = ", ".join(map(self._print, expr.symbols))
inv = ""
if not expr.is_Poly:
inv = r"S_<^{-1}"
return r"%s%s\left[%s\right]" % (inv, domain, symbols)
def _print_Poly(self, poly):
cls = poly.__class__.__name__
terms = []
for monom, coeff in poly.terms():
s_monom = ''
for i, exp in enumerate(monom):
if exp > 0:
if exp == 1:
s_monom += self._print(poly.gens[i])
else:
s_monom += self._print(pow(poly.gens[i], exp))
if coeff.is_Add:
if s_monom:
s_coeff = r"\left(%s\right)" % 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]
expr = ' '.join(terms)
gens = list(map(self._print, poly.gens))
domain = "domain=%s" % self._print(poly.get_domain())
args = ", ".join([expr] + gens + [domain])
if cls in accepted_latex_functions:
tex = r"\%s {\left(%s \right)}" % (cls, args)
else:
tex = r"\operatorname{%s}{\left( %s \right)}" % (cls, args)
return tex
def _print_ComplexRootOf(self, root):
cls = root.__class__.__name__
if cls == "ComplexRootOf":
cls = "CRootOf"
expr = self._print(root.expr)
index = root.index
if cls in accepted_latex_functions:
return r"\%s {\left(%s, %d\right)}" % (cls, expr, index)
else:
return r"\operatorname{%s} {\left(%s, %d\right)}" % (cls, expr,
index)
def _print_RootSum(self, expr):
cls = expr.__class__.__name__
args = [self._print(expr.expr)]
if expr.fun is not S.IdentityFunction:
args.append(self._print(expr.fun))
if cls in accepted_latex_functions:
return r"\%s {\left(%s\right)}" % (cls, ", ".join(args))
else:
return r"\operatorname{%s} {\left(%s\right)}" % (cls,
", ".join(args))
def _print_OrdinalOmega(self, expr):
return r"\omega"
def _print_OmegaPower(self, expr):
exp, mul = expr.args
if mul != 1:
if exp != 1:
return r"{} \omega^{{{}}}".format(mul, exp)
else:
return r"{} \omega".format(mul)
else:
if exp != 1:
return r"\omega^{{{}}}".format(exp)
else:
return r"\omega"
def _print_Ordinal(self, expr):
return " + ".join([self._print(arg) for arg in expr.args])
def _print_PolyElement(self, poly):
mul_symbol = self._settings['mul_symbol_latex']
return poly.str(self, PRECEDENCE, "{%s}^{%d}", mul_symbol)
def _print_FracElement(self, frac):
if frac.denom == 1:
return self._print(frac.numer)
else:
numer = self._print(frac.numer)
denom = self._print(frac.denom)
return r"\frac{%s}{%s}" % (numer, denom)
def _print_euler(self, expr, exp=None):
m, x = (expr.args[0], None) if len(expr.args) == 1 else expr.args
tex = r"E_{%s}" % self._print(m)
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
if x is not None:
tex = r"%s\left(%s\right)" % (tex, self._print(x))
return tex
def _print_catalan(self, expr, exp=None):
tex = r"C_{%s}" % self._print(expr.args[0])
if exp is not None:
tex = r"%s^{%s}" % (tex, exp)
return tex
def _print_UnifiedTransform(self, expr, s, inverse=False):
return r"\mathcal{{{}}}{}_{{{}}}\left[{}\right]\left({}\right)".format(s, '^{-1}' if inverse else '', self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))
def _print_MellinTransform(self, expr):
return self._print_UnifiedTransform(expr, 'M')
def _print_InverseMellinTransform(self, expr):
return self._print_UnifiedTransform(expr, 'M', True)
def _print_LaplaceTransform(self, expr):
return self._print_UnifiedTransform(expr, 'L')
def _print_InverseLaplaceTransform(self, expr):
return self._print_UnifiedTransform(expr, 'L', True)
def _print_FourierTransform(self, expr):
return self._print_UnifiedTransform(expr, 'F')
def _print_InverseFourierTransform(self, expr):
return self._print_UnifiedTransform(expr, 'F', True)
def _print_SineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'SIN')
def _print_InverseSineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'SIN', True)
def _print_CosineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'COS')
def _print_InverseCosineTransform(self, expr):
return self._print_UnifiedTransform(expr, 'COS', True)
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(Symbol(object.name))
def _print_LambertW(self, expr, exp=None):
arg0 = self._print(expr.args[0])
exp = r"^{%s}" % (exp,) if exp is not None else ""
if len(expr.args) == 1:
result = r"W%s\left(%s\right)" % (exp, arg0)
else:
arg1 = self._print(expr.args[1])
result = "W{0}_{{{1}}}\\left({2}\\right)".format(exp, arg1, arg0)
return result
def _print_Expectation(self, expr):
return r"\operatorname{{E}}\left[{}\right]".format(self._print(expr.args[0]))
def _print_Variance(self, expr):
return r"\operatorname{{Var}}\left({}\right)".format(self._print(expr.args[0]))
def _print_Covariance(self, expr):
return r"\operatorname{{Cov}}\left({}\right)".format(", ".join(self._print(arg) for arg in expr.args))
def _print_Probability(self, expr):
return r"\operatorname{{P}}\left({}\right)".format(self._print(expr.args[0]))
def _print_Morphism(self, morphism):
domain = self._print(morphism.domain)
codomain = self._print(morphism.codomain)
return "%s\\rightarrow %s" % (domain, codomain)
def _print_TransferFunction(self, expr):
num, den = self._print(expr.num), self._print(expr.den)
return r"\frac{%s}{%s}" % (num, den)
def _print_Series(self, expr):
args = list(expr.args)
parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
False)
return ' '.join(map(parens, args))
def _print_MIMOSeries(self, expr):
from sympy.physics.control.lti import MIMOParallel
args = list(expr.args)[::-1]
parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
False) if isinstance(x, MIMOParallel) else self._print(x)
return r"\cdot".join(map(parens, args))
def _print_Parallel(self, expr):
return ' + '.join(map(self._print, expr.args))
def _print_MIMOParallel(self, expr):
return ' + '.join(map(self._print, expr.args))
def _print_Feedback(self, expr):
from sympy.physics.control import TransferFunction, Series
num, tf = expr.sys1, TransferFunction(1, 1, expr.var)
num_arg_list = list(num.args) if isinstance(num, Series) else [num]
den_arg_list = list(expr.sys2.args) if \
isinstance(expr.sys2, Series) else [expr.sys2]
den_term_1 = tf
if isinstance(num, Series) and isinstance(expr.sys2, Series):
den_term_2 = Series(*num_arg_list, *den_arg_list)
elif isinstance(num, Series) and isinstance(expr.sys2, TransferFunction):
if expr.sys2 == tf:
den_term_2 = Series(*num_arg_list)
else:
den_term_2 = tf, Series(*num_arg_list, expr.sys2)
elif isinstance(num, TransferFunction) and isinstance(expr.sys2, Series):
if num == tf:
den_term_2 = Series(*den_arg_list)
else:
den_term_2 = Series(num, *den_arg_list)
else:
if num == tf:
den_term_2 = Series(*den_arg_list)
elif expr.sys2 == tf:
den_term_2 = Series(*num_arg_list)
else:
den_term_2 = Series(*num_arg_list, *den_arg_list)
numer = self._print(num)
denom_1 = self._print(den_term_1)
denom_2 = self._print(den_term_2)
_sign = "+" if expr.sign == -1 else "-"
return r"\frac{%s}{%s %s %s}" % (numer, denom_1, _sign, denom_2)
def _print_MIMOFeedback(self, expr):
from sympy.physics.control import MIMOSeries
inv_mat = self._print(MIMOSeries(expr.sys2, expr.sys1))
sys1 = self._print(expr.sys1)
_sign = "+" if expr.sign == -1 else "-"
return r"\left(I_{\tau} %s %s\right)^{-1} \cdot %s" % (_sign, inv_mat, sys1)
def _print_TransferFunctionMatrix(self, expr):
mat = self._print(expr._expr_mat)
return r"%s_\tau" % mat
def _print_DFT(self, expr):
return r"\text{{{}}}_{{{}}}".format(expr.__class__.__name__, expr.n)
_print_IDFT = _print_DFT
def _print_NamedMorphism(self, morphism):
pretty_name = self._print(Symbol(morphism.name))
pretty_morphism = self._print_Morphism(morphism)
return "%s:%s" % (pretty_name, pretty_morphism)
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):
# All components of the morphism have names and it is thus
# possible to build the name of the composite.
component_names_list = [self._print(Symbol(component.name)) for
component in morphism.components]
component_names_list.reverse()
component_names = "\\circ ".join(component_names_list) + ":"
pretty_morphism = self._print_Morphism(morphism)
return component_names + pretty_morphism
def _print_Category(self, morphism):
return r"\mathbf{{{}}}".format(self._print(Symbol(morphism.name)))
def _print_Diagram(self, diagram):
if not diagram.premises:
# This is an empty diagram.
return self._print(S.EmptySet)
latex_result = self._print(diagram.premises)
if diagram.conclusions:
latex_result += "\\Longrightarrow %s" % \
self._print(diagram.conclusions)
return latex_result
def _print_DiagramGrid(self, grid):
latex_result = "\\begin{array}{%s}\n" % ("c" * grid.width)
for i in range(grid.height):
for j in range(grid.width):
if grid[i, j]:
latex_result += latex(grid[i, j])
latex_result += " "
if j != grid.width - 1:
latex_result += "& "
if i != grid.height - 1:
latex_result += "\\\\"
latex_result += "\n"
latex_result += "\\end{array}\n"
return latex_result
def _print_FreeModule(self, M):
return '{{{}}}^{{{}}}'.format(self._print(M.ring), self._print(M.rank))
def _print_FreeModuleElement(self, m):
# Print as row vector for convenience, for now.
return r"\left[ {} \right]".format(",".join(
'{' + self._print(x) + '}' for x in m))
def _print_SubModule(self, m):
return r"\left\langle {} \right\rangle".format(",".join(
'{' + self._print(x) + '}' for x in m.gens))
def _print_ModuleImplementedIdeal(self, m):
return r"\left\langle {} \right\rangle".format(",".join(
'{' + self._print(x) + '}' for [x] in m._module.gens))
def _print_Quaternion(self, expr):
# TODO: This expression is potentially confusing,
# shall we print it as `Quaternion( ... )`?
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_QuotientRing(self, R):
# TODO nicer fractions for few generators...
return r"\frac{{{}}}{{{}}}".format(self._print(R.ring),
self._print(R.base_ideal))
def _print_QuotientRingElement(self, x):
return r"{{{}}} + {{{}}}".format(self._print(x.data),
self._print(x.ring.base_ideal))
def _print_QuotientModuleElement(self, m):
return r"{{{}}} + {{{}}}".format(self._print(m.data),
self._print(m.module.killed_module))
def _print_QuotientModule(self, M):
# TODO nicer fractions for few generators...
return r"\frac{{{}}}{{{}}}".format(self._print(M.base),
self._print(M.killed_module))
def _print_MatrixHomomorphism(self, h):
return r"{{{}}} : {{{}}} \to {{{}}}".format(self._print(h._sympy_matrix()),
self._print(h.domain), self._print(h.codomain))
def _print_Manifold(self, manifold):
string = manifold.name.name
if '{' in string:
name, supers, subs = string, [], []
else:
name, supers, subs = split_super_sub(string)
name = translate(name)
supers = [translate(sup) for sup in supers]
subs = [translate(sub) for sub in subs]
name = r'\text{%s}' % name
if supers:
name += "^{%s}" % " ".join(supers)
if subs:
name += "_{%s}" % " ".join(subs)
return name
def _print_Patch(self, patch):
return r'\text{%s}_{%s}' % (self._print(patch.name), self._print(patch.manifold))
def _print_CoordSystem(self, coordsys):
return r'\text{%s}^{\text{%s}}_{%s}' % (
self._print(coordsys.name), self._print(coordsys.patch.name), self._print(coordsys.manifold)
)
def _print_CovarDerivativeOp(self, cvd):
return r'\mathbb{\nabla}_{%s}' % self._print(cvd._wrt)
def _print_BaseScalarField(self, field):
string = field._coord_sys.symbols[field._index].name
return r'\mathbf{{{}}}'.format(self._print(Symbol(string)))
def _print_BaseVectorField(self, field):
string = field._coord_sys.symbols[field._index].name
return r'\partial_{{{}}}'.format(self._print(Symbol(string)))
def _print_Differential(self, diff):
field = diff._form_field
if hasattr(field, '_coord_sys'):
string = field._coord_sys.symbols[field._index].name
return r'\operatorname{{d}}{}'.format(self._print(Symbol(string)))
else:
string = self._print(field)
return r'\operatorname{{d}}\left({}\right)'.format(string)
def _print_Tr(self, p):
# TODO: Handle indices
contents = self._print(p.args[0])
return r'\operatorname{{tr}}\left({}\right)'.format(contents)
def _print_totient(self, expr, exp=None):
if exp is not None:
return r'\left(\phi\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\phi\left(%s\right)' % self._print(expr.args[0])
def _print_reduced_totient(self, expr, exp=None):
if exp is not None:
return r'\left(\lambda\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\lambda\left(%s\right)' % self._print(expr.args[0])
def _print_divisor_sigma(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"_%s\left(%s\right)" % tuple(map(self._print,
(expr.args[1], expr.args[0])))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\sigma^{%s}%s" % (exp, tex)
return r"\sigma%s" % tex
def _print_udivisor_sigma(self, expr, exp=None):
if len(expr.args) == 2:
tex = r"_%s\left(%s\right)" % tuple(map(self._print,
(expr.args[1], expr.args[0])))
else:
tex = r"\left(%s\right)" % self._print(expr.args[0])
if exp is not None:
return r"\sigma^*^{%s}%s" % (exp, tex)
return r"\sigma^*%s" % tex
def _print_primenu(self, expr, exp=None):
if exp is not None:
return r'\left(\nu\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\nu\left(%s\right)' % self._print(expr.args[0])
def _print_primeomega(self, expr, exp=None):
if exp is not None:
return r'\left(\Omega\left(%s\right)\right)^{%s}' % \
(self._print(expr.args[0]), exp)
return r'\Omega\left(%s\right)' % self._print(expr.args[0])
def _print_Str(self, s):
return str(s.name)
def _print_float(self, expr):
return self._print(Float(expr))
def _print_int(self, expr):
return str(expr)
def _print_mpz(self, expr):
return str(expr)
def _print_mpq(self, expr):
return str(expr)
def _print_Predicate(self, expr):
return r"\operatorname{{Q}}_{{\text{{{}}}}}".format(latex_escape(str(expr.name)))
def _print_AppliedPredicate(self, expr):
pred = expr.function
args = expr.arguments
pred_latex = self._print(pred)
args_latex = ', '.join([self._print(a) for a in args])
return '%s(%s)' % (pred_latex, args_latex)
def emptyPrinter(self, expr):
# default to just printing as monospace, like would normally be shown
s = super().emptyPrinter(expr)
return r"\mathtt{\text{%s}}" % latex_escape(s)
def translate(s):
r'''
Check for a modifier ending the string. If present, convert the
modifier to latex and translate the rest recursively.
Given a description of a Greek letter or other special character,
return the appropriate latex.
Let everything else pass as given.
>>> from sympy.printing.latex import translate
>>> translate('alphahatdotprime')
"{\\dot{\\hat{\\alpha}}}'"
'''
# Process the rest
tex = tex_greek_dictionary.get(s)
if tex:
return tex
elif s.lower() in greek_letters_set:
return "\\" + s.lower()
elif s in other_symbols:
return "\\" + s
else:
# Process modifiers, if any, and recurse
for key in sorted(modifier_dict.keys(), key=len, reverse=True):
if s.lower().endswith(key) and len(s) > len(key):
return modifier_dict[key](translate(s[:-len(key)]))
return s
@print_function(LatexPrinter)
def latex(expr, **settings):
r"""Convert the given expression to LaTeX string representation.
Parameters
==========
full_prec: boolean, optional
If set to True, a floating point number is printed with full precision.
fold_frac_powers : boolean, optional
Emit ``^{p/q}`` instead of ``^{\frac{p}{q}}`` for fractional powers.
fold_func_brackets : boolean, optional
Fold function brackets where applicable.
fold_short_frac : boolean, optional
Emit ``p / q`` instead of ``\frac{p}{q}`` when the denominator is
simple enough (at most two terms and no powers). The default value is
``True`` for inline mode, ``False`` otherwise.
inv_trig_style : string, optional
How inverse trig functions should be displayed. Can be one of
``'abbreviated'``, ``'full'``, or ``'power'``. Defaults to
``'abbreviated'``.
itex : boolean, optional
Specifies if itex-specific syntax is used, including emitting
``$$...$$``.
ln_notation : boolean, optional
If set to ``True``, ``\ln`` is used instead of default ``\log``.
long_frac_ratio : float or None, optional
The allowed ratio of the width of the numerator to the width of the
denominator before the printer breaks off long fractions. If ``None``
(the default value), long fractions are not broken up.
mat_delim : string, optional
The delimiter to wrap around matrices. Can be one of ``'['``, ``'('``,
or the empty string ``''``. Defaults to ``'['``.
mat_str : string, optional
Which matrix environment string to emit. ``'smallmatrix'``,
``'matrix'``, ``'array'``, etc. Defaults to ``'smallmatrix'`` for
inline mode, ``'matrix'`` for matrices of no more than 10 columns, and
``'array'`` otherwise.
mode: string, optional
Specifies how the generated code will be delimited. ``mode`` can be one
of ``'plain'``, ``'inline'``, ``'equation'`` or ``'equation*'``. If
``mode`` is set to ``'plain'``, then the resulting code will not be
delimited at all (this is the default). If ``mode`` is set to
``'inline'`` then inline LaTeX ``$...$`` will be used. If ``mode`` is
set to ``'equation'`` or ``'equation*'``, the resulting code will be
enclosed in the ``equation`` or ``equation*`` environment (remember to
import ``amsmath`` for ``equation*``), unless the ``itex`` option is
set. In the latter case, the ``$$...$$`` syntax is used.
mul_symbol : string or None, optional
The symbol to use for multiplication. Can be one of ``None``,
``'ldot'``, ``'dot'``, or ``'times'``.
order: string, optional
Any of the supported monomial orderings (currently ``'lex'``,
``'grlex'``, or ``'grevlex'``), ``'old'``, and ``'none'``. This
parameter does nothing for `~.Mul` objects. Setting order to ``'old'``
uses the compatibility ordering for ``~.Add`` defined in Printer. For
very large expressions, set the ``order`` keyword to ``'none'`` if
speed is a concern.
symbol_names : dictionary of strings mapped to symbols, optional
Dictionary of symbols and the custom strings they should be emitted as.
root_notation : boolean, optional
If set to ``False``, exponents of the form 1/n are printed in fractonal
form. Default is ``True``, to print exponent in root form.
mat_symbol_style : string, optional
Can be either ``'plain'`` (default) or ``'bold'``. If set to
``'bold'``, a `~.MatrixSymbol` A will be printed as ``\mathbf{A}``,
otherwise as ``A``.
imaginary_unit : string, optional
String to use for the imaginary unit. Defined options are ``'i'``
(default) and ``'j'``. Adding ``r`` or ``t`` in front gives ``\mathrm``
or ``\text``, so ``'ri'`` leads to ``\mathrm{i}`` which gives
`\mathrm{i}`.
gothic_re_im : boolean, optional
If set to ``True``, `\Re` and `\Im` is used for ``re`` and ``im``, respectively.
The default is ``False`` leading to `\operatorname{re}` and `\operatorname{im}`.
decimal_separator : string, optional
Specifies what separator to use to separate the whole and fractional parts of a
floating point number as in `2.5` for the default, ``period`` or `2{,}5`
when ``comma`` is specified. Lists, sets, and tuple are printed with semicolon
separating the elements when ``comma`` is chosen. For example, [1; 2; 3] when
``comma`` is chosen and [1,2,3] for when ``period`` is chosen.
parenthesize_super : boolean, optional
If set to ``False``, superscripted expressions will not be parenthesized when
powered. Default is ``True``, which parenthesizes the expression when powered.
min: Integer or None, optional
Sets the lower bound for the exponent to print floating point numbers in
fixed-point format.
max: Integer or None, optional
Sets the upper bound for the exponent to print floating point numbers in
fixed-point format.
diff_operator: string, optional
String to use for differential operator. Default is ``'d'``, to print in italic
form. ``'rd'``, ``'td'`` are shortcuts for ``\mathrm{d}`` and ``\text{d}``.
Notes
=====
Not using a print statement for printing, results in double backslashes for
latex commands since that's the way Python escapes backslashes in strings.
>>> from sympy import latex, Rational
>>> from sympy.abc import tau
>>> latex((2*tau)**Rational(7,2))
'8 \\sqrt{2} \\tau^{\\frac{7}{2}}'
>>> print(latex((2*tau)**Rational(7,2)))
8 \sqrt{2} \tau^{\frac{7}{2}}
Examples
========
>>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log
>>> from sympy.abc import x, y, mu, r, tau
Basic usage:
>>> print(latex((2*tau)**Rational(7,2)))
8 \sqrt{2} \tau^{\frac{7}{2}}
``mode`` and ``itex`` options:
>>> print(latex((2*mu)**Rational(7,2), mode='plain'))
8 \sqrt{2} \mu^{\frac{7}{2}}
>>> print(latex((2*tau)**Rational(7,2), mode='inline'))
$8 \sqrt{2} \tau^{7 / 2}$
>>> print(latex((2*mu)**Rational(7,2), mode='equation*'))
\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}
>>> print(latex((2*mu)**Rational(7,2), mode='equation'))
\begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation}
>>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True))
$$8 \sqrt{2} \mu^{\frac{7}{2}}$$
>>> print(latex((2*mu)**Rational(7,2), mode='plain'))
8 \sqrt{2} \mu^{\frac{7}{2}}
>>> print(latex((2*tau)**Rational(7,2), mode='inline'))
$8 \sqrt{2} \tau^{7 / 2}$
>>> print(latex((2*mu)**Rational(7,2), mode='equation*'))
\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}
>>> print(latex((2*mu)**Rational(7,2), mode='equation'))
\begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation}
>>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True))
$$8 \sqrt{2} \mu^{\frac{7}{2}}$$
Fraction options:
>>> print(latex((2*tau)**Rational(7,2), fold_frac_powers=True))
8 \sqrt{2} \tau^{7/2}
>>> print(latex((2*tau)**sin(Rational(7,2))))
\left(2 \tau\right)^{\sin{\left(\frac{7}{2} \right)}}
>>> print(latex((2*tau)**sin(Rational(7,2)), fold_func_brackets=True))
\left(2 \tau\right)^{\sin {\frac{7}{2}}}
>>> print(latex(3*x**2/y))
\frac{3 x^{2}}{y}
>>> print(latex(3*x**2/y, fold_short_frac=True))
3 x^{2} / y
>>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=2))
\frac{\int r\, dr}{2 \pi}
>>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=0))
\frac{1}{2 \pi} \int r\, dr
Multiplication options:
>>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol="times"))
\left(2 \times \tau\right)^{\sin{\left(\frac{7}{2} \right)}}
Trig options:
>>> print(latex(asin(Rational(7,2))))
\operatorname{asin}{\left(\frac{7}{2} \right)}
>>> print(latex(asin(Rational(7,2)), inv_trig_style="full"))
\arcsin{\left(\frac{7}{2} \right)}
>>> print(latex(asin(Rational(7,2)), inv_trig_style="power"))
\sin^{-1}{\left(\frac{7}{2} \right)}
Matrix options:
>>> print(latex(Matrix(2, 1, [x, y])))
\left[\begin{matrix}x\\y\end{matrix}\right]
>>> print(latex(Matrix(2, 1, [x, y]), mat_str = "array"))
\left[\begin{array}{c}x\\y\end{array}\right]
>>> print(latex(Matrix(2, 1, [x, y]), mat_delim="("))
\left(\begin{matrix}x\\y\end{matrix}\right)
Custom printing of symbols:
>>> print(latex(x**2, symbol_names={x: 'x_i'}))
x_i^{2}
Logarithms:
>>> print(latex(log(10)))
\log{\left(10 \right)}
>>> print(latex(log(10), ln_notation=True))
\ln{\left(10 \right)}
``latex()`` also supports the builtin container types :class:`list`,
:class:`tuple`, and :class:`dict`:
>>> print(latex([2/x, y], mode='inline'))
$\left[ 2 / x, \ y\right]$
Unsupported types are rendered as monospaced plaintext:
>>> print(latex(int))
\mathtt{\text{<class 'int'>}}
>>> print(latex("plain % text"))
\mathtt{\text{plain \% text}}
See :ref:`printer_method_example` for an example of how to override
this behavior for your own types by implementing ``_latex``.
.. versionchanged:: 1.7.0
Unsupported types no longer have their ``str`` representation treated as valid latex.
"""
return LatexPrinter(settings).doprint(expr)
def print_latex(expr, **settings):
"""Prints LaTeX representation of the given expression. Takes the same
settings as ``latex()``."""
print(latex(expr, **settings))
def multiline_latex(lhs, rhs, terms_per_line=1, environment="align*", use_dots=False, **settings):
r"""
This function generates a LaTeX equation with a multiline right-hand side
in an ``align*``, ``eqnarray`` or ``IEEEeqnarray`` environment.
Parameters
==========
lhs : Expr
Left-hand side of equation
rhs : Expr
Right-hand side of equation
terms_per_line : integer, optional
Number of terms per line to print. Default is 1.
environment : "string", optional
Which LaTeX wnvironment to use for the output. Options are "align*"
(default), "eqnarray", and "IEEEeqnarray".
use_dots : boolean, optional
If ``True``, ``\\dots`` is added to the end of each line. Default is ``False``.
Examples
========
>>> from sympy import multiline_latex, symbols, sin, cos, exp, log, I
>>> x, y, alpha = symbols('x y alpha')
>>> expr = sin(alpha*y) + exp(I*alpha) - cos(log(y))
>>> print(multiline_latex(x, expr))
\begin{align*}
x = & e^{i \alpha} \\
& + \sin{\left(\alpha y \right)} \\
& - \cos{\left(\log{\left(y \right)} \right)}
\end{align*}
Using at most two terms per line:
>>> print(multiline_latex(x, expr, 2))
\begin{align*}
x = & e^{i \alpha} + \sin{\left(\alpha y \right)} \\
& - \cos{\left(\log{\left(y \right)} \right)}
\end{align*}
Using ``eqnarray`` and dots:
>>> print(multiline_latex(x, expr, terms_per_line=2, environment="eqnarray", use_dots=True))
\begin{eqnarray}
x & = & e^{i \alpha} + \sin{\left(\alpha y \right)} \dots\nonumber\\
& & - \cos{\left(\log{\left(y \right)} \right)}
\end{eqnarray}
Using ``IEEEeqnarray``:
>>> print(multiline_latex(x, expr, environment="IEEEeqnarray"))
\begin{IEEEeqnarray}{rCl}
x & = & e^{i \alpha} \nonumber\\
& & + \sin{\left(\alpha y \right)} \nonumber\\
& & - \cos{\left(\log{\left(y \right)} \right)}
\end{IEEEeqnarray}
Notes
=====
All optional parameters from ``latex`` can also be used.
"""
# Based on code from https://github.com/sympy/sympy/issues/3001
l = LatexPrinter(**settings)
if environment == "eqnarray":
result = r'\begin{eqnarray}' + '\n'
first_term = '& = &'
nonumber = r'\nonumber'
end_term = '\n\\end{eqnarray}'
doubleet = True
elif environment == "IEEEeqnarray":
result = r'\begin{IEEEeqnarray}{rCl}' + '\n'
first_term = '& = &'
nonumber = r'\nonumber'
end_term = '\n\\end{IEEEeqnarray}'
doubleet = True
elif environment == "align*":
result = r'\begin{align*}' + '\n'
first_term = '= &'
nonumber = ''
end_term = '\n\\end{align*}'
doubleet = False
else:
raise ValueError("Unknown environment: {}".format(environment))
dots = ''
if use_dots:
dots=r'\dots'
terms = rhs.as_ordered_terms()
n_terms = len(terms)
term_count = 1
for i in range(n_terms):
term = terms[i]
term_start = ''
term_end = ''
sign = '+'
if term_count > terms_per_line:
if doubleet:
term_start = '& & '
else:
term_start = '& '
term_count = 1
if term_count == terms_per_line:
# End of line
if i < n_terms-1:
# There are terms remaining
term_end = dots + nonumber + r'\\' + '\n'
else:
term_end = ''
if term.as_ordered_factors()[0] == -1:
term = -1*term
sign = r'-'
if i == 0: # beginning
if sign == '+':
sign = ''
result += r'{:s} {:s}{:s} {:s} {:s}'.format(l.doprint(lhs),
first_term, sign, l.doprint(term), term_end)
else:
result += r'{:s}{:s} {:s} {:s}'.format(term_start, sign,
l.doprint(term), term_end)
term_count += 1
result += end_term
return result
|
df7dc631949c3e5e26f0162c725466a247bed5782e305a87755f9568ae46dc2f | """Printing subsystem driver
SymPy's printing system works the following way: Any expression can be
passed to a designated Printer who then is responsible to return an
adequate representation of that expression.
**The basic concept is the following:**
1. Let the object print itself if it knows how.
2. Take the best fitting method defined in the printer.
3. As fall-back use the emptyPrinter method for the printer.
Which Method is Responsible for Printing?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The whole printing process is started by calling ``.doprint(expr)`` on the printer
which you want to use. This method looks for an appropriate method which can
print the given expression in the given style that the printer defines.
While looking for the method, it follows these steps:
1. **Let the object print itself if it knows how.**
The printer looks for a specific method in every object. The name of that method
depends on the specific printer and is defined under ``Printer.printmethod``.
For example, StrPrinter calls ``_sympystr`` and LatexPrinter calls ``_latex``.
Look at the documentation of the printer that you want to use.
The name of the method is specified there.
This was the original way of doing printing in sympy. Every class had
its own latex, mathml, str and repr methods, but it turned out that it
is hard to produce a high quality printer, if all the methods are spread
out that far. Therefore all printing code was combined into the different
printers, which works great for built-in SymPy objects, but not that
good for user defined classes where it is inconvenient to patch the
printers.
2. **Take the best fitting method defined in the printer.**
The printer loops through expr classes (class + its bases), and tries
to dispatch the work to ``_print_<EXPR_CLASS>``
e.g., suppose we have the following class hierarchy::
Basic
|
Atom
|
Number
|
Rational
then, for ``expr=Rational(...)``, the Printer will try
to call printer methods in the order as shown in the figure below::
p._print(expr)
|
|-- p._print_Rational(expr)
|
|-- p._print_Number(expr)
|
|-- p._print_Atom(expr)
|
`-- p._print_Basic(expr)
if ``._print_Rational`` method exists in the printer, then it is called,
and the result is returned back. Otherwise, the printer tries to call
``._print_Number`` and so on.
3. **As a fall-back use the emptyPrinter method for the printer.**
As fall-back ``self.emptyPrinter`` will be called with the expression. If
not defined in the Printer subclass this will be the same as ``str(expr)``.
.. _printer_example:
Example of Custom Printer
^^^^^^^^^^^^^^^^^^^^^^^^^
In the example below, we have a printer which prints the derivative of a function
in a shorter form.
.. code-block:: python
from sympy.core.symbol import Symbol
from sympy.printing.latex import LatexPrinter, print_latex
from sympy.core.function import UndefinedFunction, Function
class MyLatexPrinter(LatexPrinter):
\"\"\"Print derivative of a function of symbols in a shorter form.
\"\"\"
def _print_Derivative(self, expr):
function, *vars = expr.args
if not isinstance(type(function), UndefinedFunction) or \\
not all(isinstance(i, Symbol) for i in vars):
return super()._print_Derivative(expr)
# If you want the printer to work correctly for nested
# expressions then use self._print() instead of str() or latex().
# See the example of nested modulo below in the custom printing
# method section.
return "{}_{{{}}}".format(
self._print(Symbol(function.func.__name__)),
''.join(self._print(i) for i in vars))
def print_my_latex(expr):
\"\"\" Most of the printers define their own wrappers for print().
These wrappers usually take printer settings. Our printer does not have
any settings.
\"\"\"
print(MyLatexPrinter().doprint(expr))
y = Symbol("y")
x = Symbol("x")
f = Function("f")
expr = f(x, y).diff(x, y)
# Print the expression using the normal latex printer and our custom
# printer.
print_latex(expr)
print_my_latex(expr)
The output of the code above is::
\\frac{\\partial^{2}}{\\partial x\\partial y} f{\\left(x,y \\right)}
f_{xy}
.. _printer_method_example:
Example of Custom Printing Method
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
In the example below, the latex printing of the modulo operator is modified.
This is done by overriding the method ``_latex`` of ``Mod``.
>>> from sympy import Symbol, Mod, Integer, print_latex
>>> # Always use printer._print()
>>> class ModOp(Mod):
... def _latex(self, printer):
... a, b = [printer._print(i) for i in self.args]
... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
Comparing the output of our custom operator to the builtin one:
>>> x = Symbol('x')
>>> m = Symbol('m')
>>> print_latex(Mod(x, m))
x \\bmod m
>>> print_latex(ModOp(x, m))
\\operatorname{Mod}{\\left(x, m\\right)}
Common mistakes
~~~~~~~~~~~~~~~
It's important to always use ``self._print(obj)`` to print subcomponents of
an expression when customizing a printer. Mistakes include:
1. Using ``self.doprint(obj)`` instead:
>>> # This example does not work properly, as only the outermost call may use
>>> # doprint.
>>> class ModOpModeWrong(Mod):
... def _latex(self, printer):
... a, b = [printer.doprint(i) for i in self.args]
... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
This fails when the `mode` argument is passed to the printer:
>>> print_latex(ModOp(x, m), mode='inline') # ok
$\\operatorname{Mod}{\\left(x, m\\right)}$
>>> print_latex(ModOpModeWrong(x, m), mode='inline') # bad
$\\operatorname{Mod}{\\left($x$, $m$\\right)}$
2. Using ``str(obj)`` instead:
>>> class ModOpNestedWrong(Mod):
... def _latex(self, printer):
... a, b = [str(i) for i in self.args]
... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
This fails on nested objects:
>>> # Nested modulo.
>>> print_latex(ModOp(ModOp(x, m), Integer(7))) # ok
\\operatorname{Mod}{\\left(\\operatorname{Mod}{\\left(x, m\\right)}, 7\\right)}
>>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7))) # bad
\\operatorname{Mod}{\\left(ModOpNestedWrong(x, m), 7\\right)}
3. Using ``LatexPrinter()._print(obj)`` instead.
>>> from sympy.printing.latex import LatexPrinter
>>> class ModOpSettingsWrong(Mod):
... def _latex(self, printer):
... a, b = [LatexPrinter()._print(i) for i in self.args]
... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
This causes all the settings to be discarded in the subobjects. As an
example, the ``full_prec`` setting which shows floats to full precision is
ignored:
>>> from sympy import Float
>>> print_latex(ModOp(Float(1) * x, m), full_prec=True) # ok
\\operatorname{Mod}{\\left(1.00000000000000 x, m\\right)}
>>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True) # bad
\\operatorname{Mod}{\\left(1.0 x, m\\right)}
"""
import sys
from typing import Any, Dict as tDict, Type
import inspect
from contextlib import contextmanager
from functools import cmp_to_key, update_wrapper
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.core import BasicMeta
from sympy.core.function import AppliedUndef, UndefinedFunction, Function
@contextmanager
def printer_context(printer, **kwargs):
original = printer._context.copy()
try:
printer._context.update(kwargs)
yield
finally:
printer._context = original
class Printer:
""" Generic printer
Its job is to provide infrastructure for implementing new printers easily.
If you want to define your custom Printer or your custom printing method
for your custom class then see the example above: printer_example_ .
"""
_global_settings = {} # type: tDict[str, Any]
_default_settings = {} # type: tDict[str, Any]
printmethod = None # type: str
@classmethod
def _get_initial_settings(cls):
settings = cls._default_settings.copy()
for key, val in cls._global_settings.items():
if key in cls._default_settings:
settings[key] = val
return settings
def __init__(self, settings=None):
self._str = str
self._settings = self._get_initial_settings()
self._context = dict() # mutable during printing
if settings is not None:
self._settings.update(settings)
if len(self._settings) > len(self._default_settings):
for key in self._settings:
if key not in self._default_settings:
raise TypeError("Unknown setting '%s'." % key)
# _print_level is the number of times self._print() was recursively
# called. See StrPrinter._print_Float() for an example of usage
self._print_level = 0
@classmethod
def set_global_settings(cls, **settings):
"""Set system-wide printing settings. """
for key, val in settings.items():
if val is not None:
cls._global_settings[key] = val
@property
def order(self):
if 'order' in self._settings:
return self._settings['order']
else:
raise AttributeError("No order defined.")
def doprint(self, expr):
"""Returns printer's representation for expr (as a string)"""
return self._str(self._print(expr))
def _print(self, expr, **kwargs):
"""Internal dispatcher
Tries the following concepts to print an expression:
1. Let the object print itself if it knows how.
2. Take the best fitting method defined in the printer.
3. As fall-back use the emptyPrinter method for the printer.
"""
self._print_level += 1
try:
# If the printer defines a name for a printing method
# (Printer.printmethod) and the object knows for itself how it
# should be printed, use that method.
if (self.printmethod and hasattr(expr, self.printmethod)
and not isinstance(expr, BasicMeta)):
return getattr(expr, self.printmethod)(self, **kwargs)
# See if the class of expr is known, or if one of its super
# classes is known, and use that print function
# Exception: ignore the subclasses of Undefined, so that, e.g.,
# Function('gamma') does not get dispatched to _print_gamma
classes = type(expr).__mro__
if AppliedUndef in classes:
classes = classes[classes.index(AppliedUndef):]
if UndefinedFunction in classes:
classes = classes[classes.index(UndefinedFunction):]
# Another exception: if someone subclasses a known function, e.g.,
# gamma, and changes the name, then ignore _print_gamma
if Function in classes:
i = classes.index(Function)
classes = tuple(c for c in classes[:i] if \
c.__name__ == classes[0].__name__ or \
c.__name__.endswith("Base")) + classes[i:]
for cls in classes:
printmethodname = '_print_' + cls.__name__
printmethod = getattr(self, printmethodname, None)
if printmethod is not None:
return printmethod(expr, **kwargs)
# Unknown object, fall back to the emptyPrinter.
return self.emptyPrinter(expr)
finally:
self._print_level -= 1
def emptyPrinter(self, expr):
return str(expr)
def _as_ordered_terms(self, expr, order=None):
"""A compatibility function for ordering terms in Add. """
order = order or self.order
if order == 'old':
return sorted(Add.make_args(expr), key=cmp_to_key(Basic._compare_pretty))
elif order == 'none':
return list(expr.args)
else:
return expr.as_ordered_terms(order=order)
class _PrintFunction:
"""
Function wrapper to replace ``**settings`` in the signature with printer defaults
"""
def __init__(self, f, print_cls: Type[Printer]):
# find all the non-setting arguments
params = list(inspect.signature(f).parameters.values())
assert params.pop(-1).kind == inspect.Parameter.VAR_KEYWORD
self.__other_params = params
self.__print_cls = print_cls
update_wrapper(self, f)
def __reduce__(self):
# Since this is used as a decorator, it replaces the original function.
# The default pickling will try to pickle self.__wrapped__ and fail
# because the wrapped function can't be retrieved by name.
return self.__wrapped__.__qualname__
def __call__(self, *args, **kwargs):
return self.__wrapped__(*args, **kwargs)
@property
def __signature__(self) -> inspect.Signature:
settings = self.__print_cls._get_initial_settings()
return inspect.Signature(
parameters=self.__other_params + [
inspect.Parameter(k, inspect.Parameter.KEYWORD_ONLY, default=v)
for k, v in settings.items()
],
return_annotation=self.__wrapped__.__annotations__.get('return', inspect.Signature.empty) # type:ignore
)
def print_function(print_cls):
""" A decorator to replace kwargs with the printer settings in __signature__ """
def decorator(f):
if sys.version_info < (3, 9):
# We have to create a subclass so that `help` actually shows the docstring in older Python versions.
# IPython and Sphinx do not need this, only a raw Python console.
cls = type(f'{f.__qualname__}_PrintFunction', (_PrintFunction,), dict(__doc__=f.__doc__))
else:
cls = _PrintFunction
return cls(f, print_cls)
return decorator
|
fb57757309a7a6b24a3d7a558936d0c69c32df04fb2bc2a33c3e470b28db0c69 | from sympy.core.containers import Tuple
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.core.sympify import SympifyError
from types import FunctionType
class TableForm:
r"""
Create a nice table representation of data.
Examples
========
>>> from sympy import TableForm
>>> t = TableForm([[5, 7], [4, 2], [10, 3]])
>>> print(t)
5 7
4 2
10 3
You can use the SymPy's printing system to produce tables in any
format (ascii, latex, html, ...).
>>> print(t.as_latex())
\begin{tabular}{l l}
$5$ & $7$ \\
$4$ & $2$ \\
$10$ & $3$ \\
\end{tabular}
"""
def __init__(self, data, **kwarg):
"""
Creates a TableForm.
Parameters:
data ...
2D data to be put into the table; data can be
given as a Matrix
headings ...
gives the labels for rows and columns:
Can be a single argument that applies to both
dimensions:
- None ... no labels
- "automatic" ... labels are 1, 2, 3, ...
Can be a list of labels for rows and columns:
The labels for each dimension can be given
as None, "automatic", or [l1, l2, ...] e.g.
["automatic", None] will number the rows
[default: None]
alignments ...
alignment of the columns with:
- "left" or "<"
- "center" or "^"
- "right" or ">"
When given as a single value, the value is used for
all columns. The row headings (if given) will be
right justified unless an explicit alignment is
given for it and all other columns.
[default: "left"]
formats ...
a list of format strings or functions that accept
3 arguments (entry, row number, col number) and
return a string for the table entry. (If a function
returns None then the _print method will be used.)
wipe_zeros ...
Do not show zeros in the table.
[default: True]
pad ...
the string to use to indicate a missing value (e.g.
elements that are None or those that are missing
from the end of a row (i.e. any row that is shorter
than the rest is assumed to have missing values).
When None, nothing will be shown for values that
are missing from the end of a row; values that are
None, however, will be shown.
[default: None]
Examples
========
>>> from sympy import TableForm, Symbol
>>> TableForm([[5, 7], [4, 2], [10, 3]])
5 7
4 2
10 3
>>> TableForm([list('.'*i) for i in range(1, 4)], headings='automatic')
| 1 2 3
---------
1 | .
2 | . .
3 | . . .
>>> TableForm([[Symbol('.'*(j if not i%2 else 1)) for i in range(3)]
... for j in range(4)], alignments='rcl')
.
. . .
.. . ..
... . ...
"""
from sympy.matrices.dense import Matrix
# We only support 2D data. Check the consistency:
if isinstance(data, Matrix):
data = data.tolist()
_h = len(data)
# fill out any short lines
pad = kwarg.get('pad', None)
ok_None = False
if pad is None:
pad = " "
ok_None = True
pad = Symbol(pad)
_w = max(len(line) for line in data)
for i, line in enumerate(data):
if len(line) != _w:
line.extend([pad]*(_w - len(line)))
for j, lj in enumerate(line):
if lj is None:
if not ok_None:
lj = pad
else:
try:
lj = S(lj)
except SympifyError:
lj = Symbol(str(lj))
line[j] = lj
data[i] = line
_lines = Tuple(*[Tuple(*d) for d in data])
headings = kwarg.get("headings", [None, None])
if headings == "automatic":
_headings = [range(1, _h + 1), range(1, _w + 1)]
else:
h1, h2 = headings
if h1 == "automatic":
h1 = range(1, _h + 1)
if h2 == "automatic":
h2 = range(1, _w + 1)
_headings = [h1, h2]
allow = ('l', 'r', 'c')
alignments = kwarg.get("alignments", "l")
def _std_align(a):
a = a.strip().lower()
if len(a) > 1:
return {'left': 'l', 'right': 'r', 'center': 'c'}.get(a, a)
else:
return {'<': 'l', '>': 'r', '^': 'c'}.get(a, a)
std_align = _std_align(alignments)
if std_align in allow:
_alignments = [std_align]*_w
else:
_alignments = []
for a in alignments:
std_align = _std_align(a)
_alignments.append(std_align)
if std_align not in ('l', 'r', 'c'):
raise ValueError('alignment "%s" unrecognized' %
alignments)
if _headings[0] and len(_alignments) == _w + 1:
_head_align = _alignments[0]
_alignments = _alignments[1:]
else:
_head_align = 'r'
if len(_alignments) != _w:
raise ValueError(
'wrong number of alignments: expected %s but got %s' %
(_w, len(_alignments)))
_column_formats = kwarg.get("formats", [None]*_w)
_wipe_zeros = kwarg.get("wipe_zeros", True)
self._w = _w
self._h = _h
self._lines = _lines
self._headings = _headings
self._head_align = _head_align
self._alignments = _alignments
self._column_formats = _column_formats
self._wipe_zeros = _wipe_zeros
def __repr__(self):
from .str import sstr
return sstr(self, order=None)
def __str__(self):
from .str import sstr
return sstr(self, order=None)
def as_matrix(self):
"""Returns the data of the table in Matrix form.
Examples
========
>>> from sympy import TableForm
>>> t = TableForm([[5, 7], [4, 2], [10, 3]], headings='automatic')
>>> t
| 1 2
--------
1 | 5 7
2 | 4 2
3 | 10 3
>>> t.as_matrix()
Matrix([
[ 5, 7],
[ 4, 2],
[10, 3]])
"""
from sympy.matrices.dense import Matrix
return Matrix(self._lines)
def as_str(self):
# XXX obsolete ?
return str(self)
def as_latex(self):
from .latex import latex
return latex(self)
def _sympystr(self, p):
"""
Returns the string representation of 'self'.
Examples
========
>>> from sympy import TableForm
>>> t = TableForm([[5, 7], [4, 2], [10, 3]])
>>> s = t.as_str()
"""
column_widths = [0] * self._w
lines = []
for line in self._lines:
new_line = []
for i in range(self._w):
# Format the item somehow if needed:
s = str(line[i])
if self._wipe_zeros and (s == "0"):
s = " "
w = len(s)
if w > column_widths[i]:
column_widths[i] = w
new_line.append(s)
lines.append(new_line)
# Check heading:
if self._headings[0]:
self._headings[0] = [str(x) for x in self._headings[0]]
_head_width = max([len(x) for x in self._headings[0]])
if self._headings[1]:
new_line = []
for i in range(self._w):
# Format the item somehow if needed:
s = str(self._headings[1][i])
w = len(s)
if w > column_widths[i]:
column_widths[i] = w
new_line.append(s)
self._headings[1] = new_line
format_str = []
def _align(align, w):
return '%%%s%ss' % (
("-" if align == "l" else ""),
str(w))
format_str = [_align(align, w) for align, w in
zip(self._alignments, column_widths)]
if self._headings[0]:
format_str.insert(0, _align(self._head_align, _head_width))
format_str.insert(1, '|')
format_str = ' '.join(format_str) + '\n'
s = []
if self._headings[1]:
d = self._headings[1]
if self._headings[0]:
d = [""] + d
first_line = format_str % tuple(d)
s.append(first_line)
s.append("-" * (len(first_line) - 1) + "\n")
for i, line in enumerate(lines):
d = [l if self._alignments[j] != 'c' else
l.center(column_widths[j]) for j, l in enumerate(line)]
if self._headings[0]:
l = self._headings[0][i]
l = (l if self._head_align != 'c' else
l.center(_head_width))
d = [l] + d
s.append(format_str % tuple(d))
return ''.join(s)[:-1] # don't include trailing newline
def _latex(self, printer):
"""
Returns the string representation of 'self'.
"""
# Check heading:
if self._headings[1]:
new_line = []
for i in range(self._w):
# Format the item somehow if needed:
new_line.append(str(self._headings[1][i]))
self._headings[1] = new_line
alignments = []
if self._headings[0]:
self._headings[0] = [str(x) for x in self._headings[0]]
alignments = [self._head_align]
alignments.extend(self._alignments)
s = r"\begin{tabular}{" + " ".join(alignments) + "}\n"
if self._headings[1]:
d = self._headings[1]
if self._headings[0]:
d = [""] + d
first_line = " & ".join(d) + r" \\" + "\n"
s += first_line
s += r"\hline" + "\n"
for i, line in enumerate(self._lines):
d = []
for j, x in enumerate(line):
if self._wipe_zeros and (x in (0, "0")):
d.append(" ")
continue
f = self._column_formats[j]
if f:
if isinstance(f, FunctionType):
v = f(x, i, j)
if v is None:
v = printer._print(x)
else:
v = f % x
d.append(v)
else:
v = printer._print(x)
d.append("$%s$" % v)
if self._headings[0]:
d = [self._headings[0][i]] + d
s += " & ".join(d) + r" \\" + "\n"
s += r"\end{tabular}"
return s
|
d6375f9ffc2c3aebd96921a7b63c8439a24d3447463e85ecf18768dc27adb065 | from .pycode import (
PythonCodePrinter,
MpmathPrinter,
)
from .numpy import NumPyPrinter # NumPyPrinter is imported for backward compatibility
from sympy.core.sorting import default_sort_key
__all__ = [
'PythonCodePrinter',
'MpmathPrinter', # MpmathPrinter is published for backward compatibility
'NumPyPrinter',
'LambdaPrinter',
'NumPyPrinter',
'IntervalPrinter',
'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',
}
module = 'numexpr'
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_SparseRepMatrix = \
_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 _print_NumExprEvaluate(self, expr):
evaluate = self._module_format(self.module +".evaluate")
return "%s('%s', truediv=True)" % (evaluate, self._print(expr.expr))
def doprint(self, expr):
from sympy.codegen.ast import CodegenAST
from sympy.codegen.pynodes import NumExprEvaluate
if not isinstance(expr, CodegenAST):
expr = NumExprEvaluate(expr)
return super().doprint(expr)
def _print_Return(self, expr):
from sympy.codegen.pynodes import NumExprEvaluate
r, = expr.args
if not isinstance(r, NumExprEvaluate):
expr = expr.func(NumExprEvaluate(r))
return super()._print_Return(expr)
def _print_Assignment(self, expr):
from sympy.codegen.pynodes import NumExprEvaluate
lhs, rhs, *args = expr.args
if not isinstance(rhs, NumExprEvaluate):
expr = expr.func(lhs, NumExprEvaluate(rhs), *args)
return super()._print_Assignment(expr)
def _print_CodeBlock(self, expr):
from sympy.codegen.ast import CodegenAST
from sympy.codegen.pynodes import NumExprEvaluate
args = [ arg if isinstance(arg, CodegenAST) else NumExprEvaluate(arg) for arg in expr.args ]
return super()._print_CodeBlock(self, expr.func(*args))
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)
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)
|
712363adb25d7db7027832df24ea6cf60a3419bd6a63c0f709bd7606f01fae61 | """
.. deprecated:: 1.7
ccode.py was deprecated and renamed to c.py. This is a shim file to provide
backwards compatibility.
"""
from sympy.utilities.exceptions import sympy_deprecation_warning
sympy_deprecation_warning(
"""
The sympy.printing.ccode submodule is deprecated. It has been renamed to
sympy.printing.c.
""",
deprecated_since_version="1.7",
active_deprecations_target="deprecated-printing-code-submodules",
)
from .c import (ccode, print_ccode, known_functions_C89, known_functions_C99, # noqa:F401
reserved_words, reserved_words_c99, get_math_macros,
C89CodePrinter, C99CodePrinter, C11CodePrinter,
c_code_printers)
|
72952883a7ad43f083d56c81e0f8c5db090fb8300ec752f412fa905fafe91d09 | """
A MathML printer.
"""
from typing import Any, Dict as tDict
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.core.sympify import sympify
from sympy.printing.conventions import split_super_sub, requires_partial
from sympy.printing.precedence import \
precedence_traditional, PRECEDENCE, PRECEDENCE_TRADITIONAL
from sympy.printing.pretty.pretty_symbology import greek_unicode
from sympy.printing.printer import Printer, print_function
from mpmath.libmp import prec_to_dps, repr_dps, to_str as mlib_to_str
class MathMLPrinterBase(Printer):
"""Contains common code required for MathMLContentPrinter and
MathMLPresentationPrinter.
"""
_default_settings = {
"order": None,
"encoding": "utf-8",
"fold_frac_powers": False,
"fold_func_brackets": False,
"fold_short_frac": None,
"inv_trig_style": "abbreviated",
"ln_notation": False,
"long_frac_ratio": None,
"mat_delim": "[",
"mat_symbol_style": "plain",
"mul_symbol": None,
"root_notation": True,
"symbol_names": {},
"mul_symbol_mathml_numbers": '·',
} # type: tDict[str, Any]
def __init__(self, settings=None):
Printer.__init__(self, settings)
from xml.dom.minidom import Document, Text
self.dom = Document()
# Workaround to allow strings to remain unescaped
# Based on
# https://stackoverflow.com/questions/38015864/python-xml-dom-minidom-\
# please-dont-escape-my-strings/38041194
class RawText(Text):
def writexml(self, writer, indent='', addindent='', newl=''):
if self.data:
writer.write('{}{}{}'.format(indent, self.data, newl))
def createRawTextNode(data):
r = RawText()
r.data = data
r.ownerDocument = self.dom
return r
self.dom.createTextNode = createRawTextNode
def doprint(self, expr):
"""
Prints the expression as MathML.
"""
mathML = Printer._print(self, expr)
unistr = mathML.toxml()
xmlbstr = unistr.encode('ascii', 'xmlcharrefreplace')
res = xmlbstr.decode()
return res
def apply_patch(self):
# Applying the patch of xml.dom.minidom bug
# Date: 2011-11-18
# Description: http://ronrothman.com/public/leftbraned/xml-dom-minidom\
# -toprettyxml-and-silly-whitespace/#best-solution
# Issue: http://bugs.python.org/issue4147
# Patch: http://hg.python.org/cpython/rev/7262f8f276ff/
from xml.dom.minidom import Element, Text, Node, _write_data
def writexml(self, writer, indent="", addindent="", newl=""):
# indent = current indentation
# addindent = indentation to add to higher levels
# newl = newline string
writer.write(indent + "<" + self.tagName)
attrs = self._get_attributes()
a_names = list(attrs.keys())
a_names.sort()
for a_name in a_names:
writer.write(" %s=\"" % a_name)
_write_data(writer, attrs[a_name].value)
writer.write("\"")
if self.childNodes:
writer.write(">")
if (len(self.childNodes) == 1 and
self.childNodes[0].nodeType == Node.TEXT_NODE):
self.childNodes[0].writexml(writer, '', '', '')
else:
writer.write(newl)
for node in self.childNodes:
node.writexml(
writer, indent + addindent, addindent, newl)
writer.write(indent)
writer.write("</%s>%s" % (self.tagName, newl))
else:
writer.write("/>%s" % (newl))
self._Element_writexml_old = Element.writexml
Element.writexml = writexml
def writexml(self, writer, indent="", addindent="", newl=""):
_write_data(writer, "%s%s%s" % (indent, self.data, newl))
self._Text_writexml_old = Text.writexml
Text.writexml = writexml
def restore_patch(self):
from xml.dom.minidom import Element, Text
Element.writexml = self._Element_writexml_old
Text.writexml = self._Text_writexml_old
class MathMLContentPrinter(MathMLPrinterBase):
"""Prints an expression to the Content MathML markup language.
References: https://www.w3.org/TR/MathML2/chapter4.html
"""
printmethod = "_mathml_content"
def mathml_tag(self, e):
"""Returns the MathML tag for an expression."""
translate = {
'Add': 'plus',
'Mul': 'times',
'Derivative': 'diff',
'Number': 'cn',
'int': 'cn',
'Pow': 'power',
'Max': 'max',
'Min': 'min',
'Abs': 'abs',
'And': 'and',
'Or': 'or',
'Xor': 'xor',
'Not': 'not',
'Implies': 'implies',
'Symbol': 'ci',
'MatrixSymbol': 'ci',
'RandomSymbol': 'ci',
'Integral': 'int',
'Sum': 'sum',
'sin': 'sin',
'cos': 'cos',
'tan': 'tan',
'cot': 'cot',
'csc': 'csc',
'sec': 'sec',
'sinh': 'sinh',
'cosh': 'cosh',
'tanh': 'tanh',
'coth': 'coth',
'csch': 'csch',
'sech': 'sech',
'asin': 'arcsin',
'asinh': 'arcsinh',
'acos': 'arccos',
'acosh': 'arccosh',
'atan': 'arctan',
'atanh': 'arctanh',
'atan2': 'arctan',
'acot': 'arccot',
'acoth': 'arccoth',
'asec': 'arcsec',
'asech': 'arcsech',
'acsc': 'arccsc',
'acsch': 'arccsch',
'log': 'ln',
'Equality': 'eq',
'Unequality': 'neq',
'GreaterThan': 'geq',
'LessThan': 'leq',
'StrictGreaterThan': 'gt',
'StrictLessThan': 'lt',
'Union': 'union',
'Intersection': 'intersect',
}
for cls in e.__class__.__mro__:
n = cls.__name__
if n in translate:
return translate[n]
# Not found in the MRO set
n = e.__class__.__name__
return n.lower()
def _print_Mul(self, expr):
if expr.could_extract_minus_sign():
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement('minus'))
x.appendChild(self._print_Mul(-expr))
return x
from sympy.simplify import fraction
numer, denom = fraction(expr)
if denom is not S.One:
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement('divide'))
x.appendChild(self._print(numer))
x.appendChild(self._print(denom))
return x
coeff, terms = expr.as_coeff_mul()
if coeff is S.One and len(terms) == 1:
# XXX since the negative coefficient has been handled, I don't
# think a coeff of 1 can remain
return self._print(terms[0])
if self.order != 'old':
terms = Mul._from_args(terms).as_ordered_factors()
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement('times'))
if coeff != 1:
x.appendChild(self._print(coeff))
for term in terms:
x.appendChild(self._print(term))
return x
def _print_Add(self, expr, order=None):
args = self._as_ordered_terms(expr, order=order)
lastProcessed = self._print(args[0])
plusNodes = []
for arg in args[1:]:
if arg.could_extract_minus_sign():
# use minus
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement('minus'))
x.appendChild(lastProcessed)
x.appendChild(self._print(-arg))
# invert expression since this is now minused
lastProcessed = x
if arg == args[-1]:
plusNodes.append(lastProcessed)
else:
plusNodes.append(lastProcessed)
lastProcessed = self._print(arg)
if arg == args[-1]:
plusNodes.append(self._print(arg))
if len(plusNodes) == 1:
return lastProcessed
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement('plus'))
while plusNodes:
x.appendChild(plusNodes.pop(0))
return x
def _print_Piecewise(self, expr):
if expr.args[-1].cond != True:
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
root = self.dom.createElement('piecewise')
for i, (e, c) in enumerate(expr.args):
if i == len(expr.args) - 1 and c == True:
piece = self.dom.createElement('otherwise')
piece.appendChild(self._print(e))
else:
piece = self.dom.createElement('piece')
piece.appendChild(self._print(e))
piece.appendChild(self._print(c))
root.appendChild(piece)
return root
def _print_MatrixBase(self, m):
x = self.dom.createElement('matrix')
for i in range(m.rows):
x_r = self.dom.createElement('matrixrow')
for j in range(m.cols):
x_r.appendChild(self._print(m[i, j]))
x.appendChild(x_r)
return x
def _print_Rational(self, e):
if e.q == 1:
# don't divide
x = self.dom.createElement('cn')
x.appendChild(self.dom.createTextNode(str(e.p)))
return x
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement('divide'))
# numerator
xnum = self.dom.createElement('cn')
xnum.appendChild(self.dom.createTextNode(str(e.p)))
# denominator
xdenom = self.dom.createElement('cn')
xdenom.appendChild(self.dom.createTextNode(str(e.q)))
x.appendChild(xnum)
x.appendChild(xdenom)
return x
def _print_Limit(self, e):
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement(self.mathml_tag(e)))
x_1 = self.dom.createElement('bvar')
x_2 = self.dom.createElement('lowlimit')
x_1.appendChild(self._print(e.args[1]))
x_2.appendChild(self._print(e.args[2]))
x.appendChild(x_1)
x.appendChild(x_2)
x.appendChild(self._print(e.args[0]))
return x
def _print_ImaginaryUnit(self, e):
return self.dom.createElement('imaginaryi')
def _print_EulerGamma(self, e):
return self.dom.createElement('eulergamma')
def _print_GoldenRatio(self, e):
"""We use unicode #x3c6 for Greek letter phi as defined here
http://www.w3.org/2003/entities/2007doc/isogrk1.html"""
x = self.dom.createElement('cn')
x.appendChild(self.dom.createTextNode("\N{GREEK SMALL LETTER PHI}"))
return x
def _print_Exp1(self, e):
return self.dom.createElement('exponentiale')
def _print_Pi(self, e):
return self.dom.createElement('pi')
def _print_Infinity(self, e):
return self.dom.createElement('infinity')
def _print_NaN(self, e):
return self.dom.createElement('notanumber')
def _print_EmptySet(self, e):
return self.dom.createElement('emptyset')
def _print_BooleanTrue(self, e):
return self.dom.createElement('true')
def _print_BooleanFalse(self, e):
return self.dom.createElement('false')
def _print_NegativeInfinity(self, e):
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement('minus'))
x.appendChild(self.dom.createElement('infinity'))
return x
def _print_Integral(self, e):
def lime_recur(limits):
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement(self.mathml_tag(e)))
bvar_elem = self.dom.createElement('bvar')
bvar_elem.appendChild(self._print(limits[0][0]))
x.appendChild(bvar_elem)
if len(limits[0]) == 3:
low_elem = self.dom.createElement('lowlimit')
low_elem.appendChild(self._print(limits[0][1]))
x.appendChild(low_elem)
up_elem = self.dom.createElement('uplimit')
up_elem.appendChild(self._print(limits[0][2]))
x.appendChild(up_elem)
if len(limits[0]) == 2:
up_elem = self.dom.createElement('uplimit')
up_elem.appendChild(self._print(limits[0][1]))
x.appendChild(up_elem)
if len(limits) == 1:
x.appendChild(self._print(e.function))
else:
x.appendChild(lime_recur(limits[1:]))
return x
limits = list(e.limits)
limits.reverse()
return lime_recur(limits)
def _print_Sum(self, e):
# Printer can be shared because Sum and Integral have the
# same internal representation.
return self._print_Integral(e)
def _print_Symbol(self, sym):
ci = self.dom.createElement(self.mathml_tag(sym))
def join(items):
if len(items) > 1:
mrow = self.dom.createElement('mml:mrow')
for i, item in enumerate(items):
if i > 0:
mo = self.dom.createElement('mml:mo')
mo.appendChild(self.dom.createTextNode(" "))
mrow.appendChild(mo)
mi = self.dom.createElement('mml:mi')
mi.appendChild(self.dom.createTextNode(item))
mrow.appendChild(mi)
return mrow
else:
mi = self.dom.createElement('mml:mi')
mi.appendChild(self.dom.createTextNode(items[0]))
return mi
# translate name, supers and subs to unicode characters
def translate(s):
if s in greek_unicode:
return greek_unicode.get(s)
else:
return s
name, supers, subs = split_super_sub(sym.name)
name = translate(name)
supers = [translate(sup) for sup in supers]
subs = [translate(sub) for sub in subs]
mname = self.dom.createElement('mml:mi')
mname.appendChild(self.dom.createTextNode(name))
if not supers:
if not subs:
ci.appendChild(self.dom.createTextNode(name))
else:
msub = self.dom.createElement('mml:msub')
msub.appendChild(mname)
msub.appendChild(join(subs))
ci.appendChild(msub)
else:
if not subs:
msup = self.dom.createElement('mml:msup')
msup.appendChild(mname)
msup.appendChild(join(supers))
ci.appendChild(msup)
else:
msubsup = self.dom.createElement('mml:msubsup')
msubsup.appendChild(mname)
msubsup.appendChild(join(subs))
msubsup.appendChild(join(supers))
ci.appendChild(msubsup)
return ci
_print_MatrixSymbol = _print_Symbol
_print_RandomSymbol = _print_Symbol
def _print_Pow(self, e):
# Here we use root instead of power if the exponent is the reciprocal
# of an integer
if (self._settings['root_notation'] and e.exp.is_Rational
and e.exp.p == 1):
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement('root'))
if e.exp.q != 2:
xmldeg = self.dom.createElement('degree')
xmlcn = self.dom.createElement('cn')
xmlcn.appendChild(self.dom.createTextNode(str(e.exp.q)))
xmldeg.appendChild(xmlcn)
x.appendChild(xmldeg)
x.appendChild(self._print(e.base))
return x
x = self.dom.createElement('apply')
x_1 = self.dom.createElement(self.mathml_tag(e))
x.appendChild(x_1)
x.appendChild(self._print(e.base))
x.appendChild(self._print(e.exp))
return x
def _print_Number(self, e):
x = self.dom.createElement(self.mathml_tag(e))
x.appendChild(self.dom.createTextNode(str(e)))
return x
def _print_Float(self, e):
x = self.dom.createElement(self.mathml_tag(e))
repr_e = mlib_to_str(e._mpf_, repr_dps(e._prec))
x.appendChild(self.dom.createTextNode(repr_e))
return x
def _print_Derivative(self, e):
x = self.dom.createElement('apply')
diff_symbol = self.mathml_tag(e)
if requires_partial(e.expr):
diff_symbol = 'partialdiff'
x.appendChild(self.dom.createElement(diff_symbol))
x_1 = self.dom.createElement('bvar')
for sym, times in reversed(e.variable_count):
x_1.appendChild(self._print(sym))
if times > 1:
degree = self.dom.createElement('degree')
degree.appendChild(self._print(sympify(times)))
x_1.appendChild(degree)
x.appendChild(x_1)
x.appendChild(self._print(e.expr))
return x
def _print_Function(self, e):
x = self.dom.createElement("apply")
x.appendChild(self.dom.createElement(self.mathml_tag(e)))
for arg in e.args:
x.appendChild(self._print(arg))
return x
def _print_Basic(self, e):
x = self.dom.createElement(self.mathml_tag(e))
for arg in e.args:
x.appendChild(self._print(arg))
return x
def _print_AssocOp(self, e):
x = self.dom.createElement('apply')
x_1 = self.dom.createElement(self.mathml_tag(e))
x.appendChild(x_1)
for arg in e.args:
x.appendChild(self._print(arg))
return x
def _print_Relational(self, e):
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement(self.mathml_tag(e)))
x.appendChild(self._print(e.lhs))
x.appendChild(self._print(e.rhs))
return x
def _print_list(self, seq):
"""MathML reference for the <list> element:
http://www.w3.org/TR/MathML2/chapter4.html#contm.list"""
dom_element = self.dom.createElement('list')
for item in seq:
dom_element.appendChild(self._print(item))
return dom_element
def _print_int(self, p):
dom_element = self.dom.createElement(self.mathml_tag(p))
dom_element.appendChild(self.dom.createTextNode(str(p)))
return dom_element
_print_Implies = _print_AssocOp
_print_Not = _print_AssocOp
_print_Xor = _print_AssocOp
def _print_FiniteSet(self, e):
x = self.dom.createElement('set')
for arg in e.args:
x.appendChild(self._print(arg))
return x
def _print_Complement(self, e):
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement('setdiff'))
for arg in e.args:
x.appendChild(self._print(arg))
return x
def _print_ProductSet(self, e):
x = self.dom.createElement('apply')
x.appendChild(self.dom.createElement('cartesianproduct'))
for arg in e.args:
x.appendChild(self._print(arg))
return x
# XXX Symmetric difference is not supported for MathML content printers.
class MathMLPresentationPrinter(MathMLPrinterBase):
"""Prints an expression to the Presentation MathML markup language.
References: https://www.w3.org/TR/MathML2/chapter3.html
"""
printmethod = "_mathml_presentation"
def mathml_tag(self, e):
"""Returns the MathML tag for an expression."""
translate = {
'Number': 'mn',
'Limit': '→',
'Derivative': 'ⅆ',
'int': 'mn',
'Symbol': 'mi',
'Integral': '∫',
'Sum': '∑',
'sin': 'sin',
'cos': 'cos',
'tan': 'tan',
'cot': 'cot',
'asin': 'arcsin',
'asinh': 'arcsinh',
'acos': 'arccos',
'acosh': 'arccosh',
'atan': 'arctan',
'atanh': 'arctanh',
'acot': 'arccot',
'atan2': 'arctan',
'Equality': '=',
'Unequality': '≠',
'GreaterThan': '≥',
'LessThan': '≤',
'StrictGreaterThan': '>',
'StrictLessThan': '<',
'lerchphi': 'Φ',
'zeta': 'ζ',
'dirichlet_eta': 'η',
'elliptic_k': 'Κ',
'lowergamma': 'γ',
'uppergamma': 'Γ',
'gamma': 'Γ',
'totient': 'ϕ',
'reduced_totient': 'λ',
'primenu': 'ν',
'primeomega': 'Ω',
'fresnels': 'S',
'fresnelc': 'C',
'LambertW': 'W',
'Heaviside': 'Θ',
'BooleanTrue': 'True',
'BooleanFalse': 'False',
'NoneType': 'None',
'mathieus': 'S',
'mathieuc': 'C',
'mathieusprime': 'S′',
'mathieucprime': 'C′',
}
def mul_symbol_selection():
if (self._settings["mul_symbol"] is None or
self._settings["mul_symbol"] == 'None'):
return '⁢'
elif self._settings["mul_symbol"] == 'times':
return '×'
elif self._settings["mul_symbol"] == 'dot':
return '·'
elif self._settings["mul_symbol"] == 'ldot':
return '․'
elif not isinstance(self._settings["mul_symbol"], str):
raise TypeError
else:
return self._settings["mul_symbol"]
for cls in e.__class__.__mro__:
n = cls.__name__
if n in translate:
return translate[n]
# Not found in the MRO set
if e.__class__.__name__ == "Mul":
return mul_symbol_selection()
n = e.__class__.__name__
return n.lower()
def parenthesize(self, item, level, strict=False):
prec_val = precedence_traditional(item)
if (prec_val < level) or ((not strict) and prec_val <= level):
brac = self.dom.createElement('mfenced')
brac.appendChild(self._print(item))
return brac
else:
return self._print(item)
def _print_Mul(self, expr):
def multiply(expr, mrow):
from sympy.simplify import fraction
numer, denom = fraction(expr)
if denom is not S.One:
frac = self.dom.createElement('mfrac')
if self._settings["fold_short_frac"] and len(str(expr)) < 7:
frac.setAttribute('bevelled', 'true')
xnum = self._print(numer)
xden = self._print(denom)
frac.appendChild(xnum)
frac.appendChild(xden)
mrow.appendChild(frac)
return mrow
coeff, terms = expr.as_coeff_mul()
if coeff is S.One and len(terms) == 1:
mrow.appendChild(self._print(terms[0]))
return mrow
if self.order != 'old':
terms = Mul._from_args(terms).as_ordered_factors()
if coeff != 1:
x = self._print(coeff)
y = self.dom.createElement('mo')
y.appendChild(self.dom.createTextNode(self.mathml_tag(expr)))
mrow.appendChild(x)
mrow.appendChild(y)
for term in terms:
mrow.appendChild(self.parenthesize(term, PRECEDENCE['Mul']))
if not term == terms[-1]:
y = self.dom.createElement('mo')
y.appendChild(self.dom.createTextNode(self.mathml_tag(expr)))
mrow.appendChild(y)
return mrow
mrow = self.dom.createElement('mrow')
if expr.could_extract_minus_sign():
x = self.dom.createElement('mo')
x.appendChild(self.dom.createTextNode('-'))
mrow.appendChild(x)
mrow = multiply(-expr, mrow)
else:
mrow = multiply(expr, mrow)
return mrow
def _print_Add(self, expr, order=None):
mrow = self.dom.createElement('mrow')
args = self._as_ordered_terms(expr, order=order)
mrow.appendChild(self._print(args[0]))
for arg in args[1:]:
if arg.could_extract_minus_sign():
# use minus
x = self.dom.createElement('mo')
x.appendChild(self.dom.createTextNode('-'))
y = self._print(-arg)
# invert expression since this is now minused
else:
x = self.dom.createElement('mo')
x.appendChild(self.dom.createTextNode('+'))
y = self._print(arg)
mrow.appendChild(x)
mrow.appendChild(y)
return mrow
def _print_MatrixBase(self, m):
table = self.dom.createElement('mtable')
for i in range(m.rows):
x = self.dom.createElement('mtr')
for j in range(m.cols):
y = self.dom.createElement('mtd')
y.appendChild(self._print(m[i, j]))
x.appendChild(y)
table.appendChild(x)
if self._settings["mat_delim"] == '':
return table
brac = self.dom.createElement('mfenced')
if self._settings["mat_delim"] == "[":
brac.setAttribute('close', ']')
brac.setAttribute('open', '[')
brac.appendChild(table)
return brac
def _get_printed_Rational(self, e, folded=None):
if e.p < 0:
p = -e.p
else:
p = e.p
x = self.dom.createElement('mfrac')
if folded or self._settings["fold_short_frac"]:
x.setAttribute('bevelled', 'true')
x.appendChild(self._print(p))
x.appendChild(self._print(e.q))
if e.p < 0:
mrow = self.dom.createElement('mrow')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('-'))
mrow.appendChild(mo)
mrow.appendChild(x)
return mrow
else:
return x
def _print_Rational(self, e):
if e.q == 1:
# don't divide
return self._print(e.p)
return self._get_printed_Rational(e, self._settings["fold_short_frac"])
def _print_Limit(self, e):
mrow = self.dom.createElement('mrow')
munder = self.dom.createElement('munder')
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode('lim'))
x = self.dom.createElement('mrow')
x_1 = self._print(e.args[1])
arrow = self.dom.createElement('mo')
arrow.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
x_2 = self._print(e.args[2])
x.appendChild(x_1)
x.appendChild(arrow)
x.appendChild(x_2)
munder.appendChild(mi)
munder.appendChild(x)
mrow.appendChild(munder)
mrow.appendChild(self._print(e.args[0]))
return mrow
def _print_ImaginaryUnit(self, e):
x = self.dom.createElement('mi')
x.appendChild(self.dom.createTextNode('ⅈ'))
return x
def _print_GoldenRatio(self, e):
x = self.dom.createElement('mi')
x.appendChild(self.dom.createTextNode('Φ'))
return x
def _print_Exp1(self, e):
x = self.dom.createElement('mi')
x.appendChild(self.dom.createTextNode('ⅇ'))
return x
def _print_Pi(self, e):
x = self.dom.createElement('mi')
x.appendChild(self.dom.createTextNode('π'))
return x
def _print_Infinity(self, e):
x = self.dom.createElement('mi')
x.appendChild(self.dom.createTextNode('∞'))
return x
def _print_NegativeInfinity(self, e):
mrow = self.dom.createElement('mrow')
y = self.dom.createElement('mo')
y.appendChild(self.dom.createTextNode('-'))
x = self._print_Infinity(e)
mrow.appendChild(y)
mrow.appendChild(x)
return mrow
def _print_HBar(self, e):
x = self.dom.createElement('mi')
x.appendChild(self.dom.createTextNode('ℏ'))
return x
def _print_EulerGamma(self, e):
x = self.dom.createElement('mi')
x.appendChild(self.dom.createTextNode('γ'))
return x
def _print_TribonacciConstant(self, e):
x = self.dom.createElement('mi')
x.appendChild(self.dom.createTextNode('TribonacciConstant'))
return x
def _print_Dagger(self, e):
msup = self.dom.createElement('msup')
msup.appendChild(self._print(e.args[0]))
msup.appendChild(self.dom.createTextNode('†'))
return msup
def _print_Contains(self, e):
mrow = self.dom.createElement('mrow')
mrow.appendChild(self._print(e.args[0]))
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('∈'))
mrow.appendChild(mo)
mrow.appendChild(self._print(e.args[1]))
return mrow
def _print_HilbertSpace(self, e):
x = self.dom.createElement('mi')
x.appendChild(self.dom.createTextNode('ℋ'))
return x
def _print_ComplexSpace(self, e):
msup = self.dom.createElement('msup')
msup.appendChild(self.dom.createTextNode('𝒞'))
msup.appendChild(self._print(e.args[0]))
return msup
def _print_FockSpace(self, e):
x = self.dom.createElement('mi')
x.appendChild(self.dom.createTextNode('ℱ'))
return x
def _print_Integral(self, expr):
intsymbols = {1: "∫", 2: "∬", 3: "∭"}
mrow = self.dom.createElement('mrow')
if len(expr.limits) <= 3 and all(len(lim) == 1 for lim in expr.limits):
# Only up to three-integral signs exists
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode(intsymbols[len(expr.limits)]))
mrow.appendChild(mo)
else:
# Either more than three or limits provided
for lim in reversed(expr.limits):
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode(intsymbols[1]))
if len(lim) == 1:
mrow.appendChild(mo)
if len(lim) == 2:
msup = self.dom.createElement('msup')
msup.appendChild(mo)
msup.appendChild(self._print(lim[1]))
mrow.appendChild(msup)
if len(lim) == 3:
msubsup = self.dom.createElement('msubsup')
msubsup.appendChild(mo)
msubsup.appendChild(self._print(lim[1]))
msubsup.appendChild(self._print(lim[2]))
mrow.appendChild(msubsup)
# print function
mrow.appendChild(self.parenthesize(expr.function, PRECEDENCE["Mul"],
strict=True))
# print integration variables
for lim in reversed(expr.limits):
d = self.dom.createElement('mo')
d.appendChild(self.dom.createTextNode('ⅆ'))
mrow.appendChild(d)
mrow.appendChild(self._print(lim[0]))
return mrow
def _print_Sum(self, e):
limits = list(e.limits)
subsup = self.dom.createElement('munderover')
low_elem = self._print(limits[0][1])
up_elem = self._print(limits[0][2])
summand = self.dom.createElement('mo')
summand.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
low = self.dom.createElement('mrow')
var = self._print(limits[0][0])
equal = self.dom.createElement('mo')
equal.appendChild(self.dom.createTextNode('='))
low.appendChild(var)
low.appendChild(equal)
low.appendChild(low_elem)
subsup.appendChild(summand)
subsup.appendChild(low)
subsup.appendChild(up_elem)
mrow = self.dom.createElement('mrow')
mrow.appendChild(subsup)
if len(str(e.function)) == 1:
mrow.appendChild(self._print(e.function))
else:
fence = self.dom.createElement('mfenced')
fence.appendChild(self._print(e.function))
mrow.appendChild(fence)
return mrow
def _print_Symbol(self, sym, style='plain'):
def join(items):
if len(items) > 1:
mrow = self.dom.createElement('mrow')
for i, item in enumerate(items):
if i > 0:
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode(" "))
mrow.appendChild(mo)
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode(item))
mrow.appendChild(mi)
return mrow
else:
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode(items[0]))
return mi
# translate name, supers and subs to unicode characters
def translate(s):
if s in greek_unicode:
return greek_unicode.get(s)
else:
return s
name, supers, subs = split_super_sub(sym.name)
name = translate(name)
supers = [translate(sup) for sup in supers]
subs = [translate(sub) for sub in subs]
mname = self.dom.createElement('mi')
mname.appendChild(self.dom.createTextNode(name))
if len(supers) == 0:
if len(subs) == 0:
x = mname
else:
x = self.dom.createElement('msub')
x.appendChild(mname)
x.appendChild(join(subs))
else:
if len(subs) == 0:
x = self.dom.createElement('msup')
x.appendChild(mname)
x.appendChild(join(supers))
else:
x = self.dom.createElement('msubsup')
x.appendChild(mname)
x.appendChild(join(subs))
x.appendChild(join(supers))
# Set bold font?
if style == 'bold':
x.setAttribute('mathvariant', 'bold')
return x
def _print_MatrixSymbol(self, sym):
return self._print_Symbol(sym,
style=self._settings['mat_symbol_style'])
_print_RandomSymbol = _print_Symbol
def _print_conjugate(self, expr):
enc = self.dom.createElement('menclose')
enc.setAttribute('notation', 'top')
enc.appendChild(self._print(expr.args[0]))
return enc
def _print_operator_after(self, op, expr):
row = self.dom.createElement('mrow')
row.appendChild(self.parenthesize(expr, PRECEDENCE["Func"]))
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode(op))
row.appendChild(mo)
return row
def _print_factorial(self, expr):
return self._print_operator_after('!', expr.args[0])
def _print_factorial2(self, expr):
return self._print_operator_after('!!', expr.args[0])
def _print_binomial(self, expr):
brac = self.dom.createElement('mfenced')
frac = self.dom.createElement('mfrac')
frac.setAttribute('linethickness', '0')
frac.appendChild(self._print(expr.args[0]))
frac.appendChild(self._print(expr.args[1]))
brac.appendChild(frac)
return brac
def _print_Pow(self, e):
# Here we use root instead of power if the exponent is the
# reciprocal of an integer
if (e.exp.is_Rational and abs(e.exp.p) == 1 and e.exp.q != 1 and
self._settings['root_notation']):
if e.exp.q == 2:
x = self.dom.createElement('msqrt')
x.appendChild(self._print(e.base))
if e.exp.q != 2:
x = self.dom.createElement('mroot')
x.appendChild(self._print(e.base))
x.appendChild(self._print(e.exp.q))
if e.exp.p == -1:
frac = self.dom.createElement('mfrac')
frac.appendChild(self._print(1))
frac.appendChild(x)
return frac
else:
return x
if e.exp.is_Rational and e.exp.q != 1:
if e.exp.is_negative:
top = self.dom.createElement('mfrac')
top.appendChild(self._print(1))
x = self.dom.createElement('msup')
x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow']))
x.appendChild(self._get_printed_Rational(-e.exp,
self._settings['fold_frac_powers']))
top.appendChild(x)
return top
else:
x = self.dom.createElement('msup')
x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow']))
x.appendChild(self._get_printed_Rational(e.exp,
self._settings['fold_frac_powers']))
return x
if e.exp.is_negative:
top = self.dom.createElement('mfrac')
top.appendChild(self._print(1))
if e.exp == -1:
top.appendChild(self._print(e.base))
else:
x = self.dom.createElement('msup')
x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow']))
x.appendChild(self._print(-e.exp))
top.appendChild(x)
return top
x = self.dom.createElement('msup')
x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow']))
x.appendChild(self._print(e.exp))
return x
def _print_Number(self, e):
x = self.dom.createElement(self.mathml_tag(e))
x.appendChild(self.dom.createTextNode(str(e)))
return x
def _print_AccumulationBounds(self, i):
brac = self.dom.createElement('mfenced')
brac.setAttribute('close', '\u27e9')
brac.setAttribute('open', '\u27e8')
brac.appendChild(self._print(i.min))
brac.appendChild(self._print(i.max))
return brac
def _print_Derivative(self, e):
if requires_partial(e.expr):
d = '∂'
else:
d = self.mathml_tag(e)
# Determine denominator
m = self.dom.createElement('mrow')
dim = 0 # Total diff dimension, for numerator
for sym, num in reversed(e.variable_count):
dim += num
if num >= 2:
x = self.dom.createElement('msup')
xx = self.dom.createElement('mo')
xx.appendChild(self.dom.createTextNode(d))
x.appendChild(xx)
x.appendChild(self._print(num))
else:
x = self.dom.createElement('mo')
x.appendChild(self.dom.createTextNode(d))
m.appendChild(x)
y = self._print(sym)
m.appendChild(y)
mnum = self.dom.createElement('mrow')
if dim >= 2:
x = self.dom.createElement('msup')
xx = self.dom.createElement('mo')
xx.appendChild(self.dom.createTextNode(d))
x.appendChild(xx)
x.appendChild(self._print(dim))
else:
x = self.dom.createElement('mo')
x.appendChild(self.dom.createTextNode(d))
mnum.appendChild(x)
mrow = self.dom.createElement('mrow')
frac = self.dom.createElement('mfrac')
frac.appendChild(mnum)
frac.appendChild(m)
mrow.appendChild(frac)
# Print function
mrow.appendChild(self._print(e.expr))
return mrow
def _print_Function(self, e):
mrow = self.dom.createElement('mrow')
x = self.dom.createElement('mi')
if self.mathml_tag(e) == 'log' and self._settings["ln_notation"]:
x.appendChild(self.dom.createTextNode('ln'))
else:
x.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
y = self.dom.createElement('mfenced')
for arg in e.args:
y.appendChild(self._print(arg))
mrow.appendChild(x)
mrow.appendChild(y)
return mrow
def _print_Float(self, expr):
# Based off of that in StrPrinter
dps = prec_to_dps(expr._prec)
str_real = mlib_to_str(expr._mpf_, dps, strip_zeros=True)
# Must always have a mul symbol (as 2.5 10^{20} just looks odd)
# thus we use the number separator
separator = self._settings['mul_symbol_mathml_numbers']
mrow = self.dom.createElement('mrow')
if 'e' in str_real:
(mant, exp) = str_real.split('e')
if exp[0] == '+':
exp = exp[1:]
mn = self.dom.createElement('mn')
mn.appendChild(self.dom.createTextNode(mant))
mrow.appendChild(mn)
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode(separator))
mrow.appendChild(mo)
msup = self.dom.createElement('msup')
mn = self.dom.createElement('mn')
mn.appendChild(self.dom.createTextNode("10"))
msup.appendChild(mn)
mn = self.dom.createElement('mn')
mn.appendChild(self.dom.createTextNode(exp))
msup.appendChild(mn)
mrow.appendChild(msup)
return mrow
elif str_real == "+inf":
return self._print_Infinity(None)
elif str_real == "-inf":
return self._print_NegativeInfinity(None)
else:
mn = self.dom.createElement('mn')
mn.appendChild(self.dom.createTextNode(str_real))
return mn
def _print_polylog(self, expr):
mrow = self.dom.createElement('mrow')
m = self.dom.createElement('msub')
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode('Li'))
m.appendChild(mi)
m.appendChild(self._print(expr.args[0]))
mrow.appendChild(m)
brac = self.dom.createElement('mfenced')
brac.appendChild(self._print(expr.args[1]))
mrow.appendChild(brac)
return mrow
def _print_Basic(self, e):
mrow = self.dom.createElement('mrow')
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
mrow.appendChild(mi)
brac = self.dom.createElement('mfenced')
for arg in e.args:
brac.appendChild(self._print(arg))
mrow.appendChild(brac)
return mrow
def _print_Tuple(self, e):
mrow = self.dom.createElement('mrow')
x = self.dom.createElement('mfenced')
for arg in e.args:
x.appendChild(self._print(arg))
mrow.appendChild(x)
return mrow
def _print_Interval(self, i):
mrow = self.dom.createElement('mrow')
brac = self.dom.createElement('mfenced')
if i.start == i.end:
# Most often, this type of Interval is converted to a FiniteSet
brac.setAttribute('close', '}')
brac.setAttribute('open', '{')
brac.appendChild(self._print(i.start))
else:
if i.right_open:
brac.setAttribute('close', ')')
else:
brac.setAttribute('close', ']')
if i.left_open:
brac.setAttribute('open', '(')
else:
brac.setAttribute('open', '[')
brac.appendChild(self._print(i.start))
brac.appendChild(self._print(i.end))
mrow.appendChild(brac)
return mrow
def _print_Abs(self, expr, exp=None):
mrow = self.dom.createElement('mrow')
x = self.dom.createElement('mfenced')
x.setAttribute('close', '|')
x.setAttribute('open', '|')
x.appendChild(self._print(expr.args[0]))
mrow.appendChild(x)
return mrow
_print_Determinant = _print_Abs
def _print_re_im(self, c, expr):
mrow = self.dom.createElement('mrow')
mi = self.dom.createElement('mi')
mi.setAttribute('mathvariant', 'fraktur')
mi.appendChild(self.dom.createTextNode(c))
mrow.appendChild(mi)
brac = self.dom.createElement('mfenced')
brac.appendChild(self._print(expr))
mrow.appendChild(brac)
return mrow
def _print_re(self, expr, exp=None):
return self._print_re_im('R', expr.args[0])
def _print_im(self, expr, exp=None):
return self._print_re_im('I', expr.args[0])
def _print_AssocOp(self, e):
mrow = self.dom.createElement('mrow')
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
mrow.appendChild(mi)
for arg in e.args:
mrow.appendChild(self._print(arg))
return mrow
def _print_SetOp(self, expr, symbol, prec):
mrow = self.dom.createElement('mrow')
mrow.appendChild(self.parenthesize(expr.args[0], prec))
for arg in expr.args[1:]:
x = self.dom.createElement('mo')
x.appendChild(self.dom.createTextNode(symbol))
y = self.parenthesize(arg, prec)
mrow.appendChild(x)
mrow.appendChild(y)
return mrow
def _print_Union(self, expr):
prec = PRECEDENCE_TRADITIONAL['Union']
return self._print_SetOp(expr, '∪', prec)
def _print_Intersection(self, expr):
prec = PRECEDENCE_TRADITIONAL['Intersection']
return self._print_SetOp(expr, '∩', prec)
def _print_Complement(self, expr):
prec = PRECEDENCE_TRADITIONAL['Complement']
return self._print_SetOp(expr, '∖', prec)
def _print_SymmetricDifference(self, expr):
prec = PRECEDENCE_TRADITIONAL['SymmetricDifference']
return self._print_SetOp(expr, '∆', prec)
def _print_ProductSet(self, expr):
prec = PRECEDENCE_TRADITIONAL['ProductSet']
return self._print_SetOp(expr, '×', prec)
def _print_FiniteSet(self, s):
return self._print_set(s.args)
def _print_set(self, s):
items = sorted(s, key=default_sort_key)
brac = self.dom.createElement('mfenced')
brac.setAttribute('close', '}')
brac.setAttribute('open', '{')
for item in items:
brac.appendChild(self._print(item))
return brac
_print_frozenset = _print_set
def _print_LogOp(self, args, symbol):
mrow = self.dom.createElement('mrow')
if args[0].is_Boolean and not args[0].is_Not:
brac = self.dom.createElement('mfenced')
brac.appendChild(self._print(args[0]))
mrow.appendChild(brac)
else:
mrow.appendChild(self._print(args[0]))
for arg in args[1:]:
x = self.dom.createElement('mo')
x.appendChild(self.dom.createTextNode(symbol))
if arg.is_Boolean and not arg.is_Not:
y = self.dom.createElement('mfenced')
y.appendChild(self._print(arg))
else:
y = self._print(arg)
mrow.appendChild(x)
mrow.appendChild(y)
return mrow
def _print_BasisDependent(self, expr):
from sympy.vector import Vector
if expr == expr.zero:
# Not clear if this is ever called
return self._print(expr.zero)
if isinstance(expr, Vector):
items = expr.separate().items()
else:
items = [(0, expr)]
mrow = self.dom.createElement('mrow')
for system, vect in items:
inneritems = list(vect.components.items())
inneritems.sort(key = lambda x:x[0].__str__())
for i, (k, v) in enumerate(inneritems):
if v == 1:
if i: # No + for first item
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('+'))
mrow.appendChild(mo)
mrow.appendChild(self._print(k))
elif v == -1:
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('-'))
mrow.appendChild(mo)
mrow.appendChild(self._print(k))
else:
if i: # No + for first item
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('+'))
mrow.appendChild(mo)
mbrac = self.dom.createElement('mfenced')
mbrac.appendChild(self._print(v))
mrow.appendChild(mbrac)
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('⁢'))
mrow.appendChild(mo)
mrow.appendChild(self._print(k))
return mrow
def _print_And(self, expr):
args = sorted(expr.args, key=default_sort_key)
return self._print_LogOp(args, '∧')
def _print_Or(self, expr):
args = sorted(expr.args, key=default_sort_key)
return self._print_LogOp(args, '∨')
def _print_Xor(self, expr):
args = sorted(expr.args, key=default_sort_key)
return self._print_LogOp(args, '⊻')
def _print_Implies(self, expr):
return self._print_LogOp(expr.args, '⇒')
def _print_Equivalent(self, expr):
args = sorted(expr.args, key=default_sort_key)
return self._print_LogOp(args, '⇔')
def _print_Not(self, e):
mrow = self.dom.createElement('mrow')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('¬'))
mrow.appendChild(mo)
if (e.args[0].is_Boolean):
x = self.dom.createElement('mfenced')
x.appendChild(self._print(e.args[0]))
else:
x = self._print(e.args[0])
mrow.appendChild(x)
return mrow
def _print_bool(self, e):
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
return mi
_print_BooleanTrue = _print_bool
_print_BooleanFalse = _print_bool
def _print_NoneType(self, e):
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
return mi
def _print_Range(self, s):
dots = "\u2026"
brac = self.dom.createElement('mfenced')
brac.setAttribute('close', '}')
brac.setAttribute('open', '{')
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)
for el in printset:
if el == dots:
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode(dots))
brac.appendChild(mi)
else:
brac.appendChild(self._print(el))
return brac
def _hprint_variadic_function(self, expr):
args = sorted(expr.args, key=default_sort_key)
mrow = self.dom.createElement('mrow')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode((str(expr.func)).lower()))
mrow.appendChild(mo)
brac = self.dom.createElement('mfenced')
for symbol in args:
brac.appendChild(self._print(symbol))
mrow.appendChild(brac)
return mrow
_print_Min = _print_Max = _hprint_variadic_function
def _print_exp(self, expr):
msup = self.dom.createElement('msup')
msup.appendChild(self._print_Exp1(None))
msup.appendChild(self._print(expr.args[0]))
return msup
def _print_Relational(self, e):
mrow = self.dom.createElement('mrow')
mrow.appendChild(self._print(e.lhs))
x = self.dom.createElement('mo')
x.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
mrow.appendChild(x)
mrow.appendChild(self._print(e.rhs))
return mrow
def _print_int(self, p):
dom_element = self.dom.createElement(self.mathml_tag(p))
dom_element.appendChild(self.dom.createTextNode(str(p)))
return dom_element
def _print_BaseScalar(self, e):
msub = self.dom.createElement('msub')
index, system = e._id
mi = self.dom.createElement('mi')
mi.setAttribute('mathvariant', 'bold')
mi.appendChild(self.dom.createTextNode(system._variable_names[index]))
msub.appendChild(mi)
mi = self.dom.createElement('mi')
mi.setAttribute('mathvariant', 'bold')
mi.appendChild(self.dom.createTextNode(system._name))
msub.appendChild(mi)
return msub
def _print_BaseVector(self, e):
msub = self.dom.createElement('msub')
index, system = e._id
mover = self.dom.createElement('mover')
mi = self.dom.createElement('mi')
mi.setAttribute('mathvariant', 'bold')
mi.appendChild(self.dom.createTextNode(system._vector_names[index]))
mover.appendChild(mi)
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('^'))
mover.appendChild(mo)
msub.appendChild(mover)
mi = self.dom.createElement('mi')
mi.setAttribute('mathvariant', 'bold')
mi.appendChild(self.dom.createTextNode(system._name))
msub.appendChild(mi)
return msub
def _print_VectorZero(self, e):
mover = self.dom.createElement('mover')
mi = self.dom.createElement('mi')
mi.setAttribute('mathvariant', 'bold')
mi.appendChild(self.dom.createTextNode("0"))
mover.appendChild(mi)
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('^'))
mover.appendChild(mo)
return mover
def _print_Cross(self, expr):
mrow = self.dom.createElement('mrow')
vec1 = expr._expr1
vec2 = expr._expr2
mrow.appendChild(self.parenthesize(vec1, PRECEDENCE['Mul']))
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('×'))
mrow.appendChild(mo)
mrow.appendChild(self.parenthesize(vec2, PRECEDENCE['Mul']))
return mrow
def _print_Curl(self, expr):
mrow = self.dom.createElement('mrow')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('∇'))
mrow.appendChild(mo)
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('×'))
mrow.appendChild(mo)
mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul']))
return mrow
def _print_Divergence(self, expr):
mrow = self.dom.createElement('mrow')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('∇'))
mrow.appendChild(mo)
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('·'))
mrow.appendChild(mo)
mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul']))
return mrow
def _print_Dot(self, expr):
mrow = self.dom.createElement('mrow')
vec1 = expr._expr1
vec2 = expr._expr2
mrow.appendChild(self.parenthesize(vec1, PRECEDENCE['Mul']))
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('·'))
mrow.appendChild(mo)
mrow.appendChild(self.parenthesize(vec2, PRECEDENCE['Mul']))
return mrow
def _print_Gradient(self, expr):
mrow = self.dom.createElement('mrow')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('∇'))
mrow.appendChild(mo)
mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul']))
return mrow
def _print_Laplacian(self, expr):
mrow = self.dom.createElement('mrow')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('∆'))
mrow.appendChild(mo)
mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul']))
return mrow
def _print_Integers(self, e):
x = self.dom.createElement('mi')
x.setAttribute('mathvariant', 'normal')
x.appendChild(self.dom.createTextNode('ℤ'))
return x
def _print_Complexes(self, e):
x = self.dom.createElement('mi')
x.setAttribute('mathvariant', 'normal')
x.appendChild(self.dom.createTextNode('ℂ'))
return x
def _print_Reals(self, e):
x = self.dom.createElement('mi')
x.setAttribute('mathvariant', 'normal')
x.appendChild(self.dom.createTextNode('ℝ'))
return x
def _print_Naturals(self, e):
x = self.dom.createElement('mi')
x.setAttribute('mathvariant', 'normal')
x.appendChild(self.dom.createTextNode('ℕ'))
return x
def _print_Naturals0(self, e):
sub = self.dom.createElement('msub')
x = self.dom.createElement('mi')
x.setAttribute('mathvariant', 'normal')
x.appendChild(self.dom.createTextNode('ℕ'))
sub.appendChild(x)
sub.appendChild(self._print(S.Zero))
return sub
def _print_SingularityFunction(self, expr):
shift = expr.args[0] - expr.args[1]
power = expr.args[2]
sup = self.dom.createElement('msup')
brac = self.dom.createElement('mfenced')
brac.setAttribute('close', '\u27e9')
brac.setAttribute('open', '\u27e8')
brac.appendChild(self._print(shift))
sup.appendChild(brac)
sup.appendChild(self._print(power))
return sup
def _print_NaN(self, e):
x = self.dom.createElement('mi')
x.appendChild(self.dom.createTextNode('NaN'))
return x
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
sub = self.dom.createElement('msub')
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode(name))
sub.appendChild(mi)
sub.appendChild(self._print(e.args[0]))
if len(e.args) == 1:
return sub
# TODO: copy-pasted from _print_Function: can we do better?
mrow = self.dom.createElement('mrow')
y = self.dom.createElement('mfenced')
for arg in e.args[1:]:
y.appendChild(self._print(arg))
mrow.appendChild(sub)
mrow.appendChild(y)
return mrow
def _print_bernoulli(self, e):
return self._print_number_function(e, 'B')
_print_bell = _print_bernoulli
def _print_catalan(self, e):
return self._print_number_function(e, 'C')
def _print_euler(self, e):
return self._print_number_function(e, 'E')
def _print_fibonacci(self, e):
return self._print_number_function(e, 'F')
def _print_lucas(self, e):
return self._print_number_function(e, 'L')
def _print_stieltjes(self, e):
return self._print_number_function(e, 'γ')
def _print_tribonacci(self, e):
return self._print_number_function(e, 'T')
def _print_ComplexInfinity(self, e):
x = self.dom.createElement('mover')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('∞'))
x.appendChild(mo)
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('~'))
x.appendChild(mo)
return x
def _print_EmptySet(self, e):
x = self.dom.createElement('mo')
x.appendChild(self.dom.createTextNode('∅'))
return x
def _print_UniversalSet(self, e):
x = self.dom.createElement('mo')
x.appendChild(self.dom.createTextNode('𝕌'))
return x
def _print_Adjoint(self, expr):
from sympy.matrices import MatrixSymbol
mat = expr.arg
sup = self.dom.createElement('msup')
if not isinstance(mat, MatrixSymbol):
brac = self.dom.createElement('mfenced')
brac.appendChild(self._print(mat))
sup.appendChild(brac)
else:
sup.appendChild(self._print(mat))
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('†'))
sup.appendChild(mo)
return sup
def _print_Transpose(self, expr):
from sympy.matrices import MatrixSymbol
mat = expr.arg
sup = self.dom.createElement('msup')
if not isinstance(mat, MatrixSymbol):
brac = self.dom.createElement('mfenced')
brac.appendChild(self._print(mat))
sup.appendChild(brac)
else:
sup.appendChild(self._print(mat))
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('T'))
sup.appendChild(mo)
return sup
def _print_Inverse(self, expr):
from sympy.matrices import MatrixSymbol
mat = expr.arg
sup = self.dom.createElement('msup')
if not isinstance(mat, MatrixSymbol):
brac = self.dom.createElement('mfenced')
brac.appendChild(self._print(mat))
sup.appendChild(brac)
else:
sup.appendChild(self._print(mat))
sup.appendChild(self._print(-1))
return sup
def _print_MatMul(self, expr):
from sympy.matrices.expressions.matmul import MatMul
x = self.dom.createElement('mrow')
args = expr.args
if isinstance(args[0], Mul):
args = args[0].as_ordered_factors() + list(args[1:])
else:
args = list(args)
if isinstance(expr, MatMul) and expr.could_extract_minus_sign():
if args[0] == -1:
args = args[1:]
else:
args[0] = -args[0]
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('-'))
x.appendChild(mo)
for arg in args[:-1]:
x.appendChild(self.parenthesize(arg, precedence_traditional(expr),
False))
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('⁢'))
x.appendChild(mo)
x.appendChild(self.parenthesize(args[-1], precedence_traditional(expr),
False))
return x
def _print_MatPow(self, expr):
from sympy.matrices import MatrixSymbol
base, exp = expr.base, expr.exp
sup = self.dom.createElement('msup')
if not isinstance(base, MatrixSymbol):
brac = self.dom.createElement('mfenced')
brac.appendChild(self._print(base))
sup.appendChild(brac)
else:
sup.appendChild(self._print(base))
sup.appendChild(self._print(exp))
return sup
def _print_HadamardProduct(self, expr):
x = self.dom.createElement('mrow')
args = expr.args
for arg in args[:-1]:
x.appendChild(
self.parenthesize(arg, precedence_traditional(expr), False))
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('∘'))
x.appendChild(mo)
x.appendChild(
self.parenthesize(args[-1], precedence_traditional(expr), False))
return x
def _print_ZeroMatrix(self, Z):
x = self.dom.createElement('mn')
x.appendChild(self.dom.createTextNode('𝟘'))
return x
def _print_OneMatrix(self, Z):
x = self.dom.createElement('mn')
x.appendChild(self.dom.createTextNode('𝟙'))
return x
def _print_Identity(self, I):
x = self.dom.createElement('mi')
x.appendChild(self.dom.createTextNode('𝕀'))
return x
def _print_floor(self, e):
mrow = self.dom.createElement('mrow')
x = self.dom.createElement('mfenced')
x.setAttribute('close', '\u230B')
x.setAttribute('open', '\u230A')
x.appendChild(self._print(e.args[0]))
mrow.appendChild(x)
return mrow
def _print_ceiling(self, e):
mrow = self.dom.createElement('mrow')
x = self.dom.createElement('mfenced')
x.setAttribute('close', '\u2309')
x.setAttribute('open', '\u2308')
x.appendChild(self._print(e.args[0]))
mrow.appendChild(x)
return mrow
def _print_Lambda(self, e):
x = self.dom.createElement('mfenced')
mrow = self.dom.createElement('mrow')
symbols = e.args[0]
if len(symbols) == 1:
symbols = self._print(symbols[0])
else:
symbols = self._print(symbols)
mrow.appendChild(symbols)
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('↦'))
mrow.appendChild(mo)
mrow.appendChild(self._print(e.args[1]))
x.appendChild(mrow)
return x
def _print_tuple(self, e):
x = self.dom.createElement('mfenced')
for i in e:
x.appendChild(self._print(i))
return x
def _print_IndexedBase(self, e):
return self._print(e.label)
def _print_Indexed(self, e):
x = self.dom.createElement('msub')
x.appendChild(self._print(e.base))
if len(e.indices) == 1:
x.appendChild(self._print(e.indices[0]))
return x
x.appendChild(self._print(e.indices))
return x
def _print_MatrixElement(self, e):
x = self.dom.createElement('msub')
x.appendChild(self.parenthesize(e.parent, PRECEDENCE["Atom"], strict = True))
brac = self.dom.createElement('mfenced')
brac.setAttribute("close", "")
brac.setAttribute("open", "")
for i in e.indices:
brac.appendChild(self._print(i))
x.appendChild(brac)
return x
def _print_elliptic_f(self, e):
x = self.dom.createElement('mrow')
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode('𝖥'))
x.appendChild(mi)
y = self.dom.createElement('mfenced')
y.setAttribute("separators", "|")
for i in e.args:
y.appendChild(self._print(i))
x.appendChild(y)
return x
def _print_elliptic_e(self, e):
x = self.dom.createElement('mrow')
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode('𝖤'))
x.appendChild(mi)
y = self.dom.createElement('mfenced')
y.setAttribute("separators", "|")
for i in e.args:
y.appendChild(self._print(i))
x.appendChild(y)
return x
def _print_elliptic_pi(self, e):
x = self.dom.createElement('mrow')
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode('𝛱'))
x.appendChild(mi)
y = self.dom.createElement('mfenced')
if len(e.args) == 2:
y.setAttribute("separators", "|")
else:
y.setAttribute("separators", ";|")
for i in e.args:
y.appendChild(self._print(i))
x.appendChild(y)
return x
def _print_Ei(self, e):
x = self.dom.createElement('mrow')
mi = self.dom.createElement('mi')
mi.appendChild(self.dom.createTextNode('Ei'))
x.appendChild(mi)
x.appendChild(self._print(e.args))
return x
def _print_expint(self, e):
x = self.dom.createElement('mrow')
y = self.dom.createElement('msub')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('E'))
y.appendChild(mo)
y.appendChild(self._print(e.args[0]))
x.appendChild(y)
x.appendChild(self._print(e.args[1:]))
return x
def _print_jacobi(self, e):
x = self.dom.createElement('mrow')
y = self.dom.createElement('msubsup')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('P'))
y.appendChild(mo)
y.appendChild(self._print(e.args[0]))
y.appendChild(self._print(e.args[1:3]))
x.appendChild(y)
x.appendChild(self._print(e.args[3:]))
return x
def _print_gegenbauer(self, e):
x = self.dom.createElement('mrow')
y = self.dom.createElement('msubsup')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('C'))
y.appendChild(mo)
y.appendChild(self._print(e.args[0]))
y.appendChild(self._print(e.args[1:2]))
x.appendChild(y)
x.appendChild(self._print(e.args[2:]))
return x
def _print_chebyshevt(self, e):
x = self.dom.createElement('mrow')
y = self.dom.createElement('msub')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('T'))
y.appendChild(mo)
y.appendChild(self._print(e.args[0]))
x.appendChild(y)
x.appendChild(self._print(e.args[1:]))
return x
def _print_chebyshevu(self, e):
x = self.dom.createElement('mrow')
y = self.dom.createElement('msub')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('U'))
y.appendChild(mo)
y.appendChild(self._print(e.args[0]))
x.appendChild(y)
x.appendChild(self._print(e.args[1:]))
return x
def _print_legendre(self, e):
x = self.dom.createElement('mrow')
y = self.dom.createElement('msub')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('P'))
y.appendChild(mo)
y.appendChild(self._print(e.args[0]))
x.appendChild(y)
x.appendChild(self._print(e.args[1:]))
return x
def _print_assoc_legendre(self, e):
x = self.dom.createElement('mrow')
y = self.dom.createElement('msubsup')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('P'))
y.appendChild(mo)
y.appendChild(self._print(e.args[0]))
y.appendChild(self._print(e.args[1:2]))
x.appendChild(y)
x.appendChild(self._print(e.args[2:]))
return x
def _print_laguerre(self, e):
x = self.dom.createElement('mrow')
y = self.dom.createElement('msub')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('L'))
y.appendChild(mo)
y.appendChild(self._print(e.args[0]))
x.appendChild(y)
x.appendChild(self._print(e.args[1:]))
return x
def _print_assoc_laguerre(self, e):
x = self.dom.createElement('mrow')
y = self.dom.createElement('msubsup')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('L'))
y.appendChild(mo)
y.appendChild(self._print(e.args[0]))
y.appendChild(self._print(e.args[1:2]))
x.appendChild(y)
x.appendChild(self._print(e.args[2:]))
return x
def _print_hermite(self, e):
x = self.dom.createElement('mrow')
y = self.dom.createElement('msub')
mo = self.dom.createElement('mo')
mo.appendChild(self.dom.createTextNode('H'))
y.appendChild(mo)
y.appendChild(self._print(e.args[0]))
x.appendChild(y)
x.appendChild(self._print(e.args[1:]))
return x
@print_function(MathMLPrinterBase)
def mathml(expr, printer='content', **settings):
"""Returns the MathML representation of expr. If printer is presentation
then prints Presentation MathML else prints content MathML.
"""
if printer == 'presentation':
return MathMLPresentationPrinter(settings).doprint(expr)
else:
return MathMLContentPrinter(settings).doprint(expr)
def print_mathml(expr, printer='content', **settings):
"""
Prints a pretty representation of the MathML code for expr. If printer is
presentation then prints Presentation MathML else prints content MathML.
Examples
========
>>> ##
>>> from sympy import print_mathml
>>> from sympy.abc import x
>>> print_mathml(x+1) #doctest: +NORMALIZE_WHITESPACE
<apply>
<plus/>
<ci>x</ci>
<cn>1</cn>
</apply>
>>> print_mathml(x+1, printer='presentation')
<mrow>
<mi>x</mi>
<mo>+</mo>
<mn>1</mn>
</mrow>
"""
if printer == 'presentation':
s = MathMLPresentationPrinter(settings)
else:
s = MathMLContentPrinter(settings)
xml = s._print(sympify(expr))
s.apply_patch()
pretty_xml = xml.toprettyxml()
s.restore_patch()
print(pretty_xml)
# For backward compatibility
MathMLPrinter = MathMLContentPrinter
|
393ab226f10fe30c80b2e5afdf52abc347025ff7436ed91eb8584f3efe927783 | """
.. deprecated:: 1.7
fcode.py was deprecated and renamed to fortran.py. This is a shim file to
provide backwards compatibility.
"""
from sympy.utilities.exceptions import sympy_deprecation_warning
sympy_deprecation_warning(
"""
The sympy.printing.fcode submodule is deprecated. It has been renamed to
sympy.printing.fortran.
""",
deprecated_since_version="1.7",
active_deprecations_target="deprecated-printing-code-submodules",
)
from .fortran import fcode, print_fcode, known_functions, FCodePrinter # noqa:F401
|
3a9bb67dede459ffcf183a57b1c8ceb9f6146faecacd0903702947e9aef29443 | """
Maple code printer
The MapleCodePrinter converts single SymPy expressions into single
Maple expressions, using the functions defined in the Maple objects where possible.
FIXME: This module is still under actively developed. Some functions may be not completed.
"""
from sympy.core import S
from sympy.core.numbers import Integer, IntegerConstant
from sympy.printing.codeprinter import CodePrinter
from sympy.printing.precedence import precedence, PRECEDENCE
import sympy
_known_func_same_name = (
'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinh', 'cosh', 'tanh', 'sech',
'csch', 'coth', 'exp', 'floor', 'factorial', 'bernoulli', 'euler',
'fibonacci', 'gcd', 'lcm', 'conjugate', 'Ci', 'Chi', 'Ei', 'Li', 'Si', 'Shi',
'erf', 'erfc', 'harmonic', 'LambertW',
'sqrt', # For automatic rewrites
)
known_functions = {
# SymPy -> Maple
'Abs': 'abs',
'log': 'ln',
'asin': 'arcsin',
'acos': 'arccos',
'atan': 'arctan',
'asec': 'arcsec',
'acsc': 'arccsc',
'acot': 'arccot',
'asinh': 'arcsinh',
'acosh': 'arccosh',
'atanh': 'arctanh',
'asech': 'arcsech',
'acsch': 'arccsch',
'acoth': 'arccoth',
'ceiling': 'ceil',
'Max' : 'max',
'Min' : 'min',
'factorial2': 'doublefactorial',
'RisingFactorial': 'pochhammer',
'besseli': 'BesselI',
'besselj': 'BesselJ',
'besselk': 'BesselK',
'bessely': 'BesselY',
'hankelh1': 'HankelH1',
'hankelh2': 'HankelH2',
'airyai': 'AiryAi',
'airybi': 'AiryBi',
'appellf1': 'AppellF1',
'fresnelc': 'FresnelC',
'fresnels': 'FresnelS',
'lerchphi' : 'LerchPhi',
}
for _func in _known_func_same_name:
known_functions[_func] = _func
number_symbols = {
# SymPy -> Maple
S.Pi: 'Pi',
S.Exp1: 'exp(1)',
S.Catalan: 'Catalan',
S.EulerGamma: 'gamma',
S.GoldenRatio: '(1/2 + (1/2)*sqrt(5))'
}
spec_relational_ops = {
# SymPy -> Maple
'==': '=',
'!=': '<>'
}
not_supported_symbol = [
S.ComplexInfinity
]
class MapleCodePrinter(CodePrinter):
"""
Printer which converts a SymPy expression into a maple code.
"""
printmethod = "_maple"
language = "maple"
_default_settings = {
'order': None,
'full_prec': 'auto',
'human': True,
'inline': True,
'allow_unknown_functions': True,
}
def __init__(self, settings=None):
if settings is None:
settings = dict()
super().__init__(settings)
self.known_functions = dict(known_functions)
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
def _get_statement(self, codestring):
return "%s;" % codestring
def _get_comment(self, text):
return "# {}".format(text)
def _declare_number_const(self, name, value):
return "{} := {};".format(name,
value.evalf(self._settings['precision']))
def _format_code(self, lines):
return lines
def _print_tuple(self, expr):
return self._print(list(expr))
def _print_Tuple(self, expr):
return self._print(list(expr))
def _print_Assignment(self, expr):
lhs = self._print(expr.lhs)
rhs = self._print(expr.rhs)
return "{lhs} := {rhs}".format(lhs=lhs, rhs=rhs)
def _print_Pow(self, expr, **kwargs):
PREC = precedence(expr)
if expr.exp == -1:
return '1/%s' % (self.parenthesize(expr.base, PREC))
elif expr.exp in (0.5, S.Half):
return 'sqrt(%s)' % self._print(expr.base)
elif expr.exp in (-0.5, -S.Half):
return '1/sqrt(%s)' % self._print(expr.base)
else:
return '{base}^{exp}'.format(
base=self.parenthesize(expr.base, PREC),
exp=self.parenthesize(expr.exp, PREC))
def _print_Piecewise(self, expr):
if (expr.args[-1].cond is not True) and (expr.args[-1].cond != S.BooleanTrue):
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
_coup_list = [
("{c}, {e}".format(c=self._print(c),
e=self._print(e)) if c is not True and c is not S.BooleanTrue else "{e}".format(
e=self._print(e)))
for e, c in expr.args]
_inbrace = ', '.join(_coup_list)
return 'piecewise({_inbrace})'.format(_inbrace=_inbrace)
def _print_Rational(self, expr):
p, q = int(expr.p), int(expr.q)
return "{p}/{q}".format(p=str(p), q=str(q))
def _print_Relational(self, expr):
PREC=precedence(expr)
lhs_code = self.parenthesize(expr.lhs, PREC)
rhs_code = self.parenthesize(expr.rhs, PREC)
op = expr.rel_op
if op in spec_relational_ops:
op = spec_relational_ops[op]
return "{lhs} {rel_op} {rhs}".format(lhs=lhs_code, rel_op=op, rhs=rhs_code)
def _print_NumberSymbol(self, expr):
return number_symbols[expr]
def _print_NegativeInfinity(self, expr):
return '-infinity'
def _print_Infinity(self, expr):
return 'infinity'
def _print_Idx(self, expr):
return self._print(expr.label)
def _print_BooleanTrue(self, expr):
return "true"
def _print_BooleanFalse(self, expr):
return "false"
def _print_bool(self, expr):
return 'true' if expr else 'false'
def _print_NaN(self, expr):
return 'undefined'
def _get_matrix(self, expr, sparse=False):
if S.Zero in expr.shape:
_strM = 'Matrix([], storage = {storage})'.format(
storage='sparse' if sparse else 'rectangular')
else:
_strM = 'Matrix({list}, storage = {storage})'.format(
list=self._print(expr.tolist()),
storage='sparse' if sparse else 'rectangular')
return _strM
def _print_MatrixElement(self, expr):
return "{parent}[{i_maple}, {j_maple}]".format(
parent=self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True),
i_maple=self._print(expr.i + 1),
j_maple=self._print(expr.j + 1))
def _print_MatrixBase(self, expr):
return self._get_matrix(expr, sparse=False)
def _print_SparseRepMatrix(self, expr):
return self._get_matrix(expr, sparse=True)
def _print_Identity(self, expr):
if isinstance(expr.rows, (Integer, IntegerConstant)):
return self._print(sympy.SparseMatrix(expr))
else:
return "Matrix({var_size}, shape = identity)".format(var_size=self._print(expr.rows))
def _print_MatMul(self, expr):
PREC=precedence(expr)
_fact_list = list(expr.args)
_const = None
if not isinstance(_fact_list[0], (sympy.MatrixBase, sympy.MatrixExpr,
sympy.MatrixSlice, sympy.MatrixSymbol)):
_const, _fact_list = _fact_list[0], _fact_list[1:]
if _const is None or _const == 1:
return '.'.join(self.parenthesize(_m, PREC) for _m in _fact_list)
else:
return '{c}*{m}'.format(c=_const, m='.'.join(self.parenthesize(_m, PREC) for _m in _fact_list))
def _print_MatPow(self, expr):
# This function requires LinearAlgebra Function in Maple
return 'MatrixPower({A}, {n})'.format(A=self._print(expr.base), n=self._print(expr.exp))
def _print_HadamardProduct(self, expr):
PREC = precedence(expr)
_fact_list = list(expr.args)
return '*'.join(self.parenthesize(_m, PREC) for _m in _fact_list)
def _print_Derivative(self, expr):
_f, (_var, _order) = expr.args
if _order != 1:
_second_arg = '{var}${order}'.format(var=self._print(_var),
order=self._print(_order))
else:
_second_arg = '{var}'.format(var=self._print(_var))
return 'diff({func_expr}, {sec_arg})'.format(func_expr=self._print(_f), sec_arg=_second_arg)
def maple_code(expr, assign_to=None, **settings):
r"""Converts ``expr`` to a string of Maple code.
Parameters
==========
expr : Expr
A SymPy expression to be converted.
assign_to : optional
When given, the argument is used as the name of the variable to which
the expression is assigned. Can be a string, ``Symbol``,
``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
expressions that generate multi-line statements.
precision : integer, optional
The precision for numbers such as pi [default=16].
user_functions : dict, optional
A dictionary where keys are ``FunctionClass`` instances and values are
their string representations. Alternatively, the dictionary value can
be a list of tuples i.e. [(argument_test, cfunction_string)]. See
below for examples.
human : bool, optional
If True, the result is a single string that may contain some constant
declarations for the number symbols. If False, the same information is
returned in a tuple of (symbols_to_declare, not_supported_functions,
code_text). [default=True].
contract: bool, optional
If True, ``Indexed`` instances are assumed to obey tensor contraction
rules and the corresponding nested loops over indices are generated.
Setting contract=False will not generate loops, instead the user is
responsible to provide values for the indices in the code.
[default=True].
inline: bool, optional
If True, we try to create single-statement code instead of multiple
statements. [default=True].
"""
return MapleCodePrinter(settings).doprint(expr, assign_to)
def print_maple_code(expr, **settings):
"""Prints the Maple representation of the given expression.
See :func:`maple_code` for the meaning of the optional arguments.
Examples
========
>>> from sympy import print_maple_code, symbols
>>> x, y = symbols('x y')
>>> print_maple_code(x, assign_to=y)
y := x
"""
print(maple_code(expr, **settings))
|
28774930730139a2641cef3fb817d84477815b6548ce2bff618a88577d03f9d0 | from sympy.external.importtools import version_tuple
from collections.abc import Iterable
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.codegen.cfunctions import Sqrt
from sympy.external import import_module
from sympy.printing.precedence import PRECEDENCE
from sympy.printing.pycode import AbstractPythonCodePrinter, ArrayPrinter
import sympy
tensorflow = import_module('tensorflow')
class TensorflowPrinter(ArrayPrinter, AbstractPythonCodePrinter):
"""
Tensorflow printer which handles vectorized piecewise functions,
logical operators, max/min, and relational operators.
"""
printmethod = "_tensorflowcode"
mapping = {
sympy.Abs: "tensorflow.math.abs",
sympy.sign: "tensorflow.math.sign",
# XXX May raise error for ints.
sympy.ceiling: "tensorflow.math.ceil",
sympy.floor: "tensorflow.math.floor",
sympy.log: "tensorflow.math.log",
sympy.exp: "tensorflow.math.exp",
Sqrt: "tensorflow.math.sqrt",
sympy.cos: "tensorflow.math.cos",
sympy.acos: "tensorflow.math.acos",
sympy.sin: "tensorflow.math.sin",
sympy.asin: "tensorflow.math.asin",
sympy.tan: "tensorflow.math.tan",
sympy.atan: "tensorflow.math.atan",
sympy.atan2: "tensorflow.math.atan2",
# XXX Also may give NaN for complex results.
sympy.cosh: "tensorflow.math.cosh",
sympy.acosh: "tensorflow.math.acosh",
sympy.sinh: "tensorflow.math.sinh",
sympy.asinh: "tensorflow.math.asinh",
sympy.tanh: "tensorflow.math.tanh",
sympy.atanh: "tensorflow.math.atanh",
sympy.re: "tensorflow.math.real",
sympy.im: "tensorflow.math.imag",
sympy.arg: "tensorflow.math.angle",
# XXX May raise error for ints and complexes
sympy.erf: "tensorflow.math.erf",
sympy.loggamma: "tensorflow.math.lgamma",
sympy.Eq: "tensorflow.math.equal",
sympy.Ne: "tensorflow.math.not_equal",
sympy.StrictGreaterThan: "tensorflow.math.greater",
sympy.StrictLessThan: "tensorflow.math.less",
sympy.LessThan: "tensorflow.math.less_equal",
sympy.GreaterThan: "tensorflow.math.greater_equal",
sympy.And: "tensorflow.math.logical_and",
sympy.Or: "tensorflow.math.logical_or",
sympy.Not: "tensorflow.math.logical_not",
sympy.Max: "tensorflow.math.maximum",
sympy.Min: "tensorflow.math.minimum",
# Matrices
sympy.MatAdd: "tensorflow.math.add",
sympy.HadamardProduct: "tensorflow.math.multiply",
sympy.Trace: "tensorflow.linalg.trace",
# XXX May raise error for integer matrices.
sympy.Determinant : "tensorflow.linalg.det",
}
_default_settings = dict(
AbstractPythonCodePrinter._default_settings,
tensorflow_version=None
)
def __init__(self, settings=None):
super().__init__(settings)
version = self._settings['tensorflow_version']
if version is None and tensorflow:
version = tensorflow.__version__
self.tensorflow_version = version
def _print_Function(self, expr):
op = self.mapping.get(type(expr), None)
if op is None:
return super()._print_Basic(expr)
children = [self._print(arg) for arg in expr.args]
if len(children) == 1:
return "%s(%s)" % (
self._module_format(op),
children[0]
)
else:
return self._expand_fold_binary_op(op, children)
_print_Expr = _print_Function
_print_Application = _print_Function
_print_MatrixExpr = _print_Function
# TODO: a better class structure would avoid this mess:
_print_Relational = _print_Function
_print_Not = _print_Function
_print_And = _print_Function
_print_Or = _print_Function
_print_HadamardProduct = _print_Function
_print_Trace = _print_Function
_print_Determinant = _print_Function
def _print_Inverse(self, expr):
op = self._module_format('tensorflow.linalg.inv')
return "{}({})".format(op, self._print(expr.arg))
def _print_Transpose(self, expr):
version = self.tensorflow_version
if version and version_tuple(version) < version_tuple('1.14'):
op = self._module_format('tensorflow.matrix_transpose')
else:
op = self._module_format('tensorflow.linalg.matrix_transpose')
return "{}({})".format(op, self._print(expr.arg))
def _print_Derivative(self, expr):
variables = expr.variables
if any(isinstance(i, Iterable) for i in variables):
raise NotImplementedError("derivation by multiple variables is not supported")
def unfold(expr, args):
if not args:
return self._print(expr)
return "%s(%s, %s)[0]" % (
self._module_format("tensorflow.gradients"),
unfold(expr, args[:-1]),
self._print(args[-1]),
)
return unfold(expr.expr, variables)
def _print_Piecewise(self, expr):
version = self.tensorflow_version
if version and version_tuple(version) < version_tuple('1.0'):
tensorflow_piecewise = "tensorflow.select"
else:
tensorflow_piecewise = "tensorflow.where"
from sympy.functions.elementary.piecewise import Piecewise
e, cond = expr.args[0].args
if len(expr.args) == 1:
return '{}({}, {}, {})'.format(
self._module_format(tensorflow_piecewise),
self._print(cond),
self._print(e),
0)
return '{}({}, {}, {})'.format(
self._module_format(tensorflow_piecewise),
self._print(cond),
self._print(e),
self._print(Piecewise(*expr.args[1:])))
def _print_Pow(self, expr):
# XXX May raise error for
# int**float or int**complex or float**complex
base, exp = expr.args
if expr.exp == S.Half:
return "{}({})".format(
self._module_format("tensorflow.math.sqrt"), self._print(base))
return "{}({}, {})".format(
self._module_format("tensorflow.math.pow"),
self._print(base), self._print(exp))
def _print_MatrixBase(self, expr):
tensorflow_f = "tensorflow.Variable" if expr.free_symbols else "tensorflow.constant"
data = "["+", ".join(["["+", ".join([self._print(j) for j in i])+"]" for i in expr.tolist()])+"]"
return "%s(%s)" % (
self._module_format(tensorflow_f),
data,
)
def _print_MatMul(self, expr):
from sympy.matrices.expressions import MatrixExpr
mat_args = [arg for arg in expr.args if isinstance(arg, MatrixExpr)]
args = [arg for arg in expr.args if arg not in mat_args]
if args:
return "%s*%s" % (
self.parenthesize(Mul.fromiter(args), PRECEDENCE["Mul"]),
self._expand_fold_binary_op(
"tensorflow.linalg.matmul", mat_args)
)
else:
return self._expand_fold_binary_op(
"tensorflow.linalg.matmul", mat_args)
def _print_MatPow(self, expr):
return self._expand_fold_binary_op(
"tensorflow.linalg.matmul", [expr.base]*expr.exp)
def _print_CodeBlock(self, expr):
# TODO: is this necessary?
ret = []
for subexpr in expr.args:
ret.append(self._print(subexpr))
return "\n".join(ret)
_module = "tensorflow"
_einsum = "linalg.einsum"
_add = "math.add"
_transpose = "transpose"
_ones = "ones"
_zeros = "zeros"
def tensorflow_code(expr, **settings):
printer = TensorflowPrinter(settings)
return printer.doprint(expr)
|
09f28108a3691b17ec7e0e57729250f0ce919aa279641087402f95c6e8997277 | from sympy.core.basic import Basic
from sympy.core.expr import Expr
from sympy.core.symbol import Symbol
from sympy.core.numbers import Integer, Rational, Float
from sympy.printing.repr import srepr
__all__ = ['dotprint']
default_styles = (
(Basic, {'color': 'blue', 'shape': 'ellipse'}),
(Expr, {'color': 'black'})
)
slotClasses = (Symbol, Integer, Rational, Float)
def purestr(x, with_args=False):
"""A string that follows ```obj = type(obj)(*obj.args)``` exactly.
Parameters
==========
with_args : boolean, optional
If ``True``, there will be a second argument for the return
value, which is a tuple containing ``purestr`` applied to each
of the subnodes.
If ``False``, there will not be a second argument for the
return.
Default is ``False``
Examples
========
>>> from sympy import Float, Symbol, MatrixSymbol
>>> from sympy import Integer # noqa: F401
>>> from sympy.core.symbol import Str # noqa: F401
>>> from sympy.printing.dot import purestr
Applying ``purestr`` for basic symbolic object:
>>> code = purestr(Symbol('x'))
>>> code
"Symbol('x')"
>>> eval(code) == Symbol('x')
True
For basic numeric object:
>>> purestr(Float(2))
"Float('2.0', precision=53)"
For matrix symbol:
>>> code = purestr(MatrixSymbol('x', 2, 2))
>>> code
"MatrixSymbol(Str('x'), Integer(2), Integer(2))"
>>> eval(code) == MatrixSymbol('x', 2, 2)
True
With ``with_args=True``:
>>> purestr(Float(2), with_args=True)
("Float('2.0', precision=53)", ())
>>> purestr(MatrixSymbol('x', 2, 2), with_args=True)
("MatrixSymbol(Str('x'), Integer(2), Integer(2))",
("Str('x')", 'Integer(2)', 'Integer(2)'))
"""
sargs = ()
if not isinstance(x, Basic):
rv = str(x)
elif not x.args:
rv = srepr(x)
else:
args = x.args
sargs = tuple(map(purestr, args))
rv = "%s(%s)"%(type(x).__name__, ', '.join(sargs))
if with_args:
rv = rv, sargs
return rv
def styleof(expr, styles=default_styles):
""" Merge style dictionaries in order
Examples
========
>>> from sympy import Symbol, Basic, Expr, S
>>> from sympy.printing.dot import styleof
>>> styles = [(Basic, {'color': 'blue', 'shape': 'ellipse'}),
... (Expr, {'color': 'black'})]
>>> styleof(Basic(S(1)), styles)
{'color': 'blue', 'shape': 'ellipse'}
>>> x = Symbol('x')
>>> styleof(x + 1, styles) # this is an Expr
{'color': 'black', 'shape': 'ellipse'}
"""
style = dict()
for typ, sty in styles:
if isinstance(expr, typ):
style.update(sty)
return style
def attrprint(d, delimiter=', '):
""" Print a dictionary of attributes
Examples
========
>>> from sympy.printing.dot import attrprint
>>> print(attrprint({'color': 'blue', 'shape': 'ellipse'}))
"color"="blue", "shape"="ellipse"
"""
return delimiter.join('"%s"="%s"'%item for item in sorted(d.items()))
def dotnode(expr, styles=default_styles, labelfunc=str, pos=(), repeat=True):
""" String defining a node
Examples
========
>>> from sympy.printing.dot import dotnode
>>> from sympy.abc import x
>>> print(dotnode(x))
"Symbol('x')_()" ["color"="black", "label"="x", "shape"="ellipse"];
"""
style = styleof(expr, styles)
if isinstance(expr, Basic) and not expr.is_Atom:
label = str(expr.__class__.__name__)
else:
label = labelfunc(expr)
style['label'] = label
expr_str = purestr(expr)
if repeat:
expr_str += '_%s' % str(pos)
return '"%s" [%s];' % (expr_str, attrprint(style))
def dotedges(expr, atom=lambda x: not isinstance(x, Basic), pos=(), repeat=True):
""" List of strings for all expr->expr.arg pairs
See the docstring of dotprint for explanations of the options.
Examples
========
>>> from sympy.printing.dot import dotedges
>>> from sympy.abc import x
>>> for e in dotedges(x+2):
... print(e)
"Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)";
"Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)";
"""
if atom(expr):
return []
else:
expr_str, arg_strs = purestr(expr, with_args=True)
if repeat:
expr_str += '_%s' % str(pos)
arg_strs = ['%s_%s' % (a, str(pos + (i,)))
for i, a in enumerate(arg_strs)]
return ['"%s" -> "%s";' % (expr_str, a) for a in arg_strs]
template = \
"""digraph{
# Graph style
%(graphstyle)s
#########
# Nodes #
#########
%(nodes)s
#########
# Edges #
#########
%(edges)s
}"""
_graphstyle = {'rankdir': 'TD', 'ordering': 'out'}
def dotprint(expr,
styles=default_styles, atom=lambda x: not isinstance(x, Basic),
maxdepth=None, repeat=True, labelfunc=str, **kwargs):
"""DOT description of a SymPy expression tree
Parameters
==========
styles : list of lists composed of (Class, mapping), optional
Styles for different classes.
The default is
.. code-block:: python
(
(Basic, {'color': 'blue', 'shape': 'ellipse'}),
(Expr, {'color': 'black'})
)
atom : function, optional
Function used to determine if an arg is an atom.
A good choice is ``lambda x: not x.args``.
The default is ``lambda x: not isinstance(x, Basic)``.
maxdepth : integer, optional
The maximum depth.
The default is ``None``, meaning no limit.
repeat : boolean, optional
Whether to use different nodes for common subexpressions.
The default is ``True``.
For example, for ``x + x*y`` with ``repeat=True``, it will have
two nodes for ``x``; with ``repeat=False``, it will have one
node.
.. warning::
Even if a node appears twice in the same object like ``x`` in
``Pow(x, x)``, it will still only appear once.
Hence, with ``repeat=False``, the number of arrows out of an
object might not equal the number of args it has.
labelfunc : function, optional
A function to create a label for a given leaf node.
The default is ``str``.
Another good option is ``srepr``.
For example with ``str``, the leaf nodes of ``x + 1`` are labeled,
``x`` and ``1``. With ``srepr``, they are labeled ``Symbol('x')``
and ``Integer(1)``.
**kwargs : optional
Additional keyword arguments are included as styles for the graph.
Examples
========
>>> from sympy import dotprint
>>> from sympy.abc import x
>>> print(dotprint(x+2)) # doctest: +NORMALIZE_WHITESPACE
digraph{
<BLANKLINE>
# Graph style
"ordering"="out"
"rankdir"="TD"
<BLANKLINE>
#########
# Nodes #
#########
<BLANKLINE>
"Add(Integer(2), Symbol('x'))_()" ["color"="black", "label"="Add", "shape"="ellipse"];
"Integer(2)_(0,)" ["color"="black", "label"="2", "shape"="ellipse"];
"Symbol('x')_(1,)" ["color"="black", "label"="x", "shape"="ellipse"];
<BLANKLINE>
#########
# Edges #
#########
<BLANKLINE>
"Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)";
"Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)";
}
"""
# repeat works by adding a signature tuple to the end of each node for its
# position in the graph. For example, for expr = Add(x, Pow(x, 2)), the x in the
# Pow will have the tuple (1, 0), meaning it is expr.args[1].args[0].
graphstyle = _graphstyle.copy()
graphstyle.update(kwargs)
nodes = []
edges = []
def traverse(e, depth, pos=()):
nodes.append(dotnode(e, styles, labelfunc=labelfunc, pos=pos, repeat=repeat))
if maxdepth and depth >= maxdepth:
return
edges.extend(dotedges(e, atom=atom, pos=pos, repeat=repeat))
[traverse(arg, depth+1, pos + (i,)) for i, arg in enumerate(e.args) if not atom(arg)]
traverse(expr, 0)
return template%{'graphstyle': attrprint(graphstyle, delimiter='\n'),
'nodes': '\n'.join(nodes),
'edges': '\n'.join(edges)}
|
ca31c0d1704e1af31e37493414dea668d00bae04abe9562e6629a7037650af9f | """
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 as tDict
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: tDict[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 sympy_deprecation_warning
perm_cyclic = Permutation.print_cyclic
if perm_cyclic is not None:
sympy_deprecation_warning(
f"""
Setting Permutation.print_cyclic is deprecated. Instead use
init_printing(perm_cyclic={perm_cyclic}).
""",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-permutation-print_cyclic",
stacklevel=7,
)
else:
perm_cyclic = self._settings.get("perm_cyclic", True)
if perm_cyclic:
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_Heaviside(self, expr):
# Same as _print_Function but uses pargs to suppress default value for
# 2nd arg.
r = self._print(expr.func)
r += '(%s)' % ', '.join([self._print(a) for a in expr.pargs])
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_Complexes(self, expr):
return 'Complexes'
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_EmptySet(self, expr):
return 'EmptySet'
def _print_UniversalSet(self, expr):
return 'UniversalSet'
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)
|
93999fb149fa2a73456fe699bb18264a8657366d447ffb1ab295e7d66f369d7c | """
.. deprecated:: 1.8
``sympy.printing.theanocode`` is deprecated. Theano has been renamed to
Aesara. Use ``sympy.printing.aesaracode`` instead. See
:ref:`theanocode-deprecated` for more information.
"""
from typing import Any, Dict as tDict
from sympy.external import import_module
from sympy.printing.printer import Printer
from sympy.utilities.iterables import is_sequence
import sympy
from functools import partial
from sympy.utilities.decorator import doctest_depends_on
from sympy.utilities.exceptions import sympy_deprecation_warning
theano = import_module('theano')
if theano:
ts = theano.scalar
tt = theano.tensor
from theano.sandbox import linalg as tlinalg
mapping = {
sympy.Add: tt.add,
sympy.Mul: tt.mul,
sympy.Abs: tt.abs_,
sympy.sign: tt.sgn,
sympy.ceiling: tt.ceil,
sympy.floor: tt.floor,
sympy.log: tt.log,
sympy.exp: tt.exp,
sympy.sqrt: tt.sqrt,
sympy.cos: tt.cos,
sympy.acos: tt.arccos,
sympy.sin: tt.sin,
sympy.asin: tt.arcsin,
sympy.tan: tt.tan,
sympy.atan: tt.arctan,
sympy.atan2: tt.arctan2,
sympy.cosh: tt.cosh,
sympy.acosh: tt.arccosh,
sympy.sinh: tt.sinh,
sympy.asinh: tt.arcsinh,
sympy.tanh: tt.tanh,
sympy.atanh: tt.arctanh,
sympy.re: tt.real,
sympy.im: tt.imag,
sympy.arg: tt.angle,
sympy.erf: tt.erf,
sympy.gamma: tt.gamma,
sympy.loggamma: tt.gammaln,
sympy.Pow: tt.pow,
sympy.Eq: tt.eq,
sympy.StrictGreaterThan: tt.gt,
sympy.StrictLessThan: tt.lt,
sympy.LessThan: tt.le,
sympy.GreaterThan: tt.ge,
sympy.And: tt.and_,
sympy.Or: tt.or_,
sympy.Max: tt.maximum, # SymPy accept >2 inputs, Theano only 2
sympy.Min: tt.minimum, # SymPy accept >2 inputs, Theano only 2
sympy.conjugate: tt.conj,
sympy.core.numbers.ImaginaryUnit: lambda:tt.complex(0,1),
# Matrices
sympy.MatAdd: tt.Elemwise(ts.add),
sympy.HadamardProduct: tt.Elemwise(ts.mul),
sympy.Trace: tlinalg.trace,
sympy.Determinant : tlinalg.det,
sympy.Inverse: tlinalg.matrix_inverse,
sympy.Transpose: tt.DimShuffle((False, False), [1, 0]),
}
class TheanoPrinter(Printer):
""" Code printer which creates Theano symbolic expression graphs.
Parameters
==========
cache : dict
Cache dictionary to use. If None (default) will use
the global cache. To create a printer which does not depend on or alter
global state pass an empty dictionary. Note: the dictionary is not
copied on initialization of the printer and will be updated in-place,
so using the same dict object when creating multiple printers or making
multiple calls to :func:`.theano_code` or :func:`.theano_function` means
the cache is shared between all these applications.
Attributes
==========
cache : dict
A cache of Theano variables which have been created for SymPy
symbol-like objects (e.g. :class:`sympy.core.symbol.Symbol` or
:class:`sympy.matrices.expressions.MatrixSymbol`). This is used to
ensure that all references to a given symbol in an expression (or
multiple expressions) are printed as the same Theano variable, which is
created only once. Symbols are differentiated only by name and type. The
format of the cache's contents should be considered opaque to the user.
"""
printmethod = "_theano"
def __init__(self, *args, **kwargs):
self.cache = kwargs.pop('cache', dict())
super().__init__(*args, **kwargs)
def _get_key(self, s, name=None, dtype=None, broadcastable=None):
""" Get the cache key for a SymPy object.
Parameters
==========
s : sympy.core.basic.Basic
SymPy object to get key for.
name : str
Name of object, if it does not have a ``name`` attribute.
"""
if name is None:
name = s.name
return (name, type(s), s.args, dtype, broadcastable)
def _get_or_create(self, s, name=None, dtype=None, broadcastable=None):
"""
Get the Theano variable for a SymPy symbol from the cache, or create it
if it does not exist.
"""
# Defaults
if name is None:
name = s.name
if dtype is None:
dtype = 'floatX'
if broadcastable is None:
broadcastable = ()
key = self._get_key(s, name, dtype=dtype, broadcastable=broadcastable)
if key in self.cache:
return self.cache[key]
value = tt.tensor(name=name, dtype=dtype, broadcastable=broadcastable)
self.cache[key] = value
return value
def _print_Symbol(self, s, **kwargs):
dtype = kwargs.get('dtypes', {}).get(s)
bc = kwargs.get('broadcastables', {}).get(s)
return self._get_or_create(s, dtype=dtype, broadcastable=bc)
def _print_AppliedUndef(self, s, **kwargs):
name = str(type(s)) + '_' + str(s.args[0])
dtype = kwargs.get('dtypes', {}).get(s)
bc = kwargs.get('broadcastables', {}).get(s)
return self._get_or_create(s, name=name, dtype=dtype, broadcastable=bc)
def _print_Basic(self, expr, **kwargs):
op = mapping[type(expr)]
children = [self._print(arg, **kwargs) for arg in expr.args]
return op(*children)
def _print_Number(self, n, **kwargs):
# Integers already taken care of below, interpret as float
return float(n.evalf())
def _print_MatrixSymbol(self, X, **kwargs):
dtype = kwargs.get('dtypes', {}).get(X)
return self._get_or_create(X, dtype=dtype, broadcastable=(None, None))
def _print_DenseMatrix(self, X, **kwargs):
if not hasattr(tt, 'stacklists'):
raise NotImplementedError(
"Matrix translation not yet supported in this version of Theano")
return tt.stacklists([
[self._print(arg, **kwargs) for arg in L]
for L in X.tolist()
])
_print_ImmutableMatrix = _print_ImmutableDenseMatrix = _print_DenseMatrix
def _print_MatMul(self, expr, **kwargs):
children = [self._print(arg, **kwargs) for arg in expr.args]
result = children[0]
for child in children[1:]:
result = tt.dot(result, child)
return result
def _print_MatPow(self, expr, **kwargs):
children = [self._print(arg, **kwargs) for arg in expr.args]
result = 1
if isinstance(children[1], int) and children[1] > 0:
for i in range(children[1]):
result = tt.dot(result, children[0])
else:
raise NotImplementedError('''Only non-negative integer
powers of matrices can be handled by Theano at the moment''')
return result
def _print_MatrixSlice(self, expr, **kwargs):
parent = self._print(expr.parent, **kwargs)
rowslice = self._print(slice(*expr.rowslice), **kwargs)
colslice = self._print(slice(*expr.colslice), **kwargs)
return parent[rowslice, colslice]
def _print_BlockMatrix(self, expr, **kwargs):
nrows, ncols = expr.blocks.shape
blocks = [[self._print(expr.blocks[r, c], **kwargs)
for c in range(ncols)]
for r in range(nrows)]
return tt.join(0, *[tt.join(1, *row) for row in blocks])
def _print_slice(self, expr, **kwargs):
return slice(*[self._print(i, **kwargs)
if isinstance(i, sympy.Basic) else i
for i in (expr.start, expr.stop, expr.step)])
def _print_Pi(self, expr, **kwargs):
return 3.141592653589793
def _print_Exp1(self, expr, **kwargs):
return ts.exp(1)
def _print_Piecewise(self, expr, **kwargs):
import numpy as np
e, cond = expr.args[0].args # First condition and corresponding value
# Print conditional expression and value for first condition
p_cond = self._print(cond, **kwargs)
p_e = self._print(e, **kwargs)
# One condition only
if len(expr.args) == 1:
# Return value if condition else NaN
return tt.switch(p_cond, p_e, np.nan)
# Return value_1 if condition_1 else evaluate remaining conditions
p_remaining = self._print(sympy.Piecewise(*expr.args[1:]), **kwargs)
return tt.switch(p_cond, p_e, p_remaining)
def _print_Rational(self, expr, **kwargs):
return tt.true_div(self._print(expr.p, **kwargs),
self._print(expr.q, **kwargs))
def _print_Integer(self, expr, **kwargs):
return expr.p
def _print_factorial(self, expr, **kwargs):
return self._print(sympy.gamma(expr.args[0] + 1), **kwargs)
def _print_Derivative(self, deriv, **kwargs):
rv = self._print(deriv.expr, **kwargs)
for var in deriv.variables:
var = self._print(var, **kwargs)
rv = tt.Rop(rv, var, tt.ones_like(var))
return rv
def emptyPrinter(self, expr):
return expr
def doprint(self, expr, dtypes=None, broadcastables=None):
""" Convert a SymPy expression to a Theano graph variable.
The ``dtypes`` and ``broadcastables`` arguments are used to specify the
data type, dimension, and broadcasting behavior of the Theano variables
corresponding to the free symbols in ``expr``. Each is a mapping from
SymPy symbols to the value of the corresponding argument to
``theano.tensor.Tensor``.
See the corresponding `documentation page`__ for more information on
broadcasting in Theano.
.. __: http://deeplearning.net/software/theano/tutorial/broadcasting.html
Parameters
==========
expr : sympy.core.expr.Expr
SymPy expression to print.
dtypes : dict
Mapping from SymPy symbols to Theano datatypes to use when creating
new Theano variables for those symbols. Corresponds to the ``dtype``
argument to ``theano.tensor.Tensor``. Defaults to ``'floatX'``
for symbols not included in the mapping.
broadcastables : dict
Mapping from SymPy symbols to the value of the ``broadcastable``
argument to ``theano.tensor.Tensor`` to use when creating Theano
variables for those symbols. Defaults to the empty tuple for symbols
not included in the mapping (resulting in a scalar).
Returns
=======
theano.gof.graph.Variable
A variable corresponding to the expression's value in a Theano
symbolic expression graph.
"""
if dtypes is None:
dtypes = {}
if broadcastables is None:
broadcastables = {}
return self._print(expr, dtypes=dtypes, broadcastables=broadcastables)
global_cache = {} # type: tDict[Any, Any]
def theano_code(expr, cache=None, **kwargs):
"""
Convert a SymPy expression into a Theano graph variable.
.. deprecated:: 1.8
``sympy.printing.theanocode`` is deprecated. Theano has been renamed to
Aesara. Use ``sympy.printing.aesaracode`` instead. See
:ref:`theanocode-deprecated` for more information.
Parameters
==========
expr : sympy.core.expr.Expr
SymPy expression object to convert.
cache : dict
Cached Theano variables (see :class:`TheanoPrinter.cache
<TheanoPrinter>`). Defaults to the module-level global cache.
dtypes : dict
Passed to :meth:`.TheanoPrinter.doprint`.
broadcastables : dict
Passed to :meth:`.TheanoPrinter.doprint`.
Returns
=======
theano.gof.graph.Variable
A variable corresponding to the expression's value in a Theano symbolic
expression graph.
"""
sympy_deprecation_warning(
"""
sympy.printing.theanocode is deprecated. Theano has been renamed to
Aesara. Use sympy.printing.aesaracode instead.""",
deprecated_since_version="1.8",
active_deprecations_target='theanocode-deprecated')
if not theano:
raise ImportError("theano is required for theano_code")
if cache is None:
cache = global_cache
return TheanoPrinter(cache=cache, settings={}).doprint(expr, **kwargs)
def dim_handling(inputs, dim=None, dims=None, broadcastables=None):
r"""
Get value of ``broadcastables`` argument to :func:`.theano_code` from
keyword arguments to :func:`.theano_function`.
Included for backwards compatibility.
Parameters
==========
inputs
Sequence of input symbols.
dim : int
Common number of dimensions for all inputs. Overrides other arguments
if given.
dims : dict
Mapping from input symbols to number of dimensions. Overrides
``broadcastables`` argument if given.
broadcastables : dict
Explicit value of ``broadcastables`` argument to
:meth:`.TheanoPrinter.doprint`. If not None function will return this value unchanged.
Returns
=======
dict
Dictionary mapping elements of ``inputs`` to their "broadcastable"
values (tuple of ``bool``\ s).
"""
if dim is not None:
return {s: (False,) * dim for s in inputs}
if dims is not None:
maxdim = max(dims.values())
return {
s: (False,) * d + (True,) * (maxdim - d)
for s, d in dims.items()
}
if broadcastables is not None:
return broadcastables
return {}
@doctest_depends_on(modules=('theano',))
def theano_function(inputs, outputs, scalar=False, *,
dim=None, dims=None, broadcastables=None, **kwargs):
"""
Create a Theano function from SymPy expressions.
.. deprecated:: 1.8
``sympy.printing.theanocode`` is deprecated. Theano has been renamed to
Aesara. Use ``sympy.printing.aesaracode`` instead. See
:ref:`theanocode-deprecated` for more information.
The inputs and outputs are converted to Theano variables using
:func:`.theano_code` and then passed to ``theano.function``.
Parameters
==========
inputs
Sequence of symbols which constitute the inputs of the function.
outputs
Sequence of expressions which constitute the outputs(s) of the
function. The free symbols of each expression must be a subset of
``inputs``.
scalar : bool
Convert 0-dimensional arrays in output to scalars. This will return a
Python wrapper function around the Theano function object.
cache : dict
Cached Theano variables (see :class:`TheanoPrinter.cache
<TheanoPrinter>`). Defaults to the module-level global cache.
dtypes : dict
Passed to :meth:`.TheanoPrinter.doprint`.
broadcastables : dict
Passed to :meth:`.TheanoPrinter.doprint`.
dims : dict
Alternative to ``broadcastables`` argument. Mapping from elements of
``inputs`` to integers indicating the dimension of their associated
arrays/tensors. Overrides ``broadcastables`` argument if given.
dim : int
Another alternative to the ``broadcastables`` argument. Common number of
dimensions to use for all arrays/tensors.
``theano_function([x, y], [...], dim=2)`` is equivalent to using
``broadcastables={x: (False, False), y: (False, False)}``.
Returns
=======
callable
A callable object which takes values of ``inputs`` as positional
arguments and returns an output array for each of the expressions
in ``outputs``. If ``outputs`` is a single expression the function will
return a Numpy array, if it is a list of multiple expressions the
function will return a list of arrays. See description of the ``squeeze``
argument above for the behavior when a single output is passed in a list.
The returned object will either be an instance of
``theano.compile.function_module.Function`` or a Python wrapper
function around one. In both cases, the returned value will have a
``theano_function`` attribute which points to the return value of
``theano.function``.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.printing.theanocode import theano_function
A simple function with one input and one output:
>>> f1 = theano_function([x], [x**2 - 1], scalar=True)
>>> f1(3)
8.0
A function with multiple inputs and one output:
>>> f2 = theano_function([x, y, z], [(x**z + y**z)**(1/z)], scalar=True)
>>> f2(3, 4, 2)
5.0
A function with multiple inputs and multiple outputs:
>>> f3 = theano_function([x, y], [x**2 + y**2, x**2 - y**2], scalar=True)
>>> f3(2, 3)
[13.0, -5.0]
See also
========
dim_handling
"""
sympy_deprecation_warning(
"""
sympy.printing.theanocode is deprecated. Theano has been renamed to Aesara. Use sympy.printing.aesaracode instead""",
deprecated_since_version="1.8",
active_deprecations_target='theanocode-deprecated')
if not theano:
raise ImportError("theano is required for theano_function")
# Pop off non-theano keyword args
cache = kwargs.pop('cache', {})
dtypes = kwargs.pop('dtypes', {})
broadcastables = dim_handling(
inputs, dim=dim, dims=dims, broadcastables=broadcastables,
)
# Print inputs/outputs
code = partial(theano_code, cache=cache, dtypes=dtypes,
broadcastables=broadcastables)
tinputs = list(map(code, inputs))
toutputs = list(map(code, outputs))
#fix constant expressions as variables
toutputs = [output if isinstance(output, theano.Variable) else tt.as_tensor_variable(output) for output in toutputs]
if len(toutputs) == 1:
toutputs = toutputs[0]
# Compile theano func
func = theano.function(tinputs, toutputs, **kwargs)
is_0d = [len(o.variable.broadcastable) == 0 for o in func.outputs]
# No wrapper required
if not scalar or not any(is_0d):
func.theano_function = func
return func
# Create wrapper to convert 0-dimensional outputs to scalars
def wrapper(*args):
out = func(*args)
# out can be array(1.0) or [array(1.0), array(2.0)]
if is_sequence(out):
return [o[()] if is_0d[i] else o for i, o in enumerate(out)]
else:
return out[()]
wrapper.__wrapped__ = func
wrapper.__doc__ = func.__doc__
wrapper.theano_function = func
return wrapper
|
3903cfd375b52d86ebcdcaff55ac04256fccd4037079bcfbc72b736a0e5c7ccc | """Integration method that emulates by-hand techniques.
This module also provides functionality to get the steps used to evaluate a
particular integral, in the ``integral_steps`` function. This will return
nested namedtuples representing the integration rules used. The
``manualintegrate`` function computes the integral using those steps given
an integrand; given the steps, ``_manualintegrate`` will evaluate them.
The integrator can be extended with new heuristics and evaluation
techniques. To do so, write a function that accepts an ``IntegralInfo``
object and returns either a namedtuple representing a rule or
``None``. Then, write another function that accepts the namedtuple's fields
and returns the antiderivative, and decorate it with
``@evaluates(namedtuple_type)``. If the new technique requires a new
match, add the key and call to the antiderivative function to integral_steps.
To enable simple substitutions, add the match to find_substitutions.
"""
from typing import Dict as tDict, Optional
from collections import namedtuple, defaultdict
from collections.abc import Mapping
from functools import reduce
from sympy.core.add import Add
from sympy.core.cache import cacheit
from sympy.core.containers import Dict
from sympy.core.expr import Expr
from sympy.core.function import Derivative
from sympy.core.logic import fuzzy_not
from sympy.core.mul import Mul
from sympy.core.numbers import Integer, Number, E
from sympy.core.power import Pow
from sympy.core.relational import Eq, Ne, Gt, Lt
from sympy.core.singleton import S
from sympy.core.symbol import Dummy, Symbol, Wild
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.hyperbolic import (cosh, sinh, acosh, asinh,
acoth, atanh)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (TrigonometricFunction,
cos, sin, tan, cot, csc, sec, acos, asin, atan, acot, acsc, asec)
from sympy.functions.special.delta_functions import Heaviside
from sympy.functions.special.error_functions import (erf, erfi, fresnelc,
fresnels, Ci, Chi, Si, Shi, Ei, li)
from sympy.functions.special.gamma_functions import uppergamma
from sympy.functions.special.elliptic_integrals import elliptic_e, elliptic_f
from sympy.functions.special.polynomials import (chebyshevt, chebyshevu,
legendre, hermite, laguerre, assoc_laguerre, gegenbauer, jacobi,
OrthogonalPolynomial)
from sympy.functions.special.zeta_functions import polylog
from .integrals import Integral
from sympy.logic.boolalg import And
from sympy.ntheory.factor_ import divisors
from sympy.polys.polytools import degree
from sympy.simplify.radsimp import fraction
from sympy.simplify.simplify import simplify
from sympy.solvers.solvers import solve
from sympy.strategies.core import switch, do_one, null_safe, condition
from sympy.utilities.iterables import iterable
from sympy.utilities.misc import debug
def Rule(name, props=""):
# GOTCHA: namedtuple class name not considered!
def __eq__(self, other):
return self.__class__ == other.__class__ and tuple.__eq__(self, other)
__neq__ = lambda self, other: not __eq__(self, other)
cls = namedtuple(name, props + " context symbol")
cls.__eq__ = __eq__
cls.__ne__ = __neq__
return cls
ConstantRule = Rule("ConstantRule", "constant")
ConstantTimesRule = Rule("ConstantTimesRule", "constant other substep")
PowerRule = Rule("PowerRule", "base exp")
AddRule = Rule("AddRule", "substeps")
URule = Rule("URule", "u_var u_func constant substep")
PartsRule = Rule("PartsRule", "u dv v_step second_step")
CyclicPartsRule = Rule("CyclicPartsRule", "parts_rules coefficient")
TrigRule = Rule("TrigRule", "func arg")
ExpRule = Rule("ExpRule", "base exp")
ReciprocalRule = Rule("ReciprocalRule", "func")
ArcsinRule = Rule("ArcsinRule")
InverseHyperbolicRule = Rule("InverseHyperbolicRule", "func")
AlternativeRule = Rule("AlternativeRule", "alternatives")
DontKnowRule = Rule("DontKnowRule")
DerivativeRule = Rule("DerivativeRule")
RewriteRule = Rule("RewriteRule", "rewritten substep")
PiecewiseRule = Rule("PiecewiseRule", "subfunctions")
HeavisideRule = Rule("HeavisideRule", "harg ibnd substep")
TrigSubstitutionRule = Rule("TrigSubstitutionRule",
"theta func rewritten substep restriction")
ArctanRule = Rule("ArctanRule", "a b c")
ArccothRule = Rule("ArccothRule", "a b c")
ArctanhRule = Rule("ArctanhRule", "a b c")
JacobiRule = Rule("JacobiRule", "n a b")
GegenbauerRule = Rule("GegenbauerRule", "n a")
ChebyshevTRule = Rule("ChebyshevTRule", "n")
ChebyshevURule = Rule("ChebyshevURule", "n")
LegendreRule = Rule("LegendreRule", "n")
HermiteRule = Rule("HermiteRule", "n")
LaguerreRule = Rule("LaguerreRule", "n")
AssocLaguerreRule = Rule("AssocLaguerreRule", "n a")
CiRule = Rule("CiRule", "a b")
ChiRule = Rule("ChiRule", "a b")
EiRule = Rule("EiRule", "a b")
SiRule = Rule("SiRule", "a b")
ShiRule = Rule("ShiRule", "a b")
ErfRule = Rule("ErfRule", "a b c")
FresnelCRule = Rule("FresnelCRule", "a b c")
FresnelSRule = Rule("FresnelSRule", "a b c")
LiRule = Rule("LiRule", "a b")
PolylogRule = Rule("PolylogRule", "a b")
UpperGammaRule = Rule("UpperGammaRule", "a e")
EllipticFRule = Rule("EllipticFRule", "a d")
EllipticERule = Rule("EllipticERule", "a d")
IntegralInfo = namedtuple('IntegralInfo', 'integrand symbol')
evaluators = {}
def evaluates(rule):
def _evaluates(func):
func.rule = rule
evaluators[rule] = func
return func
return _evaluates
def contains_dont_know(rule):
if isinstance(rule, DontKnowRule):
return True
else:
for val in rule:
if isinstance(val, tuple):
if contains_dont_know(val):
return True
elif isinstance(val, list):
if any(contains_dont_know(i) for i in val):
return True
return False
def manual_diff(f, symbol):
"""Derivative of f in form expected by find_substitutions
SymPy's derivatives for some trig functions (like cot) are not in a form
that works well with finding substitutions; this replaces the
derivatives for those particular forms with something that works better.
"""
if f.args:
arg = f.args[0]
if isinstance(f, tan):
return arg.diff(symbol) * sec(arg)**2
elif isinstance(f, cot):
return -arg.diff(symbol) * csc(arg)**2
elif isinstance(f, sec):
return arg.diff(symbol) * sec(arg) * tan(arg)
elif isinstance(f, csc):
return -arg.diff(symbol) * csc(arg) * cot(arg)
elif isinstance(f, Add):
return sum([manual_diff(arg, symbol) for arg in f.args])
elif isinstance(f, Mul):
if len(f.args) == 2 and isinstance(f.args[0], Number):
return f.args[0] * manual_diff(f.args[1], symbol)
return f.diff(symbol)
def manual_subs(expr, *args):
"""
A wrapper for `expr.subs(*args)` with additional logic for substitution
of invertible functions.
"""
if len(args) == 1:
sequence = args[0]
if isinstance(sequence, (Dict, Mapping)):
sequence = sequence.items()
elif not iterable(sequence):
raise ValueError("Expected an iterable of (old, new) pairs")
elif len(args) == 2:
sequence = [args]
else:
raise ValueError("subs accepts either 1 or 2 arguments")
new_subs = []
for old, new in sequence:
if isinstance(old, log):
# If log(x) = y, then exp(a*log(x)) = exp(a*y)
# that is, x**a = exp(a*y). Replace nontrivial powers of x
# before subs turns them into `exp(y)**a`, but
# do not replace x itself yet, to avoid `log(exp(y))`.
x0 = old.args[0]
expr = expr.replace(lambda x: x.is_Pow and x.base == x0,
lambda x: exp(x.exp*new))
new_subs.append((x0, exp(new)))
return expr.subs(list(sequence) + new_subs)
# Method based on that on SIN, described in "Symbolic Integration: The
# Stormy Decade"
inverse_trig_functions = (atan, asin, acos, acot, acsc, asec)
def find_substitutions(integrand, symbol, u_var):
results = []
def test_subterm(u, u_diff):
if u_diff == 0:
return False
substituted = integrand / u_diff
if symbol not in substituted.free_symbols:
# replaced everything already
return False
debug("substituted: {}, u: {}, u_var: {}".format(substituted, u, u_var))
substituted = manual_subs(substituted, u, u_var).cancel()
if symbol not in substituted.free_symbols:
# avoid increasing the degree of a rational function
if integrand.is_rational_function(symbol) and substituted.is_rational_function(u_var):
deg_before = max([degree(t, symbol) for t in integrand.as_numer_denom()])
deg_after = max([degree(t, u_var) for t in substituted.as_numer_denom()])
if deg_after > deg_before:
return False
return substituted.as_independent(u_var, as_Add=False)
# special treatment for substitutions u = (a*x+b)**(1/n)
if (isinstance(u, Pow) and (1/u.exp).is_Integer and
Abs(u.exp) < 1):
a = Wild('a', exclude=[symbol])
b = Wild('b', exclude=[symbol])
match = u.base.match(a*symbol + b)
if match:
a, b = [match.get(i, S.Zero) for i in (a, b)]
if a != 0 and b != 0:
substituted = substituted.subs(symbol,
(u_var**(1/u.exp) - b)/a)
return substituted.as_independent(u_var, as_Add=False)
return False
def possible_subterms(term):
if isinstance(term, (TrigonometricFunction,
*inverse_trig_functions,
exp, log, Heaviside)):
return [term.args[0]]
elif isinstance(term, (chebyshevt, chebyshevu,
legendre, hermite, laguerre)):
return [term.args[1]]
elif isinstance(term, (gegenbauer, assoc_laguerre)):
return [term.args[2]]
elif isinstance(term, jacobi):
return [term.args[3]]
elif isinstance(term, Mul):
r = []
for u in term.args:
r.append(u)
r.extend(possible_subterms(u))
return r
elif isinstance(term, Pow):
r = []
if term.args[1].is_constant(symbol):
r.append(term.args[0])
elif term.args[0].is_constant(symbol):
r.append(term.args[1])
if term.args[1].is_Integer:
r.extend([term.args[0]**d for d in divisors(term.args[1])
if 1 < d < abs(term.args[1])])
if term.args[0].is_Add:
r.extend([t for t in possible_subterms(term.args[0])
if t.is_Pow])
return r
elif isinstance(term, Add):
r = []
for arg in term.args:
r.append(arg)
r.extend(possible_subterms(arg))
return r
return []
for u in possible_subterms(integrand):
if u == symbol:
continue
u_diff = manual_diff(u, symbol)
new_integrand = test_subterm(u, u_diff)
if new_integrand is not False:
constant, new_integrand = new_integrand
if new_integrand == integrand.subs(symbol, u_var):
continue
substitution = (u, constant, new_integrand)
if substitution not in results:
results.append(substitution)
return results
def rewriter(condition, rewrite):
"""Strategy that rewrites an integrand."""
def _rewriter(integral):
integrand, symbol = integral
debug("Integral: {} is rewritten with {} on symbol: {}".format(integrand, rewrite, symbol))
if condition(*integral):
rewritten = rewrite(*integral)
if rewritten != integrand:
substep = integral_steps(rewritten, symbol)
if not isinstance(substep, DontKnowRule) and substep:
return RewriteRule(
rewritten,
substep,
integrand, symbol)
return _rewriter
def proxy_rewriter(condition, rewrite):
"""Strategy that rewrites an integrand based on some other criteria."""
def _proxy_rewriter(criteria):
criteria, integral = criteria
integrand, symbol = integral
debug("Integral: {} is rewritten with {} on symbol: {} and criteria: {}".format(integrand, rewrite, symbol, criteria))
args = criteria + list(integral)
if condition(*args):
rewritten = rewrite(*args)
if rewritten != integrand:
return RewriteRule(
rewritten,
integral_steps(rewritten, symbol),
integrand, symbol)
return _proxy_rewriter
def multiplexer(conditions):
"""Apply the rule that matches the condition, else None"""
def multiplexer_rl(expr):
for key, rule in conditions.items():
if key(expr):
return rule(expr)
return multiplexer_rl
def alternatives(*rules):
"""Strategy that makes an AlternativeRule out of multiple possible results."""
def _alternatives(integral):
alts = []
count = 0
debug("List of Alternative Rules")
for rule in rules:
count = count + 1
debug("Rule {}: {}".format(count, rule))
result = rule(integral)
if (result and not isinstance(result, DontKnowRule) and
result != integral and result not in alts):
alts.append(result)
if len(alts) == 1:
return alts[0]
elif alts:
doable = [rule for rule in alts if not contains_dont_know(rule)]
if doable:
return AlternativeRule(doable, *integral)
else:
return AlternativeRule(alts, *integral)
return _alternatives
def constant_rule(integral):
return ConstantRule(integral.integrand, *integral)
def power_rule(integral):
integrand, symbol = integral
base, expt = integrand.as_base_exp()
if symbol not in expt.free_symbols and isinstance(base, Symbol):
if simplify(expt + 1) == 0:
return ReciprocalRule(base, integrand, symbol)
return PowerRule(base, expt, integrand, symbol)
elif symbol not in base.free_symbols and isinstance(expt, Symbol):
rule = ExpRule(base, expt, integrand, symbol)
if fuzzy_not(log(base).is_zero):
return rule
elif log(base).is_zero:
return ConstantRule(1, 1, symbol)
return PiecewiseRule([
(rule, Ne(log(base), 0)),
(ConstantRule(1, 1, symbol), True)
], integrand, symbol)
def exp_rule(integral):
integrand, symbol = integral
if isinstance(integrand.args[0], Symbol):
return ExpRule(E, integrand.args[0], integrand, symbol)
def orthogonal_poly_rule(integral):
orthogonal_poly_classes = {
jacobi: JacobiRule,
gegenbauer: GegenbauerRule,
chebyshevt: ChebyshevTRule,
chebyshevu: ChebyshevURule,
legendre: LegendreRule,
hermite: HermiteRule,
laguerre: LaguerreRule,
assoc_laguerre: AssocLaguerreRule
}
orthogonal_poly_var_index = {
jacobi: 3,
gegenbauer: 2,
assoc_laguerre: 2
}
integrand, symbol = integral
for klass in orthogonal_poly_classes:
if isinstance(integrand, klass):
var_index = orthogonal_poly_var_index.get(klass, 1)
if (integrand.args[var_index] is symbol and not
any(v.has(symbol) for v in integrand.args[:var_index])):
args = integrand.args[:var_index] + (integrand, symbol)
return orthogonal_poly_classes[klass](*args)
def special_function_rule(integral):
integrand, symbol = integral
a = Wild('a', exclude=[symbol], properties=[lambda x: not x.is_zero])
b = Wild('b', exclude=[symbol])
c = Wild('c', exclude=[symbol])
d = Wild('d', exclude=[symbol], properties=[lambda x: not x.is_zero])
e = Wild('e', exclude=[symbol], properties=[
lambda x: not (x.is_nonnegative and x.is_integer)])
wilds = (a, b, c, d, e)
# patterns consist of a SymPy class, a wildcard expr, an optional
# condition coded as a lambda (when Wild properties are not enough),
# followed by an applicable rule
patterns = (
(Mul, exp(a*symbol + b)/symbol, None, EiRule),
(Mul, cos(a*symbol + b)/symbol, None, CiRule),
(Mul, cosh(a*symbol + b)/symbol, None, ChiRule),
(Mul, sin(a*symbol + b)/symbol, None, SiRule),
(Mul, sinh(a*symbol + b)/symbol, None, ShiRule),
(Pow, 1/log(a*symbol + b), None, LiRule),
(exp, exp(a*symbol**2 + b*symbol + c), None, ErfRule),
(sin, sin(a*symbol**2 + b*symbol + c), None, FresnelSRule),
(cos, cos(a*symbol**2 + b*symbol + c), None, FresnelCRule),
(Mul, symbol**e*exp(a*symbol), None, UpperGammaRule),
(Mul, polylog(b, a*symbol)/symbol, None, PolylogRule),
(Pow, 1/sqrt(a - d*sin(symbol)**2),
lambda a, d: a != d, EllipticFRule),
(Pow, sqrt(a - d*sin(symbol)**2),
lambda a, d: a != d, EllipticERule),
)
for p in patterns:
if isinstance(integrand, p[0]):
match = integrand.match(p[1])
if match:
wild_vals = tuple(match.get(w) for w in wilds
if match.get(w) is not None)
if p[2] is None or p[2](*wild_vals):
args = wild_vals + (integrand, symbol)
return p[3](*args)
def inverse_trig_rule(integral):
integrand, symbol = integral
base, exp = integrand.as_base_exp()
a = Wild('a', exclude=[symbol])
b = Wild('b', exclude=[symbol])
match = base.match(a + b*symbol**2)
if not match:
return
def negative(x):
return x.is_negative or x.could_extract_minus_sign()
def ArcsinhRule(integrand, symbol):
return InverseHyperbolicRule(asinh, integrand, symbol)
def ArccoshRule(integrand, symbol):
return InverseHyperbolicRule(acosh, integrand, symbol)
def make_inverse_trig(RuleClass, base_exp, a, sign_a, b, sign_b):
u_var = Dummy("u")
current_base = base
current_symbol = symbol
constant = u_func = u_constant = substep = None
factored = integrand
if a != 1:
constant = a**base_exp
current_base = sign_a + sign_b * (b/a) * current_symbol**2
factored = current_base ** base_exp
if (b/a) != 1:
u_func = sqrt(b/a) * symbol
u_constant = sqrt(a/b)
current_symbol = u_var
current_base = sign_a + sign_b * current_symbol**2
substep = RuleClass(current_base ** base_exp, current_symbol)
if u_func is not None:
if u_constant != 1 and substep is not None:
substep = ConstantTimesRule(
u_constant, current_base ** base_exp, substep,
u_constant * current_base ** base_exp, symbol)
substep = URule(u_var, u_func, u_constant, substep, factored, symbol)
if constant is not None and substep is not None:
substep = ConstantTimesRule(constant, factored, substep, integrand, symbol)
return substep
a, b = [match.get(i, S.Zero) for i in (a, b)]
# list of (rule, base_exp, a, sign_a, b, sign_b, condition)
possibilities = []
if simplify(2*exp + 1) == 0:
possibilities.append((ArcsinRule, exp, a, 1, -b, -1, And(a > 0, b < 0)))
possibilities.append((ArcsinhRule, exp, a, 1, b, 1, And(a > 0, b > 0)))
possibilities.append((ArccoshRule, exp, -a, -1, b, 1, And(a < 0, b > 0)))
possibilities = [p for p in possibilities if p[-1] is not S.false]
if a.is_number and b.is_number:
possibility = [p for p in possibilities if p[-1] is S.true]
if len(possibility) == 1:
return make_inverse_trig(*possibility[0][:-1])
elif possibilities:
return PiecewiseRule(
[(make_inverse_trig(*p[:-1]), p[-1]) for p in possibilities],
integrand, symbol)
def add_rule(integral):
integrand, symbol = integral
results = [integral_steps(g, symbol)
for g in integrand.as_ordered_terms()]
return None if None in results else AddRule(results, integrand, symbol)
def mul_rule(integral):
integrand, symbol = integral
# Constant times function case
coeff, f = integrand.as_independent(symbol)
next_step = integral_steps(f, symbol)
if coeff != 1 and next_step is not None:
return ConstantTimesRule(
coeff, f,
next_step,
integrand, symbol)
def _parts_rule(integrand, symbol):
# LIATE rule:
# log, inverse trig, algebraic, trigonometric, exponential
def pull_out_algebraic(integrand):
integrand = integrand.cancel().together()
# iterating over Piecewise args would not work here
algebraic = ([] if isinstance(integrand, Piecewise)
else [arg for arg in integrand.args if arg.is_algebraic_expr(symbol)])
if algebraic:
u = Mul(*algebraic)
dv = (integrand / u).cancel()
return u, dv
def pull_out_u(*functions):
def pull_out_u_rl(integrand):
if any(integrand.has(f) for f in functions):
args = [arg for arg in integrand.args
if any(isinstance(arg, cls) for cls in functions)]
if args:
u = reduce(lambda a,b: a*b, args)
dv = integrand / u
return u, dv
return pull_out_u_rl
liate_rules = [pull_out_u(log), pull_out_u(*inverse_trig_functions),
pull_out_algebraic, pull_out_u(sin, cos),
pull_out_u(exp)]
dummy = Dummy("temporary")
# we can integrate log(x) and atan(x) by setting dv = 1
if isinstance(integrand, (log, *inverse_trig_functions)):
integrand = dummy * integrand
for index, rule in enumerate(liate_rules):
result = rule(integrand)
if result:
u, dv = result
# Don't pick u to be a constant if possible
if symbol not in u.free_symbols and not u.has(dummy):
return
u = u.subs(dummy, 1)
dv = dv.subs(dummy, 1)
# Don't pick a non-polynomial algebraic to be differentiated
if rule == pull_out_algebraic and not u.is_polynomial(symbol):
return
# Don't trade one logarithm for another
if isinstance(u, log):
rec_dv = 1/dv
if (rec_dv.is_polynomial(symbol) and
degree(rec_dv, symbol) == 1):
return
# Can integrate a polynomial times OrthogonalPolynomial
if rule == pull_out_algebraic and isinstance(dv, OrthogonalPolynomial):
v_step = integral_steps(dv, symbol)
if contains_dont_know(v_step):
return
else:
du = u.diff(symbol)
v = _manualintegrate(v_step)
return u, dv, v, du, v_step
# make sure dv is amenable to integration
accept = False
if index < 2: # log and inverse trig are usually worth trying
accept = True
elif (rule == pull_out_algebraic and dv.args and
all(isinstance(a, (sin, cos, exp))
for a in dv.args)):
accept = True
else:
for lrule in liate_rules[index + 1:]:
r = lrule(integrand)
if r and r[0].subs(dummy, 1).equals(dv):
accept = True
break
if accept:
du = u.diff(symbol)
v_step = integral_steps(simplify(dv), symbol)
if not contains_dont_know(v_step):
v = _manualintegrate(v_step)
return u, dv, v, du, v_step
def parts_rule(integral):
integrand, symbol = integral
constant, integrand = integrand.as_coeff_Mul()
result = _parts_rule(integrand, symbol)
steps = []
if result:
u, dv, v, du, v_step = result
debug("u : {}, dv : {}, v : {}, du : {}, v_step: {}".format(u, dv, v, du, v_step))
steps.append(result)
if isinstance(v, Integral):
return
# Set a limit on the number of times u can be used
if isinstance(u, (sin, cos, exp, sinh, cosh)):
cachekey = u.xreplace({symbol: _cache_dummy})
if _parts_u_cache[cachekey] > 2:
return
_parts_u_cache[cachekey] += 1
# Try cyclic integration by parts a few times
for _ in range(4):
debug("Cyclic integration {} with v: {}, du: {}, integrand: {}".format(_, v, du, integrand))
coefficient = ((v * du) / integrand).cancel()
if coefficient == 1:
break
if symbol not in coefficient.free_symbols:
rule = CyclicPartsRule(
[PartsRule(u, dv, v_step, None, None, None)
for (u, dv, v, du, v_step) in steps],
(-1) ** len(steps) * coefficient,
integrand, symbol
)
if (constant != 1) and rule:
rule = ConstantTimesRule(constant, integrand, rule,
constant * integrand, symbol)
return rule
# _parts_rule is sensitive to constants, factor it out
next_constant, next_integrand = (v * du).as_coeff_Mul()
result = _parts_rule(next_integrand, symbol)
if result:
u, dv, v, du, v_step = result
u *= next_constant
du *= next_constant
steps.append((u, dv, v, du, v_step))
else:
break
def make_second_step(steps, integrand):
if steps:
u, dv, v, du, v_step = steps[0]
return PartsRule(u, dv, v_step,
make_second_step(steps[1:], v * du),
integrand, symbol)
else:
steps = integral_steps(integrand, symbol)
if steps:
return steps
else:
return DontKnowRule(integrand, symbol)
if steps:
u, dv, v, du, v_step = steps[0]
rule = PartsRule(u, dv, v_step,
make_second_step(steps[1:], v * du),
integrand, symbol)
if (constant != 1) and rule:
rule = ConstantTimesRule(constant, integrand, rule,
constant * integrand, symbol)
return rule
def trig_rule(integral):
integrand, symbol = integral
if isinstance(integrand, (sin, cos)):
arg = integrand.args[0]
if not isinstance(arg, Symbol):
return # perhaps a substitution can deal with it
if isinstance(integrand, sin):
func = 'sin'
else:
func = 'cos'
return TrigRule(func, arg, integrand, symbol)
if integrand == sec(symbol)**2:
return TrigRule('sec**2', symbol, integrand, symbol)
elif integrand == csc(symbol)**2:
return TrigRule('csc**2', symbol, integrand, symbol)
if isinstance(integrand, tan):
rewritten = sin(*integrand.args) / cos(*integrand.args)
elif isinstance(integrand, cot):
rewritten = cos(*integrand.args) / sin(*integrand.args)
elif isinstance(integrand, sec):
arg = integrand.args[0]
rewritten = ((sec(arg)**2 + tan(arg) * sec(arg)) /
(sec(arg) + tan(arg)))
elif isinstance(integrand, csc):
arg = integrand.args[0]
rewritten = ((csc(arg)**2 + cot(arg) * csc(arg)) /
(csc(arg) + cot(arg)))
else:
return
return RewriteRule(
rewritten,
integral_steps(rewritten, symbol),
integrand, symbol
)
def trig_product_rule(integral):
integrand, symbol = integral
sectan = sec(symbol) * tan(symbol)
q = integrand / sectan
if symbol not in q.free_symbols:
rule = TrigRule('sec*tan', symbol, sectan, symbol)
if q != 1 and rule:
rule = ConstantTimesRule(q, sectan, rule, integrand, symbol)
return rule
csccot = -csc(symbol) * cot(symbol)
q = integrand / csccot
if symbol not in q.free_symbols:
rule = TrigRule('csc*cot', symbol, csccot, symbol)
if q != 1 and rule:
rule = ConstantTimesRule(q, csccot, rule, integrand, symbol)
return rule
def quadratic_denom_rule(integral):
integrand, symbol = integral
a = Wild('a', exclude=[symbol])
b = Wild('b', exclude=[symbol])
c = Wild('c', exclude=[symbol])
match = integrand.match(a / (b * symbol ** 2 + c))
if match:
a, b, c = match[a], match[b], match[c]
if b.is_extended_real and c.is_extended_real:
return PiecewiseRule([(ArctanRule(a, b, c, integrand, symbol), Gt(c / b, 0)),
(ArccothRule(a, b, c, integrand, symbol), And(Gt(symbol ** 2, -c / b), Lt(c / b, 0))),
(ArctanhRule(a, b, c, integrand, symbol), And(Lt(symbol ** 2, -c / b), Lt(c / b, 0))),
], integrand, symbol)
else:
return ArctanRule(a, b, c, integrand, symbol)
d = Wild('d', exclude=[symbol])
match2 = integrand.match(a / (b * symbol ** 2 + c * symbol + d))
if match2:
b, c = match2[b], match2[c]
if b.is_zero:
return
u = Dummy('u')
u_func = symbol + c/(2*b)
integrand2 = integrand.subs(symbol, u - c / (2*b))
next_step = integral_steps(integrand2, u)
if next_step:
return URule(u, u_func, None, next_step, integrand2, symbol)
else:
return
e = Wild('e', exclude=[symbol])
match3 = integrand.match((a* symbol + b) / (c * symbol ** 2 + d * symbol + e))
if match3:
a, b, c, d, e = match3[a], match3[b], match3[c], match3[d], match3[e]
if c.is_zero:
return
denominator = c * symbol**2 + d * symbol + e
const = a/(2*c)
numer1 = (2*c*symbol+d)
numer2 = - const*d + b
u = Dummy('u')
step1 = URule(u,
denominator,
const,
integral_steps(u**(-1), u),
integrand,
symbol)
if const != 1:
step1 = ConstantTimesRule(const,
numer1/denominator,
step1,
const*numer1/denominator,
symbol)
if numer2.is_zero:
return step1
step2 = integral_steps(numer2/denominator, symbol)
substeps = AddRule([step1, step2], integrand, symbol)
rewriten = const*numer1/denominator+numer2/denominator
return RewriteRule(rewriten, substeps, integrand, symbol)
return
def root_mul_rule(integral):
integrand, symbol = integral
a = Wild('a', exclude=[symbol])
b = Wild('b', exclude=[symbol])
c = Wild('c')
match = integrand.match(sqrt(a * symbol + b) * c)
if not match:
return
a, b, c = match[a], match[b], match[c]
d = Wild('d', exclude=[symbol])
e = Wild('e', exclude=[symbol])
f = Wild('f')
recursion_test = c.match(sqrt(d * symbol + e) * f)
if recursion_test:
return
u = Dummy('u')
u_func = sqrt(a * symbol + b)
integrand = integrand.subs(u_func, u)
integrand = integrand.subs(symbol, (u**2 - b) / a)
integrand = integrand * 2 * u / a
next_step = integral_steps(integrand, u)
if next_step:
return URule(u, u_func, None, next_step, integrand, symbol)
@cacheit
def make_wilds(symbol):
a = Wild('a', exclude=[symbol])
b = Wild('b', exclude=[symbol])
m = Wild('m', exclude=[symbol], properties=[lambda n: isinstance(n, Integer)])
n = Wild('n', exclude=[symbol], properties=[lambda n: isinstance(n, Integer)])
return a, b, m, n
@cacheit
def sincos_pattern(symbol):
a, b, m, n = make_wilds(symbol)
pattern = sin(a*symbol)**m * cos(b*symbol)**n
return pattern, a, b, m, n
@cacheit
def tansec_pattern(symbol):
a, b, m, n = make_wilds(symbol)
pattern = tan(a*symbol)**m * sec(b*symbol)**n
return pattern, a, b, m, n
@cacheit
def cotcsc_pattern(symbol):
a, b, m, n = make_wilds(symbol)
pattern = cot(a*symbol)**m * csc(b*symbol)**n
return pattern, a, b, m, n
@cacheit
def heaviside_pattern(symbol):
m = Wild('m', exclude=[symbol])
b = Wild('b', exclude=[symbol])
g = Wild('g')
pattern = Heaviside(m*symbol + b) * g
return pattern, m, b, g
def uncurry(func):
def uncurry_rl(args):
return func(*args)
return uncurry_rl
def trig_rewriter(rewrite):
def trig_rewriter_rl(args):
a, b, m, n, integrand, symbol = args
rewritten = rewrite(a, b, m, n, integrand, symbol)
if rewritten != integrand:
return RewriteRule(
rewritten,
integral_steps(rewritten, symbol),
integrand, symbol)
return trig_rewriter_rl
sincos_botheven_condition = uncurry(
lambda a, b, m, n, i, s: m.is_even and n.is_even and
m.is_nonnegative and n.is_nonnegative)
sincos_botheven = trig_rewriter(
lambda a, b, m, n, i, symbol: ( (((1 - cos(2*a*symbol)) / 2) ** (m / 2)) *
(((1 + cos(2*b*symbol)) / 2) ** (n / 2)) ))
sincos_sinodd_condition = uncurry(lambda a, b, m, n, i, s: m.is_odd and m >= 3)
sincos_sinodd = trig_rewriter(
lambda a, b, m, n, i, symbol: ( (1 - cos(a*symbol)**2)**((m - 1) / 2) *
sin(a*symbol) *
cos(b*symbol) ** n))
sincos_cosodd_condition = uncurry(lambda a, b, m, n, i, s: n.is_odd and n >= 3)
sincos_cosodd = trig_rewriter(
lambda a, b, m, n, i, symbol: ( (1 - sin(b*symbol)**2)**((n - 1) / 2) *
cos(b*symbol) *
sin(a*symbol) ** m))
tansec_seceven_condition = uncurry(lambda a, b, m, n, i, s: n.is_even and n >= 4)
tansec_seceven = trig_rewriter(
lambda a, b, m, n, i, symbol: ( (1 + tan(b*symbol)**2) ** (n/2 - 1) *
sec(b*symbol)**2 *
tan(a*symbol) ** m ))
tansec_tanodd_condition = uncurry(lambda a, b, m, n, i, s: m.is_odd)
tansec_tanodd = trig_rewriter(
lambda a, b, m, n, i, symbol: ( (sec(a*symbol)**2 - 1) ** ((m - 1) / 2) *
tan(a*symbol) *
sec(b*symbol) ** n ))
tan_tansquared_condition = uncurry(lambda a, b, m, n, i, s: m == 2 and n == 0)
tan_tansquared = trig_rewriter(
lambda a, b, m, n, i, symbol: ( sec(a*symbol)**2 - 1))
cotcsc_csceven_condition = uncurry(lambda a, b, m, n, i, s: n.is_even and n >= 4)
cotcsc_csceven = trig_rewriter(
lambda a, b, m, n, i, symbol: ( (1 + cot(b*symbol)**2) ** (n/2 - 1) *
csc(b*symbol)**2 *
cot(a*symbol) ** m ))
cotcsc_cotodd_condition = uncurry(lambda a, b, m, n, i, s: m.is_odd)
cotcsc_cotodd = trig_rewriter(
lambda a, b, m, n, i, symbol: ( (csc(a*symbol)**2 - 1) ** ((m - 1) / 2) *
cot(a*symbol) *
csc(b*symbol) ** n ))
def trig_sincos_rule(integral):
integrand, symbol = integral
if any(integrand.has(f) for f in (sin, cos)):
pattern, a, b, m, n = sincos_pattern(symbol)
match = integrand.match(pattern)
if not match:
return
return multiplexer({
sincos_botheven_condition: sincos_botheven,
sincos_sinodd_condition: sincos_sinodd,
sincos_cosodd_condition: sincos_cosodd
})(tuple(
[match.get(i, S.Zero) for i in (a, b, m, n)] +
[integrand, symbol]))
def trig_tansec_rule(integral):
integrand, symbol = integral
integrand = integrand.subs({
1 / cos(symbol): sec(symbol)
})
if any(integrand.has(f) for f in (tan, sec)):
pattern, a, b, m, n = tansec_pattern(symbol)
match = integrand.match(pattern)
if not match:
return
return multiplexer({
tansec_tanodd_condition: tansec_tanodd,
tansec_seceven_condition: tansec_seceven,
tan_tansquared_condition: tan_tansquared
})(tuple(
[match.get(i, S.Zero) for i in (a, b, m, n)] +
[integrand, symbol]))
def trig_cotcsc_rule(integral):
integrand, symbol = integral
integrand = integrand.subs({
1 / sin(symbol): csc(symbol),
1 / tan(symbol): cot(symbol),
cos(symbol) / tan(symbol): cot(symbol)
})
if any(integrand.has(f) for f in (cot, csc)):
pattern, a, b, m, n = cotcsc_pattern(symbol)
match = integrand.match(pattern)
if not match:
return
return multiplexer({
cotcsc_cotodd_condition: cotcsc_cotodd,
cotcsc_csceven_condition: cotcsc_csceven
})(tuple(
[match.get(i, S.Zero) for i in (a, b, m, n)] +
[integrand, symbol]))
def trig_sindouble_rule(integral):
integrand, symbol = integral
a = Wild('a', exclude=[sin(2*symbol)])
match = integrand.match(sin(2*symbol)*a)
if match:
sin_double = 2*sin(symbol)*cos(symbol)/sin(2*symbol)
return integral_steps(integrand * sin_double, symbol)
def trig_powers_products_rule(integral):
return do_one(null_safe(trig_sincos_rule),
null_safe(trig_tansec_rule),
null_safe(trig_cotcsc_rule),
null_safe(trig_sindouble_rule))(integral)
def trig_substitution_rule(integral):
integrand, symbol = integral
A = Wild('a', exclude=[0, symbol])
B = Wild('b', exclude=[0, symbol])
theta = Dummy("theta")
target_pattern = A + B*symbol**2
matches = integrand.find(target_pattern)
for expr in matches:
match = expr.match(target_pattern)
a = match.get(A, S.Zero)
b = match.get(B, S.Zero)
a_positive = ((a.is_number and a > 0) or a.is_positive)
b_positive = ((b.is_number and b > 0) or b.is_positive)
a_negative = ((a.is_number and a < 0) or a.is_negative)
b_negative = ((b.is_number and b < 0) or b.is_negative)
x_func = None
if a_positive and b_positive:
# a**2 + b*x**2. Assume sec(theta) > 0, -pi/2 < theta < pi/2
x_func = (sqrt(a)/sqrt(b)) * tan(theta)
# Do not restrict the domain: tan(theta) takes on any real
# value on the interval -pi/2 < theta < pi/2 so x takes on
# any value
restriction = True
elif a_positive and b_negative:
# a**2 - b*x**2. Assume cos(theta) > 0, -pi/2 < theta < pi/2
constant = sqrt(a)/sqrt(-b)
x_func = constant * sin(theta)
restriction = And(symbol > -constant, symbol < constant)
elif a_negative and b_positive:
# b*x**2 - a**2. Assume sin(theta) > 0, 0 < theta < pi
constant = sqrt(-a)/sqrt(b)
x_func = constant * sec(theta)
restriction = And(symbol > -constant, symbol < constant)
if x_func:
# Manually simplify sqrt(trig(theta)**2) to trig(theta)
# Valid due to assumed domain restriction
substitutions = {}
for f in [sin, cos, tan,
sec, csc, cot]:
substitutions[sqrt(f(theta)**2)] = f(theta)
substitutions[sqrt(f(theta)**(-2))] = 1/f(theta)
replaced = integrand.subs(symbol, x_func).trigsimp()
replaced = manual_subs(replaced, substitutions)
if not replaced.has(symbol):
replaced *= manual_diff(x_func, theta)
replaced = replaced.trigsimp()
secants = replaced.find(1/cos(theta))
if secants:
replaced = replaced.xreplace({
1/cos(theta): sec(theta)
})
substep = integral_steps(replaced, theta)
if not contains_dont_know(substep):
return TrigSubstitutionRule(
theta, x_func, replaced, substep, restriction,
integrand, symbol)
def heaviside_rule(integral):
integrand, symbol = integral
pattern, m, b, g = heaviside_pattern(symbol)
match = integrand.match(pattern)
if match and 0 != match[g]:
# f = Heaviside(m*x + b)*g
v_step = integral_steps(match[g], symbol)
result = _manualintegrate(v_step)
m, b = match[m], match[b]
return HeavisideRule(m*symbol + b, -b/m, result, integrand, symbol)
def substitution_rule(integral):
integrand, symbol = integral
u_var = Dummy("u")
substitutions = find_substitutions(integrand, symbol, u_var)
count = 0
if substitutions:
debug("List of Substitution Rules")
ways = []
for u_func, c, substituted in substitutions:
subrule = integral_steps(substituted, u_var)
count = count + 1
debug("Rule {}: {}".format(count, subrule))
if contains_dont_know(subrule):
continue
if simplify(c - 1) != 0:
_, denom = c.as_numer_denom()
if subrule:
subrule = ConstantTimesRule(c, substituted, subrule, substituted, u_var)
if denom.free_symbols:
piecewise = []
could_be_zero = []
if isinstance(denom, Mul):
could_be_zero = denom.args
else:
could_be_zero.append(denom)
for expr in could_be_zero:
if not fuzzy_not(expr.is_zero):
substep = integral_steps(manual_subs(integrand, expr, 0), symbol)
if substep:
piecewise.append((
substep,
Eq(expr, 0)
))
piecewise.append((subrule, True))
subrule = PiecewiseRule(piecewise, substituted, symbol)
ways.append(URule(u_var, u_func, c,
subrule,
integrand, symbol))
if len(ways) > 1:
return AlternativeRule(ways, integrand, symbol)
elif ways:
return ways[0]
elif integrand.has(exp):
u_func = exp(symbol)
c = 1
substituted = integrand / u_func.diff(symbol)
substituted = substituted.subs(u_func, u_var)
if symbol not in substituted.free_symbols:
return URule(u_var, u_func, c,
integral_steps(substituted, u_var),
integrand, symbol)
partial_fractions_rule = rewriter(
lambda integrand, symbol: integrand.is_rational_function(),
lambda integrand, symbol: integrand.apart(symbol))
cancel_rule = rewriter(
# lambda integrand, symbol: integrand.is_algebraic_expr(),
# lambda integrand, symbol: isinstance(integrand, Mul),
lambda integrand, symbol: True,
lambda integrand, symbol: integrand.cancel())
distribute_expand_rule = rewriter(
lambda integrand, symbol: (
all(arg.is_Pow or arg.is_polynomial(symbol) for arg in integrand.args)
or isinstance(integrand, Pow)
or isinstance(integrand, Mul)),
lambda integrand, symbol: integrand.expand())
trig_expand_rule = rewriter(
# If there are trig functions with different arguments, expand them
lambda integrand, symbol: (
len({a.args[0] for a in integrand.atoms(TrigonometricFunction)}) > 1),
lambda integrand, symbol: integrand.expand(trig=True))
def derivative_rule(integral):
integrand = integral[0]
diff_variables = integrand.variables
undifferentiated_function = integrand.expr
integrand_variables = undifferentiated_function.free_symbols
if integral.symbol in integrand_variables:
if integral.symbol in diff_variables:
return DerivativeRule(*integral)
else:
return DontKnowRule(integrand, integral.symbol)
else:
return ConstantRule(integral.integrand, *integral)
def rewrites_rule(integral):
integrand, symbol = integral
if integrand.match(1/cos(symbol)):
rewritten = integrand.subs(1/cos(symbol), sec(symbol))
return RewriteRule(rewritten, integral_steps(rewritten, symbol), integrand, symbol)
def fallback_rule(integral):
return DontKnowRule(*integral)
# Cache is used to break cyclic integrals.
# Need to use the same dummy variable in cached expressions for them to match.
# Also record "u" of integration by parts, to avoid infinite repetition.
_integral_cache = {} # type: tDict[Expr, Optional[Expr]]
_parts_u_cache = defaultdict(int) # type: tDict[Expr, int]
_cache_dummy = Dummy("z")
def integral_steps(integrand, symbol, **options):
"""Returns the steps needed to compute an integral.
Explanation
===========
This function attempts to mirror what a student would do by hand as
closely as possible.
SymPy Gamma uses this to provide a step-by-step explanation of an
integral. The code it uses to format the results of this function can be
found at
https://github.com/sympy/sympy_gamma/blob/master/app/logic/intsteps.py.
Examples
========
>>> from sympy import exp, sin
>>> from sympy.integrals.manualintegrate import integral_steps
>>> from sympy.abc import x
>>> print(repr(integral_steps(exp(x) / (1 + exp(2 * x)), x))) \
# doctest: +NORMALIZE_WHITESPACE
URule(u_var=_u, u_func=exp(x), constant=1,
substep=PiecewiseRule(subfunctions=[(ArctanRule(a=1, b=1, c=1, context=1/(_u**2 + 1), symbol=_u), True),
(ArccothRule(a=1, b=1, c=1, context=1/(_u**2 + 1), symbol=_u), False),
(ArctanhRule(a=1, b=1, c=1, context=1/(_u**2 + 1), symbol=_u), False)],
context=1/(_u**2 + 1), symbol=_u), context=exp(x)/(exp(2*x) + 1), symbol=x)
>>> print(repr(integral_steps(sin(x), x))) \
# doctest: +NORMALIZE_WHITESPACE
TrigRule(func='sin', arg=x, context=sin(x), symbol=x)
>>> print(repr(integral_steps((x**2 + 3)**2, x))) \
# doctest: +NORMALIZE_WHITESPACE
RewriteRule(rewritten=x**4 + 6*x**2 + 9,
substep=AddRule(substeps=[PowerRule(base=x, exp=4, context=x**4, symbol=x),
ConstantTimesRule(constant=6, other=x**2,
substep=PowerRule(base=x, exp=2, context=x**2, symbol=x),
context=6*x**2, symbol=x),
ConstantRule(constant=9, context=9, symbol=x)],
context=x**4 + 6*x**2 + 9, symbol=x), context=(x**2 + 3)**2, symbol=x)
Returns
=======
rule : namedtuple
The first step; most rules have substeps that must also be
considered. These substeps can be evaluated using ``manualintegrate``
to obtain a result.
"""
cachekey = integrand.xreplace({symbol: _cache_dummy})
if cachekey in _integral_cache:
if _integral_cache[cachekey] is None:
# Stop this attempt, because it leads around in a loop
return DontKnowRule(integrand, symbol)
else:
# TODO: This is for future development, as currently
# _integral_cache gets no values other than None
return (_integral_cache[cachekey].xreplace(_cache_dummy, symbol),
symbol)
else:
_integral_cache[cachekey] = None
integral = IntegralInfo(integrand, symbol)
def key(integral):
integrand = integral.integrand
if symbol not in integrand.free_symbols:
return Number
elif isinstance(integrand, TrigonometricFunction):
return TrigonometricFunction
elif isinstance(integrand, Derivative):
return Derivative
else:
for cls in (Pow, Symbol, exp, log,
Add, Mul, *inverse_trig_functions,
Heaviside, OrthogonalPolynomial):
if isinstance(integrand, cls):
return cls
def integral_is_subclass(*klasses):
def _integral_is_subclass(integral):
k = key(integral)
return k and issubclass(k, klasses)
return _integral_is_subclass
result = do_one(
null_safe(special_function_rule),
null_safe(switch(key, {
Pow: do_one(null_safe(power_rule), null_safe(inverse_trig_rule), \
null_safe(quadratic_denom_rule)),
Symbol: power_rule,
exp: exp_rule,
Add: add_rule,
Mul: do_one(null_safe(mul_rule), null_safe(trig_product_rule), \
null_safe(heaviside_rule), null_safe(quadratic_denom_rule), \
null_safe(root_mul_rule)),
Derivative: derivative_rule,
TrigonometricFunction: trig_rule,
Heaviside: heaviside_rule,
OrthogonalPolynomial: orthogonal_poly_rule,
Number: constant_rule
})),
do_one(
null_safe(trig_rule),
null_safe(alternatives(
rewrites_rule,
substitution_rule,
condition(
integral_is_subclass(Mul, Pow),
partial_fractions_rule),
condition(
integral_is_subclass(Mul, Pow),
cancel_rule),
condition(
integral_is_subclass(Mul, log,
*inverse_trig_functions),
parts_rule),
condition(
integral_is_subclass(Mul, Pow),
distribute_expand_rule),
trig_powers_products_rule,
trig_expand_rule
)),
null_safe(trig_substitution_rule)
),
fallback_rule)(integral)
del _integral_cache[cachekey]
return result
@evaluates(ConstantRule)
def eval_constant(constant, integrand, symbol):
return constant * symbol
@evaluates(ConstantTimesRule)
def eval_constanttimes(constant, other, substep, integrand, symbol):
return constant * _manualintegrate(substep)
@evaluates(PowerRule)
def eval_power(base, exp, integrand, symbol):
return Piecewise(
((base**(exp + 1))/(exp + 1), Ne(exp, -1)),
(log(base), True),
)
@evaluates(ExpRule)
def eval_exp(base, exp, integrand, symbol):
return integrand / log(base)
@evaluates(AddRule)
def eval_add(substeps, integrand, symbol):
return sum(map(_manualintegrate, substeps))
@evaluates(URule)
def eval_u(u_var, u_func, constant, substep, integrand, symbol):
result = _manualintegrate(substep)
if u_func.is_Pow and u_func.exp == -1:
# avoid needless -log(1/x) from substitution
result = result.subs(log(u_var), -log(u_func.base))
return result.subs(u_var, u_func)
@evaluates(PartsRule)
def eval_parts(u, dv, v_step, second_step, integrand, symbol):
v = _manualintegrate(v_step)
return u * v - _manualintegrate(second_step)
@evaluates(CyclicPartsRule)
def eval_cyclicparts(parts_rules, coefficient, integrand, symbol):
coefficient = 1 - coefficient
result = []
sign = 1
for rule in parts_rules:
result.append(sign * rule.u * _manualintegrate(rule.v_step))
sign *= -1
return Add(*result) / coefficient
@evaluates(TrigRule)
def eval_trig(func, arg, integrand, symbol):
if func == 'sin':
return -cos(arg)
elif func == 'cos':
return sin(arg)
elif func == 'sec*tan':
return sec(arg)
elif func == 'csc*cot':
return csc(arg)
elif func == 'sec**2':
return tan(arg)
elif func == 'csc**2':
return -cot(arg)
@evaluates(ArctanRule)
def eval_arctan(a, b, c, integrand, symbol):
return a / b * 1 / sqrt(c / b) * atan(symbol / sqrt(c / b))
@evaluates(ArccothRule)
def eval_arccoth(a, b, c, integrand, symbol):
return - a / b * 1 / sqrt(-c / b) * acoth(symbol / sqrt(-c / b))
@evaluates(ArctanhRule)
def eval_arctanh(a, b, c, integrand, symbol):
return - a / b * 1 / sqrt(-c / b) * atanh(symbol / sqrt(-c / b))
@evaluates(ReciprocalRule)
def eval_reciprocal(func, integrand, symbol):
return log(func)
@evaluates(ArcsinRule)
def eval_arcsin(integrand, symbol):
return asin(symbol)
@evaluates(InverseHyperbolicRule)
def eval_inversehyperbolic(func, integrand, symbol):
return func(symbol)
@evaluates(AlternativeRule)
def eval_alternative(alternatives, integrand, symbol):
return _manualintegrate(alternatives[0])
@evaluates(RewriteRule)
def eval_rewrite(rewritten, substep, integrand, symbol):
return _manualintegrate(substep)
@evaluates(PiecewiseRule)
def eval_piecewise(substeps, integrand, symbol):
return Piecewise(*[(_manualintegrate(substep), cond)
for substep, cond in substeps])
@evaluates(TrigSubstitutionRule)
def eval_trigsubstitution(theta, func, rewritten, substep, restriction, integrand, symbol):
func = func.subs(sec(theta), 1/cos(theta))
func = func.subs(csc(theta), 1/sin(theta))
func = func.subs(cot(theta), 1/tan(theta))
trig_function = list(func.find(TrigonometricFunction))
assert len(trig_function) == 1
trig_function = trig_function[0]
relation = solve(symbol - func, trig_function)
assert len(relation) == 1
numer, denom = fraction(relation[0])
if isinstance(trig_function, sin):
opposite = numer
hypotenuse = denom
adjacent = sqrt(denom**2 - numer**2)
inverse = asin(relation[0])
elif isinstance(trig_function, cos):
adjacent = numer
hypotenuse = denom
opposite = sqrt(denom**2 - numer**2)
inverse = acos(relation[0])
elif isinstance(trig_function, tan):
opposite = numer
adjacent = denom
hypotenuse = sqrt(denom**2 + numer**2)
inverse = atan(relation[0])
substitution = [
(sin(theta), opposite/hypotenuse),
(cos(theta), adjacent/hypotenuse),
(tan(theta), opposite/adjacent),
(theta, inverse)
]
return Piecewise(
(_manualintegrate(substep).subs(substitution).trigsimp(), restriction)
)
@evaluates(DerivativeRule)
def eval_derivativerule(integrand, symbol):
# isinstance(integrand, Derivative) should be True
variable_count = list(integrand.variable_count)
for i, (var, count) in enumerate(variable_count):
if var == symbol:
variable_count[i] = (var, count-1)
break
return Derivative(integrand.expr, *variable_count)
@evaluates(HeavisideRule)
def eval_heaviside(harg, ibnd, substep, integrand, symbol):
# If we are integrating over x and the integrand has the form
# Heaviside(m*x+b)*g(x) == Heaviside(harg)*g(symbol)
# then there needs to be continuity at -b/m == ibnd,
# so we subtract the appropriate term.
return Heaviside(harg)*(substep - substep.subs(symbol, ibnd))
@evaluates(JacobiRule)
def eval_jacobi(n, a, b, integrand, symbol):
return Piecewise(
(2*jacobi(n + 1, a - 1, b - 1, symbol)/(n + a + b), Ne(n + a + b, 0)),
(symbol, Eq(n, 0)),
((a + b + 2)*symbol**2/4 + (a - b)*symbol/2, Eq(n, 1)))
@evaluates(GegenbauerRule)
def eval_gegenbauer(n, a, integrand, symbol):
return Piecewise(
(gegenbauer(n + 1, a - 1, symbol)/(2*(a - 1)), Ne(a, 1)),
(chebyshevt(n + 1, symbol)/(n + 1), Ne(n, -1)),
(S.Zero, True))
@evaluates(ChebyshevTRule)
def eval_chebyshevt(n, integrand, symbol):
return Piecewise(((chebyshevt(n + 1, symbol)/(n + 1) -
chebyshevt(n - 1, symbol)/(n - 1))/2, Ne(Abs(n), 1)),
(symbol**2/2, True))
@evaluates(ChebyshevURule)
def eval_chebyshevu(n, integrand, symbol):
return Piecewise(
(chebyshevt(n + 1, symbol)/(n + 1), Ne(n, -1)),
(S.Zero, True))
@evaluates(LegendreRule)
def eval_legendre(n, integrand, symbol):
return (legendre(n + 1, symbol) - legendre(n - 1, symbol))/(2*n + 1)
@evaluates(HermiteRule)
def eval_hermite(n, integrand, symbol):
return hermite(n + 1, symbol)/(2*(n + 1))
@evaluates(LaguerreRule)
def eval_laguerre(n, integrand, symbol):
return laguerre(n, symbol) - laguerre(n + 1, symbol)
@evaluates(AssocLaguerreRule)
def eval_assoclaguerre(n, a, integrand, symbol):
return -assoc_laguerre(n + 1, a - 1, symbol)
@evaluates(CiRule)
def eval_ci(a, b, integrand, symbol):
return cos(b)*Ci(a*symbol) - sin(b)*Si(a*symbol)
@evaluates(ChiRule)
def eval_chi(a, b, integrand, symbol):
return cosh(b)*Chi(a*symbol) + sinh(b)*Shi(a*symbol)
@evaluates(EiRule)
def eval_ei(a, b, integrand, symbol):
return exp(b)*Ei(a*symbol)
@evaluates(SiRule)
def eval_si(a, b, integrand, symbol):
return sin(b)*Ci(a*symbol) + cos(b)*Si(a*symbol)
@evaluates(ShiRule)
def eval_shi(a, b, integrand, symbol):
return sinh(b)*Chi(a*symbol) + cosh(b)*Shi(a*symbol)
@evaluates(ErfRule)
def eval_erf(a, b, c, integrand, symbol):
if a.is_extended_real:
return Piecewise(
(sqrt(S.Pi/(-a))/2 * exp(c - b**2/(4*a)) *
erf((-2*a*symbol - b)/(2*sqrt(-a))), a < 0),
(sqrt(S.Pi/a)/2 * exp(c - b**2/(4*a)) *
erfi((2*a*symbol + b)/(2*sqrt(a))), True))
else:
return sqrt(S.Pi/a)/2 * exp(c - b**2/(4*a)) * \
erfi((2*a*symbol + b)/(2*sqrt(a)))
@evaluates(FresnelCRule)
def eval_fresnelc(a, b, c, integrand, symbol):
return sqrt(S.Pi/(2*a)) * (
cos(b**2/(4*a) - c)*fresnelc((2*a*symbol + b)/sqrt(2*a*S.Pi)) +
sin(b**2/(4*a) - c)*fresnels((2*a*symbol + b)/sqrt(2*a*S.Pi)))
@evaluates(FresnelSRule)
def eval_fresnels(a, b, c, integrand, symbol):
return sqrt(S.Pi/(2*a)) * (
cos(b**2/(4*a) - c)*fresnels((2*a*symbol + b)/sqrt(2*a*S.Pi)) -
sin(b**2/(4*a) - c)*fresnelc((2*a*symbol + b)/sqrt(2*a*S.Pi)))
@evaluates(LiRule)
def eval_li(a, b, integrand, symbol):
return li(a*symbol + b)/a
@evaluates(PolylogRule)
def eval_polylog(a, b, integrand, symbol):
return polylog(b + 1, a*symbol)
@evaluates(UpperGammaRule)
def eval_uppergamma(a, e, integrand, symbol):
return symbol**e * (-a*symbol)**(-e) * uppergamma(e + 1, -a*symbol)/a
@evaluates(EllipticFRule)
def eval_elliptic_f(a, d, integrand, symbol):
return elliptic_f(symbol, d/a)/sqrt(a)
@evaluates(EllipticERule)
def eval_elliptic_e(a, d, integrand, symbol):
return elliptic_e(symbol, d/a)*sqrt(a)
@evaluates(DontKnowRule)
def eval_dontknowrule(integrand, symbol):
return Integral(integrand, symbol)
def _manualintegrate(rule):
evaluator = evaluators.get(rule.__class__)
if not evaluator:
raise ValueError("Cannot evaluate rule %s" % repr(rule))
return evaluator(*rule)
def manualintegrate(f, var):
"""manualintegrate(f, var)
Explanation
===========
Compute indefinite integral of a single variable using an algorithm that
resembles what a student would do by hand.
Unlike :func:`~.integrate`, var can only be a single symbol.
Examples
========
>>> from sympy import sin, cos, tan, exp, log, integrate
>>> from sympy.integrals.manualintegrate import manualintegrate
>>> from sympy.abc import x
>>> manualintegrate(1 / x, x)
log(x)
>>> integrate(1/x)
log(x)
>>> manualintegrate(log(x), x)
x*log(x) - x
>>> integrate(log(x))
x*log(x) - x
>>> manualintegrate(exp(x) / (1 + exp(2 * x)), x)
atan(exp(x))
>>> integrate(exp(x) / (1 + exp(2 * x)))
RootSum(4*_z**2 + 1, Lambda(_i, _i*log(2*_i + exp(x))))
>>> manualintegrate(cos(x)**4 * sin(x), x)
-cos(x)**5/5
>>> integrate(cos(x)**4 * sin(x), x)
-cos(x)**5/5
>>> manualintegrate(cos(x)**4 * sin(x)**3, x)
cos(x)**7/7 - cos(x)**5/5
>>> integrate(cos(x)**4 * sin(x)**3, x)
cos(x)**7/7 - cos(x)**5/5
>>> manualintegrate(tan(x), x)
-log(cos(x))
>>> integrate(tan(x), x)
-log(cos(x))
See Also
========
sympy.integrals.integrals.integrate
sympy.integrals.integrals.Integral.doit
sympy.integrals.integrals.Integral
"""
result = _manualintegrate(integral_steps(f, var))
# Clear the cache of u-parts
_parts_u_cache.clear()
# If we got Piecewise with two parts, put generic first
if isinstance(result, Piecewise) and len(result.args) == 2:
cond = result.args[0][1]
if isinstance(cond, Eq) and result.args[1][1] == True:
result = result.func(
(result.args[1][0], Ne(*cond.args)),
(result.args[0][0], True))
return result
|
b3efb4c91160b9fbb87012b616777ac7f058514b63ae514a9dd858564b029ea0 | """ Integral Transforms """
from functools import reduce, wraps
from itertools import repeat
from sympy.core import S, pi, I
from sympy.core.add import Add
from sympy.core.function import (AppliedUndef, count_ops, Derivative, expand,
expand_complex, expand_mul, Function, Lambda,
WildFunction)
from sympy.core.mul import Mul
from sympy.core.numbers import igcd, ilcm
from sympy.core.relational import _canonical, Ge, Gt, Lt, Unequality, Eq
from sympy.core.sorting import default_sort_key, ordered
from sympy.core.symbol import Dummy, symbols, Wild
from sympy.core.traversal import postorder_traversal
from sympy.functions.combinatorial.factorials import factorial, rf
from sympy.functions.elementary.complexes import (re, arg, Abs, polar_lift,
periodic_argument)
from sympy.functions.elementary.exponential import exp, log, exp_polar
from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, tanh, asinh
from sympy.functions.elementary.integers import ceiling
from sympy.functions.elementary.miscellaneous import Max, Min, sqrt
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
from sympy.functions.elementary.trigonometric import cos, cot, sin, tan, atan
from sympy.functions.special.bessel import besseli, besselj, besselk, bessely
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
from sympy.functions.special.error_functions import erf, erfc, Ei
from sympy.functions.special.gamma_functions import digamma, gamma, lowergamma
from sympy.functions.special.hyper import meijerg
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.matrices.matrices import MatrixBase
from sympy.polys.matrices.linsolve import _lin_eq2dict, PolyNonlinearError
from sympy.polys.polyroots import roots
from sympy.polys.polytools import factor, Poly
from sympy.polys.rationaltools import together
from sympy.polys.rootoftools import CRootOf, RootSum
from sympy.utilities.exceptions import (sympy_deprecation_warning,
SymPyDeprecationWarning,
ignore_warnings)
from sympy.utilities.iterables import iterable
from sympy.utilities.misc import debug
##########################################################################
# 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 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 _try_directly(self, **hints):
T = None
try_directly = not any(func.has(self.function_variable)
for func in self.function.atoms(AppliedUndef))
if try_directly:
try:
T = self._compute_transform(self.function,
self.function_variable, self.transform_variable, **hints)
except IntegralTransformError:
T = None
fn = self.function
if not fn.is_Add:
fn = expand_mul(fn)
return fn, T
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, do not 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)``.
"""
needeval = hints.pop('needeval', False)
simplify = hints.pop('simplify', True)
hints['simplify'] = simplify
fn, T = self._try_directly(**hints)
if T is not None:
return T
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:]]
if simplify==True:
res = Add(*ress).simplify()
else:
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
def _simplify(expr, doit):
if doit:
from sympy.simplify import simplify
from sympy.simplify.powsimp import powdenest
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):
@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, S.Zero, S.Infinity))
@_noconds
def _mellin_transform(f, x, s_, integrator=_default_integrator, simplify=True):
""" Backend function to compute Mellin transforms. """
# 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), (S.NegativeInfinity, S.Infinity), 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.
"""
from sympy.solvers.inequalities import _solve_inequality
a = S.NegativeInfinity
b = S.Infinity
aux = S.true
conds = conjuncts(to_cnf(cond))
t = Dummy('t', real=True)
for c in conds:
a_ = S.Infinity
b_ = S.NegativeInfinity
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_ is not S.Infinity and a_ != b:
a = Max(a_, a)
elif b_ is not S.NegativeInfinity 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, S.Zero, S.Infinity))
def _collapse_extra(self, extra):
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 import mellin_transform, 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.
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)
"""
# 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 S.Infinity:
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 not (all(x.is_Rational for x in s_multipliers) and
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. """
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:
from sympy.simplify import hyperexpand
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):
# IntegralTransform's doit will cause this hint to exist, but
# InverseMellinTransform should ignore it
hints.pop('simplify', True)
global _allowed
if _allowed is None:
_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):
c = self.__class__._c
return Integral(F*x**(-s), (s, c - S.ImaginaryUnit*S.Infinity, c +
S.ImaginaryUnit*S.Infinity))/(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 import inverse_mellin_transform, 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)/2
>>> inverse_mellin_transform(f, s, x, (-1, 1))
-x*Heaviside(1 - x)/2 - Heaviside(x - 1)/(2*x)
>>> inverse_mellin_transform(f, s, x, (1, oo))
(1/2 - x**2/2)*Heaviside(1 - x)/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)
"""
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 in (True, False):
return True
return Unequality(x, y)
def repl(ex, *args):
if ex in (True, False):
return bool(ex)
return ex.replace(*args)
from sympy.simplify.radsimp import collect_abs
expr = collect_abs(expr)
expr = repl(expr, Lt, replie)
expr = repl(expr, Gt, 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.
This backend assumes that the frontend has already split sums
such that `f` is to an addition anymore.
"""
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, S.Zero, S.Infinity)),
Add(*deltazero))
if not F.has(Integral):
return _simplify(F.subs(s, s_), simplify), S.NegativeInfinity, 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. """
from sympy.solvers.inequalities import _solve_inequality
a = S.NegativeInfinity
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(periodic_argument((s + w3)**p*q, w1)) < w2,
Abs(periodic_argument((s + w3)**p*q, w1)) <= w2,
Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) < w2,
Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) <= w2)
for c in conds:
a_ = S.Infinity
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(periodic_argument(s**w1*w5, q))*w2)*Abs(s**w3)**w4 < 0)
if not m:
m = d.match(
p - cos(Abs(periodic_argument(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_ is not S.Infinity:
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] is not S.NegativeInfinity]
if not conds2:
conds2 = [x for x in conds if x[1] != False]
conds = list(ordered(conds2))
def cnt(expr):
if expr in (True, 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))
def _laplace_deep_collect(f, t):
"""
This is an internal helper function that traverses through the epression
tree of `f(t)` and collects arguments. The purpose of it is that
anything like `f(w*t-1*t-c)` will be written as `f((w-1)*t-c)` such that
it can match `f(a*t+b)`.
"""
func = f.func
args = list(f.args)
if len(f.args) == 0:
return f
else:
for k in range(len(args)):
args[k] = _laplace_deep_collect(args[k], t)
if func.is_Add:
return func(*args).collect(t)
else:
return func(*args)
def _laplace_build_rules(t, s):
"""
This is an internal helper function that returns the table of Laplace
transfrom rules in terms of the time variable `t` and the frequency
variable `s`. It is used by `_laplace_apply_rules`.
"""
a = Wild('a', exclude=[t])
b = Wild('b', exclude=[t])
n = Wild('n', exclude=[t])
tau = Wild('tau', exclude=[t])
omega = Wild('omega', exclude=[t])
dco = lambda f: _laplace_deep_collect(f,t)
laplace_transform_rules = [
# ( time domain,
# laplace domain,
# condition, convergence plane, preparation function )
#
# Catch constant (would otherwise be treated by 2.12)
(a, a/s, S.true, S.Zero, dco),
# DiracDelta rules
(DiracDelta(a*t-b),
exp(-s*b/a)/Abs(a),
Or(And(a>0, b>=0), And(a<0, b<=0)), S.Zero, dco),
(DiracDelta(a*t-b),
S(0),
Or(And(a<0, b>=0), And(a>0, b<=0)), S.Zero, dco),
# Rules from http://eqworld.ipmnet.ru/en/auxiliary/inttrans/
# 2.1
(1,
1/s,
S.true, S.Zero, dco),
# 2.2 expressed in terms of Heaviside
(Heaviside(a*t-b),
exp(-s*b/a)/s,
And(a>0, b>0), S.Zero, dco),
(Heaviside(a*t-b),
(1-exp(-s*b/a))/s,
And(a<0, b<0), S.Zero, dco),
(Heaviside(a*t-b),
1/s,
And(a>0, b<=0), S.Zero, dco),
(Heaviside(a*t-b),
0,
And(a<0, b>0), S.Zero, dco),
# 2.3
(t,
1/s**2,
S.true, S.Zero, dco),
# 2.4
(1/(a*t+b),
-exp(-b/a*s)*Ei(-b/a*s)/a,
a>0, S.Zero, dco),
# 2.5 and 2.6 are covered by 2.11
# 2.7
(1/sqrt(a*t+b),
sqrt(a*pi/s)*exp(b/a*s)*erfc(sqrt(b/a*s))/a,
a>0, S.Zero, dco),
# 2.8
(sqrt(t)/(t+b),
sqrt(pi/s)-pi*sqrt(b)*exp(b*s)*erfc(sqrt(b*s)),
S.true, S.Zero, dco),
# 2.9
((a*t+b)**(-S(3)/2),
2*b**(-S(1)/2)-2*(pi*s/a)**(S(1)/2)*exp(b/a*s)*erfc(sqrt(b/a*s))/a,
a>0, S.Zero, dco),
# 2.10
(t**(S(1)/2)*(t+a)**(-1),
(pi/s)**(S(1)/2)-pi*a**(S(1)/2)*exp(a*s)*erfc(sqrt(a*s)),
S.true, S.Zero, dco),
# 2.11
(1/(a*sqrt(t) + t**(3/2)),
pi*a**(S(1)/2)*exp(a*s)*erfc(sqrt(a*s)),
S.true, S.Zero, dco),
# 2.12
(t**n,
gamma(n+1)/s**(n+1),
n>-1, S.Zero, dco),
# 2.13
((a*t+b)**n,
lowergamma(n+1, b/a*s)*exp(-b/a*s)/s**(n+1)/a,
And(n>-1, a>0), S.Zero, dco),
# 2.14
(t**n/(t+a),
a**n*gamma(n+1)*lowergamma(-n,a*s),
n>-1, S.Zero, dco),
# 3.1
(exp(a*t-tau),
exp(-tau)/(s-a),
S.true, a, dco),
# 3.2
(t*exp(a*t-tau),
exp(-tau)/(s-a)**2,
S.true, a, dco),
# 3.3
(t**n*exp(a*t),
gamma(n+1)/(s-a)**(n+1),
n>-1, a, dco),
# 3.4 and 3.5 cannot be covered here because they are
# sums and only the individual sum terms will get here.
# 3.6
(exp(-a*t**2),
sqrt(pi/4/a)*exp(s**2/4/a)*erfc(s/sqrt(4*a)),
a>0, S.Zero, dco),
# 3.7
(t*exp(-a*t**2),
1/(2*a)-2/sqrt(pi)/(4*a)**(S(3)/2)*s*erfc(s/sqrt(4*a)),
S.true, S.Zero, dco),
# 3.8
(exp(-a/t),
2*sqrt(a/s)*besselk(1, 2*sqrt(a*s)),
a>=0, S.Zero, dco),
# 3.9
(sqrt(t)*exp(-a/t),
S(1)/2*sqrt(pi/s**3)*(1+2*sqrt(a*s))*exp(-2*sqrt(a*s)),
a>=0, S.Zero, dco),
# 3.10
(exp(-a/t)/sqrt(t),
sqrt(pi/s)*exp(-2*sqrt(a*s)),
a>=0, S.Zero, dco),
# 3.11
(exp(-a/t)/(t*sqrt(t)),
sqrt(pi/a)*exp(-2*sqrt(a*s)),
a>0, S.Zero, dco),
# 3.12
(t**n*exp(-a/t),
2*(a/s)**((n+1)/2)*besselk(n+1, 2*sqrt(a*s)),
a>0, S.Zero, dco),
# 3.13
(exp(-2*sqrt(a*t)),
s**(-1)-sqrt(pi*a)*s**(-S(3)/2)*exp(a/s)*erfc(sqrt(a/s)),
S.true, S.Zero, dco),
# 3.14
(exp(-2*sqrt(a*t))/sqrt(t),
(pi/s)**(S(1)/2)*exp(a/s)*erfc(sqrt(a/s)),
S.true, S.Zero, dco),
# 4.1
(sinh(a*t),
a/(s**2-a**2),
S.true, Abs(a), dco),
# 4.2
(sinh(a*t)**2,
2*a**2/(s**3-4*a**2*s**2),
S.true, Abs(2*a), dco),
# 4.3
(sinh(a*t)/t,
log((s+a)/(s-a))/2,
S.true, a, dco),
# 4.4
(t**n*sinh(a*t),
gamma(n+1)/2*((s-a)**(-n-1)-(s+a)**(-n-1)),
n>-2, Abs(a), dco),
# 4.5
(sinh(2*sqrt(a*t)),
sqrt(pi*a)/s/sqrt(s)*exp(a/s),
S.true, S.Zero, dco),
# 4.6
(sqrt(t)*sinh(2*sqrt(a*t)),
pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*exp(a/s)*erf(sqrt(a/s))-a**(S(1)/2)*s**(-2),
S.true, S.Zero, dco),
# 4.7
(sinh(2*sqrt(a*t))/sqrt(t),
pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s)*erf(sqrt(a/s)),
S.true, S.Zero, dco),
# 4.8
(sinh(sqrt(a*t))**2/sqrt(t),
pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)-1),
S.true, S.Zero, dco),
# 4.9
(cosh(a*t),
s/(s**2-a**2),
S.true, Abs(a), dco),
# 4.10
(cosh(a*t)**2,
(s**2-2*a**2)/(s**3-4*a**2*s**2),
S.true, Abs(2*a), dco),
# 4.11
(t**n*cosh(a*t),
gamma(n+1)/2*((s-a)**(-n-1)+(s+a)**(-n-1)),
n>-1, Abs(a), dco),
# 4.12
(cosh(2*sqrt(a*t)),
1/s+sqrt(pi*a)/s/sqrt(s)*exp(a/s)*erf(sqrt(a/s)),
S.true, S.Zero, dco),
# 4.13
(sqrt(t)*cosh(2*sqrt(a*t)),
pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*exp(a/s),
S.true, S.Zero, dco),
# 4.14
(cosh(2*sqrt(a*t))/sqrt(t),
pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s),
S.true, S.Zero, dco),
# 4.15
(cosh(sqrt(a*t))**2/sqrt(t),
pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)+1),
S.true, S.Zero, dco),
# 5.1
(log(a*t),
-log(s/a+S.EulerGamma)/s,
a>0, S.Zero, dco),
# 5.2
(log(1+a*t),
-exp(s/a)/s*Ei(-s/a),
S.true, S.Zero, dco),
# 5.3
(log(a*t+b),
(log(b)-exp(s/b/a)/s*a*Ei(-s/b))/s*a,
a>0, S.Zero, dco),
# 5.4 is covered by 5.7
# 5.5
(log(t)/sqrt(t),
-sqrt(pi/s)*(log(4*s)+S.EulerGamma),
S.true, S.Zero, dco),
# 5.6 is covered by 5.7
# 5.7
(t**n*log(t),
gamma(n+1)*s**(-n-1)*(digamma(n+1)-log(s)),
n>-1, S.Zero, dco),
# 5.8
(log(a*t)**2,
((log(s/a)+S.EulerGamma)**2+pi**2/6)/s,
a>0, S.Zero, dco),
# 5.9
(exp(-a*t)*log(t),
-(log(s+a)+S.EulerGamma)/(s+a),
S.true, -a, dco),
# 6.1
(sin(omega*t),
omega/(s**2+omega**2),
S.true, S.Zero, dco),
# 6.2
(Abs(sin(omega*t)),
omega/(s**2+omega**2)*coth(pi*s/2/omega),
omega>0, S.Zero, dco),
# 6.3 and 6.4 are covered by 1.8
# 6.5 is covered by 1.8 together with 2.5
# 6.6
(sin(omega*t)/t,
atan(omega/s),
S.true, S.Zero, dco),
# 6.7
(sin(omega*t)**2/t,
log(1+4*omega**2/s**2)/4,
S.true, S.Zero, dco),
# 6.8
(sin(omega*t)**2/t**2,
omega*atan(2*omega/s)-s*log(1+4*omega**2/s**2)/4,
S.true, S.Zero, dco),
# 6.9
(sin(2*sqrt(a*t)),
sqrt(pi*a)/s/sqrt(s)*exp(-a/s),
a>0, S.Zero, dco),
# 6.10
(sin(2*sqrt(a*t))/t,
pi*erf(sqrt(a/s)),
a>0, S.Zero, dco),
# 6.11
(cos(omega*t),
s/(s**2+omega**2),
S.true, S.Zero, dco),
# 6.12
(cos(omega*t)**2,
(s**2+2*omega**2)/(s**2+4*omega**2)/s,
S.true, S.Zero, dco),
# 6.13 is covered by 1.9 together with 2.5
# 6.14 and 6.15 cannot be done with this method, the respective sum
# parts do not converge. Solve elsewhere if really needed.
# 6.16
(sqrt(t)*cos(2*sqrt(a*t)),
sqrt(pi)/2*s**(-S(5)/2)*(s-2*a)*exp(-a/s),
a>0, S.Zero, dco),
# 6.17
(cos(2*sqrt(a*t))/sqrt(t),
sqrt(pi/s)*exp(-a/s),
a>0, S.Zero, dco),
# 6.18
(sin(a*t)*sin(b*t),
2*a*b*s/(s**2+(a+b)**2)/(s**2+(a-b)**2),
S.true, S.Zero, dco),
# 6.19
(cos(a*t)*sin(b*t),
b*(s**2-a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2),
S.true, S.Zero, dco),
# 6.20
(cos(a*t)*cos(b*t),
s*(s**2+a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2),
S.true, S.Zero, dco),
# 6.21
(exp(b*t)*sin(a*t),
a/((s-b)**2+a**2),
S.true, b, dco),
# 6.22
(exp(b*t)*cos(a*t),
(s-b)/((s-b)**2+a**2),
S.true, b, dco),
# 7.1
(erf(a*t),
exp(s**2/(2*a)**2)*erfc(s/(2*a))/s,
a>0, S.Zero, dco),
# 7.2
(erf(sqrt(a*t)),
sqrt(a)/sqrt(s+a)/s,
a>0, S.Zero, dco),
# 7.3
(exp(a*t)*erf(sqrt(a*t)),
sqrt(a)/sqrt(s)/(s-a),
a>0, a, dco),
# 7.4
(erf(sqrt(a/t)/2),
(1-exp(-sqrt(a*s)))/s,
a>0, S.Zero, dco),
# 7.5
(erfc(sqrt(a*t)),
(sqrt(s+a)-sqrt(a))/sqrt(s+a)/s,
a>0, S.Zero, dco),
# 7.6
(exp(a*t)*erfc(sqrt(a*t)),
1/(s+sqrt(a*s)),
a>0, S.Zero, dco),
# 7.7
(erfc(sqrt(a/t)/2),
exp(-sqrt(a*s))/s,
a>0, S.Zero, dco),
# 8.1, 8.2
(besselj(n, a*t),
a**n/(sqrt(s**2+a**2)*(s+sqrt(s**2+a**2))**n),
And(a>0, n>-1), S.Zero, dco),
# 8.3, 8.4
(t**b*besselj(n, a*t),
2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2+a**2)**(-n-S.Half),
And(And(a>0, n>-S.Half), Eq(b, n)), S.Zero, dco),
# 8.5
(t**b*besselj(n, a*t),
2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2+a**2)**(-n-S(3)/2),
And(And(a>0, n>-1), Eq(b, n+1)), S.Zero, dco),
# 8.6
(besselj(0, 2*sqrt(a*t)),
exp(-a/s)/s,
a>0, S.Zero, dco),
# 8.7, 8.8
(t**(b)*besselj(n, 2*sqrt(a*t)),
a**(n/2)*s**(-n-1)*exp(-a/s),
And(And(a>0, n>-1), Eq(b, n*S.Half)), S.Zero, dco),
# 8.9
(besselj(0, a*sqrt(t**2+b*t)),
exp(b*s-b*sqrt(s**2+a**2))/sqrt(s**2+a**2),
b>0, S.Zero, dco),
# 8.10, 8.11
(besseli(n, a*t),
a**n/(sqrt(s**2-a**2)*(s+sqrt(s**2-a**2))**n),
And(a>0, n>-1), Abs(a), dco),
# 8.12
(t**b*besseli(n, a*t),
2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2-a**2)**(-n-S.Half),
And(And(a>0, n>-S.Half), Eq(b, n)), Abs(a), dco),
# 8.13
(t**b*besseli(n, a*t),
2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2-a**2)**(-n-S(3)/2),
And(And(a>0, n>-1), Eq(b, n+1)), Abs(a), dco),
# 8.15, 8.16
(t**(b)*besseli(n, 2*sqrt(a*t)),
a**(n/2)*s**(-n-1)*exp(a/s),
And(And(a>0, n>-1), Eq(b, n*S.Half)), S.Zero, dco),
# 8.17
(bessely(0, a*t),
-2/pi*asinh(s/a)/sqrt(s**2+a**2),
a>0, S.Zero, dco),
# 8.18
(besselk(0, a*t),
(log(s+sqrt(s**2-a**2)))/(sqrt(s**2-a**2)),
a>0, Abs(a), dco)
]
return laplace_transform_rules
def _laplace_cr(f, a, c, **hints):
"""
Internal helper function that will return `(f, a, c)` unless `**hints`
contains `noconds=True`, in which case it will only return `f`.
"""
conds = not hints.get('noconds', False)
if conds:
return f, a, c
else:
return f
def _laplace_rule_timescale(f, t, s, doit=True, **hints):
r"""
This internal helper function tries to apply the time-scaling rule of the
Laplace transform and returns `None` if it cannot do it.
Time-scaling means the following: if $F(s)$ is the Laplace transform of,
$f(t)$, then, for any $a>0$, the Laplace transform of $f(at)$ will be
$\frac1a F(\frac{s}{a})$. This scaling will also affect the transform's
convergence plane.
"""
_simplify = hints.pop('simplify', True)
b = Wild('b', exclude=[t])
g = WildFunction('g', nargs=1)
k, func = f.as_independent(t, as_Add=False)
ma1 = func.match(g)
if ma1:
arg = ma1[g].args[0].collect(t)
ma2 = arg.match(b*t)
if ma2 and ma2[b]>0:
debug('_laplace_apply_rules match:')
debug(' f: %s ( %s, %s )'%(f, ma1, ma2))
debug(' rule: amplitude and time scaling (1.1, 1.2)')
if ma2[b]==1:
if doit==True and not any(func.has(t) for func
in ma1[g].atoms(AppliedUndef)):
return k*_laplace_transform(ma1[g].func(t), t, s,
simplify=_simplify)
else:
return k*LaplaceTransform(ma1[g].func(t), t, s, **hints)
else:
L = _laplace_apply_rules(ma1[g].func(t), t, s/ma2[b],
doit=doit, **hints)
try:
r, p, c = L
return (k/ma2[b]*r, p, c)
except TypeError:
return k/ma2[b]*L
return None
def _laplace_rule_heaviside(f, t, s, doit=True, **hints):
"""
This internal helper function tries to transform a product containing the
`Heaviside` function and returns `None` if it cannot do it.
"""
hints.pop('simplify', True)
a = Wild('a', exclude=[t])
b = Wild('b', exclude=[t])
y = Wild('y')
g = WildFunction('g', nargs=1)
k, func = f.as_independent(t, as_Add=False)
ma1 = func.match(Heaviside(y)*g)
if ma1:
ma2 = ma1[y].match(t-a)
ma3 = ma1[g].args[0].collect(t).match(t-b)
if ma2 and ma2[a]>0 and ma3 and ma2[a]==ma3[b]:
debug('_laplace_apply_rules match:')
debug(' f: %s ( %s, %s, %s )'%(f, ma1, ma2, ma3))
debug(' rule: time shift (1.3)')
L = _laplace_apply_rules(ma1[g].func(t), t, s, doit=doit, **hints)
try:
r, p, c = L
return (k*exp(-ma2[a]*s)*r, p, c)
except TypeError:
return k*exp(-ma2[a]*s)*L
return None
def _laplace_rule_exp(f, t, s, doit=True, **hints):
"""
This internal helper function tries to transform a product containing the
`exp` function and returns `None` if it cannot do it.
"""
hints.pop('simplify', True)
a = Wild('a', exclude=[t])
y = Wild('y')
z = Wild('z')
k, func = f.as_independent(t, as_Add=False)
ma1 = func.match(exp(y)*z)
if ma1:
ma2 = ma1[y].collect(t).match(a*t)
if ma2:
debug('_laplace_apply_rules match:')
debug(' f: %s ( %s, %s )'%(f, ma1, ma2))
debug(' rule: multiply with exp (1.5)')
L = _laplace_apply_rules(ma1[z], t, s-ma2[a], doit=doit, **hints)
try:
r, p, c = L
return (r, p+ma2[a], c)
except TypeError:
return L
return None
def _laplace_rule_trig(f, t, s, doit=True, **hints):
"""
This internal helper function tries to transform a product containing a
trigonometric function (`sin`, `cos`, `sinh`, `cosh`, ) and returns
`None` if it cannot do it.
"""
_simplify = hints.pop('simplify', True)
a = Wild('a', exclude=[t])
y = Wild('y')
z = Wild('z')
k, func = f.as_independent(t, as_Add=False)
# All of the rules have a very similar form: trig(y)*z is matched, and then
# two copies of the Laplace transform of z are shifted in the s Domain
# and added with a weight; see rules 1.6 to 1.9 in
# http://eqworld.ipmnet.ru/en/auxiliary/inttrans/laplace1.pdf
# The parameters in the tuples are (fm, nu, s1, s2, sd):
# fm: Function to match
# nu: Number of the rule, for debug purposes
# s1: weight of the sum, 'I' for sin and '1' for all others
# s2: sign of the second copy of the Laplace transform of z
# sd: shift direction; shift along real or imaginary axis if `1` or `I`
trigrules = [(sinh(y), '1.6', 1, -1, 1), (cosh(y), '1.7', 1, 1, 1),
(sin(y), '1.8', -I, -1, I), (cos(y), '1.9', 1, 1, I)]
for trigrule in trigrules:
fm, nu, s1, s2, sd = trigrule
ma1 = func.match(fm*z)
if ma1:
ma2 = ma1[y].collect(t).match(a*t)
if ma2:
debug('_laplace_apply_rules match:')
debug(' f: %s ( %s, %s )'%(f, ma1, ma2))
debug(' rule: multiply with %s (%s)'%(fm.func, nu))
L = _laplace_apply_rules(ma1[z], t, s, doit=doit, **hints)
try:
r, p, c = L
# The convergence plane changes only if the shift has been
# done along the real axis:
if sd==1:
cp_shift = Abs(ma2[a])
else:
cp_shift = 0
return ((s1*(r.subs(s, s-sd*ma2[a])+\
s2*r.subs(s, s+sd*ma2[a]))).simplify()/2,
p+cp_shift, c)
except TypeError:
if doit==True and _simplify==True:
return (s1*(L.subs(s, s-sd*ma2[a])+\
s2*L.subs(s, s+sd*ma2[a]))).simplify()/2
else:
return (s1*(L.subs(s, s-sd*ma2[a])+\
s2*L.subs(s, s+sd*ma2[a])))/2
return None
def _laplace_rule_diff(f, t, s, doit=True, **hints):
"""
This internal helper function tries to transform an expression containing
a derivative of an undefined function and returns `None` if it cannot
do it.
"""
hints.pop('simplify', True)
a = Wild('a', exclude=[t])
y = Wild('y')
n = Wild('n', exclude=[t])
g = WildFunction('g', nargs=1)
ma1 = f.match(a*Derivative(g, (t, n)))
if ma1 and ma1[g].args[0] == t and ma1[n].is_integer:
debug('_laplace_apply_rules match:')
debug(' f: %s'%(f,))
debug(' rule: time derivative (1.11, 1.12)')
d = []
for k in range(ma1[n]):
if k==0:
y = ma1[g].func(t).subs(t, 0)
else:
y = Derivative(ma1[g].func(t), (t, k)).subs(t, 0)
d.append(s**(ma1[n]-k-1)*y)
r = s**ma1[n]*_laplace_apply_rules(ma1[g].func(t), t, s, doit=doit,
**hints)
return r - Add(*d)
return None
def _laplace_apply_rules(f, t, s, doit=True, **hints):
"""
Helper function for the class LaplaceTransform.
This function does a Laplace transform based on rules and, after
applying the rules, hands the rest over to `_laplace_transform`, which
will attempt to integrate.
If it is called with `doit=False`, then it will instead return
`LaplaceTransform` objects.
"""
k, func = f.as_independent(t, as_Add=False)
simple_rules = _laplace_build_rules(t, s)
for t_dom, s_dom, check, plane, prep in simple_rules:
ma = prep(func).match(t_dom)
if ma:
debug('_laplace_apply_rules match:')
debug(' f: %s'%(func,))
debug(' rule: %s o---o %s'%(t_dom, s_dom))
try:
debug(' try %s'%(check,))
c = check.xreplace(ma)
debug(' check %s -> %s'%(check, c))
if c==True:
return _laplace_cr(k*s_dom.xreplace(ma),
plane.xreplace(ma), S.true, **hints)
except Exception:
debug('_laplace_apply_rules did not match.')
if f.has(DiracDelta):
return None
prog_rules = [_laplace_rule_timescale, _laplace_rule_heaviside,
_laplace_rule_exp, _laplace_rule_trig, _laplace_rule_diff]
for p_rule in prog_rules:
LT = p_rule(f, t, s, doit=doit, **hints)
if LT is not None:
return LT
return None
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):
LT = _laplace_apply_rules(f, t, s, **hints)
if LT is None:
_simplify = hints.pop('simplify', True)
debug('_laplace_apply_rules could not match function %s'%(f,))
debug(' hints: %s'%(hints,))
return _laplace_transform(f, t, s, simplify=_simplify, **hints)
else:
return LT
def _as_integral(self, f, t, s):
return Integral(f*exp(-s*t), (t, S.Zero, S.Infinity))
def _collapse_extra(self, extra):
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 _try_directly(self, **hints):
fn = self.function
debug('----> _try_directly: %s'%(fn, ))
t_ = self.function_variable
s_ = self.transform_variable
LT = None
if not fn.is_Add:
fn = expand_mul(fn)
try:
LT = self._compute_transform(fn, t_, s_, **hints)
except IntegralTransformError:
LT = None
return fn, LT
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
.. math :: a < \operatorname{Re}(s)
This function returns ``(F, a, cond)`` where ``F`` is the Laplace
transform of ``f``, `a` is the half-plane of convergence, and `cond` are
auxiliary convergence conditions.
The implementation is rule-based, and if you are interested in which
rules are applied, and whether integration is attemped, you can switch
debug information on by setting ``sympy.SYMPY_DEBUG=True``.
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 implicitly as
.. math :: F(s) = \lim_{\tau\to 0^{-}} \int_{\tau}^\infty e^{-st} f(t) \mathrm{d}t
by applying rules.
If the integral cannot be fully 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 import DiracDelta, exp, laplace_transform
>>> from sympy.abc import t, s, a
>>> laplace_transform(t**4, t, s)
(24/s**5, 0, True)
>>> 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)
(s/(a + s), Max(0, -a), True)
See Also
========
inverse_laplace_transform, mellin_transform, fourier_transform
hankel_transform, inverse_hankel_transform
"""
debug('\n***** laplace_transform(%s, %s, %s)'%(f, t, s))
if isinstance(f, MatrixBase) and hasattr(f, 'applyfunc'):
conds = not hints.get('noconds', False)
if conds and legacy_matrix:
sympy_deprecation_warning(
"""
Calling laplace_transform() on a Matrix with noconds=False (the default) is
deprecated. Either noconds=True or use legacy_matrix=False to get the new
behavior.
""",
deprecated_since_version="1.9",
active_deprecations_target="deprecated-laplace-transform-matrix",
)
# Temporarily disable the deprecation warning for non-Expr objects
# in Matrix
with ignore_warnings(SymPyDeprecationWarning):
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.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, S.Infinity),
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)
from sympy.solvers.inequalities import _solve_inequality
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):
c = self.__class__._c
return Integral(exp(s*t)*F, (s, c - S.ImaginaryUnit*S.Infinity,
c + S.ImaginaryUnit*S.Infinity))/(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 import inverse_laplace_transform, 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)
See Also
========
laplace_transform, _fast_inverse_laplace
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)
def _fast_inverse_laplace(e, s, t):
"""Fast inverse Laplace transform of rational function including RootSum"""
a, b, n = symbols('a, b, n', cls=Wild, exclude=[s])
def _ilt(e):
if not e.has(s):
return e
elif e.is_Add:
return _ilt_add(e)
elif e.is_Mul:
return _ilt_mul(e)
elif e.is_Pow:
return _ilt_pow(e)
elif isinstance(e, RootSum):
return _ilt_rootsum(e)
else:
raise NotImplementedError
def _ilt_add(e):
return e.func(*map(_ilt, e.args))
def _ilt_mul(e):
coeff, expr = e.as_independent(s)
if expr.is_Mul:
raise NotImplementedError
return coeff * _ilt(expr)
def _ilt_pow(e):
match = e.match((a*s + b)**n)
if match is not None:
nm, am, bm = match[n], match[a], match[b]
if nm.is_Integer and nm < 0:
return t**(-nm-1)*exp(-(bm/am)*t)/(am**-nm*gamma(-nm))
if nm == 1:
return exp(-(bm/am)*t) / am
raise NotImplementedError
def _ilt_rootsum(e):
expr = e.fun.expr
[variable] = e.fun.variables
return RootSum(e.poly, Lambda(variable, together(_ilt(expr))))
return _ilt(e)
##########################################################################
# 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.
"""
F = integrate(a*f*exp(b*S.ImaginaryUnit*x*k), (x, S.NegativeInfinity, S.Infinity))
if not F.has(Integral):
return _simplify(F, simplify), S.true
integral_f = integrate(f, (x, S.NegativeInfinity, S.Infinity))
if integral_f in (S.NegativeInfinity, S.Infinity, 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):
a = self.a()
b = self.b()
return Integral(a*f*exp(b*S.ImaginaryUnit*x*k), (x, S.NegativeInfinity, S.Infinity))
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
##########################################################################
@_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, S.Zero, S.Infinity))
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, S.Zero, S.Infinity))
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 S.One
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 S.One
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 S.One
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 S.One
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.
"""
F = integrate(f*besselj(nu, k*r)*r, (r, S.Zero, S.Infinity))
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):
return Integral(f*besselj(nu, k*r)*r, (r, S.Zero, S.Infinity))
@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)
|
4b73d450bd77962cba837e73bb48bba5ebff34242ff49fc8d8fe99a2fc7a9ab1 | """
Module to implement integration of uni/bivariate polynomials over
2D Polytopes and uni/bi/trivariate polynomials over 3D Polytopes.
Uses evaluation techniques as described in Chin et al. (2015) [1].
References
===========
.. [1] Chin, Eric B., Jean B. Lasserre, and N. Sukumar. "Numerical integration
of homogeneous functions on convex and nonconvex polygons and polyhedra."
Computational Mechanics 56.6 (2015): 967-981
PDF link : http://dilbert.engr.ucdavis.edu/~suku/quadrature/cls-integration.pdf
"""
from functools import cmp_to_key
from sympy.abc import x, y, z
from sympy.core import S, diff, Expr, Symbol
from sympy.core.sympify import _sympify
from sympy.geometry import Segment2D, Polygon, Point, Point2D
from sympy.polys.polytools import LC, gcd_list, degree_list
from sympy.simplify.simplify import nsimplify
def polytope_integrate(poly, expr=None, *, clockwise=False, max_degree=None):
"""Integrates polynomials over 2/3-Polytopes.
Explanation
===========
This function accepts the polytope in ``poly`` and the function in ``expr``
(uni/bi/trivariate polynomials are implemented) and returns
the exact integral of ``expr`` over ``poly``.
Parameters
==========
poly : The input Polygon.
expr : The input polynomial.
clockwise : Binary value to sort input points of 2-Polytope clockwise.(Optional)
max_degree : The maximum degree of any monomial of the input polynomial.(Optional)
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import Point, Polygon
>>> from sympy.integrals.intpoly import polytope_integrate
>>> polygon = Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0))
>>> polys = [1, x, y, x*y, x**2*y, x*y**2]
>>> expr = x*y
>>> polytope_integrate(polygon, expr)
1/4
>>> polytope_integrate(polygon, polys, max_degree=3)
{1: 1, x: 1/2, y: 1/2, x*y: 1/4, x*y**2: 1/6, x**2*y: 1/6}
"""
if clockwise:
if isinstance(poly, Polygon):
poly = Polygon(*point_sort(poly.vertices), evaluate=False)
else:
raise TypeError("clockwise=True works for only 2-Polytope"
"V-representation input")
if isinstance(poly, Polygon):
# For Vertex Representation(2D case)
hp_params = hyperplane_parameters(poly)
facets = poly.sides
elif len(poly[0]) == 2:
# For Hyperplane Representation(2D case)
plen = len(poly)
if len(poly[0][0]) == 2:
intersections = [intersection(poly[(i - 1) % plen], poly[i],
"plane2D")
for i in range(0, plen)]
hp_params = poly
lints = len(intersections)
facets = [Segment2D(intersections[i],
intersections[(i + 1) % lints])
for i in range(0, lints)]
else:
raise NotImplementedError("Integration for H-representation 3D"
"case not implemented yet.")
else:
# For Vertex Representation(3D case)
vertices = poly[0]
facets = poly[1:]
hp_params = hyperplane_parameters(facets, vertices)
if max_degree is None:
if expr is None:
raise TypeError('Input expression be must'
'be a valid SymPy expression')
return main_integrate3d(expr, facets, vertices, hp_params)
if max_degree is not None:
result = {}
if not isinstance(expr, list) and expr is not None:
raise TypeError('Input polynomials must be list of expressions')
if len(hp_params[0][0]) == 3:
result_dict = main_integrate3d(0, facets, vertices, hp_params,
max_degree)
else:
result_dict = main_integrate(0, facets, hp_params, max_degree)
if expr is None:
return result_dict
for poly in expr:
poly = _sympify(poly)
if poly not in result:
if poly.is_zero:
result[S.Zero] = S.Zero
continue
integral_value = S.Zero
monoms = decompose(poly, separate=True)
for monom in monoms:
monom = nsimplify(monom)
coeff, m = strip(monom)
integral_value += result_dict[m] * coeff
result[poly] = integral_value
return result
if expr is None:
raise TypeError('Input expression be must'
'be a valid SymPy expression')
return main_integrate(expr, facets, hp_params)
def strip(monom):
if monom.is_zero:
return S.Zero, S.Zero
elif monom.is_number:
return monom, S.One
else:
coeff = LC(monom)
return coeff, monom / coeff
def main_integrate3d(expr, facets, vertices, hp_params, max_degree=None):
"""Function to translate the problem of integrating uni/bi/tri-variate
polynomials over a 3-Polytope to integrating over its faces.
This is done using Generalized Stokes' Theorem and Euler's Theorem.
Parameters
==========
expr :
The input polynomial.
facets :
Faces of the 3-Polytope(expressed as indices of `vertices`).
vertices :
Vertices that constitute the Polytope.
hp_params :
Hyperplane Parameters of the facets.
max_degree : optional
Max degree of constituent monomial in given list of polynomial.
Examples
========
>>> from sympy.integrals.intpoly import main_integrate3d, \
hyperplane_parameters
>>> cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
[3, 1, 0, 2], [0, 4, 6, 2]]
>>> vertices = cube[0]
>>> faces = cube[1:]
>>> hp_params = hyperplane_parameters(faces, vertices)
>>> main_integrate3d(1, faces, vertices, hp_params)
-125
"""
result = {}
dims = (x, y, z)
dim_length = len(dims)
if max_degree:
grad_terms = gradient_terms(max_degree, 3)
flat_list = [term for z_terms in grad_terms
for x_term in z_terms
for term in x_term]
for term in flat_list:
result[term[0]] = 0
for facet_count, hp in enumerate(hp_params):
a, b = hp[0], hp[1]
x0 = vertices[facets[facet_count][0]]
for i, monom in enumerate(flat_list):
# Every monomial is a tuple :
# (term, x_degree, y_degree, z_degree, value over boundary)
expr, x_d, y_d, z_d, z_index, y_index, x_index, _ = monom
degree = x_d + y_d + z_d
if b.is_zero:
value_over_face = S.Zero
else:
value_over_face = \
integration_reduction_dynamic(facets, facet_count, a,
b, expr, degree, dims,
x_index, y_index,
z_index, x0, grad_terms,
i, vertices, hp)
monom[7] = value_over_face
result[expr] += value_over_face * \
(b / norm(a)) / (dim_length + x_d + y_d + z_d)
return result
else:
integral_value = S.Zero
polynomials = decompose(expr)
for deg in polynomials:
poly_contribute = S.Zero
facet_count = 0
for i, facet in enumerate(facets):
hp = hp_params[i]
if hp[1].is_zero:
continue
pi = polygon_integrate(facet, hp, i, facets, vertices, expr, deg)
poly_contribute += pi *\
(hp[1] / norm(tuple(hp[0])))
facet_count += 1
poly_contribute /= (dim_length + deg)
integral_value += poly_contribute
return integral_value
def main_integrate(expr, facets, hp_params, max_degree=None):
"""Function to translate the problem of integrating univariate/bivariate
polynomials over a 2-Polytope to integrating over its boundary facets.
This is done using Generalized Stokes's Theorem and Euler's Theorem.
Parameters
==========
expr :
The input polynomial.
facets :
Facets(Line Segments) of the 2-Polytope.
hp_params :
Hyperplane Parameters of the facets.
max_degree : optional
The maximum degree of any monomial of the input polynomial.
>>> from sympy.abc import x, y
>>> from sympy.integrals.intpoly import main_integrate,\
hyperplane_parameters
>>> from sympy import Point, Polygon
>>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
>>> facets = triangle.sides
>>> hp_params = hyperplane_parameters(triangle)
>>> main_integrate(x**2 + y**2, facets, hp_params)
325/6
"""
dims = (x, y)
dim_length = len(dims)
result = {}
integral_value = S.Zero
if max_degree:
grad_terms = [[0, 0, 0, 0]] + gradient_terms(max_degree)
for facet_count, hp in enumerate(hp_params):
a, b = hp[0], hp[1]
x0 = facets[facet_count].points[0]
for i, monom in enumerate(grad_terms):
# Every monomial is a tuple :
# (term, x_degree, y_degree, value over boundary)
m, x_d, y_d, _ = monom
value = result.get(m, None)
degree = S.Zero
if b.is_zero:
value_over_boundary = S.Zero
else:
degree = x_d + y_d
value_over_boundary = \
integration_reduction_dynamic(facets, facet_count, a,
b, m, degree, dims, x_d,
y_d, max_degree, x0,
grad_terms, i)
monom[3] = value_over_boundary
if value is not None:
result[m] += value_over_boundary * \
(b / norm(a)) / (dim_length + degree)
else:
result[m] = value_over_boundary * \
(b / norm(a)) / (dim_length + degree)
return result
else:
polynomials = decompose(expr)
for deg in polynomials:
poly_contribute = S.Zero
facet_count = 0
for hp in hp_params:
value_over_boundary = integration_reduction(facets,
facet_count,
hp[0], hp[1],
polynomials[deg],
dims, deg)
poly_contribute += value_over_boundary * (hp[1] / norm(hp[0]))
facet_count += 1
poly_contribute /= (dim_length + deg)
integral_value += poly_contribute
return integral_value
def polygon_integrate(facet, hp_param, index, facets, vertices, expr, degree):
"""Helper function to integrate the input uni/bi/trivariate polynomial
over a certain face of the 3-Polytope.
Parameters
==========
facet :
Particular face of the 3-Polytope over which ``expr`` is integrated.
index :
The index of ``facet`` in ``facets``.
facets :
Faces of the 3-Polytope(expressed as indices of `vertices`).
vertices :
Vertices that constitute the facet.
expr :
The input polynomial.
degree :
Degree of ``expr``.
Examples
========
>>> from sympy.integrals.intpoly import polygon_integrate
>>> cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
[3, 1, 0, 2], [0, 4, 6, 2]]
>>> facet = cube[1]
>>> facets = cube[1:]
>>> vertices = cube[0]
>>> polygon_integrate(facet, [(0, 1, 0), 5], 0, facets, vertices, 1, 0)
-25
"""
expr = S(expr)
if expr.is_zero:
return S.Zero
result = S.Zero
x0 = vertices[facet[0]]
for i in range(len(facet)):
side = (vertices[facet[i]], vertices[facet[(i + 1) % len(facet)]])
result += distance_to_side(x0, side, hp_param[0]) *\
lineseg_integrate(facet, i, side, expr, degree)
if not expr.is_number:
expr = diff(expr, x) * x0[0] + diff(expr, y) * x0[1] +\
diff(expr, z) * x0[2]
result += polygon_integrate(facet, hp_param, index, facets, vertices,
expr, degree - 1)
result /= (degree + 2)
return result
def distance_to_side(point, line_seg, A):
"""Helper function to compute the signed distance between given 3D point
and a line segment.
Parameters
==========
point : 3D Point
line_seg : Line Segment
Examples
========
>>> from sympy.integrals.intpoly import distance_to_side
>>> point = (0, 0, 0)
>>> distance_to_side(point, [(0, 0, 1), (0, 1, 0)], (1, 0, 0))
-sqrt(2)/2
"""
x1, x2 = line_seg
rev_normal = [-1 * S(i)/norm(A) for i in A]
vector = [x2[i] - x1[i] for i in range(0, 3)]
vector = [vector[i]/norm(vector) for i in range(0, 3)]
n_side = cross_product((0, 0, 0), rev_normal, vector)
vectorx0 = [line_seg[0][i] - point[i] for i in range(0, 3)]
dot_product = sum([vectorx0[i] * n_side[i] for i in range(0, 3)])
return dot_product
def lineseg_integrate(polygon, index, line_seg, expr, degree):
"""Helper function to compute the line integral of ``expr`` over ``line_seg``.
Parameters
===========
polygon :
Face of a 3-Polytope.
index :
Index of line_seg in polygon.
line_seg :
Line Segment.
Examples
========
>>> from sympy.integrals.intpoly import lineseg_integrate
>>> polygon = [(0, 5, 0), (5, 5, 0), (5, 5, 5), (0, 5, 5)]
>>> line_seg = [(0, 5, 0), (5, 5, 0)]
>>> lineseg_integrate(polygon, 0, line_seg, 1, 0)
5
"""
expr = _sympify(expr)
if expr.is_zero:
return S.Zero
result = S.Zero
x0 = line_seg[0]
distance = norm(tuple([line_seg[1][i] - line_seg[0][i] for i in
range(3)]))
if isinstance(expr, Expr):
expr_dict = {x: line_seg[1][0],
y: line_seg[1][1],
z: line_seg[1][2]}
result += distance * expr.subs(expr_dict)
else:
result += distance * expr
expr = diff(expr, x) * x0[0] + diff(expr, y) * x0[1] +\
diff(expr, z) * x0[2]
result += lineseg_integrate(polygon, index, line_seg, expr, degree - 1)
result /= (degree + 1)
return result
def integration_reduction(facets, index, a, b, expr, dims, degree):
"""Helper method for main_integrate. Returns the value of the input
expression evaluated over the polytope facet referenced by a given index.
Parameters
===========
facets :
List of facets of the polytope.
index :
Index referencing the facet to integrate the expression over.
a :
Hyperplane parameter denoting direction.
b :
Hyperplane parameter denoting distance.
expr :
The expression to integrate over the facet.
dims :
List of symbols denoting axes.
degree :
Degree of the homogeneous polynomial.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.integrals.intpoly import integration_reduction,\
hyperplane_parameters
>>> from sympy import Point, Polygon
>>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
>>> facets = triangle.sides
>>> a, b = hyperplane_parameters(triangle)[0]
>>> integration_reduction(facets, 0, a, b, 1, (x, y), 0)
5
"""
expr = _sympify(expr)
if expr.is_zero:
return expr
value = S.Zero
x0 = facets[index].points[0]
m = len(facets)
gens = (x, y)
inner_product = diff(expr, gens[0]) * x0[0] + diff(expr, gens[1]) * x0[1]
if inner_product != 0:
value += integration_reduction(facets, index, a, b,
inner_product, dims, degree - 1)
value += left_integral2D(m, index, facets, x0, expr, gens)
return value/(len(dims) + degree - 1)
def left_integral2D(m, index, facets, x0, expr, gens):
"""Computes the left integral of Eq 10 in Chin et al.
For the 2D case, the integral is just an evaluation of the polynomial
at the intersection of two facets which is multiplied by the distance
between the first point of facet and that intersection.
Parameters
==========
m :
No. of hyperplanes.
index :
Index of facet to find intersections with.
facets :
List of facets(Line Segments in 2D case).
x0 :
First point on facet referenced by index.
expr :
Input polynomial
gens :
Generators which generate the polynomial
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.integrals.intpoly import left_integral2D
>>> from sympy import Point, Polygon
>>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
>>> facets = triangle.sides
>>> left_integral2D(3, 0, facets, facets[0].points[0], 1, (x, y))
5
"""
value = S.Zero
for j in range(0, m):
intersect = ()
if j in ((index - 1) % m, (index + 1) % m):
intersect = intersection(facets[index], facets[j], "segment2D")
if intersect:
distance_origin = norm(tuple(map(lambda x, y: x - y,
intersect, x0)))
if is_vertex(intersect):
if isinstance(expr, Expr):
if len(gens) == 3:
expr_dict = {gens[0]: intersect[0],
gens[1]: intersect[1],
gens[2]: intersect[2]}
else:
expr_dict = {gens[0]: intersect[0],
gens[1]: intersect[1]}
value += distance_origin * expr.subs(expr_dict)
else:
value += distance_origin * expr
return value
def integration_reduction_dynamic(facets, index, a, b, expr, degree, dims,
x_index, y_index, max_index, x0,
monomial_values, monom_index, vertices=None,
hp_param=None):
"""The same integration_reduction function which uses a dynamic
programming approach to compute terms by using the values of the integral
of previously computed terms.
Parameters
==========
facets :
Facets of the Polytope.
index :
Index of facet to find intersections with.(Used in left_integral()).
a, b :
Hyperplane parameters.
expr :
Input monomial.
degree :
Total degree of ``expr``.
dims :
Tuple denoting axes variables.
x_index :
Exponent of 'x' in ``expr``.
y_index :
Exponent of 'y' in ``expr``.
max_index :
Maximum exponent of any monomial in ``monomial_values``.
x0 :
First point on ``facets[index]``.
monomial_values :
List of monomial values constituting the polynomial.
monom_index :
Index of monomial whose integration is being found.
vertices : optional
Coordinates of vertices constituting the 3-Polytope.
hp_param : optional
Hyperplane Parameter of the face of the facets[index].
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.integrals.intpoly import (integration_reduction_dynamic, \
hyperplane_parameters)
>>> from sympy import Point, Polygon
>>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
>>> facets = triangle.sides
>>> a, b = hyperplane_parameters(triangle)[0]
>>> x0 = facets[0].points[0]
>>> monomial_values = [[0, 0, 0, 0], [1, 0, 0, 5],\
[y, 0, 1, 15], [x, 1, 0, None]]
>>> integration_reduction_dynamic(facets, 0, a, b, x, 1, (x, y), 1, 0, 1,\
x0, monomial_values, 3)
25/2
"""
value = S.Zero
m = len(facets)
if expr == S.Zero:
return expr
if len(dims) == 2:
if not expr.is_number:
_, x_degree, y_degree, _ = monomial_values[monom_index]
x_index = monom_index - max_index + \
x_index - 2 if x_degree > 0 else 0
y_index = monom_index - 1 if y_degree > 0 else 0
x_value, y_value =\
monomial_values[x_index][3], monomial_values[y_index][3]
value += x_degree * x_value * x0[0] + y_degree * y_value * x0[1]
value += left_integral2D(m, index, facets, x0, expr, dims)
else:
# For 3D use case the max_index contains the z_degree of the term
z_index = max_index
if not expr.is_number:
x_degree, y_degree, z_degree = y_index,\
z_index - x_index - y_index, x_index
x_value = monomial_values[z_index - 1][y_index - 1][x_index][7]\
if x_degree > 0 else 0
y_value = monomial_values[z_index - 1][y_index][x_index][7]\
if y_degree > 0 else 0
z_value = monomial_values[z_index - 1][y_index][x_index - 1][7]\
if z_degree > 0 else 0
value += x_degree * x_value * x0[0] + y_degree * y_value * x0[1] \
+ z_degree * z_value * x0[2]
value += left_integral3D(facets, index, expr,
vertices, hp_param, degree)
return value / (len(dims) + degree - 1)
def left_integral3D(facets, index, expr, vertices, hp_param, degree):
"""Computes the left integral of Eq 10 in Chin et al.
Explanation
===========
For the 3D case, this is the sum of the integral values over constituting
line segments of the face (which is accessed by facets[index]) multiplied
by the distance between the first point of facet and that line segment.
Parameters
==========
facets :
List of faces of the 3-Polytope.
index :
Index of face over which integral is to be calculated.
expr :
Input polynomial.
vertices :
List of vertices that constitute the 3-Polytope.
hp_param :
The hyperplane parameters of the face.
degree :
Degree of the ``expr``.
Examples
========
>>> from sympy.integrals.intpoly import left_integral3D
>>> cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
[3, 1, 0, 2], [0, 4, 6, 2]]
>>> facets = cube[1:]
>>> vertices = cube[0]
>>> left_integral3D(facets, 3, 1, vertices, ([0, -1, 0], -5), 0)
-50
"""
value = S.Zero
facet = facets[index]
x0 = vertices[facet[0]]
for i in range(len(facet)):
side = (vertices[facet[i]], vertices[facet[(i + 1) % len(facet)]])
value += distance_to_side(x0, side, hp_param[0]) * \
lineseg_integrate(facet, i, side, expr, degree)
return value
def gradient_terms(binomial_power=0, no_of_gens=2):
"""Returns a list of all the possible monomials between
0 and y**binomial_power for 2D case and z**binomial_power
for 3D case.
Parameters
==========
binomial_power :
Power upto which terms are generated.
no_of_gens :
Denotes whether terms are being generated for 2D or 3D case.
Examples
========
>>> from sympy.integrals.intpoly import gradient_terms
>>> gradient_terms(2)
[[1, 0, 0, 0], [y, 0, 1, 0], [y**2, 0, 2, 0], [x, 1, 0, 0],
[x*y, 1, 1, 0], [x**2, 2, 0, 0]]
>>> gradient_terms(2, 3)
[[[[1, 0, 0, 0, 0, 0, 0, 0]]], [[[y, 0, 1, 0, 1, 0, 0, 0],
[z, 0, 0, 1, 1, 0, 1, 0]], [[x, 1, 0, 0, 1, 1, 0, 0]]],
[[[y**2, 0, 2, 0, 2, 0, 0, 0], [y*z, 0, 1, 1, 2, 0, 1, 0],
[z**2, 0, 0, 2, 2, 0, 2, 0]], [[x*y, 1, 1, 0, 2, 1, 0, 0],
[x*z, 1, 0, 1, 2, 1, 1, 0]], [[x**2, 2, 0, 0, 2, 2, 0, 0]]]]
"""
if no_of_gens == 2:
count = 0
terms = [None] * int((binomial_power ** 2 + 3 * binomial_power + 2) / 2)
for x_count in range(0, binomial_power + 1):
for y_count in range(0, binomial_power - x_count + 1):
terms[count] = [x**x_count*y**y_count,
x_count, y_count, 0]
count += 1
else:
terms = [[[[x ** x_count * y ** y_count *
z ** (z_count - y_count - x_count),
x_count, y_count, z_count - y_count - x_count,
z_count, x_count, z_count - y_count - x_count, 0]
for y_count in range(z_count - x_count, -1, -1)]
for x_count in range(0, z_count + 1)]
for z_count in range(0, binomial_power + 1)]
return terms
def hyperplane_parameters(poly, vertices=None):
"""A helper function to return the hyperplane parameters
of which the facets of the polytope are a part of.
Parameters
==========
poly :
The input 2/3-Polytope.
vertices :
Vertex indices of 3-Polytope.
Examples
========
>>> from sympy import Point, Polygon
>>> from sympy.integrals.intpoly import hyperplane_parameters
>>> hyperplane_parameters(Polygon(Point(0, 3), Point(5, 3), Point(1, 1)))
[((0, 1), 3), ((1, -2), -1), ((-2, -1), -3)]
>>> cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
[3, 1, 0, 2], [0, 4, 6, 2]]
>>> hyperplane_parameters(cube[1:], cube[0])
[([0, -1, 0], -5), ([0, 0, -1], -5), ([-1, 0, 0], -5),
([0, 1, 0], 0), ([1, 0, 0], 0), ([0, 0, 1], 0)]
"""
if isinstance(poly, Polygon):
vertices = list(poly.vertices) + [poly.vertices[0]] # Close the polygon
params = [None] * (len(vertices) - 1)
for i in range(len(vertices) - 1):
v1 = vertices[i]
v2 = vertices[i + 1]
a1 = v1[1] - v2[1]
a2 = v2[0] - v1[0]
b = v2[0] * v1[1] - v2[1] * v1[0]
factor = gcd_list([a1, a2, b])
b = S(b) / factor
a = (S(a1) / factor, S(a2) / factor)
params[i] = (a, b)
else:
params = [None] * len(poly)
for i, polygon in enumerate(poly):
v1, v2, v3 = [vertices[vertex] for vertex in polygon[:3]]
normal = cross_product(v1, v2, v3)
b = sum([normal[j] * v1[j] for j in range(0, 3)])
fac = gcd_list(normal)
if fac.is_zero:
fac = 1
normal = [j / fac for j in normal]
b = b / fac
params[i] = (normal, b)
return params
def cross_product(v1, v2, v3):
"""Returns the cross-product of vectors (v2 - v1) and (v3 - v1)
That is : (v2 - v1) X (v3 - v1)
"""
v2 = [v2[j] - v1[j] for j in range(0, 3)]
v3 = [v3[j] - v1[j] for j in range(0, 3)]
return [v3[2] * v2[1] - v3[1] * v2[2],
v3[0] * v2[2] - v3[2] * v2[0],
v3[1] * v2[0] - v3[0] * v2[1]]
def best_origin(a, b, lineseg, expr):
"""Helper method for polytope_integrate. Currently not used in the main
algorithm.
Explanation
===========
Returns a point on the lineseg whose vector inner product with the
divergence of `expr` yields an expression with the least maximum
total power.
Parameters
==========
a :
Hyperplane parameter denoting direction.
b :
Hyperplane parameter denoting distance.
lineseg :
Line segment on which to find the origin.
expr :
The expression which determines the best point.
Algorithm(currently works only for 2D use case)
===============================================
1 > Firstly, check for edge cases. Here that would refer to vertical
or horizontal lines.
2 > If input expression is a polynomial containing more than one generator
then find out the total power of each of the generators.
x**2 + 3 + x*y + x**4*y**5 ---> {x: 7, y: 6}
If expression is a constant value then pick the first boundary point
of the line segment.
3 > First check if a point exists on the line segment where the value of
the highest power generator becomes 0. If not check if the value of
the next highest becomes 0. If none becomes 0 within line segment
constraints then pick the first boundary point of the line segment.
Actually, any point lying on the segment can be picked as best origin
in the last case.
Examples
========
>>> from sympy.integrals.intpoly import best_origin
>>> from sympy.abc import x, y
>>> from sympy import Point, Segment2D
>>> l = Segment2D(Point(0, 3), Point(1, 1))
>>> expr = x**3*y**7
>>> best_origin((2, 1), 3, l, expr)
(0, 3.0)
"""
a1, b1 = lineseg.points[0]
def x_axis_cut(ls):
"""Returns the point where the input line segment
intersects the x-axis.
Parameters
==========
ls :
Line segment
"""
p, q = ls.points
if p.y.is_zero:
return tuple(p)
elif q.y.is_zero:
return tuple(q)
elif p.y/q.y < S.Zero:
return p.y * (p.x - q.x)/(q.y - p.y) + p.x, S.Zero
else:
return ()
def y_axis_cut(ls):
"""Returns the point where the input line segment
intersects the y-axis.
Parameters
==========
ls :
Line segment
"""
p, q = ls.points
if p.x.is_zero:
return tuple(p)
elif q.x.is_zero:
return tuple(q)
elif p.x/q.x < S.Zero:
return S.Zero, p.x * (p.y - q.y)/(q.x - p.x) + p.y
else:
return ()
gens = (x, y)
power_gens = {}
for i in gens:
power_gens[i] = S.Zero
if len(gens) > 1:
# Special case for vertical and horizontal lines
if len(gens) == 2:
if a[0] == 0:
if y_axis_cut(lineseg):
return S.Zero, b/a[1]
else:
return a1, b1
elif a[1] == 0:
if x_axis_cut(lineseg):
return b/a[0], S.Zero
else:
return a1, b1
if isinstance(expr, Expr): # Find the sum total of power of each
if expr.is_Add: # generator and store in a dictionary.
for monomial in expr.args:
if monomial.is_Pow:
if monomial.args[0] in gens:
power_gens[monomial.args[0]] += monomial.args[1]
else:
for univariate in monomial.args:
term_type = len(univariate.args)
if term_type == 0 and univariate in gens:
power_gens[univariate] += 1
elif term_type == 2 and univariate.args[0] in gens:
power_gens[univariate.args[0]] +=\
univariate.args[1]
elif expr.is_Mul:
for term in expr.args:
term_type = len(term.args)
if term_type == 0 and term in gens:
power_gens[term] += 1
elif term_type == 2 and term.args[0] in gens:
power_gens[term.args[0]] += term.args[1]
elif expr.is_Pow:
power_gens[expr.args[0]] = expr.args[1]
elif expr.is_Symbol:
power_gens[expr] += 1
else: # If `expr` is a constant take first vertex of the line segment.
return a1, b1
# TODO : This part is quite hacky. Should be made more robust with
# TODO : respect to symbol names and scalable w.r.t higher dimensions.
power_gens = sorted(power_gens.items(), key=lambda k: str(k[0]))
if power_gens[0][1] >= power_gens[1][1]:
if y_axis_cut(lineseg):
x0 = (S.Zero, b / a[1])
elif x_axis_cut(lineseg):
x0 = (b / a[0], S.Zero)
else:
x0 = (a1, b1)
else:
if x_axis_cut(lineseg):
x0 = (b/a[0], S.Zero)
elif y_axis_cut(lineseg):
x0 = (S.Zero, b/a[1])
else:
x0 = (a1, b1)
else:
x0 = (b/a[0])
return x0
def decompose(expr, separate=False):
"""Decomposes an input polynomial into homogeneous ones of
smaller or equal degree.
Explanation
===========
Returns a dictionary with keys as the degree of the smaller
constituting polynomials. Values are the constituting polynomials.
Parameters
==========
expr : Expr
Polynomial(SymPy expression).
separate : bool
If True then simply return a list of the constituent monomials
If not then break up the polynomial into constituent homogeneous
polynomials.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.integrals.intpoly import decompose
>>> decompose(x**2 + x*y + x + y + x**3*y**2 + y**5)
{1: x + y, 2: x**2 + x*y, 5: x**3*y**2 + y**5}
>>> decompose(x**2 + x*y + x + y + x**3*y**2 + y**5, True)
{x, x**2, y, y**5, x*y, x**3*y**2}
"""
poly_dict = {}
if isinstance(expr, Expr) and not expr.is_number:
if expr.is_Symbol:
poly_dict[1] = expr
elif expr.is_Add:
symbols = expr.atoms(Symbol)
degrees = [(sum(degree_list(monom, *symbols)), monom)
for monom in expr.args]
if separate:
return {monom[1] for monom in degrees}
else:
for monom in degrees:
degree, term = monom
if poly_dict.get(degree):
poly_dict[degree] += term
else:
poly_dict[degree] = term
elif expr.is_Pow:
_, degree = expr.args
poly_dict[degree] = expr
else: # Now expr can only be of `Mul` type
degree = 0
for term in expr.args:
term_type = len(term.args)
if term_type == 0 and term.is_Symbol:
degree += 1
elif term_type == 2:
degree += term.args[1]
poly_dict[degree] = expr
else:
poly_dict[0] = expr
if separate:
return set(poly_dict.values())
return poly_dict
def point_sort(poly, normal=None, clockwise=True):
"""Returns the same polygon with points sorted in clockwise or
anti-clockwise order.
Note that it's necessary for input points to be sorted in some order
(clockwise or anti-clockwise) for the integration algorithm to work.
As a convention algorithm has been implemented keeping clockwise
orientation in mind.
Parameters
==========
poly:
2D or 3D Polygon.
normal : optional
The normal of the plane which the 3-Polytope is a part of.
clockwise : bool, optional
Returns points sorted in clockwise order if True and
anti-clockwise if False.
Examples
========
>>> from sympy.integrals.intpoly import point_sort
>>> from sympy import Point
>>> point_sort([Point(0, 0), Point(1, 0), Point(1, 1)])
[Point2D(1, 1), Point2D(1, 0), Point2D(0, 0)]
"""
pts = poly.vertices if isinstance(poly, Polygon) else poly
n = len(pts)
if n < 2:
return list(pts)
order = S.One if clockwise else S.NegativeOne
dim = len(pts[0])
if dim == 2:
center = Point(sum(map(lambda vertex: vertex.x, pts)) / n,
sum(map(lambda vertex: vertex.y, pts)) / n)
else:
center = Point(sum(map(lambda vertex: vertex.x, pts)) / n,
sum(map(lambda vertex: vertex.y, pts)) / n,
sum(map(lambda vertex: vertex.z, pts)) / n)
def compare(a, b):
if a.x - center.x >= S.Zero and b.x - center.x < S.Zero:
return -order
elif a.x - center.x < 0 and b.x - center.x >= 0:
return order
elif a.x - center.x == 0 and b.x - center.x == 0:
if a.y - center.y >= 0 or b.y - center.y >= 0:
return -order if a.y > b.y else order
return -order if b.y > a.y else order
det = (a.x - center.x) * (b.y - center.y) -\
(b.x - center.x) * (a.y - center.y)
if det < 0:
return -order
elif det > 0:
return order
first = (a.x - center.x) * (a.x - center.x) +\
(a.y - center.y) * (a.y - center.y)
second = (b.x - center.x) * (b.x - center.x) +\
(b.y - center.y) * (b.y - center.y)
return -order if first > second else order
def compare3d(a, b):
det = cross_product(center, a, b)
dot_product = sum([det[i] * normal[i] for i in range(0, 3)])
if dot_product < 0:
return -order
elif dot_product > 0:
return order
return sorted(pts, key=cmp_to_key(compare if dim==2 else compare3d))
def norm(point):
"""Returns the Euclidean norm of a point from origin.
Parameters
==========
point:
This denotes a point in the dimension_al spac_e.
Examples
========
>>> from sympy.integrals.intpoly import norm
>>> from sympy import Point
>>> norm(Point(2, 7))
sqrt(53)
"""
half = S.Half
if isinstance(point, (list, tuple)):
return sum([coord ** 2 for coord in point]) ** half
elif isinstance(point, Point):
if isinstance(point, Point2D):
return (point.x ** 2 + point.y ** 2) ** half
else:
return (point.x ** 2 + point.y ** 2 + point.z) ** half
elif isinstance(point, dict):
return sum(i**2 for i in point.values()) ** half
def intersection(geom_1, geom_2, intersection_type):
"""Returns intersection between geometric objects.
Explanation
===========
Note that this function is meant for use in integration_reduction and
at that point in the calling function the lines denoted by the segments
surely intersect within segment boundaries. Coincident lines are taken
to be non-intersecting. Also, the hyperplane intersection for 2D case is
also implemented.
Parameters
==========
geom_1, geom_2:
The input line segments.
Examples
========
>>> from sympy.integrals.intpoly import intersection
>>> from sympy import Point, Segment2D
>>> l1 = Segment2D(Point(1, 1), Point(3, 5))
>>> l2 = Segment2D(Point(2, 0), Point(2, 5))
>>> intersection(l1, l2, "segment2D")
(2, 3)
>>> p1 = ((-1, 0), 0)
>>> p2 = ((0, 1), 1)
>>> intersection(p1, p2, "plane2D")
(0, 1)
"""
if intersection_type[:-2] == "segment":
if intersection_type == "segment2D":
x1, y1 = geom_1.points[0]
x2, y2 = geom_1.points[1]
x3, y3 = geom_2.points[0]
x4, y4 = geom_2.points[1]
elif intersection_type == "segment3D":
x1, y1, z1 = geom_1.points[0]
x2, y2, z2 = geom_1.points[1]
x3, y3, z3 = geom_2.points[0]
x4, y4, z4 = geom_2.points[1]
denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if denom:
t1 = x1 * y2 - y1 * x2
t2 = x3 * y4 - x4 * y3
return (S(t1 * (x3 - x4) - t2 * (x1 - x2)) / denom,
S(t1 * (y3 - y4) - t2 * (y1 - y2)) / denom)
if intersection_type[:-2] == "plane":
if intersection_type == "plane2D": # Intersection of hyperplanes
a1x, a1y = geom_1[0]
a2x, a2y = geom_2[0]
b1, b2 = geom_1[1], geom_2[1]
denom = a1x * a2y - a2x * a1y
if denom:
return (S(b1 * a2y - b2 * a1y) / denom,
S(b2 * a1x - b1 * a2x) / denom)
def is_vertex(ent):
"""If the input entity is a vertex return True.
Parameter
=========
ent :
Denotes a geometric entity representing a point.
Examples
========
>>> from sympy import Point
>>> from sympy.integrals.intpoly import is_vertex
>>> is_vertex((2, 3))
True
>>> is_vertex((2, 3, 6))
True
>>> is_vertex(Point(2, 3))
True
"""
if isinstance(ent, tuple):
if len(ent) in [2, 3]:
return True
elif isinstance(ent, Point):
return True
return False
def plot_polytope(poly):
"""Plots the 2D polytope using the functions written in plotting
module which in turn uses matplotlib backend.
Parameter
=========
poly:
Denotes a 2-Polytope.
"""
from sympy.plotting.plot import Plot, List2DSeries
xl = list(map(lambda vertex: vertex.x, poly.vertices))
yl = list(map(lambda vertex: vertex.y, poly.vertices))
xl.append(poly.vertices[0].x) # Closing the polygon
yl.append(poly.vertices[0].y)
l2ds = List2DSeries(xl, yl)
p = Plot(l2ds, axes='label_axes=True')
p.show()
def plot_polynomial(expr):
"""Plots the polynomial using the functions written in
plotting module which in turn uses matplotlib backend.
Parameter
=========
expr:
Denotes a polynomial(SymPy expression).
"""
from sympy.plotting.plot import plot3d, plot
gens = expr.free_symbols
if len(gens) == 2:
plot3d(expr)
else:
plot(expr)
|
6c4302de7bce87e70f95a1fdecf310fb9a2655b5764eacd54d221b9bd881b2b7 | from typing import Tuple as tTuple
from sympy.concrete.expr_with_limits import AddWithLimits
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.exprtools import factor_terms
from sympy.core.function import diff
from sympy.core.logic import fuzzy_bool
from sympy.core.mul import Mul
from sympy.core.numbers import oo, pi
from sympy.core.relational import Ne
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, Wild)
from sympy.core.sympify import sympify
from sympy.functions import Piecewise, sqrt, piecewise_fold, tan, cot, atan
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.complexes import Abs, sign
from sympy.functions.elementary.miscellaneous import Min, Max
from .rationaltools import ratint
from sympy.matrices import MatrixBase
from sympy.polys import Poly, PolynomialError
from sympy.series.formal import FormalPowerSeries
from sympy.series.limits import limit
from sympy.series.order import Order
from sympy.tensor.functions import shape
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.iterables import is_sequence
from sympy.utilities.misc import filldedent
class Integral(AddWithLimits):
"""Represents unevaluated integral."""
__slots__ = ()
args: tTuple[Expr, Tuple]
def __new__(cls, function, *symbols, **assumptions):
"""Create an unevaluated integral.
Explanation
===========
Arguments are an integrand followed by one or more limits.
If no limits are given and there is only one free symbol in the
expression, that symbol will be used, otherwise an error will be
raised.
>>> from sympy import Integral
>>> from sympy.abc import x, y
>>> Integral(x)
Integral(x, x)
>>> Integral(y)
Integral(y, y)
When limits are provided, they are interpreted as follows (using
``x`` as though it were the variable of integration):
(x,) or x - indefinite integral
(x, a) - "evaluate at" integral is an abstract antiderivative
(x, a, b) - definite integral
The ``as_dummy`` method can be used to see which symbols cannot be
targeted by subs: those with a prepended underscore cannot be
changed with ``subs``. (Also, the integration variables themselves --
the first element of a limit -- can never be changed by subs.)
>>> i = Integral(x, x)
>>> at = Integral(x, (x, x))
>>> i.as_dummy()
Integral(x, x)
>>> at.as_dummy()
Integral(_0, (_0, x))
"""
#This will help other classes define their own definitions
#of behaviour with Integral.
if hasattr(function, '_eval_Integral'):
return function._eval_Integral(*symbols, **assumptions)
if isinstance(function, Poly):
sympy_deprecation_warning(
"""
integrate(Poly) and Integral(Poly) are deprecated. Instead,
use the Poly.integrate() method, or convert the Poly to an
Expr first with the Poly.as_expr() method.
""",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-integrate-poly")
obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
return obj
def __getnewargs__(self):
return (self.function,) + tuple([tuple(xab) for xab in self.limits])
@property
def free_symbols(self):
"""
This method returns the symbols that will exist when the
integral is evaluated. This is useful if one is trying to
determine whether an integral depends on a certain
symbol or not.
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x, y
>>> Integral(x, (x, y, 1)).free_symbols
{y}
See Also
========
sympy.concrete.expr_with_limits.ExprWithLimits.function
sympy.concrete.expr_with_limits.ExprWithLimits.limits
sympy.concrete.expr_with_limits.ExprWithLimits.variables
"""
return AddWithLimits.free_symbols.fget(self)
def _eval_is_zero(self):
# This is a very naive and quick test, not intended to do the integral to
# answer whether it is zero or not, e.g. Integral(sin(x), (x, 0, 2*pi))
# is zero but this routine should return None for that case. But, like
# Mul, there are trivial situations for which the integral will be
# zero so we check for those.
if self.function.is_zero:
return True
got_none = False
for l in self.limits:
if len(l) == 3:
z = (l[1] == l[2]) or (l[1] - l[2]).is_zero
if z:
return True
elif z is None:
got_none = True
free = self.function.free_symbols
for xab in self.limits:
if len(xab) == 1:
free.add(xab[0])
continue
if len(xab) == 2 and xab[0] not in free:
if xab[1].is_zero:
return True
elif xab[1].is_zero is None:
got_none = True
# take integration symbol out of free since it will be replaced
# with the free symbols in the limits
free.discard(xab[0])
# add in the new symbols
for i in xab[1:]:
free.update(i.free_symbols)
if self.function.is_zero is False and got_none is False:
return False
def transform(self, x, u):
r"""
Performs a change of variables from `x` to `u` using the relationship
given by `x` and `u` which will define the transformations `f` and `F`
(which are inverses of each other) as follows:
1) If `x` is a Symbol (which is a variable of integration) then `u`
will be interpreted as some function, f(u), with inverse F(u).
This, in effect, just makes the substitution of x with f(x).
2) If `u` is a Symbol then `x` will be interpreted as some function,
F(x), with inverse f(u). This is commonly referred to as
u-substitution.
Once f and F have been identified, the transformation is made as
follows:
.. math:: \int_a^b x \mathrm{d}x \rightarrow \int_{F(a)}^{F(b)} f(x)
\frac{\mathrm{d}}{\mathrm{d}x}
where `F(x)` is the inverse of `f(x)` and the limits and integrand have
been corrected so as to retain the same value after integration.
Notes
=====
The mappings, F(x) or f(u), must lead to a unique integral. Linear
or rational linear expression, ``2*x``, ``1/x`` and ``sqrt(x)``, will
always work; quadratic expressions like ``x**2 - 1`` are acceptable
as long as the resulting integrand does not depend on the sign of
the solutions (see examples).
The integral will be returned unchanged if ``x`` is not a variable of
integration.
``x`` must be (or contain) only one of of the integration variables. If
``u`` has more than one free symbol then it should be sent as a tuple
(``u``, ``uvar``) where ``uvar`` identifies which variable is replacing
the integration variable.
XXX can it contain another integration variable?
Examples
========
>>> from sympy.abc import a, x, u
>>> from sympy import Integral, cos, sqrt
>>> i = Integral(x*cos(x**2 - 1), (x, 0, 1))
transform can change the variable of integration
>>> i.transform(x, u)
Integral(u*cos(u**2 - 1), (u, 0, 1))
transform can perform u-substitution as long as a unique
integrand is obtained:
>>> i.transform(x**2 - 1, u)
Integral(cos(u)/2, (u, -1, 0))
This attempt fails because x = +/-sqrt(u + 1) and the
sign does not cancel out of the integrand:
>>> Integral(cos(x**2 - 1), (x, 0, 1)).transform(x**2 - 1, u)
Traceback (most recent call last):
...
ValueError:
The mapping between F(x) and f(u) did not give a unique integrand.
transform can do a substitution. Here, the previous
result is transformed back into the original expression
using "u-substitution":
>>> ui = _
>>> _.transform(sqrt(u + 1), x) == i
True
We can accomplish the same with a regular substitution:
>>> ui.transform(u, x**2 - 1) == i
True
If the `x` does not contain a symbol of integration then
the integral will be returned unchanged. Integral `i` does
not have an integration variable `a` so no change is made:
>>> i.transform(a, x) == i
True
When `u` has more than one free symbol the symbol that is
replacing `x` must be identified by passing `u` as a tuple:
>>> Integral(x, (x, 0, 1)).transform(x, (u + a, u))
Integral(a + u, (u, -a, 1 - a))
>>> Integral(x, (x, 0, 1)).transform(x, (u + a, a))
Integral(a + u, (a, -u, 1 - u))
See Also
========
sympy.concrete.expr_with_limits.ExprWithLimits.variables : Lists the integration variables
as_dummy : Replace integration variables with dummy ones
"""
d = Dummy('d')
xfree = x.free_symbols.intersection(self.variables)
if len(xfree) > 1:
raise ValueError(
'F(x) can only contain one of: %s' % self.variables)
xvar = xfree.pop() if xfree else d
if xvar not in self.variables:
return self
u = sympify(u)
if isinstance(u, Expr):
ufree = u.free_symbols
if len(ufree) == 0:
raise ValueError(filldedent('''
f(u) cannot be a constant'''))
if len(ufree) > 1:
raise ValueError(filldedent('''
When f(u) has more than one free symbol, the one replacing x
must be identified: pass f(u) as (f(u), u)'''))
uvar = ufree.pop()
else:
u, uvar = u
if uvar not in u.free_symbols:
raise ValueError(filldedent('''
Expecting a tuple (expr, symbol) where symbol identified
a free symbol in expr, but symbol is not in expr's free
symbols.'''))
if not isinstance(uvar, Symbol):
# This probably never evaluates to True
raise ValueError(filldedent('''
Expecting a tuple (expr, symbol) but didn't get
a symbol; got %s''' % uvar))
if x.is_Symbol and u.is_Symbol:
return self.xreplace({x: u})
if not x.is_Symbol and not u.is_Symbol:
raise ValueError('either x or u must be a symbol')
if uvar == xvar:
return self.transform(x, (u.subs(uvar, d), d)).xreplace({d: uvar})
if uvar in self.limits:
raise ValueError(filldedent('''
u must contain the same variable as in x
or a variable that is not already an integration variable'''))
from sympy.solvers.solvers import solve
if not x.is_Symbol:
F = [x.subs(xvar, d)]
soln = solve(u - x, xvar, check=False)
if not soln:
raise ValueError('no solution for solve(F(x) - f(u), x)')
f = [fi.subs(uvar, d) for fi in soln]
else:
f = [u.subs(uvar, d)]
from sympy.simplify.simplify import posify
pdiff, reps = posify(u - x)
puvar = uvar.subs([(v, k) for k, v in reps.items()])
soln = [s.subs(reps) for s in solve(pdiff, puvar)]
if not soln:
raise ValueError('no solution for solve(F(x) - f(u), u)')
F = [fi.subs(xvar, d) for fi in soln]
newfuncs = {(self.function.subs(xvar, fi)*fi.diff(d)
).subs(d, uvar) for fi in f}
if len(newfuncs) > 1:
raise ValueError(filldedent('''
The mapping between F(x) and f(u) did not give
a unique integrand.'''))
newfunc = newfuncs.pop()
def _calc_limit_1(F, a, b):
"""
replace d with a, using subs if possible, otherwise limit
where sign of b is considered
"""
wok = F.subs(d, a)
if wok is S.NaN or wok.is_finite is False and a.is_finite:
return limit(sign(b)*F, d, a)
return wok
def _calc_limit(a, b):
"""
replace d with a, using subs if possible, otherwise limit
where sign of b is considered
"""
avals = list({_calc_limit_1(Fi, a, b) for Fi in F})
if len(avals) > 1:
raise ValueError(filldedent('''
The mapping between F(x) and f(u) did not
give a unique limit.'''))
return avals[0]
newlimits = []
for xab in self.limits:
sym = xab[0]
if sym == xvar:
if len(xab) == 3:
a, b = xab[1:]
a, b = _calc_limit(a, b), _calc_limit(b, a)
if fuzzy_bool(a - b > 0):
a, b = b, a
newfunc = -newfunc
newlimits.append((uvar, a, b))
elif len(xab) == 2:
a = _calc_limit(xab[1], 1)
newlimits.append((uvar, a))
else:
newlimits.append(uvar)
else:
newlimits.append(xab)
return self.func(newfunc, *newlimits)
def doit(self, **hints):
"""
Perform the integration using any hints given.
Examples
========
>>> from sympy import Piecewise, S
>>> from sympy.abc import x, t
>>> p = x**2 + Piecewise((0, x/t < 0), (1, True))
>>> p.integrate((t, S(4)/5, 1), (x, -1, 1))
1/3
See Also
========
sympy.integrals.trigonometry.trigintegrate
sympy.integrals.heurisch.heurisch
sympy.integrals.rationaltools.ratint
as_sum : Approximate the integral using a sum
"""
if not hints.get('integrals', True):
return self
deep = hints.get('deep', True)
meijerg = hints.get('meijerg', None)
conds = hints.get('conds', 'piecewise')
risch = hints.get('risch', None)
heurisch = hints.get('heurisch', None)
manual = hints.get('manual', None)
if len(list(filter(None, (manual, meijerg, risch, heurisch)))) > 1:
raise ValueError("At most one of manual, meijerg, risch, heurisch can be True")
elif manual:
meijerg = risch = heurisch = False
elif meijerg:
manual = risch = heurisch = False
elif risch:
manual = meijerg = heurisch = False
elif heurisch:
manual = meijerg = risch = False
eval_kwargs = dict(meijerg=meijerg, risch=risch, manual=manual, heurisch=heurisch,
conds=conds)
if conds not in ('separate', 'piecewise', 'none'):
raise ValueError('conds must be one of "separate", "piecewise", '
'"none", got: %s' % conds)
if risch and any(len(xab) > 1 for xab in self.limits):
raise ValueError('risch=True is only allowed for indefinite integrals.')
# check for the trivial zero
if self.is_zero:
return S.Zero
# hacks to handle integrals of
# nested summations
from sympy.concrete.summations import Sum
if isinstance(self.function, Sum):
if any(v in self.function.limits[0] for v in self.variables):
raise ValueError('Limit of the sum cannot be an integration variable.')
if any(l.is_infinite for l in self.function.limits[0][1:]):
return self
_i = self
_sum = self.function
return _sum.func(_i.func(_sum.function, *_i.limits).doit(), *_sum.limits).doit()
# now compute and check the function
function = self.function
if deep:
function = function.doit(**hints)
if function.is_zero:
return S.Zero
# hacks to handle special cases
if isinstance(function, MatrixBase):
return function.applyfunc(
lambda f: self.func(f, self.limits).doit(**hints))
if isinstance(function, FormalPowerSeries):
if len(self.limits) > 1:
raise NotImplementedError
xab = self.limits[0]
if len(xab) > 1:
return function.integrate(xab, **eval_kwargs)
else:
return function.integrate(xab[0], **eval_kwargs)
# There is no trivial answer and special handling
# is done so continue
# first make sure any definite limits have integration
# variables with matching assumptions
reps = {}
for xab in self.limits:
if len(xab) != 3:
# it makes sense to just make
# all x real but in practice with the
# current state of integration...this
# doesn't work out well
# x = xab[0]
# if x not in reps and not x.is_real:
# reps[x] = Dummy(real=True)
continue
x, a, b = xab
l = (a, b)
if all(i.is_nonnegative for i in l) and not x.is_nonnegative:
d = Dummy(positive=True)
elif all(i.is_nonpositive for i in l) and not x.is_nonpositive:
d = Dummy(negative=True)
elif all(i.is_real for i in l) and not x.is_real:
d = Dummy(real=True)
else:
d = None
if d:
reps[x] = d
if reps:
undo = {v: k for k, v in reps.items()}
did = self.xreplace(reps).doit(**hints)
if isinstance(did, tuple): # when separate=True
did = tuple([i.xreplace(undo) for i in did])
else:
did = did.xreplace(undo)
return did
# continue with existing assumptions
undone_limits = []
# ulj = free symbols of any undone limits' upper and lower limits
ulj = set()
for xab in self.limits:
# compute uli, the free symbols in the
# Upper and Lower limits of limit I
if len(xab) == 1:
uli = set(xab[:1])
elif len(xab) == 2:
uli = xab[1].free_symbols
elif len(xab) == 3:
uli = xab[1].free_symbols.union(xab[2].free_symbols)
# this integral can be done as long as there is no blocking
# limit that has been undone. An undone limit is blocking if
# it contains an integration variable that is in this limit's
# upper or lower free symbols or vice versa
if xab[0] in ulj or any(v[0] in uli for v in undone_limits):
undone_limits.append(xab)
ulj.update(uli)
function = self.func(*([function] + [xab]))
factored_function = function.factor()
if not isinstance(factored_function, Integral):
function = factored_function
continue
if function.has(Abs, sign) and (
(len(xab) < 3 and all(x.is_extended_real for x in xab)) or
(len(xab) == 3 and all(x.is_extended_real and not x.is_infinite for
x in xab[1:]))):
# some improper integrals are better off with Abs
xr = Dummy("xr", real=True)
function = (function.xreplace({xab[0]: xr})
.rewrite(Piecewise).xreplace({xr: xab[0]}))
elif function.has(Min, Max):
function = function.rewrite(Piecewise)
if (function.has(Piecewise) and
not isinstance(function, Piecewise)):
function = piecewise_fold(function)
if isinstance(function, Piecewise):
if len(xab) == 1:
antideriv = function._eval_integral(xab[0],
**eval_kwargs)
else:
antideriv = self._eval_integral(
function, xab[0], **eval_kwargs)
else:
# There are a number of tradeoffs in using the
# Meijer G method. It can sometimes be a lot faster
# than other methods, and sometimes slower. And
# there are certain types of integrals for which it
# is more likely to work than others. These
# heuristics are incorporated in deciding what
# integration methods to try, in what order. See the
# integrate() docstring for details.
def try_meijerg(function, xab):
ret = None
if len(xab) == 3 and meijerg is not False:
x, a, b = xab
try:
res = meijerint_definite(function, x, a, b)
except NotImplementedError:
_debug('NotImplementedError '
'from meijerint_definite')
res = None
if res is not None:
f, cond = res
if conds == 'piecewise':
u = self.func(function, (x, a, b))
# if Piecewise modifies cond too
# much it may not be recognized by
# _condsimp pattern matching so just
# turn off all evaluation
return Piecewise((f, cond), (u, True),
evaluate=False)
elif conds == 'separate':
if len(self.limits) != 1:
raise ValueError(filldedent('''
conds=separate not supported in
multiple integrals'''))
ret = f, cond
else:
ret = f
return ret
meijerg1 = meijerg
if (meijerg is not False and
len(xab) == 3 and xab[1].is_extended_real and xab[2].is_extended_real
and not function.is_Poly and
(xab[1].has(oo, -oo) or xab[2].has(oo, -oo))):
ret = try_meijerg(function, xab)
if ret is not None:
function = ret
continue
meijerg1 = False
# If the special meijerg code did not succeed in
# finding a definite integral, then the code using
# meijerint_indefinite will not either (it might
# find an antiderivative, but the answer is likely
# to be nonsensical). Thus if we are requested to
# only use Meijer G-function methods, we give up at
# this stage. Otherwise we just disable G-function
# methods.
if meijerg1 is False and meijerg is True:
antideriv = None
else:
antideriv = self._eval_integral(
function, xab[0], **eval_kwargs)
if antideriv is None and meijerg is True:
ret = try_meijerg(function, xab)
if ret is not None:
function = ret
continue
final = hints.get('final', True)
# dotit may be iterated but floor terms making atan and acot
# continous should only be added in the final round
if (final and not isinstance(antideriv, Integral) and
antideriv is not None):
for atan_term in antideriv.atoms(atan):
atan_arg = atan_term.args[0]
# Checking `atan_arg` to be linear combination of `tan` or `cot`
for tan_part in atan_arg.atoms(tan):
x1 = Dummy('x1')
tan_exp1 = atan_arg.subs(tan_part, x1)
# The coefficient of `tan` should be constant
coeff = tan_exp1.diff(x1)
if x1 not in coeff.free_symbols:
a = tan_part.args[0]
antideriv = antideriv.subs(atan_term, Add(atan_term,
sign(coeff)*pi*floor((a-pi/2)/pi)))
for cot_part in atan_arg.atoms(cot):
x1 = Dummy('x1')
cot_exp1 = atan_arg.subs(cot_part, x1)
# The coefficient of `cot` should be constant
coeff = cot_exp1.diff(x1)
if x1 not in coeff.free_symbols:
a = cot_part.args[0]
antideriv = antideriv.subs(atan_term, Add(atan_term,
sign(coeff)*pi*floor((a)/pi)))
if antideriv is None:
undone_limits.append(xab)
function = self.func(*([function] + [xab])).factor()
factored_function = function.factor()
if not isinstance(factored_function, Integral):
function = factored_function
continue
else:
if len(xab) == 1:
function = antideriv
else:
if len(xab) == 3:
x, a, b = xab
elif len(xab) == 2:
x, b = xab
a = None
else:
raise NotImplementedError
if deep:
if isinstance(a, Basic):
a = a.doit(**hints)
if isinstance(b, Basic):
b = b.doit(**hints)
if antideriv.is_Poly:
gens = list(antideriv.gens)
gens.remove(x)
antideriv = antideriv.as_expr()
function = antideriv._eval_interval(x, a, b)
function = Poly(function, *gens)
else:
def is_indef_int(g, x):
return (isinstance(g, Integral) and
any(i == (x,) for i in g.limits))
def eval_factored(f, x, a, b):
# _eval_interval for integrals with
# (constant) factors
# a single indefinite integral is assumed
args = []
for g in Mul.make_args(f):
if is_indef_int(g, x):
args.append(g._eval_interval(x, a, b))
else:
args.append(g)
return Mul(*args)
integrals, others, piecewises = [], [], []
for f in Add.make_args(antideriv):
if any(is_indef_int(g, x)
for g in Mul.make_args(f)):
integrals.append(f)
elif any(isinstance(g, Piecewise)
for g in Mul.make_args(f)):
piecewises.append(piecewise_fold(f))
else:
others.append(f)
uneval = Add(*[eval_factored(f, x, a, b)
for f in integrals])
try:
evalued = Add(*others)._eval_interval(x, a, b)
evalued_pw = piecewise_fold(Add(*piecewises))._eval_interval(x, a, b)
function = uneval + evalued + evalued_pw
except NotImplementedError:
# This can happen if _eval_interval depends in a
# complicated way on limits that cannot be computed
undone_limits.append(xab)
function = self.func(*([function] + [xab]))
factored_function = function.factor()
if not isinstance(factored_function, Integral):
function = factored_function
return function
def _eval_derivative(self, sym):
"""Evaluate the derivative of the current Integral object by
differentiating under the integral sign [1], using the Fundamental
Theorem of Calculus [2] when possible.
Explanation
===========
Whenever an Integral is encountered that is equivalent to zero or
has an integrand that is independent of the variable of integration
those integrals are performed. All others are returned as Integral
instances which can be resolved with doit() (provided they are integrable).
References
==========
.. [1] https://en.wikipedia.org/wiki/Differentiation_under_the_integral_sign
.. [2] https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x, y
>>> i = Integral(x + y, y, (y, 1, x))
>>> i.diff(x)
Integral(x + y, (y, x)) + Integral(1, y, (y, 1, x))
>>> i.doit().diff(x) == i.diff(x).doit()
True
>>> i.diff(y)
0
The previous must be true since there is no y in the evaluated integral:
>>> i.free_symbols
{x}
>>> i.doit()
2*x**3/3 - x/2 - 1/6
"""
# differentiate under the integral sign; we do not
# check for regularity conditions (TODO), see issue 4215
# get limits and the function
f, limits = self.function, list(self.limits)
# the order matters if variables of integration appear in the limits
# so work our way in from the outside to the inside.
limit = limits.pop(-1)
if len(limit) == 3:
x, a, b = limit
elif len(limit) == 2:
x, b = limit
a = None
else:
a = b = None
x = limit[0]
if limits: # f is the argument to an integral
f = self.func(f, *tuple(limits))
# assemble the pieces
def _do(f, ab):
dab_dsym = diff(ab, sym)
if not dab_dsym:
return S.Zero
if isinstance(f, Integral):
limits = [(x, x) if (len(l) == 1 and l[0] == x) else l
for l in f.limits]
f = self.func(f.function, *limits)
return f.subs(x, ab)*dab_dsym
rv = S.Zero
if b is not None:
rv += _do(f, b)
if a is not None:
rv -= _do(f, a)
if len(limit) == 1 and sym == x:
# the dummy variable *is* also the real-world variable
arg = f
rv += arg
else:
# the dummy variable might match sym but it's
# only a dummy and the actual variable is determined
# by the limits, so mask off the variable of integration
# while differentiating
u = Dummy('u')
arg = f.subs(x, u).diff(sym).subs(u, x)
if arg:
rv += self.func(arg, (x, a, b))
return rv
def _eval_integral(self, f, x, meijerg=None, risch=None, manual=None,
heurisch=None, conds='piecewise',final=None):
"""
Calculate the anti-derivative to the function f(x).
Explanation
===========
The following algorithms are applied (roughly in this order):
1. Simple heuristics (based on pattern matching and integral table):
- most frequently used functions (e.g. polynomials, products of
trig functions)
2. Integration of rational functions:
- A complete algorithm for integrating rational functions is
implemented (the Lazard-Rioboo-Trager algorithm). The algorithm
also uses the partial fraction decomposition algorithm
implemented in apart() as a preprocessor to make this process
faster. Note that the integral of a rational function is always
elementary, but in general, it may include a RootSum.
3. Full Risch algorithm:
- The Risch algorithm is a complete decision
procedure for integrating elementary functions, which means that
given any elementary function, it will either compute an
elementary antiderivative, or else prove that none exists.
Currently, part of transcendental case is implemented, meaning
elementary integrals containing exponentials, logarithms, and
(soon!) trigonometric functions can be computed. The algebraic
case, e.g., functions containing roots, is much more difficult
and is not implemented yet.
- If the routine fails (because the integrand is not elementary, or
because a case is not implemented yet), it continues on to the
next algorithms below. If the routine proves that the integrals
is nonelementary, it still moves on to the algorithms below,
because we might be able to find a closed-form solution in terms
of special functions. If risch=True, however, it will stop here.
4. The Meijer G-Function algorithm:
- This algorithm works by first rewriting the integrand in terms of
very general Meijer G-Function (meijerg in SymPy), integrating
it, and then rewriting the result back, if possible. This
algorithm is particularly powerful for definite integrals (which
is actually part of a different method of Integral), since it can
compute closed-form solutions of definite integrals even when no
closed-form indefinite integral exists. But it also is capable
of computing many indefinite integrals as well.
- Another advantage of this method is that it can use some results
about the Meijer G-Function to give a result in terms of a
Piecewise expression, which allows to express conditionally
convergent integrals.
- Setting meijerg=True will cause integrate() to use only this
method.
5. The "manual integration" algorithm:
- This algorithm tries to mimic how a person would find an
antiderivative by hand, for example by looking for a
substitution or applying integration by parts. This algorithm
does not handle as many integrands but can return results in a
more familiar form.
- Sometimes this algorithm can evaluate parts of an integral; in
this case integrate() will try to evaluate the rest of the
integrand using the other methods here.
- Setting manual=True will cause integrate() to use only this
method.
6. The Heuristic Risch algorithm:
- This is a heuristic version of the Risch algorithm, meaning that
it is not deterministic. This is tried as a last resort because
it can be very slow. It is still used because not enough of the
full Risch algorithm is implemented, so that there are still some
integrals that can only be computed using this method. The goal
is to implement enough of the Risch and Meijer G-function methods
so that this can be deleted.
Setting heurisch=True will cause integrate() to use only this
method. Set heurisch=False to not use it.
"""
from sympy.integrals.risch import risch_integrate, NonElementaryIntegral
from sympy.integrals.manualintegrate import manualintegrate
if risch:
try:
return risch_integrate(f, x, conds=conds)
except NotImplementedError:
return None
if manual:
try:
result = manualintegrate(f, x)
if result is not None and result.func != Integral:
return result
except (ValueError, PolynomialError):
pass
eval_kwargs = dict(meijerg=meijerg, risch=risch, manual=manual,
heurisch=heurisch, conds=conds)
# if it is a poly(x) then let the polynomial integrate itself (fast)
#
# It is important to make this check first, otherwise the other code
# will return a SymPy expression instead of a Polynomial.
#
# see Polynomial for details.
if isinstance(f, Poly) and not (manual or meijerg or risch):
# Note: this is deprecated, but the deprecation warning is already
# issued in the Integral constructor.
return f.integrate(x)
# Piecewise antiderivatives need to call special integrate.
if isinstance(f, Piecewise):
return f.piecewise_integrate(x, **eval_kwargs)
# let's cut it short if `f` does not depend on `x`; if
# x is only a dummy, that will be handled below
if not f.has(x):
return f*x
# try to convert to poly(x) and then integrate if successful (fast)
poly = f.as_poly(x)
if poly is not None and not (manual or meijerg or risch):
return poly.integrate().as_expr()
if risch is not False:
try:
result, i = risch_integrate(f, x, separate_integral=True,
conds=conds)
except NotImplementedError:
pass
else:
if i:
# There was a nonelementary integral. Try integrating it.
# if no part of the NonElementaryIntegral is integrated by
# the Risch algorithm, then use the original function to
# integrate, instead of re-written one
if result == 0:
return NonElementaryIntegral(f, x).doit(risch=False)
else:
return result + i.doit(risch=False)
else:
return result
# since Integral(f=g1+g2+...) == Integral(g1) + Integral(g2) + ...
# we are going to handle Add terms separately,
# if `f` is not Add -- we only have one term
# Note that in general, this is a bad idea, because Integral(g1) +
# Integral(g2) might not be computable, even if Integral(g1 + g2) is.
# For example, Integral(x**x + x**x*log(x)). But many heuristics only
# work term-wise. So we compute this step last, after trying
# risch_integrate. We also try risch_integrate again in this loop,
# because maybe the integral is a sum of an elementary part and a
# nonelementary part (like erf(x) + exp(x)). risch_integrate() is
# quite fast, so this is acceptable.
from sympy.simplify.fu import sincos_to_sum
parts = []
args = Add.make_args(f)
for g in args:
coeff, g = g.as_independent(x)
# g(x) = const
if g is S.One and not meijerg:
parts.append(coeff*x)
continue
# g(x) = expr + O(x**n)
order_term = g.getO()
if order_term is not None:
h = self._eval_integral(g.removeO(), x, **eval_kwargs)
if h is not None:
h_order_expr = self._eval_integral(order_term.expr, x, **eval_kwargs)
if h_order_expr is not None:
h_order_term = order_term.func(
h_order_expr, *order_term.variables)
parts.append(coeff*(h + h_order_term))
continue
# NOTE: if there is O(x**n) and we fail to integrate then
# there is no point in trying other methods because they
# will fail, too.
return None
# c
# g(x) = (a*x+b)
if g.is_Pow and not g.exp.has(x) and not meijerg:
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
M = g.base.match(a*x + b)
if M is not None:
if g.exp == -1:
h = log(g.base)
elif conds != 'piecewise':
h = g.base**(g.exp + 1) / (g.exp + 1)
else:
h1 = log(g.base)
h2 = g.base**(g.exp + 1) / (g.exp + 1)
h = Piecewise((h2, Ne(g.exp, -1)), (h1, True))
parts.append(coeff * h / M[a])
continue
# poly(x)
# g(x) = -------
# poly(x)
if g.is_rational_function(x) and not (manual or meijerg or risch):
parts.append(coeff * ratint(g, x))
continue
if not (manual or meijerg or risch):
# g(x) = Mul(trig)
h = trigintegrate(g, x, conds=conds)
if h is not None:
parts.append(coeff * h)
continue
# g(x) has at least a DiracDelta term
h = deltaintegrate(g, x)
if h is not None:
parts.append(coeff * h)
continue
from .singularityfunctions import singularityintegrate
# g(x) has at least a Singularity Function term
h = singularityintegrate(g, x)
if h is not None:
parts.append(coeff * h)
continue
# Try risch again.
if risch is not False:
try:
h, i = risch_integrate(g, x,
separate_integral=True, conds=conds)
except NotImplementedError:
h = None
else:
if i:
h = h + i.doit(risch=False)
parts.append(coeff*h)
continue
# fall back to heurisch
if heurisch is not False:
from sympy.integrals.heurisch import (heurisch as heurisch_,
heurisch_wrapper)
try:
if conds == 'piecewise':
h = heurisch_wrapper(g, x, hints=[])
else:
h = heurisch_(g, x, hints=[])
except PolynomialError:
# XXX: this exception means there is a bug in the
# implementation of heuristic Risch integration
# algorithm.
h = None
else:
h = None
if meijerg is not False and h is None:
# rewrite using G functions
try:
h = meijerint_indefinite(g, x)
except NotImplementedError:
_debug('NotImplementedError from meijerint_definite')
if h is not None:
parts.append(coeff * h)
continue
if h is None and manual is not False:
try:
result = manualintegrate(g, x)
if result is not None and not isinstance(result, Integral):
if result.has(Integral) and not manual:
# Try to have other algorithms do the integrals
# manualintegrate can't handle,
# unless we were asked to use manual only.
# Keep the rest of eval_kwargs in case another
# method was set to False already
new_eval_kwargs = eval_kwargs
new_eval_kwargs["manual"] = False
new_eval_kwargs["final"] = False
result = result.func(*[
arg.doit(**new_eval_kwargs) if
arg.has(Integral) else arg
for arg in result.args
]).expand(multinomial=False,
log=False,
power_exp=False,
power_base=False)
if not result.has(Integral):
parts.append(coeff * result)
continue
except (ValueError, PolynomialError):
# can't handle some SymPy expressions
pass
# if we failed maybe it was because we had
# a product that could have been expanded,
# so let's try an expansion of the whole
# thing before giving up; we don't try this
# at the outset because there are things
# that cannot be solved unless they are
# NOT expanded e.g., x**x*(1+log(x)). There
# should probably be a checker somewhere in this
# routine to look for such cases and try to do
# collection on the expressions if they are already
# in an expanded form
if not h and len(args) == 1:
f = sincos_to_sum(f).expand(mul=True, deep=False)
if f.is_Add:
# Note: risch will be identical on the expanded
# expression, but maybe it will be able to pick out parts,
# like x*(exp(x) + erf(x)).
return self._eval_integral(f, x, **eval_kwargs)
if h is not None:
parts.append(coeff * h)
else:
return None
return Add(*parts)
def _eval_lseries(self, x, logx=None, cdir=0):
expr = self.as_dummy()
symb = x
for l in expr.limits:
if x in l[1:]:
symb = l[0]
break
for term in expr.function.lseries(symb, logx):
yield integrate(term, *expr.limits)
def _eval_nseries(self, x, n, logx=None, cdir=0):
expr = self.as_dummy()
symb = x
for l in expr.limits:
if x in l[1:]:
symb = l[0]
break
terms, order = expr.function.nseries(
x=symb, n=n, logx=logx).as_coeff_add(Order)
order = [o.subs(symb, x) for o in order]
return integrate(terms, *expr.limits) + Add(*order)*x
def _eval_as_leading_term(self, x, logx=None, cdir=0):
series_gen = self.args[0].lseries(x)
for leading_term in series_gen:
if leading_term != 0:
break
return integrate(leading_term, *self.args[1:])
def _eval_simplify(self, **kwargs):
expr = factor_terms(self)
if isinstance(expr, Integral):
from sympy.simplify.simplify import simplify
return expr.func(*[simplify(i, **kwargs) for i in expr.args])
return expr.simplify(**kwargs)
def as_sum(self, n=None, method="midpoint", evaluate=True):
"""
Approximates a definite integral by a sum.
Parameters
==========
n :
The number of subintervals to use, optional.
method :
One of: 'left', 'right', 'midpoint', 'trapezoid'.
evaluate : bool
If False, returns an unevaluated Sum expression. The default
is True, evaluate the sum.
Notes
=====
These methods of approximate integration are described in [1].
Examples
========
>>> from sympy import Integral, sin, sqrt
>>> from sympy.abc import x, n
>>> e = Integral(sin(x), (x, 3, 7))
>>> e
Integral(sin(x), (x, 3, 7))
For demonstration purposes, this interval will only be split into 2
regions, bounded by [3, 5] and [5, 7].
The left-hand rule uses function evaluations at the left of each
interval:
>>> e.as_sum(2, 'left')
2*sin(5) + 2*sin(3)
The midpoint rule uses evaluations at the center of each interval:
>>> e.as_sum(2, 'midpoint')
2*sin(4) + 2*sin(6)
The right-hand rule uses function evaluations at the right of each
interval:
>>> e.as_sum(2, 'right')
2*sin(5) + 2*sin(7)
The trapezoid rule uses function evaluations on both sides of the
intervals. This is equivalent to taking the average of the left and
right hand rule results:
>>> e.as_sum(2, 'trapezoid')
2*sin(5) + sin(3) + sin(7)
>>> (e.as_sum(2, 'left') + e.as_sum(2, 'right'))/2 == _
True
Here, the discontinuity at x = 0 can be avoided by using the
midpoint or right-hand method:
>>> e = Integral(1/sqrt(x), (x, 0, 1))
>>> e.as_sum(5).n(4)
1.730
>>> e.as_sum(10).n(4)
1.809
>>> e.doit().n(4) # the actual value is 2
2.000
The left- or trapezoid method will encounter the discontinuity and
return infinity:
>>> e.as_sum(5, 'left')
zoo
The number of intervals can be symbolic. If omitted, a dummy symbol
will be used for it.
>>> e = Integral(x**2, (x, 0, 2))
>>> e.as_sum(n, 'right').expand()
8/3 + 4/n + 4/(3*n**2)
This shows that the midpoint rule is more accurate, as its error
term decays as the square of n:
>>> e.as_sum(method='midpoint').expand()
8/3 - 2/(3*_n**2)
A symbolic sum is returned with evaluate=False:
>>> e.as_sum(n, 'midpoint', evaluate=False)
2*Sum((2*_k/n - 1/n)**2, (_k, 1, n))/n
See Also
========
Integral.doit : Perform the integration using any hints
References
==========
.. [1] https://en.wikipedia.org/wiki/Riemann_sum#Methods
"""
from sympy.concrete.summations import Sum
limits = self.limits
if len(limits) > 1:
raise NotImplementedError(
"Multidimensional midpoint rule not implemented yet")
else:
limit = limits[0]
if (len(limit) != 3 or limit[1].is_finite is False or
limit[2].is_finite is False):
raise ValueError("Expecting a definite integral over "
"a finite interval.")
if n is None:
n = Dummy('n', integer=True, positive=True)
else:
n = sympify(n)
if (n.is_positive is False or n.is_integer is False or
n.is_finite is False):
raise ValueError("n must be a positive integer, got %s" % n)
x, a, b = limit
dx = (b - a)/n
k = Dummy('k', integer=True, positive=True)
f = self.function
if method == "left":
result = dx*Sum(f.subs(x, a + (k-1)*dx), (k, 1, n))
elif method == "right":
result = dx*Sum(f.subs(x, a + k*dx), (k, 1, n))
elif method == "midpoint":
result = dx*Sum(f.subs(x, a + k*dx - dx/2), (k, 1, n))
elif method == "trapezoid":
result = dx*((f.subs(x, a) + f.subs(x, b))/2 +
Sum(f.subs(x, a + k*dx), (k, 1, n - 1)))
else:
raise ValueError("Unknown method %s" % method)
return result.doit() if evaluate else result
def principal_value(self, **kwargs):
"""
Compute the Cauchy Principal Value of the definite integral of a real function in the given interval
on the real axis.
Explanation
===========
In mathematics, the Cauchy principal value, is a method for assigning values to certain improper
integrals which would otherwise be undefined.
Examples
========
>>> from sympy import Integral, oo
>>> from sympy.abc import x
>>> Integral(x+1, (x, -oo, oo)).principal_value()
oo
>>> f = 1 / (x**3)
>>> Integral(f, (x, -oo, oo)).principal_value()
0
>>> Integral(f, (x, -10, 10)).principal_value()
0
>>> Integral(f, (x, -10, oo)).principal_value() + Integral(f, (x, -oo, 10)).principal_value()
0
References
==========
.. [1] https://en.wikipedia.org/wiki/Cauchy_principal_value
.. [2] http://mathworld.wolfram.com/CauchyPrincipalValue.html
"""
if len(self.limits) != 1 or len(list(self.limits[0])) != 3:
raise ValueError("You need to insert a variable, lower_limit, and upper_limit correctly to calculate "
"cauchy's principal value")
x, a, b = self.limits[0]
if not (a.is_comparable and b.is_comparable and a <= b):
raise ValueError("The lower_limit must be smaller than or equal to the upper_limit to calculate "
"cauchy's principal value. Also, a and b need to be comparable.")
if a == b:
return S.Zero
from sympy.calculus.singularities import singularities
r = Dummy('r')
f = self.function
singularities_list = [s for s in singularities(f, x) if s.is_comparable and a <= s <= b]
for i in singularities_list:
if i in (a, b):
raise ValueError(
'The principal value is not defined in the given interval due to singularity at %d.' % (i))
F = integrate(f, x, **kwargs)
if F.has(Integral):
return self
if a is -oo and b is oo:
I = limit(F - F.subs(x, -x), x, oo)
else:
I = limit(F, x, b, '-') - limit(F, x, a, '+')
for s in singularities_list:
I += limit(((F.subs(x, s - r)) - F.subs(x, s + r)), r, 0, '+')
return I
def integrate(*args, meijerg=None, conds='piecewise', risch=None, heurisch=None, manual=None, **kwargs):
"""integrate(f, var, ...)
.. deprecated:: 1.6
Using ``integrate()`` with :class:`~.Poly` is deprecated. Use
:meth:`.Poly.integrate` instead. See :ref:`deprecated-integrate-poly`.
Explanation
===========
Compute definite or indefinite integral of one or more variables
using Risch-Norman algorithm and table lookup. This procedure is
able to handle elementary algebraic and transcendental functions
and also a huge class of special functions, including Airy,
Bessel, Whittaker and Lambert.
var can be:
- a symbol -- indefinite integration
- a tuple (symbol, a) -- indefinite integration with result
given with ``a`` replacing ``symbol``
- a tuple (symbol, a, b) -- definite integration
Several variables can be specified, in which case the result is
multiple integration. (If var is omitted and the integrand is
univariate, the indefinite integral in that variable will be performed.)
Indefinite integrals are returned without terms that are independent
of the integration variables. (see examples)
Definite improper integrals often entail delicate convergence
conditions. Pass conds='piecewise', 'separate' or 'none' to have
these returned, respectively, as a Piecewise function, as a separate
result (i.e. result will be a tuple), or not at all (default is
'piecewise').
**Strategy**
SymPy uses various approaches to definite integration. One method is to
find an antiderivative for the integrand, and then use the fundamental
theorem of calculus. Various functions are implemented to integrate
polynomial, rational and trigonometric functions, and integrands
containing DiracDelta terms.
SymPy also implements the part of the Risch algorithm, which is a decision
procedure for integrating elementary functions, i.e., the algorithm can
either find an elementary antiderivative, or prove that one does not
exist. There is also a (very successful, albeit somewhat slow) general
implementation of the heuristic Risch algorithm. This algorithm will
eventually be phased out as more of the full Risch algorithm is
implemented. See the docstring of Integral._eval_integral() for more
details on computing the antiderivative using algebraic methods.
The option risch=True can be used to use only the (full) Risch algorithm.
This is useful if you want to know if an elementary function has an
elementary antiderivative. If the indefinite Integral returned by this
function is an instance of NonElementaryIntegral, that means that the
Risch algorithm has proven that integral to be non-elementary. Note that
by default, additional methods (such as the Meijer G method outlined
below) are tried on these integrals, as they may be expressible in terms
of special functions, so if you only care about elementary answers, use
risch=True. Also note that an unevaluated Integral returned by this
function is not necessarily a NonElementaryIntegral, even with risch=True,
as it may just be an indication that the particular part of the Risch
algorithm needed to integrate that function is not yet implemented.
Another family of strategies comes from re-writing the integrand in
terms of so-called Meijer G-functions. Indefinite integrals of a
single G-function can always be computed, and the definite integral
of a product of two G-functions can be computed from zero to
infinity. Various strategies are implemented to rewrite integrands
as G-functions, and use this information to compute integrals (see
the ``meijerint`` module).
The option manual=True can be used to use only an algorithm that tries
to mimic integration by hand. This algorithm does not handle as many
integrands as the other algorithms implemented but may return results in
a more familiar form. The ``manualintegrate`` module has functions that
return the steps used (see the module docstring for more information).
In general, the algebraic methods work best for computing
antiderivatives of (possibly complicated) combinations of elementary
functions. The G-function methods work best for computing definite
integrals from zero to infinity of moderately complicated
combinations of special functions, or indefinite integrals of very
simple combinations of special functions.
The strategy employed by the integration code is as follows:
- If computing a definite integral, and both limits are real,
and at least one limit is +- oo, try the G-function method of
definite integration first.
- Try to find an antiderivative, using all available methods, ordered
by performance (that is try fastest method first, slowest last; in
particular polynomial integration is tried first, Meijer
G-functions second to last, and heuristic Risch last).
- If still not successful, try G-functions irrespective of the
limits.
The option meijerg=True, False, None can be used to, respectively:
always use G-function methods and no others, never use G-function
methods, or use all available methods (in order as described above).
It defaults to None.
Examples
========
>>> from sympy import integrate, log, exp, oo
>>> from sympy.abc import a, x, y
>>> integrate(x*y, x)
x**2*y/2
>>> integrate(log(x), x)
x*log(x) - x
>>> integrate(log(x), (x, 1, a))
a*log(a) - a + 1
>>> integrate(x)
x**2/2
Terms that are independent of x are dropped by indefinite integration:
>>> from sympy import sqrt
>>> integrate(sqrt(1 + x), (x, 0, x))
2*(x + 1)**(3/2)/3 - 2/3
>>> integrate(sqrt(1 + x), x)
2*(x + 1)**(3/2)/3
>>> integrate(x*y)
Traceback (most recent call last):
...
ValueError: specify integration variables to integrate x*y
Note that ``integrate(x)`` syntax is meant only for convenience
in interactive sessions and should be avoided in library code.
>>> integrate(x**a*exp(-x), (x, 0, oo)) # same as conds='piecewise'
Piecewise((gamma(a + 1), re(a) > -1),
(Integral(x**a*exp(-x), (x, 0, oo)), True))
>>> integrate(x**a*exp(-x), (x, 0, oo), conds='none')
gamma(a + 1)
>>> integrate(x**a*exp(-x), (x, 0, oo), conds='separate')
(gamma(a + 1), re(a) > -1)
See Also
========
Integral, Integral.doit
"""
doit_flags = {
'deep': False,
'meijerg': meijerg,
'conds': conds,
'risch': risch,
'heurisch': heurisch,
'manual': manual
}
integral = Integral(*args, **kwargs)
if isinstance(integral, Integral):
return integral.doit(**doit_flags)
else:
new_args = [a.doit(**doit_flags) if isinstance(a, Integral) else a
for a in integral.args]
return integral.func(*new_args)
def line_integrate(field, curve, vars):
"""line_integrate(field, Curve, variables)
Compute the line integral.
Examples
========
>>> from sympy import Curve, line_integrate, E, ln
>>> from sympy.abc import x, y, t
>>> C = Curve([E**t + 1, E**t - 1], (t, 0, ln(2)))
>>> line_integrate(x + y, C, [x, y])
3*sqrt(2)
See Also
========
sympy.integrals.integrals.integrate, Integral
"""
from sympy.geometry import Curve
F = sympify(field)
if not F:
raise ValueError(
"Expecting function specifying field as first argument.")
if not isinstance(curve, Curve):
raise ValueError("Expecting Curve entity as second argument.")
if not is_sequence(vars):
raise ValueError("Expecting ordered iterable for variables.")
if len(curve.functions) != len(vars):
raise ValueError("Field variable size does not match curve dimension.")
if curve.parameter in vars:
raise ValueError("Curve parameter clashes with field parameters.")
# Calculate derivatives for line parameter functions
# F(r) -> F(r(t)) and finally F(r(t)*r'(t))
Ft = F
dldt = 0
for i, var in enumerate(vars):
_f = curve.functions[i]
_dn = diff(_f, curve.parameter)
# ...arc length
dldt = dldt + (_dn * _dn)
Ft = Ft.subs(var, _f)
Ft = Ft * sqrt(dldt)
integral = Integral(Ft, curve.limits).doit(deep=False)
return integral
### Property function dispatching ###
@shape.register(Integral)
def _(expr):
return shape(expr.function)
# Delayed imports
from .deltafunctions import deltaintegrate
from .meijerint import meijerint_definite, meijerint_indefinite, _debug
from .trigonometry import trigintegrate
|
d4e32146130143b8a0c36fd85f9591e2aebd401fc7d3332d185b5491c6d50f74 | """This module implements tools for integrating rational functions. """
from sympy.core.function import Lambda
from sympy.core.numbers import I
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, symbols)
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.trigonometric import atan
from sympy.polys.polyroots import roots
from sympy.polys.polytools import cancel
from sympy.polys.rootoftools import RootSum
from sympy.polys import Poly, resultant, ZZ
def ratint(f, x, **flags):
"""
Performs indefinite integration of rational functions.
Explanation
===========
Given a field :math:`K` and a rational function :math:`f = p/q`,
where :math:`p` and :math:`q` are polynomials in :math:`K[x]`,
returns a function :math:`g` such that :math:`f = g'`.
Examples
========
>>> from sympy.integrals.rationaltools import ratint
>>> from sympy.abc import x
>>> ratint(36/(x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2), x)
(12*x + 6)/(x**2 - 1) + 4*log(x - 2) - 4*log(x + 1)
References
==========
.. [1] M. Bronstein, Symbolic Integration I: Transcendental
Functions, Second Edition, Springer-Verlag, 2005, pp. 35-70
See Also
========
sympy.integrals.integrals.Integral.doit
sympy.integrals.rationaltools.ratint_logpart
sympy.integrals.rationaltools.ratint_ratpart
"""
if isinstance(f, tuple):
p, q = f
else:
p, q = f.as_numer_denom()
p, q = Poly(p, x, composite=False, field=True), Poly(q, x, composite=False, field=True)
coeff, p, q = p.cancel(q)
poly, p = p.div(q)
result = poly.integrate(x).as_expr()
if p.is_zero:
return coeff*result
g, h = ratint_ratpart(p, q, x)
P, Q = h.as_numer_denom()
P = Poly(P, x)
Q = Poly(Q, x)
q, r = P.div(Q)
result += g + q.integrate(x).as_expr()
if not r.is_zero:
symbol = flags.get('symbol', 't')
if not isinstance(symbol, Symbol):
t = Dummy(symbol)
else:
t = symbol.as_dummy()
L = ratint_logpart(r, Q, x, t)
real = flags.get('real')
if real is None:
if isinstance(f, tuple):
p, q = f
atoms = p.atoms() | q.atoms()
else:
atoms = f.atoms()
for elt in atoms - {x}:
if not elt.is_extended_real:
real = False
break
else:
real = True
eps = S.Zero
if not real:
for h, q in L:
_, h = h.primitive()
eps += RootSum(
q, Lambda(t, t*log(h.as_expr())), quadratic=True)
else:
for h, q in L:
_, h = h.primitive()
R = log_to_real(h, q, x, t)
if R is not None:
eps += R
else:
eps += RootSum(
q, Lambda(t, t*log(h.as_expr())), quadratic=True)
result += eps
return coeff*result
def ratint_ratpart(f, g, x):
"""
Horowitz-Ostrogradsky algorithm.
Explanation
===========
Given a field K and polynomials f and g in K[x], such that f and g
are coprime and deg(f) < deg(g), returns fractions A and B in K(x),
such that f/g = A' + B and B has square-free denominator.
Examples
========
>>> from sympy.integrals.rationaltools import ratint_ratpart
>>> from sympy.abc import x, y
>>> from sympy import Poly
>>> ratint_ratpart(Poly(1, x, domain='ZZ'),
... Poly(x + 1, x, domain='ZZ'), x)
(0, 1/(x + 1))
>>> ratint_ratpart(Poly(1, x, domain='EX'),
... Poly(x**2 + y**2, x, domain='EX'), x)
(0, 1/(x**2 + y**2))
>>> ratint_ratpart(Poly(36, x, domain='ZZ'),
... Poly(x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2, x, domain='ZZ'), x)
((12*x + 6)/(x**2 - 1), 12/(x**2 - x - 2))
See Also
========
ratint, ratint_logpart
"""
from sympy.solvers.solvers import solve
f = Poly(f, x)
g = Poly(g, x)
u, v, _ = g.cofactors(g.diff())
n = u.degree()
m = v.degree()
A_coeffs = [ Dummy('a' + str(n - i)) for i in range(0, n) ]
B_coeffs = [ Dummy('b' + str(m - i)) for i in range(0, m) ]
C_coeffs = A_coeffs + B_coeffs
A = Poly(A_coeffs, x, domain=ZZ[C_coeffs])
B = Poly(B_coeffs, x, domain=ZZ[C_coeffs])
H = f - A.diff()*v + A*(u.diff()*v).quo(u) - B*u
result = solve(H.coeffs(), C_coeffs)
A = A.as_expr().subs(result)
B = B.as_expr().subs(result)
rat_part = cancel(A/u.as_expr(), x)
log_part = cancel(B/v.as_expr(), x)
return rat_part, log_part
def ratint_logpart(f, g, x, t=None):
r"""
Lazard-Rioboo-Trager algorithm.
Explanation
===========
Given a field K and polynomials f and g in K[x], such that f and g
are coprime, deg(f) < deg(g) and g is square-free, returns a list
of tuples (s_i, q_i) of polynomials, for i = 1..n, such that s_i
in K[t, x] and q_i in K[t], and::
___ ___
d f d \ ` \ `
-- - = -- ) ) a log(s_i(a, x))
dx g dx /__, /__,
i=1..n a | q_i(a) = 0
Examples
========
>>> from sympy.integrals.rationaltools import ratint_logpart
>>> from sympy.abc import x
>>> from sympy import Poly
>>> ratint_logpart(Poly(1, x, domain='ZZ'),
... Poly(x**2 + x + 1, x, domain='ZZ'), x)
[(Poly(x + 3*_t/2 + 1/2, x, domain='QQ[_t]'),
...Poly(3*_t**2 + 1, _t, domain='ZZ'))]
>>> ratint_logpart(Poly(12, x, domain='ZZ'),
... Poly(x**2 - x - 2, x, domain='ZZ'), x)
[(Poly(x - 3*_t/8 - 1/2, x, domain='QQ[_t]'),
...Poly(-_t**2 + 16, _t, domain='ZZ'))]
See Also
========
ratint, ratint_ratpart
"""
f, g = Poly(f, x), Poly(g, x)
t = t or Dummy('t')
a, b = g, f - g.diff()*Poly(t, x)
res, R = resultant(a, b, includePRS=True)
res = Poly(res, t, composite=False)
assert res, "BUG: resultant(%s, %s) cannot be zero" % (a, b)
R_map, H = {}, []
for r in R:
R_map[r.degree()] = r
def _include_sign(c, sqf):
if c.is_extended_real and (c < 0) == True:
h, k = sqf[0]
c_poly = c.as_poly(h.gens)
sqf[0] = h*c_poly, k
C, res_sqf = res.sqf_list()
_include_sign(C, res_sqf)
for q, i in res_sqf:
_, q = q.primitive()
if g.degree() == i:
H.append((g, q))
else:
h = R_map[i]
h_lc = Poly(h.LC(), t, field=True)
c, h_lc_sqf = h_lc.sqf_list(all=True)
_include_sign(c, h_lc_sqf)
for a, j in h_lc_sqf:
h = h.quo(Poly(a.gcd(q)**j, x))
inv, coeffs = h_lc.invert(q), [S.One]
for coeff in h.coeffs()[1:]:
coeff = coeff.as_poly(inv.gens)
T = (inv*coeff).rem(q)
coeffs.append(T.as_expr())
h = Poly(dict(list(zip(h.monoms(), coeffs))), x)
H.append((h, q))
return H
def log_to_atan(f, g):
"""
Convert complex logarithms to real arctangents.
Explanation
===========
Given a real field K and polynomials f and g in K[x], with g != 0,
returns a sum h of arctangents of polynomials in K[x], such that:
dh d f + I g
-- = -- I log( ------- )
dx dx f - I g
Examples
========
>>> from sympy.integrals.rationaltools import log_to_atan
>>> from sympy.abc import x
>>> from sympy import Poly, sqrt, S
>>> log_to_atan(Poly(x, x, domain='ZZ'), Poly(1, x, domain='ZZ'))
2*atan(x)
>>> log_to_atan(Poly(x + S(1)/2, x, domain='QQ'),
... Poly(sqrt(3)/2, x, domain='EX'))
2*atan(2*sqrt(3)*x/3 + sqrt(3)/3)
See Also
========
log_to_real
"""
if f.degree() < g.degree():
f, g = -g, f
f = f.to_field()
g = g.to_field()
p, q = f.div(g)
if q.is_zero:
return 2*atan(p.as_expr())
else:
s, t, h = g.gcdex(-f)
u = (f*s + g*t).quo(h)
A = 2*atan(u.as_expr())
return A + log_to_atan(s, t)
def log_to_real(h, q, x, t):
r"""
Convert complex logarithms to real functions.
Explanation
===========
Given real field K and polynomials h in K[t,x] and q in K[t],
returns real function f such that:
___
df d \ `
-- = -- ) a log(h(a, x))
dx dx /__,
a | q(a) = 0
Examples
========
>>> from sympy.integrals.rationaltools import log_to_real
>>> from sympy.abc import x, y
>>> from sympy import Poly, S
>>> log_to_real(Poly(x + 3*y/2 + S(1)/2, x, domain='QQ[y]'),
... Poly(3*y**2 + 1, y, domain='ZZ'), x, y)
2*sqrt(3)*atan(2*sqrt(3)*x/3 + sqrt(3)/3)/3
>>> log_to_real(Poly(x**2 - 1, x, domain='ZZ'),
... Poly(-2*y + 1, y, domain='ZZ'), x, y)
log(x**2 - 1)/2
See Also
========
log_to_atan
"""
from sympy.simplify.radsimp import collect
u, v = symbols('u,v', cls=Dummy)
H = h.as_expr().subs({t: u + I*v}).expand()
Q = q.as_expr().subs({t: u + I*v}).expand()
H_map = collect(H, I, evaluate=False)
Q_map = collect(Q, I, evaluate=False)
a, b = H_map.get(S.One, S.Zero), H_map.get(I, S.Zero)
c, d = Q_map.get(S.One, S.Zero), Q_map.get(I, S.Zero)
R = Poly(resultant(c, d, v), u)
R_u = roots(R, filter='R')
if len(R_u) != R.count_roots():
return None
result = S.Zero
for r_u in R_u.keys():
C = Poly(c.subs({u: r_u}), v)
R_v = roots(C, filter='R')
if len(R_v) != C.count_roots():
return None
R_v_paired = [] # take one from each pair of conjugate roots
for r_v in R_v:
if r_v not in R_v_paired and -r_v not in R_v_paired:
if r_v.is_negative or r_v.could_extract_minus_sign():
R_v_paired.append(-r_v)
elif not r_v.is_zero:
R_v_paired.append(r_v)
for r_v in R_v_paired:
D = d.subs({u: r_u, v: r_v})
if D.evalf(chop=True) != 0:
continue
A = Poly(a.subs({u: r_u, v: r_v}), x)
B = Poly(b.subs({u: r_u, v: r_v}), x)
AB = (A**2 + B**2).as_expr()
result += r_u*log(AB) + r_v*log_to_atan(A, B)
R_q = roots(q, filter='R')
if len(R_q) != q.count_roots():
return None
for r in R_q.keys():
result += r*log(h.as_expr().subs(t, r))
return result
|
cac2102dd441706fd847e6d50e8c6dfacc44554f131bbee84a033e274808d261 | from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.functions import DiracDelta, Heaviside
from .integrals import Integral, integrate
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)
>>> deltaintegrate(y**2*DiracDelta(x - z)*DiracDelta(y - z), y)
z**2*DiracDelta(x - z)*Heaviside(y - z)
See Also
========
sympy.functions.special.delta_functions.DiracDelta
sympy.integrals.integrals.Integral
"""
if not f.has(DiracDelta):
return None
# 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:
from sympy.solvers import solve
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 = S.NegativeOne**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
|
6867b1d047b85fa5c89bf82f166211b44f56d9f81c9e9bb2f8704c59d1f95fee | """
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 does not 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 in ('primitive', '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 A or not all(derivation(i, DE, basic=True).is_zero for i in u):
# 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 A or not all(derivation(i, DE, basic=True).is_zero for i in u):
# 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)
|
ec56a4777b1eff122cecf817778bedf90cdf018fddbc06fef20fa9f574a0e72f | """
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 as tDict, Tuple as tTuple
from sympy import SYMPY_DEBUG
from sympy.core import S, Expr
from sympy.core.add import Add
from sympy.core.cache import cacheit
from sympy.core.containers import Tuple
from sympy.core.exprtools import factor_terms
from sympy.core.function import (expand, expand_mul, expand_power_base,
expand_trig, Function)
from sympy.core.mul import Mul
from sympy.core.numbers import ilcm, Rational, pi
from sympy.core.relational import Eq, Ne, _canonical_coeff
from sympy.core.sorting import default_sort_key, ordered
from sympy.core.symbol import Dummy, symbols, Wild
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import (re, im, arg, Abs, sign,
unpolarify, polarify, polar_lift, principal_branch, unbranched_argument,
periodic_argument)
from sympy.functions.elementary.exponential import exp, exp_polar, log
from sympy.functions.elementary.integers import ceiling
from sympy.functions.elementary.hyperbolic import (cosh, sinh,
_rewrite_hyperbolics_as_exp, HyperbolicFunction)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
from sympy.functions.elementary.trigonometric import (cos, sin, sinc,
TrigonometricFunction)
from sympy.functions.special.bessel import besselj, bessely, besseli, besselk
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
from sympy.functions.special.elliptic_integrals import elliptic_k, elliptic_e
from sympy.functions.special.error_functions import (erf, erfc, erfi, Ei,
expint, Si, Ci, Shi, Chi, fresnels, fresnelc)
from sympy.functions.special.gamma_functions import gamma
from sympy.functions.special.hyper import hyper, meijerg
from sympy.functions.special.singularity_functions import SingularityFunction
from .integrals import Integral
from sympy.logic.boolalg import And, Or, BooleanAtom, Not, BooleanFunction
from sympy.polys import cancel, factor
from sympy.utilities.iterables import multiset_partitions
from sympy.utilities.misc import debug as _debug
# 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.
class IsNonPositiveInteger(Function):
@classmethod
def eval(cls, arg):
arg = unpolarify(arg)
if arg.is_Integer is True:
return arg <= 0
# Section 8.4.2
# 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 [(S.NegativeOne**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
addi(Ei(t),
constant(-S.ImaginaryUnit*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 #####
# 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)
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.simplify 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 argument in expr.args:
_exponents_(argument, 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. """
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 argument in expr.args:
compute_innermost(argument, 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))
"""
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: tDict[tTuple[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 """
return not any(x in expr.free_symbols for expr in f.atoms(Heaviside, Abs))
def _condsimp(cond, first=True):
"""
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
>>> from sympy.abc import x, y
>>> simp(Or(x < y, Eq(x, y)))
x <= y
"""
if first:
cond = cond.replace(lambda _: _.is_Relational, _canonical_coeff)
first = False
if not isinstance(cond, BooleanFunction):
return cond
p, q, r = symbols('p q r', cls=Wild)
# transforms tests use 0, 4, 5 and 11-14
# meijer tests use 0, 2, 11, 14
# joint_rv uses 6, 7
rules = [
(Or(p < q, Eq(p, q)), p <= q), # 0
# 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)), # 1
(And(Abs(2*arg(p) + pi) <= pi, Abs(2*arg(p) - pi) <= pi),
Eq(arg(p), 0)), # 2
(And(Abs(2*arg(p) + pi) < pi, Abs(2*arg(p) - pi) <= pi),
S.false), # 3
(And(Abs(arg(p) - pi/2) <= pi/2, Abs(arg(p) + pi/2) <= pi/2),
Eq(arg(p), 0)), # 4
(And(Abs(arg(p) - pi/2) <= pi/2, Abs(arg(p) + pi/2) < pi/2),
S.false), # 5
(And(Abs(arg(p**2/2 + 1)) < pi, Ne(Abs(arg(p**2/2 + 1)), pi)),
S.true), # 6
(Or(Abs(arg(p**2/2 + 1)) < pi, Ne(1/(p**2/2 + 1), 0)),
S.true), # 7
(And(Abs(unbranched_argument(p)) <= pi,
Abs(unbranched_argument(exp_polar(-2*pi*S.ImaginaryUnit)*p)) <= pi),
Eq(unbranched_argument(exp_polar(-S.ImaginaryUnit*pi)*p), 0)), # 8
(And(Abs(unbranched_argument(p)) <= pi/2,
Abs(unbranched_argument(exp_polar(-pi*S.ImaginaryUnit)*p)) <= pi/2),
Eq(unbranched_argument(exp_polar(-S.ImaginaryUnit*pi/2)*p), 0)), # 9
(Or(p <= q, And(p < q, r)), p <= q), # 10
(Ne(p**2, 1) & (p**2 > 1), p**2 > 1), # 11
(Ne(1/p, 1) & (cos(Abs(arg(p)))*Abs(p) > 1), Abs(p) > 1), # 12
(Ne(p, 2) & (cos(Abs(arg(p)))*Abs(p) > 2), Abs(p) > 2), # 13
((Abs(arg(p)) < pi/2) & (cos(Abs(arg(p)))*sqrt(Abs(p**2)) > 1), p**2 > 1), # 14
]
cond = cond.func(*list(map(lambda _: _condsimp(_, first), cond.args)))
change = True
while change:
change = False
for irule, (fro, to) in enumerate(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)]
if SYMPY_DEBUG:
if irule not in (0, 2, 4, 5, 6, 7, 11, 12, 13, 14):
print('used new rule:', irule)
cond = cond.func(*newargs)
change = True
break
# final tweak
def rel_touchup(rel):
if rel.rel_op != '==' or rel.rhs != 0:
return rel
# handle Eq(*, 0)
LHS = rel.lhs
m = LHS.match(arg(p)**q)
if not m:
m = LHS.match(unbranched_argument(polar_lift(p)**q))
if not m:
if isinstance(LHS, periodic_argument) and not LHS.args[0].is_polar \
and LHS.args[1] is S.Infinity:
return (LHS.args[0] > 0)
return rel
return (m[p] > 0)
cond = cond.replace(lambda _: _.is_Relational, rel_touchup)
if SYMPY_DEBUG:
print('_condsimp: ', cond)
return cond
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. """
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
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(unbranched_argument(eta)), (delta - 2*k)*pi)]
tmp = [delta > 0, Abs(unbranched_argument(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(unbranched_argument(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(unbranched_argument(eta)), delta*pi),
*extra)]
case3 += [And(p <= q - 2, Eq(delta, 0), Eq(Abs(unbranched_argument(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(unbranched_argument(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(unbranched_argument(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))
"""
from sympy.simplify import gammasimp
# See [L, section 5.6.1]. Note that s=1.
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)
"""
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)
from sympy.simplify import powdenest
return powdenest(fac, polar=True), g1, g2
def _check_antecedents(g1, g2, x):
""" Return a condition under which the integral theorem applies. """
# 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(unbranched_argument(omega)))/(q - p)
theta = (pi*(v - s - t) + Abs(unbranched_argument(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(unbranched_argument(sigma)) < bstar*pi)
c11 = Eq(Abs(unbranched_argument(sigma)), bstar*pi)
c12 = (Abs(unbranched_argument(omega)) < cstar*pi)
c13 = Eq(Abs(unbranched_argument(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*S.ImaginaryUnit)
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(unbranched_argument(sigma), 0), Eq(unbranched_argument(omega), 0))),
(lambda_s0(sign(unbranched_argument(omega)), +1)*lambda_s0(sign(unbranched_argument(omega)), -1),
And(Eq(unbranched_argument(sigma), 0), Ne(unbranched_argument(omega), 0))),
(lambda_s0(+1, sign(unbranched_argument(sigma)))*lambda_s0(-1, sign(unbranched_argument(sigma))),
And(Ne(unbranched_argument(sigma), 0), Eq(unbranched_argument(omega), 0))),
(lambda_s0(sign(unbranched_argument(omega)), sign(unbranched_argument(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(unbranched_argument(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(unbranched_argument(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(unbranched_argument(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(unbranched_argument(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(unbranched_argument(omega)),
Abs(unbranched_argument(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(unbranched_argument(omega)),
Abs(unbranched_argument(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(unbranched_argument(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(unbranched_argument(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(unbranched_argument(sigma)),
Abs(unbranched_argument(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(unbranched_argument(sigma)),
Abs(unbranched_argument(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(unbranched_argument(sigma)),
Abs(unbranched_argument(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(unbranched_argument(sigma)),
Abs(unbranched_argument(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]
from sympy.simplify import powdenest
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. """
_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(S.ImaginaryUnit*re(c)*pi/2)
wm = b*exp(-S.ImaginaryUnit*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 = S.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(S.ImaginaryUnit*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(S.ImaginaryUnit*pi*(q - m))),
Hm(z*exp(-S.ImaginaryUnit*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(S.ImaginaryUnit*pi*nu)),
Hm(z*exp(-S.ImaginaryUnit*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(S.ImaginaryUnit*pi*nu)),
Hm(z*exp(-S.ImaginaryUnit*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 .transforms import (mellin_transform, inverse_mellin_transform,
IntegralTransformError, MellinTransformStripError)
global _lookup_table
if not _lookup_table:
_lookup_table = {}
_create_lookup_table(_lookup_table)
if isinstance(f, meijerg):
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(S.Infinity, S.ComplexInfinity, S.NegativeInfinity):
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.')
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:
from sympy.simplify import simplify
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):
r = _meijerint_definite_4(f, x, only_double=True)
if r is not None:
from sympy.simplify import hyperexpand
res, cond = r
res = _my_unpolarify(hyperexpand(res, rewrite='nonrepsmall'))
return Piecewise((res, cond),
(Integral(f, (x, S.Zero, S.Infinity)), True))
return Integral(f, (x, S.Zero, S.Infinity))
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(S.Infinity, S.NaN, S.ComplexInfinity):
_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)
"""
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 isinstance(rv, list):
from sympy.simplify.radsimp import collect
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. """
_debug('Trying to compute the indefinite integral of', f, 'wrt', x)
from sympy.simplify import hyperexpand, powdenest
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(S.NaN, S.ComplexInfinity):
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 does not 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
"""
res = expand_mul(cancel(res), deep=False)
return Add._from_args(res.as_coeff_add(x)[1])
res = piecewise_fold(res, evaluate=None)
if res.is_Piecewise:
newargs = []
for e, c in res.args:
e = _my_unpolarify(_clean(e))
newargs += [(e, c)]
res = Piecewise(*newargs, evaluate=False)
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).
_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 S.NegativeInfinity and b is not S.Infinity:
return meijerint_definite(f.subs(x, -x), x, -b, -a)
elif a is S.NegativeInfinity:
# 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 S.Infinity:
res = meijerint_definite(f, x, b, S.Infinity)
return -res[0], res[1]
elif (a, b) == (S.Zero, S.Infinity):
# 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 S.Infinity:
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 is not S.Infinity:
phi = exp(S.ImaginaryUnit*arg(b))
b = Abs(b)
f = f.subs(x, phi*x)
f *= Heaviside(b - x)*phi
b = S.Infinity
_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 isinstance(rv, list):
from sympy.simplify.radsimp import collect
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). """
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):
from sympy.simplify.fu import sincos_to_sum
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):
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.
"""
from sympy.simplify import hyperexpand
# 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)
"""
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)
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)
from sympy.simplify import hyperexpand
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 .transforms import InverseLaplaceTransform
return Piecewise((res.subs(t, t_), cond),
(InverseLaplaceTransform(f_.subs(t, t_), x, t_, None), True))
|
be3cae81af037c96ad4d2c163f19998b8e6e700256c6d08dcdc88f0ff7274f99 | """Base class for all the objects in SymPy"""
from collections import defaultdict
from collections.abc import Mapping
from itertools import chain, zip_longest
from typing import Set, Tuple, Any
from .assumptions import ManagedProperties
from .cache import cacheit
from .core import BasicMeta
from .sympify import _sympify, sympify, SympifyError, _external_converter
from .sorting import ordered
from .kind import Kind, UndefinedKind
from ._print_helpers import Printable
from sympy.utilities.decorator import deprecated
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.iterables import iterable, numbered_symbols
from sympy.utilities.misc import filldedent, func_name
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."""
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'
)
_args: 'Tuple[Basic, ...]'
_mhash: 'Any'
# 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: 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 __setstate__(self, state):
for name, value in state.items():
setattr(self, name, value)
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) -> 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
@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 .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 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 _do_eq_sympify(self, other):
"""Returns a boolean indicating whether a == b when either a
or b is not a Basic. This is only done for types that were either
added to `converter` by a 3rd party or when the object has `_sympy_`
defined. This essentially reuses the code in `_sympify` that is
specific for this use case. Non-user defined types that are meant
to work with SymPy should be handled directly in the __eq__ methods
of the `Basic` classes it could equate to and not be converted. Note
that after conversion, `==` is used again since it is not
neccesarily clear whether `self` or `other`'s __eq__ method needs
to be used."""
for superclass in type(other).__mro__:
conv = _external_converter.get(superclass)
if conv is not None:
return self == conv(other)
if hasattr(other, '_sympy_'):
return self == other._sympy_()
return NotImplemented
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__ : Callable[[object], int] = <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
if not isinstance(other, Basic):
return self._do_eq_sympify(other)
# 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, Basic):
continue
if a.is_Number and type(a) != type(b):
return False
return True
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 cannot
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) -> 'Set[Basic]':
"""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."""
empty: 'Set[Basic]' = set()
return empty.union(*(a.free_symbols for a in self.args))
@property
def expr_free_symbols(self):
sympy_deprecation_warning("""
The expr_free_symbols property is deprecated. Use free_symbols to get
the free symbols of an expression.
""",
deprecated_since_version="1.9",
active_deprecations_target="deprecated-expr-free-symbols")
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 .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'),
can,
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}
"""
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 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 .symbol 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.simplify import hypersimp
from sympy.functions.elementary.piecewise 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) -> 'Tuple[Basic, ...]':
"""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.
Do not override .args() from Basic (so that it is 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 do not 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 .containers import Dict
from .symbol import Dummy, Symbol
from .numbers import _illegal
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))
simultaneous = kwargs.pop('simultaneous', False)
if unordered:
from .sorting import _nodes, default_sort_key
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),
default_sort_key,
)))
sequence = [(k, sequence[k]) for k in k]
# do infinities first
if not simultaneous:
redo = []
for i in range(len(sequence)):
if sequence[i][1] in _illegal: # nan, zoo and +/-oo
redo.append(i)
for i in reversed(redo):
sequence.insert(0, sequence.pop(i))
if simultaneous: # 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 does not 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 does not 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 does not 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 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 self._has(iterargs, *patterns)
@cacheit
def has_free(self, *patterns):
"""return True if self has object(s) ``x`` as a free expression
else False.
Examples
========
>>> from sympy import Integral, Function
>>> from sympy.abc import x, y
>>> f = Function('f')
>>> g = Function('g')
>>> expr = Integral(f(x), (f(x), 1, g(y)))
>>> expr.free_symbols
{y}
>>> expr.has_free(g(y))
True
>>> expr.has_free(*(x, f(x)))
False
This works for subexpressions and types, too:
>>> expr.has_free(g)
True
>>> (x + y + 1).has_free(y + 1)
True
"""
return self._has(iterfreeargs, *patterns)
def _has(self, iterargs, *patterns):
# separate out types and unhashable objects
type_set = set() # only types
p_set = set() # hashable non-types
for p in patterns:
if isinstance(p, BasicMeta):
type_set.add(p)
continue
if not isinstance(p, Basic):
try:
p = _sympify(p)
except SympifyError:
continue # Basic won't have this in it
p_set.add(p) # fails if object defines __eq__ but
# doesn't define __hash__
types = tuple(type_set) #
for i in iterargs(self): #
if i in p_set: # <--- here, too
return True
if isinstance(i, types):
return True
# use matcher if defined, e.g. operations defines
# matcher that checks for exact subset containment,
# (x + y + 1).has(x + 1) -> True
for i in p_set - type_set: # types don't have matchers
if not hasattr(i, '_has_matcher'):
continue
match = i._has_matcher()
if any(match(arg) for arg in iterargs(self)):
return True
# no success
return False
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 does not 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
"""
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:
from .symbol import Wild
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=None, 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}
"""
expr = sympify(expr)
if not isinstance(expr, self.__class__):
return None
if repl_dict is None:
repl_dict = dict()
else:
repl_dict = repl_dict.copy()
if self == expr:
return repl_dict
if len(self.args) != len(expr.args):
return None
d = repl_dict # already a copy
for arg, other_arg in zip(self.args, expr.args):
if arg == other_arg:
continue
if arg.is_Relational:
try:
d = arg.xreplace(d).matches(other_arg, d, old=old)
except TypeError: # Should be InvalidComparisonError when introduced
d = None
else:
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}
"""
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
from .symbol import Wild
from .function import WildFunction
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 .function 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.simplify import simplify
return simplify(self, **kwargs)
def refine(self, assumption=True):
"""See the refine function in sympy.assumptions"""
from sympy.assumptions.refine import refine
return refine(self, assumption)
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 .numbers 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, deep=True, **hints):
"""
Rewrite *self* using a defined rule.
Rewriting transforms an expression to another, which is mathematically
equivalent but structurally different. For example you can rewrite
trigonometric functions as complex exponentials or combinatorial
functions as gamma function.
This method takes a *pattern* and a *rule* as positional arguments.
*pattern* is optional parameter which defines the types of expressions
that will be transformed. If it is not passed, all possible expressions
will be rewritten. *rule* defines how the expression will be rewritten.
Parameters
==========
args : *rule*, or *pattern* and *rule*.
- *pattern* is a type or an iterable of types.
- *rule* can be any object.
deep : bool, optional.
If ``True``, subexpressions are recursively transformed. Default is
``True``.
Examples
========
If *pattern* is unspecified, all possible expressions are transformed.
>>> from sympy import cos, sin, exp, I
>>> from sympy.abc import x
>>> expr = cos(x) + I*sin(x)
>>> expr.rewrite(exp)
exp(I*x)
Pattern can be a type or an iterable of types.
>>> expr.rewrite(sin, exp)
exp(I*x)/2 + cos(x) - exp(-I*x)/2
>>> expr.rewrite([cos,], exp)
exp(I*x)/2 + I*sin(x) + exp(-I*x)/2
>>> expr.rewrite([cos, sin], exp)
exp(I*x)
Rewriting behavior can be implemented by defining ``_eval_rewrite()``
method.
>>> from sympy import Expr, sqrt, pi
>>> class MySin(Expr):
... def _eval_rewrite(self, rule, args, **hints):
... x, = args
... if rule == cos:
... return cos(pi/2 - x, evaluate=False)
... if rule == sqrt:
... return sqrt(1 - cos(x)**2)
>>> MySin(MySin(x)).rewrite(cos)
cos(-cos(-x + pi/2) + pi/2)
>>> MySin(x).rewrite(sqrt)
sqrt(1 - cos(x)**2)
Defining ``_eval_rewrite_as_[...]()`` method is supported for backwards
compatibility reason. This may be removed in the future and using it is
discouraged.
>>> class MySin(Expr):
... def _eval_rewrite_as_cos(self, *args, **hints):
... x, = args
... return cos(pi/2 - x, evaluate=False)
>>> MySin(x).rewrite(cos)
cos(-x + pi/2)
"""
if not args:
return self
hints.update(deep=deep)
pattern = args[:-1]
rule = args[-1]
# support old design by _eval_rewrite_as_[...] method
if isinstance(rule, str):
method = "_eval_rewrite_as_%s" % rule
elif hasattr(rule, "__name__"):
# rule is class or function
clsname = rule.__name__
method = "_eval_rewrite_as_%s" % clsname
else:
# rule is instance
clsname = rule.__class__.__name__
method = "_eval_rewrite_as_%s" % clsname
if pattern:
if iterable(pattern[0]):
pattern = pattern[0]
pattern = tuple(p for p in pattern if self.has(p))
if not pattern:
return self
# hereafter, empty pattern is interpreted as all pattern.
return self._rewrite(pattern, rule, method, **hints)
def _rewrite(self, pattern, rule, method, **hints):
deep = hints.pop('deep', True)
if deep:
args = [a._rewrite(pattern, rule, method, **hints)
for a in self.args]
else:
args = self.args
if not pattern or any(isinstance(self, p) for p in pattern):
meth = getattr(self, method, None)
if meth is not None:
rewritten = meth(*args, **hints)
else:
rewritten = self._eval_rewrite(rule, args, **hints)
if rewritten is not None:
return rewritten
if not args:
return self
return self.func(*args)
def _eval_rewrite(self, rule, args, **hints):
return None
_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
def _sage_(self):
"""
Convert *self* to a symbolic expression of SageMath.
This version of the method is merely a placeholder.
"""
old_method = self._sage_
from sage.interfaces.sympy import sympy_init
sympy_init() # may monkey-patch _sage_ method into self's class or superclasses
if old_method == self._sage_:
raise NotImplementedError('conversion to SageMath is not implemented')
else:
# call the freshly monkey-patched method
return self._sage_()
def could_extract_minus_sign(self):
return False # see Expr.could_extract_minus_sign
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=None, old=False):
if self == expr:
if repl_dict is None:
return dict()
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. Do not
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)}
"""
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()
from .symbol import Symbol
from .function import Derivative, Function
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
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
from .traversal import (preorder_traversal as _preorder_traversal,
iterargs, iterfreeargs)
preorder_traversal = deprecated(
"""
Using preorder_traversal from the sympy.core.basic submodule is
deprecated.
Instead, use preorder_traversal from the top-level sympy namespace, like
sympy.preorder_traversal
""",
deprecated_since_version="1.10",
active_deprecations_target="deprecated-traversal-functions-moved",
)(_preorder_traversal)
|
ed959ccfec26e6deeed03e60d0c35e7c2f8b18ac43081afe9463b045e2bfd8b9 | from typing import Callable, Tuple as tTuple
from math import log as _log, sqrt as _sqrt
from itertools import product
from .sympify import _sympify
from .cache import cacheit
from .singleton import S
from .expr import Expr
from .evalf import PrecisionExhausted
from .function import (expand_complex, expand_multinomial,
expand_mul, _mexpand, PoleError)
from .logic import fuzzy_bool, fuzzy_not, fuzzy_and, fuzzy_or
from .parameters import global_parameters
from .relational import is_gt, is_lt
from .kind import NumberKind, UndefinedKind
from sympy.external.gmpy import HAS_GMPY, gmpy
from sympy.utilities.iterables import sift
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.misc import as_int
from sympy.multipledispatch import Dispatcher
from mpmath.libmp import sqrtrem as mpmath_sqrtrem
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"
.. deprecated:: 1.7
Using arguments that aren't subclasses of :class:`~.Expr` in core
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
deprecated. See :ref:`non-expr-args-deprecated` for details.
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 than 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',)
args: tTuple[Expr, Expr]
@cacheit
def __new__(cls, b, e, evaluate=None):
if evaluate is None:
evaluate = global_parameters.evaluate
b = _sympify(b)
e = _sympify(e)
# XXX: This can be removed when non-Expr args are disallowed rather
# than deprecated.
from .relational import Relational
if isinstance(b, Relational) or isinstance(e, Relational):
raise TypeError('Relational cannot be used in Pow')
# XXX: This should raise TypeError once deprecation period is over:
for arg in [b, e]:
if not isinstance(arg, Expr):
sympy_deprecation_warning(
f"""
Using non-Expr arguments in Pow is deprecated (in this case, one of the
arguments is of type {type(arg).__name__!r}).
If you really did intend to construct a power with this base, use the **
operator instead.""",
deprecated_since_version="1.7",
active_deprecations_target="non-expr-args-deprecated",
stacklevel=4,
)
if evaluate:
if e is S.ComplexInfinity:
return S.NaN
if e is S.Infinity:
if is_gt(b, S.One):
return S.Infinity
if is_gt(b, S.NegativeOne) and is_lt(b, S.One):
return S.Zero
if is_lt(b, S.NegativeOne):
if b.is_finite:
return S.ComplexInfinity
if b.is_finite is False:
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.calculus.accumulationbounds import AccumBounds
return AccumBounds(Pow(b, e.min), Pow(b, e.max))
# autosimplification if base is a number and exp odd/even
# if base is Number then the base will end up positive; we
# do not do this with arbitrary expressions since symbolic
# cancellation might occur as in (x - 1)/(1 - x) -> -1. If
# we returned Piecewise((-1, Ne(x, 1))) for such cases then
# we could do this...but we don't
elif (e.is_Symbol and e.is_integer or e.is_Integer
) and (b.is_number and b.is_Mul or b.is_Number
) and b.could_extract_minus_sign():
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
from sympy.functions.elementary.exponential import exp_polar
if not e.is_Atom and b is not S.Exp1 and not isinstance(b, exp_polar):
from .exprtools import factor_terms
from sympy.functions.elementary.exponential import log
from sympy.simplify.radsimp import fraction
c, ex = factor_terms(e, sign=False).as_coeff_Mul()
num, den = fraction(ex)
if isinstance(den, log) and den.args[0] == b:
return S.Exp1**(c*num)
elif den.is_Add:
from sympy.functions.elementary.complexes import sign, im
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*num)
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.functions.elementary.exponential import log
return log
return None
@property
def base(self):
return self._args[0]
@property
def exp(self):
return self._args[1]
@property
def kind(self):
if self.exp.kind is NumberKind:
return self.base.kind
else:
return UndefinedKind
@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 b.could_extract_minus_sign():
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):
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:
from sympy.functions.elementary.complexes import arg, im, re, sign
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.integers import floor
# 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: # XXX ok if im(b) != 0?
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 \ge \log(m)$.
Bound on m, is for safe factorization memory wise i.e. $m^{1/4}$.
For pollard-rho to be faster than built-in pow $\log(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.
"""
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
from sympy.ntheory.factor_ import totient
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))
from .mod import Mod
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):
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:
from sympy.functions.elementary.exponential import log
return log(self.base).is_imaginary
def _eval_is_extended_negative(self):
if self.exp is S.Half:
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):
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
from sympy.functions.elementary.exponential import log, exp
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
from sympy.functions.elementary.complexes import arg
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):
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:
from sympy.functions.elementary.exponential import log
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
from sympy.functions.elementary.complexes import arg
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.calculus.accumulationbounds import 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)
from sympy.functions.elementary.exponential import exp, log
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:
b, e = old.as_base_exp()
# These conditions ensure that (b**e)**f == b**(e*f) for any f
combines = b.is_positive and e.is_real or b.is_nonnegative and e.is_nonnegative
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.
Explanation
===========
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.concrete.summations import Sum
if isinstance(e, Sum) and e.is_commutative:
from sympy.concrete.products import Product
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.ntheory.multinomial 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):
if self.exp.is_Integer:
from sympy.polys.polytools import poly
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}))
from sympy.functions.elementary.trigonometric import atan2, cos, sin
if 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 sympy.functions.elementary.exponential 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:
from sympy.functions.elementary.complexes import im, re
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.functions.elementary.exponential 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.functions.elementary.exponential 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.functions.elementary.exponential import exp, log
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:
from sympy.functions.elementary.complexes import arg, Abs
return exp((log(Abs(base)) + S.ImaginaryUnit*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 exp.is_Mul and not neg_exp and not exp.is_positive:
neg_exp = exp.could_extract_minus_sign()
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=None, old=False):
expr = _sympify(expr)
if repl_dict is None:
repl_dict = dict()
# 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.functions.elementary.exponential import exp, log
from sympy.series.limits import limit
from sympy.series.order import Order
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 is S.NegativeInfinity:
return Order(x**n, x)
if e0 is 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)
from sympy.simplify.powsimp import powsimp
return powsimp(exp_series, deep=True, combine='exp')
from sympy.simplify.powsimp import powdenest
from .numbers import _illegal
self = powdenest(self, force=True).trigsimp()
b, e = self.as_base_exp()
if e.has(*_illegal):
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):
from .symbol import Wild
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:
from sympy.functions.special.gamma_functions import polygamma
if b.has(polygamma, S.EulerGamma) and logx is not None:
raise ValueError()
_, m = b.leadterm(x)
except (ValueError, NotImplementedError, PoleError):
b = b._eval_nseries(x, n=max(2, n), logx=logx, cdir=cdir).removeO()
if b.has(S.NaN, S.ComplexInfinity):
raise NotImplementedError()
_, m = b.leadterm(x)
if e.has(log):
from sympy.simplify.simplify import logcombine
e = logcombine(e).cancel()
if not (m.is_zero or e.is_number and e.is_real):
res = exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
if res is exp(e*log(b)):
return self
return res
f = b.as_leading_term(x, logx=logx)
g = (b/f - S.One).cancel(expand=False)
if not m.is_number:
raise NotImplementedError()
maxpow = n - m*e
if maxpow.is_negative:
return Order(x**(m*e), x)
if g.is_zero:
r = f**e
if r != self:
r += Order(x**n, x)
return r
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()
from sympy.functions.elementary.integers import ceiling
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
from sympy.functions.combinatorial.factorials import factorial, ff
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
from sympy.functions.elementary.complexes import im
if (not e.is_integer and m.is_zero and f.is_real
and f.is_negative and im((b - f).dir(x, cdir)).is_negative):
inco, inex = coeff_exp(f**e*exp(-2*e*S.Pi*S.ImaginaryUnit), 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 += Order(x**n, x)
return res
def _eval_as_leading_term(self, x, logx=None, cdir=0):
from sympy.functions.elementary.exponential import exp, log
e = self.exp
b = self.base
if self.base is S.Exp1:
arg = e.as_leading_term(x, logx=logx)
arg0 = arg.subs(x, 0)
if arg0 is S.NaN:
arg0 = arg.limit(x, 0)
if arg0.is_infinite is False:
return S.Exp1**arg0
raise PoleError("Cannot expand %s around 0" % (self))
elif e.has(x):
lt = exp(e * log(b))
return lt.as_leading_term(x, logx=logx, cdir=cdir)
else:
from sympy.functions.elementary.complexes import im
f = b.as_leading_term(x, logx=logx, 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)).is_negative):
return self.func(f, e) * exp(-2 * e * S.Pi * S.ImaginaryUnit)
return self.func(f, e)
@cacheit
def _taylor_term(self, n, x, *previous_terms): # of (1 + x)**e
from sympy.functions.combinatorial.factorials 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)
if n < 0:
return S.Zero
if n == 0:
return S.One
from .sympify import sympify
x = sympify(x)
if previous_terms:
p = previous_terms[-1]
if p is not None:
return p * x / n
from sympy.functions.combinatorial.factorials import factorial
return x**n/factorial(n)
def _eval_rewrite_as_sin(self, base, exp):
if self.base is S.Exp1:
from sympy.functions.elementary.trigonometric import sin
return sin(S.ImaginaryUnit*self.exp + S.Pi/2) - S.ImaginaryUnit*sin(S.ImaginaryUnit*self.exp)
def _eval_rewrite_as_cos(self, base, exp):
if self.base is S.Exp1:
from sympy.functions.elementary.trigonometric import cos
return cos(S.ImaginaryUnit*self.exp) + S.ImaginaryUnit*cos(S.ImaginaryUnit*self.exp + S.Pi/2)
def _eval_rewrite_as_tanh(self, base, exp):
if self.base is S.Exp1:
from sympy.functions.elementary.hyperbolic import tanh
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 and b != S.Zero:
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
|
247f28d8f7bc49e82028a3aca9704974c9a1c10fdea4f5ab2096f778ec905dae | """Tools for manipulating of large commutative expressions. """
from .add import Add
from .mul import Mul, _keep_coeff
from .power import Pow
from .basic import Basic
from .expr import Expr
from .sympify import sympify
from .numbers import Rational, Integer, Number, I
from .singleton import S
from .sorting import default_sort_key, ordered
from .symbol import Dummy
from .traversal import preorder_traversal
from .coreerrors import NonCommutativeExpression
from .containers import Tuple, Dict
from sympy.external.gmpy import SYMPY_INTS
from sympy.utilities.iterables import (common_prefix, common_suffix,
variations, iterable, is_sequence)
from collections import defaultdict
from typing import Tuple as tTuple
_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 Integer(3)
else:
return Integer(2)
elif s.is_composite:
if s.is_odd:
return Integer(9)
else:
return Integer(4)
elif s.is_positive:
if s.is_even:
if s.is_prime is False:
return Integer(4)
else:
return Integer(2)
elif s.is_integer:
return S.One
else:
return _eps
elif s.is_extended_negative:
if s.is_even:
return Integer(-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 in (_eps, -_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).is_nonpositive 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).is_nonnegative 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: Expr) -> tTuple[Expr, int]:
"""
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)) # type: ignore
e = exp.p # type: ignore
else:
base, e = expr, 1
else:
exp, tail = exp.as_coeff_Mul(rational=True)
if exp is S.NegativeOne:
base, e = Pow(base, tail), -1
elif exp is not S.One:
# todo: after dropping python 3.7 support, use overload and Literal
# in as_coeff_Mul to make exp Rational, and remove these 2 ignores
tail = _keep_coeff(Rational(1, exp.q), tail) # type: ignore
base, e = Pow(base, tail), exp.p # type: ignore
else:
base, e = expr, 1
return base, e
def decompose_power_rat(expr: Expr) -> tTuple[Expr, Rational]:
"""
Decompose power into symbolic base and rational exponent.
"""
base, exp = expr.as_base_exp()
if exp.is_Number:
if exp.is_Rational:
e: Rational = exp # type: ignore
else:
base, e = expr, S.One
else:
exp, tail = exp.as_coeff_Mul(rational=True)
if exp is S.NegativeOne:
base, e = Pow(base, tail), S.NegativeOne
elif exp is not S.One:
tail = _keep_coeff(Rational(1, exp.q), tail) # type: ignore
base, e = Pow(base, tail), Integer(exp.p) # type: ignore
else:
base, e = expr, S.One
return base, e
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 in (None, 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 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 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):
if not a.args:
return a
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 not any(a.as_coeff_Mul()[0].extract_multiplicatively(-1) is 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 .symbol 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 import factor_nc, 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)
"""
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])
from sympy.polys.polytools import gcd, factor
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
from sympy.simplify.powsimp import powsimp
# 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:
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)
# 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)
|
098eb280553be9eb2aca9c971dc93504a93aa0b198d84eecf11cf6482b161f4a | from collections import defaultdict
from .sympify import sympify, SympifyError
from sympy.utilities.iterables import iterable, uniq
__all__ = ['default_sort_key', 'ordered']
def default_sort_key(item, order=None):
"""Return a key that can be used for sorting.
The key has the structure:
(class_key, (len(args), args), exponent.sort_key(), coefficient)
This key is supplied by the sort_key routine of Basic objects when
``item`` is a Basic object or an object (other than a string) that
sympifies to a Basic object. Otherwise, this function produces the
key.
The ``order`` argument is passed along to the sort_key routine and is
used to determine how the terms *within* an expression are ordered.
(See examples below) ``order`` options are: 'lex', 'grlex', 'grevlex',
and reversed values of the same (e.g. 'rev-lex'). The default order
value is None (which translates to 'lex').
Examples
========
>>> from sympy import S, I, default_sort_key, sin, cos, sqrt
>>> from sympy.core.function import UndefinedFunction
>>> from sympy.abc import x
The following are equivalent ways of getting the key for an object:
>>> x.sort_key() == default_sort_key(x)
True
Here are some examples of the key that is produced:
>>> default_sort_key(UndefinedFunction('f'))
((0, 0, 'UndefinedFunction'), (1, ('f',)), ((1, 0, 'Number'),
(0, ()), (), 1), 1)
>>> default_sort_key('1')
((0, 0, 'str'), (1, ('1',)), ((1, 0, 'Number'), (0, ()), (), 1), 1)
>>> default_sort_key(S.One)
((1, 0, 'Number'), (0, ()), (), 1)
>>> default_sort_key(2)
((1, 0, 'Number'), (0, ()), (), 2)
While sort_key is a method only defined for SymPy objects,
default_sort_key will accept anything as an argument so it is
more robust as a sorting key. For the following, using key=
lambda i: i.sort_key() would fail because 2 does not have a sort_key
method; that's why default_sort_key is used. Note, that it also
handles sympification of non-string items likes ints:
>>> a = [2, I, -I]
>>> sorted(a, key=default_sort_key)
[2, -I, I]
The returned key can be used anywhere that a key can be specified for
a function, e.g. sort, min, max, etc...:
>>> a.sort(key=default_sort_key); a[0]
2
>>> min(a, key=default_sort_key)
2
Note
----
The key returned is useful for getting items into a canonical order
that will be the same across platforms. It is not directly useful for
sorting lists of expressions:
>>> a, b = x, 1/x
Since ``a`` has only 1 term, its value of sort_key is unaffected by
``order``:
>>> a.sort_key() == a.sort_key('rev-lex')
True
If ``a`` and ``b`` are combined then the key will differ because there
are terms that can be ordered:
>>> eq = a + b
>>> eq.sort_key() == eq.sort_key('rev-lex')
False
>>> eq.as_ordered_terms()
[x, 1/x]
>>> eq.as_ordered_terms('rev-lex')
[1/x, x]
But since the keys for each of these terms are independent of ``order``'s
value, they do not sort differently when they appear separately in a list:
>>> sorted(eq.args, key=default_sort_key)
[1/x, x]
>>> sorted(eq.args, key=lambda i: default_sort_key(i, order='rev-lex'))
[1/x, x]
The order of terms obtained when using these keys is the order that would
be obtained if those terms were *factors* in a product.
Although it is useful for quickly putting expressions in canonical order,
it does not sort expressions based on their complexity defined by the
number of operations, power of variables and others:
>>> sorted([sin(x)*cos(x), sin(x)], key=default_sort_key)
[sin(x)*cos(x), sin(x)]
>>> sorted([x, x**2, sqrt(x), x**3], key=default_sort_key)
[sqrt(x), x, x**2, x**3]
See Also
========
ordered, sympy.core.expr.Expr.as_ordered_factors, sympy.core.expr.Expr.as_ordered_terms
"""
from .basic import Basic
from .singleton import S
if isinstance(item, Basic):
return item.sort_key(order=order)
if iterable(item, exclude=str):
if isinstance(item, dict):
args = item.items()
unordered = True
elif isinstance(item, set):
args = item
unordered = True
else:
# e.g. tuple, list
args = list(item)
unordered = False
args = [default_sort_key(arg, order=order) for arg in args]
if unordered:
# e.g. dict, set
args = sorted(args)
cls_index, args = 10, (len(args), tuple(args))
else:
if not isinstance(item, str):
try:
item = sympify(item, strict=True)
except SympifyError:
# e.g. lambda x: x
pass
else:
if isinstance(item, Basic):
# e.g int -> Integer
return default_sort_key(item)
# e.g. UndefinedFunction
# e.g. str
cls_index, args = 0, (1, (str(item),))
return (cls_index, 0, item.__class__.__name__
), args, S.One.sort_key(), S.One
def _node_count(e):
# this not only counts nodes, it affirms that the
# args are Basic (i.e. have an args property). If
# some object has a non-Basic arg, it needs to be
# fixed since it is intended that all Basic args
# are of Basic type (though this is not easy to enforce).
if e.is_Float:
return 0.5
return 1 + sum(map(_node_count, e.args))
def _nodes(e):
"""
A helper for ordered() which returns the node count of ``e`` which
for Basic objects is the number of Basic nodes in the expression tree
but for other objects is 1 (unless the object is an iterable or dict
for which the sum of nodes is returned).
"""
from .basic import Basic
from .function import Derivative
if isinstance(e, Basic):
if isinstance(e, Derivative):
return _nodes(e.expr) + sum(i[1] if i[1].is_Number else
_nodes(i[1]) for i in e.variable_count)
return _node_count(e)
elif iterable(e):
return 1 + sum(_nodes(ei) for ei in e)
elif isinstance(e, dict):
return 1 + sum(_nodes(k) + _nodes(v) for k, v in e.items())
else:
return 1
def ordered(seq, keys=None, default=True, warn=False):
"""Return an iterator of the seq where keys are used to break ties in
a conservative fashion: if, after applying a key, there are no ties
then no other keys will be computed.
Two default keys will be applied if 1) keys are not provided or 2) the
given keys do not resolve all ties (but only if ``default`` is True). The
two keys are ``_nodes`` (which places smaller expressions before large) and
``default_sort_key`` which (if the ``sort_key`` for an object is defined
properly) should resolve any ties.
If ``warn`` is True then an error will be raised if there were no
keys remaining to break ties. This can be used if it was expected that
there should be no ties between items that are not identical.
Examples
========
>>> from sympy import ordered, count_ops
>>> from sympy.abc import x, y
The count_ops is not sufficient to break ties in this list and the first
two items appear in their original order (i.e. the sorting is stable):
>>> list(ordered([y + 2, x + 2, x**2 + y + 3],
... count_ops, default=False, warn=False))
...
[y + 2, x + 2, x**2 + y + 3]
The default_sort_key allows the tie to be broken:
>>> list(ordered([y + 2, x + 2, x**2 + y + 3]))
...
[x + 2, y + 2, x**2 + y + 3]
Here, sequences are sorted by length, then sum:
>>> seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], [
... lambda x: len(x),
... lambda x: sum(x)]]
...
>>> list(ordered(seq, keys, default=False, warn=False))
[[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]]
If ``warn`` is True, an error will be raised if there were not
enough keys to break ties:
>>> list(ordered(seq, keys, default=False, warn=True))
Traceback (most recent call last):
...
ValueError: not enough keys to break ties
Notes
=====
The decorated sort is one of the fastest ways to sort a sequence for
which special item comparison is desired: the sequence is decorated,
sorted on the basis of the decoration (e.g. making all letters lower
case) and then undecorated. If one wants to break ties for items that
have the same decorated value, a second key can be used. But if the
second key is expensive to compute then it is inefficient to decorate
all items with both keys: only those items having identical first key
values need to be decorated. This function applies keys successively
only when needed to break ties. By yielding an iterator, use of the
tie-breaker is delayed as long as possible.
This function is best used in cases when use of the first key is
expected to be a good hashing function; if there are no unique hashes
from application of a key, then that key should not have been used. The
exception, however, is that even if there are many collisions, if the
first group is small and one does not need to process all items in the
list then time will not be wasted sorting what one was not interested
in. For example, if one were looking for the minimum in a list and
there were several criteria used to define the sort order, then this
function would be good at returning that quickly if the first group
of candidates is small relative to the number of items being processed.
"""
d = defaultdict(list)
if keys:
if not isinstance(keys, (list, tuple)):
keys = [keys]
keys = list(keys)
f = keys.pop(0)
for a in seq:
d[f(a)].append(a)
else:
if not default:
raise ValueError('if default=False then keys must be provided')
d[None].extend(seq)
for k in sorted(d.keys()):
if len(d[k]) > 1:
if keys:
d[k] = ordered(d[k], keys, default, warn)
elif default:
d[k] = ordered(d[k], (_nodes, default_sort_key,),
default=False, warn=warn)
elif warn:
u = list(uniq(d[k]))
if len(u) > 1:
raise ValueError(
'not enough keys to break ties: %s' % u)
yield from d[k]
d.pop(k)
|
20c0263db7ad15d036140af5589c03843fcca52b509023d3560dea04bddfa49a | """Singleton mechanism"""
from .core import Registry
from .assumptions import ManagedProperties
from .sympify import sympify
class SingletonRegistry(Registry):
"""
The registry for the singleton classes (accessible as ``S``).
Explanation
===========
This class serves as two separate things.
The first thing it is is the ``SingletonRegistry``. Several classes in
SymPy appear so often that they are singletonized, that is, using some
metaprogramming they are made so that they can only be instantiated once
(see the :class:`sympy.core.singleton.Singleton` class for details). For
instance, every time you create ``Integer(0)``, this will return the same
instance, :class:`sympy.core.numbers.Zero`. All singleton instances are
attributes of the ``S`` object, so ``Integer(0)`` can also be accessed as
``S.Zero``.
Singletonization offers two advantages: it saves memory, and it allows
fast comparison. It saves memory because no matter how many times the
singletonized objects appear in expressions in memory, they all point to
the same single instance in memory. The fast comparison comes from the
fact that you can use ``is`` to compare exact instances in Python
(usually, you need to use ``==`` to compare things). ``is`` compares
objects by memory address, and is very fast.
Examples
========
>>> from sympy import S, Integer
>>> a = Integer(0)
>>> a is S.Zero
True
For the most part, the fact that certain objects are singletonized is an
implementation detail that users should not need to worry about. In SymPy
library code, ``is`` comparison is often used for performance purposes
The primary advantage of ``S`` for end users is the convenient access to
certain instances that are otherwise difficult to type, like ``S.Half``
(instead of ``Rational(1, 2)``).
When using ``is`` comparison, make sure the argument is sympified. For
instance,
>>> x = 0
>>> x is S.Zero
False
This problem is not an issue when using ``==``, which is recommended for
most use-cases:
>>> 0 == S.Zero
True
The second thing ``S`` is is a shortcut for
:func:`sympy.core.sympify.sympify`. :func:`sympy.core.sympify.sympify` is
the function that converts Python objects such as ``int(1)`` into SymPy
objects such as ``Integer(1)``. It also converts the string form of an
expression into a SymPy expression, like ``sympify("x**2")`` ->
``Symbol("x")**2``. ``S(1)`` is the same thing as ``sympify(1)``
(basically, ``S.__call__`` has been defined to call ``sympify``).
This is for convenience, since ``S`` is a single letter. It's mostly
useful for defining rational numbers. Consider an expression like ``x +
1/2``. If you enter this directly in Python, it will evaluate the ``1/2``
and give ``0.5``, because both arguments are ints (see also
:ref:`tutorial-gotchas-final-notes`). However, in SymPy, you usually want
the quotient of two integers to give an exact rational number. The way
Python's evaluation works, at least one side of an operator needs to be a
SymPy object for the SymPy evaluation to take over. You could write this
as ``x + Rational(1, 2)``, but this is a lot more typing. A shorter
version is ``x + S(1)/2``. Since ``S(1)`` returns ``Integer(1)``, the
division will return a ``Rational`` type, since it will call
``Integer.__truediv__``, which knows how to return a ``Rational``.
"""
__slots__ = ()
# Also allow things like S(5)
__call__ = staticmethod(sympify)
def __init__(self):
self._classes_to_install = {}
# Dict of classes that have been registered, but that have not have been
# installed as an attribute of this SingletonRegistry.
# Installation automatically happens at the first attempt to access the
# attribute.
# The purpose of this is to allow registration during class
# initialization during import, but not trigger object creation until
# actual use (which should not happen until after all imports are
# finished).
def register(self, cls):
# Make sure a duplicate class overwrites the old one
if hasattr(self, cls.__name__):
delattr(self, cls.__name__)
self._classes_to_install[cls.__name__] = cls
def __getattr__(self, name):
"""Python calls __getattr__ if no attribute of that name was installed
yet.
Explanation
===========
This __getattr__ checks whether a class with the requested name was
already registered but not installed; if no, raises an AttributeError.
Otherwise, retrieves the class, calculates its singleton value, installs
it as an attribute of the given name, and unregisters the class."""
if name not in self._classes_to_install:
raise AttributeError(
"Attribute '%s' was not installed on SymPy registry %s" % (
name, self))
class_to_install = self._classes_to_install[name]
value_to_install = class_to_install()
self.__setattr__(name, value_to_install)
del self._classes_to_install[name]
return value_to_install
def __repr__(self):
return "S"
S = SingletonRegistry()
class Singleton(ManagedProperties):
"""
Metaclass for singleton classes.
Explanation
===========
A singleton class has only one instance which is returned every time the
class is instantiated. Additionally, this instance can be accessed through
the global registry object ``S`` as ``S.<class_name>``.
Examples
========
>>> from sympy import S, Basic
>>> from sympy.core.singleton import Singleton
>>> class MySingleton(Basic, metaclass=Singleton):
... pass
>>> Basic() is Basic()
False
>>> MySingleton() is MySingleton()
True
>>> S.MySingleton is MySingleton()
True
Notes
=====
Instance creation is delayed until the first time the value is accessed.
(SymPy versions before 1.0 would create the instance during class
creation time, which would be prone to import cycles.)
This metaclass is a subclass of ManagedProperties because that is the
metaclass of many classes that need to be Singletons (Python does not allow
subclasses to have a different metaclass than the superclass, except the
subclass may use a subclassed metaclass).
"""
def __init__(cls, *args, **kwargs):
super().__init__(cls, *args, **kwargs)
cls._instance = obj = Basic.__new__(cls)
cls.__new__ = lambda cls: obj
cls.__getnewargs__ = lambda obj: ()
cls.__getstate__ = lambda obj: None
S.register(cls)
# Delayed to avoid cyclic import
from .basic import Basic
|
2125e46882d19068495e51eeb1083345bc3c4dede8665e9bcbcd5995ef9feee9 | """
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 as tUnion
from collections.abc import Iterable
from .add import Add
from .assumptions import ManagedProperties
from .basic import Basic, _atomic
from .cache import cacheit
from .containers import Tuple, Dict
from .decorators import _sympifyit
from .expr import Expr, AtomicExpr
from .logic import fuzzy_and, fuzzy_or, fuzzy_not, FuzzyBool
from .mul import Mul
from .numbers import Rational, Float, Integer
from .operations import LatticeOp
from .parameters import global_parameters
from .rules import Transform
from .singleton import S
from .sympify import sympify
from .sorting import default_sort_key, ordered
from sympy.utilities.exceptions import (sympy_deprecation_warning,
SymPyDeprecationWarning, ignore_warnings)
from sympy.utilities.iterables import (has_dups, sift, iterable,
is_sequence, uniq, topological_sort)
from sympy.utilities.lambdify import MPMATH_TRANSLATIONS
from sympy.utilities.misc import as_int, filldedent, func_name
import mpmath
from mpmath.libmp.libmpf import prec_to_dps
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 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 import arity, 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 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
{1}
>>> Function('f', nargs=(2, 1)).nargs
{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(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 should not evalf.
"""
if arg.is_Float:
return arg._prec
if not arg.is_Add:
return -1
from .evalf import pure_complex
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):
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: tUnion[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.
"""
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 .symbol import uniquely_named_symbol
from sympy.series.order import Order
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 .numbers 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, logx=None, 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.series.order import Order
args = [a.as_leading_term(x, logx=logx) 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)
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, logx=None, cdir=0):
return self
@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
{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
{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=None, old=False):
if not isinstance(expr, (AppliedUndef, Function)):
return None
if len(expr.args) not in self.nargs:
return None
if repl_dict is None:
repl_dict = dict()
else:
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):
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))
# 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)
from sympy.tensor.array import Array, NDimArray
for i, v in enumerate(variables):
if isinstance(v, UndefinedFunction):
raise TypeError(
"cannot differentiate wrt "
"UndefinedFunction: %s" % v)
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
variable_count.append(Tuple(v, count))
continue
v = sympify(v)
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:
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
from sympy.matrices.expressions.matexpr import MatrixExpr
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 = []
from sympy.matrices.common import MatrixCommon
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 v not 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 .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 does not 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]
"""
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(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 _, count in self.variable_count], 0)
@property
def free_symbols(self):
ret = self.expr.free_symbols
# Add symbolic counts to free_symbols
for _, count in self.variable_count:
ret.update(count.free_symbols)
return ret
@property
def kind(self):
return self.args[0].kind
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, logx=None, 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 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 sympy.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.matrices.expressions.matexpr import MatrixExpr
from sympy.tensor.array 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)):
sympy_deprecation_warning(
"""
Using a non-tuple iterable as the first argument to Lambda
is deprecated. Use Lambda(tuple(args), expr) instead.
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-non-tuple-lambda",
)
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):
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):
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.str 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 # type:ignore
@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):
sympy_deprecation_warning("""
The expr_free_symbols property is deprecated. Use free_symbols to get
the free symbols of an expression.
""",
deprecated_since_version="1.9",
active_deprecations_target="deprecated-expr-free-symbols")
# Don't show the warning twice from the recursive call
with ignore_warnings(SymPyDeprecationWarning):
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, logx=None, 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
==========
.. [1] 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.functions.elementary.exponential import 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()),
_handle)
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 is not 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 .relational import Relational
from sympy.concrete.summations import Sum
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import BooleanFunction
from sympy.simplify.radsimp import fraction
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 the following fails because the object is
# not Basic type, then the object should be fixed
# since it is the intention that all args of Basic
# should themselves be Basic
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...
if isinstance(a.func, UndefinedFunction):
o = Symbol("FUNC_" + a.func.__name__.upper())
else:
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) and those in undefined
functions. When processing dictionaries, do not modify the keys
unless ``dkeys=True``.
Examples
========
>>> from sympy import nfloat, cos, pi, sqrt
>>> from sympy.abc import x, y
>>> 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.matrices.matrices 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)
from sympy.polys.rootoftools import RootOf
rv = rv.xreplace({ro: ro.n(n) for ro in rv.atoms(RootOf)})
from .power import Pow
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) and not isinstance(x, AppliedUndef)))
from .symbol import Dummy, Symbol
|
624dba41907bd6580ad4aed633b9fe3b709508d3c7b2fe560f167c98e8520cab | from typing import Tuple as tTuple
from collections import defaultdict
from functools import cmp_to_key, reduce
from operator import attrgetter
from .basic import Basic
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
from sympy.utilities.iterables import is_sequence, sift
# Key for sorting commutative args in canonical order
_args_sortkey = cmp_to_key(Basic.compare)
def _could_extract_minus_sign(expr):
# assume expr is Add-like
# We choose the one with less arguments with minus signs
negative_args = sum(1 for i in expr.args
if i.could_extract_minus_sign())
positive_args = len(expr.args) - negative_args
if positive_args > negative_args:
return False
elif positive_args < negative_args:
return True
# choose based on .sort_key() to prefer
# x - 1 instead of 1 - x and
# 3 - sqrt(2) instead of -3 + sqrt(2)
return bool(expr.sort_key() < (-expr).sort_key())
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.
.. deprecated:: 1.7
Using arguments that aren't subclasses of :class:`~.Expr` in core
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
deprecated. See :ref:`non-expr-args-deprecated` for details.
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 do not display in args order.
>>> Add(x, 1)
x + 1
>>> Add(x, 1).args
(1, x)
See Also
========
MatAdd
"""
__slots__ = ()
args: tTuple[Expr, ...]
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.accumulationbounds 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 could_extract_minus_sign(self):
return _could_extract_minus_sign(self)
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:
l1, l2 = sift(self.args, lambda x: x.has_free(*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):
from .evalf import pure_complex
from .relational import is_eq
if len(self.args) == 2 and any(_.is_infinite for _ in self.args):
if e.is_zero is False and is_eq(e, S.One) is False:
# looking for literal a + I*b
a, b = self.args
if a.coeff(S.ImaginaryUnit):
a, b = b, a
ico = b.coeff(S.ImaginaryUnit)
if ico and ico.is_extended_real and a.is_extended_real:
if e.is_extended_negative:
return S.Zero
if e.is_extended_positive:
return S.ComplexInfinity
return
if e.is_Rational and self.is_number:
ri = pure_complex(self)
if ri:
r, i = ri
if e.q == 2:
from sympy.functions.elementary.miscellaneous import sqrt
D = sqrt(r**2 + i**2)
if D.is_Rational:
from .exprtools import factor_terms
from sympy.functions.elementary.complexes import sign
from .function import expand_multinomial
# (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=None, 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
inf = (S.Infinity, S.NegativeInfinity)
if lhs.has(*inf) or rhs.has(*inf):
from .symbol import Dummy
oo = Dummy('oo')
reps = {
S.Infinity: oo,
S.NegativeInfinity: -oo}
ireps = {v: k for k, v in reps.items()}
eq = 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)
rv = eq.xreplace(ireps)
else:
rv = lhs - rhs
srv = signsimp(rv)
return srv if srv.is_Number else rv
@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()
if not isinstance(expr, Add):
return Mul(content, expr, evaluate=False).as_numer_denom()
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) in [0, 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):
if self.is_number:
return super()._eval_is_extended_positive()
c, a = self.as_coeff_Add()
if not c.is_zero:
from .exprtools import _monotonic_sign
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):
if not self.is_number:
c, a = self.as_coeff_Add()
if not c.is_zero and a.is_extended_nonnegative:
from .exprtools import _monotonic_sign
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):
if not self.is_number:
c, a = self.as_coeff_Add()
if not c.is_zero and a.is_extended_nonpositive:
from .exprtools import _monotonic_sign
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):
if self.is_number:
return super()._eval_is_extended_negative()
c, a = self.as_coeff_Add()
if not c.is_zero:
from .exprtools import _monotonic_sign
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.series.order 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, logx=None, cdir=0):
from sympy.series.order import Order
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
from .function import expand_mul
old = self
if old.has(Piecewise):
old = piecewise_fold(old)
# This expansion is the last part of expand_log. expand_log also calls
# expand_mul with factor=True, which would be more expensive
if any(isinstance(a, log) for a in self.args):
logflags = dict(deep=True, log=True, mul=False, power_exp=False,
power_base=False, multinomial=False, basic=False, force=False,
factor=False)
old = old.expand(**logflags)
expr = expand_mul(old)
if not expr.is_Add:
return expr.as_leading_term(x, logx=logx, cdir=cdir)
infinite = [t for t in expr.args if t.is_infinite]
leading_terms = [t.as_leading_term(x, logx=logx, 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().powsimp().trigsimp()
incr *= 2
return res.as_leading_term(x, logx=logx, 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 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 .sorting 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 .numbers import Float
re_part, rest = self.as_coeff_Add()
im_part, imag_unit = rest.as_coeff_Mul()
if not imag_unit == S.ImaginaryUnit:
# 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, _unevaluated_Mul
from .numbers import Rational
|
df86c36e723405c3a30995b9ea7e602f27ca6892a01fc7b6bd057e86f39ad36a | from typing import Tuple as tTuple, TYPE_CHECKING
from collections.abc import Iterable
from functools import reduce
from .sympify import sympify, _sympify
from .basic import Basic, Atom
from .singleton import S
from .evalf import EvalfMixin, pure_complex, DEFAULT_MAXPREC
from .decorators import call_highest_priority, sympify_method_args, sympify_return
from .cache import cacheit
from .sorting import default_sort_key
from .kind import NumberKind
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.misc import as_int, func_name, filldedent
from sympy.utilities.iterables import has_variety, sift
from mpmath.libmp import mpf_log, prec_to_dps
from mpmath.libmp.libintmath import giant_steps
if TYPE_CHECKING:
from .numbers import Number
from collections import defaultdict
def _corem(eq, c): # helper for extract_additively
# return co, diff from co*c + diff
co = []
non = []
for i in Add.make_args(eq):
ci = i.coeff(c)
if not ci:
non.append(i)
else:
co.append(ci)
return Add(*co), Add(*non)
@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:
exp = 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 _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
# ***************
# * 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.functions.elementary.complexes 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 .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 .symbol import Dummy
if not self.is_number:
raise TypeError("Cannot convert symbols to int")
r = self.round(2)
if not r.is_Number:
raise TypeError("Cannot convert complex to int")
if r in (S.NaN, S.Infinity, S.NegativeInfinity):
raise TypeError("Cannot 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("Cannot convert complex to float")
raise TypeError("Cannot 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("Cannot truncate symbols and expressions")
else:
return Integer(self)
@staticmethod
def _from_mpmath(x, prec):
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 Function, Integral, cos, sin, pi
>>> 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.core.random.random_complex_number
"""
free = self.free_symbols
prec = 1
if free:
from sympy.core.random 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
# evaluate
for prec in giant_steps(2, DEFAULT_MAXPREC):
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 will not 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
# Don't attempt substitution or differentiation with non-number symbols
wrt_number = {sym for sym in wrt if sym.kind is NumberKind}
# try numerical evaluation to see if we get two different values
failing_number = None
if wrt_number == 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_number:
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
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 does not, 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
factors = diff.as_coeff_mul()[1]
if len(factors) > 1: # avoid infinity recursion
fac_zero = [fac.equals(0) for fac in factors]
if None not in fac_zero: # every part can be decided
return any(fac_zero)
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.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.calculus.accumulationbounds import AccumBounds
from sympy.functions.elementary.exponential import log
from sympy.series.limits import limit, Limit
from sympy.sets.sets import Interval
from sympy.solvers.solveset import solveset
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 S.Zero
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 S.Zero
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):
if self.is_zero:
return S.Zero
from sympy.functions.elementary.exponential import log
minexp = S.Zero
arg = self
while arg:
minexp += S.One
arg = arg.diff(x)
coeff = arg.subs(x, 0)
if coeff is S.NaN:
coeff = arg.limit(x, 0)
if coeff is 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.polyerrors import PolynomialError, GeneratorsNeeded
from sympy.polys.polytools import Poly
try:
poly = Poly(self, *gens, **args)
if not poly.is_Poly:
return None
else:
return poly
except (PolynomialError, GeneratorsNeeded):
# PolynomialError is caught for e.g. exp(x).as_poly(x)
# GeneratorsNeeded is caught for e.g. S(2).as_poly()
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 the second number negative
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 .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()
"""
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:
from .symbol import Dummy, Symbol
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, _first=True):
"""
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
if _first and self.is_Add and not self_c and not x_c:
# get the part that depends on x exactly
xargs = Mul.make_args(x)
d = Add(*[i for i in Add.make_args(self.as_independent(x)[1])
if all(xi in Mul.make_args(i) for xi in xargs)])
rv = d.coeff(x, right=right, _first=False)
if not rv.is_Add or not right:
return rv
c_part, nc_part = zip(*[i.args_cnc() for i in rv.args])
if has_variety(c_part):
return rv
return Add(*[Mul._from_args(i) for i in nc_part])
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
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, has)
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 cannot 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))
"""
if hints.get('ignore') == self:
return None
else:
from sympy.functions.elementary.complexes import im, re
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) -> tTuple['Expr', 'Expr']:
# 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 do not 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 do not 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 do not 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 do not 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_free(*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 sympy.functions.elementary.exponential import exp
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 or isinstance(self, exp):
sb, se = self.as_base_exp()
cb, ce = c.as_base_exp()
if cb == sb:
new_exp = se.extract_additively(ce)
if new_exp is not None:
return Pow(sb, new_exp)
elif c == sb:
new_exp = self.exp.extract_additively(1)
if new_exp is not None:
return Pow(sb, 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
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, diff = _corem(self, c)
xa0 = (co.extract_additively(1) or 0)*c
if xa0:
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.abc import x, y
>>> (x + y).expr_free_symbols # doctest: +SKIP
{x, y}
If the expression is contained in a non-expression object, do not return
the free symbols. Compare:
>>> from sympy import Tuple
>>> t = Tuple(x + y)
>>> t.expr_free_symbols # doctest: +SKIP
set()
>>> t.free_symbols
{x, y}
"""
sympy_deprecation_warning("""
The expr_free_symbols property is deprecated. Use free_symbols to get
the free symbols of an expression.
""",
deprecated_since_version="1.9",
active_deprecations_target="deprecated-expr-free-symbols")
return {j for i in self.args for j in i.expr_free_symbols}
def could_extract_minus_sign(self):
"""Return True if self has -1 as a leading factor or has
more literal negative signs than positive signs in a sum,
otherwise False.
Examples
========
>>> from sympy.abc import x, y
>>> e = x - y
>>> {i.could_extract_minus_sign() for i in (e, -e)}
{False, True}
Though the ``y - x`` is considered like ``-(x - y)``, since it
is in a product without a leading factor of -1, the result is
false below:
>>> (x*(y - x)).could_extract_minus_sign()
False
To put something in canonical form wrt to sign, use `signsimp`:
>>> from sympy import signsimp
>>> signsimp(x*(y - x))
-x*(x - y)
>>> _.could_extract_minus_sign()
True
"""
return False
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.functions.elementary.exponential import exp_polar
from sympy.functions.elementary.integers import ceiling
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 = []
ipi = S.Pi*S.ImaginaryUnit
while exps:
exp = exps.pop()
if exp.is_Add:
exps += exp.args
continue
if exp.is_Mul:
coeff = exp.as_coefficient(ipi)
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 = ipi*Add(*((c, ) + tail)) + Add(*extras)
if newexp != 0:
res *= exp_polar(newexp)
return res, n
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, Function
>>> 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
>>> (2**x + 1).is_polynomial(2**x)
True
>>> f = Function('f')
>>> (f(x) + 1).is_polynomial(x)
False
>>> (f(x) + 1).is_polynomial(f(x))
True
>>> (1/f(x) + 1).is_polynomial(f(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 not syms:
return True
return self._eval_is_polynomial(syms)
def _eval_is_polynomial(self, syms):
if self in syms:
return True
if not self.has_free(*syms):
# constant polynomial
return True
# subclasses should return True or 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 _illegal:
return False
if syms:
syms = set(map(sympify, syms))
else:
syms = self.free_symbols
if not syms:
return True
return self._eval_is_rational_function(syms)
def _eval_is_rational_function(self, syms):
if self in syms:
return True
if not self.has_free(*syms):
return True
# subclasses should return True or False
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_meromorphic(self, x, a):
if self == x:
return True
if not self.has_free(x):
return True
# subclasses should return True or 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
==========
.. [1] https://en.wikipedia.org/wiki/Algebraic_expression
"""
if syms:
syms = set(map(sympify, syms))
else:
syms = self.free_symbols
if not syms:
return True
return self._eval_is_algebraic_expr(syms)
def _eval_is_algebraic_expr(self, syms):
if self in syms:
return True
if not self.has_free(*syms):
return True
# subclasses should return True or False
###################################################################################
##################### 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
"""
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()
from .symbol import Dummy, Symbol
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]:
from .function import PoleError
try:
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)
except PoleError:
s = self.subs(x, sgn*x).aseries(x, n=n)
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)
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)
from sympy.series.order import Order
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
from sympy.functions.elementary.integers import ceiling
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()
try:
if (s1done + o).removeO() == s1done:
o = S.Zero
except NotImplementedError:
return s1
try:
from sympy.simplify.radsimp import collect
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) # doctest: +SKIP
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] Gruntz, Dominik. A new algorithm for computing asymptotic series.
In: Proc. 1993 Int. Symp. Symbolic and Algebraic Computation. 1993.
pp. 239-244.
.. [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 .symbol import Dummy
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)
from .function import PoleError
from sympy.series.gruntz import mrv, rewrite
try:
om, exps = mrv(self, x)
except PoleError:
return self
# 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).
from sympy.functions.elementary.exponential import exp, log
from sympy.series.order import Order
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])
try:
res = exp(s.subs(x, 1/x).as_leading_term(x).subs(x, 1/x))
except PoleError:
res = self
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 .symbol import Dummy
from sympy.functions.combinatorial.factorials import 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 do not 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 do not 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 only returns self
unless the ``logx`` parameter is used:
>>> e = x**y
>>> e.nseries(x, 0, 2)
x**y
>>> e.nseries(x, 0, 2, logx=logx)
exp(logx*y)
"""
if x and x not 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 do not
have to write docstrings for _eval_nseries().
"""
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.functions.elementary.piecewise import Piecewise, piecewise_fold
if self.has(Piecewise):
expr = piecewise_fold(self)
else:
expr = self
if self.removeO() == 0:
return self
from sympy.series.gruntz import calculate_series
if logx is None:
from .symbol import Dummy
from sympy.functions.elementary.exponential import log
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, logx=None, 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)
"""
if len(symbols) > 1:
c = self
for x in symbols:
c = c.as_leading_term(x, logx=logx, 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, logx=logx, cdir=cdir)
if obj is not None:
from sympy.simplify.powsimp import powsimp
return powsimp(obj, deep=True, combine='exp')
raise NotImplementedError('as_leading_term(%s, %s)' % (self, x))
def _eval_as_leading_term(self, x, logx=None, cdir=0):
return self
def as_coeff_exponent(self, x):
""" ``c*x**e -> c,e`` where x can be any symbolic expression.
"""
from sympy.simplify.radsimp 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, logx=None, 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 .symbol import Dummy
from sympy.functions.elementary.exponential import log
l = self.as_leading_term(x, logx=logx, 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:
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: bool = False) -> tTuple['Number', 'Expr']:
"""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.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.simplify import nsimplify
return nsimplify(self, constants, tolerance, full)
def separate(self, deep=False, force=False):
"""See the separate function in sympy.simplify"""
from .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.radsimp 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.rationaltools import together
return together(self, *args, **kwargs)
def apart(self, x=None, **args):
"""See the apart function in sympy.polys"""
from sympy.polys.partfrac import apart
return apart(self, x, **args)
def ratsimp(self):
"""See the ratsimp function in sympy.simplify"""
from sympy.simplify.ratsimp import ratsimp
return ratsimp(self)
def trigsimp(self, **args):
"""See the trigsimp function in sympy.simplify"""
from sympy.simplify.trigsimp import trigsimp
return trigsimp(self, **args)
def radsimp(self, **kwargs):
"""See the radsimp function in sympy.simplify"""
from sympy.simplify.radsimp import radsimp
return radsimp(self, **kwargs)
def powsimp(self, *args, **kwargs):
"""See the powsimp function in sympy.simplify"""
from sympy.simplify.powsimp import powsimp
return powsimp(self, *args, **kwargs)
def combsimp(self):
"""See the combsimp function in sympy.simplify"""
from sympy.simplify.combsimp import combsimp
return combsimp(self)
def gammasimp(self):
"""See the gammasimp function in sympy.simplify"""
from sympy.simplify.gammasimp import gammasimp
return gammasimp(self)
def factor(self, *gens, **args):
"""See the factor() function in sympy.polys.polytools"""
from sympy.polys.polytools import factor
return factor(self, *gens, **args)
def cancel(self, *gens, **args):
"""See the cancel function in sympy.polys"""
from sympy.polys.polytools 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
"""
if self.is_number and getattr(g, 'is_number', True):
from .numbers import mod_inverse
return mod_inverse(self, g)
from sympy.polys.polytools import invert
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
"""
x = self
if not x.is_number:
raise TypeError("Cannot 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 _illegal:
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 .containers import Tuple
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices.common import MatrixCommon
if isinstance(s, (MatrixCommon, Tuple, Iterable, MatrixExpr)):
return super()._eval_derivative_n_times(s, n)
from .relational import Eq
from sympy.functions.elementary.piecewise import Piecewise
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.accumulationbounds 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):
sympy_deprecation_warning("""
The expr_free_symbols property is deprecated. Use free_symbols to get
the free symbols of an expression.
""",
deprecated_since_version="1.9",
active_deprecations_target="deprecated-expr-free-symbols")
return {self}
def _mag(x):
r"""Return integer $i$ such that $0.1 \le 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
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=None, validator=None, check=True):
if not hasattr(op, "__call__"):
raise TypeError("op {} needs to be callable".format(op))
self.op = op
if args is None:
self.args = []
else:
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 Float, Integer, Rational, _illegal
|
3943d94132f888d44c21206cd0b972cd0260dc617a385158e55a9b63c9f85b6c | """
When you need to use random numbers in SymPy library code, import from here
so there is only one generator working for SymPy. Imports from here should
behave the same as if they were being imported from Python's random module.
But only the routines currently used in SymPy are included here. To use others
import ``rng`` and access the method directly. For example, to capture the
current state of the generator use ``rng.getstate()``.
There is intentionally no Random to import from here. If you want
to control the state of the generator, import ``seed`` and call it
with or without an argument to set the state.
Examples
========
>>> from sympy.core.random import random, seed
>>> assert random() < 1
>>> seed(1); a = random()
>>> b = random()
>>> seed(1); c = random()
>>> assert a == c
>>> assert a != b # remote possibility this will fail
"""
from sympy.utilities.iterables import is_sequence
from sympy.utilities.misc import as_int
import random as _random
rng = _random.Random()
choice = rng.choice
random = rng.random
randint = rng.randint
randrange = rng.randrange
seed = rng.seed
shuffle = rng.shuffle
uniform = rng.uniform
def random_complex_number(a=2, b=-1, c=3, d=1, rational=False, tolerance=None):
"""
Return a random complex number.
To reduce chance of hitting branch cuts or anything, we guarantee
b <= Im z <= d, a <= Re z <= c
When rational is True, a rational approximation to a random number
is obtained within specified tolerance, if any.
"""
from sympy.core.numbers import I
from sympy.simplify.simplify import nsimplify
A, B = uniform(a, c), uniform(b, d)
if not rational:
return A + I*B
return (nsimplify(A, rational=True, tolerance=tolerance) +
I*nsimplify(B, rational=True, tolerance=tolerance))
def verify_numerically(f, g, z=None, tol=1.0e-6, a=2, b=-1, c=3, d=1):
"""
Test numerically that f and g agree when evaluated in the argument z.
If z is None, all symbols will be tested. This routine does not test
whether there are Floats present with precision higher than 15 digits
so if there are, your results may not be what you expect due to round-
off errors.
Examples
========
>>> from sympy import sin, cos
>>> from sympy.abc import x
>>> from sympy.core.random import verify_numerically as tn
>>> tn(sin(x)**2 + cos(x)**2, 1, x)
True
"""
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.core.numbers import comp
f, g = (sympify(i) for i in (f, g))
if z is None:
z = f.free_symbols | g.free_symbols
elif isinstance(z, Symbol):
z = [z]
reps = list(zip(z, [random_complex_number(a, b, c, d) for _ in z]))
z1 = f.subs(reps).n()
z2 = g.subs(reps).n()
return comp(z1, z2, tol)
def test_derivative_numerically(f, z, tol=1.0e-6, a=2, b=-1, c=3, d=1):
"""
Test numerically that the symbolically computed derivative of f
with respect to z is correct.
This routine does not test whether there are Floats present with
precision higher than 15 digits so if there are, your results may
not be what you expect due to round-off errors.
Examples
========
>>> from sympy import sin
>>> from sympy.abc import x
>>> from sympy.core.random import test_derivative_numerically as td
>>> td(sin(x), x)
True
"""
from sympy.core.numbers import comp
from sympy.core.function import Derivative
z0 = random_complex_number(a, b, c, d)
f1 = f.diff(z).subs(z, z0)
f2 = Derivative(f, z).doit_numerically(z0)
return comp(f1.n(), f2.n(), tol)
def _randrange(seed=None):
"""Return a randrange generator.
``seed`` can be
* None - return randomly seeded generator
* int - return a generator seeded with the int
* list - the values to be returned will be taken from the list
in the order given; the provided list is not modified.
Examples
========
>>> from sympy.core.random import _randrange
>>> rr = _randrange()
>>> rr(1000) # doctest: +SKIP
999
>>> rr = _randrange(3)
>>> rr(1000) # doctest: +SKIP
238
>>> rr = _randrange([0, 5, 1, 3, 4])
>>> rr(3), rr(3)
(0, 1)
"""
if seed is None:
return randrange
elif isinstance(seed, int):
rng.seed(seed)
return randrange
elif is_sequence(seed):
seed = list(seed) # make a copy
seed.reverse()
def give(a, b=None, seq=seed):
if b is None:
a, b = 0, a
a, b = as_int(a), as_int(b)
w = b - a
if w < 1:
raise ValueError('_randrange got empty range')
try:
x = seq.pop()
except IndexError:
raise ValueError('_randrange sequence was too short')
if a <= x < b:
return x
else:
return give(a, b, seq)
return give
else:
raise ValueError('_randrange got an unexpected seed')
def _randint(seed=None):
"""Return a randint generator.
``seed`` can be
* None - return randomly seeded generator
* int - return a generator seeded with the int
* list - the values to be returned will be taken from the list
in the order given; the provided list is not modified.
Examples
========
>>> from sympy.core.random import _randint
>>> ri = _randint()
>>> ri(1, 1000) # doctest: +SKIP
999
>>> ri = _randint(3)
>>> ri(1, 1000) # doctest: +SKIP
238
>>> ri = _randint([0, 5, 1, 2, 4])
>>> ri(1, 3), ri(1, 3)
(1, 2)
"""
if seed is None:
return randint
elif isinstance(seed, int):
rng.seed(seed)
return randint
elif is_sequence(seed):
seed = list(seed) # make a copy
seed.reverse()
def give(a, b, seq=seed):
a, b = as_int(a), as_int(b)
w = b - a
if w < 0:
raise ValueError('_randint got empty range')
try:
x = seq.pop()
except IndexError:
raise ValueError('_randint sequence was too short')
if a <= x <= b:
return x
else:
return give(a, b, seq)
return give
else:
raise ValueError('_randint got an unexpected seed')
|
23cf6f8f170eb560d36f0f06a51bc994c3e7679181b45df145311659935397fc | from typing import Dict as tDict, Union as tUnion, Type
from .basic import Atom, Basic
from .sorting import ordered
from .evalf import EvalfMixin
from .function import AppliedUndef
from .singleton import S
from .sympify import _sympify, SympifyError
from .parameters import global_parameters
from .logic import fuzzy_bool, fuzzy_xor, fuzzy_and, fuzzy_not
from sympy.logic.boolalg import Boolean, BooleanAtom
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.iterables import sift
from sympy.utilities.misc import filldedent
__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...
def _canonical_coeff(rel):
# return -2*x + 1 < 0 as x > 1/2
# XXX make this part of Relational.canonical?
rel = rel.canonical
if not rel.is_Relational or rel.rhs.is_Boolean:
return rel # Eq(x, True)
b, l = rel.lhs.as_coeff_Add(rational=True)
m, lhs = l.as_coeff_Mul(rational=True)
rhs = (rel.rhs - b)/m
if m < 0:
return rel.reversed.func(lhs, rhs)
return rel.func(lhs, rhs)
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)
A relation's type can be defined upon creation using ``rop``.
The relation type of an existing expression can be obtained
using its ``rel_op`` property.
Here is a table of all the relation types, along with their
``rop`` and ``rel_op`` values:
+---------------------+----------------------------+------------+
|Relation |``rop`` |``rel_op`` |
+=====================+============================+============+
|``Equality`` |``==`` or ``eq`` or ``None``|``==`` |
+---------------------+----------------------------+------------+
|``Unequality`` |``!=`` or ``ne`` |``!=`` |
+---------------------+----------------------------+------------+
|``GreaterThan`` |``>=`` or ``ge`` |``>=`` |
+---------------------+----------------------------+------------+
|``LessThan`` |``<=`` or ``le`` |``<=`` |
+---------------------+----------------------------+------------+
|``StrictGreaterThan``|``>`` or ``gt`` |``>`` |
+---------------------+----------------------------+------------+
|``StrictLessThan`` |``<`` or ``lt`` |``<`` |
+---------------------+----------------------------+------------+
For example, setting ``rop`` to ``==`` produces an
``Equality`` relation, ``Eq()``.
So does setting ``rop`` to ``eq``, or leaving ``rop`` unspecified.
That is, the first three ``Rel()`` below all produce the same result.
Using a ``rop`` from a different row in the table produces a
different relation type.
For example, the fourth ``Rel()`` below using ``lt`` for ``rop``
produces a ``StrictLessThan`` inequality:
>>> from sympy import Rel
>>> from sympy.abc import x, y
>>> Rel(y, x + x**2, '==')
Eq(y, x**2 + x)
>>> Rel(y, x + x**2, 'eq')
Eq(y, x**2 + x)
>>> Rel(y, x + x**2)
Eq(y, x**2 + x)
>>> Rel(y, x + x**2, 'lt')
y < x**2 + x
To obtain the relation type of an existing expression,
get its ``rel_op`` property.
For example, ``rel_op`` is ``==`` for the ``Equality`` relation above,
and ``<`` for the strict less than inequality above:
>>> from sympy import Rel
>>> from sympy.abc import x, y
>>> my_equality = Rel(y, x + x**2, '==')
>>> my_equality.rel_op
'=='
>>> my_inequality = Rel(y, x + x**2, 'lt')
>>> my_inequality.rel_op
'<'
"""
__slots__ = ()
ValidRelationOperator = {} # type: tDict[tUnion[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))):
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)
@property
def weak(self):
"""return the non-strict version of the inequality or self
EXAMPLES
========
>>> from sympy.abc import x
>>> (x < 1).weak
x <= 1
>>> _.weak
x <= 1
"""
return self
@property
def strict(self):
"""return the strict version of the inequality or self
EXAMPLES
========
>>> from sympy.abc import x
>>> (x <= 1).strict
x < 1
>>> _.strict
x < 1
"""
return self
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
The canonicalization is recursively applied:
>>> from sympy import Eq
>>> Eq(x < y, y > x).canonical
True
"""
args = tuple([i.canonical if isinstance(i, Relational) else i for i in self.args])
if args != self.args:
r = self.func(*args)
if not isinstance(r, Relational):
return r
else:
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 other in (self, self.reversed):
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 .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.polyerrors import PolynomialError
from sympy.polys.polytools import gcd, Poly, poly
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.polytools 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.trigsimp 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.
.. deprecated:: 1.5
``Eq(expr)`` with a single argument is a shorthand for ``Eq(expr, 0)``,
but this behavior is deprecated and will be removed in a future version
of SymPy.
"""
rel_op = '=='
__slots__ = ()
is_Equality = True
def __new__(cls, lhs, rhs=None, **options):
if rhs is None:
sympy_deprecation_warning(
"""
Eq(expr) with a single argument with the right-hand side
defaulting to 0 is deprecated. Use Eq(expr, 0) instead.
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-eq-expr",
)
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. If one side is 0, the
non-zero side 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
if L == 0:
return R
if R == 0:
return L
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):
# standard simplify
e = super()._eval_simplify(**kwargs)
if not isinstance(e, Equality):
return e
from .expr import Expr
if not isinstance(e.lhs, Expr) or not isinstance(e.rhs, Expr):
return e
free = self.free_symbols
if len(free) == 1:
try:
from .add import Add
from sympy.solvers.solveset import linear_coeffs
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.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):
r"""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 $\ge$ 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 $\ge$ rhs |
+----------------------------+-----------------+
|LessThan(lhs, rhs) | lhs $\le$ 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/reference/expressions.html#not-in). 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)
@property
def strict(self):
return Gt(*self.args)
Ge = GreaterThan
class LessThan(_Less):
__doc__ = GreaterThan.__doc__
__slots__ = ()
rel_op = '<='
@classmethod
def _eval_fuzzy_relation(cls, lhs, rhs):
return is_le(lhs, rhs)
@property
def strict(self):
return Lt(*self.args)
Le = LessThan
class StrictGreaterThan(_Greater):
__doc__ = GreaterThan.__doc__
__slots__ = ()
rel_op = '>'
@classmethod
def _eval_fuzzy_relation(cls, lhs, rhs):
return is_gt(lhs, rhs)
@property
def weak(self):
return Ge(*self.args)
Gt = StrictGreaterThan
class StrictLessThan(_Less):
__doc__ = GreaterThan.__doc__
__slots__ = ()
rel_op = '<'
@classmethod
def _eval_fuzzy_relation(cls, lhs, rhs):
return is_lt(lhs, rhs)
@property
def weak(self):
return Le(*self.args)
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
"""
# 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
from sympy.assumptions.wrapper import (AssumptionsWrapper,
is_infinite, is_extended_real)
from .add import Add
_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]))
from sympy.functions.elementary.complexes import arg
# 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
from sympy.simplify.simplify import clear_coefficients
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
|
7e6d14634a9b749ec5037ab5c642ec7219464f0454802dd999aff48728d1a952 | import numbers
import decimal
import fractions
import math
import re as regex
import sys
from functools import lru_cache
from typing import Set as tSet, Tuple as tTuple
from .containers import Tuple
from .sympify import (SympifyError, _sympy_converter, sympify, _convert_numpy_types,
_sympify, _is_numpy_instance)
from .singleton import S, Singleton
from .basic import Basic
from .expr import Expr, AtomicExpr
from .evalf import pure_complex
from .cache import cacheit, clear_cache
from .decorators import _sympifyit
from .logic import fuzzy_not
from .kind import NumberKind
from sympy.external.gmpy import SYMPY_INTS, HAS_GMPY, gmpy
from sympy.multipledispatch import dispatch
import mpmath
import mpmath.libmp as mlib
from mpmath.libmp import bitcount, round_nearest as rnd
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, dps_to_prec)
from sympy.utilities.misc import as_int, debug, filldedent
from .parameters import global_parameters
_LOG2 = math.log(2)
def comp(z1, z2, tol=None):
r"""Return a bool indicating whether the error between z1 and z2
is $\le$ ``tol``.
Examples
========
If ``tol`` is ``None`` then ``True`` will be returned if
:math:`|z1 - z2|\times 10^p \le 5` where $p$ is minimum value of the
decimal precision of each value.
>>> from sympy 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
:math:`|z1| > 1` the error is normalized by :math:`|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 :math:`|z1| \le 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 isinstance(z2, 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 _ 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, _ = 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 [1]_. To
improve speed, ``igcd()`` has its own caching mechanism.
Examples
========
>>> from sympy import igcd
>>> igcd(2, 4)
2
>>> igcd(5, 10, 15)
5
References
==========
.. [1] https://en.wikipedia.org/wiki/Euclidean_algorithm
"""
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):
r"""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 \times b + r$$,
where the quotient $q$ and the remainder $r$ are integers
and $0 \le 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 [1]_ 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 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):
r"""
Return the number $c$ such that, $a \times c = 1 \pmod{m}$
where $c$ has the same sign as $m$. If no such value exists,
a ValueError is raised.
Examples
========
>>> from sympy import mod_inverse, S
Suppose we wish to find multiplicative inverse $x$ of
3 modulo 11. This is the same as finding $x$ such
that $3x = 1 \pmod{11}$. One value of x that satisfies
this congruence is 4. Because $3 \times 4 = 12$ and $12 = 1 \pmod{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, _, 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 big not in (S.true, 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 could_extract_minus_sign(self):
return bool(self.is_extended_negative)
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 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.series.order 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 in (S.Infinity, 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.polytools import gcd
return gcd(self, other)
def lcm(self, other):
"""Compute LCM of `self` and `other`. """
from sympy.polys.polytools import lcm
return lcm(self, other)
def cofactors(self, other):
"""Compute GCD and cofactors of `self` and `other`. """
from sympy.polys.polytools 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')
_mpf_: tTuple[int, int, int, int]
# 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, precision=None):
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()
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 math.isnan(num):
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 = 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 = 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 = 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 isinstance(num[1], str):
# it's a hexadecimal (coming from a pickled object)
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]
# Strip leading '0x' - gmpy2 only documents such inputs
# with base prefix as valid when the 2nd argument (base) is 0.
# When mpmath uses Sage as the backend, however, it
# ends up including '0x' when preparing the picklable tuple.
# See issue #19690.
if num[1].startswith('0x'):
num[1] = num[1][2:]
# Now we can assume that it is in standard form
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_ in (_mpf_ninf, _mpf_inf):
return False
return self.num < 0
def _eval_is_positive(self):
if self._mpf_ in (_mpf_ninf, _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):
if not self:
return 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_extended_positive:
return self
if expt.is_extended_negative:
return S.ComplexInfinity
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):
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 __format__(self, format_spec):
return format(decimal.Decimal(str(self)), format_spec)
# Add sympify converters
_sympy_converter[float] = _sympy_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
If an unevaluated Rational is desired, ``gcd=1`` can be passed and
this will keep common divisors of the numerator and denominator
from being eliminated. It is not possible, however, to leave a
negative value in the denominator.
>>> Rational(2, 4, gcd=1)
2/4
>>> Rational(2, -4, gcd=1).q
4
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')
p: int
q: int
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
if not isinstance(p, SYMPY_INTS):
p = Rational(p)
q *= p.q
p = p.p
else:
p = int(p)
if not isinstance(q, SYMPY_INTS):
q = Rational(q)
p *= q.q
q = q.p
else:
q = int(q)
# p and q are now ints
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):
intpart = expt.p // expt.q
if intpart:
intpart += 1
remfracpart = intpart*expt.q - expt.p
ratfracpart = Rational(remfracpart, expt.q)
if self.p != 1:
return Integer(self.p)**expt*Integer(self.q)**ratfracpart*Rational(1, self.q**intpart, 1)
return Integer(self.q)**ratfracpart*Rational(1, self.q**intpart, 1)
else:
remfracpart = expt.q - expt.p
ratfracpart = Rational(remfracpart, expt.q)
if self.p != 1:
return Integer(self.p)**expt*Integer(self.q)**ratfracpart*Rational(1, self.q, 1)
return Integer(self.q)**ratfracpart*Rational(1, self.q, 1)
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):
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
from .power import integer_log
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 isinstance(rv, 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 isinstance(rv, 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 isinstance(rv, 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 isinstance(rv, 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.factor_ 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(
igcd(self.p, other.p),
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 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__ = ()
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):
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):
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, 1)**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, 1)**ne
else:
return Rational(1, self.p, 1)**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, 1))
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.primetest 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)
# These bitwise operations (__lshift__, __rlshift__, ..., __invert__) are defined
# for Integer only and not for general SymPy expressions. This is to achieve
# compatibility with the numbers.Integral ABC which only defines these operations
# among instances of numbers.Integral. Therefore, these methods check explicitly for
# integer types rather than using sympify because they should not accept arbitrary
# symbolic expressions and there is no symbolic analogue of numbers.Integral's
# bitwise operations.
def __lshift__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p << int(other))
else:
return NotImplemented
def __rlshift__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) << self.p)
else:
return NotImplemented
def __rshift__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p >> int(other))
else:
return NotImplemented
def __rrshift__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) >> self.p)
else:
return NotImplemented
def __and__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p & int(other))
else:
return NotImplemented
def __rand__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) & self.p)
else:
return NotImplemented
def __xor__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p ^ int(other))
else:
return NotImplemented
def __rxor__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) ^ self.p)
else:
return NotImplemented
def __or__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p | int(other))
else:
return NotImplemented
def __ror__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) | self.p)
else:
return NotImplemented
def __invert__(self):
return Integer(~self.p)
# Add sympify converters
_sympy_converter[int] = Integer
class AlgebraicNumber(Expr):
r"""
Class for representing algebraic numbers in SymPy.
Symbolically, an instance of this class represents an element
$\alpha \in \mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$. That is, the
algebraic number $\alpha$ is represented as an element of a particular
number field $\mathbb{Q}(\theta)$, with a particular embedding of this
field into the complex numbers.
Formally, the primitive element $\theta$ is given by two data points: (1)
its minimal polynomial (which defines $\mathbb{Q}(\theta)$), and (2) a
particular complex number that is a root of this polynomial (which defines
the embedding $\mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$). Finally,
the algebraic number $\alpha$ which we represent is then given by the
coefficients of a polynomial in $\theta$.
"""
__slots__ = ('rep', 'root', 'alias', 'minpoly', '_own_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: tSet[Basic] = set()
def __new__(cls, expr, coeffs=None, alias=None, **args):
r"""
Construct a new algebraic number $\alpha$ belonging to a number field
$k = \mathbb{Q}(\theta)$.
There are four instance attributes to be determined:
=========== ============================================================================
Attribute Type/Meaning
=========== ============================================================================
``root`` :py:class:`~.Expr` for $\theta$ as a complex number
``minpoly`` :py:class:`~.Poly`, the minimal polynomial of $\theta$
``rep`` :py:class:`~sympy.polys.polyclasses.DMP` giving $\alpha$ as poly in $\theta$
``alias`` :py:class:`~.Symbol` for $\theta$, or ``None``
=========== ============================================================================
See Parameters section for how they are determined.
Parameters
==========
expr : :py:class:`~.Expr`, or pair $(m, r)$
There are three distinct modes of construction, depending on what
is passed as *expr*.
**(1)** *expr* is an :py:class:`~.AlgebraicNumber`:
In this case we begin by copying all four instance attributes from
*expr*. If *coeffs* were also given, we compose the two coeff
polynomials (see below). If an *alias* was given, it overrides.
**(2)** *expr* is any other type of :py:class:`~.Expr`:
Then ``root`` will equal *expr*. Therefore it
must express an algebraic quantity, and we will compute its
``minpoly``.
**(3)** *expr* is an ordered pair $(m, r)$ giving the
``minpoly`` $m$, and a ``root`` $r$ thereof, which together
define $\theta$. In this case $m$ may be either a univariate
:py:class:`~.Poly` or any :py:class:`~.Expr` which represents the
same, while $r$ must be some :py:class:`~.Expr` representing a
complex number that is a root of $m$, including both explicit
expressions in radicals, and instances of
:py:class:`~.ComplexRootOf` or :py:class:`~.AlgebraicNumber`.
coeffs : list, :py:class:`~.ANP`, None, optional (default=None)
This defines ``rep``, giving the algebraic number $\alpha$ as a
polynomial in $\theta$.
If a list, the elements should be integers or rational numbers.
If an :py:class:`~.ANP`, we take its coefficients (using its
:py:meth:`~.ANP.to_list()` method). If ``None``, then the list of
coefficients defaults to ``[1, 0]``, meaning that $\alpha = \theta$
is the primitive element of the field.
If *expr* was an :py:class:`~.AlgebraicNumber`, let $g(x)$ be its
``rep`` polynomial, and let $f(x)$ be the polynomial defined by
*coeffs*. Then ``self.rep`` will represent the composition
$(f \circ g)(x)$.
alias : str, :py:class:`~.Symbol`, None, optional (default=None)
This is a way to provide a name for the primitive element. We
described several ways in which the *expr* argument can define the
value of the primitive element, but none of these methods gave it
a name. Here, for example, *alias* could be set as
``Symbol('theta')``, in order to make this symbol appear when
$\alpha$ is printed, or rendered as a polynomial, using the
:py:meth:`~.as_poly()` method.
Examples
========
Recall that we are constructing an algebraic number as a field element
$\alpha \in \mathbb{Q}(\theta)$.
>>> from sympy import AlgebraicNumber, sqrt, CRootOf, S
>>> from sympy.abc import x
Example (1): $\alpha = \theta = \sqrt{2}$
>>> a1 = AlgebraicNumber(sqrt(2))
>>> a1.minpoly_of_element().as_expr(x)
x**2 - 2
>>> a1.evalf(10)
1.414213562
Example (2): $\alpha = 3 \sqrt{2} - 5$, $\theta = \sqrt{2}$. We can
either build on the last example:
>>> a2 = AlgebraicNumber(a1, [3, -5])
>>> a2.as_expr()
-5 + 3*sqrt(2)
or start from scratch:
>>> a2 = AlgebraicNumber(sqrt(2), [3, -5])
>>> a2.as_expr()
-5 + 3*sqrt(2)
Example (3): $\alpha = 6 \sqrt{2} - 11$, $\theta = \sqrt{2}$. Again we
can build on the previous example, and we see that the coeff polys are
composed:
>>> a3 = AlgebraicNumber(a2, [2, -1])
>>> a3.as_expr()
-11 + 6*sqrt(2)
reflecting the fact that $(2x - 1) \circ (3x - 5) = 6x - 11$.
Example (4): $\alpha = \sqrt{2}$, $\theta = \sqrt{2} + \sqrt{3}$. The
easiest way is to use the :py:func:`~.to_number_field()` function:
>>> from sympy import to_number_field
>>> a4 = to_number_field(sqrt(2), sqrt(2) + sqrt(3))
>>> a4.minpoly_of_element().as_expr(x)
x**2 - 2
>>> a4.to_root()
sqrt(2)
>>> a4.primitive_element()
sqrt(2) + sqrt(3)
>>> a4.coeffs()
[1/2, 0, -9/2, 0]
but if you already knew the right coefficients, you could construct it
directly:
>>> a4 = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1)/2, 0, S(-9)/2, 0])
>>> a4.to_root()
sqrt(2)
>>> a4.primitive_element()
sqrt(2) + sqrt(3)
Example (5): Construct the Golden Ratio as an element of the 5th
cyclotomic field, supposing we already know its coefficients. This time
we introduce the alias $\zeta$ for the primitive element of the field:
>>> from sympy import cyclotomic_poly
>>> from sympy.abc import zeta
>>> a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1),
... [-1, -1, 0, 0], alias=zeta)
>>> a5.as_poly().as_expr()
-zeta**3 - zeta**2
>>> a5.evalf()
1.61803398874989
(The index ``-1`` to ``CRootOf`` selects the complex root with the
largest real and imaginary parts, which in this case is
$\mathrm{e}^{2i\pi/5}$. See :py:class:`~.ComplexRootOf`.)
Example (6): Building on the last example, construct the number
$2 \phi \in \mathbb{Q}(\phi)$, where $\phi$ is the Golden Ratio:
>>> from sympy.abc import phi
>>> a6 = AlgebraicNumber(a5.to_root(), coeffs=[2, 0], alias=phi)
>>> a6.as_poly().as_expr()
2*phi
>>> a6.primitive_element().evalf()
1.61803398874989
Note that we needed to use ``a5.to_root()``, since passing ``a5`` as
the first argument would have constructed the number $2 \phi$ as an
element of the field $\mathbb{Q}(\zeta)$:
>>> a6_wrong = AlgebraicNumber(a5, coeffs=[2, 0])
>>> a6_wrong.as_poly().as_expr()
-2*zeta**3 - 2*zeta**2
>>> a6_wrong.primitive_element().evalf()
0.309016994374947 + 0.951056516295154*I
"""
from sympy.polys.polyclasses import ANP, DMP
from sympy.polys.numberfields import minimal_polynomial
expr = sympify(expr)
rep0 = None
alias0 = None
if isinstance(expr, (tuple, Tuple)):
minpoly, root = expr
if not minpoly.is_Poly:
from sympy.polys.polytools import Poly
minpoly = Poly(minpoly)
elif expr.is_AlgebraicNumber:
minpoly, root, rep0, alias0 = (expr.minpoly, expr.root,
expr.rep, expr.alias)
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())
else:
rep = DMP.from_list([1, 0], 0, dom)
scoeffs = Tuple(1, 0)
if rep0 is not None:
from sympy.polys.densetools import dup_compose
c = dup_compose(rep.rep, rep0.rep, dom)
rep = DMP.from_list(c, 0, dom)
scoeffs = Tuple(*c)
if rep.degree() >= minpoly.degree():
rep = rep.rem(minpoly.rep)
sargs = (root, scoeffs)
alias = alias or alias0
if alias is not None:
from .symbol import Symbol
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
obj._own_minpoly = None
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.polys.polytools import 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:
from .symbol import Dummy
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.polys.polytools 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.rootoftools import CRootOf
from sympy.polys import 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
def field_element(self, coeffs):
r"""
Form another element of the same number field.
Explanation
===========
If we represent $\alpha \in \mathbb{Q}(\theta)$, form another element
$\beta \in \mathbb{Q}(\theta)$ of the same number field.
Parameters
==========
coeffs : list, :py:class:`~.ANP`
Like the *coeffs* arg to the class
:py:meth:`constructor<.AlgebraicNumber.__new__>`, defines the
new element as a polynomial in the primitive element.
If a list, the elements should be integers or rational numbers.
If an :py:class:`~.ANP`, we take its coefficients (using its
:py:meth:`~.ANP.to_list()` method).
Examples
========
>>> from sympy import AlgebraicNumber, sqrt
>>> a = AlgebraicNumber(sqrt(5), [-1, 1])
>>> b = a.field_element([3, 2])
>>> print(a)
1 - sqrt(5)
>>> print(b)
2 + 3*sqrt(5)
>>> print(b.primitive_element() == a.primitive_element())
True
See Also
========
.AlgebraicNumber.__new__()
"""
return AlgebraicNumber(
(self.minpoly, self.root), coeffs=coeffs, alias=self.alias)
@property
def is_primitive_element(self):
r"""
Say whether this algebraic number $\alpha \in \mathbb{Q}(\theta)$ is
equal to the primitive element $\theta$ for its field.
"""
c = self.coeffs()
# Second case occurs if self.minpoly is linear:
return c == [1, 0] or c == [self.root]
def primitive_element(self):
r"""
Get the primitive element $\theta$ for the number field
$\mathbb{Q}(\theta)$ to which this algebraic number $\alpha$ belongs.
Returns
=======
AlgebraicNumber
"""
if self.is_primitive_element:
return self
return self.field_element([1, 0])
def to_primitive_element(self, radicals=True):
r"""
Convert ``self`` to an :py:class:`~.AlgebraicNumber` instance that is
equal to its own primitive element.
Explanation
===========
If we represent $\alpha \in \mathbb{Q}(\theta)$, $\alpha \neq \theta$,
construct a new :py:class:`~.AlgebraicNumber` that represents
$\alpha \in \mathbb{Q}(\alpha)$.
Examples
========
>>> from sympy import sqrt, to_number_field
>>> from sympy.abc import x
>>> a = to_number_field(sqrt(2), sqrt(2) + sqrt(3))
The :py:class:`~.AlgebraicNumber` ``a`` represents the number
$\sqrt{2}$ in the field $\mathbb{Q}(\sqrt{2} + \sqrt{3})$. Rendering
``a`` as a polynomial,
>>> a.as_poly().as_expr(x)
x**3/2 - 9*x/2
reflects the fact that $\sqrt{2} = \theta^3/2 - 9 \theta/2$, where
$\theta = \sqrt{2} + \sqrt{3}$.
``a`` is not equal to its own primitive element. Its minpoly
>>> a.minpoly.as_poly().as_expr(x)
x**4 - 10*x**2 + 1
is that of $\theta$.
Converting to a primitive element,
>>> a_prim = a.to_primitive_element()
>>> a_prim.minpoly.as_poly().as_expr(x)
x**2 - 2
we obtain an :py:class:`~.AlgebraicNumber` whose ``minpoly`` is that of
the number itself.
Parameters
==========
radicals : boolean, optional (default=True)
If ``True``, then we will try to return an
:py:class:`~.AlgebraicNumber` whose ``root`` is an expression
in radicals. If that is not possible (or if *radicals* is
``False``), ``root`` will be a :py:class:`~.ComplexRootOf`.
Returns
=======
AlgebraicNumber
See Also
========
is_primitive_element
"""
if self.is_primitive_element:
return self
m = self.minpoly_of_element()
r = self.to_root(radicals=radicals)
return AlgebraicNumber((m, r))
def minpoly_of_element(self):
r"""
Compute the minimal polynomial for this algebraic number.
Explanation
===========
Recall that we represent an element $\alpha \in \mathbb{Q}(\theta)$.
Our instance attribute ``self.minpoly`` is the minimal polynomial for
our primitive element $\theta$. This method computes the minimal
polynomial for $\alpha$.
"""
if self._own_minpoly is None:
if self.is_primitive_element:
self._own_minpoly = self.minpoly
else:
from sympy.polys.numberfields.minpoly import minpoly
theta = self.primitive_element()
self._own_minpoly = minpoly(self.as_expr(theta), polys=True)
return self._own_minpoly
def to_root(self, radicals=True, minpoly=None):
"""
Convert to an :py:class:`~.Expr` that is not an
:py:class:`~.AlgebraicNumber`, specifically, either a
:py:class:`~.ComplexRootOf`, or, optionally and where possible, an
expression in radicals.
Parameters
==========
radicals : boolean, optional (default=True)
If ``True``, then we will try to return the root as an expression
in radicals. If that is not possible, we will return a
:py:class:`~.ComplexRootOf`.
minpoly : :py:class:`~.Poly`
If the minimal polynomial for `self` has been pre-computed, it can
be passed in order to save time.
"""
if self.is_primitive_element and not isinstance(self.root, AlgebraicNumber):
return self.root
m = minpoly or self.minpoly_of_element()
roots = m.all_roots(radicals=radicals)
if len(roots) == 1:
return roots[0]
ex = self.as_expr()
for b in roots:
if m.same_root(b, ex):
return b
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_extended_positive:
return self
if expt.is_extended_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
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 in (S.Infinity, 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 in (S.NegativeInfinity, 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 in (S.Infinity, 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
"""
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:
from sympy.functions.elementary.complexes import re
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 __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 in (S.Infinity, 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 in (S.NegativeInfinity, 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
inf_part = S.Infinity**expt
s_part = S.NegativeOne**expt
if inf_part == 0 and s_part.is_finite:
return inf_part
if (inf_part is S.ComplexInfinity and
s_part.is_finite and not s_part.is_zero):
return S.ComplexInfinity
return s_part*inf_part
def _as_mpf_val(self, prec):
return mlib.fninf
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 __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
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):
if global_parameters.exp_is_pow:
return self._eval_power_exp_is_pow(expt)
else:
from sympy.functions.elementary.exponential import exp
return exp(expt)
def _eval_power_exp_is_pow(self, arg):
if arg.is_Number:
if arg is oo:
return oo
elif arg == -oo:
return S.Zero
from sympy.functions.elementary.exponential import log
if 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.functions.elementary.trigonometric import sin
return sin(I + S.Pi/2) - I*sin(I)
def _eval_rewrite_as_cos(self, **kwargs):
from sympy.functions.elementary.trigonometric import cos
return cos(I) + I*cos(I + S.Pi/2)
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, 1), Rational(22, 7, 1))
pi = S.Pi
class GoldenRatio(NumberSymbol, metaclass=Singleton):
r"""The golden ratio, `\phi`.
Explanation
===========
`\phi = \frac{1 + \sqrt{5}}{2}` is an 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.functions.elementary.miscellaneous 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
_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 1
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.functions.elementary.miscellaneous import cbrt, sqrt
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, 1))
class Catalan(NumberSymbol, metaclass=Singleton):
r"""Catalan's constant.
Explanation
===========
$G = 0.91596559\ldots$ is given by the infinite series
.. math:: G = \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, 1), S.One)
def _eval_rewrite_as_Sum(self, k_sym=None, symbols=None):
if (k_sym is not None) or (symbols is not None):
return self
from .symbol import Dummy
from sympy.concrete.summations import Sum
k = Dummy('k', integer=True, nonnegative=True)
return Sum(S.NegativeOne**k / (2*k+1)**2, (k, 0, S.Infinity))
def _latex(self, printer):
return "G"
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
@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)
_sympy_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))
_sympy_converter[type(gmpy.mpz(1))] = sympify_mpz
_sympy_converter[type(gmpy.mpq(1, 2))] = sympify_mpq
def sympify_mpmath_mpq(x):
p, q = x._mpq_
return Rational(p, q, 1)
_sympy_converter[type(mpmath.rational.mpq(1, 2))] = sympify_mpmath_mpq
def sympify_mpmath(x):
return Expr._from_mpmath(x, x.context.prec)
_sympy_converter[mpnumeric] = sympify_mpmath
def sympify_complex(a):
real, imag = list(map(sympify, (a.real, a.imag)))
return real + S.ImaginaryUnit*imag
_sympy_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.Integral.register(Integer)
_register_classes()
_illegal = (S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity)
|
3230623b567b3afaa9522f5e615e8374750484447b20351aafcc508c2dad254f | from operator import attrgetter
from typing import Tuple as tTuple, Type
from collections import defaultdict
from sympy.utilities.exceptions import sympy_deprecation_warning
from .sympify import _sympify as _sympify_, sympify
from .basic import Basic
from .cache import cacheit
from .sorting import ordered
from .logic import fuzzy_and
from .parameters import global_parameters
from sympy.utilities.iterables import sift
from sympy.multipledispatch.dispatcher import (Dispatcher,
ambiguity_register_error_ignore_dup,
str_signature, RaiseNotImplementedError)
class AssocOp(Basic):
""" Associative operations, can separate noncommutative and
commutative parts.
(a op b) op c == a op (b op c) == a op b op c.
Base class for Add and Mul.
This is an abstract base class, concrete derived classes must define
the attribute `identity`.
.. deprecated:: 1.7
Using arguments that aren't subclasses of :class:`~.Expr` in core
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
deprecated. See :ref:`non-expr-args-deprecated` for details.
Parameters
==========
*args :
Arguments which are operated
evaluate : bool, optional
Evaluate the operation. If not passed, refer to ``global_parameters.evaluate``.
"""
# for performance reason, we don't let is_commutative go to assumptions,
# and keep it right here
__slots__ = ('is_commutative',) # type: tTuple[str, ...]
_args_type = None # type: Type[Basic]
@cacheit
def __new__(cls, *args, evaluate=None, _sympify=True):
# Allow faster processing by passing ``_sympify=False``, if all arguments
# are already sympified.
if _sympify:
args = list(map(_sympify_, args))
# Disallow non-Expr args in Add/Mul
typ = cls._args_type
if typ is not None:
from .relational import Relational
if any(isinstance(arg, Relational) for arg in args):
raise TypeError("Relational cannot be used in %s" % cls.__name__)
# This should raise TypeError once deprecation period is over:
for arg in args:
if not isinstance(arg, typ):
sympy_deprecation_warning(
f"""
Using non-Expr arguments in {cls.__name__} is deprecated (in this case, one of
the arguments has type {type(arg).__name__!r}).
If you really did intend to use a multiplication or addition operation with
this object, use the * or + operator instead.
""",
deprecated_since_version="1.7",
active_deprecations_target="non-expr-args-deprecated",
stacklevel=4,
)
if evaluate is None:
evaluate = global_parameters.evaluate
if not evaluate:
obj = cls._from_args(args)
obj = cls._exec_constructor_postprocessors(obj)
return obj
args = [a for a in args if a is not cls.identity]
if len(args) == 0:
return cls.identity
if len(args) == 1:
return args[0]
c_part, nc_part, order_symbols = cls.flatten(args)
is_commutative = not nc_part
obj = cls._from_args(c_part + nc_part, is_commutative)
obj = cls._exec_constructor_postprocessors(obj)
if order_symbols is not None:
from sympy.series.order import Order
return Order(obj, *order_symbols)
return obj
@classmethod
def _from_args(cls, args, is_commutative=None):
"""Create new instance with already-processed args.
If the args are not in canonical order, then a non-canonical
result will be returned, so use with caution. The order of
args may change if the sign of the args is changed."""
if len(args) == 0:
return cls.identity
elif len(args) == 1:
return args[0]
obj = super().__new__(cls, *args)
if is_commutative is None:
is_commutative = fuzzy_and(a.is_commutative for a in args)
obj.is_commutative = is_commutative
return obj
def _new_rawargs(self, *args, reeval=True, **kwargs):
"""Create new instance of own class with args exactly as provided by
caller but returning the self class identity if args is empty.
Examples
========
This is handy when we want to optimize things, e.g.
>>> from sympy import Mul, S
>>> from sympy.abc import x, y
>>> e = Mul(3, x, y)
>>> e.args
(3, x, y)
>>> Mul(*e.args[1:])
x*y
>>> e._new_rawargs(*e.args[1:]) # the same as above, but faster
x*y
Note: use this with caution. There is no checking of arguments at
all. This is best used when you are rebuilding an Add or Mul after
simply removing one or more args. If, for example, modifications,
result in extra 1s being inserted they will show up in the result:
>>> m = (x*y)._new_rawargs(S.One, x); m
1*x
>>> m == x
False
>>> m.is_Mul
True
Another issue to be aware of is that the commutativity of the result
is based on the commutativity of self. If you are rebuilding the
terms that came from a commutative object then there will be no
problem, but if self was non-commutative then what you are
rebuilding may now be commutative.
Although this routine tries to do as little as possible with the
input, getting the commutativity right is important, so this level
of safety is enforced: commutativity will always be recomputed if
self is non-commutative and kwarg `reeval=False` has not been
passed.
"""
if reeval and self.is_commutative is False:
is_commutative = None
else:
is_commutative = self.is_commutative
return self._from_args(args, is_commutative)
@classmethod
def flatten(cls, seq):
"""Return seq so that none of the elements are of type `cls`. This is
the vanilla routine that will be used if a class derived from AssocOp
does not define its own flatten routine."""
# apply associativity, no commutativity property is used
new_seq = []
while seq:
o = seq.pop()
if o.__class__ is cls: # classes must match exactly
seq.extend(o.args)
else:
new_seq.append(o)
new_seq.reverse()
# c_part, nc_part, order_symbols
return [], new_seq, None
def _matches_commutative(self, expr, repl_dict=None, old=False):
"""
Matches Add/Mul "pattern" to an expression "expr".
repl_dict ... a dictionary of (wild: expression) pairs, that get
returned with the results
This function is the main workhorse for Add/Mul.
Examples
========
>>> from sympy import symbols, Wild, sin
>>> a = Wild("a")
>>> b = Wild("b")
>>> c = Wild("c")
>>> x, y, z = symbols("x y z")
>>> (a+sin(b)*c)._matches_commutative(x+sin(y)*z)
{a_: x, b_: y, c_: z}
In the example above, "a+sin(b)*c" is the pattern, and "x+sin(y)*z" is
the expression.
The repl_dict contains parts that were already matched. For example
here:
>>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z, repl_dict={a: x})
{a_: x, b_: y, c_: z}
the only function of the repl_dict is to return it in the
result, e.g. if you omit it:
>>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z)
{b_: y, c_: z}
the "a: x" is not returned in the result, but otherwise it is
equivalent.
"""
from .function import _coeff_isneg
# make sure expr is Expr if pattern is Expr
from .expr import Expr
if isinstance(self, Expr) and not isinstance(expr, Expr):
return None
if repl_dict is None:
repl_dict = dict()
# handle simple patterns
if self == expr:
return repl_dict
d = self._matches_simple(expr, repl_dict)
if d is not None:
return d
# eliminate exact part from pattern: (2+a+w1+w2).matches(expr) -> (w1+w2).matches(expr-a-2)
from .function import WildFunction
from .symbol import Wild
wild_part, exact_part = sift(self.args, lambda p:
p.has(Wild, WildFunction) and not expr.has(p),
binary=True)
if not exact_part:
wild_part = list(ordered(wild_part))
if self.is_Add:
# in addition to normal ordered keys, impose
# sorting on Muls with leading Number to put
# them in order
wild_part = sorted(wild_part, key=lambda x:
x.args[0] if x.is_Mul and x.args[0].is_Number else
0)
else:
exact = self._new_rawargs(*exact_part)
free = expr.free_symbols
if free and (exact.free_symbols - free):
# there are symbols in the exact part that are not
# in the expr; but if there are no free symbols, let
# the matching continue
return None
newexpr = self._combine_inverse(expr, exact)
if not old and (expr.is_Add or expr.is_Mul):
check = newexpr
if _coeff_isneg(check):
check = -check
if check.count_ops() > expr.count_ops():
return None
newpattern = self._new_rawargs(*wild_part)
return newpattern.matches(newexpr, repl_dict)
# now to real work ;)
i = 0
saw = set()
while expr not in saw:
saw.add(expr)
args = tuple(ordered(self.make_args(expr)))
if self.is_Add and expr.is_Add:
# in addition to normal ordered keys, impose
# sorting on Muls with leading Number to put
# them in order
args = tuple(sorted(args, key=lambda x:
x.args[0] if x.is_Mul and x.args[0].is_Number else
0))
expr_list = (self.identity,) + args
for last_op in reversed(expr_list):
for w in reversed(wild_part):
d1 = w.matches(last_op, repl_dict)
if d1 is not None:
d2 = self.xreplace(d1).matches(expr, d1)
if d2 is not None:
return d2
if i == 0:
if self.is_Mul:
# make e**i look like Mul
if expr.is_Pow and expr.exp.is_Integer:
from .mul import Mul
if expr.exp > 0:
expr = Mul(*[expr.base, expr.base**(expr.exp - 1)], evaluate=False)
else:
expr = Mul(*[1/expr.base, expr.base**(expr.exp + 1)], evaluate=False)
i += 1
continue
elif self.is_Add:
# make i*e look like Add
c, e = expr.as_coeff_Mul()
if abs(c) > 1:
from .add import Add
if c > 0:
expr = Add(*[e, (c - 1)*e], evaluate=False)
else:
expr = Add(*[-e, (c + 1)*e], evaluate=False)
i += 1
continue
# try collection on non-Wild symbols
from sympy.simplify.radsimp import collect
was = expr
did = set()
for w in reversed(wild_part):
c, w = w.as_coeff_mul(Wild)
free = c.free_symbols - did
if free:
did.update(free)
expr = collect(expr, free)
if expr != was:
i += 0
continue
break # if we didn't continue, there is nothing more to do
return
def _has_matcher(self):
"""Helper for .has() that checks for containment of
subexpressions within an expr by using sets of args
of similar nodes, e.g. x + 1 in x + y + 1 checks
to see that {x, 1} & {x, y, 1} == {x, 1}
"""
def _ncsplit(expr):
# this is not the same as args_cnc because here
# we don't assume expr is a Mul -- hence deal with args --
# and always return a set.
cpart, ncpart = sift(expr.args,
lambda arg: arg.is_commutative is True, binary=True)
return set(cpart), ncpart
c, nc = _ncsplit(self)
cls = self.__class__
def is_in(expr):
if isinstance(expr, cls):
if expr == self:
return True
_c, _nc = _ncsplit(expr)
if (c & _c) == c:
if not nc:
return True
elif len(nc) <= len(_nc):
for i in range(len(_nc) - len(nc) + 1):
if _nc[i:i + len(nc)] == nc:
return True
return False
return is_in
def _eval_evalf(self, prec):
"""
Evaluate the parts of self that are numbers; if the whole thing
was a number with no functions it would have been evaluated, but
it wasn't so we must judiciously extract the numbers and reconstruct
the object. This is *not* simply replacing numbers with evaluated
numbers. Numbers should be handled in the largest pure-number
expression as possible. So the code below separates ``self`` into
number and non-number parts and evaluates the number parts and
walks the args of the non-number part recursively (doing the same
thing).
"""
from .add import Add
from .mul import Mul
from .symbol import Symbol
from .function import AppliedUndef
if isinstance(self, (Mul, Add)):
x, tail = self.as_independent(Symbol, AppliedUndef)
# if x is an AssocOp Function then the _evalf below will
# call _eval_evalf (here) so we must break the recursion
if not (tail is self.identity or
isinstance(x, AssocOp) and x.is_Function or
x is self.identity and isinstance(tail, AssocOp)):
# here, we have a number so we just call to _evalf with prec;
# prec is not the same as n, it is the binary precision so
# that's why we don't call to evalf.
x = x._evalf(prec) if x is not self.identity else self.identity
args = []
tail_args = tuple(self.func.make_args(tail))
for a in tail_args:
# here we call to _eval_evalf since we don't know what we
# are dealing with and all other _eval_evalf routines should
# be doing the same thing (i.e. taking binary prec and
# finding the evalf-able args)
newa = a._eval_evalf(prec)
if newa is None:
args.append(a)
else:
args.append(newa)
return self.func(x, *args)
# this is the same as above, but there were no pure-number args to
# deal with
args = []
for a in self.args:
newa = a._eval_evalf(prec)
if newa is None:
args.append(a)
else:
args.append(newa)
return self.func(*args)
@classmethod
def make_args(cls, expr):
"""
Return a sequence of elements `args` such that cls(*args) == expr
Examples
========
>>> from sympy import Symbol, Mul, Add
>>> x, y = map(Symbol, 'xy')
>>> Mul.make_args(x*y)
(x, y)
>>> Add.make_args(x*y)
(x*y,)
>>> set(Add.make_args(x*y + y)) == set([y, x*y])
True
"""
if isinstance(expr, cls):
return expr.args
else:
return (sympify(expr),)
def doit(self, **hints):
if hints.get('deep', True):
terms = [term.doit(**hints) for term in self.args]
else:
terms = self.args
return self.func(*terms, evaluate=True)
class ShortCircuit(Exception):
pass
class LatticeOp(AssocOp):
"""
Join/meet operations of an algebraic lattice[1].
Explanation
===========
These binary operations are associative (op(op(a, b), c) = op(a, op(b, c))),
commutative (op(a, b) = op(b, a)) and idempotent (op(a, a) = op(a) = a).
Common examples are AND, OR, Union, Intersection, max or min. They have an
identity element (op(identity, a) = a) and an absorbing element
conventionally called zero (op(zero, a) = zero).
This is an abstract base class, concrete derived classes must declare
attributes zero and identity. All defining properties are then respected.
Examples
========
>>> from sympy import Integer
>>> from sympy.core.operations import LatticeOp
>>> class my_join(LatticeOp):
... zero = Integer(0)
... identity = Integer(1)
>>> my_join(2, 3) == my_join(3, 2)
True
>>> my_join(2, my_join(3, 4)) == my_join(2, 3, 4)
True
>>> my_join(0, 1, 4, 2, 3, 4)
0
>>> my_join(1, 2)
2
References:
.. [1] https://en.wikipedia.org/wiki/Lattice_%28order%29
"""
is_commutative = True
def __new__(cls, *args, **options):
args = (_sympify_(arg) for arg in args)
try:
# /!\ args is a generator and _new_args_filter
# must be careful to handle as such; this
# is done so short-circuiting can be done
# without having to sympify all values
_args = frozenset(cls._new_args_filter(args))
except ShortCircuit:
return sympify(cls.zero)
if not _args:
return sympify(cls.identity)
elif len(_args) == 1:
return set(_args).pop()
else:
# XXX in almost every other case for __new__, *_args is
# passed along, but the expectation here is for _args
obj = super(AssocOp, cls).__new__(cls, *ordered(_args))
obj._argset = _args
return obj
@classmethod
def _new_args_filter(cls, arg_sequence, call_cls=None):
"""Generator filtering args"""
ncls = call_cls or cls
for arg in arg_sequence:
if arg == ncls.zero:
raise ShortCircuit(arg)
elif arg == ncls.identity:
continue
elif arg.func == ncls:
yield from arg.args
else:
yield arg
@classmethod
def make_args(cls, expr):
"""
Return a set of args such that cls(*arg_set) == expr.
"""
if isinstance(expr, cls):
return expr._argset
else:
return frozenset([sympify(expr)])
@staticmethod
def _compare_pretty(a, b):
return (str(a) > str(b)) - (str(a) < str(b))
class AssocOpDispatcher:
"""
Handler dispatcher for associative operators
.. notes::
This approach is experimental, and can be replaced or deleted in the future.
See https://github.com/sympy/sympy/pull/19463.
Explanation
===========
If arguments of different types are passed, the classes which handle the operation for each type
are collected. Then, a class which performs the operation is selected by recursive binary dispatching.
Dispatching relation can be registered by ``register_handlerclass`` method.
Priority registration is unordered. You cannot make ``A*B`` and ``B*A`` refer to
different handler classes. All logic dealing with the order of arguments must be implemented
in the handler class.
Examples
========
>>> from sympy import Add, Expr, Symbol
>>> from sympy.core.add import add
>>> class NewExpr(Expr):
... @property
... def _add_handler(self):
... return NewAdd
>>> class NewAdd(NewExpr, Add):
... pass
>>> add.register_handlerclass((Add, NewAdd), NewAdd)
>>> a, b = Symbol('a'), NewExpr()
>>> add(a, b) == NewAdd(a, b)
True
"""
def __init__(self, name, doc=None):
self.name = name
self.doc = doc
self.handlerattr = "_%s_handler" % name
self._handlergetter = attrgetter(self.handlerattr)
self._dispatcher = Dispatcher(name)
def __repr__(self):
return "<dispatched %s>" % self.name
def register_handlerclass(self, classes, typ, on_ambiguity=ambiguity_register_error_ignore_dup):
"""
Register the handler class for two classes, in both straight and reversed order.
Paramteters
===========
classes : tuple of two types
Classes who are compared with each other.
typ:
Class which is registered to represent *cls1* and *cls2*.
Handler method of *self* must be implemented in this class.
"""
if not len(classes) == 2:
raise RuntimeError(
"Only binary dispatch is supported, but got %s types: <%s>." % (
len(classes), str_signature(classes)
))
if len(set(classes)) == 1:
raise RuntimeError(
"Duplicate types <%s> cannot be dispatched." % str_signature(classes)
)
self._dispatcher.add(tuple(classes), typ, on_ambiguity=on_ambiguity)
self._dispatcher.add(tuple(reversed(classes)), typ, on_ambiguity=on_ambiguity)
@cacheit
def __call__(self, *args, _sympify=True, **kwargs):
"""
Parameters
==========
*args :
Arguments which are operated
"""
if _sympify:
args = tuple(map(_sympify_, args))
handlers = frozenset(map(self._handlergetter, args))
# no need to sympify again
return self.dispatch(handlers)(*args, _sympify=False, **kwargs)
@cacheit
def dispatch(self, handlers):
"""
Select the handler class, and return its handler method.
"""
# Quick exit for the case where all handlers are same
if len(handlers) == 1:
h, = handlers
if not isinstance(h, type):
raise RuntimeError("Handler {!r} is not a type.".format(h))
return h
# Recursively select with registered binary priority
for i, typ in enumerate(handlers):
if not isinstance(typ, type):
raise RuntimeError("Handler {!r} is not a type.".format(typ))
if i == 0:
handler = typ
else:
prev_handler = handler
handler = self._dispatcher.dispatch(prev_handler, typ)
if not isinstance(handler, type):
raise RuntimeError(
"Dispatcher for {!r} and {!r} must return a type, but got {!r}".format(
prev_handler, typ, handler
))
# return handler class
return handler
@property
def __doc__(self):
docs = [
"Multiply dispatched associative operator: %s" % self.name,
"Note that support for this is experimental, see the docs for :class:`AssocOpDispatcher` for details"
]
if self.doc:
docs.append(self.doc)
s = "Registered handler classes\n"
s += '=' * len(s)
docs.append(s)
amb_sigs = []
typ_sigs = defaultdict(list)
for sigs in self._dispatcher.ordering[::-1]:
key = self._dispatcher.funcs[sigs]
typ_sigs[key].append(sigs)
for typ, sigs in typ_sigs.items():
sigs_str = ', '.join('<%s>' % str_signature(sig) for sig in sigs)
if isinstance(typ, RaiseNotImplementedError):
amb_sigs.append(sigs_str)
continue
s = 'Inputs: %s\n' % sigs_str
s += '-' * len(s) + '\n'
s += typ.__name__
docs.append(s)
if amb_sigs:
s = "Ambiguous handler classes\n"
s += '=' * len(s)
docs.append(s)
s = '\n'.join(amb_sigs)
docs.append(s)
return '\n\n'.join(docs)
|
0ea2338644fd4a1b3e6e3ec764fe3ccb21a7c9f01dcf94cfe080b62b9179f6a9 | from .assumptions import StdFactKB, _assume_defined
from .basic import Basic, Atom
from .cache import cacheit
from .containers import Tuple
from .expr import Expr, AtomicExpr
from .function import AppliedUndef, FunctionClass
from .kind import NumberKind, UndefinedKind
from .logic import fuzzy_bool
from .singleton import S
from .sorting import ordered
from .sympify import sympify
from sympy.logic.boolalg import Boolean
from sympy.utilities.iterables import sift, is_sequence
from sympy.utilities.misc import filldedent
import string
import re as _re
import random
from itertools import product
class Str(Atom):
"""
Represents string in SymPy.
Explanation
===========
Previously, ``Symbol`` was used where string is needed in ``args`` of SymPy
objects, e.g. denoting the name of the instance. However, since ``Symbol``
represents mathematical scalar, this class should be used instead.
"""
__slots__ = ('name',)
def __new__(cls, name, **kwargs):
if not isinstance(name, str):
raise TypeError("name should be a string, not %s" % repr(type(name)))
obj = Expr.__new__(cls, **kwargs)
obj.name = name
return obj
def __getnewargs__(self):
return (self.name,)
def _hashable_content(self):
return (self.name,)
def _filter_assumptions(kwargs):
"""Split the given dict into assumptions and non-assumptions.
Keys are taken as assumptions if they correspond to an
entry in ``_assume_defined``.
"""
assumptions, nonassumptions = map(dict, sift(kwargs.items(),
lambda i: i[0] in _assume_defined,
binary=True))
Symbol._sanitize(assumptions)
return assumptions, nonassumptions
def _symbol(s, matching_symbol=None, **assumptions):
"""Return s if s is a Symbol, else if s is a string, return either
the matching_symbol if the names are the same or else a new symbol
with the same assumptions as the matching symbol (or the
assumptions as provided).
Examples
========
>>> from sympy import Symbol
>>> from sympy.core.symbol import _symbol
>>> _symbol('y')
y
>>> _.is_real is None
True
>>> _symbol('y', real=True).is_real
True
>>> x = Symbol('x')
>>> _symbol(x, real=True)
x
>>> _.is_real is None # ignore attribute if s is a Symbol
True
Below, the variable sym has the name 'foo':
>>> sym = Symbol('foo', real=True)
Since 'x' is not the same as sym's name, a new symbol is created:
>>> _symbol('x', sym).name
'x'
It will acquire any assumptions give:
>>> _symbol('x', sym, real=False).is_real
False
Since 'foo' is the same as sym's name, sym is returned
>>> _symbol('foo', sym)
foo
Any assumptions given are ignored:
>>> _symbol('foo', sym, real=False).is_real
True
NB: the symbol here may not be the same as a symbol with the same
name defined elsewhere as a result of different assumptions.
See Also
========
sympy.core.symbol.Symbol
"""
if isinstance(s, str):
if matching_symbol and matching_symbol.name == s:
return matching_symbol
return Symbol(s, **assumptions)
elif isinstance(s, Symbol):
return s
else:
raise ValueError('symbol must be string for symbol name or Symbol')
def uniquely_named_symbol(xname, exprs=(), compare=str, modify=None, **assumptions):
"""
Return a symbol whose name is derivated from *xname* but is unique
from any other symbols in *exprs*.
*xname* and symbol names in *exprs* are passed to *compare* to be
converted to comparable forms. If ``compare(xname)`` is not unique,
it is recursively passed to *modify* until unique name is acquired.
Parameters
==========
xname : str or Symbol
Base name for the new symbol.
exprs : Expr or iterable of Expr
Expressions whose symbols are compared to *xname*.
compare : function
Unary function which transforms *xname* and symbol names from
*exprs* to comparable form.
modify : function
Unary function which modifies the string. Default is appending
the number, or increasing the number if exists.
Examples
========
By default, a number is appended to *xname* to generate unique name.
If the number already exists, it is recursively increased.
>>> from sympy.core.symbol import uniquely_named_symbol, Symbol
>>> uniquely_named_symbol('x', Symbol('x'))
x0
>>> uniquely_named_symbol('x', (Symbol('x'), Symbol('x0')))
x1
>>> uniquely_named_symbol('x0', (Symbol('x1'), Symbol('x0')))
x2
Name generation can be controlled by passing *modify* parameter.
>>> from sympy.abc import x
>>> uniquely_named_symbol('x', x, modify=lambda s: 2*s)
xx
"""
def numbered_string_incr(s, start=0):
if not s:
return str(start)
i = len(s) - 1
while i != -1:
if not s[i].isdigit():
break
i -= 1
n = str(int(s[i + 1:] or start - 1) + 1)
return s[:i + 1] + n
default = None
if is_sequence(xname):
xname, default = xname
x = compare(xname)
if not exprs:
return _symbol(x, default, **assumptions)
if not is_sequence(exprs):
exprs = [exprs]
names = set().union(
[i.name for e in exprs for i in e.atoms(Symbol)] +
[i.func.name for e in exprs for i in e.atoms(AppliedUndef)])
if modify is None:
modify = numbered_string_incr
while any(x == compare(s) for s in names):
x = modify(x)
return _symbol(x, default, **assumptions)
_uniquely_named_symbol = uniquely_named_symbol
class Symbol(AtomicExpr, Boolean):
"""
Assumptions:
commutative = True
You can override the default assumptions in the constructor.
Examples
========
>>> from sympy import symbols
>>> A,B = symbols('A,B', commutative = False)
>>> bool(A*B != B*A)
True
>>> bool(A*B*2 == 2*A*B) == True # multiplication by scalars is commutative
True
"""
is_comparable = False
__slots__ = ('name',)
name: str
is_Symbol = True
is_symbol = True
@property
def kind(self):
if self.is_commutative:
return NumberKind
return UndefinedKind
@property
def _diff_wrt(self):
"""Allow derivatives wrt Symbols.
Examples
========
>>> from sympy import Symbol
>>> x = Symbol('x')
>>> x._diff_wrt
True
"""
return True
@staticmethod
def _sanitize(assumptions, obj=None):
"""Remove None, covert values to bool, check commutativity *in place*.
"""
# be strict about commutativity: cannot be None
is_commutative = fuzzy_bool(assumptions.get('commutative', True))
if is_commutative is None:
whose = '%s ' % obj.__name__ if obj else ''
raise ValueError(
'%scommutativity must be True or False.' % whose)
# sanitize other assumptions so 1 -> True and 0 -> False
for key in list(assumptions.keys()):
v = assumptions[key]
if v is None:
assumptions.pop(key)
continue
assumptions[key] = bool(v)
def _merge(self, assumptions):
base = self.assumptions0
for k in set(assumptions) & set(base):
if assumptions[k] != base[k]:
raise ValueError(filldedent('''
non-matching assumptions for %s: existing value
is %s and new value is %s''' % (
k, base[k], assumptions[k])))
base.update(assumptions)
return base
def __new__(cls, name, **assumptions):
"""Symbols are identified by name and assumptions::
>>> from sympy import Symbol
>>> Symbol("x") == Symbol("x")
True
>>> Symbol("x", real=True) == Symbol("x", real=False)
False
"""
cls._sanitize(assumptions, cls)
return Symbol.__xnew_cached_(cls, name, **assumptions)
def __new_stage2__(cls, name, **assumptions):
if not isinstance(name, str):
raise TypeError("name should be a string, not %s" % repr(type(name)))
obj = Expr.__new__(cls)
obj.name = name
# TODO: Issue #8873: Forcing the commutative assumption here means
# later code such as ``srepr()`` cannot tell whether the user
# specified ``commutative=True`` or omitted it. To workaround this,
# we keep a copy of the assumptions dict, then create the StdFactKB,
# and finally overwrite its ``._generator`` with the dict copy. This
# is a bit of a hack because we assume StdFactKB merely copies the
# given dict as ``._generator``, but future modification might, e.g.,
# compute a minimal equivalent assumption set.
tmp_asm_copy = assumptions.copy()
# be strict about commutativity
is_commutative = fuzzy_bool(assumptions.get('commutative', True))
assumptions['commutative'] = is_commutative
obj._assumptions = StdFactKB(assumptions)
obj._assumptions._generator = tmp_asm_copy # Issue #8873
return obj
__xnew__ = staticmethod(
__new_stage2__) # never cached (e.g. dummy)
__xnew_cached_ = staticmethod(
cacheit(__new_stage2__)) # symbols are always cached
def __getnewargs_ex__(self):
return ((self.name,), self.assumptions0)
# NOTE: __setstate__ is not needed for pickles created by __getnewargs_ex__
# but was used before Symbol was changed to use __getnewargs_ex__ in v1.9.
# Pickles created in previous SymPy versions will still need __setstate__
# so that they can be unpickled in SymPy > v1.9.
def __setstate__(self, state):
for name, value in state.items():
setattr(self, name, value)
def _hashable_content(self):
# Note: user-specified assumptions not hashed, just derived ones
return (self.name,) + tuple(sorted(self.assumptions0.items()))
def _eval_subs(self, old, new):
if old.is_Pow:
from sympy.core.power import Pow
return Pow(self, S.One, evaluate=False)._eval_subs(old, new)
def _eval_refine(self, assumptions):
return self
@property
def assumptions0(self):
return {key: value for key, value
in self._assumptions.items() if value is not None}
@cacheit
def sort_key(self, order=None):
return self.class_key(), (1, (self.name,)), S.One.sort_key(), S.One
def as_dummy(self):
# only put commutativity in explicitly if it is False
return Dummy(self.name) if self.is_commutative is not False \
else Dummy(self.name, commutative=self.is_commutative)
def as_real_imag(self, deep=True, **hints):
if hints.get('ignore') == self:
return None
else:
from sympy.functions.elementary.complexes import im, re
return (re(self), im(self))
def is_constant(self, *wrt, **flags):
if not wrt:
return False
return self not in wrt
@property
def free_symbols(self):
return {self}
binary_symbols = free_symbols # in this case, not always
def as_set(self):
return S.UniversalSet
class Dummy(Symbol):
"""Dummy symbols are each unique, even if they have the same name:
Examples
========
>>> from sympy import Dummy
>>> Dummy("x") == Dummy("x")
False
If a name is not supplied then a string value of an internal count will be
used. This is useful when a temporary variable is needed and the name
of the variable used in the expression is not important.
>>> Dummy() #doctest: +SKIP
_Dummy_10
"""
# In the rare event that a Dummy object needs to be recreated, both the
# `name` and `dummy_index` should be passed. This is used by `srepr` for
# example:
# >>> d1 = Dummy()
# >>> d2 = eval(srepr(d1))
# >>> d2 == d1
# True
#
# If a new session is started between `srepr` and `eval`, there is a very
# small chance that `d2` will be equal to a previously-created Dummy.
_count = 0
_prng = random.Random()
_base_dummy_index = _prng.randint(10**6, 9*10**6)
__slots__ = ('dummy_index',)
is_Dummy = True
def __new__(cls, name=None, dummy_index=None, **assumptions):
if dummy_index is not None:
assert name is not None, "If you specify a dummy_index, you must also provide a name"
if name is None:
name = "Dummy_" + str(Dummy._count)
if dummy_index is None:
dummy_index = Dummy._base_dummy_index + Dummy._count
Dummy._count += 1
cls._sanitize(assumptions, cls)
obj = Symbol.__xnew__(cls, name, **assumptions)
obj.dummy_index = dummy_index
return obj
def __getnewargs_ex__(self):
return ((self.name, self.dummy_index), self.assumptions0)
@cacheit
def sort_key(self, order=None):
return self.class_key(), (
2, (self.name, self.dummy_index)), S.One.sort_key(), S.One
def _hashable_content(self):
return Symbol._hashable_content(self) + (self.dummy_index,)
class Wild(Symbol):
"""
A Wild symbol matches anything, or anything
without whatever is explicitly excluded.
Parameters
==========
name : str
Name of the Wild instance.
exclude : iterable, optional
Instances in ``exclude`` will not be matched.
properties : iterable of functions, optional
Functions, each taking an expressions as input
and returns a ``bool``. All functions in ``properties``
need to return ``True`` in order for the Wild instance
to match the expression.
Examples
========
>>> from sympy import Wild, WildFunction, cos, pi
>>> from sympy.abc import x, y, z
>>> a = Wild('a')
>>> x.match(a)
{a_: x}
>>> pi.match(a)
{a_: pi}
>>> (3*x**2).match(a*x)
{a_: 3*x}
>>> cos(x).match(a)
{a_: cos(x)}
>>> b = Wild('b', exclude=[x])
>>> (3*x**2).match(b*x)
>>> b.match(a)
{a_: b_}
>>> A = WildFunction('A')
>>> A.match(a)
{a_: A_}
Tips
====
When using Wild, be sure to use the exclude
keyword to make the pattern more precise.
Without the exclude pattern, you may get matches
that are technically correct, but not what you
wanted. For example, using the above without
exclude:
>>> from sympy import symbols
>>> a, b = symbols('a b', cls=Wild)
>>> (2 + 3*y).match(a*x + b*y)
{a_: 2/x, b_: 3}
This is technically correct, because
(2/x)*x + 3*y == 2 + 3*y, but you probably
wanted it to not match at all. The issue is that
you really did not want a and b to include x and y,
and the exclude parameter lets you specify exactly
this. With the exclude parameter, the pattern will
not match.
>>> a = Wild('a', exclude=[x, y])
>>> b = Wild('b', exclude=[x, y])
>>> (2 + 3*y).match(a*x + b*y)
Exclude also helps remove ambiguity from matches.
>>> E = 2*x**3*y*z
>>> a, b = symbols('a b', cls=Wild)
>>> E.match(a*b)
{a_: 2*y*z, b_: x**3}
>>> a = Wild('a', exclude=[x, y])
>>> E.match(a*b)
{a_: z, b_: 2*x**3*y}
>>> a = Wild('a', exclude=[x, y, z])
>>> E.match(a*b)
{a_: 2, b_: x**3*y*z}
Wild also accepts a ``properties`` parameter:
>>> a = Wild('a', properties=[lambda k: k.is_Integer])
>>> E.match(a*b)
{a_: 2, b_: x**3*y*z}
"""
is_Wild = True
__slots__ = ('exclude', 'properties')
def __new__(cls, name, exclude=(), properties=(), **assumptions):
exclude = tuple([sympify(x) for x in exclude])
properties = tuple(properties)
cls._sanitize(assumptions, cls)
return Wild.__xnew__(cls, name, exclude, properties, **assumptions)
def __getnewargs__(self):
return (self.name, self.exclude, self.properties)
@staticmethod
@cacheit
def __xnew__(cls, name, exclude, properties, **assumptions):
obj = Symbol.__xnew__(cls, name, **assumptions)
obj.exclude = exclude
obj.properties = properties
return obj
def _hashable_content(self):
return super()._hashable_content() + (self.exclude, self.properties)
# TODO add check against another Wild
def matches(self, expr, repl_dict=None, old=False):
if any(expr.has(x) for x in self.exclude):
return None
if not all(f(expr) for f in self.properties):
return None
if repl_dict is None:
repl_dict = dict()
else:
repl_dict = repl_dict.copy()
repl_dict[self] = expr
return repl_dict
_range = _re.compile('([0-9]*:[0-9]+|[a-zA-Z]?:[a-zA-Z])')
def symbols(names, *, cls=Symbol, **args):
r"""
Transform strings into instances of :class:`Symbol` class.
:func:`symbols` function returns a sequence of symbols with names taken
from ``names`` argument, which can be a comma or whitespace delimited
string, or a sequence of strings::
>>> from sympy import symbols, Function
>>> x, y, z = symbols('x,y,z')
>>> a, b, c = symbols('a b c')
The type of output is dependent on the properties of input arguments::
>>> symbols('x')
x
>>> symbols('x,')
(x,)
>>> symbols('x,y')
(x, y)
>>> symbols(('a', 'b', 'c'))
(a, b, c)
>>> symbols(['a', 'b', 'c'])
[a, b, c]
>>> symbols({'a', 'b', 'c'})
{a, b, c}
If an iterable container is needed for a single symbol, set the ``seq``
argument to ``True`` or terminate the symbol name with a comma::
>>> symbols('x', seq=True)
(x,)
To reduce typing, range syntax is supported to create indexed symbols.
Ranges are indicated by a colon and the type of range is determined by
the character to the right of the colon. If the character is a digit
then all contiguous digits to the left are taken as the nonnegative
starting value (or 0 if there is no digit left of the colon) and all
contiguous digits to the right are taken as 1 greater than the ending
value::
>>> symbols('x:10')
(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9)
>>> symbols('x5:10')
(x5, x6, x7, x8, x9)
>>> symbols('x5(:2)')
(x50, x51)
>>> symbols('x5:10,y:5')
(x5, x6, x7, x8, x9, y0, y1, y2, y3, y4)
>>> symbols(('x5:10', 'y:5'))
((x5, x6, x7, x8, x9), (y0, y1, y2, y3, y4))
If the character to the right of the colon is a letter, then the single
letter to the left (or 'a' if there is none) is taken as the start
and all characters in the lexicographic range *through* the letter to
the right are used as the range::
>>> symbols('x:z')
(x, y, z)
>>> symbols('x:c') # null range
()
>>> symbols('x(:c)')
(xa, xb, xc)
>>> symbols(':c')
(a, b, c)
>>> symbols('a:d, x:z')
(a, b, c, d, x, y, z)
>>> symbols(('a:d', 'x:z'))
((a, b, c, d), (x, y, z))
Multiple ranges are supported; contiguous numerical ranges should be
separated by parentheses to disambiguate the ending number of one
range from the starting number of the next::
>>> symbols('x:2(1:3)')
(x01, x02, x11, x12)
>>> symbols(':3:2') # parsing is from left to right
(00, 01, 10, 11, 20, 21)
Only one pair of parentheses surrounding ranges are removed, so to
include parentheses around ranges, double them. And to include spaces,
commas, or colons, escape them with a backslash::
>>> symbols('x((a:b))')
(x(a), x(b))
>>> symbols(r'x(:1\,:2)') # or r'x((:1)\,(:2))'
(x(0,0), x(0,1))
All newly created symbols have assumptions set according to ``args``::
>>> a = symbols('a', integer=True)
>>> a.is_integer
True
>>> x, y, z = symbols('x,y,z', real=True)
>>> x.is_real and y.is_real and z.is_real
True
Despite its name, :func:`symbols` can create symbol-like objects like
instances of Function or Wild classes. To achieve this, set ``cls``
keyword argument to the desired type::
>>> symbols('f,g,h', cls=Function)
(f, g, h)
>>> type(_[0])
<class 'sympy.core.function.UndefinedFunction'>
"""
result = []
if isinstance(names, str):
marker = 0
literals = [r'\,', r'\:', r'\ ']
for i in range(len(literals)):
lit = literals.pop(0)
if lit in names:
while chr(marker) in names:
marker += 1
lit_char = chr(marker)
marker += 1
names = names.replace(lit, lit_char)
literals.append((lit_char, lit[1:]))
def literal(s):
if literals:
for c, l in literals:
s = s.replace(c, l)
return s
names = names.strip()
as_seq = names.endswith(',')
if as_seq:
names = names[:-1].rstrip()
if not names:
raise ValueError('no symbols given')
# split on commas
names = [n.strip() for n in names.split(',')]
if not all(n for n in names):
raise ValueError('missing symbol between commas')
# split on spaces
for i in range(len(names) - 1, -1, -1):
names[i: i + 1] = names[i].split()
seq = args.pop('seq', as_seq)
for name in names:
if not name:
raise ValueError('missing symbol')
if ':' not in name:
symbol = cls(literal(name), **args)
result.append(symbol)
continue
split = _range.split(name)
# remove 1 layer of bounding parentheses around ranges
for i in range(len(split) - 1):
if i and ':' in split[i] and split[i] != ':' and \
split[i - 1].endswith('(') and \
split[i + 1].startswith(')'):
split[i - 1] = split[i - 1][:-1]
split[i + 1] = split[i + 1][1:]
for i, s in enumerate(split):
if ':' in s:
if s[-1].endswith(':'):
raise ValueError('missing end range')
a, b = s.split(':')
if b[-1] in string.digits:
a = 0 if not a else int(a)
b = int(b)
split[i] = [str(c) for c in range(a, b)]
else:
a = a or 'a'
split[i] = [string.ascii_letters[c] for c in range(
string.ascii_letters.index(a),
string.ascii_letters.index(b) + 1)] # inclusive
if not split[i]:
break
else:
split[i] = [s]
else:
seq = True
if len(split) == 1:
names = split[0]
else:
names = [''.join(s) for s in product(*split)]
if literals:
result.extend([cls(literal(s), **args) for s in names])
else:
result.extend([cls(s, **args) for s in names])
if not seq and len(result) <= 1:
if not result:
return ()
return result[0]
return tuple(result)
else:
for name in names:
result.append(symbols(name, **args))
return type(names)(result)
def var(names, **args):
"""
Create symbols and inject them into the global namespace.
Explanation
===========
This calls :func:`symbols` with the same arguments and puts the results
into the *global* namespace. It's recommended not to use :func:`var` in
library code, where :func:`symbols` has to be used::
Examples
========
>>> from sympy import var
>>> var('x')
x
>>> x # noqa: F821
x
>>> var('a,ab,abc')
(a, ab, abc)
>>> abc # noqa: F821
abc
>>> var('x,y', real=True)
(x, y)
>>> x.is_real and y.is_real # noqa: F821
True
See :func:`symbols` documentation for more details on what kinds of
arguments can be passed to :func:`var`.
"""
def traverse(symbols, frame):
"""Recursively inject symbols to the global namespace. """
for symbol in symbols:
if isinstance(symbol, Basic):
frame.f_globals[symbol.name] = symbol
elif isinstance(symbol, FunctionClass):
frame.f_globals[symbol.__name__] = symbol
else:
traverse(symbol, frame)
from inspect import currentframe
frame = currentframe().f_back
try:
syms = symbols(names, **args)
if syms is not None:
if isinstance(syms, Basic):
frame.f_globals[syms.name] = syms
elif isinstance(syms, FunctionClass):
frame.f_globals[syms.__name__] = syms
else:
traverse(syms, frame)
finally:
del frame # break cyclic dependencies as stated in inspect docs
return syms
def disambiguate(*iter):
"""
Return a Tuple containing the passed expressions with symbols
that appear the same when printed replaced with numerically
subscripted symbols, and all Dummy symbols replaced with Symbols.
Parameters
==========
iter: list of symbols or expressions.
Examples
========
>>> from sympy.core.symbol import disambiguate
>>> from sympy import Dummy, Symbol, Tuple
>>> from sympy.abc import y
>>> tup = Symbol('_x'), Dummy('x'), Dummy('x')
>>> disambiguate(*tup)
(x_2, x, x_1)
>>> eqs = Tuple(Symbol('x')/y, Dummy('x')/y)
>>> disambiguate(*eqs)
(x_1/y, x/y)
>>> ix = Symbol('x', integer=True)
>>> vx = Symbol('x')
>>> disambiguate(vx + ix)
(x + x_1,)
To make your own mapping of symbols to use, pass only the free symbols
of the expressions and create a dictionary:
>>> free = eqs.free_symbols
>>> mapping = dict(zip(free, disambiguate(*free)))
>>> eqs.xreplace(mapping)
(x_1/y, x/y)
"""
new_iter = Tuple(*iter)
key = lambda x:tuple(sorted(x.assumptions0.items()))
syms = ordered(new_iter.free_symbols, keys=key)
mapping = {}
for s in syms:
mapping.setdefault(str(s).lstrip('_'), []).append(s)
reps = {}
for k in mapping:
# the first or only symbol doesn't get subscripted but make
# sure that it's a Symbol, not a Dummy
mapk0 = Symbol("%s" % (k), **mapping[k][0].assumptions0)
if mapping[k][0] != mapk0:
reps[mapping[k][0]] = mapk0
# the others get subscripts (and are made into Symbols)
skip = 0
for i in range(1, len(mapping[k])):
while True:
name = "%s_%i" % (k, i + skip)
if name not in mapping:
break
skip += 1
ki = mapping[k][i]
reps[ki] = Symbol(name, **ki.assumptions0)
return new_iter.xreplace(reps)
|
5d01fb7b39918ba977476dea307376c1f03e60c4566e1d986233d8ecb468de5a | """
.. deprecated:: 1.10
``sympy.core.compatibility`` is deprecated. See
:ref:`sympy-core-compatibility`.
Reimplementations of constructs introduced in later versions of Python than
we support. Also some functions that are needed SymPy-wide and are located
here for easy import.
"""
from sympy.utilities.exceptions import sympy_deprecation_warning
sympy_deprecation_warning("""
The sympy.core.compatibility submodule is deprecated.
This module was only ever intended for internal use. Some of the functions
that were in this module are available from the top-level SymPy namespace,
i.e.,
from sympy import ordered, default_sort_key
The remaining were only intended for internal SymPy use and should not be used
by user code.
""",
deprecated_since_version="1.10",
active_deprecations_target="deprecated-sympy-core-compatibility",
)
from .sorting import ordered, _nodes, default_sort_key # noqa:F401
from sympy.utilities.misc import as_int as _as_int # noqa:F401
from sympy.utilities.iterables import iterable, is_sequence, NotIterable # noqa:F401
|
9f07c6fe669b7c7ae4a8e08e46084171e749fa0b2b2364ceef253fbaacbf5aec | """sympify -- convert objects SymPy internal format"""
import typing
if typing.TYPE_CHECKING:
from typing import Any, Callable, Dict as tDict, Type
from inspect import getmro
import string
from sympy.core.random import choice
from .parameters import global_parameters
from sympy.utilities.exceptions import sympy_deprecation_warning
from sympy.utilities.iterables import iterable
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)))
converter = {} # type: tDict[Type[Any], Callable[[Any], Basic]]
#holds the conversions defined in SymPy itself, i.e. non-user defined conversions
_sympy_converter = {} # type: tDict[Type[Any], Callable[[Any], Basic]]
#alias for clearer use in the library
_external_converter = converter
class CantSympify:
"""
Mix in this trait to a class to disallow sympification of its instances.
Examples
========
>>> from sympy import sympify
>>> from sympy.core.sympify import CantSympify
>>> class Something(dict):
... pass
...
>>> sympify(Something())
{}
>>> class Something(dict, CantSympify):
... pass
...
>>> sympify(Something())
Traceback (most recent call last):
...
SympifyError: SympifyError: {}
"""
__slots__ = ()
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 _sympy_converter[complex](a.item())
else:
return sympify(a.item(), **sympify_args)
else:
try:
from .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 :class:`~.Integer`, floats
into instances of :class:`~.Float`, etc. It is also able to coerce
symbolic expressions which inherit from :class:`~.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 :class:`~.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
.. deprecated:: 1.6
``sympify(obj)`` automatically falls back to ``str(obj)`` when all
other conversion methods fail, but this is deprecated. ``strict=True``
will disable this deprecated behavior. See
:ref:`deprecated-sympify-string-fallback`.
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)
- dicts, lists, sets or tuples containing any of the above
convert_xor : bool, optional
If true, treats ``^`` as exponentiation.
If False, treats ``^`` 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 : bool, 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 : bool, optional
If ``True``, converts floats into :class:`~.Rational`.
If ``False``, it lets floats remain as it is.
Used only when input is a string.
evaluate : bool, 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)
#Check if there exists a converter for any of the types in the mro
for superclass in getmro(cls):
#First check for user defined converters
conv = _external_converter.get(superclass)
if conv is None:
#if none exists, check for SymPy defined converters
conv = _sympy_converter.get(superclass)
if conv is not None:
return conv(a)
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 sympy.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)
sympy_deprecation_warning(
f"""
The string fallback in sympify() is deprecated.
To explicitly convert the string form of an object, use
sympify(str(obj)). To add define sympify behavior on custom
objects, use sympy.core.sympify.converter or define obj._sympy_
(see the sympify() docstring).
sympify() performed the string fallback resulting in the following string:
{a!r}
""",
deprecated_since_version='1.6',
active_deprecations_target="deprecated-sympify-string-fallback",
)
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 :func:`~.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 does not
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.
"""
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
from .symbol import Symbol
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
|
f560bca773a904be9374799958c0caf636821bed7a7f8b99576569b5db951fdf | from sympy.utilities.exceptions import sympy_deprecation_warning
sympy_deprecation_warning(
"""
sympy.core.trace is deprecated. Use sympy.physics.quantum.trace
instead.
""",
deprecated_since_version="1.10",
active_deprecations_target="sympy-core-trace-deprecated",
)
from sympy.physics.quantum.trace import Tr # noqa:F401
|
3588e8021256cbf27fe083c4e6c659fc2d4d251c39a4b750a8a342f5001310de | """
Adaptive numerical evaluation of SymPy expressions, using mpmath
for mathematical functions.
"""
from typing import Tuple as tTuple, Optional, Union as tUnion, Callable, List, Dict as tDict, Type, TYPE_CHECKING, \
Any, overload
import math
import mpmath.libmp as libmp
from mpmath import (
make_mpc, make_mpf, mp, mpc, mpf, nsum, quadts, quadosc, workprec)
from mpmath import inf as mpmath_inf
from mpmath.libmp import (from_int, from_man_exp, from_rational, fhalf,
fnan, finf, fninf, fnone, fone, fzero, mpf_abs, mpf_add,
mpf_atan, mpf_atan2, mpf_cmp, mpf_cos, mpf_e, mpf_exp, mpf_log, mpf_lt,
mpf_mul, mpf_neg, mpf_pi, mpf_pow, mpf_pow_int, mpf_shift, mpf_sin,
mpf_sqrt, normalize, round_nearest, to_int, to_str)
from mpmath.libmp import bitcount as mpmath_bitcount
from mpmath.libmp.backend import MPZ
from mpmath.libmp.libmpc import _infs_nan
from mpmath.libmp.libmpf import dps_to_prec, prec_to_dps
from mpmath.libmp.gammazeta import mpf_bernoulli
from .sympify import sympify
from .singleton import S
from sympy.external.gmpy import SYMPY_INTS
from sympy.utilities.iterables import is_sequence
from sympy.utilities.lambdify import lambdify
from sympy.utilities.misc import as_int
if TYPE_CHECKING:
from sympy.core.expr import Expr
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.symbol import Symbol
from sympy.integrals.integrals import Integral
from sympy.concrete.summations import Sum
from sympy.concrete.products import Product
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.complexes import Abs, re, im
from sympy.functions.elementary.integers import ceiling, floor
from sympy.functions.elementary.trigonometric import atan
from sympy.functions.combinatorial.numbers import bernoulli
from .numbers import Float, Rational, Integer, AlgebraicNumber
LG10 = math.log(10, 2)
rnd = round_nearest
def bitcount(n):
"""Return smallest integer, b, such that |n|/2**b < 1.
"""
return mpmath_bitcount(abs(int(n)))
# Used in a few places as placeholder values to denote exponents and
# precision levels, e.g. of exact numbers. Must be careful to avoid
# passing these to mpmath functions or returning them in final results.
INF = float(mpmath_inf)
MINUS_INF = float(-mpmath_inf)
# ~= 100 digits. Real men set this to INF.
DEFAULT_MAXPREC = 333
class PrecisionExhausted(ArithmeticError):
pass
#----------------------------------------------------------------------------#
# #
# Helper functions for arithmetic and complex parts #
# #
#----------------------------------------------------------------------------#
"""
An mpf value tuple is a tuple of integers (sign, man, exp, bc)
representing a floating-point number: [1, -1][sign]*man*2**exp where
sign is 0 or 1 and bc should correspond to the number of bits used to
represent the mantissa (man) in binary notation, e.g.
"""
MPF_TUP = tTuple[int, int, int, int] # mpf value tuple
"""
Explanation
===========
>>> from sympy.core.evalf import bitcount
>>> sign, man, exp, bc = 0, 5, 1, 3
>>> n = [1, -1][sign]*man*2**exp
>>> n, bitcount(man)
(10, 3)
A temporary result is a tuple (re, im, re_acc, im_acc) where
re and im are nonzero mpf value tuples representing approximate
numbers, or None to denote exact zeros.
re_acc, im_acc are integers denoting log2(e) where e is the estimated
relative accuracy of the respective complex part, but may be anything
if the corresponding complex part is None.
"""
TMP_RES = Any # temporary result, should be some variant of
# tUnion[tTuple[Optional[MPF_TUP], Optional[MPF_TUP],
# Optional[int], Optional[int]],
# 'ComplexInfinity']
# but mypy reports error because it doesn't know as we know
# 1. re and re_acc are either both None or both MPF_TUP
# 2. sometimes the result can't be zoo
# type of the "options" parameter in internal evalf functions
OPT_DICT = tDict[str, Any]
def fastlog(x: Optional[MPF_TUP]) -> tUnion[int, Any]:
"""Fast approximation of log2(x) for an mpf value tuple x.
Explanation
===========
Calculated as exponent + width of mantissa. This is an
approximation for two reasons: 1) it gives the ceil(log2(abs(x)))
value and 2) it is too high by 1 in the case that x is an exact
power of 2. Although this is easy to remedy by testing to see if
the odd mpf mantissa is 1 (indicating that one was dealing with
an exact power of 2) that would decrease the speed and is not
necessary as this is only being used as an approximation for the
number of bits in x. The correct return value could be written as
"x[2] + (x[3] if x[1] != 1 else 0)".
Since mpf tuples always have an odd mantissa, no check is done
to see if the mantissa is a multiple of 2 (in which case the
result would be too large by 1).
Examples
========
>>> from sympy import log
>>> from sympy.core.evalf import fastlog, bitcount
>>> s, m, e = 0, 5, 1
>>> bc = bitcount(m)
>>> n = [1, -1][s]*m*2**e
>>> n, (log(n)/log(2)).evalf(2), fastlog((s, m, e, bc))
(10, 3.3, 4)
"""
if not x or x == fzero:
return MINUS_INF
return x[2] + x[3]
def pure_complex(v: 'Expr', or_real=False) -> Optional[tTuple['Expr', 'Expr']]:
"""Return a and b if v matches a + I*b where b is not zero and
a and b are Numbers, else None. If `or_real` is True then 0 will
be returned for `b` if `v` is a real number.
Examples
========
>>> from sympy.core.evalf import pure_complex
>>> from sympy import sqrt, I, S
>>> a, b, surd = S(2), S(3), sqrt(2)
>>> pure_complex(a)
>>> pure_complex(a, or_real=True)
(2, 0)
>>> pure_complex(surd)
>>> pure_complex(a + b*I)
(2, 3)
>>> pure_complex(I)
(0, 1)
"""
h, t = v.as_coeff_Add()
if t:
c, i = t.as_coeff_Mul()
if i is S.ImaginaryUnit:
return h, c
elif or_real:
return h, t
return None
# I don't know what this is, see function scaled_zero below
SCALED_ZERO_TUP = tTuple[List[int], int, int, int]
@overload
def scaled_zero(mag: SCALED_ZERO_TUP, sign=1) -> MPF_TUP:
...
@overload
def scaled_zero(mag: int, sign=1) -> tTuple[SCALED_ZERO_TUP, int]:
...
def scaled_zero(mag: tUnion[SCALED_ZERO_TUP, int], sign=1) -> \
tUnion[MPF_TUP, tTuple[SCALED_ZERO_TUP, int]]:
"""Return an mpf representing a power of two with magnitude ``mag``
and -1 for precision. Or, if ``mag`` is a scaled_zero tuple, then just
remove the sign from within the list that it was initially wrapped
in.
Examples
========
>>> from sympy.core.evalf import scaled_zero
>>> from sympy import Float
>>> z, p = scaled_zero(100)
>>> z, p
(([0], 1, 100, 1), -1)
>>> ok = scaled_zero(z)
>>> ok
(0, 1, 100, 1)
>>> Float(ok)
1.26765060022823e+30
>>> Float(ok, p)
0.e+30
>>> ok, p = scaled_zero(100, -1)
>>> Float(scaled_zero(ok), p)
-0.e+30
"""
if isinstance(mag, tuple) and len(mag) == 4 and iszero(mag, scaled=True):
return (mag[0][0],) + mag[1:]
elif isinstance(mag, SYMPY_INTS):
if sign not in [-1, 1]:
raise ValueError('sign must be +/-1')
rv, p = mpf_shift(fone, mag), -1
s = 0 if sign == 1 else 1
rv = ([s],) + rv[1:]
return rv, p
else:
raise ValueError('scaled zero expects int or scaled_zero tuple.')
def iszero(mpf: tUnion[MPF_TUP, SCALED_ZERO_TUP, None], scaled=False) -> Optional[bool]:
if not scaled:
return not mpf or not mpf[1] and not mpf[-1]
return mpf and isinstance(mpf[0], list) and mpf[1] == mpf[-1] == 1
def complex_accuracy(result: TMP_RES) -> tUnion[int, Any]:
"""
Returns relative accuracy of a complex number with given accuracies
for the real and imaginary parts. The relative accuracy is defined
in the complex norm sense as ||z|+|error|| / |z| where error
is equal to (real absolute error) + (imag absolute error)*i.
The full expression for the (logarithmic) error can be approximated
easily by using the max norm to approximate the complex norm.
In the worst case (re and im equal), this is wrong by a factor
sqrt(2), or by log2(sqrt(2)) = 0.5 bit.
"""
if result is S.ComplexInfinity:
return INF
re, im, re_acc, im_acc = result
if not im:
if not re:
return INF
return re_acc
if not re:
return im_acc
re_size = fastlog(re)
im_size = fastlog(im)
absolute_error = max(re_size - re_acc, im_size - im_acc)
relative_error = absolute_error - max(re_size, im_size)
return -relative_error
def get_abs(expr: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
result = evalf(expr, prec + 2, options)
if result is S.ComplexInfinity:
return finf, None, prec, None
re, im, re_acc, im_acc = result
if not re:
re, re_acc, im, im_acc = im, im_acc, re, re_acc
if im:
if expr.is_number:
abs_expr, _, acc, _ = evalf(abs(N(expr, prec + 2)),
prec + 2, options)
return abs_expr, None, acc, None
else:
if 'subs' in options:
return libmp.mpc_abs((re, im), prec), None, re_acc, None
return abs(expr), None, prec, None
elif re:
return mpf_abs(re), None, re_acc, None
else:
return None, None, None, None
def get_complex_part(expr: 'Expr', no: int, prec: int, options: OPT_DICT) -> TMP_RES:
"""no = 0 for real part, no = 1 for imaginary part"""
workprec = prec
i = 0
while 1:
res = evalf(expr, workprec, options)
if res is S.ComplexInfinity:
return fnan, None, prec, None
value, accuracy = res[no::2]
# XXX is the last one correct? Consider re((1+I)**2).n()
if (not value) or accuracy >= prec or -value[2] > prec:
return value, None, accuracy, None
workprec += max(30, 2**i)
i += 1
def evalf_abs(expr: 'Abs', prec: int, options: OPT_DICT) -> TMP_RES:
return get_abs(expr.args[0], prec, options)
def evalf_re(expr: 're', prec: int, options: OPT_DICT) -> TMP_RES:
return get_complex_part(expr.args[0], 0, prec, options)
def evalf_im(expr: 'im', prec: int, options: OPT_DICT) -> TMP_RES:
return get_complex_part(expr.args[0], 1, prec, options)
def finalize_complex(re: MPF_TUP, im: MPF_TUP, prec: int) -> TMP_RES:
if re == fzero and im == fzero:
raise ValueError("got complex zero with unknown accuracy")
elif re == fzero:
return None, im, None, prec
elif im == fzero:
return re, None, prec, None
size_re = fastlog(re)
size_im = fastlog(im)
if size_re > size_im:
re_acc = prec
im_acc = prec + min(-(size_re - size_im), 0)
else:
im_acc = prec
re_acc = prec + min(-(size_im - size_re), 0)
return re, im, re_acc, im_acc
def chop_parts(value: TMP_RES, prec: int) -> TMP_RES:
"""
Chop off tiny real or complex parts.
"""
if value is S.ComplexInfinity:
return value
re, im, re_acc, im_acc = value
# Method 1: chop based on absolute value
if re and re not in _infs_nan and (fastlog(re) < -prec + 4):
re, re_acc = None, None
if im and im not in _infs_nan and (fastlog(im) < -prec + 4):
im, im_acc = None, None
# Method 2: chop if inaccurate and relatively small
if re and im:
delta = fastlog(re) - fastlog(im)
if re_acc < 2 and (delta - re_acc <= -prec + 4):
re, re_acc = None, None
if im_acc < 2 and (delta - im_acc >= prec - 4):
im, im_acc = None, None
return re, im, re_acc, im_acc
def check_target(expr: 'Expr', result: TMP_RES, prec: int):
a = complex_accuracy(result)
if a < prec:
raise PrecisionExhausted("Failed to distinguish the expression: \n\n%s\n\n"
"from zero. Try simplifying the input, using chop=True, or providing "
"a higher maxn for evalf" % (expr))
def get_integer_part(expr: 'Expr', no: int, options: OPT_DICT, return_ints=False) -> \
tUnion[TMP_RES, tTuple[int, int]]:
"""
With no = 1, computes ceiling(expr)
With no = -1, computes floor(expr)
Note: this function either gives the exact result or signals failure.
"""
from sympy.functions.elementary.complexes import re, im
# The expression is likely less than 2^30 or so
assumed_size = 30
result = evalf(expr, assumed_size, options)
if result is S.ComplexInfinity:
raise ValueError("Cannot get integer part of Complex Infinity")
ire, iim, ire_acc, iim_acc = result
# We now know the size, so we can calculate how much extra precision
# (if any) is needed to get within the nearest integer
if ire and iim:
gap = max(fastlog(ire) - ire_acc, fastlog(iim) - iim_acc)
elif ire:
gap = fastlog(ire) - ire_acc
elif iim:
gap = fastlog(iim) - iim_acc
else:
# ... or maybe the expression was exactly zero
if return_ints:
return 0, 0
else:
return None, None, None, None
margin = 10
if gap >= -margin:
prec = margin + assumed_size + gap
ire, iim, ire_acc, iim_acc = evalf(
expr, prec, options)
else:
prec = assumed_size
# We can now easily find the nearest integer, but to find floor/ceil, we
# must also calculate whether the difference to the nearest integer is
# positive or negative (which may fail if very close).
def calc_part(re_im: 'Expr', nexpr: MPF_TUP):
from .add import Add
_, _, exponent, _ = nexpr
is_int = exponent == 0
nint = int(to_int(nexpr, rnd))
if is_int:
# make sure that we had enough precision to distinguish
# between nint and the re or im part (re_im) of expr that
# was passed to calc_part
ire, iim, ire_acc, iim_acc = evalf(
re_im - nint, 10, options) # don't need much precision
assert not iim
size = -fastlog(ire) + 2 # -ve b/c ire is less than 1
if size > prec:
ire, iim, ire_acc, iim_acc = evalf(
re_im, size, options)
assert not iim
nexpr = ire
nint = int(to_int(nexpr, rnd))
_, _, new_exp, _ = ire
is_int = new_exp == 0
if not is_int:
# if there are subs and they all contain integer re/im parts
# then we can (hopefully) safely substitute them into the
# expression
s = options.get('subs', False)
if s:
doit = True
# use strict=False with as_int because we take
# 2.0 == 2
for v in s.values():
try:
as_int(v, strict=False)
except ValueError:
try:
[as_int(i, strict=False) for i in v.as_real_imag()]
continue
except (ValueError, AttributeError):
doit = False
break
if doit:
re_im = re_im.subs(s)
re_im = Add(re_im, -nint, evaluate=False)
x, _, x_acc, _ = evalf(re_im, 10, options)
try:
check_target(re_im, (x, None, x_acc, None), 3)
except PrecisionExhausted:
if not re_im.equals(0):
raise PrecisionExhausted
x = fzero
nint += int(no*(mpf_cmp(x or fzero, fzero) == no))
nint = from_int(nint)
return nint, INF
re_, im_, re_acc, im_acc = None, None, None, None
if ire:
re_, re_acc = calc_part(re(expr, evaluate=False), ire)
if iim:
im_, im_acc = calc_part(im(expr, evaluate=False), iim)
if return_ints:
return int(to_int(re_ or fzero)), int(to_int(im_ or fzero))
return re_, im_, re_acc, im_acc
def evalf_ceiling(expr: 'ceiling', prec: int, options: OPT_DICT) -> TMP_RES:
return get_integer_part(expr.args[0], 1, options)
def evalf_floor(expr: 'floor', prec: int, options: OPT_DICT) -> TMP_RES:
return get_integer_part(expr.args[0], -1, options)
def evalf_float(expr: 'Float', prec: int, options: OPT_DICT) -> TMP_RES:
return expr._mpf_, None, prec, None
def evalf_rational(expr: 'Rational', prec: int, options: OPT_DICT) -> TMP_RES:
return from_rational(expr.p, expr.q, prec), None, prec, None
def evalf_integer(expr: 'Integer', prec: int, options: OPT_DICT) -> TMP_RES:
return from_int(expr.p, prec), None, prec, None
#----------------------------------------------------------------------------#
# #
# Arithmetic operations #
# #
#----------------------------------------------------------------------------#
def add_terms(terms: list, prec: int, target_prec: int) -> \
tTuple[tUnion[MPF_TUP, SCALED_ZERO_TUP, None], Optional[int]]:
"""
Helper for evalf_add. Adds a list of (mpfval, accuracy) terms.
Returns
=======
- None, None if there are no non-zero terms;
- terms[0] if there is only 1 term;
- scaled_zero if the sum of the terms produces a zero by cancellation
e.g. mpfs representing 1 and -1 would produce a scaled zero which need
special handling since they are not actually zero and they are purposely
malformed to ensure that they cannot be used in anything but accuracy
calculations;
- a tuple that is scaled to target_prec that corresponds to the
sum of the terms.
The returned mpf tuple will be normalized to target_prec; the input
prec is used to define the working precision.
XXX explain why this is needed and why one cannot just loop using mpf_add
"""
terms = [t for t in terms if not iszero(t[0])]
if not terms:
return None, None
elif len(terms) == 1:
return terms[0]
# see if any argument is NaN or oo and thus warrants a special return
special = []
from .numbers import Float
for t in terms:
arg = Float._new(t[0], 1)
if arg is S.NaN or arg.is_infinite:
special.append(arg)
if special:
from .add import Add
rv = evalf(Add(*special), prec + 4, {})
return rv[0], rv[2]
working_prec = 2*prec
sum_man, sum_exp = 0, 0
absolute_err: List[int] = []
for x, accuracy in terms:
sign, man, exp, bc = x
if sign:
man = -man
absolute_err.append(bc + exp - accuracy)
delta = exp - sum_exp
if exp >= sum_exp:
# x much larger than existing sum?
# first: quick test
if ((delta > working_prec) and
((not sum_man) or
delta - bitcount(abs(sum_man)) > working_prec)):
sum_man = man
sum_exp = exp
else:
sum_man += (man << delta)
else:
delta = -delta
# x much smaller than existing sum?
if delta - bc > working_prec:
if not sum_man:
sum_man, sum_exp = man, exp
else:
sum_man = (sum_man << delta) + man
sum_exp = exp
absolute_error = max(absolute_err)
if not sum_man:
return scaled_zero(absolute_error)
if sum_man < 0:
sum_sign = 1
sum_man = -sum_man
else:
sum_sign = 0
sum_bc = bitcount(sum_man)
sum_accuracy = sum_exp + sum_bc - absolute_error
r = normalize(sum_sign, sum_man, sum_exp, sum_bc, target_prec,
rnd), sum_accuracy
return r
def evalf_add(v: 'Add', prec: int, options: OPT_DICT) -> TMP_RES:
res = pure_complex(v)
if res:
h, c = res
re, _, re_acc, _ = evalf(h, prec, options)
im, _, im_acc, _ = evalf(c, prec, options)
return re, im, re_acc, im_acc
oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC)
i = 0
target_prec = prec
while 1:
options['maxprec'] = min(oldmaxprec, 2*prec)
terms = [evalf(arg, prec + 10, options) for arg in v.args]
n = terms.count(S.ComplexInfinity)
if n >= 2:
return fnan, None, prec, None
re, re_acc = add_terms(
[a[0::2] for a in terms if isinstance(a, tuple) and a[0]], prec, target_prec)
im, im_acc = add_terms(
[a[1::2] for a in terms if isinstance(a, tuple) and a[1]], prec, target_prec)
if n == 1:
if re in (finf, fninf, fnan) or im in (finf, fninf, fnan):
return fnan, None, prec, None
return S.ComplexInfinity
acc = complex_accuracy((re, im, re_acc, im_acc))
if acc >= target_prec:
if options.get('verbose'):
print("ADD: wanted", target_prec, "accurate bits, got", re_acc, im_acc)
break
else:
if (prec - target_prec) > options['maxprec']:
break
prec = prec + max(10 + 2**i, target_prec - acc)
i += 1
if options.get('verbose'):
print("ADD: restarting with prec", prec)
options['maxprec'] = oldmaxprec
if iszero(re, scaled=True):
re = scaled_zero(re)
if iszero(im, scaled=True):
im = scaled_zero(im)
return re, im, re_acc, im_acc
def evalf_mul(v: 'Mul', prec: int, options: OPT_DICT) -> TMP_RES:
res = pure_complex(v)
if res:
# the only pure complex that is a mul is h*I
_, h = res
im, _, im_acc, _ = evalf(h, prec, options)
return None, im, None, im_acc
args = list(v.args)
# see if any argument is NaN or oo and thus warrants a special return
has_zero = False
special = []
from .numbers import Float
for arg in args:
result = evalf(arg, prec, options)
if result is S.ComplexInfinity:
special.append(result)
continue
if result[0] is None:
if result[1] is None:
has_zero = True
continue
num = Float._new(result[0], 1)
if num is S.NaN:
return fnan, None, prec, None
if num.is_infinite:
special.append(num)
if special:
if has_zero:
return fnan, None, prec, None
from .mul import Mul
return evalf(Mul(*special), prec + 4, {})
if has_zero:
return None, None, None, None
# With guard digits, multiplication in the real case does not destroy
# accuracy. This is also true in the complex case when considering the
# total accuracy; however accuracy for the real or imaginary parts
# separately may be lower.
acc = prec
# XXX: big overestimate
working_prec = prec + len(args) + 5
# Empty product is 1
start = man, exp, bc = MPZ(1), 0, 1
# First, we multiply all pure real or pure imaginary numbers.
# direction tells us that the result should be multiplied by
# I**direction; all other numbers get put into complex_factors
# to be multiplied out after the first phase.
last = len(args)
direction = 0
args.append(S.One)
complex_factors = []
for i, arg in enumerate(args):
if i != last and pure_complex(arg):
args[-1] = (args[-1]*arg).expand()
continue
elif i == last and arg is S.One:
continue
re, im, re_acc, im_acc = evalf(arg, working_prec, options)
if re and im:
complex_factors.append((re, im, re_acc, im_acc))
continue
elif re:
(s, m, e, b), w_acc = re, re_acc
elif im:
(s, m, e, b), w_acc = im, im_acc
direction += 1
else:
return None, None, None, None
direction += 2*s
man *= m
exp += e
bc += b
while bc > 3*working_prec:
man >>= working_prec
exp += working_prec
bc -= working_prec
acc = min(acc, w_acc)
sign = (direction & 2) >> 1
if not complex_factors:
v = normalize(sign, man, exp, bitcount(man), prec, rnd)
# multiply by i
if direction & 1:
return None, v, None, acc
else:
return v, None, acc, None
else:
# initialize with the first term
if (man, exp, bc) != start:
# there was a real part; give it an imaginary part
re, im = (sign, man, exp, bitcount(man)), (0, MPZ(0), 0, 0)
i0 = 0
else:
# there is no real part to start (other than the starting 1)
wre, wim, wre_acc, wim_acc = complex_factors[0]
acc = min(acc,
complex_accuracy((wre, wim, wre_acc, wim_acc)))
re = wre
im = wim
i0 = 1
for wre, wim, wre_acc, wim_acc in complex_factors[i0:]:
# acc is the overall accuracy of the product; we aren't
# computing exact accuracies of the product.
acc = min(acc,
complex_accuracy((wre, wim, wre_acc, wim_acc)))
use_prec = working_prec
A = mpf_mul(re, wre, use_prec)
B = mpf_mul(mpf_neg(im), wim, use_prec)
C = mpf_mul(re, wim, use_prec)
D = mpf_mul(im, wre, use_prec)
re = mpf_add(A, B, use_prec)
im = mpf_add(C, D, use_prec)
if options.get('verbose'):
print("MUL: wanted", prec, "accurate bits, got", acc)
# multiply by I
if direction & 1:
re, im = mpf_neg(im), re
return re, im, acc, acc
def evalf_pow(v: 'Pow', prec: int, options) -> TMP_RES:
target_prec = prec
base, exp = v.args
# We handle x**n separately. This has two purposes: 1) it is much
# faster, because we avoid calling evalf on the exponent, and 2) it
# allows better handling of real/imaginary parts that are exactly zero
if exp.is_Integer:
p: int = exp.p # type: ignore
# Exact
if not p:
return fone, None, prec, None
# Exponentiation by p magnifies relative error by |p|, so the
# base must be evaluated with increased precision if p is large
prec += int(math.log(abs(p), 2))
result = evalf(base, prec + 5, options)
if result is S.ComplexInfinity:
if p < 0:
return None, None, None, None
return result
re, im, re_acc, im_acc = result
# Real to integer power
if re and not im:
return mpf_pow_int(re, p, target_prec), None, target_prec, None
# (x*I)**n = I**n * x**n
if im and not re:
z = mpf_pow_int(im, p, target_prec)
case = p % 4
if case == 0:
return z, None, target_prec, None
if case == 1:
return None, z, None, target_prec
if case == 2:
return mpf_neg(z), None, target_prec, None
if case == 3:
return None, mpf_neg(z), None, target_prec
# Zero raised to an integer power
if not re:
if p < 0:
return S.ComplexInfinity
return None, None, None, None
# General complex number to arbitrary integer power
re, im = libmp.mpc_pow_int((re, im), p, prec)
# Assumes full accuracy in input
return finalize_complex(re, im, target_prec)
result = evalf(base, prec + 5, options)
if result is S.ComplexInfinity:
if exp.is_Rational:
if exp < 0:
return None, None, None, None
return result
raise NotImplementedError
# Pure square root
if exp is S.Half:
xre, xim, _, _ = result
# General complex square root
if xim:
re, im = libmp.mpc_sqrt((xre or fzero, xim), prec)
return finalize_complex(re, im, prec)
if not xre:
return None, None, None, None
# Square root of a negative real number
if mpf_lt(xre, fzero):
return None, mpf_sqrt(mpf_neg(xre), prec), None, prec
# Positive square root
return mpf_sqrt(xre, prec), None, prec, None
# We first evaluate the exponent to find its magnitude
# This determines the working precision that must be used
prec += 10
result = evalf(exp, prec, options)
if result is S.ComplexInfinity:
return fnan, None, prec, None
yre, yim, _, _ = result
# Special cases: x**0
if not (yre or yim):
return fone, None, prec, None
ysize = fastlog(yre)
# Restart if too big
# XXX: prec + ysize might exceed maxprec
if ysize > 5:
prec += ysize
yre, yim, _, _ = evalf(exp, prec, options)
# Pure exponential function; no need to evalf the base
if base is S.Exp1:
if yim:
re, im = libmp.mpc_exp((yre or fzero, yim), prec)
return finalize_complex(re, im, target_prec)
return mpf_exp(yre, target_prec), None, target_prec, None
xre, xim, _, _ = evalf(base, prec + 5, options)
# 0**y
if not (xre or xim):
if yim:
return fnan, None, prec, None
if yre[0] == 1: # y < 0
return S.ComplexInfinity
return None, None, None, None
# (real ** complex) or (complex ** complex)
if yim:
re, im = libmp.mpc_pow(
(xre or fzero, xim or fzero), (yre or fzero, yim),
target_prec)
return finalize_complex(re, im, target_prec)
# complex ** real
if xim:
re, im = libmp.mpc_pow_mpf((xre or fzero, xim), yre, target_prec)
return finalize_complex(re, im, target_prec)
# negative ** real
elif mpf_lt(xre, fzero):
re, im = libmp.mpc_pow_mpf((xre, fzero), yre, target_prec)
return finalize_complex(re, im, target_prec)
# positive ** real
else:
return mpf_pow(xre, yre, target_prec), None, target_prec, None
#----------------------------------------------------------------------------#
# #
# Special functions #
# #
#----------------------------------------------------------------------------#
def evalf_exp(expr: 'exp', prec: int, options: OPT_DICT) -> TMP_RES:
from .power import Pow
return evalf_pow(Pow(S.Exp1, expr.exp, evaluate=False), prec, options)
def evalf_trig(v: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
"""
This function handles sin and cos of complex arguments.
TODO: should also handle tan of complex arguments.
"""
from sympy.functions.elementary.trigonometric import cos, sin
if isinstance(v, cos):
func = mpf_cos
elif isinstance(v, sin):
func = mpf_sin
else:
raise NotImplementedError
arg = v.args[0]
# 20 extra bits is possibly overkill. It does make the need
# to restart very unlikely
xprec = prec + 20
re, im, re_acc, im_acc = evalf(arg, xprec, options)
if im:
if 'subs' in options:
v = v.subs(options['subs'])
return evalf(v._eval_evalf(prec), prec, options)
if not re:
if isinstance(v, cos):
return fone, None, prec, None
elif isinstance(v, sin):
return None, None, None, None
else:
raise NotImplementedError
# For trigonometric functions, we are interested in the
# fixed-point (absolute) accuracy of the argument.
xsize = fastlog(re)
# Magnitude <= 1.0. OK to compute directly, because there is no
# danger of hitting the first root of cos (with sin, magnitude
# <= 2.0 would actually be ok)
if xsize < 1:
return func(re, prec, rnd), None, prec, None
# Very large
if xsize >= 10:
xprec = prec + xsize
re, im, re_acc, im_acc = evalf(arg, xprec, options)
# Need to repeat in case the argument is very close to a
# multiple of pi (or pi/2), hitting close to a root
while 1:
y = func(re, prec, rnd)
ysize = fastlog(y)
gap = -ysize
accuracy = (xprec - xsize) - gap
if accuracy < prec:
if options.get('verbose'):
print("SIN/COS", accuracy, "wanted", prec, "gap", gap)
print(to_str(y, 10))
if xprec > options.get('maxprec', DEFAULT_MAXPREC):
return y, None, accuracy, None
xprec += gap
re, im, re_acc, im_acc = evalf(arg, xprec, options)
continue
else:
return y, None, prec, None
def evalf_log(expr: 'log', prec: int, options: OPT_DICT) -> TMP_RES:
if len(expr.args)>1:
expr = expr.doit()
return evalf(expr, prec, options)
arg = expr.args[0]
workprec = prec + 10
result = evalf(arg, workprec, options)
if result is S.ComplexInfinity:
return result
xre, xim, xacc, _ = result
# evalf can return NoneTypes if chop=True
# issue 18516, 19623
if xre is xim is None:
# Dear reviewer, I do not know what -inf is;
# it looks to be (1, 0, -789, -3)
# but I'm not sure in general,
# so we just let mpmath figure
# it out by taking log of 0 directly.
# It would be better to return -inf instead.
xre = fzero
if xim:
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import log
# XXX: use get_abs etc instead
re = evalf_log(
log(Abs(arg, evaluate=False), evaluate=False), prec, options)
im = mpf_atan2(xim, xre or fzero, prec)
return re[0], im, re[2], prec
imaginary_term = (mpf_cmp(xre, fzero) < 0)
re = mpf_log(mpf_abs(xre), prec, rnd)
size = fastlog(re)
if prec - size > workprec and re != fzero:
from .add import Add
# We actually need to compute 1+x accurately, not x
add = Add(S.NegativeOne, arg, evaluate=False)
xre, xim, _, _ = evalf_add(add, prec, options)
prec2 = workprec - fastlog(xre)
# xre is now x - 1 so we add 1 back here to calculate x
re = mpf_log(mpf_abs(mpf_add(xre, fone, prec2)), prec, rnd)
re_acc = prec
if imaginary_term:
return re, mpf_pi(prec), re_acc, prec
else:
return re, None, re_acc, None
def evalf_atan(v: 'atan', prec: int, options: OPT_DICT) -> TMP_RES:
arg = v.args[0]
xre, xim, reacc, imacc = evalf(arg, prec + 5, options)
if xre is xim is None:
return (None,)*4
if xim:
raise NotImplementedError
return mpf_atan(xre, prec, rnd), None, prec, None
def evalf_subs(prec: int, subs: dict) -> dict:
""" Change all Float entries in `subs` to have precision prec. """
newsubs = {}
for a, b in subs.items():
b = S(b)
if b.is_Float:
b = b._eval_evalf(prec)
newsubs[a] = b
return newsubs
def evalf_piecewise(expr: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
from .numbers import Float, Integer
if 'subs' in options:
expr = expr.subs(evalf_subs(prec, options['subs']))
newopts = options.copy()
del newopts['subs']
if hasattr(expr, 'func'):
return evalf(expr, prec, newopts)
if isinstance(expr, float):
return evalf(Float(expr), prec, newopts)
if isinstance(expr, int):
return evalf(Integer(expr), prec, newopts)
# We still have undefined symbols
raise NotImplementedError
def evalf_bernoulli(expr: 'bernoulli', prec: int, options: OPT_DICT) -> TMP_RES:
arg = expr.args[0]
if not arg.is_Integer:
raise ValueError("Bernoulli number index must be an integer")
n = int(arg)
b = mpf_bernoulli(n, prec, rnd)
if b == fzero:
return None, None, None, None
return b, None, prec, None
def evalf_alg_num(a: 'AlgebraicNumber', prec: int, options: OPT_DICT) -> TMP_RES:
return evalf(a.to_root(), prec, options)
#----------------------------------------------------------------------------#
# #
# High-level operations #
# #
#----------------------------------------------------------------------------#
def as_mpmath(x: Any, prec: int, options: OPT_DICT) -> tUnion[mpc, mpf]:
from .numbers import Infinity, NegativeInfinity, Zero
x = sympify(x)
if isinstance(x, Zero) or x == 0:
return mpf(0)
if isinstance(x, Infinity):
return mpf('inf')
if isinstance(x, NegativeInfinity):
return mpf('-inf')
# XXX
result = evalf(x, prec, options)
return quad_to_mpmath(result)
def do_integral(expr: 'Integral', prec: int, options: OPT_DICT) -> TMP_RES:
func = expr.args[0]
x, xlow, xhigh = expr.args[1]
if xlow == xhigh:
xlow = xhigh = 0
elif x not in func.free_symbols:
# only the difference in limits matters in this case
# so if there is a symbol in common that will cancel
# out when taking the difference, then use that
# difference
if xhigh.free_symbols & xlow.free_symbols:
diff = xhigh - xlow
if diff.is_number:
xlow, xhigh = 0, diff
oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC)
options['maxprec'] = min(oldmaxprec, 2*prec)
with workprec(prec + 5):
xlow = as_mpmath(xlow, prec + 15, options)
xhigh = as_mpmath(xhigh, prec + 15, options)
# Integration is like summation, and we can phone home from
# the integrand function to update accuracy summation style
# Note that this accuracy is inaccurate, since it fails
# to account for the variable quadrature weights,
# but it is better than nothing
from sympy.functions.elementary.trigonometric import cos, sin
from .symbol import Wild
have_part = [False, False]
max_real_term: tUnion[float, int] = MINUS_INF
max_imag_term: tUnion[float, int] = MINUS_INF
def f(t: 'Expr') -> tUnion[mpc, mpf]:
nonlocal max_real_term, max_imag_term
re, im, re_acc, im_acc = evalf(func, mp.prec, {'subs': {x: t}})
have_part[0] = re or have_part[0]
have_part[1] = im or have_part[1]
max_real_term = max(max_real_term, fastlog(re))
max_imag_term = max(max_imag_term, fastlog(im))
if im:
return mpc(re or fzero, im)
return mpf(re or fzero)
if options.get('quad') == 'osc':
A = Wild('A', exclude=[x])
B = Wild('B', exclude=[x])
D = Wild('D')
m = func.match(cos(A*x + B)*D)
if not m:
m = func.match(sin(A*x + B)*D)
if not m:
raise ValueError("An integrand of the form sin(A*x+B)*f(x) "
"or cos(A*x+B)*f(x) is required for oscillatory quadrature")
period = as_mpmath(2*S.Pi/m[A], prec + 15, options)
result = quadosc(f, [xlow, xhigh], period=period)
# XXX: quadosc does not do error detection yet
quadrature_error = MINUS_INF
else:
result, quadrature_err = quadts(f, [xlow, xhigh], error=1)
quadrature_error = fastlog(quadrature_err._mpf_)
options['maxprec'] = oldmaxprec
if have_part[0]:
re: Optional[MPF_TUP] = result.real._mpf_
re_acc: Optional[int]
if re == fzero:
re_s, re_acc = scaled_zero(int(-max(prec, max_real_term, quadrature_error)))
re = scaled_zero(re_s) # handled ok in evalf_integral
else:
re_acc = int(-max(max_real_term - fastlog(re) - prec, quadrature_error))
else:
re, re_acc = None, None
if have_part[1]:
im: Optional[MPF_TUP] = result.imag._mpf_
im_acc: Optional[int]
if im == fzero:
im_s, im_acc = scaled_zero(int(-max(prec, max_imag_term, quadrature_error)))
im = scaled_zero(im_s) # handled ok in evalf_integral
else:
im_acc = int(-max(max_imag_term - fastlog(im) - prec, quadrature_error))
else:
im, im_acc = None, None
result = re, im, re_acc, im_acc
return result
def evalf_integral(expr: 'Integral', prec: int, options: OPT_DICT) -> TMP_RES:
limits = expr.limits
if len(limits) != 1 or len(limits[0]) != 3:
raise NotImplementedError
workprec = prec
i = 0
maxprec = options.get('maxprec', INF)
while 1:
result = do_integral(expr, workprec, options)
accuracy = complex_accuracy(result)
if accuracy >= prec: # achieved desired precision
break
if workprec >= maxprec: # can't increase accuracy any more
break
if accuracy == -1:
# maybe the answer really is zero and maybe we just haven't increased
# the precision enough. So increase by doubling to not take too long
# to get to maxprec.
workprec *= 2
else:
workprec += max(prec, 2**i)
workprec = min(workprec, maxprec)
i += 1
return result
def check_convergence(numer: 'Expr', denom: 'Expr', n: 'Symbol') -> tTuple[int, Any, Any]:
"""
Returns
=======
(h, g, p) where
-- h is:
> 0 for convergence of rate 1/factorial(n)**h
< 0 for divergence of rate factorial(n)**(-h)
= 0 for geometric or polynomial convergence or divergence
-- abs(g) is:
> 1 for geometric convergence of rate 1/h**n
< 1 for geometric divergence of rate h**n
= 1 for polynomial convergence or divergence
(g < 0 indicates an alternating series)
-- p is:
> 1 for polynomial convergence of rate 1/n**h
<= 1 for polynomial divergence of rate n**(-h)
"""
from sympy.polys.polytools import Poly
npol = Poly(numer, n)
dpol = Poly(denom, n)
p = npol.degree()
q = dpol.degree()
rate = q - p
if rate:
return rate, None, None
constant = dpol.LC() / npol.LC()
if abs(constant) != 1:
return rate, constant, None
if npol.degree() == dpol.degree() == 0:
return rate, constant, 0
pc = npol.all_coeffs()[1]
qc = dpol.all_coeffs()[1]
return rate, constant, (qc - pc)/dpol.LC()
def hypsum(expr: 'Expr', n: 'Symbol', start: int, prec: int) -> mpf:
"""
Sum a rapidly convergent infinite hypergeometric series with
given general term, e.g. e = hypsum(1/factorial(n), n). The
quotient between successive terms must be a quotient of integer
polynomials.
"""
from .numbers import Float
from sympy.simplify.simplify import hypersimp
if prec == float('inf'):
raise NotImplementedError('does not support inf prec')
if start:
expr = expr.subs(n, n + start)
hs = hypersimp(expr, n)
if hs is None:
raise NotImplementedError("a hypergeometric series is required")
num, den = hs.as_numer_denom()
func1 = lambdify(n, num)
func2 = lambdify(n, den)
h, g, p = check_convergence(num, den, n)
if h < 0:
raise ValueError("Sum diverges like (n!)^%i" % (-h))
term = expr.subs(n, 0)
if not term.is_Rational:
raise NotImplementedError("Non rational term functionality is not implemented.")
# Direct summation if geometric or faster
if h > 0 or (h == 0 and abs(g) > 1):
term = (MPZ(term.p) << prec) // term.q
s = term
k = 1
while abs(term) > 5:
term *= MPZ(func1(k - 1))
term //= MPZ(func2(k - 1))
s += term
k += 1
return from_man_exp(s, -prec)
else:
alt = g < 0
if abs(g) < 1:
raise ValueError("Sum diverges like (%i)^n" % abs(1/g))
if p < 1 or (p == 1 and not alt):
raise ValueError("Sum diverges like n^%i" % (-p))
# We have polynomial convergence: use Richardson extrapolation
vold = None
ndig = prec_to_dps(prec)
while True:
# Need to use at least quad precision because a lot of cancellation
# might occur in the extrapolation process; we check the answer to
# make sure that the desired precision has been reached, too.
prec2 = 4*prec
term0 = (MPZ(term.p) << prec2) // term.q
def summand(k, _term=[term0]):
if k:
k = int(k)
_term[0] *= MPZ(func1(k - 1))
_term[0] //= MPZ(func2(k - 1))
return make_mpf(from_man_exp(_term[0], -prec2))
with workprec(prec):
v = nsum(summand, [0, mpmath_inf], method='richardson')
vf = Float(v, ndig)
if vold is not None and vold == vf:
break
prec += prec # double precision each time
vold = vf
return v._mpf_
def evalf_prod(expr: 'Product', prec: int, options: OPT_DICT) -> TMP_RES:
if all((l[1] - l[2]).is_Integer for l in expr.limits):
result = evalf(expr.doit(), prec=prec, options=options)
else:
from sympy.concrete.summations import Sum
result = evalf(expr.rewrite(Sum), prec=prec, options=options)
return result
def evalf_sum(expr: 'Sum', prec: int, options: OPT_DICT) -> TMP_RES:
from .numbers import Float
if 'subs' in options:
expr = expr.subs(options['subs'])
func = expr.function
limits = expr.limits
if len(limits) != 1 or len(limits[0]) != 3:
raise NotImplementedError
if func.is_zero:
return None, None, prec, None
prec2 = prec + 10
try:
n, a, b = limits[0]
if b is not S.Infinity or a is S.NegativeInfinity or a != int(a):
raise NotImplementedError
# Use fast hypergeometric summation if possible
v = hypsum(func, n, int(a), prec2)
delta = prec - fastlog(v)
if fastlog(v) < -10:
v = hypsum(func, n, int(a), delta)
return v, None, min(prec, delta), None
except NotImplementedError:
# Euler-Maclaurin summation for general series
eps = Float(2.0)**(-prec)
for i in range(1, 5):
m = n = 2**i * prec
s, err = expr.euler_maclaurin(m=m, n=n, eps=eps,
eval_integral=False)
err = err.evalf()
if err is S.NaN:
raise NotImplementedError
if err <= eps:
break
err = fastlog(evalf(abs(err), 20, options)[0])
re, im, re_acc, im_acc = evalf(s, prec2, options)
if re_acc is None:
re_acc = -err
if im_acc is None:
im_acc = -err
return re, im, re_acc, im_acc
#----------------------------------------------------------------------------#
# #
# Symbolic interface #
# #
#----------------------------------------------------------------------------#
def evalf_symbol(x: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
val = options['subs'][x]
if isinstance(val, mpf):
if not val:
return None, None, None, None
return val._mpf_, None, prec, None
else:
if '_cache' not in options:
options['_cache'] = {}
cache = options['_cache']
cached, cached_prec = cache.get(x, (None, MINUS_INF))
if cached_prec >= prec:
return cached
v = evalf(sympify(val), prec, options)
cache[x] = (v, prec)
return v
evalf_table: tDict[Type['Expr'], Callable[['Expr', int, OPT_DICT], TMP_RES]] = {}
def _create_evalf_table():
global evalf_table
from sympy.functions.combinatorial.numbers import bernoulli
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
from .add import Add
from .mul import Mul
from .numbers import Exp1, Float, Half, ImaginaryUnit, Integer, NaN, NegativeOne, One, Pi, Rational, \
Zero, ComplexInfinity, AlgebraicNumber
from .power import Pow
from .symbol import Dummy, Symbol
from sympy.functions.elementary.complexes import Abs, im, re
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.integers import ceiling, floor
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import atan, cos, sin
from sympy.integrals.integrals import Integral
evalf_table = {
Symbol: evalf_symbol,
Dummy: evalf_symbol,
Float: evalf_float,
Rational: evalf_rational,
Integer: evalf_integer,
Zero: lambda x, prec, options: (None, None, prec, None),
One: lambda x, prec, options: (fone, None, prec, None),
Half: lambda x, prec, options: (fhalf, None, prec, None),
Pi: lambda x, prec, options: (mpf_pi(prec), None, prec, None),
Exp1: lambda x, prec, options: (mpf_e(prec), None, prec, None),
ImaginaryUnit: lambda x, prec, options: (None, fone, None, prec),
NegativeOne: lambda x, prec, options: (fnone, None, prec, None),
ComplexInfinity: lambda x, prec, options: S.ComplexInfinity,
NaN: lambda x, prec, options: (fnan, None, prec, None),
exp: evalf_exp,
cos: evalf_trig,
sin: evalf_trig,
Add: evalf_add,
Mul: evalf_mul,
Pow: evalf_pow,
log: evalf_log,
atan: evalf_atan,
Abs: evalf_abs,
re: evalf_re,
im: evalf_im,
floor: evalf_floor,
ceiling: evalf_ceiling,
Integral: evalf_integral,
Sum: evalf_sum,
Product: evalf_prod,
Piecewise: evalf_piecewise,
bernoulli: evalf_bernoulli,
AlgebraicNumber: evalf_alg_num,
}
def evalf(x: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
"""
Evaluate the ``Expr`` instance, ``x``
to a binary precision of ``prec``. This
function is supposed to be used internally.
Parameters
==========
x : Expr
The formula to evaluate to a float.
prec : int
The binary precision that the output should have.
options : dict
A dictionary with the same entries as
``EvalfMixin.evalf`` and in addition,
``maxprec`` which is the maximum working precision.
Returns
=======
An optional tuple, ``(re, im, re_acc, im_acc)``
which are the real, imaginary, real accuracy
and imaginary accuracy respectively. ``re`` is
an mpf value tuple and so is ``im``. ``re_acc``
and ``im_acc`` are ints.
NB: all these return values can be ``None``.
If all values are ``None``, then that represents 0.
Note that 0 is also represented as ``fzero = (0, 0, 0, 0)``.
"""
from sympy.functions.elementary.complexes import re as re_, im as im_
try:
rf = evalf_table[type(x)]
r = rf(x, prec, options)
except KeyError:
# Fall back to ordinary evalf if possible
if 'subs' in options:
x = x.subs(evalf_subs(prec, options['subs']))
xe = x._eval_evalf(prec)
if xe is None:
raise NotImplementedError
as_real_imag = getattr(xe, "as_real_imag", None)
if as_real_imag is None:
raise NotImplementedError # e.g. FiniteSet(-1.0, 1.0).evalf()
re, im = as_real_imag()
if re.has(re_) or im.has(im_):
raise NotImplementedError
if re == 0:
re = None
reprec = None
elif re.is_number:
re = re._to_mpmath(prec, allow_ints=False)._mpf_
reprec = prec
else:
raise NotImplementedError
if im == 0:
im = None
imprec = None
elif im.is_number:
im = im._to_mpmath(prec, allow_ints=False)._mpf_
imprec = prec
else:
raise NotImplementedError
r = re, im, reprec, imprec
if options.get("verbose"):
print("### input", x)
print("### output", to_str(r[0] or fzero, 50) if isinstance(r, tuple) else r)
print("### raw", r) # r[0], r[2]
print()
chop = options.get('chop', False)
if chop:
if chop is True:
chop_prec = prec
else:
# convert (approximately) from given tolerance;
# the formula here will will make 1e-i rounds to 0 for
# i in the range +/-27 while 2e-i will not be chopped
chop_prec = int(round(-3.321*math.log10(chop) + 2.5))
if chop_prec == 3:
chop_prec -= 1
r = chop_parts(r, chop_prec)
if options.get("strict"):
check_target(x, r, prec)
return r
def quad_to_mpmath(q):
"""Turn the quad returned by ``evalf`` into an ``mpf`` or ``mpc``. """
if q is S.ComplexInfinity:
raise NotImplementedError
re, im, _, _ = q
if im:
if not re:
re = fzero
return make_mpc((re, im))
elif re:
return make_mpf(re)
else:
return make_mpf(fzero)
class EvalfMixin:
"""Mixin class adding evalf capability."""
__slots__ = () # type: tTuple[str, ...]
def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False):
"""
Evaluate the given formula to an accuracy of *n* digits.
Parameters
==========
subs : dict, optional
Substitute numerical values for symbols, e.g.
``subs={x:3, y:1+pi}``. The substitutions must be given as a
dictionary.
maxn : int, optional
Allow a maximum temporary working precision of maxn digits.
chop : bool or number, optional
Specifies how to replace tiny real or imaginary parts in
subresults by exact zeros.
When ``True`` the chop value defaults to standard precision.
Otherwise the chop value is used to determine the
magnitude of "small" for purposes of chopping.
>>> from sympy import N
>>> x = 1e-4
>>> N(x, chop=True)
0.000100000000000000
>>> N(x, chop=1e-5)
0.000100000000000000
>>> N(x, chop=1e-4)
0
strict : bool, optional
Raise ``PrecisionExhausted`` if any subresult fails to
evaluate to full accuracy, given the available maxprec.
quad : str, optional
Choose algorithm for numerical quadrature. By default,
tanh-sinh quadrature is used. For oscillatory
integrals on an infinite interval, try ``quad='osc'``.
verbose : bool, optional
Print debug information.
Notes
=====
When Floats are naively substituted into an expression,
precision errors may adversely affect the result. For example,
adding 1e16 (a Float) to 1 will truncate to 1e16; if 1e16 is
then subtracted, the result will be 0.
That is exactly what happens in the following:
>>> from sympy.abc import x, y, z
>>> values = {x: 1e16, y: 1, z: 1e16}
>>> (x + y - z).subs(values)
0
Using the subs argument for evalf is the accurate way to
evaluate such an expression:
>>> (x + y - z).evalf(subs=values)
1.00000000000000
"""
from .numbers import Float, Number
n = n if n is not None else 15
if subs and is_sequence(subs):
raise TypeError('subs must be given as a dictionary')
# for sake of sage that doesn't like evalf(1)
if n == 1 and isinstance(self, Number):
from .expr import _mag
rv = self.evalf(2, subs, maxn, chop, strict, quad, verbose)
m = _mag(rv)
rv = rv.round(1 - m)
return rv
if not evalf_table:
_create_evalf_table()
prec = dps_to_prec(n)
options = {'maxprec': max(prec, int(maxn*LG10)), 'chop': chop,
'strict': strict, 'verbose': verbose}
if subs is not None:
options['subs'] = subs
if quad is not None:
options['quad'] = quad
try:
result = evalf(self, prec + 4, options)
except NotImplementedError:
# Fall back to the ordinary evalf
if hasattr(self, 'subs') and subs is not None: # issue 20291
v = self.subs(subs)._eval_evalf(prec)
else:
v = self._eval_evalf(prec)
if v is None:
return self
elif not v.is_number:
return v
try:
# If the result is numerical, normalize it
result = evalf(v, prec, options)
except NotImplementedError:
# Probably contains symbols or unknown functions
return v
if result is S.ComplexInfinity:
return result
re, im, re_acc, im_acc = result
if re is S.NaN or im is S.NaN:
return S.NaN
if re:
p = max(min(prec, re_acc), 1)
re = Float._new(re, p)
else:
re = S.Zero
if im:
p = max(min(prec, im_acc), 1)
im = Float._new(im, p)
return re + im*S.ImaginaryUnit
else:
return re
n = evalf
def _evalf(self, prec):
"""Helper for evalf. Does the same thing but takes binary precision"""
r = self._eval_evalf(prec)
if r is None:
r = self
return r
def _eval_evalf(self, prec):
return
def _to_mpmath(self, prec, allow_ints=True):
# mpmath functions accept ints as input
errmsg = "cannot convert to mpmath number"
if allow_ints and self.is_Integer:
return self.p
if hasattr(self, '_as_mpf_val'):
return make_mpf(self._as_mpf_val(prec))
try:
result = evalf(self, prec, {})
return quad_to_mpmath(result)
except NotImplementedError:
v = self._eval_evalf(prec)
if v is None:
raise ValueError(errmsg)
if v.is_Float:
return make_mpf(v._mpf_)
# Number + Number*I is also fine
re, im = v.as_real_imag()
if allow_ints and re.is_Integer:
re = from_int(re.p)
elif re.is_Float:
re = re._mpf_
else:
raise ValueError(errmsg)
if allow_ints and im.is_Integer:
im = from_int(im.p)
elif im.is_Float:
im = im._mpf_
else:
raise ValueError(errmsg)
return make_mpc((re, im))
def N(x, n=15, **options):
r"""
Calls x.evalf(n, \*\*options).
Explanations
============
Both .n() and N() are equivalent to .evalf(); use the one that you like better.
See also the docstring of .evalf() for information on the options.
Examples
========
>>> from sympy import Sum, oo, N
>>> from sympy.abc import k
>>> Sum(1/k**k, (k, 1, oo))
Sum(k**(-k), (k, 1, oo))
>>> N(_, 4)
1.291
"""
# by using rational=True, any evaluation of a string
# will be done using exact values for the Floats
return sympify(x, rational=True).evalf(n, **options)
def _evalf_with_bounded_error(x: 'Expr', eps: 'Expr' = None, m: int = 0,
options: OPT_DICT = None) -> TMP_RES:
"""
Evaluate *x* to within a bounded absolute error.
Parameters
==========
x : Expr
The quantity to be evaluated.
eps : Expr, None, optional (default=None)
Positive real upper bound on the acceptable error.
m : int, optional (default=0)
If *eps* is None, then use 2**(-m) as the upper bound on the error.
options: OPT_DICT
As in the ``evalf`` function.
Returns
=======
A tuple ``(re, im, re_acc, im_acc)``, as returned by ``evalf``.
See Also
========
evalf
"""
eps = sympify(eps)
if eps is not None:
if not (eps.is_Rational or eps.is_Float) or not eps > 0:
raise ValueError("eps must be positive")
r, _, _, _ = evalf(1/eps, 1, {})
m = fastlog(r)
c, d, _, _ = evalf(x, 1, {})
# Note: If x = a + b*I, then |a| <= 2|c| and |b| <= 2|d|, with equality
# only in the zero case.
# If a is non-zero, then |c| = 2**nc for some integer nc, and c has
# bitcount 1. Therefore 2**fastlog(c) = 2**(nc+1) = 2|c| is an upper bound
# on |a|. Likewise for b and d.
nr, ni = fastlog(c), fastlog(d)
n = max(nr, ni) + 1
# If x is 0, then n is MINUS_INF, and p will be 1. Otherwise,
# n - 1 bits get us past the integer parts of a and b, and +1 accounts for
# the factor of <= sqrt(2) that is |x|/max(|a|, |b|).
p = max(1, m + n + 1)
options = options or {}
return evalf(x, p, options)
|
5ff6e5cff665d453d8b23680bb563a1750a4bf8130ff91556029a6a781deb938 | """Module for SymPy containers
(SymPy objects that store other SymPy objects)
The containers implemented in this module are subclassed to Basic.
They are supposed to work seamlessly within the SymPy framework.
"""
from collections import OrderedDict
from collections.abc import MutableSet
from typing import Any, Callable
from .basic import Basic
from .sorting import default_sort_key, ordered
from .sympify import _sympify, sympify, _sympy_converter, SympifyError
from sympy.core.kind import Kind
from sympy.utilities.iterables import iterable
from sympy.utilities.misc import as_int
class Tuple(Basic):
"""
Wrapper around the builtin tuple object.
Explanation
===========
The Tuple is a subclass of Basic, so that it works well in the
SymPy framework. The wrapped tuple is available as self.args, but
you can also access elements or slices with [:] syntax.
Parameters
==========
sympify : bool
If ``False``, ``sympify`` is not called on ``args``. This
can be used for speedups for very large tuples where the
elements are known to already be SymPy objects.
Examples
========
>>> from sympy import Tuple, symbols
>>> a, b, c, d = symbols('a b c d')
>>> Tuple(a, b, c)[1:]
(b, c)
>>> Tuple(a, b, c).subs(a, d)
(d, b, c)
"""
def __new__(cls, *args, **kwargs):
if kwargs.get('sympify', True):
args = (sympify(arg) for arg in args)
obj = Basic.__new__(cls, *args)
return obj
def __getitem__(self, i):
if isinstance(i, slice):
indices = i.indices(len(self))
return Tuple(*(self.args[j] for j in range(*indices)))
return self.args[i]
def __len__(self):
return len(self.args)
def __contains__(self, item):
return item in self.args
def __iter__(self):
return iter(self.args)
def __add__(self, other):
if isinstance(other, Tuple):
return Tuple(*(self.args + other.args))
elif isinstance(other, tuple):
return Tuple(*(self.args + other))
else:
return NotImplemented
def __radd__(self, other):
if isinstance(other, Tuple):
return Tuple(*(other.args + self.args))
elif isinstance(other, tuple):
return Tuple(*(other + self.args))
else:
return NotImplemented
def __mul__(self, other):
try:
n = as_int(other)
except ValueError:
raise TypeError("Can't multiply sequence by non-integer of type '%s'" % type(other))
return self.func(*(self.args*n))
__rmul__ = __mul__
def __eq__(self, other):
if isinstance(other, Basic):
return super().__eq__(other)
return self.args == other
def __ne__(self, other):
if isinstance(other, Basic):
return super().__ne__(other)
return self.args != other
def __hash__(self):
return hash(self.args)
def _to_mpmath(self, prec):
return tuple(a._to_mpmath(prec) for a in self.args)
def __lt__(self, other):
return _sympify(self.args < other.args)
def __le__(self, other):
return _sympify(self.args <= other.args)
# XXX: Basic defines count() as something different, so we can't
# redefine it here. Originally this lead to cse() test failure.
def tuple_count(self, value):
"""T.count(value) -> integer -- return number of occurrences of value"""
return self.args.count(value)
def index(self, value, start=None, stop=None):
"""Searches and returns the first index of the value."""
# XXX: One would expect:
#
# return self.args.index(value, start, stop)
#
# here. Any trouble with that? Yes:
#
# >>> (1,).index(1, None, None)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: slice indices must be integers or None or have an __index__ method
#
# See: http://bugs.python.org/issue13340
if start is None and stop is None:
return self.args.index(value)
elif stop is None:
return self.args.index(value, start)
else:
return self.args.index(value, start, stop)
@property
def kind(self):
"""
The kind of a Tuple instance.
The kind of a Tuple is always of :class:`TupleKind` but
parametrised by the number of elements and the kind of each element.
Examples
========
>>> from sympy import Tuple, Matrix
>>> Tuple(1, 2).kind
TupleKind(NumberKind, NumberKind)
>>> Tuple(Matrix([1, 2]), 1).kind
TupleKind(MatrixKind(NumberKind), NumberKind)
>>> Tuple(1, 2).kind.element_kind
(NumberKind, NumberKind)
See Also
========
sympy.matrices.common.MatrixKind
sympy.core.kind.NumberKind
"""
return TupleKind(*(i.kind for i in self.args))
_sympy_converter[tuple] = lambda tup: Tuple(*tup)
def tuple_wrapper(method):
"""
Decorator that converts any tuple in the function arguments into a Tuple.
Explanation
===========
The motivation for this is to provide simple user interfaces. The user can
call a function with regular tuples in the argument, and the wrapper will
convert them to Tuples before handing them to the function.
Explanation
===========
>>> from sympy.core.containers import tuple_wrapper
>>> def f(*args):
... return args
>>> g = tuple_wrapper(f)
The decorated function g sees only the Tuple argument:
>>> g(0, (1, 2), 3)
(0, (1, 2), 3)
"""
def wrap_tuples(*args, **kw_args):
newargs = []
for arg in args:
if isinstance(arg, tuple):
newargs.append(Tuple(*arg))
else:
newargs.append(arg)
return method(*newargs, **kw_args)
return wrap_tuples
class Dict(Basic):
"""
Wrapper around the builtin dict object
Explanation
===========
The Dict is a subclass of Basic, so that it works well in the
SymPy framework. Because it is immutable, it may be included
in sets, but its values must all be given at instantiation and
cannot be changed afterwards. Otherwise it behaves identically
to the Python dict.
Examples
========
>>> from sympy import Dict, Symbol
>>> D = Dict({1: 'one', 2: 'two'})
>>> for key in D:
... if key == 1:
... print('%s %s' % (key, D[key]))
1 one
The args are sympified so the 1 and 2 are Integers and the values
are Symbols. Queries automatically sympify args so the following work:
>>> 1 in D
True
>>> D.has(Symbol('one')) # searches keys and values
True
>>> 'one' in D # not in the keys
False
>>> D[1]
one
"""
def __new__(cls, *args):
if len(args) == 1 and isinstance(args[0], (dict, Dict)):
items = [Tuple(k, v) for k, v in args[0].items()]
elif iterable(args) and all(len(arg) == 2 for arg in args):
items = [Tuple(k, v) for k, v in args]
else:
raise TypeError('Pass Dict args as Dict((k1, v1), ...) or Dict({k1: v1, ...})')
elements = frozenset(items)
obj = Basic.__new__(cls, *ordered(items))
obj.elements = elements
obj._dict = dict(items) # In case Tuple decides it wants to sympify
return obj
def __getitem__(self, key):
"""x.__getitem__(y) <==> x[y]"""
try:
key = _sympify(key)
except SympifyError:
raise KeyError(key)
return self._dict[key]
def __setitem__(self, key, value):
raise NotImplementedError("SymPy Dicts are Immutable")
def items(self):
'''Returns a set-like object providing a view on dict's items.
'''
return self._dict.items()
def keys(self):
'''Returns the list of the dict's keys.'''
return self._dict.keys()
def values(self):
'''Returns the list of the dict's values.'''
return self._dict.values()
def __iter__(self):
'''x.__iter__() <==> iter(x)'''
return iter(self._dict)
def __len__(self):
'''x.__len__() <==> len(x)'''
return self._dict.__len__()
def get(self, key, default=None):
'''Returns the value for key if the key is in the dictionary.'''
try:
key = _sympify(key)
except SympifyError:
return default
return self._dict.get(key, default)
def __contains__(self, key):
'''D.__contains__(k) -> True if D has a key k, else False'''
try:
key = _sympify(key)
except SympifyError:
return False
return key in self._dict
def __lt__(self, other):
return _sympify(self.args < other.args)
@property
def _sorted_args(self):
return tuple(sorted(self.args, key=default_sort_key))
def __eq__(self, other):
if isinstance(other, dict):
return self == Dict(other)
return super().__eq__(other)
__hash__ : Callable[[Basic], Any] = Basic.__hash__
# this handles dict, defaultdict, OrderedDict
_sympy_converter[dict] = lambda d: Dict(*d.items())
class OrderedSet(MutableSet):
def __init__(self, iterable=None):
if iterable:
self.map = OrderedDict((item, None) for item in iterable)
else:
self.map = OrderedDict()
def __len__(self):
return len(self.map)
def __contains__(self, key):
return key in self.map
def add(self, key):
self.map[key] = None
def discard(self, key):
self.map.pop(key)
def pop(self, last=True):
return self.map.popitem(last=last)[0]
def __iter__(self):
yield from self.map.keys()
def __repr__(self):
if not self.map:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self.map.keys()))
def intersection(self, other):
result = []
for val in self:
if val in other:
result.append(val)
return self.__class__(result)
def difference(self, other):
result = []
for val in self:
if val not in other:
result.append(val)
return self.__class__(result)
def update(self, iterable):
for val in iterable:
self.add(val)
class TupleKind(Kind):
"""
TupleKind is a subclass of Kind, which is used to define Kind of ``Tuple``.
Parameters of TupleKind will be kinds of all the arguments in Tuples, for
example
Parameters
==========
args : tuple(element_kind)
element_kind is kind of element.
args is tuple of kinds of element
Examples
========
>>> from sympy import Tuple
>>> Tuple(1, 2).kind
TupleKind(NumberKind, NumberKind)
>>> Tuple(1, 2).kind.element_kind
(NumberKind, NumberKind)
See Also
========
sympy.core.kind.NumberKind
MatrixKind
sympy.sets.sets.SetKind
"""
def __new__(cls, *args):
obj = super().__new__(cls, *args)
obj.element_kind = args
return obj
def __repr__(self):
return "TupleKind{}".format(self.element_kind)
|
6ff2292353edbf521aa0cb72b3f9f1ecb5006304f29d7988b971be16652477a2 | from typing import Tuple as tTuple
from collections import defaultdict
from functools import cmp_to_key, reduce
from itertools import product
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
from .traversal import bottom_up
from sympy.utilities.iterables import sift
# 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.
.. deprecated:: 1.7
Using arguments that aren't subclasses of :class:`~.Expr` in core
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
deprecated. See :ref:`non-expr-args-deprecated` for details.
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__ = ()
args: tTuple[Expr]
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 could_extract_minus_sign(self):
if self == (-self):
return False # e.g. zoo*x == -zoo*x
c = self.args[0]
return c.is_Number and c.is_extended_negative
def __neg__(self):
c, args = self.as_coeff_mul()
if args[0] is not S.ComplexInfinity:
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.accumulationbounds 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 a is not 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:
newb = Add(*[_keep_coeff(a, bi) for bi in b.args])
rv = [newb], [], 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 in (S.Infinity, 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:
if self.is_imaginary:
a = self.as_real_imag()[1]
if a.is_Rational:
from .power import integer_nthroot
n, d = abs(a/2).as_numer_denom()
n, t = integer_nthroot(n, 2)
if t:
d, t = integer_nthroot(d, 2)
if t:
from sympy.functions.elementary.complexes import sign
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 .numbers import Float
im_part, imag_unit = self.as_coeff_Mul()
if imag_unit is not S.ImaginaryUnit:
# 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:
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.functions.elementary.complexes import Abs, 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)
from .function import expand_mul
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.simplify.radsimp 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 .function import AppliedUndef
from .symbol import Symbol, symbols, Dummy
if not isinstance(s, (AppliedUndef, 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)
from .numbers import Integer
args = self.args
m = len(args)
if isinstance(n, (int, Integer)):
# https://en.wikipedia.org/wiki/General_Leibniz_rule#More_than_two_factors
terms = []
from sympy.ntheory.multinomial import multinomial_coefficients_iterator
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)
from sympy.concrete.summations import Sum
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.miscellaneous import Max
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=None, old=False):
expr = sympify(expr)
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 not repl_dict 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=None):
"""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.
"""
if repl_dict is None:
repl_dict = dict()
else:
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 = {}
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?
mult = Mul(*terms) if len(terms) > 1 else terms[0]
return wildcard.matches(mult)
@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_)
rv = lhs/rhs
srv = signsimp(rv)
return srv if srv.is_Number else rv
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):
from sympy.ntheory.factor_ import trailing
is_rational = self._eval_is_rational()
if is_rational is False:
return False
numerators = []
denominators = []
unknown = False
for a in self.args:
hit = False
if a.is_integer:
if abs(a) is not S.One:
numerators.append(a)
elif a.is_Rational:
n, d = a.as_numer_denom()
if abs(n) is not S.One:
numerators.append(n)
if d is not S.One:
denominators.append(d)
elif a.is_Pow:
b, e = a.as_base_exp()
if not b.is_integer or not e.is_integer:
hit = unknown = True
if e.is_negative:
denominators.append(2 if a is S.Half else
Pow(a, S.NegativeOne))
elif not hit:
# int b and pos int e: a = b**e is integer
assert not e.is_positive
# for rational self and e equal to zero: a = b**e is 1
assert not e.is_zero
return # sign of e unknown -> self.is_integer unknown
else:
return
if not denominators and not unknown:
return True
allodd = lambda x: all(i.is_odd for i in x)
alleven = lambda x: all(i.is_even for i in x)
anyeven = lambda x: any(i.is_even for i in x)
from .relational import is_gt
if not numerators and denominators and all(is_gt(_, S.One)
for _ in denominators):
return False
elif unknown:
return
elif allodd(numerators) and anyeven(denominators):
return False
elif anyeven(numerators) and denominators == [2]:
return True
elif alleven(numerators) and allodd(denominators
) and (Mul(*denominators, evaluate=False) - 1
).is_positive:
return False
if len(denominators) == 1:
d = denominators[0]
if d.is_Integer and d.is_even:
# if minimal power of 2 in num vs den is not
# negative then we have an integer
if (Add(*[i.as_base_exp()[1] for i in
numerators if i.is_even]) - trailing(d.p)
).is_nonnegative:
return True
if len(numerators) == 1:
n = numerators[0]
if n.is_Integer and n.is_even:
# if minimal power of 2 in den vs num is positive
# then we have have a non-integer
if (Add(*[i.as_base_exp()[1] for i in
denominators if i.is_even]) - trailing(n.p)
).is_positive:
return False
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:
if self.is_zero:
return False
from sympy.simplify.radsimp import fraction
n, d = fraction(self)
if d.is_Integer and d.is_even:
from sympy.ntheory.factor_ import trailing
# if minimal power of 2 in num vs den is
# positive then we have an even number
if (Add(*[i.as_base_exp()[1] for i in
Mul.make_args(n) if i.is_even]) - trailing(d.p)
).is_positive:
return False
return
r, acc = True, 1
for t in self.args:
if abs(t) is S.One:
continue
assert t.is_integer
if t.is_even:
return False
if r is False:
pass
elif acc != 1 and (acc + t).is_odd:
r = False
elif t.is_even is None:
r = None
acc = t
return r
return is_integer # !integer -> !odd
def _eval_is_even(self):
is_integer = self.is_integer
if is_integer:
return fuzzy_not(self.is_odd)
from sympy.simplify.radsimp import fraction
n, d = fraction(self)
if n.is_Integer and n.is_even:
# if minimal power of 2 in den vs num is not
# negative then this is not an integer and
# can't be even
from sympy.ntheory.factor_ import trailing
if (Add(*[i.as_base_exp()[1] for i in
Mul.make_args(d) if i.is_even]) - trailing(n.p)
).is_nonnegative:
return False
return is_integer
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.functions.elementary.exponential 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 .function import PoleError
from sympy.functions.elementary.integers import ceiling
from sympy.series.order import Order
def coeff_exp(term, x):
lt = term.as_coeff_exponent(x)
if lt[0].has(x):
try:
lt = term.leadterm(x)
except ValueError:
return term, S.Zero
return lt
ords = []
try:
for t in self.args:
coeff, exp = t.leadterm(x, logx=logx)
if not coeff.has(x):
ords.append((t, exp))
else:
raise ValueError
n0 = sum(t[1] for t in ords if t[1].is_number)
facs = []
for t, m in ords:
n1 = ceiling(n - n0 + (m if m.is_number else 0))
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)
except (ValueError, NotImplementedError, TypeError, AttributeError, PoleError):
n0 = sympify(sum(t[1] for t in ords if t[1].is_number))
if n0.is_nonnegative:
n0 = S.Zero
facs = [t.nseries(x, n=ceiling(n-n0), logx=logx, cdir=cdir) for t in self.args]
from sympy.simplify.powsimp import powsimp
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).is_negative:
res += Mul(*coeffs)*(x**power)
def max_degree(e, x):
if e is x:
return S.One
if e.is_Atom:
return S.Zero
if e.is_Add:
return max(max_degree(a, x) for a in e.args)
if e.is_Mul:
return Add(*[max_degree(a, x) for a in e.args])
if e.is_Pow:
return max_degree(e.base, x)*e.exp
return S.Zero
if self.is_polynomial(x):
from sympy.polys.polyerrors import PolynomialError
from sympy.polys.polytools import degree
try:
if max_degree(self, x) >= n or degree(self, x) != degree(res, x):
res += Order(x**n, x)
except PolynomialError:
pass
else:
return res
if res != self:
res += Order(x**n, x)
return res
def _eval_as_leading_term(self, x, logx=None, cdir=0):
return self.func(*[t.as_leading_term(x, logx=logx, 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 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 a in 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.is_Integer 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):
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, _unevaluated_Add
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.